@agent-custody/receipts 0.16.7 → 0.16.9

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.
@@ -0,0 +1,193 @@
1
+ // `agent-custody init refunds`: a working gateway in front of Stripe refunds in one command, and with `--run`, one
2
+ // test-mode refund through it, one refused, and the receipt verified. It is the pilot in a box: what a team needs to see
3
+ // an agent's refund decided by their policy, sent with a key the agent never holds, and checked by someone else.
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { loadConfig } from "./config.js";
7
+ import { generateKeyPair, loadPublicKey, writeKeyPair } from "./crypto.js";
8
+ import { createDelegation } from "./delegation.js";
9
+ import { createGateway, RECEIPT_META_KEY } from "./gateway.js";
10
+ import { formEncode } from "./rest.js";
11
+ import { formatReport, verifyBundle } from "./verify.js";
12
+ export const STRIPE_BEARER_ENV = "AGENT_CUSTODY_STRIPE_BEARER";
13
+ export const STRIPE_KEY_ENV = "STRIPE_SECRET_KEY";
14
+ const AGENT = "refund-agent";
15
+ const PRINCIPAL = "pilot-principal";
16
+ export function refundsPolicy(limit, currency) {
17
+ return `// The agent may read a payment and its refunds, so the gateway can look them up before a refund.
18
+ permit(principal, action == Action::"stripe.payment_intent", resource);
19
+ permit(principal, action == Action::"stripe.refunds", resource);
20
+
21
+ // One refund per payment, of more than 0 and at most ${limit} (minor units, ${currency.toUpperCase()}), only against a
22
+ // payment the gateway itself looked up as succeeded in this currency, never more than it received, and only while the
23
+ // gateway's own lookup finds no refund on it yet. A retry after a lost response finds the first refund and is denied, so
24
+ // it cannot pay twice. context.facts comes from the gateway's own calls to Stripe, never from the agent.
25
+ @reason("one refund per payment, up to the limit, for a payment the gateway saw succeed")
26
+ permit(principal, action == Action::"stripe.refund", resource)
27
+ when {
28
+ context.args has amount &&
29
+ context.args.amount > 0 &&
30
+ context.args.amount <= ${limit} &&
31
+ context.facts has payment &&
32
+ context.facts.payment.status == "succeeded" &&
33
+ context.facts.payment.currency == "${currency}" &&
34
+ context.args.amount <= context.facts.payment.amount_received &&
35
+ context.facts has refunds &&
36
+ context.facts.refunds.data.isEmpty()
37
+ };
38
+ `;
39
+ }
40
+ /** Writes keys, a grant, the policy, and a gateway config into `dir`. Refuses a directory that already holds a config. */
41
+ export function initRefunds(o) {
42
+ const print = o.print ?? ((l) => console.log(l));
43
+ if (!Number.isSafeInteger(o.limit) || o.limit <= 0)
44
+ throw new Error("--limit is a positive whole number of minor units, e.g. 5000 for 50.00");
45
+ if (!/^[a-z]{3}$/.test(o.currency))
46
+ throw new Error("--currency is a three-letter code such as gbp");
47
+ if (!(o.ttlHours > 0))
48
+ throw new Error("--ttl-hours must be positive");
49
+ const dir = resolve(o.dir);
50
+ const configFile = join(dir, "gateway.json");
51
+ if (existsSync(configFile))
52
+ throw new Error(`${configFile} already exists; remove ${dir} to start again, or run with --run`);
53
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
54
+ const gateway = writeKeyPair(generateKeyPair(), join(dir, "keys"), "gateway");
55
+ const principalKp = generateKeyPair();
56
+ const principal = writeKeyPair(principalKp, join(dir, "keys"), "principal");
57
+ print(`1. keys: the gateway's (${gateway.pubFile}) and the principal's, who signs the agent's grant`);
58
+ const now = Date.now();
59
+ const grant = createDelegation(principalKp, {
60
+ version: "0.1",
61
+ principal: PRINCIPAL,
62
+ agent: AGENT,
63
+ scopes: ["stripe.payment_intent", "stripe.refunds", "stripe.refund"],
64
+ issuedAt: new Date(now - 1000).toISOString(),
65
+ expiresAt: new Date(now + o.ttlHours * 3600_000).toISOString(),
66
+ });
67
+ writeFileSync(join(dir, "grant.json"), JSON.stringify(grant, null, 2));
68
+ print(`2. grant.json: ${PRINCIPAL} lets ${AGENT} read payments and their refunds, and refund them, for ${o.ttlHours} hours`);
69
+ writeFileSync(join(dir, "policy.cedar"), refundsPolicy(o.limit, o.currency));
70
+ print(`3. policy.cedar: one refund per payment, up to ${o.limit} ${o.currency.toUpperCase()} minor units, for a payment the gateway saw succeed`);
71
+ const config = {
72
+ identity: { keyFile: "keys/gateway.key" },
73
+ upstream: {
74
+ rest: {
75
+ baseUrl: o.stripeUrl ?? "https://api.stripe.com",
76
+ headerEnv: { authorization: STRIPE_BEARER_ENV },
77
+ tools: [
78
+ { name: "stripe.payment_intent", method: "GET", path: "/v1/payment_intents/{id}", description: "Read a payment", inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } },
79
+ { name: "stripe.refunds", method: "GET", path: "/v1/refunds", description: "List a payment's refunds", inputSchema: { type: "object", properties: { payment_intent: { type: "string" } }, required: ["payment_intent"] } },
80
+ {
81
+ name: "stripe.refund", method: "POST", path: "/v1/refunds", body: "form", description: "Refund a payment, amount in minor units",
82
+ inputSchema: { type: "object", properties: { payment_intent: { type: "string" }, amount: { type: "integer" }, reason: { type: "string" } }, required: ["payment_intent", "amount"] },
83
+ },
84
+ ],
85
+ },
86
+ },
87
+ grantFile: "grant.json",
88
+ trustedPrincipalKeys: ["keys/principal.pub"],
89
+ policyFile: "policy.cedar",
90
+ facts: [
91
+ { name: "payment", tool: "stripe.payment_intent", args: { id: "$args.payment_intent" }, forTools: ["stripe.refund"] },
92
+ { name: "refunds", tool: "stripe.refunds", args: { payment_intent: "$args.payment_intent" }, forTools: ["stripe.refund"] },
93
+ ],
94
+ precommit: ["stripe.refund"],
95
+ receiptsDir: "receipts",
96
+ logFile: "log.jsonl",
97
+ };
98
+ writeFileSync(configFile, JSON.stringify(config, null, 2));
99
+ print(`4. gateway.json: Stripe as the upstream, the key read from ${STRIPE_BEARER_ENV}, each refund authorized in the log before it is sent`);
100
+ print(` principal key: ${principal.pubFile}`);
101
+ return { dir, configFile };
102
+ }
103
+ /**
104
+ * Makes a test-mode payment, refunds part of it through the gateway, asks for a refund over the limit, and verifies the
105
+ * refund's receipt. Refuses any key that is not a Stripe test-mode key, so it cannot move real money.
106
+ */
107
+ export async function runRefunds(o) {
108
+ const env = o.env ?? process.env;
109
+ const f = o.fetch ?? fetch;
110
+ const print = o.print ?? ((l) => console.log(l));
111
+ const dir = resolve(o.dir);
112
+ const configFile = join(dir, "gateway.json");
113
+ if (!existsSync(configFile))
114
+ throw new Error(`${configFile} not found; run init refunds --dir ${o.dir} first`);
115
+ const key = env[STRIPE_KEY_ENV];
116
+ if (!key)
117
+ throw new Error(`${STRIPE_KEY_ENV} is not set: export a Stripe test-mode secret key (sk_test_...)`);
118
+ if (!/^(sk|rk)_test_/.test(key))
119
+ throw new Error(`${STRIPE_KEY_ENV} is not a test-mode key; init refunds --run only runs in Stripe test mode`);
120
+ const cfg = loadConfig(configFile);
121
+ const rest = cfg.upstream && "rest" in cfg.upstream ? cfg.upstream.rest : undefined;
122
+ if (!rest)
123
+ throw new Error(`${configFile} has no REST upstream; it was not written by init refunds`);
124
+ const limit = Number(/context\.args\.amount <= (\d+)/.exec(readFileSync(cfg.policyFile, "utf8"))?.[1]);
125
+ const currency = /context\.facts\.payment\.currency == "([a-z]{3})"/.exec(readFileSync(cfg.policyFile, "utf8"))?.[1];
126
+ if (!Number.isSafeInteger(limit) || !currency)
127
+ throw new Error(`${cfg.policyFile}: cannot read the limit and currency init refunds wrote`);
128
+ const payment = await stripeForm(f, rest.baseUrl, key, "/v1/payment_intents", {
129
+ amount: limit * 2,
130
+ currency,
131
+ payment_method: "pm_card_visa",
132
+ confirm: true,
133
+ automatic_payment_methods: { enabled: true, allow_redirects: "never" },
134
+ });
135
+ const pi = String(payment.id);
136
+ print(`5. a test payment of ${limit * 2} ${currency.toUpperCase()} minor units, made directly with Stripe: ${pi} (${String(payment.status)})`);
137
+ const previous = process.env[STRIPE_BEARER_ENV];
138
+ process.env[STRIPE_BEARER_ENV] = `Bearer ${key}`;
139
+ const gw = await createGateway(cfg);
140
+ try {
141
+ const receiptOf = (r) => {
142
+ const id = String(r._meta?.[RECEIPT_META_KEY]);
143
+ const bundle = JSON.parse(readFileSync(join(cfg.receiptsDir, `${id}.json`), "utf8"));
144
+ return { id, bundle, p: JSON.parse(Buffer.from(bundle.envelope.payload, "base64").toString()).predicate };
145
+ };
146
+ // A refusal counts only when the receipt shows the policy denied it and nothing was sent; a Stripe error is not one.
147
+ const refusedByPolicy = (p) => p.policy?.decision === "deny" && p.execution.status === "denied";
148
+ const over = receiptOf(await gw.handleCall({ name: "stripe.refund", arguments: { payment_intent: pi, amount: limit + 1 } }));
149
+ print(`6. the agent asks for ${limit + 1}, over the limit: ${refusedByPolicy(over.p) ? "refused by policy, and never sent to Stripe" : `not refused by policy (${over.p.execution.status})`}; receipt ${over.id}`);
150
+ const ok = await gw.handleCall({ name: "stripe.refund", arguments: { payment_intent: pi, amount: limit } });
151
+ const refund = receiptOf(ok);
152
+ const receiptId = refund.id;
153
+ const text = ok.content[0]?.text ?? "";
154
+ print(`7. the agent asks for ${limit}: ${refund.p.execution.status === "executed" ? "refunded" : "not done: " + text}; receipt ${receiptId}`);
155
+ const again = receiptOf(await gw.handleCall({ name: "stripe.refund", arguments: { payment_intent: pi, amount: limit } }));
156
+ print(`8. the agent retries the same refund, as after a lost response: ${refusedByPolicy(again.p) ? "refused, because the gateway found the first refund" : `not refused by policy (${again.p.execution.status})`}; receipt ${again.id}`);
157
+ const bundle = refund.bundle;
158
+ const v = verifyBundle(bundle, {
159
+ issuerKeys: [loadPublicKey(cfg.identity.keyFile.replace(/\.key$/, ".pub"))],
160
+ principalKeys: cfg.trustedPrincipalKeys.map(loadPublicKey),
161
+ logFile: cfg.logFile,
162
+ });
163
+ print(`9. the refund's receipt, checked with the gateway's and the principal's public keys and the log: ${v.ok ? "VALID" : "INVALID"}`);
164
+ for (const line of formatReport(v).split("\n").filter((l) => /^RESULT|^tool|^execution|^policy|^authorization/.test(l)))
165
+ print(` ${line}`);
166
+ const verified = v.ok && refund.p.execution.status === "executed";
167
+ const refused = refusedByPolicy(over.p) && refusedByPolicy(again.p);
168
+ if (verified && refused) {
169
+ print(`\nRun the gateway for an agent: export ${STRIPE_BEARER_ENV}="Bearer $${STRIPE_KEY_ENV}" and agent-custody gateway --config ${configFile}`);
170
+ print(`Anyone can check a receipt: agent-custody verify ${join(cfg.receiptsDir, `${receiptId}.json`)} --issuer-key ${cfg.identity.keyFile.replace(/\.key$/, ".pub")} --principal-key ${cfg.trustedPrincipalKeys[0]} --log ${cfg.logFile}`);
171
+ }
172
+ return { paymentIntent: pi, refundReceipt: receiptId, refused, verified };
173
+ }
174
+ finally {
175
+ await gw.close();
176
+ if (previous === undefined)
177
+ delete process.env[STRIPE_BEARER_ENV];
178
+ else
179
+ process.env[STRIPE_BEARER_ENV] = previous;
180
+ }
181
+ }
182
+ async function stripeForm(f, base, key, path, body) {
183
+ const res = await f(new URL(path.replace(/^\//, ""), base.endsWith("/") ? base : `${base}/`), {
184
+ method: "POST",
185
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/x-www-form-urlencoded" },
186
+ body: formEncode(body),
187
+ signal: AbortSignal.timeout(30_000),
188
+ });
189
+ const json = (await res.json().catch(() => ({})));
190
+ if (!res.ok)
191
+ throw new Error(`Stripe ${path}: HTTP ${res.status} ${JSON.stringify(json.error?.message ?? json)}`);
192
+ return json;
193
+ }
package/dist/rest.d.ts CHANGED
@@ -17,6 +17,8 @@ export interface RestOptions {
17
17
  /** the environment the header secrets are read from; default process.env */
18
18
  env?: Record<string, string | undefined>;
19
19
  }
20
+ /** Form-encodes an object, nesting as `a[b]=` and `a[0]=`; null and undefined are left out. */
21
+ export declare function formEncode(value: Record<string, unknown>): string;
20
22
  /** Builds the request for one tool call: path parameters substituted, the rest of the arguments as query or body. */
21
23
  export declare function buildRequest(base: string, tool: RestToolConfig, args: Record<string, unknown>): {
22
24
  url: URL;
package/dist/rest.js CHANGED
@@ -1,5 +1,21 @@
1
1
  import { OPERATION_META_KEY } from "./operations.js";
2
2
  const encode = (v) => encodeURIComponent(typeof v === "string" ? v : JSON.stringify(v));
3
+ /** Form-encodes an object, nesting as `a[b]=` and `a[0]=`; null and undefined are left out. */
4
+ export function formEncode(value) {
5
+ const pairs = [];
6
+ const walk = (key, v) => {
7
+ if (v === null || v === undefined)
8
+ return;
9
+ if (Array.isArray(v))
10
+ return v.forEach((item, i) => walk(`${key}[${i}]`, item));
11
+ if (typeof v === "object")
12
+ return Object.entries(v).forEach(([k, item]) => walk(`${key}[${k}]`, item));
13
+ pairs.push([key, String(v)]);
14
+ };
15
+ for (const [k, v] of Object.entries(value))
16
+ walk(k, v);
17
+ return new URLSearchParams(pairs).toString();
18
+ }
3
19
  /** Builds the request for one tool call: path parameters substituted, the rest of the arguments as query or body. */
4
20
  export function buildRequest(base, tool, args) {
5
21
  const rest = { ...args };
@@ -19,7 +35,7 @@ export function buildRequest(base, tool, args) {
19
35
  url.searchParams.set(name, typeof rest[name] === "string" ? rest[name] : JSON.stringify(rest[name]));
20
36
  delete rest[name];
21
37
  }
22
- const body = method === "GET" || method === "DELETE" || tool.body === "none" ? null : JSON.stringify(rest);
38
+ const body = method === "GET" || method === "DELETE" || tool.body === "none" ? null : tool.body === "form" ? formEncode(rest) : JSON.stringify(rest);
23
39
  return { url, method, body };
24
40
  }
25
41
  /** A REST API as an upstream. Tools are what the config declares; credentials come from the environment at startup, never from the agent. */
@@ -43,7 +59,7 @@ export function restUpstream(name, cfg, opts = {}) {
43
59
  if (!tool)
44
60
  throw new Error(`upstream ${name} has no tool "${params.name}"`);
45
61
  const { url, method, body } = buildRequest(cfg.baseUrl, tool, params.arguments ?? {});
46
- const requestHeaders = new Headers({ accept: "application/json", ...(body !== null ? { "content-type": "application/json" } : {}), ...headers });
62
+ const requestHeaders = new Headers({ accept: "application/json", ...(body !== null ? { "content-type": tool.body === "form" ? "application/x-www-form-urlencoded" : "application/json" } : {}), ...headers });
47
63
  if (tool.idempotencyHeader) {
48
64
  const operation = params._meta?.[OPERATION_META_KEY];
49
65
  if (!operation || typeof operation !== "object" || !Object.hasOwn(operation, "id") || !Object.hasOwn(operation, "idempotencyKey"))
@@ -0,0 +1,14 @@
1
+ /** Replaces the revocation file by rename, so a reader never sees half a list. */
2
+ export declare function writeRevokedGrants(path: string, digests: string[]): void;
3
+ export interface RevocationList {
4
+ /** re-reads the file if it changed; throws when it exists and cannot be read as a JSON array */
5
+ reload(): void;
6
+ /** true when any of `digests` is revoked, as of the last reload */
7
+ has(digests: string[]): boolean;
8
+ /** reloads, adds a digest, and writes the file back when there is one */
9
+ add(digest: string): void;
10
+ /** reloads and returns every revoked digest */
11
+ list(): string[];
12
+ }
13
+ /** The revocation list in `path`; with no path, a list held in memory only. A missing file is an empty list. */
14
+ export declare function createRevocationList(path: string | undefined): RevocationList;
@@ -0,0 +1,53 @@
1
+ // Revoked grants: digests of grant envelopes (`grantDigest` in delegation.ts), in a JSON array the operator edits or
2
+ // `agent-custody revoke` appends to. The gateway and the door read the same file the same way: re-read whenever it
3
+ // changes, so revocation takes effect on the next call or arrival without a restart or a key rotation.
4
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
5
+ /** Replaces the revocation file by rename, so a reader never sees half a list. */
6
+ export function writeRevokedGrants(path, digests) {
7
+ const tmp = `${path}.${process.pid}.tmp`;
8
+ writeFileSync(tmp, JSON.stringify(digests, null, 2) + "\n");
9
+ renameSync(tmp, path);
10
+ }
11
+ /** The revocation list in `path`; with no path, a list held in memory only. A missing file is an empty list. */
12
+ export function createRevocationList(path) {
13
+ const revoked = new Set();
14
+ let seen = "";
15
+ const reload = () => {
16
+ if (!path)
17
+ return;
18
+ if (!existsSync(path)) {
19
+ if (seen !== "absent") {
20
+ revoked.clear();
21
+ seen = "absent";
22
+ }
23
+ return;
24
+ }
25
+ // inode as well as mtime: `revoke` replaces the file by rename, so two writes in one mtime tick are still seen
26
+ const st = statSync(path);
27
+ const m = `${st.ino}:${st.mtimeMs}:${st.size}`;
28
+ if (m === seen)
29
+ return;
30
+ const list = JSON.parse(readFileSync(path, "utf8"));
31
+ if (!Array.isArray(list))
32
+ throw new Error(`${path}: expected a JSON array of grant digests`);
33
+ revoked.clear();
34
+ for (const d of list)
35
+ if (typeof d === "string")
36
+ revoked.add(d);
37
+ seen = m;
38
+ };
39
+ return {
40
+ reload,
41
+ has: (digests) => digests.some((d) => revoked.has(d)),
42
+ add(digest) {
43
+ reload();
44
+ revoked.add(digest);
45
+ if (path)
46
+ writeRevokedGrants(path, [...revoked]);
47
+ },
48
+ list() {
49
+ reload();
50
+ return [...revoked];
51
+ },
52
+ };
53
+ }
@@ -12,12 +12,13 @@ Three labels run through the table:
12
12
 
13
13
  | signal | label | what it means | what it does not mean |
14
14
  | --- | --- | --- | --- |
15
- | `class: "verified"` | checked | A grant signed by a principal in `trustedPrincipalKeys`, inside its validity window, names this agent and lists this arrival's route among its scopes. Or, with no grant, a Web Bot Auth signature checked against the key its signature agent's directory publishes, and the agent is that origin. The Cedar `principal` is that agent | That the agent is well-behaved, that the principal is who they say they are beyond holding the key, or that the request body is what the principal intended. The grant has no revocation list: it stands until it expires. A grant alone is bearer-grade: `signature` says whether the sender also proved it holds the agent's key |
16
- | `class: "claimed"` | a claim | Something was asserted that the door could not accept: a grant from a key it does not trust, an expired one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not verify or was not checked. `grant`, `grantError`, `signature`, and `signatureError` say which | That the arrival is an agent, or that it is hostile. A misconfigured client, a grant for the wrong route, and an impostor all look the same here |
15
+ | `class: "verified"` | checked | A grant signed by a principal in `trustedPrincipalKeys`, inside its validity window, names this agent, lists this arrival's route among its scopes, and is not revoked. Or, with no grant, a Web Bot Auth signature checked against the key its signature agent's directory publishes, and the agent is that origin. The Cedar `principal` is that agent | That the agent is well-behaved, that the principal is who they say they are beyond holding the key, or that the request body is what the principal intended. It stands until it expires unless the door has `revokedGrants` and the grant is listed there. A grant alone is bearer-grade: `signature` says whether the sender also proved it holds the agent's key |
16
+ | `class: "claimed"` | a claim | Something was asserted that the door could not accept: a grant from a key it does not trust, an expired one, a revoked one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not verify or was not checked. `grant`, `grantError`, `signature`, and `signatureError` say which | That the arrival is an agent, or that it is hostile. A misconfigured client, a grant for the wrong route, and an impostor all look the same here |
17
17
  | `class: "unknown"` | observed | Nothing was presented | That the arrival is a person. A browser, a crawler, and a script that sends no headers are all `unknown`. There is no `human` class, and a policy that admits `unknown` on a route admits everything on that route |
18
18
  | `grant: "verified"` | checked | As `class: "verified"` | |
19
19
  | `grant: "out-of-scope"` | checked | The grant verified and is valid, but this route is not among its scopes. `subject` is the agent it names | That the agent may do anything here. The principal did not grant this route |
20
20
  | `grant: "invalid"` | checked | The grant did not verify against a trusted key, did not decode, or is outside its window. `grantError` says which | Who signed it. A grant from an untrusted principal is `invalid` even when it is genuine |
21
+ | `grant: "revoked"` | checked | The grant verified against a trusted key, and it, or a grant above it in its chain, is in the door's `revokedGrants` file; or that file could not be read, which revokes every grant until it can. `grantError` says which | That the agent misbehaved. The operator withdrew the grant, for whatever reason; the revocation file does not record why |
21
22
  | `grant: "wrong-sender"` | checked | The grant verified and is in scope, and the request is signed, verifiably, by a signature agent the grant does not name. The arrival is `claimed` | Which of the two is lying. The grant was handed on or taken; the door does not admit it as the agent it names |
22
23
  | `grant: "absent"` | observed | No grant header | |
23
24
  | `subject` | checked only when `class` is `verified` | The agent a verified grant names; else the signature agent of a verified signature; else the declared name or the agent a rejected grant named; else `unknown` | For a `claimed` arrival, anything. It is recorded so the receipt shows what was asserted; the Cedar `principal` is `Agent::"unknown"` for it |
package/docs/door.md CHANGED
@@ -14,6 +14,8 @@ agent-custody check --config door.json
14
14
  agent-custody door --config door.json --port 8780
15
15
  ```
16
16
 
17
+ To run it as a service, the gateway image has a `door` mode (`docker run ... ghcr.io/svayatta/agent-custody-gateway:<version> door`, config at `/config/door.json`, key created at `/data/keys/door.key`), and [deploy/door](../../../deploy/door/README.md#as-a-reverse-proxy-from-the-gateway-image) has a compose file in front of a stand-in site, Kubernetes manifests, a systemd unit, and the smoke test that every build of the image passes.
18
+
17
19
  ## The config file
18
20
 
19
21
  `door.json`, paths relative to the file. Loaded with `loadDoorConfig(path)`.
@@ -37,7 +39,7 @@ agent-custody door --config door.json --port 8780
37
39
 
38
40
  Every field of the config, with its type and default, is in [the door reference](../../../site/reference/door.md#config).
39
41
 
40
- `agent-custody check --config door.json` reads a door config the way the door would: unknown keys, the key, the principal keys, the policy (including a permit that names an agent without requiring a verified arrival, see below), the routes, what is precommitted, the challenge provider or its absence, the partner engine and its key, the origin's scheme, every credential variable the door reads at startup (origin headers, the log, Splunk, OTel, the capture key, the challenge secret), and the paths. It exits 1 on an error.
42
+ `agent-custody check --config door.json` reads a door config the way the door would: unknown keys, the key, the principal keys, the policy (including a permit that names an agent without requiring a verified arrival, see below), the routes, what is precommitted, the challenge provider or its absence, the partner engine and its key, the revocation file, the origin's scheme, every credential variable the door reads at startup (origin headers, the log, Splunk, OTel, the capture key, the challenge secret), and the paths. It exits 1 on an error.
41
43
 
42
44
  ## What the door knows about an arrival
43
45
 
@@ -45,9 +47,9 @@ The door records one fact for every arrival, `arrival`, observed by the door its
45
47
 
46
48
  | field | values | meaning |
47
49
  | --- | --- | --- |
48
- | `class` | `verified`, `claimed`, `unknown` | `verified`: a grant signed by a trusted principal, inside its window, naming this route among its scopes; or, with no grant, a [Web Bot Auth signature](#web-bot-auth-signatures) that checked against the key its agent's directory publishes. `claimed`: something was asserted that the door could not accept: a grant from a stranger, an expired one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not check or was not checked. `unknown`: nothing was presented |
50
+ | `class` | `verified`, `claimed`, `unknown` | `verified`: a grant signed by a trusted principal, inside its window, naming this route among its scopes; or, with no grant, a [Web Bot Auth signature](#web-bot-auth-signatures) that checked against the key its agent's directory publishes. `claimed`: something was asserted that the door could not accept: a grant from a stranger, an expired one, a revoked one, one for other routes, one presented under another agent's signature, a declared agent name, or a signature that did not check or was not checked. `unknown`: nothing was presented |
49
51
  | `subject` | string | the agent named in a verified grant; else the signature agent of a verified signature (its https origin); else the declared name or the agent a rejected grant named; else `unknown`. Only a verified subject reaches the Cedar `principal` |
50
- | `grant` | `verified`, `out-of-scope`, `invalid`, `wrong-sender`, `absent` | what became of the grant header, with `grantError` when it was not accepted. `wrong-sender`: the grant verified, and the request is signed by a signature agent the grant does not name |
52
+ | `grant` | `verified`, `out-of-scope`, `invalid`, `revoked`, `wrong-sender`, `absent` | what became of the grant header, with `grantError` when it was not accepted. `revoked`: the grant verified, and it or a grant above it in its chain is in `revokedGrants` (see [revoking a grant](#revoking-a-grant)). `wrong-sender`: the grant verified, and the request is signed by a signature agent the grant does not name |
51
53
  | `signature` | `verified`, `invalid`, `unavailable`, `unchecked`, `absent` | what became of an RFC 9421 signature tagged `web-bot-auth`, with `signatureError` when it was not verified. `unchecked`: a `Signature-Input` arrived and the config has no `webBotAuth`, so it is a claim. See [Web Bot Auth signatures](#web-bot-auth-signatures) |
52
54
  | `signatureAgent`, `signatureKeyid` | strings | the `Signature-Agent` origin and the keyid the signature named. Checked only when `signature` is `verified` |
53
55
  | `declared` | string | the `x-agent-custody-agent` header, when sent. A claim |
@@ -65,6 +67,8 @@ There is no `human` class. The door cannot tell a person from a program that pre
65
67
 
66
68
  **A grant alone is bearer-grade; a grant under its agent's signature is bound to its sender.** The door checks the grant's signature, window, and scope. On its own, that does not show that the sender holds the agent's key. Anyone who holds the grant's bytes is that agent until the grant expires, and every verified receipt carries the grant in `delegation`, so a person who can read one receipt can replay its grant. When the request also carries a Web Bot Auth signature that the door verified, and the grant names that signature agent (`"agent": "https://crawler.example"`), the grant is bound to its sender: a thief has the grant's bytes but not the agent's signing key, and a captured signature serves one request (its nonce) for at most `maxAgeSeconds`. A grant presented under another agent's signature is `wrong-sender`, and the arrival is `claimed`. A grant with no signature, or with one that did not verify, is still verified, bearer-grade, as before, so a route that needs the binding says so in its policy: `context.facts.arrival.grant == "verified" && context.facts.arrival.signature == "verified"` holds only for a bound grant, since a mismatch makes `grant` `wrong-sender`. For bearer grants, issue door grants with short lifetimes (minutes, not days), scope them to the routes they need, bound what a route allows per call in the policy, and treat receipt files and logs as holding live credentials until those grants expire.
67
69
 
70
+ **Revoking a grant.** <a id="revoking-a-grant"></a>With `revokedGrants` in the config, a grant can be withdrawn before it expires: the file is the gateway's, a JSON array of grant digests, and `agent-custody revoke --config door.json --grant grant.json` appends one. The door re-reads the file when it changes and checks every grant against it after the signature and before the window and the scope, so a running door classifies the next arrival that carries the grant as `claimed` with `grant: "revoked"`, and the Cedar principal is not the agent. Revoking a grant revokes every grant delegated from it (`grantError` says "a grant above it in its chain has been revoked"). A file that is there and cannot be read stops the door from starting; one that becomes unreadable while it runs makes every grant `revoked` until it can be read, so a broken list never lets a grant through. A missing file is an empty list. Without `revokedGrants`, a grant stands until it expires, and `check` warns when the door trusts principals.
71
+
68
72
  **Challenging a human.** The door builds no CAPTCHA. With `challenge` configured, a page in front of a protected route renders the provider's widget (Cloudflare Turnstile or hCaptcha) with `siteKey`, and sends the token the widget produced in the `challenge.header` header of its request. The door posts the token and the secret from `secretEnv` to the provider's `siteverify` endpoint, with a timeout, and records the answer as `challenge.outcome`. It adds the arrival's address as `remoteip` only with `trustProxy`, where that address is the client's; without it the socket's address may be a proxy's, and the provider would refuse a token the client solved. It never follows a redirect, which would resend the secret and the token elsewhere. To hCaptcha it also sends `siteKey` as `sitekey`: an hCaptcha secret belongs to the account, and without it a token solved on the account's easiest widget would pass on the hardest. A Turnstile secret belongs to one widget already. `success` alone does not pass: the token must have been issued on one of `hostnames`, and for `action` when one is set, or a token solved on another site that uses this site key, or for another widget, would count. At most `maxInFlight` checks wait on the provider at once; an arrival past that is `unavailable`. The token is stripped before the request is relayed, and neither the token nor the secret is recorded. A policy admits a person on a form route with
69
73
 
70
74
  ```cedar
@@ -390,7 +394,7 @@ To record more in clear, give the route a rule of its own, as for the gateway ([
390
394
 
391
395
  A door receipt is a v0.2 receipt with `issuer.kind: "door"` and `issuer.framework: "http"` (`"authz"` when it answered a proxy's check, [below](#behind-nginx-or-envoy-authz-mode)). The route is the tool, observed. `request.args` is the arrival as the table above describes it, claimed. `facts.arrival` is the door's observation; `facts.partner`, when present, is a partner engine's signed verdict, attested ([above](#a-partner-engines-verdict)). When the arrival was verified by a grant, `principal` and `agent` are attested and `delegation` carries the grant. When it was verified by a signature alone, `principal` is `{ id: null, provenance: "claimed" }` and `agent` is the signature agent, observed. Otherwise `principal` is `{ id: null, provenance: "claimed" }` and `agent` is the subject, claimed. `execution.result` for a relayed call is `{ status, contentType?, bodyBytes, bodyDigest }`: the origin's body is never copied into the receipt, only committed to.
392
396
 
393
- The verifier runs `door receipt carries a policy decision` in place of the gateway's two checks, and otherwise the same checks: a verified arrival's receipt passes `delegation binds principal and agent` and `executed tool within delegated scope`; an unknown arrival's passes `principal is claimed, not attested`; a receipt that carries an `authorization` passes the authorization checks, including `authorization logged before execution`. Both verifiers, the Python verifier, and `policy simulate` accept door receipts; the conformance vectors `door-unknown-executed`, `door-unknown-denied`, and `door-verified-executed` pin them.
397
+ The verifier runs `door receipt carries a policy decision` in place of the gateway's two checks, and otherwise the same checks: a verified arrival's receipt passes `delegation binds principal and agent` and `executed tool within delegated scope`; an unknown arrival's passes `principal is claimed, not attested`; a receipt that carries an `authorization` passes the authorization checks, including `authorization logged before execution`. Both verifiers, the Python verifier, and `policy simulate` accept door receipts; the conformance vectors `door-unknown-executed`, `door-unknown-denied`, and `door-verified-executed` pin them. The `door-grant-*` vectors pin each passport the door may be shown: an expired grant, one signed by a key it does not trust, a revoked grant, a delegated grant (with `delegation chain to the principal`), and a delegated grant whose parent was revoked. Each one the door refuses is a claimed arrival whose receipt verifies with no delegation; the `resigned-door-grant-*` vectors paste the refused grant into the receipt as if the door had accepted it, and fail `delegation valid at receipt time` or `delegation signature (principal key)`.
394
398
 
395
399
  ## Behind nginx or Envoy: authz mode
396
400
 
@@ -426,7 +430,6 @@ A site that already runs nginx or Envoy need not send its traffic through the do
426
430
  - Check AP2 mandates.
427
431
  - Check every Web Bot Auth signature: Ed25519 only (no RSA-PSS or ECDSA), the components listed above only, no `Content-Digest`, no response signatures on the directory, and nonces in one process's memory. A signature agent must be listed in `agents`; the door does not fetch the directory of an origin it was not told about.
428
432
  - Challenge an arrival with a passkey. Turnstile and hCaptcha are the providers; see [challenging a human](#challenging-a-human).
429
- - Revoke a grant by a revocation list; a grant stands until it expires.
430
433
  - Bind a grant to its sender without a signature. A grant presented alone is bearer-grade; under its agent's Web Bot Auth signature it is bound: see [presenting a passport](#what-the-door-knows-about-an-arrival).
431
434
  - Stream a request body: the body is read whole, up to `maxBodyBytes`, so that the policy can read it and the receipt can commit to it.
432
435
  - Relay a response larger than `maxResponseBytes`, or stream one: the body is relayed whole so that its digest can be recorded. A larger one is not held: reading stops at the limit, the client gets 502, and the receipt records that the origin answered.
package/docs/egress.md CHANGED
@@ -9,6 +9,8 @@ The gateway holds an agent's tool credentials and receipts every call made throu
9
9
  - relays the connection or refuses it;
10
10
  - signs a receipt either way, with `issuer.kind: "egress"`. The receipt goes to the log like any other.
11
11
 
12
+ ![The egress witness, animated: a locked-down agent pod reaches the outside only through the gateway or the witness. A direct call to Stripe is refused and receipted, a permitted host is relayed and receipted by bytes and times, a connection with no proxy credential is refused, and one that ignores the proxy is dropped by the network policy with no receipt.](../../../site/public/egress-witness.svg)
13
+
12
14
  **It needs lockdown.** A proxy alone is advice: an agent can ignore `HTTPS_PROXY` and connect directly. The witness means something only when the agent's network reaches nothing but the gateway and the witness. The witness runs anywhere Node 22 runs, but the lockdown belongs to the platform the agent runs on. `deploy/gateway/lockdown` ships it for Kubernetes (a NetworkPolicy), docker compose (an internal network), and a Linux VM or bare metal (`lockdown/vm`: an nftables rule on the agent's Unix user, a systemd drop-in for the agent's unit, a unit for the witness, and a script that runs the lockdown checks). On a cloud task or a laptop, you build the default-deny egress with that platform's own firewall. [Credential custody and lockdown](../../../site/guide/credential-custody.md) explains each.
13
15
 
14
16
  **What it cannot see.** Every page about the witness repeats this list:
@@ -20,7 +20,7 @@ jobs:
20
20
  runs-on: ubuntu-latest
21
21
  steps:
22
22
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
23
- - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.7
23
+ - uses: svayatta/agent-custody@<commit sha of the release> # 0.16.9
24
24
  with:
25
25
  path: .custody/receipts
26
26
  issuer-key: .custody/keys/agent.pub
@@ -37,7 +37,7 @@ Pin the action to the commit of a release, as you pin every other action. A movi
37
37
  | `principal-key` | the public key files of the principals whose grants a gateway receipt carries, one path on each line; SDK and Claude Code hook receipts need none | |
38
38
  | `log-url` | the URL of the log; the action fetches the log key from it (`verify --log-url`) | |
39
39
  | `log-id` | the id that every tree head must name (`verify --log-id`) | |
40
- | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.7` |
40
+ | `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.9` |
41
41
  | `github-token` | a token that can write pull request comments; an empty value writes the job summary only | `github.token` |
42
42
  | `comment-author` | the login of the account that `github-token` posts as; the action edits only a comment from this account | `github-actions[bot]` |
43
43
 
package/docs/policies.md CHANGED
@@ -12,7 +12,7 @@ For an intercepted call to tool `T` by the agent named in the grant:
12
12
  | `action` | `Action::"<T>"` |
13
13
  | `resource` | `Tool::"<T>"` |
14
14
  | `context.args` | the call's arguments, exactly as the agent sent them. **Provenance: claimed.** |
15
- | `context.facts` | results of the gateway's own upstream lookups configured in `facts`. **Provenance: observed.** |
15
+ | `context.facts` | results of the gateway's own upstream lookups configured in `facts`. In Cedar, a `null` field is left out, because Cedar has no null, so `context.facts.payment has description` is false when Stripe returned `"description": null`; a `null` inside a list denies the call, because leaving it out would move the elements after it. The receipt keeps the result as returned, and Rego and OPA policies see it unchanged. **Provenance: observed.** |
16
16
  | `context.grant` | `{ principal, scopes }` from the signed delegation. **Provenance: attested.** |
17
17
 
18
18
  No entity hierarchy or schema is loaded yet, so policies reason about `context` and the three identifiers above.
package/docs/sdk.md CHANGED
@@ -167,6 +167,17 @@ agent-custody report --config ~/.config/agent-custody/sdk.json
167
167
 
168
168
  `node examples/38-incident-replay.ts` runs the hook in enforce mode with scripted events. `terraform plan` runs. `terraform destroy -auto-approve` and `rm -rf ~` are denied before they run, and a reviewer verifies the denial receipts with the public key only. The page [An incident replay](../../../site/guide/incident-replay.md) shows the output and the limit: a credential in the agent's environment goes around the hook.
169
169
 
170
+ ### What the hook does not stop
171
+
172
+ The hook stops a shell command, a file edit, or an MCP tool call that the agent makes. Read these limits before you rely on it.
173
+
174
+ - **A credential in the agent's environment goes around the hook.** If the shell of the agent holds a cloud key or a database password, a process that the agent starts can use it. The hook does not stop that process.
175
+ - **The starter list matches the text of a command.** It catches the plain form of each command. It is not a sandbox.
176
+ - **Some tools are not seen.** The hook matches `Bash`, `Write`, `Edit`, `MultiEdit`, `NotebookEdit`, and MCP tools. It does not see `Read`, `Grep`, `Glob`, `WebFetch`, `WebSearch`, or `Task`. The starter deny list has rules for `Bash` only.
177
+ - **The record is the agent's own report.** Every field is `claimed`. The signature shows that the record did not change after the hook wrote it. It does not show that the hook saw every call.
178
+
179
+ To cover more, keep production credentials out of the agent's environment, and put a gateway between the agent and the tools that touch production. [Credential custody and egress lockdown](../../../site/guide/credential-custody.md) shows how. The [threat model](threat-model.md) lists what each part defends, and what it does not. No independent witness runs yet, and the hosted log is not anchored on mainnet yet.
180
+
170
181
  ### Register the hook by hand
171
182
 
172
183
  Register the hook command in `.claude/settings.json`. The same command handles all three events.
package/docs/tutorials.md CHANGED
@@ -49,7 +49,7 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
49
49
  | 37 | receipts on a pull request | [37-pr-summary.ts](../examples/37-pr-summary.ts) | two receipts from a gateway verify into one Markdown table (what `verify --markdown` and the GitHub Action post); one changed byte makes the table name the failed check; a directory with no receipt fails | `src/pr-summary.ts`, `action.yml` |
50
50
  | 38 | an incident replay | [38-incident-replay.ts](../examples/38-incident-replay.ts) | the same setup as `init claude-code --enforce`, in a temporary home; a scripted Claude Code session that runs the real hook command for each event: `terraform plan` runs and gets an executed receipt, `terraform destroy -auto-approve` and `rm -rf ~` are denied before they run, with the denial text and the receipt id; a reviewer with only the public key verifies all three receipts, and a stranger's key fails | `src/sdk/claude.ts`, `src/claude-init.ts`, `templates/claude-code.cedar` |
51
51
  | 39 | exporting receipts to a pull request | [39-export.ts](../examples/39-export.ts) | an agent works under a capture rule; `export` copies the two receipts that withhold their values, byte for byte, and refuses the one that records plain values; one changed byte makes it refuse a third | `src/export.ts`, `src/cli.ts` |
52
- | 40 | the door: a receipted reverse proxy in front of your own API | [40-door.ts](../examples/40-door.ts) | a stand-in shop behind the door; an unknown arrival reads the catalogue and is refused a refund; an agent with a grant signed by the shop's principal is verified and refunds within the policy, refused above it; a forged grant is claimed; the origin saw only what was allowed; both receipts verified | `src/door.ts`, `src/config.ts` |
52
+ | 40 | the door: a receipted reverse proxy in front of your own API | [40-door.ts](../examples/40-door.ts) | a stand-in shop behind the door; an unknown arrival reads the catalogue and is refused a refund; an agent with a grant signed by the shop's principal is verified and refunds within the policy, refused above it; a forged grant is claimed, and so is the grant once the shop revokes it, with no restart; the origin saw only what was allowed; both receipts verified | `src/door.ts`, `src/config.ts` |
53
53
  | 41 | the egress witness: a receipted forward proxy for calls around the gateway | [41-egress.ts](../examples/41-egress.ts) | a locked-down agent tries a direct call to a payment provider (CONNECT api.stripe.com:443) and the witness refuses it; an allowed tunnel to a stand-in docs mirror is relayed and recorded by destination and byte counts, never its contents; a connection with no proxy credential gets 407; the refusal's receipt verifies with the witness's key | `src/egress.ts`, `src/config.ts` |
54
54
  | 42 | a first egress policy from what the agents did in observe mode | [42-egress-draft.ts](../examples/42-egress-draft.ts) | the witness observes an agent reach a docs mirror three times and a paste site once; `egress draft-policy` verifies the receipts and drafts one permit with a count and first and last time per destination, under a warning that it permits everything the agent did; the review deletes the paste site, and the enforced policy relays the mirror and refuses the paste site | `src/egress-draft.ts` |
55
55
  | 43 | an OWASP ACS Guardian whose decisions land in a transparency log | [43-acs-guardian.ts](../examples/43-acs-guardian.ts) | a log runs under a key of its own; the ACS README's sample `steps/toolCallRequest` piped through `agent-custody acs` is allowed, its receipt carries the session's `chain_hash`, and it verifies offline with only the Guardian's and the log's public keys; in one session a read outside `/reports` is denied, a result for an allowed request passes, and a result for an unknown request is denied; a consistency proof shows the log after the deny extends the log that held the first decision (ACS issue #18, directions 1 and 3) | `src/acs.ts`, `src/config.ts` |
@@ -59,6 +59,7 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
59
59
  | 47 | the door checks Web Bot Auth signatures | [47-web-bot-auth.ts](../examples/47-web-bot-auth.ts) | a crawler publishes its Ed25519 key in a directory at its own origin (served by a stub here) and signs each request (RFC 9421, tag `web-bot-auth`); unsigned it is unknown and refused, signed it is verified as `https://crawler.example` with no grant and the directory is fetched once; the same request again is a replay, a signature made for another site is refused; a grant naming the crawler under its signature is bound to its sender, another agent's grant under it is `wrong-sender`; the receipts verify | `src/web-bot-auth.ts`, `src/door.ts`, `src/config.ts` |
60
60
  | 48 | the door in-process: Express middleware and a Next.js route-handler wrapper | [48-door-app.ts](../examples/48-door-app.ts) | `door.json` without an origin; an Express shop with `app.use(door)` before `express.json()`; an unknown arrival reads the catalogue and is refused a refund that the app never sees; an agent with a grant refunds £45, committed to the log before the app runs, its body reaching `express.json()` and its grant stripped; the same door wraps a fetch-style `POST` handler as a Next.js route; every receipt records the app's status and body digest and verifies | `src/door-app.ts`, `src/door.ts` |
61
61
  | 49 | the door behind stock nginx or Envoy: authz checks instead of relaying | [49-door-authz.ts](../examples/49-door-authz.ts) | the door with `authz: true` answers checks as nginx `auth_request` sends them (`X-Original-Method`, `X-Original-URI`): a catalogue read 200 and an unknown refund 403; a verified agent's refund is committed to the log before the 200; a check that names no original request is refused 400 with no receipt; each receipt verifies and its report says it records the decision, not the origin's answer. `deploy/door/demo.sh` runs the real nginx and Envoy | `src/door.ts`, `src/config.ts` |
62
+ | 50 | the refund pilot in one command: `init refunds`, then `--run` | [50-init-refunds.ts](../examples/50-init-refunds.ts) | keys, a grant, a refund policy and a Stripe gateway config written in one call; a test payment, an over-limit refund refused before Stripe, a refund through the gateway, a retry refused because the gateway finds the first refund, and the receipt verified, against a stand-in Stripe |
62
63
  | 52 | the door asks a partner detection engine, and the engine signs its verdict | [52-door-partner-verdict.ts](../examples/52-door-partner-verdict.ts) | a stub engine (`scripts/fake-partner.ts`) signs a verdict for each arrival's receipt and route; a browser's `human` verdict is relayed and a bot's refused by a policy on `context.facts.partner`; the receipt carries the verdict as an attested fact and verifies with the engine's key as an upstream key, and not without it; a verdict replayed from another arrival is refused with 503, and so is an arrival when the engine times out (`onFailure: "deny"`), even on a route the policy alone would allow | `src/door-partner.ts`, `src/door.ts` |
63
64
 
64
65
  ## How policies are defined, in one paragraph
package/docs/usage.md CHANGED
@@ -94,16 +94,16 @@ An upstream need not be an MCP server. A plain HTTP API is described as tools:
94
94
  "baseUrl": "https://api.stripe.com",
95
95
  "headerEnv": { "authorization": "STRIPE_BEARER" },
96
96
  "tools": [
97
- { "name": "customer.lookup", "method": "GET", "path": "/v1/customers/{customer_id}",
98
- "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" } }, "required": ["customer_id"] } },
99
- { "name": "stripe.refund", "method": "POST", "path": "/v1/refunds", "description": "Refund a customer, amount in minor units",
100
- "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" }, "amount": { "type": "integer" } }, "required": ["customer_id", "amount"] } }
97
+ { "name": "stripe.payment_intent", "method": "GET", "path": "/v1/payment_intents/{id}",
98
+ "inputSchema": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] } },
99
+ { "name": "stripe.refund", "method": "POST", "path": "/v1/refunds", "body": "form", "description": "Refund a payment, amount in minor units",
100
+ "inputSchema": { "type": "object", "properties": { "payment_intent": { "type": "string" }, "amount": { "type": "integer" } }, "required": ["payment_intent", "amount"] } }
101
101
  ]
102
102
  }
103
103
  }
104
104
  ```
105
105
 
106
- `{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.
106
+ `{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; `body: "form"` sends `application/x-www-form-urlencoded` instead, nesting objects and arrays as `a[b]` and `a[0]` and leaving out nulls, which is what Stripe's v1 API reads. `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. `agent-custody init refunds` writes this setup for Stripe in one command, with a refund policy, a grant, and keys, and `--run` makes a test-mode refund through it and verifies the receipt ([getting started](../../../site/guide/getting-started.md#stripe-refunds-in-one-command), tutorial 50).
107
107
 
108
108
  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:
109
109
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.16.7",
3
+ "version": "0.16.9",
4
4
  "mcpName": "io.github.svayatta/agent-custody",
5
5
  "description": "Proof of what your AI agents did. Give your agents real power, without losing control of them: signed, verifiable receipts for tool calls, an MCP gateway with Cedar or Rego policy, and a Merkle transparency log.",
6
6
  "license": "Apache-2.0",