From a59847dffaf2f82c100930d4da770152633e41e8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:41:26 -0500 Subject: [PATCH 01/18] wip: handoff core --- packages/flow/openadapt_flow/handoff.py | 457 ++++++++++++++++++++++++ 1 file changed, 457 insertions(+) create mode 100644 packages/flow/openadapt_flow/handoff.py diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py new file mode 100644 index 0000000000..f3b8ad2404 --- /dev/null +++ b/packages/flow/openadapt_flow/handoff.py @@ -0,0 +1,457 @@ +"""Agent-to-agent handoffs: a payload with the run's receipt attached. + +One agent hands a task or a result to another. The receipt for the run that +produced it (``record/run/v1``, see :mod:`openadapt_types.receipt`) travels +with it. The receiving agent verifies the receipt against keys *it* pins and +gets a verdict that says exactly what the signature does and does not prove. + +The same document works over any channel: + +* **Inline**: one JSON document (``openadapt.handoff/v1``) holding the payload + and the receipt. It is the body of an HTTP request or webhook, an MCP tool + result, or an A2A artifact part. +* **Detached**: the payload stays a file (an email attachment, a shared + folder), and ``.handoff.json`` beside it holds the payload's SHA-256 + and the receipt. + +What the verdict says, and why: + +* A valid signature proves **who signed** the receipt (the role comes from + the verifier's pinned registry, never from the document) and that the + receipt is unchanged. It does not prove the receipt's claims are true. +* The receipt signs the run (its report and bundle), not the handoff payload. + The payload counts as **bound** only when its SHA-256 equals a signed + subject digest. Otherwise anyone could staple this receipt to another + payload, and the verdict says so. +* A confirmation line counts as **independent of the sender** only when it + was read from the other party's system (``read_method`` ``portal_read_back`` + or ``api``). Everything else is the sender's own word. + +The handoff wrapper itself is not signed. The private openings file +(``receipt.private.json``) never travels; :func:`make_handoff` refuses it. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +SCHEMA = "openadapt.handoff/v1" +VERDICT_SCHEMA = "openadapt.handoff-verdict/v1" +MEDIA_TYPE = "application/vnd.openadapt.handoff+json" +#: The draft extension URI (docs/HANDOFF_RECEIPTS.md). An identifier only. +EXTENSION_URI = "https://openadapt.ai/extensions/handoff-receipt/v1" +DETACHED_SUFFIX = ".handoff.json" +#: Largest inline payload, in bytes. A bigger one goes detached. +MAX_INLINE_BYTES = 1_048_576 +#: Read methods that look at the other party's system, not the sender's. +INDEPENDENT_READ_METHODS = frozenset({"portal_read_back", "api"}) + +WHAT_A_SIGNATURE_PROVES = ( + "A valid signature proves who signed this receipt and that it has not " + "changed since. It does not prove that what the receipt says is true." +) +NOT_BOUND = ( + "The receipt signs the run's report, not this payload. Nothing ties this " + "payload to the receipt: anyone could attach the same receipt to another " + "payload." +) + + +class HandoffError(ValueError): + """A handoff that can't be built (never a verification result).""" + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _canonical(value: Any) -> bytes: + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=False + ).encode("utf-8") + + +def _loads_strict(text: str | bytes) -> Any: + from openadapt_types.receipt import loads_strict + + return loads_strict(text) + + +def _check_receipt_document(receipt: Any) -> dict[str, Any]: + """Only an envelope or a public card may travel; never private openings.""" + from openadapt_types import receipt as r + + if not isinstance(receipt, Mapping): + raise HandoffError("the receipt is a JSON object") + if receipt.get("schema") == r.OPENINGS_SCHEMA or "payload_sha256" in receipt: + raise HandoffError( + "that is receipt.private.json, which never leaves this computer; " + "attach receipt.json or receipt.card.json" + ) + if not (r.is_receipt_envelope(receipt) or r.is_receipt_card(receipt)): + raise HandoffError("the receipt is a record/run/v1 envelope or card") + return dict(receipt) + + +def payload_bytes(payload: Any) -> tuple[bytes, str]: + """The exact bytes a payload's digest covers, and their media type. + + ``bytes`` are taken as they are. Any other value is JSON, digested in its + canonical form (sorted keys, compact separators, UTF-8). + """ + if isinstance(payload, (bytes, bytearray)): + return bytes(payload), "application/octet-stream" + return _canonical(payload), "application/json" + + +def make_handoff( + payload: Any, + receipt: Mapping[str, Any], + *, + name: Optional[str] = None, + media_type: Optional[str] = None, + detached: bool = False, +) -> dict[str, Any]: + """Attach ``receipt`` to ``payload`` as an ``openadapt.handoff/v1`` document. + + ``detached`` leaves the payload out and keeps only its digest, for a file + sent beside the document. + """ + data, default_type = payload_bytes(payload) + doc_payload: dict[str, Any] = { + "media_type": media_type or default_type, + "sha256": _sha256(data), + "size": len(data), + } + if name: + doc_payload["name"] = Path(name).name + if not detached: + if len(data) > MAX_INLINE_BYTES: + raise HandoffError( + "the payload is larger than 1 MiB; send it detached instead" + ) + if isinstance(payload, (bytes, bytearray)): + doc_payload["content_base64"] = base64.b64encode(data).decode("ascii") + else: + doc_payload["content"] = payload + return { + "schema": SCHEMA, + "payload": doc_payload, + "receipt": _check_receipt_document(receipt), + } + + +def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: + """Read a run's ``receipt.json`` (or its public card) for attaching.""" + from openadapt_types import receipt as r + + path = Path(run_dir) / (r.CARD_FILE if public else r.RECEIPT_FILE) + try: + return _check_receipt_document(_loads_strict(path.read_text("utf-8"))) + except FileNotFoundError: + raise HandoffError(f"no {path.name} in that run folder") from None + except (OSError, UnicodeDecodeError, ValueError) as exc: + if isinstance(exc, HandoffError): + raise + raise HandoffError(f"{path.name} is not a readable receipt") from None + + +# -- verification ---------------------------------------------------------------- + + +@dataclass +class Verdict: + """What a receiving agent may conclude from a handoff.""" + + #: ``intact``: every signature checked against a pinned key and the + #: receipt is well formed. ``refused``: anything else. + integrity: str + reason: Optional[str] = None + detail: str = "" + signer_roles: list[str] = field(default_factory=list) + signer_lines: list[str] = field(default_factory=list) + demo: bool = False + #: The receipt's outcome, copied, never upgraded. + outcome: Optional[str] = None + checks: dict[str, Any] = field(default_factory=dict) + payload: dict[str, Any] = field(default_factory=dict) + confirmations: list[dict[str, Any]] = field(default_factory=list) + confirmation_lines: list[str] = field(default_factory=list) + independent_confirmations: int = 0 + what_this_proves: list[str] = field(default_factory=list) + + @property + def ok(self) -> bool: + return self.integrity == "intact" + + def to_dict(self) -> dict[str, Any]: + return { + "schema": VERDICT_SCHEMA, + "integrity": self.integrity, + "reason": self.reason, + "detail": self.detail, + "signer_roles": list(self.signer_roles), + "signer_lines": list(self.signer_lines), + "demo": self.demo, + "outcome": self.outcome, + "checks": self.checks, + "payload": self.payload, + "confirmations": self.confirmations, + "confirmation_lines": list(self.confirmation_lines), + "independent_confirmations": self.independent_confirmations, + "what_this_proves": list(self.what_this_proves), + } + + +def _refused(reason: str, detail: str = "", line: Optional[str] = None) -> Verdict: + from openadapt_types.receipt import refusal_line + + return Verdict( + integrity="refused", + reason=reason, + detail=detail, + signer_lines=[line or refusal_line(reason)], + what_this_proves=[ + "Nothing: the receipt did not verify, so treat the handoff as an " + "unchecked claim." + ], + ) + + +_CHECK_NAMES = ("identity", "postconditions", "effects", "authorization") + + +def _checks(statement: Mapping[str, Any]) -> dict[str, Any]: + """Which checks passed and which were not checked, straight from the receipt.""" + predicate = statement.get("predicate") or {} + checks = predicate.get("checks") or {} + passed: list[str] = [] + incomplete: list[str] = [] + for name in _CHECK_NAMES: + count = checks.get(name) or {} + required, confirmed = count.get("required", 0), count.get("confirmed", 0) + if required and confirmed >= required: + passed.append(name) + elif required: + incomplete.append(name) + not_checked: list[str] = [] + for line in predicate.get("lines") or []: + for code in line.get("not_checked") or []: + if code not in not_checked: + not_checked.append(code) + return { + "passed": passed, + "incomplete": incomplete, + "not_checked": not_checked, + "writes": { + "confirmed": checks.get("lines_confirmed", 0), + "refuted": checks.get("lines_refuted", 0), + "not_checked": checks.get("lines_not_checked", 0), + }, + "counts": {name: dict(checks.get(name) or {}) for name in _CHECK_NAMES}, + } + + +def _confirmations(statement: Mapping[str, Any]) -> list[dict[str, Any]]: + """Each counterparty confirmation, marked independent from its read method. + + Independence is decided here, from the closed ``read_method`` the signed + statement carries, never from anything else in the handoff. + """ + out = [] + for item in (statement.get("predicate") or {}).get("confirmations") or []: + if not isinstance(item, Mapping): + continue + state = item.get("state") + read_method = item.get("read_method") + independent = read_method in INDEPENDENT_READ_METHODS and state in ( + "recorded_as_intended", + "recorded_differently", + ) + out.append( + { + "for_step": item.get("for_step"), + "system_kind": item.get("system_kind"), + "state": state, + "read_method": read_method, + "strength": item.get("strength"), + "differing_count": item.get("differing_count"), + "independent": independent, + } + ) + return out + + +def _confirmation_line(item: Mapping[str, Any]) -> str: + system = str(item.get("system_kind") or "other").replace("_", " ") + state = item.get("state") + if state == "recorded_as_intended": + text = f"Confirmed in the other party's system ({system}): recorded as intended" + elif state == "recorded_differently": + text = ( + f"Confirmed in the other party's system ({system}): recorded " + f"differently ({item.get('differing_count') or 0} field(s) differ)" + ) + elif state == "acknowledged": + text = f"The other party ({system}) acknowledged it; not read back" + else: + text = f"Sent to the other party ({system}); no answer recorded" + if not item.get("independent"): + text += ". Reported by the sender, not read independently" + return text + + +def _payload_verdict( + doc_payload: Mapping[str, Any], + statement: Mapping[str, Any], + supplied: Optional[bytes], +) -> tuple[dict[str, Any], Optional[str]]: + """Whether the payload is what the document says, and whether it is signed.""" + declared = doc_payload.get("sha256") + actual: Optional[str] = None + if supplied is not None: + actual = _sha256(supplied) + elif "content_base64" in doc_payload: + try: + actual = _sha256( + base64.b64decode(str(doc_payload["content_base64"]), validate=True) + ) + except ValueError: + return {}, "the inline payload is not base64" + elif "content" in doc_payload: + actual = _sha256(_canonical(doc_payload["content"])) + if actual is not None and actual != declared: + return {}, "the payload does not match its digest in the handoff" + subjects = { + s.get("digest", {}).get("sha256"): s.get("name") + for s in statement.get("subject") or [] + if isinstance(s, Mapping) + } + subject = subjects.get(actual or declared) if (actual or declared) else None + result: dict[str, Any] = { + "sha256": declared, + "present": actual is not None, + "bound": subject is not None and actual is not None, + "bound_to": subject if actual is not None else None, + } + if result["bound"]: + result["note"] = f"The payload is the signed {subject} itself." + elif actual is None: + result["note"] = ( + "The payload was not supplied, so it could not be checked. " + NOT_BOUND + ) + else: + result["note"] = NOT_BOUND + return result, None + + +def verify_handoff( + document: Any, + registry: Sequence[Any], + *, + payload: Optional[bytes] = None, +) -> Verdict: + """Verify a handoff document's receipt against the receiver's pinned keys. + + ``registry`` is the receiver's own key list + (:func:`openadapt_types.receipt.parse_registry`). ``payload`` is the + detached file's bytes. Fails closed: anything unexpected is a refusal. + """ + from openadapt_types import receipt as r + + if isinstance(document, (bytes, str)): + try: + document = _loads_strict(document) + except (UnicodeDecodeError, ValueError): + return _refused("malformed", "the handoff is not JSON") + if not isinstance(document, Mapping) or document.get("schema") != SCHEMA: + return _refused( + "unknown_schema", + "not an openadapt.handoff/v1 document", + "Not verified: not a handoff document", + ) + if set(document) - {"schema", "payload", "receipt"}: + return _refused("malformed", "a handoff has schema, payload and receipt") + doc_payload = document.get("payload") + receipt = document.get("receipt") + if not isinstance(doc_payload, Mapping) or not isinstance(receipt, Mapping): + return _refused("malformed", "a handoff has a payload and a receipt object") + if receipt.get("schema") == r.OPENINGS_SCHEMA: + return _refused("malformed", "a handoff never carries private openings") + result = r.verify_receipt(receipt, registry) + if not result.ok or result.statement is None: + return _refused(str(result.reason or "malformed"), result.detail) + statement = result.statement + payload_result, problem = _payload_verdict(doc_payload, statement, payload) + if problem: + return _refused("payload_mismatch", problem, "Not verified: " + problem) + confirmations = _confirmations(statement) + lines = list(getattr(result, "confirmation_lines", ()) or ()) + if not lines: + lines = [_confirmation_line(c) for c in confirmations] + independent = sum(1 for c in confirmations if c["independent"]) + proves = [WHAT_A_SIGNATURE_PROVES] + if result.demo: + proves.append("A demo key signed it: it checks only inside that demo.") + if independent: + proves.append( + f"{independent} confirmation(s) were read back from the other " + "party's system, so they do not rest on the sender's word alone." + ) + else: + proves.append( + "No confirmation was read from the other party's system, so every " + "claim here rests on the signer's word." + ) + proves.append(payload_result["note"]) + return Verdict( + integrity="intact", + signer_roles=[s.role for s in result.signers], + signer_lines=list(result.signer_lines), + demo=result.demo, + outcome=result.outcome, + checks=_checks(statement), + payload=payload_result, + confirmations=confirmations, + confirmation_lines=lines, + independent_confirmations=independent, + what_this_proves=proves, + ) + + +def load_registry(path: Optional[Path] = None) -> list[Any]: + """The receiver's pinned keys: a registry file, or this computer's defaults.""" + if path is not None: + from openadapt_flow.receipt_record import load_role_registry + + return load_role_registry(Path(path)) + from openadapt_flow.receipt_record import local_registry + + return local_registry() + + +def detached_path(payload_path: Path) -> Path: + return Path(str(payload_path) + DETACHED_SUFFIX) + + +__all__ = [ + "DETACHED_SUFFIX", + "EXTENSION_URI", + "HandoffError", + "INDEPENDENT_READ_METHODS", + "MEDIA_TYPE", + "SCHEMA", + "VERDICT_SCHEMA", + "Verdict", + "detached_path", + "load_registry", + "make_handoff", + "payload_bytes", + "receipt_for_run", + "verify_handoff", +] From 76e1075304692fe6a00e2d052b07310debaf3544 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:56:38 -0500 Subject: [PATCH 02/18] feat: agent-to-agent handoffs with receipts, over MCP, HTTP, files and the A2A protocol openadapt handoff send/verify attaches a run's record/run/v1 receipt to what one agent hands another and verifies it on arrival against the receiver's pinned keys. The verdict states the signer role, integrity, checks passed and not checked, and counterparty confirmation lines, and always says a valid signature proves who signed, not that the claim is true. decide() accepts a claim only when the receiver's own record shows it. openadapt agent serve --handoffs adds get_handoff and verify_handoff over MCP. serve --a2a serves the same workflows over the A2A protocol 1.0 with the official a2a-sdk (new a2a extra), through the MCP server's own gate (agent/contract_call.py), with a draft handoff-receipt extension. --- CAPABILITIES.md | 3 + CHANGELOG.md | 11 + README.md | 20 + openadapt/cli.py | 26 + openadapt/cli_tasks.py | 1 + packages/agent/CHANGELOG.md | 7 + packages/agent/pyproject.toml | 23 +- packages/agent/tests/test_handoff_e2e.py | 503 +++++++++++++++ packages/agent/uv.lock | 153 ++++- packages/flow/CHANGELOG.md | 24 + packages/flow/docs/A2A.md | 81 +++ packages/flow/docs/HANDOFFS.md | 119 ++++ packages/flow/docs/HANDOFF_RECEIPTS.md | 256 ++++++++ .../06-give-agents-the-program/handoff.md | 1 + packages/flow/openadapt_flow/__main__.py | 4 + .../flow/openadapt_flow/agent/a2a_server.py | 571 ++++++++++++++++++ packages/flow/openadapt_flow/agent/bridge.py | 19 + packages/flow/openadapt_flow/agent/cli.py | 101 ++++ .../openadapt_flow/agent/contract_call.py | 94 +++ .../openadapt_flow/agent/handoff_tools.py | 134 ++++ packages/flow/openadapt_flow/agent/mcp.py | 37 +- packages/flow/openadapt_flow/cli_handoff.py | 221 +++++++ packages/flow/openadapt_flow/cli_tasks.py | 1 + packages/flow/openadapt_flow/handoff.py | 179 ++++-- packages/flow/pyproject.toml | 23 + packages/flow/tests/test_handoff.py | 328 ++++++++++ packages/flow/uv.lock | 149 ++++- pyproject.toml | 14 + uv.lock | 69 ++- 29 files changed, 3099 insertions(+), 73 deletions(-) create mode 100644 packages/agent/tests/test_handoff_e2e.py create mode 100644 packages/flow/docs/A2A.md create mode 100644 packages/flow/docs/HANDOFFS.md create mode 100644 packages/flow/docs/HANDOFF_RECEIPTS.md create mode 100644 packages/flow/docs/commands/06-give-agents-the-program/handoff.md create mode 100644 packages/flow/openadapt_flow/agent/a2a_server.py create mode 100644 packages/flow/openadapt_flow/agent/contract_call.py create mode 100644 packages/flow/openadapt_flow/agent/handoff_tools.py create mode 100644 packages/flow/openadapt_flow/cli_handoff.py create mode 100644 packages/flow/tests/test_handoff.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 1c71807699..cab5069740 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -313,6 +313,8 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main (#PR_NUMBER) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main (#PR_NUMBER) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; TCK_RESULT | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | @@ -443,6 +445,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. +- `handoff`: Hand a result to another agent with its run's receipt attached (inline, detached beside a file, or POSTed to a webhook), and verify one on arrival against your pinned keys: who signed, what was checked, and that a valid signature proves who signed, not that the claim is true. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** diff --git a/CHANGELOG.md b/CHANGELOG.md index 69a39e2c64..107fb06790 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,17 @@ ### Features +- **Agent-to-agent handoffs.** + - `openadapt handoff send` attaches a run's receipt to a result for + another agent: inline, detached beside a file, or POSTed to a webhook. + `openadapt handoff verify` checks one on arrival against your pinned keys + and says who signed it, what was checked, and that a valid signature + proves who signed, not that the claim is true. Also available as + `openadapt verify handoff`. + - `openadapt agent serve --handoffs` adds the same over MCP. + - `openadapt agent serve --a2a` serves workflows over the A2A (Agent2Agent) + protocol with an Agent Card. It needs the new `openadapt[a2a]` extra. + - **Receipts replace Seals.** A receipt is a signed, itemized record of one run: what it changed, how each change was checked, and who signed it. It doesn't grade the run. Every run, with any outcome, now writes `receipt.json` (a DSSE diff --git a/README.md b/README.md index dce82fc919..10f1fc5a1e 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,25 @@ and `openadapt verify effect` judges a write made by any agent or script against the system of record. [Connect an agent](https://docs.openadapt.ai/how-to/connect-an-agent/) covers other clients. +### Hand results from agent to agent + +When one agent hands a result to another, the run's signed receipt goes with +it, and the receiving agent verifies it against keys it pins: + +```bash +openadapt handoff send result.json --run RUN_DIR --out result.handoff.json +openadapt handoff verify result.handoff.json --keys trusted-keys.json +``` + +The verdict says who signed, which checks passed and which were not checked, +and any change confirmed in the other party's own system. A valid signature +proves who signed, not that the claim is true. Handoffs travel over MCP +(`serve --handoffs`), HTTP and webhooks (`--post URL`), files and email +(`--detached`), and the A2A (Agent2Agent) protocol (`openadapt agent serve +--a2a`, with an Agent Card, after `pip install 'openadapt[a2a]'`). +[HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) +has the details. + ### Record a task by hand Recording works the same way on every surface; only the target differs: @@ -317,6 +336,7 @@ the right record is on screen, makes the entry, and reads the record back. - **Binds each approval to exactly what will be saved**, with one-tap answers on a paired phone. - **Repairs itself when the app changes**, probing a fix up to the save and asking a person to approve it (qualified on browser runs and end to end on native macOS). - **Works as a safety layer under any agent**: MCP tools, a guarded save, Agent Skills and a CLI. +- **Hands results from agent to agent with their receipts**, over MCP, HTTP, files and the A2A protocol, and verifies a handoff on arrival. - **Runs locally**: no calls to a hosted AI model on healthy runs, personal and health data redacted, signed receipts. [CAPABILITIES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/CAPABILITIES.md) has the evidence and code for each. diff --git a/openadapt/cli.py b/openadapt/cli.py index cae0993eb0..ba80cc19f4 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1908,6 +1908,32 @@ def agent(command_ctx: click.Context) -> None: sys.exit(int(agent_main(list(command_ctx.args)) or 0)) +@main.command( + "handoff", + context_settings={ + "ignore_unknown_options": True, + "allow_extra_args": True, + "help_option_names": [], + }, +) +@click.pass_context +def handoff(command_ctx: click.Context) -> None: + """Hand a result to another agent with its run's receipt, and verify one. + + `send FILE --run RUN_DIR` attaches the run's receipt (inline, `--detached` + beside the file, or `--post URL` to a webhook). `verify FILE.handoff.json` + checks it against your pinned keys and says who signed it, what was + checked, and that a valid signature proves who signed, not that the claim + is true. Also available as `openadapt verify handoff`. + """ + _require_supported_python() + args = list(command_ctx.args) + if args[:1] in ([], ["-h"], ["--help"]): + click.echo(command_ctx.get_help()) + sys.exit(0 if args else 2) + sys.exit(_invoke_flow(["handoff", *args])) + + @main.command( "receipt", context_settings={ diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index c43bbb993c..c5885f85d0 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -83,6 +83,7 @@ "push": "workflow push", "qualify": "qualify", "receipt": "verify receipt", + "handoff": "verify handoff", "reconcile": "verify reconcile", "record": "record", "redact-report": "inspect redact-report", diff --git a/packages/agent/CHANGELOG.md b/packages/agent/CHANGELOG.md index 926c3607a4..4932c46388 100644 --- a/packages/agent/CHANGELOG.md +++ b/packages/agent/CHANGELOG.md @@ -2,6 +2,13 @@ Releases up to v2.2.0 are recorded in the [openadapt-agent repository](https://github.com/OpenAdaptAI/openadapt-agent/blob/main/CHANGELOG.md). +## Unreleased + +- New `a2a` extra for `openadapt-agent serve --a2a`, the A2A (Agent2Agent) + protocol adapter in openadapt-flow (docs/A2A.md). `--handoffs` adds + `get_handoff` and `verify_handoff`. Both need an openadapt-flow that has + them. + ## v2.2.2 (2026-11-14) - Accept `openadapt-flow` 3.x. Flow 3 moved its vision stack to the `vision` diff --git a/packages/agent/pyproject.toml b/packages/agent/pyproject.toml index 1804ffd445..2b6284d37b 100644 --- a/packages/agent/pyproject.toml +++ b/packages/agent/pyproject.toml @@ -26,7 +26,21 @@ classifiers = [ "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Software Development :: Libraries :: Python Modules", ] -keywords = ["mcp", "agent-skills", "gui", "automation", "workflow", "openadapt", "ai-agents", "ehr", "rpa"] +keywords = [ + "mcp", + "a2a", + "agent2agent", + "agent-card", + "agent-handoff", + "agent-skills", + "gui", + "automation", + "workflow", + "openadapt", + "ai-agents", + "ehr", + "rpa", +] dependencies = [ # Governed workflow compiler/runtime this package bridges. Execution @@ -66,6 +80,13 @@ repair-screens = [ # it, scrubbed_only and ask_each_time share no screen. "openadapt-privacy[presidio]>=1.1.2", ] +# `openadapt-agent serve --a2a`: the A2A (Agent2Agent) protocol adapter. +# Listed directly so it resolves the same whichever Flow release is +# installed; keep in step with openadapt-flow's a2a extra. +a2a = [ + "a2a-sdk[http-server]>=1.3.1,<2", + "uvicorn>=0.29", +] tutorial = [ # The sandbox's real engine drives MockMed through Flow's tutorial entry # query, added in openadapt-flow 1.29.0. Older Flow falls back to the diff --git a/packages/agent/tests/test_handoff_e2e.py b/packages/agent/tests/test_handoff_e2e.py new file mode 100644 index 0000000000..940fcc4e0f --- /dev/null +++ b/packages/agent/tests/test_handoff_e2e.py @@ -0,0 +1,503 @@ +"""End to end: a program run hands its receipt to another agent over MCP and A2A. + +The run goes through the governed runner with Flow's ``openadapt-flow run`` +process stubbed (as everywhere in this suite), and then Flow's real receipt +writer (``write_receipt_record``) signs the run's report.json with a +throwaway key, exactly as Flow's run hook does after every run. The A2A side +uses the official ``a2a-sdk`` client against our server over real HTTP on +127.0.0.1. + +Covered: a real run's receipt in the A2A artifact and the MCP tool result; +verification of a good, a tampered, an unknown-signer and a swapped-payload +handoff; the A2A and MCP gates refusing the same things; no browser Origin +or foreign Host; the extensions header echo; and a follow-up message that +can't approve a run waiting for a person. +""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import socket +import threading +import time +import uuid +from pathlib import Path + +import pytest +from conftest import FlowCliStub + +pytest.importorskip("a2a.server.routes") +pytest.importorskip("uvicorn") +pytest.importorskip("cryptography") + +import httpx # noqa: E402 +import uvicorn # noqa: E402 +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_types import receipt as r # noqa: E402 + +import openadapt_agent.runner as runner_mod # noqa: E402 +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow.agent import a2a_server # noqa: E402 +from openadapt_flow.agent.bridge import AgentBridge # noqa: E402 +from openadapt_flow.agent.handoff_tools import HandoffTools # noqa: E402 +from openadapt_flow.agent.mcp import build_server # noqa: E402 +from openadapt_flow.receipt_record import write_receipt_record # noqa: E402 +from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402 + +WRITE_REPORT_RESULTS = [ + {"step_id": "s1", "intent": "Open the patient chart", "ok": True}, + { + "step_id": "s2", + "intent": "Type the triage note", + "ok": True, + "effect_verified": True, + "postconditions_ok": True, + }, +] + + +class ReceiptWritingStub(FlowCliStub): + """`openadapt-flow run`, stubbed; then Flow's real receipt writer runs.""" + + def __init__(self, signer, **kwargs): + super().__init__(**kwargs) + self.signer = signer + + def __call__(self, cmd, *args, **kwargs): + done = super().__call__(cmd, *args, **kwargs) + run_dir = Path(cmd[cmd.index("--run-dir") + 1]) + if (run_dir / "report.json").is_file(): + write_receipt_record(run_dir, signer=self.signer, flow_version="3.4.0") + return done + + +def _registry(*signers): + return r.parse_registry( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [{**s.registry_entry(), "role": "this_computer"} for s in signers], + } + ) + + +@pytest.fixture() +def signer(): + return SoftwareSigner(Ed25519PrivateKey.generate(), "generated") + + +@pytest.fixture() +def bridge(monkeypatch, bundles_root, runner_config, success_report, signer): + report = dict(success_report, results=WRITE_REPORT_RESULTS, started_at="2026-11-21T01:02:03Z") + monkeypatch.setattr( + runner_mod, "_run_flow_process", ReceiptWritingStub(signer, exit_code=0, report=report) + ) + bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") + bridge.handoffs = HandoffTools(registry=_registry(signer)) + return bridge + + +def _free_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +@pytest.fixture() +def a2a_url(bridge): + config = a2a_server.A2AConfig(port=_free_port()) + server = uvicorn.Server( + uvicorn.Config( + a2a_server.build_app(bridge, config), + host=config.host, + port=config.port, + log_level="warning", + ) + ) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + deadline = time.monotonic() + 15 + while not server.started: + if time.monotonic() > deadline: + raise RuntimeError("the A2A server did not start") + time.sleep(0.05) + try: + yield config.base_url + finally: + server.should_exit = True + thread.join(timeout=10) + + +def _message(data, *, task_id=None, context_id=None): + from a2a.helpers.proto_helpers import new_data_part + from a2a.types import Message, Role + + message = Message( + role=Role.ROLE_USER, message_id=str(uuid.uuid4()), parts=[new_data_part(data)] + ) + if task_id: + message.task_id = task_id + if context_id: + message.context_id = context_id + return message + + +async def _send(url, data, **ids): + """Send one message with the official SDK client; return the final task.""" + from a2a.client import ClientConfig, create_client + from a2a.types import SendMessageRequest + + client = await create_client(url, client_config=ClientConfig(streaming=False)) + try: + task = None + async for event in client.send_message( + SendMessageRequest(message=_message(data, **ids)) + ): + if event.HasField("task"): + task = event.task + assert task is not None + return task + finally: + await client.close() + + +def _handoff_from(task): + from google.protobuf.json_format import MessageToDict + + for artifact in task.artifacts: + for part in artifact.parts: + if part.HasField("raw") and part.media_type == h.MEDIA_TYPE: + assert h.EXTENSION_URI in artifact.extensions + return json.loads(part.raw.decode("utf-8")) + raise AssertionError(f"no handoff part in {MessageToDict(task)}") + + +def _result_from(task): + from google.protobuf.json_format import MessageToDict + + for artifact in task.artifacts: + for part in artifact.parts: + if part.HasField("data"): + return MessageToDict(part.data) + raise AssertionError("no data part") + + +def _verdict_from(task): + return _result_from(task) + + +def _tampered(doc): + bad = json.loads(json.dumps(doc)) + statement = json.loads(base64.b64decode(bad["receipt"]["payload"])) + statement["predicate"]["model_calls"] = 9 + bad["receipt"]["payload"] = base64.b64encode(r.canonical_json(statement).encode()).decode() + return bad + + +def test_a2a_agent_card_declares_skills_interfaces_and_the_extension(a2a_url, bridge): + card = httpx.get(a2a_url + "/.well-known/agent-card.json").json() + assert card["name"] == "OpenAdapt" + skills = {s["id"] for s in card["skills"]} + assert "verify_handoff" in skills and next(iter(bridge.catalog)) in skills + bindings = {(i["protocolBinding"], i["protocolVersion"]) for i in card["supportedInterfaces"]} + assert bindings == {("JSONRPC", "1.0"), ("HTTP+JSON", "1.0")} + (extension,) = card["capabilities"]["extensions"] + assert extension["uri"] == h.EXTENSION_URI + assert extension.get("required", False) is False + assert extension["params"]["handoff_schema"] == h.SCHEMA + # The card is built from the public projection: no step text, no paths. + text = json.dumps(card) + assert "Type the triage note" not in text and str(bridge.bundles_dir) not in text + + +def test_a2a_run_carries_its_receipt_and_verifies_good_tampered_unknown_and_swapped( + a2a_url, bridge, signer +): + workflow = next(iter(bridge.catalog)) + + async def scenario(): + task = await _send( + a2a_url, + {"skill": workflow, "inputs": {"note": "x"}, "request_id": "ref-a2a-0001"}, + ) + from a2a.types import TaskState + + assert task.status.state == TaskState.TASK_STATE_COMPLETED + result = _result_from(task) + assert result["outcome"] == "done" + handoff = _handoff_from(task) + assert handoff["schema"] == h.SCHEMA + assert r.is_receipt_envelope(handoff["receipt"]) + assert "openings" not in json.dumps(handoff["receipt"]) + + good = await _send(a2a_url, {"skill": "verify_handoff", "handoff": handoff}) + tampered = await _send( + a2a_url, {"skill": "verify_handoff", "handoff": _tampered(handoff)} + ) + restapled = h.make_handoff({"outcome": "done", "amount": 10**6}, handoff["receipt"]) + swapped = await _send(a2a_url, {"skill": "verify_handoff", "handoff": restapled}) + return handoff, _verdict_from(good), _verdict_from(tampered), _verdict_from(swapped) + + handoff, good, tampered, swapped = asyncio.run(scenario()) + assert good["integrity"] == "intact" + assert good["signer_roles"] == ["this_computer"] + assert good["outcome"] == "VERIFIED" + assert good["what_this_proves"][0] == h.WHAT_A_SIGNATURE_PROVES + assert tampered["integrity"] == "refused" and tampered["reason"] == "bad_signature" + assert swapped["integrity"] == "intact" and swapped["payload"]["bound"] is False + # Unknown signer: a receiver that pins other keys refuses the same handoff. + other = SoftwareSigner(Ed25519PrivateKey.generate(), "generated") + assert h.verify_handoff(handoff, _registry(other)).reason == "unknown_signer" + # And the receiver's own check agrees with the server's. + assert h.verify_handoff(handoff, _registry(signer)).ok + + +def test_a2a_unknown_signer_through_the_server(a2a_url, bridge, tmp_path): + other = SoftwareSigner(Ed25519PrivateKey.generate(), "generated") + run = tmp_path / "elsewhere" + run.mkdir() + (run / "report.json").write_text( + json.dumps({"execution_outcome": "VERIFIED", "results": WRITE_REPORT_RESULTS}) + ) + write_receipt_record(run, signer=other, flow_version="3.4.0") + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run)) + + async def scenario(): + return _verdict_from(await _send(a2a_url, {"skill": "verify_handoff", "handoff": doc})) + + verdict = asyncio.run(scenario()) + assert verdict["integrity"] == "refused" and verdict["reason"] == "unknown_signer" + assert verdict["signer_lines"] == [r.UNKNOWN_SIGNER_LINE] + + +def test_a2a_refuses_what_mcp_refuses(a2a_url, bridge): + workflow = next(iter(bridge.catalog)) + + async def scenario(): + from a2a.types import TaskState + + no_id = await _send(a2a_url, {"skill": workflow, "inputs": {"note": "x"}}) + attended = await _send(a2a_url, {"skill": "continue_attention", "attention_id": "a" * 24}) + approve = await _send( + a2a_url, + {"skill": "answer_approval_request", "request_id": "x", "approve": True}, + ) + for task in (no_id, attended, approve): + assert task.status.state == TaskState.TASK_STATE_FAILED + return [t.status.message.parts[0].text for t in (no_id, attended, approve)] + + no_id, attended, approve = asyncio.run(scenario()) + # The same schema refusal text MCP returns; nothing ran. + assert "request_id" in no_id and "Nothing ran" in no_id + # Attended and approval tools are never workflow names, so they are + # refused as unknown workflows by the same run_workflow schema. + assert "Nothing ran" in attended and "Nothing ran" in approve + records = list((Path(bridge.runner_config.runs_dir) / "openadapt-agent").rglob("*.json")) + assert not [p for p in records if "run-" in p.name] + + +def test_a2a_refuses_browsers_and_foreign_hosts_and_echoes_extensions(a2a_url): + card = a2a_url + "/.well-known/agent-card.json" + assert httpx.get(card, headers={"Origin": "https://evil.example"}).status_code == 403 + assert httpx.get(card, headers={"Host": "evil.example"}).status_code == 421 + echoed = httpx.get(card, headers={"A2A-Extensions": h.EXTENSION_URI}) + assert echoed.headers.get("a2a-extensions") == h.EXTENSION_URI + assert "a2a-extensions" not in httpx.get(card).headers + + +def test_a2a_off_loopback_needs_a_token_and_hides_workflows(bridge, tmp_path): + with pytest.raises(ValueError, match="needs --a2a-token-file"): + a2a_server.A2AConfig(host="0.0.0.0") + config = a2a_server.A2AConfig(host="0.0.0.0", port=_free_port(), token="t" * 40) + public = a2a_server.build_agent_card(bridge, config) + assert [s.id for s in public.skills] == ["verify_handoff"] + assert public.capabilities.extended_agent_card is True + assert "bearer" in public.security_schemes + extended = a2a_server.build_agent_card(bridge, config, extended=True) + assert next(iter(bridge.catalog)) in {s.id for s in extended.skills} + + from starlette.testclient import TestClient + + client = TestClient(a2a_server.build_app(bridge, config), base_url=f"http://0.0.0.0:{config.port}") + body = {"jsonrpc": "2.0", "id": 1, "method": "GetExtendedAgentCard", "params": {}} + assert client.post("/a2a/jsonrpc", json=body).status_code == 401 + wrong = client.post("/a2a/jsonrpc", json=body, headers={"Authorization": "Bearer nope"}) + assert wrong.status_code == 401 + ok = client.post( + "/a2a/jsonrpc", + json=body, + headers={"Authorization": "Bearer " + "t" * 40, "A2A-Version": "1.0"}, + ) + assert ok.status_code == 200 + + +def test_a2a_follow_up_cannot_approve_a_run_waiting_for_a_person( + monkeypatch, bundles_root, runner_config, halt_report, signer +): + monkeypatch.setattr( + runner_mod, "_run_flow_process", ReceiptWritingStub(signer, exit_code=1, report=halt_report) + ) + bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") + bridge.handoffs = HandoffTools(registry=_registry(signer)) + executor = a2a_server.OpenAdaptExecutor(bridge) + result = a2a_server.call_remote_tool( + bridge, + "run_workflow", + {"workflow": next(iter(bridge.catalog)), "inputs": {"note": "x"}, "request_id": "ref-hold-1"}, + ) + assert result["outcome"] == "needs_review" + assert a2a_server.task_state_for(result["outcome"]) == "TASK_STATE_INPUT_REQUIRED" + # A message on that task is mapped to get_run, whatever it says. + executor.runs["task-1"] = result["run_id"] + calls = [] + monkeypatch.setattr( + a2a_server, "call_remote_tool", lambda b, name, args: calls.append((name, args)) or result + ) + + class Queue: + events: list = [] + + async def enqueue_event(self, event): + self.events.append(event) + + class Context: + task_id, context_id = "task-1", "ctx-1" + current_task = object() + message = _message({"skill": "answer_approval_request", "approve": True}) + + asyncio.run(executor.execute(Context(), Queue())) + assert [name for name, _ in calls if name != "get_handoff"] == ["get_run"] + assert calls[0][1] == {"run_id": result["run_id"]} + + +def test_only_done_is_completed(): + assert a2a_server.task_state_for("done") == "TASK_STATE_COMPLETED" + for outcome in ("not_sure_if_saved", "did_not_run", None, "anything"): + assert a2a_server.task_state_for(outcome) == "TASK_STATE_FAILED" + + +def test_mcp_run_get_handoff_and_verify(bridge, signer, mcp_client): + server = build_server(bridge) + workflow = next(iter(bridge.catalog)) + + async def scenario(): + async with mcp_client(server) as client: + tools = {t.name for t in (await client.list_tools()).tools} + assert {"get_handoff", "verify_handoff"} <= tools + run = await client.call_tool( + "run_workflow", + {"workflow": workflow, "inputs": {"note": "x"}, "request_id": "ref-mcp-0001"}, + ) + run_id = json.loads(run.content[0].text)["run_id"] + got = await client.call_tool("get_handoff", {"run_id": run_id}) + handoff = json.loads(got.content[0].text) + good = await client.call_tool("verify_handoff", {"handoff": handoff}) + bad = await client.call_tool("verify_handoff", {"handoff": _tampered(handoff)}) + return handoff, json.loads(good.content[0].text), json.loads(bad.content[0].text) + + handoff, good, bad = asyncio.run(scenario()) + assert handoff["payload"]["content"]["outcome"] == "done" + assert good["integrity"] == "intact" and good["signer_roles"] == ["this_computer"] + assert bad["reason"] == "bad_signature" + # The same handoff verifies the same way outside the server. + assert h.verify_handoff(handoff, _registry(signer)).ok + + +def test_handoff_tools_are_off_unless_asked(bundles_root, runner_config): + bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") + names = {s.name for s in bridge.list_tool_specs()} + assert not names & {"get_handoff", "verify_handoff"} + + +def test_two_party_twenty_handoffs_receiver_reads_its_own_record(a2a_url, bridge, signer): + """The memo's kill criterion, measured. + + Party A (OpenAdapt over A2A) runs a program 20 times and hands party B a + claim about each record with the run's receipt, POSTed to B's inbox. B + pins A's key and reads its own record store (SQLite here) for every + claim. 10 claims are true, 5 are fabricated (no such record) and 5 + differ from B's record; all 20 carry a valid receipt from a trusted + signer, so the signature alone can't tell them apart. Pass: B accepts + zero fabricated or differing handoffs, rejects zero true ones, and its + check adds at most 2 s per handoff. + """ + import sqlite3 + from http.server import BaseHTTPRequestHandler, HTTPServer + + from openadapt_flow.cli_handoff import post_handoff + + db = sqlite3.connect(":memory:", check_same_thread=False) + db.execute("create table referral (ref text primary key, note text)") + kinds = ["true"] * 10 + ["fabricated"] * 5 + ["differing"] * 5 + workflow = next(iter(bridge.catalog)) + + def own_record(claim): + row = db.execute("select note from referral where ref = ?", (claim["ref"],)).fetchone() + if row is None: + return h.ReceiverRecord("not_found") + if row[0] != claim["fields"]["note"]: + return h.ReceiverRecord("recorded_differently", ("note",)) + return h.ReceiverRecord("recorded_as_intended") + + registry = _registry(signer) + decisions: list[tuple[str, str, float]] = [] + + class Inbox(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + body = self.rfile.read(int(self.headers["Content-Length"])) + started = time.perf_counter() + verdict = h.decide(body, registry, own_record) + spent = time.perf_counter() - started + kind = json.loads(body)["payload"]["content"]["kind"] + decisions.append((kind, verdict.decision, spent)) + self.send_response(202) + self.end_headers() + + inbox = HTTPServer(("127.0.0.1", 0), Inbox) + thread = threading.Thread(target=inbox.serve_forever, daemon=True) + thread.start() + + async def runs(): + out = [] + for i, kind in enumerate(kinds): + task = await _send( + a2a_url, + {"skill": workflow, "inputs": {"note": f"n{i}"}, "request_id": f"ref-2p-{i:04d}"}, + ) + out.append(_handoff_from(task)["receipt"]) + return out + + try: + receipts = asyncio.run(runs()) + for i, (kind, receipt) in enumerate(zip(kinds, receipts)): + ref, note = f"ref-2p-{i:04d}", f"n{i}" + # Stands in for the record party A's program wrote in B's system. + if kind == "true": + db.execute("insert into referral values (?, ?)", (ref, note)) + elif kind == "differing": + db.execute("insert into referral values (?, ?)", (ref, note + "-changed")) + claim = {"kind": kind, "ref": ref, "fields": {"note": note}} + status = post_handoff( + f"http://127.0.0.1:{inbox.server_address[1]}/inbox", h.make_handoff(claim, receipt) + ) + assert status == 202 + finally: + inbox.shutdown() + + assert len(decisions) == 20 + accepted_false = [d for d in decisions if d[0] != "true" and d[1] == "accept"] + rejected_true = [d for d in decisions if d[0] == "true" and d[1] != "accept"] + slowest = max(d[2] for d in decisions) + print( + f"two-party: 20 handoffs, accepted fabricated/differing {len(accepted_false)}, " + f"rejected true {len(rejected_true)}, slowest check {slowest * 1000:.1f} ms" + ) + assert accepted_false == [] and rejected_true == [] + assert slowest <= 2.0 + # Without its own read, the receiver never accepts on the signature. + unchecked = h.decide(h.make_handoff({"ref": "x"}, receipts[0]), registry) + assert unchecked.ok and unchecked.decision == "unchecked" diff --git a/packages/agent/uv.lock b/packages/agent/uv.lock index 5e334276bb..e9f4f03a92 100644 --- a/packages/agent/uv.lock +++ b/packages/agent/uv.lock @@ -16,6 +16,45 @@ required-markers = [ "python_full_version < '3.11' and sys_platform == 'win32'", ] +[[package]] +name = "a2a-sdk" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "culsans" }, + { name = "google-api-core" }, + { name = "googleapis-common-protos" }, + { name = "httpx" }, + { name = "json-rpc" }, + { name = "packaging" }, + { name = "protobuf" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e6/ca/90d8c95185a53be332772d5b28c42bf1586a2214e8bd937e769f3d566d7c/a2a_sdk-1.3.1.tar.gz", hash = "sha256:f18465fd040d2f75728c8ec915315ff25c072d271e6faeb9fa85a29ac36076ea", size = 456720, upload-time = "2026-11-17T10:51:19.721Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/76/baed78b223d9919a013c625ed853ab220c2c932050d8ded974a4eaaf969b/a2a_sdk-1.3.1-py3-none-any.whl", hash = "sha256:6073b8c04989609d087b9fed18ec1c8a13ae7e56246cf7a23c7c55a1a2a3b813", size = 299006, upload-time = "2026-11-17T10:51:17.787Z" }, +] + +[package.optional-dependencies] +http-server = [ + { name = "sse-starlette" }, + { name = "starlette" }, +] + +[[package]] +name = "aiologic" +version = "0.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sniffio" }, + { name = "typing-extensions" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/7a/d51f2fde1e8ae8a83431f8e97b7a71e9358cdb1d4d2ce6be387fa44d68de/aiologic-0.17.1.tar.gz", hash = "sha256:2e1b93b9e88ced318c2a63ad7b382688f40cbfe40e3d42258d49dc9c5aea179d", size = 252354, upload-time = "2026-06-27T20:41:33.25Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/d3/2d310b1b839014034dba0cba685e492df8a5c7ad32c19cab7e979eed6554/aiologic-0.17.1-py3-none-any.whl", hash = "sha256:c66b319830fedb7ca3d2b2125fa6f5b653f89418c2a27ea76f259ec5f00943c0", size = 161331, upload-time = "2026-06-27T20:41:31.877Z" }, +] + [[package]] name = "annotated-doc" version = "0.0.5" @@ -502,6 +541,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8e/b5/c2c5fce26f0ee40d21bafe7f191d29a34b35a65ac4fe8a1191d1983612e9/cryptography-50.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:c99c003e088647b8a5b7c145d6f78c335f6348332b62e142d411c4b63d1460b9", size = 3813796, upload-time = "2026-07-31T14:25:02.298Z" }, ] +[[package]] +name = "culsans" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiologic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/e3/49afa1bc180e0d28008ec6bcdf82a4072d1c7a41032b5b759b60814ca4b0/culsans-0.11.0.tar.gz", hash = "sha256:0b43d0d05dce6106293d114c86e3fb4bfc63088cfe8ff08ed3fe36891447fe33", size = 107546, upload-time = "2025-12-31T23:15:38.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/5d/9fb19fb38f6d6120422064279ea5532e22b84aa2be8831d49607194feda3/culsans-0.11.0-py3-none-any.whl", hash = "sha256:278d118f63fc75b9db11b664b436a1b83cc30d9577127848ba41420e66eb5a47", size = 21811, upload-time = "2025-12-31T23:15:37.189Z" }, +] + [[package]] name = "cycler" version = "0.12.1" @@ -661,6 +713,48 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3d/61/4161946319472aaa9b897bd18ad5108a5b10f5ebaa503d921a001ac4fff9/fonttools-4.67.0-py3-none-any.whl", hash = "sha256:4304f03ed7f4ba000a8dcc941ad854bfa52e2f3b6112b8f099b6f431cf98e701", size = 1213142, upload-time = "2026-10-14T13:20:26.258Z" }, ] +[[package]] +name = "google-api-core" +version = "2.44.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "google-auth" }, + { name = "googleapis-common-protos" }, + { name = "opentelemetry-api" }, + { name = "proto-plus" }, + { name = "protobuf" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/ef/63d89cb580f3a42c51db53b3d151352aa61b9c87ea8cfdd8d24ee6caa09d/google_api_core-2.44.0.tar.gz", hash = "sha256:5ab9a396965c1227d7dea4581e562b7018aa2bca96d2de0be5eb70dc9c8ab3a1", size = 288859, upload-time = "2026-11-05T18:39:43.265Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/73/4068d4b123d206f42e44d476b6ed4de773d81efc4e88101ff82e318b9a7a/google_api_core-2.44.0-py3-none-any.whl", hash = "sha256:8cb9ad8af28de9bc75121686d69b697ce0937e21fad2ad80c9a7e89f22b26e1f", size = 225627, upload-time = "2026-11-05T18:39:01.342Z" }, +] + +[[package]] +name = "google-auth" +version = "2.63.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "pyasn1-modules" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/04/0c/d09755ddb3fb67dcba41f35c04ba33377e5bcf73af6c022de33c3241532b/google_auth-2.63.0.tar.gz", hash = "sha256:f198b99dd49e81f96f54abce2c03d4dd28fb7e3c77702eb6ae1c5bf25435054c", size = 406302, upload-time = "2026-11-20T23:24:00.618Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/78/1c31250140faba4206c557b2bb16e8b1f1e42202864f0dbe0a8f4bc8dab2/google_auth-2.63.0-py3-none-any.whl", hash = "sha256:cbc065325f67511946d1a66672e4f47e71ed162ef1abd2bb8404ceec407c86ba", size = 270723, upload-time = "2026-11-20T23:23:59.008Z" }, +] + +[[package]] +name = "googleapis-common-protos" +version = "1.76.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/62/b6/bc095b23a3e0d978e75c8c18cabe4c11f791837410670e4486f0d539bfba/googleapis_common_protos-1.76.0.tar.gz", hash = "sha256:71db0e44a1d4c2dd024ebad44ca67129cc1e2892e4861df466764749d5ef8642", size = 156250, upload-time = "2026-10-22T23:43:36.263Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/6d/78dc67a9e779e594b49bf62604034d3a6aa428a55afc729cafda4b7333e1/googleapis_common_protos-1.76.0-py3-none-any.whl", hash = "sha256:59e13344a9f3651aa201a03e2bee815a3bf43a4baf1f9ff8a9b62a840ce25fac", size = 307707, upload-time = "2026-10-22T23:43:10.445Z" }, +] + [[package]] name = "greenlet" version = "3.5.5" @@ -837,6 +931,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, ] +[[package]] +name = "json-rpc" +version = "1.15.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854, upload-time = "2023-06-11T09:45:49.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450, upload-time = "2023-06-11T09:45:47.136Z" }, +] + [[package]] name = "jsonschema" version = "4.26.0" @@ -1319,6 +1422,10 @@ dependencies = [ ] [package.optional-dependencies] +a2a = [ + { name = "a2a-sdk", extra = ["http-server"] }, + { name = "uvicorn" }, +] dev = [ { name = "build" }, { name = "pytest" }, @@ -1333,6 +1440,7 @@ tutorial = [ [package.metadata] requires-dist = [ + { name = "a2a-sdk", extras = ["http-server"], marker = "extra == 'a2a'", specifier = ">=1.3.1,<2" }, { name = "anyio", specifier = ">=4.0" }, { name = "build", marker = "extra == 'dev'", specifier = ">=1.2.0" }, { name = "cryptography", specifier = ">=50.0.0" }, @@ -1343,8 +1451,9 @@ requires-dist = [ { name = "openadapt-privacy", extras = ["presidio"], marker = "extra == 'repair-screens'", specifier = ">=1.1.2" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.4.0" }, + { name = "uvicorn", marker = "extra == 'a2a'", specifier = ">=0.29" }, ] -provides-extras = ["dev", "repair-screens", "tutorial"] +provides-extras = ["dev", "repair-screens", "a2a", "tutorial"] [[package]] name = "openadapt-flow" @@ -1615,6 +1724,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9a/50/d8b64150837c8e02633cd9da8786a7a65663ba43a16a574a12e8d12468de/presidio_image_redactor-0.0.60-py3-none-any.whl", hash = "sha256:8e323334472f2bd7cba79f1b0b0d7739223c166fdbfa55dcd2f17dfea8795bb1", size = 34266, upload-time = "2026-07-22T07:54:40.813Z" }, ] +[[package]] +name = "proto-plus" +version = "1.29.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/46/70/783e33ffbb4466cc154a94f79b869b92a451e2bd45605054e68ff68b7af6/proto_plus-1.29.0.tar.gz", hash = "sha256:cfb4e62ad7e13dd18f346cabbda00cab39930d36a05791fd81ddb074d6ee884f", size = 58592, upload-time = "2026-09-29T19:26:15.963Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/05/a3ef5b1161498e7b5a2a60288a9cf41b9149e94555423a43ec536737ac1a/proto_plus-1.29.0-py3-none-any.whl", hash = "sha256:8acd070469a7aaf43f440b022ef9757c8cac1a9f866e933f59ae98669ddc6c8b", size = 50786, upload-time = "2026-09-29T19:25:50.409Z" }, +] + [[package]] name = "protobuf" version = "7.35.1" @@ -1630,6 +1751,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/19/c7/5f7c636ec43e0c545e28d1f1db71990108306f7bdcb89f069ba97e428e7f/protobuf-7.35.1-py3-none-any.whl", hash = "sha256:4bc97768d8fe4ad6743c8a19403e314511ed9f6d13205b687e52421c023ac1b9", size = 171659, upload-time = "2026-06-11T21:55:39.155Z" }, ] +[[package]] +name = "pyasn1" +version = "0.6.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/88/7e/3c0da41061a2021cac7cd524fd57092adbe5b515e8bf9005702e366802e2/pyasn1-0.6.5.tar.gz", hash = "sha256:6b11616a6bcf3a40e635f082bb232fa57b5e0dd7f517bd7ddd69ec3794508a47", size = 155152, upload-time = "2026-10-27T06:32:49.125Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/1f/3eefd5c84c35cae44549ce1c7f7e58f7945b34f5a6bce07a135438522073/pyasn1-0.6.5-py3-none-any.whl", hash = "sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587", size = 84807, upload-time = "2026-10-27T06:32:48.045Z" }, +] + +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a", size = 181259, upload-time = "2025-03-28T02:41:19.028Z" }, +] + [[package]] name = "pyclipper" version = "1.4.0" @@ -2342,6 +2484,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/79/60e14c5a19f39ebcf4fecd8ae8b0b01418ff5839bd7e66cf02b019d31826/smart_open-8.0.3-py3-none-any.whl", hash = "sha256:c3f67795b1a2bdb62dd9aca9ba4d4018e8f11e4188700b3246ea5ae049f65887", size = 73451, upload-time = "2026-10-12T20:21:48.353Z" }, ] +[[package]] +name = "sniffio" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372, upload-time = "2024-02-25T23:20:04.057Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, +] + [[package]] name = "spacy" version = "3.8.16" diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index c488559fb3..ae382fbc6c 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -19,6 +19,30 @@ ### Features +- Agent-to-agent handoffs. `openadapt-flow handoff send` attaches a run's + `record/run/v1` receipt to what one agent hands another: inline, detached + beside a file (`FILE.handoff.json`), or POSTed to a webhook. + `openadapt-flow handoff verify` checks one against the receiver's pinned + keys and returns a verdict (`openadapt.handoff-verdict/v1`). The verdict + gives the signer role, integrity, the checks passed and not checked, and + counterparty confirmation lines. It always says that a valid signature + proves who signed, not that the claim is true, and it marks the payload + unbound unless it is a signed subject. The private openings file never + travels (docs/HANDOFFS.md, docs/HANDOFF_RECEIPTS.md). +- `openadapt-agent serve --handoffs` adds the MCP tools `get_handoff` and + `verify_handoff`. `serve --a2a` serves the same workflows over the A2A + (Agent2Agent) protocol 1.0 with the official `a2a-sdk` (new `a2a` extra): + - an Agent Card at `/.well-known/agent-card.json`; + - JSON-RPC and HTTP+JSON bindings; + - one skill per workflow plus `verify_handoff`; + - the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. + + It listens on 127.0.0.1 by default, needs a bearer token on any other + address, and refuses browser `Origin` and unknown `Host` headers. Every A2A + call goes through the MCP server's gate (`agent/contract_call.py`). Person + confirmations are not served, and only `done` is `TASK_STATE_COMPLETED` + (docs/A2A.md). + - Dropdowns, searchable selects, type-aheads and native selects are recorded, compiled and run as one model, a choice (`OptionChoice` on a `SELECT_OPTION` step, docs/CHOICES.md). A click on an option of a list the diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md new file mode 100644 index 0000000000..6a7d1d5e1f --- /dev/null +++ b/packages/flow/docs/A2A.md @@ -0,0 +1,81 @@ +# The A2A protocol adapter + +`openadapt agent serve --a2a` serves compiled OpenAdapt programs to any agent +that speaks the [A2A (Agent2Agent) protocol](https://a2a-protocol.org/latest/specification/). +It implements A2A specification 1.0 through the official Python +[`a2a-sdk`](https://github.com/a2aproject/a2a-python) (1.3.1 or later, +Apache-2.0). + +It is one transport for [agent-to-agent handoffs](HANDOFFS.md). The MCP, +HTTP and file transports need no extra package. + +```bash +pip install 'openadapt[a2a]' # or: pip install 'openadapt-flow[a2a]' +openadapt agent serve --bundles ./bundles --mode production --a2a +# Agent Card: http://127.0.0.1:8770/.well-known/agent-card.json +``` + +## What it serves + +| A2A | OpenAdapt | +|---|---| +| Agent Card at `/.well-known/agent-card.json` | Built from the same public workflow list `list_workflows` returns. It never includes step text, recorded values or paths. | +| `supportedInterfaces` | `JSONRPC` at `/a2a/jsonrpc` and `HTTP+JSON` at `/a2a/rest`, protocol version 1.0. | +| One skill per workflow | Send a data part `{"skill": NAME, "inputs": {...}, "request_id": ID}`. | +| Skill `verify_handoff` | Send another agent's handoff and get the verdict ([HANDOFFS.md](HANDOFFS.md)). | +| `capabilities.extensions` | `https://openadapt.ai/extensions/handoff-receipt/v1`, not required ([HANDOFF_RECEIPTS.md](HANDOFF_RECEIPTS.md)). | +| Task artifact `run_result` | The run result (`outcome`, `safe_to_retry` unchanged) plus the `openadapt.handoff/v1` document with the run's signed receipt (`record/run/v1`). | + +Only outcome `done` is `TASK_STATE_COMPLETED`. `needs_review` is +`TASK_STATE_INPUT_REQUIRED`: a person at this computer decides. A message on +that task only re-checks the run; it never approves it. Every other outcome +is `TASK_STATE_FAILED`. Cancelling a task never stops a run part way through +a write; the server answers `TaskNotCancelableError`. + +## Same rules as MCP + +A request over A2A goes through the same gate as the same request over MCP +(`openadapt_flow/agent/contract_call.py`). That gate applies: + +- the tool's input schema; +- the task ledger; +- the server's mode (runs need `--mode production`); +- the request-id ledger, so the same `request_id` never writes twice; +- intake grants; +- Flow's fail-closed admission. + +Only these calls exist over A2A: `list_workflows`, `run_workflow`, `get_run`, +`get_handoff` and `verify_handoff`. Attended decisions, admission decisions +and approval answers need a person in a confirmation form, so A2A doesn't +serve them. `--authoring`, `--guard`, `--verify`, `--teach` and +`--teach-browser` stay on MCP stdio. + +## Network + +- **Loopback by default.** It listens on 127.0.0.1:8770 by default + (`--a2a-host`, `--a2a-port`). +- **A token off loopback.** Any other address needs `--a2a-token-file FILE`, + a bearer token of 32 or more characters that every request must carry. + Off loopback, the public card lists only `verify_handoff`, and the + workflows are in the authenticated extended card. Set `--a2a-public-url` + to the address other agents use. +- **No browser requests.** A request with a browser `Origin` header, or a + `Host` the server doesn't answer for, is refused. A web page can't reach + the port, even through DNS rebinding. + +## Tests + +`packages/agent/tests/test_handoff_e2e.py` runs the official `a2a-sdk` client +against this server over HTTP on 127.0.0.1. A program run goes through the +governed runner with Flow's run process stubbed, and Flow's receipt writer +signs the report. The tests cover: + +- the receipt in the task artifact; +- a good handoff, verified; +- tampered, unknown-signer and re-stapled handoffs; +- the MCP gate's refusals, repeated over A2A; +- refusals of a browser `Origin` and a foreign `Host`; +- the token off loopback; +- a follow-up message that can't approve a run. + +The same file covers the MCP tools. diff --git a/packages/flow/docs/HANDOFFS.md b/packages/flow/docs/HANDOFFS.md new file mode 100644 index 0000000000..22c2e050bc --- /dev/null +++ b/packages/flow/docs/HANDOFFS.md @@ -0,0 +1,119 @@ +# Agent-to-agent handoffs + +When your agent hands a result to another agent, the run's signed receipt +can go with it. The receiving agent checks the receipt against keys it chose +to trust and gets back a verdict. A handoff works over the channels agents +already use: MCP tool results, HTTP requests and webhooks, files and email +attachments, and the A2A (Agent2Agent) protocol. + +The format is described in +[HANDOFF_RECEIPTS.md](HANDOFF_RECEIPTS.md). + +## What the verdict tells the receiving agent + +- **Who signed it.** For example "Signed by this computer" or "Countersigned + by OpenAdapt Cloud". The role comes from the receiver's pinned keys, never + from the handoff. +- **Whether it is intact.** A changed receipt, an unknown signer or a changed + payload is refused. +- **Checks passed, and what was not checked.** These come straight from the + receipt, with its outcome copied and never upgraded. +- **Confirmed in the other party's system.** These lines appear when the run + read the result back from the other party's system (a portal read-back or + an API). +- **What it does not prove.** A valid signature proves who signed, not that + the claim is true. Only a confirmation read from the other party's own + system is independent of the sender. + +The receipt signs the run, not the payload, unless the payload is the signed +report itself. The verdict says when nothing ties the payload to the receipt. + +## A signature doesn't make the claim true + +A receipt the sender signed can't prove the sender's claim to you. It shows +who sent the handoff and that it wasn't changed. A sender can still sign a +claim that is false. Before you act on a handoff, read your own record: + +```python +from openadapt_flow.handoff import ReceiverRecord, decide + +def my_record(claim): + row = my_db.get(claim["ref"]) + if row is None: + return ReceiverRecord("not_found") + if row.note != claim["fields"]["note"]: + return ReceiverRecord("recorded_differently", ("note",)) + return ReceiverRecord("recorded_as_intended") + +verdict = decide(handoff, my_keys, my_record) +verdict.decision # "accept", "reject", or "unchecked" when you passed no read +``` + +`decide` accepts a handoff only when both are true: + +- the receipt is intact; +- your own system shows the record as the handoff describes it. + +It rejects a fabricated or differing claim even when a trusted sender signed +it. It rejects when your read fails. Without a read it never accepts. + +`packages/agent/tests/test_handoff_e2e.py` measures this with two parties: + +- **The handoffs.** One OpenAdapt server over A2A runs 20 programs and POSTs + 20 signed handoffs to a second party's inbox: 10 true, 5 fabricated and 5 + that differ from the second party's own records. +- **The pass bar.** The second party must accept no false handoff, reject no + true one, and spend at most 2 s checking each. + +## From the command line + +```bash +# Attach a run's receipt to a result and write one JSON document +openadapt handoff send result.json --run ~/.openadapt/runs/run-123 --out result.handoff.json + +# Files and email: keep the attachment as it is, and put result.pdf.handoff.json beside it +openadapt handoff send result.pdf --run ~/.openadapt/runs/run-123 --detached + +# A webhook or agent inbox (https, or http to this computer) +openadapt handoff send result.json --run ~/.openadapt/runs/run-123 --post https://agent.example/inbox + +# On arrival, against the keys you pin +openadapt handoff verify result.handoff.json --keys trusted-keys.json +``` + +`verify` exits 0 when the receipt is intact and 1 when it is refused. Add +`--json` to get the verdict as data. `receipt.private.json` never leaves the +computer: `send` refuses to attach it. + +## From Python + +```python +from openadapt_flow.handoff import make_handoff, receipt_for_run, verify_handoff, load_registry + +doc = make_handoff({"outcome": "done"}, receipt_for_run(run_dir)) +verdict = verify_handoff(doc, load_registry(Path("trusted-keys.json"))) +verdict.ok, verdict.signer_lines, verdict.what_this_proves +``` + +## Over MCP + +```bash +openadapt agent serve --bundles ./bundles --mode production --handoffs +``` + +This adds two read-only tools: + +- **`get_handoff`** returns a finished run's result with its receipt attached. +- **`verify_handoff`** checks a handoff another agent sent. `--handoff-keys + REGISTRY` sets which keys it trusts. + +## Over the A2A protocol + +```bash +pip install 'openadapt[a2a]' +openadapt agent serve --bundles ./bundles --mode production --a2a +``` + +This serves the same workflows as A2A skills, with an Agent Card at +`/.well-known/agent-card.json`. Each run's task result carries the receipt. +See [A2A.md](A2A.md). diff --git a/packages/flow/docs/HANDOFF_RECEIPTS.md b/packages/flow/docs/HANDOFF_RECEIPTS.md new file mode 100644 index 0000000000..f8675a0cf3 --- /dev/null +++ b/packages/flow/docs/HANDOFF_RECEIPTS.md @@ -0,0 +1,256 @@ +# Handoff receipts: a receipt that travels with an agent handoff (draft) + +| | | +|---|---| +| **Identifier** | `https://openadapt.ai/extensions/handoff-receipt/v1` | +| **Status** | Draft, version 1. Implemented in OpenAdapt, not submitted to any standards body. | +| **Document schema** | `openadapt.handoff/v1` | +| **Verdict schema** | `openadapt.handoff-verdict/v1` | +| **Media type** | `application/vnd.openadapt.handoff+json` | +| **Receipt format** | `https://openadapt.ai/record/run/v1`: an in-toto Statement v1 in a DSSE v1.0.2 envelope | +| **Reference implementation** | [`openadapt_flow/handoff.py`](../openadapt_flow/handoff.py), [`openadapt_types/receipt.py`](../../types/openadapt_types/receipt.py) | + +The identifier is a name, not a location; nothing is fetched from it. + +## 1. Purpose + +When one agent hands a task or a result to another, the receiving agent +usually has only the sender's word for what happened. This extension carries +the signed receipt of the run that produced the result alongside the result. +The receiver can then check, against keys it chose to trust: + +- who signed the receipt, and that it is unchanged; +- what the run checked, what it didn't check, and what it couldn't confirm; +- whether any part was confirmed in the other party's own system rather than + reported by the sender. + +The handoff works the same over any channel. Section 6 defines bindings for +MCP tool results, HTTP requests and webhooks, files and email attachments, and +the A2A (Agent2Agent) protocol. + +## 2. What a valid receipt does and does not prove + +Every verifier MUST tell its user the following, in its own words: + +1. A valid signature proves **who signed** the receipt and that it has not + changed since. It does **not** prove that the receipt's claims are true. +2. The signer's role comes from the **receiver's** pinned key registry, never + from the handoff document or the envelope. +3. The receipt signs the **run** (its report and bundle digests), not the + handoff payload. The payload is **bound** only when its SHA-256 equals a + signed subject digest. Otherwise the verdict MUST say that nothing ties the + payload to the receipt. +4. A confirmation counts as **independent of the sender** only when its + signed `read_method` reads the other party's own system (`portal_read_back` + or `api`). Any other claim rests on the signer's word. + +5. A sender-signed receipt can't prove the sender's claim to the receiver. + Before acting, the receiver SHOULD confirm the claim by reading its own + record. The reference implementation's `decide()` accepts only when the + receipt is intact and the receiver's own read is `recorded_as_intended`. + It rejects a fabricated or differing claim even with a valid signature from + a trusted sender, and it never accepts without that read (`unchecked`). + +## 3. The handoff document + +```json +{ + "schema": "openadapt.handoff/v1", + "payload": { + "media_type": "application/json", + "sha256": "<64 hex>", + "size": 123, + "name": "result.json", + "content": {"outcome": "done"} + }, + "receipt": {"payloadType": "application/vnd.in-toto+json", "payload": "", "signatures": [{"keyid": "seal-ed25519-<16 hex>", "sig": ""}]} +} +``` + +- `schema` is required and is exactly `openadapt.handoff/v1`. Other top-level + fields are refused. +- `payload.sha256` is required. It covers the exact payload bytes: for + `content_base64`, the decoded bytes; for `content` (a JSON value), its + canonical form (sorted keys, `,` and `:` separators, UTF-8). +- Exactly one of `content`, `content_base64`, or neither (**detached**) is + present. An inline payload is at most 1 MiB. +- `receipt` is a `record/run/v1` DSSE envelope (`receipt.json`) or its public + card (`openadapt.receipt-card/v1`). The private openings file + (`receipt.private.json`, `openadapt.receipt-openings/v1`) MUST NOT be sent. + Senders MUST refuse to attach it, and verifiers MUST refuse a document that + carries it. +- The document itself is not signed. Its integrity comes only from the + receipt and the payload digest. + +## 4. Verifying + +A receiver MUST perform these steps in order and stop at the first failure. +The result is a refusal, never a partial pass. + +1. **Parse** the document as JSON, refusing duplicate keys. Check `schema` and + the closed field set. +2. **Verify the receipt** as `record/run/v1` requires + ([`openadapt_types/receipt.py`](../../types/openadapt_types/receipt.py), + vectors in `packages/types/tests/vectors/record-run-v1/`): + - the DSSE envelope's `payloadType` is `application/vnd.in-toto+json`; + - each signature is Ed25519 over `PAE(payloadType, payload)` as DSSE + defines it, from a key in the receiver's pinned registry + (`openadapt.receipt-keys/v1`); + - an unknown key, role or schema, a revoked key, or a demo key next to a + real one is refused; + - the payload is canonical JSON, an in-toto Statement v1 with + `predicateType` `https://openadapt.ai/record/run/v1`, closed, internally + consistent, and free of embedded content. +3. **Check the payload**: + - recompute its SHA-256 from the inline content or the detached file; + - refuse on mismatch (`payload_mismatch`); + - mark it bound only if it equals a signed `subject` digest. +4. **Report** the verdict (section 5). + +## 5. The verdict + +```json +{ + "schema": "openadapt.handoff-verdict/v1", + "integrity": "intact", + "reason": null, + "signer_roles": ["this_computer"], + "signer_lines": ["Signed by this computer"], + "outcome": "VERIFIED", + "checks": {"passed": [], "incomplete": [], "not_checked": ["field_values"], + "writes": {"confirmed": 1, "refuted": 0, "not_checked": 0}}, + "payload": {"bound": false, "note": "The receipt signs the run's report, not this payload. ..."}, + "confirmations": [{"state": "recorded_as_intended", "read_method": "api", "independent": true}], + "confirmation_lines": ["Confirmed in the other party's system"], + "independent_confirmations": 1, + "what_this_proves": ["A valid signature proves who signed this receipt and that it has not changed since. It does not prove that what the receipt says is true.", "..."] +} +``` + +These rules apply to the verdict: + +- **`integrity`** is `intact` or `refused`. A refusal carries `reason`, using + the `record/run/v1` refusal codes plus `payload_mismatch`. +- **`outcome`** is copied from the receipt and never upgraded. +- **`signer_lines` and `confirmation_lines`** are kept separate. A + confirmation never strengthens a signer line. +- **`what_this_proves`** always opens with the statement in section 2, + point 1. +- **`receiver_check` and `decision`** are filled in by `decide()`. + `receiver_check` is the receiver's own read: a `state` from + `recorded_as_intended`, `recorded_differently`, `not_found` or `unreadable`, + the `differing_fields` as field ids only, and the `read_method`. `decision` + is `accept`, `reject` or `unchecked`. + +## 6. Bindings + +### 6.1 MCP + +`openadapt agent serve --handoffs` adds two read-only tools: + +- **`get_handoff {run_id}`** returns the run's public result as the payload, + with its receipt attached. +- **`verify_handoff {handoff}`** returns the verdict, checked against the + server's pinned keys. + +### 6.2 HTTP and webhooks + +The document is the request body, with `Content-Type: +application/vnd.openadapt.handoff+json`. The receiver verifies the body it +received, as is. `openadapt handoff send FILE --run RUN_DIR --post URL` +sends one. It accepts HTTPS, or plain HTTP only to loopback. + +### 6.3 Files and email attachments + +The payload stays as the file. `FILE.handoff.json` beside it is a detached +document: it holds the payload digest and the receipt, and no content. +`openadapt handoff verify FILE.handoff.json` finds `FILE` next to it and +checks it. If `FILE` is missing, the verdict says the payload was not +checked. + +### 6.4 A2A protocol (Agent2Agent, specification 1.0) + +**Agent Card declaration.** The extension is declared in +`capabilities.extensions`: + +```json +{ + "uri": "https://openadapt.ai/extensions/handoff-receipt/v1", + "description": "Task results carry the run's record/run/v1 receipt ...", + "required": false, + "params": { + "handoff_schema": "openadapt.handoff/v1", + "verdict_schema": "openadapt.handoff-verdict/v1", + "media_type": "application/vnd.openadapt.handoff+json", + "receipt_predicate": "https://openadapt.ai/record/run/v1", + "envelope": "dsse" + } +} +``` + +The extension adds data only and is never `required`, so a client that +doesn't know it still gets every result. + +**Activation.** A client MAY send `A2A-Extensions: +https://openadapt.ai/extensions/handoff-receipt/v1`, and the server echoes the +header when it activates the extension. Artifacts are the same either way. + +**Artifact shape.** A run's task carries one artifact, `run_result`, with +`extensions: ["https://openadapt.ai/extensions/handoff-receipt/v1"]` and two +parts: + +1. a `data` part (`application/json`) holding the run result. `outcome` and + `safe_to_retry` are unchanged; +2. a `raw` part (`mediaType` `application/vnd.openadapt.handoff+json`, + `filename` `.handoff.json`) holding the handoff document's exact + bytes. + +The handoff travels as `raw` bytes, not as a `data` part, because a `data` +part is a protobuf `Value`, which stores every number as a double and would +change the digested bytes. + +**Task states.** + +| Outcome | Task state | +|---|---| +| `done` | `TASK_STATE_COMPLETED` | +| `needs_review` | `TASK_STATE_INPUT_REQUIRED` | +| Anything else | `TASK_STATE_FAILED` | + +For `needs_review`, a person at the serving computer decides. A message on +that task only re-checks the run and never approves it. + +**Verifier skill.** The `verify_handoff` skill accepts a message with either +part: + +- a `raw` part of the handoff media type; +- a `data` part `{"skill": "verify_handoff", "handoff": {...}}`. + +It returns the verdict as a `data` part artifact, `verdict`, marked with the +extension. Over a `data` part, whole-number doubles are restored to integers +before verifying. Send the `raw` part when the payload contains numbers that +are not whole. + +## 7. Security considerations + +- **Trust comes from the receiver.** Pin keys you chose. The default registry + of `openadapt handoff verify` trusts only this computer's key and pinned + OpenAdapt Cloud keys. +- **Replay.** A receipt can be re-sent. Bind it to the payload, as in + section 4, step 3, or check the run identity yourself before acting. +- **Privacy.** A `record/run/v1` statement holds only digests, enums, counts + and salted commitments. A handoff never carries the openings. +- **Transport.** `openadapt agent serve --a2a` listens on 127.0.0.1 by + default and needs a bearer token on any other address. It refuses requests + that carry a browser `Origin` or an unknown `Host`. + +## 8. References + +- A2A Protocol Specification 1.0 (latest release v1.0.1, 2026-05-28): + . Proto: + . +- A2A extensions: . +- in-toto Attestation Framework, Statement v1: + . +- DSSE v1.0.2, envelope and protocol (PAE): + . diff --git a/packages/flow/docs/commands/06-give-agents-the-program/handoff.md b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md new file mode 100644 index 0000000000..b1e6ec2a53 --- /dev/null +++ b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md @@ -0,0 +1 @@ +Hand a result to another agent with its run's receipt attached (inline, detached beside a file, or POSTed to a webhook), and verify one on arrival against your pinned keys: who signed, what was checked, and that a valid signature proves who signed, not that the claim is true. diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index b3a3b13912..e9277863a8 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13194,6 +13194,10 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _register_receipt(sub) + from openadapt_flow.cli_handoff import register as _register_handoff + + _register_handoff(sub) + from openadapt_flow.learn import register as _register_learn _register_learn(sub) diff --git a/packages/flow/openadapt_flow/agent/a2a_server.py b/packages/flow/openadapt_flow/agent/a2a_server.py new file mode 100644 index 0000000000..7d63e17855 --- /dev/null +++ b/packages/flow/openadapt_flow/agent/a2a_server.py @@ -0,0 +1,571 @@ +"""The A2A protocol adapter: ``openadapt agent serve --a2a``. + +Serves the same workflows as the MCP server to any agent that speaks the +Agent2Agent (A2A) protocol, using the official ``a2a-sdk`` (Apache-2.0, +``pip install 'openadapt-flow[a2a]'``). This module is a thin transport: + +* Every call goes through :func:`openadapt_flow.agent.contract_call.call_remote_tool`, + the gate MCP uses: schema validation, the task ledger, the bridge's run mode, + the request-id ledger and Flow's fail-closed admission. Only + ``list_workflows``, ``run_workflow``, ``get_run``, ``get_handoff`` and + ``verify_handoff`` exist here. Attended decisions, admission decisions and + approval answers need a person in a confirmation form, so they are not + served, and no A2A message ever counts as a person's approval. +* A run is an A2A task. Only outcome ``done`` is ``TASK_STATE_COMPLETED``. + ``needs_review`` waits for a person at this computer + (``TASK_STATE_INPUT_REQUIRED``); a message on that task only re-checks the + run. Everything else is ``TASK_STATE_FAILED``. The run's own result, with + ``outcome`` and ``safe_to_retry`` unchanged, is always an artifact. +* A finished run's receipt travels as an ``openadapt.handoff/v1`` artifact + part (exact bytes, so its digests hold), marked with the handoff-receipt + extension URI. +* It listens on 127.0.0.1 by default. Any other address needs a bearer token. + Every request with a browser ``Origin`` header, or a ``Host`` it doesn't + serve, is refused, so a web page can't reach the port (DNS rebinding). +""" + +from __future__ import annotations + +import asyncio +import hmac +import ipaddress +import json +import logging +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.agent.bridge import AgentBridge, BridgeError +from openadapt_flow.agent.contract_call import call_remote_tool +from openadapt_flow.handoff import EXTENSION_URI, MEDIA_TYPE, SCHEMA, VERDICT_SCHEMA + +_LOG = logging.getLogger(__name__) + +PROTOCOL_VERSION = "1.0" +JSONRPC_PATH = "/a2a/jsonrpc" +REST_PATH = "/a2a/rest" +VERIFY_SKILL = "verify_handoff" +#: Longest one task waits for a running run before it reports where it got. +MAX_TASK_SECONDS = 1800.0 +_POLL_SECONDS = 10 + +A2A_INSTALL_HINT = ( + "the A2A adapter needs the a2a extra: pip install 'openadapt-flow[a2a]' " + "(or 'openadapt[a2a]')" +) + + +def a2a_available() -> bool: + try: + import a2a.server.routes # noqa: F401 + import uvicorn # noqa: F401 + except ImportError: + return False + return True + + +def is_loopback(host: str) -> bool: + if host == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +@dataclass +class A2AConfig: + host: str = "127.0.0.1" + port: int = 8770 + #: The URL other agents reach this server at (the Agent Card's interfaces). + public_url: Optional[str] = None + #: Bearer token; required unless ``host`` is loopback. + token: Optional[str] = None + extra_hosts: tuple[str, ...] = field(default_factory=tuple) + + def __post_init__(self) -> None: + if not is_loopback(self.host) and not self.token: + raise ValueError( + "--a2a-host other than 127.0.0.1 needs --a2a-token-file: " + "anything off this computer must authenticate" + ) + + @property + def base_url(self) -> str: + if self.public_url: + return self.public_url.rstrip("/") + host = f"[{self.host}]" if ":" in self.host else self.host + return f"http://{host}:{self.port}" + + def allowed_hosts(self) -> set[str]: + from urllib.parse import urlparse + + hosts = {f"{self.host}:{self.port}", f"127.0.0.1:{self.port}"} + hosts.add(f"localhost:{self.port}") + parsed = urlparse(self.base_url) + if parsed.netloc: + hosts.add(parsed.netloc) + hosts.update(self.extra_hosts) + return hosts + + +# -- the Agent Card --------------------------------------------------------------- + + +def _skills(bridge: AgentBridge, *, include_workflows: bool) -> list[Any]: + from a2a.types import AgentSkill + + skills = [] + if include_workflows and bridge.allow_run: + listing = bridge.dispatch("list_workflows", {}) + for item in listing.get("workflows") or []: + if not item.get("available", True): + continue + name = str(item.get("name")) + purpose = str(item.get("purpose") or item.get("description") or "") + done = item.get("done_means") or item.get("what_done_means") + description = purpose + (f" Done means: {done}" if done else "") + skills.append( + AgentSkill( + id=name, + name=name, + description=( + description.strip() + or "A compiled OpenAdapt workflow on this computer." + ) + + " Send a data part {\"skill\": \"" + + name + + "\", \"inputs\": {...}, \"request_id\": \"...\"}. The " + "result includes the run's signed receipt.", + tags=["openadapt", "workflow", "receipt"], + input_modes=["application/json"], + output_modes=["application/json", MEDIA_TYPE], + ) + ) + skills.append( + AgentSkill( + id=VERIFY_SKILL, + name="Verify a handoff", + description=( + "Send another agent's result with its receipt (an " + f"{SCHEMA} document, as a data part or a {MEDIA_TYPE} file " + "part). Returns who signed it, whether it is intact, which " + "checks passed and which were not checked, and any confirmation " + "read from the other party's system. A valid signature proves " + "who signed, not that the claim is true." + ), + tags=["verification", "receipt", "handoff", "in-toto", "dsse"], + input_modes=["application/json", MEDIA_TYPE], + output_modes=["application/json"], + ) + ) + return skills + + +def build_agent_card( + bridge: AgentBridge, config: A2AConfig, *, extended: bool = False +) -> Any: + """The Agent Card. Built only from the public workflow projection. + + On loopback the card lists every workflow. Off loopback the public card + lists only the verifier skill; the workflows are in the authenticated + extended card. + """ + from a2a.types import ( + AgentCapabilities, + AgentCard, + AgentExtension, + AgentInterface, + AgentProvider, + HTTPAuthSecurityScheme, + SecurityRequirement, + SecurityScheme, + StringList, + ) + from google.protobuf import struct_pb2 + from google.protobuf.json_format import ParseDict + + from openadapt_flow.agent import __version__ + + remote = not is_loopback(config.host) + params = ParseDict( + { + "handoff_schema": SCHEMA, + "verdict_schema": VERDICT_SCHEMA, + "media_type": MEDIA_TYPE, + "receipt_predicate": "https://openadapt.ai/record/run/v1", + "envelope": "dsse", + }, + struct_pb2.Struct(), + ) + card = AgentCard( + name="OpenAdapt", + description=( + "Runs compiled OpenAdapt workflows on this computer and checks that " + "they saved. Every run's result carries its signed receipt, and any " + "agent can send a handoff to be verified." + ), + provider=AgentProvider(organization="OpenAdapt", url="https://openadapt.ai"), + version=__version__, + documentation_url=( + "https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md" + ), + capabilities=AgentCapabilities( + streaming=True, + push_notifications=False, + extended_agent_card=remote, + extensions=[ + AgentExtension( + uri=EXTENSION_URI, + description=( + "Task results carry the run's record/run/v1 receipt " + "(in-toto Statement in a DSSE envelope) as an " + f"{SCHEMA} artifact part; {VERIFY_SKILL} returns an " + f"{VERDICT_SCHEMA} verdict." + ), + required=False, + params=params, + ) + ], + ), + default_input_modes=["application/json"], + default_output_modes=["application/json", MEDIA_TYPE], + skills=_skills(bridge, include_workflows=extended or not remote), + supported_interfaces=[ + AgentInterface( + protocol_binding="JSONRPC", + protocol_version=PROTOCOL_VERSION, + url=config.base_url + JSONRPC_PATH, + ), + AgentInterface( + protocol_binding="HTTP+JSON", + protocol_version=PROTOCOL_VERSION, + url=config.base_url + REST_PATH, + ), + ], + ) + if config.token: + card.security_schemes["bearer"].CopyFrom( + SecurityScheme( + http_auth_security_scheme=HTTPAuthSecurityScheme(scheme="Bearer") + ) + ) + requirement = SecurityRequirement() + requirement.schemes["bearer"].CopyFrom(StringList()) + card.security_requirements.append(requirement) + return card + + +# -- requests --------------------------------------------------------------------- + + +def _integral(value: Any) -> Any: + """A data part stores numbers as doubles; restore whole numbers.""" + if isinstance(value, float) and value.is_integer(): + return int(value) + if isinstance(value, dict): + return {k: _integral(v) for k, v in value.items()} + if isinstance(value, list): + return [_integral(v) for v in value] + return value + + +def parse_request(message: Any) -> tuple[str, dict[str, Any]]: + """Map one A2A message to (tool, arguments). Raises BridgeError.""" + from google.protobuf.json_format import MessageToDict + + for part in message.parts: + if part.HasField("raw") and part.media_type == MEDIA_TYPE: + try: + document = json.loads(part.raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + raise BridgeError("the handoff file part is not JSON") from None + return VERIFY_SKILL, {"handoff": document} + data = [ + _integral(MessageToDict(part.data)) for part in message.parts if part.HasField("data") + ] + if len(data) != 1 or not isinstance(data[0], dict): + raise BridgeError( + 'send one data part: {"skill": NAME, "inputs": {...}, "request_id": ID}, ' + '{"skill": "verify_handoff", "handoff": {...}}, or ' + '{"skill": "get_run", "run_id": ID}' + ) + body = dict(data[0]) + skill = body.pop("skill", None) + if not isinstance(skill, str) or not skill: + if body.get("schema") == SCHEMA: + return VERIFY_SKILL, {"handoff": body} + raise BridgeError('the data part needs "skill"') + if skill == VERIFY_SKILL: + return VERIFY_SKILL, {"handoff": body.get("handoff")} + if skill in ("get_run", "get_handoff", "list_workflows"): + return skill, body + if skill == "run_workflow": + return "run_workflow", body + # A workflow skill from the Agent Card is a run_workflow call. + return "run_workflow", {"workflow": skill, **body} + + +def task_state_for(outcome: Optional[str]) -> str: + """Only done is COMPLETED. needs_review waits for a person here.""" + if outcome == "done": + return "TASK_STATE_COMPLETED" + if outcome == "needs_review": + return "TASK_STATE_INPUT_REQUIRED" + if outcome == "running": + return "TASK_STATE_WORKING" + return "TASK_STATE_FAILED" + + +def _status_text(result: dict[str, Any]) -> str: + outcome = result.get("outcome") + text = str(result.get("what_happened") or outcome or "") + if outcome == "needs_review": + text += ( + " A person at the OpenAdapt computer decides. A message on this " + "task only re-checks the run; it never approves it." + ) + return text.strip() + + +class OpenAdaptExecutor: + """An ``a2a`` AgentExecutor over one bridge (built lazily, see ``executor_class``).""" + + def __init__(self, bridge: AgentBridge) -> None: + self.bridge = bridge + #: A2A task id -> OpenAdapt run id, for re-checks on the same task. + self.runs: dict[str, str] = {} + + async def _call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]: + return await asyncio.to_thread(call_remote_tool, self.bridge, name, arguments) + + async def execute(self, context: Any, event_queue: Any) -> None: + from a2a.helpers.proto_helpers import new_data_part, new_raw_part, new_text_part + from a2a.server.tasks.task_updater import TaskUpdater + from a2a.types import Task, TaskState, TaskStatus + + message = context.message + task_id, context_id = context.task_id, context.context_id + if message is None or not task_id or not context_id: + return + updater = TaskUpdater(event_queue, task_id, context_id) + + def say(text: str) -> Any: + return updater.new_agent_message(parts=[new_text_part(text)]) + + if context.current_task is None: + await event_queue.enqueue_event( + Task( + id=task_id, + context_id=context_id, + status=TaskStatus(state=TaskState.TASK_STATE_SUBMITTED), + history=[message], + ) + ) + try: + if task_id in self.runs: + # A follow-up on a run's task re-checks it. The message's + # content is never read: it can't approve or change a run. + tool, arguments = "get_run", {"run_id": self.runs[task_id]} + else: + tool, arguments = parse_request(message) + if tool == VERIFY_SKILL: + verdict = await self._call(tool, arguments) + await updater.add_artifact( + [new_data_part(verdict, media_type="application/json")], + name="verdict", + extensions=[EXTENSION_URI], + last_chunk=True, + ) + await updater.complete( + say(" ".join(verdict.get("signer_lines") or []) or "Verified.") + ) + return + await updater.start_work(say("Working.")) + if tool in ("list_workflows", "get_handoff"): + result = await self._call(tool, arguments) + await updater.add_artifact( + [new_data_part(result, media_type="application/json")], + name=tool, + last_chunk=True, + ) + await updater.complete() + return + result = await self._call(tool, arguments) + run_id = result.get("run_id") + if isinstance(run_id, str): + self.runs[task_id] = run_id + waited = 0.0 + while result.get("outcome") == "running" and waited < MAX_TASK_SECONDS: + await updater.update_status( + TaskState.TASK_STATE_WORKING, message=say(_status_text(result)) + ) + result = await self._call( + "get_run", {"run_id": run_id, "wait_seconds": _POLL_SECONDS} + ) + waited += _POLL_SECONDS + parts = [new_data_part(result, media_type="application/json")] + if result.get("outcome") not in (None, "running") and isinstance(run_id, str): + try: + handoff = await self._call("get_handoff", {"run_id": run_id}) + except BridgeError as exc: + parts.append(new_text_part(f"No receipt attached: {exc}")) + else: + parts.append( + new_raw_part( + json.dumps(handoff, sort_keys=True).encode("utf-8"), + media_type=MEDIA_TYPE, + filename=f"{run_id}.handoff.json", + ) + ) + await updater.add_artifact( + parts, name="run_result", extensions=[EXTENSION_URI], last_chunk=True + ) + state = task_state_for(result.get("outcome")) + text = say(_status_text(result)) + if state == "TASK_STATE_COMPLETED": + await updater.complete(text) + elif state == "TASK_STATE_INPUT_REQUIRED": + await updater.requires_input(text) + elif state == "TASK_STATE_WORKING": + await updater.update_status(TaskState.TASK_STATE_WORKING, message=text) + else: + await updater.failed(text) + except BridgeError as exc: + await updater.failed(say(str(exc))) + except Exception: + _LOG.exception("A2A task failed inside the protected boundary") + await updater.failed( + say( + "Local tool execution failed safely. Inspect the protected " + "local logs before retrying." + ) + ) + + async def cancel(self, context: Any, event_queue: Any) -> None: + from a2a.utils.errors import TaskNotCancelableError + + # A run in progress is never cancelled from here: stopping a write + # half way is itself uncertain. The run stays as it is. + raise TaskNotCancelableError( + "OpenAdapt doesn't cancel a run over A2A; check it with get_run" + ) + + +def executor_class() -> type: + from a2a.server.agent_execution.agent_executor import AgentExecutor + + return type("OpenAdaptAgentExecutor", (OpenAdaptExecutor, AgentExecutor), {}) + + +# -- the HTTP app ------------------------------------------------------------------- + + +class GuardMiddleware: + """Host check, no browser Origin, bearer token, and the extensions header.""" + + def __init__(self, app: Any, config: A2AConfig) -> None: + self.app = app + self.config = config + self.hosts = config.allowed_hosts() + + async def __call__(self, scope: Any, receive: Any, send: Any) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope["headers"]} + problem = None + if headers.get("host") not in self.hosts: + problem = (421, "this server does not answer for that host") + elif "origin" in headers: + problem = (403, "browser requests are refused") + elif self.config.token and scope["path"] != "/.well-known/agent-card.json": + supplied = headers.get("authorization", "") + expected = f"Bearer {self.config.token}" + if not hmac.compare_digest(supplied.encode(), expected.encode()): + problem = (401, "a bearer token is required") + if problem is not None: + body = json.dumps({"error": problem[1]}).encode() + await send( + { + "type": "http.response.start", + "status": problem[0], + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode()), + ] + + ([(b"www-authenticate", b"Bearer")] if problem[0] == 401 else []), + } + ) + await send({"type": "http.response.body", "body": body}) + return + requested = { + item.strip() + for item in headers.get("a2a-extensions", "").split(",") + if item.strip() + } + + async def send_with_extensions(message: Any) -> None: + if message["type"] == "http.response.start" and EXTENSION_URI in requested: + message = dict(message) + message["headers"] = list(message.get("headers") or []) + [ + (b"a2a-extensions", EXTENSION_URI.encode()) + ] + await send(message) + + await self.app(scope, receive, send_with_extensions) + + +def build_app(bridge: AgentBridge, config: A2AConfig) -> Any: + """The ASGI app: Agent Card, JSON-RPC and HTTP+JSON bindings.""" + from a2a.server.request_handlers import DefaultRequestHandler + from a2a.server.routes import ( + create_agent_card_routes, + create_jsonrpc_routes, + create_rest_routes, + ) + from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore + from starlette.applications import Starlette + + card = build_agent_card(bridge, config) + extended = ( + build_agent_card(bridge, config, extended=True) + if card.capabilities.extended_agent_card + else None + ) + handler = DefaultRequestHandler( + agent_executor=executor_class()(bridge), + task_store=InMemoryTaskStore(), + agent_card=card, + extended_agent_card=extended, + ) + routes = [ + *create_agent_card_routes(agent_card=card), + *create_jsonrpc_routes(request_handler=handler, rpc_url=JSONRPC_PATH), + *create_rest_routes(request_handler=handler, path_prefix=REST_PATH), + ] + app = Starlette(routes=routes) + return GuardMiddleware(app, config) + + +def read_token(path: Optional[str]) -> Optional[str]: + if not path: + return None + token = Path(path).expanduser().read_text(encoding="utf-8").strip() + if len(token) < 32: + raise ValueError("the --a2a-token-file token must be at least 32 characters") + return token + + +def serve(bridge: AgentBridge, config: A2AConfig) -> None: + """Serve until interrupted.""" + import uvicorn + + uvicorn.run( + build_app(bridge, config), + host=config.host, + port=config.port, + log_level="warning", + proxy_headers=False, + server_header=False, + ) diff --git a/packages/flow/openadapt_flow/agent/bridge.py b/packages/flow/openadapt_flow/agent/bridge.py index 74f78bb16c..c54bdec93d 100644 --- a/packages/flow/openadapt_flow/agent/bridge.py +++ b/packages/flow/openadapt_flow/agent/bridge.py @@ -158,6 +158,9 @@ class AgentBridge: #: when runs are allowed. ``mcp.build_server`` serves its job tools and #: feeds it every run result. ledger: Any = None + #: :class:`~openadapt_flow.agent.handoff_tools.HandoffTools` when the + #: operator started the server with ``--handoffs`` (or ``--a2a``). + handoffs: Any = None def __init__( self, @@ -381,6 +384,8 @@ def _contract_specs(self) -> list[ToolSpec]: specs.extend(self._repair_specs()) specs.extend(self._approval_specs()) specs.extend(self._admission_specs()) + if self.handoffs is not None: + specs.extend(self.handoffs.list_tool_specs(runs_enabled=self.allow_run)) return specs def _admission_specs(self) -> list[ToolSpec]: @@ -741,6 +746,8 @@ def dispatch(self, name: str, arguments: Optional[dict]) -> dict: ) except ServiceError as exc: raise BridgeError(str(exc)) from exc + if self.handoffs is not None and self.handoffs.handles(name): + return self._handoff_dispatch(name, arguments) if name in ( "get_approval_mode", "list_approval_requests", @@ -788,6 +795,18 @@ def dispatch(self, name: str, arguments: Optional[dict]) -> dict: return self._run(name[len("run_") :], arguments) raise BridgeError("unknown tool name") + def _handoff_dispatch(self, name: str, arguments: dict) -> dict: + if name == "verify_handoff": + return self.handoffs.verify(arguments.get("handoff")) + if not self.allow_run: + raise BridgeError("runs are disabled on this server, so it has no handoffs") + return self.handoffs.get( + arguments.get("run_id", ""), + public=bool(arguments.get("public", False)), + result_for=lambda run_id: self.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0}), + run_dir_for=self._safe_run_dir, + ) + def _list_workflows(self) -> dict: workflows = [] for name, entry in self.catalog.items(): diff --git a/packages/flow/openadapt_flow/agent/cli.py b/packages/flow/openadapt_flow/agent/cli.py index 495c2a681b..94d783c8bc 100644 --- a/packages/flow/openadapt_flow/agent/cli.py +++ b/packages/flow/openadapt_flow/agent/cli.py @@ -610,6 +610,54 @@ def build_parser() -> argparse.ArgumentParser: "long so teach_repair acts on it (default 300; 0 turns it off)." ), ) + p.add_argument( + "--handoffs", + action="store_true", + help=( + "Add get_handoff (a run's result with its signed receipt, to pass " + "to another agent) and verify_handoff (check one another agent " + "sent). --a2a turns this on." + ), + ) + p.add_argument( + "--handoff-keys", + default=None, + metavar="REGISTRY", + help=( + "The key registry verify_handoff trusts (openadapt.receipt-keys/v1). " + "Default: this computer's key and pinned OpenAdapt Cloud keys." + ), + ) + p.add_argument( + "--a2a", + action="store_true", + help=( + "Serve over the Agent2Agent (A2A) protocol (HTTP, JSON-RPC and " + "HTTP+JSON) instead of MCP stdio, with an Agent Card at " + "/.well-known/agent-card.json. Needs the a2a extra." + ), + ) + p.add_argument( + "--a2a-host", + default="127.0.0.1", + help="Address to listen on (default 127.0.0.1). Any other needs --a2a-token-file.", + ) + p.add_argument("--a2a-port", type=int, default=8770, help="Port (default 8770)") + p.add_argument( + "--a2a-public-url", + default=None, + metavar="URL", + help="The URL other agents use to reach this server, for the Agent Card.", + ) + p.add_argument( + "--a2a-token-file", + default=None, + metavar="FILE", + help=( + "A file holding the bearer token (32+ characters) every A2A request " + "must carry. Required off loopback." + ), + ) p.set_defaults(func=_cmd_serve) repair = sub.add_parser( @@ -784,10 +832,42 @@ def _cmd_serve(args: argparse.Namespace) -> int: from openadapt_flow.agent.tutorial import TutorialError def serve(*bridges: Any, **options: Any) -> None: + bridge = bridges[0] if bridges else None + if bridge is not None and (args.handoffs or args.a2a): + from openadapt_flow.agent.handoff_tools import HandoffTools + + bridge.handoffs = HandoffTools(registry_path=args.handoff_keys) + if args.a2a: + from openadapt_flow.agent import a2a_server + + a2a_server.serve(bridge, a2a_config) + return from openadapt_flow.agent.mcp import serve as serve_mcp serve_mcp(*bridges, **options) + a2a_config = None + if args.a2a: + problem = _a2a_problem(args) + if problem: + print(f"serve: {problem}", file=sys.stderr) + return 2 + from openadapt_flow.agent import a2a_server + + try: + a2a_config = a2a_server.A2AConfig( + host=args.a2a_host, + port=args.a2a_port, + public_url=args.a2a_public_url, + token=a2a_server.read_token(args.a2a_token_file), + ) + except (OSError, ValueError) as exc: + print(f"serve: {exc}", file=sys.stderr) + return 2 + elif args.a2a_token_file or args.a2a_public_url: + print("serve: the --a2a-* flags need --a2a", file=sys.stderr) + return 2 + if args.guard: return _serve_guard(args, serve) if args.verify: @@ -1488,6 +1568,27 @@ def _config_approvers(args: argparse.Namespace) -> Any: ) from None +def _a2a_problem(args: argparse.Namespace) -> Optional[str]: + """Why --a2a can't be combined with these flags, or None.""" + from openadapt_flow.agent import a2a_server + + for flag, value in ( + ("--authoring", args.authoring), + ("--guard", args.guard), + ("--verify", args.verify), + ("--teach", args.teach), + ("--teach-browser", args.teach_browser), + ): + if value: + return ( + f"--a2a serves run and handoff tools only; {flag} needs a person " + "in an MCP client, so it stays on MCP stdio" + ) + if not a2a_server.a2a_available(): + return a2a_server.A2A_INSTALL_HINT + return None + + def _attach_ledger(args: argparse.Namespace, bridge: Any, runs_dir: Path) -> None: """Give the bridge a task ledger one level inside its runs folder. diff --git a/packages/flow/openadapt_flow/agent/contract_call.py b/packages/flow/openadapt_flow/agent/contract_call.py new file mode 100644 index 0000000000..a7884c9bc6 --- /dev/null +++ b/packages/flow/openadapt_flow/agent/contract_call.py @@ -0,0 +1,94 @@ +"""One gate for a tool call, whichever transport it came in on. + +MCP (:mod:`openadapt_flow.agent.mcp`) and the A2A protocol adapter +(:mod:`openadapt_flow.agent.a2a_server`) both call these, so a request over +A2A passes exactly the checks the same request over MCP passes: + +* the arguments must match the tool's input schema, and the error never + echoes input values; +* a run goes through the task ledger's ``check_run`` first, and the ledger + records every result this server returns; +* the tool is dispatched by the transport-agnostic bridge, which applies the + run mode, the request-id ledger, intake grants and Flow's fail-closed + admission (``openadapt-flow run``). + +A remote transport also gets an allowlist. Tools that change state only after +a person confirms in the client's own form (attended decisions, admission +decisions, ``admit``) and the approval-answer tools are never on it: a +message from another agent is never a person's approval. +""" + +from __future__ import annotations + +import logging +from typing import Any, Callable, Mapping, Optional + +from jsonschema import ValidationError, validate + +from openadapt_flow.agent.bridge import AgentBridge, BridgeError + +_LOG = logging.getLogger(__name__) + +#: What a remote agent may call. Read-only tools plus run_workflow, which +#: is itself gated by the server's mode (production needs --mode production). +REMOTE_TOOLS = frozenset( + {"list_workflows", "run_workflow", "get_run", "get_handoff", "verify_handoff"} +) + + +def validate_arguments(spec: Any, arguments: Optional[Mapping[str, Any]]) -> None: + """Refuse arguments that don't match the schema, without echoing them.""" + try: + validate(dict(arguments or {}), spec.input_schema) + except ValidationError: + # ValidationError text contains input values, so never return it. + raise BridgeError( + getattr(spec, "usage", None) or "tool arguments do not match the input schema" + ) from None + + +def call_with_ledger( + ledger: Any, + name: str, + payload: dict[str, Any], + dispatch: Callable[[dict[str, Any]], dict[str, Any]], + *, + taught_run: bool = False, +) -> dict[str, Any]: + """Dispatch through the task ledger: check a run first, record its result.""" + if ledger is None: + return dispatch(payload) + if ledger.handles(name): + return ledger.dispatch(name, payload) + if name == "run_workflow" or taught_run: + ledger.check_run(payload) + result = dispatch(payload) + # Item status comes only from this server's own results. A ledger + # failure never hides a run's result from the caller. + try: + ledger.observe("run_workflow" if taught_run else name, payload, result) + except Exception: + _LOG.exception("could not record a result in the task ledger") + return result + + +def call_remote_tool( + bridge: AgentBridge, + name: str, + arguments: Optional[Mapping[str, Any]], + *, + allowed: frozenset[str] = REMOTE_TOOLS, +) -> dict[str, Any]: + """The whole gate for one call from a remote agent. Blocking.""" + if name not in allowed: + raise BridgeError("that tool is not available to a remote agent") + spec = next((s for s in bridge.list_tool_specs() if s.name == name), None) + if spec is None: + raise BridgeError("unknown or unavailable tool name") + validate_arguments(spec, arguments) + return call_with_ledger( + bridge.ledger, + name, + dict(arguments or {}), + lambda payload: bridge.dispatch(name, payload), + ) diff --git a/packages/flow/openadapt_flow/agent/handoff_tools.py b/packages/flow/openadapt_flow/agent/handoff_tools.py new file mode 100644 index 0000000000..6de811a987 --- /dev/null +++ b/packages/flow/openadapt_flow/agent/handoff_tools.py @@ -0,0 +1,134 @@ +"""Handoff tools for ``openadapt agent serve --handoffs`` (MCP and A2A alike). + +* ``get_handoff``: a finished run's public result with its receipt attached + (``openadapt.handoff/v1``), ready to pass to another agent. +* ``verify_handoff``: check a handoff another agent sent, against the keys + this server pins, and return the verdict (:mod:`openadapt_flow.handoff`). + +Both are read-only. ``get_handoff`` reads only this server's own runs folder +and never sends ``receipt.private.json``. ``verify_handoff`` trusts only the +operator's pinned registry, never a key inside the handoff. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Callable, Optional, Sequence + +_READ_ONLY = { + "readOnlyHint": True, + "destructiveHint": False, + "idempotentHint": True, + "openWorldHint": False, +} +_RUN_ID_PATTERN = r"^run-[A-Za-z0-9._-]{1,124}$" + +HANDOFF_TOOLS = ("get_handoff", "verify_handoff") + + +class HandoffTools: + """The handoff tool surface over one bridge's runs folder.""" + + def __init__( + self, + *, + registry_path: Optional[Path] = None, + registry: Optional[Sequence[Any]] = None, + ) -> None: + self.registry_path = Path(registry_path) if registry_path else None + self._registry = list(registry) if registry is not None else None + + def registry(self) -> list[Any]: + if self._registry is None: + from openadapt_flow.handoff import load_registry + + self._registry = load_registry(self.registry_path) + return self._registry + + def list_tool_specs(self, *, runs_enabled: bool) -> list[Any]: + from openadapt_flow.agent.bridge import ToolSpec + + specs = [] + if runs_enabled: + specs.append( + ToolSpec( + name="get_handoff", + description=( + "Get a run's result with its signed receipt attached, " + "to hand to another agent. The receiving agent checks " + "it with verify_handoff or `openadapt handoff verify`. " + "Only finished runs have a receipt." + ), + input_schema={ + "type": "object", + "properties": { + "run_id": {"type": "string", "pattern": _RUN_ID_PATTERN}, + "public": { + "type": "boolean", + "default": False, + "description": ( + "Attach the public card instead of the full " + "receipt, if the run has one." + ), + }, + }, + "required": ["run_id"], + "additionalProperties": False, + }, + annotations=_READ_ONLY, + ) + ) + specs.append( + ToolSpec( + name="verify_handoff", + description=( + "Check a handoff another agent sent (an openadapt.handoff/v1 " + "document) against the keys this computer pins. Returns who " + "signed it, whether it is intact, which checks passed and " + "which were not checked, and any confirmation read from the " + "other party's system. A valid signature proves who signed, " + "not that the claim is true." + ), + input_schema={ + "type": "object", + "properties": { + "handoff": { + "type": "object", + "description": "The openadapt.handoff/v1 document.", + } + }, + "required": ["handoff"], + "additionalProperties": False, + }, + annotations=_READ_ONLY, + ) + ) + return specs + + def handles(self, name: str) -> bool: + return name in HANDOFF_TOOLS + + def verify(self, document: Any) -> dict[str, Any]: + from openadapt_flow.handoff import verify_handoff + + return verify_handoff(document, self.registry()).to_dict() + + def get( + self, + run_id: str, + *, + public: bool, + result_for: Callable[[str], dict[str, Any]], + run_dir_for: Callable[[str], Path], + ) -> dict[str, Any]: + from openadapt_flow.agent.bridge import BridgeError + from openadapt_flow.handoff import HandoffError, make_handoff, receipt_for_run + + result = result_for(run_id) + if result.get("outcome") == "running": + raise BridgeError("the run is still running; it has no receipt yet") + try: + receipt = receipt_for_run(run_dir_for(run_id), public=public) + return make_handoff(result, receipt, name=f"{run_id}.result.json") + except HandoffError as exc: + raise BridgeError(f"no handoff for this run: {exc}") from None diff --git a/packages/flow/openadapt_flow/agent/mcp.py b/packages/flow/openadapt_flow/agent/mcp.py index 1c405173dc..85b7e3047a 100644 --- a/packages/flow/openadapt_flow/agent/mcp.py +++ b/packages/flow/openadapt_flow/agent/mcp.py @@ -26,7 +26,6 @@ import anyio import mcp.server.stdio as _mcp_stdio import mcp.types as types -from jsonschema import ValidationError, validate from mcp.server.lowlevel import Server from mcp.server.stdio import stdio_server @@ -34,6 +33,7 @@ from openadapt_flow.agent.attended import ATTENDED_TOOLS from openadapt_flow.agent.authoring import AuthoringBridge from openadapt_flow.agent.bridge import AgentBridge, BridgeError +from openadapt_flow.agent.contract_call import call_with_ledger, validate_arguments __all__ = ["HUMAN_CONFIRMED_TOOLS", "build_server", "serve"] @@ -369,14 +369,8 @@ async def _call_tool( raise BridgeError("unknown or unavailable tool name") # MCP 2 removed the low-level decorator's schema validation. # Keep it explicit on both SDKs, before confirmation or dispatch. - # ValidationError text contains input values, so never return it. - try: - validate(arguments or {}, spec.input_schema) - except ValidationError: - raise BridgeError( - getattr(spec, "usage", None) - or "tool arguments do not match the input schema" - ) from None + # The same gate serves the A2A adapter (contract_call). + validate_arguments(spec, arguments) human_confirmed = False teaching = teach is not None and teach.handles(name) held_by_person: str | None = None @@ -418,25 +412,14 @@ async def _call_tool( person = await _ask_person_name(context, message) def call() -> dict[str, Any]: - payload = dict(arguments or {}) - if ledger is None: - return dispatch(payload) - if ledger.handles(name): - return ledger.dispatch(name, payload) # A taught workflow's own tool is a run_workflow call. - taught_run = teaching and name in teach.taught - if name == "run_workflow" or taught_run: - ledger.check_run(payload) - result = dispatch(payload) - # Item status comes only from this server's own results. A - # ledger failure never hides a run's result from the caller. - try: - ledger.observe( - "run_workflow" if taught_run else name, payload, result - ) - except Exception: - _LOG.exception("could not record a result in the task ledger") - return result + return call_with_ledger( + ledger, + name, + dict(arguments or {}), + dispatch, + taught_run=bool(teaching and name in teach.taught), + ) def dispatch(payload: dict[str, Any]) -> dict[str, Any]: if guard is not None and guard.handles(name): diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py new file mode 100644 index 0000000000..e9c6ae282a --- /dev/null +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -0,0 +1,221 @@ +"""CLI: ``openadapt-flow handoff`` -- attach a run's receipt to what one agent +hands another, and verify one on arrival. See ``docs/HANDOFFS.md``. + + openadapt-flow handoff send result.json --run RUN_DIR --out result.handoff.json + openadapt-flow handoff send claim.pdf --run RUN_DIR --detached + openadapt-flow handoff send result.json --run RUN_DIR --post https://agent.example/inbox + openadapt-flow handoff verify result.handoff.json --keys keys.json +""" + +from __future__ import annotations + +import argparse +import ipaddress +import json +import sys +import urllib.parse +import urllib.request +from pathlib import Path +from typing import Any, Optional + + +def register(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser( + "handoff", + help=( + "Attach a run's receipt to what one agent hands another, and " + "verify one on arrival" + ), + allow_abbrev=False, + ) + hsub = p.add_subparsers(dest="handoff_command", required=True) + + s = hsub.add_parser( + "send", + help="Attach a run's receipt to a payload (inline, detached, or POSTed)", + allow_abbrev=False, + ) + s.add_argument("payload", help="the file to hand off ('-' reads stdin)") + source = s.add_mutually_exclusive_group(required=True) + source.add_argument("--run", metavar="RUN_DIR", help="the run whose receipt.json to attach") + source.add_argument("--receipt", metavar="FILE", help="a receipt.json or receipt.card.json") + s.add_argument( + "--public", + action="store_true", + help="with --run, attach the public card (receipt.card.json) instead", + ) + s.add_argument( + "--detached", + action="store_true", + help=( + "leave the payload out and write PAYLOAD.handoff.json beside it, " + "for a file sent as an attachment" + ), + ) + s.add_argument("--media-type", help="the payload's media type") + s.add_argument("--out", help="where to write the handoff (default: stdout)") + s.add_argument( + "--post", + metavar="URL", + help=( + "POST the handoff to this URL (a webhook or agent inbox). https, " + "or http only to this computer" + ), + ) + s.set_defaults(func=cmd_send) + + v = hsub.add_parser( + "verify", + help="Verify a handoff's receipt against your pinned keys", + allow_abbrev=False, + ) + v.add_argument("handoff", help="a .handoff.json document ('-' reads stdin)") + v.add_argument( + "--payload", + help=( + "the detached payload file (default: the handoff's path without " + ".handoff.json, if it exists)" + ), + ) + v.add_argument( + "--keys", + metavar="REGISTRY", + help=( + "your pinned key registry (openadapt.receipt-keys/v1). Default: " + "this computer's key and pinned OpenAdapt Cloud keys" + ), + ) + v.add_argument("--json", action="store_true", help="print the verdict as JSON") + v.set_defaults(func=cmd_verify) + + +def _read(path: str) -> bytes: + if path == "-": + return sys.stdin.buffer.read() + return Path(path).read_bytes() + + +def _post_allowed(url: str) -> bool: + parsed = urllib.parse.urlparse(url) + if parsed.scheme == "https" and parsed.hostname: + return True + if parsed.scheme != "http" or not parsed.hostname: + return False + if parsed.hostname == "localhost": + return True + try: + return ipaddress.ip_address(parsed.hostname).is_loopback + except ValueError: + return False + + +def post_handoff(url: str, document: dict[str, Any], *, timeout: float = 30.0) -> int: + """POST a handoff document as its own media type. Returns the HTTP status.""" + from openadapt_flow.handoff import MEDIA_TYPE + + if not _post_allowed(url): + raise ValueError("--post needs an https URL, or http to this computer") + request = urllib.request.Request( + url, + data=json.dumps(document).encode("utf-8"), + headers={"Content-Type": MEDIA_TYPE}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 - scheme checked + return int(response.status) + + +def cmd_send(args: argparse.Namespace) -> int: + from openadapt_flow import handoff as h + + if args.detached and args.payload == "-": + print("handoff send: --detached needs a payload file", file=sys.stderr) + return 2 + if args.public and not args.run: + print("handoff send: --public goes with --run", file=sys.stderr) + return 2 + try: + data = _read(args.payload) + if args.run: + receipt = h.receipt_for_run(Path(args.run), public=args.public) + else: + receipt = h._loads_strict(Path(args.receipt).read_text("utf-8")) + document = h.make_handoff( + data, + receipt, + name=None if args.payload == "-" else args.payload, + media_type=args.media_type, + detached=args.detached, + ) + except h.HandoffError as exc: + print(f"handoff send: {exc}", file=sys.stderr) + return 2 + except (OSError, ValueError) as exc: + print(f"handoff send: {type(exc).__name__}: {exc}", file=sys.stderr) + return 2 + text = json.dumps(document, indent=2, sort_keys=True) + "\n" + out: Optional[Path] = Path(args.out) if args.out else None + if out is None and args.detached: + out = h.detached_path(Path(args.payload)) + if out is not None: + out.write_text(text, encoding="utf-8") + print(f"handoff: {out}", file=sys.stderr) + elif not args.post: + sys.stdout.write(text) + if args.post: + try: + status = post_handoff(args.post, document) + except (OSError, ValueError) as exc: + print(f"handoff send: POST failed: {exc}", file=sys.stderr) + return 1 + print(f"handoff: POST {args.post} -> HTTP {status}", file=sys.stderr) + if status >= 300: + return 1 + return 0 + + +def _print_verdict(verdict: dict[str, Any]) -> None: + for line in verdict["signer_lines"]: + print(line) + if verdict["integrity"] != "intact": + print(verdict["what_this_proves"][0]) + return + print(f"Outcome: {verdict['outcome']}") + checks = verdict["checks"] + print("Checks passed: " + (", ".join(checks["passed"]) or "none")) + if checks["incomplete"]: + print("Checks not complete: " + ", ".join(checks["incomplete"])) + print("Not checked: " + (", ".join(checks["not_checked"]) or "nothing listed")) + for line in verdict["confirmation_lines"]: + print(line) + for line in verdict["what_this_proves"]: + print(line) + + +def cmd_verify(args: argparse.Namespace) -> int: + from openadapt_types.receipt import RegistryError + + from openadapt_flow import handoff as h + + try: + raw = _read(args.handoff) + payload: Optional[bytes] = None + if args.payload: + payload = Path(args.payload).read_bytes() + elif args.handoff != "-" and args.handoff.endswith(h.DETACHED_SUFFIX): + beside = Path(args.handoff[: -len(h.DETACHED_SUFFIX)]) + if beside.is_file(): + payload = beside.read_bytes() + registry = h.load_registry(Path(args.keys) if args.keys else None) + except RegistryError as exc: + print(f"handoff verify: the key registry is refused ({exc.reason})", file=sys.stderr) + return 2 + except (OSError, ValueError) as exc: + print(f"handoff verify: {type(exc).__name__}: {exc}", file=sys.stderr) + return 2 + verdict = h.verify_handoff(raw, registry, payload=payload).to_dict() + if args.json: + print(json.dumps(verdict, indent=2, sort_keys=True)) + else: + _print_verdict(verdict) + return 0 if verdict["integrity"] == "intact" else 1 diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index 8d18591838..0d758f9f91 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -82,6 +82,7 @@ "push": "workflow push", "qualify": "qualify", "receipt": "verify receipt", + "handoff": "verify handoff", "reconcile": "verify reconcile", "record": "record", "redact-report": "inspect redact-report", diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index f3b8ad2404..1368ee3346 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -48,8 +48,6 @@ DETACHED_SUFFIX = ".handoff.json" #: Largest inline payload, in bytes. A bigger one goes detached. MAX_INLINE_BYTES = 1_048_576 -#: Read methods that look at the other party's system, not the sender's. -INDEPENDENT_READ_METHODS = frozenset({"portal_read_back", "api"}) WHAT_A_SIGNATURE_PROVES = ( "A valid signature proves who signed this receipt and that it has not " @@ -184,6 +182,12 @@ class Verdict: confirmation_lines: list[str] = field(default_factory=list) independent_confirmations: int = 0 what_this_proves: list[str] = field(default_factory=list) + #: The receiver's own read of its own record, when it made one + #: (:func:`decide`). ``None``: the receiver didn't check. + receiver_check: Optional[dict[str, Any]] = None + #: ``accept`` only when the receipt is intact and the receiver's own + #: record shows the claim; ``reject``; or ``unchecked`` (no own read). + decision: str = "unchecked" @property def ok(self) -> bool: @@ -205,6 +209,8 @@ def to_dict(self) -> dict[str, Any]: "confirmation_lines": list(self.confirmation_lines), "independent_confirmations": self.independent_confirmations, "what_this_proves": list(self.what_this_proves), + "receiver_check": self.receiver_check, + "decision": self.decision, } @@ -213,6 +219,7 @@ def _refused(reason: str, detail: str = "", line: Optional[str] = None) -> Verdi return Verdict( integrity="refused", + decision="reject", reason=reason, detail=detail, signer_lines=[line or refusal_line(reason)], @@ -257,55 +264,39 @@ def _checks(statement: Mapping[str, Any]) -> dict[str, Any]: } -def _confirmations(statement: Mapping[str, Any]) -> list[dict[str, Any]]: - """Each counterparty confirmation, marked independent from its read method. +def _confirmations(statement: Mapping[str, Any], result: Any) -> list[dict[str, Any]]: + """Each counterparty confirmation, with the verifier's own independence flag. - Independence is decided here, from the closed ``read_method`` the signed - statement carries, never from anything else in the handoff. + :func:`openadapt_types.receipt.verify_receipt` decides independence from + the signed, closed ``read_method`` alone (``portal_read_back`` or + ``api``), never from anything else in the handoff. """ + items = [ + c + for c in (statement.get("predicate") or {}).get("confirmations") or [] + if isinstance(c, Mapping) + ] + flags = tuple(getattr(result, "independent", ()) or ()) + lines = tuple(getattr(result, "confirmation_lines", ()) or ()) out = [] - for item in (statement.get("predicate") or {}).get("confirmations") or []: - if not isinstance(item, Mapping): - continue - state = item.get("state") - read_method = item.get("read_method") - independent = read_method in INDEPENDENT_READ_METHODS and state in ( - "recorded_as_intended", - "recorded_differently", - ) + for index, item in enumerate(items): out.append( { "for_step": item.get("for_step"), "system_kind": item.get("system_kind"), - "state": state, - "read_method": read_method, + "state": item.get("state"), + "read_method": item.get("read_method"), "strength": item.get("strength"), "differing_count": item.get("differing_count"), - "independent": independent, + # Fail closed: a confirmation the verifier gave no flag for + # is not independent. + "independent": bool(flags[index]) if index < len(flags) else False, + "line": lines[index] if index < len(lines) else None, } ) return out -def _confirmation_line(item: Mapping[str, Any]) -> str: - system = str(item.get("system_kind") or "other").replace("_", " ") - state = item.get("state") - if state == "recorded_as_intended": - text = f"Confirmed in the other party's system ({system}): recorded as intended" - elif state == "recorded_differently": - text = ( - f"Confirmed in the other party's system ({system}): recorded " - f"differently ({item.get('differing_count') or 0} field(s) differ)" - ) - elif state == "acknowledged": - text = f"The other party ({system}) acknowledged it; not read back" - else: - text = f"Sent to the other party ({system}); no answer recorded" - if not item.get("independent"): - text += ". Reported by the sender, not read independently" - return text - - def _payload_verdict( doc_payload: Mapping[str, Any], statement: Mapping[str, Any], @@ -390,10 +381,8 @@ def verify_handoff( payload_result, problem = _payload_verdict(doc_payload, statement, payload) if problem: return _refused("payload_mismatch", problem, "Not verified: " + problem) - confirmations = _confirmations(statement) - lines = list(getattr(result, "confirmation_lines", ()) or ()) - if not lines: - lines = [_confirmation_line(c) for c in confirmations] + confirmations = _confirmations(statement, result) + lines = [c["line"] for c in confirmations if c["line"]] independent = sum(1 for c in confirmations if c["independent"]) proves = [WHAT_A_SIGNATURE_PROVES] if result.demo: @@ -424,6 +413,110 @@ def verify_handoff( ) +# -- the receiver's own record ------------------------------------------------------ + +#: States a receiver's own read can return, as in a counterparty confirmation. +RECEIVER_STATES = ("recorded_as_intended", "recorded_differently", "not_found", "unreadable") + +ACCEPT_LINE = ( + "Accepted: your own system shows the record the handoff describes. That " + "read, not the sender's signature, is what confirms the claim." +) +UNCHECKED_LINE = ( + "Not accepted: the signature shows who sent this, but a sender-signed " + "receipt can't prove the claim. Read your own record before acting on it." +) + + +@dataclass(frozen=True) +class ReceiverRecord: + """The receiver's own read of its own system for one handoff's claim.""" + + state: str + #: Closed field ids that differ, never their values. + differing_fields: tuple[str, ...] = () + #: How the receiver read it, e.g. ``api`` or ``portal_read_back``. + read_method: str = "api" + + def __post_init__(self) -> None: + if self.state not in RECEIVER_STATES: + raise ValueError(f"unknown receiver state {self.state!r}") + + +def _payload_value(document: Mapping[str, Any], supplied: Optional[bytes]) -> Any: + doc_payload = document.get("payload") or {} + if "content" in doc_payload: + return doc_payload["content"] + data = supplied + if data is None and "content_base64" in doc_payload: + data = base64.b64decode(str(doc_payload["content_base64"]), validate=True) + if data is None: + raise HandoffError("the payload is not available to check") + try: + return json.loads(data.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + return data + + +def decide( + document: Any, + registry: Sequence[Any], + receiver_check: Optional[Any] = None, + *, + payload: Optional[bytes] = None, +) -> Verdict: + """Verify a handoff, then confirm its claim in the receiver's own record. + + ``receiver_check(claim) -> ReceiverRecord`` reads the receiver's own + system for the payload's claim. The handoff is accepted only when the + receipt is intact and that read is ``recorded_as_intended``. A fabricated + or differing claim is rejected even with a valid signature from a + trusted sender. Without a ``receiver_check`` the decision is + ``unchecked``: the receipt alone never accepts a claim. Any error in the + read rejects (fails closed). + """ + if isinstance(document, (bytes, str)): + try: + document = _loads_strict(document) + except (UnicodeDecodeError, ValueError): + document = None + verdict = verify_handoff(document, registry, payload=payload) + if not verdict.ok: + verdict.decision = "reject" + return verdict + if receiver_check is None: + verdict.what_this_proves.append(UNCHECKED_LINE) + return verdict + try: + record = receiver_check(_payload_value(document, payload)) + if not isinstance(record, ReceiverRecord): + raise TypeError("receiver_check returns a ReceiverRecord") + except Exception as exc: # noqa: BLE001 - an unreadable record never accepts + record = ReceiverRecord("unreadable") + verdict.detail = f"the receiver's own read failed: {type(exc).__name__}" + verdict.receiver_check = { + "state": record.state, + "differing_fields": list(record.differing_fields), + "read_method": record.read_method, + } + if record.state == "recorded_as_intended": + verdict.decision = "accept" + verdict.what_this_proves.append(ACCEPT_LINE) + else: + verdict.decision = "reject" + verdict.what_this_proves.append( + { + "recorded_differently": ( + "Rejected: your own system has this record with different " + f"values ({len(record.differing_fields)} field(s) differ)." + ), + "not_found": "Rejected: your own system has no such record.", + "unreadable": "Rejected: your own record could not be read.", + }[record.state] + ) + return verdict + + def load_registry(path: Optional[Path] = None) -> list[Any]: """The receiver's pinned keys: a registry file, or this computer's defaults.""" if path is not None: @@ -443,11 +536,13 @@ def detached_path(payload_path: Path) -> Path: "DETACHED_SUFFIX", "EXTENSION_URI", "HandoffError", - "INDEPENDENT_READ_METHODS", "MEDIA_TYPE", "SCHEMA", "VERDICT_SCHEMA", + "RECEIVER_STATES", + "ReceiverRecord", "Verdict", + "decide", "detached_path", "load_registry", "make_handoff", diff --git a/packages/flow/pyproject.toml b/packages/flow/pyproject.toml index d0ebac63a9..8c399f0fde 100644 --- a/packages/flow/pyproject.toml +++ b/packages/flow/pyproject.toml @@ -14,6 +14,20 @@ license = { text = "MIT" } # the identity and dense-surface safety evidence first. requires-python = ">=3.10,<3.13" authors = [{ name = "OpenAdapt.AI" }] +keywords = [ + "gui", + "automation", + "workflow", + "verification", + "mcp", + "a2a", + "agent2agent", + "agent-card", + "agent-handoff", + "receipts", + "in-toto", + "dsse", +] # The Python classifiers feed the PyPI "python versions" badge; keep them in # step with requires-python above. classifiers = [ @@ -310,6 +324,15 @@ agent = [ "anyio>=4.0", ] +# Agent-to-agent handoffs over the A2A (Agent2Agent) protocol: +# `openadapt-agent serve --a2a`. a2a-sdk is Apache-2.0 (a2aproject/a2a-python); +# http-server adds Starlette and sse-starlette (BSD-3-Clause). +a2a = [ + "openadapt-flow[agent]", + "a2a-sdk[http-server]>=1.3.1,<2", + "uvicorn>=0.29", +] + # Verified write tools for agent frameworks # (openadapt_flow.integrations.agents): one extra per framework, each only # the framework itself. Every write the wrapped tool makes is read back from diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py new file mode 100644 index 0000000000..2412c14bac --- /dev/null +++ b/packages/flow/tests/test_handoff.py @@ -0,0 +1,328 @@ +"""Agent-to-agent handoffs: a payload with its run's receipt, verified on arrival. + +Receipts come from Flow's real writer (``write_receipt_record``) over a run +report, or from the shared ``record/run/v1`` vectors for confirmation lines. +""" + +from __future__ import annotations + +import base64 +import json +from pathlib import Path + +import pytest + +pytest.importorskip("cryptography") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow.__main__ import main as flow_main # noqa: E402 +from openadapt_flow.receipt_record import PRIVATE_FILE, write_receipt_record # noqa: E402 +from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402 +from openadapt_types import receipt as r # noqa: E402 + +VECTORS = ( + Path(__file__).resolve().parents[2] / "types" / "tests" / "vectors" / "record-run-v1" +) + +REPORT = { + "workflow_name": "Demo Triage", + "execution_outcome": "VERIFIED", + "run_id": "run-handoff-1", + "started_at": "2026-11-21T01:02:03Z", + "results": [ + {"step_id": "s1", "ok": True}, + {"step_id": "s2", "ok": True, "effect_verified": True, "postconditions_ok": True}, + ], +} + + +def _signer() -> SoftwareSigner: + return SoftwareSigner(Ed25519PrivateKey.generate(), "generated") + + +def _registry(*signers: SoftwareSigner) -> list[r.RoleKey]: + return r.parse_registry( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [{**s.registry_entry(), "role": "this_computer"} for s in signers], + } + ) + + +@pytest.fixture() +def signer() -> SoftwareSigner: + return _signer() + + +@pytest.fixture() +def run_dir(tmp_path: Path, signer: SoftwareSigner) -> Path: + run = tmp_path / "run-handoff-1" + run.mkdir() + (run / "report.json").write_text(json.dumps(REPORT, indent=2)) + write_receipt_record(run, signer=signer, flow_version="3.4.0") + return run + + +def test_a_good_handoff_says_who_signed_and_what_that_does_not_prove(run_dir, signer): + doc = h.make_handoff({"outcome": "done", "count": 3}, h.receipt_for_run(run_dir)) + verdict = h.verify_handoff(doc, _registry(signer)) + assert verdict.ok and verdict.integrity == "intact" + assert verdict.signer_roles == ["this_computer"] + assert verdict.signer_lines == ["Signed by this computer"] + assert verdict.outcome == "VERIFIED" + assert verdict.checks["writes"] == {"confirmed": 1, "refuted": 0, "not_checked": 0} + assert "field_values" in verdict.checks["not_checked"] + # The honesty rule: a signature proves who signed, not that it is true. + assert verdict.what_this_proves[0] == h.WHAT_A_SIGNATURE_PROVES + assert "does not prove" in verdict.what_this_proves[0] + # The receipt signs the report, not this payload. + assert verdict.payload["bound"] is False + assert verdict.payload["note"] == h.NOT_BOUND + assert verdict.confirmations == [] and verdict.independent_confirmations == 0 + + +def test_the_signed_report_itself_is_a_bound_payload(run_dir, signer): + report = (run_dir / "report.json").read_bytes() + doc = h.make_handoff(report, h.receipt_for_run(run_dir), name="report.json") + verdict = h.verify_handoff(doc, _registry(signer)) + assert verdict.payload["bound"] is True + assert verdict.payload["bound_to"] == "report.json" + + +def test_a_tampered_receipt_is_refused(run_dir, signer): + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) + statement = json.loads(base64.b64decode(doc["receipt"]["payload"])) + statement["predicate"]["outcome"] = "VERIFIED" + statement["predicate"]["model_calls"] = 7 + doc["receipt"]["payload"] = base64.b64encode( + r.canonical_json(statement).encode() + ).decode() + verdict = h.verify_handoff(doc, _registry(signer)) + assert not verdict.ok + assert verdict.reason == "bad_signature" + assert verdict.signer_lines == [ + "Not verified: the receipt was changed after it was signed" + ] + + +def test_an_unknown_signer_is_refused_even_when_the_signature_is_valid(run_dir): + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) + verdict = h.verify_handoff(doc, _registry(_signer())) + assert not verdict.ok and verdict.reason == "unknown_signer" + assert verdict.signer_lines == [r.UNKNOWN_SIGNER_LINE] + assert h.verify_handoff(doc, []).reason == "unknown_signer" + + +def test_a_swapped_payload_is_caught_or_reported_unbound(run_dir, signer): + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) + # Swap the content but keep the old digest: the wrapper no longer matches. + swapped = json.loads(json.dumps(doc)) + swapped["payload"]["content"] = {"outcome": "done", "amount": 1_000_000} + verdict = h.verify_handoff(swapped, _registry(signer)) + assert not verdict.ok and verdict.reason == "payload_mismatch" + # Re-staple the receipt to a new payload with its own digest: the receipt + # still verifies, and the verdict says nothing ties the two together. + restapled = h.make_handoff({"outcome": "done", "amount": 1_000_000}, doc["receipt"]) + verdict = h.verify_handoff(restapled, _registry(signer)) + assert verdict.ok and verdict.payload["bound"] is False + + +def test_private_openings_never_travel(run_dir): + private = json.loads((run_dir / PRIVATE_FILE).read_text()) + with pytest.raises(h.HandoffError, match="never leaves this computer"): + h.make_handoff({"x": 1}, private) + doc = h.make_handoff({"x": 1}, h.receipt_for_run(run_dir)) + doc["receipt"] = private + assert h.verify_handoff(doc, []).reason == "malformed" + + +def test_a_handoff_with_extra_fields_or_another_schema_is_refused(run_dir, signer): + doc = h.make_handoff({"x": 1}, h.receipt_for_run(run_dir)) + assert h.verify_handoff({**doc, "signer_role": "openadapt_cloud"}, []).reason == ( + "malformed" + ) + assert h.verify_handoff({**doc, "schema": "other/v1"}, []).reason == "unknown_schema" + assert h.verify_handoff(b"not json", []).reason == "malformed" + + +def test_a_detached_handoff_checks_the_file_beside_it(run_dir, signer, tmp_path): + attachment = tmp_path / "claim.pdf" + attachment.write_bytes(b"%PDF-1.7 synthetic") + doc = h.make_handoff( + attachment.read_bytes(), + h.receipt_for_run(run_dir), + name=str(attachment), + detached=True, + ) + assert "content" not in doc["payload"] and "content_base64" not in doc["payload"] + assert doc["payload"]["name"] == "claim.pdf" + good = h.verify_handoff(doc, _registry(signer), payload=attachment.read_bytes()) + assert good.ok and good.payload["present"] is True + bad = h.verify_handoff(doc, _registry(signer), payload=b"another file") + assert not bad.ok and bad.reason == "payload_mismatch" + missing = h.verify_handoff(doc, _registry(signer)) + assert missing.ok and missing.payload["present"] is False + + +def _vector(name: str) -> dict: + return json.loads((VECTORS / name).read_text()) + + +def _vector_registry(case: dict) -> list[r.RoleKey]: + return r.parse_registry(json.loads((VECTORS / case["registry"]).read_text())) + + +@pytest.mark.parametrize( + ("name", "independent"), + [ + ("confirmation-recorded-as-intended.json", True), + ("confirmation-recorded-differently.json", True), + ("confirmation-sent.json", False), + ("confirmation-acknowledged.json", False), + ], +) +def test_confirmation_lines_come_from_the_shared_verifier(name, independent): + case = _vector(name) + doc = h.make_handoff({"outcome": "done"}, case["document"]) + verdict = h.verify_handoff(doc, _vector_registry(case)) + assert verdict.ok + assert [c["independent"] for c in verdict.confirmations] == [independent] + # Without the private openings the line carries no time; otherwise it is + # the shared verifier's own line. + expected = r.verify_receipt(case["document"], _vector_registry(case)) + assert verdict.confirmation_lines == list(expected.confirmation_lines) + assert verdict.signer_lines == ["Signed by this computer"] + if independent: + assert verdict.independent_confirmations == 1 + assert any("read back from the other party" in line for line in verdict.what_this_proves) + else: + assert any("rests on the signer's word" in line for line in verdict.what_this_proves) + + +def test_a_tampered_confirmation_is_refused(): + case = _vector("confirmation-tampered.json") + doc = h.make_handoff({"outcome": "done"}, case["document"]) + assert h.verify_handoff(doc, _vector_registry(case)).reason == "bad_signature" + + +def test_cli_send_and_verify_inline_and_detached(run_dir, signer, tmp_path, capsys): + keys = tmp_path / "keys.json" + keys.write_text( + json.dumps( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [{**signer.registry_entry(), "role": "this_computer"}], + } + ) + ) + payload = tmp_path / "result.json" + payload.write_text('{"outcome": "done"}') + out = tmp_path / "result.handoff.json" + assert flow_main(["handoff", "send", str(payload), "--run", str(run_dir), "--out", str(out)]) == 0 + assert flow_main(["handoff", "verify", str(out), "--keys", str(keys), "--json"]) == 0 + verdict = json.loads(capsys.readouterr().out) + assert verdict["integrity"] == "intact" and verdict["signer_roles"] == ["this_computer"] + + assert flow_main(["handoff", "send", str(payload), "--run", str(run_dir), "--detached"]) == 0 + detached = h.detached_path(payload) + assert detached.is_file() + assert flow_main(["handoff", "verify", str(detached), "--keys", str(keys)]) == 0 + text = capsys.readouterr().out + assert "Signed by this computer" in text and h.WHAT_A_SIGNATURE_PROVES in text + payload.write_text('{"outcome": "done", "changed": true}') + assert flow_main(["handoff", "verify", str(detached), "--keys", str(keys)]) == 1 + + other = tmp_path / "other.json" + other.write_text(json.dumps({"schema": r.REGISTRY_SCHEMA, "keys": []})) + assert flow_main(["handoff", "verify", str(out), "--keys", str(other)]) == 1 + + +def test_cli_send_refuses_the_private_file_and_plain_http(run_dir, tmp_path, capsys): + payload = tmp_path / "p.json" + payload.write_text("{}") + code = flow_main( + ["handoff", "send", str(payload), "--receipt", str(run_dir / PRIVATE_FILE)] + ) + assert code == 2 + assert "never leaves this computer" in capsys.readouterr().err + from openadapt_flow.cli_handoff import _post_allowed + + assert _post_allowed("https://agent.example/inbox") + assert _post_allowed("http://127.0.0.1:9000/inbox") + assert not _post_allowed("http://agent.example/inbox") + assert not _post_allowed("file:///etc/passwd") + + +def test_cli_send_posts_to_a_local_webhook(run_dir, signer, tmp_path): + import threading + from http.server import BaseHTTPRequestHandler, HTTPServer + + received: list[tuple[str, bytes]] = [] + + class Inbox(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + body = self.rfile.read(int(self.headers["Content-Length"])) + received.append((self.headers["Content-Type"], body)) + self.send_response(202) + self.end_headers() + + server = HTTPServer(("127.0.0.1", 0), Inbox) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + payload = tmp_path / "p.json" + payload.write_text('{"outcome": "done"}') + url = f"http://127.0.0.1:{server.server_address[1]}/inbox" + assert flow_main(["handoff", "send", str(payload), "--run", str(run_dir), "--post", url]) == 0 + finally: + server.shutdown() + content_type, body = received[0] + assert content_type == h.MEDIA_TYPE + # The webhook receiver verifies exactly what arrived. + assert h.verify_handoff(body, _registry(signer)).ok + + +def test_decide_accepts_only_what_the_receivers_own_record_shows(run_dir, signer): + registry = _registry(signer) + receipt = h.receipt_for_run(run_dir) + records = {"ref-1": "note A", "ref-2": "note B"} + + def own_record(claim): + value = records.get(claim["ref"]) + if value is None: + return h.ReceiverRecord("not_found") + if value != claim["note"]: + return h.ReceiverRecord("recorded_differently", ("note",)) + return h.ReceiverRecord("recorded_as_intended") + + def decision(claim, check=own_record): + return h.decide(h.make_handoff(claim, receipt), registry, check) + + true = decision({"ref": "ref-1", "note": "note A"}) + assert true.decision == "accept" and true.what_this_proves[-1] == h.ACCEPT_LINE + assert true.receiver_check == { + "state": "recorded_as_intended", + "differing_fields": [], + "read_method": "api", + } + # A valid signature from a trusted sender does not save a false claim. + assert decision({"ref": "ref-9", "note": "x"}).decision == "reject" + differing = decision({"ref": "ref-2", "note": "note C"}) + assert differing.decision == "reject" + assert differing.receiver_check["differing_fields"] == ["note"] + + def broken(claim): + raise OSError("database is locked") + + assert decision({"ref": "ref-1", "note": "note A"}, broken).decision == "reject" + # No own read: never accepted on the receipt alone. + unchecked = h.decide(h.make_handoff({"ref": "ref-1"}, receipt), registry) + assert unchecked.decision == "unchecked" and unchecked.what_this_proves[-1] == h.UNCHECKED_LINE + # A refused receipt is rejected before the receiver reads anything. + calls = [] + refused = h.decide(h.make_handoff({"ref": "ref-1"}, receipt), [], calls.append) + assert refused.decision == "reject" and calls == [] diff --git a/packages/flow/uv.lock b/packages/flow/uv.lock index a84e4c492a..766c84ccfa 100644 --- a/packages/flow/uv.lock +++ b/packages/flow/uv.lock @@ -17,6 +17,31 @@ required-markers = [ "python_full_version < '3.11' and sys_platform == 'win32'", ] +[[package]] +name = "a2a-sdk" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "culsans" }, + { name = "google-api-core" }, + { name = "googleapis-common-protos" }, + { name = "httpx" }, + { name = "json-rpc" }, + { name = "packaging" }, + { name = "protobuf" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e6/ca/90d8c95185a53be332772d5b28c42bf1586a2214e8bd937e769f3d566d7c/a2a_sdk-1.3.1.tar.gz", hash = "sha256:f18465fd040d2f75728c8ec915315ff25c072d271e6faeb9fa85a29ac36076ea", size = 456720, upload-time = "2026-11-17T10:51:19.721Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/76/baed78b223d9919a013c625ed853ab220c2c932050d8ded974a4eaaf969b/a2a_sdk-1.3.1-py3-none-any.whl", hash = "sha256:6073b8c04989609d087b9fed18ec1c8a13ae7e56246cf7a23c7c55a1a2a3b813", size = 299006, upload-time = "2026-11-17T10:51:17.787Z" }, +] + +[package.optional-dependencies] +http-server = [ + { name = "sse-starlette" }, + { name = "starlette" }, +] + [[package]] name = "aardwolf" version = "0.2.14" @@ -47,6 +72,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4e/79/6e45e778c4c3cab39e0937b007b720c15f76c50c6453d153282d0fcc3588/aiofile-3.12.3-py3-none-any.whl", hash = "sha256:5c1bcc9e929c50834608e8cc1a4cc1d7503eb60c15a535b779fd39e2f372c017", size = 22122, upload-time = "2026-08-04T22:59:25.838Z" }, ] +[[package]] +name = "aiologic" +version = "0.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sniffio" }, + { name = "typing-extensions" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/7a/d51f2fde1e8ae8a83431f8e97b7a71e9358cdb1d4d2ce6be387fa44d68de/aiologic-0.17.1.tar.gz", hash = "sha256:2e1b93b9e88ced318c2a63ad7b382688f40cbfe40e3d42258d49dc9c5aea179d", size = 252354, upload-time = "2026-06-27T20:41:33.25Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/d3/2d310b1b839014034dba0cba685e492df8a5c7ad32c19cab7e979eed6554/aiologic-0.17.1-py3-none-any.whl", hash = "sha256:c66b319830fedb7ca3d2b2125fa6f5b653f89418c2a27ea76f259ec5f00943c0", size = 161331, upload-time = "2026-06-27T20:41:31.877Z" }, +] + [[package]] name = "alembic" version = "1.18.5" @@ -827,6 +866,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8e/b5/c2c5fce26f0ee40d21bafe7f191d29a34b35a65ac4fe8a1191d1983612e9/cryptography-50.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:c99c003e088647b8a5b7c145d6f78c335f6348332b62e142d411c4b63d1460b9", size = 3813796, upload-time = "2026-07-31T14:25:02.298Z" }, ] +[[package]] +name = "culsans" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiologic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/e3/49afa1bc180e0d28008ec6bcdf82a4072d1c7a41032b5b759b60814ca4b0/culsans-0.11.0.tar.gz", hash = "sha256:0b43d0d05dce6106293d114c86e3fb4bfc63088cfe8ff08ed3fe36891447fe33", size = 107546, upload-time = "2025-12-31T23:15:38.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/5d/9fb19fb38f6d6120422064279ea5532e22b84aa2be8831d49607194feda3/culsans-0.11.0-py3-none-any.whl", hash = "sha256:278d118f63fc75b9db11b664b436a1b83cc30d9577127848ba41420e66eb5a47", size = 21811, upload-time = "2025-12-31T23:15:37.189Z" }, +] + [[package]] name = "cwt" version = "3.3.0" @@ -1110,6 +1162,48 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/6c/c0/a98505f18594f1bce828bb159cec0fcf9860562f1a2c85913409fc8f3d9e/fsspec-2026.9.0-py3-none-any.whl", hash = "sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f", size = 221738, upload-time = "2026-09-18T17:50:41.341Z" }, ] +[[package]] +name = "google-api-core" +version = "2.44.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "google-auth" }, + { name = "googleapis-common-protos" }, + { name = "opentelemetry-api" }, + { name = "proto-plus" }, + { name = "protobuf" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/ef/63d89cb580f3a42c51db53b3d151352aa61b9c87ea8cfdd8d24ee6caa09d/google_api_core-2.44.0.tar.gz", hash = "sha256:5ab9a396965c1227d7dea4581e562b7018aa2bca96d2de0be5eb70dc9c8ab3a1", size = 288859, upload-time = "2026-11-05T18:39:43.265Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/73/4068d4b123d206f42e44d476b6ed4de773d81efc4e88101ff82e318b9a7a/google_api_core-2.44.0-py3-none-any.whl", hash = "sha256:8cb9ad8af28de9bc75121686d69b697ce0937e21fad2ad80c9a7e89f22b26e1f", size = 225627, upload-time = "2026-11-05T18:39:01.342Z" }, +] + +[[package]] +name = "google-auth" +version = "2.63.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "pyasn1-modules" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/04/0c/d09755ddb3fb67dcba41f35c04ba33377e5bcf73af6c022de33c3241532b/google_auth-2.63.0.tar.gz", hash = "sha256:f198b99dd49e81f96f54abce2c03d4dd28fb7e3c77702eb6ae1c5bf25435054c", size = 406302, upload-time = "2026-11-20T23:24:00.618Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/78/1c31250140faba4206c557b2bb16e8b1f1e42202864f0dbe0a8f4bc8dab2/google_auth-2.63.0-py3-none-any.whl", hash = "sha256:cbc065325f67511946d1a66672e4f47e71ed162ef1abd2bb8404ceec407c86ba", size = 270723, upload-time = "2026-11-20T23:23:59.008Z" }, +] + +[[package]] +name = "googleapis-common-protos" +version = "1.76.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/62/b6/bc095b23a3e0d978e75c8c18cabe4c11f791837410670e4486f0d539bfba/googleapis_common_protos-1.76.0.tar.gz", hash = "sha256:71db0e44a1d4c2dd024ebad44ca67129cc1e2892e4861df466764749d5ef8642", size = 156250, upload-time = "2026-10-22T23:43:36.263Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/6d/78dc67a9e779e594b49bf62604034d3a6aa428a55afc729cafda4b7333e1/googleapis_common_protos-1.76.0-py3-none-any.whl", hash = "sha256:59e13344a9f3651aa201a03e2bee815a3bf43a4baf1f9ff8a9b62a840ce25fac", size = 307707, upload-time = "2026-10-22T23:43:10.445Z" }, +] + [[package]] name = "gradio" version = "6.31.0" @@ -1704,6 +1798,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5e/7e/7ffaae13415e8f51c8e8d5d1845f2de7a27ebf2717e97a38d7e7446d6030/joserfc-1.8.0-py3-none-any.whl", hash = "sha256:176b836ac7ed9a46a88629e24076314b475f33a75d0bad7f26146e572eed7c79", size = 73147, upload-time = "2026-11-03T10:45:56.531Z" }, ] +[[package]] +name = "json-rpc" +version = "1.15.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854, upload-time = "2023-06-11T09:45:49.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450, upload-time = "2023-06-11T09:45:47.136Z" }, +] + [[package]] name = "jsonpatch" version = "1.38" @@ -2635,6 +2738,14 @@ dependencies = [ ] [package.optional-dependencies] +a2a = [ + { name = "a2a-sdk", extra = ["http-server"] }, + { name = "anyio" }, + { name = "cryptography" }, + { name = "jsonschema" }, + { name = "mcp" }, + { name = "uvicorn" }, +] agent = [ { name = "anyio" }, { name = "cryptography" }, @@ -2819,6 +2930,7 @@ windows = [ [package.metadata] requires-dist = [ + { name = "a2a-sdk", extras = ["http-server"], marker = "extra == 'a2a'", specifier = ">=1.3.1,<2" }, { name = "aardwolf", marker = "extra == 'rdp'", specifier = "==0.2.14" }, { name = "anthropic", marker = "extra == 'dev'", specifier = ">=0.40" }, { name = "anthropic", marker = "extra == 'grounder'", specifier = ">=0.40" }, @@ -2858,6 +2970,7 @@ requires-dist = [ { name = "numpy", marker = "extra == 'vision'", specifier = ">=1.26" }, { name = "onnxruntime", marker = "extra == 'local-grounding'", specifier = ">=1.17" }, { name = "openadapt-capture", marker = "extra == 'capture'", specifier = ">=1.2.0" }, + { name = "openadapt-flow", extras = ["agent"], marker = "extra == 'a2a'" }, { name = "openadapt-flow", extras = ["vision"], marker = "extra == 'browser'" }, { name = "openadapt-flow", extras = ["vision"], marker = "extra == 'capture'" }, { name = "openadapt-flow", extras = ["vision"], marker = "extra == 'linux'" }, @@ -2906,6 +3019,7 @@ requires-dist = [ { name = "transformers", marker = "extra == 'service-mlx'", specifier = ">=5.14,<5.18" }, { name = "uiautomation", marker = "sys_platform == 'win32' and extra == 'dev'", specifier = ">=2.0.20" }, { name = "uvicorn", marker = "python_full_version >= '3.11' and extra == 'openenv'", specifier = ">=0.29" }, + { name = "uvicorn", marker = "extra == 'a2a'", specifier = ">=0.29" }, { name = "uvicorn", marker = "extra == 'console'", specifier = ">=0.29" }, { name = "uvicorn", marker = "extra == 'dev'", specifier = ">=0.29" }, { name = "uvicorn", marker = "extra == 'execute'", specifier = ">=0.29" }, @@ -2920,7 +3034,7 @@ requires-dist = [ { name = "winrt-windows-media-ocr", marker = "sys_platform == 'win32' and extra == 'native-ocr'", specifier = ">=2.0" }, { name = "winrt-windows-storage-streams", marker = "sys_platform == 'win32' and extra == 'native-ocr'", specifier = ">=2.0" }, ] -provides-extras = ["vision", "native-ocr", "browser", "dev", "grounder", "grounding", "local-grounding", "console", "countersign", "receipts", "keychain", "pkcs11", "execute", "windows", "connector-windows", "reward", "openenv", "macos", "linux", "rdp", "registry", "privacy", "hosted", "service", "service-mlx", "capture", "interop", "agent", "claude-agent-sdk", "openai-agents", "langgraph"] +provides-extras = ["vision", "native-ocr", "browser", "dev", "grounder", "grounding", "local-grounding", "console", "countersign", "receipts", "keychain", "pkcs11", "execute", "windows", "connector-windows", "reward", "openenv", "macos", "linux", "rdp", "registry", "privacy", "hosted", "service", "service-mlx", "capture", "interop", "agent", "a2a", "claude-agent-sdk", "openai-agents", "langgraph"] [[package]] name = "openadapt-grounding" @@ -3440,6 +3554,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ae/87/c1d1a58c71c8b4bd0b138f47ee71ffc988e3f907d419422493bae8ac6d4f/presidio_image_redactor-0.0.59-py3-none-any.whl", hash = "sha256:47a7560566a01a05ad1aa30e99ac55b332e995fa5fcdd78b1ef2e4b93c4568d2", size = 34239, upload-time = "2026-06-28T16:09:12.219Z" }, ] +[[package]] +name = "proto-plus" +version = "1.29.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/46/70/783e33ffbb4466cc154a94f79b869b92a451e2bd45605054e68ff68b7af6/proto_plus-1.29.0.tar.gz", hash = "sha256:cfb4e62ad7e13dd18f346cabbda00cab39930d36a05791fd81ddb074d6ee884f", size = 58592, upload-time = "2026-09-29T19:26:15.963Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/05/a3ef5b1161498e7b5a2a60288a9cf41b9149e94555423a43ec536737ac1a/proto_plus-1.29.0-py3-none-any.whl", hash = "sha256:8acd070469a7aaf43f440b022ef9757c8cac1a9f866e933f59ae98669ddc6c8b", size = 50786, upload-time = "2026-09-29T19:25:50.409Z" }, +] + [[package]] name = "protobuf" version = "7.35.1" @@ -3496,6 +3622,27 @@ memory = [ { name = "cachetools" }, ] +[[package]] +name = "pyasn1" +version = "0.6.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/88/7e/3c0da41061a2021cac7cd524fd57092adbe5b515e8bf9005702e366802e2/pyasn1-0.6.5.tar.gz", hash = "sha256:6b11616a6bcf3a40e635f082bb232fa57b5e0dd7f517bd7ddd69ec3794508a47", size = 155152, upload-time = "2026-10-27T06:32:49.125Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/1f/3eefd5c84c35cae44549ce1c7f7e58f7945b34f5a6bce07a135438522073/pyasn1-0.6.5-py3-none-any.whl", hash = "sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587", size = 84807, upload-time = "2026-10-27T06:32:48.045Z" }, +] + +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a", size = 181259, upload-time = "2025-03-28T02:41:19.028Z" }, +] + [[package]] name = "pycairo" version = "1.29.0" diff --git a/pyproject.toml b/pyproject.toml index a0bd280565..f8d93a128e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,12 @@ keywords = [ "citrix", "emr", "data-entry", + "mcp", + "a2a", + "agent2agent", + "agent-card", + "agent-handoff", + "receipts", ] classifiers = [ "Intended Audience :: Developers", @@ -134,6 +140,14 @@ flow = [ agent = [ "openadapt-agent>=2.1.0,<3; python_version < '3.13'", ] +# Agent-to-agent handoffs over the A2A (Agent2Agent) protocol: +# `openadapt agent serve --a2a`. Handoffs over MCP, HTTP and files need no extra. +# Listed directly, not as openadapt-flow[a2a], so the extra resolves the same +# whichever Flow release is installed; keep in step with Flow's a2a extra. +a2a = [ + "a2a-sdk[http-server]>=1.3.1,<2; python_version < '3.13'", + "uvicorn>=0.29; python_version < '3.13'", +] # Bundles core = [ "openadapt[capture,ml,evals,viewer]", diff --git a/uv.lock b/uv.lock index eeb1ac3c23..b12d87edd5 100644 --- a/uv.lock +++ b/uv.lock @@ -20,6 +20,31 @@ required-markers = [ "python_full_version < '3.11' and sys_platform == 'win32'", ] +[[package]] +name = "a2a-sdk" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "culsans" }, + { name = "google-api-core" }, + { name = "googleapis-common-protos" }, + { name = "httpx" }, + { name = "json-rpc" }, + { name = "packaging" }, + { name = "protobuf" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e6/ca/90d8c95185a53be332772d5b28c42bf1586a2214e8bd937e769f3d566d7c/a2a_sdk-1.3.1.tar.gz", hash = "sha256:f18465fd040d2f75728c8ec915315ff25c072d271e6faeb9fa85a29ac36076ea", size = 456720, upload-time = "2026-11-17T10:51:19.721Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/76/baed78b223d9919a013c625ed853ab220c2c932050d8ded974a4eaaf969b/a2a_sdk-1.3.1-py3-none-any.whl", hash = "sha256:6073b8c04989609d087b9fed18ec1c8a13ae7e56246cf7a23c7c55a1a2a3b813", size = 299006, upload-time = "2026-11-17T10:51:17.787Z" }, +] + +[package.optional-dependencies] +http-server = [ + { name = "sse-starlette" }, + { name = "starlette" }, +] + [[package]] name = "aardwolf" version = "0.2.14" @@ -184,6 +209,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a4/37/cfd1ed540a4d318da025590d96b728e63713c09e9377950fc655dadeb856/aiohttp-3.14.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2e1161602f45a54de2ce0905243a95f58cb42dcd378402f3697f5e0b21e9d2e7", size = 469280, upload-time = "2026-07-23T01:57:24.241Z" }, ] +[[package]] +name = "aiologic" +version = "0.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sniffio" }, + { name = "typing-extensions" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/7a/d51f2fde1e8ae8a83431f8e97b7a71e9358cdb1d4d2ce6be387fa44d68de/aiologic-0.17.1.tar.gz", hash = "sha256:2e1b93b9e88ced318c2a63ad7b382688f40cbfe40e3d42258d49dc9c5aea179d", size = 252354, upload-time = "2026-06-27T20:41:33.25Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/d3/2d310b1b839014034dba0cba685e492df8a5c7ad32c19cab7e979eed6554/aiologic-0.17.1-py3-none-any.whl", hash = "sha256:c66b319830fedb7ca3d2b2125fa6f5b653f89418c2a27ea76f259ec5f00943c0", size = 161331, upload-time = "2026-06-27T20:41:31.877Z" }, +] + [[package]] name = "aiosignal" version = "1.4.0" @@ -1144,6 +1183,19 @@ nvtx = [ { name = "nvidia-nvtx", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, ] +[[package]] +name = "culsans" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiologic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/e3/49afa1bc180e0d28008ec6bcdf82a4072d1c7a41032b5b759b60814ca4b0/culsans-0.11.0.tar.gz", hash = "sha256:0b43d0d05dce6106293d114c86e3fb4bfc63088cfe8ff08ed3fe36891447fe33", size = 107546, upload-time = "2025-12-31T23:15:38.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/5d/9fb19fb38f6d6120422064279ea5532e22b84aa2be8831d49607194feda3/culsans-0.11.0-py3-none-any.whl", hash = "sha256:278d118f63fc75b9db11b664b436a1b83cc30d9577127848ba41420e66eb5a47", size = 21811, upload-time = "2025-12-31T23:15:37.189Z" }, +] + [[package]] name = "cycler" version = "0.12.1" @@ -2136,6 +2188,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/8a/a342b2f0251f3dac4ca17618265d93bf244a2a4d089126e81e4c1056ac50/jiter-0.13.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7bb00b6d26db67a05fe3e12c76edc75f32077fb51deed13822dc648fa373bc19", size = 343768, upload-time = "2026-02-02T12:37:55.055Z" }, ] +[[package]] +name = "json-rpc" +version = "1.15.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854, upload-time = "2023-06-11T09:45:49.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450, upload-time = "2023-06-11T09:45:47.136Z" }, +] + [[package]] name = "jsonschema" version = "4.26.0" @@ -3241,6 +3302,10 @@ dependencies = [ ] [package.optional-dependencies] +a2a = [ + { name = "a2a-sdk", extra = ["http-server"], marker = "python_full_version < '3.13'" }, + { name = "uvicorn", marker = "python_full_version < '3.13'" }, +] agent = [ { name = "openadapt-agent", marker = "python_full_version < '3.13'" }, ] @@ -3311,6 +3376,7 @@ windows = [ [package.metadata] requires-dist = [ + { name = "a2a-sdk", extras = ["http-server"], marker = "python_full_version < '3.13' and extra == 'a2a'", specifier = ">=1.3.1,<2" }, { name = "build", marker = "extra == 'dev'", specifier = ">=1.2.0" }, { name = "click", specifier = ">=8.0.0" }, { name = "openadapt", extras = ["browser", "core", "grounding", "retrieval", "privacy", "flow", "windows", "rdp", "agent"], marker = "extra == 'all'" }, @@ -3337,8 +3403,9 @@ requires-dist = [ { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" }, { name = "rich", marker = "python_full_version < '3.13'", specifier = ">=13.0.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" }, + { name = "uvicorn", marker = "python_full_version < '3.13' and extra == 'a2a'", specifier = ">=0.29" }, ] -provides-extras = ["browser", "capture", "windows", "macos", "linux", "rdp", "ml", "evals", "viewer", "grounding", "retrieval", "privacy", "flow", "agent", "core", "all", "dev"] +provides-extras = ["browser", "capture", "windows", "macos", "linux", "rdp", "ml", "evals", "viewer", "grounding", "retrieval", "privacy", "flow", "agent", "a2a", "core", "all", "dev"] [[package]] name = "openadapt-agent" From 6be24781f8658168214d95507bc8ce97ab9b103c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:17:34 -0500 Subject: [PATCH 03/18] fix(a2a): pass the A2A TCK's transport checks, keep the listener out of the CLI, and record the TCK run JSON-RPC also answers at the interface URL plus '/', input modes are validated (ContentTypeNotSupportedError), and the Agent Card sends Cache-Control. The loopback default moves into a2a_server.py, the one listener, and the no-listener test now pins it there. The TCK report is in packages/flow/benchmark/a2a_tck. --- CAPABILITIES.md | 2 +- llms-full.txt | 47 + packages/agent/README.md | 18 + packages/agent/tests/test_mailbox.py | 5 + .../a2a_tck/2026-11-21/compatibility.json | 1717 +++++++++++++++++ .../benchmark/a2a_tck/2026-11-21/tck-run.log | 143 ++ packages/flow/benchmark/a2a_tck/README.md | 58 + packages/flow/docs/A2A.md | 5 + .../flow/openadapt_flow/agent/a2a_server.py | 12 +- packages/flow/openadapt_flow/agent/cli.py | 9 +- 10 files changed, 2010 insertions(+), 6 deletions(-) create mode 100644 packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json create mode 100644 packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log create mode 100644 packages/flow/benchmark/a2a_tck/README.md diff --git a/CAPABILITIES.md b/CAPABILITIES.md index cab5069740..462414a4a0 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -314,7 +314,7 @@ improvising or retrying when something is off. | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | | Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main (#PR_NUMBER) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main (#PR_NUMBER) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; TCK_RESULT | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main (#PR_NUMBER) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | diff --git a/llms-full.txt b/llms-full.txt index 856523850d..8562adbca5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -181,6 +181,25 @@ and `openadapt verify effect` judges a write made by any agent or script against the system of record. [Connect an agent](https://docs.openadapt.ai/how-to/connect-an-agent/) covers other clients. +### Hand results from agent to agent + +When one agent hands a result to another, the run's signed receipt goes with +it, and the receiving agent verifies it against keys it pins: + +```bash +openadapt handoff send result.json --run RUN_DIR --out result.handoff.json +openadapt handoff verify result.handoff.json --keys trusted-keys.json +``` + +The verdict says who signed, which checks passed and which were not checked, +and any change confirmed in the other party's own system. A valid signature +proves who signed, not that the claim is true. Handoffs travel over MCP +(`serve --handoffs`), HTTP and webhooks (`--post URL`), files and email +(`--detached`), and the A2A (Agent2Agent) protocol (`openadapt agent serve +--a2a`, with an Agent Card, after `pip install 'openadapt[a2a]'`). +[HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) +has the details. + ### Record a task by hand Recording works the same way on every surface; only the target differs: @@ -327,6 +346,7 @@ the right record is on screen, makes the entry, and reads the record back. - **Binds each approval to exactly what will be saved**, with one-tap answers on a paired phone. - **Repairs itself when the app changes**, probing a fix up to the save and asking a person to approve it (qualified on browser runs and end to end on native macOS). - **Works as a safety layer under any agent**: MCP tools, a guarded save, Agent Skills and a CLI. +- **Hands results from agent to agent with their receipts**, over MCP, HTTP, files and the A2A protocol, and verifies a handoff on arrival. - **Runs locally**: no calls to a hosted AI model on healthy runs, personal and health data redacted, signed receipts. [CAPABILITIES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/CAPABILITIES.md) has the evidence and code for each. @@ -747,6 +767,8 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main (#PR_NUMBER) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main (#PR_NUMBER) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | @@ -877,6 +899,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. +- `handoff`: Hand a result to another agent with its run's receipt attached (inline, detached beside a file, or POSTed to a webhook), and verify one on arrival against your pinned keys: who signed, what was checked, and that a valid signature proves who signed, not that the claim is true. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** @@ -2382,6 +2405,30 @@ automation into an independently certified transaction system. ### Features +- Agent-to-agent handoffs. `openadapt-flow handoff send` attaches a run's + `record/run/v1` receipt to what one agent hands another: inline, detached + beside a file (`FILE.handoff.json`), or POSTed to a webhook. + `openadapt-flow handoff verify` checks one against the receiver's pinned + keys and returns a verdict (`openadapt.handoff-verdict/v1`). The verdict + gives the signer role, integrity, the checks passed and not checked, and + counterparty confirmation lines. It always says that a valid signature + proves who signed, not that the claim is true, and it marks the payload + unbound unless it is a signed subject. The private openings file never + travels (docs/HANDOFFS.md, docs/HANDOFF_RECEIPTS.md). +- `openadapt-agent serve --handoffs` adds the MCP tools `get_handoff` and + `verify_handoff`. `serve --a2a` serves the same workflows over the A2A + (Agent2Agent) protocol 1.0 with the official `a2a-sdk` (new `a2a` extra): + - an Agent Card at `/.well-known/agent-card.json`; + - JSON-RPC and HTTP+JSON bindings; + - one skill per workflow plus `verify_handoff`; + - the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. + + It listens on 127.0.0.1 by default, needs a bearer token on any other + address, and refuses browser `Origin` and unknown `Host` headers. Every A2A + call goes through the MCP server's gate (`agent/contract_call.py`). Person + confirmations are not served, and only `done` is `TASK_STATE_COMPLETED` + (docs/A2A.md). + - Dropdowns, searchable selects, type-aheads and native selects are recorded, compiled and run as one model, a choice (`OptionChoice` on a `SELECT_OPTION` step, docs/CHOICES.md). A click on an option of a list the diff --git a/packages/agent/README.md b/packages/agent/README.md index 0830988dad..5039c8bfbf 100644 --- a/packages/agent/README.md +++ b/packages/agent/README.md @@ -503,6 +503,24 @@ python packages/agent/tests/ledger_demo.py Results: [docs/task-ledger-measurement.json](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/docs/task-ledger-measurement.json). +## Hand results to other agents + +`serve --handoffs` adds two tools: + +- `get_handoff` returns a finished run's result with its signed receipt + attached. +- `verify_handoff` checks a handoff another agent sent, against the keys this + computer pins. + +`serve --a2a` serves the same workflows over the A2A (Agent2Agent) protocol +instead of MCP stdio. It needs `pip install 'openadapt-agent[a2a]'` and +publishes an Agent Card at `/.well-known/agent-card.json`. It listens on +127.0.0.1, and any other address needs `--a2a-token-file`. + +A valid signature proves who signed, not that the claim is true. The +receiving agent confirms the claim in its own record. See +[HANDOFFS.md](../flow/docs/HANDOFFS.md) and [A2A.md](../flow/docs/A2A.md). + ## Security - The server talks only over stdio and has no sign-in. Anything that can write to its input acts as the OS account that started it, so don't expose it over a network or a tunnel. diff --git a/packages/agent/tests/test_mailbox.py b/packages/agent/tests/test_mailbox.py index b8aef71dd1..40786bc579 100644 --- a/packages/agent/tests/test_mailbox.py +++ b/packages/agent/tests/test_mailbox.py @@ -505,6 +505,11 @@ def test_mailbox_sources_have_no_listener_or_win_agent() -> None: bind_src = (root / "runner_bind.py").read_text(encoding="utf-8") assert "wait_seconds" not in bind_src assert "def claim" not in bind_src + # The one listener is the opt-in A2A adapter (`serve --a2a`), in its own + # module, bound to loopback unless the operator names an address. + a2a_src = (root / "a2a_server.py").read_text(encoding="utf-8") + assert 'DEFAULT_HOST = "127.0.0.1"' in a2a_src + assert "needs --a2a-token-file" in a2a_src mailbox_src = (root / "mailbox.py").read_text(encoding="utf-8") assert 'method="POST"' in mailbox_src assert 'method="GET"' not in mailbox_src diff --git a/packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json b/packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json new file mode 100644 index 0000000000..e2d9fe28af --- /dev/null +++ b/packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json @@ -0,0 +1,1717 @@ +{ + "summary": { + "score_scope": "automated", + "manual_verification_required": [ + "CARD-CLIENT-001", + "CARD-SIGN-001", + "CARD-SIGN-002", + "CARD-SIGN-003", + "CARD-SIGN-004", + "AUTH-TLS-001", + "AUTH-TLS-002", + "AUTH-SERVER-001", + "BIND-CUSTOM-002" + ], + "timestamp": "2026-11-21T06:11:41.629424+00:00", + "sut_url": "http://localhost:9999", + "spec_version": "", + "overall_compatibility": "75.0%", + "must_compatibility": "76.0%", + "should_compatibility": "57.1%", + "may_compatibility": "100.0%" + }, + "per_requirement": { + "CARD-DISC-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "agent_card": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card.py::TestAgentCardDiscovery::test_agent_card_retrievable" + ] + }, + "CARD-STRUCT-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "agent_card": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card.py::TestAgentCardStructure::test_agent_card_validates_against_schema", + "tests/compatibility/agent_card/test_agent_card.py::TestAgentCardStructure::test_required_fields_present" + ] + }, + "CARD-PROTO-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "agent_card": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card.py::TestAgentCardProtocol::test_supported_interfaces_non_empty" + ] + }, + "CARD-PROTO-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "agent_card": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card.py::TestAgentCardProtocol::test_each_interface_validates_against_schema" + ] + }, + "BIND-FIELD-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "agent_card": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card.py::TestBindingFieldDeclaration::test_all_protocols_declared" + ] + }, + "BIND-CUSTOM-001": { + "level": "SHOULD", + "status": "SKIPPED", + "transports": { + "agent_card": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card.py::TestCustomBindingIdentifiers::test_custom_binding_identifiers_are_uris" + ] + }, + "CARD-CACHE-001": { + "level": "SHOULD", + "status": "PASS", + "transports": { + "agent_card": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card_caching.py::TestAgentCardCacheControl::test_cache_control_has_max_age", + "tests/compatibility/agent_card/test_agent_card_caching.py::TestAgentCardCacheControl::test_cache_control_present" + ] + }, + "CARD-CACHE-002": { + "level": "SHOULD", + "status": "PASS", + "transports": { + "agent_card": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card_caching.py::TestAgentCardETag::test_etag_present" + ] + }, + "CARD-CACHE-003": { + "level": "MAY", + "status": "SKIPPED", + "transports": { + "agent_card": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/agent_card/test_agent_card_caching.py::TestAgentCardLastModified::test_last_modified_present" + ] + }, + "DM-ART-001": { + "level": "MUST", + "status": "FAIL", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "FAIL", + "http_json": "FAIL" + }, + "errors": [ + "Response contains no artifacts", + "Response contains no artifacts", + "Response contains no artifacts", + "Response contains no artifacts", + "Response contains no artifacts", + "Response contains no artifacts", + "Response contains no artifacts", + "Response contains no artifacts" + ], + "test_ids": [ + "tests/compatibility/core_operations/test_artifacts.py::TestDataArtifact::test_task_has_data_artifact[grpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestDataArtifact::test_task_has_data_artifact[http_json]", + "tests/compatibility/core_operations/test_artifacts.py::TestDataArtifact::test_task_has_data_artifact[jsonrpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestFileArtifact::test_task_has_file_artifact[grpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestFileArtifact::test_task_has_file_artifact[http_json]", + "tests/compatibility/core_operations/test_artifacts.py::TestFileArtifact::test_task_has_file_artifact[jsonrpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestFileUrlArtifact::test_task_has_file_url_artifact[grpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestFileUrlArtifact::test_task_has_file_url_artifact[http_json]", + "tests/compatibility/core_operations/test_artifacts.py::TestFileUrlArtifact::test_task_has_file_url_artifact[jsonrpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestTextArtifact::test_task_has_text_artifact[grpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestTextArtifact::test_task_has_text_artifact[http_json]", + "tests/compatibility/core_operations/test_artifacts.py::TestTextArtifact::test_task_has_text_artifact[jsonrpc]", + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-MSG-001": { + "level": "MUST", + "status": "FAIL", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "FAIL", + "http_json": "FAIL" + }, + "errors": [ + "Expected a Message response, but got a Task or no payload", + "Expected a Message response, but got a Task or no payload" + ], + "test_ids": [ + "tests/compatibility/core_operations/test_artifacts.py::TestMessageResponse::test_returns_message_with_text_part[grpc]", + "tests/compatibility/core_operations/test_artifacts.py::TestMessageResponse::test_returns_message_with_text_part[http_json]", + "tests/compatibility/core_operations/test_artifacts.py::TestMessageResponse::test_returns_message_with_text_part[jsonrpc]", + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-TASK-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-TASK-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-MSG-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-PART-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-STATUS-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-SERIAL-004": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestSendMessageResponseSchema::test_response_validates_against_schema" + ] + }, + "DM-SERIAL-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestCamelCaseFieldNames::test_no_snake_case_keys" + ] + }, + "DM-SERIAL-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestEnumSerialization::test_enum_values_are_strings" + ] + }, + "DM-SERIAL-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestTimestampFormat::test_timestamps_are_iso8601_utc" + ] + }, + "DM-SERIAL-005": { + "level": "SHOULD", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_data_model.py::TestIgnoreUnrecognizedFields::test_extra_fields_ignored_jsonrpc", + "tests/compatibility/core_operations/test_data_model.py::TestIgnoreUnrecognizedFields::test_extra_fields_ignored_rest" + ] + }, + "CORE-ERR-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestCoreErrorStructure::test_error_has_code_and_message_jsonrpc", + "tests/compatibility/core_operations/test_error_handling.py::TestCoreErrorStructure::test_error_has_code_and_message_rest" + ] + }, + "CORE-ERR-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestCoreInputValidation::test_malformed_request_rejected_jsonrpc", + "tests/compatibility/core_operations/test_error_handling.py::TestCoreInputValidation::test_malformed_request_rejected_rest" + ] + }, + "CORE-CAP-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestCapabilityPushNotifications::test_push_not_supported_jsonrpc", + "tests/compatibility/core_operations/test_error_handling.py::TestCapabilityPushNotifications::test_push_not_supported_rest" + ] + }, + "CORE-CAP-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "jsonrpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestCapabilityStreaming::test_streaming_not_supported_jsonrpc" + ] + }, + "CORE-CAP-004": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestCapabilityExtensionRequired::test_missing_required_extension_returns_error_http_json", + "tests/compatibility/core_operations/test_error_handling.py::TestCapabilityExtensionRequired::test_missing_required_extension_returns_error_jsonrpc" + ] + }, + "CORE-CAP-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestCapabilityExtendedCard::test_extended_card_not_supported_jsonrpc" + ] + }, + "CARD-EXT-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED", + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestExtendedCardNotConfigured::test_extended_card_not_configured_grpc", + "tests/compatibility/core_operations/test_error_handling.py::TestExtendedCardNotConfigured::test_extended_card_not_configured_http_json", + "tests/compatibility/core_operations/test_error_handling.py::TestExtendedCardNotConfigured::test_extended_card_not_configured_jsonrpc" + ] + }, + "CARD-EXT-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED", + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestExtendedCardRequiresAuth::test_extended_card_requires_auth_grpc", + "tests/compatibility/core_operations/test_error_handling.py::TestExtendedCardRequiresAuth::test_extended_card_requires_auth_http_json", + "tests/compatibility/core_operations/test_error_handling.py::TestExtendedCardRequiresAuth::test_extended_card_requires_auth_jsonrpc" + ] + }, + "VER-SERVER-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestVersionErrors::test_unsupported_version_returns_error_jsonrpc", + "tests/compatibility/core_operations/test_error_handling.py::TestVersionErrors::test_unsupported_version_returns_error_rest" + ] + }, + "VER-SERVER-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestVersionErrors::test_empty_version_treated_as_default_jsonrpc" + ] + }, + "JSONRPC-ERR-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestJsonRpcErrorStructure::test_error_object_structure", + "tests/compatibility/jsonrpc/test_error_info.py::TestJsonRpcErrorDetails::test_present_error_data_is_any_array" + ] + }, + "JSONRPC-ERR-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestJsonRpcErrorStructure::test_a2a_error_codes_in_range" + ] + }, + "JSONRPC-SSE-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestJsonRpcErrorStructure::test_a2a_error_type_mappings", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeMappings::test_push_notification_not_supported_error", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeMappings::test_task_not_cancelable_error", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeMappings::test_task_not_found_error", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeMappings::test_unsupported_operation_error", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeMappings::test_version_not_supported_error", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeRange::test_error_code_in_valid_range[CancelTask-nonexistent]", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeRange::test_error_code_in_valid_range[GetTask-nonexistent]", + "tests/compatibility/jsonrpc/test_error_codes.py::TestJsonRpcErrorCodeRange::test_error_code_in_valid_range[SendMessage-bad-version]" + ] + }, + "JSONRPC-ERR-003": { + "level": "SHOULD", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestJsonRpcErrorStructure::test_error_data_contains_error_info", + "tests/compatibility/jsonrpc/test_error_info.py::TestJsonRpcWellKnownErrorDetails::test_error_data_uses_well_known_type" + ] + }, + "HTTP_JSON-ERR-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestRestErrorStructure::test_error_uses_aip193_format", + "tests/compatibility/http_json/test_problem_details.py::TestAIP193ErrorFormat::test_code_field_matches_http_status", + "tests/compatibility/http_json/test_problem_details.py::TestAIP193ErrorFormat::test_error_object_present" + ] + }, + "HTTP_JSON-ERR-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestRestErrorStructure::test_a2a_error_info_in_details", + "tests/compatibility/http_json/test_problem_details.py::TestAIP193ErrorInfo::test_details_contains_error_info", + "tests/compatibility/http_json/test_problem_details.py::TestAIP193ErrorInfo::test_error_info_reason_matches_condition", + "tests/compatibility/http_json/test_problem_details.py::TestAIP193ErrorInfo::test_error_info_valid" + ] + }, + "GRPC-ERR-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_error_handling.py::TestGrpcErrorStructure::test_grpc_error_for_nonexistent_task", + "tests/compatibility/grpc/test_status_codes.py::TestGrpcErrorInfo::test_error_info_in_status_details" + ] + }, + "STREAM-ORDER-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_multi_stream.py::TestMultiStreamOrdering::test_events_broadcast_to_all_streams[grpc]" + ] + }, + "STREAM-ORDER-003": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_multi_stream.py::TestMultiStreamOrdering::test_streams_receive_same_events_in_order[grpc]" + ] + }, + "STREAM-ORDER-004": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_multi_stream.py::TestMultiStreamOrdering::test_closing_one_stream_does_not_affect_others[grpc]" + ] + }, + "PUSH-CREATE-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_create_push_config[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_create_push_config[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_create_push_config[jsonrpc]" + ] + }, + "PUSH-CREATE-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_config_persists[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_config_persists[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_config_persists[jsonrpc]" + ] + }, + "PUSH-GET-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_get_push_config[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_get_push_config[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_get_push_config[jsonrpc]" + ] + }, + "PUSH-GET-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_get_nonexistent_config_returns_error[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_get_nonexistent_config_returns_error[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_get_nonexistent_config_returns_error[jsonrpc]" + ] + }, + "PUSH-LIST-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_list_push_configs[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_list_push_configs[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_list_push_configs[jsonrpc]" + ] + }, + "PUSH-DEL-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_delete_push_config[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_delete_push_config[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_delete_push_config[jsonrpc]" + ] + }, + "PUSH-DEL-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_delete_is_idempotent[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_delete_is_idempotent[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationCrud::test_delete_is_idempotent[jsonrpc]" + ] + }, + "PUSH-DELIVER-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_includes_auth[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_includes_auth[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_includes_auth[jsonrpc]" + ] + }, + "PUSH-DELIVER-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_at_least_once[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_at_least_once[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_at_least_once[jsonrpc]" + ] + }, + "PUSH-DELIVER-003": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "SKIPPED", + "http_json": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_payload_format[grpc]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_payload_format[http_json]", + "tests/compatibility/core_operations/test_push_notifications.py::TestPushNotificationDelivery::test_delivery_payload_format[jsonrpc]" + ] + }, + "CORE-SEND-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-SEND-001-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-SEND-001-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-SEND-001-jsonrpc]" + ] + }, + "CORE-SEND-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-SEND-003-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-SEND-003-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-SEND-003-jsonrpc]" + ] + }, + "CORE-STREAM-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-001-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-001-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-001-jsonrpc]" + ] + }, + "CORE-STREAM-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-002-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-002-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-002-jsonrpc]" + ] + }, + "CORE-STREAM-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-003-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-003-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-STREAM-003-jsonrpc]" + ] + }, + "CORE-GET-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-GET-002-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-GET-002-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-GET-002-jsonrpc]" + ] + }, + "CORE-LIST-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-001-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-001-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-001-jsonrpc]" + ] + }, + "CORE-LIST-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-002-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-002-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-002-jsonrpc]" + ] + }, + "CORE-LIST-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-003-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-003-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-003-jsonrpc]" + ] + }, + "CORE-LIST-004": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-004-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-004-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-004-jsonrpc]" + ] + }, + "CORE-LIST-005": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-005-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-005-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-LIST-005-jsonrpc]" + ] + }, + "CORE-CANCEL-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-CANCEL-003-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-CANCEL-003-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-CANCEL-003-jsonrpc]" + ] + }, + "CORE-EXECUTION-MODE-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-EXECUTION-MODE-001-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-EXECUTION-MODE-001-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-EXECUTION-MODE-001-jsonrpc]" + ] + }, + "CORE-EXECUTION-MODE-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-EXECUTION-MODE-002-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-EXECUTION-MODE-002-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-EXECUTION-MODE-002-jsonrpc]" + ] + }, + "CORE-MULTI-001a": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-001a-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-001a-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-001a-jsonrpc]" + ] + }, + "CORE-MULTI-002a": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-002a-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-002a-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-002a-jsonrpc]" + ] + }, + "CORE-MULTI-003": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-003-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-003-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-003-jsonrpc]" + ] + }, + "CORE-MULTI-004": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-004-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-004-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[CORE-MULTI-004-jsonrpc]" + ] + }, + "STREAM-SUB-004": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[STREAM-SUB-004-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[STREAM-SUB-004-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_must_requirement[STREAM-SUB-004-jsonrpc]", + "tests/compatibility/grpc/test_streaming.py::TestGrpcStreaming::test_streaming_error_propagation", + "tests/compatibility/jsonrpc/test_sse_streaming.py::TestSseSubscribeToTask::test_subscribe_nonexistent_task_returns_error" + ] + }, + "CORE-MULTI-001": { + "level": "MAY", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_may_requirement[CORE-MULTI-001-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_may_requirement[CORE-MULTI-001-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_may_requirement[CORE-MULTI-001-jsonrpc]" + ] + }, + "CORE-MULTI-002": { + "level": "MAY", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_requirements.py::test_may_requirement[CORE-MULTI-002-grpc]", + "tests/compatibility/core_operations/test_requirements.py::test_may_requirement[CORE-MULTI-002-http_json]", + "tests/compatibility/core_operations/test_requirements.py::test_may_requirement[CORE-MULTI-002-jsonrpc]" + ] + }, + "STREAM-ORDER-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "grpc": "SKIPPED", + "jsonrpc": "PASS", + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_stream_ordering.py::TestStreamEventOrdering::test_streaming_event_ordering[grpc]", + "tests/compatibility/core_operations/test_stream_ordering.py::TestStreamEventOrdering::test_streaming_event_ordering[http_json]", + "tests/compatibility/core_operations/test_stream_ordering.py::TestStreamEventOrdering::test_streaming_event_ordering[jsonrpc]" + ] + }, + "CORE-HIST-001": { + "level": "SHOULD", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_history.py::TestHistoryLengthZeroGetTask::test_get_task_history_length_zero[grpc]" + ] + }, + "CORE-HIST-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_history.py::TestHistoryLengthLimit::test_get_task_history_does_not_exceed_limit[grpc]" + ] + }, + "CORE-HIST-003": { + "level": "SHOULD", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_history.py::TestHistoryLengthZeroSendMessage::test_send_message_history_length_zero[grpc]" + ] + }, + "CORE-HIST-004": { + "level": "MAY", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_history.py::TestHistoryPersistence::test_get_task_returns_history[grpc]" + ] + }, + "CORE-HIST-005": { + "level": "SHOULD", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_history.py::TestHistoryOrdering::test_history_messages_in_chronological_order[grpc]" + ] + }, + "CORE-HIST-006": { + "level": "SHOULD", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_history.py::TestHistoryContent::test_history_content_matches_sent_messages[grpc]" + ] + }, + "CORE-GET-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestGetTask::test_get_task_returns_current_state[grpc]" + ] + }, + "CORE-CANCEL-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestCancelTask::test_cancel_task_returns_updated_state[grpc]" + ] + }, + "CORE-CANCEL-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestCancelTask::test_cancel_terminal_task_returns_error[grpc]" + ] + }, + "CORE-SEND-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestMultiTurn::test_send_message_to_terminal_task[grpc]" + ] + }, + "CORE-MULTI-005": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestMultiTurn::test_infer_context_from_task[grpc]" + ] + }, + "CORE-MULTI-006": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestMultiTurn::test_reject_mismatching_context[grpc]" + ] + }, + "STREAM-SUB-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestSubscribeLifecycle::test_subscribe_terminates_at_terminal_state[grpc]" + ] + }, + "STREAM-SUB-003": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_task_lifecycle.py::TestSubscribeLifecycle::test_subscribe_rejects_terminal_task[grpc]" + ] + }, + "JSONRPC-FMT-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestJsonRpcFormat::test_response_validates_jsonrpc_envelope" + ] + }, + "JSONRPC-FMT-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestJsonRpcFormat::test_content_type_is_application_json" + ] + }, + "JSONRPC-SVC-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestJsonRpcMethodNames::test_bindings_use_spec_method_names" + ] + }, + "JSONRPC-SVC-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestJsonRpcServiceParams::test_extensions_header_accepted" + ] + }, + "JSONRPC-SSE-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "jsonrpc": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestJsonRpcStreaming::test_streaming_content_type", + "tests/compatibility/jsonrpc/test_sse_streaming.py::TestSseStreamingFormat::test_streaming_events_contain_stream_response", + "tests/compatibility/jsonrpc/test_sse_streaming.py::TestSseStreamingFormat::test_streaming_events_have_jsonrpc_envelope" + ] + }, + "HTTP_JSON-SVC-001": { + "level": "SHOULD", + "status": "FAIL", + "transports": { + "http_json": "FAIL" + }, + "errors": [ + "Error Content-Type should be application/a2a+json for 1.0.1" + ], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestRestFormat::test_response_content_type", + "tests/compatibility/http_json/test_problem_details.py::TestHttpJsonErrorMediaType::test_error_content_type" + ] + }, + "HTTP_JSON-FMT-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestRestFormat::test_response_validates_against_schema" + ] + }, + "HTTP_JSON-SVC-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestRestServiceParams::test_extensions_header_accepted" + ] + }, + "HTTP_JSON-URL-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestRestUrlPatterns::test_url_patterns_defined" + ] + }, + "HTTP_JSON-URL-002": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestRestUrlPatterns::test_http_methods_correct" + ] + }, + "HTTP_JSON-QP-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestRestQueryParams::test_query_params_are_camel_case" + ] + }, + "HTTP_JSON-SSE-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestRestStreaming::test_streaming_content_type" + ] + }, + "GRPC-SVC-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestGrpcService::test_grpc_response_validates_against_proto" + ] + }, + "GRPC-SVC-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestGrpcProto3::test_response_uses_proto3" + ] + }, + "GRPC-META-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestGrpcServiceParams::test_extensions_metadata_accepted" + ] + }, + "GRPC-ERR-003": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/core_operations/test_transport_behavior.py::TestGrpcStreaming::test_grpc_streaming_works", + "tests/compatibility/grpc/test_streaming.py::TestGrpcStreaming::test_streaming_cancellation", + "tests/compatibility/grpc/test_streaming.py::TestGrpcStreaming::test_streaming_message_structure", + "tests/compatibility/grpc/test_streaming.py::TestGrpcStreaming::test_streaming_response_type" + ] + }, + "GRPC-ERR-002": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/grpc/test_status_codes.py::TestGrpcStatusCodes::test_cancel_missing_task_returns_not_found", + "tests/compatibility/grpc/test_status_codes.py::TestGrpcStatusCodes::test_push_not_supported_returns_expected_error", + "tests/compatibility/grpc/test_status_codes.py::TestGrpcStatusCodes::test_task_not_found_returns_not_found", + "tests/compatibility/grpc/test_status_codes.py::TestGrpcStatusCodes::test_unsupported_operation_returns_expected_error", + "tests/compatibility/grpc/test_status_codes.py::TestGrpcStatusCodes::test_version_not_supported_returns_expected_error" + ] + }, + "STREAM-SUB-001": { + "level": "MUST", + "status": "SKIPPED", + "transports": { + "grpc": "SKIPPED" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/grpc/test_streaming.py::TestGrpcStreaming::test_subscribe_first_event_is_task" + ] + }, + "HTTP_JSON-STATUS-001": { + "level": "MUST", + "status": "PASS", + "transports": { + "http_json": "PASS" + }, + "errors": [], + "test_ids": [ + "tests/compatibility/http_json/test_http_status.py::TestHttpJsonStatusCodes::test_cancel_missing_task_returns_404", + "tests/compatibility/http_json/test_http_status.py::TestHttpJsonStatusCodes::test_content_type_not_supported_returns_expected_error", + "tests/compatibility/http_json/test_http_status.py::TestHttpJsonStatusCodes::test_push_not_supported_returns_400", + "tests/compatibility/http_json/test_http_status.py::TestHttpJsonStatusCodes::test_success_returns_2xx", + "tests/compatibility/http_json/test_http_status.py::TestHttpJsonStatusCodes::test_task_not_found_returns_404", + "tests/compatibility/http_json/test_http_status.py::TestHttpJsonStatusCodes::test_unsupported_operation_returns_400", + "tests/compatibility/http_json/test_http_status.py::TestHttpJsonStatusCodes::test_version_not_supported_returns_400" + ] + }, + "CARD-CLIENT-001": { + "level": "MUST", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "CARD-SIGN-001": { + "level": "MUST", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "CARD-SIGN-002": { + "level": "MUST", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "CARD-SIGN-003": { + "level": "MUST", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "CARD-SIGN-004": { + "level": "MUST", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-TLS-001": { + "level": "MUST", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-TLS-002": { + "level": "SHOULD", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-SERVER-001": { + "level": "SHOULD", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-SERVER-002": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-INTASK-001": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-INTASK-002": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-INTASK-003": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-INTASK-004": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-INTASK-005": { + "level": "SHOULD", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-INTASK-006": { + "level": "SHOULD", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-SCOPE-001": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-SCOPE-002": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "AUTH-SCOPE-003": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "VER-CLIENT-001": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "VER-SERVER-001": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "VER-CLIENT-002": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "BIND-CUSTOM-002": { + "level": "MUST", + "status": "MANUAL", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "BIND-EQUIV-001": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "BIND-EQUIV-002": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "BIND-EQUIV-003": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "BIND-EQUIV-004": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + }, + "GRPC-SVC-003": { + "level": "MUST", + "status": "NOT TESTED", + "transports": {}, + "errors": [], + "test_ids": [] + } + }, + "per_transport": { + "agent_card": { + "total": 11, + "passed": 9, + "failed": 0, + "skipped": 2 + }, + "grpc": { + "total": 72, + "passed": 0, + "failed": 0, + "skipped": 72 + }, + "jsonrpc": { + "total": 81, + "passed": 61, + "failed": 5, + "skipped": 15 + }, + "http_json": { + "total": 78, + "passed": 58, + "failed": 6, + "skipped": 14 + } + }, + "agent_card": { + "name": "OpenAdapt", + "description": "Runs compiled OpenAdapt workflows on this computer and checks that they saved. Every run's result carries its signed receipt, and any agent can send a handoff to be verified.", + "supportedInterfaces": [ + { + "url": "http://127.0.0.1:9999/a2a/jsonrpc", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0" + }, + { + "url": "http://127.0.0.1:9999/a2a/rest", + "protocolBinding": "HTTP+JSON", + "protocolVersion": "1.0" + } + ], + "provider": { + "url": "https://openadapt.ai", + "organization": "OpenAdapt" + }, + "version": "2.2.2", + "documentationUrl": "https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md", + "capabilities": { + "streaming": true, + "pushNotifications": false, + "extensions": [ + { + "uri": "https://openadapt.ai/extensions/handoff-receipt/v1", + "description": "Task results carry the run's record/run/v1 receipt (in-toto Statement in a DSSE envelope) as an openadapt.handoff/v1 artifact part; verify_handoff returns an openadapt.handoff-verdict/v1 verdict.", + "params": { + "handoff_schema": "openadapt.handoff/v1", + "envelope": "dsse", + "media_type": "application/vnd.openadapt.handoff+json", + "verdict_schema": "openadapt.handoff-verdict/v1", + "receipt_predicate": "https://openadapt.ai/record/run/v1" + } + } + ], + "extendedAgentCard": false + }, + "defaultInputModes": [ + "application/json" + ], + "defaultOutputModes": [ + "application/json", + "application/vnd.openadapt.handoff+json" + ], + "skills": [ + { + "id": "add_triage_note", + "name": "add_triage_note", + "description": "Sandbox: add a triage note to the first referral in a synthetic clinic app. Nothing real changes. Done means: The note is in the synthetic app's record store, confirmed by reading the store directly after the save. Send a data part {\"skill\": \"add_triage_note\", \"inputs\": {...}, \"request_id\": \"...\"}. The result includes the run's signed receipt.", + "tags": [ + "openadapt", + "workflow", + "receipt" + ], + "inputModes": [ + "application/json" + ], + "outputModes": [ + "application/json", + "application/vnd.openadapt.handoff+json" + ] + }, + { + "id": "verify_handoff", + "name": "Verify a handoff", + "description": "Send another agent's result with its receipt (an openadapt.handoff/v1 document, as a data part or a application/vnd.openadapt.handoff+json file part). Returns who signed it, whether it is intact, which checks passed and which were not checked, and any confirmation read from the other party's system. A valid signature proves who signed, not that the claim is true.", + "tags": [ + "verification", + "receipt", + "handoff", + "in-toto", + "dsse" + ], + "inputModes": [ + "application/json", + "application/vnd.openadapt.handoff+json" + ], + "outputModes": [ + "application/json" + ] + } + ] + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log b/packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log new file mode 100644 index 0000000000..446fb9bf84 --- /dev/null +++ b/packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log @@ -0,0 +1,143 @@ +SCRATCH/tck-src/a2a-tck/.venv314/lib/python3.14/site-packages/pytest_asyncio/plugin.py:306: PytestDeprecationWarning: The configuration option "asyncio_default_fixture_loop_scope" is unset. +The event loop scope for asynchronous fixtures will default to the fixture scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to "function" scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: "function", "class", "module", "package", "session". Set it to "fixture-scope" to keep the current behavior. + + warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET)) +......s...ssFFsFFsFFsFFsFF............sss.ssssss.........sssssssssssssss [ 27%] +ssssssssssssssssssssssssss..s..s..s..s..s..s..s..s..s..s..s..s..s..s..s. [ 54%] +.s..s..s..ssss..s..s..ssssssssssssssssssssssssssssssssssssssssss........ [ 82%] +....sssssssssssssss..s....F........ss.........s [100%] +═══════════════════════════════════════════════════════ + A2A TCK Compatibility Report +═══════════════════════════════════════════════════════ +SUT: http://localhost:9999 +Timestamp: 2026-11-21T06:11:41.629424+00:00 + +OVERALL COMPATIBILITY: 75.0% (automated checks) + +┌────────┬────────┬────────┬─────────┬────────┬────────────┬───────┐ +│ Level │ Passed │ Failed │ Skipped │ Manual │ Not tested │ Total │ +├────────┼────────┼────────┼─────────┼────────┼────────────┼───────┤ +│ MUST │ 57 │ 2 │ 33 │ 7 │ 16 │ 115 │ +│ SHOULD │ 4 │ 1 │ 5 │ 2 │ 2 │ 14 │ +│ MAY │ 2 │ 0 │ 2 │ 0 │ 0 │ 4 │ +└────────┴────────┴────────┴─────────┴────────┴────────────┴───────┘ + +BY TRANSPORT: + agent_card: 9/11 (2 skipped) ✓ + grpc: 0/72 (72 skipped) ✓ + jsonrpc: 61/81 (15 skipped) ⚠ + http_json: 58/78 (14 skipped) ⚠ + +FAILED REQUIREMENTS: + ✗ DM-ART-001 (jsonrpc, http_json): Response contains no artifacts + ✗ DM-MSG-001 (jsonrpc, http_json): Expected a Message response, but got a Task or no payload + ✗ HTTP_JSON-SVC-001 (http_json): Error Content-Type should be application/a2a+json for 1.0.1 + +PENDING MANUAL VERIFICATION (excluded from automated scores): + CARD-CLIENT-001 [MUST]: Clients MUST set the tenant field in every request to exactly the selected AgentInterface tenant, omitting it when unset. This client behavior requires observing the client's outbound requests; it cannot be established by this server-only conformance probe. + CARD-SIGN-001 [MUST]: Before signing, the Agent Card content MUST be canonicalized using the JSON Canonicalization Scheme (JCS) as defined in RFC 8785. + CARD-SIGN-002 [MUST]: The signatures field itself MUST be excluded from the content being signed to avoid circular dependencies. + CARD-SIGN-003 [MUST]: The JWS protected header MUST include alg (algorithm) and kid (key ID) parameters. + CARD-SIGN-004 [MUST]: Expired or revoked keys MUST NOT be used for signature verification. + AUTH-TLS-001 [MUST]: Production deployments MUST use encrypted communication (HTTPS for HTTP-based bindings, TLS for gRPC). + AUTH-TLS-002 [SHOULD]: Implementations SHOULD use modern TLS configurations (TLS 1.3+ recommended) with strong cipher suites. + AUTH-SERVER-001 [SHOULD]: A2A Clients SHOULD verify the A2A Server's identity by validating its TLS certificate against trusted CAs. + BIND-CUSTOM-002 [MUST]: A breaking change to a custom binding MUST use a new URI. Verifying this requires comparing binding versions and their semantics, which cannot be observed from a single server snapshot. +═══════════════════════════════════════════════════════ + + +=================================== FAILURES =================================== +____________ TestTextArtifact.test_task_has_text_artifact[jsonrpc] _____________ +tests/compatibility/core_operations/test_artifacts.py:107: in test_task_has_text_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on jsonrpc: Response contains no artifacts (see specification/specification.md#417-artifact) +___________ TestTextArtifact.test_task_has_text_artifact[http_json] ____________ +tests/compatibility/core_operations/test_artifacts.py:107: in test_task_has_text_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on http_json: Response contains no artifacts (see specification/specification.md#417-artifact) +____________ TestFileArtifact.test_task_has_file_artifact[jsonrpc] _____________ +tests/compatibility/core_operations/test_artifacts.py:162: in test_task_has_file_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on jsonrpc: Response contains no artifacts (see specification/specification.md#417-artifact) +___________ TestFileArtifact.test_task_has_file_artifact[http_json] ____________ +tests/compatibility/core_operations/test_artifacts.py:162: in test_task_has_file_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on http_json: Response contains no artifacts (see specification/specification.md#417-artifact) +_________ TestFileUrlArtifact.test_task_has_file_url_artifact[jsonrpc] _________ +tests/compatibility/core_operations/test_artifacts.py:216: in test_task_has_file_url_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on jsonrpc: Response contains no artifacts (see specification/specification.md#417-artifact) +________ TestFileUrlArtifact.test_task_has_file_url_artifact[http_json] ________ +tests/compatibility/core_operations/test_artifacts.py:216: in test_task_has_file_url_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on http_json: Response contains no artifacts (see specification/specification.md#417-artifact) +____________ TestDataArtifact.test_task_has_data_artifact[jsonrpc] _____________ +tests/compatibility/core_operations/test_artifacts.py:248: in test_task_has_data_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on jsonrpc: Response contains no artifacts (see specification/specification.md#417-artifact) +___________ TestDataArtifact.test_task_has_data_artifact[http_json] ____________ +tests/compatibility/core_operations/test_artifacts.py:248: in test_task_has_data_artifact + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-ART-001 [Artifact contains required fields] failed on http_json: Response contains no artifacts (see specification/specification.md#417-artifact) +_______ TestMessageResponse.test_returns_message_with_text_part[jsonrpc] _______ +tests/compatibility/core_operations/test_artifacts.py:295: in test_returns_message_with_text_part + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-MSG-001 [Message contains required fields] failed on jsonrpc: Expected a Message response, but got a Task or no payload (see specification/specification.md#414-message) +______ TestMessageResponse.test_returns_message_with_text_part[http_json] ______ +tests/compatibility/core_operations/test_artifacts.py:295: in test_returns_message_with_text_part + assert_and_record(compatibility_collector, req, transport, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: DM-MSG-001 [Message contains required fields] failed on http_json: Expected a Message response, but got a Task or no payload (see specification/specification.md#414-message) +______________ TestHttpJsonErrorMediaType.test_error_content_type ______________ +tests/compatibility/http_json/test_problem_details.py:94: in test_error_content_type + assert_and_record(compatibility_collector, req, TRANSPORT, errors) +tests/compatibility/_test_helpers.py:71: in assert_and_record + assert passed, fail_msg(req, transport, "; ".join(errors)) + ^^^^^^ +E AssertionError: HTTP_JSON-SVC-001 [Content-Type is an accepted JSON media type] failed on http_json: Error Content-Type should be application/a2a+json for 1.0.1 (see specification/specification.md#111-protocol-requirements) +- Generated html report: file://SCRATCH/tck-src/a2a-tck/reports/tck_report.html - +=========================== short test summary info ============================ +FAILED tests/compatibility/core_operations/test_artifacts.py::TestTextArtifact::test_task_has_text_artifact[jsonrpc] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestTextArtifact::test_task_has_text_artifact[http_json] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestFileArtifact::test_task_has_file_artifact[jsonrpc] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestFileArtifact::test_task_has_file_artifact[http_json] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestFileUrlArtifact::test_task_has_file_url_artifact[jsonrpc] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestFileUrlArtifact::test_task_has_file_url_artifact[http_json] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestDataArtifact::test_task_has_data_artifact[jsonrpc] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestDataArtifact::test_task_has_data_artifact[http_json] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestMessageResponse::test_returns_message_with_text_part[jsonrpc] +FAILED tests/compatibility/core_operations/test_artifacts.py::TestMessageResponse::test_returns_message_with_text_part[http_json] +FAILED tests/compatibility/http_json/test_problem_details.py::TestHttpJsonErrorMediaType::test_error_content_type +11 failed, 110 passed, 142 skipped in 1.00s +Command: SCRATCH/tck-src/a2a-tck/.venv314/bin/python -m pytest tests/compatibility/ --sut-host=http://localhost:9999 --tb=short --media-type-spec-version=1.0.1 -q --compatibility-report=reports/compatibility --html=reports/tck_report.html --self-contained-html --junitxml=reports/junitreport.xml + +tck exit 1 diff --git a/packages/flow/benchmark/a2a_tck/README.md b/packages/flow/benchmark/a2a_tck/README.md new file mode 100644 index 0000000000..bc0b908fa0 --- /dev/null +++ b/packages/flow/benchmark/a2a_tck/README.md @@ -0,0 +1,58 @@ +# A2A TCK run against `openadapt-agent serve --a2a` + +This is the official A2A Technology Compatibility Kit +([a2aproject/a2a-tck](https://github.com/a2aproject/a2a-tck), Apache-2.0, +commit `5e6f37c2d38eb3d7684686243c34d365c83df49b`, 2026-11-18). It was run on +2026-11-21 against the sandbox server, started with this command: + +```bash +openadapt-agent serve --a2a --a2a-port 9999 --sandbox-engine simulated +./run_tck.py --sut-host http://localhost:9999 +``` + +- **Python.** The TCK declares Python 3.15. Its `grpcio` wheel crashed on + 3.15.0b3 (exit 139), so it ran on Python 3.14.9 with its own dependencies + installed. +- **Transports.** The card declares only JSON-RPC and HTTP+JSON, so the gRPC + tests were skipped. + +## Result + +These numbers come from `2026-11-21/compatibility.json`: + +| | | +|---|---| +| Automated checks | 110 passed, 11 failed, 142 skipped | +| Agent Card | 9 of 11 passed, 0 failed (2 skipped) | +| MUST | 76.0% | +| SHOULD | 57.1% | +| MAY | 100% | +| Overall | 75.0% | + +**What failed, and why:** + +- **`DM-ART-001` and `DM-MSG-001`** (10 tests). These tests send messages + whose `messageId` starts with a scenario prefix such as `tck-artifact-text`, + and expect the SDK's generated test agent to answer with that exact + artifact or message. OpenAdapt is not that test agent. It answers every + message with its own skills: a workflow run, or `verify_handoff`. The tests + therefore get a failed task with usage text, not the scripted artifact. +- **`HTTP_JSON-SVC-001`** (1 test). HTTP+JSON error responses come from + `a2a-sdk` 1.3.1 with `Content-Type: application/json`. Specification 1.0.1 + expects `application/a2a+json`. That behaviour is in the SDK, not in + OpenAdapt. + +Before two fixes in this pull request, the TCK found two more failures: + +- JSON-RPC posts to the interface URL plus `/`, which now has a route. +- `ContentTypeNotSupportedError` was not returned, which input-mode + validation now handles. + +The Agent Card also now sends `Cache-Control`. + +The TCK also lists checks it can't automate, which it marks for manual +verification. Two of them don't apply to this server: + +- **Agent Card signing.** The card is not signed. +- **TLS.** The server listens on loopback over HTTP. Off loopback it needs a + bearer token, and TLS is the deployment's job. diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md index 6a7d1d5e1f..10c6724724 100644 --- a/packages/flow/docs/A2A.md +++ b/packages/flow/docs/A2A.md @@ -79,3 +79,8 @@ signs the report. The tests cover: - a follow-up message that can't approve a run. The same file covers the MCP tools. + +The official A2A TCK was run against the sandbox server. 110 automated checks +passed and 11 failed. The Agent Card checks passed 9 of 11, with 0 failed and +2 skipped. For what failed and why, see +[benchmark/a2a_tck](../benchmark/a2a_tck/README.md). diff --git a/packages/flow/openadapt_flow/agent/a2a_server.py b/packages/flow/openadapt_flow/agent/a2a_server.py index 7d63e17855..b887093dcd 100644 --- a/packages/flow/openadapt_flow/agent/a2a_server.py +++ b/packages/flow/openadapt_flow/agent/a2a_server.py @@ -41,6 +41,8 @@ _LOG = logging.getLogger(__name__) +#: The A2A listener binds loopback unless the operator names another address. +DEFAULT_HOST = "127.0.0.1" PROTOCOL_VERSION = "1.0" JSONRPC_PATH = "/a2a/jsonrpc" REST_PATH = "/a2a/rest" @@ -75,7 +77,7 @@ def is_loopback(host: str) -> bool: @dataclass class A2AConfig: - host: str = "127.0.0.1" + host: str = DEFAULT_HOST port: int = 8770 #: The URL other agents reach this server at (the Agent Card's interfaces). public_url: Optional[str] = None @@ -538,10 +540,16 @@ def build_app(bridge: AgentBridge, config: A2AConfig) -> Any: task_store=InMemoryTaskStore(), agent_card=card, extended_agent_card=extended, + # Refuse a part whose stated media type no skill takes + # (ContentTypeNotSupportedError), as the spec requires. + validate_input_modes=True, ) routes = [ - *create_agent_card_routes(agent_card=card), + # The card changes only when the server restarts with other bundles. + *create_agent_card_routes(agent_card=card, cache_control="private, max-age=300"), *create_jsonrpc_routes(request_handler=handler, rpc_url=JSONRPC_PATH), + # Clients that join "/" to the interface URL post here. + *create_jsonrpc_routes(request_handler=handler, rpc_url=JSONRPC_PATH + "/"), *create_rest_routes(request_handler=handler, path_prefix=REST_PATH), ] app = Starlette(routes=routes) diff --git a/packages/flow/openadapt_flow/agent/cli.py b/packages/flow/openadapt_flow/agent/cli.py index 94d783c8bc..551258bf0a 100644 --- a/packages/flow/openadapt_flow/agent/cli.py +++ b/packages/flow/openadapt_flow/agent/cli.py @@ -639,8 +639,11 @@ def build_parser() -> argparse.ArgumentParser: ) p.add_argument( "--a2a-host", - default="127.0.0.1", - help="Address to listen on (default 127.0.0.1). Any other needs --a2a-token-file.", + default=None, + help=( + "Address to listen on (default: this computer's loopback address " + "only). Any other needs --a2a-token-file." + ), ) p.add_argument("--a2a-port", type=int, default=8770, help="Port (default 8770)") p.add_argument( @@ -856,7 +859,7 @@ def serve(*bridges: Any, **options: Any) -> None: try: a2a_config = a2a_server.A2AConfig( - host=args.a2a_host, + host=args.a2a_host or a2a_server.DEFAULT_HOST, port=args.a2a_port, public_url=args.a2a_public_url, token=a2a_server.read_token(args.a2a_token_file), From 911c9de71b7ac7d4ff9d762b7c47adc4ff96d6cb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:18:00 -0500 Subject: [PATCH 04/18] docs: link the handoff and A2A capability rows to #2414 --- CAPABILITIES.md | 4 ++-- llms-full.txt | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 462414a4a0..bf3ef78492 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -313,8 +313,8 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | -| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main (#PR_NUMBER) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main (#PR_NUMBER) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | diff --git a/llms-full.txt b/llms-full.txt index 8562adbca5..ee8c8ff134 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -767,8 +767,8 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md) | -| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main (#PR_NUMBER) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main (#PR_NUMBER) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | From ce8546675363dc1a6a57bcb1e9af985e5d3dbd8a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:24:23 -0500 Subject: [PATCH 05/18] feat(handoff): key and trust commands, named signer in the two-party test, conditional receipt copy openadapt handoff key prints this computer's receipt key; handoff trust pins another party's key as customer_key under its name, so its receipts verify as 'Signed by 's key'. The two-party test now pins the sender that way. The Agent Card and docs say a result carries its receipt when Flow wrote one (sandbox and strict at-rest runs have none). --a2a refuses --allow-protected-export and prints its URL at startup. --- CAPABILITIES.md | 2 +- packages/agent/tests/test_handoff_e2e.py | 22 +++++- packages/flow/docs/A2A.md | 20 ++++- packages/flow/docs/HANDOFFS.md | 16 ++++ .../flow/openadapt_flow/agent/a2a_server.py | 17 ++++- packages/flow/openadapt_flow/agent/cli.py | 5 ++ packages/flow/openadapt_flow/cli_handoff.py | 76 +++++++++++++++++++ packages/flow/tests/test_handoff.py | 17 +++++ 8 files changed, 166 insertions(+), 9 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index bf3ef78492..57fd8d032c 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -314,7 +314,7 @@ improvising or retrying when something is off. | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | | Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | diff --git a/packages/agent/tests/test_handoff_e2e.py b/packages/agent/tests/test_handoff_e2e.py index 940fcc4e0f..c4c9a31365 100644 --- a/packages/agent/tests/test_handoff_e2e.py +++ b/packages/agent/tests/test_handoff_e2e.py @@ -404,6 +404,17 @@ async def scenario(): assert h.verify_handoff(handoff, _registry(signer)).ok +def test_a2a_refuses_flags_that_need_a_person_or_export_protected_data(bundles_root, capsys): + from openadapt_flow.agent.cli import main + + for flag in (["--allow-protected-export"], ["--authoring"]): + assert main(["serve", "--bundles", str(bundles_root), "--a2a", *flag]) == 2 + err = capsys.readouterr().err + assert "--allow-protected-export stays on local MCP stdio" in err + assert "--authoring needs a person" in err + assert main(["serve", "--a2a-token-file", "x"]) == 2 + + def test_handoff_tools_are_off_unless_asked(bundles_root, runner_config): bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") names = {s.name for s in bridge.list_tool_specs()} @@ -440,7 +451,14 @@ def own_record(claim): return h.ReceiverRecord("recorded_differently", ("note",)) return h.ReceiverRecord("recorded_as_intended") - registry = _registry(signer) + # B pins A's key under A's name, never as "this computer". + registry = r.parse_registry( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [{**signer.registry_entry(), "role": "customer_key", "org": "Party A"}], + } + ) + signer_lines: set[tuple[str, ...]] = set() decisions: list[tuple[str, str, float]] = [] class Inbox(BaseHTTPRequestHandler): @@ -454,6 +472,7 @@ def do_POST(self): spent = time.perf_counter() - started kind = json.loads(body)["payload"]["content"]["kind"] decisions.append((kind, verdict.decision, spent)) + signer_lines.add(tuple(verdict.signer_lines)) self.send_response(202) self.end_headers() @@ -497,6 +516,7 @@ async def runs(): f"rejected true {len(rejected_true)}, slowest check {slowest * 1000:.1f} ms" ) assert accepted_false == [] and rejected_true == [] + assert signer_lines == {("Signed by Party A's key",)} assert slowest <= 2.0 # Without its own read, the receiver never accepts on the signature. unchecked = h.decide(h.make_handoff({"ref": "x"}, receipts[0]), registry) diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md index 10c6724724..ea77bb60fa 100644 --- a/packages/flow/docs/A2A.md +++ b/packages/flow/docs/A2A.md @@ -24,7 +24,7 @@ openadapt agent serve --bundles ./bundles --mode production --a2a | One skill per workflow | Send a data part `{"skill": NAME, "inputs": {...}, "request_id": ID}`. | | Skill `verify_handoff` | Send another agent's handoff and get the verdict ([HANDOFFS.md](HANDOFFS.md)). | | `capabilities.extensions` | `https://openadapt.ai/extensions/handoff-receipt/v1`, not required ([HANDOFF_RECEIPTS.md](HANDOFF_RECEIPTS.md)). | -| Task artifact `run_result` | The run result (`outcome`, `safe_to_retry` unchanged) plus the `openadapt.handoff/v1` document with the run's signed receipt (`record/run/v1`). | +| Task artifact `run_result` | The run result (`outcome`, `safe_to_retry` unchanged), plus the `openadapt.handoff/v1` document with the run's signed receipt (`record/run/v1`) when Flow wrote one. Otherwise a text part says why no receipt is attached. | Only outcome `done` is `TASK_STATE_COMPLETED`. `needs_review` is `TASK_STATE_INPUT_REQUIRED`: a person at this computer decides. A message on @@ -32,6 +32,20 @@ that task only re-checks the run; it never approves it. Every other outcome is `TASK_STATE_FAILED`. Cancelling a task never stops a run part way through a write; the server answers `TaskNotCancelableError`. +## When a run has no receipt + +Flow writes `receipt.json` after every `openadapt-flow run` and `replay`. +Three kinds of run have none: + +- **Sandbox runs.** `--mode sandbox` runs on a synthetic app, not through + the Flow CLI. +- **Encrypted runs.** With `OPENADAPT_FLOW_AT_REST=strict`, the run folder is + encrypted at rest and Flow writes no receipt. +- **Runs with receipts off.** Runs with `OPENADAPT_RECEIPT=off`. + +For these, `get_handoff` refuses, and the A2A artifact carries the run result +without a handoff. + ## Same rules as MCP A request over A2A goes through the same gate as the same request over MCP @@ -47,8 +61,8 @@ A request over A2A goes through the same gate as the same request over MCP Only these calls exist over A2A: `list_workflows`, `run_workflow`, `get_run`, `get_handoff` and `verify_handoff`. Attended decisions, admission decisions and approval answers need a person in a confirmation form, so A2A doesn't -serve them. `--authoring`, `--guard`, `--verify`, `--teach` and -`--teach-browser` stay on MCP stdio. +serve them. `--authoring`, `--guard`, `--verify`, `--teach`, +`--teach-browser` and `--allow-protected-export` stay on MCP stdio. ## Network diff --git a/packages/flow/docs/HANDOFFS.md b/packages/flow/docs/HANDOFFS.md index 22c2e050bc..4b216a5561 100644 --- a/packages/flow/docs/HANDOFFS.md +++ b/packages/flow/docs/HANDOFFS.md @@ -65,6 +65,22 @@ it. It rejects when your read fails. Without a read it never accepts. - **The pass bar.** The second party must accept no false handoff, reject no true one, and spend at most 2 s checking each. +## Trusting another party's key + +Each party pins the keys it trusts. Nothing in a handoff can make a key +trusted. The sender prints its key, and the receiver pins it under the +sender's name: + +```bash +# Sender +openadapt handoff key > sender-key.json +# Receiver, after getting sender-key.json from the sender by a channel it trusts +openadapt handoff trust sender-key.json --org "Example Clinic" --keys trusted-keys.json +``` + +Receipts from that key then verify as "Signed by Example Clinic's key". They +never verify as "Signed by this computer", which is reserved for your own key. + ## From the command line ```bash diff --git a/packages/flow/openadapt_flow/agent/a2a_server.py b/packages/flow/openadapt_flow/agent/a2a_server.py index b887093dcd..000a2630bf 100644 --- a/packages/flow/openadapt_flow/agent/a2a_server.py +++ b/packages/flow/openadapt_flow/agent/a2a_server.py @@ -137,8 +137,9 @@ def _skills(bridge: AgentBridge, *, include_workflows: bool) -> list[Any]: ) + " Send a data part {\"skill\": \"" + name - + "\", \"inputs\": {...}, \"request_id\": \"...\"}. The " - "result includes the run's signed receipt.", + + "\", \"inputs\": {...}, \"request_id\": \"...\"}. A " + "finished run's result includes its signed receipt when Flow " + "wrote one.", tags=["openadapt", "workflow", "receipt"], input_modes=["application/json"], output_modes=["application/json", MEDIA_TYPE], @@ -204,8 +205,8 @@ def build_agent_card( name="OpenAdapt", description=( "Runs compiled OpenAdapt workflows on this computer and checks that " - "they saved. Every run's result carries its signed receipt, and any " - "agent can send a handoff to be verified." + "they saved. A finished run's result carries its signed receipt when " + "Flow wrote one, and any agent can send a handoff to be verified." ), provider=AgentProvider(organization="OpenAdapt", url="https://openadapt.ai"), version=__version__, @@ -567,8 +568,16 @@ def read_token(path: Optional[str]) -> Optional[str]: def serve(bridge: AgentBridge, config: A2AConfig) -> None: """Serve until interrupted.""" + import sys + import uvicorn + print( + f"openadapt-agent: serving over A2A at {config.base_url} (Agent Card " + f"{config.base_url}/.well-known/agent-card.json); " + + ("bearer token required" if config.token else "loopback only"), + file=sys.stderr, + ) uvicorn.run( build_app(bridge, config), host=config.host, diff --git a/packages/flow/openadapt_flow/agent/cli.py b/packages/flow/openadapt_flow/agent/cli.py index 551258bf0a..3fb9cbfaac 100644 --- a/packages/flow/openadapt_flow/agent/cli.py +++ b/packages/flow/openadapt_flow/agent/cli.py @@ -1587,6 +1587,11 @@ def _a2a_problem(args: argparse.Namespace) -> Optional[str]: f"--a2a serves run and handoff tools only; {flag} needs a person " "in an MCP client, so it stays on MCP stdio" ) + if args.allow_protected_export: + return ( + "--allow-protected-export stays on local MCP stdio; --a2a never " + "sends protected workflow data" + ) if not a2a_server.a2a_available(): return a2a_server.A2A_INSTALL_HINT return None diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index e9c6ae282a..20179c0c03 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -88,6 +88,28 @@ def register(sub: argparse._SubParsersAction) -> None: v.add_argument("--json", action="store_true", help="print the verdict as JSON") v.set_defaults(func=cmd_verify) + k = hsub.add_parser( + "key", + help="Print this computer's receipt key, for another agent to trust", + allow_abbrev=False, + ) + k.set_defaults(func=cmd_key) + + t = hsub.add_parser( + "trust", + help="Add another party's key (from `handoff key`) to your key registry", + allow_abbrev=False, + ) + t.add_argument("key_file", help="the other party's `handoff key` output") + t.add_argument("--org", required=True, help="who they are, e.g. 'Example Clinic'") + t.add_argument( + "--keys", + required=True, + metavar="REGISTRY", + help="your registry file (created if missing)", + ) + t.set_defaults(func=cmd_trust) + def _read(path: str) -> bytes: if path == "-": @@ -219,3 +241,57 @@ def cmd_verify(args: argparse.Namespace) -> int: else: _print_verdict(verdict) return 0 if verdict["integrity"] == "intact" else 1 + + +def cmd_key(args: argparse.Namespace) -> int: + from openadapt_flow.offline_seal import public_key_entry, seal_home + + try: + entry = public_key_entry(seal_home()) + except Exception as exc: # noqa: BLE001 - no usable key: say so, sign nothing + print(f"handoff key: no receipt key on this computer ({exc})", file=sys.stderr) + return 2 + print(json.dumps({"key_id": entry["key_id"], "public_key": entry["public_key"]}, indent=2)) + return 0 + + +def cmd_trust(args: argparse.Namespace) -> int: + """Pin another party's key as ``customer_key`` with the org you name. + + Their receipts then verify as "Signed by 's key", never as this + computer. The registry is parsed again after the change, so a bad + entry is refused before it is written. + """ + from openadapt_types import receipt as r + + try: + entry = r.loads_strict(Path(args.key_file).read_text("utf-8")) + path = Path(args.keys) + registry = ( + r.loads_strict(path.read_text("utf-8")) + if path.is_file() + else {"schema": r.REGISTRY_SCHEMA, "keys": []} + ) + if not isinstance(entry, dict) or set(entry) - {"key_id", "public_key", "status"}: + raise ValueError("the key file is one `handoff key` entry") + keys = [k for k in registry.get("keys", []) if k.get("key_id") != entry.get("key_id")] + keys.append( + { + "key_id": entry.get("key_id"), + "public_key": entry.get("public_key"), + "role": "customer_key", + "org": args.org, + "status": "active", + } + ) + updated = {"schema": r.REGISTRY_SCHEMA, "keys": keys} + r.parse_registry(updated) + except r.RegistryError as exc: + print(f"handoff trust: refused ({exc.reason}): {exc}", file=sys.stderr) + return 2 + except (OSError, ValueError) as exc: + print(f"handoff trust: {type(exc).__name__}: {exc}", file=sys.stderr) + return 2 + path.write_text(json.dumps(updated, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(f"handoff: {args.org}'s key {entry['key_id']} is trusted in {path}", file=sys.stderr) + return 0 diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index 2412c14bac..a75b069dfa 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -238,6 +238,23 @@ def test_cli_send_and_verify_inline_and_detached(run_dir, signer, tmp_path, caps assert flow_main(["handoff", "verify", str(out), "--keys", str(other)]) == 1 +def test_cli_key_and_trust_pin_the_other_party_by_name(run_dir, signer, tmp_path, capsys): + key = tmp_path / "sender-key.json" + key.write_text(json.dumps({k: v for k, v in signer.registry_entry().items() if k != "status"})) + keys = tmp_path / "trusted.json" + args = ["handoff", "trust", str(key), "--org", "Example Clinic", "--keys", str(keys)] + assert flow_main(args) == 0 + registry = r.parse_registry(json.loads(keys.read_text())) + assert [(k.role, k.org) for k in registry] == [("customer_key", "Example Clinic")] + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) + assert h.verify_handoff(doc, registry).signer_lines == ["Signed by Example Clinic's key"] + bad = ["handoff", "trust", str(key), "--org", "x" * 80, "--keys", str(keys)] + assert flow_main(bad) == 2 + key.write_text('{"key_id": "seal-ed25519-0000000000000000", "public_key": "AAAA"}') + assert flow_main(args) == 2 + capsys.readouterr() + + def test_cli_send_refuses_the_private_file_and_plain_http(run_dir, tmp_path, capsys): payload = tmp_path / "p.json" payload.write_text("{}") From f7f80117364e878c734b437fcc5b0a774db1096a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:24:35 -0500 Subject: [PATCH 06/18] docs: regenerate llms-full.txt --- llms-full.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/llms-full.txt b/llms-full.txt index ee8c8ff134..2ada9a3959 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -768,7 +768,7 @@ improvising or retrying when something is off. | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md) | | Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact, a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | From 4fe4719ff48368fa0280fbf5f3eef71f2603cd7e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:33:07 -0500 Subject: [PATCH 07/18] refactor(cli): register handoff beside receipt, not in __main__ (size budget) --- packages/flow/openadapt_flow/__main__.py | 4 ---- packages/flow/openadapt_flow/cli_receipt.py | 6 ++++++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index e9277863a8..b3a3b13912 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13194,10 +13194,6 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _register_receipt(sub) - from openadapt_flow.cli_handoff import register as _register_handoff - - _register_handoff(sub) - from openadapt_flow.learn import register as _register_learn _register_learn(sub) diff --git a/packages/flow/openadapt_flow/cli_receipt.py b/packages/flow/openadapt_flow/cli_receipt.py index 75a2829350..e037e2223b 100644 --- a/packages/flow/openadapt_flow/cli_receipt.py +++ b/packages/flow/openadapt_flow/cli_receipt.py @@ -65,6 +65,12 @@ def register(sub: argparse._SubParsersAction) -> None: a.add_argument("file") a.set_defaults(func=cmd_anchor) + # `handoff` attaches a run's receipt to what one agent hands another. It + # registers here, beside `receipt`, to keep __main__ within its size budget. + from openadapt_flow.cli_handoff import register as register_handoff + + register_handoff(sub) + def _pem(raw: bytes) -> bytes: from cryptography.hazmat.primitives import serialization From 6ee51139bc6c8da3f265af6d9e8416710914a890 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:37:39 -0500 Subject: [PATCH 08/18] feat(cli): share one handoff group with the counterparty list command, in either registration order --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../06-give-agents-the-program/handoff.md | 2 +- packages/flow/openadapt_flow/cli_handoff.py | 33 ++++++++++++++----- packages/flow/tests/test_handoff.py | 16 +++++++++ 5 files changed, 43 insertions(+), 12 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 57fd8d032c..20982b27c7 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -445,7 +445,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. -- `handoff`: Hand a result to another agent with its run's receipt attached (inline, detached beside a file, or POSTed to a webhook), and verify one on arrival against your pinned keys: who signed, what was checked, and that a valid signature proves who signed, not that the claim is true. +- `handoff`: Agent-to-agent handoffs: `send` attaches a run's receipt to what one agent hands another (inline, detached beside a file, or POSTed to a webhook); `verify` checks one on arrival against your pinned keys (who signed, what was checked, and that a valid signature proves who signed, not that the claim is true); `key` and `trust` exchange receipt keys between parties; `list` shows handoffs to other parties and what their systems confirmed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** diff --git a/llms-full.txt b/llms-full.txt index 2ada9a3959..e95d131588 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -899,7 +899,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. -- `handoff`: Hand a result to another agent with its run's receipt attached (inline, detached beside a file, or POSTed to a webhook), and verify one on arrival against your pinned keys: who signed, what was checked, and that a valid signature proves who signed, not that the claim is true. +- `handoff`: Agent-to-agent handoffs: `send` attaches a run's receipt to what one agent hands another (inline, detached beside a file, or POSTed to a webhook); `verify` checks one on arrival against your pinned keys (who signed, what was checked, and that a valid signature proves who signed, not that the claim is true); `key` and `trust` exchange receipt keys between parties; `list` shows handoffs to other parties and what their systems confirmed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** diff --git a/packages/flow/docs/commands/06-give-agents-the-program/handoff.md b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md index b1e6ec2a53..af830da10d 100644 --- a/packages/flow/docs/commands/06-give-agents-the-program/handoff.md +++ b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md @@ -1 +1 @@ -Hand a result to another agent with its run's receipt attached (inline, detached beside a file, or POSTed to a webhook), and verify one on arrival against your pinned keys: who signed, what was checked, and that a valid signature proves who signed, not that the claim is true. +Agent-to-agent handoffs: `send` attaches a run's receipt to what one agent hands another (inline, detached beside a file, or POSTed to a webhook); `verify` checks one on arrival against your pinned keys (who signed, what was checked, and that a valid signature proves who signed, not that the claim is true); `key` and `trust` exchange receipt keys between parties; `list` shows handoffs to other parties and what their systems confirmed. diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index 20179c0c03..e665593d05 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -19,16 +19,31 @@ from typing import Any, Optional +def handoff_group(sub: argparse._SubParsersAction) -> argparse._SubParsersAction: + """The ``handoff`` group's subcommands, created once and shared. + + ``send``, ``verify``, ``key`` and ``trust`` register here; the + counterparty confirmations' ``list`` registers into the same group, + whichever module registers first. + """ + parser = sub.choices.get("handoff") + if parser is None: + parser = sub.add_parser( + "handoff", + help=( + "Hand a result to another agent with its run's receipt, verify " + "one on arrival, and follow handoffs to other parties" + ), + allow_abbrev=False, + ) + for action in parser._actions: + if isinstance(action, argparse._SubParsersAction): + return action + return parser.add_subparsers(dest="handoff_command", required=True) + + def register(sub: argparse._SubParsersAction) -> None: - p = sub.add_parser( - "handoff", - help=( - "Attach a run's receipt to what one agent hands another, and " - "verify one on arrival" - ), - allow_abbrev=False, - ) - hsub = p.add_subparsers(dest="handoff_command", required=True) + hsub = handoff_group(sub) s = hsub.add_parser( "send", diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index a75b069dfa..c6a0a45995 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -343,3 +343,19 @@ def broken(claim): calls = [] refused = h.decide(h.make_handoff({"ref": "ref-1"}, receipt), [], calls.append) assert refused.decision == "reject" and calls == [] + + +def test_the_handoff_group_is_shared_whichever_module_registers_first(): + import argparse + + from openadapt_flow.cli_handoff import handoff_group, register + + for list_first in (True, False): + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="command") + if list_first: + handoff_group(sub).add_parser("list") + register(sub) + if not list_first: + handoff_group(sub).add_parser("list") + assert sorted(handoff_group(sub).choices) == ["key", "list", "send", "trust", "verify"] From 00905966cf501df8c9fc6e206206302fabaa7953 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:44:53 -0500 Subject: [PATCH 09/18] feat(handoff): bind each handoff's payload as the receipt's payload subject handoff send, get_handoff and the A2A run artifact re-sign the run's receipt with the payload subject (digest and media type) using the key that signed the run; verify checks the bytes with verify_receipt(received=...), so a swapped payload is payload_mismatch and a receipt naming none is payload_not_bound. The two-party test now includes both, and the shared payload vectors run through a handoff. Merges #2410 at 49da9cdd. --- CAPABILITIES.md | 2 +- llms-full.txt | 8 +- packages/agent/tests/test_handoff_e2e.py | 49 ++++-- packages/flow/CHANGELOG.md | 6 +- packages/flow/docs/HANDOFFS.md | 11 +- packages/flow/docs/HANDOFF_RECEIPTS.md | 22 ++- .../openadapt_flow/agent/handoff_tools.py | 19 ++- packages/flow/openadapt_flow/cli_handoff.py | 17 ++ packages/flow/openadapt_flow/handoff.py | 151 ++++++++++++------ packages/flow/tests/test_handoff.py | 104 ++++++++---- 10 files changed, 286 insertions(+), 103 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 20982b27c7..7020202650 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -313,7 +313,7 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | -| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects) | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | | A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | diff --git a/llms-full.txt b/llms-full.txt index e95d131588..0adbd7462d 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -767,7 +767,7 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md) | -| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, marks the payload unbound unless it is a signed subject, and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors (good, tampered, unknown signer, swapped payload, detached file, local webhook); MCP end to end with the stubbed run process | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects) | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | | A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | @@ -2412,8 +2412,10 @@ automation into an independently certified transaction system. keys and returns a verdict (`openadapt.handoff-verdict/v1`). The verdict gives the signer role, integrity, the checks passed and not checked, and counterparty confirmation lines. It always says that a valid signature - proves who signed, not that the claim is true, and it marks the payload - unbound unless it is a signed subject. The private openings file never + proves who signed, not that the claim is true. `send` binds the payload as + the receipt's `payload` subject, re-signed by the run's own key, so a + receiver refuses other bytes (`payload_mismatch`) or a receipt that names + no payload (`payload_not_bound`). The private openings file never travels (docs/HANDOFFS.md, docs/HANDOFF_RECEIPTS.md). - `openadapt-agent serve --handoffs` adds the MCP tools `get_handoff` and `verify_handoff`. `serve --a2a` serves the same workflows over the A2A diff --git a/packages/agent/tests/test_handoff_e2e.py b/packages/agent/tests/test_handoff_e2e.py index c4c9a31365..d0bffb73b3 100644 --- a/packages/agent/tests/test_handoff_e2e.py +++ b/packages/agent/tests/test_handoff_e2e.py @@ -18,6 +18,7 @@ import asyncio import base64 +import hashlib import json import socket import threading @@ -94,7 +95,7 @@ def bridge(monkeypatch, bundles_root, runner_config, success_report, signer): runner_mod, "_run_flow_process", ReceiptWritingStub(signer, exit_code=0, report=report) ) bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") - bridge.handoffs = HandoffTools(registry=_registry(signer)) + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) return bridge @@ -235,6 +236,7 @@ async def scenario(): tampered = await _send( a2a_url, {"skill": "verify_handoff", "handoff": _tampered(handoff)} ) + # The receipt is bound to the run result; stapled to other bytes it fails. restapled = h.make_handoff({"outcome": "done", "amount": 10**6}, handoff["receipt"]) swapped = await _send(a2a_url, {"skill": "verify_handoff", "handoff": restapled}) return handoff, _verdict_from(good), _verdict_from(tampered), _verdict_from(swapped) @@ -245,7 +247,8 @@ async def scenario(): assert good["outcome"] == "VERIFIED" assert good["what_this_proves"][0] == h.WHAT_A_SIGNATURE_PROVES assert tampered["integrity"] == "refused" and tampered["reason"] == "bad_signature" - assert swapped["integrity"] == "intact" and swapped["payload"]["bound"] is False + assert good["payload"]["bound"] is True + assert swapped["integrity"] == "refused" and swapped["reason"] == "payload_mismatch" # Unknown signer: a receiver that pins other keys refuses the same handoff. other = SoftwareSigner(Ed25519PrivateKey.generate(), "generated") assert h.verify_handoff(handoff, _registry(other)).reason == "unknown_signer" @@ -261,7 +264,7 @@ def test_a2a_unknown_signer_through_the_server(a2a_url, bridge, tmp_path): json.dumps({"execution_outcome": "VERIFIED", "results": WRITE_REPORT_RESULTS}) ) write_receipt_record(run, signer=other, flow_version="3.4.0") - doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run)) + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run), signer=other) async def scenario(): return _verdict_from(await _send(a2a_url, {"skill": "verify_handoff", "handoff": doc})) @@ -339,7 +342,7 @@ def test_a2a_follow_up_cannot_approve_a_run_waiting_for_a_person( runner_mod, "_run_flow_process", ReceiptWritingStub(signer, exit_code=1, report=halt_report) ) bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") - bridge.handoffs = HandoffTools(registry=_registry(signer)) + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) executor = a2a_server.OpenAdaptExecutor(bridge) result = a2a_server.call_remote_tool( bridge, @@ -440,7 +443,10 @@ def test_two_party_twenty_handoffs_receiver_reads_its_own_record(a2a_url, bridge db = sqlite3.connect(":memory:", check_same_thread=False) db.execute("create table referral (ref text primary key, note text)") - kinds = ["true"] * 10 + ["fabricated"] * 5 + ["differing"] * 5 + # Every handoff but "unbound" binds its claim as the receipt's payload. + # "swapped" changes the claim after binding (mismatched); "unbound" + # carries a receipt that names no payload (missing). + kinds = ["true"] * 10 + ["fabricated"] * 4 + ["differing"] * 4 + ["swapped", "unbound"] workflow = next(iter(bridge.catalog)) def own_record(claim): @@ -459,6 +465,7 @@ def own_record(claim): } ) signer_lines: set[tuple[str, ...]] = set() + reasons: dict[str, set] = {kind: set() for kind in ("true", "fabricated", "differing", "swapped", "unbound")} decisions: list[tuple[str, str, float]] = [] class Inbox(BaseHTTPRequestHandler): @@ -472,7 +479,9 @@ def do_POST(self): spent = time.perf_counter() - started kind = json.loads(body)["payload"]["content"]["kind"] decisions.append((kind, verdict.decision, spent)) - signer_lines.add(tuple(verdict.signer_lines)) + reasons[kind].add(verdict.reason) + if verdict.ok: + signer_lines.add(tuple(verdict.signer_lines)) self.send_response(202) self.end_headers() @@ -487,12 +496,12 @@ async def runs(): a2a_url, {"skill": workflow, "inputs": {"note": f"n{i}"}, "request_id": f"ref-2p-{i:04d}"}, ) - out.append(_handoff_from(task)["receipt"]) + out.append((_handoff_from(task)["receipt"], _result_from(task)["run_id"])) return out try: receipts = asyncio.run(runs()) - for i, (kind, receipt) in enumerate(zip(kinds, receipts)): + for i, (kind, (receipt, run_id)) in enumerate(zip(kinds, receipts)): ref, note = f"ref-2p-{i:04d}", f"n{i}" # Stands in for the record party A's program wrote in B's system. if kind == "true": @@ -500,9 +509,18 @@ async def runs(): elif kind == "differing": db.execute("insert into referral values (?, ?)", (ref, note + "-changed")) claim = {"kind": kind, "ref": ref, "fields": {"note": note}} - status = post_handoff( - f"http://127.0.0.1:{inbox.server_address[1]}/inbox", h.make_handoff(claim, receipt) - ) + if kind == "unbound": + # The run's own receipt.json, which names no payload. + run_dir = Path(bridge.runner_config.runs_dir) / run_id + doc = h.make_handoff(claim, h.receipt_for_run(run_dir)) + else: + doc = h.make_handoff(claim, receipt, signer=signer) + if kind == "swapped": + db.execute("insert into referral values (?, ?)", (ref, note + "-other")) + swapped = {**claim, "fields": {"note": note + "-other"}} + doc["payload"]["content"] = swapped + doc["payload"]["sha256"] = hashlib.sha256(h.payload_bytes(swapped)[0]).hexdigest() + status = post_handoff(f"http://127.0.0.1:{inbox.server_address[1]}/inbox", doc) assert status == 202 finally: inbox.shutdown() @@ -517,7 +535,14 @@ async def runs(): ) assert accepted_false == [] and rejected_true == [] assert signer_lines == {("Signed by Party A's key",)} + # Bound and true: accepted. Fabricated or differing: the receipt is + # intact, and the receiver's own record rejects them. Mismatched and + # missing payloads: the receipt itself refuses them. + assert reasons["true"] == {None} + assert reasons["fabricated"] == {None} and reasons["differing"] == {None} + assert reasons["swapped"] == {"payload_mismatch"} + assert reasons["unbound"] == {"payload_not_bound"} assert slowest <= 2.0 # Without its own read, the receiver never accepts on the signature. - unchecked = h.decide(h.make_handoff({"ref": "x"}, receipts[0]), registry) + unchecked = h.decide(h.make_handoff({"ref": "x"}, receipts[0][0], signer=signer), registry) assert unchecked.ok and unchecked.decision == "unchecked" diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index ae382fbc6c..b83a5ccc35 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -26,8 +26,10 @@ keys and returns a verdict (`openadapt.handoff-verdict/v1`). The verdict gives the signer role, integrity, the checks passed and not checked, and counterparty confirmation lines. It always says that a valid signature - proves who signed, not that the claim is true, and it marks the payload - unbound unless it is a signed subject. The private openings file never + proves who signed, not that the claim is true. `send` binds the payload as + the receipt's `payload` subject, re-signed by the run's own key, so a + receiver refuses other bytes (`payload_mismatch`) or a receipt that names + no payload (`payload_not_bound`). The private openings file never travels (docs/HANDOFFS.md, docs/HANDOFF_RECEIPTS.md). - `openadapt-agent serve --handoffs` adds the MCP tools `get_handoff` and `verify_handoff`. `serve --a2a` serves the same workflows over the A2A diff --git a/packages/flow/docs/HANDOFFS.md b/packages/flow/docs/HANDOFFS.md index 4b216a5561..a1e36f3223 100644 --- a/packages/flow/docs/HANDOFFS.md +++ b/packages/flow/docs/HANDOFFS.md @@ -25,8 +25,15 @@ The format is described in the claim is true. Only a confirmation read from the other party's own system is independent of the sender. -The receipt signs the run, not the payload, unless the payload is the signed -report itself. The verdict says when nothing ties the payload to the receipt. +`send` binds the payload to the receipt. It adds the payload's digest and +media type as the receipt's `payload` subject and signs again with the key +that signed the run. A receiver holding the payload refuses two kinds of +receipt: + +- one that names no payload (`payload_not_bound`); +- one that names other bytes (`payload_mismatch`). + +`--unbound` attaches the run's receipt as it is. ## A signature doesn't make the claim true diff --git a/packages/flow/docs/HANDOFF_RECEIPTS.md b/packages/flow/docs/HANDOFF_RECEIPTS.md index f8675a0cf3..bb7dcbde52 100644 --- a/packages/flow/docs/HANDOFF_RECEIPTS.md +++ b/packages/flow/docs/HANDOFF_RECEIPTS.md @@ -36,10 +36,12 @@ Every verifier MUST tell its user the following, in its own words: changed since. It does **not** prove that the receipt's claims are true. 2. The signer's role comes from the **receiver's** pinned key registry, never from the handoff document or the envelope. -3. The receipt signs the **run** (its report and bundle digests), not the - handoff payload. The payload is **bound** only when its SHA-256 equals a - signed subject digest. Otherwise the verdict MUST say that nothing ties the - payload to the receipt. +3. The receipt binds the handoff payload only through a `payload` subject: + `{"name": "payload", "digest": {"sha256": ...}, "media_type": ...}`. + The sender adds that subject and signs again with the key that signed the + run, which never changes who signed. A receiver that holds the payload + MUST refuse a receipt with no `payload` subject (`payload_not_bound`) or + with another digest (`payload_mismatch`). 4. A confirmation counts as **independent of the sender** only when its signed `read_method` reads the other party's own system (`portal_read_back` or `api`). Any other claim rests on the signer's word. @@ -103,8 +105,14 @@ The result is a refusal, never a partial pass. consistent, and free of embedded content. 3. **Check the payload**: - recompute its SHA-256 from the inline content or the detached file; - - refuse on mismatch (`payload_mismatch`); - - mark it bound only if it equals a signed `subject` digest. + - refuse when it doesn't match the document's own `payload.sha256` + (`payload_mismatch`); + - check the bytes against the receipt's `payload` subject, as + `verify_receipt(..., received=bytes)` does in the reference verifier. + A receipt with no `payload` subject is refused (`payload_not_bound`), + and one with a different digest is refused (`payload_mismatch`); + - a detached payload the receiver doesn't have is reported as not + checked, never as bound. 4. **Report** the verdict (section 5). ## 5. The verdict @@ -119,7 +127,7 @@ The result is a refusal, never a partial pass. "outcome": "VERIFIED", "checks": {"passed": [], "incomplete": [], "not_checked": ["field_values"], "writes": {"confirmed": 1, "refuted": 0, "not_checked": 0}}, - "payload": {"bound": false, "note": "The receipt signs the run's report, not this payload. ..."}, + "payload": {"bound": true, "media_type": "application/json", "note": "The receipt's signer bound these exact payload bytes: ..."}, "confirmations": [{"state": "recorded_as_intended", "read_method": "api", "independent": true}], "confirmation_lines": ["Confirmed in the other party's system"], "independent_confirmations": 1, diff --git a/packages/flow/openadapt_flow/agent/handoff_tools.py b/packages/flow/openadapt_flow/agent/handoff_tools.py index 6de811a987..3219f75258 100644 --- a/packages/flow/openadapt_flow/agent/handoff_tools.py +++ b/packages/flow/openadapt_flow/agent/handoff_tools.py @@ -34,9 +34,20 @@ def __init__( *, registry_path: Optional[Path] = None, registry: Optional[Sequence[Any]] = None, + signer: Optional[Any] = None, ) -> None: self.registry_path = Path(registry_path) if registry_path else None self._registry = list(registry) if registry is not None else None + #: The key that signs this computer's run receipts; it binds each + #: handed-off result as the receipt's payload subject. + self._signer = signer + + def signer(self) -> Any: + if self._signer is None: + from openadapt_flow.offline_seal import seal_home, signer_for + + self._signer = signer_for(seal_home()) + return self._signer def registry(self) -> list[Any]: if self._registry is None: @@ -129,6 +140,12 @@ def get( raise BridgeError("the run is still running; it has no receipt yet") try: receipt = receipt_for_run(run_dir_for(run_id), public=public) - return make_handoff(result, receipt, name=f"{run_id}.result.json") + return make_handoff( + result, receipt, name=f"{run_id}.result.json", signer=self.signer() + ) except HandoffError as exc: raise BridgeError(f"no handoff for this run: {exc}") from None + except RuntimeError: + raise BridgeError( + "no handoff for this run: this computer's receipt key is unavailable" + ) from None diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index e665593d05..145ecf7283 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -68,6 +68,14 @@ def register(sub: argparse._SubParsersAction) -> None: ), ) s.add_argument("--media-type", help="the payload's media type") + s.add_argument( + "--unbound", + action="store_true", + help=( + "attach the receipt as it is, without binding this payload to it. " + "A receiver that checks the payload refuses it (payload_not_bound)" + ), + ) s.add_argument("--out", help="where to write the handoff (default: stdout)") s.add_argument( "--post", @@ -177,16 +185,25 @@ def cmd_send(args: argparse.Namespace) -> int: receipt = h.receipt_for_run(Path(args.run), public=args.public) else: receipt = h._loads_strict(Path(args.receipt).read_text("utf-8")) + signer = None + if not args.unbound: + from openadapt_flow.offline_seal import seal_home, signer_for + + signer = signer_for(seal_home()) document = h.make_handoff( data, receipt, name=None if args.payload == "-" else args.payload, media_type=args.media_type, detached=args.detached, + signer=signer, ) except h.HandoffError as exc: print(f"handoff send: {exc}", file=sys.stderr) return 2 + except RuntimeError as exc: + print(f"handoff send: no receipt key to bind the payload ({exc})", file=sys.stderr) + return 2 except (OSError, ValueError) as exc: print(f"handoff send: {type(exc).__name__}: {exc}", file=sys.stderr) return 2 diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index 1368ee3346..77f34f87c3 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -19,10 +19,11 @@ * A valid signature proves **who signed** the receipt (the role comes from the verifier's pinned registry, never from the document) and that the receipt is unchanged. It does not prove the receipt's claims are true. -* The receipt signs the run (its report and bundle), not the handoff payload. - The payload counts as **bound** only when its SHA-256 equals a signed - subject digest. Otherwise anyone could staple this receipt to another - payload, and the verdict says so. +* The sender binds the payload: :func:`bind_payload` adds it as the + receipt's ``payload`` subject and signs again with the key that signed the + run. A receiver holding the payload refuses a receipt that names other + bytes (``payload_mismatch``) or none (``payload_not_bound``), so a receipt + can't be stapled to another payload. * A confirmation line counts as **independent of the sender** only when it was read from the other party's system (``read_method`` ``portal_read_back`` or ``api``). Everything else is the sender's own word. @@ -53,11 +54,6 @@ "A valid signature proves who signed this receipt and that it has not " "changed since. It does not prove that what the receipt says is true." ) -NOT_BOUND = ( - "The receipt signs the run's report, not this payload. Nothing ties this " - "payload to the receipt: anyone could attach the same receipt to another " - "payload." -) class HandoffError(ValueError): @@ -114,13 +110,20 @@ def make_handoff( name: Optional[str] = None, media_type: Optional[str] = None, detached: bool = False, + signer: Optional[Any] = None, ) -> dict[str, Any]: """Attach ``receipt`` to ``payload`` as an ``openadapt.handoff/v1`` document. ``detached`` leaves the payload out and keeps only its digest, for a file - sent beside the document. + sent beside the document. With ``signer`` (the key that signed the run's + receipt), the receipt is re-signed with the payload as its ``payload`` + subject (:func:`bind_payload`), so the receiver can check that these are + the bytes the sender handed off. Without it the receipt names no payload + and a receiver's check refuses it (``payload_not_bound``). """ data, default_type = payload_bytes(payload) + if signer is not None: + receipt = bind_payload(receipt, data, media_type or default_type, signer) doc_payload: dict[str, Any] = { "media_type": media_type or default_type, "sha256": _sha256(data), @@ -144,6 +147,58 @@ def make_handoff( } +def _subject_media_type(media_type: str) -> str: + from typing import get_args + + from openadapt_types import receipt as r + + essence = media_type.split(";", 1)[0].strip().lower() + allowed = get_args(r.PayloadMediaType) + return essence if essence in allowed else "application/octet-stream" + + +def bind_payload( + receipt: Mapping[str, Any], data: bytes, media_type: str, signer: Any +) -> dict[str, Any]: + """Re-sign a run's receipt with ``data`` as its ``payload`` subject. + + Only a key that already signed the receipt may bind it, so binding never + changes who signed. Any other signature (a Cloud countersignature) covers + the old bytes and is dropped; it can be added again over the new ones. + A public card keeps its openings, which still match the commitments. + """ + from openadapt_types import receipt as r + + receipt = _check_receipt_document(receipt) + envelope = receipt["envelope"] if r.is_receipt_card(receipt) else receipt + kid = r.key_id(signer.public_raw()) + if kid not in {s.get("keyid") for s in envelope.get("signatures") or []}: + raise HandoffError( + "this computer's key didn't sign that receipt, so it can't bind a " + "payload to it" + ) + try: + statement = r.loads_strict(base64.b64decode(str(envelope["payload"]))) + except ValueError: + raise HandoffError("the receipt's statement is not readable") from None + subjects = [s for s in statement.get("subject") or [] if s.get("name") != "payload"] + subjects.append( + { + "name": "payload", + "digest": {"sha256": _sha256(data)}, + "media_type": _subject_media_type(media_type), + } + ) + statement["subject"] = subjects + try: + bound = r.sign_statement(statement, [(kid, signer.sign)]) + except ValueError as exc: + raise HandoffError(f"the payload can't be bound: {exc}") from None + if r.is_receipt_card(receipt): + return {**receipt, "envelope": bound} + return bound + + def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: """Read a run's ``receipt.json`` (or its public card) for attaching.""" from openadapt_types import receipt as r @@ -297,48 +352,48 @@ def _confirmations(statement: Mapping[str, Any], result: Any) -> list[dict[str, return out -def _payload_verdict( - doc_payload: Mapping[str, Any], - statement: Mapping[str, Any], - supplied: Optional[bytes], -) -> tuple[dict[str, Any], Optional[str]]: - """Whether the payload is what the document says, and whether it is signed.""" - declared = doc_payload.get("sha256") - actual: Optional[str] = None +def _received_bytes( + doc_payload: Mapping[str, Any], supplied: Optional[bytes] +) -> tuple[Optional[bytes], Optional[str]]: + """The payload bytes the receiver has, checked against the handoff's digest.""" + data: Optional[bytes] = None if supplied is not None: - actual = _sha256(supplied) + data = supplied elif "content_base64" in doc_payload: try: - actual = _sha256( - base64.b64decode(str(doc_payload["content_base64"]), validate=True) - ) + data = base64.b64decode(str(doc_payload["content_base64"]), validate=True) except ValueError: - return {}, "the inline payload is not base64" + return None, "the inline payload is not base64" elif "content" in doc_payload: - actual = _sha256(_canonical(doc_payload["content"])) - if actual is not None and actual != declared: - return {}, "the payload does not match its digest in the handoff" - subjects = { - s.get("digest", {}).get("sha256"): s.get("name") - for s in statement.get("subject") or [] - if isinstance(s, Mapping) - } - subject = subjects.get(actual or declared) if (actual or declared) else None + data = _canonical(doc_payload["content"]) + if data is not None and _sha256(data) != doc_payload.get("sha256"): + return None, "the payload does not match its digest in the handoff" + return data, None + + +def _payload_verdict( + doc_payload: Mapping[str, Any], statement: Mapping[str, Any], data: Optional[bytes] +) -> dict[str, Any]: + bound = next( + (s for s in statement.get("subject") or [] if s.get("name") == "payload"), None + ) result: dict[str, Any] = { - "sha256": declared, - "present": actual is not None, - "bound": subject is not None and actual is not None, - "bound_to": subject if actual is not None else None, + "sha256": doc_payload.get("sha256"), + "present": data is not None, + "bound": data is not None, + "media_type": (bound or {}).get("media_type"), } - if result["bound"]: - result["note"] = f"The payload is the signed {subject} itself." - elif actual is None: + if data is not None: result["note"] = ( - "The payload was not supplied, so it could not be checked. " + NOT_BOUND + "The receipt's signer bound these exact payload bytes: they are what " + "the sender handed off." ) else: - result["note"] = NOT_BOUND - return result, None + result["note"] = ( + "The payload was not supplied, so it could not be checked against " + "the receipt." + ) + return result def verify_handoff( @@ -374,13 +429,16 @@ def verify_handoff( return _refused("malformed", "a handoff has a payload and a receipt object") if receipt.get("schema") == r.OPENINGS_SCHEMA: return _refused("malformed", "a handoff never carries private openings") - result = r.verify_receipt(receipt, registry) + data, problem = _received_bytes(doc_payload, payload) + if problem: + return _refused("payload_mismatch", problem, "Not verified: " + problem) + # With the payload in hand, the receipt must name exactly these bytes as + # its payload subject (payload_not_bound, payload_mismatch otherwise). + result = r.verify_receipt(receipt, registry, received=data) if not result.ok or result.statement is None: return _refused(str(result.reason or "malformed"), result.detail) statement = result.statement - payload_result, problem = _payload_verdict(doc_payload, statement, payload) - if problem: - return _refused("payload_mismatch", problem, "Not verified: " + problem) + payload_result = _payload_verdict(doc_payload, statement, data) confirmations = _confirmations(statement, result) lines = [c["line"] for c in confirmations if c["line"]] independent = sum(1 for c in confirmations if c["independent"]) @@ -542,6 +600,7 @@ def detached_path(payload_path: Path) -> Path: "RECEIVER_STATES", "ReceiverRecord", "Verdict", + "bind_payload", "decide", "detached_path", "load_registry", diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index c6a0a45995..fa41e41d2d 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -51,8 +51,14 @@ def _registry(*signers: SoftwareSigner) -> list[r.RoleKey]: @pytest.fixture() -def signer() -> SoftwareSigner: - return _signer() +def signer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SoftwareSigner: + """This computer's receipt key, in a throwaway seal home.""" + from openadapt_flow.offline_seal import signer_for + + home = tmp_path / "seal-home" + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(home)) + monkeypatch.delenv("OPENADAPT_SEAL_KEY", raising=False) + return signer_for(home) @pytest.fixture() @@ -64,8 +70,12 @@ def run_dir(tmp_path: Path, signer: SoftwareSigner) -> Path: return run +def _bound(payload, run_dir, signer, **kwargs): + return h.make_handoff(payload, h.receipt_for_run(run_dir), signer=signer, **kwargs) + + def test_a_good_handoff_says_who_signed_and_what_that_does_not_prove(run_dir, signer): - doc = h.make_handoff({"outcome": "done", "count": 3}, h.receipt_for_run(run_dir)) + doc = _bound({"outcome": "done", "count": 3}, run_dir, signer) verdict = h.verify_handoff(doc, _registry(signer)) assert verdict.ok and verdict.integrity == "intact" assert verdict.signer_roles == ["this_computer"] @@ -76,24 +86,36 @@ def test_a_good_handoff_says_who_signed_and_what_that_does_not_prove(run_dir, si # The honesty rule: a signature proves who signed, not that it is true. assert verdict.what_this_proves[0] == h.WHAT_A_SIGNATURE_PROVES assert "does not prove" in verdict.what_this_proves[0] - # The receipt signs the report, not this payload. - assert verdict.payload["bound"] is False - assert verdict.payload["note"] == h.NOT_BOUND + # The sender's key bound these exact bytes as the payload subject. + assert verdict.payload["bound"] is True + assert verdict.payload["media_type"] == "application/json" assert verdict.confirmations == [] and verdict.independent_confirmations == 0 -def test_the_signed_report_itself_is_a_bound_payload(run_dir, signer): - report = (run_dir / "report.json").read_bytes() - doc = h.make_handoff(report, h.receipt_for_run(run_dir), name="report.json") +def test_binding_keeps_the_signer_and_names_the_payload(run_dir, signer): + original = h.receipt_for_run(run_dir) + doc = _bound(b"%PDF-1.7 claim", run_dir, signer, media_type="application/pdf") + statement = json.loads(base64.b64decode(doc["receipt"]["payload"])) + (payload,) = [s for s in statement["subject"] if s["name"] == "payload"] + assert payload["media_type"] == "application/pdf" + assert [s["keyid"] for s in doc["receipt"]["signatures"]] == [ + s["keyid"] for s in original["signatures"] + ] + # A key that didn't sign the run can't bind a payload to it. + with pytest.raises(h.HandoffError, match="didn't sign that receipt"): + h.make_handoff({"x": 1}, original, signer=_signer()) + + +def test_an_unbound_receipt_is_refused_once_the_payload_is_checked(run_dir, signer): + """Missing: a receipt that names no payload doesn't vouch for this one.""" + doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) verdict = h.verify_handoff(doc, _registry(signer)) - assert verdict.payload["bound"] is True - assert verdict.payload["bound_to"] == "report.json" + assert not verdict.ok and verdict.reason == "payload_not_bound" def test_a_tampered_receipt_is_refused(run_dir, signer): - doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) + doc = _bound({"outcome": "done"}, run_dir, signer) statement = json.loads(base64.b64decode(doc["receipt"]["payload"])) - statement["predicate"]["outcome"] = "VERIFIED" statement["predicate"]["model_calls"] = 7 doc["receipt"]["payload"] = base64.b64encode( r.canonical_json(statement).encode() @@ -106,26 +128,27 @@ def test_a_tampered_receipt_is_refused(run_dir, signer): ] -def test_an_unknown_signer_is_refused_even_when_the_signature_is_valid(run_dir): - doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) +def test_an_unknown_signer_is_refused_even_when_the_signature_is_valid(run_dir, signer): + doc = _bound({"outcome": "done"}, run_dir, signer) verdict = h.verify_handoff(doc, _registry(_signer())) assert not verdict.ok and verdict.reason == "unknown_signer" assert verdict.signer_lines == [r.UNKNOWN_SIGNER_LINE] assert h.verify_handoff(doc, []).reason == "unknown_signer" -def test_a_swapped_payload_is_caught_or_reported_unbound(run_dir, signer): - doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) +def test_a_swapped_payload_is_refused(run_dir, signer): + """Mismatched: the receipt signed other bytes than the ones received.""" + doc = _bound({"outcome": "done"}, run_dir, signer) # Swap the content but keep the old digest: the wrapper no longer matches. swapped = json.loads(json.dumps(doc)) swapped["payload"]["content"] = {"outcome": "done", "amount": 1_000_000} verdict = h.verify_handoff(swapped, _registry(signer)) assert not verdict.ok and verdict.reason == "payload_mismatch" - # Re-staple the receipt to a new payload with its own digest: the receipt - # still verifies, and the verdict says nothing ties the two together. + # Re-staple the bound receipt to a new payload with its own digest: the + # receipt names other bytes, so it is refused too. restapled = h.make_handoff({"outcome": "done", "amount": 1_000_000}, doc["receipt"]) verdict = h.verify_handoff(restapled, _registry(signer)) - assert verdict.ok and verdict.payload["bound"] is False + assert not verdict.ok and verdict.reason == "payload_mismatch" def test_private_openings_never_travel(run_dir): @@ -138,7 +161,7 @@ def test_private_openings_never_travel(run_dir): def test_a_handoff_with_extra_fields_or_another_schema_is_refused(run_dir, signer): - doc = h.make_handoff({"x": 1}, h.receipt_for_run(run_dir)) + doc = _bound({"x": 1}, run_dir, signer) assert h.verify_handoff({**doc, "signer_role": "openadapt_cloud"}, []).reason == ( "malformed" ) @@ -149,20 +172,23 @@ def test_a_handoff_with_extra_fields_or_another_schema_is_refused(run_dir, signe def test_a_detached_handoff_checks_the_file_beside_it(run_dir, signer, tmp_path): attachment = tmp_path / "claim.pdf" attachment.write_bytes(b"%PDF-1.7 synthetic") - doc = h.make_handoff( + doc = _bound( attachment.read_bytes(), - h.receipt_for_run(run_dir), + run_dir, + signer, name=str(attachment), detached=True, + media_type="application/pdf", ) assert "content" not in doc["payload"] and "content_base64" not in doc["payload"] assert doc["payload"]["name"] == "claim.pdf" good = h.verify_handoff(doc, _registry(signer), payload=attachment.read_bytes()) - assert good.ok and good.payload["present"] is True + assert good.ok and good.payload["bound"] is True bad = h.verify_handoff(doc, _registry(signer), payload=b"another file") assert not bad.ok and bad.reason == "payload_mismatch" missing = h.verify_handoff(doc, _registry(signer)) assert missing.ok and missing.payload["present"] is False + assert missing.payload["bound"] is False def _vector(name: str) -> dict: @@ -184,7 +210,8 @@ def _vector_registry(case: dict) -> list[r.RoleKey]: ) def test_confirmation_lines_come_from_the_shared_verifier(name, independent): case = _vector(name) - doc = h.make_handoff({"outcome": "done"}, case["document"]) + # The vectors' keys aren't ours to bind with, so the payload stays detached. + doc = h.make_handoff(b"claim", case["document"], detached=True) verdict = h.verify_handoff(doc, _vector_registry(case)) assert verdict.ok assert [c["independent"] for c in verdict.confirmations] == [independent] @@ -202,7 +229,7 @@ def test_confirmation_lines_come_from_the_shared_verifier(name, independent): def test_a_tampered_confirmation_is_refused(): case = _vector("confirmation-tampered.json") - doc = h.make_handoff({"outcome": "done"}, case["document"]) + doc = h.make_handoff(b"claim", case["document"], detached=True) assert h.verify_handoff(doc, _vector_registry(case)).reason == "bad_signature" @@ -246,7 +273,7 @@ def test_cli_key_and_trust_pin_the_other_party_by_name(run_dir, signer, tmp_path assert flow_main(args) == 0 registry = r.parse_registry(json.loads(keys.read_text())) assert [(k.role, k.org) for k in registry] == [("customer_key", "Example Clinic")] - doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) + doc = _bound({"outcome": "done"}, run_dir, signer) assert h.verify_handoff(doc, registry).signer_lines == ["Signed by Example Clinic's key"] bad = ["handoff", "trust", str(key), "--org", "x" * 80, "--keys", str(keys)] assert flow_main(bad) == 2 @@ -317,7 +344,7 @@ def own_record(claim): return h.ReceiverRecord("recorded_as_intended") def decision(claim, check=own_record): - return h.decide(h.make_handoff(claim, receipt), registry, check) + return h.decide(h.make_handoff(claim, receipt, signer=signer), registry, check) true = decision({"ref": "ref-1", "note": "note A"}) assert true.decision == "accept" and true.what_this_proves[-1] == h.ACCEPT_LINE @@ -337,7 +364,7 @@ def broken(claim): assert decision({"ref": "ref-1", "note": "note A"}, broken).decision == "reject" # No own read: never accepted on the receipt alone. - unchecked = h.decide(h.make_handoff({"ref": "ref-1"}, receipt), registry) + unchecked = h.decide(h.make_handoff({"ref": "ref-1"}, receipt, signer=signer), registry) assert unchecked.decision == "unchecked" and unchecked.what_this_proves[-1] == h.UNCHECKED_LINE # A refused receipt is rejected before the receiver reads anything. calls = [] @@ -359,3 +386,22 @@ def test_the_handoff_group_is_shared_whichever_module_registers_first(): if not list_first: handoff_group(sub).add_parser("list") assert sorted(handoff_group(sub).choices) == ["key", "list", "send", "trust", "verify"] + + +@pytest.mark.parametrize( + ("name", "reason"), + [ + ("payload-bound.json", None), + ("payload-mismatch.json", "payload_mismatch"), + ("payload-missing.json", "payload_not_bound"), + ], +) +def test_the_shared_payload_vectors_give_the_same_answer_through_a_handoff(name, reason): + case = _vector(name) + received = base64.b64decode(case["received"]) + doc = h.make_handoff(received, case["document"], detached=True) + verdict = h.verify_handoff(doc, _vector_registry(case), payload=received) + assert verdict.reason == reason + assert verdict.signer_lines == case["expected"]["signer_lines"] + if reason is None: + assert verdict.ok and verdict.payload["bound"] is True From 66d93e1c5b60592dcf9ee9fa769be3eaf80ba97a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:49:52 -0500 Subject: [PATCH 10/18] feat(handoff): record sends in the handoff ledger, a real-run evidence file, and a distinct document schema handoff send --ledger DIR --counterparty LABEL [--key-field F] records the send with HandoffLedger (the record handoff list reads), digests only. The wire document is now openadapt.handoff-document/v1, so it no longer shares a schema id with the ledger's openadapt.handoff/v1 record. benchmark/ handoff_real_run holds a real headless MockMed run handed off and checked by its receiver over the CLI. --- .../handoff_real_run/2026-11-21/evidence.json | 77 +++++++++++++ .../flow/benchmark/handoff_real_run/README.md | 38 +++++++ .../handoff_real_run/real_handoff.py | 102 ++++++++++++++++++ packages/flow/docs/A2A.md | 2 +- packages/flow/docs/HANDOFF_RECEIPTS.md | 8 +- .../flow/openadapt_flow/agent/a2a_server.py | 2 +- .../openadapt_flow/agent/handoff_tools.py | 6 +- packages/flow/openadapt_flow/cli_handoff.py | 97 +++++++++++++++++ packages/flow/openadapt_flow/handoff.py | 8 +- packages/flow/tests/test_handoff.py | 23 +++- 10 files changed, 349 insertions(+), 14 deletions(-) create mode 100644 packages/flow/benchmark/handoff_real_run/2026-11-21/evidence.json create mode 100644 packages/flow/benchmark/handoff_real_run/README.md create mode 100644 packages/flow/benchmark/handoff_real_run/real_handoff.py diff --git a/packages/flow/benchmark/handoff_real_run/2026-11-21/evidence.json b/packages/flow/benchmark/handoff_real_run/2026-11-21/evidence.json new file mode 100644 index 0000000000..40c2b71114 --- /dev/null +++ b/packages/flow/benchmark/handoff_real_run/2026-11-21/evidence.json @@ -0,0 +1,77 @@ +{ + "handoffs": { + "differing": { + "decide_ms": 3.7, + "decision": "reject", + "integrity": "intact", + "outcome": "VERIFIED", + "payload_bound": true, + "receiver_check": { + "differing_fields": [ + "key" + ], + "read_method": "api", + "state": "recorded_differently" + }, + "send_exit": 0, + "signer_lines": [ + "Signed by Sender Clinic's key" + ], + "verify_exit": 0 + }, + "fabricated": { + "decide_ms": 2.3, + "decision": "reject", + "integrity": "intact", + "outcome": "VERIFIED", + "payload_bound": true, + "receiver_check": { + "differing_fields": [], + "read_method": "api", + "state": "not_found" + }, + "send_exit": 0, + "signer_lines": [ + "Signed by Sender Clinic's key" + ], + "verify_exit": 0 + }, + "true": { + "decide_ms": 3.34, + "decision": "accept", + "integrity": "intact", + "outcome": "VERIFIED", + "payload_bound": true, + "receiver_check": { + "differing_fields": [], + "read_method": "api", + "state": "recorded_as_intended" + }, + "send_exit": 0, + "signer_lines": [ + "Signed by Sender Clinic's key" + ], + "verify_exit": 0 + } + }, + "record_fields": [ + "id", + "key", + "note", + "patient_id", + "source", + "type" + ], + "run": { + "execution_outcome": "VERIFIED", + "model_calls": 0, + "receipt_written": true, + "transaction_outcome": "VERIFIED" + }, + "run_seconds": 26.2, + "started": "2026-11-21T06:47:19Z", + "swapped_payload": { + "integrity": "refused", + "reason": "payload_mismatch" + } +} \ No newline at end of file diff --git a/packages/flow/benchmark/handoff_real_run/README.md b/packages/flow/benchmark/handoff_real_run/README.md new file mode 100644 index 0000000000..b150d5c251 --- /dev/null +++ b/packages/flow/benchmark/handoff_real_run/README.md @@ -0,0 +1,38 @@ +# A real run, handed off and checked by its receiver + +`real_handoff.py` connects two parties through a real headless browser run: + +- **Party A (sender).** It runs the tutorial program against MockMed in + headless Chromium (`openadapt_flow.tutorial.run_tutorial`). Flow writes the + run's `receipt.json` with its run hook (`receipt_after_run`). A then sends + three claims about the record it entered with `openadapt-flow handoff send`. + Each claim is bound as the receipt's `payload` subject. +- **Party B (receiver).** B owns MockMed's system of record. It pins A's key + with `handoff key` and `handoff trust --org "Sender Clinic"`, then runs + `handoff verify` on each claim. Last, `decide()` reads B's own record + through MockMed's `/api/db`. + +```bash +python real_handoff.py OUT_DIR +``` + +## Result (2026-11-21, `2026-11-21/evidence.json`) + +The run was `VERIFIED`, with 0 model calls, in 26.2 s, and Flow wrote +`receipt.json`. + +| Handoff | `verify` | Signer line | Payload bound | B's own record | `decide` | +|---|---|---|---|---|---| +| True claim | intact | Signed by Sender Clinic's key | yes | `recorded_as_intended` | accept | +| Differing claim, one field changed | intact | Signed by Sender Clinic's key | yes | `recorded_differently` | reject | +| Fabricated claim, no such record | intact | Signed by Sender Clinic's key | yes | `not_found` | reject | +| True handoff with other bytes beside it | refused, `payload_mismatch` | | | | | + +All three claims carry a valid, bound receipt from a trusted sender. Only B's +read of its own record tells the true claim from the false ones. That read +took 2.3 to 3.7 ms per claim. + +**What this is.** One real run on a synthetic app on one computer. Both +parties are local processes with separate seal homes. The claim files hold +MockMed's made-up values. The evidence file lists field names only, never +values. diff --git a/packages/flow/benchmark/handoff_real_run/real_handoff.py b/packages/flow/benchmark/handoff_real_run/real_handoff.py new file mode 100644 index 0000000000..9671a4e203 --- /dev/null +++ b/packages/flow/benchmark/handoff_real_run/real_handoff.py @@ -0,0 +1,102 @@ +"""A real headless MockMed run, then a two-party handoff over the real CLI. + +Party A (sender) runs the tutorial program in a headless browser; Flow writes +receipt.json. A hands claims about the record it entered with +`openadapt-flow handoff send`. Party B (receiver: the MockMed system of +record's owner) pins A's key with `handoff trust`, checks each handoff with +`handoff verify`, then `decide()` reads B's own record (MockMed's /api/db). +""" +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +out = Path(sys.argv[1]) +out.mkdir(parents=True, exist_ok=True) +FLOW = [sys.executable, "-m", "openadapt_flow"] +sender_env = dict(os.environ, OPENADAPT_SEAL_HOME=str(out / "sender-seal")) +receiver_env = dict(os.environ, OPENADAPT_SEAL_HOME=str(out / "receiver-seal")) +os.environ.update(OPENADAPT_SEAL_HOME=str(out / "sender-seal")) + +import openadapt_flow.mockmed.fault_server as fs # noqa: E402 +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow import tutorial # noqa: E402 + +real_serve, held = fs.serve, {} +def serve(*a, **k): + base, db, stop = real_serve(*a, **k) + held.update(base=base, stop=stop) + return base, db, (lambda: None) # keep B's system up for B's own read +fs.serve = serve + +evidence = {"started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} +try: + t0 = time.monotonic() + tutorial.run_tutorial(out / "sender", echo=lambda m: None) + evidence["run_seconds"] = round(time.monotonic() - t0, 1) + run_dir = out / "sender" / "run" + report = json.loads((run_dir / "report.json").read_text()) + evidence["run"] = { + "execution_outcome": report.get("execution_outcome"), + "transaction_outcome": report.get("transaction_outcome"), + "model_calls": report.get("model_calls"), + "receipt_written": (run_dir / "receipt.json").is_file(), + } + records = tutorial._records(held["base"]) + entered = records[-1] + evidence["record_fields"] = sorted(entered) + fields = {k: v for k, v in entered.items() if isinstance(v, str) and k != "id"} + key_field = "id" if "id" in entered else sorted(fields)[0] + first_field = next(k for k in sorted(fields) if k != key_field) + claims = { + "true": {"key": entered.get(key_field), "fields": fields}, + "differing": {"key": entered.get(key_field), "fields": {**fields, first_field: fields[first_field] + " (changed)"}}, + "fabricated": {"key": "no-such-record", "fields": fields}, + } + + # A's key, pinned by B under A's name. + key = subprocess.run(FLOW + ["handoff", "key"], env=sender_env, capture_output=True, text=True, check=True).stdout + (out / "sender-key.json").write_text(key) + subprocess.run(FLOW + ["handoff", "trust", str(out / "sender-key.json"), "--org", "Sender Clinic", "--keys", str(out / "receiver-keys.json")], env=receiver_env, check=True, capture_output=True) + registry = h.load_registry(out / "receiver-keys.json") + + def own_record(claim): + for record in tutorial._records(held["base"]): + if record.get(key_field) == claim["key"]: + differ = tuple(k for k, v in claim["fields"].items() if record.get(k) != v) + return h.ReceiverRecord("recorded_differently", differ) if differ else h.ReceiverRecord("recorded_as_intended") + return h.ReceiverRecord("not_found") + + evidence["handoffs"] = {} + for kind, claim in claims.items(): + path = out / f"claim-{kind}.json" + path.write_text(json.dumps(claim, sort_keys=True)) + doc_path = out / f"claim-{kind}.handoff.json" + send = subprocess.run(FLOW + ["handoff", "send", str(path), "--run", str(run_dir), "--out", str(doc_path), "--media-type", "application/json"], env=sender_env, capture_output=True, text=True) + verify = subprocess.run(FLOW + ["handoff", "verify", str(doc_path), "--keys", str(out / "receiver-keys.json"), "--json"], env=receiver_env, capture_output=True, text=True) + v = json.loads(verify.stdout) + doc = json.loads(doc_path.read_text()) + payload_bytes = path.read_bytes() + started = time.perf_counter() + d = h.decide(doc, registry, own_record, payload=payload_bytes) + evidence["handoffs"][kind] = { + "send_exit": send.returncode, + "verify_exit": verify.returncode, + "integrity": v["integrity"], + "signer_lines": v["signer_lines"], + "payload_bound": v["payload"].get("bound"), + "outcome": v["outcome"], + "decision": d.decision, + "receiver_check": d.receiver_check, + "decide_ms": round((time.perf_counter() - started) * 1000, 2), + } + # A swapped payload: the bound handoff with other bytes beside it. + swap = h.verify_handoff(json.loads((out / "claim-true.handoff.json").read_text()), registry, payload=(out / "claim-differing.json").read_bytes()) + evidence["swapped_payload"] = {"integrity": swap.integrity, "reason": swap.reason} +finally: + if "stop" in held: + held["stop"]() +(out / "evidence.json").write_text(json.dumps(evidence, indent=2, sort_keys=True)) +print(json.dumps(evidence, indent=2, sort_keys=True)) diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md index ea77bb60fa..0201cd1a62 100644 --- a/packages/flow/docs/A2A.md +++ b/packages/flow/docs/A2A.md @@ -24,7 +24,7 @@ openadapt agent serve --bundles ./bundles --mode production --a2a | One skill per workflow | Send a data part `{"skill": NAME, "inputs": {...}, "request_id": ID}`. | | Skill `verify_handoff` | Send another agent's handoff and get the verdict ([HANDOFFS.md](HANDOFFS.md)). | | `capabilities.extensions` | `https://openadapt.ai/extensions/handoff-receipt/v1`, not required ([HANDOFF_RECEIPTS.md](HANDOFF_RECEIPTS.md)). | -| Task artifact `run_result` | The run result (`outcome`, `safe_to_retry` unchanged), plus the `openadapt.handoff/v1` document with the run's signed receipt (`record/run/v1`) when Flow wrote one. Otherwise a text part says why no receipt is attached. | +| Task artifact `run_result` | The run result (`outcome`, `safe_to_retry` unchanged), plus the `openadapt.handoff-document/v1` document with the run's signed receipt (`record/run/v1`) when Flow wrote one. Otherwise a text part says why no receipt is attached. | Only outcome `done` is `TASK_STATE_COMPLETED`. `needs_review` is `TASK_STATE_INPUT_REQUIRED`: a person at this computer decides. A message on diff --git a/packages/flow/docs/HANDOFF_RECEIPTS.md b/packages/flow/docs/HANDOFF_RECEIPTS.md index bb7dcbde52..4acc9e431e 100644 --- a/packages/flow/docs/HANDOFF_RECEIPTS.md +++ b/packages/flow/docs/HANDOFF_RECEIPTS.md @@ -4,7 +4,7 @@ |---|---| | **Identifier** | `https://openadapt.ai/extensions/handoff-receipt/v1` | | **Status** | Draft, version 1. Implemented in OpenAdapt, not submitted to any standards body. | -| **Document schema** | `openadapt.handoff/v1` | +| **Document schema** | `openadapt.handoff-document/v1` | | **Verdict schema** | `openadapt.handoff-verdict/v1` | | **Media type** | `application/vnd.openadapt.handoff+json` | | **Receipt format** | `https://openadapt.ai/record/run/v1`: an in-toto Statement v1 in a DSSE v1.0.2 envelope | @@ -57,7 +57,7 @@ Every verifier MUST tell its user the following, in its own words: ```json { - "schema": "openadapt.handoff/v1", + "schema": "openadapt.handoff-document/v1", "payload": { "media_type": "application/json", "sha256": "<64 hex>", @@ -69,7 +69,7 @@ Every verifier MUST tell its user the following, in its own words: } ``` -- `schema` is required and is exactly `openadapt.handoff/v1`. Other top-level +- `schema` is required and is exactly `openadapt.handoff-document/v1`. Other top-level fields are refused. - `payload.sha256` is required. It covers the exact payload bytes: for `content_base64`, the decoded bytes; for `content` (a JSON value), its @@ -187,7 +187,7 @@ checked. "description": "Task results carry the run's record/run/v1 receipt ...", "required": false, "params": { - "handoff_schema": "openadapt.handoff/v1", + "handoff_schema": "openadapt.handoff-document/v1", "verdict_schema": "openadapt.handoff-verdict/v1", "media_type": "application/vnd.openadapt.handoff+json", "receipt_predicate": "https://openadapt.ai/record/run/v1", diff --git a/packages/flow/openadapt_flow/agent/a2a_server.py b/packages/flow/openadapt_flow/agent/a2a_server.py index 000a2630bf..16f828a270 100644 --- a/packages/flow/openadapt_flow/agent/a2a_server.py +++ b/packages/flow/openadapt_flow/agent/a2a_server.py @@ -16,7 +16,7 @@ (``TASK_STATE_INPUT_REQUIRED``); a message on that task only re-checks the run. Everything else is ``TASK_STATE_FAILED``. The run's own result, with ``outcome`` and ``safe_to_retry`` unchanged, is always an artifact. -* A finished run's receipt travels as an ``openadapt.handoff/v1`` artifact +* A finished run's receipt travels as an ``openadapt.handoff-document/v1`` artifact part (exact bytes, so its digests hold), marked with the handoff-receipt extension URI. * It listens on 127.0.0.1 by default. Any other address needs a bearer token. diff --git a/packages/flow/openadapt_flow/agent/handoff_tools.py b/packages/flow/openadapt_flow/agent/handoff_tools.py index 3219f75258..7ad1f6a567 100644 --- a/packages/flow/openadapt_flow/agent/handoff_tools.py +++ b/packages/flow/openadapt_flow/agent/handoff_tools.py @@ -1,7 +1,7 @@ """Handoff tools for ``openadapt agent serve --handoffs`` (MCP and A2A alike). * ``get_handoff``: a finished run's public result with its receipt attached - (``openadapt.handoff/v1``), ready to pass to another agent. + (``openadapt.handoff-document/v1``), ready to pass to another agent. * ``verify_handoff``: check a handoff another agent sent, against the keys this server pins, and return the verdict (:mod:`openadapt_flow.handoff`). @@ -93,7 +93,7 @@ def list_tool_specs(self, *, runs_enabled: bool) -> list[Any]: ToolSpec( name="verify_handoff", description=( - "Check a handoff another agent sent (an openadapt.handoff/v1 " + "Check a handoff another agent sent (an openadapt.handoff-document/v1 " "document) against the keys this computer pins. Returns who " "signed it, whether it is intact, which checks passed and " "which were not checked, and any confirmation read from the " @@ -105,7 +105,7 @@ def list_tool_specs(self, *, runs_enabled: bool) -> list[Any]: "properties": { "handoff": { "type": "object", - "description": "The openadapt.handoff/v1 document.", + "description": "The openadapt.handoff-document/v1 document.", } }, "required": ["handoff"], diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index 145ecf7283..56c846917b 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -85,6 +85,31 @@ def register(sub: argparse._SubParsersAction) -> None: "or http only to this computer" ), ) + s.add_argument( + "--ledger", + metavar="DIR", + help=( + "also record the handoff in this handoff ledger, so `handoff list` " + "shows it until the other party's system confirms it" + ), + ) + s.add_argument( + "--counterparty", + help="with --ledger: who receives it, for people ('receiving clinic')", + ) + s.add_argument( + "--key-field", + help=( + "with --ledger: the payload's JSON field that identifies the item " + "in the other party's system (default: the payload digest)" + ), + ) + s.add_argument( + "--follow-up-hours", + type=float, + default=72.0, + help="with --ledger: when to follow up if nothing is confirmed (default 72)", + ) s.set_defaults(func=cmd_send) v = hsub.add_parser( @@ -170,6 +195,58 @@ def post_handoff(url: str, document: dict[str, Any], *, timeout: float = 30.0) - return int(response.status) +def record_in_ledger( + directory: Path, + data: bytes, + *, + counterparty: str, + key_field: Optional[str], + follow_up_hours: float, + run_id: Optional[str], +) -> Any: + """Record a sent handoff in the counterparty-confirmation ledger. + + The same record ``handoff list`` reads (:class:`HandoffLedger`): the + item's key and each top-level text field of a JSON payload, as salted + digests only. A payload that isn't a JSON object is recorded by its + digest, with no fields. + """ + import hashlib + + try: + from openadapt_flow.handoffs.ledger import HandoffLedger + except ImportError: + raise ImportError( + "this openadapt-flow has no handoff ledger (openadapt_flow.handoffs)" + ) from None + try: + value = json.loads(data.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + value = None + fields: dict[str, tuple[str, str]] = {} + key = None + if isinstance(value, dict): + if key_field is not None: + key = value.get(key_field) + if not isinstance(key, str) or not key: + raise ValueError(f"the payload has no text field {key_field!r}") + for name, field_value in sorted(value.items()): + if name != key_field and isinstance(field_value, str) and field_value: + fields[name] = (field_value, "text") + elif key_field is not None: + raise ValueError("--key-field needs a JSON object payload") + if key is None: + key = "sha256:" + hashlib.sha256(data).hexdigest() + return HandoffLedger(directory).send( + key, + fields, + counterparty=counterparty, + follow_up_hours=follow_up_hours, + source="agent_handoff", + run_id=run_id, + ) + + def cmd_send(args: argparse.Namespace) -> int: from openadapt_flow import handoff as h @@ -179,6 +256,12 @@ def cmd_send(args: argparse.Namespace) -> int: if args.public and not args.run: print("handoff send: --public goes with --run", file=sys.stderr) return 2 + if args.ledger and not args.counterparty: + print("handoff send: --ledger needs --counterparty", file=sys.stderr) + return 2 + if (args.counterparty or args.key_field) and not args.ledger: + print("handoff send: --counterparty and --key-field go with --ledger", file=sys.stderr) + return 2 try: data = _read(args.payload) if args.run: @@ -207,6 +290,20 @@ def cmd_send(args: argparse.Namespace) -> int: except (OSError, ValueError) as exc: print(f"handoff send: {type(exc).__name__}: {exc}", file=sys.stderr) return 2 + if args.ledger: + try: + entry = record_in_ledger( + Path(args.ledger), + data, + counterparty=args.counterparty, + key_field=args.key_field, + follow_up_hours=args.follow_up_hours, + run_id=Path(args.run).name if args.run else None, + ) + except (ImportError, ValueError) as exc: + print(f"handoff send: not recorded in the ledger: {exc}", file=sys.stderr) + return 2 + print(f"handoff: recorded {entry.id} in {args.ledger}", file=sys.stderr) text = json.dumps(document, indent=2, sort_keys=True) + "\n" out: Optional[Path] = Path(args.out) if args.out else None if out is None and args.detached: diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index 77f34f87c3..f97ab5faf5 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -7,7 +7,7 @@ The same document works over any channel: -* **Inline**: one JSON document (``openadapt.handoff/v1``) holding the payload +* **Inline**: one JSON document (``openadapt.handoff-document/v1``) holding the payload and the receipt. It is the body of an HTTP request or webhook, an MCP tool result, or an A2A artifact part. * **Detached**: the payload stays a file (an email attachment, a shared @@ -41,7 +41,7 @@ from pathlib import Path from typing import Any, Mapping, Optional, Sequence -SCHEMA = "openadapt.handoff/v1" +SCHEMA = "openadapt.handoff-document/v1" VERDICT_SCHEMA = "openadapt.handoff-verdict/v1" MEDIA_TYPE = "application/vnd.openadapt.handoff+json" #: The draft extension URI (docs/HANDOFF_RECEIPTS.md). An identifier only. @@ -112,7 +112,7 @@ def make_handoff( detached: bool = False, signer: Optional[Any] = None, ) -> dict[str, Any]: - """Attach ``receipt`` to ``payload`` as an ``openadapt.handoff/v1`` document. + """Attach ``receipt`` to ``payload`` as an ``openadapt.handoff-document/v1`` document. ``detached`` leaves the payload out and keeps only its digest, for a file sent beside the document. With ``signer`` (the key that signed the run's @@ -418,7 +418,7 @@ def verify_handoff( if not isinstance(document, Mapping) or document.get("schema") != SCHEMA: return _refused( "unknown_schema", - "not an openadapt.handoff/v1 document", + "not an openadapt.handoff-document/v1 document", "Not verified: not a handoff document", ) if set(document) - {"schema", "payload", "receipt"}: diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index fa41e41d2d..cbea01eb6e 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -15,11 +15,12 @@ pytest.importorskip("cryptography") from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_types import receipt as r # noqa: E402 + from openadapt_flow import handoff as h # noqa: E402 from openadapt_flow.__main__ import main as flow_main # noqa: E402 from openadapt_flow.receipt_record import PRIVATE_FILE, write_receipt_record # noqa: E402 from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402 -from openadapt_types import receipt as r # noqa: E402 VECTORS = ( Path(__file__).resolve().parents[2] / "types" / "tests" / "vectors" / "record-run-v1" @@ -405,3 +406,23 @@ def test_the_shared_payload_vectors_give_the_same_answer_through_a_handoff(name, assert verdict.signer_lines == case["expected"]["signer_lines"] if reason is None: assert verdict.ok and verdict.payload["bound"] is True + + +def test_send_records_the_handoff_in_the_ledger_handoff_list_reads(run_dir, signer, tmp_path): + ledger_mod = pytest.importorskip("openadapt_flow.handoffs.ledger") + payload = tmp_path / "referral.json" + payload.write_text(json.dumps({"ref": "ref-77", "note": "Follow-up in 2 weeks", "n": 3})) + ledger = tmp_path / "ledger" + args = ["handoff", "send", str(payload), "--run", str(run_dir), "--out", str(tmp_path / "o.json")] + assert flow_main([*args, "--ledger", str(ledger), "--counterparty", "receiving clinic", + "--key-field", "ref"]) == 0 + (entry,) = ledger_mod.HandoffLedger(ledger).entries() + assert entry.counterparty == "receiving clinic" + assert entry.source == "agent_handoff" and entry.run_id == run_dir.name + assert sorted(entry.fields) == ["note"] # text fields only, as digests + stored = "".join(p.read_text() for p in ledger.rglob("*.json")) + assert "Follow-up" not in stored and "ref-77" not in stored + assert entry.key_digest == ledger_mod.HandoffLedger(ledger).digest("ref-77") + # A key that another open handoff uses is refused, and nothing is sent. + assert flow_main([*args, "--ledger", str(ledger), "--counterparty", "x", "--key-field", "ref"]) == 2 + assert flow_main([*args, "--counterparty", "x"]) == 2 From 833680fd05c515b5278a170238bd14e6505c82ca Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:54:46 -0500 Subject: [PATCH 11/18] docs: ledger and real-run evidence in HANDOFFS.md; TCK rerun on the current card --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../a2a_tck/2026-11-21/compatibility.json | 18 +++++++++--------- .../benchmark/a2a_tck/2026-11-21/tck-run.log | 4 ++-- packages/flow/docs/HANDOFFS.md | 12 ++++++++++++ 5 files changed, 25 insertions(+), 13 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7020202650..ba86f5b18a 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -313,7 +313,7 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | -| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects) | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects); one real headless MockMed run handed off over the CLI and checked against the receiver's own record ([benchmark/handoff_real_run](packages/flow/benchmark/handoff_real_run/README.md)); `--ledger` tested against #2415's `HandoffLedger` | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | | A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | diff --git a/llms-full.txt b/llms-full.txt index 0adbd7462d..c436be3601 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -767,7 +767,7 @@ improvising or retrying when something is off. | Code as action is the default run-1 agent (compile-agent, and `teach_run` in the MCP teach tools): one terminal tool (structure first, actions by role and name, a sandboxed read-only shell, screenshots on request); every action is a structured step checked against the compiled program, and every save the gate detects is read back from the system of record | Released ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | Real app (local OpenEMR) and synthetic | `ClaudeAgent(vision="code")`, `CODE_AS_ACTION.md` ([#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)) | | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md) | -| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects) | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | +| Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects); one real headless MockMed run handed off over the CLI and checked against the receiver's own record ([benchmark/handoff_real_run](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_real_run/README.md)); `--ledger` tested against #2415's `HandoffLedger` | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | | A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | diff --git a/packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json b/packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json index e2d9fe28af..adc41879e1 100644 --- a/packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json +++ b/packages/flow/benchmark/a2a_tck/2026-11-21/compatibility.json @@ -12,7 +12,7 @@ "AUTH-SERVER-001", "BIND-CUSTOM-002" ], - "timestamp": "2026-11-21T06:11:41.629424+00:00", + "timestamp": "2026-11-21T06:51:05.927798+00:00", "sut_url": "http://localhost:9999", "spec_version": "", "overall_compatibility": "75.0%", @@ -1631,7 +1631,7 @@ }, "agent_card": { "name": "OpenAdapt", - "description": "Runs compiled OpenAdapt workflows on this computer and checks that they saved. Every run's result carries its signed receipt, and any agent can send a handoff to be verified.", + "description": "Runs compiled OpenAdapt workflows on this computer and checks that they saved. A finished run's result carries its signed receipt when Flow wrote one, and any agent can send a handoff to be verified.", "supportedInterfaces": [ { "url": "http://127.0.0.1:9999/a2a/jsonrpc", @@ -1656,13 +1656,13 @@ "extensions": [ { "uri": "https://openadapt.ai/extensions/handoff-receipt/v1", - "description": "Task results carry the run's record/run/v1 receipt (in-toto Statement in a DSSE envelope) as an openadapt.handoff/v1 artifact part; verify_handoff returns an openadapt.handoff-verdict/v1 verdict.", + "description": "Task results carry the run's record/run/v1 receipt (in-toto Statement in a DSSE envelope) as an openadapt.handoff-document/v1 artifact part; verify_handoff returns an openadapt.handoff-verdict/v1 verdict.", "params": { - "handoff_schema": "openadapt.handoff/v1", - "envelope": "dsse", - "media_type": "application/vnd.openadapt.handoff+json", + "receipt_predicate": "https://openadapt.ai/record/run/v1", "verdict_schema": "openadapt.handoff-verdict/v1", - "receipt_predicate": "https://openadapt.ai/record/run/v1" + "media_type": "application/vnd.openadapt.handoff+json", + "handoff_schema": "openadapt.handoff-document/v1", + "envelope": "dsse" } } ], @@ -1679,7 +1679,7 @@ { "id": "add_triage_note", "name": "add_triage_note", - "description": "Sandbox: add a triage note to the first referral in a synthetic clinic app. Nothing real changes. Done means: The note is in the synthetic app's record store, confirmed by reading the store directly after the save. Send a data part {\"skill\": \"add_triage_note\", \"inputs\": {...}, \"request_id\": \"...\"}. The result includes the run's signed receipt.", + "description": "Sandbox: add a triage note to the first referral in a synthetic clinic app. Nothing real changes. Done means: The note is in the synthetic app's record store, confirmed by reading the store directly after the save. Send a data part {\"skill\": \"add_triage_note\", \"inputs\": {...}, \"request_id\": \"...\"}. A finished run's result includes its signed receipt when Flow wrote one.", "tags": [ "openadapt", "workflow", @@ -1696,7 +1696,7 @@ { "id": "verify_handoff", "name": "Verify a handoff", - "description": "Send another agent's result with its receipt (an openadapt.handoff/v1 document, as a data part or a application/vnd.openadapt.handoff+json file part). Returns who signed it, whether it is intact, which checks passed and which were not checked, and any confirmation read from the other party's system. A valid signature proves who signed, not that the claim is true.", + "description": "Send another agent's result with its receipt (an openadapt.handoff-document/v1 document, as a data part or a application/vnd.openadapt.handoff+json file part). Returns who signed it, whether it is intact, which checks passed and which were not checked, and any confirmation read from the other party's system. A valid signature proves who signed, not that the claim is true.", "tags": [ "verification", "receipt", diff --git a/packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log b/packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log index 446fb9bf84..92fdfeed77 100644 --- a/packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log +++ b/packages/flow/benchmark/a2a_tck/2026-11-21/tck-run.log @@ -10,7 +10,7 @@ ssssssssssssssssssssssssss..s..s..s..s..s..s..s..s..s..s..s..s..s..s..s. [ 54%] A2A TCK Compatibility Report ═══════════════════════════════════════════════════════ SUT: http://localhost:9999 -Timestamp: 2026-11-21T06:11:41.629424+00:00 +Timestamp: 2026-11-21T06:51:05.927798+00:00 OVERALL COMPATIBILITY: 75.0% (automated checks) @@ -137,7 +137,7 @@ FAILED tests/compatibility/core_operations/test_artifacts.py::TestDataArtifact:: FAILED tests/compatibility/core_operations/test_artifacts.py::TestMessageResponse::test_returns_message_with_text_part[jsonrpc] FAILED tests/compatibility/core_operations/test_artifacts.py::TestMessageResponse::test_returns_message_with_text_part[http_json] FAILED tests/compatibility/http_json/test_problem_details.py::TestHttpJsonErrorMediaType::test_error_content_type -11 failed, 110 passed, 142 skipped in 1.00s +11 failed, 110 passed, 142 skipped in 1.48s Command: SCRATCH/tck-src/a2a-tck/.venv314/bin/python -m pytest tests/compatibility/ --sut-host=http://localhost:9999 --tb=short --media-type-spec-version=1.0.1 -q --compatibility-report=reports/compatibility --html=reports/tck_report.html --self-contained-html --junitxml=reports/junitreport.xml tck exit 1 diff --git a/packages/flow/docs/HANDOFFS.md b/packages/flow/docs/HANDOFFS.md index a1e36f3223..45b9beedf5 100644 --- a/packages/flow/docs/HANDOFFS.md +++ b/packages/flow/docs/HANDOFFS.md @@ -72,6 +72,11 @@ it. It rejects when your read fails. Without a read it never accepts. - **The pass bar.** The second party must accept no false handoff, reject no true one, and spend at most 2 s checking each. +[benchmark/handoff_real_run](../benchmark/handoff_real_run/README.md) does +the same with a real headless browser run against MockMed. It uses the real +CLI for `send`, `key`, `trust` and `verify`, and the receiver reads its own +record store. + ## Trusting another party's key Each party pins the keys it trusts. Nothing in a handoff can make a key @@ -102,8 +107,15 @@ openadapt handoff send result.json --run ~/.openadapt/runs/run-123 --post https: # On arrival, against the keys you pin openadapt handoff verify result.handoff.json --keys trusted-keys.json + +# Also record it, so `openadapt handoff list` follows it until the other side confirms +openadapt handoff send referral.json --run RUN_DIR --out referral.handoff.json \ + --ledger ~/.openadapt/handoffs --counterparty "receiving clinic" --key-field ref ``` +`--ledger` records the key and the text fields of the payload. It stores +them as salted digests, never as values. + `verify` exits 0 when the receipt is intact and 1 when it is refused. Add `--json` to get the verdict as data. `receipt.private.json` never leaves the computer: `send` refuses to attach it. From 791f6bfe112df0e234e73d9d9ff78148e6559a64 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:06:44 -0500 Subject: [PATCH 12/18] fix(handoff): bind only a receipt this key verifiably signed; POST without redirects bind_payload now checks this computer's DSSE signature over the envelope's payload before re-signing, so a keyid with a bad sig never becomes a valid receipt. post_handoff refuses every redirect (a 3xx raises), so an allowed URL can't hand the document to a target _post_allowed would refuse. Tests for both; ruff format for the touched files. --- packages/flow/openadapt_flow/cli_handoff.py | 59 ++++-- packages/flow/openadapt_flow/handoff.py | 40 +++- packages/flow/tests/test_handoff.py | 198 +++++++++++++++++--- 3 files changed, 260 insertions(+), 37 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index 56c846917b..04361ab06b 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -52,8 +52,12 @@ def register(sub: argparse._SubParsersAction) -> None: ) s.add_argument("payload", help="the file to hand off ('-' reads stdin)") source = s.add_mutually_exclusive_group(required=True) - source.add_argument("--run", metavar="RUN_DIR", help="the run whose receipt.json to attach") - source.add_argument("--receipt", metavar="FILE", help="a receipt.json or receipt.card.json") + source.add_argument( + "--run", metavar="RUN_DIR", help="the run whose receipt.json to attach" + ) + source.add_argument( + "--receipt", metavar="FILE", help="a receipt.json or receipt.card.json" + ) s.add_argument( "--public", action="store_true", @@ -179,6 +183,11 @@ def _post_allowed(url: str) -> bool: return False +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001 + return None + + def post_handoff(url: str, document: dict[str, Any], *, timeout: float = 30.0) -> int: """POST a handoff document as its own media type. Returns the HTTP status.""" from openadapt_flow.handoff import MEDIA_TYPE @@ -191,7 +200,10 @@ def post_handoff(url: str, document: dict[str, Any], *, timeout: float = 30.0) - headers={"Content-Type": MEDIA_TYPE}, method="POST", ) - with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 - scheme checked + # No redirects: an allowed URL must not hand the document on to a target + # _post_allowed would refuse. A 3xx raises HTTPError (an OSError). + opener = urllib.request.build_opener(_NoRedirect) + with opener.open(request, timeout=timeout) as response: # noqa: S310 - scheme checked return int(response.status) @@ -260,7 +272,10 @@ def cmd_send(args: argparse.Namespace) -> int: print("handoff send: --ledger needs --counterparty", file=sys.stderr) return 2 if (args.counterparty or args.key_field) and not args.ledger: - print("handoff send: --counterparty and --key-field go with --ledger", file=sys.stderr) + print( + "handoff send: --counterparty and --key-field go with --ledger", + file=sys.stderr, + ) return 2 try: data = _read(args.payload) @@ -285,7 +300,9 @@ def cmd_send(args: argparse.Namespace) -> int: print(f"handoff send: {exc}", file=sys.stderr) return 2 except RuntimeError as exc: - print(f"handoff send: no receipt key to bind the payload ({exc})", file=sys.stderr) + print( + f"handoff send: no receipt key to bind the payload ({exc})", file=sys.stderr + ) return 2 except (OSError, ValueError) as exc: print(f"handoff send: {type(exc).__name__}: {exc}", file=sys.stderr) @@ -359,7 +376,10 @@ def cmd_verify(args: argparse.Namespace) -> int: payload = beside.read_bytes() registry = h.load_registry(Path(args.keys) if args.keys else None) except RegistryError as exc: - print(f"handoff verify: the key registry is refused ({exc.reason})", file=sys.stderr) + print( + f"handoff verify: the key registry is refused ({exc.reason})", + file=sys.stderr, + ) return 2 except (OSError, ValueError) as exc: print(f"handoff verify: {type(exc).__name__}: {exc}", file=sys.stderr) @@ -380,7 +400,11 @@ def cmd_key(args: argparse.Namespace) -> int: except Exception as exc: # noqa: BLE001 - no usable key: say so, sign nothing print(f"handoff key: no receipt key on this computer ({exc})", file=sys.stderr) return 2 - print(json.dumps({"key_id": entry["key_id"], "public_key": entry["public_key"]}, indent=2)) + print( + json.dumps( + {"key_id": entry["key_id"], "public_key": entry["public_key"]}, indent=2 + ) + ) return 0 @@ -401,9 +425,17 @@ def cmd_trust(args: argparse.Namespace) -> int: if path.is_file() else {"schema": r.REGISTRY_SCHEMA, "keys": []} ) - if not isinstance(entry, dict) or set(entry) - {"key_id", "public_key", "status"}: + if not isinstance(entry, dict) or set(entry) - { + "key_id", + "public_key", + "status", + }: raise ValueError("the key file is one `handoff key` entry") - keys = [k for k in registry.get("keys", []) if k.get("key_id") != entry.get("key_id")] + keys = [ + k + for k in registry.get("keys", []) + if k.get("key_id") != entry.get("key_id") + ] keys.append( { "key_id": entry.get("key_id"), @@ -421,6 +453,11 @@ def cmd_trust(args: argparse.Namespace) -> int: except (OSError, ValueError) as exc: print(f"handoff trust: {type(exc).__name__}: {exc}", file=sys.stderr) return 2 - path.write_text(json.dumps(updated, indent=2, sort_keys=True) + "\n", encoding="utf-8") - print(f"handoff: {args.org}'s key {entry['key_id']} is trusted in {path}", file=sys.stderr) + path.write_text( + json.dumps(updated, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print( + f"handoff: {args.org}'s key {entry['key_id']} is trusted in {path}", + file=sys.stderr, + ) return 0 diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index f97ab5faf5..ccff0e6783 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -157,6 +157,35 @@ def _subject_media_type(media_type: str) -> str: return essence if essence in allowed else "application/octet-stream" +def _signed_by(envelope: Mapping[str, Any], kid: str, public_raw: bytes) -> bool: + """True when ``envelope`` carries a valid DSSE signature by ``kid``.""" + from cryptography.exceptions import InvalidSignature + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + from openadapt_types import receipt as r + + if ( + not isinstance(envelope, Mapping) + or envelope.get("payloadType") != r.PAYLOAD_TYPE + ): + return False + try: + signed = r.pae( + r.PAYLOAD_TYPE, base64.b64decode(str(envelope["payload"]), validate=True) + ) + key = Ed25519PublicKey.from_public_bytes(public_raw) + except (KeyError, ValueError): + return False + for sig in envelope.get("signatures") or []: + if not isinstance(sig, Mapping) or sig.get("keyid") != kid: + continue + try: + key.verify(base64.b64decode(str(sig.get("sig")), validate=True), signed) + return True + except (InvalidSignature, ValueError): + return False + return False + + def bind_payload( receipt: Mapping[str, Any], data: bytes, media_type: str, signer: Any ) -> dict[str, Any]: @@ -172,7 +201,9 @@ def bind_payload( receipt = _check_receipt_document(receipt) envelope = receipt["envelope"] if r.is_receipt_card(receipt) else receipt kid = r.key_id(signer.public_raw()) - if kid not in {s.get("keyid") for s in envelope.get("signatures") or []}: + # Verify this computer's own signature before re-signing: a keyid with a + # bad sig must never turn into a valid receipt. + if not _signed_by(envelope, kid, signer.public_raw()): raise HandoffError( "this computer's key didn't sign that receipt, so it can't bind a " "payload to it" @@ -474,7 +505,12 @@ def verify_handoff( # -- the receiver's own record ------------------------------------------------------ #: States a receiver's own read can return, as in a counterparty confirmation. -RECEIVER_STATES = ("recorded_as_intended", "recorded_differently", "not_found", "unreadable") +RECEIVER_STATES = ( + "recorded_as_intended", + "recorded_differently", + "not_found", + "unreadable", +) ACCEPT_LINE = ( "Accepted: your own system shows the record the handoff describes. That " diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index cbea01eb6e..567b4c4d72 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -23,7 +23,11 @@ from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402 VECTORS = ( - Path(__file__).resolve().parents[2] / "types" / "tests" / "vectors" / "record-run-v1" + Path(__file__).resolve().parents[2] + / "types" + / "tests" + / "vectors" + / "record-run-v1" ) REPORT = { @@ -33,7 +37,12 @@ "started_at": "2026-11-21T01:02:03Z", "results": [ {"step_id": "s1", "ok": True}, - {"step_id": "s2", "ok": True, "effect_verified": True, "postconditions_ok": True}, + { + "step_id": "s2", + "ok": True, + "effect_verified": True, + "postconditions_ok": True, + }, ], } @@ -107,6 +116,57 @@ def test_binding_keeps_the_signer_and_names_the_payload(run_dir, signer): h.make_handoff({"x": 1}, original, signer=_signer()) +def test_binding_refuses_this_keyid_with_a_bad_signature(run_dir, signer): + """A crafted envelope naming this computer's keyid never gets re-signed.""" + original = h.receipt_for_run(run_dir) + statement = json.loads(base64.b64decode(original["payload"])) + statement["predicate"]["model_calls"] = 99 + forged_payload = base64.b64encode(r.canonical_json(statement).encode()).decode() + kid = original["signatures"][0]["keyid"] + for sig in ["AAAA", original["signatures"][0]["sig"]]: + forged = dict( + original, payload=forged_payload, signatures=[{"keyid": kid, "sig": sig}] + ) + with pytest.raises(h.HandoffError, match="didn't sign that receipt"): + h.make_handoff({"x": 1}, forged, signer=signer) + + +def test_a_post_is_never_redirected(monkeypatch): + import urllib.error + from http.server import BaseHTTPRequestHandler, HTTPServer + from threading import Thread + + from openadapt_flow.cli_handoff import post_handoff + + followed = [] + + class Redirect(BaseHTTPRequestHandler): + def do_POST(self): # noqa: N802 + # 302 is the code urllib would follow (as a GET) by default. + self.send_response(302) + self.send_header("Location", "/elsewhere") + self.end_headers() + + def do_GET(self): # noqa: N802 + followed.append(self.path) + self.send_response(200) + self.end_headers() + + def log_message(self, *args): + pass + + server = HTTPServer(("127.0.0.1", 0), Redirect) + Thread(target=server.serve_forever, daemon=True).start() + try: + with pytest.raises(urllib.error.HTTPError) as caught: + post_handoff(f"http://127.0.0.1:{server.server_address[1]}/inbox", {"a": 1}) + assert caught.value.code == 302 + assert followed == [] + finally: + server.shutdown() + server.server_close() + + def test_an_unbound_receipt_is_refused_once_the_payload_is_checked(run_dir, signer): """Missing: a receipt that names no payload doesn't vouch for this one.""" doc = h.make_handoff({"outcome": "done"}, h.receipt_for_run(run_dir)) @@ -166,7 +226,9 @@ def test_a_handoff_with_extra_fields_or_another_schema_is_refused(run_dir, signe assert h.verify_handoff({**doc, "signer_role": "openadapt_cloud"}, []).reason == ( "malformed" ) - assert h.verify_handoff({**doc, "schema": "other/v1"}, []).reason == "unknown_schema" + assert ( + h.verify_handoff({**doc, "schema": "other/v1"}, []).reason == "unknown_schema" + ) assert h.verify_handoff(b"not json", []).reason == "malformed" @@ -223,9 +285,14 @@ def test_confirmation_lines_come_from_the_shared_verifier(name, independent): assert verdict.signer_lines == ["Signed by this computer"] if independent: assert verdict.independent_confirmations == 1 - assert any("read back from the other party" in line for line in verdict.what_this_proves) + assert any( + "read back from the other party" in line + for line in verdict.what_this_proves + ) else: - assert any("rests on the signer's word" in line for line in verdict.what_this_proves) + assert any( + "rests on the signer's word" in line for line in verdict.what_this_proves + ) def test_a_tampered_confirmation_is_refused(): @@ -247,12 +314,26 @@ def test_cli_send_and_verify_inline_and_detached(run_dir, signer, tmp_path, caps payload = tmp_path / "result.json" payload.write_text('{"outcome": "done"}') out = tmp_path / "result.handoff.json" - assert flow_main(["handoff", "send", str(payload), "--run", str(run_dir), "--out", str(out)]) == 0 - assert flow_main(["handoff", "verify", str(out), "--keys", str(keys), "--json"]) == 0 + assert ( + flow_main( + ["handoff", "send", str(payload), "--run", str(run_dir), "--out", str(out)] + ) + == 0 + ) + assert ( + flow_main(["handoff", "verify", str(out), "--keys", str(keys), "--json"]) == 0 + ) verdict = json.loads(capsys.readouterr().out) - assert verdict["integrity"] == "intact" and verdict["signer_roles"] == ["this_computer"] + assert verdict["integrity"] == "intact" and verdict["signer_roles"] == [ + "this_computer" + ] - assert flow_main(["handoff", "send", str(payload), "--run", str(run_dir), "--detached"]) == 0 + assert ( + flow_main( + ["handoff", "send", str(payload), "--run", str(run_dir), "--detached"] + ) + == 0 + ) detached = h.detached_path(payload) assert detached.is_file() assert flow_main(["handoff", "verify", str(detached), "--keys", str(keys)]) == 0 @@ -266,16 +347,30 @@ def test_cli_send_and_verify_inline_and_detached(run_dir, signer, tmp_path, caps assert flow_main(["handoff", "verify", str(out), "--keys", str(other)]) == 1 -def test_cli_key_and_trust_pin_the_other_party_by_name(run_dir, signer, tmp_path, capsys): +def test_cli_key_and_trust_pin_the_other_party_by_name( + run_dir, signer, tmp_path, capsys +): key = tmp_path / "sender-key.json" - key.write_text(json.dumps({k: v for k, v in signer.registry_entry().items() if k != "status"})) + key.write_text( + json.dumps({k: v for k, v in signer.registry_entry().items() if k != "status"}) + ) keys = tmp_path / "trusted.json" - args = ["handoff", "trust", str(key), "--org", "Example Clinic", "--keys", str(keys)] + args = [ + "handoff", + "trust", + str(key), + "--org", + "Example Clinic", + "--keys", + str(keys), + ] assert flow_main(args) == 0 registry = r.parse_registry(json.loads(keys.read_text())) assert [(k.role, k.org) for k in registry] == [("customer_key", "Example Clinic")] doc = _bound({"outcome": "done"}, run_dir, signer) - assert h.verify_handoff(doc, registry).signer_lines == ["Signed by Example Clinic's key"] + assert h.verify_handoff(doc, registry).signer_lines == [ + "Signed by Example Clinic's key" + ] bad = ["handoff", "trust", str(key), "--org", "x" * 80, "--keys", str(keys)] assert flow_main(bad) == 2 key.write_text('{"key_id": "seal-ed25519-0000000000000000", "public_key": "AAAA"}') @@ -322,7 +417,12 @@ def do_POST(self): payload = tmp_path / "p.json" payload.write_text('{"outcome": "done"}') url = f"http://127.0.0.1:{server.server_address[1]}/inbox" - assert flow_main(["handoff", "send", str(payload), "--run", str(run_dir), "--post", url]) == 0 + assert ( + flow_main( + ["handoff", "send", str(payload), "--run", str(run_dir), "--post", url] + ) + == 0 + ) finally: server.shutdown() content_type, body = received[0] @@ -365,8 +465,13 @@ def broken(claim): assert decision({"ref": "ref-1", "note": "note A"}, broken).decision == "reject" # No own read: never accepted on the receipt alone. - unchecked = h.decide(h.make_handoff({"ref": "ref-1"}, receipt, signer=signer), registry) - assert unchecked.decision == "unchecked" and unchecked.what_this_proves[-1] == h.UNCHECKED_LINE + unchecked = h.decide( + h.make_handoff({"ref": "ref-1"}, receipt, signer=signer), registry + ) + assert ( + unchecked.decision == "unchecked" + and unchecked.what_this_proves[-1] == h.UNCHECKED_LINE + ) # A refused receipt is rejected before the receiver reads anything. calls = [] refused = h.decide(h.make_handoff({"ref": "ref-1"}, receipt), [], calls.append) @@ -386,7 +491,13 @@ def test_the_handoff_group_is_shared_whichever_module_registers_first(): register(sub) if not list_first: handoff_group(sub).add_parser("list") - assert sorted(handoff_group(sub).choices) == ["key", "list", "send", "trust", "verify"] + assert sorted(handoff_group(sub).choices) == [ + "key", + "list", + "send", + "trust", + "verify", + ] @pytest.mark.parametrize( @@ -397,7 +508,9 @@ def test_the_handoff_group_is_shared_whichever_module_registers_first(): ("payload-missing.json", "payload_not_bound"), ], ) -def test_the_shared_payload_vectors_give_the_same_answer_through_a_handoff(name, reason): +def test_the_shared_payload_vectors_give_the_same_answer_through_a_handoff( + name, reason +): case = _vector(name) received = base64.b64decode(case["received"]) doc = h.make_handoff(received, case["document"], detached=True) @@ -408,14 +521,38 @@ def test_the_shared_payload_vectors_give_the_same_answer_through_a_handoff(name, assert verdict.ok and verdict.payload["bound"] is True -def test_send_records_the_handoff_in_the_ledger_handoff_list_reads(run_dir, signer, tmp_path): +def test_send_records_the_handoff_in_the_ledger_handoff_list_reads( + run_dir, signer, tmp_path +): ledger_mod = pytest.importorskip("openadapt_flow.handoffs.ledger") payload = tmp_path / "referral.json" - payload.write_text(json.dumps({"ref": "ref-77", "note": "Follow-up in 2 weeks", "n": 3})) + payload.write_text( + json.dumps({"ref": "ref-77", "note": "Follow-up in 2 weeks", "n": 3}) + ) ledger = tmp_path / "ledger" - args = ["handoff", "send", str(payload), "--run", str(run_dir), "--out", str(tmp_path / "o.json")] - assert flow_main([*args, "--ledger", str(ledger), "--counterparty", "receiving clinic", - "--key-field", "ref"]) == 0 + args = [ + "handoff", + "send", + str(payload), + "--run", + str(run_dir), + "--out", + str(tmp_path / "o.json"), + ] + assert ( + flow_main( + [ + *args, + "--ledger", + str(ledger), + "--counterparty", + "receiving clinic", + "--key-field", + "ref", + ] + ) + == 0 + ) (entry,) = ledger_mod.HandoffLedger(ledger).entries() assert entry.counterparty == "receiving clinic" assert entry.source == "agent_handoff" and entry.run_id == run_dir.name @@ -424,5 +561,18 @@ def test_send_records_the_handoff_in_the_ledger_handoff_list_reads(run_dir, sign assert "Follow-up" not in stored and "ref-77" not in stored assert entry.key_digest == ledger_mod.HandoffLedger(ledger).digest("ref-77") # A key that another open handoff uses is refused, and nothing is sent. - assert flow_main([*args, "--ledger", str(ledger), "--counterparty", "x", "--key-field", "ref"]) == 2 + assert ( + flow_main( + [ + *args, + "--ledger", + str(ledger), + "--counterparty", + "x", + "--key-field", + "ref", + ] + ) + == 2 + ) assert flow_main([*args, "--counterparty", "x"]) == 2 From 2eb7e8dd6b8ae41faed11e49a1bb19259940394c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:12:05 -0500 Subject: [PATCH 13/18] fix(handoff): check the claim from the bytes the signature bound A handoff carries its payload as content or content_base64, never both, and bytes supplied out of band must equal an inline copy. decide() derives the claim it hands the receiver from those same checked bytes. --- packages/flow/openadapt_flow/handoff.py | 35 +++++++++++++++-------- packages/flow/tests/test_handoff.py | 38 +++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 12 deletions(-) diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index ccff0e6783..1e19f3b1e6 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -386,17 +386,28 @@ def _confirmations(statement: Mapping[str, Any], result: Any) -> list[dict[str, def _received_bytes( doc_payload: Mapping[str, Any], supplied: Optional[bytes] ) -> tuple[Optional[bytes], Optional[str]]: - """The payload bytes the receiver has, checked against the handoff's digest.""" - data: Optional[bytes] = None - if supplied is not None: - data = supplied - elif "content_base64" in doc_payload: + """The payload bytes the receiver has, checked against the handoff's digest. + + One representation only: ``content`` or ``content_base64``, never both, + and bytes supplied out of band must equal an inline copy. Everything the + receiver checks is derived from the bytes returned here. + """ + inline = [k for k in ("content", "content_base64") if k in doc_payload] + if len(inline) > 1: + return None, "the handoff carries its payload two ways" + inline_data: Optional[bytes] = None + if "content_base64" in doc_payload: try: - data = base64.b64decode(str(doc_payload["content_base64"]), validate=True) + inline_data = base64.b64decode( + str(doc_payload["content_base64"]), validate=True + ) except ValueError: return None, "the inline payload is not base64" elif "content" in doc_payload: - data = _canonical(doc_payload["content"]) + inline_data = _canonical(doc_payload["content"]) + if supplied is not None and inline_data is not None and supplied != inline_data: + return None, "the supplied payload differs from the one in the handoff" + data = supplied if supplied is not None else inline_data if data is not None and _sha256(data) != doc_payload.get("sha256"): return None, "the payload does not match its digest in the handoff" return data, None @@ -538,14 +549,14 @@ def __post_init__(self) -> None: def _payload_value(document: Mapping[str, Any], supplied: Optional[bytes]) -> Any: + """The claim to check, from the same bytes the signature check bound.""" doc_payload = document.get("payload") or {} + data, problem = _received_bytes(doc_payload, supplied) + if problem is not None or data is None: + raise HandoffError(problem or "the payload is not available to check") if "content" in doc_payload: + # _received_bytes checked the digest over this content's canonical form. return doc_payload["content"] - data = supplied - if data is None and "content_base64" in doc_payload: - data = base64.b64decode(str(doc_payload["content_base64"]), validate=True) - if data is None: - raise HandoffError("the payload is not available to check") try: return json.loads(data.decode("utf-8")) except (UnicodeDecodeError, ValueError): diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index 567b4c4d72..d48f12aaf5 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -478,6 +478,44 @@ def broken(claim): assert refused.decision == "reject" and calls == [] +def test_the_checked_claim_is_always_the_signed_bytes(run_dir, signer): + """A second payload copy, inline or supplied, never reaches the receiver.""" + registry = _registry(signer) + receipt = h.receipt_for_run(run_dir) + seen = [] + + def check(claim): + seen.append(claim) + return h.ReceiverRecord("recorded_as_intended") + + signed = {"ref": "ref-1", "note": "note A"} + forged = {"ref": "ref-1", "note": "unsigned note"} + doc = h.make_handoff(signed, receipt, signer=signer) + assert "content" in doc["payload"] + both = json.loads(json.dumps(doc)) + both["payload"]["content_base64"] = base64.b64encode( + json.dumps(signed, sort_keys=True, separators=(",", ":")).encode() + ).decode() + both["payload"]["content"] = forged + assert h.decide(both, registry, check).decision == "reject" + as_bytes = h.make_handoff( + json.dumps(signed).encode(), + receipt, + signer=signer, + media_type="application/json", + ) + assert "content_base64" in as_bytes["payload"] + two = json.loads(json.dumps(as_bytes)) + two["payload"]["content"] = forged + assert h.decide(two, registry, check).decision == "reject" + # Supplied bytes must equal the inline copy. + other = json.dumps(forged).encode() + assert h.decide(doc, registry, check, payload=other).decision == "reject" + assert seen == [] + assert h.decide(as_bytes, registry, check).decision == "accept" + assert seen == [signed] + + def test_the_handoff_group_is_shared_whichever_module_registers_first(): import argparse From 71cea82eacf3c68ba56411e1c15400e791582ba3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:37:54 -0500 Subject: [PATCH 14/18] fix(handoff): a public card leaves only if it matches its receipt Unbound-evidence class: before either sender mode attaches a card, its shape, disclosure version and every opening are checked against the receipt's signed commitments. --- packages/flow/openadapt_flow/handoff.py | 30 +++++++++++++++++++++++++ packages/flow/tests/test_handoff.py | 18 +++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index 1e19f3b1e6..f9018244ee 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -89,9 +89,39 @@ def _check_receipt_document(receipt: Any) -> dict[str, Any]: ) if not (r.is_receipt_envelope(receipt) or r.is_receipt_card(receipt)): raise HandoffError("the receipt is a record/run/v1 envelope or card") + if r.is_receipt_card(receipt): + _check_card(receipt) return dict(receipt) +def _check_card(card: Mapping[str, Any]) -> None: + """Unbound-evidence class: a card leaves this computer only if its shape, + disclosure version and every opening match what the receipt committed.""" + from openadapt_types import receipt as r + + if set(card) != {"schema", "disclosure_version", "envelope", "openings"}: + raise HandoffError("a receipt card has exactly four fields") + allowed = r.PUBLIC_DISCLOSURE.get(str(card.get("disclosure_version"))) + openings = card.get("openings") + envelope = card.get("envelope") + if allowed is None or not isinstance(openings, Mapping): + raise HandoffError("the receipt card's disclosure is not a known version") + if not (isinstance(envelope, Mapping) and r.is_receipt_envelope(envelope)): + raise HandoffError("the receipt card holds no record/run/v1 envelope") + try: + statement = r.loads_strict( + base64.b64decode(str(envelope["payload"]), validate=True) + ) + commitments = statement["predicate"]["disclosure"]["commitments"] + except (KeyError, TypeError, ValueError): + raise HandoffError("the receipt card's statement is not readable") from None + checked = r._check_openings(openings, commitments, allowed) + if isinstance(checked, r.ReceiptVerification): + raise HandoffError( + f"the receipt card doesn't match its receipt: {checked.reason}" + ) + + def payload_bytes(payload: Any) -> tuple[bytes, str]: """The exact bytes a payload's digest covers, and their media type. diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index d48f12aaf5..fc63f9063c 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -131,6 +131,24 @@ def test_binding_refuses_this_keyid_with_a_bad_signature(run_dir, signer): h.make_handoff({"x": 1}, forged, signer=signer) +def test_a_card_that_does_not_match_its_receipt_never_leaves(run_dir, signer): + receipt = h.receipt_for_run(run_dir) + statement = json.loads(base64.b64decode(receipt["payload"])) + commitments = statement["predicate"]["disclosure"]["commitments"] + assert "flow_version" in commitments + private = json.loads((run_dir / PRIVATE_FILE).read_text()) + good = r.public_card(receipt, private["openings"], reveal=["flow_version"]) + h.make_handoff({"x": 1}, good) # a matching card travels + bad_value = json.loads(json.dumps(good)) + bad_value["openings"]["flow_version"]["value"] = "9.9.9" + extra_field = {**good, "note": "x"} + unknown_version = {**good, "disclosure_version": "openadapt.public-disclosure/v0"} + for card in (bad_value, extra_field, unknown_version): + for kwargs in ({}, {"signer": signer}): # unbound and bound senders + with pytest.raises(h.HandoffError): + h.make_handoff({"x": 1}, card, **kwargs) + + def test_a_post_is_never_redirected(monkeypatch): import urllib.error from http.server import BaseHTTPRequestHandler, HTTPServer From 5aab4aba1658fff66686681adce117760803b9d4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:49:32 -0500 Subject: [PATCH 15/18] fix(handoff): only an exactly shaped, signed DSSE envelope leaves the sender Unbound-evidence class, round 4: the envelope (bare, or inside a card) must have exactly payloadType, payload and signatures, the record/run/v1 payload type and a nonempty list of well-formed signatures before either sender mode attaches it. --- packages/flow/openadapt_flow/handoff.py | 33 +++++++++++++++++++++++++ packages/flow/tests/test_handoff.py | 15 ++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index f9018244ee..4191be4811 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -91,9 +91,41 @@ def _check_receipt_document(receipt: Any) -> dict[str, Any]: raise HandoffError("the receipt is a record/run/v1 envelope or card") if r.is_receipt_card(receipt): _check_card(receipt) + else: + _check_envelope(receipt) return dict(receipt) +def _check_envelope(envelope: Any) -> None: + """Unbound-evidence class: only an exactly shaped, signed DSSE envelope + leaves the sender; the receiver authenticates the signer itself.""" + from openadapt_types import receipt as r + + if not isinstance(envelope, Mapping) or set(envelope) != { + "payloadType", + "payload", + "signatures", + }: + raise HandoffError( + "the receipt envelope has exactly payloadType, payload, signatures" + ) + if envelope.get("payloadType") != r.PAYLOAD_TYPE: + raise HandoffError("the receipt envelope is not a record/run/v1 statement") + signatures = envelope.get("signatures") + if ( + not isinstance(signatures, list) + or not signatures + or not all( + isinstance(sig, Mapping) + and set(sig) == {"keyid", "sig"} + and isinstance(sig.get("keyid"), str) + and isinstance(sig.get("sig"), str) + for sig in signatures + ) + ): + raise HandoffError("the receipt envelope carries no well-formed signature") + + def _check_card(card: Mapping[str, Any]) -> None: """Unbound-evidence class: a card leaves this computer only if its shape, disclosure version and every opening match what the receipt committed.""" @@ -108,6 +140,7 @@ def _check_card(card: Mapping[str, Any]) -> None: raise HandoffError("the receipt card's disclosure is not a known version") if not (isinstance(envelope, Mapping) and r.is_receipt_envelope(envelope)): raise HandoffError("the receipt card holds no record/run/v1 envelope") + _check_envelope(envelope) try: statement = r.loads_strict( base64.b64decode(str(envelope["payload"]), validate=True) diff --git a/packages/flow/tests/test_handoff.py b/packages/flow/tests/test_handoff.py index fc63f9063c..319ebad68d 100644 --- a/packages/flow/tests/test_handoff.py +++ b/packages/flow/tests/test_handoff.py @@ -143,10 +143,23 @@ def test_a_card_that_does_not_match_its_receipt_never_leaves(run_dir, signer): bad_value["openings"]["flow_version"]["value"] = "9.9.9" extra_field = {**good, "note": "x"} unknown_version = {**good, "disclosure_version": "openadapt.public-disclosure/v0"} - for card in (bad_value, extra_field, unknown_version): + extra_envelope = json.loads(json.dumps(good)) + extra_envelope["envelope"]["note"] = "unsigned" + no_signatures = json.loads(json.dumps(good)) + no_signatures["envelope"]["signatures"] = [] + for card in ( + bad_value, + extra_field, + unknown_version, + extra_envelope, + no_signatures, + ): for kwargs in ({}, {"signer": signer}): # unbound and bound senders with pytest.raises(h.HandoffError): h.make_handoff({"x": 1}, card, **kwargs) + # A bare envelope is held to the same shape before it leaves. + with pytest.raises(h.HandoffError): + h.make_handoff({"x": 1}, {**receipt, "note": "unsigned"}) def test_a_post_is_never_redirected(monkeypatch): From bb1a3090362fcd7b720a8e572002e437f54a7e8e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:24:35 -0500 Subject: [PATCH 16/18] fix(release,lint): update public-artifacts.json and ruff lint/format on flow files --- .../flow/openadapt_flow/agent/a2a_server.py | 21 +++++++++++++------ packages/flow/openadapt_flow/agent/bridge.py | 4 +++- .../openadapt_flow/agent/contract_call.py | 3 ++- .../flow/openadapt_flow/receipt_record.py | 18 ++++++++++------ packages/flow/public-artifacts.json | 2 ++ 5 files changed, 34 insertions(+), 14 deletions(-) diff --git a/packages/flow/openadapt_flow/agent/a2a_server.py b/packages/flow/openadapt_flow/agent/a2a_server.py index 16f828a270..b5a5bb6c47 100644 --- a/packages/flow/openadapt_flow/agent/a2a_server.py +++ b/packages/flow/openadapt_flow/agent/a2a_server.py @@ -135,9 +135,9 @@ def _skills(bridge: AgentBridge, *, include_workflows: bool) -> list[Any]: description.strip() or "A compiled OpenAdapt workflow on this computer." ) - + " Send a data part {\"skill\": \"" + + ' Send a data part {"skill": "' + name - + "\", \"inputs\": {...}, \"request_id\": \"...\"}. A " + + '", "inputs": {...}, "request_id": "..."}. A ' "finished run's result includes its signed receipt when Flow " "wrote one.", tags=["openadapt", "workflow", "receipt"], @@ -285,7 +285,9 @@ def parse_request(message: Any) -> tuple[str, dict[str, Any]]: raise BridgeError("the handoff file part is not JSON") from None return VERIFY_SKILL, {"handoff": document} data = [ - _integral(MessageToDict(part.data)) for part in message.parts if part.HasField("data") + _integral(MessageToDict(part.data)) + for part in message.parts + if part.HasField("data") ] if len(data) != 1 or not isinstance(data[0], dict): raise BridgeError( @@ -408,7 +410,9 @@ def say(text: str) -> Any: ) waited += _POLL_SECONDS parts = [new_data_part(result, media_type="application/json")] - if result.get("outcome") not in (None, "running") and isinstance(run_id, str): + if result.get("outcome") not in (None, "running") and isinstance( + run_id, str + ): try: handoff = await self._call("get_handoff", {"run_id": run_id}) except BridgeError as exc: @@ -476,7 +480,10 @@ async def __call__(self, scope: Any, receive: Any, send: Any) -> None: if scope["type"] != "http": await self.app(scope, receive, send) return - headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope["headers"]} + headers = { + k.decode("latin-1").lower(): v.decode("latin-1") + for k, v in scope["headers"] + } problem = None if headers.get("host") not in self.hosts: problem = (421, "this server does not answer for that host") @@ -547,7 +554,9 @@ def build_app(bridge: AgentBridge, config: A2AConfig) -> Any: ) routes = [ # The card changes only when the server restarts with other bundles. - *create_agent_card_routes(agent_card=card, cache_control="private, max-age=300"), + *create_agent_card_routes( + agent_card=card, cache_control="private, max-age=300" + ), *create_jsonrpc_routes(request_handler=handler, rpc_url=JSONRPC_PATH), # Clients that join "/" to the interface URL post here. *create_jsonrpc_routes(request_handler=handler, rpc_url=JSONRPC_PATH + "/"), diff --git a/packages/flow/openadapt_flow/agent/bridge.py b/packages/flow/openadapt_flow/agent/bridge.py index c54bdec93d..e84f0b11c8 100644 --- a/packages/flow/openadapt_flow/agent/bridge.py +++ b/packages/flow/openadapt_flow/agent/bridge.py @@ -803,7 +803,9 @@ def _handoff_dispatch(self, name: str, arguments: dict) -> dict: return self.handoffs.get( arguments.get("run_id", ""), public=bool(arguments.get("public", False)), - result_for=lambda run_id: self.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0}), + result_for=lambda run_id: self.dispatch( + "get_run", {"run_id": run_id, "wait_seconds": 0} + ), run_dir_for=self._safe_run_dir, ) diff --git a/packages/flow/openadapt_flow/agent/contract_call.py b/packages/flow/openadapt_flow/agent/contract_call.py index a7884c9bc6..5e30d58f95 100644 --- a/packages/flow/openadapt_flow/agent/contract_call.py +++ b/packages/flow/openadapt_flow/agent/contract_call.py @@ -43,7 +43,8 @@ def validate_arguments(spec: Any, arguments: Optional[Mapping[str, Any]]) -> Non except ValidationError: # ValidationError text contains input values, so never return it. raise BridgeError( - getattr(spec, "usage", None) or "tool arguments do not match the input schema" + getattr(spec, "usage", None) + or "tool arguments do not match the input schema" ) from None diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index e732fe2a67..fd889594fa 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -28,9 +28,10 @@ from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence if TYPE_CHECKING: - from openadapt_flow.seal_keys import SealSigner from openadapt_types.receipt import ReceiptVerification, RoleKey + from openadapt_flow.seal_keys import SealSigner + RECEIPT_FILE = "receipt.json" PRIVATE_FILE = "receipt.private.json" CARD_FILE = "receipt.card.json" @@ -155,9 +156,10 @@ def build_statement( salt: Any = None, ) -> tuple[dict[str, Any], dict[str, dict[str, str]]]: """The ``record/run/v1`` statement for a run report, and its private openings.""" - from openadapt_flow.public_seal import _checks, _hour, _int from openadapt_types import receipt as r + from openadapt_flow.public_seal import _checks, _hour, _int + results = report.get("results") results = ( [x for x in results if isinstance(x, Mapping)] @@ -281,9 +283,10 @@ def write_receipt_record( Idempotent: an existing receipt over the same report bytes is kept. A receipt over different bytes is never silently replaced. """ + from openadapt_types import receipt as r + from openadapt_flow.offline_seal import loads_strict, signer_for from openadapt_flow.seal_keys import KeyUnavailable - from openadapt_types import receipt as r run_dir = Path(run_dir) report_path = run_dir / "report.json" @@ -385,9 +388,10 @@ def local_registry( Demo keys are never trusted by default. """ - from openadapt_flow.offline_seal import public_key_entry, seal_home, signer_for from openadapt_types.receipt import RoleKey + from openadapt_flow.offline_seal import public_key_entry, seal_home, signer_for + keys: list[RoleKey] = list(extra) try: home = home or seal_home(env) @@ -438,9 +442,10 @@ def _pinned_cloud_keys(home: Optional[Path]) -> list["RoleKey"]: def load_role_registry(path: Path) -> list["RoleKey"]: - from openadapt_flow.offline_seal import loads_strict from openadapt_types.receipt import parse_registry + from openadapt_flow.offline_seal import loads_strict + return parse_registry(loads_strict(Path(path).read_text(encoding="utf-8"))) @@ -448,9 +453,10 @@ def verify_run_receipt( run_dir: Path, registry: Sequence["RoleKey"] ) -> "ReceiptVerification": """Verify ``run_dir/receipt.json`` and check it covers the run's report bytes.""" - from openadapt_flow.offline_seal import loads_strict from openadapt_types import receipt as r + from openadapt_flow.offline_seal import loads_strict + run_dir = Path(run_dir) try: envelope = loads_strict((run_dir / RECEIPT_FILE).read_text(encoding="utf-8")) diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index e61429e282..85328d2a92 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -96,6 +96,7 @@ ".github/workflows/release.yml", ".github/workflows/validate-claims.yml", ".pre-commit-config.yaml", + "benchmark/a2a_tck/2026-11-21/compatibility.json", "benchmark/agent_guard/results.json", "benchmark/ap_invoice/results.json", "benchmark/api_generalization/recordings/dolibarr_contact/mode.json", @@ -788,6 +789,7 @@ "benchmark/grounding_eval/results.json", "benchmark/grounding_eval/results_sweep.json", "benchmark/halt_cleanup/results/openemr.json", + "benchmark/handoff_real_run/2026-11-21/evidence.json", "benchmark/harness2_scorer/evidence/base/results.json", "benchmark/harness2_scorer/evidence/harness2/results.json", "benchmark/harness2_scorer/evidence/harness2_readback/results.json", From 3c11b2f0f07d555d557f33938a223443397563ca Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 15:45:30 -0500 Subject: [PATCH 17/18] fix(typing): narrow registry keys entries in cli_handoff.py --- packages/flow/openadapt_flow/cli_handoff.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index 04361ab06b..44465f4cd8 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -431,10 +431,15 @@ def cmd_trust(args: argparse.Namespace) -> int: "status", }: raise ValueError("the key file is one `handoff key` entry") - keys = [ + if not isinstance(registry, dict): + raise ValueError("the keys file must be a JSON object") + raw_keys = registry.get("keys", []) + if not isinstance(raw_keys, list): + raise ValueError("the keys file 'keys' field must be a list") + keys: list[Any] = [ k - for k in registry.get("keys", []) - if k.get("key_id") != entry.get("key_id") + for k in raw_keys + if not isinstance(k, dict) or k.get("key_id") != entry.get("key_id") ] keys.append( { From 2e93a0dd91e7aca000f119a5d5e7b8c5935f29c1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:52:28 -0500 Subject: [PATCH 18/18] chore(deps): relock the eligibility connector for flow's a2a extra --- packages/connectors/eligibility/uv.lock | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/connectors/eligibility/uv.lock b/packages/connectors/eligibility/uv.lock index fe73fee1d1..992746e55e 100644 --- a/packages/connectors/eligibility/uv.lock +++ b/packages/connectors/eligibility/uv.lock @@ -495,6 +495,7 @@ dependencies = [ [package.metadata] requires-dist = [ + { name = "a2a-sdk", extras = ["http-server"], marker = "extra == 'a2a'", specifier = ">=1.3.1,<2" }, { name = "aardwolf", marker = "extra == 'rdp'", specifier = "==0.2.14" }, { name = "anthropic", marker = "extra == 'dev'", specifier = ">=0.40" }, { name = "anthropic", marker = "extra == 'grounder'", specifier = ">=0.40" }, @@ -534,6 +535,7 @@ requires-dist = [ { name = "numpy", marker = "extra == 'vision'", specifier = ">=1.26" }, { name = "onnxruntime", marker = "extra == 'local-grounding'", specifier = ">=1.17" }, { name = "openadapt-capture", marker = "extra == 'capture'", specifier = ">=1.2.0" }, + { name = "openadapt-flow", extras = ["agent"], marker = "extra == 'a2a'" }, { name = "openadapt-flow", extras = ["vision"], marker = "extra == 'browser'" }, { name = "openadapt-flow", extras = ["vision"], marker = "extra == 'capture'" }, { name = "openadapt-flow", extras = ["vision"], marker = "extra == 'linux'" }, @@ -582,6 +584,7 @@ requires-dist = [ { name = "transformers", marker = "extra == 'service-mlx'", specifier = ">=5.14,<5.18" }, { name = "uiautomation", marker = "sys_platform == 'win32' and extra == 'dev'", specifier = ">=2.0.20" }, { name = "uvicorn", marker = "python_full_version >= '3.11' and extra == 'openenv'", specifier = ">=0.29" }, + { name = "uvicorn", marker = "extra == 'a2a'", specifier = ">=0.29" }, { name = "uvicorn", marker = "extra == 'console'", specifier = ">=0.29" }, { name = "uvicorn", marker = "extra == 'dev'", specifier = ">=0.29" }, { name = "uvicorn", marker = "extra == 'execute'", specifier = ">=0.29" }, @@ -596,7 +599,7 @@ requires-dist = [ { name = "winrt-windows-media-ocr", marker = "sys_platform == 'win32' and extra == 'native-ocr'", specifier = ">=2.0" }, { name = "winrt-windows-storage-streams", marker = "sys_platform == 'win32' and extra == 'native-ocr'", specifier = ">=2.0" }, ] -provides-extras = ["vision", "native-ocr", "browser", "dev", "grounder", "grounding", "local-grounding", "console", "countersign", "receipts", "keychain", "pkcs11", "execute", "windows", "connector-windows", "reward", "openenv", "macos", "linux", "rdp", "registry", "privacy", "hosted", "service", "service-mlx", "capture", "interop", "agent", "claude-agent-sdk", "openai-agents", "langgraph"] +provides-extras = ["vision", "native-ocr", "browser", "dev", "grounder", "grounding", "local-grounding", "console", "countersign", "receipts", "keychain", "pkcs11", "execute", "windows", "connector-windows", "reward", "openenv", "macos", "linux", "rdp", "registry", "privacy", "hosted", "service", "service-mlx", "capture", "interop", "agent", "a2a", "claude-agent-sdk", "openai-agents", "langgraph"] [[package]] name = "openadapt-types"