theokit 0.72.1 → 0.73.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{actions-virtual-module-EAKYEMGF.js → actions-virtual-module-QCDKQ6QD.js} +4 -4
- package/dist/adapters/security-headers.d.ts +27 -11
- package/dist/adapters/security-headers.js.map +1 -1
- package/dist/{agent-VJTZ4DQ7.js → agent-OWJ5A7W5.js} +2 -2
- package/dist/{app-typed-client-LHH77QDB.js → app-typed-client-2PTK2SJH.js} +4 -4
- package/dist/{aws-lambda-7AZNJGWU.js → aws-lambda-OP2L5RKZ.js} +3 -3
- package/dist/{build-23QF5FNQ.js → build-CVP2XU5M.js} +5 -5
- package/dist/{bun-NKVHOFSJ.js → bun-CZXHPK2W.js} +4 -4
- package/dist/{chunk-V5SSTT3C.js → chunk-C43AHOHI.js} +1 -1
- package/dist/chunk-C43AHOHI.js.map +1 -0
- package/dist/{chunk-XLSJWKSP.js → chunk-D3M7LPHY.js} +12 -6
- package/dist/{chunk-XLSJWKSP.js.map → chunk-D3M7LPHY.js.map} +1 -1
- package/dist/{chunk-E2RC367T.js → chunk-EDBQM6RB.js} +3 -3
- package/dist/{chunk-QD5X56I3.js → chunk-FNJVSFEC.js} +1 -1
- package/dist/chunk-FNJVSFEC.js.map +1 -0
- package/dist/{chunk-DKX7LF5Q.js → chunk-HDAILYVM.js} +2 -2
- package/dist/{chunk-RE2WE7CD.js → chunk-LOOOB46A.js} +2 -2
- package/dist/{chunk-L6UHMWXU.js → chunk-M3DT6EMK.js} +3 -3
- package/dist/chunk-M3DT6EMK.js.map +1 -0
- package/dist/{chunk-PEL3MJLM.js → chunk-MX63AWEK.js} +1 -1
- package/dist/{chunk-PEL3MJLM.js.map → chunk-MX63AWEK.js.map} +1 -1
- package/dist/{chunk-IB5VIXLR.js → chunk-R36YNWBU.js} +2 -2
- package/dist/{chunk-C5CAL3DX.js → chunk-SEGD3JUC.js} +1 -1
- package/dist/chunk-SEGD3JUC.js.map +1 -0
- package/dist/{chunk-4EQEJ4PH.js → chunk-WRHT5NAJ.js} +20 -14
- package/dist/{chunk-4EQEJ4PH.js.map → chunk-WRHT5NAJ.js.map} +1 -1
- package/dist/cli/index.js +6 -6
- package/dist/client/index.d.ts +18 -1
- package/dist/client/index.js +15 -1
- package/dist/client/index.js.map +1 -1
- package/dist/{cloudflare-4M4XVNUH.js → cloudflare-2SVRRVV5.js} +3 -3
- package/dist/{deno-deploy-IVACZ62D.js → deno-deploy-OK4QFJIZ.js} +4 -4
- package/dist/{dev-JDJWMRLH.js → dev-B2IZEVAD.js} +6 -6
- package/dist/index.js +1 -1
- package/dist/{internal-api-VDYOXOT7.js → internal-api-5Y3MLZH4.js} +4 -4
- package/dist/{mcp-WJNCTM7M.js → mcp-GJQIREYC.js} +2 -2
- package/dist/{netlify-3HEWV375.js → netlify-IAC53FVZ.js} +3 -3
- package/dist/{observability-bootstrap-FP6LMMJE.js → observability-bootstrap-DOWRMADT.js} +2 -2
- package/dist/{preview-BARW75PN.js → preview-XBP622HM.js} +3 -3
- package/dist/{registry-SDBODRU6.js → registry-L6JG75LY.js} +7 -7
- package/dist/{server-boundary-AO6EELRF.js → server-boundary-IFIYNGTA.js} +4 -4
- package/dist/{start-4JTYXQQJ.js → start-JGNBTTG2.js} +7 -7
- package/dist/{vercel-5PMYEEKF.js → vercel-EHAOKPF7.js} +3 -3
- package/dist/vite-plugin/index.js +1 -1
- package/dist/{vite-plugin-3ON45MQE.js → vite-plugin-54XIRMKT.js} +6 -6
- package/package.json +2 -2
- package/dist/chunk-C5CAL3DX.js.map +0 -1
- package/dist/chunk-L6UHMWXU.js.map +0 -1
- package/dist/chunk-QD5X56I3.js.map +0 -1
- package/dist/chunk-V5SSTT3C.js.map +0 -1
- /package/dist/{actions-virtual-module-EAKYEMGF.js.map → actions-virtual-module-QCDKQ6QD.js.map} +0 -0
- /package/dist/{agent-VJTZ4DQ7.js.map → agent-OWJ5A7W5.js.map} +0 -0
- /package/dist/{app-typed-client-LHH77QDB.js.map → app-typed-client-2PTK2SJH.js.map} +0 -0
- /package/dist/{aws-lambda-7AZNJGWU.js.map → aws-lambda-OP2L5RKZ.js.map} +0 -0
- /package/dist/{build-23QF5FNQ.js.map → build-CVP2XU5M.js.map} +0 -0
- /package/dist/{bun-NKVHOFSJ.js.map → bun-CZXHPK2W.js.map} +0 -0
- /package/dist/{chunk-E2RC367T.js.map → chunk-EDBQM6RB.js.map} +0 -0
- /package/dist/{chunk-DKX7LF5Q.js.map → chunk-HDAILYVM.js.map} +0 -0
- /package/dist/{chunk-RE2WE7CD.js.map → chunk-LOOOB46A.js.map} +0 -0
- /package/dist/{chunk-IB5VIXLR.js.map → chunk-R36YNWBU.js.map} +0 -0
- /package/dist/{cloudflare-4M4XVNUH.js.map → cloudflare-2SVRRVV5.js.map} +0 -0
- /package/dist/{deno-deploy-IVACZ62D.js.map → deno-deploy-OK4QFJIZ.js.map} +0 -0
- /package/dist/{dev-JDJWMRLH.js.map → dev-B2IZEVAD.js.map} +0 -0
- /package/dist/{internal-api-VDYOXOT7.js.map → internal-api-5Y3MLZH4.js.map} +0 -0
- /package/dist/{mcp-WJNCTM7M.js.map → mcp-GJQIREYC.js.map} +0 -0
- /package/dist/{netlify-3HEWV375.js.map → netlify-IAC53FVZ.js.map} +0 -0
- /package/dist/{observability-bootstrap-FP6LMMJE.js.map → observability-bootstrap-DOWRMADT.js.map} +0 -0
- /package/dist/{preview-BARW75PN.js.map → preview-XBP622HM.js.map} +0 -0
- /package/dist/{registry-SDBODRU6.js.map → registry-L6JG75LY.js.map} +0 -0
- /package/dist/{server-boundary-AO6EELRF.js.map → server-boundary-IFIYNGTA.js.map} +0 -0
- /package/dist/{start-4JTYXQQJ.js.map → start-JGNBTTG2.js.map} +0 -0
- /package/dist/{vercel-5PMYEEKF.js.map → vercel-EHAOKPF7.js.map} +0 -0
- /package/dist/{vite-plugin-3ON45MQE.js.map → vite-plugin-54XIRMKT.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/deployed-agents.ts","../src/adapters/deployed-cors.ts","../src/adapters/deployed-csrf.ts","../src/adapters/security-headers.ts","../src/adapters/deployed-rate-limit.ts","../src/adapters/deployed-runtime-config.ts","../src/adapters/deployed-trace.ts"],"sourcesContent":["/**\n * Serving an agent from a generated deploy entry (usetheokit/theokit#367).\n *\n * ## The gap this closes\n *\n * `grep -rc \"agent\" packages/theo/src/adapters/*.ts` used to return nothing across 14 files. The\n * notion did not exist in this layer at all: every generated entry routes `/api/` exclusively\n * through `scanServerRoutes` + `executeRoute`, and an agent is a DIFFERENT scan served by a\n * DIFFERENT function — `scanAgents` + `mountAgent`. So `/api/agents/chat` matched no file route and\n * fell into `notFoundResponse()` on every target.\n *\n * For a framework whose stated reason to exist is \"the agent is a file, delivered by the same\n * pipeline that serves the page\", that is the gap which contradicts the sentence: the agent was\n * delivered by no pipeline at all outside a machine running `theokit start`.\n *\n * ## Why baking, and why `../../`\n *\n * A Worker has no filesystem to scan and no path to `import()`, which is the same reason routes are\n * baked (#369). The agent modules are resolved on the build machine and emitted as static imports,\n * relative to the entry's directory — every target that can do this writes two levels below the\n * project root, so the arithmetic is the one `renderBakedRoutes` already does.\n *\n * ## Which targets can do it\n *\n * Only the ones whose output is BUNDLED from the project: `cloudflare` (wrangler), `bun` and\n * `deno-deploy` resolve the emitted import against the app's own source tree. `vercel`, `netlify`\n * and `aws-lambda` receive a standalone function directory that never sees the app's modules, so\n * an agent cannot travel there by this road at all. Same split as plugins (#425), same cause.\n *\n * ## The table is keyed by NAME\n *\n * The URL carries the name, the access policy is judged under the name, and the run's spans are\n * labelled with it (#406). Keying by file path would make the lookup depend on the server's\n * directory layout — which changes per deploy, and which is exactly the value #406 removed from\n * telemetry for the same reason.\n */\n\n/** One agent, as `scanAgents` reports it. Structural, so the adapters need no `server/` import. */\nexport interface DeployedAgent {\n /** Path relative to the project root — the specifier the static import uses. */\n readonly filePath: string\n /** The URL the agent answers on. */\n readonly agentPath: string\n /** The agent's NAME — what the URL carries, the policy is judged under, and spans are labelled. */\n readonly name: string\n}\n\nexport interface DeployedAgentsFragment {\n /** Top-level imports of the agent modules. */\n readonly imports: string[]\n /** Module-scope declarations — the name→module table. */\n readonly declarations: string[]\n /** The request-handler branch, to be emitted before the file-route table is consulted. */\n readonly branch: string[]\n /**\n * SI-020 — the condition a host ANDs into its non-API early-return guard, so an agent card path\n * is not handed to static assets before this fragment's branch is reached.\n *\n * Empty string when the fragment emits nothing, so a host that interpolates it unconditionally\n * never references a name that was not declared.\n */\n readonly hostBypass: string\n}\n\nconst EMPTY: DeployedAgentsFragment = { imports: [], declarations: [], branch: [], hostBypass: '' }\n\n/**\n * How the host entry names the things this branch has to use.\n *\n * The fragment is generated code injected into three entries that do NOT agree on their own\n * vocabulary — Bun reads `pathname`, Cloudflare reads `url.pathname`; Deno calls `notFound()`,\n * Cloudflare calls `notFoundResponse()`; Cloudflare wraps each branch in the security baseline\n * while Bun and Deno wrap once at the caller; Deno resolves npm packages with an `npm:` prefix.\n *\n * Naming those differences is what keeps this ONE fragment. The alternative — three near-identical\n * branches, one per adapter — is the copy that `serveThroughPluginLifecycle` was extracted to undo\n * after it had drifted five ways (#405).\n */\n/**\n * How the target REACHES its agent modules — and the two answers are genuinely different, not a\n * copy waiting to be merged.\n *\n * A Worker has no filesystem: its agents must be resolved on the build machine and emitted as\n * static imports, which is what `renderBakedRoutes` already does for routes there. Bun and Deno DO\n * have a filesystem and already scan their routes at request time; making them bake would couple an\n * agent's existence to a rebuild for no gain. The split mirrors the one routes already have on\n * exactly these targets, which is the argument for keeping it.\n */\nexport type DeployedAgentsSource =\n | {\n readonly kind: 'baked'\n /** Scanned on the build machine, emitted as static imports. */\n readonly agents: readonly DeployedAgent[]\n /**\n * B-185 — the app's `server/context.ts`, as a specifier relative to the emitted entry, or\n * `undefined` when the app has none. A Worker has no filesystem on which to find it, so it is\n * baked like the agent modules beside it (ADR 0014). `undefined` is the ordinary case for an\n * app that declares no context, and emitting an import of a file that is not there would\n * fail the BUILD rather than the request — which is why `planDeployedPlugins` takes the same\n * road for plugins.\n */\n readonly contextModule?: string\n }\n | {\n readonly kind: 'scan'\n /** Expression yielding the project root at runtime. */\n readonly projectRoot: string\n /** Expression yielding the module loader the entry already builds. */\n readonly loadModule: string\n /**\n * A statement that guarantees `loadModule` is usable, for a host that builds its loader\n * lazily. Deno's `loaderCache` is created on the route path, which runs AFTER this branch —\n * so without this the agent branch would call `null`.\n */\n readonly ensureLoader?: string\n /** The configured agents directory as a quoted literal. Absent ⇒ `scanAgents` defaults to `agents`. */\n readonly agentsDirLiteral?: string\n /**\n * B-185 — an expression yielding the app's `server/` directory, which this host already\n * declares (`bun.ts:95`, `deno-deploy.ts:69`) and already hands to `executeRoute`. A host\n * with a filesystem locates its own `context.ts`, so it needs no baking (ADR 0014, and the\n * split `deployed-agents.ts` already argues for routes two docblocks above).\n */\n readonly serverDir?: string\n }\n\nexport interface DeployedAgentsHost {\n /** Expression yielding the request path inside the handler. Default `url.pathname`. */\n readonly pathname?: string\n /** Call producing the 404 response. Default `notFoundResponse()`. */\n readonly notFound?: string\n /** Whether THIS branch applies the security baseline, or the caller already does. */\n readonly wrapSecurityHeaders?: boolean\n /** Prefix for bare package specifiers. Deno needs `npm:`; the others need nothing. */\n readonly importPrefix?: string\n /**\n * Expression yielding the entry's plugin runner, or `undefined` when the app declared no plugins\n * and the build emitted no module to bind.\n *\n * `deployedRuntimeConfigFragment` already declares `const THEO_PLUGIN_RUNNER` at module scope and\n * spreads `pluginRunner: await THEO_PLUGIN_RUNNER` into `executeRoute`; an adapter passes that\n * same expression here rather than building a second runner, because a runner rebuilt per request\n * re-runs every plugin's `register` -- which is where a plugin allocates the state its hooks read.\n */\n readonly pluginRunnerExpr?: string\n}\n\n/**\n * The two `AuxRouteDeps` fields a deployed entry must supply to match what dev already does.\n *\n * Both dev callers pass them — `vite-plugin/agent-middleware.ts:161,164` and\n * `cli/commands/start/handlers.ts:226,229` — and a first draft of this fragment passed neither,\n * on a quotation from `serve-aux-routes.ts:83-85` that names three routes (\"card, approvals,\n * stream\") while the dispatcher serves six. Two reviewers measured the same two consequences:\n *\n * - `csrfMode` unset defaults to `'strict'` (`serve-aux-routes.ts:379`), so an app declaring\n * `security: { csrf: 'off' }` got `off` on `POST /api/agents/<name>` and `strict` on its `/mcp`\n * sibling one line away — verbatim the divergence `deployed-csrf.ts`'s own header exists to\n * record, re-created on a route this slice had just made reachable.\n * - `resolveApiKey` unset makes the thread follow-up answer a permanent 501 on every deploy\n * target (`serve-aux-routes.ts:359-365`), naming a framework-internal parameter to the caller.\n *\n * Both values are already in scope: `CSRF_CONFIG` is spread into `mountAgent` in the same emitted\n * function, and `resolveProvider` is already on its import line.\n */\nconst AUX_DEPS_PARITY = [\n ` ...CSRF_CONFIG,`,\n ` resolveApiKey: (model, plugins) => resolveProvider(model, { plugins }).apiKey,`,\n] as const\n\n/** The prefix the agent convention owns. Matches `handlers.ts`'s own `tryServeAgent`. */\nconst AGENT_PREFIX = '/api/agents/'\n\n/**\n * The second shape the aux dispatcher owns. `matchGetAuxRoute` serves M15's\n * `GET /.well-known/<name>/agent-card.json`, and a guard admitting only {@link AGENT_PREFIX} left\n * five of the dispatcher's six families reachable on a deploy target and excluded the sixth — by\n * the guard, not by a decision, and silently.\n *\n * A prefix rather than the matcher's own `isAgentCardPath`: the guard exists to keep a url nobody\n * answers from paying for anything, and importing the matcher's predicate into every emitted entry\n * would buy a narrower pre-filter at the cost of a module the branch already declines without.\n */\nconst WELL_KNOWN_PREFIX = '/.well-known/'\n\n/**\n * What a deployed entry needs in order to serve the app's agents.\n *\n * @param agents - the agents scanned on the build machine. Empty emits nothing at all.\n */\n/**\n * The scan source every filesystem host with a lazily-created loader shares.\n *\n * Four adapters — `netlify`, `vercel`, `aws-lambda`, `deno-deploy` — emit an entry that resolves\n * `serverDir` itself, caches its loader in `loaderCache`, and creates that cache on first use.\n * They therefore hand this fragment the SAME six fields, and writing them out four times is the\n * copy `serveThroughPluginLifecycle` was extracted to undo after it had drifted five ways (#405).\n *\n * B-235 is what made it four: wiring three more targets duplicated the block three more times, and\n * the duplication gate on new code is what said so — 4.2% against a 3% ceiling. The gate was right\n * and the fix is the one it implies, not a threshold.\n *\n * `bun` is deliberately NOT a caller. It names its loader `loadModule` and creates it eagerly, so\n * it has no `ensureLoader` — a parameter to cover that difference would make this function a\n * switch over its callers, which is the shape that drifts.\n */\nexport function scannedFromLoaderCache(agentsDirLiteral?: string): DeployedAgentsSource {\n return {\n kind: 'scan',\n projectRoot: 'cwd',\n agentsDirLiteral,\n loadModule: 'loaderCache',\n serverDir: 'serverDir',\n ensureLoader: 'if (!loaderCache) loaderCache = createProductionLoader()',\n }\n}\n\n/**\n * The JSON 404 `vercel` and `aws-lambda` answer a routing miss with.\n *\n * An expression rather than a call, because the fragment interpolates `notFound` into a `return`\n * and neither host declares a helper for it.\n */\nexport const JSON_NOT_FOUND_RESPONSE = `new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), { status: 404, headers: { 'content-type': 'application/json' } })`\n\nexport function deployedAgentsFragment(\n source: DeployedAgentsSource | undefined,\n host: DeployedAgentsHost = {},\n): DeployedAgentsFragment {\n if (source === undefined) return EMPTY\n if (source.kind === 'baked' && source.agents.length === 0) return EMPTY\n\n const pathname = host.pathname ?? 'url.pathname'\n const notFound = host.notFound ?? 'notFoundResponse()'\n const prefix = host.importPrefix ?? ''\n\n const resolution =\n source.kind === 'baked'\n ? bakedResolution(source.agents, source.contextModule, host.pluginRunnerExpr)\n : scannedResolution({ ...source, pluginRunnerExpr: host.pluginRunnerExpr })\n\n return {\n hostBypass: ` && !__theoIsAgentCardPath(${pathname})`,\n imports: [\n // `theokit/adapters/agent-mount`, not `theokit/server`: `mount-agent` is deliberately not on\n // the app-facing surface (ADR 0041), and a generated entry is not an app. See that module.\n // B-185 — the identity entry differs by host: a filesystem host LOCATES its own\n // `context.ts`, a Worker is handed the baked factory (ADR 0014). `createWebShim` is not here\n // because all three entries already import it at module level.\n `import { mountAgent, resolveProvider, matchAgentAuxRoute, serveMatchedAuxRoute${resolution.identityImport}${source.kind === 'scan' ? ', scanAgents' : ''} } from '${prefix}theokit/adapters/agent-mount'`,\n ...resolution.imports,\n ],\n declarations: [\n ...resolution.declarations,\n // SI-020 — the host's `/api/` guard decides between the API surface and static assets, and it\n // runs BEFORE this branch. Widening the branch guard alone left the `.well-known` arm as dead\n // code on all three targets: present in the source, unreachable in the emitted program. The\n // host consults this predicate, so the card path escapes the asset branch and NOTHING else\n // under `/.well-known/` does — a blanket prefix bypass would route `/.well-known/security.txt`\n // away from assets, trading an unreachable card for a broken namespace.\n //\n // Same shape as `agent-card-handler.ts`'s own WELL_KNOWN. That is a COPY, not a shared\n // definition, and saying otherwise was the claim an inventory judge falsified: changing the\n // handler to serve `/agent.json` left every card test green, because this guard and that\n // matcher are checked separately and never against each other. The drift that matters here —\n // this guard narrowing while the matcher still serves the path — is caught by\n // `a-deployed-worker-reaches-the-agent-card.test.ts`, which drives a real request. The other\n // direction is not, and is the honest limit of this line.\n String.raw`const __theoIsAgentCardPath = (p) => /^\\/\\.well-known\\/[^/]+\\/agent-card\\.json$/.test(p)`,\n // B-185 — one factory, two call sites: the aux branch on a hit, and the run handler below.\n // Declared rather than inlined twice so the mechanism ADR 0014 decides has a single home.\n // `async` because the entry's plugin runner is a promise: `createPluginRunnerFromConfig` is\n // async, so the runtime-config fragment declares `const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(...)`\n // WITHOUT awaiting it, and every consumer awaits at the point of use. `await` is a reserved\n // word everywhere in an ES module, so a non-async factory carrying that binding does not\n // merely misbehave -- the entry does not parse, and `tests/unit/adapter-entry-parses.test.ts`\n // is where that is caught. It went red at HEAD before this line existed, on a first version\n // of this fix whose own test asserted `toContain('await THEO_PLUGIN_RUNNER')`: the presence\n // of the token that breaks the parse. That test file's header says why, in its own words --\n // `toContain` does not care whether the string is a program.\n //\n // Laziness is unaffected. The shim was always built eagerly inside this factory; what ADR-1\n // refuses is paying for a url nobody answers, and neither call site is reached by one.\n `async function __theoResolveSubject(request) {`,\n ...resolution.identity,\n ` return resolveSubject`,\n `}`,\n ],\n branch: [\n ` // #367 — the agent convention owns this prefix. It is answered BEFORE the file-route`,\n ` // table because an agent matches no file route: falling through is how a deployed`,\n ` // \\`/api/agents/<name>\\` used to 404 on every target.`,\n ` if (`,\n ` ${pathname}.startsWith(${JSON.stringify(AGENT_PREFIX)}) ||`,\n ` ${pathname}.startsWith(${JSON.stringify(WELL_KNOWN_PREFIX)})`,\n ` ) {`,\n ...resolution.auxPrelude,\n ` // B-185 — the aux dispatcher is asked FIRST, and declining costs nothing: the matcher`,\n ` // reads the url and the scanned nodes, never a module (ADR-1). A miss falls through to`,\n ` // the run handler exactly as before, so this branch owns the sub-paths and nothing more.`,\n ` const auxRoute = await matchAgentAuxRoute(request.method, ${pathname}, auxDeps)`,\n ` if (auxRoute !== null) {`,\n ` // B-185 — identity is resolved only now. Building it costs a web shim and, where the`,\n ` // app declares one, a call into its own \\`createContext\\`; a url this dispatcher`,\n ` // merely declined must pay for neither (resolve-agent-subject.ts:93-96).`,\n ` const auxResponse = await serveMatchedAuxRoute(auxRoute, request, {`,\n ` ...auxDeps,`,\n ` resolveSubject: await __theoResolveSubject(request),`,\n ` })`,\n host.wrapSecurityHeaders === true\n ? ` return withSecurityHeaders(auxResponse, SECURITY_HEADERS)`\n : ` return auxResponse`,\n ` }`,\n ` // B-185 — only the agent prefix has a run handler behind it. A \\`.well-known\\` url the`,\n ` // dispatcher declined must NOT slice a prefix it does not carry: the name would be`,\n ` // garbage and mountAgent would answer 500 for what is a routing miss.`,\n ` if (!${pathname}.startsWith(${JSON.stringify(AGENT_PREFIX)})) return ${notFound}`,\n ` const agentName = ${pathname}.slice(${String(AGENT_PREFIX.length)}).split('/')[0]`,\n ...resolution.lookup,\n ` // A name nobody scanned is a 404, exactly like any other unknown path. Handing`,\n ` // \\`undefined\\` to mountAgent would surface as a 500 for what is a routing miss.`,\n ` if (mod === undefined) return ${notFound}`,\n ` const agentResponse = await mountAgent(mod, request, (model, plugins) => resolveProvider(model, { plugins }).apiKey, {`,\n ` agentName,`,\n ` // B-185 — mount-agent.ts:121 has accepted this since #365 and 0 of 23 adapters passed`,\n ` // one, so agent-access.ts:146 judged every deployed policy against \\`subject: null\\`.`,\n ` // A run is not a decline: it is about to do real work, so the shim this builds is not`,\n ` // the cost ADR-1 refuses.`,\n ` resolveSubject: await __theoResolveSubject(request),`,\n ` ...CSRF_CONFIG,`,\n ` })`,\n host.wrapSecurityHeaders === true\n ? ` return withSecurityHeaders(agentResponse, SECURITY_HEADERS)`\n : ` return agentResponse`,\n ` }`,\n ],\n }\n}\n\ninterface AgentResolution {\n imports: string[]\n declarations: string[]\n /** Lines that must leave `mod` bound to the agent's module, or `undefined`. */\n lookup: string[]\n /**\n * B-185 — lines that must leave `auxDeps` bound to an `AuxRouteDeps`, plus the expression for\n * its `agents`. They run BEFORE {@link AgentResolution.lookup} so a declined aux route performs\n * no module load, which is what ADR-1 buys and what a later ordering would spend.\n */\n auxPrelude: string[]\n /**\n * B-185 — lines that must leave `resolveSubject` bound to a resolver, or to `undefined`. Emitted\n * only where a match has already happened, because building one costs a web shim and\n * `resolve-agent-subject.ts:93-96` states that a declined url must never run the application's\n * `createContext`.\n */\n identity: string[]\n /**\n * B-185 — what {@link AgentResolution.identity} imports, appended to the `agent-mount` line, or\n * `''` where identity is not resolved at all.\n *\n * It lives HERE, beside the lines that CALL it, because a first draft decided it in a separate\n * `identityEntryFor` that switched the same discriminated union a second time. The two could not\n * disagree then — the conditions were identical — which is what made it latent rather than live.\n * A later drift would emit an entry that CALLS a symbol it never imported, and nothing catches\n * that: the stub-coverage guard derives its requirement FROM the imports, so a missing import\n * shrinks the requirement instead of failing, and `node --check` is syntax rather than\n * resolution. It would surface as a `ReferenceError` inside a deployed Worker.\n */\n identityImport: string\n}\n\n/** No filesystem: every agent module is a static import decided on the build machine. */\nfunction bakedResolution(\n agents: readonly DeployedAgent[],\n contextModule: string | undefined,\n pluginRunnerExpr: string | undefined,\n): AgentResolution {\n const varOf = (index: number): string => `__theoAgent${String(index)}`\n return {\n imports: [\n ...agents.map((agent, index) => `import * as ${varOf(index)} from '../../${agent.filePath}'`),\n // B-185 — the app's context module, baked exactly like the agents above it (ADR 0014).\n ...(contextModule === undefined\n ? []\n : [\n // SI-022 — DYNAMIC, not a top-level static import. B-185 added this import; before it\n // a Worker did not load the app's `server/context.ts` at all. A module-scope throw\n // there — the commonest shape being a required-env-var check — then went from costing\n // nothing to taking the ENTIRE target down: the import fails, the module never\n // evaluates, and every route dies rather than only the one that wanted an identity.\n //\n // That is strictly worse than what `resolve-agent-subject.ts:69-72` promises. It says\n // a throwing `createContext` reaches the branch's own error handler and becomes a 500,\n // which is a failure scoped to the request that needed identity. A throw at IMPORT\n // time reaches no handler at all.\n //\n // A relative `import()` is statically analysable, so wrangler bundles the module\n // exactly as it bundled the static form — the reason ADR 0014 bakes it is unaffected.\n // What changes is WHEN it evaluates, and therefore what a failure costs. It is only\n // a real improvement if the import stays inside the thunk; see the factory below.\n `const __theoContext = () => import('../../${contextModule}')`,\n ]),\n ],\n declarations: [\n `// #367 — the app's agents, keyed by NAME because that is what the URL carries, what the`,\n `// access policy is judged under, and what the run's spans are labelled with (#406).`,\n `const agents = {`,\n ...agents.map((agent, index) => ` ${JSON.stringify(agent.name)}: ${varOf(index)},`),\n `}`,\n `// B-185 — the node list the aux dispatcher matches a url against. There is deliberately NO`,\n `// second table keyed by file path: \\`test_the_table_is_keyed_by_agent_name_not_by_file_path\\``,\n `// forbids one, and the reason it gives is the right one — a path key makes a lookup depend on`,\n `// the server's directory layout. The loader below reaches the module THROUGH this list, so the`,\n `// layout appears once, here, and the module table above stays keyed by the name the URL, the`,\n `// access policy and the run's spans all carry (#406).`,\n `const agentNodes = [`,\n ...agents.map(\n (agent) =>\n ` { filePath: ${JSON.stringify(agent.filePath)}, agentPath: ${JSON.stringify(agent.agentPath)}, name: ${JSON.stringify(agent.name)} },`,\n ),\n `]`,\n ],\n lookup: [\n ` const mod = Object.prototype.hasOwnProperty.call(agents, agentName)`,\n ` ? agents[agentName]`,\n ` : undefined`,\n ],\n identityImport: contextModule === undefined ? '' : ', createSubjectResolverFromFactory',\n identity:\n contextModule === undefined\n ? [\n ` // B-185 — this app declares no \\`server/context.ts\\`, so there is no factory to`,\n ` // bake and an anonymous caller is the honest answer. A policy that admits`,\n ` // nobody is the correct outcome, not an error.`,\n ` const resolveSubject = undefined`,\n ]\n : [\n ` // B-185 — a Worker has no filesystem to find \\`context.ts\\` on, so the module is baked`,\n ` // and its factory handed straight to the resolver (ADR 0014).`,\n ` //`,\n ` // This function has TWO callers and is lazy on purpose. Both build a shim, and that is`,\n ` // correct at both: the aux branch calls it only AFTER a match, and the run handler is`,\n ` // about to do real work. What neither pays for is the app's own \\`createContext\\` on a`,\n ` // url nobody answers — the resolver is a thunk, and \\`agent-access.ts:146\\` returns early`,\n ` // for an absent or public policy without ever invoking it.`,\n ` const { req: __theoReq, res: __theoRes } = createWebShim(request)`,\n ` const resolveSubject = createSubjectResolverFromFactory(`,\n // The import happens HERE, inside the factory, and `createSubjectResolverFromFactory`\n // calls the factory inside the thunk it returns (`resolve-agent-subject.ts:127-133`).\n // A first version of this fix awaited the import as an ARGUMENT, which evaluated it\n // eagerly inside `__theoResolveSubject` — both call sites await that before\n // `agent-access.ts:145` returns early for an absent or `'public'` policy. The blast\n // radius was then every agent request rather than the one that wanted an identity,\n // and the laziness invariant the lines above assert was broken. Found by the\n // inventory judge while the change was still in the working tree.\n ` async (__theoArgs) => (await __theoContext()).createContext(__theoArgs),`,\n ` __theoReq,`,\n ` __theoRes,`,\n ` ${pluginRunnerExpr ?? 'undefined'},`,\n ` )`,\n ],\n auxPrelude: [\n ` // B-185 — the aux dispatcher needs nodes carrying \\`filePath\\` and a loader keyed by it.`,\n ` // The loader resolves the path to a NAME through the node list, then reads the same`,\n ` // name-keyed table the url lookup uses: one map, one layout mention, no filesystem`,\n ` // (ADR-2). A linear find over a handful of agents is not worth a second table that`,\n ` // \\`test_the_table_is_keyed_by_agent_name_not_by_file_path\\` exists to forbid.`,\n ` const auxDeps = {`,\n ` agents: agentNodes,`,\n ` loadModule: async (filePath) => {`,\n ` const node = agentNodes.find((a) => a.filePath === filePath)`,\n ` return node === undefined ? undefined : agents[node.name]`,\n ` },`,\n ` baseUrl: url.origin,`,\n ...AUX_DEPS_PARITY,\n ` }`,\n ],\n }\n}\n\n/** A filesystem: scan once and load on demand, exactly as this entry already treats its routes. */\nfunction scannedResolution(source: {\n projectRoot: string\n loadModule: string\n ensureLoader?: string\n agentsDirLiteral?: string\n serverDir?: string\n pluginRunnerExpr?: string\n}): AgentResolution {\n // The configured directory as a second argument, or nothing. `scanAgents` defaults the name to\n // `agents`, which is right for a project that never set one and wrong for every project that did.\n const agentsDirArg = source.agentsDirLiteral === undefined ? '' : `, ${source.agentsDirLiteral}`\n\n return {\n imports: [],\n declarations: [\n `// #367 — scanned on first use and cached, the same shape this entry already gives routes.`,\n `// Baking would tie an agent's existence to a rebuild on a target that has a filesystem.`,\n `let agentsCache = null`,\n ],\n lookup: [\n ` const agentNode = agentsCache.find((a) => a.name === agentName)`,\n ` const mod = agentNode === undefined ? undefined : await ${source.loadModule}(agentNode.filePath)`,\n ],\n identityImport: source.serverDir === undefined ? '' : ', createAgentSubjectResolver',\n identity:\n source.serverDir === undefined\n ? [` const resolveSubject = undefined`]\n : [\n ` // B-185 — this host HAS a filesystem, so it locates its own \\`context.ts\\` and the`,\n ` // existing resolver works unchanged; nothing is baked (ADR 0014). Lazy for the reason`,\n ` // the baked branch gives: both callers build a shim, and neither runs the app's own`,\n ` // \\`createContext\\` for a url nobody answers.`,\n ` const { req: __theoReq, res: __theoRes } = createWebShim(request)`,\n ` const resolveSubject = createAgentSubjectResolver({`,\n ` req: __theoReq,`,\n ` res: __theoRes,`,\n ` loadModule: ${source.loadModule},`,\n ` serverDir: ${source.serverDir},`,\n ` pluginRunner: ${source.pluginRunnerExpr ?? 'undefined'},`,\n ` })`,\n ],\n auxPrelude: [\n ...(source.ensureLoader === undefined ? [] : [` ${source.ensureLoader}`]),\n ` // B-185 — hoisted above the lookup so a declined aux route loads no module. The scan`,\n ` // LISTS agent files; it imports none, so moving it here costs a declined request`,\n ` // nothing it was not already paying.`,\n ` if (!agentsCache) agentsCache = scanAgents(${source.projectRoot}${agentsDirArg})`,\n ` const auxDeps = {`,\n ` agents: agentsCache,`,\n ` loadModule: ${source.loadModule},`,\n ` baseUrl: url.origin,`,\n ...AUX_DEPS_PARITY,\n ` }`,\n ],\n }\n}\n","/**\n * The CORS configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * `security.cors` reached exactly one consumer: Vite's `configureServer` hook. So an app that\n * worked cross-origin under `theokit dev` stopped working the moment anything else served it —\n * `theokit start` (fixed separately) and all six Web deploy targets (usetheokit/theokit#409). Same\n * config, same code, no error and no warning; the failure surfaces in a browser as a blocked fetch\n * on the deployed URL, three layers from the key that had quietly stopped being read.\n *\n * The pure half was written twice and called once: `createCorsWebHandler` — the Web mirror — had no\n * caller anywhere in the repository. Nothing here reimplements it.\n *\n * ## A callback origin is REFUSED, not silently dropped\n *\n * `corsSchema.origins` accepts `z.function(...)` alongside the string / RegExp / array shapes. A\n * deployed function has no `theo.config.ts` to read, and there is no literal for a closure — so a\n * build that baked only the serialisable shapes would produce an app whose CORS silently allowed\n * nothing, which is the exact class of failure this issue reports.\n *\n * `rules/three-target-parity.md` § 3 is explicit about the alternative: \"a target that cannot serve\n * a capability refuses by name. Silent degradation is the failure mode this rule exists to\n * prevent.\" So the build throws, naming the target, the key and the two ways forward.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype CorsConfig = NonNullable<NonNullable<TheoConfig['security']>['cors']>\n\n/**\n * The CORS slice of an adapter's build options.\n *\n * Narrow and named once, matching how `securityHeaders` and `DeployedCsrfOptions` already reach the\n * emitters: each renderer receives what it uses, and six signatures name one type instead of six\n * inline shapes that can drift.\n */\nexport interface DeployedCorsOptions {\n cors?: CorsConfig\n}\n\n/**\n * Thrown at BUILD time when the declared CORS cannot be carried to a deployed target.\n *\n * A build error is the point: the alternative is a deploy that looks configured and refuses every\n * cross-origin request, discovered by a browser rather than by the build.\n */\nexport class UnserializableCorsOriginError extends Error {\n constructor(target: string) {\n super(\n `security.cors.origins is a function, and the \\`${target}\\` target cannot carry it: a deployed ` +\n `function has no theo.config.ts to read, and a callback cannot be written into the emitted ` +\n `entry. Replace it with the origin, a RegExp, or an array of either — all of which travel — ` +\n `or build for \\`node\\` and run \\`theokit start\\`, which evaluates the callback at runtime.`,\n )\n this.name = 'UnserializableCorsOriginError'\n }\n}\n\n/** Source text for one origin matcher: a RegExp as a literal, anything else as JSON. */\nfunction renderOrigin(origin: unknown, target: string): string {\n if (typeof origin === 'function') throw new UnserializableCorsOriginError(target)\n if (origin instanceof RegExp) return String(origin)\n if (Array.isArray(origin)) return `[${origin.map((o) => renderOrigin(o, target)).join(', ')}]`\n return JSON.stringify(origin)\n}\n\n/**\n * Source text for the CORS config, or `undefined` when the app declared none.\n *\n * RegExp entries are emitted as regex literals for the reason `deployed-csrf.ts` gives at length:\n * `JSON.stringify` renders a RegExp as `{}`, and `matchesOrigin` checks `instanceof RegExp`, so a\n * JSON-rendered origin would sit in the emitted file looking configured and matching nothing.\n *\n * @throws UnserializableCorsOriginError when `origins` is a callback\n */\nexport function renderDeployedCorsLiteral(cors: CorsConfig | undefined, target: string): string {\n if (cors === undefined) return 'undefined'\n\n const parts = [`origins: ${renderOrigin(cors.origins, target)}`]\n if (cors.methods !== undefined) parts.push(`methods: ${JSON.stringify(cors.methods)}`)\n if (cors.allowedHeaders !== undefined)\n parts.push(`allowedHeaders: ${JSON.stringify(cors.allowedHeaders)}`)\n if (cors.exposedHeaders !== undefined)\n parts.push(`exposedHeaders: ${JSON.stringify(cors.exposedHeaders)}`)\n // Both carry schema defaults, so they are always present and always emitted — unlike the\n // optional fields above, whose absence is a real answer the handler already has one for.\n parts.push(\n `credentials: ${JSON.stringify(cors.credentials)}`,\n `maxAge: ${JSON.stringify(cors.maxAge)}`,\n )\n\n return `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare the CORS handler in a generated entry.\n *\n * `null` when nothing was declared, which is what \"no cors block\" meant before and still means: no\n * headers, not permissive ones.\n */\nexport function deployedCorsFragment(cors: CorsConfig | undefined, target: string): string[] {\n return [\n `// #409 — the CORS the app declared, carried as a literal because a deployed function has no`,\n `// theo.config.ts to read. \\`null\\` when the app declared none: no headers, not permissive ones.`,\n `const CORS_CONFIG = ${renderDeployedCorsLiteral(cors, target)}`,\n `const CORS_HANDLER = CORS_CONFIG === undefined ? null : createCorsWebHandler(CORS_CONFIG)`,\n ``,\n `/** Answer a preflight before routing — an OPTIONS the router handles never gets a CORS answer. */`,\n `function corsPreflight(request) {`,\n ` return CORS_HANDLER === null ? null : CORS_HANDLER.handlePreflightRequest(request)`,\n `}`,\n ``,\n `/** Put the headers on whatever the app answered, including its 404s — a browser reads a 404`,\n ` * without them as a CORS failure rather than as the 404 it is. */`,\n `function withCors(request, response) {`,\n ` if (CORS_HANDLER !== null) CORS_HANDLER.applyCorsHeaders(request, response.headers)`,\n ` return response`,\n `}`,\n ]\n}\n","/**\n * The CSRF configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * The six Web-standards adapter entries built `executeRoute`'s context from an eight-field\n * literal, and neither `csrfMode` nor `disallowed` was among the eight (usetheokit/theokit#410).\n * `executeRoute` defaults an absent mode to `'strict'`, so an app declaring\n * `security: { csrf: 'off' }` — or `'warn'` — got `'strict'` on every deploy target: a `POST` that\n * works under `theokit dev` and `theokit start` answers `403 CSRF_INVALID` on Vercel, naming a\n * mechanism the operator had switched off. The config still validated and the build still\n * succeeded; the behaviour simply changed.\n *\n * The deployed function has no `theo.config.ts` to read, which is why the value is carried as a\n * literal — the same shape `security.headers` already uses (`renderSecurityHeadersConfigLiteral`).\n *\n * ## Why this is not `JSON.stringify`\n *\n * `disallowed.routes` accepts RegExp entries (`config/schemas/security.ts`), and `JSON.stringify`\n * renders a RegExp as `{}`. That is not a formatting problem: `matchDisallowed` checks\n * `p instanceof RegExp`, so a `{}` matches nothing while reading, in the emitted file, as a rule\n * that is present and configured. Reaching for JSON here would reproduce this issue's own defect —\n * configuration that survives validation and quietly stops applying — one layer further down.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype SecurityConfig = NonNullable<TheoConfig['security']>\n\n/**\n * The two slices of `security` that reach `executeRoute`'s context.\n *\n * Narrow rather than the whole block, matching how `securityHeaders` is already passed: each\n * renderer receives what it uses and nothing else, so a headers change cannot reach the CSRF\n * literal and vice versa.\n */\nexport interface DeployedCsrfOptions {\n csrf?: SecurityConfig['csrf']\n disallowed?: SecurityConfig['disallowed']\n}\n\n/**\n * Source text for one route pattern.\n *\n * A RegExp is emitted as a regex literal so it arrives as a RegExp; a string goes through\n * `JSON.stringify`, which is the correct escaper for a JS string literal (quotes, backslashes,\n * control characters, line separators).\n */\nfunction renderRoutePattern(pattern: string | RegExp): string {\n return pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern)\n}\n\n/**\n * Source text for the CSRF slice of `executeRoute`'s context.\n *\n * Absent values are OMITTED rather than defaulted. `executeRoute` already defaults an absent\n * `csrfMode` to `'strict'`, and writing `'strict'` here would put that default in a second place\n * where the two can disagree — which is the class of drift the whole issue is about.\n *\n * @param security - the declared csrf slices, or `undefined` when the app declared no security block\n */\nexport function renderDeployedCsrfLiteral(security: DeployedCsrfOptions | undefined): string {\n if (security === undefined) return '{}'\n\n const parts: string[] = []\n if (security.csrf !== undefined) parts.push(`csrfMode: ${JSON.stringify(security.csrf)}`)\n\n const { disallowed } = security\n if (disallowed !== undefined) {\n const routes = disallowed.routes.map(renderRoutePattern).join(', ')\n parts.push(\n `disallowed: { routes: [${routes}], behavior: ${JSON.stringify(disallowed.behavior)} }`,\n )\n }\n\n // `{}` and not `{ }` when nothing was declared: the emitted file is read by people, and the\n // two-space version reads as though something was meant to be there.\n return parts.length === 0 ? '{}' : `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare `CSRF_CONFIG` in a generated entry.\n *\n * One function rather than the same six lines pasted into each of the six adapters: that\n * duplication is how the eight-field context literal came to be wrong in six places at once, and\n * repeating the fix in the same shape would leave the next field with the same six places to be\n * forgotten in. It also keeps the two largest emitters under the `max-lines-per-function` ceiling,\n * which `vercel.ts` already extracts fragments to respect.\n *\n * @param opts - the declared csrf slices, passed straight through from the adapter's build options\n * @param home - what the target has instead of a config file, for the comment's second sentence\n */\nexport function deployedCsrfFragment(\n opts: DeployedCsrfOptions,\n home = 'a deployed function',\n): string[] {\n return [\n `// #410 — the CSRF mode and per-route escalation the app declared. Carried as a`,\n `// literal for the same reason as the headers above: ${home} has no theo.config.ts`,\n `// to read. Absent keys stay absent so executeRoute's own default ('strict') applies,`,\n `// rather than this file becoming a second place it can drift.`,\n `const CSRF_CONFIG = ${renderDeployedCsrfLiteral(opts)}`,\n ]\n}\n","/**\n * The security headers a deployed target puts on its responses.\n *\n * `theokit start` applies the configured baseline to every response it writes\n * (`cli/commands/start/request-handler.ts`). None of the six Web-standards\n * deploy adapters applied any, so the same page carried a CSP,\n * `X-Frame-Options`, HSTS and `nosniff` under `theokit start` and none of them\n * once deployed (usetheokit/theokit#410, GHSA-87qq-fgcr-384x).\n *\n * This module is the seam that closes that half of the gap. It has two halves\n * and they live together on purpose: the code that writes the literal into a\n * generated entry and the code that reads it at request time have to agree on\n * one shape, and a shape stated in two files drifts.\n *\n * - **Build time** — {@link renderSecurityHeadersConfigLiteral} turns\n * `security.headers` into a JSON literal the adapter inlines. A deployed\n * runtime has no `theo.config.ts` to read, so the configuration travels as\n * data.\n * - **Request time** — the generated entry calls {@link buildSecurityHeaders}\n * on that literal and hands every response to {@link withSecurityHeaders}.\n * The same function `theokit start` calls, on the same input, so the two\n * cannot disagree about what the configuration means.\n *\n * ## The per-request nonce, and where it stops\n *\n * `buildSecurityHeaders` accepts a per-request `nonce` and substitutes it into\n * `script-src`. A nonce cannot survive a build-time literal — it is minted per\n * response — so a target reaches one only if it renders the HTML at request\n * time and can put the same value on the script tags it emits.\n *\n * Exactly one deploy path does: **Cloudflare with `ssrStreaming: true`**, whose\n * worker calls `renderStreamingWeb(request, { nonce })`, and that renderer\n * threads the value into `renderToReadableStream` and into the hydration script\n * (`router/entry-server.ts`). That branch mints a nonce per request and builds\n * its CSP from it. Everything else serves HTML written at build time, or no\n * HTML at all, and carries a **nonce-less CSP** — the same answer\n * `buildSecurityHeaders` already gives a prerendered route (EC-4), for the same\n * reason: a nonce in the header with no nonce on the tag blocks every inline\n * script.\n *\n * That asymmetry is real and is not smoothed over. It is stated in the emitted\n * entry, printed by the build through\n * {@link describeDeployedSecurityHeaders}, and written down in\n * `docs/surfaces/build-adapters.md`.\n */\nimport { generateNonce } from '../core/contracts/nonce.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { buildSecurityHeaders } from '../core/contracts/security-headers.js'\n\n/**\n * Re-exported so a generated entry has ONE import for the whole concern.\n *\n * Reaching it through `theokit/server/security` would work and would also drag\n * that barrel's CSRF surface into a Worker bundle, for a function that is forty\n * lines of string concatenation. It is defined in `core/contracts/`, which is\n * the module every target may import from — `adapters → server` is not an edge\n * in the DAG, and the header policy was never server code.\n */\nexport { buildSecurityHeaders }\n\n/**\n * Re-exported for the same reason, and so the streamed Cloudflare worker mints\n * its nonce with the identical primitive `theokit start` uses\n * (`cli/commands/start/request-handler.ts`) rather than a second, hand-rolled\n * one. It is already runtime-portable: Web Crypto first, with a named error\n * when the runtime has none.\n */\nexport { generateNonce }\n\n/**\n * The `security.headers` block, as a literal a generated entry can carry.\n *\n * `{}` when the app declares none — which is not the same as \"no headers\".\n * `buildSecurityHeaders({})` returns the full default baseline, and `{}` is\n * exactly what `theokit start` passes when `security.headers` is absent\n * (`cli/commands/start/index.ts`). An app with no security block gets the same\n * baseline deployed as it gets locally.\n */\n/**\n * The two declarations every deploy entry emits to carry the security baseline.\n *\n * Four adapters wrote these same two lines — `netlify`, `vercel`, `aws-lambda`, `deno-deploy` —\n * each under a comment naming its own host's static-asset boundary. The COMMENT differs and is\n * meant to; the declarations do not.\n *\n * Extracted after SonarCloud's duplication gate failed a PR at 4.0% against a 3% ceiling and named\n * this as the largest repeated block among the changed files. The gate was measuring something\n * real: a literal renderer and a builder call, copied four times, is four places to update when\n * either changes.\n *\n * Returns the lines rather than a joined string, because every caller splices them into an array\n * of emitted lines.\n */\nexport function securityHeadersDeclarations(config: SecurityHeadersConfig | undefined): string[] {\n return [\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(config)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ]\n}\n\nexport function renderSecurityHeadersConfigLiteral(\n headers: SecurityHeadersConfig | undefined,\n): string {\n return JSON.stringify(headers ?? {})\n}\n\n/**\n * Put the headers on a response, without overruling the handler.\n *\n * `theokit start` sets the baseline BEFORE the route handler runs, so a handler\n * can override it with `res.setHeader` (last write wins, Node convention). On a\n * Web target the response arrives already built, so the equivalent of \"the\n * handler wins\" is to skip a header the response already carries: a route that\n * set its own `Content-Security-Policy` keeps it.\n *\n * Mutates and returns the same `Response` rather than constructing a\n * replacement, because these responses are handed to the runtime while their\n * body is still being written (#382) and re-wrapping the stream is exactly the\n * second buffering point that change removed.\n *\n * Mutation is safe for every response these entries produce: the Fetch spec\n * gives a locally constructed `Response` the `response` header guard, which\n * permits `set` for every name used here. The `immutable` guard belongs to\n * responses that came back from `fetch()`, and none of the six emitted handlers\n * returns one — each builds its response from `createWebShim`, from a `new\n * Response(...)`, or from the SSR renderer. The WebSocket upgrade, which is the\n * one response an adapter gets from its runtime rather than building, is\n * deliberately not routed through here.\n */\nexport function withSecurityHeaders(response: Response, headers: Record<string, string>): Response {\n for (const [key, value] of Object.entries(headers)) {\n if (!response.headers.has(key)) response.headers.set(key, value)\n }\n return response\n}\n\nexport interface DeployedSecurityHeaderLimits {\n target: string\n /** The app's `security.headers` block, or undefined when it declares none. */\n securityHeaders: SecurityHeadersConfig | undefined\n /**\n * Does the emitted handler render HTML at request time and mint a CSP nonce\n * for it? True only for Cloudflare with `ssrStreaming: true`.\n */\n mintsNonce: boolean\n /**\n * Is the HTML document served by a platform static host rather than by the\n * handler this build emits? True wherever the emitted handler answers\n * `/api/*` and returns 404 for everything else.\n */\n /**\n * Who puts the security headers on the HTML DOCUMENT — a different question from who serves it,\n * and the two used to be collapsed into one boolean (usetheokit/theokit#412).\n *\n * - `handler` — this target's own handler returns the document, so it carries the same baseline\n * every API response carries. No caveat.\n * - `platform-configured` — the platform's static host serves the document, AND this build emits\n * the configuration that puts the headers on it (`.vercel/output/config.json`, `netlify.toml`).\n * Still worth stating, because nothing here has seen a deployed response.\n * - `platform-unmanaged` — the platform serves it and this build owns no artifact that could\n * configure it. This is the real remaining gap, and it stays named.\n *\n * The two-value version reported `platform-configured` targets with the same message as\n * `platform-unmanaged` ones, telling an operator to go and do work the build had already done —\n * and a stale limitation reads exactly like a current one.\n */\n documentHeaders: 'handler' | 'platform-configured' | 'platform-unmanaged'\n}\n\n/**\n * What the build tells the operator, once, per target.\n *\n * Silent degradation is the failure mode `rules/three-target-parity.md` exists\n * to prevent. Two things degrade quietly here and both are named rather than\n * discovered in production: a CSP that refuses inline scripts on a deploy while\n * allowing them locally, and an HTML document that never passes through the\n * handler these headers are attached to.\n *\n * The header names are read from the map the entry will actually carry, not\n * from a list written next to it. A configuration that switches HSTS or the CSP\n * off would otherwise be announced as sending them.\n */\nexport function describeDeployedSecurityHeaders(limits: DeployedSecurityHeaderLimits): string {\n const headers = buildSecurityHeaders(limits.securityHeaders ?? {}, { production: true })\n const names = Object.keys(headers)\n if (names.length === 0) {\n return ` ! \\`${limits.target}\\` sends no security headers: the configuration switched every one of them off.`\n }\n\n const lines = [\n ` ✓ security headers on every response \\`${limits.target}\\` returns: ${names.join(', ')}.`,\n ]\n const sendsCsp = names.some((name) => name.startsWith('Content-Security-Policy'))\n if (sendsCsp && !limits.mintsNonce) {\n lines.push(\n ` - The CSP carries no nonce: this target serves HTML written at build time,`,\n ` so there is no per-request value to put on a script tag. An inline`,\n ` <script> is refused by \\`script-src 'self'\\` here, while the same page`,\n ` under \\`theokit start\\` gets a nonce and runs it. Move inline scripts to`,\n ` \\`<script src=\"...\">\\`, or set \\`security.headers.cspMode: 'report-only'\\``,\n ` while you migrate.`,\n )\n }\n if (limits.documentHeaders === 'platform-configured') {\n lines.push(\n ` - The HTML document is served by the platform's static host, and reaches`,\n ` the browser with these headers through config this build emits. That`,\n ` path is not verified by a deploy from here — the values come from the`,\n ` same function the handler uses, but no response has been read back.`,\n )\n }\n if (limits.documentHeaders === 'platform-unmanaged') {\n lines.push(\n ` - The HTML document does NOT pass through this handler — the platform's`,\n ` static host serves it — so these headers reach \\`/api/*\\` responses and`,\n ` not the page. This build emits no artifact that could configure it, so`,\n ` set the document's headers on the platform (usetheokit/theokit#412).`,\n )\n }\n return lines.join('\\n')\n}\n","/**\n * The rate limit a deployed entry carries, baked at build time.\n *\n * ## What #508 asked for, and what this answers\n *\n * `theokit build` refuses the six Web-standards targets when `theo.config.ts` declares a\n * `rateLimit` (`UnenforceableRateLimitError`). That refusal is honest and it is not enforcement.\n * The issue names three things standing between the refusal and a working limit: per-runtime\n * caller-address resolution, a refusal that survives where the address cannot be resolved, and\n * storage that outlives one invocation.\n *\n * For `bun` all three already have answers, which is why it is the target that moves first:\n *\n * - **Address** — `Bun.serve`'s handler is `fetch(request, server)`, and `server.requestIP(request)`\n * returns the peer address without depending on a proxy header a client could set.\n * - **Storage** — `Bun.serve` is a long-lived process. `createRateLimiterWeb`'s default\n * `InMemoryStore` therefore behaves exactly as it does under `theokit start`, which is the\n * deployment `node` already ships.\n * - **Refusal** — see below: every shape whose key cannot be resolved in a deployed entry throws\n * at BUILD time rather than degrading.\n *\n * ## Why the other five are not here\n *\n * Cloudflare, AWS Lambda, Netlify and Vercel are per-invocation runtimes: an in-process counter\n * does not survive between requests, so a limiter built on one forgets. A limit that forgets is a\n * limit that does not limit — the same class of failure as the shared bucket, reached by a\n * different road. Deno Deploy evicts isolates for the same reason. Those need an external counter,\n * which is a storage design and not a wiring change, so they keep refusing by name.\n *\n * Being explicit about that boundary is the point. The failure this whole area exists to prevent is\n * a config that reads as protection while protecting nothing.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype RateLimitConfig = NonNullable<TheoConfig['rateLimit']>\n\n/** The rate-limit slice of an adapter's build options, named once like `DeployedCorsOptions`. */\nexport interface DeployedRateLimitOptions {\n rateLimit?: RateLimitConfig\n}\n\n/**\n * Thrown at BUILD time when a declared rate limit cannot be carried into a deployed entry.\n *\n * Distinct from {@link UnenforceableRateLimitError}, and the distinction is not cosmetic: that one\n * means *this target enforces no limit at all*, this one means *this target enforces limits, and\n * cannot carry THIS one*. An operator reading the first looks for another target; an operator\n * reading the second changes the key.\n */\nexport class UnserialisableRateLimitError extends Error {\n override readonly name = 'UnserialisableRateLimitError'\n constructor(\n readonly target: string,\n readonly reason: string,\n ways: readonly string[],\n ) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit this target cannot carry.`,\n ``,\n ` ${reason}`,\n ``,\n ` Ways forward:`,\n ...ways.map((w) => ` • ${w}`),\n ``,\n ` This refuses rather than dropping the key, because a rate limit that silently does not`,\n ` apply looks exactly like one that does (usetheokit/theokit#461, #508).`,\n ].join('\\n'),\n )\n }\n}\n\n/** The base shape every accepted config narrows to: a window, a ceiling, and an IP key. */\ninterface BakeableRateLimit {\n windowMs: number\n max: number\n /**\n * How many proxies sit in front of the app, for the forwarded-header path. Dropped before the\n * entry until B-027: the schema declares it (`config/schemas/rate-limit.ts:36`) and the generated\n * code could not honour it, so a deployment behind a proxy keyed every visitor on the proxy.\n */\n trustProxy: boolean | number\n /**\n * B-257 — the durable counter the entry constructs, or `undefined` for the in-process default.\n *\n * A reference rather than an instance: this is baked into a generated file, so it must survive\n * being written as source. `factory` is the one field that cannot be escaped — see\n * `bakeableStore` below.\n */\n store?: BakeableStore\n}\n\n/** A durable store named by `theo.config.ts`, in the form a generated entry can construct. */\ninterface BakeableStore {\n /** The specifier the entry imports from. Written through `JSON.stringify`. */\n module: string\n /** The exported name it constructs. VALIDATED, never escaped — it becomes a bare identifier. */\n factory: string\n /** Constructor options. Written through `JSON.stringify`. */\n options?: Record<string, string | number | boolean>\n}\n\n/**\n * A JavaScript identifier, and nothing else.\n *\n * `factory` becomes a bare identifier in `import { <factory> } from …`, where `JSON.stringify` would\n * emit `import { \"x\" }` and not parse. So it cannot be escaped — only validated. Without this, a\n * `theo.config.ts` carrying `factory: \"x } from 'evil'; //\"` writes arbitrary code into every\n * generated entry, and that file usually arrives with the clone.\n */\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/\n\n/**\n * The words that are well-formed identifiers and cannot be BOUND.\n *\n * `IDENTIFIER` answers \"could this be a name?\"; the emitter needs \"can this be THIS name?\", and the\n * two differ on exactly this set. `factory` lands as a bare binding in\n * `import { <factory> } from '<module>'`, where `import { default }` is a SyntaxError — so a config\n * naming one produces a generated entry that does not parse, and the deploy fails pointing at the\n * emitted file rather than at the line that caused it.\n *\n * `default` is the one a real config reaches by accident, because `export default createStore` is\n * the ordinary shape of the module being named. The rest are here because the cost of the list is\n * one comparison and the cost of an omission is a deploy that fails somewhere else.\n *\n * Reserved words only. `defaultStore` is a legal binding, and a substring match would refuse it —\n * an over-correction that breaks working configs to protect against a shape they do not have.\n */\nconst NOT_BINDABLE = new Set([\n 'await',\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'enum',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'import',\n 'in',\n 'instanceof',\n 'new',\n 'null',\n 'return',\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield',\n])\n\n/**\n * Refuse a `store` a generated entry could not construct — or could construct into a hole.\n *\n * Extracted from `bakeableRateLimit` because it is its own responsibility and because inlining it\n * took that function to a cyclomatic complexity of 18 against a ceiling of 15. The three refusals\n * are one question asked of three fields, which is the shape SRP asks for.\n *\n * The third is the one that cannot be solved by escaping. `module` and `options` are written through\n * `JSON.stringify`, as `trustProxy` already is at the emit site. `factory` lands as a BARE\n * IDENTIFIER in `import { <factory> } from …`, where a quoted string does not parse — so it is\n * validated, and a config that fails the check is refused by name rather than interpolated raw.\n */\nfunction assertBakeableStore(store: unknown, target: string): void {\n if (store === undefined) return\n\n if (!isStoreShaped(store)) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.store` must be an object naming a module and a factory.',\n [\n \"declare `store: { module: '@upstash/redis', factory: 'Redis' }`\",\n 'omit `store` and let the build refuse this target, which is honest about not limiting',\n ],\n )\n }\n\n const { module: mod, factory } = store as Record<string, unknown>\n\n if (typeof mod !== 'string' || mod.length === 0) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.store.module` must be the specifier the entry imports from.',\n [\"declare `module: '@upstash/redis'`\", 'omit `store`'],\n )\n }\n\n if (typeof factory !== 'string' || !IDENTIFIER.test(factory) || NOT_BINDABLE.has(factory)) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.store.factory` must be a plain identifier — it is written into the ' +\n 'generated entry as `import { <factory> }`, where a quoted string would not parse, so it ' +\n 'is validated rather than escaped. Anything else would put arbitrary source in every ' +\n 'deployment this config builds.',\n [\n \"name the export directly: `factory: 'Redis'`\",\n 'omit `store` and let the build refuse this target',\n ],\n )\n }\n\n // `options` is typed `Record<string, string | number | boolean>` and the type is erased before\n // this runs, so the declaration protects nobody: the value arrives from a config file. Three\n // measured escapes, and the third is why this is a refusal rather than a comment —\n // `JSON.stringify` throws a raw TypeError naming JSON on a BigInt and on a cycle, and on a\n // FUNCTION it throws nothing and omits the key. The option was then simply absent from the\n // emitted entry, with no diagnostic: a store configured and not configured, which is the same\n // silence this whole feature exists to remove.\n const { options } = store as Record<string, unknown>\n if (options !== undefined) {\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.store.options` must be an object of scalar values.',\n [\n \"declare `options: { url: 'redis://…', retries: 3 }`\",\n 'omit `options` and configure the store inside the factory',\n ],\n )\n }\n\n const offending = Object.entries(options as Record<string, unknown>).find(\n ([, v]) => typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean',\n )\n if (offending !== undefined) {\n throw new UnserialisableRateLimitError(\n target,\n `\\`security.rateLimit.store.options.${offending[0]}\\` must be a string, number or boolean.`,\n [\n 'declare scalars only — strings, numbers and booleans',\n 'move anything else into the factory itself, which the generated entry calls at runtime',\n ],\n )\n }\n }\n}\n\n/**\n * The ONE predicate both sides read — the call emitter here and `assertBakeableStore`'s first\n * refusal. They were two, differing on arrays: this one accepted `store: []` while the refusal\n * rejected it, so the declaration threw while the call side would still have emitted `await`. The\n * build refused first, so no bad entry reached disk — and the pair exists to agree BY CONSTRUCTION\n * rather than because one check happens to run earlier.\n */\nfunction isStoreShaped(store: unknown): boolean {\n return typeof store === 'object' && store !== null && !Array.isArray(store)\n}\n\n/**\n * Narrow a declared rate limit to what a deployed entry can actually enforce, or refuse by name.\n *\n * Accepts the base `{ windowMs, max }` and the explicit `keyBy: 'ip'`, which is what the address\n * resolution below can key. Everything else throws:\n *\n * - a **function** `keyBy` has no literal — the same wall `deployed-cors.ts` hits on a callback\n * origin, and refused for the same reason;\n * - `keyBy: 'session' | 'user'` needs a session the deployed entry does not resolve at the point\n * the limit runs, which is before routing;\n * - `routes` needs the matched route, decided after this check. Refusing it is honest today and is\n * the natural next slice.\n */\nfunction bakeableRateLimit(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n): BakeableRateLimit | undefined {\n if (rateLimit === undefined) return undefined\n const cfg = rateLimit as Record<string, unknown>\n\n if (typeof cfg.keyBy === 'function') {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.keyBy` is a function, and a deployed entry has no literal for a closure.',\n [\n \"use `keyBy: 'ip'` (the default), which this target resolves from the connection\",\n 'build for `node` and run `theokit start`, which can call the function',\n ],\n )\n }\n if (cfg.keyBy === 'session' || cfg.keyBy === 'user') {\n throw new UnserialisableRateLimitError(\n target,\n `\\`security.rateLimit.keyBy: '${cfg.keyBy}'\\` needs a resolved session, and the limit runs before routing.`,\n [\n \"use `keyBy: 'ip'`, which is resolvable at that point\",\n 'build for `node` and run `theokit start`',\n ],\n )\n }\n assertBakeableStore(cfg.store, target)\n\n if (cfg.routes !== undefined) {\n throw new UnserialisableRateLimitError(\n target,\n '`security.rateLimit.routes` needs the matched route, which is decided after the limit runs here.',\n [\n 'declare a single global limit (`windowMs` + `max`)',\n 'build for `node` and run `theokit start`, which applies per-route limits',\n ],\n )\n }\n\n const windowMs = cfg.windowMs\n const max = cfg.max\n if (typeof windowMs !== 'number' || typeof max !== 'number') return undefined\n // `?? false` and not `|| false`: `trustProxy: 0` is a number and falsy, and it means the same to\n // the resolver as `false` — but emitting `false` where the operator wrote `0` makes the generated\n // entry disagree with the config a reader compares it against.\n const trustProxy = cfg.trustProxy\n return {\n windowMs,\n max,\n trustProxy:\n typeof trustProxy === 'boolean' || typeof trustProxy === 'number' ? trustProxy : false,\n // Validated above — `module` and `options` are escaped at emit time, `factory` was checked\n // against IDENTIFIER because it cannot be.\n store: cfg.store as BakeableStore | undefined,\n }\n}\n\n/**\n * The generated declarations and helper for a target that keys on the connection's peer address.\n *\n * `addressExpression` is the per-runtime half the issue calls out — the one thing that genuinely\n * differs between targets. Bun passes `server`; a future Deno slice would pass its\n * `ServeHandlerInfo`. Everything else here is shared.\n *\n * Returns `[]` when nothing was declared, so an app without a limit emits no limiter at all rather\n * than an inert one.\n */\nexport function deployedRateLimitFragment(\n rateLimit: RateLimitConfig | undefined,\n target: string,\n addressExpression: string,\n /**\n * The parameter list `callerAddress` is DECLARED with, because the runtime source differs per\n * target and only `bun` binds these two names (`bun.ts:158`). `cloudflare.ts:452` binds\n * `(request, env, ctx)`, `vercel.ts:39` `(nodeReq, nodeRes)`, `netlify.ts:84` `(request, context)`,\n * `deno-deploy.ts:90` `(request)` and `aws-lambda.ts:152` `(event)`. An expression naming\n * `context`, `info`, `event` or `nodeReq` inside a function declared `(request, server)` is an\n * unbound identifier, and the entry throws on the first limited request.\n */\n params = 'request, server',\n /**\n * The specifier prefix this target needs — `'npm:'` on Deno Deploy, empty everywhere else.\n *\n * B-257: this function now emits its OWN import for the durable limiter, rather than relying on\n * each adapter to remember one. The previous shape had THREE sides to keep in step — the\n * declaration here, the call in `rateLimitCheckFragment`, and a per-adapter import line — and the\n * third was not joined: six adapters imported `createRateLimiterWeb` and none imported\n * `createDurableRateLimiterWeb`, so a store-carrying entry referenced a free variable and would\n * have thrown `ReferenceError` while evaluating its module body. Not at the first limited request:\n * at LOAD, taking down every route including those declaring no limit.\n *\n * `cloudflare.ts:370-373` documents that exact defect from B-027, one symbol earlier. Owning the\n * import here is what stops a fourth recurrence.\n */\n importPrefix = '',\n): string[] {\n const baked = bakeableRateLimit(rateLimit, target)\n if (baked === undefined) return []\n return [\n `// #508 — the limit the app declared, carried as a literal because a deployed entry has no`,\n `// theo.config.ts to read.`,\n `//`,\n `// WHERE THIS COUNTER LIVES, and it is not the same answer per target. On a long-lived server`,\n `// (\\`bun\\`) the process outlives a request and the count holds. On a per-invocation or`,\n `// per-isolate runtime — Cloudflare, AWS Lambda, Netlify, Vercel, Deno Deploy — it does not:`,\n `// the limit is PER INSTANCE, and a caller spread across instances gets that many budgets.`,\n `// The address is resolved correctly either way; the counting is what B-257 is about, and`,\n `// \\`theokit build\\` refuses a declared limit on those five until it is.`,\n // B-262 — ONE builder, one signature, always async. The emitter used to branch here:\n // `createRateLimiterWeb` returns a value and `createDurableRateLimiterWeb` returns a Promise, so\n // the CALL SITE had to know which it got and emit `await` or not. A call site whose shape changes\n // with the config is what produced B-257's missing `await`, and `buildRateLimiter` removes the\n // decision rather than documenting it.\n `import { buildRateLimiter } from '${importPrefix}theokit/server/rate-limit'`,\n ...(baked.store === undefined\n ? [\n `const RATE_LIMIT = buildRateLimiter({ windowMs: ${baked.windowMs}, max: ${baked.max} }, undefined)`,\n ]\n : [\n // B-257 — a durable counter, named by the app. `module` and the options are JSON literals;\n // `factory` was validated against IDENTIFIER at bake time because it lands here as a bare\n // identifier and no escape can make that safe.\n //\n // The limiter's own import is emitted HERE rather than by each adapter. See `importPrefix`.\n `import { ${baked.store.factory} } from ${JSON.stringify(baked.store.module)}`,\n `const RATE_LIMIT_STORE = new ${baked.store.factory}(${JSON.stringify(baked.store.options ?? {})})`,\n `const RATE_LIMIT = buildRateLimiter(`,\n ` { windowMs: ${baked.windowMs}, max: ${baked.max} },`,\n ` RATE_LIMIT_STORE,`,\n `)`,\n ]),\n ``,\n `// How many proxies the deployment declared in front of it. \\`client-ip.ts\\` reads a forwarded`,\n `// header only when this says one wrote it: the header is whatever the client typed, so`,\n `// trusting it unasked lets anyone rotate a forged value past the limiter with one \\`curl -H\\`.`,\n `const TRUST_PROXY = ${JSON.stringify(baked.trustProxy)}`,\n ``,\n `/**`,\n ` * The caller's address, from the connection rather than from a header.`,\n ` *`,\n ` * A header a client can set is a key a client can choose, which makes the bucket theirs to`,\n ` * split. An address this runtime cannot resolve returns \\`undefined\\`, and the caller answers`,\n ` * 503 rather than keying on a constant: one shared bucket is a budget the first caller each`,\n ` * window exhausts for everyone, which is worse than no limiting at all.`,\n ` */`,\n `const addr = (v) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined)`,\n `function callerAddress(${params}) {`,\n ` return addr(${addressExpression})`,\n `}`,\n ``,\n `/** The 503 a caller this runtime cannot name gets, instead of everyone's shared bucket. */`,\n `function unnamedCaller() {`,\n ` return new Response(`,\n ` JSON.stringify({ error: { code: 'CALLER_UNRESOLVED', message: ${JSON.stringify(\n `${target} could not resolve the caller's address, and a rate limit keyed on a constant is a denial of service`,\n )} } }),`,\n ` { status: 503, headers: { 'Content-Type': 'application/json' } },`,\n ` )`,\n `}`,\n ``,\n `/** The 429 a limited caller gets, carrying the limiter's own headers. */`,\n `function rateLimited(result) {`,\n ` return new Response(JSON.stringify({ error: { code: 'RATE_LIMITED', message: 'Too many requests' } }), {`,\n ` status: 429,`,\n ` headers: { 'Content-Type': 'application/json', ...result.headers },`,\n ` })`,\n `}`,\n ]\n}\n\n/**\n * The check itself, as generated source, placed inside the runtime's request handler.\n *\n * Extracted for the reason `bun.ts` extracts its other fragments: the emitter is one array literal,\n * so every line the entry gains counts against `max-lines-per-function`, and this one pushed it\n * past the ceiling.\n *\n * Runs AFTER the CORS preflight and BEFORE routing: a limited caller should not reach a handler,\n * and a browser still needs its CORS answer to read the 429 as a 429 rather than as a network\n * failure.\n */\nexport function rateLimitCheckFragment(\n rateLimit: RateLimitConfig | undefined,\n indent: string,\n /** The arguments `callerAddress` is CALLED with — see `deployedRateLimitFragment`'s `params`. */\n args = 'request, server',\n /** How this target answers a caller over its budget. Only `bun` can use the default. */\n refuse = 'return withCors(request, withSecurityHeaders(rateLimited(limit), SECURITY_HEADERS))',\n /** How it answers a caller it could not name. Same shape, different body. */\n refuseUnnamed = 'return withCors(request, withSecurityHeaders(unnamedCaller(), SECURITY_HEADERS))',\n): string[] {\n if (rateLimit === undefined) return []\n return [\n `${indent}const caller = callerAddress(${args})`,\n `${indent}if (caller === undefined) {`,\n `${indent} ${refuseUnnamed}`,\n `${indent}}`,\n // B-257 — the call side of the pair. `deployedRateLimitFragment` emits the DECLARATION; this\n // emits the CALL, and the two branch on the same fact or the entry names a symbol it never\n // declared. A durable limiter returns a promise; the sync facade does not.\n // B-262 — `await` unconditionally. `buildRateLimiter` is always async, so this line no longer\n // asks what the config declared. The conditional it replaces is where B-257's defect lived:\n // a Promise read for `limited` is always `undefined`, always falsy, and every request passes.\n `${indent}const limit = await RATE_LIMIT(caller)`,\n `${indent}if (limit.limited) {`,\n `${indent} ${refuse}`,\n `${indent}}`,\n ]\n}\n","/**\n * The configuration a deployed entry could not apply (usetheokit/theokit#425).\n *\n * ## Why this is not another literal renderer\n *\n * `deployed-csrf.ts` and `deployed-cors.ts` bake their values into the emitted source, which works\n * because `csrf` is an enum and `disallowed` is a `{ routes, behavior }` object — plain data, and a\n * deployed function has no `theo.config.ts` to read.\n *\n * The two concerns left over from #410 turn out to be different from each other, and the difference\n * is the whole design:\n *\n * - **`serialization` is plain data too.** The config field is `z.enum(['json', 'superjson'])`\n * (`config/schema.ts:147`) — a selector, not a transformer. `resolveTransformer` turns it into the\n * functions, and it already ships from `theokit/server`. So this half is a literal like the rest,\n * and the deployed entry resolves it exactly the way `theokit start` does\n * (`cli/commands/start/index.ts:108`), from the same string, through the same function.\n * - **`plugins` genuinely carries functions.** A plugin is constructed in `theo.config.ts` and there\n * is no literal for a closure, so this half needs the entry to import a module instead.\n *\n * ## Static import, not `import()` in the request path\n *\n * The tempting shortcut is `await import('../../theo.config.js')` inside the handler. It trades a\n * silent failure for a louder one on targets with no filesystem, and it moves configuration\n * resolution into every request on the targets that do have one.\n *\n * What this emits instead is a TOP-LEVEL import of a module the build already resolved and wrote\n * beside the entry — the same shape `renderBakedRoutes` uses for route modules (#369): decide on\n * the build machine, emit a static specifier. It is evaluated once at module load, the target's\n * bundler can see through it, and a plugin that needs an API the target lacks fails the build\n * rather than the first request.\n *\n * ## Why each half is optional\n *\n * An app that declares neither concern must produce the entry it produced before this existed.\n * Importing a module the build did not emit fails at load, and spreading an empty object costs an\n * allocation per request for nothing. So an empty request renders to nothing at all, and the\n * caller's `executeRoute` literal is unchanged.\n *\n * The halves are independent on purpose: an app that only picks `superjson` must not be made to\n * carry a plugins module, and an app with plugins and default JSON must not gain a transformer\n * lookup. Coupling them would have made the common case pay for the rare one.\n */\n\n/**\n * The option every Web-standards adapter grows to carry non-serialisable configuration.\n *\n * Composed into each adapter's option type the way `DeployedCsrfOptions` already is, so the six\n * targets cannot drift into six spellings of the same field.\n */\n/**\n * The project's `serverDir`, carried into every generated entrypoint (#RFC server-layout).\n *\n * Separate from the other option groups because it is not a runtime feature toggle: it is the\n * project's own layout, and an adapter that hardcodes `'server'` agrees with the default by\n * COINCIDENCE. The moment a project sets the option — the entire point of it existing — the\n * generated entrypoint resolves a directory that is not there, and only after deploy: the build\n * succeeds, the bundle is written, and routes 404 in production with nothing naming the cause.\n */\nexport interface DeployedServerDirOptions {\n /** Project-relative server directory. Absent ⇒ the schema default, `server`. */\n serverDir?: string\n}\n\n/**\n * The server directory as a quoted TypeScript literal, ready to interpolate into generated source.\n *\n * `JSON.stringify` rather than wrapping in quotes by hand: the value reaches this from user config,\n * so a directory containing a quote or a backslash would otherwise emit a syntax error into\n * somebody else's build — a worse failure than the one this fixes.\n */\nexport function serverDirLiteral(opts: DeployedServerDirOptions): string {\n return JSON.stringify(opts.serverDir ?? 'server')\n}\n\n/**\n * The agents directory, same shape and same reason as `serverDir` above.\n *\n * `scanAgents(projectRoot, agentsDirName = 'agents')` takes the name as its SECOND parameter\n * (`server/scan/agent-scan.ts:56`). Nine call sites pass the configured value; the generated\n * deploy entry was the only one that did not, so the default won and a project whose agents live\n * under the documented `core/agents` (`config/schema.ts:66`) served none of them — 404 per agent,\n * after deploy, with nothing naming the cause. Measured 2026-09-21 by executing `buildBun`\n * against a config carrying both directories and reading what it emitted.\n */\nexport interface DeployedAgentsDirOptions {\n /** Project-relative agents directory. Absent ⇒ the schema default, `agents`. */\n agentsDir?: string\n}\n\nexport function agentsDirLiteral(opts: DeployedAgentsDirOptions): string {\n return JSON.stringify(opts.agentsDir ?? 'agents')\n}\n\nexport interface DeployedRuntimeConfigOptions {\n /**\n * Specifier of the plugins module the build wrote beside the entry, or `undefined` when the app\n * declares no plugins and the build wrote none.\n */\n runtimeConfigModule?: string\n /**\n * The app's `serialization` selector, carried as a literal.\n *\n * `'json'` and `undefined` both mean the default, and neither emits anything: `executeRoute`\n * already falls back to `JSON.stringify`, and the `x-theo-transformer` header is deliberately\n * absent for the default so a client is told only when there is something to be told.\n */\n serialization?: 'json' | 'superjson'\n}\n\n/** The three places an entry has to grow to carry non-serialisable configuration. */\nexport interface DeployedRuntimeConfigFragment {\n /** Top-level imports. Empty when the build emitted no config module. */\n readonly imports: string[]\n /** Module-scope declarations — evaluated once, at load. Empty when there is nothing to carry. */\n readonly declarations: string[]\n /**\n * Spread into the entry's `executeRoute({ … })` literal, inside an async function.\n *\n * Empty string when there is nothing to carry, so the call site keeps the exact shape it had.\n */\n readonly executeRouteSpread: string\n}\n\nconst EMPTY: DeployedRuntimeConfigFragment = {\n imports: [],\n declarations: [],\n executeRouteSpread: '',\n}\n\n/**\n * What a deployed entry needs in order to apply `config.plugins` and `config.serialization`.\n *\n * @param moduleSpecifier - specifier of the runtime-config module the build emitted beside the\n * entry, or `undefined` when the app declared neither concern and the build emitted none.\n */\nexport function deployedRuntimeConfigFragment(\n options: DeployedRuntimeConfigOptions | undefined,\n): DeployedRuntimeConfigFragment {\n const pluginsModule = options?.runtimeConfigModule\n // 'json' is the default and emits nothing — see `serialization` above.\n const serialization = options?.serialization === 'superjson' ? 'superjson' : undefined\n if (pluginsModule === undefined && serialization === undefined) return EMPTY\n\n const imports: string[] = []\n const declarations: string[] = []\n const spread: string[] = []\n\n if (pluginsModule !== undefined) {\n imports.push(\n `import { createPluginRunnerFromConfig } from 'theokit/server'`,\n `// #425 — the app's own plugins, resolved on the build machine and written beside this entry.`,\n `// A closure has no literal, so this is an import rather than a baked value.`,\n `import theoRuntimeConfig from '${pluginsModule}'`,\n )\n declarations.push(\n `// Built ONCE, at module load. A runner rebuilt per request would re-run every plugin's`,\n `// \\`register\\`, which is where a plugin allocates the state its hooks then read.`,\n `const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(theoRuntimeConfig.plugins)`,\n )\n // Awaited, not passed along: `createPluginRunnerFromConfig` is async because `register` is, and\n // a pending promise handed to `executeRoute` is a truthy object with none of the runner's\n // methods — every hook would silently not fire, which is this issue's own defect one layer in.\n spread.push(`pluginRunner: await THEO_PLUGIN_RUNNER`)\n }\n\n if (serialization !== undefined) {\n imports.push(`import { resolveTransformer } from 'theokit/server'`)\n declarations.push(\n `// #425 — a literal, because \\`config.serialization\\` is a SELECTOR and not a transformer.`,\n `// Same string, same function \\`theokit start\\` calls, so the deployed response and the local`,\n `// one cannot disagree about what the app asked for — including the \\`x-theo-transformer\\``,\n `// header, whose absence is what made this a data bug rather than a formatting one.`,\n `const THEO_TRANSFORMER = resolveTransformer('${serialization}')`,\n )\n spread.push(`transformer: THEO_TRANSFORMER`)\n }\n\n return { imports, declarations, executeRouteSpread: `${spread.join(', ')},` }\n}\n","/**\n * The request id a deployed entry uses, and the header it echoes back.\n *\n * ## The defect this closes\n *\n * Every generated entry minted a fresh `randomUUID()` per request and set no correlation header\n * at all on a success path (usetheokit/theokit#410). Both Node paths do the opposite: they resolve\n * an incoming `traceparent` / `x-request-id` through `extractTraceId` and echo the result under\n * both `x-request-id` and `x-trace-id` (`cli/commands/start/request-handler.ts`,\n * `vite-plugin/api-middleware.ts`).\n *\n * The consequence is that a trace crossing into a deployed function starts over. The caller's id\n * is discarded, and the response carries nothing to correlate against — so a request that fails in\n * production cannot be tied to the client that made it, which is the one situation the id exists\n * for.\n *\n * ## Why `setHeader` before the handler, rather than wrapping the response\n *\n * It is what the Node path does, and the shim reproduces Node's semantics exactly: `writeHead`\n * MERGES into the header map rather than replacing it (`web-shim.ts`), so a header set here\n * survives the handler's own `writeHead` and a handler that sets its own id still wins. Wrapping\n * the finished `Response` instead would have to mutate a response whose body is already streaming\n * (#382), and would miss the branches that return before the shim is built.\n */\n\n/**\n * Lines that resolve the request id and echo it, as generated source.\n *\n * @param requestVar - the name the entry gave the Web `Request` in scope\n * @param indent - leading whitespace, so the emitted file stays readable\n */\nexport function deployedTraceFragment(requestVar: string, indent: string): string[] {\n return [\n `${indent}// #410 — honour the caller's trace id instead of minting a new one, and echo it.`,\n `${indent}// \\`extractTraceIdFromRequest\\` validates the caller-controlled \\`x-request-id\\``,\n `${indent}// before trusting it, and falls back to a fresh UUID when neither header is present.`,\n `${indent}const requestId = extractTraceIdFromRequest(${requestVar})`,\n `${indent}res.setHeader('x-request-id', requestId)`,\n `${indent}res.setHeader(TRACE_HEADER, requestId)`,\n ]\n}\n"],"mappings":";;;;;;;AAgEA,IAAM,QAAgC,EAAE,SAAS,CAAC,GAAG,cAAc,CAAC,GAAG,QAAQ,CAAC,GAAG,YAAY,GAAG;AAqGlG,IAAM,kBAAkB;AAAA,EACtB;AAAA,EACA;AACF;AAGA,IAAM,eAAe;AAYrB,IAAM,oBAAoB;AAuBnB,SAAS,uBAAuBA,mBAAiD;AACtF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,aAAa;AAAA,IACb,kBAAAA;AAAA,IACA,YAAY;AAAA,IACZ,WAAW;AAAA,IACX,cAAc;AAAA,EAChB;AACF;AAQO,IAAM,0BAA0B;AAEhC,SAAS,uBACd,QACA,OAA2B,CAAC,GACJ;AACxB,MAAI,WAAW,OAAW,QAAO;AACjC,MAAI,OAAO,SAAS,WAAW,OAAO,OAAO,WAAW,EAAG,QAAO;AAElE,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,SAAS,KAAK,gBAAgB;AAEpC,QAAM,aACJ,OAAO,SAAS,UACZ,gBAAgB,OAAO,QAAQ,OAAO,eAAe,KAAK,gBAAgB,IAC1E,kBAAkB,EAAE,GAAG,QAAQ,kBAAkB,KAAK,iBAAiB,CAAC;AAE9E,SAAO;AAAA,IACL,YAAY,8BAA8B,QAAQ;AAAA,IAClD,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMP,iFAAiF,WAAW,cAAc,GAAG,OAAO,SAAS,SAAS,iBAAiB,EAAE,YAAY,MAAM;AAAA,MAC3K,GAAG,WAAW;AAAA,IAChB;AAAA,IACA,cAAc;AAAA,M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AAQ;AAClD;AAgCA,IAAMC,SAAuC;AAAA,EAC3C,SAAS,CAAC;AAAA,EACV,cAAc,CAAC;AAAA,EACf,oBAAoB;AACtB;AAQO,SAAS,8BACd,SAC+B;AAC/B,QAAM,gBAAgB,SAAS;AAE/B,QAAM,gBAAgB,SAAS,kBAAkB,cAAc,cAAc;AAC7E,MAAI,kBAAkB,UAAa,kBAAkB,OAAW,QAAOA;AAEvE,QAAM,UAAoB,CAAC;AAC3B,QAAM,eAAyB,CAAC;AAChC,QAAM,SAAmB,CAAC;AAE1B,MAAI,kBAAkB,QAAW;AAC/B,YAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA,kCAAkC,aAAa;AAAA,IACjD;AACA,iBAAa;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAIA,WAAO,KAAK,wCAAwC;AAAA,EACtD;AAEA,MAAI,kBAAkB,QAAW;AAC/B,YAAQ,KAAK,qDAAqD;AAClE,iBAAa;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,gDAAgD,aAAa;AAAA,IAC/D;AACA,WAAO,KAAK,+BAA+B;AAAA,EAC7C;AAEA,SAAO,EAAE,SAAS,cAAc,oBAAoB,GAAG,OAAO,KAAK,IAAI,CAAC,IAAI;AAC9E;;;ACpJO,SAAS,sBAAsB,YAAoB,QAA0B;AAClF,SAAO;AAAA,IACL,GAAG,MAAM;AAAA,IACT,GAAG,MAAM;AAAA,IACT,GAAG,MAAM;AAAA,IACT,GAAG,MAAM,+CAA+C,UAAU;AAAA,IAClE,GAAG,MAAM;AAAA,IACT,GAAG,MAAM;AAAA,EACX;AACF;","names":["agentsDirLiteral","EMPTY"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/resolve-plugin-specifiers.ts","../src/server/transformer.ts","../src/vite-plugin/hoist-head-tags.ts","../src/vite-plugin/ssr-dev-middleware.ts","../src/server/agent/agent-card-handler.ts","../src/server/agent/approve-agent.ts","../src/server/agent/handle-agent-run-reconnect.ts","../src/server/agent/thread-dispatcher.ts","../src/server/agent/thread-run-registry.ts","../src/server/agent/handle-thread-routes.ts","../src/server/agent/list-approvals-handler.ts","../src/server/agent/serve-aux-routes.ts","../src/server/http/plugin-lifecycle.ts","../src/server/http/resolve-agent-subject.ts"],"sourcesContent":["/**\n * Turn `config.plugins` entries that are module SPECIFIERS into plugins (usetheokit/theokit#425).\n *\n * ## Why the field grew a second shape\n *\n * `config.plugins` holds constructed objects, and a generated deploy entry cannot carry a closure:\n * there is no literal for one. So on all six Web-standards targets the entry built its request\n * context with no runner and every lifecycle hook was dead on a deployed app while firing locally.\n *\n * Two ways out were weighed:\n *\n * - **Bundle `theo.config.ts` into the entry.** Rejected on measurement. It silently drops\n * `theo.config.<NODE_ENV>.ts`, which `loadConfig` merges (`config/load-config.ts:92`) — a new\n * silent drop, which is the exact class of defect this work exists to remove. And it pulls every\n * module the config imports (database drivers, build-only helpers) into a Worker bundle that\n * builds today, so the common case would pay for the rare one.\n * - **Name the module.** A string entry says which module the plugin comes from, so the build emits\n * a static import for that module and nothing else. One declaration serves the local server and\n * the deployed entry, which is what keeps them from disagreeing.\n *\n * The second is what this implements. It is ADDITIVE: an app passing constructed objects is\n * untouched, and gets the same treatment it always got.\n *\n * ## Why this lives in `config/` and not beside `createPluginRunnerFromConfig`\n *\n * Resolving a specifier means importing a path, and that means `node:url`/`node:path`. `server/`\n * holds a no-`node:*` invariant so the same code serves the Web, Tauri and TUI targets\n * (`rules/three-target-parity.md`). `config/` already reads the filesystem — `load-config.ts` is\n * the module that finds `theo.config.ts` at all — and it is the one place BOTH local entry points\n * (`theokit start` and the Vite dev server) already import from. So the specifier is resolved\n * where the config is read, and `createPluginRunnerFromConfig` keeps taking what it always took:\n * objects.\n */\nimport { isAbsolute, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\n/**\n * A declared plugin module that could not be turned into a plugin.\n *\n * Its own error type because the alternative — skipping the entry — leaves an app running with one\n * fewer plugin than it declared and nothing saying so. That is the failure this issue is about,\n * reproduced at the door.\n */\nexport class UnresolvablePluginSpecifierError extends Error {\n constructor(index: number, specifier: string, reason: string) {\n super(`plugins[${index}] (${specifier}) could not be loaded: ${reason}`)\n this.name = 'UnresolvablePluginSpecifierError'\n }\n}\n\n/**\n * Resolve every string entry in `plugins` to the module's default export, in order.\n *\n * @param plugins - the raw `config.plugins` array: constructed plugins, module specifiers, or both.\n * @param cwd - the project root a relative specifier is resolved against.\n */\nexport async function resolvePluginSpecifiers(\n plugins: readonly unknown[],\n cwd: string,\n): Promise<unknown[]> {\n const resolved: unknown[] = []\n // Sequential on purpose. Plugin order is hook order, and resolving concurrently then collecting\n // as each settles would reorder an app's lifecycle by module size.\n for (const [index, entry] of plugins.entries()) {\n resolved.push(typeof entry === 'string' ? await importPlugin(entry, index, cwd) : entry)\n }\n return resolved\n}\n\nasync function importPlugin(specifier: string, index: number, cwd: string): Promise<unknown> {\n const target = isAbsolute(specifier) ? specifier : resolve(cwd, specifier)\n let mod: { default?: unknown }\n try {\n mod = (await import(/* @vite-ignore */ pathToFileURL(target).href)) as { default?: unknown }\n } catch (err) {\n throw new UnresolvablePluginSpecifierError(index, specifier, messageOf(err))\n }\n if (mod.default === undefined) {\n // Registering `undefined` would fail later inside `createPluginRunnerFromConfig` with an error\n // naming a shape rather than a file, which is the harder half of the diagnosis.\n throw new UnresolvablePluginSpecifierError(\n index,\n specifier,\n 'the module has no default export; a plugin module must `export default` its plugin',\n )\n }\n return mod.default\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * Moves the document metadata a route rendered into the `<head>` where it belongs.\n *\n * ## Why this exists\n *\n * React 19 hoists `<title>`, `<meta>` and `<link>` into the head — **in the browser**, by moving\n * DOM nodes after hydration. On the server it emits them inline, wherever the component sat, and\n * the SSR output is injected inside `<div id=\"root\">`. So a route's own metadata ships in the\n * BODY.\n *\n * For a reader that changes nothing: hydration moves the tags a moment later. For a crawler it\n * changes everything, because the ones that matter never run JavaScript. Every social unfurler —\n * X, LinkedIn, Slack, Discord, WhatsApp — reads the served `<head>` and stops. Without this, every\n * page of a site unfurls with whatever static fallback `index.html` happens to carry: share ten\n * different documentation pages, get ten identical cards.\n *\n * Turning SSR on to fix social previews and finding they still do not work is a bad afternoon, so\n * the framework does the hoist itself (usetheokit/theokit#319).\n *\n * ## Precedence\n *\n * The route wins over the template. `index.html` holds site-wide defaults; a page that states its\n * own title, description or canonical is being specific on purpose, and shipping both would leave\n * the crawler to pick — in practice the first one, which is the generic one.\n */\n\n/**\n * Tags React hoists, and therefore the ones worth moving.\n *\n * Two separate patterns rather than one with an alternation: a single expression covering both the\n * self-closing tags and the `<title>…</title>` pair needs a lazy `[\\s\\S]*?` next to a lazy\n * `[^>]*?`, and that nests two unbounded quantifiers — catastrophic backtracking on hostile input,\n * which here is a served HTML document. Each pattern below is linear: `[^>]` and `[^<]` cannot\n * cross the delimiter that ends the match.\n */\nconst VOID_METADATA = /<(?:meta|link)\\b[^>]*>/gi\n/** `<title>` content is text, so it cannot contain `<` — the class is what keeps this linear. */\nconst TITLE_TAG = /<title\\b[^>]*>[^<]*<\\/title>/gi\n\n/** Runs `replacer` over every hoistable tag, in document order. */\nfunction replaceHoistable(html: string, replacer: (tag: string) => string): string {\n return html.replace(TITLE_TAG, replacer).replace(VOID_METADATA, replacer)\n}\n\n/**\n * The identity of a metadata tag, used to decide what the route replaces.\n *\n * `<meta name=\"description\">` and `<meta property=\"og:title\">` are distinct slots; two `<meta>`\n * tags with different names are not duplicates. A `<link>` is keyed by `rel`, so a route's\n * canonical replaces the template's while a stylesheet link is left alone.\n *\n * Anything unkeyed (a `<link rel=\"preconnect\">`, say) returns `undefined` and is simply appended —\n * additive tags must not evict each other.\n */\nexport function metadataKey(tag: string): string | undefined {\n if (/^<title\\b/i.test(tag)) return 'title'\n\n const name = /\\bname=[\"']([^\"']+)[\"']/i.exec(tag)?.[1]\n const property = /\\bproperty=[\"']([^\"']+)[\"']/i.exec(tag)?.[1]\n const rel = /\\brel=[\"']([^\"']+)[\"']/i.exec(tag)?.[1]\n\n if (/^<meta\\b/i.test(tag)) {\n if (property !== undefined) return `property:${property.toLowerCase()}`\n if (name !== undefined) return `name:${name.toLowerCase()}`\n return undefined\n }\n\n if (/^<link\\b/i.test(tag) && rel !== undefined) {\n const slug = rel.toLowerCase()\n // Only single-valued rels are slots. `stylesheet`, `preload` and friends are additive: keying\n // them would let one page's stylesheet evict another's.\n return slug === 'canonical' || slug === 'manifest' ? `link:${slug}` : undefined\n }\n\n return undefined\n}\n\nexport interface HoistedHead {\n /** The rendered HTML with its metadata tags removed. */\n html: string\n /** Those tags, ready to be placed in the head. */\n headTags: string[]\n}\n\n/** Pulls hoistable metadata out of rendered SSR markup. */\nexport function extractHeadTags(ssrHtml: string): HoistedHead {\n const headTags: string[] = []\n const html = replaceHoistable(ssrHtml, (tag) => {\n headTags.push(tag)\n return ''\n })\n return { html, headTags }\n}\n\n/**\n * Inserts `headTags` into the template's head, dropping any template tag the route supersedes.\n *\n * Returns the template untouched when there is nothing to hoist or no `</head>` to hoist into —\n * a missing head is a malformed template, and rewriting it further would not help anyone.\n */\nexport function injectIntoHead(template: string, headTags: string[]): string {\n if (headTags.length === 0) return template\n\n const closingHead = template.toLowerCase().lastIndexOf('</head>')\n if (closingHead === -1) return template\n\n const supersededKeys = new Set(\n headTags.map((tag) => metadataKey(tag)).filter((key): key is string => key !== undefined),\n )\n\n let head = template.slice(0, closingHead)\n if (supersededKeys.size > 0) {\n head = replaceHoistable(head, (tag) => {\n const key = metadataKey(tag)\n return key !== undefined && supersededKeys.has(key) ? '' : tag\n })\n }\n\n return `${head} ${headTags.join('\\n ')}\\n ${template.slice(closingHead)}`\n}\n\n/**\n * The whole operation: strip metadata from the rendered markup and place it in the template's head.\n */\nexport function hoistHeadTags(\n template: string,\n ssrHtml: string,\n): { template: string; html: string } {\n const { html, headTags } = extractHeadTags(ssrHtml)\n const hoisted = injectIntoHead(template, headTags)\n\n // Fail SAFE, not silent. `injectIntoHead` returns the template untouched when it finds no\n // `</head>` — and if we returned the stripped body alongside it, the metadata would be removed\n // from one place and added to neither. It would vanish, with nothing to show for it.\n //\n // That is not hypothetical: a template whose COMMENT mentioned `<div id=\"root\">` split at the\n // comment, leaving a \"head\" half with no `</head>` in it, and every route silently lost its\n // title and canonical. Metadata in the wrong place still works after hydration; metadata that is\n // gone never comes back.\n if (hoisted === template) return { template, html: ssrHtml }\n\n return { template: hoisted, html }\n}\n","/**\n * T2.2 (architecture-medium-deferrals plan, ADR D2) — SSR dev middleware\n * extracted from `vite-plugin/index.ts` for SRP.\n *\n * `setupSsrDevMiddleware(server, opts)` registers a Connect-style middleware\n * on the Vite dev server that:\n * 1. Skips API, static, and HMR requests (let other middlewares handle).\n * 2. Reads `index.html`, runs `transformIndexHtml`.\n * 3. Generates per-request nonce, applies security headers (CSP + Cache-Control).\n * 4. Calls `ssrLoadModule(VIRTUAL_ENTRY_SERVER_ID).render(url, { nonce })`.\n * 5. Injects rendered HTML (with hydration script) into root div.\n * 6. On error: ssrFixStacktrace + fallback to CSR via `next()`.\n *\n * No-op when `ssrEnabled === false`. Caller's responsibility to gate.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { ViteDevServer } from 'vite'\n\nimport { findRootDiv } from '../core/contracts/find-root-div.js'\nimport {\n applySecurityHeaders,\n generateNonce,\n type SecurityHeadersConfig,\n} from '../server/internal-api.js'\n\nimport { hoistHeadTags } from './hoist-head-tags.js'\n\ninterface SsrRenderResult {\n html: string\n hydrationData: {\n loaderData?: unknown\n actionData?: unknown\n errors?: unknown\n }\n}\n\ninterface SsrEntryServer {\n render: (\n url: string,\n opts: { nonce: string },\n ) => Promise<SsrRenderResult | { redirect: Response } | string>\n}\n\n/**\n * Stamps the request nonce onto every inline `<script>` the HTML already carries.\n *\n * `transformIndexHtml` lets Vite plugins inject their own scripts, and they know nothing about our\n * CSP. `@vitejs/plugin-react` injects its refresh preamble as an INLINE module script with no\n * nonce, so a nonce-based `script-src` blocks it, `window.$RefreshReg$` is never defined, and the\n * first component module throws \"@vitejs/plugin-react can't detect preamble\". SSR still produced\n * the HTML, so the page looks fine and simply never hydrates — nothing interactive works, and the\n * one console error points at Vite rather than at us (usetheokit/theokit#319).\n *\n * Only scripts WITHOUT `src` are stamped: a same-origin `src` is already covered by `'self'`, and\n * an inline script is the only kind a nonce is needed for. Scripts that already carry a nonce are\n * left alone, so the render's own output is never rewritten.\n *\n * Deliberately not a general HTML parser: this runs per request in dev, on markup we produced or a\n * Vite plugin injected, and the pattern only ever matches an opening `<script>` tag.\n */\nexport function applyNonceToInlineScripts(html: string, nonce: string): string {\n return html.replace(\n /<script(?![^>]*\\ssrc=)(?![^>]*\\snonce=)([^>]*)>/gi,\n `<script nonce=\"${nonce}\"$1>`,\n )\n}\n\nfunction isSsrRenderResult(value: unknown): value is SsrRenderResult {\n if (typeof value !== 'object' || value === null) return false\n if (!('html' in value)) return false\n return typeof (value as Record<string, unknown>).html === 'string'\n}\n\ninterface SsrDevMiddlewareOptions {\n projectRoot: string\n virtualEntryServerId: string\n securityHeaders: SecurityHeadersConfig | undefined\n}\n\n/**\n * Attach the SSR dev middleware to a Vite dev server. Caller decides whether\n * to invoke this based on `ssrEnabled` — this function does not gate.\n */\nexport function setupSsrDevMiddleware(server: ViteDevServer, opts: SsrDevMiddlewareOptions): void {\n server.middlewares.use((req, res, next) => {\n void (async () => {\n const url = req.url ?? '/'\n // Skip API, static, and HMR requests\n if (\n url.startsWith('/api/') ||\n url.startsWith('/@') ||\n url.startsWith('/node_modules/') ||\n url.includes('.')\n ) {\n next()\n return\n }\n\n try {\n const indexPath = resolve(opts.projectRoot, 'index.html')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- projectRoot is from `theokit dev`'s caller-controlled cwd\n let template = readFileSync(indexPath, 'utf-8')\n\n // T4.1 — Generate a per-request nonce and apply security headers BEFORE render.\n // The same nonce flows into React's renderToPipeableStream({ nonce }) so every\n // emitted <script> carries it AND into the CSP script-src directive.\n // EC-3: applySecurityHeaders also forces Cache-Control: private, no-store.\n //\n // The nonce is minted BEFORE `transformIndexHtml` so the scripts Vite plugins inject can be\n // stamped with it. Minting it afterwards left the React refresh preamble unnonced, the CSP\n // blocked it, and the app never hydrated (usetheokit/theokit#319).\n const nonce = generateNonce()\n\n template = await server.transformIndexHtml(url, template)\n template = applyNonceToInlineScripts(template, nonce)\n applySecurityHeaders(\n res,\n opts.securityHeaders ?? {},\n { production: process.env.NODE_ENV === 'production' },\n { nonce },\n )\n\n const mod = (await server.ssrLoadModule(opts.virtualEntryServerId)) as SsrEntryServer\n const result = await mod.render(url, { nonce })\n\n if (result && typeof result === 'object' && 'redirect' in result) {\n res.writeHead(302, {\n Location: result.redirect.headers.get('location') ?? '/',\n })\n res.end()\n return\n }\n\n // Backward-compat: old render returned string. New shape returns\n // { html, hydrationData } so the framework can emit the hydration\n // data script OUTSIDE the React root (fixes hydration mismatch).\n let ssrHtml: string\n let hydrationScript = ''\n if (typeof result === 'string') {\n ssrHtml = result\n } else if (isSsrRenderResult(result)) {\n ssrHtml = result.html\n const dataJson = JSON.stringify(result.hydrationData).replace(/</g, '\\\\u003c')\n hydrationScript = `<script nonce=\"${nonce}\">window.__staticRouterHydrationData=${dataJson}</script>`\n } else {\n ssrHtml = ''\n }\n // Move the route's <title>/<meta>/<link> out of the rendered body and into the head.\n // React only hoists those in the browser, after hydration — a crawler that does not run JS\n // would otherwise never see a page's own title or social card (usetheokit/theokit#319).\n const hoisted = hoistHeadTags(template, ssrHtml)\n template = hoisted.template\n ssrHtml = hoisted.html\n\n const rootDiv = findRootDiv(template)\n if (!rootDiv) {\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(template)\n return\n }\n\n const splitIdx = rootDiv.insertAt\n const html =\n template.slice(0, splitIdx) + ssrHtml + hydrationScript + template.slice(splitIdx)\n\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(html)\n } catch (err) {\n server.ssrFixStacktrace(err as Error)\n console.error('[SSR Dev Error]', err)\n // Fallback to CSR\n next()\n return\n }\n })()\n })\n}\n","/**\n * M15 (theokit-ai-first) — serve the A2A agent card at `/.well-known/<name>/agent-card.json`.\n *\n * `buildAgentCard` (@theokit/agents) is the pure generator; this handler compiles a loaded agent\n * module to its tools + streaming capability, builds the card, and returns it as a Web-Standard\n * JSON `Response` (G8). The dev middleware + prod handler branch to this before the agent POST route.\n */\nimport { type AgentManifestEntry, buildAgentCard, compileLoadedAgentModule } from '@theokit/agents'\n\nconst WELL_KNOWN = /^\\/\\.well-known\\/([^/]+)\\/agent-card\\.json$/\n\n/** Return the agent name when `urlPath` is a well-known card path, else `null`. */\nexport function isAgentCardPath(urlPath: string): string | null {\n const match = WELL_KNOWN.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Build a minimal manifest entry (the subset `buildAgentCard` reads) from a compiled agent. */\nfunction toManifestEntry(name: string, route: string, mod: unknown): AgentManifestEntry {\n const compiled = compileLoadedAgentModule(mod, `agent card for \"${name}\"`)\n return {\n name,\n route,\n stream: compiled.stream,\n mainLoop: { method: '', strategy: '' },\n guards: [],\n interceptors: [],\n tools: compiled.tools.map((t) => ({\n name: t.name,\n description: t.description,\n approval: false,\n trace: false,\n audit: false,\n })),\n subAgents: [],\n }\n}\n\n/**\n * Serve the A2A card for a loaded agent module. Returns 200 with the card JSON, or 500 with an\n * error body if the module is not a valid agent (fail-clear, not a silent empty card).\n */\nexport function handleAgentCard(\n mod: unknown,\n name: string,\n route: string,\n baseUrl: string,\n): Response {\n try {\n const card = buildAgentCard(toManifestEntry(name, route, mod), { baseUrl })\n return new Response(JSON.stringify(card), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n } catch (err) {\n return new Response(\n JSON.stringify({\n error: {\n code: 'AGENT_CARD_FAILED',\n message: err instanceof Error ? err.message : 'card build failed',\n },\n }),\n { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } },\n )\n }\n}\n","/**\n * M4 (theokit-ai-first) — the HITL approve endpoint: `POST /api/agents/<name>/approve/<approvalId>`.\n *\n * The counterpart to `mountAgent`'s HITL pause. While a gated tool holds the SDK run paused (the\n * awaited `pre_tool_call` hook), the client POSTs here with `{ approved }`; this resolves the\n * pending approval in the shared registry, which un-pauses the run (allow) or vetoes the tool (deny).\n *\n * Web-Standard `Request` → `Response`, one wiring point shared by dev (vite middleware) and prod\n * (built server) so the two never drift (EC-4 parity with `mountAgent`). The registry is INJECTED —\n * dev/prod pass the process singleton (`getApprovalRegistry`), tests pass a fresh instance.\n */\nimport type { RoutePolicy } from '../../core/contracts/route-policy.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { admitAgentRequest, agentAccessDenied, type AgentSubjectResolver } from './agent-access.js'\nimport type { ApprovalDecision, ApprovalRegistry } from './approval-registry.js'\nimport { closePauseSpan } from './hitl-pause-spans.js'\n\n/** The path segment separating the agent name from the approval id. */\nconst APPROVE_SEGMENT = '/approve/'\n\nconst APPROVE_PATH = /^\\/api\\/agents\\/([^/]+)\\/approve\\/([^/]+)$/\n\n/**\n * The agent named by a `/api/agents/<name>/approve/<id>` path, or `null`.\n *\n * The route's own gate is the agent's declared policy, and reading the policy needs the agent —\n * which this path carries and nothing previously read (usetheokit/theokit#365).\n */\nexport function parseApprovalAgentName(urlPath: string): string | null {\n const match = APPROVE_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/**\n * Extract the `<approvalId>` from a `/api/agents/<name>/approve/<approvalId>` path.\n * Returns `null` when the path has no `/approve/` segment or an empty / nested id.\n */\nexport function parseApprovalId(urlPath: string): string | null {\n const at = urlPath.indexOf(APPROVE_SEGMENT)\n if (at === -1) return null\n const id = urlPath.slice(at + APPROVE_SEGMENT.length)\n return id.length > 0 && !id.includes('/') ? id : null\n}\n\n/** True when `urlPath` targets a HITL approve endpoint (used by dev/prod routing to branch early). */\nexport function isApprovalPath(urlPath: string): boolean {\n return urlPath.includes(APPROVE_SEGMENT)\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * M20 — cap on the serialized custom payload (16 KiB). A payload is a small structured note\n * (edited args, a reviewer comment), not a data channel — an oversized one is rejected fail-fast\n * rather than silently truncated (Rule 8).\n */\nconst MAX_PAYLOAD_BYTES = 16 * 1024\n\n/**\n * Extract an {@link ApprovalDecision} from an untrusted body; `null` when the shape is wrong.\n *\n * M20 — accepts an optional `reason` (string) and `payload` (object, capped at\n * {@link MAX_PAYLOAD_BYTES}). Backward-compatible: `{ approved }` and `{ approved, reason }` parse\n * unchanged. A non-object or oversized `payload` is rejected (returns `null` → the route 400s).\n *\n * @public\n */\nexport function parseApprovalBody(body: unknown): ApprovalDecision | null {\n if (typeof body !== 'object' || body === null) return null\n const b = body as Record<string, unknown>\n if (typeof b.approved !== 'boolean') return null\n const decision: ApprovalDecision = { approved: b.approved }\n if (b.reason !== undefined) {\n if (typeof b.reason !== 'string') return null\n decision.reason = b.reason\n }\n if (b.payload !== undefined) {\n if (typeof b.payload !== 'object' || b.payload === null || Array.isArray(b.payload)) return null\n if (JSON.stringify(b.payload).length > MAX_PAYLOAD_BYTES) return null\n decision.payload = b.payload\n }\n return decision\n}\n\n/**\n * The gates it applies (usetheokit/theokit#365):\n *\n * CSRF, which refuses a cross-origin POST and identifies nobody — and then the agent's declared\n * `policy`, which is what makes \"who is asking\" a question this endpoint can answer at all.\n * Reproduced before the policy existed: a process holding no cookie and no credential read a\n * pending id off the listing, POSTed here, and the gated tool ran.\n *\n * Ownership, which this endpoint could NOT decide until B-016 and now can, within a stated scope.\n * `mountAgent` records the run's subject on each approval it registers, for agents that DECLARE a\n * policy, and this route refuses a caller whose identity does not match. Before it, an\n * authenticated tenant could settle another tenant's approval on an agent both were admitted to —\n * the policy was the only thing between them, and the policy cannot see whose approval it is.\n *\n * Two limits, stated rather than implied. An agent that declares `'public'` records no owner, since\n * attributing approvals there would start refusing callers the declaration admits. And a thread\n * continuation runs headless, with no request whose identity could be resolved, so its approvals\n * record nobody. In both cases the endpoint behaves exactly as it did — `params.approvalId` is\n * still passed so an application holding its own owner map can answer more than the framework does.\n *\n * Returns:\n * 403 CSRF_FAILED — strict CSRF check failed\n * 403 FORBIDDEN — the agent's policy refused this caller\n * 400 BAD_REQUEST — no `/approve/<id>` in the path, or body lacks a boolean `approved`\n * 404 NOT_PENDING — the id is unknown or already settled (idempotent double-submit)\n * 200 { resolved:true } — the approval was settled by this call\n */\n/**\n * Refuse a caller who does not own this approval, where the ledger knows the owner (B-016).\n *\n * The agent's policy answers \"may this subject touch this agent's approvals\". It cannot answer \"is\n * this approval theirs\", because it is never told — which is why an authenticated tenant could\n * settle another tenant's approval on an agent both were admitted to. `mountAgent` now records the\n * run's subject on each approval it registers, for agents that DECLARE a policy, and this reads it.\n *\n * `undefined` from `ownerOf` covers three cases the endpoint treats identically — never registered,\n * already settled, and registered with no owner — and in all three there is nothing to compare a\n * caller against, so the endpoint behaves exactly as it did. The check only ever narrows.\n */\nasync function refuseIfNotOwner(\n registry: ApprovalRegistry,\n approvalId: string,\n resolveSubject: AgentSubjectResolver | undefined,\n params: Parameters<typeof agentAccessDenied>[1],\n): Promise<Response | undefined> {\n const owner = registry.ownerOf(approvalId)\n if (owner === undefined) return undefined\n\n const subject = resolveSubject === undefined ? null : await resolveSubject()\n if (subject?.id === owner) return undefined\n\n // An unidentifiable caller is refused, deliberately. An approval that HAS an owner must not be\n // settleable by whoever reaches the endpoint without an identity — admitting there would make the\n // guarantee depend on how the host wired its resolver rather than on who is asking.\n return agentAccessDenied(\n { allowed: false, reason: 'the approval belongs to another subject' },\n params,\n )\n}\n\nexport async function handleAgentApproval(\n request: Request,\n urlPath: string,\n registry: ApprovalRegistry,\n csrfMode: CsrfMode = 'strict',\n access: { policy?: RoutePolicy; resolveSubject?: AgentSubjectResolver } = {},\n): Promise<Response> {\n if (csrfMode !== 'off') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid && csrfMode === 'strict') {\n return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n }\n\n const approvalId = parseApprovalId(urlPath)\n if (approvalId === null) {\n return jsonError(400, 'BAD_REQUEST', 'Approval path must be /api/agents/<name>/approve/<id>.')\n }\n\n const params = {\n agent: parseApprovalAgentName(urlPath) ?? 'unknown',\n endpoint: 'approve' as const,\n approvalId,\n }\n const decision = await admitAgentRequest(access.policy, access.resolveSubject, params)\n if (!decision.allowed) return agentAccessDenied(decision, params)\n\n const notOwner = await refuseIfNotOwner(registry, approvalId, access.resolveSubject, params)\n if (notOwner !== undefined) return notOwner\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\n }\n const parsed = parseApprovalBody(body)\n if (parsed === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request body must contain a boolean `approved`.')\n }\n\n const resolved = registry.resolve(approvalId, parsed)\n if (!resolved) {\n return jsonError(404, 'NOT_PENDING', `No pending approval for id '${approvalId}'.`)\n }\n\n // THIS is the resume instant, and it is why the span could not be closed correctly before\n // (B-028). The run's observer never sees this request; it saw the tool's output arriving later\n // and closed the pause there, so the recorded wait was the human's plus the model's — measured at\n // +1523 ms on a run whose human answered at 3306 ms. Closing here, on the request that carries\n // the answer, makes the duration the human's by construction rather than by subtraction.\n closePauseSpan(approvalId, { resumeObserved: true })\n return new Response(JSON.stringify({ resolved: true }), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n","import {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport type { RunEventCache } from './run-event-cache.js'\n\n/**\n * M37 (ADR-0046 D5) — the reconnect / observe endpoint handler for\n * `GET /api/agents/<name>/runs/<runId>/stream`.\n *\n * Replays the frames the client missed (`seq > Last-Event-ID`, SSE-native), then\n * — if the run is still live — follows the live tail; a SECOND client can\n * observe a run a first started. Run already ended ⇒ replay + `[DONE]`. Unknown\n * `runId` ⇒ 404. The request `AbortSignal` unsubscribes on disconnect.\n */\n\nconst RUN_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/runs\\/([^/]+)\\/stream$/\n\n/**\n * Match `GET /api/agents/<name>/runs/<runId>/stream`; returns the decoded\n * `{ name, runId }` or `null` to fall through (mirrors `isMcpPath` etc.).\n */\nexport function isAgentRunStreamPath(urlPath: string): { name: string; runId: string } | null {\n const m = RUN_STREAM_PATH.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), runId: decodeURIComponent(m[2]) } : null\n}\n\n/** Parse `Last-Event-ID` (a frame `seq`) to a number; absent/invalid ⇒ -1 (replay from the start). */\nfunction parseLastEventId(raw: string | null): number {\n if (raw === null) return -1\n const n = Number.parseInt(raw, 10)\n return Number.isInteger(n) && n >= 0 ? n : -1\n}\n\nexport function handleAgentRunReconnect(\n runId: string,\n request: Request,\n cache: RunEventCache,\n): Response {\n // Unknown run ⇒ 404 (a run never started here, or already evicted).\n if (!cache.has(runId)) {\n return new Response(\n JSON.stringify({ error: { code: 'RUN_NOT_FOUND', message: `Unknown run '${runId}'.` } }),\n {\n status: 404,\n headers: { 'content-type': 'application/json' },\n },\n )\n }\n\n const afterSeq = parseLastEventId(request.headers.get('last-event-id'))\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const safeEnqueue = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* controller already closed by an abort race — ignore */\n }\n }\n const close = (): void => {\n if (closed) return\n safeEnqueue(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n\n // Atomic: snapshot replay frames AND subscribe to the live tail in one tick.\n const res = cache.attach(\n runId,\n afterSeq,\n (frame) => {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n // Evicted between has() and attach() (rare TOCTOU) ⇒ just end the stream.\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n }\n if (res.ended) {\n close()\n return\n }\n // Client disconnects ⇒ detach the live listener + close.\n request.signal.addEventListener('abort', () => {\n res.unsubscribe()\n close()\n })\n },\n })\n\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId } })\n}\n","/**\n * M39 (ADR-0048) — the thread follow-up dispatcher.\n *\n * Drives a run over the M37 durable cache HEADLESS — it iterates the SDK chunk\n * generator and `cache.append`s directly, NOT via a `Response` `ReadableStream`\n * (whose backpressure would stall a run with no HTTP reader). Subscribers read\n * from the cache via the thread / reconnect stream.\n *\n * - Post to an IDLE thread ⇒ start a run + pump.\n * - Post to an ACTIVE thread ⇒ FIFO-queue the follow-up.\n * - On terminal ⇒ `registry.endRun` hands back the next queued follow-up, which\n * is dispatched as a continuation on the SAME sessionId (⇒ the SDK continues\n * the conversation via its `ConversationStorageAdapter`).\n *\n * This adds NO agent loop — it reuses the SDK run (`startRun`) + the M37 cache.\n * Single-process (ADR-0048 D2).\n */\n\nimport type { WireChunk as UIMessageChunk } from '@theokit/presenter/wire'\n\nimport { type RunEventCache, mintRunId } from './run-event-cache.js'\nimport type { ThreadRunRegistry } from './thread-run-registry.js'\n\ninterface ThreadDispatchDeps {\n readonly registry: ThreadRunRegistry\n readonly cache: RunEventCache\n /** Start a run for a follow-up on `sessionId`; returns the SDK chunk stream. */\n readonly startRun: (sessionId: string, message: string) => AsyncIterable<UIMessageChunk>\n}\n\n/** Result of posting a follow-up: the started `runId` (idle thread) or `queued` (active thread). */\ntype PostFollowUpResult = { runId: string } | { queued: true }\n\n/**\n * Post a follow-up on a thread. IDLE ⇒ start a run (returns its `runId`); ACTIVE\n * ⇒ FIFO-queue it (returns `{ queued: true }`) — dispatched when the active run ends.\n */\nexport function postThreadFollowUp(\n deps: ThreadDispatchDeps,\n sessionId: string,\n message: string,\n): PostFollowUpResult {\n if (deps.registry.getActive(sessionId) !== null) {\n deps.registry.queue(sessionId, { message })\n return { queued: true }\n }\n return { runId: startAndPump(deps, sessionId, message) }\n}\n\n/** Mint a runId, mark the thread active, and pump the run into the cache headless. */\nfunction startAndPump(deps: ThreadDispatchDeps, sessionId: string, message: string): string {\n const runId = mintRunId()\n // Register the run in the cache SYNCHRONOUSLY (before the async pump appends its\n // first frame) so a subscriber resolving the active runId can attach immediately.\n deps.cache.begin(runId)\n deps.registry.startRun(sessionId, runId)\n pumpIntoCache(deps, sessionId, runId, deps.startRun(sessionId, message))\n return runId\n}\n\n/**\n * Drive `chunks` into the cache under `runId`, then end the run and dispatch the\n * next queued follow-up (if any) as a continuation. Fire-and-forget — the caller\n * does not await the run; subscribers observe it via the cache.\n */\nfunction pumpIntoCache(\n deps: ThreadDispatchDeps,\n sessionId: string,\n runId: string,\n chunks: AsyncIterable<UIMessageChunk>,\n): void {\n void (async () => {\n try {\n for await (const chunk of chunks) {\n deps.cache.append(runId, JSON.stringify(chunk))\n }\n } catch {\n // The SDK translator owns error semantics (surfaces failures as chunks);\n // the transport guarantees only a terminated, cache-ended run.\n } finally {\n deps.cache.end(runId)\n const next = deps.registry.endRun(sessionId, runId)\n if (next !== undefined) startAndPump(deps, sessionId, next.message)\n }\n })()\n}\n","/**\n * M39 (ADR-0048) — the in-process thread→run registry.\n *\n * A thread is the existing `sessionId` (the SDK conversation key). This registry\n * tracks, per thread, the single ACTIVE run, a FIFO queue of follow-ups to\n * dispatch as continuations, and one-shot \"next run\" waiters (so a client can\n * subscribe to a thread before posting a message and attach when the run starts).\n *\n * Pure state only — it never starts a run or touches the transport. The route\n * layer owns dispatch: on `endRun` it receives the next queued follow-up (if any)\n * and starts the continuation over the M37 durable transport.\n *\n * Single-process contract (ADR-0048 D2): a multi-instance deploy needs a shared\n * registry + leasing — that is infra (TheoCloud), explicitly out of M39. The\n * interface is injectable so a durable impl slots in later without touching the\n * routes. We do NOT build a distributed store now (YAGNI).\n */\n\n/** A follow-up message queued on an active thread, dispatched as a continuation. */\nexport interface FollowUp {\n readonly message: string\n}\n\nexport interface ThreadRunRegistry {\n /** The active runId for a thread, or `null` when the thread is idle. */\n getActive(sessionId: string): string | null\n /** Mark a run started for a thread (sets it active; fires + clears one-shot waiters). */\n startRun(sessionId: string, runId: string): void\n /**\n * Mark `runId` ended for a thread. A no-op unless `runId` is the current active\n * run (a stale terminal never clears a newer run). Clears the active run and\n * returns the next FIFO follow-up to dispatch as a continuation, or `undefined`.\n */\n endRun(sessionId: string, runId: string): FollowUp | undefined\n /** FIFO-enqueue a follow-up on a thread (dispatched when the active run ends). */\n queue(sessionId: string, followUp: FollowUp): void\n /**\n * Register a ONE-SHOT waiter fired with the runId of the NEXT run started on\n * this thread. Returns an unsubscribe fn. Used by subscribe-by-thread on an\n * idle thread (attach when the next run starts).\n */\n onNextRun(sessionId: string, cb: (runId: string) => void): () => void\n}\n\ninterface ThreadState {\n activeRunId: string | null\n readonly queue: FollowUp[]\n readonly waiters: Set<(runId: string) => void>\n}\n\nexport function createInProcessThreadRunRegistry(): ThreadRunRegistry {\n const threads = new Map<string, ThreadState>()\n const ensure = (sessionId: string): ThreadState => {\n let s = threads.get(sessionId)\n if (s === undefined) {\n s = { activeRunId: null, queue: [], waiters: new Set() }\n threads.set(sessionId, s)\n }\n return s\n }\n\n return {\n getActive(sessionId) {\n return threads.get(sessionId)?.activeRunId ?? null\n },\n startRun(sessionId, runId) {\n const s = ensure(sessionId)\n s.activeRunId = runId\n // Fire one-shot waiters, then clear them (single-threaded → no re-entrancy race).\n const waiters = [...s.waiters]\n s.waiters.clear()\n for (const cb of waiters) cb(runId)\n },\n endRun(sessionId, runId) {\n const s = threads.get(sessionId)\n if (s?.activeRunId !== runId) return undefined\n s.activeRunId = null\n return s.queue.shift()\n },\n queue(sessionId, followUp) {\n ensure(sessionId).queue.push(followUp)\n },\n onNextRun(sessionId, cb) {\n const s = ensure(sessionId)\n s.waiters.add(cb)\n return () => {\n s.waiters.delete(cb)\n }\n },\n }\n}\n\nlet serverRegistry: ThreadRunRegistry | undefined\n\n/** Process-wide singleton (mirrors `getRunEventCache` / `getApprovalRegistry`). */\nexport function getThreadRunRegistry(): ThreadRunRegistry {\n serverRegistry ??= createInProcessThreadRunRegistry()\n return serverRegistry\n}\n","/**\n * M39 (ADR-0048) — the thread signal routes over the M37 durable transport:\n *\n * - `POST /api/agents/<name>/threads/<sessionId>/message` — a follow-up. ACTIVE\n * run ⇒ FIFO-queue (dispatched as a continuation when it ends); IDLE ⇒ start a\n * run. Returns `202` (the run streams headless into the cache; observe it via\n * the thread stream). Spends LLM tokens ⇒ CSRF-gated (parity with mount-agent).\n * - `GET /api/agents/<name>/threads/<sessionId>/stream` — subscribe. ACTIVE ⇒\n * attach to the durable stream (reuse the M37 reconnect handler); IDLE ⇒ wait\n * (bounded) for the next run on the thread, then attach (subscribe-then-post).\n *\n * These DRIVE the SDK run (via `makeThreadStartRun`) + the M37 cache — no new loop.\n */\n\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport type { ApiKeyResolver } from './api-key-resolver.js'\nimport { makeThreadStartRun } from './build-agent-streamer.js'\nimport {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport { handleAgentRunReconnect } from './handle-agent-run-reconnect.js'\nimport { parseAgentRequestBody } from './mount-agent.js'\nimport { getRunEventCache, type RunEventCache } from './run-event-cache.js'\nimport { postThreadFollowUp } from './thread-dispatcher.js'\nimport { getThreadRunRegistry, type ThreadRunRegistry } from './thread-run-registry.js'\n\nconst THREAD_MESSAGE_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/message$/\nconst THREAD_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/stream$/\n\n/** How long a subscribe-to-idle-thread waits for the next run before closing. */\nconst DEFAULT_IDLE_WAIT_MS = 30_000\n\nfunction matchThread(re: RegExp, urlPath: string): { name: string; sessionId: string } | null {\n const m = re.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), sessionId: decodeURIComponent(m[2]) } : null\n}\n\nexport const isThreadMessagePath = (urlPath: string) => matchThread(THREAD_MESSAGE_PATH, urlPath)\nexport const isThreadStreamPath = (urlPath: string) => matchThread(THREAD_STREAM_PATH, urlPath)\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Inputs for {@link handleThreadMessage} (bundled to stay within the arity budget). */\ninterface ThreadMessageArgs {\n readonly mod: unknown\n /** theokit#328 — a resolver is passed through unresolved so the model can pick the provider. */\n readonly apiKey: string | ApiKeyResolver\n readonly sessionId: string\n readonly request: Request\n /** Labels a fail-fast `AgentDefinitionError`. Human-readable; never a telemetry key. */\n readonly source: string\n /**\n * The agent's name, as the scanner discovered it — the attribute an operator groups runs by.\n * Separate from {@link ThreadMessageArgs.source} since usetheokit/theokit#406: one field was\n * carrying both, and this route's `source` is the label `agent \"chat\"`.\n */\n readonly agentName: string\n readonly csrfMode?: CsrfMode\n}\n\n/** POST a follow-up on a thread. Returns `202` with `{ runId }` (started) or `{ queued: true }`. */\nexport async function handleThreadMessage(args: ThreadMessageArgs): Promise<Response> {\n const { mod, apiKey, sessionId, request, source, agentName, csrfMode = 'strict' } = args\n // A follow-up drives the agent (spends LLM tokens) — reject a cross-origin POST.\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → 400 below */\n }\n const input = parseAgentRequestBody(body)\n if (input === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request must contain a non-empty message.')\n }\n const result = postThreadFollowUp(\n {\n registry: getThreadRunRegistry(),\n cache: getRunEventCache(),\n // usetheokit/theokit#381 — the request goes with it, so the run's spans join the trace of\n // the caller that queued it instead of opening one of their own.\n startRun: makeThreadStartRun(mod, apiKey, source, agentName, request),\n },\n sessionId,\n input.message,\n )\n const headers: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' }\n if ('runId' in result) headers[RUN_ID_HEADER] = result.runId\n return new Response(JSON.stringify(result), { status: 202, headers })\n}\n\n/** GET the thread's durable stream. Active ⇒ attach now; idle ⇒ wait (bounded) for the next run. */\nexport function handleThreadStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry = getThreadRunRegistry(),\n cache: RunEventCache = getRunEventCache(),\n idleWaitMs = DEFAULT_IDLE_WAIT_MS,\n): Response {\n const active = registry.getActive(sessionId)\n if (active !== null && cache.has(active)) {\n // Reuse the M37 reconnect handler — replay + live tail on the active run.\n return handleAgentRunReconnect(active, request, cache)\n }\n return waitThenAttachStream(sessionId, request, registry, cache, idleWaitMs)\n}\n\n/** Subscribe to an idle thread: wait (bounded) for the NEXT run to start, then attach + tail. */\nfunction waitThenAttachStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry,\n cache: RunEventCache,\n idleWaitMs: number,\n): Response {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const send = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* closed by an abort race */\n }\n }\n let detachAttach: (() => void) | undefined\n const close = (): void => {\n if (closed) return\n send(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n const offNext = registry.onNextRun(sessionId, (runId) => {\n const res = cache.attach(\n runId,\n -1,\n (frame) => {\n send(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) send(formatSseFrame(frame.seq, frame.data))\n if (res.ended) {\n close()\n return\n }\n detachAttach = res.unsubscribe\n })\n // HIGH-1 — the waiter teardown MUST run on BOTH the idle-wait timeout AND the\n // client abort, else the (one-shot) `onNextRun` waiter leaks in the registry\n // when a timed-out subscriber's session never receives another run.\n const teardownWaiter = (): void => {\n offNext()\n detachAttach?.()\n }\n const timer = setTimeout(() => {\n teardownWaiter()\n close()\n }, idleWaitMs)\n timer.unref()\n request.signal.addEventListener('abort', () => {\n teardownWaiter()\n clearTimeout(timer)\n close()\n })\n },\n })\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS } })\n}\n","/**\n * M14 (theokit-ai-first) — GET /api/agents/<name>/approvals: list pending HITL approvals.\n *\n * Serves the approvals the CALLER owns, plus the ownerless ones, as JSON. Web Standards Response (G8).\n *\n * ## Why this is scoped, and what it closes\n *\n * The registry is process-wide by contract (ADR 0017): `list()` returns every pending approval, and\n * the `<name>` segment is accepted for a future per-agent store. That was the whole answer here, so\n * one admitted tenant of one agent received every pending approval in the process — other tenants',\n * other agents' — each with the `approvalId` the settle route needs.\n *\n * The draft advisory `GHSA-g94h-459g-rjhj` describes two steps: list without authentication, then\n * settle with an id from the listing. Both halves were closed around this file and neither in it —\n * `admitAux` refuses a caller the agent's policy does not admit (usetheokit/theokit#365), and\n * `approve-agent.ts` refuses a settle by a caller who is not the owner (B-016). The door was gated\n * and the window left open: an ADMITTED caller still read everyone's ids.\n *\n * ## An ownerless approval stays visible, deliberately\n *\n * The registry records an owner only for agents that DECLARE a policy — `admitAgentRequest` resolves\n * no subject for `'public'` or for an undeclared agent, so there is nothing to attribute. The settle\n * route already treats an absent owner as \"nothing to compare a caller against\" and refuses nobody\n * on it. Listing follows the same rule rather than inventing a second one, because hiding those\n * would blank a public agent's own approvals UI while protecting nobody.\n *\n * The filter asks `ownerOf` per approval rather than reading an owner off the listing, because\n * `owner` is held BESIDE `info` precisely so `list()` cannot leak it (B-016). Scoping the response\n * must not put the identity back into it.\n */\nimport type { ApprovalRegistry } from './approval-registry.js'\n\nconst LIST_PATH = /^\\/api\\/agents\\/([^/]+)\\/approvals$/\n\n/** Return the agent name when `urlPath` is the approvals-listing path, else `null`. */\nexport function isListApprovalsPath(urlPath: string): string | null {\n const match = LIST_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/**\n * Serve the pending approvals this caller may see as `{ approvals: [...], scope }` JSON.\n *\n * `scope` says how far the answer reaches — `'instance'` for the in-process registry this\n * framework ships, which is every answer it can currently give (B-236). It is present on every\n * response, empty or not.\n *\n * `subject` is the admitted caller's id, or `undefined` when the agent declares no policy and none\n * was resolved. An approval is included when it has no owner, or when its owner is this subject.\n */\nexport function handleListApprovals(\n registry: ApprovalRegistry,\n subject: string | undefined,\n): Response {\n const visible = registry.list().filter((approval) => {\n const owner = registry.ownerOf(approval.approvalId)\n return owner === undefined || owner === subject\n })\n // B-236 — every answer carries how far it reaches, including a non-empty one: a listing of two\n // from one instance can be two of five, so a caveat that appeared only when the list was empty\n // would vanish exactly when a caller starts trusting the numbers. Read from the registry, not\n // written here, so a shared implementation reports itself without this file changing.\n return new Response(JSON.stringify({ approvals: visible, scope: registry.scope ?? 'instance' }), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n","/**\n * M15/M16 follow-up — shared dispatcher for the agent AUXILIARY routes that BOTH dev (vite\n * middleware) and prod (`theokit start` handler) must serve identically. Before this, these routes\n * were wired only into the dev middleware, so a built/deployed app served none of them (agent cards,\n * MCP, pending-approvals listing all 404'd in production).\n *\n * Single source of truth (DRY): one Web-Request→Response dispatcher, two callers. It handles the\n * routes that derive purely from the agent module + shared registry:\n * - **M15** `GET /.well-known/<name>/agent-card.json` → {@link handleAgentCard}\n * - **M14** `GET /api/agents/<name>/approvals` → {@link handleListApprovals}\n * - **M16** `POST /api/agents/<name>/mcp` → {@link handleMcpJsonRpc}\n * - **M37** `GET /api/agents/<name>/runs/<id>/stream` → {@link handleAgentRunReconnect}\n * - **M39** the two thread routes → {@link handleThreadMessage} / {@link handleThreadStream}\n *\n * Channels (M27) are NOT here: a channel webhook needs app-supplied `validators` + `onMessage`, so\n * the app wires `handleChannelWebhook` in its own route (it cannot be auto-derived from the module).\n * The HITL approve route stays in each caller (it carries caller-specific rate-limiting/CSRF plumbing).\n *\n * ## Deciding and answering are two functions, and that is the fix\n *\n * This used to be one call that took a not-yet-converted request, decided whether it owned the path\n * and answered in the same breath. A caller could therefore learn \"this is an agent aux route\" only\n * by receiving the finished `Response` — too late to run anything around the handler. So the plugin\n * lifecycle, which every other branch of `theokit start` runs, was never run here: `onRequest`,\n * `onResponse` and `onError` fired for a file route and for the plain agent route and for none of\n * these six, and the observability plugin therefore emitted no `http.request` span for the endpoints\n * that spend tokens and settle human decisions (usetheokit/theokit#405).\n *\n * {@link matchAgentAuxRoute} decides; {@link serveMatchedAuxRoute} answers. A caller brackets the\n * gap with whatever the request lifecycle owes — and a seventh route added to the match table\n * inherits that bracket instead of having to remember it.\n */\nimport type { RouteSubject } from '../../core/contracts/route-policy.js'\nimport type { AgentNode } from '../scan/agent-scan.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport {\n AgentIdentityUnavailableError,\n admitAgentRequest,\n agentAccessDenied,\n readAgentPolicy,\n type AgentAccessParams,\n type AgentSubjectResolver,\n} from './agent-access.js'\nimport { isAgentCardPath, handleAgentCard } from './agent-card-handler.js'\nimport type { ApiKeyResolver } from './api-key-resolver.js'\nimport { getApprovalRegistry } from './approval-registry.js'\nimport { handleAgentRunReconnect, isAgentRunStreamPath } from './handle-agent-run-reconnect.js'\nimport {\n handleThreadMessage,\n handleThreadStream,\n isThreadMessagePath,\n isThreadStreamPath,\n} from './handle-thread-routes.js'\nimport { isListApprovalsPath, handleListApprovals } from './list-approvals-handler.js'\nimport { extractAppResources } from './mcp-app-resources.js'\nimport { isMcpPath, handleMcpJsonRpc } from './mcp-handler.js'\nimport { getRunEventCache } from './run-event-cache.js'\n\n/** JSON error envelope (mirrors mount-agent.ts:37 — the parity source for the MCP CSRF gate). */\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Dependencies the aux dispatcher needs from its caller (dev or prod). */\ninterface AuxRouteDeps {\n /** Discovered agents (from `scanAgents`). */\n agents: readonly AgentNode[]\n /** Load an agent module from its file path (dev: vite loader; prod: dynamic import). */\n loadModule: (filePath: string) => Promise<unknown>\n /** Absolute base URL (`http(s)://host`) for the agent-card endpoint URLs. */\n baseUrl: string\n /**\n * M34 (#97) — CSRF enforcement mode for the MCP route. `POST /api/agents/<name>/mcp` drives the\n * agent (spends LLM tokens), so a cross-origin POST MUST be rejected in `'strict'` — parity with\n * the agent-run route (`mount-agent.ts:83-91`). Defaults to `'strict'` (safe-by-default); a caller\n * that already gated upstream may pass `'off'`.\n */\n csrfMode?: CsrfMode\n /**\n * M39 — lazily resolve the provider apiKey. Required only for the thread\n * follow-up route (which drives the agent); resolved on demand so non-agent\n * aux routes (card, approvals, stream) never need a provider key.\n *\n * theokit#328 — it receives the model the agent declares, so the credential matches the provider\n * the agent asked for. It was called with no argument, before the module was even compiled, so\n * an agent declaring `anthropic/…` was handed whichever key env priority found first.\n */\n resolveApiKey?: ApiKeyResolver\n /**\n * Who is asking (usetheokit/theokit#365). Invoked ONLY from {@link serveMatchedAuxRoute}, and only\n * when the matched path's agent declares a policy — so the application's `createContext` never\n * runs for a url this dispatcher merely declines. {@link matchAgentAuxRoute} is not given it, for\n * the same reason it is not given the request body: deciding must cost nothing.\n */\n resolveSubject?: AgentSubjectResolver\n}\n\n/**\n * One aux route, already decided. Carries what the match resolved so the serve half re-derives\n * nothing: the agent node it looked up, and for MCP the module it had to open in order to answer\n * the opt-in question at all.\n */\nexport type AgentAuxRoute =\n | { readonly kind: 'card'; readonly agent: AgentNode }\n | { readonly kind: 'approvals'; readonly agent: AgentNode }\n | { readonly kind: 'run-stream'; readonly agent: AgentNode; readonly runId: string }\n | { readonly kind: 'thread-stream'; readonly agent: AgentNode; readonly sessionId: string }\n | { readonly kind: 'thread-message'; readonly agent: AgentNode; readonly sessionId: string }\n | { readonly kind: 'mcp'; readonly agent: AgentNode; readonly mod: unknown }\n\n/**\n * Resolve `name` to a discovered agent and build a route from it, or `null` when there is no name\n * (the path did not match) or no such agent (fall through to the caller's 404).\n *\n * Both misses collapse to `null` deliberately: every one of them means \"this dispatcher does not\n * answer this url\", and the path families below are mutually exclusive, so a family that declines\n * can safely let the next matcher look.\n */\nfunction routeFor<R>(\n deps: AuxRouteDeps,\n name: string | null,\n build: (agent: AgentNode) => R,\n): R | null {\n if (name === null) return null\n const agent = deps.agents.find((a) => a.name === name)\n return agent === undefined ? null : build(agent)\n}\n\n/** The GET-only aux routes: agent card, approvals listing, run stream, thread stream. */\nfunction matchGetAuxRoute(verb: string, urlPath: string, deps: AuxRouteDeps): AgentAuxRoute | null {\n if (verb !== 'GET') return null\n\n // M15 — A2A agent card at `/.well-known/<name>/agent-card.json`.\n const card = routeFor(\n deps,\n isAgentCardPath(urlPath),\n (agent) => ({ kind: 'card', agent }) as const,\n )\n if (card !== null) return card\n\n // M14 — the pending HITL approvals of one agent.\n const approvals = routeFor(\n deps,\n isListApprovalsPath(urlPath),\n (agent) => ({ kind: 'approvals', agent }) as const,\n )\n if (approvals !== null) return approvals\n\n // M37 — the durable run stream (`/runs/<runId>/stream`), reconnect or observe.\n const run = isAgentRunStreamPath(urlPath)\n if (run !== null) {\n return routeFor(\n deps,\n run.name,\n (agent) => ({ kind: 'run-stream', agent, runId: run.runId }) as const,\n )\n }\n\n // M39 — subscribe to a thread (`/threads/<sessionId>/stream`).\n const stream = isThreadStreamPath(urlPath)\n if (stream === null) return null\n return routeFor(\n deps,\n stream.name,\n (agent) => ({ kind: 'thread-stream', agent, sessionId: stream.sessionId }) as const,\n )\n}\n\n/** The POST-only aux routes: thread follow-up and MCP. */\nasync function matchPostAuxRoute(\n verb: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<AgentAuxRoute | null> {\n if (verb !== 'POST') return null\n\n // M39 — a follow-up message on a thread.\n const msg = isThreadMessagePath(urlPath)\n if (msg !== null) {\n return routeFor(\n deps,\n msg.name,\n (agent) => ({ kind: 'thread-message', agent, sessionId: msg.sessionId }) as const,\n )\n }\n\n // M16 — the JSON-RPC MCP server, behind the M34 opt-in.\n const agent = routeFor(deps, isMcpPath(urlPath), (found) => found)\n if (agent === null) return null\n // M34 — DEFAULT-DENY: an agent is NOT exposed on MCP unless it explicitly opts in with a named\n // `export const mcp = true` (blueprint D5 — default-EXPOSE is the footgun magnified by the\n // multi-surface thesis). Absent the opt-in, fall through to 404 (the agent is web-only). This is a\n // breaking change from the M16 auto-mount (documented in the CHANGELOG § Security).\n const mod = await deps.loadModule(agent.filePath)\n return isMcpExposed(mod) ? { kind: 'mcp', agent, mod } : null\n}\n\n/**\n * Does this dispatcher own `urlPath`? Returns the matched route, or `null` to fall through (not an\n * aux path, wrong method, unknown agent, or an agent that did not opt into MCP).\n *\n * theokit#400 — this function is where the \"convert only on a path you are about to answer\" rule\n * now lives, and it is enforced by the signature rather than by discipline: it is handed a method\n * and a url and has no request to convert. Converting in order to decide is what drained the Node\n * body stream on every path this dispatcher declined, so an ordinary `POST /api/…` file route then\n * waited forever for an `'end'` that had already fired — no status, no timeout, no response.\n *\n * The one branch that does real work here is MCP, which must open the module to read its\n * `export const mcp` opt-in. That is deliberate: a match that could still fall through would hand\n * the caller a request it had already started a lifecycle for, and the span opened for it would\n * either double-count or never close.\n */\nexport async function matchAgentAuxRoute(\n method: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<AgentAuxRoute | null> {\n const verb = method.toUpperCase()\n return matchGetAuxRoute(verb, urlPath, deps) ?? (await matchPostAuxRoute(verb, urlPath, deps))\n}\n\n/** What {@link admitAux} decided, and — when a policy declared one — who was admitted. */\ninterface Admission {\n readonly refusal: Response | null\n /** The admitted caller's id, or `undefined` when no policy asked for one. */\n readonly subject: string | undefined\n}\n\n/**\n * Evaluate the agent's declared policy for one aux endpoint.\n *\n * Returns the refusal `Response`, or `null` when the caller is admitted. Loading the module here is\n * what makes the gate reachable at all: the policy is an export of the agent file, and three of\n * these branches previously answered without ever opening it.\n */\nasync function admitAux(\n deps: AuxRouteDeps,\n agent: AgentNode,\n params: AgentAccessParams,\n body?: unknown,\n): Promise<Admission> {\n const mod = await deps.loadModule(agent.filePath)\n // The subject is RECORDED rather than resolved twice. `admitAgentRequest` returns before touching\n // the resolver when the policy is absent or `'public'`, which is the guarantee `resolveSubject`'s\n // own docblock makes: the application's `createContext` must not run for a url this dispatcher\n // merely declines. Wrapping preserves that exactly — `seen` stays `undefined` in those cases —\n // while the approvals branch gets the id it needs to scope its answer.\n const resolve = deps.resolveSubject\n // A box rather than a `let`: the assignment happens inside a closure the compiler cannot see as\n // reachable before the read, so a plain binding narrows to `never` and `seen?.id` stops compiling.\n const admitted: { subject: RouteSubject | null } = { subject: null }\n const recording: AgentSubjectResolver | undefined =\n resolve === undefined\n ? undefined\n : async () => {\n // B-254 — the APP's resolution is wrapped, not the whole admission. A policy that throws\n // is a different failure with a different cause, and tagging both the same way would hand\n // an operator one code for two problems.\n try {\n admitted.subject = await resolve()\n } catch (cause) {\n throw new AgentIdentityUnavailableError(cause)\n }\n return admitted.subject\n }\n let decision\n try {\n decision = await admitAgentRequest(\n readAgentPolicy(mod, agent.filePath),\n recording,\n params,\n body,\n )\n } catch (err) {\n // B-254 — only the identity failure is shaped here. Anything else keeps escaping exactly as it\n // did, because turning every throw on this path into a 500 would swallow the ones a caller\n // SHOULD see differently — `AgentPolicyTypeError` is a developer's mistake, not an outage.\n if (!(err instanceof AgentIdentityUnavailableError)) throw err\n console.error('[theokit] agent identity resolution failed', err)\n // Returned through `refusal`, which is this function's channel for \"answer with this Response\"\n // — the caller writes it out and never looks at `subject`. `subject: undefined` is the honest\n // value: nobody was identified, and it must not read as an anonymous caller who WAS.\n return {\n refusal: jsonError(\n 500,\n 'IDENTITY_UNAVAILABLE',\n 'The application could not resolve the caller. This is not a refusal: `createContext` in ' +\n 'server/context.ts threw, so there was no identity to judge. The server log carries the cause.',\n ),\n subject: undefined,\n }\n }\n const refusal = decision.allowed ? null : agentAccessDenied(decision, params)\n return { refusal, subject: admitted.subject?.id }\n}\n\n/**\n * Answer a route {@link matchAgentAuxRoute} already claimed. Always returns a `Response` — every\n * fall-through was decided upstream, which is what lets a caller open a request span before this\n * runs and be sure something will close it.\n */\nexport async function serveMatchedAuxRoute(\n route: AgentAuxRoute,\n request: Request,\n deps: AuxRouteDeps,\n): Promise<Response> {\n if (route.kind === 'card') {\n const mod = await deps.loadModule(route.agent.filePath)\n return handleAgentCard(mod, route.agent.name, route.agent.agentPath, deps.baseUrl)\n }\n\n // usetheokit/theokit#365 — the approvals listing used to answer 200 with every pending approval\n // id to anyone who asked, and the id is all the approve route needs to settle a paused tool.\n if (route.kind === 'approvals') {\n const admission = await admitAux(deps, route.agent, {\n agent: route.agent.name,\n endpoint: 'approvals',\n })\n if (admission.refusal !== null) return admission.refusal\n // SCOPED to this caller. `admitAux` answered \"may you touch this agent's approvals\"; it cannot\n // answer \"which of them are yours\", and the registry is process-wide by contract (ADR 0017).\n return handleListApprovals(getApprovalRegistry(), admission.subject)\n }\n\n // M37 — INTENTIONALLY open (no CSRF, no auth gate): a GET is not CSRF-vulnerable, the run-start\n // POST is already gated, and the `runId` is a 122-bit UUID minted BY THE SERVER (`mintRunId`) and\n // handed only to the caller that started the run — a capability the framework issued rather than\n // a name the caller chose. That is the property the thread and conversation keys lack, and it is\n // the whole of the difference. Observe-by-runId is a FEATURE (ADR-0046 D5). Do NOT add a\n // custom-header CSRF check here: browsers send NO custom headers with `EventSource`, so it would\n // break native SSE reconnect.\n if (route.kind === 'run-stream') {\n return handleAgentRunReconnect(route.runId, request, getRunEventCache())\n }\n\n if (route.kind === 'mcp') return serveMcpRoute(route, request, deps)\n\n return serveThreadRoute(route, request, deps)\n}\n\n/**\n * M39 — serve the thread routes:\n * - `POST .../threads/<sessionId>/message` (follow-up) — loads the module, drives\n * the run headless via the thread dispatcher. Needs `resolveApiKey` (drives the\n * agent) → 501 when absent (rather than a silent 404).\n * - `GET .../threads/<sessionId>/stream` (subscribe) — attach to the active/next\n * run's durable stream. INTENTIONALLY open (GET, no custom headers — like the\n * M37 reconnect route).\n *\n * SECURITY (thread stream): unlike the M37 reconnect route — keyed on an\n * `mintRunId()` UUID (122-bit unguessable) — the thread stream is keyed on the\n * caller-supplied `sessionId`, so an app using a PREDICTABLE sessionId (a user id,\n * an email, a tenant-derived key) is one guess away from another party reading the\n * thread's live conversation.\n *\n * usetheokit/theokit#365 — this paragraph used to end by telling the application it\n * \"MUST add its own auth gate before this endpoint\", and no such gate was constructible:\n * the URL is dispatched before route matching, so no `route()` and no middleware ever\n * saw it. The gate is the agent's own `export const policy`, evaluated here, and the\n * instruction is now one an application can follow.\n */\nasync function serveThreadRoute(\n route: Extract<AgentAuxRoute, { kind: 'thread-stream' | 'thread-message' }>,\n request: Request,\n deps: AuxRouteDeps,\n): Promise<Response> {\n const { agent, sessionId } = route\n\n if (route.kind === 'thread-stream') {\n const { refusal } = await admitAux(deps, agent, {\n agent: agent.name,\n endpoint: 'thread-stream',\n sessionId,\n })\n return refusal ?? handleThreadStream(sessionId, request)\n }\n\n const { refusal } = await admitAux(deps, agent, {\n agent: agent.name,\n endpoint: 'thread-message',\n sessionId,\n })\n if (refusal !== null) return refusal\n if (deps.resolveApiKey === undefined) {\n // MEDIUM-1 — the path matched but the caller wired no provider-key resolver.\n // Fail loudly (501) instead of a silent 404 that reads as \"route not found\".\n return jsonError(\n 501,\n 'NOT_CONFIGURED',\n 'Thread follow-up requires a provider API key (resolveApiKey was not provided to serveMatchedAuxRoute).',\n )\n }\n const mod = await deps.loadModule(agent.filePath)\n return handleThreadMessage({\n mod,\n // Passed unresolved: `makeThreadStartRun` calls it once the module is compiled and the\n // model is known (theokit#328).\n apiKey: deps.resolveApiKey,\n sessionId,\n request,\n source: `agent \"${agent.name}\"`,\n // usetheokit/theokit#406 — the label above reads well in an `AgentDefinitionError` and is not\n // a name; the spans get the name, so the same agent is one series whichever route started it.\n agentName: agent.name,\n csrfMode: deps.csrfMode ?? 'strict',\n })\n}\n\n/**\n * Serve the MCP route with the M34 gates. The opt-in check already ran in the match (it is what\n * decides ownership), so what is left here is: default-DENY policy → CSRF → dispatch.\n */\nasync function serveMcpRoute(\n route: Extract<AgentAuxRoute, { kind: 'mcp' }>,\n request: Request,\n deps: AuxRouteDeps,\n): Promise<Response> {\n const { agent, mod } = route\n\n // usetheokit/theokit#365 — the MCP route drives the agent and reaches its tools, so it answers to\n // the same declared policy as the run route.\n const mcpParams = { agent: agent.name, endpoint: 'mcp' as const }\n const mcpDecision = await admitAgentRequest(\n readAgentPolicy(mod, agent.filePath),\n deps.resolveSubject,\n mcpParams,\n )\n if (!mcpDecision.allowed) return agentAccessDenied(mcpDecision, mcpParams)\n\n // M34 (#97) — enforce CSRF BEFORE any work. The MCP route drives the agent (real LLM tokens), so a\n // cross-origin POST must be rejected — parity with the agent-run route (`mount-agent.ts:83-91`).\n const csrfMode = deps.csrfMode ?? 'strict'\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* malformed/empty JSON → handleMcpJsonRpc returns a -32600 envelope */\n }\n // M30 — pass the agent's declared `ui://` App resources (named `appResources` export) so the MCP\n // server advertises + serves them via resources/list + resources/read.\n return handleMcpJsonRpc(mod, agent.name, body, extractAppResources(mod))\n}\n\n/**\n * M34 — DEFAULT-DENY opt-in check: is this agent module exposed on the MCP surface? An agent opts in\n * with a named `export const mcp = true` (mirroring the `appResources` named-export convention).\n * Anything else (absent / falsy) → NOT exposed. Read at the emit layer (blueprint D5).\n */\nfunction isMcpExposed(mod: unknown): boolean {\n return (mod as { mcp?: unknown } | null | undefined)?.mcp === true\n}\n","/**\n * One bracket around a Node-dispatched request, so every agent branch has the same lifecycle\n * (theokit#324, usetheokit/theokit#405).\n *\n * ## Why this is a function and not a paragraph in a review checklist\n *\n * `executeRoute` and `executeAction` have run the plugin lifecycle since the beginning. The agent\n * branches did not, and they were fixed one at a time: theokit#324 taught the plain\n * `POST /api/agents/<name>` to call `applyDecorations` → `runOnRequest` → handler →\n * `runOnResponse`, with `runOnError` on the failure path, and copied that shape into the dev\n * middleware. The aux routes (thread message and stream, MCP, agent card, approvals listing) and the\n * HITL approve route kept answering without it, in BOTH surfaces, so an application embedding\n * TheoKit had no supported place to observe six endpoints — two of which spend tokens and one of\n * which settles a human decision. The observability plugin is the case that made it legible: no\n * `onRequest` means no `http.request` span, and an operator reading HTTP latency or error rate sees\n * no traffic for endpoints that are serving traffic (usetheokit/theokit#405).\n *\n * A copied bracket is what let five branches drift from one. This is the bracket, once.\n *\n * ## The conversion is here, and only here\n *\n * The lifecycle needs a Web `Request` (that is what `PluginContext` carries), and converting an\n * `IncomingMessage` drains its body exactly once — a second conversion yields a Request whose body\n * is an empty closed stream, which is a silent truncation (theokit#400). So callers hand over a\n * {@link WebRequestSource}, whose `toRequest()` memoizes, and hand the SAME source to the handler\n * they wrap. Converting is therefore idempotent across the bracket, by construction rather than by\n * anyone noticing.\n *\n * The caller must still only enter this bracket on a path it is about to answer: `toRequest()` runs\n * here, and running it to decide ownership is the theokit#400 hang.\n */\nimport type { ServerResponse } from 'node:http'\n\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\n\nimport type { WebRequestSource } from './node-request.js'\nimport { sendError } from './send-response.js'\n\n/** What the bracket needs from the branch it wraps. */\nexport interface PluginLifecycleTarget {\n /** The unconverted request. Converted once, here — see the module docstring. */\n source: WebRequestSource\n res: ServerResponse\n requestId: string\n /** Absent ⇒ no plugins are registered, and the bracket costs one object allocation. */\n pluginRunner: PluginRunner | undefined\n /** The 500 message when the handler (or the conversion) throws, e.g. `'Agent handler failed'`. */\n failureMessage: string\n}\n\nfunction messageOf(err: unknown, fallback: string): string {\n return err instanceof Error ? err.message : fallback\n}\n\n/**\n * Run `serve` inside the plugin lifecycle: decorations, `onRequest` (which may short-circuit),\n * the handler, `onError` on a throw, and `onResponse` after the response is written.\n *\n * Mirrors `executeRoute`'s shape deliberately — same `PluginContext`, same short-circuit contract,\n * same `onError` placement. An agent route should not have a lifecycle of its own.\n *\n * Never throws: a handler failure becomes a 500 through the same `sendError` envelope the branches\n * used before, so the caller's `logRequest` still reads a settled `res.statusCode`.\n */\nexport async function serveThroughPluginLifecycle(\n target: PluginLifecycleTarget,\n serve: (request: Request, pluginCtx: PluginContext) => Promise<void>,\n): Promise<void> {\n const { res, requestId, pluginRunner, failureMessage } = target\n\n let request: Request\n try {\n request = target.source.toRequest()\n } catch (err) {\n // A request the adapter cannot represent is a 500, exactly as it was before these branches grew\n // a lifecycle — the conversion used to sit inside the handler's own try.\n sendError(res, 'INTERNAL', messageOf(err, failureMessage), 500, undefined, requestId)\n return\n }\n\n const pluginCtx: PluginContext = { request, response: res, ctx: {}, requestId }\n\n if (pluginRunner) {\n pluginRunner.applyDecorations(pluginCtx.ctx)\n const onRequest = await pluginRunner.runOnRequest(pluginCtx)\n // A hook that answered the request stops the pipeline — the same guarantee `executeRoute` gives.\n if (onRequest.shortCircuited) return\n }\n\n try {\n await serve(request, pluginCtx)\n } catch (err) {\n if (pluginRunner) await pluginRunner.runOnError(pluginCtx, err)\n sendError(res, 'INTERNAL', messageOf(err, failureMessage), 500, undefined, requestId)\n }\n\n // After the response is written, as `executeRoute` does — a hook here observes a completed turn.\n if (pluginRunner) await pluginRunner.runOnResponse(pluginCtx)\n}\n","/**\n * Who is asking, on the Node dispatch path that serves the agent endpoints\n * (usetheokit/theokit#365).\n *\n * `executeRoute` answers this with `subjectFromContext(ctx)`, where `ctx` is the run context built\n * from the application's `server/context.ts` plus plugin decorations. The agent branches build no\n * such context — which is why `mountAgent`'s `subject` option had nowhere to come from and every\n * caller left it out. This builds the same context from the same two sources, so the agent surface\n * reads identity from the seam the routes already read it from rather than from a second one.\n *\n * ## Why it returns a resolver instead of a subject\n *\n * `tryServeAgentAux` runs for EVERY url, including the ones it does not own. Resolving eagerly\n * there would execute the application's `createContext` twice on every route request — once in the\n * aux branch that falls through, once in the route executor. So callers get a memoized thunk and\n * invoke it only on a path they are about to answer, which is the same discipline theokit#400\n * imposed on `source.toRequest()` for the same dispatcher.\n *\n * ## What `createContext` can read here, and what it cannot (usetheokit/theokit#415)\n *\n * **Headers and cookies: yes. The request body: no.**\n *\n * This used to state the opposite as a MUST — \"invoke it before converting the request to a Web\n * `Request`\" — and no caller could honour it. The laziness argued for directly above is what makes\n * it unsatisfiable: the invocation necessarily happens INSIDE the handler, and the handler is\n * entered after `serveThroughPluginLifecycle` has already called `source.toRequest()` at the top of\n * its bracket. `incomingMessageToWebRequest` attaches the Node readable as the request body\n * (`body: webStream, duplex: 'half'`), so by the time an application's `createContext` receives\n * that `IncomingMessage`, the stream is consumed.\n *\n * The contract was written for an EAGER resolver and kept when the resolver became lazy. Both\n * decisions were right on their own; the sentence joining them was not, and it pointed callers at\n * something impossible while implying a capability that does not exist.\n *\n * Practically this costs little — identity is overwhelmingly a header or a cookie, and both survive\n * the conversion untouched. What it costs an application that resolves identity from the BODY is an\n * empty read or a wait for an `'end'` that already fired, which is why saying so plainly matters\n * more than the frequency suggests.\n *\n * Restoring body access would mean resolving eagerly — running the application's `createContext`\n * twice on every route request, which is exactly what the laziness exists to prevent — or buffering\n * every agent request body to replay it, which is a cost paid by every caller for a case almost\n * none has.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { subjectFromContext, type RouteSubject } from '../../core/contracts/route-policy.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport type { LoadModule } from '../scan/module-loader.js'\n\nimport { createServerContext } from './middleware-runner.js'\n\n/** What {@link createAgentSubjectResolver} needs in order to build the run context. */\nexport interface AgentSubjectSources {\n req: IncomingMessage\n res: ServerResponse\n loadModule: LoadModule\n /** The app's `server/` directory. Absent ⇒ there is no `context.ts` to consult. */\n serverDir: string | undefined\n pluginRunner: PluginRunner | undefined\n}\n\n/**\n * Build a memoized resolver for the caller's identity.\n *\n * Decorations are applied ON TOP of the factory's result, matching `executeRoute`: a plugin\n * decoration wins only where `context.ts` did not set the same key.\n *\n * A `createContext` that throws is not swallowed — an application whose identity resolution is\n * broken must not be treated as an anonymous caller, because that reads as a clean refusal and\n * hides the fault. The throw reaches the branch's own error handler and becomes a 500.\n */\nexport function createAgentSubjectResolver(\n sources: AgentSubjectSources,\n): () => Promise<RouteSubject | null> {\n let pending: Promise<RouteSubject | null> | undefined\n return () => {\n pending ??= resolve(sources)\n return pending\n }\n}\n\nasync function resolve(sources: AgentSubjectSources): Promise<RouteSubject | null> {\n const { req, res, loadModule, serverDir, pluginRunner } = sources\n const produced =\n serverDir === undefined ? {} : await createServerContext(req, res, loadModule, serverDir)\n return subjectFrom(produced, pluginRunner)\n}\n\n/**\n * The app's `createContext`, as a host that is not Node sees it.\n *\n * Deliberately NOT `middleware-runner`'s `ContextFactory`, which types its argument as\n * `IncomingMessage`/`ServerResponse`. Those are exactly right for the dev path and wrong here: on\n * every deploy target the pair is what `createWebShim` synthesises over a Web `Request`. Widening\n * to `unknown` says what is actually true at this boundary rather than casting a lie past the\n * type system — the app's own `createContext` is typed by the app, and a generated fragment is the\n * one caller that cannot promise it Node objects.\n */\nexport type HostContextFactory = (args: { request: unknown; response: unknown }) => unknown\n\n/**\n * The half that CALLS an already-resolved context factory (B-185, ADR 0014).\n *\n * {@link createAgentSubjectResolver} does two things: it LOCATES `context.ts` on a filesystem —\n * `existsSync` plus `loadModule`, inside `createServerContext` — and then CALLS what it found. A\n * deploy target with no filesystem can do the second and not the first, so the generator bakes the\n * module as a static import (the way routes, agents and plugins already are) and hands the factory\n * here directly.\n *\n * Measured before this existed: passing `serverDir: undefined` to the resolver above takes its\n * `produced = {}` branch, never touches `req`/`res`/`loadModule`, and returns\n * `subjectFromContext({})` — which is null for every caller. Satisfying its types would have\n * satisfied nothing.\n *\n * `request`/`response` are whatever the host has. On every deploy target that is the\n * `ShimRequest`/`ShimResponse` pair `createWebShim` synthesises over a Web `Request`, which is the\n * same contract routes on those targets have crossed since they were baked.\n */\nexport function createSubjectResolverFromFactory(\n createContext: HostContextFactory | undefined,\n request: unknown,\n response: unknown,\n pluginRunner?: PluginRunner,\n): () => Promise<RouteSubject | null> {\n let pending: Promise<RouteSubject | null> | undefined\n return () => {\n pending ??= (async () =>\n subjectFrom(\n // An app with no `context.ts` bakes no factory, and an anonymous caller is the honest\n // answer — not an error, and not a subject invented to fill the slot.\n createContext === undefined ? {} : await createContext({ request, response }),\n pluginRunner,\n ))()\n return pending\n }\n}\n\n/**\n * Decorations are applied ON TOP of the factory's result, matching `executeRoute`. Shared by both\n * entries so the rule — and the deliberate non-swallowing of a throwing factory, which reaches the\n * branch's own error handler as a 500 rather than reading as a clean refusal — has one home.\n */\nfunction subjectFrom(\n produced: unknown,\n pluginRunner: PluginRunner | undefined,\n): RouteSubject | null {\n const ctx = (produced ?? {}) as Record<string, unknown>\n pluginRunner?.applyDecorations(ctx)\n return subjectFromContext(ctx)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,YAAY,eAAe;AACpC,SAAS,qBAAqB;AASvB,IAAM,mCAAN,cAA+C,MAAM;AAAA,EAC1D,YAAY,OAAe,WAAmB,QAAgB;AAC5D,UAAM,WAAW,KAAK,MAAM,SAAS,0BAA0B,MAAM,EAAE;AACvE,SAAK,OAAO;AAAA,EACd;AACF;AAQA,eAAsB,wBACpB,SACA,KACoB;AACpB,QAAM,WAAsB,CAAC;AAG7B,aAAW,CAAC,OAAO,KAAK,KAAK,QAAQ,QAAQ,GAAG;AAC9C,aAAS,KAAK,OAAO,UAAU,WAAW,MAAM,aAAa,OAAO,OAAO,GAAG,IAAI,KAAK;AAAA,EACzF;AACA,SAAO;AACT;AAEA,eAAe,aAAa,WAAmB,OAAe,KAA+B;AAC3F,QAAM,SAAS,W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