theokit 0.67.0 → 0.69.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/README.md +21 -0
- package/dist/{actions-virtual-module-YIWQTI6Q.js → actions-virtual-module-DH3N34I6.js} +6 -6
- package/dist/{actions-virtual-module-WCHXKH6R.js → actions-virtual-module-OMIFGXK6.js} +4 -4
- package/dist/adapters/agent-mount.d.ts +190 -2
- package/dist/adapters/agent-mount.js +18 -3
- package/dist/adapters/security-headers.d.ts +17 -1
- package/dist/adapters/security-headers.js +7 -0
- package/dist/adapters/security-headers.js.map +1 -1
- package/dist/{agent-C7F5O5V4.js → agent-7RPGAKTY.js} +3 -3
- package/dist/{app-typed-client-2ZEGNFJP.js → app-typed-client-C4LRUSIS.js} +6 -6
- package/dist/{app-typed-client-CUM2GZ5Y.js → app-typed-client-R6OUJZEE.js} +4 -4
- package/dist/assets-map-BMQASQHW.js +70 -0
- package/dist/assets-map-BMQASQHW.js.map +1 -0
- package/dist/assets-map-CV2YZ3MY.js +69 -0
- package/dist/assets-map-CV2YZ3MY.js.map +1 -0
- package/dist/{aws-lambda-R76PWR27.js → aws-lambda-OCJM5YGB.js} +35 -23
- package/dist/aws-lambda-OCJM5YGB.js.map +1 -0
- package/dist/{build-UNBI6VKC.js → build-CGFKWZ73.js} +13 -8
- package/dist/build-CGFKWZ73.js.map +1 -0
- package/dist/{bun-NPBIAWSU.js → bun-KRUAWYRW.js} +51 -39
- package/dist/bun-KRUAWYRW.js.map +1 -0
- package/dist/{chunk-GQNBZDYK.js → chunk-2FHNJ7LI.js} +1 -1
- package/dist/{chunk-GQNBZDYK.js.map → chunk-2FHNJ7LI.js.map} +1 -1
- package/dist/chunk-3T5XLDOH.js +807 -0
- package/dist/chunk-3T5XLDOH.js.map +1 -0
- package/dist/{chunk-WAYUHS54.js → chunk-425FJKKO.js} +5 -3
- package/dist/chunk-425FJKKO.js.map +1 -0
- package/dist/chunk-46FM5AFZ.js +44 -0
- package/dist/chunk-46FM5AFZ.js.map +1 -0
- package/dist/{chunk-ASBXR57P.js → chunk-4WB62S22.js} +7 -4
- package/dist/{chunk-ASBXR57P.js.map → chunk-4WB62S22.js.map} +1 -1
- package/dist/chunk-BDPD5HEO.js +554 -0
- package/dist/chunk-BDPD5HEO.js.map +1 -0
- package/dist/{chunk-UETVDZBE.js → chunk-BINRCILF.js} +4 -1
- package/dist/{chunk-UETVDZBE.js.map → chunk-BINRCILF.js.map} +1 -1
- package/dist/{chunk-EQCSUC65.js → chunk-BTDTHXUI.js} +2 -2
- package/dist/chunk-FFGP2LGQ.js +465 -0
- package/dist/chunk-FFGP2LGQ.js.map +1 -0
- package/dist/{chunk-PRZCPSUE.js → chunk-I2H6KRCQ.js} +29 -14
- package/dist/chunk-I2H6KRCQ.js.map +1 -0
- package/dist/{chunk-ENRT6DAU.js → chunk-IDWN2OSG.js} +15 -2
- package/dist/chunk-IDWN2OSG.js.map +1 -0
- package/dist/{chunk-GAJOZJWD.js → chunk-MOGTMGGA.js} +5 -2
- package/dist/chunk-MOGTMGGA.js.map +1 -0
- package/dist/{chunk-5VLP3GQ2.js → chunk-MS4A7N77.js} +1 -1
- package/dist/chunk-MS4A7N77.js.map +1 -0
- package/dist/{chunk-YNK7DW5V.js → chunk-QVXMAHZC.js} +55 -551
- package/dist/chunk-QVXMAHZC.js.map +1 -0
- package/dist/{chunk-B4Z7KIIU.js → chunk-SJ4AW54X.js} +45 -4
- package/dist/chunk-SJ4AW54X.js.map +1 -0
- package/dist/{chunk-5AGNZXHJ.js → chunk-SRJBH5E5.js} +16 -679
- package/dist/chunk-SRJBH5E5.js.map +1 -0
- package/dist/{chunk-GQIATJEG.js → chunk-T2LDLVVV.js} +28 -3
- package/dist/chunk-T2LDLVVV.js.map +1 -0
- package/dist/{chunk-UKMOQWUC.js → chunk-TJPENLGQ.js} +3 -3
- package/dist/chunk-V5SSTT3C.js +52 -0
- package/dist/chunk-V5SSTT3C.js.map +1 -0
- package/dist/chunk-XG6SQUEP.js +27 -0
- package/dist/chunk-XG6SQUEP.js.map +1 -0
- package/dist/cli/index.js +6 -6
- package/dist/client/index.d.ts +20 -0
- package/dist/client/index.js.map +1 -1
- package/dist/{cloudflare-2WVDBHCC.js → cloudflare-GK4VD3EU.js} +71 -21
- package/dist/cloudflare-GK4VD3EU.js.map +1 -0
- package/dist/{route-config-B7FaTSby.d.ts → define-middleware-BOHpPOBs.d.ts} +39 -1
- package/dist/{deno-deploy-BXOQ45LD.js → deno-deploy-WMNXRVGL.js} +37 -36
- package/dist/deno-deploy-WMNXRVGL.js.map +1 -0
- package/dist/{dev-GLUZNBNH.js → dev-72ISY3BP.js} +7 -7
- package/dist/{index-BdIaxp0c.d.ts → index-DZ_G5iY2.d.ts} +76 -5
- package/dist/index.js +7 -6
- package/dist/index.js.map +1 -1
- package/dist/{internal-api-3JIWUI3V.js → internal-api-CEZSXGRB.js} +4 -4
- package/dist/{internal-api-OK7FS2ZF.js → internal-api-XRIBUACB.js} +8 -7
- package/dist/match-DaKsL73w.d.ts +28 -0
- package/dist/{mcp-IPDFRK4S.js → mcp-S2AOB3RE.js} +3 -3
- package/dist/{match-Dw4CNXJH.d.ts → module-loader-DCip7NoL.d.ts} +1 -28
- package/dist/{netlify-LPJAPMQ2.js → netlify-VOL54SC7.js} +23 -20
- package/dist/netlify-VOL54SC7.js.map +1 -0
- package/dist/{observability-bootstrap-H4NSILXD.js → observability-bootstrap-YQKMEYW7.js} +2 -2
- package/dist/{preview-5ONGHDKY.js → preview-WA4HORUQ.js} +3 -3
- package/dist/registry-DDBXDHJ2.js +23 -0
- package/dist/server/cost/index.d.ts +14 -1
- package/dist/server/cost/index.js +1 -1
- package/dist/server/define/index.d.ts +2 -28
- package/dist/server/define/index.js +2 -3
- package/dist/server/http/index.d.ts +4 -3
- package/dist/server/http/index.js +13 -8
- package/dist/server/index.d.ts +6 -4
- package/dist/server/index.js +15 -10
- package/dist/server/index.js.map +1 -1
- package/dist/server/scan/index.d.ts +3 -2
- package/dist/{server-boundary-6PYWFYEL.js → server-boundary-S3G4CSNK.js} +4 -4
- package/dist/{server-boundary-CNYNVFT5.js → server-boundary-YN5HAICY.js} +6 -6
- package/dist/{start-UYBVPTSV.js → start-ZTMQLNJI.js} +39 -15
- package/dist/start-ZTMQLNJI.js.map +1 -0
- package/dist/{static-SVDWIOXJ.js → static-7OJNB7D2.js} +4 -4
- package/dist/{vercel-YUZADKGV.js → vercel-LZTDSDJF.js} +42 -28
- package/dist/vercel-LZTDSDJF.js.map +1 -0
- package/dist/vite-plugin/index.js +7 -6
- package/dist/{vite-plugin-ILWLTOKK.js → vite-plugin-Z7AJG3M2.js} +7 -7
- package/package.json +4 -4
- package/dist/aws-lambda-R76PWR27.js.map +0 -1
- package/dist/build-UNBI6VKC.js.map +0 -1
- package/dist/bun-NPBIAWSU.js.map +0 -1
- package/dist/chunk-5AGNZXHJ.js.map +0 -1
- package/dist/chunk-5VLP3GQ2.js.map +0 -1
- package/dist/chunk-6B3CMPE4.js +0 -192
- package/dist/chunk-6B3CMPE4.js.map +0 -1
- package/dist/chunk-B4Z7KIIU.js.map +0 -1
- package/dist/chunk-D4VP2QPR.js +0 -16
- package/dist/chunk-D4VP2QPR.js.map +0 -1
- package/dist/chunk-ENRT6DAU.js.map +0 -1
- package/dist/chunk-GAJOZJWD.js.map +0 -1
- package/dist/chunk-GQIATJEG.js.map +0 -1
- package/dist/chunk-O55RLSGG.js +0 -127
- package/dist/chunk-O55RLSGG.js.map +0 -1
- package/dist/chunk-PRZCPSUE.js.map +0 -1
- package/dist/chunk-WAYUHS54.js.map +0 -1
- package/dist/chunk-YNK7DW5V.js.map +0 -1
- package/dist/cloudflare-2WVDBHCC.js.map +0 -1
- package/dist/deno-deploy-BXOQ45LD.js.map +0 -1
- package/dist/netlify-LPJAPMQ2.js.map +0 -1
- package/dist/registry-E5XEUKG6.js +0 -23
- package/dist/start-UYBVPTSV.js.map +0 -1
- package/dist/vercel-YUZADKGV.js.map +0 -1
- /package/dist/{actions-virtual-module-YIWQTI6Q.js.map → actions-virtual-module-DH3N34I6.js.map} +0 -0
- /package/dist/{actions-virtual-module-WCHXKH6R.js.map → actions-virtual-module-OMIFGXK6.js.map} +0 -0
- /package/dist/{agent-C7F5O5V4.js.map → agent-7RPGAKTY.js.map} +0 -0
- /package/dist/{app-typed-client-2ZEGNFJP.js.map → app-typed-client-C4LRUSIS.js.map} +0 -0
- /package/dist/{app-typed-client-CUM2GZ5Y.js.map → app-typed-client-R6OUJZEE.js.map} +0 -0
- /package/dist/{chunk-EQCSUC65.js.map → chunk-BTDTHXUI.js.map} +0 -0
- /package/dist/{chunk-UKMOQWUC.js.map → chunk-TJPENLGQ.js.map} +0 -0
- /package/dist/{dev-GLUZNBNH.js.map → dev-72ISY3BP.js.map} +0 -0
- /package/dist/{internal-api-3JIWUI3V.js.map → internal-api-CEZSXGRB.js.map} +0 -0
- /package/dist/{internal-api-OK7FS2ZF.js.map → internal-api-XRIBUACB.js.map} +0 -0
- /package/dist/{mcp-IPDFRK4S.js.map → mcp-S2AOB3RE.js.map} +0 -0
- /package/dist/{observability-bootstrap-H4NSILXD.js.map → observability-bootstrap-YQKMEYW7.js.map} +0 -0
- /package/dist/{preview-5ONGHDKY.js.map → preview-WA4HORUQ.js.map} +0 -0
- /package/dist/{registry-E5XEUKG6.js.map → registry-DDBXDHJ2.js.map} +0 -0
- /package/dist/{server-boundary-6PYWFYEL.js.map → server-boundary-S3G4CSNK.js.map} +0 -0
- /package/dist/{server-boundary-CNYNVFT5.js.map → server-boundary-YN5HAICY.js.map} +0 -0
- /package/dist/{static-SVDWIOXJ.js.map → static-7OJNB7D2.js.map} +0 -0
- /package/dist/{vite-plugin-ILWLTOKK.js.map → vite-plugin-Z7AJG3M2.js.map} +0 -0
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "tsx/esm";
|
|
3
|
+
import {
|
|
4
|
+
buildSecurityHeaders
|
|
5
|
+
} from "./chunk-WSMLSIS5.js";
|
|
6
|
+
|
|
7
|
+
// src/adapters/deployed-agents.ts
|
|
8
|
+
var EMPTY = { imports: [], declarations: [], branch: [], hostBypass: "" };
|
|
9
|
+
var AUX_DEPS_PARITY = [
|
|
10
|
+
` ...CSRF_CONFIG,`,
|
|
11
|
+
` resolveApiKey: (model, plugins) => resolveProvider(model, { plugins }).apiKey,`
|
|
12
|
+
];
|
|
13
|
+
var AGENT_PREFIX = "/api/agents/";
|
|
14
|
+
var WELL_KNOWN_PREFIX = "/.well-known/";
|
|
15
|
+
function scannedFromLoaderCache(agentsDirLiteral2) {
|
|
16
|
+
return {
|
|
17
|
+
kind: "scan",
|
|
18
|
+
projectRoot: "cwd",
|
|
19
|
+
agentsDirLiteral: agentsDirLiteral2,
|
|
20
|
+
loadModule: "loaderCache",
|
|
21
|
+
serverDir: "serverDir",
|
|
22
|
+
ensureLoader: "if (!loaderCache) loaderCache = createProductionLoader()"
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
var JSON_NOT_FOUND_RESPONSE = `new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), { status: 404, headers: { 'content-type': 'application/json' } })`;
|
|
26
|
+
function deployedAgentsFragment(source, host = {}) {
|
|
27
|
+
if (source === void 0) return EMPTY;
|
|
28
|
+
if (source.kind === "baked" && source.agents.length === 0) return EMPTY;
|
|
29
|
+
const pathname = host.pathname ?? "url.pathname";
|
|
30
|
+
const notFound = host.notFound ?? "notFoundResponse()";
|
|
31
|
+
const prefix = host.importPrefix ?? "";
|
|
32
|
+
const resolution = source.kind === "baked" ? bakedResolution(source.agents, source.contextModule, host.pluginRunnerExpr) : scannedResolution({ ...source, pluginRunnerExpr: host.pluginRunnerExpr });
|
|
33
|
+
return {
|
|
34
|
+
hostBypass: ` && !__theoIsAgentCardPath(${pathname})`,
|
|
35
|
+
imports: [
|
|
36
|
+
// `theokit/adapters/agent-mount`, not `theokit/server`: `mount-agent` is deliberately not on
|
|
37
|
+
// the app-facing surface (ADR 0041), and a generated entry is not an app. See that module.
|
|
38
|
+
// B-185 — the identity entry differs by host: a filesystem host LOCATES its own
|
|
39
|
+
// `context.ts`, a Worker is handed the baked factory (ADR 0014). `createWebShim` is not here
|
|
40
|
+
// because all three entries already import it at module level.
|
|
41
|
+
`import { mountAgent, resolveProvider, matchAgentAuxRoute, serveMatchedAuxRoute${resolution.identityImport}${source.kind === "scan" ? ", scanAgents" : ""} } from '${prefix}theokit/adapters/agent-mount'`,
|
|
42
|
+
...resolution.imports
|
|
43
|
+
],
|
|
44
|
+
declarations: [
|
|
45
|
+
...resolution.declarations,
|
|
46
|
+
// SI-020 — the host's `/api/` guard decides between the API surface and static assets, and it
|
|
47
|
+
// runs BEFORE this branch. Widening the branch guard alone left the `.well-known` arm as dead
|
|
48
|
+
// code on all three targets: present in the source, unreachable in the emitted program. The
|
|
49
|
+
// host consults this predicate, so the card path escapes the asset branch and NOTHING else
|
|
50
|
+
// under `/.well-known/` does — a blanket prefix bypass would route `/.well-known/security.txt`
|
|
51
|
+
// away from assets, trading an unreachable card for a broken namespace.
|
|
52
|
+
//
|
|
53
|
+
// Same shape as `agent-card-handler.ts`'s own WELL_KNOWN. That is a COPY, not a shared
|
|
54
|
+
// definition, and saying otherwise was the claim an inventory judge falsified: changing the
|
|
55
|
+
// handler to serve `/agent.json` left every card test green, because this guard and that
|
|
56
|
+
// matcher are checked separately and never against each other. The drift that matters here —
|
|
57
|
+
// this guard narrowing while the matcher still serves the path — is caught by
|
|
58
|
+
// `a-deployed-worker-reaches-the-agent-card.test.ts`, which drives a real request. The other
|
|
59
|
+
// direction is not, and is the honest limit of this line.
|
|
60
|
+
String.raw`const __theoIsAgentCardPath = (p) => /^\/\.well-known\/[^/]+\/agent-card\.json$/.test(p)`,
|
|
61
|
+
// B-185 — one factory, two call sites: the aux branch on a hit, and the run handler below.
|
|
62
|
+
// Declared rather than inlined twice so the mechanism ADR 0014 decides has a single home.
|
|
63
|
+
// `async` because the entry's plugin runner is a promise: `createPluginRunnerFromConfig` is
|
|
64
|
+
// async, so the runtime-config fragment declares `const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(...)`
|
|
65
|
+
// WITHOUT awaiting it, and every consumer awaits at the point of use. `await` is a reserved
|
|
66
|
+
// word everywhere in an ES module, so a non-async factory carrying that binding does not
|
|
67
|
+
// merely misbehave -- the entry does not parse, and `tests/unit/adapter-entry-parses.test.ts`
|
|
68
|
+
// is where that is caught. It went red at HEAD before this line existed, on a first version
|
|
69
|
+
// of this fix whose own test asserted `toContain('await THEO_PLUGIN_RUNNER')`: the presence
|
|
70
|
+
// of the token that breaks the parse. That test file's header says why, in its own words --
|
|
71
|
+
// `toContain` does not care whether the string is a program.
|
|
72
|
+
//
|
|
73
|
+
// Laziness is unaffected. The shim was always built eagerly inside this factory; what ADR-1
|
|
74
|
+
// refuses is paying for a url nobody answers, and neither call site is reached by one.
|
|
75
|
+
`async function __theoResolveSubject(request) {`,
|
|
76
|
+
...resolution.identity,
|
|
77
|
+
` return resolveSubject`,
|
|
78
|
+
`}`
|
|
79
|
+
],
|
|
80
|
+
branch: [
|
|
81
|
+
` // #367 \u2014 the agent convention owns this prefix. It is answered BEFORE the file-route`,
|
|
82
|
+
` // table because an agent matches no file route: falling through is how a deployed`,
|
|
83
|
+
` // \`/api/agents/<name>\` used to 404 on every target.`,
|
|
84
|
+
` if (`,
|
|
85
|
+
` ${pathname}.startsWith(${JSON.stringify(AGENT_PREFIX)}) ||`,
|
|
86
|
+
` ${pathname}.startsWith(${JSON.stringify(WELL_KNOWN_PREFIX)})`,
|
|
87
|
+
` ) {`,
|
|
88
|
+
...resolution.auxPrelude,
|
|
89
|
+
` // B-185 \u2014 the aux dispatcher is asked FIRST, and declining costs nothing: the matcher`,
|
|
90
|
+
` // reads the url and the scanned nodes, never a module (ADR-1). A miss falls through to`,
|
|
91
|
+
` // the run handler exactly as before, so this branch owns the sub-paths and nothing more.`,
|
|
92
|
+
` const auxRoute = await matchAgentAuxRoute(request.method, ${pathname}, auxDeps)`,
|
|
93
|
+
` if (auxRoute !== null) {`,
|
|
94
|
+
` // B-185 \u2014 identity is resolved only now. Building it costs a web shim and, where the`,
|
|
95
|
+
` // app declares one, a call into its own \`createContext\`; a url this dispatcher`,
|
|
96
|
+
` // merely declined must pay for neither (resolve-agent-subject.ts:93-96).`,
|
|
97
|
+
` const auxResponse = await serveMatchedAuxRoute(auxRoute, request, {`,
|
|
98
|
+
` ...auxDeps,`,
|
|
99
|
+
` resolveSubject: await __theoResolveSubject(request),`,
|
|
100
|
+
` })`,
|
|
101
|
+
host.wrapSecurityHeaders === true ? ` return withSecurityHeaders(auxResponse, SECURITY_HEADERS)` : ` return auxResponse`,
|
|
102
|
+
` }`,
|
|
103
|
+
` // B-185 \u2014 only the agent prefix has a run handler behind it. A \`.well-known\` url the`,
|
|
104
|
+
` // dispatcher declined must NOT slice a prefix it does not carry: the name would be`,
|
|
105
|
+
` // garbage and mountAgent would answer 500 for what is a routing miss.`,
|
|
106
|
+
` if (!${pathname}.startsWith(${JSON.stringify(AGENT_PREFIX)})) return ${notFound}`,
|
|
107
|
+
` const agentName = ${pathname}.slice(${String(AGENT_PREFIX.length)}).split('/')[0]`,
|
|
108
|
+
...resolution.lookup,
|
|
109
|
+
` // A name nobody scanned is a 404, exactly like any other unknown path. Handing`,
|
|
110
|
+
` // \`undefined\` to mountAgent would surface as a 500 for what is a routing miss.`,
|
|
111
|
+
` if (mod === undefined) return ${notFound}`,
|
|
112
|
+
` const agentResponse = await mountAgent(mod, request, (model, plugins) => resolveProvider(model, { plugins }).apiKey, {`,
|
|
113
|
+
` agentName,`,
|
|
114
|
+
` // B-185 \u2014 mount-agent.ts:121 has accepted this since #365 and 0 of 23 adapters passed`,
|
|
115
|
+
` // one, so agent-access.ts:146 judged every deployed policy against \`subject: null\`.`,
|
|
116
|
+
` // A run is not a decline: it is about to do real work, so the shim this builds is not`,
|
|
117
|
+
` // the cost ADR-1 refuses.`,
|
|
118
|
+
` resolveSubject: await __theoResolveSubject(request),`,
|
|
119
|
+
` ...CSRF_CONFIG,`,
|
|
120
|
+
` })`,
|
|
121
|
+
host.wrapSecurityHeaders === true ? ` return withSecurityHeaders(agentResponse, SECURITY_HEADERS)` : ` return agentResponse`,
|
|
122
|
+
` }`
|
|
123
|
+
]
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function bakedResolution(agents, contextModule, pluginRunnerExpr) {
|
|
127
|
+
const varOf = (index) => `__theoAgent${String(index)}`;
|
|
128
|
+
return {
|
|
129
|
+
imports: [
|
|
130
|
+
...agents.map((agent, index) => `import * as ${varOf(index)} from '../../${agent.filePath}'`),
|
|
131
|
+
// B-185 — the app's context module, baked exactly like the agents above it (ADR 0014).
|
|
132
|
+
...contextModule === void 0 ? [] : [
|
|
133
|
+
// SI-022 — DYNAMIC, not a top-level static import. B-185 added this import; before it
|
|
134
|
+
// a Worker did not load the app's `server/context.ts` at all. A module-scope throw
|
|
135
|
+
// there — the commonest shape being a required-env-var check — then went from costing
|
|
136
|
+
// nothing to taking the ENTIRE target down: the import fails, the module never
|
|
137
|
+
// evaluates, and every route dies rather than only the one that wanted an identity.
|
|
138
|
+
//
|
|
139
|
+
// That is strictly worse than what `resolve-agent-subject.ts:69-72` promises. It says
|
|
140
|
+
// a throwing `createContext` reaches the branch's own error handler and becomes a 500,
|
|
141
|
+
// which is a failure scoped to the request that needed identity. A throw at IMPORT
|
|
142
|
+
// time reaches no handler at all.
|
|
143
|
+
//
|
|
144
|
+
// A relative `import()` is statically analysable, so wrangler bundles the module
|
|
145
|
+
// exactly as it bundled the static form — the reason ADR 0014 bakes it is unaffected.
|
|
146
|
+
// What changes is WHEN it evaluates, and therefore what a failure costs. It is only
|
|
147
|
+
// a real improvement if the import stays inside the thunk; see the factory below.
|
|
148
|
+
`const __theoContext = () => import('../../${contextModule}')`
|
|
149
|
+
]
|
|
150
|
+
],
|
|
151
|
+
declarations: [
|
|
152
|
+
`// #367 \u2014 the app's agents, keyed by NAME because that is what the URL carries, what the`,
|
|
153
|
+
`// access policy is judged under, and what the run's spans are labelled with (#406).`,
|
|
154
|
+
`const agents = {`,
|
|
155
|
+
...agents.map((agent, index) => ` ${JSON.stringify(agent.name)}: ${varOf(index)},`),
|
|
156
|
+
`}`,
|
|
157
|
+
`// B-185 \u2014 the node list the aux dispatcher matches a url against. There is deliberately NO`,
|
|
158
|
+
`// second table keyed by file path: \`test_the_table_is_keyed_by_agent_name_not_by_file_path\``,
|
|
159
|
+
`// forbids one, and the reason it gives is the right one \u2014 a path key makes a lookup depend on`,
|
|
160
|
+
`// the server's directory layout. The loader below reaches the module THROUGH this list, so the`,
|
|
161
|
+
`// layout appears once, here, and the module table above stays keyed by the name the URL, the`,
|
|
162
|
+
`// access policy and the run's spans all carry (#406).`,
|
|
163
|
+
`const agentNodes = [`,
|
|
164
|
+
...agents.map(
|
|
165
|
+
(agent) => ` { filePath: ${JSON.stringify(agent.filePath)}, agentPath: ${JSON.stringify(agent.agentPath)}, name: ${JSON.stringify(agent.name)} },`
|
|
166
|
+
),
|
|
167
|
+
`]`
|
|
168
|
+
],
|
|
169
|
+
lookup: [
|
|
170
|
+
` const mod = Object.prototype.hasOwnProperty.call(agents, agentName)`,
|
|
171
|
+
` ? agents[agentName]`,
|
|
172
|
+
` : undefined`
|
|
173
|
+
],
|
|
174
|
+
identityImport: contextModule === void 0 ? "" : ", createSubjectResolverFromFactory",
|
|
175
|
+
identity: contextModule === void 0 ? [
|
|
176
|
+
` // B-185 \u2014 this app declares no \`server/context.ts\`, so there is no factory to`,
|
|
177
|
+
` // bake and an anonymous caller is the honest answer. A policy that admits`,
|
|
178
|
+
` // nobody is the correct outcome, not an error.`,
|
|
179
|
+
` const resolveSubject = undefined`
|
|
180
|
+
] : [
|
|
181
|
+
` // B-185 \u2014 a Worker has no filesystem to find \`context.ts\` on, so the module is baked`,
|
|
182
|
+
` // and its factory handed straight to the resolver (ADR 0014).`,
|
|
183
|
+
` //`,
|
|
184
|
+
` // This function has TWO callers and is lazy on purpose. Both build a shim, and that is`,
|
|
185
|
+
` // correct at both: the aux branch calls it only AFTER a match, and the run handler is`,
|
|
186
|
+
` // about to do real work. What neither pays for is the app's own \`createContext\` on a`,
|
|
187
|
+
` // url nobody answers \u2014 the resolver is a thunk, and \`agent-access.ts:146\` returns early`,
|
|
188
|
+
` // for an absent or public policy without ever invoking it.`,
|
|
189
|
+
` const { req: __theoReq, res: __theoRes } = createWebShim(request)`,
|
|
190
|
+
` const resolveSubject = createSubjectResolverFromFactory(`,
|
|
191
|
+
// The import happens HERE, inside the factory, and `createSubjectResolverFromFactory`
|
|
192
|
+
// calls the factory inside the thunk it returns (`resolve-agent-subject.ts:127-133`).
|
|
193
|
+
// A first version of this fix awaited the import as an ARGUMENT, which evaluated it
|
|
194
|
+
// eagerly inside `__theoResolveSubject` — both call sites await that before
|
|
195
|
+
// `agent-access.ts:145` returns early for an absent or `'public'` policy. The blast
|
|
196
|
+
// radius was then every agent request rather than the one that wanted an identity,
|
|
197
|
+
// and the laziness invariant the lines above assert was broken. Found by the
|
|
198
|
+
// inventory judge while the change was still in the working tree.
|
|
199
|
+
` async (__theoArgs) => (await __theoContext()).createContext(__theoArgs),`,
|
|
200
|
+
` __theoReq,`,
|
|
201
|
+
` __theoRes,`,
|
|
202
|
+
` ${pluginRunnerExpr ?? "undefined"},`,
|
|
203
|
+
` )`
|
|
204
|
+
],
|
|
205
|
+
auxPrelude: [
|
|
206
|
+
` // B-185 \u2014 the aux dispatcher needs nodes carrying \`filePath\` and a loader keyed by it.`,
|
|
207
|
+
` // The loader resolves the path to a NAME through the node list, then reads the same`,
|
|
208
|
+
` // name-keyed table the url lookup uses: one map, one layout mention, no filesystem`,
|
|
209
|
+
` // (ADR-2). A linear find over a handful of agents is not worth a second table that`,
|
|
210
|
+
` // \`test_the_table_is_keyed_by_agent_name_not_by_file_path\` exists to forbid.`,
|
|
211
|
+
` const auxDeps = {`,
|
|
212
|
+
` agents: agentNodes,`,
|
|
213
|
+
` loadModule: async (filePath) => {`,
|
|
214
|
+
` const node = agentNodes.find((a) => a.filePath === filePath)`,
|
|
215
|
+
` return node === undefined ? undefined : agents[node.name]`,
|
|
216
|
+
` },`,
|
|
217
|
+
` baseUrl: url.origin,`,
|
|
218
|
+
...AUX_DEPS_PARITY,
|
|
219
|
+
` }`
|
|
220
|
+
]
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function scannedResolution(source) {
|
|
224
|
+
const agentsDirArg = source.agentsDirLiteral === void 0 ? "" : `, ${source.agentsDirLiteral}`;
|
|
225
|
+
return {
|
|
226
|
+
imports: [],
|
|
227
|
+
declarations: [
|
|
228
|
+
`// #367 \u2014 scanned on first use and cached, the same shape this entry already gives routes.`,
|
|
229
|
+
`// Baking would tie an agent's existence to a rebuild on a target that has a filesystem.`,
|
|
230
|
+
`let agentsCache = null`
|
|
231
|
+
],
|
|
232
|
+
lookup: [
|
|
233
|
+
` const agentNode = agentsCache.find((a) => a.name === agentName)`,
|
|
234
|
+
` const mod = agentNode === undefined ? undefined : await ${source.loadModule}(agentNode.filePath)`
|
|
235
|
+
],
|
|
236
|
+
identityImport: source.serverDir === void 0 ? "" : ", createAgentSubjectResolver",
|
|
237
|
+
identity: source.serverDir === void 0 ? [` const resolveSubject = undefined`] : [
|
|
238
|
+
` // B-185 \u2014 this host HAS a filesystem, so it locates its own \`context.ts\` and the`,
|
|
239
|
+
` // existing resolver works unchanged; nothing is baked (ADR 0014). Lazy for the reason`,
|
|
240
|
+
` // the baked branch gives: both callers build a shim, and neither runs the app's own`,
|
|
241
|
+
` // \`createContext\` for a url nobody answers.`,
|
|
242
|
+
` const { req: __theoReq, res: __theoRes } = createWebShim(request)`,
|
|
243
|
+
` const resolveSubject = createAgentSubjectResolver({`,
|
|
244
|
+
` req: __theoReq,`,
|
|
245
|
+
` res: __theoRes,`,
|
|
246
|
+
` loadModule: ${source.loadModule},`,
|
|
247
|
+
` serverDir: ${source.serverDir},`,
|
|
248
|
+
` pluginRunner: ${source.pluginRunnerExpr ?? "undefined"},`,
|
|
249
|
+
` })`
|
|
250
|
+
],
|
|
251
|
+
auxPrelude: [
|
|
252
|
+
...source.ensureLoader === void 0 ? [] : [` ${source.ensureLoader}`],
|
|
253
|
+
` // B-185 \u2014 hoisted above the lookup so a declined aux route loads no module. The scan`,
|
|
254
|
+
` // LISTS agent files; it imports none, so moving it here costs a declined request`,
|
|
255
|
+
` // nothing it was not already paying.`,
|
|
256
|
+
` if (!agentsCache) agentsCache = scanAgents(${source.projectRoot}${agentsDirArg})`,
|
|
257
|
+
` const auxDeps = {`,
|
|
258
|
+
` agents: agentsCache,`,
|
|
259
|
+
` loadModule: ${source.loadModule},`,
|
|
260
|
+
` baseUrl: url.origin,`,
|
|
261
|
+
...AUX_DEPS_PARITY,
|
|
262
|
+
` }`
|
|
263
|
+
]
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/adapters/deployed-cors.ts
|
|
268
|
+
var UnserializableCorsOriginError = class extends Error {
|
|
269
|
+
constructor(target) {
|
|
270
|
+
super(
|
|
271
|
+
`security.cors.origins is a function, and the \`${target}\` target cannot carry it: a deployed function has no theo.config.ts to read, and a callback cannot be written into the emitted entry. Replace it with the origin, a RegExp, or an array of either \u2014 all of which travel \u2014 or build for \`node\` and run \`theokit start\`, which evaluates the callback at runtime.`
|
|
272
|
+
);
|
|
273
|
+
this.name = "UnserializableCorsOriginError";
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
function renderOrigin(origin, target) {
|
|
277
|
+
if (typeof origin === "function") throw new UnserializableCorsOriginError(target);
|
|
278
|
+
if (origin instanceof RegExp) return String(origin);
|
|
279
|
+
if (Array.isArray(origin)) return `[${origin.map((o) => renderOrigin(o, target)).join(", ")}]`;
|
|
280
|
+
return JSON.stringify(origin);
|
|
281
|
+
}
|
|
282
|
+
function renderDeployedCorsLiteral(cors, target) {
|
|
283
|
+
if (cors === void 0) return "undefined";
|
|
284
|
+
const parts = [`origins: ${renderOrigin(cors.origins, target)}`];
|
|
285
|
+
if (cors.methods !== void 0) parts.push(`methods: ${JSON.stringify(cors.methods)}`);
|
|
286
|
+
if (cors.allowedHeaders !== void 0)
|
|
287
|
+
parts.push(`allowedHeaders: ${JSON.stringify(cors.allowedHeaders)}`);
|
|
288
|
+
if (cors.exposedHeaders !== void 0)
|
|
289
|
+
parts.push(`exposedHeaders: ${JSON.stringify(cors.exposedHeaders)}`);
|
|
290
|
+
parts.push(
|
|
291
|
+
`credentials: ${JSON.stringify(cors.credentials)}`,
|
|
292
|
+
`maxAge: ${JSON.stringify(cors.maxAge)}`
|
|
293
|
+
);
|
|
294
|
+
return `{ ${parts.join(", ")} }`;
|
|
295
|
+
}
|
|
296
|
+
function deployedCorsFragment(cors, target) {
|
|
297
|
+
return [
|
|
298
|
+
`// #409 \u2014 the CORS the app declared, carried as a literal because a deployed function has no`,
|
|
299
|
+
`// theo.config.ts to read. \`null\` when the app declared none: no headers, not permissive ones.`,
|
|
300
|
+
`const CORS_CONFIG = ${renderDeployedCorsLiteral(cors, target)}`,
|
|
301
|
+
`const CORS_HANDLER = CORS_CONFIG === undefined ? null : createCorsWebHandler(CORS_CONFIG)`,
|
|
302
|
+
``,
|
|
303
|
+
`/** Answer a preflight before routing \u2014 an OPTIONS the router handles never gets a CORS answer. */`,
|
|
304
|
+
`function corsPreflight(request) {`,
|
|
305
|
+
` return CORS_HANDLER === null ? null : CORS_HANDLER.handlePreflightRequest(request)`,
|
|
306
|
+
`}`,
|
|
307
|
+
``,
|
|
308
|
+
`/** Put the headers on whatever the app answered, including its 404s \u2014 a browser reads a 404`,
|
|
309
|
+
` * without them as a CORS failure rather than as the 404 it is. */`,
|
|
310
|
+
`function withCors(request, response) {`,
|
|
311
|
+
` if (CORS_HANDLER !== null) CORS_HANDLER.applyCorsHeaders(request, response.headers)`,
|
|
312
|
+
` return response`,
|
|
313
|
+
`}`
|
|
314
|
+
];
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/adapters/deployed-csrf.ts
|
|
318
|
+
function renderRoutePattern(pattern) {
|
|
319
|
+
return pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern);
|
|
320
|
+
}
|
|
321
|
+
function renderDeployedCsrfLiteral(security) {
|
|
322
|
+
if (security === void 0) return "{}";
|
|
323
|
+
const parts = [];
|
|
324
|
+
if (security.csrf !== void 0) parts.push(`csrfMode: ${JSON.stringify(security.csrf)}`);
|
|
325
|
+
const { disallowed } = security;
|
|
326
|
+
if (disallowed !== void 0) {
|
|
327
|
+
const routes = disallowed.routes.map(renderRoutePattern).join(", ");
|
|
328
|
+
parts.push(
|
|
329
|
+
`disallowed: { routes: [${routes}], behavior: ${JSON.stringify(disallowed.behavior)} }`
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
return parts.length === 0 ? "{}" : `{ ${parts.join(", ")} }`;
|
|
333
|
+
}
|
|
334
|
+
function deployedCsrfFragment(opts, home = "a deployed function") {
|
|
335
|
+
return [
|
|
336
|
+
`// #410 \u2014 the CSRF mode and per-route escalation the app declared. Carried as a`,
|
|
337
|
+
`// literal for the same reason as the headers above: ${home} has no theo.config.ts`,
|
|
338
|
+
`// to read. Absent keys stay absent so executeRoute's own default ('strict') applies,`,
|
|
339
|
+
`// rather than this file becoming a second place it can drift.`,
|
|
340
|
+
`const CSRF_CONFIG = ${renderDeployedCsrfLiteral(opts)}`
|
|
341
|
+
];
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/adapters/security-headers.ts
|
|
345
|
+
function securityHeadersDeclarations(config) {
|
|
346
|
+
return [
|
|
347
|
+
`const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(config)}`,
|
|
348
|
+
`const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`
|
|
349
|
+
];
|
|
350
|
+
}
|
|
351
|
+
function renderSecurityHeadersConfigLiteral(headers) {
|
|
352
|
+
return JSON.stringify(headers ?? {});
|
|
353
|
+
}
|
|
354
|
+
function describeDeployedSecurityHeaders(limits) {
|
|
355
|
+
const headers = buildSecurityHeaders(limits.securityHeaders ?? {}, { production: true });
|
|
356
|
+
const names = Object.keys(headers);
|
|
357
|
+
if (names.length === 0) {
|
|
358
|
+
return ` ! \`${limits.target}\` sends no security headers: the configuration switched every one of them off.`;
|
|
359
|
+
}
|
|
360
|
+
const lines = [
|
|
361
|
+
` \u2713 security headers on every response \`${limits.target}\` returns: ${names.join(", ")}.`
|
|
362
|
+
];
|
|
363
|
+
const sendsCsp = names.some((name) => name.startsWith("Content-Security-Policy"));
|
|
364
|
+
if (sendsCsp && !limits.mintsNonce) {
|
|
365
|
+
lines.push(
|
|
366
|
+
` - The CSP carries no nonce: this target serves HTML written at build time,`,
|
|
367
|
+
` so there is no per-request value to put on a script tag. An inline`,
|
|
368
|
+
` <script> is refused by \`script-src 'self'\` here, while the same page`,
|
|
369
|
+
` under \`theokit start\` gets a nonce and runs it. Move inline scripts to`,
|
|
370
|
+
` \`<script src="...">\`, or set \`security.headers.cspMode: 'report-only'\``,
|
|
371
|
+
` while you migrate.`
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
if (limits.documentHeaders === "platform-configured") {
|
|
375
|
+
lines.push(
|
|
376
|
+
` - The HTML document is served by the platform's static host, and reaches`,
|
|
377
|
+
` the browser with these headers through config this build emits. That`,
|
|
378
|
+
` path is not verified by a deploy from here \u2014 the values come from the`,
|
|
379
|
+
` same function the handler uses, but no response has been read back.`
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
if (limits.documentHeaders === "platform-unmanaged") {
|
|
383
|
+
lines.push(
|
|
384
|
+
` - The HTML document does NOT pass through this handler \u2014 the platform's`,
|
|
385
|
+
` static host serves it \u2014 so these headers reach \`/api/*\` responses and`,
|
|
386
|
+
` not the page. This build emits no artifact that could configure it, so`,
|
|
387
|
+
` set the document's headers on the platform (usetheokit/theokit#412).`
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
return lines.join("\n");
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// src/adapters/deployed-runtime-config.ts
|
|
394
|
+
function serverDirLiteral(opts) {
|
|
395
|
+
return JSON.stringify(opts.serverDir ?? "server");
|
|
396
|
+
}
|
|
397
|
+
function agentsDirLiteral(opts) {
|
|
398
|
+
return JSON.stringify(opts.agentsDir ?? "agents");
|
|
399
|
+
}
|
|
400
|
+
var EMPTY2 = {
|
|
401
|
+
imports: [],
|
|
402
|
+
declarations: [],
|
|
403
|
+
executeRouteSpread: ""
|
|
404
|
+
};
|
|
405
|
+
function deployedRuntimeConfigFragment(options) {
|
|
406
|
+
const pluginsModule = options?.runtimeConfigModule;
|
|
407
|
+
const serialization = options?.serialization === "superjson" ? "superjson" : void 0;
|
|
408
|
+
if (pluginsModule === void 0 && serialization === void 0) return EMPTY2;
|
|
409
|
+
const imports = [];
|
|
410
|
+
const declarations = [];
|
|
411
|
+
const spread = [];
|
|
412
|
+
if (pluginsModule !== void 0) {
|
|
413
|
+
imports.push(
|
|
414
|
+
`import { createPluginRunnerFromConfig } from 'theokit/server'`,
|
|
415
|
+
`// #425 \u2014 the app's own plugins, resolved on the build machine and written beside this entry.`,
|
|
416
|
+
`// A closure has no literal, so this is an import rather than a baked value.`,
|
|
417
|
+
`import theoRuntimeConfig from '${pluginsModule}'`
|
|
418
|
+
);
|
|
419
|
+
declarations.push(
|
|
420
|
+
`// Built ONCE, at module load. A runner rebuilt per request would re-run every plugin's`,
|
|
421
|
+
`// \`register\`, which is where a plugin allocates the state its hooks then read.`,
|
|
422
|
+
`const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(theoRuntimeConfig.plugins)`
|
|
423
|
+
);
|
|
424
|
+
spread.push(`pluginRunner: await THEO_PLUGIN_RUNNER`);
|
|
425
|
+
}
|
|
426
|
+
if (serialization !== void 0) {
|
|
427
|
+
imports.push(`import { resolveTransformer } from 'theokit/server'`);
|
|
428
|
+
declarations.push(
|
|
429
|
+
`// #425 \u2014 a literal, because \`config.serialization\` is a SELECTOR and not a transformer.`,
|
|
430
|
+
`// Same string, same function \`theokit start\` calls, so the deployed response and the local`,
|
|
431
|
+
`// one cannot disagree about what the app asked for \u2014 including the \`x-theo-transformer\``,
|
|
432
|
+
`// header, whose absence is what made this a data bug rather than a formatting one.`,
|
|
433
|
+
`const THEO_TRANSFORMER = resolveTransformer('${serialization}')`
|
|
434
|
+
);
|
|
435
|
+
spread.push(`transformer: THEO_TRANSFORMER`);
|
|
436
|
+
}
|
|
437
|
+
return { imports, declarations, executeRouteSpread: `${spread.join(", ")},` };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// src/adapters/deployed-trace.ts
|
|
441
|
+
function deployedTraceFragment(requestVar, indent) {
|
|
442
|
+
return [
|
|
443
|
+
`${indent}// #410 \u2014 honour the caller's trace id instead of minting a new one, and echo it.`,
|
|
444
|
+
`${indent}// \`extractTraceIdFromRequest\` validates the caller-controlled \`x-request-id\``,
|
|
445
|
+
`${indent}// before trusting it, and falls back to a fresh UUID when neither header is present.`,
|
|
446
|
+
`${indent}const requestId = extractTraceIdFromRequest(${requestVar})`,
|
|
447
|
+
`${indent}res.setHeader('x-request-id', requestId)`,
|
|
448
|
+
`${indent}res.setHeader(TRACE_HEADER, requestId)`
|
|
449
|
+
];
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export {
|
|
453
|
+
scannedFromLoaderCache,
|
|
454
|
+
JSON_NOT_FOUND_RESPONSE,
|
|
455
|
+
deployedAgentsFragment,
|
|
456
|
+
deployedCorsFragment,
|
|
457
|
+
deployedCsrfFragment,
|
|
458
|
+
securityHeadersDeclarations,
|
|
459
|
+
describeDeployedSecurityHeaders,
|
|
460
|
+
serverDirLiteral,
|
|
461
|
+
agentsDirLiteral,
|
|
462
|
+
deployedRuntimeConfigFragment,
|
|
463
|
+
deployedTraceFragment
|
|
464
|
+
};
|
|
465
|
+
//# sourceMappingURL=chunk-FFGP2LGQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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-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 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,WA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