@decionis/mcp 0.1.2 → 0.1.3
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 +44 -5
- package/dist/AgentHookCli.js +2 -2
- package/dist/ManagedAgentHookCli.js +17975 -7768
- package/dist/agent/AgentIndex.js +2 -2
- package/dist/{chunk-2C62WFX2.js → chunk-NFWSCSMQ.js} +2 -2
- package/dist/{chunk-KY5AVRL6.js → chunk-XNC3IZW5.js} +13504 -2577
- package/dist/chunk-XNC3IZW5.js.map +1 -0
- package/dist/index.js +2233 -8
- package/dist/index.js.map +1 -1
- package/package.json +5 -3
- package/dist/chunk-KY5AVRL6.js.map +0 -1
- /package/dist/{chunk-2C62WFX2.js.map → chunk-NFWSCSMQ.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Server.ts","../src/Tools.ts","../src/index.ts"],"sourcesContent":["/**\n * Minimal MCP (Model Context Protocol) server core: JSON-RPC 2.0 over\n * newline-delimited stdio. Hand-rolled (no SDK dependency), matching the\n * protocol service's hand-rolled remote MCP surface. The message handler is\n * transport-agnostic and unit-testable; the stdio loop is a thin shell.\n */\n\nimport { createInterface } from \"node:readline\";\n\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\"2025-11-25\", \"2025-06-18\", \"2025-03-26\", \"2024-11-05\"];\nexport const MCP_SERVER_VERSION = \"0.1.2\";\nconst DEFAULT_PROTOCOL_VERSION = \"2025-11-25\";\n\nexport interface ToolContent {\n type: \"text\";\n text: string;\n}\n\nexport interface ToolDefinition {\n name: string;\n title: string;\n description: string;\n inputSchema: Record<string, unknown>;\n annotations: {\n readOnlyHint: boolean;\n destructiveHint: boolean;\n idempotentHint: boolean;\n openWorldHint: boolean;\n };\n handler: (\n args: Record<string, unknown>,\n ) => Promise<{ content: ToolContent[]; isError?: boolean }>;\n}\n\nexport interface ServerInfo {\n name: string;\n version: string;\n}\n\ntype JsonRpcResponse = Record<string, unknown>;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nfunction rpcResult(id: unknown, result: unknown): JsonRpcResponse {\n return { jsonrpc: \"2.0\", id, result };\n}\n\nfunction rpcError(id: unknown, code: number, message: string): JsonRpcResponse {\n return { jsonrpc: \"2.0\", id, error: { code, message } };\n}\n\n/**\n * The MCP message handler. Returns `null` for notifications (no reply) and\n * a JSON-RPC response object otherwise.\n */\nexport class McpMessageHandler {\n private readonly toolsByName: Map<string, ToolDefinition>;\n\n constructor(private readonly options: { serverInfo: ServerInfo; tools: ToolDefinition[] }) {\n this.toolsByName = new Map(options.tools.map((tool) => [tool.name, tool]));\n }\n\n async handle(message: unknown): Promise<JsonRpcResponse | null> {\n if (\n !isPlainObject(message) ||\n message.jsonrpc !== \"2.0\" ||\n typeof message.method !== \"string\"\n ) {\n const id = isPlainObject(message) && \"id\" in message ? message.id : null;\n return rpcError(id, -32600, \"Invalid JSON-RPC 2.0 request\");\n }\n const { method, id } = message;\n const isNotification = !(\"id\" in message);\n const params = isPlainObject(message.params) ? message.params : {};\n\n if (isNotification) return null; // notifications/initialized, cancellations, …\n\n switch (method) {\n case \"initialize\": {\n const requested = typeof params.protocolVersion === \"string\" ? params.protocolVersion : \"\";\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested)\n ? requested\n : DEFAULT_PROTOCOL_VERSION;\n return rpcResult(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: this.options.serverInfo,\n });\n }\n case \"ping\":\n return rpcResult(id, {});\n case \"tools/list\":\n return rpcResult(id, {\n tools: this.options.tools.map(\n ({ name, title, description, inputSchema, annotations }) => ({\n name,\n title,\n description,\n inputSchema,\n annotations,\n }),\n ),\n });\n case \"tools/call\": {\n const name = typeof params.name === \"string\" ? params.name : \"\";\n const tool = this.toolsByName.get(name);\n if (!tool) return rpcError(id, -32602, `Unknown tool: ${name || \"(missing name)\"}`);\n const args = isPlainObject(params.arguments) ? params.arguments : {};\n try {\n const result = await tool.handler(args);\n return rpcResult(id, { content: result.content, isError: result.isError ?? false });\n } catch (err) {\n return rpcResult(id, {\n content: [\n {\n type: \"text\",\n text: `Tool ${name} failed: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n });\n }\n }\n default:\n return rpcError(id, -32601, `Method not found: ${method}`);\n }\n }\n}\n\n/**\n * Runs a message handler over stdio: one JSON message per line in, one per\n * line out. Only protocol JSON is ever written to stdout; diagnostics go to\n * stderr.\n */\nexport class McpStdioServer {\n static run(\n handler: (message: unknown) => Promise<JsonRpcResponse | null>,\n streams: { input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream } = {},\n ): Promise<void> {\n const input = streams.input ?? process.stdin;\n const output = streams.output ?? process.stdout;\n const rl = createInterface({ input, crlfDelay: Infinity });\n const inFlight = new Set<Promise<void>>();\n\n return new Promise((resolve) => {\n rl.on(\"line\", (line) => {\n const trimmed = line.trim();\n if (!trimmed) return;\n const work = (async () => {\n let message: unknown;\n try {\n message = JSON.parse(trimmed);\n } catch {\n output.write(`${JSON.stringify(rpcError(null, -32700, \"Parse error\"))}\\n`);\n return;\n }\n try {\n const response = await handler(message);\n if (response !== null) output.write(`${JSON.stringify(response)}\\n`);\n } catch (err) {\n process.stderr.write(`decionis-mcp: handler error: ${String(err)}\\n`);\n }\n })();\n inFlight.add(work);\n void work.finally(() => inFlight.delete(work));\n });\n rl.on(\"close\", () => {\n // stdin EOF: drain in-flight handlers so no response is lost.\n void Promise.allSettled([...inFlight]).then(() => resolve());\n });\n });\n }\n}\n\n/**\n * Build the message handler. Returns `null` for notifications (no reply) and\n * a JSON-RPC response object otherwise.\n */\nexport function createMcpHandler(options: { serverInfo: ServerInfo; tools: ToolDefinition[] }) {\n const handler = new McpMessageHandler(options);\n return async function handleMessage(message: unknown): Promise<JsonRpcResponse | null> {\n return handler.handle(message);\n };\n}\n\n/**\n * Run the handler over stdio: one JSON message per line in, one per line out.\n * Only protocol JSON is ever written to stdout; diagnostics go to stderr.\n */\nexport function runStdioServer(\n handler: (message: unknown) => Promise<JsonRpcResponse | null>,\n streams: { input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream } = {},\n): Promise<void> {\n return McpStdioServer.run(handler, streams);\n}\n","/**\n * The Decionis MCP tools: read the repo's DECIONIS_POLICY.md, evaluate a\n * candidate action against it through the real protocol evaluator, and\n * explain the verdict vocabulary — so coding agents can check governance\n * constraints BEFORE committing or triggering anything.\n */\n\nimport { LocalDecionisGateway, normalizeVerdict } from \"./Gateway.js\";\nimport { PolicyFileRepository } from \"./agent/PolicyFileRepository.js\";\nimport { sha256Hex } from \"./RulesBlock.js\";\nimport type { ToolContent, ToolDefinition } from \"./Server.js\";\n\nconst text = (value: unknown): ToolContent[] => [\n { type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2) },\n];\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst VERDICT_HELP = `# Decionis verdicts and rule grammar\n\n**Verdicts** (a rule's \\`action\\`): \\`allow\\` (execute), \\`block\\` (never execute),\n\\`restrain\\` (hold for human review), \\`escalate\\` (require an authorized approver).\nThe protocol reports outcomes as APPROVE / REJECT / REVIEW / ESCALATE; this server\nalso returns the normalized verdict (allow / block / review / escalate). When no\nrule matches, the platform holds the decision for review (outcome REVIEW).\n\n**Rules block** (in DECIONIS_POLICY.md):\n\\`\\`\\`decionis\n{ \"version\": 1, \"rules\": [\n { \"name\": \"Block deploys during a change freeze\",\n \"priority\": 100, \"domain\": \"*\",\n \"all\": [{ \"field\": \"context.change_freeze\", \"op\": \"eq\", \"value\": true }],\n \"action\": \"block\" } ] }\n\\`\\`\\`\n\n- Each rule has exactly one of \\`all\\` (AND) / \\`any\\` (OR).\n- Operators: eq, ne/neq, gt, gte, lt, lte, in (values array), not_in (values array),\n exists, contains, matches (case-insensitive regex). Equality coerces numbers,\n booleans, and lowercased text; arrays match on any element.\n- Fields resolve against the decision payload: \\`context.<key>\\` reads payload keys,\n \\`decision_type\\` derives from the payload's \\`action\\` label, then the workflow key.\n- Give every rule an explicit \\`priority\\` (higher evaluates first) and keep\n \\`\"domain\": \"*\"\\` so it applies to every decision the repo gates.\n\n**Before committing or running anything risky**, call \\`decionis_evaluate\\` with the\naction you intend to take (e.g. {\"action\": \"production-deploy\", \"agent_generated\": true})\nand abide by the verdict: allow → proceed; block → do not proceed; review/escalate →\nstop and ask a human.`;\n\n/** Builds the Decionis tool set bound to a local gateway. */\nexport class DecionisTools {\n constructor(\n private readonly gateway: LocalDecionisGateway,\n private readonly policyFiles: PolicyFileRepository = new PolicyFileRepository(),\n ) {}\n\n build(): ToolDefinition[] {\n const gateway = this.gateway;\n return [\n {\n name: \"decionis_read_policy\",\n title: \"Read Repository Policy\",\n description:\n \"Read and compile the repo's DECIONIS_POLICY.md governance policy: path, sha256, and the \" +\n \"enforceable rules (name, verdict, priority, domain) or compile errors. Use this to learn \" +\n \"what this repository allows, blocks, restrains, or escalates.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"Policy file path (default: $DECIONIS_POLICY_PATH or ./DECIONIS_POLICY.md)\",\n },\n },\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (args) => {\n const file = await this.policyFiles.read(args.path);\n if (!file.ok) return { content: text(file.message), isError: true };\n const compiled = gateway.compile(file.content);\n return {\n content: text({\n path: file.path,\n sha256: sha256Hex(file.content),\n bytes: Buffer.byteLength(file.content, \"utf8\"),\n rules:\n compiled === null\n ? \"no ```decionis rules block — the file is prose-only documentation\"\n : compiled.errors.length > 0\n ? { compile_errors: compiled.errors }\n : compiled.rules.map((rule) => ({\n name: rule.name,\n verdict: rule.then.action,\n priority: rule.priority,\n domain: rule.decision_domain,\n when: rule.when,\n })),\n }),\n };\n },\n },\n {\n name: \"decionis_evaluate\",\n title: \"Evaluate Candidate Action Locally\",\n description:\n \"Evaluate a candidate action against the repo's DECIONIS_POLICY.md through the real Decionis \" +\n \"protocol evaluator, entirely locally (no network, no credentials, nothing recorded). Call this \" +\n \"BEFORE committing, deploying, migrating, or any risky action, and abide by the verdict: \" +\n \"allow → proceed; block → do not proceed; review/escalate → stop and involve a human.\",\n inputSchema: {\n type: \"object\",\n required: [\"payload\"],\n properties: {\n payload: {\n type: \"object\",\n description:\n 'The candidate action, e.g. {\"action\": \"production-deploy\", \"change_freeze\": true, \"agent_generated\": true}',\n },\n workflow_key: {\n type: \"string\",\n description: \"Optional workflow key for the gated surface.\",\n },\n mode: { type: \"string\", enum: [\"shadow\", \"enforce\"], description: \"Default: shadow.\" },\n path: { type: \"string\", description: \"Policy file path override.\" },\n },\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (args) => {\n if (!isPlainObject(args.payload)) {\n return {\n content: text(\"`payload` must be a JSON object describing the action.\"),\n isError: true,\n };\n }\n const file = await this.policyFiles.read(args.path);\n if (!file.ok) return { content: text(file.message), isError: true };\n const workflowKey = typeof args.workflow_key === \"string\" ? args.workflow_key : null;\n\n const published = await gateway.publishPolicy(file.content, { workflowKey });\n if (!published.ok) {\n return {\n content: text({\n error: published.reason,\n details: published.errors,\n hint:\n published.reason === \"no_rules_block\"\n ? \"Add a ```decionis rules block to make the policy enforceable — see decionis_verdict_help.\"\n : \"Fix the rules block so it compiles; the platform enforces all-or-nothing.\",\n }),\n isError: true,\n };\n }\n\n const evaluated = await gateway.evaluate({\n payload: args.payload,\n workflowKey,\n mode: args.mode === \"enforce\" ? \"enforce\" : \"shadow\",\n });\n if (evaluated.status !== 200) {\n return {\n content: text({\n error: `protocol evaluation failed (HTTP ${evaluated.status})`,\n body: evaluated.body,\n }),\n isError: true,\n };\n }\n\n const body = evaluated.body;\n const policyEvaluation = isPlainObject(body.policy_evaluation)\n ? body.policy_evaluation\n : {};\n const evaluatedRuleCount =\n typeof policyEvaluation.evaluated_rule_count === \"number\"\n ? policyEvaluation.evaluated_rule_count\n : null;\n\n return {\n content: text({\n verdict: normalizeVerdict(body.outcome),\n outcome: body.outcome,\n resolution: policyEvaluation.resolution ?? null,\n selected_rule: policyEvaluation.selected_rule_name ?? null,\n matched_rule_count: policyEvaluation.matched_rule_count ?? null,\n evaluated_rule_count: evaluatedRuleCount,\n decision_domain: policyEvaluation.decision_domain ?? body.decision_domain ?? null,\n policy_version: published.version,\n policy_sha256: published.sha256,\n confidence: body.confidence ?? null,\n note:\n \"Local sandbox evaluation — nothing was recorded and no signed dossier was minted. \" +\n \"CI runs through decionis/govern produce the signed, verifiable record.\",\n ...(published.ruleCount > 0 && evaluatedRuleCount === 0\n ? {\n hint:\n `All ${published.ruleCount} compiled rule(s) were filtered out by the decision-domain ` +\n 'match before evaluation. Add \"domain\": \"*\" to each rule so it applies to every ' +\n \"decision this repo gates.\",\n }\n : {}),\n }),\n };\n },\n },\n {\n name: \"decionis_verdict_help\",\n title: \"Explain Decionis Verdicts\",\n description:\n \"Reference for Decionis verdicts (allow/block/restrain/escalate), the rules-block grammar and \" +\n \"operators, and how an agent should behave on each verdict.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async () => ({ content: text(VERDICT_HELP) }),\n },\n ];\n }\n}\n\n/** Functional alias for {@link DecionisTools.build}. */\nexport function createDecionisTools(gateway: LocalDecionisGateway): ToolDefinition[] {\n return new DecionisTools(gateway).build();\n}\n","// Decionis local MCP server — stdio entrypoint.\n// Lets AI coding agents (Claude Code, Cursor, …) read DECIONIS_POLICY.md and\n// evaluate candidate actions through the real @decionis/protocol evaluator\n// before they commit, deploy, or migrate anything.\n\nimport { LocalDecionisGateway } from \"./Gateway.js\";\nimport { createMcpHandler, MCP_SERVER_VERSION, runStdioServer } from \"./Server.js\";\nimport { createDecionisTools } from \"./Tools.js\";\n\nconst gateway = new LocalDecionisGateway();\nconst handler = createMcpHandler({\n serverInfo: { name: \"decionis-mcp\", version: MCP_SERVER_VERSION },\n tools: createDecionisTools(gateway),\n});\n\nrunStdioServer(handler)\n .then(async () => {\n await gateway.close();\n process.exit(0);\n })\n .catch(async (err) => {\n process.stderr.write(`decionis-mcp: fatal: ${String(err)}\\n`);\n await gateway.close().catch(() => {});\n process.exit(1);\n });\n"],"mappings":";;;;;;;;;AAOA,SAAS,uBAAuB;AAEzB,IAAM,8BAA8B,CAAC,cAAc,cAAc,cAAc,YAAY;AAC3F,IAAM,qBAAqB;AAClC,IAAM,2BAA2B;AA8BjC,IAAM,gBAAgB,CAAC,MACrB,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAEzD,SAAS,UAAU,IAAa,QAAkC;AAChE,SAAO,EAAE,SAAS,OAAO,IAAI,OAAO;AACtC;AAEA,SAAS,SAAS,IAAa,MAAc,SAAkC;AAC7E,SAAO,EAAE,SAAS,OAAO,IAAI,OAAO,EAAE,MAAM,QAAQ,EAAE;AACxD;AAMO,IAAM,oBAAN,MAAwB;AAAA,EAG7B,YAA6B,SAA8D;AAA9D;AAC3B,SAAK,cAAc,IAAI,IAAI,QAAQ,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;AAAA,EAC3E;AAAA,EAJiB;AAAA,EAMjB,MAAM,OAAO,SAAmD;AAC9D,QACE,CAAC,cAAc,OAAO,KACtB,QAAQ,YAAY,SACpB,OAAO,QAAQ,WAAW,UAC1B;AACA,YAAMA,MAAK,cAAc,OAAO,KAAK,QAAQ,UAAU,QAAQ,KAAK;AACpE,aAAO,SAASA,KAAI,QAAQ,8BAA8B;AAAA,IAC5D;AACA,UAAM,EAAE,QAAQ,GAAG,IAAI;AACvB,UAAM,iBAAiB,EAAE,QAAQ;AACjC,UA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handler","isPlainObject","gateway"]}
|
|
1
|
+
{"version":3,"sources":["../src/Server.ts","../src/Tools.ts","../src/kubernetes/KubernetesActionPlanner.ts","../../../packages/sdk-node/src/AgenticGate.ts","../../../packages/sdk-node/src/AgenticRemote.ts","../../../packages/sdk-node/src/AgenticSnapshotCache.ts","../../../packages/sdk-node/src/AgentTaskGateway.ts","../../../packages/sdk-node/src/AuthorityRequirement.ts","../../../packages/sdk-node/src/Contracts.ts","../../../packages/sdk-node/src/Client.ts","../../../packages/sdk-node/src/Gate.ts","../../../packages/sdk-node/src/Express.ts","../../../packages/sdk-node/src/ExecutionAuthority.ts","../../../packages/sdk-node/src/ExecutionToken.ts","../../../packages/sdk-node/src/Fastify.ts","../../../packages/sdk-node/src/KubernetesAuthority.ts","../../../packages/sdk-node/src/Personal.ts","../../../packages/sdk-node/src/RuntimeAdapter.ts","../src/kubernetes/KubernetesCommandRunner.ts","../../../packages/dossier-verify/src/canonical.ts","../../../packages/dossier-verify/src/verify.ts","../../../packages/dossier-verify/src/resolve.ts","../src/kubernetes/KubernetesOperations.ts","../src/kubernetes/KubernetesMcpTools.ts","../src/ShieldClient.ts","../src/ShieldTools.ts","../src/index.ts"],"sourcesContent":["/**\n * Minimal MCP (Model Context Protocol) server core: JSON-RPC 2.0 over\n * newline-delimited stdio. Hand-rolled (no SDK dependency), matching the\n * protocol service's hand-rolled remote MCP surface. The message handler is\n * transport-agnostic and unit-testable; the stdio loop is a thin shell.\n */\n\nimport { createInterface } from \"node:readline\";\n\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\"2025-11-25\", \"2025-06-18\", \"2025-03-26\", \"2024-11-05\"];\nexport const MCP_SERVER_VERSION = \"0.1.3\";\nconst DEFAULT_PROTOCOL_VERSION = \"2025-11-25\";\n\nexport interface ToolContent {\n type: \"text\";\n text: string;\n}\n\nexport interface ToolDefinition {\n name: string;\n title: string;\n description: string;\n inputSchema: Record<string, unknown>;\n annotations: {\n readOnlyHint: boolean;\n destructiveHint: boolean;\n idempotentHint: boolean;\n openWorldHint: boolean;\n };\n handler: (\n args: Record<string, unknown>,\n ) => Promise<{ content: ToolContent[]; isError?: boolean }>;\n}\n\nexport interface ServerInfo {\n name: string;\n version: string;\n}\n\ntype JsonRpcResponse = Record<string, unknown>;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nfunction rpcResult(id: unknown, result: unknown): JsonRpcResponse {\n return { jsonrpc: \"2.0\", id, result };\n}\n\nfunction rpcError(id: unknown, code: number, message: string): JsonRpcResponse {\n return { jsonrpc: \"2.0\", id, error: { code, message } };\n}\n\n/**\n * The MCP message handler. Returns `null` for notifications (no reply) and\n * a JSON-RPC response object otherwise.\n */\nexport class McpMessageHandler {\n private readonly toolsByName: Map<string, ToolDefinition>;\n\n constructor(private readonly options: { serverInfo: ServerInfo; tools: ToolDefinition[] }) {\n this.toolsByName = new Map(options.tools.map((tool) => [tool.name, tool]));\n }\n\n async handle(message: unknown): Promise<JsonRpcResponse | null> {\n if (\n !isPlainObject(message) ||\n message.jsonrpc !== \"2.0\" ||\n typeof message.method !== \"string\"\n ) {\n const id = isPlainObject(message) && \"id\" in message ? message.id : null;\n return rpcError(id, -32600, \"Invalid JSON-RPC 2.0 request\");\n }\n const { method, id } = message;\n const isNotification = !(\"id\" in message);\n const params = isPlainObject(message.params) ? message.params : {};\n\n if (isNotification) return null; // notifications/initialized, cancellations, …\n\n switch (method) {\n case \"initialize\": {\n const requested = typeof params.protocolVersion === \"string\" ? params.protocolVersion : \"\";\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested)\n ? requested\n : DEFAULT_PROTOCOL_VERSION;\n return rpcResult(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: this.options.serverInfo,\n });\n }\n case \"ping\":\n return rpcResult(id, {});\n case \"tools/list\":\n return rpcResult(id, {\n tools: this.options.tools.map(\n ({ name, title, description, inputSchema, annotations }) => ({\n name,\n title,\n description,\n inputSchema,\n annotations: {\n title,\n ...annotations,\n },\n }),\n ),\n });\n case \"tools/call\": {\n const name = typeof params.name === \"string\" ? params.name : \"\";\n const tool = this.toolsByName.get(name);\n if (!tool) return rpcError(id, -32602, `Unknown tool: ${name || \"(missing name)\"}`);\n const args = isPlainObject(params.arguments) ? params.arguments : {};\n try {\n const result = await tool.handler(args);\n return rpcResult(id, { content: result.content, isError: result.isError ?? false });\n } catch (err) {\n return rpcResult(id, {\n content: [\n {\n type: \"text\",\n text: `Tool ${name} failed: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n });\n }\n }\n default:\n return rpcError(id, -32601, `Method not found: ${method}`);\n }\n }\n}\n\n/**\n * Runs a message handler over stdio: one JSON message per line in, one per\n * line out. Only protocol JSON is ever written to stdout; diagnostics go to\n * stderr.\n */\nexport class McpStdioServer {\n static run(\n handler: (message: unknown) => Promise<JsonRpcResponse | null>,\n streams: { input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream } = {},\n ): Promise<void> {\n const input = streams.input ?? process.stdin;\n const output = streams.output ?? process.stdout;\n const rl = createInterface({ input, crlfDelay: Infinity });\n const inFlight = new Set<Promise<void>>();\n\n return new Promise((resolve) => {\n rl.on(\"line\", (line) => {\n const trimmed = line.trim();\n if (!trimmed) return;\n const work = (async () => {\n let message: unknown;\n try {\n message = JSON.parse(trimmed);\n } catch {\n output.write(`${JSON.stringify(rpcError(null, -32700, \"Parse error\"))}\\n`);\n return;\n }\n try {\n const response = await handler(message);\n if (response !== null) output.write(`${JSON.stringify(response)}\\n`);\n } catch (err) {\n process.stderr.write(`decionis-mcp: handler error: ${String(err)}\\n`);\n }\n })();\n inFlight.add(work);\n void work.finally(() => inFlight.delete(work));\n });\n rl.on(\"close\", () => {\n // stdin EOF: drain in-flight handlers so no response is lost.\n void Promise.allSettled([...inFlight]).then(() => resolve());\n });\n });\n }\n}\n\n/**\n * Build the message handler. Returns `null` for notifications (no reply) and\n * a JSON-RPC response object otherwise.\n */\nexport function createMcpHandler(options: { serverInfo: ServerInfo; tools: ToolDefinition[] }) {\n const handler = new McpMessageHandler(options);\n return async function handleMessage(message: unknown): Promise<JsonRpcResponse | null> {\n return handler.handle(message);\n };\n}\n\n/**\n * Run the handler over stdio: one JSON message per line in, one per line out.\n * Only protocol JSON is ever written to stdout; diagnostics go to stderr.\n */\nexport function runStdioServer(\n handler: (message: unknown) => Promise<JsonRpcResponse | null>,\n streams: { input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream } = {},\n): Promise<void> {\n return McpStdioServer.run(handler, streams);\n}\n","/**\n * The Decionis MCP tools: read the repo's DECIONIS_POLICY.md, evaluate a\n * candidate action against it through the real protocol evaluator, run the\n * self-contained one-minute demo, and explain the verdict vocabulary — so\n * coding agents can check execution-authority constraints BEFORE committing\n * or triggering anything. All four are read-only, credential-free, and\n * networkless: the \"approval gate\" a cautious MCP client shows for\n * side-effectful tools has nothing to gate here.\n */\n\nimport { LocalDecionisGateway, normalizeVerdict } from \"./Gateway.js\";\nimport { PolicyFileRepository } from \"./agent/PolicyFileRepository.js\";\nimport { sha256Hex } from \"./RulesBlock.js\";\nimport type { ToolContent, ToolDefinition } from \"./Server.js\";\n\nconst text = (value: unknown): ToolContent[] => [\n { type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2) },\n];\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nconst VERDICT_HELP = `# Decionis verdicts and rule grammar\n\n**Verdicts** (a rule's \\`action\\`): \\`allow\\` (execute), \\`block\\` (never execute),\n\\`restrain\\` (hold for human review), \\`escalate\\` (require an authorized approver).\nThe protocol reports outcomes as APPROVE / REJECT / REVIEW / ESCALATE; this server\nalso returns the normalized verdict (allow / block / review / escalate). When no\nrule matches, the platform holds the decision for review (outcome REVIEW).\n\n**Rules block** (in DECIONIS_POLICY.md):\n\\`\\`\\`decionis\n{ \"version\": 1, \"rules\": [\n { \"name\": \"Block deploys during a change freeze\",\n \"priority\": 100, \"domain\": \"*\",\n \"all\": [{ \"field\": \"context.change_freeze\", \"op\": \"eq\", \"value\": true }],\n \"action\": \"block\" } ] }\n\\`\\`\\`\n\n- Each rule has exactly one of \\`all\\` (AND) / \\`any\\` (OR).\n- Operators: eq, ne/neq, gt, gte, lt, lte, in (values array), not_in (values array),\n exists, contains, matches (case-insensitive regex). Equality coerces numbers,\n booleans, and lowercased text; arrays match on any element.\n- Fields resolve against the decision payload: \\`context.<key>\\` reads payload keys,\n \\`decision_type\\` derives from the payload's \\`action\\` label, then the workflow key.\n- Give every rule an explicit \\`priority\\` (higher evaluates first) and keep\n \\`\"domain\": \"*\"\\` so it applies to every decision the repo gates.\n\n**Before committing or running anything risky**, call \\`decionis_evaluate\\` with the\naction you intend to take (e.g. {\"action\": \"production-deploy\", \"agent_generated\": true})\nand abide by the verdict: allow → proceed; block → do not proceed; review/escalate →\nstop and ask a human.`;\n\n/**\n * The one-minute demo: a self-contained policy plus four canned intents, one\n * per wire outcome. Everything runs through the real protocol evaluator\n * in-process — no account, no network, no policy file on disk, nothing\n * recorded — so an agent meeting Decionis for the first time can see a\n * verdict without a human at the keyboard to approve anything.\n */\nconst DEMO_POLICY = `# Decionis demo policy\n\nThree rules and a default: refunds under the desk limit run, refunds over it\nwait for a named approver, deploys during a change freeze never run, and\nanything the policy has no opinion on is held for review.\n\n\\`\\`\\`decionis\n{ \"version\": 1, \"rules\": [\n { \"name\": \"Block production deploys during a change freeze\",\n \"priority\": 100, \"domain\": \"*\",\n \"all\": [{ \"field\": \"context.change_freeze\", \"op\": \"eq\", \"value\": true }],\n \"action\": \"block\" },\n { \"name\": \"Escalate refunds over the desk limit\",\n \"priority\": 90, \"domain\": \"*\",\n \"all\": [{ \"field\": \"context.amount\", \"op\": \"gt\", \"value\": 1000 }],\n \"action\": \"escalate\" },\n { \"name\": \"Allow refunds within the desk limit\",\n \"priority\": 80, \"domain\": \"*\",\n \"all\": [{ \"field\": \"context.amount\", \"op\": \"lte\", \"value\": 1000 }],\n \"action\": \"allow\" } ] }\n\\`\\`\\`\n`;\n\nconst DEMO_INTENTS: ReadonlyArray<{\n readonly label: string;\n readonly payload: Record<string, unknown>;\n readonly shows: string;\n}> = [\n {\n label: \"Refund $180 — within the desk limit\",\n payload: { action: \"issue-refund\", amount: 180, agent_generated: true },\n shows: \"Within policy: execution continues, and the rule that allowed it is named.\",\n },\n {\n label: \"Refund $7,500 — over the desk limit\",\n payload: { action: \"issue-refund\", amount: 7500, agent_generated: true },\n shows: \"Held short of execution and routed to a named approver — not refused.\",\n },\n {\n label: \"Production deploy during a change freeze\",\n payload: { action: \"production-deploy\", change_freeze: true, agent_generated: true },\n shows: \"Refused outright: nobody is asked to approve it.\",\n },\n {\n label: \"Export customer data — no rule covers it\",\n payload: { action: \"export-customer-data\", destination: \"personal-email\" },\n shows: \"No rule matched, so the decision queues for review — unmatched intents fail safe.\",\n },\n];\n\n/** Builds the Decionis tool set bound to a local gateway. */\nexport class DecionisTools {\n constructor(\n private readonly gateway: LocalDecionisGateway,\n private readonly policyFiles: PolicyFileRepository = new PolicyFileRepository(),\n private readonly additionalTools: ToolDefinition[] = [],\n ) {}\n\n build(): ToolDefinition[] {\n const gateway = this.gateway;\n return [\n {\n name: \"decionis_read_policy\",\n title: \"Read Repository Policy\",\n description:\n \"Read and compile the repo's DECIONIS_POLICY.md execution policy: path, sha256, and the \" +\n \"enforceable rules (name, verdict, priority, domain) or compile errors. Use this to learn \" +\n \"what this repository allows, blocks, restrains, or escalates.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"Policy file path (default: $DECIONIS_POLICY_PATH or ./DECIONIS_POLICY.md)\",\n },\n },\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (args) => {\n const file = await this.policyFiles.read(args.path);\n if (!file.ok) return { content: text(file.message), isError: true };\n const compiled = gateway.compile(file.content);\n return {\n content: text({\n path: file.path,\n sha256: sha256Hex(file.content),\n bytes: Buffer.byteLength(file.content, \"utf8\"),\n rules:\n compiled === null\n ? \"no ```decionis rules block — the file is prose-only documentation\"\n : compiled.errors.length > 0\n ? { compile_errors: compiled.errors }\n : compiled.rules.map((rule) => ({\n name: rule.name,\n verdict: rule.then.action,\n priority: rule.priority,\n domain: rule.decision_domain,\n when: rule.when,\n })),\n }),\n };\n },\n },\n {\n name: \"decionis_evaluate\",\n title: \"Evaluate Candidate Action Locally\",\n description:\n \"Evaluate a candidate action against the repo's DECIONIS_POLICY.md through the real Decionis \" +\n \"protocol evaluator, entirely locally (no network, no credentials, nothing recorded). Call this \" +\n \"BEFORE committing, deploying, migrating, or any risky action, and abide by the verdict: \" +\n \"allow → proceed; block → do not proceed; review/escalate → stop and involve a human.\",\n inputSchema: {\n type: \"object\",\n required: [\"payload\"],\n properties: {\n payload: {\n type: \"object\",\n description:\n 'The candidate action, e.g. {\"action\": \"production-deploy\", \"change_freeze\": true, \"agent_generated\": true}',\n },\n workflow_key: {\n type: \"string\",\n description: \"Optional workflow key for the gated surface.\",\n },\n mode: { type: \"string\", enum: [\"shadow\", \"enforce\"], description: \"Default: shadow.\" },\n path: { type: \"string\", description: \"Policy file path override.\" },\n },\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async (args) => {\n if (!isPlainObject(args.payload)) {\n return {\n content: text(\"`payload` must be a JSON object describing the action.\"),\n isError: true,\n };\n }\n const file = await this.policyFiles.read(args.path);\n if (!file.ok) return { content: text(file.message), isError: true };\n const workflowKey = typeof args.workflow_key === \"string\" ? args.workflow_key : null;\n\n const published = await gateway.publishPolicy(file.content, { workflowKey });\n if (!published.ok) {\n return {\n content: text({\n error: published.reason,\n details: published.errors,\n hint:\n published.reason === \"no_rules_block\"\n ? \"Add a ```decionis rules block to make the policy enforceable — see decionis_verdict_help.\"\n : \"Fix the rules block so it compiles; the platform enforces all-or-nothing.\",\n }),\n isError: true,\n };\n }\n\n const evaluated = await gateway.evaluate({\n payload: args.payload,\n workflowKey,\n mode: args.mode === \"enforce\" ? \"enforce\" : \"shadow\",\n });\n if (evaluated.status !== 200) {\n return {\n content: text({\n error: `protocol evaluation failed (HTTP ${evaluated.status})`,\n body: evaluated.body,\n }),\n isError: true,\n };\n }\n\n const body = evaluated.body;\n const policyEvaluation = isPlainObject(body.policy_evaluation)\n ? body.policy_evaluation\n : {};\n const evaluatedRuleCount =\n typeof policyEvaluation.evaluated_rule_count === \"number\"\n ? policyEvaluation.evaluated_rule_count\n : null;\n\n return {\n content: text({\n verdict: normalizeVerdict(body.outcome),\n outcome: body.outcome,\n resolution: policyEvaluation.resolution ?? null,\n selected_rule: policyEvaluation.selected_rule_name ?? null,\n matched_rule_count: policyEvaluation.matched_rule_count ?? null,\n evaluated_rule_count: evaluatedRuleCount,\n decision_domain: policyEvaluation.decision_domain ?? body.decision_domain ?? null,\n policy_version: published.version,\n policy_sha256: published.sha256,\n confidence: body.confidence ?? null,\n note:\n \"Local sandbox evaluation — nothing was recorded and no signed dossier was minted. \" +\n \"CI runs through decionis/govern produce the signed, verifiable record.\",\n ...(published.ruleCount > 0 && evaluatedRuleCount === 0\n ? {\n hint:\n `All ${published.ruleCount} compiled rule(s) were filtered out by the decision-domain ` +\n 'match before evaluation. Add \"domain\": \"*\" to each rule so it applies to every ' +\n \"decision this repo gates.\",\n }\n : {}),\n }),\n };\n },\n },\n {\n name: \"decionis_demo\",\n title: \"Run the One-Minute Demo\",\n description:\n \"See Decionis work in under a minute: runs four canned intents (refund within limit, refund \" +\n \"over limit, deploy during a change freeze, an action no rule covers) through the real \" +\n \"protocol evaluator with a built-in sample policy. Entirely local — no account, no API key, \" +\n \"no network, no policy file needed, nothing recorded. Call this on first contact with \" +\n \"Decionis; use decionis_evaluate to gate this repo's own actions afterwards.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async () => {\n const published = await gateway.publishPolicy(DEMO_POLICY, { workflowKey: null });\n if (!published.ok) {\n return {\n content: text({ error: \"demo policy failed to compile\", details: published.errors }),\n isError: true,\n };\n }\n const decisions: Array<Record<string, unknown>> = [];\n for (const intent of DEMO_INTENTS) {\n const evaluated = await gateway.evaluate({\n payload: intent.payload,\n workflowKey: null,\n mode: \"shadow\",\n });\n if (evaluated.status !== 200) {\n return {\n content: text({\n error: `protocol evaluation failed (HTTP ${evaluated.status})`,\n intent: intent.label,\n body: evaluated.body,\n }),\n isError: true,\n };\n }\n const body = evaluated.body;\n const policyEvaluation = isPlainObject(body.policy_evaluation)\n ? body.policy_evaluation\n : {};\n decisions.push({\n intent: intent.label,\n outcome: body.outcome,\n verdict: normalizeVerdict(body.outcome),\n selected_rule: policyEvaluation.selected_rule_name ?? null,\n what_this_shows: intent.shows,\n });\n }\n return {\n content: text({\n headline:\n \"Four intents, four outcomes — each decided by policy before execution, through the \" +\n \"same evaluator that runs in production.\",\n decisions,\n vocabulary:\n \"Wire outcomes are APPROVE / ESCALATE / REJECT / REVIEW — the wire spellings of the \" +\n \"three decision classes (allow / escalate / block). ESCALATE routes to a named \" +\n \"approver; REVIEW queues without one.\",\n note:\n \"Local sandbox — the sample policy above, nothing recorded, no signed dossier \" +\n \"minted. In production every decision leaves an Ed25519-signed Decision Dossier \" +\n \"anyone can verify offline against the published JWKS.\",\n next_steps: [\n \"Gate this repo's own actions: decionis_read_policy, then decionis_evaluate before anything risky.\",\n \"Watch real traffic read-only first: https://decionis.com/shadow-mode\",\n \"First governed decision with signed proof: https://decionis.com/docs/quickstart\",\n ],\n }),\n };\n },\n },\n {\n name: \"decionis_verdict_help\",\n title: \"Explain Decionis Verdicts\",\n description:\n \"Reference for Decionis verdicts (allow/block/restrain/escalate), the rules-block grammar and \" +\n \"operators, and how an agent should behave on each verdict.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n handler: async () => ({ content: text(VERDICT_HELP) }),\n },\n ...this.additionalTools,\n ];\n }\n}\n\n/** Functional alias for {@link DecionisTools.build}. */\nexport function createDecionisTools(\n gateway: LocalDecionisGateway,\n additionalTools: ToolDefinition[] = [],\n): ToolDefinition[] {\n return new DecionisTools(gateway, new PolicyFileRepository(), additionalTools).build();\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n bindKubernetesAuthorityAction,\n deriveKubernetesMaterialFacts,\n hashKubernetesObject,\n summarizeKubernetesObjectDiff,\n type DecionisAuthorityRequest,\n} from \"@decionis/sdk\";\nimport type { KubernetesCommandRunner } from \"./KubernetesCommandRunner.js\";\n\nexport interface KubernetesMcpConfiguration {\n organizationId: string;\n clusterId: string;\n actorId: string;\n policyVersion: string;\n grantTtlSeconds: number;\n}\n\nexport interface PlannedKubernetesAction {\n request: DecionisAuthorityRequest;\n operation: \"CREATE\" | \"UPDATE\";\n apiGroup: string;\n apiVersion: string;\n kind: string;\n resource: string;\n namespace: string | null;\n name: string;\n oldObjectDigest: string | null;\n proposedObjectDigest: string;\n materialDiff: ReturnType<typeof summarizeKubernetesObjectDiff>;\n materialFacts: ReturnType<typeof deriveKubernetesMaterialFacts>;\n executionObject: Record<string, unknown>;\n executionEndpoint: string | null;\n}\n\nexport class KubernetesActionPlanner {\n private readonly discoveryCache = new Map<string, Array<{ name: string; kind: string }>>();\n\n public constructor(\n private readonly config: KubernetesMcpConfiguration,\n private readonly runner: KubernetesCommandRunner,\n private readonly now: () => Date = () => new Date(),\n private readonly createId: () => string = randomUUID,\n ) {}\n\n public async planManifest(\n manifestPath: string,\n namespace: string | null,\n source: string,\n ): Promise<PlannedKubernetesAction[]> {\n if (!manifestPath.trim() || manifestPath.length > 2_000 || /[\\r\\n\\0]/.test(manifestPath)) {\n throw new Error(\"KUBERNETES_MANIFEST_PATH_INVALID\");\n }\n const namespaceArgs = namespace ? [\"--namespace\", namespace] : [];\n const proposed = this.objects(\n await this.jsonCommand([\n \"create\",\n \"--dry-run=client\",\n \"--output=json\",\n \"--filename\",\n manifestPath,\n ...namespaceArgs,\n ]),\n );\n if (proposed.length === 0 || proposed.length > 100) {\n throw new Error(\"KUBERNETES_MANIFEST_OBJECT_COUNT_INVALID\");\n }\n const current = this.objects(\n await this.jsonCommand([\n \"get\",\n \"--ignore-not-found\",\n \"--output=json\",\n \"--filename\",\n manifestPath,\n ...namespaceArgs,\n ]),\n );\n\n return Promise.all(\n proposed.map(async (object) => {\n const identity = this.identity(object, namespace);\n const oldObject =\n current.find((candidate) => this.sameIdentity(candidate, identity)) ?? null;\n const resource = await this.resourceName(\n identity.apiGroup,\n identity.apiVersion,\n identity.kind,\n );\n return this.build({\n object,\n oldObject,\n resource,\n subresource: null,\n source,\n ...identity,\n });\n }),\n );\n }\n\n public async planScale(input: {\n namespace: string;\n name: string;\n replicas: number;\n }): Promise<PlannedKubernetesAction> {\n if (!Number.isInteger(input.replicas) || input.replicas < 0 || input.replicas > 1_000_000) {\n throw new Error(\"KUBERNETES_REPLICA_COUNT_INVALID\");\n }\n const endpoint = `/apis/apps/v1/namespaces/${encodeURIComponent(input.namespace)}/deployments/${encodeURIComponent(input.name)}/scale`;\n const oldObject = this.record(await this.jsonCommand([\"get\", \"--raw\", endpoint]));\n const object = {\n ...oldObject,\n spec: { ...this.record(oldObject.spec), replicas: input.replicas },\n };\n return this.build({\n object,\n oldObject,\n apiGroup: \"apps\",\n apiVersion: \"v1\",\n kind: \"Scale\",\n resource: \"deployments\",\n subresource: \"scale\",\n namespace: input.namespace,\n name: input.name,\n source: \"mcp:k8s_scale\",\n executionEndpoint: endpoint,\n });\n }\n\n private build(input: {\n object: Record<string, unknown>;\n oldObject: Record<string, unknown> | null;\n apiGroup: string;\n apiVersion: string;\n kind: string;\n resource: string;\n subresource: string | null;\n namespace: string | null;\n name: string;\n source: string;\n executionEndpoint?: string;\n }): PlannedKubernetesAction {\n const capturedAt = this.now();\n const proposedObjectDigest = hashKubernetesObject(input.object);\n if (!proposedObjectDigest) throw new Error(\"KUBERNETES_OBJECT_DIGEST_MISSING\");\n const oldObjectDigest = hashKubernetesObject(input.oldObject);\n const materialDiff = summarizeKubernetesObjectDiff(\n input.oldObject,\n input.object,\n input.kind === \"Secret\",\n );\n const materialFacts = deriveKubernetesMaterialFacts({\n object: input.object,\n oldObject: input.oldObject,\n kind: input.kind,\n apiGroup: input.apiGroup,\n resource: input.resource,\n });\n const operation = input.oldObject ? \"UPDATE\" : \"CREATE\";\n const request = bindKubernetesAuthorityAction({\n organizationId: this.config.organizationId,\n clusterId: this.config.clusterId,\n policyVersion: this.config.policyVersion,\n policyRule: \"mcp-client-gate\",\n mode: \"ENFORCEMENT\",\n intentId: this.createId(),\n capturedAt: capturedAt.toISOString(),\n expiresAt: new Date(capturedAt.valueOf() + this.config.grantTtlSeconds * 1_000).toISOString(),\n actor: {\n id: this.config.actorId,\n type: \"KUBERNETES_CLIENT\",\n runtime: \"mcp\",\n trust_level: \"MCP_CONFIGURED\",\n },\n operation,\n apiGroup: input.apiGroup,\n apiVersion: input.apiVersion,\n kind: input.kind,\n resource: input.resource,\n subresource: input.subresource,\n namespace: input.namespace,\n name: input.name,\n oldObjectDigest,\n proposedObjectDigest,\n materialDiff,\n materialFacts,\n requestSource: input.source,\n });\n return {\n request,\n operation,\n apiGroup: input.apiGroup,\n apiVersion: input.apiVersion,\n kind: input.kind,\n resource: input.resource,\n namespace: input.namespace,\n name: input.name,\n oldObjectDigest,\n proposedObjectDigest,\n materialDiff,\n materialFacts,\n executionObject: input.object,\n executionEndpoint: input.executionEndpoint ?? null,\n };\n }\n\n private async resourceName(apiGroup: string, apiVersion: string, kind: string): Promise<string> {\n const key = `${apiGroup}/${apiVersion}`;\n let resources = this.discoveryCache.get(key);\n if (!resources) {\n const endpoint = apiGroup\n ? `/apis/${encodeURIComponent(apiGroup)}/${encodeURIComponent(apiVersion)}`\n : `/api/${encodeURIComponent(apiVersion)}`;\n const discovery = this.record(await this.jsonCommand([\"get\", \"--raw\", endpoint]));\n resources = Array.isArray(discovery.resources)\n ? discovery.resources.flatMap((candidate) => {\n const value = this.record(candidate);\n return typeof value.name === \"string\" &&\n typeof value.kind === \"string\" &&\n !value.name.includes(\"/\")\n ? [{ name: value.name, kind: value.kind }]\n : [];\n })\n : [];\n this.discoveryCache.set(key, resources);\n }\n const matched = resources.find((candidate) => candidate.kind === kind);\n if (!matched) throw new Error(\"KUBERNETES_RESOURCE_DISCOVERY_FAILED\");\n return matched.name;\n }\n\n private identity(object: Record<string, unknown>, fallbackNamespace: string | null) {\n const apiVersionValue = typeof object.apiVersion === \"string\" ? object.apiVersion : \"\";\n const kind = typeof object.kind === \"string\" ? object.kind : \"\";\n const metadata = this.record(object.metadata);\n const name = typeof metadata.name === \"string\" ? metadata.name : \"\";\n if (!apiVersionValue || !kind || !name) throw new Error(\"KUBERNETES_OBJECT_IDENTITY_INVALID\");\n const separator = apiVersionValue.indexOf(\"/\");\n const apiGroup = separator < 0 ? \"\" : apiVersionValue.slice(0, separator);\n const apiVersion = separator < 0 ? apiVersionValue : apiVersionValue.slice(separator + 1);\n const objectNamespace = typeof metadata.namespace === \"string\" ? metadata.namespace : null;\n return { apiGroup, apiVersion, kind, namespace: objectNamespace ?? fallbackNamespace, name };\n }\n\n private sameIdentity(\n object: Record<string, unknown>,\n expected: ReturnType<KubernetesActionPlanner[\"identity\"]>,\n ): boolean {\n const actual = this.identity(object, expected.namespace);\n return (\n actual.apiGroup === expected.apiGroup &&\n actual.apiVersion === expected.apiVersion &&\n actual.kind === expected.kind &&\n actual.namespace === expected.namespace &&\n actual.name === expected.name\n );\n }\n\n private async jsonCommand(args: string[]): Promise<unknown> {\n const output = await this.runner.run(args);\n if (Buffer.byteLength(output, \"utf8\") > 4 * 1024 * 1024) {\n throw new Error(\"KUBERNETES_COMMAND_OUTPUT_TOO_LARGE\");\n }\n try {\n return JSON.parse(output) as unknown;\n } catch {\n throw new Error(\"KUBERNETES_COMMAND_OUTPUT_INVALID\");\n }\n }\n\n private objects(input: unknown): Record<string, unknown>[] {\n const value = this.record(input);\n if (value.kind === \"List\" && Array.isArray(value.items)) {\n return value.items\n .map((item) => this.record(item))\n .filter((item) => Object.keys(item).length > 0);\n }\n return Object.keys(value).length > 0 ? [value] : [];\n }\n\n private record(input: unknown): Record<string, unknown> {\n return input && typeof input === \"object\" && !Array.isArray(input)\n ? (input as Record<string, unknown>)\n : {};\n }\n}\n","/**\n * Co-located inline agentic-checkout guard (design.agentic-inline-complete.md P1).\n *\n * Runs the deterministic gate **in-process** against a pre-synced signed policy\n * snapshot (surface, zero network), issues a bound Execution Grant on ALLOW\n * via an injected signer, and appends to the ledger asynchronously (off the hot\n * path). Crypto + ledger are injected so this stays light and the consumer owns\n * key management: a server passes the API's `issueExecutionGrant`; an edge guard\n * passes its own local signer.\n */\n\nimport {\n evaluateAgenticCheckoutInline,\n type AgenticBinding,\n type AgenticCheckoutRequest,\n type AgenticInlineDecision,\n type CartSignal,\n type PolicySnapshot,\n} from \"@decionis/surface\";\n\nexport interface AgenticGrant {\n token: string;\n jti?: string;\n expires_at?: string;\n binding?: AgenticBinding | null;\n}\n\n/** Issue a bound Execution Grant. Returns null when authority can't be minted. */\nexport type AgenticGrantIssuer = (input: {\n request: AgenticCheckoutRequest;\n binding: AgenticBinding | null;\n amount: number | undefined;\n}) => Promise<AgenticGrant | null>;\n\n/** Fire-and-forget accountability append — kept OFF the hot path. */\nexport type AgenticLedgerSink = (entry: {\n request: AgenticCheckoutRequest;\n decision: AgenticInlineDecision;\n grant: AgenticGrant | null;\n}) => void | Promise<void>;\n\nexport interface AgenticCheckoutGateConfig {\n /** A static pre-synced signed snapshot. Use this OR `getSnapshot`. */\n snapshot?: PolicySnapshot | null;\n /**\n * A snapshot provider (e.g. `createPolicySnapshotCache(...).get`) that returns\n * the current verified, fresh snapshot — or null to fail closed. Resolved BEFORE\n * the eval timer so `eval_ms` stays the pure network-free hot path.\n */\n getSnapshot?: () => Promise<PolicySnapshot | null | undefined>;\n issueGrant?: AgenticGrantIssuer;\n ledgerSink?: AgenticLedgerSink;\n}\n\nexport type AgenticGateResult = AgenticInlineDecision & {\n execution_grant: AgenticGrant | null;\n /** Deterministic gate eval duration in ms (the network-free hot path). */\n eval_ms: number;\n};\n\n/**\n * AgenticCheckoutGate is the class form of the inline guard built by\n * {@link createAgenticCheckoutGate}. `authorize` evaluates locally, mints a\n * bound grant on ALLOW (if a signer is injected), and fires the async ledger sink.\n */\nexport class AgenticCheckoutGate {\n private readonly config: AgenticCheckoutGateConfig;\n\n constructor(config: AgenticCheckoutGateConfig) {\n this.config = config;\n }\n\n authorize = async (input: {\n request: AgenticCheckoutRequest;\n signal: CartSignal;\n now?: Date;\n }): Promise<AgenticGateResult> => {\n const config = this.config;\n // Resolve the snapshot (cache hit, or a refresh-ahead pull) BEFORE timing —\n // eval_ms measures only the network-free deterministic gate.\n const snapshot = config.getSnapshot ? await config.getSnapshot() : config.snapshot;\n const start = process.hrtime.bigint();\n const decision = evaluateAgenticCheckoutInline({\n snapshot,\n request: input.request,\n signal: input.signal,\n now: input.now,\n });\n const eval_ms = Number(process.hrtime.bigint() - start) / 1e6;\n\n let grant: AgenticGrant | null = null;\n // Never sign authority for a cart policy never evaluated. A fail-open verdict\n // buys availability, not an attestation — mirrors the server route, which\n // returns execution_grant: null while the engine is unreachable.\n if (decision.decision === \"allow\" && !decision.degraded && config.issueGrant) {\n grant = await config.issueGrant({\n request: input.request,\n binding: decision.binding,\n amount: decision.amount,\n });\n }\n\n // Async, never awaited: the ledger append is for accountability, not a gate.\n if (config.ledgerSink) {\n const sink = config.ledgerSink;\n void Promise.resolve()\n .then(() => sink({ request: input.request, decision, grant }))\n .catch(() => undefined);\n }\n\n return { ...decision, execution_grant: grant, eval_ms };\n };\n}\n\n/**\n * Build an inline guard bound to a snapshot. `authorize` evaluates locally, mints a\n * bound grant on ALLOW (if a signer is injected), and fires the async ledger sink.\n *\n * Functional alias for {@link AgenticCheckoutGate}.\n */\nexport function createAgenticCheckoutGate(config: AgenticCheckoutGateConfig): {\n authorize(input: {\n request: AgenticCheckoutRequest;\n signal: CartSignal;\n now?: Date;\n }): Promise<AgenticGateResult>;\n} {\n return new AgenticCheckoutGate(config);\n}\n\n/**\n * The productized ACP / AP2 authorization result: a flat accept/decline shape an\n * agentic-commerce caller can act on directly. `authorized` reflects the gate's\n * verdict; with `{ requireGrant: true }` it becomes the strict, Phase-3-aligned\n * \"no bound grant, no authorization\" posture — an ALLOW without a minted\n * single-use Execution Grant is treated as NOT authorized.\n */\nexport interface AgenticAuthorization {\n authorized: boolean;\n /** Native ACP / AP2 status carried straight from the deterministic gate. */\n acp_status: AgenticGateResult[\"acp_status\"];\n execution_grant: AgenticGrant | null;\n /** A single-use, action-bound Execution Grant was minted. */\n grant_bound: boolean;\n reasons: string[];\n policy_version: string;\n /** The gate failed closed (e.g. missing/expired snapshot). */\n fail_closed: boolean;\n eval_ms: number;\n}\n\n/**\n * Map an {@link AgenticGateResult} to the flat ACP / AP2 authorization primitive.\n * Pass `{ requireGrant: true }` to require a bound Execution Grant for `authorized`\n * — the fail-closed posture that pairs with `enforceAndExecuteStrict`.\n */\nexport function toAgenticAuthorization(\n result: AgenticGateResult,\n opts?: { requireGrant?: boolean },\n): AgenticAuthorization {\n const grant_bound = result.execution_grant !== null;\n const allowed = result.decision === \"allow\";\n return {\n authorized: opts?.requireGrant ? allowed && grant_bound : allowed,\n acp_status: result.acp_status,\n execution_grant: result.execution_grant,\n grant_bound,\n reasons: result.reasons,\n policy_version: result.policy_version,\n fail_closed: result.fail_closed,\n eval_ms: result.eval_ms,\n };\n}\n\n/**\n * One-shot convenience: build the inline gate and authorize a single agentic\n * checkout, returning the flat {@link AgenticAuthorization}. For hot paths that\n * reuse a gate, construct {@link AgenticCheckoutGate} once instead.\n */\nexport async function authorizeAgenticCheckout(\n config: AgenticCheckoutGateConfig,\n input: { request: AgenticCheckoutRequest; signal: CartSignal; now?: Date },\n opts?: { requireGrant?: boolean },\n): Promise<AgenticAuthorization> {\n const result = await new AgenticCheckoutGate(config).authorize(input);\n return toAgenticAuthorization(result, opts);\n}\n","/**\n * Remote agentic-checkout gate — the Regional Secure Node / pre-flight consumption\n * path (design.agentic-inline-complete.md shapes 2 & 3, P3).\n *\n * For merchants who don't co-locate the inline guard: a thin typed client that\n * calls the deployed Decionis `POST /v1/agentic/checkout/authorize` and exposes\n * the same mental model as `createAgenticCheckoutGate`. Point `baseUrl` at a\n * Decionis-operated node in your region for low round-trip latency, or at the\n * central API. Crypto + ledger stay server-side; the merchant holds no keys.\n */\n\nimport type { AgenticCheckoutRequest } from \"@decionis/surface\";\n\nexport interface RemoteExecutionGrant {\n token: string;\n jti: string;\n key_id: string;\n expires_at: string;\n binding: { cart_hash?: string; payment_ref_hash?: string; intent_hash?: string } | null;\n}\n\nexport interface RemoteAgenticDecision {\n decision: \"allow\" | \"block\" | \"escalate\";\n acp_status: \"ready_for_payment\" | \"not_ready_for_payment\" | \"requires_escalation\";\n outcome: string | null;\n dossier_id: string | null;\n policy_version?: string;\n reason_codes?: string[];\n execution_grant: RemoteExecutionGrant | null;\n escalation: { override_id: string; status: string } | null;\n requires_human_approval?: boolean;\n signature_verified?: boolean;\n acp_version?: string;\n}\n\n/** Result of polling an escalation for its outcome (GET .../escalations/:id). */\nexport interface RemoteEscalationStatus {\n status: string;\n decision: \"allow\" | \"block\" | \"escalate\";\n acp_status: RemoteAgenticDecision[\"acp_status\"];\n already_issued?: boolean;\n execution_grant: RemoteExecutionGrant | null;\n}\n\nexport interface RemoteAgenticGateConfig {\n /** Base URL of the Decionis API / regional node (e.g. https://api.decionis.com). */\n baseUrl: string;\n /** Org-scoped API key. */\n apiKey: string;\n /** Org id, when the key isn't already org-scoped. */\n orgId?: string;\n fetchImpl?: typeof fetch;\n}\n\nexport interface RemoteAgenticGate {\n authorize(\n request: AgenticCheckoutRequest & {\n idempotency_key?: string;\n /** Optional `x-decionis-signature` over the raw body (when HMAC is enforced). */\n signature?: string;\n },\n ): Promise<RemoteAgenticDecision>;\n /** Poll an escalation; once a human has approved, the bound grant is returned once. */\n getEscalation(overrideId: string): Promise<RemoteEscalationStatus>;\n}\n\n/**\n * RemoteAgenticGateClient is the class form of the remote gate returned by\n * {@link createRemoteAgenticGate}.\n */\nexport class RemoteAgenticGateClient implements RemoteAgenticGate {\n private readonly config: RemoteAgenticGateConfig;\n private readonly doFetch: typeof fetch;\n private readonly base: string;\n\n constructor(config: RemoteAgenticGateConfig) {\n this.config = config;\n this.doFetch = config.fetchImpl ?? fetch;\n this.base = config.baseUrl.replace(/\\/+$/, \"\");\n }\n\n private headers(extra?: Record<string, string>) {\n return {\n authorization: `Bearer ${this.config.apiKey}`,\n \"content-type\": \"application/json\",\n ...extra,\n };\n }\n\n authorize = async (\n request: AgenticCheckoutRequest & {\n idempotency_key?: string;\n signature?: string;\n },\n ): Promise<RemoteAgenticDecision> => {\n const { signature, ...body } = request;\n const payload = JSON.stringify(\n this.config.orgId ? { org_id: this.config.orgId, ...body } : body,\n );\n const res = await this.doFetch(`${this.base}/v1/agentic/checkout/authorize`, {\n method: \"POST\",\n headers: this.headers(signature ? { \"x-decionis-signature\": signature } : undefined),\n body: payload,\n });\n const json = (await res.json()) as RemoteAgenticDecision & { error?: string };\n if (!res.ok) {\n // 401/503 etc. — surface a block so the caller fails closed by default.\n throw new Error(`agentic authorize failed (${res.status}): ${json.error ?? \"unknown\"}`);\n }\n return json;\n };\n\n getEscalation = async (overrideId: string): Promise<RemoteEscalationStatus> => {\n const q = this.config.orgId ? `?org_id=${encodeURIComponent(this.config.orgId)}` : \"\";\n const res = await this.doFetch(\n `${this.base}/v1/agentic/checkout/escalations/${encodeURIComponent(overrideId)}${q}`,\n { headers: this.headers() },\n );\n const json = (await res.json()) as RemoteEscalationStatus & { error?: string };\n if (!res.ok)\n throw new Error(`escalation poll failed (${res.status}): ${json.error ?? \"unknown\"}`);\n return json;\n };\n}\n\n/** Functional alias for {@link RemoteAgenticGateClient}. */\nexport function createRemoteAgenticGate(config: RemoteAgenticGateConfig): RemoteAgenticGate {\n return new RemoteAgenticGateClient(config);\n}\n","/**\n * Policy snapshot cache for the co-located inline guard\n * (design.agentic-snapshot-distribution.md P2.1).\n *\n * Pulls the org's signed PolicySnapshot from the Decionis pull endpoint, verifies\n * its Ed25519 signature against the published policy JWKS **at the edge**, caches\n * it, and refreshes **ahead of expiry** — so the guard's hot path (`createAgenticCheckoutGate`)\n * reads a verified snapshot with no network call. On fetch/verify failure it keeps\n * serving the last still-fresh snapshot; once that expires it returns null →\n * the gate fails closed. Fetchers are injected so this is unit-testable without HTTP.\n */\n\nimport {\n isPolicySnapshotFresh,\n policySnapshotRefreshWindowMs,\n verifyPolicySnapshotSignature,\n type PolicySnapshot,\n} from \"@decionis/surface\";\n\nexport interface PolicyJwks {\n keys: Array<Record<string, unknown>>;\n}\n\nexport interface SnapshotSource {\n /**\n * Fetch the current signed snapshot, or null on failure. `minVersion` is the\n * server-published revocation floor (P2.2) the guard must also enforce.\n */\n fetchSnapshot: () => Promise<{ snapshot: PolicySnapshot; minVersion?: string | null } | null>;\n /** Fetch the policy JWKS used to verify the snapshot signature, or null on failure. */\n fetchJwks: () => Promise<PolicyJwks | null>;\n}\n\nexport type PolicySnapshotCacheConfig = SnapshotSource & {\n /** Refresh when within this many ms of expiry (default 6h). */\n refreshSkewMs?: number;\n /**\n * Re-pull at least this often even while the cached snapshot is comfortably\n * fresh (default: the configured refresh window, 1h). Expiry-skew alone is not\n * enough — with a 24h TTL it would leave a guard on the same snapshot for\n * ~18h, so an emergency `min_version` bump (P2.2) would take that long to\n * revoke fleet-wide. This bounds that to one window.\n */\n refreshIntervalMs?: number;\n /** Clock seam for tests. */\n now?: () => number;\n /** Reject snapshots below this policy version (P2.2 revocation floor). */\n minVersion?: string;\n};\n\nexport interface PolicySnapshotCache {\n /** Verified, fresh snapshot — or null (→ gate fails closed). Refreshes ahead of expiry. */\n get(): Promise<PolicySnapshot | null>;\n}\n\nconst DEFAULT_SKEW_MS = 6 * 60 * 60 * 1000;\n\n/**\n * PolicySnapshotCacheStore is the class form of the cache returned by\n * {@link createPolicySnapshotCache}.\n */\nexport class PolicySnapshotCacheStore implements PolicySnapshotCache {\n private readonly config: PolicySnapshotCacheConfig;\n private readonly now: () => number;\n private readonly skew: number;\n private readonly refreshInterval: number;\n private cached: PolicySnapshot | null = null;\n private serverMinVersion: string | null = null;\n private inflight: Promise<void> | null = null;\n private lastAttemptAt: number | null = null;\n\n constructor(config: PolicySnapshotCacheConfig) {\n this.config = config;\n this.now = config.now ?? (() => Date.now());\n this.skew = config.refreshSkewMs ?? DEFAULT_SKEW_MS;\n this.refreshInterval = config.refreshIntervalMs ?? policySnapshotRefreshWindowMs();\n }\n\n private isFresh(s: PolicySnapshot | null): s is PolicySnapshot {\n return !!s && isPolicySnapshotFresh(s, new Date(this.now()));\n }\n\n private needsRefresh(s: PolicySnapshot | null): boolean {\n if (!s) return true;\n const exp = Date.parse(s.expiresAt);\n if (!Number.isFinite(exp) || this.now() > exp - this.skew) return true;\n // Refresh-ahead on a timer as well as near expiry, so a policy change or an\n // emergency revocation floor lands within one refresh window.\n return (\n this.refreshInterval > 0 &&\n (this.lastAttemptAt === null || this.now() - this.lastAttemptAt >= this.refreshInterval)\n );\n }\n\n /** Effective floor = the greater of the configured floor and the server-published one. */\n private effectiveFloor(): string | null {\n const floors = [this.config.minVersion, this.serverMinVersion].filter(\n (v): v is string => typeof v === \"string\" && v.length > 0,\n );\n return floors.length ? floors.sort().pop()! : null;\n }\n\n private belowFloor(s: PolicySnapshot): boolean {\n const floor = this.effectiveFloor();\n return !!floor && s.policyVersion < floor;\n }\n\n private async refresh(): Promise<void> {\n // Stamp the ATTEMPT, not the success: a failing origin is retried once per\n // window rather than on every hot-path get() while the last-good is served.\n this.lastAttemptAt = this.now();\n try {\n const [snapRes, jwks] = await Promise.all([\n this.config.fetchSnapshot(),\n this.config.fetchJwks(),\n ]);\n if (!snapRes || !jwks) return; // transient failure — keep last good\n if (typeof snapRes.minVersion === \"string\") this.serverMinVersion = snapRes.minVersion;\n const snapshot = snapRes.snapshot;\n if (this.belowFloor(snapshot)) return; // revoked policy version — reject\n if (!verifyPolicySnapshotSignature(snapshot, jwks)) return; // tampered/unverifiable — reject\n if (!isPolicySnapshotFresh(snapshot, new Date(this.now()))) return; // already stale — reject\n this.cached = snapshot;\n } catch {\n // keep last good\n }\n }\n\n get = async (): Promise<PolicySnapshot | null> => {\n if (this.needsRefresh(this.cached)) {\n // Coalesce concurrent refreshes.\n this.inflight ??= this.refresh().finally(() => {\n this.inflight = null;\n });\n await this.inflight;\n }\n return this.isFresh(this.cached) && !this.belowFloor(this.cached) ? this.cached : null;\n };\n}\n\n/**\n * HttpPolicySnapshotSource is the class form of the convenience source built by\n * {@link httpPolicySnapshotSource}. The guard usually injects its own fetcher;\n * this wires the standard pull endpoint + policy JWKS for the common case.\n */\nexport class HttpPolicySnapshotSource implements SnapshotSource {\n private readonly input: {\n baseUrl: string;\n apiKey: string;\n orgId?: string;\n fetchImpl?: typeof fetch;\n };\n private readonly doFetch: typeof fetch;\n private readonly base: string;\n private readonly auth: { authorization: string };\n private readonly orgQuery: string;\n\n constructor(input: {\n baseUrl: string;\n apiKey: string;\n orgId?: string;\n fetchImpl?: typeof fetch;\n }) {\n this.input = input;\n this.doFetch = input.fetchImpl ?? fetch;\n this.base = input.baseUrl.replace(/\\/+$/, \"\");\n this.auth = { authorization: `Bearer ${input.apiKey}` };\n this.orgQuery = input.orgId ? `?org_id=${encodeURIComponent(input.orgId)}` : \"\";\n }\n\n fetchSnapshot = async (): Promise<{\n snapshot: PolicySnapshot;\n minVersion?: string | null;\n } | null> => {\n const res = await this.doFetch(`${this.base}/v1/agentic/policy/snapshot${this.orgQuery}`, {\n headers: this.auth,\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { snapshot?: PolicySnapshot; min_version?: string | null };\n return body.snapshot ? { snapshot: body.snapshot, minVersion: body.min_version ?? null } : null;\n };\n\n fetchJwks = async (): Promise<PolicyJwks | null> => {\n const res = await this.doFetch(`${this.base}/v1/.well-known/decionis-policy-jwks.json`);\n if (!res.ok) return null;\n return (await res.json()) as PolicyJwks;\n };\n}\n\n/** Functional alias for {@link PolicySnapshotCacheStore}. */\nexport function createPolicySnapshotCache(config: PolicySnapshotCacheConfig): PolicySnapshotCache {\n return new PolicySnapshotCacheStore(config);\n}\n\n/**\n * Convenience source backed by the Decionis P2.0 endpoints over HTTP. The guard\n * usually injects its own fetcher; this wires the standard pull endpoint + policy\n * JWKS for the common case.\n *\n * Functional alias for {@link HttpPolicySnapshotSource}.\n */\nexport function httpPolicySnapshotSource(input: {\n baseUrl: string;\n apiKey: string;\n orgId?: string;\n fetchImpl?: typeof fetch;\n}): SnapshotSource {\n return new HttpPolicySnapshotSource(input);\n}\n","type FetchLike = typeof fetch;\n\nexport type DecionisAgentProvider = \"openai\" | \"anthropic\" | \"github_copilot\" | \"custom\";\n\nexport interface DecionisAgentTaskTarget {\n system: string;\n operation: string;\n endpoint: string;\n}\n\nexport interface DecionisAgentTaskIntent {\n orgId: string;\n userId: string;\n provider: DecionisAgentProvider;\n model: string;\n sessionId: string;\n idempotencyKey: string;\n prompt: {\n sha256?: string | null;\n characterCount?: number | null;\n estimatedInputTokens?: number | null;\n };\n limits: {\n maxOutputTokens: number;\n estimatedToolCalls?: number;\n };\n downstreamTarget: DecionisAgentTaskTarget;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DecionisAgentTokenUsage {\n inputTokens: number;\n outputTokens: number;\n cachedInputTokens?: number;\n cacheCreationInputTokens?: number;\n cacheCreationOneHourInputTokens?: number;\n toolCalls?: number;\n}\n\nexport interface DecionisAgentTaskReservation {\n reservationId: string;\n orgId: string;\n userId: string;\n provider: DecionisAgentProvider;\n model: string;\n status: \"RESERVED\" | \"RECONCILED\" | \"RELEASED\" | \"EXPIRED\";\n reservedCostUsd: number;\n actualCostUsd: number | null;\n downstreamTarget: DecionisAgentTaskTarget;\n expiresAt: string;\n grantIssuedAt: string | null;\n [key: string]: unknown;\n}\n\nexport interface DecionisAgentTaskReserveResult {\n allowed: boolean;\n reasonCodes: string[];\n reservation: DecionisAgentTaskReservation | null;\n executionToken: string | null;\n executionTokenExpiresAt: string | null;\n}\n\nexport interface DecionisAgentTaskGatewayOptions {\n gatewayBaseUrl: string;\n apiKey: string;\n fetch?: FetchLike;\n timeoutMs?: number;\n}\n\nexport interface DecionisAgentProxyContext {\n orgId: string;\n userId: string;\n sessionId: string;\n idempotencyKey: string;\n estimatedToolCalls?: number;\n host?: \"codex\" | \"copilot\" | \"claude\" | string;\n}\n\nexport class DecionisAgentTaskGatewayError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly body: unknown,\n ) {\n super(message);\n this.name = \"DecionisAgentTaskGatewayError\";\n }\n}\n\n/** Reusable pre-prompt reservation client for API, proxy, sandbox, and downstream gates. */\nexport class DecionisAgentTaskGateway {\n private readonly fetchImpl: FetchLike;\n private readonly baseUrl: string;\n\n constructor(private readonly options: DecionisAgentTaskGatewayOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n this.baseUrl = options.gatewayBaseUrl.replace(/\\/+$/, \"\");\n }\n\n reserve(intent: DecionisAgentTaskIntent): Promise<DecionisAgentTaskReserveResult> {\n return this.request(\"/v1/agent/tasks/reserve\", {\n method: \"POST\",\n body: JSON.stringify({\n ...intent,\n prompt: {\n sha256: intent.prompt.sha256 ?? null,\n characterCount: intent.prompt.characterCount ?? null,\n estimatedInputTokens: intent.prompt.estimatedInputTokens ?? null,\n },\n limits: {\n maxOutputTokens: intent.limits.maxOutputTokens,\n estimatedToolCalls: intent.limits.estimatedToolCalls ?? 0,\n },\n metadata: intent.metadata ?? {},\n }),\n });\n }\n\n get(reservationId: string, orgId: string) {\n const query = new URLSearchParams({ orgId });\n return this.request<{ reservation: DecionisAgentTaskReservation }>(\n `/v1/agent/tasks/${encodeURIComponent(reservationId)}?${query.toString()}`,\n { method: \"GET\" },\n );\n }\n\n authorizeEgress(input: { reservationId: string; orgId: string; executionToken: string }) {\n return this.request<{\n allowed: boolean;\n authorizedTarget: DecionisAgentTaskTarget;\n reservationId: string;\n }>(`/v1/agent/tasks/${encodeURIComponent(input.reservationId)}/authorize-egress`, {\n method: \"POST\",\n body: JSON.stringify({\n orgId: input.orgId,\n executionToken: input.executionToken,\n }),\n });\n }\n\n reconcile(input: { reservationId: string; orgId: string; usage: DecionisAgentTokenUsage }) {\n return this.request<{ reservation: DecionisAgentTaskReservation }>(\n `/v1/agent/tasks/${encodeURIComponent(input.reservationId)}/reconcile`,\n {\n method: \"POST\",\n body: JSON.stringify({\n orgId: input.orgId,\n usage: {\n inputTokens: input.usage.inputTokens,\n outputTokens: input.usage.outputTokens,\n cachedInputTokens: input.usage.cachedInputTokens ?? 0,\n cacheCreationInputTokens: input.usage.cacheCreationInputTokens ?? 0,\n cacheCreationOneHourInputTokens: input.usage.cacheCreationOneHourInputTokens ?? 0,\n toolCalls: input.usage.toolCalls ?? 0,\n },\n }),\n },\n );\n }\n\n release(input: { reservationId: string; orgId: string; reason?: string }) {\n return this.request<{ reservation: DecionisAgentTaskReservation }>(\n `/v1/agent/tasks/${encodeURIComponent(input.reservationId)}/release`,\n {\n method: \"POST\",\n body: JSON.stringify({\n orgId: input.orgId,\n reason: input.reason ?? \"CALLER_RELEASED\",\n }),\n },\n );\n }\n\n /** Base URL for the official OpenAI or Anthropic SDK. */\n providerBaseUrl(provider: \"openai\" | \"anthropic\"): string {\n return `${this.baseUrl}/v1/agent/proxy/${provider}/v1`;\n }\n\n /** Headers attached to an official SDK client or individual provider request. */\n providerHeaders(context: DecionisAgentProxyContext): Record<string, string> {\n return {\n \"x-decionis-api-key\": this.options.apiKey,\n \"x-decionis-org-id\": context.orgId,\n \"x-decionis-user-id\": context.userId,\n \"x-decionis-session-id\": context.sessionId,\n \"x-decionis-idempotency-key\": context.idempotencyKey,\n \"x-decionis-estimated-tool-calls\": String(context.estimatedToolCalls ?? 0),\n ...(context.host ? { \"x-decionis-agent-host\": context.host } : {}),\n };\n }\n\n private async request<TResult>(\n path: string,\n init: { method: \"GET\" | \"POST\"; body?: string },\n ): Promise<TResult> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs ?? 4_000);\n try {\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n ...init,\n headers: {\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"x-decionis-api-key\": this.options.apiKey,\n },\n signal: controller.signal,\n });\n const body = await response.json().catch(() => null);\n if (!response.ok) {\n throw new DecionisAgentTaskGatewayError(\n `Decionis agent task gateway returned HTTP ${response.status}`,\n response.status,\n body,\n );\n }\n return body as TResult;\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\nexport function createDecionisAgentTaskGateway(\n options: DecionisAgentTaskGatewayOptions,\n): DecionisAgentTaskGateway {\n return new DecionisAgentTaskGateway(options);\n}\n","import { z } from \"zod\";\n\nexport const authoritySelectorSchema = z.discriminatedUnion(\"kind\", [\n z\n .object({\n kind: z.literal(\"ROLE\"),\n role_id: z.string().regex(/^[A-Z][A-Z0-9_]{1,63}$/),\n })\n .strict(),\n z\n .object({\n kind: z.literal(\"PRINCIPAL\"),\n principal_id: z.string().min(1).max(200),\n })\n .strict(),\n]);\n\nexport const authorityVerificationRequirementsSchema = z\n .object({\n level: z.enum([\"STANDARD\", \"HIGH_CONFIDENCE\"]),\n methods: z\n .array(z.enum([\"WEBAUTHN\", \"MOBILE_DEVICE\", \"ACTIVE_LIVENESS\"]))\n .min(1)\n .max(3),\n hardware_pki_required: z.boolean(),\n disallow_virtual_cameras: z.boolean(),\n mobile_device_policy: z.enum([\"WEB_OR_JIT_DEVICE\", \"MANAGED_DEVICE_REQUIRED\"]).optional(),\n trusted_ip_regions: z.array(z.string().trim().min(1).max(64)).min(1).max(100).optional(),\n })\n .strict()\n .superRefine((requirements, context) => {\n if (new Set(requirements.methods).size !== requirements.methods.length) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"methods\"],\n message: \"verification methods must be unique\",\n });\n }\n if (\n requirements.trusted_ip_regions !== undefined &&\n new Set(requirements.trusted_ip_regions).size !== requirements.trusted_ip_regions.length\n ) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"trusted_ip_regions\"],\n message: \"trusted IP regions must be unique\",\n });\n }\n });\n\nexport const authorityResolutionPolicySchema = z\n .object({\n quorum: z.literal(1),\n delegation: z.enum([\"DISALLOWED\", \"REQUIREMENT_REFRESH\"]),\n fallback_role_ids: z\n .array(z.string().regex(/^[A-Z][A-Z0-9_]{1,63}$/))\n .max(10)\n .default([]),\n })\n .strict()\n .superRefine((policy, context) => {\n if (new Set(policy.fallback_role_ids).size !== policy.fallback_role_ids.length) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"fallback_role_ids\"],\n message: \"fallback role ids must be unique\",\n });\n }\n });\n\nconst originatorSchema = z\n .object({\n organization_id: z.string().min(1).max(200),\n organization_name: z.string().trim().min(1).max(160),\n actor_id: z.string().min(1).max(200).optional(),\n display_name: z.string().trim().min(1).max(160).optional(),\n role: z.string().trim().min(1).max(120).optional(),\n provenance: z.enum([\"AUTHENTICATED_TENANT\", \"VERIFIED_CONNECTOR\", \"CALLER_DECLARED\"]),\n })\n .strict();\n\nconst displayFieldSchema = z\n .object({\n key: z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),\n label: z.string().trim().min(1).max(120),\n value: z.string().trim().min(1).max(500),\n })\n .strict();\n\nconst presentationSchema = z\n .object({\n locale: z\n .string()\n .min(2)\n .max(35)\n .regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/),\n title: z.string().trim().min(1).max(160),\n description: z.string().trim().min(1).max(1_000),\n display_fields: z.array(displayFieldSchema).max(20),\n })\n .strict()\n .superRefine((presentation, context) => {\n const keys = presentation.display_fields.map((field) => field.key);\n if (new Set(keys).size !== keys.length) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"display_fields\"],\n message: \"display field keys must be unique\",\n });\n }\n });\n\n/** Exact `decionis.authority_requirement/1` object returned by an ESCALATE decision. */\nexport const decionisAuthorityRequirementSchema = z\n .object({\n requirement_version: z.literal(\"decionis.authority_requirement/1\"),\n requirement_id: z.string().min(8).max(200),\n source_decision_id: z.string().min(1).max(200),\n source_dossier_id: z.string().min(1).max(200),\n policy_version: z.string().min(1).max(120),\n policy_reason_codes: z\n .array(z.string().regex(/^[A-Z][A-Z0-9_]{1,119}$/))\n .min(1)\n .max(20),\n action_digest: z.string().regex(/^[0-9a-f]{64}$/),\n selector: authoritySelectorSchema,\n verification_requirements: authorityVerificationRequirementsSchema,\n resolution: authorityResolutionPolicySchema,\n originator: originatorSchema,\n presentation: presentationSchema,\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43,128}$/),\n issued_at: z.string().datetime(),\n expires_at: z.string().datetime(),\n })\n .strict()\n .superRefine((requirement, context) => {\n if (Date.parse(requirement.expires_at) <= Date.parse(requirement.issued_at)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"expires_at\"],\n message: \"expires_at must be later than issued_at\",\n });\n }\n if (\n requirement.selector.kind === \"ROLE\" &&\n requirement.resolution.fallback_role_ids.includes(requirement.selector.role_id)\n ) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"resolution\", \"fallback_role_ids\"],\n message: \"fallback roles must not repeat the primary role\",\n });\n }\n });\n\nexport type DecionisAuthorityRequirement = z.infer<typeof decionisAuthorityRequirementSchema>;\n","import { z } from \"zod\";\nimport { decionisAuthorityRequirementSchema } from \"./AuthorityRequirement\";\n\nexport const decionisEvaluateModeSchema = z.enum([\"SHADOW\", \"PARALLEL\", \"ENFORCEMENT\"]);\nexport const decionisEvaluateOutcomeSchema = z.enum([\"APPROVE\", \"ESCALATE\", \"REJECT\", \"REVIEW\"]);\n\nexport const decionisEvaluateDecisionRequestSchema = z.object({\n org_id: z.string().uuid(),\n decision_type: z.string().min(1).max(120),\n amount: z.number().optional(),\n risk_score: z.number().min(0).max(1).optional(),\n channel: z.string().min(1).max(120).optional(),\n policy_version: z.string().min(1).max(120).optional(),\n objective_profile: z.string().min(1).max(120).optional(),\n mode: decionisEvaluateModeSchema.optional(),\n decision_band: z.string().min(1).max(120).optional(),\n transaction_type: z.string().min(1).max(120).optional(),\n workflow_key: z.string().min(1).max(120).optional(),\n vertical_pack: z.string().min(1).max(120).optional(),\n context: z.record(z.unknown()).optional(),\n idempotency_key: z.string().min(1).max(180).optional(),\n});\n\nconst governanceMetricsSchema = z.object({\n override_drift_rate: z.number(),\n governance_tension_index: z.number(),\n boundary_volatility_score: z.number(),\n decision_volume_under_governance: z.number(),\n});\n\nconst policyGuardSchema = z\n .object({\n status: z.enum([\"ready\", \"configured\", \"missing\"]),\n requires_manual_review: z.boolean(),\n total_bundle_count: z.number(),\n active_bundle_count: z.number(),\n active_bundle_id: z.string().uuid().nullable(),\n active_bundle_version: z.string().nullable(),\n active_effective_from: z.string().nullable(),\n active_effective_to: z.string().nullable(),\n latest_bundle_id: z.string().uuid().nullable(),\n latest_bundle_version: z.string().nullable(),\n latest_effective_from: z.string().nullable(),\n latest_effective_to: z.string().nullable(),\n reason: z\n .enum([\n \"missing_org_policy_bundle\",\n \"no_active_org_policy_bundle\",\n \"requested_policy_bundle_not_found\",\n ])\n .nullable(),\n evaluated_at: z.string(),\n })\n .optional();\n\nconst policyEvaluationSchema = z\n .object({\n resolution: z.enum([\n \"policy_guard_blocked\",\n \"matched_rule\",\n \"no_matching_rule\",\n \"missing_required_signals\",\n ]),\n bundle_id: z.string().uuid().nullable(),\n bundle_version: z.string().nullable(),\n evaluated_at: z.string(),\n decision_domain: z.string(),\n evaluated_rule_count: z.number(),\n matched_rule_count: z.number(),\n matched_rule_ids: z.array(z.string()),\n selected_rule_id: z.string().nullable(),\n selected_rule_name: z.string().nullable(),\n selected_rule_action: z\n .enum([\"REQUIRE_REVIEW\", \"AUTO_APPROVE\", \"AUTO_REJECT\", \"ESCALATE\", \"REQUEST_INFO\"])\n .nullable(),\n selected_rule_priority: z.number().nullable(),\n selected_rule_rationale: z.string().nullable(),\n selected_rule_severity: z.enum([\"routine\", \"elevated\", \"urgent\"]).nullable(),\n selected_rule_assignee_role: z.string().nullable(),\n selected_rule_sla_minutes: z.number().nullable(),\n selected_rule_authority: z.unknown().optional(),\n missing_required_signals: z.array(z.string()).optional(),\n })\n .optional();\n\nconst policySnapshotSchema = z\n .object({\n policy_version: z.string(),\n policy_bundle_id: z.string().uuid().nullable(),\n rules_sha256: z.string().nullable(),\n parameters_sha256: z.string().nullable(),\n effective_from: z.string().nullable(),\n effective_to: z.string().nullable(),\n evaluated_at: z.string(),\n source: z.enum([\"org_policy_bundle\", \"policy_guard\", \"request_default\"]),\n })\n .optional();\n\nexport const decionisEvaluateDecisionResponseSchema = z.object({\n outcome: decionisEvaluateOutcomeSchema,\n confidence: z.number(),\n policy_version: z.string(),\n objective_profile: z.string(),\n dossier_id: z.string().uuid(),\n dossier_sha256: z.string().nullable().optional(),\n evaluation_id: z.string().uuid(),\n decision_resolution_id: z.string().uuid().nullable().optional(),\n ledger_entry_id: z.string().uuid().nullable().optional(),\n ledger_entry_hash: z.string().nullable().optional(),\n mode: decionisEvaluateModeSchema,\n reason_codes: z.array(z.string().min(1)).optional(),\n fallback_to_legacy: z.boolean(),\n fallback_reason: z.string().nullable().optional(),\n reconciliation_required: z.boolean().optional(),\n reconciliation_status: z\n .enum([\"NOT_REQUIRED\", \"PENDING\", \"IN_PROGRESS\", \"COMPLETED\", \"FAILED\"])\n .optional(),\n decision_domain: z.string().optional(),\n governance_metrics: governanceMetricsSchema,\n policy_guard: policyGuardSchema,\n policy_evaluation: policyEvaluationSchema,\n policy_snapshot: policySnapshotSchema.nullable().optional(),\n authority_requirement: decionisAuthorityRequirementSchema.optional(),\n idempotent_replay: z.boolean(),\n});\n\nexport type DecionisEvaluateMode = z.infer<typeof decionisEvaluateModeSchema>;\nexport type DecionisEvaluateOutcome = z.infer<typeof decionisEvaluateOutcomeSchema>;\nexport type DecionisEvaluateDecisionRequest = z.infer<typeof decionisEvaluateDecisionRequestSchema>;\nexport type DecionisEvaluateDecisionResponse = z.infer<\n typeof decionisEvaluateDecisionResponseSchema\n>;\n\nexport type DecionisRequestDefaults = Partial<\n Omit<DecionisEvaluateDecisionRequest, \"org_id\" | \"decision_type\">\n>;\n","import {\n type DecionisEvaluateDecisionRequest,\n type DecionisEvaluateDecisionResponse,\n type DecionisRequestDefaults,\n decionisEvaluateDecisionRequestSchema,\n decionisEvaluateDecisionResponseSchema,\n} from \"./Contracts\";\n\ntype FetchLike = typeof fetch;\n\nexport interface DecionisDecisionExecutor {\n evaluateDecision(\n request: DecionisEvaluateDecisionRequest,\n options?: { idempotencyKey?: string | null },\n ): Promise<DecionisEvaluateDecisionResponse>;\n}\n\nexport interface DecionisNodeSdkOptions {\n baseUrl: string;\n apiKey: string;\n route?: string;\n timeoutMs?: number;\n fetch?: FetchLike;\n defaultHeaders?: Record<string, string>;\n defaultRequest?: DecionisRequestDefaults;\n}\n\nexport class DecionisNodeSdkError extends Error {\n status: number;\n body: unknown;\n\n constructor(message: string, options: { status: number; body: unknown }) {\n super(message);\n this.name = \"DecionisNodeSdkError\";\n this.status = options.status;\n this.body = options.body;\n }\n}\n\n/**\n * DecionisNodeSdk is the class form of the decision executor returned by\n * {@link createDecionisNodeSdk}.\n */\nexport class DecionisNodeSdk implements DecionisDecisionExecutor {\n private readonly options: DecionisNodeSdkOptions;\n private readonly baseUrl: string;\n private readonly route: string;\n private readonly fetchImpl: FetchLike;\n\n constructor(options: DecionisNodeSdkOptions) {\n this.options = options;\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.route = options.route ?? \"/v1/protocol/evaluate-decision\";\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n static mergeDecisionRequest(\n defaults: DecionisRequestDefaults | undefined,\n request: DecionisEvaluateDecisionRequest,\n ): DecionisEvaluateDecisionRequest {\n return decionisEvaluateDecisionRequestSchema.parse({\n ...defaults,\n ...request,\n context: {\n ...(defaults?.context ?? {}),\n ...(request.context ?? {}),\n },\n });\n }\n\n evaluateDecision = async (\n request: DecionisEvaluateDecisionRequest,\n invokeOptions?: { idempotencyKey?: string | null },\n ): Promise<DecionisEvaluateDecisionResponse> => {\n const payload = mergeDecisionRequest(this.options.defaultRequest, request);\n const controller = new AbortController();\n const timeoutMs = this.options.timeoutMs ?? 4000;\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n const idempotencyKey = invokeOptions?.idempotencyKey ?? payload.idempotency_key ?? null;\n\n try {\n const response = await this.fetchImpl(`${this.baseUrl}${this.route}`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${this.options.apiKey}`,\n \"content-type\": \"application/json\",\n ...(idempotencyKey ? { \"idempotency-key\": idempotencyKey } : {}),\n ...(this.options.defaultHeaders ?? {}),\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n const body = await response.json().catch(() => null);\n if (!response.ok) {\n throw new DecionisNodeSdkError(`Decionis request failed with status ${response.status}`, {\n status: response.status,\n body,\n });\n }\n return decionisEvaluateDecisionResponseSchema.parse(body);\n } finally {\n clearTimeout(timeout);\n }\n };\n}\n\n/** Functional alias for {@link DecionisNodeSdk.mergeDecisionRequest}. */\nexport function mergeDecisionRequest(\n defaults: DecionisRequestDefaults | undefined,\n request: DecionisEvaluateDecisionRequest,\n): DecionisEvaluateDecisionRequest {\n return DecionisNodeSdk.mergeDecisionRequest(defaults, request);\n}\n\n/** Functional alias for {@link DecionisNodeSdk}. */\nexport function createDecionisNodeSdk(options: DecionisNodeSdkOptions): DecionisDecisionExecutor {\n return new DecionisNodeSdk(options);\n}\n","import type { DecionisDecisionExecutor } from \"./Client\";\nimport type {\n DecionisEvaluateDecisionRequest,\n DecionisEvaluateDecisionResponse,\n DecionisEvaluateOutcome,\n} from \"./Contracts\";\n\nexport type DecionisOutcomeAction = \"continue\" | \"deny\";\n\nexport interface DecionisDecisionAttachment {\n request: DecionisEvaluateDecisionRequest;\n response: DecionisEvaluateDecisionResponse;\n}\n\nexport interface DecionisGateResolution {\n skipped: boolean;\n action: DecionisOutcomeAction;\n denyStatusCode: number;\n denyBody: Record<string, unknown> | null;\n attachment: DecionisDecisionAttachment | null;\n}\n\nexport interface DecionisPolicyGateOptions<TRequest, TReply = unknown> {\n client: DecionisDecisionExecutor;\n buildDecisionRequest: (\n request: TRequest,\n reply: TReply | undefined,\n ) => Promise<DecionisEvaluateDecisionRequest | null> | DecionisEvaluateDecisionRequest | null;\n outcomeActions?: Partial<Record<DecionisEvaluateOutcome, DecionisOutcomeAction>>;\n denyStatusCodes?: Partial<Record<DecionisEvaluateOutcome, number>>;\n attachProperty?: string;\n onDecision?: (\n attachment: DecionisDecisionAttachment,\n request: TRequest,\n reply: TReply | undefined,\n ) => Promise<void> | void;\n}\n\nexport const DEFAULT_OUTCOME_ACTIONS: Record<DecionisEvaluateOutcome, DecionisOutcomeAction> = {\n APPROVE: \"continue\",\n ESCALATE: \"deny\",\n REJECT: \"deny\",\n REVIEW: \"deny\",\n};\n\nexport const DEFAULT_DENY_STATUS_CODES: Record<DecionisEvaluateOutcome, number> = {\n APPROVE: 200,\n ESCALATE: 409,\n REJECT: 403,\n REVIEW: 409,\n};\n\n/**\n * PolicyGate groups this module's exported functions as static methods.\n */\nexport class PolicyGate {\n static resolveOutcomeAction(\n outcome: DecionisEvaluateOutcome,\n overrides?: Partial<Record<DecionisEvaluateOutcome, DecionisOutcomeAction>>,\n ): DecionisOutcomeAction {\n return overrides?.[outcome] ?? DEFAULT_OUTCOME_ACTIONS[outcome];\n }\n\n static resolveDenyStatusCode(\n outcome: DecionisEvaluateOutcome,\n overrides?: Partial<Record<DecionisEvaluateOutcome, number>>,\n ): number {\n return overrides?.[outcome] ?? DEFAULT_DENY_STATUS_CODES[outcome];\n }\n\n static buildDecisionHeaders(response: DecionisEvaluateDecisionResponse): Record<string, string> {\n return {\n \"x-decionis-outcome\": response.outcome,\n \"x-decionis-dossier-id\": response.dossier_id,\n \"x-decionis-evaluation-id\": response.evaluation_id,\n \"x-decionis-policy-version\": response.policy_version,\n };\n }\n\n static buildDefaultDenyBody(response: DecionisEvaluateDecisionResponse): Record<string, unknown> {\n return {\n error: \"DECIONIS_POLICY_GATE_BLOCKED\",\n message: `Decionis returned ${response.outcome} for this request.`,\n outcome: response.outcome,\n dossier_id: response.dossier_id,\n evaluation_id: response.evaluation_id,\n policy_version: response.policy_version,\n decision: response,\n };\n }\n\n static async resolvePolicyGateDecision<TRequest, TReply = unknown>(\n options: DecionisPolicyGateOptions<TRequest, TReply>,\n request: TRequest,\n reply?: TReply,\n ): Promise<DecionisGateResolution> {\n const decisionRequest = await options.buildDecisionRequest(request, reply);\n if (!decisionRequest) {\n return {\n skipped: true,\n action: \"continue\",\n denyStatusCode: 200,\n denyBody: null,\n attachment: null,\n };\n }\n\n const response = await options.client.evaluateDecision(decisionRequest, {\n idempotencyKey: decisionRequest.idempotency_key ?? null,\n });\n const attachment = {\n request: decisionRequest,\n response,\n };\n await options.onDecision?.(attachment, request, reply);\n const action = resolveOutcomeAction(response.outcome, options.outcomeActions);\n\n return {\n skipped: false,\n action,\n denyStatusCode: resolveDenyStatusCode(response.outcome, options.denyStatusCodes),\n denyBody: action === \"deny\" ? buildDefaultDenyBody(response) : null,\n attachment,\n };\n }\n}\n\n/** Functional alias for {@link PolicyGate.resolveOutcomeAction}. */\nexport function resolveOutcomeAction(\n outcome: DecionisEvaluateOutcome,\n overrides?: Partial<Record<DecionisEvaluateOutcome, DecionisOutcomeAction>>,\n): DecionisOutcomeAction {\n return PolicyGate.resolveOutcomeAction(outcome, overrides);\n}\n\n/** Functional alias for {@link PolicyGate.resolveDenyStatusCode}. */\nexport function resolveDenyStatusCode(\n outcome: DecionisEvaluateOutcome,\n overrides?: Partial<Record<DecionisEvaluateOutcome, number>>,\n): number {\n return PolicyGate.resolveDenyStatusCode(outcome, overrides);\n}\n\n/** Functional alias for {@link PolicyGate.buildDecisionHeaders}. */\nexport function buildDecisionHeaders(\n response: DecionisEvaluateDecisionResponse,\n): Record<string, string> {\n return PolicyGate.buildDecisionHeaders(response);\n}\n\n/** Functional alias for {@link PolicyGate.buildDefaultDenyBody}. */\nexport function buildDefaultDenyBody(\n response: DecionisEvaluateDecisionResponse,\n): Record<string, unknown> {\n return PolicyGate.buildDefaultDenyBody(response);\n}\n\n/** Functional alias for {@link PolicyGate.resolvePolicyGateDecision}. */\nexport function resolvePolicyGateDecision<TRequest, TReply = unknown>(\n options: DecionisPolicyGateOptions<TRequest, TReply>,\n request: TRequest,\n reply?: TReply,\n): Promise<DecionisGateResolution> {\n return PolicyGate.resolvePolicyGateDecision<TRequest, TReply>(options, request, reply);\n}\n","import {\n buildDecisionHeaders,\n resolvePolicyGateDecision,\n type DecionisDecisionAttachment,\n type DecionisPolicyGateOptions,\n} from \"./Gate\";\n\ntype ExpressLikeRequest = object;\ninterface ExpressLikeResponse {\n setHeader(name: string, value: string): void;\n status(code: number): ExpressLikeResponse;\n json(body: unknown): unknown;\n}\ntype ExpressNext = (error?: unknown) => void;\n\nexport type ExpressDecionisPolicyGateOptions = DecionisPolicyGateOptions<\n ExpressLikeRequest,\n ExpressLikeResponse\n> & {\n onDeny?: (\n attachment: DecionisDecisionAttachment,\n request: ExpressLikeRequest,\n response: ExpressLikeResponse,\n statusCode: number,\n body: Record<string, unknown>,\n ) => Promise<void> | void;\n};\n\n/**\n * ExpressPolicyGate is the class form of the middleware factory\n * {@link createExpressPolicyGate}.\n */\nexport class ExpressPolicyGate {\n private readonly options: ExpressDecionisPolicyGateOptions;\n\n constructor(options: ExpressDecionisPolicyGateOptions) {\n this.options = options;\n }\n\n /** Build the Express middleware bound to this gate's options. */\n middleware() {\n const options = this.options;\n const attachProperty = options.attachProperty ?? \"decionis\";\n\n return async function decionisExpressPolicyGate(\n request: ExpressLikeRequest,\n response: ExpressLikeResponse,\n next: ExpressNext,\n ) {\n try {\n const resolution = await resolvePolicyGateDecision(options, request, response);\n if (!resolution.attachment) {\n next();\n return;\n }\n\n (request as Record<string, unknown>)[attachProperty] = resolution.attachment;\n const headers = buildDecisionHeaders(resolution.attachment.response);\n for (const [name, value] of Object.entries(headers)) response.setHeader(name, value);\n\n if (resolution.action === \"continue\") {\n next();\n return;\n }\n\n if (options.onDeny && resolution.denyBody) {\n await options.onDeny(\n resolution.attachment,\n request,\n response,\n resolution.denyStatusCode,\n resolution.denyBody,\n );\n return;\n }\n\n response.status(resolution.denyStatusCode).json(resolution.denyBody);\n } catch (error) {\n next(error);\n }\n };\n }\n}\n\n/** Functional alias for {@link ExpressPolicyGate.middleware}. */\nexport function createExpressPolicyGate(options: ExpressDecionisPolicyGateOptions) {\n return new ExpressPolicyGate(options).middleware();\n}\n","import { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\ntype FetchLike = typeof fetch;\n\nconst authorityDecisionSchema = z\n .object({\n decision_id: z.string().min(1),\n chain_id: z.string().nullable(),\n status: z.enum([\"ALLOW\", \"BLOCK\", \"ESCALATE\", \"REVIEW_REQUIRED\", \"ERROR\"]),\n should_execute: z.boolean(),\n reason_codes: z.array(z.string()),\n action_hash: z.string().regex(/^sha256:[0-9a-f]{64}$/),\n policy_version: z.string().nullable().optional().default(null),\n mode: z.enum([\"SHADOW\", \"PARALLEL\", \"ENFORCEMENT\"]).nullable().optional().default(null),\n execution_token: z.string().min(1).nullable(),\n execution_token_expires_at: z.string().datetime().nullable(),\n dossier_id: z.string().nullable(),\n dossier_sha256: z.string().nullable().optional().default(null),\n dossier_url: z.string().nullable(),\n approval_request_id: z.string().nullable().optional().default(null),\n ledger_entry_id: z.string().nullable(),\n })\n .passthrough();\n\nexport interface DecionisAuthorityActor {\n id: string;\n type: string;\n runtime?: string;\n trust_level?: string;\n}\n\nexport interface DecionisAuthorityAction {\n type: string;\n resource: string;\n parameters: Record<string, unknown>;\n}\n\nexport interface DecionisAuthorityDownstreamTarget {\n system: string;\n environment?: string;\n operation: string;\n endpoint?: string;\n}\n\nexport interface DecionisAuthorityRequest {\n protocol_version: \"agent-safe.intent/1\";\n tenant_id: string;\n intent_id: string;\n captured_at: string;\n expires_at: string;\n actor: DecionisAuthorityActor;\n action: DecionisAuthorityAction;\n context: Record<string, unknown>;\n downstream_target: DecionisAuthorityDownstreamTarget;\n intent_hash: `sha256:${string}`;\n mode: \"SHADOW\" | \"ENFORCEMENT\";\n evidence?: {\n humanApproval?: {\n provider: \"presence\";\n requestId: string;\n receiptDossierId: string;\n };\n };\n}\n\nexport type DecionisAuthorityIntentBinding = Omit<\n DecionisAuthorityRequest,\n \"intent_hash\" | \"mode\" | \"evidence\"\n>;\n\nexport interface DecionisAuthorityDecision {\n decision_id: string;\n chain_id: string | null;\n status: \"ALLOW\" | \"BLOCK\" | \"ESCALATE\" | \"REVIEW_REQUIRED\" | \"ERROR\";\n should_execute: boolean;\n reason_codes: string[];\n action_hash: string;\n policy_version: string | null;\n mode: \"SHADOW\" | \"PARALLEL\" | \"ENFORCEMENT\" | null;\n execution_token: string | null;\n execution_token_expires_at: string | null;\n dossier_id: string | null;\n dossier_sha256: string | null;\n dossier_url: string | null;\n approval_request_id: string | null;\n ledger_entry_id: string | null;\n [key: string]: unknown;\n}\n\nexport interface DecionisExecutionClientOptions {\n authorityBaseUrl: string;\n fetch?: FetchLike;\n timeoutMs?: number;\n defaultHeaders?: Record<string, string>;\n allowInsecureLoopback?: boolean;\n}\n\nexport interface DecionisEnforceAndExecuteInput<TOutput> {\n request: DecionisAuthorityRequest;\n execute: (input: {\n decision: DecionisAuthorityDecision;\n executionToken: string;\n }) => Promise<TOutput> | TOutput;\n}\n\nexport type DecionisEnforceAndExecuteResult<TOutput> =\n | {\n executed: true;\n decision: DecionisAuthorityDecision;\n result: TOutput;\n }\n | {\n executed: false;\n decision: DecionisAuthorityDecision | null;\n result: null;\n };\n\n/** Result of redeeming a single-use execution grant via `/v1/execution/consume-token`. */\nexport interface DecionisExecutionGrantRedemption {\n valid: boolean;\n reason_codes: string[];\n claims: Record<string, unknown> | null;\n claim_token?: string | null;\n claim_lease_expires_at?: string | null;\n evidence?: Record<string, unknown>;\n}\n\nexport interface DecionisEnforceAndExecuteStrictInput<TOutput> {\n request: DecionisAuthorityRequest;\n execute: (input: {\n decision: DecionisAuthorityDecision;\n executionToken: string;\n grant: DecionisExecutionGrantRedemption;\n claimToken?: string;\n commitCorrelationId?: string;\n }) => Promise<TOutput> | TOutput;\n classifyFailure?: (error: unknown) => \"FAILED\" | \"INDETERMINATE\";\n}\n\n/**\n * Why an action did not execute under grant-required (strict) enforcement:\n * - `BLOCKED_BY_POLICY` — the authority did not authorize the action.\n * - `NO_EXECUTION_GRANT` — authorized, but no single-use grant was issued.\n * - `GRANT_NOT_REDEEMABLE` — the grant failed to redeem (expired, already used,\n * binding mismatch, or the redeem call errored). Fail closed, no execution.\n * - `AUTHORITY_ERROR` — the authority call itself failed; no decision, no execution.\n */\nexport type DecionisStrictBlockReason =\n | \"BLOCKED_BY_POLICY\"\n | \"NO_EXECUTION_GRANT\"\n | \"GRANT_NOT_REDEEMABLE\"\n | \"AUTHORITY_ERROR\";\n\nexport type DecionisEnforceAndExecuteStrictResult<TOutput> =\n | {\n executed: true;\n decision: DecionisAuthorityDecision;\n grant: DecionisExecutionGrantRedemption;\n result: TOutput;\n }\n | {\n executed: false;\n decision: DecionisAuthorityDecision | null;\n grant: DecionisExecutionGrantRedemption | null;\n reason: DecionisStrictBlockReason;\n result: null;\n };\n\nexport class DecionisExecutionClientError extends Error {\n status: number;\n body: unknown;\n\n constructor(message: string, options: { status: number; body: unknown }) {\n super(message);\n this.name = \"DecionisExecutionClientError\";\n this.status = options.status;\n this.body = options.body;\n }\n}\n\nasync function postJson<TBody, TResult>(\n options: DecionisExecutionClientOptions,\n route: string,\n body: TBody,\n): Promise<TResult> {\n const baseUrl = options.authorityBaseUrl.replace(/\\/+$/, \"\");\n const fetchImpl = options.fetch ?? fetch;\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n Math.min(Math.max(options.timeoutMs ?? 4_000, 1), 15_000),\n );\n\n try {\n const response = await fetchImpl(`${baseUrl}${route}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(options.defaultHeaders ?? {}),\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n const responseText = await response.text();\n const responseBody =\n Buffer.byteLength(responseText, \"utf8\") <= 100 * 1024\n ? (() => {\n try {\n return JSON.parse(responseText) as unknown;\n } catch {\n return null;\n }\n })()\n : null;\n if (!response.ok) {\n throw new DecionisExecutionClientError(\n `Decionis execution authority request failed with status ${response.status}`,\n {\n status: response.status,\n body: responseBody,\n },\n );\n }\n return responseBody as TResult;\n } finally {\n clearTimeout(timeout);\n }\n}\n\n/**\n * DecionisExecutionClient is the class form of the client returned by\n * {@link createDecionisExecutionClient}.\n */\nexport class DecionisExecutionClient {\n private readonly options: DecionisExecutionClientOptions;\n\n constructor(options: DecionisExecutionClientOptions) {\n assertAuthorityUrl(options);\n this.options = options;\n }\n\n enforceAndBind = async (request: DecionisAuthorityRequest) => {\n const response = await postJson<DecionisAuthorityRequest, unknown>(\n {\n ...this.options,\n defaultHeaders: {\n \"idempotency-key\": request.intent_id,\n ...(this.options.defaultHeaders ?? {}),\n },\n },\n \"/v1/authority/enforce-and-bind\",\n request,\n );\n return authorityDecisionSchema.parse(response) as DecionisAuthorityDecision;\n };\n\n verifyToken = (body: Record<string, unknown>) => {\n return postJson<Record<string, unknown>, unknown>(\n this.options,\n \"/v1/execution/verify-token\",\n body,\n );\n };\n\n consumeToken = (body: Record<string, unknown>) => {\n return postJson<Record<string, unknown>, unknown>(\n this.options,\n \"/v1/execution/consume-token\",\n body,\n );\n };\n\n claimToken = (body: Record<string, unknown>) => {\n return postJson<Record<string, unknown>, unknown>(\n this.options,\n \"/v1/execution/claim-token\",\n body,\n );\n };\n\n /**\n * Grant-required, fail-closed enforcement — the default path. Delegates to\n * {@link enforceAndExecuteStrict}: the authority must authorize AND issue a\n * single-use grant, and that grant must redeem, BEFORE `execute` runs. Policy\n * block, missing grant, failed redemption, and an unreachable authority all\n * resolve to `executed: false` (`decision` is `null` on authority errors)\n * instead of running the action. Call the strict method directly when the\n * caller needs the grant redemption or the precise non-execution reason;\n * this wrapper keeps the smaller executed/decision/result shape.\n */\n enforceAndExecute = async <TOutput>(\n input: DecionisEnforceAndExecuteInput<TOutput>,\n ): Promise<DecionisEnforceAndExecuteResult<TOutput>> => {\n const strict = await this.enforceAndExecuteStrict({\n request: input.request,\n execute: ({ decision, executionToken }) => input.execute({ decision, executionToken }),\n });\n if (!strict.executed) {\n return {\n executed: false,\n decision: strict.decision,\n result: null,\n };\n }\n return {\n executed: true,\n decision: strict.decision,\n result: strict.result,\n };\n };\n\n /**\n * Redeem a single-use execution grant via `/v1/execution/consume-token`, binding\n * it to the exact action. Never throws — a transport/HTTP failure returns an\n * invalid redemption so the strict path fails closed rather than executing on an\n * unverified grant.\n */\n redeemGrant = async (\n executionToken: string,\n request: DecionisAuthorityRequest,\n expectedDecision?: DecionisAuthorityDecision,\n commitCorrelationId = request.intent_id,\n ): Promise<DecionisExecutionGrantRedemption> => {\n const baseUrl = this.options.authorityBaseUrl.replace(/\\/+$/, \"\");\n const fetchImpl = this.options.fetch ?? fetch;\n const controller = new AbortController();\n const timeout = setTimeout(\n () => controller.abort(),\n Math.min(Math.max(this.options.timeoutMs ?? 4_000, 1), 15_000),\n );\n try {\n const response = await fetchImpl(`${baseUrl}/v1/execution/claim-token`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", ...(this.options.defaultHeaders ?? {}) },\n body: JSON.stringify({\n execution_token: executionToken,\n intent_hash: request.intent_hash,\n intent: authorityIntentBindingOf(request),\n ...(request.evidence ? { evidence: request.evidence } : {}),\n consumed_by: request.actor.id,\n commit_correlation_id: commitCorrelationId,\n }),\n signal: controller.signal,\n });\n const responseText = await response.text();\n const body = (() => {\n if (Buffer.byteLength(responseText, \"utf8\") > 100 * 1024) return null;\n try {\n return JSON.parse(responseText) as Partial<DecionisExecutionGrantRedemption>;\n } catch {\n return null;\n }\n })();\n if (!response.ok || !body || body.valid !== true) {\n const reason_codes = Array.isArray(body?.reason_codes)\n ? (body?.reason_codes as string[])\n : [\"DECIONIS_GRANT_REJECTED\"];\n return { valid: false, reason_codes, claims: body?.claims ?? null };\n }\n const claims = body.claims;\n const binding =\n claims && typeof claims.binding === \"object\" && !Array.isArray(claims.binding)\n ? (claims.binding as Record<string, unknown>)\n : null;\n if (\n !claims ||\n typeof claims.jti !== \"string\" ||\n claims.org_id !== request.tenant_id ||\n claims.sub !== request.actor.id ||\n claims.action !== request.action.type ||\n binding?.intent_hash !== request.intent_hash ||\n (expectedDecision !== undefined &&\n (claims.decision_id !== expectedDecision.decision_id ||\n claims.dossier_id !== expectedDecision.dossier_id))\n ) {\n return {\n valid: false,\n reason_codes: [\"DECIONIS_GRANT_BINDING_MISMATCH\"],\n claims: null,\n };\n }\n return {\n valid: true,\n reason_codes: Array.isArray(body.reason_codes) ? body.reason_codes : [],\n claims,\n claim_token: typeof body.claim_token === \"string\" ? body.claim_token : null,\n claim_lease_expires_at:\n typeof body.claim_lease_expires_at === \"string\" ? body.claim_lease_expires_at : null,\n ...(body.evidence && typeof body.evidence === \"object\"\n ? { evidence: body.evidence as Record<string, unknown> }\n : {}),\n };\n } catch {\n return { valid: false, reason_codes: [\"DECIONIS_GRANT_REDEEM_ERROR\"], claims: null };\n } finally {\n clearTimeout(timeout);\n }\n };\n\n finalizeGrant = async (input: {\n executionToken: string;\n claimToken: string;\n outcome: \"COMMITTED\" | \"FAILED\" | \"INDETERMINATE\";\n commitCorrelationId: string;\n downstreamEvidence?: Record<string, unknown>;\n }): Promise<boolean> => {\n try {\n const response = await postJson<Record<string, unknown>, Record<string, unknown>>(\n this.options,\n \"/v1/execution/finalize-token\",\n {\n execution_token: input.executionToken,\n claim_token: input.claimToken,\n outcome: input.outcome,\n commit_correlation_id: input.commitCorrelationId,\n ...(input.downstreamEvidence ? { downstream_evidence: input.downstreamEvidence } : {}),\n },\n );\n return response.finalized === true;\n } catch {\n return false;\n }\n };\n\n /**\n * Grant-required (strict) enforcement: \"no valid grant, no execution.\" The default\n * {@link enforceAndExecute} delegates to this path. This makes the single-use\n * execution grant a hard precondition: the authority must authorize AND issue a\n * grant, and that grant must redeem successfully, BEFORE `execute` runs. Because\n * the grant is redeemed up front, a downstream failure requires a fresh decision\n * rather than replaying an ALLOW — the fail-closed posture for consequential\n * actions. Every non-executing path returns `executed: false` with a reason.\n */\n enforceAndExecuteStrict = async <TOutput>(\n input: DecionisEnforceAndExecuteStrictInput<TOutput>,\n ): Promise<DecionisEnforceAndExecuteStrictResult<TOutput>> => {\n let decision: DecionisAuthorityDecision;\n try {\n decision = await this.enforceAndBind(input.request);\n } catch {\n return {\n executed: false,\n decision: null,\n grant: null,\n reason: \"AUTHORITY_ERROR\",\n result: null,\n };\n }\n if (!decision.should_execute) {\n return { executed: false, decision, grant: null, reason: \"BLOCKED_BY_POLICY\", result: null };\n }\n if (!decision.execution_token) {\n return { executed: false, decision, grant: null, reason: \"NO_EXECUTION_GRANT\", result: null };\n }\n const commitCorrelationId = input.request.intent_id;\n const grant = await this.redeemGrant(\n decision.execution_token,\n input.request,\n decision,\n commitCorrelationId,\n );\n if (!grant.valid || !grant.claim_token) {\n return { executed: false, decision, grant, reason: \"GRANT_NOT_REDEEMABLE\", result: null };\n }\n let result: TOutput;\n try {\n result = await input.execute({\n decision,\n executionToken: decision.execution_token,\n grant,\n claimToken: grant.claim_token,\n commitCorrelationId,\n });\n } catch (error) {\n await this.finalizeGrant({\n executionToken: decision.execution_token,\n claimToken: grant.claim_token,\n outcome: input.classifyFailure?.(error) ?? \"INDETERMINATE\",\n commitCorrelationId,\n downstreamEvidence: { error_type: error instanceof Error ? error.name : \"unknown\" },\n });\n throw error;\n }\n const finalized = await this.finalizeGrant({\n executionToken: decision.execution_token,\n claimToken: grant.claim_token,\n outcome: \"COMMITTED\",\n commitCorrelationId,\n });\n if (!finalized) grant.reason_codes = [...grant.reason_codes, \"COMMIT_FINALIZATION_PENDING\"];\n return { executed: true, decision, grant, result };\n };\n}\n\n/** Functional alias for {@link DecionisExecutionClient}. */\nexport function createDecionisExecutionClient(options: DecionisExecutionClientOptions) {\n return new DecionisExecutionClient(options);\n}\n\nexport function authorityIntentBindingOf(\n request: DecionisAuthorityRequest,\n): DecionisAuthorityIntentBinding {\n return {\n protocol_version: request.protocol_version,\n tenant_id: request.tenant_id,\n intent_id: request.intent_id,\n captured_at: request.captured_at,\n expires_at: request.expires_at,\n actor: request.actor,\n action: request.action,\n context: request.context,\n downstream_target: request.downstream_target,\n };\n}\n\nexport function hashAuthorityIntentBinding(\n binding: DecionisAuthorityIntentBinding,\n): `sha256:${string}` {\n const canonical = stableJsonStringify(binding);\n if (Buffer.byteLength(canonical, \"utf8\") > 100 * 1024) {\n throw new Error(\"DECIONIS_INTENT_TOO_LARGE\");\n }\n return `sha256:${createHash(\"sha256\").update(canonical, \"utf8\").digest(\"hex\")}`;\n}\n\nexport function bindAuthorityIntent(\n binding: DecionisAuthorityIntentBinding,\n evidence?: DecionisAuthorityRequest[\"evidence\"],\n mode: DecionisAuthorityRequest[\"mode\"] = \"ENFORCEMENT\",\n): DecionisAuthorityRequest {\n return {\n ...binding,\n intent_hash: hashAuthorityIntentBinding(binding),\n mode,\n ...(evidence === undefined ? {} : { evidence }),\n };\n}\n\nfunction stableJsonStringify(value: unknown): string {\n let entries = 0;\n const normalize = (current: unknown, depth: number): unknown => {\n if (depth > 20) throw new Error(\"DECIONIS_INTENT_TOO_DEEP\");\n if (current === null || typeof current === \"string\" || typeof current === \"boolean\") {\n return current;\n }\n if (typeof current === \"number\") {\n if (!Number.isFinite(current)) throw new Error(\"DECIONIS_INTENT_NUMBER_INVALID\");\n return current;\n }\n if (Array.isArray(current)) {\n if (current.length > 1_000) throw new Error(\"DECIONIS_INTENT_ARRAY_TOO_LARGE\");\n entries += current.length;\n if (entries > 5_000) throw new Error(\"DECIONIS_INTENT_TOO_MANY_ENTRIES\");\n return current.map((item) => normalize(item, depth + 1));\n }\n if (!current || typeof current !== \"object\") throw new Error(\"DECIONIS_INTENT_VALUE_INVALID\");\n const source = current as Record<string, unknown>;\n const keys = Object.keys(source).sort();\n entries += keys.length;\n if (entries > 5_000) throw new Error(\"DECIONIS_INTENT_TOO_MANY_ENTRIES\");\n const normalized: Record<string, unknown> = {};\n for (const key of keys) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n throw new Error(\"DECIONIS_INTENT_KEY_UNSAFE\");\n }\n normalized[key] = normalize(source[key], depth + 1);\n }\n return normalized;\n };\n return JSON.stringify(normalize(value, 0));\n}\n\nfunction assertAuthorityUrl(options: DecionisExecutionClientOptions): void {\n const url = new URL(options.authorityBaseUrl);\n const loopback =\n url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\";\n if (url.username || url.password) throw new Error(\"DECIONIS_URL_MUST_NOT_CONTAIN_CREDENTIALS\");\n if (url.protocol !== \"https:\" && !(loopback && options.allowInsecureLoopback === true)) {\n throw new Error(\"DECIONIS_URL_MUST_USE_HTTPS\");\n }\n}\n","type FetchLike = typeof fetch;\n\ntype HeaderValue = string | string[] | undefined;\n\ninterface ExpressLikeRequest {\n headers?: Record<string, HeaderValue>;\n get?: (name: string) => HeaderValue;\n header?: (name: string) => HeaderValue;\n}\n\ninterface ExpressLikeResponse {\n setHeader(name: string, value: string): void;\n status(code: number): ExpressLikeResponse;\n json(body: unknown): unknown;\n}\n\ntype ExpressNext = (error?: unknown) => void;\n\nexport interface DecionisDownstreamTargetBinding {\n system?: string;\n operation?: string;\n endpoint?: string;\n}\n\nexport interface DecionisExecutionBinding {\n actor_id?: string;\n actor_type?: string;\n action_type?: string;\n resource?: string;\n amount?: number;\n currency?: string;\n downstream_target?: DecionisDownstreamTargetBinding;\n}\n\nexport interface DecionisExecutionTokenClaims {\n iss: \"decionis\";\n sub: string;\n jti: string;\n decision_id: string;\n chain_id: string;\n actor_id: string;\n actor_type: string;\n action_type: string;\n resource: string;\n amount: number | null;\n currency: string;\n target_system: string;\n target_operation: string;\n target_endpoint: string | null;\n action_hash: string;\n iat: number;\n exp: number;\n single_use: true;\n}\n\nexport interface DecionisExecutionTokenConsumeResponse {\n valid: boolean;\n reason_codes: string[];\n claims: DecionisExecutionTokenClaims | null;\n}\n\nexport interface DecionisExecutionAttachment {\n token: string;\n binding: DecionisExecutionBinding;\n response: DecionisExecutionTokenConsumeResponse;\n}\n\nexport interface ExpressExecutionTokenVerifierOptions<TRequest extends ExpressLikeRequest> {\n authorityBaseUrl: string;\n tokenHeader?: string;\n fetch?: FetchLike;\n timeoutMs?: number;\n attachProperty?: string;\n buildVerificationRequest: (\n request: TRequest,\n ) => Promise<DecionisExecutionBinding> | DecionisExecutionBinding;\n onVerified?: (\n attachment: DecionisExecutionAttachment,\n request: TRequest,\n response: ExpressLikeResponse,\n ) => Promise<void> | void;\n onReject?: (\n body: Record<string, unknown>,\n request: TRequest,\n response: ExpressLikeResponse,\n ) => Promise<void> | void;\n}\n\nfunction headerToString(value: HeaderValue): string | null {\n if (Array.isArray(value)) return value[0] ?? null;\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction readHeader(request: ExpressLikeRequest, name: string): string | null {\n return (\n headerToString(request.get?.(name)) ??\n headerToString(request.header?.(name)) ??\n headerToString(request.headers?.[name.toLowerCase()]) ??\n headerToString(request.headers?.[name])\n );\n}\n\nfunction buildRejectBody(reason_codes: string[], detail?: unknown): Record<string, unknown> {\n return {\n error: \"NO_VALID_DECIONIS_AUTHORITY\",\n reason_codes,\n ...(detail ? { detail } : {}),\n };\n}\n\nfunction reasonCodesFromBody(body: unknown): string[] {\n if (!body || typeof body !== \"object\") return [\"DECIONIS_TOKEN_REJECTED\"];\n const reason_codes = (body as { reason_codes?: unknown }).reason_codes;\n if (!Array.isArray(reason_codes)) return [\"DECIONIS_TOKEN_REJECTED\"];\n const parsed = reason_codes.filter((item): item is string => typeof item === \"string\");\n return parsed.length > 0 ? parsed : [\"DECIONIS_TOKEN_REJECTED\"];\n}\n\nasync function consumeExecutionToken<TRequest extends ExpressLikeRequest>(\n options: ExpressExecutionTokenVerifierOptions<TRequest>,\n token: string,\n binding: DecionisExecutionBinding,\n): Promise<DecionisExecutionTokenConsumeResponse> {\n const baseUrl = options.authorityBaseUrl.replace(/\\/+$/, \"\");\n const fetchImpl = options.fetch ?? fetch;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 4000);\n\n try {\n const response = await fetchImpl(`${baseUrl}/v1/execution/consume-token`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n execution_token: token,\n ...binding,\n }),\n signal: controller.signal,\n });\n const body = await response.json().catch(() => null);\n if (!response.ok) {\n return {\n valid: false,\n reason_codes: reasonCodesFromBody(body),\n claims: null,\n };\n }\n return body as DecionisExecutionTokenConsumeResponse;\n } finally {\n clearTimeout(timeout);\n }\n}\n\n/**\n * ExpressExecutionTokenVerifier is the class form of the middleware factory\n * {@link createExpressExecutionTokenVerifier}.\n */\nexport class ExpressExecutionTokenVerifier<TRequest extends ExpressLikeRequest> {\n private readonly options: ExpressExecutionTokenVerifierOptions<TRequest>;\n\n constructor(options: ExpressExecutionTokenVerifierOptions<TRequest>) {\n this.options = options;\n }\n\n /** Build the Express middleware bound to this verifier's options. */\n middleware() {\n const options = this.options;\n const tokenHeader = options.tokenHeader ?? \"x-decionis-execution-token\";\n const attachProperty = options.attachProperty ?? \"decionisExecution\";\n\n return async function decionisExpressExecutionTokenVerifier(\n request: TRequest,\n response: ExpressLikeResponse,\n next: ExpressNext,\n ) {\n try {\n const token = readHeader(request, tokenHeader);\n if (!token) {\n const body = buildRejectBody([\"NO_VALID_EXECUTION_TOKEN\"]);\n if (options.onReject) {\n await options.onReject(body, request, response);\n return;\n }\n response.status(403).json(body);\n return;\n }\n\n const binding = await options.buildVerificationRequest(request);\n const verification = await consumeExecutionToken(options, token, binding);\n if (!verification.valid) {\n const body = buildRejectBody(verification.reason_codes, verification);\n if (options.onReject) {\n await options.onReject(body, request, response);\n return;\n }\n response.status(403).json(body);\n return;\n }\n\n const attachment = {\n token,\n binding,\n response: verification,\n };\n (request as Record<string, unknown>)[attachProperty] = attachment;\n response.setHeader(\"x-decionis-execution-authority\", \"valid\");\n if (verification.claims?.decision_id) {\n response.setHeader(\"x-decionis-decision-id\", verification.claims.decision_id);\n }\n await options.onVerified?.(attachment, request, response);\n next();\n } catch (error) {\n next(error);\n }\n };\n }\n}\n\n/** Functional alias for {@link ExpressExecutionTokenVerifier.middleware}. */\nexport function createExpressExecutionTokenVerifier<TRequest extends ExpressLikeRequest>(\n options: ExpressExecutionTokenVerifierOptions<TRequest>,\n) {\n return new ExpressExecutionTokenVerifier(options).middleware();\n}\n","import {\n buildDecisionHeaders,\n resolvePolicyGateDecision,\n type DecionisDecisionAttachment,\n type DecionisPolicyGateOptions,\n} from \"./Gate\";\n\ntype FastifyLikeRequest = object;\ninterface FastifyLikeReply {\n header(name: string, value: string): FastifyLikeReply;\n code(statusCode: number): FastifyLikeReply;\n send(payload: unknown): unknown;\n}\n\nexport type FastifyDecionisPolicyGateOptions = DecionisPolicyGateOptions<\n FastifyLikeRequest,\n FastifyLikeReply\n> & {\n onDeny?: (\n attachment: DecionisDecisionAttachment,\n request: FastifyLikeRequest,\n reply: FastifyLikeReply,\n statusCode: number,\n body: Record<string, unknown>,\n ) => Promise<void> | void;\n};\n\n/**\n * FastifyPolicyGate is the class form of the hook factory\n * {@link buildFastifyPolicyGate}.\n */\nexport class FastifyPolicyGate {\n private readonly options: FastifyDecionisPolicyGateOptions;\n\n constructor(options: FastifyDecionisPolicyGateOptions) {\n this.options = options;\n }\n\n /** Build the Fastify preHandler hook bound to this gate's options. */\n middleware() {\n const options = this.options;\n const attachProperty = options.attachProperty ?? \"decionis\";\n\n return async function decionisFastifyPolicyGate(\n request: FastifyLikeRequest,\n reply: FastifyLikeReply,\n ) {\n const resolution = await resolvePolicyGateDecision(options, request, reply);\n if (!resolution.attachment) return;\n\n (request as Record<string, unknown>)[attachProperty] = resolution.attachment;\n const headers = buildDecisionHeaders(resolution.attachment.response);\n for (const [name, value] of Object.entries(headers)) reply.header(name, value);\n\n if (resolution.action === \"continue\") return;\n if (options.onDeny && resolution.denyBody) {\n await options.onDeny(\n resolution.attachment,\n request,\n reply,\n resolution.denyStatusCode,\n resolution.denyBody,\n );\n return;\n }\n reply.code(resolution.denyStatusCode).send(resolution.denyBody);\n };\n }\n}\n\n/** Functional alias for {@link FastifyPolicyGate.middleware}. */\nexport function buildFastifyPolicyGate(options: FastifyDecionisPolicyGateOptions) {\n return new FastifyPolicyGate(options).middleware();\n}\n","import { createHash } from \"node:crypto\";\nimport {\n bindAuthorityIntent,\n type DecionisAuthorityActor,\n type DecionisAuthorityRequest,\n} from \"./ExecutionAuthority.js\";\n\nexport interface DecionisKubernetesMaterialDiff {\n changed_path_count: number;\n changed_paths: string[];\n truncated: boolean;\n}\n\nexport interface DecionisKubernetesMaterialFacts {\n proposed_replicas?: number;\n workload_security?: {\n privileged_containers: number;\n allow_privilege_escalation_containers: number;\n host_network: boolean;\n host_pid: boolean;\n host_ipc: boolean;\n host_path_volumes: number;\n host_port_bindings: number;\n gpu_count: number;\n workload_service_account_sha256?: string;\n };\n rbac?: {\n binds_cluster_admin: boolean;\n wildcard_rules: number;\n privilege_escalation_rules: number;\n };\n sensitive_object?: boolean;\n}\n\nexport interface DecionisKubernetesActionInput {\n organizationId: string;\n clusterId: string;\n policyVersion: string;\n policyRule: string;\n mode: DecionisAuthorityRequest[\"mode\"];\n intentId: string;\n capturedAt: string;\n expiresAt: string;\n actor: DecionisAuthorityActor;\n operation: \"CREATE\" | \"UPDATE\" | \"DELETE\";\n apiGroup: string;\n apiVersion: string;\n kind: string;\n resource: string;\n subresource?: string | null;\n namespace?: string | null;\n name?: string | null;\n oldObjectDigest: string | null;\n proposedObjectDigest: string | null;\n materialDiff: DecionisKubernetesMaterialDiff;\n materialFacts: DecionisKubernetesMaterialFacts;\n requestSource?: string | null;\n dryRun?: boolean;\n additionalKubernetesContext?: Record<string, unknown>;\n}\n\n/** Shared manifest-free authority binding for Kubernetes clients and admission. */\nexport function bindKubernetesAuthorityAction(\n input: DecionisKubernetesActionInput,\n): DecionisAuthorityRequest {\n const group = input.apiGroup || \"core\";\n const actionType =\n `kubernetes.${input.operation.toLowerCase()}.${token(group)}.${token(input.resource)}`.slice(\n 0,\n 120,\n );\n const parameters = {\n cluster_id: input.clusterId,\n operation: input.operation,\n api_group: input.apiGroup,\n api_version: input.apiVersion,\n kind: input.kind,\n resource: input.resource,\n subresource: input.subresource ?? null,\n namespace: input.namespace ?? null,\n name: input.name ?? null,\n old_object_digest: input.oldObjectDigest,\n proposed_object_digest: input.proposedObjectDigest,\n material_diff: input.materialDiff,\n material_facts: input.materialFacts,\n policy_version: input.policyVersion,\n policy_rule: input.policyRule,\n dry_run: input.dryRun ?? false,\n };\n return bindAuthorityIntent(\n {\n protocol_version: \"agent-safe.intent/1\",\n tenant_id: input.organizationId,\n intent_id: input.intentId,\n captured_at: input.capturedAt,\n expires_at: input.expiresAt,\n actor: input.actor,\n action: {\n type: actionType,\n resource: [\n input.clusterId,\n group,\n input.apiVersion,\n input.resource,\n input.subresource ?? \"-\",\n input.namespace ?? \"-\",\n input.name ?? \"-\",\n ]\n .map((part) => encodeURIComponent(part))\n .join(\":\")\n .slice(0, 500),\n parameters,\n },\n context: {\n source: input.requestSource ?? \"kubernetes\",\n kubernetes: {\n ...parameters,\n request_source: input.requestSource ?? null,\n ...(input.additionalKubernetesContext ?? {}),\n },\n },\n downstream_target: {\n system: `kubernetes:${input.clusterId}`,\n operation: input.operation,\n endpoint: [\n group,\n input.apiVersion,\n input.resource,\n input.namespace ?? \"-\",\n input.name ?? \"-\",\n ]\n .map((part) => encodeURIComponent(part))\n .join(\"/\")\n .slice(0, 500),\n },\n },\n undefined,\n input.mode,\n );\n}\n\nexport function hashKubernetesObject(\n input: Record<string, unknown> | null | undefined,\n): string | null {\n if (!input) return null;\n return `sha256:${createHash(\"sha256\").update(stableJson(input), \"utf8\").digest(\"hex\")}`;\n}\n\nexport function summarizeKubernetesObjectDiff(\n oldObject: Record<string, unknown> | null | undefined,\n proposedObject: Record<string, unknown> | null | undefined,\n secret: boolean,\n): DecionisKubernetesMaterialDiff {\n const paths: string[] = [];\n collectChangedPaths(oldObject, proposedObject, \"\", paths, secret);\n const unique = [...new Set(paths)].sort();\n return {\n changed_path_count: unique.length,\n changed_paths: unique.slice(0, 64),\n truncated: unique.length > 64,\n };\n}\n\nexport function deriveKubernetesMaterialFacts(input: {\n object: Record<string, unknown> | null | undefined;\n oldObject?: Record<string, unknown> | null;\n kind: string;\n apiGroup: string;\n resource: string;\n}): DecionisKubernetesMaterialFacts {\n const object = input.object ?? input.oldObject;\n const facts: DecionisKubernetesMaterialFacts = {};\n const replicas = finiteNumber(record(input.object?.spec).replicas);\n if (replicas !== null && replicas >= 0) facts.proposed_replicas = replicas;\n\n const workloadSpec = podSpec(object, input.kind);\n if (workloadSpec) {\n const containers = [\n ...records(workloadSpec.containers),\n ...records(workloadSpec.initContainers),\n ...records(workloadSpec.ephemeralContainers),\n ];\n const serviceAccount =\n string(workloadSpec.serviceAccountName) ?? string(workloadSpec.serviceAccount);\n facts.workload_security = {\n privileged_containers: containers.filter(\n (container) => record(container.securityContext).privileged === true,\n ).length,\n allow_privilege_escalation_containers: containers.filter(\n (container) => record(container.securityContext).allowPrivilegeEscalation === true,\n ).length,\n host_network: workloadSpec.hostNetwork === true,\n host_pid: workloadSpec.hostPID === true,\n host_ipc: workloadSpec.hostIPC === true,\n host_path_volumes: records(workloadSpec.volumes).filter((volume) => isRecord(volume.hostPath))\n .length,\n host_port_bindings: containers.reduce(\n (count, container) =>\n count +\n records(container.ports).filter((port) => finiteNumber(port.hostPort) !== null).length,\n 0,\n ),\n gpu_count: containers.reduce((count, container) => count + gpuCount(container), 0),\n ...(serviceAccount\n ? {\n workload_service_account_sha256: createHash(\"sha256\")\n .update(serviceAccount, \"utf8\")\n .digest(\"hex\"),\n }\n : {}),\n };\n }\n\n if (\n input.apiGroup === \"rbac.authorization.k8s.io\" &&\n [\"roles\", \"clusterroles\", \"rolebindings\", \"clusterrolebindings\"].includes(input.resource)\n ) {\n const roleRef = record(object?.roleRef);\n const rules = records(object?.rules);\n facts.rbac = {\n binds_cluster_admin:\n string(roleRef.name) === \"cluster-admin\" && string(roleRef.kind) === \"ClusterRole\",\n wildcard_rules: rules.filter((rule) => {\n const verbs = strings(rule.verbs);\n const resources = strings(rule.resources);\n const apiGroups = strings(rule.apiGroups);\n return verbs.includes(\"*\") || resources.includes(\"*\") || apiGroups.includes(\"*\");\n }).length,\n privilege_escalation_rules: rules.filter((rule) =>\n strings(rule.verbs).some((verb) => [\"bind\", \"escalate\", \"impersonate\"].includes(verb)),\n ).length,\n };\n }\n\n if (input.kind === \"Secret\") facts.sensitive_object = true;\n return facts;\n}\n\nfunction collectChangedPaths(\n before: unknown,\n after: unknown,\n path: string,\n paths: string[],\n secret: boolean,\n): void {\n if (stableJson(before) === stableJson(after)) return;\n if (secret && (path === \"/data\" || path === \"/stringData\")) {\n paths.push(`${path}/<redacted>`);\n return;\n }\n if (isRecord(before) && isRecord(after)) {\n for (const key of [...new Set([...Object.keys(before), ...Object.keys(after)])].sort()) {\n collectChangedPaths(before[key], after[key], `${path}/${pointer(key)}`, paths, secret);\n }\n return;\n }\n paths.push(path || \"/\");\n}\n\nfunction stableJson(value: unknown): string {\n if (value === undefined) return \"undefined\";\n const normalize = (current: unknown): unknown => {\n if (Array.isArray(current)) return current.map(normalize);\n if (!isRecord(current)) return current;\n return Object.fromEntries(\n Object.keys(current)\n .sort()\n .map((key) => [key, normalize(current[key])]),\n );\n };\n return JSON.stringify(normalize(value));\n}\n\nfunction podSpec(\n object: Record<string, unknown> | null | undefined,\n kind: string,\n): Record<string, unknown> | null {\n const spec = record(object?.spec);\n if (kind === \"Pod\") return spec;\n if (kind === \"CronJob\") {\n const jobSpec = record(record(spec.jobTemplate).spec);\n const cronPodSpec = record(record(jobSpec.template).spec);\n return Object.keys(cronPodSpec).length > 0 ? cronPodSpec : null;\n }\n const workloadPodSpec = record(record(spec.template).spec);\n return Object.keys(workloadPodSpec).length > 0 ? workloadPodSpec : null;\n}\n\nfunction gpuCount(container: Record<string, unknown>): number {\n const resources = record(container.resources);\n const requests = record(resources.requests);\n const limits = record(resources.limits);\n let total = 0;\n for (const key of new Set([...Object.keys(requests), ...Object.keys(limits)])) {\n if (!/(^|[./-])gpu$/i.test(key)) continue;\n total += Math.max(quantity(requests[key]), quantity(limits[key]));\n }\n return total;\n}\n\nfunction quantity(input: unknown): number {\n if (typeof input === \"number\" && Number.isFinite(input) && input >= 0) return input;\n if (typeof input !== \"string\" || !/^\\d+(?:\\.\\d+)?$/.test(input)) return 0;\n const parsed = Number(input);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;\n}\n\nfunction finiteNumber(input: unknown): number | null {\n return typeof input === \"number\" && Number.isFinite(input) ? input : null;\n}\n\nfunction string(input: unknown): string | null {\n return typeof input === \"string\" && input.length > 0 ? input : null;\n}\n\nfunction strings(input: unknown): string[] {\n return Array.isArray(input)\n ? input.filter((value): value is string => typeof value === \"string\")\n : [];\n}\n\nfunction records(input: unknown): Record<string, unknown>[] {\n return Array.isArray(input) ? input.filter(isRecord) : [];\n}\n\nfunction record(input: unknown): Record<string, unknown> {\n return isRecord(input) ? input : {};\n}\n\nfunction isRecord(input: unknown): input is Record<string, unknown> {\n return !!input && typeof input === \"object\" && !Array.isArray(input);\n}\n\nfunction pointer(input: string): string {\n return input.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n\nfunction token(input: string): string {\n return input\n .toLowerCase()\n .replace(/[^a-z0-9._:-]+/g, \"-\")\n .replace(/^[^a-z]+/, \"x\");\n}\n","import { createHash } from \"node:crypto\";\n\nimport { z } from \"zod\";\n\nimport { DecionisNodeSdkError } from \"./Client\";\n\ntype FetchLike = typeof fetch;\n\nexport interface DecionisPersonalClientOptions {\n baseUrl: string;\n deviceToken: string;\n timeoutMs?: number;\n fetch?: FetchLike;\n defaultHeaders?: Record<string, string>;\n}\n\nexport type DecionisPersonalRecallSource =\n | \"CALENDAR\"\n | \"URL_PATTERN\"\n | \"APP_FOCUS\"\n | \"LOCATION\"\n | \"TIME\";\n\nexport type DecionisPersonalRecallAction = \"PIN_RESOURCE\" | \"LOAD_SIDEBAR\" | \"OPEN_RESOURCE\";\n\nconst personalDeviceSchema = z.object({\n device_id: z.string(),\n org_id: z.string(),\n label: z.string(),\n scopes: z.array(z.string()),\n registered_at: z.string(),\n});\n\nconst personalProtocolSchema = z\n .object({\n outcome: z.string(),\n dossier_id: z.string(),\n evaluation_id: z.string().optional(),\n policy_version: z.string().optional(),\n verification_url: z.string().optional(),\n })\n .passthrough();\n\nconst personalCapsuleSchema = z.object({\n capsule_id: z.string(),\n org_id: z.string(),\n title: z.string(),\n state_hash: z.string(),\n payload_ref: z.string(),\n dossier_id: z.string(),\n verification_url: z.string(),\n evidence_hashes: z.array(z.string()),\n captured_at: z.string(),\n retention_days: z.number(),\n deleted_at: z.string().nullable(),\n});\n\nconst registerDeviceResponseSchema = z.object({\n device: personalDeviceSchema,\n token: z.string(),\n});\n\nconst captureCapsuleResponseSchema = z.object({\n capsule: personalCapsuleSchema,\n protocol: personalProtocolSchema,\n});\n\nconst resumeCapsuleResponseSchema = z.object({\n verdict: z.literal(\"RESTORE\"),\n execution: z\n .object({\n type: z.string(),\n parameters: z.record(z.unknown()),\n })\n .optional(),\n protocol: personalProtocolSchema,\n});\n\nconst recallResponseSchema = z.object({\n verdict: z.enum([\"NO_ACTION\", \"PIN_RESOURCE\", \"LOAD_SIDEBAR\", \"OPEN_RESOURCE\"]),\n dispatch: z\n .object({\n type: z.enum([\"PIN_RESOURCE\", \"LOAD_SIDEBAR\", \"OPEN_RESOURCE\"]),\n parameters: z.object({\n resource_url: z.string(),\n label: z.string().nullable(),\n rule_id: z.string(),\n }),\n })\n .nullable(),\n protocol: personalProtocolSchema.optional(),\n});\n\nconst personalConfigResponseSchema = z.object({\n service: z.literal(\"personal\"),\n org_id: z.string(),\n config_version: z.string().nullable(),\n device: z.object({\n device_id: z.string().nullable(),\n auth_type: z.string().nullable(),\n scopes: z.array(z.string()),\n }),\n policy: z\n .object({\n bundle_id: z.string(),\n version: z.string(),\n rules_sha256: z.string(),\n parameters_sha256: z.string(),\n rule_count: z.number(),\n source: z.string(),\n stored_at: z.string(),\n })\n .nullable(),\n realms: z.record(z.unknown()),\n recall_rules: z.array(z.record(z.unknown())),\n});\n\nexport type DecionisPersonalDeviceRegistration = z.infer<typeof registerDeviceResponseSchema>;\nexport type DecionisPersonalCapsuleCapture = z.infer<typeof captureCapsuleResponseSchema>;\nexport type DecionisPersonalCapsuleResume = z.infer<typeof resumeCapsuleResponseSchema>;\nexport type DecionisPersonalRecallDispatch = z.infer<typeof recallResponseSchema>;\nexport type DecionisPersonalConfig = z.infer<typeof personalConfigResponseSchema>;\n\nfunction messageFromBody(status: number, body: unknown): string {\n if (body && typeof body === \"object\") {\n const record = body as Record<string, unknown>;\n if (typeof record.message === \"string\" && record.message.trim()) return record.message;\n if (typeof record.error === \"string\" && record.error.trim()) return record.error;\n }\n return `Decionis personal request failed with status ${status}`;\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n const type = response.headers.get(\"content-type\") ?? \"\";\n if (type.includes(\"application/json\")) return await response.json();\n const text = await response.text().catch(() => \"\");\n return text ? { message: text } : null;\n}\n\n/**\n * DecionisPersonalClient is the class form of the client returned by\n * {@link createDecionisPersonalClient}.\n */\nexport class DecionisPersonalClient {\n private readonly options: DecionisPersonalClientOptions;\n private readonly baseUrl: string;\n private readonly fetchImpl: FetchLike;\n\n constructor(options: DecionisPersonalClientOptions) {\n this.options = options;\n this.baseUrl = personalServiceBaseUrl(options.baseUrl);\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n static personalServiceBaseUrl(baseUrl: string): string {\n const base = baseUrl.replace(/\\/+$/, \"\");\n if (base.endsWith(\"/v1/personal\")) return base;\n if (base.endsWith(\"/v1\")) return `${base}/personal`;\n return `${base}/v1/personal`;\n }\n\n static hashPersonalState(value: string | Uint8Array): string {\n return `sha256:${createHash(\"sha256\").update(value).digest(\"hex\")}`;\n }\n\n static normalizePersonalRecallValue(source: DecionisPersonalRecallSource, value: string): string {\n if (source !== \"URL_PATTERN\") return value;\n try {\n const url = new URL(value);\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n } catch {\n return value;\n }\n }\n\n private async request<T>(path: string, init: RequestInit, schema: z.ZodType<T>): Promise<T> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs ?? 4000);\n try {\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n ...init,\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${this.options.deviceToken}`,\n ...(init.body ? { \"content-type\": \"application/json\" } : {}),\n ...(this.options.defaultHeaders ?? {}),\n ...(init.headers ?? {}),\n },\n signal: init.signal ?? controller.signal,\n });\n const body = await readJson(response);\n if (!response.ok) {\n throw new DecionisNodeSdkError(messageFromBody(response.status, body), {\n status: response.status,\n body,\n });\n }\n return schema.parse(body);\n } finally {\n clearTimeout(timeout);\n }\n }\n\n getConfig = (input: { orgId: string }) => {\n return this.request(\n `/config?org_id=${encodeURIComponent(input.orgId)}`,\n {\n method: \"GET\",\n },\n personalConfigResponseSchema,\n );\n };\n\n registerDevice = (input: { orgId: string; label: string; scopes?: string[] }) => {\n return this.request(\n \"/devices/register\",\n {\n method: \"POST\",\n body: JSON.stringify({\n org_id: input.orgId,\n label: input.label,\n scopes: input.scopes,\n }),\n },\n registerDeviceResponseSchema,\n );\n };\n\n captureCapsule = (input: {\n orgId: string;\n title: string;\n stateHash: string;\n payloadRef: string;\n evidenceHashes?: string[];\n retentionDays?: number;\n idempotencyKey?: string;\n }) => {\n return this.request(\n \"/capsules/capture\",\n {\n method: \"POST\",\n body: JSON.stringify({\n org_id: input.orgId,\n title: input.title,\n state_hash: input.stateHash,\n payload_ref: input.payloadRef,\n evidence_hashes: input.evidenceHashes ?? [input.stateHash],\n retention_days: input.retentionDays,\n idempotency_key: input.idempotencyKey,\n }),\n },\n captureCapsuleResponseSchema,\n );\n };\n\n resumeCapsule = (input: {\n orgId: string;\n capsuleId: string;\n stateHash: string;\n idempotencyKey?: string;\n }) => {\n return this.request(\n `/capsules/${encodeURIComponent(input.capsuleId)}/resume`,\n {\n method: \"POST\",\n body: JSON.stringify({\n org_id: input.orgId,\n state_hash: input.stateHash,\n idempotency_key: input.idempotencyKey,\n }),\n },\n resumeCapsuleResponseSchema,\n );\n };\n\n evaluateRecall = (input: {\n orgId: string;\n source: DecionisPersonalRecallSource;\n value: string;\n context?: Record<string, unknown>;\n idempotencyKey?: string;\n }) => {\n const value = normalizePersonalRecallValue(input.source, input.value);\n return this.request(\n \"/recall/evaluate\",\n {\n method: \"POST\",\n body: JSON.stringify({\n org_id: input.orgId,\n source: input.source,\n value,\n context: input.context ?? {},\n idempotency_key: input.idempotencyKey,\n }),\n },\n recallResponseSchema,\n );\n };\n}\n\n/** Functional alias for {@link DecionisPersonalClient.personalServiceBaseUrl}. */\nexport function personalServiceBaseUrl(baseUrl: string): string {\n return DecionisPersonalClient.personalServiceBaseUrl(baseUrl);\n}\n\n/** Functional alias for {@link DecionisPersonalClient.hashPersonalState}. */\nexport function hashPersonalState(value: string | Uint8Array): string {\n return DecionisPersonalClient.hashPersonalState(value);\n}\n\n/** Functional alias for {@link DecionisPersonalClient.normalizePersonalRecallValue}. */\nexport function normalizePersonalRecallValue(\n source: DecionisPersonalRecallSource,\n value: string,\n): string {\n return DecionisPersonalClient.normalizePersonalRecallValue(source, value);\n}\n\n/** Functional alias for {@link DecionisPersonalClient}. */\nexport function createDecionisPersonalClient(options: DecionisPersonalClientOptions) {\n return new DecionisPersonalClient(options);\n}\n","/**\n * Runtime adapter — the layer-cake seam between a sandbox/runtime and Decionis.\n *\n * A runtime-isolation layer (a microVM/sandbox such as Runta, Firecracker, or a\n * container) governs *where* an agent runs: process isolation, network egress,\n * credentials. It is deliberately blind to business meaning. Decionis governs\n * *whether a specific business action is allowed* and proves the verdict. The two\n * compose: an agent inside a sandbox calls this adapter before a consequential\n * action, and the adapter runs the grant-required (strict) path — authorize, then\n * redeem a single-use, action-bound grant, then execute, failing closed otherwise.\n *\n * The adapter is transport-agnostic: it drives any client exposing\n * `enforceAndExecuteStrict` (the {@link DecionisExecutionClient}), and enriches the\n * authority request with the runtime's identity so policy and dossiers record which\n * sandbox the action came from.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { bindAuthorityIntent, type DecionisAuthorityIntentBinding } from \"./ExecutionAuthority.js\";\nimport type {\n DecionisAuthorityAction,\n DecionisAuthorityActor,\n DecionisAuthorityDecision,\n DecionisAuthorityDownstreamTarget,\n DecionisAuthorityRequest,\n DecionisEnforceAndExecuteStrictResult,\n DecionisExecutionClient,\n DecionisExecutionGrantRedemption,\n} from \"./ExecutionAuthority.js\";\n\n/** The sandbox/runtime an agent is executing inside. */\nexport interface DecionisRuntimeContext {\n /** Stable id of the runtime instance (e.g. a Runta runtime id). */\n id: string;\n /** Runtime kind, e.g. \"runta\", \"firecracker\", \"container\". */\n type?: string;\n trust_level?: string | null;\n}\n\n/** The slice of the execution client the adapter drives — the grant-required path. */\nexport type DecionisRuntimeAuthorityClient = Pick<\n DecionisExecutionClient,\n \"enforceAndExecuteStrict\"\n>;\n\nexport interface DecionisRuntimeAdapterConfig {\n client: DecionisRuntimeAuthorityClient;\n runtime: DecionisRuntimeContext;\n tenant_id: string;\n clock?: () => Date;\n createId?: () => string;\n intentTtlSeconds?: number;\n}\n\nexport interface DecionisRuntimeGuardInput {\n actor: DecionisAuthorityActor;\n action: DecionisAuthorityAction;\n downstream_target: DecionisAuthorityDownstreamTarget;\n context?: Record<string, unknown>;\n}\n\ntype DecionisRuntimeExecute<T> = (input: {\n decision: DecionisAuthorityDecision;\n executionToken: string;\n grant: DecionisExecutionGrantRedemption;\n}) => Promise<T> | T;\n\n/**\n * DecionisRuntimeAdapter is the class form of the adapter built by\n * {@link createDecionisRuntimeAdapter}.\n */\nexport class DecionisRuntimeAdapter {\n private readonly config: DecionisRuntimeAdapterConfig;\n\n constructor(config: DecionisRuntimeAdapterConfig) {\n this.config = config;\n }\n\n /** Build the authority request for an action, stamped with the runtime identity. */\n buildRequest = (input: DecionisRuntimeGuardInput): DecionisAuthorityRequest => {\n const { runtime, tenant_id } = this.config;\n const capturedAt = this.config.clock?.() ?? new Date();\n const ttlSeconds = Math.min(Math.max(this.config.intentTtlSeconds ?? 60, 1), 300);\n const trustLevel = input.actor.trust_level ?? runtime.trust_level ?? undefined;\n const binding: DecionisAuthorityIntentBinding = {\n protocol_version: \"agent-safe.intent/1\",\n tenant_id,\n intent_id: this.config.createId?.() ?? randomUUID(),\n captured_at: capturedAt.toISOString(),\n expires_at: new Date(capturedAt.valueOf() + ttlSeconds * 1_000).toISOString(),\n actor: {\n ...input.actor,\n runtime: runtime.id,\n ...(trustLevel === undefined ? {} : { trust_level: trustLevel }),\n },\n action: input.action,\n context: {\n ...(input.context ?? {}),\n runtime: { id: runtime.id, type: runtime.type ?? null },\n },\n downstream_target: input.downstream_target,\n };\n return bindAuthorityIntent(binding);\n };\n\n /**\n * Guard a consequential action from inside the sandbox: authorize, redeem the\n * single-use grant, then execute — failing closed on every other path (see\n * `enforceAndExecuteStrict`). \"No valid grant, no execution.\"\n */\n guard = <T>(\n input: DecionisRuntimeGuardInput,\n execute: DecionisRuntimeExecute<T>,\n ): Promise<DecionisEnforceAndExecuteStrictResult<T>> => {\n return this.config.client.enforceAndExecuteStrict({\n request: this.buildRequest(input),\n execute,\n });\n };\n}\n\n/** Functional alias for {@link DecionisRuntimeAdapter}. */\nexport function createDecionisRuntimeAdapter(config: DecionisRuntimeAdapterConfig) {\n return new DecionisRuntimeAdapter(config);\n}\n\n/**\n * The downstream target the sandbox may open egress to — and ONLY when Decionis\n * authorized the action and the single-use grant redeemed. Containment (sandbox\n * egress allow-listing) composes with authorization (the Decionis grant): keep\n * egress closed until this returns a non-null target.\n */\nexport function authorizedEgressTarget(\n input: DecionisRuntimeGuardInput,\n result: DecionisEnforceAndExecuteStrictResult<unknown>,\n): DecionisAuthorityDownstreamTarget | null {\n return result.executed ? input.downstream_target : null;\n}\n","import { spawn } from \"node:child_process\";\n\nexport interface KubernetesCommandRunner {\n run(args: string[], standardInput?: string): Promise<string>;\n}\n\nexport class KubectlCommandError extends Error {\n public constructor(public readonly code: string) {\n super(code);\n this.name = \"KubectlCommandError\";\n }\n}\n\nexport class KubectlCommandRunner implements KubernetesCommandRunner {\n public constructor(\n private readonly context: string | null,\n private readonly timeoutMs: number = 10_000,\n ) {}\n\n public run(args: string[], standardInput?: string): Promise<string> {\n if (standardInput && Buffer.byteLength(standardInput, \"utf8\") > 4 * 1024 * 1024) {\n return Promise.reject(new KubectlCommandError(\"KUBECTL_STANDARD_INPUT_TOO_LARGE\"));\n }\n const fullArgs = this.context ? [\"--context\", this.context, ...args] : args;\n return new Promise((resolve, reject) => {\n const child = spawn(\"kubectl\", fullArgs, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n const chunks: Buffer[] = [];\n let outputBytes = 0;\n let settled = false;\n const finish = (callback: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n callback();\n };\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n finish(() => reject(new KubectlCommandError(\"KUBECTL_COMMAND_TIMEOUT\")));\n }, this.timeoutMs);\n child.stdout.on(\"data\", (chunk: Buffer) => {\n outputBytes += chunk.length;\n if (outputBytes > 4 * 1024 * 1024) {\n child.kill(\"SIGKILL\");\n finish(() => reject(new KubectlCommandError(\"KUBECTL_COMMAND_OUTPUT_TOO_LARGE\")));\n return;\n }\n chunks.push(chunk);\n });\n // Drain stderr, but never surface it: kubectl errors can echo manifest values.\n child.stderr.resume();\n child.on(\"error\", () => {\n finish(() => reject(new KubectlCommandError(\"KUBECTL_COMMAND_FAILED\")));\n });\n child.on(\"close\", (code) => {\n finish(() => {\n if (code !== 0) {\n reject(new KubectlCommandError(\"KUBECTL_COMMAND_FAILED\"));\n return;\n }\n resolve(Buffer.concat(chunks).toString(\"utf8\"));\n });\n });\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(standardInput);\n });\n }\n}\n","/**\n * Canonical JSON used to hash and sign Decision Dossier artifacts.\n *\n * This MUST stay byte-for-byte identical to the server's canonicalization\n * (`DecisionDossierIntegrity.stableJsonStringify` in `@decionis/shared`), or a\n * signature produced by the server will not verify here. The rule is simple and\n * intentionally boring: recursively sort object keys, leave arrays and scalars\n * in place, then `JSON.stringify`. There is a parity test asserting this matches\n * the server implementation for a battery of inputs.\n */\nexport function canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => canonicalize(item));\n }\n if (!value || typeof value !== \"object\") {\n return value;\n }\n const record = value as Record<string, unknown>;\n const sortedKeys = Object.keys(record).sort();\n const normalized: Record<string, unknown> = {};\n for (const key of sortedKeys) {\n normalized[key] = canonicalize(record[key]);\n }\n return normalized;\n}\n\nexport function stableJsonStringify(value: unknown): string {\n return JSON.stringify(canonicalize(value));\n}\n\n/** RFC 8785/JCS canonical JSON used only by execution-binding artifacts. */\nexport function jcsCanonicalize(value: unknown): string {\n if (value === null) return \"null\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"string\") {\n assertUnicodeScalarString(value);\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(\"JCS_NUMBER_MUST_BE_FINITE\");\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `[${value.map((item) => jcsCanonicalize(item)).join(\",\")}]`;\n if (!value || typeof value !== \"object\") throw new TypeError(\"JCS_VALUE_NOT_JSON\");\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(\"JCS_OBJECT_MUST_BE_PLAIN\");\n }\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .sort()\n .map((key) => {\n assertUnicodeScalarString(key);\n if (record[key] === undefined) throw new TypeError(\"JCS_UNDEFINED_NOT_ALLOWED\");\n return `${JSON.stringify(key)}:${jcsCanonicalize(record[key])}`;\n })\n .join(\",\")}}`;\n}\n\nfunction assertUnicodeScalarString(value: string): void {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) throw new TypeError(\"JCS_LONE_SURROGATE\");\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n throw new TypeError(\"JCS_LONE_SURROGATE\");\n }\n }\n}\n","import { createHash, createPublicKey, verify as verifyEd25519 } from \"node:crypto\";\n\nimport { jcsCanonicalize, stableJsonStringify } from \"./canonical.js\";\n\n/**\n * `inputs_snapshot` carries the facts the verdict was reached on — amount, risk\n * score, request context. It was added after \"2.1\" deliberately without a\n * version bump: this parser rejects any version outside \"2.0\"/\"2.1\" but\n * iterates artifacts generically, so a new kind verifies correctly on every\n * copy of this package already installed, where a version bump would break all\n * of them.\n */\nexport type ProofArtifactKind =\n | \"portable_artifact\"\n | \"json_ld\"\n | \"execution_binding\"\n | \"inputs_snapshot\";\n\nexport interface ProofArtifact {\n artifact_kind: ProofArtifactKind;\n media_type: \"application/json\" | \"application/ld+json\";\n document_path: string;\n canonical_document_sha256: string;\n canonicalization_profile?: \"DECIONIS_SORTED_JSON_V1\" | \"RFC8785/JCS\";\n signature: string;\n}\n\nexport interface KeyRotationPolicy {\n strategy: string;\n active_key_id: string;\n previous_key_ids: string[];\n verification_grace_period_days: number;\n rotated_at: string | null;\n public_jwks_path: string;\n /** Absolute JWKS URL, present when the dossier was served by the public API. */\n public_jwks_url?: string;\n}\n\nexport interface DecisionDossierProofBundle {\n bundle_type: \"decionis.decision_dossier.proof_bundle\";\n version: \"2.0\" | \"2.1\";\n issued_at: string;\n algorithm: \"Ed25519\";\n key_id: string;\n rotation_policy: KeyRotationPolicy;\n artifacts: ProofArtifact[];\n}\n\nexport interface Jwks {\n keys: Array<Record<string, unknown>>;\n}\n\nexport interface VerifyCheck {\n key: string;\n label: string;\n verified: boolean;\n severity: \"pass\" | \"warn\" | \"fail\";\n detail: string;\n}\n\nexport interface VerifyResult {\n /** True only when every check passed. */\n verified: boolean;\n /** True when a well-formed Ed25519 proof bundle was found to check. */\n available: boolean;\n key_id: string | null;\n artifacts_checked: number;\n checks: VerifyCheck[];\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n}\n\nfunction asString(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\n/** RFC 6901 JSON Pointer resolution (objects only — mirrors the server). */\nfunction resolveJsonPointer(root: unknown, pointer: string): unknown {\n if (!pointer.startsWith(\"/\")) return undefined;\n return pointer\n .split(\"/\")\n .slice(1)\n .reduce<unknown>((current, rawSegment) => {\n const segment = rawSegment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n if (current && typeof current === \"object\" && !Array.isArray(current)) {\n return (current as Record<string, unknown>)[segment];\n }\n return undefined;\n }, root);\n}\n\nfunction findJwk(jwks: Jwks | null, keyIds: string[]): Record<string, unknown> | null {\n const wanted = new Set(keyIds.filter((keyId) => keyId.trim().length > 0));\n if (!jwks || wanted.size === 0) return null;\n for (const key of jwks.keys) {\n if (\n asString(key.kty) === \"OKP\" &&\n asString(key.crv) === \"Ed25519\" &&\n wanted.has(asString(key.kid) ?? \"\")\n ) {\n return key;\n }\n }\n return null;\n}\n\n/**\n * Validate and normalize a persisted proof bundle. Returns null when the value\n * is not a v2.0 Ed25519 proof bundle with at least one well-formed artifact.\n * Mirrors `DecisionDossierSignatures.getPersistedDecisionDossierProofBundle`.\n */\nexport function parseProofBundle(value: unknown): DecisionDossierProofBundle | null {\n const record = asRecord(value);\n if (\n asString(record.bundle_type) !== \"decionis.decision_dossier.proof_bundle\" ||\n (asString(record.version) !== \"2.0\" && asString(record.version) !== \"2.1\") ||\n asString(record.issued_at) == null ||\n asString(record.key_id) == null\n ) {\n return null;\n }\n\n const rotationPolicyRecord = asRecord(record.rotation_policy);\n const activeKeyId = asString(rotationPolicyRecord.active_key_id);\n const publicJwksPath = asString(rotationPolicyRecord.public_jwks_path);\n if (!activeKeyId || !publicJwksPath) return null;\n\n const artifacts = (Array.isArray(record.artifacts) ? record.artifacts : [])\n .map((entry): ProofArtifact | null => {\n const item = asRecord(entry);\n const artifactKind = asString(item.artifact_kind);\n const mediaType = asString(item.media_type);\n const documentPath = asString(item.document_path);\n const canonicalDocumentSha = asString(item.canonical_document_sha256);\n const signature = asString(item.signature);\n const canonicalizationProfile = asString(item.canonicalization_profile);\n if (!artifactKind || !mediaType || !documentPath || !canonicalDocumentSha || !signature) {\n return null;\n }\n return {\n artifact_kind: artifactKind as ProofArtifactKind,\n media_type: mediaType as ProofArtifact[\"media_type\"],\n document_path: documentPath,\n canonical_document_sha256: canonicalDocumentSha,\n ...(canonicalizationProfile === \"RFC8785/JCS\" ||\n canonicalizationProfile === \"DECIONIS_SORTED_JSON_V1\"\n ? { canonicalization_profile: canonicalizationProfile }\n : {}),\n signature,\n };\n })\n .filter((item): item is ProofArtifact => item !== null);\n if (artifacts.length === 0) return null;\n\n const previousKeyIds = (\n Array.isArray(rotationPolicyRecord.previous_key_ids)\n ? rotationPolicyRecord.previous_key_ids\n : []\n )\n .map((entry) => asString(entry))\n .filter((entry): entry is string => entry !== null);\n\n const gracePeriod = Number.parseInt(\n String(rotationPolicyRecord.verification_grace_period_days ?? \"\"),\n 10,\n );\n\n return {\n bundle_type: \"decionis.decision_dossier.proof_bundle\",\n version: asString(record.version) as \"2.0\" | \"2.1\",\n issued_at: asString(record.issued_at) as string,\n algorithm: \"Ed25519\",\n key_id: asString(record.key_id) as string,\n rotation_policy: {\n strategy: asString(rotationPolicyRecord.strategy) ?? \"JWKS_OVERLAP\",\n active_key_id: activeKeyId,\n previous_key_ids: previousKeyIds,\n verification_grace_period_days: Number.isFinite(gracePeriod) ? gracePeriod : 0,\n rotated_at: asString(rotationPolicyRecord.rotated_at),\n public_jwks_path: publicJwksPath,\n public_jwks_url: asString(rotationPolicyRecord.public_jwks_url) ?? undefined,\n },\n artifacts,\n };\n}\n\n/**\n * Independently verify a Decision Dossier's Ed25519 proof bundle against a\n * public JWKS. Every input is public: the dossier payload and the JWKS. This is\n * a faithful, dependency-free port of the server verifier — a third party can\n * run it with no Decionis involvement and get the same answer.\n */\nexport function verifyDossierProofBundle(input: {\n dossier_payload: Record<string, unknown>;\n public_jwks?: Jwks | null;\n}): VerifyResult {\n const integrity = asRecord(input.dossier_payload.integrity);\n const bundle = parseProofBundle(integrity.proof_bundle);\n if (!bundle) {\n return {\n verified: false,\n available: false,\n key_id: null,\n artifacts_checked: 0,\n checks: [\n {\n key: \"proof_bundle\",\n label: \"Proof Bundle\",\n verified: false,\n severity: \"warn\",\n detail: \"No persisted Ed25519 proof bundle was available for verification.\",\n },\n ],\n };\n }\n\n const jwk = findJwk(input.public_jwks ?? null, [\n bundle.key_id,\n bundle.rotation_policy.active_key_id,\n ...bundle.rotation_policy.previous_key_ids,\n ]);\n if (!jwk) {\n return {\n verified: false,\n available: true,\n key_id: bundle.key_id,\n artifacts_checked: 0,\n checks: [\n {\n key: \"public_key\",\n label: \"Public Key\",\n verified: false,\n severity: \"fail\",\n detail: `No Ed25519 public key matched proof bundle key ${bundle.key_id}.`,\n },\n ],\n };\n }\n\n let publicKey: ReturnType<typeof createPublicKey>;\n try {\n publicKey = createPublicKey({ key: jwk as Record<string, unknown>, format: \"jwk\" });\n } catch (err) {\n return {\n verified: false,\n available: true,\n key_id: bundle.key_id,\n artifacts_checked: 0,\n checks: [\n {\n key: \"public_key\",\n label: \"Public Key\",\n verified: false,\n severity: \"fail\",\n detail: err instanceof Error ? err.message : \"Unable to import Ed25519 public key.\",\n },\n ],\n };\n }\n\n const checks: VerifyCheck[] = [\n {\n key: \"public_key\",\n label: \"Public Key\",\n verified: true,\n severity: \"pass\",\n detail: `Loaded Ed25519 public key ${String(jwk.kid ?? bundle.key_id)}.`,\n },\n ];\n let artifactsChecked = 0;\n\n for (const artifact of bundle.artifacts) {\n const document = resolveJsonPointer(input.dossier_payload, artifact.document_path);\n if (document === undefined) {\n checks.push({\n key: `${artifact.artifact_kind}:document`,\n label: `${artifact.artifact_kind} Document`,\n verified: false,\n severity: \"fail\",\n detail: `Signed document path ${artifact.document_path} was not present in the dossier payload.`,\n });\n continue;\n }\n\n const canonicalDocument =\n artifact.canonicalization_profile === \"RFC8785/JCS\"\n ? jcsCanonicalize(document)\n : stableJsonStringify(document);\n const actualSha = createHash(\"sha256\").update(canonicalDocument, \"utf8\").digest(\"hex\");\n const hashVerified =\n actualSha.toLowerCase() === artifact.canonical_document_sha256.toLowerCase();\n checks.push({\n key: `${artifact.artifact_kind}:sha256`,\n label: `${artifact.artifact_kind} SHA-256`,\n verified: hashVerified,\n severity: hashVerified ? \"pass\" : \"fail\",\n detail: hashVerified\n ? `Canonical digest ${actualSha}.`\n : `Expected ${artifact.canonical_document_sha256}, computed ${actualSha}.`,\n });\n\n let signatureVerified = false;\n try {\n signatureVerified = verifyEd25519(\n null,\n Buffer.from(canonicalDocument, \"utf8\"),\n publicKey,\n Buffer.from(artifact.signature, \"base64url\"),\n );\n } catch {\n signatureVerified = false;\n }\n checks.push({\n key: `${artifact.artifact_kind}:signature`,\n label: `${artifact.artifact_kind} Signature`,\n verified: signatureVerified,\n severity: signatureVerified ? \"pass\" : \"fail\",\n detail: signatureVerified\n ? \"Ed25519 signature verified against the public JWKS.\"\n : \"Ed25519 signature did not verify against the public JWKS.\",\n });\n artifactsChecked += 1;\n }\n\n return {\n verified: checks.every((check) => check.verified),\n available: true,\n key_id: bundle.key_id,\n artifacts_checked: artifactsChecked,\n checks,\n };\n}\n\n/**\n * Reproducibility is the differentiator over a plain signed audit record: a\n * verified signature proves a dossier was not altered, but reproducibility means\n * a third party can re-run the exact recorded policy against the exact recorded\n * inputs and get the same verdict. That recompute needs the deterministic engine,\n * so it is not offline — but whether a dossier *carries what the engine needs* to\n * reproduce it IS offline-checkable. This reports that posture.\n */\nexport type ReproducibilityPosture = \"reproduction_ready\" | \"incomplete\" | \"signature_only\";\n\nexport interface ReproducibilityInput {\n key: string;\n label: string;\n present: boolean;\n value: string | null;\n}\n\nexport interface ReproducibilityAssessment {\n posture: ReproducibilityPosture;\n detail: string;\n inputs: ReproducibilityInput[];\n}\n\nfunction isNonEmptyObject(value: unknown): boolean {\n return (\n !!value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value as Record<string, unknown>).length > 0\n );\n}\n\n/**\n * Assess whether a dossier payload carries every input the server-side reproduce\n * routine reads to deterministically re-run the decision: the recorded outcome,\n * the policy version, the recorded rules hash (the anchor that proves the same\n * bundle was applied), the evaluation timestamp, and the inputs snapshot. Mirrors\n * the field reads in `apps/protocol/src/reproduce/ReproduceDecision.ts`. Purely a\n * shape/coverage check — it never claims the verdict *did* reproduce, only that\n * the dossier is reproduction-ready.\n */\nexport function assessDossierReproducibility(\n dossier_payload: Record<string, unknown>,\n): ReproducibilityAssessment {\n const payload = asRecord(dossier_payload);\n const policySnapshot = asRecord(asRecord(payload.governance).policy_snapshot);\n const routing = asRecord(payload.routing_decision);\n\n const recordedOutcome = asString(routing.outcome);\n const policyVersion = asString(policySnapshot.policy_version) ?? asString(routing.policy_version);\n const rulesSha = asString(policySnapshot.rules_sha256);\n const evaluatedAt =\n asString(policySnapshot.evaluated_at) ??\n asString(asRecord(routing.policy_evaluation).evaluated_at) ??\n asString(payload.generated_at);\n const inputsPresent = isNonEmptyObject(payload.inputs_snapshot);\n\n const inputs: ReproducibilityInput[] = [\n {\n key: \"recorded_outcome\",\n label: \"Recorded outcome\",\n present: !!recordedOutcome,\n value: recordedOutcome,\n },\n {\n key: \"policy_version\",\n label: \"Policy version\",\n present: !!policyVersion,\n value: policyVersion,\n },\n { key: \"rules_sha256\", label: \"Recorded rules hash\", present: !!rulesSha, value: rulesSha },\n {\n key: \"evaluated_at\",\n label: \"Evaluation timestamp\",\n present: !!evaluatedAt,\n value: evaluatedAt,\n },\n { key: \"inputs_snapshot\", label: \"Inputs snapshot\", present: inputsPresent, value: null },\n ];\n\n const presentCount = inputs.filter((input) => input.present).length;\n let posture: ReproducibilityPosture;\n let detail: string;\n if (presentCount === inputs.length) {\n posture = \"reproduction_ready\";\n detail =\n \"Carries the recorded policy version, rules hash, evaluation time, outcome, and inputs — the engine can re-run this decision and hash-match the exact recorded bundle.\";\n } else if (presentCount === 0) {\n posture = \"signature_only\";\n detail =\n \"No reproduction metadata present. The signature can still be verified, but the verdict cannot be independently recomputed — this is a signed record, not a reproducible one.\";\n } else {\n posture = \"incomplete\";\n const missing = inputs.filter((input) => !input.present).map((input) => input.label);\n detail = `Missing reproduction inputs: ${missing.join(\", \")}. Reproduction would return indeterminate.`;\n }\n\n return { posture, detail, inputs };\n}\n","import {\n parseProofBundle,\n verifyDossierProofBundle,\n type Jwks,\n type VerifyResult,\n} from \"./verify.js\";\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n}\n\n/**\n * Pull the signed dossier payload out of whatever envelope a public endpoint\n * returned. The payload is the object carrying `integrity.proof_bundle`; accept\n * the raw payload or a common wrapper key so callers don't have to care.\n */\nexport function extractDossierPayload(body: unknown): Record<string, unknown> {\n const record = asRecord(body);\n if (asRecord(record.integrity).proof_bundle !== undefined) return record;\n for (const key of [\"dossier\", \"dossier_payload\", \"data\", \"result\"]) {\n const candidate = asRecord(record[key]);\n if (asRecord(candidate.integrity).proof_bundle !== undefined) return candidate;\n }\n // Fall back to the record itself; verify() will report \"no proof bundle\".\n return record;\n}\n\n/**\n * Work out where to fetch the public JWKS for a dossier. Prefer the absolute\n * URL the public API embeds; otherwise resolve the relative `public_jwks_path`\n * against the origin the dossier was served from.\n */\nexport function resolveJwksUrl(\n payload: Record<string, unknown>,\n dossierUrl: string,\n): string | null {\n const bundle = parseProofBundle(asRecord(payload.integrity).proof_bundle);\n if (!bundle) return null;\n const absolute = bundle.rotation_policy.public_jwks_url;\n if (absolute && /^https?:\\/\\//i.test(absolute)) return absolute;\n try {\n return new URL(bundle.rotation_policy.public_jwks_path, dossierUrl).toString();\n } catch {\n return null;\n }\n}\n\nconst MAX_VERIFICATION_RESPONSE_BYTES = 2 * 1024 * 1024;\n\nasync function fetchJson(url: string, fetchImpl: typeof fetch): Promise<unknown> {\n const response = await fetchImpl(url, { headers: { accept: \"application/json\" } });\n if (!response.ok) {\n throw new Error(`Request to ${url} failed with HTTP ${response.status}.`);\n }\n const responseText = await boundedResponseText(response, url);\n return JSON.parse(responseText) as unknown;\n}\n\nasync function boundedResponseText(response: Response, url: string): Promise<string> {\n const declaredLength = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declaredLength) && declaredLength > MAX_VERIFICATION_RESPONSE_BYTES) {\n throw new Error(`Response from ${url} exceeded the verification size limit.`);\n }\n if (!response.body) return \"\";\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let receivedBytes = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n receivedBytes += value.byteLength;\n if (receivedBytes > MAX_VERIFICATION_RESPONSE_BYTES) {\n await reader.cancel().catch(() => undefined);\n throw new Error(`Response from ${url} exceeded the verification size limit.`);\n }\n chunks.push(value);\n }\n return Buffer.concat(\n chunks.map((chunk) => Buffer.from(chunk)),\n receivedBytes,\n ).toString(\"utf8\");\n}\n\n/**\n * Fetch a dossier (and its JWKS, auto-discovered unless overridden) from public\n * URLs and verify its Ed25519 proof bundle. Node 18+ `fetch` only — no SDK.\n */\nexport async function verifyDossierFromUrls(input: {\n dossierUrl: string;\n jwksUrl?: string;\n fetch?: typeof fetch;\n}): Promise<{\n result: VerifyResult;\n jwksUrl: string | null;\n payload: Record<string, unknown>;\n}> {\n const fetchImpl = input.fetch ?? fetch;\n const body = await fetchJson(input.dossierUrl, fetchImpl);\n const payload = extractDossierPayload(body);\n const jwksUrl = input.jwksUrl ?? resolveJwksUrl(payload, input.dossierUrl);\n if (!jwksUrl) {\n return {\n result: verifyDossierProofBundle({ dossier_payload: payload, public_jwks: null }),\n jwksUrl: null,\n payload,\n };\n }\n const jwks = (await fetchJson(jwksUrl, fetchImpl)) as Jwks;\n return {\n result: verifyDossierProofBundle({ dossier_payload: payload, public_jwks: jwks }),\n jwksUrl,\n payload,\n };\n}\n","import {\n createDecionisExecutionClient,\n type DecionisAuthorityDecision,\n type DecionisAuthorityRequest,\n type DecionisExecutionGrantRedemption,\n} from \"@decionis/sdk\";\nimport { verifyDossierFromUrls } from \"@decionis/verify\";\nimport type {\n KubernetesActionPlanner,\n PlannedKubernetesAction,\n} from \"./KubernetesActionPlanner.js\";\nimport type { KubernetesCommandRunner } from \"./KubernetesCommandRunner.js\";\n\nexport interface KubernetesAuthorityClient {\n enforceAndBind(request: DecionisAuthorityRequest): Promise<DecionisAuthorityDecision>;\n redeemGrant(\n executionToken: string,\n request: DecionisAuthorityRequest,\n decision: DecionisAuthorityDecision,\n ): Promise<DecionisExecutionGrantRedemption>;\n}\n\nexport interface KubernetesOperationResult {\n executed: boolean;\n verdict: \"ALLOW\" | \"HOLD\" | \"BLOCK\" | \"ERROR\";\n decisions: KubernetesDecisionSummary[];\n kubernetes_result?: string;\n reason_code?: string;\n}\n\nexport interface KubernetesDecisionSummary {\n verdict: KubernetesOperationResult[\"verdict\"];\n decision_id: string;\n dossier_id: string | null;\n dossier_sha256: string | null;\n dossier_url: string | null;\n policy_version: string | null;\n approval_request_id: string | null;\n reason_codes: string[];\n action_hash: string;\n expected_action_hash: string;\n resource: string;\n namespace: string | null;\n name: string;\n}\n\nexport class KubernetesOperations {\n public constructor(\n private readonly planner: KubernetesActionPlanner,\n private readonly runner: KubernetesCommandRunner,\n private readonly authority: KubernetesAuthorityClient,\n private readonly allowedVerificationOrigins: ReadonlySet<string>,\n ) {}\n\n public async plan(manifestPath: string, namespace: string | null) {\n return this.planSummary(\n await this.planner.planManifest(manifestPath, namespace, \"mcp:k8s_plan\"),\n );\n }\n\n public async requestAuthority(manifestPath: string, namespace: string | null) {\n const planned = await this.planner.planManifest(\n manifestPath,\n namespace,\n \"mcp:k8s_request_authority\",\n );\n const decisions = await Promise.all(\n planned.map(async (action) => this.authority.enforceAndBind(action.request)),\n );\n return decisions.map((decision, index) => this.decisionSummary(decision, planned[index]!));\n }\n\n public async apply(\n manifestPath: string,\n namespace: string | null,\n ): Promise<KubernetesOperationResult> {\n const planned = await this.planner.planManifest(manifestPath, namespace, \"mcp:k8s_apply\");\n return this.authorizeAndExecute(planned, async () => {\n const args = [\"apply\", \"--filename\", \"-\"];\n if (namespace) args.push(\"--namespace\", namespace);\n return this.runner.run(args, KubernetesOperations.executionManifest(planned));\n });\n }\n\n public async rollback(\n manifestPath: string,\n namespace: string | null,\n ): Promise<KubernetesOperationResult> {\n const planned = await this.planner.planManifest(manifestPath, namespace, \"mcp:k8s_rollback\");\n if (planned.some((action) => action.operation !== \"UPDATE\")) {\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: [],\n reason_code: \"KUBERNETES_ROLLBACK_TARGET_NOT_FOUND\",\n };\n }\n return this.authorizeAndExecute(planned, async () => {\n const args = [\"apply\", \"--filename\", \"-\"];\n if (namespace) args.push(\"--namespace\", namespace);\n return this.runner.run(args, KubernetesOperations.executionManifest(planned));\n });\n }\n\n public async scale(input: {\n namespace: string;\n name: string;\n replicas: number;\n }): Promise<KubernetesOperationResult> {\n const planned = await this.planner.planScale(input);\n if (!planned.executionEndpoint) throw new Error(\"KUBERNETES_SCALE_ENDPOINT_MISSING\");\n return this.authorizeAndExecute([planned], () =>\n this.runner.run(\n [\"replace\", \"--raw\", planned.executionEndpoint!, \"--filename\", \"-\"],\n JSON.stringify(planned.executionObject),\n ),\n );\n }\n\n public async verifyDossier(dossierUrl: string, jwksUrl: string) {\n this.assertAllowedVerificationUrl(dossierUrl);\n this.assertAllowedVerificationUrl(jwksUrl);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 10_000);\n try {\n const verified = await verifyDossierFromUrls({\n dossierUrl,\n jwksUrl,\n fetch: (input, init) =>\n fetch(input, { ...init, redirect: \"error\", signal: controller.signal }),\n });\n return {\n verified: verified.result.verified,\n available: verified.result.available,\n key_id: verified.result.key_id,\n artifacts_checked: verified.result.artifacts_checked,\n checks: verified.result.checks,\n jwks_url: verified.jwksUrl,\n };\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async authorizeAndExecute(\n planned: PlannedKubernetesAction[],\n execute: () => Promise<string>,\n ): Promise<KubernetesOperationResult> {\n const decisions: DecionisAuthorityDecision[] = [];\n for (const action of planned) {\n try {\n decisions.push(await this.authority.enforceAndBind(action.request));\n } catch {\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: decisions.map((decision, index) =>\n this.decisionSummary(decision, planned[index]!),\n ),\n reason_code: \"DECIONIS_AUTHORITY_UNAVAILABLE\",\n };\n }\n }\n const summaries = decisions.map((decision, index) =>\n this.decisionSummary(decision, planned[index]!),\n );\n const deniedIndex = decisions.findIndex(\n (decision, index) =>\n decision.status !== \"ALLOW\" ||\n !decision.should_execute ||\n !decision.execution_token ||\n decision.mode !== \"ENFORCEMENT\" ||\n decision.action_hash !== planned[index]?.request.intent_hash ||\n !decision.dossier_id ||\n !decision.dossier_sha256,\n );\n if (deniedIndex >= 0) {\n const decision = decisions[deniedIndex]!;\n return {\n executed: false,\n verdict: KubernetesOperations.verdict(decision),\n decisions: summaries,\n reason_code: decision.reason_codes[0] ?? \"DECIONIS_EXECUTION_NOT_AUTHORIZED\",\n };\n }\n\n for (let index = 0; index < decisions.length; index += 1) {\n const decision = decisions[index]!;\n const action = planned[index]!;\n const redemption = await this.authority.redeemGrant(\n decision.execution_token!,\n action.request,\n decision,\n );\n if (!redemption.valid) {\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: summaries,\n reason_code: redemption.reason_codes[0] ?? \"DECIONIS_EXECUTION_GRANT_INVALID\",\n };\n }\n }\n\n try {\n return {\n executed: true,\n verdict: \"ALLOW\",\n decisions: summaries,\n kubernetes_result: (await execute()).trim().slice(0, 8_000),\n };\n } catch {\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: summaries,\n reason_code: \"KUBERNETES_EXECUTION_FAILED_FRESH_AUTHORITY_REQUIRED\",\n };\n }\n }\n\n private planSummary(planned: PlannedKubernetesAction[]) {\n return planned.map((action) => ({\n action_hash: action.request.intent_hash,\n action_type: action.request.action.type,\n operation: action.operation,\n api_group: action.apiGroup,\n api_version: action.apiVersion,\n kind: action.kind,\n resource: action.resource,\n namespace: action.namespace,\n name: action.name,\n old_object_digest: action.oldObjectDigest,\n proposed_object_digest: action.proposedObjectDigest,\n material_diff: action.materialDiff,\n material_facts: action.materialFacts,\n note: \"No raw manifest or Secret value is included in this plan.\",\n }));\n }\n\n private decisionSummary(\n decision: DecionisAuthorityDecision,\n action: PlannedKubernetesAction,\n ): KubernetesDecisionSummary {\n return {\n verdict: KubernetesOperations.verdict(decision),\n decision_id: decision.decision_id,\n dossier_id: decision.dossier_id,\n dossier_sha256: decision.dossier_sha256,\n dossier_url: decision.dossier_url,\n policy_version: decision.policy_version,\n approval_request_id: decision.approval_request_id,\n reason_codes: decision.reason_codes,\n action_hash: decision.action_hash,\n expected_action_hash: action.request.intent_hash,\n resource: action.resource,\n namespace: action.namespace,\n name: action.name,\n };\n }\n\n private static verdict(\n decision: DecionisAuthorityDecision,\n ): KubernetesOperationResult[\"verdict\"] {\n if (decision.status === \"ALLOW\") return \"ALLOW\";\n if (decision.status === \"ESCALATE\" || decision.status === \"REVIEW_REQUIRED\") return \"HOLD\";\n if (decision.status === \"BLOCK\") return \"BLOCK\";\n return \"ERROR\";\n }\n\n private static executionManifest(planned: PlannedKubernetesAction[]): string {\n if (planned.length === 1) return JSON.stringify(planned[0]!.executionObject);\n return JSON.stringify({\n apiVersion: \"v1\",\n kind: \"List\",\n items: planned.map((action) => action.executionObject),\n });\n }\n\n private assertAllowedVerificationUrl(input: string): void {\n const url = new URL(input);\n if (\n url.protocol !== \"https:\" ||\n url.username ||\n url.password ||\n !this.allowedVerificationOrigins.has(url.origin)\n ) {\n throw new Error(\"DOSSIER_URL_ORIGIN_NOT_ALLOWED\");\n }\n }\n}\n\nexport function createKubernetesAuthorityClient(input: {\n baseUrl: string;\n apiKey: string;\n timeoutMs: number;\n}): KubernetesAuthorityClient {\n return createDecionisExecutionClient({\n authorityBaseUrl: input.baseUrl,\n timeoutMs: input.timeoutMs,\n defaultHeaders: { authorization: `Bearer ${input.apiKey}` },\n });\n}\n","import type { ToolContent, ToolDefinition } from \"../Server.js\";\nimport { KubernetesActionPlanner } from \"./KubernetesActionPlanner.js\";\nimport { KubectlCommandRunner } from \"./KubernetesCommandRunner.js\";\nimport { createKubernetesAuthorityClient, KubernetesOperations } from \"./KubernetesOperations.js\";\n\nconst text = (value: unknown): ToolContent[] => [\n { type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2) },\n];\n\nexport class KubernetesMcpTools {\n public constructor(private readonly operations: KubernetesOperations) {}\n\n public build(): ToolDefinition[] {\n const manifestSchema = {\n type: \"object\",\n required: [\"manifest_path\"],\n properties: {\n manifest_path: {\n type: \"string\",\n description:\n \"Local path to the exact Kubernetes manifest. Manifest content is never returned.\",\n },\n namespace: { type: \"string\", description: \"Optional namespace fallback.\" },\n },\n additionalProperties: false,\n };\n return [\n {\n name: \"k8s_plan\",\n title: \"Plan Exact Kubernetes Actions\",\n description:\n \"Resolve an exact manifest against the current cluster and return only digests, bounded material facts, and action hashes. Does not call authority or mutate Kubernetes.\",\n inputSchema: manifestSchema,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n handler: async (args) => ({\n content: text(\n await this.operations.plan(\n KubernetesMcpTools.requiredString(args.manifest_path, \"manifest_path\"),\n KubernetesMcpTools.optionalNamespace(args.namespace),\n ),\n ),\n }),\n },\n {\n name: \"k8s_request_authority\",\n title: \"Request Kubernetes Execution Authority\",\n description:\n \"Ask the existing Decionis authority for ALLOW, HOLD, or BLOCK on each exact manifest action and return dossier references. Does not run kubectl apply.\",\n inputSchema: manifestSchema,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (args) => ({\n content: text(\n await this.operations.requestAuthority(\n KubernetesMcpTools.requiredString(args.manifest_path, \"manifest_path\"),\n KubernetesMcpTools.optionalNamespace(args.namespace),\n ),\n ),\n }),\n },\n {\n name: \"k8s_apply\",\n title: \"Apply an Authorized Kubernetes Manifest\",\n description:\n \"Recompute the exact action, require and consume a Decionis ALLOW grant, then run kubectl apply. The admission webhook remains the independent cluster-side gate.\",\n inputSchema: manifestSchema,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (args) => ({\n content: text(\n await this.operations.apply(\n KubernetesMcpTools.requiredString(args.manifest_path, \"manifest_path\"),\n KubernetesMcpTools.optionalNamespace(args.namespace),\n ),\n ),\n }),\n },\n {\n name: \"k8s_scale\",\n title: \"Scale an Authorized Kubernetes Deployment\",\n description:\n \"Bind the exact Deployment scale object and replica count, require and consume a Decionis ALLOW grant, then run kubectl scale. Scale-to-zero is visible as a material fact.\",\n inputSchema: {\n type: \"object\",\n required: [\"namespace\", \"name\", \"replicas\"],\n properties: {\n namespace: { type: \"string\" },\n name: { type: \"string\" },\n replicas: { type: \"integer\", minimum: 0, maximum: 1000000 },\n },\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (args) => ({\n content: text(\n await this.operations.scale({\n namespace: KubernetesMcpTools.requiredDnsName(args.namespace, \"namespace\"),\n name: KubernetesMcpTools.requiredDnsName(args.name, \"name\"),\n replicas: KubernetesMcpTools.requiredInteger(args.replicas, \"replicas\"),\n }),\n ),\n }),\n },\n {\n name: \"k8s_rollback\",\n title: \"Apply an Exact Authorized Rollback\",\n description:\n \"Apply an operator-supplied exact rollback manifest only when the target already exists and Decionis grants the bound UPDATE. Vague rollout undo is intentionally not used.\",\n inputSchema: manifestSchema,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n },\n handler: async (args) => ({\n content: text(\n await this.operations.rollback(\n KubernetesMcpTools.requiredString(args.manifest_path, \"manifest_path\"),\n KubernetesMcpTools.optionalNamespace(args.namespace),\n ),\n ),\n }),\n },\n {\n name: \"k8s_verify_dossier\",\n title: \"Verify a Kubernetes Decision Dossier\",\n description:\n \"Fetch a dossier proof bundle and JWKS from configured HTTPS origins and verify SHA-256 plus Ed25519 evidence independently.\",\n inputSchema: {\n type: \"object\",\n required: [\"dossier_url\", \"jwks_url\"],\n properties: {\n dossier_url: { type: \"string\", format: \"uri\" },\n jwks_url: { type: \"string\", format: \"uri\" },\n },\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n handler: async (args) => ({\n content: text(\n await this.operations.verifyDossier(\n KubernetesMcpTools.requiredString(args.dossier_url, \"dossier_url\"),\n KubernetesMcpTools.requiredString(args.jwks_url, \"jwks_url\"),\n ),\n ),\n }),\n },\n ];\n }\n\n private static requiredString(input: unknown, field: string): string {\n if (typeof input !== \"string\" || !input.trim())\n throw new Error(`${field.toUpperCase()}_REQUIRED`);\n return input.trim();\n }\n\n private static optionalNamespace(input: unknown): string | null {\n if (input === undefined) return null;\n return KubernetesMcpTools.requiredDnsName(input, \"namespace\");\n }\n\n private static requiredDnsName(input: unknown, field: string): string {\n const value = KubernetesMcpTools.requiredString(input, field);\n if (!/^[a-z0-9](?:[-a-z0-9.]*[a-z0-9])?$/.test(value) || value.length > 253) {\n throw new Error(`${field.toUpperCase()}_INVALID`);\n }\n return value;\n }\n\n private static requiredInteger(input: unknown, field: string): number {\n if (!Number.isInteger(input)) throw new Error(`${field.toUpperCase()}_INVALID`);\n return input as number;\n }\n}\n\nexport function createKubernetesMcpToolsFromEnvironment(\n environment: NodeJS.ProcessEnv = process.env,\n): ToolDefinition[] {\n if (environment.DECIONIS_KUBERNETES_TOOLS_ENABLED !== \"true\") return [];\n const baseUrl = requiredEnvironment(environment, \"DECIONIS_AUTHORITY_BASE_URL\");\n const apiKey = requiredEnvironment(environment, \"DECIONIS_API_KEY\");\n const organizationId = requiredEnvironment(environment, \"DECIONIS_ORG_ID\");\n const clusterId = requiredEnvironment(environment, \"DECIONIS_KUBERNETES_CLUSTER_ID\");\n const actorId = requiredEnvironment(environment, \"DECIONIS_KUBERNETES_ACTOR\");\n const policyVersion = requiredEnvironment(environment, \"DECIONIS_KUBERNETES_POLICY_VERSION\");\n const context = environment.DECIONIS_KUBERNETES_CONTEXT?.trim() || null;\n const timeoutMs = boundedInteger(environment.DECIONIS_KUBERNETES_TIMEOUT_MS, 4_000, 100, 10_000);\n const grantTtlSeconds = boundedInteger(\n environment.DECIONIS_KUBERNETES_GRANT_TTL_SECONDS,\n 60,\n 1,\n 300,\n );\n const authorityOrigin = new URL(baseUrl).origin;\n const allowedVerificationOrigins = new Set([\n authorityOrigin,\n ...(environment.DECIONIS_KUBERNETES_VERIFICATION_ORIGINS ?? \"\")\n .split(\",\")\n .map((value) => value.trim())\n .filter(Boolean)\n .map((value) => new URL(value).origin),\n ]);\n const runner = new KubectlCommandRunner(context, timeoutMs);\n const planner = new KubernetesActionPlanner(\n { organizationId, clusterId, actorId, policyVersion, grantTtlSeconds },\n runner,\n );\n const operations = new KubernetesOperations(\n planner,\n runner,\n createKubernetesAuthorityClient({ baseUrl, apiKey, timeoutMs }),\n allowedVerificationOrigins,\n );\n return new KubernetesMcpTools(operations).build();\n}\n\nfunction requiredEnvironment(environment: NodeJS.ProcessEnv, name: string): string {\n const value = environment[name]?.trim();\n if (!value) throw new Error(`${name}_REQUIRED`);\n return value;\n}\n\nfunction boundedInteger(\n input: string | undefined,\n fallback: number,\n minimum: number,\n maximum: number,\n): number {\n const value = input === undefined ? fallback : Number(input);\n if (!Number.isInteger(value) || value < minimum || value > maximum) {\n throw new Error(\"DECIONIS_KUBERNETES_NUMERIC_CONFIGURATION_INVALID\");\n }\n return value;\n}\n","export interface ShieldApi {\n authorize(request: Record<string, unknown>): Promise<Record<string, unknown>>;\n permission(): Promise<Record<string, unknown>>;\n requestApproval(decisionId: string): Promise<Record<string, unknown>>;\n decision(decisionId: string): Promise<Record<string, unknown>>;\n}\n\nexport class ShieldClient implements ShieldApi {\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly appId: string;\n private readonly fetchImpl: typeof fetch;\n\n public constructor(\n options: {\n baseUrl?: string;\n apiKey?: string;\n appId?: string;\n fetch?: typeof fetch;\n } = {},\n ) {\n this.baseUrl = (\n options.baseUrl ??\n process.env.DECIONIS_SHIELD_API_URL ??\n \"https://api.decionis.com\"\n ).replace(/\\/+$/, \"\");\n this.apiKey = options.apiKey ?? process.env.DECIONIS_SHIELD_API_KEY ?? \"\";\n this.appId = options.appId ?? process.env.DECIONIS_SHIELD_APP_ID ?? \"\";\n this.fetchImpl = options.fetch ?? fetch;\n }\n\n authorize(request: Record<string, unknown>): Promise<Record<string, unknown>> {\n return this.json(\"/v1/shield/authorize\", \"POST\", request);\n }\n\n permission(): Promise<Record<string, unknown>> {\n return this.json(\"/v1/shield/permission\", \"GET\");\n }\n\n requestApproval(decisionId: string): Promise<Record<string, unknown>> {\n return this.json(`/v1/shield/decisions/${encodeURIComponent(decisionId)}/approval`, \"POST\", {});\n }\n\n decision(decisionId: string): Promise<Record<string, unknown>> {\n return this.json(`/v1/shield/decisions/${encodeURIComponent(decisionId)}`, \"GET\");\n }\n\n private async json(\n path: string,\n method: \"GET\" | \"POST\",\n body?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n if (!this.apiKey || !this.appId) {\n throw new ShieldClientError(\n \"SHIELD_MCP_CONFIGURATION_REQUIRED\",\n \"Configure DECIONIS_SHIELD_API_KEY and DECIONIS_SHIELD_APP_ID. Do not execute the transaction.\",\n );\n }\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${this.apiKey}`,\n \"content-type\": \"application/json\",\n \"x-shield-app-id\": this.appId,\n \"x-shield-environment\": \"production\",\n },\n ...(method === \"POST\" ? { body: JSON.stringify(body ?? {}) } : {}),\n });\n const payload = await response.json().catch(() => null);\n if (!response.ok) {\n const server = asRecord(payload);\n throw new ShieldClientError(\n typeof server.error === \"string\" ? server.error : \"SHIELD_MCP_REQUEST_FAILED\",\n typeof server.message === \"string\"\n ? `${server.message} Do not execute the transaction.`\n : `Shield returned HTTP ${response.status}. Do not execute the transaction.`,\n );\n }\n return asRecord(payload);\n }\n}\n\nexport class ShieldClientError extends Error {\n public constructor(\n public readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"ShieldClientError\";\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n","import type { ToolContent, ToolDefinition } from \"./Server.js\";\nimport type { ShieldApi } from \"./ShieldClient.js\";\n\nconst text = (value: unknown): ToolContent[] => [\n { type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2) },\n];\n\nconst purchaseProperties = {\n amount: { type: \"number\", minimum: 0, description: \"Amount in major currency units.\" },\n currency: {\n type: \"string\",\n pattern: \"^[A-Za-z]{3}$\",\n description: \"ISO 4217 currency code.\",\n },\n purpose: {\n type: \"string\",\n minLength: 1,\n description: \"Clear user-facing reason for spending.\",\n },\n merchant: { type: \"string\" },\n category: { type: \"string\" },\n agentId: {\n type: \"string\",\n description: \"Registered agent identity, when an agent is spending.\",\n },\n transactionType: {\n type: \"string\",\n enum: [\"PURCHASE\", \"SUBSCRIPTION\", \"RENEWAL\", \"TRANSFER\", \"REFUND\", \"OTHER\"],\n },\n metadata: { type: \"object\" },\n};\n\nconst networkMutation = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n};\n\nconst networkRead = {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n};\n\nexport function createShieldTools(shield: ShieldApi): ToolDefinition[] {\n const authorize = async (args: Record<string, unknown>) => {\n if (\n typeof args.amount !== \"number\" ||\n typeof args.currency !== \"string\" ||\n typeof args.purpose !== \"string\"\n ) {\n return {\n content: text(\n \"amount, currency, and purpose are required. Do not execute the transaction.\",\n ),\n isError: true,\n };\n }\n return shieldResult(async () => await shield.authorize(args));\n };\n\n return [\n {\n name: \"shield.request_purchase\",\n title: \"Request Shield Purchase Authorization\",\n description:\n \"Ask the user's Shield for ALLOW, ASK, or BLOCK before a purchase. Execute only on ALLOW.\",\n inputSchema: {\n type: \"object\",\n required: [\"amount\", \"currency\", \"purpose\"],\n properties: purchaseProperties,\n additionalProperties: false,\n },\n annotations: networkMutation,\n handler: authorize,\n },\n {\n name: \"shield.check_spending_authority\",\n title: \"Check Shield Spending Authority\",\n description:\n \"Check spending authority for an app or AI agent before taking the consequential action.\",\n inputSchema: {\n type: \"object\",\n required: [\"amount\", \"currency\", \"purpose\"],\n properties: purchaseProperties,\n additionalProperties: false,\n },\n annotations: networkMutation,\n handler: authorize,\n },\n {\n name: \"shield.get_permission\",\n title: \"Get Shield Permission\",\n description:\n \"Read the spender identity and user-owned limits bound to this Shield credential.\",\n inputSchema: { type: \"object\", properties: {}, additionalProperties: false },\n annotations: networkRead,\n handler: async () => shieldResult(async () => await shield.permission()),\n },\n {\n name: \"shield.request_approval\",\n title: \"Request Shield Approval\",\n description:\n \"Start or poll Presence approval for an ASK decision. Do not execute while the verdict remains ASK.\",\n inputSchema: {\n type: \"object\",\n required: [\"decisionId\"],\n properties: { decisionId: { type: \"string\" } },\n additionalProperties: false,\n },\n annotations: networkMutation,\n handler: async (args) =>\n typeof args.decisionId === \"string\"\n ? shieldResult(async () => await shield.requestApproval(args.decisionId as string))\n : {\n content: text(\"decisionId is required. Do not execute the transaction.\"),\n isError: true,\n },\n },\n {\n name: \"shield.get_decision\",\n title: \"Get Shield Decision\",\n description:\n \"Retrieve the current ALLOW, ASK, or BLOCK decision and its evidence identifiers.\",\n inputSchema: {\n type: \"object\",\n required: [\"decisionId\"],\n properties: { decisionId: { type: \"string\" } },\n additionalProperties: false,\n },\n annotations: networkRead,\n handler: async (args) =>\n typeof args.decisionId === \"string\"\n ? shieldResult(async () => await shield.decision(args.decisionId as string))\n : {\n content: text(\"decisionId is required. Do not execute the transaction.\"),\n isError: true,\n },\n },\n ];\n}\n\nasync function shieldResult(\n work: () => Promise<Record<string, unknown>>,\n): Promise<{ content: ToolContent[]; isError?: boolean }> {\n try {\n return { content: text(await work()) };\n } catch (error) {\n return {\n content: text({\n error: error instanceof Error ? error.name : \"ShieldError\",\n message: error instanceof Error ? error.message : String(error),\n safeToExecute: false,\n }),\n isError: true,\n };\n }\n}\n","// Decionis local MCP server — stdio entrypoint.\n// Lets AI coding agents (Claude Code, Cursor, …) read DECIONIS_POLICY.md and\n// evaluate candidate actions through the real @decionis/protocol evaluator\n// before they commit, deploy, or migrate anything.\n\nimport { LocalDecionisGateway } from \"./Gateway.js\";\nimport { createMcpHandler, MCP_SERVER_VERSION, runStdioServer } from \"./Server.js\";\nimport { createDecionisTools } from \"./Tools.js\";\nimport { createKubernetesMcpToolsFromEnvironment } from \"./kubernetes/KubernetesMcpTools.js\";\nimport { ShieldClient } from \"./ShieldClient.js\";\nimport { createShieldTools } from \"./ShieldTools.js\";\n\nconst gateway = new LocalDecionisGateway();\n\n// Shield tools only exist when Shield is configured. Without the credentials\n// every call would fail closed with SHIELD_MCP_CONFIGURATION_REQUIRED anyway,\n// and advertising five network-capable tools a fresh `npx @decionis/mcp`\n// cannot use put the published tool list out of step with tools/list.\nconst shieldConfigured = Boolean(\n process.env.DECIONIS_SHIELD_API_KEY && process.env.DECIONIS_SHIELD_APP_ID,\n);\n\nconst handler = createMcpHandler({\n serverInfo: { name: \"decionis-mcp\", version: MCP_SERVER_VERSION },\n tools: createDecionisTools(gateway, [\n ...createKubernetesMcpToolsFromEnvironment(),\n ...(shieldConfigured ? createShieldTools(new ShieldClient()) : []),\n ]),\n});\n\nrunStdioServer(handler)\n .then(async () => {\n await gateway.close();\n process.exit(0);\n })\n .catch(async (err) => {\n process.stderr.write(`decionis-mcp: fatal: ${String(err)}\\n`);\n await gateway.close().catch(() => {});\n process.exit(1);\n });\n"],"mappings":";;;;;;;;;;AAOA,SAAS,uBAAuB;AAEzB,IAAM,8BAA8B,CAAC,cAAc,cAAc,cAAc,YAAY;AAC3F,IAAM,qBAAqB;AAClC,IAAM,2BAA2B;AA8BjC,IAAM,gBAAgB,CAAC,MACrB,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAEzD,SAAS,UAAU,IAAa,QAAkC;AAChE,SAAO,EAAE,SAAS,OAAO,IAAI,OAAO;AACtC;AAEA,SAAS,SAAS,IAAa,MAAc,SAAkC;AAC7E,SAAO,EAAE,SAAS,OAAO,IAAI,OAAO,EAAE,MAAM,QAAQ,EAAE;AACxD;AAMO,IAAM,oBAAN,MAAwB;AAAA,EAG7B,YAA6B,SAA8D;AAA9D;AAC3B,SAAK,cAAc,IAAI,IAAI,QAAQ,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;AAAA,EAC3E;AAAA,EAJiB;AAAA,EAMjB,MAAM,OAAO,SAAmD;AAC9D,QACE,CAAC,cAAc,OAAO,KACtB,QAAQ,YAAY,SACpB,OAAO,QAAQ,WAAW,UAC1B;AACA,YAAMA,MAAK,cAAc,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Y,EAAE,MAAM,gBAAgB,SAAS,mBAAmB;AAAA,EAChE,OAAO,oBAAoB,SAAS;AAAA,IAClC,GAAG,wCAAwC;AAAA,IAC3C,GAAI,mBAAmB,kBAAkB,IAAI,aAAa,CAAC,IAAI,CAAC;AAAA,EAClE,CAAC;AACH,CAAC;AAED,eAAe,OAAO,EACnB,KAAK,YAAY;AAChB,QAAM,QAAQ,MAAM;AACpB,UAAQ,KAAK,CAAC;AAChB,CAAC,EACA,MAAM,OAAO,QAAQ;AACpB,UAAQ,OAAO,MAAM,wBAAwB,OAAO,GAAG,CAAC;AAAA,CAAI;AAC5D,QAAM,QAAQ,MAAM,EAAE,MAAM,MAAM;AAAA,EAAC,CAAC;AACpC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["id","handler","isPlainObject","gateway","createHash","z","z","createHash","z","record","stableJsonStringify","createHash","pointer","record","stableJsonStringify","createHash","asRecord","record","text","asRecord","text"]}
|