saktum 0.13.0 → 0.14.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 +11 -1
  2. package/package.json +1 -1
  3. package/saktum.mjs +191 -38
package/README.md CHANGED
@@ -11,6 +11,16 @@ npx saktum check https://your-server.example/mcp # a remote server (sign-in
11
11
 
12
12
  Runs on your machine. Nothing is uploaded. Your own environment variables are never passed to the server.
13
13
 
14
+ ## Industry-ready governance (v0.14)
15
+
16
+ - **Resource-scoped credentials:** `identity issue --where legal.case_id=C-7731` limits an agent to the cases (or
17
+ accounts, patients, tickets) it is assigned; scope can only narrow down the chain, and the proxy enforces it.
18
+ - **Required fields per action class:** a rule such as `{ "field": "legal.citation", "op": "present", "actions":
19
+ ["communicate"] }` refuses client messages that cite no source.
20
+ - **Supervised autonomy:** `"review": { "sample": 0.2, "actions": ["change"] }` lets an agent act while a share of its
21
+ actions is queued for human review (`saktum receipts review receipts.jsonl`).
22
+ - **Legal vocabulary** and `npx saktum demo --story legal`; see the legal-tech industry demo on the website.
23
+
14
24
  ## Close the nine gaps (v0.13)
15
25
 
16
26
  Saktum now addresses all nine common agent security gaps at the tool layer: **task-scoped, short-lived agent
@@ -256,7 +266,7 @@ servers not on your allowlist, and the weakest grades. Configured secrets are ne
256
266
 
257
267
  ```yaml
258
268
  - uses: actions/checkout@v4
259
- - uses: soodhere/saktum-check@v0.13.0
269
+ - uses: soodhere/saktum-check@v0.14.0
260
270
  with:
261
271
  target: "-- node build/index.js" # or an https URL
262
272
  args: "--active --tests saktum.tests.yaml" # optional; --active only for your own server
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "saktum",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Test MCP servers in one command: conformance, sign-in, security (OWASP MCP Top 10), agent experience, context cost and performance.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
package/saktum.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Saktum Check 0.13.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
2
+ // Saktum Check 0.14.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;
@@ -19516,8 +19516,7 @@ var init_embedded = __esm({
19516
19516
  "additionalProperties": false,
19517
19517
  "required": [
19518
19518
  "field",
19519
- "op",
19520
- "value"
19519
+ "op"
19521
19520
  ],
19522
19521
  "properties": {
19523
19522
  "field": {
@@ -19526,17 +19525,24 @@ var init_embedded = __esm({
19526
19525
  },
19527
19526
  "op": {
19528
19527
  "enum": [
19529
- "max",
19530
- "min",
19531
19528
  "eq",
19532
19529
  "in",
19533
- "notIn"
19530
+ "max",
19531
+ "min",
19532
+ "notIn",
19533
+ "present"
19534
19534
  ]
19535
19535
  },
19536
19536
  "value": {},
19537
19537
  "label": {
19538
19538
  "type": "string",
19539
19539
  "maxLength": 200
19540
+ },
19541
+ "actions": {
19542
+ "type": "array",
19543
+ "items": {
19544
+ "type": "string"
19545
+ }
19540
19546
  }
19541
19547
  }
19542
19548
  }
@@ -19642,6 +19648,26 @@ var init_embedded = __esm({
19642
19648
  "operatorCountersign": {
19643
19649
  "type": "object",
19644
19650
  "description": "The operator's signed statement over the mandate digest (role, name, mandate, at, signature)"
19651
+ },
19652
+ "review": {
19653
+ "type": "object",
19654
+ "properties": {
19655
+ "sample": {
19656
+ "type": "number",
19657
+ "minimum": 0,
19658
+ "maximum": 1
19659
+ },
19660
+ "actions": {
19661
+ "type": "array",
19662
+ "items": {
19663
+ "type": "string"
19664
+ }
19665
+ }
19666
+ },
19667
+ "required": [
19668
+ "sample"
19669
+ ],
19670
+ "additionalProperties": false
19645
19671
  }
19646
19672
  }
19647
19673
  }
@@ -34057,7 +34083,7 @@ var init_dist3 = __esm({
34057
34083
  init_stdio2();
34058
34084
  init_streamableHttp();
34059
34085
  init_types2();
34060
- USER_AGENT = "saktum-check/0.13.0 (+https://saktum.dev/check)";
34086
+ USER_AGENT = "saktum-check/0.14.0 (+https://saktum.dev/check)";
34061
34087
  LIMITS = { requestTimeoutMs: 1e4, connectTimeoutMs: 6e4, maxResponseChars: 5e6 };
34062
34088
  LimitError = class extends Error {
34063
34089
  };
@@ -34095,7 +34121,7 @@ var init_dist3 = __esm({
34095
34121
  jsonrpc: "2.0",
34096
34122
  id: 1,
34097
34123
  method: "initialize",
34098
- params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.13.0" } }
34124
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.14.0" } }
34099
34125
  });
34100
34126
  }
34101
34127
  });
@@ -35467,7 +35493,7 @@ var init_engine = __esm({
35467
35493
  init_runner();
35468
35494
  init_safe();
35469
35495
  init_scoring();
35470
- ENGINE_VERSION = "0.13.0";
35496
+ ENGINE_VERSION = "0.14.0";
35471
35497
  UNKNOWN_TOOL = "saktum_trust_check_no_such_tool";
35472
35498
  INVALID_TOKEN = "saktum-check-deliberately-invalid-token";
35473
35499
  baseOf = (pack, check) => ({
@@ -36115,6 +36141,14 @@ var init_vocab = __esm({
36115
36141
  { path: "support.customer_id", type: "string", description: "The customer a support case is about" },
36116
36142
  { path: "support.amount", type: "number", description: "A refund or credit amount" }
36117
36143
  ] };
36144
+ VOCABULARIES.legal = { version: "0.1", fields: [
36145
+ { path: "legal.case_id", type: "string", description: "The legal matter (case) an action concerns" },
36146
+ { path: "legal.client_id", type: "string", description: "The client the matter is for" },
36147
+ { path: "legal.practice_area", type: "string", description: "Practice area, e.g. economic immigration, family sponsorship" },
36148
+ { path: "legal.document_type", type: "string", description: "Type of document, e.g. passport, language test, reference letter" },
36149
+ { path: "legal.citation", type: "string", description: "Source cited for a statement: rule version, official page or case evidence" },
36150
+ { path: "legal.rule_version", type: "string", description: "Version of the rule pack used for a score or eligibility result" }
36151
+ ] };
36118
36152
  KNOWN_FIELDS = new Set(Object.values(VOCABULARIES).flatMap((v) => v.fields.map((f) => f.path)));
36119
36153
  NAME_RULES = [
36120
36154
  [/(^|[_-])(search|find|list|get|lookup|deals|browse)([_-]|$)/i, "search"],
@@ -36257,7 +36291,8 @@ function createMandate(o, ownerKey) {
36257
36291
  ...o.upsell ? { upsell: o.upsell } : {},
36258
36292
  ...o.approvalTriggers?.length ? { approvalTriggers: o.approvalTriggers } : {},
36259
36293
  ...o.counterparties?.length ? { counterparties: o.counterparties } : {},
36260
- ...o.dataSharing?.length ? { dataSharing: o.dataSharing } : {}
36294
+ ...o.dataSharing?.length ? { dataSharing: o.dataSharing } : {},
36295
+ ...o.review && o.review.sample > 0 ? { review: { sample: Math.min(1, o.review.sample), ...o.review.actions?.length ? { actions: o.review.actions } : {} } } : {}
36261
36296
  };
36262
36297
  return signDocument(body2, ownerKey);
36263
36298
  }
@@ -36342,6 +36377,15 @@ function decideIntent(m, tool, args, ctx = {}) {
36342
36377
  if (auto === "notify" && cls !== "search")
36343
36378
  return stop("notify-only", `only alerts for ${cls}: tell your user instead`);
36344
36379
  for (const rule of m.rules ?? []) {
36380
+ if (rule.actions && !rule.actions.includes(cls))
36381
+ continue;
36382
+ if (rule.op === "present") {
36383
+ const ok2 = rule.field in v && String(v[rule.field] ?? "").trim() !== "";
36384
+ r.evaluated.push({ rule: ruleText(rule), ok: ok2 });
36385
+ if (!ok2)
36386
+ return stop("rule-violated", ruleText(rule));
36387
+ continue;
36388
+ }
36345
36389
  if (!(rule.field in v))
36346
36390
  continue;
36347
36391
  const x = v[rule.field];
@@ -36584,7 +36628,7 @@ var init_agentid = __esm({
36584
36628
  init_safe();
36585
36629
  init_receipts();
36586
36630
  FIELD_LABEL = (f) => VOCABULARIES[f.split(".")[0]]?.fields.find((x) => x.path === f)?.description.toLowerCase() ?? f;
36587
- ruleText = (r) => r.label ?? (r.op === "max" ? `${FIELD_LABEL(r.field)} at most ${r.value}` : r.op === "min" ? `${FIELD_LABEL(r.field)} at least ${r.value}` : r.op === "eq" ? `${FIELD_LABEL(r.field)}: ${r.value === true ? "yes" : r.value === false ? "no" : String(r.value)}` : r.op === "in" ? `${FIELD_LABEL(r.field)} only ${r.value.join(", ")}` : `never ${r.value.join(", ")} (${FIELD_LABEL(r.field)})`);
36631
+ ruleText = (r) => r.label ?? (r.op === "present" ? `${FIELD_LABEL(r.field)} must be given` : r.op === "max" ? `${FIELD_LABEL(r.field)} at most ${r.value}` : r.op === "min" ? `${FIELD_LABEL(r.field)} at least ${r.value}` : r.op === "eq" ? `${FIELD_LABEL(r.field)}: ${r.value === true ? "yes" : r.value === false ? "no" : String(r.value)}` : r.op === "in" ? `${FIELD_LABEL(r.field)} only ${r.value.join(", ")}` : `never ${r.value.join(", ")} (${FIELD_LABEL(r.field)})`);
36588
36632
  DEFAULT_REVOCATIONS = () => _join(_home(), ".saktum", "revocations.json");
36589
36633
  readRevocations = (path) => {
36590
36634
  try {
@@ -36776,9 +36820,16 @@ function issueCredential(issuerCred, issuerKey, s) {
36776
36820
  if (issuerCred.maxDepth !== void 0 && issuerCred.maxDepth < 1)
36777
36821
  throw new Error("The issuer's credential does not allow further delegation.");
36778
36822
  const tools = s.tools ?? parentTools;
36823
+ const pw = issuerCred.scope?.where;
36824
+ if (pw) {
36825
+ for (const [f, vals] of Object.entries(pw))
36826
+ if (s.where && s.where[f] && s.where[f].some((x) => !vals.includes(x)))
36827
+ throw new Error(`The issuer may only grant ${f} within ${vals.join(", ")}.`);
36828
+ }
36829
+ const where = s.where || pw ? { ...pw ?? {}, ...s.where ?? {} } : void 0;
36779
36830
  const maxDepth2 = issuerCred.maxDepth !== void 0 ? Math.min(s.maxDepth ?? issuerCred.maxDepth - 1, issuerCred.maxDepth - 1) : s.maxDepth;
36780
36831
  const chain = [...issuerCred.chain ?? [], { ...issuerCred, chain: void 0 }].map((c2) => JSON.parse(JSON.stringify(c2)));
36781
- const c = { credentialFormat: "0.1", type: s.type, ...tools ? { scope: { tools } } : {}, ...maxDepth2 !== void 0 ? { maxDepth: maxDepth2 } : {}, subject: { id: s.id, name: s.name, ...s.role ? { role: s.role } : {} }, issuer: { id: issuerKey.kid, name: issuerCred.subject.name, ...issuerCred.issuer.domain ? { domain: issuerCred.issuer.domain } : {} }, issuedAt: nowIso(), expires: s.expires };
36832
+ const c = { credentialFormat: "0.1", type: s.type, ...tools || where ? { scope: { ...tools ? { tools } : {}, ...where ? { where } : {} } } : {}, ...maxDepth2 !== void 0 ? { maxDepth: maxDepth2 } : {}, subject: { id: s.id, name: s.name, ...s.role ? { role: s.role } : {} }, issuer: { id: issuerKey.kid, name: issuerCred.subject.name, ...issuerCred.issuer.domain ? { domain: issuerCred.issuer.domain } : {} }, issuedAt: nowIso(), expires: s.expires };
36782
36833
  return { ...signDocument({ ...c, id: short("cred_", c) }, issuerKey), chain };
36783
36834
  }
36784
36835
  function verifyChain(c, o = {}) {
@@ -36806,12 +36857,15 @@ function verifyChain(c, o = {}) {
36806
36857
  return { valid: false, path, reason: `${l.subject.name}'s credential grants more than its issuer holds` };
36807
36858
  if (l.expires > p.expires)
36808
36859
  return { valid: false, path, reason: `${l.subject.name}'s credential outlives its issuer's` };
36860
+ for (const [f, vals] of Object.entries(p.scope?.where ?? {}))
36861
+ if (!l.scope?.where?.[f] || l.scope.where[f].some((x) => !vals.includes(x)))
36862
+ return { valid: false, path, reason: `${l.subject.name}'s credential reaches beyond its issuer's ${f}` };
36809
36863
  }
36810
36864
  if (l.maxDepth !== void 0 && links.length - 1 - i > l.maxDepth)
36811
36865
  return { valid: false, path, reason: `the chain delegates deeper than ${l.subject.name}'s credential allows (${l.maxDepth})` };
36812
36866
  path.push(`${l.subject.name}${l.subject.role ? ` (${l.subject.role})` : ""}`);
36813
36867
  }
36814
- return { valid: true, path, organisation: links[0].subject.name + (links[0].issuer.domain ? ` (${links[0].issuer.domain})` : ""), ...links[links.length - 1].scope?.tools ? { tools: links[links.length - 1].scope.tools } : {} };
36868
+ return { valid: true, path, organisation: links[0].subject.name + (links[0].issuer.domain ? ` (${links[0].issuer.domain})` : ""), ...links[links.length - 1].scope?.tools ? { tools: links[links.length - 1].scope.tools } : {}, ...links[links.length - 1].scope?.where ? { where: links[links.length - 1].scope.where } : {} };
36815
36869
  }
36816
36870
  function findOrphans(creds, o = {}) {
36817
36871
  return creds.filter((c) => c.type === "agent").map((c) => ({ agent: c.subject.name, id: c.subject.id, ...verifyChain(c, o) })).filter((x) => !x.valid);
@@ -38429,7 +38483,17 @@ async function runProxy(o) {
38429
38483
  d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
38430
38484
  else if (vc.tools && !vc.tools.includes(tool))
38431
38485
  d = { allow: false, code: "outside-credential-scope", reason: `the agent's credential covers only ${vc.tools.join(", ")}` };
38432
- else if (o.agreement && root !== o.agreement.invoker.id)
38486
+ else if (vc.where) {
38487
+ const b = bindingsFor(toolDefs.get(tool) ?? { name: tool }).bindings;
38488
+ for (const [arg, field] of Object.entries(b)) {
38489
+ const allowed = vc.where[field];
38490
+ const val = args[arg];
38491
+ if (allowed && val !== void 0 && !allowed.includes(String(val))) {
38492
+ d = { allow: false, code: "outside-credential-scope", reason: `the agent's credential covers ${field} ${allowed.join(", ")} only (got ${String(val)})` };
38493
+ break;
38494
+ }
38495
+ }
38496
+ } else if (o.agreement && root !== o.agreement.invoker.id)
38433
38497
  d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
38434
38498
  }
38435
38499
  if (d.allow && o.agreement) {
@@ -38510,14 +38574,16 @@ async function runProxy(o) {
38510
38574
  const status = msg.error ? "protocol-error" : msg.result?.isError ? "tool-error" : "ok";
38511
38575
  const text2 = msg.result ? resultText(msg.result) : "";
38512
38576
  const hidden = text2 ? findHiddenInstruction(text2, { broad: true }) : void 0, secret = text2 ? findSecret(text2) : void 0;
38513
- const flags = [...hidden ? ["hidden-instruction-in-result"] : [], ...secret ? [`secret-in-result:${secret}`] : []];
38577
+ const rv = o.mandate?.review;
38578
+ const sampled = Boolean(rv && !msg.error && (!rv.actions || rv.actions.includes(actionClass(toolDefs.get(c.tool) ?? { name: c.tool }).cls)) && parseInt(sha256Tag(c.argsHash + c.start).slice(7, 15), 16) / 4294967295 < rv.sample);
38579
+ const flags = [...hidden ? ["hidden-instruction-in-result"] : [], ...secret ? [`secret-in-result:${secret}`] : [], ...sampled ? ["review-sampled"] : []];
38514
38580
  if (flags.length)
38515
38581
  o.log?.(`${c.tool}: result flagged (${flags.join(", ")})`);
38516
- if (flags.length && o.quarantineResults) {
38582
+ if ((hidden || secret) && o.quarantineResults) {
38517
38583
  msg.result = { content: [{ type: "text", text: `Withheld by Saktum: this tool's result contained ${hidden ? "instructions aimed at the agent" : "what looks like a secret"}. Ask the user before continuing.` }], isError: true };
38518
38584
  line = JSON.stringify(msg);
38519
38585
  }
38520
- record2(c.tool, c.argsHash, msg.error ? "error" : "allow", c.reason + (flags.length ? ` [result ${o.quarantineResults ? "withheld" : "flagged"}: ${flags.join(", ")}]` : ""), { status, latencyMs: Date.now() - c.start, destructive: c.destructive, code: c.code, values: c.values, outputDigest: digest(msg.result ?? msg.error ?? null), ...flags.length ? { flags } : {}, ...c.rationale ? { rationale: c.rationale } : {}, ...c.metering ? { metering: c.metering } : {} });
38586
+ record2(c.tool, c.argsHash, msg.error ? "error" : "allow", c.reason + (hidden || secret ? ` [result ${o.quarantineResults ? "withheld" : "flagged"}: ${flags.filter((f) => f !== "review-sampled").join(", ")}]` : "") + (sampled ? " [sampled for human review]" : ""), { status, latencyMs: Date.now() - c.start, destructive: c.destructive, code: c.code, values: c.values, outputDigest: digest(msg.result ?? msg.error ?? null), ...flags.length ? { flags } : {}, ...c.rationale ? { rationale: c.rationale } : {}, ...c.metering ? { metering: c.metering } : {} });
38521
38587
  }
38522
38588
  process.stdout.write(line + "\n");
38523
38589
  });
@@ -39291,7 +39357,7 @@ __export(demo_exports, {
39291
39357
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync4, existsSync as existsSync6, rmSync } from "node:fs";
39292
39358
  import { join as join6 } from "node:path";
39293
39359
  async function startDemoServer(story = "autonomy") {
39294
- const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : story === "coding" ? CODING_TOOLS : story === "support" ? SUPPORT_TOOLS : DEMO_TOOLS;
39360
+ const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : story === "coding" ? CODING_TOOLS : story === "support" ? SUPPORT_TOOLS : story === "legal" ? LEGAL_TOOLS : DEMO_TOOLS;
39295
39361
  const server = new Server({ name: story === "travel" ? "demo-travel" : story === "finance" ? "demo-finance" : "demo-grocer", version: "1.0.0" }, { capabilities: { tools: {} } });
39296
39362
  const cart = [];
39297
39363
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
@@ -39324,6 +39390,12 @@ async function startDemoServer(story = "autonomy") {
39324
39390
  return text2(`Sent "${a.report}" to ${a.recipient}.`);
39325
39391
  case "pay_invoice":
39326
39392
  return text2(`Paid $${a.amount} to ${a.vendor}.`);
39393
+ case "read_case_document":
39394
+ return text2(`${a.case_id}: ${a.document_type} read (expires 2031-04-30).`);
39395
+ case "update_profile_field":
39396
+ return text2(`${a.case_id}: ${a.field} set from source document.`);
39397
+ case "send_client_message":
39398
+ return text2(`Message sent on ${a.case_id}.`);
39327
39399
  case "lookup_customer":
39328
39400
  return text2(`${a.customer_id}: 3 orders; latest arrived damaged.`);
39329
39401
  case "issue_refund":
@@ -39349,6 +39421,47 @@ async function startDemoServer(story = "autonomy") {
39349
39421
  await server.connect(new StdioServerTransport());
39350
39422
  await closed;
39351
39423
  }
39424
+ async function governedSession(open2) {
39425
+ const start = async () => {
39426
+ try {
39427
+ const x = await open2();
39428
+ await x.listTools();
39429
+ return x;
39430
+ } catch {
39431
+ await new Promise((r) => setTimeout(r, 1500));
39432
+ const x = await open2();
39433
+ await x.listTools();
39434
+ return x;
39435
+ }
39436
+ };
39437
+ let s = await start();
39438
+ return {
39439
+ call: async (tool, args) => {
39440
+ try {
39441
+ return await s.callTool(tool, args);
39442
+ } catch (e) {
39443
+ try {
39444
+ await s.close();
39445
+ } catch {
39446
+ }
39447
+ try {
39448
+ s = await start();
39449
+ return await s.callTool(tool, args);
39450
+ } catch (e2) {
39451
+ process.stderr.write(`demo step ${tool} failed: ${String(e2.message ?? e2)} (first attempt: ${String(e.message ?? e)})
39452
+ `);
39453
+ return { kind: "error", message: String(e2.message ?? e2) };
39454
+ }
39455
+ }
39456
+ },
39457
+ close: async () => {
39458
+ try {
39459
+ await s.close();
39460
+ } catch {
39461
+ }
39462
+ }
39463
+ };
39464
+ }
39352
39465
  async function runStory(dir, st, owner, log) {
39353
39466
  const self = [...process.execArgv, process.argv[1]];
39354
39467
  const agentKey = loadOrCreateKey(join6(dir, `${st.id}-agent-key.json`));
@@ -39370,9 +39483,9 @@ async function runStory(dir, st, owner, log) {
39370
39483
  for (const line of describeMandate(m))
39371
39484
  log(` ${line}`);
39372
39485
  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] });
39373
- const s = await open2();
39486
+ const gs = await governedSession(open2);
39487
+ const call = gs.call;
39374
39488
  try {
39375
- await s.listTools();
39376
39489
  let lastRid = "";
39377
39490
  for (const step of st.steps) {
39378
39491
  if (step.approveLast) {
@@ -39381,7 +39494,11 @@ async function runStory(dir, st, owner, log) {
39381
39494
  log(` \u270D ${step.say}: ${lastRid}`);
39382
39495
  continue;
39383
39496
  }
39384
- const o = await s.callTool(step.tool, step.args);
39497
+ const o = await call(step.tool, step.args);
39498
+ if (o.kind === "error" && "message" in o) {
39499
+ log(` ! ${step.say}: could not complete on this machine (${o.message}); continuing`);
39500
+ continue;
39501
+ }
39385
39502
  const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
39386
39503
  const rid = /\[approval request (apr_[0-9a-f]+)\]/.exec(txt);
39387
39504
  if (rid)
@@ -39398,15 +39515,14 @@ async function runStory(dir, st, owner, log) {
39398
39515
  log(` ! ${f}`);
39399
39516
  }
39400
39517
  } finally {
39401
- await s.close();
39518
+ await gs.close();
39402
39519
  await new Promise((r) => setTimeout(r, 300));
39403
39520
  }
39404
39521
  if (st.id === "grocery") {
39405
39522
  revokeMandate(cm, "you pressed stop", revf);
39406
- const s2 = await open2();
39523
+ const s2 = await governedSession(open2);
39407
39524
  try {
39408
- await s2.listTools();
39409
- const o = await s2.callTool("search_products", { query: "milk" });
39525
+ const o = await s2.call("search_products", { query: "milk" });
39410
39526
  const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
39411
39527
  log(/revoked/.test(txt) ? " \u26D4 after you press stop (saktum agent revoke), it tries to search again: revoked" : ` ? after revoke: ${txt.slice(0, 80)}`);
39412
39528
  } finally {
@@ -39509,11 +39625,10 @@ async function runMarketplace(dir, log) {
39509
39625
  { tool: "search_products", args: { query: "fruit" }, say: "searches again" }
39510
39626
  ];
39511
39627
  const run = async (st2) => {
39512
- const s2 = await open2();
39628
+ const s2 = await governedSession(open2);
39513
39629
  try {
39514
- await s2.listTools();
39515
39630
  for (const st1 of st2) {
39516
- const o = await s2.callTool(st1.tool, st1.args);
39631
+ const o = await s2.call(st1.tool, st1.args);
39517
39632
  const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
39518
39633
  const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)\.( Ask| Tell|$)/.exec(txt);
39519
39634
  const last = parseReceiptLog(readFileSync8(rf, "utf8")).pop();
@@ -39559,7 +39674,7 @@ async function runDemo(dir, log, story = "all") {
39559
39674
  const owner = loadOrCreateKey(join6(dir, "owner-key.json"));
39560
39675
  log("Saktum demo: agents acting on real instructions (rules, preferences, substitutions, upsells), every decision explained and signed.\n");
39561
39676
  const files = [];
39562
- for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : story === "coding" ? [CODING] : story === "support" ? [SUPPORT] : [GROCERY, TRAVEL, FINANCE, CODING, SUPPORT])
39677
+ for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : story === "coding" ? [CODING] : story === "support" ? [SUPPORT] : story === "legal" ? [LEGAL] : [GROCERY, TRAVEL, FINANCE, CODING, SUPPORT, LEGAL])
39563
39678
  files.push(await runStory(dir, st, owner, log));
39564
39679
  if (story === "all")
39565
39680
  files.push(await runMarketplace(dir, log));
@@ -39604,17 +39719,21 @@ async function runAutonomyDemo(dir, log) {
39604
39719
  writeFileSync4(mf, JSON.stringify(m, null, 2));
39605
39720
  const tier = agentRiskTier(m);
39606
39721
  log(`\u2500\u2500 ${p.title} autonomy ${m.autonomy} \xB7 risk ${tier.tier}`);
39607
- 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"] });
39722
+ const open2 = () => 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"] });
39723
+ const gs = await governedSession(open2);
39608
39724
  try {
39609
- await s.listTools();
39610
39725
  for (const st of p.steps) {
39611
- const o = await s.callTool(st.tool, st.args);
39726
+ const o = await gs.call(st.tool, st.args);
39727
+ if (o.kind === "error" && "message" in o) {
39728
+ log(` ! ${st.say}: could not complete on this machine (${o.message}); continuing`);
39729
+ continue;
39730
+ }
39612
39731
  const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
39613
39732
  const blocked = /^Blocked by Saktum \(([^)]+)\): ([^.]+)/.exec(txt);
39614
39733
  log(blocked ? ` \u26D4 ${st.say}: blocked (${blocked[1]}): ${blocked[2]}` : ` \u2713 ${st.say}: ${txt.split("\n")[0]}`);
39615
39734
  }
39616
39735
  } finally {
39617
- await s.close();
39736
+ await gs.close();
39618
39737
  await new Promise((r) => setTimeout(r, 300));
39619
39738
  }
39620
39739
  const entries = parseReceiptLog(readFileSync8(rf, "utf8"));
@@ -39636,7 +39755,7 @@ async function runAutonomyDemo(dir, log) {
39636
39755
  log("What you just saw: the same agent and the same shop. Only the mandate changed what it was allowed to do, and every\ndecision, allowed or blocked, has a signed receipt. Open the passports to see each agent's permissions and path.");
39637
39756
  return { files };
39638
39757
  }
39639
- var PRODUCTS, DEMO_TOOLS, B, GROCERY_TOOLS, TRAVEL_TOOLS, FINANCE_TOOLS, CODING_TOOLS, SUPPORT_TOOLS, SCRIPT, EXTRA, GROCERY, TRAVEL, FINANCE, CODING, SUPPORT;
39758
+ var PRODUCTS, DEMO_TOOLS, B, GROCERY_TOOLS, TRAVEL_TOOLS, FINANCE_TOOLS, CODING_TOOLS, SUPPORT_TOOLS, LEGAL_TOOLS, SCRIPT, EXTRA, GROCERY, TRAVEL, FINANCE, CODING, SUPPORT, LEGAL;
39640
39759
  var init_demo = __esm({
39641
39760
  "packages/cli/dist/demo.js"() {
39642
39761
  "use strict";
@@ -39700,6 +39819,11 @@ var init_demo = __esm({
39700
39819
  { name: "lookup_customer", description: "Look up a customer's account and recent orders.", inputSchema: { type: "object", properties: { customer_id: { type: "string" } }, required: ["customer_id"] }, annotations: { readOnlyHint: true }, _meta: B({ customer_id: "support.customer_id" }, "search") },
39701
39820
  { name: "issue_refund", description: "Refund an amount to the customer's original payment method.", inputSchema: { type: "object", properties: { customer_id: { type: "string" }, amount: { type: "number" } }, required: ["customer_id", "amount"] }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }, _meta: B({ customer_id: "support.customer_id", amount: "support.amount" }, "pay") }
39702
39821
  ];
39822
+ LEGAL_TOOLS = [
39823
+ { name: "read_case_document", description: "Read a document from a case file.", inputSchema: { type: "object", properties: { case_id: { type: "string" }, document_type: { type: "string" } }, required: ["case_id", "document_type"] }, annotations: { readOnlyHint: true }, _meta: B({ case_id: "legal.case_id", document_type: "legal.document_type" }, "search") },
39824
+ { name: "update_profile_field", description: "Set a field in the case profile from a source document.", inputSchema: { type: "object", properties: { case_id: { type: "string" }, field: { type: "string" }, value: { type: "string" } }, required: ["case_id", "field", "value"] }, annotations: { readOnlyHint: false, destructiveHint: false }, _meta: B({ case_id: "legal.case_id" }, "change") },
39825
+ { name: "send_client_message", description: "Send a message to the client on a case.", inputSchema: { type: "object", properties: { case_id: { type: "string" }, body: { type: "string" }, citation: { type: "string" } }, required: ["case_id", "body"] }, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, _meta: B({ case_id: "legal.case_id", citation: "legal.citation" }, "communicate") }
39826
+ ];
39703
39827
  SCRIPT = [
39704
39828
  { tool: "get_deals", args: {}, say: "checks this week's deals" },
39705
39829
  { tool: "search_products", args: { query: "coffee" }, say: "searches for coffee" },
@@ -39805,6 +39929,22 @@ var init_demo = __esm({
39805
39929
  { tool: "", args: {}, say: "a support lead approves exactly that refund (saktum agent approve)", approveLast: true },
39806
39930
  { tool: "issue_refund", args: { customer_id: "C-1042", amount: 250 }, say: "retries the same refund" }
39807
39931
  ] };
39932
+ LEGAL = { id: "legal", title: 'Legal document agent: "prepare case 7731; every client message cites its source; a lawyer approves what leaves"', server: "legal", tools: LEGAL_TOOLS.map((t) => t.name), m: {
39933
+ autonomy: "act",
39934
+ purpose: "Prepare the Express Entry file for case C-7731",
39935
+ actions: [{ cls: "search", autonomy: "act" }, { cls: "change", autonomy: "act" }, { cls: "communicate", autonomy: "propose" }],
39936
+ rules: [{ field: "legal.case_id", op: "in", value: ["C-7731"], label: "only its assigned case" }, { field: "legal.citation", op: "present", actions: ["communicate"], label: "every client message cites its source" }],
39937
+ review: { sample: 1, actions: ["change"] },
39938
+ disclosures: { operator: "Maple Path Immigration Law", incentives: "None", dataUse: "Case C-7731 only; passport data to the IRCC package and the supervising lawyer" }
39939
+ }, steps: [
39940
+ { tool: "read_case_document", args: { case_id: "C-7731", document_type: "passport" }, say: "reads the passport on its case" },
39941
+ { tool: "read_case_document", args: { case_id: "C-9120", document_type: "passport" }, say: "tries to read a passport from another case" },
39942
+ { tool: "update_profile_field", args: { case_id: "C-7731", field: "passport_expiry", value: "2031-04-30" }, say: "fills the profile from the passport (sampled for lawyer review)" },
39943
+ { tool: "send_client_message", args: { case_id: "C-7731", body: "Your language test is still valid." }, say: "tries to message the client without citing a source" },
39944
+ { tool: "send_client_message", args: { case_id: "C-7731", body: "Your language test is valid for two years from the test date.", citation: "IRCC language test validity, rule pack ee-2026.11" }, say: "drafts the message with its citation" },
39945
+ { tool: "", args: {}, say: "the supervising lawyer approves exactly that message (saktum agent approve)", approveLast: true },
39946
+ { tool: "send_client_message", args: { case_id: "C-7731", body: "Your language test is valid for two years from the test date.", citation: "IRCC language test validity, rule pack ee-2026.11" }, say: "sends the approved message" }
39947
+ ] };
39808
39948
  }
39809
39949
  });
39810
39950
 
@@ -40804,6 +40944,14 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
40804
40944
  `);
40805
40945
  exitCode = logs.every((l) => l.verified) ? 0 : 1;
40806
40946
  });
40947
+ receipts.command("review").description("The human-review queue: allowed actions sampled for review under supervised autonomy").argument("<file>", "receipt log").action((f) => {
40948
+ const e = parseReceiptLog(readFileSync10(f, "utf8")).filter((x) => x.result.flags?.includes("review-sampled"));
40949
+ for (const x of e)
40950
+ process.stdout.write(`#${x.seq} ${x.receipt.issuedAt.slice(0, 16).replace("T", " ")} ${sanitizeText(x.receipt.envelope.tool, 40)} ${sanitizeText(String(x.receipt.reason ?? ""), 120)}
40951
+ `);
40952
+ process.stdout.write(`${e.length} action(s) sampled for review.
40953
+ `);
40954
+ });
40807
40955
  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) => {
40808
40956
  const { homedir: homedir2 } = await import("node:os");
40809
40957
  const { join: join7 } = await import("node:path");
@@ -40970,13 +41118,18 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
40970
41118
  `);
40971
41119
  });
40972
41120
  const identity = program2.command("identity").description("Identity chains: organisation -> people -> agents");
40973
- identity.command("issue").description("Issue a credential to a person or an agent, from your own credential").requiredOption("--from <credential>", "your credential (the organisation's, or one it issued to you)").requiredOption("--key <path>", "your signing key").requiredOption("--type <type>", "member or agent").requiredOption("--name <name>", "the subject's name").option("--subject-key <path>", "the subject's key file (its id is used)").option("--subject <did>", "the subject's did:key").option("--role <role>", "role, for a member").option("--expires <date>", "YYYY-MM-DD", new Date(Date.now() + 180 * 864e5).toISOString().slice(0, 10)).option("--out <file>", "credential file", "credential.json").option("--minutes <n>", "short-lived: expire this many minutes from now (overrides --expires)").option("--tools <list>", "comma-separated tools this credential covers (can only narrow down the chain)").option("--max-depth <n>", "how many credentials may follow this one in a chain (0 = no further delegation)").action((o) => {
41121
+ identity.command("issue").description("Issue a credential to a person or an agent, from your own credential").requiredOption("--from <credential>", "your credential (the organisation's, or one it issued to you)").requiredOption("--key <path>", "your signing key").requiredOption("--type <type>", "member or agent").requiredOption("--name <name>", "the subject's name").option("--subject-key <path>", "the subject's key file (its id is used)").option("--subject <did>", "the subject's did:key").option("--role <role>", "role, for a member").option("--expires <date>", "YYYY-MM-DD", new Date(Date.now() + 180 * 864e5).toISOString().slice(0, 10)).option("--out <file>", "credential file", "credential.json").option("--minutes <n>", "short-lived: expire this many minutes from now (overrides --expires)").option("--tools <list>", "comma-separated tools this credential covers (can only narrow down the chain)").option("--max-depth <n>", "how many credentials may follow this one in a chain (0 = no further delegation)").option("--where <field=values>", "resource scope, e.g. legal.case_id=C-7731 (repeatable; values comma-separated; can only narrow)", collect, []).action((o) => {
40974
41122
  if (o.minutes)
40975
41123
  o.expires = new Date(Date.now() + Number(o.minutes) * 6e4).toISOString();
40976
41124
  const subject = o.subject ?? (o.subjectKey ? loadOrCreateKey(o.subjectKey).kid : void 0);
40977
41125
  if (!subject)
40978
41126
  throw new Error("Give --subject <did:key> or --subject-key <file>.");
40979
- 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, ...o.tools ? { tools: o.tools.split(",").map((t) => t.trim()).filter(Boolean) } : {}, ...o.maxDepth !== void 0 ? { maxDepth: Number(o.maxDepth) } : {} });
41127
+ 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, ...o.tools ? { tools: o.tools.split(",").map((t) => t.trim()).filter(Boolean) } : {}, ...o.maxDepth !== void 0 ? { maxDepth: Number(o.maxDepth) } : {}, ...o.where?.length ? { where: Object.fromEntries(o.where.map((w) => {
41128
+ const i = w.indexOf("=");
41129
+ if (i < 1)
41130
+ throw new Error(`--where ${w}: use field=value1,value2`);
41131
+ return [w.slice(0, i), w.slice(i + 1).split(",").map((x) => x.trim()).filter(Boolean)];
41132
+ })) } : {} });
40980
41133
  writeFileSync5(o.out, JSON.stringify(c, null, 2) + "\n");
40981
41134
  process.stdout.write(`Issued ${c.id} to ${sanitizeText(o.name, 80)} (${o.type}). Chain: ${verifyChain(c).path.join(" -> ")}
40982
41135
  `);
@@ -41349,11 +41502,11 @@ ${published ? published === mine ? "\u2713 Matches the published release.\n" : "
41349
41502
  npm provenance: npm audit signatures
41350
41503
  `);
41351
41504
  });
41352
- 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, support, marketplace, autonomy, or all (grocery, travel, finance, coding, support and marketplace)", "all").action(async (o) => {
41505
+ 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, support, legal, marketplace, autonomy, or all (grocery, travel, finance, coding, support, legal and marketplace)", "all").action(async (o) => {
41353
41506
  const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
41354
41507
  await runDemo2(o.out, (l) => process.stdout.write(l + "\n"), o.story);
41355
41508
  });
41356
- program2.command("demo-server", { hidden: true }).description("The demo MCP servers (used by saktum demo)").option("--story <name>", "grocery, travel, finance, coding, support or autonomy", "autonomy").action(async (o) => {
41509
+ program2.command("demo-server", { hidden: true }).description("The demo MCP servers (used by saktum demo)").option("--story <name>", "grocery, travel, finance, coding, support, legal or autonomy", "autonomy").action(async (o) => {
41357
41510
  const { startDemoServer: startDemoServer2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
41358
41511
  await startDemoServer2(o.story);
41359
41512
  });