From 468377cb7a90219dbc90675f729bdd5b11ef4486 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:26:37 -0300 Subject: [PATCH 01/10] fix(asap): report health and echo JSON-RPC IDs --- Makefile | 2 +- src/asap/manifest.c | 19 +++++-- src/asap/manifest.h | 9 ++-- src/asap/manifest_build.c | 3 +- src/asap/manifest_build.h | 3 ++ src/gateway/http.c | 2 +- src/gateway/http_lws.h | 2 +- src/gateway/routes.c | 103 +++++++++++++++++------------------- tests/test_gateway_http.c | 37 +++++++++++-- tests/test_manifest_build.c | 19 +++---- 10 files changed, 121 insertions(+), 78 deletions(-) diff --git a/Makefile b/Makefile index 503cce1b..a9b3574a 100644 --- a/Makefile +++ b/Makefile @@ -330,7 +330,7 @@ src/gateway/static.o: src/gateway/static.c src/gateway/static.h src/gateway/ui_a $(JCS_O): src/crypto/jcs.c src/crypto/jcs.h vendor/cJSON/cJSON.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/crypto/jcs.c -$(MANIFEST_O): src/asap/manifest.c src/asap/manifest.h +$(MANIFEST_O): src/asap/manifest.c src/asap/manifest.h src/asap/manifest_build.h src/core/config.h src/core/version.h vendor/cJSON/cJSON.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/asap/manifest.c $(MANIFEST_PROFILES_O): src/asap/manifest_profiles.c src/asap/manifest_profiles.h src/core/config.h src/hardware/board_detect.h diff --git a/src/asap/manifest.c b/src/asap/manifest.c index 0d41fde0..a9f25740 100644 --- a/src/asap/manifest.c +++ b/src/asap/manifest.c @@ -6,9 +6,22 @@ #include "asap/manifest.h" -static const char *HEALTH_JSON = "{\"status\":\"ok\"}"; +#include "core/config.h" +#include "core/version.h" +#include "cJSON.h" -const char *manifest_health_json(void) +char *manifest_health_json(const config_t *cfg, double uptime_seconds) { - return HEALTH_JSON; + cJSON *health = cJSON_CreateObject(); + char *json = NULL; + + if (health && + cJSON_AddStringToObject(health, "status", "healthy") && + cJSON_AddStringToObject(health, "agent_id", config_asap_agent_urn(cfg)) && + cJSON_AddStringToObject(health, "version", SHELLCLAW_RELEASE_VERSION) && + cJSON_AddStringToObject(health, "asap_version", ASAP_DISCOVERY_VERSION) && + cJSON_AddNumberToObject(health, "uptime_seconds", uptime_seconds)) + json = cJSON_PrintUnformatted(health); + cJSON_Delete(health); + return json; } diff --git a/src/asap/manifest.h b/src/asap/manifest.h index 5677e418..f6d7d394 100644 --- a/src/asap/manifest.h +++ b/src/asap/manifest.h @@ -13,10 +13,13 @@ extern "C" { #endif /** - * Return ASAP health JSON string. - * Static string; do not free. + * Return the ASAP health response as JSON, or NULL on allocation failure. + * The caller frees the returned string. + * + * @param cfg Agent configuration, or NULL for defaults. + * @param uptime_seconds Seconds since the gateway started. */ -const char *manifest_health_json(void); +char *manifest_health_json(const config_t *cfg, double uptime_seconds); #ifdef __cplusplus } diff --git a/src/asap/manifest_build.c b/src/asap/manifest_build.c index efb7b730..ef042e1f 100644 --- a/src/asap/manifest_build.c +++ b/src/asap/manifest_build.c @@ -19,7 +19,6 @@ #define MAX_SKILL_NAMES 64 #define MAX_SKILL_DESC 512 #define MAX_ASAP_ENDPOINT 512 -#define MANIFEST_ASAP_VERSION "2.1.0" /* Upstream asap.crypto.models defaults (verified against asap-protocol 2.5.0): * the signed inner manifest must carry every field Manifest.model_dump() would * populate, since asap.crypto.signing.canonicalize re-derives these defaults. */ @@ -453,7 +452,7 @@ cJSON *manifest_build_tree(const config_t *cfg) cJSON_Delete(root); return NULL; } - item = cJSON_CreateString(MANIFEST_ASAP_VERSION); + item = cJSON_CreateString(ASAP_DISCOVERY_VERSION); if (!item) { cJSON_Delete(root); return NULL; diff --git a/src/asap/manifest_build.h b/src/asap/manifest_build.h index 96485f00..bdda7b65 100644 --- a/src/asap/manifest_build.h +++ b/src/asap/manifest_build.h @@ -7,6 +7,9 @@ #include "cJSON.h" +/** Protocol version advertised by the manifest and health endpoints. */ +#define ASAP_DISCOVERY_VERSION "2.1.0" + struct config; typedef struct config config_t; diff --git a/src/gateway/http.c b/src/gateway/http.c index 6b571ffb..1e193e6e 100644 --- a/src/gateway/http.c +++ b/src/gateway/http.c @@ -122,7 +122,7 @@ int http_start(const config_t *cfg, struct auth_ctx *auth_ctx, const char *confi ctx->cfg = cfg; ctx->auth = auth_ctx; ctx->config_path = config_path ? strdup(config_path) : NULL; - ctx->start_time = time(NULL); + (void)clock_gettime(CLOCK_MONOTONIC, &ctx->started_at); ctx->running = 1; memset(&info, 0, sizeof(info)); info.port = config_gateway_port(cfg); diff --git a/src/gateway/http_lws.h b/src/gateway/http_lws.h index 5f6f3e8f..6add68dd 100644 --- a/src/gateway/http_lws.h +++ b/src/gateway/http_lws.h @@ -37,7 +37,7 @@ typedef struct http_server_ctx { const config_t *cfg; auth_ctx_t *auth; char *config_path; - time_t start_time; + struct timespec started_at; struct lws_context *lws_ctx; pthread_t thread; volatile int running; diff --git a/src/gateway/routes.c b/src/gateway/routes.c index e53b9752..1a6563a9 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -100,10 +100,18 @@ void json_error(char *buf, size_t size, int *status, int code, const char *msg) } } +static double gateway_uptime_seconds(const http_server_ctx_t *ctx) +{ + struct timespec now; + if (!ctx || clock_gettime(CLOCK_MONOTONIC, &now) != 0) + return 0.0; + return (double)(now.tv_sec - ctx->started_at.tv_sec) + + (double)(now.tv_nsec - ctx->started_at.tv_nsec) / 1e9; +} + static void handle_health(http_server_ctx_t *ctx, char *buf, size_t size, int *status) { - time_t now = time(NULL); - long uptime = (long)(now - ctx->start_time); + long uptime = (long)gateway_uptime_seconds(ctx); cJSON *obj = cJSON_CreateObject(); if (!obj) { json_error(buf, size, status, 500, "Internal error"); return; } cJSON_AddItemToObject(obj, "status", cJSON_CreateString("ok")); @@ -688,34 +696,23 @@ static void handle_cron_toggle(const char *id, char *buf, size_t size, int *stat json_response(buf, size, status, "{\"ok\":true}"); } -/** Build a minimal JSON-RPC 2.0 error response into @p buf. */ -static void jsonrpc_error(char *buf, size_t size, int *status, - int http_code, int rpc_code, const char *msg) +static void write_asap_error(char *buf, size_t size, int *status, int http_code, cJSON *error) { - cJSON *obj; - cJSON *err; - char *s; - if (!buf || size == 0 || !status) return; + char *json = error ? cJSON_PrintUnformatted(error) : NULL; + cJSON_Delete(error); *status = http_code; - obj = cJSON_CreateObject(); - if (!obj) { snprintf(buf, size, "{\"error\":{\"code\":%d}}", rpc_code); return; } - cJSON_AddStringToObject(obj, "jsonrpc", "2.0"); - cJSON_AddNullToObject(obj, "id"); - err = cJSON_CreateObject(); - if (err) { - cJSON_AddNumberToObject(err, "code", (double)rpc_code); - cJSON_AddStringToObject(err, "message", msg ? msg : "error"); - cJSON_AddItemToObject(obj, "error", err); - } - s = cJSON_PrintUnformatted(obj); - cJSON_Delete(obj); - if (s) { - size_t len = strlen(s); - if (len >= size) len = size - 1; - memcpy(buf, s, len); - buf[len] = '\0'; - free(s); - } + if (json && strlen(json) < size) + memcpy(buf, json, strlen(json) + 1); + else + snprintf(buf, size, "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32603," + "\"message\":\"Cannot serialize response\"},\"id\":null}"); + free(json); +} + +static void jsonrpc_error(char *buf, size_t size, int *status, + int http_code, int rpc_code, const char *msg, cJSON *id) +{ + write_asap_error(buf, size, status, http_code, asap_jsonrpc_error(rpc_code, msg, id)); } static void handle_asap_log_get(char *buf, size_t size, int *status) @@ -787,7 +784,7 @@ static void asap_ctx_bind_bootstrap(asap_server_ctx_t *asap_ctx, const config_t * Takes ownership of @p resp_json. * @return 0 if copied, -1 if rejected as too large. */ -static int write_asap_jsonrpc(char *buf, size_t size, int *status, char *resp_json) +static int write_asap_jsonrpc(char *buf, size_t size, int *status, char *resp_json, cJSON *id) { size_t rlen; rlen = strlen(resp_json); @@ -797,7 +794,7 @@ static int write_asap_jsonrpc(char *buf, size_t size, int *status, char *resp_js "ASAP response length %zu exceeds gateway buffer %zu", rlen, size); free(resp_json); - jsonrpc_error(buf, size, status, 500, -32603, too_big); + jsonrpc_error(buf, size, status, 500, -32603, too_big, id); return -1; } *status = 200; @@ -815,22 +812,18 @@ static void handle_asap(http_server_ctx_t *ctx, const char *client_ip, asap_server_ctx_t asap_ctx; cJSON *parse_err = NULL; char err_msg[256]; - char *resp_json; char *snippet; int rc; (void)body_len; if (rate_limit_asap(client_ip, time(NULL))) { - jsonrpc_error(buf, size, status, 429, -32000, "rate limit exceeded"); + jsonrpc_error(buf, size, status, 429, -32000, "rate limit exceeded", NULL); return; } asap_envelope_init(&in); rc = asap_envelope_parse(body, &in, &parse_err); if (rc != 0) { - char *err_str = parse_err ? cJSON_PrintUnformatted(parse_err) : NULL; - cJSON_Delete(parse_err); + write_asap_error(buf, size, status, 400, parse_err); asap_envelope_clear(&in); - jsonrpc_error(buf, size, status, 400, -32700, err_str ? err_str : "parse error"); - free(err_str); return; } snippet = in.payload ? cJSON_PrintUnformatted(in.payload) : NULL; @@ -844,25 +837,21 @@ static void handle_asap(http_server_ctx_t *ctx, const char *client_ip, asap_envelope_init(&out); rc = asap_server_handle(&in, &out, &asap_ctx, err_msg, sizeof err_msg); } - asap_envelope_clear(&in); if (rc != 0) { - asap_envelope_clear(&out); - jsonrpc_error(buf, size, status, 400, rc, err_msg[0] ? err_msg : "handler error"); - return; - } - resp_json = asap_envelope_to_jsonrpc_string(&out, NULL); - if (!resp_json) { - asap_envelope_clear(&out); - jsonrpc_error(buf, size, status, 500, -32603, "failed to serialize response"); - return; - } - if (write_asap_jsonrpc(buf, size, status, resp_json) != 0) { - asap_envelope_clear(&out); - return; + jsonrpc_error(buf, size, status, 400, rc, err_msg[0] ? err_msg : "Handler error", + in.jsonrpc_request_id); + } else { + char *resp_json = asap_envelope_to_jsonrpc_string(&out, in.jsonrpc_request_id); + if (!resp_json) { + jsonrpc_error(buf, size, status, 500, -32603, "Cannot serialize response", + in.jsonrpc_request_id); + } else if (write_asap_jsonrpc(buf, size, status, resp_json, in.jsonrpc_request_id) == 0) { + snippet = cJSON_PrintUnformatted(out.payload); + asap_log_append_out(out.payload_type, out.id, snippet); + free(snippet); + } } - snippet = out.payload ? cJSON_PrintUnformatted(out.payload) : NULL; - asap_log_append_out(out.payload_type, out.id, snippet); - free(snippet); + asap_envelope_clear(&in); asap_envelope_clear(&out); } @@ -896,8 +885,12 @@ static void handle_well_known(http_server_ctx_t *ctx, const char *uri, int uri_l return; } if (uri_exact_eq(uri, uri_len, "/.well-known/asap/health")) { - *status = 200; - json_response(buf, size, status, manifest_health_json()); + char *json = manifest_health_json(ctx ? ctx->cfg : NULL, gateway_uptime_seconds(ctx)); + if (!json || strlen(json) >= size) + json_error(buf, size, status, 500, "Internal error"); + else + json_response(buf, size, status, json); + free(json); return; } json_error(buf, size, status, 404, "Not found"); diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index a1e61bc1..9e6a308f 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -644,6 +644,17 @@ static int test_api_config_401_malformed_auth(void) return 0; } +static int asap_rpc_id_is(const char *body, const char *expected_json) +{ + cJSON *root = cJSON_Parse(body); + cJSON *expected = cJSON_Parse(expected_json); + int matches = cJSON_Compare(cJSON_GetObjectItemCaseSensitive(root, "id"), expected, 1); + + cJSON_Delete(root); + cJSON_Delete(expected); + return matches; +} + static int test_asap_invalid_body(void) { long code; @@ -653,6 +664,7 @@ static int test_asap_invalid_body(void) ASSERT(code == 400); ASSERT(body != NULL); ASSERT(strstr(body, "error") != NULL); + ASSERT(asap_rpc_id_is(body, "null")); free(body); return 0; } @@ -661,11 +673,14 @@ static int test_asap_missing_fields(void) { long code; char *body = NULL; - int r = http_post(gw_url("/asap"), "{\"jsonrpc\":\"2.0\"}", &code, &body); + int r = http_post(gw_url("/asap"), + "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\"," + "\"params\":{},\"id\":\"qa-missing-fields\"}", &code, &body); ASSERT(r == 0); ASSERT(code == 400); ASSERT(body != NULL); ASSERT(strstr(body, "error") != NULL); + ASSERT(asap_rpc_id_is(body, "\"qa-missing-fields\"")); free(body); return 0; } @@ -768,6 +783,7 @@ static int test_asap_task_request(void) ASSERT(asap_http_is(code, 200, body)); ASSERT(body != NULL); ASSERT(asap_result_payload_type_is(body, "task.response")); + ASSERT(asap_rpc_id_is(body, "42")); free(body); return 0; } @@ -802,6 +818,7 @@ static int test_asap_mcp_unknown_tool(void) ASSERT(code == 400); ASSERT(body != NULL); ASSERT(asap_error_code_is(body, -32001)); + ASSERT(asap_rpc_id_is(body, "42")); free(body); return 0; } @@ -905,6 +922,7 @@ static int test_asap_rejects_oversized_response(const char *token) ASSERT(parsed != NULL); cJSON_Delete(parsed); ASSERT(asap_error_code_is(body, -32603)); + ASSERT(asap_rpc_id_is(body, "42")); ASSERT(strstr(body, "exceeds gateway buffer") != NULL); free(body); if (token && token[0]) { @@ -1020,9 +1038,21 @@ static int test_health_wellknown(void) ASSERT(r == 0); ASSERT(code == 200); ASSERT(body != NULL); - ASSERT(strstr(body, "status") != NULL); - ASSERT(strstr(body, "ok") != NULL); + cJSON *json = cJSON_Parse(body); free(body); + ASSERT(json != NULL); + const char *status = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(json, "status")); + const char *agent = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(json, "agent_id")); + const char *version = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(json, "version")); + const char *asap_version = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(json, "asap_version")); + cJSON *uptime = cJSON_GetObjectItemCaseSensitive(json, "uptime_seconds"); + int valid = status && strcmp(status, "healthy") == 0 && + agent && strcmp(agent, "urn:asap:agent:shellclaw-gateway-test") == 0 && + version && strcmp(version, SHELLCLAW_RELEASE_VERSION) == 0 && + asap_version && strcmp(asap_version, "2.1.0") == 0 && + cJSON_IsNumber(uptime) && uptime->valuedouble >= 0.0; + cJSON_Delete(json); + ASSERT(valid); return 0; } @@ -1749,6 +1779,7 @@ int main(int argc, char **argv) fprintf(f, "[agent]\nmodel = \"test\"\n"); fprintf(f, "[providers]\nfallback_chain = [ \"stub\" ]\n"); fprintf(f, "[gateway]\nenabled = true\nhost = \"127.0.0.1\"\nport = %d\n", port); + fprintf(f, "[asap]\nagent_urn = \"urn:asap:agent:shellclaw-gateway-test\"\n"); fprintf(f, "[memory]\ndb_path = \"%s/.shellclaw/memory.db\"\n", g_test_home); fprintf(f, "[skills]\ndir = \"%s\"\n", skills_dir); fclose(f); diff --git a/tests/test_manifest_build.c b/tests/test_manifest_build.c index 26cfda8c..9d0a4a04 100644 --- a/tests/test_manifest_build.c +++ b/tests/test_manifest_build.c @@ -25,16 +25,17 @@ static int test_health_json(void) { - const char *s = manifest_health_json(); - ASSERT(s != NULL); - ASSERT(strstr(s, "status") != NULL); - ASSERT(strstr(s, "ok") != NULL); - cJSON *parsed = cJSON_Parse(s); + char *json = manifest_health_json(NULL, 12.25); + ASSERT(json != NULL); + cJSON *parsed = cJSON_Parse(json); + free(json); ASSERT(parsed != NULL); - cJSON *status = cJSON_GetObjectItem(parsed, "status"); - ASSERT(status != NULL); - ASSERT(cJSON_IsString(status)); - ASSERT(strcmp(status->valuestring, "ok") == 0); + const char *status = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(parsed, "status")); + const char *agent = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(parsed, "agent_id")); + cJSON *uptime = cJSON_GetObjectItemCaseSensitive(parsed, "uptime_seconds"); + ASSERT(status && strcmp(status, "healthy") == 0); + ASSERT(agent && strcmp(agent, "urn:asap:agent:shellclaw") == 0); + ASSERT(cJSON_IsNumber(uptime) && uptime->valuedouble == 12.25); cJSON_Delete(parsed); return 0; } From 04a95dc9457c330ff6afa21825975c70152d7f04 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:32:42 -0300 Subject: [PATCH 02/10] fix(asap): accept SDK echo task envelopes --- Makefile | 8 ++-- src/asap/envelope.c | 73 ++++++++++++++++++++++++++++++++----- src/asap/envelope.h | 14 ++++--- src/asap/manifest_build.c | 19 ++++++++-- src/asap/manifest_build.h | 3 ++ src/asap/server.c | 51 +++++++++++++++++++++++--- tests/test_asap_envelope.c | 34 +++++++++++++++++ tests/test_asap_server.c | 21 +++++++++++ tests/test_manifest_build.c | 11 ++++++ 9 files changed, 205 insertions(+), 29 deletions(-) diff --git a/Makefile b/Makefile index a9b3574a..aaef1aec 100644 --- a/Makefile +++ b/Makefile @@ -348,7 +348,7 @@ $(MANIFEST_KEYS_O): src/asap/manifest_keys.c src/asap/manifest_keys.h src/core/c $(ASAP_HTTP_BODY_O): src/gateway/asap_http_body.c src/gateway/asap_http_body.h src/gateway/http_lws.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -c -o $@ src/gateway/asap_http_body.c -$(ENVELOPE_O): src/asap/envelope.c src/asap/envelope.h src/asap/asap_version.h vendor/cJSON/cJSON.h +$(ENVELOPE_O): src/asap/envelope.c src/asap/envelope.h src/asap/asap_version.h src/asap/ulid.h vendor/cJSON/cJSON.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/asap/envelope.c $(ULID_O): src/asap/ulid.c src/asap/ulid.h src/crypto/crypto.h @@ -360,7 +360,7 @@ $(CLIENT_O): src/asap/client.c src/asap/client.h src/asap/envelope.h src/asap/ul $(ASAP_REGISTRY_O): src/asap/registry.c src/asap/registry.h src/asap/client.h src/providers/provider.h vendor/cJSON/cJSON.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/asap/registry.c -$(SERVER_O): src/asap/server.c src/asap/server.h src/asap/envelope.h src/asap/asap_version.h src/asap/ulid.h src/core/agent.h src/core/config.h src/core/memory.h src/providers/provider.h vendor/cJSON/cJSON.h +$(SERVER_O): src/asap/server.c src/asap/server.h src/asap/envelope.h src/asap/manifest_build.h src/asap/asap_version.h src/asap/ulid.h src/core/agent.h src/core/config.h src/core/memory.h src/providers/provider.h vendor/cJSON/cJSON.h $(CC) $(CFLAGS) $(INC) -pthread -c -o $@ src/asap/server.c $(ASAP_LOG_O): src/asap/log.c src/asap/log.h @@ -713,9 +713,9 @@ test_manifest: test_manifest_build test_manifest_keys test_jcs $(BINDIR)/test_manifest_keys $(BINDIR)/test_jcs -test_asap_envelope: tests/test_asap_envelope.c $(ENVELOPE_O) $(CJSON_O) +test_asap_envelope: tests/test_asap_envelope.c $(ENVELOPE_O) $(ULID_O) $(CRYPTO_LINK) $(CJSON_O) @mkdir -p $(BINDIR) - $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ tests/test_asap_envelope.c $(ENVELOPE_O) $(CJSON_O) $(LDLIBS) + $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ tests/test_asap_envelope.c $(ENVELOPE_O) $(ULID_O) $(CRYPTO_LINK) $(CJSON_O) $(LDLIBS) -pthread $(DSYM_SCRIPT) test_asap_ulid: tests/test_asap_ulid.c $(ULID_O) $(CRYPTO_LINK) diff --git a/src/asap/envelope.c b/src/asap/envelope.c index 11d4857d..019b3d7c 100644 --- a/src/asap/envelope.c +++ b/src/asap/envelope.c @@ -5,6 +5,7 @@ #define _POSIX_C_SOURCE 200809L #include "asap/envelope.h" +#include "asap/ulid.h" #include #include #include @@ -43,6 +44,7 @@ void asap_envelope_clear(asap_envelope_t *env) str_free(&env->correlation_id); str_free(&env->trace_id); str_free(&env->timestamp); + env->sdk_wire = 0; } cJSON *asap_jsonrpc_error(int code, const char *message, cJSON *id) @@ -130,11 +132,11 @@ static int require_str_in_params(cJSON *params, const char *key, char **out, cJS } static int optional_str_in_params(cJSON *params, const char *key, char **out, cJSON *rpc_id, - asap_envelope_t *env, cJSON **err_out) + asap_envelope_t *env, cJSON **err_out, int sdk_wire) { - *out = NULL; - if (!cJSON_HasObjectItem(params, key)) return 0; cJSON *j = cJSON_GetObjectItemCaseSensitive(params, key); + *out = NULL; + if (!j || (sdk_wire && cJSON_IsNull(j))) return 0; if (!cJSON_IsString(j) || !j->valuestring) return parse_fail(env, rpc_id, err_out, "Invalid params: optional field has wrong type"); *out = strdup(j->valuestring); @@ -142,7 +144,25 @@ static int optional_str_in_params(cJSON *params, const char *key, char **out, cJ return 0; } -int asap_envelope_from_object(const cJSON *obj, cJSON *rpc_id, asap_envelope_t *out, cJSON **err_out) +static int parse_envelope_id(cJSON *obj, cJSON *rpc_id, asap_envelope_t *out, + cJSON **err_out, int sdk_wire) +{ + cJSON *id = cJSON_GetObjectItemCaseSensitive(obj, "id"); + if (!sdk_wire || (id && !cJSON_IsNull(id))) { + if (require_str_in_params(obj, "id", &out->id, rpc_id, out, err_out) != 0) + return -1; + if (sdk_wire && !out->id[0]) + return parse_fail(out, rpc_id, err_out, "Envelope ID must not be empty"); + return 0; + } + char generated[ULID_STRING_LEN + 1]; + if (ulid_generate(generated, sizeof generated) != 0 || !(out->id = strdup(generated))) + return parse_fail(out, rpc_id, err_out, "Cannot generate envelope ID"); + return 0; +} + +static int envelope_from_object(const cJSON *obj, cJSON *rpc_id, + asap_envelope_t *out, cJSON **err_out, int sdk_wire) { cJSON *r = (cJSON *)obj; cJSON *rid_temp = NULL; @@ -156,13 +176,18 @@ int asap_envelope_from_object(const cJSON *obj, cJSON *rpc_id, asap_envelope_t * } asap_envelope_clear(out); asap_envelope_init(out); - if (require_str_in_params(r, "id", &out->id, rpc_id, out, err_out) != 0) return -1; + if (parse_envelope_id(r, rpc_id, out, err_out, sdk_wire) != 0) return -1; if (require_str_in_params(r, "asap_version", &out->asap_version, rpc_id, out, err_out) != 0) return -1; if (require_str_in_params(r, "sender", &out->sender, rpc_id, out, err_out) != 0) return -1; if (require_str_in_params(r, "recipient", &out->recipient, rpc_id, out, err_out) != 0) return -1; if (require_str_in_params(r, "payload_type", &out->payload_type, rpc_id, out, err_out) != 0) return -1; - if (!payload_type_is_allowed(out->payload_type)) + if (sdk_wire) { + if (strcmp(out->payload_type, "TaskRequest") != 0 && + strcmp(out->payload_type, "task.request") != 0) + return parse_fail(out, rpc_id, err_out, "The SDK request must contain a TaskRequest"); + } else if (!payload_type_is_allowed(out->payload_type)) { return parse_fail(out, rpc_id, err_out, "Invalid params: unknown payload_type"); + } { cJSON *pl = cJSON_GetObjectItemCaseSensitive(r, "payload"); if (pl == NULL || cJSON_IsNull(pl)) @@ -170,13 +195,19 @@ int asap_envelope_from_object(const cJSON *obj, cJSON *rpc_id, asap_envelope_t * out->payload = cJSON_Duplicate(pl, 1); if (!out->payload) return parse_fail(out, rpc_id, err_out, "Invalid params: allocation failed"); } - if (optional_str_in_params(r, "correlation_id", &out->correlation_id, rpc_id, out, err_out) != 0) return -1; - if (optional_str_in_params(r, "trace_id", &out->trace_id, rpc_id, out, err_out) != 0) return -1; - if (optional_str_in_params(r, "timestamp", &out->timestamp, rpc_id, out, err_out) != 0) return -1; + if (optional_str_in_params(r, "correlation_id", &out->correlation_id, rpc_id, out, err_out, sdk_wire) != 0) return -1; + if (optional_str_in_params(r, "trace_id", &out->trace_id, rpc_id, out, err_out, sdk_wire) != 0) return -1; + if (optional_str_in_params(r, "timestamp", &out->timestamp, rpc_id, out, err_out, sdk_wire) != 0) return -1; + out->sdk_wire = sdk_wire; if (rid_temp) cJSON_Delete(rid_temp); return 0; } +int asap_envelope_from_object(const cJSON *obj, cJSON *rpc_id, asap_envelope_t *out, cJSON **err_out) +{ + return envelope_from_object(obj, rpc_id, out, err_out, 0); +} + /** Envelope key/value object for params or result (same shape). */ static cJSON *envelope_fields_cjson(const asap_envelope_t *env) { @@ -220,6 +251,15 @@ cJSON *asap_envelope_to_jsonrpc(const asap_envelope_t *env, cJSON *jsonrpc_id) cJSON *result = envelope_fields_cjson(env); cJSON *root; if (!result) return NULL; + if (env->sdk_wire) { + cJSON *wrapped = cJSON_CreateObject(); + if (!wrapped || !cJSON_AddItemToObject(wrapped, "envelope", result)) { + cJSON_Delete(wrapped); + cJSON_Delete(result); + return NULL; + } + result = wrapped; + } root = cJSON_CreateObject(); if (!root) { cJSON_Delete(result); return NULL; } if (!cJSON_AddStringToObject(root, "jsonrpc", "2.0") || !cJSON_AddItemToObject(root, "result", result)) { @@ -354,6 +394,14 @@ int asap_envelope_parse(const char *json, asap_envelope_t *out, cJSON **err_out) } return -1; } + cJSON *request_id = cJSON_GetObjectItemCaseSensitive(root, "id"); + if (request_id && !cJSON_IsString(request_id) && !cJSON_IsNumber(request_id) && + !cJSON_IsNull(request_id)) { + if (err_out) + *err_out = asap_jsonrpc_error(-32600, "Invalid JSON-RPC request ID", NULL); + cJSON_Delete(root); + return -1; + } cJSON *rpc_id = dup_request_id(root); if (!rpc_id) { cJSON_Delete(root); @@ -374,7 +422,12 @@ int asap_envelope_parse(const char *json, asap_envelope_t *out, cJSON **err_out) cJSON_Delete(root); return parse_fail(out, rpc_id, err_out, "Invalid Request: params must be an object"); } - if (asap_envelope_from_object(params, rpc_id, out, err_out) != 0) { + cJSON *nested = cJSON_GetObjectItemCaseSensitive(params, "envelope"); + if (nested && (!cJSON_IsObject(nested) || strcmp(meth->valuestring, "asap.send") != 0)) { + cJSON_Delete(root); + return parse_fail(out, rpc_id, err_out, "Invalid SDK request"); + } + if (envelope_from_object(nested ? nested : params, rpc_id, out, err_out, nested != NULL) != 0) { cJSON_Delete(root); return -1; } diff --git a/src/asap/envelope.h b/src/asap/envelope.h index fda2f906..6f8e55ca 100644 --- a/src/asap/envelope.h +++ b/src/asap/envelope.h @@ -19,7 +19,7 @@ extern "C" { * asap_envelope_clear to release. */ typedef struct asap_envelope { - cJSON *jsonrpc_request_id; /**< Top-level JSON-RPC "id" (any JSON type); for responses/errors. */ + cJSON *jsonrpc_request_id; /**< Top-level JSON-RPC request ID for responses and errors. */ char *id; /**< Envelope or task id (ULID or string). */ char *asap_version; /**< Protocol version, e.g. "2.1". */ char *sender; /**< Sender URN. */ @@ -29,6 +29,7 @@ typedef struct asap_envelope { char *correlation_id; /**< Correlation for tracing. */ char *trace_id; /**< Distributed trace id. */ char *timestamp; /**< ISO 8601 timestamp string. */ + int sdk_wire; /**< Use the SDK envelope wrapper for a task. */ } asap_envelope_t; /** @@ -49,11 +50,11 @@ void asap_envelope_clear(asap_envelope_t *env); /** * Parse a JSON-RPC 2.0 request body. Top-level @c jsonrpc must be @c "2.0", - * @c method a non-empty string, @c params an object with required ASAP - * fields: @c id, @c asap_version, @c sender, @c recipient, @c payload_type, + * @c method a non-empty string, and @c params an object. Legacy parameters + * contain these fields: @c id, @c asap_version, @c sender, @c recipient, @c payload_type, * and @c payload. Optional: @c correlation_id, @c trace_id, @c timestamp - * (strings). On success, @p out is filled; call asap_envelope_clear when - * done. On failure, out may be cleared and, if @p err_out is non-NULL, + * (strings). SDK tasks use @c asap.send with fields in @c params.envelope. + * Their envelope ID defaults to a generated ULID. Clear @p out after use. On failure, out may be cleared and, if @p err_out is non-NULL, * *err_out is a full JSON-RPC error (code -32602 Invalid params) with * the request @c id echoed; caller must cJSON_Delete. * @@ -86,7 +87,8 @@ int asap_envelope_from_object(const cJSON *obj, cJSON *rpc_id, asap_envelope_t * /** * Build a JSON-RPC 2.0 success response: @c { "jsonrpc": "2.0", "result": { ...envelope... }, "id": ... }. - * The @a result object mirrors the request @c params shape. If @a jsonrpc_id + * The @a result object mirrors the request @c params shape. SDK replies + * contain @c result.envelope. If @a jsonrpc_id * is NULL, uses @c env->jsonrpc_request_id. Caller cJSON_Deletes the return * or uses #asap_envelope_to_jsonrpc_string. * diff --git a/src/asap/manifest_build.c b/src/asap/manifest_build.c index ef042e1f..34ef7f8f 100644 --- a/src/asap/manifest_build.c +++ b/src/asap/manifest_build.c @@ -136,7 +136,7 @@ static int count_skills_on_disk(const config_t *cfg) static int add_capabilities_skills(cJSON *capabilities, const config_t *cfg) { cJSON *skills; - char *names[MAX_SKILL_NAMES]; + char *names[MAX_SKILL_NAMES + 1]; int n; int total; int i; @@ -148,16 +148,27 @@ static int add_capabilities_skills(cJSON *capabilities, const config_t *cfg) return -1; /* skills orphan deleted by helper; root cleaned by caller */ if (!cfg) return 0; total = count_skills_on_disk(cfg); - n = skill_list_names(cfg, names, MAX_SKILL_NAMES); + n = skill_list_names(cfg, names + 1, MAX_SKILL_NAMES); if (n < 0) return -1; + n++; + names[0] = strdup(ASAP_SDK_ECHO_SKILL); + if (!names[0]) { + for (i = 1; i < n; i++) + free(names[i]); + return -1; + } if (total > MAX_SKILL_NAMES) fprintf(stderr, "manifest: skills truncated (%d > %d)\n", total, MAX_SKILL_NAMES); - for (i = 0; i < n && i < MAX_SKILL_NAMES; i++) { + for (i = 0; i < n; i++) { cJSON *item; cJSON *id_str; cJSON *desc_str; const char *desc; + if (i > 0 && strcmp(names[i], ASAP_SDK_ECHO_SKILL) == 0) { + free(names[i]); + continue; + } item = cJSON_CreateObject(); if (!item) { for (int j = i; j < n; j++) @@ -184,7 +195,7 @@ static int add_capabilities_skills(cJSON *capabilities, const config_t *cfg) free(names[j]); return -1; } - desc = skill_description_for(cfg, names[i]); + desc = i == 0 ? "Return the task input." : skill_description_for(cfg, names[i]); desc_str = cJSON_CreateString(desc ? desc : names[i]); if (!desc_str) { cJSON_DeleteItemFromArray(skills, cJSON_GetArraySize(skills) - 1); diff --git a/src/asap/manifest_build.h b/src/asap/manifest_build.h index bdda7b65..d21eaea7 100644 --- a/src/asap/manifest_build.h +++ b/src/asap/manifest_build.h @@ -10,6 +10,9 @@ /** Protocol version advertised by the manifest and health endpoints. */ #define ASAP_DISCOVERY_VERSION "2.1.0" +/** Name of the built-in SDK skill that returns its task input. */ +#define ASAP_SDK_ECHO_SKILL "echo" + struct config; typedef struct config config_t; diff --git a/src/asap/server.c b/src/asap/server.c index 63bebdc1..98e79185 100644 --- a/src/asap/server.c +++ b/src/asap/server.c @@ -6,6 +6,7 @@ #include "asap/server.h" #include "asap/asap_version.h" +#include "asap/manifest_build.h" #include "asap/ulid.h" #include "core/agent.h" #include "core/config.h" @@ -101,11 +102,14 @@ static int fill_response_envelope(asap_envelope_t *out, const asap_envelope_t *i out->payload_type = strdup(payload_type); /* Ownership of payload moves to out; asap_envelope_clear frees it once. */ out->payload = payload; - if (in->correlation_id) - out->correlation_id = strdup(in->correlation_id); + const char *correlation = in->sdk_wire ? in->id : in->correlation_id; + out->sdk_wire = in->sdk_wire; + if (correlation) + out->correlation_id = strdup(correlation); if (in->trace_id) out->trace_id = strdup(in->trace_id); - if (!out->id || !out->asap_version || !out->sender || !out->recipient || !out->payload_type) { + if (!out->id || !out->asap_version || !out->sender || !out->recipient || !out->payload_type || + (correlation && !out->correlation_id) || (in->trace_id && !out->trace_id)) { asap_envelope_clear(out); asap_envelope_init(out); return -32603; @@ -130,6 +134,19 @@ const char *asap_resolve_task_session_id(const char *sender, char *buf, size_t b return buf; } +static int fill_sdk_task_response(asap_envelope_t *out, const asap_envelope_t *in, cJSON *result) +{ + cJSON *payload = cJSON_CreateObject(); + if (!payload || !result || !cJSON_AddStringToObject(payload, "task_id", in->id) || + !cJSON_AddStringToObject(payload, "status", "completed") || + !cJSON_AddItemToObject(payload, "result", result)) { + cJSON_Delete(payload); + cJSON_Delete(result); + return -32603; + } + return fill_response_envelope(out, in, "task.response", payload); +} + static int handle_task_request(const asap_envelope_t *in, asap_envelope_t *out, asap_server_ctx_t *ctx, char *err_message, size_t err_message_size) { @@ -155,8 +172,7 @@ static int handle_task_request(const asap_envelope_t *in, asap_envelope_t *out, resp_buf[0] = '\0'; /* Isolate SQLite history by sender URN; "asap:inbound" mixed clients (#64). * Ignore ctx->session_id so a later constant (including asap:inbound) - * cannot restore a shared bucket. Authenticity is sender_is_trusted(): - * POST /asap is protocol-public; empty trusted_senders allows every URN. */ + * cannot restore a shared bucket. */ sid = asap_resolve_task_session_id(in->sender, sid_buf, sizeof sid_buf); if (!sid) { char too_long[128]; @@ -204,6 +220,29 @@ static int handle_task_request(const asap_envelope_t *in, asap_envelope_t *out, return fill_rc; } +static int handle_sdk_task(const asap_envelope_t *in, asap_envelope_t *out, + asap_server_ctx_t *ctx, char *err_message, size_t err_message_size) +{ + const char *skill = payload_pick_string(in->payload, "skill_id"); + const char *conversation = payload_pick_string(in->payload, "conversation_id"); + const cJSON *input = cJSON_GetObjectItemCaseSensitive(in->payload, "input"); + + if (!in->sender || !in->sender[0] || !in->recipient || + strcmp(in->recipient, config_asap_agent_urn(ctx->cfg)) != 0) { + set_err(err_message, err_message_size, "Invalid sender or recipient"); + return -32602; + } + if (!skill || !*skill || !conversation || !*conversation || !cJSON_IsObject(input)) { + set_err(err_message, err_message_size, "TaskRequest needs a skill, conversation and input object"); + return -32602; + } + if (strcmp(skill, ASAP_SDK_ECHO_SKILL) != 0) { + set_err(err_message, err_message_size, "SDK tasks support only the echo skill"); + return -32602; + } + return fill_sdk_task_response(out, in, cJSON_Duplicate(input, 1)); +} + static int handle_task_cancel(const asap_envelope_t *in, asap_envelope_t *out, char *err_message, size_t err_message_size) { @@ -381,6 +420,8 @@ int asap_server_handle(const asap_envelope_t *in, asap_envelope_t *out, return ASAP_SERVER_RPC_SENDER_UNTRUSTED; } asap_envelope_init(out); + if (in->sdk_wire) + return handle_sdk_task(in, out, ctx, err_message, err_message_size); if (strcmp(in->payload_type, "task.response") == 0 || strcmp(in->payload_type, "mcp.tool_result") == 0) { set_err(err_message, err_message_size, "payload_type not accepted on inbound server"); diff --git a/tests/test_asap_envelope.c b/tests/test_asap_envelope.c index 5999f5f6..2b435a33 100644 --- a/tests/test_asap_envelope.c +++ b/tests/test_asap_envelope.c @@ -117,6 +117,25 @@ static int test_parse_valid(void) return 0; } +static int test_parse_sdk_task(void) +{ + const char *request = + "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":\"req-1\",\"params\":{\"envelope\":{" + "\"asap_version\":\"0.1\",\"sender\":\"urn:asap:agent:a\",\"recipient\":\"urn:asap:agent:b\"," + "\"payload_type\":\"TaskRequest\",\"payload\":{\"conversation_id\":\"c\",\"skill_id\":\"echo\",\"input\":{}}," + "\"correlation_id\":null,\"trace_id\":null,\"timestamp\":null}}}"; + asap_envelope_t env; + cJSON *error = NULL; + int rc = asap_envelope_parse(request, &env, &error); + cJSON_Delete(error); + ASSERT(rc == 0); + ASSERT(env.id && strlen(env.id) == 26); + ASSERT(env.trace_id == NULL && env.correlation_id == NULL && env.timestamp == NULL); + ASSERT(strcmp(cJSON_GetStringValue(env.jsonrpc_request_id), "req-1") == 0); + asap_envelope_clear(&env); + return 0; +} + #define ASSERT_ERR_CODE(err, want) do { \ cJSON *_e = cJSON_GetObjectItem((err), "error"); \ ASSERT(_e != NULL); \ @@ -124,6 +143,19 @@ static int test_parse_valid(void) ASSERT(_c != NULL && cJSON_IsNumber(_c) && (int)_c->valuedouble == (want)); \ } while (0) +static int test_parse_bad_request_id(void) +{ + const char *request = "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":[],\"params\":{}}"; + asap_envelope_t env; + cJSON *err = NULL; + + ASSERT(asap_envelope_parse(request, &env, &err) == -1); + ASSERT_ERR_CODE(err, -32600); + ASSERT(cJSON_IsNull(cJSON_GetObjectItemCaseSensitive(err, "id"))); + cJSON_Delete(err); + return 0; +} + static int test_parse_unquoted_body_fails(void) { asap_envelope_t env; @@ -342,7 +374,9 @@ int main(int argc, char **argv) if (test_clear_idempotent() != 0) { fprintf(stderr, "test_clear_idempotent failed\n"); failed++; } if (test_jsonrpc_error_shape() != 0) { fprintf(stderr, "test_jsonrpc_error_shape failed\n"); failed++; } if (test_jsonrpc_error_null_id() != 0) { fprintf(stderr, "test_jsonrpc_error_null_id failed\n"); failed++; } + if (test_parse_sdk_task() != 0) { fprintf(stderr, "test_parse_sdk_task failed\n"); failed++; } if (test_parse_valid() != 0) { fprintf(stderr, "test_parse_valid failed\n"); failed++; } + if (test_parse_bad_request_id() != 0) { fprintf(stderr, "test_parse_bad_request_id failed\n"); failed++; } if (test_parse_unquoted_body_fails() != 0) { fprintf(stderr, "test_parse_unquoted_body_fails failed\n"); failed++; } if (test_parse_wrong_jsonrpc() != 0) { fprintf(stderr, "test_parse_wrong_jsonrpc failed\n"); failed++; } if (test_parse_all_missing_in_turn() != 0) { fprintf(stderr, "test_parse_all_missing_in_turn failed\n"); failed++; } diff --git a/tests/test_asap_server.c b/tests/test_asap_server.c index 7d104909..f77ad30d 100644 --- a/tests/test_asap_server.c +++ b/tests/test_asap_server.c @@ -222,6 +222,26 @@ static void teardown_env(asap_envelope_t *e) asap_envelope_init(e); } +static int test_sdk_unknown_skill(void) +{ + const char *request = + "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":1,\"params\":{\"envelope\":{" + "\"id\":\"this-request\",\"correlation_id\":\"earlier-request\",\"asap_version\":\"0.1\"," + "\"sender\":\"urn:asap:agent:peer\",\"recipient\":\"urn:asap:agent:shellclaw\"," + "\"payload_type\":\"TaskRequest\",\"payload\":{\"conversation_id\":\"c\",\"skill_id\":\"chat\",\"input\":{}}}}}"; + asap_envelope_t in; + asap_envelope_t out = {0}; + asap_server_ctx_t ctx = {.task_request_hook = test_hook_task}; + char err[128]; + + ASSERT(asap_envelope_parse(request, &in, NULL) == 0); + ASSERT(asap_server_handle(&in, &out, &ctx, err, sizeof err) == -32602); + ASSERT(out.payload == NULL); + teardown_env(&in); + teardown_env(&out); + return 0; +} + static int test_task_request_hook(void) { asap_envelope_t in; @@ -1064,6 +1084,7 @@ static int test_state_query_hook_holds_agent_mutex(void) int main(void) { int r = 0; + r |= test_sdk_unknown_skill(); r |= test_task_request_hook(); r |= test_task_cancel_stub(); r |= test_state_query_hook(); diff --git a/tests/test_manifest_build.c b/tests/test_manifest_build.c index 9d0a4a04..7ac24600 100644 --- a/tests/test_manifest_build.c +++ b/tests/test_manifest_build.c @@ -157,6 +157,10 @@ static int test_manifest_skill_objects(void) ASSERT(f); fprintf(f, "# Demo skill headline\nBody ignored for manifest.\n"); fclose(f); + f = fopen("/tmp/shellclaw_test_manifest_skills_obj/echo.md", "w"); + ASSERT(f); + fprintf(f, "# Local echo skill\n"); + fclose(f); f = fopen(TMP_CONFIG, "w"); ASSERT(f); fprintf(f, "[agent]\nmodel = \"test\"\n"); @@ -173,9 +177,15 @@ static int test_manifest_skill_objects(void) skills = cJSON_GetObjectItem(cJSON_GetObjectItem(parsed, "capabilities"), "skills"); ASSERT(skills != NULL); item = NULL; + int echo_count = 0; for (int i = 0; i < cJSON_GetArraySize(skills); i++) { cJSON *s = cJSON_GetArrayItem(skills, i); const char *sid = cJSON_GetObjectItem(s, "id")->valuestring; + if (strcmp(sid, ASAP_SDK_ECHO_SKILL) == 0) { + echo_count++; + ASSERT(strcmp(cJSON_GetObjectItem(s, "description")->valuestring, + "Return the task input.") == 0); + } if (strcmp(sid, "demo") == 0) item = s; if (strcmp(sid, "override_skill") == 0) @@ -183,6 +193,7 @@ static int test_manifest_skill_objects(void) "From config table") == 0); } ASSERT(item != NULL); + ASSERT(echo_count == 1); ASSERT(strcmp(cJSON_GetObjectItem(item, "description")->valuestring, "Demo skill headline") == 0); cJSON_Delete(parsed); From b34d261cdd28cf4aa6e8afe5ff436810a78f8ba0 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:38:13 -0300 Subject: [PATCH 03/10] ci(asap): require live gateway compliance checks --- .github/workflows/ci.yml | 18 ++--- config.example.toml | 10 ++- docs/ASAP.md | 113 ++++++------------------------- scripts/run_asap_ci.py | 66 ++++++++++++++++++ scripts/run_asap_compliance.sh | 60 +++++++++++----- tests/fixtures/ci_asap_test.toml | 20 ++++-- 6 files changed, 156 insertions(+), 131 deletions(-) create mode 100644 scripts/run_asap_ci.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9da02672..227d41c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,13 +55,15 @@ jobs: fi echo "Binary size: $size bytes (OK)" - - name: Coverage (agent core >= 80%, hardware excluded) - run: GATEWAY=1 make coverage + - name: Set up Python for ASAP compliance + uses: actions/setup-python@v5 + with: + python-version: "3.14" - - name: ASAP compliance check - # Pin: asap-compliance >= 1.0.0 (https://pypi.org/project/asap-compliance/) - # Requires Python 3.10+. Gracefully skips if package not yet published. + - name: Check ASAP compliance against a live gateway run: | - pip install --quiet 'asap-compliance>=1.0.0' 2>/dev/null \ - && asap-compliance --config tests/fixtures/ci_asap_test.toml build/shellclaw \ - || echo "asap-compliance unavailable or skipped (non-blocking until v0.3.0 release)" + python3 -m pip install 'asap-compliance==1.4.0' 'asap-protocol==2.6.0' + python3 scripts/run_asap_ci.py build/shellclaw + + - name: Coverage (agent core >= 80%, hardware excluded) + run: GATEWAY=1 make coverage diff --git a/config.example.toml b/config.example.toml index 0bde6210..13a069e9 100644 --- a/config.example.toml +++ b/config.example.toml @@ -78,12 +78,10 @@ description = "C-native edge-AI ASAP agent on NVIDIA Jetson Orin Nano Super (CUD # Production: set to your HTTPS origin before marketplace registration (example.com is dev-only). public_base_url = "https://shellclaw.example.com" registry_url = "https://raw.githubusercontent.com/asap-protocol/asap-protocol/main/registry.json" -# POST /asap is protocol-public (rate-limited, not Bearer). Empty trusted_senders -# allows every sender URN. After inbound dispatch is wired, a trusted (or, with -# an empty list, any) sender can run task.request (agent_run + tool table) and -# mcp.tool_call (direct tool execute, no LLM). Default gateway bind is 127.0.0.1. -# Set this in production before exposing the gateway so sessions keyed as -# asap: cannot be spoofed and local tools are not open to any URN. +# The gateway compares the sender URN on every /asap request with this list. +# If the list is empty, the gateway accepts all sender URNs. +# Control network access to legacy ASAP requests that can use local tools. +# The SDK envelope format supports the built-in echo skill. # trusted_senders = ["urn:asap:agent:peer"] [asap.skill_descriptions] diff --git a/docs/ASAP.md b/docs/ASAP.md index 8426463c..26a4178e 100644 --- a/docs/ASAP.md +++ b/docs/ASAP.md @@ -15,8 +15,8 @@ When the gateway is enabled and signing keys load successfully, ShellClaw serves | Route | Auth | Response | |-------|------|----------| | `GET /.well-known/asap/manifest.json` | Public | **SignedManifest** JSON (inner manifest + Ed25519 signature + public_key) | -| `GET /.well-known/asap/health` | Public | Minimal health stub (`{"status":"ok"}` in v1.0) | -| `POST /asap` | Rate-limited | JSON-RPC ASAP ingress: `task.request` / `mcp.tool_call` dispatch with the process provider and tool table. Inbound bodies use a 1 MiB dynamic buffer (`ASAP_BODY_MAX`); do not reintroduce the 64 KiB static `BODY_BUF_SIZE` check used by `PUT /api/config`. Serialized responses larger than the 64 KiB gateway HTTP buffer (`RESP_BUF_SIZE`) are rejected with HTTP 500 / JSON-RPC `-32603` rather than truncated. Compliance harness shape is still partial (see Known gaps). | +| `GET /.well-known/asap/health` | Public | Agent liveness, manifest identity and version, and gateway uptime | +| `POST /asap` | Rate-limited | Accepts flat legacy messages and SDK echo tasks. Requests have a 1 MiB limit. Responses that exceed the 64 KiB gateway buffer return HTTP 500 with JSON-RPC error `-32603`. | | `GET /api/asap/log` | Bearer | Inbound ASAP message log | Implementation: `src/asap/manifest.c`, `src/gateway/routes.c`. If keys cannot load, manifest route returns **500** and agent startup fails fast (`init_subsystems()`). @@ -87,7 +87,7 @@ Schema-only check (CI-safe skip if `asap` package missing): ./scripts/validate_manifest.sh /tmp/manifest.json ``` -**v1.0 note:** upstream `asap-compliance` harness may report `SignatureVerificationError` against the local gateway until JCS/signing is byte-identical with Python reference (planned v1.0.1+). C unit tests round-trip in `tests/test_manifest.c`. +The live compliance checks verify the gateway's Ed25519 signature with the Python SDK. --- @@ -150,7 +150,7 @@ IssueOps skills CSV must match manifest `capabilities.skills[].id` for v1.0: | `home_monitor` | No — Phase 7 (v1.2) | | `visual_monitor` | No — Phase 7 (v1.2) | -Manifest code registers skills from `skills/*.md` on disk; default descriptions in `src/asap/manifest_build.c` align with the four IDs above. **Discovery cap:** at most **64** skills appear in `capabilities.skills` on `/.well-known/asap/manifest.json`; additional on-disk skills remain available via the authenticated `/api/skills` API at runtime. +Manifest code registers skills from `skills/*.md` on disk; default descriptions in `src/asap/manifest_build.c` align with the four IDs above. **Discovery cap:** the manifest lists the built-in `echo` skill and up to **64** installed skills on `/.well-known/asap/manifest.json`; additional on-disk skills remain available via the authenticated `/api/skills` API at runtime. #### `online_check` and Demo badge @@ -210,105 +210,32 @@ v1.0 does not expose a reachable `endpoints.asap` URL for cross-agent invocation Security: exposing the agent increases attack surface — complete gateway hardening and audit before production funnel use (see slice risks in planning doc). -### Other v1.0.1+ items +## SDK tasks -- **ASAP compliance harness** — see [ASAP compliance harness](#asap-compliance-harness) below; target green run in v1.0.1 after live endpoint + schema alignment. +The Python SDK sends requests to `POST /asap`. Put a `TaskRequest` in `params.envelope`. The recipient must match `[asap].agent_urn`. If you configure `[asap].trusted_senders`, the gateway also checks the sender URN against that list. ---- - -## ASAP compliance harness - -ShellClaw v1.0 ships a **static** signed manifest on GitHub Pages (Q-URL) and a **partial** local gateway (manifest + minimal health + `/asap` stub). The upstream [`asap-compliance`](https://pypi.org/project/asap-compliance/) pytest harness (PRD §4.12) is the reference for a **reachable live agent**. v1.0 accepts documented deviations instead of a green badge. - -### Manual procedure (contributors) - -Re-run after any change to `src/asap/`, `src/gateway/routes.c`, or manifest signing (`src/crypto/`). **Not** a v1.0 release gate — for pre-release iteration only. +The manifest advertises the built-in `echo` skill once. The skill returns the input object as `TaskResponse.result`. Repeating an echo request produces the same result without using the model, local tools, or conversation history. -1. **Build** — `make shellclaw` -2. **Start gateway** — either: - - Existing install: `systemctl --user start shellclaw` with `[gateway] enabled`, **or** - - Ephemeral: `./scripts/dump_manifest.sh` (boots short-lived gateway on `127.0.0.1:18789`) -3. **Health** — `curl -sf http://127.0.0.1:18789/health` -4. **Manifest shape** — `curl -sf http://127.0.0.1:18789/.well-known/asap/manifest.json | head -c 200` -5. **Run harness**: +The gateway rejects other SDK skill IDs before the model runs. Use the legacy flat request format for tasks that run the agent or call local tools. -```bash -python3 -m venv .venv-asap && source .venv-asap/bin/activate -./scripts/run_asap_compliance.sh -# or explicit URL: -./scripts/run_asap_compliance.sh http://127.0.0.1:18789 -``` +SDK replies use `result.envelope`. The reply's `correlation_id` contains the request envelope ID. Both SDK and legacy replies echo the top-level JSON-RPC ID when the gateway can read it. Legacy requests use flat `params` and receive flat `result` envelopes. -6. **Compare failures** to the [documented deviations](#documented-deviations) table below. New failures after a gateway change need a row update or a code fix. -7. **Optional schema check** — pipe unsigned inner manifest or use `validate_manifest.sh` on `manifest_build_json` output in tests. +The sender list compares a URN supplied by the client. Control network access to the legacy route because it uses that list for agent and tool requests. -Requires **Python 3.13+** recommended and network for first `pip install asap-compliance` (unless `ASAP_COMPLIANCE_SKIP_PIP=1`). +## ASAP compliance harness -### How to run (reference) +CI runs the handshake, task state, and SLA validators from `asap-compliance==1.4.0` with `asap-protocol==2.6.0` on Python 3.14. The job starts a real gateway on loopback with a temporary home and a stub provider. All three tests must pass. The SLA check sends an `echo` task and measures it against a five-second timeout. -From the repository root, with the gateway listening (default `http://127.0.0.1:18789` per `config.example.toml`): +To run the same checks locally, build the gateway and install the pinned packages in a Python 3.14 virtual environment. ```bash -make shellclaw -# Start shellclaw with [gateway] enabled, or use an ephemeral instance: -# ./scripts/dump_manifest.sh -o /tmp/manifest.json # boots gateway, then exits - -python3 -m venv .venv-asap && source .venv-asap/bin/activate # PEP 668 / macOS -./scripts/run_asap_compliance.sh -./scripts/run_asap_compliance.sh http://127.0.0.1:18789 -ASAP_AGENT_URL=http://127.0.0.1:18789 ./scripts/run_asap_compliance.sh +make GATEWAY=1 shellclaw +python3.14 -m venv .venv-asap +source .venv-asap/bin/activate +python3 -m pip install 'asap-compliance==1.4.0' 'asap-protocol==2.6.0' +python3 scripts/run_asap_ci.py build/shellclaw ``` -| Environment variable | Purpose | -|---------------------|---------| -| `ASAP_AGENT_URL` | Agent base URL (default `http://127.0.0.1:18789`) | -| `ASAP_COMPLIANCE_SKIP_PIP=1` | Skip `pip install` when `asap-compliance` is already installed | -| `ASAP_COMPLIANCE_PIP_USER=1` | Use `pip install --user` | -| `ASAP_COMPLIANCE_VERSION` | Pip spec (default `asap-compliance>=1.0.0`) | -| `ASAP_COMPLIANCE_SKIP_HEALTH=1` | Skip curl probe of `/health` before pytest | -| `ASAP_COMPLIANCE_LIVE_TEST_DIR` | Directory for generated live pytest (default: temp) | - -The script installs `asap-compliance`, probes `GET $ASAP_AGENT_URL/health`, then runs three live tests (`test_live_handshake`, `test_live_state_machine`, `test_live_sla`) generated under a temp dir. It does **not** start the agent; use `scripts/dump_manifest.sh` for a short-lived local gateway during manifest publish. - -**Last harness run (2026-05-24):** `asap-compliance` 1.2.0, Python 3.14 venv `.venv-asap`, agent `http://127.0.0.1:18789` — **3 failed**, 0 passed (see deviations table). - -### v1.0 stance - -| Area | v1.0 | v1.0.1+ | -|------|------|---------| -| Marketplace discovery | Static `SignedManifest` on GitHub Pages | Optional live `endpoints.asap` + tunnel | -| Compliance badge | Deviations documented here (PRD §4.12 OR) | Run harness green against public URL | -| Gateway ASAP route | Manifest + health stubs; `/asap` parses legacy flat `params` | Align with harness `params.envelope`, task handlers, `HealthStatus` | -| Manifest trust | Ed25519 + JCS in C; unit tests pass | Byte-identical verification with upstream `asap` Python | - -### Documented deviations - -Failures observed from `./scripts/run_asap_compliance.sh` against a local gateway with `[gateway] enabled` and a signed manifest served at `/.well-known/asap/manifest.json`. - -| Test / check | Observed | Expected (harness / upstream) | Reason | Planned fix | -|--------------|----------|-------------------------------|--------|-------------| -| `test_live_handshake` → `health_schema` | `GET /.well-known/asap/health` → `{"status":"ok"}` | `HealthStatus`: `status` (`healthy`/`unhealthy`), `agent_id`, `version`, `uptime_seconds`, optional `asap_version`, `load` | v1.0 minimal stub in `manifest_health_json()`; not wired to agent URN, release semver, or uptime | **v1.0.1+** — emit full `HealthStatus` from config + `board_detect` | -| `test_live_handshake` → `manifest_signature` | `validate_signed_manifest_response(..., verify_signature=True)` raises `SignatureVerificationError` | Ed25519 over JCS-canonical inner `manifest` verifies with upstream `asap` crypto | C-side RFC 8785 JCS subset (`src/crypto/jcs.c`) + TweetNaCl sign path not yet byte-identical with Python verifier used by harness; C unit tests round-trip locally | **v1.0.1+** — align JCS + signing with upstream reference; keep `tests/test_manifest.c` + `scripts/validate_manifest.sh` | -| `test_live_handshake` → `version_reported` | Skipped (manifest not trusted) | ASAP protocol version compatibility check after manifest parse | Cascades from `manifest_signature` failure | **v1.0.1+** — after signature fix | -| `test_live_state_machine` → `state_agent_response` | `POST /asap` → HTTP **400** (`Invalid params: missing or bad type for 'id'`) | HTTP **200** JSON-RPC result with `task.response` envelope | Harness sends `params.envelope` + `idempotency_key` (no top-level envelope `id` in nested object); ShellClaw `asap_envelope_parse` reads **flat** envelope fields directly under `params` (legacy client shape in `asap_envelope_to_jsonrpc_request`) | **v1.0.1+** — accept `params.envelope`, generate/validate envelope `id`, implement compliance `echo` skill (or map harness skill id) | -| `test_live_sla` → `sla_task_timeout` | `POST /asap` → HTTP **400** (same as state) | HTTP **200** within SLA window for `sla_skill_id` (`echo`) | Same JSON-RPC `params` shape mismatch; SLA cannot reach agent handler | **v1.0.1+** — same as state machine row | -| `test_live_sla` → `sla_progress_schema` | Passed (static schema check) | Valid `TaskUpdate` progress schema | Does not require live agent success | No change for v1.0 | -| Gateway `GET /health` (script preflight only) | `{"status":"ok","uptime":…,"version":"…"}` (gateway build label) | Not used by harness (harness uses `/.well-known/asap/health` only) | Separate ShellClaw gateway health route; harmless for harness | Optional alignment in v1.0.1+ if operators want one schema everywhere | - -**Note:** `/api/status` and provider health are out of scope for the ASAP harness; only well-known ASAP paths and `POST /asap` are tested. - -### Static manifest vs live compliance - -IssueOps registration (task 6.3) intentionally uses **static** manifest URL with `online_check: false` so the marketplace does not run Compliance Harness v2 against a live endpoint. Local `./scripts/run_asap_compliance.sh` is for **pre-release iteration** on a dev gateway; a green run is **not** a v1.0 release gate. - ---- - -## Related docs +For a running test gateway, use `ASAP_COMPLIANCE_SKIP_PIP=1 ./scripts/run_asap_compliance.sh http://127.0.0.1:18789`. The upstream validator sends from `urn:asap:agent:compliance-harness` to `urn:asap:agent:under-test`. Set those identities in the test gateway configuration. -| Doc | Topic | -|-----|-------| -| [ARCHITECTURE.md](ARCHITECTURE.md) | Module map, gateway, thread safety | -| [SECURITY.md](SECURITY.md) | Key file permissions, gateway auth | -| [LOCAL_INFERENCE.md](LOCAL_INFERENCE.md) | llama-server (out of ASAP scope) | -| [issueops/register-agent-prefill.md](issueops/register-agent-prefill.md) | Copy-paste IssueOps values | -| [MARKETPLACE_STATUS.md](MARKETPLACE_STATUS.md) | Operator checklist tracking | +The marketplace entry uses a static signed manifest. The CI checks exercise the local gateway. diff --git a/scripts/run_asap_ci.py b/scripts/run_asap_ci.py new file mode 100644 index 00000000..86e7519e --- /dev/null +++ b/scripts/run_asap_ci.py @@ -0,0 +1,66 @@ +"""Start a local gateway and run the ASAP compliance checks.""" + +import os +from pathlib import Path +import socket +import subprocess +import sys +import tempfile +import time +from urllib.error import URLError +from urllib.request import ProxyHandler, build_opener + +ROOT = Path(__file__).resolve().parents[1] + + +def wait_for_gateway(process: subprocess.Popen, url: str) -> None: + opener = build_opener(ProxyHandler({})) + deadline = time.monotonic() + 10 + while process.poll() is None and time.monotonic() < deadline: + try: + with opener.open(f"{url}/health", timeout=0.25) as response: + if response.status == 200: + return + except (URLError, TimeoutError): + time.sleep(0.05) + raise RuntimeError("The test gateway did not become ready") + + +def run(binary: Path) -> None: + fixture = ROOT / "tests/fixtures/ci_asap_test.toml" + with tempfile.TemporaryDirectory(prefix="shellclaw-asap-") as directory: + home = Path(directory) + (home / ".shellclaw").mkdir() + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + config = home / "config.toml" + config.write_text(fixture.read_text(encoding="utf-8").format(port=port), encoding="utf-8") + url = f"http://127.0.0.1:{port}" + # Use only fixture settings and an empty ShellClaw home. + gateway_env = {"HOME": str(home), "PATH": os.environ["PATH"]} + with subprocess.Popen( + [binary, "--config", config], cwd=home, env=gateway_env, + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, + ) as gateway: + try: + wait_for_gateway(gateway, url) + python_path = f"{Path(sys.executable).parent}{os.pathsep}{os.environ['PATH']}" + env = dict(os.environ, PATH=python_path, ASAP_COMPLIANCE_SKIP_PIP="1", + NO_PROXY="127.0.0.1", no_proxy="127.0.0.1") + env.setdefault("ASAP_COMPLIANCE_TIMEOUT", "5") + subprocess.run([ROOT / "scripts/run_asap_compliance.sh", url], env=env, check=True) + finally: + if gateway.poll() is None: + gateway.terminate() + try: + gateway.wait(timeout=2) + except subprocess.TimeoutExpired: + gateway.kill() + + +if __name__ == "__main__": + try: + run(Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else ROOT / "build/shellclaw") + except subprocess.CalledProcessError as error: + sys.exit(error.returncode) diff --git a/scripts/run_asap_compliance.sh b/scripts/run_asap_compliance.sh index fc0a2816..6a9bc89f 100755 --- a/scripts/run_asap_compliance.sh +++ b/scripts/run_asap_compliance.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Run the upstream asap-compliance pytest harness against a live ShellClaw gateway. # -# Deviations, v1.0 stance, and env reference: docs/ASAP.md § "ASAP compliance harness". +# See docs/ASAP.md § "ASAP compliance harness". # # Usage: # ./scripts/run_asap_compliance.sh @@ -12,22 +12,22 @@ # ASAP_AGENT_URL agent base URL (default: http://127.0.0.1:18789) # ASAP_COMPLIANCE_SKIP_PIP=1 skip pip install when asap-compliance is already installed # ASAP_COMPLIANCE_PIP_USER=1 use "pip install --user" (prints a note when set) -# ASAP_COMPLIANCE_VERSION pip spec (default: asap-compliance>=1.0.0) +# ASAP_COMPLIANCE_VERSION pip spec (default: asap-compliance==1.4.0) +# ASAP_COMPLIANCE_TIMEOUT HTTP timeout in seconds (default: 30) # ASAP_COMPLIANCE_SKIP_HEALTH=1 skip /health probe before pytest # ASAP_COMPLIANCE_LIVE_TEST_DIR directory for generated live pytest (default: temp) # # Prerequisites: python3 + pip (3.13+); gateway listening at ASAP_AGENT_URL (start shellclaw # with [gateway] enabled — see config.example.toml port 18789). This script does not -# boot the agent; use scripts/dump_manifest.sh if you need an ephemeral local gateway. +# start the agent. For an isolated gateway, use scripts/run_asap_ci.py. # # Exit codes: 0 pytest green, 1 usage/deps, 2 pip install failed, 3 agent unreachable, # 4 pytest failed. set -euo pipefail -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" DEFAULT_URL="http://127.0.0.1:18789" AGENT_URL="${ASAP_AGENT_URL:-${DEFAULT_URL}}" -PIP_SPEC="${ASAP_COMPLIANCE_VERSION:-asap-compliance>=1.0.0}" +PIP_SPEC="${ASAP_COMPLIANCE_VERSION:-asap-compliance==1.4.0}" usage() { sed -n '2,21p' "$0" | sed 's/^# \{0,1\}//' @@ -117,6 +117,7 @@ cat >"${LIVE_TEST_DIR}/test_shellclaw_live.py" <<'PY' from __future__ import annotations +import httpx import pytest from asap_compliance.validators.handshake import validate_handshake @@ -124,34 +125,59 @@ from asap_compliance.validators.sla import validate_sla from asap_compliance.validators.state import validate_state_machine +def check_result(result, required_check): + for check in result.checks: + print(f"{check.name}: {check.message}") + failed = [c for c in result.checks if not c.passed] + assert result.passed, ", ".join(f"{c.name}: {c.message}" for c in failed) + assert not failed + assert required_check in {c.name for c in result.checks} + + @pytest.mark.asap_compliance def test_live_handshake(compliance_harness) -> None: - result = validate_handshake(compliance_harness) - failed = [c for c in result.checks if not c.passed] - assert result.passed, "; ".join(f"{c.name}: {c.message}" for c in failed) + manifest_url = f"{compliance_harness.agent_url.rstrip('/')}/.well-known/asap/manifest.json" + response = httpx.get(manifest_url, timeout=compliance_harness.timeout_seconds) + response.raise_for_status() + signed = response.json() + assert signed.get("signature") and signed.get("public_key") + skills = signed["manifest"]["capabilities"]["skills"] + assert sum(skill["id"] == "echo" for skill in skills) == 1 + check_result(validate_handshake(compliance_harness), "manifest_signature") @pytest.mark.asap_compliance def test_live_state_machine(compliance_harness) -> None: - result = validate_state_machine(compliance_harness) - failed = [c for c in result.checks if not c.passed] - assert result.passed, "; ".join(f"{c.name}: {c.message}" for c in failed) + check_result(validate_state_machine(compliance_harness), "state_terminal_status") @pytest.mark.asap_compliance def test_live_sla(compliance_harness) -> None: - result = validate_sla(compliance_harness) - failed = [c for c in result.checks if not c.passed] - assert result.passed, "; ".join(f"{c.name}: {c.message}" for c in failed) + assert not compliance_harness.skip_checks + check_result(validate_sla(compliance_harness), "sla_task_timeout") PY echo "==> pytest asap-compliance (-m asap_compliance) against ${AGENT_URL}" # Upstream CLI: pytest --asap-agent-url= -m asap_compliance (PyPI wheel ships library only). python3 -m pytest \ --asap-agent-url="${AGENT_URL}" \ - -m asap_compliance \ - -v \ - "${LIVE_TEST_DIR}" \ + --asap-timeout="${ASAP_COMPLIANCE_TIMEOUT:-30}" \ + -m asap_compliance -v -rP \ + --junitxml="${LIVE_TEST_DIR}/shellclaw-compliance.xml" \ + "${LIVE_TEST_DIR}/test_shellclaw_live.py" \ || exit 4 +python3 - "${LIVE_TEST_DIR}/shellclaw-compliance.xml" <<'PY' || exit 4 +import sys +from xml.etree import ElementTree + +cases = ElementTree.parse(sys.argv[1]).findall(".//testcase") +expected = {"test_live_handshake", "test_live_state_machine", "test_live_sla"} +if len(cases) != len(expected) or {case.get("name") for case in cases} != expected: + sys.exit("The three compliance tests must all run") +outcomes = {child.tag for case in cases for child in case} +if outcomes & {"failure", "error", "skipped"}: + sys.exit("The three compliance tests must all pass") +PY + echo "==> run_asap_compliance: all checks passed" diff --git a/tests/fixtures/ci_asap_test.toml b/tests/fixtures/ci_asap_test.toml index 652d1140..0edb4331 100644 --- a/tests/fixtures/ci_asap_test.toml +++ b/tests/fixtures/ci_asap_test.toml @@ -1,17 +1,23 @@ -# Minimal config for CI asap-compliance check. -# Used by the asap-compliance harness step in .github/workflows/ci.yml. +# run_asap_ci.py supplies the loopback port for each run. [agent] -model = "claude-3-5-sonnet-20241022" -max_tokens = 512 -max_tool_iterations = 5 +model = "asap-test" + +[providers] +fallback_chain = ["stub"] [gateway] enabled = true host = "127.0.0.1" -port = 19999 +port = {port} +require_pairing = true [asap] enabled = true -agent_urn = "urn:asap:agent:shellclaw-ci" +agent_urn = "urn:asap:agent:under-test" agent_name = "ShellClaw-CI" +public_base_url = "http://127.0.0.1:{port}" +trusted_senders = ["urn:asap:agent:compliance-harness"] + +[hardware] +enabled = false From 680d1d876036831b620b362df95030e3c398ead8 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:56:37 -0300 Subject: [PATCH 04/10] fix(asap): decode SDK request compression --- .github/workflows/ci.yml | 2 +- .github/workflows/publish-manifest.yml | 4 +- Makefile | 6 +- README.md | 2 +- scripts/ci-local.sh | 2 +- src/gateway/asap_http_body.c | 78 ++++++++++++++++++++++++++ src/gateway/asap_http_body.h | 9 +++ src/gateway/routes.c | 26 ++++++++- 8 files changed, 119 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 227d41c4..ca1dca8c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ jobs: - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libgpiod-dev i2c-tools cppcheck lcov nodejs + sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libbrotli-dev zlib1g-dev libgpiod-dev i2c-tools cppcheck lcov nodejs - name: Static analysis (cppcheck) run: make static diff --git a/.github/workflows/publish-manifest.yml b/.github/workflows/publish-manifest.yml index 27afafa1..7d375d81 100644 --- a/.github/workflows/publish-manifest.yml +++ b/.github/workflows/publish-manifest.yml @@ -45,7 +45,7 @@ jobs: - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libgpiod-dev + sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libbrotli-dev zlib1g-dev libgpiod-dev - name: Build shellclaw (gateway) run: make clean && GATEWAY=1 make shellclaw @@ -99,7 +99,7 @@ jobs: - name: Install dependencies run: | sudo apt-get update - sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libgpiod-dev + sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libbrotli-dev zlib1g-dev libgpiod-dev - name: Build shellclaw (gateway) run: make clean && GATEWAY=1 make shellclaw diff --git a/Makefile b/Makefile index aaef1aec..5acf7ac7 100644 --- a/Makefile +++ b/Makefile @@ -6,13 +6,15 @@ DSYMDIR ?= tests-dSYM INC := -I. -I tests -I src -I vendor/tomlc99 -I vendor/sqlite3 -I vendor/cJSON -Isrc/vendor/tweetnacl LDLIBS := -lcurl -lm # Gateway (Phase 2): libwebsockets for HTTP+WebSocket on same port -# Install: brew install libwebsockets +# Install: brew install libwebsockets brotli zlib # Set GATEWAY=0 to build without gateway when libwebsockets not installed GATEWAY ?= $(shell pkg-config --exists libwebsockets 2>/dev/null && echo 1 || echo 0) GATEWAY_CFLAGS := $(if $(filter 1,$(GATEWAY)),$(shell pkg-config --cflags libwebsockets 2>/dev/null),) GATEWAY_CFLAGS += $(if $(filter 1,$(GATEWAY)),$(shell pkg-config --cflags openssl 2>/dev/null),) +GATEWAY_CFLAGS += $(if $(filter 1,$(GATEWAY)),$(shell pkg-config --cflags libbrotlidec zlib),) GATEWAY_LDLIBS := $(if $(filter 1,$(GATEWAY)),$(shell pkg-config --libs libwebsockets 2>/dev/null),) GATEWAY_LDLIBS += $(if $(filter 1,$(GATEWAY)),$(shell pkg-config --libs openssl 2>/dev/null),) +GATEWAY_LDLIBS += $(if $(filter 1,$(GATEWAY)),$(shell pkg-config --libs libbrotlidec zlib),) # Hardware GPIO (Phase 5): libgpiod v2 API for Jetson / RPi (JetPack 6 / Bookworm) # Set LIBGPIOD=0 when libgpiod-dev is not installed (stub backend only). # pkg-config may find libgpiod 1.x on older distros; we require >= 2.0. @@ -379,7 +381,7 @@ $(HTTP_O): src/gateway/http.c src/gateway/http.h src/gateway/http_lws.h src/gate $(HTTP_LWS_O): src/gateway/http_lws.c src/gateway/http_lws.h src/gateway/asap_http_body.h src/gateway/routes.h src/gateway/auth.h src/gateway/static.h src/gateway/ws.h src/gateway/ws_rx.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/http_lws.c -$(ROUTES_O): src/gateway/routes.c src/gateway/routes.h src/gateway/routes_hardware.h src/gateway/http.h src/gateway/http_lws.h src/gateway/auth.h src/gateway/rate_limit.h src/tools/context.h src/asap/manifest.h src/asap/envelope.h src/asap/server.h src/asap/log.h src/core/bootstrap.h src/core/agent.h src/core/config.h src/core/config_patch.h src/core/dispatch.h src/core/reload.h src/core/memory.h src/core/skill.h src/providers/provider.h src/channels/channel.h src/tools/cron.h src/tools/tool.h +$(ROUTES_O): src/gateway/routes.c src/gateway/routes.h src/gateway/asap_http_body.h src/gateway/routes_hardware.h src/gateway/http.h src/gateway/http_lws.h src/gateway/auth.h src/gateway/rate_limit.h src/tools/context.h src/asap/manifest.h src/asap/envelope.h src/asap/server.h src/asap/log.h src/core/bootstrap.h src/core/agent.h src/core/config.h src/core/config_patch.h src/core/dispatch.h src/core/reload.h src/core/memory.h src/core/skill.h src/providers/provider.h src/channels/channel.h src/tools/cron.h src/tools/tool.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/routes.c $(ROUTES_HARDWARE_O): src/gateway/routes_hardware.c src/gateway/routes_hardware.h src/gateway/routes.h src/gateway/http_lws.h src/gateway/uri_match.h src/hardware/hardware.h src/hardware/hardware_gpio_snapshot.h src/hardware/hardware_tegrastats.h src/hardware/board_detect.h src/core/config.h diff --git a/README.md b/README.md index bbc1cf59..21de122d 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ ShellClaw is **not another OpenClaw clone** in a different language. It is a **h See [CONTRIBUTING.md](CONTRIBUTING.md) for PR workflow, coding standards, and the pre-tag `gpio-mockup` release ritual. -**Configuration:** copy [`config.example.toml`](config.example.toml) to `~/.shellclaw/config.toml` and [`.env.example`](.env.example) to `.env`. Phase 3+ keys (ASAP, sandbox, gateway) and the Jetson `[hardware]` block are documented there. Install **libwebsockets** (`pkg-config` must find it) to build the gateway and run `GATEWAY=1 make test_gateway_http`. +**Configuration:** copy [`config.example.toml`](config.example.toml) to `~/.shellclaw/config.toml` and [`.env.example`](.env.example) to `.env`. Phase 3+ keys (ASAP, sandbox, gateway) and the Jetson `[hardware]` block are documented there. Install libwebsockets, Brotli, and zlib to build the gateway. Make sure that `pkg-config` finds `libwebsockets`, `libbrotlidec`, and `zlib`. Run `GATEWAY=1 make test_gateway_http` to test the gateway. **Jetson install (v1.0):** `./scripts/install.sh`, `./scripts/build_llama_jetson.sh`, `./scripts/download_model.sh phi3` — details in [`docs/HARDWARE_JETSON.md`](docs/HARDWARE_JETSON.md) and [`docs/LOCAL_INFERENCE.md`](docs/LOCAL_INFERENCE.md). diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 7190c97f..80ff3b09 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -8,7 +8,7 @@ export GATEWAY=1 if command -v apt-get >/dev/null 2>&1; then echo "==> apt-get (CI deps incl. libgpiod-dev >= 2.x, i2c-tools; use Ubuntu 24.04+)" sudo apt-get update - sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libgpiod-dev i2c-tools cppcheck lcov nodejs + sudo apt-get install -y build-essential libcurl4-openssl-dev libwebsockets-dev libbrotli-dev zlib1g-dev libgpiod-dev i2c-tools cppcheck lcov nodejs fi echo "==> cppcheck (make static)" make static diff --git a/src/gateway/asap_http_body.c b/src/gateway/asap_http_body.c index 46f7475e..041b948b 100644 --- a/src/gateway/asap_http_body.c +++ b/src/gateway/asap_http_body.c @@ -6,10 +6,13 @@ #include "gateway/asap_http_body.h" #include "gateway/uri_match.h" +#include #include #include #include #include +#include +#include static int asap_is_asap_post(struct lws *wsi) { @@ -80,6 +83,81 @@ int asap_http_body_init_from_request(struct lws *wsi, asap_http_body_t *body) return 0; } +static int decode_gzip(const char *body, size_t len, char *decoded, size_t *decoded_len) +{ + z_stream stream = {0}; + int rc = inflateInit2(&stream, MAX_WBITS + 16); /* Require a gzip header. */ + if (rc != Z_OK) + return 500; + stream.next_in = (z_const Bytef *)body; + stream.avail_in = (uInt)len; + stream.next_out = (Bytef *)decoded; + stream.avail_out = ASAP_BODY_MAX + 1; + rc = inflate(&stream, Z_FINISH); + *decoded_len = stream.total_out; + int status = 400; + if (stream.total_out > ASAP_BODY_MAX) + status = 413; + else if (rc == Z_STREAM_END && stream.avail_in == 0) + status = 0; + else if (rc == Z_MEM_ERROR) + status = 500; + inflateEnd(&stream); + return status; +} + +static int decode_brotli(const char *body, size_t len, char *decoded, size_t *decoded_len) +{ + BrotliDecoderState *state = BrotliDecoderCreateInstance(NULL, NULL, NULL); + if (!state) + return 500; + const uint8_t *input = (const uint8_t *)body; + uint8_t *output = (uint8_t *)decoded; + size_t space = ASAP_BODY_MAX + 1; + BrotliDecoderResult result = BrotliDecoderDecompressStream(state, + &len, &input, &space, &output, decoded_len); + BrotliDecoderDestroyInstance(state); + if (*decoded_len > ASAP_BODY_MAX || result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) + return 413; + return result == BROTLI_DECODER_RESULT_SUCCESS && len == 0 ? 0 : 400; +} + +int asap_http_body_decode(struct lws *wsi, const char *body, size_t len, + char **decoded, size_t *decoded_len) +{ + char encoding[32]; + *decoded = NULL; + *decoded_len = len; + if (len > ASAP_BODY_MAX) + return 413; + if (!wsi || lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_ENCODING) <= 0) + return 0; + if (lws_hdr_copy(wsi, encoding, sizeof encoding, WSI_TOKEN_HTTP_CONTENT_ENCODING) <= 0) + return 415; + char *coding = encoding + strspn(encoding, " \t"); + size_t coding_len = strlen(coding); + while (coding_len > 0 && (coding[coding_len - 1] == ' ' || coding[coding_len - 1] == '\t')) + coding[--coding_len] = '\0'; + if (strcasecmp(coding, "identity") == 0) + return 0; + int gzip = strcasecmp(coding, "gzip") == 0; + if (!gzip && strcasecmp(coding, "br") != 0) + return 415; + + char *output = malloc(ASAP_BODY_MAX + 1); + if (!output) + return 500; + int status = gzip ? decode_gzip(body, len, output, decoded_len) + : decode_brotli(body, len, output, decoded_len); + if (status == 0) { + output[*decoded_len] = '\0'; + *decoded = output; + } else { + free(output); + } + return status; +} + void asap_http_body_append(asap_http_body_t *body, const void *in, size_t len) { if (!body || !in || len == 0) diff --git a/src/gateway/asap_http_body.h b/src/gateway/asap_http_body.h index 7728866b..1540ec1d 100644 --- a/src/gateway/asap_http_body.h +++ b/src/gateway/asap_http_body.h @@ -49,6 +49,15 @@ int asap_http_body_exceeds_static_cap(const asap_http_body_t *body, long content */ int asap_http_body_init_from_request(struct lws *wsi, asap_http_body_t *body); +/** + * Decode the Content-Encoding of a POST /asap request. + * @param decoded Receives an owned buffer, or NULL for an identity body. + * @param decoded_len Receives the length of the decoded bytes on success. + * @return 0 on success, or HTTP 400, 413, 415, or 500 on failure. + */ +int asap_http_body_decode(struct lws *wsi, const char *body, size_t len, + char **decoded, size_t *decoded_len); + void asap_http_body_append(asap_http_body_t *body, const void *in, size_t len); void asap_http_body_free(asap_http_body_t *body); diff --git a/src/gateway/routes.c b/src/gateway/routes.c index 1a6563a9..0805d3f3 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -8,6 +8,7 @@ #include "gateway/routes_hardware.h" #include "gateway/http.h" #include "gateway/auth.h" +#include "gateway/asap_http_body.h" #include "gateway/rate_limit.h" #include "channels/channel.h" #include "asap/manifest.h" @@ -804,7 +805,7 @@ static int write_asap_jsonrpc(char *buf, size_t size, int *status, char *resp_js return 0; } -static void handle_asap(http_server_ctx_t *ctx, const char *client_ip, +static void handle_asap(http_server_ctx_t *ctx, struct lws *wsi, const char *client_ip, const char *body, size_t body_len, char *buf, size_t size, int *status) { asap_envelope_t in; @@ -814,13 +815,32 @@ static void handle_asap(http_server_ctx_t *ctx, const char *client_ip, char err_msg[256]; char *snippet; int rc; - (void)body_len; if (rate_limit_asap(client_ip, time(NULL))) { jsonrpc_error(buf, size, status, 429, -32000, "rate limit exceeded", NULL); return; } + char *decoded = NULL; + size_t decoded_len; + int decode_status = asap_http_body_decode(wsi, body, body_len, &decoded, &decoded_len); + if (decode_status != 0) { + const char *message = "Cannot decode request body"; + if (decode_status == 413) + message = "Decoded request body too large"; + else if (decode_status == 415) + message = "Unsupported Content-Encoding"; + jsonrpc_error(buf, size, status, decode_status, + decode_status == 500 ? -32603 : -32700, message, NULL); + return; + } + body = decoded ? decoded : body; asap_envelope_init(&in); + if (!body || memchr(body, '\0', decoded_len)) { + jsonrpc_error(buf, size, status, 400, -32700, "Parse error", NULL); + free(decoded); + return; + } rc = asap_envelope_parse(body, &in, &parse_err); + free(decoded); if (rc != 0) { write_asap_error(buf, size, status, 400, parse_err); asap_envelope_clear(&in); @@ -1088,7 +1108,7 @@ int dispatch_route(http_server_ctx_t *ctx, struct lws *wsi, int method, if (uri_exact_eq(uri, uri_len, "/asap") && method == HTTP_POST) { char client_ip[64] = {0}; lws_get_peer_simple(wsi, client_ip, sizeof client_ip); - handle_asap(ctx, client_ip, body, body_len, buf, size, status); + handle_asap(ctx, wsi, client_ip, body, body_len, buf, size, status); return 0; } json_error(buf, size, status, 404, "Not found"); From 22d8793b4f9c7d865dba1f228ea205619a570091 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:56:37 -0300 Subject: [PATCH 05/10] fix(asap): preserve JSON-RPC IDs and Echo values --- src/asap/envelope.c | 179 +++++++++++++++++++++++++++++++++++++++---- src/asap/envelope.h | 25 ++++++ src/gateway/routes.c | 37 +++++---- 3 files changed, 210 insertions(+), 31 deletions(-) diff --git a/src/asap/envelope.c b/src/asap/envelope.c index 019b3d7c..7eddf95c 100644 --- a/src/asap/envelope.c +++ b/src/asap/envelope.c @@ -378,25 +378,170 @@ int asap_envelope_parse_jsonrpc_response(const char *json, asap_envelope_t *out, } } -int asap_envelope_parse(const char *json, asap_envelope_t *out, cJSON **err_out) +static const char *json_string_end(const char *text) +{ + if (*text != '"') + return NULL; + for (text++; *text && *text != '"'; text++) { + if ((unsigned char)*text < 0x20) + return NULL; + if (*text == '\\' && !*++text) + return NULL; + } + return *text == '"' ? text + 1 : NULL; +} + +static const char *json_number_end(const char *text) +{ + static const char digits[] = "0123456789"; + text += (*text == '-'); + size_t count = strspn(text, digits); + if (count == 0 || (count > 1 && *text == '0')) + return NULL; + text += count; + if (*text == '.') { + count = strspn(++text, digits); + if (count == 0) + return NULL; + text += count; + } + if (*text == 'e' || *text == 'E') { + text++; + text += (*text == '+' || *text == '-'); + count = strspn(text, digits); + if (count == 0) + return NULL; + text += count; + } + return text; +} + +static const char *json_skip_space(const char *text) +{ + return text + strspn(text, " \r\n\t"); +} + +/* Match source values to the tree that cJSON already parsed. Check token + * boundaries before a source value can appear in a response. */ +static const char *capture_wire_values(const char *text, const cJSON *item, + const cJSON *id, const cJSON *echo_input, asap_request_wire_t *wire) +{ + const char *start = json_skip_space(text); + text = start; + if (cJSON_IsObject(item) || cJSON_IsArray(item)) { + int object = cJSON_IsObject(item); + if (*text != (object ? '{' : '[')) + return NULL; + text = json_skip_space(text + 1); + const cJSON *child; + cJSON_ArrayForEach(child, item) { + if (object) { + if (!(text = json_string_end(text))) + return NULL; + text = json_skip_space(text); + if (*text++ != ':') + return NULL; + } + text = capture_wire_values(text, child, id, echo_input, wire); + if (!text) + return NULL; + text = json_skip_space(text); + if (child->next) { + if (*text++ != ',') + return NULL; + text = json_skip_space(text); + } + } + if (*text++ != (object ? '}' : ']')) + return NULL; + } else if (cJSON_IsNumber(item)) { + text = json_number_end(text); + } else if (cJSON_IsString(item)) { + text = json_string_end(text); + } else { + const char *literal = cJSON_IsNull(item) ? "null" : cJSON_IsTrue(item) ? "true" : "false"; + size_t len = strlen(literal); + if (strncmp(text, literal, len) != 0) + return NULL; + text += len; + } + if (!text) + return NULL; + if (item == id) + wire->id = (asap_json_span_t){start, (size_t)(text - start)}; + if (item == echo_input) + wire->echo_input = (asap_json_span_t){start, (size_t)(text - start)}; + return text; +} + +static int capture_request_wire(const char *json, cJSON *root, cJSON *id, + cJSON *nested, asap_request_wire_t *wire) +{ + const cJSON *payload = cJSON_GetObjectItemCaseSensitive(nested, "payload"); + const cJSON *input = cJSON_GetObjectItemCaseSensitive(payload, "input"); + if (strncmp(json, "\xef\xbb\xbf", 3) == 0) + json += 3; + const char *end = capture_wire_values(json, root, id, input, wire); + return end && *json_skip_space(end) == '\0'; +} + +static int replace_wire_value(cJSON *object, const char *key, asap_json_span_t span) +{ + char *value = strndup(span.start, span.len); + if (!value) + return 0; + cJSON *raw = cJSON_CreateRaw(value); + free(value); + if (!raw) + return 0; + if (!cJSON_ReplaceItemInObjectCaseSensitive(object, key, raw)) { + cJSON_Delete(raw); + return 0; + } + return 1; +} + +char *asap_jsonrpc_print_response(cJSON *response, const asap_request_wire_t *wire) +{ + if (!response) + return NULL; + if (wire && wire->id.start && !replace_wire_value(response, "id", wire->id)) + return NULL; + cJSON *result = cJSON_GetObjectItemCaseSensitive(response, "result"); + if (wire && wire->echo_input.start && result) { + cJSON *envelope = cJSON_GetObjectItemCaseSensitive(result, "envelope"); + cJSON *payload = cJSON_GetObjectItemCaseSensitive(envelope, "payload"); + if (!replace_wire_value(payload, "result", wire->echo_input)) + return NULL; + } + return cJSON_PrintUnformatted(response); +} + +int asap_envelope_parse_request(const char *json, asap_envelope_t *out, + cJSON **err_out, asap_request_wire_t *wire) { if (err_out) *err_out = NULL; + if (wire) memset(wire, 0, sizeof(*wire)); if (!json || !out) return -1; asap_envelope_init(out); cJSON *root = cJSON_Parse(json); - if (!root) { - if (err_out) { - cJSON *null_id = cJSON_CreateNull(); - if (null_id) { - *err_out = asap_jsonrpc_error(-32700, "Parse error", null_id); - cJSON_Delete(null_id); - } - } + cJSON *request_id = cJSON_GetObjectItemCaseSensitive(root, "id"); + cJSON *jrpc = cJSON_GetObjectItemCaseSensitive(root, "jsonrpc"); + cJSON *meth = cJSON_GetObjectItemCaseSensitive(root, "method"); + cJSON *params = cJSON_GetObjectItemCaseSensitive(root, "params"); + cJSON *nested = cJSON_GetObjectItemCaseSensitive(params, "envelope"); + int sdk_wire = cJSON_IsObject(params) && nested && cJSON_IsString(meth) && + strcmp(meth->valuestring, "asap.send") == 0; + if (!root || (wire && !capture_request_wire(json, root, request_id, sdk_wire ? nested : NULL, wire))) { + if (wire) memset(wire, 0, sizeof(*wire)); + if (err_out) + *err_out = asap_jsonrpc_error(-32700, "Parse error", NULL); + cJSON_Delete(root); return -1; } - cJSON *request_id = cJSON_GetObjectItemCaseSensitive(root, "id"); if (request_id && !cJSON_IsString(request_id) && !cJSON_IsNumber(request_id) && !cJSON_IsNull(request_id)) { + if (wire) memset(wire, 0, sizeof(*wire)); if (err_out) *err_out = asap_jsonrpc_error(-32600, "Invalid JSON-RPC request ID", NULL); cJSON_Delete(root); @@ -407,27 +552,24 @@ int asap_envelope_parse(const char *json, asap_envelope_t *out, cJSON **err_out) cJSON_Delete(root); return -1; } - cJSON *jrpc = cJSON_GetObjectItemCaseSensitive(root, "jsonrpc"); if (!cJSON_IsString(jrpc) || !jrpc->valuestring || strcmp(jrpc->valuestring, "2.0") != 0) { cJSON_Delete(root); return parse_fail(out, rpc_id, err_out, "Invalid Request: jsonrpc must be \"2.0\""); } - cJSON *meth = cJSON_GetObjectItemCaseSensitive(root, "method"); if (!cJSON_IsString(meth) || !meth->valuestring || meth->valuestring[0] == '\0') { cJSON_Delete(root); return parse_fail(out, rpc_id, err_out, "Invalid Request: method must be a non-empty string"); } - cJSON *params = cJSON_GetObjectItemCaseSensitive(root, "params"); if (!params || !cJSON_IsObject(params)) { cJSON_Delete(root); return parse_fail(out, rpc_id, err_out, "Invalid Request: params must be an object"); } - cJSON *nested = cJSON_GetObjectItemCaseSensitive(params, "envelope"); - if (nested && (!cJSON_IsObject(nested) || strcmp(meth->valuestring, "asap.send") != 0)) { + if (wire) wire->sdk_wire = sdk_wire; + if (nested && (!cJSON_IsObject(nested) || !sdk_wire)) { cJSON_Delete(root); return parse_fail(out, rpc_id, err_out, "Invalid SDK request"); } - if (envelope_from_object(nested ? nested : params, rpc_id, out, err_out, nested != NULL) != 0) { + if (envelope_from_object(nested ? nested : params, rpc_id, out, err_out, sdk_wire) != 0) { cJSON_Delete(root); return -1; } @@ -435,3 +577,8 @@ int asap_envelope_parse(const char *json, asap_envelope_t *out, cJSON **err_out) cJSON_Delete(root); return 0; } + +int asap_envelope_parse(const char *json, asap_envelope_t *out, cJSON **err_out) +{ + return asap_envelope_parse_request(json, out, err_out, NULL); +} diff --git a/src/asap/envelope.h b/src/asap/envelope.h index 6f8e55ca..6225e09a 100644 --- a/src/asap/envelope.h +++ b/src/asap/envelope.h @@ -65,6 +65,31 @@ void asap_envelope_clear(asap_envelope_t *env); */ int asap_envelope_parse(const char *json, asap_envelope_t *out, cJSON **err_out); +typedef struct asap_json_span { + const char *start; + size_t len; +} asap_json_span_t; + +typedef struct asap_request_wire { + asap_json_span_t id; + asap_json_span_t echo_input; + int sdk_wire; +} asap_request_wire_t; + +/** + * Parse an HTTP request and record the original ID and Echo input. + * The spans borrow bytes from @p json. Keep the body until the response is printed. + */ +int asap_envelope_parse_request(const char *json, asap_envelope_t *out, + cJSON **err_out, asap_request_wire_t *wire); + +/** + * Insert the request's exact ID and Echo input before printing a response. + * This changes @p response. The caller owns the returned string. + */ +char *asap_jsonrpc_print_response(cJSON *response, const asap_request_wire_t *wire); + + /** * Load envelope fields from a plain JSON object (same key layout as * JSON-RPC @c params / @c result). Used for result bodies and tests. diff --git a/src/gateway/routes.c b/src/gateway/routes.c index 0805d3f3..951f65fb 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -697,9 +697,10 @@ static void handle_cron_toggle(const char *id, char *buf, size_t size, int *stat json_response(buf, size, status, "{\"ok\":true}"); } -static void write_asap_error(char *buf, size_t size, int *status, int http_code, cJSON *error) +static void write_asap_error(char *buf, size_t size, int *status, int http_code, + cJSON *error, const asap_request_wire_t *wire) { - char *json = error ? cJSON_PrintUnformatted(error) : NULL; + char *json = asap_jsonrpc_print_response(error, wire); cJSON_Delete(error); *status = http_code; if (json && strlen(json) < size) @@ -711,9 +712,9 @@ static void write_asap_error(char *buf, size_t size, int *status, int http_code, } static void jsonrpc_error(char *buf, size_t size, int *status, - int http_code, int rpc_code, const char *msg, cJSON *id) + int http_code, int rpc_code, const char *msg, const asap_request_wire_t *wire) { - write_asap_error(buf, size, status, http_code, asap_jsonrpc_error(rpc_code, msg, id)); + write_asap_error(buf, size, status, http_code, asap_jsonrpc_error(rpc_code, msg, NULL), wire); } static void handle_asap_log_get(char *buf, size_t size, int *status) @@ -785,7 +786,8 @@ static void asap_ctx_bind_bootstrap(asap_server_ctx_t *asap_ctx, const config_t * Takes ownership of @p resp_json. * @return 0 if copied, -1 if rejected as too large. */ -static int write_asap_jsonrpc(char *buf, size_t size, int *status, char *resp_json, cJSON *id) +static int write_asap_jsonrpc(char *buf, size_t size, int *status, char *resp_json, + const asap_request_wire_t *wire) { size_t rlen; rlen = strlen(resp_json); @@ -795,7 +797,7 @@ static int write_asap_jsonrpc(char *buf, size_t size, int *status, char *resp_js "ASAP response length %zu exceeds gateway buffer %zu", rlen, size); free(resp_json); - jsonrpc_error(buf, size, status, 500, -32603, too_big, id); + jsonrpc_error(buf, size, status, wire->sdk_wire ? 200 : 500, -32603, too_big, wire); return -1; } *status = 200; @@ -811,6 +813,7 @@ static void handle_asap(http_server_ctx_t *ctx, struct lws *wsi, const char *cli asap_envelope_t in; asap_envelope_t out; asap_server_ctx_t asap_ctx; + asap_request_wire_t wire; cJSON *parse_err = NULL; char err_msg[256]; char *snippet; @@ -839,11 +842,11 @@ static void handle_asap(http_server_ctx_t *ctx, struct lws *wsi, const char *cli free(decoded); return; } - rc = asap_envelope_parse(body, &in, &parse_err); - free(decoded); + rc = asap_envelope_parse_request(body, &in, &parse_err, &wire); if (rc != 0) { - write_asap_error(buf, size, status, 400, parse_err); + write_asap_error(buf, size, status, wire.sdk_wire ? 200 : 400, parse_err, &wire); asap_envelope_clear(&in); + free(decoded); return; } snippet = in.payload ? cJSON_PrintUnformatted(in.payload) : NULL; @@ -858,14 +861,17 @@ static void handle_asap(http_server_ctx_t *ctx, struct lws *wsi, const char *cli rc = asap_server_handle(&in, &out, &asap_ctx, err_msg, sizeof err_msg); } if (rc != 0) { - jsonrpc_error(buf, size, status, 400, rc, err_msg[0] ? err_msg : "Handler error", - in.jsonrpc_request_id); + int http_status = wire.sdk_wire && rc != ASAP_SERVER_RPC_SENDER_UNTRUSTED ? 200 : 400; + jsonrpc_error(buf, size, status, http_status, rc, + err_msg[0] ? err_msg : "Handler error", &wire); } else { - char *resp_json = asap_envelope_to_jsonrpc_string(&out, in.jsonrpc_request_id); + cJSON *response = asap_envelope_to_jsonrpc(&out, NULL); + char *resp_json = asap_jsonrpc_print_response(response, &wire); + cJSON_Delete(response); if (!resp_json) { - jsonrpc_error(buf, size, status, 500, -32603, "Cannot serialize response", - in.jsonrpc_request_id); - } else if (write_asap_jsonrpc(buf, size, status, resp_json, in.jsonrpc_request_id) == 0) { + jsonrpc_error(buf, size, status, wire.sdk_wire ? 200 : 500, -32603, + "Cannot serialize response", &wire); + } else if (write_asap_jsonrpc(buf, size, status, resp_json, &wire) == 0) { snippet = cJSON_PrintUnformatted(out.payload); asap_log_append_out(out.payload_type, out.id, snippet); free(snippet); @@ -873,6 +879,7 @@ static void handle_asap(http_server_ctx_t *ctx, struct lws *wsi, const char *cli } asap_envelope_clear(&in); asap_envelope_clear(&out); + free(decoded); } static void handle_well_known(http_server_ctx_t *ctx, const char *uri, int uri_len, From eb4bdda455346657a5b20407d021ec7eff3b5bf2 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:56:37 -0300 Subject: [PATCH 06/10] test(asap): check live gateway with the official SDK --- .github/workflows/ci.yml | 2 +- scripts/check_asap_sdk.py | 148 ++++++++++++++++++++++++++++++++++++++ scripts/run_asap_ci.py | 25 +++++-- 3 files changed, 167 insertions(+), 8 deletions(-) create mode 100644 scripts/check_asap_sdk.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca1dca8c..8c2aacc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,7 +60,7 @@ jobs: with: python-version: "3.14" - - name: Check ASAP compliance against a live gateway + - name: Check ASAP compliance and SDK interoperability run: | python3 -m pip install 'asap-compliance==1.4.0' 'asap-protocol==2.6.0' python3 scripts/run_asap_ci.py build/shellclaw diff --git a/scripts/check_asap_sdk.py b/scripts/check_asap_sdk.py new file mode 100644 index 00000000..22768794 --- /dev/null +++ b/scripts/check_asap_sdk.py @@ -0,0 +1,148 @@ +"""Exercise ShellClaw with the official SDK and check JSON-RPC on the wire.""" + +import asyncio +from decimal import Decimal +import json +import sys +import unittest +from unittest.mock import patch + +import httpx +from asap.errors import RemoteRPCError +from asap.models.envelope import Envelope +from asap.models.payloads import TaskRequest +from asap.transport.client import ASAPClient + +SENDER = "urn:asap:agent:compliance-harness" +AGENT = "urn:asap:agent:under-test" +FIRST_ID = 5000000000000001 +SECOND_ID = 9007199254740993 + + +def echo(input_data, recipient=AGENT): + return Envelope( + asap_version="0.1", + sender=SENDER, + recipient=recipient, + correlation_id="previous-request", + trace_id="sdk-ci-trace", + payload_type="TaskRequest", + payload=TaskRequest(conversation_id="sdk-ci", skill_id="echo", input=input_data), + ) + + +class SDKChecks(unittest.IsolatedAsyncioTestCase): + async def check_echo(self, request, encoding): + encodings = [] + + async def record_encoding(http_request): + encodings.append(http_request.headers.get("content-encoding")) + + async with ASAPClient(self.url, max_retries=1, require_https=False) as client: + client._client.event_hooks["request"].append(record_encoding) + response = await client.send(request) + + self.assertEqual(encodings, [encoding]) + self.assertEqual(response.payload.status, "completed") + self.assertEqual(response.payload.result, request.payload.input) + self.assertEqual(response.correlation_id, request.id) + self.assertEqual(response.payload.task_id, request.id) + self.assertEqual(response.trace_id, request.trace_id) + self.assertEqual(response.recipient, request.sender) + self.assertEqual(response.sender, request.recipient) + return response.payload.result + + async def test_identity_preserves_nested_numbers(self): + result = await self.check_echo(echo({ + "first": FIRST_ID, + "nested": [SECOND_ID, {"signed": -SECOND_ID, "float": 1.25, "bool": True}], + "escaped": "línea\x00with NUL", + }), None) + self.assertIs(type(result["first"]), int) + self.assertIs(type(result["nested"][0]), int) + self.assertIs(type(result["nested"][1]["bool"]), bool) + + async def test_default_brotli(self): + await self.check_echo(echo({"text": "Standard SDK compression. " * 90}), "br") + + async def test_default_gzip_without_brotli(self): + with patch("asap.transport.compression.is_brotli_available", return_value=False): + await self.check_echo(echo({"text": "Standard SDK compression. " * 90}), "gzip") + + async def test_invalid_recipient_is_remote_rpc_error(self): + async with ASAPClient(self.url, max_retries=1, require_https=False) as client: + request = echo({"text": "SDK error test"}, recipient="urn:asap:agent:other") + with self.assertRaises(RemoteRPCError) as caught: + await client.send(request) + self.assertEqual(caught.exception.json_rpc_code, -32602) + + async def test_exact_numeric_ids_on_success_and_parse_error(self): + envelope = echo({}).model_dump(mode="json") + async with httpx.AsyncClient(trust_env=False) as client: + request = {"jsonrpc": "2.0", "method": "asap.send", "id": FIRST_ID, + "params": {"envelope": envelope}} + response = await client.post(f"{self.url}/asap", json=request) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["id"], FIRST_ID) + self.assertIs(type(response.json()["id"]), int) + + request["id"] = SECOND_ID + request["params"] = {"envelope": {}} + response = await client.post(f"{self.url}/asap", json=request) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["error"]["code"], -32602) + self.assertEqual(response.json()["id"], SECOND_ID) + self.assertIs(type(response.json()["id"]), int) + + async def test_flat_http_contract(self): + async with httpx.AsyncClient(trust_env=False) as client: + request = { + "jsonrpc": "2.0", "method": "asap.send", "id": SECOND_ID, + "params": {"id": "legacy", "asap_version": "2.1", "sender": SENDER, + "recipient": AGENT, "payload_type": "task.cancel", "payload": {}}, + } + response = await client.post(f"{self.url}/asap", json=request) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["result"]["payload"]["cancelled"], False) + self.assertEqual(response.json()["id"], SECOND_ID) + + request["id"] = FIRST_ID + request["params"] = {} + response = await client.post(f"{self.url}/asap", json=request) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error"]["code"], -32602) + self.assertEqual(response.json()["id"], FIRST_ID) + + async def test_sender_rejection_keeps_http_status(self): + envelope = echo({}).model_dump(mode="json") + envelope["sender"] = "urn:asap:agent:untrusted" + async with httpx.AsyncClient(trust_env=False) as client: + response = await client.post(f"{self.url}/asap", json={ + "jsonrpc": "2.0", "method": "asap.send", "id": "sender-check", + "params": {"envelope": envelope}, + }) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error"]["code"], -32002) + self.assertEqual(response.json()["id"], "sender-check") + + async def test_decimal_tokens_in_echo_and_id(self): + request = { + "jsonrpc": "2.0", "method": "asap.send", "id": "RPC_ID", + "params": {"envelope": echo({"decimal": "INPUT"}).model_dump(mode="json")}, + } + rpc_id = "1.234567890123456789" + decimal = "-1.234567890123456789e-123" + content = json.dumps(request).replace('"RPC_ID"', rpc_id).replace('"INPUT"', decimal) + async with httpx.AsyncClient(trust_env=False) as client: + response = await client.post( + f"{self.url}/asap", content=content, headers={"Content-Type": "application/json"}, + ) + self.assertEqual(response.status_code, 200) + body = json.loads(response.content, parse_float=Decimal) + self.assertEqual(body["id"], Decimal(rpc_id)) + self.assertEqual(body["result"]["envelope"]["payload"]["result"]["decimal"], Decimal(decimal)) + + +if __name__ == "__main__": + SDKChecks.url = sys.argv.pop(1) + unittest.main(verbosity=2) diff --git a/scripts/run_asap_ci.py b/scripts/run_asap_ci.py index 86e7519e..3f814f0f 100644 --- a/scripts/run_asap_ci.py +++ b/scripts/run_asap_ci.py @@ -1,5 +1,7 @@ -"""Start a local gateway and run the ASAP compliance checks.""" +"""Start a local gateway and run the ASAP compliance and SDK checks.""" +from collections.abc import Iterator +from contextlib import contextmanager import os from pathlib import Path import socket @@ -26,7 +28,8 @@ def wait_for_gateway(process: subprocess.Popen, url: str) -> None: raise RuntimeError("The test gateway did not become ready") -def run(binary: Path) -> None: +@contextmanager +def running_gateway(binary: Path) -> Iterator[str]: fixture = ROOT / "tests/fixtures/ci_asap_test.toml" with tempfile.TemporaryDirectory(prefix="shellclaw-asap-") as directory: home = Path(directory) @@ -45,11 +48,7 @@ def run(binary: Path) -> None: ) as gateway: try: wait_for_gateway(gateway, url) - python_path = f"{Path(sys.executable).parent}{os.pathsep}{os.environ['PATH']}" - env = dict(os.environ, PATH=python_path, ASAP_COMPLIANCE_SKIP_PIP="1", - NO_PROXY="127.0.0.1", no_proxy="127.0.0.1") - env.setdefault("ASAP_COMPLIANCE_TIMEOUT", "5") - subprocess.run([ROOT / "scripts/run_asap_compliance.sh", url], env=env, check=True) + yield url finally: if gateway.poll() is None: gateway.terminate() @@ -59,6 +58,18 @@ def run(binary: Path) -> None: gateway.kill() +def run(binary: Path) -> None: + python_path = f"{Path(sys.executable).parent}{os.pathsep}{os.environ['PATH']}" + env = dict(os.environ, PATH=python_path, ASAP_COMPLIANCE_SKIP_PIP="1", + NO_PROXY="127.0.0.1", no_proxy="127.0.0.1") + env.setdefault("ASAP_COMPLIANCE_TIMEOUT", "5") + with running_gateway(binary) as url: + subprocess.run([ROOT / "scripts/run_asap_compliance.sh", url], env=env, check=True) + # Start a new gateway so the validators do not consume the SDK tests' rate limit. + with running_gateway(binary) as url: + subprocess.run([sys.executable, ROOT / "scripts/check_asap_sdk.py", url], env=env, check=True) + + if __name__ == "__main__": try: run(Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else ROOT / "build/shellclaw") From 53a67d345e3fcb63cd505b352990c86d55f8ff32 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:56:37 -0300 Subject: [PATCH 07/10] docs(asap): describe SDK transport and manifest skills --- docs/ASAP.md | 24 ++++++++++++++++-------- docs/issueops/VERIFY_MARKETPLACE.md | 2 +- docs/issueops/register-agent-prefill.md | 4 ++-- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/docs/ASAP.md b/docs/ASAP.md index 26a4178e..1bd6e4f5 100644 --- a/docs/ASAP.md +++ b/docs/ASAP.md @@ -16,7 +16,7 @@ When the gateway is enabled and signing keys load successfully, ShellClaw serves |-------|------|----------| | `GET /.well-known/asap/manifest.json` | Public | **SignedManifest** JSON (inner manifest + Ed25519 signature + public_key) | | `GET /.well-known/asap/health` | Public | Agent liveness, manifest identity and version, and gateway uptime | -| `POST /asap` | Rate-limited | Accepts flat legacy messages and SDK echo tasks. Requests have a 1 MiB limit. Responses that exceed the 64 KiB gateway buffer return HTTP 500 with JSON-RPC error `-32603`. | +| `POST /asap` | Rate-limited | Accepts flat legacy messages and SDK Echo tasks. The gateway limits the received and decoded bodies to 1 MiB each. See [SDK tasks](#sdk-tasks) for response limits. | | `GET /api/asap/log` | Bearer | Inbound ASAP message log | Implementation: `src/asap/manifest.c`, `src/gateway/routes.c`. If keys cannot load, manifest route returns **500** and agent startup fails fast (`init_subsystems()`). @@ -135,9 +135,9 @@ Use the table below. These are the **only** fields you enter manually. Do **not* - **`hardware_class`**, **`inference_modes`**, **`hardware_io`** — derived from `capabilities.hardware` and `capabilities.inference` in the signed manifest (e.g. Jetson: `edge_accelerator`, `["cloud","local_cuda"]`, `["gpio","i2c"]`). - **`self-signed` in tags** — upstream `anti_spam.py` adds the trust tag automatically; including it in your CSV can cause rejection or duplication. -#### Skills: v1.0 allowed vs deferred +#### Marketplace skills -IssueOps skills CSV must match manifest `capabilities.skills[].id` for v1.0: +Use `capabilities.skills[].id` from the published signed manifest for the IssueOps skills CSV. The v1.0 fixture lists these installed skills. | Skill | v1.0 | |-------|------| @@ -150,7 +150,7 @@ IssueOps skills CSV must match manifest `capabilities.skills[].id` for v1.0: | `home_monitor` | No — Phase 7 (v1.2) | | `visual_monitor` | No — Phase 7 (v1.2) | -Manifest code registers skills from `skills/*.md` on disk; default descriptions in `src/asap/manifest_build.c` align with the four IDs above. **Discovery cap:** the manifest lists the built-in `echo` skill and up to **64** installed skills on `/.well-known/asap/manifest.json`; additional on-disk skills remain available via the authenticated `/api/skills` API at runtime. +ShellClaw reads installed skills from `skills/*.md`. The current gateway manifest lists the built-in `echo` skill and up to 64 installed skills. The authenticated `/api/skills` endpoint lists additional installed skills. #### `online_check` and Demo badge @@ -185,7 +185,7 @@ Complete **after** Wave 5 signing is live on GitHub Pages (task 6.1) and **befor - [ ] `curl` manifest URL; `verify_manifest` succeeds - [ ] Open [Register Agent](https://github.com/asap-protocol/asap-protocol/issues/new?template=register_agent.yml) and fill fields from the table above (or prefill doc) -- [ ] Skills CSV is exactly four v1.0 skills (no sensor/camera/monitor skills) +- [ ] Skills CSV matches the published signed manifest. Include `echo` if the manifest lists it. - [ ] Tags CSV does **not** include `self-signed` - [ ] Did **not** manually add `hardware_class`, `inference_modes`, or `hardware_io` in the issue body - [ ] Wait for bot merge; confirm listing on marketplace Browse UI @@ -212,19 +212,27 @@ Security: exposing the agent increases attack surface — complete gateway harde ## SDK tasks -The Python SDK sends requests to `POST /asap`. Put a `TaskRequest` in `params.envelope`. The recipient must match `[asap].agent_urn`. If you configure `[asap].trusted_senders`, the gateway also checks the sender URN against that list. +The Python SDK sends requests to `POST /asap`. Put a `TaskRequest` in `params.envelope`. The recipient must match `[asap].agent_urn`. If you configure `[asap].trusted_senders`, the gateway checks the sender URN against that list. + +The gateway accepts uncompressed, Brotli (`br`), and `gzip` request bodies. Both the received and decoded bodies must fit within 1 MiB. The gateway returns HTTP 413 if either body exceeds the limit. It returns HTTP 415 for unsupported content codings and HTTP 400 for invalid compressed bodies. The manifest advertises the built-in `echo` skill once. The skill returns the input object as `TaskResponse.result`. Repeating an echo request produces the same result without using the model, local tools, or conversation history. The gateway rejects other SDK skill IDs before the model runs. Use the legacy flat request format for tasks that run the agent or call local tools. -SDK replies use `result.envelope`. The reply's `correlation_id` contains the request envelope ID. Both SDK and legacy replies echo the top-level JSON-RPC ID when the gateway can read it. Legacy requests use flat `params` and receive flat `result` envelopes. +SDK replies use `result.envelope`. The reply's `correlation_id` contains the request envelope ID. Both SDK and legacy replies preserve the JSON-RPC request ID. Legacy requests use flat `params` and receive flat `result` envelopes. + +The gateway sends SDK protocol errors in HTTP 200 responses so the SDK can report them as `RemoteRPCError`. An invalid recipient or skill returns JSON-RPC code `-32602`. The gateway returns HTTP 400 for an untrusted sender and HTTP 429 when a client reaches the rate limit. + +If a success response exceeds the 64 KiB gateway buffer, the gateway returns JSON-RPC code `-32603`. SDK envelopes receive HTTP 200 and flat envelopes receive HTTP 500. The sender list compares a URN supplied by the client. Control network access to the legacy route because it uses that list for agent and tool requests. ## ASAP compliance harness -CI runs the handshake, task state, and SLA validators from `asap-compliance==1.4.0` with `asap-protocol==2.6.0` on Python 3.14. The job starts a real gateway on loopback with a temporary home and a stub provider. All three tests must pass. The SLA check sends an `echo` task and measures it against a five-second timeout. +CI runs the handshake, task state, and SLA validators from `asap-compliance==1.4.0` with `asap-protocol==2.6.0` on Python 3.14. The validators run against a loopback gateway with a temporary home and a stub provider. The SLA check measures an `echo` task against a five-second timeout. + +CI also starts a separate gateway for the Python SDK tests. The tests cover both compression formats, numeric precision, request correlation, and HTTP status codes. To run the same checks locally, build the gateway and install the pinned packages in a Python 3.14 virtual environment. diff --git a/docs/issueops/VERIFY_MARKETPLACE.md b/docs/issueops/VERIFY_MARKETPLACE.md index fa844c83..8d3b0561 100644 --- a/docs/issueops/VERIFY_MARKETPLACE.md +++ b/docs/issueops/VERIFY_MARKETPLACE.md @@ -18,7 +18,7 @@ Short operator runbook after IssueOps registration for ShellClaw v1.0. Prefill a | Derived hardware | Filters or detail show `hardware_class` = `edge_accelerator` | | Derived inference | `inference_modes` includes `local_cuda` (and `cloud`) | | Derived I/O | `hardware_io` includes `gpio` and `i2c` | -| Skills | Exactly four: `assistant`, `edge_briefing`, `server_admin`, `gpio_control` | +| Skills | Match `capabilities.skills[].id` in the published signed manifest | | Registry shape | Live entry matches [`docs/fixtures/shellclaw-v1.0-registry-entry.json`](../fixtures/shellclaw-v1.0-registry-entry.json) for derived fields and `online_check: false` | ## Quick diff (optional) diff --git a/docs/issueops/register-agent-prefill.md b/docs/issueops/register-agent-prefill.md index 6135c2f1..7c697ac8 100644 --- a/docs/issueops/register-agent-prefill.md +++ b/docs/issueops/register-agent-prefill.md @@ -19,7 +19,7 @@ Manifest URL: https://asap-protocol.github.io/shellclaw/manifest.json HTTP endpoint: https://shellclaw.example.com/asap -Skills (CSV): assistant,edge_briefing,server_admin,gpio_control +Skills (CSV): Category: Infrastructure @@ -58,7 +58,7 @@ Complete **before** opening the issue (ideally after GitHub Pages publish from a Note: `validate_manifest.sh` validates the inner `Manifest` shape when given bare manifest JSON; for the published **SignedManifest**, use `verify_manifest` as the gate. -4. **Skills policy** — CSV must be exactly four IDs: `assistant`, `edge_briefing`, `server_admin`, `gpio_control` (no Phase 7 skills). +4. Match the Skills CSV to `capabilities.skills[].id` in the published signed manifest. Include `echo` if the manifest lists it. 5. **Tags** — do **not** include `self-signed` in your CSV. From e4f54741ef36695b8a8f881f1299b4afee509b45 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:57:37 -0300 Subject: [PATCH 08/10] chore(asap): keep adjacent gateway changes mergeable --- Makefile | 4 +++- README.md | 5 +++-- src/gateway/asap_http_body.c | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 5acf7ac7..0c635cc4 100644 --- a/Makefile +++ b/Makefile @@ -350,6 +350,8 @@ $(MANIFEST_KEYS_O): src/asap/manifest_keys.c src/asap/manifest_keys.h src/core/c $(ASAP_HTTP_BODY_O): src/gateway/asap_http_body.c src/gateway/asap_http_body.h src/gateway/http_lws.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -c -o $@ src/gateway/asap_http_body.c +$(ROUTES_O): src/gateway/asap_http_body.h + $(ENVELOPE_O): src/asap/envelope.c src/asap/envelope.h src/asap/asap_version.h src/asap/ulid.h vendor/cJSON/cJSON.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/asap/envelope.c @@ -381,7 +383,7 @@ $(HTTP_O): src/gateway/http.c src/gateway/http.h src/gateway/http_lws.h src/gate $(HTTP_LWS_O): src/gateway/http_lws.c src/gateway/http_lws.h src/gateway/asap_http_body.h src/gateway/routes.h src/gateway/auth.h src/gateway/static.h src/gateway/ws.h src/gateway/ws_rx.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/http_lws.c -$(ROUTES_O): src/gateway/routes.c src/gateway/routes.h src/gateway/asap_http_body.h src/gateway/routes_hardware.h src/gateway/http.h src/gateway/http_lws.h src/gateway/auth.h src/gateway/rate_limit.h src/tools/context.h src/asap/manifest.h src/asap/envelope.h src/asap/server.h src/asap/log.h src/core/bootstrap.h src/core/agent.h src/core/config.h src/core/config_patch.h src/core/dispatch.h src/core/reload.h src/core/memory.h src/core/skill.h src/providers/provider.h src/channels/channel.h src/tools/cron.h src/tools/tool.h +$(ROUTES_O): src/gateway/routes.c src/gateway/routes.h src/gateway/routes_hardware.h src/gateway/http.h src/gateway/http_lws.h src/gateway/auth.h src/gateway/rate_limit.h src/tools/context.h src/asap/manifest.h src/asap/envelope.h src/asap/server.h src/asap/log.h src/core/bootstrap.h src/core/agent.h src/core/config.h src/core/config_patch.h src/core/dispatch.h src/core/reload.h src/core/memory.h src/core/skill.h src/providers/provider.h src/channels/channel.h src/tools/cron.h src/tools/tool.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/routes.c $(ROUTES_HARDWARE_O): src/gateway/routes_hardware.c src/gateway/routes_hardware.h src/gateway/routes.h src/gateway/http_lws.h src/gateway/uri_match.h src/hardware/hardware.h src/hardware/hardware_gpio_snapshot.h src/hardware/hardware_tegrastats.h src/hardware/board_detect.h src/core/config.h diff --git a/README.md b/README.md index 21de122d..33fa446e 100644 --- a/README.md +++ b/README.md @@ -54,12 +54,13 @@ ShellClaw is **not another OpenClaw clone** in a different language. It is a **h - `make static` — cppcheck on `src/` (requires cppcheck) - `make test-sanitize` — AddressSanitizer + UBSan full suite - `make coverage` — coverage report; fails if core < 80% (requires lcov) -- CI enforces release binary < 2 MB; optional `asap-compliance` when the Python package is available +- The gateway build requires libwebsockets, Brotli, and zlib. Make sure that `pkg-config` finds `libwebsockets`, `libbrotlidec`, and `zlib`. +- CI enforces a release binary smaller than 2 MB. The ASAP validators and the official SDK tests must pass. - **Before opening a PR:** run `CI=true make clean && CI=true make test` (matches Linux CI with `-Werror`), or on a machine with the same apt deps as [.github/workflows/ci.yml](.github/workflows/ci.yml): `chmod +x scripts/ci-local.sh && ./scripts/ci-local.sh` See [CONTRIBUTING.md](CONTRIBUTING.md) for PR workflow, coding standards, and the pre-tag `gpio-mockup` release ritual. -**Configuration:** copy [`config.example.toml`](config.example.toml) to `~/.shellclaw/config.toml` and [`.env.example`](.env.example) to `.env`. Phase 3+ keys (ASAP, sandbox, gateway) and the Jetson `[hardware]` block are documented there. Install libwebsockets, Brotli, and zlib to build the gateway. Make sure that `pkg-config` finds `libwebsockets`, `libbrotlidec`, and `zlib`. Run `GATEWAY=1 make test_gateway_http` to test the gateway. +**Configuration:** copy [`config.example.toml`](config.example.toml) to `~/.shellclaw/config.toml` and [`.env.example`](.env.example) to `.env`. Phase 3+ keys (ASAP, sandbox, gateway) and the Jetson `[hardware]` block are documented there. Install **libwebsockets** (`pkg-config` must find it) to build the gateway and run `GATEWAY=1 make test_gateway_http`. **Jetson install (v1.0):** `./scripts/install.sh`, `./scripts/build_llama_jetson.sh`, `./scripts/download_model.sh phi3` — details in [`docs/HARDWARE_JETSON.md`](docs/HARDWARE_JETSON.md) and [`docs/LOCAL_INFERENCE.md`](docs/LOCAL_INFERENCE.md). diff --git a/src/gateway/asap_http_body.c b/src/gateway/asap_http_body.c index 041b948b..4dd0f1d3 100644 --- a/src/gateway/asap_http_body.c +++ b/src/gateway/asap_http_body.c @@ -6,12 +6,12 @@ #include "gateway/asap_http_body.h" #include "gateway/uri_match.h" -#include #include #include #include #include #include +#include #include static int asap_is_asap_post(struct lws *wsi) From c0b3ebe09d218a55bb7f0840978f0f057bedd64a Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:07:39 -0300 Subject: [PATCH 09/10] test(asap): cover wire values in C protocol tests --- tests/test_asap_envelope.c | 38 ++++++++++++++++++++++++++++++++++ tests/test_asap_server.c | 42 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/tests/test_asap_envelope.c b/tests/test_asap_envelope.c index 2b435a33..13dff461 100644 --- a/tests/test_asap_envelope.c +++ b/tests/test_asap_envelope.c @@ -143,6 +143,43 @@ static int test_parse_sdk_task(void) ASSERT(_c != NULL && cJSON_IsNumber(_c) && (int)_c->valuedouble == (want)); \ } while (0) +static int test_http_request_error_ids(void) +{ + const struct { + const char *request; + const char *response_id; + int error_code; + int sdk_wire; + } cases[] = { + { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":5000000000000001," + "\"params\":{\"envelope\":{}}}", + "\"id\":5000000000000001}", -32602, 1 }, + { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"params\":{}}", + "\"id\":null}", -32602, 0 }, + { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":[1],\"params\":{}}", + "\"id\":null}", -32600, 0 }, + { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":1.,\"params\":{}}", + "\"id\":null}", -32700, 0 }, + }; + asap_request_wire_t wire = {0}; + + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + asap_envelope_t env; + cJSON *error = NULL; + ASSERT(asap_envelope_parse_request(cases[i].request, &env, &error, &wire) == -1); + ASSERT_ERR_CODE(error, cases[i].error_code); + ASSERT(wire.sdk_wire == cases[i].sdk_wire); + + char *json = asap_jsonrpc_print_response(error, &wire); + ASSERT(json != NULL); + ASSERT(strstr(json, cases[i].response_id) != NULL); + free(json); + cJSON_Delete(error); + asap_envelope_clear(&env); + } + return 0; +} + static int test_parse_bad_request_id(void) { const char *request = "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":[],\"params\":{}}"; @@ -376,6 +413,7 @@ int main(int argc, char **argv) if (test_jsonrpc_error_null_id() != 0) { fprintf(stderr, "test_jsonrpc_error_null_id failed\n"); failed++; } if (test_parse_sdk_task() != 0) { fprintf(stderr, "test_parse_sdk_task failed\n"); failed++; } if (test_parse_valid() != 0) { fprintf(stderr, "test_parse_valid failed\n"); failed++; } + if (test_http_request_error_ids() != 0) { fprintf(stderr, "test_http_request_error_ids failed\n"); failed++; } if (test_parse_bad_request_id() != 0) { fprintf(stderr, "test_parse_bad_request_id failed\n"); failed++; } if (test_parse_unquoted_body_fails() != 0) { fprintf(stderr, "test_parse_unquoted_body_fails failed\n"); failed++; } if (test_parse_wrong_jsonrpc() != 0) { fprintf(stderr, "test_parse_wrong_jsonrpc failed\n"); failed++; } diff --git a/tests/test_asap_server.c b/tests/test_asap_server.c index f77ad30d..8d98aa93 100644 --- a/tests/test_asap_server.c +++ b/tests/test_asap_server.c @@ -242,6 +242,47 @@ static int test_sdk_unknown_skill(void) return 0; } +static int test_sdk_echo_preserves_wire_values(void) +{ + const char input[] = + "{\"samples\": [5000000000000001, -9007199254740993, " + "{\"mean\":1.234567890123456789e-12,\"label\":\"test \\\"A\\\"\"," + "\"ready\":true,\"retry\":false,\"note\":null}]}"; + char request[512]; + int len = snprintf(request, sizeof request, + "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":9007199254740993," + "\"params\":{\"envelope\":{\"id\":\"sdk-echo\",\"asap_version\":\"0.1\"," + "\"sender\":\"urn:asap:agent:peer\",\"recipient\":\"urn:asap:agent:shellclaw\"," + "\"payload_type\":\"TaskRequest\",\"payload\":{\"conversation_id\":\"c\"," + "\"skill_id\":\"echo\",\"input\": %s}}}}\n", input); + ASSERT(len > 0 && (size_t)len < sizeof request); + + asap_envelope_t in; + asap_envelope_t out = {0}; + asap_request_wire_t wire; + asap_server_ctx_t ctx = {0}; + char error[128]; + + ASSERT(asap_envelope_parse_request(request, &in, NULL, &wire) == 0); + ASSERT(asap_server_handle(&in, &out, &ctx, error, sizeof error) == 0); + cJSON *response = asap_envelope_to_jsonrpc(&out, in.jsonrpc_request_id); + char *json = asap_jsonrpc_print_response(response, &wire); + ASSERT(json != NULL); + + char result[sizeof input + sizeof "\"result\":"]; + snprintf(result, sizeof result, "\"result\":%s", input); + ASSERT(strstr(json, result) != NULL); + ASSERT(strstr(json, "\"id\":9007199254740993}") != NULL); + ASSERT(strstr(json, "\"status\":\"completed\"") != NULL); + ASSERT(strstr(json, "\"task_id\":\"sdk-echo\"") != NULL); + + free(json); + cJSON_Delete(response); + teardown_env(&in); + teardown_env(&out); + return 0; +} + static int test_task_request_hook(void) { asap_envelope_t in; @@ -1085,6 +1126,7 @@ int main(void) { int r = 0; r |= test_sdk_unknown_skill(); + r |= test_sdk_echo_preserves_wire_values(); r |= test_task_request_hook(); r |= test_task_cancel_stub(); r |= test_state_query_hook(); From 75afd8beb210f1c945515d8333722c0675073056 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:12:31 -0300 Subject: [PATCH 10/10] test(asap): compare response structure and numeric tokens --- tests/test_asap_envelope.c | 32 +++++++++++++++++++++------- tests/test_asap_server.c | 43 +++++++++++++++++++++++++++++++------- 2 files changed, 61 insertions(+), 14 deletions(-) diff --git a/tests/test_asap_envelope.c b/tests/test_asap_envelope.c index 13dff461..ce7c452c 100644 --- a/tests/test_asap_envelope.c +++ b/tests/test_asap_envelope.c @@ -147,19 +147,19 @@ static int test_http_request_error_ids(void) { const struct { const char *request; - const char *response_id; + const char *numeric_id; int error_code; int sdk_wire; } cases[] = { { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":5000000000000001," "\"params\":{\"envelope\":{}}}", - "\"id\":5000000000000001}", -32602, 1 }, + "5000000000000001", -32602, 1 }, { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"params\":{}}", - "\"id\":null}", -32602, 0 }, + NULL, -32602, 0 }, { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":[1],\"params\":{}}", - "\"id\":null}", -32600, 0 }, + NULL, -32600, 0 }, { "{\"jsonrpc\":\"2.0\",\"method\":\"asap.send\",\"id\":1.,\"params\":{}}", - "\"id\":null}", -32700, 0 }, + NULL, -32700, 0 }, }; asap_request_wire_t wire = {0}; @@ -167,12 +167,30 @@ static int test_http_request_error_ids(void) asap_envelope_t env; cJSON *error = NULL; ASSERT(asap_envelope_parse_request(cases[i].request, &env, &error, &wire) == -1); - ASSERT_ERR_CODE(error, cases[i].error_code); ASSERT(wire.sdk_wire == cases[i].sdk_wire); char *json = asap_jsonrpc_print_response(error, &wire); ASSERT(json != NULL); - ASSERT(strstr(json, cases[i].response_id) != NULL); + cJSON *response = cJSON_Parse(json); + ASSERT(cJSON_IsObject(response)); + ASSERT_ERR_CODE(response, cases[i].error_code); + const cJSON *id = cJSON_GetObjectItemCaseSensitive(response, "id"); + if (cases[i].numeric_id) { + ASSERT(cJSON_IsNumber(id)); + ASSERT(cJSON_GetNumberValue(id) == strtod(cases[i].numeric_id, NULL)); + const char *number = strstr(json, cases[i].numeric_id); + ASSERT(number != NULL); + const char *start = number; + while (start > json && strchr(" \t\r\n", start[-1])) + start--; + ASSERT(start > json && start[-1] == ':'); + const char *end = number + strlen(cases[i].numeric_id); + end += strspn(end, " \t\r\n"); + ASSERT(*end == ',' || *end == '}'); + } else { + ASSERT(cJSON_IsNull(id)); + } + cJSON_Delete(response); free(json); cJSON_Delete(error); asap_envelope_clear(&env); diff --git a/tests/test_asap_server.c b/tests/test_asap_server.c index 8d98aa93..da08966b 100644 --- a/tests/test_asap_server.c +++ b/tests/test_asap_server.c @@ -242,6 +242,22 @@ static int test_sdk_unknown_skill(void) return 0; } +/* cJSON checks the types and structure. Check full number tokens for precision. */ +static int has_json_number_token(const char *json, const char *number) +{ + size_t len = strlen(number); + for (const char *at = strstr(json, number); at; at = strstr(at + len, number)) { + const char *start = at; + while (start > json && strchr(" \t\r\n", start[-1])) + start--; + const char *end = at + len; + end += strspn(end, " \t\r\n"); + if (start > json && strchr("[:,", start[-1]) && *end && strchr(",]}", *end)) + return 1; + } + return 0; +} + static int test_sdk_echo_preserves_wire_values(void) { const char input[] = @@ -269,13 +285,26 @@ static int test_sdk_echo_preserves_wire_values(void) char *json = asap_jsonrpc_print_response(response, &wire); ASSERT(json != NULL); - char result[sizeof input + sizeof "\"result\":"]; - snprintf(result, sizeof result, "\"result\":%s", input); - ASSERT(strstr(json, result) != NULL); - ASSERT(strstr(json, "\"id\":9007199254740993}") != NULL); - ASSERT(strstr(json, "\"status\":\"completed\"") != NULL); - ASSERT(strstr(json, "\"task_id\":\"sdk-echo\"") != NULL); - + cJSON *body = cJSON_Parse(json); + ASSERT(cJSON_IsObject(body)); + ASSERT(cJSON_IsNumber(cJSON_GetObjectItemCaseSensitive(body, "id"))); + const cJSON *result = cJSON_GetObjectItemCaseSensitive(body, "result"); + const cJSON *envelope = cJSON_GetObjectItemCaseSensitive(result, "envelope"); + const cJSON *payload = cJSON_GetObjectItemCaseSensitive(envelope, "payload"); + const char *status = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(payload, "status")); + const char *task_id = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(payload, "task_id")); + ASSERT(status && strcmp(status, "completed") == 0); + ASSERT(task_id && strcmp(task_id, "sdk-echo") == 0); + const cJSON *echo = cJSON_GetObjectItemCaseSensitive(payload, "result"); + cJSON *expected = cJSON_Parse(input); + ASSERT(cJSON_IsObject(echo) && cJSON_Compare(echo, expected, 1)); + ASSERT(has_json_number_token(json, "9007199254740993")); + ASSERT(has_json_number_token(json, "5000000000000001")); + ASSERT(has_json_number_token(json, "-9007199254740993")); + ASSERT(has_json_number_token(json, "1.234567890123456789e-12")); + + cJSON_Delete(expected); + cJSON_Delete(body); free(json); cJSON_Delete(response); teardown_env(&in);