saktum 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -1
- package/package.json +1 -1
- package/saktum.mjs +369 -61
package/README.md
CHANGED
|
@@ -11,6 +11,27 @@ npx saktum check https://your-server.example/mcp # a remote server (sign-in
|
|
|
11
11
|
|
|
12
12
|
Runs on your machine. Nothing is uploaded. Your own environment variables are never passed to the server.
|
|
13
13
|
|
|
14
|
+
## Guardian-grade (v0.15)
|
|
15
|
+
|
|
16
|
+
Saktum is the deterministic, evidence-producing guardian for AI agents:
|
|
17
|
+
- **Permissions follow the person:** `proxy --on-behalf-of user.json`; the agent's effective permissions are the
|
|
18
|
+
intersection of its own and the user's, and every receipt names the user.
|
|
19
|
+
- **Steer, don't stop:** every refusal carries machine-readable guidance (`_meta["io.saktum/guidance"]`: permitted tools
|
|
20
|
+
and values, the rule, the approval to request, whether to retry). When the agent corrects course, its receipt is
|
|
21
|
+
flagged `self-corrected`; `saktum kpi` reports self-corrections and escalations.
|
|
22
|
+
- **Signed, change-controlled policies:** `saktum policy sign` (repeat for a two-person rule), `saktum policy verify`;
|
|
23
|
+
a signature file next to a policy is always verified, and `SAKTUM_POLICY_APPROVERS` / `SAKTUM_POLICY_MIN` require
|
|
24
|
+
named approvers. Tampered or unsigned policies are refused.
|
|
25
|
+
- **Deployment gate:** `saktum agents scan --gate` fails CI when an agent lacks an accountable owner, an operator, a
|
|
26
|
+
valid mandate or tier-appropriate controls.
|
|
27
|
+
- **Evidence package on demand:** `saktum evidence --package audit/ --receipts logs/*.jsonl --agents-dir agents/ --policy saktum-policy.yaml`.
|
|
28
|
+
- **Stop, then restart only with a human:** `saktum agent reinstate m.json --approver "Dana (CISO)" --evidence "INC-4411 fixed"`, signed
|
|
29
|
+
by the owner or operator; until then the revocation holds, including in the receipt chain.
|
|
30
|
+
- **Enforcement you can show:** `saktum receipts enforcement receipts.jsonl` reports, per decision, that it was made before the action
|
|
31
|
+
(by construction: the proxy forwards only after an allow).
|
|
32
|
+
- **Multi-agent:** `proxy --handoff-from <receipt>` records who handed the work over, and `saktum receipts trace` follows handoffs
|
|
33
|
+
across agents' logs; `proxy --cluster cluster.json` enforces limits shared by several agents (for example a desk's daily refund total).
|
|
34
|
+
|
|
14
35
|
## Industry-ready governance (v0.14)
|
|
15
36
|
|
|
16
37
|
- **Resource-scoped credentials:** `identity issue --where legal.case_id=C-7731` limits an agent to the cases (or
|
|
@@ -266,7 +287,7 @@ servers not on your allowlist, and the weakest grades. Configured secrets are ne
|
|
|
266
287
|
|
|
267
288
|
```yaml
|
|
268
289
|
- uses: actions/checkout@v4
|
|
269
|
-
- uses: soodhere/saktum-check@v0.
|
|
290
|
+
- uses: soodhere/saktum-check@v0.15.0
|
|
270
291
|
with:
|
|
271
292
|
target: "-- node build/index.js" # or an https URL
|
|
272
293
|
args: "--active --tests saktum.tests.yaml" # optional; --active only for your own server
|
package/package.json
CHANGED
package/saktum.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Saktum Check 0.
|
|
2
|
+
// Saktum Check 0.15.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
|
|
3
3
|
import { createRequire as __saktumCreateRequire } from "node:module";
|
|
4
4
|
const require = __saktumCreateRequire(import.meta.url);
|
|
5
5
|
var __create = Object.create;
|
|
@@ -34083,7 +34083,7 @@ var init_dist3 = __esm({
|
|
|
34083
34083
|
init_stdio2();
|
|
34084
34084
|
init_streamableHttp();
|
|
34085
34085
|
init_types2();
|
|
34086
|
-
USER_AGENT = "saktum-check/0.
|
|
34086
|
+
USER_AGENT = "saktum-check/0.15.0 (+https://saktum.dev/check)";
|
|
34087
34087
|
LIMITS = { requestTimeoutMs: 1e4, connectTimeoutMs: 6e4, maxResponseChars: 5e6 };
|
|
34088
34088
|
LimitError = class extends Error {
|
|
34089
34089
|
};
|
|
@@ -34121,7 +34121,7 @@ var init_dist3 = __esm({
|
|
|
34121
34121
|
jsonrpc: "2.0",
|
|
34122
34122
|
id: 1,
|
|
34123
34123
|
method: "initialize",
|
|
34124
|
-
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.
|
|
34124
|
+
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.15.0" } }
|
|
34125
34125
|
});
|
|
34126
34126
|
}
|
|
34127
34127
|
});
|
|
@@ -35493,7 +35493,7 @@ var init_engine = __esm({
|
|
|
35493
35493
|
init_runner();
|
|
35494
35494
|
init_safe();
|
|
35495
35495
|
init_scoring();
|
|
35496
|
-
ENGINE_VERSION = "0.
|
|
35496
|
+
ENGINE_VERSION = "0.15.0";
|
|
35497
35497
|
UNKNOWN_TOOL = "saktum_trust_check_no_such_tool";
|
|
35498
35498
|
INVALID_TOKEN = "saktum-check-deliberately-invalid-token";
|
|
35499
35499
|
baseOf = (pack, check) => ({
|
|
@@ -36520,6 +36520,29 @@ function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS(), key) {
|
|
|
36520
36520
|
_write(path, JSON.stringify(r, null, 2) + "\n");
|
|
36521
36521
|
return r.revoked.find((x) => x.mandate === d);
|
|
36522
36522
|
}
|
|
36523
|
+
function reinstateMandate(m, key, approver, evidence, path = DEFAULT_REVOCATIONS()) {
|
|
36524
|
+
if (!approver.trim() || !evidence.trim())
|
|
36525
|
+
throw new Error("A reinstatement needs a named human approver and evidence.");
|
|
36526
|
+
const r = readRevocations(path);
|
|
36527
|
+
const op = m.operatorCountersign?.signature?.kid;
|
|
36528
|
+
if (key.kid !== m.owner.id && key.kid !== op)
|
|
36529
|
+
throw new Error("Only the mandate's owner or operator can reinstate it.");
|
|
36530
|
+
const doc = signDocument({ reinstatementFormat: "0.1", mandate: mandateDigest(m), approver: approver.trim(), evidence: evidence.trim(), at: (/* @__PURE__ */ new Date()).toISOString() }, key);
|
|
36531
|
+
(r.reinstated ??= []).push(doc);
|
|
36532
|
+
_mkdir(_dirname(path), { recursive: true });
|
|
36533
|
+
_write(path, JSON.stringify(r, null, 2) + "\n");
|
|
36534
|
+
return doc;
|
|
36535
|
+
}
|
|
36536
|
+
function reinstatementOf(m, path = DEFAULT_REVOCATIONS()) {
|
|
36537
|
+
const d = mandateDigest(m);
|
|
36538
|
+
const op = m.operatorCountersign?.signature?.kid;
|
|
36539
|
+
return (readRevocations(path).reinstated ?? []).filter((x) => {
|
|
36540
|
+
if (x.mandate !== d)
|
|
36541
|
+
return false;
|
|
36542
|
+
const v = verifyDocument(x);
|
|
36543
|
+
return v.valid && (v.kid === m.owner.id || Boolean(op) && v.kid === op);
|
|
36544
|
+
}).sort((p, q) => p.at.localeCompare(q.at)).pop();
|
|
36545
|
+
}
|
|
36523
36546
|
function revocationOf(m, path = DEFAULT_REVOCATIONS()) {
|
|
36524
36547
|
const d = mandateDigest(m);
|
|
36525
36548
|
const op = m.operatorCountersign?.signature?.kid;
|
|
@@ -37033,6 +37056,8 @@ function kpis(entries, f = {}) {
|
|
|
37033
37056
|
allowed: xs.filter((e) => e.receipt.outcome === "allow").length,
|
|
37034
37057
|
blocked: xs.filter((e) => e.receipt.outcome === "deny").length,
|
|
37035
37058
|
approvals: xs.filter((e) => /approved by/.test(String(e.receipt.reason ?? ""))).length,
|
|
37059
|
+
selfCorrected: xs.filter((e) => e.result.flags?.includes("self-corrected")).length,
|
|
37060
|
+
escalations: xs.filter((e) => e.result.code === "approval-needed").length,
|
|
37036
37061
|
tokens: xs.reduce((n, e) => n + (e.result.metering?.tokens ?? 0), 0),
|
|
37037
37062
|
latencyP50: pct(50),
|
|
37038
37063
|
latencyP95: pct(95),
|
|
@@ -37296,6 +37321,44 @@ async function verifyDomain(domain, did, o = {}) {
|
|
|
37296
37321
|
}
|
|
37297
37322
|
return { verified: false };
|
|
37298
37323
|
}
|
|
37324
|
+
function signPolicy(text2, key) {
|
|
37325
|
+
return signDocument({ policySignatureFormat: "0.1", digest: sha256Tag(text2), at: (/* @__PURE__ */ new Date()).toISOString() }, key);
|
|
37326
|
+
}
|
|
37327
|
+
function verifyPolicy(text2, sigs, o = {}) {
|
|
37328
|
+
const d = sha256Tag(text2);
|
|
37329
|
+
const signers = [...new Set(sigs.flatMap((s) => {
|
|
37330
|
+
const x = s;
|
|
37331
|
+
const v = verifyDocument(s);
|
|
37332
|
+
return v.valid && x.digest === d ? [v.kid] : [];
|
|
37333
|
+
}))].filter((k) => !o.approvers?.length || o.approvers.includes(k));
|
|
37334
|
+
const need = o.min ?? 1;
|
|
37335
|
+
if (signers.length < need)
|
|
37336
|
+
return { ok: false, signers, reason: sigs.length ? `${signers.length} valid approver signature(s) for this exact policy; ${need} required (was it changed after signing?)` : "the policy is not signed" };
|
|
37337
|
+
return { ok: true, signers };
|
|
37338
|
+
}
|
|
37339
|
+
function intersectScopes(a, b) {
|
|
37340
|
+
const tools = a?.tools && b?.tools ? a.tools.filter((t) => b.tools.includes(t)) : a?.tools ?? b?.tools;
|
|
37341
|
+
const where = {};
|
|
37342
|
+
for (const f of /* @__PURE__ */ new Set([...Object.keys(a?.where ?? {}), ...Object.keys(b?.where ?? {})])) {
|
|
37343
|
+
const x = a?.where?.[f], y = b?.where?.[f];
|
|
37344
|
+
where[f] = x && y ? x.filter((v) => y.includes(v)) : x ?? y;
|
|
37345
|
+
}
|
|
37346
|
+
return { ...tools ? { tools } : {}, ...Object.keys(where).length ? { where } : {} };
|
|
37347
|
+
}
|
|
37348
|
+
function gateAgent(a) {
|
|
37349
|
+
const why = [];
|
|
37350
|
+
if (!a.owner)
|
|
37351
|
+
why.push("no named accountable owner");
|
|
37352
|
+
if (!a.operator || a.operator === "invalid countersignature")
|
|
37353
|
+
why.push(a.operator ? "operator countersignature is invalid" : "no operator countersignature");
|
|
37354
|
+
if (!a.valid)
|
|
37355
|
+
why.push("mandate invalid or expired");
|
|
37356
|
+
if (a.revoked)
|
|
37357
|
+
why.push("mandate revoked");
|
|
37358
|
+
if ((a.riskTier === "R3" || a.riskTier === "R4") && !/^A[3-5]/.test(a.maturity))
|
|
37359
|
+
why.push(`risk ${a.riskTier} without approvals or limits (maturity ${a.maturity})`);
|
|
37360
|
+
return why;
|
|
37361
|
+
}
|
|
37299
37362
|
var keyedDigest, revokedInChain, approvalUsedInChain, cpCore;
|
|
37300
37363
|
var init_trust = __esm({
|
|
37301
37364
|
"packages/testkit-core/dist/trust.js"() {
|
|
@@ -37554,8 +37617,10 @@ __export(dist_exports, {
|
|
|
37554
37617
|
findOrphans: () => findOrphans,
|
|
37555
37618
|
findSecret: () => findSecret,
|
|
37556
37619
|
fleetHtml: () => fleetHtml,
|
|
37620
|
+
gateAgent: () => gateAgent,
|
|
37557
37621
|
gradeFor: () => gradeFor,
|
|
37558
37622
|
hasIntent: () => hasIntent,
|
|
37623
|
+
intersectScopes: () => intersectScopes,
|
|
37559
37624
|
invalidArgProblems: () => invalidArgProblems,
|
|
37560
37625
|
invalidArgsFor: () => invalidArgsFor,
|
|
37561
37626
|
issueCredential: () => issueCredential,
|
|
@@ -37592,6 +37657,8 @@ __export(dist_exports, {
|
|
|
37592
37657
|
recordPending: () => recordPending,
|
|
37593
37658
|
redactCommand: () => redactCommand,
|
|
37594
37659
|
redactUrl: () => redactUrl,
|
|
37660
|
+
reinstateMandate: () => reinstateMandate,
|
|
37661
|
+
reinstatementOf: () => reinstatementOf,
|
|
37595
37662
|
renderFix: () => renderFix,
|
|
37596
37663
|
renderFleet: () => renderFleet,
|
|
37597
37664
|
renderSetup: () => renderSetup,
|
|
@@ -37614,6 +37681,7 @@ __export(dist_exports, {
|
|
|
37614
37681
|
searchCatalogue: () => searchCatalogue,
|
|
37615
37682
|
semanticValues: () => semanticValues,
|
|
37616
37683
|
signCredentialJwt: () => signCredentialJwt,
|
|
37684
|
+
signPolicy: () => signPolicy,
|
|
37617
37685
|
signReceipt: () => signReceipt,
|
|
37618
37686
|
signRevocation: () => signRevocation,
|
|
37619
37687
|
sourceFiles: () => sourceFiles,
|
|
@@ -37639,6 +37707,7 @@ __export(dist_exports, {
|
|
|
37639
37707
|
verifyLedger: () => verifyLedger,
|
|
37640
37708
|
verifyPasskeyAssertion: () => verifyPasskeyAssertion,
|
|
37641
37709
|
verifyPasskeyRegistration: () => verifyPasskeyRegistration,
|
|
37710
|
+
verifyPolicy: () => verifyPolicy,
|
|
37642
37711
|
verifyReceipt: () => verifyReceipt,
|
|
37643
37712
|
verifyReceiptLog: () => verifyReceiptLog,
|
|
37644
37713
|
verifyWallet: () => verifyWallet,
|
|
@@ -38365,7 +38434,9 @@ async function runProxy(o) {
|
|
|
38365
38434
|
const bare = !/[\\/]/.test(o.command);
|
|
38366
38435
|
const child = spawn3(o.command, o.args, { stdio: ["pipe", "pipe", "inherit"], shell: process.platform === "win32" && (bare || /\.(cmd|bat)$/i.test(o.command)) });
|
|
38367
38436
|
let service = o.command.split(/[\\/]/).pop() ?? o.command, version2;
|
|
38368
|
-
let remoteRevoked = false, toolsChanged = false;
|
|
38437
|
+
let remoteRevoked = false, toolsChanged = false, lastRefusal = 0;
|
|
38438
|
+
const pendingCluster = /* @__PURE__ */ new Map();
|
|
38439
|
+
let scopeNow;
|
|
38369
38440
|
const pollRevocations = async () => {
|
|
38370
38441
|
if (!o.revocationsUrl || !o.mandate)
|
|
38371
38442
|
return;
|
|
@@ -38444,8 +38515,12 @@ async function runProxy(o) {
|
|
|
38444
38515
|
let rationale;
|
|
38445
38516
|
let metering;
|
|
38446
38517
|
try {
|
|
38447
|
-
const
|
|
38448
|
-
|
|
38518
|
+
const rev0 = o.mandate ? revocationOf(o.mandate, o.revocationsPath) : void 0;
|
|
38519
|
+
const re = o.mandate ? reinstatementOf(o.mandate, o.revocationsPath) : void 0;
|
|
38520
|
+
const rev = rev0 && !(re && re.at > rev0.at) ? rev0 : void 0;
|
|
38521
|
+
const lastChainRevoked = [...history].reverse().find((e) => e.result.code === "revoked")?.receipt.issuedAt;
|
|
38522
|
+
const chainRevoked = Boolean(lastChainRevoked) && !(re && re.at > lastChainRevoked);
|
|
38523
|
+
d = rev ? { allow: false, code: "revoked", reason: `the mandate was revoked on ${rev.at.slice(0, 10)}${rev.reason ? ` (${rev.reason})` : ""}` } : o.mandate && (remoteRevoked && !re || chainRevoked) ? { allow: false, code: "revoked", reason: "the mandate was revoked (recorded in the ledger or in this receipt chain)" } : findSecret(JSON.stringify(args ?? {})) ? { allow: false, code: "secret-in-arguments", reason: `the arguments contain what looks like a secret (${findSecret(JSON.stringify(args ?? {}))}); it was not sent and is not recorded` } : toolsChanged ? { allow: false, code: "tools-changed", reason: "the server's tools differ from the pinned, approved fingerprint" } : o.mandate ? decideCall(o.mandate, { tool, server: service, args, annotations: ann, isMoney, usage: usage() }) : { allow: true, code: "ok", reason: "no mandate: observed" };
|
|
38449
38524
|
if (d.allow && o.mandate && hasIntent(o.mandate)) {
|
|
38450
38525
|
const di = decideIntent(o.mandate, def ?? { name: tool }, args, { server: service });
|
|
38451
38526
|
rationale = di.rationale;
|
|
@@ -38481,20 +38556,31 @@ async function runProxy(o) {
|
|
|
38481
38556
|
const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
|
|
38482
38557
|
if (!vc.valid)
|
|
38483
38558
|
d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
|
|
38484
|
-
else if (
|
|
38485
|
-
d = { allow: false, code: "
|
|
38486
|
-
else
|
|
38487
|
-
const
|
|
38488
|
-
|
|
38489
|
-
|
|
38490
|
-
|
|
38491
|
-
|
|
38492
|
-
|
|
38493
|
-
|
|
38559
|
+
else if (o.agreement && root !== o.agreement.invoker.id)
|
|
38560
|
+
d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
|
|
38561
|
+
else {
|
|
38562
|
+
const uc = o.onBehalfOf ? verifyChain(o.onBehalfOf, { revoked: o.revokedCredentials }) : void 0;
|
|
38563
|
+
if (uc && !uc.valid)
|
|
38564
|
+
d = { allow: false, code: "on-behalf-of", reason: `the user's credential is not valid: ${uc.reason}` };
|
|
38565
|
+
else {
|
|
38566
|
+
const eff = uc ? intersectScopes({ tools: vc.tools, where: vc.where }, { tools: uc.tools, where: uc.where }) : { tools: vc.tools, where: vc.where };
|
|
38567
|
+
const code2 = uc ? "outside-user-permissions" : "outside-credential-scope", who = uc ? `${o.onBehalfOf.subject.name}'s permissions and the agent's credential together cover` : "the agent's credential covers";
|
|
38568
|
+
if (eff.tools && !eff.tools.includes(tool))
|
|
38569
|
+
d = { allow: false, code: code2, reason: `${who} only ${eff.tools.join(", ") || "no tools"}` };
|
|
38570
|
+
else if (eff.where) {
|
|
38571
|
+
const b = bindingsFor(toolDefs.get(tool) ?? { name: tool }).bindings;
|
|
38572
|
+
for (const [arg, field] of Object.entries(b)) {
|
|
38573
|
+
const allowed = eff.where[field];
|
|
38574
|
+
const val = args[arg];
|
|
38575
|
+
if (allowed && val !== void 0 && !allowed.includes(String(val))) {
|
|
38576
|
+
d = { allow: false, code: code2, reason: `${who} ${field} ${allowed.join(", ") || "nothing"} only (got ${String(val)})` };
|
|
38577
|
+
break;
|
|
38578
|
+
}
|
|
38579
|
+
}
|
|
38494
38580
|
}
|
|
38581
|
+
scopeNow = eff;
|
|
38495
38582
|
}
|
|
38496
|
-
}
|
|
38497
|
-
d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
|
|
38583
|
+
}
|
|
38498
38584
|
}
|
|
38499
38585
|
if (d.allow && o.agreement) {
|
|
38500
38586
|
const va = verifyAgreement(o.agreement);
|
|
@@ -38511,13 +38597,60 @@ async function runProxy(o) {
|
|
|
38511
38597
|
} else
|
|
38512
38598
|
metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
|
|
38513
38599
|
}
|
|
38600
|
+
if (d.allow && o.cluster) {
|
|
38601
|
+
const b = bindingsFor(toolDefs.get(tool) ?? { name: tool }).bindings, today2 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
38602
|
+
const rows = (existsSync5(o.cluster.file) ? readFileSync7(o.cluster.file, "utf8") : "").split("\n").filter(Boolean).map((l) => {
|
|
38603
|
+
try {
|
|
38604
|
+
return JSON.parse(l);
|
|
38605
|
+
} catch {
|
|
38606
|
+
return void 0;
|
|
38607
|
+
}
|
|
38608
|
+
}).filter((r) => Boolean(r) && r.at.startsWith(today2));
|
|
38609
|
+
for (const lim of o.cluster.limits) {
|
|
38610
|
+
const arg = Object.entries(b).find(([, f]) => f === lim.field)?.[0];
|
|
38611
|
+
const val = arg ? Number(args[arg]) : NaN;
|
|
38612
|
+
if (!Number.isFinite(val))
|
|
38613
|
+
continue;
|
|
38614
|
+
const used = rows.filter((r) => r.field === lim.field).reduce((n, r) => n + r.value, 0);
|
|
38615
|
+
if (used + val > lim.max) {
|
|
38616
|
+
d = { allow: false, code: "cluster-limit", reason: `${lim.label ?? `the cluster's daily ${lim.field}`} would reach ${used + val} (limit ${lim.max}, already used ${used} across the cluster ${o.cluster.id})` };
|
|
38617
|
+
break;
|
|
38618
|
+
}
|
|
38619
|
+
}
|
|
38620
|
+
if (d.allow)
|
|
38621
|
+
pendingCluster.set(String(msg.id), Object.entries(b).flatMap(([arg, f]) => {
|
|
38622
|
+
const v = Number(args[arg]);
|
|
38623
|
+
return o.cluster.limits.some((l) => l.field === f) && Number.isFinite(v) ? [{ field: f, value: v }] : [];
|
|
38624
|
+
}));
|
|
38625
|
+
}
|
|
38514
38626
|
} catch (err) {
|
|
38515
38627
|
d = { allow: false, code: "error-fail-closed", reason: `the decision could not be completed, so the call is refused (${String(err.message).slice(0, 120)})` };
|
|
38516
38628
|
}
|
|
38517
38629
|
if (!d.allow && (o.enforce || d.code === "error-fail-closed")) {
|
|
38518
38630
|
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.";
|
|
38519
|
-
|
|
38520
|
-
|
|
38631
|
+
const guidance = { code: d.code, retryable: !["revoked", "tools-changed", "error-fail-closed", "on-behalf-of"].includes(d.code) };
|
|
38632
|
+
if (d.code === "not-in-mandate" && o.mandate?.allow?.tools?.length)
|
|
38633
|
+
guidance.allowedTools = o.mandate.allow.tools;
|
|
38634
|
+
if ((d.code === "outside-credential-scope" || d.code === "outside-user-permissions") && scopeNow) {
|
|
38635
|
+
if (scopeNow.tools)
|
|
38636
|
+
guidance.allowedTools = scopeNow.tools;
|
|
38637
|
+
if (scopeNow.where)
|
|
38638
|
+
guidance.allowedValues = scopeNow.where;
|
|
38639
|
+
}
|
|
38640
|
+
if (d.code === "rule-violated")
|
|
38641
|
+
guidance.rule = d.reason;
|
|
38642
|
+
if (d.code === "approval-needed") {
|
|
38643
|
+
const m2 = /approval request ([^\]]+)\]/.exec(d.reason);
|
|
38644
|
+
if (m2)
|
|
38645
|
+
guidance.approval = { requestId: m2[1], how: "ask your user to approve exactly this action, then retry it unchanged" };
|
|
38646
|
+
}
|
|
38647
|
+
if (d.code === "secret-in-arguments")
|
|
38648
|
+
guidance.fix = "remove the secret from the arguments; refer to it by name and let the tool fetch it";
|
|
38649
|
+
lastRefusal = 3;
|
|
38650
|
+
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}${guidance.retryable ? " Adjust the call within the guidance and try again." : ""}` }], _meta: { "io.saktum/guidance": guidance } } }) + "\n");
|
|
38651
|
+
if (lastRefusal > 0)
|
|
38652
|
+
lastRefusal--;
|
|
38653
|
+
record2(tool, argsHash, "deny", d.reason, { status: "blocked", destructive: isDestructive(ann), code: d.code, values: d.code === "secret-in-arguments" ? void 0 : values, ...o.onBehalfOf ? { onBehalfOf: o.onBehalfOf.subject.name } : {}, ...rationale ? { rationale } : {} });
|
|
38521
38654
|
o.log?.(`denied ${tool} (${d.code}): ${d.reason}`);
|
|
38522
38655
|
return;
|
|
38523
38656
|
}
|
|
@@ -38576,14 +38709,25 @@ async function runProxy(o) {
|
|
|
38576
38709
|
const hidden = text2 ? findHiddenInstruction(text2, { broad: true }) : void 0, secret = text2 ? findSecret(text2) : void 0;
|
|
38577
38710
|
const rv = o.mandate?.review;
|
|
38578
38711
|
const sampled = Boolean(rv && !msg.error && (!rv.actions || rv.actions.includes(actionClass(toolDefs.get(c.tool) ?? { name: c.tool }).cls)) && parseInt(sha256Tag(c.argsHash + c.start).slice(7, 15), 16) / 4294967295 < rv.sample);
|
|
38579
|
-
const
|
|
38712
|
+
const cl = pendingCluster.get(String(msg.id));
|
|
38713
|
+
pendingCluster.delete(String(msg.id));
|
|
38714
|
+
if (cl?.length && o.cluster && !msg.error && !msg.result?.isError) {
|
|
38715
|
+
try {
|
|
38716
|
+
appendFileSync(o.cluster.file, cl.map((x) => JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), cluster: o.cluster.id, agent: o.mandate?.agent.name ?? "", ...x })).join("\n") + "\n");
|
|
38717
|
+
} catch {
|
|
38718
|
+
}
|
|
38719
|
+
}
|
|
38720
|
+
const corrected = lastRefusal > 0 && !msg.error && !/approved by/.test(c.reason);
|
|
38721
|
+
if (!msg.error)
|
|
38722
|
+
lastRefusal = 0;
|
|
38723
|
+
const flags = [...hidden ? ["hidden-instruction-in-result"] : [], ...secret ? [`secret-in-result:${secret}`] : [], ...sampled ? ["review-sampled"] : [], ...corrected ? ["self-corrected"] : []];
|
|
38580
38724
|
if (flags.length)
|
|
38581
38725
|
o.log?.(`${c.tool}: result flagged (${flags.join(", ")})`);
|
|
38582
38726
|
if ((hidden || secret) && o.quarantineResults) {
|
|
38583
38727
|
msg.result = { content: [{ type: "text", text: `Withheld by Saktum: this tool's result contained ${hidden ? "instructions aimed at the agent" : "what looks like a secret"}. Ask the user before continuing.` }], isError: true };
|
|
38584
38728
|
line = JSON.stringify(msg);
|
|
38585
38729
|
}
|
|
38586
|
-
record2(c.tool, c.argsHash, msg.error ? "error" : "allow", c.reason + (hidden || secret ? ` [result ${o.quarantineResults ? "withheld" : "flagged"}: ${flags.filter((f) => f !== "review-sampled").join(", ")}]` : "") + (sampled ? " [sampled for human review]" : ""), { status, latencyMs: Date.now() - c.start, destructive: c.destructive, code: c.code, values: c.values, outputDigest: digest(msg.result ?? msg.error ?? null), ...flags.length ? { flags } : {}, ...c.rationale ? { rationale: c.rationale } : {}, ...c.metering ? { metering: c.metering } : {} });
|
|
38730
|
+
record2(c.tool, c.argsHash, msg.error ? "error" : "allow", c.reason + (hidden || secret ? ` [result ${o.quarantineResults ? "withheld" : "flagged"}: ${flags.filter((f) => f !== "review-sampled").join(", ")}]` : "") + (sampled ? " [sampled for human review]" : ""), { status, latencyMs: Date.now() - c.start, destructive: c.destructive, code: c.code, values: c.values, outputDigest: digest(msg.result ?? msg.error ?? null), ...flags.length ? { flags } : {}, ...o.onBehalfOf ? { onBehalfOf: o.onBehalfOf.subject.name } : {}, ...o.handoffFrom ? { handoffFrom: o.handoffFrom } : {}, ...o.cluster ? { cluster: o.cluster.id } : {}, ...c.rationale ? { rationale: c.rationale } : {}, ...c.metering ? { metering: c.metering } : {} });
|
|
38587
38731
|
}
|
|
38588
38732
|
process.stdout.write(line + "\n");
|
|
38589
38733
|
});
|
|
@@ -39421,6 +39565,16 @@ async function startDemoServer(story = "autonomy") {
|
|
|
39421
39565
|
await server.connect(new StdioServerTransport());
|
|
39422
39566
|
await closed;
|
|
39423
39567
|
}
|
|
39568
|
+
async function lastReceipt(rf) {
|
|
39569
|
+
for (let i = 0; i < 4; i++) {
|
|
39570
|
+
try {
|
|
39571
|
+
return parseReceiptLog(readFileSync8(rf, "utf8")).pop();
|
|
39572
|
+
} catch {
|
|
39573
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
39574
|
+
}
|
|
39575
|
+
}
|
|
39576
|
+
return void 0;
|
|
39577
|
+
}
|
|
39424
39578
|
async function governedSession(open2) {
|
|
39425
39579
|
const start = async () => {
|
|
39426
39580
|
try {
|
|
@@ -39488,31 +39642,39 @@ async function runStory(dir, st, owner, log) {
|
|
|
39488
39642
|
try {
|
|
39489
39643
|
let lastRid = "";
|
|
39490
39644
|
for (const step of st.steps) {
|
|
39491
|
-
|
|
39492
|
-
|
|
39493
|
-
|
|
39494
|
-
|
|
39495
|
-
|
|
39496
|
-
|
|
39497
|
-
|
|
39498
|
-
|
|
39499
|
-
|
|
39500
|
-
|
|
39645
|
+
try {
|
|
39646
|
+
if (step.approveLast) {
|
|
39647
|
+
const { approveAction: approveAction2 } = await Promise.resolve().then(() => (init_dist4(), dist_exports));
|
|
39648
|
+
approveAction2(cm, lastRid, owner, 60, join6(dir, "approvals.json"));
|
|
39649
|
+
log(` \u270D ${step.say}: ${lastRid}`);
|
|
39650
|
+
continue;
|
|
39651
|
+
}
|
|
39652
|
+
const o = await call(step.tool, step.args);
|
|
39653
|
+
if (o.kind === "error" && "message" in o) {
|
|
39654
|
+
log(` ! ${step.say}: could not complete on this machine (${o.message}); continuing`);
|
|
39655
|
+
continue;
|
|
39656
|
+
}
|
|
39657
|
+
const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
|
|
39658
|
+
const rid = /\[approval request (apr_[0-9a-f]+)\]/.exec(txt);
|
|
39659
|
+
if (rid)
|
|
39660
|
+
lastRid = rid[1];
|
|
39661
|
+
const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)( \[approval request [^\]]+\])?\.( Ask| Tell|$)/.exec(txt);
|
|
39662
|
+
const lastR = await lastReceipt(rf);
|
|
39663
|
+
log(blocked ? ` \u26D4 ${step.say}: ${blocked[1]}: ${blocked[2]}` : ` \u2713 ${step.say}${/approved by/.test(String(lastR?.receipt.reason ?? "")) ? ": approved by you, once" : ""}`);
|
|
39664
|
+
const last = lastR;
|
|
39665
|
+
for (const p of last?.result.rationale?.preferences ?? [])
|
|
39666
|
+
if (!blocked)
|
|
39667
|
+
log(` \xB7 ${p}`);
|
|
39668
|
+
for (const f of last?.result.rationale?.flags ?? [])
|
|
39669
|
+
if (!blocked && !/differs from the stated preference/.test(f))
|
|
39670
|
+
log(` ! ${f}`);
|
|
39671
|
+
if (!blocked && lastR?.result.flags?.includes("self-corrected"))
|
|
39672
|
+
log(` \u21BB corrected course after Saktum's guidance (no person needed)`);
|
|
39673
|
+
} catch (e) {
|
|
39674
|
+
log(` ! ${step.say}: ${String(e.message ?? e).slice(0, 160)}; continuing`);
|
|
39675
|
+
process.stderr.write(`demo step failed: ${e.stack ?? e}
|
|
39676
|
+
`);
|
|
39501
39677
|
}
|
|
39502
|
-
const txt = o.kind === "result" ? o.content.map((c) => c.text ?? "").join(" ") : o.kind;
|
|
39503
|
-
const rid = /\[approval request (apr_[0-9a-f]+)\]/.exec(txt);
|
|
39504
|
-
if (rid)
|
|
39505
|
-
lastRid = rid[1];
|
|
39506
|
-
const blocked = /^Blocked by Saktum \(([^)]+)\): (.+?)( \[approval request [^\]]+\])?\.( Ask| Tell|$)/.exec(txt);
|
|
39507
|
-
const lastR = parseReceiptLog(readFileSync8(rf, "utf8")).pop();
|
|
39508
|
-
log(blocked ? ` \u26D4 ${step.say}: ${blocked[1]}: ${blocked[2]}` : ` \u2713 ${step.say}${/approved by/.test(String(lastR?.receipt.reason ?? "")) ? ": approved by you, once" : ""}`);
|
|
39509
|
-
const last = parseReceiptLog(readFileSync8(rf, "utf8")).pop();
|
|
39510
|
-
for (const p of last?.result.rationale?.preferences ?? [])
|
|
39511
|
-
if (!blocked)
|
|
39512
|
-
log(` \xB7 ${p}`);
|
|
39513
|
-
for (const f of last?.result.rationale?.flags ?? [])
|
|
39514
|
-
if (!blocked && !/differs from the stated preference/.test(f))
|
|
39515
|
-
log(` ! ${f}`);
|
|
39516
39678
|
}
|
|
39517
39679
|
} finally {
|
|
39518
39680
|
await gs.close();
|
|
@@ -39939,6 +40101,7 @@ var init_demo = __esm({
|
|
|
39939
40101
|
}, steps: [
|
|
39940
40102
|
{ tool: "read_case_document", args: { case_id: "C-7731", document_type: "passport" }, say: "reads the passport on its case" },
|
|
39941
40103
|
{ tool: "read_case_document", args: { case_id: "C-9120", document_type: "passport" }, say: "tries to read a passport from another case" },
|
|
40104
|
+
{ tool: "read_case_document", args: { case_id: "C-7731", document_type: "reference_letter" }, say: "reads the guidance and returns to its own case" },
|
|
39942
40105
|
{ tool: "update_profile_field", args: { case_id: "C-7731", field: "passport_expiry", value: "2031-04-30" }, say: "fills the profile from the passport (sampled for lawyer review)" },
|
|
39943
40106
|
{ tool: "send_client_message", args: { case_id: "C-7731", body: "Your language test is still valid." }, say: "tries to message the client without citing a source" },
|
|
39944
40107
|
{ tool: "send_client_message", args: { case_id: "C-7731", body: "Your language test is valid for two years from the test date.", citation: "IRCC language test validity, rule pack ee-2026.11" }, say: "drafts the message with its citation" },
|
|
@@ -40203,7 +40366,7 @@ function keyLine(stderr) {
|
|
|
40203
40366
|
const lines = stderr.split("\n").map((l) => l.trim()).filter((l) => /[a-z]{3}/i.test(l));
|
|
40204
40367
|
return [...lines].reverse().find((l) => /error|exception|failed|not found|missing|denied|refused|invalid|cannot|unable/i.test(l)) ?? lines[lines.length - 1] ?? "";
|
|
40205
40368
|
}
|
|
40206
|
-
async function startProbe(t) {
|
|
40369
|
+
async function startProbe(t, waitMs = 4e3) {
|
|
40207
40370
|
return new Promise((resolve) => {
|
|
40208
40371
|
let stderr = "";
|
|
40209
40372
|
let done = false;
|
|
@@ -40227,7 +40390,7 @@ ${e.message}`;
|
|
|
40227
40390
|
finish2(true, null);
|
|
40228
40391
|
});
|
|
40229
40392
|
child.on("exit", (code) => finish2(true, code));
|
|
40230
|
-
const timer = setTimeout(() => finish2(false, null),
|
|
40393
|
+
const timer = setTimeout(() => finish2(false, null), waitMs);
|
|
40231
40394
|
});
|
|
40232
40395
|
}
|
|
40233
40396
|
async function runDoctor(targetParts, env = [], headers = []) {
|
|
@@ -40278,11 +40441,23 @@ async function runDoctor(targetParts, env = [], headers = []) {
|
|
|
40278
40441
|
} catch (e) {
|
|
40279
40442
|
const msg = e.message;
|
|
40280
40443
|
const timeout = /timed out/i.test(msg);
|
|
40281
|
-
|
|
40282
|
-
|
|
40283
|
-
|
|
40284
|
-
|
|
40285
|
-
|
|
40444
|
+
let diagnosed = false;
|
|
40445
|
+
if (target.kind === "stdio" && /Connection closed/i.test(msg)) {
|
|
40446
|
+
const p2 = await startProbe(target, 15e3);
|
|
40447
|
+
if (p2.exited) {
|
|
40448
|
+
const i = lines.findIndex((l) => l.label === "The server starts and stays up");
|
|
40449
|
+
if (i >= 0)
|
|
40450
|
+
lines.splice(i, 1);
|
|
40451
|
+
lines.push({ ok: false, label: `The server exited during start-up${p2.code !== null ? ` (code ${p2.code})` : ""}`, hint: [...hintsFrom(p2.stderr), keyLine(p2.stderr) ? `Server said: ${sanitizeText(keyLine(p2.stderr), 240)}` : ""].filter(Boolean).join(" ") || void 0 });
|
|
40452
|
+
diagnosed = true;
|
|
40453
|
+
}
|
|
40454
|
+
}
|
|
40455
|
+
if (!diagnosed)
|
|
40456
|
+
lines.push({
|
|
40457
|
+
ok: /401/.test(msg) ? null : false,
|
|
40458
|
+
label: /401/.test(msg) ? "MCP handshake needs sign-in" : "MCP handshake failed",
|
|
40459
|
+
hint: /401/.test(msg) ? void 0 : /Connection closed/i.test(msg) ? "The server closed the connection during the handshake: it probably exited because something it needs is missing (credentials, a running service such as a database, or network). Run it directly in a terminal to see its error output." : timeout ? "The server started but did not answer the handshake. If it is launched with npx or uvx, the first run downloads it: check your network, proxy (HTTPS_PROXY) and certificates (NODE_EXTRA_CA_CERTS), then try again. Otherwise the server may write logs to standard output, which breaks the protocol." : sanitizeText(msg, 200)
|
|
40460
|
+
});
|
|
40286
40461
|
}
|
|
40287
40462
|
}
|
|
40288
40463
|
}
|
|
@@ -40303,7 +40478,14 @@ async function loadPolicy(file) {
|
|
|
40303
40478
|
const { dirname: dirname4, resolve } = await import("node:path");
|
|
40304
40479
|
if (!ex(file))
|
|
40305
40480
|
throw new Error(`Policy file not found: ${file}`);
|
|
40306
|
-
const
|
|
40481
|
+
const text2 = rf(file, "utf8"), sig = `${file}.sig.json`, approvers = (process.env.SAKTUM_POLICY_APPROVERS ?? "").split(",").map((x) => x.trim()).filter(Boolean);
|
|
40482
|
+
if (ex(sig) || approvers.length) {
|
|
40483
|
+
const { verifyPolicy: verifyPolicy2 } = await Promise.resolve().then(() => (init_dist4(), dist_exports));
|
|
40484
|
+
const v = verifyPolicy2(text2, ex(sig) ? JSON.parse(rf(sig, "utf8")) : [], { approvers, min: Number(process.env.SAKTUM_POLICY_MIN ?? (approvers.length ? 1 : 1)) });
|
|
40485
|
+
if (!v.ok)
|
|
40486
|
+
throw new Error(`Refusing the policy ${file}: ${v.reason}.`);
|
|
40487
|
+
}
|
|
40488
|
+
const policy = await parsePolicy(text2);
|
|
40307
40489
|
let allow;
|
|
40308
40490
|
if (policy.allowlist) {
|
|
40309
40491
|
const path = resolve(dirname4(file), policy.allowlist);
|
|
@@ -40854,6 +41036,12 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
40854
41036
|
const m = JSON.parse(readFileSync10(o.mandate, "utf8"));
|
|
40855
41037
|
const a = approveAction(m, rid, loadOrCreateKey(o.key), Number(o.minutes), o.approvals);
|
|
40856
41038
|
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.
|
|
41039
|
+
`);
|
|
41040
|
+
});
|
|
41041
|
+
agent.command("reinstate").description("Restart a stopped agent: signed by its owner or operator, naming the human approver and the evidence").argument("<mandate>", "mandate file").requiredOption("--approver <name>", "the named human who approves").requiredOption("--evidence <text>", "why it is safe to restart (incident reference, fix, review)").option("--key <spec>", "the owner's or operator's key").action((f, o) => {
|
|
41042
|
+
const m = JSON.parse(readFileSync10(f, "utf8"));
|
|
41043
|
+
const doc = reinstateMandate(m, loadOrCreateKey(o.key), o.approver, o.evidence);
|
|
41044
|
+
process.stdout.write(`Reinstated ${sanitizeText(m.agent.name, 60)}: approved by ${sanitizeText(doc.approver, 60)} at ${doc.at}. Evidence: ${sanitizeText(doc.evidence, 200)}
|
|
40857
41045
|
`);
|
|
40858
41046
|
});
|
|
40859
41047
|
agent.command("revoke").description("Stop an agent now: every Saktum proxy on this machine refuses calls under this mandate").argument("<mandate>", "mandate file").option("--reason <text>", "why").option("--key <spec>", "sign the revocation as the owner or operator (file, env:VAR, keychain:NAME or exec:PROGRAM)").option("--out <file>", "also write the signed revocation (for a remote list or the ledger)").action((f, o) => {
|
|
@@ -40865,7 +41053,7 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
40865
41053
|
process.stdout.write(`Revoked the mandate for ${sanitizeText(m.agent.name, 80)} at ${r.at}. Its calls are now refused (code: revoked).
|
|
40866
41054
|
`);
|
|
40867
41055
|
});
|
|
40868
|
-
program2.command("proxy").description("Put Saktum between an agent and a local MCP server: signed receipts for every tool call, and the agent's mandate observed or enforced (preview)").argument("<command...>", "the server command, after --").option("--mandate <file>", "the agent's mandate (from saktum agent create)").option("--agent-key <file>", "the agent's key, which signs receipts", "agent-key.json").option("--enforce", "block calls outside the mandate (default: observe and record only)", false).option("--receipts <file>", "receipt log (append-only, hash-chained)").option("--revocations <file>", "revocation list to honour (default ~/.saktum/revocations.json)").option("--approvals <file>", "signed approvals to honour (default ~/.saktum/approvals.json)").option("--credential <file>", "the agent's credential: its accountability chain is verified on every call").option("--revoked-credentials <file>", "JSON list of revoked credential ids").option("--agreement <file>", "the signed agreement with the provider: calls outside it are refused and every call is metered").option("--wallet <file>", "prepaid token wallet charged per call under the agreement").option("--approval-webhook <url>", "post approval requests to this webhook (Slack, Teams or an email relay)").option("--approval-url <url>", "base link of saktum approvals serve, included in approval requests").option("--bindings <file>", "bindings override: JSON { tool: { action, bindings: { arg: field } } } for tools that declare nothing").option("--revocations-url <url>", "a remote revocation list (for example in the ledger) the agent cannot edit").option("--digest-key <spec>", "keyed digests of arguments in receipts: env:VAR (recommended)").option("--pin <fingerprint>", "refuse calls if the server's tools differ from this approved fingerprint (sha256:...)").option("--checkpoint-every <n>", "write a signed checkpoint every n receipts").option("--checkpoint-file <file>", "where checkpoints go (keep it off the agent's machine or ship it)").option("--approval-secret <spec>", "secret shared with approvals serve for single-use, per-request links: env:VAR").option("--quarantine-results", "withhold tool results that contain instructions aimed at the agent or secrets (default: flag them in receipts)", false).action(async (parts, o) => {
|
|
41056
|
+
program2.command("proxy").description("Put Saktum between an agent and a local MCP server: signed receipts for every tool call, and the agent's mandate observed or enforced (preview)").argument("<command...>", "the server command, after --").option("--mandate <file>", "the agent's mandate (from saktum agent create)").option("--agent-key <file>", "the agent's key, which signs receipts", "agent-key.json").option("--enforce", "block calls outside the mandate (default: observe and record only)", false).option("--receipts <file>", "receipt log (append-only, hash-chained)").option("--revocations <file>", "revocation list to honour (default ~/.saktum/revocations.json)").option("--approvals <file>", "signed approvals to honour (default ~/.saktum/approvals.json)").option("--credential <file>", "the agent's credential: its accountability chain is verified on every call").option("--revoked-credentials <file>", "JSON list of revoked credential ids").option("--agreement <file>", "the signed agreement with the provider: calls outside it are refused and every call is metered").option("--wallet <file>", "prepaid token wallet charged per call under the agreement").option("--approval-webhook <url>", "post approval requests to this webhook (Slack, Teams or an email relay)").option("--approval-url <url>", "base link of saktum approvals serve, included in approval requests").option("--bindings <file>", "bindings override: JSON { tool: { action, bindings: { arg: field } } } for tools that declare nothing").option("--revocations-url <url>", "a remote revocation list (for example in the ledger) the agent cannot edit").option("--digest-key <spec>", "keyed digests of arguments in receipts: env:VAR (recommended)").option("--pin <fingerprint>", "refuse calls if the server's tools differ from this approved fingerprint (sha256:...)").option("--checkpoint-every <n>", "write a signed checkpoint every n receipts").option("--checkpoint-file <file>", "where checkpoints go (keep it off the agent's machine or ship it)").option("--approval-secret <spec>", "secret shared with approvals serve for single-use, per-request links: env:VAR").option("--quarantine-results", "withhold tool results that contain instructions aimed at the agent or secrets (default: flag them in receipts)", false).option("--on-behalf-of <file>", "the user this agent acts for (their credential): the agent never exceeds that user's permissions").option("--handoff-from <ref>", "the receipt (entry hash) of the agent that handed this work over; recorded on every receipt for provenance").option("--cluster <file>", "a cluster of agents sharing limits: JSON { id, file, limits: [{ field, max, label }] }").action(async (parts, o) => {
|
|
40869
41057
|
const { homedir: homedir2 } = await import("node:os");
|
|
40870
41058
|
const { join: join7 } = await import("node:path");
|
|
40871
41059
|
let mandate;
|
|
@@ -40901,6 +41089,9 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
40901
41089
|
...o.checkpointEvery && o.checkpointFile ? { checkpointEvery: Number(o.checkpointEvery), checkpointFile: o.checkpointFile } : {},
|
|
40902
41090
|
...o.approvalSecret ? { approvalSecret: secretFrom(o.approvalSecret) } : {},
|
|
40903
41091
|
...o.quarantineResults ? { quarantineResults: true } : {},
|
|
41092
|
+
...o.onBehalfOf ? { onBehalfOf: JSON.parse(readFileSync10(o.onBehalfOf, "utf8")) } : {},
|
|
41093
|
+
...o.handoffFrom ? { handoffFrom: o.handoffFrom } : {},
|
|
41094
|
+
...o.cluster ? { cluster: JSON.parse(readFileSync10(o.cluster, "utf8")) } : {},
|
|
40904
41095
|
log: (m) => process.stderr.write(`saktum: ${m}
|
|
40905
41096
|
`)
|
|
40906
41097
|
});
|
|
@@ -40944,6 +41135,42 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
40944
41135
|
`);
|
|
40945
41136
|
exitCode = logs.every((l) => l.verified) ? 0 : 1;
|
|
40946
41137
|
});
|
|
41138
|
+
receipts.command("enforcement").description("For every decision: was it made before the action? (by construction, the proxy decides before forwarding)").argument("<file>", "receipt log").action((f) => {
|
|
41139
|
+
const e = parseReceiptLog(readFileSync10(f, "utf8"));
|
|
41140
|
+
const ok = verifyReceiptLog(e).ok;
|
|
41141
|
+
const ran = e.filter((x) => x.receipt.outcome === "allow"), stopped = e.filter((x) => x.receipt.outcome === "deny"), failed = e.filter((x) => x.receipt.outcome === "error");
|
|
41142
|
+
process.stdout.write(`${e.length} decision(s) in a ${ok ? "verified" : "NOT verified"} log:
|
|
41143
|
+
${ran.length} decided before the action, which then ran
|
|
41144
|
+
${stopped.length} decided before the action, which never ran
|
|
41145
|
+
${failed.length} decided before the action, which failed or got no response
|
|
41146
|
+
0 actions without a prior decision (the proxy forwards only after an allow)
|
|
41147
|
+
`);
|
|
41148
|
+
exitCode = ok ? 0 : 1;
|
|
41149
|
+
});
|
|
41150
|
+
receipts.command("trace").description("Follow handoffs between agents: from a receipt, through the logs of the agents it handed work to").argument("<entryHash>", "the receipt to start from").argument("<files...>", "receipt logs of the agents involved").action((start, files) => {
|
|
41151
|
+
const all = files.flatMap((f) => parseReceiptLog(readFileSync10(f, "utf8")).map((x) => ({ x, f })));
|
|
41152
|
+
const seen = /* @__PURE__ */ new Set();
|
|
41153
|
+
let frontier = [start], depth = 0;
|
|
41154
|
+
while (frontier.length && depth < 10) {
|
|
41155
|
+
const next = [];
|
|
41156
|
+
for (const h of frontier) {
|
|
41157
|
+
if (seen.has(h))
|
|
41158
|
+
continue;
|
|
41159
|
+
seen.add(h);
|
|
41160
|
+
const own2 = all.find((a) => a.x.entryHash === h);
|
|
41161
|
+
if (own2)
|
|
41162
|
+
process.stdout.write(`${" ".repeat(depth)}${own2.x.receipt.outcome === "deny" ? "\u26D4" : "\u2713"} ${sanitizeText(own2.x.receipt.envelope.tool, 40)} by ${sanitizeText(own2.x.receipt.envelope.caller.agent?.slice(0, 24) ?? "?", 30)} (${sanitizeText(own2.f, 60)})
|
|
41163
|
+
`);
|
|
41164
|
+
for (const a of all.filter((a2) => a2.x.result.handoffFrom === h)) {
|
|
41165
|
+
process.stdout.write(`${" ".repeat(depth + 1)}\u21B3 handed to ${sanitizeText(a.x.receipt.envelope.caller.agent?.slice(0, 24) ?? "?", 30)}: ${a.x.receipt.outcome === "deny" ? "\u26D4" : "\u2713"} ${sanitizeText(a.x.receipt.envelope.tool, 40)} (${sanitizeText(a.f, 60)})
|
|
41166
|
+
`);
|
|
41167
|
+
next.push(a.x.entryHash);
|
|
41168
|
+
}
|
|
41169
|
+
}
|
|
41170
|
+
frontier = next;
|
|
41171
|
+
depth++;
|
|
41172
|
+
}
|
|
41173
|
+
});
|
|
40947
41174
|
receipts.command("review").description("The human-review queue: allowed actions sampled for review under supervised autonomy").argument("<file>", "receipt log").action((f) => {
|
|
40948
41175
|
const e = parseReceiptLog(readFileSync10(f, "utf8")).filter((x) => x.result.flags?.includes("review-sampled"));
|
|
40949
41176
|
for (const x of e)
|
|
@@ -41075,8 +41302,8 @@ Assumptions: ${r.assumptions}.
|
|
|
41075
41302
|
const j = JSON.parse(readFileSync10(f, "utf8"));
|
|
41076
41303
|
return { machine: j.machine ?? f, servers: j.servers ?? [] };
|
|
41077
41304
|
});
|
|
41078
|
-
const
|
|
41079
|
-
const fleet = buildFleet(setups,
|
|
41305
|
+
const pol2 = o.policy ? await loadPolicy(o.policy) : void 0;
|
|
41306
|
+
const fleet = buildFleet(setups, pol2?.policy, pol2?.allow);
|
|
41080
41307
|
process.stdout.write(renderFleet(fleet));
|
|
41081
41308
|
if (o.out)
|
|
41082
41309
|
writeFileSync5(o.out, JSON.stringify(fleet, null, 2) + "\n");
|
|
@@ -41237,7 +41464,7 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
|
|
|
41237
41464
|
const { homedir: homedir2 } = await import("node:os");
|
|
41238
41465
|
const { join: join7 } = await import("node:path");
|
|
41239
41466
|
const k = kpis(parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), o);
|
|
41240
|
-
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
|
|
41467
|
+
process.stdout.write(`Calls ${k.calls} \xB7 allowed ${k.allowed} \xB7 blocked ${k.blocked} \xB7 approved ${k.approvals} \xB7 self-corrected ${k.selfCorrected} \xB7 escalated ${k.escalations} \xB7 tokens ${k.tokens} \xB7 latency p50 ${k.latencyP50 ?? "-"} ms, p95 ${k.latencyP95 ?? "-"} ms
|
|
41241
41468
|
`);
|
|
41242
41469
|
process.stdout.write(`By outcome: ${k.byOutcome.map(([c, n]) => `${c} ${n}`).join(", ")}
|
|
41243
41470
|
By tool: ${k.byTool.map(([c, n]) => `${c} ${n}`).join(", ")}
|
|
@@ -41248,7 +41475,61 @@ By tool: ${k.byTool.map(([c, n]) => `${c} ${n}`).join(", ")}
|
|
|
41248
41475
|
process.stdout.write(ok ? "\u2713 Valid bounty document.\n" : "\u2717 Not a valid bounty document.\n");
|
|
41249
41476
|
exitCode = ok ? 0 : 1;
|
|
41250
41477
|
});
|
|
41251
|
-
program2.command("evidence").description("Saktum's evidence mapped to the frameworks you're held to (supports evidence; never a compliance claim)").option("--framework <id>", "all, eu-ai-act, nist-ai-rmf, iso-42001, owasp-llm, dora-nis2, gdpr-dpdp", "all").option("--markdown", "print as Markdown tables", false).action((o) => {
|
|
41478
|
+
program2.command("evidence").description("Saktum's evidence mapped to the frameworks you're held to (supports evidence; never a compliance claim)").option("--framework <id>", "all, eu-ai-act, nist-ai-rmf, iso-42001, owasp-llm, dora-nis2, gdpr-dpdp", "all").option("--markdown", "print as Markdown tables", false).option("--package <dir>", "write a complete evidence package to this folder (inventory, policy, receipts, crosswalk) with an index page").option("--receipts <files...>", "receipt logs to include in the package").option("--fleet <file>", "fleet inventory JSON").option("--agents-dir <dir>", "folder with agent mandates").option("--policy <file>", "policy file (and its signatures)").action(async (o) => {
|
|
41479
|
+
if (o.package) {
|
|
41480
|
+
const { mkdirSync: mk, copyFileSync: cp } = await import("node:fs");
|
|
41481
|
+
const { join: join7, basename } = await import("node:path");
|
|
41482
|
+
mk(o.package, { recursive: true });
|
|
41483
|
+
const items = [];
|
|
41484
|
+
const md = crosswalk("all").map((f) => `## ${f.name}
|
|
41485
|
+
|
|
41486
|
+
${f.note}
|
|
41487
|
+
|
|
41488
|
+
| Ref | Obligation | Coverage | Evidence |
|
|
41489
|
+
| --- | --- | --- | --- |
|
|
41490
|
+
${f.items.map((i) => `| ${i.ref} | ${i.obligation} | ${i.coverage} | ${i.evidence} |`).join("\n")}`).join("\n\n");
|
|
41491
|
+
writeFileSync5(join7(o.package, "frameworks.md"), `# Evidence for frameworks
|
|
41492
|
+
|
|
41493
|
+
${DISCLAIMER}
|
|
41494
|
+
|
|
41495
|
+
${md}
|
|
41496
|
+
`);
|
|
41497
|
+
items.push("frameworks.md: evidence mapped to frameworks");
|
|
41498
|
+
if (o.receipts?.length) {
|
|
41499
|
+
const logs = o.receipts.map((f) => {
|
|
41500
|
+
const e = parseReceiptLog(readFileSync10(f, "utf8"));
|
|
41501
|
+
return { name: basename(f), verified: verifyReceiptLog(e).ok, entries: e.map((x) => ({ at: x.receipt.issuedAt, agent: x.receipt.envelope.caller.agent?.slice(0, 24) ?? "", tool: x.receipt.envelope.tool, outcome: x.receipt.outcome, code: x.result.code ?? "", reason: String(x.receipt.reason ?? ""), tokens: x.result.metering?.tokens ?? 0 })) };
|
|
41502
|
+
});
|
|
41503
|
+
writeFileSync5(join7(o.package, "receipts.html"), renderReceiptsView(logs));
|
|
41504
|
+
for (const f of o.receipts)
|
|
41505
|
+
cp(f, join7(o.package, basename(f)));
|
|
41506
|
+
items.push(`receipts.html: ${logs.reduce((n, l) => n + l.entries.length, 0)} receipts from ${logs.length} log(s), ${logs.filter((l) => l.verified).length} verified`);
|
|
41507
|
+
}
|
|
41508
|
+
if (o.agentsDir) {
|
|
41509
|
+
const a = scanAgents([o.agentsDir]);
|
|
41510
|
+
writeFileSync5(join7(o.package, "agents.json"), JSON.stringify(a, null, 2));
|
|
41511
|
+
const fails = a.filter((x) => gateAgent(x).length).length;
|
|
41512
|
+
items.push(`agents.json: ${a.length} agent(s); deployment gate ${fails ? `failed for ${fails}` : "passed"}`);
|
|
41513
|
+
}
|
|
41514
|
+
if (o.fleet) {
|
|
41515
|
+
cp(o.fleet, join7(o.package, "inventory.json"));
|
|
41516
|
+
items.push("inventory.json: MCP server inventory");
|
|
41517
|
+
}
|
|
41518
|
+
if (o.policy) {
|
|
41519
|
+
cp(o.policy, join7(o.package, basename(o.policy)));
|
|
41520
|
+
const sig = `${o.policy}.sig.json`;
|
|
41521
|
+
const v = verifyPolicy(readFileSync10(o.policy, "utf8"), existsSync7(sig) ? JSON.parse(readFileSync10(sig, "utf8")) : []);
|
|
41522
|
+
if (existsSync7(sig))
|
|
41523
|
+
cp(sig, join7(o.package, basename(sig)));
|
|
41524
|
+
items.push(`${basename(o.policy)}: ${v.ok ? `signed by ${v.signers.length} approver(s)` : `NOT approved (${v.reason})`}`);
|
|
41525
|
+
}
|
|
41526
|
+
const esc3 = (x) => x.replace(/[&<>]/g, (c) => ({ "&": "&", "<": "<", ">": ">" })[c]);
|
|
41527
|
+
writeFileSync5(join7(o.package, "index.html"), `<!doctype html><meta charset="utf-8"><title>Evidence package</title><body style="font:15px system-ui;max-width:760px;margin:24px auto;padding:0 16px"><h1>Evidence package</h1><p>Generated ${(/* @__PURE__ */ new Date()).toISOString()} by Saktum Check ${ENGINE_VERSION}.</p><ul>${items.map((i) => `<li>${esc3(i)}</li>`).join("")}</ul><p style="color:#666">${esc3(DISCLAIMER)} Every receipt and signature can be verified independently (saktum receipts verify, or saktum.vercel.app/verify).</p></body>`);
|
|
41528
|
+
process.stdout.write(`Evidence package written to ${sanitizeText(o.package)}:
|
|
41529
|
+
${items.map((i) => ` ${i}`).join("\n")}
|
|
41530
|
+
`);
|
|
41531
|
+
return;
|
|
41532
|
+
}
|
|
41252
41533
|
const fs2 = crosswalk(o.framework);
|
|
41253
41534
|
if (!fs2.length)
|
|
41254
41535
|
throw new Error("Unknown framework. Use all, eu-ai-act, nist-ai-rmf, iso-42001, owasp-llm, dora-nis2 or gdpr-dpdp.");
|
|
@@ -41414,7 +41695,7 @@ ${secret ? "Per-request links: give the proxy the same --approval-secret and --a
|
|
|
41414
41695
|
`));
|
|
41415
41696
|
await new Promise(() => void 0);
|
|
41416
41697
|
});
|
|
41417
|
-
program2.command("agents").description("Agent inventory (v0.10)").command("scan").argument("[dirs...]", "folders to search for agent mandates (default: this folder and ~/.saktum)").option("--out <file>", "write the inventory as JSON (for saktum assess --agents)").action(async (dirs, o) => {
|
|
41698
|
+
program2.command("agents").description("Agent inventory (v0.10)").command("scan").argument("[dirs...]", "folders to search for agent mandates (default: this folder and ~/.saktum)").option("--out <file>", "write the inventory as JSON (for saktum assess --agents)").option("--gate", "deployment gate: exit 1 if any agent lacks an accountable owner, an operator, a valid mandate or tier-appropriate approvals", false).action(async (dirs, o) => {
|
|
41418
41699
|
const { homedir: homedir2 } = await import("node:os");
|
|
41419
41700
|
const { join: join7 } = await import("node:path");
|
|
41420
41701
|
const a = scanAgents(dirs.length ? dirs : [".", join7(homedir2(), ".saktum")]);
|
|
@@ -41425,6 +41706,15 @@ ${secret ? "Per-request links: give the proxy the same --approval-secret and --a
|
|
|
41425
41706
|
`);
|
|
41426
41707
|
if (o.out)
|
|
41427
41708
|
writeFileSync5(o.out, JSON.stringify(a, null, 2) + "\n");
|
|
41709
|
+
if (o.gate) {
|
|
41710
|
+
const fails = a.map((x) => ({ x, why: gateAgent(x) })).filter((f) => f.why.length);
|
|
41711
|
+
for (const f of fails)
|
|
41712
|
+
process.stdout.write(`\u2717 gate: ${sanitizeText(f.x.name, 40)}: ${f.why.join("; ")}
|
|
41713
|
+
`);
|
|
41714
|
+
process.stdout.write(fails.length ? `Deployment gate failed for ${fails.length} agent(s).
|
|
41715
|
+
` : "\u2713 Deployment gate passed: every agent has an accountable owner, an operator, a valid mandate and tier-appropriate controls.\n");
|
|
41716
|
+
exitCode = fails.length ? 1 : 0;
|
|
41717
|
+
}
|
|
41428
41718
|
});
|
|
41429
41719
|
const ledger2 = program2.commands.find((c) => c.name() === "ledger");
|
|
41430
41720
|
ledger2.command("rotate").description("Record a key rotation: signed by the old key, with proof of possession of the new key").requiredOption("--old-key <spec>").requiredOption("--new-key <spec>").option("--out <file>", "statement file", "saktum-rotation.json").action((o) => {
|
|
@@ -41502,6 +41792,24 @@ ${published ? published === mine ? "\u2713 Matches the published release.\n" : "
|
|
|
41502
41792
|
npm provenance: npm audit signatures
|
|
41503
41793
|
`);
|
|
41504
41794
|
});
|
|
41795
|
+
const pol = program2.command("policy").description("Signed, change-controlled policies (v0.15)");
|
|
41796
|
+
pol.command("sign").argument("<file>", "policy file").option("--key <spec>", "approver's key").action((f, o) => {
|
|
41797
|
+
const sig = `${f}.sig.json`;
|
|
41798
|
+
const k = loadOrCreateKey(o.key);
|
|
41799
|
+
const list = existsSync7(sig) ? JSON.parse(readFileSync10(sig, "utf8")) : [];
|
|
41800
|
+
list.push(signPolicy(readFileSync10(f, "utf8"), k));
|
|
41801
|
+
writeFileSync5(sig, JSON.stringify(list, null, 2) + "\n");
|
|
41802
|
+
process.stdout.write(`Signed ${sanitizeText(f)} as ${k.kid.slice(0, 24)}...; ${list.length} signature(s) in ${sanitizeText(sig)}.
|
|
41803
|
+
`);
|
|
41804
|
+
});
|
|
41805
|
+
pol.command("verify").argument("<file>").option("--approvers <dids>", "comma-separated approver did:keys").option("--min <n>", "signatures required", "1").action((f, o) => {
|
|
41806
|
+
const sig = `${f}.sig.json`;
|
|
41807
|
+
const v = verifyPolicy(readFileSync10(f, "utf8"), existsSync7(sig) ? JSON.parse(readFileSync10(sig, "utf8")) : [], { approvers: o.approvers?.split(",").map((x) => x.trim()).filter(Boolean), min: Number(o.min) });
|
|
41808
|
+
process.stdout.write(v.ok ? `\u2713 Policy approved by ${v.signers.length} approver(s).
|
|
41809
|
+
` : `\u2717 ${v.reason}
|
|
41810
|
+
`);
|
|
41811
|
+
exitCode = v.ok ? 0 : 1;
|
|
41812
|
+
});
|
|
41505
41813
|
program2.command("demo").description("See permissions, autonomy, risk and receipts in 60 seconds: one shopping agent under three mandates").option("--out <dir>", "folder for the demo's mandates, receipts and passports", "saktum-demo").option("--story <name>", "grocery, travel, finance, coding, support, legal, marketplace, autonomy, or all (grocery, travel, finance, coding, support, legal and marketplace)", "all").action(async (o) => {
|
|
41506
41814
|
const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
|
|
41507
41815
|
await runDemo2(o.out, (l) => process.stdout.write(l + "\n"), o.story);
|