saktum 0.7.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 +9 -1
  2. package/package.json +1 -1
  3. package/saktum.mjs +711 -168
package/saktum.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Saktum Check 0.7.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;
@@ -4389,10 +4389,10 @@ ${indent}`) + "'";
4389
4389
  literalFallback = true;
4390
4390
  };
4391
4391
  }
4392
- 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);
4393
4393
  if (!literalFallback)
4394
4394
  return `>${header}
4395
- ${indent}${body}`;
4395
+ ${indent}${body2}`;
4396
4396
  }
4397
4397
  value = value.replace(/\n+/g, `$&${indent}`);
4398
4398
  return `|${header}
@@ -6408,13 +6408,13 @@ var require_stringifyDocument = __commonJS({
6408
6408
  contentComment = doc.contents.comment;
6409
6409
  }
6410
6410
  const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
6411
- let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
6411
+ let body2 = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
6412
6412
  if (contentComment)
6413
- body += stringifyComment.lineComment(body, "", commentString(contentComment));
6414
- if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
6415
- 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}`;
6416
6416
  } else
6417
- lines.push(body);
6417
+ lines.push(body2);
6418
6418
  } else {
6419
6419
  lines.push(stringify.stringify(doc.contents, ctx));
6420
6420
  }
@@ -8407,13 +8407,13 @@ var require_cst_scalar = __commonJS({
8407
8407
  case ">": {
8408
8408
  const he = source.indexOf("\n");
8409
8409
  const head = source.substring(0, he);
8410
- const body = source.substring(he + 1) + "\n";
8410
+ const body2 = source.substring(he + 1) + "\n";
8411
8411
  const props = [
8412
8412
  { type: "block-scalar-header", offset, indent, source: head }
8413
8413
  ];
8414
8414
  if (!addEndtoBlockProps(props, end))
8415
8415
  props.push({ type: "newline", offset: -1, indent, source: "\n" });
8416
- return { type: "block-scalar", offset, indent, props, source: body };
8416
+ return { type: "block-scalar", offset, indent, props, source: body2 };
8417
8417
  }
8418
8418
  case '"':
8419
8419
  return { type: "double-quoted-scalar", offset, indent, source, end };
@@ -8470,13 +8470,13 @@ var require_cst_scalar = __commonJS({
8470
8470
  function setBlockScalarValue(token, source) {
8471
8471
  const he = source.indexOf("\n");
8472
8472
  const head = source.substring(0, he);
8473
- const body = source.substring(he + 1) + "\n";
8473
+ const body2 = source.substring(he + 1) + "\n";
8474
8474
  if (token.type === "block-scalar") {
8475
8475
  const header = token.props[0];
8476
8476
  if (header.type !== "block-scalar-header")
8477
8477
  throw new Error("Invalid block scalar header");
8478
8478
  header.source = head;
8479
- token.source = body;
8479
+ token.source = body2;
8480
8480
  } else {
8481
8481
  const { offset } = token;
8482
8482
  const indent = "indent" in token ? token.indent : -1;
@@ -8488,7 +8488,7 @@ var require_cst_scalar = __commonJS({
8488
8488
  for (const key of Object.keys(token))
8489
8489
  if (key !== "type" && key !== "offset")
8490
8490
  delete token[key];
8491
- Object.assign(token, { type: "block-scalar", indent, props, source: body });
8491
+ Object.assign(token, { type: "block-scalar", indent, props, source: body2 });
8492
8492
  }
8493
8493
  }
8494
8494
  function addEndtoBlockProps(props, end) {
@@ -10500,11 +10500,11 @@ function loadOrCreateKey(path = defaultKeyPath()) {
10500
10500
  return key;
10501
10501
  }
10502
10502
  function signDocument(doc, key) {
10503
- const { signature: _ignored, ...body } = doc;
10503
+ const { signature: _ignored, ...body2 } = doc;
10504
10504
  const header = b64u(Buffer.from(JSON.stringify({ alg: "EdDSA", kid: key.kid })));
10505
- const payload = b64u(Buffer.from(canonicalize(body)));
10505
+ const payload = b64u(Buffer.from(canonicalize(body2)));
10506
10506
  const sig = sign(null, Buffer.from(`${header}.${payload}`), key.privateKey);
10507
- 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)}` } };
10508
10508
  }
10509
10509
  function verifyDocument(doc) {
10510
10510
  const s = doc.signature;
@@ -10527,8 +10527,8 @@ function verifyDocument(doc) {
10527
10527
  } catch (e) {
10528
10528
  return { valid: false, reason: e.message };
10529
10529
  }
10530
- const { signature: _s, ...body } = doc;
10531
- const payload = b64u(Buffer.from(canonicalize(body)));
10530
+ const { signature: _s, ...body2 } = doc;
10531
+ const payload = b64u(Buffer.from(canonicalize(body2)));
10532
10532
  const ok = verify(null, Buffer.from(`${parts[0]}.${payload}`), publicKey, Buffer.from(parts[2], "base64url"));
10533
10533
  return ok ? { valid: true, kid: s.kid } : { valid: false, kid: s.kid, reason: "signature does not match content" };
10534
10534
  }
@@ -11432,10 +11432,10 @@ var require_codegen = __commonJS({
11432
11432
  return this._leafNode(new Throw(error2));
11433
11433
  }
11434
11434
  // start self-balancing block
11435
- block(body, nodeCount) {
11435
+ block(body2, nodeCount) {
11436
11436
  this._blockStarts.push(this._nodes.length);
11437
- if (body)
11438
- this.code(body).endBlock(nodeCount);
11437
+ if (body2)
11438
+ this.code(body2).endBlock(nodeCount);
11439
11439
  return this;
11440
11440
  }
11441
11441
  // end the current self-balancing block
@@ -12860,15 +12860,15 @@ var require_validate = __commonJS({
12860
12860
  validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
12861
12861
  }
12862
12862
  exports.validateFunctionCode = validateFunctionCode;
12863
- function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
12863
+ function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body2) {
12864
12864
  if (opts.code.es5) {
12865
12865
  gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
12866
12866
  gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
12867
12867
  destructureValCxtES5(gen, opts);
12868
- gen.code(body);
12868
+ gen.code(body2);
12869
12869
  });
12870
12870
  } else {
12871
- 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));
12872
12872
  }
12873
12873
  }
12874
12874
  function destructureValCxt(opts) {
@@ -19052,7 +19052,7 @@ var EMBEDDED_CONTRACTS, EMBEDDED_PACKS;
19052
19052
  var init_embedded = __esm({
19053
19053
  "packages/testkit-core/dist/embedded.js"() {
19054
19054
  "use strict";
19055
- 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": `{
19056
19056
  "$schema": "https://json-schema.org/draft/2020-12/schema",
19057
19057
  "$id": "https://saktum.dev/schemas/envelope/0.1.json",
19058
19058
  "title": "Saktum canonical call envelope",
@@ -19584,7 +19584,7 @@ var init_embedded = __esm({
19584
19584
  }
19585
19585
  }
19586
19586
  }
19587
- `, "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": `{
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": `{
19588
19588
  "$schema": "https://json-schema.org/draft/2020-12/schema",
19589
19589
  "$id": "https://saktum.dev/contracts/policy.schema.json",
19590
19590
  "title": "Saktum policy",
@@ -20023,9 +20023,9 @@ function compileUntrustedSchema(schema) {
20023
20023
  const dialect = schemaDialect(schema);
20024
20024
  if (dialect === "unknown")
20025
20025
  return { ok: false, error: `unrecognised $schema dialect ${JSON.stringify(schema.$schema).slice(0, 80)}` };
20026
- const { $schema: _ignored, ...body } = schema;
20026
+ const { $schema: _ignored, ...body2 } = schema;
20027
20027
  const Ctor = dialect === "2020-12" ? Ajv2020 : dialect === "2019-09" ? Ajv2019 : AjvDraft7;
20028
- 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);
20029
20029
  return { ok: true };
20030
20030
  } catch (e) {
20031
20031
  return { ok: false, error: e.message };
@@ -20038,10 +20038,10 @@ function compileUntrustedSchemaValidator(schema) {
20038
20038
  const dialect = schemaDialect(schema);
20039
20039
  if (dialect === "unknown")
20040
20040
  return { ok: false, error: "unrecognised $schema dialect" };
20041
- const { $schema: _ignored, ...body } = schema;
20041
+ const { $schema: _ignored, ...body2 } = schema;
20042
20042
  const Ctor = dialect === "2020-12" ? Ajv2020 : dialect === "2019-09" ? Ajv2019 : AjvDraft7;
20043
20043
  const ajv2 = new Ctor({ strict: false, allErrors: false, validateSchema: true, logger: false });
20044
- const fn = ajv2.compile(body);
20044
+ const fn = ajv2.compile(body2);
20045
20045
  return { ok: true, validate: (d) => Boolean(fn(d)), errors: () => (fn.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message ?? ""}`).join("; ") };
20046
20046
  } catch (e) {
20047
20047
  return { ok: false, error: e.message };
@@ -20069,7 +20069,7 @@ var init_contracts = __esm({
20069
20069
  contractsDir = fileURLToPath(new URL("../../../contracts/", import.meta.url));
20070
20070
  ajv = new Ajv2020({ allErrors: true, strict: false });
20071
20071
  addFormats(ajv);
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"]) {
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"]) {
20073
20073
  ajv.addSchema(JSON.parse(contractText(f)), f);
20074
20074
  }
20075
20075
  }
@@ -20094,14 +20094,14 @@ function loadPackText(text2, path, opts = {}) {
20094
20094
  throw new PackError(`${path}: pack signed by an untrusted key`);
20095
20095
  signedBy = v.kid;
20096
20096
  }
20097
- const { signature: _s, ...body } = data;
20097
+ const { signature: _s, ...body2 } = data;
20098
20098
  const ids = /* @__PURE__ */ new Set();
20099
20099
  for (const c of data.checks) {
20100
20100
  if (ids.has(c.id))
20101
20101
  throw new PackError(`${path}: duplicate check id ${c.id}`);
20102
20102
  ids.add(c.id);
20103
20103
  }
20104
- return { pack: data, hash: sha256Tag(canonicalize(body)), signedBy };
20104
+ return { pack: data, hash: sha256Tag(canonicalize(body2)), signedBy };
20105
20105
  }
20106
20106
  function loadPackDir(dir, opts) {
20107
20107
  return readdirSync(dir).filter((f) => /\.(ya?ml|json)$/.test(f)).sort().map((f) => loadPack(join2(dir, f), opts));
@@ -20248,9 +20248,9 @@ annotations: ${tsValue(x.suggested)},`);
20248
20248
  lines.push(`${format === "py" ? "#" : "//"} ${sanitizeText(x.tool, 60)}: ${x.conflict}`);
20249
20249
  lines.push("");
20250
20250
  }
20251
- const short = tools.filter((t) => (t.description ?? "").trim().length < 20);
20252
- if (short.length)
20253
- 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(", ")}`);
20254
20254
  const cost = contextCost(tools);
20255
20255
  if (cost.contextCostTokens > 1e4)
20256
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.`);
@@ -32639,15 +32639,15 @@ function applyPublicAuth(clientId, params) {
32639
32639
  }
32640
32640
  async function parseErrorResponse(input) {
32641
32641
  const statusCode = input instanceof Response ? input.status : void 0;
32642
- const body = input instanceof Response ? await input.text() : input;
32642
+ const body2 = input instanceof Response ? await input.text() : input;
32643
32643
  try {
32644
- const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
32644
+ const result = OAuthErrorResponseSchema.parse(JSON.parse(body2));
32645
32645
  const { error: error2, error_description, error_uri } = result;
32646
32646
  const errorClass = OAUTH_ERRORS[error2] || ServerError;
32647
32647
  return new errorClass(error_description || "", error_uri);
32648
32648
  } catch (error2) {
32649
32649
  const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
32650
- 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}`}`;
32651
32651
  return new ServerError(errorMessage);
32652
32652
  }
32653
32653
  }
@@ -33925,12 +33925,12 @@ async function httpRequest(url2, init = {}) {
33925
33925
  res.headers.forEach((v, k) => {
33926
33926
  headers[k.toLowerCase()] = v;
33927
33927
  });
33928
- let body = "";
33928
+ let body2 = "";
33929
33929
  try {
33930
- body = (await res.text()).slice(0, HTTP_LIMITS.maxBodyChars);
33930
+ body2 = (await res.text()).slice(0, HTTP_LIMITS.maxBodyChars);
33931
33931
  } catch {
33932
33932
  }
33933
- return { status: res.status, headers, body, ms: Date.now() - t0 };
33933
+ return { status: res.status, headers, body: body2, ms: Date.now() - t0 };
33934
33934
  } catch (e) {
33935
33935
  return { status: null, headers: {}, body: "", error: e.name === "AbortError" ? "timed out" : e.message, ms: Date.now() - t0 };
33936
33936
  } finally {
@@ -33996,7 +33996,7 @@ var init_dist3 = __esm({
33996
33996
  init_stdio2();
33997
33997
  init_streamableHttp();
33998
33998
  init_types2();
33999
- USER_AGENT = "saktum-check/0.7.0 (+https://saktum.dev/check)";
33999
+ USER_AGENT = "saktum-check/0.8.0 (+https://saktum.dev/check)";
34000
34000
  LIMITS = { requestTimeoutMs: 1e4, connectTimeoutMs: 6e4, maxResponseChars: 5e6 };
34001
34001
  LimitError = class extends Error {
34002
34002
  };
@@ -34034,7 +34034,7 @@ var init_dist3 = __esm({
34034
34034
  jsonrpc: "2.0",
34035
34035
  id: 1,
34036
34036
  method: "initialize",
34037
- params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.7.0" } }
34037
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.8.0" } }
34038
34038
  });
34039
34039
  }
34040
34040
  });
@@ -34592,8 +34592,8 @@ ${JSON.stringify(t.inputSchema ?? {})}`;
34592
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." };
34593
34593
  },
34594
34594
  "short-descriptions": ({ tools }) => {
34595
- const short = tools.filter((t) => (t.description ?? "").trim().length < 20);
34596
- 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." };
34597
34597
  },
34598
34598
  "context-cost": ({ tools, pricePerMTokUsd }) => {
34599
34599
  const { contextCostTokens, largestTools, contextCostPer1kTurnsUsd } = contextCost(tools, pricePerMTokUsd);
@@ -35406,7 +35406,7 @@ var init_engine = __esm({
35406
35406
  init_runner();
35407
35407
  init_safe();
35408
35408
  init_scoring();
35409
- ENGINE_VERSION = "0.7.0";
35409
+ ENGINE_VERSION = "0.8.0";
35410
35410
  UNKNOWN_TOOL = "saktum_trust_check_no_such_tool";
35411
35411
  INVALID_TOKEN = "saktum-check-deliberately-invalid-token";
35412
35412
  baseOf = (pack, check) => ({
@@ -35814,11 +35814,11 @@ function checkAttestation(a) {
35814
35814
  }
35815
35815
  function extractJson(text2) {
35816
35816
  const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text2);
35817
- const body = fenced ? fenced[1] : text2;
35818
- const start = body.indexOf("{"), end = body.lastIndexOf("}");
35817
+ const body2 = fenced ? fenced[1] : text2;
35818
+ const start = body2.indexOf("{"), end = body2.lastIndexOf("}");
35819
35819
  if (start < 0 || end <= start)
35820
35820
  throw new Error("no JSON object found");
35821
- return JSON.parse(body.slice(start, end + 1));
35821
+ return JSON.parse(body2.slice(start, end + 1));
35822
35822
  }
35823
35823
  function appendToLedger(ledgerText, attestation, source, now = /* @__PURE__ */ new Date()) {
35824
35824
  const c = checkAttestation(attestation);
@@ -36118,7 +36118,7 @@ import { homedir as _home } from "node:os";
36118
36118
  import { existsSync as _exists, readFileSync as _read, writeFileSync as _write, mkdirSync as _mkdir } from "node:fs";
36119
36119
  import { dirname as _dirname, join as _join } from "node:path";
36120
36120
  function createMandate(o, ownerKey) {
36121
- const body = {
36121
+ const body2 = {
36122
36122
  mandateFormat: "0.1",
36123
36123
  agent: { id: o.agentId, name: sanitizeText(o.agentName, 120) },
36124
36124
  owner: { id: ownerKey.kid, ...o.ownerName ? { name: sanitizeText(o.ownerName, 120) } : {} },
@@ -36141,7 +36141,7 @@ function createMandate(o, ownerKey) {
36141
36141
  ...o.counterparties?.length ? { counterparties: o.counterparties } : {},
36142
36142
  ...o.dataSharing?.length ? { dataSharing: o.dataSharing } : {}
36143
36143
  };
36144
- return signDocument(body, ownerKey);
36144
+ return signDocument(body2, ownerKey);
36145
36145
  }
36146
36146
  function checkMandate(m, today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)) {
36147
36147
  const { operatorCountersign: _cs, ...principalPart } = m;
@@ -36594,6 +36594,239 @@ var init_watch = __esm({
36594
36594
  }
36595
36595
  });
36596
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
+
36597
36830
  // packages/testkit-core/dist/index.js
36598
36831
  var dist_exports = {};
36599
36832
  __export(dist_exports, {
@@ -36604,6 +36837,7 @@ __export(dist_exports, {
36604
36837
  DEFAULT_APPROVALS: () => DEFAULT_APPROVALS,
36605
36838
  DEFAULT_LEDGER_URL: () => DEFAULT_LEDGER_URL,
36606
36839
  DEFAULT_REVOCATIONS: () => DEFAULT_REVOCATIONS,
36840
+ DEFAULT_TERMS: () => DEFAULT_TERMS,
36607
36841
  EMBEDDED_CONTRACTS: () => EMBEDDED_CONTRACTS,
36608
36842
  EMBEDDED_PACKS: () => EMBEDDED_PACKS,
36609
36843
  ENGINE_VERSION: () => ENGINE_VERSION,
@@ -36617,6 +36851,7 @@ __export(dist_exports, {
36617
36851
  MIN_GRADED_CHECKS: () => MIN_GRADED_CHECKS,
36618
36852
  PERF_NEEDS: () => PERF_NEEDS,
36619
36853
  PERF_THRESHOLDS: () => PERF_THRESHOLDS,
36854
+ PREPAID: () => PREPAID,
36620
36855
  PackError: () => PackError,
36621
36856
  READINESS: () => READINESS,
36622
36857
  RECEIPTS_GENESIS: () => RECEIPTS_GENESIS,
@@ -36629,6 +36864,7 @@ __export(dist_exports, {
36629
36864
  TRUST_WEIGHTS: () => TRUST_WEIGHTS,
36630
36865
  UNKNOWN_TOOL: () => UNKNOWN_TOOL,
36631
36866
  VOCABULARIES: () => VOCABULARIES,
36867
+ acceptAgreement: () => acceptAgreement,
36632
36868
  actionClass: () => actionClass,
36633
36869
  agentRiskTier: () => agentRiskTier,
36634
36870
  allowlistFromLedger: () => allowlistFromLedger,
@@ -36645,8 +36881,10 @@ __export(dist_exports, {
36645
36881
  buildAllowlist: () => buildAllowlist,
36646
36882
  buildAttestation: () => buildAttestation,
36647
36883
  buildFleet: () => buildFleet,
36884
+ buildManifest: () => buildManifest,
36648
36885
  capabilityProfile: () => capabilityProfile,
36649
36886
  chainEntry: () => chainEntry,
36887
+ chargeCall: () => chargeCall,
36650
36888
  checkAttestation: () => checkAttestation,
36651
36889
  checkMandate: () => checkMandate,
36652
36890
  checkNeedsSession: () => checkNeedsSession,
@@ -36667,16 +36905,20 @@ __export(dist_exports, {
36667
36905
  describeMandate: () => describeMandate,
36668
36906
  diffLocks: () => diffLocks,
36669
36907
  docsFor: () => docsFor,
36908
+ draftAgreement: () => draftAgreement,
36670
36909
  escapeHtml: () => escapeHtml,
36671
36910
  evaluatePolicy: () => evaluatePolicy,
36672
36911
  exampleFor: () => exampleFor,
36673
36912
  extractJson: () => extractJson,
36674
36913
  findInLedger: () => findInLedger,
36914
+ findOrphans: () => findOrphans,
36675
36915
  fleetHtml: () => fleetHtml,
36676
36916
  gradeFor: () => gradeFor,
36677
36917
  hasIntent: () => hasIntent,
36678
36918
  invalidArgProblems: () => invalidArgProblems,
36679
36919
  invalidArgsFor: () => invalidArgsFor,
36920
+ issueCredential: () => issueCredential,
36921
+ kpis: () => kpis,
36680
36922
  leakageAnalysers: () => leakageAnalysers,
36681
36923
  lintPaths: () => lintPaths,
36682
36924
  lintSarif: () => lintSarif,
@@ -36690,6 +36932,7 @@ __export(dist_exports, {
36690
36932
  maxDepth: () => maxDepth,
36691
36933
  measureLoad: () => measureLoad,
36692
36934
  needsOf: () => needsOf,
36935
+ organisationRoot: () => organisationRoot,
36693
36936
  outcomeText: () => outcomeText,
36694
36937
  parseChallenge: () => parseChallenge,
36695
36938
  parseClientConfig: () => parseClientConfig,
@@ -36719,6 +36962,7 @@ __export(dist_exports, {
36719
36962
  sanitizeText: () => sanitizeText,
36720
36963
  schemaDialect: () => schemaDialect,
36721
36964
  score: () => score,
36965
+ searchCatalogue: () => searchCatalogue,
36722
36966
  semanticValues: () => semanticValues,
36723
36967
  signCredentialJwt: () => signCredentialJwt,
36724
36968
  signReceipt: () => signReceipt,
@@ -36729,13 +36973,19 @@ __export(dist_exports, {
36729
36973
  suggestAnnotations: () => suggestAnnotations,
36730
36974
  summarise: () => summarise,
36731
36975
  summariseReceipts: () => summariseReceipts,
36976
+ tokensFor: () => tokensFor,
36732
36977
  toolsContextCost: () => contextCost,
36733
36978
  toolsLock: () => toolsLock,
36979
+ topUp: () => topUp,
36734
36980
  trustStatement: () => trustStatement,
36981
+ usageStatement: () => usageStatement,
36982
+ verifyAgreement: () => verifyAgreement,
36983
+ verifyChain: () => verifyChain,
36735
36984
  verifyCredentialJwt: () => verifyCredentialJwt,
36736
36985
  verifyLedger: () => verifyLedger,
36737
36986
  verifyReceipt: () => verifyReceipt,
36738
36987
  verifyReceiptLog: () => verifyReceiptLog,
36988
+ walletBalance: () => walletBalance,
36739
36989
  watchAllowlist: () => watchAllowlist,
36740
36990
  wellKnownUrls: () => wellKnownUrls
36741
36991
  });
@@ -36771,6 +37021,7 @@ var init_dist4 = __esm({
36771
37021
  init_watch();
36772
37022
  init_risk();
36773
37023
  init_vocab();
37024
+ init_market();
36774
37025
  }
36775
37026
  });
36776
37027
 
@@ -36793,7 +37044,7 @@ function renderServerPassport(r, tools, o = {}) {
36793
37044
  const req = (t.inputSchema?.required ?? []).join(", ");
36794
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>`;
36795
37046
  }).join("");
36796
- 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>
36797
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>
36798
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>
36799
37050
  <div class="card"><h2>Maturity</h2>${levelBar(lvl, lvl === 4 ? "L5 also needs supply-chain evidence (provenance, no install scripts)" : void 0)}</div>
@@ -36801,7 +37052,7 @@ ${r.riskTier ? `<div class="card"><h2>Risk tier</h2><p><b>${esc2(r.riskTier.tier
36801
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>
36802
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>
36803
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>`;
36804
- return page(`${name}: MCP Server Passport`, body);
37055
+ return page(`${name}: MCP Server Passport`, body2);
36805
37056
  }
36806
37057
  function renderAgentPassport(m, valid, receipts, tier, plain, extra = {}) {
36807
37058
  const AUTO = { notify: "Notify only: it alerts, never acts", propose: "Propose: it suggests, you approve", act: "Act: within the limits below" };
@@ -36818,7 +37069,7 @@ function renderAgentPassport(m, valid, receipts, tier, plain, extra = {}) {
36818
37069
  ].map(([k, v]) => `<tr><td><b>${esc2(k)}</b></td><td>${esc2(v)}</td></tr>`).join("");
36819
37070
  const s = receipts?.summary;
36820
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>');
36821
- 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>
36822
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>
36823
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>
36824
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>` : ""}
@@ -36831,17 +37082,17 @@ ${s.repeatedIdenticalCalls.length ? `<p><b>Repeated identical calls:</b> ${s.rep
36831
37082
  <h2 style="margin-top:14px">The path, not the answer</h2><div class="timeline">${steps}</div>
36832
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>` : ""}
36833
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>`;
36834
- return page(`${m.agent.name}: Agent Passport`, body);
37085
+ return page(`${m.agent.name}: Agent Passport`, body2);
36835
37086
  }
36836
37087
  function renderLedgerPassport(e) {
36837
37088
  const c = e.attestation.claims, g = c.trustGrade ?? "-";
36838
- 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>
36839
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>
36840
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>
36841
37092
  <div class="card"><h2>Maturity evidence</h2>${levelBar(evidenceLevel(c.evidence))}</div>
36842
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>
36843
37094
  <p class="muted"><a href="index.html">All passports</a> \xB7 <a href="../index.html">State of MCP Trust</a></p>`;
36844
- return page(`${e.subject.server}: MCP Server Passport`, body);
37095
+ return page(`${e.subject.server}: MCP Server Passport`, body2);
36845
37096
  }
36846
37097
  function renderPassportGallery(entries) {
36847
37098
  const latest = /* @__PURE__ */ new Map();
@@ -36875,7 +37126,7 @@ function renderAssessment(org, f, receipts = [], roi) {
36875
37126
  if (tokens > 5e4)
36876
37127
  rec.push(`Tool definitions cost ${tokens.toLocaleString("en-US")} tokens per turn across distinct servers: remove duplicates and unused servers.`);
36877
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("");
36878
- 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>
36879
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>
36880
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>
36881
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>
@@ -36883,7 +37134,7 @@ ${rc ? `<div class="card"><h2>Agent receipts</h2><div class="wrap"><table><tr><t
36883
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>` : ""}
36884
37135
  <div class="card"><h2>Recommendations</h2><ol>${rec.map((x) => `<li>${esc2(x)}</li>`).join("")}</ol></div>
36885
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>`;
36886
- return page(`MCP Trust Assessment: ${org}`, body);
37137
+ return page(`MCP Trust Assessment: ${org}`, body2);
36887
37138
  }
36888
37139
  var esc2, GRADE_COLOUR, chip, STYLE, page, levelBar, effect, passportSlug, evidenceLevel;
36889
37140
  var init_passport = __esm({
@@ -36906,7 +37157,7 @@ code{font:12.5px ui-monospace,Menlo,Consolas,monospace;word-break:break-all}.lev
36906
37157
  .ok{background:#e8f5e9;color:#1b5e20}.deny{background:#ffebee;color:#b71c1c}.err{background:#fff8e1;color:#7a5a00}.rep{outline:2px solid #b7791f}
36907
37158
  @media (prefers-color-scheme:dark){.ok{background:#1b3a1e;color:#a5d6a7}.deny{background:#3b1616;color:#ef9a9a}.err{background:#3a3214;color:#ffe082}}
36908
37159
  @media print{body{background:#fff}.card{break-inside:avoid}}`;
36909
- 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>
36910
37161
  `;
36911
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>`;
36912
37163
  effect = (t) => {
@@ -37234,10 +37485,10 @@ __export(init_exports, {
37234
37485
  AGENT_RULES: () => AGENT_RULES,
37235
37486
  initProject: () => initProject
37236
37487
  });
37237
- 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";
37238
37489
  import { join as join4 } from "node:path";
37239
37490
  function initProject(dir, lang, name) {
37240
- 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")))
37241
37492
  throw new Error(`${dir} already contains a project; choose an empty folder.`);
37242
37493
  const id = name.replace(/[^a-z0-9-]/gi, "-").toLowerCase() || "my-mcp-server";
37243
37494
  const files = {};
@@ -37327,8 +37578,8 @@ if __name__ == "__main__":
37327
37578
  ${AGENT_RULES}`;
37328
37579
  for (const [p, text2] of Object.entries(files)) {
37329
37580
  const f = join4(dir, p);
37330
- mkdirSync2(join4(f, ".."), { recursive: true });
37331
- writeFileSync2(f, text2);
37581
+ mkdirSync3(join4(f, ".."), { recursive: true });
37582
+ writeFileSync3(f, text2);
37332
37583
  }
37333
37584
  return Object.keys(files);
37334
37585
  }
@@ -37415,16 +37666,16 @@ __export(proxy_exports, {
37415
37666
  runProxy: () => runProxy
37416
37667
  });
37417
37668
  import { spawn as spawn3 } from "node:child_process";
37418
- import { appendFileSync, existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync5 } from "node:fs";
37419
- 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";
37420
37671
  import { createInterface } from "node:readline";
37421
37672
  import { randomUUID } from "node:crypto";
37422
37673
  async function runProxy(o) {
37423
- mkdirSync3(dirname2(o.receiptsPath), { recursive: true });
37674
+ mkdirSync4(dirname3(o.receiptsPath), { recursive: true });
37424
37675
  let last;
37425
37676
  let history = [];
37426
- if (existsSync4(o.receiptsPath)) {
37427
- history = parseReceiptLog(readFileSync5(o.receiptsPath, "utf8"));
37677
+ if (existsSync5(o.receiptsPath)) {
37678
+ history = parseReceiptLog(readFileSync6(o.receiptsPath, "utf8"));
37428
37679
  last = history[history.length - 1];
37429
37680
  }
37430
37681
  const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
@@ -37510,6 +37761,30 @@ async function runProxy(o) {
37510
37761
  else
37511
37762
  d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
37512
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
+ }
37513
37788
  if (!d.allow && o.enforce) {
37514
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.";
37515
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");
@@ -37518,7 +37793,7 @@ async function runProxy(o) {
37518
37793
  return;
37519
37794
  }
37520
37795
  const code = !d.allow ? `observed-${d.code}` : ann?.readOnlyHint === true ? "ok-read" : "ok-action";
37521
- 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 });
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 });
37522
37797
  }
37523
37798
  child.stdin.write(line + "\n");
37524
37799
  });
@@ -37560,7 +37835,7 @@ async function runProxy(o) {
37560
37835
  if (c) {
37561
37836
  calls.delete(k);
37562
37837
  const status = msg.error ? "protocol-error" : msg.result?.isError ? "tool-error" : "ok";
37563
- 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 } : {} });
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 } : {} });
37564
37839
  }
37565
37840
  process.stdout.write(line + "\n");
37566
37841
  });
@@ -38259,7 +38534,7 @@ __export(demo_exports, {
38259
38534
  runDemo: () => runDemo,
38260
38535
  startDemoServer: () => startDemoServer
38261
38536
  });
38262
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync5, rmSync } from "node:fs";
38537
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync4, existsSync as existsSync6, rmSync } from "node:fs";
38263
38538
  import { join as join5 } from "node:path";
38264
38539
  async function startDemoServer(story = "autonomy") {
38265
38540
  const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : DEMO_TOOLS;
@@ -38321,7 +38596,7 @@ async function runStory(dir, st, owner, log) {
38321
38596
  const operatorName = String(st.m.disclosures?.operator ?? "Demo operator");
38322
38597
  const cm = cosignMandate(m, loadOrCreateKey(join5(dir, `${st.id}-operator-key.json`)), operatorName);
38323
38598
  const mf = join5(dir, `${st.id}-mandate.json`), rf = join5(dir, `${st.id}-receipts.jsonl`), revf = join5(dir, "revocations.json");
38324
- writeFileSync3(mf, JSON.stringify(cm, null, 2));
38599
+ writeFileSync4(mf, JSON.stringify(cm, null, 2));
38325
38600
  log(`\u2500\u2500 ${st.title}`);
38326
38601
  log(` Signed by you; countersigned by the operator, ${operatorName}.`);
38327
38602
  for (const line of describeMandate(m))
@@ -38344,9 +38619,9 @@ async function runStory(dir, st, owner, log) {
38344
38619
  if (rid)
38345
38620
  lastRid = rid[1];
38346
38621
  const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)( \[approval request [^\]]+\])?\.( Ask| Tell|$)/.exec(txt);
38347
- const lastR = parseReceiptLog(readFileSync6(rf, "utf8")).pop();
38622
+ const lastR = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
38348
38623
  log(blocked ? ` \u26D4 ${step.say}: ${blocked[1]}: ${blocked[2]}` : ` \u2713 ${step.say}${/approved by/.test(String(lastR?.receipt.reason ?? "")) ? ": approved by you, once" : ""}`);
38349
- const last = parseReceiptLog(readFileSync6(rf, "utf8")).pop();
38624
+ const last = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
38350
38625
  for (const p of last?.result.rationale?.preferences ?? [])
38351
38626
  if (!blocked)
38352
38627
  log(` \xB7 ${p}`);
@@ -38371,13 +38646,13 @@ async function runStory(dir, st, owner, log) {
38371
38646
  await new Promise((r) => setTimeout(r, 300));
38372
38647
  }
38373
38648
  }
38374
- const entries = parseReceiptLog(readFileSync6(rf, "utf8"));
38649
+ const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
38375
38650
  const ts = trustStatement(entries, verifyReceiptLog(entries).ok);
38376
38651
  log(" Track record:");
38377
38652
  for (const l of ts.lines)
38378
38653
  log(` ${l}`);
38379
38654
  const html = join5(dir, `${st.id}-passport.html`);
38380
- writeFileSync3(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38655
+ writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38381
38656
  verified: verifyReceiptLog(entries).ok,
38382
38657
  summary: summariseReceipts(entries),
38383
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 ") }))
@@ -38389,24 +38664,147 @@ async function runStory(dir, st, owner, log) {
38389
38664
  `);
38390
38665
  return html;
38391
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
+ }
38392
38775
  async function runDemo(dir, log, story = "all") {
38393
38776
  if (story === "autonomy")
38394
38777
  return runAutonomyDemo(dir, log);
38395
- if (existsSync5(dir))
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))
38396
38785
  rmSync(dir, { recursive: true, force: true });
38397
- mkdirSync4(dir, { recursive: true });
38786
+ mkdirSync5(dir, { recursive: true });
38398
38787
  const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
38399
38788
  log("Saktum demo: agents acting on real instructions (rules, preferences, substitutions, upsells), every decision explained and signed.\n");
38400
38789
  const files = [];
38401
38790
  for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : [GROCERY, TRAVEL, FINANCE])
38402
38791
  files.push(await runStory(dir, st, owner, log));
38403
- log("What you just saw: each agent followed its owner's instructions, not just limits. Even when tricked by a hidden\ninstruction, the mandate held; personal and confidential data went only where you allowed; a big invoice waited for your\nsigned approval of exactly that payment; and the stop button worked. Blocked steps never\nreached the store or airline, and every decision has a signed receipt with its reason. Open the passports for the\ninstructions in plain words, the track record and the reason for every step. Also try: npx saktum demo --story autonomy");
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"));
38404
38802
  return { files };
38405
38803
  }
38406
38804
  async function runAutonomyDemo(dir, log) {
38407
- if (existsSync5(dir))
38805
+ if (existsSync6(dir))
38408
38806
  rmSync(dir, { recursive: true, force: true });
38409
- mkdirSync4(dir, { recursive: true });
38807
+ mkdirSync5(dir, { recursive: true });
38410
38808
  const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
38411
38809
  const self = [...process.execArgv, process.argv[1]];
38412
38810
  const tools = DEMO_TOOLS.map((t) => t.name);
@@ -38431,7 +38829,7 @@ async function runAutonomyDemo(dir, log) {
38431
38829
  ...p.m
38432
38830
  }, owner);
38433
38831
  const mf = join5(dir, `${p.id}-mandate.json`), rf = join5(dir, `${p.id}-receipts.jsonl`);
38434
- writeFileSync3(mf, JSON.stringify(m, null, 2));
38832
+ writeFileSync4(mf, JSON.stringify(m, null, 2));
38435
38833
  const tier = agentRiskTier(m);
38436
38834
  log(`\u2500\u2500 ${p.title} autonomy ${m.autonomy} \xB7 risk ${tier.tier}`);
38437
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"] });
@@ -38447,14 +38845,14 @@ async function runAutonomyDemo(dir, log) {
38447
38845
  await s.close();
38448
38846
  await new Promise((r) => setTimeout(r, 300));
38449
38847
  }
38450
- const entries = parseReceiptLog(readFileSync6(rf, "utf8"));
38848
+ const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
38451
38849
  const counts = /* @__PURE__ */ new Map();
38452
38850
  for (const e of entries) {
38453
38851
  const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
38454
38852
  counts.set(k, (counts.get(k) ?? 0) + 1);
38455
38853
  }
38456
38854
  const html = join5(dir, `${p.id}-passport.html`);
38457
- writeFileSync3(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38855
+ writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
38458
38856
  verified: verifyReceiptLog(entries).ok,
38459
38857
  summary: summariseReceipts(entries),
38460
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 }))
@@ -38603,7 +39001,7 @@ __export(mcp_server_exports, {
38603
39001
  splitTarget: () => splitTarget,
38604
39002
  startMcpServer: () => startMcpServer
38605
39003
  });
38606
- import { readFileSync as readFileSync7 } from "node:fs";
39004
+ import { readFileSync as readFileSync8 } from "node:fs";
38607
39005
  function splitTarget(target) {
38608
39006
  const t = target.trim();
38609
39007
  if (/^https?:\/\//i.test(t))
@@ -38639,7 +39037,7 @@ async function handleSaktumTool(name, args, packs) {
38639
39037
  case "diff_against_lock": {
38640
39038
  if (typeof args.lock_path !== "string")
38641
39039
  throw new Error("lock_path is required");
38642
- const before = JSON.parse(readFileSync7(args.lock_path, "utf8"));
39040
+ const before = JSON.parse(readFileSync8(args.lock_path, "utf8"));
38643
39041
  const d = diffLocks(before, { tools: (await listTools(targetOf(args.target))).tools });
38644
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 });
38645
39043
  }
@@ -38780,7 +39178,7 @@ var init_mcp_server = __esm({
38780
39178
  });
38781
39179
 
38782
39180
  // packages/cli/dist/main.js
38783
- import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "node:fs";
39181
+ import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
38784
39182
  import { fileURLToPath as fileURLToPath2 } from "node:url";
38785
39183
 
38786
39184
  // node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
@@ -38947,13 +39345,13 @@ init_dist3();
38947
39345
  var SEV2 = ["critical", "high", "medium", "low", "info"];
38948
39346
  async function loadPolicy(file) {
38949
39347
  const { readFileSync: rf, existsSync: ex } = await import("node:fs");
38950
- const { dirname: dirname3, resolve } = await import("node:path");
39348
+ const { dirname: dirname4, resolve } = await import("node:path");
38951
39349
  if (!ex(file))
38952
39350
  throw new Error(`Policy file not found: ${file}`);
38953
39351
  const policy = await parsePolicy(rf(file, "utf8"));
38954
39352
  let allow;
38955
39353
  if (policy.allowlist) {
38956
- const path = resolve(dirname3(file), policy.allowlist);
39354
+ const path = resolve(dirname4(file), policy.allowlist);
38957
39355
  if (!ex(path))
38958
39356
  throw new Error(`The policy's allowlist was not found: ${policy.allowlist}`);
38959
39357
  allow = new Set(JSON.parse(rf(path, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f)));
@@ -39016,16 +39414,16 @@ async function main(argv = process.argv) {
39016
39414
  });
39017
39415
  let testCases;
39018
39416
  if (o.tests) {
39019
- if (!existsSync6(o.tests))
39417
+ if (!existsSync7(o.tests))
39020
39418
  throw new Error(`Test file not found: ${o.tests}. See docs/TESTS.md for the format.`);
39021
- testCases = await parseTestCases(readFileSync8(o.tests, "utf8"));
39419
+ testCases = await parseTestCases(readFileSync9(o.tests, "utf8"));
39022
39420
  }
39023
39421
  const target = parseTarget(targetParts);
39024
39422
  if (target.kind === "stdio" && o.env.length)
39025
39423
  target.env = parseEnv(o.env);
39026
39424
  if (target.kind === "streamable-http" && o.header.length)
39027
39425
  target.headers = parseHeaders(o.header);
39028
- const packs = o.packs ? loadPackDir(o.packs) : existsSync6(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39426
+ const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39029
39427
  let result;
39030
39428
  try {
39031
39429
  result = await runTrustCheck(target, { packs, mode: o.active ? "active" : "passive", pricePerMTokUsd: price, callTools: o.call, testCases, ignore });
@@ -39037,23 +39435,23 @@ async function main(argv = process.argv) {
39037
39435
  return 2;
39038
39436
  }
39039
39437
  const signed = signDocument(result, loadOrCreateKey(o.key));
39040
- writeFileSync4(o.out, JSON.stringify(signed, null, 2));
39438
+ writeFileSync5(o.out, JSON.stringify(signed, null, 2));
39041
39439
  if (o.html)
39042
- writeFileSync4(o.html, renderHtml(signed));
39440
+ writeFileSync5(o.html, renderHtml(signed));
39043
39441
  if (o.badge)
39044
- writeFileSync4(o.badge, badgeSvg(signed));
39442
+ writeFileSync5(o.badge, badgeSvg(signed));
39045
39443
  const keyOf = (f) => `${f.check}:${f.subject ?? ""}`;
39046
39444
  const failing = signed.findings.filter((f) => f.status === "fail" && !f.suppressed);
39047
39445
  let accepted = /* @__PURE__ */ new Set();
39048
39446
  if (o.baseline && o.updateBaseline) {
39049
- writeFileSync4(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");
39050
39448
  process.stdout.write(`Wrote baseline ${sanitizeText(o.baseline)} accepting ${failing.length} existing finding(s). Commit it; later runs fail only on new findings.
39051
39449
  `);
39052
- } else if (o.baseline && existsSync6(o.baseline)) {
39053
- accepted = new Set(JSON.parse(readFileSync8(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));
39054
39452
  }
39055
39453
  if (o.sarif)
39056
- writeFileSync4(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");
39057
39455
  process.stdout.write(renderTerminal(signed) + "\n");
39058
39456
  process.stdout.write(`
39059
39457
  Signed result: ${sanitizeText(o.out)} (verify with: saktum verify ${sanitizeText(o.out)})${o.badge ? `
@@ -39122,7 +39520,7 @@ Watching ${sanitizeText(o.watchDir)} for changes (Ctrl+C to stop).
39122
39520
  exitCode = await runCheckCommand(targetParts, o);
39123
39521
  });
39124
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) => {
39125
- const packs = o.packs ? loadPackDir(o.packs) : existsSync6(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39523
+ const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39126
39524
  process.stdout.write(checksTable(packs, o.markdown));
39127
39525
  });
39128
39526
  const listTarget = async (targetParts, env, header) => {
@@ -39144,13 +39542,13 @@ Watching ${sanitizeText(o.watchDir)} for changes (Ctrl+C to stop).
39144
39542
  });
39145
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) => {
39146
39544
  const { tools, server } = await listTarget(targetParts, o.env, o.header);
39147
- writeFileSync4(o.out, JSON.stringify(toolsLock(tools, server), null, 2) + "\n");
39545
+ writeFileSync5(o.out, JSON.stringify(toolsLock(tools, server), null, 2) + "\n");
39148
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.
39149
39547
  `);
39150
39548
  });
39151
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) => {
39152
- const before = JSON.parse(readFileSync8(lock, "utf8"));
39153
- const after = rest.length === 1 && rest[0].endsWith(".json") ? JSON.parse(readFileSync8(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 };
39154
39552
  const d = diffLocks(before, after);
39155
39553
  const mark2 = { breaking: "\u2717 BREAKING", risky: "! REVIEW ", addition: "+ ADDED ", change: "~ CHANGED " };
39156
39554
  for (const c of d.changes)
@@ -39167,11 +39565,11 @@ ${d.summary}
39167
39565
  process.stdout.write(docsFor(tools, name, target.kind === "stdio" ? { command: target.command, args: target.args } : { url: target.url }));
39168
39566
  });
39169
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) => {
39170
- const doc = JSON.parse(readFileSync8(file, "utf8"));
39568
+ const doc = JSON.parse(readFileSync9(file, "utf8"));
39171
39569
  const v = verifyDocument(doc);
39172
39570
  if (!v.valid)
39173
39571
  throw new Error(`The result's signature is not valid (${v.reason}); a packet must be built from an unaltered signed result.`);
39174
- writeFileSync4(o.out, renderPacket(doc, v.kid));
39572
+ writeFileSync5(o.out, renderPacket(doc, v.kid));
39175
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.
39176
39574
  `);
39177
39575
  });
@@ -39181,9 +39579,9 @@ ${d.summary}
39181
39579
  const check = verifyLedger(entries);
39182
39580
  if (!check.ok)
39183
39581
  throw new Error(`The ledger does not verify: ${check.errors[0]}`);
39184
- const signers = o.trustedSigners ? new Set(readFileSync8(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;
39185
39583
  const list2 = allowlistFromLedger(entries, { minTrust: o.minTrust.toUpperCase(), minReadiness: o.minReadiness.toUpperCase(), trustedSigners: signers });
39186
- writeFileSync4(o.out, JSON.stringify(list2, null, 2) + "\n");
39584
+ writeFileSync5(o.out, JSON.stringify(list2, null, 2) + "\n");
39187
39585
  process.stdout.write(`Ledger verified (${check.count} entries). Wrote ${sanitizeText(o.out)}: ${list2.allowed.length} allowed, ${list2.excluded.length} excluded.
39188
39586
  `);
39189
39587
  return;
@@ -39191,14 +39589,14 @@ ${d.summary}
39191
39589
  if (!files.length)
39192
39590
  throw new Error("Give signed results, or use --from-ledger.");
39193
39591
  const inputs = files.map((f) => {
39194
- const doc = JSON.parse(readFileSync8(f, "utf8"));
39592
+ const doc = JSON.parse(readFileSync9(f, "utf8"));
39195
39593
  const v = verifyDocument(doc);
39196
39594
  if (!v.valid)
39197
39595
  throw new Error(`${f}: signature not valid (${v.reason}); only unaltered signed results can be allowlisted.`);
39198
39596
  return { result: doc, signedBy: v.kid };
39199
39597
  });
39200
39598
  const list = buildAllowlist(inputs, { minTrust: o.minTrust.toUpperCase(), minReadiness: o.minReadiness.toUpperCase(), noFailedCritical: !o.allowCritical });
39201
- writeFileSync4(o.out, JSON.stringify(list, null, 2) + "\n");
39599
+ writeFileSync5(o.out, JSON.stringify(list, null, 2) + "\n");
39202
39600
  for (const a of list.allowed)
39203
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
39204
39602
  `);
@@ -39235,7 +39633,7 @@ Next:
39235
39633
  ${findings.length} finding(s) in tool definitions.
39236
39634
  ` : "No problems found in tool definitions (files importing an MCP SDK).\n");
39237
39635
  if (o.sarif)
39238
- writeFileSync4(o.sarif, JSON.stringify(lintSarif(findings, ENGINE_VERSION), null, 2) + "\n");
39636
+ writeFileSync5(o.sarif, JSON.stringify(lintSarif(findings, ENGINE_VERSION), null, 2) + "\n");
39239
39637
  exitCode = findings.some((f) => f.severity === "error" || o.strict) ? 1 : 0;
39240
39638
  });
39241
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) => {
@@ -39278,7 +39676,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
39278
39676
  expect.outputSchema = true;
39279
39677
  expect.latencyMs = { lt: Math.max(2e3, outcome.latencyMs * 5) };
39280
39678
  const tc = { id: o.saveTest, tool: toolName, input: args, ...tool.annotations?.readOnlyHint === true ? {} : { sideEffects: true }, expect };
39281
- writeFileSync4(o.tests, await appendTestCase(existsSync6(o.tests) ? readFileSync8(o.tests, "utf8") : void 0, tc));
39679
+ writeFileSync5(o.tests, await appendTestCase(existsSync7(o.tests) ? readFileSync9(o.tests, "utf8") : void 0, tc));
39282
39680
  process.stdout.write(`Saved test case ${sanitizeText(o.saveTest, 60)} to ${sanitizeText(o.tests)}. Run: saktum test -- <start command>
39283
39681
  `);
39284
39682
  }
@@ -39286,7 +39684,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
39286
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) => {
39287
39685
  const { homedir: homedir2 } = await import("node:os");
39288
39686
  const locations = o.config.length ? o.config.map((file) => ({ client: "configuration", file })) : configLocations(homedir2(), process.cwd(), process.platform, process.env.APPDATA);
39289
- const servers = locations.filter((l) => existsSync6(l.file)).flatMap((l) => parseClientConfig(readFileSync8(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);
39290
39688
  if (!servers.length) {
39291
39689
  process.stdout.write("No MCP servers found in the known configuration locations. Point to one with --config <file>.\n");
39292
39690
  return;
@@ -39309,7 +39707,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
39309
39707
  return;
39310
39708
  }
39311
39709
  }
39312
- const packs = existsSync6(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39710
+ const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39313
39711
  const scans = [];
39314
39712
  for (const x of servers) {
39315
39713
  let tools = [];
@@ -39336,7 +39734,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
39336
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) });
39337
39735
  }
39338
39736
  }
39339
- const allow = o.allowlist ? new Set(JSON.parse(readFileSync8(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;
39340
39738
  const report = analyseSetup(scans, { turnsPerDay: Number(o.turnsPerDay) || 50, pricePerMTokUsd: Number(o.pricePerMtok) || 3, allowlistFingerprints: allow });
39341
39739
  process.stdout.write("\n" + renderSetup(report));
39342
39740
  if (o.policy) {
@@ -39349,10 +39747,10 @@ POLICY${policy.name ? ` (${sanitizeText(policy.name, 80)})` : ""}
39349
39747
  }
39350
39748
  const { hostname } = await import("node:os");
39351
39749
  if (o.out)
39352
- writeFileSync4(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");
39353
39751
  });
39354
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) => {
39355
- const r = verifyCredentialJwt(readFileSync8(f, "utf8"));
39753
+ const r = verifyCredentialJwt(readFileSync9(f, "utf8"));
39356
39754
  if (r.valid) {
39357
39755
  const cs = r.credential.credentialSubject ?? {};
39358
39756
  process.stdout.write(`\u2713 Valid credential from ${r.issuer}: ${sanitizeText(String(cs.server ?? ""), 80)} trust ${cs.trustGrade ?? "-"}, readiness ${cs.readinessGrade ?? "-"}.
@@ -39385,21 +39783,21 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
39385
39783
  const v = verifyLedger(entries);
39386
39784
  if (!v.ok)
39387
39785
  throw new Error(`The ledger does not verify: ${v.errors[0]}`);
39388
- const { mkdirSync: mkdirSync5 } = await import("node:fs");
39389
- mkdirSync5(o.out, { recursive: true });
39786
+ const { mkdirSync: mkdirSync6 } = await import("node:fs");
39787
+ mkdirSync6(o.out, { recursive: true });
39390
39788
  const latest = /* @__PURE__ */ new Map();
39391
39789
  for (const e of entries)
39392
39790
  latest.set(e.subject.server, e);
39393
39791
  for (const e of latest.values())
39394
- writeFileSync4(`${o.out}/${passportSlug(e.subject.server)}.html`, renderLedgerPassport(e));
39395
- writeFileSync4(`${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));
39396
39794
  process.stdout.write(`Wrote ${latest.size} passport page(s) and the gallery to ${sanitizeText(o.out)}.
39397
39795
  `);
39398
39796
  });
39399
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) => {
39400
- const att = extractJson(readFileSync8(input, "utf8"));
39401
- const { text: text2, entry } = appendToLedger(existsSync6(o.ledger) ? readFileSync8(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
39402
- writeFileSync4(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);
39403
39801
  process.stdout.write(`Recorded entry #${entry.seq} for ${sanitizeText(entry.subject.server, 80)} (signed by ${entry.signer}); entry hash ${entry.entryHash}.
39404
39802
  `);
39405
39803
  });
@@ -39445,17 +39843,17 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
39445
39843
  approveAbove: aa,
39446
39844
  disclosures: { ...o.operator ? { operator: o.operator } : {}, ...o.incentives ? { incentives: o.incentives } : {}, ...o.dataUse ? { dataUse: o.dataUse } : {} },
39447
39845
  delegation: o.allowDelegation,
39448
- ...o.intent ? JSON.parse(readFileSync8(o.intent, "utf8")) : {}
39846
+ ...o.intent ? JSON.parse(readFileSync9(o.intent, "utf8")) : {}
39449
39847
  }, loadOrCreateKey(o.key));
39450
39848
  if (o.software) {
39451
- const { signature: _old, ...body } = m;
39452
- body.agent = { ...body.agent, software: o.software };
39453
- Object.assign(m, signDocument(body, loadOrCreateKey(o.key)));
39849
+ const { signature: _old, ...body2 } = m;
39850
+ body2.agent = { ...body2.agent, software: o.software };
39851
+ Object.assign(m, signDocument(body2, loadOrCreateKey(o.key)));
39454
39852
  }
39455
39853
  const valid = compileContract("mandate.schema.json");
39456
39854
  if (!valid(m))
39457
39855
  throw new Error(`The mandate is not valid: ${(valid.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}`);
39458
- writeFileSync4(o.out, JSON.stringify(m, null, 2) + "\n");
39856
+ writeFileSync5(o.out, JSON.stringify(m, null, 2) + "\n");
39459
39857
  for (const line of describeMandate(m))
39460
39858
  process.stdout.write(` ${line}
39461
39859
  `);
@@ -39465,7 +39863,7 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
39465
39863
  `);
39466
39864
  });
39467
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) => {
39468
- const m = JSON.parse(readFileSync8(f, "utf8"));
39866
+ const m = JSON.parse(readFileSync9(f, "utf8"));
39469
39867
  const c = checkMandate(m), op = checkOperator(m), rev = revocationOf(m);
39470
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}.
39471
39869
  ` : `\u2717 ${c.reason}
@@ -39480,32 +39878,32 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
39480
39878
  exitCode = c.ok && (!op.present || op.valid) && !rev ? 0 : 1;
39481
39879
  });
39482
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) => {
39483
- const m = JSON.parse(readFileSync8(f, "utf8"));
39881
+ const m = JSON.parse(readFileSync9(f, "utf8"));
39484
39882
  if (!checkMandate(m).ok)
39485
39883
  throw new Error("The mandate is not valid; it cannot be countersigned.");
39486
39884
  const signed = cosignMandate(m, loadOrCreateKey(o.key), o.name);
39487
- writeFileSync4(f, JSON.stringify(signed, null, 2) + "\n");
39885
+ writeFileSync5(f, JSON.stringify(signed, null, 2) + "\n");
39488
39886
  process.stdout.write(`Countersigned by ${sanitizeText(o.name, 80)} (${loadOrCreateKey(o.key).kid}). Check: npx saktum agent verify ${sanitizeText(f)}
39489
39887
  `);
39490
39888
  });
39491
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) => {
39492
- const m = JSON.parse(readFileSync8(o.mandate, "utf8"));
39890
+ const m = JSON.parse(readFileSync9(o.mandate, "utf8"));
39493
39891
  const a = approveAction(m, rid, loadOrCreateKey(o.key), Number(o.minutes), o.approvals);
39494
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.
39495
39893
  `);
39496
39894
  });
39497
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) => {
39498
- const m = JSON.parse(readFileSync8(f, "utf8"));
39896
+ const m = JSON.parse(readFileSync9(f, "utf8"));
39499
39897
  const r = revokeMandate(m, o.reason);
39500
39898
  process.stdout.write(`Revoked the mandate for ${sanitizeText(m.agent.name, 80)} at ${r.at}. Its calls are now refused (code: revoked).
39501
39899
  `);
39502
39900
  });
39503
- 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)").action(async (parts, o) => {
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) => {
39504
39902
  const { homedir: homedir2 } = await import("node:os");
39505
39903
  const { join: join6 } = await import("node:path");
39506
39904
  let mandate;
39507
39905
  if (o.mandate) {
39508
- mandate = JSON.parse(readFileSync8(o.mandate, "utf8"));
39906
+ mandate = JSON.parse(readFileSync9(o.mandate, "utf8"));
39509
39907
  const c = checkMandate(mandate);
39510
39908
  if (!c.ok)
39511
39909
  throw new Error(`Mandate refused: ${c.reason}`);
@@ -39514,14 +39912,28 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
39514
39912
  if (mandate && agentKey.kid !== mandate.agent.id)
39515
39913
  throw new Error("The agent key does not match the mandate's agent.");
39516
39914
  const { runProxy: runProxy2 } = await Promise.resolve().then(() => (init_proxy(), proxy_exports));
39517
- exitCode = await runProxy2({ command: parts[0], args: parts.slice(1), receiptsPath: o.receipts ?? join6(homedir2(), ".saktum", "receipts.jsonl"), agentKey, mandate, enforce: o.enforce, ...o.revocations ? { revocationsPath: o.revocations } : {}, ...o.approvals ? { approvalsPath: o.approvals } : {}, log: (m) => process.stderr.write(`saktum: ${m}
39518
- `) });
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
+ });
39519
39931
  });
39520
39932
  const receipts = program2.command("receipts").description("Signed receipts of agent tool calls (from saktum proxy)");
39521
39933
  receipts.command("verify").description("Verify every receipt's signature and the hash chain").argument("[file]", "receipt log").action(async (f) => {
39522
39934
  const { homedir: homedir2 } = await import("node:os");
39523
39935
  const { join: join6 } = await import("node:path");
39524
- const r = verifyReceiptLog(parseReceiptLog(readFileSync8(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")));
39936
+ const r = verifyReceiptLog(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")));
39525
39937
  process.stdout.write(r.ok ? `\u2713 ${r.count} receipts verified: every signature valid, chain intact.
39526
39938
  ` : `\u2717 Receipts do NOT verify:
39527
39939
  ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
@@ -39531,10 +39943,10 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
39531
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) => {
39532
39944
  const { homedir: homedir2 } = await import("node:os");
39533
39945
  const { join: join6 } = await import("node:path");
39534
- const entries = parseReceiptLog(readFileSync8(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
39946
+ const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
39535
39947
  const v = verifyReceiptLog(entries);
39536
39948
  const otlp = receiptsToOtlp(entries, { verified: v.ok, version: ENGINE_VERSION });
39537
- writeFileSync4(o.otel, JSON.stringify(otlp, null, 2) + "\n");
39949
+ writeFileSync5(o.otel, JSON.stringify(otlp, null, 2) + "\n");
39538
39950
  process.stdout.write(`Wrote ${entries.length} span(s) to ${sanitizeText(o.otel)} (receipts ${v.ok ? "verified" : "DO NOT verify"}).
39539
39951
  `);
39540
39952
  if (o.endpoint) {
@@ -39549,7 +39961,7 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
39549
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) => {
39550
39962
  const { homedir: homedir2 } = await import("node:os");
39551
39963
  const { join: join6 } = await import("node:path");
39552
- const entries = parseReceiptLog(readFileSync8(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
39964
+ const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
39553
39965
  const v = verifyReceiptLog(entries), s = summariseReceipts(entries);
39554
39966
  if (o.json) {
39555
39967
  process.stdout.write(JSON.stringify({ verified: v.ok, ...s }, null, 2) + "\n");
@@ -39563,11 +39975,11 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
39563
39975
  });
39564
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) => {
39565
39977
  if (o.agent) {
39566
- const m = JSON.parse(readFileSync8(o.agent, "utf8"));
39978
+ const m = JSON.parse(readFileSync9(o.agent, "utf8"));
39567
39979
  const valid = checkMandate(m);
39568
39980
  let receipts2;
39569
39981
  if (o.receipts) {
39570
- const entries = parseReceiptLog(readFileSync8(o.receipts, "utf8"));
39982
+ const entries = parseReceiptLog(readFileSync9(o.receipts, "utf8"));
39571
39983
  const counts = /* @__PURE__ */ new Map();
39572
39984
  for (const e of entries) {
39573
39985
  const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
@@ -39580,8 +39992,8 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
39580
39992
  };
39581
39993
  }
39582
39994
  const rev = revocationOf(m), op = checkOperator(m);
39583
- const ts = o.receipts ? trustStatement(parseReceiptLog(readFileSync8(o.receipts, "utf8")), receipts2?.verified ?? false) : void 0;
39584
- writeFileSync4(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 }));
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 }));
39585
39997
  process.stdout.write(`Wrote the Agent Passport for ${sanitizeText(m.agent.name, 80)} to ${sanitizeText(o.out)}. Open it in a browser.
39586
39998
  `);
39587
39999
  return;
@@ -39593,20 +40005,20 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
39593
40005
  target.env = parseEnv(o.env);
39594
40006
  if (target.kind === "streamable-http" && o.header.length)
39595
40007
  target.headers = parseHeaders(o.header);
39596
- const packs = existsSync6(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40008
+ const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39597
40009
  let tools = [];
39598
40010
  const r = await runTrustCheck(target, { packs, onTools: (t) => {
39599
40011
  tools = t;
39600
40012
  } });
39601
40013
  const signed = signDocument(r, loadOrCreateKey(o.key));
39602
- writeFileSync4(o.out, renderServerPassport(signed, tools));
39603
- writeFileSync4(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));
39604
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.
39605
40017
  `);
39606
40018
  });
39607
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) => {
39608
- const list = JSON.parse(readFileSync8(file, "utf8"));
39609
- const packs = existsSync6(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40020
+ const list = JSON.parse(readFileSync9(file, "utf8"));
40021
+ const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39610
40022
  const r = await watchAllowlist(list.allowed ?? [], packs);
39611
40023
  const mark2 = { unchanged: "\u2713", changed: "\u2717", degraded: "!", unreachable: "?" };
39612
40024
  for (const f of r.findings)
@@ -39616,7 +40028,7 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
39616
40028
  ${r.findings.length} server(s) checked; ${r.alerts} need attention.
39617
40029
  `);
39618
40030
  if (o.out)
39619
- writeFileSync4(o.out, JSON.stringify(r, null, 2) + "\n");
40031
+ writeFileSync5(o.out, JSON.stringify(r, null, 2) + "\n");
39620
40032
  if (o.webhook && r.alerts) {
39621
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);
39622
40034
  try {
@@ -39641,29 +40053,29 @@ Assumptions: ${r.assumptions}.
39641
40053
  `);
39642
40054
  });
39643
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) => {
39644
- const fleet = JSON.parse(readFileSync8(o.fleet, "utf8"));
40056
+ const fleet = JSON.parse(readFileSync9(o.fleet, "utf8"));
39645
40057
  const rec = o.receipts.map((f) => {
39646
- const e = parseReceiptLog(readFileSync8(f, "utf8"));
40058
+ const e = parseReceiptLog(readFileSync9(f, "utf8"));
39647
40059
  return { agent: e[0]?.receipt.envelope.caller.agent?.slice(0, 32) ?? f, summary: summariseReceipts(e), verified: verifyReceiptLog(e).ok };
39648
40060
  });
39649
40061
  const distinctTokens = (fleet.servers ?? []).reduce((a, x) => a + (x.tokens ?? 0), 0);
39650
40062
  const roi = roiEstimate({ ...ROI_DEFAULTS, tokensPerTurn: distinctTokens, agents: Number(o.agents), turnsPerDay: Number(o.turnsPerDay), pricePerMTok: Number(o.pricePerMtok), vendorReviews: Number(o.vendorReviews) });
39651
- writeFileSync4(o.out, renderAssessment(o.org, fleet, rec, roi));
40063
+ writeFileSync5(o.out, renderAssessment(o.org, fleet, rec, roi));
39652
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.
39653
40065
  `);
39654
40066
  });
39655
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) => {
39656
40068
  const setups = files.map((f) => {
39657
- const j = JSON.parse(readFileSync8(f, "utf8"));
40069
+ const j = JSON.parse(readFileSync9(f, "utf8"));
39658
40070
  return { machine: j.machine ?? f, servers: j.servers ?? [] };
39659
40071
  });
39660
40072
  const pol = o.policy ? await loadPolicy(o.policy) : void 0;
39661
40073
  const fleet = buildFleet(setups, pol?.policy, pol?.allow);
39662
40074
  process.stdout.write(renderFleet(fleet));
39663
40075
  if (o.out)
39664
- writeFileSync4(o.out, JSON.stringify(fleet, null, 2) + "\n");
40076
+ writeFileSync5(o.out, JSON.stringify(fleet, null, 2) + "\n");
39665
40077
  if (o.html)
39666
- writeFileSync4(o.html, fleetHtml(fleet));
40078
+ writeFileSync5(o.html, fleetHtml(fleet));
39667
40079
  exitCode = fleet.nonCompliant ? 1 : 0;
39668
40080
  });
39669
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) => {
@@ -39692,7 +40104,138 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
39692
40104
  `);
39693
40105
  }
39694
40106
  });
39695
- 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, autonomy, or all (grocery, travel and finance)", "all").action(async (o) => {
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) => {
39696
40239
  const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
39697
40240
  await runDemo2(o.out, (l) => process.stdout.write(l + "\n"), o.story);
39698
40241
  });
@@ -39701,17 +40244,17 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
39701
40244
  await startDemoServer2(o.story);
39702
40245
  });
39703
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) => {
39704
- const packs = o.packs ? loadPackDir(o.packs) : existsSync6(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
40247
+ const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
39705
40248
  const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports));
39706
40249
  await startMcpServer2(packs);
39707
40250
  });
39708
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) => {
39709
- const doc = JSON.parse(readFileSync8(file, "utf8"));
40252
+ const doc = JSON.parse(readFileSync9(file, "utf8"));
39710
40253
  const v = verifyDocument(doc);
39711
40254
  if (!v.valid)
39712
40255
  throw new Error(`The result's signature is not valid (${v.reason}); attestations are built only from unaltered signed results.`);
39713
40256
  const att = signDocument(buildAttestation(doc), loadOrCreateKey(o.key));
39714
- writeFileSync4(o.out, JSON.stringify(att, null, 2) + "\n");
40257
+ writeFileSync5(o.out, JSON.stringify(att, null, 2) + "\n");
39715
40258
  const c = att.claims, colour = (g) => ({ A: "2e7d32", B: "558b2f", C: "f9a825", D: "ef6c00", F: "c62828" })[g ?? ""] ?? "757575";
39716
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"}).
39717
40260
  Anyone can check it: npx saktum verify ${sanitizeText(o.out)}
@@ -39723,20 +40266,20 @@ README badge:
39723
40266
  const key = loadOrCreateKey(o.key);
39724
40267
  const cred = attestationToCredential(att, key.kid);
39725
40268
  const base = o.out.replace(/\.json$/i, "");
39726
- writeFileSync4(`${base}.vc.jwt`, signCredentialJwt(cred, key) + "\n");
39727
- writeFileSync4(`${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");
39728
40271
  process.stdout.write(`
39729
40272
  W3C Verifiable Credential: ${sanitizeText(base)}.vc.jwt (check it: npx saktum vc verify ${sanitizeText(base)}.vc.jwt)
39730
40273
  `);
39731
40274
  }
39732
40275
  if (o.publish) {
39733
- 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.
39734
40277
 
39735
40278
  \`\`\`json
39736
40279
  ${JSON.stringify(att)}
39737
40280
  \`\`\`
39738
40281
  `;
39739
- 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)}`;
39740
40283
  process.stdout.write(`
39741
40284
  Publish to the public trust ledger (opens a pre-filled GitHub issue; anyone can then verify it):
39742
40285
  ${url2}
@@ -39749,7 +40292,7 @@ ${url2}
39749
40292
  exitCode = r.code;
39750
40293
  });
39751
40294
  program2.command("verify").description("Verify a signed Saktum Check result").argument("<file>").action((file) => {
39752
- const doc = JSON.parse(readFileSync8(file, "utf8"));
40295
+ const doc = JSON.parse(readFileSync9(file, "utf8"));
39753
40296
  const validate2 = compileContract("result.schema.json");
39754
40297
  if (!validate2(doc)) {
39755
40298
  process.stdout.write(`Invalid result format: ${JSON.stringify(validate2.errors?.slice(0, 2))}