Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/a2a.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / a2a.py` 361 lines ยท 17610 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """A2A protocol 1.0 JSON-RPC for one call: SendMessage, passed to the introduce door. 3 4 The HTTP route is POST /allen/api/a2a (public POST /aien/api/a2a). This module 5 does not write a file, a log line, or a task. The only store is the introduce 6 door, and only when that door accepts the record. Consent is the introduce 7 door's rule: the JSON boolean true. Anything else stores nothing. The handler 8 sends Cache-Control: no-store, the same header as introduce. 9 10 Supported method: 11 SendMessage. The legacy method name message/send is the same call. 12 13 Not supported. A known method returns the A2A error for the missing capability. 14 Any other method returns JSON-RPC -32601 Method not found. Nothing is stored. 15 16 SendStreamingMessage, message/stream: -32004 Unsupported operation. 17 capabilities.streaming is false. 18 SubscribeToTask, tasks/resubscribe: -32004 Unsupported operation. 19 capabilities.streaming is false. 20 GetTask, tasks/get: -32004 Unsupported operation. This agent keeps no tasks. 21 ListTasks, tasks/list: -32004 Unsupported operation. This agent keeps no tasks. 22 CancelTask, tasks/cancel: -32004 Unsupported operation. This agent keeps no tasks. 23 CreateTaskPushNotificationConfig, tasks/pushNotificationConfig/set: -32003 24 Push notifications are not supported. capabilities.pushNotifications is false. 25 GetTaskPushNotificationConfig, tasks/pushNotificationConfig/get: -32003. 26 ListTaskPushNotificationConfigs, tasks/pushNotificationConfig/list: -32003. 27 DeleteTaskPushNotificationConfig, tasks/pushNotificationConfig/delete: -32003. 28 GetExtendedAgentCard, agent/getAuthenticatedExtendedCard: -32004 29 Unsupported operation. capabilities.extendedAgentCard is false. 30 31 A2A-Version: spec 3.6.2 says an empty value is version 0.3, and spec 3.6.1 32 assumes 0.3 when the header is empty. A missing header is that empty case. 33 This door implements 1.0 only, so a missing or empty version is 0.3 and 34 returns -32009, and nothing is stored. Send A2A-Version: 1.0. When the header 35 is absent, the query parameter A2A-Version is read instead (spec 3.6.1). Any 36 other version returns -32009. Notifications (a request with no id) are 37 rejected with -32600. This door does not take a silent store. 38 39 SendMessage params.message is the introduction. Fields come from message.metadata, 40 then from each JSON data part (a later part overrides). A text part is the 41 purpose only when purpose is still empty. role must be ROLE_USER. File parts 42 (raw, url) return -32005. taskId and a non-empty referenceTaskIds return -32004. 43 historyLength, returnImmediately, extensions, and the A2A-Extensions header are 44 ignored and are not stored. The JSON-RPC envelope, messageId, and contextId are 45 not stored. contextId is echoed when the client sent one, otherwise a new id is 46 returned and forgotten. 47 48 The introduce door still applies its own caps, the anonymous-mode refusal, the 49 rate limit, and the daily cap. Those replies are JSON-RPC errors here. HTTP 50 status is 200 for every JSON-RPC body, including errors, with the error in the 51 body. Cache-Control stays no-store. 52 """ 53 54 import json 55 import secrets 56 from urllib.parse import parse_qs, urlsplit 57 58 # The introduce door's field names. consent is checked by that door, not copied 59 # into the stored record. 60 INTRO_FIELDS = ("kind", "name", "org", "contact", "github", "origin", "purpose", 61 "homepage", "framework", "model", "human") 62 63 SEND_METHODS = frozenset({"SendMessage", "message/send"}) 64 65 # code, message, reason. Legacy slash names are the same operations. 66 UNSUPPORTED = { 67 "SendStreamingMessage": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), 68 "message/stream": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), 69 "SubscribeToTask": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), 70 "tasks/resubscribe": (-32004, "Unsupported operation", "STREAMING_NOT_SUPPORTED"), 71 "GetTask": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), 72 "tasks/get": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), 73 "ListTasks": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), 74 "tasks/list": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), 75 "CancelTask": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), 76 "tasks/cancel": (-32004, "Unsupported operation", "TASKS_NOT_SUPPORTED"), 77 "CreateTaskPushNotificationConfig": (-32003, "Push notifications are not supported", 78 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 79 "tasks/pushNotificationConfig/set": (-32003, "Push notifications are not supported", 80 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 81 "GetTaskPushNotificationConfig": (-32003, "Push notifications are not supported", 82 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 83 "tasks/pushNotificationConfig/get": (-32003, "Push notifications are not supported", 84 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 85 "ListTaskPushNotificationConfigs": (-32003, "Push notifications are not supported", 86 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 87 "tasks/pushNotificationConfig/list": (-32003, "Push notifications are not supported", 88 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 89 "DeleteTaskPushNotificationConfig": (-32003, "Push notifications are not supported", 90 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 91 "tasks/pushNotificationConfig/delete": (-32003, "Push notifications are not supported", 92 "PUSH_NOTIFICATIONS_NOT_SUPPORTED"), 93 "GetExtendedAgentCard": (-32004, "Unsupported operation", "EXTENDED_AGENT_CARD_NOT_SUPPORTED"), 94 "agent/getAuthenticatedExtendedCard": (-32004, "Unsupported operation", 95 "EXTENDED_AGENT_CARD_NOT_SUPPORTED"), 96 } 97 98 OUTPUT_MODES = frozenset({"text/plain", "application/json"}) 99 MAX_PARTS = 8 100 MAX_ID = 200 101 102 103 def error_info(reason, metadata=None): 104 info = { 105 "@type": "type.googleapis.com/google.rpc.ErrorInfo", 106 "reason": reason, 107 "domain": "a2a-protocol.org", 108 } 109 if metadata: 110 info["metadata"] = {str(k): str(v) for k, v in metadata.items()} 111 return [info] 112 113 114 def bad_request(field, description): 115 return [{ 116 "@type": "type.googleapis.com/google.rpc.BadRequest", 117 "fieldViolations": [{"field": field, "description": description}], 118 }] 119 120 121 def error_obj(rid, code, message, data=None): 122 err = {"code": code, "message": message} 123 if data is not None: 124 err["data"] = data 125 return {"jsonrpc": "2.0", "id": rid, "error": err} 126 127 128 def valid_id(rid): 129 if rid is None or isinstance(rid, str): 130 return True 131 # bool is a subclass of int. JSON-RPC ids are strings, numbers, or null. 132 if type(rid) is bool: 133 return False 134 return type(rid) in (int, float) 135 136 137 def controls(text): 138 return any((ord(c) < 32 and c not in "\n\t") or ord(c) == 127 for c in text) 139 140 141 def _header(headers, name): 142 """(value, present). Missing is not the same as an empty value.""" 143 if headers is None: 144 return None, False 145 for key in headers.keys(): 146 if str(key).lower() == name.lower(): 147 return headers.get(key), True 148 return None, False 149 150 151 def version_token(headers, path=""): 152 """The version this door must apply. 153 154 Spec 3.6.2: an empty value is 0.3. Spec 3.6.1: an empty header is assumed 155 to be 0.3, and a client may send A2A-Version as a query parameter instead 156 of the header. A missing header is that empty case, so it is 0.3 unless 157 the query parameter is present. This door speaks 1.0 only. 158 """ 159 raw, present = _header(headers, "A2A-Version") 160 if not present and path: 161 query = parse_qs(urlsplit(path).query, keep_blank_values=True) 162 if "A2A-Version" in query: 163 raw = query["A2A-Version"][0] if query["A2A-Version"] else "" 164 present = True 165 if not present or raw is None or str(raw).strip() == "": 166 return "0.3" 167 return str(raw).strip() 168 169 170 def version_error(headers, path=""): 171 """None when the call is version 1.0. Otherwise VersionNotSupportedError.""" 172 version = version_token(headers, path) 173 if version == "1.0": 174 return None 175 return (-32009, "Version is not supported", 176 error_info("VERSION_NOT_SUPPORTED", {"version": version})) 177 178 179 def parse(raw): 180 """('ok', request) or ('error', response object).""" 181 if not isinstance(raw, (bytes, bytearray)): 182 return "error", error_obj(None, -32700, "Invalid JSON payload") 183 try: 184 req = json.loads(raw.decode("utf-8")) 185 except (UnicodeDecodeError, ValueError): 186 return "error", error_obj(None, -32700, "Invalid JSON payload") 187 if not isinstance(req, dict): 188 return "error", error_obj(None, -32600, "Request payload validation error") 189 rid = req.get("id", None) 190 if "id" not in req or not valid_id(rid): 191 # A notification, or an id this door will not echo. No silent store. 192 return "error", error_obj(None, -32600, "Request payload validation error") 193 if req.get("jsonrpc") != "2.0" or not isinstance(req.get("method"), str) or not req["method"]: 194 return "error", error_obj(rid, -32600, "Request payload validation error") 195 if "params" in req and not isinstance(req["params"], dict): 196 return "error", error_obj(rid, -32602, "Invalid parameters", 197 bad_request("params", "params must be an object")) 198 return "ok", req 199 200 201 def check_config(params): 202 cfg = params.get("configuration") 203 if cfg is None: 204 return None 205 if not isinstance(cfg, dict): 206 return (-32602, "Invalid parameters", bad_request("configuration", "configuration must be an object")) 207 push = cfg.get("taskPushNotificationConfig") 208 if push is not None: 209 return (-32003, "Push notifications are not supported", 210 error_info("PUSH_NOTIFICATIONS_NOT_SUPPORTED")) 211 modes = cfg.get("acceptedOutputModes") 212 if modes is None: 213 return None 214 if not isinstance(modes, list) or not modes or not all(isinstance(m, str) for m in modes): 215 return (-32602, "Invalid parameters", 216 bad_request("configuration.acceptedOutputModes", "acceptedOutputModes must be media types")) 217 if OUTPUT_MODES.isdisjoint(modes): 218 return (-32005, "Content type is not supported", 219 error_info("CONTENT_TYPE_NOT_SUPPORTED", {"acceptedOutputModes": ",".join(modes)})) 220 return None 221 222 223 def build_intro(message): 224 """('ok', intro dict, context id) or ('error', code, message, data).""" 225 if not isinstance(message, dict): 226 return ("error", -32602, "Invalid parameters", 227 bad_request("message", "message is required")) 228 if message.get("role") != "ROLE_USER": 229 return ("error", -32602, "Invalid parameters", 230 bad_request("message.role", "role must be ROLE_USER")) 231 mid = message.get("messageId") 232 if not isinstance(mid, str) or not mid.strip() or len(mid) > MAX_ID or controls(mid): 233 return ("error", -32602, "Invalid parameters", 234 bad_request("message.messageId", "messageId must be text")) 235 if message.get("taskId") or message.get("referenceTaskIds"): 236 return ("error", -32004, "Unsupported operation", 237 error_info("TASKS_NOT_SUPPORTED")) 238 ctx = message.get("contextId") 239 if ctx is None: 240 context_id = "ctx_" + secrets.token_hex(16) 241 elif not isinstance(ctx, str) or not ctx.strip() or len(ctx) > MAX_ID or controls(ctx): 242 return ("error", -32602, "Invalid parameters", 243 bad_request("message.contextId", "contextId must be text")) 244 else: 245 context_id = ctx 246 parts = message.get("parts") 247 if not isinstance(parts, list) or not parts or len(parts) > MAX_PARTS: 248 return ("error", -32602, "Invalid parameters", 249 bad_request("message.parts", "Send one to eight parts")) 250 meta = message.get("metadata", {}) 251 if meta is None: 252 meta = {} 253 if not isinstance(meta, dict): 254 return ("error", -32602, "Invalid parameters", 255 bad_request("message.metadata", "metadata must be an object")) 256 intro = dict(meta) 257 texts = [] 258 for part in parts: 259 if not isinstance(part, dict): 260 return ("error", -32602, "Invalid parameters", 261 bad_request("message.parts", "each part must be an object")) 262 present = [k for k in ("text", "raw", "url", "data") if k in part] 263 if len(present) != 1: 264 return ("error", -32602, "Invalid parameters", 265 bad_request("message.parts", "a part needs exactly one of text, raw, url, data")) 266 kind = present[0] 267 media = part.get("mediaType") 268 if kind in ("raw", "url"): 269 return ("error", -32005, "Content type is not supported", 270 error_info("CONTENT_TYPE_NOT_SUPPORTED")) 271 if kind == "text": 272 if not isinstance(part["text"], str): 273 return ("error", -32602, "Invalid parameters", 274 bad_request("message.parts", "text must be a string")) 275 if media is not None and media != "text/plain": 276 return ("error", -32005, "Content type is not supported", 277 error_info("CONTENT_TYPE_NOT_SUPPORTED", {"mediaType": media})) 278 if part["text"].strip(): 279 texts.append(part["text"].strip()) 280 else: 281 if media is not None and media != "application/json": 282 return ("error", -32005, "Content type is not supported", 283 error_info("CONTENT_TYPE_NOT_SUPPORTED", {"mediaType": media})) 284 if not isinstance(part["data"], dict): 285 return ("error", -32602, "Invalid parameters", 286 bad_request("message.parts", "a data part must be a JSON object")) 287 intro.update(part["data"]) 288 purpose = intro.get("purpose") 289 if texts and (not isinstance(purpose, str) or not purpose.strip()): 290 intro["purpose"] = "\n".join(texts) 291 return "ok", intro, context_id 292 293 294 def map_intro(status, body): 295 err = body.get("error") if isinstance(body, dict) else None 296 msg = body.get("message") if isinstance(body, dict) and isinstance(body.get("message"), str) else "Invalid parameters" 297 if err == "consent_required": 298 return -32602, "Invalid parameters", bad_request("message.metadata.consent", msg) 299 if err in ("invalid", "too_long"): 300 return -32602, "Invalid parameters", bad_request("message", msg) 301 if err == "anonymous": 302 return -32602, "Invalid parameters", bad_request("X-Allen-Anonymous", msg) 303 # Spec 3.3.2 names "rate limit exceeded" as an example of -32603. The 304 # -32001 to -32009 table has no rate-limit code, so this stays -32603. 305 if err == "rate": 306 return -32603, "Internal error", error_info("RATE_LIMITED", {"message": msg}) 307 if err == "busy": 308 return -32603, "Internal error", error_info("BUSY", {"message": msg}) 309 if err == "not_found": 310 return -32603, "Internal error", error_info("INTRODUCTION_DOOR_UNAVAILABLE") 311 return -32603, "Internal error", error_info("INTRODUCTION_FAILED", {"status": status}) 312 313 314 def result_message(body, context_id): 315 data = {k: body[k] for k in ("id", "stored", "delete", "key") if k in body} 316 return {"message": { 317 "role": "ROLE_AGENT", 318 "messageId": "m_" + secrets.token_hex(16), 319 "contextId": context_id, 320 "parts": [ 321 {"text": "Introduction stored.", "mediaType": "text/plain"}, 322 {"data": data, "mediaType": "application/json"}, 323 ], 324 }} 325 326 327 def dispatch(raw, headers, accept, path=""): 328 """One JSON-RPC call. accept(intro) is the introduce door. 329 330 Returns (http_status, object, extra_headers). This function does not write 331 storage. accept does, and only when the introduce door stores a record. 332 http_status is 200. The handler adds Cache-Control: no-store. 333 """ 334 kind, parsed = parse(raw) 335 if kind == "error": 336 return 200, parsed, None 337 ver = version_error(headers, path) 338 if ver: 339 return 200, error_obj(parsed["id"], ver[0], ver[1], ver[2]), None 340 method = parsed["method"] 341 if method not in SEND_METHODS: 342 if method in UNSUPPORTED: 343 code, message, reason = UNSUPPORTED[method] 344 return 200, error_obj(parsed["id"], code, message, 345 error_info(reason, {"method": method})), None 346 return 200, error_obj(parsed["id"], -32601, "Method not found", 347 error_info("METHOD_NOT_FOUND", 348 {"method": method, "supported": "SendMessage"})), None 349 params = parsed.get("params") or {} 350 cfg = check_config(params) 351 if cfg: 352 return 200, error_obj(parsed["id"], cfg[0], cfg[1], cfg[2]), None 353 built = build_intro(params.get("message")) 354 if built[0] == "error": 355 return 200, error_obj(parsed["id"], built[1], built[2], built[3]), None 356 status, body, retry = accept(built[1]) 357 extra = {"Retry-After": str(retry)} if retry else None 358 if status == 200 and isinstance(body, dict) and body.get("stored") is True: 359 return 200, {"jsonrpc": "2.0", "id": parsed["id"], "result": result_message(body, built[2])}, extra 360 code, message, data = map_intro(status, body) 361 return 200, error_obj(parsed["id"], code, message, data), extra