{"version":3,"file":"orchestrator-edge.mjs","names":[],"sources":["../src/vendor-keys/feed.ts","../src/engine/orchestrator/kya-signature-presentation.ts","../src/engine/orchestrator/utf8.ts","../src/engine/orchestrator/build-agent-request.ts","../src/engine/types.ts","../src/engine/orchestrator/synthetic-results.ts","../src/engine/orchestrator/directed.ts","../src/engine/orchestrator/signed-body.ts","../src/engine/orchestrator/render-engine.ts","../src/engine/orchestrator/render-decision.ts","../src/engine/orchestrator/verify-request-edge.ts"],"sourcesContent":["import type {\n  FeedAttemptOutcome,\n  FeedDemandReason,\n  KeySetOutcome,\n  RuleBundleRejectionCode,\n  RuleBundleReport,\n  VendorKeyFeedStatus,\n  VendorKeyMiss,\n  VendorKeyMissReason,\n} from '../engine/types';\n\nexport const VENDOR_KEY_FEED_URL = 'https://feeds.kya-os.ai/rules/v1/bundle.json';\nexport const MAX_RULE_BUNDLE_BYTES = 1_048_576;\n\nconst FEED_URL_ENV = 'KYA_VENDOR_KEY_FEED_URL';\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport interface VendorKeyFeedBindings {\n  demand: (nowUnix: number) => MaybePromise<FeedDemandReason | undefined>;\n  finished: (outcome: FeedAttemptOutcome) => MaybePromise<boolean>;\n  apply: (bundleJson: string, nowUnix: number) => MaybePromise<RuleBundleReport>;\n  status: (nowUnix: number) => MaybePromise<VendorKeyFeedStatus | null>;\n  noteMiss: (keyid: string, reason: VendorKeyMissReason) => MaybePromise<boolean>;\n  /**\n   * When a demanded round may start. Absent, it starts at once. The Node and\n   * bundler orchestrator builds pass `afterThisNodeTask`\n   * (`engine/orchestrator/node-deferral.ts`); the edge build\n   * passes nothing, because edge runtimes may expose a `setImmediate` that\n   * throws (Next.js Edge) and their `fetch` is native anyway. A deferral that\n   * throws or rejects starts the round at once.\n   */\n  deferRound?: () => Promise<void>;\n}\n\nexport type VendorKeyFeedFailureCode =\n  | RuleBundleRejectionCode\n  | 'fetch-failed'\n  | 'http-error'\n  | 'too-large'\n  | 'apply-failed';\n\nexport type VendorKeyFeedEvent =\n  | { kind: 'demand'; reason: FeedDemandReason }\n  | { kind: 'applied'; version: number; keyOutcomes: KeySetOutcome[]; durationMs: number }\n  | { kind: 'current'; version: number }\n  | { kind: 'failed'; code: VendorKeyFeedFailureCode; message: string; durationMs?: number }\n  | { kind: 'finished'; outcome: FeedAttemptOutcome };\n\nexport interface VendorKeyFeedOptions {\n  bindings: VendorKeyFeedBindings;\n  url?: string;\n  fetchImpl?: typeof fetch;\n  now?: () => number;\n  monotonicNow?: () => number;\n  maxBytes?: number;\n  onEvent?: (event: VendorKeyFeedEvent) => void;\n}\n\nexport type { VendorKeyMiss } from '../engine/types';\n\nexport interface VendorKeyEdgeOptions {\n  waitUntil?: (promise: Promise<unknown>) => void;\n}\n\nexport interface VendorKeyFeed {\n  afterVerify(outcome: {\n    miss?: VendorKeyMiss;\n    waitUntil?: VendorKeyEdgeOptions['waitUntil'];\n  }): Promise<void>;\n  getStatus(): Promise<VendorKeyFeedStatus | null>;\n}\n\ntype Failure = { code: VendorKeyFeedFailureCode; message: string };\ntype Downloaded = { body: string } | { failure: Failure };\nfunction describeError(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n\nfunction assertHttps(url: string): void {\n  if (new URL(url).protocol !== 'https:') {\n    throw new Error('vendor key feed url must be https');\n  }\n}\n\nasync function readBounded(\n  response: Response,\n  maxBytes: number,\n  onProgress: () => void\n): Promise<Downloaded> {\n  const tooLarge: Downloaded = {\n    failure: { code: 'too-large', message: `bundle exceeds ${maxBytes} bytes` },\n  };\n  const declared = Number(response.headers.get('content-length'));\n  if (Number.isFinite(declared) && declared > maxBytes) return tooLarge;\n\n  const reader = response.body?.getReader();\n  if (!reader) {\n    const text = await response.text();\n    return new TextEncoder().encode(text).byteLength > maxBytes ? tooLarge : { body: text };\n  }\n  const decoder = new TextDecoder();\n  let total = 0;\n  let body = '';\n  for (;;) {\n    const { done, value } = await reader.read();\n    if (done) break;\n    onProgress();\n    total += value.byteLength;\n    if (total > maxBytes) {\n      await reader.cancel();\n      return tooLarge;\n    }\n    body += decoder.decode(value, { stream: true });\n  }\n  return { body: body + decoder.decode() };\n}\n\nfunction handOff(\n  waitUntil: VendorKeyEdgeOptions['waitUntil'],\n  pending: Promise<unknown> | undefined\n): void {\n  try {\n    if (pending) waitUntil?.(pending);\n  } catch {\n    return;\n  }\n}\n\ninterface Flight {\n  controller: AbortController;\n  progressed: boolean;\n}\n\n/** Run a build's deferral; one that throws or rejects starts the round at once. */\nfunction deferred(deferRound: (() => Promise<void>) | undefined): Promise<void> {\n  if (!deferRound) return Promise.resolve();\n  try {\n    return deferRound().catch(() => undefined);\n  } catch {\n    return Promise.resolve();\n  }\n}\n\nexport function createVendorKeyFeed(options: VendorKeyFeedOptions): VendorKeyFeed {\n  const {\n    bindings,\n    url = VENDOR_KEY_FEED_URL,\n    fetchImpl = globalThis.fetch,\n    now = () => Date.now(),\n    monotonicNow = () => performance.now(),\n    maxBytes = MAX_RULE_BUNDLE_BYTES,\n    onEvent,\n  } = options;\n\n  assertHttps(url);\n\n  const nowSec = (): number => Math.floor(now() / 1000);\n\n  async function fetchBounded(flight: Flight): Promise<Downloaded> {\n    const onProgress = (): void => {\n      flight.progressed = true;\n    };\n    const response = await fetchImpl(url, {\n      signal: flight.controller.signal,\n      cache: 'no-store',\n      redirect: 'manual',\n    });\n    onProgress();\n    if (!response.ok) {\n      return { failure: { code: 'http-error', message: `feed host responded ${response.status}` } };\n    }\n    return readBounded(response, maxBytes, onProgress);\n  }\n\n  async function download(flight: Flight): Promise<Downloaded> {\n    return fetchBounded(flight).catch(\n      (err: unknown): Downloaded => ({\n        failure: { code: 'fetch-failed', message: describeError(err) },\n      })\n    );\n  }\n\n  function emit(event: VendorKeyFeedEvent): void {\n    try {\n      onEvent?.(event);\n    } catch {\n      return;\n    }\n  }\n\n  function fail(err: unknown, durationMs?: number): void {\n    emit({\n      kind: 'failed',\n      code: 'apply-failed',\n      message: describeError(err),\n      ...(durationMs === undefined ? {} : { durationMs }),\n    });\n  }\n\n  async function noteMiss(miss: VendorKeyMiss): Promise<void> {\n    try {\n      await bindings.noteMiss(miss.keyid, miss.reason);\n    } catch (err) {\n      fail(err);\n    }\n  }\n\n  let current: Flight | undefined;\n\n  async function attempt(flight: Flight): Promise<FeedAttemptOutcome | undefined> {\n    const signal = flight.controller.signal;\n    const startedAt = monotonicNow();\n    const elapsed = (): number => Math.round(monotonicNow() - startedAt);\n    try {\n      const downloaded = await download(flight);\n      if (signal.aborted) return undefined;\n      if ('failure' in downloaded) {\n        emit({ kind: 'failed', ...downloaded.failure, durationMs: elapsed() });\n        return 'failed';\n      }\n      const report = await bindings.apply(downloaded.body, nowSec());\n      if (signal.aborted) return undefined;\n      if (!report.ok) {\n        emit({ kind: 'failed', code: report.code, message: report.message, durationMs: elapsed() });\n        return 'failed';\n      }\n      if (report.unchanged) {\n        emit({ kind: 'current', version: report.version });\n        return 'current';\n      }\n      emit({\n        kind: 'applied',\n        version: report.version,\n        keyOutcomes: report.keyOutcomes,\n        durationMs: elapsed(),\n      });\n      return 'applied';\n    } catch (err) {\n      if (signal.aborted) return undefined;\n      fail(err, elapsed());\n      return 'failed';\n    }\n  }\n\n  async function round(flight: Flight): Promise<void> {\n    const outcome = await attempt(flight);\n    if (current === flight) current = undefined;\n    if (outcome === undefined) return;\n    try {\n      await bindings.finished(outcome);\n    } catch (err) {\n      fail(err);\n    }\n    emit({ kind: 'finished', outcome });\n  }\n\n  function startRound(): Promise<void> {\n    current?.controller.abort();\n    const flight: Flight = { controller: new AbortController(), progressed: false };\n    current = flight;\n    return deferred(bindings.deferRound)\n      .then(() => (flight.controller.signal.aborted ? undefined : round(flight)))\n      .finally(() => {\n        if (current === flight) current = undefined;\n      });\n  }\n\n  return {\n    async afterVerify(verified) {\n      try {\n        if (verified.miss) await noteMiss(verified.miss);\n        const asked = await bindings.demand(nowSec());\n        if (asked === undefined) return;\n        if (current?.progressed) {\n          current.progressed = false;\n          return;\n        }\n        emit({ kind: 'demand', reason: asked });\n        handOff(verified.waitUntil, startRound());\n      } catch (err) {\n        fail(err);\n      }\n    },\n    getStatus: async () => bindings.status(nowSec()),\n  };\n}\n\ninterface SharedFeedConfig {\n  url?: string;\n  onEvent?: (event: VendorKeyFeedEvent) => void;\n  generation: number;\n}\n\nconst CONFIG_KEY = Symbol.for('kya.vendorKeyFeed.config');\n\nfunction sharedConfig(): SharedFeedConfig {\n  const holder = globalThis as unknown as Record<symbol, SharedFeedConfig | undefined>;\n  return (holder[CONFIG_KEY] ??= { generation: 0 });\n}\n\nconst defaultFeeds = new WeakMap<\n  VendorKeyFeedBindings,\n  { feed: VendorKeyFeed; generation: number }\n>();\n\nexport function configureVendorKeyFeed(config: {\n  url?: string;\n  onEvent?: (event: VendorKeyFeedEvent) => void;\n}): void {\n  if (config.url !== undefined) assertHttps(config.url);\n  const shared = sharedConfig();\n  shared.url = config.url;\n  shared.onEvent = config.onEvent;\n  shared.generation += 1;\n}\n\nexport function getDefaultVendorKeyFeed(bindings: VendorKeyFeedBindings): VendorKeyFeed {\n  const shared = sharedConfig();\n  const existing = defaultFeeds.get(bindings);\n  if (existing && existing.generation === shared.generation) return existing.feed;\n\n  const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n    ?.env;\n  const feed = createVendorKeyFeed({\n    bindings,\n    url: shared.url ?? (env?.[FEED_URL_ENV] || VENDOR_KEY_FEED_URL),\n    onEvent: shared.onEvent,\n  });\n  defaultFeeds.set(bindings, { feed, generation: shared.generation });\n  return feed;\n}\n\nexport async function feedAfterVerify(\n  bindings: VendorKeyFeedBindings,\n  waitUntil?: VendorKeyEdgeOptions['waitUntil']\n): Promise<void> {\n  try {\n    await getDefaultVendorKeyFeed(bindings).afterVerify({ waitUntil });\n  } catch {\n    return;\n  }\n}\n","import type { IncomingHttpLike } from './types';\n\n/** Routing only. The engine validates the full profile, including missing or\n * malformed counterparts. Match the same member boundaries as Rust and .NET;\n * never let a quoted parameter or another vendor's label select KYA. */\nexport function hasKyaSignatureMember(headers: IncomingHttpLike['headers']): boolean {\n  const fields: Record<string, string[]> = { signature: [], 'signature-input': [] };\n  for (const [name, values] of Object.entries(headers)) {\n    const target = name.toLowerCase();\n    if (target !== 'signature' && target !== 'signature-input') continue;\n    for (const value of Array.isArray(values) ? values : [values]) {\n      if (typeof value === 'string') fields[target].push(value);\n    }\n  }\n  // RFC field combination and the Rust verifier preserve quote state across\n  // duplicate lines. Scanning each line alone can hide a real member or turn\n  // a quoted continuation into a false KYA presentation.\n  return Object.values(fields).some((values) => hasMember(values.join(', ')));\n}\n\nfunction hasMember(value: string): boolean {\n  let memberStart = true;\n  let quoted = false;\n  let escaped = false;\n  for (let i = 0; i < value.length; i++) {\n    const c = value[i];\n    if (quoted) {\n      if (escaped) escaped = false;\n      else if (c === '\\\\') escaped = true;\n      else if (c === '\"') quoted = false;\n      continue;\n    }\n    if (memberStart) {\n      if (c === ' ' || c === '\\t') continue;\n      if (value.startsWith('kya', i) && (i + 3 === value.length || '=;, \\t'.includes(value[i + 3])))\n        return true;\n      memberStart = false;\n    }\n    if (c === '\"') quoted = true;\n    else if (c === ',') memberStart = true;\n  }\n  return false;\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 * 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 * 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 * `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 * TS `Decision` → HTTP renderer, exported by the edge orchestrator entry only.\n *\n * The engine owns the verdict→HTTP mapping (`rust/crates/kya-os-engine/src/render`),\n * and the Node and bundler orchestrator builds render through it\n * (`render-engine.ts`). The edge entry re-exports this renderer instead, and\n * `render-parity-oracle.test.ts` holds it to the engine's output on every\n * render-parity vector.\n *\n * Translates a `VerifyResult` into a framework-neutral\n * `{ status, headers, body }` shape that the Next.js and Express adapters\n * apply.\n *\n * Mapping table (§ 4.5 of Phase C kickoff):\n *\n * | Decision                          | HTTP | Notes                                   |\n * |-----------------------------------|------|-----------------------------------------|\n * | Permit                            | null | Pass through to next handler            |\n * | Block(Unauthenticated)            | 401  | WWW-Authenticate header                 |\n * | Block(InvalidSignature)           | 403  |                                          |\n * | Block(Revoked)                    | 403  | 401 Delegation wire when lapsed + reg.  |\n * | Block(Expired)                    | 401  | Delegation wire when lapsed + reg.      |\n * | Block(OutOfScope)                 | 403  | 401 Delegation wire when registered     |\n * | Block(LowReputation)              | 403  | Body carries score + threshold          |\n * | Block(PolicyDenied)               | 403  | Body carries detail                     |\n * | Block(ParseError)                 | 400  | Body carries detail                     |\n * | Block(AgentAttribution)           | 403  | Body carries vendor + tier + confidence |\n * | Block(Tier3UAMatch)               | 403  | Body carries pattern_id + kind + conf   |\n * | Challenge                         | 401  | Body carries ChallengeParams            |\n * | Redirect                          | 302  | Location header                         |\n * | Instruct                          | 422  | application/problem+json body           |\n *\n * Observe mode overrides: every verdict renders as `status: null`\n * (pass through) with an `X-Checkpoint-Would-Have-Been` header\n * carrying the verdict kind, plus the standard attribution headers.\n *\n * Every response carries the Phase 0.1 attribution headers:\n * `X-Checkpoint-Engine`, `X-Checkpoint-Engine-Version`, and\n * (when present) `X-Checkpoint-Ruleset-Hash`.\n */\n\nimport type { BlockReason, VerifyResult } from '../types';\nimport { KYA_HTTP_ERROR } from '@kya-os/checkpoint-shared/kya-http';\nimport {\n  buildDelegationChallengeEnvelope,\n  type ChallengeWireInput,\n} from '@kya-os/checkpoint-shared/host-adapter';\n\nimport {\n  KYA_IDENTITY_PENDING,\n  isRetryableKyaStatus,\n  readKyaErrorCode,\n  statusForKyaError,\n} from './presented-credential';\nimport { isConsentRemediableBlock } from './consent-remediable';\nimport { toRenderedResponse } from './render-engine';\nimport type { RenderedResponse } from './types';\n\n/** Options for {@link renderDecisionAsResponse}. */\nexport interface RenderDecisionOptions {\n  /**\n   * Serve the body-readable HTTP 200 fetcher envelope for the agent-facing\n   * step-up verdicts (Challenge / Instruct) instead of the spec 401 / 422.\n   * The caller decides this via the shared `serveBodyReadable200` predicate\n   * (`@kya-os/checkpoint-shared`) when its challenge-emission mode is\n   * `negotiated`. Same body, no `WWW-Authenticate`; a cooperative-UX bridge\n   * for fetchers that drop 4xx/5xx bodies, NOT an access control.\n   */\n  bodyReadable200?: boolean;\n  /**\n   * Complete registered context for a canonical Delegation challenge. Hosts\n   * resolve this asynchronously before calling the synchronous renderer.\n   */\n  delegationChallenge?: ChallengeWireInput;\n  /** The host attempted registered context resolution but none was available. */\n  challengeContextRequested?: boolean;\n}\n\nexport function renderDecisionAsResponse(\n  result: VerifyResult,\n  options?: RenderDecisionOptions\n): RenderedResponse {\n  const baseHeaders = buildBaseHeaders(result);\n\n  // Observe mode never blocks — pass through with would-have-been headers.\n  if (result.enforcementMode === 'observe') {\n    return {\n      status: null,\n      headers: {\n        ...baseHeaders,\n        'X-Checkpoint-Mode': 'observe',\n        'X-Checkpoint-Would-Have-Been': result.decision.kind,\n        ...wouldHaveBeenReasonHeader(result),\n      },\n    };\n  }\n\n  switch (result.decision.kind) {\n    case 'Permit':\n      return {\n        status: null,\n        headers: { ...baseHeaders, 'X-Checkpoint-Decision': 'permit' },\n      };\n\n    case 'Block': {\n      const reason = result.decision.reason;\n      const headers = {\n        ...baseHeaders,\n        'X-Checkpoint-Decision': 'block',\n        'X-Checkpoint-Reason': reason.kind,\n      };\n\n      if (options?.delegationChallenge && isConsentRemediableBlock(result)) {\n        return renderDelegationChallenge(\n          {\n            ...headers,\n            'X-Checkpoint-Decision': 'challenge',\n            'X-Checkpoint-Challenge': options.delegationChallenge.sid,\n          },\n          options.delegationChallenge,\n          options.bodyReadable200\n        );\n      }\n\n      // #3388: an identity-pending reject (a presented kya credential whose trusted\n      // roots aren't warm yet) is RETRYABLE — 503 + Retry-After, NOT a hard 4xx.\n      // Distinct from a confirmed §9 verify failure below.\n      if (result.detectionDetail.metadata?.['resolution_pending'] === true) {\n        return {\n          status: 503,\n          headers: { ...headers, 'Retry-After': '1' },\n          body: { error: KYA_IDENTITY_PENDING },\n        };\n      }\n\n      // #3362 break #2: when the engine tagged the Block with its §9\n      // `kya_error_code` (kyaos/*), render the kyaos wire body { error } + the\n      // registry-defined status (error-codes.json): 401 for the identity class,\n      // 403 for the delegation / profile class (including\n      // assurance-insufficient), 503 for the retryable fail-closed codes, 429\n      // for replay-capacity. Otherwise fall back to the coarse reason-keyed body.\n      const kyaError = readKyaErrorCode(result.detectionDetail.metadata);\n      if (kyaError) {\n        const status = statusForKyaError(kyaError);\n        // A retryable §9 status (503, e.g. kyaos/status-pending, a cold status\n        // list that may warm, #3345; or 429 replay-capacity) carries\n        // Retry-After, mirroring the identity-pending branch above, so a\n        // client backs off and retries rather than treating it as terminal.\n        const kyaHeaders = isRetryableKyaStatus(status)\n          ? { ...headers, 'Retry-After': '1' }\n          : headers;\n        return { status, headers: kyaHeaders, body: { error: kyaError } };\n      }\n\n      return {\n        status: httpStatusForBlockReason(reason),\n        headers,\n        body: blockResponseBody(reason),\n      };\n    }\n\n    case 'Challenge': {\n      const params = result.decision.params;\n      const challengeHeaders = {\n        ...baseHeaders,\n        'X-Checkpoint-Decision': 'challenge',\n        'X-Checkpoint-Challenge': params.nonce,\n      };\n      if (options?.delegationChallenge) {\n        // fetcher-200 has no committed fixture for approval_quorum (#4795);\n        // force the spec 401 envelope for that kind regardless of the\n        // caller's negotiated bodyReadable200 preference so a cooperative\n        // fetcher request never throws out of the synchronous renderer.\n        return renderDelegationChallenge(\n          challengeHeaders,\n          options.delegationChallenge,\n          options.bodyReadable200\n        );\n      }\n      if (!options?.challengeContextRequested) {\n        if (options?.bodyReadable200) {\n          return {\n            status: 200,\n            headers: { ...challengeHeaders, ...fetcherHintHeaders('challenge') },\n            body: { challenge: params },\n          };\n        }\n        return {\n          status: 401,\n          headers: challengeHeaders,\n          body: { challenge: params },\n        };\n      }\n\n      // Once a host opts into registered Delegation context, resolution failure\n      // is temporarily unavailable—not permission to fabricate or downgrade.\n      return {\n        status: 503,\n        headers: {\n          ...challengeHeaders,\n          'Content-Type': 'application/json',\n          'Cache-Control': 'no-store',\n          'Retry-After': '1',\n          'KYA-Action': 'challenge',\n        },\n        body: { error: KYA_HTTP_ERROR.STATUS_PENDING },\n      };\n    }\n\n    case 'Redirect': {\n      const target = result.decision.target;\n      return {\n        status: 302,\n        headers: {\n          ...baseHeaders,\n          'X-Checkpoint-Decision': 'redirect',\n          Location: target.url,\n          'X-Checkpoint-Redirect-Reason': target.reason,\n        },\n      };\n    }\n\n    case 'Instruct': {\n      const payload = result.decision.payload;\n      const body = {\n        type: payload.problem,\n        title: payload.title,\n        suggestedActions: payload.suggestedActions,\n      };\n      // Dual envelope: 200 for cooperative fetchers (off 422), else the spec\n      // 422 problem+json. Body identical across both.\n      if (options?.bodyReadable200) {\n        return {\n          status: 200,\n          headers: {\n            ...baseHeaders,\n            'X-Checkpoint-Decision': 'instruct',\n            ...fetcherHintHeaders('instruct'),\n          },\n          body,\n        };\n      }\n      return {\n        status: 422,\n        headers: {\n          ...baseHeaders,\n          'X-Checkpoint-Decision': 'instruct',\n          'Content-Type': 'application/problem+json',\n        },\n        body,\n      };\n    }\n  }\n}\n\n// -----------------------------------------------------------------------------\n// Helpers.\n// -----------------------------------------------------------------------------\n\nfunction renderDelegationChallenge(\n  headers: Record<string, string>,\n  context: ChallengeWireInput,\n  bodyReadable200: boolean | undefined\n): RenderedResponse {\n  const envelope = buildDelegationChallengeEnvelope(\n    context,\n    bodyReadable200 && context.kind !== 'approval_quorum' ? 'fetcher-200' : 'spec-401'\n  );\n  // Split the fields the way the engine renderer's are split: a field named\n  // once is set, so the envelope's Content-Type replaces the framework default\n  // instead of joining it; only a repeated field (WWW-Authenticate) is appended.\n  return toRenderedResponse({\n    status: envelope.status,\n    headers: [...Object.entries(headers), ...envelope.headers],\n    body: envelope.body,\n  });\n}\n\n/**\n * Hint headers for the body-readable HTTP 200 fetcher envelope (PR 3,\n * draft-kya-http-02 §8.1). Deliberately NO `WWW-Authenticate` (a 200 carrying\n * it is reinterpreted as a 401 by some agent fetchers, re-dropping the body)\n * and NO `Retry-After` (cadence lives in the body). `KYA-Action` is also the\n * observability discriminator so a challenge-200 is not miscounted as a served\n * 200. The engine step-up carries no consent URL, so `KYA-Auth-Url`/`Link` are\n * intentionally absent here — those belong to the §8.1 delegation surfaces.\n */\nfunction fetcherHintHeaders(action: 'challenge' | 'instruct'): Record<string, string> {\n  return {\n    'Cache-Control': 'no-store',\n    'KYA-Auth-Required': 'true',\n    'KYA-Action': action,\n  };\n}\n\nfunction buildBaseHeaders(result: VerifyResult): Record<string, string> {\n  const headers: Record<string, string> = {\n    'X-Checkpoint-Engine': result.engineInfo.name,\n    'X-Checkpoint-Engine-Version': result.engineInfo.version,\n  };\n  if (result.engineInfo.rulesetHash) {\n    headers['X-Checkpoint-Ruleset-Hash'] = result.engineInfo.rulesetHash;\n  }\n\n  // Tier 1 attribution: surface `verified_tier` / `verified_vendor` /\n  // `verified_protocol` from `detectionDetail.metadata` as response\n  // headers when present. The engine populates this metadata when\n  // Tier 1 (cryptographic) verification succeeds; surfacing it on\n  // the wire makes Tier 1 state observable without consumers having\n  // to parse the body. Added after Bench-Detection-Delta V3 (2026-05-20)\n  // showed operators couldn't tell from response headers whether\n  // Tier 1 was actually engaging — only the engine's `onResult`\n  // callback exposed `metadata.verified_*` previously.\n  //\n  // Each field is optional and only emitted when present. The metadata\n  // bag is `Record<string, unknown>`, so each lookup is type-narrowed\n  // before stringification.\n  const meta = result.detectionDetail.metadata;\n  if (meta) {\n    const verifiedTier = meta.verified_tier;\n    // Defensive parity with verified_vendor / verified_protocol:\n    // - number path uses `Number.isFinite` to exclude NaN / ±Infinity\n    //   (`typeof NaN === 'number'` is true, so a plain typeof check\n    //   would let NaN through and emit `X-Checkpoint-Verified-Tier: NaN`).\n    // - string path requires non-empty (mirrors the vendor / protocol\n    //   defensive guard).\n    if (typeof verifiedTier === 'number' && Number.isFinite(verifiedTier)) {\n      headers['X-Checkpoint-Verified-Tier'] = String(verifiedTier);\n    } else if (typeof verifiedTier === 'string' && verifiedTier.length > 0) {\n      headers['X-Checkpoint-Verified-Tier'] = verifiedTier;\n    }\n    const verifiedVendor = meta.verified_vendor;\n    if (typeof verifiedVendor === 'string' && verifiedVendor.length > 0) {\n      headers['X-Checkpoint-Verified-Vendor'] = verifiedVendor;\n    }\n    const verifiedProtocol = meta.verified_protocol;\n    if (typeof verifiedProtocol === 'string' && verifiedProtocol.length > 0) {\n      headers['X-Checkpoint-Verified-Protocol'] = verifiedProtocol;\n    }\n  }\n\n  return headers;\n}\n\nfunction httpStatusForBlockReason(reason: BlockReason): number {\n  switch (reason.kind) {\n    case 'Unauthenticated':\n    case 'Expired':\n      return 401;\n    case 'ParseError':\n      return 400;\n    case 'InvalidSignature':\n    case 'Revoked':\n    case 'OutOfScope':\n    case 'LowReputation':\n    case 'PolicyDenied':\n    case 'AgentAttribution':\n    case 'Tier3UAMatch':\n      return 403;\n  }\n}\n\nfunction blockResponseBody(reason: BlockReason): object {\n  switch (reason.kind) {\n    case 'Revoked':\n    case 'InvalidSignature':\n    case 'Unauthenticated':\n    case 'Expired':\n      return { error: humanError(reason.kind), reason: reason.kind };\n    case 'OutOfScope':\n      return {\n        error: 'requested scope is not granted',\n        reason: 'OutOfScope',\n        requested: reason.requested,\n        granted: reason.granted,\n      };\n    case 'LowReputation':\n      return {\n        error: 'agent reputation below tenant threshold',\n        reason: 'LowReputation',\n        score: reason.score,\n        threshold: reason.threshold,\n      };\n    case 'PolicyDenied':\n      return {\n        error: 'tenant policy denied the request',\n        reason: 'PolicyDenied',\n        detail: reason.detail,\n      };\n    case 'ParseError':\n      return {\n        error: 'request envelope could not be parsed',\n        reason: 'ParseError',\n        detail: reason.detail,\n      };\n    case 'AgentAttribution':\n      return {\n        error: 'request identified as agent traffic via Tier-2 IP+UA cross-match',\n        reason: 'AgentAttribution',\n        vendor: reason.vendor,\n        tier: reason.tier,\n        confidence: reason.confidence,\n      };\n    case 'Tier3UAMatch':\n      return {\n        error: 'request identified as agent traffic via Tier-3 UA pattern match',\n        reason: 'Tier3UAMatch',\n        pattern_id: reason.pattern_id,\n        pattern_kind: reason.pattern_kind,\n        confidence: reason.confidence,\n      };\n  }\n}\n\nfunction humanError(kind: 'Revoked' | 'InvalidSignature' | 'Unauthenticated' | 'Expired'): string {\n  switch (kind) {\n    case 'Revoked':\n      return 'credential has been revoked';\n    case 'InvalidSignature':\n      return 'request signature failed verification';\n    case 'Unauthenticated':\n      return 'authentication required';\n    case 'Expired':\n      return 'credential is expired';\n  }\n}\n\n/** Observe-mode helper — surface the block reason in a side header so */\n/** dashboards can attribute the would-have-been verdict. */\nfunction wouldHaveBeenReasonHeader(result: VerifyResult): Record<string, string> {\n  if (result.decision.kind === 'Block') {\n    return { 'X-Checkpoint-Would-Have-Been-Reason': result.decision.reason.kind };\n  }\n  return {};\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"],"mappings":";;;;;;;;AAWA,MAAa,sBAAsB;AACnC,MAAa,wBAAwB;AAErC,MAAM,eAAe;AA6DrB,SAAS,cAAc,KAAsB;CAC3C,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AAEA,SAAS,YAAY,KAAmB;CACtC,IAAI,IAAI,IAAI,GAAG,CAAC,CAAC,aAAa,UAC5B,MAAM,IAAI,MAAM,mCAAmC;AAEvD;AAEA,eAAe,YACb,UACA,UACA,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