@agent-custody/state 0.6.19 → 0.7.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 +6 -4
- package/dist/blast.d.ts +9 -3
- package/dist/blast.js +29 -6
- package/dist/cli.js +27 -14
- package/dist/explain.d.ts +7 -2
- package/dist/explain.js +32 -13
- package/dist/http.d.ts +4 -2
- package/dist/http.js +26 -7
- package/dist/pack.d.ts +3 -1
- package/dist/pack.js +3 -3
- package/dist/server.d.ts +8 -0
- package/dist/server.js +18 -16
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -74,11 +74,11 @@ The lookup for writes is optional, so a write that supersedes nothing needs no l
|
|
|
74
74
|
|
|
75
75
|
**Attested executions.** Started with `--key memory.key`, the server signs every result for the receipt the gateway is issuing. A verifier given `memory.pub` then reports the execution of each memory call as attested by the memory server, not only observed by the gateway; the test suite verifies a write this way.
|
|
76
76
|
|
|
77
|
-
**Shared over HTTP.** `agent-custody-memory serve --ledger ./ledger.jsonl --http --port 8790 --token-env MEMORY_TOKEN` serves the same tools over Streamable HTTP, so several gateways, one per agent host, and, with `--allow-direct`, SDK-only agents share one ledger. That is the deployment quarantine was built for: writes arriving through a gateway are attested, writes arriving directly are claimed and hidden until a gateway confirms them, and the ledger tells them apart. A gateway reaches it with `"upstream": { "url": "http://127.0.0.1:8790/mcp", "tokenEnv": "MEMORY_TOKEN" }` in its config.
|
|
77
|
+
**Shared over HTTP.** `agent-custody-memory serve --ledger ./ledger.jsonl --http --port 8790 --token-env MEMORY_TOKEN --allow-direct --direct-token-env MEMORY_DIRECT_TOKEN` serves the same tools over Streamable HTTP, so several gateways, one per agent host, and, with `--allow-direct`, SDK-only agents share one ledger. The two kinds of caller hold different tokens, and the token decides what the server believes: a gateway's call carries the receipt id, the agent, and the facts the gateway observed in its `_meta`, and that is what makes a write attested or verified; a direct writer's `_meta` is dropped before the server reads it, so it can claim a fact and never attest one, whatever its call says. Never give a direct writer the gateway's token. That is the deployment quarantine was built for: writes arriving through a gateway are attested, writes arriving directly are claimed and hidden until a gateway confirms them, and the ledger tells them apart. A gateway reaches it with `"upstream": { "url": "http://127.0.0.1:8790/mcp", "tokenEnv": "MEMORY_TOKEN" }` in its config. The server does not start over HTTP without the gateway token, because without it any caller that reaches the port could pass as a gateway. The test suite runs exactly this: one gateway writer, one direct writer, one ledger.
|
|
78
78
|
|
|
79
79
|
[Writing policies](../receipts/docs/policies.md#policies-for-memory) in the receipts guide has six tested policies for the memory tools, from confining an agent to its team's space to a complete support-agent policy. Trust tiers are Cedar policies over the space and, through `includeClaimed`, over quarantine: `permit(principal, action == Action::"memory.write", resource) when { context.args.space == "team:support" };` lets this agent write team memory and nothing else. A read's receipt carries, as `observed`, the exact facts returned, so the ids the agent relied on are already on the record.
|
|
80
80
|
|
|
81
|
-
`--allow-direct` lets the server take calls without a gateway; then `source.receiptId` is null
|
|
81
|
+
`--allow-direct` lets the server take calls without a gateway; then `source.receiptId` is null, `actor` is whatever the caller said, recorded as such, and anything the caller puts in `_meta` is ignored. Over stdio the one client is either the gateway or a direct writer, and `--allow-direct` says which: a gateway must never spawn the server with `--allow-direct`. [examples/03-memory-behind-the-gateway.ts](examples/03-memory-behind-the-gateway.ts) runs the whole loop, including a denied write and a retraction that cites its own receipt.
|
|
82
82
|
|
|
83
83
|
## Certified forget
|
|
84
84
|
|
|
@@ -101,9 +101,11 @@ Receipts are the other place a value lives: the receipt that recorded the write
|
|
|
101
101
|
When a belief turns out wrong, the next question is what relied on it. Two records answer it together. Every gateway receipt carries `consumed`: the fact ids the agent had been shown, through the gateway, before that call, which the memory server declares on each read. Every fact in the ledger carries the receipt that wrote it. Walking forward from a fact through those two links gives every later call and every belief written in those calls, transitively, and whether the root was retracted and which derived beliefs are still believed.
|
|
102
102
|
|
|
103
103
|
```bash
|
|
104
|
-
agent-custody-memory blast --ledger ./ledger.jsonl --receipts ./receipts --fact <factId>
|
|
104
|
+
agent-custody-memory blast --ledger ./ledger.jsonl --receipts ./receipts --fact <factId> [--capture-key-env NAME]
|
|
105
105
|
```
|
|
106
106
|
|
|
107
|
+
A receipt issued under a private capture rule withholds what the agent had been shown. The query never counts such a call as having relied on nothing: it lists every one made since the ledger learned the fact (by transaction time: a fact valid from tomorrow is readable today) under `INCOMPLETE`, and the capture key, for receipts in mode `encrypted`, lets it see through.
|
|
108
|
+
|
|
107
109
|
```
|
|
108
110
|
fact 3f2a…: acct:42 plan = "enterprise" (space team:support, by support-agent, attested)
|
|
109
111
|
retracted at 2026-09-07T10:12:04.118Z by support-agent: CRM sync bug: account is on the free plan
|
|
@@ -250,7 +252,7 @@ tsconfig.build.json emits dist/ for consumers; the repo itself runs the .ts dir
|
|
|
250
252
|
- Retention and legal hold: a receipted sweep forgets what was learned before an instant and reaches the stores; a hold refuses forget and sweep until released, as events on the fact's history.
|
|
251
253
|
- Value-level quarantine: a write may cite a fact the gateway fetched itself; the value must match it and the fact is then `verified`, the provenance level above attested, or the write is refused.
|
|
252
254
|
- Attested executions: with a key, the memory server signs its results for the gateway's receipt, so a verifier holding its public key sees memory calls as attested.
|
|
253
|
-
- The memory server over HTTP: one ledger shared by several gateways and direct writers,
|
|
255
|
+
- The memory server over HTTP: one ledger shared by several gateways and direct writers, a token per kind of caller so only a gateway is believed about receipts and agents, quarantine live.
|
|
254
256
|
- Certified forget: `memory.forget` erases a value from the ledger file keeping its digest, stops believing it, removes it from every store, and reports exactly what happened; the gateway's receipt of that call is the certificate.
|
|
255
257
|
- Policy over provenance: the gateway looks up the fact a write supersedes or a retraction targets, so policy decides on its space, actor, and provenance; a claimed fact can be displaced, an attested org fact cannot.
|
|
256
258
|
- Consumed facts and blast radius: the memory server declares the facts it serves, the gateway records them on every later receipt, and `blast` walks from a fact to every downstream call and derived belief, transitively, with its retraction status.
|
package/dist/blast.d.ts
CHANGED
|
@@ -5,11 +5,15 @@ export interface ReceiptSummary {
|
|
|
5
5
|
timestamp: string;
|
|
6
6
|
tool: string;
|
|
7
7
|
status: string;
|
|
8
|
-
/** fact ids the agent had been shown before this call, from the receipt's consumed field */
|
|
8
|
+
/** fact ids the agent had been shown before this call, from the receipt's consumed field; empty when none, or when they are withheld */
|
|
9
9
|
consumed: string[];
|
|
10
|
+
/** true when the receipt withholds the consumed ids under a capture rule and no key brought them back: the call may depend on any fact, and the query cannot tell */
|
|
11
|
+
consumedWithheld: boolean;
|
|
10
12
|
}
|
|
11
|
-
/** Reads every bundle in a receipts directory. Order is by timestamp. */
|
|
12
|
-
export declare function loadReceipts(dir: string
|
|
13
|
+
/** Reads every bundle in a receipts directory. Order is by timestamp. With the capture key, withheld consumed ids are decrypted; otherwise a receipt that withholds them is marked, not treated as having consumed nothing. */
|
|
14
|
+
export declare function loadReceipts(dir: string, opts?: {
|
|
15
|
+
captureKey?: Buffer;
|
|
16
|
+
}): ReceiptSummary[];
|
|
13
17
|
export interface BlastRadius {
|
|
14
18
|
fact: Fact | null;
|
|
15
19
|
/** every receipt for a call made after the agent had been shown this fact or one derived from it */
|
|
@@ -20,6 +24,8 @@ export interface BlastRadius {
|
|
|
20
24
|
retraction: RetractEvent | null;
|
|
21
25
|
/** derived facts that are still believed; the ones a cleanup has to decide about */
|
|
22
26
|
stillBelieved: Fact[];
|
|
27
|
+
/** receipts made since the ledger learned the fact (its assert's transaction time) whose consumed ids are withheld: each may depend on it, and the sets above are incomplete while any is listed */
|
|
28
|
+
withheld: ReceiptSummary[];
|
|
23
29
|
}
|
|
24
30
|
export declare function blastRadius(ledger: Ledger, receipts: ReceiptSummary[], factId: string): Promise<BlastRadius>;
|
|
25
31
|
export declare function formatBlastRadius(b: BlastRadius, factId: string): string;
|
package/dist/blast.js
CHANGED
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
// downstream action and every derived belief, transitively, and the retraction that undoes the belief if there is one.
|
|
4
4
|
import { readdirSync, readFileSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
import { restorePaths } from "@agent-custody/receipts";
|
|
7
|
+
/** Reads every bundle in a receipts directory. Order is by timestamp. With the capture key, withheld consumed ids are decrypted; otherwise a receipt that withholds them is marked, not treated as having consumed nothing. */
|
|
8
|
+
export function loadReceipts(dir, opts = {}) {
|
|
8
9
|
const out = [];
|
|
9
10
|
for (const f of readdirSync(dir)) {
|
|
10
|
-
|
|
11
|
+
// the authorization committed before a pre-committed call carries the same call: the receipt is the record
|
|
12
|
+
if (!f.endsWith(".json") || f.endsWith(".authorization.json"))
|
|
11
13
|
continue;
|
|
12
14
|
const bundle = JSON.parse(readFileSync(join(dir, f), "utf8"));
|
|
13
15
|
if (!bundle.envelope?.payload)
|
|
@@ -16,7 +18,16 @@ export function loadReceipts(dir) {
|
|
|
16
18
|
const p = st.predicate;
|
|
17
19
|
if (!p?.receiptId)
|
|
18
20
|
continue;
|
|
19
|
-
|
|
21
|
+
let ids = p.consumed?.factIds;
|
|
22
|
+
let consumedWithheld = false;
|
|
23
|
+
if (p.consumed && !Array.isArray(ids)) {
|
|
24
|
+
const back = opts.captureKey ? restorePaths(p, p.capture, undefined, opts.captureKey).predicate : null;
|
|
25
|
+
if (Array.isArray(back?.consumed?.factIds))
|
|
26
|
+
ids = back.consumed.factIds;
|
|
27
|
+
else
|
|
28
|
+
consumedWithheld = true;
|
|
29
|
+
}
|
|
30
|
+
out.push({ receiptId: p.receiptId, timestamp: p.timestamp, tool: p.tool?.name ?? "?", status: p.execution?.status ?? "?", consumed: Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [], consumedWithheld });
|
|
20
31
|
}
|
|
21
32
|
return out.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
22
33
|
}
|
|
@@ -44,9 +55,16 @@ export async function blastRadius(ledger, receipts, factId) {
|
|
|
44
55
|
grew = true;
|
|
45
56
|
}
|
|
46
57
|
}
|
|
47
|
-
const
|
|
58
|
+
const history = await ledger.history(factId);
|
|
59
|
+
const retraction = history.find((e) => e.kind === "retract") ?? null;
|
|
48
60
|
const derivedFacts = [...derived.values()];
|
|
49
|
-
|
|
61
|
+
const fact = byId.get(factId) ?? null;
|
|
62
|
+
// What the query cannot see: a call whose consumed ids are withheld, made once the ledger knew the fact, may have
|
|
63
|
+
// relied on it. The bound is the assert's transaction time, never validFrom: a fact valid from tomorrow is readable
|
|
64
|
+
// today (memory.read with validAt), so a call today may already have consumed it. Unknown, no bound at all.
|
|
65
|
+
const known = history.find((e) => e.kind === "assert")?.txTime;
|
|
66
|
+
const withheld = receipts.filter((r) => r.consumedWithheld && !hit.has(r.receiptId) && (!known || r.timestamp >= known));
|
|
67
|
+
return { fact, receipts: [...hit.values()].sort((a, b) => a.timestamp.localeCompare(b.timestamp)), derivedFacts, retraction, stillBelieved: derivedFacts.filter((f) => believed.has(f.factId)), withheld };
|
|
50
68
|
}
|
|
51
69
|
export function formatBlastRadius(b, factId) {
|
|
52
70
|
const lines = [];
|
|
@@ -58,5 +76,10 @@ export function formatBlastRadius(b, factId) {
|
|
|
58
76
|
lines.push(`${b.derivedFacts.length} belief(s) written in those calls, ${b.stillBelieved.length} still believed:`);
|
|
59
77
|
for (const f of b.derivedFacts)
|
|
60
78
|
lines.push(` ${f.subject} ${f.predicate} = ${JSON.stringify(f.value)} fact ${f.factId.slice(0, 8)} ${b.stillBelieved.includes(f) ? "STILL BELIEVED" : "no longer believed"}`);
|
|
79
|
+
if (b.withheld.length) {
|
|
80
|
+
lines.push(`INCOMPLETE: ${b.withheld.length} call(s) made since the ledger learned the fact withhold what the agent had been shown under a capture rule; each may depend on it, and so may beliefs written in them. Give the capture key to see.`);
|
|
81
|
+
for (const r of b.withheld)
|
|
82
|
+
lines.push(` ${r.timestamp} ${r.tool.padEnd(18)} ${r.status.padEnd(9)} receipt ${r.receiptId.slice(0, 8)} consumed ids withheld`);
|
|
83
|
+
}
|
|
61
84
|
return lines.join("\n");
|
|
62
85
|
}
|
package/dist/cli.js
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
import { parseArgs } from "node:util";
|
|
3
3
|
import { Ledger } from "./ledger.js";
|
|
4
4
|
import { createMemoryServer, serveStdio } from "./server.js";
|
|
5
|
+
import { captureKeyFrom } from "@agent-custody/receipts";
|
|
6
|
+
/** the capture key from the environment variable named, for queries over receipts under a capture rule; none when no variable is named */
|
|
7
|
+
const keyFromEnv = (name) => (name ? captureKeyFrom(process.env[name] ?? (() => { throw new Error(`${name} is not set`); })()) : undefined);
|
|
5
8
|
import { blastRadius, formatBlastRadius, loadReceipts } from "./blast.js";
|
|
6
9
|
import { serveMemoryHttp } from "./http.js";
|
|
7
10
|
import { loadPrivateKey, loadPublicKey, verifyBundle } from "@agent-custody/receipts";
|
|
@@ -44,8 +47,10 @@ const USAGE = `agent-custody-memory <command>
|
|
|
44
47
|
the memory server over stdio; run it as the receipts gateway's upstream.
|
|
45
48
|
--key signs every result for its receipt, so executions verify as attested by this server.
|
|
46
49
|
By default it refuses calls that did not come through the gateway.
|
|
47
|
-
serve --ledger <ledger.jsonl> --http [--port 8790] [--host 127.0.0.1]
|
|
48
|
-
the same server shared over HTTP: several gateways, one ledger.
|
|
50
|
+
serve --ledger <ledger.jsonl> --http [--port 8790] [--host 127.0.0.1] --token-env NAME [--allow-direct --direct-token-env NAME]
|
|
51
|
+
the same server shared over HTTP: several gateways, one ledger. --token-env is the
|
|
52
|
+
gateways' token; direct writers get their own under --direct-token-env and are never
|
|
53
|
+
believed about receipts or agents, whatever their calls carry.
|
|
49
54
|
A postgres:// ledger (needs the pg package; ?table=custody.events names the table)
|
|
50
55
|
is shared by every server pointed at it.
|
|
51
56
|
sweep --via <gateway.json> --reason <text> [--before <ISO instant>] [--space <space>] [--no-digest]
|
|
@@ -82,7 +87,7 @@ async function main(argv) {
|
|
|
82
87
|
const [cmd, ...rest] = argv;
|
|
83
88
|
switch (cmd) {
|
|
84
89
|
case "serve": {
|
|
85
|
-
const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, "allow-direct": { type: "boolean", default: false }, http: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "token-env": { type: "string" }, key: { type: "string" }, "forget-key-env": { type: "string" }, retention: { type: "string" } } });
|
|
90
|
+
const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, "allow-direct": { type: "boolean", default: false }, http: { type: "boolean", default: false }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "token-env": { type: "string" }, "direct-token-env": { type: "string" }, key: { type: "string" }, "forget-key-env": { type: "string" }, retention: { type: "string" } } });
|
|
86
91
|
if (!values.ledger)
|
|
87
92
|
throw new Error("serve needs --ledger");
|
|
88
93
|
const ledger = new Ledger(values.ledger, forgetKeyFrom(values["forget-key-env"]));
|
|
@@ -92,11 +97,18 @@ async function main(argv) {
|
|
|
92
97
|
const retention = values.retention ? parseRetention(values.retention) : undefined;
|
|
93
98
|
const common = { requireGateway: !values["allow-direct"], ...(identity ? { identity } : {}), ...(retention ? { retention } : {}) };
|
|
94
99
|
if (values.http) {
|
|
95
|
-
|
|
96
|
-
|
|
100
|
+
if (!values["token-env"])
|
|
101
|
+
throw new Error("serve --http needs --token-env: the gateways' token is what tells a gateway from any other caller");
|
|
102
|
+
const token = process.env[values["token-env"]];
|
|
103
|
+
if (!token)
|
|
97
104
|
throw new Error(`serve: environment variable ${values["token-env"]} is not set`);
|
|
98
|
-
const
|
|
99
|
-
|
|
105
|
+
const directToken = values["direct-token-env"] ? process.env[values["direct-token-env"]] : undefined;
|
|
106
|
+
if (values["direct-token-env"] && !directToken)
|
|
107
|
+
throw new Error(`serve: environment variable ${values["direct-token-env"]} is not set`);
|
|
108
|
+
if (values["allow-direct"] && !directToken)
|
|
109
|
+
throw new Error("serve --http --allow-direct needs --direct-token-env: direct writers present their own token, never the gateways'");
|
|
110
|
+
const running = await serveMemoryHttp(ledger, { port: Number(values.port), host: values.host, ...common, tokens: [token], ...(directToken ? { directTokens: [directToken] } : {}) });
|
|
111
|
+
console.error(`agent-custody-memory: ${running.url} ledger=${values.ledger} events=${await ledger.count()} gateway token required ${values["allow-direct"] ? "direct writers with their own token" : "gateway calls only"}`);
|
|
100
112
|
if (digestWarning)
|
|
101
113
|
console.error(digestWarning);
|
|
102
114
|
await new Promise((resolve) => process.once("SIGINT", resolve));
|
|
@@ -177,7 +189,7 @@ async function main(argv) {
|
|
|
177
189
|
return regressed ? 1 : 0;
|
|
178
190
|
}
|
|
179
191
|
case "pack": {
|
|
180
|
-
const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, receipts: { type: "string" }, fact: { type: "string" }, out: { type: "string" }, sign: { type: "string" }, verify: { type: "string" }, key: { type: "string", multiple: true }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, json: { type: "boolean", default: false } } });
|
|
192
|
+
const { values } = parseArgs({ args: rest, options: { "capture-key-env": { type: "string" }, ledger: { type: "string" }, receipts: { type: "string" }, fact: { type: "string" }, out: { type: "string" }, sign: { type: "string" }, verify: { type: "string" }, key: { type: "string", multiple: true }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, json: { type: "boolean", default: false } } });
|
|
181
193
|
if (values.verify) {
|
|
182
194
|
if (!values.key?.length)
|
|
183
195
|
throw new Error("pack --verify needs --key <pub>");
|
|
@@ -196,7 +208,7 @@ async function main(argv) {
|
|
|
196
208
|
if (!values.ledger || !values.receipts || !values.fact || !values.out || !values.sign)
|
|
197
209
|
throw new Error("pack needs --ledger, --receipts, --fact, --out, and --sign");
|
|
198
210
|
const packLedger = new Ledger(values.ledger);
|
|
199
|
-
const pack = await buildPack(packLedger, values.receipts, values.fact);
|
|
211
|
+
const pack = await buildPack(packLedger, values.receipts, values.fact, { captureKey: keyFromEnv(values["capture-key-env"]) });
|
|
200
212
|
await packLedger.close();
|
|
201
213
|
writeFileSync(values.out, JSON.stringify(signPack(pack, loadPrivateKey(values.sign)), null, 2));
|
|
202
214
|
console.log(formatPack(pack));
|
|
@@ -204,7 +216,7 @@ async function main(argv) {
|
|
|
204
216
|
return pack.missingReceipts.length ? 1 : 0;
|
|
205
217
|
}
|
|
206
218
|
case "explain": {
|
|
207
|
-
const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, receipts: { type: "string" }, receipt: { type: "string" }, out: { type: "string" }, sign: { type: "string" }, verify: { type: "string" }, key: { type: "string", multiple: true }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, "log-key": { type: "string", multiple: true }, json: { type: "boolean", default: false } } });
|
|
219
|
+
const { values } = parseArgs({ args: rest, options: { "capture-key-env": { type: "string" }, ledger: { type: "string" }, receipts: { type: "string" }, receipt: { type: "string" }, out: { type: "string" }, sign: { type: "string" }, verify: { type: "string" }, key: { type: "string", multiple: true }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, "log-key": { type: "string", multiple: true }, json: { type: "boolean", default: false } } });
|
|
208
220
|
const receiptKeys = values["issuer-key"]?.length ? { issuerKeys: values["issuer-key"].map(loadPublicKey), principalKeys: (values["principal-key"] ?? []).map(loadPublicKey), ...(values["log-key"]?.length ? { logKeys: values["log-key"].map(loadPublicKey) } : {}) } : undefined;
|
|
209
221
|
if (values.verify) {
|
|
210
222
|
if (!values.key?.length)
|
|
@@ -224,7 +236,7 @@ async function main(argv) {
|
|
|
224
236
|
if (!values.receipts || !values.receipt)
|
|
225
237
|
throw new Error("explain needs --receipts and --receipt, or --verify");
|
|
226
238
|
const ledger = values.ledger ? new Ledger(values.ledger) : undefined;
|
|
227
|
-
const pack = await buildActionPack(values.receipts, values.receipt, ledger);
|
|
239
|
+
const pack = await buildActionPack(values.receipts, values.receipt, ledger, { captureKey: keyFromEnv(values["capture-key-env"]) });
|
|
228
240
|
await ledger?.close();
|
|
229
241
|
const verification = receiptKeys ? verifyBundle(pack.receipt, receiptKeys) : null;
|
|
230
242
|
if (values.out) {
|
|
@@ -271,11 +283,12 @@ async function main(argv) {
|
|
|
271
283
|
return 0;
|
|
272
284
|
}
|
|
273
285
|
case "blast": {
|
|
274
|
-
const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, receipts: { type: "string" }, fact: { type: "string" }, json: { type: "boolean", default: false } } });
|
|
286
|
+
const { values } = parseArgs({ args: rest, options: { ledger: { type: "string" }, receipts: { type: "string" }, fact: { type: "string" }, "capture-key-env": { type: "string" }, json: { type: "boolean", default: false } } });
|
|
275
287
|
if (!values.ledger || !values.receipts || !values.fact)
|
|
276
|
-
throw new Error("blast needs --ledger, --receipts, and --fact");
|
|
288
|
+
throw new Error("blast needs --ledger, --receipts, and --fact [--capture-key-env NAME]");
|
|
277
289
|
const blastLedger = new Ledger(values.ledger);
|
|
278
|
-
|
|
290
|
+
// receipts under a capture rule withhold what the agent had been shown; the key brings it back, else the query says it is incomplete
|
|
291
|
+
const b = await blastRadius(blastLedger, loadReceipts(values.receipts, { captureKey: keyFromEnv(values["capture-key-env"]) }), values.fact);
|
|
279
292
|
await blastLedger.close();
|
|
280
293
|
console.log(values.json ? JSON.stringify(b, null, 2) : formatBlastRadius(b, values.fact));
|
|
281
294
|
return b.fact ? 0 : 1;
|
package/dist/explain.d.ts
CHANGED
|
@@ -17,11 +17,14 @@ export interface ActionPack {
|
|
|
17
17
|
written: Fact[];
|
|
18
18
|
/** what each written belief is today */
|
|
19
19
|
status: Record<string, "believed" | "retracted" | "forgotten" | "superseded">;
|
|
20
|
-
/**
|
|
20
|
+
/** true when the receipt withholds the ids of the beliefs shown before the call under a capture rule and no key opened them: `consumed` is then empty for want of seeing, not for want of beliefs */
|
|
21
|
+
consumedWithheld: boolean;
|
|
22
|
+
/** everything downstream of the written beliefs: later calls that consumed them and beliefs derived, transitively; `withheld` lists later calls whose consumed ids a capture rule withholds, each of which may depend on them, so the other sets are incomplete while it is not empty */
|
|
21
23
|
downstream: {
|
|
22
24
|
receipts: ReceiptSummary[];
|
|
23
25
|
derivedFacts: Fact[];
|
|
24
26
|
stillBelieved: Fact[];
|
|
27
|
+
withheld: ReceiptSummary[];
|
|
25
28
|
};
|
|
26
29
|
/** every receipt cited by the downstream walk, by id, as the full bundle */
|
|
27
30
|
receipts: Record<string, ReceiptBundle>;
|
|
@@ -32,7 +35,9 @@ export declare const decodeStatement: (b: ReceiptBundle) => ReceiptStatement;
|
|
|
32
35
|
* Builds the pack. Without a ledger the receipt is explained on its own and the belief questions are answered as
|
|
33
36
|
* unknown rather than as nothing, so a reader can tell "nothing depended on it" from "nobody looked".
|
|
34
37
|
*/
|
|
35
|
-
export declare function buildActionPack(receiptsDir: string, receiptId: string, ledger?: Ledger
|
|
38
|
+
export declare function buildActionPack(receiptsDir: string, receiptId: string, ledger?: Ledger, opts?: {
|
|
39
|
+
captureKey?: Buffer;
|
|
40
|
+
}): Promise<ActionPack>;
|
|
36
41
|
export declare function signActionPack(pack: ActionPack, key: KeyPair): Envelope;
|
|
37
42
|
export interface ActionPackCheck {
|
|
38
43
|
name: string;
|
package/dist/explain.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { digestOf, dsseSign, dsseVerify, verifyBundle } from "@agent-custody/receipts";
|
|
9
|
+
import { restorePaths } from "@agent-custody/receipts";
|
|
9
10
|
import { blastRadius, loadReceipts } from "./blast.js";
|
|
10
11
|
export const ACTION_PACK_TYPE = "https://agent-custody.dev/action-pack/v0.1";
|
|
11
12
|
export const decodeStatement = (b) => JSON.parse(Buffer.from(b.envelope.payload, "base64").toString());
|
|
@@ -16,14 +17,17 @@ function loadBundle(receiptsDir, receiptId) {
|
|
|
16
17
|
* Builds the pack. Without a ledger the receipt is explained on its own and the belief questions are answered as
|
|
17
18
|
* unknown rather than as nothing, so a reader can tell "nothing depended on it" from "nobody looked".
|
|
18
19
|
*/
|
|
19
|
-
export async function buildActionPack(receiptsDir, receiptId, ledger) {
|
|
20
|
+
export async function buildActionPack(receiptsDir, receiptId, ledger, opts = {}) {
|
|
20
21
|
const receipt = loadBundle(receiptsDir, receiptId);
|
|
21
22
|
const p = decodeStatement(receipt).predicate;
|
|
22
|
-
|
|
23
|
+
// under a capture rule the ids are a commitment in the receipt: the key brings them back; without it there is nothing to look up, and the explanation says so
|
|
24
|
+
const opened = !Array.isArray(p.consumed?.factIds) && opts.captureKey ? restorePaths(p, p.capture, undefined, opts.captureKey).predicate.consumed?.factIds : undefined;
|
|
25
|
+
const consumedIds = Array.isArray(p.consumed?.factIds) ? p.consumed.factIds : Array.isArray(opened) ? opened.filter((id) => typeof id === "string") : [];
|
|
26
|
+
const consumedWithheld = !!p.consumed && !Array.isArray(p.consumed.factIds) && !Array.isArray(opened);
|
|
23
27
|
const consumed = { facts: [], unknown: [] };
|
|
24
28
|
const written = [];
|
|
25
29
|
const status = {};
|
|
26
|
-
const downstream = { receipts: [], derivedFacts: [], stillBelieved: [] };
|
|
30
|
+
const downstream = { receipts: [], derivedFacts: [], stillBelieved: [], withheld: [] };
|
|
27
31
|
const receipts = {};
|
|
28
32
|
const missingReceipts = [];
|
|
29
33
|
if (ledger) {
|
|
@@ -37,8 +41,9 @@ export async function buildActionPack(receiptsDir, receiptId, ledger) {
|
|
|
37
41
|
for (const f of await ledger.facts())
|
|
38
42
|
if (f.source.receiptId === receiptId)
|
|
39
43
|
written.push(f);
|
|
40
|
-
const summaries = loadReceipts(receiptsDir);
|
|
44
|
+
const summaries = loadReceipts(receiptsDir, opts);
|
|
41
45
|
const seenReceipts = new Map();
|
|
46
|
+
const seenWithheld = new Map();
|
|
42
47
|
const seenFacts = new Map();
|
|
43
48
|
const believed = new Set();
|
|
44
49
|
for (const f of written) {
|
|
@@ -47,6 +52,8 @@ export async function buildActionPack(receiptsDir, receiptId, ledger) {
|
|
|
47
52
|
const b = await blastRadius(ledger, summaries, f.factId);
|
|
48
53
|
for (const r of b.receipts)
|
|
49
54
|
seenReceipts.set(r.receiptId, r);
|
|
55
|
+
for (const r of b.withheld)
|
|
56
|
+
seenWithheld.set(r.receiptId, r);
|
|
50
57
|
for (const d of b.derivedFacts)
|
|
51
58
|
seenFacts.set(d.factId, d);
|
|
52
59
|
for (const s of b.stillBelieved)
|
|
@@ -55,6 +62,7 @@ export async function buildActionPack(receiptsDir, receiptId, ledger) {
|
|
|
55
62
|
downstream.receipts = [...seenReceipts.values()].sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
56
63
|
downstream.derivedFacts = [...seenFacts.values()];
|
|
57
64
|
downstream.stillBelieved = downstream.derivedFacts.filter((f) => believed.has(f.factId));
|
|
65
|
+
downstream.withheld = [...seenWithheld.values()].filter((r) => !seenReceipts.has(r.receiptId)).sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
58
66
|
const wanted = new Set([...downstream.receipts.map((r) => r.receiptId), ...downstream.derivedFacts.map((f) => f.source.receiptId).filter((x) => !!x)]);
|
|
59
67
|
for (const id of [...wanted].sort()) {
|
|
60
68
|
try {
|
|
@@ -68,7 +76,7 @@ export async function buildActionPack(receiptsDir, receiptId, ledger) {
|
|
|
68
76
|
else {
|
|
69
77
|
consumed.unknown.push(...consumedIds);
|
|
70
78
|
}
|
|
71
|
-
return { version: "0.1", generatedAt: new Date().toISOString(), receiptId, receipt, consumed, written, status, downstream, receipts, missingReceipts };
|
|
79
|
+
return { version: "0.1", generatedAt: new Date().toISOString(), receiptId, receipt, consumed, consumedWithheld, written, status, downstream, receipts, missingReceipts };
|
|
72
80
|
}
|
|
73
81
|
export function signActionPack(pack, key) {
|
|
74
82
|
const statement = { _type: "https://in-toto.io/Statement/v1", subject: [{ name: `action-pack:${pack.receiptId}`, digest: { sha256: digestOf(pack) } }], predicateType: ACTION_PACK_TYPE, predicate: pack };
|
|
@@ -133,24 +141,30 @@ export function formatExplain(pack, verification, withLedger) {
|
|
|
133
141
|
else
|
|
134
142
|
row("WHO AUTHORIZED IT", `${p.principal.id ?? "nobody named"} (claimed; no signed grant)`);
|
|
135
143
|
row("WHAT WAS ALLOWED", d?.scopes ? `tools ${d.scopes.join(", ")}` : "no grant in this receipt");
|
|
144
|
+
// under a capture rule a message is a commitment in the receipt; the explanation says so rather than printing it
|
|
145
|
+
const text = (v) => (typeof v === "string" ? v : "(withheld under the capture rule)");
|
|
146
|
+
const errors = Array.isArray(p.policy?.errors) ? p.policy.errors : p.policy?.errors ? [text(p.policy.errors)] : [];
|
|
136
147
|
if (p.policy)
|
|
137
|
-
more(`policy ${p.policy.policyDigest.slice(0, 12)} decided ${p.policy.decision}${p.policy.reasons.length ? ` by ${p.policy.reasons.join(", ")}` : ""}${
|
|
148
|
+
more(`policy ${p.policy.policyDigest.slice(0, 12)} decided ${p.policy.decision}${p.policy.reasons.length ? ` by ${p.policy.reasons.join(", ")}` : ""}${errors.length ? `; errors: ${errors.join("; ")}` : ""}`);
|
|
138
149
|
const facts = Object.entries(p.facts);
|
|
139
150
|
row("WHAT THE AGENT SAW", facts.length ? facts.map(([k, f]) => `${k} = ${JSON.stringify(f.value)} (fetched by the gateway via ${f.tool})`).join("; ") : "no facts fetched for this call");
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
151
|
+
// from the pack, not the receipt: under a capture rule the receipt holds a commitment, and the pack holds what the key opened
|
|
152
|
+
const shown = pack.consumed.facts.length + pack.consumed.unknown.length;
|
|
153
|
+
if (pack.consumedWithheld)
|
|
154
|
+
more("the beliefs shown before this call are withheld under the capture rule; give the capture key to see them");
|
|
155
|
+
else if (!withLedger)
|
|
156
|
+
more(shown ? `${shown} belief(s) shown before this call; open with a ledger to see them` : "no beliefs shown before this call");
|
|
157
|
+
else if (shown === 0)
|
|
144
158
|
more("no beliefs shown before this call");
|
|
145
159
|
else {
|
|
146
|
-
more(`${shown
|
|
160
|
+
more(`${shown} belief(s) shown before this call:`);
|
|
147
161
|
for (const f of pack.consumed.facts)
|
|
148
162
|
more(` ${factLine(f)}`);
|
|
149
163
|
for (const id of pack.consumed.unknown)
|
|
150
164
|
more(` ${id.slice(0, 8)} (not in this ledger)`);
|
|
151
165
|
}
|
|
152
|
-
row("WHAT IT DID", `${p.tool.name} ${JSON.stringify(p.request.args)} -> ${p.execution.status}${p.execution.status === "denied" ? `: ${p.execution.reason}` : p.execution.status === "withheld" ? `: ${p.execution.reason}` : p.execution.status === "error" ? `: ${p.execution.error}` : ""}`);
|
|
153
|
-
row("WHY", p.policy ? (p.policy.decision === "allow" ? `the policy permitted it${p.policy.reasons.length ? ` (${p.policy.reasons.join(", ")})` : ""}` : p.policy.enforced === false ? `the policy would have refused it, and was in observe mode, so the call went through: ${[...p.policy.reasons, ...
|
|
166
|
+
row("WHAT IT DID", `${p.tool.name} ${JSON.stringify(p.request.args)} -> ${p.execution.status}${p.execution.status === "denied" ? `: ${text(p.execution.reason)}` : p.execution.status === "withheld" ? `: ${text(p.execution.reason)}` : p.execution.status === "error" ? `: ${text(p.execution.error)}` : ""}`);
|
|
167
|
+
row("WHY", p.policy ? (p.policy.decision === "allow" ? `the policy permitted it${p.policy.reasons.length ? ` (${p.policy.reasons.join(", ")})` : ""}` : p.policy.enforced === false ? `the policy would have refused it, and was in observe mode, so the call went through: ${[...p.policy.reasons, ...errors].join("; ") || "no permit matched"}` : `the policy refused it: ${[...p.policy.reasons, ...errors].join("; ") || "no permit matched"}`) : "no policy was evaluated");
|
|
154
168
|
const th = pack.receipt.treeHead.signatures[0]?.keyid ?? "?";
|
|
155
169
|
row("WHAT EVIDENCE", `receipt ${p.receiptId}, leaf ${pack.receipt.inclusion.leafIndex} of a log whose head is signed by ${th.slice(0, 12)}`);
|
|
156
170
|
if (p.authorization)
|
|
@@ -172,6 +186,11 @@ export function formatExplain(pack, verification, withLedger) {
|
|
|
172
186
|
more(` wrote ${factLine(f)}: ${pack.status[f.factId]}`);
|
|
173
187
|
for (const r of pack.downstream.receipts)
|
|
174
188
|
more(` then ${r.timestamp} ${r.tool} ${r.status} (receipt ${r.receiptId.slice(0, 8)})`);
|
|
189
|
+
if (pack.downstream.withheld?.length) {
|
|
190
|
+
more(` INCOMPLETE: ${pack.downstream.withheld.length} later call(s) withhold what the agent had been shown under a capture rule; each may depend on these beliefs. Give the capture key to see.`);
|
|
191
|
+
for (const r of pack.downstream.withheld)
|
|
192
|
+
more(` maybe ${r.timestamp} ${r.tool} ${r.status} (receipt ${r.receiptId.slice(0, 8)}, consumed ids withheld)`);
|
|
193
|
+
}
|
|
175
194
|
}
|
|
176
195
|
const open = [...w.filter((f) => pack.status[f.factId] === "believed"), ...pack.downstream.stillBelieved];
|
|
177
196
|
if (open.length === 0)
|
package/dist/http.d.ts
CHANGED
|
@@ -4,8 +4,10 @@ import { type MemoryServerOptions } from "./server.ts";
|
|
|
4
4
|
export interface MemoryHttpOptions extends MemoryServerOptions {
|
|
5
5
|
port: number;
|
|
6
6
|
host?: string;
|
|
7
|
-
/** bearer tokens
|
|
8
|
-
tokens
|
|
7
|
+
/** the gateways' bearer tokens: a caller presenting one is believed about receipts, agents, and observed facts. At least one is required; a server without one would take any caller for a gateway. */
|
|
8
|
+
tokens: string[];
|
|
9
|
+
/** direct writers' bearer tokens: a caller presenting one is a direct writer, its `_meta` is dropped, and what it writes is claimed. Required when `requireGateway` is false. */
|
|
10
|
+
directTokens?: string[];
|
|
9
11
|
}
|
|
10
12
|
export interface RunningMemoryServer {
|
|
11
13
|
url: string;
|
package/dist/http.js
CHANGED
|
@@ -1,27 +1,46 @@
|
|
|
1
1
|
// The memory server over HTTP: one ledger shared by several gateways and, if allowed, direct writers. This is what
|
|
2
2
|
// makes quarantine a live deployment: attested writes arrive through gateways, self-reported ones directly, and the
|
|
3
3
|
// ledger tells them apart. Stateless Streamable HTTP, one MCP server instance per request over the shared ledger.
|
|
4
|
+
//
|
|
5
|
+
// The two kinds of caller hold different tokens, and the token decides what the server believes. A caller with a
|
|
6
|
+
// gateway token is a gateway: its `_meta` (receipt id, agent, observed facts) is what makes a write attested or
|
|
7
|
+
// verified, and is believed. A caller with a direct token is a direct writer: its `_meta` is dropped before the
|
|
8
|
+
// server looks at it, so it can claim a fact but never attest one, whatever it puts in the call. A direct writer is
|
|
9
|
+
// therefore never given the gateway's token.
|
|
4
10
|
import { timingSafeEqual } from "node:crypto";
|
|
5
11
|
import { createServer } from "node:http";
|
|
6
12
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
7
13
|
import { createMemoryServer } from "./server.js";
|
|
8
14
|
export function memoryHttpHandler(ledger, opts) {
|
|
9
15
|
const tokens = opts.tokens ?? [];
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
16
|
+
const directTokens = opts.directTokens ?? [];
|
|
17
|
+
if (tokens.length === 0)
|
|
18
|
+
throw new Error("memory server: a gateway token is required (tokens); without one, any caller that reaches the port could name its own receipt and agent");
|
|
19
|
+
if (opts.requireGateway === false && directTokens.length === 0)
|
|
20
|
+
throw new Error("memory server: direct writers need their own tokens (directTokens); a direct writer holding a gateway token could attest its own writes");
|
|
21
|
+
if (tokens.some((t) => directTokens.includes(t)))
|
|
22
|
+
throw new Error("memory server: a token cannot be both a gateway token and a direct token");
|
|
23
|
+
const matches = (list, given) => list.some((t) => Buffer.from(t).length === given.length && timingSafeEqual(Buffer.from(t), given));
|
|
24
|
+
/** Which kind of caller this is, by the token it presented; null when it presented none that is known. */
|
|
25
|
+
const callerOf = (req) => {
|
|
13
26
|
const h = req.headers.authorization ?? "";
|
|
14
27
|
const given = Buffer.from(h.startsWith("Bearer ") ? h.slice(7) : "");
|
|
15
|
-
|
|
28
|
+
if (matches(tokens, given))
|
|
29
|
+
return "gateway";
|
|
30
|
+
if (matches(directTokens, given))
|
|
31
|
+
return "direct";
|
|
32
|
+
return null;
|
|
16
33
|
};
|
|
17
34
|
return async (req, res) => {
|
|
18
|
-
|
|
35
|
+
const caller = callerOf(req);
|
|
36
|
+
if (!caller) {
|
|
19
37
|
res.writeHead(401, { "content-type": "application/json" });
|
|
20
38
|
res.end(JSON.stringify({ error: "unauthorized" }));
|
|
21
39
|
return;
|
|
22
40
|
}
|
|
23
41
|
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
24
|
-
|
|
42
|
+
// A direct writer's _meta is dropped: with requireGateway it is then refused outright, without it its writes are claimed.
|
|
43
|
+
const server = createMemoryServer(ledger, { ...opts, trustMeta: caller === "gateway" });
|
|
25
44
|
res.on("close", () => {
|
|
26
45
|
void transport.close();
|
|
27
46
|
void server.close();
|
|
@@ -31,7 +50,7 @@ export function memoryHttpHandler(ledger, opts) {
|
|
|
31
50
|
};
|
|
32
51
|
}
|
|
33
52
|
/** Starts the memory server over HTTP. Port 0 picks a free port. Host defaults to loopback; bind wider only behind auth. */
|
|
34
|
-
export function serveMemoryHttp(ledger, opts) {
|
|
53
|
+
export async function serveMemoryHttp(ledger, opts) {
|
|
35
54
|
const host = opts.host ?? "127.0.0.1";
|
|
36
55
|
const handler = memoryHttpHandler(ledger, opts);
|
|
37
56
|
const server = createServer((req, res) => {
|
package/dist/pack.d.ts
CHANGED
|
@@ -24,7 +24,9 @@ export interface CustodyPack {
|
|
|
24
24
|
/** hold and release events, in order */
|
|
25
25
|
holds: LedgerEvent[];
|
|
26
26
|
}
|
|
27
|
-
export declare function buildPack(ledger: Ledger, receiptsDir: string, factId: string
|
|
27
|
+
export declare function buildPack(ledger: Ledger, receiptsDir: string, factId: string, opts?: {
|
|
28
|
+
captureKey?: Buffer;
|
|
29
|
+
}): Promise<CustodyPack>;
|
|
28
30
|
export declare function signPack(pack: CustodyPack, key: KeyPair): Envelope;
|
|
29
31
|
export interface PackCheck {
|
|
30
32
|
name: string;
|
package/dist/pack.js
CHANGED
|
@@ -41,10 +41,10 @@ function receiptResult(bundle) {
|
|
|
41
41
|
return null; // a damaged bundle; the receipt check reports it
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
export async function buildPack(ledger, receiptsDir, factId) {
|
|
44
|
+
export async function buildPack(ledger, receiptsDir, factId, opts = {}) {
|
|
45
45
|
const bundles = loadBundles(receiptsDir);
|
|
46
46
|
const history = await ledger.history(factId);
|
|
47
|
-
const blast = await blastRadius(ledger, loadReceipts(receiptsDir), factId);
|
|
47
|
+
const blast = await blastRadius(ledger, loadReceipts(receiptsDir, opts), factId);
|
|
48
48
|
const wanted = new Set();
|
|
49
49
|
for (const e of history) {
|
|
50
50
|
const src = e.kind === "assert" ? e.fact.source.receiptId : e.source.receiptId;
|
|
@@ -143,6 +143,6 @@ export function formatPack(p) {
|
|
|
143
143
|
lines.push(`holds: ${p.holds.map((e) => (e.kind === "hold" || e.kind === "release" ? `${e.kind} by ${e.actor} (${e.reason})` : e.kind)).join("; ")}`);
|
|
144
144
|
if (p.forget)
|
|
145
145
|
lines.push(`forgotten at ${p.forget.event.txTime} by ${p.forget.event.actor}; receipt ${p.forget.receiptId?.slice(0, 8) ?? "none"}; stores: ${p.forget.verification ? Object.entries(p.forget.verification).map(([k, v]) => `${k}=${v}`).join(", ") : "none"}`);
|
|
146
|
-
lines.push(`blast radius: ${p.blast.receipts.length} later call(s), ${p.blast.derivedFacts.length} derived belief(s), ${p.blast.stillBelieved.length} still believed`);
|
|
146
|
+
lines.push(`blast radius: ${p.blast.receipts.length} later call(s), ${p.blast.derivedFacts.length} derived belief(s), ${p.blast.stillBelieved.length} still believed${p.blast.withheld?.length ? `; INCOMPLETE: ${p.blast.withheld.length} later call(s) withhold what the agent had been shown under a capture rule and may depend on it` : ""}`);
|
|
147
147
|
return lines.join("\n");
|
|
148
148
|
}
|
package/dist/server.d.ts
CHANGED
|
@@ -15,6 +15,14 @@ export declare const TOOLS: Tool[];
|
|
|
15
15
|
export interface MemoryServerOptions {
|
|
16
16
|
/** Refuse calls that did not come through the gateway, i.e. carry no receipt id. On by default when served from the CLI. */
|
|
17
17
|
requireGateway?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Believe the `_meta` the call carries: the receipt id, the agent, the principal, and the facts the gateway observed.
|
|
20
|
+
* Only the gateway may be believed, because those keys are what make a write attested or verified. Default: true
|
|
21
|
+
* exactly when `requireGateway` is not false, i.e. when the one caller is the gateway. A server that accepts direct
|
|
22
|
+
* writers must run with it false for them (the HTTP server does this per request, by which token the caller presented),
|
|
23
|
+
* so a direct writer's `_meta` is dropped and its write is claimed, whatever it says about itself.
|
|
24
|
+
*/
|
|
25
|
+
trustMeta?: boolean;
|
|
18
26
|
/** Retrieval stores every write goes through to and every retraction reaches. A store that refuses a write fails the write; nothing is recorded. */
|
|
19
27
|
stores?: Store[];
|
|
20
28
|
/** With a key, every result to a gateway call is signed for that receipt, so a verifier holding the public key sees the execution as attested by this server. */
|
package/dist/server.js
CHANGED
|
@@ -40,16 +40,18 @@ const Forget = z.object({ factId: z.string().min(1), reason: z.string().min(1),
|
|
|
40
40
|
const Hold = z.object({ factId: z.string().min(1), reason: z.string().min(1) });
|
|
41
41
|
const Sweep = z.object({ before: iso.optional(), space: z.string().min(1).optional(), reason: z.string().min(1), keepDigest: z.boolean().optional() });
|
|
42
42
|
const str = { type: "string" };
|
|
43
|
+
const isoStr = { type: "string", description: "an ISO 8601 date-time with a UTC offset, for example 2026-10-15T09:00:00Z" };
|
|
44
|
+
const actorStr = { type: "string", description: "who acts; ignored behind the gateway, which records the agent named in the signed grant" };
|
|
43
45
|
export const TOOLS = [
|
|
44
46
|
{
|
|
45
47
|
name: "memory.write",
|
|
46
48
|
description: "Record a belief: subject, predicate, value, in a space. Optionally supersede an earlier fact. With evidence naming a fact the gateway fetched for this call, the value must equal it (or the field at path) and the write is verified; otherwise it is refused. Returns the new fact with its id, transaction time, actor, provenance, and source receipt.",
|
|
47
|
-
inputSchema: { type: "object", properties: { subject: str, predicate: str, value: {}, space: str, actor:
|
|
49
|
+
inputSchema: { type: "object", properties: { subject: str, predicate: str, value: {}, space: str, actor: actorStr, validFrom: isoStr, confidence: { type: "number", minimum: 0, maximum: 1 }, supersedes: str, evidence: { type: "object", properties: { fact: str, path: str }, required: ["fact"] } }, required: ["subject", "predicate", "value", "space"] },
|
|
48
50
|
},
|
|
49
51
|
{
|
|
50
52
|
name: "memory.read",
|
|
51
53
|
description: "The facts believed at a moment. validAt asks whether a fact was true then; txAt asks whether the ledger knew it then. Both default to now. Filter by space, subject, predicate. Quarantined (claimed, unconfirmed) facts are left out unless includeClaimed is true; requireVerified returns only facts whose value the gateway checked against its source.",
|
|
52
|
-
inputSchema: { type: "object", properties: { subject: str, predicate: str, space: str, validAt:
|
|
54
|
+
inputSchema: { type: "object", properties: { subject: str, predicate: str, space: str, validAt: isoStr, txAt: isoStr, includeClaimed: { type: "boolean" }, requireVerified: { type: "boolean" } } },
|
|
53
55
|
},
|
|
54
56
|
{
|
|
55
57
|
name: "memory.confirm",
|
|
@@ -59,7 +61,7 @@ export const TOOLS = [
|
|
|
59
61
|
{
|
|
60
62
|
name: "memory.retract",
|
|
61
63
|
description: "Undo a belief: the fact leaves the present, stays visible to questions about the past, and whatever it superseded is believed again.",
|
|
62
|
-
inputSchema: { type: "object", properties: { factId: str, reason: str, actor:
|
|
64
|
+
inputSchema: { type: "object", properties: { factId: str, reason: str, actor: actorStr }, required: ["factId", "reason"] },
|
|
63
65
|
},
|
|
64
66
|
{
|
|
65
67
|
name: "memory.forget",
|
|
@@ -68,18 +70,18 @@ export const TOOLS = [
|
|
|
68
70
|
},
|
|
69
71
|
{
|
|
70
72
|
name: "memory.hold",
|
|
71
|
-
description: "
|
|
73
|
+
description: "Place a legal hold on a fact. While the hold stands, memory.forget refuses the fact and memory.sweep skips it. The reason is recorded with the hold event. Fails when the fact does not exist, is already forgotten, or is already on hold. Returns the hold event. Lift it with memory.release.",
|
|
72
74
|
inputSchema: { type: "object", properties: { factId: str, reason: str }, required: ["factId", "reason"] },
|
|
73
75
|
},
|
|
74
76
|
{
|
|
75
77
|
name: "memory.release",
|
|
76
|
-
description: "Lift
|
|
78
|
+
description: "Lift the legal hold on a fact, so that memory.forget and retention sweeps can reach it again. The reason is recorded with the release event. Fails when the fact is not on hold. Returns the release event.",
|
|
77
79
|
inputSchema: { type: "object", properties: { factId: str, reason: str }, required: ["factId", "reason"] },
|
|
78
80
|
},
|
|
79
81
|
{
|
|
80
82
|
name: "memory.sweep",
|
|
81
83
|
description: "Retention: forget every fact the ledger learned of before an instant, in one space or all, skipping held facts, and remove each from every store. Without `before`, the server's configured retention windows decide per space. The receipt is the record of the sweep.",
|
|
82
|
-
inputSchema: { type: "object", properties: { before:
|
|
84
|
+
inputSchema: { type: "object", properties: { before: isoStr, space: str, reason: str, keepDigest: { type: "boolean" } }, required: ["reason"] },
|
|
83
85
|
},
|
|
84
86
|
{
|
|
85
87
|
name: "memory.get",
|
|
@@ -88,7 +90,7 @@ export const TOOLS = [
|
|
|
88
90
|
},
|
|
89
91
|
{
|
|
90
92
|
name: "memory.history",
|
|
91
|
-
description: "Every event
|
|
93
|
+
description: "Every ledger event for one fact, oldest first: its assert, the assert that superseded it, and its confirm, retract, hold, release, and forget events. Returns { events }. Use it to see how a belief changed; use memory.read for what is believed now, and memory.get for one fact's current state.",
|
|
92
94
|
inputSchema: { type: "object", properties: { factId: str }, required: ["factId"] },
|
|
93
95
|
},
|
|
94
96
|
];
|
|
@@ -114,8 +116,10 @@ const fail = (msg) => ({ isError: true, content: [{ type: "text", text: msg }] }
|
|
|
114
116
|
export function createMemoryServer(ledger, opts = {}) {
|
|
115
117
|
const server = new Server({ name: "agent-custody-memory", version: SERVER_VERSION }, { capabilities: { tools: {} } });
|
|
116
118
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
119
|
+
const trustMeta = opts.trustMeta ?? opts.requireGateway !== false;
|
|
117
120
|
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
118
|
-
|
|
121
|
+
// A caller that is not the gateway gets no say in who it is or what was observed: its _meta is dropped whole.
|
|
122
|
+
const meta = trustMeta ? (req.params._meta ?? {}) : {};
|
|
119
123
|
const receiptId = typeof meta[RECEIPT_META_KEY] === "string" ? meta[RECEIPT_META_KEY] : null;
|
|
120
124
|
const result = await handle(req.params.name, req.params.arguments ?? {}, meta, receiptId);
|
|
121
125
|
return opts.identity && receiptId ? signResult(result, opts.identity, receiptId, req.params.name) : result;
|
|
@@ -165,14 +169,12 @@ export function createMemoryServer(ledger, opts = {}) {
|
|
|
165
169
|
}
|
|
166
170
|
return { removedFrom, stillHeld, verification };
|
|
167
171
|
}
|
|
168
|
-
async function forgetOne(factId, reason, keepDigest, compact = true) {
|
|
172
|
+
async function forgetOne(factId, reason, who, keepDigest, compact = true) {
|
|
169
173
|
const fact = await ledger.get(factId);
|
|
170
|
-
const ev = await ledger.forget({ factId, actor:
|
|
174
|
+
const ev = await ledger.forget({ factId, actor: who.actor, reason, source: { receiptId: who.receiptId }, ...(keepDigest === undefined ? {} : { keepDigest }), compact });
|
|
171
175
|
const { removedFrom, stillHeld, verification } = await removeFromStores(fact);
|
|
172
176
|
return { factId: ev.factId, valueDigest: ev.valueDigest, digestKind: ev.digestKind, txTime: ev.txTime, actor: ev.actor, reason: ev.reason, source: ev.source, erasedFromLedger: true, removedFrom, stillHeld, verification };
|
|
173
177
|
}
|
|
174
|
-
let currentActor = "anonymous";
|
|
175
|
-
let currentReceipt = null;
|
|
176
178
|
async function handle(name, args, meta, receiptId) {
|
|
177
179
|
const gatewayAgent = typeof meta[AGENT_META_KEY] === "string" ? meta[AGENT_META_KEY] : null;
|
|
178
180
|
if (opts.requireGateway && !receiptId)
|
|
@@ -181,8 +183,8 @@ export function createMemoryServer(ledger, opts = {}) {
|
|
|
181
183
|
// A write is attested when it came through the gateway: the actor is from a signed grant and the receipt exists.
|
|
182
184
|
const provenance = receiptId && gatewayAgent ? "attested" : "claimed";
|
|
183
185
|
const observed = (meta[OBSERVED_META_KEY] ?? {});
|
|
184
|
-
|
|
185
|
-
|
|
186
|
+
// Who this call is, carried as a value through the awaits below; never shared between concurrent calls.
|
|
187
|
+
const who = { actor: actorFor(undefined), receiptId };
|
|
186
188
|
try {
|
|
187
189
|
switch (name) {
|
|
188
190
|
case "memory.write": {
|
|
@@ -238,7 +240,7 @@ export function createMemoryServer(ledger, opts = {}) {
|
|
|
238
240
|
}
|
|
239
241
|
case "memory.forget": {
|
|
240
242
|
const a = Forget.parse(args);
|
|
241
|
-
const out = await forgetOne(a.factId, a.reason, a.keepDigest);
|
|
243
|
+
const out = await forgetOne(a.factId, a.reason, who, a.keepDigest);
|
|
242
244
|
if (out.stillHeld.length > 0)
|
|
243
245
|
return { isError: true, content: [{ type: "text", text: `erased from the ledger, but still held by ${out.stillHeld.join("; ")}` }, { type: "text", text: JSON.stringify(out) }] };
|
|
244
246
|
return json(out);
|
|
@@ -271,7 +273,7 @@ export function createMemoryServer(ledger, opts = {}) {
|
|
|
271
273
|
held.push(f.factId);
|
|
272
274
|
continue;
|
|
273
275
|
}
|
|
274
|
-
forgotten.push(await forgetOne(f.factId, a.reason, a.keepDigest, false));
|
|
276
|
+
forgotten.push(await forgetOne(f.factId, a.reason, who, a.keepDigest, false));
|
|
275
277
|
}
|
|
276
278
|
if (forgotten.length > 0)
|
|
277
279
|
await ledger.compact();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-custody/state",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Governed memory for AI agents: a fact ledger with provenance, valid time, rollback, lineage, certified forget, and a store that is a JSONL file, SQLite, or Postgres, built on @agent-custody/receipts",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"node": ">=22"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@agent-custody/receipts": "0.
|
|
36
|
+
"@agent-custody/receipts": "0.7.0",
|
|
37
37
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
38
38
|
"zod": "^4.5.4"
|
|
39
39
|
},
|