@decionis/mcp 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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.4\";\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 * The artifact kinds whose signature check passed, derived from a verify\n * result. Kept as a derivation rather than a new field on `VerifyResult` so\n * already-installed copies of this package keep the same contract shape.\n */\nexport function verifiedArtifactKinds(result: VerifyResult): Set<string> {\n const kinds = new Set<string>();\n for (const check of result.checks) {\n const [kind, aspect] = check.key.split(\":\");\n if (aspect === \"signature\" && check.verified && kind) kinds.add(kind);\n }\n return kinds;\n}\n\n/**\n * Who minted this dossier — the half of verification that a signature alone\n * does not answer.\n *\n * A verified Ed25519 signature proves the record was not altered. It says\n * nothing about whether the workspace behind it was ever attached to a human.\n * Decionis mints anonymous provisional workspaces with no signup, so without\n * this a dossier produced by a stranger in an unclaimed workspace verifies\n * identically to one from an owned account — which turns \"here is a signed\n * Decionis dossier\" into a claim anyone can manufacture.\n *\n * The tier lives inside `portable_artifact`, which IS a signed artifact, so\n * when that artifact's signature verified, the tier is a signed fact rather\n * than an assertion the caller can edit. `signature_covered` reports exactly\n * that distinction, and it is the field a caller should branch on.\n */\nexport type IssuerTier = \"provisional_anonymous\" | \"owned\";\n\nexport interface IssuerAssessment {\n /** Null when the dossier carries no issuer context (records predating it). */\n tier: IssuerTier | null;\n /** A tier value we do not recognise, surfaced rather than swallowed. */\n unknown_tier: string | null;\n /** True only when the tier was read from an artifact whose signature verified. */\n signature_covered: boolean;\n /** True when the issuing workspace was never attached to a human owner. */\n provisional: boolean;\n label: string;\n detail: string;\n}\n\n/**\n * Read the issuer watermark from a dossier payload.\n *\n * `verified_artifact_kinds` is the set of artifact kinds whose signature checks\n * passed, from a prior `verifyDossierProofBundle` run — pass it so the result\n * can distinguish a signed tier from an unsigned one. Omit it and the tier is\n * still reported, but never as signature-covered.\n */\nexport function assessDossierIssuer(\n dossier_payload: Record<string, unknown>,\n verified_artifact_kinds: ReadonlySet<string> = new Set(),\n): IssuerAssessment {\n const payload = asRecord(dossier_payload);\n // Two shapes carry it: the proof-bundle payload nests the dossier under\n // portable_artifact.machine_readable; the public /verify projection puts it\n // at the top level. Read both so the CLI behaves the same either way.\n const machineReadable = asRecord(asRecord(payload.portable_artifact).machine_readable);\n const rawIssuer = isNonEmptyObject(payload.issuer_context)\n ? asRecord(payload.issuer_context)\n : asRecord(machineReadable.issuer_context);\n const rawTier = asString(rawIssuer.tier);\n\n const signatureCovered =\n verified_artifact_kinds.has(\"portable_artifact\") && isNonEmptyObject(rawIssuer);\n\n if (rawTier == null) {\n return {\n tier: null,\n unknown_tier: null,\n signature_covered: false,\n provisional: false,\n label: \"Issuer not stated\",\n detail:\n \"This dossier carries no issuer context, so the workspace that minted it cannot be \" +\n \"established from the record alone.\",\n };\n }\n\n if (rawTier !== \"provisional_anonymous\" && rawTier !== \"owned\") {\n return {\n tier: null,\n unknown_tier: rawTier,\n signature_covered: signatureCovered,\n provisional: false,\n label: `Unrecognised issuer tier \"${rawTier}\"`,\n detail:\n `The dossier states an issuer tier this verifier does not recognise (\"${rawTier}\"). ` +\n \"Treat the origin of this record as unestablished.\",\n };\n }\n\n const provisional = rawTier === \"provisional_anonymous\";\n return {\n tier: rawTier,\n unknown_tier: null,\n signature_covered: signatureCovered,\n provisional,\n label: provisional ? \"Provisional anonymous workspace\" : \"Owned workspace\",\n detail: provisional\n ? \"Minted by a workspace created without signup and never claimed by a human owner. \" +\n \"The signature is genuine, but nobody has taken responsibility for this record.\"\n : \"Minted by a workspace with a human owner attached.\",\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,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,UAAM,SAAS,cAAc,QAAQ,MAAM,IAAI,QAAQ,SAAS,CAAC;AAEjE,QAAI,eAAgB,QAAO;AAE3B,YAAQ,QAA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K,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"]}
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/BoundedFetch.ts","../../../packages/sdk-node/src/AgentTaskGateway.ts","../../../packages/sdk-node/src/AuthorityRequirement.ts","../../../packages/sdk-node/src/AuthZenEntitlementProvider.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","../src/kubernetes/KubernetesOperations.ts","../../../packages/dossier-verify/src/canonical.ts","../../../packages/dossier-verify/src/verify.ts","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js","../../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js","../../../packages/shared/src/Decisioning/AuthoritySemantics.ts","../../../packages/shared/src/Decisioning/ExecutionBinding.ts","../../../packages/dossier-verify/src/resolve.ts","../../../packages/dossier-verify/src/intent.ts","../src/kubernetes/KubernetesMcpTools.ts","../src/ShieldCredentialStore.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.3.0\";\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 (or against one of the protocol's policy packs)\n * through the real protocol evaluator, list those packs, 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. The five core tools are read-only, credential-free,\n * and networkless: the \"approval gate\" a cautious MCP client shows for\n * side-effectful tools has nothing to gate here.\n *\n * Two more register only when a Presence tenant key is configured\n * (DECIONIS_PRESENCE_API_KEY): decionis_request_presence_verification and\n * decionis_get_presence_verification_status. They close the loop the\n * evaluator opens — evaluate → hold (ESCALATE) → a verified person on their\n * own device → re-evaluate — by reusing the hosted MCP's own handlers against\n * the in-process store, so the local loop is the hosted loop. Both call\n * presence.decionis.com and say so in their annotations.\n *\n * Every evaluation pins the exact policy version it decided under\n * (require_exact_policy_version). A version the evaluator does not hold is a\n * loud fail-closed result, never a silent substitute.\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**Closing the loop with Presence** (when DECIONIS_PRESENCE_API_KEY is set): an\n\\`escalate\\` in enforce mode returns an evaluation_id. After\n\\`decionis_request_presence_verification\\` and a clean approval,\n\\`decionis_get_presence_verification_status\\` re-evaluates the SAME action with\n\\`context.presence.verified\\` and \\`context.presence.receipt_valid\\` set to true by\nDecionis (never by the caller — an untrusted claim is forced to false). Only a rule\nthat names those facts turns the held action into an allow:\n\\`\\`\\`decionis\n{ \"name\": \"Allow once a verified person approved it through Presence\",\n \"priority\": 100, \"domain\": \"*\",\n \"all\": [{ \"field\": \"context.presence.verified\", \"op\": \"eq\", \"value\": true },\n { \"field\": \"context.presence.receipt_valid\", \"op\": \"eq\", \"value\": true }],\n \"action\": \"allow\" }\n\\`\\`\\`\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 private readonly presenceConfigured: boolean = false,\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 — or, with policy_pack, \" +\n \"against one of the Decionis policy packs (decionis_list_policy_packs) — through the real \" +\n \"Decionis protocol evaluator, entirely locally (no network, no credentials, nothing recorded). \" +\n \"The exact policy version is pinned on every call; an unavailable version fails closed rather \" +\n \"than silently deciding under another bundle. Call this BEFORE committing, deploying, \" +\n \"migrating, or any risky action, and abide by the verdict: allow → proceed; block → do not \" +\n \"proceed; review/escalate → stop and involve a human (an ESCALATE in enforce mode returns an \" +\n \"evaluation_id that decionis_request_presence_verification can resolve when Presence is configured).\",\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 policy_pack: {\n type: \"string\",\n description:\n \"Evaluate under a named Decionis policy pack (a key from decionis_list_policy_packs, \" +\n \"e.g. finance, devops, sap) instead of the repository policy file. The pack's bundle is \" +\n \"seeded into the local evaluator once and its exact version is pinned.\",\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 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 workflowKey = typeof args.workflow_key === \"string\" ? args.workflow_key : null;\n const packKey =\n typeof args.policy_pack === \"string\" && args.policy_pack.trim() !== \"\"\n ? args.policy_pack.trim()\n : null;\n\n let published: { version: string; sha256: string | null; ruleCount: number };\n if (packKey) {\n const seeded = await gateway.seedPolicyPack(packKey);\n if (!seeded.ok) {\n return {\n content: text({\n error: seeded.reason,\n details: seeded.errors,\n hint: \"Call decionis_list_policy_packs for the keys the evaluator ships.\",\n }),\n isError: true,\n };\n }\n published = { version: seeded.version, sha256: null, ruleCount: seeded.ruleCount };\n } else {\n const file = await this.policyFiles.read(args.path);\n if (!file.ok) return { content: text(file.message), isError: true };\n const filePublished = await gateway.publishPolicy(file.content, { workflowKey });\n if (!filePublished.ok) {\n return {\n content: text({\n error: filePublished.reason,\n details: filePublished.errors,\n hint:\n filePublished.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 published = filePublished;\n }\n\n const evaluated = await gateway.evaluate({\n payload: args.payload,\n workflowKey,\n mode: args.mode === \"enforce\" ? \"enforce\" : \"shadow\",\n policyVersion: published.version,\n verticalPack: packKey,\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 ...(packKey ? { policy_pack: packKey } : {}),\n // Loud by construction: the version the evaluator actually\n // decided under, beside the one this tool asked for.\n policy_bundle_resolution: body.policy_bundle_resolution ?? null,\n mode: body.mode ?? null,\n evaluation_id: body.evaluation_id ?? null,\n dossier_id: body.dossier_id ?? null,\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_list_policy_packs\",\n title: \"List Decionis Policy Packs\",\n description:\n \"List the policy packs the Decionis evaluator ships — finance, devops, sap, salesforce, \" +\n \"workday, hospitality and the workflow overlays — with each pack's key, description, \" +\n \"default decision domain and exact bundle version. Pass a key as policy_pack to \" +\n \"decionis_evaluate to decide under that pack instead of the repository policy file. \" +\n \"Entirely local: the catalogue is read from the in-process protocol, nothing is fetched.\",\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 packs = await gateway.listPolicyPacks();\n return {\n content: text({\n count: packs.length,\n packs,\n how_to_use:\n 'decionis_evaluate with {\"policy_pack\": \"<key>\", \"payload\": {...}}. The pack\\'s bundle is ' +\n \"seeded into the local evaluator once, and every evaluation pins its exact version.\",\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.presenceConfigured ? buildPresenceTools(gateway) : []),\n ...this.additionalTools,\n ];\n }\n}\n\n/**\n * The Presence tools, registered only when a tenant key is configured. They\n * delegate to the hosted MCP's own handlers bound to the in-process app and\n * store (see LocalDecionisGateway.callHostedTool), so a held ESCALATE from\n * decionis_evaluate in enforce mode is resolved exactly the way the hosted\n * service resolves one: Presence seals a signed Presence Record, Decionis\n * verifies it and re-evaluates, and only the new verdict can return PROCEED.\n * A BLOCK cannot be bypassed and a Shadow Mode evaluation is refused.\n */\nfunction buildPresenceTools(gateway: LocalDecionisGateway): ToolDefinition[] {\n return [\n {\n name: \"decionis_request_presence_verification\",\n title: \"Ask a Person to Approve It Through Presence\",\n description:\n \"Request action-bound human verification through Decionis Presence for a held ESCALATE from \" +\n \"decionis_evaluate (enforce mode). Returns HUMAN_REQUIRED with an approval link for the named \" +\n \"approver; the action stays held and nothing downstream executes. Cannot bypass a BLOCK and \" +\n \"refuses Shadow Mode evaluations. Calls presence.decionis.com with the configured tenant key.\",\n inputSchema: {\n type: \"object\",\n required: [\"evaluation_id\", \"approver_id\"],\n properties: {\n evaluation_id: {\n type: \"string\",\n description: \"The evaluation_id of a held ESCALATE returned by decionis_evaluate.\",\n },\n approver_id: {\n type: \"string\",\n description: \"Email or stable subject ID of the person who must approve.\",\n },\n ttl_seconds: {\n type: \"number\",\n minimum: 30,\n maximum: 600,\n description: \"Approval-link lifetime; defaults to 300 seconds.\",\n },\n request_attempt: {\n type: \"integer\",\n minimum: 1,\n description:\n \"Increment to deliberately re-request after an earlier request for the same evaluation \" +\n \"and approver was cancelled but has not expired (otherwise Presence answers 409).\",\n },\n },\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n handler: async (args) => {\n const evaluationId = typeof args.evaluation_id === \"string\" ? args.evaluation_id : \"\";\n const approverId = typeof args.approver_id === \"string\" ? args.approver_id : \"\";\n if (!evaluationId || !approverId) {\n return {\n content: text({\n error: \"APPROVER_ID_REQUIRED\",\n message: \"evaluation_id and approver_id are both required.\",\n }),\n isError: true,\n };\n }\n return gateway.callHostedTool(\"decionis.request_presence_verification\", {\n evaluation_id: evaluationId,\n approver_id: approverId,\n ...(typeof args.ttl_seconds === \"number\" ? { ttl_seconds: args.ttl_seconds } : {}),\n ...(typeof args.request_attempt === \"number\"\n ? { request_attempt: args.request_attempt }\n : {}),\n });\n },\n },\n {\n name: \"decionis_get_presence_verification_status\",\n title: \"Check the Presence Approval\",\n description:\n \"Check an action-bound Presence approval. A clean signed Presence Record is verified and \" +\n \"Decionis re-evaluates the held action; only the new Decionis verdict can return PROCEED. \" +\n \"Pending, denied, invalid or unavailable evidence stays fail-closed. Calls presence.decionis.com.\",\n inputSchema: {\n type: \"object\",\n required: [\"evaluation_id\", \"request_id\"],\n properties: {\n evaluation_id: { type: \"string\", description: \"The held evaluation_id.\" },\n request_id: {\n type: \"string\",\n description:\n \"The Presence request_id returned by decionis_request_presence_verification.\",\n },\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 const evaluationId = typeof args.evaluation_id === \"string\" ? args.evaluation_id : \"\";\n const requestId = typeof args.request_id === \"string\" ? args.request_id : \"\";\n if (!evaluationId || !requestId) {\n return {\n content: text({\n error: \"REQUEST_ID_REQUIRED\",\n message: \"evaluation_id and request_id are both required.\",\n }),\n isError: true,\n };\n }\n return gateway.callHostedTool(\"decionis.get_presence_verification_status\", {\n evaluation_id: evaluationId,\n request_id: requestId,\n });\n },\n },\n ];\n}\n\n/** Functional alias for {@link DecionisTools.build}. */\nexport function createDecionisTools(\n gateway: LocalDecionisGateway,\n additionalTools: ToolDefinition[] = [],\n options: { presenceConfigured?: boolean } = {},\n): ToolDefinition[] {\n return new DecionisTools(\n gateway,\n new PolicyFileRepository(),\n additionalTools,\n options.presenceConfigured === true,\n ).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\nconst DEFAULT_MAX_RESPONSE_BYTES = 100 * 1024;\n\nexport interface BoundedFetchResult {\n response: Response;\n text: string;\n}\n\nexport class DecionisFetchDeadlineError extends Error {\n public constructor() {\n super(\"DECIONIS_HTTP_DEADLINE_EXCEEDED\");\n this.name = \"DecionisFetchDeadlineError\";\n }\n}\n\nexport class DecionisResponseTooLargeError extends Error {\n public constructor() {\n super(\"DECIONIS_HTTP_RESPONSE_TOO_LARGE\");\n this.name = \"DecionisResponseTooLargeError\";\n }\n}\n\nfunction boundedTimeout(timeoutMs: number): number {\n return Math.min(Math.max(Number.isFinite(timeoutMs) ? timeoutMs : 4_000, 1), 15_000);\n}\n\nasync function readBoundedText(response: Response, maxBytes: number): Promise<string> {\n const responseLike = response as Response & {\n headers?: { get?: (name: string) => string | null };\n text?: () => Promise<string>;\n json?: () => Promise<unknown>;\n };\n const declaredLength = Number.parseInt(responseLike.headers?.get?.(\"content-length\") ?? \"\", 10);\n if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n throw new DecionisResponseTooLargeError();\n }\n\n if (!response.body || typeof response.body.getReader !== \"function\") {\n const text =\n typeof responseLike.text === \"function\"\n ? await responseLike.text()\n : typeof responseLike.json === \"function\"\n ? JSON.stringify(await responseLike.json())\n : \"\";\n if (Buffer.byteLength(text, \"utf8\") > maxBytes) throw new DecionisResponseTooLargeError();\n return text;\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let bytes = 0;\n try {\n while (true) {\n const result = await reader.read();\n if (result.done) break;\n bytes += result.value.byteLength;\n if (bytes > maxBytes) {\n void reader.cancel().catch(() => undefined);\n throw new DecionisResponseTooLargeError();\n }\n chunks.push(result.value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString(\"utf8\");\n}\n\n/**\n * Bound both transport and body consumption with a hard Promise race. Abort is\n * still sent to cooperative implementations, but correctness never depends on\n * an injected fetch or body stream honoring it.\n */\nexport async function fetchBounded(\n fetchImpl: FetchLike,\n input: string | URL | Request,\n init: RequestInit,\n timeoutMs: number,\n maxResponseBytes = DEFAULT_MAX_RESPONSE_BYTES,\n): Promise<BoundedFetchResult> {\n const controller = new AbortController();\n const externalSignal = init.signal;\n const relayAbort = () => controller.abort(externalSignal?.reason);\n if (externalSignal?.aborted) relayAbort();\n else externalSignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new DecionisFetchDeadlineError());\n }, boundedTimeout(timeoutMs));\n });\n const operation = (async () => {\n const response = await fetchImpl(input, { ...init, signal: controller.signal });\n const text = await readBoundedText(response, maxResponseBytes);\n return { response, text };\n })();\n\n try {\n return await Promise.race([operation, deadline]);\n } finally {\n if (timer) clearTimeout(timer);\n externalSignal?.removeEventListener(\"abort\", relayAbort);\n }\n}\n\nexport async function fetchBoundedJson(\n fetchImpl: FetchLike,\n input: string | URL | Request,\n init: RequestInit,\n timeoutMs: number,\n maxResponseBytes = DEFAULT_MAX_RESPONSE_BYTES,\n): Promise<{ response: Response; body: unknown }> {\n const { response, text } = await fetchBounded(\n fetchImpl,\n input,\n init,\n timeoutMs,\n maxResponseBytes,\n );\n if (!text) return { response, body: null };\n try {\n return { response, body: JSON.parse(text) as unknown };\n } catch {\n return { response, body: null };\n }\n}\n","import { fetchBoundedJson } from \"./BoundedFetch\";\n\ntype 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 { response, body } = await fetchBoundedJson(\n this.fetchImpl,\n `${this.baseUrl}${path}`,\n {\n ...init,\n headers: {\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"x-decionis-api-key\": this.options.apiKey,\n },\n },\n this.options.timeoutMs ?? 4_000,\n );\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 }\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 /** Optional exact-human narrowing; role authority is still independently required. */\n principal_id: z.string().min(1).max(200).optional(),\n })\n .strict(),\n z\n .object({\n kind: z.literal(\"PRINCIPAL\"),\n principal_id: z.string().min(1).max(200),\n /** Trusted effective human authority role; mandatory for managed orchestration. */\n role_id: z\n .string()\n .regex(/^[A-Z][A-Z0-9_]{1,63}$/)\n .optional(),\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\n/** One tier of an approval chain: the principals who may answer for it. */\nexport const authorityApprovalTierSchema = z\n .object({\n priority: z.number().int().min(1).max(5),\n principal_ids: z.array(z.string().min(1).max(200)).min(1).max(10),\n })\n .strict();\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 /** An approval chain: one valid proof from every tier satisfies the requirement. */\n tiers: z.array(authorityApprovalTierSchema).min(1).max(5).optional(),\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 if (policy.tiers) {\n const priorities = policy.tiers.map((tier) => tier.priority);\n if (priorities.some((priority, index) => index > 0 && priority <= priorities[index - 1]!)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"tiers\"],\n message: \"tier priorities must be unique and ascending\",\n });\n }\n const principals = policy.tiers.flatMap((tier) => tier.principal_ids);\n if (new Set(principals).size !== principals.length) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"tiers\"],\n message: \"a principal belongs to one tier only\",\n });\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 /** Decionis-owned marker; absent requirements retain the DIRECT flow. */\n orchestration: z\n .object({\n mode: z.literal(\"MANAGED\"),\n escalation_id: z.string().uuid(),\n })\n .strict()\n .optional(),\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 if (requirement.resolution.tiers && requirement.selector.kind !== \"ROLE\") {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"resolution\", \"tiers\"],\n message: \"an approval chain names its members' trusted role through a ROLE selector\",\n });\n }\n if (\n requirement.orchestration?.mode === \"MANAGED\" &&\n requirement.selector.kind === \"PRINCIPAL\" &&\n requirement.selector.role_id === undefined\n ) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"selector\", \"role_id\"],\n message: \"managed principal authority must include its trusted human role\",\n });\n }\n });\n\nexport type DecionisAuthorityRequirement = z.infer<typeof decionisAuthorityRequirementSchema>;\n","/**\n * AuthZEN entitlement provider — an enterprise policy decision point as an\n * input to Decionis, never as its core.\n *\n * Mature enterprises already have a PDP (Okta, Microsoft Entra, SGNL, an OPA\n * fleet) that answers the OpenID AuthZEN Authorization API question: is this\n * subject permitted to perform this action on this resource? Decionis does\n * not re-ask it. This provider calls the PDP BEFORE the authority request,\n * digests the exact request and response, and packs the answer into a\n * typed `upstream_authorization` semantic signal that travels in the\n * evaluate-decision context. The Protocol then treats it like any other\n * material signal: admission rules name which PDPs count, policy reads\n * `signals.upstream_authorization.decision`, a missing or untrusted answer\n * fails safe, and a changed answer invalidates the execution binding at\n * claim time. Decionis still decides whether this exact execution has\n * authority now; the PDP's answer is one fact it decides with.\n *\n * Okta / Entra / SGNL / AuthZEN PDP\n * │ access decision\n * ▼\n * Decionis ← material authority input\n * │ deterministic execution authority\n * ▼\n * ExecutionBinding\n *\n * Boundaries. The call is made from the caller's process, never from inside\n * evaluation. Only an allow-listed origin is ever called. The response is\n * parsed strictly against the AuthZEN 1.0 shape; anything else yields no\n * signal, and no signal means the policy's fail-safe applies. Decionis is\n * not a member of the OpenID Foundation.\n *\n * Reference: OpenID AuthZEN Authorization API 1.0 (final, 2026-01-11).\n * Evaluation endpoint: `POST {pdp}/access/v1/evaluation`; discovery:\n * `GET {pdp}/.well-known/authzen-configuration`.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\nimport {\n decionisSemanticSignalEnvelopeSchema,\n type DecionisSemanticSignalEnvelope,\n} from \"./Contracts.js\";\n\nexport const AUTHZEN_PROTOCOL = \"authzen/1.0\" as const;\nexport const AUTHZEN_EVALUATION_PATH = \"/access/v1/evaluation\" as const;\nexport const AUTHZEN_DISCOVERY_PATH = \"/.well-known/authzen-configuration\" as const;\nexport const UPSTREAM_AUTHORIZATION_SIGNAL_NAME = \"upstream_authorization\" as const;\n\nconst bounded = z.string().trim().min(1).max(200);\n\nexport const authZenSubjectSchema = z\n .object({ type: bounded, id: bounded, properties: z.record(z.unknown()).optional() })\n .strict();\nexport const authZenResourceSchema = z\n .object({ type: bounded, id: bounded, properties: z.record(z.unknown()).optional() })\n .strict();\nexport const authZenActionSchema = z\n .object({ name: bounded, properties: z.record(z.unknown()).optional() })\n .strict();\n\nexport const authZenEvaluationRequestSchema = z\n .object({\n subject: authZenSubjectSchema,\n resource: authZenResourceSchema,\n action: authZenActionSchema,\n context: z.record(z.unknown()).optional(),\n })\n .strict();\n\nexport const authZenEvaluationResponseSchema = z\n .object({ decision: z.boolean(), context: z.record(z.unknown()).optional() })\n .strict();\n\nexport type AuthZenEvaluationRequest = z.infer<typeof authZenEvaluationRequestSchema>;\nexport type AuthZenEvaluationResponse = z.infer<typeof authZenEvaluationResponseSchema>;\n\nexport interface AuthZenEntitlementProviderConfig {\n /** The PDP's origin, e.g. \"https://pdp.example.com\". The evaluation path is appended. */\n pdpUrl: string;\n /**\n * Origins the provider may call. Defaults to the origin of `pdpUrl`; a\n * discovery document can only redirect evaluation within this list.\n */\n allowedOrigins?: string[];\n /** How the PDP is named inside the signal — defaults to the origin. Must match the policy's `allowed_producers`. */\n pdpId?: string;\n /** Bearer token or other headers the PDP requires. */\n headers?: Record<string, string>;\n fetchImpl?: typeof fetch;\n clock?: () => Date;\n timeoutMs?: number;\n}\n\nexport type AuthZenEntitlementResult =\n | {\n ok: true;\n decision: boolean;\n signal: DecionisSemanticSignalEnvelope;\n request: AuthZenEvaluationRequest;\n response: AuthZenEvaluationResponse;\n }\n | {\n ok: false;\n reason:\n | \"origin_not_allowed\"\n | \"pdp_unreachable\"\n | \"pdp_http_error\"\n | \"pdp_response_invalid\"\n | \"pdp_timeout\";\n status?: number;\n detail?: string;\n };\n\n/**\n * Canonical JSON digest, RFC 8785 (JCS) for JSON values: recursively sorted\n * object keys, JSON.stringify serialization of primitives (which is the\n * ECMAScript number and string formatting JCS specifies). The Protocol\n * recomputes `value_digest` with its own JCS implementation and compares —\n * parity is pinned by test against `@decionis/shared`'s digest.\n */\nexport function authZenCanonicalDigest(value: unknown): `sha256:${string}` {\n const canonical = JSON.stringify(sortKeysDeep(value));\n return `sha256:${createHash(\"sha256\").update(canonical, \"utf8\").digest(\"hex\")}`;\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") {\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw new Error(\"DECIONIS_AUTHZEN_NUMBER_INVALID\");\n }\n return value;\n }\n if (Array.isArray(value)) return value.map(sortKeysDeep);\n const record = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(record).sort()) {\n if (record[key] === undefined) continue;\n out[key] = sortKeysDeep(record[key]);\n }\n return out;\n}\n\n/** Reason or obligation identifiers a PDP may return in `context` — kept as strings, bounded. */\nfunction extractReasons(context: Record<string, unknown> | undefined): string[] {\n if (!context) return [];\n const candidates: unknown[] = [];\n for (const key of [\"reason\", \"reasons\", \"reason_admin\", \"reason_user\", \"obligations\"]) {\n const value = context[key];\n if (Array.isArray(value)) candidates.push(...value);\n else if (value !== undefined) candidates.push(value);\n }\n return candidates\n .map((entry) =>\n typeof entry === \"string\"\n ? entry\n : entry && typeof entry === \"object\"\n ? JSON.stringify(sortKeysDeep(entry))\n : String(entry),\n )\n .map((entry) => entry.slice(0, 200))\n .filter((entry) => entry.length > 0)\n .slice(0, 50);\n}\n\n/**\n * Build the `upstream_authorization` semantic signal for one PDP answer —\n * the same envelope `@decionis/shared`'s `buildUpstreamAuthorizationSignal`\n * produces, so a policy written against one reads the other.\n */\nexport function buildUpstreamAuthorizationSignal(input: {\n pdp: string;\n request: AuthZenEvaluationRequest;\n response: AuthZenEvaluationResponse;\n evaluated_at: string;\n signal_id?: string;\n reasons?: string[];\n}): DecionisSemanticSignalEnvelope {\n const request = authZenEvaluationRequestSchema.parse(input.request);\n const response = authZenEvaluationResponseSchema.parse(input.response);\n const requestDigest = authZenCanonicalDigest(request);\n const responseDigest = authZenCanonicalDigest(response);\n const value = {\n protocol: AUTHZEN_PROTOCOL,\n pdp: input.pdp,\n decision: response.decision,\n subject: { type: request.subject.type, id: request.subject.id },\n resource: { type: request.resource.type, id: request.resource.id },\n action: { name: request.action.name },\n evaluated_at: input.evaluated_at,\n request_digest: requestDigest,\n response_digest: responseDigest,\n ...(input.reasons && input.reasons.length > 0 ? { reasons: input.reasons } : {}),\n };\n return decionisSemanticSignalEnvelopeSchema.parse({\n schema_version: \"1.0\",\n signal_id: input.signal_id ?? `authzen:${input.pdp}:${requestDigest.slice(7, 23)}`,\n kind: UPSTREAM_AUTHORIZATION_SIGNAL_NAME,\n value,\n producer: { provider: input.pdp, detector_version: AUTHZEN_PROTOCOL },\n observed_at: input.evaluated_at,\n confidence_basis_points: 10_000,\n evidence_digest: responseDigest,\n value_digest: authZenCanonicalDigest(value),\n material: true,\n });\n}\n\n/** Merge a PDP answer into an authority request context under the conventional signal name. */\nexport function withUpstreamAuthorization(\n context: Record<string, unknown> | undefined,\n signal: DecionisSemanticSignalEnvelope,\n name: string = UPSTREAM_AUTHORIZATION_SIGNAL_NAME,\n): Record<string, unknown> {\n const base = context ?? {};\n const signals =\n base.signals && typeof base.signals === \"object\" && !Array.isArray(base.signals)\n ? (base.signals as Record<string, unknown>)\n : {};\n return { ...base, signals: { ...signals, [name]: signal } };\n}\n\nexport class AuthZenEntitlementProvider {\n private readonly origin: string;\n private readonly allowedOrigins: Set<string>;\n private readonly pdpId: string;\n private readonly doFetch: typeof fetch;\n private readonly clock: () => Date;\n private readonly headers: Record<string, string>;\n private readonly timeoutMs: number;\n private evaluationUrl: string;\n\n constructor(config: AuthZenEntitlementProviderConfig) {\n const url = new URL(config.pdpUrl);\n if (url.protocol !== \"https:\" && url.hostname !== \"localhost\" && url.hostname !== \"127.0.0.1\") {\n throw new Error(\"DECIONIS_AUTHZEN_PDP_URL_MUST_BE_HTTPS\");\n }\n this.origin = url.origin;\n this.allowedOrigins = new Set([this.origin, ...(config.allowedOrigins ?? [])]);\n this.pdpId = config.pdpId ?? this.origin;\n this.doFetch = config.fetchImpl ?? fetch;\n this.clock = config.clock ?? (() => new Date());\n this.headers = { ...(config.headers ?? {}) };\n this.timeoutMs = Math.min(Math.max(config.timeoutMs ?? 5_000, 100), 30_000);\n this.evaluationUrl = `${this.origin}${AUTHZEN_EVALUATION_PATH}`;\n }\n\n /** The PDP identity that must appear in the policy's `allowed_producers`. */\n get producer(): string {\n return this.pdpId;\n }\n\n /**\n * Optional: read the PDP's discovery document and adopt its evaluation\n * endpoint — but only when it stays within the allow-list. A document that\n * points elsewhere is ignored, not followed.\n */\n async discover(): Promise<{ ok: boolean; evaluationUrl: string }> {\n const response = await this.request(`${this.origin}${AUTHZEN_DISCOVERY_PATH}`, {\n method: \"GET\",\n });\n if (!response.ok) return { ok: false, evaluationUrl: this.evaluationUrl };\n const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n const endpoint =\n body && typeof body.access_evaluation_endpoint === \"string\"\n ? body.access_evaluation_endpoint\n : null;\n if (!endpoint) return { ok: false, evaluationUrl: this.evaluationUrl };\n let candidate: URL;\n try {\n candidate = new URL(endpoint);\n } catch {\n return { ok: false, evaluationUrl: this.evaluationUrl };\n }\n if (!this.allowedOrigins.has(candidate.origin)) {\n return { ok: false, evaluationUrl: this.evaluationUrl };\n }\n this.evaluationUrl = candidate.toString();\n return { ok: true, evaluationUrl: this.evaluationUrl };\n }\n\n /**\n * Ask the PDP, and return the answer as a material signal. A failed call\n * returns `ok: false` and NO signal: attach nothing, and let the policy's\n * `required_signals` fail-safe decide. Never fabricate a deny.\n */\n async evaluate(input: AuthZenEvaluationRequest): Promise<AuthZenEntitlementResult> {\n const request = authZenEvaluationRequestSchema.parse(input);\n const target = new URL(this.evaluationUrl);\n if (!this.allowedOrigins.has(target.origin)) {\n return { ok: false, reason: \"origin_not_allowed\", detail: target.origin };\n }\n let response: Response;\n try {\n response = await this.request(this.evaluationUrl, {\n method: \"POST\",\n body: JSON.stringify(request),\n });\n } catch (error) {\n const reason =\n (error as { name?: string })?.name === \"AbortError\" ? \"pdp_timeout\" : \"pdp_unreachable\";\n return { ok: false, reason, detail: error instanceof Error ? error.message : String(error) };\n }\n if (!response.ok) {\n return { ok: false, reason: \"pdp_http_error\", status: response.status };\n }\n const raw = await response.json().catch(() => undefined);\n const parsed = authZenEvaluationResponseSchema.safeParse(raw);\n if (!parsed.success) {\n return { ok: false, reason: \"pdp_response_invalid\", status: response.status };\n }\n const evaluatedAt = this.clock().toISOString();\n const signal = buildUpstreamAuthorizationSignal({\n pdp: this.pdpId,\n request,\n response: parsed.data,\n evaluated_at: evaluatedAt,\n reasons: extractReasons(parsed.data.context),\n });\n return { ok: true, decision: parsed.data.decision, signal, request, response: parsed.data };\n }\n\n /**\n * Convenience: ask the PDP and return the context to send to Decionis. On a\n * failed call the context is returned unchanged — no signal, so the policy's\n * fail-safe applies — together with the result for the caller to log.\n */\n async enrichContext(\n input: AuthZenEvaluationRequest,\n context?: Record<string, unknown>,\n name: string = UPSTREAM_AUTHORIZATION_SIGNAL_NAME,\n ): Promise<{ context: Record<string, unknown>; result: AuthZenEntitlementResult }> {\n const result = await this.evaluate(input);\n return {\n context: result.ok\n ? withUpstreamAuthorization(context, result.signal, name)\n : { ...(context ?? {}) },\n result,\n };\n }\n\n private async request(\n url: string,\n init: { method: \"GET\" | \"POST\"; body?: string },\n ): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n return await this.doFetch(url, {\n method: init.method,\n headers: {\n accept: \"application/json\",\n ...(init.body ? { \"content-type\": \"application/json\" } : {}),\n ...this.headers,\n },\n ...(init.body ? { body: init.body } : {}),\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\n/** Functional alias for {@link AuthZenEntitlementProvider}. */\nexport function createAuthZenEntitlementProvider(config: AuthZenEntitlementProviderConfig) {\n return new AuthZenEntitlementProvider(config);\n}\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 decionisSemanticSignalKindSchema = z.union([\n z.enum([\n \"intent_risk\",\n \"scope_drift\",\n \"data_sensitivity\",\n \"suspected_exfiltration\",\n \"upstream_authorization\",\n ]),\n z.string().regex(/^[a-z0-9][a-z0-9.-]{0,62}:[a-z0-9][a-z0-9._-]{0,119}$/),\n]);\n\n/** Evidence-bearing classifier output; deterministic policy remains authoritative. */\nexport const decionisSemanticSignalEnvelopeSchema = z\n .object({\n schema_version: z.literal(\"1.0\"),\n signal_id: z.string().min(1).max(200),\n kind: decionisSemanticSignalKindSchema,\n value: z.unknown().refine((value) => value !== undefined, \"value is required\"),\n producer: z\n .object({\n provider: z.string().min(1).max(200),\n detector_version: z.string().min(1).max(200),\n })\n .strict(),\n observed_at: z.string().datetime(),\n confidence_basis_points: z.number().int().min(0).max(10_000),\n evidence_digest: z\n .string()\n .regex(/^sha256:[0-9a-f]{64}$/)\n .nullable(),\n value_digest: z.string().regex(/^sha256:[0-9a-f]{64}$/),\n material: z.boolean(),\n })\n .strict();\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 // The published SDK carries no workspace dependency, so this list is a\n // deliberate copy. `PolicyResolutionParity.test.ts` in @decionis/shared\n // fails if it falls behind the canonical one.\n resolution: z.enum([\n \"policy_guard_blocked\",\n \"matched_rule\",\n \"no_matching_rule\",\n \"missing_required_signals\",\n \"signal_admission_rejected\",\n \"shadowed_request_facts\",\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 shadowed_request_facts: z.array(z.string()).optional(),\n signal_admission_findings: z\n .array(\n z.object({\n signal_path: z.string(),\n signal_id: z.string().nullable(),\n admitted: z.boolean(),\n reasons: z.array(z.string()),\n }),\n )\n .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 DecionisSemanticSignalEnvelope = z.infer<typeof decionisSemanticSignalEnvelopeSchema>;\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\";\nimport { fetchBoundedJson } from \"./BoundedFetch\";\n\ntype FetchLike = typeof fetch;\n\n/** The one authoritative served decision route. Product adapters must not mirror it. */\nexport const DECIONIS_DECISION_RUNTIME_ROUTE = \"/v1/protocol/evaluate-decision\" as const;\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\n/**\n * Configuration for the canonical served decision runtime. Unlike the legacy\n * client options, the route cannot be overridden by a product adapter.\n */\nexport type DecionisDecisionRuntimeClientOptions = Omit<DecionisNodeSdkOptions, \"route\">;\n\n/** Transport contract exposed by the canonical Decionis decision runtime. */\nexport type DecionisDecisionRuntimeClient = DecionisDecisionExecutor;\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 ?? DECIONIS_DECISION_RUNTIME_ROUTE;\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 timeoutMs = this.options.timeoutMs ?? 4000;\n const idempotencyKey = invokeOptions?.idempotencyKey ?? payload.idempotency_key ?? null;\n\n const { response, body } = await fetchBoundedJson(\n this.fetchImpl,\n `${this.baseUrl}${this.route}`,\n {\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 },\n timeoutMs,\n );\n\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 };\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\n/**\n * Create a client for the canonical Decionis decision runtime.\n *\n * Product repositories own signal normalization and platform I/O. They send the\n * normalized intent here and consume the signed runtime verdict; they do not\n * carry a local copy of the protocol evaluator.\n */\nexport function createDecionisDecisionRuntimeClient(\n options: DecionisDecisionRuntimeClientOptions,\n): DecionisDecisionRuntimeClient {\n return new DecionisNodeSdk({ ...options, route: DECIONIS_DECISION_RUNTIME_ROUTE });\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\";\nimport { fetchBoundedJson } from \"./BoundedFetch\";\n\ntype FetchLike = typeof fetch;\n\nconst managedEscalationStatusSchema = z.enum([\n \"PENDING_PRESENCE\",\n \"PRESENCE_REQUESTED\",\n \"AWAITING_APPROVER\",\n \"PRESENCE_VERIFIED\",\n \"REAUTHORIZING\",\n \"GRANT_READY\",\n \"EXPIRED\",\n \"REJECTED\",\n \"BLOCKED\",\n \"CANCELLED\",\n \"FAILED\",\n]);\n\nconst managedEscalationOutcomeSchema = z.enum([\"ESCALATE_PENDING\", \"ALLOW\", \"BLOCK\", \"ERROR\"]);\n\nfunction expectedManagedEscalationOutcome(\n status: z.infer<typeof managedEscalationStatusSchema>,\n): z.infer<typeof managedEscalationOutcomeSchema> {\n if (status === \"GRANT_READY\") return \"ALLOW\";\n if (status === \"FAILED\") return \"ERROR\";\n if ([\"EXPIRED\", \"REJECTED\", \"BLOCKED\", \"CANCELLED\"].includes(status)) return \"BLOCK\";\n return \"ESCALATE_PENDING\";\n}\n\n/** Which tier of the policy's approval chain one managed ceremony proves. */\nconst managedApprovalTierSchema = z\n .object({\n tier: z.number().int().min(1).max(5),\n tier_count: z.number().int().min(1).max(5),\n principal_id: z.string().min(1).max(200),\n })\n .strict();\n\n/** When Presence runs the whole chain: which chain, and how many tiers have approved. */\nconst managedApprovalChainSchema = z\n .object({\n chain_id: z.string().max(200),\n tier_count: z.number().int().min(1).max(5),\n tiers_approved: z.number().int().min(0).max(5),\n })\n .strict();\n\nconst managedEscalationReferenceSchema = z\n .object({\n outcome: managedEscalationOutcomeSchema,\n escalation_id: z.string().min(8).max(200),\n intent_id: z.string().min(1).max(200),\n status: managedEscalationStatusSchema,\n expires_at: z.string().datetime(),\n reason_codes: z.array(z.string().min(1).max(200)).max(50),\n approval_tier: managedApprovalTierSchema.nullable().optional().default(null),\n approval_chain: managedApprovalChainSchema.nullable().optional().default(null),\n })\n .strict()\n .superRefine((reference, context) => {\n if (reference.outcome !== expectedManagedEscalationOutcome(reference.status)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"outcome\"],\n message: \"managed escalation outcome does not match its lifecycle status\",\n });\n }\n });\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 authority_classification: z\n .enum([\"AUTHORITATIVE\", \"OBSERVATIONAL\"])\n .nullable()\n .optional()\n .default(null),\n execution_eligible: z.boolean().optional().default(false),\n execution_binding_digest: z\n .string()\n .regex(/^sha256:[0-9a-f]{64}$/)\n .nullable()\n .optional()\n .default(null),\n execution_token: z.string().min(1).nullable(),\n execution_token_jti: z.string().uuid().nullable().optional().default(null),\n execution_token_key_id: z.string().min(1).nullable().optional().default(null),\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 managed_escalation: managedEscalationReferenceSchema.nullable().optional().default(null),\n })\n .passthrough()\n .superRefine((decision, context) => {\n const escalation = decision.managed_escalation;\n if (escalation === null) return;\n // The enforce-and-bind response is always a locator-only summary in\n // managed mode, including an idempotent retry that is already terminal.\n // A normal grant is retrievable only through the authenticated status API.\n if (\n decision.should_execute ||\n decision.execution_eligible ||\n decision.execution_binding_digest !== null ||\n decision.execution_token !== null ||\n decision.execution_token_jti !== null ||\n decision.execution_token_key_id !== null ||\n decision.execution_token_expires_at !== null\n ) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"managed_escalation\", \"status\"],\n message: \"managed enforce-and-bind summaries cannot carry execution authority\",\n });\n }\n });\n\nconst managedEscalationViewSchema = z\n .object({\n escalation_id: z.string().min(8).max(200),\n intent_id: z.string().min(1).max(200),\n action_hash: z.string().regex(/^sha256:[0-9a-f]{64}$/),\n status: managedEscalationStatusSchema,\n outcome: managedEscalationOutcomeSchema,\n expires_at: z.string().datetime(),\n reason_codes: z.array(z.string().min(1).max(200)).max(50),\n approval_tier: managedApprovalTierSchema.nullable().optional().default(null),\n approval_chain: managedApprovalChainSchema.nullable().optional().default(null),\n decision: authorityDecisionSchema.nullable(),\n })\n .strict()\n .superRefine((view, context) => {\n if (view.outcome !== expectedManagedEscalationOutcome(view.status)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"outcome\"],\n message: \"managed escalation outcome does not match its lifecycle status\",\n });\n }\n const grantReady = view.status === \"GRANT_READY\";\n if (\n grantReady !==\n (view.outcome === \"ALLOW\" &&\n view.decision?.status === \"ALLOW\" &&\n view.decision.should_execute === true &&\n view.decision.execution_eligible === true &&\n typeof view.decision.execution_token === \"string\")\n ) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"decision\"],\n message: \"GRANT_READY must carry one normal executable ALLOW decision\",\n });\n }\n if (!grantReady && view.decision !== null) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"decision\"],\n message: \"a non-ready managed escalation cannot carry a decision or grant\",\n });\n }\n });\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 DecionisAuthorityPolicyProjection {\n decision_type: string;\n transaction_type: string | null;\n workflow_key: string | null;\n channel: string | null;\n}\n\n/** Ceremony methods currently supported by Decionis-managed Presence orchestration. */\nexport type DecionisPresenceVerificationMethod = \"WEBAUTHN\" | \"ACTIVE_LIVENESS\";\n\n/**\n * Optional orchestration constraints for Decionis-managed Presence escalation.\n * These fields never assert that a human has a role. Decionis and Presence\n * resolve the effective policy requirement from trusted tenant identity data.\n */\nexport interface DecionisManagedEscalationRequest {\n mode: \"MANAGED\";\n approver?: {\n principal_id?: string;\n role_id?: string;\n };\n verification_requirements?: {\n methods: DecionisPresenceVerificationMethod[];\n level?: \"STANDARD\" | \"HIGH_CONFIDENCE\";\n };\n}\n\nexport type DecionisManagedEscalationStatus = z.infer<typeof managedEscalationStatusSchema>;\nexport type DecionisManagedEscalationOutcome = z.infer<typeof managedEscalationOutcomeSchema>;\n\nexport interface DecionisManagedEscalationReference {\n outcome: DecionisManagedEscalationOutcome;\n escalation_id: string;\n intent_id: string;\n status: DecionisManagedEscalationStatus;\n expires_at: string;\n reason_codes: 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 policy_projection?: DecionisAuthorityPolicyProjection;\n /** Pre-dispatch digest of the state that may later qualify as a confirmed effect. */\n expected_effect_digest?: `sha256:${string}`;\n intent_hash: `sha256:${string}`;\n mode: \"SHADOW\" | \"PARALLEL\" | \"ENFORCEMENT\";\n escalation?: DecionisManagedEscalationRequest;\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\" | \"escalation\"\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 authority_classification: \"AUTHORITATIVE\" | \"OBSERVATIONAL\" | null;\n execution_eligible: boolean;\n execution_binding_digest: string | null;\n execution_token: string | null;\n execution_token_jti: string | null;\n execution_token_key_id: 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 /** Present only for Decionis-managed escalation responses. */\n managed_escalation?: DecionisManagedEscalationReference | null;\n [key: string]: unknown;\n}\n\nexport interface DecionisManagedEscalationView {\n escalation_id: string;\n intent_id: string;\n action_hash: string;\n status: DecionisManagedEscalationStatus;\n outcome: DecionisManagedEscalationOutcome;\n expires_at: string;\n reason_codes: string[];\n decision: DecionisAuthorityDecision | null;\n}\n\nexport interface DecionisManagedEscalationWaitOptions {\n /** Stop waiting and reject immediately when aborted. */\n signal?: AbortSignal;\n /** Test/advanced seam; production callers normally keep the 500ms default. */\n initialDelayMs?: number;\n /** Hard cap for exponential polling. Never allowed above five seconds. */\n maxDelayMs?: number;\n /** Random source for bounded equal jitter. */\n random?: () => number;\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 should_execute?: boolean;\n reason_codes: string[];\n claims: Record<string, unknown> | null;\n claim_token?: string | null;\n /** Database time of the final pre-dispatch eligibility confirmation. */\n claim_validated_at?: string | null;\n claim_lease_expires_at?: string | null;\n /**\n * Proof of this claim a downstream system of record can verify without\n * trusting the caller: a compact EdDSA JWS signed with the execution-grant\n * key, verifiable against `/.well-known/decionis-execution-grant-jwks.json`.\n * Forward it with the downstream request. Absent when the authority\n * predates it; a consumer that never reads it is exactly as correct as\n * before it existed.\n */\n claim_attestation?: string | null;\n evidence?: Record<string, unknown>;\n}\n\nexport interface DecionisLegacyExecutionEffectEvidence {\n effect_schema_version: \"1.0\";\n status: \"CONFIRMED\" | \"FAILED\" | \"INDETERMINATE\";\n request_digest: `sha256:${string}`;\n response_digest: `sha256:${string}` | null;\n digest_algorithm: \"SHA-256\";\n canonicalization_profile: string;\n external_reference: string | null;\n observation_mode: \"GATE_OBSERVED\" | \"RUNTIME_REPORTED\";\n observer: {\n id: string;\n version: string;\n };\n observed_at: string;\n metadata_digest: `sha256:${string}` | null;\n}\n\n/**\n * Validate the database-time confirmation returned by the pre-commit claim.\n * A live lease without this boundary is not sufficient execution authority.\n */\nexport function isExecutionClaimConfirmationValid(\n claim: Pick<\n DecionisExecutionGrantRedemption,\n \"claim_validated_at\" | \"claim_lease_expires_at\" | \"evidence\"\n >,\n nowMs = Date.now(),\n): boolean {\n const validatedAtMs =\n typeof claim.claim_validated_at === \"string\"\n ? Date.parse(claim.claim_validated_at)\n : Number.NaN;\n const leaseExpiresAtMs =\n typeof claim.claim_lease_expires_at === \"string\"\n ? Date.parse(claim.claim_lease_expires_at)\n : Number.NaN;\n const evidenceRevalidatedAt = claim.evidence?.revalidated_at;\n const evidenceRevalidatedAtMs =\n typeof evidenceRevalidatedAt === \"string\" ? Date.parse(evidenceRevalidatedAt) : null;\n return (\n Number.isFinite(validatedAtMs) &&\n Number.isFinite(leaseExpiresAtMs) &&\n validatedAtMs <= nowMs &&\n validatedAtMs < leaseExpiresAtMs &&\n (evidenceRevalidatedAtMs === null ||\n (Number.isFinite(evidenceRevalidatedAtMs) && evidenceRevalidatedAtMs <= validatedAtMs))\n );\n}\n\n/** Fields shared by confirmed and unconfirmed Protocol 1.1 effect observations. */\ninterface DecionisProtocol11EffectEvidenceBase {\n version: \"1.0\";\n observation_method:\n | \"DOWNSTREAM_ACK\"\n | \"READ_AFTER_WRITE\"\n | \"EVENT_CONFIRMATION\"\n | \"STATE_RECONCILIATION\"\n | \"SIGNED_RECEIPT\"\n | \"EXTERNAL_ATTESTATION\"\n | \"HUMAN_VALIDATION\";\n expected_effect_digest: `sha256:${string}`;\n evidence_digest: `sha256:${string}` | null;\n evidence_reference: string | null;\n execution_correlation_id: string;\n}\n\n/**\n * Protocol 1.1 effect observation. Confirmation requires a pre-bound expected\n * digest and versioned observer provenance; weaker observations remain typed\n * as UNCONFIRMED instead of manufacturing that provenance.\n */\nexport type DecionisProtocol11EffectEvidence =\n | (DecionisProtocol11EffectEvidenceBase & {\n status: \"CONFIRMED\";\n observer: { id: string; version: string };\n observed_effect_digest: `sha256:${string}`;\n observed_at: string;\n })\n | (DecionisProtocol11EffectEvidenceBase & {\n status: \"UNCONFIRMED\";\n observer: { id: string; version: string | null } | null;\n observed_effect_digest: `sha256:${string}` | null;\n observed_at: string | null;\n });\n\nexport type DecionisExecutionEffectEvidence =\n | DecionisLegacyExecutionEffectEvidence\n | DecionisProtocol11EffectEvidence;\n\nexport interface DecionisExecutionEffectOptions<TOutput = unknown> {\n /** Stable downstream identifier such as a payment, deployment, or transaction id. */\n externalReference?: string;\n /** Identifies the gate that directly observed the callback result. */\n observer?: { id: string; version: string };\n /** Optional non-sensitive metadata, represented in evidence only by its digest. */\n metadata?: Record<string, unknown>;\n /** Deterministic response bytes for non-JSON callback results. */\n responseCanonicalizer?: {\n profile: string;\n canonicalize: (response: TOutput) => string | Uint8Array;\n };\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 effectEvidence?: DecionisExecutionEffectOptions<TOutput>;\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 { response, body: responseBody } = await fetchBoundedJson(\n fetchImpl,\n `${baseUrl}${route}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(options.defaultHeaders ?? {}),\n },\n body: JSON.stringify(body),\n },\n options.timeoutMs ?? 4_000,\n );\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}\n\nasync function getJson<TResult>(\n options: DecionisExecutionClientOptions,\n route: string,\n signal?: AbortSignal,\n): Promise<TResult> {\n const baseUrl = options.authorityBaseUrl.replace(/\\/+$/, \"\");\n const fetchImpl = options.fetch ?? fetch;\n const { response, body } = await fetchBoundedJson(\n fetchImpl,\n `${baseUrl}${route}`,\n {\n method: \"GET\",\n headers: { accept: \"application/json\", ...(options.defaultHeaders ?? {}) },\n ...(signal === undefined ? {} : { signal }),\n },\n options.timeoutMs ?? 4_000,\n );\n if (!response.ok) {\n throw new DecionisExecutionClientError(\n `Decionis execution authority request failed with status ${response.status}`,\n { status: response.status, body },\n );\n }\n return body as TResult;\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 if (request.escalation !== undefined) {\n if (request.mode !== \"ENFORCEMENT\") {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_REQUIRES_ENFORCEMENT\");\n }\n if (request.evidence?.humanApproval !== undefined) {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_EVIDENCE_IS_SERVER_MANAGED\");\n }\n }\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 const decision = authorityDecisionSchema.parse(response) as DecionisAuthorityDecision;\n assertAuthorityDecisionMatchesRequest(decision, request);\n if (\n request.escalation?.mode === \"MANAGED\" &&\n decision.status === \"ESCALATE\" &&\n (decision.managed_escalation ?? null) === null\n ) {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_REFERENCE_MISSING\");\n }\n if (request.escalation === undefined && (decision.managed_escalation ?? null) !== null) {\n throw new Error(\"DECIONIS_UNREQUESTED_MANAGED_ESCALATION\");\n }\n return decision;\n };\n\n /** Fetch one tenant-bound managed escalation without contacting Presence. */\n getManagedEscalationStatus = async (\n request: DecionisAuthorityRequest,\n escalation: string | DecionisManagedEscalationReference,\n signal?: AbortSignal,\n ): Promise<DecionisManagedEscalationView> => {\n const reference = managedEscalationReference(request, escalation);\n const response = await getJson<unknown>(\n this.options,\n `/v1/authority/escalations/${encodeURIComponent(reference.escalation_id)}`,\n signal,\n );\n const view = managedEscalationViewSchema.parse(response) as DecionisManagedEscalationView;\n assertManagedEscalationMatchesRequest(view, reference, request);\n return view;\n };\n\n /**\n * Wait for Decionis-managed Presence authorization using capped exponential\n * backoff with equal jitter. The waiter never talks to Presence and never\n * waits beyond the original exact intent's expiry.\n */\n waitForAuthorization = async (\n request: DecionisAuthorityRequest,\n pending: DecionisAuthorityDecision | DecionisManagedEscalationReference | string,\n options: DecionisManagedEscalationWaitOptions = {},\n ): Promise<DecionisManagedEscalationView> => {\n const source =\n typeof pending === \"object\" && \"decision_id\" in pending\n ? pending.managed_escalation\n : pending;\n if (source === null || source === undefined) {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_REFERENCE_MISSING\");\n }\n const reference = managedEscalationReference(request, source);\n let deadline = Math.min(Date.parse(request.expires_at), Date.parse(reference.expires_at));\n if (!Number.isFinite(deadline)) throw new Error(\"DECIONIS_MANAGED_ESCALATION_EXPIRY_INVALID\");\n const initialDelayMs = boundedPollDelay(options.initialDelayMs ?? 500, 50, 5_000);\n const maxDelayMs = boundedPollDelay(options.maxDelayMs ?? 5_000, initialDelayMs, 5_000);\n const random = options.random ?? Math.random;\n let delayMs = initialDelayMs;\n\n while (true) {\n throwIfAborted(options.signal);\n const now = Date.now();\n if (now >= deadline) return expiredManagedEscalation(reference, request);\n const jitteredDelay = Math.max(1, Math.floor(delayMs * (0.5 + boundedRandom(random) * 0.5)));\n await abortableDelay(Math.min(jitteredDelay, Math.max(1, deadline - now)), options.signal);\n if (Date.now() >= deadline) return expiredManagedEscalation(reference, request);\n const view = await this.getManagedEscalationStatus(request, reference, options.signal);\n if (isManagedEscalationTerminal(view.status)) return view;\n // The policy-issued authority requirement may be stricter than the\n // captured intent. Once Decionis returns that bound deadline, never poll\n // beyond it (including when the caller supplied only an escalation id).\n deadline = Math.min(deadline, Date.parse(view.expires_at));\n delayMs = Math.min(maxDelayMs, delayMs * 2);\n }\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 try {\n const { response, body: rawBody } = await fetchBoundedJson(\n fetchImpl,\n `${baseUrl}/v1/execution/claim-token`,\n {\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 },\n this.options.timeoutMs ?? 4_000,\n );\n const body = rawBody as Partial<DecionisExecutionGrantRedemption> | null;\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 claimToken =\n typeof body.claim_token === \"string\" && body.claim_token.trim().length > 0\n ? body.claim_token\n : null;\n const claimLeaseExpiresAt =\n typeof body.claim_lease_expires_at === \"string\" ? body.claim_lease_expires_at : null;\n const claimValidatedAt =\n typeof body.claim_validated_at === \"string\" ? body.claim_validated_at : null;\n const claimLeaseExpiresAtMs =\n claimLeaseExpiresAt === null ? Number.NaN : Date.parse(claimLeaseExpiresAt);\n const claimCheckedAtMs = Date.now();\n if (\n body.should_execute !== true ||\n claimToken === null ||\n !Number.isFinite(claimLeaseExpiresAtMs) ||\n claimCheckedAtMs >= claimLeaseExpiresAtMs ||\n !isExecutionClaimConfirmationValid(\n {\n claim_validated_at: claimValidatedAt,\n claim_lease_expires_at: claimLeaseExpiresAt,\n ...(body.evidence && typeof body.evidence === \"object\"\n ? { evidence: body.evidence as Record<string, unknown> }\n : {}),\n },\n claimCheckedAtMs,\n )\n ) {\n return {\n valid: false,\n reason_codes: [\"DECIONIS_CLAIM_NOT_EXECUTION_ELIGIBLE\"],\n claims: body.claims ?? null,\n };\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 (typeof binding?.execution_payload_digest === \"string\" &&\n (binding.execution_payload_canonicalization_profile !== \"RFC8785/JCS\" ||\n binding.execution_payload_digest !==\n executionEffectDigest(request.action.parameters))) ||\n (request.expected_effect_digest !== undefined &&\n binding?.expected_effect_digest !== request.expected_effect_digest) ||\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 const redemption: DecionisExecutionGrantRedemption = {\n valid: true,\n should_execute: true,\n reason_codes: Array.isArray(body.reason_codes) ? body.reason_codes : [],\n claims,\n claim_token: claimToken,\n claim_validated_at: claimValidatedAt,\n claim_lease_expires_at: claimLeaseExpiresAt,\n ...(typeof body.claim_attestation === \"string\" && body.claim_attestation.length > 0\n ? { claim_attestation: body.claim_attestation }\n : {}),\n ...(body.evidence && typeof body.evidence === \"object\"\n ? { evidence: body.evidence as Record<string, unknown> }\n : {}),\n };\n if (executionAuthorityProtocolSemantics(redemption) === \"UNSUPPORTED\") {\n return {\n ...redemption,\n valid: false,\n should_execute: false,\n claim_token: null,\n reason_codes: [\n ...redemption.reason_codes,\n \"DECIONIS_AUTHORITY_PROTOCOL_VERSION_UNSUPPORTED\",\n ],\n };\n }\n return redemption;\n } catch {\n return { valid: false, reason_codes: [\"DECIONIS_GRANT_REDEEM_ERROR\"], claims: null };\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 effectEvidence?: DecionisExecutionEffectEvidence;\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 ...(input.effectEvidence ? { effect_evidence: input.effectEvidence } : {}),\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.should_execute !== true || !grant.claim_token) {\n return { executed: false, decision, grant, reason: \"GRANT_NOT_REDEEMABLE\", result: null };\n }\n const authorityProtocolSemantics = executionAuthorityProtocolSemantics(grant);\n if (authorityProtocolSemantics === \"UNSUPPORTED\") {\n grant.reason_codes = [\n ...grant.reason_codes,\n \"DECIONIS_AUTHORITY_PROTOCOL_VERSION_UNSUPPORTED\",\n ];\n return { executed: false, decision, grant, reason: \"GRANT_NOT_REDEEMABLE\", result: null };\n }\n let result: TOutput;\n // Historical grants retain their original gate-observed effect record.\n // A 1.1 grant may only carry the stronger, pre-bound EffectEvidence\n // contract; this helper does not infer READ_AFTER_WRITE from an executor\n // callback, so it finalizes without confirmation rather than downgrading.\n const protocol11Authority = authorityProtocolSemantics === \"PROTOCOL_1_1\";\n const effectRequestBinding = protocol11Authority ? null : executionEffectRequestBinding(grant);\n const claimLeaseExpiresAtMs = grant.claim_lease_expires_at\n ? Date.parse(grant.claim_lease_expires_at)\n : Number.NaN;\n if (!Number.isFinite(claimLeaseExpiresAtMs) || Date.now() >= claimLeaseExpiresAtMs) {\n return { executed: false, decision, grant, reason: \"GRANT_NOT_REDEEMABLE\", result: null };\n }\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 const outcome = input.classifyFailure?.(error) ?? \"INDETERMINATE\";\n const downstreamEvidence = {\n error_type: error instanceof Error ? error.name : \"unknown\",\n };\n const failureEffectEvidence = effectRequestBinding\n ? (tryCreateExecutionEffectEvidence({\n requestDigest: effectRequestBinding.digest,\n status: outcome,\n responseDigest: null,\n canonicalizationProfile: effectRequestBinding.profile,\n options: input.effectEvidence,\n metadata: input.effectEvidence?.metadata ?? downstreamEvidence,\n }) ??\n tryCreateExecutionEffectEvidence({\n requestDigest: effectRequestBinding.digest,\n status: outcome,\n responseDigest: null,\n canonicalizationProfile: effectRequestBinding.profile,\n options: input.effectEvidence,\n metadata: downstreamEvidence,\n }))\n : undefined;\n await this.finalizeGrant({\n executionToken: decision.execution_token,\n claimToken: grant.claim_token,\n outcome,\n commitCorrelationId,\n downstreamEvidence,\n ...(failureEffectEvidence ? { effectEvidence: failureEffectEvidence } : {}),\n });\n throw error;\n }\n let effectEvidence: DecionisExecutionEffectEvidence | undefined;\n if (effectRequestBinding) {\n const responseBinding = executionEffectResponseBinding(result, input.effectEvidence);\n effectEvidence = responseBinding\n ? tryCreateExecutionEffectEvidence({\n requestDigest: effectRequestBinding.digest,\n status: \"CONFIRMED\",\n responseDigest: responseBinding.digest,\n canonicalizationProfile: responseBinding.profile,\n options: input.effectEvidence,\n metadata: input.effectEvidence?.metadata,\n })\n : undefined;\n if (!effectEvidence) {\n grant.reason_codes = [...grant.reason_codes, \"EFFECT_CONFIRMATION_UNAVAILABLE\"];\n }\n } else {\n grant.reason_codes = [\n ...grant.reason_codes,\n protocol11Authority\n ? \"PROTOCOL_1_1_EFFECT_EVIDENCE_REQUIRED\"\n : \"EFFECT_CONFIRMATION_UNAVAILABLE\",\n ];\n }\n const finalized = await this.finalizeGrant({\n executionToken: decision.execution_token,\n claimToken: grant.claim_token,\n outcome: \"COMMITTED\",\n commitCorrelationId,\n ...(effectEvidence ? { effectEvidence } : {}),\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 ...(request.policy_projection ? { policy_projection: request.policy_projection } : {}),\n ...(request.expected_effect_digest\n ? { expected_effect_digest: request.expected_effect_digest }\n : {}),\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 escalation?: DecionisManagedEscalationRequest,\n): DecionisAuthorityRequest {\n return {\n ...binding,\n intent_hash: hashAuthorityIntentBinding(binding),\n mode,\n ...(evidence === undefined ? {} : { evidence }),\n ...(escalation === undefined ? {} : { escalation }),\n };\n}\n\n/** Bind an exact intent while requesting Decionis-owned Presence orchestration. */\nexport function bindManagedAuthorityIntent(\n binding: DecionisAuthorityIntentBinding,\n escalation: DecionisManagedEscalationRequest,\n): DecionisAuthorityRequest {\n return bindAuthorityIntent(binding, undefined, \"ENFORCEMENT\", escalation);\n}\n\nfunction assertAuthorityDecisionMatchesRequest(\n decision: DecionisAuthorityDecision,\n request: DecionisAuthorityRequest,\n): void {\n if (decision.action_hash !== request.intent_hash) {\n throw new Error(\"DECIONIS_AUTHORITY_ACTION_HASH_MISMATCH\");\n }\n const escalation = decision.managed_escalation;\n if (escalation === null || escalation === undefined) return;\n if (\n escalation.intent_id !== request.intent_id ||\n Date.parse(escalation.expires_at) > Date.parse(request.expires_at)\n ) {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_BINDING_MISMATCH\");\n }\n}\n\nfunction managedEscalationReference(\n request: DecionisAuthorityRequest,\n input: string | DecionisManagedEscalationReference,\n): DecionisManagedEscalationReference {\n if (typeof input !== \"string\") {\n const parsed = managedEscalationReferenceSchema.parse(input);\n if (\n parsed.intent_id !== request.intent_id ||\n Date.parse(parsed.expires_at) > Date.parse(request.expires_at)\n ) {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_BINDING_MISMATCH\");\n }\n return parsed;\n }\n const id = input.trim();\n if (id.length < 8 || id.length > 200) {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_ID_INVALID\");\n }\n return {\n escalation_id: id,\n intent_id: request.intent_id,\n status: \"PENDING_PRESENCE\",\n outcome: \"ESCALATE_PENDING\",\n expires_at: request.expires_at,\n reason_codes: [\"PRESENCE_PENDING\"],\n };\n}\n\nfunction assertManagedEscalationMatchesRequest(\n view: DecionisManagedEscalationView,\n reference: DecionisManagedEscalationReference,\n request: DecionisAuthorityRequest,\n): void {\n if (\n view.escalation_id !== reference.escalation_id ||\n view.intent_id !== request.intent_id ||\n view.action_hash !== request.intent_hash ||\n Date.parse(view.expires_at) > Date.parse(reference.expires_at) ||\n Date.parse(view.expires_at) > Date.parse(request.expires_at)\n ) {\n throw new Error(\"DECIONIS_MANAGED_ESCALATION_BINDING_MISMATCH\");\n }\n if (view.decision !== null) assertAuthorityDecisionMatchesRequest(view.decision, request);\n}\n\nfunction isManagedEscalationTerminal(status: DecionisManagedEscalationStatus): boolean {\n return [\"GRANT_READY\", \"EXPIRED\", \"REJECTED\", \"BLOCKED\", \"CANCELLED\", \"FAILED\"].includes(status);\n}\n\nfunction expiredManagedEscalation(\n reference: DecionisManagedEscalationReference,\n request: DecionisAuthorityRequest,\n): DecionisManagedEscalationView {\n return {\n escalation_id: reference.escalation_id,\n intent_id: request.intent_id,\n action_hash: request.intent_hash,\n status: \"EXPIRED\",\n outcome: \"BLOCK\",\n expires_at: reference.expires_at,\n reason_codes: [\"INTENT_EXPIRED\", \"RECAPTURE_REQUIRED\"],\n decision: null,\n };\n}\n\nfunction boundedPollDelay(value: number, minimum: number, maximum: number): number {\n if (!Number.isFinite(value)) return minimum;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\n\nfunction boundedRandom(random: () => number): number {\n const value = random();\n return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0.5;\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (!signal?.aborted) return;\n throw signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n\nasync function abortableDelay(delayMs: number, signal: AbortSignal | undefined): Promise<void> {\n throwIfAborted(signal);\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", abort);\n resolve();\n }, delayMs);\n const abort = () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abort);\n reject(\n signal?.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The operation was aborted\", \"AbortError\"),\n );\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\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 executionEffectRequestBinding(\n grant: DecionisExecutionGrantRedemption,\n): { digest: `sha256:${string}`; profile: \"RFC8785/JCS\" } | null {\n const binding =\n grant.claims &&\n typeof grant.claims.binding === \"object\" &&\n grant.claims.binding !== null &&\n !Array.isArray(grant.claims.binding)\n ? (grant.claims.binding as Record<string, unknown>)\n : null;\n const digest = binding?.execution_payload_digest;\n const profile = binding?.execution_payload_canonicalization_profile;\n return typeof digest === \"string\" &&\n /^sha256:[0-9a-f]{64}$/.test(digest) &&\n profile === \"RFC8785/JCS\"\n ? { digest: digest as `sha256:${string}`, profile }\n : null;\n}\n\ntype ExecutionAuthorityProtocolSemantics = \"LEGACY\" | \"PROTOCOL_1_1\" | \"UNSUPPORTED\";\n\nfunction executionAuthorityProtocolSemantics(\n grant: DecionisExecutionGrantRedemption,\n): ExecutionAuthorityProtocolSemantics {\n const binding =\n grant.claims &&\n typeof grant.claims.binding === \"object\" &&\n grant.claims.binding !== null &&\n !Array.isArray(grant.claims.binding)\n ? (grant.claims.binding as Record<string, unknown>)\n : null;\n if (!binding || !Object.prototype.hasOwnProperty.call(binding, \"authority_protocol_version\")) {\n return \"LEGACY\";\n }\n const version = binding.authority_protocol_version;\n if (version === \"1.1\") return \"PROTOCOL_1_1\";\n if (version === \"1.0\" || version === \"1.0.0\") return \"LEGACY\";\n return \"UNSUPPORTED\";\n}\n\nfunction createExecutionEffectEvidence(input: {\n requestDigest: `sha256:${string}`;\n status: \"CONFIRMED\" | \"FAILED\" | \"INDETERMINATE\";\n responseDigest: `sha256:${string}` | null;\n canonicalizationProfile: string;\n options?: Pick<\n DecionisExecutionEffectOptions<never>,\n \"externalReference\" | \"observer\" | \"metadata\"\n >;\n metadata?: Record<string, unknown>;\n}): DecionisLegacyExecutionEffectEvidence {\n return {\n effect_schema_version: \"1.0\",\n status: input.status,\n request_digest: input.requestDigest,\n response_digest: input.responseDigest,\n digest_algorithm: \"SHA-256\",\n canonicalization_profile: input.canonicalizationProfile,\n external_reference: input.options?.externalReference?.trim() || null,\n observation_mode: \"GATE_OBSERVED\",\n observer: input.options?.observer ?? {\n id: \"@decionis/sdk\",\n version: \"effect-binding-v1\",\n },\n observed_at: new Date().toISOString(),\n metadata_digest: input.metadata ? executionEffectDigest(input.metadata) : null,\n };\n}\n\nfunction tryCreateExecutionEffectEvidence(\n input: Omit<Parameters<typeof createExecutionEffectEvidence>[0], \"responseDigest\"> & {\n responseDigest: `sha256:${string}` | null | undefined;\n },\n): DecionisLegacyExecutionEffectEvidence | undefined {\n if (input.status === \"CONFIRMED\" && !input.responseDigest) return undefined;\n try {\n return createExecutionEffectEvidence({\n ...input,\n responseDigest: input.responseDigest ?? null,\n });\n } catch {\n return undefined;\n }\n}\n\nfunction executionEffectResponseBinding<TOutput>(\n value: TOutput,\n options: DecionisExecutionEffectOptions<TOutput> | undefined,\n): { digest: `sha256:${string}`; profile: string } | undefined {\n try {\n const canonicalizer = options?.responseCanonicalizer;\n if (!canonicalizer) {\n return { digest: executionEffectDigest(value), profile: \"RFC8785/JCS\" };\n }\n const profile = canonicalizer.profile.trim();\n if (!profile || profile.length > 500) return undefined;\n const bytes = canonicalizer.canonicalize(value);\n return {\n digest: `sha256:${createHash(\"sha256\").update(bytes).digest(\"hex\")}`,\n profile,\n };\n } catch {\n return undefined;\n }\n}\n\n/** RFC 8785/JCS SHA-256 digest used for SDK-observed execution effects. */\nexport function executionEffectDigest(value: unknown): `sha256:${string}` {\n return `sha256:${createHash(\"sha256\").update(jcsCanonicalize(value), \"utf8\").digest(\"hex\")}`;\n}\n\nfunction 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 const item = record[key];\n if (item === undefined) throw new TypeError(\"JCS_UNDEFINED_NOT_ALLOWED\");\n return `${JSON.stringify(key)}:${jcsCanonicalize(item)}`;\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\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","import { fetchBoundedJson } from \"./BoundedFetch\";\n\ntype 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 binding?: {\n authority_protocol_version?: unknown;\n [key: string]: unknown;\n };\n}\n\nexport interface DecionisExecutionTokenConsumeResponse {\n valid: boolean;\n should_execute?: boolean;\n reason_codes: string[];\n claims: DecionisExecutionTokenClaims | null;\n claim_token?: string | null;\n claim_validated_at?: string | null;\n claim_lease_expires_at?: string | null;\n evidence?: Record<string, unknown>;\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\nfunction hasSupportedAuthorityProtocolVersion(\n claims: DecionisExecutionTokenClaims | null,\n): boolean {\n const binding = claims?.binding;\n if (!binding || !Object.prototype.hasOwnProperty.call(binding, \"authority_protocol_version\")) {\n return true;\n }\n return (\n binding.authority_protocol_version === \"1.0\" ||\n binding.authority_protocol_version === \"1.0.0\" ||\n binding.authority_protocol_version === \"1.1\"\n );\n}\n\n/**\n * A successful verification response is not, by itself, execution authority.\n * The compatibility consume route is a pre-commit claim boundary, so a\n * downstream handler may run only while its returned single-use claim lease is\n * live and its authority semantics are understood by this SDK.\n */\nexport function isExecutionTokenClaimEligible(\n response: DecionisExecutionTokenConsumeResponse,\n nowMs = Date.now(),\n): boolean {\n const claimToken =\n typeof response.claim_token === \"string\" && response.claim_token.trim().length > 0\n ? response.claim_token\n : null;\n const leaseExpiresAtMs =\n typeof response.claim_lease_expires_at === \"string\"\n ? Date.parse(response.claim_lease_expires_at)\n : Number.NaN;\n const validatedAtMs =\n typeof response.claim_validated_at === \"string\"\n ? Date.parse(response.claim_validated_at)\n : Number.NaN;\n const evidenceRevalidatedAt = response.evidence?.revalidated_at;\n const evidenceRevalidatedAtMs =\n typeof evidenceRevalidatedAt === \"string\" ? Date.parse(evidenceRevalidatedAt) : null;\n return (\n response.valid === true &&\n response.should_execute === true &&\n response.claims !== null &&\n claimToken !== null &&\n Number.isFinite(leaseExpiresAtMs) &&\n Number.isFinite(validatedAtMs) &&\n validatedAtMs <= nowMs &&\n validatedAtMs < leaseExpiresAtMs &&\n (evidenceRevalidatedAtMs === null ||\n (Number.isFinite(evidenceRevalidatedAtMs) && evidenceRevalidatedAtMs <= validatedAtMs)) &&\n nowMs < leaseExpiresAtMs &&\n hasSupportedAuthorityProtocolVersion(response.claims)\n );\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 { response, body } = await fetchBoundedJson(\n fetchImpl,\n `${baseUrl}/v1/execution/consume-token`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n execution_token: token,\n ...binding,\n }),\n },\n options.timeoutMs ?? 4_000,\n );\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}\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 (!isExecutionTokenClaimEligible(verification)) {\n const reasonCodes = hasSupportedAuthorityProtocolVersion(verification.claims)\n ? verification.reason_codes.length > 0\n ? verification.reason_codes\n : [\"DECIONIS_CLAIM_NOT_EXECUTION_ELIGIBLE\"]\n : [\"DECIONIS_AUTHORITY_PROTOCOL_VERSION_UNSUPPORTED\"];\n const body = buildRejectBody(reasonCodes, 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 await options.onVerified?.(attachment, request, response);\n\n // `onVerified` may perform asynchronous setup. Recheck immediately\n // before yielding to the downstream handler so an elapsed lease cannot\n // cross this last responsible execution boundary.\n if (!isExecutionTokenClaimEligible(verification)) {\n const body = buildRejectBody([\"DECIONIS_CLAIM_NOT_EXECUTION_ELIGIBLE\"], 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 (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 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\";\nimport { fetchBounded } from \"./BoundedFetch\";\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\nfunction readResponseBody(response: Response, text: string): unknown {\n const type = response.headers.get(\"content-type\") ?? \"\";\n if (type.includes(\"application/json\")) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return null;\n }\n }\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 { response, text } = await fetchBounded(\n this.fetchImpl,\n `${this.baseUrl}${path}`,\n {\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 },\n this.options.timeoutMs ?? 4_000,\n );\n const body = readResponseBody(response, text);\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 }\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","import {\n createDecionisExecutionClient,\n isExecutionClaimConfirmationValid,\n type DecionisAuthorityDecision,\n type DecionisAuthorityRequest,\n type DecionisExecutionEffectEvidence,\n type DecionisExecutionGrantRedemption,\n} from \"@decionis/sdk\";\nimport { createHash } from \"node:crypto\";\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 finalizeGrant(input: {\n executionToken: string;\n claimToken: string;\n outcome: \"COMMITTED\" | \"FAILED\" | \"INDETERMINATE\";\n commitCorrelationId: string;\n downstreamEvidence?: Record<string, unknown>;\n effectEvidence?: DecionisExecutionEffectEvidence;\n }): Promise<boolean>;\n}\n\nexport interface KubernetesEffectSummary {\n action_hash: string;\n resource: string;\n status: \"COMMITTED\" | \"CONFIRMED\" | \"INDETERMINATE\";\n finalized: boolean;\n response_digest: string | null;\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 execution_attempted?: boolean;\n partial_execution?: boolean;\n effects?: KubernetesEffectSummary[];\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\ntype AuthorityProtocolSemantics = \"LEGACY\" | \"PROTOCOL_1_1\" | \"UNSUPPORTED\";\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 (action) => {\n const args = [\"apply\", \"--filename\", \"-\"];\n if (namespace) args.push(\"--namespace\", namespace);\n return this.runner.run(args, KubernetesOperations.executionManifest([action]));\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 (action) => {\n const args = [\"apply\", \"--filename\", \"-\"];\n if (namespace) args.push(\"--namespace\", namespace);\n return this.runner.run(args, KubernetesOperations.executionManifest([action]));\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: (action: PlannedKubernetesAction) => 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 const effects: KubernetesEffectSummary[] = [];\n const outputs: string[] = [];\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 (!KubernetesOperations.executionClaimEligible(redemption, Date.now())) {\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: summaries,\n execution_attempted: outputs.length > 0,\n partial_execution: outputs.length > 0,\n effects,\n reason_code: redemption.reason_codes[0] ?? \"DECIONIS_EXECUTION_GRANT_INVALID\",\n };\n }\n const authorityProtocolSemantics =\n KubernetesOperations.authorityProtocolSemantics(redemption);\n if (authorityProtocolSemantics === \"UNSUPPORTED\") {\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: summaries,\n execution_attempted: outputs.length > 0,\n partial_execution: outputs.length > 0,\n effects,\n reason_code: \"DECIONIS_AUTHORITY_PROTOCOL_VERSION_UNSUPPORTED\",\n };\n }\n const commitCorrelationId = action.request.intent_id;\n if (!KubernetesOperations.effectRequestDigest(redemption)) {\n await this.authority.finalizeGrant({\n executionToken: decision.execution_token!,\n claimToken: redemption.claim_token,\n outcome: \"FAILED\",\n commitCorrelationId,\n downstreamEvidence: { reason_code: \"DECIONIS_EFFECT_REQUEST_BINDING_REQUIRED\" },\n });\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: summaries,\n execution_attempted: outputs.length > 0,\n partial_execution: outputs.length > 0,\n effects,\n reason_code: \"DECIONIS_EFFECT_REQUEST_BINDING_REQUIRED\",\n };\n }\n // This is the last authority check before the cluster mutation. No await\n // or evidence work may be inserted between it and execute(action).\n if (!KubernetesOperations.executionClaimEligible(redemption, Date.now())) {\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: summaries,\n execution_attempted: outputs.length > 0,\n partial_execution: outputs.length > 0,\n effects,\n reason_code: \"DECIONIS_EXECUTION_CLAIM_NOT_ELIGIBLE\",\n };\n }\n try {\n const output = (await execute(action)).trim().slice(0, 8_000);\n outputs.push(output);\n const effectEvidence = KubernetesOperations.effectEvidence({\n action,\n redemption,\n status: \"CONFIRMED\",\n response: output,\n });\n const finalized = await this.authority.finalizeGrant({\n executionToken: decision.execution_token!,\n claimToken: redemption.claim_token,\n outcome: \"COMMITTED\",\n commitCorrelationId,\n ...(effectEvidence ? { effectEvidence } : {}),\n });\n effects.push({\n action_hash: action.request.intent_hash,\n resource: action.request.action.resource,\n status: effectEvidence?.status === \"CONFIRMED\" ? \"CONFIRMED\" : \"COMMITTED\",\n finalized,\n response_digest: KubernetesOperations.effectResponseDigest(effectEvidence),\n });\n if (!finalized) {\n return {\n executed: true,\n verdict: \"ERROR\",\n decisions: summaries,\n kubernetes_result: outputs.join(\"\\n\").slice(0, 8_000),\n execution_attempted: true,\n partial_execution: index + 1 < planned.length,\n effects,\n reason_code: \"DECIONIS_COMMIT_FINALIZATION_PENDING\",\n };\n }\n } catch (error) {\n const effectEvidence = KubernetesOperations.effectEvidence({\n action,\n redemption,\n status: \"INDETERMINATE\",\n });\n const finalized = await this.authority.finalizeGrant({\n executionToken: decision.execution_token!,\n claimToken: redemption.claim_token,\n outcome: \"INDETERMINATE\",\n commitCorrelationId,\n downstreamEvidence: {\n error_type: error instanceof Error ? error.name : \"unknown\",\n },\n ...(effectEvidence ? { effectEvidence } : {}),\n });\n effects.push({\n action_hash: action.request.intent_hash,\n resource: action.request.action.resource,\n status: \"INDETERMINATE\",\n finalized,\n response_digest: null,\n });\n return {\n executed: false,\n verdict: \"ERROR\",\n decisions: summaries,\n execution_attempted: true,\n partial_execution: outputs.length > 0,\n effects,\n reason_code: \"KUBERNETES_EXECUTION_INDETERMINATE_FRESH_AUTHORITY_REQUIRED\",\n };\n }\n }\n return {\n executed: true,\n verdict: \"ALLOW\",\n decisions: summaries,\n kubernetes_result: outputs.join(\"\\n\").slice(0, 8_000),\n execution_attempted: true,\n partial_execution: false,\n effects,\n };\n }\n\n private static effectEvidence(input: {\n action: PlannedKubernetesAction;\n redemption: DecionisExecutionGrantRedemption;\n status: \"CONFIRMED\" | \"INDETERMINATE\";\n response?: string;\n }): DecionisExecutionEffectEvidence | undefined {\n const requestDigest = KubernetesOperations.effectRequestDigest(input.redemption);\n if (!requestDigest) return undefined;\n // Protocol 1.1 refuses the historical evidence shape. Kubernetes does not\n // yet have a deterministic, pre-dispatch projection of the resulting\n // cluster state, so it must stop at COMMITTED instead of manufacturing a\n // confirmation from kubectl's acknowledgement text.\n if (KubernetesOperations.authorityProtocolSemantics(input.redemption) !== \"LEGACY\") {\n return undefined;\n }\n const responseDigest =\n input.status === \"CONFIRMED\" && input.response !== undefined\n ? (`sha256:${createHash(\"sha256\").update(input.response, \"utf8\").digest(\"hex\")}` as const)\n : null;\n return {\n effect_schema_version: \"1.0\",\n status: input.status,\n request_digest: requestDigest,\n response_digest: responseDigest,\n digest_algorithm: \"SHA-256\",\n canonicalization_profile: input.status === \"CONFIRMED\" ? \"UTF-8\" : \"RFC8785/JCS\",\n external_reference: KubernetesOperations.externalReference(input.action),\n observation_mode: \"GATE_OBSERVED\",\n observer: { id: \"@decionis/mcp:kubernetes\", version: \"effect-binding-v1\" },\n observed_at: new Date().toISOString(),\n metadata_digest: null,\n };\n }\n\n private static effectRequestDigest(\n redemption: DecionisExecutionGrantRedemption,\n ): `sha256:${string}` | null {\n const binding =\n redemption.claims &&\n typeof redemption.claims.binding === \"object\" &&\n redemption.claims.binding !== null &&\n !Array.isArray(redemption.claims.binding)\n ? (redemption.claims.binding as Record<string, unknown>)\n : null;\n const requestDigest = binding?.execution_payload_digest;\n if (typeof requestDigest !== \"string\" || !/^sha256:[0-9a-f]{64}$/.test(requestDigest)) {\n return null;\n }\n return requestDigest as `sha256:${string}`;\n }\n\n private static authorityProtocolSemantics(\n redemption: DecionisExecutionGrantRedemption,\n ): AuthorityProtocolSemantics {\n const binding =\n redemption.claims &&\n typeof redemption.claims.binding === \"object\" &&\n redemption.claims.binding !== null &&\n !Array.isArray(redemption.claims.binding)\n ? (redemption.claims.binding as Record<string, unknown>)\n : null;\n if (!binding || !Object.prototype.hasOwnProperty.call(binding, \"authority_protocol_version\")) {\n return \"LEGACY\";\n }\n const version = binding.authority_protocol_version;\n if (version === \"1.1\") return \"PROTOCOL_1_1\";\n if (version === \"1.0\" || version === \"1.0.0\") return \"LEGACY\";\n return \"UNSUPPORTED\";\n }\n\n private static executionClaimEligible(\n redemption: DecionisExecutionGrantRedemption,\n nowMs: number,\n ): redemption is DecionisExecutionGrantRedemption & {\n valid: true;\n should_execute: true;\n claim_token: string;\n claim_validated_at: string;\n claim_lease_expires_at: string;\n } {\n const claimToken = redemption.claim_token;\n const expiresAt = redemption.claim_lease_expires_at;\n const expiresAtMs = typeof expiresAt === \"string\" ? Date.parse(expiresAt) : Number.NaN;\n return (\n redemption.valid === true &&\n redemption.should_execute === true &&\n typeof claimToken === \"string\" &&\n claimToken.trim().length > 0 &&\n isExecutionClaimConfirmationValid(redemption, nowMs) &&\n Number.isFinite(expiresAtMs) &&\n nowMs < expiresAtMs\n );\n }\n\n private static effectResponseDigest(\n evidence: DecionisExecutionEffectEvidence | undefined,\n ): string | null {\n if (!evidence) return null;\n return \"response_digest\" in evidence\n ? evidence.response_digest\n : evidence.observed_effect_digest;\n }\n\n private static externalReference(action: PlannedKubernetesAction): string {\n const namespace = action.namespace ? `${action.namespace}/` : \"\";\n return `kubernetes://${action.request.downstream_target.system}/${namespace}${action.resource}/${action.name}`;\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","/**\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\";\nimport {\n classifyAuthorityProtocolEnvelope,\n validateProtocol11DossierAuthorityCommitments,\n} from \"@decionis/shared/decision-dossier-authority\";\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: \"JWKS_OVERLAP\";\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 when the listed proof-artifact digests and Ed25519 signatures verify. */\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 /** Bundle version and exact document paths whose signatures verified. */\n proof_bundle_version?: \"2.0\" | \"2.1\";\n verified_artifact_paths?: string[];\n /** Separate from signature validity: required before treating a dossier as executable. */\n required_artifact_coverage_verified?: boolean;\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\nconst DECISION_DOSSIER_JWKS_PATH = \"/.well-known/decision-dossier-jwks.json\";\nconst MAX_PROOF_KEY_ID_LENGTH = 128;\nconst MAX_RETAINED_PROOF_KEYS = 32;\nconst MAX_PUBLIC_JWKS_KEYS = 128;\n\nconst PROOF_ARTIFACT_SHAPES: Record<\n ProofArtifactKind,\n Pick<ProofArtifact, \"document_path\" | \"media_type\">\n> = {\n portable_artifact: {\n document_path: \"/portable_artifact\",\n media_type: \"application/json\",\n },\n inputs_snapshot: {\n document_path: \"/inputs_snapshot\",\n media_type: \"application/json\",\n },\n json_ld: {\n document_path: \"/linked_data/document\",\n media_type: \"application/ld+json\",\n },\n execution_binding: {\n document_path: \"/execution_binding\",\n media_type: \"application/json\",\n },\n};\n\nfunction nullableRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n}\n\nfunction boundedString(value: unknown, maxLength = 500): string | null {\n if (typeof value !== \"string\" || value.length === 0 || value.length > maxLength) return null;\n if (value !== value.trim()) return null;\n for (let index = 0; index < value.length; index += 1) {\n const codeUnit = value.charCodeAt(index);\n if (codeUnit <= 0x1f || codeUnit === 0x7f) return null;\n }\n return value;\n}\n\nfunction boundedKeyId(value: unknown): string | null {\n return boundedString(value, MAX_PROOF_KEY_ID_LENGTH);\n}\n\nfunction validDateTime(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$/.test(value) &&\n !Number.isNaN(Date.parse(value))\n );\n}\n\nfunction validEd25519Signature(value: unknown): value is string {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(value)) return false;\n try {\n return Buffer.from(value, \"base64url\").length === 64;\n } catch {\n return false;\n }\n}\n\nfunction normalizedPublicJwksUrl(value: unknown): string | undefined | null {\n if (value === undefined) return undefined;\n const text = boundedString(value, 2048);\n if (!text) return null;\n try {\n const url = new URL(text);\n if (url.protocol !== \"https:\" || url.username || url.password) return null;\n return url.toString();\n } catch {\n return null;\n }\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 validatePublicJwks(\n value: unknown,\n): { valid: true; jwks: Jwks | null } | { valid: false; detail: string } {\n if (value === null || value === undefined) return { valid: true, jwks: null };\n const record = nullableRecord(value);\n if (!record || !Array.isArray(record.keys)) {\n return { valid: false, detail: \"The public JWKS must contain a keys array.\" };\n }\n if (record.keys.length > MAX_PUBLIC_JWKS_KEYS) {\n return {\n valid: false,\n detail: `The public JWKS exceeds the ${MAX_PUBLIC_JWKS_KEYS}-key verification limit.`,\n };\n }\n const keys: Array<Record<string, unknown>> = [];\n for (const candidate of record.keys) {\n const key = nullableRecord(candidate);\n if (!key) {\n return { valid: false, detail: \"Every public JWKS key must be a JSON object.\" };\n }\n if (key.kid !== undefined && !boundedKeyId(key.kid)) {\n return { valid: false, detail: \"A public JWKS key has an invalid key identifier.\" };\n }\n for (const field of [\"kty\", \"crv\", \"alg\", \"use\", \"x\"] as const) {\n if (key[field] !== undefined && !boundedString(key[field], 512)) {\n return { valid: false, detail: `A public JWKS key has an invalid ${field} field.` };\n }\n }\n keys.push(key);\n }\n return { valid: true, jwks: { keys } };\n}\n\nfunction validEd25519PublicCoordinate(value: unknown): value is string {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9_-]{43}$/.test(value)) return false;\n try {\n return Buffer.from(value, \"base64url\").length === 32;\n } catch {\n return false;\n }\n}\n\nfunction findJwk(jwks: Jwks | null, keyId: string): Record<string, unknown> | null {\n if (!jwks || keyId.trim().length === 0) return null;\n const matches = jwks.keys.filter(\n (key) =>\n asString(key.kty) === \"OKP\" &&\n asString(key.crv) === \"Ed25519\" &&\n asString(key.kid) === keyId &&\n (key.alg === undefined || asString(key.alg) === \"EdDSA\") &&\n (key.use === undefined || asString(key.use) === \"sig\") &&\n validEd25519PublicCoordinate(key.x),\n );\n return matches.length === 1 ? matches[0]! : null;\n}\n\nfunction hasArtifact(\n bundle: DecisionDossierProofBundle,\n artifactKind: ProofArtifactKind,\n documentPath: string,\n): boolean {\n return bundle.artifacts.some(\n (artifact) =>\n artifact.artifact_kind === artifactKind && artifact.document_path === documentPath,\n );\n}\n\n/**\n * A valid signature over the artifacts named by a mutable manifest is not, by\n * itself, proof that every security-critical document was named. Enforce the\n * version-aware completeness rules before reporting the bundle as verified.\n *\n * Historical 2.0/2.1 bundles retain their original meaning unless a binding is\n * presented or signed Protocol 1.1 claims say that one is required.\n */\nfunction requiredArtifactCoverageCheck(\n bundle: DecisionDossierProofBundle,\n dossierPayload: Record<string, unknown>,\n verifiedArtifactPaths?: ReadonlySet<string>,\n): VerifyCheck {\n const bindingPresented = Object.prototype.hasOwnProperty.call(\n dossierPayload,\n \"execution_binding\",\n );\n const machineReadable = asRecord(asRecord(dossierPayload.portable_artifact).machine_readable);\n const protocol11ClaimsPresent = asString(machineReadable.protocol_version) === \"1.1\";\n const protocol11BindingRequired =\n protocol11ClaimsPresent &&\n (machineReadable.execution_eligible === true ||\n asString(machineReadable.execution_binding_digest) !== null);\n const artifactCovered = (kind: ProofArtifactKind, path: string) =>\n hasArtifact(bundle, kind, path) &&\n (verifiedArtifactPaths === undefined || verifiedArtifactPaths.has(path));\n const portableCovered = artifactCovered(\"portable_artifact\", \"/portable_artifact\");\n const inputsSnapshotPresented = Object.prototype.hasOwnProperty.call(\n dossierPayload,\n \"inputs_snapshot\",\n );\n const inputsSnapshotCovered = artifactCovered(\"inputs_snapshot\", \"/inputs_snapshot\");\n const bindingCovered = bundle.artifacts.some(\n (artifact) =>\n artifact.artifact_kind === \"execution_binding\" &&\n artifact.document_path === \"/execution_binding\" &&\n artifact.canonicalization_profile === \"RFC8785/JCS\" &&\n (verifiedArtifactPaths === undefined || verifiedArtifactPaths.has(\"/execution_binding\")),\n );\n const authorityValidation = validateProtocol11DossierAuthorityCommitments({\n dossier_payload: dossierPayload,\n portable_artifact_covered: portableCovered,\n inputs_snapshot_covered: inputsSnapshotPresented && inputsSnapshotCovered,\n execution_binding_covered: bindingPresented && bindingCovered,\n });\n const protocol11CommitmentsMatch =\n authorityValidation.valid && (!protocol11ClaimsPresent || authorityValidation.protocol11);\n\n const portableRequired = protocol11ClaimsPresent || bindingPresented;\n const verified =\n (!portableRequired || portableCovered) &&\n (!(bindingPresented || protocol11BindingRequired) ||\n (bindingPresented && bundle.version === \"2.1\" && portableCovered && bindingCovered)) &&\n protocol11CommitmentsMatch;\n\n return {\n key: \"proof_bundle:required_artifacts\",\n label: \"Required Proof Artifacts\",\n verified,\n severity: verified ? \"pass\" : \"fail\",\n detail: verified\n ? \"Proof-bundle version and artifact coverage match the presented authority documents.\"\n : \"An execution binding or Protocol 1.1 authority claim was not covered by the required proof-bundle artifact and version.\",\n };\n}\n\nfunction isSha256Digest(value: unknown): value is string {\n return typeof value === \"string\" && /^sha256:[0-9a-f]{64}$/.test(value);\n}\n\nfunction safeJcsDigest(value: unknown): string | null {\n try {\n return `sha256:${createHash(\"sha256\").update(jcsCanonicalize(value), \"utf8\").digest(\"hex\")}`;\n } catch {\n return null;\n }\n}\n\n/**\n * Validate and normalize a persisted proof bundle. The manifest routes unsigned\n * metadata to signed documents and verification keys, so ambiguous/defaulted\n * paths, media, profiles, rotation metadata, and duplicate kinds fail closed.\n * This mirrors the Protocol and API parsers exactly.\n */\nexport function parseProofBundle(value: unknown): DecisionDossierProofBundle | null {\n const record = nullableRecord(value);\n if (!record) return null;\n const version = record.version;\n const keyId = boundedKeyId(record.key_id);\n if (\n record.bundle_type !== \"decionis.decision_dossier.proof_bundle\" ||\n (version !== \"2.0\" && version !== \"2.1\") ||\n record.algorithm !== \"Ed25519\" ||\n !validDateTime(record.issued_at) ||\n !keyId\n ) {\n return null;\n }\n\n const rotationPolicyRecord = nullableRecord(record.rotation_policy);\n if (\n !rotationPolicyRecord ||\n rotationPolicyRecord.strategy !== \"JWKS_OVERLAP\" ||\n boundedKeyId(rotationPolicyRecord.active_key_id) !== keyId ||\n rotationPolicyRecord.public_jwks_path !== DECISION_DOSSIER_JWKS_PATH ||\n !Array.isArray(rotationPolicyRecord.previous_key_ids) ||\n rotationPolicyRecord.previous_key_ids.length > MAX_RETAINED_PROOF_KEYS ||\n !Number.isInteger(rotationPolicyRecord.verification_grace_period_days) ||\n (rotationPolicyRecord.verification_grace_period_days as number) < 1 ||\n (rotationPolicyRecord.verification_grace_period_days as number) > 3650 ||\n !(rotationPolicyRecord.rotated_at === null || validDateTime(rotationPolicyRecord.rotated_at))\n ) {\n return null;\n }\n const previousKeyIds = rotationPolicyRecord.previous_key_ids.map((entry) => boundedKeyId(entry));\n if (\n previousKeyIds.some((entry) => entry === null) ||\n new Set(previousKeyIds).size !== previousKeyIds.length ||\n previousKeyIds.includes(keyId)\n ) {\n return null;\n }\n\n const publicJwksUrl = normalizedPublicJwksUrl(rotationPolicyRecord.public_jwks_url);\n if (publicJwksUrl === null) return null;\n\n const rawArtifacts = Array.isArray(record.artifacts) ? record.artifacts : [];\n if (rawArtifacts.length < 1 || rawArtifacts.length > Object.keys(PROOF_ARTIFACT_SHAPES).length) {\n return null;\n }\n\n const artifacts: ProofArtifact[] = [];\n for (const entry of rawArtifacts) {\n const item = nullableRecord(entry);\n if (!item) return null;\n const artifactKind = boundedString(item.artifact_kind) as ProofArtifactKind | null;\n if (\n !artifactKind ||\n !Object.prototype.hasOwnProperty.call(PROOF_ARTIFACT_SHAPES, artifactKind)\n ) {\n return null;\n }\n const expected = PROOF_ARTIFACT_SHAPES[artifactKind];\n const hasProfile = Object.prototype.hasOwnProperty.call(item, \"canonicalization_profile\");\n const profile = hasProfile ? boundedString(item.canonicalization_profile) : undefined;\n if (\n item.document_path !== expected.document_path ||\n item.media_type !== expected.media_type ||\n typeof item.canonical_document_sha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/.test(item.canonical_document_sha256) ||\n !validEd25519Signature(item.signature) ||\n (hasProfile && profile !== \"RFC8785/JCS\" && profile !== \"DECIONIS_SORTED_JSON_V1\") ||\n (artifactKind === \"execution_binding\" && profile !== \"RFC8785/JCS\") ||\n (artifactKind === \"execution_binding\" && version !== \"2.1\")\n ) {\n return null;\n }\n const canonicalizationProfile = profile as ProofArtifact[\"canonicalization_profile\"];\n artifacts.push({\n artifact_kind: artifactKind,\n media_type: expected.media_type,\n document_path: expected.document_path,\n canonical_document_sha256: item.canonical_document_sha256,\n ...(canonicalizationProfile ? { canonicalization_profile: canonicalizationProfile } : {}),\n signature: item.signature,\n });\n }\n if (\n new Set(artifacts.map((artifact) => artifact.document_path)).size !== artifacts.length ||\n new Set(artifacts.map((artifact) => artifact.artifact_kind)).size !== artifacts.length\n ) {\n return null;\n }\n\n return {\n bundle_type: \"decionis.decision_dossier.proof_bundle\",\n version,\n issued_at: record.issued_at,\n algorithm: \"Ed25519\",\n key_id: keyId,\n rotation_policy: {\n strategy: \"JWKS_OVERLAP\",\n active_key_id: keyId,\n previous_key_ids: previousKeyIds as string[],\n verification_grace_period_days: rotationPolicyRecord.verification_grace_period_days as number,\n rotated_at: rotationPolicyRecord.rotated_at as string | null,\n public_jwks_path: DECISION_DOSSIER_JWKS_PATH,\n ...(publicJwksUrl ? { public_jwks_url: publicJwksUrl } : {}),\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?: unknown;\n}): VerifyResult {\n const integrity = asRecord(input.dossier_payload.integrity);\n const presentedProofBundle = integrity.proof_bundle;\n const proofBundlePresented = presentedProofBundle !== undefined && presentedProofBundle !== null;\n const bundle = parseProofBundle(presentedProofBundle);\n if (!bundle) {\n return {\n verified: false,\n available: proofBundlePresented,\n key_id: null,\n artifacts_checked: 0,\n required_artifact_coverage_verified: false,\n checks: [\n {\n key: \"proof_bundle\",\n label: \"Proof Bundle\",\n verified: false,\n severity: proofBundlePresented ? \"fail\" : \"warn\",\n detail: proofBundlePresented\n ? \"A proof bundle was presented but its version, manifest, or cryptographic profile is malformed or unsupported.\"\n : \"No persisted Ed25519 proof bundle was available for verification.\",\n },\n ],\n };\n }\n\n const publicJwks = validatePublicJwks(input.public_jwks);\n if (!publicJwks.valid) {\n return {\n verified: false,\n available: true,\n key_id: bundle.key_id,\n artifacts_checked: 0,\n required_artifact_coverage_verified: false,\n checks: [\n {\n key: \"public_jwks\",\n label: \"Public JWKS\",\n verified: false,\n severity: \"fail\",\n detail: publicJwks.detail,\n },\n ],\n };\n }\n\n const jwk = findJwk(publicJwks.jwks, bundle.key_id);\n if (!jwk) {\n return {\n verified: false,\n available: true,\n key_id: bundle.key_id,\n artifacts_checked: 0,\n required_artifact_coverage_verified: false,\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 required_artifact_coverage_verified: false,\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 const verifiedArtifactPaths: string[] = [];\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 let canonicalDocument: string;\n try {\n canonicalDocument =\n artifact.canonicalization_profile === \"RFC8785/JCS\"\n ? jcsCanonicalize(document)\n : stableJsonStringify(document);\n } catch {\n checks.push(\n {\n key: `${artifact.artifact_kind}:sha256`,\n label: `${artifact.artifact_kind} SHA-256`,\n verified: false,\n severity: \"fail\",\n detail: `Signed document path ${artifact.document_path} is not valid for ${artifact.canonicalization_profile} canonicalization.`,\n },\n {\n key: `${artifact.artifact_kind}:signature`,\n label: `${artifact.artifact_kind} Signature`,\n verified: false,\n severity: \"fail\",\n detail:\n \"The document could not be canonicalized, so its Ed25519 signature was not verified.\",\n },\n );\n artifactsChecked += 1;\n continue;\n }\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 if (hashVerified && signatureVerified) {\n verifiedArtifactPaths.push(artifact.document_path);\n }\n artifactsChecked += 1;\n }\n\n const requiredCoverage = requiredArtifactCoverageCheck(\n bundle,\n input.dossier_payload,\n new Set(verifiedArtifactPaths),\n );\n checks.splice(1, 0, requiredCoverage);\n\n return {\n // Preserve the protocol distinction: signature validity is historical;\n // required authority coverage determines present execution eligibility.\n verified: checks\n .filter((check) => check.key !== \"proof_bundle:required_artifacts\")\n .every((check) => check.verified),\n available: true,\n key_id: bundle.key_id,\n artifacts_checked: artifactsChecked,\n proof_bundle_version: bundle.version,\n verified_artifact_paths: verifiedArtifactPaths,\n required_artifact_coverage_verified: requiredCoverage.verified,\n checks,\n };\n}\n\n/**\n * The artifact kinds whose signature check passed, derived from a verify\n * result. Kept as a derivation rather than a new field on `VerifyResult` so\n * already-installed copies of this package keep the same contract shape.\n */\nexport function verifiedArtifactKinds(result: VerifyResult): Set<string> {\n const kinds = new Set<string>();\n for (const check of result.checks) {\n const [kind, aspect] = check.key.split(\":\");\n if (aspect === \"signature\" && check.verified && kind) kinds.add(kind);\n }\n return kinds;\n}\n\n/**\n * Who minted this dossier — the half of verification that a signature alone\n * does not answer.\n *\n * A verified Ed25519 signature proves the record was not altered. It says\n * nothing about whether the workspace behind it was ever attached to a human.\n * Decionis mints anonymous provisional workspaces with no signup, so without\n * this a dossier produced by a stranger in an unclaimed workspace verifies\n * identically to one from an owned account — which turns \"here is a signed\n * Decionis dossier\" into a claim anyone can manufacture.\n *\n * The tier lives inside `portable_artifact`, which IS a signed artifact, so\n * when that artifact's signature verified, the tier is a signed fact rather\n * than an assertion the caller can edit. `signature_covered` reports exactly\n * that distinction, and it is the field a caller should branch on.\n */\nexport type IssuerTier = \"provisional_anonymous\" | \"owned\";\n\nexport interface IssuerAssessment {\n /** Null when the dossier carries no issuer context (records predating it). */\n tier: IssuerTier | null;\n /** A tier value we do not recognise, surfaced rather than swallowed. */\n unknown_tier: string | null;\n /** True only when the tier was read from an artifact whose signature verified. */\n signature_covered: boolean;\n /** True when the issuing workspace was never attached to a human owner. */\n provisional: boolean;\n label: string;\n detail: string;\n}\n\n/**\n * Read the issuer watermark from a dossier payload.\n *\n * `verified_artifact_paths` is the set of exact JSON Pointer paths whose\n * signature checks passed in a prior `verifyDossierProofBundle` run. Artifact\n * kind labels and flat projections are mutable metadata and never confer\n * coverage.\n */\nexport function assessDossierIssuer(\n dossier_payload: Record<string, unknown>,\n verified_artifact_paths: ReadonlySet<string> = new Set(),\n): IssuerAssessment {\n const payload = asRecord(dossier_payload);\n // The signed nested claim always wins. A public flat projection can still be\n // displayed when no nested claim exists, but it is necessarily unproven.\n const machineReadable = asRecord(asRecord(payload.portable_artifact).machine_readable);\n const nestedIssuerPresent = isNonEmptyObject(machineReadable.issuer_context);\n const rawIssuer = nestedIssuerPresent\n ? asRecord(machineReadable.issuer_context)\n : asRecord(payload.issuer_context);\n const rawTier = asString(rawIssuer.tier);\n\n const signatureCovered = nestedIssuerPresent && verified_artifact_paths.has(\"/portable_artifact\");\n\n if (rawTier == null) {\n return {\n tier: null,\n unknown_tier: null,\n signature_covered: false,\n provisional: false,\n label: \"Issuer not stated\",\n detail:\n \"This dossier carries no issuer context, so the workspace that minted it cannot be \" +\n \"established from the record alone.\",\n };\n }\n\n if (rawTier !== \"provisional_anonymous\" && rawTier !== \"owned\") {\n return {\n tier: null,\n unknown_tier: rawTier,\n signature_covered: signatureCovered,\n provisional: false,\n label: `Unrecognised issuer tier \"${rawTier}\"`,\n detail:\n `The dossier states an issuer tier this verifier does not recognise (\"${rawTier}\"). ` +\n \"Treat the origin of this record as unestablished.\",\n };\n }\n\n const provisional = rawTier === \"provisional_anonymous\";\n return {\n tier: rawTier,\n unknown_tier: null,\n signature_covered: signatureCovered,\n provisional,\n label: provisional ? \"Claimed provisional anonymous workspace\" : \"Claimed owned workspace\",\n detail: provisional\n ? \"The signed portable artifact states that the workspace was created without signup and never claimed by a human owner.\"\n : \"The signed portable artifact states that the workspace has a human owner attached.\",\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 * an authorized verifier with the committed policy/evaluator artifacts can re-run\n * the exact recorded inputs and get the same verdict. That recompute needs the\n * retained deterministic engine artifacts, so it is not offline — but whether a\n * dossier carries signed replay commitments is offline-checkable.\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. Protocol 1.1 requires\n * proof-covered policy-reference, evaluator-semantics, outcome, policy hashes,\n * evaluation-time, and canonical-input commitments. This mirrors the field reads\n * in `apps/protocol/src/reproduce/ReproduceDecision.ts`. It is a coverage check —\n * it never claims that a replay was performed or that retained artifacts are\n * publicly obtainable.\n */\nexport function assessDossierReproducibility(\n dossier_payload: Record<string, unknown>,\n verified_artifact_paths: ReadonlySet<string> = new Set(),\n): ReproducibilityAssessment {\n const payload = asRecord(dossier_payload);\n const machineReadable = asRecord(asRecord(payload.portable_artifact).machine_readable);\n const protocolVersionDeclared = Object.prototype.hasOwnProperty.call(\n machineReadable,\n \"protocol_version\",\n );\n const declaredProtocolVersion = machineReadable.protocol_version;\n const protocolEnvelope = classifyAuthorityProtocolEnvelope(machineReadable);\n const protocol11 = protocolEnvelope === \"PROTOCOL_1_1\";\n const protocolVersionSupported = protocol11 || protocolEnvelope === \"LEGACY\";\n const protocolVersionDisplay = !protocolVersionDeclared\n ? null\n : typeof declaredProtocolVersion === \"string\"\n ? declaredProtocolVersion.trim().length > 0\n ? declaredProtocolVersion.slice(0, 128)\n : \"<blank>\"\n : declaredProtocolVersion === null\n ? \"<null>\"\n : `<${typeof declaredProtocolVersion}>`;\n const policySnapshot = asRecord(machineReadable.policy_snapshot);\n const routing = asRecord(payload.routing_decision);\n const projectedPolicySnapshot = isNonEmptyObject(routing.policy_snapshot)\n ? asRecord(routing.policy_snapshot)\n : asRecord(asRecord(payload.governance).policy_snapshot);\n\n const recordedOutcome = asString(machineReadable.outcome);\n const policyVersion = asString(machineReadable.policy_version);\n const rulesSha = asString(policySnapshot.rules_sha256);\n const parametersSha = asString(policySnapshot.parameters_sha256);\n const evaluatedAt =\n asString(policySnapshot.evaluated_at) ?? asString(machineReadable.generated_at);\n const inputsPresent = isNonEmptyObject(payload.inputs_snapshot);\n const portableCovered = verified_artifact_paths.has(\"/portable_artifact\");\n const inputsCovered = verified_artifact_paths.has(\"/inputs_snapshot\");\n const projectionConsistent =\n !!recordedOutcome &&\n recordedOutcome === asString(routing.outcome) &&\n !!policyVersion &&\n policyVersion ===\n (asString(projectedPolicySnapshot.policy_version) ?? asString(routing.policy_version)) &&\n isNonEmptyObject(policySnapshot) &&\n stableJsonStringify(policySnapshot) === stableJsonStringify(projectedPolicySnapshot);\n const committedInputDigest = asString(machineReadable.input_snapshot_digest);\n const inputCommitmentMatches =\n protocol11 &&\n committedInputDigest !== null &&\n safeJcsDigest(payload.inputs_snapshot) === committedInputDigest;\n const policyReference = asRecord(machineReadable.policy_reference);\n const policyReferenceDigest = safeJcsDigest({\n identifier: asString(policySnapshot.policy_bundle_id),\n version: asString(policySnapshot.policy_version),\n rules_sha256: rulesSha,\n parameters_sha256: parametersSha,\n });\n const policyReferenceValid =\n protocol11 &&\n !!asString(policyReference.policy_id) &&\n asString(policyReference.revision_id) === asString(policySnapshot.policy_bundle_id) &&\n asString(policyReference.version) === policyVersion &&\n isSha256Digest(policyReference.digest) &&\n policyReference.digest === policyReferenceDigest;\n const semantics = asRecord(machineReadable.evaluation_semantics);\n const evaluationSemanticsSupported =\n protocol11 &&\n semantics.protocol_version === \"1.1\" &&\n semantics.evaluator_version === \"policy-graph/1.1\" &&\n semantics.policy_schema_version === \"1.0\" &&\n semantics.canonicalization === \"RFC8785/JCS\" &&\n semantics.digest_algorithm === \"SHA-256\" &&\n semantics.signal_normalization_version === \"external-signal-envelope/1.0\";\n const snapshot = asRecord(payload.inputs_snapshot);\n const requiredSnapshotKeys = [\n \"decision_type\",\n \"amount\",\n \"risk_score\",\n \"channel\",\n \"source\",\n \"policy_version\",\n \"objective_profile\",\n \"vertical_pack\",\n \"workflow_key\",\n \"mode\",\n \"decision_band\",\n \"transaction_type\",\n ];\n const embeddedContextPresent =\n snapshot.context !== null &&\n typeof snapshot.context === \"object\" &&\n !Array.isArray(snapshot.context);\n const contextCommitment = asRecord(snapshot.context_commitment);\n const contextReference = asRecord(contextCommitment.artifact_reference);\n const authorizedContextReferenceValid =\n contextCommitment.version === \"1.0\" &&\n contextCommitment.canonicalization === \"RFC8785/JCS\" &&\n isSha256Digest(contextCommitment.digest) &&\n contextReference.kind === \"DECISION_EVALUATION_REQUEST\" &&\n asString(contextReference.evaluation_id) === asString(machineReadable.evaluation_id) &&\n contextReference.document_path === \"/request_payload/context\" &&\n contextReference.access === \"AUTHORIZED\";\n // Early Protocol 1.1 artifacts embedded raw context. New artifacts keep it\n // in the access-controlled immutable evaluation and sign this exact\n // reference instead. Both are replayable under their original semantics.\n const contextReplayInputReady = embeddedContextPresent || authorizedContextReferenceValid;\n const canonicalInputComplete =\n protocol11 &&\n contextReplayInputReady &&\n requiredSnapshotKeys.every((key) => Object.prototype.hasOwnProperty.call(snapshot, key));\n\n const inputs: ReproducibilityInput[] = [\n ...(protocolVersionDeclared || protocolEnvelope === \"PARTIAL_PROTOCOL_1_1\"\n ? [\n {\n key: \"protocol_version\",\n label: \"Supported complete protocol envelope\",\n present: protocolVersionSupported,\n value: protocolVersionDisplay,\n },\n ]\n : []),\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 {\n key: \"rules_sha256\",\n label: \"Recorded rules hash\",\n present: /^[0-9a-f]{64}$/.test(rulesSha ?? \"\"),\n value: rulesSha,\n },\n {\n key: \"parameters_sha256\",\n label: \"Recorded parameters hash\",\n present: /^[0-9a-f]{64}$/.test(parametersSha ?? \"\"),\n value: parametersSha,\n },\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 key: \"portable_artifact_signature\",\n label: \"Signed portable artifact\",\n present: portableCovered,\n value: portableCovered ? \"/portable_artifact\" : null,\n },\n {\n key: \"inputs_snapshot_signature\",\n label: \"Signed inputs snapshot\",\n present: inputsCovered,\n value: inputsCovered ? \"/inputs_snapshot\" : null,\n },\n {\n key: \"signed_projection_consistency\",\n label: \"Signed decision projection consistency\",\n present: projectionConsistent,\n value: null,\n },\n {\n key: \"input_snapshot_commitment\",\n label: \"Input snapshot commitment\",\n present: protocol11 ? inputCommitmentMatches : inputsCovered,\n value: committedInputDigest,\n },\n ...(protocol11\n ? [\n {\n key: \"immutable_policy_reference\",\n label: \"Immutable policy reference\",\n present: policyReferenceValid,\n value: asString(policyReference.revision_id),\n },\n {\n key: \"evaluation_semantics\",\n label: \"Supported evaluation semantics\",\n present: evaluationSemanticsSupported,\n value: asString(semantics.evaluator_version),\n },\n {\n key: \"canonical_input_shape\",\n label: \"Complete canonical evaluator input\",\n present: canonicalInputComplete,\n value: null,\n },\n {\n key: \"context_replay_input\",\n label: \"Embedded context or authorized immutable context reference\",\n present: contextReplayInputReady,\n value: authorizedContextReferenceValid\n ? asString(contextReference.evaluation_id)\n : embeddedContextPresent\n ? \"embedded\"\n : null,\n },\n ]\n : []),\n ];\n\n const presentCount = inputs.filter((input) => input.present).length;\n let posture: ReproducibilityPosture;\n let detail: string;\n const carriesReproductionMetadata =\n protocolVersionDeclared ||\n !!recordedOutcome ||\n !!policyVersion ||\n !!rulesSha ||\n !!evaluatedAt ||\n inputsPresent;\n if (!protocolVersionSupported) {\n posture = \"incomplete\";\n detail =\n protocolEnvelope === \"PARTIAL_PROTOCOL_1_1\"\n ? \"Partial Protocol 1.1 commitments were signed without the exact 1.1 version marker. Reproduction would return indeterminate.\"\n : `Unsupported or malformed protocol version declaration (${protocolVersionDisplay ?? \"unknown\"}). Reproduction would return indeterminate.`;\n } else if (protocol11 && presentCount === inputs.length) {\n posture = \"reproduction_ready\";\n detail =\n \"Carries signed, mutually consistent policy, outcome, evaluation-time, and input artifacts — an authorized verifier with the retained evaluator and policy can re-run this decision.\";\n } else if (!carriesReproductionMetadata) {\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 if (!protocol11) {\n posture = \"incomplete\";\n detail =\n \"Historical Protocol 1.0 metadata does not carry the complete signed Protocol 1.1 reproduction prerequisites. Its signature may remain valid under its original rules.\";\n } else {\n posture = \"incomplete\";\n const missing = inputs.filter((input) => !input.present).map((input) => input.label);\n detail = `Missing or unverified reproduction prerequisites: ${missing.join(\", \")}. Reproduction would return indeterminate.`;\n }\n\n return { posture, detail, inputs };\n}\n","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst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){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { z } from \"zod\";\nimport {\n JCS_CANONICALIZATION_PROFILE,\n canonicalPayloadDigest,\n ExecutionBindingSchema,\n type ExecutionBinding,\n executionBindingDigest,\n jcsCanonicalize,\n} from \"./ExecutionBinding\";\n\nexport const DECIONIS_PROTOCOL_AUTHORITY_VERSION = \"1.1\" as const;\nexport const DECIONIS_EVALUATOR_VERSION = \"policy-graph/1.1\" as const;\nexport const DECIONIS_POLICY_SCHEMA_VERSION = \"1.0\" as const;\nexport const DECIONIS_SIGNAL_NORMALIZATION_VERSION = \"external-signal-envelope/1.0\" as const;\n\n/**\n * Fields whose signed meaning was introduced by Protocol 1.1. Their presence\n * without an exact 1.1 version marker is not a historical 1.0 artifact: it is\n * an incomplete or downgraded 1.1 authority envelope and must fail closed.\n * ExecutionBinding is deliberately absent from this list because deployed\n * Protocol 1.0 artifacts already carried it.\n */\nexport const PROTOCOL_11_AUTHORITY_COMMITMENT_FIELDS = [\n \"verdict\",\n \"authority_classification\",\n \"execution_eligible\",\n \"policy_reference\",\n \"evaluation_semantics\",\n \"input_snapshot_digest\",\n \"execution_binding_digest\",\n] as const;\n\nexport type AuthorityProtocolEnvelopeClassification =\n | \"PROTOCOL_1_1\"\n | \"LEGACY\"\n | \"PARTIAL_PROTOCOL_1_1\"\n | \"UNSUPPORTED\";\n\n/**\n * Version-dispatch an untrusted authority envelope without silently treating\n * forward or partial semantics as Protocol 1.0.\n */\nexport function classifyAuthorityProtocolEnvelope(\n envelope: Record<string, unknown>,\n): AuthorityProtocolEnvelopeClassification {\n const version = envelope.protocol_version;\n if (version === DECIONIS_PROTOCOL_AUTHORITY_VERSION) return \"PROTOCOL_1_1\";\n\n const legacyVersion = version === undefined || version === \"1.0\" || version === \"1.0.0\";\n if (!legacyVersion) return \"UNSUPPORTED\";\n\n return PROTOCOL_11_AUTHORITY_COMMITMENT_FIELDS.some((field) =>\n Object.prototype.hasOwnProperty.call(envelope, field),\n )\n ? \"PARTIAL_PROTOCOL_1_1\"\n : \"LEGACY\";\n}\n\nexport const AuthorityClassificationSchema = z.enum([\"AUTHORITATIVE\", \"OBSERVATIONAL\"]);\nexport const EvaluationModeSchema = z.enum([\"SHADOW\", \"PARALLEL\", \"ENFORCEMENT\"]);\nexport const AuthorityVerdictSchema = z.enum([\"ALLOW\", \"ESCALATE\", \"BLOCK\"]);\n\nconst sha256DigestSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/);\nconst boundedIdentifier = z.string().trim().min(1).max(500);\n\n/** Immutable identity and digest of the exact policy revision used by an evaluation. */\nexport const PolicyReferenceSchema = z\n .object({\n policy_id: boundedIdentifier,\n revision_id: boundedIdentifier,\n version: boundedIdentifier,\n digest: sha256DigestSchema,\n })\n .strict();\n\n/** Maintained evaluator commitments required to interpret a Protocol 1.1 decision. */\nexport const EvaluationSemanticsSchema = z\n .object({\n protocol_version: z.literal(DECIONIS_PROTOCOL_AUTHORITY_VERSION),\n evaluator_version: boundedIdentifier,\n policy_schema_version: boundedIdentifier,\n canonicalization: z.literal(JCS_CANONICALIZATION_PROFILE),\n digest_algorithm: z.literal(\"SHA-256\"),\n signal_normalization_version: boundedIdentifier,\n })\n .strict();\n\n/**\n * Signed authority interpretation for a decision. A decision describes\n * authority; ExecutionBinding grants use of it for one exact action.\n */\nexport const AuthorityEvidenceSchema = z\n .object({\n protocol_version: z.literal(DECIONIS_PROTOCOL_AUTHORITY_VERSION),\n evaluation_id: boundedIdentifier,\n dossier_id: boundedIdentifier,\n evaluation_mode: EvaluationModeSchema,\n authority_classification: AuthorityClassificationSchema,\n verdict: AuthorityVerdictSchema,\n execution_eligible: z.boolean(),\n policy_reference: PolicyReferenceSchema,\n evaluation_semantics: EvaluationSemanticsSchema,\n input_snapshot_digest: sha256DigestSchema,\n execution_binding_digest: sha256DigestSchema.nullable(),\n })\n .strict()\n .superRefine((value, context) => {\n const expectedClassification = authorityClassificationForMode(value.evaluation_mode);\n if (value.authority_classification !== expectedClassification) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"authority_classification\"],\n message: `${value.evaluation_mode} evaluations must be ${expectedClassification}`,\n });\n }\n if (\n value.execution_eligible &&\n (value.authority_classification !== \"AUTHORITATIVE\" ||\n value.verdict !== \"ALLOW\" ||\n value.execution_binding_digest === null)\n ) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"execution_eligible\"],\n message: \"Execution eligibility requires an authoritative ALLOW and ExecutionBinding\",\n });\n }\n if (\n value.authority_classification === \"OBSERVATIONAL\" &&\n value.execution_binding_digest !== null\n ) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"execution_binding_digest\"],\n message: \"Observational evaluations cannot carry an ExecutionBinding commitment\",\n });\n }\n if (!value.execution_eligible && value.execution_binding_digest !== null) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"execution_binding_digest\"],\n message: \"A binding commitment requires explicit execution eligibility\",\n });\n }\n });\n\nexport type AuthorityClassification = z.infer<typeof AuthorityClassificationSchema>;\nexport type EvaluationMode = z.infer<typeof EvaluationModeSchema>;\nexport type AuthorityVerdict = z.infer<typeof AuthorityVerdictSchema>;\nexport type PolicyReference = z.infer<typeof PolicyReferenceSchema>;\nexport type EvaluationSemantics = z.infer<typeof EvaluationSemanticsSchema>;\nexport type AuthorityEvidence = z.infer<typeof AuthorityEvidenceSchema>;\n\nexport type Protocol11AuthorityCommitmentFailure =\n | \"UNSUPPORTED_PROTOCOL_VERSION\"\n | \"OBSERVATIONAL_DOSSIER_NOT_EXECUTABLE\"\n | \"SIGNED_ARTIFACT_COVERAGE_INCOMPLETE\"\n | \"EVALUATION_ID_UNBOUND\"\n | \"AUTHORITY_SCHEMA_INVALID\"\n | \"INPUT_SNAPSHOT_DIGEST_MISMATCH\"\n | \"AUTHORITY_PROJECTION_MISMATCH\"\n | \"EXECUTION_BINDING_MISMATCH\";\n\nexport type Protocol11AuthorityCommitmentValidation =\n | { protocol11: false; valid: true; evidence: null; execution_binding: null; failure: null }\n | {\n protocol11: false;\n valid: false;\n evidence: null;\n execution_binding: null;\n failure: \"UNSUPPORTED_PROTOCOL_VERSION\" | \"OBSERVATIONAL_DOSSIER_NOT_EXECUTABLE\";\n }\n | {\n protocol11: true;\n valid: true;\n evidence: AuthorityEvidence;\n execution_binding: ExecutionBinding | null;\n failure: null;\n }\n | {\n protocol11: true;\n valid: false;\n evidence: null;\n execution_binding: null;\n failure: Protocol11AuthorityCommitmentFailure;\n };\n\n/**\n * Validate Protocol 1.1 authority claims only from exact proof-covered dossier\n * paths. This is the shared semantic gate used by the API claim boundary and\n * Decision Chain projection; mutable top-level conveniences never create\n * signed authority.\n */\nexport function validateProtocol11DossierAuthorityCommitments(input: {\n dossier_payload: Record<string, unknown>;\n portable_artifact_covered: boolean;\n inputs_snapshot_covered: boolean;\n execution_binding_covered: boolean;\n}): Protocol11AuthorityCommitmentValidation {\n const portable = recordValue(input.dossier_payload.portable_artifact);\n const machine = recordValue(portable.machine_readable);\n const protocolEnvelope = classifyAuthorityProtocolEnvelope(machine);\n if (protocolEnvelope !== \"PROTOCOL_1_1\") {\n // A proof-covered observational mode/classification has a more specific\n // failure than a generic partial-envelope error. It still never reaches\n // the historical compatibility path.\n const signedModeIsNonAuthoritative =\n Object.prototype.hasOwnProperty.call(machine, \"mode\") && machine.mode !== \"ENFORCEMENT\";\n const signedClassificationIsNonAuthoritative =\n Object.prototype.hasOwnProperty.call(machine, \"authority_classification\") &&\n machine.authority_classification !== \"AUTHORITATIVE\";\n if (\n input.portable_artifact_covered &&\n (signedModeIsNonAuthoritative || signedClassificationIsNonAuthoritative)\n ) {\n return {\n protocol11: false,\n valid: false,\n evidence: null,\n execution_binding: null,\n failure: \"OBSERVATIONAL_DOSSIER_NOT_EXECUTABLE\",\n };\n }\n // Historical Dossiers either omitted this signed field or used the two\n // deployed 1.0 spellings and carried none of the 1.1-only commitments. A\n // partial or explicitly unknown envelope is not legacy: treating it as\n // 1.0 would be a downgrade at claim time.\n if (protocolEnvelope !== \"LEGACY\") {\n return {\n protocol11: false,\n valid: false,\n evidence: null,\n execution_binding: null,\n failure: \"UNSUPPORTED_PROTOCOL_VERSION\",\n };\n }\n return {\n protocol11: false,\n valid: true,\n evidence: null,\n execution_binding: null,\n failure: null,\n };\n }\n if (!input.portable_artifact_covered || !input.inputs_snapshot_covered) {\n return invalidProtocol11(\"SIGNED_ARTIFACT_COVERAGE_INCOMPLETE\");\n }\n\n const bindingPresented = Object.prototype.hasOwnProperty.call(\n input.dossier_payload,\n \"execution_binding\",\n );\n const parsedBinding = bindingPresented\n ? ExecutionBindingSchema.safeParse(input.dossier_payload.execution_binding)\n : null;\n if (bindingPresented && (!input.execution_binding_covered || !parsedBinding?.success)) {\n return invalidProtocol11(\"EXECUTION_BINDING_MISMATCH\");\n }\n const binding = parsedBinding?.success ? parsedBinding.data : null;\n const signedEvaluationId = stringValue(machine.evaluation_id);\n const evaluationId = signedEvaluationId ?? binding?.evaluation_id ?? null;\n if (\n !evaluationId ||\n (signedEvaluationId !== null &&\n binding !== null &&\n signedEvaluationId !== binding.evaluation_id)\n ) {\n return invalidProtocol11(\"EVALUATION_ID_UNBOUND\");\n }\n\n const parsedAuthority = AuthorityEvidenceSchema.safeParse({\n protocol_version: machine.protocol_version,\n evaluation_id: evaluationId,\n dossier_id: machine.dossier_id,\n evaluation_mode: machine.mode,\n authority_classification: machine.authority_classification,\n verdict: machine.verdict,\n execution_eligible: machine.execution_eligible,\n policy_reference: machine.policy_reference,\n evaluation_semantics: machine.evaluation_semantics,\n input_snapshot_digest: machine.input_snapshot_digest,\n execution_binding_digest: machine.execution_binding_digest,\n });\n if (!parsedAuthority.success) return invalidProtocol11(\"AUTHORITY_SCHEMA_INVALID\");\n const authority = parsedAuthority.data;\n let snapshotDigest: string | null = null;\n try {\n snapshotDigest = canonicalPayloadDigest(input.dossier_payload.inputs_snapshot);\n } catch {\n snapshotDigest = null;\n }\n if (snapshotDigest !== authority.input_snapshot_digest) {\n return invalidProtocol11(\"INPUT_SNAPSHOT_DIGEST_MISMATCH\");\n }\n\n const topDossierId = stringValue(input.dossier_payload.dossier_id);\n const topEvaluationId = stringValue(input.dossier_payload.evaluation_id);\n const routingEvaluationId = stringValue(\n recordValue(input.dossier_payload.routing_decision).evaluation_id,\n );\n if (\n (topDossierId !== null && topDossierId !== authority.dossier_id) ||\n (topEvaluationId !== null && topEvaluationId !== authority.evaluation_id) ||\n (routingEvaluationId !== null && routingEvaluationId !== authority.evaluation_id)\n ) {\n return invalidProtocol11(\"AUTHORITY_PROJECTION_MISMATCH\");\n }\n if (input.dossier_payload.authority_evidence !== undefined) {\n const projection = AuthorityEvidenceSchema.safeParse(input.dossier_payload.authority_evidence);\n if (!projection.success || jcsCanonicalize(projection.data) !== jcsCanonicalize(authority)) {\n return invalidProtocol11(\"AUTHORITY_PROJECTION_MISMATCH\");\n }\n }\n\n if (binding) {\n if (\n authority.execution_binding_digest !== executionBindingDigest(binding) ||\n authority.dossier_id !== binding.dossier_id ||\n authority.evaluation_id !== binding.evaluation_id ||\n authority.policy_reference.revision_id !== binding.policy.identifier ||\n authority.policy_reference.version !== binding.policy.version ||\n authority.policy_reference.digest !== binding.policy.digest\n ) {\n return invalidProtocol11(\"EXECUTION_BINDING_MISMATCH\");\n }\n } else if (authority.execution_binding_digest !== null || authority.execution_eligible) {\n return invalidProtocol11(\"EXECUTION_BINDING_MISMATCH\");\n }\n\n return {\n protocol11: true,\n valid: true,\n evidence: authority,\n execution_binding: binding,\n failure: null,\n };\n}\n\nfunction invalidProtocol11(\n failure: Protocol11AuthorityCommitmentFailure,\n): Protocol11AuthorityCommitmentValidation {\n return {\n protocol11: true,\n valid: false,\n evidence: null,\n execution_binding: null,\n failure,\n };\n}\n\nfunction recordValue(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n}\n\n/** PARALLEL is explicitly observational in the current Decionis implementation. */\nexport function authorityClassificationForMode(mode: EvaluationMode): AuthorityClassification {\n return mode === \"ENFORCEMENT\" ? \"AUTHORITATIVE\" : \"OBSERVATIONAL\";\n}\n\nexport function authorityVerdictForOutcome(outcome: string): AuthorityVerdict {\n if (outcome === \"APPROVE\" || outcome === \"ALLOW\") return \"ALLOW\";\n if (outcome === \"REJECT\" || outcome === \"BLOCK\") return \"BLOCK\";\n return \"ESCALATE\";\n}\n\nexport function currentEvaluationSemantics(): EvaluationSemantics {\n return {\n protocol_version: DECIONIS_PROTOCOL_AUTHORITY_VERSION,\n evaluator_version: DECIONIS_EVALUATOR_VERSION,\n policy_schema_version: DECIONIS_POLICY_SCHEMA_VERSION,\n canonicalization: JCS_CANONICALIZATION_PROFILE,\n digest_algorithm: \"SHA-256\",\n signal_normalization_version: DECIONIS_SIGNAL_NORMALIZATION_VERSION,\n };\n}\n\nexport function policyReferenceDigest(revision: unknown): `sha256:${string}` {\n return canonicalPayloadDigest(revision);\n}\n\nexport function buildAuthorityEvidence(input: {\n evaluation_id: string;\n dossier_id: string;\n evaluation_mode: EvaluationMode;\n verdict: AuthorityVerdict;\n policy_reference: PolicyReference;\n evaluation_semantics?: EvaluationSemantics;\n input_snapshot: unknown;\n execution_binding?: ExecutionBinding | null;\n}): AuthorityEvidence {\n const authorityClassification = authorityClassificationForMode(input.evaluation_mode);\n const bindingDigest = input.execution_binding\n ? executionBindingDigest(input.execution_binding)\n : null;\n return AuthorityEvidenceSchema.parse({\n protocol_version: DECIONIS_PROTOCOL_AUTHORITY_VERSION,\n evaluation_id: input.evaluation_id,\n dossier_id: input.dossier_id,\n evaluation_mode: input.evaluation_mode,\n authority_classification: authorityClassification,\n verdict: input.verdict,\n execution_eligible:\n authorityClassification === \"AUTHORITATIVE\" &&\n input.verdict === \"ALLOW\" &&\n bindingDigest !== null,\n policy_reference: input.policy_reference,\n evaluation_semantics: input.evaluation_semantics ?? currentEvaluationSemantics(),\n input_snapshot_digest: canonicalPayloadDigest(input.input_snapshot),\n execution_binding_digest: bindingDigest,\n });\n}\n","import { z } from \"zod\";\n\nexport const EXECUTION_BINDING_SCHEMA_VERSION = \"1.0\" as const;\nexport const EXECUTION_BINDING_DIGEST_ALGORITHM = \"SHA-256\" as const;\nexport const JCS_CANONICALIZATION_PROFILE = \"RFC8785/JCS\" as const;\n\nconst sha256DigestSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/);\nconst boundedIdentifier = z.string().trim().min(1).max(500);\n\nexport const ExecutionTargetSchema = z\n .object({\n system: boundedIdentifier,\n environment: boundedIdentifier,\n operation: boundedIdentifier,\n resource: boundedIdentifier,\n endpoint: boundedIdentifier.nullable(),\n })\n .strict();\n\nexport const ExecutionPolicyBindingSchema = z\n .object({\n identifier: boundedIdentifier,\n version: boundedIdentifier,\n digest: sha256DigestSchema,\n digest_algorithm: z.literal(EXECUTION_BINDING_DIGEST_ALGORITHM),\n })\n .strict();\n\nexport const MaterialSignalReferenceSchema = z\n .object({\n signal_id: boundedIdentifier,\n version: boundedIdentifier,\n observed_at: z.string().datetime(),\n value_digest: sha256DigestSchema.nullable(),\n evidence_digest: sha256DigestSchema.nullable(),\n })\n .strict()\n .refine((value) => value.value_digest !== null || value.evidence_digest !== null, {\n message: \"A material signal requires a value or evidence digest\",\n });\n\nexport const PresenceExecutionApprovalSchema = z\n .object({\n approval_reference: boundedIdentifier,\n receipt_dossier_id: boundedIdentifier,\n approver_identity: boundedIdentifier,\n approver_role: boundedIdentifier,\n approved_action_digest: sha256DigestSchema,\n action_binding_digest: sha256DigestSchema,\n expires_at: z.string().datetime(),\n conditions_digest: sha256DigestSchema,\n /** When the ceremony concluded, when Presence reports it. Optional: bindings signed before this field existed parse unchanged. */\n approved_at: z.string().datetime().optional(),\n /** Ceremony/authenticator evidence — identity of the ceremony, never payload data. */\n authenticator: z\n .object({\n method: boundedIdentifier.nullable().optional(),\n aaguid: boundedIdentifier.nullable().optional(),\n device_platform: boundedIdentifier.nullable().optional(),\n user_verified: z.boolean().nullable().optional(),\n attestation_reference: boundedIdentifier.nullable().optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport const ExecutionBindingSchema = z\n .object({\n binding_schema_version: z.literal(EXECUTION_BINDING_SCHEMA_VERSION),\n dossier_id: boundedIdentifier,\n evaluation_id: boundedIdentifier,\n payload: z\n .object({\n digest: sha256DigestSchema,\n digest_algorithm: z.literal(EXECUTION_BINDING_DIGEST_ALGORITHM),\n canonicalization_profile: boundedIdentifier,\n })\n .strict(),\n /**\n * Optional pre-dispatch commitment to the downstream state that would\n * qualify as a confirmed effect. Absence preserves historical bindings\n * and means finalization can report COMMITTED, but not CONFIRMED through\n * Protocol 1.1 EffectEvidence.\n */\n expected_effect_digest: sha256DigestSchema.optional(),\n execution_target: ExecutionTargetSchema,\n policy: ExecutionPolicyBindingSchema,\n material_signals: z.array(MaterialSignalReferenceSchema).max(100),\n issued_at: z.string().datetime(),\n not_before: z.string().datetime().nullable(),\n expires_at: z.string().datetime(),\n nonce: z.string().regex(/^[A-Za-z0-9_-]{43,128}$/),\n idempotency_key: boundedIdentifier.nullable(),\n execution_correlation_id: boundedIdentifier,\n concurrency_scope_digest: sha256DigestSchema,\n authorization_state_digest: sha256DigestSchema,\n presence_approval: PresenceExecutionApprovalSchema.nullable(),\n })\n .strict()\n .superRefine((binding, context) => {\n const issuedAt = Date.parse(binding.issued_at);\n const notBefore = binding.not_before ? Date.parse(binding.not_before) : issuedAt;\n const expiresAt = Date.parse(binding.expires_at);\n if (notBefore < issuedAt) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"not_before\"],\n message: \"not_before cannot precede issuance\",\n });\n }\n if (expiresAt <= notBefore) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"expires_at\"],\n message: \"expires_at must follow not_before\",\n });\n }\n });\n\nexport type ExecutionTarget = z.infer<typeof ExecutionTargetSchema>;\nexport type ExecutionPolicyBinding = z.infer<typeof ExecutionPolicyBindingSchema>;\nexport type MaterialSignalReference = z.infer<typeof MaterialSignalReferenceSchema>;\nexport type PresenceExecutionApproval = z.infer<typeof PresenceExecutionApprovalSchema>;\nexport type ExecutionBinding = z.infer<typeof ExecutionBindingSchema>;\n\nexport interface PayloadCanonicalizer {\n readonly profile: string;\n canonicalize(payload: unknown): Uint8Array;\n}\n\nexport class PayloadCanonicalizerRegistry {\n private readonly byProfile = new Map<string, PayloadCanonicalizer>();\n\n public constructor(canonicalizers: PayloadCanonicalizer[] = [JsonJcsCanonicalizer]) {\n for (const canonicalizer of canonicalizers) this.register(canonicalizer);\n }\n\n public register(canonicalizer: PayloadCanonicalizer): void {\n if (!canonicalizer.profile.trim()) throw new Error(\"CANONICALIZATION_PROFILE_REQUIRED\");\n this.byProfile.set(canonicalizer.profile, canonicalizer);\n }\n\n public canonicalize(profile: string, payload: unknown): Uint8Array {\n const canonicalizer = this.byProfile.get(profile);\n if (!canonicalizer) throw new Error(\"CANONICALIZATION_PROFILE_UNSUPPORTED\");\n return canonicalizer.canonicalize(payload);\n }\n}\n\nexport const JsonJcsCanonicalizer: PayloadCanonicalizer = {\n profile: JCS_CANONICALIZATION_PROFILE,\n canonicalize(payload: unknown): Uint8Array {\n return new TextEncoder().encode(jcsCanonicalize(payload));\n },\n};\n\n/** RFC 8785 JSON Canonicalization Scheme for I-JSON values. */\nexport function jcsCanonicalize(value: unknown): string {\n return serializeJcs(value);\n}\n\nexport function sha256Digest(bytes: string | Uint8Array): `sha256:${string}` {\n const input = typeof bytes === \"string\" ? new TextEncoder().encode(bytes) : bytes;\n const bitLength = BigInt(input.length) * 8n;\n const paddedLength = Math.ceil((input.length + 9) / 64) * 64;\n const message = new Uint8Array(paddedLength);\n message.set(input);\n message[input.length] = 0x80;\n for (let index = 0; index < 8; index += 1) {\n message[paddedLength - 1 - index] = Number((bitLength >> BigInt(index * 8)) & 0xffn);\n }\n\n const hash = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]);\n const words = new Uint32Array(64);\n const view = new DataView(message.buffer, message.byteOffset, message.byteLength);\n for (let offset = 0; offset < message.length; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n words[index] = view.getUint32(offset + index * 4, false);\n }\n for (let index = 16; index < 64; index += 1) {\n const before15 = words[index - 15]!;\n const before2 = words[index - 2]!;\n const sigma0 = rotateRight(before15, 7) ^ rotateRight(before15, 18) ^ (before15 >>> 3);\n const sigma1 = rotateRight(before2, 17) ^ rotateRight(before2, 19) ^ (before2 >>> 10);\n words[index] = (words[index - 16]! + sigma0 + words[index - 7]! + sigma1) >>> 0;\n }\n\n let [a, b, c, d, e, f, g, h] = hash;\n for (let index = 0; index < 64; index += 1) {\n const sum1 = rotateRight(e!, 6) ^ rotateRight(e!, 11) ^ rotateRight(e!, 25);\n const choice = (e! & f!) ^ (~e! & g!);\n const temporary1 = (h! + sum1 + choice + SHA256_CONSTANTS[index]! + words[index]!) >>> 0;\n const sum0 = rotateRight(a!, 2) ^ rotateRight(a!, 13) ^ rotateRight(a!, 22);\n const majority = (a! & b!) ^ (a! & c!) ^ (b! & c!);\n const temporary2 = (sum0 + majority) >>> 0;\n h = g;\n g = f;\n f = e;\n e = (d! + temporary1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temporary1 + temporary2) >>> 0;\n }\n hash[0] = (hash[0]! + a!) >>> 0;\n hash[1] = (hash[1]! + b!) >>> 0;\n hash[2] = (hash[2]! + c!) >>> 0;\n hash[3] = (hash[3]! + d!) >>> 0;\n hash[4] = (hash[4]! + e!) >>> 0;\n hash[5] = (hash[5]! + f!) >>> 0;\n hash[6] = (hash[6]! + g!) >>> 0;\n hash[7] = (hash[7]! + h!) >>> 0;\n }\n return `sha256:${Array.from(hash, (word) => word.toString(16).padStart(8, \"0\")).join(\"\")}`;\n}\n\nconst SHA256_CONSTANTS = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nfunction rotateRight(value: number, count: number): number {\n return (value >>> count) | (value << (32 - count));\n}\n\nexport function canonicalPayloadDigest(\n payload: unknown,\n profile: string = JCS_CANONICALIZATION_PROFILE,\n registry = new PayloadCanonicalizerRegistry(),\n): `sha256:${string}` {\n return sha256Digest(registry.canonicalize(profile, payload));\n}\n\nexport function executionPolicyDigest(input: {\n identifier: string;\n version: string;\n rules_sha256?: string | null;\n parameters_sha256?: string | null;\n}): `sha256:${string}` {\n return canonicalPayloadDigest({\n identifier: input.identifier,\n version: input.version,\n rules_sha256: input.rules_sha256 ?? null,\n parameters_sha256: input.parameters_sha256 ?? null,\n });\n}\n\nexport function executionTargetDigest(target: ExecutionTarget): `sha256:${string}` {\n return canonicalPayloadDigest(ExecutionTargetSchema.parse(target));\n}\n\nexport function executionActionBindingDigest(input: {\n payload_digest: string;\n execution_target: ExecutionTarget;\n}): `sha256:${string}` {\n return canonicalPayloadDigest({\n payload_digest: input.payload_digest,\n execution_target: ExecutionTargetSchema.parse(input.execution_target),\n });\n}\n\nexport function executionAuthorizationStateDigest(input: {\n policy: ExecutionPolicyBinding;\n material_signals: MaterialSignalReference[];\n presence_conditions_digest?: string | null;\n}): `sha256:${string}` {\n return canonicalPayloadDigest({\n policy: ExecutionPolicyBindingSchema.parse(input.policy),\n material_signals: [...input.material_signals]\n .map((signal) => MaterialSignalReferenceSchema.parse(signal))\n .sort((left, right) => left.signal_id.localeCompare(right.signal_id)),\n presence_conditions_digest: input.presence_conditions_digest ?? null,\n });\n}\n\nexport function executionConcurrencyScopeDigest(input: {\n execution_target: ExecutionTarget;\n material_signal_ids: string[];\n}): `sha256:${string}` {\n return canonicalPayloadDigest({\n concurrency_scope_digests: executionConcurrencyScopeDigests(input),\n });\n}\n\n/** Individually claimable conflict domains derived only from signed binding fields. */\nexport function executionConcurrencyScopeDigests(input: {\n execution_target: ExecutionTarget;\n material_signal_ids: string[];\n}): `sha256:${string}`[] {\n const materialSignalIds = [...new Set(input.material_signal_ids)].sort();\n if (materialSignalIds.length > 0) {\n return materialSignalIds.map((signalId) =>\n canonicalPayloadDigest({ scope_type: \"MATERIAL_SIGNAL\", signal_id: signalId }),\n );\n }\n return [\n canonicalPayloadDigest({\n scope_type: \"TARGET_RESOURCE\",\n execution_target: ExecutionTargetSchema.parse(input.execution_target),\n }),\n ];\n}\n\nexport function executionBindingDigest(binding: ExecutionBinding): `sha256:${string}` {\n return canonicalPayloadDigest(ExecutionBindingSchema.parse(binding));\n}\n\nfunction serializeJcs(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) => serializeJcs(item)).join(\",\")}]`;\n if (!value || typeof value !== \"object\") throw new TypeError(\"JCS_VALUE_NOT_JSON\");\n\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 const item = record[key];\n if (item === undefined) throw new TypeError(\"JCS_UNDEFINED_NOT_ALLOWED\");\n return `${JSON.stringify(key)}:${serializeJcs(item)}`;\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 { lookup } from \"node:dns/promises\";\nimport { request as httpsRequest } from \"node:https\";\nimport { isIP } from \"node:net\";\nimport { Readable } from \"node:stream\";\n\nimport { parseProofBundle, verifyDossierProofBundle, type VerifyResult } from \"./verify.js\";\n\nconst MAX_VERIFICATION_RESPONSE_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_FETCH_TIMEOUT_MS = 10_000;\nconst MAX_REDIRECTS = 3;\nconst OFFICIAL_DECIONIS_JWKS_PATHS = new Set([\n \"/.well-known/decision-dossier-jwks.json\",\n \"/v1/.well-known/decision-dossier-jwks.json\",\n]);\n\nexport type TrustAnchorStatus = \"DECIONIS_OFFICIAL\" | \"UNESTABLISHED\" | \"UNAVAILABLE\";\n\nexport interface TrustAnchorAssessment {\n status: TrustAnchorStatus;\n trusted: boolean;\n source: string | null;\n detail: string;\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\n/** Pull the dossier payload out of a public endpoint's common envelope shapes. */\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 // GET /v1/protocol/dossiers/{id} wraps the payload in a dossier database row.\n const payload = asRecord(asRecord(record.dossier).dossier_payload);\n if (asRecord(payload.integrity).proof_bundle !== undefined) return payload;\n return record;\n}\n\n/** Resolve the manifest's JWKS location without assigning trust to that location. */\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\n/** Classify the JWKS source independently from signature validity. */\nexport function assessJwksTrustAnchor(source: string | null): TrustAnchorAssessment {\n if (!source) {\n return {\n status: \"UNAVAILABLE\",\n trusted: false,\n source: null,\n detail: \"No JWKS trust anchor was available.\",\n };\n }\n try {\n const url = new URL(source);\n if (\n url.protocol === \"https:\" &&\n url.hostname.toLowerCase() === \"api.decionis.com\" &&\n url.port === \"\" &&\n url.username === \"\" &&\n url.password === \"\" &&\n url.search === \"\" &&\n url.hash === \"\" &&\n OFFICIAL_DECIONIS_JWKS_PATHS.has(url.pathname)\n ) {\n return {\n status: \"DECIONIS_OFFICIAL\",\n trusted: true,\n source: url.toString(),\n detail: \"The key was loaded from Decionis's pinned production JWKS endpoint.\",\n };\n }\n } catch {\n // Local files are valid offline inputs, but remain caller-selected.\n }\n return {\n status: \"UNESTABLISHED\",\n trusted: false,\n source,\n detail:\n \"The key source is caller- or artifact-selected. Signature validity against this key does not establish Decionis issuer authenticity.\",\n };\n}\n\nfunction isRedirect(status: number): boolean {\n return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n\nfunction isForbiddenIpv4(address: string): boolean {\n const parts = address.split(\".\").map((part) => Number.parseInt(part, 10));\n if (parts.length !== 4 || parts.some((part) => !Number.isFinite(part))) return true;\n const [a, b] = parts as [number, number, number, number];\n return (\n a === 0 ||\n a === 10 ||\n a === 127 ||\n (a === 100 && b >= 64 && b <= 127) ||\n (a === 169 && b === 254) ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 192 && b === 0) ||\n (a === 198 && (b === 18 || b === 19)) ||\n a >= 224\n );\n}\n\nfunction isForbiddenIp(address: string): boolean {\n const normalized = address.toLowerCase().split(\"%\")[0]!;\n const version = isIP(normalized);\n if (version === 4) return isForbiddenIpv4(normalized);\n if (version !== 6) return true;\n if (\n normalized === \"::\" ||\n normalized === \"::1\" ||\n normalized.startsWith(\"fc\") ||\n normalized.startsWith(\"fd\") ||\n normalized.startsWith(\"fe\") ||\n normalized.startsWith(\"ff\") ||\n normalized.startsWith(\"2001:db8:\")\n ) {\n return true;\n }\n const mapped = embeddedIpv4Address(normalized);\n return mapped ? isForbiddenIpv4(mapped) : false;\n}\n\n/** Resolve dotted and hexadecimal IPv4-mapped IPv6 spellings after URL normalization. */\nfunction embeddedIpv4Address(address: string): string | null {\n const dotted = address.match(/::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/)?.[1];\n if (dotted) return dotted;\n\n const halves = address.split(\"::\");\n if (halves.length > 2) return null;\n const left = halves[0] ? halves[0].split(\":\") : [];\n const right = halves.length === 2 && halves[1] ? halves[1].split(\":\") : [];\n const missing = 8 - left.length - right.length;\n if (missing < 0 || (halves.length === 1 && missing !== 0)) return null;\n const words = [...left, ...Array.from({ length: missing }, () => \"0\"), ...right];\n if (words.length !== 8 || words.some((word) => !/^[0-9a-f]{1,4}$/.test(word))) return null;\n const parsed = words.map((word) => Number.parseInt(word, 16));\n const mappedPrefix = parsed.slice(0, 5).every((word) => word === 0) && parsed[5] === 0xffff;\n if (!mappedPrefix) return null;\n return [parsed[6]! >>> 8, parsed[6]! & 0xff, parsed[7]! >>> 8, parsed[7]! & 0xff].join(\".\");\n}\n\nasync function assertSafeRemoteUrl(urlText: string): Promise<URL> {\n let url: URL;\n try {\n url = new URL(urlText);\n } catch {\n throw new Error(`Verification URL is invalid: ${urlText}`);\n }\n if (url.protocol !== \"https:\") {\n throw new Error(`Verification URL must use HTTPS: ${urlText}`);\n }\n if (url.username || url.password) {\n throw new Error(`Verification URL must not contain credentials: ${urlText}`);\n }\n const hostname = url.hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (\n hostname === \"localhost\" ||\n hostname.endsWith(\".localhost\") ||\n hostname.endsWith(\".local\") ||\n (isIP(hostname) !== 0 && isForbiddenIp(hostname))\n ) {\n throw new Error(`Verification URL resolves to a non-public destination: ${urlText}`);\n }\n return url;\n}\n\nasync function pinnedHttpsFetch(url: URL, signal: AbortSignal): Promise<Response> {\n const hostname = url.hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n let addresses: Array<{ address: string; family: number }>;\n if (isIP(hostname) !== 0) {\n addresses = [{ address: hostname, family: isIP(hostname) }];\n } else {\n try {\n addresses = await lookup(hostname, { all: true, verbatim: true });\n } catch {\n throw new Error(`Unable to resolve verification host: ${hostname}`);\n }\n }\n if (addresses.length === 0 || addresses.some(({ address }) => isForbiddenIp(address))) {\n throw new Error(`Verification URL resolves to a non-public destination: ${url.toString()}`);\n }\n\n // Connect to the exact address that passed validation. The HTTP Host header\n // and TLS SNI retain the original hostname for certificate verification.\n const destination = addresses[0]!;\n return await new Promise<Response>((resolve, reject) => {\n const request = httpsRequest(\n {\n protocol: \"https:\",\n hostname: destination.address,\n family: destination.family,\n port: url.port || 443,\n path: `${url.pathname}${url.search}`,\n method: \"GET\",\n servername: isIP(hostname) === 0 ? hostname : undefined,\n headers: { accept: \"application/json\", host: url.host },\n signal,\n },\n (incoming) => {\n const headers = new Headers();\n for (const [name, value] of Object.entries(incoming.headers)) {\n if (Array.isArray(value)) {\n for (const item of value) headers.append(name, item);\n } else if (value !== undefined) {\n headers.set(name, value);\n }\n }\n resolve(\n new Response(\n Readable.toWeb(incoming) as unknown as ConstructorParameters<typeof Response>[0],\n {\n status: incoming.statusCode ?? 500,\n statusText: incoming.statusMessage,\n headers,\n },\n ),\n );\n },\n );\n request.once(\"error\", reject);\n request.end();\n });\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 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/** Fetch bounded verification JSON with HTTPS, destination, redirect, and time limits. */\nexport async function fetchVerificationJson(\n urlText: string,\n options: { fetch?: typeof fetch; timeoutMs?: number } = {},\n): Promise<unknown> {\n const fetchImpl = options.fetch;\n const timeoutMs = Math.max(1, Math.min(options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS, 60_000));\n const controller = new AbortController();\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timeoutHandle = setTimeout(() => {\n controller.abort();\n reject(new Error(`Verification request timed out after ${timeoutMs}ms.`));\n }, timeoutMs);\n });\n const operation = (async () => {\n let current = urlText;\n for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects += 1) {\n const url = await assertSafeRemoteUrl(current);\n const response = fetchImpl\n ? await fetchImpl(url.toString(), {\n headers: { accept: \"application/json\" },\n redirect: \"manual\",\n signal: controller.signal,\n })\n : await pinnedHttpsFetch(url, controller.signal);\n if (isRedirect(response.status)) {\n const location = response.headers.get(\"location\");\n if (!location) throw new Error(`Redirect from ${url} did not include a location.`);\n if (redirects === MAX_REDIRECTS) {\n throw new Error(`Request to ${url} exceeded the redirect limit.`);\n }\n current = new URL(location, url).toString();\n continue;\n }\n if (!response.ok) {\n throw new Error(`Request to ${url} failed with HTTP ${response.status}.`);\n }\n return JSON.parse(await boundedResponseText(response, url.toString())) as unknown;\n }\n throw new Error(\"Verification request exceeded the redirect limit.\");\n })();\n try {\n return await Promise.race([operation, timeout]);\n } finally {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n }\n}\n\nfunction autoDiscoveryAllowed(dossierUrl: string, jwksUrl: string): boolean {\n if (assessJwksTrustAnchor(jwksUrl).trusted) return true;\n try {\n return new URL(dossierUrl).origin === new URL(jwksUrl).origin;\n } catch {\n return false;\n }\n}\n\n/** Fetch a dossier and its explicit or safely auto-discovered JWKS, then verify it. */\nexport async function verifyDossierFromUrls(input: {\n dossierUrl: string;\n jwksUrl?: string;\n fetch?: typeof fetch;\n timeoutMs?: number;\n}): Promise<{\n result: VerifyResult;\n jwksUrl: string | null;\n trust_anchor: TrustAnchorAssessment;\n payload: Record<string, unknown>;\n}> {\n const body = await fetchVerificationJson(input.dossierUrl, {\n fetch: input.fetch,\n timeoutMs: input.timeoutMs,\n });\n const payload = extractDossierPayload(body);\n const discovered = resolveJwksUrl(payload, input.dossierUrl);\n const jwksUrl = input.jwksUrl ?? discovered;\n if (jwksUrl && input.jwksUrl === undefined && !autoDiscoveryAllowed(input.dossierUrl, jwksUrl)) {\n throw new Error(\n `Refusing cross-origin JWKS auto-discovery from an unsigned proof manifest: ${jwksUrl}`,\n );\n }\n const trustAnchor = assessJwksTrustAnchor(jwksUrl ?? null);\n if (!jwksUrl) {\n return {\n result: verifyDossierProofBundle({ dossier_payload: payload, public_jwks: null }),\n jwksUrl: null,\n trust_anchor: trustAnchor,\n payload,\n };\n }\n const jwks = await fetchVerificationJson(jwksUrl, {\n fetch: input.fetch,\n timeoutMs: input.timeoutMs,\n });\n return {\n result: verifyDossierProofBundle({ dossier_payload: payload, public_jwks: jwks }),\n jwksUrl,\n trust_anchor: trustAnchor,\n payload,\n };\n}\n","/**\n * Agent-Safe Intent v1 (`agent-safe.intent/1`) conformance, offline and with\n * Node's built-in crypto alone: the second implementation of the profile,\n * written from the specification rather than from the reference runtime, so\n * that an agreement between the two is evidence and not an echo.\n *\n * A binding is the portable statement of one consequential action an agent\n * proposes; its canonical form is the JSON of the binding with every object's\n * keys sorted by UTF-16 code unit at every depth (the ECMAScript default sort,\n * which `stableJsonStringify` already is), encoded as `JSON.stringify` encodes\n * it, with no Unicode normalization; its hash is `sha256:` and the lowercase\n * hex SHA-256 of the UTF-8 bytes of that form. Execution authority is bound\n * to the hash and to nothing looser, so every single-property change is\n * another intent: the vectors carry `mutations` that must each hash apart.\n *\n * Two kinds of vector exist, as the specification states them. A `binding`\n * vector holds a whole binding, which must also satisfy the profile's\n * structure (§3), and may carry mutations. A `canonical` vector holds any\n * JSON object and pins only the bytes and the digest: the Unicode, number\n * and key-order cases. A bare binding with no expected hash is not checked\n * but described: its bytes and hash are computed so another implementation\n * can compare. Nothing is fetched, and nothing here needs an account.\n *\n * The specification: https://github.com/decionis/agent-safe-pipeline/blob/master/spec/intent/v1/README.md\n */\nimport { createHash } from \"node:crypto\";\n\nimport { stableJsonStringify } from \"./canonical.js\";\n\nexport const AGENT_SAFE_INTENT_PROTOCOL = \"agent-safe.intent/1\";\nexport const AGENT_SAFE_INTENT_SPEC_URL =\n \"https://github.com/decionis/agent-safe-pipeline/blob/master/spec/intent/v1/README.md\";\n\nexport type IntentVectorFindingCode =\n | \"DOCUMENT_UNRECOGNISED\"\n | \"BINDING_INVALID\"\n | \"CANONICAL_MISMATCH\"\n | \"HASH_MISMATCH\"\n | \"MUTATION_INVALID\"\n | \"MUTATION_CANONICAL_MISMATCH\"\n | \"MUTATION_HASH_MISMATCH\"\n | \"MUTATION_NOT_DISTINCT\"\n | \"MUTATION_PATH_UNCHANGED\";\n\nexport interface IntentVectorFinding {\n readonly code: IntentVectorFindingCode;\n /** The mutation's path, or the property that failed the profile; null for the base as a whole. */\n readonly path: string | null;\n readonly expected: string | null;\n readonly computed: string | null;\n}\n\nexport interface IntentVectorResult {\n readonly protocol: typeof AGENT_SAFE_INTENT_PROTOCOL;\n /** `binding` for a whole intent binding, `canonical` for a bytes-and-digest case. */\n readonly kind: \"binding\" | \"canonical\" | \"unrecognised\";\n readonly ok: boolean;\n /** Whether the document stated a hash to reproduce, or only asked for one. */\n readonly pinned: boolean;\n readonly canonical_json: string | null;\n readonly intent_hash: string | null;\n /** Mutations the document carried, and how many distinct hashes the whole vector came to. */\n readonly mutations: number;\n readonly hashes: number;\n readonly findings: readonly IntentVectorFinding[];\n}\n\n/** The bounds of §3: a producer refuses, never truncates, a binding beyond them. */\nconst MAX_DEPTH = 20;\nconst MAX_ENTRIES = 5_000;\nconst MAX_ARRAY_LENGTH = 1_000;\nconst MAX_BYTES = 100 * 1024;\nconst FORBIDDEN_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/;\nconst ACTION_TYPE = /^[a-z][a-z0-9._:-]*$/;\nconst DIGEST = /^sha256:[0-9a-f]{64}$/;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Throws `INTENT_*` when a value is outside the profile's bounds; otherwise returns. */\nfunction assertBounded(root: unknown): void {\n const pending: Array<{ value: unknown; depth: number }> = [{ value: root, depth: 0 }];\n let entries = 0;\n while (pending.length > 0) {\n const current = pending.pop() as { value: unknown; depth: number };\n const { value, depth } = current;\n if (value === null || typeof value !== \"object\") {\n if (typeof value === \"number\" && !Number.isFinite(value)) throw new Error(\"INVALID_NUMBER\");\n continue;\n }\n if (depth > MAX_DEPTH) throw new Error(\"INTENT_TOO_DEEP\");\n if (Array.isArray(value)) {\n if (value.length > MAX_ARRAY_LENGTH) throw new Error(\"INTENT_ARRAY_TOO_LARGE\");\n for (const item of value) {\n entries += 1;\n if (entries > MAX_ENTRIES) throw new Error(\"INTENT_TOO_COMPLEX\");\n pending.push({ value: item, depth: depth + 1 });\n }\n continue;\n }\n if (!isPlainObject(value)) throw new Error(\"INVALID_JSON_OBJECT\");\n for (const key of Object.keys(value)) {\n if (FORBIDDEN_KEYS.has(key)) throw new Error(\"UNSAFE_INTENT_KEY\");\n entries += 1;\n if (entries > MAX_ENTRIES) throw new Error(\"INTENT_TOO_COMPLEX\");\n pending.push({ value: value[key], depth: depth + 1 });\n }\n }\n}\n\n/**\n * The canonical bytes and the hash of a JSON object, exactly as the profile\n * defines them. Throws with a stable code when the object is not a plain,\n * finite, bounded JSON object.\n */\nexport function intentHash(binding: unknown): { canonical_json: string; intent_hash: string } {\n if (!isPlainObject(binding)) throw new Error(\"INVALID_JSON_OBJECT\");\n assertBounded(binding);\n const canonical = stableJsonStringify(binding);\n if (Buffer.byteLength(canonical, \"utf8\") > MAX_BYTES) throw new Error(\"INTENT_TOO_LARGE\");\n return {\n canonical_json: canonical,\n intent_hash: `sha256:${createHash(\"sha256\").update(canonical, \"utf8\").digest(\"hex\")}`,\n };\n}\n\ntype Check = (value: unknown) => boolean;\nconst text =\n (min: number, max: number): Check =>\n (value) =>\n typeof value === \"string\" && value.length >= min && value.length <= max;\nconst pattern =\n (expression: RegExp): Check =>\n (value) =>\n typeof value === \"string\" && expression.test(value);\n\ninterface Shape {\n readonly required: Readonly<Record<string, Check>>;\n readonly optional: Readonly<Record<string, Check>>;\n /** Whether keys beyond the named ones are refused. */\n readonly closed: boolean;\n}\n\nconst ACTOR: Shape = {\n required: { id: text(1, 200), type: text(1, 200) },\n optional: { runtime: text(1, 200), trust_level: text(1, 80) },\n closed: true,\n};\nconst ACTION: Shape = {\n required: {\n type: (value) => text(1, 120)(value) && ACTION_TYPE.test(value as string),\n resource: text(1, 500),\n parameters: isPlainObject,\n },\n optional: {},\n closed: true,\n};\nconst CONTEXT: Shape = {\n required: { idempotency_key: text(1, 180) },\n optional: {},\n closed: false,\n};\nconst DOWNSTREAM_TARGET: Shape = {\n required: { system: text(1, 200), operation: text(1, 200) },\n optional: { environment: text(1, 200), endpoint: text(1, 500) },\n closed: true,\n};\nconst BINDING: Shape = {\n required: {\n protocol_version: (value) => value === AGENT_SAFE_INTENT_PROTOCOL,\n tenant_id: pattern(UUID),\n intent_id: pattern(UUID),\n captured_at: pattern(INSTANT),\n expires_at: pattern(INSTANT),\n actor: isPlainObject,\n action: isPlainObject,\n context: isPlainObject,\n downstream_target: isPlainObject,\n },\n optional: { expected_effect_digest: pattern(DIGEST) },\n closed: true,\n};\n\n/** The first property of `value` that fails `shape`, as a dotted path, or null. */\nfunction shapeFailure(value: unknown, shape: Shape, prefix: string): string | null {\n if (!isPlainObject(value)) return prefix === \"\" ? \"(binding)\" : prefix;\n const at = (key: string): string => (prefix === \"\" ? key : `${prefix}.${key}`);\n for (const [key, check] of Object.entries(shape.required)) {\n if (!(key in value) || !check(value[key])) return at(key);\n }\n for (const [key, check] of Object.entries(shape.optional)) {\n if (key in value && !check(value[key])) return at(key);\n }\n if (shape.closed) {\n for (const key of Object.keys(value)) {\n if (!(key in shape.required) && !(key in shape.optional)) return at(key);\n }\n }\n return null;\n}\n\n/** Where a whole binding departs from §3 of the profile, or null when it does not. */\nexport function bindingFailure(binding: unknown): string | null {\n return (\n shapeFailure(binding, BINDING, \"\") ??\n shapeFailure((binding as Record<string, unknown>).actor, ACTOR, \"actor\") ??\n shapeFailure((binding as Record<string, unknown>).action, ACTION, \"action\") ??\n shapeFailure((binding as Record<string, unknown>).context, CONTEXT, \"context\") ??\n shapeFailure(\n (binding as Record<string, unknown>).downstream_target,\n DOWNSTREAM_TARGET,\n \"downstream_target\",\n )\n );\n}\n\nfunction valueAt(value: unknown, path: string): unknown {\n let current: unknown = value;\n for (const key of path.split(\".\")) {\n if (!isPlainObject(current)) return undefined;\n current = current[key];\n }\n return current;\n}\n\nfunction hashed(value: unknown): { canonical_json: string; intent_hash: string } | null {\n try {\n return intentHash(value);\n } catch {\n return null;\n }\n}\n\nexport function verifyIntentVector(document: unknown): IntentVectorResult {\n const unrecognised: IntentVectorResult = {\n protocol: AGENT_SAFE_INTENT_PROTOCOL,\n kind: \"unrecognised\",\n ok: false,\n pinned: false,\n canonical_json: null,\n intent_hash: null,\n mutations: 0,\n hashes: 0,\n findings: [{ code: \"DOCUMENT_UNRECOGNISED\", path: null, expected: null, computed: null }],\n };\n if (!isPlainObject(document)) return unrecognised;\n // A vector wraps its binding; a bare binding is the document itself.\n const wrapped = isPlainObject(document.binding);\n const binding = wrapped ? document.binding : document;\n if (!isPlainObject(binding)) return unrecognised;\n const kind = binding.protocol_version === AGENT_SAFE_INTENT_PROTOCOL ? \"binding\" : \"canonical\";\n if (!wrapped && kind !== \"binding\") return unrecognised;\n const findings: IntentVectorFinding[] = [];\n const base = hashed(binding);\n if (base === null) {\n return {\n ...unrecognised,\n kind,\n findings: [\n { code: \"BINDING_INVALID\", path: null, expected: \"bounded JSON object\", computed: null },\n ],\n };\n }\n if (kind === \"binding\") {\n const failure = bindingFailure(binding);\n if (failure !== null) {\n findings.push({ code: \"BINDING_INVALID\", path: failure, expected: null, computed: null });\n }\n }\n const expectedCanonical = wrapped ? document.canonical_json : undefined;\n const expectedHash = wrapped ? document.intent_hash : undefined;\n const pinned = typeof expectedHash === \"string\";\n if (typeof expectedCanonical === \"string\" && expectedCanonical !== base.canonical_json) {\n findings.push({\n code: \"CANONICAL_MISMATCH\",\n path: null,\n expected: expectedCanonical,\n computed: base.canonical_json,\n });\n }\n if (pinned && expectedHash !== base.intent_hash) {\n findings.push({\n code: \"HASH_MISMATCH\",\n path: null,\n expected: expectedHash as string,\n computed: base.intent_hash,\n });\n }\n const hashes = new Set([base.intent_hash]);\n const mutations = wrapped && Array.isArray(document.mutations) ? document.mutations : [];\n mutations.forEach((mutation: unknown, index: number) => {\n const label =\n isPlainObject(mutation) && typeof mutation.path === \"string\" ? mutation.path : `#${index}`;\n const mutated = isPlainObject(mutation) ? hashed(mutation.binding) : null;\n if (!isPlainObject(mutation) || mutated === null || typeof mutation.intent_hash !== \"string\") {\n findings.push({ code: \"MUTATION_INVALID\", path: label, expected: null, computed: null });\n return;\n }\n if (kind === \"binding\") {\n const failure = bindingFailure(mutation.binding);\n if (failure !== null) {\n findings.push({\n code: \"MUTATION_INVALID\",\n path: `${label} (${failure})`,\n expected: null,\n computed: null,\n });\n }\n }\n if (\n typeof mutation.canonical_json === \"string\" &&\n mutation.canonical_json !== mutated.canonical_json\n ) {\n findings.push({\n code: \"MUTATION_CANONICAL_MISMATCH\",\n path: label,\n expected: mutation.canonical_json,\n computed: mutated.canonical_json,\n });\n }\n if (mutation.intent_hash !== mutated.intent_hash) {\n findings.push({\n code: \"MUTATION_HASH_MISMATCH\",\n path: label,\n expected: mutation.intent_hash,\n computed: mutated.intent_hash,\n });\n }\n if (hashes.has(mutated.intent_hash)) {\n findings.push({\n code: \"MUTATION_NOT_DISTINCT\",\n path: label,\n expected: null,\n computed: mutated.intent_hash,\n });\n }\n hashes.add(mutated.intent_hash);\n // The mutation must be what it says it is: the named property differs from the base.\n if (\n typeof mutation.path === \"string\" &&\n JSON.stringify(valueAt(mutation.binding, mutation.path)) ===\n JSON.stringify(valueAt(binding, mutation.path))\n ) {\n findings.push({\n code: \"MUTATION_PATH_UNCHANGED\",\n path: label,\n expected: null,\n computed: null,\n });\n }\n });\n return {\n protocol: AGENT_SAFE_INTENT_PROTOCOL,\n kind,\n ok: findings.length === 0,\n pinned,\n canonical_json: base.canonical_json,\n intent_hash: base.intent_hash,\n mutations: mutations.length,\n hashes: hashes.size,\n findings,\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","// Where a paired Shield credential lives between runs (Shield growth plan V5,\n// \"bind your own agent\"). The user types a six-character code from the\n// Shield app into their assistant; `shield.pair` claims it and keeps the\n// credential here, so the user never handles a key. Environment variables\n// still win, for integrators who provision keys themselves.\n\nimport { mkdirSync, readFileSync, writeFileSync, chmodSync } from \"node:fs\";\nimport { homedir, hostname } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\n\nexport interface ShieldCredential {\n apiKey: string;\n appId: string;\n baseUrl: string;\n integrationId?: string;\n displayName?: string;\n /** A stable id for this install, so pairing again rotates rather than duplicates. */\n agentId: string;\n pairedAt?: string;\n}\n\nexport const SHIELD_MCP_APP_ID = \"decionis-mcp\";\nexport const DEFAULT_SHIELD_API_URL = \"https://api.shield.decionis.com\";\n\nexport function defaultCredentialPath(): string {\n return (\n process.env.DECIONIS_SHIELD_CREDENTIAL_FILE?.trim() ||\n join(homedir(), \".decionis\", \"shield-credential.json\")\n );\n}\n\nexport class ShieldCredentialStore {\n public constructor(private readonly path: string = defaultCredentialPath()) {}\n\n /** The credential to use now: the environment first, then the paired file. */\n public resolve(): ShieldCredential | null {\n const envKey = process.env.DECIONIS_SHIELD_API_KEY?.trim();\n const envApp = process.env.DECIONIS_SHIELD_APP_ID?.trim();\n const baseUrl = (process.env.DECIONIS_SHIELD_API_URL?.trim() || DEFAULT_SHIELD_API_URL).replace(\n /\\/+$/,\n \"\",\n );\n if (envKey && envApp) {\n return { apiKey: envKey, appId: envApp, baseUrl, agentId: envApp };\n }\n const stored = this.read();\n if (!stored) return null;\n return { ...stored, baseUrl: process.env.DECIONIS_SHIELD_API_URL?.trim() || stored.baseUrl };\n }\n\n public read(): ShieldCredential | null {\n try {\n const raw = JSON.parse(readFileSync(this.path, \"utf8\")) as Partial<ShieldCredential>;\n if (typeof raw.apiKey !== \"string\" || typeof raw.appId !== \"string\") return null;\n return {\n apiKey: raw.apiKey,\n appId: raw.appId,\n baseUrl: typeof raw.baseUrl === \"string\" ? raw.baseUrl : DEFAULT_SHIELD_API_URL,\n integrationId: typeof raw.integrationId === \"string\" ? raw.integrationId : undefined,\n displayName: typeof raw.displayName === \"string\" ? raw.displayName : undefined,\n agentId: typeof raw.agentId === \"string\" ? raw.agentId : randomUUID(),\n pairedAt: typeof raw.pairedAt === \"string\" ? raw.pairedAt : undefined,\n };\n } catch {\n return null;\n }\n }\n\n /** The install's stable id: the stored one, else a new one written at first pairing. */\n public agentId(): string {\n return this.read()?.agentId ?? randomUUID();\n }\n\n public write(credential: ShieldCredential): void {\n mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });\n writeFileSync(this.path, `${JSON.stringify(credential, null, 2)}\\n`, { mode: 0o600 });\n try {\n chmodSync(this.path, 0o600);\n } catch {\n // Best effort on filesystems without POSIX modes.\n }\n }\n\n public location(): string {\n return this.path;\n }\n}\n\n/** A name the user recognises in the Shield app's list of agents. */\nexport function defaultAgentDisplayName(clientName?: string): string {\n const host = hostname().split(\".\")[0] || \"this computer\";\n return clientName ? `${clientName} on ${host}` : `Decionis MCP on ${host}`;\n}\n","import {\n DEFAULT_SHIELD_API_URL,\n ShieldCredentialStore,\n type ShieldCredential,\n} from \"./ShieldCredentialStore.js\";\n\nexport 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 fetchImpl: typeof fetch;\n private readonly credentials: () => ShieldCredential | null;\n\n public constructor(\n options: {\n baseUrl?: string;\n apiKey?: string;\n appId?: string;\n fetch?: typeof fetch;\n /** Resolved per request, so a `shield.pair` mid-session takes effect at once. */\n credentials?: () => ShieldCredential | null;\n } = {},\n ) {\n this.fetchImpl = options.fetch ?? fetch;\n if (options.credentials) {\n this.credentials = options.credentials;\n } else if (options.apiKey !== undefined || options.appId !== undefined || options.baseUrl) {\n const fixed: ShieldCredential | null =\n options.apiKey && options.appId\n ? {\n apiKey: options.apiKey,\n appId: options.appId,\n baseUrl: (options.baseUrl ?? DEFAULT_SHIELD_API_URL).replace(/\\/+$/, \"\"),\n agentId: options.appId,\n }\n : null;\n this.credentials = () => fixed;\n } else {\n const store = new ShieldCredentialStore();\n this.credentials = () => store.resolve();\n }\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 const credential = this.credentials();\n if (!credential || !credential.apiKey || !credential.appId) {\n throw new ShieldClientError(\n \"SHIELD_MCP_CONFIGURATION_REQUIRED\",\n \"Shield is not paired. Ask the user for the six-character code from the Shield app (AI spending allowance → Bind your own agent) and call shield.pair with it — or configure DECIONIS_SHIELD_API_KEY and DECIONIS_SHIELD_APP_ID. Do not execute the transaction.\",\n );\n }\n const response = await this.fetchImpl(`${credential.baseUrl}${path}`, {\n method,\n headers: {\n accept: \"application/json\",\n authorization: `Bearer ${credential.apiKey}`,\n \"content-type\": \"application/json\",\n \"x-shield-app-id\": credential.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\";\nimport {\n SHIELD_MCP_APP_ID,\n ShieldCredentialStore,\n defaultAgentDisplayName,\n type ShieldCredential,\n} from \"./ShieldCredentialStore.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\n/**\n * `shield.pair` (Shield growth plan V5, \"bind your own agent\"): the user reads\n * a six-character code off the Shield app (AI spending allowance → Bind your\n * own agent) and says it to their assistant; this claims it and keeps the\n * production credential in the user's config directory. From then on the\n * five shield.* tools ask the user's own Shield, and the app lists this\n * assistant with what it was allowed to spend this week. The user never\n * handles a key. Pairing again from the same install rotates the credential\n * rather than binding a second agent.\n */\nexport function createShieldPairTool(\n options: {\n store?: ShieldCredentialStore;\n fetch?: typeof fetch;\n baseUrl?: () => string;\n clientName?: () => string | undefined;\n } = {},\n): ToolDefinition {\n const store = options.store ?? new ShieldCredentialStore();\n const fetchImpl = options.fetch ?? fetch;\n const baseUrl = () =>\n (options.baseUrl?.() ?? process.env.DECIONIS_SHIELD_API_URL?.trim() ?? \"\").replace(/\\/+$/, \"\") ||\n \"https://api.shield.decionis.com\";\n return {\n name: \"shield.pair\",\n title: \"Pair with the user's Shield\",\n description:\n \"Bind this assistant to the user's Decionis Shield with the six-character pairing code shown in the Shield app (AI spending allowance → Bind your own agent). Ask the user for the code; never guess one. After pairing, shield.request_purchase and the other shield.* tools ask the user's own spending rules.\",\n inputSchema: {\n type: \"object\",\n required: [\"code\"],\n properties: {\n code: { type: \"string\", pattern: \"^[A-Za-z0-9]{6,8}$\", description: \"The code from the Shield app.\" },\n displayName: {\n type: \"string\",\n maxLength: 120,\n description: \"How the Shield app should list this assistant (default: the client and this computer).\",\n },\n },\n additionalProperties: false,\n },\n annotations: networkMutation,\n handler: async (args) => {\n const code = typeof args.code === \"string\" ? args.code.trim().toUpperCase() : \"\";\n if (!/^[A-Z0-9]{6,8}$/.test(code)) {\n return { content: text(\"A pairing code is 6 to 8 letters and digits. Ask the user for the code shown in the Shield app.\"), isError: true };\n }\n const displayName =\n typeof args.displayName === \"string\" && args.displayName.trim()\n ? args.displayName.trim().slice(0, 120)\n : defaultAgentDisplayName(options.clientName?.());\n const agentId = store.agentId();\n let response: Response;\n try {\n response = await fetchImpl(`${baseUrl()}/v1/consumer/pairing/claim`, {\n method: \"POST\",\n headers: {\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"x-shield-surface\": \"mcp\",\n },\n body: JSON.stringify({\n code,\n agent: { app_id: SHIELD_MCP_APP_ID, agent_id: agentId, display_name: displayName },\n }),\n });\n } catch (error) {\n return {\n content: text({\n error: \"SHIELD_PAIRING_UNREACHABLE\",\n message: `Could not reach Shield: ${error instanceof Error ? error.message : String(error)}. Nothing was paired.`,\n }),\n isError: true,\n };\n }\n const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n if (!response.ok || !payload || typeof payload.api_key !== \"string\" || typeof payload.app_id !== \"string\") {\n const code_ = payload && typeof payload.error === \"string\" ? payload.error : `HTTP ${response.status}`;\n const hint =\n code_ === \"PAIRING_CODE_INVALID\"\n ? \"The code is wrong, expired (ten minutes) or already used. Ask the user for a fresh one from the Shield app.\"\n : \"Nothing was paired.\";\n return { content: text({ error: code_, message: hint }), isError: true };\n }\n const integration = (payload.integration ?? {}) as Record<string, unknown>;\n const credential: ShieldCredential = {\n apiKey: payload.api_key,\n appId: payload.app_id,\n baseUrl: baseUrl(),\n integrationId: typeof integration.integrationId === \"string\" ? integration.integrationId : undefined,\n displayName,\n agentId,\n pairedAt: new Date().toISOString(),\n };\n store.write(credential);\n const limit = typeof payload.weekly_limit === \"number\" ? payload.weekly_limit : null;\n return {\n content: text({\n paired: true,\n rotated: payload.rotated === true,\n displayName,\n weeklyLimit: limit,\n storedAt: store.location(),\n next: \"The shield.* tools now ask this user's own Shield. Before any purchase, call shield.request_purchase; execute only on ALLOW.\",\n }),\n };\n },\n };\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 { createShieldPairTool, createShieldTools } from \"./ShieldTools.js\";\n\n// Presence tools exist only when a tenant key is configured. The hosted\n// integration reads DECIONIS_PRESENCE_SERVICE_TOKEN (the service credential on\n// protocol.decionis.com); a local integrator supplies their own Presence tenant\n// key as DECIONIS_PRESENCE_API_KEY, which is mapped onto the same variable\n// before the protocol boots so the request, the receipt check and the\n// re-evaluation's proof seal all use one key.\nconst presenceKey =\n process.env.DECIONIS_PRESENCE_API_KEY?.trim() ||\n process.env.DECIONIS_PRESENCE_SERVICE_TOKEN?.trim() ||\n \"\";\nif (presenceKey && !process.env.DECIONIS_PRESENCE_SERVICE_TOKEN) {\n process.env.DECIONIS_PRESENCE_SERVICE_TOKEN = presenceKey;\n}\nconst presenceConfigured = presenceKey.length > 0;\n\nconst gateway = new LocalDecionisGateway();\n\n// The Shield tools are always advertised (Shield growth plan V5): a fresh\n// `npx @decionis/mcp` can pair with the user's Shield through `shield.pair`\n// and a six-character code from the app, and the credential is read per\n// call, so the five shield.* tools go live the moment pairing succeeds.\n// Until then — or without DECIONIS_SHIELD_API_KEY / DECIONIS_SHIELD_APP_ID\n// — every shield.* call fails closed with SHIELD_MCP_CONFIGURATION_REQUIRED\n// and tells the model to ask the user for the code.\nconst shieldClient = new ShieldClient();\n\nconst handler = createMcpHandler({\n serverInfo: { name: \"decionis-mcp\", version: MCP_SERVER_VERSION },\n tools: createDecionisTools(\n gateway,\n [\n ...createKubernetesMcpToolsFromEnvironment(),\n createShieldPairTool(),\n ...createShieldTools(shieldClient),\n ],\n { presenceConfigured },\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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KAAK,CAAC;AAChB,CAAC;","names":["id","handler","isPlainObject","gateway","presenceConfigured","createHash","createHash","text","z","z","z","createHash","createHash","record","createHash","z","createHash","record","stableJsonStringify","jcsCanonicalize","assertUnicodeScalarString","external_exports","util","objectUtil","errorUtil","errorMap","ctx","result","issues","elements","processed","r","ZodFirstPartyTypeKind","z","sha256DigestSchema","boundedIdentifier","text","pointer","record","jcsCanonicalize","stableJsonStringify","asRecord","record","hostname","isPlainObject","text","isPlainObject","createHash","text","randomUUID","asRecord","text"]}