saktum 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +46 -1
  2. package/package.json +1 -1
  3. package/saktum.mjs +2396 -234
package/saktum.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Saktum Check 0.6.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
2
+ // Saktum Check 0.8.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;
@@ -3061,6 +3061,19 @@ function sanitizeText(text2, maxLength = 240) {
3061
3061
  function escapeHtml(text2) {
3062
3062
  return text2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
3063
3063
  }
3064
+ function maxDepth(value, limit = 64) {
3065
+ let deepest = 0;
3066
+ const walk = (v, d) => {
3067
+ if (d > limit)
3068
+ throw new Error(`value nested deeper than ${limit} levels`);
3069
+ deepest = Math.max(deepest, d);
3070
+ if (v && typeof v === "object")
3071
+ for (const x of Object.values(v))
3072
+ walk(x, d + 1);
3073
+ };
3074
+ walk(value, 0);
3075
+ return deepest;
3076
+ }
3064
3077
  var ANSI_CSI, ANSI_OSC, OTHER_ESC, C0_C1, INVISIBLE;
3065
3078
  var init_safe = __esm({
3066
3079
  "packages/testkit-core/dist/safe.js"() {
@@ -4376,10 +4389,10 @@ ${indent}`) + "'";
4376
4389
  literalFallback = true;
4377
4390
  };
4378
4391
  }
4379
- const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
4392
+ const body2 = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
4380
4393
  if (!literalFallback)
4381
4394
  return `>${header}
4382
- ${indent}${body}`;
4395
+ ${indent}${body2}`;
4383
4396
  }
4384
4397
  value = value.replace(/\n+/g, `$&${indent}`);
4385
4398
  return `|${header}
@@ -6395,13 +6408,13 @@ var require_stringifyDocument = __commonJS({
6395
6408
  contentComment = doc.contents.comment;
6396
6409
  }
6397
6410
  const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
6398
- let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
6411
+ let body2 = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
6399
6412
  if (contentComment)
6400
- body += stringifyComment.lineComment(body, "", commentString(contentComment));
6401
- if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
6402
- lines[lines.length - 1] = `--- ${body}`;
6413
+ body2 += stringifyComment.lineComment(body2, "", commentString(contentComment));
6414
+ if ((body2[0] === "|" || body2[0] === ">") && lines[lines.length - 1] === "---") {
6415
+ lines[lines.length - 1] = `--- ${body2}`;
6403
6416
  } else
6404
- lines.push(body);
6417
+ lines.push(body2);
6405
6418
  } else {
6406
6419
  lines.push(stringify.stringify(doc.contents, ctx));
6407
6420
  }
@@ -8394,13 +8407,13 @@ var require_cst_scalar = __commonJS({
8394
8407
  case ">": {
8395
8408
  const he = source.indexOf("\n");
8396
8409
  const head = source.substring(0, he);
8397
- const body = source.substring(he + 1) + "\n";
8410
+ const body2 = source.substring(he + 1) + "\n";
8398
8411
  const props = [
8399
8412
  { type: "block-scalar-header", offset, indent, source: head }
8400
8413
  ];
8401
8414
  if (!addEndtoBlockProps(props, end))
8402
8415
  props.push({ type: "newline", offset: -1, indent, source: "\n" });
8403
- return { type: "block-scalar", offset, indent, props, source: body };
8416
+ return { type: "block-scalar", offset, indent, props, source: body2 };
8404
8417
  }
8405
8418
  case '"':
8406
8419
  return { type: "double-quoted-scalar", offset, indent, source, end };
@@ -8457,13 +8470,13 @@ var require_cst_scalar = __commonJS({
8457
8470
  function setBlockScalarValue(token, source) {
8458
8471
  const he = source.indexOf("\n");
8459
8472
  const head = source.substring(0, he);
8460
- const body = source.substring(he + 1) + "\n";
8473
+ const body2 = source.substring(he + 1) + "\n";
8461
8474
  if (token.type === "block-scalar") {
8462
8475
  const header = token.props[0];
8463
8476
  if (header.type !== "block-scalar-header")
8464
8477
  throw new Error("Invalid block scalar header");
8465
8478
  header.source = head;
8466
- token.source = body;
8479
+ token.source = body2;
8467
8480
  } else {
8468
8481
  const { offset } = token;
8469
8482
  const indent = "indent" in token ? token.indent : -1;
@@ -8475,7 +8488,7 @@ var require_cst_scalar = __commonJS({
8475
8488
  for (const key of Object.keys(token))
8476
8489
  if (key !== "type" && key !== "offset")
8477
8490
  delete token[key];
8478
- Object.assign(token, { type: "block-scalar", indent, props, source: body });
8491
+ Object.assign(token, { type: "block-scalar", indent, props, source: body2 });
8479
8492
  }
8480
8493
  }
8481
8494
  function addEndtoBlockProps(props, end) {
@@ -10487,11 +10500,11 @@ function loadOrCreateKey(path = defaultKeyPath()) {
10487
10500
  return key;
10488
10501
  }
10489
10502
  function signDocument(doc, key) {
10490
- const { signature: _ignored, ...body } = doc;
10503
+ const { signature: _ignored, ...body2 } = doc;
10491
10504
  const header = b64u(Buffer.from(JSON.stringify({ alg: "EdDSA", kid: key.kid })));
10492
- const payload = b64u(Buffer.from(canonicalize(body)));
10505
+ const payload = b64u(Buffer.from(canonicalize(body2)));
10493
10506
  const sig = sign(null, Buffer.from(`${header}.${payload}`), key.privateKey);
10494
- return { ...body, signature: { alg: "EdDSA", kid: key.kid, jws: `${header}..${b64u(sig)}` } };
10507
+ return { ...body2, signature: { alg: "EdDSA", kid: key.kid, jws: `${header}..${b64u(sig)}` } };
10495
10508
  }
10496
10509
  function verifyDocument(doc) {
10497
10510
  const s = doc.signature;
@@ -10514,8 +10527,8 @@ function verifyDocument(doc) {
10514
10527
  } catch (e) {
10515
10528
  return { valid: false, reason: e.message };
10516
10529
  }
10517
- const { signature: _s, ...body } = doc;
10518
- const payload = b64u(Buffer.from(canonicalize(body)));
10530
+ const { signature: _s, ...body2 } = doc;
10531
+ const payload = b64u(Buffer.from(canonicalize(body2)));
10519
10532
  const ok = verify(null, Buffer.from(`${parts[0]}.${payload}`), publicKey, Buffer.from(parts[2], "base64url"));
10520
10533
  return ok ? { valid: true, kid: s.kid } : { valid: false, kid: s.kid, reason: "signature does not match content" };
10521
10534
  }
@@ -11419,10 +11432,10 @@ var require_codegen = __commonJS({
11419
11432
  return this._leafNode(new Throw(error2));
11420
11433
  }
11421
11434
  // start self-balancing block
11422
- block(body, nodeCount) {
11435
+ block(body2, nodeCount) {
11423
11436
  this._blockStarts.push(this._nodes.length);
11424
- if (body)
11425
- this.code(body).endBlock(nodeCount);
11437
+ if (body2)
11438
+ this.code(body2).endBlock(nodeCount);
11426
11439
  return this;
11427
11440
  }
11428
11441
  // end the current self-balancing block
@@ -12847,15 +12860,15 @@ var require_validate = __commonJS({
12847
12860
  validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
12848
12861
  }
12849
12862
  exports.validateFunctionCode = validateFunctionCode;
12850
- function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
12863
+ function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body2) {
12851
12864
  if (opts.code.es5) {
12852
12865
  gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
12853
12866
  gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
12854
12867
  destructureValCxtES5(gen, opts);
12855
- gen.code(body);
12868
+ gen.code(body2);
12856
12869
  });
12857
12870
  } else {
12858
- gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
12871
+ gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body2));
12859
12872
  }
12860
12873
  }
12861
12874
  function destructureValCxt(opts) {
@@ -19039,7 +19052,7 @@ var EMBEDDED_CONTRACTS, EMBEDDED_PACKS;
19039
19052
  var init_embedded = __esm({
19040
19053
  "packages/testkit-core/dist/embedded.js"() {
19041
19054
  "use strict";
19042
- EMBEDDED_CONTRACTS = { "envelope.schema.json": `{
19055
+ EMBEDDED_CONTRACTS = { "agreement.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/contracts/agreement.schema.json",\n "title": "agreement.schema.json",\n "type": "object",\n "required": [\n "agreementFormat",\n "id",\n "template",\n "purpose",\n "provider",\n "invoker",\n "scope",\n "rates",\n "terms",\n "validFrom",\n "validUntil",\n "signature"\n ],\n "properties": {\n "agreementFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string",\n "pattern": "^agr_"\n },\n "template": {\n "type": "string"\n },\n "purpose": {\n "type": "string",\n "maxLength": 500\n },\n "provider": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^did:key:"\n },\n "name": {\n "type": "string",\n "maxLength": 200\n },\n "domain": {\n "type": "string",\n "maxLength": 253\n },\n "role": {\n "type": "string",\n "maxLength": 100\n },\n "manifest": {\n "type": "string"\n }\n }\n },\n "invoker": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^did:key:"\n },\n "name": {\n "type": "string",\n "maxLength": 200\n },\n "domain": {\n "type": "string",\n "maxLength": 253\n },\n "role": {\n "type": "string",\n "maxLength": 100\n },\n "manifest": {\n "type": "string"\n }\n }\n },\n "scope": {\n "type": "object"\n },\n "rates": {\n "type": "object",\n "required": [\n "perCall"\n ],\n "properties": {\n "perCall": {\n "type": "number",\n "minimum": 0\n },\n "perTool": {\n "type": "object",\n "additionalProperties": {\n "type": "number",\n "minimum": 0\n }\n }\n }\n },\n "limits": {\n "type": "object"\n },\n "terms": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "specificTerms": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "dataTerms": {\n "type": "string"\n },\n "disputeContact": {\n "type": "string"\n },\n "validFrom": {\n "type": "string"\n },\n "validUntil": {\n "type": "string"\n },\n "signature": {\n "type": "object",\n "required": [\n "kid"\n ]\n },\n "countersignature": {\n "type": "object",\n "required": [\n "by",\n "agreement",\n "signature"\n ]\n }\n }\n}\n', "bounty.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/contracts/bounty.schema.json",\n "title": "bounty.schema.json",\n "type": "object",\n "required": [\n "bountyFormat",\n "id",\n "sponsor",\n "target",\n "intent",\n "scope",\n "prequalification",\n "success",\n "failure",\n "reward",\n "disclosure",\n "status"\n ],\n "properties": {\n "bountyFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string"\n },\n "sponsor": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^did:key:"\n },\n "name": {\n "type": "string",\n "maxLength": 200\n },\n "domain": {\n "type": "string",\n "maxLength": 253\n },\n "role": {\n "type": "string",\n "maxLength": 100\n },\n "manifest": {\n "type": "string"\n }\n }\n },\n "target": {\n "type": "object",\n "description": "the manifest or server under test"\n },\n "intent": {\n "type": "string",\n "maxLength": 500\n },\n "scope": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "prequalification": {\n "type": "array",\n "items": {\n "type": "string"\n },\n "description": "who may take part (for example verified identity, prior findings)"\n },\n "success": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "failure": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "reward": {\n "type": "object",\n "required": [\n "tokens"\n ],\n "properties": {\n "tokens": {\n "type": "number",\n "minimum": 0\n }\n }\n },\n "disclosure": {\n "type": "string",\n "description": "responsible-disclosure and safe-harbour terms"\n },\n "status": {\n "enum": [\n "draft",\n "open",\n "in-review",\n "paid",\n "closed"\n ]\n },\n "signature": {\n "type": "object",\n "required": [\n "kid"\n ]\n }\n }\n}\n', "credential.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/contracts/credential.schema.json",\n "title": "credential.schema.json",\n "type": "object",\n "required": [\n "credentialFormat",\n "id",\n "type",\n "subject",\n "issuer",\n "issuedAt",\n "expires",\n "signature"\n ],\n "properties": {\n "credentialFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string",\n "pattern": "^cred_"\n },\n "type": {\n "enum": [\n "organisation",\n "member",\n "agent"\n ]\n },\n "subject": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^did:key:"\n },\n "name": {\n "type": "string",\n "maxLength": 200\n },\n "domain": {\n "type": "string",\n "maxLength": 253\n },\n "role": {\n "type": "string",\n "maxLength": 100\n },\n "manifest": {\n "type": "string"\n }\n }\n },\n "issuer": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^did:key:"\n },\n "name": {\n "type": "string",\n "maxLength": 200\n },\n "domain": {\n "type": "string",\n "maxLength": 253\n },\n "role": {\n "type": "string",\n "maxLength": 100\n },\n "manifest": {\n "type": "string"\n }\n }\n },\n "chain": {\n "type": "array",\n "items": {\n "type": "object"\n }\n },\n "issuedAt": {\n "type": "string"\n },\n "expires": {\n "type": "string"\n },\n "signature": {\n "type": "object",\n "required": [\n "kid"\n ]\n }\n }\n}\n', "envelope.schema.json": `{
19043
19056
  "$schema": "https://json-schema.org/draft/2020-12/schema",
19044
19057
  "$id": "https://saktum.dev/schemas/envelope/0.1.json",
19045
19058
  "title": "Saktum canonical call envelope",
@@ -19186,42 +19199,514 @@ var init_embedded = __esm({
19186
19199
  "description": "An agent's identity and what its human owner allows it to do, signed by the owner.",
19187
19200
  "type": "object",
19188
19201
  "additionalProperties": false,
19189
- "required": ["mandateFormat", "agent", "owner", "allow", "issuedAt", "expires", "signature"],
19202
+ "required": [
19203
+ "mandateFormat",
19204
+ "agent",
19205
+ "owner",
19206
+ "allow",
19207
+ "issuedAt",
19208
+ "expires",
19209
+ "signature"
19210
+ ],
19190
19211
  "properties": {
19191
- "mandateFormat": { "const": "0.1" },
19192
- "agent": { "type": "object", "additionalProperties": false, "required": ["id", "name"], "properties": { "id": { "type": "string", "pattern": "^did:key:" }, "name": { "type": "string", "maxLength": 120 } } },
19193
- "owner": { "type": "object", "additionalProperties": false, "required": ["id"], "properties": { "id": { "type": "string", "pattern": "^did:key:" }, "name": { "type": "string", "maxLength": 120 } } },
19194
- "purpose": { "type": "string", "maxLength": 300 },
19195
- "allow": { "type": "object", "additionalProperties": false, "required": ["destructive"], "properties": {
19196
- "servers": { "type": "array", "items": { "type": "string", "maxLength": 200 } },
19197
- "tools": { "type": "array", "items": { "type": "string", "maxLength": 200 } },
19198
- "destructive": { "type": "boolean" } } },
19199
- "issuedAt": { "type": "string", "format": "date-time" },
19200
- "expires": { "type": "string", "format": "date" },
19201
- "signature": { "type": "object", "required": ["alg", "kid", "jws"], "properties": { "alg": { "const": "EdDSA" }, "kid": { "type": "string" }, "jws": { "type": "string" } } }
19202
- }
19203
- }
19204
- `, "pack.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/pack/0.1.json",\n "title": "Saktum Trust Check test pack",\n "description": "A versioned set of checks. Packs are data, never code: steps use a closed set of actions, and any logic lives in named, engine-versioned analysers.",\n "type": "object",\n "required": [\n "packFormat",\n "id",\n "version",\n "category",\n "checks"\n ],\n "additionalProperties": false,\n "properties": {\n "packFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string",\n "pattern": "^[a-z][a-z0-9-]*$"\n },\n "version": {\n "type": "string",\n "pattern": "^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$"\n },\n "category": {\n "enum": [\n "conformance",\n "auth",\n "security",\n "agent-experience",\n "performance",\n "functional"\n ]\n },\n "description": {\n "type": "string"\n },\n "checks": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/check"\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n },\n "description": "Detached JWS over the canonical pack without this member. Required for packs from the feed (v0.2)."\n }\n },\n "$defs": {\n "check": {\n "type": "object",\n "required": [\n "id",\n "title",\n "severity",\n "safety",\n "steps",\n "fix"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^[a-z]+(\\\\.[a-z0-9-]+)+$"\n },\n "title": {\n "type": "string"\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "safety": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "scored": {\n "type": "boolean",\n "default": true\n },\n "appliesTo": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "transports": {\n "type": "array",\n "items": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n }\n },\n "protocol": {\n "type": "string",\n "description": "Minimum protocol revision, e.g. >=2025-03-26"\n }\n }\n },\n "steps": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/step"\n }\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "normative": {\n "type": "array",\n "description": "Baseline 4.1: the normative statements this check verifies, for the public traceability matrix.",\n "items": {\n "type": "object",\n "required": [\n "source",\n "level"\n ],\n "additionalProperties": false,\n "properties": {\n "source": {\n "type": "string",\n "description": "e.g. MCP specification, RFC 9728, OWASP MCP Top 10"\n },\n "version": {\n "type": "string",\n "description": "specification revision or date"\n },\n "clause": {\n "type": "string",\n "description": "section or requirement identifier"\n },\n "level": {\n "enum": [\n "MUST",\n "SHOULD",\n "MAY",\n "best-practice"\n ]\n }\n }\n }\n }\n }\n },\n "step": {\n "type": "object",\n "required": [\n "action"\n ],\n "additionalProperties": false,\n "properties": {\n "action": {\n "enum": [\n "mcp.initialize",\n "mcp.listTools",\n "mcp.callTool",\n "analyse"\n ]\n },\n "tool": {\n "type": "string"\n },\n "arguments": {\n "type": "object"\n },\n "analyser": {\n "type": "string"\n },\n "expect": {\n "$ref": "#/$defs/expectation"\n }\n }\n },\n "expectation": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "exists": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "isError": {\n "type": "boolean"\n },\n "errorCodeIn": {\n "type": "array",\n "items": {\n "type": "integer"\n }\n },\n "failed": {\n "type": "boolean",\n "description": "The call must not succeed: either a protocol error or a tool result flagged as an error."\n },\n "anyOf": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/expectation"\n }\n }\n }\n }\n }\n}\n', "policy.schema.json": `{
19212
+ "mandateFormat": {
19213
+ "const": "0.1"
19214
+ },
19215
+ "agent": {
19216
+ "type": "object",
19217
+ "additionalProperties": false,
19218
+ "required": [
19219
+ "id",
19220
+ "name"
19221
+ ],
19222
+ "properties": {
19223
+ "id": {
19224
+ "type": "string",
19225
+ "pattern": "^did:key:"
19226
+ },
19227
+ "name": {
19228
+ "type": "string",
19229
+ "maxLength": 120
19230
+ },
19231
+ "software": {
19232
+ "type": "string",
19233
+ "maxLength": 200
19234
+ }
19235
+ }
19236
+ },
19237
+ "owner": {
19238
+ "type": "object",
19239
+ "additionalProperties": false,
19240
+ "required": [
19241
+ "id"
19242
+ ],
19243
+ "properties": {
19244
+ "id": {
19245
+ "type": "string",
19246
+ "pattern": "^did:key:"
19247
+ },
19248
+ "name": {
19249
+ "type": "string",
19250
+ "maxLength": 120
19251
+ }
19252
+ }
19253
+ },
19254
+ "purpose": {
19255
+ "type": "string",
19256
+ "maxLength": 300
19257
+ },
19258
+ "allow": {
19259
+ "type": "object",
19260
+ "additionalProperties": false,
19261
+ "required": [
19262
+ "destructive"
19263
+ ],
19264
+ "properties": {
19265
+ "servers": {
19266
+ "type": "array",
19267
+ "items": {
19268
+ "type": "string",
19269
+ "maxLength": 200
19270
+ }
19271
+ },
19272
+ "tools": {
19273
+ "type": "array",
19274
+ "items": {
19275
+ "type": "string",
19276
+ "maxLength": 200
19277
+ }
19278
+ },
19279
+ "destructive": {
19280
+ "type": "boolean"
19281
+ }
19282
+ }
19283
+ },
19284
+ "issuedAt": {
19285
+ "type": "string",
19286
+ "format": "date-time"
19287
+ },
19288
+ "expires": {
19289
+ "type": "string",
19290
+ "format": "date"
19291
+ },
19292
+ "signature": {
19293
+ "type": "object",
19294
+ "required": [
19295
+ "alg",
19296
+ "kid",
19297
+ "jws"
19298
+ ],
19299
+ "properties": {
19300
+ "alg": {
19301
+ "const": "EdDSA"
19302
+ },
19303
+ "kid": {
19304
+ "type": "string"
19305
+ },
19306
+ "jws": {
19307
+ "type": "string"
19308
+ }
19309
+ }
19310
+ },
19311
+ "autonomy": {
19312
+ "enum": [
19313
+ "notify",
19314
+ "propose",
19315
+ "act"
19316
+ ],
19317
+ "description": "notify: only alert the user; propose: suggest, the user approves; act: act within the limits"
19318
+ },
19319
+ "constraints": {
19320
+ "type": "array",
19321
+ "items": {
19322
+ "type": "object",
19323
+ "additionalProperties": false,
19324
+ "required": [
19325
+ "tool",
19326
+ "arg"
19327
+ ],
19328
+ "properties": {
19329
+ "tool": {
19330
+ "type": "string",
19331
+ "maxLength": 200
19332
+ },
19333
+ "arg": {
19334
+ "type": "string",
19335
+ "maxLength": 100
19336
+ },
19337
+ "max": {
19338
+ "type": "number"
19339
+ },
19340
+ "oneOf": {
19341
+ "type": "array",
19342
+ "items": {
19343
+ "type": [
19344
+ "string",
19345
+ "number"
19346
+ ]
19347
+ }
19348
+ }
19349
+ }
19350
+ }
19351
+ },
19352
+ "limits": {
19353
+ "type": "object",
19354
+ "additionalProperties": false,
19355
+ "properties": {
19356
+ "callsPerDay": {
19357
+ "type": "integer",
19358
+ "minimum": 0
19359
+ },
19360
+ "totalPerDay": {
19361
+ "type": "object",
19362
+ "additionalProperties": false,
19363
+ "required": [
19364
+ "arg",
19365
+ "max"
19366
+ ],
19367
+ "properties": {
19368
+ "arg": {
19369
+ "type": "string",
19370
+ "maxLength": 100
19371
+ },
19372
+ "max": {
19373
+ "type": "number"
19374
+ }
19375
+ }
19376
+ }
19377
+ }
19378
+ },
19379
+ "approveAbove": {
19380
+ "type": "object",
19381
+ "additionalProperties": false,
19382
+ "required": [
19383
+ "arg",
19384
+ "value"
19385
+ ],
19386
+ "properties": {
19387
+ "arg": {
19388
+ "type": "string",
19389
+ "maxLength": 100
19390
+ },
19391
+ "value": {
19392
+ "type": "number"
19393
+ }
19394
+ }
19395
+ },
19396
+ "disclosures": {
19397
+ "type": "object",
19398
+ "additionalProperties": false,
19399
+ "properties": {
19400
+ "operator": {
19401
+ "type": "string",
19402
+ "maxLength": 200
19403
+ },
19404
+ "incentives": {
19405
+ "type": "string",
19406
+ "maxLength": 300
19407
+ },
19408
+ "dataUse": {
19409
+ "type": "string",
19410
+ "maxLength": 300
19411
+ }
19412
+ }
19413
+ },
19414
+ "delegation": {
19415
+ "type": "boolean",
19416
+ "description": "May the agent hand work to other agents (default false)"
19417
+ },
19418
+ "actions": {
19419
+ "type": "array",
19420
+ "items": {
19421
+ "type": "object",
19422
+ "additionalProperties": false,
19423
+ "required": [
19424
+ "cls",
19425
+ "autonomy"
19426
+ ],
19427
+ "properties": {
19428
+ "cls": {
19429
+ "enum": [
19430
+ "search",
19431
+ "cart",
19432
+ "substitute",
19433
+ "pay",
19434
+ "book",
19435
+ "change",
19436
+ "cancel",
19437
+ "communicate",
19438
+ "other"
19439
+ ]
19440
+ },
19441
+ "autonomy": {
19442
+ "enum": [
19443
+ "notify",
19444
+ "propose",
19445
+ "act"
19446
+ ]
19447
+ }
19448
+ }
19449
+ }
19450
+ },
19451
+ "rules": {
19452
+ "type": "array",
19453
+ "items": {
19454
+ "type": "object",
19455
+ "additionalProperties": false,
19456
+ "required": [
19457
+ "field",
19458
+ "op",
19459
+ "value"
19460
+ ],
19461
+ "properties": {
19462
+ "field": {
19463
+ "type": "string",
19464
+ "pattern": "^[a-z]+(\\\\.[a-z_]+)+$"
19465
+ },
19466
+ "op": {
19467
+ "enum": [
19468
+ "max",
19469
+ "min",
19470
+ "eq",
19471
+ "in",
19472
+ "notIn"
19473
+ ]
19474
+ },
19475
+ "value": {},
19476
+ "label": {
19477
+ "type": "string",
19478
+ "maxLength": 200
19479
+ }
19480
+ }
19481
+ }
19482
+ },
19483
+ "preferences": {
19484
+ "type": "array",
19485
+ "items": {
19486
+ "type": "object",
19487
+ "additionalProperties": false,
19488
+ "required": [
19489
+ "field",
19490
+ "prefer"
19491
+ ],
19492
+ "properties": {
19493
+ "field": {
19494
+ "type": "string",
19495
+ "pattern": "^[a-z]+(\\\\.[a-z_]+)+$"
19496
+ },
19497
+ "prefer": {
19498
+ "type": [
19499
+ "string",
19500
+ "number",
19501
+ "boolean"
19502
+ ]
19503
+ },
19504
+ "label": {
19505
+ "type": "string",
19506
+ "maxLength": 200
19507
+ }
19508
+ }
19509
+ }
19510
+ },
19511
+ "substitution": {
19512
+ "type": "object",
19513
+ "additionalProperties": false,
19514
+ "required": [
19515
+ "allowed"
19516
+ ],
19517
+ "properties": {
19518
+ "allowed": {
19519
+ "type": "boolean"
19520
+ },
19521
+ "maxPriceChangePct": {
19522
+ "type": "number",
19523
+ "minimum": 0
19524
+ },
19525
+ "neverFor": {
19526
+ "type": "array",
19527
+ "items": {
19528
+ "type": "string",
19529
+ "maxLength": 100
19530
+ }
19531
+ }
19532
+ }
19533
+ },
19534
+ "upsell": {
19535
+ "enum": [
19536
+ "never",
19537
+ "ask",
19538
+ "allowed"
19539
+ ]
19540
+ },
19541
+ "approvalTriggers": {
19542
+ "type": "array",
19543
+ "items": {
19544
+ "enum": [
19545
+ "substitution",
19546
+ "fee",
19547
+ "upsell",
19548
+ "sponsored",
19549
+ "new-counterparty"
19550
+ ]
19551
+ }
19552
+ },
19553
+ "counterparties": {
19554
+ "type": "array",
19555
+ "items": {
19556
+ "type": "string",
19557
+ "maxLength": 200
19558
+ }
19559
+ },
19560
+ "dataSharing": {
19561
+ "type": "array",
19562
+ "items": {
19563
+ "type": "object",
19564
+ "additionalProperties": false,
19565
+ "required": [
19566
+ "data",
19567
+ "to"
19568
+ ],
19569
+ "properties": {
19570
+ "data": {
19571
+ "type": "string",
19572
+ "maxLength": 100
19573
+ },
19574
+ "to": {
19575
+ "type": "string",
19576
+ "maxLength": 200
19577
+ }
19578
+ }
19579
+ }
19580
+ },
19581
+ "operatorCountersign": {
19582
+ "type": "object",
19583
+ "description": "The operator's signed statement over the mandate digest (role, name, mandate, at, signature)"
19584
+ }
19585
+ }
19586
+ }
19587
+ `, "manifest.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/contracts/manifest.schema.json",\n "title": "manifest.schema.json",\n "type": "object",\n "required": [\n "manifestFormat",\n "id",\n "publisher",\n "server",\n "categories",\n "intents",\n "capabilities",\n "rates",\n "issuedAt",\n "signature"\n ],\n "properties": {\n "manifestFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string",\n "pattern": "^man_"\n },\n "publisher": {\n "type": "object",\n "required": [\n "id",\n "name"\n ],\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^did:key:"\n },\n "name": {\n "type": "string",\n "maxLength": 200\n },\n "domain": {\n "type": "string",\n "maxLength": 253\n },\n "role": {\n "type": "string",\n "maxLength": 100\n },\n "manifest": {\n "type": "string"\n }\n }\n },\n "server": {\n "type": "object",\n "required": [\n "name",\n "version"\n ]\n },\n "categories": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "intents": {\n "type": "array",\n "items": {\n "type": "string",\n "pattern": "^[a-z]+:[a-z]+$"\n }\n },\n "capabilities": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "tool",\n "action",\n "fields"\n ]\n }\n },\n "rates": {\n "type": "object",\n "required": [\n "perCall"\n ],\n "properties": {\n "perCall": {\n "type": "number",\n "minimum": 0\n },\n "perTool": {\n "type": "object",\n "additionalProperties": {\n "type": "number",\n "minimum": 0\n }\n }\n }\n },\n "quality": {\n "type": "object"\n },\n "documentation": {\n "type": "string"\n },\n "bounties": {\n "type": "array"\n },\n "issuedAt": {\n "type": "string"\n },\n "signature": {\n "type": "object",\n "required": [\n "kid"\n ]\n }\n }\n}\n', "pack.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/pack/0.1.json",\n "title": "Saktum Trust Check test pack",\n "description": "A versioned set of checks. Packs are data, never code: steps use a closed set of actions, and any logic lives in named, engine-versioned analysers.",\n "type": "object",\n "required": [\n "packFormat",\n "id",\n "version",\n "category",\n "checks"\n ],\n "additionalProperties": false,\n "properties": {\n "packFormat": {\n "const": "0.1"\n },\n "id": {\n "type": "string",\n "pattern": "^[a-z][a-z0-9-]*$"\n },\n "version": {\n "type": "string",\n "pattern": "^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$"\n },\n "category": {\n "enum": [\n "conformance",\n "auth",\n "security",\n "agent-experience",\n "performance",\n "functional"\n ]\n },\n "description": {\n "type": "string"\n },\n "checks": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/check"\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n },\n "description": "Detached JWS over the canonical pack without this member. Required for packs from the feed (v0.2)."\n }\n },\n "$defs": {\n "check": {\n "type": "object",\n "required": [\n "id",\n "title",\n "severity",\n "safety",\n "steps",\n "fix"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string",\n "pattern": "^[a-z]+(\\\\.[a-z0-9-]+)+$"\n },\n "title": {\n "type": "string"\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "safety": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "scored": {\n "type": "boolean",\n "default": true\n },\n "appliesTo": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "transports": {\n "type": "array",\n "items": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n }\n },\n "protocol": {\n "type": "string",\n "description": "Minimum protocol revision, e.g. >=2025-03-26"\n }\n }\n },\n "steps": {\n "type": "array",\n "minItems": 1,\n "items": {\n "$ref": "#/$defs/step"\n }\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "normative": {\n "type": "array",\n "description": "Baseline 4.1: the normative statements this check verifies, for the public traceability matrix.",\n "items": {\n "type": "object",\n "required": [\n "source",\n "level"\n ],\n "additionalProperties": false,\n "properties": {\n "source": {\n "type": "string",\n "description": "e.g. MCP specification, RFC 9728, OWASP MCP Top 10"\n },\n "version": {\n "type": "string",\n "description": "specification revision or date"\n },\n "clause": {\n "type": "string",\n "description": "section or requirement identifier"\n },\n "level": {\n "enum": [\n "MUST",\n "SHOULD",\n "MAY",\n "best-practice"\n ]\n }\n }\n }\n }\n }\n },\n "step": {\n "type": "object",\n "required": [\n "action"\n ],\n "additionalProperties": false,\n "properties": {\n "action": {\n "enum": [\n "mcp.initialize",\n "mcp.listTools",\n "mcp.callTool",\n "analyse"\n ]\n },\n "tool": {\n "type": "string"\n },\n "arguments": {\n "type": "object"\n },\n "analyser": {\n "type": "string"\n },\n "expect": {\n "$ref": "#/$defs/expectation"\n }\n }\n },\n "expectation": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "exists": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "isError": {\n "type": "boolean"\n },\n "errorCodeIn": {\n "type": "array",\n "items": {\n "type": "integer"\n }\n },\n "failed": {\n "type": "boolean",\n "description": "The call must not succeed: either a protocol error or a tool result flagged as an error."\n },\n "anyOf": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/expectation"\n }\n }\n }\n }\n }\n}\n', "policy.schema.json": `{
19205
19588
  "$schema": "https://json-schema.org/draft/2020-12/schema",
19206
19589
  "$id": "https://saktum.dev/contracts/policy.schema.json",
19207
19590
  "title": "Saktum policy",
19208
19591
  "description": "An organisation's own rules for which MCP servers its people and agents may use.",
19209
19592
  "type": "object",
19210
19593
  "additionalProperties": false,
19211
- "required": ["policyFormat"],
19594
+ "required": [
19595
+ "policyFormat"
19596
+ ],
19212
19597
  "properties": {
19213
- "policyFormat": { "const": "0.1" },
19214
- "name": { "type": "string", "maxLength": 120 },
19215
- "minTrust": { "enum": ["A", "B", "C", "D", "F"] },
19216
- "minReadiness": { "enum": ["A", "B", "C", "D", "F"] },
19217
- "forbidCapabilities": { "type": "array", "items": { "enum": ["reads-private-data", "untrusted-content", "network", "code-execution", "filesystem", "writes-or-deletes", "sends-messages", "money"] }, "uniqueItems": true },
19218
- "forbidLethalTrifecta": { "type": "boolean" },
19219
- "maxContextTokens": { "type": "integer", "minimum": 0 },
19220
- "noFailedSeverity": { "enum": ["critical", "high", "medium", "low"], "description": "Any failed check at or above this severity violates the policy" },
19221
- "requireAllowlist": { "type": "boolean", "description": "Every server must match an entry (by tool fingerprint) in the allowlist file" },
19222
- "allowlist": { "type": "string", "maxLength": 500, "description": "Path of a saktum allowlist file" },
19223
- "exceptions": { "type": "array", "items": { "type": "object", "additionalProperties": false, "required": ["server", "reason"],
19224
- "properties": { "server": { "type": "string", "maxLength": 200 }, "rules": { "type": "array", "items": { "type": "string" } }, "reason": { "type": "string", "minLength": 3, "maxLength": 300 }, "approvedBy": { "type": "string", "maxLength": 120 }, "until": { "type": "string", "format": "date" } } } }
19598
+ "policyFormat": {
19599
+ "const": "0.1"
19600
+ },
19601
+ "name": {
19602
+ "type": "string",
19603
+ "maxLength": 120
19604
+ },
19605
+ "minTrust": {
19606
+ "enum": [
19607
+ "A",
19608
+ "B",
19609
+ "C",
19610
+ "D",
19611
+ "F"
19612
+ ]
19613
+ },
19614
+ "minReadiness": {
19615
+ "enum": [
19616
+ "A",
19617
+ "B",
19618
+ "C",
19619
+ "D",
19620
+ "F"
19621
+ ]
19622
+ },
19623
+ "forbidCapabilities": {
19624
+ "type": "array",
19625
+ "items": {
19626
+ "enum": [
19627
+ "reads-private-data",
19628
+ "untrusted-content",
19629
+ "network",
19630
+ "code-execution",
19631
+ "filesystem",
19632
+ "writes-or-deletes",
19633
+ "sends-messages",
19634
+ "money"
19635
+ ]
19636
+ },
19637
+ "uniqueItems": true
19638
+ },
19639
+ "forbidLethalTrifecta": {
19640
+ "type": "boolean"
19641
+ },
19642
+ "maxContextTokens": {
19643
+ "type": "integer",
19644
+ "minimum": 0
19645
+ },
19646
+ "noFailedSeverity": {
19647
+ "enum": [
19648
+ "critical",
19649
+ "high",
19650
+ "medium",
19651
+ "low"
19652
+ ],
19653
+ "description": "Any failed check at or above this severity violates the policy"
19654
+ },
19655
+ "requireAllowlist": {
19656
+ "type": "boolean",
19657
+ "description": "Every server must match an entry (by tool fingerprint) in the allowlist file"
19658
+ },
19659
+ "allowlist": {
19660
+ "type": "string",
19661
+ "maxLength": 500,
19662
+ "description": "Path of a saktum allowlist file"
19663
+ },
19664
+ "exceptions": {
19665
+ "type": "array",
19666
+ "items": {
19667
+ "type": "object",
19668
+ "additionalProperties": false,
19669
+ "required": [
19670
+ "server",
19671
+ "reason"
19672
+ ],
19673
+ "properties": {
19674
+ "server": {
19675
+ "type": "string",
19676
+ "maxLength": 200
19677
+ },
19678
+ "rules": {
19679
+ "type": "array",
19680
+ "items": {
19681
+ "type": "string"
19682
+ }
19683
+ },
19684
+ "reason": {
19685
+ "type": "string",
19686
+ "minLength": 3,
19687
+ "maxLength": 300
19688
+ },
19689
+ "approvedBy": {
19690
+ "type": "string",
19691
+ "maxLength": 120
19692
+ },
19693
+ "until": {
19694
+ "type": "string",
19695
+ "format": "date"
19696
+ }
19697
+ }
19698
+ }
19699
+ },
19700
+ "maxRiskTier": {
19701
+ "enum": [
19702
+ "R0",
19703
+ "R1",
19704
+ "R2",
19705
+ "R3",
19706
+ "R4"
19707
+ ],
19708
+ "description": "Servers above this risk tier violate the policy unless excepted"
19709
+ }
19225
19710
  }
19226
19711
  }
19227
19712
  `, "receipt.schema.json": `{
@@ -19296,8 +19781,8 @@ var init_embedded = __esm({
19296
19781
  }
19297
19782
  }
19298
19783
  }
19299
- `, "result.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/result/0.1.json",\n "title": "Saktum Trust Check result",\n "description": "The canonical result of one run. Every report format is rendered from this model. Evidence is a hash plus a short, sanitised excerpt; raw payloads never appear.",\n "type": "object",\n "required": [\n "resultFormat",\n "tool",\n "target",\n "packs",\n "findings",\n "scores",\n "metrics",\n "run"\n ],\n "additionalProperties": false,\n "properties": {\n "resultFormat": {\n "const": "0.1"\n },\n "tool": {\n "type": "object",\n "required": [\n "name",\n "version"\n ],\n "additionalProperties": false,\n "properties": {\n "name": {\n "const": "saktum-trust-check"\n },\n "version": {\n "type": "string"\n }\n }\n },\n "target": {\n "type": "object",\n "required": [\n "transport",\n "description"\n ],\n "additionalProperties": false,\n "properties": {\n "transport": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n },\n "description": {\n "type": "string"\n },\n "protocolVersion": {\n "type": "string"\n },\n "serverInfo": {\n "type": "object"\n },\n "toolsFingerprint": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "packs": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "version",\n "hash"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "hash": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n }\n }\n }\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/finding"\n }\n },\n "scores": {\n "type": "object",\n "required": [\n "overall",\n "capped",\n "categories"\n ],\n "additionalProperties": false,\n "properties": {\n "overall": {\n "type": [\n "integer",\n "null"\n ],\n "minimum": 0,\n "maximum": 100\n },\n "capped": {\n "type": "boolean"\n },\n "categories": {\n "type": "object",\n "additionalProperties": {\n "type": [\n "integer",\n "null"\n ]\n }\n }\n }\n },\n "metrics": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "contextCostTokens": {\n "type": "integer",\n "minimum": 0\n },\n "largestTools": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "tool",\n "tokens"\n ],\n "properties": {\n "tool": {\n "type": "string"\n },\n "tokens": {\n "type": "integer"\n }\n }\n }\n },\n "contextCostPer1kTurnsUsd": {\n "type": "number",\n "minimum": 0,\n "description": "Estimated cost of loading the tool definitions on 1,000 agent turns at pricePerMTokUsd. Reported only."\n },\n "pricePerMTokUsd": {\n "type": "number",\n "minimum": 0\n },\n "performance": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "initMs": {\n "type": "integer",\n "minimum": 0\n },\n "listMs": {\n "type": "integer",\n "minimum": 0\n },\n "listBytes": {\n "type": "integer",\n "minimum": 0\n },\n "rssMb": {\n "type": "number",\n "minimum": 0\n },\n "cpuPct": {\n "type": "number",\n "minimum": 0\n },\n "burst": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "requests": {\n "type": "integer"\n },\n "ok": {\n "type": "integer"\n },\n "rateLimited": {\n "type": "integer"\n },\n "errors": {\n "type": "integer"\n },\n "p95Ms": {\n "type": "integer"\n }\n }\n }\n }\n }\n }\n },\n "run": {\n "type": "object",\n "required": [\n "startedAt",\n "durationMs",\n "mode",\n "runner",\n "sandbox"\n ],\n "additionalProperties": false,\n "properties": {\n "startedAt": {\n "type": "string",\n "format": "date-time"\n },\n "durationMs": {\n "type": "integer",\n "minimum": 0\n },\n "mode": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "runner": {\n "enum": [\n "self",\n "hosted"\n ],\n "description": "self: run and signed by the user, proves integrity not independence. hosted: run and signed by Saktum (later)."\n },\n "sandbox": {\n "enum": [\n "none",\n "docker"\n ],\n "description": "Whether local servers ran inside a container sandbox."\n }\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n }\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ],\n "description": "Letter grade from the trust score: A 90-100, B 80-89, C 70-79, D 50-69, F below 50 or any failed critical check."\n },\n "summary": {\n "type": "array",\n "maxItems": 5,\n "items": {\n "type": "string",\n "maxLength": 400\n },\n "description": "Plain-language summary sentences shown first in every report."\n },\n "assuranceLevel": {\n "enum": [\n "L1",\n "L2",\n "L3",\n "L4"\n ],\n "description": "L1 self-tested (Saktum Check); L2 independently tested; L3 certified; L4 continuously certified."\n },\n "readiness": {\n "description": "Agent readiness: a second grade beside trust (annotations, descriptions, context cost), never mixed into the trust score.",\n "oneOf": [\n {\n "type": "null"\n },\n {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "score",\n "grade",\n "toolsAnnotated",\n "toolsDescribed",\n "toolCount",\n "contextTokens"\n ],\n "properties": {\n "score": {\n "type": "integer",\n "minimum": 0,\n "maximum": 100\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ]\n },\n "toolsAnnotated": {\n "type": "integer",\n "minimum": 0\n },\n "toolsDescribed": {\n "type": "integer",\n "minimum": 0\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n },\n "contextTokens": {\n "type": "integer",\n "minimum": 0\n },\n "topImprovement": {\n "type": "string",\n "maxLength": 300\n }\n }\n }\n ]\n },\n "coverage": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "trustChecksRun": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "capabilities": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "capabilities",\n "lethalTrifecta",\n "note"\n ],\n "properties": {\n "capabilities": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "capability",\n "label",\n "tools",\n "basis"\n ],\n "properties": {\n "capability": {\n "type": "string"\n },\n "label": {\n "type": "string",\n "maxLength": 400\n },\n "tools": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n },\n "maxItems": 20\n },\n "basis": {\n "enum": [\n "declared",\n "inferred"\n ]\n }\n }\n }\n },\n "lethalTrifecta": {\n "type": "boolean"\n },\n "note": {\n "type": "string",\n "maxLength": 400\n }\n }\n },\n "functional": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "ran",\n "calledTools",\n "notCalled",\n "calls"\n ],\n "properties": {\n "ran": {\n "type": "boolean"\n },\n "reason": {\n "type": "string",\n "maxLength": 400\n },\n "calledTools": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n },\n "survived": {\n "type": "boolean"\n },\n "notCalled": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "tool",\n "why"\n ],\n "properties": {\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "why": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n },\n "calls": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "tool",\n "purpose",\n "outcome",\n "latencyMs",\n "problems"\n ],\n "properties": {\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "purpose": {\n "type": "string",\n "maxLength": 400\n },\n "outcome": {\n "type": "string",\n "maxLength": 400\n },\n "latencyMs": {\n "type": "integer",\n "minimum": 0\n },\n "problems": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n }\n }\n },\n "load": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "operation",\n "latency",\n "levels",\n "verdicts"\n ],\n "properties": {\n "operation": {\n "type": "string",\n "maxLength": 400\n },\n "latency": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "p50": {\n "type": "number"\n },\n "p95": {\n "type": "number"\n },\n "samples": {\n "type": "integer"\n }\n }\n },\n "levels": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "concurrency",\n "requests",\n "ok",\n "rateLimited",\n "errors",\n "p95",\n "throughput"\n ],\n "properties": {\n "concurrency": {\n "type": "number",\n "minimum": 0\n },\n "requests": {\n "type": "number",\n "minimum": 0\n },\n "ok": {\n "type": "number",\n "minimum": 0\n },\n "rateLimited": {\n "type": "number",\n "minimum": 0\n },\n "errors": {\n "type": "number",\n "minimum": 0\n },\n "p95": {\n "type": "number",\n "minimum": 0\n },\n "throughput": {\n "type": "number",\n "minimum": 0\n }\n }\n }\n },\n "memoryGrowthMb": {\n "type": "number"\n },\n "verdicts": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n },\n "tests": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "id",\n "tool",\n "status",\n "problems"\n ],\n "properties": {\n "id": {\n "type": "string",\n "maxLength": 400\n },\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "status": {\n "enum": [\n "pass",\n "fail",\n "skipped"\n ]\n },\n "problems": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n },\n "latencyMs": {\n "type": "integer",\n "minimum": 0\n }\n }\n }\n },\n "suppressions": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "check",\n "reason"\n ],\n "properties": {\n "check": {\n "type": "string",\n "maxLength": 400\n },\n "reason": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n },\n "$defs": {\n "finding": {\n "type": "object",\n "required": [\n "check",\n "pack",\n "status",\n "severity",\n "title"\n ],\n "additionalProperties": false,\n "properties": {\n "check": {\n "type": "string"\n },\n "pack": {\n "type": "string"\n },\n "status": {\n "enum": [\n "pass",\n "fail",\n "skipped",\n "inconclusive",\n "info"\n ]\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "scored": {\n "type": "boolean"\n },\n "title": {\n "type": "string"\n },\n "subject": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "evidence": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "hash": {\n "type": "string"\n },\n "excerpt": {\n "type": "string",\n "maxLength": 240\n }\n }\n },\n "suppressed": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "reason"\n ],\n "properties": {\n "reason": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n }\n }\n}\n', "test-cases.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/test-cases/0.1.json",\n "title": "Saktum Trust Check functional test cases (saktum.tests.yaml)",\n "type": "object",\n "required": ["testsFormat", "tests"],\n "additionalProperties": false,\n "properties": {\n "testsFormat": { "const": "0.1" },\n "tests": {\n "type": "array",\n "items": {\n "type": "object",\n "required": ["id", "tool", "input", "expect"],\n "additionalProperties": false,\n "properties": {\n "id": { "type": "string" },\n "tool": { "type": "string" },\n "input": { "type": "object" },\n "sideEffects": { "type": "boolean", "default": false, "description": "Tests with side effects run only against owned targets." },\n "expect": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "isError": { "type": "boolean" },\n "textContains": { "type": "string" },\n "structured": { "type": "object" },\n "outputSchema": { "type": "boolean" },\n "latencyMs": { "type": "object", "properties": { "lt": { "type": "integer" } }, "additionalProperties": false }\n }\n }\n }\n }\n }\n }\n}\n' };
19300
- EMBEDDED_PACKS = { "agent-experience.yaml": 'packFormat: "0.1"\nid: agent-experience\nversion: 0.1.0\ncategory: agent-experience\ndescription: How easily and cheaply agents can use the server. Reported, never part of the trust score.\nchecks:\n - id: ax.context-cost\n title: Context cost of tool definitions\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: context-cost }]\n fix: Shorten long descriptions, split large servers, and drop tools agents rarely need.\n - id: ax.annotations\n title: Tools declare annotations\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: annotations-present }]\n fix: Set readOnlyHint, destructiveHint, idempotentHint and openWorldHint on every tool so clients can warn before risky actions.\n references: ["MCP specification: tool annotations", "OWASP MCP Top 10: MCP02 Privilege Escalation via Scope Creep (undeclared write and destructive tools)"]\n - id: ax.short-descriptions\n title: Tools have usable descriptions\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: short-descriptions }]\n fix: Describe what the tool does, when to use it and when not to, in at least a full sentence.\n - id: ax.client-compat\n title: Fits common client and model-provider constraints\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: client-compat }]\n fix: Use tool names of 1 to 64 letters, digits, underscores and hyphens, keep them short enough for a server prefix, and keep the tool count manageable.\n', "auth.yaml": `packFormat: "0.1"
19784
+ `, "result.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/result/0.1.json",\n "title": "Saktum Trust Check result",\n "description": "The canonical result of one run. Every report format is rendered from this model. Evidence is a hash plus a short, sanitised excerpt; raw payloads never appear.",\n "type": "object",\n "required": [\n "resultFormat",\n "tool",\n "target",\n "packs",\n "findings",\n "scores",\n "metrics",\n "run"\n ],\n "additionalProperties": false,\n "properties": {\n "resultFormat": {\n "const": "0.1"\n },\n "tool": {\n "type": "object",\n "required": [\n "name",\n "version"\n ],\n "additionalProperties": false,\n "properties": {\n "name": {\n "const": "saktum-trust-check"\n },\n "version": {\n "type": "string"\n }\n }\n },\n "target": {\n "type": "object",\n "required": [\n "transport",\n "description"\n ],\n "additionalProperties": false,\n "properties": {\n "transport": {\n "enum": [\n "stdio",\n "streamable-http"\n ]\n },\n "description": {\n "type": "string"\n },\n "protocolVersion": {\n "type": "string"\n },\n "serverInfo": {\n "type": "object"\n },\n "toolsFingerprint": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "packs": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "id",\n "version",\n "hash"\n ],\n "additionalProperties": false,\n "properties": {\n "id": {\n "type": "string"\n },\n "version": {\n "type": "string"\n },\n "hash": {\n "type": "string",\n "pattern": "^sha256:[0-9a-f]{64}$"\n }\n }\n }\n },\n "findings": {\n "type": "array",\n "items": {\n "$ref": "#/$defs/finding"\n }\n },\n "scores": {\n "type": "object",\n "required": [\n "overall",\n "capped",\n "categories"\n ],\n "additionalProperties": false,\n "properties": {\n "overall": {\n "type": [\n "integer",\n "null"\n ],\n "minimum": 0,\n "maximum": 100\n },\n "capped": {\n "type": "boolean"\n },\n "categories": {\n "type": "object",\n "additionalProperties": {\n "type": [\n "integer",\n "null"\n ]\n }\n }\n }\n },\n "metrics": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "contextCostTokens": {\n "type": "integer",\n "minimum": 0\n },\n "largestTools": {\n "type": "array",\n "items": {\n "type": "object",\n "required": [\n "tool",\n "tokens"\n ],\n "properties": {\n "tool": {\n "type": "string"\n },\n "tokens": {\n "type": "integer"\n }\n }\n }\n },\n "contextCostPer1kTurnsUsd": {\n "type": "number",\n "minimum": 0,\n "description": "Estimated cost of loading the tool definitions on 1,000 agent turns at pricePerMTokUsd. Reported only."\n },\n "pricePerMTokUsd": {\n "type": "number",\n "minimum": 0\n },\n "performance": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "initMs": {\n "type": "integer",\n "minimum": 0\n },\n "listMs": {\n "type": "integer",\n "minimum": 0\n },\n "listBytes": {\n "type": "integer",\n "minimum": 0\n },\n "rssMb": {\n "type": "number",\n "minimum": 0\n },\n "cpuPct": {\n "type": "number",\n "minimum": 0\n },\n "burst": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "requests": {\n "type": "integer"\n },\n "ok": {\n "type": "integer"\n },\n "rateLimited": {\n "type": "integer"\n },\n "errors": {\n "type": "integer"\n },\n "p95Ms": {\n "type": "integer"\n }\n }\n }\n }\n }\n }\n },\n "run": {\n "type": "object",\n "required": [\n "startedAt",\n "durationMs",\n "mode",\n "runner",\n "sandbox"\n ],\n "additionalProperties": false,\n "properties": {\n "startedAt": {\n "type": "string",\n "format": "date-time"\n },\n "durationMs": {\n "type": "integer",\n "minimum": 0\n },\n "mode": {\n "enum": [\n "passive",\n "active"\n ]\n },\n "runner": {\n "enum": [\n "self",\n "hosted"\n ],\n "description": "self: run and signed by the user, proves integrity not independence. hosted: run and signed by Saktum (later)."\n },\n "sandbox": {\n "enum": [\n "none",\n "docker"\n ],\n "description": "Whether local servers ran inside a container sandbox."\n }\n }\n },\n "signature": {\n "type": "object",\n "required": [\n "alg",\n "kid",\n "jws"\n ],\n "additionalProperties": false,\n "properties": {\n "alg": {\n "const": "EdDSA"\n },\n "kid": {\n "type": "string",\n "pattern": "^did:key:z"\n },\n "jws": {\n "type": "string"\n }\n }\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ],\n "description": "Letter grade from the trust score: A 90-100, B 80-89, C 70-79, D 50-69, F below 50 or any failed critical check."\n },\n "summary": {\n "type": "array",\n "maxItems": 5,\n "items": {\n "type": "string",\n "maxLength": 400\n },\n "description": "Plain-language summary sentences shown first in every report."\n },\n "assuranceLevel": {\n "enum": [\n "L1",\n "L2",\n "L3",\n "L4"\n ],\n "description": "L1 self-tested (Saktum Check); L2 independently tested; L3 certified; L4 continuously certified."\n },\n "readiness": {\n "description": "Agent readiness: a second grade beside trust (annotations, descriptions, context cost), never mixed into the trust score.",\n "oneOf": [\n {\n "type": "null"\n },\n {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "score",\n "grade",\n "toolsAnnotated",\n "toolsDescribed",\n "toolCount",\n "contextTokens"\n ],\n "properties": {\n "score": {\n "type": "integer",\n "minimum": 0,\n "maximum": 100\n },\n "grade": {\n "enum": [\n "A",\n "B",\n "C",\n "D",\n "F",\n null\n ]\n },\n "toolsAnnotated": {\n "type": "integer",\n "minimum": 0\n },\n "toolsDescribed": {\n "type": "integer",\n "minimum": 0\n },\n "toolCount": {\n "type": "integer",\n "minimum": 0\n },\n "contextTokens": {\n "type": "integer",\n "minimum": 0\n },\n "topImprovement": {\n "type": "string",\n "maxLength": 300\n }\n }\n }\n ]\n },\n "coverage": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "trustChecksRun": {\n "type": "integer",\n "minimum": 0\n }\n }\n },\n "capabilities": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "capabilities",\n "lethalTrifecta",\n "note"\n ],\n "properties": {\n "capabilities": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "capability",\n "label",\n "tools",\n "basis"\n ],\n "properties": {\n "capability": {\n "type": "string"\n },\n "label": {\n "type": "string",\n "maxLength": 400\n },\n "tools": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n },\n "maxItems": 20\n },\n "basis": {\n "enum": [\n "declared",\n "inferred"\n ]\n }\n }\n }\n },\n "lethalTrifecta": {\n "type": "boolean"\n },\n "note": {\n "type": "string",\n "maxLength": 400\n }\n }\n },\n "functional": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "ran",\n "calledTools",\n "notCalled",\n "calls"\n ],\n "properties": {\n "ran": {\n "type": "boolean"\n },\n "reason": {\n "type": "string",\n "maxLength": 400\n },\n "calledTools": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n },\n "survived": {\n "type": "boolean"\n },\n "notCalled": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "tool",\n "why"\n ],\n "properties": {\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "why": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n },\n "calls": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "tool",\n "purpose",\n "outcome",\n "latencyMs",\n "problems"\n ],\n "properties": {\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "purpose": {\n "type": "string",\n "maxLength": 400\n },\n "outcome": {\n "type": "string",\n "maxLength": 400\n },\n "latencyMs": {\n "type": "integer",\n "minimum": 0\n },\n "problems": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n }\n }\n },\n "load": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "operation",\n "latency",\n "levels",\n "verdicts"\n ],\n "properties": {\n "operation": {\n "type": "string",\n "maxLength": 400\n },\n "latency": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "p50": {\n "type": "number"\n },\n "p95": {\n "type": "number"\n },\n "samples": {\n "type": "integer"\n }\n }\n },\n "levels": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "concurrency",\n "requests",\n "ok",\n "rateLimited",\n "errors",\n "p95",\n "throughput"\n ],\n "properties": {\n "concurrency": {\n "type": "number",\n "minimum": 0\n },\n "requests": {\n "type": "number",\n "minimum": 0\n },\n "ok": {\n "type": "number",\n "minimum": 0\n },\n "rateLimited": {\n "type": "number",\n "minimum": 0\n },\n "errors": {\n "type": "number",\n "minimum": 0\n },\n "p95": {\n "type": "number",\n "minimum": 0\n },\n "throughput": {\n "type": "number",\n "minimum": 0\n }\n }\n }\n },\n "memoryGrowthMb": {\n "type": "number"\n },\n "verdicts": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n },\n "tests": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "id",\n "tool",\n "status",\n "problems"\n ],\n "properties": {\n "id": {\n "type": "string",\n "maxLength": 400\n },\n "tool": {\n "type": "string",\n "maxLength": 400\n },\n "status": {\n "enum": [\n "pass",\n "fail",\n "skipped"\n ]\n },\n "problems": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n },\n "latencyMs": {\n "type": "integer",\n "minimum": 0\n }\n }\n }\n },\n "suppressions": {\n "type": "array",\n "items": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "check",\n "reason"\n ],\n "properties": {\n "check": {\n "type": "string",\n "maxLength": 400\n },\n "reason": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n },\n "riskTier": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "tier",\n "label",\n "reasons",\n "requirement"\n ],\n "properties": {\n "tier": {\n "enum": [\n "R0",\n "R1",\n "R2",\n "R3",\n "R4"\n ]\n },\n "label": {\n "type": "string",\n "maxLength": 200\n },\n "reasons": {\n "type": "array",\n "items": {\n "type": "string",\n "maxLength": 400\n }\n },\n "requirement": {\n "type": "string",\n "maxLength": 300\n }\n }\n }\n },\n "$defs": {\n "finding": {\n "type": "object",\n "required": [\n "check",\n "pack",\n "status",\n "severity",\n "title"\n ],\n "additionalProperties": false,\n "properties": {\n "check": {\n "type": "string"\n },\n "pack": {\n "type": "string"\n },\n "status": {\n "enum": [\n "pass",\n "fail",\n "skipped",\n "inconclusive",\n "info"\n ]\n },\n "severity": {\n "enum": [\n "critical",\n "high",\n "medium",\n "low",\n "info"\n ]\n },\n "scored": {\n "type": "boolean"\n },\n "title": {\n "type": "string"\n },\n "subject": {\n "type": "string"\n },\n "message": {\n "type": "string"\n },\n "fix": {\n "type": "string"\n },\n "references": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "evidence": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "hash": {\n "type": "string"\n },\n "excerpt": {\n "type": "string",\n "maxLength": 240\n }\n }\n },\n "suppressed": {\n "type": "object",\n "additionalProperties": false,\n "required": [\n "reason"\n ],\n "properties": {\n "reason": {\n "type": "string",\n "maxLength": 400\n }\n }\n }\n }\n }\n }\n}\n', "test-cases.schema.json": '{\n "$schema": "https://json-schema.org/draft/2020-12/schema",\n "$id": "https://saktum.dev/schemas/test-cases/0.1.json",\n "title": "Saktum Trust Check functional test cases (saktum.tests.yaml)",\n "type": "object",\n "required": ["testsFormat", "tests"],\n "additionalProperties": false,\n "properties": {\n "testsFormat": { "const": "0.1" },\n "tests": {\n "type": "array",\n "items": {\n "type": "object",\n "required": ["id", "tool", "input", "expect"],\n "additionalProperties": false,\n "properties": {\n "id": { "type": "string" },\n "tool": { "type": "string" },\n "input": { "type": "object" },\n "sideEffects": { "type": "boolean", "default": false, "description": "Tests with side effects run only against owned targets." },\n "expect": {\n "type": "object",\n "additionalProperties": false,\n "properties": {\n "isError": { "type": "boolean" },\n "textContains": { "type": "string" },\n "structured": { "type": "object" },\n "outputSchema": { "type": "boolean" },\n "latencyMs": { "type": "object", "properties": { "lt": { "type": "integer" } }, "additionalProperties": false }\n }\n }\n }\n }\n }\n }\n}\n' };
19785
+ EMBEDDED_PACKS = { "agent-experience.yaml": 'packFormat: "0.1"\nid: agent-experience\nversion: 0.1.0\ncategory: agent-experience\ndescription: How easily and cheaply agents can use the server. Reported, never part of the trust score.\nchecks:\n - id: ax.context-cost\n title: Context cost of tool definitions\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: context-cost }]\n fix: Shorten long descriptions, split large servers, and drop tools agents rarely need.\n - id: ax.annotations\n title: Tools declare annotations\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: annotations-present }]\n fix: Set readOnlyHint, destructiveHint, idempotentHint and openWorldHint on every tool so clients can warn before risky actions.\n references: ["MCP specification: tool annotations", "OWASP MCP Top 10: MCP02 Privilege Escalation via Scope Creep (undeclared write and destructive tools)"]\n - id: ax.short-descriptions\n title: Tools have usable descriptions\n severity: low\n safety: passive\n steps: [{ action: analyse, analyser: short-descriptions }]\n fix: Describe what the tool does, when to use it and when not to, in at least a full sentence.\n - id: ax.client-compat\n title: Fits common client and model-provider constraints\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: client-compat }]\n fix: Use tool names of 1 to 64 letters, digits, underscores and hyphens, keep them short enough for a server prefix, and keep the tool count manageable.\n - id: ax.payments-idempotent\n title: Tools that move money are idempotent\n severity: info\n safety: passive\n scored: false\n steps: [{ action: analyse, analyser: payments-idempotency }]\n fix: Mark payment tools idempotentHint true and accept an idempotency key, so a retried call can never charge twice.\n', "auth.yaml": `packFormat: "0.1"
19301
19786
  id: auth
19302
19787
  version: 0.1.0
19303
19788
  category: auth
@@ -19538,9 +20023,9 @@ function compileUntrustedSchema(schema) {
19538
20023
  const dialect = schemaDialect(schema);
19539
20024
  if (dialect === "unknown")
19540
20025
  return { ok: false, error: `unrecognised $schema dialect ${JSON.stringify(schema.$schema).slice(0, 80)}` };
19541
- const { $schema: _ignored, ...body } = schema;
20026
+ const { $schema: _ignored, ...body2 } = schema;
19542
20027
  const Ctor = dialect === "2020-12" ? Ajv2020 : dialect === "2019-09" ? Ajv2019 : AjvDraft7;
19543
- new Ctor({ strict: false, allErrors: false, validateSchema: true, logger: false }).compile(body);
20028
+ new Ctor({ strict: false, allErrors: false, validateSchema: true, logger: false }).compile(body2);
19544
20029
  return { ok: true };
19545
20030
  } catch (e) {
19546
20031
  return { ok: false, error: e.message };
@@ -19553,10 +20038,10 @@ function compileUntrustedSchemaValidator(schema) {
19553
20038
  const dialect = schemaDialect(schema);
19554
20039
  if (dialect === "unknown")
19555
20040
  return { ok: false, error: "unrecognised $schema dialect" };
19556
- const { $schema: _ignored, ...body } = schema;
20041
+ const { $schema: _ignored, ...body2 } = schema;
19557
20042
  const Ctor = dialect === "2020-12" ? Ajv2020 : dialect === "2019-09" ? Ajv2019 : AjvDraft7;
19558
20043
  const ajv2 = new Ctor({ strict: false, allErrors: false, validateSchema: true, logger: false });
19559
- const fn = ajv2.compile(body);
20044
+ const fn = ajv2.compile(body2);
19560
20045
  return { ok: true, validate: (d) => Boolean(fn(d)), errors: () => (fn.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message ?? ""}`).join("; ") };
19561
20046
  } catch (e) {
19562
20047
  return { ok: false, error: e.message };
@@ -19584,7 +20069,7 @@ var init_contracts = __esm({
19584
20069
  contractsDir = fileURLToPath(new URL("../../../contracts/", import.meta.url));
19585
20070
  ajv = new Ajv2020({ allErrors: true, strict: false });
19586
20071
  addFormats(ajv);
19587
- for (const f of ["envelope.schema.json", "receipt.schema.json", "pack.schema.json", "result.schema.json", "test-cases.schema.json", "policy.schema.json", "mandate.schema.json"]) {
20072
+ for (const f of ["envelope.schema.json", "receipt.schema.json", "pack.schema.json", "result.schema.json", "test-cases.schema.json", "policy.schema.json", "mandate.schema.json", "credential.schema.json", "manifest.schema.json", "agreement.schema.json", "bounty.schema.json"]) {
19588
20073
  ajv.addSchema(JSON.parse(contractText(f)), f);
19589
20074
  }
19590
20075
  }
@@ -19609,14 +20094,14 @@ function loadPackText(text2, path, opts = {}) {
19609
20094
  throw new PackError(`${path}: pack signed by an untrusted key`);
19610
20095
  signedBy = v.kid;
19611
20096
  }
19612
- const { signature: _s, ...body } = data;
20097
+ const { signature: _s, ...body2 } = data;
19613
20098
  const ids = /* @__PURE__ */ new Set();
19614
20099
  for (const c of data.checks) {
19615
20100
  if (ids.has(c.id))
19616
20101
  throw new PackError(`${path}: duplicate check id ${c.id}`);
19617
20102
  ids.add(c.id);
19618
20103
  }
19619
- return { pack: data, hash: sha256Tag(canonicalize(body)), signedBy };
20104
+ return { pack: data, hash: sha256Tag(canonicalize(body2)), signedBy };
19620
20105
  }
19621
20106
  function loadPackDir(dir, opts) {
19622
20107
  return readdirSync(dir).filter((f) => /\.(ya?ml|json)$/.test(f)).sort().map((f) => loadPack(join2(dir, f), opts));
@@ -19763,9 +20248,9 @@ annotations: ${tsValue(x.suggested)},`);
19763
20248
  lines.push(`${format === "py" ? "#" : "//"} ${sanitizeText(x.tool, 60)}: ${x.conflict}`);
19764
20249
  lines.push("");
19765
20250
  }
19766
- const short = tools.filter((t) => (t.description ?? "").trim().length < 20);
19767
- if (short.length)
19768
- lines.push(`${format === "py" ? "#" : "//"} Also write a one-sentence description (what it does, when to use it) for: ${short.map((t) => sanitizeText(t.name, 40)).join(", ")}`);
20251
+ const short2 = tools.filter((t) => (t.description ?? "").trim().length < 20);
20252
+ if (short2.length)
20253
+ lines.push(`${format === "py" ? "#" : "//"} Also write a one-sentence description (what it does, when to use it) for: ${short2.map((t) => sanitizeText(t.name, 40)).join(", ")}`);
19769
20254
  const cost = contextCost(tools);
19770
20255
  if (cost.contextCostTokens > 1e4)
19771
20256
  lines.push(`${format === "py" ? "#" : "//"} Context cost is ${cost.contextCostTokens.toLocaleString("en-US")} tokens per turn; the largest tools are ${cost.largestTools.slice(0, 3).map((x) => `${x.tool} (${x.tokens})`).join(", ")}: shorten their descriptions and schemas first.`);
@@ -32154,15 +32639,15 @@ function applyPublicAuth(clientId, params) {
32154
32639
  }
32155
32640
  async function parseErrorResponse(input) {
32156
32641
  const statusCode = input instanceof Response ? input.status : void 0;
32157
- const body = input instanceof Response ? await input.text() : input;
32642
+ const body2 = input instanceof Response ? await input.text() : input;
32158
32643
  try {
32159
- const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
32644
+ const result = OAuthErrorResponseSchema.parse(JSON.parse(body2));
32160
32645
  const { error: error2, error_description, error_uri } = result;
32161
32646
  const errorClass = OAUTH_ERRORS[error2] || ServerError;
32162
32647
  return new errorClass(error_description || "", error_uri);
32163
32648
  } catch (error2) {
32164
32649
  const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
32165
- const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error2}. Raw body: ${body}`}`;
32650
+ const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error2}. Raw body: ${body2}`}`;
32166
32651
  return new ServerError(errorMessage);
32167
32652
  }
32168
32653
  }
@@ -33440,12 +33925,12 @@ async function httpRequest(url2, init = {}) {
33440
33925
  res.headers.forEach((v, k) => {
33441
33926
  headers[k.toLowerCase()] = v;
33442
33927
  });
33443
- let body = "";
33928
+ let body2 = "";
33444
33929
  try {
33445
- body = (await res.text()).slice(0, HTTP_LIMITS.maxBodyChars);
33930
+ body2 = (await res.text()).slice(0, HTTP_LIMITS.maxBodyChars);
33446
33931
  } catch {
33447
33932
  }
33448
- return { status: res.status, headers, body, ms: Date.now() - t0 };
33933
+ return { status: res.status, headers, body: body2, ms: Date.now() - t0 };
33449
33934
  } catch (e) {
33450
33935
  return { status: null, headers: {}, body: "", error: e.name === "AbortError" ? "timed out" : e.message, ms: Date.now() - t0 };
33451
33936
  } finally {
@@ -33511,7 +33996,7 @@ var init_dist3 = __esm({
33511
33996
  init_stdio2();
33512
33997
  init_streamableHttp();
33513
33998
  init_types2();
33514
- USER_AGENT = "saktum-check/0.6.0 (+https://saktum.dev/check)";
33999
+ USER_AGENT = "saktum-check/0.8.0 (+https://saktum.dev/check)";
33515
34000
  LIMITS = { requestTimeoutMs: 1e4, connectTimeoutMs: 6e4, maxResponseChars: 5e6 };
33516
34001
  LimitError = class extends Error {
33517
34002
  };
@@ -33549,7 +34034,7 @@ var init_dist3 = __esm({
33549
34034
  jsonrpc: "2.0",
33550
34035
  id: 1,
33551
34036
  method: "initialize",
33552
- params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.6.0" } }
34037
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.8.0" } }
33553
34038
  });
33554
34039
  }
33555
34040
  });
@@ -33990,6 +34475,7 @@ var init_analysers = __esm({
33990
34475
  init_contracts();
33991
34476
  init_safe();
33992
34477
  init_provider();
34478
+ init_capabilities();
33993
34479
  init_auth3();
33994
34480
  init_leakage();
33995
34481
  init_perf();
@@ -34018,6 +34504,13 @@ ${JSON.stringify(t.inputSchema ?? {})}`;
34018
34504
  /(send|upload|post|forward) (the |all |any )?(conversation|chat history|credentials|api keys?|secrets?|tokens?) to/i
34019
34505
  ];
34020
34506
  coreAnalysers = {
34507
+ "payments-idempotency": ({ tools }) => {
34508
+ const money = tools.filter((t) => capabilityProfile([t]).capabilities.some((c) => c.capability === "money"));
34509
+ if (!money.length)
34510
+ return { status: "pass", message: "No tools that move money were found." };
34511
+ const weak = money.filter((t) => t.annotations?.idempotentHint !== true && !Object.keys((t.inputSchema ?? {}).properties ?? {}).some((k) => /idempot|request_?id|client_?reference|dedup/i.test(k)));
34512
+ return weak.length ? { status: "info", message: `${weak.length} tool(s) that move money declare no idempotency (idempotentHint or an idempotency key): ${weak.slice(0, 5).map((t) => t.name).join(", ")}. A retried call could charge twice.` } : { status: "pass", message: `${money.length} tool(s) that move money declare idempotency.` };
34513
+ },
34021
34514
  "client-compat": ({ tools }) => {
34022
34515
  const issues = clientCompatibility(tools);
34023
34516
  return issues.length ? { status: "info", message: issues.join(" ") } : { status: "pass", message: "Tool names and count fit the constraints common to model providers and clients." };
@@ -34099,8 +34592,8 @@ ${JSON.stringify(t.inputSchema ?? {})}`;
34099
34592
  return missing.length ? { status: "fail", subject: "tools", message: `${missing.length} of ${tools.length} tool(s) declare no annotations (read-only, destructive, idempotent, open-world hints): ${listNames(missing)}.` } : { status: "pass", message: "Every tool declares annotations." };
34100
34593
  },
34101
34594
  "short-descriptions": ({ tools }) => {
34102
- const short = tools.filter((t) => (t.description ?? "").trim().length < 20);
34103
- return short.length ? { status: "fail", subject: "tools", message: `${short.length} tool(s) have descriptions under 20 characters, which agents find hard to choose between: ${listNames(short)}.`, evidence: evidenceFor(short[0]) } : { status: "pass", message: "Every tool has a usable description." };
34595
+ const short2 = tools.filter((t) => (t.description ?? "").trim().length < 20);
34596
+ return short2.length ? { status: "fail", subject: "tools", message: `${short2.length} tool(s) have descriptions under 20 characters, which agents find hard to choose between: ${listNames(short2)}.`, evidence: evidenceFor(short2[0]) } : { status: "pass", message: "Every tool has a usable description." };
34104
34597
  },
34105
34598
  "context-cost": ({ tools, pricePerMTokUsd }) => {
34106
34599
  const { contextCostTokens, largestTools, contextCostPer1kTurnsUsd } = contextCost(tools, pricePerMTokUsd);
@@ -34348,6 +34841,56 @@ var init_readiness = __esm({
34348
34841
  }
34349
34842
  });
34350
34843
 
34844
+ // packages/testkit-core/dist/risk.js
34845
+ function riskTier(tools) {
34846
+ const caps = capabilityProfile(tools).capabilities;
34847
+ const has2 = (c) => caps.find((x) => x.capability === c);
34848
+ const destructive = tools.filter((t) => t.annotations?.destructiveHint === true).map((t) => t.name);
34849
+ const reasons = [];
34850
+ let tier = "R0";
34851
+ const bump = (t, why) => {
34852
+ reasons.push(why);
34853
+ if (t > tier)
34854
+ tier = t;
34855
+ };
34856
+ if (has2("money"))
34857
+ bump("R4", `moves money (${has2("money").tools.slice(0, 3).join(", ")})`);
34858
+ if (has2("code-execution"))
34859
+ bump("R4", `runs code or commands (${has2("code-execution").tools.slice(0, 3).join(", ")})`);
34860
+ if (destructive.length)
34861
+ bump("R3", `declares destructive tools (${destructive.slice(0, 3).join(", ")})`);
34862
+ if (has2("sends-messages"))
34863
+ bump("R3", `sends messages (${has2("sends-messages").tools.slice(0, 3).join(", ")})`);
34864
+ if (has2("writes-or-deletes"))
34865
+ bump("R2", `changes data (${has2("writes-or-deletes").tools.slice(0, 3).join(", ")})`);
34866
+ if (has2("reads-private-data"))
34867
+ bump("R1", "reads private data");
34868
+ if (!reasons.length)
34869
+ reasons.push("only reads; no capability that changes data, moves money or runs code was found");
34870
+ return { tier, label: RISK_LABELS[tier], reasons, requirement: TIER_REQUIREMENT[tier] };
34871
+ }
34872
+ var RISK_LABELS, TIER_REQUIREMENT;
34873
+ var init_risk = __esm({
34874
+ "packages/testkit-core/dist/risk.js"() {
34875
+ "use strict";
34876
+ init_capabilities();
34877
+ RISK_LABELS = {
34878
+ R0: "reads public information",
34879
+ R1: "reads private data",
34880
+ R2: "changes data",
34881
+ R3: "irreversible actions or external messages",
34882
+ R4: "moves money or runs code"
34883
+ };
34884
+ TIER_REQUIREMENT = {
34885
+ R0: "L2 (conformant)",
34886
+ R1: "L3 (safe by default)",
34887
+ R2: "L4 (agent-ready) and a mandate",
34888
+ R3: "L5, a mandate, approval for irreversible actions, receipts",
34889
+ R4: "L5, an enforced mandate with value caps, approvals, receipts and monitoring"
34890
+ };
34891
+ }
34892
+ });
34893
+
34351
34894
  // packages/testkit-core/dist/functional.js
34352
34895
  function exampleFor(schema, depth = 0) {
34353
34896
  const s = obj(schema);
@@ -34837,7 +35380,7 @@ async function runTrustCheck(target, opts) {
34837
35380
  }
34838
35381
  const noGrade = signInRequired ? { kind: "sign-in" } : listError ? { kind: "list-failed", error: sanitizeText(listError, 160) } : tools.length === 0 ? { kind: "no-tools", toolsCapability: Boolean(session?.capabilities?.tools) } : void 0;
34839
35382
  return finish(target, { ...opts, mode }, startedAt, findings, session ? { protocolVersion: session.protocolVersion, serverInfo: session.serverInfo, toolsFingerprint: fingerprint, toolCount: tools.length } : { toolCount: 0 }, metrics, session?.sandbox ?? "none", noGrade, session && !listError ? readinessFor(tools) : null, {
34840
- ...session && !listError && tools.length ? { capabilities: capabilityProfile(tools) } : {},
35383
+ ...session && !listError && tools.length ? { capabilities: capabilityProfile(tools), riskTier: riskTier(tools) } : {},
34841
35384
  ...ctx.functional ? { functional: summariseFunctional(ctx.functional) } : {},
34842
35385
  ...ctx.load ? { load: ctx.load } : {},
34843
35386
  ...testResults ? { tests: testResults } : {}
@@ -34857,12 +35400,13 @@ var init_engine = __esm({
34857
35400
  init_grade();
34858
35401
  init_readiness();
34859
35402
  init_capabilities();
35403
+ init_risk();
34860
35404
  init_functional();
34861
35405
  init_load();
34862
35406
  init_runner();
34863
35407
  init_safe();
34864
35408
  init_scoring();
34865
- ENGINE_VERSION = "0.6.0";
35409
+ ENGINE_VERSION = "0.8.0";
34866
35410
  UNKNOWN_TOOL = "saktum_trust_check_no_such_tool";
34867
35411
  INVALID_TOKEN = "saktum-check-deliberately-invalid-token";
34868
35412
  baseOf = (pack, check) => ({
@@ -35123,6 +35667,8 @@ function evaluatePolicy(s, p, allowlistFingerprints, today = (/* @__PURE__ */ ne
35123
35667
  if (bad.length)
35124
35668
  v.push({ rule: "noFailedSeverity", message: `${bad.length} failed check(s) at ${p.noFailedSeverity} or above` });
35125
35669
  }
35670
+ if (p.maxRiskTier && s.riskTier && s.riskTier > p.maxRiskTier)
35671
+ v.push({ rule: "maxRiskTier", message: `risk tier ${s.riskTier} is above the allowed ${p.maxRiskTier}` });
35126
35672
  if (p.requireAllowlist && !(s.toolsFingerprint && allowlistFingerprints?.has(s.toolsFingerprint)))
35127
35673
  v.push({ rule: "requireAllowlist", message: "is not on the organisation's allowlist (or its tools changed since it was approved)" });
35128
35674
  for (const x of v) {
@@ -35141,7 +35687,8 @@ function subjectFromResult(r, name) {
35141
35687
  lethalTrifecta: Boolean(r.capabilities?.lethalTrifecta),
35142
35688
  contextTokens: r.readiness?.contextTokens ?? null,
35143
35689
  failedSeverities: r.findings.filter((f) => f.status === "fail" && !f.suppressed).map((f) => f.severity),
35144
- toolsFingerprint: r.target.toolsFingerprint
35690
+ toolsFingerprint: r.target.toolsFingerprint,
35691
+ riskTier: r.riskTier?.tier
35145
35692
  };
35146
35693
  }
35147
35694
  function renderVerdict(v) {
@@ -35267,11 +35814,11 @@ function checkAttestation(a) {
35267
35814
  }
35268
35815
  function extractJson(text2) {
35269
35816
  const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text2);
35270
- const body = fenced ? fenced[1] : text2;
35271
- const start = body.indexOf("{"), end = body.lastIndexOf("}");
35817
+ const body2 = fenced ? fenced[1] : text2;
35818
+ const start = body2.indexOf("{"), end = body2.lastIndexOf("}");
35272
35819
  if (start < 0 || end <= start)
35273
35820
  throw new Error("no JSON object found");
35274
- return JSON.parse(body.slice(start, end + 1));
35821
+ return JSON.parse(body2.slice(start, end + 1));
35275
35822
  }
35276
35823
  function appendToLedger(ledgerText, attestation, source, now = /* @__PURE__ */ new Date()) {
35277
35824
  const c = checkAttestation(attestation);
@@ -35380,44 +35927,116 @@ var init_ledger = __esm({
35380
35927
  }
35381
35928
  });
35382
35929
 
35383
- // packages/testkit-core/dist/agentid.js
35384
- function createMandate(o, ownerKey) {
35385
- const body = {
35386
- mandateFormat: "0.1",
35387
- agent: { id: o.agentId, name: sanitizeText(o.agentName, 120) },
35388
- owner: { id: ownerKey.kid, ...o.ownerName ? { name: sanitizeText(o.ownerName, 120) } : {} },
35389
- ...o.purpose ? { purpose: sanitizeText(o.purpose, 300) } : {},
35390
- allow: { ...o.servers?.length ? { servers: o.servers } : {}, ...o.tools?.length ? { tools: o.tools } : {}, destructive: o.destructive },
35391
- issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
35392
- expires: o.expires
35393
- };
35394
- return signDocument(body, ownerKey);
35395
- }
35396
- function checkMandate(m, today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)) {
35397
- const v = verifyDocument(m);
35398
- if (!v.valid)
35399
- return { ok: false, reason: `mandate signature not valid (${v.reason})` };
35400
- if (v.kid !== m.owner.id)
35401
- return { ok: false, reason: "mandate is not signed by its stated owner" };
35402
- if (m.expires < today)
35403
- return { ok: false, reason: `mandate expired on ${m.expires}` };
35404
- return { ok: true };
35930
+ // packages/testkit-core/dist/vocab.js
35931
+ function actionClass(t) {
35932
+ const declared = t._meta?.["io.saktum/action"];
35933
+ if (typeof declared === "string")
35934
+ return { cls: declared, basis: "declared" };
35935
+ for (const [re, c] of NAME_RULES)
35936
+ if (re.test(t.name))
35937
+ return { cls: c, basis: "inferred" };
35938
+ return { cls: "other", basis: "inferred" };
35939
+ }
35940
+ function bindingsFor(t) {
35941
+ const declared = t._meta?.["io.saktum/bindings"];
35942
+ if (declared && typeof declared === "object")
35943
+ return { bindings: Object.fromEntries(Object.entries(declared).filter(([, f]) => KNOWN_FIELDS.has(f))), basis: "declared" };
35944
+ const props = Object.keys((t.inputSchema ?? {}).properties ?? {});
35945
+ const domainHint = /flight|seat|fare|trip|travel|hotel/i.test(`${t.name} ${t.description ?? ""}`) ? "travel" : "commerce";
35946
+ const out = {};
35947
+ for (const p of props)
35948
+ for (const [re, f] of ARG_RULES)
35949
+ if (re.test(p)) {
35950
+ out[p] = domainHint === "travel" && f === "commerce.order.total" ? "travel.fare.total" : domainHint === "travel" && f === "commerce.order.currency" ? "travel.fare.currency" : f;
35951
+ break;
35952
+ }
35953
+ return { bindings: out, basis: "inferred" };
35405
35954
  }
35406
- function mandateDecision(m, server, tool, ann) {
35407
- if (m.allow.servers && !m.allow.servers.includes(server))
35408
- return { allow: false, reason: `server ${server} is not in the agent's mandate` };
35409
- if (m.allow.tools && !m.allow.tools.includes(tool))
35410
- return { allow: false, reason: `tool ${tool} is not in the agent's mandate` };
35411
- const destructive = ann?.destructiveHint === true || ann?.readOnlyHint === false && ann?.destructiveHint !== false;
35412
- if (destructive && !m.allow.destructive)
35413
- return { allow: false, reason: `tool ${tool} is declared destructive and the mandate does not allow destructive actions` };
35414
- return { allow: true, reason: m.allow.tools || m.allow.servers ? "within the agent's mandate" : "mandate allows it" };
35955
+ function semanticValues(t, args) {
35956
+ const { bindings } = bindingsFor(t);
35957
+ return Object.fromEntries(Object.entries(bindings).filter(([a]) => args[a] !== void 0).map(([a, f]) => [f, args[a]]));
35415
35958
  }
35416
- var init_agentid = __esm({
35417
- "packages/testkit-core/dist/agentid.js"() {
35959
+ var VOCABULARIES, KNOWN_FIELDS, NAME_RULES, ARG_RULES;
35960
+ var init_vocab = __esm({
35961
+ "packages/testkit-core/dist/vocab.js"() {
35418
35962
  "use strict";
35419
- init_dist();
35420
- init_safe();
35963
+ VOCABULARIES = {
35964
+ commerce: { version: "0.1", fields: [
35965
+ { path: "commerce.order.total", type: "number", description: "Total amount of the order or payment" },
35966
+ { path: "commerce.order.currency", type: "string", description: "Currency of the order" },
35967
+ { path: "commerce.item.product", type: "string", description: "Product identifier or name" },
35968
+ { path: "commerce.item.brand", type: "string", description: "Brand of the item" },
35969
+ { path: "commerce.item.category", type: "string", description: "Category of the item (for example dairy, baby food, alcohol)" },
35970
+ { path: "commerce.item.quantity", type: "number", description: "Quantity of the item" },
35971
+ { path: "commerce.item.unit_price", type: "number", description: "Price of one unit" },
35972
+ { path: "commerce.item.substitute_for", type: "string", description: "The item this one replaces (a substitution)" },
35973
+ { path: "commerce.item.reference_price", type: "number", description: "Price of the item being replaced" },
35974
+ { path: "commerce.item.upgrade", type: "boolean", description: "A larger or premium option than requested (an upsell)" },
35975
+ { path: "commerce.item.sponsored", type: "boolean", description: "The option was sponsored or promoted" },
35976
+ { path: "commerce.counterparty", type: "string", description: "The merchant or seller" }
35977
+ ] },
35978
+ travel: { version: "0.1", fields: [
35979
+ { path: "travel.fare.total", type: "number", description: "Total fare" },
35980
+ { path: "travel.fare.currency", type: "string", description: "Currency of the fare" },
35981
+ { path: "travel.fare.refundable", type: "boolean", description: "Whether the fare is refundable" },
35982
+ { path: "travel.itinerary.connections", type: "number", description: "Number of connections (stops)" },
35983
+ { path: "travel.itinerary.arrive_by", type: "string", description: "Latest arrival time" },
35984
+ { path: "travel.carrier", type: "string", description: "Airline, rail or other carrier" },
35985
+ { path: "travel.seat", type: "string", description: "Seat or seat type (aisle, window)" },
35986
+ { path: "travel.fee", type: "number", description: "Any extra fee (seat, change, baggage)" },
35987
+ { path: "travel.upgrade", type: "boolean", description: "A paid upgrade (an upsell)" }
35988
+ ] }
35989
+ };
35990
+ VOCABULARIES.personal = { version: "0.1", fields: [
35991
+ { path: "personal.email", type: "string", description: "The principal's email address" },
35992
+ { path: "personal.phone", type: "string", description: "The principal's phone number" },
35993
+ { path: "personal.address", type: "string", description: "The principal's postal or delivery address" },
35994
+ { path: "personal.passport", type: "string", description: "The principal's passport or identity document number" },
35995
+ { path: "party.recipient", type: "string", description: "Who receives the data or the action" }
35996
+ ] };
35997
+ VOCABULARIES.enterprise = { version: "0.1", fields: [
35998
+ { path: "enterprise.data_class", type: "string", description: "Classification of the data: public, internal, confidential or restricted" },
35999
+ { path: "enterprise.vendor", type: "string", description: "The supplier or vendor" }
36000
+ ] };
36001
+ KNOWN_FIELDS = new Set(Object.values(VOCABULARIES).flatMap((v) => v.fields.map((f) => f.path)));
36002
+ NAME_RULES = [
36003
+ [/(^|[_-])(search|find|list|get|lookup|deals|browse)([_-]|$)/i, "search"],
36004
+ [/(^|[_-])(substitute|replace|swap)([_-]|$)/i, "substitute"],
36005
+ [/(^|[_-])(add_to_cart|cart|basket)([_-]|$)|add_to_cart/i, "cart"],
36006
+ [/(^|[_-])(pay|payment|checkout|purchase|charge)([_-]|$)/i, "pay"],
36007
+ [/(^|[_-])(book|reserve|hold)([_-]|$)/i, "book"],
36008
+ [/(^|[_-])(change|modify|update|seat|upgrade)([_-]|$)/i, "change"],
36009
+ [/(^|[_-])(cancel|refund|void)([_-]|$)/i, "cancel"],
36010
+ [/(^|[_-])(send|email|message|notify|post)([_-]|$)/i, "communicate"]
36011
+ ];
36012
+ ARG_RULES = [
36013
+ [/^(amount|total|order_total|price_total|grand_total)$/i, "commerce.order.total"],
36014
+ [/^currency$/i, "commerce.order.currency"],
36015
+ [/^(product|product_id|item|sku)$/i, "commerce.item.product"],
36016
+ [/^brand$/i, "commerce.item.brand"],
36017
+ [/^category$/i, "commerce.item.category"],
36018
+ [/^(quantity|qty|count)$/i, "commerce.item.quantity"],
36019
+ [/^(price|unit_price)$/i, "commerce.item.unit_price"],
36020
+ [/^(substitute_for|replaces|replacement_for)$/i, "commerce.item.substitute_for"],
36021
+ [/^(reference_price|original_price)$/i, "commerce.item.reference_price"],
36022
+ [/^(upgrade|premium|upsell)$/i, "commerce.item.upgrade"],
36023
+ [/^(sponsored|promoted)$/i, "commerce.item.sponsored"],
36024
+ [/^(merchant|seller|store)$/i, "commerce.counterparty"],
36025
+ [/^(fare|fare_total)$/i, "travel.fare.total"],
36026
+ [/^refundable$/i, "travel.fare.refundable"],
36027
+ [/^(stops|connections|max_stops)$/i, "travel.itinerary.connections"],
36028
+ [/^(email|email_address)$/i, "personal.email"],
36029
+ [/^(phone|phone_number|mobile)$/i, "personal.phone"],
36030
+ [/^(address|delivery_address|shipping_address)$/i, "personal.address"],
36031
+ [/^(passport|passport_number|id_number|document_number)$/i, "personal.passport"],
36032
+ [/^(recipient|partner|share_with)$/i, "party.recipient"],
36033
+ [/^(data_class|classification|sensitivity)$/i, "enterprise.data_class"],
36034
+ [/^(vendor|supplier|payee)$/i, "enterprise.vendor"],
36035
+ [/^(arrive_by|arrival)$/i, "travel.itinerary.arrive_by"],
36036
+ [/^(carrier|airline)$/i, "travel.carrier"],
36037
+ [/^seat$/i, "travel.seat"],
36038
+ [/^(fee|seat_fee|change_fee)$/i, "travel.fee"]
36039
+ ];
35421
36040
  }
35422
36041
  });
35423
36042
 
@@ -35475,7 +36094,12 @@ function summariseReceipts(entries) {
35475
36094
  from: entries[0]?.receipt.issuedAt,
35476
36095
  to: entries[entries.length - 1]?.receipt.issuedAt,
35477
36096
  medianLatencyMs: lat.length ? [...lat].sort((a, b) => a - b)[Math.floor(lat.length / 2)] : void 0,
35478
- order: entries.slice(0, 50).map((e) => e.receipt.envelope.tool)
36097
+ order: entries.slice(0, 50).map((e) => e.receipt.envelope.tool),
36098
+ byCode: Object.entries(entries.reduce((a, e) => {
36099
+ const k = e.result.code ?? (e.receipt.outcome === "deny" ? "denied" : "ok");
36100
+ a[k] = (a[k] ?? 0) + 1;
36101
+ return a;
36102
+ }, {})).map(([code, count]) => ({ code, count }))
35479
36103
  };
35480
36104
  }
35481
36105
  var RECEIPTS_GENESIS, argumentsHash, entryHashOf;
@@ -35489,6 +36113,335 @@ var init_receipts = __esm({
35489
36113
  }
35490
36114
  });
35491
36115
 
36116
+ // packages/testkit-core/dist/agentid.js
36117
+ import { homedir as _home } from "node:os";
36118
+ import { existsSync as _exists, readFileSync as _read, writeFileSync as _write, mkdirSync as _mkdir } from "node:fs";
36119
+ import { dirname as _dirname, join as _join } from "node:path";
36120
+ function createMandate(o, ownerKey) {
36121
+ const body2 = {
36122
+ mandateFormat: "0.1",
36123
+ agent: { id: o.agentId, name: sanitizeText(o.agentName, 120) },
36124
+ owner: { id: ownerKey.kid, ...o.ownerName ? { name: sanitizeText(o.ownerName, 120) } : {} },
36125
+ ...o.purpose ? { purpose: sanitizeText(o.purpose, 300) } : {},
36126
+ allow: { ...o.servers?.length ? { servers: o.servers } : {}, ...o.tools?.length ? { tools: o.tools } : {}, destructive: o.destructive },
36127
+ issuedAt: (/* @__PURE__ */ new Date()).toISOString(),
36128
+ expires: o.expires,
36129
+ ...o.autonomy ? { autonomy: o.autonomy } : {},
36130
+ ...o.constraints?.length ? { constraints: o.constraints } : {},
36131
+ ...o.limits && Object.keys(o.limits).length ? { limits: o.limits } : {},
36132
+ ...o.approveAbove ? { approveAbove: o.approveAbove } : {},
36133
+ ...o.disclosures && Object.keys(o.disclosures).length ? { disclosures: o.disclosures } : {},
36134
+ delegation: o.delegation === true,
36135
+ ...o.actions?.length ? { actions: o.actions } : {},
36136
+ ...o.rules?.length ? { rules: o.rules } : {},
36137
+ ...o.preferences?.length ? { preferences: o.preferences } : {},
36138
+ ...o.substitution ? { substitution: o.substitution } : {},
36139
+ ...o.upsell ? { upsell: o.upsell } : {},
36140
+ ...o.approvalTriggers?.length ? { approvalTriggers: o.approvalTriggers } : {},
36141
+ ...o.counterparties?.length ? { counterparties: o.counterparties } : {},
36142
+ ...o.dataSharing?.length ? { dataSharing: o.dataSharing } : {}
36143
+ };
36144
+ return signDocument(body2, ownerKey);
36145
+ }
36146
+ function checkMandate(m, today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)) {
36147
+ const { operatorCountersign: _cs, ...principalPart } = m;
36148
+ const v = verifyDocument(principalPart);
36149
+ if (!v.valid)
36150
+ return { ok: false, reason: `mandate signature not valid (${v.reason})` };
36151
+ if (v.kid !== m.owner.id)
36152
+ return { ok: false, reason: "mandate is not signed by its stated owner" };
36153
+ if (m.expires < today)
36154
+ return { ok: false, reason: `mandate expired on ${m.expires}` };
36155
+ return { ok: true };
36156
+ }
36157
+ function mandateDecision(m, server, tool, ann) {
36158
+ if (m.allow.servers && !m.allow.servers.includes(server))
36159
+ return { allow: false, reason: `server ${server} is not in the agent's mandate` };
36160
+ if (m.allow.tools && !m.allow.tools.includes(tool))
36161
+ return { allow: false, reason: `tool ${tool} is not in the agent's mandate` };
36162
+ const destructive = ann?.destructiveHint === true || ann?.readOnlyHint === false && ann?.destructiveHint !== false;
36163
+ if (destructive && !m.allow.destructive)
36164
+ return { allow: false, reason: `tool ${tool} is declared destructive and the mandate does not allow destructive actions` };
36165
+ return { allow: true, reason: m.allow.tools || m.allow.servers ? "within the agent's mandate" : "mandate allows it" };
36166
+ }
36167
+ function decideCall(m, c) {
36168
+ const base = mandateDecision(m, c.server, c.tool, c.annotations);
36169
+ if (!base.allow)
36170
+ return { allow: false, code: base.reason.includes("destructive") ? "destructive" : "not-in-mandate", reason: base.reason };
36171
+ const isRead = c.annotations?.readOnlyHint === true;
36172
+ const autonomy = m.autonomy ?? "act";
36173
+ if (autonomy === "notify" && !isRead)
36174
+ return { allow: false, code: "notify-only", reason: `notify-only mandate: tell your user about ${c.tool} instead of doing it` };
36175
+ const granted = m.allow.tools?.includes(c.tool) || m.constraints?.some((k) => k.tool === c.tool);
36176
+ if (c.isMoney && !granted)
36177
+ return { allow: false, code: "money-not-granted", reason: `${c.tool} moves money and is not explicitly granted in the mandate` };
36178
+ for (const k of (m.constraints ?? []).filter((x) => x.tool === c.tool)) {
36179
+ const v = c.args[k.arg];
36180
+ if (k.max !== void 0 && Number(v) > k.max)
36181
+ return { allow: false, code: "over-cap", reason: `${k.arg} ${v} is above the cap of ${k.max}` };
36182
+ if (k.oneOf && !k.oneOf.map(String).includes(String(v)))
36183
+ return { allow: false, code: "value-not-allowed", reason: `${k.arg} ${String(v)} is not one of ${k.oneOf.join(", ")}` };
36184
+ }
36185
+ if (!isRead && m.limits?.callsPerDay !== void 0 && c.usage.callsToday >= m.limits.callsPerDay)
36186
+ return { allow: false, code: "daily-limit", reason: `daily limit of ${m.limits.callsPerDay} actions reached` };
36187
+ const tot = m.limits?.totalPerDay;
36188
+ if (tot && c.args[tot.arg] !== void 0 && c.usage.totalToday + Number(c.args[tot.arg]) > tot.max)
36189
+ return { allow: false, code: "daily-limit", reason: `daily total for ${tot.arg} would reach ${c.usage.totalToday + Number(c.args[tot.arg])}, above ${tot.max}` };
36190
+ const ap = m.approveAbove;
36191
+ if (ap && c.args[ap.arg] !== void 0 && Number(c.args[ap.arg]) > ap.value)
36192
+ return { allow: false, code: "approval-needed", reason: `${ap.arg} ${c.args[ap.arg]} is above the approval threshold of ${ap.value}: ask your user to approve` };
36193
+ if (autonomy === "propose" && !isRead)
36194
+ return { allow: false, code: "approval-needed", reason: `propose mandate: ask your user to approve ${c.tool} before it runs` };
36195
+ return { allow: true, code: "ok", reason: autonomy === "act" ? "within the mandate's limits" : "read allowed" };
36196
+ }
36197
+ function agentRiskTier(m) {
36198
+ if (!m.allow.tools?.length && !m.constraints?.length)
36199
+ return { tier: m.autonomy === "notify" ? "R1" : "depends on servers", note: "no tool list: the tier follows the servers it connects to" };
36200
+ const names = [.../* @__PURE__ */ new Set([...m.allow.tools ?? [], ...(m.constraints ?? []).map((k) => k.tool)])];
36201
+ const money = names.some((n) => /(^|[_-])(pay|payment|charge|refund|checkout|purchase|buy|order|transfer|invoice)([_-]|$)/i.test(n));
36202
+ const exec = names.some((n) => /(^|[_-])(exec|execute|run_command|shell|bash)([_-]|$)/i.test(n));
36203
+ const writes = names.some((n) => /(^|[_-])(create|update|delete|add|write|send|post|set|remove|cart)([_-]|$)/i.test(n));
36204
+ let tier = money || exec ? "R4" : m.allow.destructive ? "R3" : writes ? "R2" : "R0";
36205
+ let note = money ? "can spend money" : exec ? "can run code" : writes ? "can change data" : "reads only";
36206
+ if (m.autonomy === "notify") {
36207
+ tier = "R0";
36208
+ note += ", but notify-only: it cannot act";
36209
+ } else if (m.autonomy === "propose" && tier > "R1")
36210
+ note += ", but every action needs approval";
36211
+ else if (tier === "R4" && m.constraints?.some((k) => k.max !== void 0))
36212
+ note += `, capped (${m.constraints.filter((k) => k.max !== void 0).map((k) => `${k.arg} \u2264 ${k.max}`).join(", ")})`;
36213
+ return { tier, note };
36214
+ }
36215
+ function hasIntent(m) {
36216
+ return Boolean(m.purpose && (m.actions || m.rules || m.preferences || m.substitution || m.upsell || m.approvalTriggers || m.counterparties));
36217
+ }
36218
+ function decideIntent(m, tool, args, ctx = {}) {
36219
+ const v = semanticValues(tool, args);
36220
+ const r = { evaluated: [], preferences: [], flags: [] };
36221
+ const stop = (code, reason) => ({ allow: false, code, reason, rationale: r, values: v });
36222
+ const cls = actionClass(tool).cls;
36223
+ const auto = m.actions?.find((a) => a.cls === cls)?.autonomy;
36224
+ if (auto === "notify" && cls !== "search")
36225
+ return stop("notify-only", `only alerts for ${cls}: tell your user instead`);
36226
+ for (const rule of m.rules ?? []) {
36227
+ if (!(rule.field in v))
36228
+ continue;
36229
+ const x = v[rule.field];
36230
+ const ok = rule.op === "max" ? Number(x) <= Number(rule.value) : rule.op === "min" ? Number(x) >= Number(rule.value) : rule.op === "eq" ? x === rule.value : rule.op === "in" ? rule.value.map(String).includes(String(x)) : !rule.value.map((s) => String(s).toLowerCase()).includes(String(x).toLowerCase());
36231
+ r.evaluated.push({ rule: ruleText(rule), ok });
36232
+ if (!ok)
36233
+ return stop("rule-violated", `${ruleText(rule)} (got ${String(x)})`);
36234
+ }
36235
+ const cp = v["commerce.counterparty"];
36236
+ if (m.counterparties && cp !== void 0 && !m.counterparties.includes(String(cp))) {
36237
+ if (m.approvalTriggers?.includes("new-counterparty"))
36238
+ return stop("approval-needed", `new counterparty ${String(cp)}: ask your user`);
36239
+ return stop("counterparty-not-allowed", `${String(cp)} is not an allowed counterparty`);
36240
+ }
36241
+ const personal = Object.keys(v).filter((k) => k.startsWith("personal."));
36242
+ const dclass = v["enterprise.data_class"] !== void 0 ? String(v["enterprise.data_class"]).toLowerCase() : void 0;
36243
+ if (dclass && dclass !== "public")
36244
+ personal.push(`class.${dclass}`);
36245
+ if (personal.length) {
36246
+ const recipient = String(v["party.recipient"] ?? v["commerce.counterparty"] ?? v["travel.carrier"] ?? v["enterprise.vendor"] ?? ctx.server ?? "the service");
36247
+ const norm = (x) => x.toLowerCase().replace(/^the /, "").trim();
36248
+ for (const f of personal) {
36249
+ const kind = f.startsWith("class.") ? `${f.slice(6)} data` : f.split(".")[1];
36250
+ const key = kind.replace(/ data$/, "");
36251
+ const ok = (m.dataSharing ?? []).some((d) => norm(d.data).includes(key) && (norm(recipient).includes(norm(d.to)) || norm(d.to).includes(norm(recipient))));
36252
+ if (m.dataSharing) {
36253
+ r.evaluated.push({ rule: `share ${kind} only as permitted (to ${recipient})`, ok });
36254
+ if (!ok)
36255
+ return stop("data-not-permitted", `${kind} may not be shared with ${recipient}`);
36256
+ } else
36257
+ r.flags.push(`personal data shared: ${kind} with ${recipient}`);
36258
+ }
36259
+ }
36260
+ const subFor = v["commerce.item.substitute_for"];
36261
+ if (subFor !== void 0 || cls === "substitute") {
36262
+ const s = m.substitution;
36263
+ if (!s?.allowed)
36264
+ return stop("substitution-not-allowed", "substitutions are not allowed");
36265
+ const cat = String(v["commerce.item.category"] ?? "").toLowerCase();
36266
+ if (s.neverFor?.some((c) => c.toLowerCase() === cat))
36267
+ return stop("substitution-not-allowed", `never substitute ${cat}`);
36268
+ const p = Number(v["commerce.item.unit_price"]), ref = Number(v["commerce.item.reference_price"]);
36269
+ if (s.maxPriceChangePct !== void 0 && p > 0 && ref > 0) {
36270
+ const pct = Math.round((p - ref) / ref * 1e3) / 10;
36271
+ const ok = Math.abs(pct) <= s.maxPriceChangePct;
36272
+ r.evaluated.push({ rule: `substitute within ${s.maxPriceChangePct}% of the price (${pct > 0 ? "+" : ""}${pct}%)`, ok });
36273
+ if (!ok)
36274
+ return stop("substitution-not-allowed", `substitute is ${pct > 0 ? "+" : ""}${pct}% in price, above ${s.maxPriceChangePct}%`);
36275
+ }
36276
+ if (m.approvalTriggers?.includes("substitution"))
36277
+ return stop("approval-needed", `substitution for ${String(subFor)}: ask your user`);
36278
+ r.flags.push(`substitution for ${String(subFor ?? "an item")}, within policy`);
36279
+ }
36280
+ if (v["commerce.item.upgrade"] === true || v["travel.upgrade"] === true) {
36281
+ if (m.upsell === "never")
36282
+ return stop("upsell-not-allowed", "upgrades and upsells are not allowed");
36283
+ if (m.upsell === "ask" || m.approvalTriggers?.includes("upsell"))
36284
+ return stop("approval-needed", "this is an upgrade: ask your user first");
36285
+ r.flags.push("upgrade chosen, allowed by the mandate");
36286
+ }
36287
+ const fee = Number(v["travel.fee"] ?? 0);
36288
+ if (fee > 0 && m.approvalTriggers?.includes("fee"))
36289
+ return stop("approval-needed", `there is a fee of ${fee}: ask your user first`);
36290
+ if (v["commerce.item.sponsored"] === true) {
36291
+ if (m.approvalTriggers?.includes("sponsored"))
36292
+ return stop("approval-needed", "this option is sponsored: ask your user first");
36293
+ r.flags.push("sponsored option chosen");
36294
+ }
36295
+ for (const p of m.preferences ?? [])
36296
+ if (p.field in v) {
36297
+ const matched = String(v[p.field]).toLowerCase() === String(p.prefer).toLowerCase();
36298
+ r.preferences.push(matched ? `matches preference: ${p.label ?? `${FIELD_LABEL(p.field)} ${p.prefer}`}` : `differs from preference: wanted ${p.prefer}, chose ${String(v[p.field])}`);
36299
+ if (!matched)
36300
+ r.flags.push(`differs from the stated preference (${FIELD_LABEL(p.field)})`);
36301
+ }
36302
+ if (auto === "propose" && cls !== "search")
36303
+ return stop("approval-needed", `asks before ${cls}: ask your user to approve`);
36304
+ return { allow: true, code: "ok", reason: r.evaluated.length ? `within the mandate: ${r.evaluated.map((e) => e.rule).join("; ")}` : "within the mandate", rationale: r, values: v };
36305
+ }
36306
+ function describeMandate(m) {
36307
+ const out = [];
36308
+ if (m.purpose)
36309
+ out.push(m.purpose + ".");
36310
+ const verbs = { notify: "only alerts you about", propose: "asks you before", act: "does on its own:" };
36311
+ for (const level of ["act", "propose", "notify"]) {
36312
+ const cl = (m.actions ?? []).filter((a) => a.autonomy === level).map((a) => a.cls);
36313
+ if (cl.length)
36314
+ out.push(`It ${verbs[level]} ${cl.join(", ")}.`);
36315
+ }
36316
+ if (m.rules?.length)
36317
+ out.push(`Always: ${m.rules.map(ruleText).join("; ")}.`);
36318
+ if (m.substitution)
36319
+ out.push(m.substitution.allowed ? `Substitutes${m.substitution.maxPriceChangePct !== void 0 ? ` within ${m.substitution.maxPriceChangePct}% of the price` : ""}${m.substitution.neverFor?.length ? `, never for ${m.substitution.neverFor.join(", ")}` : ""}.` : "Never substitutes.");
36320
+ if (m.upsell)
36321
+ out.push(m.upsell === "never" ? "Never upsells." : m.upsell === "ask" ? "Asks before any upgrade." : "May choose upgrades.");
36322
+ if (m.approvalTriggers?.length)
36323
+ out.push(`Asks you first for: ${m.approvalTriggers.join(", ")}.`);
36324
+ if (m.preferences?.length)
36325
+ out.push(`Prefers: ${m.preferences.map((p) => p.label ?? `${FIELD_LABEL(p.field)} ${p.prefer}`).join("; ")}.`);
36326
+ if (m.counterparties?.length)
36327
+ out.push(`Only with: ${m.counterparties.join(", ")}.`);
36328
+ if (m.dataSharing?.length)
36329
+ out.push(`Shares: ${m.dataSharing.map((d) => `${d.data} with ${d.to} only`).join("; ")}.`);
36330
+ if (m.disclosures?.operator)
36331
+ out.push(`Operated by ${m.disclosures.operator}${m.disclosures.incentives ? ` (incentives: ${m.disclosures.incentives})` : ""}.`);
36332
+ return out;
36333
+ }
36334
+ function mandateDigest(m) {
36335
+ const { operatorCountersign: _x, ...rest } = m;
36336
+ return argumentsHash(JSON.parse(JSON.stringify(rest)));
36337
+ }
36338
+ function cosignMandate(m, key, name) {
36339
+ return { ...m, operatorCountersign: signDocument({ role: "operator", name, mandate: mandateDigest(m), at: (/* @__PURE__ */ new Date()).toISOString() }, key) };
36340
+ }
36341
+ function checkOperator(m) {
36342
+ const cs = m.operatorCountersign;
36343
+ if (!cs)
36344
+ return { present: false };
36345
+ const v = verifyDocument(cs);
36346
+ if (!v.valid)
36347
+ return { present: true, valid: false, reason: "operator signature not valid" };
36348
+ if (cs.mandate !== mandateDigest(m))
36349
+ return { present: true, valid: false, reason: "operator signed a different mandate" };
36350
+ return { present: true, valid: true, id: v.kid, name: cs.name };
36351
+ }
36352
+ function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS()) {
36353
+ const r = readRevocations(path), d = mandateDigest(m);
36354
+ if (!r.revoked.some((x) => x.mandate === d))
36355
+ r.revoked.push({ mandate: d, agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} });
36356
+ _mkdir(_dirname(path), { recursive: true });
36357
+ _write(path, JSON.stringify(r, null, 2) + "\n");
36358
+ return r.revoked.find((x) => x.mandate === d);
36359
+ }
36360
+ function revocationOf(m, path = DEFAULT_REVOCATIONS()) {
36361
+ const d = mandateDigest(m);
36362
+ return readRevocations(path).revoked.find((x) => x.mandate === d);
36363
+ }
36364
+ function trustStatement(entries, verified) {
36365
+ const allowed = entries.filter((e) => e.receipt.outcome === "allow" && e.result.status === "ok").length;
36366
+ const blocked = entries.filter((e) => e.receipt.outcome === "deny");
36367
+ const observed = entries.filter((e) => String(e.result.code ?? "").startsWith("observed-")).length;
36368
+ const prefs = entries.flatMap((e) => e.result.rationale?.preferences ?? []);
36369
+ const matched = prefs.filter((p) => p.startsWith("matches")).length;
36370
+ const flags = entries.flatMap((e) => e.result.rationale?.flags ?? []);
36371
+ const sponsored = flags.filter((f) => /sponsored/.test(f)).length, subs = flags.filter((f) => /^substitution/.test(f)).length, personal = flags.filter((f) => /^personal data/.test(f)).length;
36372
+ const byCode = /* @__PURE__ */ new Map();
36373
+ for (const b of blocked) {
36374
+ const c = b.result.code ?? "denied";
36375
+ byCode.set(c, (byCode.get(c) ?? 0) + 1);
36376
+ }
36377
+ const approved = entries.filter((e) => /^approved by /.test(String(e.receipt.reason ?? "").replace(/^\[[^\]]+\] /, ""))).length;
36378
+ const lines = [
36379
+ `${allowed} action(s) within its instructions${approved ? ` (${approved} after your signed approval)` : ""}${observed ? `; ${observed} outside them (observed, not blocked)` : "; none outside them"}.`,
36380
+ blocked.length ? `${blocked.length} attempt(s) stopped before reaching the service: ${[...byCode].map(([c, n]) => `${n} ${c}`).join(", ")}.` : "No attempts needed stopping.",
36381
+ prefs.length ? `Preferences: matched in ${matched} of ${prefs.length} choice(s).` : "No preference-relevant choices.",
36382
+ sponsored || subs || personal ? `Disclosed: ${[sponsored ? `${sponsored} sponsored option(s)` : "", subs ? `${subs} substitution(s)` : "", personal ? `${personal} personal-data share(s)` : ""].filter(Boolean).join(", ")}.` : "Nothing sponsored, substituted or shared that needed disclosure.",
36383
+ `Receipts: ${entries.length}, ${verified ? "all signed and verified" : "NOT verified"}.`
36384
+ ];
36385
+ return { lines, facts: { allowed, approved, blocked: blocked.length, observed, preferences: prefs.length, matched, sponsored, substitutions: subs } };
36386
+ }
36387
+ function approvalRequestId(m, tool, args) {
36388
+ return "apr_" + argumentsHash({ mandate: mandateDigest(m), tool, args: argumentsHash(args) }).replace(/^sha256:/, "").slice(0, 16);
36389
+ }
36390
+ function approveAction(m, requestId, ownerKey, minutes = 60, path = DEFAULT_APPROVALS()) {
36391
+ if (ownerKey.kid !== m.owner.id)
36392
+ throw new Error("Only the mandate's owner can approve its actions.");
36393
+ const a = readApprovals(path);
36394
+ const signed = signDocument({ approval: requestId, mandate: mandateDigest(m), approvedBy: m.owner.name ?? m.owner.id, expires: new Date(Date.now() + minutes * 6e4).toISOString() }, ownerKey);
36395
+ a.approvals.push(signed);
36396
+ _mkdir(_dirname(path), { recursive: true });
36397
+ _write(path, JSON.stringify(a, null, 2) + "\n");
36398
+ return signed;
36399
+ }
36400
+ function consumeApproval(m, requestId, path = DEFAULT_APPROVALS()) {
36401
+ const a = readApprovals(path);
36402
+ if (a.used.includes(requestId))
36403
+ return { ok: false };
36404
+ for (const x of a.approvals) {
36405
+ if (x.approval !== requestId || x.mandate !== mandateDigest(m) || x.expires < (/* @__PURE__ */ new Date()).toISOString())
36406
+ continue;
36407
+ const v = verifyDocument(x);
36408
+ if (!v.valid || v.kid !== m.owner.id)
36409
+ continue;
36410
+ a.used.push(requestId);
36411
+ _write(path, JSON.stringify(a, null, 2) + "\n");
36412
+ return { ok: true, by: x.approvedBy, at: (/* @__PURE__ */ new Date()).toISOString() };
36413
+ }
36414
+ return { ok: false };
36415
+ }
36416
+ var FIELD_LABEL, ruleText, DEFAULT_REVOCATIONS, readRevocations, DEFAULT_APPROVALS, readApprovals;
36417
+ var init_agentid = __esm({
36418
+ "packages/testkit-core/dist/agentid.js"() {
36419
+ "use strict";
36420
+ init_vocab();
36421
+ init_dist();
36422
+ init_safe();
36423
+ init_receipts();
36424
+ FIELD_LABEL = (f) => VOCABULARIES[f.split(".")[0]]?.fields.find((x) => x.path === f)?.description.toLowerCase() ?? f;
36425
+ 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)})`);
36426
+ DEFAULT_REVOCATIONS = () => _join(_home(), ".saktum", "revocations.json");
36427
+ readRevocations = (path) => {
36428
+ try {
36429
+ return _exists(path) ? JSON.parse(_read(path, "utf8")) : { revoked: [] };
36430
+ } catch {
36431
+ return { revoked: [] };
36432
+ }
36433
+ };
36434
+ DEFAULT_APPROVALS = () => _join(_home(), ".saktum", "approvals.json");
36435
+ readApprovals = (path) => {
36436
+ try {
36437
+ return _exists(path) ? JSON.parse(_read(path, "utf8")) : { approvals: [], used: [] };
36438
+ } catch {
36439
+ return { approvals: [], used: [] };
36440
+ }
36441
+ };
36442
+ }
36443
+ });
36444
+
35492
36445
  // packages/testkit-core/dist/interop.js
35493
36446
  import { createHash as createHash2, sign as edSign, verify as edVerify } from "node:crypto";
35494
36447
  function receiptsToOtlp(entries, o) {
@@ -35641,7 +36594,401 @@ var init_watch = __esm({
35641
36594
  }
35642
36595
  });
35643
36596
 
36597
+ // packages/testkit-core/dist/market.js
36598
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
36599
+ import { dirname as dirname2 } from "node:path";
36600
+ function organisationRoot(o, key) {
36601
+ const c = { credentialFormat: "0.1", type: "organisation", subject: { id: key.kid, name: o.name }, issuer: { id: key.kid, name: o.name, ...o.domain ? { domain: o.domain } : {} }, issuedAt: nowIso(), expires: o.expires };
36602
+ return signDocument({ ...c, id: short("cred_", c) }, key);
36603
+ }
36604
+ function issueCredential(issuerCred, issuerKey, s) {
36605
+ if (issuerCred.subject.id !== issuerKey.kid)
36606
+ throw new Error("The signing key does not belong to the issuer's credential.");
36607
+ if (issuerCred.type === "agent")
36608
+ throw new Error("Agents cannot issue credentials.");
36609
+ const chain = [...issuerCred.chain ?? [], { ...issuerCred, chain: void 0 }].map((c2) => JSON.parse(JSON.stringify(c2)));
36610
+ const c = { credentialFormat: "0.1", type: s.type, 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 };
36611
+ return { ...signDocument({ ...c, id: short("cred_", c) }, issuerKey), chain };
36612
+ }
36613
+ function verifyChain(c, o = {}) {
36614
+ const today = o.today ?? nowIso();
36615
+ const links = [...c.chain ?? [], { ...c, chain: void 0 }];
36616
+ const path = [];
36617
+ for (let i = 0; i < links.length; i++) {
36618
+ const l = links[i];
36619
+ const v = verifyDocument(JSON.parse(JSON.stringify({ ...l, chain: void 0 })));
36620
+ if (!v.valid)
36621
+ return { valid: false, path, reason: `signature not valid on ${l.subject.name}'s credential` };
36622
+ if (v.kid !== l.issuer.id)
36623
+ return { valid: false, path, reason: `${l.subject.name}'s credential was not signed by its stated issuer` };
36624
+ if (l.expires < today.slice(0, l.expires.length))
36625
+ return { valid: false, path, reason: `${l.subject.name}'s credential expired on ${l.expires}` };
36626
+ if (o.revoked?.includes(l.id))
36627
+ return { valid: false, path, reason: `${l.subject.name}'s credential was revoked` };
36628
+ if (i === 0 && (l.type !== "organisation" || l.issuer.id !== l.subject.id))
36629
+ return { valid: false, path, reason: "the chain does not start at an organisation" };
36630
+ if (i > 0 && l.issuer.id !== links[i - 1].subject.id)
36631
+ return { valid: false, path, reason: `${l.subject.name}'s issuer is not the previous link in the chain` };
36632
+ path.push(`${l.subject.name}${l.subject.role ? ` (${l.subject.role})` : ""}`);
36633
+ }
36634
+ return { valid: true, path, organisation: links[0].subject.name + (links[0].issuer.domain ? ` (${links[0].issuer.domain})` : "") };
36635
+ }
36636
+ function findOrphans(creds, o = {}) {
36637
+ return creds.filter((c) => c.type === "agent").map((c) => ({ agent: c.subject.name, id: c.subject.id, ...verifyChain(c, o) })).filter((x) => !x.valid);
36638
+ }
36639
+ function buildManifest(o, key) {
36640
+ const caps = o.tools.map((t) => {
36641
+ const b = bindingsFor(t).bindings;
36642
+ return { tool: t.name, action: actionClass(t).cls, fields: [...new Set(Object.values(b))], description: (t.description ?? "").split(/(?<=[.!?])\s/)[0].slice(0, 160) };
36643
+ });
36644
+ const domains = [...new Set(caps.flatMap((c) => c.fields.map((f) => f.split(".")[0])))].filter((d) => d !== "personal" && d !== "party");
36645
+ const intents = [...new Set(caps.flatMap((c) => (domains.length ? domains : ["general"]).map((d) => `${c.action}:${d}`)))];
36646
+ const m = {
36647
+ manifestFormat: "0.1",
36648
+ publisher: { id: key.kid, ...o.publisher },
36649
+ server: o.server,
36650
+ categories: o.categories ?? domains.map((d) => CAT[d] ?? d),
36651
+ intents,
36652
+ capabilities: caps,
36653
+ rates: o.rates,
36654
+ ...o.quality ? { quality: o.quality } : {},
36655
+ ...o.documentation ? { documentation: o.documentation } : {},
36656
+ issuedAt: nowIso()
36657
+ };
36658
+ return signDocument({ ...m, id: short("man_", { ...m, issuedAt: void 0 }) }, key);
36659
+ }
36660
+ function searchCatalogue(entries, query, o = {}) {
36661
+ const q = query.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2);
36662
+ return entries.filter((m) => verifyDocument(m).valid && (!o.maxRisk || !m.quality?.riskTier || m.quality.riskTier <= o.maxRisk)).map((m) => {
36663
+ let score2 = 0;
36664
+ const why = [];
36665
+ for (const it of m.intents) {
36666
+ const [a, d] = it.split(":");
36667
+ const hit = q.filter((w) => (WORDS[a] ?? []).includes(w) || w === d || d === "commerce" && ["groceries", "grocery", "shop", "shopping", "buy"].includes(w) || d === "travel" && ["flight", "flights", "trip", "travel"].includes(w));
36668
+ if (hit.length) {
36669
+ score2 += 2 * hit.length;
36670
+ why.push(it);
36671
+ }
36672
+ }
36673
+ const text2 = `${m.server.name} ${m.categories.join(" ")} ${m.capabilities.map((c) => `${c.tool} ${c.description}`).join(" ")}`.toLowerCase();
36674
+ for (const w of q)
36675
+ if (text2.includes(w))
36676
+ score2 += 1;
36677
+ return { manifest: m, score: score2, matched: [...new Set(why)] };
36678
+ }).filter((r) => r.score > 0).sort((a, b) => b.score - a.score);
36679
+ }
36680
+ function draftAgreement(o, providerKey) {
36681
+ if (providerKey.kid !== o.manifest.publisher.id)
36682
+ throw new Error("Only the manifest's publisher can offer an agreement for it.");
36683
+ const a = {
36684
+ agreementFormat: "0.1",
36685
+ template: "saktum-default-0.1",
36686
+ purpose: o.purpose,
36687
+ provider: { id: providerKey.kid, name: o.manifest.publisher.name, manifest: o.manifest.id },
36688
+ invoker: o.invoker,
36689
+ scope: { ...o.tools?.length ? { tools: o.tools } : {} },
36690
+ rates: o.rates ?? o.manifest.rates,
36691
+ ...o.tokensPerMonth ? { limits: { tokensPerMonth: o.tokensPerMonth } } : {},
36692
+ terms: DEFAULT_TERMS,
36693
+ ...o.specificTerms?.length ? { specificTerms: o.specificTerms } : {},
36694
+ ...o.dataTerms ? { dataTerms: o.dataTerms } : {},
36695
+ ...o.disputeContact ? { disputeContact: o.disputeContact } : {},
36696
+ validFrom: nowIso().slice(0, 10),
36697
+ validUntil: o.validUntil
36698
+ };
36699
+ return signDocument({ ...a, id: short("agr_", a) }, providerKey);
36700
+ }
36701
+ function acceptAgreement(a, invokerKey) {
36702
+ if (invokerKey.kid !== a.invoker.id)
36703
+ throw new Error("Only the named invoker can accept this agreement.");
36704
+ return { ...a, countersignature: signDocument({ by: invokerKey.kid, agreement: argumentsHash(body(a)) }, invokerKey) };
36705
+ }
36706
+ function verifyAgreement(a, today = nowIso().slice(0, 10)) {
36707
+ const { countersignature: cs, ...providerPart } = a;
36708
+ const p = verifyDocument(providerPart);
36709
+ if (!p.valid || p.kid !== a.provider.id)
36710
+ return { valid: false, reason: "the provider's signature is not valid" };
36711
+ if (!cs)
36712
+ return { valid: false, reason: "not yet accepted by the invoker" };
36713
+ const c = verifyDocument(cs);
36714
+ if (!c.valid || c.kid !== a.invoker.id || cs.agreement !== argumentsHash(body(a)))
36715
+ return { valid: false, reason: "the invoker's countersignature is not valid for this agreement" };
36716
+ if (a.validUntil < today)
36717
+ return { valid: false, reason: `expired on ${a.validUntil}` };
36718
+ return { valid: true };
36719
+ }
36720
+ function walletBalance(path, account) {
36721
+ return readWallet(path).entries.reduce((b, e) => b + (e.to === account ? e.tokens : 0) - (e.from === account ? e.tokens : 0), 0);
36722
+ }
36723
+ function topUp(path, account, tokens, ref = "top-up") {
36724
+ const w = readWallet(path);
36725
+ w.entries.push({ at: nowIso(), from: PREPAID, to: account, tokens, ref });
36726
+ writeWallet(path, w);
36727
+ return walletBalance(path, account);
36728
+ }
36729
+ function chargeCall(path, a, tool, ref) {
36730
+ const cost = tokensFor(a, tool), bal = walletBalance(path, a.invoker.id);
36731
+ if (bal < cost)
36732
+ return { ok: false, tokens: cost, balance: bal };
36733
+ const w = readWallet(path);
36734
+ w.entries.push({ at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref });
36735
+ writeWallet(path, w);
36736
+ return { ok: true, tokens: cost, balance: bal - cost };
36737
+ }
36738
+ function usageStatement(entries, a, key) {
36739
+ const metered = entries.filter((e) => e.result.metering?.agreement === a.id);
36740
+ const byTool = /* @__PURE__ */ new Map();
36741
+ for (const e of metered) {
36742
+ const t = e.receipt.envelope.tool;
36743
+ const x = byTool.get(t) ?? { calls: 0, tokens: 0 };
36744
+ x.calls++;
36745
+ x.tokens += e.result.metering.tokens;
36746
+ byTool.set(t, x);
36747
+ }
36748
+ const s = {
36749
+ statementFormat: "0.1",
36750
+ agreement: a.id,
36751
+ provider: a.provider.name,
36752
+ invoker: a.invoker.name,
36753
+ from: metered[0]?.receipt.issuedAt ?? null,
36754
+ to: metered[metered.length - 1]?.receipt.issuedAt ?? null,
36755
+ lines: [...byTool].map(([tool, v]) => ({ tool, calls: v.calls, tokens: v.tokens })),
36756
+ totalTokens: metered.reduce((n, e) => n + e.result.metering.tokens, 0),
36757
+ receipts: metered.map((e) => e.entryHash),
36758
+ producedAt: nowIso()
36759
+ };
36760
+ return key ? signDocument(s, key) : s;
36761
+ }
36762
+ function kpis(entries, f = {}) {
36763
+ const xs = entries.filter((e) => (!f.tool || e.receipt.envelope.tool === f.tool) && (!f.agent || e.receipt.envelope.caller.agent === f.agent) && (!f.since || e.receipt.issuedAt >= f.since));
36764
+ const lat = xs.map((e) => e.result.latencyMs).filter((n) => typeof n === "number").sort((a, b) => a - b);
36765
+ const pct = (p) => lat.length ? lat[Math.min(lat.length - 1, Math.floor(p / 100 * lat.length))] : null;
36766
+ const by = (k) => Object.entries(xs.reduce((m, e) => {
36767
+ const key = k(e);
36768
+ m[key] = (m[key] ?? 0) + 1;
36769
+ return m;
36770
+ }, {})).sort((a, b) => b[1] - a[1]);
36771
+ return {
36772
+ calls: xs.length,
36773
+ allowed: xs.filter((e) => e.receipt.outcome === "allow").length,
36774
+ blocked: xs.filter((e) => e.receipt.outcome === "deny").length,
36775
+ approvals: xs.filter((e) => /approved by/.test(String(e.receipt.reason ?? ""))).length,
36776
+ tokens: xs.reduce((n, e) => n + (e.result.metering?.tokens ?? 0), 0),
36777
+ latencyP50: pct(50),
36778
+ latencyP95: pct(95),
36779
+ byOutcome: by((e) => e.result.code ?? e.receipt.outcome),
36780
+ byTool: by((e) => e.receipt.envelope.tool)
36781
+ };
36782
+ }
36783
+ var short, nowIso, body, CAT, WORDS, DEFAULT_TERMS, tokensFor, readWallet, writeWallet, PREPAID;
36784
+ var init_market = __esm({
36785
+ "packages/testkit-core/dist/market.js"() {
36786
+ "use strict";
36787
+ init_dist();
36788
+ init_vocab();
36789
+ init_receipts();
36790
+ short = (prefix, x) => prefix + argumentsHash(JSON.parse(JSON.stringify(x))).replace(/^sha256:/, "").slice(0, 16);
36791
+ nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
36792
+ body = (d) => {
36793
+ const { signature: _s, countersignature: _c, ...rest } = d;
36794
+ return rest;
36795
+ };
36796
+ CAT = { commerce: "Commerce and shopping", travel: "Travel", personal: "Personal data", enterprise: "Business operations" };
36797
+ WORDS = {
36798
+ search: ["find", "search", "look", "browse", "deal", "deals"],
36799
+ cart: ["buy", "shop", "shopping", "groceries", "grocery", "cart", "order"],
36800
+ pay: ["pay", "payment", "checkout", "invoice", "purchase"],
36801
+ book: ["book", "booking", "reserve", "flight", "flights", "trip", "travel"],
36802
+ change: ["change", "seat", "upgrade", "modify"],
36803
+ communicate: ["send", "share", "email", "report"],
36804
+ cancel: ["cancel", "refund"]
36805
+ };
36806
+ DEFAULT_TERMS = [
36807
+ "The provider operates the service as described in its signed manifest; material changes to tools require a new manifest.",
36808
+ "The invoker's agents act only within their mandates; the provider may refuse calls outside the agreed scope.",
36809
+ "Each call is metered in prepaid tokens at the agreed rates; settlement in money happens outside Saktum.",
36810
+ "Both parties keep signed receipts; either may present them as evidence in a dispute.",
36811
+ "Personal and classified data are shared only as the invoker's mandates permit.",
36812
+ "Either party may end the agreement with notice; receipts and usage statements remain valid evidence."
36813
+ ];
36814
+ tokensFor = (a, tool) => a.rates.perTool?.[tool] ?? a.rates.perCall;
36815
+ readWallet = (path) => {
36816
+ try {
36817
+ return existsSync3(path) ? JSON.parse(readFileSync5(path, "utf8")) : { entries: [] };
36818
+ } catch {
36819
+ return { entries: [] };
36820
+ }
36821
+ };
36822
+ writeWallet = (path, w) => {
36823
+ mkdirSync2(dirname2(path), { recursive: true });
36824
+ writeFileSync2(path, JSON.stringify(w, null, 2) + "\n");
36825
+ };
36826
+ PREPAID = "saktum:prepaid";
36827
+ }
36828
+ });
36829
+
35644
36830
  // packages/testkit-core/dist/index.js
36831
+ var dist_exports = {};
36832
+ __export(dist_exports, {
36833
+ ANALYSER_NEEDS: () => ANALYSER_NEEDS,
36834
+ AUTH_NEEDS: () => AUTH_NEEDS,
36835
+ CAPABILITY_LABELS: () => CAPABILITY_LABELS,
36836
+ CRITICAL_CAP: () => CRITICAL_CAP,
36837
+ DEFAULT_APPROVALS: () => DEFAULT_APPROVALS,
36838
+ DEFAULT_LEDGER_URL: () => DEFAULT_LEDGER_URL,
36839
+ DEFAULT_REVOCATIONS: () => DEFAULT_REVOCATIONS,
36840
+ DEFAULT_TERMS: () => DEFAULT_TERMS,
36841
+ EMBEDDED_CONTRACTS: () => EMBEDDED_CONTRACTS,
36842
+ EMBEDDED_PACKS: () => EMBEDDED_PACKS,
36843
+ ENGINE_VERSION: () => ENGINE_VERSION,
36844
+ FUNCTIONAL_LIMITS: () => FUNCTIONAL_LIMITS,
36845
+ GENESIS: () => GENESIS,
36846
+ INVISIBLE: () => INVISIBLE,
36847
+ KNOWN_FIELDS: () => KNOWN_FIELDS,
36848
+ LEAKAGE_NEEDS: () => LEAKAGE_NEEDS,
36849
+ LEAK_PATTERNS: () => LEAK_PATTERNS,
36850
+ LOAD: () => LOAD,
36851
+ MIN_GRADED_CHECKS: () => MIN_GRADED_CHECKS,
36852
+ PERF_NEEDS: () => PERF_NEEDS,
36853
+ PERF_THRESHOLDS: () => PERF_THRESHOLDS,
36854
+ PREPAID: () => PREPAID,
36855
+ PackError: () => PackError,
36856
+ READINESS: () => READINESS,
36857
+ RECEIPTS_GENESIS: () => RECEIPTS_GENESIS,
36858
+ RISK_LABELS: () => RISK_LABELS,
36859
+ ROI_DEFAULTS: () => ROI_DEFAULTS,
36860
+ SECRET_PATTERNS: () => SECRET_PATTERNS,
36861
+ SEVERITY_WEIGHT: () => SEVERITY_WEIGHT,
36862
+ SIGN_IN_HINT: () => SIGN_IN_HINT,
36863
+ TIER_REQUIREMENT: () => TIER_REQUIREMENT,
36864
+ TRUST_WEIGHTS: () => TRUST_WEIGHTS,
36865
+ UNKNOWN_TOOL: () => UNKNOWN_TOOL,
36866
+ VOCABULARIES: () => VOCABULARIES,
36867
+ acceptAgreement: () => acceptAgreement,
36868
+ actionClass: () => actionClass,
36869
+ agentRiskTier: () => agentRiskTier,
36870
+ allowlistFromLedger: () => allowlistFromLedger,
36871
+ analyseSetup: () => analyseSetup,
36872
+ analysers: () => analysers,
36873
+ appendTestCase: () => appendTestCase,
36874
+ appendToLedger: () => appendToLedger,
36875
+ approvalRequestId: () => approvalRequestId,
36876
+ approveAction: () => approveAction,
36877
+ argumentsHash: () => argumentsHash,
36878
+ attestationToCredential: () => attestationToCredential,
36879
+ authAnalysers: () => authAnalysers,
36880
+ bindingsFor: () => bindingsFor,
36881
+ buildAllowlist: () => buildAllowlist,
36882
+ buildAttestation: () => buildAttestation,
36883
+ buildFleet: () => buildFleet,
36884
+ buildManifest: () => buildManifest,
36885
+ capabilityProfile: () => capabilityProfile,
36886
+ chainEntry: () => chainEntry,
36887
+ chargeCall: () => chargeCall,
36888
+ checkAttestation: () => checkAttestation,
36889
+ checkMandate: () => checkMandate,
36890
+ checkNeedsSession: () => checkNeedsSession,
36891
+ checkOperator: () => checkOperator,
36892
+ clientCompatibility: () => clientCompatibility,
36893
+ compileContract: () => compileContract,
36894
+ compileUntrustedSchema: () => compileUntrustedSchema,
36895
+ compileUntrustedSchemaValidator: () => compileUntrustedSchemaValidator,
36896
+ configLocations: () => configLocations,
36897
+ consumeApproval: () => consumeApproval,
36898
+ contextCost: () => contextCost,
36899
+ contractText: () => contractText,
36900
+ contractsDir: () => contractsDir,
36901
+ cosignMandate: () => cosignMandate,
36902
+ createMandate: () => createMandate,
36903
+ decideCall: () => decideCall,
36904
+ decideIntent: () => decideIntent,
36905
+ describeMandate: () => describeMandate,
36906
+ diffLocks: () => diffLocks,
36907
+ docsFor: () => docsFor,
36908
+ draftAgreement: () => draftAgreement,
36909
+ escapeHtml: () => escapeHtml,
36910
+ evaluatePolicy: () => evaluatePolicy,
36911
+ exampleFor: () => exampleFor,
36912
+ extractJson: () => extractJson,
36913
+ findInLedger: () => findInLedger,
36914
+ findOrphans: () => findOrphans,
36915
+ fleetHtml: () => fleetHtml,
36916
+ gradeFor: () => gradeFor,
36917
+ hasIntent: () => hasIntent,
36918
+ invalidArgProblems: () => invalidArgProblems,
36919
+ invalidArgsFor: () => invalidArgsFor,
36920
+ issueCredential: () => issueCredential,
36921
+ kpis: () => kpis,
36922
+ leakageAnalysers: () => leakageAnalysers,
36923
+ lintPaths: () => lintPaths,
36924
+ lintSarif: () => lintSarif,
36925
+ lintSource: () => lintSource,
36926
+ loadEmbeddedPacks: () => loadEmbeddedPacks,
36927
+ loadPack: () => loadPack,
36928
+ loadPackDir: () => loadPackDir,
36929
+ loadPackText: () => loadPackText,
36930
+ mandateDecision: () => mandateDecision,
36931
+ mandateDigest: () => mandateDigest,
36932
+ maxDepth: () => maxDepth,
36933
+ measureLoad: () => measureLoad,
36934
+ needsOf: () => needsOf,
36935
+ organisationRoot: () => organisationRoot,
36936
+ outcomeText: () => outcomeText,
36937
+ parseChallenge: () => parseChallenge,
36938
+ parseClientConfig: () => parseClientConfig,
36939
+ parseLedger: () => parseLedger,
36940
+ parsePolicy: () => parsePolicy,
36941
+ parseReceiptLog: () => parseReceiptLog,
36942
+ parseTestCases: () => parseTestCases,
36943
+ percentile: () => percentile,
36944
+ perfAnalysers: () => perfAnalysers,
36945
+ readinessFor: () => readinessFor,
36946
+ receiptsToOtlp: () => receiptsToOtlp,
36947
+ redactCommand: () => redactCommand,
36948
+ redactUrl: () => redactUrl,
36949
+ renderFix: () => renderFix,
36950
+ renderFleet: () => renderFleet,
36951
+ renderSetup: () => renderSetup,
36952
+ renderVerdict: () => renderVerdict,
36953
+ resultProblems: () => resultProblems,
36954
+ revocationOf: () => revocationOf,
36955
+ revokeMandate: () => revokeMandate,
36956
+ riskTier: () => riskTier,
36957
+ roiEstimate: () => roiEstimate,
36958
+ runCheck: () => runCheck,
36959
+ runFunctional: () => runFunctional,
36960
+ runTestCases: () => runTestCases,
36961
+ runTrustCheck: () => runTrustCheck,
36962
+ sanitizeText: () => sanitizeText,
36963
+ schemaDialect: () => schemaDialect,
36964
+ score: () => score,
36965
+ searchCatalogue: () => searchCatalogue,
36966
+ semanticValues: () => semanticValues,
36967
+ signCredentialJwt: () => signCredentialJwt,
36968
+ signReceipt: () => signReceipt,
36969
+ sourceFiles: () => sourceFiles,
36970
+ splitCommand: () => splitCommand,
36971
+ subjectFromResult: () => subjectFromResult,
36972
+ subsetMatch: () => subsetMatch,
36973
+ suggestAnnotations: () => suggestAnnotations,
36974
+ summarise: () => summarise,
36975
+ summariseReceipts: () => summariseReceipts,
36976
+ tokensFor: () => tokensFor,
36977
+ toolsContextCost: () => contextCost,
36978
+ toolsLock: () => toolsLock,
36979
+ topUp: () => topUp,
36980
+ trustStatement: () => trustStatement,
36981
+ usageStatement: () => usageStatement,
36982
+ verifyAgreement: () => verifyAgreement,
36983
+ verifyChain: () => verifyChain,
36984
+ verifyCredentialJwt: () => verifyCredentialJwt,
36985
+ verifyLedger: () => verifyLedger,
36986
+ verifyReceipt: () => verifyReceipt,
36987
+ verifyReceiptLog: () => verifyReceiptLog,
36988
+ walletBalance: () => walletBalance,
36989
+ watchAllowlist: () => watchAllowlist,
36990
+ wellKnownUrls: () => wellKnownUrls
36991
+ });
35645
36992
  var init_dist4 = __esm({
35646
36993
  "packages/testkit-core/dist/index.js"() {
35647
36994
  "use strict";
@@ -35672,6 +37019,9 @@ var init_dist4 = __esm({
35672
37019
  init_receipts();
35673
37020
  init_interop();
35674
37021
  init_watch();
37022
+ init_risk();
37023
+ init_vocab();
37024
+ init_market();
35675
37025
  }
35676
37026
  });
35677
37027
 
@@ -35694,38 +37044,55 @@ function renderServerPassport(r, tools, o = {}) {
35694
37044
  const req = (t.inputSchema?.required ?? []).join(", ");
35695
37045
  return `<tr><td><code>${esc2(t.name)}</code><br><small>${esc2((t.description ?? "").split(/(?<=[.!?])\s/)[0].slice(0, 140))}</small></td><td>${esc2(effect(t))}</td><td>${t.outputSchema ? "yes" : "no"}</td><td>${esc2(req || "none")}</td></tr>`;
35696
37046
  }).join("");
35697
- const body = `<div class="card"><div class="top"><div class="seal" style="background:${GRADE_COLOUR[g] ?? "#757575"}">${esc2(g)}</div>
37047
+ const body2 = `<div class="card"><div class="top"><div class="seal" style="background:${GRADE_COLOUR[g] ?? "#757575"}">${esc2(g)}</div>
35698
37048
  <div><small>MCP SERVER PASSPORT</small><h1>${esc2(name)} ${esc2(version2)}</h1><div class="muted">${esc2(r.target.transport)} \xB7 protocol ${esc2(r.target.protocolVersion ?? "unknown")} \xB7 ${esc2(String(r.target.toolCount ?? tools.length))} tools</div></div></div>
35699
- <div class="chips">${chip("Trust", r.grade, GRADE_COLOUR[g])}${chip("Agent readiness", r.readiness?.grade, GRADE_COLOUR[r.readiness?.grade ?? ""])}${chip("Context", `${(r.readiness?.contextTokens ?? 0).toLocaleString("en-US")} tokens/turn`)}${chip("Assurance", r.assuranceLevel ?? "L1")}${o.ledgerEntry ? chip("Ledger entry", `#${o.ledgerEntry}`) : ""}</div></div>
37049
+ <div class="chips">${chip("Trust", r.grade, GRADE_COLOUR[g])}${chip("Agent readiness", r.readiness?.grade, GRADE_COLOUR[r.readiness?.grade ?? ""])}${chip("Context", `${(r.readiness?.contextTokens ?? 0).toLocaleString("en-US")} tokens/turn`)}${r.riskTier ? chip("Risk", `${r.riskTier.tier} \xB7 ${r.riskTier.label}`, r.riskTier.tier >= "R3" ? "#b7791f" : void 0) : ""}${chip("Assurance", r.assuranceLevel ?? "L1")}${o.ledgerEntry ? chip("Ledger entry", `#${o.ledgerEntry}`) : ""}</div></div>
35700
37050
  <div class="card"><h2>Maturity</h2>${levelBar(lvl, lvl === 4 ? "L5 also needs supply-chain evidence (provenance, no install scripts)" : void 0)}</div>
37051
+ ${r.riskTier ? `<div class="card"><h2>Risk tier</h2><p><b>${esc2(r.riskTier.tier)}: ${esc2(r.riskTier.label)}.</b> ${esc2(r.riskTier.reasons.join("; "))}.</p><p class="muted">Proportionate requirement: ${esc2(r.riskTier.requirement)}.</p></div>` : ""}
35701
37052
  <div class="card"><h2>What it can do</h2>${caps.length ? `<div class="chips">${caps.map((c) => chip(c.basis, c.label)).join("")}</div>` : `<p class="muted">No notable capabilities inferred.</p>`}${r.capabilities?.lethalTrifecta ? `<p><b>Note:</b> combines private data, untrusted content and an outbound channel.</p>` : ""}</div>
35702
37053
  <div class="card"><h2>Interface</h2>${tools.length ? `<div class="wrap"><table><tr><th>Tool</th><th>Effect</th><th>Output schema</th><th>Required inputs</th></tr>${rows}</table></div>${tools.length > 60 ? `<p class="muted">First 60 of ${tools.length} tools.</p>` : ""}` : `<p class="muted">Tool list not included.</p>`}</div>
35703
37054
  <div class="card"><h2>Verify this passport</h2><p>Generated by Saktum Check ${esc2(r.tool.version)} on ${esc2(r.run.startedAt.slice(0, 10))} from a signed result${r.signature?.kid ? ` (signer <code>${esc2(r.signature.kid)}</code>)` : ""}; tool fingerprint <code>${esc2(r.target.toolsFingerprint ?? "-")}</code>. Check it yourself: <code>npx saktum verify saktum-report.json</code>${o.ledgerEntry ? ` and <code>npx saktum ledger find "${esc2(name)}"</code>` : ""}.</p><p class="muted">Self-tested (L1) unless stated otherwise. A passport describes these exact tools at that time; any tool change needs a new one.</p></div>`;
35704
- return page(`${name}: MCP Server Passport`, body);
35705
- }
35706
- function renderAgentPassport(m, valid, receipts) {
37055
+ return page(`${name}: MCP Server Passport`, body2);
37056
+ }
37057
+ function renderAgentPassport(m, valid, receipts, tier, plain, extra = {}) {
37058
+ const AUTO = { notify: "Notify only: it alerts, never acts", propose: "Propose: it suggests, you approve", act: "Act: within the limits below" };
37059
+ const perms = [
37060
+ ["Autonomy", AUTO[m.autonomy ?? "act"] ?? "Act"],
37061
+ ...(m.constraints ?? []).map((k) => [`${k.tool}.${k.arg}`, k.max !== void 0 ? `at most ${k.max}` : `only ${(k.oneOf ?? []).join(", ")}`]),
37062
+ ...m.approveAbove ? [["Approval", `ask above ${m.approveAbove.arg} ${m.approveAbove.value}`]] : [],
37063
+ ...m.limits?.callsPerDay !== void 0 ? [["Daily actions", `at most ${m.limits.callsPerDay}`]] : [],
37064
+ ...m.limits?.totalPerDay ? [["Daily total", `${m.limits.totalPerDay.arg} at most ${m.limits.totalPerDay.max}`]] : [],
37065
+ ["Delegation", m.delegation ? "may hand work to other agents" : "may not hand work to other agents"],
37066
+ ...m.disclosures?.operator ? [["Operated by", m.disclosures.operator]] : [],
37067
+ ...m.disclosures?.incentives ? [["Incentives", m.disclosures.incentives]] : [],
37068
+ ...m.disclosures?.dataUse ? [["Data use", m.disclosures.dataUse]] : []
37069
+ ].map(([k, v]) => `<tr><td><b>${esc2(k)}</b></td><td>${esc2(v)}</td></tr>`).join("");
35707
37070
  const s = receipts?.summary;
35708
37071
  const steps = (receipts?.timeline ?? []).slice(0, 80).map((t) => `<span class="step ${t.outcome === "deny" ? "deny" : t.status === "ok" ? "ok" : "err"}${t.repeated ? " rep" : ""}" title="${esc2(t.outcome)} \xB7 ${esc2(t.status)}">${t.outcome === "deny" ? "\u26D4" : t.status === "ok" ? "\u2713" : "!"} ${esc2(t.tool)}</span>`).join('<span class="muted">\u2192</span>');
35709
- const body = `<div class="card"><div class="top"><div class="seal" style="background:${valid.ok ? "#5a3fc0" : "#c62828"}">AI</div>
37072
+ const body2 = `<div class="card"><div class="top"><div class="seal" style="background:${valid.ok ? "#5a3fc0" : "#c62828"}">AI</div>
35710
37073
  <div><small>AGENT PASSPORT</small><h1>${esc2(m.agent.name)}</h1><div class="muted">acts for ${esc2(m.owner.name ?? m.owner.id)}${m.purpose ? ` \xB7 ${esc2(m.purpose)}` : ""}</div></div></div>
35711
- <div class="chips">${chip("Mandate", valid.ok ? "valid" : "not valid", valid.ok ? "#2e7d32" : "#c62828")}${chip("Expires", m.expires)}${chip("Destructive actions", m.allow.destructive ? "allowed" : "not allowed")}${s ? chip("Receipts", receipts.verified ? "verified" : "DO NOT verify", receipts.verified ? "#2e7d32" : "#c62828") : ""}</div>${valid.ok ? "" : `<p><b>${esc2(valid.reason)}</b></p>`}</div>
37074
+ <div class="chips">${chip("Mandate", valid.ok ? "valid" : "not valid", valid.ok ? "#2e7d32" : "#c62828")}${chip("Expires", m.expires)}${chip("Destructive actions", m.allow.destructive ? "allowed" : "not allowed")}${tier ? chip("Risk", `${tier.tier}`, tier.tier === "R4" ? "#b7791f" : void 0) : ""}${s ? chip("Receipts", receipts.verified ? "verified" : "DO NOT verify", receipts.verified ? "#2e7d32" : "#c62828") : ""}</div>${valid.ok ? "" : `<p><b>${esc2(valid.reason)}</b></p>`}</div>
37075
+ ${extra.track?.length ? `<div class="card"><h2>Track record</h2>${extra.track.map((l) => `<p style="margin:4px 0">${esc2(l)}</p>`).join("")}<p class="muted">A statement from its signed receipts, not a score.</p></div>` : ""}
37076
+ ${plain?.length ? `<div class="card"><h2>Its instructions, in plain words</h2>${plain.map((l) => `<p style="margin:4px 0">${esc2(l)}</p>`).join("")}</div>` : ""}
37077
+ <div class="card"><h2>Permissions</h2><div class="wrap"><table>${perms}</table></div>${tier ? `<p class="muted">Risk tier ${esc2(tier.tier)}: ${esc2(tier.note)}.</p>` : ""}</div>
35712
37078
  <div class="card"><h2>Mandate</h2><div class="grid"><div class="kv"><small>Servers</small><b>${esc2(m.allow.servers?.join(", ") ?? "any")}</b></div><div class="kv"><small>Tools</small><b>${esc2(m.allow.tools?.join(", ") ?? "any")}</b></div><div class="kv"><small>Issued</small><b>${esc2(m.issuedAt.slice(0, 10))}</b></div></div>
35713
- <p class="muted">Agent identity <code>${esc2(m.agent.id)}</code>, signed by its owner <code>${esc2(m.owner.id)}</code>.</p></div>
37079
+ <p class="muted">Agent identity <code>${esc2(m.agent.id)}</code>${m.agent.software ? ` running ${esc2(m.agent.software)}` : ""}, signed by its owner <code>${esc2(m.owner.id)}</code>${extra.operator ? ` and countersigned by the operator ${esc2(extra.operator)}` : ""}.</p></div>
35714
37080
  ${s ? `<div class="card"><h2>What it did</h2><div class="grid"><div class="kv"><small>Tool calls</small><b>${s.calls}</b></div><div class="kv"><small>Blocked</small><b>${s.denied}</b></div><div class="kv"><small>Errors</small><b>${s.errors}</b></div><div class="kv"><small>Destructive actions</small><b>${s.destructiveAllowed}</b></div></div>
35715
37081
  ${s.repeatedIdenticalCalls.length ? `<p><b>Repeated identical calls:</b> ${s.repeatedIdenticalCalls.map((x) => `${esc2(x.call)} \xD7${x.times}`).join(", ")} (possible retry storm; highlighted below).</p>` : ""}
35716
- <h2 style="margin-top:14px">The path, not the answer</h2><div class="timeline">${steps}</div><p class="muted">${esc2(s.from?.slice(0, 19).replace("T", " ") ?? "")} to ${esc2(s.to?.slice(0, 19).replace("T", " ") ?? "")} \xB7 ${esc2(s.servers.join(", "))}. Each step is a signed, hash-chained receipt; arguments are stored only as digests.</p></div>` : ""}
37082
+ <h2 style="margin-top:14px">The path, not the answer</h2><div class="timeline">${steps}</div>
37083
+ ${(receipts?.timeline ?? []).some((t) => t.why) ? `<h2 style="margin-top:14px">Why, step by step</h2><div class="wrap"><table>${(receipts?.timeline ?? []).map((t, i) => `<tr><td>${i + 1}</td><td><span class="step ${t.outcome === "deny" ? "deny" : t.status === "ok" ? "ok" : "err"}">${esc2(t.tool)}</span></td><td>${esc2(t.why ?? "")}</td></tr>`).join("")}</table></div>` : ""}<p class="muted">${esc2(s.from?.slice(0, 19).replace("T", " ") ?? "")} to ${esc2(s.to?.slice(0, 19).replace("T", " ") ?? "")} \xB7 ${esc2(s.servers.join(", "))}. Each step is a signed, hash-chained receipt; arguments are stored only as digests.</p></div>` : ""}
35717
37084
  <div class="card"><h2>Verify</h2><p><code>npx saktum agent verify agent-mandate.json</code> \xB7 <code>npx saktum receipts verify</code></p><p class="muted">Preview: receipts are signed by the agent side; the Saktum gateway adds the server side's signature.</p></div>`;
35718
- return page(`${m.agent.name}: Agent Passport`, body);
37085
+ return page(`${m.agent.name}: Agent Passport`, body2);
35719
37086
  }
35720
37087
  function renderLedgerPassport(e) {
35721
37088
  const c = e.attestation.claims, g = c.trustGrade ?? "-";
35722
- const body = `<div class="card"><div class="top"><div class="seal" style="background:${GRADE_COLOUR[g] ?? "#757575"}">${esc2(g)}</div><div><small>MCP SERVER PASSPORT \xB7 TRUST LEDGER ENTRY #${e.seq}</small><h1>${esc2(e.subject.server)} ${esc2(e.subject.version ?? "")}</h1>
37089
+ const body2 = `<div class="card"><div class="top"><div class="seal" style="background:${GRADE_COLOUR[g] ?? "#757575"}">${esc2(g)}</div><div><small>MCP SERVER PASSPORT \xB7 TRUST LEDGER ENTRY #${e.seq}</small><h1>${esc2(e.subject.server)} ${esc2(e.subject.version ?? "")}</h1>
35723
37090
  <div class="muted">${esc2(e.attestation.subject.transport)} \xB7 ${esc2(String(e.attestation.subject.toolCount ?? "?"))} tools \xB7 checked ${esc2(e.attestation.checkedAt.slice(0, 10))} with ${esc2(e.attestation.checkedWith)}</div></div></div>
35724
37091
  <div class="chips">${chip("Trust", c.trustGrade, GRADE_COLOUR[g])}${chip("Agent readiness", c.readinessGrade, GRADE_COLOUR[c.readinessGrade ?? ""])}${chip("Assurance", c.assuranceLevel)}${chip("Recorded", e.recordedAt.slice(0, 10))}</div></div>
35725
37092
  <div class="card"><h2>Maturity evidence</h2>${levelBar(evidenceLevel(c.evidence))}</div>
35726
37093
  <div class="card"><h2>Verify</h2><p>Signed by <code>${esc2(e.signer)}</code>; tools fingerprint <code>${esc2(e.subject.toolsFingerprint ?? "-")}</code>.</p><p><code>npx saktum ledger verify</code> \xB7 <code>npx saktum ledger find "${esc2(e.subject.server)}"</code></p><p class="muted">A signed claim by the server's publisher (assurance ${esc2(c.assuranceLevel)}; L1 = self-tested). It describes the tools matching the fingerprint at that time.</p></div>
35727
37094
  <p class="muted"><a href="index.html">All passports</a> \xB7 <a href="../index.html">State of MCP Trust</a></p>`;
35728
- return page(`${e.subject.server}: MCP Server Passport`, body);
37095
+ return page(`${e.subject.server}: MCP Server Passport`, body2);
35729
37096
  }
35730
37097
  function renderPassportGallery(entries) {
35731
37098
  const latest = /* @__PURE__ */ new Map();
@@ -35759,7 +37126,7 @@ function renderAssessment(org, f, receipts = [], roi) {
35759
37126
  if (tokens > 5e4)
35760
37127
  rec.push(`Tool definitions cost ${tokens.toLocaleString("en-US")} tokens per turn across distinct servers: remove duplicates and unused servers.`);
35761
37128
  const rc = receipts.map((r) => `<tr><td><b>${esc2(r.agent)}</b></td><td>${r.summary.calls}</td><td>${r.summary.denied}</td><td>${r.summary.destructiveAllowed}</td><td>${esc2(r.summary.repeatedIdenticalCalls.map((x) => `${x.call} \xD7${x.times}`).join(", ") || "none")}</td><td>${r.verified ? "verified" : "NOT verified"}</td></tr>`).join("");
35762
- const body = `<div class="card"><small>MCP TRUST ASSESSMENT</small><h1>${esc2(org)}</h1><p class="muted">Prepared with Saktum on ${esc2(f.generatedAt.slice(0, 10))}${f.policyName ? ` against policy \u201C${esc2(f.policyName)}\u201D` : ""}. Evidence collected inside ${esc2(org)}'s environment; nothing was sent to Saktum.</p>
37129
+ const body2 = `<div class="card"><small>MCP TRUST ASSESSMENT</small><h1>${esc2(org)}</h1><p class="muted">Prepared with Saktum on ${esc2(f.generatedAt.slice(0, 10))}${f.policyName ? ` against policy \u201C${esc2(f.policyName)}\u201D` : ""}. Evidence collected inside ${esc2(org)}'s environment; nothing was sent to Saktum.</p>
35763
37130
  <div class="grid"><div class="kv"><small>Machines</small><b>${f.machines}</b></div><div class="kv"><small>Distinct MCP servers</small><b>${f.servers.length}</b></div><div class="kv"><small>Violate policy</small><b>${f.nonCompliant}</b></div><div class="kv"><small>Not assessable</small><b>${f.unassessed}</b></div></div></div>
35764
37131
  <div class="card"><h2>Risk heat map: capability by trust grade</h2><div class="wrap"><table><tr><th>Capability</th>${grades.map((g) => `<th style="text-align:center">${g === "-" ? "n/a" : g}</th>`).join("")}</tr>${heat}</table></div><small>Red cells: risky capabilities on servers graded C or below, or not assessed.</small></div>
35765
37132
  <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>
@@ -35767,7 +37134,7 @@ ${rc ? `<div class="card"><h2>Agent receipts</h2><div class="wrap"><table><tr><t
35767
37134
  ${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>` : ""}
35768
37135
  <div class="card"><h2>Recommendations</h2><ol>${rec.map((x) => `<li>${esc2(x)}</li>`).join("")}</ol></div>
35769
37136
  <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>`;
35770
- return page(`MCP Trust Assessment: ${org}`, body);
37137
+ return page(`MCP Trust Assessment: ${org}`, body2);
35771
37138
  }
35772
37139
  var esc2, GRADE_COLOUR, chip, STYLE, page, levelBar, effect, passportSlug, evidenceLevel;
35773
37140
  var init_passport = __esm({
@@ -35790,7 +37157,7 @@ code{font:12.5px ui-monospace,Menlo,Consolas,monospace;word-break:break-all}.lev
35790
37157
  .ok{background:#e8f5e9;color:#1b5e20}.deny{background:#ffebee;color:#b71c1c}.err{background:#fff8e1;color:#7a5a00}.rep{outline:2px solid #b7791f}
35791
37158
  @media (prefers-color-scheme:dark){.ok{background:#1b3a1e;color:#a5d6a7}.deny{background:#3b1616;color:#ef9a9a}.err{background:#3a3214;color:#ffe082}}
35792
37159
  @media print{body{background:#fff}.card{break-inside:avoid}}`;
35793
- page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>${esc2(title)}</title><style>${STYLE}</style></head><body><main>${body}</main></body></html>
37160
+ page = (title, body2) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>${esc2(title)}</title><style>${STYLE}</style></head><body><main>${body2}</main></body></html>
35794
37161
  `;
35795
37162
  levelBar = (level, note) => `<div class="levels">${[1, 2, 3, 4, 5].map((l) => `<div class="lv${l <= level ? " on" : ""}">L${l}</div>`).join("")}</div><small>${esc2(["", "Responds", "Conformant", "Safe by default", "Agent-ready", "Assured"][level] ?? "Not assessed")}${note ? ` \xB7 ${esc2(note)}` : ""}</small>`;
35796
37163
  effect = (t) => {
@@ -35844,6 +37211,8 @@ function trustCard(r) {
35844
37211
  rows.push({ dimension: "Performance", mark: "-", text: `start-up and tool-list latency only${r.metrics.performance?.listMs !== void 0 ? ` (${r.metrics.performance.listMs} ms)` : ""}; run with --active for latency percentiles and concurrency` });
35845
37212
  if (r.readiness)
35846
37213
  rows.push({ dimension: "Agent readiness", mark: r.readiness.grade ?? "-", text: r.readiness.topImprovement ? `${r.readiness.topImprovement}` : "annotations, descriptions and context cost all good" });
37214
+ if (r.riskTier)
37215
+ rows.push({ dimension: "Risk tier", mark: r.riskTier.tier, text: `${r.riskTier.label}: ${r.riskTier.reasons.join("; ")}. Needs ${r.riskTier.requirement}.` });
35847
37216
  if (r.capabilities) {
35848
37217
  const caps = r.capabilities.capabilities.map((c) => c.label);
35849
37218
  rows.push({ dimension: "Capabilities", mark: r.capabilities.lethalTrifecta ? "!" : "i", text: caps.length ? `${caps.join("; ")}${r.capabilities.lethalTrifecta ? ". Warning: private data + untrusted content + outbound channel (the lethal trifecta); limit what agents can combine" : ""}` : "no notable capabilities inferred" });
@@ -35885,6 +37254,8 @@ function renderTerminal(r) {
35885
37254
  }
35886
37255
  const fn = r.findings.filter((f) => (f.pack === "functional" || f.pack === "tests") && f.scored && !f.suppressed && (f.status === "pass" || f.status === "fail"));
35887
37256
  lines.push(` FUNCTIONAL ${fn.length ? `${fn.filter((f) => f.status === "pass").length} of ${fn.length} checks passed${r.functional?.calledTools.length ? ` \xB7 ${r.functional.calledTools.length} tool${r.functional.calledTools.length === 1 ? "" : "s"} called` : ""}${r.tests?.length ? ` \xB7 ${r.tests.length} test cases` : ""}` : "not tested (run with --active, or add test cases)"}`);
37257
+ if (r.riskTier)
37258
+ lines.push(` RISK ${r.riskTier.tier} (${r.riskTier.label}; needs ${r.riskTier.requirement})`);
35888
37259
  lines.push(` ${COVERAGE_NOTE}`);
35889
37260
  for (const line of r.summary ?? [])
35890
37261
  lines.push(` ${s(line, 300)}`);
@@ -36114,10 +37485,10 @@ __export(init_exports, {
36114
37485
  AGENT_RULES: () => AGENT_RULES,
36115
37486
  initProject: () => initProject
36116
37487
  });
36117
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
37488
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
36118
37489
  import { join as join4 } from "node:path";
36119
37490
  function initProject(dir, lang, name) {
36120
- if (existsSync3(join4(dir, "package.json")) || existsSync3(join4(dir, "pyproject.toml")) || existsSync3(join4(dir, "server.py")))
37491
+ if (existsSync4(join4(dir, "package.json")) || existsSync4(join4(dir, "pyproject.toml")) || existsSync4(join4(dir, "server.py")))
36121
37492
  throw new Error(`${dir} already contains a project; choose an empty folder.`);
36122
37493
  const id = name.replace(/[^a-z0-9-]/gi, "-").toLowerCase() || "my-mcp-server";
36123
37494
  const files = {};
@@ -36207,8 +37578,8 @@ if __name__ == "__main__":
36207
37578
  ${AGENT_RULES}`;
36208
37579
  for (const [p, text2] of Object.entries(files)) {
36209
37580
  const f = join4(dir, p);
36210
- mkdirSync2(join4(f, ".."), { recursive: true });
36211
- writeFileSync2(f, text2);
37581
+ mkdirSync3(join4(f, ".."), { recursive: true });
37582
+ writeFileSync3(f, text2);
36212
37583
  }
36213
37584
  return Object.keys(files);
36214
37585
  }
@@ -36295,26 +37666,38 @@ __export(proxy_exports, {
36295
37666
  runProxy: () => runProxy
36296
37667
  });
36297
37668
  import { spawn as spawn3 } from "node:child_process";
36298
- import { appendFileSync, existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync5 } from "node:fs";
36299
- import { dirname as dirname2 } from "node:path";
37669
+ import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "node:fs";
37670
+ import { dirname as dirname3 } from "node:path";
36300
37671
  import { createInterface } from "node:readline";
36301
37672
  import { randomUUID } from "node:crypto";
36302
37673
  async function runProxy(o) {
36303
- mkdirSync3(dirname2(o.receiptsPath), { recursive: true });
37674
+ mkdirSync4(dirname3(o.receiptsPath), { recursive: true });
36304
37675
  let last;
36305
- if (existsSync4(o.receiptsPath)) {
36306
- const e = parseReceiptLog(readFileSync5(o.receiptsPath, "utf8"));
36307
- last = e[e.length - 1];
36308
- }
37676
+ let history = [];
37677
+ if (existsSync5(o.receiptsPath)) {
37678
+ history = parseReceiptLog(readFileSync6(o.receiptsPath, "utf8"));
37679
+ last = history[history.length - 1];
37680
+ }
37681
+ const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
37682
+ const totArg = o.mandate?.limits?.totalPerDay?.arg;
37683
+ const governed = /* @__PURE__ */ new Set([...(o.mandate?.constraints ?? []).map((k) => k.arg), ...totArg ? [totArg] : [], ...o.mandate?.approveAbove ? [o.mandate.approveAbove.arg] : []]);
37684
+ const usage = () => {
37685
+ const t = today();
37686
+ const done = history.filter((e) => e.receipt.issuedAt.startsWith(t) && e.receipt.outcome === "allow" && e.result.status === "ok" && e.result.code === "ok-action");
37687
+ return { callsToday: done.length, totalToday: totArg ? done.reduce((a, e) => a + Number(e.result.values?.[totArg] ?? 0), 0) : 0 };
37688
+ };
36309
37689
  const bare = !/[\\/]/.test(o.command);
36310
37690
  const child = spawn3(o.command, o.args, { stdio: ["pipe", "pipe", "inherit"], shell: process.platform === "win32" && (bare || /\.(cmd|bat)$/i.test(o.command)) });
36311
37691
  let service = o.command.split(/[\\/]/).pop() ?? o.command, version2;
36312
37692
  const annotations = /* @__PURE__ */ new Map();
37693
+ const toolDefs = /* @__PURE__ */ new Map();
36313
37694
  const pendingKinds = /* @__PURE__ */ new Map();
36314
37695
  const calls = /* @__PURE__ */ new Map();
36315
37696
  const key = (id) => JSON.stringify(id);
36316
37697
  const isDestructive = (a) => a?.destructiveHint === true || a?.readOnlyHint === false && a?.destructiveHint !== false;
36317
37698
  const record2 = (tool, argsHash, outcome, reason, result) => {
37699
+ if (result.code)
37700
+ reason = `[${result.code}] ${reason}`;
36318
37701
  const receipt = signReceipt({
36319
37702
  receiptFormat: "0.1",
36320
37703
  envelope: {
@@ -36336,6 +37719,7 @@ async function runProxy(o) {
36336
37719
  const entry = chainEntry(last, receipt, result);
36337
37720
  appendFileSync(o.receiptsPath, JSON.stringify(entry) + "\n");
36338
37721
  last = entry;
37722
+ history.push(entry);
36339
37723
  };
36340
37724
  createInterface({ input: process.stdin }).on("line", (line) => {
36341
37725
  let msg;
@@ -36349,16 +37733,67 @@ async function runProxy(o) {
36349
37733
  pendingKinds.set(key(msg.id), msg.method);
36350
37734
  if (msg.method === "tools/call" && msg.id !== void 0) {
36351
37735
  const tool = String(msg.params?.name ?? "");
36352
- const argsHash = argumentsHash(msg.params?.arguments);
37736
+ const args = msg.params?.arguments ?? {};
37737
+ const argsHash = argumentsHash(args);
36353
37738
  const ann = annotations.get(tool);
36354
- const d = o.mandate ? mandateDecision(o.mandate, service, tool, ann) : { allow: true, reason: "no mandate: observed" };
37739
+ const def = toolDefs.get(tool);
37740
+ const isMoney = def ? capabilityProfile([def]).capabilities.some((c) => c.capability === "money") : false;
37741
+ const values = Object.fromEntries([...governed].filter((k) => args[k] !== void 0 && (typeof args[k] === "number" || typeof args[k] === "string")).map((k) => [k, args[k]]));
37742
+ const rev = o.mandate ? revocationOf(o.mandate, o.revocationsPath) : void 0;
37743
+ 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" };
37744
+ let rationale;
37745
+ if (d.allow && o.mandate && hasIntent(o.mandate)) {
37746
+ const di = decideIntent(o.mandate, def ?? { name: tool }, args, { server: service });
37747
+ rationale = di.rationale;
37748
+ for (const [k, val] of Object.entries(di.values))
37749
+ if (typeof val === "number" || typeof val === "string" || typeof val === "boolean")
37750
+ values[k] = val;
37751
+ if (!di.allow)
37752
+ d = { allow: false, code: di.code, reason: di.reason };
37753
+ else if (di.reason !== "within the mandate")
37754
+ d = { allow: true, code: "ok", reason: di.reason };
37755
+ }
37756
+ if (!d.allow && d.code === "approval-needed" && o.mandate) {
37757
+ const rid = approvalRequestId(o.mandate, tool, args);
37758
+ const ap = consumeApproval(o.mandate, rid, o.approvalsPath);
37759
+ if (ap.ok)
37760
+ d = { allow: true, code: "ok", reason: `approved by ${ap.by} (${rid}), after: ${d.reason}` };
37761
+ else
37762
+ d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
37763
+ }
37764
+ if (d.allow && o.credential) {
37765
+ const vc = verifyChain(o.credential, { revoked: o.revokedCredentials });
37766
+ const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
37767
+ if (!vc.valid)
37768
+ d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
37769
+ else if (o.agreement && root !== o.agreement.invoker.id)
37770
+ d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
37771
+ }
37772
+ let metering;
37773
+ if (d.allow && o.agreement) {
37774
+ const va = verifyAgreement(o.agreement);
37775
+ if (!va.valid)
37776
+ d = { allow: false, code: "no-valid-agreement", reason: `no valid agreement with the provider: ${va.reason}` };
37777
+ else if (o.agreement.scope.tools && !o.agreement.scope.tools.includes(tool))
37778
+ d = { allow: false, code: "outside-agreement", reason: `${tool} is outside the agreement ${o.agreement.id}` };
37779
+ else if (o.walletPath) {
37780
+ const ch = chargeCall(o.walletPath, o.agreement, tool, `${o.agreement.id}:${tool}`);
37781
+ if (!ch.ok)
37782
+ d = { allow: false, code: "insufficient-credit", reason: `${tool} costs ${ch.tokens} tokens; the prepaid balance is ${ch.balance}` };
37783
+ else
37784
+ metering = { agreement: o.agreement.id, tokens: ch.tokens, balance: ch.balance };
37785
+ } else
37786
+ metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
37787
+ }
36355
37788
  if (!d.allow && o.enforce) {
36356
- process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { isError: true, content: [{ type: "text", text: `Blocked by Saktum: ${d.reason}. Ask the agent's owner to extend its mandate if this action is needed.` }] } }) + "\n");
36357
- record2(tool, argsHash, "deny", d.reason, { status: "blocked", destructive: isDestructive(ann) });
36358
- o.log?.(`denied ${tool}: ${d.reason}`);
37789
+ 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.";
37790
+ 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");
37791
+ record2(tool, argsHash, "deny", d.reason, { status: "blocked", destructive: isDestructive(ann), code: d.code, values, ...rationale ? { rationale } : {} });
37792
+ o.log?.(`denied ${tool} (${d.code}): ${d.reason}`);
36359
37793
  return;
36360
37794
  }
36361
- calls.set(key(msg.id), { tool, argsHash, start: Date.now(), reason: d.allow ? d.reason : `outside the mandate (observed, not blocked): ${d.reason}`, destructive: isDestructive(ann) });
37795
+ const code = !d.allow ? `observed-${d.code}` : ann?.readOnlyHint === true ? "ok-read" : "ok-action";
37796
+ calls.set(key(msg.id), { tool, argsHash, start: Date.now(), reason: d.allow ? d.reason : `outside the mandate (observed, not blocked): ${d.reason}`, destructive: isDestructive(ann), code, values, rationale, metering });
36362
37797
  }
36363
37798
  child.stdin.write(line + "\n");
36364
37799
  });
@@ -36390,21 +37825,23 @@ async function runProxy(o) {
36390
37825
  pendingKinds.delete(k);
36391
37826
  }
36392
37827
  if (kind === "tools/list" && Array.isArray(msg.result?.tools)) {
36393
- for (const t of msg.result.tools)
37828
+ for (const t of msg.result.tools) {
36394
37829
  annotations.set(t.name, t.annotations);
37830
+ toolDefs.set(t.name, t);
37831
+ }
36395
37832
  pendingKinds.delete(k);
36396
37833
  }
36397
37834
  const c = calls.get(k);
36398
37835
  if (c) {
36399
37836
  calls.delete(k);
36400
37837
  const status = msg.error ? "protocol-error" : msg.result?.isError ? "tool-error" : "ok";
36401
- record2(c.tool, c.argsHash, msg.error ? "error" : "allow", c.reason, { status, latencyMs: Date.now() - c.start, destructive: c.destructive });
37838
+ record2(c.tool, c.argsHash, msg.error ? "error" : "allow", c.reason, { status, latencyMs: Date.now() - c.start, destructive: c.destructive, code: c.code, values: c.values, ...c.rationale ? { rationale: c.rationale } : {}, ...c.metering ? { metering: c.metering } : {} });
36402
37839
  }
36403
37840
  process.stdout.write(line + "\n");
36404
37841
  });
36405
37842
  return new Promise((resolve) => child.on("exit", (code) => {
36406
37843
  for (const c of calls.values())
36407
- record2(c.tool, c.argsHash, "error", c.reason, { status: "no-response", destructive: c.destructive });
37844
+ record2(c.tool, c.argsHash, "error", c.reason, { status: "no-response", destructive: c.destructive, code: c.code, values: c.values });
36408
37845
  resolve(code ?? 0);
36409
37846
  }));
36410
37847
  }
@@ -37090,6 +38527,472 @@ var init_stdio3 = __esm({
37090
38527
  }
37091
38528
  });
37092
38529
 
38530
+ // packages/cli/dist/demo.js
38531
+ var demo_exports = {};
38532
+ __export(demo_exports, {
38533
+ runAutonomyDemo: () => runAutonomyDemo,
38534
+ runDemo: () => runDemo,
38535
+ startDemoServer: () => startDemoServer
38536
+ });
38537
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync4, existsSync as existsSync6, rmSync } from "node:fs";
38538
+ import { join as join5 } from "node:path";
38539
+ async function startDemoServer(story = "autonomy") {
38540
+ const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : DEMO_TOOLS;
38541
+ const server = new Server({ name: story === "travel" ? "demo-travel" : story === "finance" ? "demo-finance" : "demo-grocer", version: "1.0.0" }, { capabilities: { tools: {} } });
38542
+ const cart = [];
38543
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
38544
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
38545
+ const a = req.params.arguments ?? {};
38546
+ const text2 = (t) => ({ content: [{ type: "text", text: t }] });
38547
+ switch (req.params.name) {
38548
+ case "search_products":
38549
+ if (story === "grocery")
38550
+ return text2("Oat milk (Usual Farms) $4.49 \xB7 Rye bread (Bakehouse) $6.35 \xB7 Sourdough: out of stock \xB7 Snack bar (Promo, sponsored) $3.99");
38551
+ return text2(PRODUCTS.filter((p) => p.name.toLowerCase().includes(String(a.query ?? "").toLowerCase().split(" ")[0])).map((p) => `${p.name}: $${p.price}`).join("\n") || "No match.");
38552
+ case "get_deals":
38553
+ return text2("Deal: coffee beans 1 kg, $21.99 (was $27.99).");
38554
+ case "add_to_cart":
38555
+ cart.push(String(a.product));
38556
+ return text2(`Added ${a.quantity} \xD7 ${a.product}${a.brand ? ` (${a.brand})` : ""}.`);
38557
+ case "pay_for_order":
38558
+ return text2(`Paid $${a.amount} ${a.currency}. Order placed.`);
38559
+ case "search_flights":
38560
+ return text2("YUL 3 Mar: Maple Air 1 stop $540 refundable \xB7 Budget Jet 2 stops $420 \xB7 Direct Air $380 non-refundable.");
38561
+ case "book_flight":
38562
+ return text2(`Booked ${a.flight} for $${a.fare}.`);
38563
+ case "change_seat":
38564
+ return text2(`Seat changed to ${a.seat}.`);
38565
+ case "upgrade_cabin":
38566
+ return text2(`Upgraded to ${a.cabin}.`);
38567
+ case "share_traveller_details":
38568
+ return text2(`Shared with ${a.recipient}.`);
38569
+ case "send_report":
38570
+ return text2(`Sent "${a.report}" to ${a.recipient}.`);
38571
+ case "pay_invoice":
38572
+ return text2(`Paid $${a.amount} to ${a.vendor}.`);
38573
+ default:
38574
+ return { isError: true, content: [{ type: "text", text: "Unknown tool" }] };
38575
+ }
38576
+ });
38577
+ const closed = new Promise((r) => {
38578
+ server.onclose = () => r();
38579
+ process.stdin.on("end", () => r());
38580
+ });
38581
+ await server.connect(new StdioServerTransport());
38582
+ await closed;
38583
+ }
38584
+ async function runStory(dir, st, owner, log) {
38585
+ const self = [...process.execArgv, process.argv[1]];
38586
+ const agentKey = loadOrCreateKey(join5(dir, `${st.id}-agent-key.json`));
38587
+ const m = createMandate({
38588
+ agentId: agentKey.kid,
38589
+ agentName: `${st.id === "travel" ? "Travel" : "Shopping"} agent`,
38590
+ ownerName: "Demo customer",
38591
+ tools: st.tools,
38592
+ destructive: false,
38593
+ expires: new Date(Date.now() + 7 * 864e5).toISOString().slice(0, 10),
38594
+ ...st.m
38595
+ }, owner);
38596
+ const operatorName = String(st.m.disclosures?.operator ?? "Demo operator");
38597
+ const cm = cosignMandate(m, loadOrCreateKey(join5(dir, `${st.id}-operator-key.json`)), operatorName);
38598
+ const mf = join5(dir, `${st.id}-mandate.json`), rf = join5(dir, `${st.id}-receipts.jsonl`), revf = join5(dir, "revocations.json");
38599
+ writeFileSync4(mf, JSON.stringify(cm, null, 2));
38600
+ log(`\u2500\u2500 ${st.title}`);
38601
+ log(` Signed by you; countersigned by the operator, ${operatorName}.`);
38602
+ for (const line of describeMandate(m))
38603
+ log(` ${line}`);
38604
+ 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] });
38605
+ const s = await open2();
38606
+ try {
38607
+ await s.listTools();
38608
+ let lastRid = "";
38609
+ for (const step of st.steps) {
38610
+ if (step.approveLast) {
38611
+ const { approveAction: approveAction2 } = await Promise.resolve().then(() => (init_dist4(), dist_exports));
38612
+ approveAction2(cm, lastRid, owner, 60, join5(dir, "approvals.json"));
38613
+ log(` \u270D ${step.say}: ${lastRid}`);
38614
+ continue;
38615
+ }
38616
+ const o = await s.callTool(step.tool, step.args);
38617
+ const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
38618
+ const rid = /\[approval request (apr_[0-9a-f]+)\]/.exec(txt);
38619
+ if (rid)
38620
+ lastRid = rid[1];
38621
+ const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)( \[approval request [^\]]+\])?\.( Ask| Tell|$)/.exec(txt);
38622
+ const lastR = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
38623
+ log(blocked ? ` \u26D4 ${step.say}: ${blocked[1]}: ${blocked[2]}` : ` \u2713 ${step.say}${/approved by/.test(String(lastR?.receipt.reason ?? "")) ? ": approved by you, once" : ""}`);
38624
+ const last = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
38625
+ for (const p of last?.result.rationale?.preferences ?? [])
38626
+ if (!blocked)
38627
+ log(` \xB7 ${p}`);
38628
+ for (const f of last?.result.rationale?.flags ?? [])
38629
+ if (!blocked && !/differs from the stated preference/.test(f))
38630
+ log(` ! ${f}`);
38631
+ }
38632
+ } finally {
38633
+ await s.close();
38634
+ await new Promise((r) => setTimeout(r, 300));
38635
+ }
38636
+ if (st.id === "grocery") {
38637
+ revokeMandate(cm, "you pressed stop", revf);
38638
+ const s2 = await open2();
38639
+ try {
38640
+ await s2.listTools();
38641
+ const o = await s2.callTool("search_products", { query: "milk" });
38642
+ const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
38643
+ log(/revoked/.test(txt) ? " \u26D4 after you press stop (saktum agent revoke), it tries to search again: revoked" : ` ? after revoke: ${txt.slice(0, 80)}`);
38644
+ } finally {
38645
+ await s2.close();
38646
+ await new Promise((r) => setTimeout(r, 300));
38647
+ }
38648
+ }
38649
+ const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
38650
+ const ts = trustStatement(entries, verifyReceiptLog(entries).ok);
38651
+ log(" Track record:");
38652
+ for (const l of ts.lines)
38653
+ log(` ${l}`);
38654
+ const html = join5(dir, `${st.id}-passport.html`);
38655
+ writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38656
+ verified: verifyReceiptLog(entries).ok,
38657
+ summary: summariseReceipts(entries),
38658
+ timeline: entries.map((e) => ({ tool: e.receipt.envelope.tool, outcome: e.receipt.outcome, status: e.result.status, repeated: false, why: [e.receipt.reason ?? "", ...e.result.rationale?.preferences ?? [], ...e.result.rationale?.flags ?? []].filter(Boolean).join(" \xB7 ") }))
38659
+ }, agentRiskTier(m), describeMandate(m), { operator: (() => {
38660
+ const op = checkOperator(cm);
38661
+ return op.present && op.valid ? `${op.name} (${op.id})` : void 0;
38662
+ })(), track: ts.lines }));
38663
+ log(` ${entries.length} signed receipts \xB7 ${verifyReceiptLog(entries).ok ? "verified" : "NOT verified"} \xB7 passport: ${html}
38664
+ `);
38665
+ return html;
38666
+ }
38667
+ async function runMarketplace(dir, log) {
38668
+ const self = [...process.execArgv, process.argv[1]];
38669
+ const k = (n) => loadOrCreateKey(join5(dir, `market-${n}-key.json`));
38670
+ const acme = k("acme"), priya = k("priya"), agent = k("agent"), grocer = k("grocer"), travel = k("travel");
38671
+ const exp = new Date(Date.now() + 180 * 864e5).toISOString().slice(0, 10);
38672
+ const w = (f, x) => {
38673
+ writeFileSync4(join5(dir, f), JSON.stringify(x, null, 2));
38674
+ return join5(dir, f);
38675
+ };
38676
+ log(`\u2500\u2500 Marketplace: "Acme's shopping agent finds a store, agrees terms, and pays per call in prepaid tokens"`);
38677
+ const root = organisationRoot({ name: "Acme Corp", domain: "acme.example", expires: exp }, acme);
38678
+ const priyaCred = issueCredential(root, acme, { type: "member", id: priya.kid, name: "Priya", role: "procurement lead", expires: exp });
38679
+ const agentCred = issueCredential(priyaCred, priya, { type: "agent", id: agent.kid, name: "Acme shopping agent", expires: exp });
38680
+ const credFile = w("market-agent-credential.json", agentCred);
38681
+ const vchain = verifyChain(agentCred);
38682
+ log(vchain.valid ? ` \u2713 identity chain: ${vchain.path.join(" \u2192 ")}; accountable organisation ${vchain.organisation}` : ` \u2717 identity chain broken: ${vchain.reason}`);
38683
+ const gm = buildManifest({ publisher: { name: "Demo Grocer", domain: "grocer.example" }, server: { name: "demo-grocer", version: "1.0.0" }, tools: GROCERY_TOOLS, rates: { perCall: 1, perTool: { add_to_cart: 2, pay_for_order: 5 } } }, grocer);
38684
+ const tm = buildManifest({ publisher: { name: "Demo Travel", domain: "travel.example" }, server: { name: "demo-travel", version: "1.0.0" }, tools: TRAVEL_TOOLS, rates: { perCall: 2 } }, travel);
38685
+ w("market-catalog.json", [gm, tm]);
38686
+ log(` \u2713 Demo Grocer and Demo Travel publish signed manifests to the catalogue (rates in tokens per call)`);
38687
+ const hits = searchCatalogue([gm, tm], "buy weekly groceries for the office");
38688
+ log(` \u2713 the agent searches "buy weekly groceries for the office": ${hits[0].manifest.publisher.name} (intents ${hits[0].matched.join(", ")})`);
38689
+ const ag = acceptAgreement(draftAgreement({
38690
+ manifest: gm,
38691
+ invoker: { id: acme.kid, name: "Acme Corp" },
38692
+ purpose: "Weekly office groceries",
38693
+ tools: gm.capabilities.map((c) => c.tool),
38694
+ tokensPerMonth: 500,
38695
+ specificTerms: ["Deliveries to the Acme office only", "Substitutions within 10% of the price"],
38696
+ validUntil: exp
38697
+ }, grocer), acme);
38698
+ const agFile = w("market-agreement.json", ag);
38699
+ 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"})`);
38700
+ const wf = join5(dir, "market-wallet.json");
38701
+ topUp(wf, acme.kid, 12);
38702
+ log(` \u2713 Acme tops up 12 prepaid tokens (bought outside Saktum; no money is handled here)`);
38703
+ 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" }, priya), acme, "Acme Corp");
38704
+ const mf = w("market-mandate.json", m), rf = join5(dir, "market-receipts.jsonl"), revf = join5(dir, "market-revoked-credentials.json");
38705
+ writeFileSync4(revf, "[]");
38706
+ const open2 = () => connect({ kind: "stdio", command: process.execPath, args: [
38707
+ ...self,
38708
+ "proxy",
38709
+ "--mandate",
38710
+ mf,
38711
+ "--agent-key",
38712
+ join5(dir, "market-agent-key.json"),
38713
+ "--enforce",
38714
+ "--receipts",
38715
+ rf,
38716
+ "--credential",
38717
+ credFile,
38718
+ "--revoked-credentials",
38719
+ revf,
38720
+ "--agreement",
38721
+ agFile,
38722
+ "--wallet",
38723
+ wf,
38724
+ "--",
38725
+ process.execPath,
38726
+ ...self,
38727
+ "demo-server",
38728
+ "--story",
38729
+ "grocery"
38730
+ ] });
38731
+ const steps = [
38732
+ { tool: "search_products", args: { query: "milk" }, say: "searches the catalogue" },
38733
+ { tool: "add_to_cart", args: { product: "Oat milk", brand: "Usual Farms", category: "dairy", quantity: 2, price: 4.49 }, say: "adds oat milk" },
38734
+ { tool: "add_to_cart", args: { product: "Coffee beans 1 kg", brand: "Usual Farms", category: "coffee", quantity: 1, price: 21.99 }, say: "adds coffee" },
38735
+ { tool: "pay_for_order", args: { amount: 30.97, currency: "CAD", merchant: "Demo Grocer", idempotency_key: "m-1" }, say: "pays $30.97" },
38736
+ { tool: "add_to_cart", args: { product: "Bread", brand: "Usual Farms", category: "bakery", quantity: 1, price: 5.99 }, say: "starts next week's order" },
38737
+ { tool: "search_products", args: { query: "fruit" }, say: "searches again" }
38738
+ ];
38739
+ const run = async (st2) => {
38740
+ const s2 = await open2();
38741
+ try {
38742
+ await s2.listTools();
38743
+ for (const st1 of st2) {
38744
+ const o = await s2.callTool(st1.tool, st1.args);
38745
+ const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
38746
+ const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)\.( Ask| Tell|$)/.exec(txt);
38747
+ const last = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
38748
+ 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 ?? "-"}`);
38749
+ }
38750
+ } finally {
38751
+ await s2.close();
38752
+ await new Promise((r) => setTimeout(r, 300));
38753
+ }
38754
+ };
38755
+ await run(steps);
38756
+ const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
38757
+ const st = usageStatement(entries, ag, grocer);
38758
+ log(` \u2713 usage statement signed by Demo Grocer: ${st.lines.map((l) => `${l.tool} ${l.calls}\xD7 = ${l.tokens}`).join(", ")}; total ${st.totalTokens} tokens`);
38759
+ log(` \u2713 wallet (double-entry): Acme ${walletBalance(wf, acme.kid)} tokens, Demo Grocer ${walletBalance(wf, grocer.kid)} tokens`);
38760
+ writeFileSync4(revf, JSON.stringify([priyaCred.id]));
38761
+ const orphan = findOrphans([agentCred], { revoked: [priyaCred.id] })[0];
38762
+ log(` \u26D4 Priya leaves Acme and her credential is revoked: the agent is now an orphan (${orphan?.reason})`);
38763
+ topUp(wf, acme.kid, 5);
38764
+ await run([{ tool: "search_products", args: { query: "milk" }, say: "the orphaned agent tries to search" }]);
38765
+ const all = parseReceiptLog(readFileSync7(rf, "utf8"));
38766
+ const k2 = kpis(all);
38767
+ 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`);
38768
+ const html = join5(dir, "marketplace-passport.html");
38769
+ const ts = trustStatement(all, verifyReceiptLog(all).ok);
38770
+ 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 }));
38771
+ log(` ${all.length} signed receipts \xB7 ${verifyReceiptLog(all).ok ? "verified" : "NOT verified"} \xB7 passport: ${html}
38772
+ `);
38773
+ return html;
38774
+ }
38775
+ async function runDemo(dir, log, story = "all") {
38776
+ if (story === "autonomy")
38777
+ return runAutonomyDemo(dir, log);
38778
+ if (story === "marketplace") {
38779
+ if (existsSync6(dir))
38780
+ rmSync(dir, { recursive: true, force: true });
38781
+ mkdirSync5(dir, { recursive: true });
38782
+ return { files: [await runMarketplace(dir, log)] };
38783
+ }
38784
+ if (existsSync6(dir))
38785
+ rmSync(dir, { recursive: true, force: true });
38786
+ mkdirSync5(dir, { recursive: true });
38787
+ const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
38788
+ log("Saktum demo: agents acting on real instructions (rules, preferences, substitutions, upsells), every decision explained and signed.\n");
38789
+ const files = [];
38790
+ for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : [GROCERY, TRAVEL, FINANCE])
38791
+ files.push(await runStory(dir, st, owner, log));
38792
+ if (story === "all")
38793
+ files.push(await runMarketplace(dir, log));
38794
+ log([
38795
+ "What you just saw: each agent followed its owner's instructions, not just limits. Even when tricked by a hidden",
38796
+ "instruction, the mandate held; personal and confidential data went only where you allowed; a big invoice waited for your",
38797
+ "signed approval of exactly that payment; and the stop button worked. In the marketplace, an agent traceable to a person",
38798
+ "and its organisation found a store by intent, both sides signed an agreement, every call was metered in prepaid tokens",
38799
+ "until credit ran out, and when its sponsor left, the orphaned agent was refused. Every decision has a signed receipt.",
38800
+ "Open the passports in the demo folder. Also try: npx saktum demo --story autonomy"
38801
+ ].join("\n"));
38802
+ return { files };
38803
+ }
38804
+ async function runAutonomyDemo(dir, log) {
38805
+ if (existsSync6(dir))
38806
+ rmSync(dir, { recursive: true, force: true });
38807
+ mkdirSync5(dir, { recursive: true });
38808
+ const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
38809
+ const self = [...process.execArgv, process.argv[1]];
38810
+ const tools = DEMO_TOOLS.map((t) => t.name);
38811
+ const personas = [
38812
+ { id: "notify", title: '"Only alert me to great deals"', m: { autonomy: "notify" }, steps: SCRIPT },
38813
+ { id: "propose", title: `"Suggest, and I'll approve"`, m: { autonomy: "propose" }, steps: SCRIPT },
38814
+ { id: "act", title: '"Act for me, up to $50; ask me above $25; Canadian dollars only"', m: { autonomy: "act", constraints: [{ tool: "pay_for_order", arg: "amount", max: 50 }, { tool: "pay_for_order", arg: "currency", oneOf: ["CAD"] }], approveAbove: { arg: "amount", value: 25 }, limits: { totalPerDay: { arg: "amount", max: 100 } } }, steps: [...SCRIPT, ...EXTRA] }
38815
+ ];
38816
+ const files = [];
38817
+ log("Saktum demo: one shopping agent, three mandates, every call governed and receipted.\n");
38818
+ for (const p of personas) {
38819
+ const agentKey = loadOrCreateKey(join5(dir, `${p.id}-agent-key.json`));
38820
+ const m = createMandate({
38821
+ agentId: agentKey.kid,
38822
+ agentName: `Shopping agent (${p.id})`,
38823
+ ownerName: "Demo shopper",
38824
+ purpose: "Weekly grocery shopping",
38825
+ tools,
38826
+ destructive: false,
38827
+ expires: new Date(Date.now() + 7 * 864e5).toISOString().slice(0, 10),
38828
+ disclosures: { operator: "Demo Grocer", incentives: "None: no sponsored ranking", dataUse: "Order history used only to suggest your usual items" },
38829
+ ...p.m
38830
+ }, owner);
38831
+ const mf = join5(dir, `${p.id}-mandate.json`), rf = join5(dir, `${p.id}-receipts.jsonl`);
38832
+ writeFileSync4(mf, JSON.stringify(m, null, 2));
38833
+ const tier = agentRiskTier(m);
38834
+ log(`\u2500\u2500 ${p.title} autonomy ${m.autonomy} \xB7 risk ${tier.tier}`);
38835
+ 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"] });
38836
+ try {
38837
+ await s.listTools();
38838
+ for (const st of p.steps) {
38839
+ const o = await s.callTool(st.tool, st.args);
38840
+ const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
38841
+ const blocked = /^Blocked by Saktum \(([^)]+)\): ([^.]+)/.exec(txt);
38842
+ log(blocked ? ` \u26D4 ${st.say}: blocked (${blocked[1]}): ${blocked[2]}` : ` \u2713 ${st.say}: ${txt.split("\n")[0]}`);
38843
+ }
38844
+ } finally {
38845
+ await s.close();
38846
+ await new Promise((r) => setTimeout(r, 300));
38847
+ }
38848
+ const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
38849
+ const counts = /* @__PURE__ */ new Map();
38850
+ for (const e of entries) {
38851
+ const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
38852
+ counts.set(k, (counts.get(k) ?? 0) + 1);
38853
+ }
38854
+ const html = join5(dir, `${p.id}-passport.html`);
38855
+ writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38856
+ verified: verifyReceiptLog(entries).ok,
38857
+ summary: summariseReceipts(entries),
38858
+ timeline: entries.map((e) => ({ tool: e.receipt.envelope.tool, outcome: e.receipt.outcome, status: e.result.status, repeated: (counts.get(`${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`) ?? 0) >= 3 }))
38859
+ }, tier));
38860
+ files.push(html);
38861
+ log(` ${entries.length} signed receipts \xB7 ${verifyReceiptLog(entries).ok ? "verified" : "NOT verified"} \xB7 passport: ${html}
38862
+ `);
38863
+ }
38864
+ 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.");
38865
+ return { files };
38866
+ }
38867
+ var PRODUCTS, DEMO_TOOLS, B, GROCERY_TOOLS, TRAVEL_TOOLS, FINANCE_TOOLS, SCRIPT, EXTRA, GROCERY, TRAVEL, FINANCE;
38868
+ var init_demo = __esm({
38869
+ "packages/cli/dist/demo.js"() {
38870
+ "use strict";
38871
+ init_server2();
38872
+ init_stdio3();
38873
+ init_types2();
38874
+ init_dist();
38875
+ init_dist3();
38876
+ init_dist4();
38877
+ init_dist5();
38878
+ PRODUCTS = [{ id: "oat-milk", name: "Oat milk 1 L", price: 4.49 }, { id: "bread", name: "Sourdough bread", price: 5.99 }, { id: "coffee", name: "Coffee beans 1 kg", price: 21.99 }];
38879
+ DEMO_TOOLS = [
38880
+ { name: "search_products", description: "Search the store's catalogue for products matching a query.", inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] }, annotations: { readOnlyHint: true, openWorldHint: false } },
38881
+ { name: "get_deals", description: "List this week's best deals on products the user usually buys.", inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true, openWorldHint: false } },
38882
+ { name: "add_to_cart", description: "Add a product to the user's cart.", inputSchema: { type: "object", properties: { product: { type: "string" }, quantity: { type: "integer", minimum: 1 } }, required: ["product", "quantity"] }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false } },
38883
+ { name: "pay_for_order", description: "Charges the customer's card for the cart total and places the order.", inputSchema: { type: "object", properties: { amount: { type: "number" }, currency: { type: "string" }, idempotency_key: { type: "string" } }, required: ["amount", "currency", "idempotency_key"] }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true } }
38884
+ ];
38885
+ B = (bindings, action) => ({ "io.saktum/bindings": bindings, "io.saktum/action": action });
38886
+ GROCERY_TOOLS = [
38887
+ { name: "search_products", description: "Search the store's catalogue for products matching a query.", inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] }, annotations: { readOnlyHint: true }, _meta: B({}, "search") },
38888
+ {
38889
+ name: "add_to_cart",
38890
+ description: "Add a product to the cart, or a substitute for an unavailable product.",
38891
+ inputSchema: { type: "object", properties: { product: { type: "string" }, brand: { type: "string" }, category: { type: "string" }, quantity: { type: "integer" }, price: { type: "number" }, substitute_for: { type: "string" }, reference_price: { type: "number" }, upgrade: { type: "boolean" }, sponsored: { type: "boolean" } }, required: ["product", "quantity", "price"] },
38892
+ annotations: { readOnlyHint: false, destructiveHint: false },
38893
+ _meta: B({ product: "commerce.item.product", brand: "commerce.item.brand", category: "commerce.item.category", quantity: "commerce.item.quantity", price: "commerce.item.unit_price", substitute_for: "commerce.item.substitute_for", reference_price: "commerce.item.reference_price", upgrade: "commerce.item.upgrade", sponsored: "commerce.item.sponsored" }, "cart")
38894
+ },
38895
+ {
38896
+ name: "pay_for_order",
38897
+ description: "Charges the customer's card for the cart total and places the order.",
38898
+ inputSchema: { type: "object", properties: { amount: { type: "number" }, currency: { type: "string" }, merchant: { type: "string" }, delivery_address: { type: "string" }, idempotency_key: { type: "string" } }, required: ["amount", "currency", "idempotency_key"] },
38899
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
38900
+ _meta: B({ amount: "commerce.order.total", currency: "commerce.order.currency", merchant: "commerce.counterparty", delivery_address: "personal.address" }, "pay")
38901
+ }
38902
+ ];
38903
+ TRAVEL_TOOLS = [
38904
+ { name: "search_flights", description: "Search flights between two cities on a date.", inputSchema: { type: "object", properties: { from: { type: "string" }, to: { type: "string" }, date: { type: "string" } }, required: ["from", "to", "date"] }, annotations: { readOnlyHint: true }, _meta: B({}, "search") },
38905
+ {
38906
+ name: "book_flight",
38907
+ description: "Book a flight itinerary for the traveller.",
38908
+ inputSchema: { type: "object", properties: { flight: { type: "string" }, fare: { type: "number" }, currency: { type: "string" }, stops: { type: "integer" }, refundable: { type: "boolean" }, carrier: { type: "string" }, passport_number: { type: "string" }, idempotency_key: { type: "string" } }, required: ["flight", "fare", "stops", "refundable"] },
38909
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
38910
+ _meta: B({ fare: "travel.fare.total", currency: "travel.fare.currency", stops: "travel.itinerary.connections", refundable: "travel.fare.refundable", carrier: "travel.carrier", passport_number: "personal.passport" }, "book")
38911
+ },
38912
+ { name: "share_traveller_details", description: "Share the traveller's details with a travel partner.", inputSchema: { type: "object", properties: { recipient: { type: "string" }, passport_number: { type: "string" }, email: { type: "string" } }, required: ["recipient"] }, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, _meta: B({ recipient: "party.recipient", passport_number: "personal.passport", email: "personal.email" }, "communicate") },
38913
+ { name: "change_seat", description: "Change the traveller's seat on a booked flight.", inputSchema: { type: "object", properties: { seat: { type: "string" }, fee: { type: "number" } }, required: ["seat", "fee"] }, annotations: { readOnlyHint: false, destructiveHint: false }, _meta: B({ seat: "travel.seat", fee: "travel.fee" }, "change") },
38914
+ { name: "upgrade_cabin", description: "Upgrade the traveller to a higher cabin for a fee.", inputSchema: { type: "object", properties: { cabin: { type: "string" }, fee: { type: "number" }, upgrade: { type: "boolean" } }, required: ["cabin", "fee"] }, annotations: { readOnlyHint: false, destructiveHint: false }, _meta: B({ fee: "travel.fee", upgrade: "travel.upgrade" }, "change") }
38915
+ ];
38916
+ FINANCE_TOOLS = [
38917
+ { name: "send_report", description: "Send a report to a recipient.", inputSchema: { type: "object", properties: { recipient: { type: "string" }, report: { type: "string" }, data_class: { type: "string" } }, required: ["recipient", "report", "data_class"] }, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, _meta: B({ recipient: "party.recipient", data_class: "enterprise.data_class" }, "communicate") },
38918
+ { name: "pay_invoice", description: "Pays a vendor invoice from the company account.", inputSchema: { type: "object", properties: { amount: { type: "number" }, currency: { type: "string" }, vendor: { type: "string" }, idempotency_key: { type: "string" } }, required: ["amount", "currency", "vendor", "idempotency_key"] }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }, _meta: B({ amount: "commerce.order.total", currency: "commerce.order.currency", vendor: "enterprise.vendor" }, "pay") }
38919
+ ];
38920
+ SCRIPT = [
38921
+ { tool: "get_deals", args: {}, say: "checks this week's deals" },
38922
+ { tool: "search_products", args: { query: "coffee" }, say: "searches for coffee" },
38923
+ { tool: "add_to_cart", args: { product: "coffee", quantity: 1 }, say: "adds coffee beans to the cart" },
38924
+ { tool: "pay_for_order", args: { amount: 18, currency: "CAD", idempotency_key: "order-1" }, say: "tries to pay $18" }
38925
+ ];
38926
+ EXTRA = [
38927
+ { tool: "pay_for_order", args: { amount: 30, currency: "CAD", idempotency_key: "order-2" }, say: "tries to pay $30" },
38928
+ { tool: "pay_for_order", args: { amount: 80, currency: "CAD", idempotency_key: "order-3" }, say: "tries to pay $80" },
38929
+ { tool: "pay_for_order", args: { amount: 10, currency: "USD", idempotency_key: "order-4" }, say: "tries to pay $10 in USD" }
38930
+ ];
38931
+ GROCERY = { id: "grocery", title: 'Grocery: "weekly groceries, my usual brands"', server: "grocery", tools: GROCERY_TOOLS.map((t) => t.name), m: {
38932
+ autonomy: "act",
38933
+ purpose: "Weekly groceries for the family",
38934
+ actions: [{ cls: "search", autonomy: "act" }, { cls: "cart", autonomy: "act" }, { cls: "pay", autonomy: "act" }],
38935
+ rules: [{ field: "commerce.item.quantity", op: "max", value: 2, label: "at most 2 of each item" }, { field: "commerce.item.category", op: "notIn", value: ["alcohol"], label: "never alcohol" }, { field: "commerce.order.total", op: "max", value: 150, label: "up to $150 per order" }],
38936
+ substitution: { allowed: true, maxPriceChangePct: 10, neverFor: ["baby food"] },
38937
+ upsell: "ask",
38938
+ preferences: [{ field: "commerce.item.brand", prefer: "Usual Farms", label: "the usual brand, Usual Farms" }],
38939
+ counterparties: ["Demo Grocer"],
38940
+ dataSharing: [{ data: "delivery address", to: "Demo Grocer" }],
38941
+ disclosures: { operator: "Demo Grocer", incentives: "Sponsored products are labelled", dataUse: "Order history used only for your lists" }
38942
+ }, steps: [
38943
+ { tool: "search_products", args: { query: "milk" }, say: "searches the catalogue" },
38944
+ { tool: "add_to_cart", args: { product: "Oat milk", brand: "Usual Farms", category: "dairy", quantity: 1, price: 4.49 }, say: "adds oat milk" },
38945
+ { tool: "add_to_cart", args: { product: "Apples", brand: "Usual Farms", category: "produce", quantity: 5, price: 0.8 }, say: "adds 5 bags of apples" },
38946
+ { tool: "add_to_cart", args: { product: "Rye bread", brand: "Bakehouse", category: "bakery", quantity: 1, price: 6.35, substitute_for: "Sourdough bread", reference_price: 5.99 }, say: "substitutes rye for the out-of-stock sourdough (+6%)" },
38947
+ { tool: "add_to_cart", args: { product: "Baby oatmeal", brand: "Other Co", category: "baby food", quantity: 1, price: 4.2, substitute_for: "Usual Farms baby oatmeal", reference_price: 4.1 }, say: "substitutes another brand of baby oatmeal" },
38948
+ { tool: "add_to_cart", args: { product: "Premium coffee 2 kg", brand: "Usual Farms", category: "coffee", quantity: 1, price: 39.99, upgrade: true }, say: "upgrades coffee to the premium 2 kg bag" },
38949
+ { tool: "add_to_cart", args: { product: "Snack bar", brand: "Promo", category: "snacks", quantity: 1, price: 3.99, sponsored: true }, say: "adds a sponsored snack bar" },
38950
+ { tool: "add_to_cart", args: { product: "Red wine", brand: "Cellar", category: "alcohol", quantity: 1, price: 14.99 }, say: "adds a bottle of wine" },
38951
+ { tool: "add_to_cart", args: { product: "Gift card $50", category: "gift cards", quantity: 10, price: 50 }, say: "is tricked by a hidden instruction in a listing: adds 10 gift cards" },
38952
+ { tool: "pay_for_order", args: { amount: 90, currency: "CAD", merchant: "QuickCash", idempotency_key: "g-x" }, say: "is tricked into paying $90 to QuickCash" },
38953
+ { tool: "pay_for_order", args: { amount: 68.4, currency: "CAD", merchant: "Demo Grocer", delivery_address: "12 King St, Toronto", idempotency_key: "g-1" }, say: "pays $68.40 to Demo Grocer, with your delivery address" },
38954
+ { tool: "pay_for_order", args: { amount: 180, currency: "CAD", merchant: "Demo Grocer", idempotency_key: "g-2" }, say: "tries to pay $180" }
38955
+ ] };
38956
+ TRAVEL = { id: "travel", title: 'Travel: "business trip to Montreal, refundable, at most one stop"', server: "travel", tools: TRAVEL_TOOLS.map((t) => t.name), m: {
38957
+ autonomy: "act",
38958
+ purpose: "Business trip to Montreal, 3 to 4 March",
38959
+ actions: [{ cls: "search", autonomy: "act" }, { cls: "book", autonomy: "act" }, { cls: "change", autonomy: "act" }],
38960
+ rules: [{ field: "travel.fare.total", op: "max", value: 600, label: "fare up to $600" }, { field: "travel.itinerary.connections", op: "max", value: 1, label: "at most one connection" }, { field: "travel.fare.refundable", op: "eq", value: true, label: "refundable fares only" }],
38961
+ upsell: "ask",
38962
+ approvalTriggers: ["fee"],
38963
+ preferences: [{ field: "travel.seat", prefer: "aisle", label: "an aisle seat" }, { field: "travel.carrier", prefer: "Maple Air", label: "Maple Air (loyalty)" }],
38964
+ dataSharing: [{ data: "passport", to: "Maple Air" }],
38965
+ disclosures: { operator: "Demo Travel", incentives: "No commissions affect choices", dataUse: "Trip details used only for this booking" }
38966
+ }, steps: [
38967
+ { tool: "search_flights", args: { from: "YYZ", to: "YUL", date: "2027-03-03" }, say: "searches flights" },
38968
+ { tool: "book_flight", args: { flight: "BJ 210", fare: 420, currency: "CAD", stops: 2, refundable: true, carrier: "Budget Jet", idempotency_key: "t-1" }, say: "tries the cheapest fare (2 stops, $420)" },
38969
+ { tool: "book_flight", args: { flight: "DA 101", fare: 380, currency: "CAD", stops: 0, refundable: false, carrier: "Direct Air", idempotency_key: "t-2" }, say: "tries a direct non-refundable fare ($380)" },
38970
+ { tool: "book_flight", args: { flight: "MA 330", fare: 540, currency: "CAD", stops: 1, refundable: true, carrier: "Maple Air", passport_number: "X1234567", idempotency_key: "t-3" }, say: "books Maple Air, 1 stop, refundable ($540), with your passport" },
38971
+ { tool: "share_traveller_details", args: { recipient: "Hotel Partner", passport_number: "X1234567" }, say: "tries to share your passport with a hotel partner" },
38972
+ { tool: "change_seat", args: { seat: "aisle", fee: 0 }, say: "changes to a free aisle seat" },
38973
+ { tool: "change_seat", args: { seat: "window, extra legroom", fee: 45 }, say: "tries a $45 extra-legroom seat" },
38974
+ { tool: "upgrade_cabin", args: { cabin: "business", fee: 120, upgrade: true }, say: "tries a $120 business upgrade" }
38975
+ ] };
38976
+ FINANCE = { id: "finance", title: 'Finance: "month-end operations; confidential data only to the auditor; I approve big invoices"', server: "finance", tools: FINANCE_TOOLS.map((t) => t.name), m: {
38977
+ autonomy: "act",
38978
+ purpose: "Month-end finance operations",
38979
+ actions: [{ cls: "communicate", autonomy: "act" }, { cls: "pay", autonomy: "act" }],
38980
+ rules: [{ field: "commerce.order.total", op: "max", value: 5e4, label: "invoices up to $50,000" }],
38981
+ approveAbove: { arg: "amount", value: 1e4 },
38982
+ dataSharing: [{ data: "internal", to: "Finance team" }, { data: "confidential", to: "External Auditor" }],
38983
+ disclosures: { operator: "Acme Corp IT", incentives: "None", dataUse: "Company data stays within the recipients listed" }
38984
+ }, steps: [
38985
+ { tool: "send_report", args: { recipient: "Finance team", report: "Month-end close summary", data_class: "internal" }, say: "sends the internal close summary to the finance team" },
38986
+ { tool: "send_report", args: { recipient: "Partner Agency", report: "Q1 forecast", data_class: "confidential" }, say: "tries to send the confidential forecast to a partner agency" },
38987
+ { tool: "send_report", args: { recipient: "External Auditor", report: "Q4 results", data_class: "confidential" }, say: "sends confidential results to the external auditor" },
38988
+ { tool: "pay_invoice", args: { amount: 4200, currency: "CAD", vendor: "Cloud Hosting Inc", idempotency_key: "f-1" }, say: "pays a $4,200 hosting invoice" },
38989
+ { tool: "pay_invoice", args: { amount: 12e3, currency: "CAD", vendor: "Consulting LLP", idempotency_key: "f-2" }, say: "tries to pay a $12,000 consulting invoice" },
38990
+ { tool: "", args: {}, say: "you approve exactly that invoice (saktum agent approve)", approveLast: true },
38991
+ { tool: "pay_invoice", args: { amount: 12e3, currency: "CAD", vendor: "Consulting LLP", idempotency_key: "f-2" }, say: "retries the same $12,000 invoice" }
38992
+ ] };
38993
+ }
38994
+ });
38995
+
37093
38996
  // packages/cli/dist/mcp-server.js
37094
38997
  var mcp_server_exports = {};
37095
38998
  __export(mcp_server_exports, {
@@ -37098,7 +39001,7 @@ __export(mcp_server_exports, {
37098
39001
  splitTarget: () => splitTarget,
37099
39002
  startMcpServer: () => startMcpServer
37100
39003
  });
37101
- import { readFileSync as readFileSync6 } from "node:fs";
39004
+ import { readFileSync as readFileSync8 } from "node:fs";
37102
39005
  function splitTarget(target) {
37103
39006
  const t = target.trim();
37104
39007
  if (/^https?:\/\//i.test(t))
@@ -37134,7 +39037,7 @@ async function handleSaktumTool(name, args, packs) {
37134
39037
  case "diff_against_lock": {
37135
39038
  if (typeof args.lock_path !== "string")
37136
39039
  throw new Error("lock_path is required");
37137
- const before = JSON.parse(readFileSync6(args.lock_path, "utf8"));
39040
+ const before = JSON.parse(readFileSync8(args.lock_path, "utf8"));
37138
39041
  const d = diffLocks(before, { tools: (await listTools(targetOf(args.target))).tools });
37139
39042
  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 });
37140
39043
  }
@@ -37275,7 +39178,7 @@ var init_mcp_server = __esm({
37275
39178
  });
37276
39179
 
37277
39180
  // packages/cli/dist/main.js
37278
- import { existsSync as existsSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "node:fs";
39181
+ import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
37279
39182
  import { fileURLToPath as fileURLToPath2 } from "node:url";
37280
39183
 
37281
39184
  // node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
@@ -37442,13 +39345,13 @@ init_dist3();
37442
39345
  var SEV2 = ["critical", "high", "medium", "low", "info"];
37443
39346
  async function loadPolicy(file) {
37444
39347
  const { readFileSync: rf, existsSync: ex } = await import("node:fs");
37445
- const { dirname: dirname3, resolve } = await import("node:path");
39348
+ const { dirname: dirname4, resolve } = await import("node:path");
37446
39349
  if (!ex(file))
37447
39350
  throw new Error(`Policy file not found: ${file}`);
37448
39351
  const policy = await parsePolicy(rf(file, "utf8"));
37449
39352
  let allow;
37450
39353
  if (policy.allowlist) {
37451
- const path = resolve(dirname3(file), policy.allowlist);
39354
+ const path = resolve(dirname4(file), policy.allowlist);
37452
39355
  if (!ex(path))
37453
39356
  throw new Error(`The policy's allowlist was not found: ${policy.allowlist}`);
37454
39357
  allow = new Set(JSON.parse(rf(path, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f)));
@@ -37469,6 +39372,7 @@ var WELCOME = `Saktum Check \u2014 make the tools AI agents use trustworthy.
37469
39372
 
37470
39373
  What would you like to do?
37471
39374
 
39375
+ 0. See it in 60 seconds npx saktum demo
37472
39376
  1. Test an MCP server npx saktum check -- npx -y some-mcp-server
37473
39377
  npx saktum check https://your-server.example/mcp
37474
39378
  2. Start a new MCP server npx saktum init my-server --lang ts (or --lang py)
@@ -37510,16 +39414,16 @@ async function main(argv = process.argv) {
37510
39414
  });
37511
39415
  let testCases;
37512
39416
  if (o.tests) {
37513
- if (!existsSync5(o.tests))
39417
+ if (!existsSync7(o.tests))
37514
39418
  throw new Error(`Test file not found: ${o.tests}. See docs/TESTS.md for the format.`);
37515
- testCases = await parseTestCases(readFileSync7(o.tests, "utf8"));
39419
+ testCases = await parseTestCases(readFileSync9(o.tests, "utf8"));
37516
39420
  }
37517
39421
  const target = parseTarget(targetParts);
37518
39422
  if (target.kind === "stdio" && o.env.length)
37519
39423
  target.env = parseEnv(o.env);
37520
39424
  if (target.kind === "streamable-http" && o.header.length)
37521
39425
  target.headers = parseHeaders(o.header);
37522
- const packs = o.packs ? loadPackDir(o.packs) : existsSync5(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39426
+ const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
37523
39427
  let result;
37524
39428
  try {
37525
39429
  result = await runTrustCheck(target, { packs, mode: o.active ? "active" : "passive", pricePerMTokUsd: price, callTools: o.call, testCases, ignore });
@@ -37531,23 +39435,23 @@ async function main(argv = process.argv) {
37531
39435
  return 2;
37532
39436
  }
37533
39437
  const signed = signDocument(result, loadOrCreateKey(o.key));
37534
- writeFileSync3(o.out, JSON.stringify(signed, null, 2));
39438
+ writeFileSync5(o.out, JSON.stringify(signed, null, 2));
37535
39439
  if (o.html)
37536
- writeFileSync3(o.html, renderHtml(signed));
39440
+ writeFileSync5(o.html, renderHtml(signed));
37537
39441
  if (o.badge)
37538
- writeFileSync3(o.badge, badgeSvg(signed));
39442
+ writeFileSync5(o.badge, badgeSvg(signed));
37539
39443
  const keyOf = (f) => `${f.check}:${f.subject ?? ""}`;
37540
39444
  const failing = signed.findings.filter((f) => f.status === "fail" && !f.suppressed);
37541
39445
  let accepted = /* @__PURE__ */ new Set();
37542
39446
  if (o.baseline && o.updateBaseline) {
37543
- writeFileSync3(o.baseline, JSON.stringify({ baselineFormat: "0.1", createdAt: (/* @__PURE__ */ new Date()).toISOString(), accepted: failing.map((f) => ({ check: f.check, subject: f.subject, severity: f.severity, title: f.title })) }, null, 2) + "\n");
39447
+ writeFileSync5(o.baseline, JSON.stringify({ baselineFormat: "0.1", createdAt: (/* @__PURE__ */ new Date()).toISOString(), accepted: failing.map((f) => ({ check: f.check, subject: f.subject, severity: f.severity, title: f.title })) }, null, 2) + "\n");
37544
39448
  process.stdout.write(`Wrote baseline ${sanitizeText(o.baseline)} accepting ${failing.length} existing finding(s). Commit it; later runs fail only on new findings.
37545
39449
  `);
37546
- } else if (o.baseline && existsSync5(o.baseline)) {
37547
- accepted = new Set(JSON.parse(readFileSync7(o.baseline, "utf8")).accepted.map(keyOf));
39450
+ } else if (o.baseline && existsSync7(o.baseline)) {
39451
+ accepted = new Set(JSON.parse(readFileSync9(o.baseline, "utf8")).accepted.map(keyOf));
37548
39452
  }
37549
39453
  if (o.sarif)
37550
- writeFileSync3(o.sarif, JSON.stringify(toSarif(signed, o.sarifAnchor, accepted), null, 2) + "\n");
39454
+ writeFileSync5(o.sarif, JSON.stringify(toSarif(signed, o.sarifAnchor, accepted), null, 2) + "\n");
37551
39455
  process.stdout.write(renderTerminal(signed) + "\n");
37552
39456
  process.stdout.write(`
37553
39457
  Signed result: ${sanitizeText(o.out)} (verify with: saktum verify ${sanitizeText(o.out)})${o.badge ? `
@@ -37616,7 +39520,7 @@ Watching ${sanitizeText(o.watchDir)} for changes (Ctrl+C to stop).
37616
39520
  exitCode = await runCheckCommand(targetParts, o);
37617
39521
  });
37618
39522
  program2.command("checks").description("List every check: what it tests, the standard behind it, and when it runs").option("--markdown", "print a Markdown table (as in docs/CHECKS.md)", false).option("--packs <dir>", "directory of packs (default: the built-in packs)").action((o) => {
37619
- const packs = o.packs ? loadPackDir(o.packs) : existsSync5(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39523
+ const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
37620
39524
  process.stdout.write(checksTable(packs, o.markdown));
37621
39525
  });
37622
39526
  const listTarget = async (targetParts, env, header) => {
@@ -37638,13 +39542,13 @@ Watching ${sanitizeText(o.watchDir)} for changes (Ctrl+C to stop).
37638
39542
  });
37639
39543
  program2.command("snapshot").description("Write a lock file of the server's tools, to detect breaking or silent changes later with saktum diff").argument("<target...>", "https://host/mcp or -- node server.js").option("--out <file>", "lock file", "saktum.lock.json").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 (targetParts, o) => {
37640
39544
  const { tools, server } = await listTarget(targetParts, o.env, o.header);
37641
- writeFileSync3(o.out, JSON.stringify(toolsLock(tools, server), null, 2) + "\n");
39545
+ writeFileSync5(o.out, JSON.stringify(toolsLock(tools, server), null, 2) + "\n");
37642
39546
  process.stdout.write(`Wrote ${sanitizeText(o.out)} with ${tools.length} tools. Commit it; run saktum diff in CI to catch breaking or silent changes.
37643
39547
  `);
37644
39548
  });
37645
39549
  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) => {
37646
- const before = JSON.parse(readFileSync7(lock, "utf8"));
37647
- const after = rest.length === 1 && rest[0].endsWith(".json") ? JSON.parse(readFileSync7(rest[0], "utf8")) : { tools: (await listTarget(rest, o.env, o.header)).tools };
39550
+ const before = JSON.parse(readFileSync9(lock, "utf8"));
39551
+ const after = rest.length === 1 && rest[0].endsWith(".json") ? JSON.parse(readFileSync9(rest[0], "utf8")) : { tools: (await listTarget(rest, o.env, o.header)).tools };
37648
39552
  const d = diffLocks(before, after);
37649
39553
  const mark2 = { breaking: "\u2717 BREAKING", risky: "! REVIEW ", addition: "+ ADDED ", change: "~ CHANGED " };
37650
39554
  for (const c of d.changes)
@@ -37661,11 +39565,11 @@ ${d.summary}
37661
39565
  process.stdout.write(docsFor(tools, name, target.kind === "stdio" ? { command: target.command, args: target.args } : { url: target.url }));
37662
39566
  });
37663
39567
  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) => {
37664
- const doc = JSON.parse(readFileSync7(file, "utf8"));
39568
+ const doc = JSON.parse(readFileSync9(file, "utf8"));
37665
39569
  const v = verifyDocument(doc);
37666
39570
  if (!v.valid)
37667
39571
  throw new Error(`The result's signature is not valid (${v.reason}); a packet must be built from an unaltered signed result.`);
37668
- writeFileSync3(o.out, renderPacket(doc, v.kid));
39572
+ writeFileSync5(o.out, renderPacket(doc, v.kid));
37669
39573
  process.stdout.write(`Wrote ${sanitizeText(o.out)}: open it in a browser and print to PDF. Send it with ${sanitizeText(file)} so customers can verify it.
37670
39574
  `);
37671
39575
  });
@@ -37675,9 +39579,9 @@ ${d.summary}
37675
39579
  const check = verifyLedger(entries);
37676
39580
  if (!check.ok)
37677
39581
  throw new Error(`The ledger does not verify: ${check.errors[0]}`);
37678
- const signers = o.trustedSigners ? new Set(readFileSync7(o.trustedSigners, "utf8").split(/\r?\n/).map((l) => l.trim()).filter(Boolean)) : void 0;
39582
+ const signers = o.trustedSigners ? new Set(readFileSync9(o.trustedSigners, "utf8").split(/\r?\n/).map((l) => l.trim()).filter(Boolean)) : void 0;
37679
39583
  const list2 = allowlistFromLedger(entries, { minTrust: o.minTrust.toUpperCase(), minReadiness: o.minReadiness.toUpperCase(), trustedSigners: signers });
37680
- writeFileSync3(o.out, JSON.stringify(list2, null, 2) + "\n");
39584
+ writeFileSync5(o.out, JSON.stringify(list2, null, 2) + "\n");
37681
39585
  process.stdout.write(`Ledger verified (${check.count} entries). Wrote ${sanitizeText(o.out)}: ${list2.allowed.length} allowed, ${list2.excluded.length} excluded.
37682
39586
  `);
37683
39587
  return;
@@ -37685,14 +39589,14 @@ ${d.summary}
37685
39589
  if (!files.length)
37686
39590
  throw new Error("Give signed results, or use --from-ledger.");
37687
39591
  const inputs = files.map((f) => {
37688
- const doc = JSON.parse(readFileSync7(f, "utf8"));
39592
+ const doc = JSON.parse(readFileSync9(f, "utf8"));
37689
39593
  const v = verifyDocument(doc);
37690
39594
  if (!v.valid)
37691
39595
  throw new Error(`${f}: signature not valid (${v.reason}); only unaltered signed results can be allowlisted.`);
37692
39596
  return { result: doc, signedBy: v.kid };
37693
39597
  });
37694
39598
  const list = buildAllowlist(inputs, { minTrust: o.minTrust.toUpperCase(), minReadiness: o.minReadiness.toUpperCase(), noFailedCritical: !o.allowCritical });
37695
- writeFileSync3(o.out, JSON.stringify(list, null, 2) + "\n");
39599
+ writeFileSync5(o.out, JSON.stringify(list, null, 2) + "\n");
37696
39600
  for (const a of list.allowed)
37697
39601
  process.stdout.write(`\u2713 ${sanitizeText(a.server, 60)} ${sanitizeText(a.version ?? "", 20)} trust ${a.trustGrade} \xB7 readiness ${a.readinessGrade} \xB7 ${a.toolCount} tools pinned
37698
39602
  `);
@@ -37729,7 +39633,7 @@ Next:
37729
39633
  ${findings.length} finding(s) in tool definitions.
37730
39634
  ` : "No problems found in tool definitions (files importing an MCP SDK).\n");
37731
39635
  if (o.sarif)
37732
- writeFileSync3(o.sarif, JSON.stringify(lintSarif(findings, ENGINE_VERSION), null, 2) + "\n");
39636
+ writeFileSync5(o.sarif, JSON.stringify(lintSarif(findings, ENGINE_VERSION), null, 2) + "\n");
37733
39637
  exitCode = findings.some((f) => f.severity === "error" || o.strict) ? 1 : 0;
37734
39638
  });
37735
39639
  program2.command("call").description("Call one tool and show the result; --save-test turns the call into a test case (save as test)").argument("<tool>", "tool name").argument("<target...>", "https://host/mcp or -- node server.js").option("--args <json>", "arguments as JSON", "{}").option("--save-test <id>", "append this call and its result as a test case").option("--tests <file>", "test file to append to", "saktum.tests.yaml").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 (toolName, targetParts, o) => {
@@ -37772,7 +39676,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
37772
39676
  expect.outputSchema = true;
37773
39677
  expect.latencyMs = { lt: Math.max(2e3, outcome.latencyMs * 5) };
37774
39678
  const tc = { id: o.saveTest, tool: toolName, input: args, ...tool.annotations?.readOnlyHint === true ? {} : { sideEffects: true }, expect };
37775
- writeFileSync3(o.tests, await appendTestCase(existsSync5(o.tests) ? readFileSync7(o.tests, "utf8") : void 0, tc));
39679
+ writeFileSync5(o.tests, await appendTestCase(existsSync7(o.tests) ? readFileSync9(o.tests, "utf8") : void 0, tc));
37776
39680
  process.stdout.write(`Saved test case ${sanitizeText(o.saveTest, 60)} to ${sanitizeText(o.tests)}. Run: saktum test -- <start command>
37777
39681
  `);
37778
39682
  }
@@ -37780,7 +39684,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
37780
39684
  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) => {
37781
39685
  const { homedir: homedir2 } = await import("node:os");
37782
39686
  const locations = o.config.length ? o.config.map((file) => ({ client: "configuration", file })) : configLocations(homedir2(), process.cwd(), process.platform, process.env.APPDATA);
37783
- const servers = locations.filter((l) => existsSync5(l.file)).flatMap((l) => parseClientConfig(readFileSync7(l.file, "utf8"), l.client, l.file)).filter((x) => !x.disabled);
39687
+ const servers = locations.filter((l) => existsSync7(l.file)).flatMap((l) => parseClientConfig(readFileSync9(l.file, "utf8"), l.client, l.file)).filter((x) => !x.disabled);
37784
39688
  if (!servers.length) {
37785
39689
  process.stdout.write("No MCP servers found in the known configuration locations. Point to one with --config <file>.\n");
37786
39690
  return;
@@ -37803,7 +39707,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
37803
39707
  return;
37804
39708
  }
37805
39709
  }
37806
- const packs = existsSync5(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39710
+ const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
37807
39711
  const scans = [];
37808
39712
  for (const x of servers) {
37809
39713
  let tools = [];
@@ -37830,7 +39734,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
37830
39734
  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) });
37831
39735
  }
37832
39736
  }
37833
- const allow = o.allowlist ? new Set(JSON.parse(readFileSync7(o.allowlist, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f))) : void 0;
39737
+ const allow = o.allowlist ? new Set(JSON.parse(readFileSync9(o.allowlist, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f))) : void 0;
37834
39738
  const report = analyseSetup(scans, { turnsPerDay: Number(o.turnsPerDay) || 50, pricePerMTokUsd: Number(o.pricePerMtok) || 3, allowlistFingerprints: allow });
37835
39739
  process.stdout.write("\n" + renderSetup(report));
37836
39740
  if (o.policy) {
@@ -37843,10 +39747,10 @@ POLICY${policy.name ? ` (${sanitizeText(policy.name, 80)})` : ""}
37843
39747
  }
37844
39748
  const { hostname } = await import("node:os");
37845
39749
  if (o.out)
37846
- writeFileSync3(o.out, JSON.stringify({ ...report, machine: o.machine ?? hostname() }, null, 2) + "\n");
39750
+ writeFileSync5(o.out, JSON.stringify({ ...report, machine: o.machine ?? hostname() }, null, 2) + "\n");
37847
39751
  });
37848
39752
  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) => {
37849
- const r = verifyCredentialJwt(readFileSync7(f, "utf8"));
39753
+ const r = verifyCredentialJwt(readFileSync9(f, "utf8"));
37850
39754
  if (r.valid) {
37851
39755
  const cs = r.credential.credentialSubject ?? {};
37852
39756
  process.stdout.write(`\u2713 Valid credential from ${r.issuer}: ${sanitizeText(String(cs.server ?? ""), 80)} trust ${cs.trustGrade ?? "-"}, readiness ${cs.readinessGrade ?? "-"}.
@@ -37879,50 +39783,127 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
37879
39783
  const v = verifyLedger(entries);
37880
39784
  if (!v.ok)
37881
39785
  throw new Error(`The ledger does not verify: ${v.errors[0]}`);
37882
- const { mkdirSync: mkdirSync4 } = await import("node:fs");
37883
- mkdirSync4(o.out, { recursive: true });
39786
+ const { mkdirSync: mkdirSync6 } = await import("node:fs");
39787
+ mkdirSync6(o.out, { recursive: true });
37884
39788
  const latest = /* @__PURE__ */ new Map();
37885
39789
  for (const e of entries)
37886
39790
  latest.set(e.subject.server, e);
37887
39791
  for (const e of latest.values())
37888
- writeFileSync3(`${o.out}/${passportSlug(e.subject.server)}.html`, renderLedgerPassport(e));
37889
- writeFileSync3(`${o.out}/index.html`, renderPassportGallery(entries));
39792
+ writeFileSync5(`${o.out}/${passportSlug(e.subject.server)}.html`, renderLedgerPassport(e));
39793
+ writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries));
37890
39794
  process.stdout.write(`Wrote ${latest.size} passport page(s) and the gallery to ${sanitizeText(o.out)}.
37891
39795
  `);
37892
39796
  });
37893
39797
  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) => {
37894
- const att = extractJson(readFileSync7(input, "utf8"));
37895
- const { text: text2, entry } = appendToLedger(existsSync5(o.ledger) ? readFileSync7(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
37896
- writeFileSync3(o.ledger, text2);
39798
+ const att = extractJson(readFileSync9(input, "utf8"));
39799
+ const { text: text2, entry } = appendToLedger(existsSync7(o.ledger) ? readFileSync9(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
39800
+ writeFileSync5(o.ledger, text2);
37897
39801
  process.stdout.write(`Recorded entry #${entry.seq} for ${sanitizeText(entry.subject.server, 80)} (signed by ${entry.signer}); entry hash ${entry.entryHash}.
37898
39802
  `);
37899
39803
  });
37900
39804
  const agent = program2.command("agent").description("Agent identity: give an agent its own key and a mandate signed by its owner (preview)");
37901
- agent.command("create").description("Create an agent identity (did:key) and a mandate you sign: allowed servers and tools, destructive actions, expiry").requiredOption("--name <name>", 'agent name, for example "Billing assistant"').option("--purpose <text>", "what the agent is for").option("--owner-name <name>", "your name or team, shown in receipts").option("--allow-server <name>", "server the agent may use (repeatable; default: any)", collect, []).option("--allow-tool <name>", "tool the agent may use (repeatable; default: any)", collect, []).option("--allow-destructive", "allow tools declared destructive", false).option("--expires <date>", "last valid day, YYYY-MM-DD", new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10)).option("--out <file>", "mandate file", "agent-mandate.json").option("--agent-key <file>", "where to keep the agent's own key", "agent-key.json").option("--key <file>", "your (owner's) signing key").action((o) => {
39805
+ agent.command("create").description("Create an agent identity (did:key) and a mandate you sign: allowed servers and tools, destructive actions, expiry").requiredOption("--name <name>", 'agent name, for example "Billing assistant"').option("--purpose <text>", "what the agent is for").option("--owner-name <name>", "your name or team, shown in receipts").option("--allow-server <name>", "server the agent may use (repeatable; default: any)", collect, []).option("--allow-tool <name>", "tool the agent may use (repeatable; default: any)", collect, []).option("--allow-destructive", "allow tools declared destructive", false).option("--autonomy <level>", "notify (only alert), propose (suggest, the user approves) or act (within the limits)", "propose").option("--max <tool.arg=value>", "cap a numeric argument, for example checkout.amount=50 (repeatable)", collect, []).option("--allow-value <tool.arg=v1,v2>", "allowed values for an argument, for example checkout.currency=CAD (repeatable)", collect, []).option("--daily-calls <n>", "at most this many actions a day").option("--daily-total <arg=max>", "at most this total a day for an argument, for example amount=200").option("--approve-above <arg=value>", "ask the user above this value, for example amount=25").option("--operator <name>", "who operates the agent (disclosure)").option("--incentives <text>", "incentives that could influence the agent, for example sponsored products (disclosure)").option("--data-use <text>", "what the agent does with the user's data (disclosure)").option("--allow-delegation", "allow the agent to hand work to other agents", false).option("--software <name@version>", "the agent software that will act under this mandate").option("--intent <file>", "instructions as JSON: purpose, actions, rules, preferences, substitution, upsell, approvalTriggers, counterparties, dataSharing (see examples/mandate-grocery.json)").option("--expires <date>", "last valid day, YYYY-MM-DD", new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10)).option("--out <file>", "mandate file", "agent-mandate.json").option("--agent-key <file>", "where to keep the agent's own key", "agent-key.json").option("--key <file>", "your (owner's) signing key").action((o) => {
37902
39806
  if (!/^\d{4}-\d{2}-\d{2}$/.test(o.expires))
37903
39807
  throw new Error("--expires must be YYYY-MM-DD");
39808
+ if (!["notify", "propose", "act"].includes(o.autonomy))
39809
+ throw new Error("--autonomy must be notify, propose or act");
39810
+ const ta = (x, flag) => {
39811
+ const m2 = /^([^.=]+)\.([^=]+)=(.+)$/.exec(x);
39812
+ if (!m2)
39813
+ throw new Error(`${flag} must look like tool.arg=value`);
39814
+ return { tool: m2[1], arg: m2[2], value: m2[3] };
39815
+ };
39816
+ const av = (x, flag) => {
39817
+ const m2 = /^([^=]+)=(-?[\d.]+)$/.exec(x);
39818
+ if (!m2)
39819
+ throw new Error(`${flag} must look like arg=number`);
39820
+ return { arg: m2[1], value: Number(m2[2]) };
39821
+ };
39822
+ const constraints = [...o.max.map((x) => {
39823
+ const t = ta(x, "--max");
39824
+ return { tool: t.tool, arg: t.arg, max: Number(t.value) };
39825
+ }), ...o.allowValue.map((x) => {
39826
+ const t = ta(x, "--allow-value");
39827
+ return { tool: t.tool, arg: t.arg, oneOf: t.value.split(",").map((v) => v.trim()) };
39828
+ })];
39829
+ const dt = o.dailyTotal ? av(o.dailyTotal, "--daily-total") : void 0, aa = o.approveAbove ? av(o.approveAbove, "--approve-above") : void 0;
37904
39830
  const agentKey = loadOrCreateKey(o.agentKey);
37905
- const m = createMandate({ agentId: agentKey.kid, agentName: o.name, ownerName: o.ownerName, purpose: o.purpose, servers: o.allowServer, tools: o.allowTool, destructive: o.allowDestructive, expires: o.expires }, loadOrCreateKey(o.key));
37906
- writeFileSync3(o.out, JSON.stringify(m, null, 2) + "\n");
39831
+ const m = createMandate({
39832
+ agentId: agentKey.kid,
39833
+ agentName: o.name,
39834
+ ownerName: o.ownerName,
39835
+ purpose: o.purpose,
39836
+ servers: o.allowServer,
39837
+ tools: o.allowTool,
39838
+ destructive: o.allowDestructive,
39839
+ expires: o.expires,
39840
+ autonomy: o.autonomy,
39841
+ constraints,
39842
+ limits: { ...o.dailyCalls ? { callsPerDay: Number(o.dailyCalls) } : {}, ...dt ? { totalPerDay: { arg: dt.arg, max: dt.value } } : {} },
39843
+ approveAbove: aa,
39844
+ disclosures: { ...o.operator ? { operator: o.operator } : {}, ...o.incentives ? { incentives: o.incentives } : {}, ...o.dataUse ? { dataUse: o.dataUse } : {} },
39845
+ delegation: o.allowDelegation,
39846
+ ...o.intent ? JSON.parse(readFileSync9(o.intent, "utf8")) : {}
39847
+ }, loadOrCreateKey(o.key));
39848
+ if (o.software) {
39849
+ const { signature: _old, ...body2 } = m;
39850
+ body2.agent = { ...body2.agent, software: o.software };
39851
+ Object.assign(m, signDocument(body2, loadOrCreateKey(o.key)));
39852
+ }
39853
+ const valid = compileContract("mandate.schema.json");
39854
+ if (!valid(m))
39855
+ throw new Error(`The mandate is not valid: ${(valid.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}`);
39856
+ writeFileSync5(o.out, JSON.stringify(m, null, 2) + "\n");
39857
+ for (const line of describeMandate(m))
39858
+ process.stdout.write(` ${line}
39859
+ `);
37907
39860
  process.stdout.write(`Agent ${sanitizeText(o.name, 80)}: ${agentKey.kid}
37908
- Mandate signed by ${m.owner.id}, valid until ${o.expires}: ${m.allow.servers ? `servers ${m.allow.servers.join(", ")}` : "any server"}; ${m.allow.tools ? `tools ${m.allow.tools.join(", ")}` : "any tool"}; destructive actions ${m.allow.destructive ? "allowed" : "not allowed"}.
39861
+ Mandate signed by ${m.owner.id}, valid until ${o.expires}: ${m.allow.servers ? `servers ${m.allow.servers.join(", ")}` : "any server"}; ${m.allow.tools ? `tools ${m.allow.tools.join(", ")}` : "any tool"}; destructive actions ${m.allow.destructive ? "allowed" : "not allowed"}; autonomy ${m.autonomy}; risk tier ${agentRiskTier(m).tier} (${agentRiskTier(m).note}).
37909
39862
  Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep it private).
37910
39863
  `);
37911
39864
  });
37912
- agent.command("verify").description("Check a mandate's owner signature and expiry").argument("<mandate>", "mandate file").action((f) => {
37913
- const m = JSON.parse(readFileSync7(f, "utf8"));
37914
- const c = checkMandate(m);
39865
+ agent.command("verify").description("Check a mandate: the principal's signature, the operator's countersignature, expiry and revocation").argument("<mandate>", "mandate file").action((f) => {
39866
+ const m = JSON.parse(readFileSync9(f, "utf8"));
39867
+ const c = checkMandate(m), op = checkOperator(m), rev = revocationOf(m);
37915
39868
  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}.
37916
39869
  ` : `\u2717 ${c.reason}
37917
39870
  `);
37918
- exitCode = c.ok ? 0 : 1;
39871
+ if (op.present)
39872
+ process.stdout.write(op.valid ? `\u2713 Countersigned by the operator ${sanitizeText(op.name ?? "", 80)} (${op.id}).
39873
+ ` : `\u2717 Operator countersignature: ${op.reason}
39874
+ `);
39875
+ if (rev)
39876
+ process.stdout.write(`\u2717 Revoked on ${rev.at.slice(0, 10)}${rev.reason ? `: ${sanitizeText(rev.reason, 200)}` : ""}.
39877
+ `);
39878
+ exitCode = c.ok && (!op.present || op.valid) && !rev ? 0 : 1;
39879
+ });
39880
+ 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) => {
39881
+ const m = JSON.parse(readFileSync9(f, "utf8"));
39882
+ if (!checkMandate(m).ok)
39883
+ throw new Error("The mandate is not valid; it cannot be countersigned.");
39884
+ const signed = cosignMandate(m, loadOrCreateKey(o.key), o.name);
39885
+ writeFileSync5(f, JSON.stringify(signed, null, 2) + "\n");
39886
+ process.stdout.write(`Countersigned by ${sanitizeText(o.name, 80)} (${loadOrCreateKey(o.key).kid}). Check: npx saktum agent verify ${sanitizeText(f)}
39887
+ `);
37919
39888
  });
37920
- 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)").action(async (parts, o) => {
39889
+ 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) => {
39890
+ const m = JSON.parse(readFileSync9(o.mandate, "utf8"));
39891
+ const a = approveAction(m, rid, loadOrCreateKey(o.key), Number(o.minutes), o.approvals);
39892
+ 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.
39893
+ `);
39894
+ });
39895
+ 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) => {
39896
+ const m = JSON.parse(readFileSync9(f, "utf8"));
39897
+ const r = revokeMandate(m, o.reason);
39898
+ process.stdout.write(`Revoked the mandate for ${sanitizeText(m.agent.name, 80)} at ${r.at}. Its calls are now refused (code: revoked).
39899
+ `);
39900
+ });
39901
+ 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) => {
37921
39902
  const { homedir: homedir2 } = await import("node:os");
37922
- const { join: join5 } = await import("node:path");
39903
+ const { join: join6 } = await import("node:path");
37923
39904
  let mandate;
37924
39905
  if (o.mandate) {
37925
- mandate = JSON.parse(readFileSync7(o.mandate, "utf8"));
39906
+ mandate = JSON.parse(readFileSync9(o.mandate, "utf8"));
37926
39907
  const c = checkMandate(mandate);
37927
39908
  if (!c.ok)
37928
39909
  throw new Error(`Mandate refused: ${c.reason}`);
@@ -37931,14 +39912,28 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
37931
39912
  if (mandate && agentKey.kid !== mandate.agent.id)
37932
39913
  throw new Error("The agent key does not match the mandate's agent.");
37933
39914
  const { runProxy: runProxy2 } = await Promise.resolve().then(() => (init_proxy(), proxy_exports));
37934
- exitCode = await runProxy2({ command: parts[0], args: parts.slice(1), receiptsPath: o.receipts ?? join5(homedir2(), ".saktum", "receipts.jsonl"), agentKey, mandate, enforce: o.enforce, log: (m) => process.stderr.write(`saktum: ${m}
37935
- `) });
39915
+ exitCode = await runProxy2({
39916
+ command: parts[0],
39917
+ args: parts.slice(1),
39918
+ receiptsPath: o.receipts ?? join6(homedir2(), ".saktum", "receipts.jsonl"),
39919
+ agentKey,
39920
+ mandate,
39921
+ enforce: o.enforce,
39922
+ ...o.revocations ? { revocationsPath: o.revocations } : {},
39923
+ ...o.approvals ? { approvalsPath: o.approvals } : {},
39924
+ ...o.credential ? { credential: JSON.parse(readFileSync9(o.credential, "utf8")) } : {},
39925
+ ...o.revokedCredentials ? { revokedCredentials: JSON.parse(readFileSync9(o.revokedCredentials, "utf8")) } : {},
39926
+ ...o.agreement ? { agreement: JSON.parse(readFileSync9(o.agreement, "utf8")) } : {},
39927
+ ...o.wallet ? { walletPath: o.wallet } : {},
39928
+ log: (m) => process.stderr.write(`saktum: ${m}
39929
+ `)
39930
+ });
37936
39931
  });
37937
39932
  const receipts = program2.command("receipts").description("Signed receipts of agent tool calls (from saktum proxy)");
37938
39933
  receipts.command("verify").description("Verify every receipt's signature and the hash chain").argument("[file]", "receipt log").action(async (f) => {
37939
39934
  const { homedir: homedir2 } = await import("node:os");
37940
- const { join: join5 } = await import("node:path");
37941
- const r = verifyReceiptLog(parseReceiptLog(readFileSync7(f ?? join5(homedir2(), ".saktum", "receipts.jsonl"), "utf8")));
39935
+ const { join: join6 } = await import("node:path");
39936
+ const r = verifyReceiptLog(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")));
37942
39937
  process.stdout.write(r.ok ? `\u2713 ${r.count} receipts verified: every signature valid, chain intact.
37943
39938
  ` : `\u2717 Receipts do NOT verify:
37944
39939
  ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
@@ -37947,11 +39942,11 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
37947
39942
  });
37948
39943
  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) => {
37949
39944
  const { homedir: homedir2 } = await import("node:os");
37950
- const { join: join5 } = await import("node:path");
37951
- const entries = parseReceiptLog(readFileSync7(f ?? join5(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
39945
+ const { join: join6 } = await import("node:path");
39946
+ const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
37952
39947
  const v = verifyReceiptLog(entries);
37953
39948
  const otlp = receiptsToOtlp(entries, { verified: v.ok, version: ENGINE_VERSION });
37954
- writeFileSync3(o.otel, JSON.stringify(otlp, null, 2) + "\n");
39949
+ writeFileSync5(o.otel, JSON.stringify(otlp, null, 2) + "\n");
37955
39950
  process.stdout.write(`Wrote ${entries.length} span(s) to ${sanitizeText(o.otel)} (receipts ${v.ok ? "verified" : "DO NOT verify"}).
37956
39951
  `);
37957
39952
  if (o.endpoint) {
@@ -37965,8 +39960,8 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
37965
39960
  });
37966
39961
  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) => {
37967
39962
  const { homedir: homedir2 } = await import("node:os");
37968
- const { join: join5 } = await import("node:path");
37969
- const entries = parseReceiptLog(readFileSync7(f ?? join5(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
39963
+ const { join: join6 } = await import("node:path");
39964
+ const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
37970
39965
  const v = verifyReceiptLog(entries), s = summariseReceipts(entries);
37971
39966
  if (o.json) {
37972
39967
  process.stdout.write(JSON.stringify({ verified: v.ok, ...s }, null, 2) + "\n");
@@ -37980,11 +39975,11 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
37980
39975
  });
37981
39976
  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) => {
37982
39977
  if (o.agent) {
37983
- const m = JSON.parse(readFileSync7(o.agent, "utf8"));
39978
+ const m = JSON.parse(readFileSync9(o.agent, "utf8"));
37984
39979
  const valid = checkMandate(m);
37985
39980
  let receipts2;
37986
39981
  if (o.receipts) {
37987
- const entries = parseReceiptLog(readFileSync7(o.receipts, "utf8"));
39982
+ const entries = parseReceiptLog(readFileSync9(o.receipts, "utf8"));
37988
39983
  const counts = /* @__PURE__ */ new Map();
37989
39984
  for (const e of entries) {
37990
39985
  const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
@@ -37996,7 +39991,9 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
37996
39991
  timeline: entries.map((e) => ({ tool: e.receipt.envelope.tool, outcome: e.receipt.outcome, status: e.result.status, repeated: (counts.get(`${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`) ?? 0) >= 3 }))
37997
39992
  };
37998
39993
  }
37999
- writeFileSync3(o.out, renderAgentPassport(m, valid.ok ? { ok: true } : { ok: false, reason: valid.reason }, receipts2));
39994
+ const rev = revocationOf(m), op = checkOperator(m);
39995
+ const ts = o.receipts ? trustStatement(parseReceiptLog(readFileSync9(o.receipts, "utf8")), receipts2?.verified ?? false) : void 0;
39996
+ 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), { operator: op.present && op.valid ? `${op.name} (${op.id})` : void 0, track: ts?.lines }));
38000
39997
  process.stdout.write(`Wrote the Agent Passport for ${sanitizeText(m.agent.name, 80)} to ${sanitizeText(o.out)}. Open it in a browser.
38001
39998
  `);
38002
39999
  return;
@@ -38008,20 +40005,20 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
38008
40005
  target.env = parseEnv(o.env);
38009
40006
  if (target.kind === "streamable-http" && o.header.length)
38010
40007
  target.headers = parseHeaders(o.header);
38011
- const packs = existsSync5(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40008
+ const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
38012
40009
  let tools = [];
38013
40010
  const r = await runTrustCheck(target, { packs, onTools: (t) => {
38014
40011
  tools = t;
38015
40012
  } });
38016
40013
  const signed = signDocument(r, loadOrCreateKey(o.key));
38017
- writeFileSync3(o.out, renderServerPassport(signed, tools));
38018
- writeFileSync3(o.out.replace(/\.html?$/i, "") + ".json", JSON.stringify(signed, null, 2));
40014
+ writeFileSync5(o.out, renderServerPassport(signed, tools));
40015
+ writeFileSync5(o.out.replace(/\.html?$/i, "") + ".json", JSON.stringify(signed, null, 2));
38019
40016
  process.stdout.write(`Wrote the MCP Server Passport for ${sanitizeText(String(r.target.serverInfo?.["name"] ?? "server"), 80)} to ${sanitizeText(o.out)} (trust ${r.grade ?? "-"}, readiness ${r.readiness?.grade ?? "-"}), and its signed result beside it.
38020
40017
  `);
38021
40018
  });
38022
40019
  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) => {
38023
- const list = JSON.parse(readFileSync7(file, "utf8"));
38024
- const packs = existsSync5(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40020
+ const list = JSON.parse(readFileSync9(file, "utf8"));
40021
+ const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
38025
40022
  const r = await watchAllowlist(list.allowed ?? [], packs);
38026
40023
  const mark2 = { unchanged: "\u2713", changed: "\u2717", degraded: "!", unreachable: "?" };
38027
40024
  for (const f of r.findings)
@@ -38031,7 +40028,7 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
38031
40028
  ${r.findings.length} server(s) checked; ${r.alerts} need attention.
38032
40029
  `);
38033
40030
  if (o.out)
38034
- writeFileSync3(o.out, JSON.stringify(r, null, 2) + "\n");
40031
+ writeFileSync5(o.out, JSON.stringify(r, null, 2) + "\n");
38035
40032
  if (o.webhook && r.alerts) {
38036
40033
  const text2 = `Saktum watch: ${r.alerts} MCP server(s) need attention. ${r.findings.filter((f) => f.status !== "unchanged").map((f) => `${f.server}: ${f.details.join("; ")}`).join(" | ")}`.slice(0, 3e3);
38037
40034
  try {
@@ -38056,43 +40053,208 @@ Assumptions: ${r.assumptions}.
38056
40053
  `);
38057
40054
  });
38058
40055
  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) => {
38059
- const fleet = JSON.parse(readFileSync7(o.fleet, "utf8"));
40056
+ const fleet = JSON.parse(readFileSync9(o.fleet, "utf8"));
38060
40057
  const rec = o.receipts.map((f) => {
38061
- const e = parseReceiptLog(readFileSync7(f, "utf8"));
40058
+ const e = parseReceiptLog(readFileSync9(f, "utf8"));
38062
40059
  return { agent: e[0]?.receipt.envelope.caller.agent?.slice(0, 32) ?? f, summary: summariseReceipts(e), verified: verifyReceiptLog(e).ok };
38063
40060
  });
38064
40061
  const distinctTokens = (fleet.servers ?? []).reduce((a, x) => a + (x.tokens ?? 0), 0);
38065
40062
  const roi = roiEstimate({ ...ROI_DEFAULTS, tokensPerTurn: distinctTokens, agents: Number(o.agents), turnsPerDay: Number(o.turnsPerDay), pricePerMTok: Number(o.pricePerMtok), vendorReviews: Number(o.vendorReviews) });
38066
- writeFileSync3(o.out, renderAssessment(o.org, fleet, rec, roi));
40063
+ writeFileSync5(o.out, renderAssessment(o.org, fleet, rec, roi));
38067
40064
  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.
38068
40065
  `);
38069
40066
  });
38070
40067
  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) => {
38071
40068
  const setups = files.map((f) => {
38072
- const j = JSON.parse(readFileSync7(f, "utf8"));
40069
+ const j = JSON.parse(readFileSync9(f, "utf8"));
38073
40070
  return { machine: j.machine ?? f, servers: j.servers ?? [] };
38074
40071
  });
38075
40072
  const pol = o.policy ? await loadPolicy(o.policy) : void 0;
38076
40073
  const fleet = buildFleet(setups, pol?.policy, pol?.allow);
38077
40074
  process.stdout.write(renderFleet(fleet));
38078
40075
  if (o.out)
38079
- writeFileSync3(o.out, JSON.stringify(fleet, null, 2) + "\n");
40076
+ writeFileSync5(o.out, JSON.stringify(fleet, null, 2) + "\n");
38080
40077
  if (o.html)
38081
- writeFileSync3(o.html, fleetHtml(fleet));
40078
+ writeFileSync5(o.html, fleetHtml(fleet));
38082
40079
  exitCode = fleet.nonCompliant ? 1 : 0;
38083
40080
  });
40081
+ program2.command("bindings").description("How Saktum reads a server's tools (action class, what each argument means), and the _meta block to declare them").argument("<target...>", "https://host/mcp or -- node server.js").option("--env <KEY=VALUE>", "environment variable for a local server (repeatable)", collect, []).action(async (parts, o) => {
40082
+ const target = parseTarget(parts);
40083
+ if (target.kind === "stdio" && o.env.length)
40084
+ target.env = parseEnv(o.env);
40085
+ const s2 = await connect(target);
40086
+ let tools = [];
40087
+ try {
40088
+ tools = await s2.listTools();
40089
+ } finally {
40090
+ await s2.close();
40091
+ }
40092
+ for (const t of tools) {
40093
+ const a = actionClass(t), b = bindingsFor(t);
40094
+ process.stdout.write(`${sanitizeText(t.name, 60).padEnd(28)} ${a.cls.padEnd(12)} ${b.basis === "declared" ? "declared" : "inferred"}: ${Object.entries(b.bindings).map(([k, f]) => `${k} \u2192 ${f}`).join(", ") || "(no domain arguments)"}
40095
+ `);
40096
+ }
40097
+ const undeclared = tools.filter((t) => !t._meta?.["io.saktum/bindings"]);
40098
+ if (undeclared.length) {
40099
+ process.stdout.write(`
40100
+ To declare them, add to each tool's definition (MCP tools accept _meta):
40101
+ `);
40102
+ for (const t of undeclared.slice(0, 5))
40103
+ process.stdout.write(` ${t.name}: _meta: ${JSON.stringify({ "io.saktum/action": actionClass(t).cls, "io.saktum/bindings": bindingsFor(t).bindings })}
40104
+ `);
40105
+ }
40106
+ });
40107
+ const org = program2.command("org").description("Organisations: the root of every accountability chain");
40108
+ org.command("init").description("Create your organisation's root identity credential").requiredOption("--name <name>", "organisation name").option("--domain <domain>", "the organisation's domain").option("--key <path>", "the organisation's signing key (created if missing)", "saktum-org-key.json").option("--expires <date>", "YYYY-MM-DD", new Date(Date.now() + 365 * 864e5).toISOString().slice(0, 10)).option("--out <file>", "credential file", "org-credential.json").action((o) => {
40109
+ const c = organisationRoot({ name: o.name, domain: o.domain, expires: o.expires }, loadOrCreateKey(o.key));
40110
+ writeFileSync5(o.out, JSON.stringify(c, null, 2) + "\n");
40111
+ process.stdout.write(`Organisation ${sanitizeText(o.name, 80)}: ${c.subject.id}. Root credential ${c.id} in ${sanitizeText(o.out)}.
40112
+ `);
40113
+ });
40114
+ const identity = program2.command("identity").description("Identity chains: organisation -> people -> agents");
40115
+ 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").action((o) => {
40116
+ const subject = o.subject ?? (o.subjectKey ? loadOrCreateKey(o.subjectKey).kid : void 0);
40117
+ if (!subject)
40118
+ throw new Error("Give --subject <did:key> or --subject-key <file>.");
40119
+ 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 });
40120
+ writeFileSync5(o.out, JSON.stringify(c, null, 2) + "\n");
40121
+ process.stdout.write(`Issued ${c.id} to ${sanitizeText(o.name, 80)} (${o.type}). Chain: ${verifyChain(c).path.join(" -> ")}
40122
+ `);
40123
+ });
40124
+ 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) => {
40125
+ const v = verifyChain(JSON.parse(readFileSync9(f, "utf8")), { revoked: o.revoked ? JSON.parse(readFileSync9(o.revoked, "utf8")) : [] });
40126
+ process.stdout.write(v.valid ? `\u2713 ${v.path.join(" -> ")}: accountable organisation ${v.organisation}
40127
+ ` : `\u2717 ${v.reason}
40128
+ `);
40129
+ exitCode = v.valid ? 0 : 1;
40130
+ });
40131
+ 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) => {
40132
+ const orphans = findOrphans(fs.map((f) => JSON.parse(readFileSync9(f, "utf8"))), { revoked: o.revoked ? JSON.parse(readFileSync9(o.revoked, "utf8")) : [] });
40133
+ for (const x of orphans)
40134
+ process.stdout.write(`\u2717 ${sanitizeText(x.agent, 80)} (${x.id}): ${x.reason}
40135
+ `);
40136
+ process.stdout.write(`${orphans.length} orphaned agent(s).
40137
+ `);
40138
+ exitCode = orphans.length ? 1 : 0;
40139
+ });
40140
+ const manifest = program2.command("manifest").description("What a server offers, signed by its publisher");
40141
+ manifest.command("create").description("Build and sign a manifest from a server's tools (with its grades and risk tier)").argument("<target...>", "https://host/mcp or -- node server.js").requiredOption("--publisher <name>", "publishing organisation").option("--domain <domain>").option("--key <path>", "the publisher's signing key", "saktum-publisher-key.json").option("--per-call <tokens>", "default tokens per call", "1").option("--rate <tool=tokens>", "tokens for one tool (repeatable)", collect, []).option("--out <file>", "manifest file", "saktum-manifest.json").action(async (parts, o) => {
40142
+ const target = parseTarget(parts);
40143
+ const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40144
+ let tools = [];
40145
+ const r = await runTrustCheck(target, { packs, onTools: (t) => {
40146
+ tools = t;
40147
+ } });
40148
+ const perTool = Object.fromEntries(o.rate.map((x) => {
40149
+ const [t, n] = x.split("=");
40150
+ return [t, Number(n)];
40151
+ }));
40152
+ const m = buildManifest({
40153
+ publisher: { name: o.publisher, ...o.domain ? { domain: o.domain } : {} },
40154
+ server: { name: String(r.target.serverInfo?.["name"] ?? "server"), version: String(r.target.serverInfo?.["version"] ?? ""), toolsFingerprint: r.target.toolsFingerprint },
40155
+ tools,
40156
+ rates: { perCall: Number(o.perCall), ...o.rate.length ? { perTool } : {} },
40157
+ quality: { trustGrade: r.grade ?? null, readinessGrade: r.readiness?.grade ?? null, riskTier: r.riskTier?.tier }
40158
+ }, loadOrCreateKey(o.key));
40159
+ writeFileSync5(o.out, JSON.stringify(m, null, 2) + "\n");
40160
+ process.stdout.write(`Manifest ${m.id} for ${sanitizeText(m.server.name, 80)}: intents ${m.intents.join(", ")}; trust ${r.grade ?? "-"}, readiness ${r.readiness?.grade ?? "-"}, risk ${r.riskTier?.tier ?? "-"}.
40161
+ `);
40162
+ });
40163
+ const catalog = program2.command("catalog").description("A catalogue of signed manifests, searchable by intent");
40164
+ catalog.command("add").argument("<manifest>").option("--catalog <file>", "catalogue file", "saktum-catalog.json").action((f, o) => {
40165
+ const m = JSON.parse(readFileSync9(f, "utf8"));
40166
+ if (!verifyDocument(m).valid)
40167
+ throw new Error("The manifest's signature is not valid.");
40168
+ const c = existsSync7(o.catalog) ? JSON.parse(readFileSync9(o.catalog, "utf8")) : [];
40169
+ writeFileSync5(o.catalog, JSON.stringify([...c.filter((x) => x.server.name !== m.server.name || x.publisher.id !== m.publisher.id), m], null, 2) + "\n");
40170
+ process.stdout.write(`Added ${sanitizeText(m.server.name, 80)} by ${sanitizeText(m.publisher.name, 80)} to ${sanitizeText(o.catalog)}.
40171
+ `);
40172
+ });
40173
+ 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) => {
40174
+ const res = searchCatalogue(JSON.parse(readFileSync9(o.catalog, "utf8")), q.join(" "), { maxRisk: o.maxRisk });
40175
+ for (const r of res.slice(0, 10))
40176
+ 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(", ")}
40177
+ `);
40178
+ if (!res.length)
40179
+ process.stdout.write("No match.\n");
40180
+ });
40181
+ const agreement = program2.command("agreement").description("Agreements between providers and invokers (smart contracts as signed documents)");
40182
+ 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) => {
40183
+ 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));
40184
+ writeFileSync5(o.out, JSON.stringify(a, null, 2) + "\n");
40185
+ 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>
40186
+ `);
40187
+ });
40188
+ agreement.command("accept").argument("<agreement>").requiredOption("--key <path>", "the invoker's key").action((f, o) => {
40189
+ const a = acceptAgreement(JSON.parse(readFileSync9(f, "utf8")), loadOrCreateKey(o.key));
40190
+ writeFileSync5(f, JSON.stringify(a, null, 2) + "\n");
40191
+ process.stdout.write(`Accepted ${a.id}: signed by both parties.
40192
+ `);
40193
+ });
40194
+ agreement.command("verify").argument("<agreement>").action((f) => {
40195
+ const a = JSON.parse(readFileSync9(f, "utf8"));
40196
+ const v = verifyAgreement(a);
40197
+ process.stdout.write(v.valid ? `\u2713 ${a.id}: ${sanitizeText(a.provider.name, 80)} and ${sanitizeText(a.invoker.name, 80)}, until ${a.validUntil}.
40198
+ ` : `\u2717 ${v.reason}
40199
+ `);
40200
+ exitCode = v.valid ? 0 : 1;
40201
+ });
40202
+ const wallet = program2.command("wallet").description("Prepaid tokens (bought outside Saktum; no money is handled here)");
40203
+ wallet.command("topup").requiredOption("--account <id>").requiredOption("--tokens <n>").option("--wallet <file>", "wallet file", "saktum-wallet.json").action((o) => {
40204
+ process.stdout.write(`Balance of ${sanitizeText(o.account, 80)}: ${topUp(o.wallet, o.account, Number(o.tokens))} tokens.
40205
+ `);
40206
+ });
40207
+ wallet.command("balance").requiredOption("--account <id>").option("--wallet <file>", "wallet file", "saktum-wallet.json").action((o) => {
40208
+ process.stdout.write(`${walletBalance(o.wallet, o.account)} tokens
40209
+ `);
40210
+ });
40211
+ 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) => {
40212
+ const { homedir: homedir2 } = await import("node:os");
40213
+ const { join: join6 } = await import("node:path");
40214
+ 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);
40215
+ for (const l of st.lines)
40216
+ process.stdout.write(`${sanitizeText(l.tool, 60).padEnd(24)} ${String(l.calls).padStart(5)} calls ${String(l.tokens).padStart(7)} tokens
40217
+ `);
40218
+ process.stdout.write(`Total: ${st.totalTokens} tokens
40219
+ `);
40220
+ if (o.out)
40221
+ writeFileSync5(o.out, JSON.stringify(st, null, 2) + "\n");
40222
+ });
40223
+ 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) => {
40224
+ const { homedir: homedir2 } = await import("node:os");
40225
+ const { join: join6 } = await import("node:path");
40226
+ const k = kpis(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), o);
40227
+ 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
40228
+ `);
40229
+ process.stdout.write(`By outcome: ${k.byOutcome.map(([c, n]) => `${c} ${n}`).join(", ")}
40230
+ By tool: ${k.byTool.map(([c, n]) => `${c} ${n}`).join(", ")}
40231
+ `);
40232
+ });
40233
+ program2.command("bounty").description("Bounties (contract only for now)").command("validate").argument("<file>").action((f) => {
40234
+ const ok = compileContract("bounty.schema.json")(JSON.parse(readFileSync9(f, "utf8")));
40235
+ process.stdout.write(ok ? "\u2713 Valid bounty document.\n" : "\u2717 Not a valid bounty document.\n");
40236
+ exitCode = ok ? 0 : 1;
40237
+ });
40238
+ 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, marketplace, autonomy, or all (grocery, travel, finance and marketplace)", "all").action(async (o) => {
40239
+ const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
40240
+ await runDemo2(o.out, (l) => process.stdout.write(l + "\n"), o.story);
40241
+ });
40242
+ program2.command("demo-server", { hidden: true }).description("The demo MCP servers (used by saktum demo)").option("--story <name>", "grocery, travel, finance or autonomy", "autonomy").action(async (o) => {
40243
+ const { startDemoServer: startDemoServer2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
40244
+ await startDemoServer2(o.story);
40245
+ });
38084
40246
  program2.command("mcp").description("Run Saktum Check as an MCP server (stdio), so coding agents can test, fix, diff and document MCP servers").option("--packs <dir>", "directory of packs (default: the built-in packs)").action(async (o) => {
38085
- const packs = o.packs ? loadPackDir(o.packs) : existsSync5(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40247
+ const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
38086
40248
  const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports));
38087
40249
  await startMcpServer2(packs);
38088
40250
  });
38089
40251
  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) => {
38090
- const doc = JSON.parse(readFileSync7(file, "utf8"));
40252
+ const doc = JSON.parse(readFileSync9(file, "utf8"));
38091
40253
  const v = verifyDocument(doc);
38092
40254
  if (!v.valid)
38093
40255
  throw new Error(`The result's signature is not valid (${v.reason}); attestations are built only from unaltered signed results.`);
38094
40256
  const att = signDocument(buildAttestation(doc), loadOrCreateKey(o.key));
38095
- writeFileSync3(o.out, JSON.stringify(att, null, 2) + "\n");
40257
+ writeFileSync5(o.out, JSON.stringify(att, null, 2) + "\n");
38096
40258
  const c = att.claims, colour = (g) => ({ A: "2e7d32", B: "558b2f", C: "f9a825", D: "ef6c00", F: "c62828" })[g ?? ""] ?? "757575";
38097
40259
  process.stdout.write(`Wrote ${sanitizeText(o.out)} (trust ${c.trustGrade ?? "-"}, agent readiness ${c.readinessGrade ?? "-"}; evidence: ${Object.entries(c.evidence).filter(([, x]) => x).map(([k]) => k).join(", ") || "none"}).
38098
40260
  Anyone can check it: npx saktum verify ${sanitizeText(o.out)}
@@ -38104,20 +40266,20 @@ README badge:
38104
40266
  const key = loadOrCreateKey(o.key);
38105
40267
  const cred = attestationToCredential(att, key.kid);
38106
40268
  const base = o.out.replace(/\.json$/i, "");
38107
- writeFileSync3(`${base}.vc.jwt`, signCredentialJwt(cred, key) + "\n");
38108
- writeFileSync3(`${base}.vc.json`, JSON.stringify(cred, null, 2) + "\n");
40269
+ writeFileSync5(`${base}.vc.jwt`, signCredentialJwt(cred, key) + "\n");
40270
+ writeFileSync5(`${base}.vc.json`, JSON.stringify(cred, null, 2) + "\n");
38109
40271
  process.stdout.write(`
38110
40272
  W3C Verifiable Credential: ${sanitizeText(base)}.vc.jwt (check it: npx saktum vc verify ${sanitizeText(base)}.vc.jwt)
38111
40273
  `);
38112
40274
  }
38113
40275
  if (o.publish) {
38114
- const body = `Publishing a signed Saktum attestation to the public trust ledger. The bot verifies the signature and appends it.
40276
+ const body2 = `Publishing a signed Saktum attestation to the public trust ledger. The bot verifies the signature and appends it.
38115
40277
 
38116
40278
  \`\`\`json
38117
40279
  ${JSON.stringify(att)}
38118
40280
  \`\`\`
38119
40281
  `;
38120
- const url2 = `https://github.com/soodhere/saktum-index/issues/new?title=${encodeURIComponent(`Attest: ${att.subject.server}`)}&body=${encodeURIComponent(body)}`;
40282
+ const url2 = `https://github.com/soodhere/saktum-index/issues/new?title=${encodeURIComponent(`Attest: ${att.subject.server}`)}&body=${encodeURIComponent(body2)}`;
38121
40283
  process.stdout.write(`
38122
40284
  Publish to the public trust ledger (opens a pre-filled GitHub issue; anyone can then verify it):
38123
40285
  ${url2}
@@ -38130,7 +40292,7 @@ ${url2}
38130
40292
  exitCode = r.code;
38131
40293
  });
38132
40294
  program2.command("verify").description("Verify a signed Saktum Check result").argument("<file>").action((file) => {
38133
- const doc = JSON.parse(readFileSync7(file, "utf8"));
40295
+ const doc = JSON.parse(readFileSync9(file, "utf8"));
38134
40296
  const validate2 = compileContract("result.schema.json");
38135
40297
  if (!validate2(doc)) {
38136
40298
  process.stdout.write(`Invalid result format: ${JSON.stringify(validate2.errors?.slice(0, 2))}