@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
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
export declare const OPERATION_META_KEY = "agent-custody/operation";
|
|
2
|
+
export type OperationStatus = "submitted" | "pending" | "confirmed" | "failed" | "unknown";
|
|
3
|
+
/**
|
|
4
|
+
* A stamp that tells one process from a later process with the same PID: the kernel start time of the process.
|
|
5
|
+
* The prefix names the source, so two stamps from different sources never compare equal. Returns undefined when
|
|
6
|
+
* the start time cannot be read.
|
|
7
|
+
*/
|
|
8
|
+
export declare function processStamp(pid: number): string | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* The start time from `ps`, for a system without /proc. `ps` prints it in local time, so the time zone is pinned to
|
|
11
|
+
* UTC: a creator and an operator that run under different TZ values must still get the same text.
|
|
12
|
+
*/
|
|
13
|
+
export declare function psStamp(pid: number): string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Whether the process that created an operation may still run. A process that is gone is not alive. A live process
|
|
16
|
+
* with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
|
|
17
|
+
* start time cannot be compared, the answer is "alive": recovery waits, and never releases a live forward.
|
|
18
|
+
*/
|
|
19
|
+
export declare function ownerAlive(op: Pick<OperationRecord, "ownerPid" | "ownerStart">): boolean;
|
|
20
|
+
export interface OperationRecord {
|
|
21
|
+
id: string;
|
|
22
|
+
/** Creator process on this machine. A live submitted call cannot be reconciled underneath its forward. */
|
|
23
|
+
ownerPid: number;
|
|
24
|
+
/** `processStamp` of the creator, so that a later process with the same PID is not taken for it. */
|
|
25
|
+
ownerStart?: string;
|
|
26
|
+
issuerKeyid: string;
|
|
27
|
+
providerDigest?: string;
|
|
28
|
+
idempotencyKey: string;
|
|
29
|
+
principal: string;
|
|
30
|
+
agent: string;
|
|
31
|
+
tool: string;
|
|
32
|
+
argsDigest: string;
|
|
33
|
+
budget: string;
|
|
34
|
+
currency: string;
|
|
35
|
+
amount: number;
|
|
36
|
+
/** UTC date on which this operation was reserved; a retry never moves it to a new budget period. */
|
|
37
|
+
period: string;
|
|
38
|
+
status: OperationStatus;
|
|
39
|
+
originalReceiptId: string;
|
|
40
|
+
/** Signed authorization or execution bundle, saved before forwarding or returning it to the caller. */
|
|
41
|
+
original?: unknown;
|
|
42
|
+
/** The call as the gateway decided it, kept until `original` exists. It lets recovery sign a receipt for a call that was never forwarded. Holds raw request values: keep the database private. */
|
|
43
|
+
unsent?: unknown;
|
|
44
|
+
result?: unknown;
|
|
45
|
+
reconciliation?: unknown;
|
|
46
|
+
updatedAt: string;
|
|
47
|
+
}
|
|
48
|
+
export interface OperationReservation {
|
|
49
|
+
id: string;
|
|
50
|
+
issuerKeyid: string;
|
|
51
|
+
/** Digest of the configured upstream and destination; prevents retrying a key against a changed provider. */
|
|
52
|
+
providerDigest?: string;
|
|
53
|
+
principal: string;
|
|
54
|
+
agent: string;
|
|
55
|
+
tool: string;
|
|
56
|
+
argsDigest: string;
|
|
57
|
+
budget: string;
|
|
58
|
+
currency: string;
|
|
59
|
+
amount: number;
|
|
60
|
+
limit: number;
|
|
61
|
+
originalReceiptId: string;
|
|
62
|
+
/** Normally omitted; the gateway always uses the current UTC date. */
|
|
63
|
+
period?: string;
|
|
64
|
+
/** See `OperationRecord.unsent`. */
|
|
65
|
+
unsent?: unknown;
|
|
66
|
+
}
|
|
67
|
+
export interface OperationUpdate {
|
|
68
|
+
status?: OperationStatus;
|
|
69
|
+
original?: unknown;
|
|
70
|
+
unsent?: unknown;
|
|
71
|
+
result?: unknown;
|
|
72
|
+
reconciliation?: unknown;
|
|
73
|
+
}
|
|
74
|
+
/** One owner-only SQLite database, shared by all gateway sessions/processes using the same budgets. */
|
|
75
|
+
export declare class OperationStore {
|
|
76
|
+
private readonly db;
|
|
77
|
+
constructor(file: string);
|
|
78
|
+
get(id: string): OperationRecord | undefined;
|
|
79
|
+
/** Stable enumeration for an operator recovering outstanding work after a restart. */
|
|
80
|
+
list(): OperationRecord[];
|
|
81
|
+
reserve(input: OperationReservation): {
|
|
82
|
+
created: boolean;
|
|
83
|
+
operation: OperationRecord;
|
|
84
|
+
};
|
|
85
|
+
update(id: string, patch: OperationUpdate): OperationRecord;
|
|
86
|
+
/**
|
|
87
|
+
* Save the signed authorization of a submitted operation, and let the gateway forward. This is a compare-and-set:
|
|
88
|
+
* it refuses once recovery has closed the operation or claimed a reconciliation, whatever a liveness check said,
|
|
89
|
+
* so a call that recovery closed as "not forwarded" is never forwarded afterwards.
|
|
90
|
+
*/
|
|
91
|
+
saveAuthorization(id: string, original: unknown): OperationRecord;
|
|
92
|
+
/**
|
|
93
|
+
* Persist one terminal reconciliation intent before its asynchronous log append; later reconcilers use it.
|
|
94
|
+
* With `unsent`, the claim says that the call was never forwarded, and it holds only while no authorization is saved.
|
|
95
|
+
*/
|
|
96
|
+
claimReconciliation(id: string, candidate: unknown, unsent?: boolean): unknown;
|
|
97
|
+
/** Retain the first signed/captured receipt and its private salts, so every crash/concurrent retry uses identical bytes. */
|
|
98
|
+
prepareReconciliation(id: string, prepared: unknown): unknown;
|
|
99
|
+
close(): void;
|
|
100
|
+
private transaction;
|
|
101
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// A side effect is claimed durably before it may be forwarded. An existing claim is never forwarded again,
|
|
2
|
+
// even after a crash: only a provider reconciliation read may resolve its outcome and release its reservation.
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { closeSync, constants, lstatSync, mkdirSync, openSync, chmodSync, readFileSync } from "node:fs";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { dirname, resolve } from "node:path";
|
|
7
|
+
import { digestOf } from "./crypto.js";
|
|
8
|
+
export const OPERATION_META_KEY = "agent-custody/operation";
|
|
9
|
+
/**
|
|
10
|
+
* A stamp that tells one process from a later process with the same PID: the kernel start time of the process.
|
|
11
|
+
* The prefix names the source, so two stamps from different sources never compare equal. Returns undefined when
|
|
12
|
+
* the start time cannot be read.
|
|
13
|
+
*/
|
|
14
|
+
export function processStamp(pid) {
|
|
15
|
+
try {
|
|
16
|
+
// Linux: field 22 of /proc/<pid>/stat, in clock ticks since boot. The command name (field 2) may hold spaces.
|
|
17
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
18
|
+
const field = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
19
|
+
if (field)
|
|
20
|
+
return `proc:${field}`;
|
|
21
|
+
}
|
|
22
|
+
catch { /* no /proc: try ps */ }
|
|
23
|
+
return psStamp(pid);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The start time from `ps`, for a system without /proc. `ps` prints it in local time, so the time zone is pinned to
|
|
27
|
+
* UTC: a creator and an operator that run under different TZ values must still get the same text.
|
|
28
|
+
*/
|
|
29
|
+
export function psStamp(pid) {
|
|
30
|
+
try {
|
|
31
|
+
const started = execFileSync("/bin/ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, env: { LC_ALL: "C", TZ: "UTC" }, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
32
|
+
if (started)
|
|
33
|
+
return `ps:${started}`;
|
|
34
|
+
}
|
|
35
|
+
catch { /* unreadable */ }
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
let own;
|
|
39
|
+
/**
|
|
40
|
+
* Whether the process that created an operation may still run. A process that is gone is not alive. A live process
|
|
41
|
+
* with the same PID but another start time is a different process (a container restart gives PID 1 again). When a
|
|
42
|
+
* start time cannot be compared, the answer is "alive": recovery waits, and never releases a live forward.
|
|
43
|
+
*/
|
|
44
|
+
export function ownerAlive(op) {
|
|
45
|
+
try {
|
|
46
|
+
process.kill(op.ownerPid, 0);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error.code === "ESRCH")
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
const now = op.ownerStart === undefined ? undefined : processStamp(op.ownerPid);
|
|
53
|
+
if (op.ownerStart === undefined || now === undefined || op.ownerStart.split(":")[0] !== now.split(":")[0])
|
|
54
|
+
return true;
|
|
55
|
+
return now === op.ownerStart;
|
|
56
|
+
}
|
|
57
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
58
|
+
const STATUS = new Set(["submitted", "pending", "confirmed", "failed", "unknown"]);
|
|
59
|
+
const BINDING = ["issuerKeyid", "providerDigest", "principal", "agent", "tool", "argsDigest", "budget", "currency", "amount"];
|
|
60
|
+
/** One owner-only SQLite database, shared by all gateway sessions/processes using the same budgets. */
|
|
61
|
+
export class OperationStore {
|
|
62
|
+
db;
|
|
63
|
+
constructor(file) {
|
|
64
|
+
const path = resolve(file);
|
|
65
|
+
const directory = dirname(path);
|
|
66
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
67
|
+
const dir = lstatSync(directory);
|
|
68
|
+
if (!dir.isDirectory() || dir.isSymbolicLink() || (dir.mode & 0o077) !== 0)
|
|
69
|
+
throw new Error("operation database needs an owner-only directory (0700)");
|
|
70
|
+
// Create the file without following a symlink, before SQLite can open it. An existing regular file is
|
|
71
|
+
// tightened to 0600; the private parent prevents another user from swapping it while SQLite opens it.
|
|
72
|
+
try {
|
|
73
|
+
closeSync(openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600));
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (error.code !== "EEXIST")
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
const stat = lstatSync(path);
|
|
80
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)
|
|
81
|
+
throw new Error("operation database must be a regular file, without symlinks or hard links");
|
|
82
|
+
chmodSync(path, 0o600);
|
|
83
|
+
// Deliberately lazy: gateways without financial operations never load SQLite (Node 22 may warn).
|
|
84
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
85
|
+
this.db = new DatabaseSync(path);
|
|
86
|
+
this.db.exec("PRAGMA busy_timeout = 10000; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;");
|
|
87
|
+
this.db.exec("CREATE TABLE IF NOT EXISTS operations (id TEXT PRIMARY KEY, budget TEXT NOT NULL, currency TEXT NOT NULL, period TEXT NOT NULL, amount INTEGER NOT NULL, status TEXT NOT NULL, json TEXT NOT NULL)");
|
|
88
|
+
this.db.exec("CREATE INDEX IF NOT EXISTS operations_budget_period ON operations (budget, period, status)");
|
|
89
|
+
}
|
|
90
|
+
get(id) {
|
|
91
|
+
const row = this.db.prepare("SELECT json FROM operations WHERE id = ?").get(id);
|
|
92
|
+
return row ? JSON.parse(row.json) : undefined;
|
|
93
|
+
}
|
|
94
|
+
/** Stable enumeration for an operator recovering outstanding work after a restart. */
|
|
95
|
+
list() {
|
|
96
|
+
return this.db.prepare("SELECT json FROM operations ORDER BY id").all().map((row) => JSON.parse(row.json));
|
|
97
|
+
}
|
|
98
|
+
reserve(input) {
|
|
99
|
+
if (!UUID.test(input.id))
|
|
100
|
+
throw new Error("operation id must be a lowercase UUID");
|
|
101
|
+
if (!Number.isSafeInteger(input.amount) || input.amount <= 0)
|
|
102
|
+
throw new Error("operation amount must be a positive safe integer in minor units");
|
|
103
|
+
if (!Number.isSafeInteger(input.limit) || input.limit < 0)
|
|
104
|
+
throw new Error("operation budget limit must be a nonnegative safe integer in minor units");
|
|
105
|
+
for (const name of ["issuerKeyid", "principal", "agent", "tool", "argsDigest", "budget", "currency", "originalReceiptId"]) {
|
|
106
|
+
if (typeof input[name] !== "string" || !input[name].length)
|
|
107
|
+
throw new Error(`operation ${name} is required`);
|
|
108
|
+
}
|
|
109
|
+
if (input.budget.length > 128)
|
|
110
|
+
throw new Error("operation budget id must be at most 128 characters");
|
|
111
|
+
if (!/^[A-Z]{3}$/.test(input.currency))
|
|
112
|
+
throw new Error("operation currency must be three uppercase letters");
|
|
113
|
+
const period = input.period ?? new Date().toISOString().slice(0, 10);
|
|
114
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(period) || !Number.isFinite(Date.parse(`${period}T00:00:00.000Z`)) || new Date(`${period}T00:00:00.000Z`).toISOString().slice(0, 10) !== period)
|
|
115
|
+
throw new Error("operation period must be a UTC date");
|
|
116
|
+
return this.transaction(() => {
|
|
117
|
+
const previous = this.get(input.id);
|
|
118
|
+
if (previous) {
|
|
119
|
+
for (const field of BINDING) {
|
|
120
|
+
if (previous[field] !== input[field])
|
|
121
|
+
throw new Error(`operation id is already bound to different ${field}`);
|
|
122
|
+
}
|
|
123
|
+
return { created: false, operation: previous };
|
|
124
|
+
}
|
|
125
|
+
// Bind the currency even when an older operation failed or belongs to a previous day. Changing a
|
|
126
|
+
// budget's unit under the same name would otherwise make its amounts incomparable.
|
|
127
|
+
const otherCurrency = this.db.prepare("SELECT 1 FROM operations WHERE budget = ? AND currency <> ? LIMIT 1").get(input.budget, input.currency);
|
|
128
|
+
if (otherCurrency)
|
|
129
|
+
throw new Error("operation budget is already bound to another currency");
|
|
130
|
+
// Add with BigInt: individual minor-unit amounts are safe JS integers, but a sum need not be.
|
|
131
|
+
const reserved = this.db.prepare("SELECT amount FROM operations WHERE budget = ? AND period = ? AND status <> 'failed'").all(input.budget, period).reduce((sum, row) => sum + BigInt(row.amount), 0n);
|
|
132
|
+
if (reserved + BigInt(input.amount) > BigInt(input.limit))
|
|
133
|
+
throw new Error(`operation budget ${input.budget} exceeded for ${period}`);
|
|
134
|
+
const operation = {
|
|
135
|
+
id: input.id,
|
|
136
|
+
ownerPid: process.pid,
|
|
137
|
+
...((own ??= { stamp: processStamp(process.pid) }).stamp !== undefined ? { ownerStart: own.stamp } : {}),
|
|
138
|
+
issuerKeyid: input.issuerKeyid,
|
|
139
|
+
...(input.providerDigest !== undefined ? { providerDigest: input.providerDigest } : {}),
|
|
140
|
+
idempotencyKey: digestOf({ issuerKeyid: input.issuerKeyid, providerDigest: input.providerDigest ?? null, tool: input.tool, principal: input.principal, agent: input.agent, id: input.id }),
|
|
141
|
+
principal: input.principal,
|
|
142
|
+
agent: input.agent,
|
|
143
|
+
tool: input.tool,
|
|
144
|
+
argsDigest: input.argsDigest,
|
|
145
|
+
budget: input.budget,
|
|
146
|
+
currency: input.currency,
|
|
147
|
+
amount: input.amount,
|
|
148
|
+
period,
|
|
149
|
+
status: "submitted",
|
|
150
|
+
originalReceiptId: input.originalReceiptId,
|
|
151
|
+
...(input.unsent !== undefined ? { unsent: input.unsent } : {}),
|
|
152
|
+
updatedAt: new Date().toISOString(),
|
|
153
|
+
};
|
|
154
|
+
this.db.prepare("INSERT INTO operations (id, budget, currency, period, amount, status, json) VALUES (?, ?, ?, ?, ?, ?, ?)").run(operation.id, operation.budget, operation.currency, operation.period, operation.amount, operation.status, JSON.stringify(operation));
|
|
155
|
+
return { created: true, operation };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
update(id, patch) {
|
|
159
|
+
if (patch.status !== undefined && !STATUS.has(patch.status))
|
|
160
|
+
throw new Error("invalid operation status");
|
|
161
|
+
return this.transaction(() => {
|
|
162
|
+
const operation = this.get(id);
|
|
163
|
+
if (!operation)
|
|
164
|
+
throw new Error("operation not found");
|
|
165
|
+
if ((operation.status === "confirmed" || operation.status === "failed") && patch.status !== undefined && patch.status !== operation.status)
|
|
166
|
+
throw new Error(`operation ${operation.status} is terminal`);
|
|
167
|
+
const updated = { ...operation, ...patch, updatedAt: new Date().toISOString() };
|
|
168
|
+
this.db.prepare("UPDATE operations SET status = ?, json = ? WHERE id = ?").run(updated.status, JSON.stringify(updated), id);
|
|
169
|
+
return updated;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Save the signed authorization of a submitted operation, and let the gateway forward. This is a compare-and-set:
|
|
174
|
+
* it refuses once recovery has closed the operation or claimed a reconciliation, whatever a liveness check said,
|
|
175
|
+
* so a call that recovery closed as "not forwarded" is never forwarded afterwards.
|
|
176
|
+
*/
|
|
177
|
+
saveAuthorization(id, original) {
|
|
178
|
+
return this.transaction(() => {
|
|
179
|
+
const operation = this.get(id);
|
|
180
|
+
if (!operation)
|
|
181
|
+
throw new Error("operation not found");
|
|
182
|
+
if (operation.status !== "submitted" || operation.reconciliation !== undefined)
|
|
183
|
+
throw new Error(`operation was closed (${operation.status}) before its call was forwarded`);
|
|
184
|
+
const updated = { ...operation, original, updatedAt: new Date().toISOString() };
|
|
185
|
+
delete updated.unsent;
|
|
186
|
+
this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
|
|
187
|
+
return updated;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Persist one terminal reconciliation intent before its asynchronous log append; later reconcilers use it.
|
|
192
|
+
* With `unsent`, the claim says that the call was never forwarded, and it holds only while no authorization is saved.
|
|
193
|
+
*/
|
|
194
|
+
claimReconciliation(id, candidate, unsent = false) {
|
|
195
|
+
if (candidate === undefined || candidate === null)
|
|
196
|
+
throw new Error("reconciliation intent is required");
|
|
197
|
+
return this.transaction(() => {
|
|
198
|
+
const operation = this.get(id);
|
|
199
|
+
if (!operation)
|
|
200
|
+
throw new Error("operation not found");
|
|
201
|
+
if (operation.reconciliation !== undefined)
|
|
202
|
+
return operation.reconciliation;
|
|
203
|
+
if (unsent && (operation.original !== undefined || operation.status !== "submitted"))
|
|
204
|
+
throw new Error("the operation saved its authorization meanwhile; it may have been forwarded");
|
|
205
|
+
const updated = { ...operation, reconciliation: candidate, updatedAt: new Date().toISOString() };
|
|
206
|
+
this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
|
|
207
|
+
return candidate;
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
/** Retain the first signed/captured receipt and its private salts, so every crash/concurrent retry uses identical bytes. */
|
|
211
|
+
prepareReconciliation(id, prepared) {
|
|
212
|
+
return this.transaction(() => {
|
|
213
|
+
const operation = this.get(id);
|
|
214
|
+
if (!operation || !operation.reconciliation)
|
|
215
|
+
throw new Error("reconciliation intent is required");
|
|
216
|
+
const reconciliation = operation.reconciliation;
|
|
217
|
+
if (reconciliation.prepared !== undefined)
|
|
218
|
+
return reconciliation.prepared;
|
|
219
|
+
const updated = { ...operation, reconciliation: { ...reconciliation, prepared }, updatedAt: new Date().toISOString() };
|
|
220
|
+
this.db.prepare("UPDATE operations SET json = ? WHERE id = ?").run(JSON.stringify(updated), id);
|
|
221
|
+
return prepared;
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
close() { this.db.close(); }
|
|
225
|
+
transaction(body) {
|
|
226
|
+
// The write lock covers BOTH looking up the key and checking/reserving the budget. A second process
|
|
227
|
+
// cannot claim the same operation or pass the same budget check while this one is committing it.
|
|
228
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
229
|
+
try {
|
|
230
|
+
const result = body();
|
|
231
|
+
this.db.exec("COMMIT");
|
|
232
|
+
return result;
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
this.db.exec("ROLLBACK");
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
package/dist/otel.js
CHANGED
|
@@ -7,20 +7,27 @@ export function spanFor(p, bundle, serviceName) {
|
|
|
7
7
|
const traceId = hex.length === 32 ? hex : hex.padEnd(32, "0").slice(0, 32);
|
|
8
8
|
const start = BigInt(Date.parse(p.timestamp)) * 1000000n;
|
|
9
9
|
const end = BigInt(Date.now()) * 1000000n;
|
|
10
|
-
|
|
10
|
+
// A reconciliation receipt records a provider read that the gateway made. The gateway evaluated no policy, and it did
|
|
11
|
+
// not execute the payment tool again. The span says so: a dashboard must not count it as a second allowed call.
|
|
12
|
+
const reconciliation = p.reconciliation !== undefined;
|
|
13
|
+
const status = reconciliation ? "reconciled" : p.execution.status;
|
|
14
|
+
const operationFailed = reconciliation && p.operation?.status === "failed";
|
|
11
15
|
const auth = p.authorization;
|
|
12
16
|
const attributes = [
|
|
13
17
|
...str("agent_custody.receipt_id", p.receiptId),
|
|
14
18
|
...str("agent_custody.issuer.kind", p.issuer.kind),
|
|
15
19
|
...str("agent_custody.issuer.keyid", p.issuer.keyid),
|
|
16
20
|
...str("agent_custody.tool", p.tool.name),
|
|
21
|
+
...(reconciliation ? [{ key: "agent_custody.reconciliation", value: { boolValue: true } }, ...str("agent_custody.reconciliation.lookup_tool", p.reconciliation.lookup?.tool)] : []),
|
|
22
|
+
...str("agent_custody.operation.status", p.operation?.status),
|
|
23
|
+
...str("agent_custody.operation.original_receipt_id", p.operation?.originalReceiptId),
|
|
17
24
|
...str("agent_custody.upstream", p.tool.upstream),
|
|
18
25
|
...str("agent_custody.agent", p.agent.id),
|
|
19
26
|
...str("agent_custody.agent.provenance", p.agent.provenance),
|
|
20
27
|
...str("agent_custody.principal", p.principal.id),
|
|
21
28
|
...str("agent_custody.execution.status", status),
|
|
22
|
-
...str("agent_custody.policy.decision", p.policy?.decision),
|
|
23
|
-
...str("agent_custody.policy.digest", p.policy?.policyDigest),
|
|
29
|
+
...(reconciliation ? [] : str("agent_custody.policy.decision", p.policy?.decision)),
|
|
30
|
+
...(reconciliation ? [] : str("agent_custody.policy.digest", p.policy?.policyDigest)),
|
|
24
31
|
...int("agent_custody.log.leaf_index", bundle.inclusion.leafIndex),
|
|
25
32
|
...int("agent_custody.log.tree_size", bundle.inclusion.treeSize),
|
|
26
33
|
...(auth ? int("agent_custody.authorization.leaf_index", auth.inclusion.leafIndex) : []),
|
|
@@ -39,13 +46,13 @@ export function spanFor(p, bundle, serviceName) {
|
|
|
39
46
|
{
|
|
40
47
|
traceId,
|
|
41
48
|
spanId: traceId.slice(0, 16),
|
|
42
|
-
name: `${p.tool.name}`,
|
|
49
|
+
name: reconciliation ? `${p.tool.name} reconciliation` : `${p.tool.name}`,
|
|
43
50
|
kind: 3, // CLIENT: the agent calling out
|
|
44
51
|
startTimeUnixNano: start.toString(),
|
|
45
52
|
endTimeUnixNano: (end > start ? end : start).toString(),
|
|
46
53
|
attributes,
|
|
47
54
|
// Status.message is a string in OTLP; under a capture rule the error is a commitment, and the span says so
|
|
48
|
-
status: status === "executed" || status === "denied" || status === "withheld" ? { code: 1 } : { code: 2, message: status === "failed" ? "the upstream reported failure" : typeof p.execution.error === "string" ? (p.execution.error) : p.execution.error ? "the upstream reported an error (withheld under the capture rule)" : status },
|
|
55
|
+
status: operationFailed ? { code: 2, message: "the provider reports that the operation failed" } : status === "executed" || status === "reconciled" || status === "denied" || status === "withheld" ? { code: 1 } : { code: 2, message: status === "failed" ? "the upstream reported failure" : typeof p.execution.error === "string" ? (p.execution.error) : p.execution.error ? "the upstream reported an error (withheld under the capture rule)" : status },
|
|
49
56
|
},
|
|
50
57
|
],
|
|
51
58
|
},
|
package/dist/receipt.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { CaptureNote, Commitment } from "./capture.ts";
|
|
|
3
3
|
import type { InclusionProof } from "./log.ts";
|
|
4
4
|
import type { PolicyDecision } from "./policy.ts";
|
|
5
5
|
import type { UpstreamEvidence } from "./upstream.ts";
|
|
6
|
+
import type { ApprovalRecord } from "./approval.ts";
|
|
7
|
+
export type { ApprovalRecord } from "./approval.ts";
|
|
6
8
|
export declare const RECEIPT_TYPE = "application/vnd.in-toto+json";
|
|
7
9
|
export declare const RECEIPT_PREDICATE_TYPE = "https://agent-custody.dev/receipt/v0.2";
|
|
8
10
|
/** The statement a gateway commits to the log before forwarding a consequential call; the receipt for that call embeds it. */
|
|
@@ -30,6 +32,34 @@ export interface FactRecord {
|
|
|
30
32
|
resultDigest: string | Commitment;
|
|
31
33
|
provenance: "observed";
|
|
32
34
|
}
|
|
35
|
+
/** A gateway's durable financial operation identity; execution still describes only the tool/API call. */
|
|
36
|
+
export interface OperationEvidence {
|
|
37
|
+
id: string;
|
|
38
|
+
idempotencyKey: string;
|
|
39
|
+
/** Commits the configured provider read and status mapping before the financial call is forwarded. */
|
|
40
|
+
lookupDigest: string;
|
|
41
|
+
status: "submitted" | "pending" | "confirmed" | "failed" | "unknown";
|
|
42
|
+
/** Amounts stay in the original request, under its capture rule, rather than being copied into public metadata. */
|
|
43
|
+
budget: {
|
|
44
|
+
id: string;
|
|
45
|
+
currency: string;
|
|
46
|
+
period: string;
|
|
47
|
+
};
|
|
48
|
+
originalReceiptId: string;
|
|
49
|
+
provenance: "observed";
|
|
50
|
+
}
|
|
51
|
+
/** A later provider read, observed by the gateway, linked to the original signed, logged operation. */
|
|
52
|
+
export interface ReconciliationEvidence {
|
|
53
|
+
original: ReceiptBundle | AuthorizationBundle;
|
|
54
|
+
lookup: {
|
|
55
|
+
tool: string;
|
|
56
|
+
args: Record<string, unknown>;
|
|
57
|
+
statusPath: string;
|
|
58
|
+
identityPath: string;
|
|
59
|
+
confirmed: string[];
|
|
60
|
+
failed: string[];
|
|
61
|
+
};
|
|
62
|
+
}
|
|
33
63
|
export interface ReceiptPredicate {
|
|
34
64
|
receiptId: string;
|
|
35
65
|
timestamp: string;
|
|
@@ -56,6 +86,8 @@ export interface ReceiptPredicate {
|
|
|
56
86
|
envelope: Envelope;
|
|
57
87
|
provenance: "attested";
|
|
58
88
|
};
|
|
89
|
+
/** The gateway's payload-bound human approval check, when this tool requires approval. */
|
|
90
|
+
approval?: ApprovalRecord;
|
|
59
91
|
/** Correlation ids from the host, when it supplied any. Never checked, always claimed. */
|
|
60
92
|
session: {
|
|
61
93
|
id: string | null;
|
|
@@ -100,6 +132,9 @@ export interface ReceiptPredicate {
|
|
|
100
132
|
* side effect exists only after the side effect.
|
|
101
133
|
*/
|
|
102
134
|
authorization?: AuthorizationBundle;
|
|
135
|
+
operation?: OperationEvidence;
|
|
136
|
+
/** The provider read's full result is execution.result and follows the ordinary result capture rule. */
|
|
137
|
+
reconciliation?: ReconciliationEvidence;
|
|
103
138
|
execution: {
|
|
104
139
|
status: "executed" | "failed";
|
|
105
140
|
/** the result as the receipt carries it; `resultDigest` is over the whole result, salted from the field salts when any are withheld */
|
|
@@ -130,7 +165,7 @@ export interface ReceiptPredicate {
|
|
|
130
165
|
capture?: CaptureNote;
|
|
131
166
|
}
|
|
132
167
|
/** What the gateway commits before a consequential call goes out: everything the receipt will say, except the outcome. */
|
|
133
|
-
export type AuthorizationPredicate = Pick<ReceiptPredicate, "receiptId" | "timestamp" | "issuer" | "principal" | "agent" | "delegation" | "tool" | "request" | "facts" | "consumed" | "policy" | "capture">;
|
|
168
|
+
export type AuthorizationPredicate = Pick<ReceiptPredicate, "receiptId" | "timestamp" | "issuer" | "principal" | "agent" | "delegation" | "approval" | "tool" | "request" | "facts" | "consumed" | "policy" | "capture" | "operation">;
|
|
134
169
|
export interface AuthorizationStatement {
|
|
135
170
|
_type: "https://in-toto.io/Statement/v1";
|
|
136
171
|
subject: {
|
package/dist/rest.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { OPERATION_META_KEY } from "./operations.js";
|
|
1
2
|
const encode = (v) => encodeURIComponent(typeof v === "string" ? v : JSON.stringify(v));
|
|
2
3
|
/** Builds the request for one tool call: path parameters substituted, the rest of the arguments as query or body. */
|
|
3
4
|
export function buildRequest(base, tool, args) {
|
|
@@ -42,7 +43,19 @@ export function restUpstream(name, cfg, opts = {}) {
|
|
|
42
43
|
if (!tool)
|
|
43
44
|
throw new Error(`upstream ${name} has no tool "${params.name}"`);
|
|
44
45
|
const { url, method, body } = buildRequest(cfg.baseUrl, tool, params.arguments ?? {});
|
|
45
|
-
const
|
|
46
|
+
const requestHeaders = new Headers({ accept: "application/json", ...(body !== null ? { "content-type": "application/json" } : {}), ...headers });
|
|
47
|
+
if (tool.idempotencyHeader) {
|
|
48
|
+
const operation = params._meta?.[OPERATION_META_KEY];
|
|
49
|
+
if (!operation || typeof operation !== "object" || !Object.hasOwn(operation, "id") || !Object.hasOwn(operation, "idempotencyKey"))
|
|
50
|
+
throw new Error(`tool ${tool.name}: durable operation metadata is required`);
|
|
51
|
+
const { id, idempotencyKey } = operation;
|
|
52
|
+
if (typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) || typeof idempotencyKey !== "string" || !/^[0-9a-f]{64}$/.test(idempotencyKey))
|
|
53
|
+
throw new Error(`tool ${tool.name}: malformed durable operation metadata`);
|
|
54
|
+
// Set after static/environment headers, case-insensitively, so a configured header cannot replace
|
|
55
|
+
// the durable key. The metadata itself never enters the provider's body or query arguments.
|
|
56
|
+
requestHeaders.set(tool.idempotencyHeader, idempotencyKey);
|
|
57
|
+
}
|
|
58
|
+
const res = await f(url, { method, headers: requestHeaders, ...(body !== null ? { body } : {}), signal: AbortSignal.timeout(cfg.timeoutMs) });
|
|
46
59
|
const text = await res.text();
|
|
47
60
|
// The result is what the API returned, as text. JSON stays JSON so policy facts and consumers can read it.
|
|
48
61
|
return { content: [{ type: "text", text: text.length ? text : JSON.stringify({ status: res.status }) }], ...(res.ok ? {} : { isError: true }) };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type PublicKeyRef } from "./crypto.ts";
|
|
2
|
+
import { type PolicyDecision } from "./policy.ts";
|
|
3
|
+
import { type AuthorizationBundle, type AuthorizationStatement, type ReceiptPredicate } from "./receipt.ts";
|
|
4
|
+
export interface SimulationChange {
|
|
5
|
+
receiptId: string;
|
|
6
|
+
tool: string;
|
|
7
|
+
/** The recorded Cedar decision, including observe-mode and provenance information. */
|
|
8
|
+
previous: NonNullable<ReceiptPredicate["policy"]>;
|
|
9
|
+
proposed: PolicyDecision;
|
|
10
|
+
}
|
|
11
|
+
export interface SimulationSkip {
|
|
12
|
+
receiptId: string;
|
|
13
|
+
tool: string;
|
|
14
|
+
reason: string;
|
|
15
|
+
}
|
|
16
|
+
export interface SimulationGroup {
|
|
17
|
+
tool: string;
|
|
18
|
+
/** The proposed policy's determining policy ids and evaluation errors. */
|
|
19
|
+
reason: string;
|
|
20
|
+
receiptIds: string[];
|
|
21
|
+
}
|
|
22
|
+
export interface SimulationReport {
|
|
23
|
+
runId: string;
|
|
24
|
+
timestamp: string;
|
|
25
|
+
policyDigest: string;
|
|
26
|
+
previousPolicyDigests: string[];
|
|
27
|
+
total: number;
|
|
28
|
+
evaluated: number;
|
|
29
|
+
unchanged: number;
|
|
30
|
+
complete: boolean;
|
|
31
|
+
changes: SimulationChange[];
|
|
32
|
+
skipped: SimulationSkip[];
|
|
33
|
+
/** Changed decisions, grouped by tool and the proposed reason. */
|
|
34
|
+
groups: SimulationGroup[];
|
|
35
|
+
}
|
|
36
|
+
export interface SimulationOptions {
|
|
37
|
+
/** The customer's capture key. It decrypts the withheld values that were encrypted under it. */
|
|
38
|
+
captureKey?: Buffer;
|
|
39
|
+
/** Disclosure files by receipt id, as `agent-custody reveal` writes them. A disclosure applies only to its own receipt. */
|
|
40
|
+
disclosures?: ReadonlyMap<string, unknown>;
|
|
41
|
+
/** Calls that have no receipt to replay. Each counts in `total` and is reported as skipped. */
|
|
42
|
+
unreplayable?: SimulationSkip[];
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Check an authorization bundle that has no receipt, as the verifier does for an embedded one: the issuer signed it, it
|
|
46
|
+
* is an authorization statement, and its leaf is in the log under a signed tree head. Throws when a check fails.
|
|
47
|
+
* Returns the statement's predicate.
|
|
48
|
+
*/
|
|
49
|
+
export declare function verifyOrphanAuthorization(bundle: AuthorizationBundle, issuerKeys: PublicKeyRef[], logKeys: PublicKeyRef[]): AuthorizationStatement["predicate"];
|
|
50
|
+
/**
|
|
51
|
+
* Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
|
|
52
|
+
* values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
|
|
53
|
+
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
|
|
54
|
+
* Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
|
|
55
|
+
* The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
|
|
56
|
+
*/
|
|
57
|
+
export declare function simulatePolicy(policyText: string, receipts: Iterable<ReceiptPredicate>, options?: SimulationOptions): SimulationReport;
|
|
58
|
+
export declare function formatSimulation(report: SimulationReport): string;
|