Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ examples:
# libopus install above, so require it only when opus is present.
- |
MISSING=""
for t in activate_demo scan_by_app_pair_demo scan_by_device_pair_demo \
for t in activate_demo ble_only_activate scan_by_app_pair_demo scan_by_device_pair_demo \
unbind_demo dp_management_demo ota_demo ota_confirm_demo \
ai/role-management/role_management_demo \
udp_chat_demo udp_edu_camera_demo \
Expand Down Expand Up @@ -399,6 +399,7 @@ test:memory-leak:
VG=modules/iot-client/test/run_valgrind_check.sh
chmod +x "$VG"
# Leak-check the pure (no-subprocess) binaries, grouped by module:
# common : json_lexical_test, bounded_string_test
# pal : pal_freertos_time_*_test, pal_posix_time_test
# rtc-tcp-client : tai_unit_tests, tai_log_level_zero_tests,
# tai_log_module_zero_tests, tai_integration_tests,
Expand All @@ -410,7 +411,7 @@ test:memory-leak:
# test, so there is nothing to leak-check for it here. The mock-driven iot
# tests are covered by the `test` job; under valgrind their Python
# handshakes would time out.
for t in pal_freertos_time_16_1000_test pal_freertos_time_32_1000_test pal_freertos_time_32_100_test pal_freertos_time_32_128_test pal_freertos_time_32_2000_test pal_freertos_time_64_1000_test pal_posix_time_test biz_ai_role_test tai_unit_tests tai_log_level_zero_tests tai_log_module_zero_tests tai_integration_tests workflow_variables_demo_test iot_cipher_test iot_ai_ctrl_test tuya_ble_test; do
for t in json_lexical_test bounded_string_test pal_freertos_time_16_1000_test pal_freertos_time_32_1000_test pal_freertos_time_32_100_test pal_freertos_time_32_128_test pal_freertos_time_32_2000_test pal_freertos_time_64_1000_test pal_posix_time_test biz_ai_role_test tai_unit_tests tai_log_level_zero_tests tai_log_module_zero_tests tai_integration_tests workflow_variables_demo_test iot_cipher_test iot_ai_ctrl_test tuya_ble_test; do
echo "==================== valgrind: ${t} ===================="
"$VG" "./${CMAKE_BUILD_DIR}/${t}" 2>&1 | tee "valgrind-${t}.log"
rc=${PIPESTATUS[0]}
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,21 @@ New entries use explicit platform-qualified PR/MR links; see [CONTRIBUTING.md](C

### Added

- tuya-ble — Hey Tuya voice-mode control (cmd `0x0094`): a `voice_control` callback receives the App's start/stop/error/heartbeat opcodes with their `[Version][Type][Opcode]` header in any paired session, and `tuya_ble_send_voice_control()` sends the device's own `REQUEST_START`/`REQUEST_STOP`; inbound frames get a frame-level ACK only (the App answers a request with a fresh `0x0094` frame), device-originated opcodes inbound and short payloads are dropped with a log (PR pending).
- The device-info response Flag2 advertises the Hey Tuya capability bit (bit 5, PV >= 4.8) only when a `voice_control` callback is registered.
- tuya-ble — AI audio uplink via `tuya_ble_send_voice_frame()` (`0x0091`, `ACK_SN=0`) and authenticated BT device-info replies (`0x0060`) (PR pending).
- Opus audio format codes distinguish 32 kbps (`1`) and 16 kbps (`2`).
- tuya-ble — device-info protocol version 4.8 with the pair-request extension tail parsed per the App implementation: AppFlagLength/AppFlag (App DP-channel claim recorded in `app_dp_transport` and the activation JSON), optional mesh `node_id`/`ble_net_key`, malformed tails rejected before the activation callback; the 3-byte device capability is configurable via `TUYA_BLE_DEV_CAP_*` bits (bit 19 transparent DP, bit 21 mesh control), and the advertisement V2 flags and response Flag2 now derive from one source (PR pending).
- v4.4 pair frames (82/98 bytes) are still accepted; a capability of zero keeps the legacy capability byte, so unchanged products stay byte-identical apart from the version field.
- Transparent-DP routing (`0x801E`/`0x801F`) itself is not implemented: advertise bit 19 only after a port routes DP accordingly.
- iot-client — apply authenticated local DP batches atomically through `iot_client_apply_local_dps()`, with persistence callbacks and explicit cloud reporting (PR pending).
- docs — manual contribution workflow for GitLab 17.8.7: contribution guidelines, PR/MR templates and a GitLab-to-GitHub sync runbook ([GitLab MR !5](https://registry.code.tuya-inc.top/TuyaAI/agentic-kit/-/merge_requests/5)).
- ci — GitLab pipeline mirrors the GitHub checks (sanitizers, POSIX examples) and adds the valgrind leak, CodeScan and gitleaks secret-detection gates ([GitLab MR !5](https://registry.code.tuya-inc.top/TuyaAI/agentic-kit/-/merge_requests/5)).
- External contributions must pass the CodeScan gate; `BLOCK_ON_VULN=false` switches it to report-only.
- tuya-ble — BLE single-mode provisioning: activation delivery (cmd `0x001B`) in the unbound session, in-session bind via `tuya_ble_prov_bind()`, and Unbind/Device reset (`0x0005`/`0x0006`) with an `unbound` callback (PR pending).
- The SDK parses the protocol-defined JSON payload (`devID`, `secKey`, `localKey`, `schema`) and validates the 16-byte credential pair; a malformed payload is failure-ACKed without a callback. The application callback receives the parsed, borrowed fields to persist and may veto the install. The ACK rides the unbound session and the bound form flips only after the ACK is queued.
- Examples — `ble_only_activate` runs BLE-only (single-mode) provisioning end to end: the App-assisted cloud activation, the `0x001B` activation delivery over an in-process BLE loopback, and bound DP control (PR pending).
- tuya-ble — activated-device local DP control over bound KEY_14/KEY_15 sessions: DP write/query callbacks, explicit TLV reports with optional UTC timestamps, and bound advertising (PR pending).
- Examples — `workflow_variables_demo` sends sequential `chat`, `generate-img`, and `decide` Events with plain-text, saved-image, and boolean-result JSON responses (PR pending).
- biz-client — typed AI role management, language/timbre queries, POSIX and ESP-IDF examples, and bilingual API documentation (#47).
- iot-client — `iot_get_binding_status()` queries `tuya.device.info.sync` with saved credentials, without an IoT client (#44).
Expand All @@ -24,6 +36,7 @@ New entries use explicit platform-qualified PR/MR links; see [CONTRIBUTING.md](C

### Changed

- tuya-ble — single-mode binding now requires a schema: the pair request never carries one, so the firmware must pre-provision `tuya_ble_prov_cfg_ext_t.schema`; pair binding and activation delivery (`0x001B`) refuse to install credentials unless the delivered JSON or the firmware supplies a usable schema, ACKing failure and leaving the device unbound (PR pending).
- ci — GitLab pipelines run the same job set at three moments: merge-request events (a detached pipeline on the MR head, satisfying the project's "Pipelines must succeed" gate), `master`/`main` pushes (the merge itself, plus `pages`), and manual pipelines (`IS_RELEASE=true` releases skip the history gitleaks scan); bare branch and tag pushes no longer run GitLab CI — open the MR (GitHub's push CI still covers `feature/**` directly) (PR pending).
- **BREAKING** pal — mandatory `wal_clock_time` provides Unix UTC milliseconds; `time_ms` keeps its monotonic timing contract (#45).
- Custom PALs must supply `wal_clock_time` and rebuild SDK/PAL consumers.
Expand All @@ -35,6 +48,7 @@ New entries use explicit platform-qualified PR/MR links; see [CONTRIBUTING.md](C
### Fixed

- rtc-tcp-client — `tai_frame_verify` rejects a declared frame length smaller than the signature before deriving the payload size, preventing a size_t underflow that swept out of bounds inside the HMAC computation (CodeScan high; not reachable through the SDK's own receive path, where the frame-length guard rejects the frame first) (PR pending).
- tuya-ble — persist verified credentials from extended single-mode pair requests, retain bound advertising on reconnect, and omit WiFi status frames for BLE-only devices (PR pending).
- pal — FreeRTOS `time_ms` preserves tick wraps and converts non-integral tick periods correctly (#45).
- biz-client — role request timestamps and the clock gate read PAL UTC instead of libc time, so ports without a synchronized libc clock work (#45).

Expand Down
19 changes: 19 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ add_library(agentic_kit_common STATIC
"${COMMON_DIR}/log.c"
"${COMMON_DIR}/tls.c"
"${COMMON_DIR}/rng.c"
"${COMMON_DIR}/json_lexical.c"
)
target_include_directories(agentic_kit_common PUBLIC
"${COMMON_DIR}"
Expand Down Expand Up @@ -272,6 +273,7 @@ set(TUYA_BLE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/modules/tuya-ble")

add_library(tuya_ble STATIC
"${TUYA_BLE_DIR}/src/tuya_ble_bigdata.c"
"${TUYA_BLE_DIR}/src/tuya_ble_dp.c"
"${TUYA_BLE_DIR}/src/tuya_ble_prov.c"
"${TUYA_BLE_DIR}/src/tuya_ble_trsmitr.c"
)
Expand All @@ -289,6 +291,21 @@ target_link_libraries(tuya_ble PUBLIC
# Tests
# -----------------------------------------------------------------------------
if(AGENTIC_KIT_BUILD_TESTS AND AGENTIC_KIT_ENABLE_PROJECT_TESTS)
add_executable(json_lexical_test
"${COMMON_DIR}/json_lexical.c" "${COMMON_DIR}/test/test_json_lexical.c")
target_include_directories(json_lexical_test PRIVATE "${COMMON_DIR}")
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(json_lexical_test PRIVATE -Wall -Wextra -Werror)
endif()
add_test(NAME json_lexical_test COMMAND json_lexical_test)

add_executable(bounded_string_test "${COMMON_DIR}/test/test_bounded_string.c")
target_include_directories(bounded_string_test PRIVATE "${COMMON_DIR}")
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(bounded_string_test PRIVATE -Wall -Wextra -Werror)
endif()
add_test(NAME bounded_string_test COMMAND bounded_string_test)

# Fake only the public ATOP boundary, so service parsing/ownership can be
# checked without network credentials or a subprocess. Register in ctest.
add_executable(biz_ai_role_test ${BIZ_CLIENT_SOURCES}
Expand Down Expand Up @@ -565,9 +582,11 @@ if(AGENTIC_KIT_BUILD_TESTS AND AGENTIC_KIT_ENABLE_PROJECT_TESTS)
# test_wire assert on "[ble] [TRSMITR]" warns.
add_executable(tuya_ble_test
"${TUYA_BLE_DIR}/src/tuya_ble_bigdata.c"
"${TUYA_BLE_DIR}/src/tuya_ble_dp.c"
"${TUYA_BLE_DIR}/src/tuya_ble_prov.c"
"${TUYA_BLE_DIR}/src/tuya_ble_trsmitr.c"
"${TUYA_BLE_TESTS_DIR}/test_wire.c"
"${TUYA_BLE_TESTS_DIR}/test_control.c"
"${TUYA_BLE_TESTS_DIR}/test_prov.c"
"${TUYA_BLE_TESTS_DIR}/tuya_ble_hal_host.c"
)
Expand Down
6 changes: 5 additions & 1 deletion CONTEXT-MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ and decisions.
and `modules/rtc-tcp-client/docs/adr/0001-receive-backpressure-pauses-the-connection.md`.
- **Tuya BLE → IoT Client**: BLE provisioning runs first and hands the device its WiFi
credentials (incl. the pairing token); once on WiFi, the IoT Client uses them to activate
against the cloud.
against the cloud. For an activated device the application supplies the saved
`local_key` and `secret_key` to BLE, then copies validated DP commands from the
BLE owner to the IoT owner. The public local-DP input reuses the IoT schema,
state and callbacks; explicit BLE reports return through the BLE owner.
BLE never publishes MQTT or calls IoT APIs from its receive callback.
- All contexts share the Platform Abstraction Layer (`pal/pal.h`) for sockets, memory,
mutex, threads, and time.
17 changes: 17 additions & 0 deletions common/bounded_string.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#ifndef AGENTIC_KIT_BOUNDED_STRING_H
#define AGENTIC_KIT_BOUNDED_STRING_H

#include <stdbool.h>
#include <stddef.h>

/* Require a nonempty string terminated within capacity bytes, including its
* NUL. Read at most capacity bytes, stopping at the first NUL. NULL, zero
* capacity, empty and unterminated strings are invalid. */
static inline bool bounded_string_nonempty(const char *text, size_t capacity)
{
if (!text || !capacity || !text[0]) return false;
for (size_t i = 1; i < capacity; ++i) if (!text[i]) return true;
return false;
}

#endif
134 changes: 134 additions & 0 deletions common/json_lexical.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
#include "json_lexical.h"

#include <string.h>

static bool unicode_escape(const char *data, size_t len, size_t *offset, unsigned *code)
{
unsigned value = 0;
if (len - *offset < 4) return false;
for (unsigned i = 0; i < 4; ++i) {
unsigned char c = (unsigned char)data[(*offset)++];
int digit = c >= '0' && c <= '9' ? c - '0' :
c >= 'a' && c <= 'f' ? c - 'a' + 10 :
c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
if (digit < 0) return false;
value = (value << 4) | (unsigned)digit;
}
*code = value;
return true;
}

/* The lead byte restricts the first continuation byte as well as the length:
* exclude overlong encodings, UTF-16 surrogates and scalars above U+10FFFF. */
static bool utf8_tail(const char *data, size_t len, size_t *offset, unsigned char lead)
{
unsigned extra;
unsigned char lo = 0x80, hi = 0xbf;
if (lead >= 0xc2 && lead <= 0xdf) extra = 1;
else if (lead >= 0xe0 && lead <= 0xef) {
extra = 2;
if (lead == 0xe0) lo = 0xa0;
if (lead == 0xed) hi = 0x9f;
} else if (lead >= 0xf0 && lead <= 0xf4) {
extra = 3;
if (lead == 0xf0) lo = 0x90;
if (lead == 0xf4) hi = 0x8f;
} else return false;
if (len - *offset < extra || (unsigned char)data[*offset] < lo ||
(unsigned char)data[*offset] > hi) return false;
++*offset;
while (--extra > 0) {
unsigned char c = (unsigned char)data[(*offset)++];
if (c < 0x80 || c > 0xbf) return false;
}
return true;
}

bool json_lexical_scan_string(const char *data, size_t len, size_t *offset)
{
if (!data || !offset || *offset >= len || data[*offset] != '"') return false;
size_t i = *offset + 1;
while (i < len) {
unsigned char c = (unsigned char)data[i++];
if (c == '"') { *offset = i; return true; }
if (c < 0x20) return false;
if (c == '\\') {
unsigned code, low;
if (i == len) return false;
c = (unsigned char)data[i++];
if (c == 'u') {
if (!unicode_escape(data, len, &i, &code) || !code ||
(code >= 0xdc00 && code <= 0xdfff)) return false;
if (code >= 0xd800 && code <= 0xdbff) {
if (len - i < 6 || data[i] != '\\' || data[i + 1] != 'u') return false;
i += 2;
if (!unicode_escape(data, len, &i, &low) || low < 0xdc00 || low > 0xdfff)
return false;
}
} else if (c != '"' && c != '\\' && c != '/' && c != 'b' &&
c != 'f' && c != 'n' && c != 'r' && c != 't') return false;
} else if (c >= 0x80 && !utf8_tail(data, len, &i, c)) return false;
}
return false;
}

static bool delimiter(char c)
{
return c == ',' || c == ']' || c == '}' || c == ' ' ||
c == '\t' || c == '\n' || c == '\r';
}

bool json_lexical_scan_number(const char *data, size_t len, size_t *offset)
{
if (!data || !offset || *offset >= len) return false;
size_t i = *offset;
if (data[i] == '-') ++i;
if (i == len) return false;
if (data[i] == '0') ++i;
else {
if (data[i] < '1' || data[i] > '9') return false;
do { ++i; } while (i < len && data[i] >= '0' && data[i] <= '9');
}
if (i < len && data[i] == '.') {
++i;
if (i == len || data[i] < '0' || data[i] > '9') return false;
do { ++i; } while (i < len && data[i] >= '0' && data[i] <= '9');
}
if (i < len && (data[i] == 'e' || data[i] == 'E')) {
++i;
if (i < len && (data[i] == '+' || data[i] == '-')) ++i;
if (i == len || data[i] < '0' || data[i] > '9') return false;
do { ++i; } while (i < len && data[i] >= '0' && data[i] <= '9');
}
if (i < len && !delimiter(data[i])) return false;
*offset = i;
return true;
}

bool json_lexical_validate(const char *data, size_t len)
{
if (!data || !len) return false;
size_t i = 0;
unsigned depth = 0;
while (i < len) {
unsigned char c = (unsigned char)data[i];
if (c == '"') { if (!json_lexical_scan_string(data, len, &i)) return false; }
else if (c == '-' || (c >= '0' && c <= '9')) {
if (!json_lexical_scan_number(data, len, &i)) return false;
} else if (c == '{' || c == '[') { if (++depth > JSON_LEXICAL_MAX_DEPTH) return false; ++i; }
else if (c == '}' || c == ']') { if (!depth) return false; --depth; ++i; }
else if (c == ':' || c == ',' || c == ' ' || c == '\t' || c == '\n' || c == '\r') ++i;
else {
size_t word_len;
const char *word;
if (c == 't') { word = "true"; word_len = 4; }
else if (c == 'f') { word = "false"; word_len = 5; }
else if (c == 'n') { word = "null"; word_len = 4; }
else return false;
if (len - i < word_len || memcmp(data + i, word, word_len)) return false;
i += word_len;
if (i < len && !delimiter(data[i])) return false;
}
}
return depth == 0;
}
22 changes: 22 additions & 0 deletions common/json_lexical.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* Internal, allocation-free lexical checks before cJSON normalization.
* This is not a JSON parser: callers still validate document structure with
* cJSON, and apply their own domain constraints. Strings must be UTF-8 and may
* not decode to NUL, because cJSON exposes NUL-terminated C strings. */
#ifndef AGENTIC_KIT_JSON_LEXICAL_H
#define AGENTIC_KIT_JSON_LEXICAL_H

#include <stdbool.h>
#include <stddef.h>

#define JSON_LEXICAL_MAX_DEPTH 32u

/* Scan one token at *offset without reading outside data[0..len). Advance the
* offset only on success; failure includes a missing or malformed token. */
bool json_lexical_scan_string(const char *data, size_t len, size_t *offset);
bool json_lexical_scan_number(const char *data, size_t len, size_t *offset);

/* Check all lexical forms and cap nesting before invoking cJSON's recursive
* parser. This accepts punctuation sequences that only cJSON can reject. */
bool json_lexical_validate(const char *data, size_t len);

#endif
12 changes: 0 additions & 12 deletions common/log.c
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,14 @@ static void default_output(log_level_t level, const char *fmt, va_list args)
char ts[16];
time_t t = time(NULL);
struct tm tm_buf;
#if defined(_WIN32)
localtime_s(&tm_buf, &t);
#else
localtime_r(&t, &tm_buf);
#endif
strftime(ts, sizeof ts, "%H:%M:%S", &tm_buf);

#if defined(_WIN32)
_lock_file(stderr);
#else
flockfile(stderr);
#endif
fprintf(stderr, "%s [%s] ", ts, lc);
vfprintf(stderr, fmt ? fmt : "", args);
fputc('\n', stderr);
#if defined(_WIN32)
_unlock_file(stderr);
#else
funlockfile(stderr);
#endif
}

void log_emit_valist(log_level_t level, const char *fmt, va_list args)
Expand Down
Loading
Loading