@agent-custody/receipts 0.7.0 → 0.9.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 (51) hide show
  1. package/README.md +29 -13
  2. package/dist/approval.d.ts +74 -0
  3. package/dist/approval.js +196 -0
  4. package/dist/capture.js +49 -1
  5. package/dist/check.d.ts +19 -0
  6. package/dist/check.js +288 -0
  7. package/dist/cli.js +238 -11
  8. package/dist/config.d.ts +85 -0
  9. package/dist/config.js +72 -2
  10. package/dist/console-page.d.ts +4 -0
  11. package/dist/console-page.js +342 -0
  12. package/dist/console.d.ts +20 -0
  13. package/dist/console.js +521 -0
  14. package/dist/gateway.d.ts +9 -0
  15. package/dist/gateway.js +335 -45
  16. package/dist/index.d.ts +9 -2
  17. package/dist/index.js +7 -1
  18. package/dist/issue.d.ts +8 -3
  19. package/dist/issue.js +13 -4
  20. package/dist/log-store.d.ts +3 -2
  21. package/dist/log-store.js +2 -0
  22. package/dist/operations.d.ts +101 -0
  23. package/dist/operations.js +239 -0
  24. package/dist/otel.js +12 -5
  25. package/dist/policy.d.ts +2 -0
  26. package/dist/policy.js +10 -0
  27. package/dist/portal.d.ts +78 -4
  28. package/dist/portal.js +516 -26
  29. package/dist/receipt.d.ts +36 -1
  30. package/dist/rest.js +14 -1
  31. package/dist/simulate.d.ts +58 -0
  32. package/dist/simulate.js +204 -0
  33. package/dist/splunk.js +11 -4
  34. package/dist/sso.d.ts +47 -0
  35. package/dist/sso.js +161 -0
  36. package/dist/verify.d.ts +2 -0
  37. package/dist/verify.js +241 -7
  38. package/docs/approvals.md +107 -0
  39. package/docs/codex-recovery.md +132 -0
  40. package/docs/configuration.md +224 -0
  41. package/docs/console.md +79 -0
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +23 -0
  44. package/docs/threat-model.md +13 -0
  45. package/docs/tutorials.md +9 -0
  46. package/docs/usage.md +49 -4
  47. package/docs/verification.md +26 -8
  48. package/package.json +8 -2
  49. package/vectors/audit.json +27 -27
  50. package/vectors/canonical.json +5 -5
  51. package/vectors/receipts.json +2866 -464
package/dist/gateway.js CHANGED
@@ -8,8 +8,9 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
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";
11
+ import { digestOf, dsseVerifiers, dsseVerify, loadPrivateKey, loadPublicKey } from "./crypto.js";
12
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";
@@ -18,9 +19,12 @@ import { restUpstream } from "./rest.js";
18
19
  import { a2aUpstream } from "./a2a.js";
19
20
  import { captureKeyFrom, effectiveRule } from "./capture.js";
20
21
  import { evaluate, policyDigest } from "./policy.js";
22
+ import { OPERATION_META_KEY, OperationStore, ownerAlive } from "./operations.js";
21
23
  export const GATEWAY_VERSION = "0.1.0";
22
24
  export const RECEIPT_META_KEY = "agent-custody/receipt";
23
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";
24
28
  /** Set by the gateway on the call it forwards upstream: the receipt id, and the agent and principal from the attested grant. */
25
29
  export const AGENT_META_KEY = "agent-custody/agent";
26
30
  export const PRINCIPAL_META_KEY = "agent-custody/principal";
@@ -59,6 +63,10 @@ function extractValue(result) {
59
63
  return text.text;
60
64
  }
61
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
+ }
62
70
  /**
63
71
  * The environment a stdio upstream is started with: what a child process needs to run, plus what the config names.
64
72
  * Never the gateway's own environment, which holds the tokens other upstreams and the log are given. An explicit
@@ -82,6 +90,8 @@ export function writeRevokedGrants(path, digests) {
82
90
  export async function createGatewayHost(cfg, options = {}) {
83
91
  const gatewayKey = loadPrivateKey(cfg.identity.keyFile);
84
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 === "*");
85
95
  const policyText = readFileSync(cfg.policyFile, "utf8");
86
96
  const pDigest = policyDigest(policyText);
87
97
  // Private evidence: the key that encrypts withheld fields, read once; a rule in mode encrypted without it is a config error.
@@ -94,13 +104,16 @@ export async function createGatewayHost(cfg, options = {}) {
94
104
  // The rules are applied by the issuer to every statement it signs, the authorization included: the gateway hands it the call in full.
95
105
  const issuer = createIssuer(gatewayKey, cfg.receiptsDir, options.log ?? openLog(cfg, gatewayKey), { exporter: options.exporter ?? openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
96
106
  const precommit = new Set(cfg.precommit);
97
- 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);
98
109
  // A fact lookup runs before the policy can decide, because the policy decides on it. It is therefore a read the
99
110
  // gateway makes on the agent's request, never a consequential call: a fact tool named in precommit is a config error.
100
111
  // "*" covers the tools the agent calls; a lookup is the gateway's own read, so only an explicit name makes it consequential.
101
112
  for (const f of cfg.facts) {
102
- if (precommit.has(f.tool))
103
- 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`);
104
117
  }
105
118
  // Revoked grants: digests of grant envelopes, from the file the operator edits (or `revoke` appends to), re-read
106
119
  // whenever the file changes. Checked when a session opens and again on every call, so revocation takes effect on
@@ -143,38 +156,96 @@ export async function createGatewayHost(cfg, options = {}) {
143
156
  const upstreams = new Map();
144
157
  const owner = new Map();
145
158
  const advertised = [];
146
- for (const { name, cfg: u } of upstreamConfigs) {
147
- let client;
148
- if ("rest" in u) {
149
- client = restUpstream(name, u.rest);
150
- }
151
- else if ("a2a" in u) {
152
- client = a2aUpstream(name, u.a2a);
153
- }
154
- else if ("url" in u) {
155
- client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
156
- const token = u.tokenEnv ? process.env[u.tokenEnv] : undefined;
157
- if (u.tokenEnv && !token)
158
- throw new Error(`upstream ${name}: environment variable ${u.tokenEnv} is not set`);
159
- await client.connect(new StreamableHTTPClientTransport(new URL(u.url), token ? { requestInit: { headers: { authorization: `Bearer ${token}` } } } : {}));
160
- }
161
- else {
162
- client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
163
- await client.connect(new StdioClientTransport({ command: u.command, args: u.args, env: upstreamEnv(u.env), stderr: "inherit" }));
164
- }
165
- upstreams.set(name, client);
166
- const { tools } = await client.listTools();
167
- for (const t of tools) {
168
- const other = owner.get(t.name);
169
- if (other) {
170
- for (const c of upstreams.values())
171
- await c.close();
172
- throw new Error(`tool "${t.name}" is offered by both upstream "${other}" and upstream "${name}"; a gateway needs one owner per tool`);
159
+ const cancelled = options.signal
160
+ ? new Promise((_, reject) => {
161
+ const stop = () => reject(new Error("the gateway start was cancelled"));
162
+ if (options.signal.aborted)
163
+ stop();
164
+ else
165
+ options.signal.addEventListener("abort", stop, { once: true });
166
+ })
167
+ : null;
168
+ cancelled?.catch(() => { });
169
+ /** a connection that hangs must not hold the start: it loses the race to a cancel */
170
+ const guard = (p) => (cancelled ? Promise.race([p, cancelled]) : p);
171
+ try {
172
+ for (const { name, cfg: u } of upstreamConfigs) {
173
+ options.signal?.throwIfAborted();
174
+ let client;
175
+ if ("rest" in u) {
176
+ client = restUpstream(name, { ...u.rest, tools: u.rest.tools.map((tool) => {
177
+ const rule = operationRule(tool.name);
178
+ return rule ? { ...tool, idempotencyHeader: rule.idempotencyHeader } : tool;
179
+ }) });
180
+ upstreams.set(name, client);
181
+ }
182
+ else if ("a2a" in u) {
183
+ client = a2aUpstream(name, u.a2a);
184
+ upstreams.set(name, client);
185
+ }
186
+ else if ("url" in u) {
187
+ client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
188
+ upstreams.set(name, client);
189
+ const token = u.tokenEnv ? process.env[u.tokenEnv] : undefined;
190
+ if (u.tokenEnv && !token)
191
+ throw new Error(`upstream ${name}: environment variable ${u.tokenEnv} is not set`);
192
+ await guard(client.connect(new StreamableHTTPClientTransport(new URL(u.url), token ? { requestInit: { headers: { authorization: `Bearer ${token}` } } } : {})));
193
+ }
194
+ else {
195
+ client = new Client({ name: "agent-custody-gateway", version: GATEWAY_VERSION });
196
+ upstreams.set(name, client);
197
+ await guard(client.connect(new StdioClientTransport({ command: u.command, args: u.args, env: upstreamEnv(u.env), stderr: "inherit" })));
198
+ }
199
+ const { tools } = await guard(client.listTools());
200
+ for (const t of tools) {
201
+ const other = owner.get(t.name);
202
+ if (other)
203
+ throw new Error(`tool "${t.name}" is offered by both upstream "${other}" and upstream "${name}"; a gateway needs one owner per tool`);
204
+ owner.set(t.name, name);
205
+ advertised.push(t);
173
206
  }
174
- owner.set(t.name, name);
175
- advertised.push(t);
176
207
  }
177
208
  }
209
+ catch (e) {
210
+ // an upstream that was started stays running unless it is closed here: a failed or cancelled start leaves nothing behind
211
+ for (const c of upstreams.values())
212
+ await c.close().catch(() => { });
213
+ throw e;
214
+ }
215
+ for (const rule of cfg.operations?.tools ?? []) {
216
+ const via = upstreamConfigs.find((u) => u.name === owner.get(rule.tool));
217
+ const readVia = upstreamConfigs.find((u) => u.name === owner.get(rule.reconcile.tool));
218
+ // A REST read makes the provider lookup contract explicit. MCP payment providers must honor the operation
219
+ // metadata; A2A has no payment idempotency contract and cannot be used here.
220
+ if (!via || "a2a" in via.cfg)
221
+ throw new Error(`operation tool ${rule.tool} needs an MCP or REST upstream`);
222
+ if (!readVia || operationRule(rule.reconcile.tool) || precommit.has(rule.reconcile.tool))
223
+ throw new Error(`operation ${rule.tool}: reconciliation must name an advertised read tool`);
224
+ if ("rest" in readVia.cfg && readVia.cfg.rest.tools.find((t) => t.name === rule.reconcile.tool)?.method !== "GET")
225
+ throw new Error(`operation ${rule.tool}: REST reconciliation must use GET`);
226
+ }
227
+ const operations = cfg.operations ? new OperationStore(cfg.operations.database) : undefined;
228
+ 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) });
229
+ const lookupFor = (op) => {
230
+ const rule = operationRule(op.tool);
231
+ 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 };
232
+ };
233
+ 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" });
234
+ const outcome = (op, result) => {
235
+ if (result.isError)
236
+ return "unknown";
237
+ const rule = operationRule(op.tool);
238
+ const value = providerField(result, rule.reconcile.statusPath);
239
+ if (typeof value !== "string")
240
+ return "pending";
241
+ // Even a provider's initial failure response retains the reservation: only the authoritative reconciliation
242
+ // read releases it. A response can be an error after the provider accepted the transfer.
243
+ if (rule.reconcile.confirmed.includes(value))
244
+ return "pending";
245
+ if (rule.reconcile.pending?.includes(value))
246
+ return "pending";
247
+ return "unknown";
248
+ };
178
249
  const callUpstream = async (name, args, meta) => {
179
250
  const via = owner.get(name);
180
251
  if (!via)
@@ -249,7 +320,19 @@ export async function createGatewayHost(cfg, options = {}) {
249
320
  };
250
321
  async function handleCall(params) {
251
322
  const tool = params.name;
252
- const args = params.arguments ?? {};
323
+ // An embedding caller can mutate its objects while a lookup or log append is awaited. Snapshot the call and
324
+ // approval before the first await, so the approved bytes are the bytes evaluated, logged, and forwarded. A caller
325
+ // also cannot change the payment after its reservation was bound.
326
+ const args = structuredClone(params.arguments ?? {});
327
+ const operationId = params._meta?.[OPERATION_META_KEY];
328
+ const suppliedApproval = params._meta?.[APPROVAL_META_KEY];
329
+ let approvalEnvelope;
330
+ try {
331
+ approvalEnvelope = structuredClone(suppliedApproval);
332
+ }
333
+ catch {
334
+ approvalEnvelope = undefined;
335
+ }
253
336
  const receiptId = randomUUID();
254
337
  const timestamp = new Date().toISOString();
255
338
  const modelClaim = params._meta?.[MODEL_META_KEY];
@@ -264,6 +347,31 @@ export async function createGatewayHost(cfg, options = {}) {
264
347
  /** what the upstream answered, in full: the agent gets this; the receipt gets the captured view */
265
348
  let forwarded;
266
349
  let authorization;
350
+ let approval;
351
+ let approvedWindow;
352
+ const rule = approvalRule(tool);
353
+ const approvalBinding = { principal: delegation.principal, agent: delegation.agent, tool, args, ...(rule?.fields ? { fields: rule.fields } : {}) };
354
+ // Only an authenticated statement is embedded in the approval record. Untrusted or malformed metadata is never
355
+ // copied there: it could carry arbitrary text from withheld arguments. Under a private rule the issuer then
356
+ // withholds the embedded envelope as a commitment (see CLEAR_IN.approval in capture.ts), because even an
357
+ // authentic one carries the action fields and an unsalted digest of the arguments.
358
+ const signedApproval = rule ? verifyApprovalStatement(approvalEnvelope, approvalKeys) : undefined;
359
+ // Signatures lie outside the signed payload. Keep only entries that independently verify: an attacker can
360
+ // append an untrusted signature, or a forged duplicate of a trusted key id, without invalidating the approval.
361
+ const rawEnvelope = signedApproval?.ok ? approvalEnvelope : undefined;
362
+ const envelope = rawEnvelope ? { ...rawEnvelope, signatures: rawEnvelope.signatures.filter((signature) => dsseVerifiers({ ...rawEnvelope, signatures: [signature] }, approvalKeys).length > 0) } : undefined;
363
+ const checkApproval = (at) => {
364
+ if (!rule)
365
+ return undefined;
366
+ const checked = verifyApproval(approvalEnvelope, approvalKeys, approvalBinding, { at, minApprovers: rule.minApprovers, maxLifetimeSeconds: cfg.approvals.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS });
367
+ 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" };
368
+ return checked;
369
+ };
370
+ const initialApproval = checkApproval(timestamp);
371
+ const approvalProblem = initialApproval && !initialApproval.ok ? initialApproval.error : undefined;
372
+ let operation;
373
+ let createdOperation = false;
374
+ let attemptedOperation = false;
267
375
  // The grant is enforced in every mode: a call outside its scopes, or after it expired or was revoked, is denied
268
376
  // and never forwarded, observe mode or not. Observe mode suspends the Cedar policy, nothing else.
269
377
  const problem = grantProblem(timestamp);
@@ -274,6 +382,9 @@ export async function createGatewayHost(cfg, options = {}) {
274
382
  else if (!inScope) {
275
383
  policy = { decision: "deny", reasons: [], errors: [`tool "${tool}" is not in the delegation scopes`], policyDigest: pDigest };
276
384
  }
385
+ else if (approvalProblem) {
386
+ policy = { decision: "deny", reasons: [], errors: [`approval rejected: ${approvalProblem}`], policyDigest: pDigest };
387
+ }
277
388
  else {
278
389
  try {
279
390
  ({ facts, templates: factTemplates, results: factResults } = await gatherFacts(tool, args, upstreamMeta));
@@ -290,7 +401,7 @@ export async function createGatewayHost(cfg, options = {}) {
290
401
  }
291
402
  // Observe mode: the decision is recorded, never enforced. The receipt says so on every call, so a verifier can
292
403
  // tell a policy that was being tested from one that was in force.
293
- if (cfg.mode === "observe" && !problem && inScope)
404
+ if (cfg.mode === "observe" && !problem && inScope && !approvalProblem)
294
405
  policy = { ...policy, enforced: false };
295
406
  const forward = policy.decision === "allow" || policy.enforced === false;
296
407
  // Private evidence is applied by the issuer to the whole statement. What it cannot know by itself: a fact's lookup
@@ -314,8 +425,42 @@ export async function createGatewayHost(cfg, options = {}) {
314
425
  request: { args, argsDigest: digestOf(args), provenance: "claimed" },
315
426
  facts,
316
427
  consumed: { factIds: consumedNow, provenance: "observed" },
428
+ ...(approval ? { approval } : {}),
429
+ operation: undefined,
317
430
  };
318
- if (policy.decision === "allow" && consequential(tool)) {
431
+ const financial = operationRule(tool);
432
+ if (forward && financial) {
433
+ try {
434
+ 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))
435
+ throw new Error(`financial calls require a stable UUID in _meta["${OPERATION_META_KEY}"]`);
436
+ const budget = cfg.operations.budgets.find((b) => b.id === financial.budget);
437
+ if (args[financial.currencyField] !== budget.currency)
438
+ throw new Error(`operation currency must match budget ${budget.id}`);
439
+ const amount = args[financial.amountField];
440
+ if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount <= 0)
441
+ throw new Error("operation amount must be a positive safe integer in minor units");
442
+ 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" } } });
443
+ operation = reserved.operation;
444
+ createdOperation = reserved.created;
445
+ head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
446
+ }
447
+ catch (e) {
448
+ execution = { status: "withheld", reason: `operation not forwarded: ${e instanceof Error ? e.message : String(e)}`, provenance: "observed" };
449
+ }
450
+ }
451
+ /** The answer to a retry of an existing operation: the stored outcome, which the retry receipt below records as withheld. */
452
+ let cached;
453
+ if (!execution && operation && !createdOperation) {
454
+ // An existing reservation can mean another process is still forwarding, or died immediately afterwards.
455
+ // Never repeat the side effect. Reconciliation is the only path from an uncertain operation to closure.
456
+ // The retry gets a receipt of its own, so that the log shows the agent asked again and what it was told.
457
+ const settled = operation.reconciliation;
458
+ const result = settled?.bundle && settled.predicate && "result" in settled.predicate.execution ? settled.predicate.execution.result : operation.result;
459
+ const receipt = settled?.bundle ? settled.predicate.receiptId : operation.originalReceiptId;
460
+ 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 } : {}) } };
461
+ execution = { status: "withheld", reason: `existing operation: not forwarded again; the stored outcome is ${head.operation.status}`, provenance: "observed" };
462
+ }
463
+ if (!execution && (policy.decision === "allow" || financial && forward) && consequential(tool)) {
319
464
  // A consequential call is committed to the log before it goes out, so that evidence of the side effect exists
320
465
  // before the side effect does. If the log will not take the authorization, the call is not forwarded; in
321
466
  // observe mode nothing is withheld, and the missing authorization is printed instead.
@@ -323,13 +468,54 @@ export async function createGatewayHost(cfg, options = {}) {
323
468
  authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } }, captureCtx);
324
469
  }
325
470
  catch (e) {
326
- if (cfg.mode === "observe")
471
+ if (cfg.mode === "observe" && !financial)
327
472
  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)}`);
328
473
  else
329
474
  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" };
330
475
  }
476
+ if (authorization && operation) {
477
+ try {
478
+ operation = operations.saveAuthorization(operation.id, authorization);
479
+ }
480
+ catch (e) {
481
+ // Recovery closed this operation as "not forwarded" while the log held the authorization. Its closing receipt
482
+ // has this receipt id, so no second receipt is issued. The call is not forwarded.
483
+ 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) } };
484
+ }
485
+ }
486
+ }
487
+ let late = execution ? null : forward ? grantProblem() : null;
488
+ if (!execution && !late && forward && rule) {
489
+ // No awaits between this fresh check, the persistent atomic claim, and entering the upstream call. The
490
+ // claim is shared across sessions and processes, and a storage error withholds the side effect.
491
+ const at = new Date().toISOString();
492
+ const checked = checkApproval(at);
493
+ if (!checked.ok) {
494
+ execution = { status: "withheld", reason: `approval rejected before the call was forwarded: ${checked.error}`, provenance: "observed" };
495
+ }
496
+ else {
497
+ try {
498
+ consumeApproval(cfg.approvals.usedDir, checked.approval.approvalId, receiptId, at);
499
+ // A synchronous durable claim can block on storage. Recheck after it returns, because the grant or
500
+ // approval may have expired (or the grant been revoked) during that wait. A refusal keeps the claim.
501
+ const afterConsume = new Date().toISOString();
502
+ const finalCheck = checkApproval(afterConsume);
503
+ // Signature verification can be slow too. Read revocations after it, immediately before the cheap
504
+ // final window check, so a revocation made during that work still withholds this call.
505
+ late = grantProblem();
506
+ approval = { ...approval, consumedAt: afterConsume };
507
+ if (!finalCheck.ok)
508
+ execution = { status: "withheld", reason: `approval rejected before the call was forwarded: ${finalCheck.error}`, provenance: "observed" };
509
+ else
510
+ approvedWindow = { issuedAt: Date.parse(finalCheck.approval.issuedAt), expiresAt: Date.parse(finalCheck.approval.expiresAt) };
511
+ }
512
+ catch (e) {
513
+ const reason = `approval could not be consumed: ${String(e instanceof Error ? e.message : e)}`;
514
+ approval = { ...approval, status: "denied", reason };
515
+ execution = { status: "withheld", reason, provenance: "observed" };
516
+ }
517
+ }
331
518
  }
332
- const late = execution ? null : forward ? grantProblem() : null;
333
519
  if (execution) {
334
520
  // withheld: nothing was forwarded
335
521
  }
@@ -342,28 +528,57 @@ export async function createGatewayHost(cfg, options = {}) {
342
528
  // The upstream learns which receipt this call is, and who the grant says is calling. An upstream that keeps
343
529
  // state, such as the memory server, cites the receipt as the source of what it stores.
344
530
  const observed = Object.fromEntries(Object.entries(facts).map(([k, f]) => [k, f.value]));
345
- const result = await callUpstream(tool, args, { ...upstreamMeta, [OBSERVED_META_KEY]: observed });
346
- const evidence = upstreamEvidenceOf(result);
347
- forwarded = result;
348
- execution = { status: result.isError ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed", ...(evidence ? { upstream: evidence } : {}) };
349
- noteServedFacts(result);
531
+ // Signature checks and revocation-file I/O can themselves take time. Sample once more after all of them,
532
+ // using the authenticated window directly, so this last check does no crypto or storage before forwarding.
533
+ const forwardAt = new Date().toISOString();
534
+ const forwardMs = Date.parse(forwardAt);
535
+ if (approval)
536
+ approval = { ...approval, checkedAt: forwardAt, ...(approval.consumedAt ? { consumedAt: forwardAt } : {}) };
537
+ if (rule && (!approvedWindow || forwardMs < approvedWindow.issuedAt || forwardMs >= approvedWindow.expiresAt)) {
538
+ const reason = approvedWindow && forwardMs < approvedWindow.issuedAt ? "approval is not yet valid" : "approval has expired";
539
+ approval = { ...approval, status: "denied", reason, approverKeyids: [] };
540
+ execution = { status: "withheld", reason: `approval rejected before the call was forwarded: ${reason}`, provenance: "observed" };
541
+ }
542
+ else if (!delegationValidAt(delegation, forwardAt)) {
543
+ execution = { status: "withheld", reason: "the delegation grant is outside its validity window before the call was forwarded", provenance: "observed" };
544
+ }
545
+ else {
546
+ attemptedOperation = !!operation;
547
+ const result = await callUpstream(tool, args, { ...upstreamMeta, [OBSERVED_META_KEY]: observed, ...(operation ? { [OPERATION_META_KEY]: { id: operation.id, idempotencyKey: operation.idempotencyKey } } : {}) });
548
+ const evidence = upstreamEvidenceOf(result);
549
+ forwarded = result;
550
+ execution = { status: result.isError ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed", ...(evidence ? { upstream: evidence } : {}) };
551
+ noteServedFacts(result);
552
+ if (operation)
553
+ operation = operations.update(operation.id, { status: outcome(operation, result), result });
554
+ }
350
555
  }
351
556
  catch (e) {
352
557
  execution = { status: "error", error: String(e instanceof Error ? e.message : e), provenance: "observed" };
558
+ if (operation)
559
+ operation = operations.update(operation.id, { status: "unknown" });
353
560
  }
354
561
  }
355
562
  else {
356
563
  execution = { status: "denied", reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched", provenance: "observed" };
357
564
  }
358
- await issuer.issue({
565
+ // Only a call known never to have been forwarded may release a reservation without a provider record.
566
+ if (operation && createdOperation && !attemptedOperation)
567
+ operation = operations.update(operation.id, { status: "failed", unsent: undefined });
568
+ if (operation)
569
+ head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
570
+ const issued = await issuer.issue({
359
571
  ...head,
572
+ ...(approval ? { approval } : {}),
360
573
  session: { id: null, toolUseId: null, provenance: "claimed" },
361
574
  model: { id: typeof modelClaim === "string" ? modelClaim : null, provenance: "claimed" },
362
575
  policy: { ...policy, provenance: "observed" },
363
576
  ...(authorization ? { authorization } : {}),
364
577
  execution,
365
578
  }, captureCtx);
366
- const meta = { [RECEIPT_META_KEY]: receiptId };
579
+ if (operation && createdOperation && attemptedOperation)
580
+ operations.update(operation.id, { original: issued });
581
+ const meta = { [RECEIPT_META_KEY]: receiptId, ...(head.operation ? { [OPERATION_META_KEY]: head.operation } : {}) };
367
582
  const refuse = (text) => ({ isError: true, content: [{ type: "text", text: `${text} (receipt ${receiptId})` }], _meta: meta });
368
583
  switch (execution.status) {
369
584
  // the agent gets the real result, the real reason, and the real error: what is withheld is withheld from the receipt
@@ -372,6 +587,8 @@ export async function createGatewayHost(cfg, options = {}) {
372
587
  case "error":
373
588
  return refuse(`Upstream error: ${execution.error}`);
374
589
  case "withheld":
590
+ if (cached)
591
+ return { ...cached, _meta: { ...cached._meta, [OPERATION_META_KEY]: head.operation, [RETRY_RECEIPT_META_KEY]: receiptId } };
375
592
  return refuse(`Not executed: ${execution.reason}`);
376
593
  default: {
377
594
  const result = forwarded ?? execution.result;
@@ -397,13 +614,86 @@ export async function createGatewayHost(cfg, options = {}) {
397
614
  keyid: issuer.keyid,
398
615
  open,
399
616
  revoke,
617
+ tools: () => advertised.map((t) => t.name),
400
618
  revoked: () => {
401
619
  reloadRevoked();
402
620
  return [...revokedSet];
403
621
  },
622
+ async reconcile(operationId) {
623
+ if (!operations)
624
+ throw new Error("gateway has no financial operations configured");
625
+ const op = operations.get(operationId);
626
+ if (!op)
627
+ throw new Error("operation not found");
628
+ if (op.issuerKeyid !== issuer.keyid || op.providerDigest !== providerDigest(op.tool))
629
+ throw new Error("operation provider or gateway identity changed; use the original configuration");
630
+ let intent = op.reconciliation;
631
+ if (intent?.bundle)
632
+ return intent.bundle;
633
+ if (!intent) {
634
+ if (op.status === "failed")
635
+ throw new Error("operation was never forwarded and needs no provider reconciliation");
636
+ // SQLite is shared on this machine. A live creator may still be about to send, or awaiting its response;
637
+ // reconciliation cannot release its budget underneath that forward. A process with the same PID but another
638
+ // start time is not the creator. A start time that cannot be read fails closed.
639
+ if (op.status === "submitted" && ownerAlive(op))
640
+ throw new Error("operation is still submitted by a live process; wait for its outcome before reconciling");
641
+ const original = op.original;
642
+ if (!original) {
643
+ // The authorization is saved before the forward. A dead creator and no authorization prove that the call was
644
+ // never sent. Close it with a receipt that says so, then release the reservation.
645
+ const unsent = op.unsent;
646
+ if (!unsent)
647
+ throw new Error("operation has no committed authorization and no record of the call; it was not forwarded");
648
+ const predicate = {
649
+ ...unsent, receiptId: op.originalReceiptId, timestamp: new Date().toISOString(),
650
+ session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
651
+ operation: operationEvidence(op, "failed"),
652
+ execution: { status: "withheld", reason: "the gateway stopped before it forwarded the call; the call was not forwarded", provenance: "observed" },
653
+ };
654
+ intent = operations.claimReconciliation(op.id, { predicate }, true);
655
+ }
656
+ }
657
+ if (!intent) {
658
+ const original = op.original;
659
+ const checked = dsseVerify(original.envelope, [gatewayKey]);
660
+ if (!checked.ok)
661
+ throw new Error("stored original operation signature is invalid");
662
+ const initial = checked.payload.predicate;
663
+ const lookup = lookupFor(op);
664
+ const result = await callUpstream(lookup.tool, lookup.args);
665
+ const identity = providerField(result, lookup.identityPath);
666
+ if (identity !== op.idempotencyKey)
667
+ throw new Error("provider record does not bind this operation's idempotency key; the reservation is retained");
668
+ const value = providerField(result, lookup.statusPath);
669
+ const status = typeof value === "string" && !result.isError ? lookup.confirmed.includes(value) ? "confirmed" : lookup.failed.includes(value) ? "failed" : null : null;
670
+ if (!status)
671
+ throw new Error("provider outcome remains pending or unknown; the reservation is retained");
672
+ const predicate = {
673
+ receiptId: randomUUID(), timestamp: new Date().toISOString(),
674
+ issuer: { kind: "gateway", keyid: issuer.keyid, version: GATEWAY_VERSION },
675
+ principal: initial.principal, agent: initial.agent, delegation: initial.delegation,
676
+ session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
677
+ tool: initial.tool, request: { args: lookup.args, argsDigest: digestOf(lookup.args), provenance: "claimed" },
678
+ facts: {}, policy: { decision: "allow", reasons: ["reconciliation: the gateway read the provider record and evaluated no policy"], errors: [], policyDigest: pDigest, provenance: "observed" },
679
+ operation: operationEvidence(op, status), reconciliation: { original, lookup },
680
+ execution: { status: "executed", result, resultDigest: digestOf(result), provenance: "observed" },
681
+ };
682
+ intent = operations.claimReconciliation(op.id, { predicate });
683
+ }
684
+ // Commit the receipt before releasing a failed reservation. A crash before this update retains the amount;
685
+ // the persisted intent allows another operator/process to finish precisely the same resolution.
686
+ // A receipt for an unsent call holds the call's own values, so the issuer applies the capture rule of its tool.
687
+ const ctx = intent.predicate.reconciliation ? undefined : { unknownTool: !owner.has(intent.predicate.tool.name) };
688
+ const bundle = intent.bundle ?? await issuer.issue(intent.predicate, ctx, (prepared) => operations.prepareReconciliation(op.id, prepared));
689
+ const retained = operations.get(op.id).reconciliation;
690
+ operations.update(op.id, { status: intent.predicate.operation.status, reconciliation: { ...retained, bundle }, result: intent.predicate.execution.result, unsent: undefined });
691
+ return bundle;
692
+ },
404
693
  async close() {
405
694
  for (const c of upstreams.values())
406
695
  await c.close();
696
+ operations?.close();
407
697
  },
408
698
  };
409
699
  }
package/dist/index.d.ts CHANGED
@@ -4,11 +4,15 @@ export type { GatewayOptions } from "./gateway.ts";
4
4
  export { buildRequest, restUpstream } from "./rest.ts";
5
5
  export { openExporter, otlpExporter, spanFor } from "./otel.ts";
6
6
  export { hecEvent, splunkExporter } from "./splunk.ts";
7
+ export { serveConsole, type ConsoleOptions, type RunningConsole } from "./console.ts";
8
+ export { checkConfig, formatFindings, type CheckFinding, type CheckOptions } from "./check.ts";
7
9
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
8
10
  export * from "./capture.ts";
9
11
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
10
- export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
11
- export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
12
+ export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.ts";
13
+ export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, SsoSetting, StripeOptions } from "./portal.ts";
14
+ export { oidcAuthorizeUrl, oidcExchange, pkce, samlAuthorizeUrl, samlValidate } from "./sso.ts";
15
+ export type { OidcConfig, SamlConfig, SsoIdentity } from "./sso.ts";
12
16
  export type { HttpGatewayOptions, RunningHttpGateway } from "./gateway-http.ts";
13
17
  export type { A2aServerOptions, AgentCard, ResolvedCard, RunningA2aServer } from "./a2a.ts";
14
18
  export { exportLog, formatExport } from "./log-export.ts";
@@ -33,8 +37,10 @@ export type { SplunkConfig, SplunkOptions } from "./splunk.ts";
33
37
  export type { IssuerOptions } from "./issue.ts";
34
38
  export type { RestOptions, UpstreamClient } from "./rest.ts";
35
39
  export * from "./config.ts";
40
+ export * from "./operations.ts";
36
41
  export * from "./crypto.ts";
37
42
  export * from "./delegation.ts";
43
+ export * from "./approval.ts";
38
44
  export * from "./gateway.ts";
39
45
  export * from "./issue.ts";
40
46
  export * from "./log.ts";
@@ -46,3 +52,4 @@ export * from "./sdk/index.ts";
46
52
  export * from "./sidecar.ts";
47
53
  export * from "./upstream.ts";
48
54
  export * from "./retention.ts";
55
+ export * from "./simulate.ts";
package/dist/index.js CHANGED
@@ -3,10 +3,13 @@ export { AUTHORIZATION_PREDICATE_TYPE, buildAuthorizationStatement } from "./rec
3
3
  export { buildRequest, restUpstream } from "./rest.js";
4
4
  export { openExporter, otlpExporter, spanFor } from "./otel.js";
5
5
  export { hecEvent, splunkExporter } from "./splunk.js";
6
+ export { serveConsole } from "./console.js";
7
+ export { checkConfig, formatFindings } from "./check.js";
6
8
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
7
9
  export * from "./capture.js";
8
10
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
9
- export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.js";
11
+ export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.js";
12
+ export { oidcAuthorizeUrl, oidcExchange, pkce, samlAuthorizeUrl, samlValidate } from "./sso.js";
10
13
  export { exportLog, formatExport } from "./log-export.js";
11
14
  export { fileBackend, importLogFile, PostgresLog, PostgresTenancy, RateLimiter } from "./log-store.js";
12
15
  export { PLAN_QUOTAS, PLANS } from "./log-store.js";
@@ -16,8 +19,10 @@ export { adminRoutes, welcomeSheet } from "./log-admin.js";
16
19
  export { fetchWitnessKeys, Witness } from "./witness.js";
17
20
  export { checkLog, formatLogCheck } from "./log-check.js";
18
21
  export * from "./config.js";
22
+ export * from "./operations.js";
19
23
  export * from "./crypto.js";
20
24
  export * from "./delegation.js";
25
+ export * from "./approval.js";
21
26
  export * from "./gateway.js";
22
27
  export * from "./issue.js";
23
28
  export * from "./log.js";
@@ -29,3 +34,4 @@ export * from "./sdk/index.js";
29
34
  export * from "./sidecar.js";
30
35
  export * from "./upstream.js";
31
36
  export * from "./retention.js";
37
+ export * from "./simulate.js";
package/dist/issue.d.ts CHANGED
@@ -1,8 +1,13 @@
1
- import { type CaptureConfig, type CaptureContext } from "./capture.ts";
2
- import { type KeyPair } from "./crypto.ts";
1
+ import { type CaptureConfig, type CaptureContext, type PrivateView } from "./capture.ts";
2
+ import { type Envelope, type KeyPair } from "./crypto.ts";
3
3
  import { type LogSink } from "./log-sink.ts";
4
4
  import type { ReceiptExporter } from "./otel.ts";
5
5
  import { type AuthorizationBundle, type AuthorizationPredicate, type ReceiptBundle, type ReceiptPredicate } from "./receipt.ts";
6
+ /** Private recovery data: includes commitment salts. Persist only in an owner-only store, never in a receipt or export. */
7
+ export interface PreparedReceipt {
8
+ envelope: Envelope;
9
+ view: PrivateView<ReceiptPredicate>;
10
+ }
6
11
  export interface Issuer {
7
12
  keyid: string;
8
13
  log: LogSink;
@@ -11,7 +16,7 @@ export interface Issuer {
11
16
  * bundle. Rejects if the log refuses the leaf; no bundle is written then. The predicate is the call in full; what
12
17
  * is signed, written, and exported is the view.
13
18
  */
14
- issue(predicate: ReceiptPredicate, ctx?: CaptureContext): Promise<ReceiptBundle>;
19
+ issue(predicate: ReceiptPredicate, ctx?: CaptureContext, retainPrepared?: (prepared: PreparedReceipt) => PreparedReceipt): Promise<ReceiptBundle>;
15
20
  /** The same for an authorization, signed and committed before a consequential call is forwarded. Rejects if the log refuses; the caller must then not forward. */
16
21
  authorize(predicate: AuthorizationPredicate, ctx?: CaptureContext): Promise<AuthorizationBundle>;
17
22
  }