{"version":3,"file":"orchestrator.mjs","names":["defaultLogger","blockWithParseError"],"sources":["../src/engine/orchestrator/render-engine.ts","../src/engine/orchestrator/node-deferral.ts","../src/engine/warm-up.ts","../src/engine/adapters/util.ts","../src/engine/orchestrator/utf8.ts","../src/engine/orchestrator/build-agent-request.ts","../src/engine/adapters/outbound-url-policy.ts","../src/engine/adapters/safe-get.ts","../src/engine/adapters/resolution-host.ts","../src/engine/types.ts","../src/engine/orchestrator/synthetic-results.ts","../src/engine/orchestrator/directed.ts","../src/engine/orchestrator/presented-credential.ts","../src/engine/orchestrator/signed-body.ts","../src/engine/orchestrator/verify-request.ts","../src/wasm-module-error.ts","../src/engine/edge-wasm.ts","../src/engine/edge.ts","../src/engine/orchestrator/verify-request-edge.ts","../src/engine/orchestrator/index.ts"],"sourcesContent":["/**\n * `renderDecisionAsResponse` for the Node and bundler orchestrator builds.\n *\n * The engine renders the kya-os/http answer for a `VerifyResult`\n * (`rust/crates/kya-os-engine/src/render`): status, ordered headers and body.\n * This module only reshapes that answer for the host adapters; it makes no\n * rendering decision of its own.\n *\n * The engine returns headers as one ordered list of `(name, value)` pairs.\n * `RenderedResponse` splits them by how a host applies them. A field the answer\n * names once goes in `headers`, which the adapters set, replacing any value\n * already on the response. A field it names more than once (the Delegation\n * challenge's two `WWW-Authenticate` fields) goes in `headerEntries`, which the\n * adapters append in order. Names compare case-insensitively, as HTTP field\n * names do.\n */\n\nimport type { HeaderEntry } from '@kya-os/checkpoint-shared';\n\nimport type { EngineRenderedResponse, EngineRenderOptions } from '../render-types';\nimport type { VerifyResult } from '../types';\nimport type { RenderedResponse } from './types';\n\n/** Per-request host settings for {@link makeRenderDecision}'s renderer. */\nexport type RenderDecisionOptions = EngineRenderOptions;\n\n/** One target's engine render binding (`engineRender` from `../index` or `../node`). */\nexport type EngineRenderFn = (\n  result: VerifyResult,\n  options?: EngineRenderOptions\n) => EngineRenderedResponse;\n\n/** The renderer the host adapters call. */\nexport type RenderDecision = (\n  result: VerifyResult,\n  options?: RenderDecisionOptions\n) => RenderedResponse;\n\n/**\n * Bind `renderDecisionAsResponse` to one target's engine. The renderer throws\n * `EngineRenderError` when the registered challenge context fails validation;\n * the SDKs answer that with their fail-closed 503.\n */\nexport function makeRenderDecision(engineRender: EngineRenderFn): RenderDecision {\n  return (result, options) => toRenderedResponse(engineRender(result, options));\n}\n\n/** Reshape the engine's answer into the host-adapter {@link RenderedResponse}. */\nexport function toRenderedResponse(rendered: {\n  status: EngineRenderedResponse['status'];\n  headers: readonly HeaderEntry[];\n  body?: unknown;\n}): RenderedResponse {\n  const occurrences = new Map<string, number>();\n  for (const [name] of rendered.headers) {\n    const key = name.toLowerCase();\n    occurrences.set(key, (occurrences.get(key) ?? 0) + 1);\n  }\n  const headers: Record<string, string> = {};\n  const headerEntries: HeaderEntry[] = [];\n  for (const [name, value] of rendered.headers) {\n    if (occurrences.get(name.toLowerCase()) === 1) headers[name] = value;\n    else headerEntries.push([name, value]);\n  }\n  return {\n    status: rendered.status,\n    headers,\n    ...(headerEntries.length > 0 ? { headerEntries } : {}),\n    ...(rendered.body === undefined ? {} : { body: rendered.body as RenderedResponse['body'] }),\n  };\n}\n","/**\n * The Node and bundler builds' vendor-key round deferral: settles once the\n * task that asked for a round has run to completion. Node's first `fetch()`\n * loads its HTTP client synchronously, so a round started inside\n * `afterVerify` ran that load on the request that triggered it, before its\n * response was written. `setImmediate` runs after that request's own\n * continuations. It is not a timer: nothing waits on the clock.\n *\n * Only the Node and bundler orchestrator entries import this module, so it\n * stays out of the shared feed chunk that the package root and Edge\n * middleware load. The `globalThis` property access keeps Edge bundlers from\n * rejecting a bare `setImmediate` should it ever be reachable there; where it\n * is missing or throws, the feed starts the round at once.\n */\nexport function afterThisNodeTask(): Promise<void> {\n  return new Promise<void>((resolve) => {\n    (globalThis as { setImmediate: (callback: () => void) => unknown }).setImmediate(resolve);\n  });\n}\n","/**\n * Engine warm-up (epic #6089, stage 3).\n *\n * The engine's first verify pays for work no later verify repeats: it builds\n * its user-agent pattern tables, and V8 compiles each WASM function on its\n * first call. Running one verify ahead of traffic moves that cost off the\n * first real request. A Chrome page load is the request used, because it\n * matches no AI-agent pattern and so reaches every pattern table.\n *\n * The warm-up calls the engine binding directly, never `verifyRequest`, so it\n * resolves no DID, fetches no status list, asks no policy or reputation\n * service, starts no vendor-key feed round and reports nothing. The engine\n * records state on a verify only for a signed request (a vendor-key miss), and\n * this request carries no signature, so the feed's cold-start demand is left\n * for the first real request exactly as it was.\n *\n * Each engine loader calls `warmEngine` once, after a successful load and\n * before it reports the engine ready, so no real request reaches a cold engine\n * through it. This module imports no scheduling helper: the edge build loads\n * it too, and a build that warms later passes its own deferral to\n * `scheduleWarmUp`.\n */\n\nimport type { AgentRequest, ContextSpec, VerifyResult } from './types';\n\nexport type EngineVerify = (input: AgentRequest, ctx: ContextSpec) => VerifyResult;\n\nconst CHROME_USER_AGENT =\n  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36';\n\nconst WARM_UP_REQUEST: AgentRequest = {\n  protocol: 'PlainHttp',\n  request: {\n    raw: [],\n    method: 'GET',\n    path: '/',\n    headers: [\n      ['user-agent', CHROME_USER_AGENT],\n      ['accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'],\n      ['accept-language', 'en-US,en;q=0.9'],\n      ['accept-encoding', 'gzip, deflate, br'],\n    ],\n    userAgent: CHROME_USER_AGENT,\n    // TEST-NET-3 (RFC 5737): never a real client.\n    remoteIp: '203.0.113.7',\n    signals: null,\n    sessionVelocity: null,\n  },\n};\n\nfunction warmUpContext(): ContextSpec {\n  return {\n    didDocs: {},\n    revoked: {},\n    reputation: {},\n    tenantDecision: { kind: 'Permit' },\n    nowUnix: Math.floor(Date.now() / 1000),\n    enforcementMode: 'observe',\n  };\n}\n\n/**\n * Run one verify of a Chrome page load on `verify`. Never throws: an engine\n * that cannot verify reports that on the first real request, through the\n * caller's usual error path.\n */\nexport function warmEngine(verify: EngineVerify): void {\n  try {\n    verify(WARM_UP_REQUEST, warmUpContext());\n  } catch {\n    // Left for the first real verify to report.\n  }\n}\n\n/**\n * For an engine that loads when its module is imported (the bundler build):\n * queue the warm-up behind `defer`, so the import stays as fast as before and a\n * server that imports at startup is warm before its first request arrives.\n * When `defer` rejects (no `setImmediate`, say), the warm-up runs then.\n * Returns a function that runs the warm-up now unless it has run, for\n * `initEngine()`, so a host that awaits it at startup gets a warm engine\n * whatever the scheduling.\n */\nexport function scheduleWarmUp(verify: EngineVerify, defer: () => Promise<void>): () => void {\n  let warmed = false;\n  const warmNow = (): void => {\n    if (warmed) return;\n    warmed = true;\n    warmEngine(verify);\n  };\n  let deferred: Promise<void>;\n  try {\n    deferred = defer();\n  } catch {\n    deferred = Promise.resolve();\n  }\n  void deferred.then(warmNow, warmNow);\n  return warmNow;\n}\n","/**\n * Shared utilities for the Phase B adapters.\n *\n * Anything used by more than one adapter belongs here so a future\n * bug fix touches one site, not N.\n */\n\n/**\n * base64url decode (RFC 4648, section 5): `-` and `_` stand for `+` and `/`,\n * and padding is optional. Uses `atob`, which Node, Cloudflare Workers and the\n * Edge runtime all have, so it also works where Node's `Buffer` is missing\n * (Workers without `nodejs_compat`). A character outside the alphabet throws\n * instead of being skipped.\n */\nexport function base64UrlDecode(input: string): Uint8Array {\n  const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/'));\n  const bytes = new Uint8Array(binary.length);\n  for (let index = 0; index < binary.length; index += 1) {\n    bytes[index] = binary.charCodeAt(index);\n  }\n  return bytes;\n}\n","/**\n * UTF-8 conversions for request bodies and JWS strings, with the APIs every\n * runtime has (TextEncoder, TextDecoder, typed arrays) instead of Node's\n * `Buffer`, which Cloudflare Workers without `nodejs_compat` do not have.\n *\n * They give the bytes and strings `Buffer` gave on Node: unpaired surrogates\n * and invalid bytes become U+FFFD both ways, and a leading byte-order mark is\n * kept (`ignoreBOM`), as `Buffer#toString` keeps it.\n * `__tests__/utf8.test.ts` pins that against `Buffer`.\n */\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder('utf-8', { ignoreBOM: true });\n\n/** The UTF-8 bytes of `text`. */\nexport function utf8Bytes(text: string): number[] {\n  return Array.from(ENCODER.encode(text));\n}\n\n/** The string the UTF-8 `bytes` decode to. */\nexport function utf8Text(bytes: Uint8Array | readonly number[]): string {\n  return DECODER.decode(bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes));\n}\n\n/**\n * The bytes of a body the host passed as binary (a Node `Buffer`, a\n * `Uint8Array` or any other view), from any realm; `null` for anything else.\n */\nexport function bytesOf(body: unknown): Uint8Array | null {\n  return ArrayBuffer.isView(body)\n    ? new Uint8Array(body.buffer, body.byteOffset, body.byteLength)\n    : null;\n}\n","/**\n * HTTP-to-`AgentRequest` translator — Phase C.1.\n *\n * Detects which engine protocol the request belongs to and builds\n * the typed `AgentRequest` the WASM consumes. Conservative\n * detection: never escalates an ambiguous request into a higher\n * verification tier. Anonymous PlainHttp is the default.\n *\n * **What this layer parses and what it doesn't.** It parses *only\n * what's needed to drive conditional pre-fetch* — header presence,\n * the KYA-OS envelope's payload segment (to extract `iss` + `sub` +\n * optional credentialStatus lookup). It does **not** verify\n * signatures, decode VC chains for revocation bits, or evaluate\n * scope. Those live in the engine (H-1's parser + Stages 2-5).\n *\n * **No Node `Buffer`.** Every byte and string conversion (request\n * bodies, the JWS preflight, the credential decodes) goes through\n * `./utf8`, which uses `TextEncoder`, `TextDecoder` and typed arrays,\n * so this module runs where `Buffer` does not exist: Cloudflare Workers\n * without `nodejs_compat`, whose acceptance test is\n * `tests/e2e/workers-no-nodejs-compat`.\n */\n\nimport { requestDeclaresBody } from '@kya-os/checkpoint-shared/kya-http';\n\nimport { base64UrlDecode } from '../adapters/util';\nimport type {\n  AgentRequest,\n  HttpSignedRequest,\n  McpIPayload,\n  McpIRequest,\n  PlainHttpRequest,\n} from '../types';\n\nimport type { IncomingHttpLike } from './types';\nimport { hasKyaSignatureMember } from './kya-signature-presentation';\nimport { bytesOf, utf8Bytes, utf8Text } from './utf8';\n\n// -----------------------------------------------------------------------------\n// Public surface.\n// -----------------------------------------------------------------------------\n\nexport interface BuildAgentRequestOpts {\n  /** See `VerifyRequestOpts.legacyEnvelopeFallback`. */\n  legacyEnvelopeFallback?: boolean;\n}\n\nexport interface CredentialStatusRef {\n  /** URL the host should fetch from the StatusList cache. */\n  fetchUrl: string;\n  /** Exact key the engine will query in `ContextSpec.revoked`. */\n  mapUrl: string;\n  /**\n   * The issuer of the credential carrying the status entry: the list must be\n   * signed by it. Null when the credential names none (the list then fails\n   * closed).\n   */\n  issuer: string | null;\n  /**\n   * The credential's `statusListIndex`, or null when it is not a\n   * non-negative integer. An index outside the list fails closed.\n   */\n  index: number | null;\n}\n\n/** Bits per org status list: an index at or past this is outside every list. */\nexport const STATUS_LIST_SIZE = 131_072;\n\n/**\n * A credential's status entry no list can answer (no usable index, or an\n * index outside the list). The orchestrators reject the request rather than\n * treat the credential as not revoked.\n */\nexport class InvalidCredentialStatus extends Error {\n  readonly kind = 'InvalidCredentialStatus';\n}\n\n/**\n * The `iss` a presented DelegationCredential names, read before any signature\n * check. Null when the credential has no string `iss`.\n */\nexport interface DelegationIssuerRef {\n  issuer: string | null;\n}\n\nexport interface BearerDelegationCredentialRef extends DelegationIssuerRef {\n  /** The compact VC-JWT presented as a standalone bearer delegation. */\n  credential: string;\n  /** Decoded JWT payload claims. Signature verification happens in the engine. */\n  claims: Record<string, unknown>;\n  agentDid: string | null;\n  credentialStatus: CredentialStatusRef | null;\n}\n\n/**\n * Translate an HTTP-like request into the engine's `AgentRequest`.\n *\n * Detection order (conservative — never escalate ambiguous input):\n *   1. KYA-OS L2 detached proof in `_meta.proof.jws` (spec form).\n *   2. (Legacy, opt-in) KYA-OS in `KYA-Delegation` header\n *      (Envelope-1 #2537 transition window only).\n *   3. RFC 9421 HTTP Message Signatures (`Signature-Input` header).\n *   4. PlainHttp (default — anonymous traffic).\n */\nexport function buildAgentRequest(\n  req: IncomingHttpLike,\n  opts: BuildAgentRequestOpts = {}\n): AgentRequest {\n  // 1. KYA-OS L2 detached proof — spec form, body's `_meta.proof.jws`.\n  const mcpI = tryBuildMcpIFromBody(req);\n  if (mcpI) {\n    return { protocol: 'McpI', request: mcpI };\n  }\n\n  // 2. KYA-OS legacy header (Envelope-1 transition only).\n  if (opts.legacyEnvelopeFallback) {\n    const legacyMcpI = tryBuildMcpIFromLegacyHeader(req);\n    if (legacyMcpI) {\n      return { protocol: 'McpI', request: legacyMcpI };\n    }\n  }\n\n  // 3. RFC 9421 HTTP Message Signatures. An incomplete KYA presentation\n  // must reach verification even when its Signature-Input is absent.\n  if (getHeader(req, 'signature-input') || hasKyaSignatureMember(req.headers)) {\n    return { protocol: 'HttpSigned', request: buildHttpSigned(req) };\n  }\n\n  // 4. Default — anonymous PlainHttp.\n  return { protocol: 'PlainHttp', request: buildPlainHttp(req) };\n}\n\n/**\n * Preflight check — does the request body carry a `_meta.proof.jws`\n * string that `parseJwsPayloadStruct` cannot project into a typed\n * `McpIPayload`?\n *\n * The caller declared intent (an KYA-OS envelope) by including the\n * JWS field; structural failure to extract the payload means the\n * envelope is malformed, not absent. Without this preflight, the\n * orchestrator would silently fall through to PlainHttp — pre-#2560\n * that happened to also Block (engine returned `Block(ParseError)`\n * for every PlainHttp), so the regression was invisible; post-#2560\n * the engine's Stage 1 + stub policy returns `Permit` for anonymous\n * PlainHttp and tampered envelopes would be silently accepted.\n *\n * Returns `true` when the orchestrator should synthesize\n * `Block(ParseError)` BEFORE calling `buildAgentRequest`.\n */\nexport function hasMalformedJwsBody(req: IncomingHttpLike): boolean {\n  const parsed = parseBodyAsObject(req.body);\n  if (!parsed || typeof parsed !== 'object') return false;\n  const meta = (parsed as Record<string, unknown>)._meta;\n  if (!meta || typeof meta !== 'object') return false;\n  const proof = (meta as Record<string, unknown>).proof;\n  if (!proof || typeof proof !== 'object') return false;\n  const jws = (proof as Record<string, unknown>).jws;\n  if (typeof jws !== 'string' || jws.length === 0) return false;\n  const raw = utf8Bytes(jws);\n  return parseJwsPayloadStruct(raw) === null;\n}\n\n// -----------------------------------------------------------------------------\n// Identifier extractors — drive conditional pre-fetch in Phase C.2.\n// -----------------------------------------------------------------------------\n\n/**\n * Issuer DID — Stage 1 (identity resolution) targets this. `null`\n * for PlainHttp (anonymous → no DID to resolve) and for an McpI envelope,\n * which the engine refuses without resolving anything.\n *\n * For `HttpSigned`, this is the KYA HTTP Binding `kya=` signature's base\n * DID (see [[extractKyaHttpDid]]) — the #3362 gap this closes: without a\n * pre-fetched `did_doc`, the engine cannot resolve the `keyid` and blocks\n * a validly-signed request with `kyaos/did-unresolvable`.\n * A generic RFC 9421 signature (e.g. ChatGPT's `sig1=` profile) has no\n * `kya` label and stays `null` here, unaffected.\n */\nexport function extractIssuer(request: AgentRequest): string | null {\n  if (request.protocol === 'HttpSigned') return extractKyaHttpDid(request.request.headers);\n  return null;\n}\n\n/**\n * Agent DID — used by ReputationOracle. For `HttpSigned`, the KYA signer IS\n * the subject (no separate `sub` claim on a bare L1 signature), so this\n * returns the same DID as [[extractIssuer]]. `null` otherwise.\n */\nexport function extractAgentDid(request: AgentRequest): string | null {\n  if (request.protocol === 'HttpSigned') return extractKyaHttpDid(request.request.headers);\n  return null;\n}\n\n// -----------------------------------------------------------------------------\n// KYA HTTP Binding (`kya=`, `tag=\"kya-http/2\"`) — Signature-Input keyid → DID.\n// -----------------------------------------------------------------------------\n\n/** draft-kya-http-02 §2.3 — the only two algs the profile accepts. */\nconst KYA_SUPPORTED_ALGS = new Set(['ed25519', 'ecdsa-p256']);\n\n/** Defensive upper bound on the header this parser walks — well above any\n * real `Signature-Input` (RFC 9421 signatures carry a handful of short\n * params), but keeps the scan linear-bounded against a pathological input. */\nconst MAX_SIGNATURE_INPUT_LENGTH = 8192;\n\n/**\n * Extract the base KYA agent DID (fragment stripped) from an `HttpSigned`\n * request's `Signature-Input` header — the pre-fetch hint that lets the\n * orchestrator resolve a `did_doc` BEFORE calling into the engine.\n *\n * Deliberately conservative: returns `null` unless the header\n * unambiguously carries a `kya`-labelled, `tag=\"kya-http/2\"` entry with a\n * supported `alg` and a `did:web:`/`did:key:` DID-URL `keyid` — mirroring\n * the engine's own gating (`signature_input_has_kya_label` +\n * `classify_keyid` in `rust/crates/kya-os-engine/src/tier1/rfc9421/`) so\n * this layer never pre-fetches for a request the engine wouldn't treat as\n * KYA anyway. A miss here just means no pre-fetch (falls through to the\n * `ctx.didDocs`-less path, same as today) — this layer never verifies a\n * signature, so returning the wrong (or no) DID is an availability\n * concern, not a security one; the engine's `sfv`-based parser is the\n * authoritative grammar.\n */\nfunction extractKyaHttpDid(headers: Array<[string, string]>): string | null {\n  const signatureInput = getHeaderFromPairs(headers, 'signature-input');\n  if (!signatureInput || signatureInput.length > MAX_SIGNATURE_INPUT_LENGTH) return null;\n\n  const entryValue = findDictionaryMember(signatureInput, 'kya');\n  if (!entryValue) return null;\n\n  const params = parseInnerListParams(entryValue);\n  if (!params) return null;\n  if (params.tag !== 'kya-http/2') return null;\n  if (!params.alg || !KYA_SUPPORTED_ALGS.has(params.alg)) return null;\n\n  const keyid = params.keyid;\n  if (!keyid) return null;\n  if (!keyid.startsWith('did:web:') && !keyid.startsWith('did:key:')) return null;\n  const fragmentIndex = keyid.indexOf('#');\n  if (fragmentIndex === -1) return null;\n  return keyid.slice(0, fragmentIndex);\n}\n\n/**\n * Split `input` on `delimiter` at depth 0 — i.e. never inside `(...)` or a\n * `\"...\"` quoted string (RFC 8941 escapes `\\\"` and `\\\\` inside a quoted\n * string; both are honored so an escaped quote doesn't prematurely close\n * one). A single left-to-right scan, no backtracking — bounded by\n * `input.length` regardless of content.\n */\nfunction splitTopLevel(input: string, delimiter: string): string[] {\n  const parts: string[] = [];\n  let depth = 0;\n  let inQuotes = false;\n  let escaped = false;\n  let current = '';\n  for (const ch of input) {\n    if (escaped) {\n      current += ch;\n      escaped = false;\n      continue;\n    }\n    if (inQuotes) {\n      current += ch;\n      if (ch === '\\\\') escaped = true;\n      else if (ch === '\"') inQuotes = false;\n      continue;\n    }\n    if (ch === '\"') {\n      inQuotes = true;\n      current += ch;\n      continue;\n    }\n    if (ch === '(') {\n      depth += 1;\n      current += ch;\n      continue;\n    }\n    if (ch === ')') {\n      depth = Math.max(0, depth - 1);\n      current += ch;\n      continue;\n    }\n    if (ch === delimiter && depth === 0) {\n      parts.push(current);\n      current = '';\n      continue;\n    }\n    current += ch;\n  }\n  parts.push(current);\n  return parts;\n}\n\n/**\n * Find the Dictionary member named `label` in a `Signature-Input` header\n * (RFC 8941 §3.2) and return its raw value (everything after `label=`).\n * Members are comma-separated at depth 0 — `sig1=(...);..., kya=(...);...`\n * — so a non-`kya`-labelled signature coexisting in the same header (e.g.\n * a vendor `sig1` alongside a `kya` entry) doesn't shadow the lookup.\n */\nfunction findDictionaryMember(header: string, label: string): string | null {\n  for (const rawMember of splitTopLevel(header, ',')) {\n    const member = rawMember.trim();\n    const eq = member.indexOf('=');\n    if (eq === -1) continue;\n    if (member.slice(0, eq).trim() !== label) continue;\n    return member.slice(eq + 1);\n  }\n  return null;\n}\n\n/**\n * Parse a Dictionary member's value — `(<covered-components>);<params>` —\n * into its semicolon-separated parameters. Covered components are\n * discarded (this layer only needs `keyid` / `tag` / `alg`); the engine's\n * `sfv`-based parser is what actually validates the covered set.\n */\nfunction parseInnerListParams(value: string): Record<string, string> | null {\n  const trimmed = value.trim();\n  if (!trimmed.startsWith('(')) return null;\n\n  let depth = 0;\n  let closeIndex = -1;\n  for (let i = 0; i < trimmed.length; i += 1) {\n    const ch = trimmed[i];\n    if (ch === '(') depth += 1;\n    else if (ch === ')') {\n      depth -= 1;\n      if (depth === 0) {\n        closeIndex = i;\n        break;\n      }\n    }\n  }\n  if (closeIndex === -1) return null;\n\n  const params: Record<string, string> = {};\n  for (const rawParam of splitTopLevel(trimmed.slice(closeIndex + 1), ';')) {\n    const param = rawParam.trim();\n    if (!param) continue;\n    const eq = param.indexOf('=');\n    if (eq === -1) continue;\n    const key = param.slice(0, eq).trim();\n    let paramValue = param.slice(eq + 1).trim();\n    if (paramValue.length >= 2 && paramValue.startsWith('\"') && paramValue.endsWith('\"')) {\n      paramValue = paramValue.slice(1, -1).replace(/\\\\(.)/g, '$1');\n    }\n    params[key] = paramValue;\n  }\n  return params;\n}\n\nconst KYA_DELEGATION_HEADER = 'kya-delegation';\n\n/**\n * Standalone draft-kya-http bearer delegation (`Authorization: Bearer <VC-JWT>`)\n * plus its explicit fallback header (`KYA-Delegation`). This intentionally does\n * NOT consume `KYA-OS-Delegation-Credential` when the request is RFC-9421 signed;\n * that path must stay on `HttpSigned` so holder binding is verified.\n */\nexport function extractBearerDelegationCredential(\n  req: IncomingHttpLike\n): BearerDelegationCredentialRef | null {\n  // A saved bearer-eligible VC cannot bypass a presented KYA request proof.\n  // Preserve the signed path even for a malformed or one-sided presentation.\n  if (hasKyaSignatureMember(req.headers)) return null;\n  const candidates = [extractAuthorizationBearer(req), getHeader(req, KYA_DELEGATION_HEADER)];\n  for (const credential of candidates) {\n    if (!credential) continue;\n    const claims = decodeJwsPayloadJson(utf8Bytes(credential));\n    if (!isDelegationCredentialClaims(claims)) continue;\n    return {\n      credential,\n      claims,\n      issuer: readString(claims, 'iss'),\n      agentDid: readString(claims, 'sub'),\n      credentialStatus: extractCredentialStatusFromClaims(claims),\n    };\n  }\n  return null;\n}\n\nfunction extractAuthorizationBearer(req: IncomingHttpLike): string | null {\n  const authz = getHeader(req, 'authorization');\n  if (!authz || !/^bearer\\s/i.test(authz)) return null;\n  const token = authz.slice(6).trim();\n  return token.length > 0 ? token : null;\n}\n\nfunction isDelegationCredentialClaims(raw: unknown): raw is Record<string, unknown> {\n  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false;\n  const claims = raw as Record<string, unknown>;\n  const type = claims.type;\n  if (Array.isArray(type) && type.includes('DelegationCredential')) return true;\n  const vc = claims.vc;\n  if (!vc || typeof vc !== 'object' || Array.isArray(vc)) return false;\n  const subject = (vc as Record<string, unknown>).credentialSubject;\n  if (!subject || typeof subject !== 'object' || Array.isArray(subject)) return false;\n  const delegation = (subject as Record<string, unknown>).delegation;\n  return typeof delegation === 'object' && delegation !== null && !Array.isArray(delegation);\n}\n\n/** A delegation credential's status list, which may sit at either level. */\nfunction extractCredentialStatusFromClaims(\n  claims: Record<string, unknown>\n): CredentialStatusRef | null {\n  const status = readCredentialStatus(claims);\n  if (!status) return null;\n\n  const statusListCredential = readString(status, 'statusListCredential');\n  const index = readStatusIndex(status.statusListIndex);\n  if (!statusListCredential) return null;\n  const url = bareStatusListUrl(statusListCredential);\n  // A VC-JWT's `iss` is its issuer; `vc.issuer` covers a credential without one.\n  const issuer = readString(claims, 'iss') ?? readVcIssuer(claims);\n  return url ? { fetchUrl: url, mapUrl: url, issuer, index } : null;\n}\n\n/**\n * A status index as a number: a non-negative safe integer, or its decimal\n * string (the VC wire form). Anything else is null, which fails closed.\n */\nfunction readStatusIndex(value: unknown): number | null {\n  if (typeof value === 'number') return Number.isSafeInteger(value) && value >= 0 ? value : null;\n  if (typeof value === 'string' && /^(0|[1-9][0-9]{0,15})$/.test(value)) {\n    const index = Number(value);\n    return Number.isSafeInteger(index) ? index : null;\n  }\n  return null;\n}\n\n/** `vc.issuer` (a DID string or an object with an `id`), or null. */\nfunction readVcIssuer(claims: Record<string, unknown>): string | null {\n  const vc = claims.vc;\n  if (!vc || typeof vc !== 'object' || Array.isArray(vc)) return null;\n  const issuer = (vc as Record<string, unknown>).issuer;\n  if (typeof issuer === 'string') return issuer;\n  if (issuer && typeof issuer === 'object' && !Array.isArray(issuer)) {\n    return readString(issuer as Record<string, unknown>, 'id');\n  }\n  return null;\n}\n\nfunction readCredentialStatus(raw: Record<string, unknown>): Record<string, unknown> | null {\n  const direct = raw.credentialStatus;\n  if (direct && typeof direct === 'object') return direct as Record<string, unknown>;\n  return readVcCredentialStatus(raw);\n}\n\nfunction readVcCredentialStatus(raw: Record<string, unknown>): Record<string, unknown> | null {\n  const vc = raw.vc;\n  if (!vc || typeof vc !== 'object') return null;\n  const credentialStatus = (vc as Record<string, unknown>).credentialStatus;\n  if (!credentialStatus || typeof credentialStatus !== 'object') return null;\n  return credentialStatus as Record<string, unknown>;\n}\n\nfunction readString(obj: Record<string, unknown>, key: string): string | null {\n  const value = obj[key];\n  return typeof value === 'string' ? value : null;\n}\n\nfunction bareStatusListUrl(urlOrId: string): string {\n  return urlOrId.split('#')[0] ?? urlOrId;\n}\n\nfunction getHeaderFromPairs(headers: Array<[string, string]>, name: string): string | null {\n  const lowered = name.toLowerCase();\n  for (const [key, value] of headers) {\n    if (key.toLowerCase() === lowered) return value;\n  }\n  return null;\n}\n\n// -----------------------------------------------------------------------------\n// KYA-OS — spec form (`_meta.proof.jws`).\n// -----------------------------------------------------------------------------\n\nfunction tryBuildMcpIFromBody(req: IncomingHttpLike): McpIRequest | null {\n  const parsed = parseBodyAsObject(req.body);\n  if (!parsed) return null;\n  const meta = (parsed as Record<string, unknown>)._meta;\n  if (!meta || typeof meta !== 'object') return null;\n  const proof = (meta as Record<string, unknown>).proof;\n  if (!proof || typeof proof !== 'object') return null;\n  const jws = (proof as Record<string, unknown>).jws;\n  if (typeof jws !== 'string' || jws.length === 0) return null;\n\n  const raw = utf8Bytes(jws);\n  const payload = parseJwsPayloadStruct(raw);\n  if (!payload) return null;\n  return { raw, payload };\n}\n\nfunction parseBodyAsObject(body: unknown): unknown {\n  if (!body) return null;\n  // The bytes check MUST come before the generic `typeof === 'object'`\n  // branch — `typeof <Buffer> === 'object'` in JavaScript, so the\n  // naive ordering would return the raw Buffer instance instead of\n  // a parsed object, and `tryBuildMcpIFromBody` would silently fail\n  // to find `_meta.proof.jws` (which Express middleware passing\n  // `req.body` as a Buffer exercises). Bugbot caught the ordering\n  // on the initial Phase C drop.\n  const bytes = bytesOf(body);\n  if (bytes) {\n    try {\n      return JSON.parse(utf8Text(bytes));\n    } catch {\n      return null;\n    }\n  }\n  if (typeof body === 'string') {\n    try {\n      return JSON.parse(body);\n    } catch {\n      return null;\n    }\n  }\n  if (typeof body === 'object') return body;\n  return null;\n}\n\n// -----------------------------------------------------------------------------\n// KYA-OS — legacy header form (Envelope-1 transition only).\n// -----------------------------------------------------------------------------\n\n/**\n * Pre-Envelope-1, the TS bouncer ships `{protected,payload,signature}`\n * JSON in the `KYA-Delegation` header. Phase 1 reconstructs the\n * compact JWS form (`<protected>.<payload>.<signature>`) so the\n * engine's parser can consume it uniformly.\n *\n * **Two accepted wire shapes** — both produce the same compact-JWS\n * byte string for the engine's parser:\n *   1. JSON envelope: `{\"protected\":\"...\",\"payload\":\"...\",\"signature\":\"...\"}`\n *      (the TS-bouncer pre-Envelope-1 form).\n *   2. Compact JWS: `<protected>.<payload>.<signature>` (the form\n *      consumed by the legacy `checkpoint-wasm`\n *      `verify_mcp_i_proof` function; preserved on the gateway-worker\n *      cutover in Phase-D.9b so third-party agents or custom\n *      integrations shipping compact JWS in the header don't silently\n *      fall through to PlainHttp).\n */\nfunction tryBuildMcpIFromLegacyHeader(req: IncomingHttpLike): McpIRequest | null {\n  const header = getHeader(req, 'kya-delegation');\n  if (!header) return null;\n\n  // Shape 1 — JSON envelope. JSON.parse first because compact JWS is\n  // never valid JSON (starts with base64url, no quotes / braces), so\n  // a malformed envelope rejection has no false positives against\n  // compact-JWS input.\n  let parsed: unknown = undefined;\n  try {\n    parsed = JSON.parse(header);\n  } catch {\n    // Not JSON — try Shape 2 below.\n  }\n  if (parsed && typeof parsed === 'object') {\n    const obj = parsed as Record<string, unknown>;\n    const protectedSeg = obj.protected;\n    const payloadSeg = obj.payload;\n    const signatureSeg = obj.signature;\n    if (\n      typeof protectedSeg === 'string' &&\n      typeof payloadSeg === 'string' &&\n      typeof signatureSeg === 'string'\n    ) {\n      const compact = `${protectedSeg}.${payloadSeg}.${signatureSeg}`;\n      return buildMcpIRequestFromCompact(compact);\n    }\n    // JSON object but not envelope shape — nothing to do, fall\n    // through and return null (don't try Shape 2; a JSON object that\n    // isn't an envelope is unambiguously NOT a compact JWS either).\n    return null;\n  }\n\n  // Shape 2 — compact JWS `<h>.<p>.<s>`. Three base64url segments\n  // separated by dots; payload section is the only one that needs to\n  // parse into structured JSON for the orchestrator's bare-vs-signed\n  // cross-check. Signature verification still happens engine-side.\n  const trimmed = header.trim();\n  if (COMPACT_JWS_PATTERN.test(trimmed)) {\n    return buildMcpIRequestFromCompact(trimmed);\n  }\n  return null;\n}\n\n/**\n * RFC 7515 § 3.1 compact JWS — three base64url segments separated by\n * `.`. We accept the trailing-`=` pad variant too (some JWT libraries\n * emit it) even though canonical JWS strips it.\n */\nconst COMPACT_JWS_PATTERN = /^[A-Za-z0-9_-]+=*\\.[A-Za-z0-9_-]+=*\\.[A-Za-z0-9_-]+=*$/;\n\nfunction buildMcpIRequestFromCompact(compact: string): McpIRequest | null {\n  const raw = utf8Bytes(compact);\n  const payload = parseJwsPayloadStruct(raw);\n  if (!payload) return null;\n  return { raw, payload };\n}\n\n// -----------------------------------------------------------------------------\n// JWS payload extraction — just enough to populate McpIRequest.payload.\n// -----------------------------------------------------------------------------\n\n/**\n * Decode the payload segment of a JWS-compact byte string into the\n * typed `McpIPayload` shape. **Does not verify the signature.** The\n * engine does that (H-1's `verify_mcp_i` Stage 2); this layer just\n * extracts the struct so the engine's bare-vs-signed cross-check\n * has something to compare against.\n *\n * Returns `null` on any structural failure — the orchestrator\n * treats that as \"not a parseable KYA-OS envelope\" and falls\n * through to the next detection branch.\n */\nfunction parseJwsPayloadStruct(rawBytes: readonly number[]): McpIPayload | null {\n  const json = decodeJwsPayloadJson(rawBytes);\n  if (!json || typeof json !== 'object') return null;\n  return projectMcpIPayload(json as Record<string, unknown>);\n}\n\n/**\n * Decode the payload segment of a JWS-compact byte string into raw\n * JSON. Returns `null` on any failure (not 3 segments / not valid\n * base64url / not valid JSON).\n */\nfunction decodeJwsPayloadJson(rawBytes: readonly number[]): unknown {\n  const text = utf8Text(rawBytes);\n  const segments = text.split('.');\n  if (segments.length !== 3) return null;\n  let decoded: Uint8Array;\n  try {\n    decoded = base64UrlDecode(segments[1]);\n  } catch {\n    return null;\n  }\n  try {\n    return JSON.parse(utf8Text(decoded));\n  } catch {\n    return null;\n  }\n}\n\nfunction projectMcpIPayload(raw: Record<string, unknown>): McpIPayload | null {\n  // Defensive: require all eight fields. Returning `null` here\n  // signals \"payload extraction failed\". The orchestrator-level\n  // `hasMalformedJwsBody` preflight (see verify-request.ts /\n  // verify-request-edge.ts) catches that signal when the body\n  // carried a JWS string and synthesizes `Block(ParseError)`\n  // — keeping a malformed envelope from silently degrading to\n  // PlainHttp. We still bail rather than synthesizing a partial\n  // payload here, because letting an incomplete payload through\n  // would mask bare-vs-signed mismatches at engine Stage 2.\n  const aud = raw.aud;\n  const iss = raw.iss;\n  const sub = raw.sub;\n  const nonce = raw.nonce;\n  const sessionId = raw.sessionId;\n  const ts = raw.ts;\n  const requestHash = raw.requestHash;\n  const responseHash = raw.responseHash;\n  if (\n    typeof aud !== 'string' ||\n    typeof iss !== 'string' ||\n    typeof sub !== 'string' ||\n    typeof nonce !== 'string' ||\n    typeof sessionId !== 'string' ||\n    typeof ts !== 'number' ||\n    typeof requestHash !== 'string' ||\n    typeof responseHash !== 'string'\n  ) {\n    return null;\n  }\n  return { aud, iss, sub, nonce, sessionId, ts, requestHash, responseHash };\n}\n\n// -----------------------------------------------------------------------------\n// HTTP-Signed (RFC 9421).\n// -----------------------------------------------------------------------------\n\nfunction buildHttpSigned(req: IncomingHttpLike): HttpSignedRequest {\n  // The KYA HTTP Binding recomputes `Content-Digest` over `body`, and only\n  // treats a request as bodyless when `body` is empty and no digest header\n  // came with it. Without these bytes every body-carrying kya-http/2 request\n  // fails as `kyaos/invalid-signature`. The vendor `sig1` path never reads\n  // `body`, so it stays off that wire.\n  const signedBody = hasKyaSignatureMember(req.headers) ? signedBodyBytes(req) : [];\n  return {\n    raw: bodyAsBytes(req.body),\n    method: req.method,\n    path: req.url,\n    headers: flattenHeaders(req.headers),\n    ...(signedBody.length > 0 ? { body: signedBody } : {}),\n    remoteIp: req.remoteAddress ?? null,\n    signals: req.signals ?? null,\n    sessionVelocity: req.sessionVelocity ?? null,\n  };\n}\n\n/**\n * The bytes a kya-http/2 signature covers. Prefers the host's untouched wire\n * bytes (`rawBody`); otherwise falls back to `body`, which is exact for\n * binary (a `Uint8Array`, `Buffer` or other view) or a string and a JSON\n * re-serialisation for a parsed object. A\n * re-serialised body that differs from what the client sent fails the digest\n * check, so the fallback can only refuse, never admit, a body the client did\n * not sign.\n *\n * A parsed object is never turned into bytes for a request whose framing\n * declares no body: Express body-parser sets `req.body = {}` on every\n * request, and serialising that `{}` would make the engine demand a\n * `Content-Digest` from a signed GET.\n *\n * A non-strict JSON parser (`express.json({ strict: false })`) can yield a\n * bare `false`, `true` or number, which `bodyAsBytes` has no bytes for, so it\n * is serialised as a parsed object is. A `null` body stays \"not read\": hosts\n * pass `null` for a body they never materialised.\n */\nfunction signedBodyBytes(req: IncomingHttpLike): number[] {\n  if (req.rawBody === undefined || req.rawBody === null) {\n    const body: unknown = req.body;\n    if (isParsedBody(body) && !requestDeclaresBody(req.headers)) return [];\n    if (typeof body === 'boolean' || typeof body === 'number') {\n      return utf8Bytes(JSON.stringify(body));\n    }\n    return bodyAsBytes(body);\n  }\n  if (typeof req.rawBody === 'string') return utf8Bytes(req.rawBody);\n  return Array.from(req.rawBody);\n}\n\nfunction isParsedBody(body: unknown): boolean {\n  if (typeof body === 'boolean' || typeof body === 'number') return true;\n  return typeof body === 'object' && body !== null && !(body instanceof Uint8Array);\n}\n\n// -----------------------------------------------------------------------------\n// PlainHttp.\n// -----------------------------------------------------------------------------\n\nfunction buildPlainHttp(req: IncomingHttpLike): PlainHttpRequest {\n  return {\n    raw: bodyAsBytes(req.body),\n    method: req.method,\n    path: req.url,\n    headers: flattenHeaders(req.headers),\n    userAgent: getHeader(req, 'user-agent') ?? null,\n    remoteIp: req.remoteAddress ?? null,\n    signals: req.signals ?? null,\n    sessionVelocity: req.sessionVelocity ?? null,\n    clientIntegrity: req.clientIntegrity ?? null,\n  };\n}\n\n// -----------------------------------------------------------------------------\n// Helpers — header / body normalisation.\n// -----------------------------------------------------------------------------\n\nfunction getHeader(req: IncomingHttpLike, name: string): string | null {\n  const lowered = name.toLowerCase();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (key.toLowerCase() !== lowered) continue;\n    if (Array.isArray(value)) return value[0] ?? null;\n    if (typeof value === 'string') return value;\n  }\n  return null;\n}\n\nfunction flattenHeaders(\n  headers: Record<string, string | string[] | undefined>\n): Array<[string, string]> {\n  const out: Array<[string, string]> = [];\n  for (const [key, value] of Object.entries(headers)) {\n    if (value === undefined) continue;\n    if (Array.isArray(value)) {\n      for (const v of value) out.push([key, v]);\n    } else {\n      out.push([key, value]);\n    }\n  }\n  return out;\n}\n\nfunction bodyAsBytes(body: unknown): number[] {\n  if (!body) return [];\n  const bytes = bytesOf(body);\n  if (bytes) return Array.from(bytes);\n  if (typeof body === 'string') return utf8Bytes(body);\n  if (typeof body === 'object') return utf8Bytes(JSON.stringify(body));\n  return [];\n}\n","/**\n * Shared egress guard for verifier-owned outbound fetches.\n *\n * KYA-OS payloads are attacker controlled until the signature verifies. Any\n * host-side fetch derived from that payload must reject obvious local/private\n * targets before invoking `fetch`.\n */\n\nconst BLOCKED_HOSTNAMES = new Set(['localhost', 'metadata', 'metadata.google.internal']);\n\nexport class UnsafeOutboundUrl extends Error {\n  readonly kind = 'UnsafeOutboundUrl';\n}\n\nexport function assertSafeHttpsUrl(rawUrl: string, label = 'outbound URL'): string {\n  let parsed: URL;\n  try {\n    parsed = new URL(rawUrl);\n  } catch {\n    throw new UnsafeOutboundUrl(`${label} must be a valid URL: ${rawUrl}`);\n  }\n\n  if (parsed.protocol !== 'https:') {\n    throw new UnsafeOutboundUrl(`${label} must use https: ${rawUrl}`);\n  }\n  if (parsed.username || parsed.password) {\n    throw new UnsafeOutboundUrl(`${label} must not contain credentials: ${rawUrl}`);\n  }\n  // #3331: https on 443 only. `URL` drops an explicit `:443` for https, so\n  // any port left here is a non-default one, which would let a caller-chosen\n  // URL probe arbitrary services on a host.\n  if (parsed.port !== '') {\n    throw new UnsafeOutboundUrl(`${label} must use the default https port 443: ${rawUrl}`);\n  }\n\n  const hostname = normalizeHostname(parsed.hostname);\n  if (!hostname || isBlockedHostname(hostname)) {\n    throw new UnsafeOutboundUrl(`${label} targets a local or private host: ${rawUrl}`);\n  }\n\n  return rawUrl;\n}\n\n/**\n * True when a resolved socket address must not be dialed. The Node transport\n * in `safe-get.ts` calls this at connect time on every address a hostname\n * resolves to. Anything that is not a parseable IP address fails closed.\n */\nexport function isBlockedIpAddress(address: string): boolean {\n  const ipv4 = parseIpv4(address);\n  if (ipv4) return isBlockedIpv4(ipv4);\n  if (!address.includes(':')) return true;\n  try {\n    // Same canonical form `URL` gives an IPv6 literal hostname, which is what\n    // `isBlockedIpv6` expects (a zone id such as `%en0` throws: fail closed).\n    return isBlockedIpv6(normalizeHostname(new URL(`https://[${address}]/`).hostname));\n  } catch {\n    return true;\n  }\n}\n\nfunction normalizeHostname(hostname: string): string {\n  let normalized = hostname.trim().toLowerCase();\n  if (normalized.startsWith('[') && normalized.endsWith(']')) {\n    normalized = normalized.slice(1, -1);\n  }\n  while (normalized.endsWith('.')) {\n    normalized = normalized.slice(0, -1);\n  }\n  return normalized;\n}\n\nfunction isBlockedHostname(hostname: string): boolean {\n  if (BLOCKED_HOSTNAMES.has(hostname) || hostname.endsWith('.localhost')) {\n    return true;\n  }\n\n  const ipv4 = parseIpv4(hostname);\n  if (ipv4) {\n    return isBlockedIpv4(ipv4);\n  }\n\n  return isBlockedIpv6(hostname);\n}\n\nfunction parseIpv4(hostname: string): [number, number, number, number] | null {\n  const parts = hostname.split('.');\n  if (parts.length !== 4) return null;\n\n  const octets = parts.map((part) => {\n    if (!/^\\d{1,3}$/.test(part)) return Number.NaN;\n    const value = Number(part);\n    return value >= 0 && value <= 255 ? value : Number.NaN;\n  });\n\n  if (octets.some(Number.isNaN)) return null;\n  return octets as [number, number, number, number];\n}\n\nfunction isBlockedIpv4([a, b, c]: [number, number, number, number]): boolean {\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 && c === 0) || // IETF protocol block; Oracle Cloud metadata 192.0.0.192\n    (a === 198 && (b === 18 || b === 19)) ||\n    a >= 224\n  );\n}\n\nfunction isBlockedIpv6(hostname: string): boolean {\n  if (!hostname.includes(':')) return false;\n\n  // Expand to the 8 16-bit groups so every textual encoding of the same\n  // address (dotted-quad tail, compressed hex pairs, fully expanded) is\n  // judged identically. `URL` itself canonicalizes IPv6 literals to the\n  // compressed hex-pair form (`::ffff:127.0.0.1` becomes `::ffff:7f00:1`)\n  // before this function ever runs, so checking only the dotted textual\n  // form here would never actually fire.\n  const groups = expandIpv6Groups(hostname);\n\n  // IPv4-mapped (::ffff:a.b.c.d) and the deprecated IPv4-compatible\n  // (::a.b.c.d) forms both embed an IPv4 address in the low 32 bits.\n  const top5Zero = groups.slice(0, 5).every((g) => g === 0);\n  if (top5Zero && groups[5] === 0xffff) {\n    return isBlockedIpv4(groupPairToIpv4(groups[6], groups[7]));\n  }\n  if (top5Zero && groups[5] === 0) {\n    // This also rejects :: and ::1 through the existing IPv4 zero-network rule.\n    return isBlockedIpv4(groupPairToIpv4(groups[6], groups[7]));\n  }\n\n  // NAT64 (RFC 6052, 64:ff9b::/96): top 96 bits fixed at\n  // 0064:ff9b:0000:0000:0000:0000, last 32 bits are the embedded IPv4 (e.g.\n  // 64:ff9b::a9fe:a9fe embeds the AWS/GCP/Azure IMDS address\n  // 169.254.169.254). Standard on IPv6-only / DNS64+NAT64 cloud subnets, so\n  // this is a live cloud-metadata SSRF vector, not a theoretical one. Groups\n  // are already fully expanded above, so every compression an attacker's\n  // textual encoding could use collapses to the same check here.\n  if (\n    groups[0] === 0x64 &&\n    groups[1] === 0xff9b &&\n    groups[2] === 0 &&\n    groups[3] === 0 &&\n    groups[4] === 0 &&\n    groups[5] === 0\n  ) {\n    return isBlockedIpv4(groupPairToIpv4(groups[6], groups[7]));\n  }\n\n  // Local-use NAT64 (RFC 8215, 64:ff9b:1::/48): a site's own translator, so\n  // never a public destination. Where the IPv4 sits depends on the prefix\n  // length the site picked (RFC 6052 layouts), so block the whole /48.\n  if (groups[0] === 0x64 && groups[1] === 0xff9b && groups[2] === 1) {\n    return true;\n  }\n\n  // 6to4 (RFC 3056, 2002::/16): groups 1-2 embed the IPv4 A.B.C.D\n  // (group1 = A<<8|B, group2 = C<<8|D). Unlike NAT64/mapped above, groups\n  // 3-7 (SLA ID + interface ID) are attacker- or router-arbitrary, not fixed\n  // at zero, so this checks group[0] alone rather than assuming any\n  // particular trailing shape.\n  if (groups[0] === 0x2002) {\n    return isBlockedIpv4(groupPairToIpv4(groups[1], groups[2]));\n  }\n\n  const firstSegment = groups[0];\n  return (\n    (firstSegment & 0xfe00) === 0xfc00 || // unique local fc00::/7\n    (firstSegment & 0xffc0) === 0xfe80 || // link-local fe80::/10\n    (firstSegment & 0xff00) === 0xff00 // multicast ff00::/8\n  );\n}\n\n/** Splits a pair of 16-bit IPv6 groups into the 4 octets of their embedded IPv4 address. */\nfunction groupPairToIpv4(hi: number, lo: number): [number, number, number, number] {\n  return [(hi >> 8) & 0xff, hi & 0xff, (lo >> 8) & 0xff, lo & 0xff];\n}\n\n/**\n * Expands the canonical IPv6 hostname produced by `URL` into its 8 16-bit\n * groups. The URL parser rejects malformed literals and converts mixed\n * dotted-quad tails to hexadecimal groups before this function runs.\n */\nfunction expandIpv6Groups(hostname: string): number[] {\n  const halves = hostname.split('::');\n  const parseGroups = (segment: string): number[] =>\n    segment === '' ? [] : segment.split(':').map((part) => Number.parseInt(part, 16));\n\n  if (halves.length === 1) return parseGroups(halves[0]);\n\n  const left = parseGroups(halves[0]);\n  const right = parseGroups(halves[1]);\n  const zeroGroups = new Array(8 - left.length - right.length).fill(0);\n  return [...left, ...zeroGroups, ...right];\n}\n","/**\n * Hardened GET for verifier-owned fetches whose URL comes from an\n * attacker-presented request: the did:web document and the status list\n * (#3331). The caller has already passed the URL through `assertSafeHttpsUrl`.\n *\n * - No redirects. Any 3xx is refused: its `Location` was never checked.\n * - The body is capped at `maxBytes`. The read stops as soon as it goes over.\n *   On Node the body is decoded per Content-Encoding first (gzip, deflate,\n *   br), as `fetch` does, and the cap counts decoded bytes.\n * - On Node, the socket only ever connects to an address `isBlockedIpAddress`\n *   accepted: `https.get` runs every A/AAAA answer through a custom `lookup`\n *   and connects to the address that lookup returned. A public-looking\n *   hostname that resolves (or re-resolves, DNS rebinding) to a private,\n *   loopback, link-local, CGNAT or metadata address is refused.\n * - Edge runtimes, Workers, Bun and Deno expose no connect hook, so there the\n *   DNS step is skipped and global `fetch` runs with the other rules. They\n *   are recognized by markers a Node host does not carry. Anything else with\n *   `process.versions.node` is Node, where the check is mandatory: Node\n *   without `process.getBuiltinModule` (before 20.16 / 22.3) is refused\n *   rather than silently fetched without it.\n *\n * Node modules are reached through `process.getBuiltinModule`, never a\n * static import, so the runtime-agnostic `adapters` entry stays loadable on\n * Edge and in Workers (see `rdns-verifier.ts` for the same constraint).\n */\n\nimport type { LookupAddress, LookupOptions } from 'node:dns';\nimport type * as NodeDns from 'node:dns';\nimport type * as NodeHttps from 'node:https';\nimport type * as NodeZlib from 'node:zlib';\n\nimport { isBlockedIpAddress } from './outbound-url-policy';\n\n/** Why `safeGet` refused a fetch. */\nexport type SafeGetRefusal =\n  | 'redirect'\n  | 'too-large'\n  | 'blocked-address'\n  | 'no-address'\n  | 'content-encoding'\n  | 'no-address-check';\n\n/** A redirect, an oversized body, or a blocked address. */\nexport class SafeGetRefused extends Error {\n  readonly kind = 'SafeGetRefused';\n\n  constructor(\n    message: string,\n    readonly reason: SafeGetRefusal\n  ) {\n    super(message);\n  }\n}\n\nexport interface SafeGetResponse {\n  status: number;\n  /** The body for a 2xx; empty for any other status (never read). */\n  body: Uint8Array;\n}\n\nexport interface SafeGetOpts {\n  /** Bounds the whole exchange: connect, headers and body. */\n  signal: AbortSignal;\n  maxBytes: number;\n  /**\n   * A caller-supplied `fetch` is used as-is (with `redirect: 'manual'`, the\n   * size cap and `SAFE_GET_HEADERS`); connect-time address checks are then\n   * the caller's job.\n   */\n  fetch?: typeof fetch;\n}\n\n// Sent on every transport, so a did:web or status-list host sees the same\n// request from Node, Edge and Workers. `https.get` sends no User-Agent or\n// Accept of its own (undici's `fetch` sent `node` and `*/*`), and a WAF or bot\n// filter that refuses a header-less request would otherwise 403 on Node only.\n// Accept still ends in `*/*`, so no host that served the old fetch answers 406.\n// No version and nothing about the operator: one fixed, public identity.\nexport const SAFE_GET_HEADERS: Readonly<Record<'user-agent' | 'accept', string>> = Object.freeze({\n  'user-agent': 'kya-checkpoint-resolver (+https://github.com/Know-That-Ai/checkpoint)',\n  accept: 'application/json, */*;q=0.8',\n});\n\nconst EMPTY = new Uint8Array(0);\n\nexport async function safeGet(url: string, opts: SafeGetOpts): Promise<SafeGetResponse> {\n  try {\n    if (opts.fetch) return await fetchGet(url, opts.fetch, opts);\n    const transport = pickTransport();\n    if (transport === 'fetch') return await fetchGet(url, fetch, opts);\n    if (transport === 'unchecked-node') {\n      warnUncheckedNodeOnce();\n      throw new SafeGetRefused(\n        `refused ${url}: this Node has no process.getBuiltinModule, ` +\n          'so the connect-time address check cannot run; upgrade to Node 20.19+ or 22.12+ or pass your own fetch',\n        'no-address-check'\n      );\n    }\n    return await nodeGet(url, transport, opts);\n  } catch (cause) {\n    // One error shape for \"ran out of time\", whichever layer noticed first.\n    if (opts.signal.aborted && !(cause instanceof SafeGetRefused)) throw abortError(url);\n    throw cause;\n  }\n}\n\nfunction abortError(url: string): Error {\n  const err = new Error(`request aborted: ${url}`);\n  err.name = 'AbortError';\n  return err;\n}\n\nfunction tooLarge(url: string, maxBytes: number): SafeGetRefused {\n  return new SafeGetRefused(`response body exceeds ${maxBytes} bytes: ${url}`, 'too-large');\n}\n\n// -----------------------------------------------------------------------------\n// fetch transport (Edge, Workers, injected fetch).\n// -----------------------------------------------------------------------------\n\nasync function fetchGet(\n  url: string,\n  fetchImpl: typeof fetch,\n  { signal, maxBytes }: SafeGetOpts\n): Promise<SafeGetResponse> {\n  // 'manual', not 'error': Cloudflare Workers reject `redirect: 'error'`.\n  const response = await fetchImpl(url, {\n    signal,\n    redirect: 'manual',\n    headers: { ...SAFE_GET_HEADERS },\n  });\n  // An opaque redirect (browsers, some edge runtimes) reports status 0.\n  if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {\n    await response.body?.cancel().catch(() => {});\n    throw new SafeGetRefused(`redirect refused (HTTP ${response.status}): ${url}`, 'redirect');\n  }\n  if (!response.ok) {\n    await response.body?.cancel().catch(() => {});\n    return { status: response.status, body: EMPTY };\n  }\n  if (Number(response.headers.get('content-length')) > maxBytes) {\n    await response.body?.cancel().catch(() => {});\n    throw tooLarge(url, maxBytes);\n  }\n  return { status: response.status, body: await readCapped(response, url, signal, maxBytes) };\n}\n\n/**\n * Reads the body through a stream reader so the read can stop at `maxBytes`\n * and so an abort settles a pending `read()` (a body that drips forever).\n */\nasync function readCapped(\n  response: Response,\n  url: string,\n  signal: AbortSignal,\n  maxBytes: number\n): Promise<Uint8Array> {\n  if (!response.body) {\n    // A runtime (or test double) without a streaming body.\n    const whole = new Uint8Array(await response.arrayBuffer());\n    if (whole.byteLength > maxBytes) throw tooLarge(url, maxBytes);\n    return whole;\n  }\n  const reader = response.body.getReader();\n  if (signal.aborted) {\n    await reader.cancel().catch(() => {});\n    throw abortError(url);\n  }\n  let aborted = false;\n  const onAbort = (): void => {\n    aborted = true;\n    reader.cancel().catch(() => {});\n  };\n  signal.addEventListener('abort', onAbort);\n  try {\n    const chunks: Uint8Array[] = [];\n    let total = 0;\n    for (;;) {\n      const { done, value } = await reader.read();\n      if (aborted) throw abortError(url);\n      if (done) break;\n      total += value.byteLength;\n      if (total > maxBytes) {\n        await reader.cancel().catch(() => {});\n        throw tooLarge(url, maxBytes);\n      }\n      chunks.push(value);\n    }\n    return concat(chunks, total);\n  } finally {\n    signal.removeEventListener('abort', onAbort);\n  }\n}\n\nfunction concat(chunks: Uint8Array[], total: number): Uint8Array {\n  const out = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    out.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return out;\n}\n\n// -----------------------------------------------------------------------------\n// Node transport: `https.get` with a lookup that refuses blocked addresses.\n// -----------------------------------------------------------------------------\n\ninterface NodeNetModules {\n  https: typeof NodeHttps;\n  dns: typeof NodeDns;\n  zlib: typeof NodeZlib;\n}\n\ntype LookupCallback = (\n  err: NodeJS.ErrnoException | null,\n  address: string | LookupAddress[],\n  family?: number\n) => void;\n\ninterface RuntimeGlobals {\n  process?: {\n    versions?: { node?: unknown; bun?: unknown };\n    getBuiltinModule?: (id: string) => unknown;\n  };\n  navigator?: { userAgent?: unknown };\n  EdgeRuntime?: unknown;\n  Deno?: unknown;\n}\n\n/**\n * Which transport this runtime gets. Non-Node runtimes are matched on\n * markers a Node host does not carry (not on a missing or odd\n * `navigator.userAgent`, which jsdom or a polyfill can set on Node), so a\n * Node host never falls through to an unchecked fetch.\n */\nfunction pickTransport(): NodeNetModules | 'fetch' | 'unchecked-node' {\n  const runtime = globalThis as RuntimeGlobals;\n  const proc = runtime.process;\n  // Workers (nodejs_compat), Bun and Deno expose `process.versions.node` and\n  // `getBuiltinModule` too, but their `node:https` has no connect-time lookup.\n  if (\n    runtime.navigator?.userAgent === 'Cloudflare-Workers' ||\n    typeof runtime.EdgeRuntime === 'string' ||\n    runtime.Deno !== undefined ||\n    proc?.versions?.bun !== undefined ||\n    typeof proc?.versions?.node !== 'string'\n  ) {\n    return 'fetch';\n  }\n  if (typeof proc.getBuiltinModule !== 'function') return 'unchecked-node';\n  const https = proc.getBuiltinModule('node:https') as typeof NodeHttps | undefined;\n  const dns = proc.getBuiltinModule('node:dns') as typeof NodeDns | undefined;\n  const zlib = proc.getBuiltinModule('node:zlib') as typeof NodeZlib | undefined;\n  return https && dns && zlib ? { https, dns, zlib } : 'unchecked-node';\n}\n\n// On `globalThis` under a registered symbol so the CJS and ESM builds (or a\n// duplicate copy of the package) share it: one warning per process.\nconst UNCHECKED_NODE_WARNED = Symbol.for('kya.safeGet.uncheckedNodeWarned');\n\n/**\n * Every did:web and status-list fetch on this host is about to be refused\n * (and each request carrying one answered 503 or blocked). Say why once, so\n * an operator on old Node sees the cause instead of a wall of 503s.\n */\nfunction warnUncheckedNodeOnce(): void {\n  const registry = globalThis as { [UNCHECKED_NODE_WARNED]?: boolean };\n  if (registry[UNCHECKED_NODE_WARNED]) return;\n  registry[UNCHECKED_NODE_WARNED] = true;\n  const version = (globalThis as { process?: { version?: unknown } }).process?.version;\n  console.warn(\n    `[checkpoint] Node ${String(version)} has no process.getBuiltinModule, so the ` +\n      'connect-time address check cannot run: did:web and status-list fetches are refused. ' +\n      'Upgrade to Node 20.19+ or 22.12+, or pass your own fetch to makeResolutionHost.'\n  );\n}\n\n/**\n * Wraps `dns.lookup` so the socket can only connect to checked addresses.\n * One blocked answer refuses the whole host (as the .NET SDK's\n * `SsrfSafeDidFetcher` does), so a mixed public/private record set cannot\n * win a Happy Eyeballs race to the private one.\n */\nexport function makeSafeLookup(lookup: typeof NodeDns.lookup) {\n  return (hostname: string, options: LookupOptions, callback: LookupCallback): void => {\n    lookup(hostname, { ...options, all: true }, (err, addresses) => {\n      if (err) {\n        callback(err, '');\n        return;\n      }\n      const blocked = addresses.find((entry) => isBlockedIpAddress(entry.address));\n      if (blocked || addresses.length === 0) {\n        callback(\n          new SafeGetRefused(\n            `${hostname} resolves to ${blocked ? `blocked address ${blocked.address}` : 'no address'}`,\n            blocked ? 'blocked-address' : 'no-address'\n          ),\n          ''\n        );\n        return;\n      }\n      if (options.all) callback(null, addresses);\n      else callback(null, addresses[0].address, addresses[0].family);\n    });\n  };\n}\n\n/**\n * `https.get` hands back the bytes as sent, while global `fetch` decodes\n * Content-Encoding. A did.json or status list stored gzipped (S3 object\n * metadata, a precompressed CDN object) is sent that way whatever the request\n * asked for, so the Node path decodes the codings fetch decodes. Anything\n * else (an unknown coding, or a stack of them) is refused rather than handed\n * to JSON.parse as bytes.\n */\nfunction makeDecoder(\n  contentEncoding: string | undefined,\n  zlib: typeof NodeZlib,\n  url: string\n): NodeZlib.Gunzip | NodeZlib.Inflate | NodeZlib.BrotliDecompress | null {\n  const coding = (contentEncoding ?? '').trim().toLowerCase();\n  if (coding === '' || coding === 'identity') return null;\n  if (coding === 'gzip' || coding === 'x-gzip') return zlib.createGunzip();\n  if (coding === 'deflate') return zlib.createInflate();\n  if (coding === 'br') return zlib.createBrotliDecompress();\n  throw new SafeGetRefused(`unsupported content-encoding \"${coding}\": ${url}`, 'content-encoding');\n}\n\nfunction nodeGet(\n  url: string,\n  { https, dns, zlib }: NodeNetModules,\n  { signal, maxBytes }: SafeGetOpts\n): Promise<SafeGetResponse> {\n  return new Promise((resolve, reject) => {\n    // `agent: false`: a fresh socket every time, so a pooled socket some\n    // other caller opened without this lookup is never reused.\n    const request = https.get(\n      url,\n      {\n        agent: false,\n        signal,\n        lookup: makeSafeLookup(dns.lookup),\n        headers: { ...SAFE_GET_HEADERS },\n      },\n      (response) => {\n        const status = response.statusCode ?? 0;\n        let decoder: ReturnType<typeof makeDecoder> = null;\n        const refuse = (err: Error): void => {\n          response.destroy();\n          decoder?.destroy();\n          reject(err);\n        };\n        if (status >= 300 && status < 400) {\n          refuse(new SafeGetRefused(`redirect refused (HTTP ${status}): ${url}`, 'redirect'));\n          return;\n        }\n        if (status < 200 || status >= 300) {\n          response.destroy();\n          resolve({ status, body: EMPTY });\n          return;\n        }\n        if (Number(response.headers['content-length']) > maxBytes) {\n          refuse(tooLarge(url, maxBytes));\n          return;\n        }\n        try {\n          decoder = makeDecoder(response.headers['content-encoding'], zlib, url);\n        } catch (err) {\n          refuse(err as Error);\n          return;\n        }\n        // The cap counts decoded bytes, as on the fetch path, so a\n        // compression bomb stops at `maxBytes`.\n        const body = decoder ? response.pipe(decoder) : response;\n        const chunks: Uint8Array[] = [];\n        let total = 0;\n        body.on('data', (chunk: Uint8Array) => {\n          total += chunk.byteLength;\n          if (total > maxBytes) {\n            refuse(tooLarge(url, maxBytes));\n            return;\n          }\n          chunks.push(chunk);\n        });\n        body.on('end', () => resolve({ status, body: concat(chunks, total) }));\n        response.on('error', refuse);\n        decoder?.on('error', refuse);\n      }\n    );\n    request.on('error', reject);\n  });\n}\n","/**\n * The host side of engine-directed resolution: answers the DID documents and\n * status lists the engine names (`Need`), from a cache keyed by need key.\n *\n * The engine owns every trust and freshness rule. This module only fetches\n * what was named, keeps the answers, and reports one outcome per need:\n *\n * - a fetched DID document (`body`, `fetchedAtUnix`, `lastRefreshFailed`);\n * - a status list, verified once per fetch with the engine's\n *   `verifyStatusList` against its issuer's cached DID document;\n * - `pending` until the first fetch attempt for a key has finished;\n * - after that, `failed` with the attempt's reason until a fetch succeeds.\n *\n * Two modes:\n *\n * - `inline`: a miss, or an entry past its maximum age, is fetched before\n *   the answer, within the fetch budget.\n * - `cache-only`: the request path never waits on a fetch. A miss is answered\n *   `pending` and starts a background fetch, so the client's retry after\n *   `kyaos/identity-pending` (503, `Retry-After: 1`) usually finds it; the\n *   owner's `refresh` tick keeps every entry fresh.\n *\n * A host with no memory shared between requests (a Worker isolate) passes a\n * `store`: a fetched DID document or status list is put there as its raw\n * bytes and its fetch time, and an entry this host has never tried is read\n * from it before anything is fetched, so a cold host answers what another\n * already fetched. In cache-only mode an entry past its refresh point, or a\n * failure past the retry wait, is refreshed in the background (the store\n * first, then a fetch), so a host with no `refresh` tick of its own still\n * keeps the entries it is asked for fresh. Background work goes to the\n * caller's `waitUntil` when it passes one.\n *\n * Entries are kept by role, because a request chooses which presenter DIDs it\n * names. Configured roots are pinned. Issuer status lists and presenter DID\n * documents each live in their own bounded table, least recently named\n * evicted first, with a fetch budget per window, so request-chosen DIDs can\n * displace only other presenters and add only a bounded number of fetches.\n *\n * Fetches go through `safeGet`: no redirects, the need's byte cap, a\n * deadline, and on Node a socket that connects only to an address its lookup\n * checked. A caller-supplied `fetch` replaces that transport, and with it the\n * connect-time address check: it must connect only to a vetted public\n * address, refuse redirects, cap the body and enforce a deadline. Edge\n * runtimes and Workers have no connect hook, so there the platform's egress\n * rules are what keep a fetch off private addresses.\n */\n\nimport type {\n  Need,\n  NeedRole,\n  ResourceFailureDetail,\n  ResourceOutcome,\n  StatusListRecord,\n} from '../types';\nimport { assertSafeHttpsUrl, UnsafeOutboundUrl } from './outbound-url-policy';\nimport { safeGet, SafeGetRefused } from './safe-get';\nimport type { StatusListVerifier } from './status-list-cache';\n\n/** One fetch's deadline: connect, headers and body. */\nexport const RESOLUTION_FETCH_TIMEOUT_MS = 3_000;\n/** The window the per-role fetch budget counts in. */\nexport const RESOLUTION_BUDGET_WINDOW_MS = 10_000;\n/** Fetches per window for each request-chosen role. Roots are not budgeted. */\nexport const RESOLUTION_FETCH_BUDGET: Readonly<Record<'issuer' | 'presenter', number>> =\n  Object.freeze({ issuer: 32, presenter: 16 });\n/** Largest number of entries kept for each request-chosen role. */\nexport const RESOLUTION_MAX_ENTRIES: Readonly<Record<'issuer' | 'presenter', number>> =\n  Object.freeze({ issuer: 1024, presenter: 1024 });\n/** A non-root entry is refreshed in the background while it was named this recently. */\nexport const RESOLUTION_ACTIVE_MS = 900_000;\n/** After a failed fetch, an entry is tried again after this long. */\nexport const RESOLUTION_RETRY_MS = 30_000;\n/** The background refresh fetches an entry this far ahead of its maximum age. */\nexport const RESOLUTION_REFRESH_LEAD_MS = 35_000;\n/** A non-root entry no request named for this long is dropped. */\nexport const RESOLUTION_INACTIVE_EVICT_MS = 86_400_000;\n/** Background fetches in flight at once. */\nexport const RESOLUTION_MAX_CONCURRENT_FETCHES = 4;\n\ntype Freshness = 'stale' | 'refresh';\n\n/**\n * Milliseconds after its fetch at which the background refresh fetches an\n * entry again: half its maximum age, or `RESOLUTION_REFRESH_LEAD_MS` before\n * it, whichever is sooner, and never under a second.\n */\nexport function refreshAfterMs(maxAgeSeconds: number): number {\n  const leadSeconds = RESOLUTION_REFRESH_LEAD_MS / 1000;\n  return Math.max(1, Math.min(maxAgeSeconds / 2, maxAgeSeconds - leadSeconds)) * 1000;\n}\n\n/** The engine call a host needs to answer a status-list need. */\nexport interface ResolutionEngine {\n  verifyStatusList: StatusListVerifier;\n}\n\nexport type ResolutionMode = 'inline' | 'cache-only';\n\n/** A fetched resource as a store keeps it: the raw body and when it was fetched. */\nexport interface StoredResource {\n  /** The response body: a DID document's JSON, or a status list's envelope. */\n  body: string;\n  /** Epoch seconds of the fetch that produced `body`. */\n  fetchedAtUnix: number;\n}\n\n/**\n * Persistent storage for fetched resources, keyed by need key, for a host\n * that keeps no memory between requests. A `get` that throws counts as a\n * miss and a `put` that throws is logged; neither fails a request.\n */\nexport interface ResolutionStore {\n  get(key: string): Promise<StoredResource | null>;\n  put(key: string, value: StoredResource): Promise<void>;\n}\n\nexport interface ResolutionHostOptions {\n  mode: ResolutionMode;\n  /**\n   * Replaces `safeGet`'s transport. It must connect only to a vetted public\n   * address, refuse redirects, cap the body and enforce a deadline; the\n   * connect-time address check is then the caller's job.\n   */\n  fetch?: typeof fetch;\n  /** Epoch milliseconds. Defaults to `Date.now`. */\n  now?: () => number;\n  fetchTimeoutMs?: number;\n  logger?: (msg: string) => void;\n  /** Where fetched resources are kept between requests. See {@link ResolutionStore}. */\n  store?: ResolutionStore;\n}\n\n/**\n * The verification a host answers for. The engine judges every answer with the\n * verify call's clock (`opts.clock`), which need not be the host's: a replay or\n * a conformance run pins it to an instant of its own. So what the host hands\n * the engine is in that clock: a resource's fetch time is the call's `nowUnix`\n * less the resource's real age, and a status list fetched for the call is\n * verified, and its expiry judged, at the call's `nowUnix`. The host's own\n * timing (retry delays, budgets, refresh points) stays on its clock.\n */\nexport interface ResolutionCall {\n  /** The `nowUnix` the engine is called with for this request. */\n  nowUnix: number;\n  /**\n   * Keeps the call's background work alive after the response (Cloudflare\n   * Workers' `ctx.waitUntil`). Without it, background fetches run detached.\n   */\n  waitUntil?: (promise: Promise<unknown>) => void;\n}\n\nexport interface ResolutionHost {\n  readonly mode: ResolutionMode;\n  /**\n   * The answers already held for configured roots that an engine would\n   * accept, to send with a request's first call so a request that needs only\n   * roots is decided in one call. Without `call`, in the host's clock.\n   */\n  rootAnswers(call?: ResolutionCall): Record<string, ResourceOutcome>;\n  /**\n   * One outcome per need, from the cache, a fetch, or `pending`. Never throws.\n   * Without `call`, in the host's clock.\n   */\n  answer(\n    needs: readonly Need[],\n    engine: ResolutionEngine,\n    call?: ResolutionCall\n  ): Promise<Record<string, ResourceOutcome>>;\n  /** Track needs without answering them (the configured roots at startup). */\n  register(needs: readonly Need[]): void;\n  /** Keep only these root needs pinned; a root no longer configured is dropped. */\n  setRoots(needs: readonly Need[]): void;\n  /**\n   * Fetch every tracked need that is due, DID documents before status lists,\n   * within the budgets, reading the store first when there is one. Never\n   * throws.\n   */\n  refresh(engine: ResolutionEngine): Promise<void>;\n}\n\ninterface Entry {\n  key: string;\n  need: Need;\n  role: NeedRole;\n  body?: string;\n  record?: StatusListRecord;\n  /** Epoch ms of the latest successful fetch. */\n  fetchedAt?: number;\n  lastRefreshFailed: boolean;\n  /** The latest attempt's failure, cleared by a success. */\n  failure?: ResourceFailureDetail;\n  /** Epoch ms the latest attempt finished. */\n  attemptedAt?: number;\n  inFlight?: Promise<void>;\n  /** The store read in progress for this entry, shared by concurrent callers. */\n  storeRead?: Promise<boolean>;\n  /**\n   * Epoch ms the latest store read finished. The store is read again for this\n   * entry only `RESOLUTION_RETRY_MS` later, so a key the store does not hold\n   * (and the fetch budget skipped) costs one read per wait, not one per request.\n   */\n  storeReadAt?: number;\n  /** Epoch ms a request last named this entry. */\n  namedAt: number;\n}\n\nexport function makeResolutionHost(options: ResolutionHostOptions): ResolutionHost {\n  const now = options.now ?? (() => Date.now());\n  const timeoutMs = options.fetchTimeoutMs ?? RESOLUTION_FETCH_TIMEOUT_MS;\n  const log = options.logger ?? (() => {});\n  const tables: Record<NeedRole, Map<string, Entry>> = {\n    root: new Map(),\n    issuer: new Map(),\n    presenter: new Map(),\n  };\n  let windowStart = Number.NEGATIVE_INFINITY;\n  const spent: Record<'issuer' | 'presenter', number> = { issuer: 0, presenter: 0 };\n\n  function find(key: string): Entry | undefined {\n    return tables.root.get(key) ?? tables.issuer.get(key) ?? tables.presenter.get(key);\n  }\n\n  /** The entry for `need`, created or moved to its role's table and marked named. */\n  function track(need: Need, named: boolean): Entry {\n    const at = now();\n    let entry = find(need.key);\n    if (entry && entry.role !== need.role && (need.role === 'root' || entry.role !== 'root')) {\n      tables[entry.role].delete(entry.key);\n      entry.role = need.role;\n    }\n    if (!entry) {\n      entry = { key: need.key, need, role: need.role, lastRefreshFailed: false, namedAt: at };\n    }\n    entry.need = need;\n    if (named) entry.namedAt = at;\n    const table = tables[entry.role];\n    // Re-inserting moves the key to the end: Map order is least recently named first.\n    table.delete(entry.key);\n    table.set(entry.key, entry);\n    if (entry.role !== 'root') evictOver(entry.role);\n    return entry;\n  }\n\n  function evictOver(role: 'issuer' | 'presenter'): void {\n    const table = tables[role];\n    for (const victim of table.values()) {\n      if (table.size <= RESOLUTION_MAX_ENTRIES[role]) return;\n      if (!victim.inFlight) table.delete(victim.key);\n    }\n  }\n\n  function spend(role: NeedRole): boolean {\n    if (role === 'root') return true;\n    const at = now();\n    if (at < windowStart || at - windowStart >= RESOLUTION_BUDGET_WINDOW_MS) {\n      windowStart = at;\n      spent.issuer = 0;\n      spent.presenter = 0;\n    }\n    if (spent[role] >= RESOLUTION_FETCH_BUDGET[role]) return false;\n    spent[role] += 1;\n    return true;\n  }\n\n  function ageMs(entry: Entry): number {\n    return entry.fetchedAt === undefined ? Number.POSITIVE_INFINITY : now() - entry.fetchedAt;\n  }\n\n  /** The `nowUnix` the engine judges with: the call's, else the host's. */\n  function engineNowUnix(call: ResolutionCall | undefined): number {\n    return call?.nowUnix ?? Math.floor(now() / 1000);\n  }\n\n  /**\n   * Whether `entry` holds a resource younger than `when` allows: `stale`, the\n   * need's maximum age (what the engine accepts), or `refresh`, the instant the\n   * background refresh fetches it again.\n   */\n  function isFresh(entry: Entry, when: Freshness = 'stale', call?: ResolutionCall): boolean {\n    if (entry.body === undefined && entry.record === undefined) return false;\n    const limitMs =\n      when === 'stale' ? entry.need.maxAgeSeconds * 1000 : refreshAfterMs(entry.need.maxAgeSeconds);\n    if (ageMs(entry) >= limitMs) return false;\n    // A list's own expiry is an instant the engine checks in its clock.\n    return entry.record === undefined || entry.record.expiresAt > engineNowUnix(call);\n  }\n\n  /** Whether a fetch of `entry` should start now. */\n  function isDue(entry: Entry, when: Freshness, call?: ResolutionCall): boolean {\n    if (entry.inFlight) return false;\n    if (entry.attemptedAt === undefined) return true;\n    if (isFresh(entry, when, call)) return false;\n    // Past its age or never fetched: a failed attempt waits before the next.\n    return entry.failure === undefined || now() - entry.attemptedAt >= RESOLUTION_RETRY_MS;\n  }\n\n  function outcomeOf(entry: Entry, call?: ResolutionCall): ResourceOutcome {\n    // The fetch time in the engine's clock: its real age, back from `nowUnix`.\n    const fetchedAtUnix =\n      entry.fetchedAt === undefined\n        ? 0\n        : call\n          ? call.nowUnix - Math.floor(ageMs(entry) / 1000)\n          : Math.floor(entry.fetchedAt / 1000);\n    if (entry.body !== undefined) {\n      return {\n        ok: true,\n        body: entry.body,\n        fetchedAtUnix,\n        lastRefreshFailed: entry.lastRefreshFailed,\n      };\n    }\n    // A status list is never used past its maximum age, so a failed refresh\n    // of a stale list answers the failure.\n    if (\n      entry.record !== undefined &&\n      (entry.failure === undefined || isFresh(entry, 'stale', call))\n    ) {\n      return { ok: true, record: entry.record, fetchedAtUnix };\n    }\n    if (entry.failure !== undefined) return { ok: false, reason: 'failed', detail: entry.failure };\n    return { ok: false, reason: 'pending' };\n  }\n\n  /** The entries tracking `did`'s DID document, in whichever role holds it. */\n  function documentEntries(did: string | undefined): Entry[] {\n    if (!did) return [];\n    const found: Entry[] = [];\n    for (const table of Object.values(tables)) {\n      for (const entry of table.values()) {\n        if (entry.need.kind === 'did-document' && entry.need.did === did) found.push(entry);\n      }\n    }\n    return found;\n  }\n\n  /** The cached body of `did`'s DID document, from whichever role holds it. */\n  function documentBody(did: string | undefined): string | null {\n    return documentEntries(did).find((entry) => entry.body !== undefined)?.body ?? null;\n  }\n\n  function start(entry: Entry, engine: ResolutionEngine, call?: ResolutionCall): Promise<void> {\n    if (entry.inFlight) return entry.inFlight;\n    const run = (async () => {\n      try {\n        if (entry.need.kind === 'did-document') {\n          const body = await fetchText(entry.need, options.fetch, timeoutMs);\n          entry.body = body;\n          entry.fetchedAt = now();\n          entry.lastRefreshFailed = false;\n          entry.failure = undefined;\n          await persist(entry, body);\n        } else {\n          const envelope = await fetchText(entry.need, options.fetch, timeoutMs);\n          entry.record = await verifyStatusListEnvelope(\n            entry.need,\n            envelope,\n            documentBody(entry.need.issuer),\n            engine,\n            engineNowUnix(call)\n          );\n          entry.fetchedAt = now();\n          entry.failure = undefined;\n          await persist(entry, envelope);\n        }\n      } catch (cause) {\n        const detail = failureDetail(cause);\n        entry.failure = detail;\n        entry.lastRefreshFailed = entry.body !== undefined;\n        log(\n          `[checkpoint] resolution fetch failed (${detail}): ${entry.need.url}: ${String(cause)}`\n        );\n      } finally {\n        entry.attemptedAt = now();\n        entry.inFlight = undefined;\n      }\n    })();\n    entry.inFlight = run;\n    return run;\n  }\n\n  /** Put a fetched resource in the store, with the fetch's own time. */\n  async function persist(entry: Entry, body: string): Promise<void> {\n    if (!options.store || entry.fetchedAt === undefined) return;\n    try {\n      await options.store.put(entry.key, {\n        body,\n        fetchedAtUnix: Math.floor(entry.fetchedAt / 1000),\n      });\n    } catch (cause) {\n      log(`[checkpoint] resolution store put failed: ${entry.need.url}: ${String(cause)}`);\n    }\n  }\n\n  /**\n   * Take a stored resource for `entry` when it was fetched after what the\n   * entry holds. A stored status list is verified again first, at the call's\n   * `nowUnix`, against its issuer's document, and not used when the engine\n   * rejects it or the issuer has no document yet. The stored fetch time is\n   * the host's clock, like the entry's.\n   */\n  async function adopt(\n    entry: Entry,\n    stored: StoredResource,\n    engine: ResolutionEngine,\n    call: ResolutionCall | undefined\n  ): Promise<boolean> {\n    const fetchedAt = stored.fetchedAtUnix * 1000;\n    if (entry.fetchedAt !== undefined && fetchedAt <= entry.fetchedAt) return false;\n    if (entry.need.kind === 'did-document') {\n      entry.body = stored.body;\n      entry.lastRefreshFailed = false;\n    } else {\n      const issuerDocument = documentBody(entry.need.issuer);\n      if (issuerDocument === null) return false;\n      try {\n        entry.record = await verifyStatusListEnvelope(\n          entry.need,\n          stored.body,\n          issuerDocument,\n          engine,\n          engineNowUnix(call)\n        );\n      } catch (cause) {\n        log(`[checkpoint] stored status list not used: ${entry.need.url}: ${String(cause)}`);\n        return false;\n      }\n    }\n    entry.fetchedAt = fetchedAt;\n    entry.failure = undefined;\n    entry.attemptedAt = now();\n    return true;\n  }\n\n  /**\n   * Read `entry` from the store, one read at a time per entry and at most one\n   * per `RESOLUTION_RETRY_MS`. A status list whose issuer has no document yet\n   * is not read: like a fetch, it waits for a later call. Never throws.\n   */\n  function readStore(\n    entry: Entry,\n    engine: ResolutionEngine,\n    call: ResolutionCall | undefined\n  ): Promise<boolean> {\n    const store = options.store;\n    if (!store) return Promise.resolve(false);\n    if (entry.need.kind === 'status-list' && documentBody(entry.need.issuer) === null) {\n      return Promise.resolve(false);\n    }\n    if (entry.storeRead) return entry.storeRead;\n    if (entry.storeReadAt !== undefined && now() - entry.storeReadAt < RESOLUTION_RETRY_MS) {\n      return Promise.resolve(false);\n    }\n    const read = (async () => {\n      try {\n        const stored = await store.get(entry.key);\n        if (\n          !stored ||\n          typeof stored.body !== 'string' ||\n          typeof stored.fetchedAtUnix !== 'number' ||\n          !Number.isFinite(stored.fetchedAtUnix)\n        ) {\n          return false;\n        }\n        return await adopt(entry, stored, engine, call);\n      } catch (cause) {\n        log(`[checkpoint] resolution store read failed: ${entry.need.url}: ${String(cause)}`);\n        return false;\n      } finally {\n        entry.storeReadAt = now();\n      }\n    })();\n    entry.storeRead = read;\n    void read.finally(() => {\n      if (entry.storeRead === read) entry.storeRead = undefined;\n    });\n    return read;\n  }\n\n  /**\n   * Read the store for the entries this host has never tried, DID documents\n   * before status lists so a stored list is verified against its issuer's\n   * stored document.\n   */\n  async function hydrate(\n    entries: readonly Entry[],\n    engine: ResolutionEngine,\n    call: ResolutionCall | undefined\n  ): Promise<void> {\n    if (!options.store) return;\n    const cold = (kind: Need['kind']) =>\n      entries.filter(\n        (entry) =>\n          entry.need.kind === kind &&\n          entry.body === undefined &&\n          entry.record === undefined &&\n          entry.attemptedAt === undefined &&\n          !entry.inFlight\n      );\n    await Promise.all(cold('did-document').map((entry) => readStore(entry, engine, call)));\n    await Promise.all(cold('status-list').map((entry) => readStore(entry, engine, call)));\n  }\n\n  /**\n   * Bring the due entries up to date: a newer copy in the store when there is\n   * one, otherwise a fetch within the budgets.\n   */\n  async function refreshEntries(\n    entries: readonly Entry[],\n    engine: ResolutionEngine,\n    when: Freshness,\n    call?: ResolutionCall\n  ): Promise<void> {\n    if (options.store) {\n      const due = (kind: Need['kind']) =>\n        entries.filter((entry) => entry.need.kind === kind && isDue(entry, when, call));\n      await Promise.all(due('did-document').map((entry) => readStore(entry, engine, call)));\n      await Promise.all(due('status-list').map((entry) => readStore(entry, engine, call)));\n    }\n    await fetchDue(entries, engine, when, call);\n  }\n\n  /** Run background work under the call's `waitUntil`, or detached. */\n  function inBackground(work: Promise<void>, call: ResolutionCall | undefined): void {\n    const guarded = work.catch(() => {});\n    if (call?.waitUntil) {\n      try {\n        call.waitUntil(guarded);\n      } catch {\n        // A waitUntil that throws leaves the work running detached.\n      }\n    }\n  }\n\n  /** Start every due entry the budget allows, DID documents first, at most `RESOLUTION_MAX_CONCURRENT_FETCHES` at once. */\n  async function fetchDue(\n    entries: readonly Entry[],\n    engine: ResolutionEngine,\n    when: Freshness,\n    call?: ResolutionCall\n  ) {\n    // A list is verified against its issuer's document, so lists are picked\n    // after the documents: those this call fetched, and any fetch of an\n    // issuer's document another call already started. A list whose issuer\n    // still has no document is left for a later call, unattempted and\n    // unbudgeted, so it is never rejected for want of one.\n    const due = (kind: Need['kind']) =>\n      entries.filter(\n        (entry) =>\n          entry.need.kind === kind &&\n          isDue(entry, when, call) &&\n          (kind === 'did-document' || documentBody(entry.need.issuer) !== null) &&\n          spend(entry.role)\n      );\n    await runBounded(due('did-document'), (entry) => start(entry, engine, call));\n    const issuerFetches = entries\n      .filter((entry) => entry.need.kind === 'status-list')\n      .flatMap((entry) => documentEntries(entry.need.issuer))\n      .map((document) => document.inFlight)\n      .filter((running) => running !== undefined);\n    await Promise.all(issuerFetches);\n    await runBounded(due('status-list'), (entry) => start(entry, engine, call));\n  }\n\n  async function runBounded(entries: readonly Entry[], fn: (entry: Entry) => Promise<void>) {\n    let cursor = 0;\n    const worker = async (): Promise<void> => {\n      while (cursor < entries.length) await fn(entries[cursor++]!);\n    };\n    await Promise.all(\n      Array.from({ length: Math.min(RESOLUTION_MAX_CONCURRENT_FETCHES, entries.length) }, worker)\n    );\n  }\n\n  return {\n    mode: options.mode,\n\n    rootAnswers(call) {\n      const out: Record<string, ResourceOutcome> = {};\n      for (const entry of tables.root.values()) {\n        const usable =\n          isFresh(entry, 'stale', call) ||\n          (entry.body !== undefined &&\n            entry.lastRefreshFailed &&\n            ageMs(entry) < entry.need.maxStaleSeconds * 1000);\n        if (usable) out[entry.key] = outcomeOf(entry, call);\n      }\n      return out;\n    },\n\n    async answer(needs, engine, call) {\n      const entries = needs.map((need) => track(need, true));\n      await hydrate(entries, engine, call);\n      if (options.mode === 'inline') {\n        await fetchDue(entries, engine, 'stale', call);\n      } else {\n        // A miss the store did not answer, and an entry past its refresh point\n        // (a quiet period can outlast the background refresh's active window),\n        // is brought up to date in the background now, from a newer stored\n        // copy or a fetch, so the client's retry finds it, as a miss's does.\n        const due = entries.filter((entry) => isDue(entry, 'refresh', call));\n        if (due.length > 0) {\n          inBackground(refreshEntries(due, engine, 'refresh', call), call);\n        }\n      }\n      // Wait for a fetch another request already started for the same key.\n      if (options.mode === 'inline') {\n        await Promise.all(entries.map((entry) => entry.inFlight).filter(Boolean));\n      }\n      const out: Record<string, ResourceOutcome> = {};\n      for (const entry of entries) out[entry.key] = outcomeOf(entry, call);\n      return out;\n    },\n\n    register(needs) {\n      for (const need of needs) track(need, false);\n    },\n\n    setRoots(needs) {\n      const keep = new Set(needs.map((need) => need.key));\n      for (const key of [...tables.root.keys()]) {\n        if (!keep.has(key)) tables.root.delete(key);\n      }\n      for (const need of needs) track(need, false);\n    },\n\n    async refresh(engine) {\n      const at = now();\n      for (const role of ['issuer', 'presenter'] as const) {\n        for (const entry of [...tables[role].values()]) {\n          if (at - entry.namedAt > RESOLUTION_INACTIVE_EVICT_MS && !entry.inFlight)\n            tables[role].delete(entry.key);\n        }\n      }\n      const active = [\n        ...tables.root.values(),\n        ...[...tables.issuer.values(), ...tables.presenter.values()].filter(\n          (entry) => at - entry.namedAt <= RESOLUTION_ACTIVE_MS\n        ),\n      ];\n      try {\n        await refreshEntries(active, engine, 'refresh');\n      } catch (cause) {\n        log(`[checkpoint] resolution refresh failed: ${String(cause)}`);\n      }\n    },\n  };\n}\n\n// -----------------------------------------------------------------------------\n// Transport.\n// -----------------------------------------------------------------------------\n\n/** A fetch that produced no usable resource, with the reason the engine is told. */\nexport class ResourceFetchError extends Error {\n  readonly kind = 'ResourceFetchError';\n\n  constructor(\n    readonly detail: ResourceFailureDetail,\n    message: string\n  ) {\n    super(message);\n  }\n}\n\nfunction failureDetail(cause: unknown): ResourceFailureDetail {\n  if (cause instanceof ResourceFetchError) return cause.detail;\n  if (cause instanceof UnsafeOutboundUrl) return 'unsafe-address';\n  if (cause instanceof SafeGetRefused) {\n    switch (cause.reason) {\n      case 'redirect':\n        return 'http-status';\n      case 'too-large':\n        return 'too-large';\n      case 'blocked-address':\n      case 'no-address-check':\n        return 'unsafe-address';\n      case 'content-encoding':\n        return 'rejected';\n      case 'no-address':\n        return 'network';\n    }\n  }\n  if (cause instanceof Error && cause.name === 'AbortError') return 'timeout';\n  return 'network';\n}\n\n/** The response body at `need.url` as text, within the need's byte cap. */\nasync function fetchText(\n  need: Pick<Need, 'url' | 'maxBytes'>,\n  fetchImpl: typeof fetch | undefined,\n  timeoutMs: number\n): Promise<string> {\n  const url = assertSafeHttpsUrl(need.url, 'resolution URL');\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), timeoutMs);\n  try {\n    const response = await safeGet(url, {\n      signal: controller.signal,\n      maxBytes: need.maxBytes,\n      fetch: fetchImpl,\n    });\n    if (response.status < 200 || response.status >= 300) {\n      throw new ResourceFetchError('http-status', `HTTP ${response.status} at ${url}`);\n    }\n    return new TextDecoder().decode(response.body);\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\n/**\n * Verify a status-list need's envelope with the engine against its issuer's\n * DID document, at `nowUnix` in the engine's clock. A list the engine rejects\n * is `rejected`.\n */\nasync function verifyStatusListEnvelope(\n  need: Need,\n  envelope: string,\n  issuerDocument: string | null,\n  engine: ResolutionEngine,\n  nowUnix: number\n): Promise<StatusListRecord> {\n  const result = await engine.verifyStatusList(\n    JSON.stringify({\n      envelope,\n      url: need.url,\n      issuer: need.issuer ?? '',\n      didDocument: issuerDocument,\n      nowUnix,\n    })\n  );\n  if (!result.ok) {\n    throw new ResourceFetchError('rejected', `status list rejected (${result.code}): ${need.url}`);\n  }\n  return {\n    url: result.url,\n    issuer: result.issuer,\n    issuedAt: result.issuedAt,\n    expiresAt: result.expiresAt,\n    setIndices: result.setIndices,\n  };\n}\n","/**\n * TypeScript shapes for the `kya-os-engine` WASM `verify` ABI (E-1).\n *\n * These mirror the Rust types in `rust/crates/kya-os-engine/src/{types,context,signing,error}.rs`.\n *\n * **Wire format is camelCase across every type.** The engine crate\n * carries `#[serde(rename_all = \"camelCase\")]` on every struct with\n * multi-word fields, so JS hosts produce idiomatic camelCase and the\n * cross-runtime parity contract has one convention. The initial E-1\n * drop had an asymmetry (some structs lacked the rename attr) which\n * Bugbot caught at the serde-wasm-bindgen boundary; harmonising the\n * Rust side fixed it without changing any Rust public-API field name.\n *\n * **Do not extend these in this package.** When the engine's surface\n * changes (a re-ratification event), regenerate from the Rust types.\n * Phase 1 host wrappers see what D-design § 6 ratified — nothing more.\n */\n\n// -----------------------------------------------------------------------------\n// AgentRequest — input to verify()\n// -----------------------------------------------------------------------------\n\n// `McpIPayload` lives in `@kya-os/checkpoint-shared` (Sign-1 / #2500).\n// One TS source of truth across the org — Phase A's WASM ABI consumes\n// the same shape that Sign-1's canonical signer produces, so producer +\n// consumer drift can only happen on the Rust side (caught by Sign-1's\n// JCS parity firewall against `reference_payload.jcs`). Re-exported\n// here so existing `import { McpIPayload } from '.../engine'` paths\n// continue to resolve without touching call-sites.\nexport type { DetectionDetail, McpIPayload, TraceStep } from '@kya-os/checkpoint-shared';\nimport type {\n  DetectionDetail,\n  McpIPayload,\n  TraceStep,\n  ProxyAssertion,\n  ProxyCollectionState,\n  IpRoutingType,\n} from '@kya-os/checkpoint-shared';\n\n/**\n * What the edge engine can be instantiated from. On Cloudflare Workers this\n * must be the `WebAssembly.Module` wrangler hands over for a static import of\n * `@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-web/kya_os_engine_bg.wasm`.\n */\nexport type EngineWasmSource = WebAssembly.Module | URL | string | Request | BufferSource;\n\nexport interface McpIRequest {\n  raw: number[]; // bytes; serde sees Vec<u8>\n  payload: McpIPayload;\n}\n\n/**\n * The A2A JSON-RPC payload rides over the same HTTP transport an RFC 9421 or\n * JWT-bearer signature covers, so the shape mirrors {@link HttpSignedRequest}\n * rather than carrying only `raw` bytes — see\n * `docs/architecture/a2a-verification.md`.\n */\nexport interface A2ARequest {\n  raw: number[];\n  method: string;\n  path: string;\n  headers: Array<[string, string]>;\n  body?: number[] | null;\n  remoteIp?: string | null;\n}\n\nexport interface A2PRequest {\n  raw: number[];\n}\n\nexport interface HttpSignedRequest {\n  raw: number[];\n  method: string;\n  path: string;\n  headers: Array<[string, string]>;\n  /**\n   * The request body exactly as the client sent it. The KYA HTTP Binding\n   * (`kya=`, `tag=\"kya-http/2\"`) recomputes the RFC 9530 `Content-Digest`\n   * over these bytes, so a body-carrying signed request that omits them is\n   * refused as `kyaos/invalid-signature`. The vendor `sig1` path never reads\n   * it. Mirrors the Rust `HttpSignedRequest::body`.\n   */\n  body?: number[] | null;\n  /**\n   * Client IP resolved by the host's own trust policy (#4794), mirroring\n   * {@link PlainHttpRequest.remoteIp}. The engine never derives an address\n   * from `headers`, so without this it has none.\n   */\n  remoteIp?: string | null;\n  /**\n   * Mirrors {@link PlainHttpRequest.signals}. A verified signature never\n   * reads them; a signature that fails or is skipped falls through to\n   * classification with them, exactly as the same request unsigned.\n   */\n  signals?: SignalsEnvelope | null;\n  /** Mirrors {@link PlainHttpRequest.sessionVelocity}, read on the same\n   * fall-through as `signals`. */\n  sessionVelocity?: SessionVelocitySignal | null;\n}\n\n/**\n * Reserved ahead of the full signal-versioning registry — a tier\n * cannot be backfilled onto historical records once collected without\n * one. Nothing assigns this yet.\n */\nexport type StabilityTier = 'high' | 'medium' | 'low';\n\n/** One client-collected attribute: a value digest plus its (currently unassigned) stability tier. */\nexport interface ClientSignalAttribute {\n  value: string;\n  stabilityTier?: StabilityTier | null;\n}\n\n/**\n * Transport-layer fingerprint from the terminating proxy. `tlsJa4`\n * sorts extensions before hashing (unlike a raw extensions digest),\n * so it survives Chrome's TLS-extension-order shuffling.\n *\n * `cfBotScore`/`cfVerifiedBot`/`asn`/`asOrganization` (roadmap item 2,\n * spoofed-browser-api-bots PROMPT.md) are Cloudflare bot-management/ASN\n * fields resolved via `resolveBotSignals` (`@kya-os/checkpoint-shared`) —\n * never read off `request.cf` directly, and never forwarded as a header\n * between two different request objects (the exact class of bug PR #4269\n * shipped and #4282 reverted same-day). `cfBotScore` is pre-normalized:\n * Cloudflare's `0` (\"Bot Management did not run\") is absent here, never a\n * real score, only 1-99 are real values. These four fields are Noisy-OR\n * combiner inputs (shadow confidence, persisted evidence). They move the\n * live verdict under `NoisyOrShadowMode`'s `'live'` mode, the default:\n * omit `noisyOrCalibration` to inherit the engine's embedded curve, or\n * pass `null` to fail closed to the static table instead.\n *\n * `tlsCiphersSha1`/`tlsExtensionsSha1` (SW-P20) are Cloudflare's raw TLS\n * client cipher-suite / extension-list hashes, present on every zone\n * regardless of Bot Management, unlike `tlsJa4`, which requires it.\n * `tlsExtensionsSha1` is order-dependent (Chrome has shuffled TLS extension\n * order since early 2023) and is therefore NOT a stable per-client identity\n * key for browser traffic; both are safe as static non-browser-tool\n * deny-list keys in the engine, the same rationale `tlsJa4`'s own deny\n * table already relies on.\n */\nexport interface TransportSignals {\n  tlsJa4?: string | null;\n  /** Akamai HTTP/2 fingerprint from the terminating proxy. */\n  http2Fingerprint?: string | null;\n  httpProtocol?: string;\n  tlsVersion?: string | null;\n  cfBotScore?: number | null;\n  cfVerifiedBot?: boolean | null;\n  asn?: number | null;\n  asOrganization?: string | null;\n  tlsCiphersSha1?: string | null;\n  tlsExtensionsSha1?: string | null;\n}\n\n/**\n * Client-collected entropy, per attribute rather than one blob — a\n * single opaque hash cannot be weighted or debugged when it moves.\n */\nexport interface ClientSignals {\n  attributes: Record<string, ClientSignalAttribute>;\n}\n\n/** Interaction dynamics collected client-side. */\nexport interface BehaviouralSignals {\n  mouseMovements?: number | null;\n  clickCount?: number | null;\n  /** Percentage, 0-100. */\n  scrollDepthPercent?: number | null;\n  timeOnPageMs?: number | null;\n  /** Count of key presses observed on the page. */\n  keyEvents?: number | null;\n  /** Count of touch events observed on the page. */\n  touchEvents?: number | null;\n}\n\n/**\n * Host-verified client-integrity facts for a browser request (the pixel and\n * beacon ingest): the host's own beacon nonce check, and the session verdict\n * of the host's interaction-integrity scorer or its latch. Deliberately NOT a\n * field of {@link SignalsEnvelope}, which carries what the client reported:\n * these are the host's findings about that client. A failed nonce classifies\n * the request as a bot; an `agent-driven` verdict keeps it from being called\n * human. `verdict` is a string so a newer scorer vocabulary never fails\n * verification: a value the engine doesn't know counts as absent.\n */\nexport interface ClientIntegrityInput {\n  nonceFailed?: boolean | null;\n  verdict?: 'agent-driven' | 'human' | 'insufficient' | (string & Record<never, never>) | null;\n  scorerVersion?: number | null;\n}\n\n/** Coarse network-path classification for a request's `trueIp`. */\nexport type RoutingType = 'residential' | 'mobile' | 'datacenter' | 'hosting' | 'unknown';\n\n/** Coarse proxy/anonymization category, when {@link ProxyInfo.isProxy} is true. */\nexport type ProxyType = 'vpn' | 'tor' | 'datacenter' | 'residential_proxy' | 'unknown';\n\n/** Host-supplied proxy/anonymization verdict for a request's `trueIp`. */\nexport interface ProxyInfo {\n  isProxy: boolean;\n  proxyIp?: string | null;\n  proxyType: ProxyType;\n  lastDetected?: number | null;\n  /** Provider confidence in the proxy verdict, `0..=100`. */\n  confidence: number;\n}\n\nexport interface IpReputation {\n  attackSource?: boolean;\n  spamSource?: boolean;\n  lists: readonly string[];\n  asOf: number;\n}\n\n/**\n * Host-supplied network / IP-intelligence context for a request's `trueIp`.\n * Absent-safe like the other {@link SignalsEnvelope} families: a request with\n * no network context is the normal case, not an error. Echoed verbatim on\n * {@link VerifyResult.network} and exposed to Cedar as `context.ip_routing_type`\n * / `context.is_proxy` only when supplied.\n */\nexport interface NetworkContext {\n  trueIp?: string | null;\n  asn?: number | null;\n  isp?: string | null;\n  routingType: RoutingType;\n  proxy?: ProxyInfo | null;\n  /**\n   * TypeScript-host evidence, retained in detection rows and extended API read-back.\n   * Older Rust readers do not echo these additive fields.\n   */\n  proxyAssertions?: readonly ProxyAssertion[];\n  proxyCollectionState?: ProxyCollectionState;\n  ipRoutingType?: IpRoutingType;\n  ipReputation?: IpReputation;\n}\n\n/**\n * Optional entropy signals accompanying a {@link PlainHttpRequest}.\n * Absent-safe at every level — a request with no signals is the\n * normal case at the gateway, not an error.\n */\nexport interface SignalsEnvelope {\n  transport?: TransportSignals | null;\n  client?: ClientSignals | null;\n  behavioural?: BehaviouralSignals | null;\n  network?: NetworkContext | null;\n}\n\n/**\n * Edge-computed request-velocity heuristic for the current client within\n * a rolling window (gateway-session-velocity). **Deliberately NOT a\n * field of {@link SignalsEnvelope}** — unlike that envelope, this input\n * also drives the (default-off) dormant-escalation reclassification in\n * `api.rs`. SW-P40: confidence/weight now scale with\n * `requestCountInWindow` (a documented first-pass linear ramp up to a\n * fixed ceiling)\n * instead of the flat `UNCALIBRATED_CONFIDENCE`/`UNCALIBRATED_WEIGHT`\n * (0) the envelope's three producers still use: bestbrian's #4897\n * review found the gateway counted every proxied sub-resource (now\n * fixed), which is what made a real confidence safe to stamp. Mirrors\n * the Rust `kya_os_engine::types::SessionVelocitySignal`.\n */\nexport interface SessionVelocitySignal {\n  /** Requests observed from this client within `windowSeconds`. */\n  requestCountInWindow: number;\n  windowSeconds: number;\n  /** `requestCountInWindow` normalized to a per-minute rate, when cheap\n   * to compute. Omit if not computed. **If supplied, it MUST equal\n   * `requestCountInWindow * 60 / windowSeconds`** (the engine's own\n   * `session_velocity_rate` derives that same value and rejects the WHOLE\n   * signal — not just this field — when a supplied rate disagrees by more\n   * than 0.01; rust/crates/kya-os-engine/src/api.rs). In particular, do NOT\n   * compute this from actual elapsed wall-clock time while reporting a\n   * fixed `windowSeconds` — the two will disagree for almost every real\n   * request (SW-P42 fixed exactly this bug in the gateway producer). When\n   * in doubt, omit it and let the engine derive the rate itself. */\n  requestsPerMinute?: number | null;\n}\n\nexport interface PlainHttpRequest {\n  raw: number[];\n  method: string;\n  path: string;\n  headers: Array<[string, string]>;\n  userAgent?: string | null;\n  remoteIp?: string | null;\n  signals?: SignalsEnvelope | null;\n  /** See {@link SessionVelocitySignal}. Additive; omit when the host\n   * hasn't wired an edge tracker. */\n  sessionVelocity?: SessionVelocitySignal | null;\n  /** See {@link ClientIntegrityInput}. Additive; omit when the host runs no\n   * client-integrity checks. */\n  clientIntegrity?: ClientIntegrityInput | null;\n}\n\nexport type AgentRequest =\n  | { protocol: 'McpI'; request: McpIRequest }\n  | { protocol: 'A2A'; request: A2ARequest }\n  | { protocol: 'A2P'; request: A2PRequest }\n  | { protocol: 'HttpSigned'; request: HttpSignedRequest }\n  | { protocol: 'PlainHttp'; request: PlainHttpRequest };\n\n// -----------------------------------------------------------------------------\n// Decision / BlockReason / suggested actions — output of verify()\n// -----------------------------------------------------------------------------\n\nexport type BlockReason =\n  | { kind: 'Revoked' }\n  | { kind: 'InvalidSignature' }\n  | { kind: 'Unauthenticated' }\n  | { kind: 'Expired' }\n  | { kind: 'OutOfScope'; requested: string; granted: string[] }\n  | { kind: 'LowReputation'; score: number; threshold: number }\n  /**\n   * `policyId` (#3272 PR2): the determining policy's authored Cedar `@id`\n   * annotation — the stable join key into the `policies` index. Optional +\n   * additive; absent on pre-PR2 engines, deny-by-default, and `@id`-less\n   * policies.\n   */\n  | { kind: 'PolicyDenied'; detail: string; policyId?: string }\n  | { kind: 'ParseError'; detail: string }\n  /**\n   * Tier-2 IP+UA cross-match against the vendor SSOT (AIVF-1 Path B\n   * / agent-shield#2639). Emitted by `TieredPolicy` when the request\n   * carries both a vendor-published IP and a matching UA pattern.\n   * `tier` is the tier ordinal (`2` for IP+UA cross-match today;\n   * reserved for future Tier-1 cryptographic attribution).\n   * `confidence` is f32 in `[0.0, 1.0]`.\n   */\n  | { kind: 'AgentAttribution'; vendor: string; tier: number; confidence: number }\n  /**\n   * Tier-3 UA-only pattern match short-circuit (Engine-Tier3-\n   * Ruleset-Wiring-1 / agent-shield#2641). Emitted at Stage 1b when\n   * `EngineConfig.tier3_action == Block` and the request classifies\n   * as KnownAiAgent / AiCrawler / HeadlessBrowser. **Field names are\n   * snake_case on the wire** (no `rename_all` on the Rust enum) —\n   * they mirror the Rust struct field names verbatim.\n   */\n  | { kind: 'Tier3UAMatch'; pattern_id: string; pattern_kind: string; confidence: number };\n\nexport interface ChallengeParams {\n  nonce: string;\n  audience: string;\n  expiresAt: number;\n  algorithmsAccepted: string[];\n  /** Minimum assurance tier demanded by the determining policy. */\n  minAssurance?: 'anonymous' | 'attested-bearer' | 'key-bound' | 'registered' | 'delegated';\n  /** Determining policy's authored Cedar `@id` (#3272 PR2). Optional + additive. */\n  policyId?: string;\n  /**\n   * Which handshake this challenge demands, set by a Cedar\n   * `@challenge_type(...)` annotation. Known values today: `'delegation'`\n   * (the pre-existing MCP-I Level 2+ handshake) | `'browser_integrity'` |\n   * `'human_step_up'`. Kept a loose `string` (like the shared\n   * `ChallengeParamsSchema.challengeType`, not a literal union) so a FUTURE\n   * engine-added kind this host doesn't know yet stays additive rather than\n   * a type mismatch. Absent means `'delegation'`. **Every renderer MUST\n   * treat an absent or unrecognized value as `'delegation'`** — fail closed\n   * to the handshake it already understands, never throw or silently drop\n   * the challenge. See `normalizeChallengeType` in `@kya-os/checkpoint-shared`.\n   */\n  challengeType?: string;\n}\n\nexport interface RedirectTarget {\n  url: string;\n  reason: string;\n  state?: string | null;\n  /** Determining policy's authored Cedar `@id` (#3272 PR2). Optional + additive. */\n  policyId?: string;\n}\n\nexport type SuggestedAction =\n  | { kind: 'UseDifferentScope'; scope: string }\n  | { kind: 'UpdateRequestField'; field: string; acceptedValues: string[] }\n  | { kind: 'UpgradeProtocolVersion'; version: string }\n  | { kind: 'Other'; code: string; detail: string };\n\nexport interface InstructPayload {\n  problem: string;\n  title: string;\n  suggestedActions: SuggestedAction[];\n  /** Determining policy's authored Cedar `@id` (#3272 PR2). Optional + additive. */\n  policyId?: string;\n}\n\nexport type Decision =\n  /**\n   * `policyId` (#3272 PR2): the authored Cedar `@id` of the determining\n   * permit policy — \"which rule admitted this\". Absent on pre-PR2 engines\n   * and non-policy-determined permits.\n   */\n  | { kind: 'Permit'; policyId?: string }\n  | { kind: 'Block'; reason: BlockReason }\n  | { kind: 'Challenge'; params: ChallengeParams }\n  | { kind: 'Redirect'; target: RedirectTarget }\n  | { kind: 'Instruct'; payload: InstructPayload };\n\nexport type EnforcementMode = 'enforce' | 'observe';\n\nexport interface EngineInfo {\n  name: string;\n  version: string;\n  rulesetHash: string;\n  rulesetVersion: string;\n  buildSha?: string;\n  extras?: Record<string, unknown>;\n}\n\n/**\n * The standalone bearer delegation (`Authorization: Bearer <VC-JWT>`) an\n * orchestrator observed on the request, independent of what the engine's own\n * `detectionDetail.metadata` chose to stamp (KYA-1099 W1). TS-host-composed,\n * like `composedBlobHash` above — never produced by the Rust ABI itself.\n *\n * Kept separate from the engine-metadata-derived identity the reporter\n * already builds (`buildReportedIdentity` in `reporter/index.ts`, sourced\n * from `metadata.agent_did` / `metadata.kya_session_id`) rather than folded\n * into it here: that mechanism is sid-gated (kya-http/2 registered\n * sessions) and doesn't carry a delegation `jti`. This field is the carrier\n * for the case that mechanism misses — a plain bearer delegation with no\n * `sid` claim — and the reporter merges the two (see `buildReportedIdentity`\n * doc comment) rather than one replacing the other.\n */\nexport interface BearerDelegationIdentity {\n  /** The delegation credential's `sub` claim, when present. */\n  agentDid?: string;\n  /**\n   * The delegation credential's handle: `vc.id`, else its `jti` claim. The\n   * reported wire field keeps the name `jti`.\n   */\n  jti?: string;\n  /** The delegation credential's `iss` claim, when present. */\n  iss?: string;\n  /** Whether `verifyDelegation` (or the request's overall decision, after any fail-closed demotion) resolved to `Permit`. */\n  verified: boolean;\n}\n\nexport interface VerifyResult {\n  decision: Decision;\n  detectionDetail: DetectionDetail;\n  enforcementMode: EnforcementMode;\n  engineInfo: EngineInfo;\n  /** Per-stage trace from the engine (Layer 1 / #3164). Optional — absent on WASM builds predating this field. */\n  trace?: TraceStep[];\n  /**\n   * Revision pin for the composed bundle that produced `decision` (#3246\n   * PR5): the SSOT-served sha256, set by the middleware when the composed\n   * path ACTED (see checkpoint-express composed-policy apply). The reporter\n   * copies it into `enforcement.composedBlobHash`; joins\n   * `policy_revisions (project_id, policy_id, composed_blob_hash)`.\n   */\n  composedBlobHash?: string;\n  /**\n   * Set by `verifyRequestEdge` (KYA-1099 W1) when the request carried a\n   * standalone bearer delegation. Absent otherwise — every existing caller\n   * that never sees a bearer delegation is unaffected. See\n   * {@link BearerDelegationIdentity}.\n   */\n  bearerDelegationIdentity?: BearerDelegationIdentity;\n  /**\n   * Echo of the host-supplied {@link NetworkContext}, when the request\n   * carried one (`PlainHttpRequest.signals.network`). Absent on every\n   * other protocol and on any `PlainHttp` request that supplied none.\n   */\n  network?: NetworkContext | null;\n  /**\n   * The vendor-key miss this verify raised, already recorded in the\n   * engine's own feed state. A host that runs its vendor-key feed on another\n   * engine instance passes it unchanged to that instance's `feedNoteMiss`;\n   * this package runs one instance and needs nothing. Absent when the verify\n   * raised none.\n   */\n  vendorKeyMiss?: VendorKeyMiss;\n}\n\n// -----------------------------------------------------------------------------\n// VerifyContext — plain-data lookups the WASM glue reads sync.\n// -----------------------------------------------------------------------------\n//\n// The WASM glue (`rust/crates/kya-os-engine/src/wasm.rs`) accepts a\n// `ContextSpec` and builds internal sync-trait adapters over these\n// lookup tables. The TS host pre-fetches every value here BEFORE\n// calling `verify()`; this preserves the sync-engine / async-host\n// invariant (H-1 Kickoff § 4.5).\n\nexport type KeyType = 'Ed25519';\n\nexport interface VerificationMethod {\n  id: string;\n  keyType: KeyType;\n  publicKeyBytes: number[];\n}\n\nexport interface DidDocument {\n  id: string;\n  verificationMethods: VerificationMethod[];\n}\n\n/**\n * The verifiable subset of an A2A Agent Card's `securitySchemes`, already\n * selected and resolved by the host — see\n * `docs/architecture/a2a-verification.md`. Mirrors the Rust\n * `AgentCardSecurityScheme` enum's internally-tagged wire format.\n */\nexport type AgentCardSecurityScheme =\n  | { kind: 'httpMessageSignatures'; keyid: string }\n  | { kind: 'jwtBearer'; keys: VerificationMethod[] }\n  | { kind: 'unverifiable' };\n\n/** A resolved A2A Agent Card. Mirrors the Rust `AgentCard` struct. */\nexport interface AgentCard {\n  name: string;\n  providerOrganization?: string;\n  securityScheme: AgentCardSecurityScheme;\n}\n\nexport interface ContextSpec {\n  didDocs?: Record<string, DidDocument>;\n  /**\n   * Agent Cards the host already resolved (fetched + reduced), keyed by\n   * origin (`https://scheme-and-authority`, no path) — `AgentRequest.A2A`\n   * only. An origin absent from this map fails closed identically to\n   * omitting the field entirely; see `docs/architecture/a2a-verification.md`.\n   *\n   * bestbrian, PR #4987 review 2 P3: keys MUST be the canonical origin the\n   * Rust engine's `canonical_a2a_origin` produces (lowercased, `https://`,\n   * no trailing `/`, no default `:443` port, no userinfo) — the same form\n   * `agent-card-resolver.ts`'s `normalizeOrigin` already keys its own\n   * cache on. A resolver (in any language) that populates this map with\n   * the raw, un-normalized origin fails every A2A lookup silently,\n   * indistinguishable from a genuinely unreachable card. The engine also\n   * caps every card's `name`/`providerOrganization` at 128 chars on its\n   * own deserialization boundary, on top of (never instead of)\n   * `reduceCard`'s cap here.\n   */\n  agentCards?: Record<string, AgentCard>;\n  revoked?: Record<string, number[]>;\n  reputation?: Record<string, number>;\n  tenantDecision: Decision;\n  nowUnix: number;\n  enforcementMode: EnforcementMode;\n  /**\n   * Engine-default behaviour knobs. Omit, or pass `{}`, to take the\n   * customer-onboarding-safe defaults (Tier-3 in Monitor mode —\n   * tenant policy is the arbiter). See [`EngineConfig`].\n   */\n  config?: EngineConfig;\n  /**\n   * Allow-list of trusted Layer-2 delegation root DIDs, forwarded to the\n   * engine's `trusted_delegation_roots`. Empty/omitted ⇒ the engine rejects every\n   * presented delegation (fail closed). The host\n   * resolves this (see `resolveTrustedDelegationRoots` in\n   * `@kya-os/checkpoint-shared`); the runtime never derives it. camelCase\n   * matches the Rust `#[serde(rename_all = \"camelCase\")]` wire key.\n   */\n  trustedDelegationRoots?: string[];\n  /**\n   * This resource server's own org DID — the audience a\n   * DelegationCredential must name on the standalone bearer path\n   * (`engineVerifyDelegation`, `draft-kya-http-02` §4.3(2)). Optional;\n   * absent ⇒ the bearer path fails closed (`kyaos/audience-mismatch`).\n   * Unused by `engineVerify`.\n   */\n  resourceOrgDid?: string;\n  /** Resource-owned HTTP agent-lane requirements, never copied from request headers. */\n  httpDelegation?: {\n    resourceDid: string;\n    requiredScopes: string[];\n    /** Trusted configured HTTPS authority (including non-default port), required for native propagation. */\n    resourceAuthority?: string;\n  };\n  /**\n   * `'engine-directed'`: the engine names every DID document and status list\n   * the request needs and reads them only from `resources`; `didDocs` and\n   * `revoked` are ignored. Absent, the host supplies them up front.\n   */\n  resolution?: ResolutionMode;\n  /** The host's answer to each need, keyed by the need's `key` (engine-directed only). */\n  resources?: Record<string, ResourceOutcome>;\n}\n\n// -----------------------------------------------------------------------------\n// Engine-directed resolution (engine `resolution/wire.rs`).\n// -----------------------------------------------------------------------------\n\nexport type ResolutionMode = 'engine-directed';\n\n/**\n * The most calls a host makes to decide one request in engine-directed mode.\n * A host that answers every need it is given before calling again is decided\n * on its second call; at this bound it stops and fails the request closed as\n * retryable.\n */\nexport const MAX_RESOLUTION_ROUNDS = 3;\n\nexport type NeedKind = 'did-document' | 'status-list';\n\n/**\n * Where a need came from: a configured trusted root's DID document, a status\n * list named after the trust gates passed, or any other DID the request named.\n */\nexport type NeedRole = 'root' | 'issuer' | 'presenter';\n\n/** One resource the engine needs before it decides. */\nexport interface Need {\n  /** `\"<kind>:<url>\"`; answers, caches and in-flight fetches are keyed by it. */\n  key: string;\n  kind: NeedKind;\n  /** The HTTPS URL to fetch, built by the engine. */\n  url: string;\n  role: NeedRole;\n  /** Largest response body to accept, in bytes. */\n  maxBytes: number;\n  /** Age, in seconds, up to which an answer is fresh. */\n  maxAgeSeconds: number;\n  /** Age up to which a DID document is still accepted while its refresh is failing; 0 for status lists. */\n  maxStaleSeconds: number;\n  /** The DID whose document this is (`did-document` only). */\n  did?: string;\n  /** The DID that must have signed the list (`status-list` only). */\n  issuer?: string;\n  /** The list's expected `statusPurpose` (`status-list` only). */\n  purpose?: string;\n}\n\n/** A verified status list: what `verifyStatusList` returned with `ok: true`. */\nexport interface StatusListRecord {\n  url: string;\n  issuer: string;\n  issuedAt: number;\n  expiresAt: number;\n  setIndices: number[];\n}\n\n/** Why a host could not answer a need. */\nexport type ResourceFailureDetail =\n  | 'timeout'\n  | 'http-status'\n  | 'too-large'\n  | 'unsafe-address'\n  | 'network'\n  | 'rejected';\n\n/** The host's answer to one need. */\nexport type ResourceOutcome =\n  | { ok: true; body: string; fetchedAtUnix: number; lastRefreshFailed: boolean }\n  | { ok: true; record: StatusListRecord; fetchedAtUnix: number }\n  | { ok: false; reason: 'pending' }\n  | { ok: false; reason: 'failed'; detail: ResourceFailureDetail };\n\n/** An engine-directed verify: the decision, or the needs to answer first. */\nexport type DirectedVerifyResult = VerifyResult | { needs: Need[] };\n\n/** The engine's `rootNeeds` answer: the trusted roots' DID-document needs. */\nexport type RootNeedsResult = { needs: Need[] } | { error: string };\n\nexport function isNeedsResult(result: DirectedVerifyResult): result is { needs: Need[] } {\n  return 'needs' in result && Array.isArray((result as { needs?: unknown }).needs);\n}\n\n/**\n * Input to the standalone Layer-2-only delegation-verify entry\n * (`engineVerifyDelegation`, `draft-kya-http-02` §4.1/§4.3). Header-agnostic:\n * the host extracts the VC-JWT from wherever it arrived (`Authorization:\n * Bearer`, the `KYA-Delegation:` fallback, the optional `KYA-OS-*` headers, or\n * an MCP param) and passes it in. Mirrors the Rust `DelegationVerifyInput`.\n */\nexport interface DelegationVerifyInput {\n  /** The DelegationCredential as a JWS-compact VC-JWT (§4.2 claims profile). */\n  credential: string;\n  /**\n   * The scopes this action requires — the WHOLE set (§4.3(3) is granted ⊇\n   * required). The credential's granted scopes MUST include every entry, else\n   * `kyaos/scope-insufficient`. Empty set asserts nothing (passes).\n   */\n  requiredScopes: string[];\n  /**\n   * Opt-in `@min_assurance(...)` floor (draft-kya-http-02 §1/§8). When set, a\n   * verified credential whose achieved assurance tier is BELOW this floor is\n   * denied (`kyaos/assurance-insufficient`) — a bearer credential\n   * (`attested-bearer`, no proof-of-possession) cannot satisfy a `key-bound`+\n   * floor (trust-gap G3). Absent = no floor = permit-any-verified (legacy).\n   * Mirrors the Rust `required_min_assurance` (wire: `requiredMinAssurance`).\n   */\n  requiredMinAssurance?: string;\n}\n\n/**\n * Engine-default behaviour knobs the host can opt into. Mirrors the\n * Rust `kya_os_engine::EngineConfig` shape; deserialised by the WASM\n * glue with `#[serde(default)]` so an absent / empty `config` resolves\n * to the safe defaults.\n */\nexport interface EngineConfig {\n  /**\n   * Tier-3 (UA-only pattern match) engine-default action. Defaults to\n   * `'monitor'` — Stage 1 classification flows through to the tenant\n   * policy evaluator, but the engine does NOT short-circuit with its\n   * own `Block { Tier3UAMatch }`. Set to `'block'` when the host\n   * wants the engine to emit an engine-default block for known-agent\n   * UAs before the tenant policy seam (e.g., the bench harness or\n   * customers who've reviewed their traffic and want the calibrated\n   * block without writing a tenant-policy rule).\n   */\n  tier3Action?: Tier3Action;\n  /**\n   * O2: how the Tier 1 verified-vendor arm treats the tenant policy seam.\n   * Defaults to `'enforcePolicy'` — a cryptographically verified vendor\n   * still obeys the tenant's resolved decision. Set to `'bypassPolicy'`\n   * to restore the pre-O2 immediate-permit shortcut. On WASM hosts this\n   * knob has no per-vendor effect — `WasmConstantPolicy` echoes a\n   * pre-resolved `tenantDecision` and ignores `PolicyEvaluationInput`\n   * entirely, so `'enforcePolicy'` here only gates the engine's own\n   * short-circuit, not per-vendor Cedar rules (that needs a WASM policy\n   * seam — see `docs/architecture/D-design-ratification.md` § O2).\n   */\n  tier1PolicyMode?: Tier1PolicyMode;\n  /**\n   * Governs Stage 1's Noisy-OR probability combiner and (since P18)\n   * whether its score drives the live verdict. An earlier draft of the\n   * P18 cutover deleted the static first-match-wins confidence table\n   * this combiner replaced; that was reversed before merge. `'off'` IS\n   * byte-identical to the pre-P16 engine: `'off'` and `'shadow'` both\n   * use the static table for `detectionDetail.confidence`, never the\n   * combiner's score. Only `'live'` reads the combiner, and only once a\n   * `noisyOrCalibration` curve is configured (with no curve it fails\n   * closed to the same static table). `'shadow'`\n   * additionally attaches `shadow_noisy_or_confidence` /\n   * `shadow_scoring_algorithm` (and, with a curve configured, a\n   * `shadow_calibrated_confidence` / `shadow_calibration_method` PREVIEW\n   * of what `'live'` would produce, without applying it) to\n   * `detectionDetail.metadata` under those verbatim (not camelCased)\n   * keys, see `crate::stages::scoring` on the Rust side. Defaults to\n   * `'live'` (the engine's own `EngineConfig::default()`): omit\n   * `noisyOrCalibration` to inherit the engine's embedded curve and move\n   * the verdict, or pass `null` to keep the static table. Never\n   * consulted on the Tier 1 cryptographic-verification\n   * path — a verified signature is dispositive and short-circuits before\n   * Stage 1 (and this flag) is ever reached.\n   */\n  noisyOrShadow?: NoisyOrShadowMode;\n  /**\n   * A fitted Noisy-OR calibration curve, produced offline by\n   * `apps/web/lib/services/detections/calibration` and supplied here.\n   * Drives the live verdict only when `noisyOrShadow` is `'live'`; under\n   * `'off'` / `'shadow'` a curve here has zero effect on\n   * `detectionDetail.confidence` (curve-or-not, both always use the\n   * static confidence table, never the combiner) — `'shadow'` still logs\n   * what the curve WOULD produce as a preview. Omit it to inherit the\n   * engine's embedded production-fitted curve\n   * (`EMBEDDED_NOISY_OR_CALIBRATION` in `context.rs`), which is how every\n   * runtime gets calibrated `'live'` scoring with nothing plumbed. Supply\n   * a curve to override it. Send an explicit `null` to opt out: `'live'`\n   * then fails closed to the static table (the same `confidence` as\n   * `'off'` / `'shadow'`, never the combiner's raw score) and stamps\n   * `shadow_calibration_curve_missing: true` so that degradation isn't\n   * silent. See `crate::stages::calibration` on the\n   * Rust side.\n   */\n  noisyOrCalibration?: CalibrationCurve | null;\n  /**\n   * Session velocity classification for high-volume anonymous traffic\n   * (gateway-session-velocity). **Defaults to `true`** (since SW-P42; was\n   * `false`). When `true`, a valid signal meeting the engine's count and\n   * normalized-rate floors produces a provisional `bot` detail with\n   * confidence `80` before the tenant policy seam runs. It never emits an\n   * engine-default block, and known agent attribution remains unchanged.\n   * See the Rust `EngineConfig.session_velocity_escalation` /\n   * `SessionVelocityEscalation` doc comments for the full contract.\n   */\n  sessionVelocityEscalation?: boolean;\n  /**\n   * Roadmap item 2 (spoofed-browser-api-bots PROMPT.md): the narrow Option\n   * A fix for the zero-evidence branch's Detection-Scanner-Misclassification\n   * gap — a browser UA with strongly contradicting resolved bot-management\n   * evidence (a real Cloudflare bot-management score at or below a low\n   * threshold) classifies `'incomplete_data'` instead of `'human'`.\n   * **Defaults to `'on'`** (since SW-P42; was `'off'`), same rationale as\n   * `sessionVelocityEscalation`: evidence the engine already resolves\n   * should not sit silently discarded by default. Even `'on'`, this only\n   * ever produces `'incomplete_data'` — never a `bot`/`ai_agent`\n   * classification and never an engine-default block on its own; tenant\n   * policy still owns what, if anything, happens with the result. No SDK\n   * caller has a way to request `'off'` through this package today (added\n   * for type completeness — see the Rust `EngineConfig.\n   * scanner_misclassification_hint` / `ScannerMisclassificationHint` doc\n   * comments for the full contract and the explicit rollback path).\n   */\n  scannerMisclassificationHint?: 'on' | 'off';\n  /**\n   * Client-Headless-Engine-Consumption-1 (PR #5072): whether beacon-\n   * collected automation evidence (`checkpoint-beacon`'s\n   * `client.webdriver` / `client.headless` attributes on\n   * {@link ClientSignals.attributes}) escalates the Stage-1 classification\n   * bucket. **Defaults to `'on'`**, same as `sessionVelocityEscalation`\n   * since SW-P42: a beacon-collected automation disclosure left dormant\n   * behind an opt-in flag defeats the point of collecting it. Two tiers:\n   * `client.webdriver === 'true'` (direct disclosure) escalates to\n   * `headlessBrowser` at confidence 80;\n   * `client.headless === 'true'` alone (corroborating evidence only, no\n   * direct disclosure) escalates only to `unknown` at confidence 40 —\n   * weak evidence alone never asserts a confident Bot verdict. Neither\n   * tier overrides an already self-identified class or double-counts an\n   * existing UA-based `headlessBrowser` match. Set to `'off'` to restore\n   * pre-PR-#5072 behaviour: the raw attributes still transport and\n   * persist either way, only the classification escalation stops. See\n   * the Rust `EngineConfig.client_headless_escalation` /\n   * `ClientHeadlessEscalation` doc comments for the full contract.\n   */\n  clientHeadlessEscalation?: 'on' | 'off';\n  /**\n   * Whether an unsigned browser request with client-reported interaction\n   * and nothing pointing the other way classifies as `human` (confidence 85,\n   * `detectionDetail.metadata.detection_basis` `client_interaction`).\n   * Interaction is the engine's own reading of the behavioural counts: more\n   * than 5 mouse moves, any click, key press or touch, or a scroll depth over\n   * 10% of the page. **Defaults to `'on'`.** `'off'` is \"human only when\n   * proven\": such requests stay `incomplete_data`. See the Rust\n   * `EngineConfig.client_interaction_human` doc comment for the full rule.\n   */\n  clientInteractionHuman?: 'on' | 'off';\n  /**\n   * Whether an automation tool's default viewport (`screen.viewport`\n   * 800x600) with reported behaviour and no interaction classifies an\n   * unsigned browser request as a bot at confidence 70. A request without\n   * behaviour data is never a tell. **Defaults to `'on'`.**\n   */\n  clientViewportTell?: 'on' | 'off';\n}\n\n/**\n * Tier-3 default action — `'monitor'` (default) lets tenant policy\n * decide; `'block'` opts into the engine-default short-circuit.\n */\nexport type Tier3Action = 'monitor' | 'block';\n\n/**\n * Noisy-OR scoring mode. `'off'` and `'shadow'` both drive\n * `detectionDetail.confidence` with the static first-match-wins\n * confidence table, byte-identical to the pre-P16 engine — `'shadow'`\n * additionally logs the combiner's score (and a calibration preview) to\n * metadata, without applying either to the live verdict. `'live'` (P18)\n * is the default and the only mode that reads the combiner for the live\n * verdict: it applies a configured `noisyOrCalibration` curve, and with no\n * curve it fails closed to the same static table. See\n * `EngineConfig.noisyOrShadow`'s doc comment for the full P18 history.\n */\nexport type NoisyOrShadowMode = 'off' | 'shadow' | 'live';\n\n/**\n * A fitted Noisy-OR calibration mapping (P17). Mirrors the Rust\n * `kya_os_engine::CalibrationCurve` wire shape field-for-field (internally\n * tagged on `method`) — which itself mirrors TS `CalibrationCurve` from\n * `apps/web/lib/services/detections/calibration/types.ts`. This is the\n * SAME shape `fitCalibration()`'s `FitCalibrationReport.curve` produces,\n * so a fitted curve can be passed here without translation.\n */\nexport type CalibrationCurve = PlattCurve | IsotonicCurve;\n\n/** Sigmoid: `P(automated | score) = 1 / (1 + exp(a * score + b))`. */\nexport interface PlattCurve {\n  method: 'platt';\n  params: { a: number; b: number };\n}\n\n/**\n * Non-decreasing step function over the raw score, ordered by `minScore`\n * ascending. `maxScore` is informational — the engine selects by\n * `minScore` alone (flat, right-continuous extrapolation), matching TS\n * `predictIsotonic`.\n */\nexport interface IsotonicCurve {\n  method: 'isotonic';\n  blocks: ReadonlyArray<{ minScore: number; maxScore: number; probability: number }>;\n}\n\n/**\n * O2 default-action knob — `'enforcePolicy'` (default) routes a Tier 1\n * verified vendor through the tenant policy seam; `'bypassPolicy'` restores\n * the pre-O2 immediate-permit shortcut.\n */\nexport type Tier1PolicyMode = 'enforcePolicy' | 'bypassPolicy';\n\n// ─────────────────────────────────────────────────── signed rule bundle ──\n// Mirrors the report `RuleBundleRuntime::apply_json` returns (rust/crates/\n// kya-os-engine/src/rule_bundle.rs). `code` is the stable discriminant of `BundleError::code`,\n// so alerting keys on it rather than on prose.\n\n/** Why the engine refused a bundle. Compiled-in data stays in effect. */\nexport type RuleBundleRejectionCode =\n  | 'too-large'\n  | 'invalid-clock'\n  | 'malformed-envelope'\n  | 'unsupported-envelope'\n  | 'unknown-key'\n  | 'key-not-valid'\n  | 'bad-signature'\n  | 'malformed-payload'\n  | 'unsupported-schema'\n  | 'expired'\n  | 'not-yet-valid'\n  | 'invalid-window'\n  | 'invalid-key-set'\n  | 'invalid-delegation'\n  | 'invalid-version'\n  | 'rollback'\n  | 'invalid-ranges'\n  | 'too-many-entries';\n\nexport interface KeySetOutcome {\n  kind: 'added' | 'extended' | 'shortened' | 'unchanged' | 'retired';\n  keyid: string;\n  previousExp?: number;\n  newExp?: number;\n}\n\nexport interface ReinstateExtendedOutcome {\n  kind: 'extended';\n  keyid: string;\n  previousExp: number;\n  newExp: number;\n}\n\nexport interface ReinstateUnchangedOutcome {\n  kind: 'unchanged';\n  keyid: string;\n}\n\nexport type ReinstateRefusalReason =\n  | 'unknown_keyid'\n  | 'key_material_changed'\n  | 'validity_window_changed'\n  | 'expiry_regression'\n  | 'malformed';\n\nexport interface ReinstateRefusedOutcome {\n  kind: 'refused';\n  keyid: string;\n  reason: ReinstateRefusalReason;\n}\n\nexport type ReinstateOutcome =\n  | ReinstateExtendedOutcome\n  | ReinstateUnchangedOutcome\n  | ReinstateRefusedOutcome;\n\nexport type FeedDemandReason = 'cold-start' | 'unknown-key' | 'expired-key' | 'feed-aging';\n\nexport type FeedAttemptOutcome = 'applied' | 'current' | 'failed';\n\nexport type VendorKeyMissReason = 'unknown-key' | 'expired-key';\n\n/** A vendor-key miss, in the shape `feedNoteMiss` takes. */\nexport interface VendorKeyMiss {\n  keyid: string;\n  reason: VendorKeyMissReason;\n}\n\nexport interface AdoptedVendorKey {\n  keyid: string;\n  x: string;\n  notBefore: number;\n  expiresAt: number;\n}\n\nexport interface AdoptedVendorKeys {\n  feedVersion: number | null;\n  keys: AdoptedVendorKey[];\n}\n\nexport interface VendorKeyFeedKeyStatus {\n  keyid: string;\n  notBefore: number;\n  expiresAt: number;\n  expired: boolean;\n}\n\nexport interface VendorKeyFeedStatus {\n  keySource: 'feed' | 'embedded';\n  feedVersion?: number;\n  issuedAt?: number;\n  expiresAt?: number;\n  refreshDueAt?: number;\n  stale: boolean;\n  pendingDemand?: FeedDemandReason;\n  inFlight: boolean;\n  failureStreak: number;\n  keys: VendorKeyFeedKeyStatus[];\n}\n\n/** The bundle verified and was applied (or was already in effect). */\nexport interface RuleBundleApplied {\n  ok: true;\n  version: number;\n  /** True when this exact version was already in effect and nothing changed. */\n  unchanged: boolean;\n  /** Unix seconds after which the publisher considers this bundle stale. */\n  expiresAt: number;\n  /** Vendors whose CIDR sets were replaced. */\n  ipVendorsUpdated: string[];\n  /** Vendors named in the bundle that this engine build does not know. */\n  vendorsIgnored: string[];\n  keyOutcomes: KeySetOutcome[];\n}\n\n/** The bundle was refused; nothing was applied. */\nexport interface RuleBundleRejected {\n  ok: false;\n  code: RuleBundleRejectionCode;\n  message: string;\n}\n\nexport type RuleBundleReport = RuleBundleApplied | RuleBundleRejected;\n","import type { DetectionDetail, EngineInfo } from '../types';\n\n/**\n * Engine attribution for host-synthesized results emitted before the\n * WASM engine is invoked.\n */\nexport function hostSynthesizedEngineInfo(): EngineInfo {\n  return {\n    name: 'checkpoint-engine-wasm',\n    version: '0.0.0-host-synth',\n    rulesetHash: 'sha256:host-synthesized',\n    rulesetVersion: '0.0.0-host-synth',\n    extras: { synthesized: true },\n  };\n}\n\nexport function parseErrorDetectionDetail(detail: string): DetectionDetail {\n  return {\n    isAgent: false,\n    confidence: 0,\n    detectionClass: { type: 'IncompleteData' },\n    confidenceLevel: 'low',\n    reasons: [detail],\n    signals: [],\n    verificationMethod: 'error',\n    riskLevel: 'high',\n    forgeabilityRisk: 'high',\n    timestamp: 0,\n    engine: hostSynthesizedEngineInfo(),\n  };\n}\n","/**\n * The engine-directed resolution loop both orchestrators run: call the engine\n * with the answers held, answer every need it names, call again, and stop at\n * `MAX_RESOLUTION_ROUNDS` calls.\n *\n * The engine keeps no state between calls and never names a need it has an\n * answer for, so a host that answers every need before calling again is\n * decided on its second call. The bound only stops a host or engine bug from\n * turning verification into a loop; reaching it fails the request closed as\n * retryable.\n */\n\nimport {\n  makeResolutionHost,\n  type ResolutionCall,\n  type ResolutionEngine,\n  type ResolutionHost,\n} from '../adapters/resolution-host';\nimport {\n  isNeedsResult,\n  MAX_RESOLUTION_ROUNDS,\n  type Decision,\n  type DirectedVerifyResult,\n  type EnforcementMode,\n  type ResourceOutcome,\n  type VerifyResult,\n} from '../types';\nimport { hostSynthesizedEngineInfo, parseErrorDetectionDetail } from './synthetic-results';\n\n/**\n * The tenant decision every verification hands the engine. The engine\n * decides: a tenant's rules are Cedar, which the engine evaluates, so the host\n * contributes no decision of its own.\n */\nexport const TENANT_DECISION: Decision = { kind: 'Permit' };\n\n/** The `kya_error_code` of a request whose resolution did not finish in time. */\nconst IDENTITY_PENDING = 'kyaos/identity-pending';\n\nexport type DirectedCall = (\n  resources: Record<string, ResourceOutcome>\n) => DirectedVerifyResult | Promise<DirectedVerifyResult>;\n\n/**\n * Decide one request in engine-directed mode. The first call carries the\n * answers the host holds for its configured roots, so a request that needs\n * only roots is decided in one call. `resolution` carries the `nowUnix` every\n * engine call is made with, so the host answers in the engine's clock, and an\n * edge host's `waitUntil` for the host's background fetches.\n */\nexport async function verifyDirected(\n  call: DirectedCall,\n  host: ResolutionHost,\n  engine: ResolutionEngine,\n  enforcementMode: EnforcementMode,\n  resolution: ResolutionCall\n): Promise<VerifyResult> {\n  let resources = host.rootAnswers(resolution);\n  for (let round = 1; ; round++) {\n    const result = await call(resources);\n    if (!isNeedsResult(result)) return result;\n    if (round >= MAX_RESOLUTION_ROUNDS) return resolutionUnfinished(enforcementMode);\n    resources = { ...resources, ...(await host.answer(result.needs, engine, resolution)) };\n  }\n}\n\n/**\n * The retryable refusal for a request still naming needs at the round bound:\n * `Block(Unauthenticated)` with `kyaos/identity-pending`, which the engine's\n * renderer answers 503 with `Retry-After`.\n */\nfunction resolutionUnfinished(enforcementMode: EnforcementMode): VerifyResult {\n  const detectionDetail = parseErrorDetectionDetail('engine-directed resolution did not finish');\n  return {\n    decision: { kind: 'Block', reason: { kind: 'Unauthenticated' } },\n    detectionDetail: {\n      ...detectionDetail,\n      metadata: {\n        ...detectionDetail.metadata,\n        kya_error_code: IDENTITY_PENDING,\n        resolution_pending: true,\n      },\n    },\n    enforcementMode,\n    engineInfo: hostSynthesizedEngineInfo(),\n  };\n}\n\nlet sharedHost: ResolutionHost | undefined;\n\n/**\n * The inline resolution host a caller that brings none shares, one per\n * process or isolate, so its cache outlives a request.\n */\nexport function defaultResolutionHost(): ResolutionHost {\n  return (sharedHost ??= makeResolutionHost({ mode: 'inline' }));\n}\n","/**\n * What the orchestrators read from the engine's verdict on a presented\n * credential, and the carriages they refuse before calling it.\n *\n * draft-kya-http-02's downgrade-attack defense, \"absent demotes, invalid\n * rejects\", is the engine's: it blocks a presented KYA credential it cannot\n * verify, with the precise `kyaos/*` code on `metadata.kya_error_code`, and\n * never demotes one to an anonymous Permit. The presented-credential parity\n * vectors (tests/cross-runtime-parity/presented-credential/) pin that in every\n * runtime, so the orchestrators return the engine's decision as it is.\n */\n\nimport {\n  KYA_HTTP_ERROR,\n  KYA_HTTP_ERROR_STATUS,\n  REGISTERED_SID_MAX_LENGTH,\n  type KyaHttpErrorCode,\n} from '@kya-os/checkpoint-shared/kya-http';\n\nimport type { AgentRequest, BearerDelegationIdentity, VerifyResult } from '../types';\n\nimport type { BearerDelegationCredentialRef } from './build-agent-request';\nimport type { IncomingHttpLike } from './types';\n\n/**\n * #3388 — the identity-pending reject code: a presented kya credential whose\n * trusted roots are not yet warm. Retryable (renders 503 + Retry-After); distinct\n * from a confirmed §9 verify failure.\n */\nexport const KYA_IDENTITY_PENDING = 'kyaos/identity-pending';\n\n/**\n * Whether the engine refuses this request as an unsupported carriage\n * (`kyaos/unsupported-carriage`) without resolving anything: an MCP-I\n * envelope, or a request carrying `KYA-OS-Delegation-Credential` or\n * `KYA-OS-Delegation-Proof`, which only the engine's native propagation lane\n * verifies, and these orchestrators do not configure that lane. They fetch\n * nothing such a request names. Header presence alone counts, as in the\n * engine. A host that configures the native lane must narrow this, or its\n * requests reach the engine without their documents and fail closed.\n */\nexport function isRefusedDelegationCarriage(\n  req: IncomingHttpLike,\n  agentRequest: AgentRequest\n): boolean {\n  if (agentRequest.protocol === 'McpI') return true;\n  return Object.keys(req.headers).some((name) =>\n    PROPAGATION_ARTIFACT_HEADERS.has(name.toLowerCase())\n  );\n}\n\nconst PROPAGATION_ARTIFACT_HEADERS: ReadonlySet<string> = new Set([\n  'kya-os-delegation-credential',\n  'kya-os-delegation-proof',\n]);\n\n/**\n * Read the engine's `metadata.kya_error_code` ONLY when it's a well-formed §9\n * registry code — an arbitrary string is never trusted onto the wire.\n */\nexport function readKyaErrorCode(\n  metadata: Record<string, unknown> | undefined\n): KyaHttpErrorCode | undefined {\n  const raw = metadata?.['kya_error_code'];\n  if (typeof raw !== 'string') return undefined;\n  return KYA_ERROR_CODES.has(raw) ? (raw as KyaHttpErrorCode) : undefined;\n}\n\n/**\n * Read the engine's `metadata.kya_session_id`: the draft-kya-http-02 registered\n * session anchor (the presented credential's `sid` claim), passthrough from\n * `detection_detail.metadata` on the Rust side\n * (`rust/crates/kya-os-engine/src/api.rs`, `bearer_delegation_verified_detail` and the\n * Tier-1 kya-http/2-signed success path). The engine stamps this ONLY on a\n * successfully verified presentation; never on a reject, and never on a demotion\n * (D15 of the flow-lab-customer-delegation-timeline plan). A non-string or empty value\n * is treated as absent, mirroring `readKyaErrorCode`'s refusal to trust an\n * unrecognised shape onto the wire. The trim + `REGISTERED_SID_MAX_LENGTH` bound also\n * guards the wire schema's own constraint (`ReportedDelegationSchema.sid` is\n * `NonEmptyTrimmed.max(REGISTERED_SID_MAX_LENGTH)`): the Rust extraction only checks\n * `is_empty()`, so a malformed-but-validly-signed credential could otherwise produce a\n * whitespace-only or over-length sid that reaches the wire and 400s the whole\n * detection at `LogDetectionRequestSchema.parse()`, the same hazard `sanitizeEngineInfo`\n * guards against for `rulesetHash`.\n */\nexport function readVerifiedDelegationSid(\n  metadata: Record<string, unknown> | undefined\n): string | undefined {\n  const raw = metadata?.['kya_session_id'];\n  if (typeof raw !== 'string') return undefined;\n  const trimmed = raw.trim();\n  return trimmed.length > 0 && trimmed.length <= REGISTERED_SID_MAX_LENGTH ? trimmed : undefined;\n}\n\n/**\n * Read the engine's `metadata.agent_did`: the leaf agent DID the engine attributes a\n * Tier-1 cryptographically verified presentation to (kya-http/2-signed OR standalone\n * bearer delegation; both write this key on their verified path, see\n * `rust/crates/kya-os-engine/src/api.rs` lines ~1868 and ~2010-2019). Same passthrough\n * + guard shape as {@link readVerifiedDelegationSid}. Independent of whether a sid is\n * also present: a verified identity signature can exist without a delegation-bearing\n * sid. Also enforces the wire schema's `did:` prefix shape (`DidStringSchema`): the\n * Rust extraction has no DID-shape check on `agent_did`/`sub` at all, so a\n * non-`did:`-prefixed value is dropped here rather than sent onto the wire, avoiding\n * the same 400-the-whole-detection hazard as above.\n */\nexport function readVerifiedAgentDid(\n  metadata: Record<string, unknown> | undefined\n): string | undefined {\n  const raw = metadata?.['agent_did'];\n  if (typeof raw !== 'string') return undefined;\n  const trimmed = raw.trim();\n  return isDidShaped(trimmed) ? trimmed : undefined;\n}\n\n/**\n * Guard for wire fields typed `DidStringSchema` (`ReportedIdentitySchema` in\n * `@kya-os/checkpoint-shared`, requires a `did:`-prefixed string). Shared by\n * `readVerifiedAgentDid` above (an engine-metadata value) and, via export,\n * `reporter/index.ts`'s bearer-delegation identity merge (a decoded-but-not-\n * re-verified credential claim) — one DID-shape rule for the wire, not two\n * independently-maintained copies.\n */\nexport function isDidShaped(value: string): boolean {\n  return /^did:/.test(value);\n}\n\n/**\n * The §9 HTTP status for a `kyaos/*` code, read from the registry\n * (`KYA_HTTP_ERROR_STATUS`, pinned to error-codes.json). The retryable 503\n * codes (e.g. kyaos/status-pending, #3345) and the 429 replay-capacity code\n * tell a client to back off and retry, not to treat the reject as terminal.\n * The engine renders from the same table (`render/kya_error.rs`).\n */\nexport function statusForKyaError(code: KyaHttpErrorCode): number {\n  return KYA_HTTP_ERROR_STATUS[code];\n}\n\n/** True for the statuses that carry `Retry-After`: 503 and 429. */\nexport function isRetryableKyaStatus(status: number): boolean {\n  return status === 503 || status === 429;\n}\n\n/**\n * KYA-1099 W1 — attach the observed bearer delegation's `agentDid` / `jti` /\n * `iss` plus a `verified` flag (from the decision the orchestrator returns)\n * onto the result an orchestrator is about to return. No-op (returns\n * `result` unchanged, same reference) when the request never carried a\n * bearer delegation — every existing caller is unaffected. Shared by BOTH\n * orchestrators (edge and node) so a request\n * presenting a standalone bearer delegation resolves to the same identity\n * regardless of which runtime handled it — see the module header's sync\n * requirement between `verify-request.ts` and `verify-request-edge.ts`.\n */\nexport function withBearerDelegationIdentity(\n  result: VerifyResult,\n  bearerDelegation: BearerDelegationCredentialRef | null\n): VerifyResult {\n  if (!bearerDelegation) return result;\n  const handle = credentialHandle(bearerDelegation.claims);\n  const bearerDelegationIdentity: BearerDelegationIdentity = {\n    ...(bearerDelegation.agentDid ? { agentDid: bearerDelegation.agentDid } : {}),\n    ...(handle ? { jti: handle } : {}),\n    ...(bearerDelegation.issuer ? { iss: bearerDelegation.issuer } : {}),\n    verified: result.decision.kind === 'Permit',\n  };\n  return { ...result, bearerDelegationIdentity };\n}\n\n// -----------------------------------------------------------------------------\n// Internals.\n// -----------------------------------------------------------------------------\n\n/**\n * The credential handle a verifier keys budgets, blocks and revocations on:\n * `vc.id`, else the JWT `jti`. An org-issued delegation carries one\n * credential id per delegation as `vc.id` and no `jti`.\n */\nfunction credentialHandle(claims: Record<string, unknown>): string | undefined {\n  const vc = claims['vc'];\n  const vcId =\n    typeof vc === 'object' && vc !== null ? (vc as Record<string, unknown>)['id'] : undefined;\n  if (typeof vcId === 'string' && vcId.length > 0) return vcId;\n  const jti = claims['jti'];\n  return typeof jti === 'string' && jti.length > 0 ? jti : undefined;\n}\n\nconst KYA_ERROR_CODES: ReadonlySet<string> = new Set(Object.values(KYA_HTTP_ERROR));\n","/**\n * The body of a kya-http/2 (KYA HTTP Binding) signed request.\n *\n * The engine counts a request as carrying a body only when it is given body\n * bytes or sees a `Content-Digest` header. A host that cannot hand over the\n * bytes (body over its read bound, reading switched off, no body parser) would\n * otherwise let a signer that sent a body without `Content-Digest`, and so\n * never signed it, verify with the body unbound. These helpers close that gap\n * on the host side using the request's own framing headers.\n */\n\nimport { KYA_HTTP_ERROR, requestDeclaresBody } from '@kya-os/checkpoint-shared/kya-http';\n\nimport type { AgentRequest, DetectionDetail, VerifyResult } from '../types';\nimport { hasKyaSignatureMember } from './kya-signature-presentation';\nimport type { IncomingHttpLike } from './types';\n\n/**\n * True when `req` presents a kya-http/2 signature, its framing declares a body\n * (`Transfer-Encoding`, or `Content-Length` other than 0), and the engine\n * input carries no body bytes.\n *\n * A chunked body can be empty, so when the host read the body (`rawBody`) and\n * it was empty, `Transfer-Encoding` alone does not make it withheld. A\n * `Content-Length` other than 0 still does: the host's empty read contradicts it.\n */\nexport function isSignedBodyWithheld(req: IncomingHttpLike, agentRequest: AgentRequest): boolean {\n  if (agentRequest.protocol !== 'HttpSigned') return false;\n  if (!hasKyaSignatureMember(req.headers)) return false;\n  if ((agentRequest.request.body?.length ?? 0) > 0) return false;\n  const hostReadBody = req.rawBody !== undefined && req.rawBody !== null;\n  return requestDeclaresBody(hostReadBody ? withoutTransferEncoding(req.headers) : req.headers);\n}\n\nfunction withoutTransferEncoding(\n  headers: IncomingHttpLike['headers']\n): IncomingHttpLike['headers'] {\n  return Object.fromEntries(\n    Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'transfer-encoding')\n  );\n}\n\n/**\n * Refuse a request whose signed body was withheld from the engine, exactly as\n * the engine refuses a body its signature does not bind: Block, reason\n * `Unauthenticated`, `kyaos/profile-violation` (403 on the wire). An engine\n * Block stands as it is (for example `kyaos/invalid-signature` when a signed\n * `Content-Digest` met no bytes), so this only ever turns a pass into a refusal.\n */\nexport function refuseWithheldSignedBody(result: VerifyResult, withheld: boolean): VerifyResult {\n  if (!withheld || result.decision.kind === 'Block') return result;\n  return {\n    ...result,\n    decision: { kind: 'Block', reason: { kind: 'Unauthenticated' } },\n    detectionDetail: profileViolationDetail(result.detectionDetail.timestamp),\n    trace: [\n      {\n        name: 'identity',\n        verdict: 'fail',\n        latencyMicros: 0,\n        reason: KYA_HTTP_ERROR.PROFILE_VIOLATION,\n      },\n    ],\n  };\n}\n\n/** Mirrors the engine's `kya_rejection` detail for `kyaos/profile-violation`. */\nfunction profileViolationDetail(timestamp: DetectionDetail['timestamp']): DetectionDetail {\n  return {\n    isAgent: false,\n    confidence: 0,\n    detectionClass: { type: 'IncompleteData' },\n    confidenceLevel: 'low',\n    reasons: [\n      `KYA HTTP proof rejected: ${KYA_HTTP_ERROR.PROFILE_VIOLATION} (the request has a body the verifier never received)`,\n    ],\n    signals: [],\n    riskLevel: 'high',\n    forgeabilityRisk: 'high',\n    metadata: { kya_error_code: KYA_HTTP_ERROR.PROFILE_VIOLATION },\n    timestamp,\n    assurance: 'anonymous',\n  };\n}\n","/**\n * `verifyRequest` async orchestrator — Phase C.2.\n *\n * The single entry point Phase D (Next.js) and Phase E (Express)\n * compose. Async pre-fetch on the host side; one sync `engineVerify`\n * call across the WASM boundary. Sync-engine / async-host invariant\n * (H-1 § 4.5) preserved.\n *\n * Orchestration:\n *   1. Translate HTTP → AgentRequest (no engine I/O).\n *   2. Look up the agent DID's reputation. The tenant decision handed to the\n *      engine is always Permit (`TENANT_DECISION`): the engine decides, and a\n *      tenant's rules are Cedar.\n *   3. Verify in engine-directed mode (`./directed.ts`): the engine names\n *      every DID document and status list the request needs, after its own\n *      trust gates; the resolution host answers them; the engine decides.\n *      Plain traffic is decided in one call.\n *\n * ## SDK-Next.js-Integration-Audit-1 (#2618) — engine injection\n *\n * This module is intentionally **engine-agnostic**: it does NOT\n * import an `engineVerify` symbol at module scope. Instead, it\n * exports a factory `createVerifyRequestApi(defaultEngine)` that\n * closes over the sync-bridge function. Two entries bind it:\n *\n *   - `./orchestrator/index.ts` — binds the wasm-bindgen `--target\n *     bundler` `engineVerify` (canonical default).\n *   - `./orchestrator/node.ts` — binds the wasm-bindgen `--target\n *     nodejs` `engineVerify` (Webpack-without-asyncWebAssembly safety\n *     net).\n *\n * Keeping the engine import out of this file is what makes the\n * `./orchestrator/node` subpath actually different at the dist level\n * — `orchestrator-node.mjs` no longer transitively pulls the bundler\n * artifact's `.wasm` static import into the consumer's graph.\n */\n\nimport type { StatusListVerification, StatusListVerifier } from '../adapters/status-list-cache';\nimport type {\n  AgentRequest,\n  ContextSpec,\n  DelegationVerifyInput,\n  DirectedVerifyResult,\n  EnforcementMode,\n  VerifyResult,\n} from '../types';\n\nimport {\n  buildAgentRequest,\n  extractBearerDelegationCredential,\n  extractAgentDid,\n  hasMalformedJwsBody,\n} from './build-agent-request';\nimport { defaultResolutionHost, TENANT_DECISION, verifyDirected } from './directed';\nimport { isRefusedDelegationCarriage, withBearerDelegationIdentity } from './presented-credential';\nimport { feedAfterVerify, type VendorKeyFeedBindings } from '../../vendor-keys/feed';\nimport { hostSynthesizedEngineInfo, parseErrorDetectionDetail } from './synthetic-results';\nimport type { IncomingHttpLike, VerifyRequestOpts } from './types';\nimport { isSignedBodyWithheld, refuseWithheldSignedBody } from './signed-body';\n\ntype EngineVerifyFn = (input: AgentRequest, ctx: ContextSpec) => DirectedVerifyResult;\ntype EngineVerifyDelegationFn = (\n  input: DelegationVerifyInput,\n  ctx: ContextSpec\n) => DirectedVerifyResult | Promise<DirectedVerifyResult>;\n\n/**\n * The `verifyRequest` + `makeVerifyRequest` pair produced by\n * [`createVerifyRequestApi`]. Entry barrels (`./orchestrator/index.ts`,\n * `./orchestrator/node.ts`) destructure this and re-export the two\n * closures as the public surface.\n */\nexport interface VerifyRequestApi {\n  /** Single-shot async entry. */\n  verifyRequest(req: IncomingHttpLike, opts: VerifyRequestOpts): Promise<VerifyResult>;\n  /** Factory variant — remembers the one-shot Argus-not-configured warning. */\n  makeVerifyRequest(opts: VerifyRequestOpts): (req: IncomingHttpLike) => Promise<VerifyResult>;\n}\n\n/**\n * Bind a sync-bridge `engineVerify` and produce the public\n * `verifyRequest` + `makeVerifyRequest` closures. The bound default\n * is overridable per-call via `VerifyRequestOpts.engineVerifyFn`\n * (kept for tests + advanced consumers who need to swap bridges\n * per-invocation).\n *\n * Why a factory instead of a top-level `import { engineVerify }` —\n * see this file's module-doc § \"engine injection\".\n */\nexport function createVerifyRequestApi(\n  defaultEngine: EngineVerifyFn,\n  defaultDelegationEngine: EngineVerifyDelegationFn,\n  feedBindings?: VendorKeyFeedBindings,\n  defaultStatusListVerifier: StatusListVerifier = unboundStatusListVerifier\n): VerifyRequestApi {\n  function verifyRequest(req: IncomingHttpLike, opts: VerifyRequestOpts): Promise<VerifyResult> {\n    return verifyRequest_internal(\n      req,\n      opts,\n      opts.engineVerifyFn ?? defaultEngine,\n      opts.engineVerifyDelegationFn ?? defaultDelegationEngine,\n      opts.engineVerifyFn ? undefined : feedBindings,\n      opts.engineVerifyStatusListFn ?? defaultStatusListVerifier\n    );\n  }\n\n  function makeVerifyRequest(\n    opts: VerifyRequestOpts\n  ): (req: IncomingHttpLike) => Promise<VerifyResult> {\n    let argusWarningLogged = false;\n    const log = opts.logger ?? defaultLogger;\n    const engine = opts.engineVerifyFn ?? defaultEngine;\n    const delegationEngine = opts.engineVerifyDelegationFn ?? defaultDelegationEngine;\n    const statusListVerifier = opts.engineVerifyStatusListFn ?? defaultStatusListVerifier;\n    return async function verifyRequest(req: IncomingHttpLike): Promise<VerifyResult> {\n      if (!argusWarningLogged && !opts.argusUrl) {\n        log(\n          '[Checkpoint] WARNING: Argus URL not configured; reputation will degrade to baseline 1.0 (\"trust by default\"). Set ARGUS_API_URL to enable.'\n        );\n        argusWarningLogged = true;\n      }\n      return verifyRequest_internal(\n        req,\n        opts,\n        engine,\n        delegationEngine,\n        opts.engineVerifyFn ? undefined : feedBindings,\n        statusListVerifier\n      );\n    };\n  }\n\n  return { verifyRequest, makeVerifyRequest };\n}\n\n/**\n * The verifier of an entry that bound no engine `verifyStatusList`: every\n * list is rejected, so a credential with a status entry fails closed.\n */\nfunction unboundStatusListVerifier(): StatusListVerification {\n  return {\n    ok: false,\n    code: 'invalid_input',\n    message: 'no engine status-list verifier is bound to this orchestrator',\n  };\n}\n\nasync function verifyRequest_internal(\n  req: IncomingHttpLike,\n  opts: VerifyRequestOpts,\n  engineVerify: EngineVerifyFn,\n  engineVerifyDelegation: EngineVerifyDelegationFn,\n  feedBindings: VendorKeyFeedBindings | undefined,\n  verifyStatusList: StatusListVerifier\n): Promise<VerifyResult> {\n  // JWS-aware preflight — when the body carries `_meta.proof.jws`\n  // but the payload won't project into a typed McpIPayload, treat\n  // the envelope as malformed (Block(ParseError)) rather than\n  // silently degrading to PlainHttp.\n  if (hasMalformedJwsBody(req)) {\n    return blockWithParseError('malformed JWS body', opts.enforcementMode);\n  }\n\n  const bearerDelegation = extractBearerDelegationCredential(req);\n  const agentRequest = buildAgentRequest(req, {\n    legacyEnvelopeFallback: opts.legacyEnvelopeFallback,\n  });\n  // A kya-http/2 body the engine never received is unbound; refused at the end.\n  const signedBodyWithheld = isSignedBodyWithheld(req, agentRequest);\n  // The engine refuses an MCP-I envelope, and KYA-OS delegation headers this\n  // host has no native propagation lane for, as an unsupported carriage, so\n  // such a request's agent DID gets no reputation lookup either.\n  const refusedCarriage = !bearerDelegation && isRefusedDelegationCarriage(req, agentRequest);\n  const agentDid = refusedCarriage\n    ? null\n    : (bearerDelegation?.agentDid ?? extractAgentDid(agentRequest));\n  const reputation = agentDid ? { [agentDid]: await opts.reputationOracle.score(agentDid) } : {};\n\n  // `config` carries the engine-default behaviour knobs forwarded from\n  // VerifyRequestOpts. Omit when the host didn't supply one — the WASM glue's\n  // `#[serde(default)]` resolves it to `EngineConfig::default()`.\n  const ctx: ContextSpec = {\n    reputation,\n    tenantDecision: TENANT_DECISION,\n    nowUnix: opts.clock.nowUnix(),\n    enforcementMode: opts.enforcementMode,\n    resolution: 'engine-directed',\n    ...(opts.engineConfig ? { config: opts.engineConfig } : {}),\n    ...(opts.trustedDelegationRoots ? { trustedDelegationRoots: opts.trustedDelegationRoots } : {}),\n    ...(opts.resourceOrgDid ? { resourceOrgDid: opts.resourceOrgDid } : {}),\n    ...(opts.httpDelegation ? { httpDelegation: opts.httpDelegation } : {}),\n  };\n\n  const result = await verifyDirected(\n    (resources) =>\n      bearerDelegation\n        ? engineVerifyDelegation(\n            {\n              credential: bearerDelegation.credential,\n              requiredScopes: opts.requiredScopes ?? [],\n            },\n            { ...ctx, resources }\n          )\n        : engineVerify(agentRequest, { ...ctx, resources }),\n    opts.resolutionHost ?? defaultResolutionHost(),\n    { verifyStatusList },\n    opts.enforcementMode,\n    { nowUnix: ctx.nowUnix }\n  );\n  if (!bearerDelegation && feedBindings) await feedAfterVerify(feedBindings);\n\n  // The engine's decision stands: it blocks a presented KYA credential it\n  // cannot verify (\"absent demotes, invalid rejects\", presented-credential.ts).\n  //\n  // KYA-1099 W1 — mirror verify-request-edge.ts: attach the observed bearer\n  // delegation's identity onto that decision. A kya-http/2 body the engine\n  // never received is refused last (`refuseWithheldSignedBody`).\n  return refuseWithheldSignedBody(\n    withBearerDelegationIdentity(result, bearerDelegation),\n    signedBodyWithheld\n  );\n}\n\n/**\n * Synthesize a `VerifyResult` carrying `Block(ParseError)` for the\n * DID-failure case. The engine emits its own `EngineInfo` only when\n * `engineVerify` is actually invoked; this synthetic block path\n * happens *before* the WASM call, so we fabricate a minimal\n * attribution block here. Marked with a sentinel `extras.synthesized`\n * so dashboards / logs can distinguish engine-emitted vs.\n * host-synthesized attribution.\n */\nfunction blockWithParseError(detail: string, enforcementMode: EnforcementMode): VerifyResult {\n  return {\n    decision: {\n      kind: 'Block',\n      reason: {\n        kind: 'ParseError',\n        detail,\n      },\n    },\n    detectionDetail: parseErrorDetectionDetail(detail),\n    enforcementMode,\n    engineInfo: hostSynthesizedEngineInfo(),\n  };\n}\n\nfunction defaultLogger(msg: string): void {\n  console.warn(msg);\n}\n","/** The compiled WebAssembly module an edge entry was missing. */\nexport type EdgeWasmArtifact = 'engine' | 'cedar';\n\n/**\n * Thrown when an edge entry has to instantiate its WebAssembly before the host\n * registered the compiled `WebAssembly.Module`. The edge glue has no URL\n * fallback (`rust/scripts/lib/remove-wasm-url-fallback.mjs` removes it at\n * build time): bundlers copy the wasm into every bundle for that fallback, and\n * it fails on Cloudflare Workers anyway. A host catches this like any other\n * evaluator failure and fails closed.\n */\nexport class WasmModuleNotRegisteredError extends Error {\n  readonly code = 'wasm_module_not_registered' as const;\n  readonly artifact: EdgeWasmArtifact;\n\n  /** `register` names where the module goes, e.g. `initEngine()`. */\n  constructor(artifact: EdgeWasmArtifact, register: string) {\n    super(\n      `No ${artifact} WebAssembly.Module is registered: import the module and pass it to ${register} before use.`\n    );\n    this.name = 'WasmModuleNotRegisteredError';\n    this.artifact = artifact;\n  }\n}\n","/**\n * The compiled engines an edge host registers, shared by the edge engine\n * (`./edge.ts`) and the edge Cedar evaluator (`../policy-evaluator-edge.ts`).\n *\n * The cedar-web build is the engine-web build plus the Cedar evaluator: the\n * `cedar` feature only adds `src/policy`, so its detection exports are the same\n * code. A host that enforces Cedar on the edge therefore passes one module,\n * the cedar-web one, and one instance of it serves both roles; passing both\n * modules still works, but bundles the engine twice.\n *\n * This file imports no glue, so the module check and the registry cost a\n * bundle nothing. The Cedar evaluator does import `./edge.ts` to share its\n * instance, so a bundle that uses only `./policy-edge` also carries the\n * engine-web glue JS, never its wasm: neither web glue can load a wasm the\n * host did not pass.\n */\n\nimport type { EngineWasmSource } from './types';\n\n/**\n * Whether a module is the cedar-web build, judged by what it exports (its\n * Cedar evaluator constructor). Only a compiled `WebAssembly.Module` can be\n * inspected; any other source (bytes, a URL) counts as the engine-web build.\n *\n * `WebAssembly.Module.exports` is the module check, not `instanceof`: the\n * Next.js Edge sandbox hands middleware `.wasm?module` imports compiled in\n * another realm, which fail `instanceof WebAssembly.Module` here, and\n * `exports` accepts a module from any realm and throws for anything else.\n */\nexport function isCedarModule(source: EngineWasmSource | undefined): source is WebAssembly.Module {\n  if (typeof WebAssembly === 'undefined' || typeof source !== 'object' || source === null) {\n    return false;\n  }\n  try {\n    return WebAssembly.Module.exports(source as WebAssembly.Module).some(\n      (entry) => entry.name === 'policyevaluator_new'\n    );\n  } catch {\n    return false;\n  }\n}\n\n/** The cedar-web module registered through `initPolicyEvaluatorEdge`. */\nlet cedarModule: WebAssembly.Module | undefined;\n/**\n * The last attempt to instantiate `cedarModule`, by either side: the Cedar\n * evaluator's own, or the engine's when it runs on the registered module.\n */\nlet lastAttempt: Promise<unknown> | undefined;\nlet lastAttemptFailed = false;\n\n/**\n * Register the cedar-web module (`initPolicyEvaluatorEdge`), with the same\n * module rule as `initEngineEdge`: the first one registered is used, and a\n * different one replaces it only after an attempt on it failed, never while\n * one is pending or after one succeeded.\n */\nexport function registerCedarModule(module: WebAssembly.Module): void {\n  if (module === cedarModule) return;\n  if (cedarModule !== undefined && !lastAttemptFailed) return;\n  cedarModule = module;\n  lastAttempt = undefined;\n  lastAttemptFailed = false;\n}\n\n/** The registered cedar-web module, if any. */\nexport function registeredCedarModule(): WebAssembly.Module | undefined {\n  return cedarModule;\n}\n\n/**\n * Record an attempt to instantiate `module`. Only an attempt on the registered\n * module counts, and only the latest one: its outcome decides whether\n * {@link registerCedarModule} may replace the module.\n */\nexport function noteCedarAttempt(\n  module: EngineWasmSource | undefined,\n  attempt: Promise<unknown>\n): void {\n  if (module === undefined || module !== cedarModule) return;\n  lastAttempt = attempt;\n  lastAttemptFailed = false;\n  attempt.then(\n    () => undefined,\n    () => {\n      if (lastAttempt === attempt) lastAttemptFailed = true;\n    }\n  );\n}\n","/**\n * `kya-os-engine` WASM bridge for edge runtimes — Edge-WASM-1.\n *\n * The Node target (`./index.ts`) uses `fs.readFileSync` at module\n * load and exposes a sync `engineVerify`. That's incompatible with\n * Vercel Edge / Cloudflare Workers / browser embedding (no `fs`,\n * no sync wasm load).\n *\n * This module loads the `wasm-pack --target web` artifact via the\n * async `__wbg_init` default export. The web target's `init()`\n * accepts a pre-instantiated `WebAssembly.Module` argument — the\n * canonical Cloudflare-Workers + wasm-bindgen pattern.\n *\n * # Why the caller MUST pass `wasmModule` on Cloudflare Workers\n *\n * Both `--target web` (URL fetch) and `--target bundler` (auto-\n * instantiated `__wbg_set_wasm(wasm)`) have failure modes on wrangler:\n *\n *   - `--target web` falls back to `new URL('<wasm>', import.meta.url)`\n *     when `init()` is called with no arg. Cloudflare Workers don't\n *     materialise `import.meta.url` the way browsers do → throws\n *     `TypeError: Invalid URL string`. (Broke production 2026-05-23,\n *     captured via dev tail in run 26352287112.)\n *\n *   - `--target bundler` expects the host bundler to AUTO-INSTANTIATE\n *     `import * as wasm from './foo.wasm'` so `wasm` is the\n *     `Instance.exports` object. Webpack does this. **Wrangler does\n *     NOT** — wrangler gives you a raw `WebAssembly.Module`, and the\n *     bundler-target shim's `__wbg_set_wasm(rawModule)` happily\n *     accepts it, then every export lookup (`wasm.__wbindgen_add_\n *     to_stack_pointer`, etc.) returns undefined → throws\n *     `TypeError: wasm.__wbindgen_add_to_stack_pointer is not a function`.\n *     (Broke production 2026-05-24 after switching to bundler target\n *     in PR #2785; captured via prod tail.)\n *\n * The fix is the standard Cloudflare-Workers + wasm-bindgen pattern:\n * the consumer statically imports the `.wasm` file (wrangler then\n * bundles it + hands the worker a `WebAssembly.Module`), then passes\n * it to `init(wasmModule)`. The web target's init detects the Module\n * input + calls `WebAssembly.instantiate(Module, imports)` internally\n * to produce a real `Instance` whose exports populate the JS shim's\n * `wasm` binding correctly.\n *\n * Every host passes it, on every runtime. The web glue no longer has the\n * URL fallback (`rust/scripts/lib/remove-wasm-url-fallback.mjs` removes\n * it at build time, because bundlers copied the wasm into the bundle a\n * second time for it), so an engine that was never given a module\n * rejects with `WasmModuleNotRegisteredError` and fetches nothing.\n *\n * **Why this matters for the consolidation narrative.** Phase A\n * shipped Node-only. Without an edge build, the first Vercel-edge\n * or Cloudflare-Workers deployment after Phase D would hit the\n * same wasm-bindgen-on-edge wall the Sites-1 F3 workaround was\n * created to dodge — and someone would re-introduce the\n * inline-TS detector that Q10 ratified deleting. Shipping the\n * edge target alongside the Node target keeps Phase D's\n * deletion narrative durable.\n */\n\nimport type {\n  AdoptedVendorKeys,\n  AgentRequest,\n  ContextSpec,\n  DelegationVerifyInput,\n  EngineWasmSource,\n  FeedAttemptOutcome,\n  FeedDemandReason,\n  RootNeedsResult,\n  RuleBundleReport,\n  VendorKeyFeedStatus,\n  VendorKeyMissReason,\n  VerifyResult,\n} from './types';\nimport {\n  unwrapRenderEnvelope,\n  type EngineManifest,\n  type EngineRenderEnvelope,\n  type EngineRenderOptions,\n  type EngineRenderedResponse,\n} from './render-types';\nimport { WasmModuleNotRegisteredError } from '../wasm-module-error';\nimport { isCedarModule, noteCedarAttempt, registeredCedarModule } from './edge-wasm';\nimport { warmEngine } from './warm-up';\nimport type { StatusListVerification } from './adapters/status-list-cache';\n\nexport { WasmModuleNotRegisteredError } from '../wasm-module-error';\n\ntype VerifyFn = (input: unknown, ctx: unknown) => unknown;\n/** The engine exports the edge bridge needs once the wasm module is ready. */\ninterface EngineExports {\n  verify: VerifyFn;\n  verifyDelegation: VerifyFn;\n  applyRuleBundle: (bundleJson: string, nowUnix: number) => unknown;\n  feedDemand: (nowUnix: number) => unknown;\n  feedAttemptFinished: (outcome: string) => unknown;\n  feedStatus: (nowUnix: number) => unknown;\n  feedNoteMiss: (keyid: string, reason: string) => unknown;\n  vendorKeys: () => unknown;\n  render: (input: unknown) => EngineRenderEnvelope;\n  engineInfo: () => EngineManifest;\n  verifyStatusList: (requestJson: string) => StatusListVerification;\n  rootNeeds: (contextJson: string) => RootNeedsResult;\n  /** The initialised cedar-web glue, when the engine runs on it (see {@link edgeEngineCedarGlue}). */\n  cedarGlue?: unknown;\n}\ntype InitFn = (\n  moduleOrPath?: WebAssembly.Module | URL | string | Request | BufferSource\n) => Promise<unknown>;\n\nlet initialised: Promise<EngineExports> | null = null;\nlet providedModule: EngineWasmSource | undefined;\n/** The module the current attempt (`initialised`) instantiates. */\nlet initialisedWith: EngineWasmSource | undefined;\n\n/**\n * The module the engine runs on: the one given to `initEngineEdge`, else the\n * cedar-web module registered for policy (`initPolicyEvaluatorEdge`), which\n * carries the same engine.\n */\nfunction engineModule(): EngineWasmSource | undefined {\n  return providedModule ?? registeredCedarModule();\n}\n\n/**\n * Initialise the edge wasm module. Idempotent — subsequent calls\n * return the same in-flight or resolved promise. Host wrappers\n * should call this once at startup with the `wasmModule` they\n * statically imported from the package's `./wasm/kya-os-engine-web/`\n * subpath (see CLAUDE.md for the wrangler/webpack import pattern).\n *\n * @param wasmModule  The engine module the host imported\n *                    (`./wasm/kya-os-engine-web/kya_os_engine_bg.wasm`).\n *                    Required on the first call, on every runtime. Which\n *                    module an attempt uses:\n *                    - the first one given;\n *                    - a different one only after an attempt failed, so a\n *                      host can replace a bad module; never while an\n *                      attempt is pending or after one succeeded;\n *                    - after a failure, the module that failed, when the\n *                      retry passes none (`verifyRequestEdge` calls\n *                      `initEngineEdge()` itself), so one transient\n *                      failure is not permanent.\n *                    With no module ever given it rejects with\n *                    `WasmModuleNotRegisteredError`.\n */\nexport function initEngineEdge(wasmModule?: EngineWasmSource): Promise<void> {\n  // `initialised` is null only before the first attempt and after a\n  // failed one, which are exactly the times a given module may be taken.\n  if (wasmModule !== undefined && initialised === null) {\n    providedModule = wasmModule;\n  }\n  return ensureReady().then(() => undefined);\n}\n\nfunction ensureReady(): Promise<EngineExports> {\n  if (initialised) return initialised;\n\n  // Dynamic import keeps this module's top level free of side\n  // effects — important for edge runtimes that statically analyse\n  // imports at deploy time. The generated wasm-bindgen module\n  // has no static `.d.ts` types we can rely on; cast at the\n  // boundary.\n  const wasmModule = engineModule();\n  initialisedWith = wasmModule;\n  const pending = (async () => {\n    if (wasmModule === undefined) {\n      throw new WasmModuleNotRegisteredError('engine', 'initEngine()');\n    }\n    // A wasm runs only with the glue generated for it. The cedar-web build is\n    // this engine plus the Cedar evaluator, so its glue serves both, and the\n    // edge Cedar evaluator shares the instance (`edgeEngineCedarGlue`).\n    const cedar = isCedarModule(wasmModule);\n    // Package self-import — keeps the import string stable across\n    // the source-vs-dist location boundary; tsup leaves the literal\n    // in place (external regex in tsup.config.ts), the consumer's\n    // bundler resolves via the package's `./wasm/*` exports pattern.\n    const mod = (await (cedar\n      ? import('@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar-web/kya_os_engine.js')\n      : import(\n          '@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-web/kya_os_engine.js'\n        ))) as unknown as {\n      default: InitFn;\n      verify: VerifyFn;\n      verifyDelegation: VerifyFn;\n      applyRuleBundle: (bundleJson: string, nowUnix: number) => unknown;\n      feedDemand: (nowUnix: number) => unknown;\n      feedAttemptFinished: (outcome: string) => unknown;\n      feedStatus: (nowUnix: number) => unknown;\n      feedNoteMiss: (keyid: string, reason: string) => unknown;\n      vendorKeys: () => unknown;\n      render: (input: unknown) => EngineRenderEnvelope;\n      engineInfo: () => EngineManifest;\n      verifyStatusList: (requestJson: string) => StatusListVerification;\n      rootNeeds: (contextJson: string) => RootNeedsResult;\n    };\n    // wasm-bindgen's web-target init instantiates a `WebAssembly.Module`\n    // (or compiles bytes) passed as `{ module_or_path }`; the object form\n    // suppresses the deprecation warning the bare-argument form emits.\n    await mod.default({ module_or_path: wasmModule });\n    // Once per successful instantiation, before any caller sees the engine\n    // ready: the first real verify then finds it warm (./warm-up.ts).\n    warmEngine((input, ctx) => mod.verify(input, ctx) as VerifyResult);\n    return {\n      verify: mod.verify,\n      verifyDelegation: mod.verifyDelegation,\n      applyRuleBundle: mod.applyRuleBundle,\n      feedDemand: mod.feedDemand,\n      feedAttemptFinished: mod.feedAttemptFinished,\n      feedStatus: mod.feedStatus,\n      feedNoteMiss: mod.feedNoteMiss,\n      vendorKeys: mod.vendorKeys,\n      render: mod.render,\n      engineInfo: mod.engineInfo,\n      verifyStatusList: mod.verifyStatusList,\n      rootNeeds: mod.rootNeeds,\n      cedarGlue: cedar ? mod : undefined,\n    };\n  })();\n\n  // Cache the in-flight promise so concurrent callers join the\n  // same init. On rejection, clear the init cache but keep the\n  // module: a retry without an argument tries it again, and a retry\n  // that passes a module replaces it (`initEngineEdge`), so neither a\n  // transient failure nor a bad module is permanent.\n  initialised = pending;\n  // An attempt on the module registered for policy decides, for both sides,\n  // whether a newly registered module may replace it.\n  noteCedarAttempt(wasmModule, pending);\n  pending.catch(() => {\n    if (initialised === pending) {\n      initialised = null;\n    }\n  });\n  return initialised;\n}\n\n/**\n * The engine's cedar-web glue, initialised, when the engine runs on the\n * cedar-web module (or would, once it starts): the edge Cedar evaluator then\n * uses this one instance instead of instantiating its own. `null` when the\n * engine runs on the engine-web module.\n */\nexport function edgeEngineCedarGlue(): Promise<unknown> | null {\n  const module = initialised ? initialisedWith : engineModule();\n  if (!isCedarModule(module)) return null;\n  return ensureReady().then((exports) => exports.cedarGlue);\n}\n\n/**\n * Edge-runtime async equivalent of `engineVerify`.\n *\n * Identical contract (typed `AgentRequest` + `ContextSpec` in,\n * typed `VerifyResult` out) — only the return type changes from\n * `VerifyResult` to `Promise<VerifyResult>` because the underlying\n * wasm artifact is loaded async on this target.\n *\n * @throws If `engineVerify` rejects the input (deserialisation\n *   failure) or the engine returns a `VerifyError`. Verdicts\n *   surface inside the returned `VerifyResult`, not as throws.\n */\nexport async function engineVerifyEdge(\n  input: AgentRequest,\n  ctx: ContextSpec\n): Promise<VerifyResult> {\n  const { verify } = await ensureReady();\n  return verify(input, ctx) as VerifyResult;\n}\n\n/**\n * Edge-runtime async equivalent of `engineVerifyDelegation` — the standalone\n * Layer-2-only (`Authorization: Bearer <DelegationCredential>`) path,\n * `draft-kya-http-02` §4.3. Same contract as the bundler/node entries, only\n * the return type is `Promise<VerifyResult>` (the wasm artifact loads async on\n * this target). The resource server's own org DID rides on `ctx.resourceOrgDid`.\n */\nexport async function engineVerifyDelegationEdge(\n  input: DelegationVerifyInput,\n  ctx: ContextSpec\n): Promise<VerifyResult> {\n  const { verifyDelegation } = await ensureReady();\n  return verifyDelegation(input, ctx) as VerifyResult;\n}\n\n/**\n * Edge-runtime async equivalent of `engineRender`: the kya-os/http answer,\n * rendered in the engine. Same output as the bundler and Node entries.\n *\n * @throws {EngineRenderError} when the registered challenge context fails\n *   validation.\n */\nexport async function engineRenderEdge(\n  result: VerifyResult,\n  options: EngineRenderOptions = {}\n): Promise<EngineRenderedResponse> {\n  const { render } = await ensureReady();\n  return unwrapRenderEnvelope(render({ result, options }));\n}\n\n/**\n * Edge-runtime async equivalent of `engineVerifyStatusList`: verify a fetched\n * status list against its issuer's DID document. Never rejects for a bad\n * list; a rejection is `{ ok: false, code, message }`.\n */\n/** The trusted roots' DID-document needs (`rootNeeds`), on the edge engine. Never throws. */\nexport async function engineRootNeedsEdge(contextJson: string): Promise<RootNeedsResult> {\n  const { rootNeeds } = await ensureReady();\n  return rootNeeds(contextJson);\n}\n\nexport async function engineVerifyStatusListEdge(\n  requestJson: string\n): Promise<StatusListVerification> {\n  const { verifyStatusList } = await ensureReady();\n  return verifyStatusList(requestJson);\n}\n\n/** Edge-runtime async equivalent of `engineInfo`: the capability manifest. */\nexport async function engineInfoEdge(): Promise<EngineManifest> {\n  const { engineInfo } = await ensureReady();\n  return engineInfo();\n}\n\nexport {\n  EngineRenderError,\n  type EngineCapability,\n  type EngineManifest,\n  type EngineRenderEnvelope,\n  type EngineRenderErrorCode,\n  type EngineRenderOptions,\n  type EngineRenderedResponse,\n} from './render-types';\n\n// Re-export every typed shape so edge consumers don't need a second\n// import line for the ABI types.\nexport type {\n  AdoptedVendorKey,\n  AdoptedVendorKeys,\n  AgentRequest,\n  A2ARequest,\n  A2PRequest,\n  BehaviouralSignals,\n  BlockReason,\n  ChallengeParams,\n  ClientSignalAttribute,\n  ClientIntegrityInput,\n  ClientSignals,\n  ContextSpec,\n  Decision,\n  DelegationVerifyInput,\n  DetectionDetail,\n  DidDocument,\n  EngineConfig,\n  EngineInfo,\n  EnforcementMode,\n  FeedAttemptOutcome,\n  FeedDemandReason,\n  HttpSignedRequest,\n  InstructPayload,\n  IpReputation,\n  KeySetOutcome,\n  KeyType,\n  McpIPayload,\n  McpIRequest,\n  NetworkContext,\n  PlainHttpRequest,\n  ProxyInfo,\n  ProxyType,\n  RedirectTarget,\n  RuleBundleApplied,\n  RuleBundleRejected,\n  RuleBundleRejectionCode,\n  RuleBundleReport,\n  RoutingType,\n  SignalsEnvelope,\n  StabilityTier,\n  SuggestedAction,\n  Tier1PolicyMode,\n  Tier3Action,\n  TransportSignals,\n  VendorKeyFeedKeyStatus,\n  VendorKeyFeedStatus,\n  VendorKeyMissReason,\n  VerificationMethod,\n  VerifyResult,\n} from './types';\n\nexport async function engineApplyRuleBundleEdge(\n  bundleJson: string,\n  nowUnix: number\n): Promise<RuleBundleReport> {\n  const { applyRuleBundle } = await ensureReady();\n  return applyRuleBundle(bundleJson, nowUnix) as RuleBundleReport;\n}\n\nexport async function engineFeedDemandEdge(nowUnix: number): Promise<FeedDemandReason | undefined> {\n  const { feedDemand } = await ensureReady();\n  return feedDemand(nowUnix) as FeedDemandReason | undefined;\n}\n\nexport async function engineFeedAttemptFinishedEdge(outcome: FeedAttemptOutcome): Promise<boolean> {\n  const { feedAttemptFinished } = await ensureReady();\n  return feedAttemptFinished(outcome) as boolean;\n}\n\nexport async function engineFeedStatusEdge(nowUnix: number): Promise<VendorKeyFeedStatus | null> {\n  const { feedStatus } = await ensureReady();\n  return feedStatus(nowUnix) as VendorKeyFeedStatus | null;\n}\n\nexport async function engineFeedNoteMissEdge(\n  keyid: string,\n  reason: VendorKeyMissReason\n): Promise<boolean> {\n  const { feedNoteMiss } = await ensureReady();\n  return feedNoteMiss(keyid, reason) as boolean;\n}\n\nexport async function engineVendorKeysEdge(): Promise<AdoptedVendorKeys> {\n  const { vendorKeys } = await ensureReady();\n  return vendorKeys() as AdoptedVendorKeys;\n}\n","/**\n * `verifyRequestEdge` async-init orchestrator — Edge-WASM-2 (folded into\n * Phase D's PR).\n *\n * Mirror of [[./verify-request.ts]] for edge runtimes. Differs in only\n * three places:\n *\n *   1. Imports `engineVerifyEdge` + `initEngineEdge` from `../edge`\n *      instead of `engineVerify` from `../index` (Node target).\n *   2. Awaits `initEngineEdge()` before the engine call — async-init\n *      pattern required by the `--target web` wasm-bindgen build.\n *   3. The final engine call is `await engineVerifyEdge(...)` rather\n *      than the synchronous `engineVerify(...)`.\n *\n * **The two files MUST stay in sync.** Any change to verify-request.ts\n * (new adapter, new error-classification rule, new ContextSpec field)\n * MUST be mirrored here. The cross-target parity test in\n * [[__tests__/verify-request-parity.test.ts]] guards the verdict-shape\n * invariant — both orchestrators must produce identical\n * `VerifyResult.decision` / `engineInfo.name` on identical inputs.\n */\n\nimport type { ResolutionWarmerEngine } from '../adapters/resolution-warmer';\nimport {\n  engineApplyRuleBundleEdge,\n  engineFeedAttemptFinishedEdge,\n  engineFeedDemandEdge,\n  engineFeedNoteMissEdge,\n  engineFeedStatusEdge,\n  engineRootNeedsEdge,\n  engineVerifyDelegationEdge,\n  engineVendorKeysEdge,\n  engineVerifyEdge,\n  engineVerifyStatusListEdge,\n  initEngineEdge,\n} from '../edge';\nimport {\n  feedAfterVerify,\n  getDefaultVendorKeyFeed,\n  type VendorKeyFeedBindings,\n  type VendorKeyEdgeOptions,\n  type VendorKeyMiss,\n} from '../../vendor-keys/feed';\nimport type {\n  AdoptedVendorKeys,\n  AgentRequest,\n  ContextSpec,\n  DelegationVerifyInput,\n  DirectedVerifyResult,\n  EnforcementMode,\n  EngineWasmSource,\n  VerifyResult,\n} from '../types';\n\nimport {\n  buildAgentRequest,\n  extractBearerDelegationCredential,\n  extractAgentDid,\n  hasMalformedJwsBody,\n} from './build-agent-request';\nimport { isRefusedDelegationCarriage, withBearerDelegationIdentity } from './presented-credential';\nimport { defaultResolutionHost, TENANT_DECISION, verifyDirected } from './directed';\nimport { hostSynthesizedEngineInfo, parseErrorDetectionDetail } from './synthetic-results';\nimport type { IncomingHttpLike, VerifyRequestOpts } from './types';\nimport { isSignedBodyWithheld, refuseWithheldSignedBody } from './signed-body';\n\nexport type VerifyRequestEdgeOpts = VerifyRequestOpts & VendorKeyEdgeOptions;\n\nconst edgeFeedBindings: VendorKeyFeedBindings = {\n  demand: engineFeedDemandEdge,\n  finished: engineFeedAttemptFinishedEdge,\n  apply: engineApplyRuleBundleEdge,\n  status: engineFeedStatusEdge,\n  noteMiss: engineFeedNoteMissEdge,\n};\n\nexport async function vendorKeysEdge(options?: VendorKeyEdgeOptions): Promise<AdoptedVendorKeys> {\n  const keys = await engineVendorKeysEdge();\n  const tick = tickDefaultEdgeFeed();\n  try {\n    options?.waitUntil?.(tick);\n  } catch {\n    return keys;\n  }\n  return keys;\n}\n\nasync function tickDefaultEdgeFeed(): Promise<void> {\n  let round: Promise<unknown> | undefined;\n  try {\n    await getDefaultVendorKeyFeed(edgeFeedBindings).afterVerify({\n      waitUntil: (pending) => {\n        round = pending;\n      },\n    });\n  } catch {\n    return;\n  }\n  await round;\n}\n\nexport async function reportVendorKeyMissEdge(\n  miss: VendorKeyMiss,\n  options?: VendorKeyEdgeOptions\n): Promise<void> {\n  try {\n    await getDefaultVendorKeyFeed(edgeFeedBindings).afterVerify({\n      miss,\n      waitUntil: options?.waitUntil,\n    });\n  } catch {\n    return;\n  }\n}\n\ntype EngineVerifyDelegationFn = (\n  input: DelegationVerifyInput,\n  ctx: ContextSpec\n) => DirectedVerifyResult | Promise<DirectedVerifyResult>;\n\n/**\n * Factory — constructs a `verifyRequestEdge` closure that remembers the\n * one-shot Argus-not-configured warning state. Use this when the\n * host wrapper wants the startup log; call `verifyRequestEdge` directly\n * (the loose function below) if you don't.\n */\nexport function makeVerifyRequestEdge(\n  opts: VerifyRequestEdgeOpts\n): (req: IncomingHttpLike) => Promise<VerifyResult> {\n  let argusWarningLogged = false;\n  const log = opts.logger ?? defaultLogger;\n  return async function verifyRequestEdge(req: IncomingHttpLike): Promise<VerifyResult> {\n    if (!argusWarningLogged && !opts.argusUrl) {\n      log(\n        '[Checkpoint] WARNING: Argus URL not configured; reputation will degrade to baseline 1.0 (\"trust by default\"). Set ARGUS_API_URL to enable.'\n      );\n      argusWarningLogged = true;\n    }\n    return verifyRequestEdge_internal(req, opts);\n  };\n}\n\n/**\n * Single-shot async entry. Use [`makeVerifyRequestEdge`] in long-lived\n * hosts (so the Argus warning is one-shot per process); use this\n * loose form in tests + one-off invocations.\n */\nexport async function verifyRequestEdge(\n  req: IncomingHttpLike,\n  opts: VerifyRequestEdgeOpts\n): Promise<VerifyResult> {\n  return verifyRequestEdge_internal(req, opts);\n}\n\nasync function verifyRequestEdge_internal(\n  req: IncomingHttpLike,\n  opts: VerifyRequestEdgeOpts\n): Promise<VerifyResult> {\n  // JWS-aware preflight — see verify-request.ts for rationale. The\n  // edge variant MUST mirror Node-side behaviour exactly per the\n  // cross-runtime parity contract (D.1.5 — verify-request-parity).\n  if (hasMalformedJwsBody(req)) {\n    return blockWithParseError('malformed JWS body', opts.enforcementMode);\n  }\n\n  const bearerDelegation = extractBearerDelegationCredential(req);\n  const agentRequest = buildAgentRequest(req, {\n    legacyEnvelopeFallback: opts.legacyEnvelopeFallback,\n  });\n  // A kya-http/2 body the engine never received is unbound; refused at the end.\n  const signedBodyWithheld = isSignedBodyWithheld(req, agentRequest);\n  const refusedCarriage = !bearerDelegation && isRefusedDelegationCarriage(req, agentRequest);\n  const agentDid = refusedCarriage\n    ? null\n    : (bearerDelegation?.agentDid ?? extractAgentDid(agentRequest));\n  const reputation = agentDid ? { [agentDid]: await opts.reputationOracle.score(agentDid) } : {};\n\n  // **The async-init pre-call.** `initEngineEdge()` is idempotent: the first\n  // call in a long-lived edge host wraps the cold-boot latency, every later\n  // one resolves the completed init. Eager-init hosts call it at startup.\n  await initEngineEdge();\n\n  const ctx: ContextSpec = {\n    reputation,\n    tenantDecision: TENANT_DECISION,\n    nowUnix: opts.clock.nowUnix(),\n    enforcementMode: opts.enforcementMode,\n    resolution: 'engine-directed',\n    ...(opts.engineConfig ? { config: opts.engineConfig } : {}),\n    ...(opts.trustedDelegationRoots ? { trustedDelegationRoots: opts.trustedDelegationRoots } : {}),\n    ...(opts.resourceOrgDid ? { resourceOrgDid: opts.resourceOrgDid } : {}),\n    ...(opts.httpDelegation ? { httpDelegation: opts.httpDelegation } : {}),\n  };\n\n  // (engineVerifyEdge is async on the edge build, unlike the sync Node engineVerify.)\n  const verify: (input: AgentRequest, ctx: ContextSpec) => Promise<DirectedVerifyResult> =\n    engineVerifyEdge;\n  const verifyDelegation: EngineVerifyDelegationFn =\n    opts.engineVerifyDelegationFn ?? engineVerifyDelegationEdge;\n  const result = await verifyDirected(\n    (resources) =>\n      bearerDelegation\n        ? verifyDelegation(\n            {\n              credential: bearerDelegation.credential,\n              requiredScopes: opts.requiredScopes ?? [],\n            },\n            { ...ctx, resources }\n          )\n        : verify(agentRequest, { ...ctx, resources }),\n    opts.resolutionHost ?? defaultResolutionHost(),\n    { verifyStatusList: opts.engineVerifyStatusListFn ?? engineVerifyStatusListEdge },\n    opts.enforcementMode,\n    { nowUnix: ctx.nowUnix, waitUntil: opts.waitUntil }\n  );\n  if (!bearerDelegation) await feedAfterVerify(edgeFeedBindings, opts.waitUntil);\n\n  // Mirror verify-request.ts: the engine's decision stands.\n  return refuseWithheldSignedBody(\n    withBearerDelegationIdentity(result, bearerDelegation),\n    signedBodyWithheld\n  );\n}\n\n/**\n * Synthesize a `VerifyResult` carrying `Block(ParseError)` for the\n * DID-failure case. Identical to verify-request.ts's helper — kept in\n * sync so that DID-resolver-failure verdicts are byte-identical across\n * Node + Edge targets (the parity test asserts this).\n */\nfunction blockWithParseError(detail: string, enforcementMode: EnforcementMode): VerifyResult {\n  return {\n    decision: {\n      kind: 'Block',\n      reason: {\n        kind: 'ParseError',\n        detail,\n      },\n    },\n    detectionDetail: parseErrorDetectionDetail(detail),\n    enforcementMode,\n    engineInfo: hostSynthesizedEngineInfo(),\n  };\n}\n\nfunction defaultLogger(msg: string): void {\n  console.warn(msg);\n}\n\n// Re-export `initEngineEdge` so eager-init hosts can warm the wasm\n// load at startup instead of waiting for the first request:\n//\n//     import { initEngineEdge } from '@kya-os/checkpoint-wasm-runtime/orchestrator/edge';\n//     await initEngineEdge(webAssemblyModule);  // process startup\n//\n// Without this re-export, hosts would need a second import line\n// pointing at `./engine/edge`. Surfacing it through the orchestrator\n// subpath keeps the host wrapper's import block tight.\nexport { initEngineEdge };\nexport { WasmModuleNotRegisteredError } from '../../wasm-module-error';\n\n/**\n * Runtime-neutral names. Every `./orchestrator` build exports `verifyRequest`\n * and `initEngine`, so a host can import that one subpath and let the\n * package's export conditions choose the edge, Node or bundler engine.\n */\nexport { verifyRequestEdge as verifyRequest };\n\n/**\n * The engine calls a resolution warmer makes (`makeResolutionWarmer`), on the\n * edge engine `verifyRequestEdge` uses.\n */\nexport const resolutionEngine: ResolutionWarmerEngine = {\n  rootNeeds: engineRootNeedsEdge,\n  verifyStatusList: engineVerifyStatusListEdge,\n};\n/**\n * Load the engine from the module the host imported. The edge engine has no\n * URL fallback, so the first call passes `wasmModule` on every runtime; see\n * `initEngineEdge` for which module a retry uses.\n */\nexport async function initEngine(wasmModule?: EngineWasmSource): Promise<void> {\n  await initEngineEdge(wasmModule);\n}\nexport type { EngineWasmSource };\n\n// -----------------------------------------------------------------------------\n// Re-export shared orchestrator utilities so edge-runtime bundlers get\n// a complete surface from this single subpath. Without these, an edge\n// host wrapper would need two import lines:\n//\n//     import { verifyRequestEdge } from '.../orchestrator/edge';\n//     import { renderDecisionAsResponse } from '.../orchestrator';    // ← awkward\n//\n// The shared utilities (renderDecisionAsResponse, buildAgentRequest,\n// types) are pure / runtime-independent — same bytes in both targets.\n// -----------------------------------------------------------------------------\n\nexport {\n  buildAgentRequest,\n  extractAgentDid,\n  extractBearerDelegationCredential,\n  extractIssuer,\n  hasMalformedJwsBody,\n  type BearerDelegationCredentialRef,\n  type BuildAgentRequestOpts,\n} from './build-agent-request';\nexport { renderDecisionAsResponse } from './render-decision';\nexport { configureVendorKeyFeed, type VendorKeyFeedEvent } from '../../vendor-keys/feed';\nexport type { IncomingHttpLike, RenderedResponse, VerifyRequestOpts } from './types';\n","/**\n * Phase C + Edge-WASM-2 orchestrator barrel.\n *\n * The async entry point Phase D / E / future host wrappers compose.\n * Subpath: `@kya-os/checkpoint-wasm-runtime/orchestrator`.\n *\n * Two variants:\n *\n * - **Node** — sync engine via `engineVerify`. Use under Vercel Node-\n *   runtime / serverless functions / long-lived Node servers. Exported:\n *   `verifyRequest`, `makeVerifyRequest`.\n *\n * - **Edge** — async-init engine via `engineVerifyEdge`. Use under\n *   Vercel Edge runtime / Cloudflare Workers / browser embedding.\n *   Exported: `verifyRequestEdge`, `makeVerifyRequestEdge`,\n *   `initEngineEdge`. The `edge-runtime` + `browser` conditions on\n *   the `./orchestrator` subpath automatically route to this variant\n *   for edge bundlers; consumers can also import explicitly from\n *   `./orchestrator/edge`.\n *\n * The cross-target parity test in [[__tests__/verify-request-parity.test.ts]]\n * pins the verdict-equivalence invariant: both variants produce\n * identical `VerifyResult.decision` on identical inputs. Any change\n * to `verify-request.ts` MUST be mirrored in `verify-request-edge.ts`\n * (see the doc-comment header on both files).\n */\n\nimport {\n  engineApplyRuleBundle,\n  engineFeedAttemptFinished,\n  engineFeedDemand,\n  engineFeedNoteMiss,\n  engineFeedStatus,\n  engineRender,\n  engineRootNeeds,\n  engineVerify,\n  engineVerifyDelegation,\n  engineVerifyStatusList,\n} from '../index';\nimport type { ResolutionWarmerEngine } from '../adapters/resolution-warmer';\nimport type { EngineWasmSource } from '../types';\nimport { makeRenderDecision } from './render-engine';\nimport { afterThisNodeTask } from './node-deferral';\nimport { scheduleWarmUp } from '../warm-up';\nimport { createVerifyRequestApi } from './verify-request';\n\n// SDK-Next.js-Integration-Audit-1 (#2618): bind the bundler-target\n// engineVerify as the default for this orchestrator entry. The Node\n// fallback subpath (`./orchestrator/node`) binds the nodejs-target\n// variant instead — see `./verify-request.ts` module-doc for why the\n// engine import lives here rather than in `verify-request.ts`.\nconst bundlerApi = createVerifyRequestApi(\n  engineVerify,\n  engineVerifyDelegation,\n  {\n    demand: engineFeedDemand,\n    finished: engineFeedAttemptFinished,\n    apply: engineApplyRuleBundle,\n    status: engineFeedStatus,\n    noteMiss: engineFeedNoteMiss,\n    deferRound: afterThisNodeTask,\n  },\n  engineVerifyStatusList\n);\n\nexport const verifyRequest = bundlerApi.verifyRequest;\nexport const makeVerifyRequest = bundlerApi.makeVerifyRequest;\n\n/** Render a `VerifyResult` as the kya-os/http answer, in the bundler-target engine. */\nexport const renderDecisionAsResponse = makeRenderDecision(engineRender);\n\n/**\n * The engine calls a resolution warmer makes (`makeResolutionWarmer`), on the\n * same engine instance `verifyRequest` uses.\n */\nexport const resolutionEngine: ResolutionWarmerEngine = {\n  rootNeeds: engineRootNeeds,\n  verifyStatusList: engineVerifyStatusList,\n};\n\n// This build loads the engine when the module is imported, and warms it once\n// after the importing task (../warm-up.ts).\nconst warmEngineNow = scheduleWarmUp(engineVerify, afterThisNodeTask);\n\n/**\n * Warm the engine now if the after-import warm-up has not run yet, so a host\n * that awaits this at startup serves its first request from a warm engine.\n * `wasmModule` is ignored (the edge build needs it on Cloudflare Workers). It\n * exists so every `./orchestrator` build exports the same `initEngine`, and a\n * host can warm the engine without knowing which build its runtime resolved.\n */\nexport async function initEngine(_wasmModule?: EngineWasmSource): Promise<void> {\n  warmEngineNow();\n}\nexport type { EngineWasmSource };\nexport {\n  verifyRequestEdge,\n  makeVerifyRequestEdge,\n  initEngineEdge,\n  vendorKeysEdge,\n  reportVendorKeyMissEdge,\n} from './verify-request-edge';\nexport {\n  buildAgentRequest,\n  extractAgentDid,\n  extractBearerDelegationCredential,\n  extractIssuer,\n  hasMalformedJwsBody,\n  type BearerDelegationCredentialRef,\n  type BuildAgentRequestOpts,\n} from './build-agent-request';\nexport type { IncomingHttpLike, RenderedResponse, VerifyRequestOpts } from './types';\n"],"mappings":";;;;;;;;;AA2CA,SAAgB,mBAAmB,cAA8C;CAC/E,QAAQ,QAAQ,YAAY,mBAAmB,aAAa,QAAQ,OAAO,CAAC;AAC9E;;AAGA,SAAgB,mBAAmB,UAId;CACnB,MAAM,8BAAc,IAAI,IAAoB;CAC5C,KAAK,MAAM,CAAC,SAAS,SAAS,SAAS;EACrC,MAAM,MAAM,KAAK,YAAY;EAC7B,YAAY,IAAI,MAAM,YAAY,IAAI,GAAG,KAAK,KAAK,CAAC;CACtD;CACA,MAAM,UAAkC,CAAC;CACzC,MAAM,gBAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,MAAM,UAAU,SAAS,SACnC,IAAI,YAAY,IAAI,KAAK,YAAY,CAAC,MAAM,GAAG,QAAQ,QAAQ;MAC1D,cAAc,KAAK,CAAC,MAAM,KAAK,CAAC;CAEvC,OAAO;EACL,QAAQ,SAAS;EACjB;EACA,GAAI,cAAc,SAAS,IAAI,EAAE,cAAc,IAAI,CAAC;EACpD,GAAI,SAAS,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,SAAS,KAAiC;CAC3F;AACF;;;;;;;;;;;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