@agent-custody/receipts 0.9.0 → 0.11.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 +22 -10
- package/dist/anchor-evm.d.ts +19 -0
- package/dist/anchor-evm.js +49 -0
- package/dist/anchor.d.ts +167 -0
- package/dist/anchor.js +367 -0
- package/dist/check.js +9 -3
- package/dist/cli.js +73 -7
- package/dist/config.d.ts +10 -0
- package/dist/config.js +25 -0
- package/dist/console-page.js +3 -3
- package/dist/console.js +2 -1
- package/dist/gateway-http.js +1 -1
- package/dist/gateway.d.ts +15 -1
- package/dist/gateway.js +161 -23
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/issue.d.ts +31 -1
- package/dist/issue.js +261 -10
- package/dist/log-check.d.ts +15 -0
- package/dist/log-check.js +52 -0
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +5 -0
- package/dist/portal.js +1 -0
- package/dist/receipt.d.ts +2 -0
- package/dist/simulate.d.ts +7 -1
- package/dist/simulate.js +27 -2
- package/dist/verify.d.ts +2 -0
- package/dist/verify.js +11 -3
- package/docs/anchoring.md +115 -0
- package/docs/codex-recovery.md +1 -1
- package/docs/configuration.md +7 -1
- package/docs/console.md +2 -3
- package/docs/policies.md +3 -1
- package/docs/threat-model.md +16 -2
- package/docs/tutorials.md +3 -0
- package/docs/usage.md +36 -3
- package/docs/verification.md +4 -2
- package/package.json +7 -2
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +1176 -967
package/dist/console-page.js
CHANGED
|
@@ -172,7 +172,7 @@ const SCRIPT = String.raw `
|
|
|
172
172
|
var r = s.report;
|
|
173
173
|
out.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Replay of recorded calls' }),
|
|
174
174
|
h('p', { class: 'muted', text: 'A replay re-decides calls that already happened. A limit that no recorded call reached, and an argument value that was never sent, are not covered, so a change that widens what is allowed can show no change here.' }),
|
|
175
|
-
h('p', { text: s.replayed + ' verified receipts replayed (' + s.unverified + ' skipped because they did not verify). ' + r.evaluated + ' evaluated, ' + r.unchanged + ' unchanged, ' + r.changeCount + ' would change.' + (r.complete ? '' : ' The replay is incomplete: ' + r.skipped.length + ' calls could not be replayed.') }),
|
|
175
|
+
h('p', { text: s.replayed + ' verified receipts replayed (' + s.unverified + ' skipped because they did not verify). ' + r.evaluated + ' evaluated, ' + r.unchanged + ' unchanged, ' + r.reconciliations + ' reconciliations (provider reads with no policy decision), ' + r.changeCount + ' would change.' + (r.complete ? '' : ' The replay is incomplete: ' + r.skipped.length + ' calls could not be replayed.') }),
|
|
176
176
|
r.changes.length ? (function () {
|
|
177
177
|
var t = h('table', null, h('tr', null, h('th', { text: 'receipt' }), h('th', { text: 'tool' }), h('th', { text: 'was' }), h('th', { text: 'would be' })));
|
|
178
178
|
r.changes.forEach(function (c) { t.appendChild(h('tr', null, h('td', { text: short(c.receiptId) }), h('td', { text: c.tool }), h('td', { text: c.from }), h('td', { class: c.to === 'deny' ? 'bad' : 'warn', text: c.to }))); });
|
|
@@ -184,7 +184,7 @@ const SCRIPT = String.raw `
|
|
|
184
184
|
function save() {
|
|
185
185
|
return validate().then(function (v) {
|
|
186
186
|
if (!v.ok) return;
|
|
187
|
-
var ask = 'Save this policy?\n\
|
|
187
|
+
var ask = 'Save this policy?\n\nA running gateway applies it from its next call.';
|
|
188
188
|
if (v.issues.length) ask = 'Confirm before saving:\n\n' + v.issues.join('\n\n') + '\n\nSave this policy anyway?';
|
|
189
189
|
if (!window.confirm(ask)) return;
|
|
190
190
|
return api('PUT', '/api/policy', { text: area.value, expectDigest: policyDigest, confirm: v.issues.length > 0 }).then(function (r) {
|
|
@@ -194,7 +194,7 @@ const SCRIPT = String.raw `
|
|
|
194
194
|
});
|
|
195
195
|
}
|
|
196
196
|
return h('div', null, h('h2', { text: 'Policy' }),
|
|
197
|
-
h('div', { class: 'banner' }, '
|
|
197
|
+
h('div', { class: 'banner' }, 'A running gateway applies a saved change from its next call; every save is recorded in the audit trail, and the previous version is kept.'),
|
|
198
198
|
h('p', { class: 'muted' }, p.path + ' · ' + short(p.digest)),
|
|
199
199
|
area, h('div', { class: 'row' },
|
|
200
200
|
h('button', { class: 'secondary', onclick: function () { validate().catch(fail); } }, 'Validate'),
|
package/dist/console.js
CHANGED
|
@@ -326,6 +326,7 @@ export async function serveConsole(options) {
|
|
|
326
326
|
total: report.total,
|
|
327
327
|
evaluated: report.evaluated,
|
|
328
328
|
unchanged: report.unchanged,
|
|
329
|
+
reconciliations: report.reconciliations,
|
|
329
330
|
complete: report.complete,
|
|
330
331
|
changes: report.changes.slice(0, 200).map((c) => ({ receiptId: c.receiptId, tool: c.tool, from: c.previous.decision, to: c.proposed.decision })),
|
|
331
332
|
changeCount: report.changes.length,
|
|
@@ -357,7 +358,7 @@ export async function serveConsole(options) {
|
|
|
357
358
|
throw new HttpError(500, `the policy file cannot be written (${e instanceof Error ? e.message : String(e)}); mount the config directory read-write for the console`);
|
|
358
359
|
}
|
|
359
360
|
audit("policy.save", { file: cfg.policyFile, from: policyDigest(current), to: policyDigest(text), bytes: text.length, confirmed: issues }, by);
|
|
360
|
-
return { digest: policyDigest(text), note: "saved;
|
|
361
|
+
return { digest: policyDigest(text), note: "saved; a running gateway applies it from its next call" };
|
|
361
362
|
});
|
|
362
363
|
},
|
|
363
364
|
"POST /api/grants/inspect": async (req) => {
|
package/dist/gateway-http.js
CHANGED
|
@@ -89,7 +89,7 @@ export async function serveHttp(host, opts) {
|
|
|
89
89
|
const handler = async (req, res) => {
|
|
90
90
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
91
91
|
if (req.method === "GET" && url.pathname === "/health")
|
|
92
|
-
return json(res, 200, { ok: true, sessions: sessions.size, keyid: host.keyid });
|
|
92
|
+
return json(res, 200, { ok: true, sessions: sessions.size, keyid: host.keyid, pendingReceipts: host.pendingReceipts() });
|
|
93
93
|
if (url.pathname !== path)
|
|
94
94
|
return json(res, 404, { error: "not found" });
|
|
95
95
|
try {
|
package/dist/gateway.d.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { type CallToolResult, type Tool } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type GatewayConfig } from "./config.ts";
|
|
3
3
|
import { type Envelope } from "./crypto.ts";
|
|
4
4
|
import { type Delegation } from "./delegation.ts";
|
|
5
|
+
import { type FlushResult } from "./issue.ts";
|
|
5
6
|
import { type LogSink } from "./log-sink.ts";
|
|
6
7
|
import { type ReceiptExporter } from "./otel.ts";
|
|
7
8
|
import type { ReceiptBundle } from "./receipt.ts";
|
|
8
9
|
export declare const GATEWAY_VERSION = "0.1.0";
|
|
9
10
|
export declare const RECEIPT_META_KEY = "agent-custody/receipt";
|
|
10
11
|
export declare const MODEL_META_KEY = "agent-custody/model";
|
|
12
|
+
/** true on a result whose receipt is signed and kept in the outbox, and not yet in the log */
|
|
13
|
+
export declare const LOG_PENDING_META_KEY = "agent-custody/log-pending";
|
|
11
14
|
/** 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. */
|
|
12
15
|
export declare const RETRY_RECEIPT_META_KEY = "agent-custody/retry-receipt";
|
|
13
16
|
/** Set by the gateway on the call it forwards upstream: the receipt id, and the agent and principal from the attested grant. */
|
|
@@ -46,6 +49,11 @@ export interface GatewayOptions {
|
|
|
46
49
|
exporter?: ReceiptExporter;
|
|
47
50
|
/** cancels the start while it is connecting to the upstreams: every upstream already started is closed and the call rejects */
|
|
48
51
|
signal?: AbortSignal;
|
|
52
|
+
/**
|
|
53
|
+
* Appends the outbox at start and every 30 seconds. Only a gateway that serves sets it: `check` and `reconcile` open
|
|
54
|
+
* a host too, and must not append to the log or touch the outbox of a gateway that runs.
|
|
55
|
+
*/
|
|
56
|
+
autoFlush?: boolean;
|
|
49
57
|
}
|
|
50
58
|
/**
|
|
51
59
|
* The shared part of a gateway: the key, the policy, the issuer, the log, the upstreams, and the fact lookups. One host
|
|
@@ -59,10 +67,16 @@ export interface GatewayHost {
|
|
|
59
67
|
revoke(grantDigest: string): void;
|
|
60
68
|
/** the digests revoked so far */
|
|
61
69
|
revoked(): string[];
|
|
70
|
+
/** sha256 of the policy in force: the one the next call is evaluated under */
|
|
71
|
+
policyDigest(): string;
|
|
62
72
|
/** the names of every tool the upstreams offer, before any grant narrows them */
|
|
63
73
|
tools(): string[];
|
|
64
74
|
/** Operator-only provider lookup. Never exposed as an agent tool. Unknown/pending reservations remain held until a terminal reconciliation receipt is committed. */
|
|
65
75
|
reconcile(operationId: string): Promise<ReceiptBundle>;
|
|
76
|
+
/** Appends the receipts in the outbox, whose log append failed. A host opened with `autoFlush` also runs it at start and every 30 seconds; `close()` waits for a flush that runs. */
|
|
77
|
+
flushOutbox(): Promise<FlushResult>;
|
|
78
|
+
/** the receipts in the outbox */
|
|
79
|
+
pendingReceipts(): number;
|
|
66
80
|
/** closes the upstreams; every session opened from this host is finished with */
|
|
67
81
|
close(): Promise<void>;
|
|
68
82
|
}
|
package/dist/gateway.js
CHANGED
|
@@ -1,28 +1,32 @@
|
|
|
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 { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
5
6
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
6
7
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
7
8
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
8
9
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
9
10
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
10
11
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
12
|
+
import { strictRefusals } from "./config.js";
|
|
11
13
|
import { digestOf, dsseVerifiers, dsseVerify, loadPrivateKey, loadPublicKey } from "./crypto.js";
|
|
12
14
|
import { delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
|
|
13
15
|
import { APPROVAL_META_KEY, DEFAULT_APPROVAL_LIFETIME_SECONDS, consumeApproval, verifyApproval, verifyApprovalStatement } from "./approval.js";
|
|
14
|
-
import { createIssuer } from "./issue.js";
|
|
16
|
+
import { createIssuer, ReceiptPending } from "./issue.js";
|
|
15
17
|
import { openLog } from "./log-sink.js";
|
|
16
18
|
import { openExporter } from "./otel.js";
|
|
17
19
|
import { upstreamEvidenceOf } from "./upstream.js";
|
|
18
20
|
import { restUpstream } from "./rest.js";
|
|
19
21
|
import { a2aUpstream } from "./a2a.js";
|
|
20
22
|
import { captureKeyFrom, effectiveRule } from "./capture.js";
|
|
21
|
-
import { evaluate, policyDigest } from "./policy.js";
|
|
23
|
+
import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
|
|
22
24
|
import { OPERATION_META_KEY, OperationStore, ownerAlive } from "./operations.js";
|
|
23
25
|
export const GATEWAY_VERSION = "0.1.0";
|
|
24
26
|
export const RECEIPT_META_KEY = "agent-custody/receipt";
|
|
25
27
|
export const MODEL_META_KEY = "agent-custody/model";
|
|
28
|
+
/** true on a result whose receipt is signed and kept in the outbox, and not yet in the log */
|
|
29
|
+
export const LOG_PENDING_META_KEY = "agent-custody/log-pending";
|
|
26
30
|
/** 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
31
|
export const RETRY_RECEIPT_META_KEY = "agent-custody/retry-receipt";
|
|
28
32
|
/** Set by the gateway on the call it forwards upstream: the receipt id, and the agent and principal from the attested grant. */
|
|
@@ -92,8 +96,95 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
92
96
|
const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
|
|
93
97
|
const approvalKeys = cfg.approvals?.trustedKeys.map(loadPublicKey) ?? [];
|
|
94
98
|
const approvalRule = (tool) => cfg.approvals?.tools.find((rule) => rule.tool === tool) ?? cfg.approvals?.tools.find((rule) => rule.tool === "*");
|
|
95
|
-
|
|
96
|
-
|
|
99
|
+
// The Cedar policy, re-read whenever the file changes, like the revocation list. A call is evaluated under the policy
|
|
100
|
+
// in force when it starts, and its receipt names that policy's digest. A changed file that cannot be read or does not
|
|
101
|
+
// parse is refused and the policy in force stays: never an allow, and never a fall back to no policy. Every change
|
|
102
|
+
// and every refusal is printed and appended to receiptsDir/policy-reloads.jsonl with both digests and the time.
|
|
103
|
+
// The bytes and the metadata come from one open file, so a rename between reading and stat'ing cannot pair them wrongly.
|
|
104
|
+
// ctime is in the key because a program can set mtime back but not ctime, and every write moves it. A file written in
|
|
105
|
+
// the last two seconds may still be being written within one timestamp tick, so its key is not kept: it is re-read on
|
|
106
|
+
// each call until it settles, and a half-written file read meanwhile is replaced by the finished one.
|
|
107
|
+
const keyOf = (st) => `${st.dev}:${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
|
|
108
|
+
const settled = (st) => Date.now() - Math.max(st.mtimeMs, st.ctimeMs) >= 2000;
|
|
109
|
+
const readPolicy = () => {
|
|
110
|
+
const fd = openSync(cfg.policyFile, "r");
|
|
111
|
+
try {
|
|
112
|
+
const st = fstatSync(fd);
|
|
113
|
+
const text = readFileSync(fd, "utf8");
|
|
114
|
+
return { text, seen: settled(st) ? keyOf(st) : "" };
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
closeSync(fd);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const policyStat = () => keyOf(statSync(cfg.policyFile));
|
|
121
|
+
const initialPolicy = readPolicy();
|
|
122
|
+
let policyNow = { text: initialPolicy.text, digest: policyDigest(initialPolicy.text) };
|
|
123
|
+
let policySeen = initialPolicy.seen;
|
|
124
|
+
// A file that cannot be read is retried on every call, since restoring access changes none of its metadata; this
|
|
125
|
+
// keeps the refusal from being printed and recorded on each of those calls.
|
|
126
|
+
let unreadableSeen = "";
|
|
127
|
+
// A file still settling is re-read on each call; a refusal is recorded once for the same bytes.
|
|
128
|
+
let refusedDigest = "";
|
|
129
|
+
const policyReloads = join(cfg.receiptsDir, "policy-reloads.jsonl");
|
|
130
|
+
const recordReload = (entry) => {
|
|
131
|
+
try {
|
|
132
|
+
mkdirSync(cfg.receiptsDir, { recursive: true });
|
|
133
|
+
appendFileSync(policyReloads, JSON.stringify({ at: new Date().toISOString(), file: cfg.policyFile, ...entry }) + "\n");
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
console.error(`agent-custody gateway: cannot record the policy change in ${policyReloads}: ${e instanceof Error ? e.message : String(e)}`);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const refuseReload = (to, errors) => {
|
|
140
|
+
console.error(`agent-custody gateway: POLICY NOT RELOADED: ${cfg.policyFile} ${errors.join("; ")}; policy ${policyNow.digest} stays in force`);
|
|
141
|
+
recordReload({ event: "refused", from: policyNow.digest, to, errors });
|
|
142
|
+
};
|
|
143
|
+
const currentPolicy = () => {
|
|
144
|
+
const unreadable = (seen, e) => {
|
|
145
|
+
if (unreadableSeen !== seen)
|
|
146
|
+
refuseReload(null, [`cannot be read (${e instanceof Error ? e.message : String(e)})`]);
|
|
147
|
+
unreadableSeen = seen;
|
|
148
|
+
return policyNow;
|
|
149
|
+
};
|
|
150
|
+
let seen;
|
|
151
|
+
try {
|
|
152
|
+
seen = policyStat();
|
|
153
|
+
}
|
|
154
|
+
catch (e) {
|
|
155
|
+
return unreadable("missing", e);
|
|
156
|
+
}
|
|
157
|
+
if (seen === policySeen)
|
|
158
|
+
return policyNow;
|
|
159
|
+
let read;
|
|
160
|
+
try {
|
|
161
|
+
read = readPolicy();
|
|
162
|
+
}
|
|
163
|
+
catch (e) {
|
|
164
|
+
return unreadable(seen, e);
|
|
165
|
+
}
|
|
166
|
+
unreadableSeen = "";
|
|
167
|
+
policySeen = read.seen;
|
|
168
|
+
const text = read.text;
|
|
169
|
+
const digest = policyDigest(text);
|
|
170
|
+
if (digest === policyNow.digest)
|
|
171
|
+
return policyNow;
|
|
172
|
+
if (digest === refusedDigest)
|
|
173
|
+
return policyNow;
|
|
174
|
+
const errors = policyParseErrors(text);
|
|
175
|
+
if (errors.length > 0) {
|
|
176
|
+
refusedDigest = digest;
|
|
177
|
+
refuseReload(digest, [`does not parse: ${errors.join("; ")}`]);
|
|
178
|
+
return policyNow;
|
|
179
|
+
}
|
|
180
|
+
refusedDigest = "";
|
|
181
|
+
// a policy with no permit rule parses and denies every call: fail-closed, but never a reload to pass over quietly
|
|
182
|
+
const warnings = hasPermitRule(text) ? [] : ["no permit rule: every call is denied"];
|
|
183
|
+
console.error(`agent-custody gateway: policy reloaded from ${cfg.policyFile}: ${policyNow.digest} -> ${digest}${warnings.length ? `; WARNING: ${warnings.join("; ")}` : ""}`);
|
|
184
|
+
recordReload({ event: "reloaded", from: policyNow.digest, to: digest, ...(warnings.length ? { warnings } : {}) });
|
|
185
|
+
policyNow = { text, digest };
|
|
186
|
+
return policyNow;
|
|
187
|
+
};
|
|
97
188
|
// Private evidence: the key that encrypts withheld fields, read once; a rule in mode encrypted without it is a config error.
|
|
98
189
|
const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
|
|
99
190
|
for (const [tool, rule] of Object.entries(cfg.capture ?? {})) {
|
|
@@ -102,10 +193,19 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
102
193
|
throw new Error(`capture for ${tool} uses mode encrypted, which needs captureKeyEnv`);
|
|
103
194
|
}
|
|
104
195
|
// The rules are applied by the issuer to every statement it signs, the authorization included: the gateway hands it the call in full.
|
|
105
|
-
|
|
196
|
+
if (cfg.strict) {
|
|
197
|
+
const refused = strictRefusals(cfg);
|
|
198
|
+
if (refused.length)
|
|
199
|
+
throw new Error(`agent-custody gateway: ${refused.join("; ")}`);
|
|
200
|
+
}
|
|
201
|
+
const sink = options.log ?? openLog(cfg, gatewayKey);
|
|
202
|
+
if (cfg.strict && sink.kind !== "http")
|
|
203
|
+
throw new Error(`agent-custody gateway: strict mode needs a remote log, and ${sink.where} is a file`);
|
|
204
|
+
const issuer = createIssuer(gatewayKey, cfg.receiptsDir, sink, { exporter: options.exporter ?? openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
|
|
205
|
+
const issuedBy = { kind: "gateway", keyid: issuer.keyid, version: GATEWAY_VERSION, ...(cfg.strict ? { strict: true } : {}) };
|
|
106
206
|
const precommit = new Set(cfg.precommit);
|
|
107
207
|
const operationRule = (tool) => cfg.operations?.tools.find((rule) => rule.tool === tool);
|
|
108
|
-
const consequential = (tool) => !!operationRule(tool) || precommit.has("*") || precommit.has(tool);
|
|
208
|
+
const consequential = (tool) => !!cfg.strict || !!operationRule(tool) || precommit.has("*") || precommit.has(tool);
|
|
109
209
|
// A fact lookup runs before the policy can decide, because the policy decides on it. It is therefore a read the
|
|
110
210
|
// gateway makes on the agent's request, never a consequential call: a fact tool named in precommit is a config error.
|
|
111
211
|
// "*" covers the tools the agent calls; a lookup is the gateway's own read, so only an explicit name makes it consequential.
|
|
@@ -320,6 +420,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
320
420
|
};
|
|
321
421
|
async function handleCall(params) {
|
|
322
422
|
const tool = params.name;
|
|
423
|
+
const { text: policyText, digest: pDigest } = currentPolicy();
|
|
323
424
|
// An embedding caller can mutate its objects while a lookup or log append is awaited. Snapshot the call and
|
|
324
425
|
// approval before the first await, so the approved bytes are the bytes evaluated, logged, and forwarded. A caller
|
|
325
426
|
// also cannot change the payment after its reservation was bound.
|
|
@@ -417,7 +518,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
417
518
|
const head = {
|
|
418
519
|
receiptId,
|
|
419
520
|
timestamp,
|
|
420
|
-
issuer:
|
|
521
|
+
issuer: issuedBy,
|
|
421
522
|
principal: { id: delegation.principal, keyid: principalKeyid, provenance: "attested" },
|
|
422
523
|
agent: { id: delegation.agent, provenance: "attested" },
|
|
423
524
|
delegation: { envelope: grantEnvelope, provenance: "attested" },
|
|
@@ -460,15 +561,15 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
460
561
|
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
562
|
execution = { status: "withheld", reason: `existing operation: not forwarded again; the stored outcome is ${head.operation.status}`, provenance: "observed" };
|
|
462
563
|
}
|
|
463
|
-
if (!execution && (policy.decision === "allow" || financial && forward) && consequential(tool)) {
|
|
564
|
+
if (!execution && (policy.decision === "allow" || (financial || cfg.strict) && forward) && consequential(tool)) {
|
|
464
565
|
// A consequential call is committed to the log before it goes out, so that evidence of the side effect exists
|
|
465
566
|
// before the side effect does. If the log will not take the authorization, the call is not forwarded; in
|
|
466
|
-
// observe mode nothing is withheld, and the missing authorization is printed instead.
|
|
567
|
+
// observe mode nothing is withheld, and the missing authorization is printed instead, unless the mode is strict.
|
|
467
568
|
try {
|
|
468
569
|
authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } }, captureCtx);
|
|
469
570
|
}
|
|
470
571
|
catch (e) {
|
|
471
|
-
if (cfg.mode === "observe" && !financial)
|
|
572
|
+
if (cfg.mode === "observe" && !financial && !cfg.strict)
|
|
472
573
|
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)}`);
|
|
473
574
|
else
|
|
474
575
|
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" };
|
|
@@ -567,18 +668,31 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
567
668
|
operation = operations.update(operation.id, { status: "failed", unsent: undefined });
|
|
568
669
|
if (operation)
|
|
569
670
|
head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
671
|
+
// The call is done, so a log outage now must not tell the agent it failed: the receipt waits in the outbox. An
|
|
672
|
+
// operation keeps the old order, because its record holds the bundle and its retry is idempotent. Strict mode
|
|
673
|
+
// keeps no outbox: the authorization is in the log, and a receipt the log refuses leaves the call incomplete.
|
|
674
|
+
let issued;
|
|
675
|
+
let logPending = false;
|
|
676
|
+
try {
|
|
677
|
+
issued = await issuer.issue({
|
|
678
|
+
...head,
|
|
679
|
+
...(approval ? { approval } : {}),
|
|
680
|
+
session: { id: null, toolUseId: null, provenance: "claimed" },
|
|
681
|
+
model: { id: typeof modelClaim === "string" ? modelClaim : null, provenance: "claimed" },
|
|
682
|
+
policy: { ...policy, provenance: "observed" },
|
|
683
|
+
...(authorization ? { authorization } : {}),
|
|
684
|
+
execution,
|
|
685
|
+
}, captureCtx, undefined, { deferLog: !operation && !cfg.strict });
|
|
686
|
+
}
|
|
687
|
+
catch (e) {
|
|
688
|
+
if (!(e instanceof ReceiptPending))
|
|
689
|
+
throw e;
|
|
690
|
+
console.error(`agent-custody gateway: ${e.message}`);
|
|
691
|
+
logPending = true;
|
|
692
|
+
}
|
|
579
693
|
if (operation && createdOperation && attemptedOperation)
|
|
580
694
|
operations.update(operation.id, { original: issued });
|
|
581
|
-
const meta = { [RECEIPT_META_KEY]: receiptId, ...(head.operation ? { [OPERATION_META_KEY]: head.operation } : {}) };
|
|
695
|
+
const meta = { [RECEIPT_META_KEY]: receiptId, ...(head.operation ? { [OPERATION_META_KEY]: head.operation } : {}), ...(logPending ? { [LOG_PENDING_META_KEY]: true } : {}) };
|
|
582
696
|
const refuse = (text) => ({ isError: true, content: [{ type: "text", text: `${text} (receipt ${receiptId})` }], _meta: meta });
|
|
583
697
|
switch (execution.status) {
|
|
584
698
|
// the agent gets the real result, the real reason, and the real error: what is withheld is withheld from the receipt
|
|
@@ -610,10 +724,29 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
610
724
|
},
|
|
611
725
|
};
|
|
612
726
|
}
|
|
727
|
+
if (cfg.log && !cfg.precommit.length && !cfg.strict)
|
|
728
|
+
console.error("agent-custody gateway: a remote log is set and precommit is empty: every call is forwarded before its receipt is logged. Name the consequential tools in precommit, or [\"*\"]; requirePrecommit makes this an error");
|
|
729
|
+
let flushing;
|
|
730
|
+
const flushOutbox = () => flushing ??= (async () => {
|
|
731
|
+
const r = await issuer.flushOutbox();
|
|
732
|
+
if (r.setAside)
|
|
733
|
+
console.error(`agent-custody gateway: ${r.setAside} outbox entr${r.setAside === 1 ? "y is" : "ies are"} damaged, or not signed under its file name; renamed to .bad and not appended`);
|
|
734
|
+
if (r.foreign)
|
|
735
|
+
console.error(`agent-custody gateway: ${r.foreign} outbox entr${r.foreign === 1 ? "y is" : "ies are"} signed by a key other than ${issuer.keyid.slice(0, 12)}; left in the outbox and not appended. Restore the key that signed them, or move them away`);
|
|
736
|
+
if (r.error)
|
|
737
|
+
console.error(`agent-custody gateway: ${r.pending} receipt(s) wait in the outbox: ${r.error}`);
|
|
738
|
+
return r;
|
|
739
|
+
})().finally(() => { flushing = undefined; });
|
|
740
|
+
const autoFlush = () => void flushOutbox().catch((e) => console.error(`agent-custody gateway: the outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
|
|
741
|
+
// strict mode never adds to the outbox; receipts left there from before it was turned on are appended once, at start
|
|
742
|
+
const outboxTimer = options.autoFlush && !cfg.strict ? setInterval(autoFlush, 30_000).unref() : undefined;
|
|
743
|
+
if (options.autoFlush)
|
|
744
|
+
autoFlush();
|
|
613
745
|
return {
|
|
614
746
|
keyid: issuer.keyid,
|
|
615
747
|
open,
|
|
616
748
|
revoke,
|
|
749
|
+
policyDigest: () => currentPolicy().digest,
|
|
617
750
|
tools: () => advertised.map((t) => t.name),
|
|
618
751
|
revoked: () => {
|
|
619
752
|
reloadRevoked();
|
|
@@ -671,11 +804,11 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
671
804
|
throw new Error("provider outcome remains pending or unknown; the reservation is retained");
|
|
672
805
|
const predicate = {
|
|
673
806
|
receiptId: randomUUID(), timestamp: new Date().toISOString(),
|
|
674
|
-
issuer:
|
|
807
|
+
issuer: issuedBy,
|
|
675
808
|
principal: initial.principal, agent: initial.agent, delegation: initial.delegation,
|
|
676
809
|
session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
|
|
677
810
|
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:
|
|
811
|
+
facts: {}, policy: { decision: "allow", reasons: ["reconciliation: the gateway read the provider record and evaluated no policy"], errors: [], policyDigest: currentPolicy().digest, provenance: "observed" },
|
|
679
812
|
operation: operationEvidence(op, status), reconciliation: { original, lookup },
|
|
680
813
|
execution: { status: "executed", result, resultDigest: digestOf(result), provenance: "observed" },
|
|
681
814
|
};
|
|
@@ -690,7 +823,12 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
690
823
|
operations.update(op.id, { status: intent.predicate.operation.status, reconciliation: { ...retained, bundle }, result: intent.predicate.execution.result, unsent: undefined });
|
|
691
824
|
return bundle;
|
|
692
825
|
},
|
|
826
|
+
flushOutbox,
|
|
827
|
+
pendingReceipts: () => issuer.pending(),
|
|
693
828
|
async close() {
|
|
829
|
+
if (outboxTimer)
|
|
830
|
+
clearInterval(outboxTimer);
|
|
831
|
+
await flushing?.catch(() => { });
|
|
694
832
|
for (const c of upstreams.values())
|
|
695
833
|
await c.close();
|
|
696
834
|
operations?.close();
|
package/dist/index.d.ts
CHANGED
|
@@ -25,6 +25,10 @@ export type { KeyDocument, RemoteSignerOptions, RetiredKey, RunningSigner, Signe
|
|
|
25
25
|
export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.ts";
|
|
26
26
|
export { adminRoutes, welcomeSheet } from "./log-admin.ts";
|
|
27
27
|
export { fetchWitnessKeys, Witness } from "./witness.ts";
|
|
28
|
+
export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.ts";
|
|
29
|
+
export type { AnchorChain, AnchorCheck, AnchorCheckOptions, AnchorOptions, AnchorRecord, AnchorRun, AnchorTenantOutcome, AnchorTxOutcome } from "./anchor.ts";
|
|
30
|
+
export { evmChain } from "./anchor-evm.ts";
|
|
31
|
+
export type { EvmChainOptions } from "./anchor-evm.ts";
|
|
28
32
|
export { checkLog, formatLogCheck } from "./log-check.ts";
|
|
29
33
|
export type { LogCheck, LogCheckOptions, LogCheckResult } from "./log-check.ts";
|
|
30
34
|
export type { WitnessOptions, WitnessOutcome, WitnessedCheckpoint } from "./witness.ts";
|
package/dist/index.js
CHANGED
|
@@ -17,6 +17,8 @@ export { connectSigner, fetchLogKeys, localSigner, serveSigner, signerHandler }
|
|
|
17
17
|
export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.js";
|
|
18
18
|
export { adminRoutes, welcomeSheet } from "./log-admin.js";
|
|
19
19
|
export { fetchWitnessKeys, Witness } from "./witness.js";
|
|
20
|
+
export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.js";
|
|
21
|
+
export { evmChain } from "./anchor-evm.js";
|
|
20
22
|
export { checkLog, formatLogCheck } from "./log-check.js";
|
|
21
23
|
export * from "./config.js";
|
|
22
24
|
export * from "./operations.js";
|
package/dist/issue.d.ts
CHANGED
|
@@ -8,6 +8,24 @@ export interface PreparedReceipt {
|
|
|
8
8
|
envelope: Envelope;
|
|
9
9
|
view: PrivateView<ReceiptPredicate>;
|
|
10
10
|
}
|
|
11
|
+
/** The receipts whose log append failed wait here, signed, until `flushOutbox` appends them. */
|
|
12
|
+
export declare const OUTBOX_DIR = "outbox";
|
|
13
|
+
/** What one `flushOutbox` did. `foreign` entries are signed by another key and stay in the outbox. */
|
|
14
|
+
export interface FlushResult {
|
|
15
|
+
sent: number;
|
|
16
|
+
pending: number;
|
|
17
|
+
setAside: number;
|
|
18
|
+
foreign: number;
|
|
19
|
+
error?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Thrown by `issue` with `deferLog` when the log did not take the receipt. The signed receipt is kept in the outbox and
|
|
23
|
+
* no bundle is written yet: `flushOutbox` appends it later and then writes the bundle.
|
|
24
|
+
*/
|
|
25
|
+
export declare class ReceiptPending extends Error {
|
|
26
|
+
readonly receiptId: string;
|
|
27
|
+
constructor(receiptId: string, cause: unknown);
|
|
28
|
+
}
|
|
11
29
|
export interface Issuer {
|
|
12
30
|
keyid: string;
|
|
13
31
|
log: LogSink;
|
|
@@ -16,9 +34,21 @@ export interface Issuer {
|
|
|
16
34
|
* bundle. Rejects if the log refuses the leaf; no bundle is written then. The predicate is the call in full; what
|
|
17
35
|
* is signed, written, and exported is the view.
|
|
18
36
|
*/
|
|
19
|
-
issue(predicate: ReceiptPredicate, ctx?: CaptureContext, retainPrepared?: (prepared: PreparedReceipt) => PreparedReceipt
|
|
37
|
+
issue(predicate: ReceiptPredicate, ctx?: CaptureContext, retainPrepared?: (prepared: PreparedReceipt) => PreparedReceipt, opts?: {
|
|
38
|
+
deferLog?: boolean;
|
|
39
|
+
}): Promise<ReceiptBundle>;
|
|
20
40
|
/** 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. */
|
|
21
41
|
authorize(predicate: AuthorizationPredicate, ctx?: CaptureContext): Promise<AuthorizationBundle>;
|
|
42
|
+
/**
|
|
43
|
+
* Appends each receipt in the outbox, oldest statement first, and writes its bundle. A log refusal stops the flush;
|
|
44
|
+
* another failure is reported in `error` and the flush goes on. One flush runs at a time in a process, and a lock
|
|
45
|
+
* file in the outbox keeps other processes out: when another process holds it, nothing is done. An entry that is
|
|
46
|
+
* damaged, or that this issuer's key signed under another receipt id, is renamed to `<name>.bad` and counted in
|
|
47
|
+
* `setAside`. An entry signed by another key stays in the outbox and is counted in `foreign`.
|
|
48
|
+
*/
|
|
49
|
+
flushOutbox(): Promise<FlushResult>;
|
|
50
|
+
/** the receipts in the outbox */
|
|
51
|
+
pending(): number;
|
|
22
52
|
}
|
|
23
53
|
export interface IssuerOptions {
|
|
24
54
|
/** told about every receipt after it is written; an exporter's failure never reaches the caller */
|