diff --git a/CAPABILITIES.md b/CAPABILITIES.md index f679bf283b..12daba4123 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -314,6 +314,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, 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) | | 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) | @@ -447,6 +449,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`: 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/CHANGELOG.md b/CHANGELOG.md index 0f2363a264..5533ef8e34 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 7a386e6177..d645a431fd 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,25 @@ receipt. The hooks are advisory; see [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: @@ -323,6 +342,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/llms-full.txt b/llms-full.txt index 333173dddf..f9c86e0182 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -187,6 +187,25 @@ receipt. The hooks are advisory; see [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: @@ -333,6 +352,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. @@ -754,6 +774,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, 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) | | 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) | @@ -887,6 +909,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`: 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:** @@ -2395,6 +2418,32 @@ 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. `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 + (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/openadapt/cli.py b/openadapt/cli.py index db751e0c6c..a376c76158 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -2155,6 +2155,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 86eb1bc08b..298ac8056b 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -86,6 +86,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/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/pyproject.toml b/packages/agent/pyproject.toml index 4c5dabb538..325a5f510e 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..d0bffb73b3 --- /dev/null +++ b/packages/agent/tests/test_handoff_e2e.py @@ -0,0 +1,548 @@ +"""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 hashlib +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), signer=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)} + ) + # 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) + + 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 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" + # 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), signer=other) + + 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), signer=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_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()} + 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)") + # 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): + 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") + + # 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() + reasons: dict[str, set] = {kind: set() for kind in ("true", "fabricated", "differing", "swapped", "unbound")} + 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)) + reasons[kind].add(verdict.reason) + if verdict.ok: + signer_lines.add(tuple(verdict.signer_lines)) + 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"], _result_from(task)["run_id"])) + return out + + try: + receipts = asyncio.run(runs()) + 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": + 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}} + 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() + + 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 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][0], signer=signer), registry) + assert unchecked.ok and unchecked.decision == "unchecked" 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/agent/uv.lock b/packages/agent/uv.lock index 2bb40fed10..974fd2c843 100644 --- a/packages/agent/uv.lock +++ b/packages/agent/uv.lock @@ -22,6 +22,45 @@ constraints = [ { name = "pillow", marker = "python_full_version >= '3.11'", specifier = ">=13.0.0" }, ] +[[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" @@ -508,6 +547,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" @@ -667,6 +719,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" @@ -843,6 +937,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" @@ -1325,6 +1428,10 @@ dependencies = [ ] [package.optional-dependencies] +a2a = [ + { name = "a2a-sdk", extra = ["http-server"] }, + { name = "uvicorn" }, +] dev = [ { name = "build" }, { name = "pytest" }, @@ -1339,6 +1446,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" }, @@ -1349,8 +1457,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" @@ -1701,6 +1810,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5c/8e/ce3d95562d8166801ba95af98193e80c0c41ffea1c7727e03d26b35d2321/presidio_image_redactor-0.0.62-py3-none-any.whl", hash = "sha256:24d05df588fe5a020c0f7ccd7e063b2f385781dc85275a64c850c2ff4af5b93a", size = 34261, upload-time = "2026-10-27T09:06:54.261Z" }, ] +[[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" @@ -1716,6 +1837,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" @@ -2430,6 +2572,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/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" diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index d5a15df702..41d170e183 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -19,6 +19,32 @@ ### 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. `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 + (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/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..adc41879e1 --- /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:51:05.927798+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. 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", + "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-document/v1 artifact part; verify_handoff returns an openadapt.handoff-verdict/v1 verdict.", + "params": { + "receipt_predicate": "https://openadapt.ai/record/run/v1", + "verdict_schema": "openadapt.handoff-verdict/v1", + "media_type": "application/vnd.openadapt.handoff+json", + "handoff_schema": "openadapt.handoff-document/v1", + "envelope": "dsse" + } + } + ], + "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\": \"...\"}. A finished run's result includes its signed receipt when Flow wrote one.", + "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-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", + "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..92fdfeed77 --- /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:51:05.927798+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.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/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/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 new file mode 100644 index 0000000000..0201cd1a62 --- /dev/null +++ b/packages/flow/docs/A2A.md @@ -0,0 +1,100 @@ +# 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-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 +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 +(`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`, +`--teach-browser` and `--allow-protected-export` 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. + +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/docs/HANDOFFS.md b/packages/flow/docs/HANDOFFS.md new file mode 100644 index 0000000000..45b9beedf5 --- /dev/null +++ b/packages/flow/docs/HANDOFFS.md @@ -0,0 +1,154 @@ +# 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. + +`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 + +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. + +[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 +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 +# 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 + +# 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 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..4acc9e431e --- /dev/null +++ b/packages/flow/docs/HANDOFF_RECEIPTS.md @@ -0,0 +1,264 @@ +# 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-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 | +| **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 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. + +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-document/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-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 + 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 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 + +```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": 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, + "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-document/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..af830da10d --- /dev/null +++ b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md @@ -0,0 +1 @@ +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/agent/a2a_server.py b/packages/flow/openadapt_flow/agent/a2a_server.py new file mode 100644 index 0000000000..b5a5bb6c47 --- /dev/null +++ b/packages/flow/openadapt_flow/agent/a2a_server.py @@ -0,0 +1,597 @@ +"""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-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. + 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__) + +#: 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" +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 = DEFAULT_HOST + 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": "..."}. 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], + ) + ) + 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. 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__, + 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, + # Refuse a part whose stated media type no skill takes + # (ContentTypeNotSupportedError), as the spec requires. + validate_input_modes=True, + ) + 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_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) + 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 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, + 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..e84f0b11c8 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,20 @@ 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..3fb9cbfaac 100644 --- a/packages/flow/openadapt_flow/agent/cli.py +++ b/packages/flow/openadapt_flow/agent/cli.py @@ -610,6 +610,57 @@ 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=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( + "--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 +835,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 or a2a_server.DEFAULT_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 +1571,32 @@ 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 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 + + 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..5e30d58f95 --- /dev/null +++ b/packages/flow/openadapt_flow/agent/contract_call.py @@ -0,0 +1,95 @@ +"""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..7ad1f6a567 --- /dev/null +++ b/packages/flow/openadapt_flow/agent/handoff_tools.py @@ -0,0 +1,151 @@ +"""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-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`). + +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, + 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: + 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-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 " + "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-document/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", 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/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..44465f4cd8 --- /dev/null +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -0,0 +1,468 @@ +"""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 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: + hsub = handoff_group(sub) + + 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( + "--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", + metavar="URL", + help=( + "POST the handoff to this URL (a webhook or agent inbox). https, " + "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( + "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) + + 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 == "-": + 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 + + +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 + + 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", + ) + # 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) + + +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 + + 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 + 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: + 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 + 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: + 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 + + +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") + 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 raw_keys + if not isinstance(k, dict) or 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/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 diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index cb075b91ae..a0bac30176 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -85,6 +85,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 new file mode 100644 index 0000000000..4191be4811 --- /dev/null +++ b/packages/flow/openadapt_flow/handoff.py @@ -0,0 +1,721 @@ +"""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-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 + 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 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. + +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-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. +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 + +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." +) + + +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") + 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.""" + 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") + _check_envelope(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. + + ``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, + signer: Optional[Any] = None, +) -> dict[str, Any]: + """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 + 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), + "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 _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 _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]: + """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()) + # 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" + ) + 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 + + 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) + #: 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: + 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), + "receiver_check": self.receiver_check, + "decision": self.decision, + } + + +def _refused(reason: str, detail: str = "", line: Optional[str] = None) -> Verdict: + from openadapt_types.receipt import refusal_line + + return Verdict( + integrity="refused", + decision="reject", + 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], result: Any) -> list[dict[str, Any]]: + """Each counterparty confirmation, with the verifier's own independence flag. + + :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 index, item in enumerate(items): + out.append( + { + "for_step": item.get("for_step"), + "system_kind": item.get("system_kind"), + "state": item.get("state"), + "read_method": item.get("read_method"), + "strength": item.get("strength"), + "differing_count": item.get("differing_count"), + # 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 _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. + + 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: + 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: + 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 + + +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": doc_payload.get("sha256"), + "present": data is not None, + "bound": data is not None, + "media_type": (bound or {}).get("media_type"), + } + if data is not None: + result["note"] = ( + "The receipt's signer bound these exact payload bytes: they are what " + "the sender handed off." + ) + else: + result["note"] = ( + "The payload was not supplied, so it could not be checked against " + "the receipt." + ) + return result + + +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-document/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") + 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 = _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"]) + 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, + ) + + +# -- 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: + """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"] + 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: + 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", + "MEDIA_TYPE", + "SCHEMA", + "VERDICT_SCHEMA", + "RECEIVER_STATES", + "ReceiverRecord", + "Verdict", + "bind_payload", + "decide", + "detached_path", + "load_registry", + "make_handoff", + "payload_bytes", + "receipt_for_run", + "verify_handoff", +] diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index 02cf811f77..c05454d48a 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", @@ -793,6 +794,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", diff --git a/packages/flow/pyproject.toml b/packages/flow/pyproject.toml index b4d9a64959..e9e80fdf2d 100644 --- a/packages/flow/pyproject.toml +++ b/packages/flow/pyproject.toml @@ -19,6 +19,16 @@ keywords = [ "desktop", "citrix", "rdp", + "gui", + "automation", + "workflow", + "verification", + "a2a", + "agent2agent", + "agent-card", + "agent-handoff", + "in-toto", + "dsse", ] license = { text = "MIT" } # rapidocr-onnxruntime is part of the validated identity/OCR path and does not @@ -323,6 +333,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..613005b8c4 --- /dev/null +++ b/packages/flow/tests/test_handoff.py @@ -0,0 +1,660 @@ +"""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_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 + +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", + "change_ledger": [], + "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, + "effect_contract_hashes": ["sha256:" + "a" * 64], + "effect_evidence": [ + { + "effect_contract_hash": "sha256:" + "a" * 64, + "substrate": "api", + "initial_verdict": "confirmed", + "final_verdict": "confirmed", + "observed_effect": "present", + "verification_tier": 1, + } + ], + }, + ], +} + + +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(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() +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 _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 = _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"] + 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 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_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_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_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"} + 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): + 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)) + verdict = h.verify_handoff(doc, _registry(signer)) + assert not verdict.ok and verdict.reason == "payload_not_bound" + + +def test_a_tampered_receipt_is_refused(run_dir, signer): + doc = _bound({"outcome": "done"}, run_dir, signer) + statement = json.loads(base64.b64decode(doc["receipt"]["payload"])) + 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, 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_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 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 not verdict.ok and verdict.reason == "payload_mismatch" + + +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 = _bound({"x": 1}, run_dir, signer) + 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 = _bound( + attachment.read_bytes(), + 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["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: + 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) + # 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] + # 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(b"claim", case["document"], detached=True) + 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_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 = _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 + 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("{}") + 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, 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 + 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, 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) + 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 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", + ] + + +@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 + + +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 diff --git a/packages/flow/uv.lock b/packages/flow/uv.lock index c264d27eaf..a45c92df59 100644 --- a/packages/flow/uv.lock +++ b/packages/flow/uv.lock @@ -24,6 +24,31 @@ constraints = [ { name = "pillow", marker = "python_full_version >= '3.11'", specifier = ">=13.0.0" }, ] +[[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" @@ -55,6 +80,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" @@ -835,6 +874,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" @@ -1139,6 +1191,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.32.0" @@ -1735,6 +1829,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" @@ -2669,6 +2772,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" }, @@ -2864,6 +2975,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" }, @@ -2903,6 +3015,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'" }, @@ -2951,6 +3064,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" }, @@ -2965,7 +3079,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" @@ -3558,6 +3672,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5c/8e/ce3d95562d8166801ba95af98193e80c0c41ffea1c7727e03d26b35d2321/presidio_image_redactor-0.0.62-py3-none-any.whl", hash = "sha256:24d05df588fe5a020c0f7ccd7e063b2f385781dc85275a64c850c2ff4af5b93a", size = 34261, upload-time = "2026-10-27T09:06:54.261Z" }, ] +[[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" @@ -3614,6 +3740,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 4e76660ddf..c94a17552d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,12 @@ keywords = [ "citrix", "emr", "data-entry", + "mcp", + "a2a", + "agent2agent", + "agent-card", + "agent-handoff", + "receipts", ] classifiers = [ "Intended Audience :: Developers", @@ -142,6 +148,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 187d203613..d3b54a112c 100644 --- a/uv.lock +++ b/uv.lock @@ -26,6 +26,31 @@ constraints = [ { name = "pillow", marker = "python_full_version >= '3.11'", specifier = ">=13.0.0" }, ] +[[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" @@ -233,6 +258,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2b/27/5e1f8446545be98e9416af59c396b1ed1f9f3294afb0a40ee3a709889273/aiohttp-3.14.4-py3-none-any.whl", hash = "sha256:5c6758ba62aea282c537179cfc8474a90f2b5f7b089cc5ff66d8920d86a9bfdd", size = 279487, upload-time = "2026-10-05T17:43:44.905Z" }, ] +[[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" @@ -1193,6 +1232,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" @@ -2211,6 +2263,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" @@ -3317,6 +3378,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'" }, ] @@ -3387,6 +3452,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'" }, @@ -3413,8 +3479,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"