@agent-custody/state 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/review.js CHANGED
@@ -6,27 +6,46 @@
6
6
  import { readdirSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
7
7
  import { createServer } from "node:http";
8
8
  import { join } from "node:path";
9
- import { verifyBundle } from "@agent-custody/receipts";
9
+ import { createHash } from "node:crypto";
10
+ import { structuralProblem, verifyBundle } from "@agent-custody/receipts";
10
11
  import { buildActionPack, decodeStatement, formatExplain } from "./explain.js";
12
+ import { matchesReceiptSearch, receiptSearchTerms, validateReceiptSearch } from "./search.js";
13
+ import { buildCaseFile, renderCaseFile } from "./case-file.js";
14
+ const RECEIPT_ID = /^[0-9a-f-]{36}$/;
11
15
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
12
- /** Every receipt in the directory, newest first, with its verdict when keys were given. Damaged files are skipped. */
13
- export function listReceipts(o) {
16
+ /**
17
+ * Every receipt in the directory, newest first, with its verdict when keys were given. A record that does not match
18
+ * its file name is listed as NOT VERIFIED, never dropped. A file that cannot be decoded is counted in `unreadable`.
19
+ */
20
+ export function scanReceipts(o, query = o.search ?? {}) {
21
+ validateReceiptSearch(query);
14
22
  const rows = [];
23
+ let unreadable = 0;
15
24
  for (const f of readdirSync(o.receiptsDir)) {
16
25
  if (!f.endsWith(".json") || f.endsWith(".authorization.json"))
17
26
  continue;
18
27
  try {
19
28
  const bundle = JSON.parse(readFileSync(join(o.receiptsDir, f), "utf8"));
20
29
  const p = decodeStatement(bundle).predicate;
21
- const verified = o.keys ? verifyBundle(bundle, { issuerKeys: o.keys.issuerKeys, principalKeys: o.keys.principalKeys ?? [], ...(o.keys.logKeys ? { logKeys: o.keys.logKeys } : {}), ...(o.keys.logId ? { logId: o.keys.logId } : {}) }).ok : null;
22
- rows.push({ receiptId: p.receiptId, timestamp: p.timestamp, tool: p.tool.name, status: p.reconciliation ? "reconciled" : p.execution.status, agent: p.agent.id, principal: p.principal.id, issuer: p.issuer.kind, verified });
30
+ const terms = receiptSearchTerms(p);
31
+ if (!matchesReceiptSearch(p, query)) {
32
+ // A value that the search skipped may hold the id. Keep the row, marked, when only an id filter excludes it.
33
+ const { transaction: _transaction, customer: _customer, ...others } = query;
34
+ if (!terms.truncated || !matchesReceiptSearch(p, others))
35
+ continue;
36
+ }
37
+ const file = f.slice(0, -".json".length);
38
+ const problem = structuralProblem(p) ?? (file !== p.receiptId ? "file name does not match receipt id" : !RECEIPT_ID.test(file) ? "receipt id is malformed" : undefined);
39
+ const verified = problem ? false : verifyOf(bundle, o)?.ok ?? null;
40
+ rows.push({ receiptId: String(p.receiptId), timestamp: String(p.timestamp), tool: p.tool.name, status: p.reconciliation ? "reconciled" : p.execution.status, agent: p.agent.id, principal: p.principal.id, issuer: p.issuer.kind, verified, ...terms, file, ...(problem ? { problem } : {}) });
23
41
  }
24
42
  catch {
25
- // not a bundle; the index is of receipts
43
+ unreadable++;
26
44
  }
27
45
  }
28
- return rows.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
46
+ return { rows: rows.sort((a, b) => b.timestamp.localeCompare(a.timestamp)), unreadable };
29
47
  }
48
+ export const listReceipts = (o, query = o.search ?? {}) => scanReceipts(o, query).rows;
30
49
  const STYLE = `
31
50
  :root { color-scheme: light dark; --ink: #1b2430; --ink2: #5b6b7a; --line: #d7dfe5; --bg: #fafbfc; --panel: #ffffff; --accent: #0f6e63; --bad: #b3261e; --mono: ui-monospace, Menlo, monospace; }
32
51
  @media (prefers-color-scheme: dark) { :root { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #4fc3b0; --bad: #ff8a80; } }
@@ -45,27 +64,78 @@ const STYLE = `
45
64
  dd { margin: 0; white-space: pre-wrap; }
46
65
  .ok { color: var(--accent); font-weight: 600; } .bad { color: var(--bad); font-weight: 600; } .muted { color: var(--ink2); }
47
66
  .wrap { overflow-x: auto; }
67
+ form { display: flex; flex-wrap: wrap; gap: .8rem; padding: 1rem; border: 1px solid var(--line); margin-bottom: 1rem; }
68
+ label { display: grid; gap: .25rem; font-size: .85rem; }
69
+ input, button { font: inherit; padding: .45rem; color: var(--ink); background: var(--panel); border: 1px solid var(--line); border-radius: 3px; }
70
+ button { cursor: pointer; align-self: end; }
71
+ [hidden] { display: none !important; }
48
72
  @media (max-width: 40rem) { dl { grid-template-columns: 1fr; } }
49
73
  `;
50
- const page = (title, body) => `<!doctype html>
74
+ // Static exports filter their exported rows in the browser, including when opened from file://. Live pages use GET.
75
+ const SEARCH_SCRIPT = `
76
+ ${validateReceiptSearch.toString()}
77
+ const form = document.getElementById('receipt-search');
78
+ form.addEventListener('submit', (event) => {
79
+ event.preventDefault();
80
+ const value = (name) => form.elements.namedItem(name).value.trim();
81
+ const from = value('from'), to = value('to');
82
+ const error = document.getElementById('search-error');
83
+ try {
84
+ validateReceiptSearch({ ...(from ? { from } : {}), ...(to ? { to } : {}) });
85
+ } catch (problem) {
86
+ error.textContent = problem.message;
87
+ return;
88
+ }
89
+ error.textContent = '';
90
+ let count = 0;
91
+ for (const row of document.querySelectorAll('tbody tr')) {
92
+ const data = row.dataset;
93
+ const matches = (!value('transaction') || data.partial || JSON.parse(data.transactions).includes(value('transaction')))
94
+ && (!value('customer') || data.partial || JSON.parse(data.customers).includes(value('customer')))
95
+ && (!value('agent') || data.agent === value('agent'))
96
+ && (!from || Date.parse(data.timestamp) >= Date.parse(from))
97
+ && (!to || Date.parse(data.timestamp) <= Date.parse(to));
98
+ row.hidden = !matches;
99
+ if (matches) count++;
100
+ }
101
+ document.getElementById('receipt-count').textContent = count + ' receipt(s)';
102
+ document.getElementById('no-results').hidden = count !== 0;
103
+ });
104
+ form.addEventListener('reset', () => {
105
+ for (const input of form.querySelectorAll('input')) input.defaultValue = '';
106
+ queueMicrotask(() => form.requestSubmit());
107
+ });
108
+ `.replace(/\r\n?/g, "\n");
109
+ const REVIEW_CSP = `default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-${createHash("sha256").update(SEARCH_SCRIPT).digest("base64")}'; img-src data:; form-action 'self'; base-uri 'none'`;
110
+ const page = (title, body, script = "") => `<!doctype html>
51
111
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
52
- <meta http-equiv="content-security-policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:">
112
+ <meta http-equiv="content-security-policy" content="${esc(REVIEW_CSP)}">
53
113
  <title>${esc(title)}</title>
54
114
  <style>${STYLE}</style>
55
115
  <main>${body}</main>
116
+ ${script ? `<script>${script}</script>` : ""}
56
117
  `;
57
118
  /** The index: one row per receipt, newest first. */
58
- export function renderIndex(rows, o, link) {
119
+ export function renderIndex(rows, o, link, staticPage = false, unreadable = 0) {
59
120
  const withKeys = !!o.keys;
60
- const verdict = (r) => (r.verified === null ? '<span class="muted">not checked</span>' : r.verified ? '<span class="ok">verified</span>' : '<span class="bad">NOT VERIFIED</span>');
121
+ const verdict = (r) => (r.verified === null ? '<span class="muted">not checked</span>' : r.verified ? '<span class="ok">verified</span>' : `<span class="bad">NOT VERIFIED</span>${r.problem ? ` <span class="muted">(${esc(r.problem)})</span>` : ""}`);
122
+ // A tampered record can name any id inside. Only a file name that is a well formed id is a safe link target.
123
+ const receiptLink = (r) => (RECEIPT_ID.test(r.file) ? `<a class="mono" href="${esc(link(r.file))}">${esc(r.file.slice(0, 8))}</a>` : `<span class="mono">${esc(r.file.slice(0, 8))}</span>`);
61
124
  const body = `
62
125
  <h1>${esc(o.title ?? "Receipts")}</h1>
63
- <p class="sub">${rows.length} receipt(s) in ${esc(o.receiptsDir)}${withKeys ? ", each checked against the keys given" : ", not checked: start the review with the gateway's and principal's public keys to verify"}${o.ledger ? "; beliefs from the ledger" : "; no ledger, so what depended on a call is not known here"}.</p>
64
- <div class="wrap"><table><thead><tr><th>when</th><th>tool</th><th>outcome</th><th>agent</th><th>principal</th><th>producer</th><th>verification</th><th>receipt</th></tr></thead><tbody>
65
- ${rows.map((r) => `<tr><td>${esc(r.timestamp.replace("T", " ").slice(0, 19))}</td><td><code>${esc(r.tool)}</code></td><td>${esc(r.status)}</td><td>${esc(r.agent)}</td><td>${esc(r.principal ?? "")}</td><td>${esc(r.issuer)}</td><td>${verdict(r)}</td><td><a class="mono" href="${esc(link(r.receiptId))}">${esc(r.receiptId.slice(0, 8))}</a></td></tr>`).join("\n")}
126
+ <p class="sub"><span id="receipt-count">${rows.length} receipt(s)</span> in ${esc(o.receiptsDir)}${withKeys ? ", each checked against the keys given" : ", not checked: start the review with the gateway's and principal's public keys to verify"}${o.ledger ? "; beliefs from the ledger" : "; no ledger, so what depended on a call is not known here"}.</p>
127
+ ${unreadable ? `<p class="bad" role="alert">${unreadable} file(s) could not be read and are not in this list.</p>\n` : ""}<form id="receipt-search" method="get">
128
+ ${[['transaction', 'Transaction ID', 're_… / pi_… / charge ID'], ['customer', 'Customer ID', 'cust_…'], ['agent', 'Agent', 'support-agent'], ['from', 'From (inclusive)', '2026-10-14T00:00:00Z'], ['to', 'To (inclusive)', '2026-10-15T00:00:00Z']].map(([name, label, placeholder]) => `<label>${label}<input name="${name}" value="${esc(o.search?.[name] ?? "")}" placeholder="${placeholder}"${name === 'from' || name === 'to' ? ' pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T.+(Z|[+-][0-9]{2}:[0-9]{2})"' : ''}></label>`).join("\n")}
129
+ <button type="submit">Search receipts</button>${staticPage ? '<button type="reset">Clear filters</button>' : '<a href="/?transaction=&amp;customer=&amp;agent=&amp;from=&amp;to=">Clear filters</a>'}
130
+ </form>
131
+ <p class="muted">Filters combine and match exact IDs. Search covers public arguments, results and gateway facts; identifiers withheld by a capture rule are unavailable.${staticPage ? ' This export searches only the receipts included here.' : ''}</p>
132
+ <p id="search-error" role="alert" class="bad"></p>
133
+ <p id="no-results"${rows.length ? ' hidden' : ''}>No receipts match these filters.</p>
134
+ <div class="wrap"><table><thead><tr><th>when</th><th>tool</th><th>outcome</th><th>transaction</th><th>customer</th><th>agent</th><th>principal</th><th>producer</th><th>verification</th><th>receipt</th></tr></thead><tbody>
135
+ ${rows.map((r) => `<tr data-transactions="${esc(JSON.stringify(r.transactionIds))}" data-customers="${esc(JSON.stringify(r.customerIds))}" data-agent="${esc(r.agent)}" data-timestamp="${esc(r.timestamp)}"${r.truncated ? ' data-partial="1"' : ""}><td>${esc(r.timestamp.replace("T", " ").slice(0, 19))}</td><td><code>${esc(r.tool)}</code></td><td>${esc(r.status)}</td><td class="mono">${esc(r.transactionIds.join(', '))}${r.truncated ? ' <span class="muted">(partially indexed: a value was too large to search)</span>' : ""}</td><td class="mono">${esc(r.customerIds.join(', '))}</td><td>${esc(r.agent)}</td><td>${esc(r.principal ?? "")}</td><td>${esc(r.issuer)}</td><td>${verdict(r)}</td><td>${receiptLink(r)}</td></tr>`).join("\n")}
66
136
  </tbody></table></div>
67
137
  <p class="muted">A gateway receipt was enforced outside the agent's process; an SDK receipt is the agent's own report. The verification column is the offline check any auditor can repeat with the same public keys.</p>`;
68
- return page(o.title ?? "Receipts", body);
138
+ return page(o.title ?? "Receipts", body, staticPage ? SEARCH_SCRIPT : "");
69
139
  }
70
140
  /** The explain text as a definition list: question, answer, continuation lines kept with their answer. */
71
141
  function explainHtml(text) {
@@ -83,38 +153,91 @@ function explainHtml(text) {
83
153
  /** One receipt's page: the ten answers, the verification report, and the receipt itself. */
84
154
  export function renderReceipt(pack, verification, o, backLink, rawLink) {
85
155
  const p = decodeStatement(pack.receipt).predicate;
86
- const report = verification ? verification.checks.map((c) => `${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? ` (${c.detail})` : ""}`).join("\n") + `\n\nRESULT: ${verification.ok ? "VERIFIED" : "NOT VERIFIED"}` : "Not checked: start the review with --issuer-key and --principal-key to verify every receipt here.";
156
+ // pack.receiptId is the file name. A record that names another id inside was changed after it was issued.
157
+ const mismatch = pack.receiptId !== p.receiptId;
158
+ const failed = mismatch || (!!verification && !verification.ok);
159
+ const lines = [...(mismatch ? ["FAIL file name matches receipt id (file name does not match receipt id)"] : []), ...(verification ? verification.checks.map((c) => `${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? ` (${c.detail})` : ""}`) : [])];
160
+ const report = verification || mismatch ? `${lines.join("\n")}\n\nRESULT: ${failed ? "NOT VERIFIED" : "VERIFIED"}` : "Not checked: start the review with --issuer-key and --principal-key to verify every receipt here.";
87
161
  const body = `
88
162
  <p><a href="${esc(backLink)}">All receipts</a></p>
89
163
  <h1>${esc(p.tool.name)} <span class="muted">${esc(p.reconciliation ? "reconciled" : p.execution.status)}</span></h1>
90
- <p class="sub">${esc(p.timestamp.replace("T", " ").slice(0, 19))} · receipt <span class="mono">${esc(p.receiptId)}</span> · ${verification ? (verification.ok ? '<span class="ok">verified</span>' : '<span class="bad">NOT VERIFIED</span>') : '<span class="muted">not checked</span>'}</p>
164
+ <p class="sub">${esc(p.timestamp.replace("T", " ").slice(0, 19))} · receipt <span class="mono">${esc(p.receiptId)}</span> · ${failed ? '<span class="bad">NOT VERIFIED</span>' : verification ? '<span class="ok">verified</span>' : '<span class="muted">not checked</span>'}</p>
91
165
  <h2>What this action is</h2>
92
166
  ${explainHtml(formatExplain(pack, verification, !!o.ledger))}
93
167
  <h2>Verification</h2>
94
168
  <pre>${esc(report)}</pre>
95
169
  <h2>The receipt</h2>
96
- <p><a href="${esc(rawLink)}">The bundle as issued</a>, which any verifier checks with <code>agent-custody verify</code> and the public keys.</p>`;
97
- return page(`${p.tool.name} · ${p.receiptId.slice(0, 8)}`, body);
170
+ <p><a href="${esc(rawLink)}">The bundle as issued</a>, which any verifier checks with <code>agent-custody verify</code> and the public keys.</p>
171
+ <h2>Hand this case to another reviewer</h2>
172
+ <p><a download href="${esc(rawLink.replace(/\.json$/, '.case.html'))}">Download offline case file</a> · <a download href="${esc(rawLink.replace(/\.json$/, '.case.json'))}">Case data (JSON)</a></p>
173
+ <p>The case file contains the receipts, signed authorizations, public keys, log heads and verification report. Open it in a browser offline to repeat the cryptographic checks. Compare its public key fingerprints with a trusted source.</p>`;
174
+ return page(`${p.tool.name} · ${String(p.receiptId).slice(0, 8)}`, body);
175
+ }
176
+ /**
177
+ * Why the record in this file cannot be shown, or null. The verifier's own structural check decides it from the record, so
178
+ * an error from the ledger or the disk is never taken for a defect of the record.
179
+ */
180
+ function recordProblem(receiptsDir, id) {
181
+ const bundle = JSON.parse(readFileSync(join(receiptsDir, `${id}.json`), "utf8"));
182
+ // The tree head and the proof are not in the signed predicate, and the explain reads both.
183
+ const isObj = (v) => typeof v === "object" && v !== null;
184
+ if (!isObj(bundle.treeHead) || !Array.isArray(bundle.treeHead.signatures) || !isObj(bundle.inclusion))
185
+ return "the bundle has no tree head or no inclusion proof";
186
+ return structuralProblem(decodeStatement(bundle).predicate);
187
+ }
188
+ /** The page for a record that cannot be shown: a part that every check reads is missing or has the wrong type. */
189
+ function renderDamaged(file, reason, backLink, rawLink) {
190
+ return page(`Damaged record ${file.slice(0, 8)}`, `
191
+ <p><a href="${esc(backLink)}">All receipts</a></p>
192
+ <h1>A record that cannot be shown <span class="bad">NOT VERIFIED</span></h1>
193
+ <p class="sub">file <span class="mono">${esc(file)}</span></p>
194
+ <pre>${esc(`FAIL the record has the parts of a receipt (${reason})\n\nRESULT: NOT VERIFIED`)}</pre>
195
+ <p><a href="${esc(rawLink)}">The file as stored</a>. Check it with <code>agent-custody verify</code> and the public keys.</p>`);
98
196
  }
99
197
  function verifyOf(bundle, o) {
100
- return o.keys ? verifyBundle(bundle, { issuerKeys: o.keys.issuerKeys, principalKeys: o.keys.principalKeys ?? [], ...(o.keys.logKeys ? { logKeys: o.keys.logKeys } : {}), ...(o.keys.logId ? { logId: o.keys.logId } : {}) }) : null;
198
+ return o.keys ? verifyBundle(bundle, o.keys) : null;
101
199
  }
102
200
  /** Serves the review on loopback: / is the index, /r/<id> a receipt, /r/<id>.json the bundle. */
103
201
  export function reviewHandler(o) {
104
202
  return async (req, res) => {
105
203
  const url = new URL(req.url ?? "/", "http://localhost");
106
- const send = (status, type, body) => {
107
- res.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-frame-options": "DENY", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:" });
204
+ const send = (status, type, body, caseFile = false) => {
205
+ res.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-frame-options": "DENY", "x-content-type-options": "nosniff", ...(caseFile ? { "content-disposition": `attachment; filename="${url.pathname.split('/').at(-1)}"` } : { "content-security-policy": REVIEW_CSP }) });
108
206
  res.end(body);
109
207
  };
110
208
  try {
111
- if (url.pathname === "/")
112
- return send(200, "text/html; charset=utf-8", renderIndex(listReceipts(o), o, (id) => `/r/${id}`));
113
- const m = /^\/r\/([0-9a-f-]{36})(\.json)?$/.exec(url.pathname);
209
+ if (url.pathname === "/") {
210
+ const search = { ...o.search };
211
+ for (const name of ['transaction', 'customer', 'agent', 'from', 'to']) {
212
+ if (!url.searchParams.has(name))
213
+ continue;
214
+ const value = url.searchParams.get(name).trim();
215
+ if (value)
216
+ search[name] = value;
217
+ else
218
+ delete search[name];
219
+ }
220
+ try {
221
+ validateReceiptSearch(search);
222
+ }
223
+ catch (e) {
224
+ return send(400, "text/plain", e instanceof Error ? e.message : String(e));
225
+ }
226
+ const { rows, unreadable } = scanReceipts(o, search);
227
+ return send(200, "text/html; charset=utf-8", renderIndex(rows, { ...o, search }, (id) => `/r/${id}`, false, unreadable));
228
+ }
229
+ const m = /^\/r\/([0-9a-f-]{36})(\.case\.(?:html|json)|\.json)?$/.exec(url.pathname);
114
230
  if (!m)
115
231
  return send(404, "text/plain", "not found");
232
+ if (m[2]?.startsWith('.case.')) {
233
+ const file = await buildCaseFile(o, m[1]);
234
+ return send(200, m[2].endsWith('html') ? "text/html; charset=utf-8" : "application/json", m[2].endsWith('html') ? renderCaseFile(file) : JSON.stringify(file, null, 2), true);
235
+ }
116
236
  if (m[2])
117
237
  return send(200, "application/json", readFileSync(join(o.receiptsDir, `${m[1]}.json`), "utf8"));
238
+ const defect = recordProblem(o.receiptsDir, m[1]);
239
+ if (defect)
240
+ return send(200, "text/html; charset=utf-8", renderDamaged(m[1], defect, "/", `/r/${m[1]}.json`));
118
241
  const pack = await buildActionPack(o.receiptsDir, m[1], o.ledger);
119
242
  return send(200, "text/html; charset=utf-8", renderReceipt(pack, verifyOf(pack.receipt, o), o, "/", `/r/${m[1]}.json`));
120
243
  }
@@ -139,12 +262,23 @@ export function serveReview(o, opts) {
139
262
  /** Writes the same pages as static files: index.html, and r/<id>.html with r/<id>.json beside it. For a case file or a shared drive. */
140
263
  export async function writeReview(o, outDir) {
141
264
  mkdirSync(join(outDir, "r"), { recursive: true });
142
- const rows = listReceipts(o);
143
- writeFileSync(join(outDir, "index.html"), renderIndex(rows, o, (id) => `r/${id}.html`));
144
- for (const r of rows) {
145
- const pack = await buildActionPack(o.receiptsDir, r.receiptId, o.ledger);
146
- writeFileSync(join(outDir, "r", `${r.receiptId}.html`), renderReceipt(pack, verifyOf(pack.receipt, o), o, "../index.html", `${r.receiptId}.json`));
147
- writeFileSync(join(outDir, "r", `${r.receiptId}.json`), JSON.stringify(pack.receipt, null, 2));
265
+ const { rows, unreadable } = scanReceipts(o);
266
+ writeFileSync(join(outDir, "index.html"), renderIndex(rows, o, (id) => `r/${id}.html`, true, unreadable));
267
+ // A file name that is not a well formed id has no page. Its row is in the index, flagged.
268
+ for (const r of rows.filter((row) => RECEIPT_ID.test(row.file))) {
269
+ // A record with a structural defect must not stop the export. Its page says NOT VERIFIED and why, and it has no case file.
270
+ const defect = recordProblem(o.receiptsDir, r.file);
271
+ if (defect) {
272
+ writeFileSync(join(outDir, "r", `${r.file}.html`), renderDamaged(r.file, defect, "../index.html", `${r.file}.json`));
273
+ writeFileSync(join(outDir, "r", `${r.file}.json`), readFileSync(join(o.receiptsDir, `${r.file}.json`), "utf8"));
274
+ continue;
275
+ }
276
+ const file = await buildCaseFile(o, r.file);
277
+ const pack = file.pack;
278
+ writeFileSync(join(outDir, "r", `${r.file}.html`), renderReceipt(pack, verifyOf(pack.receipt, o), o, "../index.html", `${r.file}.json`));
279
+ writeFileSync(join(outDir, "r", `${r.file}.json`), JSON.stringify(pack.receipt, null, 2));
280
+ writeFileSync(join(outDir, "r", `${r.file}.case.json`), JSON.stringify(file, null, 2));
281
+ writeFileSync(join(outDir, "r", `${r.file}.case.html`), renderCaseFile(file));
148
282
  }
149
283
  return { receipts: rows.length };
150
284
  }
@@ -0,0 +1,28 @@
1
+ import type { ReceiptStatement } from "@agent-custody/receipts";
2
+ export interface ReceiptSearch {
3
+ transaction?: string;
4
+ customer?: string;
5
+ agent?: string;
6
+ /** Inclusive ISO 8601 date-time with a UTC offset. */
7
+ from?: string;
8
+ /** Inclusive ISO 8601 date-time with a UTC offset. */
9
+ to?: string;
10
+ }
11
+ /** Reject ambiguous, invalid, or inverted date ranges. Self-contained so static pages use this exact validator. */
12
+ export declare function validateReceiptSearch(query: ReceiptSearch): void;
13
+ type Predicate = ReceiptStatement["predicate"];
14
+ /**
15
+ * Named identifiers in public arguments, results, and fact lookups. Complete JSON objects/arrays in MCP text are
16
+ * inspected too; prose, digests, signatures, metadata outside those values, and encoded envelopes are not searched.
17
+ * Generic result `id` fields count only when they have a known payment or customer id prefix. Values nested deeper
18
+ * than 64 levels, and JSON text longer than 64 KiB, are not searched, so that one hostile argument cannot stall a reader.
19
+ * When a value is skipped for that reason, the result carries `truncated: true`. Otherwise it has no such field.
20
+ */
21
+ export declare function receiptSearchTerms(predicate: Predicate): {
22
+ transactionIds: string[];
23
+ customerIds: string[];
24
+ truncated?: true;
25
+ };
26
+ /** Every supplied filter must match; identifiers and agent ids are exact and case sensitive. */
27
+ export declare function matchesReceiptSearch(predicate: Predicate, query: ReceiptSearch): boolean;
28
+ export {};
package/dist/search.js ADDED
@@ -0,0 +1,177 @@
1
+ /** Reject ambiguous, invalid, or inverted date ranges. Self-contained so static pages use this exact validator. */
2
+ export function validateReceiptSearch(query) {
3
+ for (const field of ["transaction", "customer", "agent", "from", "to"]) {
4
+ const value = query[field];
5
+ if (value !== undefined && typeof value !== "string")
6
+ throw new Error(`receipt search: ${field} must be a string`);
7
+ }
8
+ for (const field of ["from", "to"]) {
9
+ const value = query[field];
10
+ if (value === undefined)
11
+ continue;
12
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/.exec(value);
13
+ const [year, month, day, hour, minute, second] = match ? match.slice(1).map((v) => Number(v ?? 0)) : [];
14
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
15
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
16
+ if (!match || month < 1 || month > 12 || day < 1 || day > days[month - 1] || hour > 23 || minute > 59 || second > 59 || !Number.isFinite(Date.parse(value))) {
17
+ throw new Error(`receipt search: ${field} must be an ISO 8601 date-time with a UTC offset`);
18
+ }
19
+ }
20
+ if (query.from !== undefined && query.to !== undefined && Date.parse(query.from) > Date.parse(query.to)) {
21
+ throw new Error("receipt search: from must be at or before to");
22
+ }
23
+ }
24
+ const TRANSACTION_FIELDS = new Set(["transaction", "transaction_id", "transactionId", "payment_intent", "payment_intent_id", "paymentIntent", "paymentIntentId", "charge", "charge_id", "chargeId", "refund", "refund_id", "refundId"]);
25
+ const CUSTOMER_FIELDS = new Set(["customer", "customer_id", "customerId"]);
26
+ const TRANSACTION_ID = /^(?:re|pi|ch|txn|tr|py|po)_.+/;
27
+ const CUSTOMER_ID = /^cus(?:t)?_.+/;
28
+ const kindOf = (field) => TRANSACTION_FIELDS.has(field) ? "transaction" : CUSTOMER_FIELDS.has(field) ? "customer" : undefined;
29
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
30
+ // The input is the agent's own text, so the work per receipt has fixed bounds. A walk stops below MAX_DEPTH levels, and
31
+ // a string is parsed as JSON only up to MAX_JSON_TEXT characters. A node deeper than that, or in longer text, is not
32
+ // searched, and the result says `truncated`, so that a reader never mistakes a skipped value for an absent one.
33
+ const MAX_DEPTH = 64;
34
+ const MAX_JSON_TEXT = 65_536;
35
+ const JSON_START = /^\s*[\[{]/;
36
+ const HIDDEN = Symbol("hidden");
37
+ /** The withheld paths as a trie, so that a walk tracks "hidden" one step at a time. */
38
+ function withheldTrie(withheld) {
39
+ const root = { end: false, kids: new Map() };
40
+ if (!Array.isArray(withheld))
41
+ return root;
42
+ for (const path of withheld) {
43
+ // An empty path, or a path with a step that is not a string, never named a field.
44
+ if (!Array.isArray(path) || !path.length || !path.every((step) => typeof step === "string"))
45
+ continue;
46
+ let at = root;
47
+ for (const step of path) {
48
+ let next = at.kids.get(step);
49
+ if (!next)
50
+ at.kids.set(step, (next = { end: false, kids: new Map() }));
51
+ at = next;
52
+ }
53
+ at.end = true;
54
+ }
55
+ return root;
56
+ }
57
+ /** The trie node below the keys, `undefined` when no withheld path goes there, or HIDDEN when a withheld path ends on the way. */
58
+ const into = (at, ...keys) => {
59
+ for (const key of keys) {
60
+ at = at?.kids.get(key);
61
+ if (at?.end)
62
+ return HIDDEN;
63
+ }
64
+ return at;
65
+ };
66
+ /**
67
+ * Named identifiers in public arguments, results, and fact lookups. Complete JSON objects/arrays in MCP text are
68
+ * inspected too; prose, digests, signatures, metadata outside those values, and encoded envelopes are not searched.
69
+ * Generic result `id` fields count only when they have a known payment or customer id prefix. Values nested deeper
70
+ * than 64 levels, and JSON text longer than 64 KiB, are not searched, so that one hostile argument cannot stall a reader.
71
+ * When a value is skipped for that reason, the result carries `truncated: true`. Otherwise it has no such field.
72
+ */
73
+ export function receiptSearchTerms(predicate) {
74
+ let truncated = false;
75
+ const transaction = new Set();
76
+ const customer = new Set();
77
+ const terms = { transaction, customer };
78
+ const trie = withheldTrie(predicate.capture?.withheld);
79
+ const add = (value, kind, at) => {
80
+ if (typeof value === "string" && value.length)
81
+ terms[kind].add(value);
82
+ else if (object(value) && Object.hasOwn(value, "id") && into(at, "id") !== HIDDEN && typeof value.id === "string" && value.id.length)
83
+ terms[kind].add(value.id);
84
+ };
85
+ // `at` is the trie node of the value's path. It is never a withheld node. It is undefined when no withheld path runs below.
86
+ const walk = (value, at, result, depth) => {
87
+ if (depth > MAX_DEPTH) {
88
+ if ((value !== null && typeof value === "object") || (typeof value === "string" && JSON_START.test(value)))
89
+ truncated = true;
90
+ return;
91
+ }
92
+ if (typeof value === "string") {
93
+ // JSON.parse only accepts the entire text. A sentence that happens to mention an id is not an identifier.
94
+ if (value.length > MAX_JSON_TEXT && JSON_START.test(value))
95
+ truncated = true;
96
+ else if (JSON_START.test(value)) {
97
+ try {
98
+ walk(JSON.parse(value), at, result, depth + 1);
99
+ }
100
+ catch {
101
+ // Ordinary tool text is not JSON.
102
+ }
103
+ }
104
+ return;
105
+ }
106
+ if (Array.isArray(value)) {
107
+ value.forEach((item, i) => {
108
+ const next = into(at, String(i));
109
+ if (next !== HIDDEN)
110
+ walk(item, next, result, depth + 1);
111
+ });
112
+ return;
113
+ }
114
+ if (!object(value))
115
+ return;
116
+ for (const [field, item] of Object.entries(value)) {
117
+ const next = into(at, field);
118
+ if (next === HIDDEN)
119
+ continue;
120
+ const kind = kindOf(field);
121
+ if (kind)
122
+ add(item, kind, next);
123
+ else if (result && field === "id" && typeof item === "string") {
124
+ if (TRANSACTION_ID.test(item))
125
+ transaction.add(item);
126
+ if (CUSTOMER_ID.test(item))
127
+ customer.add(item);
128
+ }
129
+ walk(item, next, result, depth + 1);
130
+ }
131
+ };
132
+ const start = (value, result, ...path) => {
133
+ const at = into(trie, ...path);
134
+ if (at !== HIDDEN)
135
+ walk(value, at, result, 0);
136
+ };
137
+ start(predicate.request.args, false, "request", "args");
138
+ if (predicate.execution.status === "executed" || predicate.execution.status === "failed") {
139
+ start(predicate.execution.result, true, "execution", "result");
140
+ }
141
+ for (const [name, fact] of Object.entries(predicate.facts)) {
142
+ if (into(trie, "facts", name) === HIDDEN)
143
+ continue;
144
+ start(fact.args, false, "facts", name, "args");
145
+ const valueAt = into(trie, "facts", name, "value");
146
+ if (valueAt === HIDDEN)
147
+ continue;
148
+ const kind = kindOf(name);
149
+ if (kind)
150
+ add(fact.value, kind, valueAt);
151
+ walk(fact.value, valueAt, true, 0);
152
+ }
153
+ return { transactionIds: [...transaction].sort(), customerIds: [...customer].sort(), ...(truncated ? { truncated: true } : {}) };
154
+ }
155
+ /** Every supplied filter must match; identifiers and agent ids are exact and case sensitive. */
156
+ export function matchesReceiptSearch(predicate, query) {
157
+ validateReceiptSearch(query);
158
+ if (query.agent !== undefined && predicate.agent.id !== query.agent)
159
+ return false;
160
+ if (query.from !== undefined || query.to !== undefined) {
161
+ const timestamp = Date.parse(predicate.timestamp);
162
+ if (!Number.isFinite(timestamp))
163
+ return false;
164
+ if (query.from !== undefined && timestamp < Date.parse(query.from))
165
+ return false;
166
+ if (query.to !== undefined && timestamp > Date.parse(query.to))
167
+ return false;
168
+ }
169
+ if (query.transaction !== undefined || query.customer !== undefined) {
170
+ const terms = receiptSearchTerms(predicate);
171
+ if (query.transaction !== undefined && !terms.transactionIds.includes(query.transaction))
172
+ return false;
173
+ if (query.customer !== undefined && !terms.customerIds.includes(query.customer))
174
+ return false;
175
+ }
176
+ return true;
177
+ }
package/dist/server.d.ts CHANGED
@@ -2,7 +2,7 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { type Tool } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { type KeyPair } from "@agent-custody/receipts";
4
4
  import type { Ledger } from "./ledger.ts";
5
- import type { Store } from "./stores.ts";
5
+ import { type Store } from "./stores.ts";
6
6
  export declare const SERVER_VERSION = "0.1.0";
7
7
  /** The same keys the receipts gateway sets on the upstream call. Duplicated here so this package needs no runtime import from receipts. */
8
8
  export declare const RECEIPT_META_KEY = "agent-custody/receipt";
@@ -39,6 +39,11 @@ export interface MemoryServerOptions {
39
39
  export declare function durationMs(iso: string): number;
40
40
  /** The retention cutoff for a space, from the first pattern that matches it; null when none does. */
41
41
  export declare function retentionCutoff(retention: Record<string, string>, space: string, now: Date): string | null;
42
+ /**
43
+ * How old a store entry must be before repair may remove it. A write whose stores take more than half of it fails
44
+ * before its ledger append, so the entry of a write in progress is never this old.
45
+ */
46
+ export declare const REPAIR_MIN_AGE_MS: number;
42
47
  export declare function createMemoryServer(ledger: Ledger, opts?: MemoryServerOptions): Server;
43
48
  /** Serves over stdio, the way the gateway spawns it. Diagnostics must go to stderr. */
44
49
  export declare function serveStdio(server: Server): Promise<void>;