@agent-custody/receipts 0.6.18 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,15 +4,15 @@ Chain of custody for AI agents: a signed receipt for every tool call, checkable
4
4
 
5
5
  Two producers, one receipt format, one verifier.
6
6
 
7
- - **The gateway** is an MCP proxy between an agent and the systems it can affect. For every tool call, allowed or denied, it checks a delegation grant signed by the human principal, gathers the facts the policy needs by calling upstream itself, evaluates a Cedar policy that fails closed, forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
8
- - **The SDK** is an interceptor inside the agent's own process, hooked into the framework's tool-call callbacks: Claude Code, the Claude Agent SDK, the OpenAI Agents SDK, the Vercel AI SDK, OpenClaw, DeepSeek Harness, Hermes, LangChain, or any function you wrap. It reaches everything the gateway cannot see and issues the same receipts, labelled as self-reported.
7
+ - **The gateway** is an MCP proxy between an agent and the systems it can affect: MCP servers, REST APIs described as tools, and other agents it delegates to over A2A. For every tool call, allowed or denied, it checks a delegation grant signed by the human principal, gathers the facts the policy needs by calling upstream itself, evaluates a Cedar policy that fails closed, forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
8
+ - **The SDK** is an interceptor inside the agent's own process, hooked into the framework's tool-call callbacks: Claude Code, the Claude Agent SDK, the OpenAI Agents SDK, the Vercel AI SDK, OpenClaw, DeepSeek Harness, Hermes, Google ADK, LangChain, or any function you wrap. It reaches everything the gateway cannot see and issues the same receipts, labelled as self-reported.
9
9
 
10
- Anyone holding the public keys can verify a receipt offline. The agent is not trusted. The layer around it is, and the receipt says exactly how far that trust extends, starting with who issued it.
10
+ Anyone holding the public keys can verify a receipt offline. The agent is not trusted. The layer around it is, and the receipt says exactly how far that trust extends, starting with who issued it. What the receipt file carries of a call is a choice per tool: a field can be withheld as a commitment or encrypted under your key, and the verifier recomputes the digests when it is shown the values.
11
11
 
12
12
  - [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
13
- - [Tutorials](docs/tutorials.md): twenty runnable examples, one per aspect of the code, all executed by the test suite
14
- - [Usage guide](docs/usage.md): gateway setup, wiring into Claude Desktop, Claude Code, or your own agent loop
15
- - [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK, LangChain, OpenClaw and DeepSeek Harness, a Hermes Agent plugin through the Python package, and wrapping tool functions in anything else
13
+ - [Tutorials](docs/tutorials.md): twenty-seven runnable examples, one per aspect of the code, all executed by the test suite
14
+ - [Usage guide](docs/usage.md): gateway setup, wiring into Claude Desktop, Claude Code, or your own agent loop, and the gateway as an A2A agent between agents that delegate to each other, and private evidence: what the receipt file carries of each call
15
+ - [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK, LangChain, OpenClaw and DeepSeek Harness, a Hermes Agent plugin and Google ADK callbacks through the Python package, and wrapping tool functions in anything else
16
16
  - [Writing policies](docs/policies.md): how a tool call becomes a Cedar request, with tested examples
17
17
  - [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
18
18
  - [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, the EU AI Act, and UK GDPR, with what none of them claims
@@ -47,7 +47,7 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
47
47
  verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
48
48
  ```
49
49
 
50
- Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness and Hermes, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx agent-custody gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md). The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
50
+ Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes and Google ADK, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx agent-custody gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md); between an agent and the agents it delegates to over A2A, `--a2a` serves the gateway as an A2A agent itself. The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
51
51
 
52
52
  ## How it fits together
53
53
 
@@ -110,11 +110,13 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
110
110
  | OpenClaw | SDK | `registerOpenClaw` / `openclawHooks`: `before_tool_call` deny | `after_tool_call` | OpenClaw's documented hook contract, in the plugin's process |
111
111
  | DeepSeek Harness | SDK | the module is the plugin: `tools/pre-execute` deny | `tools/post-execute` | the harness's tool waterfall types, driven as the harness drives them |
112
112
  | Hermes Agent | sidecar + [Python package](../python/README.md) | `agent_custody.hermes`: `pre_tool_call` block | `post_tool_call` | the documented hook contract, against a live sidecar |
113
+ | Google ADK | sidecar + [Python package](../python/README.md) | `adk_callbacks`: `before_tool_callback` skips | `after_tool_callback` | the real package, ADK's runner with a scripted model |
113
114
  | anything else | SDK | `issuer.wrap(name, fn)` | `issuer.record` | plain functions |
114
115
  | Python: LangChain, OpenAI Agents SDK, CrewAI, Claude Agent SDK | sidecar + [Python package](../python/README.md) | `wrap_tools` (OpenAI Agents, CrewAI), `claude_hook` PreToolUse deny, `client.wrap` | `ReceiptCallbackHandler` | the real Python packages, receipts checked by this verifier |
115
116
  | Go, Java, Rust, any language with HTTP | sidecar | decide then record | record | [examples/languages](examples/languages), each run against a live sidecar |
116
117
  | any MCP host in any language: Claude Agent SDK Python, OpenAI Agents Python | gateway | yes | | the gateway is an MCP server; [usage.md](docs/usage.md#python-hosts) |
117
118
  | any REST API, as tools the agent reaches through the gateway | gateway, `rest` upstream | yes | | a stand-in HTTP API; [usage.md](docs/usage.md#setup-step-by-step) |
119
+ | any agent reached over A2A (Google ADK `RemoteA2aAgent`, or any A2A client) | gateway, `a2a` upstream and `gateway --a2a` | yes | | stand-in A2A agents in both wire formats; ADK's own `to_a2a` and `RemoteA2aAgent` in the Python suite; [usage.md](docs/usage.md#the-gateway-as-an-a2a-agent) |
118
120
 
119
121
  The framework packages are optional peer dependencies. Each adapter imports only from its own package.
120
122
 
@@ -179,7 +181,7 @@ Every field carries a provenance label. This is the design decision that matters
179
181
  bun install # from the repository root, once for the workspace
180
182
  cd packages/receipts
181
183
  node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
182
- node examples/01-keys-and-signing.ts # first of eighteen step-by-step examples, see docs/tutorials.md
184
+ node examples/01-keys-and-signing.ts # first of twenty-seven step-by-step examples, see docs/tutorials.md
183
185
  bun run test # this package; `bun run test` at the root runs every package
184
186
  ```
185
187
 
@@ -252,15 +254,17 @@ src/sidecar.ts the SDK issuer behind a local HTTP API, for agents in other l
252
254
  src/otel.ts OpenTelemetry export: one OTLP/HTTP span per receipt, after the receipt, no SDK dependency
253
255
  src/splunk.ts Splunk export: one HTTP Event Collector event per receipt, token from the environment, beside or instead of otel
254
256
  src/rest.ts the REST connector: an HTTP API described as tools, standing where an MCP upstream stands
257
+ src/a2a.ts agents delegating to agents: a remote A2A agent as an upstream, and the gateway serving A2A itself in front of it
255
258
  src/upstream.ts attested execution: an upstream signs its result for the receipt; the verifier checks it with the upstream key
259
+ src/capture.ts private evidence: per-tool capture rules applied by the issuer to the whole statement, withheld values as salted commitments or encrypted under the customer's key, restore and reveal
256
260
  vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
257
261
  src/verify.ts offline verification, the human-readable report, and the audit that a later log extends an earlier one
258
- src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, audit
262
+ src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, reveal, audit
259
263
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
260
264
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
261
265
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
262
266
  scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and SDK, demo
263
- examples/ eighteen runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
267
+ examples/ twenty-seven runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
264
268
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
265
269
  adapter tests against the real packages, and a test that runs every policy in docs/policies.md
266
270
  docs/ tutorials, usage (gateway), sdk, policies, verification
@@ -306,12 +310,15 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
306
310
  - Splunk export: with `splunk` in either config, every receipt is also one event at the HTTP Event Collector, with the receipt id, tool, agent, principal, status, decision, and log position as searchable fields and the token from the environment; the same best-effort rule.
307
311
  - The REST connector: a plain HTTP API described as tools in the gateway config, credentials from the environment, so an agent's direct API calls become receipted, policy-checked tool calls through the gateway.
308
312
  - Pre-commit authorization for consequential tools: named in `precommit`, a call is signed and logged before it is forwarded, withheld if the log will not take it, and its receipt carries the committed authorization with proof that it precedes the execution.
313
+ - The grant on every call (issue #97): expiry and revocation are checked on every call and again before the forward, in every mode, on the MCP, HTTP, and A2A fronts; `agent-custody revoke` revokes a grant and every grant delegated from it. The remote log's answer is verified against pinned keys before a pre-committed call goes upstream (issue #99). The portal verifies an address only from the account's own session before a provider sign-in can link to it (issue #103). The verifier recomputes the execution result digest (issue #104). The Stripe webhook ignores a repeated or out-of-order event (issue #105).
314
+ - Agent-to-agent delegation under custody: the A2A upstream and the gateway's A2A front; receipts per delegation with the delegate's card as a fact. A Google ADK `RemoteA2aAgent`, or any A2A client, is pointed at the gateway and a refused delegation comes back as a rejected task the delegate never saw. The delegate does not yet countersign its answer; the receipt attests what the gateway sent and observed, not what the delegate did with it.
315
+ - Private evidence: per-tool capture rules, applied by the issuer to the whole statement so nothing outside a fixed structural list is in clear under a private rule; withheld values as salted commitments whose salts never enter the receipt, encrypted under the customer's key, revealed and recomputed by the verifier; nothing in the receipt confirms a guess of a withheld value.
309
316
 
310
317
  **Next, in the order it pays off**
311
318
 
312
319
  1. Run the witness for log.agent-custody.dev on a machine and under an account that is not ours, and require it in the welcome sheet. The code is done; what it needs is a second operator. [Issue #6](https://github.com/svayatta/agent-custody/issues/6).
313
320
  2. Post-quantum signatures: ML-DSA beside Ed25519 in the same DSSE envelope, hybrid by default when a PQ key is present, in every signed artefact and in the browser verifier. [Issue #11](https://github.com/svayatta/agent-custody/issues/11).
314
- 3. Receiver-attested receipts for agent-to-agent calls.
321
+ 3. Receiver attestation for agent-to-agent calls: the delegate signs its answer for the receipt, as a signing upstream does today.
315
322
  4. A TEE-hosted signer, then SD-JWT redaction, then ZK proofs of policy compliance. Not before.
316
323
 
317
324
  A Python SDK follows the same shape once the TypeScript adapters have settled.
package/dist/a2a.d.ts ADDED
@@ -0,0 +1,93 @@
1
+ import type { A2aUpstreamConfig } from "./config.ts";
2
+ import type { Envelope } from "./crypto.ts";
3
+ import { type GatewayHost } from "./gateway.ts";
4
+ import type { UpstreamClient } from "./rest.ts";
5
+ export declare const A2A_CARD_PATH = "/.well-known/agent-card.json";
6
+ /** where cards lived before 0.3 */
7
+ export declare const A2A_LEGACY_CARD_PATH = "/.well-known/agent.json";
8
+ /** the key under which a task or message answered through the gateway names its receipt, in `metadata` */
9
+ export declare const A2A_RECEIPT_METADATA_KEY = "agent-custody/receipt";
10
+ /** on a `.send` result for a streamed delegation: the events the remote agent produced, in order */
11
+ export declare const A2A_STREAM_META_KEY = "agent-custody/a2a-stream";
12
+ export interface AgentInterface {
13
+ url: string;
14
+ protocolBinding?: string;
15
+ protocolVersion?: string;
16
+ }
17
+ export interface AgentCard {
18
+ name: string;
19
+ description?: string;
20
+ /** 0.3: the JSON-RPC endpoint */
21
+ url?: string;
22
+ protocolVersion?: string;
23
+ /** 1.0: the endpoints, the first preferred */
24
+ supportedInterfaces?: AgentInterface[];
25
+ skills?: {
26
+ id: string;
27
+ name?: string;
28
+ description?: string;
29
+ tags?: string[];
30
+ }[];
31
+ capabilities?: Record<string, unknown>;
32
+ signatures?: unknown[];
33
+ [k: string]: unknown;
34
+ }
35
+ export interface ResolvedCard {
36
+ card: AgentCard;
37
+ cardUrl: string;
38
+ /** the JSON-RPC endpoint the card names */
39
+ endpoint: string;
40
+ /** true for a 0.3 card and wire format */
41
+ legacy: boolean;
42
+ }
43
+ export interface A2aOptions {
44
+ fetch?: typeof fetch;
45
+ env?: Record<string, string | undefined>;
46
+ }
47
+ /** Fetches an agent card from a base URL or a card URL and works out the endpoint and wire format. */
48
+ export declare function fetchAgentCard(url: string, headers: Record<string, string>, f: typeof fetch, timeoutMs: number): Promise<ResolvedCard>;
49
+ type Part = {
50
+ text?: string;
51
+ kind?: string;
52
+ [k: string]: unknown;
53
+ };
54
+ type Message = {
55
+ messageId?: string;
56
+ role?: string;
57
+ parts?: Part[];
58
+ taskId?: string;
59
+ contextId?: string;
60
+ metadata?: Record<string, unknown>;
61
+ kind?: string;
62
+ [k: string]: unknown;
63
+ };
64
+ /** The text parts of a message, joined; what a policy reads as `context.args.text`. */
65
+ export declare function textOf(message: Message | undefined): string;
66
+ /** Parses an SSE body into the JSON objects of its `data:` lines. */
67
+ export declare function parseSse(body: string): unknown[];
68
+ /** The final state of a streamed task: the first task snapshot, updated by every status and artifact event. */
69
+ export declare function finalOfStream(events: unknown[]): unknown;
70
+ /** A remote agent as an upstream: `<prefix>.send` delegates a task to it, `<prefix>.card` reads its card. */
71
+ export declare function a2aUpstream(name: string, cfg: A2aUpstreamConfig, opts?: A2aOptions): UpstreamClient & {
72
+ resolved(): Promise<ResolvedCard>;
73
+ };
74
+ export interface A2aServerOptions {
75
+ port: number;
76
+ host?: string;
77
+ /** the grant every request without a grant header runs under; without it, a grant header is required */
78
+ grant?: Envelope;
79
+ log?: (message: string) => void;
80
+ }
81
+ export interface RunningA2aServer {
82
+ /** the base URL: the card is at /.well-known/agent-card.json, JSON-RPC at / */
83
+ url: string;
84
+ close(): Promise<void>;
85
+ }
86
+ /**
87
+ * Serves the gateway as an A2A agent in front of the A2A upstream `cfg` describes. Point an A2A client at the
88
+ * returned URL: the card is served there with the gateway's own address, every SendMessage becomes a
89
+ * `<prefix>.send` call under the grant (the default one, or the one in the request's grant header), and the
90
+ * remaining methods are forwarded as they are.
91
+ */
92
+ export declare function serveA2a(host: GatewayHost, cfg: A2aUpstreamConfig, opts: A2aServerOptions): Promise<RunningA2aServer>;
93
+ export {};
package/dist/a2a.js ADDED
@@ -0,0 +1,391 @@
1
+ // Agents that delegate to agents. The A2A protocol is how one agent hands a task to another over HTTP: the remote
2
+ // agent publishes an agent card, the caller sends a message, and gets back a task with its status and artifacts.
3
+ // Here that delegation goes through the gateway, two ways.
4
+ //
5
+ // As an upstream, the remote agent is a tool: `<prefix>.send` delegates a task, `<prefix>.card` reads its card so a
6
+ // policy can decide on the agent it is actually talking to. Everything the gateway does for any upstream applies:
7
+ // scope, policy on facts it fetched itself, pre-commit for consequential delegations, a receipt either way.
8
+ //
9
+ // As a front door (`serveA2a`), the gateway speaks A2A itself. An A2A client such as Google ADK's RemoteA2aAgent is
10
+ // pointed at the gateway instead of at the remote agent; the gateway serves the agent card with its own address,
11
+ // turns every SendMessage into a `<prefix>.send` call, and answers in A2A: a task that was allowed carries the receipt
12
+ // id in its metadata, a task the policy refused comes back rejected with the reason and the receipt id, and nothing
13
+ // reached the remote agent. Both the 1.0 wire format (SendMessage, ROLE_USER) and the 0.3 one (message/send, kind)
14
+ // are understood; the remote agent's card says which it speaks.
15
+ //
16
+ // A streamed delegation is relayed once the remote agent has finished: the receipt records the task's final state,
17
+ // and the events the remote agent produced are then replayed to the caller in order.
18
+ import { randomUUID } from "node:crypto";
19
+ import { createServer } from "node:http";
20
+ import { Readable } from "node:stream";
21
+ import { RECEIPT_META_KEY } from "./gateway.js";
22
+ import { GRANT_HEADER, parseGrantHeader } from "./gateway-http.js";
23
+ export const A2A_CARD_PATH = "/.well-known/agent-card.json";
24
+ /** where cards lived before 0.3 */
25
+ export const A2A_LEGACY_CARD_PATH = "/.well-known/agent.json";
26
+ /** the key under which a task or message answered through the gateway names its receipt, in `metadata` */
27
+ export const A2A_RECEIPT_METADATA_KEY = "agent-custody/receipt";
28
+ /** on a `.send` result for a streamed delegation: the events the remote agent produced, in order */
29
+ export const A2A_STREAM_META_KEY = "agent-custody/a2a-stream";
30
+ const SEND_METHODS = new Set(["SendMessage", "message/send"]);
31
+ const STREAM_METHODS = new Set(["SendStreamingMessage", "message/stream"]);
32
+ const LEGACY_METHODS = new Set(["message/send", "message/stream"]);
33
+ function resolveHeaders(name, cfg, env) {
34
+ const headers = { ...(cfg.headers ?? {}) };
35
+ for (const [header, variable] of Object.entries(cfg.headerEnv ?? {})) {
36
+ const v = env[variable];
37
+ if (!v)
38
+ throw new Error(`upstream ${name}: environment variable ${variable} is not set`);
39
+ headers[header] = v;
40
+ }
41
+ return headers;
42
+ }
43
+ /** Fetches an agent card from a base URL or a card URL and works out the endpoint and wire format. */
44
+ export async function fetchAgentCard(url, headers, f, timeoutMs) {
45
+ const u = new URL(url);
46
+ const candidates = u.pathname.endsWith(".json") ? [u.toString()] : [new URL(A2A_CARD_PATH, u).toString(), new URL(A2A_LEGACY_CARD_PATH, u).toString()];
47
+ let last = "";
48
+ for (const cardUrl of candidates) {
49
+ const res = await f(cardUrl, { headers: { accept: "application/json", ...headers }, signal: AbortSignal.timeout(timeoutMs) });
50
+ if (res.status === 404) {
51
+ last = `${cardUrl}: 404`;
52
+ continue;
53
+ }
54
+ if (!res.ok)
55
+ throw new Error(`agent card ${cardUrl}: HTTP ${res.status}`);
56
+ const card = (await res.json());
57
+ if (!card || typeof card !== "object" || typeof card.name !== "string")
58
+ throw new Error(`agent card ${cardUrl}: not an agent card`);
59
+ const iface = card.supportedInterfaces?.find((i) => !i.protocolBinding || i.protocolBinding === "JSONRPC") ?? null;
60
+ const endpoint = iface?.url ?? card.url;
61
+ if (!endpoint)
62
+ throw new Error(`agent card ${cardUrl}: no JSON-RPC endpoint (neither supportedInterfaces nor url)`);
63
+ return { card, cardUrl, endpoint, legacy: !card.supportedInterfaces };
64
+ }
65
+ throw new Error(`no agent card at ${candidates.join(" or ")} (${last})`);
66
+ }
67
+ /** The text parts of a message, joined; what a policy reads as `context.args.text`. */
68
+ export function textOf(message) {
69
+ return (message?.parts ?? []).filter((p) => typeof p.text === "string").map((p) => p.text).join("\n");
70
+ }
71
+ function buildMessage(text, legacy, taskId, contextId) {
72
+ const ids = { ...(taskId ? { taskId } : {}), ...(contextId ? { contextId } : {}) };
73
+ return legacy
74
+ ? { kind: "message", role: "user", messageId: randomUUID(), parts: [{ kind: "text", text }], ...ids }
75
+ : { role: "ROLE_USER", messageId: randomUUID(), parts: [{ text }], ...ids };
76
+ }
77
+ /** Parses an SSE body into the JSON objects of its `data:` lines. */
78
+ export function parseSse(body) {
79
+ const out = [];
80
+ for (const block of body.split(/\r?\n\r?\n/)) {
81
+ const data = block
82
+ .split(/\r?\n/)
83
+ .filter((l) => l.startsWith("data:"))
84
+ .map((l) => l.slice(5).trim())
85
+ .join("\n");
86
+ if (!data)
87
+ continue;
88
+ try {
89
+ out.push(JSON.parse(data));
90
+ }
91
+ catch {
92
+ // a line that is not JSON is not an event
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ /** The final state of a streamed task: the first task snapshot, updated by every status and artifact event. */
98
+ export function finalOfStream(events) {
99
+ let task = null;
100
+ let message = null;
101
+ for (const raw of events) {
102
+ const ev = (raw ?? {});
103
+ // 1.0 wraps each event in a StreamResponse; 0.3 tags the object with `kind`
104
+ const snapshot = (ev.task ?? (ev.kind === "task" ? ev : null));
105
+ const status = (ev.statusUpdate ?? (ev.kind === "status-update" ? ev : null));
106
+ const artifact = (ev.artifactUpdate ?? (ev.kind === "artifact-update" ? ev : null));
107
+ const msg = ev.message ?? (ev.kind === "message" ? ev : null);
108
+ if (snapshot)
109
+ task = { ...snapshot };
110
+ if (status && task)
111
+ task = { ...task, status: status.status };
112
+ if (artifact && task) {
113
+ const artifacts = Array.isArray(task.artifacts) ? [...task.artifacts] : [];
114
+ artifacts.push(artifact.artifact);
115
+ task = { ...task, artifacts };
116
+ }
117
+ if (msg)
118
+ message = msg;
119
+ }
120
+ return task ?? message ?? events.at(-1) ?? null;
121
+ }
122
+ /** A remote agent as an upstream: `<prefix>.send` delegates a task to it, `<prefix>.card` reads its card. */
123
+ export function a2aUpstream(name, cfg, opts = {}) {
124
+ const f = opts.fetch ?? fetch;
125
+ const headers = resolveHeaders(name, cfg, opts.env ?? process.env);
126
+ const sendTool = `${cfg.prefix}.send`;
127
+ const cardTool = `${cfg.prefix}.card`;
128
+ let resolved = null;
129
+ const card = () => (resolved ??= fetchAgentCard(cfg.url, headers, f, cfg.timeoutMs));
130
+ const text = (v, isError = false) => ({ content: [{ type: "text", text: JSON.stringify(v) }], ...(isError ? { isError: true } : {}) });
131
+ return {
132
+ resolved: card,
133
+ async listTools() {
134
+ const { card: c } = await card();
135
+ const skills = (c.skills ?? []).map((s) => `${s.id}${s.description ? `: ${s.description}` : ""}`).join("; ");
136
+ const tools = [
137
+ {
138
+ name: sendTool,
139
+ description: `Delegate a task to the agent "${c.name}"${c.description ? `: ${c.description}` : ""}${skills ? `. Skills: ${skills}` : ""}. Send text for a plain task, or message for a full A2A message; one of the two is needed. Returns the agent's task or message as JSON text. A JSON-RPC error from the agent comes back as an error result.`,
140
+ inputSchema: {
141
+ type: "object",
142
+ properties: {
143
+ text: { type: "string", description: "the task, as text" },
144
+ message: { type: "object", description: "a full A2A message, forwarded as is; text is derived from it" },
145
+ taskId: { type: "string", description: "the id of an earlier task to continue; used with text only, because a full message carries its own" },
146
+ contextId: { type: "string", description: "the id of the conversation context to continue; used with text only" },
147
+ configuration: { type: "object", description: "the A2A send configuration, forwarded as is" },
148
+ metadata: { type: "object", description: "A2A metadata for the request, forwarded as is" },
149
+ },
150
+ },
151
+ },
152
+ { name: cardTool, description: `The agent card of "${c.name}", fetched afresh from the agent by the gateway: its name, description, skills, and the interfaces it serves. Call it to see what the agent can do before you delegate with ${sendTool}. A gateway config can also name it as a fact, so that a policy can read the card.`, inputSchema: { type: "object", properties: {} } },
153
+ ];
154
+ return { tools };
155
+ },
156
+ async callTool(params) {
157
+ const r = await card();
158
+ if (params.name === cardTool) {
159
+ const fresh = await fetchAgentCard(r.cardUrl, headers, f, cfg.timeoutMs);
160
+ return text(fresh.card);
161
+ }
162
+ if (params.name !== sendTool)
163
+ throw new Error(`upstream ${name} has no tool "${params.name}"`);
164
+ const args = params.arguments ?? {};
165
+ const method = typeof args.method === "string" ? args.method : r.legacy ? "message/send" : "SendMessage";
166
+ const stream = STREAM_METHODS.has(method);
167
+ const message = args.message ?? buildMessage(typeof args.text === "string" ? args.text : "", r.legacy, args.taskId, args.contextId);
168
+ const rpc = { jsonrpc: "2.0", id: randomUUID(), method, params: { message, ...(args.configuration ? { configuration: args.configuration } : {}), ...(args.metadata ? { metadata: args.metadata } : {}) } };
169
+ const res = await f(r.endpoint, {
170
+ method: "POST",
171
+ headers: { "content-type": "application/json", accept: stream ? "text/event-stream" : "application/json", ...(r.legacy ? {} : { "a2a-version": "1.0" }), ...headers },
172
+ body: JSON.stringify(rpc),
173
+ signal: AbortSignal.timeout(cfg.timeoutMs),
174
+ });
175
+ const body = await res.text();
176
+ if (!res.ok)
177
+ return text({ code: -32000, message: `HTTP ${res.status} from ${r.endpoint}`, data: body.slice(0, 2000) }, true);
178
+ if (stream) {
179
+ const envelopes = parseSse(body);
180
+ const failed = envelopes.find((e) => e.error);
181
+ if (failed)
182
+ return text(failed.error, true);
183
+ const events = envelopes.map((e) => e.result).filter((e) => e !== undefined);
184
+ return { ...text(finalOfStream(events)), _meta: { [A2A_STREAM_META_KEY]: events } };
185
+ }
186
+ let parsed;
187
+ try {
188
+ parsed = JSON.parse(body);
189
+ }
190
+ catch {
191
+ return text({ code: -32700, message: "the agent did not answer with JSON", data: body.slice(0, 2000) }, true);
192
+ }
193
+ if (parsed.error)
194
+ return text(parsed.error, true);
195
+ return text(parsed.result ?? null);
196
+ },
197
+ async close() { },
198
+ };
199
+ }
200
+ const sendBody = (res, status, type, body) => {
201
+ res.writeHead(status, { "content-type": type, "cache-control": "no-store" });
202
+ res.end(body);
203
+ };
204
+ /** Receipt id and reason out of a result the gateway refused: "Denied by policy: ... (receipt <id>)". */
205
+ function refusalOf(result) {
206
+ if (!result.isError)
207
+ return null;
208
+ const first = result.content.find((c) => c.type === "text");
209
+ const t = first && first.type === "text" ? first.text : "";
210
+ const m = /^(Denied by policy|Not executed|Upstream error): (.*) \(receipt [0-9a-f-]+\)$/s.exec(t);
211
+ if (!m)
212
+ return null;
213
+ return { kind: m[1] === "Upstream error" ? "failed" : "rejected", reason: m[2] };
214
+ }
215
+ function refusedTask(legacy, message, kind, reason, receiptId) {
216
+ const id = message.taskId ?? randomUUID();
217
+ const contextId = message.contextId ?? randomUUID();
218
+ const timestamp = new Date().toISOString();
219
+ const metadata = { [A2A_RECEIPT_METADATA_KEY]: receiptId };
220
+ const text = `agent-custody: ${reason} (receipt ${receiptId})`;
221
+ return legacy
222
+ ? { kind: "task", id, contextId, status: { state: kind, message: { kind: "message", role: "agent", messageId: randomUUID(), parts: [{ kind: "text", text }] }, timestamp }, metadata }
223
+ : { id, contextId, status: { state: kind === "rejected" ? "TASK_STATE_REJECTED" : "TASK_STATE_FAILED", message: { role: "ROLE_AGENT", messageId: randomUUID(), parts: [{ text }] }, timestamp }, metadata };
224
+ }
225
+ /** Names the receipt on whatever object the remote agent answered with, if it is a task, message or event. */
226
+ function withReceipt(value, receiptId) {
227
+ if (!value || typeof value !== "object" || Array.isArray(value))
228
+ return value;
229
+ const v = { ...value };
230
+ const mark = (o) => (o && typeof o === "object" ? { ...o, metadata: { ...o.metadata, [A2A_RECEIPT_METADATA_KEY]: receiptId } } : o);
231
+ // 1.0 stream events wrap the object; a plain task, message or 0.3 event is the object itself
232
+ for (const k of ["task", "message", "statusUpdate", "artifactUpdate"])
233
+ if (k in v)
234
+ v[k] = mark(v[k]);
235
+ if ("status" in v || "parts" in v || "kind" in v)
236
+ return mark(v);
237
+ return v;
238
+ }
239
+ /**
240
+ * Serves the gateway as an A2A agent in front of the A2A upstream `cfg` describes. Point an A2A client at the
241
+ * returned URL: the card is served there with the gateway's own address, every SendMessage becomes a
242
+ * `<prefix>.send` call under the grant (the default one, or the one in the request's grant header), and the
243
+ * remaining methods are forwarded as they are.
244
+ */
245
+ export async function serveA2a(host, cfg, opts) {
246
+ const bind = opts.host ?? "127.0.0.1";
247
+ const log = opts.log ?? ((m) => console.error(m));
248
+ const f = fetch;
249
+ const headers = resolveHeaders("a2a", cfg, process.env);
250
+ const upstream = await fetchAgentCard(cfg.url, headers, f, cfg.timeoutMs);
251
+ const sendTool = `${cfg.prefix}.send`;
252
+ const sessions = new Map();
253
+ let self = "";
254
+ const session = (req) => {
255
+ const raw = (typeof req.headers[GRANT_HEADER] === "string" && req.headers[GRANT_HEADER]) || (req.headers.authorization?.startsWith("Bearer ") ? req.headers.authorization : "");
256
+ const key = raw || "default";
257
+ const existing = sessions.get(key);
258
+ if (existing)
259
+ return existing;
260
+ const envelope = raw ? parseGrantHeader(req) : opts.grant;
261
+ if (!envelope)
262
+ throw new Error(raw ? "the grant header is not a delegation envelope" : `a grant is required: send the delegation envelope as base64url in Authorization: Bearer or ${GRANT_HEADER}`);
263
+ const gw = host.open(envelope);
264
+ sessions.set(key, gw);
265
+ log(`agent-custody gateway (a2a): session for agent=${gw.agentId} principal=${gw.delegation.principal}`);
266
+ return gw;
267
+ };
268
+ const servedCard = async () => {
269
+ const { card } = await fetchAgentCard(upstream.cardUrl, headers, f, cfg.timeoutMs);
270
+ const out = { ...card };
271
+ if (card.supportedInterfaces) {
272
+ const first = card.supportedInterfaces.find((i) => !i.protocolBinding || i.protocolBinding === "JSONRPC") ?? card.supportedInterfaces[0];
273
+ out.supportedInterfaces = [{ ...first, url: self, protocolBinding: "JSONRPC" }];
274
+ }
275
+ if (card.url)
276
+ out.url = self;
277
+ // the card has been changed, so its signatures no longer apply
278
+ delete out.signatures;
279
+ return out;
280
+ };
281
+ const forward = async (req, res, body) => {
282
+ const r = await f(upstream.endpoint, {
283
+ method: "POST",
284
+ headers: { "content-type": "application/json", accept: req.headers.accept ?? "application/json", ...(typeof req.headers["a2a-version"] === "string" ? { "a2a-version": req.headers["a2a-version"] } : {}), ...headers },
285
+ body,
286
+ signal: AbortSignal.timeout(cfg.timeoutMs),
287
+ });
288
+ res.writeHead(r.status, { "content-type": r.headers.get("content-type") ?? "application/json", "cache-control": "no-store" });
289
+ if (!r.body)
290
+ return void res.end();
291
+ Readable.fromWeb(r.body).pipe(res);
292
+ };
293
+ const handler = async (req, res) => {
294
+ const url = new URL(req.url ?? "/", self);
295
+ if (req.method === "GET" && url.pathname === "/health")
296
+ return sendBody(res, 200, "application/json", JSON.stringify({ ok: true, agent: upstream.card.name, keyid: host.keyid }));
297
+ if (req.method === "GET" && (url.pathname === A2A_CARD_PATH || url.pathname === A2A_LEGACY_CARD_PATH))
298
+ return sendBody(res, 200, "application/json", JSON.stringify(await servedCard()));
299
+ if (req.method !== "POST")
300
+ return sendBody(res, 405, "application/json", JSON.stringify({ error: "POST JSON-RPC here; the agent card is at /.well-known/agent-card.json" }));
301
+ let body = "";
302
+ for await (const chunk of req) {
303
+ body += chunk;
304
+ if (body.length > 16_777_216)
305
+ return sendBody(res, 413, "application/json", JSON.stringify({ error: "body larger than 16 MB" }));
306
+ }
307
+ let parsed;
308
+ try {
309
+ parsed = JSON.parse(body);
310
+ }
311
+ catch {
312
+ return sendBody(res, 400, "application/json", JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }));
313
+ }
314
+ // the HTTP+JSON binding of 1.0 puts the request directly in the body
315
+ const restSend = url.pathname === "/message:send" ? "SendMessage" : url.pathname === "/message:stream" ? "SendStreamingMessage" : null;
316
+ const method = restSend ?? (typeof parsed.method === "string" ? parsed.method : "");
317
+ const id = restSend ? null : parsed.id ?? null;
318
+ const params = (restSend ? parsed : parsed.params) ?? {};
319
+ if (!SEND_METHODS.has(method) && !STREAM_METHODS.has(method)) {
320
+ // reads and cancels carry no receipt, but they still need a grant in force (issue #97)
321
+ let problem;
322
+ try {
323
+ const p = session(req).grantProblem();
324
+ problem = p && `the grant ${p}`;
325
+ }
326
+ catch (e) {
327
+ problem = e instanceof Error ? e.message : String(e);
328
+ }
329
+ if (problem)
330
+ return sendBody(res, 403, "application/json", JSON.stringify(restSend ? { error: problem } : { jsonrpc: "2.0", id, error: { code: -32000, message: problem } }));
331
+ return forward(req, res, body);
332
+ }
333
+ const legacy = LEGACY_METHODS.has(method);
334
+ const stream = STREAM_METHODS.has(method);
335
+ const message = (params.message ?? {});
336
+ let gw;
337
+ try {
338
+ gw = session(req);
339
+ }
340
+ catch (e) {
341
+ const msg = e instanceof Error ? e.message : String(e);
342
+ return sendBody(res, 403, "application/json", JSON.stringify(restSend ? { error: msg } : { jsonrpc: "2.0", id, error: { code: -32000, message: msg } }));
343
+ }
344
+ const args = { text: textOf(message), message, method, ...(message.taskId ? { taskId: message.taskId } : {}), ...(message.contextId ? { contextId: message.contextId } : {}), ...(params.configuration ? { configuration: params.configuration } : {}), ...(params.metadata ? { metadata: params.metadata } : {}) };
345
+ const result = await gw.handleCall({ name: sendTool, arguments: args });
346
+ const receiptId = String(result._meta?.[RECEIPT_META_KEY] ?? "");
347
+ const refusal = refusalOf(result);
348
+ const first = result.content.find((c) => c.type === "text");
349
+ const answered = refusal ? null : first && first.type === "text" ? JSON.parse(first.text) : null;
350
+ const wrap = (v) => (restSend ? v : { jsonrpc: "2.0", id, result: v });
351
+ if (stream) {
352
+ const events = refusal
353
+ ? [legacy ? refusedTask(true, message, refusal.kind, refusal.reason, receiptId) : { task: refusedTask(false, message, refusal.kind, refusal.reason, receiptId) }]
354
+ : result.isError
355
+ ? []
356
+ : (result._meta?.[A2A_STREAM_META_KEY] ?? [legacy ? answered : { task: answered }]);
357
+ if (!refusal && result.isError)
358
+ return sendBody(res, 200, "application/json", JSON.stringify(restSend ? { error: { ...answered, data: { receipt: receiptId } } } : { jsonrpc: "2.0", id, error: { ...answered, data: { receipt: receiptId } } }));
359
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
360
+ for (const ev of events)
361
+ res.write(`data: ${JSON.stringify(wrap(withReceipt(ev, receiptId)))}\n\n`);
362
+ return void res.end();
363
+ }
364
+ if (refusal)
365
+ return sendBody(res, 200, "application/json", JSON.stringify(wrap(refusedTask(legacy, message, refusal.kind, refusal.reason, receiptId))));
366
+ if (result.isError)
367
+ return sendBody(res, 200, "application/json", JSON.stringify(restSend ? { error: { ...answered, data: { receipt: receiptId } } } : { jsonrpc: "2.0", id, error: { ...answered, data: { receipt: receiptId } } }));
368
+ return sendBody(res, 200, "application/json", JSON.stringify(wrap(withReceipt(answered, receiptId))));
369
+ };
370
+ const server = createServer((req, res) => {
371
+ handler(req, res).catch((e) => {
372
+ log(`agent-custody gateway (a2a): ${e instanceof Error ? e.message : String(e)}`);
373
+ if (!res.headersSent)
374
+ sendBody(res, 500, "application/json", JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }));
375
+ else
376
+ res.end();
377
+ });
378
+ });
379
+ await new Promise((resolve) => server.listen(opts.port, bind, resolve));
380
+ const { port } = server.address();
381
+ self = `http://${bind}:${port}`;
382
+ return {
383
+ url: self,
384
+ async close() {
385
+ for (const gw of sessions.values())
386
+ await gw.close();
387
+ server.closeAllConnections?.();
388
+ await new Promise((resolve) => server.close(() => resolve()));
389
+ },
390
+ };
391
+ }