From 0a450f959137bcf0ceda4d7fc69c6958aa8227a4 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 30 Oct 2026 13:47:15 +0000 Subject: [PATCH] allen: add an A2A 1.0 SendMessage door on introduce POST /aien/api/a2a accepts SendMessage, and the legacy name message/send, and passes the message to the existing introduce door. Other A2A methods return JSON-RPC errors. Consent and no-store match introduce. The agent card stays a template under om/ until the endpoint is live. Co-authored-by: Drake Stapleton --- om/a2a/agent-card.template.json | 29 ++ scripts/allen/README.md | 42 +++ scripts/allen/a2a.py | 330 +++++++++++++++++++++++ scripts/allen/allen_chat.py | 120 +++++++-- scripts/allen/nginx-allen-location.conf | 24 ++ scripts/allen/test_a2a.py | 338 ++++++++++++++++++++++++ 6 files changed, 854 insertions(+), 29 deletions(-) create mode 100644 om/a2a/agent-card.template.json create mode 100644 scripts/allen/a2a.py create mode 100644 scripts/allen/test_a2a.py diff --git a/om/a2a/agent-card.template.json b/om/a2a/agent-card.template.json new file mode 100644 index 00000000..0515c3c1 --- /dev/null +++ b/om/a2a/agent-card.template.json @@ -0,0 +1,29 @@ +{ + "name": "Aien", + "description": "Introduce yourself to Aien. The only skill is introduce. SendMessage passes the message to the introduction door at POST /aien/api/a2a. consent must be the JSON boolean true. Without that, nothing is stored. The JSON-RPC envelope is not stored. Streaming, tasks, push notifications, and an extended card are not supported.", + "supportedInterfaces": [ + { + "url": "https://www.aienos.com/aien/api/a2a", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0" + } + ], + "version": "0.1.0", + "capabilities": { + "streaming": false, + "pushNotifications": false, + "extendedAgentCard": false + }, + "defaultInputModes": ["text/plain", "application/json"], + "defaultOutputModes": ["text/plain", "application/json"], + "skills": [ + { + "id": "introduce", + "name": "introduce", + "description": "Pass one message to the introduction door. Put the introduction fields in message metadata or in one JSON data part. consent must be the JSON boolean true, or nothing is stored.", + "tags": ["introduce"], + "inputModes": ["text/plain", "application/json"], + "outputModes": ["text/plain", "application/json"] + } + ] +} diff --git a/scripts/allen/README.md b/scripts/allen/README.md index 0cffdda8..f6fd3b56 100644 --- a/scripts/allen/README.md +++ b/scripts/allen/README.md @@ -405,6 +405,47 @@ proxy_protocol; proxy_protocol off; proxy_pass 127.0.0.1:4443;` and the same and rollback: `/root/allenchat-backup-` holds `stream.d`, `sites-*`, `snippets` and `conf.d` as they were; copy them back, `nginx -t`, reload. +## Deploy the A2A introduction endpoint + +`POST /aien/api/a2a` is A2A protocol 1.0 JSON-RPC. Nginx rewrites it to +`/allen/api/a2a`. The only method is `SendMessage`. The older name +`message/send` is the same call. The gateway passes that message to the +introduce door. Consent and storage are that door's: `consent` must be the +JSON boolean `true`, the response is `Cache-Control: no-store`, and the +JSON-RPC envelope is not written. A consented introduction is the only record, +in the same write-only drop as `POST /aien/api/introduce`. + +These methods are not supported. Each one is a JSON-RPC error and stores nothing: + +- `SendStreamingMessage` and `SubscribeToTask`: `-32004` (streaming is off) +- `GetTask`, `ListTasks`, and `CancelTask`: `-32004` (this door keeps no tasks) +- `CreateTaskPushNotificationConfig`, `GetTaskPushNotificationConfig`, `ListTaskPushNotificationConfigs`, and `DeleteTaskPushNotificationConfig`: `-32003` +- `GetExtendedAgentCard`: `-32004` (there is no extended card) +- any other method: `-32601` Method not found + +Older slash names of those same methods return the same codes. `scripts/allen/a2a.py` lists them. + +The location is `location = /allen/api/a2a` in `nginx-allen-location.conf`. +On the hub, after that file is installed as `/etc/nginx/snippets/aienos-allen.conf`: + + sudo nginx -t + +Then reload: + + sudo systemctl reload nginx + +Then check the response. This asks for `GetTask`, which is not supported, and it does not send consent: + + curl -sS -D - -o /tmp/a2a-check.json -X POST https://www.aienos.com/aien/api/a2a \ + -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":"deploy-check","method":"GetTask","params":{}}' + +Expect HTTP 200, a `Cache-Control: no-store` header, and a JSON body whose +error code is `-32004`. Nothing is stored. Do not send a consented +`SendMessage` as the deploy check. + +Rollback: restore the previous snippet, run `nginx -t`, then reload. + ## Build loop (homes, save, publish, gallery) After the greeting Allen asks what the visitor would like to build for humanity @@ -444,6 +485,7 @@ routes in `allen_projects.py`: ```sh python3 scripts/allen/test_sandbox.py # compile sandbox escape tests, each with a control +python3 scripts/allen/test_a2a.py # A2A SendMessage: consent, errors, nothing stored python3 scripts/allen/test_gateway.py --omc om/hive-page/omc --irwasm om/hive-page/irwasm \ --system-prompt scripts/allen/system-prompt.txt [--skip-model] python3 scripts/allen/probe.py # run inside the unit's properties (systemd-run) and outside diff --git a/scripts/allen/a2a.py b/scripts/allen/a2a.py new file mode 100644 index 00000000..f8ac8841 --- /dev/null +++ b/scripts/allen/a2a.py @@ -0,0 +1,330 @@ +#!/usr/bin/env python3 +"""A2A protocol 1.0 JSON-RPC for one call: SendMessage, passed to the introduce door. + +The HTTP route is POST /allen/api/a2a (public POST /aien/api/a2a). This module +does not write a file, a log line, or a task. The only store is the introduce +door, and only when that door accepts the record. Consent is the introduce +door's rule: the JSON boolean true. Anything else stores nothing. The handler +sends Cache-Control: no-store, the same header as introduce. + +Supported method: + SendMessage. The legacy method name message/send is the same call. + +Not supported. A known method returns the A2A error for the missing capability. +Any other method returns JSON-RPC -32601 Method not found. Nothing is stored. + + SendStreamingMessage, message/stream: -32004 Unsupported operation. + capabilities.streaming is false. + SubscribeToTask, tasks/resubscribe: -32004 Unsupported operation. + capabilities.streaming is false. + GetTask, tasks/get: -32004 Unsupported operation. This agent keeps no tasks. + ListTasks, tasks/list: -32004 Unsupported operation. This agent keeps no tasks. + CancelTask, tasks/cancel: -32004 Unsupported operation. This agent keeps no tasks. + CreateTaskPushNotificationConfig, tasks/pushNotificationConfig/set: -32003 + Push notifications are not supported. capabilities.pushNotifications is false. + GetTaskPushNotificationConfig, tasks/pushNotificationConfig/get: -32003. + ListTaskPushNotificationConfigs, tasks/pushNotificationConfig/list: -32003. + DeleteTaskPushNotificationConfig, tasks/pushNotificationConfig/delete: -32003. + GetExtendedAgentCard, agent/getAuthenticatedExtendedCard: -32004 + Unsupported operation. capabilities.extendedAgentCard is false. + +A request with an A2A-Version header other than 1.0 returns -32009 and stores +nothing. A missing header is accepted as 1.0. Notifications (a request with no +id) are rejected with -32600. This door does not take a silent store. + +SendMessage params.message is the introduction. Fields come from message.metadata, +then from each JSON data part (a later part overrides). A text part is the +purpose only when purpose is still empty. role must be ROLE_USER. File parts +(raw, url) return -32005. taskId and a non-empty referenceTaskIds return -32004. +historyLength, returnImmediately, extensions, and the A2A-Extensions header are +ignored and are not stored. The JSON-RPC envelope, messageId, and contextId are +not stored. contextId is echoed when the client sent one, otherwise a new id is +returned and forgotten. + +The introduce door still applies its own caps, the anonymous-mode refusal, the +rate limit, and the daily cap. Those replies are JSON-RPC errors here. HTTP +status is 200 for every JSON-RPC body, including errors, with the error in the +body. Cache-Control stays no-store. +""" + +import json +import secrets + +# The introduce door's field names. consent is checked by that door, not copied +# into the stored record. +INTRO_FIELDS = ("kind", "name", "org", "contact", "github", "origin", "purpose", + "homepage", "framework", "model", "human") + +SEND_METHODS = frozenset({"SendMessage", "message/send"}) + +# code, message, reason. Legacy slash names are the same operations. +UNSUPPORTED = { + "SendStreamingMessage": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), + "message/stream": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), + "SubscribeToTask": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), + "tasks/resubscribe": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), + "GetTask": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), + "tasks/get": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), + "ListTasks": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), + "tasks/list": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), + "CancelTask": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), + "tasks/cancel": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), + "CreateTaskPushNotificationConfig": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "tasks/pushNotificationConfig/set": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "GetTaskPushNotificationConfig": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "tasks/pushNotificationConfig/get": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "ListTaskPushNotificationConfigs": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "tasks/pushNotificationConfig/list": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "DeleteTaskPushNotificationConfig": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "tasks/pushNotificationConfig/delete": (-32003, "Push notifications are not supported", + "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), + "GetExtendedAgentCard": (-32004, "Unsupported operation", "EXTENDED_AGENT_CARD_NOT_SUPPORTED"), + "agent/getAuthenticatedExtendedCard": (-32004, "Unsupported operation", + "EXTENDED_AGENT_CARD_NOT_SUPPORTED"), +} + +OUTPUT_MODES = frozenset({"text/plain", "application/json"}) +MAX_PARTS = 8 +MAX_ID = 200 + + +def error_info(reason, metadata=None): + info = { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": reason, + "domain": "a2a-protocol.org", + } + if metadata: + info["metadata"] = {str(k): str(v) for k, v in metadata.items()} + return [info] + + +def bad_request(field, description): + return [{ + "@type": "type.googleapis.com/google.rpc.BadRequest", + "fieldViolations": [{"field": field, "description": description}], + }] + + +def error_obj(rid, code, message, data=None): + err = {"code": code, "message": message} + if data is not None: + err["data"] = data + return {"jsonrpc": "2.0", "id": rid, "error": err} + + +def valid_id(rid): + if rid is None or isinstance(rid, str): + return True + # bool is a subclass of int. JSON-RPC ids are strings, numbers, or null. + if type(rid) is bool: + return False + return type(rid) in (int, float) + + +def controls(text): + return any((ord(c) < 32 and c not in "\n\t") or ord(c) == 127 for c in text) + + +def version_error(headers): + """None when the call may proceed. A missing header means 1.0.""" + if headers is None: + return None + raw = headers.get("A2A-Version") + if raw is None: + return None + version = str(raw).strip() + if version == "" or version == "1.0": + return None + return (-32009, "Version is not supported", + error_info("VERSION_NOT_SUPPORTED", {"version": version})) + + +def parse(raw): + """('ok', request) or ('error', response object).""" + if not isinstance(raw, (bytes, bytearray)): + return "error", error_obj(None, -32700, "Invalid JSON payload") + try: + req = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + return "error", error_obj(None, -32700, "Invalid JSON payload") + if not isinstance(req, dict): + return "error", error_obj(None, -32600, "Request payload validation error") + rid = req.get("id", None) + if "id" not in req or not valid_id(rid): + # A notification, or an id this door will not echo. No silent store. + return "error", error_obj(None, -32600, "Request payload validation error") + if req.get("jsonrpc") != "2.0" or not isinstance(req.get("method"), str) or not req["method"]: + return "error", error_obj(rid, -32600, "Request payload validation error") + if "params" in req and not isinstance(req["params"], dict): + return "error", error_obj(rid, -32602, "Invalid parameters", + bad_request("params", "params must be an object")) + return "ok", req + + +def check_config(params): + cfg = params.get("configuration") + if cfg is None: + return None + if not isinstance(cfg, dict): + return (-32602, "Invalid parameters", bad_request("configuration", "configuration must be an object")) + push = cfg.get("taskPushNotificationConfig") + if push is not None: + return (-32003, "Push notifications are not supported", + error_info("PUSH_NOTIFICATIONS_NOT_SUPPORTED")) + modes = cfg.get("acceptedOutputModes") + if modes is None: + return None + if not isinstance(modes, list) or not modes or not all(isinstance(m, str) for m in modes): + return (-32602, "Invalid parameters", + bad_request("configuration.acceptedOutputModes", "acceptedOutputModes must be media types")) + if OUTPUT_MODES.isdisjoint(modes): + return (-32005, "Content type is not supported", + error_info("CONTENT_TYPE_NOT_SUPPORTED", {"acceptedOutputModes": ",".join(modes)})) + return None + + +def build_intro(message): + """('ok', intro dict, context id) or ('error', code, message, data).""" + if not isinstance(message, dict): + return ("error", -32602, "Invalid parameters", + bad_request("message", "message is required")) + if message.get("role") != "ROLE_USER": + return ("error", -32602, "Invalid parameters", + bad_request("message.role", "role must be ROLE_USER")) + mid = message.get("messageId") + if not isinstance(mid, str) or not mid.strip() or len(mid) > MAX_ID or controls(mid): + return ("error", -32602, "Invalid parameters", + bad_request("message.messageId", "messageId must be text")) + if message.get("taskId") or message.get("referenceTaskIds"): + return ("error", -32004, "Unsupported operation", + error_info("TASKS_NOT_SUPPORTED")) + ctx = message.get("contextId") + if ctx is None: + context_id = "ctx_" + secrets.token_hex(16) + elif not isinstance(ctx, str) or not ctx.strip() or len(ctx) > MAX_ID or controls(ctx): + return ("error", -32602, "Invalid parameters", + bad_request("message.contextId", "contextId must be text")) + else: + context_id = ctx + parts = message.get("parts") + if not isinstance(parts, list) or not parts or len(parts) > MAX_PARTS: + return ("error", -32602, "Invalid parameters", + bad_request("message.parts", "Send one to eight parts")) + meta = message.get("metadata", {}) + if meta is None: + meta = {} + if not isinstance(meta, dict): + return ("error", -32602, "Invalid parameters", + bad_request("message.metadata", "metadata must be an object")) + intro = dict(meta) + texts = [] + for part in parts: + if not isinstance(part, dict): + return ("error", -32602, "Invalid parameters", + bad_request("message.parts", "each part must be an object")) + present = [k for k in ("text", "raw", "url", "data") if k in part] + if len(present) != 1: + return ("error", -32602, "Invalid parameters", + bad_request("message.parts", "a part needs exactly one of text, raw, url, data")) + kind = present[0] + media = part.get("mediaType") + if kind in ("raw", "url"): + return ("error", -32005, "Content type is not supported", + error_info("CONTENT_TYPE_NOT_SUPPORTED")) + if kind == "text": + if not isinstance(part["text"], str): + return ("error", -32602, "Invalid parameters", + bad_request("message.parts", "text must be a string")) + if media is not None and media != "text/plain": + return ("error", -32005, "Content type is not supported", + error_info("CONTENT_TYPE_NOT_SUPPORTED", {"mediaType": media})) + if part["text"].strip(): + texts.append(part["text"].strip()) + else: + if media is not None and media != "application/json": + return ("error", -32005, "Content type is not supported", + error_info("CONTENT_TYPE_NOT_SUPPORTED", {"mediaType": media})) + if not isinstance(part["data"], dict): + return ("error", -32602, "Invalid parameters", + bad_request("message.parts", "a data part must be a JSON object")) + intro.update(part["data"]) + purpose = intro.get("purpose") + if texts and (not isinstance(purpose, str) or not purpose.strip()): + intro["purpose"] = "\n".join(texts) + return "ok", intro, context_id + + +def map_intro(status, body): + err = body.get("error") if isinstance(body, dict) else None + msg = body.get("message") if isinstance(body, dict) and isinstance(body.get("message"), str) else "Invalid parameters" + if err == "consent_required": + return -32602, "Invalid parameters", bad_request("message.metadata.consent", msg) + if err in ("invalid", "too_long"): + return -32602, "Invalid parameters", bad_request("message", msg) + if err == "anonymous": + return -32602, "Invalid parameters", bad_request("X-Allen-Anonymous", msg) + if err == "rate": + return -32603, "Internal error", error_info("RATE_LIMITED", {"message": msg}) + if err == "busy": + return -32603, "Internal error", error_info("BUSY", {"message": msg}) + if err == "not_found": + return -32603, "Internal error", error_info("INTRODUCTION_DOOR_UNAVAILABLE") + return -32603, "Internal error", error_info("INTRODUCTION_FAILED", {"status": status}) + + +def result_message(body, context_id): + data = {k: body[k] for k in ("id", "stored", "delete", "key") if k in body} + return {"message": { + "role": "ROLE_AGENT", + "messageId": "m_" + secrets.token_hex(16), + "contextId": context_id, + "parts": [ + {"text": "Introduction stored.", "mediaType": "text/plain"}, + {"data": data, "mediaType": "application/json"}, + ], + }} + + +def dispatch(raw, headers, accept): + """One JSON-RPC call. accept(intro) is the introduce door. + + Returns (http_status, object, extra_headers). This function does not write + storage. accept does, and only when the introduce door stores a record. + http_status is 200. The handler adds Cache-Control: no-store. + """ + kind, parsed = parse(raw) + if kind == "error": + return 200, parsed, None + ver = version_error(headers) + if ver: + return 200, error_obj(parsed["id"], ver[0], ver[1], ver[2]), None + method = parsed["method"] + if method not in SEND_METHODS: + if method in UNSUPPORTED: + code, message, reason = UNSUPPORTED[method] + return 200, error_obj(parsed["id"], code, message, + error_info(reason, {"method": method})), None + return 200, error_obj(parsed["id"], -32601, "Method not found", + error_info("METHOD_NOT_FOUND", + {"method": method, "supported": "SendMessage"})), None + params = parsed.get("params") or {} + cfg = check_config(params) + if cfg: + return 200, error_obj(parsed["id"], cfg[0], cfg[1], cfg[2]), None + built = build_intro(params.get("message")) + if built[0] == "error": + return 200, error_obj(parsed["id"], built[1], built[2], built[3]), None + status, body, retry = accept(built[1]) + extra = {"Retry-After": str(retry)} if retry else None + if status == 200 and isinstance(body, dict) and body.get("stored") is True: + return 200, {"jsonrpc": "2.0", "id": parsed["id"], "result": result_message(body, built[2])}, extra + code, message, data = map_intro(status, body) + return 200, error_obj(parsed["id"], code, message, data), extra diff --git a/scripts/allen/allen_chat.py b/scripts/allen/allen_chat.py index fc100d2e..0e4cdd30 100755 --- a/scripts/allen/allen_chat.py +++ b/scripts/allen/allen_chat.py @@ -28,7 +28,8 @@ the hub never proxies. Visitor text and model tokens never reach that channel. Privacy: no prompt, reply, source or address is written anywhere. Rate-limit keys are salted hashes held in memory only. The only log line is an aggregate -counter summary. +counter summary. POST /allen/api/a2a is A2A 1.0 SendMessage only; it calls the +introduce door and stores nothing itself (a2a.py lists the methods that error). Python standard library only. README.md and DEPENDENCIES.md sit next to this file (in aien-dev/aienos.com scripts/allen/ and installed in /opt/allen-chat): @@ -67,6 +68,7 @@ import allen_speed # noqa: E402 import allen_infer # noqa: E402 (speed test: infer, infer-verify; allen_infer.py) import allen_math # noqa: E402 (math panes: POST math to the Omega engine; allen_math.py) import allen_transcribe # noqa: E402 (POST transcribe: push-to-talk, off unless --whisper-cli) +import a2a # noqa: E402 (POST a2a: A2A 1.0 SendMessage, passed to introduce) try: import allen_memory # noqa: E402 (isolated visitor Cortex client; optional) @@ -1273,17 +1275,28 @@ class Handler(BaseHTTPRequestHandler): extra = {"Retry-After": str(retry)} self.send_json(code, obj, extra) - def read_json(self): + def read_bytes(self): + """The raw body, or None when the size refusal was already sent.""" try: n = int(self.headers.get("Content-Length", "0")) - except ValueError: + except (TypeError, ValueError): n = -1 if n < 0 or n > MAX_BODY: self.refuse(413, "too_long", "The request is too large.") return None try: data = self.rfile.read(n) - self.body_read = True + except OSError: + self.close_connection = True + return None + self.body_read = True + return data + + def read_json(self): + data = self.read_bytes() + if data is None: + return None + try: return json.loads(data) except (ValueError, UnicodeDecodeError): self.refuse(400, "bad_request", "The request is not valid JSON.") @@ -1330,6 +1343,8 @@ class Handler(BaseHTTPRequestHandler): return self.submit() if r == "introduce": return self.introduce() + if r == "a2a": + return self.a2a() if r == "forget": return self.forget() if r == "forget-me": @@ -1931,51 +1946,55 @@ class Handler(BaseHTTPRequestHandler): INTRO_FIELDS = {"kind": 5, "name": 100, "org": 100, "contact": 200, "github": 39, "origin": 200, "purpose": 1000, "homepage": 200, "framework": 100, "model": 100, "human": 200} - def introduce(self): - """Consent-gated introduction. The record is dropped for the separate ingest unit; - this process cannot read the contact store (it is not in its mount namespace).""" - app = self.app - app.stats.add("introduce_requests") + def introduction_gate(self): + """None when an introduction may be read. Otherwise (status, body). Stores nothing.""" if anonymous(self): - app.stats.add("introduce_anonymous") - return self.send_json(409, {"error": "anonymous", "message": "Anonymous mode is on, so nothing " - "was stored. Turn it off to introduce yourself."}) - if not app.args.contacts_drop: - return self.send_json(404, {"error": "not_found"}) - req = self.read_json() - if req is None: - return + self.app.stats.add("introduce_anonymous") + return 409, {"error": "anonymous", "message": "Anonymous mode is on, so nothing " + "was stored. Turn it off to introduce yourself."} + if not self.app.args.contacts_drop: + return 404, {"error": "not_found"} + return None + + def accept_introduction(self, req): + """The introduce door. Returns (status, body, retry). + + Stores one drop only when consent is the JSON boolean true and the + fields pass. Every other result stores nothing. POST /introduce and + POST /a2a both call this. + """ + app = self.app if not isinstance(req, dict) or req.get("consent") is not True: app.stats.add("introduce_no_consent") - return self.send_json(400, {"error": "consent_required", - "message": "Nothing was stored. Send consent: true to agree to the notice."}) + return 400, {"error": "consent_required", + "message": "Nothing was stored. Send consent: true to agree to the notice."}, None extra = set(req) - set(self.INTRO_FIELDS) - {"consent"} if extra: - return self.send_json(422, {"error": "invalid", "message": "Unknown fields: " + ", ".join(sorted(extra))[:200]}) + return 422, {"error": "invalid", "message": "Unknown fields: " + ", ".join(sorted(extra))[:200]}, None rec = {} for k, cap in self.INTRO_FIELDS.items(): v = req.get(k, "") if v is None: v = "" if not isinstance(v, str): - return self.send_json(422, {"error": "invalid", "message": "%s must be text" % k}) + return 422, {"error": "invalid", "message": "%s must be text" % k}, None v = v.strip() if len(v) > cap: - return self.send_json(413, {"error": "too_long", "message": "%s is limited to %d characters" % (k, cap)}) + return 413, {"error": "too_long", "message": "%s is limited to %d characters" % (k, cap)}, None if any((ord(c) < 32 and c not in "\n\t") or ord(c) == 127 for c in v): - return self.send_json(422, {"error": "invalid", "message": "%s contains control characters" % k}) + return 422, {"error": "invalid", "message": "%s contains control characters" % k}, None rec[k] = v if rec["kind"] not in ("human", "agent"): - return self.send_json(422, {"error": "invalid", "message": "kind must be human or agent"}) + return 422, {"error": "invalid", "message": "kind must be human or agent"}, None if not (rec["name"] or rec["contact"]): - return self.send_json(422, {"error": "invalid", "message": "Give at least a name or a contact."}) + return 422, {"error": "invalid", "message": "Give at least a name or a contact."}, None if rec["homepage"] and not re.match(r"^https://[^\s]{4,}$", rec["homepage"]): - return self.send_json(422, {"error": "invalid", "message": "homepage must be an https URL"}) + return 422, {"error": "invalid", "message": "homepage must be an https URL"}, None retry = app.intro_rate.take(app.client_key(self)) if retry: - return self.refuse(429, "rate", "You have introduced yourself several times already.", retry) + return 429, {"error": "rate", "message": "You have introduced yourself several times already."}, retry if not app.submit_day(): - return self.refuse(503, "busy", "Allen has taken as many introductions as he may today.", 3600) + return 503, {"error": "busy", "message": "Allen has taken as many introductions as he may today."}, 3600 cid = "c_" + secrets.token_hex(8) token = secrets.token_urlsafe(24) # A visitor who already has a key keeps it; otherwise consent creates one. @@ -1992,7 +2011,50 @@ class Handler(BaseHTTPRequestHandler): out = {"id": cid, "stored": True, "delete": "https://www.aienos.com/aien/#forget=%s.%s" % (cid, token)} if vid: out["key"] = key - self.send_json(200, out) + return 200, out, None + + def send_introduction(self, code, body, retry): + if retry is not None: + return self.refuse(code, body["error"], body["message"], retry) + self.send_json(code, body) + + def introduce(self): + """Consent-gated introduction. The record is dropped for the separate ingest unit; + this process cannot read the contact store (it is not in its mount namespace).""" + app = self.app + app.stats.add("introduce_requests") + gate = self.introduction_gate() + if gate: + return self.send_json(gate[0], gate[1]) + req = self.read_json() + if req is None: + return + self.send_introduction(*self.accept_introduction(req)) + + def a2a(self): + """A2A 1.0 JSON-RPC. SendMessage (legacy name message/send) calls accept_introduction. + + Every other A2A method is a JSON-RPC error from a2a.py and stores nothing. + Consent and Cache-Control: no-store match introduce. The envelope is not stored. + """ + app = self.app + app.stats.add("a2a_requests") + app.stats.add("introduce_requests") + raw = self.read_bytes() + if raw is None: + return + + def accept(req): + gate = self.introduction_gate() + if gate: + return gate[0], gate[1], None + code, body, retry = self.accept_introduction(req) + if retry is not None: + app.stats.add("refused_" + body["error"]) + return code, body, retry + + status, obj, extra = a2a.dispatch(raw, self.headers, accept) + self.send_json(status, obj, extra) def project_summary(self): """The visitor's own project summary, sent only by a separate Sync click after a diff --git a/scripts/allen/nginx-allen-location.conf b/scripts/allen/nginx-allen-location.conf index 0a6b9401..3fd738f3 100644 --- a/scripts/allen/nginx-allen-location.conf +++ b/scripts/allen/nginx-allen-location.conf @@ -122,6 +122,30 @@ location ^~ /allen/api/ { proxy_read_timeout 30s; } + # A2A 1.0 JSON-RPC for the introduce door only. Public POST /aien/api/a2a + # rewrites to this exact path. SendMessage (legacy name message/send) is the + # one method. Every other method is a JSON-RPC error from the gateway. + # Consent and no-store match introduce: nothing is stored unless consent is + # the JSON boolean true, and the response carries Cache-Control: no-store. + # Agora's board is a different service at /agora/a2a. + location = /allen/api/a2a { + if ($proxy_protocol_addr = "") { return 503; } + if ($allen_xsite) { return 403; } + if ($allen_notjson) { return 415; } + limit_except POST { deny all; } + limit_req zone=allen_submit burst=3 nodelay; + limit_conn allen_conn 4; + client_max_body_size 72k; + proxy_pass http://allen_chat_gateway; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host allen-chat; + proxy_set_header X-Real-IP $proxy_protocol_addr; + proxy_set_header X-Forwarded-For ""; + proxy_connect_timeout 3s; + proxy_read_timeout 15s; + } + # Visitor-confirmed issue/project proposals, consented introductions, deletions. location ~ ^/allen/api/(submit|introduce|forget|forget-me)$ { if ($proxy_protocol_addr = "") { return 503; } diff --git a/scripts/allen/test_a2a.py b/scripts/allen/test_a2a.py new file mode 100644 index 00000000..c9770416 --- /dev/null +++ b/scripts/allen/test_a2a.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""A2A SendMessage against the introduce door. No sandbox, no model, no network listen. + +Drives Handler.do_POST on a throwaway drop directory. A consented send stores one +introduce record. Missing or false consent, malformed JSON-RPC, and an unsupported +method store nothing. The JSON-RPC envelope is not written even when the +introduction is. +""" + +import io +import json +import os +import sys +import tempfile +import threading +from email.message import Message + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(HERE, "contacts")) + +import a2a # noqa: E402 +import allen_chat # noqa: E402 +import allen_contacts_ingest # noqa: E402 + +ROOT = os.path.abspath(os.path.join(HERE, "..", "..")) +SENTINEL = "SENTINEL-a2a-message-not-stored-9f3c2a" +results = [] + + +def check(name, ok, detail): + results.append((name, ok)) + print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail), flush=True) + + +def intro(**over): + body = { + "consent": True, "kind": "agent", "name": "Test Agent", "org": "", + "contact": "test@example.org", "github": "", "origin": "", + "purpose": "testing the door", "homepage": "", "framework": "", + "model": "", "human": "Drake (test)", + } + body.update(over) + return body + + +class App: + """The pieces accept_introduction actually uses. Not a full gateway.""" + + def __init__(self, drop): + self.args = type("A", (), {"contacts_drop": drop, "submit_per_day": 40})() + self.stats = allen_chat.Stats() + self.intro_rate = allen_chat.Buckets(3, 1200) + self.salt = b"a2a-test-salt!!" + self.trusted = {"127.0.0.1"} + self.visitor_secret = None + self.day = (None, 0) + self.day_lock = threading.Lock() + + def drop(self, rec, d=None, name=None): + allen_chat.App.drop(self, rec, d, name) + + def submit_day(self): + return allen_chat.App.submit_day(self) + + def client_key(self, handler): + return allen_chat.App.client_key(self, handler) + + +def files(drop): + return sorted(f for f in os.listdir(drop) if not f.startswith(".")) + + +def tree_text(drop): + out = [] + for name in files(drop): + with open(os.path.join(drop, name), "rb") as f: + out.append(f.read()) + return b"\n".join(out) + + +class Call: + def __init__(self, app, raw, path, extra=None): + self.app = app + self.headers = Message() + self.headers["Content-Type"] = "application/json" + self.headers["Content-Length"] = str(len(raw)) + self.headers["X-Real-IP"] = "203.0.113.50" + for k, v in (extra or {}).items(): + self.headers[k] = v + self.rfile = io.BytesIO(raw) + self.wfile = io.BytesIO() + self.client_address = ("127.0.0.1", 9) + self.close_connection = False + self.command = "POST" + self.path = path + self.requestline = "POST %s HTTP/1.1" % path + self.request_version = "HTTP/1.1" + self.body_read = False + + +def post(app, path, obj=None, raw=None, headers=None): + if raw is None: + raw = json.dumps(obj).encode() + call = allen_chat.Handler.__new__(allen_chat.Handler) + src = Call(app, raw, path, headers) + call.__dict__.update(src.__dict__) + call.server = type("S", (), {"app": app})() + call.do_POST() + data = call.wfile.getvalue() + head, _, body = data.partition(b"\r\n\r\n") + line = head.split(b"\r\n", 1)[0] + status = int(line.split()[1]) + hdrs = {} + for row in head.split(b"\r\n")[1:]: + if b":" in row: + k, v = row.split(b":", 1) + hdrs[k.decode().lower()] = v.decode().strip() + payload = json.loads(body.decode()) if body else None + return status, hdrs, payload + + +def rpc(method, message, rid="t1", params_extra=None): + params = {"message": message} + if params_extra: + params.update(params_extra) + return {"jsonrpc": "2.0", "id": rid, "method": method, "params": params} + + +def message(fields, text=None, message_id="msg-1", context_id=None, part_meta=None): + parts = [] + if text is not None: + part = {"text": text, "mediaType": "text/plain"} + if part_meta is not None: + part["metadata"] = part_meta + parts.append(part) + parts.append({"data": fields, "mediaType": "application/json"}) + msg = {"role": "ROLE_USER", "messageId": message_id, "parts": parts} + if context_id is not None: + msg["contextId"] = context_id + return msg + + +def no_store(hdrs): + return hdrs.get("cache-control") == "no-store" + + +def test_valid_send(): + drop = tempfile.mkdtemp(prefix="a2a-valid-") + app = App(drop) + try: + st, hdrs, body = post(app, "/allen/api/introduce", intro()) + drops = files(drop) + rec = json.load(open(os.path.join(drop, drops[0]))) if drops else {} + check("introduce door still stores one consented record", + st == 200 and body.get("stored") is True and len(drops) == 1 + and rec.get("name") == "Test Agent" and "consent" not in rec + and no_store(hdrs), + "status %s drops %d" % (st, len(drops))) + os.remove(os.path.join(drop, drops[0])) + st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro()))) + drops = files(drop) + raw = open(os.path.join(drop, drops[0]), "rb").read() if drops else b"" + rec = json.loads(raw) if raw else {} + parsed = allen_contacts_ingest.parse_drop(raw) if raw else None + result = (body or {}).get("result", {}).get("message", {}) + data = next((p.get("data") for p in result.get("parts", []) if "data" in p), {}) + check("SendMessage with consent stores one introduce record", + st == 200 and no_store(hdrs) and body.get("jsonrpc") == "2.0" + and result.get("role") == "ROLE_AGENT" + and data.get("stored") is True and data.get("id") == rec.get("id") + and len(drops) == 1 and parsed is not None + and rec.get("purpose") == "testing the door" and "consent" not in rec + and "jsonrpc" not in raw.decode() and "SendMessage" not in raw.decode(), + "status %s drops %d role %s" % (st, len(drops), result.get("role"))) + st, hdrs, body = post(app, "/allen/api/a2a", + rpc("message/send", message(intro(name="Legacy Agent"), message_id="msg-2"), rid=2)) + drops = files(drop) + check("legacy message/send is the same call", + st == 200 and no_store(hdrs) and len(drops) == 2 + and body.get("result", {}).get("message", {}).get("role") == "ROLE_AGENT", + "status %s drops %d" % (st, len(drops))) + finally: + for name in files(drop): + os.remove(os.path.join(drop, name)) + os.rmdir(drop) + + +def test_consent(): + drop = tempfile.mkdtemp(prefix="a2a-consent-") + app = App(drop) + try: + missing = intro() + missing.pop("consent") + cases = ( + ("missing consent", missing), + ("consent false", intro(consent=False)), + ("consent as string", intro(consent="true")), + ) + for name, fields in cases: + st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(fields))) + err = (body or {}).get("error", {}) + text = json.dumps(err) + check("refuses %s and stores nothing" % name, + st == 200 and no_store(hdrs) and err.get("code") == -32602 + and "Nothing was stored" in text and not files(drop), + "status %s code %s drops %d" % (st, err.get("code"), len(files(drop)))) + st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", message(intro())), + headers={"X-Allen-Anonymous": "1"}) + err = (body or {}).get("error", {}) + check("anonymous mode stores nothing", + st == 200 and no_store(hdrs) and err.get("code") == -32602 + and "nothing was stored" in json.dumps(err).lower() and not files(drop), + "status %s code %s" % (st, err.get("code"))) + finally: + os.rmdir(drop) + + +def test_malformed(): + drop = tempfile.mkdtemp(prefix="a2a-bad-") + app = App(drop) + try: + cases = ( + ("not json", b"{", -32700), + ("empty body", b"", -32700), + ("json array", b"[1,2]", -32600), + ("missing id", b'{"jsonrpc":"2.0","method":"SendMessage"}', -32600), + ("wrong version", b'{"jsonrpc":"1.0","id":1,"method":"SendMessage"}', -32600), + ) + for name, raw, code in cases: + st, hdrs, body = post(app, "/allen/api/a2a", raw=raw) + err = (body or {}).get("error", {}) + check("malformed %s" % name, + st == 200 and no_store(hdrs) and err.get("code") == code and not files(drop), + "status %s code %s body %s" % (st, err.get("code"), body)) + finally: + os.rmdir(drop) + + +def test_unsupported(): + drop = tempfile.mkdtemp(prefix="a2a-method-") + app = App(drop) + try: + for method, code in (("GetTask", -32004), ("SendStreamingMessage", -32004), + ("CreateTaskPushNotificationConfig", -32003), + ("GetExtendedAgentCard", -32004), ("nope", -32601)): + st, hdrs, body = post(app, "/allen/api/a2a", + {"jsonrpc": "2.0", "id": 7, "method": method, "params": {}}) + err = (body or {}).get("error", {}) + check("unsupported %s" % method, + st == 200 and no_store(hdrs) and err.get("code") == code + and body.get("id") == 7 and not files(drop), + "status %s code %s" % (st, err.get("code"))) + finally: + os.rmdir(drop) + + +def test_nothing_stored(): + """The envelope, message id, and unused text are not on disk. Failures write no file.""" + drop = tempfile.mkdtemp(prefix="a2a-store-") + app = App(drop) + before = set(os.listdir(drop)) + try: + post(app, "/allen/api/a2a", raw=b"not-json") + post(app, "/allen/api/a2a", {"jsonrpc": "2.0", "id": 1, "method": "GetTask", "params": {}}) + bare = intro() + bare.pop("consent") + post(app, "/allen/api/a2a", rpc("SendMessage", message(bare))) + post(app, "/allen/api/a2a", rpc("SendMessage", message(intro(consent=False)))) + check("refusals create no file", files(drop) == [] and set(os.listdir(drop)) == before, + "entries %s" % os.listdir(drop)) + fields = intro(purpose="testing the door") + msg = message(fields, text=SENTINEL, message_id=SENTINEL, context_id=SENTINEL, + part_meta={"note": SENTINEL}) + st, hdrs, body = post(app, "/allen/api/a2a", rpc("SendMessage", msg, rid="keep")) + blob = tree_text(drop) + check("consented send does not store the message envelope", + st == 200 and no_store(hdrs) and len(files(drop)) == 1 + and SENTINEL.encode() not in blob + and b"jsonrpc" not in blob and b"SendMessage" not in blob + and b"testing the door" in blob and b'"consent"' not in blob, + "status %s files %s" % (st, files(drop))) + # The reply may echo the context id. That echo is the HTTP body, not a file. + echoed = (body or {}).get("result", {}).get("message", {}).get("contextId") + check("context id is returned and not stored", + echoed == SENTINEL and SENTINEL.encode() not in blob, "context %s" % echoed) + finally: + for name in files(drop): + os.remove(os.path.join(drop, name)) + os.rmdir(drop) + + +def test_docs_and_card(): + doc = a2a.__doc__ + required = ( + "SendMessage", "message/send", "SendStreamingMessage", "GetTask", "ListTasks", + "CancelTask", "SubscribeToTask", "CreateTaskPushNotificationConfig", + "GetTaskPushNotificationConfig", "ListTaskPushNotificationConfigs", + "DeleteTaskPushNotificationConfig", "GetExtendedAgentCard", + ) + missing = [name for name in required if name not in doc] + check("code docs name every unsupported method", not missing, "missing %s" % missing) + card_path = os.path.join(ROOT, "om", "a2a", "agent-card.template.json") + card = json.load(open(card_path, encoding="utf-8")) + iface = card["supportedInterfaces"][0] + modes = ["text/plain", "application/json"] + published = [] + for dirpath, _, names in os.walk(os.path.join(ROOT, "public")): + for name in names: + if name in ("agent-card.json", "agent.json", "server.json", "did.json"): + published.append(os.path.join(dirpath, name)) + check("agent card template is unpublished", + card["name"] == "Aien" and card["version"] == "0.1.0" + and iface["protocolBinding"] == "JSONRPC" and iface["protocolVersion"] == "1.0" + and iface["url"] == "https://www.aienos.com/aien/api/a2a" + and card["defaultInputModes"] == modes and card["defaultOutputModes"] == modes + and card["capabilities"]["streaming"] is False + and card["capabilities"]["pushNotifications"] is False + and [s["id"] for s in card["skills"]] == ["introduce"] + and not published + and not os.path.exists(os.path.join(ROOT, "public", ".well-known", "agent-card.json")), + "published %s" % published) + + +def main(): + test_valid_send() + test_consent() + test_malformed() + test_unsupported() + test_nothing_stored() + test_docs_and_card() + failed = [n for n, ok in results if not ok] + print("%d/%d passed" % (len(results) - len(failed), len(results))) + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main()