@agent-custody/receipts 0.6.18 → 0.6.19

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
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.
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-five 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
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-five 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,6 +254,7 @@ 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
256
259
  vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
257
260
  src/verify.ts offline verification, the human-readable report, and the audit that a later log extends an earlier one
@@ -260,7 +263,7 @@ src/retention.ts pruning the log: leaves become their hashes, bundles are remo
260
263
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
261
264
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
262
265
  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
266
+ examples/ twenty-five 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
267
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
265
268
  adapter tests against the real packages, and a test that runs every policy in docs/policies.md
266
269
  docs/ tutorials, usage (gateway), sdk, policies, verification
@@ -306,12 +309,13 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
306
309
  - 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
310
  - 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
311
  - 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.
312
+ - 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.
309
313
 
310
314
  **Next, in the order it pays off**
311
315
 
312
316
  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
317
  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.
318
+ 3. Receiver attestation for agent-to-agent calls: the delegate signs its answer for the receipt, as a signing upstream does today.
315
319
  4. A TEE-hosted signer, then SD-JWT redaction, then ZK proofs of policy compliance. Not before.
316
320
 
317
321
  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,379 @@
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}` : ""}`,
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" },
146
+ contextId: { type: "string" },
147
+ configuration: { type: "object" },
148
+ metadata: { type: "object" },
149
+ },
150
+ },
151
+ },
152
+ { name: cardTool, description: `The agent card of "${c.name}", fetched by the gateway`, 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
+ return forward(req, res, body);
321
+ const legacy = LEGACY_METHODS.has(method);
322
+ const stream = STREAM_METHODS.has(method);
323
+ const message = (params.message ?? {});
324
+ let gw;
325
+ try {
326
+ gw = session(req);
327
+ }
328
+ catch (e) {
329
+ const msg = e instanceof Error ? e.message : String(e);
330
+ return sendBody(res, 403, "application/json", JSON.stringify(restSend ? { error: msg } : { jsonrpc: "2.0", id, error: { code: -32000, message: msg } }));
331
+ }
332
+ 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 } : {}) };
333
+ const result = await gw.handleCall({ name: sendTool, arguments: args });
334
+ const receiptId = String(result._meta?.[RECEIPT_META_KEY] ?? "");
335
+ const refusal = refusalOf(result);
336
+ const first = result.content.find((c) => c.type === "text");
337
+ const answered = refusal ? null : first && first.type === "text" ? JSON.parse(first.text) : null;
338
+ const wrap = (v) => (restSend ? v : { jsonrpc: "2.0", id, result: v });
339
+ if (stream) {
340
+ const events = refusal
341
+ ? [legacy ? refusedTask(true, message, refusal.kind, refusal.reason, receiptId) : { task: refusedTask(false, message, refusal.kind, refusal.reason, receiptId) }]
342
+ : result.isError
343
+ ? []
344
+ : (result._meta?.[A2A_STREAM_META_KEY] ?? [legacy ? answered : { task: answered }]);
345
+ if (!refusal && result.isError)
346
+ return sendBody(res, 200, "application/json", JSON.stringify(restSend ? { error: { ...answered, data: { receipt: receiptId } } } : { jsonrpc: "2.0", id, error: { ...answered, data: { receipt: receiptId } } }));
347
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
348
+ for (const ev of events)
349
+ res.write(`data: ${JSON.stringify(wrap(withReceipt(ev, receiptId)))}\n\n`);
350
+ return void res.end();
351
+ }
352
+ if (refusal)
353
+ return sendBody(res, 200, "application/json", JSON.stringify(wrap(refusedTask(legacy, message, refusal.kind, refusal.reason, receiptId))));
354
+ if (result.isError)
355
+ return sendBody(res, 200, "application/json", JSON.stringify(restSend ? { error: { ...answered, data: { receipt: receiptId } } } : { jsonrpc: "2.0", id, error: { ...answered, data: { receipt: receiptId } } }));
356
+ return sendBody(res, 200, "application/json", JSON.stringify(wrap(withReceipt(answered, receiptId))));
357
+ };
358
+ const server = createServer((req, res) => {
359
+ handler(req, res).catch((e) => {
360
+ log(`agent-custody gateway (a2a): ${e instanceof Error ? e.message : String(e)}`);
361
+ if (!res.headersSent)
362
+ sendBody(res, 500, "application/json", JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }));
363
+ else
364
+ res.end();
365
+ });
366
+ });
367
+ await new Promise((resolve) => server.listen(opts.port, bind, resolve));
368
+ const { port } = server.address();
369
+ self = `http://${bind}:${port}`;
370
+ return {
371
+ url: self,
372
+ async close() {
373
+ for (const gw of sessions.values())
374
+ await gw.close();
375
+ server.closeAllConnections?.();
376
+ await new Promise((resolve) => server.close(() => resolve()));
377
+ },
378
+ };
379
+ }
package/dist/cli.js CHANGED
@@ -14,6 +14,7 @@ import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.
14
14
  import { fetchWitnessKeys, Witness } from "./witness.js";
15
15
  import { checkLog, formatLogCheck } from "./log-check.js";
16
16
  import { serveHttp } from "./gateway-http.js";
17
+ import { serveA2a } from "./a2a.js";
17
18
  import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
18
19
  import { exportLog, formatExport } from "./log-export.js";
19
20
  import { CheckpointPublisher, fileResolver } from "./log-sink.js";
@@ -176,9 +177,26 @@ async function main(argv) {
176
177
  return 0;
177
178
  }
178
179
  case "gateway": {
179
- const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, http: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "idle-minutes": { type: "string", default: "30" } } });
180
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, http: { type: "boolean", default: false }, a2a: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "idle-minutes": { type: "string", default: "30" } } });
180
181
  if (!values.config)
181
182
  throw new Error("gateway needs --config");
183
+ if (values.a2a) {
184
+ // The gateway as an A2A agent: the config's one A2A upstream is what it fronts; the grant file is the default
185
+ // session, and a request may present its own grant in the same header the HTTP gateway takes.
186
+ const cfg = loadConfig(values.config);
187
+ const candidates = (cfg.upstreams ?? (cfg.upstream ? [cfg.upstream] : [])).filter((u) => "a2a" in u);
188
+ if (candidates.length !== 1)
189
+ throw new Error("gateway --a2a needs exactly one { a2a: ... } upstream in the config");
190
+ const a2a = candidates[0].a2a;
191
+ const host = await createGatewayHost(cfg);
192
+ const grant = cfg.grantFile ? JSON.parse(readFileSync(cfg.grantFile, "utf8")) : undefined;
193
+ const running = await serveA2a(host, a2a, { port: Number(values.port), host: values.host, ...(grant ? { grant } : {}) });
194
+ console.error(`agent-custody gateway (a2a): ${running.url} keyid=${host.keyid} fronting ${a2a.url} as ${a2a.prefix}.send; card at ${running.url}/.well-known/agent-card.json`);
195
+ await new Promise((resolve) => process.once("SIGINT", resolve));
196
+ await running.close();
197
+ await host.close();
198
+ return 0;
199
+ }
182
200
  if (values.http) {
183
201
  const host = await createGatewayHost(loadConfig(values.config));
184
202
  const running = await serveHttp(host, { port: Number(values.port), host: values.host, idleMs: Number(values["idle-minutes"]) * 60_000 });
package/dist/config.d.ts CHANGED
@@ -45,6 +45,15 @@ declare const RestUpstreamSchema: z.ZodObject<{
45
45
  }, z.core.$strip>>;
46
46
  }, z.core.$strip>;
47
47
  export type RestUpstreamConfig = z.infer<typeof RestUpstreamSchema>;
48
+ /** Another agent, reached over the A2A protocol, as an upstream. Its agent card is fetched at startup; the gateway offers `<prefix>.send`, which delegates a task to it, and `<prefix>.card`, a read of the card for use as a fact. */
49
+ declare const A2aUpstreamSchema: z.ZodObject<{
50
+ url: z.ZodString;
51
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
52
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
53
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
54
+ prefix: z.ZodDefault<z.ZodString>;
55
+ }, z.core.$strip>;
56
+ export type A2aUpstreamConfig = z.infer<typeof A2aUpstreamSchema>;
48
57
  declare const UpstreamSchema: z.ZodUnion<readonly [z.ZodObject<{
49
58
  command: z.ZodString;
50
59
  args: z.ZodDefault<z.ZodArray<z.ZodString>>;
@@ -77,6 +86,14 @@ declare const UpstreamSchema: z.ZodUnion<readonly [z.ZodObject<{
77
86
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
78
87
  }, z.core.$strip>>;
79
88
  }, z.core.$strip>;
89
+ }, z.core.$strip>, z.ZodObject<{
90
+ a2a: z.ZodObject<{
91
+ url: z.ZodString;
92
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
93
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
94
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
95
+ prefix: z.ZodDefault<z.ZodString>;
96
+ }, z.core.$strip>;
80
97
  }, z.core.$strip>]>;
81
98
  export type UpstreamConfig = z.infer<typeof UpstreamSchema>;
82
99
  declare const FactSchema: z.ZodObject<{
@@ -122,6 +139,14 @@ export declare const GatewayConfigSchema: z.ZodObject<{
122
139
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
123
140
  }, z.core.$strip>>;
124
141
  }, z.core.$strip>;
142
+ }, z.core.$strip>, z.ZodObject<{
143
+ a2a: z.ZodObject<{
144
+ url: z.ZodString;
145
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
146
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
147
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
148
+ prefix: z.ZodDefault<z.ZodString>;
149
+ }, z.core.$strip>;
125
150
  }, z.core.$strip>]>>;
126
151
  upstreams: z.ZodOptional<z.ZodArray<z.ZodIntersection<z.ZodUnion<readonly [z.ZodObject<{
127
152
  command: z.ZodString;
@@ -155,6 +180,14 @@ export declare const GatewayConfigSchema: z.ZodObject<{
155
180
  inputSchema: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
156
181
  }, z.core.$strip>>;
157
182
  }, z.core.$strip>;
183
+ }, z.core.$strip>, z.ZodObject<{
184
+ a2a: z.ZodObject<{
185
+ url: z.ZodString;
186
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
187
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
188
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
189
+ prefix: z.ZodDefault<z.ZodString>;
190
+ }, z.core.$strip>;
158
191
  }, z.core.$strip>]>, z.ZodObject<{
159
192
  name: z.ZodString;
160
193
  }, z.core.$strip>>>>;
package/dist/config.js CHANGED
@@ -30,10 +30,23 @@ const RestUpstreamSchema = z.object({
30
30
  timeoutMs: z.number().int().positive().default(30_000),
31
31
  tools: z.array(RestToolSchema).min(1),
32
32
  });
33
+ /** Another agent, reached over the A2A protocol, as an upstream. Its agent card is fetched at startup; the gateway offers `<prefix>.send`, which delegates a task to it, and `<prefix>.card`, a read of the card for use as a fact. */
34
+ const A2aUpstreamSchema = z.object({
35
+ /** the agent's base URL (its card is at /.well-known/agent-card.json) or the card's URL itself */
36
+ url: z.string().url(),
37
+ headers: z.record(z.string(), z.string()).optional(),
38
+ /** header name to environment variable, as for a REST upstream */
39
+ headerEnv: z.record(z.string(), z.string().min(1)).optional(),
40
+ /** how long one delegated task may take, streamed or not; default two minutes */
41
+ timeoutMs: z.number().int().positive().default(120_000),
42
+ /** the tool names are `<prefix>.send` and `<prefix>.card`; default "a2a". Give each A2A upstream its own prefix. */
43
+ prefix: z.string().min(1).regex(/^[A-Za-z0-9_-]+$/).default("a2a"),
44
+ });
33
45
  const UpstreamSchema = z.union([
34
46
  z.object({ command: z.string(), args: z.array(z.string()).default([]), env: z.record(z.string(), z.string()).optional() }),
35
47
  z.object({ url: z.string().url(), tokenEnv: z.string().min(1).optional() }),
36
48
  z.object({ rest: RestUpstreamSchema }),
49
+ z.object({ a2a: A2aUpstreamSchema }),
37
50
  ]);
38
51
  const FactSchema = z.object({
39
52
  /** key under context.facts */
package/dist/gateway.js CHANGED
@@ -15,6 +15,7 @@ import { openLog } from "./log-sink.js";
15
15
  import { openExporter } from "./otel.js";
16
16
  import { upstreamEvidenceOf } from "./upstream.js";
17
17
  import { restUpstream } from "./rest.js";
18
+ import { a2aUpstream } from "./a2a.js";
18
19
  import { evaluate, policyDigest } from "./policy.js";
19
20
  export const GATEWAY_VERSION = "0.1.0";
20
21
  export const RECEIPT_META_KEY = "agent-custody/receipt";
@@ -97,6 +98,9 @@ export async function createGatewayHost(cfg, options = {}) {
97
98
  if ("rest" in u) {
98
99
  client = restUpstream(name, u.rest);
99
100
  }
101
+ else if ("a2a" in u) {
102
+ client = a2aUpstream(name, u.a2a);
103
+ }
100
104
  else if ("url" in u) {
101
105
  client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
102
106
  const token = u.tokenEnv ? process.env[u.tokenEnv] : undefined;
package/dist/index.d.ts CHANGED
@@ -5,9 +5,11 @@ export { buildRequest, restUpstream } from "./rest.ts";
5
5
  export { openExporter, otlpExporter, spanFor } from "./otel.ts";
6
6
  export { hecEvent, splunkExporter } from "./splunk.ts";
7
7
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
8
+ export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
8
9
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
9
10
  export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
10
11
  export type { HttpGatewayOptions, RunningHttpGateway } from "./gateway-http.ts";
12
+ export type { A2aServerOptions, AgentCard, ResolvedCard, RunningA2aServer } from "./a2a.ts";
11
13
  export { exportLog, formatExport } from "./log-export.ts";
12
14
  export type { ExportOptions, ExportResult } from "./log-export.ts";
13
15
  export { fileBackend, importLogFile, PostgresLog, PostgresTenancy, RateLimiter } from "./log-store.ts";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ export { buildRequest, restUpstream } from "./rest.js";
4
4
  export { openExporter, otlpExporter, spanFor } from "./otel.js";
5
5
  export { hecEvent, splunkExporter } from "./splunk.js";
6
6
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
7
+ export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
7
8
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.js";
8
9
  export { exportLog, formatExport } from "./log-export.js";
9
10
  export { fileBackend, importLogFile, PostgresLog, PostgresTenancy, RateLimiter } from "./log-store.js";
@@ -28,7 +28,7 @@ Two rules keep the answers honest. First, say which producer made the receipt: a
28
28
  | CC7.2, monitoring for anomalies | the entity monitors system components for anomalies | every call has a receipt, allowed or denied, and `explain` answers who, why, and what depended on it; the OpenTelemetry and Splunk exports carry each receipt into the existing SIEM |
29
29
  | CC7.3, evaluation of security events | events are evaluated to determine whether they are incidents | the action pack: one receipt with every downstream receipt, verifiable by the evaluator without access to the system |
30
30
  | CC7.4, incident response | incidents are contained and remediated | blast radius names every action and belief that depended on a wrong fact; retract and forget are receipted calls, so the remediation has its own evidence |
31
- | CC8.1, change management | changes are authorized and tracked | the policy digest in every receipt identifies the exact policy that decided the call, so a policy change is visible in the receipts on either side of it |
31
+ | CC8.1, change management | changes are authorized and tracked | the policy digest in every receipt identifies the exact policy that decided the call, so a policy change is visible in the receipts; for changes made by agents, the merge gate below gives per-change evidence of tier, approval, and authority on either side of it |
32
32
 
33
33
  ## ISO/IEC 27001:2022, Annex A
34
34
 
@@ -39,7 +39,7 @@ Two rules keep the answers honest. First, say which producer made the receipt: a
39
39
  | A.8.10, information deletion | information is deleted when no longer required | forget erases a value from the ledger and the adapted stores and the receipt is the certificate, with each store's own answer; retention sweeps run as receipted calls; a legal hold refuses both |
40
40
  | A.8.15, logging | logs are produced, stored, protected, and analysed | the transparency log, append-only and hashed, with a log run by someone else where the operator must not be trusted |
41
41
  | A.8.16, monitoring activities | networks, systems, and applications are monitored | `log-check` from a machine that is not the log's, and the per-receipt spans in the SIEM |
42
- | A.8.32, change management | changes are subject to change management | the policy digest, the grant's window, and the receipts either side of a change |
42
+ | A.8.32, change management | changes are subject to change management | the policy digest, the grant's window, and the receipts either side of a change; for agent-made changes, the merge gate below |
43
43
 
44
44
  ## EU AI Act, obligations on high-risk systems and their deployers
45
45
 
@@ -59,6 +59,12 @@ Two rules keep the answers honest. First, say which producer made the receipt: a
59
59
  | Article 30, records of processing | records of processing activities are kept | the receipts, and the memory ledger's history of every fact with its source receipt |
60
60
  | Article 32, security of processing | appropriate technical measures | the hosted log holds hashes only, and receipts stay with the controller |
61
61
 
62
+ ## Agent-made changes: the merge gate
63
+
64
+ Teams whose agents open pull requests hit two problems at once. Volume: SOC 2 and ISO 27001 ask that changes are authorized, tested, and approved under a defined process, and a human on every PR does not scale. Accountability: a pipeline's own audit trail, including an "evidence store" at the end of it, is written by the pipeline that made the decisions. Risk-tiered review solves the first only if the tier decision itself is evidence.
65
+
66
+ [Example 24](../examples/24-agentic-cicd-merge-gate.ts) is that gate. A release agent merges through the gateway; the risk tier is a Cedar policy over facts the gateway fetches from the git host itself, never from the agent: the diff size, whether sensitive paths are touched, the deterministic gate results, which humans approved. Low risk merges on the agent's own authority, medium needs a CODEOWNER's approval the gateway can see, high has no permit for any agent and goes to two humans in the host, and production promotion is refused. Every merge is pre-committed to the log before it is forwarded. The receipts give, per change: the tier, the decision, the approvers as the gateway saw them, the policy digest, the human whose signed grant authorized the agent, and the log positions showing authorization preceded execution, each line verifiable with public keys and no account with us. That is what the two controls above ask for, produced by a key the agent does not hold, instead of a trail the pipeline wrote about itself.
67
+
62
68
  ## What no artefact here claims
63
69
 
64
70
  That the agent's arguments were correct, that the model named in a receipt produced the call, that the upstream executed the action unless it signed the result or a provider delivery is embedded, or that an SDK receipt was enforced outside the agent. The [proof table](../README.md#what-a-receipt-proves-and-what-it-does-not) says so, and a questionnaire answer that repeats it will survive the reviewer who checks.
package/docs/sdk.md CHANGED
@@ -130,6 +130,8 @@ const graph = workflow.compile().withConfig({ callbacks: [new ReceiptCallbackHan
130
130
  const refund = tool(issuer.wrap("stripe.refund", fn), { name: "stripe.refund", schema });
131
131
  ```
132
132
 
133
+ [Example 23](../examples/23-langchain-kb-agent.ts) is a whole agent on `createAgent`, a docs agent over a knowledge base with a policy that allows writes under `notes/` only, with every receipt verified at the end; it runs with no API key. A 22-second film of it: [agent-custody.dev/demo-langchain-kb.mp4](https://agent-custody.dev/demo-langchain-kb.mp4).
134
+
133
135
  LangChain callbacks cannot block a tool, so the handler evaluates no policy; it records what happened, including the `tool_call_id` when one is present, and unwraps `ToolMessage` outputs. For enforcement wrap the function at construction. Do not do both on one tool or it will be recorded twice.
134
136
 
135
137
  ## OpenClaw
@@ -178,6 +180,22 @@ The harness also ships `@deepseek-ai/dsh-hooks-claude-code`, a bridge that runs
178
180
 
179
181
  [packages/python/agent_custody/hermes.py](../../python/agent_custody/hermes.py), through the sidecar like every Python adapter. Hermes runs Python plugins in the agent's process and fires `pre_tool_call(tool_name, args, task_id, **kwargs)`, which may return `{"action": "block", "message": …}`, and `post_tool_call(tool_name, args, result, task_id, duration_ms, **kwargs)`. The plugin is the directory [packages/python/hermes-plugin](../../python/hermes-plugin/): a `plugin.yaml` declaring both hooks and a `sidecar_url` setting, and an `__init__.py` that is one line, `from agent_custody.hermes import register`. Copy it to `~/.hermes/plugins/agent-custody/`, `pip install agent-custody`, start the sidecar, `hermes plugins enable agent-custody`. A denied call is blocked before it runs with the receipt id in the message; an allowed one gets no action, so Hermes's own guardrails and approvals still apply; every completed call is recorded with the Hermes `task_id` as the receipt's session. `hermes_hooks(client)` returns the two callables; `register_hermes(ctx, client)` registers them on a plugin context.
180
182
 
183
+ ## Google ADK
184
+
185
+ [packages/python/agent_custody/adk.py](../../python/agent_custody/adk.py), through the sidecar like every Python adapter. ADK runs `before_tool_callback(tool, args, tool_context)` before every tool call, and a dict returned there skips the tool and becomes its result; `after_tool_callback(tool, args, tool_context, tool_response)` runs after the tool and may replace the response. `adk_callbacks(client)` returns both, keyed by the `LlmAgent` fields they go in:
186
+
187
+ ```python
188
+ from google.adk.agents import LlmAgent
189
+ from agent_custody import Client
190
+ from agent_custody.adk import adk_callbacks
191
+
192
+ agent = LlmAgent(name="billing", model="gemini-2.5-flash", tools=[...], **adk_callbacks(Client()))
193
+ ```
194
+
195
+ `pip install "agent-custody[adk]"` brings in `google-adk[a2a]`. The before callback evaluates the policy: on an enforced deny it records the denial receipt and returns `{"error": "agent-custody: <reason> (receipt <id>)", "agent-custody/receipt": "<id>"}`, so ADK skips the tool and the model sees the receipt as the tool's result; on allow, or with no policy, it returns `None` and the tool runs. If the denial receipt cannot be recorded the call is still skipped. The after callback records the executed call, the result as JSON when it is JSON and as text otherwise, and returns `None`, leaving the response as it was; it recognises the denial dict by its receipt key and does not record it a second time. ADK's `invocation_id` and `function_call_id` are the receipt's session. In observe mode a deny is recorded and the tool runs, as with every adapter. Tested in `tests/test_adk.py` against ADK's own runner with a scripted model and a tool named `stripe.refund`.
196
+
197
+ A delegation an ADK agent makes to another agent over A2A, through `RemoteA2aAgent`, is not a tool call and does not pass through these callbacks. Point the `RemoteA2aAgent` at the gateway's A2A front instead, `agent-custody gateway --a2a`, in [usage.md](usage.md#the-gateway-as-an-a2a-agent): every delegation is then a receipted, policy-checked call, and a refused one never reaches the remote agent. `tests/test_adk_a2a.py` runs that with ADK's own `to_a2a` on the remote side.
198
+
181
199
  ## Any other framework: wrap the function
182
200
 
183
201
  Every agent framework ends up calling a function. Wrap it.
@@ -218,6 +236,7 @@ const bundle = await issuer.record({ tool, args, model, session }, { status: "ex
218
236
  | OpenAI Agents SDK | `wrapTools` | `observeRunner` |
219
237
  | Vercel AI SDK | `wrapTools` | wrap with a policy-less issuer |
220
238
  | LangChain / LangGraph | `tool(issuer.wrap(...))` | `ReceiptCallbackHandler` |
239
+ | Google ADK (Python) | `adk_callbacks`: `before_tool_callback` skips the tool | `after_tool_callback` |
221
240
  | anything else | `issuer.wrap` | `issuer.record` |
222
241
 
223
242
  Record-only adapters evaluate no policy on purpose. A receipt that said "policy: deny" next to "execution: executed" would fail verification, and the verifier would be right: that is not a receipt, that is a finding. Enforce, or observe, but do not pretend.
package/docs/tutorials.md CHANGED
@@ -32,6 +32,9 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
32
32
  | 20 | one gateway for many agents, over HTTP | [20-http-gateway.ts](../examples/20-http-gateway.ts) | a gateway host served over Streamable HTTP, two agents connecting with their own grants and seeing their own tools, receipts naming the right agent, a refusal by grant, and a stranger's grant getting no session | `src/gateway-http.ts`, `src/gateway.ts` |
33
33
  | 21 | OpenClaw plugin hooks | [21-openclaw.ts](../examples/21-openclaw.ts) | the two hooks driven with OpenClaw's event shapes: an allowed call gets no result, a denied one is blocked with the receipt id, executed and failed calls are recorded, every receipt verifies | `src/sdk/openclaw.ts` |
34
34
  | 22 | DeepSeek Harness plugin | [22-deepseek-harness.ts](../examples/22-deepseek-harness.ts) | the module as a plugin, applied by a stand-in context; pre-execute delegating an allowed call and denying one with the receipt id; post-execute recording executed and failed calls; every receipt verifying with the harness's session and call ids | `src/sdk/deepseek-harness.ts` |
35
+ | 23 | a LangChain agent under custody, end to end | [23-langchain-kb-agent.ts](../examples/23-langchain-kb-agent.ts) | a docs agent on LangChain's `createAgent` reading a runbook, refused when it edits one, writing a note that cites its source; three receipts verified with the public key and the log copy; the auditor's report for the refused write. Scripted model, no API key. [23-langchain-kb-agent.tape](../examples/23-langchain-kb-agent.tape) renders it as a film with vhs | `src/sdk/index.ts`, `src/verify.ts` |
36
+ | 24 | an agentic CI/CD merge gate with evidence | [24-agentic-cicd-merge-gate.ts](../examples/24-agentic-cicd-merge-gate.ts) | a release agent merging pull requests through the gateway against a stand-in git host: the risk tier is a policy on facts the gateway fetched itself (diff size, sensitive paths, gate results, human approvals); low merges alone, medium needs a CODEOWNER, high is refused for any agent, production promotion refused; merges pre-committed to the log; an evidence index from the receipts alone, every line verified | `src/gateway.ts`, `src/rest.ts`, `src/verify.ts` |
37
+ | 25 | an agent delegating to an agent over A2A | [25-a2a-delegation.ts](../examples/25-a2a-delegation.ts) | a stand-in document agent speaking A2A 1.0, the gateway serving A2A in front of it with the document agent's card at its own address, an engagement agent delegating twice as an A2A client: one task allowed and answered with the receipt id in its metadata, one refused as a rejected task because it names a privileged matter, the policy deciding on the card the gateway fetched itself; both receipts verified, the allowed one carrying the card as a fact and the authorization logged before the task went out | `src/a2a.ts`, `src/gateway.ts` |
35
38
 
36
39
  ## How policies are defined, in one paragraph
37
40
 
package/docs/usage.md CHANGED
@@ -101,6 +101,20 @@ An upstream need not be an MCP server. A plain HTTP API is described as tools:
101
101
 
102
102
  `{name}` segments in `path` are filled from the call's arguments; the remaining arguments go to the query string on GET and DELETE and to a JSON body otherwise, or `query` names the ones that go to the query and `body: "none"` sends no body. `headers` are sent as written; `headerEnv` maps a header to an environment variable read once at startup, so the credential is never in the file and never reaches the agent, and a missing variable fails at startup. The response body is the tool result, JSON kept as JSON, and a non-2xx status is a failed execution with the API's answer in the receipt. Everything else is unchanged: the tools appear in the grant's scopes, `facts` may name a REST tool for a lookup, `precommit` applies, and each call has a receipt. `rest` can be one of several `upstreams` beside MCP servers. This is how an agent's direct HTTP calls come under custody: they become tool calls through the gateway. Tutorial 17 runs one against a stand-in API.
103
103
 
104
+ Another agent is an upstream too. An agent that speaks the A2A protocol publishes an agent card and takes tasks as messages; described as an upstream, delegating to it becomes a tool call:
105
+
106
+ ```json
107
+ "upstream": {
108
+ "a2a": {
109
+ "url": "https://docs-agent.internal",
110
+ "headerEnv": { "authorization": "DOCS_AGENT_BEARER" },
111
+ "prefix": "docs"
112
+ }
113
+ }
114
+ ```
115
+
116
+ At startup the gateway fetches the agent's card from `<url>/.well-known/agent-card.json` (or `/.well-known/agent.json`, or `url` itself when it ends in `.json`) and offers two tools. `<prefix>.send` delegates a task: `text` is the task as text and the gateway builds the A2A message from it, or `message` is a full A2A message forwarded as it is; `taskId`, `contextId`, `configuration`, and `metadata` are optional and pass through. `<prefix>.card` reads the card, which is how a policy decides on the agent the gateway is actually talking to: `"facts": [{ "name": "card", "tool": "docs.card", "args": {}, "forTools": ["docs.send"] }]` puts it under `context.facts.card`, fetched by the gateway, and `context.args.text` is the task. The card says which wire format the agent speaks, A2A 1.0 (`SendMessage`, `supportedInterfaces`) or 0.3 (`message/send`, `url`), and the gateway speaks that one. The result is the agent's task or message; a streamed delegation is relayed once the agent has finished, and the receipt records the task's final state. A JSON-RPC error from the agent is a failed execution with the error in the receipt. `prefix` defaults to `a2a` (give each A2A upstream its own), `timeoutMs` to 120000, and `headers` and `headerEnv` work as for a REST upstream. `precommit: ["docs.send"]` logs the authorization before the task goes out, as for any consequential tool. An agent that delegates over A2A does not call `docs.send` itself; it reads a card and sends messages, which is what the gateway's A2A front, [below](#the-gateway-as-an-a2a-agent), is for. Tutorial 25 runs both against a stand-in agent.
117
+
104
118
  `logFile` is the local Merkle log, with tree heads signed by the gateway's own key. To log to a server the operator does not control, replace it with `log`:
105
119
 
106
120
  ```json
@@ -131,6 +145,17 @@ You will not normally run this by hand. The agent host spawns it, as below.
131
145
 
132
146
  `agent-custody gateway --config gateway.json --http --port 8790` serves the same gateway as an MCP server over Streamable HTTP at `/mcp`, and every connection presents its own grant: the delegation envelope, base64url-encoded, as `Authorization: Bearer <value>` or `X-Agent-Custody-Grant` on the initialize request. The gateway verifies it against `trustedPrincipalKeys` and its validity window, and opens a session for exactly that grant; a grant signed by a stranger, an expired one, or none at all gets 403 with the reason and no session (403 rather than 401, because MCP clients treat 401 as an OAuth challenge and hide the body). Sessions share the key, the policy, the upstreams, the log, and the fact lookups; each has its own tools (the scopes its grant names), its own receipts (its own principal and agent, attested), and its own consumed facts. `grantFile` in the config is then optional and ignored. A session ends when the client terminates it or after `--idle-minutes` (default 30) without a request; `GET /health` reports the live count and the gateway's key id. The transport is plain HTTP: bind to loopback, a private network, or put TLS in front. From JavaScript, `grantHeader(envelope)` builds the header value; from any language it is `base64url(JSON.stringify(envelope))`. Tutorial 20 runs two agents against one gateway.
133
147
 
148
+ ## The gateway as an A2A agent
149
+
150
+ `agent-custody gateway --config gateway.json --a2a --port 8790 --host 127.0.0.1` serves the gateway as an A2A agent itself, in front of the config's one `a2a` upstream (exactly one is required). An agent that delegates over A2A is pointed at the gateway instead of at the remote agent and needs no other change. With Google ADK:
151
+
152
+ ```python
153
+ from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
154
+ docs = RemoteA2aAgent(name="document_agent", agent_card="http://127.0.0.1:8790/.well-known/agent-card.json")
155
+ ```
156
+
157
+ The gateway serves the remote agent's card at `/.well-known/agent-card.json` (and `/.well-known/agent.json`) with its own address as the endpoint; the card's `signatures` are dropped, since they signed a card that named another address. `POST /` takes JSON-RPC. `SendMessage` and `SendStreamingMessage` (0.3: `message/send` and `message/stream`; the 1.0 HTTP+JSON binding at `POST /message:send` and `POST /message:stream` as well) become a `<prefix>.send` call under the grant in `grantFile`, or under the grant the request presents in `Authorization: Bearer` or `X-Agent-Custody-Grant`, base64url, exactly as for `--http`; every other method, `GetTask`, `CancelTask`, the push notification configs, is forwarded to the remote agent untouched. An allowed delegation answers with the remote agent's task or message with `metadata["agent-custody/receipt"]` set to the receipt id, on every event of a stream too. A refused one answers a task in state `TASK_STATE_REJECTED` (0.3: `rejected`) whose status message reads `agent-custody: <reason> (receipt <id>)`, and nothing reached the remote agent; a delegation the log would not pre-commit is rejected the same way. A remote agent the gateway could not reach is a task in `TASK_STATE_FAILED`; a JSON-RPC error the remote agent answered is relayed as a JSON-RPC error with the receipt id under `error.data.receipt`, and the receipt records the call as failed. `GET /health` reports the fronted agent's name and the gateway's key id. ADK 2.x with a2a-sdk 1.x speaks A2A 1.0 and streams by default; both are handled. Tutorial 25 is the whole thing: a stand-in document agent, the gateway in front of it, an engagement agent delegating twice, one allowed and one refused because the task names a privileged matter, both receipts verified.
158
+
134
159
  ## Wiring it into an agent host
135
160
 
136
161
  The gateway is an ordinary MCP server, so any host that can launch a stdio MCP server can use it. Point the host at the gateway instead of at the upstream server.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.6.18",
3
+ "version": "0.6.19",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Chain of custody for AI agents: signed, independently verifiable receipts for tool calls. MCP gateway + Cedar policy + Merkle transparency log",
6
6
  "license": "Apache-2.0",
@@ -75,14 +75,15 @@
75
75
  "zod": "^4.5.4"
76
76
  },
77
77
  "devDependencies": {
78
+ "@electric-sql/pglite": "0.5.8",
78
79
  "@langchain/core": "^1.2.9",
79
80
  "@openai/agents": "^0.18.0",
80
81
  "@types/node": "^26.4.1",
81
82
  "ai": "^7.0.92",
83
+ "langchain": "1.5.15",
82
84
  "tsx": "^4.23.13",
83
85
  "typescript": "^7.0.2",
84
- "vitest": "^5.0.0",
85
- "@electric-sql/pglite": "0.5.8"
86
+ "vitest": "^5.0.0"
86
87
  },
87
88
  "peerDependencies": {
88
89
  "@langchain/core": ">=1.0.0",