@agent-custody/receipts 0.6.19 → 0.8.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.
Files changed (50) hide show
  1. package/README.md +20 -11
  2. package/dist/a2a.js +19 -7
  3. package/dist/approval.d.ts +74 -0
  4. package/dist/approval.js +196 -0
  5. package/dist/capture.d.ts +153 -0
  6. package/dist/capture.js +607 -0
  7. package/dist/cli.js +221 -6
  8. package/dist/config.d.ts +144 -0
  9. package/dist/config.js +92 -3
  10. package/dist/crypto.d.ts +2 -2
  11. package/dist/crypto.js +7 -4
  12. package/dist/delegation.d.ts +7 -0
  13. package/dist/delegation.js +15 -1
  14. package/dist/gateway-http.js +13 -1
  15. package/dist/gateway.d.ts +15 -0
  16. package/dist/gateway.js +414 -27
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.js +4 -0
  19. package/dist/issue.d.ts +20 -5
  20. package/dist/issue.js +76 -8
  21. package/dist/log-sink.d.ts +11 -1
  22. package/dist/log-sink.js +24 -5
  23. package/dist/operations.d.ts +101 -0
  24. package/dist/operations.js +239 -0
  25. package/dist/otel.js +16 -8
  26. package/dist/portal.d.ts +23 -2
  27. package/dist/portal.js +181 -36
  28. package/dist/receipt.d.ts +54 -8
  29. package/dist/rest.js +14 -1
  30. package/dist/retention.d.ts +8 -1
  31. package/dist/retention.js +21 -2
  32. package/dist/sdk/index.js +10 -1
  33. package/dist/simulate.d.ts +58 -0
  34. package/dist/simulate.js +204 -0
  35. package/dist/splunk.js +17 -8
  36. package/dist/upstream.d.ts +9 -7
  37. package/dist/upstream.js +16 -8
  38. package/dist/verify.d.ts +18 -0
  39. package/dist/verify.js +405 -15
  40. package/docs/approvals.md +107 -0
  41. package/docs/compliance.md +1 -1
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +22 -0
  44. package/docs/tutorials.md +7 -0
  45. package/docs/usage.md +71 -5
  46. package/docs/verification.md +35 -10
  47. package/package.json +1 -1
  48. package/vectors/audit.json +27 -27
  49. package/vectors/canonical.json +5 -5
  50. package/vectors/receipts.json +3612 -292
package/dist/gateway.js CHANGED
@@ -1,25 +1,30 @@
1
1
  // The MCP gateway: sits between an agent and its upstreams, MCP servers or REST APIs, enforces scope + Cedar policy,
2
2
  // and emits a signed, logged receipt for every tool call, allowed or denied.
3
3
  import { randomUUID } from "node:crypto";
4
- import { readFileSync } from "node:fs";
4
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
5
5
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6
6
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
7
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
8
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
9
9
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
10
10
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
11
- import { digestOf, loadPrivateKey, loadPublicKey } from "./crypto.js";
12
- import { delegationValidAt, verifyDelegation } from "./delegation.js";
11
+ import { digestOf, dsseVerifiers, dsseVerify, loadPrivateKey, loadPublicKey } from "./crypto.js";
12
+ import { delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
13
+ import { APPROVAL_META_KEY, DEFAULT_APPROVAL_LIFETIME_SECONDS, consumeApproval, verifyApproval, verifyApprovalStatement } from "./approval.js";
13
14
  import { createIssuer } from "./issue.js";
14
15
  import { openLog } from "./log-sink.js";
15
16
  import { openExporter } from "./otel.js";
16
17
  import { upstreamEvidenceOf } from "./upstream.js";
17
18
  import { restUpstream } from "./rest.js";
18
19
  import { a2aUpstream } from "./a2a.js";
20
+ import { captureKeyFrom, effectiveRule } from "./capture.js";
19
21
  import { evaluate, policyDigest } from "./policy.js";
22
+ import { OPERATION_META_KEY, OperationStore, ownerAlive } from "./operations.js";
20
23
  export const GATEWAY_VERSION = "0.1.0";
21
24
  export const RECEIPT_META_KEY = "agent-custody/receipt";
22
25
  export const MODEL_META_KEY = "agent-custody/model";
26
+ /** Set by the gateway on the answer to a retry of a financial operation: the receipt of the retry itself. `agent-custody/receipt` stays the receipt that holds the operation's outcome. */
27
+ export const RETRY_RECEIPT_META_KEY = "agent-custody/retry-receipt";
23
28
  /** Set by the gateway on the call it forwards upstream: the receipt id, and the agent and principal from the attested grant. */
24
29
  export const AGENT_META_KEY = "agent-custody/agent";
25
30
  export const PRINCIPAL_META_KEY = "agent-custody/principal";
@@ -58,6 +63,10 @@ function extractValue(result) {
58
63
  return text.text;
59
64
  }
60
65
  }
66
+ /** Match both verifiers: dot paths traverse own properties of JSON objects, never arrays or prototypes. */
67
+ function providerField(result, path) {
68
+ return path.split(".").reduce((value, part) => value && typeof value === "object" && !Array.isArray(value) && Object.hasOwn(value, part) ? value[part] : undefined, extractValue(result));
69
+ }
61
70
  /**
62
71
  * The environment a stdio upstream is started with: what a child process needs to run, plus what the config names.
63
72
  * Never the gateway's own environment, which holds the tokens other upstreams and the log are given. An explicit
@@ -72,21 +81,75 @@ export function upstreamEnv(extra) {
72
81
  }
73
82
  return { ...base, ...(extra ?? {}) };
74
83
  }
84
+ /** Writes the revocation list whole, by rename, so a gateway re-reading it never sees half a file. */
85
+ export function writeRevokedGrants(path, digests) {
86
+ const tmp = `${path}.${process.pid}.tmp`;
87
+ writeFileSync(tmp, JSON.stringify(digests, null, 2) + "\n");
88
+ renameSync(tmp, path);
89
+ }
75
90
  export async function createGatewayHost(cfg, options = {}) {
76
91
  const gatewayKey = loadPrivateKey(cfg.identity.keyFile);
77
92
  const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
93
+ const approvalKeys = cfg.approvals?.trustedKeys.map(loadPublicKey) ?? [];
94
+ const approvalRule = (tool) => cfg.approvals?.tools.find((rule) => rule.tool === tool) ?? cfg.approvals?.tools.find((rule) => rule.tool === "*");
78
95
  const policyText = readFileSync(cfg.policyFile, "utf8");
79
96
  const pDigest = policyDigest(policyText);
80
- const issuer = createIssuer(gatewayKey, cfg.receiptsDir, options.log ?? openLog(cfg, gatewayKey), { exporter: options.exporter ?? openExporter(cfg) });
97
+ // Private evidence: the key that encrypts withheld fields, read once; a rule in mode encrypted without it is a config error.
98
+ const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
99
+ for (const [tool, rule] of Object.entries(cfg.capture ?? {})) {
100
+ for (const side of [rule.args, rule.result, rule.facts])
101
+ if (side?.mode === "encrypted" && !captureKey)
102
+ throw new Error(`capture for ${tool} uses mode encrypted, which needs captureKeyEnv`);
103
+ }
104
+ // The rules are applied by the issuer to every statement it signs, the authorization included: the gateway hands it the call in full.
105
+ const issuer = createIssuer(gatewayKey, cfg.receiptsDir, options.log ?? openLog(cfg, gatewayKey), { exporter: options.exporter ?? openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
81
106
  const precommit = new Set(cfg.precommit);
82
- const consequential = (tool) => precommit.has("*") || precommit.has(tool);
107
+ const operationRule = (tool) => cfg.operations?.tools.find((rule) => rule.tool === tool);
108
+ const consequential = (tool) => !!operationRule(tool) || precommit.has("*") || precommit.has(tool);
83
109
  // A fact lookup runs before the policy can decide, because the policy decides on it. It is therefore a read the
84
110
  // gateway makes on the agent's request, never a consequential call: a fact tool named in precommit is a config error.
85
111
  // "*" covers the tools the agent calls; a lookup is the gateway's own read, so only an explicit name makes it consequential.
86
112
  for (const f of cfg.facts) {
87
- if (precommit.has(f.tool))
88
- throw new Error(`fact "${f.name}" uses tool ${f.tool}, which precommit names as consequential; a fact lookup runs before the policy decides and must be a read`);
113
+ if (precommit.has(f.tool) || operationRule(f.tool))
114
+ throw new Error(`fact "${f.name}" uses tool ${f.tool}, which ${precommit.has(f.tool) ? "precommit" : "operations"} names as consequential; a fact lookup runs before the policy decides and must be a read`);
115
+ if (cfg.approvals?.tools.some((rule) => rule.tool === f.tool))
116
+ throw new Error(`fact "${f.name}" uses tool ${f.tool}, which requires approval; a fact lookup must be a read that does not require approval`);
89
117
  }
118
+ // Revoked grants: digests of grant envelopes, from the file the operator edits (or `revoke` appends to), re-read
119
+ // whenever the file changes. Checked when a session opens and again on every call, so revocation takes effect on
120
+ // the next call of a running session, without a key rotation.
121
+ const revokedSet = new Set();
122
+ let revokedSeen = "";
123
+ const reloadRevoked = () => {
124
+ if (!cfg.revokedGrants)
125
+ return;
126
+ if (!existsSync(cfg.revokedGrants)) {
127
+ if (revokedSeen !== "absent") {
128
+ revokedSet.clear();
129
+ revokedSeen = "absent";
130
+ }
131
+ return;
132
+ }
133
+ // inode as well as mtime: `revoke` replaces the file by rename, so two writes in one mtime tick are still seen
134
+ const st = statSync(cfg.revokedGrants);
135
+ const m = `${st.ino}:${st.mtimeMs}:${st.size}`;
136
+ if (m === revokedSeen)
137
+ return;
138
+ const list = JSON.parse(readFileSync(cfg.revokedGrants, "utf8"));
139
+ if (!Array.isArray(list))
140
+ throw new Error(`${cfg.revokedGrants}: expected a JSON array of grant digests`);
141
+ revokedSet.clear();
142
+ for (const d of list)
143
+ if (typeof d === "string")
144
+ revokedSet.add(d);
145
+ revokedSeen = m;
146
+ };
147
+ const revoke = (digest) => {
148
+ reloadRevoked();
149
+ revokedSet.add(digest);
150
+ if (cfg.revokedGrants)
151
+ writeRevokedGrants(cfg.revokedGrants, [...revokedSet]);
152
+ };
90
153
  // One host, as many upstreams as the agents' jobs need. Each tool name belongs to exactly one upstream, decided at
91
154
  // startup, so a receipt's tool is unambiguous and consumed facts flow across them.
92
155
  const upstreamConfigs = cfg.upstreams ? cfg.upstreams.map((u) => ({ name: u.name, cfg: u })) : [{ name: "upstream", cfg: cfg.upstream }];
@@ -96,7 +159,10 @@ export async function createGatewayHost(cfg, options = {}) {
96
159
  for (const { name, cfg: u } of upstreamConfigs) {
97
160
  let client;
98
161
  if ("rest" in u) {
99
- client = restUpstream(name, u.rest);
162
+ client = restUpstream(name, { ...u.rest, tools: u.rest.tools.map((tool) => {
163
+ const rule = operationRule(tool.name);
164
+ return rule ? { ...tool, idempotencyHeader: rule.idempotencyHeader } : tool;
165
+ }) });
100
166
  }
101
167
  else if ("a2a" in u) {
102
168
  client = a2aUpstream(name, u.a2a);
@@ -125,25 +191,73 @@ export async function createGatewayHost(cfg, options = {}) {
125
191
  advertised.push(t);
126
192
  }
127
193
  }
194
+ for (const rule of cfg.operations?.tools ?? []) {
195
+ const via = upstreamConfigs.find((u) => u.name === owner.get(rule.tool));
196
+ const readVia = upstreamConfigs.find((u) => u.name === owner.get(rule.reconcile.tool));
197
+ // A REST read makes the provider lookup contract explicit. MCP payment providers must honor the operation
198
+ // metadata; A2A has no payment idempotency contract and cannot be used here.
199
+ if (!via || "a2a" in via.cfg)
200
+ throw new Error(`operation tool ${rule.tool} needs an MCP or REST upstream`);
201
+ if (!readVia || operationRule(rule.reconcile.tool) || precommit.has(rule.reconcile.tool))
202
+ throw new Error(`operation ${rule.tool}: reconciliation must name an advertised read tool`);
203
+ if ("rest" in readVia.cfg && readVia.cfg.rest.tools.find((t) => t.name === rule.reconcile.tool)?.method !== "GET")
204
+ throw new Error(`operation ${rule.tool}: REST reconciliation must use GET`);
205
+ }
206
+ const operations = cfg.operations ? new OperationStore(cfg.operations.database) : undefined;
207
+ const providerDigest = (tool) => digestOf({ upstream: upstreamConfigs.find((u) => u.name === owner.get(tool)), reconciliationUpstream: upstreamConfigs.find((u) => u.name === owner.get(operationRule(tool).reconcile.tool)), rule: operationRule(tool) });
208
+ const lookupFor = (op) => {
209
+ const rule = operationRule(op.tool);
210
+ return { tool: rule.reconcile.tool, args: Object.fromEntries(Object.entries(rule.reconcile.args).map(([key, value]) => [key, value === "$operation.idempotencyKey" ? op.idempotencyKey : value])), statusPath: rule.reconcile.statusPath, identityPath: rule.reconcile.identityPath, confirmed: rule.reconcile.confirmed, failed: rule.reconcile.failed };
211
+ };
212
+ const operationEvidence = (op, status = op.status) => ({ id: op.id, idempotencyKey: op.idempotencyKey, status, originalReceiptId: op.originalReceiptId, budget: { id: op.budget, currency: op.currency, period: op.period }, lookupDigest: digestOf(lookupFor(op)), provenance: "observed" });
213
+ const outcome = (op, result) => {
214
+ if (result.isError)
215
+ return "unknown";
216
+ const rule = operationRule(op.tool);
217
+ const value = providerField(result, rule.reconcile.statusPath);
218
+ if (typeof value !== "string")
219
+ return "pending";
220
+ // Even a provider's initial failure response retains the reservation: only the authoritative reconciliation
221
+ // read releases it. A response can be an error after the provider accepted the transfer.
222
+ if (rule.reconcile.confirmed.includes(value))
223
+ return "pending";
224
+ if (rule.reconcile.pending?.includes(value))
225
+ return "pending";
226
+ return "unknown";
227
+ };
128
228
  const callUpstream = async (name, args, meta) => {
129
229
  const via = owner.get(name);
130
230
  if (!via)
131
231
  throw new Error(`no upstream offers tool "${name}"`);
132
232
  return (await upstreams.get(via).callTool({ name, arguments: args, ...(meta ? { _meta: meta } : {}) }));
133
233
  };
234
+ /** The facts for a call, the argument template of the fact config each one came from (two configs may share a name), and each lookup's full result. */
134
235
  async function gatherFacts(tool, args, meta) {
135
- const facts = {};
236
+ // null-prototype, so a fact named __proto__ or constructor is a fact and not a prototype
237
+ const facts = Object.create(null);
238
+ const templates = Object.create(null);
239
+ const results = Object.create(null);
136
240
  for (const f of cfg.facts.filter((f) => f.forTools.includes(tool))) {
137
241
  const fargs = resolveFactArgs(f.args, args, f.optional);
138
242
  if (fargs === null)
139
243
  continue;
140
- // Lookups carry the same metadata as the forwarded call: they are the gateway acting for this receipt.
141
- const result = await callUpstream(f.tool, fargs, meta);
244
+ // Lookups carry the same metadata as the forwarded call: they are the gateway acting for this receipt. A failed
245
+ // lookup, answered isError or thrown, denies the call with the answer in policy.errors; the issuer withholds it
246
+ // under a private rule.
247
+ let result;
248
+ try {
249
+ result = await callUpstream(f.tool, fargs, meta);
250
+ }
251
+ catch (e) {
252
+ throw new Error(`fact "${f.name}" lookup via ${f.tool} failed: ${String(e instanceof Error ? e.message : e)}`);
253
+ }
142
254
  if (result.isError)
143
255
  throw new Error(`fact "${f.name}" lookup via ${f.tool} failed: ${JSON.stringify(extractValue(result))}`);
144
256
  facts[f.name] = { tool: f.tool, args: fargs, value: extractValue(result), resultDigest: digestOf(result), provenance: "observed" };
257
+ templates[f.name] = f.args;
258
+ results[f.name] = result;
145
259
  }
146
- return facts;
260
+ return { facts, templates, results };
147
261
  }
148
262
  function open(grantEnvelope) {
149
263
  const grant = verifyDelegation(grantEnvelope, trusted);
@@ -153,6 +267,26 @@ export async function createGatewayHost(cfg, options = {}) {
153
267
  throw new Error("delegation grant is outside its validity window");
154
268
  const delegation = grant.delegation;
155
269
  const principalKeyid = grant.keyid;
270
+ const chainDigests = grantChainDigests(grantEnvelope);
271
+ const grantDigest = chainDigests[0];
272
+ reloadRevoked();
273
+ if (chainDigests.some((d) => revokedSet.has(d)))
274
+ throw new Error("delegation grant has been revoked");
275
+ /** Why the grant is not in force at `at`, or null. Asked on every call, and again just before a forward. */
276
+ const grantProblem = (at = new Date().toISOString()) => {
277
+ try {
278
+ reloadRevoked();
279
+ }
280
+ catch (e) {
281
+ // fail closed: a revocation list that cannot be read revokes everything until it can
282
+ return `cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
283
+ }
284
+ if (chainDigests.some((d) => revokedSet.has(d)))
285
+ return "has been revoked";
286
+ if (!delegationValidAt(delegation, at))
287
+ return Date.parse(at) < Date.parse(delegation.issuedAt) ? "is not yet valid" : "has expired";
288
+ return null;
289
+ };
156
290
  /** Every fact id an upstream has declared it served to this session, in order of first sight. A session is one agent under one grant. */
157
291
  const consumed = [];
158
292
  const noteServedFacts = (result) => {
@@ -165,7 +299,19 @@ export async function createGatewayHost(cfg, options = {}) {
165
299
  };
166
300
  async function handleCall(params) {
167
301
  const tool = params.name;
168
- const args = params.arguments ?? {};
302
+ // An embedding caller can mutate its objects while a lookup or log append is awaited. Snapshot the call and
303
+ // approval before the first await, so the approved bytes are the bytes evaluated, logged, and forwarded. A caller
304
+ // also cannot change the payment after its reservation was bound.
305
+ const args = structuredClone(params.arguments ?? {});
306
+ const operationId = params._meta?.[OPERATION_META_KEY];
307
+ const suppliedApproval = params._meta?.[APPROVAL_META_KEY];
308
+ let approvalEnvelope;
309
+ try {
310
+ approvalEnvelope = structuredClone(suppliedApproval);
311
+ }
312
+ catch {
313
+ approvalEnvelope = undefined;
314
+ }
169
315
  const receiptId = randomUUID();
170
316
  const timestamp = new Date().toISOString();
171
317
  const modelClaim = params._meta?.[MODEL_META_KEY];
@@ -173,15 +319,54 @@ export async function createGatewayHost(cfg, options = {}) {
173
319
  const consumedNow = [...consumed];
174
320
  const upstreamMeta = { [RECEIPT_META_KEY]: receiptId, [AGENT_META_KEY]: delegation.agent, [PRINCIPAL_META_KEY]: delegation.principal };
175
321
  let facts = {};
322
+ let factTemplates = {};
323
+ let factResults = {};
176
324
  let policy;
177
325
  let execution;
326
+ /** what the upstream answered, in full: the agent gets this; the receipt gets the captured view */
327
+ let forwarded;
178
328
  let authorization;
179
- if (!delegation.scopes.includes(tool)) {
329
+ let approval;
330
+ let approvedWindow;
331
+ const rule = approvalRule(tool);
332
+ const approvalBinding = { principal: delegation.principal, agent: delegation.agent, tool, args, ...(rule?.fields ? { fields: rule.fields } : {}) };
333
+ // Only an authenticated statement is embedded in the approval record. Untrusted or malformed metadata is never
334
+ // copied there: it could carry arbitrary text from withheld arguments. Under a private rule the issuer then
335
+ // withholds the embedded envelope as a commitment (see CLEAR_IN.approval in capture.ts), because even an
336
+ // authentic one carries the action fields and an unsalted digest of the arguments.
337
+ const signedApproval = rule ? verifyApprovalStatement(approvalEnvelope, approvalKeys) : undefined;
338
+ // Signatures lie outside the signed payload. Keep only entries that independently verify: an attacker can
339
+ // append an untrusted signature, or a forged duplicate of a trusted key id, without invalidating the approval.
340
+ const rawEnvelope = signedApproval?.ok ? approvalEnvelope : undefined;
341
+ const envelope = rawEnvelope ? { ...rawEnvelope, signatures: rawEnvelope.signatures.filter((signature) => dsseVerifiers({ ...rawEnvelope, signatures: [signature] }, approvalKeys).length > 0) } : undefined;
342
+ const checkApproval = (at) => {
343
+ if (!rule)
344
+ return undefined;
345
+ const checked = verifyApproval(approvalEnvelope, approvalKeys, approvalBinding, { at, minApprovers: rule.minApprovers, maxLifetimeSeconds: cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS });
346
+ approval = { ...(envelope ? { envelope } : {}), requiredApprovers: rule.minApprovers, ...(rule.fields ? { fields: rule.fields } : {}), checkedAt: at, status: checked.ok ? "approved" : "denied", approverKeyids: checked.ok ? checked.approverKeyids : [], ...(!checked.ok ? { reason: envelope ? checked.error : "approval rejected: malformed or untrusted statement" } : {}), provenance: "observed" };
347
+ return checked;
348
+ };
349
+ const initialApproval = checkApproval(timestamp);
350
+ const approvalProblem = initialApproval && !initialApproval.ok ? initialApproval.error : undefined;
351
+ let operation;
352
+ let createdOperation = false;
353
+ let attemptedOperation = false;
354
+ // The grant is enforced in every mode: a call outside its scopes, or after it expired or was revoked, is denied
355
+ // and never forwarded, observe mode or not. Observe mode suspends the Cedar policy, nothing else.
356
+ const problem = grantProblem(timestamp);
357
+ const inScope = delegation.scopes.includes(tool);
358
+ if (problem) {
359
+ policy = { decision: "deny", reasons: [], errors: [`delegation grant ${problem}`], policyDigest: pDigest };
360
+ }
361
+ else if (!inScope) {
180
362
  policy = { decision: "deny", reasons: [], errors: [`tool "${tool}" is not in the delegation scopes`], policyDigest: pDigest };
181
363
  }
364
+ else if (approvalProblem) {
365
+ policy = { decision: "deny", reasons: [], errors: [`approval rejected: ${approvalProblem}`], policyDigest: pDigest };
366
+ }
182
367
  else {
183
368
  try {
184
- facts = await gatherFacts(tool, args, upstreamMeta);
369
+ ({ facts, templates: factTemplates, results: factResults } = await gatherFacts(tool, args, upstreamMeta));
185
370
  const factValues = Object.fromEntries(Object.entries(facts).map(([k, f]) => [k, f.value]));
186
371
  policy = evaluate(policyText, {
187
372
  agentId: delegation.agent,
@@ -195,9 +380,19 @@ export async function createGatewayHost(cfg, options = {}) {
195
380
  }
196
381
  // Observe mode: the decision is recorded, never enforced. The receipt says so on every call, so a verifier can
197
382
  // tell a policy that was being tested from one that was in force.
198
- if (cfg.mode === "observe")
383
+ if (cfg.mode === "observe" && !problem && inScope && !approvalProblem)
199
384
  policy = { ...policy, enforced: false };
200
385
  const forward = policy.decision === "allow" || policy.enforced === false;
386
+ // Private evidence is applied by the issuer to the whole statement. What it cannot know by itself: a fact's lookup
387
+ // arguments are copied from the call, so a fact argument may stay in clear only when its template is a constant or
388
+ // copies a call argument the args rule keeps in clear (the rule's `clear` names call arguments, and a fact argument
389
+ // may carry one under another name); the template is the one of the fact config that was used, since fact names
390
+ // are not unique across tools. And the lookups' full results, behind the facts' digests.
391
+ // the same rule the issuer will apply: for a name no upstream offers that may be the wildcard, not the name's own
392
+ const argsClear = new Set(effectiveRule(cfg.capture, tool, !owner.has(tool))?.args?.clear ?? []);
393
+ const clearFactArgs = Object.fromEntries(Object.entries(factTemplates).map(([name, template]) => [name, Object.entries(template).filter(([, v]) => !v.startsWith("$args.") || argsClear.has(v.slice("$args.".length))).map(([k]) => k)]));
394
+ // a name no upstream offers is text the agent chose: the issuer selects the rule by it and masks it in the view
395
+ const captureCtx = { clearFactArgs, factResults, unknownTool: !owner.has(tool) };
201
396
  const head = {
202
397
  receiptId,
203
398
  timestamp,
@@ -209,60 +404,173 @@ export async function createGatewayHost(cfg, options = {}) {
209
404
  request: { args, argsDigest: digestOf(args), provenance: "claimed" },
210
405
  facts,
211
406
  consumed: { factIds: consumedNow, provenance: "observed" },
407
+ ...(approval ? { approval } : {}),
408
+ operation: undefined,
212
409
  };
213
- if (policy.decision === "allow" && consequential(tool)) {
410
+ const financial = operationRule(tool);
411
+ if (forward && financial) {
412
+ try {
413
+ if (typeof operationId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(operationId))
414
+ throw new Error(`financial calls require a stable UUID in _meta["${OPERATION_META_KEY}"]`);
415
+ const budget = cfg.operations.budgets.find((b) => b.id === financial.budget);
416
+ if (args[financial.currencyField] !== budget.currency)
417
+ throw new Error(`operation currency must match budget ${budget.id}`);
418
+ const amount = args[financial.amountField];
419
+ if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount <= 0)
420
+ throw new Error("operation amount must be a positive safe integer in minor units");
421
+ const reserved = operations.reserve({ id: operationId, issuerKeyid: issuer.keyid, providerDigest: providerDigest(tool), principal: delegation.principal, agent: delegation.agent, tool, argsDigest: digestOf(args), budget: budget.id, currency: budget.currency, amount, limit: budget.limit, originalReceiptId: receiptId, unsent: { ...head, policy: { ...policy, provenance: "observed" } } });
422
+ operation = reserved.operation;
423
+ createdOperation = reserved.created;
424
+ head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
425
+ }
426
+ catch (e) {
427
+ execution = { status: "withheld", reason: `operation not forwarded: ${e instanceof Error ? e.message : String(e)}`, provenance: "observed" };
428
+ }
429
+ }
430
+ /** The answer to a retry of an existing operation: the stored outcome, which the retry receipt below records as withheld. */
431
+ let cached;
432
+ if (!execution && operation && !createdOperation) {
433
+ // An existing reservation can mean another process is still forwarding, or died immediately afterwards.
434
+ // Never repeat the side effect. Reconciliation is the only path from an uncertain operation to closure.
435
+ // The retry gets a receipt of its own, so that the log shows the agent asked again and what it was told.
436
+ const settled = operation.reconciliation;
437
+ const result = settled?.bundle && settled.predicate && "result" in settled.predicate.execution ? settled.predicate.execution.result : operation.result;
438
+ const receipt = settled?.bundle ? settled.predicate.receiptId : operation.originalReceiptId;
439
+ cached = { ...(result ?? { isError: true, content: [{ type: "text", text: head.operation.status === "failed" ? "Operation failed and the call was not sent; use a new operation id to try again" : `Operation outcome is ${head.operation.status}; reconcile with the provider before taking further action` }] }), _meta: { ...result?._meta, [RECEIPT_META_KEY]: receipt, ...(operation.original && !existsSync(`${cfg.receiptsDir}/${operation.originalReceiptId}.json`) ? { "agent-custody/authorization": operation.original } : {}) } };
440
+ execution = { status: "withheld", reason: `existing operation: not forwarded again; the stored outcome is ${head.operation.status}`, provenance: "observed" };
441
+ }
442
+ if (!execution && (policy.decision === "allow" || financial && forward) && consequential(tool)) {
214
443
  // A consequential call is committed to the log before it goes out, so that evidence of the side effect exists
215
444
  // before the side effect does. If the log will not take the authorization, the call is not forwarded; in
216
445
  // observe mode nothing is withheld, and the missing authorization is printed instead.
217
446
  try {
218
- authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } });
447
+ authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } }, captureCtx);
219
448
  }
220
449
  catch (e) {
221
- if (cfg.mode === "observe")
450
+ if (cfg.mode === "observe" && !financial)
222
451
  console.error(`agent-custody gateway (observe mode): the log did not commit the authorization for ${tool}, receipt ${receiptId}; the call was forwarded without it: ${String(e instanceof Error ? e.message : e)}`);
223
452
  else
224
453
  execution = { status: "withheld", reason: `the log did not commit the authorization, so the call was not forwarded: ${String(e instanceof Error ? e.message : e)}`, provenance: "observed" };
225
454
  }
455
+ if (authorization && operation) {
456
+ try {
457
+ operation = operations.saveAuthorization(operation.id, authorization);
458
+ }
459
+ catch (e) {
460
+ // Recovery closed this operation as "not forwarded" while the log held the authorization. Its closing receipt
461
+ // has this receipt id, so no second receipt is issued. The call is not forwarded.
462
+ return { isError: true, content: [{ type: "text", text: `Not executed: ${String(e instanceof Error ? e.message : e)} (receipt ${receiptId})` }], _meta: { [RECEIPT_META_KEY]: receiptId, [OPERATION_META_KEY]: operationEvidence(operations.get(operation.id) ?? operation) } };
463
+ }
464
+ }
465
+ }
466
+ let late = execution ? null : forward ? grantProblem() : null;
467
+ if (!execution && !late && forward && rule) {
468
+ // No awaits between this fresh check, the persistent atomic claim, and entering the upstream call. The
469
+ // claim is shared across sessions and processes, and a storage error withholds the side effect.
470
+ const at = new Date().toISOString();
471
+ const checked = checkApproval(at);
472
+ if (!checked.ok) {
473
+ execution = { status: "withheld", reason: `approval rejected before the call was forwarded: ${checked.error}`, provenance: "observed" };
474
+ }
475
+ else {
476
+ try {
477
+ consumeApproval(cfg.approvals.usedDir, checked.approval.approvalId, receiptId, at);
478
+ // A synchronous durable claim can block on storage. Recheck after it returns, because the grant or
479
+ // approval may have expired (or the grant been revoked) during that wait. A refusal keeps the claim.
480
+ const afterConsume = new Date().toISOString();
481
+ const finalCheck = checkApproval(afterConsume);
482
+ // Signature verification can be slow too. Read revocations after it, immediately before the cheap
483
+ // final window check, so a revocation made during that work still withholds this call.
484
+ late = grantProblem();
485
+ approval = { ...approval, consumedAt: afterConsume };
486
+ if (!finalCheck.ok)
487
+ execution = { status: "withheld", reason: `approval rejected before the call was forwarded: ${finalCheck.error}`, provenance: "observed" };
488
+ else
489
+ approvedWindow = { issuedAt: Date.parse(finalCheck.approval.issuedAt), expiresAt: Date.parse(finalCheck.approval.expiresAt) };
490
+ }
491
+ catch (e) {
492
+ const reason = `approval could not be consumed: ${String(e instanceof Error ? e.message : e)}`;
493
+ approval = { ...approval, status: "denied", reason };
494
+ execution = { status: "withheld", reason, provenance: "observed" };
495
+ }
496
+ }
226
497
  }
227
498
  if (execution) {
228
499
  // withheld: nothing was forwarded
229
500
  }
501
+ else if (late) {
502
+ // the grant ran out, or was revoked, while the facts were gathered or the authorization logged
503
+ execution = { status: "withheld", reason: `the delegation grant ${late} before the call was forwarded`, provenance: "observed" };
504
+ }
230
505
  else if (forward) {
231
506
  try {
232
507
  // The upstream learns which receipt this call is, and who the grant says is calling. An upstream that keeps
233
508
  // state, such as the memory server, cites the receipt as the source of what it stores.
234
509
  const observed = Object.fromEntries(Object.entries(facts).map(([k, f]) => [k, f.value]));
235
- const result = await callUpstream(tool, args, { ...upstreamMeta, [OBSERVED_META_KEY]: observed });
236
- const evidence = upstreamEvidenceOf(result);
237
- execution = { status: result.isError ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed", ...(evidence ? { upstream: evidence } : {}) };
238
- noteServedFacts(result);
510
+ // Signature checks and revocation-file I/O can themselves take time. Sample once more after all of them,
511
+ // using the authenticated window directly, so this last check does no crypto or storage before forwarding.
512
+ const forwardAt = new Date().toISOString();
513
+ const forwardMs = Date.parse(forwardAt);
514
+ if (approval)
515
+ approval = { ...approval, checkedAt: forwardAt, ...(approval.consumedAt ? { consumedAt: forwardAt } : {}) };
516
+ if (rule && (!approvedWindow || forwardMs < approvedWindow.issuedAt || forwardMs >= approvedWindow.expiresAt)) {
517
+ const reason = approvedWindow && forwardMs < approvedWindow.issuedAt ? "approval is not yet valid" : "approval has expired";
518
+ approval = { ...approval, status: "denied", reason, approverKeyids: [] };
519
+ execution = { status: "withheld", reason: `approval rejected before the call was forwarded: ${reason}`, provenance: "observed" };
520
+ }
521
+ else if (!delegationValidAt(delegation, forwardAt)) {
522
+ execution = { status: "withheld", reason: "the delegation grant is outside its validity window before the call was forwarded", provenance: "observed" };
523
+ }
524
+ else {
525
+ attemptedOperation = !!operation;
526
+ const result = await callUpstream(tool, args, { ...upstreamMeta, [OBSERVED_META_KEY]: observed, ...(operation ? { [OPERATION_META_KEY]: { id: operation.id, idempotencyKey: operation.idempotencyKey } } : {}) });
527
+ const evidence = upstreamEvidenceOf(result);
528
+ forwarded = result;
529
+ execution = { status: result.isError ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed", ...(evidence ? { upstream: evidence } : {}) };
530
+ noteServedFacts(result);
531
+ if (operation)
532
+ operation = operations.update(operation.id, { status: outcome(operation, result), result });
533
+ }
239
534
  }
240
535
  catch (e) {
241
536
  execution = { status: "error", error: String(e instanceof Error ? e.message : e), provenance: "observed" };
537
+ if (operation)
538
+ operation = operations.update(operation.id, { status: "unknown" });
242
539
  }
243
540
  }
244
541
  else {
245
542
  execution = { status: "denied", reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched", provenance: "observed" };
246
543
  }
247
- await issuer.issue({
544
+ // Only a call known never to have been forwarded may release a reservation without a provider record.
545
+ if (operation && createdOperation && !attemptedOperation)
546
+ operation = operations.update(operation.id, { status: "failed", unsent: undefined });
547
+ if (operation)
548
+ head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
549
+ const issued = await issuer.issue({
248
550
  ...head,
551
+ ...(approval ? { approval } : {}),
249
552
  session: { id: null, toolUseId: null, provenance: "claimed" },
250
553
  model: { id: typeof modelClaim === "string" ? modelClaim : null, provenance: "claimed" },
251
554
  policy: { ...policy, provenance: "observed" },
252
555
  ...(authorization ? { authorization } : {}),
253
556
  execution,
254
- });
255
- const meta = { [RECEIPT_META_KEY]: receiptId };
557
+ }, captureCtx);
558
+ if (operation && createdOperation && attemptedOperation)
559
+ operations.update(operation.id, { original: issued });
560
+ const meta = { [RECEIPT_META_KEY]: receiptId, ...(head.operation ? { [OPERATION_META_KEY]: head.operation } : {}) };
256
561
  const refuse = (text) => ({ isError: true, content: [{ type: "text", text: `${text} (receipt ${receiptId})` }], _meta: meta });
257
562
  switch (execution.status) {
563
+ // the agent gets the real result, the real reason, and the real error: what is withheld is withheld from the receipt
258
564
  case "denied":
259
565
  return refuse(`Denied by policy: ${execution.reason}`);
260
566
  case "error":
261
567
  return refuse(`Upstream error: ${execution.error}`);
262
568
  case "withheld":
569
+ if (cached)
570
+ return { ...cached, _meta: { ...cached._meta, [OPERATION_META_KEY]: head.operation, [RETRY_RECEIPT_META_KEY]: receiptId } };
263
571
  return refuse(`Not executed: ${execution.reason}`);
264
572
  default: {
265
- const result = execution.result;
573
+ const result = forwarded ?? execution.result;
266
574
  return { ...result, _meta: { ...result._meta, ...meta } };
267
575
  }
268
576
  }
@@ -270,6 +578,8 @@ export async function createGatewayHost(cfg, options = {}) {
270
578
  return {
271
579
  agentId: delegation.agent,
272
580
  delegation,
581
+ grantDigest,
582
+ grantProblem,
273
583
  async listTools() {
274
584
  return advertised.filter((t) => delegation.scopes.includes(t.name));
275
585
  },
@@ -282,9 +592,86 @@ export async function createGatewayHost(cfg, options = {}) {
282
592
  return {
283
593
  keyid: issuer.keyid,
284
594
  open,
595
+ revoke,
596
+ revoked: () => {
597
+ reloadRevoked();
598
+ return [...revokedSet];
599
+ },
600
+ async reconcile(operationId) {
601
+ if (!operations)
602
+ throw new Error("gateway has no financial operations configured");
603
+ const op = operations.get(operationId);
604
+ if (!op)
605
+ throw new Error("operation not found");
606
+ if (op.issuerKeyid !== issuer.keyid || op.providerDigest !== providerDigest(op.tool))
607
+ throw new Error("operation provider or gateway identity changed; use the original configuration");
608
+ let intent = op.reconciliation;
609
+ if (intent?.bundle)
610
+ return intent.bundle;
611
+ if (!intent) {
612
+ if (op.status === "failed")
613
+ throw new Error("operation was never forwarded and needs no provider reconciliation");
614
+ // SQLite is shared on this machine. A live creator may still be about to send, or awaiting its response;
615
+ // reconciliation cannot release its budget underneath that forward. A process with the same PID but another
616
+ // start time is not the creator. A start time that cannot be read fails closed.
617
+ if (op.status === "submitted" && ownerAlive(op))
618
+ throw new Error("operation is still submitted by a live process; wait for its outcome before reconciling");
619
+ const original = op.original;
620
+ if (!original) {
621
+ // The authorization is saved before the forward. A dead creator and no authorization prove that the call was
622
+ // never sent. Close it with a receipt that says so, then release the reservation.
623
+ const unsent = op.unsent;
624
+ if (!unsent)
625
+ throw new Error("operation has no committed authorization and no record of the call; it was not forwarded");
626
+ const predicate = {
627
+ ...unsent, receiptId: op.originalReceiptId, timestamp: new Date().toISOString(),
628
+ session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
629
+ operation: operationEvidence(op, "failed"),
630
+ execution: { status: "withheld", reason: "the gateway stopped before it forwarded the call; the call was not forwarded", provenance: "observed" },
631
+ };
632
+ intent = operations.claimReconciliation(op.id, { predicate }, true);
633
+ }
634
+ }
635
+ if (!intent) {
636
+ const original = op.original;
637
+ const checked = dsseVerify(original.envelope, [gatewayKey]);
638
+ if (!checked.ok)
639
+ throw new Error("stored original operation signature is invalid");
640
+ const initial = checked.payload.predicate;
641
+ const lookup = lookupFor(op);
642
+ const result = await callUpstream(lookup.tool, lookup.args);
643
+ const identity = providerField(result, lookup.identityPath);
644
+ if (identity !== op.idempotencyKey)
645
+ throw new Error("provider record does not bind this operation's idempotency key; the reservation is retained");
646
+ const value = providerField(result, lookup.statusPath);
647
+ const status = typeof value === "string" && !result.isError ? lookup.confirmed.includes(value) ? "confirmed" : lookup.failed.includes(value) ? "failed" : null : null;
648
+ if (!status)
649
+ throw new Error("provider outcome remains pending or unknown; the reservation is retained");
650
+ const predicate = {
651
+ receiptId: randomUUID(), timestamp: new Date().toISOString(),
652
+ issuer: { kind: "gateway", keyid: issuer.keyid, version: GATEWAY_VERSION },
653
+ principal: initial.principal, agent: initial.agent, delegation: initial.delegation,
654
+ session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
655
+ tool: initial.tool, request: { args: lookup.args, argsDigest: digestOf(lookup.args), provenance: "claimed" },
656
+ facts: {}, policy: { decision: "allow", reasons: ["reconciliation: the gateway read the provider record and evaluated no policy"], errors: [], policyDigest: pDigest, provenance: "observed" },
657
+ operation: operationEvidence(op, status), reconciliation: { original, lookup },
658
+ execution: { status: "executed", result, resultDigest: digestOf(result), provenance: "observed" },
659
+ };
660
+ intent = operations.claimReconciliation(op.id, { predicate });
661
+ }
662
+ // Commit the receipt before releasing a failed reservation. A crash before this update retains the amount;
663
+ // the persisted intent allows another operator/process to finish precisely the same resolution.
664
+ // A receipt for an unsent call holds the call's own values, so the issuer applies the capture rule of its tool.
665
+ const ctx = intent.predicate.reconciliation ? undefined : { unknownTool: !owner.has(intent.predicate.tool.name) };
666
+ const bundle = intent.bundle ?? await issuer.issue(intent.predicate, ctx, (prepared) => operations.prepareReconciliation(op.id, prepared));
667
+ const retained = operations.get(op.id).reconciliation;
668
+ operations.update(op.id, { status: intent.predicate.operation.status, reconciliation: { ...retained, bundle }, result: intent.predicate.execution.result, unsent: undefined });
669
+ return bundle;
670
+ },
285
671
  async close() {
286
672
  for (const c of upstreams.values())
287
673
  await c.close();
674
+ operations?.close();
288
675
  },
289
676
  };
290
677
  }