@agent-custody/receipts 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
1
+ # Configuring the gateway
2
+
3
+ Who may use which tools, and where those tools live, is set in three files and a few environment variables. This page is the map: what each one decides, how they fit together, a worked example with two agents on one shared gateway, how it all works in the Docker image, and how to check a config before you start. The full list of config keys is in [the gateway reference](/reference/gateway); the Cedar language is in [policies.md](policies.md).
4
+
5
+ ## What you configure, and where
6
+
7
+ | what | file | written by | decides |
8
+ | --- | --- | --- | --- |
9
+ | **The grant** | `<agent>.grant.json`, signed | the principal (the person or organisation delegating), with `agent-custody grant` | which agent may use which tool names, until when |
10
+ | **The policy** | `policy.cedar` | the operator or security owner | whether this particular call, with these arguments and these facts, is allowed |
11
+ | **The gateway config** | `gateway.json` | the operator | where the tools live (the upstreams), what the gateway looks up for itself (facts), which tools are consequential (`precommit`), where receipts and the log go |
12
+ | **Credentials** | environment variables | the operator | the tokens the gateway uses to reach the tools; never in a file, never in an agent |
13
+
14
+ The agent configures none of them. It connects to the gateway as an MCP server, presents its grant, and sees only the tools the grant names.
15
+
16
+ A complete, usable layout, one config directory with a policy, is in [deploy/gateway/example](https://github.com/svayatta/agent-custody/tree/main/deploy/gateway/example).
17
+
18
+ ## How a call is decided
19
+
20
+ For each call, in this order, and a refusal at any step is a signed receipt:
21
+
22
+ 1. **The grant** is valid, signed by a trusted principal, inside its window, and not revoked.
23
+ 2. **The tool** is one of the grant's scopes.
24
+ 3. **Facts** the policy needs are fetched by the gateway from an upstream (`facts` in the config).
25
+ 4. **The Cedar policy** permits the call. No matching `permit` means deny.
26
+ 5. **For `precommit` tools**, the authorization is committed to the log before anything is forwarded.
27
+ 6. **The call** is forwarded to the upstream that owns the tool.
28
+
29
+ The one thing that ties all of it together is the **tool name**. The grant's scopes, the policy's `action == Action::"..."`, `facts`, and `precommit` all name the tools the upstreams offer, so a name that is spelled differently in one place is a rule that never applies.
30
+
31
+ ## Tool names
32
+
33
+ - A **REST** upstream's tool names are the ones you give them in `tools[].name`.
34
+ - An **A2A** agent offers `<prefix>.send` and `<prefix>.card`, with the prefix you choose.
35
+ - An **MCP** server (stdio or HTTP) offers whatever names the server defines. Run `agent-custody check --config gateway.json --connect` to print them.
36
+ - **One owner per tool.** If two upstreams offer the same name the gateway refuses to start. Give REST and A2A tools a prefix (`billing.refund`, `docs.send`) and the collision cannot happen.
37
+
38
+ ## A worked example: two agents, one shared gateway
39
+
40
+ A support agent may look customers up and refund them up to 1,000.00, and only for customers the gateway itself found to be verified. A reporting agent may only read. Both reach the same tools through one gateway.
41
+
42
+ **1. The principal issues one grant per agent.** On the principal's machine, with a key that never goes near the gateway:
43
+
44
+ ```bash
45
+ agent-custody grant --key principal.key --principal acme-support --agent support-agent \
46
+ --scopes customer.lookup,billing.refund,kb.search,docs.send --ttl-hours 8 --out support-agent.grant.json
47
+ agent-custody grant --key principal.key --principal acme-support --agent report-agent \
48
+ --scopes customer.lookup,kb.search --ttl-hours 8 --out report-agent.grant.json
49
+ ```
50
+
51
+ The grants limit *which tools*. The report agent's grant has no `billing.refund`, so it never sees that tool and the policy is not even asked.
52
+
53
+ **2. The operator writes one policy for both.** It limits *how* a tool may be used:
54
+
55
+ ```cedar
56
+ // anything in a grant's scopes may read
57
+ permit(principal, action == Action::"customer.lookup", resource);
58
+ permit(principal, action == Action::"kb.search", resource);
59
+
60
+ // refunds: only the support agent, a positive amount of at most 1,000.00 (integer minor units), and only for a
61
+ // customer the gateway itself found to be verified. The gateway does not enforce a tool's inputSchema, so the policy
62
+ // bounds the amount from below as well. context.facts comes from the gateway's own lookup, never from the agent.
63
+ permit(principal == Agent::"support-agent", action == Action::"billing.refund", resource)
64
+ when {
65
+ context.args.amount > 0 &&
66
+ context.args.amount <= 100000 &&
67
+ context.facts has customer &&
68
+ context.facts.customer.verified == true
69
+ };
70
+
71
+ // delegating a task to the docs agent: the support agent only
72
+ permit(principal == Agent::"support-agent", action == Action::"docs.send", resource);
73
+ ```
74
+
75
+ **3. The operator writes the gateway config.** One file, four kinds of upstream, one remote log:
76
+
77
+ ```json
78
+ {
79
+ "identity": { "keyFile": "/data/keys/gateway.key" },
80
+ "upstreams": [
81
+ {
82
+ "name": "billing",
83
+ "rest": {
84
+ "baseUrl": "https://billing.internal.example.com",
85
+ "headerEnv": { "authorization": "BILLING_API_AUTHORIZATION" },
86
+ "tools": [
87
+ { "name": "customer.lookup", "method": "GET", "path": "/v1/customers/{customer_id}",
88
+ "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" } }, "required": ["customer_id"] } },
89
+ { "name": "billing.refund", "method": "POST", "path": "/v1/refunds",
90
+ "description": "Refund a customer. amount is in minor units.",
91
+ "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string" }, "amount": { "type": "integer" } }, "required": ["customer_id", "amount"] } }
92
+ ]
93
+ }
94
+ },
95
+ { "name": "github", "url": "https://mcp.internal.example.com/github", "tokenEnv": "GITHUB_MCP_TOKEN" },
96
+ { "name": "kb", "command": "kb-mcp-server", "args": ["--root", "/srv/kb"], "env": { "KB_MODE": "read-only" } },
97
+ { "name": "docs", "a2a": { "url": "https://docs-agent.internal.example.com", "headerEnv": { "authorization": "DOCS_AGENT_BEARER" }, "prefix": "docs" } }
98
+ ],
99
+ "trustedPrincipalKeys": ["keys/principal.pub"],
100
+ "policyFile": "policy.cedar",
101
+ "facts": [
102
+ { "name": "customer", "tool": "customer.lookup", "args": { "customer_id": "$args.customer_id" }, "forTools": ["billing.refund"] }
103
+ ],
104
+ "precommit": ["billing.refund", "docs.send"],
105
+ "revokedGrants": "/data/revoked.json",
106
+ "receiptsDir": "/data/receipts",
107
+ "log": { "url": "https://log.agent-custody.dev/t/acme/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN", "hashOnly": true, "keys": ["keys/log.pub"] }
108
+ }
109
+ ```
110
+
111
+ What each part does:
112
+
113
+ | key | what it says here |
114
+ | --- | --- |
115
+ | `identity.keyFile` | the gateway's signing key, in `/data` because the gateway writes and keeps it. Verifiers check receipts against its public half. |
116
+ | `upstreams` | four tool sources behind one gateway: a REST API described as tools, an MCP server over HTTP, an MCP server the gateway starts, and another agent over A2A. |
117
+ | `…headerEnv`, `tokenEnv` | the **name** of an environment variable holding the credential. The gateway reads it at startup and refuses to start without it. The secret is never in the file. |
118
+ | `kb.env` | what the started MCP server gets. A stdio upstream gets a minimal environment and nothing of the gateway's own, so it cannot read the other upstreams' tokens. |
119
+ | `trustedPrincipalKeys` | the public keys whose grants this gateway accepts. Only public keys go here. |
120
+ | `facts` | before a refund, the gateway calls `customer.lookup` itself with the customer id from the call, and the policy reads the answer as `context.facts.customer`. |
121
+ | `precommit` | the consequential tools: the gateway commits the authorization to the log before it forwards, and withholds the call if the log will not take it. |
122
+ | `requirePrecommit` | with a remote log, the gateway does not start when `precommit` is empty. Without it, the gateway prints a warning. |
123
+ | `revokedGrants` | the file `agent-custody revoke` appends to; the gateway re-reads it on every call. |
124
+ | `receiptsDir`, `log` | full receipts stay on the gateway's disk. The hosted log receives only their hashes (`hashOnly`), and its public key is pinned (`keys`), which `precommit` with a remote log requires. |
125
+
126
+ Paths in `gateway.json` are resolved relative to the file, so `keys/principal.pub` sits beside it, and absolute paths are left as they are.
127
+
128
+ **4. Each agent presents its own grant** when it connects: the grant file, base64url-encoded, as `Authorization: Bearer <value>` or `X-Agent-Custody-Grant`. [The gateway guide](usage.md#one-gateway-for-many-agents-over-http) and [wiring it into an agent host](usage.md#wiring-it-into-an-agent-host) show how for each host. Adding a third agent is issuing it a grant. The gateway config does not change.
129
+
130
+ **Retries and money.** This config does not use `operations`, so the gateway cannot tell a retry from a second refund: an agent that repeats `billing.refund` after a timeout sends a second POST. For real money, configure [financial operations](financial-operations.md): each refund gets a durable identity and an idempotency key your API must honor, its amount is reserved against a daily budget before it is forwarded, and an uncertain outcome is closed by reading your API's own record. It needs the calling agent to send a persistent operation id in the call's `_meta`, an API that honors the idempotency key, and a read tool that returns the refund by that key.
131
+
132
+ ## The principal's key
133
+
134
+ A grant is only as good as the key that signed it, so this is the key to handle with the most care. There are several keys in a deployment, and they are different:
135
+
136
+ | key | who holds the private half | what the public half is for |
137
+ | --- | --- | --- |
138
+ | **The principal's key** | the person or organisation delegating authority, on their own machine | the gateway's `trustedPrincipalKeys`: it recognises a grant as genuine because this key signed it. A verifier also takes it, as `--principal-key`. |
139
+ | **The gateway's key** | the gateway only, in `/data/keys` | verifiers check receipts against it (`--issuer-key`) |
140
+ | **The log's key** | the log's signer | a verifier or a gateway pins it (`log.keys`, `--log-key`) |
141
+
142
+ **Make it where grants are issued, not where the gateway runs.**
143
+
144
+ ```bash
145
+ agent-custody keygen --dir ./principal --name principal
146
+ ```
147
+
148
+ This writes `principal.key`, the private key, in PEM (PKCS#8) with mode 0600, and `principal.pub`, the public key, in PEM (SPKI), and prints the **key id**, the sha256 of the public key. Write the key id down: it is how you confirm, after copying, that the gateway holds the key you made.
149
+
150
+ **Keep the private key off the gateway.** The gateway never needs it, and a gateway that held it would let anyone who broke into the gateway sign grants for any agent and any tool. So `principal.key` does not go in the gateway's config directory, the image, a ConfigMap, the repository, or CI. Keep it on the machine of whoever issues grants, on an encrypted disk or in a password or secrets manager, and back it up encrypted. `agent-custody grant --key principal.key` reads it from a file, so run that command where the file is.
151
+
152
+ **Give the gateway the public key only.** Copy `principal.pub` into the gateway's config and list it:
153
+
154
+ ```json
155
+ "trustedPrincipalKeys": ["keys/principal.pub"]
156
+ ```
157
+
158
+ In the Docker image that is `/config/keys/principal.pub`, mounted read-only; on Kubernetes it can sit in the ConfigMap, because it is public. List several keys to trust several principals: a grant is accepted when any listed key signed it, and one gateway can serve more than one organisation. A grant signed by a key that is not listed is refused when the agent connects (`delegation grant rejected`). The `--principal` name in a grant (`acme-support`) is only a label that receipts record; the trust is in the key.
159
+
160
+ **Rotating it.** The gateway reads `trustedPrincipalKeys` when it starts, so a rotation is: make the new key pair; add the new public key to the list beside the old one and restart the gateway; issue new grants with the new key; when the old key's grants have expired or been revoked (grants last hours, so this is short), remove the old public key and restart. Verifiers need the new `--principal-key` as well, and accept both while old receipts matter.
161
+
162
+ **If it is lost,** nothing already issued stops working, but no new grant can be signed: make a new pair and add its public key as above. **If it leaks,** remove its public key from `trustedPrincipalKeys` and restart the gateway, which ends open sessions and refuses every grant it signed from then on, and revoke any grant you want refused before that (`agent-custody revoke`). Then make a new pair.
163
+
164
+ `agent-custody init` in the Docker image writes a *demo* principal key under `/config/demo` so that you can try the gateway in a minute. Delete that directory before production, and make the real key where grants are issued.
165
+
166
+ ## In the Docker image
167
+
168
+ The same `gateway.json` works in the [gateway image](https://github.com/svayatta/agent-custody/blob/main/deploy/gateway/README.md), with these rules:
169
+
170
+ - **Mount the config read-only at `/config`** (`gateway.json`, `policy.cedar`, and the principals' and log's **public** keys) and a **volume at `/data`**. Relative paths in the file resolve against `/config`.
171
+ - **Anything the gateway writes needs an absolute path under `/data`**: the key, `receiptsDir`, `logFile`, `revokedGrants`. `/config` is read-only, so `"receiptsDir": "receipts"` fails.
172
+ - **Credentials come from the container's environment** (`--env-file`, a compose `.env`, a Kubernetes Secret), under the variable names the config gives.
173
+ - **The gateway key is created on the first start** at the path `identity.keyFile` names, if the file is absent. Keep the volume.
174
+ - **REST, A2A, and MCP-over-HTTP upstreams work as they are.** A **stdio** MCP server (`command`) has to be inside the image. Build on it:
175
+
176
+ ```dockerfile
177
+ FROM ghcr.io/svayatta/agent-custody-gateway:<version>
178
+ USER root
179
+ RUN npm install -g kb-mcp-server
180
+ USER custody
181
+ ```
182
+
183
+ - `docker run ... <image> init` writes a starter config into an empty `/config`. [The gateway README](https://github.com/svayatta/agent-custody/blob/main/deploy/gateway/README.md) has the whole run, and the limits of a shared gateway.
184
+
185
+ ## Check it before you start it
186
+
187
+ `agent-custody check --config gateway.json` reads the config the way the gateway would and reports what would go wrong at startup:
188
+
189
+ ```bash
190
+ agent-custody check --config gateway.json --connect
191
+ docker run --rm -v "$PWD/config:/config:ro" -v gateway-data:/data --env-file .env <image> check --config /config/gateway.json --connect
192
+ ```
193
+
194
+ | it checks | an error or a warning |
195
+ | --- | --- |
196
+ | the config parses, with each problem and its path | **error** |
197
+ | a key that is not in the schema (a typo such as `precomit` is otherwise silently ignored, and the setting stays at its default) | **error**, with the key it nearly is |
198
+ | the gateway key loads, and is not readable by other users | error, and a warning |
199
+ | every trusted principal key loads | error |
200
+ | the Cedar policy parses, and has at least one `permit` rule (a `permit(` in a comment does not count) | error, and a warning |
201
+ | every credential variable the config names is set: upstream tokens and headers, the log's token, the capture key, the Splunk token, and the OpenTelemetry headers | **error**: the gateway does not start without it |
202
+ | a stdio `command` exists, and a script argument exists | error, and a warning |
203
+ | the receipts, log, revocation, operations database, and approvals paths can be written, and the revocation file is a JSON array | error |
204
+ | the grant the config names verifies, and is inside its window | error, and a warning near expiry |
205
+ | a remote log with an empty `precommit` | warning: a log outage after a call puts its receipt in the outbox, so the side effect is in the log only after the outbox is appended |
206
+
207
+ With **`--connect`** it also starts the upstreams, which is where an unreachable server or **two upstreams offering the same tool** shows up, prints the tools they offer, and compares every tool name in `precommit`, `facts`, `approvals`, `operations`, and the grant's scopes with that list. A name in `precommit`, `facts`, `approvals`, or `operations` that no upstream offers is an **error** (for `precommit` it means the tool you meant is forwarded before it is logged); a grant scope that names nothing is a warning. `--connect` starts your stdio upstreams and may create the receipts directory. It exits 1 on any error, so it can gate a deploy.
208
+
209
+ **A console for all of this.** [The gateway console](console.md) shows the same config, the tools, and the check in a browser, and edits the policy with a replay of recorded calls before it saves.
210
+
211
+ ## When the gateway does not start
212
+
213
+ | the message | the cause | the fix |
214
+ | --- | --- | --- |
215
+ | `environment variable X is not set` | a `tokenEnv`, `headerEnv`, `log.tokenEnv`, or `captureKeyEnv` names a variable the process does not have | set it where the gateway runs |
216
+ | `tool "t" is offered by both upstream "a" and upstream "b"` | two upstreams offer one name | rename one (give REST and A2A tools a prefix) |
217
+ | `exactly one of upstream or upstreams is required` | both, or neither | use `upstream` for one source and `upstreams` for several |
218
+ | `exactly one of logFile or log is required` | both, or neither | a local file, or a remote log |
219
+ | `precommit with a remote log needs log.keys` | a remote log gating consequential calls without a pinned key | add the log's public key file to `log.keys` |
220
+ | `requirePrecommit is set and precommit is empty` | a remote log with no consequential tools named | name them in `precommit`, or `["*"]` |
221
+ | `fact "f" uses tool t, which precommit names as consequential` | a fact lookup must be a read | use a read tool for the fact |
222
+ | `ENOENT … gateway.key` | the key file does not exist | `agent-custody keygen`, or let the container create it |
223
+ | `EROFS` or a permission error on `receipts` | a writable path points into the read-only `/config` | use an absolute path under `/data` |
224
+ | `403 delegation grant rejected: …` (an agent's connection) | the grant is expired, revoked, not signed by a trusted principal, or missing | issue a new grant, and check `trustedPrincipalKeys` |
225
+
226
+ The gateway image runs the static check every time it starts and does not start on an error (`GATEWAY_CHECK=advisory` prints the findings and starts anyway; `off` skips it), and the command exits 1 on an error, so it can gate a deploy. Run `agent-custody check --connect` first: it reports most of these together, instead of one at a time.
@@ -0,0 +1,78 @@
1
+ # The gateway console
2
+
3
+ A small admin service for the person who runs a gateway. It shows what the gateway is configured to do and what it has done, validates and replays a policy change before it is saved, and revokes a grant. It is a separate process from the gateway, behind a token, so the gateway never serves an admin page next to the agents' credentials.
4
+
5
+ It is deliberately limited. It holds **no principal key and signs nothing**, so it cannot issue a grant or widen anyone's authority; everything it shows is read from the gateway's own config, receipts, and revocation file; and the only things it changes are the policy file and the revocation file, both of which the gateway reads. [Example 32](../examples/32-console.ts) runs it end to end.
6
+
7
+ ## Run it
8
+
9
+ ```bash
10
+ export CONSOLE_TOKEN="$(openssl rand -hex 32)" # the sign-in token; it is read from the environment (or a file), never from a flag
11
+ agent-custody console --config gateway.json --gateway-url http://127.0.0.1:8790
12
+ ```
13
+
14
+ It listens on `127.0.0.1:8795` and prints the URL. Open it and sign in with the token.
15
+
16
+ | flag | meaning |
17
+ | --- | --- |
18
+ | `--config <gateway.json>` | the gateway's config, read again on every request, so an edit shows at once |
19
+ | `--token-env NAME` | the environment variable holding the token, default `CONSOLE_TOKEN`; the console refuses to start without one |
20
+ | `--token-file <path>` | read the token from a file instead, such as a container secret at `/run/secrets/console_token`; the contents are the secret, not the path |
21
+ | `--port`, `--host` | default `8795` on `127.0.0.1`; any other host prints a reminder to put TLS in front |
22
+ | `--gateway-url <url>` | the running gateway, for its health (reachable, open sessions); omit it and the console does not look |
23
+ | `--state-dir <dir>` | where the console keeps its audit file and the earlier versions of the policy; default `console/` beside the receipts directory |
24
+
25
+ **In the Docker image** it is the same image as the gateway, run as a second service: `docker compose --profile console up -d` in [deploy/gateway](https://github.com/svayatta/agent-custody/blob/main/deploy/gateway/README.md). The token is a **Docker secret mounted only in the console service** (`openssl rand -hex 32 > console-token`), not an entry in the `.env` file that the gateway reads, because the token can rewrite the policy and revoke grants and the gateway must not hold it. The console service is not given that `.env` either, so it holds none of the upstream credentials. It mounts `./config` read-write, because the policy file is what it edits, and the same data volume as the gateway; the gateway keeps its config read-only. Both run as the same user (`GATEWAY_UID`, `GATEWAY_GID`, default 10001), so what one writes the other can read: the gateway's key is mode 0600. On Kubernetes, run the same image with the argument `console`, the token as a Secret mounted as a file and given only to that pod, the same config and data volumes, and a Service that only your administrators can reach.
26
+
27
+ ## What it shows and does
28
+
29
+ | tab | what it does |
30
+ | --- | --- |
31
+ | **Overview** | the gateway's health and key id, the mode, the upstreams and their kinds, the fact lookups, the log, `precommit`, the trusted principal keys, the number of revoked grants and of receipts, and the config check's result |
32
+ | **Check** | the same checks as `agent-custody check`, except that the credential variables are **not** checked: the console deliberately does not hold the gateway's credentials, so it cannot tell whether they are set where the gateway runs. "Connect" starts the upstreams and lists their tools only for a config that names no credentials; otherwise it says to run `agent-custody check --connect` where the gateway runs, for example `docker compose exec gateway agent-custody check --config /config/gateway.json --connect`. A connect check that does not finish in 60 seconds is stopped and the upstreams it started are closed ([configuration.md](configuration.md#check-it-before-you-start-it)) |
33
+ | **Policy** | the policy file in an editor. *Validate* asks Cedar to parse it. *Replay recorded calls* runs it against the verified receipts, using each call's own arguments and facts, and lists the decisions that would change, with their receipts. **A replay only re-decides calls that already happened**: a limit that no recorded call reached, or removing one, can show no change, so it is not a test of what a policy allows. *Save* writes it, keeping the previous version and recording the change |
34
+ | **Grants** | paste a grant to see whether the gateway would accept it (valid, expired, revoked, signed by a key it does not trust) and what it allows; *Revoke* adds its digest to the revocation file, and the gateway refuses it, and every grant delegated from it, on its next call. Lists the revoked digests |
35
+ | **Receipts** | the newest receipts with their agent, tool, decision, and outcome, each verified against the gateway key, the trusted principals, and the local log; a receipt that does not verify says which checks failed; a row opens the full statement |
36
+ | **Audit** | every change made through the console: who, when, and what, with the policy's digest before and after |
37
+
38
+ ## What a saved policy does
39
+
40
+ A running gateway re-reads `policy.cedar` when it changes, so **a saved policy applies from the gateway's next call**, with no restart, and the gateway records the change in `receipts/policy-reloads.jsonl`. The save is guarded: Cedar must parse the text; and the operator must confirm a policy that has no `permit` rule (a `permit(` in a comment does not count), because every call would be denied, or a `permit` rule with **no action and no condition**, which allows every tool in a grant's scopes and which a replay cannot show. A save made from a copy that is no longer the file on disk is refused with `409`. The digest check, the history copy, and the write happen under one lock, in this process and, through a lock file in the state directory, across consoles that share it, so two administrators cannot overwrite each other. The previous version is kept under `console/policy-history/` and the change goes in the audit trail.
41
+
42
+ ## How it is protected
43
+
44
+ - **A token on every API route.** It is compared in constant time. Five wrong tokens from one address lock it out for a minute. A request with no token is refused and does not count towards that.
45
+ - **Loopback by default.** The transport is plain HTTP. Anything beyond one machine needs TLS in front (a proxy or mesh) and a network only administrators can reach. The console has one shared token, not per-user accounts or roles.
46
+ - **No keys.** It never reads a principal's private key. It reads the gateway's key file only to take the public half, so that it can verify receipts.
47
+ - **The page cannot run what it shows.** Every value is written with `textContent`, never as markup, and the page is served with a content-security-policy that allows exactly its own script and style by hash and nothing else (no inline attributes, no outside requests). The page's own tests check both.
48
+ - **Bounded input.** A request body over a megabyte is refused, and a receipt id must be a UUID, so a path cannot be read through it.
49
+ - **Everything it changes is recorded**, in an append-only file in its state directory, and the policy it replaces is kept.
50
+
51
+ ## Limits
52
+
53
+ - It does not issue grants. A grant is signed by a principal's key, which belongs where grants are issued ([configuration.md](configuration.md#the-principals-key)).
54
+ - It does not edit `gateway.json`: upstreams, facts, and `precommit` are changed in the file, and the gateway restarted. The Overview and Check tabs show them.
55
+ - The credential variables are not checked in the console, and an upstream that needs one is not started there.
56
+ - One token, no per-user accounts, and the audit records the address and not a person.
57
+ - It reads the local receipts directory. With a remote log it verifies receipts against the keys but not the log's inclusion proofs.
58
+ - A shared gateway has one policy and one key for every agent on it, so the console edits one policy.
59
+
60
+ ## API
61
+
62
+ Every route except `GET /` (the page) and `GET /healthz` needs `Authorization: Bearer <token>`.
63
+
64
+ | route | does |
65
+ | --- | --- |
66
+ | `GET /api/overview` | the configuration summary, the gateway's health, and the static check |
67
+ | `POST /api/check` `{ connect? }` | the check; `connect` starts the upstreams |
68
+ | `GET /api/policy` | the policy text, its digest, and the earlier versions kept |
69
+ | `POST /api/policy/validate` `{ text }` | does Cedar parse it, and which things need confirming (`issues`) |
70
+ | `POST /api/policy/simulate` `{ text }` | replay up to 1,000 verified receipts against it; the report counts reconciliation receipts (provider reads, no policy decision) in `reconciliations`, apart from `evaluated` |
71
+ | `PUT /api/policy` `{ text, expectDigest, confirm? }` | save it; `400` unless `confirm` is true when the policy has an issue the validate route reported; `409` if the file changed |
72
+ | `POST /api/grants/inspect` `{ grant }` | status, agent, scopes, window, digest |
73
+ | `POST /api/grants/revoke` `{ grant }` | add its digest to the revocation file |
74
+ | `GET /api/revocations` | the revoked digests |
75
+ | `GET /api/receipts?limit=` | recent receipts with their verdicts; `GET /api/receipts/<id>` is one statement |
76
+ | `GET /api/audit` | the console's audit trail |
77
+
78
+ Programmatically: `serveConsole({ configFile, token, port?, host?, gatewayUrl?, stateDir? })` returns `{ url, close() }`.
package/docs/policies.md CHANGED
@@ -114,6 +114,7 @@ The memory server in `@agent-custody/state` is an upstream like any other, so it
114
114
  | `memory.read` | the query, and `includeClaimed` or `requireVerified` when the caller asks for them | |
115
115
  | `memory.retract`, `memory.forget`, `memory.hold`, `memory.release` | `factId` and `reason` | `target`, the fact being changed |
116
116
  | `memory.sweep` | `before`, `space`, `reason` | |
117
+ | `memory.repair` | `reason`, and optionally `before` (an earlier cutoff) | |
117
118
  | `memory.confirm` | `factId` | |
118
119
 
119
120
  A looked-up `target` has `space`, `actor`, `provenance` (`claimed`, `attested`, or `verified`), `subject`, `predicate`, `value`, and `retracted`. Fields that would be null are absent, so test with `has`. The lookup config that makes `target` available is in the [state package README](../../state/README.md#the-memory-server).
@@ -214,10 +215,12 @@ For SDK receipts, use the application's public key as `--issuer-key`; no princip
214
215
 
215
216
  A gateway that dies after it forwards a `precommit` call leaves `<id>.authorization.json` and no `<id>.json`. The command verifies each such file as an authorization statement (the issuer key, the tree head, and the inclusion proof) and lists the call under `skipped`, so the report is `INCOMPLETE`. An authorization that does not verify fails the command. An authorization that sits beside its receipt is not read twice.
216
217
 
218
+ The command also checks that each `<id>.json` holds receipt `<id>`. A receipt under another file name fails the command, so a copy over the name of another receipt cannot hide that call.
219
+
217
220
  A receipt under a capture rule needs its withheld arguments and fact values to replay. Give `--capture-key-env NAME` to decrypt the values that mode `encrypted` withheld, as `verify` does. Give `--disclose <file>`, which you can repeat, for the values that mode `digest` withheld. Each file is a disclosure as `reveal` writes it, and it applies only to the receipt that its `receiptId` names. A key or a disclosure that does not match a commitment skips that receipt as malformed. The key comes from the environment, never from a flag value.
218
221
 
219
222
  The report lists every call whose `allow` or `deny` decision changes, grouped by tool and the proposed decision's policy ids or evaluation errors, with the receipt ids and both decisions. A call executed in observe mode may already have a recorded deny: replay compares that recorded decision, not whether the tool ran. Calls with the same decision stay unchanged even when different policy ids match. Cedar evaluation errors remain denials.
220
223
 
221
- Every run records a `runId`, `timestamp`, the proposed text's sha256 as `policyDigest`, and the original digests as `previousPolicyDigests`. `--out` saves the full JSON report, and `--json` prints it to stdout. Changes alone exit 0. A report that cannot replay every call says `INCOMPLETE` and exits 1: `skipped` names each receipt and why. This includes record-only receipts with no policy baseline, withheld arguments or fact values, calls whose receipt is missing, and calls stopped before Cedar could evaluate. Grant failures cannot become permits through a policy change, and neither can an approval refusal: the gateway checks the approval before Cedar runs, so the call is skipped as a non-policy gate. The approval record says so even under a private rule. Withheld results alone do not prevent replay.
224
+ Every run records a `runId`, `timestamp`, the proposed text's sha256 as `policyDigest`, and the original digests as `previousPolicyDigests`. `--out` saves the full JSON report, and `--json` prints it to stdout. Changes alone exit 0. A report that cannot replay every call says `INCOMPLETE` and exits 1: `skipped` names each receipt and why. This includes record-only receipts with no policy baseline, withheld arguments or fact values, calls whose receipt is missing, and calls stopped before Cedar could evaluate. Grant failures cannot become permits through a policy change, and neither can an approval refusal: the gateway checks the approval before Cedar runs, so the call is skipped as a non-policy gate. The approval record says so even under a private rule. Withheld results alone do not prevent replay. A reconciliation receipt is a provider read, so no policy decision exists to replay. The report counts it in `reconciliations`, not in `evaluated` or `skipped`, and it does not make the report incomplete. A reconciliation whose original receipt is missing is the exception: the call that it settles cannot be replayed, so the report skips that call and says `INCOMPLETE`. The library trusts a reconciliation receipt only after `verifyBundle` accepts it; the CLI and the console verify first.
222
225
 
223
226
  The report is an analysis of the supplied receipt directory; it does not prove that the directory contains the whole history. Keep the report beside the proposed policy and review the changed receipt ids before switching from observe mode to enforcement. [Tutorial 28](../examples/28-policy-simulation.ts) records three refunds, stops the gateway, and replays them against a lower limit.
@@ -100,6 +100,19 @@ Each row names the attacker, the move, the defence, and whether the defence is a
100
100
  | Steal a tenant token | Tokens are bearer secrets; a stolen one appends noise to that tenant's log until revoked. Rate limits bound the damage per second; the tenant's usage shows it. | deployment |
101
101
  | Escape a per-address limit by forging `X-Forwarded-For` | Behind the proxy the deployment runs, the limiter keys on the address the proxy appended, the rightmost entry, never on one the client supplied. | deployment |
102
102
 
103
+ ### On the portal accounts
104
+
105
+ The portal is not part of the evidence: it publishes policy names and mints log tokens. A stolen account can mint a token, so the portal limits who may.
106
+
107
+ | attack | defence | kind |
108
+ | --- | --- | --- |
109
+ | Guess or steal a member's password | Optional TOTP MFA on the account. A code works once, wrong codes are throttled per address and per account, and the half-signed-in cookie is never a session. A GitHub or Google sign-in goes through the same code step. | deployment |
110
+ | A member acts beyond their job | Four roles: `readonly` reads, `reviewer` also publishes policy versions, `admin` also manages keys and members below owner, `owner` also manages billing and owners. A new write route needs `admin` unless it is listed. The last owner cannot be removed or demoted. | deployment |
111
+ | Claim an invited address to join a tenant | An invite is accepted only by an account with a verified address, and an account belongs to one tenant. | deployment |
112
+ | Sign in through an IdP the tenant does not own | The operator sets single sign-on, never the tenant. An IdP is trusted only for the email domains of its tenant, and a domain belongs to one tenant. The portal checks the OIDC `id_token` signature against the IdP's key set, or the signed SAML assertion through a maintained library, and ties the sign-in to the request that started it. | deployment |
113
+ | Lock a member out of their SSO tenant by registering their address first | The IdP proves the address, so it wins over an account that never verified it. The sign-in deletes that account with its password, sessions, memberships, and linked providers. A tenant that the account created stays, for the operator to deal with. Registering with a tenant, or linking a provider, does not change this. The one limit: an account in another tenant that has other members is refused, so that tenant keeps its members. | deployment |
114
+ | Keep access after leaving the company | With enforcement on, members sign in only through the IdP, so removal at the IdP ends access at the next sign-in. Sessions that began earlier end when enforcement is turned on. A member removed in the portal loses access at once, also in an SSO tenant: the IdP sign-in joins them again only after an admin invites the address again, also when they never verified their address. An API key that the member minted stays valid until an admin revokes it. | deployment |
115
+
103
116
  ## What is not defended
104
117
 
105
118
  Stated plainly, because a security review that finds these itself will not believe the rest.
package/docs/tutorials.md CHANGED
@@ -40,6 +40,8 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
40
40
  | 28 | policy simulation | [28-policy-simulation.ts](../examples/28-policy-simulation.ts) | three refunds recorded in observe mode, then the gateway stopped and their receipts replayed against a lower limit: only one changes decision, grouped by tool and reason with its receipt id, the proposed policy digest saved with the run | `src/simulate.ts`, `src/cli.ts` |
41
41
  | 29 | financial operations | [29-financial-operations.ts](../examples/29-financial-operations.ts) | a refund accepted before its response is dropped, a restart and retry producing no second request, the unknown reservation blocking an over-budget refund, and a provider reconciliation receipt that verifies | `src/operations.ts`, `src/gateway.ts`, `src/verify.ts` |
42
42
  | 30 | payload-bound human approvals | [30-payload-bound-approvals.ts](../examples/30-payload-bound-approvals.ts) | two people sign the exact refund; missing approval, one signer, changed amount or beneficiary, extra arguments, and expiry are refused; the approved call executes once, its replay is refused, and every receipt verifies with separately trusted approval keys | `src/approval.ts`, `src/gateway.ts`, `src/verify.ts` |
43
+ | 31 | enterprise sign-in and roles | [31-enterprise-sign-in.ts](../examples/31-enterprise-sign-in.ts) | an enterprise tenant signs in through its own identity provider, a stand-in OIDC IdP: the operator sets single sign-on, a member joins as readonly and is refused a policy write, an owner promotes them to reviewer, and enforcement turns password sign-in off | `src/sso.ts`, `src/portal.ts` |
44
+ | 32 | the gateway console | [32-console.ts](../examples/32-console.ts) | a gateway that has made two receipts, and its operator's console: a token on every route, the receipts with a verdict each, a stricter policy replayed against the recorded calls before it is saved, the save recorded with the old version kept and a stale edit refused, and a grant inspected, revoked, and then refused by the gateway | `src/console.ts`, `src/console-page.ts` |
43
45
 
44
46
  ## How policies are defined, in one paragraph
45
47
 
@@ -48,7 +50,9 @@ A policy is a Cedar file. The gateway turns each tool call into a Cedar request:
48
50
  ## Where each guide goes deeper
49
51
 
50
52
  - [usage.md](usage.md): gateway setup and wiring into hosts
53
+ - [codex-recovery.md](codex-recovery.md): the opt-in live Codex support incident, operator-reviewed recovery, and its offline state example
51
54
  - [approvals.md](approvals.md): exact-action signatures, two-person thresholds, consumption, and privacy limits
55
+ - [console.md](console.md): the admin console: run it, what each tab does, how it is protected, and its limits
52
56
  - [financial-operations.md](financial-operations.md): payment retries, budget reservations, provider contract, and operator reconciliation
53
57
  - [sdk.md](sdk.md): the interceptor and every adapter
54
58
  - [policies.md](policies.md): the Cedar mapping, evaluation rules, tested examples, gotchas
package/docs/usage.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  This page covers the gateway, the out-of-process producer. For the in-process interceptor that hooks Claude Code, the Claude Agent SDK, or any framework's tool functions, see [sdk.md](sdk.md).
4
4
 
5
+ For who may use which tools, where the tools live, a worked example with two agents on one shared gateway, how the config works in the Docker image, and how to check it before you start, see [configuration.md](configuration.md). This page is the setup in order.
6
+
5
7
  ## The parts
6
8
 
7
9
  | part | what it is | who controls it |
@@ -121,7 +123,7 @@ At startup the gateway fetches the agent's card from `<url>/.well-known/agent-ca
121
123
  "log": { "url": "https://log.example.com/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN" }
122
124
  ```
123
125
 
124
- Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log refuses a leaf, the receipt is not issued and the call returns an error to the agent. For an ordinary call the upstream action has already happened by then, and the error says so; a receipt that was never logged must not be handed out. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls, so a tenant out of quota never acts without evidence. The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
126
+ Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log does not take a receipt, the gateway keeps the signed receipt in `receipts/outbox/<receiptId>.json` and returns the real outcome of the call to the agent, with the receipt id and `_meta["agent-custody/log-pending"]: true`. The gateway appends the outbox at startup and every 30 seconds, and writes `receipts/<receiptId>.json` when the log takes the receipt. Until then no bundle exists, so no receipt that was never logged is handed out. The table [below](#when-the-log-fails) gives each case. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls, so a tenant out of quota never acts without evidence. The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
125
127
 
126
128
  `otel`, optional in both the gateway and SDK configs, sends every receipt to the collector you already run as one span over OTLP/HTTP, after the receipt is issued: `"otel": { "url": "http://localhost:4318", "headersEnv": { "x-api-key": "OTEL_KEY" }, "serviceName": "support-agents" }`. The span's trace id is the receipt id, its attributes carry the tool, agent, principal, execution status, policy decision, and log position, and its status is an error only when the upstream failed or errored, since a denial is the policy working. Export is best effort: a collector that is down or refuses costs a line on stderr, never a receipt. Tutorial 18 shows it against a stand-in collector.
127
129
 
@@ -133,7 +135,22 @@ Exactly one of the two. The bearer token comes from the named environment variab
133
135
 
134
136
  To test a different policy against the history already collected, run `agent-custody policy simulate --policy proposed.cedar --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --out simulation.json`. It replays recorded arguments and fact values without calling upstreams, lists changed decisions by tool and reason with the receipt ids, and records the proposed policy digest. Missing replay inputs make the report incomplete. See [the policy simulation guide](policies.md#simulating-a-policy-against-recorded-history).
135
137
 
136
- The grant is checked on every call, not only when the session opens: a call after `expiresAt` is denied with a receipt that says so, the check is repeated just before the forward (a grant that ran out while the facts were gathered leaves the call `withheld`), and over HTTP a session whose grant has expired or been revoked is closed on its next request with `403`. `"revokedGrants": "revoked.json"` names a file of grant digests the gateway re-reads whenever it changes. The digest is sha256 over the grant's signed payload, so extra signatures or fields on the envelope do not change it, and revoking a grant also revokes every grant delegated from it. A file that cannot be read denies every call until it can be read; `agent-custody revoke --config gateway.json --grant grant.json` appends a grant's digest to it, after which every session under that grant refuses its next call and no new session opens for it, with no key rotation. `precommit` names the consequential tools, or `["*"]` for all of them. For every other tool the gateway forwards the call and then records it, so if the log is unreachable at that moment the side effect exists before its evidence does. For a tool in `precommit` the gateway first signs an authorization statement, everything the receipt will say except the outcome, and appends it to the log. Only if the log took it does the call go upstream. The receipt then embeds that authorization with its own inclusion proof, and a verifier checks that it names this call and sits in the log before the receipt does. If the log will not take it, or answers with a head or proof that does not verify, the call is not forwarded, the agent is told `Not executed`, and the receipt records `execution.status: "withheld"` with the policy's `allow` beside it. The authorization is also written on its own as `receipts/<receiptId>.authorization.json`, which is the evidence that survives if the gateway dies between forwarding and the receipt. Use it for money, for anything irreversible, and for anything a counterparty could later dispute; the cost is one extra log append per call.
138
+ The grant is checked on every call, not only when the session opens: a call after `expiresAt` is denied with a receipt that says so, the check is repeated just before the forward (a grant that ran out while the facts were gathered leaves the call `withheld`), and over HTTP a session whose grant has expired or been revoked is closed on its next request with `403`. `"revokedGrants": "revoked.json"` names a file of grant digests the gateway re-reads whenever it changes. The digest is sha256 over the grant's signed payload, so extra signatures or fields on the envelope do not change it, and revoking a grant also revokes every grant delegated from it. A file that cannot be read denies every call until it can be read; `agent-custody revoke --config gateway.json --grant grant.json` appends a grant's digest to it, after which every session under that grant refuses its next call and no new session opens for it, with no key rotation. The Cedar policy is re-read the same way: when `policyFile` changes (device, inode, mtime, ctime, or size; a file written in the last two seconds is re-read on each call until it settles), the next call is evaluated under the new policy, with no restart and no dropped session, and a call already evaluating finishes under the policy it started with, whose digest its receipt carries. A changed file that does not parse, or that cannot be read, is refused: the policy in force stays, never an allow, and the gateway prints `POLICY NOT RELOADED` on stderr. Every change and every refusal is appended to `receipts/policy-reloads.jsonl` as `{ at, file, event: "reloaded" | "refused", from, to, errors?, warnings? }`, with the digest in force and the digest of the new file (`null` when the file was removed or cannot be read), so the change between two receipts' `policyDigest`s has a time. A reloaded policy with no permit rule is applied, since it denies every call, but is printed and recorded with the warning `no permit rule: every call is denied`. Write the file by rename, as `agent-custody console` does. A file written in place can be read half-written: a prefix that parses, missing a trailing `forbid`, decides calls until the write finishes and the settled file is read. `precommit` names the consequential tools, or `["*"]` for all of them. For every other tool the gateway forwards the call and then records it, so if the log is unreachable at that moment the side effect exists before its evidence is in the log: the receipt waits in the outbox. With a remote log and an empty `precommit`, the gateway prints a warning at startup and `agent-custody check` reports it; `"requirePrecommit": true` makes it a startup error. For a tool in `precommit` the gateway first signs an authorization statement, everything the receipt will say except the outcome, and appends it to the log. Only if the log took it does the call go upstream. The receipt then embeds that authorization with its own inclusion proof, and a verifier checks that it names this call and sits in the log before the receipt does. If the log will not take it, or answers with a head or proof that does not verify, the call is not forwarded, the agent is told `Not executed`, and the receipt records `execution.status: "withheld"` with the policy's `allow` beside it. The authorization is also written on its own as `receipts/<receiptId>.authorization.json`, which is the evidence that survives if the gateway dies between forwarding and the receipt. Use it for money, for anything irreversible, and for anything a counterparty could later dispute; the cost is one extra log append per call.
139
+
140
+ #### When the log fails
141
+
142
+ "Down" is a log that does not answer or answers 5xx. "Slow" is an append that takes longer than `log.timeoutMs` (default 10000 ms), which counts as down. "Refusing" is a 4xx answer other than 429, or an answer whose tree head or proof does not verify. "Quota" is 429, after the sink's retries. The sink makes three attempts before the gateway treats the append as failed.
143
+
144
+ | log state | ordinary tool | tool in `precommit` | financial operation |
145
+ | --- | --- | --- | --- |
146
+ | down, slow, or quota (429) | forwarded; the agent gets the real result and `log-pending`; the receipt waits in the outbox and is appended when the log answers again | not forwarded; the agent gets `Not executed` and `log-pending`; the `withheld` receipt waits in the outbox | the call returns an error and nothing is forwarded, because the authorization is not in the log; if only the receipt append fails after the forward, the call also returns an error, and `reconcile` finishes the operation |
147
+ | refusing | as above, but the outbox does not empty until the operator fixes the cause (a token, a quota, the pinned keys); the gateway prints the reason on each attempt | as above | as above |
148
+
149
+ The outbox is appended in the order of the signed statements' timestamps, oldest first. A log refusal stops the flush, so one receipt that the log refuses holds the receipts after it. `GET /health` on the HTTP gateway reports `pendingReceipts`. Only a gateway that serves (stdio, `--http`, `--a2a`) runs the flush, at start and every 30 seconds; `check`, `reconcile`, and the other commands never append the outbox. A gateway that stops waits for a flush that runs. A gateway that stops before the log takes the receipt keeps the outbox on disk and appends it on the next start. The gateway writes the outbox entry to disk, and syncs the file and its directory, before the agent gets the result.
150
+
151
+ Several gateways, or a gateway and a command, can share one `receipts/` directory. A flush takes the lock file `receipts/outbox/.lock` with an exclusive create. When another process holds the lock, the flush does nothing and reports the entries as `pending`. The gateway breaks a lock whose owner process no longer runs on this host, and a lock that nobody has touched for 15 minutes.
152
+
153
+ When the log takes a receipt, the gateway records the log's answer in the outbox entry before it writes the bundle. If the bundle write then fails (a full disk, a permission error), the gateway prints the error on stderr, and the next flush writes the bundle from the recorded answer and does not append the leaf again. A process that dies between the append and that record appends the leaf again on the next flush; the log then holds it twice, and either copy proves the receipt. A gateway that dies after the forward and before the outbox write leaves no receipt; `precommit` is the guard for the calls where that matters. Before the gateway appends an outbox entry, it checks the entry. It renames an entry to `<name>.bad`, does not append it, and prints a warning, when the file is damaged, when the entry carries this gateway's key id but the signature does not verify, or when the receipt id in the statement is not the id in the file name. An entry that another key signed (a rotated gateway key, or a restored backup) is not appended, is not called forged, and stays in the outbox; the gateway prints a warning on each flush. Restore the key that signed it, or move the entry away. Until the log takes a pending receipt, `receipts/<id>.json` does not exist, so `verify`, `explain`, `blast`, the review console, and `prune` do not see the call yet.
137
154
 
138
155
  **5. Run the gateway.** It speaks MCP on stdin/stdout and logs to stderr only.
139
156
 
@@ -163,6 +180,23 @@ The gateway checks again and consumes the approval id immediately before forward
163
180
 
164
181
  Under a private capture rule the receipt withholds the approval envelope as a commitment, because it carries the action fields and an unsalted digest of all arguments. The status, the times, and the signer key ids stay in clear. Full approval verification then requires the capture key or a disclosure. [The approval guide](approvals.md) covers signing, field mappings, failure recovery, and these privacy limits; [tutorial 30](../examples/30-payload-bound-approvals.ts) runs it end to end.
165
182
 
183
+ ## Review a transaction and export its case
184
+
185
+ The state package's `agent-custody-memory review` opens the receipts as a local review console, with one receipt's ten answers and verification report behind each index row:
186
+
187
+ ```bash
188
+ agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --transaction re_123 --customer cust_123 --agent support-agent --from 2026-10-01T00:00:00Z --to 2026-10-31T23:59:59Z
189
+ agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --out review-site/
190
+ agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --case <receiptId> --out refund.case.html
191
+ agent-custody-memory review --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --case <receiptId> --out refund.case.json
192
+ agent-custody-memory review --verify-case refund.case.json --issuer-key keys/gateway.pub --principal-key keys/principal.pub --json
193
+ agent-custody-memory review --verify-case refund.case.html --issuer-key keys/gateway.pub --principal-key keys/principal.pub
194
+ ```
195
+
196
+ `--transaction`, `--customer`, and `--agent` match exact case-sensitive ids; all filters combine with AND. `--from` and `--to` are inclusive ISO date-times with `Z` or a UTC offset. Search covers public arguments, results, and gateway facts; a withheld identifier is unavailable. A record whose receipt id differs from its file name stays in the index as NOT VERIFIED, and the header counts the files that cannot be read. A receipt with a value that search skipped (deeper than 64 levels, or JSON text over 64 KiB) is marked "partially indexed" and stays in the list under an id filter. `--ledger <path>` adds belief dependencies, `--log-key <pub>` and `--log-id <id>` check the log, and `--upstream-key <pub>` checks signed upstream results. `--host` defaults to `127.0.0.1`, `--port` to `8791`; `--title <text>` labels the console. It has no authentication of its own. A directory export includes the index, receipt pages and bundles, and portable HTML/JSON cases; its browser search covers the exported set.
197
+
198
+ The standalone `.case.html` repeats cryptographic checks on the signed evidence with embedded WebCrypto code, offline and without external requests. That result is not independent, because the script is in the same file as the data, and the page does not compare the ten answers with the receipts. Check the `.case.html` or its JSON companion independently with `--verify-case`. The file name sets the format: `.json` is read as JSON, every other name is read as a page, and content that does not match fails. It rebuilds the ten answers from the signed receipt and prints them, it fails a `.case.html` that is not exactly what its data renders, and it exits 1 on failure. Trust the printed answers, not the page. The belief, dependency, and reversal lines come from the unsigned ledger snapshot and are not attested; public key flags may be repeated and replace the entire bundled trust set. Confirm bundled key fingerprints with a trusted source. Cases include signed receipts, authorizations, log heads and proofs, public keys, and the ten answers; explanation and ledger snapshots are unsigned exporter assertions. Verification proves the recorded gateway decision and detects receipt tampering, not an external payment side effect. Without a ledger the belief questions remain unknown. Private keys, capture keys, disclosures, and issuer salts files are not exported, and withheld values stay unavailable. [The state guide](../../state/README.md#explain-one-action) and [runnable example](../../state/examples/08-review-console.ts) cover the full flow.
199
+
166
200
  ## Financial operations
167
201
 
168
202
  For payments, configure `operations` to bind a caller-retained operation UUID to the full call, reserve its amount atomically, and pass an idempotency key to the provider. Existing operations are never forwarded again on retry, and an allowed retry gets a `withheld` receipt of its own. API execution and financial settlement have separate statuses; uncertain outcomes hold their reservations until an operator's provider read commits a reconciliation receipt. The [financial operations guide](financial-operations.md) has the config, provider contract, and `agent-custody reconcile` command. [Tutorial 29](../examples/29-financial-operations.ts) runs the lost-response/restart scenario offline.
@@ -209,7 +243,7 @@ The limits. A signed human approval carries its action fields and an unsalted fu
209
243
 
210
244
  ## One gateway for many agents, over HTTP
211
245
 
212
- `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.
246
+ `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. SIGINT or SIGTERM closes the gateway, so a container runtime or systemd stops it cleanly. 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.
213
247
 
214
248
  ## The gateway as an A2A agent
215
249
 
@@ -328,6 +362,6 @@ The upstream can answer in kind. A result whose `_meta` carries `agent-custody/f
328
362
  - **Money is integer minor units.** Cedar has no floating point. A float in `args` that a policy touches is an evaluation error, which is a deny.
329
363
  - **The gateway key is the trust root for receipts.** Keep it out of the agent's reach. The upstream credentials in `upstream.env` are likewise never exposed to the agent.
330
364
  - **Rotate keys by adding, not replacing.** The verifier accepts a list of gateway keys and principal keys and matches by keyid, so old receipts stay verifiable.
331
- - **Evidence before the side effect, for the calls that matter.** Without `precommit`, a call is forwarded and then logged, and a log outage at that moment leaves an executed action with no receipt (the agent gets an error saying so). With `precommit`, the authorization is logged first and the call is withheld if that fails. The receipt of a withheld call shows `allow` next to `withheld`, so an auditor can tell a log outage from a denial.
365
+ - **Evidence before the side effect, for the calls that matter.** Without `precommit`, a call is forwarded and then logged, and a log outage at that moment leaves an executed action whose receipt waits in the outbox until the log takes it (the agent gets the real result, marked `log-pending`). With `precommit`, the authorization is logged first and the call is withheld if that fails. The receipt of a withheld call shows `allow` next to `withheld`, so an auditor can tell a log outage from a denial.
332
366
  - **The log is append-only by convention, not enforcement.** Copy it somewhere the operator cannot rewrite, on a schedule. The receipts' tree heads let an auditor check that the copy matches.
333
367
  - **stdout is the MCP channel.** Anything the gateway prints goes to stderr. Do not add `console.log` to gateway code paths.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
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",
@@ -77,16 +77,19 @@
77
77
  "devDependencies": {
78
78
  "@electric-sql/pglite": "0.5.8",
79
79
  "@langchain/core": "^1.2.9",
80
+ "@node-saml/node-saml": "^5.1.0",
80
81
  "@openai/agents": "^0.18.0",
81
82
  "@types/node": "^26.4.1",
82
83
  "ai": "^7.0.92",
83
84
  "langchain": "1.5.15",
84
85
  "tsx": "^4.23.13",
85
86
  "typescript": "^7.0.2",
86
- "vitest": "^5.0.0"
87
+ "vitest": "^5.0.0",
88
+ "xml-crypto": "^6.1.2"
87
89
  },
88
90
  "peerDependencies": {
89
91
  "@langchain/core": ">=1.0.0",
92
+ "@node-saml/node-saml": ">=5.1.0",
90
93
  "@openai/agents": ">=0.1.0",
91
94
  "ai": ">=5.0.0",
92
95
  "pg": ">=8"
@@ -95,6 +98,9 @@
95
98
  "@langchain/core": {
96
99
  "optional": true
97
100
  },
101
+ "@node-saml/node-saml": {
102
+ "optional": true
103
+ },
98
104
  "@openai/agents": {
99
105
  "optional": true
100
106
  },