saktum 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -1
- package/package.json +1 -1
- package/saktum.mjs +750 -173
package/saktum.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Saktum Check 0.
|
|
2
|
+
// Saktum Check 0.8.1 (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
|
|
4392
|
+
const body2 = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
|
|
4393
4393
|
if (!literalFallback)
|
|
4394
4394
|
return `>${header}
|
|
4395
|
-
${indent}${
|
|
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
|
|
6411
|
+
let body2 = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
|
|
6412
6412
|
if (contentComment)
|
|
6413
|
-
|
|
6414
|
-
if ((
|
|
6415
|
-
lines[lines.length - 1] = `--- ${
|
|
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(
|
|
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
|
|
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:
|
|
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
|
|
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 =
|
|
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:
|
|
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, ...
|
|
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(
|
|
10505
|
+
const payload = b64u(Buffer.from(canonicalize(body2)));
|
|
10506
10506
|
const sig = sign(null, Buffer.from(`${header}.${payload}`), key.privateKey);
|
|
10507
|
-
return { ...
|
|
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, ...
|
|
10531
|
-
const payload = b64u(Buffer.from(canonicalize(
|
|
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(
|
|
11435
|
+
block(body2, nodeCount) {
|
|
11436
11436
|
this._blockStarts.push(this._nodes.length);
|
|
11437
|
-
if (
|
|
11438
|
-
this.code(
|
|
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 },
|
|
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(
|
|
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(
|
|
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, ...
|
|
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(
|
|
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, ...
|
|
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(
|
|
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, ...
|
|
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(
|
|
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
|
|
20252
|
-
if (
|
|
20253
|
-
lines.push(`${format === "py" ? "#" : "//"} Also write a one-sentence description (what it does, when to use it) for: ${
|
|
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
|
|
32642
|
+
const body2 = input instanceof Response ? await input.text() : input;
|
|
32643
32643
|
try {
|
|
32644
|
-
const result = OAuthErrorResponseSchema.parse(JSON.parse(
|
|
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: ${
|
|
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
|
|
33928
|
+
let body2 = "";
|
|
33929
33929
|
try {
|
|
33930
|
-
|
|
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.
|
|
33999
|
+
USER_AGENT = "saktum-check/0.8.1 (+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.
|
|
34037
|
+
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.8.1" } }
|
|
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
|
|
34596
|
-
return
|
|
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.
|
|
35409
|
+
ENGINE_VERSION = "0.8.1";
|
|
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
|
|
35818
|
-
const start =
|
|
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(
|
|
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
|
|
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(
|
|
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;
|
|
@@ -36413,6 +36413,29 @@ function consumeApproval(m, requestId, path = DEFAULT_APPROVALS()) {
|
|
|
36413
36413
|
}
|
|
36414
36414
|
return { ok: false };
|
|
36415
36415
|
}
|
|
36416
|
+
function agentMaturity(m, o = {}) {
|
|
36417
|
+
const op = checkOperator(m);
|
|
36418
|
+
const tier = agentRiskTier(m).tier;
|
|
36419
|
+
const bounded = Boolean(m.allow.tools?.length || m.actions?.length) && m.delegation !== true && (!(tier === "R3" || tier === "R4") || Boolean(m.constraints?.length || m.approveAbove || m.rules?.length || m.approvalTriggers?.length || m.autonomy === "propose" || m.autonomy === "notify"));
|
|
36420
|
+
const entries = o.entries ?? [];
|
|
36421
|
+
const actions = entries.filter((e) => e.receipt.outcome === "allow" && e.result.status === "ok").length;
|
|
36422
|
+
const outside = entries.filter((e) => String(e.result.code ?? "").startsWith("observed-")).length;
|
|
36423
|
+
const explained = entries.length > 0 && o.verified === true && entries.every((e) => Boolean(e.result.code));
|
|
36424
|
+
const steps = [
|
|
36425
|
+
{ level: 1, name: "Identified", met: checkMandate(m).ok, why: "its own identity and a valid mandate signed by its owner" },
|
|
36426
|
+
{ level: 2, name: "Accountable", met: op.present && op.valid || o.chainValid === true, why: "an operator countersignature or an identity chain to an organisation" },
|
|
36427
|
+
{ level: 3, name: "Bounded", met: bounded, why: "explicit tools or action classes, no sub-delegation, and caps or approvals when it can act irreversibly or spend" },
|
|
36428
|
+
{ level: 4, name: "Explained", met: explained, why: "signed, verified receipts with a reason for every decision" },
|
|
36429
|
+
{ level: 5, name: "Proven", met: actions >= 10 && outside === 0 && !o.revoked && explained, why: `a track record of at least 10 actions, none outside its mandate (${actions} so far)` }
|
|
36430
|
+
];
|
|
36431
|
+
let level = 0;
|
|
36432
|
+
for (const st of steps) {
|
|
36433
|
+
if (!st.met)
|
|
36434
|
+
break;
|
|
36435
|
+
level = st.level;
|
|
36436
|
+
}
|
|
36437
|
+
return { level, label: level ? `A${level} ${steps[level - 1].name}` : "Not yet identified", steps };
|
|
36438
|
+
}
|
|
36416
36439
|
var FIELD_LABEL, ruleText, DEFAULT_REVOCATIONS, readRevocations, DEFAULT_APPROVALS, readApprovals;
|
|
36417
36440
|
var init_agentid = __esm({
|
|
36418
36441
|
"packages/testkit-core/dist/agentid.js"() {
|
|
@@ -36594,6 +36617,239 @@ var init_watch = __esm({
|
|
|
36594
36617
|
}
|
|
36595
36618
|
});
|
|
36596
36619
|
|
|
36620
|
+
// packages/testkit-core/dist/market.js
|
|
36621
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
|
|
36622
|
+
import { dirname as dirname2 } from "node:path";
|
|
36623
|
+
function organisationRoot(o, key) {
|
|
36624
|
+
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 };
|
|
36625
|
+
return signDocument({ ...c, id: short("cred_", c) }, key);
|
|
36626
|
+
}
|
|
36627
|
+
function issueCredential(issuerCred, issuerKey, s) {
|
|
36628
|
+
if (issuerCred.subject.id !== issuerKey.kid)
|
|
36629
|
+
throw new Error("The signing key does not belong to the issuer's credential.");
|
|
36630
|
+
if (issuerCred.type === "agent")
|
|
36631
|
+
throw new Error("Agents cannot issue credentials.");
|
|
36632
|
+
const chain = [...issuerCred.chain ?? [], { ...issuerCred, chain: void 0 }].map((c2) => JSON.parse(JSON.stringify(c2)));
|
|
36633
|
+
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 };
|
|
36634
|
+
return { ...signDocument({ ...c, id: short("cred_", c) }, issuerKey), chain };
|
|
36635
|
+
}
|
|
36636
|
+
function verifyChain(c, o = {}) {
|
|
36637
|
+
const today = o.today ?? nowIso();
|
|
36638
|
+
const links = [...c.chain ?? [], { ...c, chain: void 0 }];
|
|
36639
|
+
const path = [];
|
|
36640
|
+
for (let i = 0; i < links.length; i++) {
|
|
36641
|
+
const l = links[i];
|
|
36642
|
+
const v = verifyDocument(JSON.parse(JSON.stringify({ ...l, chain: void 0 })));
|
|
36643
|
+
if (!v.valid)
|
|
36644
|
+
return { valid: false, path, reason: `signature not valid on ${l.subject.name}'s credential` };
|
|
36645
|
+
if (v.kid !== l.issuer.id)
|
|
36646
|
+
return { valid: false, path, reason: `${l.subject.name}'s credential was not signed by its stated issuer` };
|
|
36647
|
+
if (l.expires < today.slice(0, l.expires.length))
|
|
36648
|
+
return { valid: false, path, reason: `${l.subject.name}'s credential expired on ${l.expires}` };
|
|
36649
|
+
if (o.revoked?.includes(l.id))
|
|
36650
|
+
return { valid: false, path, reason: `${l.subject.name}'s credential was revoked` };
|
|
36651
|
+
if (i === 0 && (l.type !== "organisation" || l.issuer.id !== l.subject.id))
|
|
36652
|
+
return { valid: false, path, reason: "the chain does not start at an organisation" };
|
|
36653
|
+
if (i > 0 && l.issuer.id !== links[i - 1].subject.id)
|
|
36654
|
+
return { valid: false, path, reason: `${l.subject.name}'s issuer is not the previous link in the chain` };
|
|
36655
|
+
path.push(`${l.subject.name}${l.subject.role ? ` (${l.subject.role})` : ""}`);
|
|
36656
|
+
}
|
|
36657
|
+
return { valid: true, path, organisation: links[0].subject.name + (links[0].issuer.domain ? ` (${links[0].issuer.domain})` : "") };
|
|
36658
|
+
}
|
|
36659
|
+
function findOrphans(creds, o = {}) {
|
|
36660
|
+
return creds.filter((c) => c.type === "agent").map((c) => ({ agent: c.subject.name, id: c.subject.id, ...verifyChain(c, o) })).filter((x) => !x.valid);
|
|
36661
|
+
}
|
|
36662
|
+
function buildManifest(o, key) {
|
|
36663
|
+
const caps = o.tools.map((t) => {
|
|
36664
|
+
const b = bindingsFor(t).bindings;
|
|
36665
|
+
return { tool: t.name, action: actionClass(t).cls, fields: [...new Set(Object.values(b))], description: (t.description ?? "").split(/(?<=[.!?])\s/)[0].slice(0, 160) };
|
|
36666
|
+
});
|
|
36667
|
+
const domains = [...new Set(caps.flatMap((c) => c.fields.map((f) => f.split(".")[0])))].filter((d) => d !== "personal" && d !== "party");
|
|
36668
|
+
const intents = [...new Set(caps.flatMap((c) => (domains.length ? domains : ["general"]).map((d) => `${c.action}:${d}`)))];
|
|
36669
|
+
const m = {
|
|
36670
|
+
manifestFormat: "0.1",
|
|
36671
|
+
publisher: { id: key.kid, ...o.publisher },
|
|
36672
|
+
server: o.server,
|
|
36673
|
+
categories: o.categories ?? domains.map((d) => CAT[d] ?? d),
|
|
36674
|
+
intents,
|
|
36675
|
+
capabilities: caps,
|
|
36676
|
+
rates: o.rates,
|
|
36677
|
+
...o.quality ? { quality: o.quality } : {},
|
|
36678
|
+
...o.documentation ? { documentation: o.documentation } : {},
|
|
36679
|
+
issuedAt: nowIso()
|
|
36680
|
+
};
|
|
36681
|
+
return signDocument({ ...m, id: short("man_", { ...m, issuedAt: void 0 }) }, key);
|
|
36682
|
+
}
|
|
36683
|
+
function searchCatalogue(entries, query, o = {}) {
|
|
36684
|
+
const q = query.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2);
|
|
36685
|
+
return entries.filter((m) => verifyDocument(m).valid && (!o.maxRisk || !m.quality?.riskTier || m.quality.riskTier <= o.maxRisk)).map((m) => {
|
|
36686
|
+
let score2 = 0;
|
|
36687
|
+
const why = [];
|
|
36688
|
+
for (const it of m.intents) {
|
|
36689
|
+
const [a, d] = it.split(":");
|
|
36690
|
+
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));
|
|
36691
|
+
if (hit.length) {
|
|
36692
|
+
score2 += 2 * hit.length;
|
|
36693
|
+
why.push(it);
|
|
36694
|
+
}
|
|
36695
|
+
}
|
|
36696
|
+
const text2 = `${m.server.name} ${m.categories.join(" ")} ${m.capabilities.map((c) => `${c.tool} ${c.description}`).join(" ")}`.toLowerCase();
|
|
36697
|
+
for (const w of q)
|
|
36698
|
+
if (text2.includes(w))
|
|
36699
|
+
score2 += 1;
|
|
36700
|
+
return { manifest: m, score: score2, matched: [...new Set(why)] };
|
|
36701
|
+
}).filter((r) => r.score > 0).sort((a, b) => b.score - a.score);
|
|
36702
|
+
}
|
|
36703
|
+
function draftAgreement(o, providerKey) {
|
|
36704
|
+
if (providerKey.kid !== o.manifest.publisher.id)
|
|
36705
|
+
throw new Error("Only the manifest's publisher can offer an agreement for it.");
|
|
36706
|
+
const a = {
|
|
36707
|
+
agreementFormat: "0.1",
|
|
36708
|
+
template: "saktum-default-0.1",
|
|
36709
|
+
purpose: o.purpose,
|
|
36710
|
+
provider: { id: providerKey.kid, name: o.manifest.publisher.name, manifest: o.manifest.id },
|
|
36711
|
+
invoker: o.invoker,
|
|
36712
|
+
scope: { ...o.tools?.length ? { tools: o.tools } : {} },
|
|
36713
|
+
rates: o.rates ?? o.manifest.rates,
|
|
36714
|
+
...o.tokensPerMonth ? { limits: { tokensPerMonth: o.tokensPerMonth } } : {},
|
|
36715
|
+
terms: DEFAULT_TERMS,
|
|
36716
|
+
...o.specificTerms?.length ? { specificTerms: o.specificTerms } : {},
|
|
36717
|
+
...o.dataTerms ? { dataTerms: o.dataTerms } : {},
|
|
36718
|
+
...o.disputeContact ? { disputeContact: o.disputeContact } : {},
|
|
36719
|
+
validFrom: nowIso().slice(0, 10),
|
|
36720
|
+
validUntil: o.validUntil
|
|
36721
|
+
};
|
|
36722
|
+
return signDocument({ ...a, id: short("agr_", a) }, providerKey);
|
|
36723
|
+
}
|
|
36724
|
+
function acceptAgreement(a, invokerKey) {
|
|
36725
|
+
if (invokerKey.kid !== a.invoker.id)
|
|
36726
|
+
throw new Error("Only the named invoker can accept this agreement.");
|
|
36727
|
+
return { ...a, countersignature: signDocument({ by: invokerKey.kid, agreement: argumentsHash(body(a)) }, invokerKey) };
|
|
36728
|
+
}
|
|
36729
|
+
function verifyAgreement(a, today = nowIso().slice(0, 10)) {
|
|
36730
|
+
const { countersignature: cs, ...providerPart } = a;
|
|
36731
|
+
const p = verifyDocument(providerPart);
|
|
36732
|
+
if (!p.valid || p.kid !== a.provider.id)
|
|
36733
|
+
return { valid: false, reason: "the provider's signature is not valid" };
|
|
36734
|
+
if (!cs)
|
|
36735
|
+
return { valid: false, reason: "not yet accepted by the invoker" };
|
|
36736
|
+
const c = verifyDocument(cs);
|
|
36737
|
+
if (!c.valid || c.kid !== a.invoker.id || cs.agreement !== argumentsHash(body(a)))
|
|
36738
|
+
return { valid: false, reason: "the invoker's countersignature is not valid for this agreement" };
|
|
36739
|
+
if (a.validUntil < today)
|
|
36740
|
+
return { valid: false, reason: `expired on ${a.validUntil}` };
|
|
36741
|
+
return { valid: true };
|
|
36742
|
+
}
|
|
36743
|
+
function walletBalance(path, account) {
|
|
36744
|
+
return readWallet(path).entries.reduce((b, e) => b + (e.to === account ? e.tokens : 0) - (e.from === account ? e.tokens : 0), 0);
|
|
36745
|
+
}
|
|
36746
|
+
function topUp(path, account, tokens, ref = "top-up") {
|
|
36747
|
+
const w = readWallet(path);
|
|
36748
|
+
w.entries.push({ at: nowIso(), from: PREPAID, to: account, tokens, ref });
|
|
36749
|
+
writeWallet(path, w);
|
|
36750
|
+
return walletBalance(path, account);
|
|
36751
|
+
}
|
|
36752
|
+
function chargeCall(path, a, tool, ref) {
|
|
36753
|
+
const cost = tokensFor(a, tool), bal = walletBalance(path, a.invoker.id);
|
|
36754
|
+
if (bal < cost)
|
|
36755
|
+
return { ok: false, tokens: cost, balance: bal };
|
|
36756
|
+
const w = readWallet(path);
|
|
36757
|
+
w.entries.push({ at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref });
|
|
36758
|
+
writeWallet(path, w);
|
|
36759
|
+
return { ok: true, tokens: cost, balance: bal - cost };
|
|
36760
|
+
}
|
|
36761
|
+
function usageStatement(entries, a, key) {
|
|
36762
|
+
const metered = entries.filter((e) => e.result.metering?.agreement === a.id);
|
|
36763
|
+
const byTool = /* @__PURE__ */ new Map();
|
|
36764
|
+
for (const e of metered) {
|
|
36765
|
+
const t = e.receipt.envelope.tool;
|
|
36766
|
+
const x = byTool.get(t) ?? { calls: 0, tokens: 0 };
|
|
36767
|
+
x.calls++;
|
|
36768
|
+
x.tokens += e.result.metering.tokens;
|
|
36769
|
+
byTool.set(t, x);
|
|
36770
|
+
}
|
|
36771
|
+
const s = {
|
|
36772
|
+
statementFormat: "0.1",
|
|
36773
|
+
agreement: a.id,
|
|
36774
|
+
provider: a.provider.name,
|
|
36775
|
+
invoker: a.invoker.name,
|
|
36776
|
+
from: metered[0]?.receipt.issuedAt ?? null,
|
|
36777
|
+
to: metered[metered.length - 1]?.receipt.issuedAt ?? null,
|
|
36778
|
+
lines: [...byTool].map(([tool, v]) => ({ tool, calls: v.calls, tokens: v.tokens })),
|
|
36779
|
+
totalTokens: metered.reduce((n, e) => n + e.result.metering.tokens, 0),
|
|
36780
|
+
receipts: metered.map((e) => e.entryHash),
|
|
36781
|
+
producedAt: nowIso()
|
|
36782
|
+
};
|
|
36783
|
+
return key ? signDocument(s, key) : s;
|
|
36784
|
+
}
|
|
36785
|
+
function kpis(entries, f = {}) {
|
|
36786
|
+
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));
|
|
36787
|
+
const lat = xs.map((e) => e.result.latencyMs).filter((n) => typeof n === "number").sort((a, b) => a - b);
|
|
36788
|
+
const pct = (p) => lat.length ? lat[Math.min(lat.length - 1, Math.floor(p / 100 * lat.length))] : null;
|
|
36789
|
+
const by = (k) => Object.entries(xs.reduce((m, e) => {
|
|
36790
|
+
const key = k(e);
|
|
36791
|
+
m[key] = (m[key] ?? 0) + 1;
|
|
36792
|
+
return m;
|
|
36793
|
+
}, {})).sort((a, b) => b[1] - a[1]);
|
|
36794
|
+
return {
|
|
36795
|
+
calls: xs.length,
|
|
36796
|
+
allowed: xs.filter((e) => e.receipt.outcome === "allow").length,
|
|
36797
|
+
blocked: xs.filter((e) => e.receipt.outcome === "deny").length,
|
|
36798
|
+
approvals: xs.filter((e) => /approved by/.test(String(e.receipt.reason ?? ""))).length,
|
|
36799
|
+
tokens: xs.reduce((n, e) => n + (e.result.metering?.tokens ?? 0), 0),
|
|
36800
|
+
latencyP50: pct(50),
|
|
36801
|
+
latencyP95: pct(95),
|
|
36802
|
+
byOutcome: by((e) => e.result.code ?? e.receipt.outcome),
|
|
36803
|
+
byTool: by((e) => e.receipt.envelope.tool)
|
|
36804
|
+
};
|
|
36805
|
+
}
|
|
36806
|
+
var short, nowIso, body, CAT, WORDS, DEFAULT_TERMS, tokensFor, readWallet, writeWallet, PREPAID;
|
|
36807
|
+
var init_market = __esm({
|
|
36808
|
+
"packages/testkit-core/dist/market.js"() {
|
|
36809
|
+
"use strict";
|
|
36810
|
+
init_dist();
|
|
36811
|
+
init_vocab();
|
|
36812
|
+
init_receipts();
|
|
36813
|
+
short = (prefix, x) => prefix + argumentsHash(JSON.parse(JSON.stringify(x))).replace(/^sha256:/, "").slice(0, 16);
|
|
36814
|
+
nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
36815
|
+
body = (d) => {
|
|
36816
|
+
const { signature: _s, countersignature: _c, ...rest } = d;
|
|
36817
|
+
return rest;
|
|
36818
|
+
};
|
|
36819
|
+
CAT = { commerce: "Commerce and shopping", travel: "Travel", personal: "Personal data", enterprise: "Business operations" };
|
|
36820
|
+
WORDS = {
|
|
36821
|
+
search: ["find", "search", "look", "browse", "deal", "deals"],
|
|
36822
|
+
cart: ["buy", "shop", "shopping", "groceries", "grocery", "cart", "order"],
|
|
36823
|
+
pay: ["pay", "payment", "checkout", "invoice", "purchase"],
|
|
36824
|
+
book: ["book", "booking", "reserve", "flight", "flights", "trip", "travel"],
|
|
36825
|
+
change: ["change", "seat", "upgrade", "modify"],
|
|
36826
|
+
communicate: ["send", "share", "email", "report"],
|
|
36827
|
+
cancel: ["cancel", "refund"]
|
|
36828
|
+
};
|
|
36829
|
+
DEFAULT_TERMS = [
|
|
36830
|
+
"The provider operates the service as described in its signed manifest; material changes to tools require a new manifest.",
|
|
36831
|
+
"The invoker's agents act only within their mandates; the provider may refuse calls outside the agreed scope.",
|
|
36832
|
+
"Each call is metered in prepaid tokens at the agreed rates; settlement in money happens outside Saktum.",
|
|
36833
|
+
"Both parties keep signed receipts; either may present them as evidence in a dispute.",
|
|
36834
|
+
"Personal and classified data are shared only as the invoker's mandates permit.",
|
|
36835
|
+
"Either party may end the agreement with notice; receipts and usage statements remain valid evidence."
|
|
36836
|
+
];
|
|
36837
|
+
tokensFor = (a, tool) => a.rates.perTool?.[tool] ?? a.rates.perCall;
|
|
36838
|
+
readWallet = (path) => {
|
|
36839
|
+
try {
|
|
36840
|
+
return existsSync3(path) ? JSON.parse(readFileSync5(path, "utf8")) : { entries: [] };
|
|
36841
|
+
} catch {
|
|
36842
|
+
return { entries: [] };
|
|
36843
|
+
}
|
|
36844
|
+
};
|
|
36845
|
+
writeWallet = (path, w) => {
|
|
36846
|
+
mkdirSync2(dirname2(path), { recursive: true });
|
|
36847
|
+
writeFileSync2(path, JSON.stringify(w, null, 2) + "\n");
|
|
36848
|
+
};
|
|
36849
|
+
PREPAID = "saktum:prepaid";
|
|
36850
|
+
}
|
|
36851
|
+
});
|
|
36852
|
+
|
|
36597
36853
|
// packages/testkit-core/dist/index.js
|
|
36598
36854
|
var dist_exports = {};
|
|
36599
36855
|
__export(dist_exports, {
|
|
@@ -36604,6 +36860,7 @@ __export(dist_exports, {
|
|
|
36604
36860
|
DEFAULT_APPROVALS: () => DEFAULT_APPROVALS,
|
|
36605
36861
|
DEFAULT_LEDGER_URL: () => DEFAULT_LEDGER_URL,
|
|
36606
36862
|
DEFAULT_REVOCATIONS: () => DEFAULT_REVOCATIONS,
|
|
36863
|
+
DEFAULT_TERMS: () => DEFAULT_TERMS,
|
|
36607
36864
|
EMBEDDED_CONTRACTS: () => EMBEDDED_CONTRACTS,
|
|
36608
36865
|
EMBEDDED_PACKS: () => EMBEDDED_PACKS,
|
|
36609
36866
|
ENGINE_VERSION: () => ENGINE_VERSION,
|
|
@@ -36617,6 +36874,7 @@ __export(dist_exports, {
|
|
|
36617
36874
|
MIN_GRADED_CHECKS: () => MIN_GRADED_CHECKS,
|
|
36618
36875
|
PERF_NEEDS: () => PERF_NEEDS,
|
|
36619
36876
|
PERF_THRESHOLDS: () => PERF_THRESHOLDS,
|
|
36877
|
+
PREPAID: () => PREPAID,
|
|
36620
36878
|
PackError: () => PackError,
|
|
36621
36879
|
READINESS: () => READINESS,
|
|
36622
36880
|
RECEIPTS_GENESIS: () => RECEIPTS_GENESIS,
|
|
@@ -36629,7 +36887,9 @@ __export(dist_exports, {
|
|
|
36629
36887
|
TRUST_WEIGHTS: () => TRUST_WEIGHTS,
|
|
36630
36888
|
UNKNOWN_TOOL: () => UNKNOWN_TOOL,
|
|
36631
36889
|
VOCABULARIES: () => VOCABULARIES,
|
|
36890
|
+
acceptAgreement: () => acceptAgreement,
|
|
36632
36891
|
actionClass: () => actionClass,
|
|
36892
|
+
agentMaturity: () => agentMaturity,
|
|
36633
36893
|
agentRiskTier: () => agentRiskTier,
|
|
36634
36894
|
allowlistFromLedger: () => allowlistFromLedger,
|
|
36635
36895
|
analyseSetup: () => analyseSetup,
|
|
@@ -36645,8 +36905,10 @@ __export(dist_exports, {
|
|
|
36645
36905
|
buildAllowlist: () => buildAllowlist,
|
|
36646
36906
|
buildAttestation: () => buildAttestation,
|
|
36647
36907
|
buildFleet: () => buildFleet,
|
|
36908
|
+
buildManifest: () => buildManifest,
|
|
36648
36909
|
capabilityProfile: () => capabilityProfile,
|
|
36649
36910
|
chainEntry: () => chainEntry,
|
|
36911
|
+
chargeCall: () => chargeCall,
|
|
36650
36912
|
checkAttestation: () => checkAttestation,
|
|
36651
36913
|
checkMandate: () => checkMandate,
|
|
36652
36914
|
checkNeedsSession: () => checkNeedsSession,
|
|
@@ -36667,16 +36929,20 @@ __export(dist_exports, {
|
|
|
36667
36929
|
describeMandate: () => describeMandate,
|
|
36668
36930
|
diffLocks: () => diffLocks,
|
|
36669
36931
|
docsFor: () => docsFor,
|
|
36932
|
+
draftAgreement: () => draftAgreement,
|
|
36670
36933
|
escapeHtml: () => escapeHtml,
|
|
36671
36934
|
evaluatePolicy: () => evaluatePolicy,
|
|
36672
36935
|
exampleFor: () => exampleFor,
|
|
36673
36936
|
extractJson: () => extractJson,
|
|
36674
36937
|
findInLedger: () => findInLedger,
|
|
36938
|
+
findOrphans: () => findOrphans,
|
|
36675
36939
|
fleetHtml: () => fleetHtml,
|
|
36676
36940
|
gradeFor: () => gradeFor,
|
|
36677
36941
|
hasIntent: () => hasIntent,
|
|
36678
36942
|
invalidArgProblems: () => invalidArgProblems,
|
|
36679
36943
|
invalidArgsFor: () => invalidArgsFor,
|
|
36944
|
+
issueCredential: () => issueCredential,
|
|
36945
|
+
kpis: () => kpis,
|
|
36680
36946
|
leakageAnalysers: () => leakageAnalysers,
|
|
36681
36947
|
lintPaths: () => lintPaths,
|
|
36682
36948
|
lintSarif: () => lintSarif,
|
|
@@ -36690,6 +36956,7 @@ __export(dist_exports, {
|
|
|
36690
36956
|
maxDepth: () => maxDepth,
|
|
36691
36957
|
measureLoad: () => measureLoad,
|
|
36692
36958
|
needsOf: () => needsOf,
|
|
36959
|
+
organisationRoot: () => organisationRoot,
|
|
36693
36960
|
outcomeText: () => outcomeText,
|
|
36694
36961
|
parseChallenge: () => parseChallenge,
|
|
36695
36962
|
parseClientConfig: () => parseClientConfig,
|
|
@@ -36719,6 +36986,7 @@ __export(dist_exports, {
|
|
|
36719
36986
|
sanitizeText: () => sanitizeText,
|
|
36720
36987
|
schemaDialect: () => schemaDialect,
|
|
36721
36988
|
score: () => score,
|
|
36989
|
+
searchCatalogue: () => searchCatalogue,
|
|
36722
36990
|
semanticValues: () => semanticValues,
|
|
36723
36991
|
signCredentialJwt: () => signCredentialJwt,
|
|
36724
36992
|
signReceipt: () => signReceipt,
|
|
@@ -36729,13 +36997,19 @@ __export(dist_exports, {
|
|
|
36729
36997
|
suggestAnnotations: () => suggestAnnotations,
|
|
36730
36998
|
summarise: () => summarise,
|
|
36731
36999
|
summariseReceipts: () => summariseReceipts,
|
|
37000
|
+
tokensFor: () => tokensFor,
|
|
36732
37001
|
toolsContextCost: () => contextCost,
|
|
36733
37002
|
toolsLock: () => toolsLock,
|
|
37003
|
+
topUp: () => topUp,
|
|
36734
37004
|
trustStatement: () => trustStatement,
|
|
37005
|
+
usageStatement: () => usageStatement,
|
|
37006
|
+
verifyAgreement: () => verifyAgreement,
|
|
37007
|
+
verifyChain: () => verifyChain,
|
|
36735
37008
|
verifyCredentialJwt: () => verifyCredentialJwt,
|
|
36736
37009
|
verifyLedger: () => verifyLedger,
|
|
36737
37010
|
verifyReceipt: () => verifyReceipt,
|
|
36738
37011
|
verifyReceiptLog: () => verifyReceiptLog,
|
|
37012
|
+
walletBalance: () => walletBalance,
|
|
36739
37013
|
watchAllowlist: () => watchAllowlist,
|
|
36740
37014
|
wellKnownUrls: () => wellKnownUrls
|
|
36741
37015
|
});
|
|
@@ -36771,6 +37045,7 @@ var init_dist4 = __esm({
|
|
|
36771
37045
|
init_watch();
|
|
36772
37046
|
init_risk();
|
|
36773
37047
|
init_vocab();
|
|
37048
|
+
init_market();
|
|
36774
37049
|
}
|
|
36775
37050
|
});
|
|
36776
37051
|
|
|
@@ -36793,7 +37068,7 @@ function renderServerPassport(r, tools, o = {}) {
|
|
|
36793
37068
|
const req = (t.inputSchema?.required ?? []).join(", ");
|
|
36794
37069
|
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
37070
|
}).join("");
|
|
36796
|
-
const
|
|
37071
|
+
const body2 = `<div class="card"><div class="top"><div class="seal" style="background:${GRADE_COLOUR[g] ?? "#757575"}">${esc2(g)}</div>
|
|
36797
37072
|
<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
37073
|
<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
37074
|
<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 +37076,7 @@ ${r.riskTier ? `<div class="card"><h2>Risk tier</h2><p><b>${esc2(r.riskTier.tier
|
|
|
36801
37076
|
<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
37077
|
<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
37078
|
<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`,
|
|
37079
|
+
return page(`${name}: MCP Server Passport`, body2);
|
|
36805
37080
|
}
|
|
36806
37081
|
function renderAgentPassport(m, valid, receipts, tier, plain, extra = {}) {
|
|
36807
37082
|
const AUTO = { notify: "Notify only: it alerts, never acts", propose: "Propose: it suggests, you approve", act: "Act: within the limits below" };
|
|
@@ -36818,9 +37093,11 @@ function renderAgentPassport(m, valid, receipts, tier, plain, extra = {}) {
|
|
|
36818
37093
|
].map(([k, v]) => `<tr><td><b>${esc2(k)}</b></td><td>${esc2(v)}</td></tr>`).join("");
|
|
36819
37094
|
const s = receipts?.summary;
|
|
36820
37095
|
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
|
|
37096
|
+
const body2 = `<div class="card"><div class="top"><div class="seal" style="background:${valid.ok ? "#5a3fc0" : "#c62828"}">AI</div>
|
|
36822
37097
|
<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
|
-
<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>
|
|
37098
|
+
<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")}${extra.maturity ? chip("Maturity", extra.maturity.label, "#5a3fc0") : ""}${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>
|
|
37099
|
+
${extra.maturity ? `<div class="card"><h2>Maturity</h2><div class="levels">${[1, 2, 3, 4, 5].map((l) => `<div class="lv${l <= extra.maturity.level ? " on" : ""}">A${l}</div>`).join("")}</div><small>${esc2(extra.maturity.label)} \xB7 earned from evidence, never a score</small>
|
|
37100
|
+
<div class="wrap" style="margin-top:8px"><table>${extra.maturity.steps.map((st) => `<tr><td>${st.met ? "\u2713" : "\u2013"} <b>A${st.level} ${esc2(st.name)}</b></td><td>${esc2(st.why)}</td></tr>`).join("")}</table></div></div>` : ""}
|
|
36824
37101
|
${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>` : ""}
|
|
36825
37102
|
${plain?.length ? `<div class="card"><h2>Its instructions, in plain words</h2>${plain.map((l) => `<p style="margin:4px 0">${esc2(l)}</p>`).join("")}</div>` : ""}
|
|
36826
37103
|
<div class="card"><h2>Permissions</h2><div class="wrap"><table>${perms}</table></div>${tier ? `<p class="muted">Risk tier ${esc2(tier.tier)}: ${esc2(tier.note)}.</p>` : ""}</div>
|
|
@@ -36831,17 +37108,17 @@ ${s.repeatedIdenticalCalls.length ? `<p><b>Repeated identical calls:</b> ${s.rep
|
|
|
36831
37108
|
<h2 style="margin-top:14px">The path, not the answer</h2><div class="timeline">${steps}</div>
|
|
36832
37109
|
${(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
37110
|
<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`,
|
|
37111
|
+
return page(`${m.agent.name}: Agent Passport`, body2);
|
|
36835
37112
|
}
|
|
36836
37113
|
function renderLedgerPassport(e) {
|
|
36837
37114
|
const c = e.attestation.claims, g = c.trustGrade ?? "-";
|
|
36838
|
-
const
|
|
37115
|
+
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
37116
|
<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
37117
|
<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
37118
|
<div class="card"><h2>Maturity evidence</h2>${levelBar(evidenceLevel(c.evidence))}</div>
|
|
36842
37119
|
<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
37120
|
<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`,
|
|
37121
|
+
return page(`${e.subject.server}: MCP Server Passport`, body2);
|
|
36845
37122
|
}
|
|
36846
37123
|
function renderPassportGallery(entries) {
|
|
36847
37124
|
const latest = /* @__PURE__ */ new Map();
|
|
@@ -36875,7 +37152,7 @@ function renderAssessment(org, f, receipts = [], roi) {
|
|
|
36875
37152
|
if (tokens > 5e4)
|
|
36876
37153
|
rec.push(`Tool definitions cost ${tokens.toLocaleString("en-US")} tokens per turn across distinct servers: remove duplicates and unused servers.`);
|
|
36877
37154
|
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
|
|
37155
|
+
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
37156
|
<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
37157
|
<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
37158
|
<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 +37160,7 @@ ${rc ? `<div class="card"><h2>Agent receipts</h2><div class="wrap"><table><tr><t
|
|
|
36883
37160
|
${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
37161
|
<div class="card"><h2>Recommendations</h2><ol>${rec.map((x) => `<li>${esc2(x)}</li>`).join("")}</ol></div>
|
|
36885
37162
|
<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}`,
|
|
37163
|
+
return page(`MCP Trust Assessment: ${org}`, body2);
|
|
36887
37164
|
}
|
|
36888
37165
|
var esc2, GRADE_COLOUR, chip, STYLE, page, levelBar, effect, passportSlug, evidenceLevel;
|
|
36889
37166
|
var init_passport = __esm({
|
|
@@ -36906,7 +37183,7 @@ code{font:12.5px ui-monospace,Menlo,Consolas,monospace;word-break:break-all}.lev
|
|
|
36906
37183
|
.ok{background:#e8f5e9;color:#1b5e20}.deny{background:#ffebee;color:#b71c1c}.err{background:#fff8e1;color:#7a5a00}.rep{outline:2px solid #b7791f}
|
|
36907
37184
|
@media (prefers-color-scheme:dark){.ok{background:#1b3a1e;color:#a5d6a7}.deny{background:#3b1616;color:#ef9a9a}.err{background:#3a3214;color:#ffe082}}
|
|
36908
37185
|
@media print{body{background:#fff}.card{break-inside:avoid}}`;
|
|
36909
|
-
page = (title,
|
|
37186
|
+
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
37187
|
`;
|
|
36911
37188
|
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
37189
|
effect = (t) => {
|
|
@@ -37234,10 +37511,10 @@ __export(init_exports, {
|
|
|
37234
37511
|
AGENT_RULES: () => AGENT_RULES,
|
|
37235
37512
|
initProject: () => initProject
|
|
37236
37513
|
});
|
|
37237
|
-
import { existsSync as
|
|
37514
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
37238
37515
|
import { join as join4 } from "node:path";
|
|
37239
37516
|
function initProject(dir, lang, name) {
|
|
37240
|
-
if (
|
|
37517
|
+
if (existsSync4(join4(dir, "package.json")) || existsSync4(join4(dir, "pyproject.toml")) || existsSync4(join4(dir, "server.py")))
|
|
37241
37518
|
throw new Error(`${dir} already contains a project; choose an empty folder.`);
|
|
37242
37519
|
const id = name.replace(/[^a-z0-9-]/gi, "-").toLowerCase() || "my-mcp-server";
|
|
37243
37520
|
const files = {};
|
|
@@ -37327,8 +37604,8 @@ if __name__ == "__main__":
|
|
|
37327
37604
|
${AGENT_RULES}`;
|
|
37328
37605
|
for (const [p, text2] of Object.entries(files)) {
|
|
37329
37606
|
const f = join4(dir, p);
|
|
37330
|
-
|
|
37331
|
-
|
|
37607
|
+
mkdirSync3(join4(f, ".."), { recursive: true });
|
|
37608
|
+
writeFileSync3(f, text2);
|
|
37332
37609
|
}
|
|
37333
37610
|
return Object.keys(files);
|
|
37334
37611
|
}
|
|
@@ -37415,16 +37692,16 @@ __export(proxy_exports, {
|
|
|
37415
37692
|
runProxy: () => runProxy
|
|
37416
37693
|
});
|
|
37417
37694
|
import { spawn as spawn3 } from "node:child_process";
|
|
37418
|
-
import { appendFileSync, existsSync as
|
|
37419
|
-
import { dirname as
|
|
37695
|
+
import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "node:fs";
|
|
37696
|
+
import { dirname as dirname3 } from "node:path";
|
|
37420
37697
|
import { createInterface } from "node:readline";
|
|
37421
37698
|
import { randomUUID } from "node:crypto";
|
|
37422
37699
|
async function runProxy(o) {
|
|
37423
|
-
|
|
37700
|
+
mkdirSync4(dirname3(o.receiptsPath), { recursive: true });
|
|
37424
37701
|
let last;
|
|
37425
37702
|
let history = [];
|
|
37426
|
-
if (
|
|
37427
|
-
history = parseReceiptLog(
|
|
37703
|
+
if (existsSync5(o.receiptsPath)) {
|
|
37704
|
+
history = parseReceiptLog(readFileSync6(o.receiptsPath, "utf8"));
|
|
37428
37705
|
last = history[history.length - 1];
|
|
37429
37706
|
}
|
|
37430
37707
|
const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
@@ -37510,6 +37787,30 @@ async function runProxy(o) {
|
|
|
37510
37787
|
else
|
|
37511
37788
|
d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
|
|
37512
37789
|
}
|
|
37790
|
+
if (d.allow && o.credential) {
|
|
37791
|
+
const vc = verifyChain(o.credential, { revoked: o.revokedCredentials });
|
|
37792
|
+
const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
|
|
37793
|
+
if (!vc.valid)
|
|
37794
|
+
d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
|
|
37795
|
+
else if (o.agreement && root !== o.agreement.invoker.id)
|
|
37796
|
+
d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
|
|
37797
|
+
}
|
|
37798
|
+
let metering;
|
|
37799
|
+
if (d.allow && o.agreement) {
|
|
37800
|
+
const va = verifyAgreement(o.agreement);
|
|
37801
|
+
if (!va.valid)
|
|
37802
|
+
d = { allow: false, code: "no-valid-agreement", reason: `no valid agreement with the provider: ${va.reason}` };
|
|
37803
|
+
else if (o.agreement.scope.tools && !o.agreement.scope.tools.includes(tool))
|
|
37804
|
+
d = { allow: false, code: "outside-agreement", reason: `${tool} is outside the agreement ${o.agreement.id}` };
|
|
37805
|
+
else if (o.walletPath) {
|
|
37806
|
+
const ch = chargeCall(o.walletPath, o.agreement, tool, `${o.agreement.id}:${tool}`);
|
|
37807
|
+
if (!ch.ok)
|
|
37808
|
+
d = { allow: false, code: "insufficient-credit", reason: `${tool} costs ${ch.tokens} tokens; the prepaid balance is ${ch.balance}` };
|
|
37809
|
+
else
|
|
37810
|
+
metering = { agreement: o.agreement.id, tokens: ch.tokens, balance: ch.balance };
|
|
37811
|
+
} else
|
|
37812
|
+
metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
|
|
37813
|
+
}
|
|
37513
37814
|
if (!d.allow && o.enforce) {
|
|
37514
37815
|
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
37816
|
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 +37819,7 @@ async function runProxy(o) {
|
|
|
37518
37819
|
return;
|
|
37519
37820
|
}
|
|
37520
37821
|
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 });
|
|
37822
|
+
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
37823
|
}
|
|
37523
37824
|
child.stdin.write(line + "\n");
|
|
37524
37825
|
});
|
|
@@ -37560,7 +37861,7 @@ async function runProxy(o) {
|
|
|
37560
37861
|
if (c) {
|
|
37561
37862
|
calls.delete(k);
|
|
37562
37863
|
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 } : {} });
|
|
37864
|
+
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
37865
|
}
|
|
37565
37866
|
process.stdout.write(line + "\n");
|
|
37566
37867
|
});
|
|
@@ -38259,7 +38560,7 @@ __export(demo_exports, {
|
|
|
38259
38560
|
runDemo: () => runDemo,
|
|
38260
38561
|
startDemoServer: () => startDemoServer
|
|
38261
38562
|
});
|
|
38262
|
-
import { mkdirSync as
|
|
38563
|
+
import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync4, existsSync as existsSync6, rmSync } from "node:fs";
|
|
38263
38564
|
import { join as join5 } from "node:path";
|
|
38264
38565
|
async function startDemoServer(story = "autonomy") {
|
|
38265
38566
|
const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : DEMO_TOOLS;
|
|
@@ -38321,7 +38622,7 @@ async function runStory(dir, st, owner, log) {
|
|
|
38321
38622
|
const operatorName = String(st.m.disclosures?.operator ?? "Demo operator");
|
|
38322
38623
|
const cm = cosignMandate(m, loadOrCreateKey(join5(dir, `${st.id}-operator-key.json`)), operatorName);
|
|
38323
38624
|
const mf = join5(dir, `${st.id}-mandate.json`), rf = join5(dir, `${st.id}-receipts.jsonl`), revf = join5(dir, "revocations.json");
|
|
38324
|
-
|
|
38625
|
+
writeFileSync4(mf, JSON.stringify(cm, null, 2));
|
|
38325
38626
|
log(`\u2500\u2500 ${st.title}`);
|
|
38326
38627
|
log(` Signed by you; countersigned by the operator, ${operatorName}.`);
|
|
38327
38628
|
for (const line of describeMandate(m))
|
|
@@ -38344,9 +38645,9 @@ async function runStory(dir, st, owner, log) {
|
|
|
38344
38645
|
if (rid)
|
|
38345
38646
|
lastRid = rid[1];
|
|
38346
38647
|
const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)( \[approval request [^\]]+\])?\.( Ask| Tell|$)/.exec(txt);
|
|
38347
|
-
const lastR = parseReceiptLog(
|
|
38648
|
+
const lastR = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
|
|
38348
38649
|
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(
|
|
38650
|
+
const last = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
|
|
38350
38651
|
for (const p of last?.result.rationale?.preferences ?? [])
|
|
38351
38652
|
if (!blocked)
|
|
38352
38653
|
log(` \xB7 ${p}`);
|
|
@@ -38371,42 +38672,169 @@ async function runStory(dir, st, owner, log) {
|
|
|
38371
38672
|
await new Promise((r) => setTimeout(r, 300));
|
|
38372
38673
|
}
|
|
38373
38674
|
}
|
|
38374
|
-
const entries = parseReceiptLog(
|
|
38675
|
+
const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
|
|
38375
38676
|
const ts = trustStatement(entries, verifyReceiptLog(entries).ok);
|
|
38376
38677
|
log(" Track record:");
|
|
38377
38678
|
for (const l of ts.lines)
|
|
38378
38679
|
log(` ${l}`);
|
|
38379
38680
|
const html = join5(dir, `${st.id}-passport.html`);
|
|
38380
|
-
|
|
38681
|
+
writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
|
|
38381
38682
|
verified: verifyReceiptLog(entries).ok,
|
|
38382
38683
|
summary: summariseReceipts(entries),
|
|
38383
38684
|
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 ") }))
|
|
38384
|
-
}, agentRiskTier(m), describeMandate(m), {
|
|
38385
|
-
|
|
38386
|
-
|
|
38387
|
-
|
|
38685
|
+
}, agentRiskTier(m), describeMandate(m), {
|
|
38686
|
+
operator: (() => {
|
|
38687
|
+
const op = checkOperator(cm);
|
|
38688
|
+
return op.present && op.valid ? `${op.name} (${op.id})` : void 0;
|
|
38689
|
+
})(),
|
|
38690
|
+
track: ts.lines,
|
|
38691
|
+
maturity: agentMaturity(cm, { entries, verified: verifyReceiptLog(entries).ok })
|
|
38692
|
+
}));
|
|
38388
38693
|
log(` ${entries.length} signed receipts \xB7 ${verifyReceiptLog(entries).ok ? "verified" : "NOT verified"} \xB7 passport: ${html}
|
|
38389
38694
|
`);
|
|
38390
38695
|
return html;
|
|
38391
38696
|
}
|
|
38697
|
+
async function runMarketplace(dir, log) {
|
|
38698
|
+
const self = [...process.execArgv, process.argv[1]];
|
|
38699
|
+
const k = (n) => loadOrCreateKey(join5(dir, `market-${n}-key.json`));
|
|
38700
|
+
const acme = k("acme"), priya = k("priya"), agent = k("agent"), grocer = k("grocer"), travel = k("travel");
|
|
38701
|
+
const exp = new Date(Date.now() + 180 * 864e5).toISOString().slice(0, 10);
|
|
38702
|
+
const w = (f, x) => {
|
|
38703
|
+
writeFileSync4(join5(dir, f), JSON.stringify(x, null, 2));
|
|
38704
|
+
return join5(dir, f);
|
|
38705
|
+
};
|
|
38706
|
+
log(`\u2500\u2500 Marketplace: "Acme's shopping agent finds a store, agrees terms, and pays per call in prepaid tokens"`);
|
|
38707
|
+
const root = organisationRoot({ name: "Acme Corp", domain: "acme.example", expires: exp }, acme);
|
|
38708
|
+
const priyaCred = issueCredential(root, acme, { type: "member", id: priya.kid, name: "Priya", role: "procurement lead", expires: exp });
|
|
38709
|
+
const agentCred = issueCredential(priyaCred, priya, { type: "agent", id: agent.kid, name: "Acme shopping agent", expires: exp });
|
|
38710
|
+
const credFile = w("market-agent-credential.json", agentCred);
|
|
38711
|
+
const vchain = verifyChain(agentCred);
|
|
38712
|
+
log(vchain.valid ? ` \u2713 identity chain: ${vchain.path.join(" \u2192 ")}; accountable organisation ${vchain.organisation}` : ` \u2717 identity chain broken: ${vchain.reason}`);
|
|
38713
|
+
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);
|
|
38714
|
+
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);
|
|
38715
|
+
w("market-catalog.json", [gm, tm]);
|
|
38716
|
+
log(` \u2713 Demo Grocer and Demo Travel publish signed manifests to the catalogue (rates in tokens per call)`);
|
|
38717
|
+
const hits = searchCatalogue([gm, tm], "buy weekly groceries for the office");
|
|
38718
|
+
log(` \u2713 the agent searches "buy weekly groceries for the office": ${hits[0].manifest.publisher.name} (intents ${hits[0].matched.join(", ")})`);
|
|
38719
|
+
const ag = acceptAgreement(draftAgreement({
|
|
38720
|
+
manifest: gm,
|
|
38721
|
+
invoker: { id: acme.kid, name: "Acme Corp" },
|
|
38722
|
+
purpose: "Weekly office groceries",
|
|
38723
|
+
tools: gm.capabilities.map((c) => c.tool),
|
|
38724
|
+
tokensPerMonth: 500,
|
|
38725
|
+
specificTerms: ["Deliveries to the Acme office only", "Substitutions within 10% of the price"],
|
|
38726
|
+
validUntil: exp
|
|
38727
|
+
}, grocer), acme);
|
|
38728
|
+
const agFile = w("market-agreement.json", ag);
|
|
38729
|
+
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"})`);
|
|
38730
|
+
const wf = join5(dir, "market-wallet.json");
|
|
38731
|
+
topUp(wf, acme.kid, 12);
|
|
38732
|
+
log(` \u2713 Acme tops up 12 prepaid tokens (bought outside Saktum; no money is handled here)`);
|
|
38733
|
+
const m = cosignMandate(createMandate({ agentId: agent.kid, agentName: "Acme shopping agent", ownerName: "Priya", purpose: "Weekly office groceries", tools: gm.capabilities.map((c) => c.tool), destructive: false, expires: exp, autonomy: "act", approveAbove: { arg: "amount", value: 50 } }, priya), acme, "Acme Corp");
|
|
38734
|
+
const mf = w("market-mandate.json", m), rf = join5(dir, "market-receipts.jsonl"), revf = join5(dir, "market-revoked-credentials.json");
|
|
38735
|
+
writeFileSync4(revf, "[]");
|
|
38736
|
+
const open2 = () => connect({ kind: "stdio", command: process.execPath, args: [
|
|
38737
|
+
...self,
|
|
38738
|
+
"proxy",
|
|
38739
|
+
"--mandate",
|
|
38740
|
+
mf,
|
|
38741
|
+
"--agent-key",
|
|
38742
|
+
join5(dir, "market-agent-key.json"),
|
|
38743
|
+
"--enforce",
|
|
38744
|
+
"--receipts",
|
|
38745
|
+
rf,
|
|
38746
|
+
"--credential",
|
|
38747
|
+
credFile,
|
|
38748
|
+
"--revoked-credentials",
|
|
38749
|
+
revf,
|
|
38750
|
+
"--agreement",
|
|
38751
|
+
agFile,
|
|
38752
|
+
"--wallet",
|
|
38753
|
+
wf,
|
|
38754
|
+
"--",
|
|
38755
|
+
process.execPath,
|
|
38756
|
+
...self,
|
|
38757
|
+
"demo-server",
|
|
38758
|
+
"--story",
|
|
38759
|
+
"grocery"
|
|
38760
|
+
] });
|
|
38761
|
+
const steps = [
|
|
38762
|
+
{ tool: "search_products", args: { query: "milk" }, say: "searches the catalogue" },
|
|
38763
|
+
{ tool: "add_to_cart", args: { product: "Oat milk", brand: "Usual Farms", category: "dairy", quantity: 2, price: 4.49 }, say: "adds oat milk" },
|
|
38764
|
+
{ tool: "add_to_cart", args: { product: "Coffee beans 1 kg", brand: "Usual Farms", category: "coffee", quantity: 1, price: 21.99 }, say: "adds coffee" },
|
|
38765
|
+
{ tool: "pay_for_order", args: { amount: 30.97, currency: "CAD", merchant: "Demo Grocer", idempotency_key: "m-1" }, say: "pays $30.97" },
|
|
38766
|
+
{ tool: "add_to_cart", args: { product: "Bread", brand: "Usual Farms", category: "bakery", quantity: 1, price: 5.99 }, say: "starts next week's order" },
|
|
38767
|
+
{ tool: "search_products", args: { query: "fruit" }, say: "searches again" }
|
|
38768
|
+
];
|
|
38769
|
+
const run = async (st2) => {
|
|
38770
|
+
const s2 = await open2();
|
|
38771
|
+
try {
|
|
38772
|
+
await s2.listTools();
|
|
38773
|
+
for (const st1 of st2) {
|
|
38774
|
+
const o = await s2.callTool(st1.tool, st1.args);
|
|
38775
|
+
const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
|
|
38776
|
+
const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)\.( Ask| Tell|$)/.exec(txt);
|
|
38777
|
+
const last = parseReceiptLog(readFileSync7(rf, "utf8")).pop();
|
|
38778
|
+
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 ?? "-"}`);
|
|
38779
|
+
}
|
|
38780
|
+
} finally {
|
|
38781
|
+
await s2.close();
|
|
38782
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
38783
|
+
}
|
|
38784
|
+
};
|
|
38785
|
+
await run(steps);
|
|
38786
|
+
const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
|
|
38787
|
+
const st = usageStatement(entries, ag, grocer);
|
|
38788
|
+
log(` \u2713 usage statement signed by Demo Grocer: ${st.lines.map((l) => `${l.tool} ${l.calls}\xD7 = ${l.tokens}`).join(", ")}; total ${st.totalTokens} tokens`);
|
|
38789
|
+
log(` \u2713 wallet (double-entry): Acme ${walletBalance(wf, acme.kid)} tokens, Demo Grocer ${walletBalance(wf, grocer.kid)} tokens`);
|
|
38790
|
+
writeFileSync4(revf, JSON.stringify([priyaCred.id]));
|
|
38791
|
+
const orphan = findOrphans([agentCred], { revoked: [priyaCred.id] })[0];
|
|
38792
|
+
log(` \u26D4 Priya leaves Acme and her credential is revoked: the agent is now an orphan (${orphan?.reason})`);
|
|
38793
|
+
topUp(wf, acme.kid, 5);
|
|
38794
|
+
await run([{ tool: "search_products", args: { query: "milk" }, say: "the orphaned agent tries to search" }]);
|
|
38795
|
+
const all = parseReceiptLog(readFileSync7(rf, "utf8"));
|
|
38796
|
+
const k2 = kpis(all);
|
|
38797
|
+
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`);
|
|
38798
|
+
const html = join5(dir, "marketplace-passport.html");
|
|
38799
|
+
const ts = trustStatement(all, verifyReceiptLog(all).ok);
|
|
38800
|
+
writeFileSync4(html, renderAgentPassport(m, { ok: true }, { verified: verifyReceiptLog(all).ok, summary: summariseReceipts(all), timeline: all.map((e) => ({ tool: e.receipt.envelope.tool, outcome: e.receipt.outcome, status: e.result.status, repeated: false, why: [e.receipt.reason ?? "", e.result.metering ? `${e.result.metering.tokens} token(s), balance ${e.result.metering.balance}` : ""].filter(Boolean).join(" \xB7 ") })) }, agentRiskTier(m), [`Weekly office groceries for Acme Corp, under agreement ${ag.id} with Demo Grocer.`, `Accountable: ${verifyChain(agentCred).path.join(" \u2192 ")}.`, "Paid per call in prepaid tokens."], { operator: "Acme Corp", track: ts.lines, maturity: agentMaturity(m, { entries: all, verified: verifyReceiptLog(all).ok, chainValid: verifyChain(agentCred).valid }) }));
|
|
38801
|
+
log(` ${all.length} signed receipts \xB7 ${verifyReceiptLog(all).ok ? "verified" : "NOT verified"} \xB7 passport: ${html}
|
|
38802
|
+
`);
|
|
38803
|
+
return html;
|
|
38804
|
+
}
|
|
38392
38805
|
async function runDemo(dir, log, story = "all") {
|
|
38393
38806
|
if (story === "autonomy")
|
|
38394
38807
|
return runAutonomyDemo(dir, log);
|
|
38395
|
-
if (
|
|
38808
|
+
if (story === "marketplace") {
|
|
38809
|
+
if (existsSync6(dir))
|
|
38810
|
+
rmSync(dir, { recursive: true, force: true });
|
|
38811
|
+
mkdirSync5(dir, { recursive: true });
|
|
38812
|
+
return { files: [await runMarketplace(dir, log)] };
|
|
38813
|
+
}
|
|
38814
|
+
if (existsSync6(dir))
|
|
38396
38815
|
rmSync(dir, { recursive: true, force: true });
|
|
38397
|
-
|
|
38816
|
+
mkdirSync5(dir, { recursive: true });
|
|
38398
38817
|
const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
|
|
38399
38818
|
log("Saktum demo: agents acting on real instructions (rules, preferences, substitutions, upsells), every decision explained and signed.\n");
|
|
38400
38819
|
const files = [];
|
|
38401
38820
|
for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : [GROCERY, TRAVEL, FINANCE])
|
|
38402
38821
|
files.push(await runStory(dir, st, owner, log));
|
|
38403
|
-
|
|
38822
|
+
if (story === "all")
|
|
38823
|
+
files.push(await runMarketplace(dir, log));
|
|
38824
|
+
log([
|
|
38825
|
+
"What you just saw: each agent followed its owner's instructions, not just limits. Even when tricked by a hidden",
|
|
38826
|
+
"instruction, the mandate held; personal and confidential data went only where you allowed; a big invoice waited for your",
|
|
38827
|
+
"signed approval of exactly that payment; and the stop button worked. In the marketplace, an agent traceable to a person",
|
|
38828
|
+
"and its organisation found a store by intent, both sides signed an agreement, every call was metered in prepaid tokens",
|
|
38829
|
+
"until credit ran out, and when its sponsor left, the orphaned agent was refused. Every decision has a signed receipt.",
|
|
38830
|
+
"Open the passports in the demo folder. Also try: npx saktum demo --story autonomy"
|
|
38831
|
+
].join("\n"));
|
|
38404
38832
|
return { files };
|
|
38405
38833
|
}
|
|
38406
38834
|
async function runAutonomyDemo(dir, log) {
|
|
38407
|
-
if (
|
|
38835
|
+
if (existsSync6(dir))
|
|
38408
38836
|
rmSync(dir, { recursive: true, force: true });
|
|
38409
|
-
|
|
38837
|
+
mkdirSync5(dir, { recursive: true });
|
|
38410
38838
|
const owner = loadOrCreateKey(join5(dir, "owner-key.json"));
|
|
38411
38839
|
const self = [...process.execArgv, process.argv[1]];
|
|
38412
38840
|
const tools = DEMO_TOOLS.map((t) => t.name);
|
|
@@ -38431,7 +38859,7 @@ async function runAutonomyDemo(dir, log) {
|
|
|
38431
38859
|
...p.m
|
|
38432
38860
|
}, owner);
|
|
38433
38861
|
const mf = join5(dir, `${p.id}-mandate.json`), rf = join5(dir, `${p.id}-receipts.jsonl`);
|
|
38434
|
-
|
|
38862
|
+
writeFileSync4(mf, JSON.stringify(m, null, 2));
|
|
38435
38863
|
const tier = agentRiskTier(m);
|
|
38436
38864
|
log(`\u2500\u2500 ${p.title} autonomy ${m.autonomy} \xB7 risk ${tier.tier}`);
|
|
38437
38865
|
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 +38875,14 @@ async function runAutonomyDemo(dir, log) {
|
|
|
38447
38875
|
await s.close();
|
|
38448
38876
|
await new Promise((r) => setTimeout(r, 300));
|
|
38449
38877
|
}
|
|
38450
|
-
const entries = parseReceiptLog(
|
|
38878
|
+
const entries = parseReceiptLog(readFileSync7(rf, "utf8"));
|
|
38451
38879
|
const counts = /* @__PURE__ */ new Map();
|
|
38452
38880
|
for (const e of entries) {
|
|
38453
38881
|
const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
|
|
38454
38882
|
counts.set(k, (counts.get(k) ?? 0) + 1);
|
|
38455
38883
|
}
|
|
38456
38884
|
const html = join5(dir, `${p.id}-passport.html`);
|
|
38457
|
-
|
|
38885
|
+
writeFileSync4(html, renderAgentPassport(m, checkMandate(m).ok ? { ok: true } : { ok: false }, {
|
|
38458
38886
|
verified: verifyReceiptLog(entries).ok,
|
|
38459
38887
|
summary: summariseReceipts(entries),
|
|
38460
38888
|
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 +39031,7 @@ __export(mcp_server_exports, {
|
|
|
38603
39031
|
splitTarget: () => splitTarget,
|
|
38604
39032
|
startMcpServer: () => startMcpServer
|
|
38605
39033
|
});
|
|
38606
|
-
import { readFileSync as
|
|
39034
|
+
import { readFileSync as readFileSync8 } from "node:fs";
|
|
38607
39035
|
function splitTarget(target) {
|
|
38608
39036
|
const t = target.trim();
|
|
38609
39037
|
if (/^https?:\/\//i.test(t))
|
|
@@ -38639,7 +39067,7 @@ async function handleSaktumTool(name, args, packs) {
|
|
|
38639
39067
|
case "diff_against_lock": {
|
|
38640
39068
|
if (typeof args.lock_path !== "string")
|
|
38641
39069
|
throw new Error("lock_path is required");
|
|
38642
|
-
const before = JSON.parse(
|
|
39070
|
+
const before = JSON.parse(readFileSync8(args.lock_path, "utf8"));
|
|
38643
39071
|
const d = diffLocks(before, { tools: (await listTools(targetOf(args.target))).tools });
|
|
38644
39072
|
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
39073
|
}
|
|
@@ -38780,7 +39208,7 @@ var init_mcp_server = __esm({
|
|
|
38780
39208
|
});
|
|
38781
39209
|
|
|
38782
39210
|
// packages/cli/dist/main.js
|
|
38783
|
-
import { existsSync as
|
|
39211
|
+
import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
|
|
38784
39212
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
38785
39213
|
|
|
38786
39214
|
// node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
|
|
@@ -38947,13 +39375,13 @@ init_dist3();
|
|
|
38947
39375
|
var SEV2 = ["critical", "high", "medium", "low", "info"];
|
|
38948
39376
|
async function loadPolicy(file) {
|
|
38949
39377
|
const { readFileSync: rf, existsSync: ex } = await import("node:fs");
|
|
38950
|
-
const { dirname:
|
|
39378
|
+
const { dirname: dirname4, resolve } = await import("node:path");
|
|
38951
39379
|
if (!ex(file))
|
|
38952
39380
|
throw new Error(`Policy file not found: ${file}`);
|
|
38953
39381
|
const policy = await parsePolicy(rf(file, "utf8"));
|
|
38954
39382
|
let allow;
|
|
38955
39383
|
if (policy.allowlist) {
|
|
38956
|
-
const path = resolve(
|
|
39384
|
+
const path = resolve(dirname4(file), policy.allowlist);
|
|
38957
39385
|
if (!ex(path))
|
|
38958
39386
|
throw new Error(`The policy's allowlist was not found: ${policy.allowlist}`);
|
|
38959
39387
|
allow = new Set(JSON.parse(rf(path, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f)));
|
|
@@ -39016,16 +39444,16 @@ async function main(argv = process.argv) {
|
|
|
39016
39444
|
});
|
|
39017
39445
|
let testCases;
|
|
39018
39446
|
if (o.tests) {
|
|
39019
|
-
if (!
|
|
39447
|
+
if (!existsSync7(o.tests))
|
|
39020
39448
|
throw new Error(`Test file not found: ${o.tests}. See docs/TESTS.md for the format.`);
|
|
39021
|
-
testCases = await parseTestCases(
|
|
39449
|
+
testCases = await parseTestCases(readFileSync9(o.tests, "utf8"));
|
|
39022
39450
|
}
|
|
39023
39451
|
const target = parseTarget(targetParts);
|
|
39024
39452
|
if (target.kind === "stdio" && o.env.length)
|
|
39025
39453
|
target.env = parseEnv(o.env);
|
|
39026
39454
|
if (target.kind === "streamable-http" && o.header.length)
|
|
39027
39455
|
target.headers = parseHeaders(o.header);
|
|
39028
|
-
const packs = o.packs ? loadPackDir(o.packs) :
|
|
39456
|
+
const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
|
|
39029
39457
|
let result;
|
|
39030
39458
|
try {
|
|
39031
39459
|
result = await runTrustCheck(target, { packs, mode: o.active ? "active" : "passive", pricePerMTokUsd: price, callTools: o.call, testCases, ignore });
|
|
@@ -39037,23 +39465,23 @@ async function main(argv = process.argv) {
|
|
|
39037
39465
|
return 2;
|
|
39038
39466
|
}
|
|
39039
39467
|
const signed = signDocument(result, loadOrCreateKey(o.key));
|
|
39040
|
-
|
|
39468
|
+
writeFileSync5(o.out, JSON.stringify(signed, null, 2));
|
|
39041
39469
|
if (o.html)
|
|
39042
|
-
|
|
39470
|
+
writeFileSync5(o.html, renderHtml(signed));
|
|
39043
39471
|
if (o.badge)
|
|
39044
|
-
|
|
39472
|
+
writeFileSync5(o.badge, badgeSvg(signed));
|
|
39045
39473
|
const keyOf = (f) => `${f.check}:${f.subject ?? ""}`;
|
|
39046
39474
|
const failing = signed.findings.filter((f) => f.status === "fail" && !f.suppressed);
|
|
39047
39475
|
let accepted = /* @__PURE__ */ new Set();
|
|
39048
39476
|
if (o.baseline && o.updateBaseline) {
|
|
39049
|
-
|
|
39477
|
+
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
39478
|
process.stdout.write(`Wrote baseline ${sanitizeText(o.baseline)} accepting ${failing.length} existing finding(s). Commit it; later runs fail only on new findings.
|
|
39051
39479
|
`);
|
|
39052
|
-
} else if (o.baseline &&
|
|
39053
|
-
accepted = new Set(JSON.parse(
|
|
39480
|
+
} else if (o.baseline && existsSync7(o.baseline)) {
|
|
39481
|
+
accepted = new Set(JSON.parse(readFileSync9(o.baseline, "utf8")).accepted.map(keyOf));
|
|
39054
39482
|
}
|
|
39055
39483
|
if (o.sarif)
|
|
39056
|
-
|
|
39484
|
+
writeFileSync5(o.sarif, JSON.stringify(toSarif(signed, o.sarifAnchor, accepted), null, 2) + "\n");
|
|
39057
39485
|
process.stdout.write(renderTerminal(signed) + "\n");
|
|
39058
39486
|
process.stdout.write(`
|
|
39059
39487
|
Signed result: ${sanitizeText(o.out)} (verify with: saktum verify ${sanitizeText(o.out)})${o.badge ? `
|
|
@@ -39122,7 +39550,7 @@ Watching ${sanitizeText(o.watchDir)} for changes (Ctrl+C to stop).
|
|
|
39122
39550
|
exitCode = await runCheckCommand(targetParts, o);
|
|
39123
39551
|
});
|
|
39124
39552
|
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) :
|
|
39553
|
+
const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
|
|
39126
39554
|
process.stdout.write(checksTable(packs, o.markdown));
|
|
39127
39555
|
});
|
|
39128
39556
|
const listTarget = async (targetParts, env, header) => {
|
|
@@ -39144,13 +39572,13 @@ Watching ${sanitizeText(o.watchDir)} for changes (Ctrl+C to stop).
|
|
|
39144
39572
|
});
|
|
39145
39573
|
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
39574
|
const { tools, server } = await listTarget(targetParts, o.env, o.header);
|
|
39147
|
-
|
|
39575
|
+
writeFileSync5(o.out, JSON.stringify(toolsLock(tools, server), null, 2) + "\n");
|
|
39148
39576
|
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
39577
|
`);
|
|
39150
39578
|
});
|
|
39151
39579
|
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(
|
|
39153
|
-
const after = rest.length === 1 && rest[0].endsWith(".json") ? JSON.parse(
|
|
39580
|
+
const before = JSON.parse(readFileSync9(lock, "utf8"));
|
|
39581
|
+
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
39582
|
const d = diffLocks(before, after);
|
|
39155
39583
|
const mark2 = { breaking: "\u2717 BREAKING", risky: "! REVIEW ", addition: "+ ADDED ", change: "~ CHANGED " };
|
|
39156
39584
|
for (const c of d.changes)
|
|
@@ -39167,11 +39595,11 @@ ${d.summary}
|
|
|
39167
39595
|
process.stdout.write(docsFor(tools, name, target.kind === "stdio" ? { command: target.command, args: target.args } : { url: target.url }));
|
|
39168
39596
|
});
|
|
39169
39597
|
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(
|
|
39598
|
+
const doc = JSON.parse(readFileSync9(file, "utf8"));
|
|
39171
39599
|
const v = verifyDocument(doc);
|
|
39172
39600
|
if (!v.valid)
|
|
39173
39601
|
throw new Error(`The result's signature is not valid (${v.reason}); a packet must be built from an unaltered signed result.`);
|
|
39174
|
-
|
|
39602
|
+
writeFileSync5(o.out, renderPacket(doc, v.kid));
|
|
39175
39603
|
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
39604
|
`);
|
|
39177
39605
|
});
|
|
@@ -39181,9 +39609,9 @@ ${d.summary}
|
|
|
39181
39609
|
const check = verifyLedger(entries);
|
|
39182
39610
|
if (!check.ok)
|
|
39183
39611
|
throw new Error(`The ledger does not verify: ${check.errors[0]}`);
|
|
39184
|
-
const signers = o.trustedSigners ? new Set(
|
|
39612
|
+
const signers = o.trustedSigners ? new Set(readFileSync9(o.trustedSigners, "utf8").split(/\r?\n/).map((l) => l.trim()).filter(Boolean)) : void 0;
|
|
39185
39613
|
const list2 = allowlistFromLedger(entries, { minTrust: o.minTrust.toUpperCase(), minReadiness: o.minReadiness.toUpperCase(), trustedSigners: signers });
|
|
39186
|
-
|
|
39614
|
+
writeFileSync5(o.out, JSON.stringify(list2, null, 2) + "\n");
|
|
39187
39615
|
process.stdout.write(`Ledger verified (${check.count} entries). Wrote ${sanitizeText(o.out)}: ${list2.allowed.length} allowed, ${list2.excluded.length} excluded.
|
|
39188
39616
|
`);
|
|
39189
39617
|
return;
|
|
@@ -39191,14 +39619,14 @@ ${d.summary}
|
|
|
39191
39619
|
if (!files.length)
|
|
39192
39620
|
throw new Error("Give signed results, or use --from-ledger.");
|
|
39193
39621
|
const inputs = files.map((f) => {
|
|
39194
|
-
const doc = JSON.parse(
|
|
39622
|
+
const doc = JSON.parse(readFileSync9(f, "utf8"));
|
|
39195
39623
|
const v = verifyDocument(doc);
|
|
39196
39624
|
if (!v.valid)
|
|
39197
39625
|
throw new Error(`${f}: signature not valid (${v.reason}); only unaltered signed results can be allowlisted.`);
|
|
39198
39626
|
return { result: doc, signedBy: v.kid };
|
|
39199
39627
|
});
|
|
39200
39628
|
const list = buildAllowlist(inputs, { minTrust: o.minTrust.toUpperCase(), minReadiness: o.minReadiness.toUpperCase(), noFailedCritical: !o.allowCritical });
|
|
39201
|
-
|
|
39629
|
+
writeFileSync5(o.out, JSON.stringify(list, null, 2) + "\n");
|
|
39202
39630
|
for (const a of list.allowed)
|
|
39203
39631
|
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
39632
|
`);
|
|
@@ -39235,7 +39663,7 @@ Next:
|
|
|
39235
39663
|
${findings.length} finding(s) in tool definitions.
|
|
39236
39664
|
` : "No problems found in tool definitions (files importing an MCP SDK).\n");
|
|
39237
39665
|
if (o.sarif)
|
|
39238
|
-
|
|
39666
|
+
writeFileSync5(o.sarif, JSON.stringify(lintSarif(findings, ENGINE_VERSION), null, 2) + "\n");
|
|
39239
39667
|
exitCode = findings.some((f) => f.severity === "error" || o.strict) ? 1 : 0;
|
|
39240
39668
|
});
|
|
39241
39669
|
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 +39706,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
|
|
|
39278
39706
|
expect.outputSchema = true;
|
|
39279
39707
|
expect.latencyMs = { lt: Math.max(2e3, outcome.latencyMs * 5) };
|
|
39280
39708
|
const tc = { id: o.saveTest, tool: toolName, input: args, ...tool.annotations?.readOnlyHint === true ? {} : { sideEffects: true }, expect };
|
|
39281
|
-
|
|
39709
|
+
writeFileSync5(o.tests, await appendTestCase(existsSync7(o.tests) ? readFileSync9(o.tests, "utf8") : void 0, tc));
|
|
39282
39710
|
process.stdout.write(`Saved test case ${sanitizeText(o.saveTest, 60)} to ${sanitizeText(o.tests)}. Run: saktum test -- <start command>
|
|
39283
39711
|
`);
|
|
39284
39712
|
}
|
|
@@ -39286,7 +39714,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
|
|
|
39286
39714
|
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
39715
|
const { homedir: homedir2 } = await import("node:os");
|
|
39288
39716
|
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) =>
|
|
39717
|
+
const servers = locations.filter((l) => existsSync7(l.file)).flatMap((l) => parseClientConfig(readFileSync9(l.file, "utf8"), l.client, l.file)).filter((x) => !x.disabled);
|
|
39290
39718
|
if (!servers.length) {
|
|
39291
39719
|
process.stdout.write("No MCP servers found in the known configuration locations. Point to one with --config <file>.\n");
|
|
39292
39720
|
return;
|
|
@@ -39309,7 +39737,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
|
|
|
39309
39737
|
return;
|
|
39310
39738
|
}
|
|
39311
39739
|
}
|
|
39312
|
-
const packs =
|
|
39740
|
+
const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
|
|
39313
39741
|
const scans = [];
|
|
39314
39742
|
for (const x of servers) {
|
|
39315
39743
|
let tools = [];
|
|
@@ -39336,7 +39764,7 @@ ${structured ? `structured: ${sanitizeText(JSON.stringify(structured), 1e3)}
|
|
|
39336
39764
|
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
39765
|
}
|
|
39338
39766
|
}
|
|
39339
|
-
const allow = o.allowlist ? new Set(JSON.parse(
|
|
39767
|
+
const allow = o.allowlist ? new Set(JSON.parse(readFileSync9(o.allowlist, "utf8")).allowed.map((a) => a.toolsFingerprint).filter((f) => Boolean(f))) : void 0;
|
|
39340
39768
|
const report = analyseSetup(scans, { turnsPerDay: Number(o.turnsPerDay) || 50, pricePerMTokUsd: Number(o.pricePerMtok) || 3, allowlistFingerprints: allow });
|
|
39341
39769
|
process.stdout.write("\n" + renderSetup(report));
|
|
39342
39770
|
if (o.policy) {
|
|
@@ -39349,10 +39777,10 @@ POLICY${policy.name ? ` (${sanitizeText(policy.name, 80)})` : ""}
|
|
|
39349
39777
|
}
|
|
39350
39778
|
const { hostname } = await import("node:os");
|
|
39351
39779
|
if (o.out)
|
|
39352
|
-
|
|
39780
|
+
writeFileSync5(o.out, JSON.stringify({ ...report, machine: o.machine ?? hostname() }, null, 2) + "\n");
|
|
39353
39781
|
});
|
|
39354
39782
|
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(
|
|
39783
|
+
const r = verifyCredentialJwt(readFileSync9(f, "utf8"));
|
|
39356
39784
|
if (r.valid) {
|
|
39357
39785
|
const cs = r.credential.credentialSubject ?? {};
|
|
39358
39786
|
process.stdout.write(`\u2713 Valid credential from ${r.issuer}: ${sanitizeText(String(cs.server ?? ""), 80)} trust ${cs.trustGrade ?? "-"}, readiness ${cs.readinessGrade ?? "-"}.
|
|
@@ -39385,21 +39813,21 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
|
|
|
39385
39813
|
const v = verifyLedger(entries);
|
|
39386
39814
|
if (!v.ok)
|
|
39387
39815
|
throw new Error(`The ledger does not verify: ${v.errors[0]}`);
|
|
39388
|
-
const { mkdirSync:
|
|
39389
|
-
|
|
39816
|
+
const { mkdirSync: mkdirSync6 } = await import("node:fs");
|
|
39817
|
+
mkdirSync6(o.out, { recursive: true });
|
|
39390
39818
|
const latest = /* @__PURE__ */ new Map();
|
|
39391
39819
|
for (const e of entries)
|
|
39392
39820
|
latest.set(e.subject.server, e);
|
|
39393
39821
|
for (const e of latest.values())
|
|
39394
|
-
|
|
39395
|
-
|
|
39822
|
+
writeFileSync5(`${o.out}/${passportSlug(e.subject.server)}.html`, renderLedgerPassport(e));
|
|
39823
|
+
writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries));
|
|
39396
39824
|
process.stdout.write(`Wrote ${latest.size} passport page(s) and the gallery to ${sanitizeText(o.out)}.
|
|
39397
39825
|
`);
|
|
39398
39826
|
});
|
|
39399
39827
|
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(
|
|
39401
|
-
const { text: text2, entry } = appendToLedger(
|
|
39402
|
-
|
|
39828
|
+
const att = extractJson(readFileSync9(input, "utf8"));
|
|
39829
|
+
const { text: text2, entry } = appendToLedger(existsSync7(o.ledger) ? readFileSync9(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
|
|
39830
|
+
writeFileSync5(o.ledger, text2);
|
|
39403
39831
|
process.stdout.write(`Recorded entry #${entry.seq} for ${sanitizeText(entry.subject.server, 80)} (signed by ${entry.signer}); entry hash ${entry.entryHash}.
|
|
39404
39832
|
`);
|
|
39405
39833
|
});
|
|
@@ -39445,17 +39873,17 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
|
|
|
39445
39873
|
approveAbove: aa,
|
|
39446
39874
|
disclosures: { ...o.operator ? { operator: o.operator } : {}, ...o.incentives ? { incentives: o.incentives } : {}, ...o.dataUse ? { dataUse: o.dataUse } : {} },
|
|
39447
39875
|
delegation: o.allowDelegation,
|
|
39448
|
-
...o.intent ? JSON.parse(
|
|
39876
|
+
...o.intent ? JSON.parse(readFileSync9(o.intent, "utf8")) : {}
|
|
39449
39877
|
}, loadOrCreateKey(o.key));
|
|
39450
39878
|
if (o.software) {
|
|
39451
|
-
const { signature: _old, ...
|
|
39452
|
-
|
|
39453
|
-
Object.assign(m, signDocument(
|
|
39879
|
+
const { signature: _old, ...body2 } = m;
|
|
39880
|
+
body2.agent = { ...body2.agent, software: o.software };
|
|
39881
|
+
Object.assign(m, signDocument(body2, loadOrCreateKey(o.key)));
|
|
39454
39882
|
}
|
|
39455
39883
|
const valid = compileContract("mandate.schema.json");
|
|
39456
39884
|
if (!valid(m))
|
|
39457
39885
|
throw new Error(`The mandate is not valid: ${(valid.errors ?? []).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}`);
|
|
39458
|
-
|
|
39886
|
+
writeFileSync5(o.out, JSON.stringify(m, null, 2) + "\n");
|
|
39459
39887
|
for (const line of describeMandate(m))
|
|
39460
39888
|
process.stdout.write(` ${line}
|
|
39461
39889
|
`);
|
|
@@ -39465,7 +39893,7 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
39465
39893
|
`);
|
|
39466
39894
|
});
|
|
39467
39895
|
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(
|
|
39896
|
+
const m = JSON.parse(readFileSync9(f, "utf8"));
|
|
39469
39897
|
const c = checkMandate(m), op = checkOperator(m), rev = revocationOf(m);
|
|
39470
39898
|
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
39899
|
` : `\u2717 ${c.reason}
|
|
@@ -39480,32 +39908,32 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
39480
39908
|
exitCode = c.ok && (!op.present || op.valid) && !rev ? 0 : 1;
|
|
39481
39909
|
});
|
|
39482
39910
|
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(
|
|
39911
|
+
const m = JSON.parse(readFileSync9(f, "utf8"));
|
|
39484
39912
|
if (!checkMandate(m).ok)
|
|
39485
39913
|
throw new Error("The mandate is not valid; it cannot be countersigned.");
|
|
39486
39914
|
const signed = cosignMandate(m, loadOrCreateKey(o.key), o.name);
|
|
39487
|
-
|
|
39915
|
+
writeFileSync5(f, JSON.stringify(signed, null, 2) + "\n");
|
|
39488
39916
|
process.stdout.write(`Countersigned by ${sanitizeText(o.name, 80)} (${loadOrCreateKey(o.key).kid}). Check: npx saktum agent verify ${sanitizeText(f)}
|
|
39489
39917
|
`);
|
|
39490
39918
|
});
|
|
39491
39919
|
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(
|
|
39920
|
+
const m = JSON.parse(readFileSync9(o.mandate, "utf8"));
|
|
39493
39921
|
const a = approveAction(m, rid, loadOrCreateKey(o.key), Number(o.minutes), o.approvals);
|
|
39494
39922
|
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
39923
|
`);
|
|
39496
39924
|
});
|
|
39497
39925
|
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(
|
|
39926
|
+
const m = JSON.parse(readFileSync9(f, "utf8"));
|
|
39499
39927
|
const r = revokeMandate(m, o.reason);
|
|
39500
39928
|
process.stdout.write(`Revoked the mandate for ${sanitizeText(m.agent.name, 80)} at ${r.at}. Its calls are now refused (code: revoked).
|
|
39501
39929
|
`);
|
|
39502
39930
|
});
|
|
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) => {
|
|
39931
|
+
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
39932
|
const { homedir: homedir2 } = await import("node:os");
|
|
39505
39933
|
const { join: join6 } = await import("node:path");
|
|
39506
39934
|
let mandate;
|
|
39507
39935
|
if (o.mandate) {
|
|
39508
|
-
mandate = JSON.parse(
|
|
39936
|
+
mandate = JSON.parse(readFileSync9(o.mandate, "utf8"));
|
|
39509
39937
|
const c = checkMandate(mandate);
|
|
39510
39938
|
if (!c.ok)
|
|
39511
39939
|
throw new Error(`Mandate refused: ${c.reason}`);
|
|
@@ -39514,14 +39942,28 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
39514
39942
|
if (mandate && agentKey.kid !== mandate.agent.id)
|
|
39515
39943
|
throw new Error("The agent key does not match the mandate's agent.");
|
|
39516
39944
|
const { runProxy: runProxy2 } = await Promise.resolve().then(() => (init_proxy(), proxy_exports));
|
|
39517
|
-
exitCode = await runProxy2({
|
|
39518
|
-
|
|
39945
|
+
exitCode = await runProxy2({
|
|
39946
|
+
command: parts[0],
|
|
39947
|
+
args: parts.slice(1),
|
|
39948
|
+
receiptsPath: o.receipts ?? join6(homedir2(), ".saktum", "receipts.jsonl"),
|
|
39949
|
+
agentKey,
|
|
39950
|
+
mandate,
|
|
39951
|
+
enforce: o.enforce,
|
|
39952
|
+
...o.revocations ? { revocationsPath: o.revocations } : {},
|
|
39953
|
+
...o.approvals ? { approvalsPath: o.approvals } : {},
|
|
39954
|
+
...o.credential ? { credential: JSON.parse(readFileSync9(o.credential, "utf8")) } : {},
|
|
39955
|
+
...o.revokedCredentials ? { revokedCredentials: JSON.parse(readFileSync9(o.revokedCredentials, "utf8")) } : {},
|
|
39956
|
+
...o.agreement ? { agreement: JSON.parse(readFileSync9(o.agreement, "utf8")) } : {},
|
|
39957
|
+
...o.wallet ? { walletPath: o.wallet } : {},
|
|
39958
|
+
log: (m) => process.stderr.write(`saktum: ${m}
|
|
39959
|
+
`)
|
|
39960
|
+
});
|
|
39519
39961
|
});
|
|
39520
39962
|
const receipts = program2.command("receipts").description("Signed receipts of agent tool calls (from saktum proxy)");
|
|
39521
39963
|
receipts.command("verify").description("Verify every receipt's signature and the hash chain").argument("[file]", "receipt log").action(async (f) => {
|
|
39522
39964
|
const { homedir: homedir2 } = await import("node:os");
|
|
39523
39965
|
const { join: join6 } = await import("node:path");
|
|
39524
|
-
const r = verifyReceiptLog(parseReceiptLog(
|
|
39966
|
+
const r = verifyReceiptLog(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")));
|
|
39525
39967
|
process.stdout.write(r.ok ? `\u2713 ${r.count} receipts verified: every signature valid, chain intact.
|
|
39526
39968
|
` : `\u2717 Receipts do NOT verify:
|
|
39527
39969
|
${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
@@ -39531,10 +39973,10 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
39531
39973
|
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
39974
|
const { homedir: homedir2 } = await import("node:os");
|
|
39533
39975
|
const { join: join6 } = await import("node:path");
|
|
39534
|
-
const entries = parseReceiptLog(
|
|
39976
|
+
const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
|
|
39535
39977
|
const v = verifyReceiptLog(entries);
|
|
39536
39978
|
const otlp = receiptsToOtlp(entries, { verified: v.ok, version: ENGINE_VERSION });
|
|
39537
|
-
|
|
39979
|
+
writeFileSync5(o.otel, JSON.stringify(otlp, null, 2) + "\n");
|
|
39538
39980
|
process.stdout.write(`Wrote ${entries.length} span(s) to ${sanitizeText(o.otel)} (receipts ${v.ok ? "verified" : "DO NOT verify"}).
|
|
39539
39981
|
`);
|
|
39540
39982
|
if (o.endpoint) {
|
|
@@ -39549,7 +39991,7 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
39549
39991
|
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
39992
|
const { homedir: homedir2 } = await import("node:os");
|
|
39551
39993
|
const { join: join6 } = await import("node:path");
|
|
39552
|
-
const entries = parseReceiptLog(
|
|
39994
|
+
const entries = parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8"));
|
|
39553
39995
|
const v = verifyReceiptLog(entries), s = summariseReceipts(entries);
|
|
39554
39996
|
if (o.json) {
|
|
39555
39997
|
process.stdout.write(JSON.stringify({ verified: v.ok, ...s }, null, 2) + "\n");
|
|
@@ -39563,11 +40005,11 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
39563
40005
|
});
|
|
39564
40006
|
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
40007
|
if (o.agent) {
|
|
39566
|
-
const m = JSON.parse(
|
|
40008
|
+
const m = JSON.parse(readFileSync9(o.agent, "utf8"));
|
|
39567
40009
|
const valid = checkMandate(m);
|
|
39568
40010
|
let receipts2;
|
|
39569
40011
|
if (o.receipts) {
|
|
39570
|
-
const entries = parseReceiptLog(
|
|
40012
|
+
const entries = parseReceiptLog(readFileSync9(o.receipts, "utf8"));
|
|
39571
40013
|
const counts = /* @__PURE__ */ new Map();
|
|
39572
40014
|
for (const e of entries) {
|
|
39573
40015
|
const k = `${e.receipt.envelope.tool}|${e.receipt.envelope.argumentsHash}`;
|
|
@@ -39580,8 +40022,12 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
39580
40022
|
};
|
|
39581
40023
|
}
|
|
39582
40024
|
const rev = revocationOf(m), op = checkOperator(m);
|
|
39583
|
-
const ts = o.receipts ? trustStatement(parseReceiptLog(
|
|
39584
|
-
|
|
40025
|
+
const ts = o.receipts ? trustStatement(parseReceiptLog(readFileSync9(o.receipts, "utf8")), receipts2?.verified ?? false) : void 0;
|
|
40026
|
+
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), {
|
|
40027
|
+
operator: op.present && op.valid ? `${op.name} (${op.id})` : void 0,
|
|
40028
|
+
track: ts?.lines,
|
|
40029
|
+
maturity: agentMaturity(m, { entries: o.receipts ? parseReceiptLog(readFileSync9(o.receipts, "utf8")) : [], verified: receipts2?.verified, revoked: Boolean(rev) })
|
|
40030
|
+
}));
|
|
39585
40031
|
process.stdout.write(`Wrote the Agent Passport for ${sanitizeText(m.agent.name, 80)} to ${sanitizeText(o.out)}. Open it in a browser.
|
|
39586
40032
|
`);
|
|
39587
40033
|
return;
|
|
@@ -39593,20 +40039,20 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
39593
40039
|
target.env = parseEnv(o.env);
|
|
39594
40040
|
if (target.kind === "streamable-http" && o.header.length)
|
|
39595
40041
|
target.headers = parseHeaders(o.header);
|
|
39596
|
-
const packs =
|
|
40042
|
+
const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
|
|
39597
40043
|
let tools = [];
|
|
39598
40044
|
const r = await runTrustCheck(target, { packs, onTools: (t) => {
|
|
39599
40045
|
tools = t;
|
|
39600
40046
|
} });
|
|
39601
40047
|
const signed = signDocument(r, loadOrCreateKey(o.key));
|
|
39602
|
-
|
|
39603
|
-
|
|
40048
|
+
writeFileSync5(o.out, renderServerPassport(signed, tools));
|
|
40049
|
+
writeFileSync5(o.out.replace(/\.html?$/i, "") + ".json", JSON.stringify(signed, null, 2));
|
|
39604
40050
|
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
40051
|
`);
|
|
39606
40052
|
});
|
|
39607
40053
|
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(
|
|
39609
|
-
const packs =
|
|
40054
|
+
const list = JSON.parse(readFileSync9(file, "utf8"));
|
|
40055
|
+
const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
|
|
39610
40056
|
const r = await watchAllowlist(list.allowed ?? [], packs);
|
|
39611
40057
|
const mark2 = { unchanged: "\u2713", changed: "\u2717", degraded: "!", unreachable: "?" };
|
|
39612
40058
|
for (const f of r.findings)
|
|
@@ -39616,7 +40062,7 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
39616
40062
|
${r.findings.length} server(s) checked; ${r.alerts} need attention.
|
|
39617
40063
|
`);
|
|
39618
40064
|
if (o.out)
|
|
39619
|
-
|
|
40065
|
+
writeFileSync5(o.out, JSON.stringify(r, null, 2) + "\n");
|
|
39620
40066
|
if (o.webhook && r.alerts) {
|
|
39621
40067
|
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
40068
|
try {
|
|
@@ -39641,29 +40087,29 @@ Assumptions: ${r.assumptions}.
|
|
|
39641
40087
|
`);
|
|
39642
40088
|
});
|
|
39643
40089
|
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(
|
|
40090
|
+
const fleet = JSON.parse(readFileSync9(o.fleet, "utf8"));
|
|
39645
40091
|
const rec = o.receipts.map((f) => {
|
|
39646
|
-
const e = parseReceiptLog(
|
|
40092
|
+
const e = parseReceiptLog(readFileSync9(f, "utf8"));
|
|
39647
40093
|
return { agent: e[0]?.receipt.envelope.caller.agent?.slice(0, 32) ?? f, summary: summariseReceipts(e), verified: verifyReceiptLog(e).ok };
|
|
39648
40094
|
});
|
|
39649
40095
|
const distinctTokens = (fleet.servers ?? []).reduce((a, x) => a + (x.tokens ?? 0), 0);
|
|
39650
40096
|
const roi = roiEstimate({ ...ROI_DEFAULTS, tokensPerTurn: distinctTokens, agents: Number(o.agents), turnsPerDay: Number(o.turnsPerDay), pricePerMTok: Number(o.pricePerMtok), vendorReviews: Number(o.vendorReviews) });
|
|
39651
|
-
|
|
40097
|
+
writeFileSync5(o.out, renderAssessment(o.org, fleet, rec, roi));
|
|
39652
40098
|
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
40099
|
`);
|
|
39654
40100
|
});
|
|
39655
40101
|
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
40102
|
const setups = files.map((f) => {
|
|
39657
|
-
const j = JSON.parse(
|
|
40103
|
+
const j = JSON.parse(readFileSync9(f, "utf8"));
|
|
39658
40104
|
return { machine: j.machine ?? f, servers: j.servers ?? [] };
|
|
39659
40105
|
});
|
|
39660
40106
|
const pol = o.policy ? await loadPolicy(o.policy) : void 0;
|
|
39661
40107
|
const fleet = buildFleet(setups, pol?.policy, pol?.allow);
|
|
39662
40108
|
process.stdout.write(renderFleet(fleet));
|
|
39663
40109
|
if (o.out)
|
|
39664
|
-
|
|
40110
|
+
writeFileSync5(o.out, JSON.stringify(fleet, null, 2) + "\n");
|
|
39665
40111
|
if (o.html)
|
|
39666
|
-
|
|
40112
|
+
writeFileSync5(o.html, fleetHtml(fleet));
|
|
39667
40113
|
exitCode = fleet.nonCompliant ? 1 : 0;
|
|
39668
40114
|
});
|
|
39669
40115
|
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 +40138,138 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
|
|
|
39692
40138
|
`);
|
|
39693
40139
|
}
|
|
39694
40140
|
});
|
|
39695
|
-
program2.command("
|
|
40141
|
+
const org = program2.command("org").description("Organisations: the root of every accountability chain");
|
|
40142
|
+
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) => {
|
|
40143
|
+
const c = organisationRoot({ name: o.name, domain: o.domain, expires: o.expires }, loadOrCreateKey(o.key));
|
|
40144
|
+
writeFileSync5(o.out, JSON.stringify(c, null, 2) + "\n");
|
|
40145
|
+
process.stdout.write(`Organisation ${sanitizeText(o.name, 80)}: ${c.subject.id}. Root credential ${c.id} in ${sanitizeText(o.out)}.
|
|
40146
|
+
`);
|
|
40147
|
+
});
|
|
40148
|
+
const identity = program2.command("identity").description("Identity chains: organisation -> people -> agents");
|
|
40149
|
+
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) => {
|
|
40150
|
+
const subject = o.subject ?? (o.subjectKey ? loadOrCreateKey(o.subjectKey).kid : void 0);
|
|
40151
|
+
if (!subject)
|
|
40152
|
+
throw new Error("Give --subject <did:key> or --subject-key <file>.");
|
|
40153
|
+
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 });
|
|
40154
|
+
writeFileSync5(o.out, JSON.stringify(c, null, 2) + "\n");
|
|
40155
|
+
process.stdout.write(`Issued ${c.id} to ${sanitizeText(o.name, 80)} (${o.type}). Chain: ${verifyChain(c).path.join(" -> ")}
|
|
40156
|
+
`);
|
|
40157
|
+
});
|
|
40158
|
+
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) => {
|
|
40159
|
+
const v = verifyChain(JSON.parse(readFileSync9(f, "utf8")), { revoked: o.revoked ? JSON.parse(readFileSync9(o.revoked, "utf8")) : [] });
|
|
40160
|
+
process.stdout.write(v.valid ? `\u2713 ${v.path.join(" -> ")}: accountable organisation ${v.organisation}
|
|
40161
|
+
` : `\u2717 ${v.reason}
|
|
40162
|
+
`);
|
|
40163
|
+
exitCode = v.valid ? 0 : 1;
|
|
40164
|
+
});
|
|
40165
|
+
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) => {
|
|
40166
|
+
const orphans = findOrphans(fs.map((f) => JSON.parse(readFileSync9(f, "utf8"))), { revoked: o.revoked ? JSON.parse(readFileSync9(o.revoked, "utf8")) : [] });
|
|
40167
|
+
for (const x of orphans)
|
|
40168
|
+
process.stdout.write(`\u2717 ${sanitizeText(x.agent, 80)} (${x.id}): ${x.reason}
|
|
40169
|
+
`);
|
|
40170
|
+
process.stdout.write(`${orphans.length} orphaned agent(s).
|
|
40171
|
+
`);
|
|
40172
|
+
exitCode = orphans.length ? 1 : 0;
|
|
40173
|
+
});
|
|
40174
|
+
const manifest = program2.command("manifest").description("What a server offers, signed by its publisher");
|
|
40175
|
+
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) => {
|
|
40176
|
+
const target = parseTarget(parts);
|
|
40177
|
+
const packs = existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
|
|
40178
|
+
let tools = [];
|
|
40179
|
+
const r = await runTrustCheck(target, { packs, onTools: (t) => {
|
|
40180
|
+
tools = t;
|
|
40181
|
+
} });
|
|
40182
|
+
const perTool = Object.fromEntries(o.rate.map((x) => {
|
|
40183
|
+
const [t, n] = x.split("=");
|
|
40184
|
+
return [t, Number(n)];
|
|
40185
|
+
}));
|
|
40186
|
+
const m = buildManifest({
|
|
40187
|
+
publisher: { name: o.publisher, ...o.domain ? { domain: o.domain } : {} },
|
|
40188
|
+
server: { name: String(r.target.serverInfo?.["name"] ?? "server"), version: String(r.target.serverInfo?.["version"] ?? ""), toolsFingerprint: r.target.toolsFingerprint },
|
|
40189
|
+
tools,
|
|
40190
|
+
rates: { perCall: Number(o.perCall), ...o.rate.length ? { perTool } : {} },
|
|
40191
|
+
quality: { trustGrade: r.grade ?? null, readinessGrade: r.readiness?.grade ?? null, riskTier: r.riskTier?.tier }
|
|
40192
|
+
}, loadOrCreateKey(o.key));
|
|
40193
|
+
writeFileSync5(o.out, JSON.stringify(m, null, 2) + "\n");
|
|
40194
|
+
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 ?? "-"}.
|
|
40195
|
+
`);
|
|
40196
|
+
});
|
|
40197
|
+
const catalog = program2.command("catalog").description("A catalogue of signed manifests, searchable by intent");
|
|
40198
|
+
catalog.command("add").argument("<manifest>").option("--catalog <file>", "catalogue file", "saktum-catalog.json").action((f, o) => {
|
|
40199
|
+
const m = JSON.parse(readFileSync9(f, "utf8"));
|
|
40200
|
+
if (!verifyDocument(m).valid)
|
|
40201
|
+
throw new Error("The manifest's signature is not valid.");
|
|
40202
|
+
const c = existsSync7(o.catalog) ? JSON.parse(readFileSync9(o.catalog, "utf8")) : [];
|
|
40203
|
+
writeFileSync5(o.catalog, JSON.stringify([...c.filter((x) => x.server.name !== m.server.name || x.publisher.id !== m.publisher.id), m], null, 2) + "\n");
|
|
40204
|
+
process.stdout.write(`Added ${sanitizeText(m.server.name, 80)} by ${sanitizeText(m.publisher.name, 80)} to ${sanitizeText(o.catalog)}.
|
|
40205
|
+
`);
|
|
40206
|
+
});
|
|
40207
|
+
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) => {
|
|
40208
|
+
const res = searchCatalogue(JSON.parse(readFileSync9(o.catalog, "utf8")), q.join(" "), { maxRisk: o.maxRisk });
|
|
40209
|
+
for (const r of res.slice(0, 10))
|
|
40210
|
+
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(", ")}
|
|
40211
|
+
`);
|
|
40212
|
+
if (!res.length)
|
|
40213
|
+
process.stdout.write("No match.\n");
|
|
40214
|
+
});
|
|
40215
|
+
const agreement = program2.command("agreement").description("Agreements between providers and invokers (smart contracts as signed documents)");
|
|
40216
|
+
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) => {
|
|
40217
|
+
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));
|
|
40218
|
+
writeFileSync5(o.out, JSON.stringify(a, null, 2) + "\n");
|
|
40219
|
+
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>
|
|
40220
|
+
`);
|
|
40221
|
+
});
|
|
40222
|
+
agreement.command("accept").argument("<agreement>").requiredOption("--key <path>", "the invoker's key").action((f, o) => {
|
|
40223
|
+
const a = acceptAgreement(JSON.parse(readFileSync9(f, "utf8")), loadOrCreateKey(o.key));
|
|
40224
|
+
writeFileSync5(f, JSON.stringify(a, null, 2) + "\n");
|
|
40225
|
+
process.stdout.write(`Accepted ${a.id}: signed by both parties.
|
|
40226
|
+
`);
|
|
40227
|
+
});
|
|
40228
|
+
agreement.command("verify").argument("<agreement>").action((f) => {
|
|
40229
|
+
const a = JSON.parse(readFileSync9(f, "utf8"));
|
|
40230
|
+
const v = verifyAgreement(a);
|
|
40231
|
+
process.stdout.write(v.valid ? `\u2713 ${a.id}: ${sanitizeText(a.provider.name, 80)} and ${sanitizeText(a.invoker.name, 80)}, until ${a.validUntil}.
|
|
40232
|
+
` : `\u2717 ${v.reason}
|
|
40233
|
+
`);
|
|
40234
|
+
exitCode = v.valid ? 0 : 1;
|
|
40235
|
+
});
|
|
40236
|
+
const wallet = program2.command("wallet").description("Prepaid tokens (bought outside Saktum; no money is handled here)");
|
|
40237
|
+
wallet.command("topup").requiredOption("--account <id>").requiredOption("--tokens <n>").option("--wallet <file>", "wallet file", "saktum-wallet.json").action((o) => {
|
|
40238
|
+
process.stdout.write(`Balance of ${sanitizeText(o.account, 80)}: ${topUp(o.wallet, o.account, Number(o.tokens))} tokens.
|
|
40239
|
+
`);
|
|
40240
|
+
});
|
|
40241
|
+
wallet.command("balance").requiredOption("--account <id>").option("--wallet <file>", "wallet file", "saktum-wallet.json").action((o) => {
|
|
40242
|
+
process.stdout.write(`${walletBalance(o.wallet, o.account)} tokens
|
|
40243
|
+
`);
|
|
40244
|
+
});
|
|
40245
|
+
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) => {
|
|
40246
|
+
const { homedir: homedir2 } = await import("node:os");
|
|
40247
|
+
const { join: join6 } = await import("node:path");
|
|
40248
|
+
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);
|
|
40249
|
+
for (const l of st.lines)
|
|
40250
|
+
process.stdout.write(`${sanitizeText(l.tool, 60).padEnd(24)} ${String(l.calls).padStart(5)} calls ${String(l.tokens).padStart(7)} tokens
|
|
40251
|
+
`);
|
|
40252
|
+
process.stdout.write(`Total: ${st.totalTokens} tokens
|
|
40253
|
+
`);
|
|
40254
|
+
if (o.out)
|
|
40255
|
+
writeFileSync5(o.out, JSON.stringify(st, null, 2) + "\n");
|
|
40256
|
+
});
|
|
40257
|
+
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) => {
|
|
40258
|
+
const { homedir: homedir2 } = await import("node:os");
|
|
40259
|
+
const { join: join6 } = await import("node:path");
|
|
40260
|
+
const k = kpis(parseReceiptLog(readFileSync9(f ?? join6(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), o);
|
|
40261
|
+
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
|
|
40262
|
+
`);
|
|
40263
|
+
process.stdout.write(`By outcome: ${k.byOutcome.map(([c, n]) => `${c} ${n}`).join(", ")}
|
|
40264
|
+
By tool: ${k.byTool.map(([c, n]) => `${c} ${n}`).join(", ")}
|
|
40265
|
+
`);
|
|
40266
|
+
});
|
|
40267
|
+
program2.command("bounty").description("Bounties (contract only for now)").command("validate").argument("<file>").action((f) => {
|
|
40268
|
+
const ok = compileContract("bounty.schema.json")(JSON.parse(readFileSync9(f, "utf8")));
|
|
40269
|
+
process.stdout.write(ok ? "\u2713 Valid bounty document.\n" : "\u2717 Not a valid bounty document.\n");
|
|
40270
|
+
exitCode = ok ? 0 : 1;
|
|
40271
|
+
});
|
|
40272
|
+
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
40273
|
const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
|
|
39697
40274
|
await runDemo2(o.out, (l) => process.stdout.write(l + "\n"), o.story);
|
|
39698
40275
|
});
|
|
@@ -39701,17 +40278,17 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
|
|
|
39701
40278
|
await startDemoServer2(o.story);
|
|
39702
40279
|
});
|
|
39703
40280
|
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) :
|
|
40281
|
+
const packs = o.packs ? loadPackDir(o.packs) : existsSync7(bundledPacks) ? loadPackDir(bundledPacks) : loadEmbeddedPacks();
|
|
39705
40282
|
const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_mcp_server(), mcp_server_exports));
|
|
39706
40283
|
await startMcpServer2(packs);
|
|
39707
40284
|
});
|
|
39708
40285
|
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(
|
|
40286
|
+
const doc = JSON.parse(readFileSync9(file, "utf8"));
|
|
39710
40287
|
const v = verifyDocument(doc);
|
|
39711
40288
|
if (!v.valid)
|
|
39712
40289
|
throw new Error(`The result's signature is not valid (${v.reason}); attestations are built only from unaltered signed results.`);
|
|
39713
40290
|
const att = signDocument(buildAttestation(doc), loadOrCreateKey(o.key));
|
|
39714
|
-
|
|
40291
|
+
writeFileSync5(o.out, JSON.stringify(att, null, 2) + "\n");
|
|
39715
40292
|
const c = att.claims, colour = (g) => ({ A: "2e7d32", B: "558b2f", C: "f9a825", D: "ef6c00", F: "c62828" })[g ?? ""] ?? "757575";
|
|
39716
40293
|
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
40294
|
Anyone can check it: npx saktum verify ${sanitizeText(o.out)}
|
|
@@ -39723,20 +40300,20 @@ README badge:
|
|
|
39723
40300
|
const key = loadOrCreateKey(o.key);
|
|
39724
40301
|
const cred = attestationToCredential(att, key.kid);
|
|
39725
40302
|
const base = o.out.replace(/\.json$/i, "");
|
|
39726
|
-
|
|
39727
|
-
|
|
40303
|
+
writeFileSync5(`${base}.vc.jwt`, signCredentialJwt(cred, key) + "\n");
|
|
40304
|
+
writeFileSync5(`${base}.vc.json`, JSON.stringify(cred, null, 2) + "\n");
|
|
39728
40305
|
process.stdout.write(`
|
|
39729
40306
|
W3C Verifiable Credential: ${sanitizeText(base)}.vc.jwt (check it: npx saktum vc verify ${sanitizeText(base)}.vc.jwt)
|
|
39730
40307
|
`);
|
|
39731
40308
|
}
|
|
39732
40309
|
if (o.publish) {
|
|
39733
|
-
const
|
|
40310
|
+
const body2 = `Publishing a signed Saktum attestation to the public trust ledger. The bot verifies the signature and appends it.
|
|
39734
40311
|
|
|
39735
40312
|
\`\`\`json
|
|
39736
40313
|
${JSON.stringify(att)}
|
|
39737
40314
|
\`\`\`
|
|
39738
40315
|
`;
|
|
39739
|
-
const url2 = `https://github.com/soodhere/saktum-index/issues/new?title=${encodeURIComponent(`Attest: ${att.subject.server}`)}&body=${encodeURIComponent(
|
|
40316
|
+
const url2 = `https://github.com/soodhere/saktum-index/issues/new?title=${encodeURIComponent(`Attest: ${att.subject.server}`)}&body=${encodeURIComponent(body2)}`;
|
|
39740
40317
|
process.stdout.write(`
|
|
39741
40318
|
Publish to the public trust ledger (opens a pre-filled GitHub issue; anyone can then verify it):
|
|
39742
40319
|
${url2}
|
|
@@ -39749,7 +40326,7 @@ ${url2}
|
|
|
39749
40326
|
exitCode = r.code;
|
|
39750
40327
|
});
|
|
39751
40328
|
program2.command("verify").description("Verify a signed Saktum Check result").argument("<file>").action((file) => {
|
|
39752
|
-
const doc = JSON.parse(
|
|
40329
|
+
const doc = JSON.parse(readFileSync9(file, "utf8"));
|
|
39753
40330
|
const validate2 = compileContract("result.schema.json");
|
|
39754
40331
|
if (!validate2(doc)) {
|
|
39755
40332
|
process.stdout.write(`Invalid result format: ${JSON.stringify(validate2.errors?.slice(0, 2))}
|