theokit 0.36.0 → 0.36.1

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.
Files changed (48) hide show
  1. package/dist/{actions-virtual-module-BCN7IEQC.js → actions-virtual-module-3KSP3WPJ.js} +3 -3
  2. package/dist/{actions-virtual-module-AX6UMYF5.js → actions-virtual-module-SYGQE6JQ.js} +2 -2
  3. package/dist/{agent-4FJK6PRR.js → agent-DX5LHD6X.js} +2 -2
  4. package/dist/{app-typed-client-U3OCOWYT.js → app-typed-client-ESMMLPYK.js} +2 -2
  5. package/dist/{app-typed-client-LM2PNOCL.js → app-typed-client-N4TRX5FI.js} +3 -3
  6. package/dist/{build-YQ3AWJV2.js → build-3C2KQPME.js} +2 -2
  7. package/dist/{chunk-WR4F4EEZ.js → chunk-3KD2O6DC.js} +54 -2
  8. package/dist/chunk-3KD2O6DC.js.map +1 -0
  9. package/dist/{chunk-F46GSPV7.js → chunk-DISADTFZ.js} +2 -2
  10. package/dist/{chunk-5VRQVXHH.js → chunk-MNQC5XEJ.js} +7 -41
  11. package/dist/{chunk-5VRQVXHH.js.map → chunk-MNQC5XEJ.js.map} +1 -1
  12. package/dist/{chunk-KXA37ONC.js → chunk-RPMKF6BC.js} +2 -2
  13. package/dist/{chunk-S7L6H3KP.js → chunk-RVJAM77M.js} +2 -38
  14. package/dist/{chunk-S7L6H3KP.js.map → chunk-RVJAM77M.js.map} +1 -1
  15. package/dist/{chunk-OOS5LB5Y.js → chunk-T4TCLEFB.js} +8 -8
  16. package/dist/{chunk-4MTCKE5I.js → chunk-UDG6JPVP.js} +2 -2
  17. package/dist/{chunk-TGTNRUH3.js → chunk-WL4AX5FI.js} +54 -2
  18. package/dist/chunk-WL4AX5FI.js.map +1 -0
  19. package/dist/cli/index.js +5 -5
  20. package/dist/{dev-PESPUGQU.js → dev-CNPT7COE.js} +5 -5
  21. package/dist/index.js +3 -3
  22. package/dist/{internal-api-CS3AG7MT.js → internal-api-4IXBITVV.js} +2 -2
  23. package/dist/{internal-api-CCRY3HN4.js → internal-api-5JKDYRGM.js} +3 -3
  24. package/dist/{mcp-FMZSFEEQ.js → mcp-INKDONQS.js} +2 -2
  25. package/dist/server/http/index.js +1 -1
  26. package/dist/server/index.js +2 -2
  27. package/dist/{start-CHMKI2KH.js → start-LNJZNKF6.js} +4 -4
  28. package/dist/vite-plugin/index.js +3 -3
  29. package/dist/{vite-plugin-T3EXDNQQ.js → vite-plugin-NC5ETNMV.js} +5 -5
  30. package/package.json +2 -2
  31. package/dist/chunk-TGTNRUH3.js.map +0 -1
  32. package/dist/chunk-WR4F4EEZ.js.map +0 -1
  33. /package/dist/{actions-virtual-module-BCN7IEQC.js.map → actions-virtual-module-3KSP3WPJ.js.map} +0 -0
  34. /package/dist/{actions-virtual-module-AX6UMYF5.js.map → actions-virtual-module-SYGQE6JQ.js.map} +0 -0
  35. /package/dist/{agent-4FJK6PRR.js.map → agent-DX5LHD6X.js.map} +0 -0
  36. /package/dist/{app-typed-client-U3OCOWYT.js.map → app-typed-client-ESMMLPYK.js.map} +0 -0
  37. /package/dist/{app-typed-client-LM2PNOCL.js.map → app-typed-client-N4TRX5FI.js.map} +0 -0
  38. /package/dist/{build-YQ3AWJV2.js.map → build-3C2KQPME.js.map} +0 -0
  39. /package/dist/{chunk-F46GSPV7.js.map → chunk-DISADTFZ.js.map} +0 -0
  40. /package/dist/{chunk-KXA37ONC.js.map → chunk-RPMKF6BC.js.map} +0 -0
  41. /package/dist/{chunk-OOS5LB5Y.js.map → chunk-T4TCLEFB.js.map} +0 -0
  42. /package/dist/{chunk-4MTCKE5I.js.map → chunk-UDG6JPVP.js.map} +0 -0
  43. /package/dist/{dev-PESPUGQU.js.map → dev-CNPT7COE.js.map} +0 -0
  44. /package/dist/{internal-api-CCRY3HN4.js.map → internal-api-4IXBITVV.js.map} +0 -0
  45. /package/dist/{internal-api-CS3AG7MT.js.map → internal-api-5JKDYRGM.js.map} +0 -0
  46. /package/dist/{mcp-FMZSFEEQ.js.map → mcp-INKDONQS.js.map} +0 -0
  47. /package/dist/{start-CHMKI2KH.js.map → start-LNJZNKF6.js.map} +0 -0
  48. /package/dist/{vite-plugin-T3EXDNQQ.js.map → vite-plugin-NC5ETNMV.js.map} +0 -0
@@ -2,7 +2,7 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  safeAudit
5
- } from "./chunk-WR4F4EEZ.js";
5
+ } from "./chunk-3KD2O6DC.js";
6
6
 
7
7
  // src/server/http/batch-handler.ts
8
8
  import { z } from "zod";
@@ -418,4 +418,4 @@ export {
418
418
  handleCsrfReadiness,
419
419
  CsrfReadinessStore
420
420
  };
421
- //# sourceMappingURL=chunk-KXA37ONC.js.map
421
+ //# sourceMappingURL=chunk-RPMKF6BC.js.map
@@ -10,7 +10,7 @@ import {
10
10
  } from "./chunk-M6NMS5LR.js";
11
11
  import {
12
12
  validateCsrfRequest
13
- } from "./chunk-WR4F4EEZ.js";
13
+ } from "./chunk-3KD2O6DC.js";
14
14
 
15
15
  // src/server/transformer.ts
16
16
  import superjson from "superjson";
@@ -735,34 +735,6 @@ function isMcpExposed(mod) {
735
735
  }
736
736
 
737
737
  // src/server/http/node-web-adapter.ts
738
- import { Readable } from "stream";
739
- function incomingMessageToWebRequest(req) {
740
- const host = pickHeaderString(req.headers.host) ?? "localhost";
741
- const url = `http://${host}${req.url ?? "/"}`;
742
- const headers = new Headers();
743
- for (const [key, value] of Object.entries(req.headers)) {
744
- if (value === void 0) continue;
745
- if (Array.isArray(value)) {
746
- headers.set(key, value.join(", "));
747
- } else {
748
- headers.set(key, value);
749
- }
750
- }
751
- const method = (req.method ?? "GET").toUpperCase();
752
- const hasBody = method !== "GET" && method !== "HEAD";
753
- if (!hasBody) {
754
- return new Request(url, { method, headers });
755
- }
756
- const webStream = Readable.toWeb(req);
757
- return new Request(url, {
758
- method,
759
- headers,
760
- body: webStream,
761
- // EC-2: Node 18+ requires `duplex: 'half'` when body is a stream.
762
- // The `RequestInit` type omits it (Web spec gap); cast accordingly.
763
- ...{ duplex: "half" }
764
- });
765
- }
766
738
  async function writeWebResponseToServerResponse(response, res) {
767
739
  const setCookies = response.headers.getSetCookie();
768
740
  if (setCookies.length > 0) {
@@ -790,13 +762,6 @@ async function writeWebResponseToServerResponse(response, res) {
790
762
  reader.releaseLock();
791
763
  }
792
764
  }
793
- function pickHeaderString(value) {
794
- if (typeof value === "string") return value;
795
- if (Array.isArray(value)) {
796
- for (const v of value) if (typeof v === "string" && v.length > 0) return v;
797
- }
798
- return void 0;
799
- }
800
765
 
801
766
  export {
802
767
  resolveTransformer,
@@ -806,7 +771,6 @@ export {
806
771
  isListApprovalsPath,
807
772
  mountAgent,
808
773
  serveAgentAuxRoute,
809
- incomingMessageToWebRequest,
810
774
  writeWebResponseToServerResponse
811
775
  };
812
- //# sourceMappingURL=chunk-S7L6H3KP.js.map
776
+ //# sourceMappingURL=chunk-RVJAM77M.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server/transformer.ts","../src/server/agent/agent-card-handler.ts","../src/server/agent/approve-agent.ts","../src/server/agent/list-approvals-handler.ts","../src/server/agent/mount-agent.ts","../src/server/agent/build-agent-streamer.ts","../src/server/agent/durable-ui-message-stream-response.ts","../src/server/agent/run-event-cache.ts","../src/server/agent/handle-agent-run-reconnect.ts","../src/server/agent/thread-dispatcher.ts","../src/server/agent/thread-run-registry.ts","../src/server/agent/handle-thread-routes.ts","../src/server/agent/serve-aux-routes.ts","../src/server/http/node-web-adapter.ts"],"sourcesContent":["import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * M15 (theokit-ai-first) — serve the A2A agent card at `/.well-known/<name>/agent-card.json`.\n *\n * `buildAgentCard` (@theokit/agents) is the pure generator; this handler compiles a loaded agent\n * module to its tools + streaming capability, builds the card, and returns it as a Web-Standard\n * JSON `Response` (G8). The dev middleware + prod handler branch to this before the agent POST route.\n */\nimport {\n type AgentManifestEntry,\n buildAgentCard,\n compileAgentModule,\n} from '@theokit/agents'\n\nconst WELL_KNOWN = /^\\/\\.well-known\\/([^/]+)\\/agent-card\\.json$/\n\n/** Return the agent name when `urlPath` is a well-known card path, else `null`. */\nexport function isAgentCardPath(urlPath: string): string | null {\n const match = WELL_KNOWN.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Build a minimal manifest entry (the subset `buildAgentCard` reads) from a compiled agent. */\nfunction toManifestEntry(name: string, route: string, mod: unknown): AgentManifestEntry {\n const compiled = compileAgentModule(mod, `agent card for \"${name}\"`)\n return {\n name,\n route,\n stream: compiled.stream,\n mainLoop: { method: '', strategy: '' },\n guards: [],\n interceptors: [],\n tools: compiled.tools.map((t) => ({\n name: t.name,\n description: t.description,\n approval: false,\n trace: false,\n audit: false,\n })),\n subAgents: [],\n }\n}\n\n/**\n * Serve the A2A card for a loaded agent module. Returns 200 with the card JSON, or 500 with an\n * error body if the module is not a valid agent (fail-clear, not a silent empty card).\n */\nexport function handleAgentCard(mod: unknown, name: string, route: string, baseUrl: string): Response {\n try {\n const card = buildAgentCard(toManifestEntry(name, route, mod), { baseUrl })\n return new Response(JSON.stringify(card), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n } catch (err) {\n return new Response(\n JSON.stringify({ error: { code: 'AGENT_CARD_FAILED', message: err instanceof Error ? err.message : 'card build failed' } }),\n { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } },\n )\n }\n}\n","/**\n * M4 (theokit-ai-first) — the HITL approve endpoint: `POST /api/agents/<name>/approve/<approvalId>`.\n *\n * The counterpart to `mountAgent`'s HITL pause. While a gated tool holds the SDK run paused (the\n * awaited `pre_tool_call` hook), the client POSTs here with `{ approved }`; this resolves the\n * pending approval in the shared registry, which un-pauses the run (allow) or vetoes the tool (deny).\n *\n * Web-Standard `Request` → `Response`, one wiring point shared by dev (vite middleware) and prod\n * (built server) so the two never drift (EC-4 parity with `mountAgent`). The registry is INJECTED —\n * dev/prod pass the process singleton (`getApprovalRegistry`), tests pass a fresh instance.\n */\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport type { ApprovalDecision, ApprovalRegistry } from './approval-registry.js'\n\n/** The path segment separating the agent name from the approval id. */\nconst APPROVE_SEGMENT = '/approve/'\n\n/**\n * Extract the `<approvalId>` from a `/api/agents/<name>/approve/<approvalId>` path.\n * Returns `null` when the path has no `/approve/` segment or an empty / nested id.\n */\nexport function parseApprovalId(urlPath: string): string | null {\n const at = urlPath.indexOf(APPROVE_SEGMENT)\n if (at === -1) return null\n const id = urlPath.slice(at + APPROVE_SEGMENT.length)\n return id.length > 0 && !id.includes('/') ? id : null\n}\n\n/** True when `urlPath` targets a HITL approve endpoint (used by dev/prod routing to branch early). */\nexport function isApprovalPath(urlPath: string): boolean {\n return urlPath.includes(APPROVE_SEGMENT)\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * M20 — cap on the serialized custom payload (16 KiB). A payload is a small structured note\n * (edited args, a reviewer comment), not a data channel — an oversized one is rejected fail-fast\n * rather than silently truncated (Rule 8).\n */\nconst MAX_PAYLOAD_BYTES = 16 * 1024\n\n/**\n * Extract an {@link ApprovalDecision} from an untrusted body; `null` when the shape is wrong.\n *\n * M20 — accepts an optional `reason` (string) and `payload` (object, capped at\n * {@link MAX_PAYLOAD_BYTES}). Backward-compatible: `{ approved }` and `{ approved, reason }` parse\n * unchanged. A non-object or oversized `payload` is rejected (returns `null` → the route 400s).\n *\n * @public\n */\nexport function parseApprovalBody(body: unknown): ApprovalDecision | null {\n if (typeof body !== 'object' || body === null) return null\n const b = body as Record<string, unknown>\n if (typeof b.approved !== 'boolean') return null\n const decision: ApprovalDecision = { approved: b.approved }\n if (b.reason !== undefined) {\n if (typeof b.reason !== 'string') return null\n decision.reason = b.reason\n }\n if (b.payload !== undefined) {\n if (typeof b.payload !== 'object' || b.payload === null || Array.isArray(b.payload)) return null\n if (JSON.stringify(b.payload).length > MAX_PAYLOAD_BYTES) return null\n decision.payload = b.payload\n }\n return decision\n}\n\n/**\n * Resolve a pending HITL approval. CSRF-guarded like `mountAgent` (the custom `X-Theo-Action`\n * header + Origin match) — a cross-origin POST must not approve a paused tool. Returns:\n * 403 CSRF_FAILED — strict CSRF check failed\n * 400 BAD_REQUEST — no `/approve/<id>` in the path, or body lacks a boolean `approved`\n * 404 NOT_PENDING — the id is unknown or already settled (idempotent double-submit)\n * 200 { resolved:true } — the approval was settled by this call\n */\nexport async function handleAgentApproval(\n request: Request,\n urlPath: string,\n registry: ApprovalRegistry,\n csrfMode: CsrfMode = 'strict',\n): Promise<Response> {\n if (csrfMode !== 'off') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid && csrfMode === 'strict') {\n return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n }\n\n const approvalId = parseApprovalId(urlPath)\n if (approvalId === null) {\n return jsonError(400, 'BAD_REQUEST', 'Approval path must be /api/agents/<name>/approve/<id>.')\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\n }\n const parsed = parseApprovalBody(body)\n if (parsed === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request body must contain a boolean `approved`.')\n }\n\n const resolved = registry.resolve(approvalId, parsed)\n if (!resolved) {\n return jsonError(404, 'NOT_PENDING', `No pending approval for id '${approvalId}'.`)\n }\n return new Response(JSON.stringify({ resolved: true }), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n","/**\n * M14 (theokit-ai-first) — GET /api/agents/<name>/approvals: list pending HITL approvals.\n *\n * Serves `ApprovalRegistry.list()` as JSON. Single-process contract (ADR 0038) — the list is\n * process-wide; the `<name>` segment is accepted for a future per-agent/durable store but the\n * in-process registry lists all pending approvals. Web Standards Response (G8).\n */\nimport type { ApprovalRegistry } from './approval-registry.js'\n\nconst LIST_PATH = /^\\/api\\/agents\\/([^/]+)\\/approvals$/\n\n/** Return the agent name when `urlPath` is the approvals-listing path, else `null`. */\nexport function isListApprovalsPath(urlPath: string): string | null {\n const match = LIST_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Serve the currently-pending approvals as `{ approvals: [...] }` JSON. */\nexport function handleListApprovals(registry: ApprovalRegistry): Response {\n return new Response(JSON.stringify({ approvals: registry.list() }), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\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 { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { buildAgentHitl } from './build-agent-streamer.js'\nimport { durableUiMessageStreamResponse } from './durable-ui-message-stream-response.js'\nimport { getRunEventCache, mintRunId } from './run-event-cache.js'\n\n/** The message + session extracted from a chat request, or `null` when the body is invalid. */\nexport interface 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/**\n * Mount a loaded agent module as a `Response`. `apiKey` is resolved by the caller\n * (`resolveProvider`). `source` labels a fail-fast `AgentDefinitionError` (the file path).\n */\nexport async function mountAgent(\n mod: unknown,\n request: Request,\n apiKey: string,\n source = 'agent module',\n csrfMode: CsrfMode = 'strict',\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 const compiled = compileAgentModule(mod, source)\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 let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\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 // 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)\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 return durableUiMessageStreamResponse(\n streamAgentUIMessages(compiled, apiKey, { ...input, hitl, signal: request.signal }),\n { runId, cache: getRunEventCache() },\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 { UIMessageChunk } from 'ai'\n\nimport { getApprovalRegistry } from './approval-registry.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) {\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 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 */\nexport function makeThreadStartRun(\n mod: unknown,\n apiKey: string,\n source: string,\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 const hitl = buildAgentHitl(compiled)\n yield* streamAgentUIMessages(compiled, apiKey, { message, sessionId, hitl })\n })()\n}\n","import type { UIMessageChunk } from 'ai'\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/** The UIMessageStream SSE base headers — shared by the encoder + reconnect handler (DRY). */\nexport const SSE_BASE_HEADERS = {\n 'content-type': 'text/event-stream',\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\nexport interface 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\nexport interface 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 {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport type { RunEventCache } from './run-event-cache.js'\n\n/**\n * M37 (ADR-0046 D5) — the reconnect / observe endpoint handler for\n * `GET /api/agents/<name>/runs/<runId>/stream`.\n *\n * Replays the frames the client missed (`seq > Last-Event-ID`, SSE-native), then\n * — if the run is still live — follows the live tail; a SECOND client can\n * observe a run a first started. Run already ended ⇒ replay + `[DONE]`. Unknown\n * `runId` ⇒ 404. The request `AbortSignal` unsubscribes on disconnect.\n */\n\nconst RUN_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/runs\\/([^/]+)\\/stream$/\n\n/**\n * Match `GET /api/agents/<name>/runs/<runId>/stream`; returns the decoded\n * `{ name, runId }` or `null` to fall through (mirrors `isMcpPath` etc.).\n */\nexport function isAgentRunStreamPath(urlPath: string): { name: string; runId: string } | null {\n const m = RUN_STREAM_PATH.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), runId: decodeURIComponent(m[2]) } : null\n}\n\n/** Parse `Last-Event-ID` (a frame `seq`) to a number; absent/invalid ⇒ -1 (replay from the start). */\nfunction parseLastEventId(raw: string | null): number {\n if (raw === null) return -1\n const n = Number.parseInt(raw, 10)\n return Number.isInteger(n) && n >= 0 ? n : -1\n}\n\nexport function handleAgentRunReconnect(\n runId: string,\n request: Request,\n cache: RunEventCache,\n): Response {\n // Unknown run ⇒ 404 (a run never started here, or already evicted).\n if (!cache.has(runId)) {\n return new Response(\n JSON.stringify({ error: { code: 'RUN_NOT_FOUND', message: `Unknown run '${runId}'.` } }),\n {\n status: 404,\n headers: { 'content-type': 'application/json' },\n },\n )\n }\n\n const afterSeq = parseLastEventId(request.headers.get('last-event-id'))\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const safeEnqueue = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* controller already closed by an abort race — ignore */\n }\n }\n const close = (): void => {\n if (closed) return\n safeEnqueue(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n\n // Atomic: snapshot replay frames AND subscribe to the live tail in one tick.\n const res = cache.attach(\n runId,\n afterSeq,\n (frame) => {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n // Evicted between has() and attach() (rare TOCTOU) ⇒ just end the stream.\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n }\n if (res.ended) {\n close()\n return\n }\n // Client disconnects ⇒ detach the live listener + close.\n request.signal.addEventListener('abort', () => {\n res.unsubscribe()\n close()\n })\n },\n })\n\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId } })\n}\n","/**\n * M39 (ADR-0048) — the thread follow-up dispatcher.\n *\n * Drives a run over the M37 durable cache HEADLESS — it iterates the SDK chunk\n * generator and `cache.append`s directly, NOT via a `Response` `ReadableStream`\n * (whose backpressure would stall a run with no HTTP reader). Subscribers read\n * from the cache via the thread / reconnect stream.\n *\n * - Post to an IDLE thread ⇒ start a run + pump.\n * - Post to an ACTIVE thread ⇒ FIFO-queue the follow-up.\n * - On terminal ⇒ `registry.endRun` hands back the next queued follow-up, which\n * is dispatched as a continuation on the SAME sessionId (⇒ the SDK continues\n * the conversation via its `ConversationStorageAdapter`).\n *\n * This adds NO agent loop — it reuses the SDK run (`startRun`) + the M37 cache.\n * Single-process (ADR-0048 D2).\n */\n\nimport type { UIMessageChunk } from 'ai'\n\nimport { type RunEventCache, mintRunId } from './run-event-cache.js'\nimport type { ThreadRunRegistry } from './thread-run-registry.js'\n\nexport interface ThreadDispatchDeps {\n readonly registry: ThreadRunRegistry\n readonly cache: RunEventCache\n /** Start a run for a follow-up on `sessionId`; returns the SDK chunk stream. */\n readonly startRun: (sessionId: string, message: string) => AsyncIterable<UIMessageChunk>\n}\n\n/** Result of posting a follow-up: the started `runId` (idle thread) or `queued` (active thread). */\nexport type PostFollowUpResult = { runId: string } | { queued: true }\n\n/**\n * Post a follow-up on a thread. IDLE ⇒ start a run (returns its `runId`); ACTIVE\n * ⇒ FIFO-queue it (returns `{ queued: true }`) — dispatched when the active run ends.\n */\nexport function postThreadFollowUp(\n deps: ThreadDispatchDeps,\n sessionId: string,\n message: string,\n): PostFollowUpResult {\n if (deps.registry.getActive(sessionId) !== null) {\n deps.registry.queue(sessionId, { message })\n return { queued: true }\n }\n return { runId: startAndPump(deps, sessionId, message) }\n}\n\n/** Mint a runId, mark the thread active, and pump the run into the cache headless. */\nfunction startAndPump(deps: ThreadDispatchDeps, sessionId: string, message: string): string {\n const runId = mintRunId()\n // Register the run in the cache SYNCHRONOUSLY (before the async pump appends its\n // first frame) so a subscriber resolving the active runId can attach immediately.\n deps.cache.begin(runId)\n deps.registry.startRun(sessionId, runId)\n pumpIntoCache(deps, sessionId, runId, deps.startRun(sessionId, message))\n return runId\n}\n\n/**\n * Drive `chunks` into the cache under `runId`, then end the run and dispatch the\n * next queued follow-up (if any) as a continuation. Fire-and-forget — the caller\n * does not await the run; subscribers observe it via the cache.\n */\nfunction pumpIntoCache(\n deps: ThreadDispatchDeps,\n sessionId: string,\n runId: string,\n chunks: AsyncIterable<UIMessageChunk>,\n): void {\n void (async () => {\n try {\n for await (const chunk of chunks) {\n deps.cache.append(runId, JSON.stringify(chunk))\n }\n } catch {\n // The SDK translator owns error semantics (surfaces failures as chunks);\n // the transport guarantees only a terminated, cache-ended run.\n } finally {\n deps.cache.end(runId)\n const next = deps.registry.endRun(sessionId, runId)\n if (next !== undefined) startAndPump(deps, sessionId, next.message)\n }\n })()\n}\n","/**\n * M39 (ADR-0048) — the in-process thread→run registry.\n *\n * A thread is the existing `sessionId` (the SDK conversation key). This registry\n * tracks, per thread, the single ACTIVE run, a FIFO queue of follow-ups to\n * dispatch as continuations, and one-shot \"next run\" waiters (so a client can\n * subscribe to a thread before posting a message and attach when the run starts).\n *\n * Pure state only — it never starts a run or touches the transport. The route\n * layer owns dispatch: on `endRun` it receives the next queued follow-up (if any)\n * and starts the continuation over the M37 durable transport.\n *\n * Single-process contract (ADR-0048 D2): a multi-instance deploy needs a shared\n * registry + leasing — that is infra (TheoCloud), explicitly out of M39. The\n * interface is injectable so a durable impl slots in later without touching the\n * routes. We do NOT build a distributed store now (YAGNI).\n */\n\n/** A follow-up message queued on an active thread, dispatched as a continuation. */\nexport interface FollowUp {\n readonly message: string\n}\n\nexport interface ThreadRunRegistry {\n /** The active runId for a thread, or `null` when the thread is idle. */\n getActive(sessionId: string): string | null\n /** Mark a run started for a thread (sets it active; fires + clears one-shot waiters). */\n startRun(sessionId: string, runId: string): void\n /**\n * Mark `runId` ended for a thread. A no-op unless `runId` is the current active\n * run (a stale terminal never clears a newer run). Clears the active run and\n * returns the next FIFO follow-up to dispatch as a continuation, or `undefined`.\n */\n endRun(sessionId: string, runId: string): FollowUp | undefined\n /** FIFO-enqueue a follow-up on a thread (dispatched when the active run ends). */\n queue(sessionId: string, followUp: FollowUp): void\n /**\n * Register a ONE-SHOT waiter fired with the runId of the NEXT run started on\n * this thread. Returns an unsubscribe fn. Used by subscribe-by-thread on an\n * idle thread (attach when the next run starts).\n */\n onNextRun(sessionId: string, cb: (runId: string) => void): () => void\n}\n\ninterface ThreadState {\n activeRunId: string | null\n readonly queue: FollowUp[]\n readonly waiters: Set<(runId: string) => void>\n}\n\nexport function createInProcessThreadRunRegistry(): ThreadRunRegistry {\n const threads = new Map<string, ThreadState>()\n const ensure = (sessionId: string): ThreadState => {\n let s = threads.get(sessionId)\n if (s === undefined) {\n s = { activeRunId: null, queue: [], waiters: new Set() }\n threads.set(sessionId, s)\n }\n return s\n }\n\n return {\n getActive(sessionId) {\n return threads.get(sessionId)?.activeRunId ?? null\n },\n startRun(sessionId, runId) {\n const s = ensure(sessionId)\n s.activeRunId = runId\n // Fire one-shot waiters, then clear them (single-threaded → no re-entrancy race).\n const waiters = [...s.waiters]\n s.waiters.clear()\n for (const cb of waiters) cb(runId)\n },\n endRun(sessionId, runId) {\n const s = threads.get(sessionId)\n if (s?.activeRunId !== runId) return undefined\n s.activeRunId = null\n return s.queue.shift()\n },\n queue(sessionId, followUp) {\n ensure(sessionId).queue.push(followUp)\n },\n onNextRun(sessionId, cb) {\n const s = ensure(sessionId)\n s.waiters.add(cb)\n return () => {\n s.waiters.delete(cb)\n }\n },\n }\n}\n\nlet serverRegistry: ThreadRunRegistry | undefined\n\n/** Process-wide singleton (mirrors `getRunEventCache` / `getApprovalRegistry`). */\nexport function getThreadRunRegistry(): ThreadRunRegistry {\n serverRegistry ??= createInProcessThreadRunRegistry()\n return serverRegistry\n}\n","/**\n * M39 (ADR-0048) — the thread signal routes over the M37 durable transport:\n *\n * - `POST /api/agents/<name>/threads/<sessionId>/message` — a follow-up. ACTIVE\n * run ⇒ FIFO-queue (dispatched as a continuation when it ends); IDLE ⇒ start a\n * run. Returns `202` (the run streams headless into the cache; observe it via\n * the thread stream). Spends LLM tokens ⇒ CSRF-gated (parity with mount-agent).\n * - `GET /api/agents/<name>/threads/<sessionId>/stream` — subscribe. ACTIVE ⇒\n * attach to the durable stream (reuse the M37 reconnect handler); IDLE ⇒ wait\n * (bounded) for the next run on the thread, then attach (subscribe-then-post).\n *\n * These DRIVE the SDK run (via `makeThreadStartRun`) + the M37 cache — no new loop.\n */\n\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { makeThreadStartRun } from './build-agent-streamer.js'\nimport {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport { handleAgentRunReconnect } from './handle-agent-run-reconnect.js'\nimport { parseAgentRequestBody } from './mount-agent.js'\nimport { getRunEventCache, type RunEventCache } from './run-event-cache.js'\nimport { postThreadFollowUp } from './thread-dispatcher.js'\nimport { getThreadRunRegistry, type ThreadRunRegistry } from './thread-run-registry.js'\n\nconst THREAD_MESSAGE_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/message$/\nconst THREAD_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/stream$/\n\n/** How long a subscribe-to-idle-thread waits for the next run before closing. */\nconst DEFAULT_IDLE_WAIT_MS = 30_000\n\nfunction matchThread(re: RegExp, urlPath: string): { name: string; sessionId: string } | null {\n const m = re.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), sessionId: decodeURIComponent(m[2]) } : null\n}\n\nexport const isThreadMessagePath = (urlPath: string) => matchThread(THREAD_MESSAGE_PATH, urlPath)\nexport const isThreadStreamPath = (urlPath: string) => matchThread(THREAD_STREAM_PATH, urlPath)\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Inputs for {@link handleThreadMessage} (bundled to stay within the arity budget). */\nexport interface ThreadMessageArgs {\n readonly mod: unknown\n readonly apiKey: string\n readonly sessionId: string\n readonly request: Request\n readonly source: string\n readonly csrfMode?: CsrfMode\n}\n\n/** POST a follow-up on a thread. Returns `202` with `{ runId }` (started) or `{ queued: true }`. */\nexport async function handleThreadMessage(args: ThreadMessageArgs): Promise<Response> {\n const { mod, apiKey, sessionId, request, source, csrfMode = 'strict' } = args\n // A follow-up drives the agent (spends LLM tokens) — reject a cross-origin POST.\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → 400 below */\n }\n const input = parseAgentRequestBody(body)\n if (input === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request must contain a non-empty message.')\n }\n const result = postThreadFollowUp(\n {\n registry: getThreadRunRegistry(),\n cache: getRunEventCache(),\n startRun: makeThreadStartRun(mod, apiKey, source),\n },\n sessionId,\n input.message,\n )\n const headers: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' }\n if ('runId' in result) headers[RUN_ID_HEADER] = result.runId\n return new Response(JSON.stringify(result), { status: 202, headers })\n}\n\n/** GET the thread's durable stream. Active ⇒ attach now; idle ⇒ wait (bounded) for the next run. */\nexport function handleThreadStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry = getThreadRunRegistry(),\n cache: RunEventCache = getRunEventCache(),\n idleWaitMs = DEFAULT_IDLE_WAIT_MS,\n): Response {\n const active = registry.getActive(sessionId)\n if (active !== null && cache.has(active)) {\n // Reuse the M37 reconnect handler — replay + live tail on the active run.\n return handleAgentRunReconnect(active, request, cache)\n }\n return waitThenAttachStream(sessionId, request, registry, cache, idleWaitMs)\n}\n\n/** Subscribe to an idle thread: wait (bounded) for the NEXT run to start, then attach + tail. */\nfunction waitThenAttachStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry,\n cache: RunEventCache,\n idleWaitMs: number,\n): Response {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const send = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* closed by an abort race */\n }\n }\n let detachAttach: (() => void) | undefined\n const close = (): void => {\n if (closed) return\n send(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n const offNext = registry.onNextRun(sessionId, (runId) => {\n const res = cache.attach(\n runId,\n -1,\n (frame) => {\n send(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) send(formatSseFrame(frame.seq, frame.data))\n if (res.ended) {\n close()\n return\n }\n detachAttach = res.unsubscribe\n })\n // HIGH-1 — the waiter teardown MUST run on BOTH the idle-wait timeout AND the\n // client abort, else the (one-shot) `onNextRun` waiter leaks in the registry\n // when a timed-out subscriber's session never receives another run.\n const teardownWaiter = (): void => {\n offNext()\n detachAttach?.()\n }\n const timer = setTimeout(() => {\n teardownWaiter()\n close()\n }, idleWaitMs)\n timer.unref()\n request.signal.addEventListener('abort', () => {\n teardownWaiter()\n clearTimeout(timer)\n close()\n })\n },\n })\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS } })\n}\n","/**\n * M15/M16 follow-up — shared dispatcher for the agent AUXILIARY routes that BOTH dev (vite\n * middleware) and prod (`theokit start` handler) must serve identically. Before this, these routes\n * were wired only into the dev middleware, so a built/deployed app served none of them (agent cards,\n * MCP, pending-approvals listing all 404'd in production).\n *\n * Single source of truth (DRY): one Web-Request→Response dispatcher, two callers. It handles the\n * routes that derive purely from the agent module + shared registry:\n * - **M15** `GET /.well-known/<name>/agent-card.json` → {@link handleAgentCard}\n * - **M14** `GET /api/agents/<name>/approvals` → {@link handleListApprovals}\n * - **M16** `POST /api/agents/<name>/mcp` → {@link handleMcpJsonRpc}\n *\n * Channels (M27) are NOT here: a channel webhook needs app-supplied `validators` + `onMessage`, so\n * the app wires `handleChannelWebhook` in its own route (it cannot be auto-derived from the module).\n * The HITL approve route stays in each caller (it carries caller-specific rate-limiting/CSRF plumbing).\n */\nimport type { AgentNode } from '../scan/agent-scan.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { isAgentCardPath, handleAgentCard } from './agent-card-handler.js'\nimport { getApprovalRegistry } from './approval-registry.js'\nimport { handleAgentRunReconnect, isAgentRunStreamPath } from './handle-agent-run-reconnect.js'\nimport {\n handleThreadMessage,\n handleThreadStream,\n isThreadMessagePath,\n isThreadStreamPath,\n} from './handle-thread-routes.js'\nimport { isListApprovalsPath, handleListApprovals } from './list-approvals-handler.js'\nimport { extractAppResources } from './mcp-app-resources.js'\nimport { isMcpPath, handleMcpJsonRpc } from './mcp-handler.js'\nimport { getRunEventCache } from './run-event-cache.js'\n\n/** JSON error envelope (mirrors mount-agent.ts:37 — the parity source for the MCP CSRF gate). */\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Dependencies the aux dispatcher needs from its caller (dev or prod). */\nexport interface AuxRouteDeps {\n /** Discovered agents (from `scanAgents`). */\n agents: readonly AgentNode[]\n /** Load an agent module from its file path (dev: vite loader; prod: dynamic import). */\n loadModule: (filePath: string) => Promise<unknown>\n /** Absolute base URL (`http(s)://host`) for the agent-card endpoint URLs. */\n baseUrl: string\n /**\n * M34 (#97) — CSRF enforcement mode for the MCP route. `POST /api/agents/<name>/mcp` drives the\n * agent (spends LLM tokens), so a cross-origin POST MUST be rejected in `'strict'` — parity with\n * the agent-run route (`mount-agent.ts:83-91`). Defaults to `'strict'` (safe-by-default); a caller\n * that already gated upstream may pass `'off'`.\n */\n csrfMode?: CsrfMode\n /**\n * M39 — lazily resolve the provider apiKey. Required only for the thread\n * follow-up route (which drives the agent); resolved on demand so non-agent\n * aux routes (card, approvals, stream) never need a provider key.\n */\n resolveApiKey?: () => string\n}\n\n/**\n * Serve an agent auxiliary route. Returns a `Response` when `urlPath` matches an aux route (card /\n * list-approvals / mcp) and the method + agent resolve; returns `null` to fall through (not an aux\n * route, wrong method, or unknown agent — the caller then owns the 404/next).\n */\nexport async function serveAgentAuxRoute(\n request: Request,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const method = request.method.toUpperCase()\n\n // M15 — A2A agent card at `/.well-known/<name>/agent-card.json` (GET).\n const cardName = isAgentCardPath(urlPath)\n if (cardName !== null) {\n if (method !== 'GET') return null\n const agent = deps.agents.find((a) => a.name === cardName)\n if (!agent) return null\n const mod = await deps.loadModule(agent.filePath)\n return handleAgentCard(mod, agent.name, agent.agentPath, deps.baseUrl)\n }\n\n // M14 — GET /api/agents/<name>/approvals (pending HITL approvals).\n if (isListApprovalsPath(urlPath)) {\n if (method !== 'GET') return null\n return handleListApprovals(getApprovalRegistry())\n }\n\n // M37 — GET /api/agents/<name>/runs/<runId>/stream (durable reconnect / observe).\n // INTENTIONALLY open (no CSRF, no auth gate): a GET is not CSRF-vulnerable, the\n // run-start POST is already gated, and the `runId` is a 122-bit UUID (unguessable).\n // Observe-by-runId is a FEATURE (ADR-0046 D5) — a second client resumes a run a\n // first started. Do NOT add a custom-header CSRF check here: browsers send NO\n // custom headers with `EventSource`, so it would break native SSE reconnect.\n const runStream = isAgentRunStreamPath(urlPath)\n if (runStream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === runStream.name)) return null\n return handleAgentRunReconnect(runStream.runId, request, getRunEventCache())\n }\n\n // M39 — thread signal routes (follow-up message + subscribe-by-thread). Extracted\n // to keep this dispatcher within the cognitive-complexity budget (G6).\n const threadResponse = await serveThreadRoute(request, method, urlPath, deps)\n if (threadResponse !== null) return threadResponse\n\n // M16 — POST /api/agents/<name>/mcp (JSON-RPC MCP server). Extracted to keep this dispatcher\n // within the cognitive-complexity budget (G6).\n const mcpName = isMcpPath(urlPath)\n if (mcpName !== null) {\n return serveMcpRoute(request, method, mcpName, deps)\n }\n\n return null\n}\n\n/**\n * M39 — serve the thread routes:\n * - `POST .../threads/<sessionId>/message` (follow-up) — loads the module, drives\n * the run headless via the thread dispatcher. Needs `resolveApiKey` (drives the\n * agent) → 501 when absent (rather than a silent 404).\n * - `GET .../threads/<sessionId>/stream` (subscribe) — attach to the active/next\n * run's durable stream. INTENTIONALLY open (GET, no custom headers — like the\n * M37 reconnect route).\n *\n * SECURITY (thread stream): unlike the M37 reconnect route — keyed on an\n * `mintRunId()` UUID (122-bit unguessable) — the thread stream is keyed on the\n * caller-supplied `sessionId`. The open GET is safe ONLY if the `sessionId` is\n * unguessable (e.g. a client-minted UUID). An app that uses a PREDICTABLE\n * sessionId (user id, email, sequential id) MUST add its own auth gate before\n * this endpoint, or any party who can guess the sessionId can read the thread's\n * live conversation stream. Documented in `docs/architecture/multi-surface-architecture.md`.\n *\n * Returns `null` to fall through (not a thread route, wrong method, unknown agent).\n */\nasync function serveThreadRoute(\n request: Request,\n method: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const stream = isThreadStreamPath(urlPath)\n if (stream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === stream.name)) return null\n return handleThreadStream(stream.sessionId, request)\n }\n\n const msg = isThreadMessagePath(urlPath)\n if (msg !== null) {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === msg.name)\n if (!agent) return null\n if (deps.resolveApiKey === undefined) {\n // MEDIUM-1 — the path matched but the caller wired no provider-key resolver.\n // Fail loudly (501) instead of a silent 404 that reads as \"route not found\".\n return jsonError(\n 501,\n 'NOT_CONFIGURED',\n 'Thread follow-up requires a provider API key (resolveApiKey was not provided to serveAgentAuxRoute).',\n )\n }\n const mod = await deps.loadModule(agent.filePath)\n return handleThreadMessage({\n mod,\n apiKey: deps.resolveApiKey(),\n sessionId: msg.sessionId,\n request,\n source: `agent \"${msg.name}\"`,\n csrfMode: deps.csrfMode ?? 'strict',\n })\n }\n return null\n}\n\n/**\n * Serve the MCP route with the M34 gates: default-DENY opt-in → CSRF → dispatch. Returns `null` to\n * fall through (wrong method / unknown or non-opted-in agent), a 403 on CSRF failure, else the\n * JSON-RPC response.\n */\nasync function serveMcpRoute(\n request: Request,\n method: string,\n mcpName: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === mcpName)\n if (!agent) return null\n\n const mod = await deps.loadModule(agent.filePath)\n\n // M34 — DEFAULT-DENY: an agent is NOT exposed on MCP unless it explicitly opts in with a named\n // `export const mcp = true` (blueprint D5 — default-EXPOSE is the footgun magnified by the\n // multi-surface thesis). Absent the opt-in, fall through to 404 (the agent is web-only). This is a\n // breaking change from the M16 auto-mount (documented in the CHANGELOG § Security).\n if (!isMcpExposed(mod)) return null\n\n // M34 (#97) — enforce CSRF BEFORE any work. The MCP route drives the agent (real LLM tokens), so a\n // cross-origin POST must be rejected — parity with the agent-run route (`mount-agent.ts:83-91`).\n const csrfMode = deps.csrfMode ?? 'strict'\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* malformed/empty JSON → handleMcpJsonRpc returns a -32600 envelope */\n }\n // M30 — pass the agent's declared `ui://` App resources (named `appResources` export) so the MCP\n // server advertises + serves them via resources/list + resources/read.\n return handleMcpJsonRpc(mod, agent.name, body, extractAppResources(mod))\n}\n\n/**\n * M34 — DEFAULT-DENY opt-in check: is this agent module exposed on the MCP surface? An agent opts in\n * with a named `export const mcp = true` (mirroring the `appResources` named-export convention).\n * Anything else (absent / falsy) → NOT exposed. Read at the emit layer (blueprint D5).\n */\nfunction isMcpExposed(mod: unknown): boolean {\n return (mod as { mcp?: unknown } | null | undefined)?.mcp === true\n}\n","/**\n * 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 * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase G slice 5/N (closes the executor bridge surface).\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { Readable } from 'node:stream'\n\nimport { executeWebRequest, type ExecuteWebRequestOptions } from '../web-handler.js'\n\n/**\n * Build a Web `Request` from a Node `IncomingMessage`. The Web Request\n * spec requires an absolute URL; we synthesize one from\n * `req.headers.host` (or fall back to `localhost` for test doubles).\n *\n * For methods with a body (POST/PUT/PATCH/DELETE), the Node Readable\n * stream is wrapped as a Web ReadableStream via `Readable.toWeb()` so\n * downstream consumers can call `request.json()` / `request.formData()`\n * / `request.text()` natively.\n *\n * EC-1: Node sometimes provides headers as `string | string[]`. Web\n * `Headers` collapses to single-comma-joined strings — we do the join\n * manually for repeated headers because `Headers.append` would create\n * multi-value entries which behave differently on `.get()`.\n */\nexport function incomingMessageToWebRequest(req: IncomingMessage): Request {\n const host = pickHeaderString(req.headers.host) ?? 'localhost'\n const url = `http://${host}${req.url ?? '/'}`\n\n const headers = new Headers()\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue\n if (Array.isArray(value)) {\n headers.set(key, value.join(', '))\n } else {\n headers.set(key, value)\n }\n }\n\n const method = (req.method ?? 'GET').toUpperCase()\n const hasBody = method !== 'GET' && method !== 'HEAD'\n\n if (!hasBody) {\n return new Request(url, { method, headers })\n }\n\n // Drain Node's Readable into a Web ReadableStream. `Readable.toWeb` is\n // available in Node 18+ (theokit's engines.node floor is 22+, so safe).\n const webStream = Readable.toWeb(req) as ReadableStream\n return new Request(url, {\n method,\n headers,\n body: webStream,\n // EC-2: Node 18+ requires `duplex: 'half'` when body is a stream.\n // The `RequestInit` type omits it (Web spec gap); cast accordingly.\n ...({ duplex: 'half' } as { duplex: 'half' }),\n })\n}\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\n/** Pick the first usable string from Node's `string | string[] | undefined` headers. */\nfunction pickHeaderString(value: string | string[] | undefined): string | undefined {\n if (typeof value === 'string') return value\n if (Array.isArray(value)) {\n for (const v of value) if (typeof v === 'string' && v.length > 0) return v\n }\n return undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,OAAO,eAAe;AAef,IAAM,uBAAwC;AAAA,EACnD,MAAM;AAAA,EACN,WAAW,CAAC,MAAM,KAAK,UAAU,UAAU,UAAU,CAAC,CAAC;AAAA,EACvD,aAAa,CAAC,QAAQ;AACpB,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,WAAO,UAAU,YAAY,MAAM;AAAA,EACrC;AACF;AAEO,IAAM,kBAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,WAAW,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAClC,aAAa,CAAC,QAAQ,KAAK,MAAM,GAAG;AACtC;AAEA,IAAM,YAA6C;AAAA,EACjD,WAAW;AAAA,EACX,MAAM;AACR;AAEO,SAAS,mBACd,UACiB;AACjB,MAAI,OAAO,aAAa,UAAU;AAMhC,UAAM,QAAQ,UAAU,QAAQ;AAIhC,QAAK,UAA0C,QAAW;AACxD,YAAM,IAAI;AAAA,QACR,wBAAwB,Q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AI,MAAM,OAAO,KAAK;AAC1C,UAAI,KAAM;AAEV,UAAI,MAAM,KAAK;AAAA,IACjB;AACA,QAAI,IAAI;AAAA,EACV,UAAE;AACA,WAAO,YAAY;AAAA,EACrB;AACF;AA6BA,SAAS,iBAAiB,OAA0D;AAClF,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAW,KAAK,MAAO,KAAI,OAAO,MAAM,YAAY,EAAE,SAAS,EAAG,QAAO;AAAA,EAC3E;AACA,SAAO;AACT;","names":["compileAgentModule","resolveEnabledSkills","streamAgentUIMessages","compileAgentModule","compileAgentModule","jsonError","compileAgentModule","resolveEnabledSkills","streamAgentUIMessages","jsonError","jsonError"]}
1
+ {"version":3,"sources":["../src/server/transformer.ts","../src/server/agent/agent-card-handler.ts","../src/server/agent/approve-agent.ts","../src/server/agent/list-approvals-handler.ts","../src/server/agent/mount-agent.ts","../src/server/agent/build-agent-streamer.ts","../src/server/agent/durable-ui-message-stream-response.ts","../src/server/agent/run-event-cache.ts","../src/server/agent/handle-agent-run-reconnect.ts","../src/server/agent/thread-dispatcher.ts","../src/server/agent/thread-run-registry.ts","../src/server/agent/handle-thread-routes.ts","../src/server/agent/serve-aux-routes.ts","../src/server/http/node-web-adapter.ts"],"sourcesContent":["import superjson from 'superjson'\n\n/**\n * T5.2 — pluggable response/request transformer.\n *\n * `superjson` is the default, preserving Date/Map/Set/BigInt/etc.\n * `json` is the lightweight option (plain JSON.stringify/parse).\n * Users can supply a custom object implementing this contract.\n */\nexport interface TheoTransformer {\n name: string\n serialize: (value: unknown) => string\n deserialize: (raw: string) => unknown\n}\n\nexport const superjsonTransformer: TheoTransformer = {\n name: 'superjson',\n serialize: (v) => JSON.stringify(superjson.serialize(v)),\n deserialize: (raw) => {\n const parsed = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(parsed)\n },\n}\n\nexport const jsonTransformer: TheoTransformer = {\n name: 'json',\n serialize: (v) => JSON.stringify(v),\n deserialize: (raw) => JSON.parse(raw) as unknown,\n}\n\nconst BUILT_INS: Record<string, TheoTransformer> = {\n superjson: superjsonTransformer,\n json: jsonTransformer,\n}\n\nexport function resolveTransformer(\n selector: 'json' | 'superjson' | TheoTransformer,\n): TheoTransformer {\n if (typeof selector === 'string') {\n // selector is 'json' | 'superjson' literal — both keys exist in\n // BUILT_INS by construction. Type system guarantees a hit; we keep\n // a defensive fallback that the compiler cannot see is unreachable\n // at runtime, just in case someone adds a new literal to the union\n // but forgets to register the built-in.\n const built = BUILT_INS[selector]\n // Defensive: the public union ensures `built` is defined, but if a\n // future contributor extends the union without registering the impl,\n // the cast keeps the failure mode loud.\n if ((built as TheoTransformer | undefined) === undefined) {\n throw new Error(\n `Unknown transformer \"${selector}\". Built-in options: ${Object.keys(BUILT_INS).join(', ')}.`,\n )\n }\n return built\n }\n if (\n typeof selector !== 'object' ||\n typeof selector.serialize !== 'function' ||\n typeof selector.deserialize !== 'function'\n ) {\n throw new Error(\n `Custom transformer must have serialize and deserialize functions. Got: ${JSON.stringify(selector)}`,\n )\n }\n return selector\n}\n","/**\n * M15 (theokit-ai-first) — serve the A2A agent card at `/.well-known/<name>/agent-card.json`.\n *\n * `buildAgentCard` (@theokit/agents) is the pure generator; this handler compiles a loaded agent\n * module to its tools + streaming capability, builds the card, and returns it as a Web-Standard\n * JSON `Response` (G8). The dev middleware + prod handler branch to this before the agent POST route.\n */\nimport {\n type AgentManifestEntry,\n buildAgentCard,\n compileAgentModule,\n} from '@theokit/agents'\n\nconst WELL_KNOWN = /^\\/\\.well-known\\/([^/]+)\\/agent-card\\.json$/\n\n/** Return the agent name when `urlPath` is a well-known card path, else `null`. */\nexport function isAgentCardPath(urlPath: string): string | null {\n const match = WELL_KNOWN.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Build a minimal manifest entry (the subset `buildAgentCard` reads) from a compiled agent. */\nfunction toManifestEntry(name: string, route: string, mod: unknown): AgentManifestEntry {\n const compiled = compileAgentModule(mod, `agent card for \"${name}\"`)\n return {\n name,\n route,\n stream: compiled.stream,\n mainLoop: { method: '', strategy: '' },\n guards: [],\n interceptors: [],\n tools: compiled.tools.map((t) => ({\n name: t.name,\n description: t.description,\n approval: false,\n trace: false,\n audit: false,\n })),\n subAgents: [],\n }\n}\n\n/**\n * Serve the A2A card for a loaded agent module. Returns 200 with the card JSON, or 500 with an\n * error body if the module is not a valid agent (fail-clear, not a silent empty card).\n */\nexport function handleAgentCard(mod: unknown, name: string, route: string, baseUrl: string): Response {\n try {\n const card = buildAgentCard(toManifestEntry(name, route, mod), { baseUrl })\n return new Response(JSON.stringify(card), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n } catch (err) {\n return new Response(\n JSON.stringify({ error: { code: 'AGENT_CARD_FAILED', message: err instanceof Error ? err.message : 'card build failed' } }),\n { status: 500, headers: { 'content-type': 'application/json; charset=utf-8' } },\n )\n }\n}\n","/**\n * M4 (theokit-ai-first) — the HITL approve endpoint: `POST /api/agents/<name>/approve/<approvalId>`.\n *\n * The counterpart to `mountAgent`'s HITL pause. While a gated tool holds the SDK run paused (the\n * awaited `pre_tool_call` hook), the client POSTs here with `{ approved }`; this resolves the\n * pending approval in the shared registry, which un-pauses the run (allow) or vetoes the tool (deny).\n *\n * Web-Standard `Request` → `Response`, one wiring point shared by dev (vite middleware) and prod\n * (built server) so the two never drift (EC-4 parity with `mountAgent`). The registry is INJECTED —\n * dev/prod pass the process singleton (`getApprovalRegistry`), tests pass a fresh instance.\n */\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport type { ApprovalDecision, ApprovalRegistry } from './approval-registry.js'\n\n/** The path segment separating the agent name from the approval id. */\nconst APPROVE_SEGMENT = '/approve/'\n\n/**\n * Extract the `<approvalId>` from a `/api/agents/<name>/approve/<approvalId>` path.\n * Returns `null` when the path has no `/approve/` segment or an empty / nested id.\n */\nexport function parseApprovalId(urlPath: string): string | null {\n const at = urlPath.indexOf(APPROVE_SEGMENT)\n if (at === -1) return null\n const id = urlPath.slice(at + APPROVE_SEGMENT.length)\n return id.length > 0 && !id.includes('/') ? id : null\n}\n\n/** True when `urlPath` targets a HITL approve endpoint (used by dev/prod routing to branch early). */\nexport function isApprovalPath(urlPath: string): boolean {\n return urlPath.includes(APPROVE_SEGMENT)\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\n/**\n * M20 — cap on the serialized custom payload (16 KiB). A payload is a small structured note\n * (edited args, a reviewer comment), not a data channel — an oversized one is rejected fail-fast\n * rather than silently truncated (Rule 8).\n */\nconst MAX_PAYLOAD_BYTES = 16 * 1024\n\n/**\n * Extract an {@link ApprovalDecision} from an untrusted body; `null` when the shape is wrong.\n *\n * M20 — accepts an optional `reason` (string) and `payload` (object, capped at\n * {@link MAX_PAYLOAD_BYTES}). Backward-compatible: `{ approved }` and `{ approved, reason }` parse\n * unchanged. A non-object or oversized `payload` is rejected (returns `null` → the route 400s).\n *\n * @public\n */\nexport function parseApprovalBody(body: unknown): ApprovalDecision | null {\n if (typeof body !== 'object' || body === null) return null\n const b = body as Record<string, unknown>\n if (typeof b.approved !== 'boolean') return null\n const decision: ApprovalDecision = { approved: b.approved }\n if (b.reason !== undefined) {\n if (typeof b.reason !== 'string') return null\n decision.reason = b.reason\n }\n if (b.payload !== undefined) {\n if (typeof b.payload !== 'object' || b.payload === null || Array.isArray(b.payload)) return null\n if (JSON.stringify(b.payload).length > MAX_PAYLOAD_BYTES) return null\n decision.payload = b.payload\n }\n return decision\n}\n\n/**\n * Resolve a pending HITL approval. CSRF-guarded like `mountAgent` (the custom `X-Theo-Action`\n * header + Origin match) — a cross-origin POST must not approve a paused tool. Returns:\n * 403 CSRF_FAILED — strict CSRF check failed\n * 400 BAD_REQUEST — no `/approve/<id>` in the path, or body lacks a boolean `approved`\n * 404 NOT_PENDING — the id is unknown or already settled (idempotent double-submit)\n * 200 { resolved:true } — the approval was settled by this call\n */\nexport async function handleAgentApproval(\n request: Request,\n urlPath: string,\n registry: ApprovalRegistry,\n csrfMode: CsrfMode = 'strict',\n): Promise<Response> {\n if (csrfMode !== 'off') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid && csrfMode === 'strict') {\n return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n }\n\n const approvalId = parseApprovalId(urlPath)\n if (approvalId === null) {\n return jsonError(400, 'BAD_REQUEST', 'Approval path must be /api/agents/<name>/approve/<id>.')\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\n }\n const parsed = parseApprovalBody(body)\n if (parsed === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request body must contain a boolean `approved`.')\n }\n\n const resolved = registry.resolve(approvalId, parsed)\n if (!resolved) {\n return jsonError(404, 'NOT_PENDING', `No pending approval for id '${approvalId}'.`)\n }\n return new Response(JSON.stringify({ resolved: true }), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n}\n","/**\n * M14 (theokit-ai-first) — GET /api/agents/<name>/approvals: list pending HITL approvals.\n *\n * Serves `ApprovalRegistry.list()` as JSON. Single-process contract (ADR 0038) — the list is\n * process-wide; the `<name>` segment is accepted for a future per-agent/durable store but the\n * in-process registry lists all pending approvals. Web Standards Response (G8).\n */\nimport type { ApprovalRegistry } from './approval-registry.js'\n\nconst LIST_PATH = /^\\/api\\/agents\\/([^/]+)\\/approvals$/\n\n/** Return the agent name when `urlPath` is the approvals-listing path, else `null`. */\nexport function isListApprovalsPath(urlPath: string): string | null {\n const match = LIST_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Serve the currently-pending approvals as `{ approvals: [...] }` JSON. */\nexport function handleListApprovals(registry: ApprovalRegistry): Response {\n return new Response(JSON.stringify({ approvals: registry.list() }), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\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 { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { buildAgentHitl } from './build-agent-streamer.js'\nimport { durableUiMessageStreamResponse } from './durable-ui-message-stream-response.js'\nimport { getRunEventCache, mintRunId } from './run-event-cache.js'\n\n/** The message + session extracted from a chat request, or `null` when the body is invalid. */\nexport interface 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/**\n * Mount a loaded agent module as a `Response`. `apiKey` is resolved by the caller\n * (`resolveProvider`). `source` labels a fail-fast `AgentDefinitionError` (the file path).\n */\nexport async function mountAgent(\n mod: unknown,\n request: Request,\n apiKey: string,\n source = 'agent module',\n csrfMode: CsrfMode = 'strict',\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 const compiled = compileAgentModule(mod, source)\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 let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → handled below as a 400 */\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 // 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)\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 return durableUiMessageStreamResponse(\n streamAgentUIMessages(compiled, apiKey, { ...input, hitl, signal: request.signal }),\n { runId, cache: getRunEventCache() },\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 { UIMessageChunk } from 'ai'\n\nimport { getApprovalRegistry } from './approval-registry.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) {\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 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 */\nexport function makeThreadStartRun(\n mod: unknown,\n apiKey: string,\n source: string,\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 const hitl = buildAgentHitl(compiled)\n yield* streamAgentUIMessages(compiled, apiKey, { message, sessionId, hitl })\n })()\n}\n","import type { UIMessageChunk } from 'ai'\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/** The UIMessageStream SSE base headers — shared by the encoder + reconnect handler (DRY). */\nexport const SSE_BASE_HEADERS = {\n 'content-type': 'text/event-stream',\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\nexport interface 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\nexport interface 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 {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport type { RunEventCache } from './run-event-cache.js'\n\n/**\n * M37 (ADR-0046 D5) — the reconnect / observe endpoint handler for\n * `GET /api/agents/<name>/runs/<runId>/stream`.\n *\n * Replays the frames the client missed (`seq > Last-Event-ID`, SSE-native), then\n * — if the run is still live — follows the live tail; a SECOND client can\n * observe a run a first started. Run already ended ⇒ replay + `[DONE]`. Unknown\n * `runId` ⇒ 404. The request `AbortSignal` unsubscribes on disconnect.\n */\n\nconst RUN_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/runs\\/([^/]+)\\/stream$/\n\n/**\n * Match `GET /api/agents/<name>/runs/<runId>/stream`; returns the decoded\n * `{ name, runId }` or `null` to fall through (mirrors `isMcpPath` etc.).\n */\nexport function isAgentRunStreamPath(urlPath: string): { name: string; runId: string } | null {\n const m = RUN_STREAM_PATH.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), runId: decodeURIComponent(m[2]) } : null\n}\n\n/** Parse `Last-Event-ID` (a frame `seq`) to a number; absent/invalid ⇒ -1 (replay from the start). */\nfunction parseLastEventId(raw: string | null): number {\n if (raw === null) return -1\n const n = Number.parseInt(raw, 10)\n return Number.isInteger(n) && n >= 0 ? n : -1\n}\n\nexport function handleAgentRunReconnect(\n runId: string,\n request: Request,\n cache: RunEventCache,\n): Response {\n // Unknown run ⇒ 404 (a run never started here, or already evicted).\n if (!cache.has(runId)) {\n return new Response(\n JSON.stringify({ error: { code: 'RUN_NOT_FOUND', message: `Unknown run '${runId}'.` } }),\n {\n status: 404,\n headers: { 'content-type': 'application/json' },\n },\n )\n }\n\n const afterSeq = parseLastEventId(request.headers.get('last-event-id'))\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const safeEnqueue = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* controller already closed by an abort race — ignore */\n }\n }\n const close = (): void => {\n if (closed) return\n safeEnqueue(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n\n // Atomic: snapshot replay frames AND subscribe to the live tail in one tick.\n const res = cache.attach(\n runId,\n afterSeq,\n (frame) => {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n // Evicted between has() and attach() (rare TOCTOU) ⇒ just end the stream.\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) {\n safeEnqueue(formatSseFrame(frame.seq, frame.data))\n }\n if (res.ended) {\n close()\n return\n }\n // Client disconnects ⇒ detach the live listener + close.\n request.signal.addEventListener('abort', () => {\n res.unsubscribe()\n close()\n })\n },\n })\n\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId } })\n}\n","/**\n * M39 (ADR-0048) — the thread follow-up dispatcher.\n *\n * Drives a run over the M37 durable cache HEADLESS — it iterates the SDK chunk\n * generator and `cache.append`s directly, NOT via a `Response` `ReadableStream`\n * (whose backpressure would stall a run with no HTTP reader). Subscribers read\n * from the cache via the thread / reconnect stream.\n *\n * - Post to an IDLE thread ⇒ start a run + pump.\n * - Post to an ACTIVE thread ⇒ FIFO-queue the follow-up.\n * - On terminal ⇒ `registry.endRun` hands back the next queued follow-up, which\n * is dispatched as a continuation on the SAME sessionId (⇒ the SDK continues\n * the conversation via its `ConversationStorageAdapter`).\n *\n * This adds NO agent loop — it reuses the SDK run (`startRun`) + the M37 cache.\n * Single-process (ADR-0048 D2).\n */\n\nimport type { UIMessageChunk } from 'ai'\n\nimport { type RunEventCache, mintRunId } from './run-event-cache.js'\nimport type { ThreadRunRegistry } from './thread-run-registry.js'\n\nexport interface ThreadDispatchDeps {\n readonly registry: ThreadRunRegistry\n readonly cache: RunEventCache\n /** Start a run for a follow-up on `sessionId`; returns the SDK chunk stream. */\n readonly startRun: (sessionId: string, message: string) => AsyncIterable<UIMessageChunk>\n}\n\n/** Result of posting a follow-up: the started `runId` (idle thread) or `queued` (active thread). */\nexport type PostFollowUpResult = { runId: string } | { queued: true }\n\n/**\n * Post a follow-up on a thread. IDLE ⇒ start a run (returns its `runId`); ACTIVE\n * ⇒ FIFO-queue it (returns `{ queued: true }`) — dispatched when the active run ends.\n */\nexport function postThreadFollowUp(\n deps: ThreadDispatchDeps,\n sessionId: string,\n message: string,\n): PostFollowUpResult {\n if (deps.registry.getActive(sessionId) !== null) {\n deps.registry.queue(sessionId, { message })\n return { queued: true }\n }\n return { runId: startAndPump(deps, sessionId, message) }\n}\n\n/** Mint a runId, mark the thread active, and pump the run into the cache headless. */\nfunction startAndPump(deps: ThreadDispatchDeps, sessionId: string, message: string): string {\n const runId = mintRunId()\n // Register the run in the cache SYNCHRONOUSLY (before the async pump appends its\n // first frame) so a subscriber resolving the active runId can attach immediately.\n deps.cache.begin(runId)\n deps.registry.startRun(sessionId, runId)\n pumpIntoCache(deps, sessionId, runId, deps.startRun(sessionId, message))\n return runId\n}\n\n/**\n * Drive `chunks` into the cache under `runId`, then end the run and dispatch the\n * next queued follow-up (if any) as a continuation. Fire-and-forget — the caller\n * does not await the run; subscribers observe it via the cache.\n */\nfunction pumpIntoCache(\n deps: ThreadDispatchDeps,\n sessionId: string,\n runId: string,\n chunks: AsyncIterable<UIMessageChunk>,\n): void {\n void (async () => {\n try {\n for await (const chunk of chunks) {\n deps.cache.append(runId, JSON.stringify(chunk))\n }\n } catch {\n // The SDK translator owns error semantics (surfaces failures as chunks);\n // the transport guarantees only a terminated, cache-ended run.\n } finally {\n deps.cache.end(runId)\n const next = deps.registry.endRun(sessionId, runId)\n if (next !== undefined) startAndPump(deps, sessionId, next.message)\n }\n })()\n}\n","/**\n * M39 (ADR-0048) — the in-process thread→run registry.\n *\n * A thread is the existing `sessionId` (the SDK conversation key). This registry\n * tracks, per thread, the single ACTIVE run, a FIFO queue of follow-ups to\n * dispatch as continuations, and one-shot \"next run\" waiters (so a client can\n * subscribe to a thread before posting a message and attach when the run starts).\n *\n * Pure state only — it never starts a run or touches the transport. The route\n * layer owns dispatch: on `endRun` it receives the next queued follow-up (if any)\n * and starts the continuation over the M37 durable transport.\n *\n * Single-process contract (ADR-0048 D2): a multi-instance deploy needs a shared\n * registry + leasing — that is infra (TheoCloud), explicitly out of M39. The\n * interface is injectable so a durable impl slots in later without touching the\n * routes. We do NOT build a distributed store now (YAGNI).\n */\n\n/** A follow-up message queued on an active thread, dispatched as a continuation. */\nexport interface FollowUp {\n readonly message: string\n}\n\nexport interface ThreadRunRegistry {\n /** The active runId for a thread, or `null` when the thread is idle. */\n getActive(sessionId: string): string | null\n /** Mark a run started for a thread (sets it active; fires + clears one-shot waiters). */\n startRun(sessionId: string, runId: string): void\n /**\n * Mark `runId` ended for a thread. A no-op unless `runId` is the current active\n * run (a stale terminal never clears a newer run). Clears the active run and\n * returns the next FIFO follow-up to dispatch as a continuation, or `undefined`.\n */\n endRun(sessionId: string, runId: string): FollowUp | undefined\n /** FIFO-enqueue a follow-up on a thread (dispatched when the active run ends). */\n queue(sessionId: string, followUp: FollowUp): void\n /**\n * Register a ONE-SHOT waiter fired with the runId of the NEXT run started on\n * this thread. Returns an unsubscribe fn. Used by subscribe-by-thread on an\n * idle thread (attach when the next run starts).\n */\n onNextRun(sessionId: string, cb: (runId: string) => void): () => void\n}\n\ninterface ThreadState {\n activeRunId: string | null\n readonly queue: FollowUp[]\n readonly waiters: Set<(runId: string) => void>\n}\n\nexport function createInProcessThreadRunRegistry(): ThreadRunRegistry {\n const threads = new Map<string, ThreadState>()\n const ensure = (sessionId: string): ThreadState => {\n let s = threads.get(sessionId)\n if (s === undefined) {\n s = { activeRunId: null, queue: [], waiters: new Set() }\n threads.set(sessionId, s)\n }\n return s\n }\n\n return {\n getActive(sessionId) {\n return threads.get(sessionId)?.activeRunId ?? null\n },\n startRun(sessionId, runId) {\n const s = ensure(sessionId)\n s.activeRunId = runId\n // Fire one-shot waiters, then clear them (single-threaded → no re-entrancy race).\n const waiters = [...s.waiters]\n s.waiters.clear()\n for (const cb of waiters) cb(runId)\n },\n endRun(sessionId, runId) {\n const s = threads.get(sessionId)\n if (s?.activeRunId !== runId) return undefined\n s.activeRunId = null\n return s.queue.shift()\n },\n queue(sessionId, followUp) {\n ensure(sessionId).queue.push(followUp)\n },\n onNextRun(sessionId, cb) {\n const s = ensure(sessionId)\n s.waiters.add(cb)\n return () => {\n s.waiters.delete(cb)\n }\n },\n }\n}\n\nlet serverRegistry: ThreadRunRegistry | undefined\n\n/** Process-wide singleton (mirrors `getRunEventCache` / `getApprovalRegistry`). */\nexport function getThreadRunRegistry(): ThreadRunRegistry {\n serverRegistry ??= createInProcessThreadRunRegistry()\n return serverRegistry\n}\n","/**\n * M39 (ADR-0048) — the thread signal routes over the M37 durable transport:\n *\n * - `POST /api/agents/<name>/threads/<sessionId>/message` — a follow-up. ACTIVE\n * run ⇒ FIFO-queue (dispatched as a continuation when it ends); IDLE ⇒ start a\n * run. Returns `202` (the run streams headless into the cache; observe it via\n * the thread stream). Spends LLM tokens ⇒ CSRF-gated (parity with mount-agent).\n * - `GET /api/agents/<name>/threads/<sessionId>/stream` — subscribe. ACTIVE ⇒\n * attach to the durable stream (reuse the M37 reconnect handler); IDLE ⇒ wait\n * (bounded) for the next run on the thread, then attach (subscribe-then-post).\n *\n * These DRIVE the SDK run (via `makeThreadStartRun`) + the M37 cache — no new loop.\n */\n\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { makeThreadStartRun } from './build-agent-streamer.js'\nimport {\n encodeSse,\n formatSseFrame,\n RUN_ID_HEADER,\n SSE_BASE_HEADERS,\n SSE_DONE_FRAME,\n} from './durable-ui-message-stream-response.js'\nimport { handleAgentRunReconnect } from './handle-agent-run-reconnect.js'\nimport { parseAgentRequestBody } from './mount-agent.js'\nimport { getRunEventCache, type RunEventCache } from './run-event-cache.js'\nimport { postThreadFollowUp } from './thread-dispatcher.js'\nimport { getThreadRunRegistry, type ThreadRunRegistry } from './thread-run-registry.js'\n\nconst THREAD_MESSAGE_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/message$/\nconst THREAD_STREAM_PATH = /^\\/api\\/agents\\/([^/]+)\\/threads\\/([^/]+)\\/stream$/\n\n/** How long a subscribe-to-idle-thread waits for the next run before closing. */\nconst DEFAULT_IDLE_WAIT_MS = 30_000\n\nfunction matchThread(re: RegExp, urlPath: string): { name: string; sessionId: string } | null {\n const m = re.exec(urlPath)\n return m ? { name: decodeURIComponent(m[1]), sessionId: decodeURIComponent(m[2]) } : null\n}\n\nexport const isThreadMessagePath = (urlPath: string) => matchThread(THREAD_MESSAGE_PATH, urlPath)\nexport const isThreadStreamPath = (urlPath: string) => matchThread(THREAD_STREAM_PATH, urlPath)\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Inputs for {@link handleThreadMessage} (bundled to stay within the arity budget). */\nexport interface ThreadMessageArgs {\n readonly mod: unknown\n readonly apiKey: string\n readonly sessionId: string\n readonly request: Request\n readonly source: string\n readonly csrfMode?: CsrfMode\n}\n\n/** POST a follow-up on a thread. Returns `202` with `{ runId }` (started) or `{ queued: true }`. */\nexport async function handleThreadMessage(args: ThreadMessageArgs): Promise<Response> {\n const { mod, apiKey, sessionId, request, source, csrfMode = 'strict' } = args\n // A follow-up drives the agent (spends LLM tokens) — reject a cross-origin POST.\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* invalid/empty JSON → 400 below */\n }\n const input = parseAgentRequestBody(body)\n if (input === null) {\n return jsonError(400, 'BAD_REQUEST', 'Request must contain a non-empty message.')\n }\n const result = postThreadFollowUp(\n {\n registry: getThreadRunRegistry(),\n cache: getRunEventCache(),\n startRun: makeThreadStartRun(mod, apiKey, source),\n },\n sessionId,\n input.message,\n )\n const headers: Record<string, string> = { 'content-type': 'application/json; charset=utf-8' }\n if ('runId' in result) headers[RUN_ID_HEADER] = result.runId\n return new Response(JSON.stringify(result), { status: 202, headers })\n}\n\n/** GET the thread's durable stream. Active ⇒ attach now; idle ⇒ wait (bounded) for the next run. */\nexport function handleThreadStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry = getThreadRunRegistry(),\n cache: RunEventCache = getRunEventCache(),\n idleWaitMs = DEFAULT_IDLE_WAIT_MS,\n): Response {\n const active = registry.getActive(sessionId)\n if (active !== null && cache.has(active)) {\n // Reuse the M37 reconnect handler — replay + live tail on the active run.\n return handleAgentRunReconnect(active, request, cache)\n }\n return waitThenAttachStream(sessionId, request, registry, cache, idleWaitMs)\n}\n\n/** Subscribe to an idle thread: wait (bounded) for the NEXT run to start, then attach + tail. */\nfunction waitThenAttachStream(\n sessionId: string,\n request: Request,\n registry: ThreadRunRegistry,\n cache: RunEventCache,\n idleWaitMs: number,\n): Response {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false\n const send = (text: string): void => {\n if (closed) return\n try {\n controller.enqueue(encodeSse(text))\n } catch {\n /* closed by an abort race */\n }\n }\n let detachAttach: (() => void) | undefined\n const close = (): void => {\n if (closed) return\n send(SSE_DONE_FRAME)\n closed = true\n try {\n controller.close()\n } catch {\n /* already closed */\n }\n }\n const offNext = registry.onNextRun(sessionId, (runId) => {\n const res = cache.attach(\n runId,\n -1,\n (frame) => {\n send(formatSseFrame(frame.seq, frame.data))\n },\n () => {\n close()\n },\n )\n if (!res.known) {\n close()\n return\n }\n for (const frame of res.replay) send(formatSseFrame(frame.seq, frame.data))\n if (res.ended) {\n close()\n return\n }\n detachAttach = res.unsubscribe\n })\n // HIGH-1 — the waiter teardown MUST run on BOTH the idle-wait timeout AND the\n // client abort, else the (one-shot) `onNextRun` waiter leaks in the registry\n // when a timed-out subscriber's session never receives another run.\n const teardownWaiter = (): void => {\n offNext()\n detachAttach?.()\n }\n const timer = setTimeout(() => {\n teardownWaiter()\n close()\n }, idleWaitMs)\n timer.unref()\n request.signal.addEventListener('abort', () => {\n teardownWaiter()\n clearTimeout(timer)\n close()\n })\n },\n })\n return new Response(stream, { headers: { ...SSE_BASE_HEADERS } })\n}\n","/**\n * M15/M16 follow-up — shared dispatcher for the agent AUXILIARY routes that BOTH dev (vite\n * middleware) and prod (`theokit start` handler) must serve identically. Before this, these routes\n * were wired only into the dev middleware, so a built/deployed app served none of them (agent cards,\n * MCP, pending-approvals listing all 404'd in production).\n *\n * Single source of truth (DRY): one Web-Request→Response dispatcher, two callers. It handles the\n * routes that derive purely from the agent module + shared registry:\n * - **M15** `GET /.well-known/<name>/agent-card.json` → {@link handleAgentCard}\n * - **M14** `GET /api/agents/<name>/approvals` → {@link handleListApprovals}\n * - **M16** `POST /api/agents/<name>/mcp` → {@link handleMcpJsonRpc}\n *\n * Channels (M27) are NOT here: a channel webhook needs app-supplied `validators` + `onMessage`, so\n * the app wires `handleChannelWebhook` in its own route (it cannot be auto-derived from the module).\n * The HITL approve route stays in each caller (it carries caller-specific rate-limiting/CSRF plumbing).\n */\nimport type { AgentNode } from '../scan/agent-scan.js'\nimport { validateCsrfRequest, type CsrfMode } from '../security/csrf.js'\n\nimport { isAgentCardPath, handleAgentCard } from './agent-card-handler.js'\nimport { getApprovalRegistry } from './approval-registry.js'\nimport { handleAgentRunReconnect, isAgentRunStreamPath } from './handle-agent-run-reconnect.js'\nimport {\n handleThreadMessage,\n handleThreadStream,\n isThreadMessagePath,\n isThreadStreamPath,\n} from './handle-thread-routes.js'\nimport { isListApprovalsPath, handleListApprovals } from './list-approvals-handler.js'\nimport { extractAppResources } from './mcp-app-resources.js'\nimport { isMcpPath, handleMcpJsonRpc } from './mcp-handler.js'\nimport { getRunEventCache } from './run-event-cache.js'\n\n/** JSON error envelope (mirrors mount-agent.ts:37 — the parity source for the MCP CSRF gate). */\nfunction jsonError(status: number, code: string, message: string): Response {\n return new Response(JSON.stringify({ error: { code, message } }), {\n status,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/** Dependencies the aux dispatcher needs from its caller (dev or prod). */\nexport interface AuxRouteDeps {\n /** Discovered agents (from `scanAgents`). */\n agents: readonly AgentNode[]\n /** Load an agent module from its file path (dev: vite loader; prod: dynamic import). */\n loadModule: (filePath: string) => Promise<unknown>\n /** Absolute base URL (`http(s)://host`) for the agent-card endpoint URLs. */\n baseUrl: string\n /**\n * M34 (#97) — CSRF enforcement mode for the MCP route. `POST /api/agents/<name>/mcp` drives the\n * agent (spends LLM tokens), so a cross-origin POST MUST be rejected in `'strict'` — parity with\n * the agent-run route (`mount-agent.ts:83-91`). Defaults to `'strict'` (safe-by-default); a caller\n * that already gated upstream may pass `'off'`.\n */\n csrfMode?: CsrfMode\n /**\n * M39 — lazily resolve the provider apiKey. Required only for the thread\n * follow-up route (which drives the agent); resolved on demand so non-agent\n * aux routes (card, approvals, stream) never need a provider key.\n */\n resolveApiKey?: () => string\n}\n\n/**\n * Serve an agent auxiliary route. Returns a `Response` when `urlPath` matches an aux route (card /\n * list-approvals / mcp) and the method + agent resolve; returns `null` to fall through (not an aux\n * route, wrong method, or unknown agent — the caller then owns the 404/next).\n */\nexport async function serveAgentAuxRoute(\n request: Request,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const method = request.method.toUpperCase()\n\n // M15 — A2A agent card at `/.well-known/<name>/agent-card.json` (GET).\n const cardName = isAgentCardPath(urlPath)\n if (cardName !== null) {\n if (method !== 'GET') return null\n const agent = deps.agents.find((a) => a.name === cardName)\n if (!agent) return null\n const mod = await deps.loadModule(agent.filePath)\n return handleAgentCard(mod, agent.name, agent.agentPath, deps.baseUrl)\n }\n\n // M14 — GET /api/agents/<name>/approvals (pending HITL approvals).\n if (isListApprovalsPath(urlPath)) {\n if (method !== 'GET') return null\n return handleListApprovals(getApprovalRegistry())\n }\n\n // M37 — GET /api/agents/<name>/runs/<runId>/stream (durable reconnect / observe).\n // INTENTIONALLY open (no CSRF, no auth gate): a GET is not CSRF-vulnerable, the\n // run-start POST is already gated, and the `runId` is a 122-bit UUID (unguessable).\n // Observe-by-runId is a FEATURE (ADR-0046 D5) — a second client resumes a run a\n // first started. Do NOT add a custom-header CSRF check here: browsers send NO\n // custom headers with `EventSource`, so it would break native SSE reconnect.\n const runStream = isAgentRunStreamPath(urlPath)\n if (runStream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === runStream.name)) return null\n return handleAgentRunReconnect(runStream.runId, request, getRunEventCache())\n }\n\n // M39 — thread signal routes (follow-up message + subscribe-by-thread). Extracted\n // to keep this dispatcher within the cognitive-complexity budget (G6).\n const threadResponse = await serveThreadRoute(request, method, urlPath, deps)\n if (threadResponse !== null) return threadResponse\n\n // M16 — POST /api/agents/<name>/mcp (JSON-RPC MCP server). Extracted to keep this dispatcher\n // within the cognitive-complexity budget (G6).\n const mcpName = isMcpPath(urlPath)\n if (mcpName !== null) {\n return serveMcpRoute(request, method, mcpName, deps)\n }\n\n return null\n}\n\n/**\n * M39 — serve the thread routes:\n * - `POST .../threads/<sessionId>/message` (follow-up) — loads the module, drives\n * the run headless via the thread dispatcher. Needs `resolveApiKey` (drives the\n * agent) → 501 when absent (rather than a silent 404).\n * - `GET .../threads/<sessionId>/stream` (subscribe) — attach to the active/next\n * run's durable stream. INTENTIONALLY open (GET, no custom headers — like the\n * M37 reconnect route).\n *\n * SECURITY (thread stream): unlike the M37 reconnect route — keyed on an\n * `mintRunId()` UUID (122-bit unguessable) — the thread stream is keyed on the\n * caller-supplied `sessionId`. The open GET is safe ONLY if the `sessionId` is\n * unguessable (e.g. a client-minted UUID). An app that uses a PREDICTABLE\n * sessionId (user id, email, sequential id) MUST add its own auth gate before\n * this endpoint, or any party who can guess the sessionId can read the thread's\n * live conversation stream. Documented in `docs/architecture/multi-surface-architecture.md`.\n *\n * Returns `null` to fall through (not a thread route, wrong method, unknown agent).\n */\nasync function serveThreadRoute(\n request: Request,\n method: string,\n urlPath: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n const stream = isThreadStreamPath(urlPath)\n if (stream !== null) {\n if (method !== 'GET') return null\n if (!deps.agents.some((a) => a.name === stream.name)) return null\n return handleThreadStream(stream.sessionId, request)\n }\n\n const msg = isThreadMessagePath(urlPath)\n if (msg !== null) {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === msg.name)\n if (!agent) return null\n if (deps.resolveApiKey === undefined) {\n // MEDIUM-1 — the path matched but the caller wired no provider-key resolver.\n // Fail loudly (501) instead of a silent 404 that reads as \"route not found\".\n return jsonError(\n 501,\n 'NOT_CONFIGURED',\n 'Thread follow-up requires a provider API key (resolveApiKey was not provided to serveAgentAuxRoute).',\n )\n }\n const mod = await deps.loadModule(agent.filePath)\n return handleThreadMessage({\n mod,\n apiKey: deps.resolveApiKey(),\n sessionId: msg.sessionId,\n request,\n source: `agent \"${msg.name}\"`,\n csrfMode: deps.csrfMode ?? 'strict',\n })\n }\n return null\n}\n\n/**\n * Serve the MCP route with the M34 gates: default-DENY opt-in → CSRF → dispatch. Returns `null` to\n * fall through (wrong method / unknown or non-opted-in agent), a 403 on CSRF failure, else the\n * JSON-RPC response.\n */\nasync function serveMcpRoute(\n request: Request,\n method: string,\n mcpName: string,\n deps: AuxRouteDeps,\n): Promise<Response | null> {\n if (method !== 'POST') return null\n const agent = deps.agents.find((a) => a.name === mcpName)\n if (!agent) return null\n\n const mod = await deps.loadModule(agent.filePath)\n\n // M34 — DEFAULT-DENY: an agent is NOT exposed on MCP unless it explicitly opts in with a named\n // `export const mcp = true` (blueprint D5 — default-EXPOSE is the footgun magnified by the\n // multi-surface thesis). Absent the opt-in, fall through to 404 (the agent is web-only). This is a\n // breaking change from the M16 auto-mount (documented in the CHANGELOG § Security).\n if (!isMcpExposed(mod)) return null\n\n // M34 (#97) — enforce CSRF BEFORE any work. The MCP route drives the agent (real LLM tokens), so a\n // cross-origin POST must be rejected — parity with the agent-run route (`mount-agent.ts:83-91`).\n const csrfMode = deps.csrfMode ?? 'strict'\n if (csrfMode === 'strict') {\n const csrf = validateCsrfRequest(request)\n if (!csrf.valid) return jsonError(403, 'CSRF_FAILED', `CSRF check failed: ${csrf.reason}`)\n }\n\n let body: unknown = null\n try {\n body = await request.json()\n } catch {\n /* malformed/empty JSON → handleMcpJsonRpc returns a -32600 envelope */\n }\n // M30 — pass the agent's declared `ui://` App resources (named `appResources` export) so the MCP\n // server advertises + serves them via resources/list + resources/read.\n return handleMcpJsonRpc(mod, agent.name, body, extractAppResources(mod))\n}\n\n/**\n * M34 — DEFAULT-DENY opt-in check: is this agent module exposed on the MCP surface? An agent opts in\n * with a named `export const mcp = true` (mirroring the `appResources` named-export convention).\n * Anything else (absent / falsy) → NOT exposed. Read at the emit layer (blueprint D5).\n */\nfunction isMcpExposed(mod: unknown): boolean {\n return (mod as { mcp?: unknown } | null | undefined)?.mcp === true\n}\n","/**\n * 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 * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\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// The primitive `IncomingMessage` → Web `Request` converters live in\n// `node-request.js` (dependency-free, shared with the executor). Re-exported\n// here so existing importers of the adapter keep resolving them.\nexport { incomingMessageToWebRequest, incomingMessageToHandlerRequest } 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"],"mappings":";;;;;;;;;;;;;;;AAAA,OAAO,eAAe;AAef,IAAM,uBAAwC;AAAA,EACnD,MAAM;AAAA,EACN,WAAW,CAAC,MAAM,KAAK,UAAU,UAAU,UAAU,CAAC,CAAC;AAAA,EACvD,aAAa,CAAC,QAAQ;AACpB,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,WAAO,UAAU,YAAY,MAAM;AAAA,EACrC;AACF;AAEO,IAAM,kBAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,WAAW,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAClC,aAAa,CAAC,QAAQ,KAAK,MAAM,GAAG;AACtC;AAEA,IAAM,YAA6C;AAAA,EACjD,WAAW;AAAA,EACX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AM,MAAM,oBAAoB,GAAG,CAAC;AACzE;AAOA,SAAS,aAAa,KAAuB;AAC3C,SAAQ,KAA8C,QAAQ;AAChE;;;AChLA,eAAsB,iCACpB,UACA,KACe;AAKf,QAAM,aAAa,SAAS,QAAQ,aAAa;AACjD,MAAI,WAAW,SAAS,GAAG;AACzB,QAAI,UAAU,cAAc,UAAU;AAAA,EACxC;AACA,QAAM,eAAuC,CAAC;AAC9C,aAAW,CAAC,KAAK,KAAK,KAAK,SAAS,QAAQ,QAAQ,GAAG;AACrD,QAAI,IAAI,YAAY,MAAM,aAAc;AACxC,iBAAa,GAAG,IAAI;AAAA,EACtB;AACA,MAAI,UAAU,SAAS,QAAQ,SAAS,YAAY,YAAY;AAGhE,MAAI,SAAS,SAAS,MAAM;AAC1B,QAAI,IAAI;AACR;AAAA,EACF;AACA,QAAM,SAAS,SAAS,KAAK,UAAU;AACvC,MAAI;AACF,eAAS;AACP,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,UAAI,KAAM;AAEV,UAAI,MAAM,KAAK;AAAA,IACjB;AACA,QAAI,IAAI;AAAA,EACV,UAAE;AACA,WAAO,YAAY;AAAA,EACrB;AACF;","names":["compileAgentModule","resolveEnabledSkills","streamAgentUIMessages","compileAgentModule","compileAgentModule","jsonError","compileAgentModule","resolveEnabledSkills","streamAgentUIMessages","jsonError","jsonError"]}
@@ -2,7 +2,6 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  handleAgentApproval,
5
- incomingMessageToWebRequest,
6
5
  isAgentCardPath,
7
6
  isApprovalPath,
8
7
  isListApprovalsPath,
@@ -10,7 +9,7 @@ import {
10
9
  resolveTransformer,
11
10
  serveAgentAuxRoute,
12
11
  writeWebResponseToServerResponse
13
- } from "./chunk-S7L6H3KP.js";
12
+ } from "./chunk-RVJAM77M.js";
14
13
  import {
15
14
  isMcpPath
16
15
  } from "./chunk-2CVV6CNN.js";
@@ -41,7 +40,7 @@ import {
41
40
  handleBatchRequest,
42
41
  handleCspReport,
43
42
  handleCsrfReadiness
44
- } from "./chunk-KXA37ONC.js";
43
+ } from "./chunk-RPMKF6BC.js";
45
44
  import {
46
45
  applySecurityHeaders,
47
46
  createPluginRunnerFromConfig,
@@ -51,9 +50,10 @@ import {
51
50
  executeRoute,
52
51
  findSuggestion,
53
52
  generateNonce,
53
+ incomingMessageToWebRequest,
54
54
  logRequest,
55
55
  sendError
56
- } from "./chunk-WR4F4EEZ.js";
56
+ } from "./chunk-3KD2O6DC.js";
57
57
  import {
58
58
  scanAgents
59
59
  } from "./chunk-L4GCEMNW.js";
@@ -1917,19 +1917,19 @@ async function theoPluginAsync(rootOrOptions) {
1917
1917
  })
1918
1918
  );
1919
1919
  }
1920
- const { appTypedClientPlugin } = await import("./app-typed-client-LM2PNOCL.js");
1920
+ const { appTypedClientPlugin } = await import("./app-typed-client-N4TRX5FI.js");
1921
1921
  const appClientPlugin = appTypedClientPlugin({
1922
1922
  cwd: projectRoot,
1923
1923
  serverDir: serverDirAbs,
1924
1924
  distDir: resolve7(projectRoot, ".theokit")
1925
1925
  });
1926
- const { actionsVirtualModule } = await import("./actions-virtual-module-BCN7IEQC.js");
1926
+ const { actionsVirtualModule } = await import("./actions-virtual-module-3KSP3WPJ.js");
1927
1927
  const actionsPlugin = actionsVirtualModule({
1928
1928
  serverDir: serverDirAbs,
1929
1929
  distDir: resolve7(projectRoot, ".theokit")
1930
1930
  });
1931
1931
  const { agentsTypedClientPlugin } = await import("./agents-typed-client-5DCGDWFZ.js");
1932
- const { generateManifest } = await import("./internal-api-CCRY3HN4.js");
1932
+ const { generateManifest } = await import("./internal-api-5JKDYRGM.js");
1933
1933
  const agentsClientPlugin = agentsTypedClientPlugin({
1934
1934
  projectRoot,
1935
1935
  agentsDir: agentsDirName,
@@ -2104,4 +2104,4 @@ export {
2104
2104
  theoPluginAsync,
2105
2105
  theoPlugin
2106
2106
  };
2107
- //# sourceMappingURL=chunk-OOS5LB5Y.js.map
2107
+ //# sourceMappingURL=chunk-T4TCLEFB.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isZodLike
3
- } from "./chunk-TGTNRUH3.js";
3
+ } from "./chunk-WL4AX5FI.js";
4
4
  import {
5
5
  validateCsrfRequest
6
6
  } from "./chunk-TSLSIRBR.js";
@@ -454,4 +454,4 @@ export {
454
454
  validateRouteInput,
455
455
  executeWebRequest
456
456
  };
457
- //# sourceMappingURL=chunk-4MTCKE5I.js.map
457
+ //# sourceMappingURL=chunk-UDG6JPVP.js.map