theokit 0.50.2 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action-protocol-tGm3NKRg.d.ts +170 -0
- package/dist/{actions-virtual-module-2STC6RV3.js → actions-virtual-module-SNG4JC35.js} +6 -6
- package/dist/{actions-virtual-module-ESKVARP4.js → actions-virtual-module-VJYKUIXE.js} +6 -5
- package/dist/actions-virtual-module-VJYKUIXE.js.map +1 -0
- package/dist/adapters/agent-mount.js +1 -1
- package/dist/{agent-7RP3VTSI.js → agent-AHGYRVQX.js} +4 -4
- package/dist/{app-typed-client-NYZ2PLNC.js → app-typed-client-FQVMEG4Z.js} +6 -6
- package/dist/{app-typed-client-CEW2KGXR.js → app-typed-client-ZZIASI4A.js} +6 -5
- package/dist/app-typed-client-ZZIASI4A.js.map +1 -0
- package/dist/{build-4LPUE2H3.js → build-3AYYQZGQ.js} +6 -6
- package/dist/{chunk-MLWETKFA.js → chunk-2E7JLV7L.js} +2 -2
- package/dist/{chunk-5K7WIT3Z.js → chunk-5BOKW3GX.js} +5 -172
- package/dist/chunk-5BOKW3GX.js.map +1 -0
- package/dist/{chunk-EVZKNA2W.js → chunk-6AM7HIRM.js} +2 -2
- package/dist/{chunk-QNGS7EVS.js → chunk-E53UIFH6.js} +2 -2
- package/dist/chunk-E53UIFH6.js.map +1 -0
- package/dist/{chunk-ECTUUAMR.js → chunk-I4ELCXNV.js} +10 -10
- package/dist/{chunk-L4VFNFDL.js → chunk-IRASEXOG.js} +29 -1
- package/dist/{chunk-L4VFNFDL.js.map → chunk-IRASEXOG.js.map} +1 -1
- package/dist/{chunk-LLMTORUY.js → chunk-MBFD6NHB.js} +10 -10
- package/dist/{chunk-3MIGBPTW.js → chunk-PFAVZL4F.js} +3 -3
- package/dist/{chunk-IQRL5KZL.js → chunk-VGE6AKEJ.js} +2 -2
- package/dist/{chunk-6J4JWHDJ.js → chunk-VHB2FSPM.js} +16 -2
- package/dist/chunk-VHB2FSPM.js.map +1 -0
- package/dist/{chunk-KUZVRJ7M.js → chunk-XLLW46MB.js} +3 -3
- package/dist/{chunk-XS7EX55U.js → chunk-YYOBMOO4.js} +16 -2
- package/dist/chunk-YYOBMOO4.js.map +1 -0
- package/dist/{chunk-DVYILYM6.js → chunk-YZCD3DWE.js} +2 -2
- package/dist/{chunk-FD4ZDTQ6.js → chunk-Z7CJHDLS.js} +29 -1
- package/dist/{chunk-FD4ZDTQ6.js.map → chunk-Z7CJHDLS.js.map} +1 -1
- package/dist/chunk-ZDUO4IYN.js +174 -0
- package/dist/chunk-ZDUO4IYN.js.map +1 -0
- package/dist/cli/index.js +8 -8
- package/dist/client/index.d.ts +117 -1
- package/dist/client/index.js +144 -3
- package/dist/client/index.js.map +1 -1
- package/dist/{dev-Z4YLROZD.js → dev-W7OXHMSP.js} +8 -8
- package/dist/{dev-emit-MVAJAFGX.js → dev-emit-G2E2U3NP.js} +3 -3
- package/dist/{dev-emit-BFNMDCPB.js → dev-emit-SPSV6UU7.js} +5 -5
- package/dist/{index-B_Pk2JXn.d.ts → index-C8YN9dpF.d.ts} +3 -165
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/{internal-api-53L6FIQ2.js → internal-api-EL25ADPR.js} +6 -6
- package/dist/{internal-api-IXSWWH2N.js → internal-api-S6BGJCZP.js} +6 -5
- package/dist/{mcp-RKD4QQFS.js → mcp-7BXBN7PD.js} +4 -4
- package/dist/{openapi-VFPEZSRI.js → openapi-2IBBOS3Q.js} +5 -5
- package/dist/{preview-LB3YL6U5.js → preview-4ZTFJG2D.js} +3 -3
- package/dist/{routes-BPLU3ISV.js → routes-PP5PHHLR.js} +3 -3
- package/dist/server/http/index.d.ts +2 -1
- package/dist/server/http/index.js +9 -7
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +11 -9
- package/dist/server/index.js.map +1 -1
- package/dist/server/scan/index.js +2 -2
- package/dist/{server-boundary-ACFCBLZ4.js → server-boundary-RNM25WWD.js} +6 -6
- package/dist/{server-boundary-RBMMPWCV.js → server-boundary-XRXVVUMO.js} +6 -5
- package/dist/server-boundary-XRXVVUMO.js.map +1 -0
- package/dist/{start-G2JS6422.js → start-WILEDDW2.js} +7 -7
- package/dist/vite-plugin/index.js +6 -5
- package/dist/{vite-plugin-4VM5EUQL.js → vite-plugin-2XM35VNV.js} +8 -8
- package/package.json +1 -1
- package/dist/actions-virtual-module-ESKVARP4.js.map +0 -1
- package/dist/app-typed-client-CEW2KGXR.js.map +0 -1
- package/dist/chunk-5K7WIT3Z.js.map +0 -1
- package/dist/chunk-6J4JWHDJ.js.map +0 -1
- package/dist/chunk-QNGS7EVS.js.map +0 -1
- package/dist/chunk-XS7EX55U.js.map +0 -1
- package/dist/server-boundary-RBMMPWCV.js.map +0 -1
- /package/dist/{actions-virtual-module-2STC6RV3.js.map → actions-virtual-module-SNG4JC35.js.map} +0 -0
- /package/dist/{agent-7RP3VTSI.js.map → agent-AHGYRVQX.js.map} +0 -0
- /package/dist/{app-typed-client-NYZ2PLNC.js.map → app-typed-client-FQVMEG4Z.js.map} +0 -0
- /package/dist/{build-4LPUE2H3.js.map → build-3AYYQZGQ.js.map} +0 -0
- /package/dist/{chunk-MLWETKFA.js.map → chunk-2E7JLV7L.js.map} +0 -0
- /package/dist/{chunk-EVZKNA2W.js.map → chunk-6AM7HIRM.js.map} +0 -0
- /package/dist/{chunk-ECTUUAMR.js.map → chunk-I4ELCXNV.js.map} +0 -0
- /package/dist/{chunk-LLMTORUY.js.map → chunk-MBFD6NHB.js.map} +0 -0
- /package/dist/{chunk-3MIGBPTW.js.map → chunk-PFAVZL4F.js.map} +0 -0
- /package/dist/{chunk-IQRL5KZL.js.map → chunk-VGE6AKEJ.js.map} +0 -0
- /package/dist/{chunk-KUZVRJ7M.js.map → chunk-XLLW46MB.js.map} +0 -0
- /package/dist/{chunk-DVYILYM6.js.map → chunk-YZCD3DWE.js.map} +0 -0
- /package/dist/{dev-Z4YLROZD.js.map → dev-W7OXHMSP.js.map} +0 -0
- /package/dist/{dev-emit-MVAJAFGX.js.map → dev-emit-G2E2U3NP.js.map} +0 -0
- /package/dist/{dev-emit-BFNMDCPB.js.map → dev-emit-SPSV6UU7.js.map} +0 -0
- /package/dist/{internal-api-53L6FIQ2.js.map → internal-api-EL25ADPR.js.map} +0 -0
- /package/dist/{internal-api-IXSWWH2N.js.map → internal-api-S6BGJCZP.js.map} +0 -0
- /package/dist/{mcp-RKD4QQFS.js.map → mcp-7BXBN7PD.js.map} +0 -0
- /package/dist/{openapi-VFPEZSRI.js.map → openapi-2IBBOS3Q.js.map} +0 -0
- /package/dist/{preview-LB3YL6U5.js.map → preview-4ZTFJG2D.js.map} +0 -0
- /package/dist/{routes-BPLU3ISV.js.map → routes-PP5PHHLR.js.map} +0 -0
- /package/dist/{server-boundary-ACFCBLZ4.js.map → server-boundary-RNM25WWD.js.map} +0 -0
- /package/dist/{start-G2JS6422.js.map → start-WILEDDW2.js.map} +0 -0
- /package/dist/{vite-plugin-4VM5EUQL.js.map → vite-plugin-2XM35VNV.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/contracts/action-protocol.ts","../src/core/contracts/auth-error-guard.ts","../src/core/contracts/route-policy.ts","../src/server/jobs/duplicate-context-key-error.ts","../src/server/jobs/outbox.ts","../src/server/jobs/queue-client.ts","../src/server/http/execute-stages.ts","../src/server/http/middleware-runner.ts","../src/server/define/define-middleware.ts","../src/server/scan/middleware-scan.ts","../src/core/contracts/envelope-code-to-status.ts","../src/server/http/node-web-adapter.ts","../src/server/http/execute.ts","../src/server/http/form-data-to-object.ts","../src/server/http/handle-request-error.ts","../src/server/http/serialize-action-result.ts","../src/server/http/action-execute.ts","../src/server/http/batch-handler.ts","../src/server/http/cors.ts","../src/server/observability/suggest.ts","../src/server/plugins/plugin-runner.ts","../src/server/plugins/load-plugins.ts","../src/server/rate-limit/rate-limit-store.ts","../src/server/rate-limit/rate-limit.ts","../src/server/agent/mount-agent.ts","../src/server/agent/agent-access.ts","../src/server/agent/build-agent-streamer.ts","../src/server/agent/hitl-pause-spans.ts","../src/server/agent/observe-agent-run.ts","../src/server/agent/observe-served-run.ts","../src/server/agent/durable-ui-message-stream-response.ts","../src/server/agent/run-event-cache.ts","../src/server/scan/module-loader.ts","../src/server/security/csp-report.ts","../src/server/security/csrf-readiness-endpoint.ts","../src/server/security/csrf-readiness-store.ts","../src/server/security/security-headers.ts"],"sourcesContent":["/**\n * Action protocol — cross-boundary contract for `defineAction` + `useAction`.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 0 / T0.1, ADRs D1 (encoding)\n * + D6 (full dot-notation path) + D7 (PII mask) — types and runtime referenced\n * by server (`server/http/action-execute.ts`, `server/define/define-action.ts`)\n * and client (`client/use-action.ts`, `vite-plugin/actions-virtual-module`).\n *\n * That client pointer named `@theokit/react/useAction` until #453 — a package published outside\n * this repository, with one version and a `@theokit/sdk ^1.1.0` peer against a published 4.x. The\n * hook lives beside the contract now, in `theokit/client`.\n *\n * Lives in `core/contracts/` per architecture.md v3.1 exception — cross-module\n * deep imports ALLOWED for this file. Core depends on NOTHING intra-monorepo;\n * `extractUniversalIssues` is implemented INLINE (NOT imported from `@theokit/sdk`)\n * to honor dep-cruiser `core-depends-on-nothing` invariant (EC-1 absorbed).\n *\n * Field-key convention (D6 + EC-13): dot-notation full path. Nested objects use\n * `'user.address.zip'`; array indices use `'items.0.name'` (NOT bracket\n * `'items[0].name'`). Root-level errors (path = []) use empty string `''`\n * (EC-7). Consumers needing bracket notation can write a small `dotToBracket`\n * helper in userland.\n */\n\nimport type { TheoErrorCode, TheoErrorEnvelope, ValidationFieldsExt } from './error-envelope.js'\n\n/**\n * HTTP-status mapping per IANA HTTP Status Code Registry (subset relevant to\n * action surface). VALIDATION_ERROR → 422 is preferred over Astro's BAD_REQUEST/400\n * (more semantic for input-shape mismatch). PAYLOAD_TOO_LARGE → 413 covers EC-3\n * (response-side size limit; request-side reuses standard 413).\n */\nexport type ActionErrorCode =\n | 'VALIDATION_ERROR'\n | 'BAD_REQUEST'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'NOT_FOUND'\n | 'METHOD_NOT_ALLOWED'\n | 'CONFLICT'\n | 'CONTENT_TOO_LARGE'\n | 'PAYLOAD_TOO_LARGE'\n | 'UNSUPPORTED_MEDIA_TYPE'\n | 'TOO_MANY_REQUESTS'\n | 'INTERNAL_SERVER_ERROR'\n\nconst CODE_TO_STATUS: Record<ActionErrorCode, number> = {\n VALIDATION_ERROR: 422,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n CONFLICT: 409,\n CONTENT_TOO_LARGE: 413,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n TOO_MANY_REQUESTS: 429,\n INTERNAL_SERVER_ERROR: 500,\n}\n\nconst STATUS_TO_CODE: Record<number, ActionErrorCode> = {\n 400: 'BAD_REQUEST',\n 401: 'UNAUTHORIZED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 405: 'METHOD_NOT_ALLOWED',\n 409: 'CONFLICT',\n 413: 'PAYLOAD_TOO_LARGE',\n 415: 'UNSUPPORTED_MEDIA_TYPE',\n 422: 'VALIDATION_ERROR',\n 429: 'TOO_MANY_REQUESTS',\n 500: 'INTERNAL_SERVER_ERROR',\n}\n\n/**\n * Universal zod issue shape covering BOTH v3 (`z.ZodIssue`) and v4 (`$ZodIssue`).\n * Duck-typed minimum surface: `{path, message}`. Implemented per EC-1 absorbed —\n * consumers chain may ship either zod major; constructor accepts `unknown` and\n * normalizes via `extractUniversalIssues`.\n */\nexport interface UniversalZodIssue {\n readonly path: readonly (string | number)[]\n readonly message: string\n readonly code?: string\n}\n\n/**\n * `ActionError` — general server-side action failure. Discriminator `type` is\n * literal `'TheoActionError'`; used by `ActionError.fromJson` to distinguish\n * from `ActionInputError`.\n */\nexport class ActionError extends Error {\n // Discriminator widened to the full union so subclasses can narrow to their\n // specific literal (TypeScript would otherwise reject the override). Concrete\n // values are still always exact literals at runtime.\n readonly type: 'TheoActionError' | 'TheoActionInputError' = 'TheoActionError'\n readonly code: ActionErrorCode\n readonly status: number\n\n constructor(params: { code: ActionErrorCode; message?: string; stack?: string }) {\n super(params.message ?? params.code)\n this.code = params.code\n this.status = ActionError.codeToStatus(params.code)\n if (params.stack) {\n this.stack = params.stack\n }\n }\n\n /**\n * G5 T2.4 — canonical envelope view of the action error. Maps the G3\n * ActionErrorCode to a canonical TheoErrorCode (VALIDATION_ERROR ↔\n * UNPROCESSABLE_ENTITY, CONTENT_TOO_LARGE ↔ PAYLOAD_TOO_LARGE) so consumer\n * UI / SDK code can switch on the unified envelope.\n *\n * Subclasses override to populate `ext` (see `ActionInputError.envelope`).\n */\n get envelope(): TheoErrorEnvelope {\n return {\n code: ActionError.toTheoErrorCode(this.code),\n message: this.message,\n }\n }\n\n /**\n * Translate G3 ActionErrorCode → canonical TheoErrorCode (blueprint\n * Recommendations § \"G3 ActionError becomes inaugural envelope user\").\n */\n static toTheoErrorCode(code: ActionErrorCode): TheoErrorCode {\n if (code === 'VALIDATION_ERROR') return 'UNPROCESSABLE_ENTITY'\n if (code === 'CONTENT_TOO_LARGE') return 'PAYLOAD_TOO_LARGE'\n // The other ActionErrorCode members (BAD_REQUEST/UNAUTHORIZED/FORBIDDEN/\n // NOT_FOUND/METHOD_NOT_ALLOWED/CONFLICT/PAYLOAD_TOO_LARGE/\n // UNSUPPORTED_MEDIA_TYPE/TOO_MANY_REQUESTS/INTERNAL_SERVER_ERROR) are\n // identical strings in TheoErrorCode. Narrow via a type predicate\n // instead of assertion.\n return code\n }\n\n static codeToStatus(code: ActionErrorCode): number {\n return CODE_TO_STATUS[code]\n }\n\n static statusToCode(status: number): ActionErrorCode {\n return STATUS_TO_CODE[status] ?? 'INTERNAL_SERVER_ERROR'\n }\n\n /**\n * Parse a serialized error JSON back into the typed class hierarchy.\n * Distinguishes `TheoActionInputError` (with `issues` array) from\n * `TheoActionError` via the `type` discriminator. Falls back to\n * `INTERNAL_SERVER_ERROR` for malformed bodies (non-object, missing\n * `type`, unknown `code`).\n */\n static fromJson(body: unknown): ActionError {\n if (typeof body !== 'object' || body === null) {\n return new ActionError({ code: 'INTERNAL_SERVER_ERROR' })\n }\n const obj = body as Record<string, unknown>\n if (obj.type === 'TheoActionInputError' && Array.isArray(obj.issues)) {\n return new ActionInputError(obj.issues as unknown[])\n }\n if (\n obj.type === 'TheoActionError' &&\n typeof obj.code === 'string' &&\n obj.code in CODE_TO_STATUS\n ) {\n return new ActionError({\n code: obj.code as ActionErrorCode,\n message: typeof obj.message === 'string' ? obj.message : undefined,\n })\n }\n return new ActionError({ code: 'INTERNAL_SERVER_ERROR' })\n }\n}\n\n/**\n * `ActionInputError` — validation failure with field-level mapping.\n *\n * `fields` is auto-derived from `issues`: for each issue, key = full\n * dot-notation path (`'user.address.zip'`; root-level `path:[]` → `''`;\n * array indices as numeric segments → `'items.0.name'`). Multiple messages\n * for the same key accumulate; duplicate (path, message) tuples are deduped.\n */\nexport class ActionInputError extends ActionError {\n override readonly type = 'TheoActionInputError' as const\n readonly issues: readonly UniversalZodIssue[]\n readonly fields: Record<string, string[]>\n\n constructor(rawIssues: unknown) {\n super({ code: 'VALIDATION_ERROR', message: 'Validation failed' })\n this.issues = extractUniversalIssues(rawIssues)\n this.fields = buildFieldsMap(this.issues)\n }\n\n /**\n * G5 T2.4 — envelope view with ValidationFieldsExt populated from .fields.\n * UI consumers can `switch (env.code)` on `UNPROCESSABLE_ENTITY` and read\n * `(env.ext as ValidationFieldsExt).fields` for field-level rendering.\n */\n override get envelope(): TheoErrorEnvelope<ValidationFieldsExt> {\n return {\n code: 'UNPROCESSABLE_ENTITY',\n message: this.message,\n ext: { fields: this.fields },\n }\n }\n}\n\nfunction buildFieldsMap(issues: readonly UniversalZodIssue[]): Record<string, string[]> {\n const fields: Record<string, string[]> = {}\n const seen = new Set<string>()\n for (const issue of issues) {\n // EC-7: root path → empty string key. EC-8: numeric segments preserved as strings.\n const key = issue.path.length === 0 ? '' : issue.path.join('.')\n // `\\u0000` as an escape, not the byte itself. NUL is the right separator — it cannot occur\n // in a path or a message — but a literal one makes the whole file `binary` to `grep`, which\n // then reports \"binary file matches\" instead of the matching lines. This file was silently\n // absent from every grep over `src/` because of it, including the no-`any` type audit.\n // The runtime string is identical.\n const dedupeKey = `${key}\\u0000${issue.message}`\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n const bucket = fields[key] ?? []\n bucket.push(issue.message)\n fields[key] = bucket\n }\n return fields\n}\n\n/**\n * Normalize zod v3 (`z.ZodIssue`) and v4 (`$ZodIssue`) raw issues to\n * `UniversalZodIssue[]` (EC-1 absorbed). Duck-typed on `{path, message}` —\n * does NOT import zod types (`core/contracts/` depends on no intra-monorepo\n * + zod is consumer-controlled across the boundary).\n *\n * Silently skips entries missing required fields or shape mismatches; returns\n * empty array on non-array input.\n */\nexport function extractUniversalIssues(raw: unknown): UniversalZodIssue[] {\n if (!Array.isArray(raw)) return []\n const out: UniversalZodIssue[] = []\n for (const entry of raw) {\n if (typeof entry !== 'object' || entry === null) continue\n const obj = entry as Record<string, unknown>\n if (!Array.isArray(obj.path)) continue\n if (typeof obj.message !== 'string') continue\n // Path entries must be string or number\n const path: (string | number)[] = []\n let pathValid = true\n for (const seg of obj.path) {\n if (typeof seg === 'string' || typeof seg === 'number') {\n path.push(seg)\n } else {\n pathValid = false\n break\n }\n }\n if (!pathValid) continue\n out.push({\n path,\n message: obj.message,\n code: typeof obj.code === 'string' ? obj.code : undefined,\n })\n }\n return out\n}\n\n/**\n * Type guard for `ActionError` (and its subclass `ActionInputError`). True\n * iff the value is an instance of `ActionError`. Use `isInputError` to\n * narrow specifically to validation failures.\n */\nexport function isActionError(value: unknown): value is ActionError {\n return value instanceof ActionError\n}\n\n/**\n * Type guard narrowing to `ActionInputError`. Requires `instanceof` check\n * (not duck-typing on `type`) to prevent attacker-controlled JSON from\n * being mistaken for a real error instance.\n */\nexport function isInputError(value: unknown): value is ActionInputError {\n return value instanceof ActionInputError\n}\n\n/**\n * `ActionResult<TData, TError>` — discriminated union returned by client-side\n * action invocation. Either `{data, error: undefined}` (success) or\n * `{data: undefined, error}` (failure). Mirrors Astro `SafeResult` shape.\n */\nexport type ActionResult<TData = unknown, TError extends ActionError = ActionError> =\n | { data: TData; error: undefined }\n | { data: undefined; error: TError }\n\n/**\n * `SerializedActionResult` — wire-shape emitted by `serializeActionResult`\n * in `server/http/serialize-action-result.ts` (T1.3). Discriminator `type`\n * distinguishes data (devalue-encoded), error (JSON), and empty (204) cases.\n */\nexport type SerializedActionResult =\n | {\n type: 'data'\n status: number\n contentType: 'application/json+devalue'\n body: string\n }\n | {\n type: 'error'\n status: number\n contentType: 'application/json'\n body: string\n }\n | { type: 'empty'; status: 204 }\n\n/**\n * `ActionManifestEntry` — per-action metadata emitted by `action-scan.ts`\n * (T1.4) into `.theokit/actions-manifest.json`. Consumed by virtual module\n * `@theo/actions` (T3.1) and G4 devtools \"Actions\" tab (T5.1).\n */\nexport interface ActionManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly urlPath: string\n readonly accept: 'form' | 'json'\n readonly hasInput: boolean\n}\n","/**\n * Shape-based guard for AuthRequiredError detection.\n *\n * Uses duck-type check ONLY — no class import from `server/auth/` to\n * preserve `core` INVARIANT 1 (core depends on nothing intra-monorepo).\n *\n * The `instanceof AuthRequiredError` check is intentionally omitted:\n * Vite HMR can duplicate class identity across module boundaries,\n * making `instanceof` unreliable. The shape check (`code` + `status`)\n * is the canonical detection path.\n *\n * Single source of truth — previously duplicated in handle-request-error.ts\n * and execute.ts (architecture-remediation plan T1.3, 2026-06-12).\n */\nexport function isAuthRequiredError(err: unknown): boolean {\n if (err == null || typeof err !== 'object') return false\n const e = err as Record<string, unknown>\n return e.code === 'AUTH_REQUIRED' && e.status === 401\n}\n","/**\n * Who is asking. Supplied by the caller through the run-context, never read from\n * a transport.\n *\n * A cookie is one way to establish this and a terminal has no cookies, so the\n * contract takes the resolved subject rather than the mechanism that resolved it\n * (ADR 0001 section Decision, point 4).\n */\nexport interface RouteSubject {\n id: string\n [claim: string]: unknown\n}\n\n/** The answer a policy gives. A denial carries its reason so the caller can say it. */\nexport type AccessDecision = { allowed: true } | { allowed: false; reason: string }\n\n/** What a policy is handed. Deliberately transport-free: no headers, no cookies, no response. */\nexport interface RoutePolicyInput<TQuery = unknown, TBody = unknown, TParams = unknown> {\n subject: RouteSubject | null\n query: TQuery\n body: TBody\n params: TParams\n}\n\n/**\n * A route's access policy.\n *\n * `'public'` is a declaration, not a default. The point of writing it is that\n * openness becomes greppable — today a route that enforces nothing looks exactly\n * like a route nobody thought about (ADR 0001 section Consequences, Risks).\n */\nexport type RoutePolicy<TQuery = unknown, TBody = unknown, TParams = unknown> =\n | 'public'\n | ((\n input: RoutePolicyInput<TQuery, TBody, TParams>,\n ) => boolean | AccessDecision | Promise<boolean | AccessDecision>)\n\n/** Narrow a run-context to the subject it carries, if it carries one. */\nexport function subjectFromContext(context: unknown): RouteSubject | null {\n if (context === null || typeof context !== 'object') return null\n const candidate = (context as { subject?: unknown }).subject\n if (candidate === null || candidate === undefined || typeof candidate !== 'object') return null\n const id = (candidate as { id?: unknown }).id\n return typeof id === 'string' && id.length > 0 ? (candidate as RouteSubject) : null\n}\n\n/**\n * Evaluate a route policy. THE single implementation - the HTTP executors and\n * the in-process caller all reach this function, which is what makes \"the same\n * route gives the same access decision on every transport\" a property of the code\n * rather than a claim in a document.\n *\n * The shape mirrors `validateRouteInput`, which is already described in-source as\n * \"the SINGLE shared pipeline ... One pipeline, no drift\". Access control had no\n * such pipeline; that absence is what ADR 0001 exists to close.\n *\n * An undeclared policy returns `allowed` and is NOT the same thing as `'public'`.\n * Absence is refused where an application DECLARES its routes — the file-system\n * scanner fails the build naming the file (`MissingRoutePolicyError`) — and not\n * here, where the argument may be a `RouteConfig` a caller built in memory and\n * never scanned. Reinterpreting absence as denial at this point would break\n * every direct caller of the executors at once, which the ADR routes through the\n * build gate and a migration instead.\n */\nexport async function evaluateRoutePolicy(\n policy: RoutePolicy | undefined,\n input: RoutePolicyInput,\n): Promise<AccessDecision> {\n if (policy === undefined) return { allowed: true }\n if (policy === 'public') return { allowed: true }\n\n const verdict = await policy(input)\n if (typeof verdict === 'boolean') {\n return verdict ? { allowed: true } : { allowed: false, reason: 'access denied by route policy' }\n }\n return verdict\n}\n\n/**\n * The authorization primitive the framework did not have.\n *\n * `requireAuth` answers \"is anyone there\". Every action then answered \"may THIS\n * subject touch THIS record\" on its own, which is one implementation per action\n * and one place per action to get it wrong. This is that answer, once.\n */\nexport function requireOwner(\n subject: RouteSubject | null,\n ownerId: string | null | undefined,\n): AccessDecision {\n if (subject === null) return { allowed: false, reason: 'not authenticated' }\n if (typeof ownerId !== 'string' || ownerId.length === 0) {\n // An unowned resource is not an open one. A record whose owner is unknown is\n // a record no subject can be shown to own, and guessing here would fail open\n // on exactly the data whose ownership someone failed to record.\n return { allowed: false, reason: 'resource has no recorded owner' }\n }\n return subject.id === ownerId\n ? { allowed: true }\n : { allowed: false, reason: 'subject does not own this resource' }\n}\n","/**\n * Thrown when a plugin or middleware decorates `ctx.<key>` with a value\n * that the framework would also like to inject (e.g., `ctx.queue` from\n * the jobs backend wiring).\n *\n * Per EC-202 of system-100-percent-functional-plan: silent override is a\n * latent bug class. Fail loud so the conflict surfaces immediately.\n */\nexport class DuplicateContextKeyError extends Error {\n readonly code = 'DUPLICATE_CONTEXT_KEY'\n constructor(\n public readonly key: string,\n opts?: { reason?: string },\n ) {\n super(\n `Duplicate context key \"${key}\". ${opts?.reason ?? 'The framework cannot inject a value for a key already decorated by middleware or a plugin.'}`,\n )\n this.name = 'DuplicateContextKeyError'\n }\n}\n","import type { JobEnqueueInput } from './job-backend.js'\n\n/**\n * Transactional outbox buffer for `ctx.queue.enqueue` (T2.5).\n *\n * Lifecycle (wired in `http/execute.ts` by T2.5 integration step):\n * 1. Request handler invoked → create per-request outbox.\n * 2. Handler calls `ctx.queue.enqueue(...)` → outbox.push(entry).\n * 3a. Response committed (`res.on('finish')` + statusCode < 400) →\n * outbox.flush(backend.enqueue).\n * 3b. Response errors (statusCode >= 400, handler throws, `res.on('close')`\n * without finish) → outbox.discard().\n *\n * Invariants:\n * - Outbox NEVER dispatches before commit. Backend.enqueue is NEVER\n * called on the request hot path.\n * - Handler throws → ZERO jobs dispatched. KEY guarantee from ADR-0003.\n *\n * EC-107: when `backend.enqueue` throws DURING flush (after response\n * committed), we log + continue. The response is already gone; partial\n * dispatch is better than zero. Each failure goes to `onError` (default:\n * `console.warn`).\n */\n\nexport interface OutboxFlushOptions {\n /**\n * Called once per failed entry. Default: `console.warn` with the\n * entry name (NOT input — privacy). Throw nothing back to caller —\n * flush always completes.\n */\n onError?: (entryName: string, errorMessage: string) => void\n}\n\nexport interface Outbox {\n push(entry: JobEnqueueInput): void\n drain(): JobEnqueueInput[]\n discard(): void\n size(): number\n /**\n * Dispatch all buffered entries via `dispatcher`. Returns after all\n * entries attempted. Per-entry failures invoke `opts.onError` (or\n * default warn) and do NOT abort the loop.\n */\n flush(\n dispatcher: (entry: JobEnqueueInput) => Promise<unknown>,\n opts?: OutboxFlushOptions,\n ): Promise<void>\n}\n\nexport function createOutbox(): Outbox {\n let buffer: JobEnqueueInput[] = []\n\n return {\n push(entry) {\n buffer.push(entry)\n },\n drain() {\n const out = buffer\n buffer = []\n return out\n },\n discard() {\n buffer = []\n },\n size() {\n return buffer.length\n },\n async flush(dispatcher, opts) {\n const entries = buffer\n buffer = []\n const onError =\n opts?.onError ??\n ((name, msg) => {\n console.warn(`[theokit:jobs:outbox] flush error for \"${name}\": ${msg}`)\n })\n for (const e of entries) {\n try {\n await dispatcher(e)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n onError(e.name, message)\n }\n }\n },\n }\n}\n","import type { JobBackend, JobEnqueueInput } from './job-backend.js'\nimport type { JobRegistry } from './job-types.js'\nimport type { Outbox } from './outbox.js'\n\n/**\n * Options forwarded to `backend.enqueue` at outbox flush time.\n */\nexport interface EnqueueOptions {\n /** Optional idempotency key for at-most-once dispatch within TTL. */\n idempotencyKey?: string\n /** Optional delay before the job becomes available. */\n delaySeconds?: number\n}\n\n/**\n * Typed queue client. Per ADR-0003, `enqueue` returns `void` and buffers\n * to the per-request outbox. `enqueueWithId` is the log-correlation\n * variant that resolves to `{ jobId }` AFTER the outbox flushes.\n *\n * Type inference: `JobName extends keyof JobRegistry`. Users extend the\n * `JobRegistry` interface via module augmentation (see `job-types.ts`).\n * Without augmentation, all enqueue calls compile-error with \"Type X is\n * not assignable to type never\" — documented in EC-110 as a known onboarding\n * friction.\n */\nexport interface QueueClient {\n /** Buffer a job to the outbox. Returns void (fire-and-forget). */\n enqueue<JobName extends keyof JobRegistry>(\n name: JobName,\n input: JobRegistry[JobName],\n opts?: EnqueueOptions,\n ): void\n /**\n * Buffer a job AND return a Promise that resolves with the jobId\n * AFTER the outbox flushes (i.e., after the response commits). NOT a\n * handle to await the job result — there is no result API.\n */\n enqueueWithId<JobName extends keyof JobRegistry>(\n name: JobName,\n input: JobRegistry[JobName],\n opts?: EnqueueOptions,\n ): Promise<{ jobId: string }>\n}\n\ninterface CreateQueueClientOptions {\n /** W3C traceparent to propagate to enqueued jobs. */\n traceparent?: string\n}\n\n/**\n * Create a per-request queue client wired to a backend + outbox.\n *\n * The backend is referenced only to resolve `enqueueWithId` jobIds at\n * flush time — `enqueue` itself does NOT call backend on the hot path\n * (transactional outbox guarantee per ADR-0003).\n */\nexport function createQueueClient(\n backend: JobBackend,\n outbox: Outbox,\n opts: CreateQueueClientOptions = {},\n): QueueClient {\n const traceparent = opts.traceparent\n\n return {\n enqueue(name, input, enqueueOpts) {\n const entry: JobEnqueueInput = {\n name: name,\n input,\n idempotencyKey: enqueueOpts?.idempotencyKey,\n delaySeconds: enqueueOpts?.delaySeconds,\n traceparent,\n }\n outbox.push(entry)\n },\n\n enqueueWithId(name, input, enqueueOpts) {\n let resolveJobId!: (v: { jobId: string }) => void\n let rejectJobId!: (e: unknown) => void\n const promise = new Promise<{ jobId: string }>((resolve, reject) => {\n resolveJobId = resolve\n rejectJobId = reject\n })\n // Prevent unhandled rejection if the response is discarded\n void promise.catch(() => {\n /* swallow — jobId promise is best-effort log correlation */\n })\n\n // Wrap the entry so the outbox flush resolves the promise.\n const entry: JobEnqueueInput & {\n readonly __resolveJobId?: (v: { jobId: string }) => void\n readonly __rejectJobId?: (e: unknown) => void\n } = {\n name: name,\n input,\n idempotencyKey: enqueueOpts?.idempotencyKey,\n delaySeconds: enqueueOpts?.delaySeconds,\n traceparent,\n __resolveJobId: resolveJobId,\n __rejectJobId: rejectJobId,\n }\n outbox.push(entry)\n return promise\n },\n }\n}\n\n/**\n * Outbox dispatcher that bridges enqueueWithId's hidden promise channel\n * (`__resolveJobId` / `__rejectJobId`) to the backend.enqueue result.\n *\n * Use this when the request lifecycle hooks call `outbox.flush(...)`.\n */\nexport function createOutboxDispatcher(\n backend: JobBackend,\n): (entry: JobEnqueueInput) => Promise<unknown> {\n return async (entry) => {\n const augmented = entry as JobEnqueueInput & {\n __resolveJobId?: (v: { jobId: string }) => void\n __rejectJobId?: (e: unknown) => void\n }\n try {\n const result = await backend.enqueue(entry)\n augmented.__resolveJobId?.(result)\n return result\n } catch (err) {\n augmented.__rejectJobId?.(err)\n throw err\n }\n }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { parseRequestBody, RequestBodyConsumedError } from '../body-parser.js'\n\nimport { sendError } from './send-response.js'\n\n/**\n * T5.1 (partial Pipeline extraction) — request-parsing + Zod-validation\n * stages extracted from the executeRoute monolith.\n *\n * Each stage returns `{ ok: true, ...data }` on success OR `{ ok: false }`\n * on short-circuit (in which case the stage already sent an error response).\n *\n * Per EC-5 (plugin hook ordering) and EC-15 (AsyncLocalStorage), these\n * stages do NOT invoke plugin hooks — the orchestrator (`executeRoute`)\n * keeps that responsibility in one place.\n */\n\ntype StageResult<T> = { ok: true; data: T } | { ok: false }\n\n/**\n * Parse URL query + request body (multipart/form-data or JSON).\n * On parse failure, sends 400 or 415 (Unsupported Content-Type) + returns\n * `{ ok: false }`. Otherwise returns `{ query, body }`.\n */\nexport async function parseQueryAndBody(\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string | undefined,\n): Promise<StageResult<{ query: Record<string, string>; body: unknown; raw?: string }>> {\n // Query\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`)\n const query: Record<string, string> = Object.fromEntries(url.searchParams)\n\n // Body (JSON + multipart/form-data)\n let body: unknown\n let raw: string | undefined\n try {\n const parsed = await parseRequestBody(req)\n raw = parsed.raw\n if (parsed.json !== undefined) {\n body = parsed.json\n } else if (parsed.files.length > 0 || Object.keys(parsed.fields).length > 0) {\n body = { ...parsed.fields, _files: parsed.files }\n } else {\n body = undefined\n }\n } catch (err) {\n // theokit#400 — a body somebody upstream already drained is OUR fault, not the caller's. A 400\n // would tell the client to fix a request that was correct; this says 500 and names the cause.\n if (err instanceof RequestBodyConsumedError) {\n sendError(res, 'INTERNAL_ERROR', err.message, err.status, undefined, requestId)\n return { ok: false }\n }\n const message = (err as Error).message\n const status = message.includes('Unsupported Content-Type') ? 415 : 400\n sendError(res, 'VALIDATION_ERROR', message, status, undefined, requestId)\n return { ok: false }\n }\n\n return { ok: true, data: { query, body, raw } }\n}\n\n/**\n * Validate query, body, params against the route's Zod schemas (when present).\n * On validation failure, sends 400 with Zod issues + returns `{ ok: false }`.\n * On success, returns the (possibly-transformed) values from `schema.safeParse(...).data`.\n */\ninterface ZodLike {\n safeParse: (value: unknown) => {\n success: boolean\n data?: unknown\n error?: { issues: unknown[] }\n }\n}\nexport const isZodLike = (value: unknown): value is ZodLike =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { safeParse?: unknown }).safeParse === 'function'\n\nexport function runZodValidation(\n routeConfig: Record<string, unknown>,\n res: ServerResponse,\n requestId: string | undefined,\n input: {\n query: Record<string, string>\n body: unknown\n params: Record<string, string>\n },\n): StageResult<{ query: Record<string, string>; body: unknown; params: Record<string, string> }> {\n const { query, params } = input\n let { body } = input\n\n if (isZodLike(routeConfig.query)) {\n const result = routeConfig.query.safeParse(query)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid query parameters',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n Object.assign(query, result.data)\n }\n\n if (isZodLike(routeConfig.body)) {\n const result = routeConfig.body.safeParse(body)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid request body',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n body = result.data\n }\n\n if (isZodLike(routeConfig.params)) {\n const result = routeConfig.params.safeParse(params)\n if (!result.success) {\n sendError(\n res,\n 'VALIDATION_ERROR',\n 'Invalid route parameters',\n 400,\n result.error?.issues,\n requestId,\n )\n return { ok: false }\n }\n Object.assign(params, result.data)\n }\n\n return { ok: true, data: { query, body, params } }\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Middleware runner. Checks for `serverDir/middleware.ts` + `context.ts`,\n * cached by CR-017. Paths are derived from `serverDir` (cwd-derived). No\n * HTTP input.\n */\nimport { existsSync } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { join } from 'node:path'\n\nimport { WEB_SHAPED_MIDDLEWARE, type MiddlewareHandler } from '../define/define-middleware.js'\nimport { scanMiddlewares } from '../scan/middleware-scan.js'\nimport type { LoadModule } from '../scan/module-loader.js'\n\nimport { createWebRequestSource } from './node-request.js'\nimport { writeWebResponseToServerResponse } from './node-web-adapter.js'\n\nexport interface MiddlewareResult {\n ctx: unknown\n aborted: boolean\n}\n\n// CR-017 fix: in dev `existsSync` + `scanMiddlewares` ran on EVERY request,\n// turning a constant filesystem read into per-request overhead. We cache\n// the scan result by serverDir. In prod the same scan should be done once\n// at boot — `theo build` already emits a manifest, but the dev path uses\n// this runtime cache as a defense-in-depth. The cache is invalidated by\n// process restart (Vite HMR replaces the module, clearing this map).\ninterface MiddlewareCacheEntry {\n singleFilePath: string\n singleFileExists: boolean\n dirMiddlewares: string[]\n}\nconst middlewareCache = new Map<string, MiddlewareCacheEntry>()\n\nexport function _resetMiddlewareCacheForTests(): void {\n middlewareCache.clear()\n}\n\n// Middleware default-export contract: a function (req, res, next).\ntype MiddlewareFn = (\n req: IncomingMessage,\n res: ServerResponse,\n next: () => void,\n) => void | Promise<void>\ntype ContextFactory = (args: { request: IncomingMessage; response: ServerResponse }) => unknown // Promise<unknown> is structurally `unknown`; one arm covers both.\n\nfunction getCachedScan(serverDir: string): MiddlewareCacheEntry {\n let cached = middlewareCache.get(serverDir)\n if (!cached) {\n const singleFilePath = join(serverDir, 'middleware.ts')\n cached = {\n singleFilePath,\n singleFileExists: existsSync(singleFilePath),\n dirMiddlewares: scanMiddlewares(serverDir),\n }\n middlewareCache.set(serverDir, cached)\n }\n return cached\n}\n\n/**\n * Run a Web-shaped middleware — the one `middleware()` and `defineMiddleware()` produce (#345).\n *\n * This used to REFUSE the shape by name, because the runner could only invoke `(req, res, next)`\n * and calling a Web handler that way hands it `res` as its `next`. Refusing was better than the\n * blank response it replaced, and it was never the end state: the README documented the builder as\n * the way to write middleware, so the documented path was loud instead of silent, but still broken.\n *\n * It runs now because the published contract became the one that fits this model:\n * `(request, context) => Response | void`. No continuation is needed — returning a `Response`\n * answers the request, returning nothing continues — which is exactly what a runner that executes\n * BEFORE routing can honestly offer.\n *\n * The `Request` is built by the same converter the agent and action branches use, so a middleware\n * reads the request the way every other Web-shaped surface in the framework does.\n */\nasync function runWebShapedMiddleware(\n mw: MiddlewareHandler,\n req: IncomingMessage,\n res: ServerResponse,\n context: Record<string, unknown>,\n): Promise<{ shortCircuited: boolean }> {\n const request = createWebRequestSource(req).toRequest()\n const result = await mw(request, context)\n if (!(result instanceof Response)) return { shortCircuited: false }\n\n // Written here rather than returned upward: a short-circuit that only ABORTED would leave the\n // client with a blank response, which is the failure this whole issue is about.\n await writeWebResponseToServerResponse(result, res)\n return { shortCircuited: true }\n}\n\n/** Whether a loaded default export declared the Web-shaped contract. */\nfunction isWebShaped(mw: object): mw is MiddlewareHandler {\n return WEB_SHAPED_MIDDLEWARE in mw\n}\n\n/**\n * Run ONE scanned middleware, whichever shape it declared, and say whether the request is over.\n *\n * One dispatcher rather than a branch at each load site: `server/middleware/` and the single\n * `server/middleware.ts` are two entry points to the same semantics, and this file has already\n * watched them drift — the single-file arm kept `refuseIncompatibleShape` only because someone\n * remembered to add it twice.\n */\nasync function runScannedMiddleware(\n mw: MiddlewareFn,\n req: IncomingMessage,\n res: ServerResponse,\n context: Record<string, unknown>,\n): Promise<{ aborted: boolean }> {\n if (isWebShaped(mw)) {\n const { shortCircuited } = await runWebShapedMiddleware(mw, req, res, context)\n return { aborted: shortCircuited }\n }\n const { nextCalled } = await runOneMiddleware(mw, req, res)\n return { aborted: !nextCalled || res.writableEnded }\n}\n\nasync function runOneMiddleware(\n mw: MiddlewareFn,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<{ nextCalled: boolean }> {\n // Object-held flag avoids TS narrowing `let nextCalled = false` to the\n // literal `false`, which would make `!nextCalled` an \"always-truthy\"\n // condition under control-flow analysis.\n const state = { nextCalled: false }\n await mw(req, res, () => {\n state.nextCalled = true\n })\n return state\n}\n\nexport async function runMiddlewareAndContext(\n req: IncomingMessage,\n res: ServerResponse,\n loadModule: LoadModule,\n serverDir: string,\n): Promise<MiddlewareResult> {\n const { singleFilePath, singleFileExists, dirMiddlewares } = getCachedScan(serverDir)\n const dirExists = dirMiddlewares.length > 0\n\n // #345 — what a Web-shaped middleware decorates. Before this, file middleware contributed NOTHING\n // to `ctx` (only `server/context.ts` did), so an app that wanted a middleware to pass a value to\n // a route had nowhere to put it.\n const middlewareCtx: Record<string, unknown> = {}\n\n // 1. Ambiguity check — both file and directory is a configuration error\n if (singleFileExists && dirExists) {\n throw new Error(\n 'Ambiguous middleware configuration: found both server/middleware.ts and server/middleware/ directory. ' +\n 'Use one or the other, not both.',\n )\n }\n\n // 2. Run middleware chain from directory\n if (dirExists) {\n for (const mwPath of dirMiddlewares) {\n const mod = await loadModule(mwPath)\n const mw = mod.default as MiddlewareFn | undefined\n if (typeof mw !== 'function') continue\n\n // Both shapes run, in FILENAME order. Running one family before the other would make the\n // `01-`/`02-` prefixes mean nothing the moment an app mixed them, and the prefixes are the\n // only ordering contract this directory has.\n const { aborted } = await runScannedMiddleware(mw, req, res, middlewareCtx)\n if (aborted) return { ctx: middlewareCtx, aborted: true }\n }\n }\n\n // 3. Run single middleware file (backward compat)\n if (singleFileExists) {\n const mod = await loadModule(singleFilePath)\n const mw = mod.default as MiddlewareFn | undefined\n if (typeof mw === 'function') {\n const { aborted } = await runScannedMiddleware(mw, req, res, middlewareCtx)\n if (aborted) return { ctx: middlewareCtx, aborted: true }\n }\n }\n\n // 4. Create context (if exists), on top of what middleware decorated.\n //\n // The factory wins on a key collision, matching the precedent one layer up: `execute.ts` re-applies\n // plugin decorations over the middleware ctx for the same reason — the later, more specific\n // producer is the one that meant to set it.\n const factoryCtx = await createServerContext(req, res, loadModule, serverDir)\n if (factoryCtx === null || typeof factoryCtx !== 'object') {\n return { ctx: middlewareCtx, aborted: false }\n }\n return { ctx: { ...middlewareCtx, ...(factoryCtx as Record<string, unknown>) }, aborted: false }\n}\n\n/**\n * Run ONLY the application's `server/context.ts` factory and return what it produced.\n *\n * Split out of {@link runMiddlewareAndContext} because the agent endpoints need the identity half\n * of that function and must not take the middleware half with it (usetheokit/theokit#365).\n *\n * The split is not a shortcut, it is the whole of what those endpoints can honestly reuse today:\n * middleware here is `(req, res, next)` and contributes NOTHING to `ctx` — only this factory does.\n * So running the chain would buy the policy no identity it does not already get, while adding\n * abort semantics and header side effects to a dispatch branch that has never had them. Running\n * `server/middleware/` on agent URLs is a separate, larger behaviour change; it is not this one.\n */\nexport async function createServerContext(\n req: IncomingMessage,\n res: ServerResponse,\n loadModule: LoadModule,\n serverDir: string,\n): Promise<unknown> {\n const contextPath = join(serverDir, 'context.ts')\n if (!existsSync(contextPath)) return {}\n const mod = await loadModule(contextPath)\n const createContext = mod.createContext as ContextFactory | undefined\n if (typeof createContext !== 'function') return {}\n return await createContext({ request: req, response: res })\n}\n","/**\n * A middleware, as the framework's own builder produces it (usetheokit/theokit#345).\n *\n * `(request, context)`: read the request as a Web `Request`, decorate `context` for the route that\n * follows, and RETURN a `Response` to answer the request yourself. Returning nothing continues to\n * the next middleware, and then to the route.\n *\n * ## Why not `(request, next) => Response`\n *\n * That was this type's first shape, and it described a continuation pipeline nothing in this\n * repository implements: the file-scan runner runs BEFORE routing, so it has no downstream\n * `Response` to hand back from `next(request)`. The consequence was measured rather than\n * theorised — `MiddlewareHandler` had **zero runtime consumers**, while `README.md` documented the\n * builder that produces it as the way to write middleware. A published builder whose output nothing\n * can call is worse than a missing one, because it reads as supported.\n *\n * This shape is the one that fits the model AND already runs: `executeWebRequest` has invoked\n * `(request, context) => Response | void` since T3.2 (`http/web-middleware-runner.ts`). Adopting it\n * here converges two of the three middleware contracts instead of adding a fourth.\n *\n * The Express-style `(req, res, next)` export keeps working in `server/middleware/*.ts`. It is\n * Node-bound — which is why it cannot be the framework's contract — but evicting it would break\n * every app that has one.\n */\nexport type MiddlewareHandler = (\n request: Request,\n context: Record<string, unknown>,\n // `void` is deliberate: returning nothing is how a middleware says \"continue\". The runner only\n // inspects `instanceof Response`, so there is nothing to distinguish from `undefined`.\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n) => Response | undefined | void | Promise<Response | undefined | void>\n\n/**\n * Marks a handler as declaring the Web-shaped contract above.\n *\n * `server/middleware/*.ts` may export either shape, and both are plain functions, so a `typeof`\n * screen cannot tell them apart. Arity cannot either: a hand-written Node middleware that ignores\n * `next` also has length 2, and treating that as Web-shaped would hand it a `Request` it does not\n * expect. So the shape is RECORDED where it is declared rather than guessed where it is consumed,\n * and the runner dispatches on the brand (usetheokit/theokit#345).\n *\n * @internal\n */\nexport const WEB_SHAPED_MIDDLEWARE = Symbol.for('theokit.middleware.web-shaped')\n\n/**\n * Define a middleware handler.\n *\n * Identity function — provides the type annotation, and records the declared\n * shape so a runner that cannot invoke it can say so by name. The brand is\n * non-enumerable, so it does not appear in spreads, `Object.keys` or a JSON\n * round-trip of anything holding the handler.\n */\nexport function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler {\n Object.defineProperty(handler, WEB_SHAPED_MIDDLEWARE, {\n value: true,\n enumerable: false,\n configurable: true,\n })\n return handler\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks `serverDir/middleware/` derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { readdirSync, existsSync, statSync } from 'node:fs'\nimport { join, extname } from 'node:path'\n\nimport { compareByCodeUnit } from '../_internal/compare-by-code-unit.js'\n\nconst MW_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\n\n/**\n * Scan the server/middleware/ directory for middleware files.\n * Files are returned sorted alphabetically — use numeric prefixes\n * (e.g. 01-cors.ts, 02-auth.ts) to control execution order.\n *\n * Files starting with '_' or '.' are ignored (helpers, hidden files).\n */\nexport function scanMiddlewares(serverDir: string): string[] {\n const mwDir = join(serverDir, 'middleware')\n if (!existsSync(mwDir) || !statSync(mwDir).isDirectory()) {\n return []\n }\n\n const entries = readdirSync(mwDir, { withFileTypes: true })\n const files: string[] = []\n\n for (const entry of entries) {\n if (!entry.isFile()) continue\n if (entry.name.startsWith('_') || entry.name.startsWith('.')) continue\n const ext = extname(entry.name)\n if (!MW_EXTENSIONS.has(ext)) continue\n files.push(join(mwDir, entry.name))\n }\n\n // Sorted so the numeric prefix (01-, 02-) guarantees execution order.\n // By code unit, not by collation: this order is what runs first, and a\n // collated order is machine-dependent (usetheokit/theokit#351).\n files.sort(compareByCodeUnit)\n return files\n}\n","/**\n * Maps a TheoErrorEnvelope `code` to its canonical HTTP status.\n *\n * Single source of truth — previously duplicated in `web-handler.ts` and\n * `handle-request-error.ts` (architecture-remediation plan T1.2, 2026-06-12).\n *\n * Every TheoErrorCode value MUST have an explicit entry here. SDK-domain codes\n * (AGENT_RUN_ERROR, PROVIDER_KEY_MISSING, BUDGET_EXCEEDED, CREDENTIAL_POOL_EXHAUSTED)\n * intentionally map to 500 — they represent internal failures, not client errors.\n */\n\nconst CODE_TO_STATUS: Record<string, number> = {\n // 4xx — client errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n CONFLICT: 409,\n PRECONDITION_FAILED: 412,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n RATE_LIMITED: 429,\n\n // 5xx — server errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n\n // SDK-domain codes — intentionally 500\n AGENT_RUN_ERROR: 500,\n PROVIDER_KEY_MISSING: 500,\n BUDGET_EXCEEDED: 500,\n CREDENTIAL_POOL_EXHAUSTED: 500,\n}\n\nexport function envelopeCodeToStatus(code: string): number {\n return CODE_TO_STATUS[code] ?? 500\n}\n","/**\n * T5a.2 Phase G slice 5/N — Node adapter shim for the Web request handler.\n *\n * Bridges Node's `IncomingMessage` + `ServerResponse` shape to the\n * Web-Standards `executeWebRequest` (Phase A → G slices 1-4). Per\n * ADR-0028 R3a, the Node adapter is the ONLY place IncomingMessage ↔\n * Request conversion happens — every other layer of `server/` flows\n * through Web `Request`/`Response`.\n *\n * **Two conversions:**\n *\n * 1. `incomingMessageToWebRequest(req)` — Node → Web. Reads\n * `req.method`, `req.url`, `req.headers`, and (for POST/PUT/etc.)\n * drains the Node Readable body into a Web `ReadableStream`. The\n * request URL is resolved to absolute form using `req.headers.host`\n * (Web Request guarantees absolute URL).\n *\n * 2. `writeWebResponseToServerResponse(response, res)` — Web → Node.\n * Sets status code + status text, copies headers (including all\n * `Set-Cookie` values via `getSetCookie()`), then drains the Web\n * `ReadableStream` body into the Node ServerResponse.\n *\n * Plus the convenience composer `executeWebRequestFromNode(req, res,\n * routeModule, opts?)` that wires both ends — exactly what api-middleware\n * (and the prod CLI start path) need to migrate from the legacy\n * `executeRoute` to `executeWebRequest` without touching call sites.\n *\n * v1.0 § Phase G slice 5/N (closes the executor bridge surface).\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { executeWebRequest, type ExecuteWebRequestOptions } from '../web-handler.js'\n\nimport { incomingMessageToWebRequest } from './node-request.js'\n\n/**\n * Write a Web `Response` into a Node `ServerResponse`. Mirrors the Node\n * `res.writeHead` + `res.end` pattern.\n *\n * Set-Cookie is the only multi-value header the Web spec exposes via\n * `getSetCookie()`. We append each entry individually so Node emits\n * separate `Set-Cookie:` lines per the HTTP spec.\n *\n * If the Response body is a `ReadableStream`, it's piped chunk-by-chunk\n * to `res`. Empty body (null) → just close.\n */\nexport async function writeWebResponseToServerResponse(\n response: Response,\n res: ServerResponse,\n): Promise<void> {\n // Status + headers FIRST (writeHead locks them).\n // EC-3: Set-Cookie needs special handling (writeHead's plain object\n // shape conflicts with multi-value headers; we set them via setHeader\n // BEFORE writeHead so the array form is preserved).\n const setCookies = response.headers.getSetCookie()\n if (setCookies.length > 0) {\n res.setHeader('Set-Cookie', setCookies)\n }\n const otherHeaders: Record<string, string> = {}\n for (const [key, value] of response.headers.entries()) {\n if (key.toLowerCase() === 'set-cookie') continue\n otherHeaders[key] = value\n }\n res.writeHead(response.status, response.statusText, otherHeaders)\n\n // Body — drain ReadableStream OR just end() for null body.\n if (response.body === null) {\n res.end()\n return\n }\n const reader = response.body.getReader()\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n // Node's res.write accepts Uint8Array natively (no conversion needed).\n res.write(value)\n }\n res.end()\n } finally {\n reader.releaseLock()\n }\n}\n\n/**\n * Convenience composer — full request lifecycle Node → Web → Node.\n *\n * Use case: existing api-middleware (and the prod CLI start path)\n * receive Node `(req, res)` from `http.createServer`. To migrate to the\n * Web-Standards executor without rewriting every call site, wrap with\n * this composer:\n *\n * import * as users from './app/users/route.js'\n * await executeWebRequestFromNode(req, res, users, { csrfMode: 'strict' })\n *\n * The Web request is built, dispatched through executeWebRequest, and\n * the Response is drained back into `res`. Caller does NOT need to call\n * `res.end()` afterwards — this composer handles it.\n */\nexport async function executeWebRequestFromNode(\n req: IncomingMessage,\n res: ServerResponse,\n routeModule: Parameters<typeof executeWebRequest>[1],\n opts?: ExecuteWebRequestOptions,\n): Promise<void> {\n const webRequest = incomingMessageToWebRequest(req)\n const webResponse = await executeWebRequest(webRequest, routeModule, opts)\n await writeWebResponseToServerResponse(webResponse, res)\n}\n","import type { ServerResponse } from 'node:http'\n\nimport { isAuthRequiredError } from '../../core/contracts/auth-error-guard.js'\nimport {\n evaluateRoutePolicy,\n subjectFromContext,\n type RoutePolicy,\n} from '../../core/contracts/route-policy.js'\nimport { TheoError } from '../../core/contracts/theo-error.js'\nimport { DuplicateContextKeyError } from '../jobs/duplicate-context-key-error.js'\nimport { createOutbox } from '../jobs/outbox.js'\nimport { createOutboxDispatcher, createQueueClient } from '../jobs/queue-client.js'\nimport { warnOnce } from '../observability/logger.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf } from '../security/csrf.js'\n\nimport type { ExecuteRouteContext } from './execute-context.js'\nimport { isZodLike, parseQueryAndBody, runZodValidation } from './execute-stages.js'\nimport { runMiddlewareAndContext } from './middleware-runner.js'\nimport { incomingMessageToHandlerRequest } from './node-request.js'\nimport { sendError, sendJson } from './send-response.js'\n\n// CSRF policy applies to every state-mutating method, including DELETE.\nconst CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n// T5.1: sendJson + sendError + SendErrorOptions moved to send-response.ts\n// to break the execute ↔ execute-stages cycle. Re-exported below for\n// backward compat.\nexport { sendJson, sendError } from './send-response.js'\nexport type { SendErrorOptions, SendErrorInput } from './send-response.js'\n// T3.1 — ExecuteRouteContext (ADR-0016)\nexport type { ExecuteRouteContext } from './execute-context.js'\n\ninterface StreamPipeCtx {\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n ctx: Record<string, unknown>\n method: string\n pluginRunner: PluginRunner | undefined\n requestId: string | undefined\n routePath: string\n}\n\n/**\n * Honour Node backpressure: `res.write()` answered `false`, so wait until the\n * consumer has made room before reading the next chunk. Without this the\n * producer outruns a slow consumer and the queued bytes grow unbounded —\n * which is how a streaming fix trades one memory defect for another.\n *\n * Deliberately narrow. Only an exact `false` waits (a stub `res.write` that\n * returns `undefined` must not park the pipeline), only a `res` that carries\n * an event emitter waits, and `close`/`error` release the wait as well as\n * `drain`, so a disconnected client cannot hang the handler.\n */\nasync function waitForDrain(res: ServerResponse): Promise<void> {\n if (typeof res.once !== 'function') return\n await new Promise<void>((resolve) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n if (typeof res.off === 'function') {\n res.off('drain', finish)\n res.off('close', finish)\n res.off('error', finish)\n }\n resolve()\n }\n res.once('drain', finish)\n res.once('close', finish)\n res.once('error', finish)\n })\n}\n\n/**\n * Pipe a Web Standard ReadableStream into a Node ServerResponse. Stream\n * errors after headers are sent cannot change the response status, but\n * MUST be logged + reported (CR-004 fix). Extracted from `executeRoute`\n * to keep that function's nesting under the max-depth ceiling.\n *\n * @returns whether the body was delivered IN FULL. `false` means the response has been destroyed\n * and the caller must not end it — a short body closed cleanly is an abnormal ending reported as a\n * normal one (`docs/adr/0002-*`, usetheokit/theokit#391). Logging the failure and then calling\n * `res.end()` anyway was exactly that: status 200, chunked encoding terminated correctly, and a\n * reader that sees `done: true` on a half-answer.\n */\nasync function pipeWebStreamToResponse(\n body: ReadableStream<Uint8Array>,\n res: ServerResponse,\n ctx: StreamPipeCtx,\n): Promise<boolean> {\n const reader = body.getReader()\n try {\n let done = false\n while (!done) {\n const chunk = await reader.read()\n done = chunk.done\n // The comparison is against `false` on purpose. The type says `boolean`, but stub `res`\n // objects across the suite return `undefined`, and `!x` would park the pipeline on a drain\n // those stubs never emit.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-boolean-literal-compare -- see above\n if (!done && res.write(chunk.value) === false) await waitForDrain(res)\n }\n } catch (streamErr) {\n warnOnce(`stream-error:${ctx.routePath}:${ctx.method}`, {\n event: 'stream.error',\n requestId: ctx.requestId ?? 'no-id',\n route: ctx.routePath,\n method: ctx.method,\n message: streamErr instanceof Error ? streamErr.message : String(streamErr),\n })\n if (ctx.pluginRunner) {\n try {\n await ctx.pluginRunner.runOnError(ctx.buildPluginCtx(ctx.ctx), streamErr)\n } catch {\n // onError plugins must never destabilize the response close.\n }\n }\n // The one signal left once the head has gone out. On a real `ServerResponse` this destroys the\n // socket, aborting the chunked encoding; on the Web shim it errors the body stream the\n // `Response` already carries, so a consumer's `read()` rejects instead of reporting `done`.\n // Both are what the six adapters' own generated pumps already do, citing the same ADR.\n res.destroy(streamErr instanceof Error ? streamErr : new Error(String(streamErr)))\n return false\n } finally {\n try {\n reader.releaseLock()\n } catch {\n /* lock may already be released by abort */\n }\n }\n return true\n}\n\n// sendError moved to send-response.ts (T5.1) — re-exported above.\n\n// CR-007/Knip cleanup: `parseBody` (legacy JSON-only parser) was exported\n// but had no remaining consumers — the route pipeline uses\n// `parseRequestBody` (multipart + JSON) directly. Removed to shrink the\n// public surface and remove the duplicated METHODS_WITH_BODY constant.\n\n// eslint-disable-next-line max-lines-per-function, sonarjs/cognitive-complexity, complexity -- `executeRoute` is the framework's central request pipeline; its body length + branch density mirror the actual request lifecycle. T3.1 / ADR-0016 retired `max-params` (context object replaces 12 positional args). Branch complexity remains intentional: the request lifecycle has irreducible state machine arms (CSRF stage → Zod validate → middleware → handler → stream/JSON response). Remaining helpers `runCsrfStage`, `parseQueryAndBody`, `runHandlerStage`, etc. were extracted in earlier waves.\nexport async function executeRoute(ctx: ExecuteRouteContext): Promise<void> {\n // T3.1 — destructure the context with defaults applied\n const {\n route,\n method,\n params,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n transformer,\n csrfMode = 'strict',\n disallowed,\n jobBackend,\n } = ctx\n // ADR-0028 R3a / #117 / #119 — handlers AND plugin hooks see a Web `Request` in every runtime. Built\n // once from the Node `IncomingMessage` (headers/URL/method; body stays on the parsed `ctx.body`) and\n // shared by every buildPluginCtx call + the handler invocation below.\n const webRequest = incomingMessageToHandlerRequest(req)\n const buildPluginCtx = (ctxObj: Record<string, unknown>): PluginContext => ({\n request: webRequest,\n response: res,\n ctx: ctxObj,\n requestId: requestId ?? 'no-id',\n })\n\n // T1.2 — emit x-theo-transformer header when a non-default transformer is in use.\n // 'json' is treated as default (no header); any named transformer emits.\n if (transformer && transformer.name !== 'json') {\n res.setHeader('x-theo-transformer', transformer.name)\n }\n\n try {\n // T4.2 — onRequest hook (runs before middleware)\n let ctx: Record<string, unknown> = {}\n if (pluginRunner) {\n pluginRunner.applyDecorations(ctx)\n const onReqResult = await pluginRunner.runOnRequest(buildPluginCtx(ctx))\n if (onReqResult.shortCircuited) return\n }\n\n // Run middleware + context pipeline\n if (serverDir) {\n const result = await runMiddlewareAndContext(req, res, loadModule, serverDir)\n if (result.aborted) return\n ctx = (result.ctx ?? {}) as Record<string, unknown>\n // Re-apply decorations on top of middleware-produced ctx so plugin\n // decorations win when middleware did not set the same key.\n if (pluginRunner) pluginRunner.applyDecorations(ctx)\n }\n\n // T2.1 — wire ctx.queue + outbox lifecycle when jobBackend is configured.\n // EC-202: throw on collision instead of silent override.\n if (jobBackend) {\n if (ctx.queue !== undefined) {\n throw new DuplicateContextKeyError('queue', {\n reason:\n 'A plugin or middleware already decorated ctx.queue; choose a different key OR remove jobs.backend from theo.config.ts.',\n })\n }\n const outbox = createOutbox()\n const queueClient = createQueueClient(jobBackend, outbox)\n ctx.queue = queueClient\n\n // Discard on abort or 4xx (handler throws cascade to 500 via catch\n // below, where statusCode is already >= 400).\n res.on('close', () => {\n if (!res.writableFinished) outbox.discard()\n })\n // Flush on commit, only when response indicates success.\n res.on('finish', () => {\n if (res.statusCode >= 400) {\n outbox.discard()\n return\n }\n void outbox.flush(createOutboxDispatcher(jobBackend))\n })\n }\n\n const mod = await loadModule(route.filePath)\n const routeConfig = mod[method]\n\n if (!routeConfig) {\n sendError(\n res,\n 'METHOD_NOT_ALLOWED',\n `Method ${method} not allowed`,\n 405,\n undefined,\n requestId,\n )\n return\n }\n\n const handler =\n typeof routeConfig === 'function'\n ? routeConfig\n : (routeConfig as Record<string, unknown>).handler\n if (typeof handler !== 'function') {\n sendError(res, 'INTERNAL_ERROR', 'Route handler is not a function', 500, undefined, requestId)\n return\n }\n\n // Phase 5 — CSRF enforcement (warn-first default; strict in 0.3.0).\n // Skips: safe methods (GET/HEAD/OPTIONS), per-route opt-out (`csrf: false`),\n // and bare function exports (legacy style — no opt-out hook available).\n const routeOptOut =\n typeof routeConfig === 'object' && (routeConfig as { csrf?: unknown }).csrf === false\n if (CSRF_PROTECTED_METHODS.has(method) && !routeOptOut) {\n const decision = enforceCsrf(\n req,\n csrfMode,\n {\n // T3.3 DRY — see security/csrf-warn-dispatch.ts\n warn: dispatchCsrfWarn,\n path: req.url,\n },\n disallowed,\n )\n if (!decision.allow) {\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n requestId,\n )\n return\n }\n }\n\n // T5.1 — extracted stages (parseQueryAndBody + runZodValidation).\n // Each stage either succeeds (returns parsed data) OR short-circuits\n // (sends the error response inline + returns ok:false).\n const rc = routeConfig as Record<string, unknown>\n\n const parseResult = await parseQueryAndBody(req, res, requestId)\n if (!parseResult.ok) return\n const { query, raw } = parseResult.data\n let { body } = parseResult.data\n\n const validationResult = runZodValidation(rc, res, requestId, { query, body, params })\n if (!validationResult.ok) return\n body = validationResult.data.body\n\n // T4.3 — preHandler hook (after Zod validation, before handler)\n if (pluginRunner) {\n const preResult = await pluginRunner.runPreHandler(buildPluginCtx(ctx))\n if (preResult.shortCircuited) return\n }\n\n // Execute handler. `handler` is structurally typed as `unknown` at\n // this point (came out of a duck-typed module). Cast through a narrow\n // type so the call is properly typed.\n type RouteHandlerCallable = (args: {\n query: Record<string, string>\n body: unknown\n params: Record<string, string>\n request: Request\n ctx: Record<string, unknown>\n }) => unknown\n const callableHandler = handler as RouteHandlerCallable\n\n // ADR 0001 — the same evaluator the Web executor and `callProcedure` call.\n // Placed immediately before the handler so any identity established upstream\n // (middleware, plugin hooks) is on `ctx` by the time the policy reads it.\n // Wiring only the two Web-shaped paths would have left production — this one —\n // unprotected while the parity test claimed otherwise, which is the\n // looks-protected failure mode ADR 0001 rejects by name.\n const accessDecision = await evaluateRoutePolicy((rc as { policy?: RoutePolicy }).policy, {\n subject: subjectFromContext(ctx),\n query,\n body,\n params,\n })\n if (!accessDecision.allowed) {\n sendError(\n res,\n 'FORBIDDEN',\n `Access denied: ${accessDecision.reason}`,\n 403,\n undefined,\n requestId,\n )\n return\n }\n // ADR-0028 R3a — handlers receive a Web `Request` in EVERY runtime (built once above, shared with\n // the plugin hooks). The Node path previously leaked the raw `IncomingMessage` here, so any\n // Web-standard use of `ctx.request` (e.g. `ctx.request.headers.get(...)`,\n // `createSessionManagerWeb.getSession(ctx.request)`) threw at runtime even though it type-checked\n // (`ctx.request` is declared `Request`). Body is exposed via `ctx.body`, so the request carries\n // headers/url/method only (the Node stream is already drained by `parseQueryAndBody`).\n // #445 — the handler's Request carries the body it arrived with. `webRequest` above is built\n // before the body is read and is shared with the plugin hooks, so it stays as it is; this is a\n // second Request over the same bytes, for the one caller that may read them. Without it any\n // framework API taking a `Request` — `handleChannelWebhook` among them — reads an empty stream\n // and reports a valid body as malformed.\n const handlerRequest =\n raw === undefined\n ? webRequest\n : new Request(webRequest.url, {\n method: webRequest.method,\n headers: webRequest.headers,\n body: raw,\n })\n const handlerResult = await callableHandler({\n query,\n body,\n params,\n request: handlerRequest,\n ctx,\n })\n\n // Handle result\n if (handlerResult === undefined || handlerResult === null) {\n sendJson(res, null, (rc.status as number | undefined) ?? 204, transformer)\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n return\n }\n\n if (handlerResult instanceof Response) {\n // `Object.fromEntries(Headers)` collapses multi-valued headers like\n // `Set-Cookie` to a single string. Set Set-Cookie via setHeader array\n // overload BEFORE writeHead (writeHead flushes headers; later setHeader\n // is a no-op or throws). Then writeHead with the remaining singletons.\n const headersBag: Record<string, string> = {}\n for (const [k, v] of handlerResult.headers) {\n if (k.toLowerCase() !== 'set-cookie') headersBag[k] = v\n }\n const setCookies = handlerResult.headers.getSetCookie()\n if (setCookies.length > 0) {\n res.setHeader('Set-Cookie', setCookies)\n }\n res.writeHead(handlerResult.status, headersBag)\n\n let bodyCompleted = true\n if (handlerResult.body) {\n bodyCompleted = await pipeWebStreamToResponse(handlerResult.body, res, {\n buildPluginCtx,\n ctx,\n method,\n pluginRunner,\n requestId,\n routePath: route.routePath,\n })\n }\n\n // Ending a destroyed response is a no-op on both transports, so this guard is not what makes\n // the fix work — it is what makes the intent readable. `end()` here is the call a SUCCESSFUL\n // stream makes, and reaching it on a truncated one is how #391 happened.\n if (bodyCompleted) res.end()\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n return\n }\n\n // Validate the plain-object return against config.response when declared\n // (D1/D2). A mismatch is a SERVER fault → throw TheoError, routed to a 500\n // by the catch below. Response-instance + 204 branches above are untouched.\n let responseBody: unknown = handlerResult\n if (isZodLike(rc.response)) {\n const parsed = rc.response.safeParse(handlerResult)\n if (!parsed.success) {\n throw new TheoError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'response validation failed',\n ext: { issues: parsed.error?.issues },\n })\n }\n responseBody = parsed.data\n }\n sendJson(res, responseBody, (rc.status as number | undefined) ?? 200, transformer)\n if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx))\n } catch (err) {\n // T4.4 — onError hook (runs before default error response)\n if (pluginRunner) {\n // Best-effort: capture a ctx snapshot for plugins. Decorations were\n // applied to local `ctx` above, but if the error came before that, we\n // pass an empty ctx — the request/response are what matters here.\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnError(buildPluginCtx(errCtxObj), err)\n // EC-9: response may already have been ended by an onError hook\n if (res.writableEnded) {\n // Still run onResponse but mark inErrorPath to prevent recursion\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n return\n }\n }\n // Auth error detection (shape-based guard from core/contracts — Vite HMR\n // can break instanceof, so shape check is the canonical path).\n if (isAuthRequiredError(err)) {\n const authErr = err as { code: string; message: string; status: number }\n sendError(res, authErr.code, authErr.message, authErr.status, undefined, requestId)\n if (pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n }\n return\n }\n sendError(\n res,\n 'INTERNAL_ERROR',\n err instanceof Error && err.message ? err.message : 'Internal server error',\n 500,\n undefined,\n requestId,\n )\n if (pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n pluginRunner.applyDecorations(errCtxObj)\n await pluginRunner.runOnResponse(buildPluginCtx(errCtxObj), { inErrorPath: true })\n }\n }\n}\n","/**\n * FormData → ZodObject coercion driven by the declared schema.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.3 + Astro\n * runtime/server.ts:323-397 pattern (adapted to Zod 4 shape access via\n * `.def.shape`). FormData entries arrive as strings (or File for binary);\n * we walk the schema field-by-field and coerce to the declared zod type\n * before letting `safeParse` finalize validation.\n *\n * Supports: ZodString, ZodNumber, ZodBoolean, ZodArray (via getAll), nested\n * ZodObject (via dot-notation prefix), ZodOptional / ZodNullable / ZodDefault\n * wrappers. Skips: ZodDiscriminatedUnion + ZodPipe + ZodIntersection (deferred\n * to consumer's safeParse fallback — values returned as-is, zod will validate\n * or coerce).\n */\nimport { z } from 'zod'\n\n/**\n * Walk the declared ZodObject schema and pull values from `formData`,\n * coercing per-field. Returns a plain object suitable for `schema.safeParse`.\n *\n * `prefix` is used for recursive nested-object resolution: a nested field at\n * `user.address.zip` is read from formData key `user.address.zip` (top-level\n * call uses empty prefix).\n */\nexport function formDataToObject(\n formData: FormData,\n schema: z.ZodObject<z.ZodRawShape>,\n prefix = '',\n): Record<string, unknown> {\n // Zod 4: `.shape` is a direct property on ZodObject.\n const shape = schema.shape as Record<string, z.ZodType>\n const out: Record<string, unknown> = {}\n\n for (const [key, rawValidator] of Object.entries(shape)) {\n const fullKey = prefix + key\n const validator = unwrapWrappers(rawValidator)\n\n if (validator instanceof z.ZodObject) {\n // Recurse for nested object types\n const nestedPrefix = `${fullKey}.`\n const hasNestedKeys = [...formData.keys()].some((k) => k.startsWith(nestedPrefix))\n if (hasNestedKeys) {\n out[key] = formDataToObject(formData, validator, nestedPrefix)\n continue\n }\n // No nested keys present — apply default / nullable / undefined semantics\n out[key] = unwrapMissingDefault(rawValidator)\n continue\n }\n\n if (validator instanceof z.ZodArray) {\n const values = formData.getAll(fullKey)\n out[key] = coerceArrayElements(values, validator as z.ZodArray<z.ZodType>)\n continue\n }\n\n if (validator instanceof z.ZodBoolean) {\n out[key] = coerceBoolean(formData, fullKey)\n continue\n }\n\n // Scalar (string / number / etc.)\n if (formData.has(fullKey)) {\n const raw = formData.get(fullKey)\n out[key] = coerceScalar(raw, validator)\n } else {\n out[key] = unwrapMissingDefault(rawValidator)\n }\n }\n\n return out\n}\n\n/** Strip ZodOptional / ZodNullable / ZodDefault to reach the inner validator. */\nfunction unwrapWrappers(validator: z.ZodType): z.ZodType {\n let inner: z.ZodType = validator\n while (\n inner instanceof z.ZodOptional ||\n inner instanceof z.ZodNullable ||\n inner instanceof z.ZodDefault\n ) {\n inner = getInnerType(inner)\n }\n return inner\n}\n\nfunction getInnerType(wrapper: z.ZodType): z.ZodType {\n // Zod 4 stores inner type in def.innerType\n const def = wrapper.def as unknown as { innerType?: z.ZodType }\n if (def.innerType) return def.innerType\n // Fallback: try _def for cross-version compat\n const legacyDef = (wrapper as unknown as { _def?: { innerType?: z.ZodType } })._def\n if (legacyDef?.innerType) return legacyDef.innerType\n return wrapper\n}\n\n/**\n * What to return when a field is missing from FormData:\n * - ZodDefault → the default value (evaluated if function)\n * - ZodNullable → null\n * - ZodOptional → undefined\n * - else → undefined (consumer safeParse will likely error)\n */\nfunction unwrapMissingDefault(validator: z.ZodType): unknown {\n let cursor: z.ZodType = validator\n while (\n cursor instanceof z.ZodOptional ||\n cursor instanceof z.ZodNullable ||\n cursor instanceof z.ZodDefault\n ) {\n if (cursor instanceof z.ZodDefault) {\n const def = cursor.def as unknown as { defaultValue: unknown }\n return typeof def.defaultValue === 'function'\n ? (def.defaultValue as () => unknown)()\n : def.defaultValue\n }\n if (cursor instanceof z.ZodNullable) return null\n cursor = getInnerType(cursor)\n }\n return undefined\n}\n\nfunction coerceScalar(raw: FormDataEntryValue | null, validator: z.ZodType): unknown {\n if (raw === null) return undefined\n if (validator instanceof z.ZodNumber) {\n return typeof raw === 'string' ? Number(raw) : raw\n }\n // String, File, default — pass through (zod will validate File via .instanceof if used)\n return raw\n}\n\nfunction coerceArrayElements(\n values: FormDataEntryValue[],\n arrayValidator: z.ZodArray<z.ZodType>,\n): unknown[] {\n // zod 4 stores the array element schema in `def.element` (`def.type` is the\n // discriminator string 'array'). Fall back to `def.type` for older shapes.\n const def = arrayValidator.def as unknown as { element?: z.ZodType; type?: unknown }\n const elementSchema = def.element ?? (def.type instanceof z.ZodType ? def.type : undefined)\n const elementType = elementSchema ? unwrapWrappers(elementSchema) : undefined\n if (elementType instanceof z.ZodNumber) {\n return values.map((v) => (typeof v === 'string' ? Number(v) : v))\n }\n if (elementType instanceof z.ZodBoolean) {\n return values.map((v) => {\n if (v === 'true') return true\n if (v === 'false') return false\n return Boolean(v)\n })\n }\n // String / File / unknown — pass through\n return values\n}\n\nfunction coerceBoolean(formData: FormData, key: string): boolean | undefined {\n if (!formData.has(key)) return undefined\n const val = formData.get(key)\n if (val === 'true') return true\n if (val === 'false') return false\n // Presence with truthy non-boolean string (e.g., HTML checkbox \"on\") → true\n return Boolean(val)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { isAuthRequiredError } from '../../core/contracts/auth-error-guard.js'\nimport { envelopeCodeToStatus } from '../../core/contracts/envelope-code-to-status.js'\nimport { serverErrorToEnvelope } from '../../core/contracts/server-error-to-envelope.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\n\nimport { sendError } from './send-response.js'\n\n/**\n * Canonical error handler for HTTP request pipelines (T3.4 of\n * architecture-review-remediation-plan, PV-9 DRY).\n *\n * Replaces the duplicated catch-block logic in `executeRoute` (1 site) and\n * `executeAction` (1 site, via `handleActionError`). Both code paths now\n * share this implementation.\n *\n * Behavior contract (preserved from previous inline catches):\n * - Plugin `onError` fires first (swallowed if it throws — never amplify failure).\n * - `AuthRequiredError` is detected via `instanceof` AND a duck-type shape\n * check (`code === 'AUTH_REQUIRED' && status === 401`) — required because\n * under Vite dev / vitest the module-loader can produce a duplicate\n * AuthRequiredError class identity, breaking `instanceof`.\n * - `onResponse({ inErrorPath: true })` always fires at the end (swallowed\n * if it throws — EC-9).\n */\ninterface HandleRequestErrorCtx {\n req: IncomingMessage\n res: ServerResponse\n requestId: string | undefined\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\nexport async function handleRequestError(err: unknown, c: HandleRequestErrorCtx): Promise<void> {\n // 1. onError hook — swallowed on failure (EC-9 — never amplify)\n if (c.pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n c.pluginRunner.applyDecorations(errCtxObj)\n try {\n await c.pluginRunner.runOnError(c.buildPluginCtx(errCtxObj), err)\n } catch {\n // onError handlers must never destabilize the response.\n }\n // EC-9: response may already have been ended by an onError hook\n if (c.res.writableEnded) {\n try {\n await c.pluginRunner.runOnResponse(c.buildPluginCtx(errCtxObj), {\n inErrorPath: true,\n })\n } catch {\n // Containment (same as above).\n }\n return\n }\n }\n\n // 2. Auth error detection (shape-based guard from core/contracts)\n if (isAuthRequiredError(err)) {\n const authErr = err as { code: string; message: string; status: number }\n sendError(c.res, authErr.code, authErr.message, authErr.status, undefined, c.requestId)\n } else {\n // M7-1: a thrown TheoError (incl. NotFoundError) carries a typed code that\n // maps to a real status — emit it. An untyped/unknown error has no typed\n // code (serverErrorToEnvelope falls back to INTERNAL_SERVER_ERROR), so we\n // preserve the legacy INTERNAL_ERROR path, which `sendError` special-cases\n // for production message masking + structured logging. This keeps generic\n // 500s backward-compatible while giving typed errors their proper envelope.\n const envelope = serverErrorToEnvelope(err)\n if (envelope.code === 'INTERNAL_SERVER_ERROR') {\n sendError(\n c.res,\n 'INTERNAL_ERROR',\n err instanceof Error ? err.message : 'Internal server error',\n 500,\n undefined,\n c.requestId,\n )\n } else {\n sendError(\n c.res,\n envelope.code,\n envelope.message,\n envelopeCodeToStatus(envelope.code),\n undefined,\n c.requestId,\n )\n }\n }\n\n // 3. onResponse(inErrorPath) — swallowed on failure (EC-9)\n if (c.pluginRunner) {\n const errCtxObj: Record<string, unknown> = {}\n c.pluginRunner.applyDecorations(errCtxObj)\n try {\n await c.pluginRunner.runOnResponse(c.buildPluginCtx(errCtxObj), {\n inErrorPath: true,\n })\n } catch {\n // Containment.\n }\n }\n}\n\n/**\n * T5a.2 Phase G slice 3/N — Web-Standards request error handler.\n *\n * Mirror of `handleRequestError(err, c: HandleRequestErrorCtx)` for the\n * Web `Request` shape. Returns a native `Response` directly instead of\n * mutating `res`. Same behavioral contract:\n *\n * 1. Auth-error detection via `instanceof AuthRequiredError` PLUS a\n * duck-type fallback (`code === 'AUTH_REQUIRED' && status === 401`)\n * — needed because Vite dev / vitest can produce duplicate class\n * identities, breaking `instanceof`.\n * 2. Envelope-shaped JSON body using `serverErrorToEnvelope` (G5 D3\n * boundary translation).\n * 3. Status code derived from envelope.code via `envelopeCodeToStatus`\n * mirror (already implemented inline in web-handler.ts; this slice\n * uses the same mapping table).\n *\n * **Difference vs IncomingMessage path:** the Web path's plugin runner\n * orchestration lives in `executeWebRequest`'s `runWithHooks` /\n * `runErrorHooks` (Phase G slice 1/N) — `handleWebRequestError` is the\n * leaf that builds the error Response WITHOUT touching plugin hooks.\n * Callers compose: `executeWebRequest` (or future Web execute pipeline)\n * catches a throw, calls `handleWebRequestError(err, { requestId })` to\n * build the Response, then routes through onError hooks separately.\n */\ninterface HandleWebRequestErrorCtx {\n requestId?: string\n}\n\nexport async function handleWebRequestError(\n err: unknown,\n ctx: HandleWebRequestErrorCtx = {},\n): Promise<Response> {\n // Lazy import to avoid pulling the full envelope translator into the\n // bundle for consumers who don't hit the error path. Same dynamic-\n // import pattern as web-handler.ts's parseBodyFull.\n const { serverErrorToEnvelope } = await import('../../core/contracts/server-error-to-envelope.js')\n\n // 1. Auth-error detection (shape-based guard from core/contracts)\n if (isAuthRequiredError(err)) {\n const authErr = err as { code?: string; message?: string; status?: number }\n return new Response(\n JSON.stringify({\n code: authErr.code ?? 'AUTH_REQUIRED',\n message: authErr.message ?? 'Authentication required',\n }),\n {\n status: authErr.status ?? 401,\n headers: {\n 'content-type': 'application/json',\n ...(ctx.requestId !== undefined ? { 'x-request-id': ctx.requestId } : {}),\n },\n },\n )\n }\n\n // 2. Envelope translation for everything else (G5 D3 boundary).\n const envelope = serverErrorToEnvelope(err)\n return new Response(JSON.stringify(envelope), {\n status: envelopeCodeToStatus(envelope.code),\n headers: {\n 'content-type': 'application/json',\n ...(ctx.requestId !== undefined ? { 'x-request-id': ctx.requestId } : {}),\n },\n })\n}\n\n// envelopeCodeToStatus extracted to core/contracts/envelope-code-to-status.ts\n// (architecture-remediation T1.2, 2026-06-12)\n","/**\n * Server-side action result serializer.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.3 + ADR D1.\n * Wraps `devalue.stringify` for success payloads (preserves Date/Set/URL/bigint\n * roundtrip) and JSON-encodes error envelopes for `ActionError` /\n * `ActionInputError`. Returns a `SerializedActionResult` discriminated union\n * consumed by the HTTP send layer (`action-execute.ts`).\n *\n * EC absorbed:\n * - EC-3 (response side): `responseBodySizeLimit` default 5 MB; throws\n * `ActionError({code:'PAYLOAD_TOO_LARGE'})` when the serialized body\n * exceeds the limit. Prevents handler-returns-100MB DoS.\n */\nimport { stringify as devalueStringify } from 'devalue'\n\nimport {\n ActionError,\n ActionInputError,\n type ActionResult,\n type SerializedActionResult,\n} from '../../core/contracts/action-protocol.js'\n\nconst DEFAULT_RESPONSE_BODY_SIZE_LIMIT = 5 * 1024 * 1024 // 5 MB\n\ninterface SerializeOptions {\n /**\n * Maximum allowed length of the serialized response body in BYTES (UTF-8\n * length of `body` string is checked, not the JS string length). Default\n * 5 MB. Configurable via `defineConfig({security:{responseBodySizeLimit}})`.\n */\n responseBodySizeLimit?: number\n}\n\n/**\n * Serialize an action result for the wire.\n *\n * - Success with data: `application/json+devalue` body via devalue.stringify\n * with a `URL` reviver for round-tripping URL instances.\n * - Success with `undefined` data: status 204 empty.\n * - Error: `application/json` JSON body with type discriminator\n * (`TheoActionError` or `TheoActionInputError`) + code + message\n * (+ fields/issues for input errors).\n *\n * Throws `ActionError({code:'PAYLOAD_TOO_LARGE'})` if the serialized body\n * exceeds the configured size limit (EC-3).\n *\n * Throws on `Response` instance as data (Astro guard — handler must return\n * plain JSON-serializable values, not Web Response objects).\n */\nexport function serializeActionResult(\n result: ActionResult,\n options: SerializeOptions = {},\n): SerializedActionResult {\n const limit = options.responseBodySizeLimit ?? DEFAULT_RESPONSE_BODY_SIZE_LIMIT\n\n if (result.error !== undefined) {\n const body =\n result.error instanceof ActionInputError\n ? JSON.stringify({\n type: result.error.type,\n code: result.error.code,\n message: result.error.message,\n issues: result.error.issues,\n fields: result.error.fields,\n })\n : JSON.stringify({\n type: result.error.type,\n code: result.error.code,\n message: result.error.message,\n })\n if (Buffer.byteLength(body, 'utf8') > limit) {\n throw new ActionError({\n code: 'PAYLOAD_TOO_LARGE',\n message: `Serialized error body exceeds limit (${limit} bytes)`,\n })\n }\n return {\n type: 'error',\n status: result.error.status,\n contentType: 'application/json',\n body,\n }\n }\n\n if (result.data === undefined) {\n return { type: 'empty', status: 204 }\n }\n\n if (result.data instanceof Response) {\n throw new ActionError({\n code: 'INTERNAL_SERVER_ERROR',\n message: 'Action handler cannot serialize Response objects — return plain data instead',\n })\n }\n\n let body: string\n try {\n body = devalueStringify(result.data, {\n URL: (value: unknown) => value instanceof URL && value.href,\n })\n } catch (e) {\n throw new ActionError({\n code: 'INTERNAL_SERVER_ERROR',\n message: `Action data not serializable: ${e instanceof Error ? e.message : String(e)}`,\n })\n }\n\n if (Buffer.byteLength(body, 'utf8') > limit) {\n throw new ActionError({\n code: 'PAYLOAD_TOO_LARGE',\n message: `Serialized response body exceeds limit (${limit} bytes)`,\n })\n }\n\n return {\n type: 'data',\n status: 200,\n contentType: 'application/json+devalue',\n body,\n }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { z } from 'zod'\n\nimport {\n ActionError,\n ActionInputError,\n type ActionErrorCode,\n} from '../../core/contracts/action-protocol.js'\nimport { parseRequestBody, type ParsedBody } from '../body-parser.js'\nimport type { PluginContext } from '../plugin-types.js'\nimport type { PluginRunner } from '../plugins/plugin-runner.js'\nimport type { LoadModule } from '../scan/module-loader.js'\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf, type CsrfMode, type DisallowedConfig } from '../security/csrf.js'\n\nimport { sendError } from './execute.js'\nimport { formDataToObject } from './form-data-to-object.js'\nimport { handleRequestError } from './handle-request-error.js'\nimport { runMiddlewareAndContext } from './middleware-runner.js'\nimport { incomingMessageToHandlerRequest } from './node-request.js'\nimport { serializeActionResult } from './serialize-action-result.js'\n\n// Universal dev gate — same IIFE pattern as track-agent-run (EC-11 tree-shake).\n// Both checks are statically replaceable by bundlers in prod build, so the\n// devtools dispatcher import is eliminated from prod bundles entirely.\nconst __IS_DEV = (() => {\n try {\n return (import.meta as { env?: { DEV?: boolean } }).env?.DEV === true\n } catch {\n return process.env.NODE_ENV !== 'production'\n }\n})()\n\n// Minimal Zod-shaped contract — we only need `safeParse`, not the whole API.\ninterface ZodLike {\n safeParse: (value: unknown) => {\n success: boolean\n data?: unknown\n // Derive the issue element type from `ZodError` — `z.ZodIssue` is deprecated in Zod 4.\n error?: { issues: z.ZodError['issues'] }\n }\n}\n\n// Shape of a `defineAction` export. Anchored by structural typing — we do\n// not import the action factory's return type to avoid module cycles, but\n// we do reject inputs that fail the structural test.\ninterface ActionConfig {\n input: ZodLike\n handler: (params: { input: unknown; ctx: unknown }) => unknown\n csrf?: false\n /** T1.3 sub-C: wire-protocol accept mode (defaults to 'json' when omitted). */\n accept?: 'form' | 'json'\n}\n\nfunction isActionConfig(value: unknown): value is ActionConfig {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n if (typeof candidate.handler !== 'function') return false\n const input = candidate.input as ZodLike | undefined\n return typeof input?.safeParse === 'function'\n}\n\nexport interface ExecuteActionOptions {\n filePath: string\n exportName: string\n req: IncomingMessage\n res: ServerResponse\n loadModule: LoadModule\n serverDir?: string\n requestId?: string\n pluginRunner?: PluginRunner\n csrfMode?: CsrfMode\n disallowed?: DisallowedConfig\n}\n\n// Backwards-compatible positional signature; the options-shape is the new\n// preferred entry point and what the framework uses internally.\n// eslint-disable-next-line max-params -- public API surface; existing callers pass positional args\nexport async function executeAction(\n filePath: string,\n exportName: string,\n req: IncomingMessage,\n res: ServerResponse,\n loadModule: LoadModule,\n serverDir?: string,\n requestId?: string,\n pluginRunner?: PluginRunner,\n csrfMode: CsrfMode = 'strict',\n disallowed?: DisallowedConfig,\n): Promise<void> {\n return executeActionWithOptions({\n filePath,\n exportName,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n csrfMode,\n disallowed,\n })\n}\n\nasync function loadActionConfig(\n loadModule: LoadModule,\n filePath: string,\n exportName: string,\n res: ServerResponse,\n requestId: string | undefined,\n): Promise<ActionConfig | null> {\n const mod = await loadModule(filePath)\n const exportedValue = mod[exportName]\n if (!isActionConfig(exportedValue)) {\n sendError(res, 'NOT_FOUND', `Action \"${exportName}\" not found`, 404, undefined, requestId)\n return null\n }\n return exportedValue\n}\n\ninterface CsrfActionCtx {\n actionConfig: ActionConfig\n csrfMode: CsrfMode\n disallowed: DisallowedConfig | undefined\n requestId: string | undefined\n}\n\nfunction enforceCsrfForAction(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: CsrfActionCtx,\n): boolean {\n if (ctx.actionConfig.csrf === false) return true\n const decision = enforceCsrf(\n req,\n ctx.csrfMode,\n {\n // T3.3 DRY — canonical dispatcher\n warn: dispatchCsrfWarn,\n path: req.url,\n },\n ctx.disallowed,\n )\n if (decision.allow) return true\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n ctx.requestId,\n )\n return false\n}\n\ninterface ActionPipeline {\n ctx: Record<string, unknown>\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n pluginRunner: PluginRunner | undefined\n serverDir: string | undefined\n loadModule: LoadModule\n req: IncomingMessage\n res: ServerResponse\n}\n\nasync function runPreHandlerPipeline(p: ActionPipeline): Promise<boolean> {\n if (p.serverDir) {\n const result = await runMiddlewareAndContext(p.req, p.res, p.loadModule, p.serverDir)\n if (result.aborted) return false\n Object.assign(p.ctx, (result.ctx ?? {}) as Record<string, unknown>)\n p.pluginRunner?.applyDecorations(p.ctx)\n }\n if (p.pluginRunner) {\n const preResult = await p.pluginRunner.runPreHandler(p.buildPluginCtx(p.ctx))\n if (preResult.shortCircuited) return false\n }\n return true\n}\n\nasync function readActionBody(\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string | undefined,\n actionConfig: ActionConfig,\n): Promise<{ ok: true; body: unknown } | { ok: false }> {\n try {\n const parsed = await parseRequestBody(req)\n const accept = actionConfig.accept ?? 'json'\n let body: unknown\n if (accept === 'form') {\n body = formDataToObject(\n synthesizeFormData(parsed),\n actionConfig.input as unknown as z.ZodObject<z.ZodRawShape>,\n )\n } else if (parsed.json !== undefined) {\n body = parsed.json\n } else {\n body = parsed.fields\n }\n return { ok: true, body }\n } catch (err) {\n sendError(res, 'VALIDATION_ERROR', (err as Error).message, 400, undefined, requestId)\n return { ok: false }\n }\n}\n\n/**\n * Build a FormData instance from the body-parser's `ParsedBody`. A scalar field\n * becomes one string entry and a repeated field becomes one entry per value;\n * files become Blob entries with the original filename. Used\n * only when `accept === 'form'` to feed `formDataToObject`.\n */\nfunction synthesizeFormData(parsed: ParsedBody): FormData {\n const fd = new FormData()\n for (const [name, value] of Object.entries(parsed.fields)) {\n // A repeated field arrives as an array (theokit#430). Appending it whole\n // would stringify to `'a,b'` — the same data loss the parser fix removed,\n // one layer later. `append` per value is what FormData already models, and\n // is what `formDataToObject` reads back with `getAll`.\n if (Array.isArray(value)) {\n for (const single of value) fd.append(name, single)\n } else {\n fd.append(name, value)\n }\n }\n for (const file of parsed.files) {\n const blob = new Blob([file.buffer as unknown as ArrayBuffer], {\n type: file.mimeType,\n })\n fd.append(file.fieldname, blob, file.filename)\n }\n return fd\n}\n\n/**\n * Write a serialized ActionResult to the response. Sets content-type, status,\n * and body. Returns void; caller must not write further after invoking.\n */\nfunction writeSerialized(\n res: ServerResponse,\n serialized: ReturnType<typeof serializeActionResult>,\n): void {\n if (serialized.type === 'empty') {\n res.statusCode = serialized.status\n res.end()\n return\n }\n res.statusCode = serialized.status\n res.setHeader('Content-Type', serialized.contentType)\n res.end(serialized.body)\n}\n\n/**\n * Dev-only telemetry: dispatch ACTION_CALL_ADD so the devtools Actions tab\n * (T5.1) can render this call. Tree-shaken in prod via __IS_DEV guard.\n * Mirrors trackAgentRun pattern. Never throws (swallow + log).\n */\nasync function emitActionCallTelemetry(\n name: string,\n startedAt: number,\n input: unknown,\n outcome: { status: 'success'; output: unknown } | { status: 'error'; error: ActionError },\n): Promise<void> {\n if (!__IS_DEV) return\n try {\n const mod = (await import('../../devtools/bridge/dispatcher.js')) as {\n dispatcher: {\n onActionCall: (r: {\n id: string\n timestamp: number\n name: string\n input: unknown\n output?: unknown\n error?: { code: string; message: string; fields?: Record<string, string[]> }\n durationMs: number\n status: 'success' | 'error'\n }) => void\n }\n }\n mod.dispatcher.onActionCall({\n // eslint-disable-next-line sonarjs/pseudo-random -- non-secret correlation id\n id: `act-${String(Date.now())}-${Math.random().toString(36).slice(2, 8)}`,\n timestamp: startedAt,\n name,\n input,\n output: outcome.status === 'success' ? outcome.output : undefined,\n error:\n outcome.status === 'error'\n ? {\n code: outcome.error.code,\n message: outcome.error.message,\n fields: outcome.error instanceof ActionInputError ? outcome.error.fields : undefined,\n }\n : undefined,\n durationMs: Date.now() - startedAt,\n status: outcome.status,\n })\n } catch {\n // devtools dispatcher missing in some prod-like bundle — silently skip\n }\n}\n\nasync function executeActionWithOptions(opts: ExecuteActionOptions): Promise<void> {\n const {\n filePath,\n exportName,\n req,\n res,\n loadModule,\n serverDir,\n requestId,\n pluginRunner,\n csrfMode = 'strict',\n disallowed,\n } = opts\n\n // ADR-0028 R3a / #119 — plugin hooks see a Web `Request` in every runtime (built once, shared across\n // buildPluginCtx calls). Actions have no request body on the handler ctx; hooks read headers/URL/method.\n const webRequest = incomingMessageToHandlerRequest(req)\n const buildPluginCtx = (ctxObj: Record<string, unknown>): PluginContext => ({\n request: webRequest,\n response: res,\n ctx: ctxObj,\n requestId: requestId ?? 'no-id',\n })\n\n let ctx: Record<string, unknown> = {}\n\n try {\n // 1. Only POST.\n if ((req.method ?? 'GET').toUpperCase() !== 'POST') {\n sendError(res, 'METHOD_NOT_ALLOWED', 'Actions only accept POST', 405, undefined, requestId)\n return\n }\n\n // 2. Plugin onRequest hook (parity with executeRoute).\n if (pluginRunner) {\n pluginRunner.applyDecorations(ctx)\n const onReqResult = await pluginRunner.runOnRequest(buildPluginCtx(ctx))\n if (onReqResult.shortCircuited) return\n }\n\n // 3. Load module + locate action export.\n const actionConfig = await loadActionConfig(loadModule, filePath, exportName, res, requestId)\n if (!actionConfig) return\n\n // 4. CSRF enforcement\n if (!enforceCsrfForAction(req, res, { actionConfig, csrfMode, disallowed, requestId })) {\n return\n }\n\n // 5+6. Middleware + context pipeline, then plugin preHandler.\n const pipeline: ActionPipeline = {\n ctx,\n buildPluginCtx,\n pluginRunner,\n serverDir,\n loadModule,\n req,\n res,\n }\n if (!(await runPreHandlerPipeline(pipeline))) return\n ctx = pipeline.ctx\n\n // 7. Parse body (supports JSON and multipart/form-data).\n const bodyOutcome = await readActionBody(req, res, requestId, actionConfig)\n if (!bodyOutcome.ok) return\n\n // T1.3 sub-C action name derived from exportName for telemetry.\n const actionName = exportName === 'default' ? deriveActionNameFromPath(filePath) : exportName\n const startedAt = Date.now()\n\n // 8. Validate input with Zod — failure → ActionInputError envelope (T0.1 + ADR D6).\n const result = actionConfig.input.safeParse(bodyOutcome.body)\n if (!result.success) {\n const inputErr = new ActionInputError(result.error?.issues ?? [])\n writeSerialized(res, serializeActionResult({ data: undefined, error: inputErr }))\n await emitActionCallTelemetry(actionName, startedAt, bodyOutcome.body, {\n status: 'error',\n error: inputErr,\n })\n return\n }\n\n await runActionHandler({\n actionConfig,\n actionName,\n startedAt,\n input: result.data,\n ctx,\n res,\n pluginRunner,\n buildPluginCtx,\n })\n } catch (err) {\n await handleActionError(err, { req, res, ctx, requestId, pluginRunner, buildPluginCtx })\n }\n}\n\n/** Derive a stable display name from filePath when handler exported as default. */\nfunction deriveActionNameFromPath(filePath: string): string {\n const base = filePath.split(/[\\\\/]/).pop() ?? 'unknown'\n return base.replace(/\\.[jt]sx?$/, '')\n}\n\n/**\n * Duck-typed guard for ActionError-shaped throws. Necessary because Vite SSR\n * may load multiple module copies of `core/contracts/action-protocol.ts` when\n * the fixture resolves `theokit/server` via a different path than the runtime\n * import — `err instanceof ActionError` then fails even though the user\n * legitimately threw `new ActionError(...)`.\n *\n * Server-only: only invoked on handler-thrown errors (trust boundary already\n * inside the action runtime). Not safe to use on client-parsed JSON — for\n * that path keep `isActionError` (the instanceof guard) from action-protocol.\n */\nfunction isActionErrorLike(err: unknown): err is ActionError {\n if (err === null || typeof err !== 'object') return false\n const obj = err as Record<string, unknown>\n return (\n (obj.type === 'TheoActionError' || obj.type === 'TheoActionInputError') &&\n typeof obj.code === 'string' &&\n typeof obj.status === 'number'\n )\n}\n\ninterface HandlerCtx {\n actionConfig: ActionConfig\n actionName: string\n startedAt: number\n input: unknown\n ctx: Record<string, unknown>\n res: ServerResponse\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\nasync function runActionHandler(args: HandlerCtx): Promise<void> {\n try {\n const handlerResult = await args.actionConfig.handler({ input: args.input, ctx: args.ctx })\n // T1.3 sub-C — wire devalue serialization (ADR D1). Undefined → 204; data → 200 + json+devalue.\n writeSerialized(args.res, serializeActionResult({ data: handlerResult, error: undefined }))\n if (args.pluginRunner) {\n await args.pluginRunner.runOnResponse(args.buildPluginCtx(args.ctx))\n }\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'success',\n output: handlerResult,\n })\n } catch (err) {\n // Handler-thrown ActionError → use the typed envelope; other throws bubble\n // up to executeActionWithOptions for handleActionError fallback chain.\n // Duck-type the `type` discriminator (not instanceof): Vite SSR can load\n // multiple module copies of action-protocol.ts when fixture and runtime\n // resolve different paths; `err instanceof ActionError` then fails even\n // when the handler legitimately threw via `new ActionError(...)`.\n if (isActionErrorLike(err)) {\n writeSerialized(args.res, serializeActionResult({ data: undefined, error: err }))\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'error',\n error: err,\n })\n return\n }\n // Wrap unknown throws as INTERNAL_SERVER_ERROR with the original message\n // preserved for telemetry; production error handler still consumes via\n // handleActionError fallback (preserves AuthRequiredError duck-type).\n const wrapped = new ActionError({\n code: 'INTERNAL_SERVER_ERROR' satisfies ActionErrorCode,\n message: err instanceof Error ? err.message : 'Action handler threw',\n })\n await emitActionCallTelemetry(args.actionName, args.startedAt, args.input, {\n status: 'error',\n error: wrapped,\n })\n throw err\n }\n}\n\ninterface ActionErrorCtx {\n req: IncomingMessage\n res: ServerResponse\n ctx: Record<string, unknown>\n requestId: string | undefined\n pluginRunner: PluginRunner | undefined\n buildPluginCtx: (ctxObj: Record<string, unknown>) => PluginContext\n}\n\n// T3.4 (PV-9 DRY): delegate to the shared `handleRequestError` helper.\n// Adds the duck-type AuthRequiredError fallback (latent bug fix — was\n// missing from action-execute, present in execute).\nasync function handleActionError(err: unknown, c: ActionErrorCtx): Promise<void> {\n return handleRequestError(err, {\n req: c.req,\n res: c.res,\n requestId: c.requestId,\n pluginRunner: c.pluginRunner,\n buildPluginCtx: c.buildPluginCtx,\n })\n}\n","/**\n * T1.4 — Server-side batch handler.\n *\n * Receives `{ requests: [...] }` POSTed to `/api/__theo_batch__` and returns\n * `{ results: [...] }` with per-item error isolation. EC-2: items cannot\n * override auth/forwarded headers (would be a session-bypass vector).\n */\n\nimport { z } from 'zod'\n\nexport const STRIPPED_HEADERS = [\n 'authorization',\n 'cookie',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n 'x-real-ip',\n 'host',\n] as const\n\nexport const BATCH_PATH = '/api/__theo_batch__'\nconst DEFAULT_MAX_BATCH = 32\n\nexport class BatchPathConflictError extends Error {\n constructor(path: string) {\n super(\n `Server route conflicts with reserved batch path ${path}. ` +\n `Rename the route or disable batching in theo.config.ts.`,\n )\n this.name = 'BatchPathConflictError'\n }\n}\n\nconst batchRequestSchema = z.object({\n path: z.string().min(1),\n method: z.string().min(1),\n query: z.record(z.string(), z.unknown()).optional(),\n body: z.unknown().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n})\n\nconst batchPayloadSchema = z.object({\n requests: z.array(batchRequestSchema).min(1),\n})\n\nexport type BatchRequestItem = z.infer<typeof batchRequestSchema>\nexport type BatchPayload = z.infer<typeof batchPayloadSchema>\n\nexport type BatchExecuteFn = (\n req: BatchRequestItem,\n) => Promise<{ data: unknown } | { error: { message: string; code?: string } }>\n\nexport interface HandleBatchOptions {\n execute: BatchExecuteFn\n /** Max number of items per batch. Default 32. */\n max?: number\n /** Outer-request headers that override per-item headers in STRIPPED_HEADERS. */\n outerHeaders?: Record<string, string>\n}\n\nexport type BatchResultItem = { data: unknown } | { error: { message: string; code?: string } }\n\nexport interface BatchResponse {\n results: BatchResultItem[]\n}\n\n/**\n * Sanitize a per-item header object: keys in STRIPPED_HEADERS are removed,\n * then the outer request's values for those keys are layered on top so that\n * downstream middlewares see the real session/auth headers.\n */\nfunction sanitizeItemHeaders(\n itemHeaders: Record<string, string> | undefined,\n outerHeaders: Record<string, string> | undefined,\n): Record<string, string> {\n const out: Record<string, string> = {}\n if (itemHeaders) {\n for (const [k, v] of Object.entries(itemHeaders)) {\n const lower = k.toLowerCase()\n if (!(STRIPPED_HEADERS as readonly string[]).includes(lower)) {\n out[lower] = v\n }\n }\n }\n if (outerHeaders) {\n for (const stripped of STRIPPED_HEADERS) {\n // `Object.hasOwn` defends against missing keys without triggering\n // `no-unnecessary-condition` (TypeScript types `outerHeaders` keys\n // as defined; `hasOwn` keeps the conditional honest at runtime).\n if (Object.hasOwn(outerHeaders, stripped)) {\n out[stripped] = outerHeaders[stripped]\n }\n }\n }\n return out\n}\n\n/**\n * Validate + execute a batch request.\n *\n * CR-028 fix: previously the signature was `payload: BatchPayload`,\n * suggesting the caller had already validated. In reality `api-middleware`\n * passes `JSON.parse(rawBody) as BatchPayload` — an unsafe cast over raw\n * HTTP input. We widen the input type to `unknown` so the type system\n * forces validation, then run Zod once at this single trust boundary.\n */\nexport async function handleBatchRequest(\n payload: unknown,\n options: HandleBatchOptions,\n): Promise<BatchResponse> {\n const parsed = batchPayloadSchema.parse(payload)\n const max = options.max ?? DEFAULT_MAX_BATCH\n if (parsed.requests.length > max) {\n throw new Error(`Batch size ${parsed.requests.length} exceeds max ${max}`)\n }\n\n const results: BatchResultItem[] = []\n for (const item of parsed.requests) {\n const sanitized: BatchRequestItem = {\n ...item,\n headers: sanitizeItemHeaders(item.headers, options.outerHeaders),\n }\n try {\n const r = await options.execute(sanitized)\n results.push(r)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n results.push({ error: { message } })\n }\n }\n return { results }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\n/**\n * T1.2 — CORS middleware.\n *\n * Single global middleware that runs FIRST in the request pipeline:\n * CORS preflight → rate limit → CSRF → security headers → handler\n *\n * Preflight (`OPTIONS` with `Access-Control-Request-Method`) is handled\n * by `handlePreflight`, which short-circuits the response with 204 +\n * Access-Control-* headers.\n *\n * Non-preflight requests pass through; `applyHeaders` adds\n * `Access-Control-Allow-Origin` (echoing the request's Origin),\n * `Access-Control-Expose-Headers`, and `Access-Control-Allow-Credentials`.\n *\n * Per ADR D3: preflight responses are deterministic and only the matched\n * origin is echoed back (never `'*'` when credentials are enabled —\n * required by the CORS spec).\n */\n\n// `'*'` is conceptually distinct from a regular host string (it means\n// \"any origin\"), but TypeScript-wise it is just `string`, so we collapse\n// the union and document the wildcard via the type's name. Callers should\n// still pass the literal `'*'` to mean \"allow anywhere\" for readability.\nexport type CorsOrigin =\n | string\n | RegExp\n | readonly (string | RegExp)[]\n | ((origin: string) => boolean)\n\nexport interface CorsConfig {\n origins: CorsOrigin\n methods?: readonly ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD')[]\n allowedHeaders?: readonly string[]\n exposedHeaders?: readonly string[]\n credentials?: boolean\n maxAge?: number\n}\n\nexport interface CorsHandler {\n handlePreflight(req: IncomingMessage, res: ServerResponse): boolean\n applyHeaders(req: IncomingMessage, res: ServerResponse): void\n}\n\nconst DEFAULT_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'] as const\nconst DEFAULT_ALLOWED_HEADERS = ['Content-Type', 'X-Theo-Action', 'Authorization'] as const\nconst DEFAULT_MAX_AGE = 600\n\n/**\n * Read the request Origin header. Per Node typing, it can be a string,\n * string[] (proxy doubled), or undefined. We take the FIRST non-empty\n * value (consistent with `csrf.ts:121-122`).\n */\nfunction readOrigin(req: IncomingMessage): string | undefined {\n const raw = req.headers.origin\n if (raw === undefined) return undefined\n if (Array.isArray(raw)) {\n return raw.find((v): v is string => typeof v === 'string' && v.length > 0)\n }\n return raw\n}\n\n/**\n * Test whether `origin` is allowed by `allowed`. Pure function — no I/O.\n *\n * EC-8: callback variants that throw are fail-closed (deny). Without\n * this, a transient datastore outage would silently widen CORS during\n * the failure window.\n */\nexport function matchesOrigin(origin: string, allowed: CorsOrigin): boolean {\n if (allowed === '*') return true\n if (typeof allowed === 'string') return origin === allowed\n if (allowed instanceof RegExp) {\n allowed.lastIndex = 0\n return allowed.test(origin)\n }\n if (Array.isArray(allowed)) {\n for (const entry of allowed) {\n if (typeof entry === 'string' && origin === entry) return true\n if (entry instanceof RegExp) {\n entry.lastIndex = 0\n if (entry.test(origin)) return true\n }\n }\n return false\n }\n if (typeof allowed === 'function') {\n // EC-8: fail-closed on any throw\n try {\n return allowed(origin)\n } catch {\n return false\n }\n }\n return false\n}\n\nexport function createCorsHandler(config: CorsConfig): CorsHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflight(req, res) {\n if (req.method !== 'OPTIONS') return false\n const acMethod = req.headers['access-control-request-method']\n if (!acMethod) return false\n const origin = readOrigin(req)\n if (!origin) return false\n\n if (!matchesOrigin(origin, config.origins)) {\n res.statusCode = 403\n res.end()\n return true\n }\n\n // Echo the matched origin (NEVER '*' when credentials are enabled —\n // browsers reject wildcard responses with credentials per CORS spec).\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Access-Control-Allow-Methods', methods.join(', '))\n res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '))\n res.setHeader('Access-Control-Max-Age', maxAge)\n // Mark the response as origin-varying so caches don't poison\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n res.statusCode = 204\n res.end()\n return true\n },\n\n applyHeaders(req, res) {\n const origin = readOrigin(req)\n if (!origin) return\n if (!matchesOrigin(origin, config.origins)) return\n\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders && config.exposedHeaders.length > 0) {\n res.setHeader('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n\n/**\n * T5a.2 Phase B slice 5/6 — Web-Standards CORS handler.\n *\n * Mirror of `createCorsHandler(config): CorsHandler` for the Web `Request`\n * shape. Same `CorsConfig`, same `matchesOrigin` logic (pure helper\n * already), same security guarantees (echo matched origin only — never\n * `'*'` when credentials enabled; EC-8 fail-closed on callback throw).\n *\n * Signature differences vs the IncomingMessage pair:\n * - `handlePreflightRequest(request, config): Response | null` — returns\n * `Response` when this is a CORS preflight; `null` when not. Caller\n * short-circuits accordingly (same control-flow semantic as boolean).\n * - `applyCorsHeaders(request, target, config): void` — mutates a\n * `Headers` instance in place. Caller passes the headers they're\n * building for their Response.\n */\nexport interface CorsWebHandler {\n handlePreflightRequest(request: Request): Response | null\n applyCorsHeaders(request: Request, target: Headers): void\n}\n\nexport function createCorsWebHandler(config: CorsConfig): CorsWebHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflightRequest(request) {\n if (request.method !== 'OPTIONS') return null\n const acMethod = request.headers.get('access-control-request-method')\n if (acMethod === null || acMethod.length === 0) return null\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return null\n\n if (!matchesOrigin(origin, config.origins)) {\n return new Response(null, { status: 403 })\n }\n\n // Echo matched origin only (security: never `'*'` when credentials\n // enabled — browsers reject per CORS spec).\n const headers = new Headers({\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': methods.join(', '),\n 'Access-Control-Allow-Headers': allowedHeaders.join(', '),\n 'Access-Control-Max-Age': maxAge,\n Vary: 'Origin',\n })\n if (credentials) headers.set('Access-Control-Allow-Credentials', 'true')\n return new Response(null, { status: 204, headers })\n },\n\n applyCorsHeaders(request, target) {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return\n if (!matchesOrigin(origin, config.origins)) return\n\n target.set('Access-Control-Allow-Origin', origin)\n target.set('Vary', 'Origin')\n if (credentials) target.set('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders !== undefined && config.exposedHeaders.length > 0) {\n target.set('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n","export function levenshtein(a: string, b: string): number {\n const m = a.length\n const n = b.length\n const dp: number[][] = Array.from({ length: m + 1 }, () =>\n Array.from<number>({ length: n + 1 }).fill(0),\n )\n\n for (let i = 0; i <= m; i++) dp[i][0] = i\n for (let j = 0; j <= n; j++) dp[0][j] = j\n\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n\n return dp[m][n]\n}\n\nexport function findSuggestion(\n input: string,\n candidates: string[],\n maxDistance = 3,\n): string | null {\n let best: string | null = null\n let bestDist = maxDistance + 1\n\n for (const c of candidates) {\n const d = levenshtein(input, c)\n if (d < bestDist) {\n bestDist = d\n best = c\n }\n }\n\n return best\n}\n","import type {\n HookName,\n HookResult,\n OnErrorHook,\n OnRequestHook,\n OnResponseHook,\n PluginContext,\n PluginErrorContext,\n PreHandlerHook,\n RunHookOptions,\n TheoApp,\n TheoPlugin,\n} from '../plugin-types.js'\n\nexport class DuplicatePluginError extends Error {\n constructor(name: string) {\n super(`Plugin \"${name}\" is already registered.`)\n this.name = 'DuplicatePluginError'\n }\n}\n\n/**\n * @deprecated Per T3.1 (C1 plugin scope encapsulation) — duplicate decoration\n * keys across sibling plugins are now PERMITTED because each plugin gets its\n * own child scope via `Object.create(parent)` (Fastify pattern, ADR-0028\n * blueprint D1). This class is retained for one minor cycle so consumers who\n * `instanceof DuplicateDecorationError` continue to compile; the constructor\n * is no longer reachable from `PluginRunner.register()`. Removal scheduled\n * for 0.x+2 per CHANGELOG.\n */\nexport class DuplicateDecorationError extends Error {\n constructor(key: string, existingPlugin: string, newPlugin: string) {\n super(\n `Plugin \"${newPlugin}\" tried to decorate ctx.${key}, but it is already declared by plugin \"${existingPlugin}\".`,\n )\n this.name = 'DuplicateDecorationError'\n }\n}\n\n/**\n * Per-plugin scope built by `Object.create(parentApp)` at `register()` time\n * (T3.1 / Fastify `plugin-override.js:38` pattern). Each plugin's\n * `decorateRequest` calls populate THIS scope's `decorations` map only —\n * parent + sibling scopes are isolated through the JavaScript prototype chain.\n */\ninterface PluginScope {\n /** The child TheoApp instance whose proto chain points at `parentApp`. */\n app: TheoApp\n /** Per-plugin decorations map. Cross-plugin key collision is permitted. */\n decorations: Map<string, unknown>\n}\n\nexport class PluginRunner {\n private plugins = new Set<string>()\n private pluginScopes = new Map<string, PluginScope>()\n private onRequestHooks: OnRequestHook[] = []\n private preHandlerHooks: PreHandlerHook[] = []\n private onResponseHooks: OnResponseHook[] = []\n private onErrorHooks: OnErrorHook[] = []\n\n /**\n * Parent app — proto-chain root for all child scopes. Has its OWN empty\n * decorations map (parent never receives `decorateRequest` calls under\n * the T3.1 contract; only child scopes do).\n */\n private parentDecorations = new Map<string, unknown>()\n private parentApp: TheoApp = this.buildParentAppFacade()\n\n has(name: string): boolean {\n return this.plugins.has(name)\n }\n\n /**\n * Per T3.1 (C1 plugin scope encapsulation):\n * 1. Reserve the plugin name (still rejects duplicates).\n * 2. Build a CHILD TheoApp via `Object.create(parentApp)` — Fastify\n * `plugin-override.js:38` pattern. The child's own `decorateRequest`\n * populates per-scope `decorations`; the child's `addHook` still\n * forwards into the shared hook lists (hooks ARE process-global —\n * only decorations are scoped, mirroring Fastify's decoration vs\n * hook semantics).\n * 3. Invoke `plugin.register(childApp)`.\n *\n * Cross-plugin decoration-key collisions are PERMITTED (per blueprint\n * D1). The legacy `DuplicateDecorationError` is no longer thrown.\n */\n async register(plugin: TheoPlugin): Promise<void> {\n if (this.plugins.has(plugin.name)) {\n throw new DuplicatePluginError(plugin.name)\n }\n // Add to registry FIRST so duplicate detection works even if register throws.\n this.plugins.add(plugin.name)\n\n const scope = this.buildPluginScope(plugin.name)\n this.pluginScopes.set(plugin.name, scope)\n\n try {\n await plugin.register(scope.app)\n } catch (err) {\n // Roll back partial registration so a failed plugin does not leave\n // half-mounted state (T1.1 BDD \"error scenario: plugin throws in\n // register → parent recovery is clean\").\n this.plugins.delete(plugin.name)\n this.pluginScopes.delete(plugin.name)\n throw err\n }\n }\n\n /**\n * Build the parent app facade. Hooks forward to shared lists.\n * `decorateRequest` writes into the parent decorations map — used only\n * if a future consumer registers a non-plugin \"app-level\" decoration\n * directly. T3.1 contract: plugins decorate ONLY through child scopes.\n */\n private buildParentAppFacade(): TheoApp {\n const facade: TheoApp = {\n addHook: (name: HookName, fn: unknown) => {\n this.routeHookByName(name, fn)\n },\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the per-decoration type for consumers\n decorateRequest: <T>(key: string, value: T) => {\n this.parentDecorations.set(key, value)\n },\n }\n return facade\n }\n\n /**\n * Build a child scope via `Object.create(parentApp)` so the child\n * inherits the parent's facade methods through the prototype chain.\n * Then override `decorateRequest` on the child instance so writes\n * land in the per-scope `decorations` map (parent is NOT mutated).\n */\n private buildPluginScope(_pluginName: string): PluginScope {\n const decorations = new Map<string, unknown>()\n const childApp: TheoApp = Object.create(this.parentApp) as TheoApp\n // Override decorateRequest on the child instance — parent's facade\n // method stays untouched, so `getParentApp().decorateRequest` still\n // writes to parentDecorations. This is the canonical Fastify pattern.\n // `_pluginName` reserved for future per-scope diagnostics (underscore\n // prefix marks intentional unused param per project lint convention).\n Object.defineProperty(childApp, 'decorateRequest', {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the per-decoration type for consumers\n value: <T>(key: string, value: T) => {\n if (typeof key !== 'string') {\n throw new TypeError(\n `decorateRequest: invalid key (expected string, got ${typeof key}). ` +\n `Plugin authors MUST pass string keys.`,\n )\n }\n decorations.set(key, value)\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n // Expose `decorations` on the child instance so `getPluginScope()`\n // consumers (devtools, tests) can introspect without touching this\n // private map. Read-only property — the JS prototype chain rule means\n // child.decorations shadows any parent.decorations the proto exposes.\n Object.defineProperty(childApp, 'decorations', {\n get: () => Object.fromEntries(decorations),\n enumerable: false,\n configurable: false,\n })\n return { app: childApp, decorations }\n }\n\n private routeHookByName(name: HookName, fn: unknown): void {\n switch (name) {\n case 'onRequest':\n this.onRequestHooks.push(fn as OnRequestHook)\n return\n case 'preHandler':\n this.preHandlerHooks.push(fn as PreHandlerHook)\n return\n case 'onResponse':\n this.onResponseHooks.push(fn as OnResponseHook)\n return\n case 'onError':\n this.onErrorHooks.push(fn as OnErrorHook)\n return\n }\n }\n\n /**\n * Apply ALL plugin scopes' decorations into the request ctx. Per T3.1,\n * sibling plugins MAY decorate the same key — last-writer-wins at apply\n * time (ordering = registration order). This keeps the legacy\n * `ctx.<key>` flat surface working for consumers that already aggregate\n * decorations into a single bag.\n */\n applyDecorations(ctx: Record<string, unknown>): void {\n for (const scope of this.pluginScopes.values()) {\n for (const [key, value] of scope.decorations.entries()) {\n ctx[key] = value\n }\n }\n }\n\n /**\n * Apply ONLY one plugin's scoped decorations into `target`. Used by\n * the T1.1 RED-3 test (sibling isolation proof) and by future scope-aware\n * dispatch paths. Throws if the plugin name isn't registered.\n */\n applyScopedDecorations(pluginName: string, target: Record<string, unknown>): void {\n const scope = this.pluginScopes.get(pluginName)\n if (!scope) throw new Error(`PluginRunner: unknown plugin \"${pluginName}\"`)\n for (const [key, value] of scope.decorations.entries()) {\n target[key] = value\n }\n }\n\n /** T1.1 RED-1/RED-4 introspection: returns the child TheoApp built for `pluginName`. */\n getPluginScope(pluginName: string): TheoApp {\n const scope = this.pluginScopes.get(pluginName)\n if (!scope) throw new Error(`PluginRunner: unknown plugin \"${pluginName}\"`)\n return scope.app\n }\n\n /** T1.1 RED-4: returns the parent TheoApp (root of every child's proto chain). */\n getParentApp(): TheoApp {\n return this.parentApp\n }\n\n /** T1.1 RED-2: returns the parent's decorations map (NEVER touched by plugin decorate calls under T3.1 contract). */\n getParentDecorations(): Map<string, unknown> {\n return this.parentDecorations\n }\n\n async runOnRequest(ctx: PluginContext): Promise<HookResult> {\n return this.runHookList(this.onRequestHooks, ctx)\n }\n\n async runPreHandler(ctx: PluginContext): Promise<HookResult> {\n return this.runHookList(this.preHandlerHooks, ctx)\n }\n\n async runOnResponse(ctx: PluginContext, options: RunHookOptions = {}): Promise<HookResult> {\n return this.runHookList(this.onResponseHooks, ctx, options)\n }\n\n /**\n * Run all onError hooks. Swallows errors thrown inside hooks themselves to\n * prevent recursion (an error in an error handler must not trigger onError\n * again).\n */\n async runOnError(ctx: PluginContext, error: unknown): Promise<HookResult> {\n const errorCtx: PluginErrorContext = { ...ctx, error }\n for (const hook of this.onErrorHooks) {\n try {\n await hook(errorCtx)\n } catch (innerErr) {\n // EC-9 + onError-safety: swallow to avoid recursion. Diagnostic\n // surface only — error context is preserved via innerErr arg.\n console.error(\n `[plugin-runner] onError hook threw; suppressed to avoid recursion:`,\n innerErr,\n )\n }\n }\n return { shortCircuited: false }\n }\n\n private async runHookList(\n hooks: readonly ((ctx: PluginContext) => void | Promise<void>)[],\n ctx: PluginContext,\n options: RunHookOptions = {},\n ): Promise<HookResult> {\n for (const hook of hooks) {\n try {\n await hook(ctx)\n } catch (err) {\n if (options.inErrorPath) {\n // EC-9: we're already handling an error; do NOT trigger onError again.\n // Diagnostic surface only — original error preserved via err arg.\n console.error(`[plugin-runner] hook threw during error path; suppressed (EC-9):`, err)\n continue\n }\n throw err\n }\n if (ctx.response.writableEnded || ctx.response.headersSent) {\n return { shortCircuited: true }\n }\n }\n return { shortCircuited: false }\n }\n}\n","import type { TheoPlugin } from '../plugin-types.js'\n\nimport { PluginRunner } from './plugin-runner.js'\n\nexport class InvalidPluginShapeError extends Error {\n constructor(index: number, reason: string) {\n super(`plugins[${index}] is not a valid TheoPlugin: ${reason}`)\n this.name = 'InvalidPluginShapeError'\n }\n}\n\nfunction isPlugin(value: unknown, index: number): value is TheoPlugin {\n if (value == null || typeof value !== 'object') {\n throw new InvalidPluginShapeError(index, 'expected an object')\n }\n const v = value as Record<string, unknown>\n if (typeof v.name !== 'string' || v.name.length === 0) {\n throw new InvalidPluginShapeError(index, 'missing \"name\" string')\n }\n if (typeof v.register !== 'function') {\n throw new InvalidPluginShapeError(index, 'missing \"register\" function')\n }\n return true\n}\n\n/**\n * Build a PluginRunner from a list of plugins typically declared in\n * `theo.config.ts` under the `plugins` field. Returns `undefined` when no\n * plugins are configured so callers can pass `undefined` to `executeRoute`\n * and preserve the zero-overhead path.\n */\nexport async function createPluginRunnerFromConfig(\n plugins: unknown,\n): Promise<PluginRunner | undefined> {\n if (plugins == null) return undefined\n if (!Array.isArray(plugins)) return undefined\n if (plugins.length === 0) return undefined\n\n const runner = new PluginRunner()\n const pluginsArray: unknown[] = plugins\n for (let i = 0; i < pluginsArray.length; i++) {\n const candidate: unknown = pluginsArray[i]\n if (!isPlugin(candidate, i)) {\n // Unreachable in practice — `isPlugin` throws on invalid input.\n // The branch exists to narrow `candidate` to TheoPlugin below.\n continue\n }\n await runner.register(candidate)\n }\n return runner\n}\n","/**\n * T2.1 — RateLimitStore interface.\n *\n * Pluggable backend for the rate limiter. The default `InMemoryStore`\n * preserves current single-instance behavior. Multi-instance deployments\n * (TheoCloud canary, K8s replicas) opt in to a distributed adapter\n * (Redis, Cloudflare KV) without bloating single-instance apps.\n *\n * Contract per ADR D1:\n * - `incr` is atomic — concurrent calls for the same key both observe\n * the same `resetAt` and increment count by 1.\n * - `get` returns `null` for expired entries (not just absent — checks\n * `now > resetAt`).\n * - `reset` removes the key entirely; next `incr` creates fresh.\n *\n * Async signature is honest about Redis adapters even though in-memory\n * implementation is synchronous. Callers MUST await.\n */\n\nexport interface RateLimitState {\n /** Number of requests counted in the current window. */\n count: number\n /** Absolute timestamp (ms since epoch) when this window expires. */\n resetAt: number\n}\n\nexport interface RateLimitStore {\n /**\n * Atomic increment-and-get. If the key is missing OR the previous\n * window expired (`now >= resetAt`), create with `count=1, resetAt=now+windowMs`.\n * Otherwise increment count by 1, preserving the original resetAt.\n */\n incr(key: string, windowMs: number): Promise<RateLimitState>\n\n /** Read current state. Returns `null` for missing or expired entries. */\n get(key: string): Promise<RateLimitState | null>\n\n /** Remove a key. Used by login throttling on success (T6.1). */\n reset(key: string): Promise<void>\n}\n\n/**\n * Default in-memory store. Backed by `Map<string, RateLimitState>`.\n *\n * GC: every 1000 `incr` calls, expired entries are removed. Pathological\n * key explosion is bounded by `MAX_ENTRIES` (LRU-evict oldest insertion).\n *\n * Single-thread by virtue of Node's event loop — `incr` is atomic at the\n * JavaScript level (no preemption between Map.get and Map.set).\n */\nexport class InMemoryStore implements RateLimitStore {\n private store = new Map<string, RateLimitState>()\n /** Bound the map to prevent unbounded growth from pathological inputs. */\n static readonly MAX_ENTRIES = 100_000\n /** GC sweep interval, milliseconds. */\n static readonly GC_INTERVAL_MS = 30_000\n\n private gcTimer: ReturnType<typeof setInterval> | null = null\n\n constructor() {\n // CR-007 fix: GC runs on a timer OUTSIDE the request hot path.\n // Pre-fix, every 1000th `incrSync` triggered a synchronous Map sweep\n // of up to 100K entries — an attacker with diverse client IPs could\n // keep the Map full and force a blocking sweep predictably.\n if (typeof setInterval !== 'undefined') {\n const timer = setInterval(() => {\n this.sweepExpired()\n }, InMemoryStore.GC_INTERVAL_MS)\n this.gcTimer = timer\n // Allow the process to exit even with the timer pending. `unref` is\n // Node-only; not present on browser/Cloudflare `setInterval`.\n const maybeUnref = (timer as { unref?: () => void }).unref\n if (typeof maybeUnref === 'function') maybeUnref.call(timer)\n }\n }\n\n /**\n * Synchronous fast-path used by the legacy sync `createRateLimiter`\n * surface (`api-middleware.ts` is sync). The async `incr` delegates to\n * this for in-memory; external adapters override `incr` directly.\n */\n incrSync(key: string, windowMs: number): RateLimitState {\n if (!Number.isFinite(windowMs) || windowMs <= 0) {\n throw new Error(\n `InMemoryStore.incr: windowMs must be a positive finite number (got ${windowMs})`,\n )\n }\n const now = Date.now()\n\n // Bounded LRU-ish: when over cap, drop oldest insertion.\n if (this.store.size >= InMemoryStore.MAX_ENTRIES) {\n const first = this.store.keys().next().value\n if (first !== undefined) this.store.delete(first)\n }\n\n const entry = this.store.get(key)\n if (!entry || now >= entry.resetAt) {\n const fresh = { count: 1, resetAt: now + windowMs }\n this.store.set(key, fresh)\n return { ...fresh }\n }\n entry.count++\n return { count: entry.count, resetAt: entry.resetAt }\n }\n\n /** Sweep expired entries. Called by the GC timer; safe to call manually. */\n sweepExpired(): void {\n const now = Date.now()\n for (const [k, v] of this.store) {\n if (v.resetAt <= now) this.store.delete(k)\n }\n }\n\n /**\n * Stop the GC timer. Call from tests or when discarding the store. After\n * `dispose`, the store still works but no longer auto-sweeps.\n */\n dispose(): void {\n if (this.gcTimer) {\n clearInterval(this.gcTimer)\n this.gcTimer = null\n }\n }\n\n // The async surface is required by the `RateLimitStore` interface\n // (Redis/etc. adapters are inherently async). For the in-memory case\n // we just adapt the sync implementations to Promises.\n // eslint-disable-next-line @typescript-eslint/require-await -- interface contract: async return\n async incr(key: string, windowMs: number): Promise<RateLimitState> {\n return this.incrSync(key, windowMs)\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await -- interface contract: async return\n async get(key: string): Promise<RateLimitState | null> {\n const now = Date.now()\n const entry = this.store.get(key)\n if (!entry) return null\n if (now >= entry.resetAt) return null\n return { count: entry.count, resetAt: entry.resetAt }\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await -- interface contract: async return\n async reset(key: string): Promise<void> {\n this.store.delete(key)\n }\n}\n","import type { IncomingMessage } from 'node:http'\n\nimport { InMemoryStore, type RateLimitStore } from './rate-limit-store.js'\n\n/**\n * Rate limit configuration — basic single-bucket shape. Per ADR D2, the\n * per-route + per-user variant is layered on top via T2.2; this base\n * struct is the smallest unit.\n */\nexport interface RateLimitConfig {\n windowMs: number\n max: number\n}\n\nexport interface RateLimitResult {\n limited: boolean\n headers: Record<string, string>\n}\n\n/**\n * Create a rate limiter that consumes a pluggable `RateLimitStore`.\n *\n * Backwards-compatible signature: callers passing only `config` get the\n * default `InMemoryStore`. Distributed deployments pass a Redis adapter\n * (or any other `RateLimitStore` implementation) via `opts.store`.\n *\n * T2.1: synchronous return for back-compat with the current\n * `api-middleware.ts` integration point. The async store contract is\n * exercised lazily — we use a sync fast-path against the in-memory store\n * (single-thread JS makes this safe). External stores remain async and\n * would require a different async wrapper at the middleware layer.\n */\nexport function createRateLimiter(config: RateLimitConfig, opts: { store?: RateLimitStore } = {}) {\n const store = opts.store ?? new InMemoryStore()\n const isInMemory = store instanceof InMemoryStore\n\n return function checkRateLimit(req: IncomingMessage): RateLimitResult {\n // `req.socket` is typed as always-present in Node typings; defensive\n // for test doubles (object literals without `socket`).\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- defensive for test doubles\n const key = req.socket?.remoteAddress ?? 'unknown'\n\n if (isInMemory) {\n // Sync fast-path: the in-memory store exposes a sync incr.\n const state = store.incrSync(key, config.windowMs)\n return resultFromState(state, config)\n }\n\n // External stores are NOT supported via this synchronous facade in\n // 0.3.x. Users plugging Redis adapters today must wire it via a\n // dedicated async middleware path (out-of-scope for T2.1; tracked\n // for the follow-up `@theokit/rate-limit-redis` package).\n throw new Error(\n 'createRateLimiter: async RateLimitStore implementations are not supported by this sync facade. ' +\n 'Use the InMemoryStore default or build a custom middleware around the async store directly.',\n )\n }\n}\n\nfunction resultFromState(\n state: { count: number; resetAt: number },\n config: RateLimitConfig,\n): RateLimitResult {\n if (state.count > config.max) {\n const retryAfter = Math.ceil((state.resetAt - Date.now()) / 1000)\n return {\n limited: true,\n headers: {\n 'X-RateLimit-Limit': String(config.max),\n 'X-RateLimit-Remaining': '0',\n 'Retry-After': String(retryAfter),\n },\n }\n }\n return {\n limited: false,\n headers: {\n 'X-RateLimit-Limit': String(config.max),\n 'X-RateLimit-Remaining': String(Math.max(0, config.max - state.count)),\n },\n }\n}\n\n/**\n * T5a.2 Phase D slice 2/3 — Web-Standards single-bucket rate limiter.\n *\n * Mirror of `createRateLimiter(config, opts)` returning a checker that\n * accepts `(clientIp: string)` instead of `(req: IncomingMessage)`. Web\n * `Request` has no `req.socket.remoteAddress` — the IP is resolved by\n * the caller per-runtime (Node adapter from socket; CF Workers from\n * `cf-connecting-ip`; etc., same convention as Phase D slice 1/3's\n * `DeriveKeyRequestContext.clientIp`).\n *\n * Same `RateLimitConfig`, same `InMemoryStore` default, same async\n * store rejection (use a dedicated async middleware for external stores).\n * Same `RateLimitResult` return shape.\n *\n * **Signature difference from `createRateLimiter`:** this Web factory's\n * checker takes a raw IP string instead of a Request object. The IP is\n * the ONLY input the bucket needs; passing a Request object would force\n * the caller to populate `request.headers.get('x-forwarded-for')` or\n * similar without giving us any safer extraction. KISS — accept the IP\n * directly, document the per-runtime resolution at the adapter boundary.\n */\nexport function createRateLimiterWeb(\n config: RateLimitConfig,\n opts: { store?: RateLimitStore } = {},\n) {\n const store = opts.store ?? new InMemoryStore()\n const isInMemory = store instanceof InMemoryStore\n\n return function checkRateLimitWeb(clientIp: string): RateLimitResult {\n const key = clientIp.length > 0 ? clientIp : 'unknown'\n if (isInMemory) {\n const state = store.incrSync(key, config.windowMs)\n return resultFromState(state, config)\n }\n throw new Error(\n 'createRateLimiterWeb: async RateLimitStore implementations are not supported by this sync facade. ' +\n 'Use the InMemoryStore default or build a custom middleware around the async store directly.',\n )\n }\n}\n","/**\n * M2 (theokit-ai-first) — mount a scanned `agents/<name>.ts` module as an SSE endpoint.\n *\n * The SINGLE wiring point shared by dev (vite middleware) and prod (built server), so the\n * two never drift (EC-4). Web-Standard `Request` → `Response`: parse the chat body, compile\n * the module (`compileAgentModule`, converges both surfaces), stream via the M0/M1 canonical\n * protocol (`streamAgentUIMessages` → `uiMessageStreamResponse`).\n *\n * Request body — accepts the `@ai-sdk/react` `useChat` shape (`{ id, messages: UIMessage[] }`,\n * the typed-client path) AND a simple `{ message, sessionId? }` shape (M0/M1-style clients).\n */\nimport { compileAgentModule, resolveEnabledSkills, streamAgentUIMessages } from '@theokit/agents'\n\nimport type { RoutePolicy } from '../../core/contracts/route-policy.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport {\n admitAgentRequest,\n agentAccessDenied,\n readAgentPolicy,\n type AgentSubjectResolver,\n} from './agent-access.js'\nimport type { ApiKeyResolver } from './api-key-resolver.js'\nimport { buildAgentHitl } from './build-agent-streamer.js'\nimport { durableUiMessageStreamResponse } from './durable-ui-message-stream-response.js'\nimport { observeServedRun } from './observe-served-run.js'\nimport { getRunEventCache, mintRunId } from './run-event-cache.js'\n\n// Re-exported so existing importers keep working. It is declared in its own module because\n// `build-agent-streamer.ts` needs it too and this file already imports from there (no-circular).\nexport type { ApiKeyResolver } from './api-key-resolver.js'\n\n/** The message + session extracted from a chat request, or `null` when the body is invalid. */\ninterface AgentRequestInput {\n message: string\n sessionId: string\n}\n\n/** Extract the text of a `{ type: 'text', text: string }` part from an untrusted value. */\nfunction partText(part: unknown): string {\n if (typeof part !== 'object' || part === null) return ''\n const p = part as Record<string, unknown>\n return p.type === 'text' && typeof p.text === 'string' ? p.text : ''\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * Extract `{ message, sessionId }` from a chat request body. Returns `null` when neither the\n * ai-sdk `messages` shape nor the simple `message` shape yields non-empty user text.\n */\nexport function parseAgentRequestBody(body: unknown): AgentRequestInput | null {\n if (typeof body !== 'object' || body === null) return null\n const b = body as Record<string, unknown>\n\n // ai-sdk useChat shape: { id, messages: UIMessage[] } — take the last message's text parts.\n if (Array.isArray(b.messages) && b.messages.length > 0) {\n const last = b.messages[b.messages.length - 1] as Record<string, unknown>\n const parts = Array.isArray(last.parts) ? last.parts : []\n const text = parts.map(partText).join('')\n if (text.length === 0) return null\n const sessionId = typeof b.id === 'string' && b.id.length > 0 ? b.id : crypto.randomUUID()\n return { message: text, sessionId }\n }\n\n // Simple shape: { message, sessionId? }.\n if (typeof b.message === 'string' && b.message.length > 0) {\n const sessionId =\n typeof b.sessionId === 'string' && b.sessionId.length > 0 ? b.sessionId : crypto.randomUUID()\n return { message: b.message, sessionId }\n }\n\n return null\n}\n\n/** Non-runtime options for {@link mountAgent} (grouped so the call stays ≤ 5 params). */\ninterface MountAgentOptions {\n /** Labels a fail-fast `AgentDefinitionError` (the agent file path). Default `'agent module'`. */\n source?: string\n /** CSRF posture at this boundary. Default `'strict'`; `'off'` when a controller already gated (G5). */\n csrfMode?: CsrfMode\n /**\n * theokit-file-based-config (EC-1) — the framework-resolved app root. When the agent opted into\n * `.theokit/` file-based config (`.settingSources([...])`), discovery points here, NOT `process.cwd()`.\n */\n projectRoot?: string\n /**\n * The agent's name, as the scanner discovered it. Reported to the policy under\n * `params.agent` and named in a refusal. Defaults to {@link MountAgentOptions.source}.\n */\n agentName?: string\n /**\n * Who may run this agent, and against which conversation (ADR 0001,\n * usetheokit/theokit#365).\n *\n * NORMALLY ABSENT, and that is the fix rather than an omission: the policy is read from the\n * agent module's own `export const policy`, so it travels with the agent instead of depending\n * on every caller remembering to pass it. This option exists for a host that resolved the\n * decision itself (an `@Expose`-bound controller, an embedder), and it OVERRIDES the module's\n * declaration when given.\n *\n * Evaluated against the parsed request body, so a policy can ask who owns the\n * conversation being resumed. Absent on both ends ⇒ not evaluated, matching the route\n * executors: absence means \"not declared\" and is not reinterpreted as denial. Absence is\n * refused at scan time instead, where the file that omitted it can be named.\n */\n policy?: RoutePolicy\n /**\n * Resolve the authenticated caller. Invoked at most once, and only when a policy exists — an\n * agent declaring `'public'` never pays for the application's `createContext`.\n */\n resolveSubject?: AgentSubjectResolver\n}\n\n/**\n * Read the body and decide whether this caller may run the agent at all.\n *\n * Both gates live here, and both run BEFORE the module is compiled and long\n * before the SDK is reached — the same reason the CSRF gate upstream runs first:\n * an agent run spends real tokens, so a malformed request and an unauthorized one\n * are turned away before any of that is paid for. A policy evaluated after the\n * run began is a cost gate that costs.\n *\n * The policy sees the PARSED body, so it can ask who owns the conversation the\n * request is trying to resume — which is the whole point, since the endpoint\n * accepts a caller-supplied session id and the durable store resumes whatever it\n * names (usetheokit/theokit#365).\n *\n * @returns the parsed input, or the `Response` that refuses the request.\n */\n/**\n * Wrap a subject resolver so one request resolves at most once (B-016).\n *\n * The gate needs the caller's identity, and so does the approval ledger when the run pauses on a\n * gated tool. Resolving twice would double whatever the application's `server/context.ts` does — a\n * session lookup, a token verification, a query — for a value that cannot change inside one request.\n */\nfunction memoizeSubject(\n resolveSubject: AgentSubjectResolver | undefined,\n): AgentSubjectResolver | undefined {\n if (resolveSubject === undefined) return undefined\n let resolved: { subject: Awaited<ReturnType<AgentSubjectResolver>> } | undefined\n return async () => {\n resolved ??= { subject: await resolveSubject() }\n return resolved.subject\n }\n}\n\n/**\n * Who owns the approvals this run raises, or `undefined` (B-016).\n *\n * Recorded only when the agent DECLARES a policy. An agent declaring `'public'` — or declaring\n * nothing — is one where identity does not govern access, and attributing its approvals would start\n * refusing callers the declaration admits: a behaviour change dressed as a bug fix. So the ledger\n * stays empty there and the approve route behaves exactly as before.\n */\nasync function resolveApprovalOwner(\n declaredPolicy: RoutePolicy | undefined,\n resolveOnce: AgentSubjectResolver | undefined,\n): Promise<string | undefined> {\n if (declaredPolicy === undefined || declaredPolicy === 'public') return undefined\n return ((await resolveOnce?.()) ?? undefined)?.id\n}\n\nasync function admitRequest(\n request: Request,\n policy: RoutePolicy | undefined,\n resolveSubject: AgentSubjectResolver | undefined,\n agentName: string,\n): Promise<AgentRequestInput | Response> {\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → a 400 below */\n }\n\n const input = parseAgentRequestBody(body)\n if (input === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request must contain a non-empty message or messages[].')\n }\n\n const params = { agent: agentName, endpoint: 'run' as const, sessionId: input.sessionId }\n const decision = await admitAgentRequest(policy, resolveSubject, params, input)\n if (!decision.allowed) return agentAccessDenied(decision, params)\n\n return input\n}\n\n/**\n * Mount a loaded agent module as a `Response`.\n *\n * `apiKey` accepts either a resolved string or an {@link ApiKeyResolver}. The resolver form exists\n * because the credential depends on the model, and the model is only known once the module is\n * compiled — inside here. Callers that resolved eagerly were choosing a provider before anyone\n * could read which one the agent asked for, which is theokit#326.\n *\n * See {@link MountAgentOptions} for the labeling / CSRF / app-root knobs.\n */\nexport async function mountAgent(\n mod: unknown,\n request: Request,\n apiKey: string | ApiKeyResolver,\n {\n source = 'agent module',\n csrfMode = 'strict',\n projectRoot,\n agentName,\n policy,\n resolveSubject,\n }: MountAgentOptions = {},\n): Promise<Response> {\n // Enforce CSRF BEFORE any work — an agent run spends real LLM tokens, so a cross-origin\n // POST must be rejected before it reaches the SDK (parity with actions/routes). The custom\n // `X-Theo-Action` header + Origin match is the same defense `executeRoute`/`executeAction`\n // apply; the `useAgent` client sends the header. `off` skips; `warn` never blocks.\n if (csrfMode !== 'off') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid && csrfMode === 'strict') {\n return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n }\n\n // The declaration travels with the agent, not with the caller — see `agent-access.ts`. An\n // explicit option still wins, for a host that already took the decision.\n // ONE identity for the agent, resolved once: the gate judges it and the spans are labelled with\n // it. They used to be two — `agentName` for the policy, `source` for the telemetry — and the two\n // disagreed on the plain route, where `source` is the module's absolute path\n // (usetheokit/theokit#406). A caller that names no agent still gets `source`, as the policy\n // always has; both convention routes name one, which is why neither exports a path any more.\n const identity = agentName ?? source\n\n const declaredPolicy = policy ?? readAgentPolicy(mod, source)\n\n const resolveOnce = memoizeSubject(resolveSubject)\n\n const admitted = await admitRequest(request, declaredPolicy, resolveOnce, identity)\n if (admitted instanceof Response) return admitted\n const input = admitted\n\n const compiled = compileAgentModule(mod, source)\n\n // Now that the model is known, let the caller pick the credential for THAT provider.\n const resolvedApiKey = typeof apiKey === 'function' ? apiKey(compiled.model) : apiKey\n\n // M13 — resolve a per-request skills selector (from `defineAgent({ skills: (ctx) => [...] })`)\n // against the M7 run-context, setting `skills.enabled` before the SDK runs. `undefined` ⇒ the\n // SDK enables every discovered skill. `compiled` is fresh per request, so mutation is safe.\n if (compiled.skillsResolver) {\n const enabled = await resolveEnabledSkills(compiled.skillsResolver, compiled.runContext ?? {})\n if (enabled !== undefined) compiled.skills = { enabled, autoInject: true }\n }\n\n // When the agent has @HumanInTheLoop-gated tools (M4), wire the pause: the plugin's `awaitApproval`\n // registers a pending approval in the shared registry (the Promise that PAUSES the run); the\n // approve route (`handleAgentApproval`) resolves it. No gated tools ⇒ the M2 stream path unchanged.\n // Extracted to `build-agent-streamer.ts` (M39 / DRY — the thread routes reuse the same wiring).\n const hitl = buildAgentHitl(compiled, await resolveApprovalOwner(declaredPolicy, resolveOnce))\n\n // M37 (ADR-0046) — mint a transport runId + stream through the durable layer:\n // each SSE frame is cached + `id:`-tagged so a dropped client can reconnect\n // (or a second client observe) via `GET /api/agents/<name>/runs/<runId>/stream`.\n // The runId is surfaced in the `x-theokit-run-id` response header.\n const runId = mintRunId()\n const stream = streamAgentUIMessages(compiled, resolvedApiKey, {\n ...input,\n hitl,\n signal: request.signal,\n cwd: resolveDiscoveryCwd(compiled, projectRoot),\n baseDir: resolveSessionBaseDir(projectRoot),\n })\n // M8 — spans for the run, each tool call, each HITL pause and the token usage,\n // read off the chunk stream the agent already emits. Absent adapter ⇒ the\n // stream is passed through untouched, so an app that configured no telemetry\n // pays nothing (usetheokit/theokit#353).\n //\n // The trace the spans join is decided inside `observeServedRun`, from this\n // request — the same function the thread route calls, so the two endpoints\n // cannot drift into producing different telemetry for the same agent\n // (usetheokit/theokit#381). What that function could not decide was the agent\n // LABEL, which arrives from here: this call used to pass `source`, so every\n // span of every run on this route carried the module's absolute path\n // (usetheokit/theokit#406).\n return durableUiMessageStreamResponse(\n observeServedRun(stream, { agentName: identity, request }),\n { runId, cache: getRunEventCache() },\n )\n}\n\n/**\n * theokit-file-based-config (EC-1) — resolve the `.theokit/` discovery cwd. When the agent opted into\n * file-based config (`.settingSources([...])`), point discovery at the framework-resolved app root,\n * NOT `process.cwd()` (which is not guaranteed to be the app root). No opt-in ⇒ `undefined` (byte-unchanged).\n */\nfunction resolveDiscoveryCwd(\n compiled: { settingSources?: readonly unknown[] },\n projectRoot: string | undefined,\n): string | undefined {\n const optedIn = (compiled.settingSources?.length ?? 0) > 0\n return projectRoot !== undefined && optedIn ? projectRoot : undefined\n}\n\n/** Strip trailing `/` without a backtracking regex (linear scan). */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length\n while (end > 0 && value[end - 1] === '/') end -= 1\n return value.slice(0, end)\n}\n\n/**\n * SDK 4.0 (SE40) — resolve the root of the native `.jsonl` session transcript. Unlike `.theokit/`\n * discovery, persistence is NOT gated on a file-based-config opt-in — every agent session persists.\n * Root it under the app's `.data/`, kept OUT of the `.theokit/` config dir so a\n * `projects/` transcript subtree never collides with `settingSources` discovery. Absent `projectRoot`\n * ⇒ `undefined` (the SDK default `~/.theokit` applies).\n *\n * **This directory holds conversation content and nothing here can keep it out of a repository.**\n * That is the app's `.gitignore`, which lives in a different tree. This comment used to assert\n * \"(git-ignored, EC-2)\" as though the protection were local, and the scaffold ignored `data/` —\n * without the dot — so the assertion was false and its confidence is what stopped anyone checking\n * (#395). The scaffold now ignores `.data/`, and `tests/unit/scaffold-ignores-what-the-framework-writes.test.ts`\n * derives the path from THIS function rather than repeating it, so moving the transcripts breaks the\n * test instead of leaking quietly.\n */\nexport function resolveSessionBaseDir(projectRoot: string | undefined): string | undefined {\n if (projectRoot === undefined) return undefined\n // Web-Standards discipline (R3a/G8): no `node:path` in `server/` — append with `/` (the SDK\n // normalizes the separator). Strip a trailing slash on `projectRoot` so we never emit `//`.\n // A trailing-slash strip written as a loop-free replace: `/\\/+$/` is super-linear under\n // backtracking on a long run of slashes, and this value can come from user config.\n return `${trimTrailingSlashes(projectRoot)}/.data/agent-sessions`\n}\n","/**\n * ADR 0001, applied to the agent surface (usetheokit/theokit#365).\n *\n * `RouteConfig.policy` gave routes one access decision evaluated by both HTTP executors and\n * `callProcedure`. The agent endpoints are dispatched BEFORE route matching\n * (`request-handler.ts` runs `tryServeAgentAux` and `tryServeAgent` ahead of `tryServeApiRoute`),\n * so no `route()`, no `server/middleware/` and no `server/context.ts` ever observed those URLs.\n * The policy existed and did not reach them.\n *\n * ## Why the policy is declared on the agent module and not passed by the caller\n *\n * `mountAgent` already accepted `policy` and `subject` as options. Every production caller invoked\n * it without either, so the evaluator saw `undefined` and admitted everyone — a gate that works\n * perfectly and is never reached. An option nobody passes is not a seam; it is a comment with a\n * type. So the declaration travels WITH the agent:\n *\n * ```ts\n * // agents/support.ts\n * import { requireOwner } from 'theokit/server/define'\n *\n * export const policy = ({ subject, params }) => requireOwner(subject, ownerOf(params.sessionId))\n * export default defineAgent({ ... })\n * ```\n *\n * One declaration covers every endpoint the agent exposes — the run, the thread routes, the\n * approval surface and MCP — because they all reach the same conversation and the same paused\n * tools. `params.endpoint` says which one is being asked for, so a policy that wants to answer\n * them differently can.\n *\n * `'public'` is the other legal value, and it is a decision rather than the absence of one. It is\n * greppable; silence was not.\n *\n * ## Why the refusal does not repeat the policy's reason\n *\n * `requireOwner` distinguishes `'resource has no recorded owner'` from `'subject does not own this\n * resource'`. Echoed to the wire, that pair tells an unauthenticated caller whether a conversation\n * id exists — the enumeration oracle `docs/program/journeys/j08-tenant.md` grades under criterion 2,\n * rebuilt out of the very check added to close the leak. So the reason goes to the server log,\n * where an operator can read it, and the wire gets one fixed sentence that names what the caller\n * must do. The status stays `403`: the decision is taken before any lookup, so `403` is returned\n * identically for an id that exists and one that never did, and a truthful `403` beats a `404`\n * whose truthfulness a reader cannot check (`docs/adr/0002-*`).\n */\nimport type {\n AccessDecision,\n RoutePolicy,\n RouteSubject,\n} from '../../core/contracts/route-policy.js'\nimport { evaluateRoutePolicy } from '../../core/contracts/route-policy.js'\nimport { createLogger } from '../observability/logger.js'\n\n/**\n * Which operation on the agent is being asked for.\n *\n * Handed to the policy under `params.endpoint` so one declaration can answer them separately — a\n * conversation is owned by whoever the key names, while a pending approval has no owner the\n * framework records (see the note on `'approvals'` / `'approve'` below).\n */\nexport type AgentEndpoint =\n | 'run'\n | 'thread-message'\n | 'thread-stream'\n | 'approvals'\n | 'approve'\n | 'mcp'\n\n/** The path-derived facts a policy is given, alongside the parsed body where one exists. */\nexport interface AgentAccessParams {\n /** The scanned agent's name — the `<name>` in `/api/agents/<name>`. */\n agent: string\n endpoint: AgentEndpoint\n /**\n * The conversation key, when the request names one. This is the value the durable store resumes\n * on, and the reason #365 exists: it arrives from the caller.\n */\n sessionId?: string\n /**\n * The pending approval the request settles, when it settles one.\n *\n * The framework cannot tell a policy who OWNS this approval: the ledger keys by a bare id and\n * records no owner (`approval-registry.ts`). So a policy asked about `'approve'` can decide\n * whether the caller may touch this agent's approvals at all, and cannot decide whether this\n * approval is theirs. That gap is real and is not closed here.\n */\n approvalId?: string\n}\n\n/** Resolve the caller's identity, lazily — see `resolveAgentSubject` for why it must be lazy. */\nexport type AgentSubjectResolver = () => RouteSubject | null | Promise<RouteSubject | null>\n\n/** Thrown when an agent module exports a `policy` that is neither `'public'` nor a function. */\nexport class AgentPolicyTypeError extends Error {\n constructor(source: string, actual: string) {\n super(\n `Agent \"${source}\" exports a \\`policy\\` of type ${actual}. ` +\n `A policy is the string 'public' or a function ({ subject, body, params }) => boolean | AccessDecision. ` +\n `Import \\`requireOwner\\` from 'theokit/server/define' to write the owner check.`,\n )\n this.name = 'AgentPolicyTypeError'\n }\n}\n\n/**\n * Read the access policy an agent module declares.\n *\n * Fail-fast on a wrong shape rather than falling back to \"no policy\": a module that MEANT to\n * declare one and got the type wrong would otherwise be served wide open, which is the failure\n * class this whole change exists to remove. Absent ⇒ `undefined`, which `evaluateRoutePolicy`\n * treats as \"not declared\" exactly as it does for a `RouteConfig` built in memory. Absence is\n * refused where the application DECLARES its agents — `scanAgents` fails the build naming the file.\n *\n * The three-valued answer IS the contract, which is why the mixed return type is silenced below:\n * `undefined` is \"not declared\", `'public'` is \"declared open\", and a function is \"declared\n * conditional\". `RoutePolicy` is the framework's own public union, and collapsing it here would\n * erase the distinction ADR 0001 exists to make.\n */\n/* eslint-disable-next-line sonarjs/function-return-type -- see the paragraph above */\nexport function readAgentPolicy(mod: unknown, source: string): RoutePolicy | undefined {\n const declared =\n typeof mod === 'object' && mod !== null ? (mod as { policy?: unknown }).policy : undefined\n if (declared === undefined) return undefined\n if (declared !== 'public' && typeof declared !== 'function') {\n throw new AgentPolicyTypeError(source, declared === null ? 'null' : typeof declared)\n }\n return declared as RoutePolicy\n}\n\nconst log = createLogger({ context: { scope: 'theokit:agent-access' } })\n\n/**\n * Evaluate an agent endpoint's policy for this caller.\n *\n * The subject is resolved ONLY when a policy exists. An agent declaring `'public'` therefore never\n * pays for the application's `createContext`, which keeps the zero-config path free of a cost it\n * gets nothing for.\n */\nexport async function admitAgentRequest(\n policy: RoutePolicy | undefined,\n resolveSubject: AgentSubjectResolver | undefined,\n params: AgentAccessParams,\n body?: unknown,\n): Promise<AccessDecision> {\n // `undefined` is \"not declared\" and `'public'` is \"declared open\". They differ in what they\n // MEAN and not in what they admit, and neither reads the subject — so neither pays for it.\n if (policy === undefined || policy === 'public') return { allowed: true }\n const subject = resolveSubject === undefined ? null : await resolveSubject()\n return evaluateRoutePolicy(policy, { subject, query: undefined, body, params })\n}\n\n/**\n * The refusal, once, for every agent endpoint.\n *\n * The `reason` is logged and not returned — see the module header. The message names the thing the\n * caller can act on: an identity the agent's policy admits, established by the application's own\n * `server/context.ts`.\n */\nexport function agentAccessDenied(decision: AccessDecision, params: AgentAccessParams): Response {\n if (!decision.allowed) {\n log.warn('agent endpoint refused a caller', {\n agent: params.agent,\n endpoint: params.endpoint,\n reason: decision.reason,\n })\n }\n return new Response(\n JSON.stringify({\n error: {\n code: 'FORBIDDEN',\n message:\n `Access denied by the policy exported from agent \"${params.agent}\". ` +\n `Send the credential your app turns into \\`ctx.subject\\` in server/context.ts; ` +\n `the server log records which check refused this request.`,\n },\n }),\n { status: 403, headers: { 'content-type': 'application/json; charset=utf-8' } },\n )\n}\n","/**\n * M39 (ADR-0048) — shared agent-run streamer builders, extracted from\n * `mount-agent.ts` (DRY / G12) so the thread routes drive the SAME SDK run path\n * as the plain POST. Reuses SDK primitives (`compileAgentModule` +\n * `streamAgentUIMessages`) — it does NOT reimplement the loop (G2).\n */\n\nimport {\n compileAgentModule,\n type HumanInTheLoopOptions,\n resolveEnabledSkills,\n streamAgentUIMessages,\n} from '@theokit/agents'\nimport type { WireChunk as UIMessageChunk } from '@theokit/presenter/wire'\n\nimport type { ApiKeyResolver } from './api-key-resolver.js'\nimport { getApprovalRegistry } from './approval-registry.js'\nimport { observeServedRun } from './observe-served-run.js'\n\ntype Compiled = ReturnType<typeof compileAgentModule>\n\n/**\n * Build the HITL wiring for a compiled agent: gated tools register a pending\n * approval in the shared registry (the Promise that PAUSES the run). `undefined`\n * when the agent has no `@HumanInTheLoop`-gated tools. Extracted verbatim from\n * `mountAgent` so both the plain POST and the thread routes wire HITL identically.\n */\nexport function buildAgentHitl(compiled: Compiled, owner?: string) {\n const gated = compiled.hitl\n if (gated === undefined || gated.size === 0) return undefined\n const registry = getApprovalRegistry()\n return {\n gated,\n awaitApproval: (approvalId: string, opts: HumanInTheLoopOptions, toolName: string) =>\n registry.register(approvalId, {\n ...(owner !== undefined ? { owner } : {}),\n timeoutMs: opts.timeout ?? 300_000,\n onTimeout: opts.onTimeout ?? 'abort',\n toolName,\n question: opts.question,\n ...(opts.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n }),\n }\n}\n\n/**\n * A `startRun(sessionId, message)` closure for the thread dispatcher. Per run it\n * compiles the module fresh (skills resolution mutates `compiled`), resolves\n * per-request skills, builds HITL, and streams. Headless — no request signal (a\n * thread continuation runs to completion into the durable cache, not to a client).\n *\n * `apiKey` accepts a resolved string or an {@link ApiKeyResolver}. The resolver form exists for\n * the same reason it does on `mountAgent` (theokit#327): the credential depends on the model, and\n * the model is only known once the module is compiled — which happens inside the generator below.\n * The caller resolved before that, so an agent declaring `anthropic/…` was handed whichever key\n * env priority picked first and every follow-up died with `auth_failed`. Fixed on the agent\n * endpoint by #327; this is the same defect on the thread route (theokit#328).\n *\n * `request` is REQUIRED, and required is the point (usetheokit/theokit#381). The trace the run's\n * spans join lives in that request's `traceparent`, and the previous signature had no parameter\n * that could carry it — so the value was dropped at the call site, silently, while\n * `handleThreadMessage` held the `Request` two lines away. An optional parameter would have left\n * the same omission available; a required one makes the call site state what it is doing.\n *\n * `agentName` is required for the same reason, one defect later (usetheokit/theokit#406). There was\n * one string here, `source`, and it was doing two jobs: labelling a fail-fast `AgentDefinitionError`\n * and labelling every span of the run. This route's caller passes `agent \"chat\"` — good prose in an\n * error message, and not a name — while the plain route passes the module's absolute file path. Two\n * parameters because they are two values; the compile label may stay human-readable precisely\n * because it is no longer the key an operator groups by.\n */\nexport function makeThreadStartRun(\n mod: unknown,\n apiKey: string | ApiKeyResolver,\n source: string,\n agentName: string,\n request: Request,\n): (sessionId: string, message: string) => AsyncIterable<UIMessageChunk> {\n return (sessionId, message) =>\n (async function* () {\n const compiled = compileAgentModule(mod, source)\n if (compiled.skillsResolver) {\n const enabled = await resolveEnabledSkills(\n compiled.skillsResolver,\n compiled.runContext ?? {},\n )\n if (enabled !== undefined) compiled.skills = { enabled, autoInject: true }\n }\n // No owner on this path, and that is a stated limit rather than an oversight (B-016). A thread\n // continuation runs headless — there is no request whose identity could be resolved — so an\n // approval it raises records nobody, and the approve route treats it exactly as it did before.\n const hitl = buildAgentHitl(compiled)\n // Now that the model is known, let the caller pick the credential for THAT provider.\n const resolvedApiKey = typeof apiKey === 'function' ? apiKey(compiled.model) : apiKey\n const stream = streamAgentUIMessages(compiled, resolvedApiKey, { message, sessionId, hitl })\n // M8 — the thread route runs the same agent and must produce the same\n // spans. Instrumenting only the plain POST would make a run's telemetry\n // depend on which endpoint reached it (usetheokit/theokit#353) — and for\n // the trace id that is exactly what happened, until both routes were made\n // to go through one function (usetheokit/theokit#381). The trace continued\n // is the one of the request that STARTED this run, which outlives it:\n // `observe-served-run.ts` says why that is the right answer. The `agent`\n // attribute took a second pass to converge (usetheokit/theokit#406): it was\n // `source`, so this route labelled every span `agent \"chat\"` while the plain\n // route labelled its own with a file path.\n yield* observeServedRun(stream, { agentName, sessionId, request })\n })()\n}\n","/**\n * B-028 — where a HITL pause span lives between the pause and the resume.\n *\n * ## Why this module exists at all\n *\n * The pause span used to be closed by the run's own observer, on\n * `tool-output-available`, under the premise that \"the tool producing output IS the resume\". The\n * wire refuted it: with the approval answered at ~3306 ms that chunk arrived at 4829 ms, and across\n * three runs varying only the model's post-resume latency the excess tracked it 1:1. The premise\n * holds only when the model is instantaneous, which is the one case nobody deploys — so the span\n * reported the human's wait plus the model's, and only the human was asked for.\n *\n * The resume happens on a **different HTTP request** — the approve endpoint — which the run's\n * observer never sees. Neither side can close the span alone, so the handle lives here, where both\n * reach it by approval id.\n *\n * ## Idempotent by construction, not by discipline\n *\n * The module owns the handle and drops it on close, so the tool result arriving seconds later\n * cannot re-close a span the approval already ended — which is the original defect finding its way\n * back through the fallback path. Whoever observes the resume first ends the span; everyone after\n * is a no-op.\n *\n * ## The limit, stated\n *\n * In-process, like the approval registry it shadows (ADR 0038): the span handle is a live object,\n * so the pause and the resume must be in one process. A multi-instance deploy resumes on whichever\n * instance the approve request reaches, and there the span falls through to the run's end-of-run\n * sweep and is marked as never observed to resume — the honest reading, and the same envelope\n * `B-027` records for the rate-limit store.\n */\nimport type { SpanHandle } from '../observability/adapters/types.js'\n\nconst pauseSpans = new Map<string, SpanHandle>()\n\n/** Hand the pause span for `approvalId` to whoever observes the resume. */\nexport function registerPauseSpan(approvalId: string, span: SpanHandle): void {\n pauseSpans.set(approvalId, span)\n}\n\n/**\n * End the pause span for `approvalId`, if one is still open.\n *\n * `resumeObserved` is said positively on purpose: an operator reading a four-minute pause has no\n * other way to tell \"the human thought for four minutes\" from \"we never saw the resume\".\n *\n * A no-op for an unknown id, which covers the ordinary cases rather than an error path — an\n * approval raised on a run with no observability adapter, an id already closed, and an approve\n * request for something that was never a pause.\n */\nexport function closePauseSpan(\n approvalId: string,\n { resumeObserved }: { resumeObserved: boolean },\n): void {\n const span = pauseSpans.get(approvalId)\n if (span === undefined) return\n pauseSpans.delete(approvalId)\n\n span.setAttribute('hitl.resume_observed', resumeObserved)\n if (resumeObserved) span.setStatus('ok')\n else\n span.setStatus('error', 'HITL pause never observed to resume; duration is not the human wait')\n span.end()\n}\n\n/**\n * There is deliberately no \"forget without ending\" (#419).\n *\n * One shipped with the first version of this module and nothing called it: every path that removes a\n * pause span also has an answer for the span — the approve endpoint and the tool result close it as\n * resumed, the end-of-run sweep closes it as never resumed. A handle dropped without an answer would\n * be a span that silently never arrives, which is the shape this module exists to remove.\n */\n\n/** @internal test seam — the map is process-wide and tests must not inherit each other's. */\nexport function _resetPauseSpansForTests(): void {\n pauseSpans.clear()\n}\n","/**\n * Translate an agent's wire-chunk stream into spans (M8, usetheokit/theokit#353).\n *\n * ## Why this lives here and not in the agent loop\n *\n * The obvious reading of M8 is \"instrument the agent loop\". That is unreachable:\n * `packages/agents` depends on `@theokit/presenter`, `@theokit/sdk`,\n * `@theokit/sdk-pty` and `@theokit/sdk-tools` — not on `theokit` — while\n * `ObservabilityAdapter` lives under `packages/theo/src/server/`. Instrumenting\n * the loop would mean inverting the package graph to get a telemetry type across.\n *\n * It does not need to. The agent already emits a canonical, target-agnostic wire\n * chunk stream, and every signal the milestone names is a chunk in it: `start`\n * and `finish` bracket the run, `tool-input-available` opens a tool call and\n * `tool-output-available` / `tool-output-error` close it, `tool-approval-request`\n * is the human-in-the-loop pause, and `finish` carries the token usage.\n *\n * The agent emits; the framework observes. That split is also what keeps\n * `three-target-parity.md` intact: the same events reach Tauri and a terminal\n * over the in-process path, so those targets get the same spans without a second\n * instrumenter each — which is exactly what instrumenting the loop would have\n * quietly broken.\n *\n * ## It must not change the stream\n *\n * Every chunk is forwarded unchanged. A translator that drops or reshapes one\n * breaks the client in order to instrument the server.\n */\nimport type {\n ObservabilityAdapter,\n SpanContextInput,\n SpanHandle,\n} from '../observability/adapters/types.js'\nimport { newSpanId, newTraceId } from '../observability/trace-context-propagation.js'\n\nimport { closePauseSpan, registerPauseSpan } from './hitl-pause-spans.js'\n\nexport interface AgentRunSpanContext {\n /** The agent being run, as the attribute an operator will group by. */\n agent: string\n /** Optional session/thread id, when the caller has one. */\n sessionId?: string\n /**\n * The trace this run belongs to, when the caller already has one — the\n * `traceparent` of the request that started it, typically. Absent means the\n * run opens a trace of its own, which is correct for a run nothing else\n * triggered (a cron, a terminal session).\n *\n * Without this the run would always be a root, and an agent invoked from an\n * HTTP request would sit in a trace of its own next to the request that caused\n * it — two traces for one thing that happened.\n */\n traceId?: string\n /**\n * The caller's span inside {@link traceId} — the `traceparent`'s parent-id.\n *\n * Read only when `traceId` is also present: a parent from one trace pinned\n * inside another names a span the backend cannot resolve, which is worse than\n * no parent at all.\n *\n * Without it the run was a SECOND root of the caller's trace rather than a\n * child of the caller's span: the correlation held and the waterfall's shape\n * did not (usetheokit/theokit#385).\n */\n parentSpanId?: string\n}\n\n/** The chunk fields this reads. Deliberately structural: the wire schema is owned elsewhere. */\ninterface ObservedChunk {\n type?: string\n toolCallId?: string\n toolName?: string\n approvalId?: string\n errorText?: string\n messageMetadata?: unknown\n}\n\n/**\n * The `finish` chunk's `messageMetadata` is an `AgentTurnMetadata`:\n * `{ usage: { inputTokens, outputTokens, totalTokens, ... }, cost?, durationMs }`\n * (`packages/agents/src/bridge/agent-stream-events.ts:141-146`). The tokens are\n * nested under `usage`, not flat on the metadata.\n *\n * This read them flat when it was first written, against a shape invented for the\n * test rather than read from the producer — so the span carried no token\n * attributes at all and the test agreed with it, because the fixture had the same\n * invented shape. Found by someone auditing the criteria, not by the suite. The\n * lesson is the one this codebase keeps re-learning: a test whose fixture comes\n * from the same assumption as the code cannot disagree with it.\n */\nconst TOKEN_FIELDS: [string, string][] = [\n ['inputTokens', 'tokens.input'],\n ['outputTokens', 'tokens.output'],\n ['totalTokens', 'tokens.total'],\n ['reasoningTokens', 'tokens.reasoning'],\n ['cacheReadTokens', 'tokens.cache_read'],\n ['cacheWriteTokens', 'tokens.cache_write'],\n]\n\n/**\n * usetheokit/theokit#379 — the stop reason, as the attribute an operator filters on.\n *\n * A run the SDK cut at its iteration ceiling (or stopped as a doom loop) still ends on `finish`, not\n * on an error, so without this attribute the trace of a truncated run is identical to the trace of a\n * finished one. That is the same blindness the issue reports one layer out, and the span is the\n * consumer that suffers it longest: nobody re-reads a stream, everybody re-reads a trace.\n *\n * The span status stays `ok`. A reached ceiling is a declared outcome, not a failure — calling it an\n * error would put every capped run in an operator's error budget.\n *\n * Only the two values the producer can emit are recorded. An unknown string is ignored rather than\n * passed through: the attribute is what a dashboard groups by, and a typo'd or hostile value would\n * silently create a new bucket.\n */\nconst STOP_REASONS = new Set(['step_limit', 'no_progress'])\n\n/**\n * The model that ran, under the name the OpenTelemetry GenAI semantic\n * conventions give it — B-019's fifth criterion, and J9's criterion 5.\n *\n * ## Why the run span needs it at all\n *\n * The span already carries `tokens.input` / `tokens.output` / `tokens.total`,\n * and `cost.usd` when the provider reported one. When the provider does not,\n * tokens are the only route to \"what did this run cost\" — and tokens without a\n * model id convert to nothing, because price is per model. So a complete token\n * record answered the cost question for exactly the providers that had already\n * answered it.\n *\n * ## Why this spelling and not one of ours\n *\n * `gen_ai.request.model` — \"the name of the GenAI model a request is being made\n * to\" — is the registry entry in OpenTelemetry's GenAI semantic conventions\n * (`open-telemetry/semantic-conventions-genai`,\n * `docs/registry/attributes/gen-ai.md`), and it is what the AI SDK's\n * OpenTelemetry integration emits for the same fact. The value here is the model\n * the run was STARTED with, which is the request side, not\n * `gen_ai.response.model` (what the provider says answered) — that one is not on\n * the wire and inventing it from this would be a guess wearing a spec's name.\n *\n * A name of our own would have cost nothing to write and would not have been\n * readable by a single dashboard, processor or cost tool that already knows this\n * one.\n */\nconst GEN_AI_REQUEST_MODEL = 'gen_ai.request.model'\n\n/**\n * The effective model id, read off the `finish` chunk's metadata.\n *\n * It arrives on the wire rather than from `CompiledAgentOptions.model` for two\n * reasons, and the second is the one that matters. The declared model is not\n * always the model: a per-run override wins over it, and an agent that declares\n * none still runs one (the adapter's own default). And the wire is the only path\n * the in-process targets share — a value read from the compiled agent inside the\n * HTTP route would be recorded for the served path and absent for Tauri and the\n * TUI, which is the split `three-target-parity.md` exists to prevent.\n */\nfunction recordModel(span: SpanHandle, metadata: unknown): void {\n if (metadata === null || typeof metadata !== 'object') return\n const model = (metadata as { model?: unknown }).model\n if (typeof model === 'string' && model.length > 0) span.setAttribute(GEN_AI_REQUEST_MODEL, model)\n}\n\nfunction recordStopReason(span: SpanHandle, metadata: unknown): void {\n if (metadata === null || typeof metadata !== 'object') return\n const reason = (metadata as { stopReason?: unknown }).stopReason\n if (typeof reason === 'string' && STOP_REASONS.has(reason)) {\n span.setAttribute('stop.reason', reason)\n }\n}\n\nfunction recordTokenUsage(span: SpanHandle, metadata: unknown): void {\n if (metadata === null || typeof metadata !== 'object') return\n const bag = metadata as { usage?: unknown; cost?: unknown }\n\n if (typeof bag.cost === 'number') span.setAttribute('cost.usd', bag.cost)\n\n const usage = bag.usage\n if (usage === null || usage === undefined || typeof usage !== 'object') return\n const fields = usage as Record<string, unknown>\n for (const [field, attribute] of TOKEN_FIELDS) {\n const value = fields[field]\n if (typeof value === 'number') span.setAttribute(attribute, value)\n }\n}\n\n/** Spans open for one run, plus the names needed to label a pause. */\ninterface RunSpans {\n run: SpanHandle\n tools: Map<string, SpanHandle>\n /** toolCallId → approvalId. The span itself lives in `hitl-pause-spans.ts` (B-028). */\n pauses: Map<string, string>\n toolNames: Map<string, string>\n agent: string\n /**\n * The trace every span of this run belongs to, and the run span they hang\n * under. Held here because the `SpanHandle` an adapter returns exposes no\n * identity — parentage is decided by the code that opens both spans, which is\n * this file, and passed in (usetheokit/theokit#368).\n */\n traceId: string\n runSpanId: string\n}\n\n/** Where a child span of this run sits: same trace, under the run span. */\nfunction childOf(state: RunSpans): { traceId: string; parentSpanId: string } {\n return { traceId: state.traceId, parentSpanId: state.runSpanId }\n}\n\nfunction openToolSpan(state: RunSpans, adapter: ObservabilityAdapter, chunk: ObservedChunk): void {\n const id = chunk.toolCallId\n if (id === undefined) return\n const tool = chunk.toolName ?? 'unknown'\n state.toolNames.set(id, tool)\n state.tools.set(\n id,\n adapter.startSpan('agent.tool', { agent: state.agent, tool, toolCallId: id }, childOf(state)),\n )\n}\n\nfunction openPauseSpan(state: RunSpans, adapter: ObservabilityAdapter, chunk: ObservedChunk): void {\n const id = chunk.toolCallId\n const approvalId = chunk.approvalId\n if (id === undefined || approvalId === undefined) return\n const pauseSpan = adapter.startSpan(\n 'agent.hitl',\n {\n agent: state.agent,\n tool: state.toolNames.get(id) ?? 'unknown',\n approvalId,\n toolCallId: id,\n },\n childOf(state),\n )\n state.pauses.set(id, approvalId)\n // Handed to the registry both sides reach: the resume arrives on the approve endpoint, which this\n // observer never sees (B-028).\n registerPauseSpan(approvalId, pauseSpan)\n}\n\nfunction closeToolSpan(state: RunSpans, chunk: ObservedChunk): void {\n const id = chunk.toolCallId\n if (id === undefined) return\n\n // FALLBACK, and no longer the normal path (B-028). \"The tool producing output IS the resume\" was\n // this file's stated premise, and it was wrong by the model's post-resume latency — measured at\n // +1523 ms on a run whose human answered at 3306 ms. The approve endpoint now closes the span at\n // the instant the human answers; this closes it for transports that settle an approval without\n // one, the terminal prompt among them. `closePauseSpan` drops the handle on close, so whichever\n // arrives second cannot overwrite a duration the first got right.\n const pausedApprovalId = state.pauses.get(id)\n if (pausedApprovalId !== undefined) {\n closePauseSpan(pausedApprovalId, { resumeObserved: true })\n state.pauses.delete(id)\n }\n\n const span = state.tools.get(id)\n if (span === undefined) return\n if (chunk.type === 'tool-output-error') span.setStatus('error', chunk.errorText)\n else span.setStatus('ok')\n span.end()\n state.tools.delete(id)\n}\n\nexport async function* observeAgentRun<T>(\n chunks: AsyncIterable<T>,\n adapter: ObservabilityAdapter,\n context: AgentRunSpanContext,\n): AsyncIterable<T> {\n const runAttributes: Record<string, string> = { agent: context.agent }\n if (context.sessionId !== undefined) runAttributes.sessionId = context.sessionId\n\n // Minted before the run span so the id can be pinned and then named as parent\n // by every tool and pause span below.\n const traceId = context.traceId ?? newTraceId()\n const runSpanId = newSpanId()\n const runContext: SpanContextInput =\n context.traceId !== undefined && context.parentSpanId !== undefined\n ? { traceId, spanId: runSpanId, parentSpanId: context.parentSpanId }\n : { traceId, spanId: runSpanId }\n\n const state: RunSpans = {\n run: adapter.startSpan('agent.run', runAttributes, runContext),\n tools: new Map(),\n pauses: new Map(),\n toolNames: new Map(),\n agent: context.agent,\n traceId,\n runSpanId,\n }\n let settled = false\n\n /**\n * Close everything still open. Runs on success, on failure, and on a consumer\n * that stops reading — a client disconnect mid-run would otherwise leave the\n * run span open for the life of the process, which is the one case where the\n * leak and the operator's interest coincide.\n */\n function closeAll(status: 'ok' | 'error', message?: string): void {\n if (settled) return\n settled = true\n for (const approvalId of state.pauses.values()) {\n // A pause span reaching the sweep was never observed to resume, so its\n // duration approximates the whole run rather than the time a human took.\n // Saying so is not a nicety: an operator reading a four-minute pause span\n // has no other way to tell \"the human thought for four minutes\" from \"we\n // never saw the resume\".\n //\n // This is the EXCEPTIONAL path again. It was the normal one while the\n // approval chunk and the tool result carried different ids for the same\n // logical call and `closeToolSpan` could never match the pause\n // (usetheokit/theokit#361, fixed in `hitl-call-correlation.ts`). What still\n // reaches it is a pause that genuinely never resumed: the client\n // disconnected while a human was deciding, the approval timed out into an\n // aborted run, or the stream failed mid-pause.\n closePauseSpan(approvalId, { resumeObserved: false })\n }\n for (const span of state.tools.values()) {\n span.setStatus(status, message)\n span.end()\n }\n state.pauses.clear()\n state.tools.clear()\n state.run.setStatus(status, message)\n state.run.end()\n }\n\n try {\n for await (const chunk of chunks) {\n const observed = chunk as ObservedChunk\n\n if (observed.type === 'tool-input-available') openToolSpan(state, adapter, observed)\n else if (observed.type === 'tool-approval-request') openPauseSpan(state, adapter, observed)\n else if (observed.type === 'tool-output-available' || observed.type === 'tool-output-error')\n closeToolSpan(state, observed)\n else if (observed.type === 'finish') {\n recordTokenUsage(state.run, observed.messageMetadata)\n recordStopReason(state.run, observed.messageMetadata)\n recordModel(state.run, observed.messageMetadata)\n }\n\n yield chunk\n }\n closeAll('ok')\n } catch (error) {\n closeAll('error', error instanceof Error ? error.message : 'unknown error')\n throw error\n } finally {\n // Reached when the consumer abandons the iterator — `return()` runs the\n // `finally` without the `try` block completing.\n closeAll('error', 'agent run stream abandoned by its consumer')\n }\n}\n","/**\n * The single place a SERVED agent run becomes spans (usetheokit/theokit#381).\n *\n * ## Why this exists rather than two call sites\n *\n * Two endpoints start a run the framework serves: the plain\n * `POST /api/agents/<name>` (`mount-agent.ts`) and the thread message route\n * (`build-agent-streamer.ts`). Both resolved the adapter and both called\n * `observeAgentRun` — separately. When the run learned to continue an incoming\n * `traceparent`, exactly one of them was taught, and a run's trace became a\n * function of which endpoint reached it: the same header produced the caller's\n * trace on one route and a freshly minted one on the other.\n *\n * `build-agent-streamer.ts`'s own comment had already stated the principle the\n * split violated — *\"the thread route runs the same agent and must produce the\n * same spans\"* — and the code still drifted, because nothing made the two paths\n * one thing. This function is that one thing: both routes hand it a `Request`\n * and get identical telemetry, and a third route added later inherits it by\n * calling the same function rather than by remembering to.\n *\n * Unifying the function was not enough by itself, and #406 is the proof: the two\n * routes went on labelling the same agent differently, because the label is a\n * value the caller passes in rather than one derived here. What this function\n * can do about that is refuse an ambiguous one — hence `agentName`, whose\n * documentation below says what a name is and what it is not.\n *\n * ## The honest wrinkle about a thread run\n *\n * A thread follow-up is HEADLESS: `postThreadFollowUp` answers `202` and the run\n * streams into the durable cache after the request that queued it is gone. A\n * queued follow-up may even start minutes later, when the run ahead of it ends.\n *\n * So the trace continued here is the trace of **the request that started the\n * run**, not of a request that was open while it ran. That is the right answer —\n * it is what lets an operator get from \"the client posted this message\" to \"here\n * is what the agent did about it\" — and it is said out loud because the\n * alternative reading (\"the trace of the live request\") is wrong and would look\n * identical in the payload.\n */\nimport { requestTrace } from '../observability/request-trace.js'\nimport { getObservabilityAdapter } from '../observability-bootstrap.js'\n\nimport { observeAgentRun, type AgentRunSpanContext } from './observe-agent-run.js'\n\nexport interface ServedRunObservation {\n /**\n * The agent's NAME — `chat` for `agents/chat.ts`, the same string the URL carries and the same\n * one the access policy is judged under (`params.agent`).\n *\n * It is spelled `agentName` rather than `agent` because the field's whole history is callers\n * handing it something that identifies the agent's *module* instead: the plain route passed the\n * absolute file path it compiles from, the thread route passed the label `agent \"chat\"` it puts\n * in error messages, and both are values a reviewer reads as \"the agent\" without noticing that\n * neither is a name (usetheokit/theokit#406). A path identifies a file on one machine — it\n * changes with the deploy, splits one agent into a series per environment, and carries the\n * server's directory layout (on a developer machine, the user's account name) to a telemetry\n * backend nobody decided to export it to.\n *\n * If the module path is ever wanted for debugging it belongs on its own attribute\n * (`code.filepath` is the OpenTelemetry registry spelling), deliberately, and never as the key\n * an operator groups by.\n */\n readonly agentName: string\n /** The thread/session id, when the route has one. */\n readonly sessionId?: string\n /**\n * The request that started the run. Its `traceparent`, when it carries a valid\n * one, is what the run's spans join.\n */\n readonly request: Request\n}\n\n/**\n * Wrap a served run's chunk stream in spans, when telemetry is configured.\n *\n * No adapter ⇒ the stream is returned untouched, so an application that\n * configured no observability pays nothing — the zero-cost path this framework\n * promises, kept at the one place both routes now go through.\n */\nexport function observeServedRun<T>(\n stream: AsyncIterable<T>,\n options: ServedRunObservation,\n): AsyncIterable<T> {\n const adapter = getObservabilityAdapter()\n if (adapter === undefined) return stream\n\n // The request's trace, resolved once for the whole request rather than re-read from the header\n // here (usetheokit/theokit#404). Reading the header was the same answer only while a header was\n // there; without one, this side minted a trace of its own and the request split in two.\n const trace = requestTrace(options.request)\n const context: AgentRunSpanContext = { agent: options.agentName, traceId: trace.traceId }\n if (options.sessionId !== undefined) context.sessionId = options.sessionId\n\n // Under the span this process opened for the request when there is one; otherwise under the\n // caller's, which is the pre-existing behaviour for a traced request that reached a route with no\n // HTTP span. With neither, the run is the honest root of its own trace — naming a span nobody\n // emitted would read as a span lost in transit.\n const parentSpanId = trace.outermostSpanId ?? trace.parentSpanId\n if (parentSpanId !== undefined) context.parentSpanId = parentSpanId\n\n return observeAgentRun(stream, adapter, context)\n}\n","import type { WireChunk as UIMessageChunk } from '@theokit/presenter/wire'\n\nimport type { RunEventCache } from './run-event-cache.js'\n\n/**\n * M37 (ADR-0046) — the DURABLE variant of `uiMessageStreamResponse`. Same\n * `UIMessageStream` wire (`useChat` still consumes it), plus three additions so\n * a dropped client can reconnect without missing chunks:\n *\n * 1. each SSE frame gains a monotonic `id: <seq>\\n` line (SSE-native — the\n * browser echoes it as `Last-Event-ID` on reconnect, ADR-0046 D3);\n * 2. every frame is `append`ed to the {@link RunEventCache} keyed by `runId`\n * so the reconnect endpoint can replay it;\n * 3. the response carries `x-theokit-run-id: <runId>` so the client learns the\n * reconnect key (ADR-0046 D2).\n *\n * Fail-clear (error-handling.md): if the source aborts mid-stream, the run is\n * still `end`ed in the cache and `[DONE]` is flushed — never left hanging.\n */\n\n/**\n * The UIMessageStream SSE base headers — shared by the encoder, the thread route and the reconnect\n * handler (DRY), so a response cannot stream on one path and be buffered on another.\n *\n * `cache-control` and `x-accel-buffering` are what tell the PATH not to hold the run\n * (usetheokit/theokit#383). The server streamed correctly and said nothing downstream, so any\n * intermediary that buffers by default — nginx, a compressing reverse proxy, a CDN edge — was free\n * to deliver the whole run as one block at the end. That breaks where it is hardest to notice:\n * behind someone else's proxy, in production, looking correct.\n *\n * The Vercel AI SDK, whose wire this mirrors, sends a fifth — `connection: keep-alive`. It is\n * deliberately absent, on measurement rather than preference: it is hop-by-hop, Node manages\n * keep-alive itself on HTTP/1, and on HTTP/2 Node drops it with\n * `UnsupportedWarning: The provided connection header is not valid` — so it would buy nothing on\n * one protocol and print a warning per response on the other.\n */\nexport const SSE_BASE_HEADERS = {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache',\n 'x-accel-buffering': 'no',\n 'x-vercel-ai-ui-message-stream': 'v1',\n} as const\n\n/** Header the client reads to obtain the reconnect key. */\nexport const RUN_ID_HEADER = 'x-theokit-run-id'\n\nexport const SSE_DONE_FRAME = 'data: [DONE]\\n\\n'\n\n/** Format one SSE frame with its sequence id (shared by the encoder + reconnect replay). */\nexport function formatSseFrame(seq: number, data: string): string {\n return `id: ${seq}\\ndata: ${data}\\n\\n`\n}\n\n/** UTF-8 encode an SSE frame for a `ReadableStream<Uint8Array>` (shared). */\nexport function encodeSse(text: string): Uint8Array {\n return new TextEncoder().encode(text)\n}\n\ninterface DurableStreamDeps {\n readonly runId: string\n readonly cache: RunEventCache\n}\n\nexport function durableUiMessageStreamResponse(\n chunks: AsyncIterable<UIMessageChunk>,\n deps: DurableStreamDeps,\n): Response {\n const { runId, cache } = deps\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n try {\n for await (const chunk of chunks) {\n const data = JSON.stringify(chunk)\n const seq = cache.append(runId, data)\n controller.enqueue(encodeSse(formatSseFrame(seq, data)))\n }\n } catch {\n // Source aborted mid-stream. The upstream translator owns error\n // semantics (surfaces failures as chunks + closes gracefully); this\n // transport guarantees only a terminated, cache-ended stream.\n } finally {\n cache.end(runId)\n controller.enqueue(encodeSse(SSE_DONE_FRAME))\n controller.close()\n }\n },\n })\n return new Response(stream, {\n headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId },\n })\n}\n","/**\n * M37 (ADR-0046) — the durable event cache behind resumable agent streams.\n *\n * As an agent turn streams over SSE, each `UIMessageChunk` frame is `append`ed\n * here keyed by a transport `runId`. A client that drops and reconnects (or a\n * second client that observes) `attach`es to the run: it replays the frames it\n * missed (`seq > Last-Event-ID`) and then follows the live tail. This is the\n * TRANSPORT half of durable agents (ADR-0040/0044) — it caches serialized\n * frames, it does NOT run the agent loop.\n *\n * Single-process by default (an in-memory `Map`, same contract as the HITL\n * `approval-registry`). A persistent backend (Redis / `ConversationStorageAdapter`)\n * plugs in behind {@link RunEventCache} for multi-instance deploys — it is NOT\n * shipped in core (ADR-0046 D4: no broker in core).\n */\n\n/** One recorded SSE frame: its monotonic sequence id + the serialized `data:` payload. */\nexport interface CachedFrame {\n readonly seq: number\n readonly data: string\n}\n\n/** The result of {@link RunEventCache.attach}. */\nexport interface AttachResult {\n /** False when `runId` is unknown (never started, or evicted). */\n readonly known: boolean\n /** Frames with `seq > afterSeq`, in order — replay these before the live tail. */\n readonly replay: readonly CachedFrame[]\n /** True when the run already terminated: `replay` is complete, no live frames follow. */\n readonly ended: boolean\n /** Detach the live listener (idempotent). */\n readonly unsubscribe: () => void\n}\n\n/**\n * A per-`runId` ordered frame buffer with live fan-out. Implemented in-memory by\n * default; swap a persistent backend for multi-instance deploys.\n */\nexport interface RunEventCache {\n /**\n * M39 — synchronously register `runId` as a live (frame-less) run so `has()` is\n * true and a subscriber can `attach()` BEFORE the first frame. Idempotent.\n * Closes the race where a thread's active run is resolvable in the registry but\n * not yet in the cache (a headless pump appends its first frame asynchronously).\n */\n begin(runId: string): void\n /** Record a frame for `runId`, returning its assigned monotonic `seq`. Notifies live listeners. */\n append(runId: string, data: string): number\n /** Mark `runId` terminated: notify listeners, then schedule bounded eviction. Idempotent. */\n end(runId: string): void\n /** Whether `runId` is currently cached (started + not yet evicted). */\n has(runId: string): boolean\n /**\n * Atomically snapshot the frames after `afterSeq` AND (when the run is still\n * live) register `onFrame`/`onEnd` in the SAME synchronous tick — so no frame\n * slips between replay and subscribe, and none is duplicated.\n */\n attach(\n runId: string,\n afterSeq: number,\n onFrame: (frame: CachedFrame) => void,\n onEnd: () => void,\n ): AttachResult\n}\n\ninterface Listener {\n readonly onFrame: (frame: CachedFrame) => void\n readonly onEnd: () => void\n}\n\ninterface RunBuffer {\n readonly frames: CachedFrame[]\n ended: boolean\n readonly listeners: Set<Listener>\n evictTimer?: ReturnType<typeof setTimeout>\n}\n\nconst DEFAULT_EVICT_AFTER_MS = 5 * 60_000 // 5 min after end (parity with approval-registry)\n\nconst NOOP_UNSUBSCRIBE = (): void => {\n // No live listener was registered (unknown or already-ended run).\n}\n\ninterface RunEventCacheOptions {\n /** Milliseconds after `end()` before a run's buffer is evicted. Default 5 min. */\n readonly evictAfterMs?: number\n}\n\nexport function createInMemoryRunEventCache(opts: RunEventCacheOptions = {}): RunEventCache {\n const evictAfterMs = opts.evictAfterMs ?? DEFAULT_EVICT_AFTER_MS\n const runs = new Map<string, RunBuffer>()\n\n function getOrCreate(runId: string): RunBuffer {\n let buf = runs.get(runId)\n if (buf === undefined) {\n buf = { frames: [], ended: false, listeners: new Set() }\n runs.set(runId, buf)\n }\n return buf\n }\n\n return {\n begin(runId) {\n getOrCreate(runId)\n },\n\n append(runId, data) {\n const buf = getOrCreate(runId)\n const seq = buf.frames.length\n const frame: CachedFrame = { seq, data }\n buf.frames.push(frame)\n // Notify live listeners (a throwing listener must not break the others).\n for (const l of buf.listeners) {\n try {\n l.onFrame(frame)\n } catch {\n /* a broken subscriber never breaks the producer or its peers */\n }\n }\n return seq\n },\n\n has(runId) {\n return runs.has(runId)\n },\n\n end(runId) {\n const buf = runs.get(runId)\n if (buf === undefined || buf.ended) return\n buf.ended = true\n for (const l of buf.listeners) {\n try {\n l.onEnd()\n } catch {\n /* isolate a broken subscriber */\n }\n }\n buf.listeners.clear()\n buf.evictTimer = setTimeout(() => runs.delete(runId), evictAfterMs)\n // Never keep the process alive just for an eviction timer.\n buf.evictTimer.unref()\n },\n\n attach(runId, afterSeq, onFrame, onEnd) {\n const buf = runs.get(runId)\n if (buf === undefined) {\n return { known: false, replay: [], ended: false, unsubscribe: NOOP_UNSUBSCRIBE }\n }\n // Synchronous snapshot — no `await` before the subscribe below, so no\n // append can interleave (single-threaded): no gap, no dup.\n const replay = buf.frames.filter((f) => f.seq > afterSeq)\n if (buf.ended) {\n return { known: true, replay, ended: true, unsubscribe: NOOP_UNSUBSCRIBE }\n }\n const listener: Listener = { onFrame, onEnd }\n buf.listeners.add(listener)\n return {\n known: true,\n replay,\n ended: false,\n unsubscribe: () => {\n buf.listeners.delete(listener)\n },\n }\n },\n }\n}\n\n/**\n * Process-wide singleton — the SSE encoder (`durableUiMessageStreamResponse`) and\n * the reconnect endpoint MUST share ONE cache. Lazily created; a multi-instance\n * deploy swaps this accessor for a shared-store impl (ADR-0046 D4) without\n * touching callers. Tests use {@link createInMemoryRunEventCache} directly.\n */\nlet serverCache: RunEventCache | undefined\nexport function getRunEventCache(): RunEventCache {\n serverCache ??= createInMemoryRunEventCache()\n return serverCache\n}\n\n/** Mint a stable transport `runId` (the reconnect key, ADR-0046 D2). */\nexport function mintRunId(): string {\n return `run-${crypto.randomUUID()}`\n}\n","import type { ViteDevServer } from 'vite'\n\nimport { importUserModule } from '../../config/import-user-module.js'\n\nexport type LoadModule = (path: string) => Promise<Record<string, unknown>>\n\nexport function createViteLoader(vite: ViteDevServer): LoadModule {\n return (path) => vite.ssrLoadModule(path) as Promise<Record<string, unknown>>\n}\n\n/**\n * The loader `theokit start` uses to read user-authored modules off disk.\n *\n * It delegates to {@link importUserModule} rather than calling `import()` itself\n * (usetheokit/theokit#418). The raw call worked only because the CLI bin starts with\n * `import \"tsx/esm\"`, registering a global ESM hook — so this function depended on a side effect it\n * never performed, from a module it does not reference. Any caller that reached it another way (a\n * test booting the real handler, an app embedding the framework) got\n * `ERR_UNKNOWN_FILE_EXTENSION` for a `.ts` file, or `__filename is not defined in ES module scope`\n * from tsx's CJS output.\n *\n * That was invisible above Node 22.18, where native type stripping loads the file regardless, which\n * is how it survived on a project declaring `engines.node: \">=22.12.0\"`.\n *\n * Production is unchanged in cost: `importUserModule` tries the native import FIRST, so with the\n * hook registered it takes exactly the path this used to take, and the fallback only runs where the\n * raw call would have thrown.\n */\nexport function createProductionLoader(): LoadModule {\n return (path) => importUserModule(path)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { safeAudit, type AuditLogger } from '../observability/audit-log.js'\n\n/**\n * T5.1 — Built-in CSP report endpoint.\n *\n * Browsers POST violation reports to `report-uri` (legacy `application/csp-report`)\n * or `Reporting API` (`application/reports+json`). Framework auto-registers this\n * endpoint so `cspMode: 'report-only'` is actually useful out of the box.\n *\n * Forwards normalized violations to:\n * - audit logger (`csp.violation`)\n * - devtools dispatcher (dev only, for Errors tab)\n * - optional user hook (Sentry, etc.)\n *\n * EC-2: browser MAY send `{\"csp-report\": null}`, empty `{}`, or\n * reports+json entries lacking `body`. Handler MUST short-circuit to\n * 204 (valid format, no violation), NEVER crash via null deref.\n */\n\nexport const CSP_REPORT_PATH = '/__theo/csp-report'\n\n/** Max body bytes accepted. Real CSP reports are < 2 KB; 16 KB is generous. */\nconst MAX_BODY = 16 * 1024\n\nexport interface CspViolation {\n blockedUrl: string\n documentUrl: string\n violatedDirective: string\n effectiveDirective?: string\n originalPolicy?: string\n disposition?: 'enforce' | 'report'\n statusCode?: number\n sourceFile?: string\n lineNumber?: number\n columnNumber?: number\n}\n\nexport interface CspReportHandlerOptions {\n auditLogger?: AuditLogger\n devtoolsDispatcher?: {\n onCspViolation?: (v: CspViolation) => void\n }\n /** Optional user-provided sink (Sentry, custom log router). Errors here are swallowed. */\n onViolation?: (v: CspViolation) => void\n}\n\n/**\n * Map a legacy `application/csp-report` payload to the internal shape.\n * Caller must ensure `raw` is a non-null object.\n */\nfunction pickHeader(value: string | string[] | undefined): string {\n if (typeof value === 'string') return value\n if (Array.isArray(value) && value.length > 0) return value[0]\n return ''\n}\n\nfunction toStringSafe(value: unknown, fallback = '(missing)'): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return fallback\n}\n\nexport function normalizeLegacy(raw: Record<string, unknown>): CspViolation {\n return {\n blockedUrl: toStringSafe(raw['blocked-uri']),\n documentUrl: toStringSafe(raw['document-uri']),\n violatedDirective: toStringSafe(raw['violated-directive']),\n effectiveDirective:\n typeof raw['effective-directive'] === 'string' ? raw['effective-directive'] : undefined,\n originalPolicy: typeof raw['original-policy'] === 'string' ? raw['original-policy'] : undefined,\n disposition:\n raw.disposition === 'enforce' || raw.disposition === 'report' ? raw.disposition : undefined,\n statusCode: typeof raw['status-code'] === 'number' ? raw['status-code'] : undefined,\n sourceFile: typeof raw['source-file'] === 'string' ? raw['source-file'] : undefined,\n lineNumber: typeof raw['line-number'] === 'number' ? raw['line-number'] : undefined,\n columnNumber: typeof raw['column-number'] === 'number' ? raw['column-number'] : undefined,\n }\n}\n\n/**\n * Map a `reports+json` entry to the internal shape. Returns `null` if\n * the entry lacks a usable `body` object (EC-2).\n */\nexport function normalizeNew(entry: unknown): CspViolation | null {\n if (!entry || typeof entry !== 'object') return null\n const body = (entry as { body?: unknown }).body\n if (!body || typeof body !== 'object') return null\n const b = body as Record<string, unknown>\n return {\n blockedUrl: toStringSafe(b.blockedURL),\n documentUrl: toStringSafe(b.documentURL),\n violatedDirective: toStringSafe(b.violatedDirective),\n effectiveDirective: typeof b.effectiveDirective === 'string' ? b.effectiveDirective : undefined,\n originalPolicy: typeof b.originalPolicy === 'string' ? b.originalPolicy : undefined,\n disposition:\n b.disposition === 'enforce' || b.disposition === 'report' ? b.disposition : undefined,\n statusCode: typeof b.statusCode === 'number' ? b.statusCode : undefined,\n sourceFile: typeof b.sourceFile === 'string' ? b.sourceFile : undefined,\n lineNumber: typeof b.lineNumber === 'number' ? b.lineNumber : undefined,\n columnNumber: typeof b.columnNumber === 'number' ? b.columnNumber : undefined,\n }\n}\n\nasync function readBody(req: IncomingMessage, maxBytes: number): Promise<string> {\n return await new Promise<string>((resolve, reject) => {\n const chunks: Buffer[] = []\n let total = 0\n req.on('data', (chunk: Buffer) => {\n total += chunk.length\n if (total > maxBytes) {\n reject(new Error('body too large'))\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf8'))\n })\n req.on('error', reject)\n })\n}\n\nexport async function handleCspReport(\n req: IncomingMessage,\n res: ServerResponse,\n opts: CspReportHandlerOptions,\n): Promise<void> {\n const ctHeader = req.headers['content-type']\n const ct = pickHeader(ctHeader)\n\n let raw: string\n try {\n raw = await readBody(req, MAX_BODY)\n } catch {\n res.statusCode = 413\n res.end()\n return\n }\n\n let violations: CspViolation[]\n try {\n if (ct.startsWith('application/csp-report')) {\n // EC-2: browsers MAY POST {\"csp-report\": null} or {} on\n // disposition='report' policies. Guard against null/undefined/non-object.\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const inner = parsed['csp-report']\n if (!inner || typeof inner !== 'object') {\n res.statusCode = 204\n res.end()\n return\n }\n violations = [normalizeLegacy(inner as Record<string, unknown>)]\n } else if (ct.startsWith('application/reports+json')) {\n // EC-2: filter out entries lacking `body` BEFORE normalizing.\n const parsed: unknown = JSON.parse(raw)\n const entries = Array.isArray(parsed) ? parsed : []\n violations = entries.map((e) => normalizeNew(e)).filter((v): v is CspViolation => v !== null)\n } else {\n res.statusCode = 415\n res.end()\n return\n }\n } catch {\n res.statusCode = 400\n res.end()\n return\n }\n\n for (const v of violations) {\n safeAudit(opts.auditLogger, {\n action: 'csp.violation',\n metadata: v as unknown as Record<string, unknown>,\n })\n try {\n opts.devtoolsDispatcher?.onCspViolation?.(v)\n } catch {\n // dispatcher errors are isolated from the request\n }\n try {\n opts.onViolation?.(v)\n } catch {\n // user hook throws are swallowed — never crash the request\n }\n }\n\n res.statusCode = 204\n res.end()\n}\n\n/**\n * T5a.2 Phase B slice 4/6 — Web-Standards CSP report handler.\n *\n * Mirror of `handleCspReport(req: IncomingMessage, res: ServerResponse,\n * opts): Promise<void>` for the Web `Request` shape. Returns\n * `Response` directly instead of mutating `res`.\n *\n * Same content-type dispatch (legacy `application/csp-report` vs new\n * `application/reports+json`), same normalizers (`normalizeLegacy`,\n * `normalizeNew`), same side-effect loop (safeAudit + devtools + user\n * hook). The body cap is enforced post-read because Web Request body\n * streaming doesn't have a portable mid-stream rejection primitive\n * across CF Workers / Bun / Deno; CSP reports are < 2 KB typical, well\n * under MAX_BODY (16 KB).\n *\n * Returns:\n * - 204 on accepted reports OR no-op empty payload\n * - 413 on body too large (post-read check)\n * - 415 on unsupported content-type\n * - 400 on malformed JSON\n */\nasync function readBodyFromRequest(request: Request, maxBytes: number): Promise<string | null> {\n const contentLengthHeader = request.headers.get('content-length')\n if (contentLengthHeader !== null) {\n const declared = Number.parseInt(contentLengthHeader, 10)\n if (Number.isFinite(declared) && declared > maxBytes) return null\n }\n const text = await request.text()\n if (text.length > maxBytes) return null\n return text\n}\n\nfunction dispatchViolations(violations: CspViolation[], opts: CspReportHandlerOptions): void {\n for (const v of violations) {\n safeAudit(opts.auditLogger, {\n action: 'csp.violation',\n metadata: v as unknown as Record<string, unknown>,\n })\n try {\n opts.devtoolsDispatcher?.onCspViolation?.(v)\n } catch {\n // dispatcher errors are isolated from the request\n }\n try {\n opts.onViolation?.(v)\n } catch {\n // user hook throws are swallowed — never crash the request\n }\n }\n}\n\nexport async function handleCspReportRequest(\n request: Request,\n opts: CspReportHandlerOptions,\n): Promise<Response> {\n const ct = request.headers.get('content-type') ?? ''\n\n const raw = await readBodyFromRequest(request, MAX_BODY)\n if (raw === null) {\n return new Response(null, { status: 413 })\n }\n\n let violations: CspViolation[]\n try {\n if (ct.startsWith('application/csp-report')) {\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const inner = parsed['csp-report']\n if (!inner || typeof inner !== 'object') {\n return new Response(null, { status: 204 })\n }\n violations = [normalizeLegacy(inner as Record<string, unknown>)]\n } else if (ct.startsWith('application/reports+json')) {\n const parsed: unknown = JSON.parse(raw)\n const entries = Array.isArray(parsed) ? parsed : []\n violations = entries.map((e) => normalizeNew(e)).filter((v): v is CspViolation => v !== null)\n } else {\n return new Response(null, { status: 415 })\n }\n } catch {\n return new Response(null, { status: 400 })\n }\n\n dispatchViolations(violations, opts)\n return new Response(null, { status: 204 })\n}\n","/**\n * T2.2 — `/__theo/csrf-readiness` endpoint.\n *\n * GET /__theo/csrf-readiness → 200 + JSON summary\n * POST /__theo/csrf-readiness/reset → 204; clears the store\n *\n * The reset endpoint enforces CSRF (own dog food) — requires\n * `X-Theo-Action: 1` AND a matching Origin header (EC-15). This avoids\n * the endpoint being weaponizable from a cross-origin page when the\n * endpoint is opt-in exposed in production.\n *\n * Mount opt-in: in dev mode, the host wires this in unconditionally. In\n * production, only mount when `config.security.csrfTelemetry.exposeReadinessEndpoint === true`.\n * EC-10 parallel: returns 404 (via boolean false return) when the URL\n * does not match — the caller continues normal request handling.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { CsrfReadinessStore } from './csrf-readiness-store.js'\n\nexport const CSRF_READINESS_PATH = '/__theo/csrf-readiness'\nexport const CSRF_READINESS_RESET_PATH = '/__theo/csrf-readiness/reset'\n\nfunction originMatchesHost(req: IncomingMessage): boolean {\n const origin = req.headers.origin\n if (typeof origin !== 'string') return false\n const host = req.headers.host\n if (typeof host !== 'string') return false\n try {\n const parsed = new URL(origin)\n return parsed.host === host\n } catch {\n return false\n }\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\nfunction sendNoContent(res: ServerResponse): void {\n res.writeHead(204)\n res.end()\n}\n\nfunction sendError(res: ServerResponse, status: number, code: string, message: string): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ error: { code, message } }))\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async return for future telemetry hooks\nexport async function handleCsrfReadiness(\n req: IncomingMessage,\n res: ServerResponse,\n store: CsrfReadinessStore,\n): Promise<boolean> {\n const url = (req.url ?? '').split('?')[0]\n const method = req.method ?? 'GET'\n\n if (url === CSRF_READINESS_PATH) {\n if (method === 'GET') {\n sendJson(res, 200, store.summary())\n return true\n }\n sendError(res, 405, 'METHOD_NOT_ALLOWED', `Use GET on ${CSRF_READINESS_PATH}`)\n return true\n }\n\n if (url === CSRF_READINESS_RESET_PATH) {\n if (method !== 'POST') {\n sendError(res, 405, 'METHOD_NOT_ALLOWED', `Use POST on ${CSRF_READINESS_RESET_PATH}`)\n return true\n }\n // Enforce CSRF on our own endpoint (dog-food).\n const hasHeader = req.headers['x-theo-action'] === '1'\n if (!hasHeader || !originMatchesHost(req)) {\n sendError(res, 403, 'CSRF_INVALID', 'Reset requires X-Theo-Action: 1 + same-origin')\n return true\n }\n store.reset()\n sendNoContent(res)\n return true\n }\n\n return false\n}\n\n/**\n * T5a.2 Phase B slice 3/6 — Web-Standards-shaped CSRF readiness handler.\n *\n * Mirror of `handleCsrfReadiness(req: IncomingMessage, res: ServerResponse,\n * store): Promise<boolean>` for the Web `Request` shape. Returns\n * `Response | null` instead of mutating `res` and returning a boolean:\n * - `Response` → this handler claimed the URL; caller short-circuits.\n * - `null` → URL doesn't match our endpoint; caller continues normal dispatch.\n *\n * Same routes (GET `CSRF_READINESS_PATH`, POST `CSRF_READINESS_RESET_PATH`).\n * Same CSRF dog-food on reset (X-Theo-Action + same-origin).\n *\n * Wire into `executeWebRequest` integration via a future Phase B sub-slice\n * (consumer can also call this directly today via the\n * `theokit/server/security` sub-path).\n */\nfunction buildJsonResponse(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nfunction buildErrorResponse(status: number, code: string, message: string): Response {\n return buildJsonResponse(status, { error: { code, message } })\n}\n\n/**\n * Returns true when `Origin` header and request URL host match (RFC 6454\n * same-origin check). Web-Standards counterpart of `originMatchesHost`.\n */\nfunction originMatchesHostFromRequest(request: Request): boolean {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return false\n const host = request.headers.get('host')\n if (host === null || host.length === 0) {\n // Fallback: derive host from request.url (Web Request guarantees absolute URL)\n try {\n const reqHost = new URL(request.url).host\n const originHost = new URL(origin).host\n return originHost === reqHost\n } catch {\n return false\n }\n }\n try {\n return new URL(origin).host === host\n } catch {\n return false\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async return for future telemetry hooks\nexport async function handleCsrfReadinessRequest(\n request: Request,\n store: CsrfReadinessStore,\n): Promise<Response | null> {\n const url = new URL(request.url).pathname\n const method = request.method.toUpperCase()\n\n if (url === CSRF_READINESS_PATH) {\n if (method === 'GET') {\n return buildJsonResponse(200, store.summary())\n }\n return buildErrorResponse(405, 'METHOD_NOT_ALLOWED', `Use GET on ${CSRF_READINESS_PATH}`)\n }\n\n if (url === CSRF_READINESS_RESET_PATH) {\n if (method !== 'POST') {\n return buildErrorResponse(\n 405,\n 'METHOD_NOT_ALLOWED',\n `Use POST on ${CSRF_READINESS_RESET_PATH}`,\n )\n }\n // Enforce CSRF on our own endpoint (dog-food).\n const hasHeader = request.headers.get('x-theo-action') === '1'\n if (!hasHeader || !originMatchesHostFromRequest(request)) {\n return buildErrorResponse(\n 403,\n 'CSRF_INVALID',\n 'Reset requires X-Theo-Action: 1 + same-origin',\n )\n }\n store.reset()\n return new Response(null, { status: 204 })\n }\n\n return null\n}\n","/**\n * T2.2 — In-memory bounded counter for CSRF warn events.\n *\n * Aggregates `csrf.warn` payloads by `(method, path, reason)` triple.\n * Used by the `/__theo/csrf-readiness` endpoint to expose a summary the\n * developer (or devtools tab) can inspect, so users do NOT need to grep\n * stdout to know which endpoints will break under 0.3.0 strict CSRF.\n *\n * Bounded at 1000 distinct keys (EC-22). Eviction is LRU-by-insertion —\n * when the cap is hit, the oldest key is dropped and a re-record of an\n * evicted key starts fresh (count: 1).\n *\n * Single-threaded by virtue of the JS event loop; Map operations are\n * atomic. NOT shared across processes — each worker has its own store.\n */\n\nexport interface CsrfWarnRecord {\n method: string\n path: string\n reason: string\n}\n\nexport interface CsrfReadinessRouteSummary {\n method: string\n path: string\n reason: string\n count: number\n firstSeen: string\n lastSeen: string\n}\n\nexport interface CsrfReadinessSummary {\n generatedAt: string\n totalEvents: number\n routes: CsrfReadinessRouteSummary[]\n}\n\ninterface StoredEntry {\n count: number\n firstSeen: string\n lastSeen: string\n}\n\nexport class CsrfReadinessStore {\n static readonly MAX_ENTRIES = 1000\n private readonly entries = new Map<string, StoredEntry>()\n\n private keyFor(event: CsrfWarnRecord): string {\n return `${event.method}\u0000${event.path}\u0000${event.reason}`\n }\n\n record(event: CsrfWarnRecord): void {\n const key = this.keyFor(event)\n const now = new Date().toISOString()\n const existing = this.entries.get(key)\n if (existing) {\n existing.count++\n existing.lastSeen = now\n return\n }\n if (this.entries.size >= CsrfReadinessStore.MAX_ENTRIES) {\n const firstKey = this.entries.keys().next().value\n if (firstKey !== undefined) this.entries.delete(firstKey)\n }\n this.entries.set(key, { count: 1, firstSeen: now, lastSeen: now })\n }\n\n summary(): CsrfReadinessSummary {\n let total = 0\n const routes: CsrfReadinessRouteSummary[] = []\n for (const [key, entry] of this.entries) {\n const [method, path, reason] = key.split('\u0000')\n routes.push({\n method,\n path,\n reason,\n count: entry.count,\n firstSeen: entry.firstSeen,\n lastSeen: entry.lastSeen,\n })\n total += entry.count\n }\n return {\n generatedAt: new Date().toISOString(),\n totalEvents: total,\n routes,\n }\n }\n\n reset(): void {\n this.entries.clear()\n }\n}\n","import type { ServerResponse } from 'node:http'\n\nimport {\n buildSecurityHeaders,\n type SecurityEnv,\n type SecurityHeadersConfig,\n type SecurityHeadersOptions,\n} from '../../core/contracts/security-headers.js'\n\n/**\n * The Node half of the security-header baseline.\n *\n * The policy itself — what a configuration means, what the defaults are, how a\n * nonce enters the CSP — moved to `core/contracts/security-headers.ts` when the\n * deploy adapters started needing it too. `adapters → server` is not an edge in\n * the module DAG (ADR-0001 v3), and the honest reading of the violation was that\n * a pure `config → Record<string, string>` function had never been server code.\n *\n * What stays here is the one part that genuinely is: writing that map onto a\n * Node `ServerResponse`.\n *\n * Everything from core is re-exported so `theokit/server/security` keeps the\n * surface it published.\n */\nexport * from '../../core/contracts/security-headers.js'\n\n/**\n * Apply security headers to a Node ServerResponse. Called by the\n * api-middleware before the route handler runs. The handler can override\n * any header via `res.setHeader()` — last write wins by Node convention.\n */\nexport function applySecurityHeaders(\n res: ServerResponse,\n config: SecurityHeadersConfig,\n env: SecurityEnv,\n options: SecurityHeadersOptions = {},\n): void {\n const headers = buildSecurityHeaders(config, env, options)\n for (const [key, value] of Object.entries(headers)) {\n res.setHeader(key, value)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAM,iBAAkD;AAAA,EACtD,kBAAkB;AAAA,EAClB,aAAa;AAAA,EACb,cAAc;AAAA,EACd,WAAW;AAAA,EACX,WAAW;AAAA,EACX,oBAAoB;AAAA,EACpB,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,wBAAwB;AAAA,EACxB,mBAAmB;AAAA,EACnB,uBAAuB;AACzB;AAEA,IAAM,iBAAkD;AAAA,EACtD,KAAK;AAAA,EAC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AAA,EAEA,UAAgC;AAC9B,QAAI,QAAQ;AACZ,UAAM,SAAsC,CAAC;AAC7C,eAAW,CAAC,KAAK,KAAK,KAAK,KAAK,SAAS;AACvC,YAAM,CAAC,QAAQ,MAAM,MAAM,IAAI,IAAI,MAAM,IAAG;AAC5C,aAAO,KAAK;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO,MAAM;AAAA,QACb,WAAW,MAAM;AAAA,QACjB,UAAU,MAAM;AAAA,MAClB,CAAC;AACD,eAAS,MAAM;AAAA,IACjB;AACA,WAAO;AAAA,MACL,cAAa,oBAAI,KAAK,GAAE,YAAY;AAAA,MACpC,aAAa;AAAA,MACb;AAAA,IACF;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,SAAK,QAAQ,MAAM;AAAA,EACrB;AACF;;;AC7DO,SAAS,qBACd,KACA,QACA,KACA,UAAkC,CAAC,GAC7B;AACN,QAAM,UAAU,qBAAqB,QAAQ,KAAK,OAAO;AACzD,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,GAAG;AAClD,QAAI,UAAU,KAAK,KAAK;AAAA,EAC1B;AACF;","names":["existsSync","join","CODE_TO_STATUS","join","existsSync","ctx","body","z","z","compileAgentModule","resolveEnabledSkills","streamAgentUIMessages","compileAgentModule","resolveEnabledSkills","streamAgentUIMessages","sendJson","sendError"]}
|