@agent-custody/receipts 0.7.0 → 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.
- package/README.md +16 -10
- package/dist/approval.d.ts +74 -0
- package/dist/approval.js +196 -0
- package/dist/capture.js +49 -1
- package/dist/cli.js +124 -3
- package/dist/config.d.ts +85 -0
- package/dist/config.js +72 -2
- package/dist/gateway.d.ts +5 -0
- package/dist/gateway.js +285 -17
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/issue.d.ts +8 -3
- package/dist/issue.js +13 -4
- package/dist/operations.d.ts +101 -0
- package/dist/operations.js +239 -0
- package/dist/otel.js +12 -5
- package/dist/receipt.d.ts +36 -1
- package/dist/rest.js +14 -1
- package/dist/simulate.d.ts +58 -0
- package/dist/simulate.js +204 -0
- package/dist/splunk.js +11 -4
- package/dist/verify.d.ts +2 -0
- package/dist/verify.js +237 -5
- package/docs/approvals.md +107 -0
- package/docs/financial-operations.md +99 -0
- package/docs/policies.md +22 -0
- package/docs/tutorials.md +5 -0
- package/docs/usage.md +28 -2
- package/docs/verification.md +26 -8
- package/package.json +1 -1
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +2653 -457
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
|
|
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
|
|
@@ -146,7 +159,10 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
146
159
|
for (const { name, cfg: u } of upstreamConfigs) {
|
|
147
160
|
let client;
|
|
148
161
|
if ("rest" in u) {
|
|
149
|
-
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
|
+
}) });
|
|
150
166
|
}
|
|
151
167
|
else if ("a2a" in u) {
|
|
152
168
|
client = a2aUpstream(name, u.a2a);
|
|
@@ -175,6 +191,40 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
175
191
|
advertised.push(t);
|
|
176
192
|
}
|
|
177
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
|
+
};
|
|
178
228
|
const callUpstream = async (name, args, meta) => {
|
|
179
229
|
const via = owner.get(name);
|
|
180
230
|
if (!via)
|
|
@@ -249,7 +299,19 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
249
299
|
};
|
|
250
300
|
async function handleCall(params) {
|
|
251
301
|
const tool = params.name;
|
|
252
|
-
|
|
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
|
+
}
|
|
253
315
|
const receiptId = randomUUID();
|
|
254
316
|
const timestamp = new Date().toISOString();
|
|
255
317
|
const modelClaim = params._meta?.[MODEL_META_KEY];
|
|
@@ -264,6 +326,31 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
264
326
|
/** what the upstream answered, in full: the agent gets this; the receipt gets the captured view */
|
|
265
327
|
let forwarded;
|
|
266
328
|
let authorization;
|
|
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;
|
|
267
354
|
// The grant is enforced in every mode: a call outside its scopes, or after it expired or was revoked, is denied
|
|
268
355
|
// and never forwarded, observe mode or not. Observe mode suspends the Cedar policy, nothing else.
|
|
269
356
|
const problem = grantProblem(timestamp);
|
|
@@ -274,6 +361,9 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
274
361
|
else if (!inScope) {
|
|
275
362
|
policy = { decision: "deny", reasons: [], errors: [`tool "${tool}" is not in the delegation scopes`], policyDigest: pDigest };
|
|
276
363
|
}
|
|
364
|
+
else if (approvalProblem) {
|
|
365
|
+
policy = { decision: "deny", reasons: [], errors: [`approval rejected: ${approvalProblem}`], policyDigest: pDigest };
|
|
366
|
+
}
|
|
277
367
|
else {
|
|
278
368
|
try {
|
|
279
369
|
({ facts, templates: factTemplates, results: factResults } = await gatherFacts(tool, args, upstreamMeta));
|
|
@@ -290,7 +380,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
290
380
|
}
|
|
291
381
|
// Observe mode: the decision is recorded, never enforced. The receipt says so on every call, so a verifier can
|
|
292
382
|
// tell a policy that was being tested from one that was in force.
|
|
293
|
-
if (cfg.mode === "observe" && !problem && inScope)
|
|
383
|
+
if (cfg.mode === "observe" && !problem && inScope && !approvalProblem)
|
|
294
384
|
policy = { ...policy, enforced: false };
|
|
295
385
|
const forward = policy.decision === "allow" || policy.enforced === false;
|
|
296
386
|
// Private evidence is applied by the issuer to the whole statement. What it cannot know by itself: a fact's lookup
|
|
@@ -314,8 +404,42 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
314
404
|
request: { args, argsDigest: digestOf(args), provenance: "claimed" },
|
|
315
405
|
facts,
|
|
316
406
|
consumed: { factIds: consumedNow, provenance: "observed" },
|
|
407
|
+
...(approval ? { approval } : {}),
|
|
408
|
+
operation: undefined,
|
|
317
409
|
};
|
|
318
|
-
|
|
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)) {
|
|
319
443
|
// A consequential call is committed to the log before it goes out, so that evidence of the side effect exists
|
|
320
444
|
// before the side effect does. If the log will not take the authorization, the call is not forwarded; in
|
|
321
445
|
// observe mode nothing is withheld, and the missing authorization is printed instead.
|
|
@@ -323,13 +447,54 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
323
447
|
authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } }, captureCtx);
|
|
324
448
|
}
|
|
325
449
|
catch (e) {
|
|
326
|
-
if (cfg.mode === "observe")
|
|
450
|
+
if (cfg.mode === "observe" && !financial)
|
|
327
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)}`);
|
|
328
452
|
else
|
|
329
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" };
|
|
330
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
|
+
}
|
|
331
497
|
}
|
|
332
|
-
const late = execution ? null : forward ? grantProblem() : null;
|
|
333
498
|
if (execution) {
|
|
334
499
|
// withheld: nothing was forwarded
|
|
335
500
|
}
|
|
@@ -342,28 +507,57 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
342
507
|
// The upstream learns which receipt this call is, and who the grant says is calling. An upstream that keeps
|
|
343
508
|
// state, such as the memory server, cites the receipt as the source of what it stores.
|
|
344
509
|
const observed = Object.fromEntries(Object.entries(facts).map(([k, f]) => [k, f.value]));
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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
|
+
}
|
|
350
534
|
}
|
|
351
535
|
catch (e) {
|
|
352
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" });
|
|
353
539
|
}
|
|
354
540
|
}
|
|
355
541
|
else {
|
|
356
542
|
execution = { status: "denied", reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched", provenance: "observed" };
|
|
357
543
|
}
|
|
358
|
-
|
|
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({
|
|
359
550
|
...head,
|
|
551
|
+
...(approval ? { approval } : {}),
|
|
360
552
|
session: { id: null, toolUseId: null, provenance: "claimed" },
|
|
361
553
|
model: { id: typeof modelClaim === "string" ? modelClaim : null, provenance: "claimed" },
|
|
362
554
|
policy: { ...policy, provenance: "observed" },
|
|
363
555
|
...(authorization ? { authorization } : {}),
|
|
364
556
|
execution,
|
|
365
557
|
}, captureCtx);
|
|
366
|
-
|
|
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 } : {}) };
|
|
367
561
|
const refuse = (text) => ({ isError: true, content: [{ type: "text", text: `${text} (receipt ${receiptId})` }], _meta: meta });
|
|
368
562
|
switch (execution.status) {
|
|
369
563
|
// the agent gets the real result, the real reason, and the real error: what is withheld is withheld from the receipt
|
|
@@ -372,6 +566,8 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
372
566
|
case "error":
|
|
373
567
|
return refuse(`Upstream error: ${execution.error}`);
|
|
374
568
|
case "withheld":
|
|
569
|
+
if (cached)
|
|
570
|
+
return { ...cached, _meta: { ...cached._meta, [OPERATION_META_KEY]: head.operation, [RETRY_RECEIPT_META_KEY]: receiptId } };
|
|
375
571
|
return refuse(`Not executed: ${execution.reason}`);
|
|
376
572
|
default: {
|
|
377
573
|
const result = forwarded ?? execution.result;
|
|
@@ -401,9 +597,81 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
401
597
|
reloadRevoked();
|
|
402
598
|
return [...revokedSet];
|
|
403
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
|
+
},
|
|
404
671
|
async close() {
|
|
405
672
|
for (const c of upstreams.values())
|
|
406
673
|
await c.close();
|
|
674
|
+
operations?.close();
|
|
407
675
|
},
|
|
408
676
|
};
|
|
409
677
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -33,8 +33,10 @@ export type { SplunkConfig, SplunkOptions } from "./splunk.ts";
|
|
|
33
33
|
export type { IssuerOptions } from "./issue.ts";
|
|
34
34
|
export type { RestOptions, UpstreamClient } from "./rest.ts";
|
|
35
35
|
export * from "./config.ts";
|
|
36
|
+
export * from "./operations.ts";
|
|
36
37
|
export * from "./crypto.ts";
|
|
37
38
|
export * from "./delegation.ts";
|
|
39
|
+
export * from "./approval.ts";
|
|
38
40
|
export * from "./gateway.ts";
|
|
39
41
|
export * from "./issue.ts";
|
|
40
42
|
export * from "./log.ts";
|
|
@@ -46,3 +48,4 @@ export * from "./sdk/index.ts";
|
|
|
46
48
|
export * from "./sidecar.ts";
|
|
47
49
|
export * from "./upstream.ts";
|
|
48
50
|
export * from "./retention.ts";
|
|
51
|
+
export * from "./simulate.ts";
|
package/dist/index.js
CHANGED
|
@@ -16,8 +16,10 @@ export { adminRoutes, welcomeSheet } from "./log-admin.js";
|
|
|
16
16
|
export { fetchWitnessKeys, Witness } from "./witness.js";
|
|
17
17
|
export { checkLog, formatLogCheck } from "./log-check.js";
|
|
18
18
|
export * from "./config.js";
|
|
19
|
+
export * from "./operations.js";
|
|
19
20
|
export * from "./crypto.js";
|
|
20
21
|
export * from "./delegation.js";
|
|
22
|
+
export * from "./approval.js";
|
|
21
23
|
export * from "./gateway.js";
|
|
22
24
|
export * from "./issue.js";
|
|
23
25
|
export * from "./log.js";
|
|
@@ -29,3 +31,4 @@ export * from "./sdk/index.js";
|
|
|
29
31
|
export * from "./sidecar.js";
|
|
30
32
|
export * from "./upstream.js";
|
|
31
33
|
export * from "./retention.js";
|
|
34
|
+
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
|
}
|
package/dist/issue.js
CHANGED
|
@@ -3,7 +3,7 @@ import { chmodSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { SALTS_DIR, saltsFileFor } from "./retention.js";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { effectiveRule, getAt, privateView } from "./capture.js";
|
|
6
|
-
import { canonicalize, dsseSign } from "./crypto.js";
|
|
6
|
+
import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
|
|
7
7
|
import { fileLog } from "./log-sink.js";
|
|
8
8
|
import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
|
|
9
9
|
/** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
|
|
@@ -47,13 +47,22 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
47
47
|
return {
|
|
48
48
|
keyid: key.keyid,
|
|
49
49
|
log: sink,
|
|
50
|
-
async issue(predicate, ctx) {
|
|
50
|
+
async issue(predicate, ctx, retainPrepared) {
|
|
51
51
|
ensureSaltsDir();
|
|
52
52
|
// the authorization's view stays until the log has taken the receipt: a producer that retries after a refusal gets the same commitments and salts
|
|
53
53
|
const prior = committed.get(predicate.receiptId)?.view;
|
|
54
|
-
const
|
|
54
|
+
const candidate = view(predicate, ctx, prior);
|
|
55
|
+
// A durable producer may retain the first signed view, salts included, before any append. Concurrent and
|
|
56
|
+
// restarted issuers then commit exactly those bytes rather than re-salting the same logical receipt.
|
|
57
|
+
const prepared = retainPrepared ? retainPrepared({ envelope: dsseSign(RECEIPT_TYPE, buildStatement(candidate.predicate), key), view: candidate }) : { envelope: dsseSign(RECEIPT_TYPE, buildStatement(candidate.predicate), key), view: candidate };
|
|
58
|
+
const pv = prepared.view;
|
|
55
59
|
const v = pv.predicate;
|
|
56
|
-
const envelope =
|
|
60
|
+
const envelope = prepared.envelope;
|
|
61
|
+
if (retainPrepared) {
|
|
62
|
+
const checked = dsseVerify(envelope, [key]);
|
|
63
|
+
if (!checked.ok || envelope.payloadType !== RECEIPT_TYPE || v.receiptId !== predicate.receiptId || canonicalize(checked.payload) !== canonicalize(buildStatement(v)))
|
|
64
|
+
throw new Error("prepared receipt does not match this issuer, predicate, or receipt id");
|
|
65
|
+
}
|
|
57
66
|
const entry = await sink.append(canonicalize(envelope));
|
|
58
67
|
committed.delete(predicate.receiptId);
|
|
59
68
|
// the salts once the log has taken the leaf: a receipt the log refused leaves nothing behind
|