saktum 0.9.0 → 0.12.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.
Files changed (3) hide show
  1. package/README.md +26 -1
  2. package/package.json +1 -1
  3. package/saktum.mjs +985 -162
package/saktum.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Saktum Check 0.9.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
2
+ // Saktum Check 0.12.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
3
3
  import { createRequire as __saktumCreateRequire } from "node:module";
4
4
  const require = __saktumCreateRequire(import.meta.url);
5
5
  var __create = Object.create;
@@ -10417,6 +10417,7 @@ var require_dist = __commonJS({
10417
10417
  });
10418
10418
 
10419
10419
  // packages/sign/dist/index.js
10420
+ import { execFileSync } from "node:child_process";
10420
10421
  import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "node:crypto";
10421
10422
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10422
10423
  import { dirname, join } from "node:path";
@@ -10483,7 +10484,66 @@ function generateSigningKey() {
10483
10484
  const { privateKey, publicKey } = generateKeyPairSync("ed25519");
10484
10485
  return { privateKey, publicKey, kid: didKeyFromPublicKey(publicKey) };
10485
10486
  }
10487
+ function keyFromJwk(jwkText) {
10488
+ const privateKey = createPrivateKey({ key: JSON.parse(jwkText), format: "jwk" });
10489
+ const publicKey = createPublicKey(privateKey);
10490
+ return { privateKey, publicKey, kid: didKeyFromPublicKey(publicKey) };
10491
+ }
10492
+ function keychain(name) {
10493
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(name))
10494
+ throw new Error("Keychain names may use letters, digits, dot, dash and underscore.");
10495
+ const run = (cmd, args, input, env) => execFileSync(cmd, args, { encoding: "utf8", input, env: { ...process.env, ...env ?? {} }, stdio: ["pipe", "pipe", "ignore"] }).trim();
10496
+ const fresh = () => {
10497
+ const k = generateSigningKey();
10498
+ return { k, jwk: JSON.stringify(k.privateKey.export({ format: "jwk" })) };
10499
+ };
10500
+ if (process.platform === "darwin") {
10501
+ try {
10502
+ return keyFromJwk(run("security", ["find-generic-password", "-s", "saktum", "-a", name, "-w"]));
10503
+ } catch {
10504
+ const { k, jwk } = fresh();
10505
+ run("security", ["add-generic-password", "-s", "saktum", "-a", name, "-w", jwk, "-U"]);
10506
+ return k;
10507
+ }
10508
+ }
10509
+ if (process.platform === "win32") {
10510
+ const file = join(homedir(), ".saktum", "keys", `${name}.dpapi`);
10511
+ const ps = (script, env) => run("powershell", ["-NoProfile", "-NonInteractive", "-Command", "Add-Type -AssemblyName System.Security; " + script], void 0, env);
10512
+ if (existsSync(file))
10513
+ return keyFromJwk(ps("[Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect([Convert]::FromBase64String((Get-Content -Raw $env:SAKTUM_F)), $null, 'CurrentUser'))", { SAKTUM_F: file }));
10514
+ const { k, jwk } = fresh();
10515
+ mkdirSync(dirname(file), { recursive: true });
10516
+ writeFileSync(file, ps("[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect([Text.Encoding]::UTF8.GetBytes($env:SAKTUM_J), $null, 'CurrentUser'))", { SAKTUM_J: jwk }), { mode: 384 });
10517
+ return k;
10518
+ }
10519
+ try {
10520
+ return keyFromJwk(run("secret-tool", ["lookup", "service", "saktum", "account", name]));
10521
+ } catch {
10522
+ const { k, jwk } = fresh();
10523
+ run("secret-tool", ["store", "--label", `Saktum key ${name}`, "service", "saktum", "account", name], jwk);
10524
+ return k;
10525
+ }
10526
+ }
10486
10527
  function loadOrCreateKey(path = defaultKeyPath()) {
10528
+ if (path.startsWith("env:")) {
10529
+ const v = process.env[path.slice(4)];
10530
+ if (!v)
10531
+ throw new Error(`Environment variable ${path.slice(4)} is not set.`);
10532
+ return keyFromJwk(v);
10533
+ }
10534
+ if (path.startsWith("keychain:"))
10535
+ return keychain(path.slice(9));
10536
+ if (path.startsWith("exec:")) {
10537
+ const prog = path.slice(5);
10538
+ const publicKey = createPublicKey({ key: JSON.parse(execFileSync(prog, ["public"], { encoding: "utf8" })), format: "jwk" });
10539
+ const signer = (data) => {
10540
+ const sig = Buffer.from(execFileSync(prog, ["sign"], { encoding: "utf8", input: data.toString("base64") }).trim(), "base64");
10541
+ if (!verify(null, data, publicKey, sig))
10542
+ throw new Error("The external signer returned an invalid signature.");
10543
+ return sig;
10544
+ };
10545
+ return { privateKey: publicKey, publicKey, kid: didKeyFromPublicKey(publicKey), signer };
10546
+ }
10487
10547
  if (existsSync(path)) {
10488
10548
  const jwk = JSON.parse(readFileSync(path, "utf8"));
10489
10549
  const privateKey = createPrivateKey({ key: jwk, format: "jwk" });
@@ -10503,7 +10563,7 @@ function signDocument(doc, key) {
10503
10563
  const { signature: _ignored, ...body2 } = doc;
10504
10564
  const header = b64u(Buffer.from(JSON.stringify({ alg: "EdDSA", kid: key.kid })));
10505
10565
  const payload = b64u(Buffer.from(canonicalize(body2)));
10506
- const sig = sign(null, Buffer.from(`${header}.${payload}`), key.privateKey);
10566
+ const sig = key.signer ? key.signer(Buffer.from(`${header}.${payload}`)) : sign(null, Buffer.from(`${header}.${payload}`), key.privateKey);
10507
10567
  return { ...body2, signature: { alg: "EdDSA", kid: key.kid, jws: `${header}..${b64u(sig)}` } };
10508
10568
  }
10509
10569
  function verifyDocument(doc) {
@@ -33997,7 +34057,7 @@ var init_dist3 = __esm({
33997
34057
  init_stdio2();
33998
34058
  init_streamableHttp();
33999
34059
  init_types2();
34000
- USER_AGENT = "saktum-check/0.9.0 (+https://saktum.dev/check)";
34060
+ USER_AGENT = "saktum-check/0.12.0 (+https://saktum.dev/check)";
34001
34061
  LIMITS = { requestTimeoutMs: 1e4, connectTimeoutMs: 6e4, maxResponseChars: 5e6 };
34002
34062
  LimitError = class extends Error {
34003
34063
  };
@@ -34035,7 +34095,7 @@ var init_dist3 = __esm({
34035
34095
  jsonrpc: "2.0",
34036
34096
  id: 1,
34037
34097
  method: "initialize",
34038
- params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.9.0" } }
34098
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.12.0" } }
34039
34099
  });
34040
34100
  }
34041
34101
  });
@@ -35407,7 +35467,7 @@ var init_engine = __esm({
35407
35467
  init_runner();
35408
35468
  init_safe();
35409
35469
  init_scoring();
35410
- ENGINE_VERSION = "0.9.0";
35470
+ ENGINE_VERSION = "0.12.0";
35411
35471
  UNKNOWN_TOOL = "saktum_trust_check_no_such_tool";
35412
35472
  INVALID_TOKEN = "saktum-check-deliberately-invalid-token";
35413
35473
  baseOf = (pack, check) => ({
@@ -35791,6 +35851,51 @@ var init_fleet = __esm({
35791
35851
  });
35792
35852
 
35793
35853
  // packages/testkit-core/dist/ledger.js
35854
+ function checkStatement(s) {
35855
+ const st = s;
35856
+ if (!st || st.statementFormat !== "0.1" || !["key-rotation", "revocation"].includes(st.type))
35857
+ return { ok: false, reason: "not a Saktum statement" };
35858
+ if (JSON.stringify(st).length > MAX_ATTESTATION_BYTES)
35859
+ return { ok: false, reason: "statement too large" };
35860
+ const v = verifyDocument(st);
35861
+ if (!v.valid)
35862
+ return { ok: false, reason: `signature not valid (${v.reason})` };
35863
+ if (st.type === "key-rotation") {
35864
+ if (v.kid !== st.oldKey || !st.newKey)
35865
+ return { ok: false, reason: "a rotation must be signed by the old key and name the new key" };
35866
+ const pv = verifyDocument(st.newKeyProof);
35867
+ if (!pv.valid || pv.kid !== st.newKey || st.newKeyProof.rotates !== st.oldKey)
35868
+ return { ok: false, reason: "missing proof of possession of the new key" };
35869
+ } else if (!st.target)
35870
+ return { ok: false, reason: "a revocation must name its target" };
35871
+ return { ok: true, st, signer: v.kid };
35872
+ }
35873
+ function appendStatement(ledgerText, statement, source, now = /* @__PURE__ */ new Date()) {
35874
+ const c = checkStatement(statement);
35875
+ if (!c.ok)
35876
+ throw new Error(`Refused: ${c.reason}`);
35877
+ const entries = parseLedger(ledgerText);
35878
+ const check = verifyLedger(entries);
35879
+ if (!check.ok)
35880
+ throw new Error(`Refused: the existing ledger does not verify (${check.errors[0]})`);
35881
+ if (c.st.type === "revocation" && !entries.some((e) => e.signer === c.signer && (e.attestation?.resultDigest === c.st.target || e.signer === c.st.target)) && c.st.target !== c.signer)
35882
+ throw new Error("Refused: a revocation must come from the key that signed the target");
35883
+ const prev = entries[entries.length - 1];
35884
+ const base = { ledgerFormat: "0.1", seq: (prev?.seq ?? 0) + 1, recordedAt: now.toISOString(), source, subject: { server: `${c.st.type}:${c.signer.slice(0, 32)}` }, signer: c.signer, statement: c.st, prevHash: prev?.entryHash ?? GENESIS };
35885
+ const entry = { ...base, entryHash: hashOf(base) };
35886
+ return { text: `${ledgerText.replace(/\n*$/, ledgerText.trim() ? "\n" : "")}${JSON.stringify(entry)}
35887
+ `, entry };
35888
+ }
35889
+ function ledgerStatus(entries) {
35890
+ const rotated = /* @__PURE__ */ new Map(), revoked = /* @__PURE__ */ new Set();
35891
+ for (const e of entries) {
35892
+ if (e.statement?.type === "key-rotation")
35893
+ rotated.set(e.statement.oldKey, e.statement.newKey);
35894
+ if (e.statement?.type === "revocation")
35895
+ revoked.add(e.statement.target);
35896
+ }
35897
+ return { rotated, revoked };
35898
+ }
35794
35899
  function parseLedger(text2) {
35795
35900
  return text2.split("\n").map((l) => l.trim()).filter(Boolean).map((l, i) => {
35796
35901
  try {
@@ -35829,7 +35934,7 @@ function appendToLedger(ledgerText, attestation, source, now = /* @__PURE__ */ n
35829
35934
  const check = verifyLedger(entries);
35830
35935
  if (!check.ok)
35831
35936
  throw new Error(`Refused: the existing ledger does not verify (${check.errors[0]})`);
35832
- if (entries.some((e) => e.signer === c.signer && e.attestation.resultDigest === c.att.resultDigest))
35937
+ if (entries.some((e) => e.signer === c.signer && e.attestation?.resultDigest === c.att.resultDigest))
35833
35938
  throw new Error("Refused: this attestation is already in the ledger");
35834
35939
  const prev = entries[entries.length - 1];
35835
35940
  const base = {
@@ -35857,16 +35962,17 @@ function verifyLedger(entries) {
35857
35962
  const { entryHash, ...base } = e;
35858
35963
  if (hashOf(base) !== entryHash)
35859
35964
  errors.push(`entry ${e.seq}: contents changed after it was recorded`);
35860
- const c = checkAttestation(e.attestation);
35965
+ const c = e.statement ? checkStatement(e.statement) : checkAttestation(e.attestation);
35861
35966
  if (!c.ok)
35862
35967
  errors.push(`entry ${e.seq}: ${c.reason}`);
35863
35968
  else if (c.signer !== e.signer)
35864
- errors.push(`entry ${e.seq}: signer does not match the attestation`);
35969
+ errors.push(`entry ${e.seq}: signer does not match`);
35865
35970
  prev = entryHash;
35866
35971
  });
35867
35972
  return { ok: errors.length === 0, count: entries.length, errors };
35868
35973
  }
35869
35974
  function findInLedger(entries, query) {
35975
+ entries = entries.filter((e) => e.attestation);
35870
35976
  const q = query.toLowerCase();
35871
35977
  return entries.filter((e) => e.subject.server.toLowerCase().includes(q) || e.subject.toolsFingerprint === query);
35872
35978
  }
@@ -35876,6 +35982,8 @@ function allowlistFromLedger(entries, c) {
35876
35982
  latest.set(`${e.subject.server}|${e.subject.toolsFingerprint}`, e);
35877
35983
  const allowed = [], excluded = [];
35878
35984
  for (const e of latest.values()) {
35985
+ if (!e.attestation)
35986
+ continue;
35879
35987
  const cl = e.attestation.claims, why = [];
35880
35988
  if (c.trustedSigners && !c.trustedSigners.has(e.signer))
35881
35989
  why.push("signer is not on your trusted list");
@@ -36355,17 +36463,27 @@ function checkOperator(m) {
36355
36463
  return { present: true, valid: false, reason: "operator signed a different mandate" };
36356
36464
  return { present: true, valid: true, id: v.kid, name: cs.name };
36357
36465
  }
36358
- function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS()) {
36466
+ function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS(), key) {
36359
36467
  const r = readRevocations(path), d = mandateDigest(m);
36468
+ const entry = { revocationFormat: "0.1", mandate: d, agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} };
36360
36469
  if (!r.revoked.some((x) => x.mandate === d))
36361
- r.revoked.push({ mandate: d, agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} });
36470
+ r.revoked.push(key ? signDocument(entry, key) : entry);
36362
36471
  _mkdir(_dirname(path), { recursive: true });
36363
36472
  _write(path, JSON.stringify(r, null, 2) + "\n");
36364
36473
  return r.revoked.find((x) => x.mandate === d);
36365
36474
  }
36366
36475
  function revocationOf(m, path = DEFAULT_REVOCATIONS()) {
36367
36476
  const d = mandateDigest(m);
36368
- return readRevocations(path).revoked.find((x) => x.mandate === d);
36477
+ const op = m.operatorCountersign?.signature?.kid;
36478
+ return readRevocations(path).revoked.find((x) => {
36479
+ if (x.mandate !== d)
36480
+ return false;
36481
+ const sx = x;
36482
+ if (!sx.signature)
36483
+ return true;
36484
+ const v = verifyDocument(x);
36485
+ return v.valid && (v.kid === m.owner.id || Boolean(op) && v.kid === op);
36486
+ });
36369
36487
  }
36370
36488
  function trustStatement(entries, verified) {
36371
36489
  const allowed = entries.filter((e) => e.receipt.outcome === "allow" && e.result.status === "ok").length;
@@ -36393,6 +36511,17 @@ function trustStatement(entries, verified) {
36393
36511
  function approvalRequestId(m, tool, args) {
36394
36512
  return "apr_" + argumentsHash({ mandate: mandateDigest(m), tool, args: argumentsHash(args) }).replace(/^sha256:/, "").slice(0, 16);
36395
36513
  }
36514
+ function recordPending(path, req) {
36515
+ const a = readApprovals(path);
36516
+ a.pending = (a.pending ?? []).filter((p) => p.id !== req.id);
36517
+ a.pending.push({ ...req, at: (/* @__PURE__ */ new Date()).toISOString() });
36518
+ _mkdir(_dirname(path), { recursive: true });
36519
+ _write(path, JSON.stringify(a, null, 2) + "\n");
36520
+ }
36521
+ function listPending(path = DEFAULT_APPROVALS()) {
36522
+ const a = readApprovals(path);
36523
+ return (a.pending ?? []).filter((p) => !a.used.includes(p.id) && !a.approvals.some((x) => x.approval === p.id));
36524
+ }
36396
36525
  function approveAction(m, requestId, ownerKey, minutes = 60, path = DEFAULT_APPROVALS()) {
36397
36526
  if (ownerKey.kid !== m.owner.id)
36398
36527
  throw new Error("Only the mandate's owner can approve its actions.");
@@ -36746,21 +36875,47 @@ function verifyAgreement(a, today = nowIso().slice(0, 10)) {
36746
36875
  return { valid: false, reason: `expired on ${a.validUntil}` };
36747
36876
  return { valid: true };
36748
36877
  }
36878
+ function sealEntry(w, e, key) {
36879
+ const prev = w.entries[w.entries.length - 1]?.hash ?? "sha256:genesis";
36880
+ const body2 = { at: e.at, from: e.from, to: e.to, tokens: e.tokens, ref: e.ref, prev };
36881
+ const hash = argumentsHash(body2);
36882
+ return key ? signDocument({ ...body2, hash }, key) : { ...body2, hash };
36883
+ }
36884
+ function verifyWallet(path) {
36885
+ const errors = [];
36886
+ let prev = "sha256:genesis";
36887
+ readWallet(path).entries.forEach((e, i) => {
36888
+ if (!e.hash)
36889
+ return;
36890
+ const { signature: _s, hash, ...body2 } = e;
36891
+ if (body2.prev !== prev)
36892
+ errors.push(`entry ${i + 1}: chain broken`);
36893
+ if (argumentsHash({ at: body2.at, from: body2.from, to: body2.to, tokens: body2.tokens, ref: body2.ref, prev: body2.prev }) !== hash)
36894
+ errors.push(`entry ${i + 1}: changed after it was written`);
36895
+ if (e.signature && !verifyDocument(e).valid)
36896
+ errors.push(`entry ${i + 1}: signature not valid`);
36897
+ prev = hash;
36898
+ });
36899
+ return { ok: errors.length === 0, errors };
36900
+ }
36749
36901
  function walletBalance(path, account) {
36750
36902
  return readWallet(path).entries.reduce((b, e) => b + (e.to === account ? e.tokens : 0) - (e.from === account ? e.tokens : 0), 0);
36751
36903
  }
36752
- function topUp(path, account, tokens, ref = "top-up") {
36904
+ function topUp(path, account, tokens, ref = "top-up", key) {
36753
36905
  const w = readWallet(path);
36754
- w.entries.push({ at: nowIso(), from: PREPAID, to: account, tokens, ref });
36906
+ w.entries.push(sealEntry(w, { at: nowIso(), from: PREPAID, to: account, tokens, ref }, key));
36755
36907
  writeWallet(path, w);
36756
36908
  return walletBalance(path, account);
36757
36909
  }
36758
- function chargeCall(path, a, tool, ref) {
36759
- const cost = tokensFor(a, tool), bal = walletBalance(path, a.invoker.id);
36910
+ function chargeCall(path, a, tool, ref, key) {
36911
+ const cost = tokensFor(a, tool);
36912
+ if (!verifyWallet(path).ok)
36913
+ return { ok: false, tokens: cost, balance: 0 };
36914
+ const bal = walletBalance(path, a.invoker.id);
36760
36915
  if (bal < cost)
36761
36916
  return { ok: false, tokens: cost, balance: bal };
36762
36917
  const w = readWallet(path);
36763
- w.entries.push({ at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref });
36918
+ w.entries.push(sealEntry(w, { at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref }, key));
36764
36919
  writeWallet(path, w);
36765
36920
  return { ok: true, tokens: cost, balance: bal - cost };
36766
36921
  }
@@ -36913,6 +37068,263 @@ var init_crosswalk = __esm({
36913
37068
  }
36914
37069
  });
36915
37070
 
37071
+ // packages/testkit-core/dist/agents.js
37072
+ import { readdirSync as readdirSync3, readFileSync as readFileSync6, statSync as statSync2 } from "node:fs";
37073
+ import { join as join4 } from "node:path";
37074
+ function scanAgents(dirs, o = {}) {
37075
+ const found = [];
37076
+ const walk = (dir, depth) => {
37077
+ let names = [];
37078
+ try {
37079
+ names = readdirSync3(dir);
37080
+ } catch {
37081
+ return;
37082
+ }
37083
+ for (const n of names) {
37084
+ if (n === "node_modules" || n.startsWith(".git"))
37085
+ continue;
37086
+ const p = join4(dir, n);
37087
+ let st;
37088
+ try {
37089
+ st = statSync2(p);
37090
+ } catch {
37091
+ continue;
37092
+ }
37093
+ if (st.isDirectory()) {
37094
+ if (depth > 0)
37095
+ walk(p, depth - 1);
37096
+ continue;
37097
+ }
37098
+ if (!n.endsWith(".json") || st.size > 1e6)
37099
+ continue;
37100
+ let m;
37101
+ try {
37102
+ m = JSON.parse(readFileSync6(p, "utf8"));
37103
+ } catch {
37104
+ continue;
37105
+ }
37106
+ if (!m || typeof m !== "object" || !("mandateFormat" in m) || !m.agent?.id)
37107
+ continue;
37108
+ const op = checkOperator(m);
37109
+ found.push({
37110
+ name: m.agent.name,
37111
+ id: m.agent.id,
37112
+ owner: m.owner?.name ?? m.owner?.id ?? "",
37113
+ operator: op.present ? op.valid ? op.name ?? "" : "invalid countersignature" : "",
37114
+ purpose: m.purpose ?? "",
37115
+ autonomy: m.autonomy ?? "act",
37116
+ tools: m.allow?.tools?.length ?? 0,
37117
+ riskTier: agentRiskTier(m).tier,
37118
+ maturity: agentMaturity(m).label,
37119
+ expires: m.expires,
37120
+ valid: checkMandate(m).ok,
37121
+ revoked: Boolean(revocationOf(m, o.revocationsPath)),
37122
+ file: p
37123
+ });
37124
+ }
37125
+ };
37126
+ for (const d of dirs)
37127
+ walk(d, o.depth ?? 3);
37128
+ return found;
37129
+ }
37130
+ var init_agents = __esm({
37131
+ "packages/testkit-core/dist/agents.js"() {
37132
+ "use strict";
37133
+ init_agentid();
37134
+ }
37135
+ });
37136
+
37137
+ // packages/testkit-core/dist/trust.js
37138
+ import { createHmac } from "node:crypto";
37139
+ function signRevocation(m, key, reason) {
37140
+ return signDocument({ revocationFormat: "0.1", mandate: mandateDigest(m), agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} }, key);
37141
+ }
37142
+ function validRevocation(r, m) {
37143
+ const x = r;
37144
+ if (!x || x.mandate !== mandateDigest(m))
37145
+ return false;
37146
+ if (!x.signature)
37147
+ return true;
37148
+ const v = verifyDocument(x);
37149
+ const op = m.operatorCountersign?.signature?.kid;
37150
+ return v.valid && (v.kid === m.owner.id || Boolean(op) && v.kid === op);
37151
+ }
37152
+ function makeCheckpoint(entries, key, log = "receipts") {
37153
+ const last = entries[entries.length - 1];
37154
+ return signDocument({ checkpointFormat: "0.1", log, seq: last?.seq ?? 0, head: last?.entryHash ?? "sha256:genesis", at: (/* @__PURE__ */ new Date()).toISOString() }, key);
37155
+ }
37156
+ function verifyAgainstCheckpoint(entries, cp, trustedSigners) {
37157
+ const v = verifyDocument(cpCore(cp));
37158
+ if (!v.valid)
37159
+ return { ok: false, reason: "checkpoint signature not valid" };
37160
+ if (trustedSigners?.length && !trustedSigners.includes(v.kid))
37161
+ return { ok: false, reason: "checkpoint signed by an untrusted key" };
37162
+ if (entries.length < cp.seq)
37163
+ return { ok: false, reason: `the log has ${entries.length} entries but the checkpoint covers ${cp.seq}: entries were deleted` };
37164
+ const head = cp.seq === 0 ? "sha256:genesis" : entries[cp.seq - 1]?.entryHash;
37165
+ if (head !== cp.head)
37166
+ return { ok: false, reason: `entry ${cp.seq} differs from the checkpoint: the log was rewritten` };
37167
+ return { ok: true };
37168
+ }
37169
+ function witnessCheckpoint(cp, entries, key) {
37170
+ const ok = verifyAgainstCheckpoint(entries, cp);
37171
+ if (!ok.ok)
37172
+ throw new Error(`Not witnessing: ${ok.reason}`);
37173
+ return { ...cp, witnesses: [...cp.witnesses ?? [], signDocument({ witnessFormat: "0.1", checkpoint: sha256Tag(canonicalize(cpCore(cp))), at: (/* @__PURE__ */ new Date()).toISOString() }, key)] };
37174
+ }
37175
+ function validWitnesses(cp) {
37176
+ const d = sha256Tag(canonicalize(cpCore(cp)));
37177
+ return (cp.witnesses ?? []).flatMap((w) => {
37178
+ const x = w;
37179
+ const v = verifyDocument(w);
37180
+ return v.valid && x.checkpoint === d ? [v.kid] : [];
37181
+ });
37182
+ }
37183
+ async function verifyDomain(domain, did, o = {}) {
37184
+ if (!/^[a-z0-9.-]{3,253}$/i.test(domain))
37185
+ return { verified: false };
37186
+ try {
37187
+ const rt = o.resolveTxt ?? (await import("node:dns/promises")).resolveTxt;
37188
+ const recs = await rt(`_saktum.${domain}`);
37189
+ if (recs.flat().some((t) => t.trim() === `saktum-did=${did}`))
37190
+ return { verified: true, method: "dns" };
37191
+ } catch {
37192
+ }
37193
+ try {
37194
+ const r = await (o.fetchImpl ?? fetch)(`https://${domain}/.well-known/saktum.json`);
37195
+ if (r.ok) {
37196
+ const j = await r.json();
37197
+ if (j.did === did || j.dids?.includes(did))
37198
+ return { verified: true, method: "well-known" };
37199
+ }
37200
+ } catch {
37201
+ }
37202
+ return { verified: false };
37203
+ }
37204
+ var keyedDigest, revokedInChain, approvalUsedInChain, cpCore;
37205
+ var init_trust = __esm({
37206
+ "packages/testkit-core/dist/trust.js"() {
37207
+ "use strict";
37208
+ init_dist();
37209
+ init_agentid();
37210
+ keyedDigest = (args, key) => "hmac-sha256:" + createHmac("sha256", key).update(canonicalize(JSON.parse(JSON.stringify(args ?? {})))).digest("hex");
37211
+ revokedInChain = (entries) => entries.some((e) => e.result.code === "revoked");
37212
+ approvalUsedInChain = (entries, rid) => entries.some((e) => /approved by/.test(String(e.receipt.reason ?? "")) && String(e.receipt.reason ?? "").includes(`(${rid})`));
37213
+ cpCore = (cp) => {
37214
+ const { witnesses: _w, ...rest } = cp;
37215
+ return rest;
37216
+ };
37217
+ }
37218
+ });
37219
+
37220
+ // packages/testkit-core/dist/webauthn.js
37221
+ import { createHash as createHash3, createPublicKey as createPublicKey2, verify as verify2 } from "node:crypto";
37222
+ function decodeCbor(buf) {
37223
+ let i = 0;
37224
+ const read = () => {
37225
+ const ib = buf[i++], mt = ib >> 5, ai = ib & 31;
37226
+ let len = ai;
37227
+ if (ai === 24)
37228
+ len = buf[i++];
37229
+ else if (ai === 25) {
37230
+ len = buf[i] << 8 | buf[i + 1];
37231
+ i += 2;
37232
+ } else if (ai === 26) {
37233
+ len = (buf[i] << 24 >>> 0) + (buf[i + 1] << 16) + (buf[i + 2] << 8) + buf[i + 3];
37234
+ i += 4;
37235
+ } else if (ai > 26)
37236
+ throw new Error("unsupported CBOR length");
37237
+ switch (mt) {
37238
+ case 0:
37239
+ return len;
37240
+ case 1:
37241
+ return -1 - len;
37242
+ case 2: {
37243
+ const v = buf.slice(i, i + len);
37244
+ i += len;
37245
+ return v;
37246
+ }
37247
+ case 3: {
37248
+ const v = new TextDecoder().decode(buf.slice(i, i + len));
37249
+ i += len;
37250
+ return v;
37251
+ }
37252
+ case 4: {
37253
+ const a = [];
37254
+ for (let k = 0; k < len; k++)
37255
+ a.push(read());
37256
+ return a;
37257
+ }
37258
+ case 5: {
37259
+ const m = /* @__PURE__ */ new Map();
37260
+ for (let k = 0; k < len; k++) {
37261
+ const key = read();
37262
+ m.set(key, read());
37263
+ }
37264
+ return m;
37265
+ }
37266
+ case 7:
37267
+ return ai === 20 ? false : ai === 21 ? true : null;
37268
+ default:
37269
+ throw new Error("unsupported CBOR type");
37270
+ }
37271
+ };
37272
+ const value = read();
37273
+ return { value, length: i };
37274
+ }
37275
+ function coseToJwk(m) {
37276
+ const kty = m.get(1), alg = m.get(3);
37277
+ if (kty === 2 && alg === -7)
37278
+ return { kty: "EC", crv: "P-256", x: b64u3(m.get(-2)), y: b64u3(m.get(-3)) };
37279
+ if (kty === 1 && alg === -8)
37280
+ return { kty: "OKP", crv: "Ed25519", x: b64u3(m.get(-2)) };
37281
+ throw new Error("unsupported passkey algorithm (ES256 and EdDSA are supported)");
37282
+ }
37283
+ function checkClientData(clientDataJSON, type, challenge, origin) {
37284
+ const c = JSON.parse(Buffer.from(clientDataJSON, "base64url").toString("utf8"));
37285
+ if (c.type !== type)
37286
+ throw new Error("wrong client data type");
37287
+ if (c.challenge !== b64u3(Buffer.from(challenge)))
37288
+ throw new Error("challenge does not match");
37289
+ if (c.origin !== origin)
37290
+ throw new Error("origin does not match");
37291
+ }
37292
+ function verifyPasskeyRegistration(r, expected) {
37293
+ checkClientData(r.clientDataJSON, "webauthn.create", expected.challenge, expected.origin);
37294
+ const att = decodeCbor(Buffer.from(r.attestationObject, "base64url")).value;
37295
+ const ad = att.get("authData");
37296
+ if (!Buffer.from(ad.slice(0, 32)).equals(sha256(expected.rpId)))
37297
+ throw new Error("relying party does not match");
37298
+ const flags = ad[32];
37299
+ if (!(flags & 1))
37300
+ throw new Error("user presence not confirmed");
37301
+ if (!(flags & 64))
37302
+ throw new Error("no credential data");
37303
+ const idLen = ad[53] << 8 | ad[54];
37304
+ const credentialId = b64u3(ad.slice(55, 55 + idLen));
37305
+ const jwk = coseToJwk(decodeCbor(ad.slice(55 + idLen)).value);
37306
+ return { credentialId, jwk };
37307
+ }
37308
+ function verifyPasskeyAssertion(a, jwk, expected) {
37309
+ checkClientData(a.clientDataJSON, "webauthn.get", expected.challenge, expected.origin);
37310
+ const ad = Buffer.from(a.authenticatorData, "base64url");
37311
+ if (!ad.slice(0, 32).equals(sha256(expected.rpId)))
37312
+ throw new Error("relying party does not match");
37313
+ if (!(ad[32] & 1))
37314
+ throw new Error("user presence not confirmed");
37315
+ const data = Buffer.concat([ad, sha256(Buffer.from(a.clientDataJSON, "base64url"))]);
37316
+ const key = createPublicKey2({ key: jwk, format: "jwk" });
37317
+ return jwk.kty === "OKP" ? verify2(null, data, key, Buffer.from(a.signature, "base64url")) : verify2("sha256", data, key, Buffer.from(a.signature, "base64url"));
37318
+ }
37319
+ var sha256, b64u3;
37320
+ var init_webauthn = __esm({
37321
+ "packages/testkit-core/dist/webauthn.js"() {
37322
+ "use strict";
37323
+ sha256 = (b) => createHash3("sha256").update(b).digest();
37324
+ b64u3 = (b) => Buffer.from(b).toString("base64url");
37325
+ }
37326
+ });
37327
+
36916
37328
  // packages/testkit-core/dist/index.js
36917
37329
  var dist_exports = {};
36918
37330
  __export(dist_exports, {
@@ -36959,9 +37371,11 @@ __export(dist_exports, {
36959
37371
  allowlistFromLedger: () => allowlistFromLedger,
36960
37372
  analyseSetup: () => analyseSetup,
36961
37373
  analysers: () => analysers,
37374
+ appendStatement: () => appendStatement,
36962
37375
  appendTestCase: () => appendTestCase,
36963
37376
  appendToLedger: () => appendToLedger,
36964
37377
  approvalRequestId: () => approvalRequestId,
37378
+ approvalUsedInChain: () => approvalUsedInChain,
36965
37379
  approveAction: () => approveAction,
36966
37380
  argumentsHash: () => argumentsHash,
36967
37381
  attestationToCredential: () => attestationToCredential,
@@ -36978,6 +37392,7 @@ __export(dist_exports, {
36978
37392
  checkMandate: () => checkMandate,
36979
37393
  checkNeedsSession: () => checkNeedsSession,
36980
37394
  checkOperator: () => checkOperator,
37395
+ checkStatement: () => checkStatement,
36981
37396
  clientCompatibility: () => clientCompatibility,
36982
37397
  compileContract: () => compileContract,
36983
37398
  compileUntrustedSchema: () => compileUntrustedSchema,
@@ -37009,15 +37424,19 @@ __export(dist_exports, {
37009
37424
  invalidArgProblems: () => invalidArgProblems,
37010
37425
  invalidArgsFor: () => invalidArgsFor,
37011
37426
  issueCredential: () => issueCredential,
37427
+ keyedDigest: () => keyedDigest,
37012
37428
  kpis: () => kpis,
37013
37429
  leakageAnalysers: () => leakageAnalysers,
37430
+ ledgerStatus: () => ledgerStatus,
37014
37431
  lintPaths: () => lintPaths,
37015
37432
  lintSarif: () => lintSarif,
37016
37433
  lintSource: () => lintSource,
37434
+ listPending: () => listPending,
37017
37435
  loadEmbeddedPacks: () => loadEmbeddedPacks,
37018
37436
  loadPack: () => loadPack,
37019
37437
  loadPackDir: () => loadPackDir,
37020
37438
  loadPackText: () => loadPackText,
37439
+ makeCheckpoint: () => makeCheckpoint,
37021
37440
  mandateDecision: () => mandateDecision,
37022
37441
  mandateDigest: () => mandateDigest,
37023
37442
  maxDepth: () => maxDepth,
@@ -37035,6 +37454,7 @@ __export(dist_exports, {
37035
37454
  perfAnalysers: () => perfAnalysers,
37036
37455
  readinessFor: () => readinessFor,
37037
37456
  receiptsToOtlp: () => receiptsToOtlp,
37457
+ recordPending: () => recordPending,
37038
37458
  redactCommand: () => redactCommand,
37039
37459
  redactUrl: () => redactUrl,
37040
37460
  renderFix: () => renderFix,
@@ -37044,6 +37464,7 @@ __export(dist_exports, {
37044
37464
  resultProblems: () => resultProblems,
37045
37465
  revocationOf: () => revocationOf,
37046
37466
  revokeMandate: () => revokeMandate,
37467
+ revokedInChain: () => revokedInChain,
37047
37468
  riskTier: () => riskTier,
37048
37469
  roiEstimate: () => roiEstimate,
37049
37470
  runCheck: () => runCheck,
@@ -37051,12 +37472,14 @@ __export(dist_exports, {
37051
37472
  runTestCases: () => runTestCases,
37052
37473
  runTrustCheck: () => runTrustCheck,
37053
37474
  sanitizeText: () => sanitizeText,
37475
+ scanAgents: () => scanAgents,
37054
37476
  schemaDialect: () => schemaDialect,
37055
37477
  score: () => score,
37056
37478
  searchCatalogue: () => searchCatalogue,
37057
37479
  semanticValues: () => semanticValues,
37058
37480
  signCredentialJwt: () => signCredentialJwt,
37059
37481
  signReceipt: () => signReceipt,
37482
+ signRevocation: () => signRevocation,
37060
37483
  sourceFiles: () => sourceFiles,
37061
37484
  splitCommand: () => splitCommand,
37062
37485
  subjectFromResult: () => subjectFromResult,
@@ -37070,15 +37493,23 @@ __export(dist_exports, {
37070
37493
  topUp: () => topUp,
37071
37494
  trustStatement: () => trustStatement,
37072
37495
  usageStatement: () => usageStatement,
37496
+ validRevocation: () => validRevocation,
37497
+ validWitnesses: () => validWitnesses,
37498
+ verifyAgainstCheckpoint: () => verifyAgainstCheckpoint,
37073
37499
  verifyAgreement: () => verifyAgreement,
37074
37500
  verifyChain: () => verifyChain,
37075
37501
  verifyCredentialJwt: () => verifyCredentialJwt,
37502
+ verifyDomain: () => verifyDomain,
37076
37503
  verifyLedger: () => verifyLedger,
37504
+ verifyPasskeyAssertion: () => verifyPasskeyAssertion,
37505
+ verifyPasskeyRegistration: () => verifyPasskeyRegistration,
37077
37506
  verifyReceipt: () => verifyReceipt,
37078
37507
  verifyReceiptLog: () => verifyReceiptLog,
37508
+ verifyWallet: () => verifyWallet,
37079
37509
  walletBalance: () => walletBalance,
37080
37510
  watchAllowlist: () => watchAllowlist,
37081
- wellKnownUrls: () => wellKnownUrls
37511
+ wellKnownUrls: () => wellKnownUrls,
37512
+ witnessCheckpoint: () => witnessCheckpoint
37082
37513
  });
37083
37514
  var init_dist4 = __esm({
37084
37515
  "packages/testkit-core/dist/index.js"() {
@@ -37114,6 +37545,9 @@ var init_dist4 = __esm({
37114
37545
  init_vocab();
37115
37546
  init_market();
37116
37547
  init_crosswalk();
37548
+ init_agents();
37549
+ init_trust();
37550
+ init_webauthn();
37117
37551
  }
37118
37552
  });
37119
37553
 
@@ -37198,7 +37632,7 @@ function renderPassportGallery(entries) {
37198
37632
  }).join("");
37199
37633
  return page("MCP Server Passports: the Saktum trust ledger", `<div class="card"><small>SAKTUM TRUST LEDGER</small><h1>MCP Server Passports</h1><p class="muted">Servers whose publishers recorded a signed Saktum attestation in the public, append-only ledger. Anyone can verify every entry: <code>npx saktum ledger verify</code>. Add yours: <code>npx saktum attest saktum-report.json --publish</code>.</p></div>${cards || `<p class="muted">No entries yet.</p>`}`);
37200
37634
  }
37201
- function renderAssessment(org, f, receipts = [], roi, frameworks, disclaimer) {
37635
+ function renderAssessment(org, f, receipts = [], roi, frameworks, disclaimer, agents) {
37202
37636
  const risky = /* @__PURE__ */ new Set(["code-execution", "money", "sends-messages", "writes-or-deletes", "reads-private-data"]);
37203
37637
  const caps = ["code-execution", "money", "sends-messages", "writes-or-deletes", "reads-private-data", "network", "filesystem", "untrusted-content"];
37204
37638
  const grades = ["A", "B", "C", "D", "F", "-"];
@@ -37226,11 +37660,20 @@ function renderAssessment(org, f, receipts = [], roi, frameworks, disclaimer) {
37226
37660
  <div class="card"><h2>Servers needing attention</h2>${top ? `<div class="wrap"><table><tr><th>Server</th><th>Machines</th><th>Trust / readiness</th><th>Why</th></tr>${top}</table></div>` : `<p>None: every assessed server meets the policy.</p>`}</div>
37227
37661
  ${rc ? `<div class="card"><h2>Agent receipts</h2><div class="wrap"><table><tr><th>Agent</th><th>Calls</th><th>Blocked</th><th>Destructive</th><th>Repeated calls</th><th>Receipts</th></tr>${rc}</table></div></div>` : ""}
37228
37662
  ${roi ? `<div class="card"><h2>Business case</h2><div class="grid"><div class="kv"><small>Tool definitions cost a year</small><b>$${roi.annualToolCost.toLocaleString("en-US")}</b></div><div class="kv"><small>Savings from fixes</small><b>$${roi.tokenSavings.toLocaleString("en-US")}</b></div><div class="kv"><small>Review effort replaced by passports</small><b>$${roi.reviewSavings.toLocaleString("en-US")}</b></div><div class="kv"><small>Total a year</small><b>$${roi.totalSavings.toLocaleString("en-US")}</b></div></div><p class="muted">Estimate. Assumptions: ${esc2(roi.assumptions)}. Replace them with your own figures.</p></div>` : ""}
37663
+ ${agents ? `<div class="card"><h2>Agents</h2>${agents.length ? `<div class="wrap"><table><tr><th>Agent</th><th>Owner</th><th>Operator</th><th>Autonomy</th><th>Risk</th><th>Maturity</th><th>Status</th></tr>${agents.map((a) => `<tr><td>${esc2(a.name)}</td><td>${esc2(a.owner)}</td><td>${esc2(a.operator || "none")}</td><td>${esc2(a.autonomy)}</td><td>${esc2(a.riskTier)}</td><td>${esc2(a.maturity)}</td><td>${a.revoked ? "revoked" : !a.valid ? "invalid or expired" : "active until " + esc2(a.expires)}</td></tr>`).join("")}</table></div>` : `<p>No agent mandates found.</p>`}<p class="muted">From <code>npx saktum agents scan</code>. Agents without an operator countersignature, or with broad autonomy on risky tiers, deserve review first.</p></div>` : ""}
37229
37664
  ${frameworks?.length ? `<div class="card"><h2>Evidence for the frameworks you are held to</h2><div class="wrap"><table><tr><th>Framework</th><th>Covered</th><th>Partly</th><th>Not covered</th></tr>${frameworks.map((x) => `<tr><td>${esc2(x.name)}</td><td>${x.summary.covered}</td><td>${x.summary.partial}</td><td>${x.summary.gap}</td></tr>`).join("")}</table></div><p class="muted">${esc2(disclaimer ?? "")} Details: <code>npx saktum evidence --framework all</code>.</p></div>` : ""}
37230
37665
  <div class="card"><h2>Recommendations</h2><ol>${rec.map((x) => `<li>${esc2(x)}</li>`).join("")}</ol></div>
37231
37666
  <div class="card"><h2>Next steps</h2><p>1. Agree the policy and exceptions with security. 2. Enforce it in CI on MCP repositories. 3. Deploy the allowlist to the MCP firewall or gateway. 4. Extend agent mandates and receipts to production agent workflows with the Saktum gateway (design partnership).</p><p class="muted">Findings describe the servers and agents at the time of assessment and are not a guarantee of security.</p></div>`;
37232
37667
  return page(`MCP Trust Assessment: ${org}`, body2);
37233
37668
  }
37669
+ function renderReceiptsView(logs) {
37670
+ const all = logs.flatMap((l) => l.entries.map((e) => ({ ...e, log: l.name }))).sort((a, b) => a.at.localeCompare(b.at));
37671
+ const sum = logs.map((l) => `<tr><td>${esc2(l.name)}</td><td>${l.entries.length}</td><td>${l.entries.filter((e) => e.outcome === "allow").length}</td><td>${l.entries.filter((e) => e.outcome === "deny").length}</td><td>${l.entries.reduce((n, e) => n + e.tokens, 0)}</td><td>${l.verified ? "\u2713 verified" : "\u2717 NOT verified"}</td></tr>`).join("");
37672
+ const rows = all.slice(-500).map((e) => `<tr><td><code>${esc2(e.at.slice(0, 19).replace("T", " "))}</code></td><td>${esc2(e.agent)}</td><td>${esc2(e.tool)}</td><td><span class="step ${e.outcome === "deny" ? "deny" : "ok"}">${e.outcome === "deny" ? "\u26D4 " + esc2(e.code) : "\u2713"}</span></td><td>${esc2(e.reason)}</td><td>${e.tokens || ""}</td></tr>`).join("");
37673
+ return page("Saktum receipts: combined view", `<div class="card"><small>RECEIPTS \xB7 COMBINED VIEW</small><h1>${all.length} agent calls across ${logs.length} log(s)</h1><p class="muted">Each log verified independently: every signature and every link of its hash chain.</p>
37674
+ <div class="wrap"><table><tr><th>Log</th><th>Calls</th><th>Allowed</th><th>Blocked</th><th>Tokens</th><th>Integrity</th></tr>${sum}</table></div></div>
37675
+ <div class="card"><h2>Timeline</h2><div class="wrap"><table><tr><th>Time (UTC)</th><th>Agent</th><th>Tool</th><th>Decision</th><th>Reason</th><th>Tokens</th></tr>${rows}</table></div>${all.length > 500 ? `<p class="muted">Latest 500 of ${all.length}.</p>` : ""}</div>`);
37676
+ }
37234
37677
  var esc2, GRADE_COLOUR, chip, STYLE, page, levelBar, effect, passportSlug, evidenceLevel;
37235
37678
  var init_passport = __esm({
37236
37679
  "packages/report/dist/passport.js"() {
@@ -37581,9 +38024,9 @@ __export(init_exports, {
37581
38024
  initProject: () => initProject
37582
38025
  });
37583
38026
  import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
37584
- import { join as join4 } from "node:path";
38027
+ import { join as join5 } from "node:path";
37585
38028
  function initProject(dir, lang, name) {
37586
- if (existsSync4(join4(dir, "package.json")) || existsSync4(join4(dir, "pyproject.toml")) || existsSync4(join4(dir, "server.py")))
38029
+ if (existsSync4(join5(dir, "package.json")) || existsSync4(join5(dir, "pyproject.toml")) || existsSync4(join5(dir, "server.py")))
37587
38030
  throw new Error(`${dir} already contains a project; choose an empty folder.`);
37588
38031
  const id = name.replace(/[^a-z0-9-]/gi, "-").toLowerCase() || "my-mcp-server";
37589
38032
  const files = {};
@@ -37672,8 +38115,8 @@ if __name__ == "__main__":
37672
38115
 
37673
38116
  ${AGENT_RULES}`;
37674
38117
  for (const [p, text2] of Object.entries(files)) {
37675
- const f = join4(dir, p);
37676
- mkdirSync3(join4(f, ".."), { recursive: true });
38118
+ const f = join5(dir, p);
38119
+ mkdirSync3(join5(f, ".."), { recursive: true });
37677
38120
  writeFileSync3(f, text2);
37678
38121
  }
37679
38122
  return Object.keys(files);
@@ -37760,8 +38203,9 @@ var proxy_exports = {};
37760
38203
  __export(proxy_exports, {
37761
38204
  runProxy: () => runProxy
37762
38205
  });
38206
+ import { createHmac as createHmac2 } from "node:crypto";
37763
38207
  import { spawn as spawn3 } from "node:child_process";
37764
- import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "node:fs";
38208
+ import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7 } from "node:fs";
37765
38209
  import { dirname as dirname3 } from "node:path";
37766
38210
  import { createInterface } from "node:readline";
37767
38211
  import { randomUUID } from "node:crypto";
@@ -37770,7 +38214,7 @@ async function runProxy(o) {
37770
38214
  let last;
37771
38215
  let history = [];
37772
38216
  if (existsSync5(o.receiptsPath)) {
37773
- history = parseReceiptLog(readFileSync6(o.receiptsPath, "utf8"));
38217
+ history = parseReceiptLog(readFileSync7(o.receiptsPath, "utf8"));
37774
38218
  last = history[history.length - 1];
37775
38219
  }
37776
38220
  const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
@@ -37784,6 +38228,25 @@ async function runProxy(o) {
37784
38228
  const bare = !/[\\/]/.test(o.command);
37785
38229
  const child = spawn3(o.command, o.args, { stdio: ["pipe", "pipe", "inherit"], shell: process.platform === "win32" && (bare || /\.(cmd|bat)$/i.test(o.command)) });
37786
38230
  let service = o.command.split(/[\\/]/).pop() ?? o.command, version2;
38231
+ let remoteRevoked = false, toolsChanged = false;
38232
+ const pollRevocations = async () => {
38233
+ if (!o.revocationsUrl || !o.mandate)
38234
+ return;
38235
+ try {
38236
+ const r = await fetch(o.revocationsUrl);
38237
+ if (r.ok) {
38238
+ const j = await r.json();
38239
+ const list = Array.isArray(j) ? j : j.revoked ?? [];
38240
+ if (list.some((e) => validRevocation(e, o.mandate)))
38241
+ remoteRevoked = true;
38242
+ }
38243
+ } catch {
38244
+ }
38245
+ };
38246
+ await pollRevocations();
38247
+ if (o.revocationsUrl)
38248
+ setInterval(pollRevocations, 5 * 6e4).unref();
38249
+ const digest = (args) => o.digestKey ? keyedDigest(args, o.digestKey) : argumentsHash(args);
37787
38250
  const annotations = /* @__PURE__ */ new Map();
37788
38251
  const toolDefs = /* @__PURE__ */ new Map();
37789
38252
  const pendingKinds = /* @__PURE__ */ new Map();
@@ -37815,6 +38278,12 @@ async function runProxy(o) {
37815
38278
  appendFileSync(o.receiptsPath, JSON.stringify(entry) + "\n");
37816
38279
  last = entry;
37817
38280
  history.push(entry);
38281
+ if (o.checkpointEvery && o.checkpointFile && entry.seq % o.checkpointEvery === 0) {
38282
+ try {
38283
+ appendFileSync(o.checkpointFile, JSON.stringify(makeCheckpoint(history, o.agentKey)) + "\n");
38284
+ } catch {
38285
+ }
38286
+ }
37818
38287
  };
37819
38288
  createInterface({ input: process.stdin }).on("line", (line) => {
37820
38289
  let msg;
@@ -37829,58 +38298,74 @@ async function runProxy(o) {
37829
38298
  if (msg.method === "tools/call" && msg.id !== void 0) {
37830
38299
  const tool = String(msg.params?.name ?? "");
37831
38300
  const args = msg.params?.arguments ?? {};
37832
- const argsHash = argumentsHash(args);
38301
+ const argsHash = digest(args);
37833
38302
  const ann = annotations.get(tool);
37834
38303
  const def = toolDefs.get(tool);
37835
38304
  const isMoney = def ? capabilityProfile([def]).capabilities.some((c) => c.capability === "money") : false;
37836
38305
  const values = Object.fromEntries([...governed].filter((k) => args[k] !== void 0 && (typeof args[k] === "number" || typeof args[k] === "string")).map((k) => [k, args[k]]));
37837
- const rev = o.mandate ? revocationOf(o.mandate, o.revocationsPath) : void 0;
37838
- let d = rev ? { allow: false, code: "revoked", reason: `the mandate was revoked on ${rev.at.slice(0, 10)}${rev.reason ? ` (${rev.reason})` : ""}` } : o.mandate ? decideCall(o.mandate, { tool, server: service, args, annotations: ann, isMoney, usage: usage() }) : { allow: true, code: "ok", reason: "no mandate: observed" };
38306
+ let d;
37839
38307
  let rationale;
37840
- if (d.allow && o.mandate && hasIntent(o.mandate)) {
37841
- const di = decideIntent(o.mandate, def ?? { name: tool }, args, { server: service });
37842
- rationale = di.rationale;
37843
- for (const [k, val] of Object.entries(di.values))
37844
- if (typeof val === "number" || typeof val === "string" || typeof val === "boolean")
37845
- values[k] = val;
37846
- if (!di.allow)
37847
- d = { allow: false, code: di.code, reason: di.reason };
37848
- else if (di.reason !== "within the mandate")
37849
- d = { allow: true, code: "ok", reason: di.reason };
37850
- }
37851
- if (!d.allow && d.code === "approval-needed" && o.mandate) {
37852
- const rid = approvalRequestId(o.mandate, tool, args);
37853
- const ap = consumeApproval(o.mandate, rid, o.approvalsPath);
37854
- if (ap.ok)
37855
- d = { allow: true, code: "ok", reason: `approved by ${ap.by} (${rid}), after: ${d.reason}` };
37856
- else
37857
- d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
37858
- }
37859
- if (d.allow && o.credential) {
37860
- const vc = verifyChain(o.credential, { revoked: o.revokedCredentials });
37861
- const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
37862
- if (!vc.valid)
37863
- d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
37864
- else if (o.agreement && root !== o.agreement.invoker.id)
37865
- d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
37866
- }
37867
38308
  let metering;
37868
- if (d.allow && o.agreement) {
37869
- const va = verifyAgreement(o.agreement);
37870
- if (!va.valid)
37871
- d = { allow: false, code: "no-valid-agreement", reason: `no valid agreement with the provider: ${va.reason}` };
37872
- else if (o.agreement.scope.tools && !o.agreement.scope.tools.includes(tool))
37873
- d = { allow: false, code: "outside-agreement", reason: `${tool} is outside the agreement ${o.agreement.id}` };
37874
- else if (o.walletPath) {
37875
- const ch = chargeCall(o.walletPath, o.agreement, tool, `${o.agreement.id}:${tool}`);
37876
- if (!ch.ok)
37877
- d = { allow: false, code: "insufficient-credit", reason: `${tool} costs ${ch.tokens} tokens; the prepaid balance is ${ch.balance}` };
37878
- else
37879
- metering = { agreement: o.agreement.id, tokens: ch.tokens, balance: ch.balance };
37880
- } else
37881
- metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
38309
+ try {
38310
+ const rev = o.mandate ? revocationOf(o.mandate, o.revocationsPath) : void 0;
38311
+ d = rev ? { allow: false, code: "revoked", reason: `the mandate was revoked on ${rev.at.slice(0, 10)}${rev.reason ? ` (${rev.reason})` : ""}` } : o.mandate && (remoteRevoked || revokedInChain(history)) ? { allow: false, code: "revoked", reason: "the mandate was revoked (recorded in the ledger or in this receipt chain)" } : toolsChanged ? { allow: false, code: "tools-changed", reason: "the server's tools differ from the pinned, approved fingerprint" } : o.mandate ? decideCall(o.mandate, { tool, server: service, args, annotations: ann, isMoney, usage: usage() }) : { allow: true, code: "ok", reason: "no mandate: observed" };
38312
+ if (d.allow && o.mandate && hasIntent(o.mandate)) {
38313
+ const di = decideIntent(o.mandate, def ?? { name: tool }, args, { server: service });
38314
+ rationale = di.rationale;
38315
+ for (const [k, val] of Object.entries(di.values))
38316
+ if (typeof val === "number" || typeof val === "string" || typeof val === "boolean")
38317
+ values[k] = val;
38318
+ if (!di.allow)
38319
+ d = { allow: false, code: di.code, reason: di.reason };
38320
+ else if (di.reason !== "within the mandate")
38321
+ d = { allow: true, code: "ok", reason: di.reason };
38322
+ }
38323
+ if (!d.allow && d.code === "approval-needed" && o.mandate) {
38324
+ const rid = approvalRequestId(o.mandate, tool, args);
38325
+ const ap = approvalUsedInChain(history, rid) ? { ok: false } : consumeApproval(o.mandate, rid, o.approvalsPath);
38326
+ if (ap.ok)
38327
+ d = { allow: true, code: "ok", reason: `approved by ${ap.by} (${rid}), after: ${d.reason}` };
38328
+ else {
38329
+ d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
38330
+ try {
38331
+ recordPending(o.approvalsPath ?? DEFAULT_APPROVALS(), { id: rid, tool, reason: d.reason, agent: o.mandate.agent.name });
38332
+ } catch {
38333
+ }
38334
+ if (o.approvalWebhook) {
38335
+ const t = o.approvalSecret ? createHmac2("sha256", o.approvalSecret).update(rid).digest("hex").slice(0, 32) : "";
38336
+ const link = o.approvalUrl ? `${o.approvalUrl}${o.approvalUrl.includes("?") ? "&" : "?"}id=${rid}${t ? `&t=${t}` : ""}` : "";
38337
+ const text2 = `Approval needed: ${o.mandate.agent.name} wants to run ${tool}. ${d.reason.replace(/ \[approval request [^\]]+\]/, "")}. Request ${rid}. ${link ? `Approve: ${link}` : `Approve with: npx saktum agent approve ${rid} --mandate <mandate>`}`;
38338
+ fetch(o.approvalWebhook, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: text2, requestId: rid, tool, agent: o.mandate.agent.name, ...link ? { approveUrl: link } : {} }) }).catch(() => void 0);
38339
+ }
38340
+ }
38341
+ }
38342
+ if (d.allow && o.credential) {
38343
+ const vc = verifyChain(o.credential, { revoked: o.revokedCredentials });
38344
+ const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
38345
+ if (!vc.valid)
38346
+ d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
38347
+ else if (o.agreement && root !== o.agreement.invoker.id)
38348
+ d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
38349
+ }
38350
+ if (d.allow && o.agreement) {
38351
+ const va = verifyAgreement(o.agreement);
38352
+ if (!va.valid)
38353
+ d = { allow: false, code: "no-valid-agreement", reason: `no valid agreement with the provider: ${va.reason}` };
38354
+ else if (o.agreement.scope.tools && !o.agreement.scope.tools.includes(tool))
38355
+ d = { allow: false, code: "outside-agreement", reason: `${tool} is outside the agreement ${o.agreement.id}` };
38356
+ else if (o.walletPath) {
38357
+ const ch = chargeCall(o.walletPath, o.agreement, tool, `${o.agreement.id}:${tool}`, o.agentKey);
38358
+ if (!ch.ok)
38359
+ d = { allow: false, code: "insufficient-credit", reason: `${tool} costs ${ch.tokens} tokens; the prepaid balance is ${ch.balance}` };
38360
+ else
38361
+ metering = { agreement: o.agreement.id, tokens: ch.tokens, balance: ch.balance };
38362
+ } else
38363
+ metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
38364
+ }
38365
+ } catch (err) {
38366
+ d = { allow: false, code: "error-fail-closed", reason: `the decision could not be completed, so the call is refused (${String(err.message).slice(0, 120)})` };
37882
38367
  }
37883
- if (!d.allow && o.enforce) {
38368
+ if (!d.allow && (o.enforce || d.code === "error-fail-closed")) {
37884
38369
  const hint = d.code === "revoked" ? " The agent's owner stopped it; do not retry." : d.code === "approval-needed" ? " Ask your user to approve it (saktum agent approve with the request id), then retry the same action once." : d.code === "notify-only" ? " Tell your user what you found instead." : " Ask the agent's owner to change the mandate if this action is needed.";
37885
38370
  process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { isError: true, content: [{ type: "text", text: `Blocked by Saktum (${d.code}): ${d.reason}.${hint}` }] } }) + "\n");
37886
38371
  record2(tool, argsHash, "deny", d.reason, { status: "blocked", destructive: isDestructive(ann), code: d.code, values, ...rationale ? { rationale } : {} });
@@ -37921,8 +38406,16 @@ async function runProxy(o) {
37921
38406
  }
37922
38407
  if (kind === "tools/list" && Array.isArray(msg.result?.tools)) {
37923
38408
  for (const t of msg.result.tools) {
38409
+ const ov = o.bindingsOverride?.[t.name];
38410
+ const def = ov ? { ...t, _meta: { ...t._meta ?? {}, ...ov.action ? { "io.saktum/action": ov.action } : {}, ...ov.bindings ? { "io.saktum/bindings": ov.bindings } : {} } } : t;
37924
38411
  annotations.set(t.name, t.annotations);
37925
- toolDefs.set(t.name, t);
38412
+ toolDefs.set(t.name, def);
38413
+ }
38414
+ if (o.pin) {
38415
+ const fp = sha256Tag(canonicalize([...msg.result.tools].sort((a, b) => String(a.name).localeCompare(String(b.name)))));
38416
+ toolsChanged = fp !== o.pin;
38417
+ if (toolsChanged)
38418
+ o.log?.(`tools changed: ${fp} differs from the pinned ${o.pin}`);
37926
38419
  }
37927
38420
  pendingKinds.delete(k);
37928
38421
  }
@@ -37943,10 +38436,82 @@ async function runProxy(o) {
37943
38436
  var init_proxy = __esm({
37944
38437
  "packages/cli/dist/proxy.js"() {
37945
38438
  "use strict";
38439
+ init_dist();
37946
38440
  init_dist4();
37947
38441
  }
37948
38442
  });
37949
38443
 
38444
+ // packages/cli/dist/bridge.js
38445
+ var bridge_exports = {};
38446
+ __export(bridge_exports, {
38447
+ runBridge: () => runBridge
38448
+ });
38449
+ import { createInterface as createInterface2 } from "node:readline";
38450
+ async function runBridge(url2, headers) {
38451
+ let session;
38452
+ const out = (m) => process.stdout.write(JSON.stringify(m) + "\n");
38453
+ const rl = createInterface2({ input: process.stdin });
38454
+ const pending = [];
38455
+ const forward = async (line) => {
38456
+ let msg = {};
38457
+ try {
38458
+ msg = JSON.parse(line);
38459
+ } catch {
38460
+ return;
38461
+ }
38462
+ try {
38463
+ const res = await fetch(url2, {
38464
+ method: "POST",
38465
+ body: line,
38466
+ headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream", ...session ? { "Mcp-Session-Id": session } : {}, ...headers }
38467
+ });
38468
+ const sid = res.headers.get("mcp-session-id");
38469
+ if (sid)
38470
+ session = sid;
38471
+ const text2 = await res.text();
38472
+ if (msg.id === void 0 || res.status === 202)
38473
+ return;
38474
+ if (!res.ok && !text2.trim()) {
38475
+ out({ jsonrpc: "2.0", id: msg.id, error: { code: -32e3, message: `upstream HTTP ${res.status}` } });
38476
+ return;
38477
+ }
38478
+ if ((res.headers.get("content-type") ?? "").includes("text/event-stream")) {
38479
+ for (const l of text2.split(/\r?\n/))
38480
+ if (l.startsWith("data:")) {
38481
+ const d = l.slice(5).trim();
38482
+ if (d)
38483
+ process.stdout.write(d + "\n");
38484
+ }
38485
+ } else if (text2.trim()) {
38486
+ const j = JSON.parse(text2);
38487
+ for (const m of Array.isArray(j) ? j : [j])
38488
+ out(m);
38489
+ }
38490
+ } catch (e) {
38491
+ if (msg.id !== void 0)
38492
+ out({ jsonrpc: "2.0", id: msg.id, error: { code: -32e3, message: `upstream unreachable: ${String(e.message).slice(0, 120)}` } });
38493
+ }
38494
+ };
38495
+ rl.on("line", (line) => {
38496
+ if (line.trim())
38497
+ pending.push(forward(line));
38498
+ });
38499
+ await new Promise((r) => rl.on("close", () => r()));
38500
+ await Promise.allSettled(pending);
38501
+ if (session) {
38502
+ try {
38503
+ await fetch(url2, { method: "DELETE", headers: { "Mcp-Session-Id": session, ...headers } });
38504
+ } catch {
38505
+ }
38506
+ }
38507
+ return 0;
38508
+ }
38509
+ var init_bridge = __esm({
38510
+ "packages/cli/dist/bridge.js"() {
38511
+ "use strict";
38512
+ }
38513
+ });
38514
+
37950
38515
  // node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
37951
38516
  var ExperimentalServerTasks;
37952
38517
  var init_server = __esm({
@@ -38629,8 +39194,8 @@ __export(demo_exports, {
38629
39194
  runDemo: () => runDemo,
38630
39195
  startDemoServer: () => startDemoServer
38631
39196
  });
38632
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync4, existsSync as existsSync6, rmSync } from "node:fs";
38633
- import { join as join5 } from "node:path";
39197
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync4, existsSync as existsSync6, rmSync } from "node:fs";
39198
+ import { join as join6 } from "node:path";
38634
39199
  async function startDemoServer(story = "autonomy") {
38635
39200
  const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : story === "coding" ? CODING_TOOLS : DEMO_TOOLS;
38636
39201
  const server = new Server({ name: story === "travel" ? "demo-travel" : story === "finance" ? "demo-finance" : "demo-grocer", version: "1.0.0" }, { capabilities: { tools: {} } });
@@ -38688,7 +39253,7 @@ async function startDemoServer(story = "autonomy") {
38688
39253
  }
38689
39254
  async function runStory(dir, st, owner, log) {
38690
39255
  const self = [...process.execArgv, process.argv[1]];
38691
- const agentKey = loadOrCreateKey(join5(dir, `${st.id}-agent-key.json`));
39256
+ const agentKey = loadOrCreateKey(join6(dir, `${st.id}-agent-key.json`));
38692
39257
  const m = createMandate({
38693
39258
  agentId: agentKey.kid,
38694
39259
  agentName: `${st.id === "travel" ? "Travel" : "Shopping"} agent`,
@@ -38699,14 +39264,14 @@ async function runStory(dir, st, owner, log) {
38699
39264
  ...st.m
38700
39265
  }, owner);
38701
39266
  const operatorName = String(st.m.disclosures?.operator ?? "Demo operator");
38702
- const cm = cosignMandate(m, loadOrCreateKey(join5(dir, `${st.id}-operator-key.json`)), operatorName);
38703
- const mf = join5(dir, `${st.id}-mandate.json`), rf = join5(dir, `${st.id}-receipts.jsonl`), revf = join5(dir, "revocations.json");
39267
+ const cm = cosignMandate(m, loadOrCreateKey(join6(dir, `${st.id}-operator-key.json`)), operatorName);
39268
+ const mf = join6(dir, `${st.id}-mandate.json`), rf = join6(dir, `${st.id}-receipts.jsonl`), revf = join6(dir, "revocations.json");
38704
39269
  writeFileSync4(mf, JSON.stringify(cm, null, 2));
38705
39270
  log(`\u2500\u2500 ${st.title}`);
38706
39271
  log(` Signed by you; countersigned by the operator, ${operatorName}.`);
38707
39272
  for (const line of describeMandate(m))
38708
39273
  log(` ${line}`);
38709
- const open2 = () => connect({ kind: "stdio", command: process.execPath, args: [...self, "proxy", "--mandate", mf, "--agent-key", join5(dir, `${st.id}-agent-key.json`), "--enforce", "--receipts", rf, "--revocations", revf, "--approvals", join5(dir, "approvals.json"), "--", process.execPath, ...self, "demo-server", "--story", st.server] });
39274
+ const open2 = () => connect({ kind: "stdio", command: process.execPath, args: [...self, "proxy", "--mandate", mf, "--agent-key", join6(dir, `${st.id}-agent-key.json`), "--enforce", "--receipts", rf, "--revocations", revf, "--approvals", join6(dir, "approvals.json"), "--", process.execPath, ...self, "demo-server", "--story", st.server] });
38710
39275
  const s = await open2();
38711
39276
  try {
38712
39277
  await s.listTools();
@@ -38714,7 +39279,7 @@ async function runStory(dir, st, owner, log) {
38714
39279
  for (const step of st.steps) {
38715
39280
  if (step.approveLast) {
38716
39281
  const { approveAction: approveAction2 } = await Promise.resolve().then(() => (init_dist4(), dist_exports));
38717
- approveAction2(cm, lastRid, owner, 60, join5(dir, "approvals.json"));
39282
+ approveAction2(cm, lastRid, owner, 60, join6(dir, "approvals.json"));
38718
39283
  log(` \u270D ${step.say}: ${lastRid}`);
38719
39284
  continue;
38720
39285
  }
@@ -38724,9 +39289,9 @@ async function runStory(dir, st, owner, log) {
38724
39289
  if (rid)
38725
39290
  lastRid = rid[1];
38726
39291
  const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)( \[approval request [^\]]+\])?\.( Ask| Tell|$)/.exec(txt);
38727
- const lastR = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
39292
+ const lastR = parseReceiptLog(readFileSync8(rf, "utf8")).pop();
38728
39293
  log(blocked ? ` \u26D4 ${step.say}: ${blocked[1]}: ${blocked[2]}` : ` \u2713 ${step.say}${/approved by/.test(String(lastR?.receipt.reason ?? "")) ? ": approved by you, once" : ""}`);
38729
- const last = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
39294
+ const last = parseReceiptLog(readFileSync8(rf, "utf8")).pop();
38730
39295
  for (const p of last?.result.rationale?.preferences ?? [])
38731
39296
  if (!blocked)
38732
39297
  log(` \xB7 ${p}`);
@@ -38751,12 +39316,12 @@ async function runStory(dir, st, owner, log) {
38751
39316
  await new Promise((r) => setTimeout(r, 300));
38752
39317
  }
38753
39318
  }
38754
- const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
39319
+ const entries = parseReceiptLog(readFileSync8(rf, "utf8"));
38755
39320
  const ts = trustStatement(entries, verifyReceiptLog(entries).ok);
38756
39321
  log(" Track record:");
38757
39322
  for (const l of ts.lines)
38758
39323
  log(` ${l}`);
38759
- const html = join5(dir, `${st.id}-passport.html`);
39324
+ const html = join6(dir, `${st.id}-passport.html`);
38760
39325
  writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38761
39326
  verified: verifyReceiptLog(entries).ok,
38762
39327
  summary: summariseReceipts(entries),
@@ -38775,12 +39340,12 @@ async function runStory(dir, st, owner, log) {
38775
39340
  }
38776
39341
  async function runMarketplace(dir, log) {
38777
39342
  const self = [...process.execArgv, process.argv[1]];
38778
- const k = (n) => loadOrCreateKey(join5(dir, `market-${n}-key.json`));
39343
+ const k = (n) => loadOrCreateKey(join6(dir, `market-${n}-key.json`));
38779
39344
  const acme = k("acme"), priya = k("priya"), agent = k("agent"), grocer = k("grocer"), travel = k("travel");
38780
39345
  const exp = new Date(Date.now() + 180 * 864e5).toISOString().slice(0, 10);
38781
39346
  const w = (f, x) => {
38782
- writeFileSync4(join5(dir, f), JSON.stringify(x, null, 2));
38783
- return join5(dir, f);
39347
+ writeFileSync4(join6(dir, f), JSON.stringify(x, null, 2));
39348
+ return join6(dir, f);
38784
39349
  };
38785
39350
  log(`\u2500\u2500 Marketplace: "Acme's shopping agent finds a store, agrees terms, and pays per call in prepaid tokens"`);
38786
39351
  const root = organisationRoot({ name: "Acme Corp", domain: "acme.example", expires: exp }, acme);
@@ -38806,11 +39371,11 @@ async function runMarketplace(dir, log) {
38806
39371
  }, grocer), acme);
38807
39372
  const agFile = w("market-agreement.json", ag);
38808
39373
  log(` \u2713 agreement ${ag.id}: ${ag.terms.length} default terms + ${ag.specificTerms.length} specific, signed by Demo Grocer and Acme Corp (${verifyAgreement(ag).valid ? "verified" : "NOT valid"})`);
38809
- const wf = join5(dir, "market-wallet.json");
39374
+ const wf = join6(dir, "market-wallet.json");
38810
39375
  topUp(wf, acme.kid, 12);
38811
39376
  log(` \u2713 Acme tops up 12 prepaid tokens (bought outside Saktum; no money is handled here)`);
38812
39377
  const m = cosignMandate(createMandate({ agentId: agent.kid, agentName: "Acme shopping agent", ownerName: "Priya", purpose: "Weekly office groceries", tools: gm.capabilities.map((c) => c.tool), destructive: false, expires: exp, autonomy: "act", approveAbove: { arg: "amount", value: 50 } }, priya), acme, "Acme Corp");
38813
- const mf = w("market-mandate.json", m), rf = join5(dir, "market-receipts.jsonl"), revf = join5(dir, "market-revoked-credentials.json");
39378
+ const mf = w("market-mandate.json", m), rf = join6(dir, "market-receipts.jsonl"), revf = join6(dir, "market-revoked-credentials.json");
38814
39379
  writeFileSync4(revf, "[]");
38815
39380
  const open2 = () => connect({ kind: "stdio", command: process.execPath, args: [
38816
39381
  ...self,
@@ -38818,7 +39383,7 @@ async function runMarketplace(dir, log) {
38818
39383
  "--mandate",
38819
39384
  mf,
38820
39385
  "--agent-key",
38821
- join5(dir, "market-agent-key.json"),
39386
+ join6(dir, "market-agent-key.json"),
38822
39387
  "--enforce",
38823
39388
  "--receipts",
38824
39389
  rf,
@@ -38853,7 +39418,7 @@ async function runMarketplace(dir, log) {
38853
39418
  const o = await s2.callTool(st1.tool, st1.args);
38854
39419
  const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
38855
39420
  const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)\.( Ask| Tell|$)/.exec(txt);
38856
- const last = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
39421
+ const last = parseReceiptLog(readFileSync8(rf, "utf8")).pop();
38857
39422
  log(blocked ? ` \u26D4 ${st1.say}: ${blocked[1]}: ${blocked[2]}` : ` \u2713 ${st1.say} \xB7 ${last?.result.metering?.tokens ?? 0} token(s), balance ${last?.result.metering?.balance ?? "-"}`);
38858
39423
  }
38859
39424
  } finally {
@@ -38862,7 +39427,7 @@ async function runMarketplace(dir, log) {
38862
39427
  }
38863
39428
  };
38864
39429
  await run(steps);
38865
- const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
39430
+ const entries = parseReceiptLog(readFileSync8(rf, "utf8"));
38866
39431
  const st = usageStatement(entries, ag, grocer);
38867
39432
  log(` \u2713 usage statement signed by Demo Grocer: ${st.lines.map((l) => `${l.tool} ${l.calls}\xD7 = ${l.tokens}`).join(", ")}; total ${st.totalTokens} tokens`);
38868
39433
  log(` \u2713 wallet (double-entry): Acme ${walletBalance(wf, acme.kid)} tokens, Demo Grocer ${walletBalance(wf, grocer.kid)} tokens`);
@@ -38871,10 +39436,10 @@ async function runMarketplace(dir, log) {
38871
39436
  log(` \u26D4 Priya leaves Acme and her credential is revoked: the agent is now an orphan (${orphan?.reason})`);
38872
39437
  topUp(wf, acme.kid, 5);
38873
39438
  await run([{ tool: "search_products", args: { query: "milk" }, say: "the orphaned agent tries to search" }]);
38874
- const all = parseReceiptLog(readFileSync7(rf, "utf8"));
39439
+ const all = parseReceiptLog(readFileSync8(rf, "utf8"));
38875
39440
  const k2 = kpis(all);
38876
39441
  log(` KPIs: ${k2.calls} calls \xB7 ${k2.allowed} allowed \xB7 ${k2.blocked} blocked (${k2.byOutcome.filter(([c]) => !c.startsWith("ok")).map(([c, n]) => `${n} ${c}`).join(", ")}) \xB7 ${k2.tokens} tokens`);
38877
- const html = join5(dir, "marketplace-passport.html");
39442
+ const html = join6(dir, "marketplace-passport.html");
38878
39443
  const ts = trustStatement(all, verifyReceiptLog(all).ok);
38879
39444
  writeFileSync4(html, renderAgentPassport(m, { ok: true }, { verified: verifyReceiptLog(all).ok, summary: summariseReceipts(all), timeline: all.map((e) => ({ tool: e.receipt.envelope.tool, outcome: e.receipt.outcome, status: e.result.status, repeated: false, why: [e.receipt.reason ?? "", e.result.metering ? `${e.result.metering.tokens} token(s), balance ${e.result.metering.balance}` : ""].filter(Boolean).join(" \xB7 ") })) }, agentRiskTier(m), [`Weekly office groceries for Acme Corp, under agreement ${ag.id} with Demo Grocer.`, `Accountable: ${verifyChain(agentCred).path.join(" \u2192 ")}.`, "Paid per call in prepaid tokens."], { operator: "Acme Corp", track: ts.lines, maturity: agentMaturity(m, { entries: all, verified: verifyReceiptLog(all).ok, chainValid: verifyChain(agentCred).valid }) }));
38880
39445
  log(` ${all.length} signed receipts \xB7 ${verifyReceiptLog(all).ok ? "verified" : "NOT verified"} \xB7 passport: ${html}
@@ -38893,7 +39458,7 @@ async function runDemo(dir, log, story = "all") {
38893
39458
  if (existsSync6(dir))
38894
39459
  rmSync(dir, { recursive: true, force: true });
38895
39460
  mkdirSync5(dir, { recursive: true });
38896
- const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
39461
+ const owner = loadOrCreateKey(join6(dir, "owner-key.json"));
38897
39462
  log("Saktum demo: agents acting on real instructions (rules, preferences, substitutions, upsells), every decision explained and signed.\n");
38898
39463
  const files = [];
38899
39464
  for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : story === "coding" ? [CODING] : [GROCERY, TRAVEL, FINANCE, CODING])
@@ -38914,7 +39479,7 @@ async function runAutonomyDemo(dir, log) {
38914
39479
  if (existsSync6(dir))
38915
39480
  rmSync(dir, { recursive: true, force: true });
38916
39481
  mkdirSync5(dir, { recursive: true });
38917
- const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
39482
+ const owner = loadOrCreateKey(join6(dir, "owner-key.json"));
38918
39483
  const self = [...process.execArgv, process.argv[1]];
38919
39484
  const tools = DEMO_TOOLS.map((t) => t.name);
38920
39485
  const personas = [
@@ -38925,7 +39490,7 @@ async function runAutonomyDemo(dir, log) {
38925
39490
  const files = [];
38926
39491
  log("Saktum demo: one shopping agent, three mandates, every call governed and receipted.\n");
38927
39492
  for (const p of personas) {
38928
- const agentKey = loadOrCreateKey(join5(dir, `${p.id}-agent-key.json`));
39493
+ const agentKey = loadOrCreateKey(join6(dir, `${p.id}-agent-key.json`));
38929
39494
  const m = createMandate({
38930
39495
  agentId: agentKey.kid,
38931
39496
  agentName: `Shopping agent (${p.id})`,
@@ -38937,11 +39502,11 @@ async function runAutonomyDemo(dir, log) {
38937
39502
  disclosures: { operator: "Demo Grocer", incentives: "None: no sponsored ranking", dataUse: "Order history used only to suggest your usual items" },
38938
39503
  ...p.m
38939
39504
  }, owner);
38940
- const mf = join5(dir, `${p.id}-mandate.json`), rf = join5(dir, `${p.id}-receipts.jsonl`);
39505
+ const mf = join6(dir, `${p.id}-mandate.json`), rf = join6(dir, `${p.id}-receipts.jsonl`);
38941
39506
  writeFileSync4(mf, JSON.stringify(m, null, 2));
38942
39507
  const tier = agentRiskTier(m);
38943
39508
  log(`\u2500\u2500 ${p.title} autonomy ${m.autonomy} \xB7 risk ${tier.tier}`);
38944
- const s = await connect({ kind: "stdio", command: process.execPath, args: [...self, "proxy", "--mandate", mf, "--agent-key", join5(dir, `${p.id}-agent-key.json`), "--enforce", "--receipts", rf, "--", process.execPath, ...self, "demo-server"] });
39509
+ const s = await connect({ kind: "stdio", command: process.execPath, args: [...self, "proxy", "--mandate", mf, "--agent-key", join6(dir, `${p.id}-agent-key.json`), "--enforce", "--receipts", rf, "--", process.execPath, ...self, "demo-server"] });
38945
39510
  try {
38946
39511
  await s.listTools();
38947
39512
  for (const st of p.steps) {
@@ -38954,13 +39519,13 @@ async function runAutonomyDemo(dir, log) {
38954
39519
  await s.close();
38955
39520
  await new Promise((r) => setTimeout(r, 300));
38956
39521
  }
38957
- const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
39522
+ const entries = parseReceiptLog(readFileSync8(rf, "utf8"));
38958
39523
  const counts = /* @__PURE__ */ new Map();
38959
39524
  for (const e of entries) {
38960
39525
  const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
38961
39526
  counts.set(k, (counts.get(k) ?? 0) + 1);
38962
39527
  }
38963
- const html = join5(dir, `${p.id}-passport.html`);
39528
+ const html = join6(dir, `${p.id}-passport.html`);
38964
39529
  writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38965
39530
  verified: verifyReceiptLog(entries).ok,
38966
39531
  summary: summariseReceipts(entries),
@@ -39134,7 +39699,7 @@ __export(mcp_server_exports, {
39134
39699
  splitTarget: () => splitTarget,
39135
39700
  startMcpServer: () => startMcpServer
39136
39701
  });
39137
- import { readFileSync as readFileSync8 } from "node:fs";
39702
+ import { readFileSync as readFileSync9 } from "node:fs";
39138
39703
  function splitTarget(target) {
39139
39704
  const t = target.trim();
39140
39705
  if (/^https?:\/\//i.test(t))
@@ -39170,7 +39735,7 @@ async function handleSaktumTool(name, args, packs) {
39170
39735
  case "diff_against_lock": {
39171
39736
  if (typeof args.lock_path !== "string")
39172
39737
  throw new Error("lock_path is required");
39173
- const before = JSON.parse(readFileSync8(args.lock_path, "utf8"));
39738
+ const before = JSON.parse(readFileSync9(args.lock_path, "utf8"));
39174
39739
  const d = diffLocks(before, { tools: (await listTools(targetOf(args.target))).tools });
39175
39740
  return text([...d.changes.map((c) => `${c.kind}: ${c.tool}: ${c.detail}`), d.summary].join("\n"), { semver: d.semver, summary: d.summary, changes: d.changes });
39176
39741
  }
@@ -39311,7 +39876,7 @@ var init_mcp_server = __esm({
39311
39876
  });
39312
39877
 
39313
39878
  // packages/cli/dist/main.js
39314
- import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
39879
+ import { existsSync as existsSync7, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "node:fs";
39315
39880
  import { fileURLToPath as fileURLToPath2 } from "node:url";
39316
39881
 
39317
39882
  // node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
@@ -39516,6 +40081,15 @@ What would you like to do?
39516
40081
  All commands: npx saktum --help \xB7 Guide: https://github.com/soodhere/saktum-check
39517
40082
  `;
39518
40083
  var bundledPacks = fileURLToPath2(new URL("../../../packs/", import.meta.url));
40084
+ var secretFrom = (spec) => {
40085
+ if (spec.startsWith("env:")) {
40086
+ const v = process.env[spec.slice(4)];
40087
+ if (!v)
40088
+ throw new Error(`Environment variable ${spec.slice(4)} is not set.`);
40089
+ return v;
40090
+ }
40091
+ return spec;
40092
+ };
39519
40093
  var collect = (v, acc) => [...acc, v];
39520
40094
  var parseHeaders = (hs) => Object.fromEntries(hs.map((h) => {
39521
40095
  const i = h.indexOf(":");
@@ -39549,7 +40123,7 @@ async function main(argv = process.argv) {
39549
40123
  if (o.tests) {
39550
40124
  if (!existsSync7(o.tests))
39551
40125
  throw new Error(`Test file not found: ${o.tests}. See docs/TESTS.md for the format.`);
39552
- testCases = await parseTestCases(readFileSync9(o.tests, "utf8"));
40126
+ testCases = await parseTestCases(readFileSync10(o.tests, "utf8"));
39553
40127
  }
39554
40128
  const target = parseTarget(targetParts);
39555
40129
  if (target.kind === "stdio" && o.env.length)
@@ -39581,7 +40155,7 @@ async function main(argv = process.argv) {
39581
40155
  process.stdout.write(`Wrote baseline ${sanitizeText(o.baseline)} accepting ${failing.length} existing finding(s). Commit it; later runs fail only on new findings.
39582
40156
  `);
39583
40157
  } else if (o.baseline && existsSync7(o.baseline)) {
39584
- accepted = new Set(JSON.parse(readFileSync9(o.baseline, "utf8")).accepted.map(keyOf));
40158
+ accepted = new Set(JSON.parse(readFileSync10(o.baseline, "utf8")).accepted.map(keyOf));
39585
40159
  }
39586
40160
  if (o.sarif)
39587
40161
  writeFileSync5(o.sarif, JSON.stringify(toSarif(signed, o.sarifAnchor, accepted), null, 2) + "\n");
@@ -39680,8 +40254,8 @@ Watching ${sanitizeText(o.watchDir)} for changes (Ctrl+C to stop).
39680
40254
  `);
39681
40255
  });
39682
40256
  program2.command("diff").description("Compare tools with a lock file: breaking changes, risky changes (silent tool changes), additions, and the version bump they need").argument("<lock>", "the lock file written by saktum snapshot").argument("[target...]", "a second lock file, or the server to compare (after --)").option("--allow-breaking", "do not fail on breaking or risky changes", false).option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).option("--header <Name: value>", "HTTP header for a remote server (repeatable)", collect, []).action(async (lock, rest, o) => {
39683
- const before = JSON.parse(readFileSync9(lock, "utf8"));
39684
- const after = rest.length === 1 && rest[0].endsWith(".json") ? JSON.parse(readFileSync9(rest[0], "utf8")) : { tools: (await listTarget(rest, o.env, o.header)).tools };
40257
+ const before = JSON.parse(readFileSync10(lock, "utf8"));
40258
+ const after = rest.length === 1 && rest[0].endsWith(".json") ? JSON.parse(readFileSync10(rest[0], "utf8")) : { tools: (await listTarget(rest, o.env, o.header)).tools };
39685
40259
  const d = diffLocks(before, after);
39686
40260
  const mark2 = { breaking: "\u2717 BREAKING", risky: "! REVIEW ", addition: "+ ADDED ", change: "~ CHANGED " };
39687
40261
  for (const c of d.changes)
@@ -39698,7 +40272,7 @@ ${d.summary}
39698
40272
  process.stdout.write(docsFor(tools, name, target.kind === "stdio" ? { command: target.command, args: target.args } : { url: target.url }));
39699
40273
  });
39700
40274
  program2.command("packet").description("Turn a signed result into a printable security packet for customers' security reviews").argument("<result>", "a signed result (saktum-report.json)").option("--out <file>", "HTML packet (print to PDF from a browser)", "saktum-security-packet.html").action((file, o) => {
39701
- const doc = JSON.parse(readFileSync9(file, "utf8"));
40275
+ const doc = JSON.parse(readFileSync10(file, "utf8"));
39702
40276
  const v = verifyDocument(doc);
39703
40277
  if (!v.valid)
39704
40278
  throw new Error(`The result's signature is not valid (${v.reason}); a packet must be built from an unaltered signed result.`);
@@ -39712,7 +40286,7 @@ ${d.summary}
39712
40286
  const check = verifyLedger(entries);
39713
40287
  if (!check.ok)
39714
40288
  throw new Error(`The ledger does not verify: ${check.errors[0]}`);
39715
- const signers = o.trustedSigners ? new Set(readFileSync9(o.trustedSigners, "utf8").split(/\r?\n/).map((l) => l.trim()).filter(Boolean)) : void 0;
40289
+ const signers = o.trustedSigners ? new Set(readFileSync10(o.trustedSigners, "utf8").split(/\r?\n/).map((l) => l.trim()).filter(Boolean)) : void 0;
39716
40290
  const list2 = allowlistFromLedger(entries, { minTrust: o.minTrust.toUpperCase(), minReadiness: o.minReadiness.toUpperCase(), trustedSigners: signers });
39717
40291
  writeFileSync5(o.out, JSON.stringify(list2, null, 2) + "\n");
39718
40292
  process.stdout.write(`Ledger verified (${check.count} entries). Wrote ${sanitizeText(o.out)}: ${list2.allowed.length} allowed, ${list2.excluded.length} excluded.
@@ -39722,7 +40296,7 @@ ${d.summary}
39722
40296
  if (!files.length)
39723
40297
  throw new Error("Give signed results, or use --from-ledger.");
39724
40298
  const inputs = files.map((f) => {
39725
- const doc = JSON.parse(readFileSync9(f, "utf8"));
40299
+ const doc = JSON.parse(readFileSync10(f, "utf8"));
39726
40300
  const v = verifyDocument(doc);
39727
40301
  if (!v.valid)
39728
40302
  throw new Error(`${f}: signature not valid (${v.reason}); only unaltered signed results can be allowlisted.`);
@@ -39809,7 +40383,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
39809
40383
  expect.outputSchema = true;
39810
40384
  expect.latencyMs = { lt: Math.max(2e3, outcome.latencyMs * 5) };
39811
40385
  const tc = { id: o.saveTest, tool: toolName, input: args, ...tool.annotations?.readOnlyHint === true ? {} : { sideEffects: true }, expect };
39812
- writeFileSync5(o.tests, await appendTestCase(existsSync7(o.tests) ? readFileSync9(o.tests, "utf8") : void 0, tc));
40386
+ writeFileSync5(o.tests, await appendTestCase(existsSync7(o.tests) ? readFileSync10(o.tests, "utf8") : void 0, tc));
39813
40387
  process.stdout.write(`Saved test case ${sanitizeText(o.saveTest, 60)} to ${sanitizeText(o.tests)}. Run: saktum test -- <start command>
39814
40388
  `);
39815
40389
  }
@@ -39817,7 +40391,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
39817
40391
  program2.command("scan-config").description("Check every MCP server your agents load (Claude Desktop, Claude Code, Cursor, VS Code): total context cost, duplicate tools, unvetted servers").option("--config <file>", "a specific configuration file (repeatable); default: the known locations", collect, []).option("--yes", "start the servers without asking (they run with the settings in your configuration)", false).option("--turns-per-day <n>", "agent turns a day, for the monthly cost estimate", "50").option("--price-per-mtok <usd>", "your model's price per million input tokens", "3").option("--allowlist <file>", "saktum-allowlist.json: flag servers that are not on it").option("--out <file>", "also write the analysis as JSON (input for saktum fleet)").option("--policy <file>", "your organisation's policy: show which servers violate it").option("--machine <label>", "label for this machine in fleet reports (default: the host name)").action(async (o) => {
39818
40392
  const { homedir: homedir2 } = await import("node:os");
39819
40393
  const locations = o.config.length ? o.config.map((file) => ({ client: "configuration", file })) : configLocations(homedir2(), process.cwd(), process.platform, process.env.APPDATA);
39820
- const servers = locations.filter((l) => existsSync7(l.file)).flatMap((l) => parseClientConfig(readFileSync9(l.file, "utf8"), l.client, l.file)).filter((x) => !x.disabled);
40394
+ const servers = locations.filter((l) => existsSync7(l.file)).flatMap((l) => parseClientConfig(readFileSync10(l.file, "utf8"), l.client, l.file)).filter((x) => !x.disabled);
39821
40395
  if (!servers.length) {
39822
40396
  process.stdout.write("No MCP servers found in the known configuration locations. Point to one with --config <file>.\n");
39823
40397
  return;
@@ -39867,7 +40441,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
39867
40441
  scans.push({ name: x.name, client: x.client, trustGrade: null, readinessGrade: null, tools: [], tokens: 0, target: x.url ? redactUrl(x.url) : redactCommand(x.command, x.args), error: sanitizeText(e.message, 120) });
39868
40442
  }
39869
40443
  }
39870
- const allow = o.allowlist ? new Set(JSON.parse(readFileSync9(o.allowlist, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f))) : void 0;
40444
+ const allow = o.allowlist ? new Set(JSON.parse(readFileSync10(o.allowlist, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f))) : void 0;
39871
40445
  const report = analyseSetup(scans, { turnsPerDay: Number(o.turnsPerDay) || 50, pricePerMTokUsd: Number(o.pricePerMtok) || 3, allowlistFingerprints: allow });
39872
40446
  process.stdout.write("\n" + renderSetup(report));
39873
40447
  if (o.policy) {
@@ -39883,7 +40457,7 @@ POLICY${policy.name ? ` (${sanitizeText(policy.name, 80)})` : ""}
39883
40457
  writeFileSync5(o.out, JSON.stringify({ ...report, machine: o.machine ?? hostname() }, null, 2) + "\n");
39884
40458
  });
39885
40459
  program2.command("vc").description("W3C Verifiable Credentials made by saktum attest --vc").command("verify").description("Verify a Saktum credential (vc+jwt): signature and issuer did:key").argument("<file>", "the .vc.jwt file").action((f) => {
39886
- const r = verifyCredentialJwt(readFileSync9(f, "utf8"));
40460
+ const r = verifyCredentialJwt(readFileSync10(f, "utf8"));
39887
40461
  if (r.valid) {
39888
40462
  const cs = r.credential.credentialSubject ?? {};
39889
40463
  process.stdout.write(`\u2713 Valid credential from ${r.issuer}: ${sanitizeText(String(cs.server ?? ""), 80)} trust ${cs.trustGrade ?? "-"}, readiness ${cs.readinessGrade ?? "-"}.
@@ -39921,15 +40495,15 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
39921
40495
  const latest = /* @__PURE__ */ new Map();
39922
40496
  for (const e of entries)
39923
40497
  latest.set(e.subject.server, e);
39924
- for (const e of latest.values())
40498
+ for (const e of [...latest.values()].filter((x) => x.attestation))
39925
40499
  writeFileSync5(`${o.out}/${passportSlug(e.subject.server)}.html`, renderLedgerPassport(e));
39926
- writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries));
40500
+ writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries.filter((x) => x.attestation)));
39927
40501
  process.stdout.write(`Wrote ${latest.size} passport page(s) and the gallery to ${sanitizeText(o.out)}.
39928
40502
  `);
39929
40503
  });
39930
40504
  ledger.command("append").description("Append a signed attestation to a ledger file after verifying it (used by the ledger bot)").argument("<input>", "attestation JSON, or a text file (such as an issue body) containing it").requiredOption("--ledger <file>", "ledger file to append to").option("--issue <n>", "issue number that requested it").action((input, o) => {
39931
- const att = extractJson(readFileSync9(input, "utf8"));
39932
- const { text: text2, entry } = appendToLedger(existsSync7(o.ledger) ? readFileSync9(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
40505
+ const att = extractJson(readFileSync10(input, "utf8"));
40506
+ const { text: text2, entry } = (att?.statementFormat ? appendStatement : appendToLedger)(existsSync7(o.ledger) ? readFileSync10(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
39933
40507
  writeFileSync5(o.ledger, text2);
39934
40508
  process.stdout.write(`Recorded entry #${entry.seq} for ${sanitizeText(entry.subject.server, 80)} (signed by ${entry.signer}); entry hash ${entry.entryHash}.
39935
40509
  `);
@@ -39976,7 +40550,7 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
39976
40550
  approveAbove: aa,
39977
40551
  disclosures: { ...o.operator ? { operator: o.operator } : {}, ...o.incentives ? { incentives: o.incentives } : {}, ...o.dataUse ? { dataUse: o.dataUse } : {} },
39978
40552
  delegation: o.allowDelegation,
39979
- ...o.intent ? JSON.parse(readFileSync9(o.intent, "utf8")) : {}
40553
+ ...o.intent ? JSON.parse(readFileSync10(o.intent, "utf8")) : {}
39980
40554
  }, loadOrCreateKey(o.key));
39981
40555
  if (o.software) {
39982
40556
  const { signature: _old, ...body2 } = m;
@@ -39996,7 +40570,7 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
39996
40570
  `);
39997
40571
  });
39998
40572
  agent.command("verify").description("Check a mandate: the principal's signature, the operator's countersignature, expiry and revocation").argument("<mandate>", "mandate file").action((f) => {
39999
- const m = JSON.parse(readFileSync9(f, "utf8"));
40573
+ const m = JSON.parse(readFileSync10(f, "utf8"));
40000
40574
  const c = checkMandate(m), op = checkOperator(m), rev = revocationOf(m);
40001
40575
  process.stdout.write(c.ok ? `\u2713 Valid mandate for ${sanitizeText(m.agent.name, 80)} (${m.agent.id}), signed by ${m.owner.name ?? m.owner.id}, until ${m.expires}.
40002
40576
  ` : `\u2717 ${c.reason}
@@ -40011,7 +40585,7 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
40011
40585
  exitCode = c.ok && (!op.present || op.valid) && !rev ? 0 : 1;
40012
40586
  });
40013
40587
  agent.command("cosign").description("As the operator (who runs the agent and is accountable), countersign a principal's mandate").argument("<mandate>", "mandate file (updated in place)").requiredOption("--name <operator>", "the operator's name").option("--key <path>", "the operator's signing key (created if missing)", "saktum-operator-key.json").action((f, o) => {
40014
- const m = JSON.parse(readFileSync9(f, "utf8"));
40588
+ const m = JSON.parse(readFileSync10(f, "utf8"));
40015
40589
  if (!checkMandate(m).ok)
40016
40590
  throw new Error("The mandate is not valid; it cannot be countersigned.");
40017
40591
  const signed = cosignMandate(m, loadOrCreateKey(o.key), o.name);
@@ -40020,23 +40594,26 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
40020
40594
  `);
40021
40595
  });
40022
40596
  agent.command("approve").description("As the mandate's owner, approve exactly one pending action (by its request id), for a limited time, once").argument("<request-id>", "the approval request id from the blocked call (apr_...)").requiredOption("--mandate <file>", "the mandate").option("--key <path>", "the owner's signing key (the one that signed the mandate)").option("--minutes <n>", "how long the approval stays valid", "60").option("--approvals <file>", "approvals file the proxy reads (default ~/.saktum/approvals.json)").action((rid, o) => {
40023
- const m = JSON.parse(readFileSync9(o.mandate, "utf8"));
40597
+ const m = JSON.parse(readFileSync10(o.mandate, "utf8"));
40024
40598
  const a = approveAction(m, rid, loadOrCreateKey(o.key), Number(o.minutes), o.approvals);
40025
40599
  process.stdout.write(`Approved ${sanitizeText(rid, 40)} for ${sanitizeText(m.agent.name, 80)}, valid until ${a.expires}, once. The agent can now retry exactly that action.
40026
40600
  `);
40027
40601
  });
40028
- agent.command("revoke").description("Stop an agent now: every Saktum proxy on this machine refuses calls under this mandate").argument("<mandate>", "mandate file").option("--reason <text>", "why").action((f, o) => {
40029
- const m = JSON.parse(readFileSync9(f, "utf8"));
40030
- const r = revokeMandate(m, o.reason);
40602
+ agent.command("revoke").description("Stop an agent now: every Saktum proxy on this machine refuses calls under this mandate").argument("<mandate>", "mandate file").option("--reason <text>", "why").option("--key <spec>", "sign the revocation as the owner or operator (file, env:VAR, keychain:NAME or exec:PROGRAM)").option("--out <file>", "also write the signed revocation (for a remote list or the ledger)").action((f, o) => {
40603
+ const m = JSON.parse(readFileSync10(f, "utf8"));
40604
+ const key = o.key ? loadOrCreateKey(o.key) : void 0;
40605
+ const r = revokeMandate(m, o.reason, void 0, key);
40606
+ if (o.out && key)
40607
+ writeFileSync5(o.out, JSON.stringify(signRevocation(m, key, o.reason), null, 2) + "\n");
40031
40608
  process.stdout.write(`Revoked the mandate for ${sanitizeText(m.agent.name, 80)} at ${r.at}. Its calls are now refused (code: revoked).
40032
40609
  `);
40033
40610
  });
40034
- program2.command("proxy").description("Put Saktum between an agent and a local MCP server: signed receipts for every tool call, and the agent's mandate observed or enforced (preview)").argument("<command...>", "the server command, after --").option("--mandate <file>", "the agent's mandate (from saktum agent create)").option("--agent-key <file>", "the agent's key, which signs receipts", "agent-key.json").option("--enforce", "block calls outside the mandate (default: observe and record only)", false).option("--receipts <file>", "receipt log (append-only, hash-chained)").option("--revocations <file>", "revocation list to honour (default ~/.saktum/revocations.json)").option("--approvals <file>", "signed approvals to honour (default ~/.saktum/approvals.json)").option("--credential <file>", "the agent's credential: its accountability chain is verified on every call").option("--revoked-credentials <file>", "JSON list of revoked credential ids").option("--agreement <file>", "the signed agreement with the provider: calls outside it are refused and every call is metered").option("--wallet <file>", "prepaid token wallet charged per call under the agreement").action(async (parts, o) => {
40611
+ program2.command("proxy").description("Put Saktum between an agent and a local MCP server: signed receipts for every tool call, and the agent's mandate observed or enforced (preview)").argument("<command...>", "the server command, after --").option("--mandate <file>", "the agent's mandate (from saktum agent create)").option("--agent-key <file>", "the agent's key, which signs receipts", "agent-key.json").option("--enforce", "block calls outside the mandate (default: observe and record only)", false).option("--receipts <file>", "receipt log (append-only, hash-chained)").option("--revocations <file>", "revocation list to honour (default ~/.saktum/revocations.json)").option("--approvals <file>", "signed approvals to honour (default ~/.saktum/approvals.json)").option("--credential <file>", "the agent's credential: its accountability chain is verified on every call").option("--revoked-credentials <file>", "JSON list of revoked credential ids").option("--agreement <file>", "the signed agreement with the provider: calls outside it are refused and every call is metered").option("--wallet <file>", "prepaid token wallet charged per call under the agreement").option("--approval-webhook <url>", "post approval requests to this webhook (Slack, Teams or an email relay)").option("--approval-url <url>", "base link of saktum approvals serve, included in approval requests").option("--bindings <file>", "bindings override: JSON { tool: { action, bindings: { arg: field } } } for tools that declare nothing").option("--revocations-url <url>", "a remote revocation list (for example in the ledger) the agent cannot edit").option("--digest-key <spec>", "keyed digests of arguments in receipts: env:VAR (recommended)").option("--pin <fingerprint>", "refuse calls if the server's tools differ from this approved fingerprint (sha256:...)").option("--checkpoint-every <n>", "write a signed checkpoint every n receipts").option("--checkpoint-file <file>", "where checkpoints go (keep it off the agent's machine or ship it)").option("--approval-secret <spec>", "secret shared with approvals serve for single-use, per-request links: env:VAR").action(async (parts, o) => {
40035
40612
  const { homedir: homedir2 } = await import("node:os");
40036
- const { join: join6 } = await import("node:path");
40613
+ const { join: join7 } = await import("node:path");
40037
40614
  let mandate;
40038
40615
  if (o.mandate) {
40039
- mandate = JSON.parse(readFileSync9(o.mandate, "utf8"));
40616
+ mandate = JSON.parse(readFileSync10(o.mandate, "utf8"));
40040
40617
  const c = checkMandate(mandate);
40041
40618
  if (!c.ok)
40042
40619
  throw new Error(`Mandate refused: ${c.reason}`);
@@ -40048,16 +40625,24 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
40048
40625
  exitCode = await runProxy2({
40049
40626
  command: parts[0],
40050
40627
  args: parts.slice(1),
40051
- receiptsPath: o.receipts ?? join6(homedir2(), ".saktum", "receipts.jsonl"),
40628
+ receiptsPath: o.receipts ?? join7(homedir2(), ".saktum", "receipts.jsonl"),
40052
40629
  agentKey,
40053
40630
  mandate,
40054
40631
  enforce: o.enforce,
40055
40632
  ...o.revocations ? { revocationsPath: o.revocations } : {},
40056
40633
  ...o.approvals ? { approvalsPath: o.approvals } : {},
40057
- ...o.credential ? { credential: JSON.parse(readFileSync9(o.credential, "utf8")) } : {},
40058
- ...o.revokedCredentials ? { revokedCredentials: JSON.parse(readFileSync9(o.revokedCredentials, "utf8")) } : {},
40059
- ...o.agreement ? { agreement: JSON.parse(readFileSync9(o.agreement, "utf8")) } : {},
40634
+ ...o.credential ? { credential: JSON.parse(readFileSync10(o.credential, "utf8")) } : {},
40635
+ ...o.revokedCredentials ? { revokedCredentials: JSON.parse(readFileSync10(o.revokedCredentials, "utf8")) } : {},
40636
+ ...o.agreement ? { agreement: JSON.parse(readFileSync10(o.agreement, "utf8")) } : {},
40060
40637
  ...o.wallet ? { walletPath: o.wallet } : {},
40638
+ ...o.approvalWebhook ? { approvalWebhook: o.approvalWebhook } : {},
40639
+ ...o.approvalUrl ? { approvalUrl: o.approvalUrl } : {},
40640
+ ...o.bindings ? { bindingsOverride: JSON.parse(readFileSync10(o.bindings, "utf8")) } : {},
40641
+ ...o.revocationsUrl ? { revocationsUrl: o.revocationsUrl } : {},
40642
+ ...o.digestKey ? { digestKey: secretFrom(o.digestKey) } : {},
40643
+ ...o.pin ? { pin: o.pin } : {},
40644
+ ...o.checkpointEvery && o.checkpointFile ? { checkpointEvery: Number(o.checkpointEvery), checkpointFile: o.checkpointFile } : {},
40645
+ ...o.approvalSecret ? { approvalSecret: secretFrom(o.approvalSecret) } : {},
40061
40646
  log: (m) => process.stderr.write(`saktum: ${m}
40062
40647
  `)
40063
40648
  });
@@ -40065,8 +40650,8 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
40065
40650
  const receipts = program2.command("receipts").description("Signed receipts of agent tool calls (from saktum proxy)");
40066
40651
  receipts.command("verify").description("Verify every receipt's signature and the hash chain").argument("[file]", "receipt log").action(async (f) => {
40067
40652
  const { homedir: homedir2 } = await import("node:os");
40068
- const { join: join6 } = await import("node:path");
40069
- const r = verifyReceiptLog(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")));
40653
+ const { join: join7 } = await import("node:path");
40654
+ const r = verifyReceiptLog(parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8")));
40070
40655
  process.stdout.write(r.ok ? `\u2713 ${r.count} receipts verified: every signature valid, chain intact.
40071
40656
  ` : `\u2717 Receipts do NOT verify:
40072
40657
  ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
@@ -40075,8 +40660,8 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
40075
40660
  });
40076
40661
  receipts.command("export").description("Export receipts as OpenTelemetry traces (OTLP/JSON) for your observability or security tools").argument("[file]", "receipt log").option("--otel <file>", "write OTLP/JSON traces to this file", "saktum-receipts.otlp.json").option("--endpoint <url>", "also send them to an OpenTelemetry collector (OTLP/HTTP), for example http://localhost:4318").action(async (f, o) => {
40077
40662
  const { homedir: homedir2 } = await import("node:os");
40078
- const { join: join6 } = await import("node:path");
40079
- const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
40663
+ const { join: join7 } = await import("node:path");
40664
+ const entries = parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
40080
40665
  const v = verifyReceiptLog(entries);
40081
40666
  const otlp = receiptsToOtlp(entries, { verified: v.ok, version: ENGINE_VERSION });
40082
40667
  writeFileSync5(o.otel, JSON.stringify(otlp, null, 2) + "\n");
@@ -40091,10 +40676,28 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
40091
40676
  exitCode = 1;
40092
40677
  }
40093
40678
  });
40679
+ receipts.command("view").description("One verified view across many agents' receipt logs (for example collected in a shared folder)").argument("<files...>", "receipt logs").option("--html <file>", "output", "saktum-receipts.html").action((fs3, o) => {
40680
+ const logs = fs3.map((f) => {
40681
+ const e = parseReceiptLog(readFileSync10(f, "utf8"));
40682
+ return { name: f, verified: verifyReceiptLog(e).ok, entries: e.map((x) => ({ at: x.receipt.issuedAt, agent: x.receipt.envelope.caller.agent?.slice(0, 24) ?? "", tool: x.receipt.envelope.tool, outcome: x.receipt.outcome, code: x.result.code ?? "", reason: String(x.receipt.reason ?? ""), tokens: x.result.metering?.tokens ?? 0 })) };
40683
+ });
40684
+ writeFileSync5(o.html, renderReceiptsView(logs));
40685
+ process.stdout.write(`Combined ${logs.reduce((n, l) => n + l.entries.length, 0)} receipts from ${logs.length} log(s) into ${sanitizeText(o.html)}; ${logs.filter((l) => !l.verified).length} log(s) failed verification.
40686
+ `);
40687
+ exitCode = logs.every((l) => l.verified) ? 0 : 1;
40688
+ });
40689
+ receipts.command("checkpoint").description("Write a signed checkpoint of a receipt log (keep it elsewhere, so deletions are detectable)").argument("[file]", "receipt log").option("--key <spec>", "signing key").option("--out <file>", "checkpoint file", "saktum-checkpoint.json").action(async (f, o) => {
40690
+ const { homedir: homedir2 } = await import("node:os");
40691
+ const { join: join7 } = await import("node:path");
40692
+ const cp = makeCheckpoint(parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), loadOrCreateKey(o.key));
40693
+ writeFileSync5(o.out, JSON.stringify(cp, null, 2) + "\n");
40694
+ process.stdout.write(`Checkpoint at receipt ${cp.seq} (${cp.head.slice(0, 20)}...) written to ${sanitizeText(o.out)}.
40695
+ `);
40696
+ });
40094
40697
  receipts.command("summary").description("The path, not the answer: which tools were called, how often, in what order, retries, denials, destructive actions").argument("[file]", "receipt log").option("--json", "print JSON", false).action(async (f, o) => {
40095
40698
  const { homedir: homedir2 } = await import("node:os");
40096
- const { join: join6 } = await import("node:path");
40097
- const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
40699
+ const { join: join7 } = await import("node:path");
40700
+ const entries = parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
40098
40701
  const v = verifyReceiptLog(entries), s = summariseReceipts(entries);
40099
40702
  if (o.json) {
40100
40703
  process.stdout.write(JSON.stringify({ verified: v.ok, ...s }, null, 2) + "\n");
@@ -40108,11 +40711,11 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
40108
40711
  });
40109
40712
  program2.command("passport").description("A visual passport: for an MCP server (checks it first) or, with --agent, for an agent (mandate and receipt timeline)").argument("[target...]", "the server: https URL, or -- <command that starts it>").option("--agent <mandate>", "make an Agent Passport from this mandate instead").option("--receipts <file>", "with --agent: the agent's receipt log, for the timeline").option("--out <file>", "HTML file", "saktum-passport.html").option("--key <path>", "signing key for the server's result").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).option("--header <Name: value>", "HTTP header for a remote server (repeatable)", collect, []).action(async (parts, o) => {
40110
40713
  if (o.agent) {
40111
- const m = JSON.parse(readFileSync9(o.agent, "utf8"));
40714
+ const m = JSON.parse(readFileSync10(o.agent, "utf8"));
40112
40715
  const valid = checkMandate(m);
40113
40716
  let receipts2;
40114
40717
  if (o.receipts) {
40115
- const entries = parseReceiptLog(readFileSync9(o.receipts, "utf8"));
40718
+ const entries = parseReceiptLog(readFileSync10(o.receipts, "utf8"));
40116
40719
  const counts = /* @__PURE__ */ new Map();
40117
40720
  for (const e of entries) {
40118
40721
  const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
@@ -40125,11 +40728,11 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
40125
40728
  };
40126
40729
  }
40127
40730
  const rev = revocationOf(m), op = checkOperator(m);
40128
- const ts = o.receipts ? trustStatement(parseReceiptLog(readFileSync9(o.receipts, "utf8")), receipts2?.verified ?? false) : void 0;
40731
+ const ts = o.receipts ? trustStatement(parseReceiptLog(readFileSync10(o.receipts, "utf8")), receipts2?.verified ?? false) : void 0;
40129
40732
  writeFileSync5(o.out, renderAgentPassport(m, rev ? { ok: false, reason: `Revoked on ${rev.at.slice(0, 10)}${rev.reason ? `: ${rev.reason}` : ""}` } : valid.ok ? { ok: true } : { ok: false, reason: valid.reason }, receipts2, agentRiskTier(m), describeMandate(m), {
40130
40733
  operator: op.present && op.valid ? `${op.name} (${op.id})` : void 0,
40131
40734
  track: ts?.lines,
40132
- maturity: agentMaturity(m, { entries: o.receipts ? parseReceiptLog(readFileSync9(o.receipts, "utf8")) : [], verified: receipts2?.verified, revoked: Boolean(rev) })
40735
+ maturity: agentMaturity(m, { entries: o.receipts ? parseReceiptLog(readFileSync10(o.receipts, "utf8")) : [], verified: receipts2?.verified, revoked: Boolean(rev) })
40133
40736
  }));
40134
40737
  process.stdout.write(`Wrote the Agent Passport for ${sanitizeText(m.agent.name, 80)} to ${sanitizeText(o.out)}. Open it in a browser.
40135
40738
  `);
@@ -40154,7 +40757,7 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
40154
40757
  `);
40155
40758
  });
40156
40759
  program2.command("watch").description("Continuous monitoring: re-check every server on an allowlist and alert on changed tools, grade drops or unreachable servers").argument("<allowlist>", "saktum-allowlist.json (from saktum allowlist)").option("--out <file>", "write the results as JSON").option("--webhook <url>", "POST a summary to this URL when something changed (for example a chat or incident webhook)").action(async (file, o) => {
40157
- const list = JSON.parse(readFileSync9(file, "utf8"));
40760
+ const list = JSON.parse(readFileSync10(file, "utf8"));
40158
40761
  const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40159
40762
  const r = await watchAllowlist(list.allowed ?? [], packs);
40160
40763
  const mark2 = { unchanged: "\u2713", changed: "\u2717", degraded: "!", unreachable: "?" };
@@ -40189,21 +40792,21 @@ Total: about ${usd(r.totalSavings)} a year.
40189
40792
  Assumptions: ${r.assumptions}.
40190
40793
  `);
40191
40794
  });
40192
- program2.command("assess").description("An executive MCP Trust Assessment for an organisation, from a fleet inventory and agent receipts (pilot deliverable)").requiredOption("--fleet <file>", "inventory JSON from saktum fleet --out").option("--org <name>", "organisation name", "Your organisation").option("--receipts <file>", "an agent's receipt log (repeatable)", collect, []).option("--out <file>", "HTML report (print to PDF from a browser)", "saktum-assessment.html").option("--agents <n>", "agents in production, for the business case", "10").option("--turns-per-day <n>", "turns a day per agent", "1000").option("--price-per-mtok <usd>", "price per million input tokens", "3").option("--vendor-reviews <n>", "AI vendor or tool security reviews a year", "20").action((o) => {
40193
- const fleet = JSON.parse(readFileSync9(o.fleet, "utf8"));
40795
+ program2.command("assess").description("An executive MCP Trust Assessment for an organisation, from a fleet inventory and agent receipts (pilot deliverable)").requiredOption("--fleet <file>", "inventory JSON from saktum fleet --out").option("--org <name>", "organisation name", "Your organisation").option("--receipts <file>", "an agent's receipt log (repeatable)", collect, []).option("--out <file>", "HTML report (print to PDF from a browser)", "saktum-assessment.html").option("--agents <n>", "agents in production, for the business case", "10").option("--turns-per-day <n>", "turns a day per agent", "1000").option("--price-per-mtok <usd>", "price per million input tokens", "3").option("--vendor-reviews <n>", "AI vendor or tool security reviews a year", "20").option("--agents-inventory <file>", "agent inventory from saktum agents scan --out").action((o) => {
40796
+ const fleet = JSON.parse(readFileSync10(o.fleet, "utf8"));
40194
40797
  const rec = o.receipts.map((f) => {
40195
- const e = parseReceiptLog(readFileSync9(f, "utf8"));
40798
+ const e = parseReceiptLog(readFileSync10(f, "utf8"));
40196
40799
  return { agent: e[0]?.receipt.envelope.caller.agent?.slice(0, 32) ?? f, summary: summariseReceipts(e), verified: verifyReceiptLog(e).ok };
40197
40800
  });
40198
40801
  const distinctTokens = (fleet.servers ?? []).reduce((a, x) => a + (x.tokens ?? 0), 0);
40199
40802
  const roi = roiEstimate({ ...ROI_DEFAULTS, tokensPerTurn: distinctTokens, agents: Number(o.agents), turnsPerDay: Number(o.turnsPerDay), pricePerMTok: Number(o.pricePerMtok), vendorReviews: Number(o.vendorReviews) });
40200
- writeFileSync5(o.out, renderAssessment(o.org, fleet, rec, roi, crosswalk().map((x) => ({ name: x.name, summary: coverageSummary(x) })), DISCLAIMER));
40803
+ writeFileSync5(o.out, renderAssessment(o.org, fleet, rec, roi, crosswalk().map((x) => ({ name: x.name, summary: coverageSummary(x) })), DISCLAIMER, o.agentsInventory ? JSON.parse(readFileSync10(o.agentsInventory, "utf8")) : void 0));
40201
40804
  process.stdout.write(`Wrote the MCP Trust Assessment for ${sanitizeText(o.org, 80)} to ${sanitizeText(o.out)}: ${fleet.servers?.length ?? 0} servers, ${fleet.nonCompliant ?? 0} violating policy. Open it in a browser and print to PDF.
40202
40805
  `);
40203
40806
  });
40204
40807
  program2.command("fleet").description("Merge scan-config results from many machines into one organisation inventory, checked against your policy").argument("<setups...>", "JSON files written by saktum scan-config --out").option("--policy <file>", "your organisation's policy").option("--out <file>", "inventory as JSON").option("--html <file>", "inventory as an HTML page").action(async (files, o) => {
40205
40808
  const setups = files.map((f) => {
40206
- const j = JSON.parse(readFileSync9(f, "utf8"));
40809
+ const j = JSON.parse(readFileSync10(f, "utf8"));
40207
40810
  return { machine: j.machine ?? f, servers: j.servers ?? [] };
40208
40811
  });
40209
40812
  const pol = o.policy ? await loadPolicy(o.policy) : void 0;
@@ -40253,20 +40856,20 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
40253
40856
  const subject = o.subject ?? (o.subjectKey ? loadOrCreateKey(o.subjectKey).kid : void 0);
40254
40857
  if (!subject)
40255
40858
  throw new Error("Give --subject <did:key> or --subject-key <file>.");
40256
- const c = issueCredential(JSON.parse(readFileSync9(o.from, "utf8")), loadOrCreateKey(o.key), { type: o.type, id: subject, name: o.name, role: o.role, expires: o.expires });
40859
+ const c = issueCredential(JSON.parse(readFileSync10(o.from, "utf8")), loadOrCreateKey(o.key), { type: o.type, id: subject, name: o.name, role: o.role, expires: o.expires });
40257
40860
  writeFileSync5(o.out, JSON.stringify(c, null, 2) + "\n");
40258
40861
  process.stdout.write(`Issued ${c.id} to ${sanitizeText(o.name, 80)} (${o.type}). Chain: ${verifyChain(c).path.join(" -> ")}
40259
40862
  `);
40260
40863
  });
40261
40864
  identity.command("verify").description("Walk a credential's chain to its organisation").argument("<credential>").option("--revoked <file>", "JSON list of revoked credential ids").action((f, o) => {
40262
- const v = verifyChain(JSON.parse(readFileSync9(f, "utf8")), { revoked: o.revoked ? JSON.parse(readFileSync9(o.revoked, "utf8")) : [] });
40865
+ const v = verifyChain(JSON.parse(readFileSync10(f, "utf8")), { revoked: o.revoked ? JSON.parse(readFileSync10(o.revoked, "utf8")) : [] });
40263
40866
  process.stdout.write(v.valid ? `\u2713 ${v.path.join(" -> ")}: accountable organisation ${v.organisation}
40264
40867
  ` : `\u2717 ${v.reason}
40265
40868
  `);
40266
40869
  exitCode = v.valid ? 0 : 1;
40267
40870
  });
40268
40871
  identity.command("orphans").description("Agents whose accountability chain is broken (expired, revoked or invalid)").argument("<credentials...>").option("--revoked <file>", "JSON list of revoked credential ids").action((fs, o) => {
40269
- const orphans = findOrphans(fs.map((f) => JSON.parse(readFileSync9(f, "utf8"))), { revoked: o.revoked ? JSON.parse(readFileSync9(o.revoked, "utf8")) : [] });
40872
+ const orphans = findOrphans(fs.map((f) => JSON.parse(readFileSync10(f, "utf8"))), { revoked: o.revoked ? JSON.parse(readFileSync10(o.revoked, "utf8")) : [] });
40270
40873
  for (const x of orphans)
40271
40874
  process.stdout.write(`\u2717 ${sanitizeText(x.agent, 80)} (${x.id}): ${x.reason}
40272
40875
  `);
@@ -40299,16 +40902,16 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
40299
40902
  });
40300
40903
  const catalog = program2.command("catalog").description("A catalogue of signed manifests, searchable by intent");
40301
40904
  catalog.command("add").argument("<manifest>").option("--catalog <file>", "catalogue file", "saktum-catalog.json").action((f, o) => {
40302
- const m = JSON.parse(readFileSync9(f, "utf8"));
40905
+ const m = JSON.parse(readFileSync10(f, "utf8"));
40303
40906
  if (!verifyDocument(m).valid)
40304
40907
  throw new Error("The manifest's signature is not valid.");
40305
- const c = existsSync7(o.catalog) ? JSON.parse(readFileSync9(o.catalog, "utf8")) : [];
40908
+ const c = existsSync7(o.catalog) ? JSON.parse(readFileSync10(o.catalog, "utf8")) : [];
40306
40909
  writeFileSync5(o.catalog, JSON.stringify([...c.filter((x) => x.server.name !== m.server.name || x.publisher.id !== m.publisher.id), m], null, 2) + "\n");
40307
40910
  process.stdout.write(`Added ${sanitizeText(m.server.name, 80)} by ${sanitizeText(m.publisher.name, 80)} to ${sanitizeText(o.catalog)}.
40308
40911
  `);
40309
40912
  });
40310
40913
  catalog.command("search").argument("<query...>").option("--catalog <file>", "catalogue file", "saktum-catalog.json").option("--max-risk <tier>", "only servers at or below this risk tier").action((q, o) => {
40311
- const res = searchCatalogue(JSON.parse(readFileSync9(o.catalog, "utf8")), q.join(" "), { maxRisk: o.maxRisk });
40914
+ const res = searchCatalogue(JSON.parse(readFileSync10(o.catalog, "utf8")), q.join(" "), { maxRisk: o.maxRisk });
40312
40915
  for (const r of res.slice(0, 10))
40313
40916
  process.stdout.write(`${String(r.score).padStart(3)} ${sanitizeText(r.manifest.server.name, 40).padEnd(24)} ${sanitizeText(r.manifest.publisher.name, 40).padEnd(20)} trust ${r.manifest.quality?.trustGrade ?? "-"} \xB7 risk ${r.manifest.quality?.riskTier ?? "-"} \xB7 ${r.matched.join(", ")}
40314
40917
  `);
@@ -40317,19 +40920,19 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
40317
40920
  });
40318
40921
  const agreement = program2.command("agreement").description("Agreements between providers and invokers (smart contracts as signed documents)");
40319
40922
  agreement.command("draft").description("As the provider, draft and sign an agreement from the default template").requiredOption("--manifest <file>").requiredOption("--invoker-name <name>").requiredOption("--invoker <did>", "the invoker organisation's id").requiredOption("--purpose <text>").option("--tools <list>", "comma-separated tools in scope").option("--tokens-per-month <n>").option("--term <text>", "a specific term (repeatable)", collect, []).option("--valid-until <date>", "YYYY-MM-DD", new Date(Date.now() + 365 * 864e5).toISOString().slice(0, 10)).option("--key <path>", "the provider's key", "saktum-publisher-key.json").option("--out <file>", "agreement file", "saktum-agreement.json").action((o) => {
40320
- const a = draftAgreement({ manifest: JSON.parse(readFileSync9(o.manifest, "utf8")), invoker: { id: o.invoker, name: o.invokerName }, purpose: o.purpose, tools: o.tools?.split(",").map((x) => x.trim()), tokensPerMonth: o.tokensPerMonth ? Number(o.tokensPerMonth) : void 0, specificTerms: o.term, validUntil: o.validUntil }, loadOrCreateKey(o.key));
40923
+ const a = draftAgreement({ manifest: JSON.parse(readFileSync10(o.manifest, "utf8")), invoker: { id: o.invoker, name: o.invokerName }, purpose: o.purpose, tools: o.tools?.split(",").map((x) => x.trim()), tokensPerMonth: o.tokensPerMonth ? Number(o.tokensPerMonth) : void 0, specificTerms: o.term, validUntil: o.validUntil }, loadOrCreateKey(o.key));
40321
40924
  writeFileSync5(o.out, JSON.stringify(a, null, 2) + "\n");
40322
40925
  process.stdout.write(`Drafted ${a.id} (${a.terms.length} default terms, ${a.specificTerms?.length ?? 0} specific), signed by the provider. The invoker accepts with: npx saktum agreement accept ${sanitizeText(o.out)} --key <invoker-key>
40323
40926
  `);
40324
40927
  });
40325
40928
  agreement.command("accept").argument("<agreement>").requiredOption("--key <path>", "the invoker's key").action((f, o) => {
40326
- const a = acceptAgreement(JSON.parse(readFileSync9(f, "utf8")), loadOrCreateKey(o.key));
40929
+ const a = acceptAgreement(JSON.parse(readFileSync10(f, "utf8")), loadOrCreateKey(o.key));
40327
40930
  writeFileSync5(f, JSON.stringify(a, null, 2) + "\n");
40328
40931
  process.stdout.write(`Accepted ${a.id}: signed by both parties.
40329
40932
  `);
40330
40933
  });
40331
40934
  agreement.command("verify").argument("<agreement>").action((f) => {
40332
- const a = JSON.parse(readFileSync9(f, "utf8"));
40935
+ const a = JSON.parse(readFileSync10(f, "utf8"));
40333
40936
  const v = verifyAgreement(a);
40334
40937
  process.stdout.write(v.valid ? `\u2713 ${a.id}: ${sanitizeText(a.provider.name, 80)} and ${sanitizeText(a.invoker.name, 80)}, until ${a.validUntil}.
40335
40938
  ` : `\u2717 ${v.reason}
@@ -40347,8 +40950,8 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
40347
40950
  });
40348
40951
  program2.command("usage").description("A usage statement for an agreement, from the receipts (optionally signed)").requiredOption("--agreement <file>").argument("[receipts]").option("--key <path>", "sign the statement with this key").option("--out <file>").action(async (f, o) => {
40349
40952
  const { homedir: homedir2 } = await import("node:os");
40350
- const { join: join6 } = await import("node:path");
40351
- const st = usageStatement(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), JSON.parse(readFileSync9(o.agreement, "utf8")), o.key ? loadOrCreateKey(o.key) : void 0);
40953
+ const { join: join7 } = await import("node:path");
40954
+ const st = usageStatement(parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), JSON.parse(readFileSync10(o.agreement, "utf8")), o.key ? loadOrCreateKey(o.key) : void 0);
40352
40955
  for (const l of st.lines)
40353
40956
  process.stdout.write(`${sanitizeText(l.tool, 60).padEnd(24)} ${String(l.calls).padStart(5)} calls ${String(l.tokens).padStart(7)} tokens
40354
40957
  `);
@@ -40359,8 +40962,8 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
40359
40962
  });
40360
40963
  program2.command("kpi").description("KPIs over receipts: calls, outcomes, approvals, tokens, latency, by tool").argument("[receipts]").option("--tool <name>").option("--agent <did>").option("--since <date>").action(async (f, o) => {
40361
40964
  const { homedir: homedir2 } = await import("node:os");
40362
- const { join: join6 } = await import("node:path");
40363
- const k = kpis(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), o);
40965
+ const { join: join7 } = await import("node:path");
40966
+ const k = kpis(parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), o);
40364
40967
  process.stdout.write(`Calls ${k.calls} \xB7 allowed ${k.allowed} \xB7 blocked ${k.blocked} \xB7 approved ${k.approvals} \xB7 tokens ${k.tokens} \xB7 latency p50 ${k.latencyP50 ?? "-"} ms, p95 ${k.latencyP95 ?? "-"} ms
40365
40968
  `);
40366
40969
  process.stdout.write(`By outcome: ${k.byOutcome.map(([c, n]) => `${c} ${n}`).join(", ")}
@@ -40368,7 +40971,7 @@ By tool: ${k.byTool.map(([c, n]) => `${c} ${n}`).join(", ")}
40368
40971
  `);
40369
40972
  });
40370
40973
  program2.command("bounty").description("Bounties (contract only for now)").command("validate").argument("<file>").action((f) => {
40371
- const ok = compileContract("bounty.schema.json")(JSON.parse(readFileSync9(f, "utf8")));
40974
+ const ok = compileContract("bounty.schema.json")(JSON.parse(readFileSync10(f, "utf8")));
40372
40975
  process.stdout.write(ok ? "\u2713 Valid bounty document.\n" : "\u2717 Not a valid bounty document.\n");
40373
40976
  exitCode = ok ? 0 : 1;
40374
40977
  });
@@ -40404,6 +41007,226 @@ ${" ".repeat(36)}${i.evidence}${i.commands.length ? ` (${i.commands.join("; ")})
40404
41007
  }
40405
41008
  process.stdout.write(`
40406
41009
  ${DISCLAIMER}
41010
+ `);
41011
+ });
41012
+ program2.command("bridge").description("Present a remote MCP server (Streamable HTTP) as a local one, so saktum proxy can govern it: saktum proxy ... -- saktum bridge https://host/mcp").argument("<url>", "the remote server's URL").option("--header <Name: value>", "HTTP header to send (repeatable; never logged). Prefer --header-env for secrets", collect, []).option("--header-env <Name=VAR>", "HTTP header whose value comes from an environment variable, e.g. Authorization=MCP_TOKEN (keeps secrets out of the process list)", collect, []).action(async (url2, o) => {
41013
+ if (!/^https?:\/\//.test(url2))
41014
+ throw new Error("Give the remote server's http(s) URL.");
41015
+ const h = parseHeaders(o.header);
41016
+ for (const x of o.headerEnv) {
41017
+ const i = x.indexOf("=");
41018
+ const v = process.env[x.slice(i + 1)];
41019
+ if (i < 1 || v === void 0)
41020
+ throw new Error(`--header-env ${x}: use Name=VAR with VAR set`);
41021
+ h[x.slice(0, i)] = v;
41022
+ }
41023
+ const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_bridge(), bridge_exports));
41024
+ exitCode = await runBridge2(url2, h);
41025
+ });
41026
+ const approvals = program2.command("approvals").description("Approvals by link (v0.10)");
41027
+ approvals.command("list").option("--approvals <file>", "approvals file").action((o) => {
41028
+ const p = listPending(o.approvals);
41029
+ for (const x of p)
41030
+ process.stdout.write(`${x.id} ${sanitizeText(x.agent, 40)} ${sanitizeText(x.tool, 40)} ${sanitizeText(x.reason, 160)} (${x.at.slice(0, 16).replace("T", " ")})
41031
+ `);
41032
+ process.stdout.write(`${p.length} waiting.
41033
+ `);
41034
+ });
41035
+ approvals.command("serve").description("A local page where the mandate's owner approves exactly one pending action (optionally with a passkey)").requiredOption("--mandate <file>").option("--key <spec>", "the owner's key (file, env:VAR, keychain:NAME or exec:PROGRAM)").option("--approvals <file>", "approvals file shared with the proxy").option("--port <n>", "port", "8787").option("--host <host>", "interface (localhost is required for passkeys)", "localhost").option("--minutes <n>", "approval validity", "60").option("--secret <spec>", "secret shared with the proxy (--approval-secret) for single-use, per-request links: env:VAR").option("--passkey", "require a passkey (Face ID, Touch ID, Windows Hello or a security key) for every approval (beta)", false).option("--passkeys <file>", "registered passkeys", "saktum-passkeys.json").action(async (o) => {
41036
+ const http = await import("node:http");
41037
+ const { randomBytes, createHmac: createHmac3 } = await import("node:crypto");
41038
+ const m = JSON.parse(readFileSync10(o.mandate, "utf8"));
41039
+ const key = loadOrCreateKey(o.key);
41040
+ const token = randomBytes(16).toString("hex");
41041
+ if (key.kid !== m.owner.id)
41042
+ throw new Error("This key is not the mandate owner's key.");
41043
+ const secret = o.secret ? secretFrom(o.secret) : "";
41044
+ const origin = `http://${o.host}:${o.port}`, rpId = o.host;
41045
+ const nonces = /* @__PURE__ */ new Map();
41046
+ const pks = () => existsSync7(o.passkeys) ? JSON.parse(readFileSync10(o.passkeys, "utf8")) : [];
41047
+ const esc22 = (x) => String(x).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
41048
+ const js = `const b=s=>Uint8Array.from(atob(s.replace(/-/g,'+').replace(/_/g,'/')),c=>c.charCodeAt(0)),u=a=>btoa(String.fromCharCode(...new Uint8Array(a))).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,'');`;
41049
+ const pageOf = (body2) => `<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><title>Saktum approvals</title><body style="font:15px system-ui;max-width:760px;margin:24px auto;padding:0 16px"><h1>Approvals for ${esc22(m.agent.name)}</h1>${body2}<script>${js}</script></body>`;
41050
+ const okToken = (u, id) => u.searchParams.get("token") === token || Boolean(secret) && Boolean(id) && u.searchParams.get("t") === createHmac3("sha256", secret).update(id).digest("hex").slice(0, 32);
41051
+ const item = (x, q) => {
41052
+ const n = randomBytes(12).toString("hex");
41053
+ nonces.set(x.id, n);
41054
+ const ch = `${x.id}:${n}`;
41055
+ return `<form data-id="${esc22(x.id)}" data-ch="${esc22(ch)}" method="post" action="/approve?${q}" style="border:1px solid #ddd;border-radius:12px;padding:12px;margin:10px 0"><b>${esc22(x.tool)}</b> <code>${esc22(x.id)}</code><p>${esc22(x.reason)}</p><small>${esc22(x.at)}</small><input type="hidden" name="id" value="${esc22(x.id)}"><p><button type="submit">Approve exactly this action, once${o.passkey ? " (with your passkey)" : ""}</button></p></form>`;
41056
+ };
41057
+ const pkScript = o.passkey ? `<script>document.querySelectorAll('form[data-ch]').forEach(f=>f.addEventListener('submit',async e=>{e.preventDefault();const ids=${JSON.stringify(pks().map((p) => p.credentialId))};const c=await navigator.credentials.get({publicKey:{challenge:new TextEncoder().encode(f.dataset.ch),rpId:${JSON.stringify(rpId)},allowCredentials:ids.map(i=>({type:'public-key',id:b(i)})),userVerification:'required'}});const r=c.response;const res=await fetch(f.action,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:f.dataset.id,credentialId:u(c.rawId),authenticatorData:u(r.authenticatorData),clientDataJSON:u(r.clientDataJSON),signature:u(r.signature)})});document.body.insertAdjacentHTML('beforeend',await res.text());}));</script>` : "";
41058
+ const server = http.createServer((req, res) => {
41059
+ const u = new URL(req.url ?? "/", origin);
41060
+ const send = (code, html) => {
41061
+ res.writeHead(code, { "Content-Type": "text/html", "X-Frame-Options": "DENY", "Content-Security-Policy": "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; frame-ancestors 'none'" });
41062
+ res.end(html);
41063
+ };
41064
+ if (u.pathname === "/passkey/register") {
41065
+ if (u.searchParams.get("token") !== token)
41066
+ return send(403, "Forbidden");
41067
+ if (req.method === "GET") {
41068
+ const ch = randomBytes(16).toString("hex");
41069
+ nonces.set("register", ch);
41070
+ return send(200, pageOf(`<p>Register a passkey for approving ${esc22(m.agent.name)}'s actions.</p><button id="r">Register a passkey</button><p id="o"></p><script>document.getElementById('r').onclick=async()=>{const c=await navigator.credentials.create({publicKey:{challenge:new TextEncoder().encode(${JSON.stringify(ch)}),rp:{name:'Saktum approvals',id:${JSON.stringify(rpId)}},user:{id:new TextEncoder().encode(${JSON.stringify(m.owner.id.slice(-32))}),name:${JSON.stringify(m.owner.name ?? "owner")},displayName:${JSON.stringify(m.owner.name ?? "owner")}},pubKeyCredParams:[{type:'public-key',alg:-7},{type:'public-key',alg:-8}],authenticatorSelection:{userVerification:'required'},attestation:'none'}});const res=await fetch(location.href,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({attestationObject:u(c.response.attestationObject),clientDataJSON:u(c.response.clientDataJSON)})});document.getElementById('o').textContent=await res.text();};</script>`));
41071
+ }
41072
+ let b = "";
41073
+ req.on("data", (c) => {
41074
+ b += c;
41075
+ if (b.length > 2e4)
41076
+ req.destroy();
41077
+ });
41078
+ req.on("end", () => {
41079
+ try {
41080
+ const r = verifyPasskeyRegistration(JSON.parse(b), { challenge: nonces.get("register") ?? "", origin, rpId });
41081
+ writeFileSync5(o.passkeys, JSON.stringify([...pks(), { ...r, binding: signDocument({ credentialId: r.credentialId, owner: m.owner.id, at: (/* @__PURE__ */ new Date()).toISOString() }, key) }], null, 2));
41082
+ nonces.delete("register");
41083
+ res.writeHead(200);
41084
+ res.end("Passkey registered. Restart approvals serve to use it.");
41085
+ } catch (e) {
41086
+ res.writeHead(400);
41087
+ res.end(`Registration failed: ${e.message}`);
41088
+ }
41089
+ });
41090
+ return;
41091
+ }
41092
+ if (req.method === "POST" && u.pathname === "/approve") {
41093
+ let b = "";
41094
+ req.on("data", (c) => {
41095
+ b += c;
41096
+ if (b.length > 2e4)
41097
+ req.destroy();
41098
+ });
41099
+ req.on("end", () => {
41100
+ let id = "", assertion = {};
41101
+ try {
41102
+ if ((req.headers["content-type"] ?? "").includes("json")) {
41103
+ const j = JSON.parse(b);
41104
+ id = j.id;
41105
+ assertion = j;
41106
+ } else
41107
+ id = new URLSearchParams(b).get("id") ?? "";
41108
+ } catch {
41109
+ }
41110
+ if (!okToken(u, id))
41111
+ return send(403, "Forbidden");
41112
+ if (!listPending(o.approvals).some((p2) => p2.id === id))
41113
+ return send(400, `<p>No pending request ${esc22(id)}.</p>`);
41114
+ if (o.passkey) {
41115
+ const pk = pks().find((p2) => p2.credentialId === assertion.credentialId && verifyDocument(p2.binding).kid === m.owner.id);
41116
+ let ok = false;
41117
+ try {
41118
+ ok = Boolean(pk) && verifyPasskeyAssertion(assertion, pk.jwk, { challenge: `${id}:${nonces.get(id) ?? ""}`, origin, rpId });
41119
+ } catch {
41120
+ ok = false;
41121
+ }
41122
+ if (!ok)
41123
+ return send(403, "<p>\u2717 Passkey check failed. Nothing was approved.</p>");
41124
+ nonces.delete(id);
41125
+ }
41126
+ approveAction(m, id, key, Number(o.minutes), o.approvals);
41127
+ send(200, `<p>\u2713 Approved <code>${esc22(id)}</code>, once, for ${esc22(o.minutes)} minutes${o.passkey ? ", confirmed with your passkey" : ""}. The agent can retry exactly that action.</p>`);
41128
+ });
41129
+ return;
41130
+ }
41131
+ const only = u.searchParams.get("id") ?? void 0;
41132
+ if (!okToken(u, only))
41133
+ return send(403, "Forbidden");
41134
+ const q = u.searchParams.get("token") ? `token=${token}` : `t=${u.searchParams.get("t")}`;
41135
+ const p = listPending(o.approvals).filter((x) => !only || x.id === only);
41136
+ send(200, pageOf((o.passkey && !pks().length ? `<p>No passkey registered yet: <a href="/passkey/register?token=${token}">register one</a> (owner only).</p>` : "") + (p.length ? p.map((x) => item(x, q)).join("") : "<p>Nothing is waiting for approval.</p>") + pkScript));
41137
+ });
41138
+ server.listen(Number(o.port), o.host, () => process.stdout.write(`Approvals page (owner): ${origin}/?token=${token}
41139
+ ${secret ? "Per-request links: give the proxy the same --approval-secret and --approval-url " + origin + "\n" : ""}${o.passkey ? `Passkeys: register at ${origin}/passkey/register?token=${token}
41140
+ ` : ""}Ctrl+C to stop.
41141
+ `));
41142
+ await new Promise(() => void 0);
41143
+ });
41144
+ program2.command("agents").description("Agent inventory (v0.10)").command("scan").argument("[dirs...]", "folders to search for agent mandates (default: this folder and ~/.saktum)").option("--out <file>", "write the inventory as JSON (for saktum assess --agents)").action(async (dirs, o) => {
41145
+ const { homedir: homedir2 } = await import("node:os");
41146
+ const { join: join7 } = await import("node:path");
41147
+ const a = scanAgents(dirs.length ? dirs : [".", join7(homedir2(), ".saktum")]);
41148
+ for (const x of a)
41149
+ process.stdout.write(`${x.revoked ? "\u26D4" : x.valid ? "\u2713" : "\u2717"} ${sanitizeText(x.name, 40).padEnd(26)} owner ${sanitizeText(x.owner, 30).padEnd(16)} ${x.operator ? "operator " + sanitizeText(x.operator, 30) : "no operator"} \xB7 ${x.autonomy} \xB7 ${x.riskTier} \xB7 ${x.maturity}
41150
+ `);
41151
+ process.stdout.write(`${a.length} agent(s); ${a.filter((x) => !x.operator).length} without an operator countersignature; ${a.filter((x) => x.revoked).length} revoked.
41152
+ `);
41153
+ if (o.out)
41154
+ writeFileSync5(o.out, JSON.stringify(a, null, 2) + "\n");
41155
+ });
41156
+ const ledger2 = program2.commands.find((c) => c.name() === "ledger");
41157
+ ledger2.command("rotate").description("Record a key rotation: signed by the old key, with proof of possession of the new key").requiredOption("--old-key <spec>").requiredOption("--new-key <spec>").option("--out <file>", "statement file", "saktum-rotation.json").action((o) => {
41158
+ const ok = loadOrCreateKey(o.oldKey), nk = loadOrCreateKey(o.newKey);
41159
+ const st = signDocument({ statementFormat: "0.1", type: "key-rotation", oldKey: ok.kid, newKey: nk.kid, newKeyProof: signDocument({ rotates: ok.kid, at: (/* @__PURE__ */ new Date()).toISOString() }, nk), at: (/* @__PURE__ */ new Date()).toISOString() }, ok);
41160
+ writeFileSync5(o.out, JSON.stringify(st, null, 2) + "\n");
41161
+ process.stdout.write(`Rotation statement written to ${sanitizeText(o.out)}. Publish it to the ledger like an attestation (saktum ledger append, or the attest issue).
41162
+ `);
41163
+ });
41164
+ ledger2.command("revoke-entry").description("Revoke one of your attestations (by its result digest) or your key, as a ledger statement").requiredOption("--key <spec>").requiredOption("--target <digest-or-did>").option("--reason <text>").option("--out <file>", "statement file", "saktum-revocation.json").action((o) => {
41165
+ const k = loadOrCreateKey(o.key);
41166
+ writeFileSync5(o.out, JSON.stringify(signDocument({ statementFormat: "0.1", type: "revocation", target: o.target, ...o.reason ? { reason: o.reason } : {}, at: (/* @__PURE__ */ new Date()).toISOString() }, k), null, 2) + "\n");
41167
+ process.stdout.write(`Revocation statement written to ${sanitizeText(o.out)}.
41168
+ `);
41169
+ });
41170
+ ledger2.command("checkpoint").description("Sign a checkpoint of the ledger's current head").argument("[source]", "ledger file or URL", DEFAULT_LEDGER_URL).option("--key <spec>").option("--out <file>", "checkpoint file", "ledger-checkpoint.json").action(async (src, o) => {
41171
+ const e = parseLedger(await readLedgerText(src));
41172
+ const cp = makeCheckpoint(e, loadOrCreateKey(o.key), "saktum-ledger");
41173
+ writeFileSync5(o.out, JSON.stringify(cp, null, 2) + "\n");
41174
+ process.stdout.write(`Checkpoint at entry ${cp.seq} written to ${sanitizeText(o.out)}.
41175
+ `);
41176
+ });
41177
+ ledger2.command("witness").description("Independently check the ledger against a checkpoint and add your witness signature").argument("<checkpoint>").option("--ledger <source>", "ledger file or URL", DEFAULT_LEDGER_URL).option("--key <spec>").action(async (f, o) => {
41178
+ const cp = JSON.parse(readFileSync10(f, "utf8"));
41179
+ const e = parseLedger(await readLedgerText(o.ledger));
41180
+ if (!verifyLedger(e).ok)
41181
+ throw new Error("The ledger does not verify.");
41182
+ const w = witnessCheckpoint(cp, e, loadOrCreateKey(o.key));
41183
+ writeFileSync5(f, JSON.stringify(w, null, 2) + "\n");
41184
+ process.stdout.write(`Witnessed. Valid witnesses: ${validWitnesses(w).length}.
41185
+ `);
41186
+ });
41187
+ ledger2.command("check").description("Check a ledger or receipt log against a checkpoint (detects deletion and rewriting)").argument("<checkpoint>").option("--ledger <source>").option("--receipts <file>").action(async (f, o) => {
41188
+ const cp = JSON.parse(readFileSync10(f, "utf8"));
41189
+ const e = o.receipts ? parseReceiptLog(readFileSync10(o.receipts, "utf8")) : parseLedger(await readLedgerText(o.ledger ?? DEFAULT_LEDGER_URL));
41190
+ const r = verifyAgainstCheckpoint(e, cp);
41191
+ process.stdout.write(r.ok ? `\u2713 Consistent with the checkpoint at ${cp.seq} (${validWitnesses(cp).length} witness signature(s)).
41192
+ ` : `\u2717 ${r.reason}
41193
+ `);
41194
+ exitCode = r.ok ? 0 : 1;
41195
+ });
41196
+ org.command("verify-domain").description("Verify that an organisation controls its domain (DNS TXT _saktum.<domain> or https://<domain>/.well-known/saktum.json)").argument("<credential>", "the organisation's credential").action(async (f) => {
41197
+ const c = JSON.parse(readFileSync10(f, "utf8"));
41198
+ const d = c.issuer.domain;
41199
+ if (!d)
41200
+ throw new Error("This credential names no domain (org init --domain).");
41201
+ const r = await verifyDomain(d, c.subject.id);
41202
+ process.stdout.write(r.verified ? `\u2713 ${d} is verified for ${sanitizeText(c.subject.name, 80)} (${r.method}).
41203
+ ` : `\u2717 Not verified. Add a DNS TXT record:
41204
+ _saktum.${d} "saktum-did=${c.subject.id}"
41205
+ or publish https://${d}/.well-known/saktum.json containing {"did":"${c.subject.id}"}.
41206
+ `);
41207
+ exitCode = r.verified ? 0 : 1;
41208
+ });
41209
+ wallet.command("verify").option("--wallet <file>", "wallet file", "saktum-wallet.json").action((o) => {
41210
+ const r = verifyWallet(o.wallet);
41211
+ process.stdout.write(r.ok ? "\u2713 Wallet entries intact (chained and, where signed, signatures valid).\n" : `\u2717 ${r.errors.join("; ")}
41212
+ `);
41213
+ exitCode = r.ok ? 0 : 1;
41214
+ });
41215
+ program2.command("self-verify").description("Check that the saktum you are running matches the published, signed release").action(async () => {
41216
+ const { createHash: createHash4 } = await import("node:crypto");
41217
+ const self = process.argv[1];
41218
+ const mine = createHash4("sha256").update(readFileSync10(self)).digest("hex");
41219
+ let published = "";
41220
+ try {
41221
+ const r = await fetch(`https://github.com/soodhere/saktum-check/releases/download/v${ENGINE_VERSION}/saktum.mjs.sha256`);
41222
+ if (r.ok)
41223
+ published = (await r.text()).trim().split(/\s+/)[0] ?? "";
41224
+ } catch {
41225
+ }
41226
+ process.stdout.write(`This copy (${sanitizeText(self, 120)}): sha256 ${mine}
41227
+ Published v${ENGINE_VERSION}: ${published || "(not reachable)"}
41228
+ ${published ? published === mine ? "\u2713 Matches the published release.\n" : "\u2717 Does not match the published bundle (npm installs add a wrapper; compare the release asset saktum.mjs).\n" : ""}Signature: cosign verify-blob --bundle saktum.mjs.sigstore.json --certificate-identity-regexp "https://github.com/soodhere/saktum-check/" --certificate-oidc-issuer https://token.actions.githubusercontent.com saktum.mjs
41229
+ npm provenance: npm audit signatures
40407
41230
  `);
40408
41231
  });
40409
41232
  program2.command("demo").description("See permissions, autonomy, risk and receipts in 60 seconds: one shopping agent under three mandates").option("--out <dir>", "folder for the demo's mandates, receipts and passports", "saktum-demo").option("--story <name>", "grocery, travel, finance, coding, marketplace, autonomy, or all (grocery, travel, finance, coding and marketplace)", "all").action(async (o) => {
@@ -40420,7 +41243,7 @@ ${DISCLAIMER}
40420
41243
  await startMcpServer2(packs);
40421
41244
  });
40422
41245
  program2.command("attest").description("Turn a signed result into a compact signed attestation for your README or registry listing").argument("<result>", "a signed result (saktum-report.json)").option("--out <file>", "attestation file", "saktum-attestation.json").option("--key <path>", "signing key file").option("--publish", "also print a link that publishes it to the public Saktum trust ledger (a pre-filled GitHub issue)", false).option("--vc", "also write it as a W3C Verifiable Credential (vc+jwt, issued by your did:key)", false).action((file, o) => {
40423
- const doc = JSON.parse(readFileSync9(file, "utf8"));
41246
+ const doc = JSON.parse(readFileSync10(file, "utf8"));
40424
41247
  const v = verifyDocument(doc);
40425
41248
  if (!v.valid)
40426
41249
  throw new Error(`The result's signature is not valid (${v.reason}); attestations are built only from unaltered signed results.`);
@@ -40463,7 +41286,7 @@ ${url2}
40463
41286
  exitCode = r.code;
40464
41287
  });
40465
41288
  program2.command("verify").description("Verify a signed Saktum Check result").argument("<file>").action((file) => {
40466
- const doc = JSON.parse(readFileSync9(file, "utf8"));
41289
+ const doc = JSON.parse(readFileSync10(file, "utf8"));
40467
41290
  const validate2 = compileContract("result.schema.json");
40468
41291
  if (!validate2(doc)) {
40469
41292
  process.stdout.write(`Invalid result format: ${JSON.stringify(validate2.errors?.slice(0, 2))}