theokit 0.23.1 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions-virtual-module-Z2IXNF72.js +0 -0
- package/dist/add-W6FNTAFS.js +0 -0
- package/dist/{agent-7IGDT55V.js → agent-7474NDZD.js} +2 -2
- package/dist/agents-typed-client-RIJVHSX4.js +0 -0
- package/dist/app-typed-client-YCQC3MZ7.js +0 -0
- package/dist/aws-lambda-7GSCNLPY.js +0 -0
- package/dist/body-parser-web-FV5HWCY3.js +0 -0
- package/dist/broadcast-LUMOJIJT.js +0 -0
- package/dist/{build-G7WWVZTL.js → build-CVWAK4UE.js} +2 -2
- package/dist/build-request-body-preview-QMWD2IXK.js +0 -0
- package/dist/bun-KP2KES6S.js +0 -0
- package/dist/check-PD2FTKMM.js +0 -0
- package/dist/chunk-2CVV6CNN.js +0 -0
- package/dist/chunk-45C3WUQ7.js +0 -0
- package/dist/chunk-5ODOE6EF.js +0 -0
- package/dist/chunk-AFVTEAES.js +0 -0
- package/dist/{chunk-5PY3QPVM.js → chunk-DMGVH3VG.js} +30 -1
- package/dist/chunk-DMGVH3VG.js.map +1 -0
- package/dist/{chunk-BLL5LY7R.js → chunk-FARW5PH6.js} +200 -6
- package/dist/chunk-FARW5PH6.js.map +1 -0
- package/dist/chunk-FOZIR3TG.js +0 -0
- package/dist/chunk-FRUEDJFX.js +0 -0
- package/dist/chunk-GDN3PXFH.js +0 -0
- package/dist/chunk-GEQJAFSV.js +0 -0
- package/dist/chunk-GSO77FSM.js +0 -0
- package/dist/chunk-HGZL5EOI.js +0 -0
- package/dist/chunk-HNBWZKIQ.js +0 -0
- package/dist/{chunk-AYZCGJXA.js → chunk-IEA4O6ZN.js} +2 -2
- package/dist/chunk-IEES3CHD.js +0 -0
- package/dist/chunk-JAIKGP3Q.js +0 -0
- package/dist/chunk-KXA37ONC.js +0 -0
- package/dist/chunk-M6NMS5LR.js +0 -0
- package/dist/chunk-P37RZRFV.js +0 -0
- package/dist/chunk-TERFLG67.js +0 -0
- package/dist/{chunk-LGVVX3BV.js → chunk-VK553I55.js} +180 -13
- package/dist/chunk-VK553I55.js.map +1 -0
- package/dist/chunk-WR4F4EEZ.js +0 -0
- package/dist/chunk-YJWEADAW.js +0 -0
- package/dist/{chunk-JITNAZXE.js → chunk-ZGKGXXZG.js} +2 -2
- package/dist/cli/index.js +5 -5
- package/dist/cloudflare-C6E5SPAE.js +0 -0
- package/dist/configure-agent-registry-ZOBVU3MV.js +0 -0
- package/dist/db-3UNAMSFK.js +0 -0
- package/dist/deno-deploy-RFZN56X4.js +0 -0
- package/dist/{dev-SHAN56K5.js → dev-FSTYMPPF.js} +3 -3
- package/dist/dev-emit-EFQRBVYS.js +0 -0
- package/dist/dispatcher-EJHL6JMJ.js +0 -0
- package/dist/docker-LZZB4D5E.js +0 -0
- package/dist/generate-373DALPY.js +0 -0
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/info-2OOXFTJX.js +0 -0
- package/dist/internal-api-Y5REPVUS.js +0 -0
- package/dist/load-config-3EAQTXPH.js +0 -0
- package/dist/{mcp-P4MHP3VA.js → mcp-TOYHKCB6.js} +2 -2
- package/dist/netlify-PMLHVPN4.js +0 -0
- package/dist/node-BPJ3Z4DT.js +0 -0
- package/dist/openapi-ERYWAT3A.js +0 -0
- package/dist/registry-3NB7KOUI.js +0 -0
- package/dist/router-TLEAOFID.js +0 -0
- package/dist/routes-XNS3UM3B.js +0 -0
- package/dist/scan-7MJC6PYU.js +0 -0
- package/dist/schema-LYOLNHZ7.js +0 -0
- package/dist/server/define/index.js +2 -4
- package/dist/server/index.js +2 -4
- package/dist/server/index.js.map +1 -1
- package/dist/server-error-to-envelope-UUXDSLAZ.js +0 -0
- package/dist/server-routes-hmr-VZXOP5YT.js +0 -0
- package/dist/services-json-Y3XODNB5.js +0 -0
- package/dist/services-typed-client-32KMTTXR.js +0 -0
- package/dist/{start-RD5WQMIH.js → start-LEDGWJF2.js} +2 -2
- package/dist/static-MB2CD5Y3.js +0 -0
- package/dist/storage-manager-ZSQFLEYT.js +0 -0
- package/dist/theo-cloud-DQRP6S6M.js +0 -0
- package/dist/upgrade-readiness-ACGW44JC.js +0 -0
- package/dist/vercel-J6G7ZHYQ.js +0 -0
- package/dist/vite-plugin/index.js +1 -2
- package/dist/{vite-plugin-A7WGYEMD.js → vite-plugin-HSOWPMK4.js} +3 -3
- package/package.json +10 -10
- package/LICENSE +0 -201
- package/dist/chunk-5PY3QPVM.js.map +0 -1
- package/dist/chunk-BLL5LY7R.js.map +0 -1
- package/dist/chunk-JZHT3LW7.js +0 -32
- package/dist/chunk-JZHT3LW7.js.map +0 -1
- package/dist/chunk-LGVVX3BV.js.map +0 -1
- /package/dist/{agent-7IGDT55V.js.map → agent-7474NDZD.js.map} +0 -0
- /package/dist/{build-G7WWVZTL.js.map → build-CVWAK4UE.js.map} +0 -0
- /package/dist/{chunk-AYZCGJXA.js.map → chunk-IEA4O6ZN.js.map} +0 -0
- /package/dist/{chunk-JITNAZXE.js.map → chunk-ZGKGXXZG.js.map} +0 -0
- /package/dist/{dev-SHAN56K5.js.map → dev-FSTYMPPF.js.map} +0 -0
- /package/dist/{mcp-P4MHP3VA.js.map → mcp-TOYHKCB6.js.map} +0 -0
- /package/dist/{start-RD5WQMIH.js.map → start-LEDGWJF2.js.map} +0 -0
- /package/dist/{vite-plugin-A7WGYEMD.js.map → vite-plugin-HSOWPMK4.js.map} +0 -0
|
File without changes
|
package/dist/add-W6FNTAFS.js
CHANGED
|
File without changes
|
|
@@ -3,7 +3,7 @@ import "tsx/esm";
|
|
|
3
3
|
import {
|
|
4
4
|
agentCommand,
|
|
5
5
|
createAgentSsrLoader
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-ZGKGXXZG.js";
|
|
7
7
|
import "./chunk-M6NMS5LR.js";
|
|
8
8
|
import "./chunk-GDN3PXFH.js";
|
|
9
9
|
import "./chunk-TERFLG67.js";
|
|
@@ -12,4 +12,4 @@ export {
|
|
|
12
12
|
agentCommand,
|
|
13
13
|
createAgentSsrLoader
|
|
14
14
|
};
|
|
15
|
-
//# sourceMappingURL=agent-
|
|
15
|
+
//# sourceMappingURL=agent-7474NDZD.js.map
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -531,7 +531,7 @@ async function buildCommand(options) {
|
|
|
531
531
|
`);
|
|
532
532
|
}
|
|
533
533
|
async function runAdapterBuild(target, config, cwd) {
|
|
534
|
-
const { theoPluginAsync } = await import("./vite-plugin-
|
|
534
|
+
const { theoPluginAsync } = await import("./vite-plugin-HSOWPMK4.js");
|
|
535
535
|
const { default: react } = await import("@vitejs/plugin-react");
|
|
536
536
|
const ctx = {
|
|
537
537
|
// `react()` may return Plugin or Plugin[] depending on version; spread the
|
|
@@ -616,4 +616,4 @@ function relativize3(absPath, root) {
|
|
|
616
616
|
export {
|
|
617
617
|
buildCommand
|
|
618
618
|
};
|
|
619
|
-
//# sourceMappingURL=build-
|
|
619
|
+
//# sourceMappingURL=build-CVWAK4UE.js.map
|
|
File without changes
|
package/dist/bun-KP2KES6S.js
CHANGED
|
File without changes
|
package/dist/check-PD2FTKMM.js
CHANGED
|
File without changes
|
package/dist/chunk-2CVV6CNN.js
CHANGED
|
File without changes
|
package/dist/chunk-45C3WUQ7.js
CHANGED
|
File without changes
|
package/dist/chunk-5ODOE6EF.js
CHANGED
|
File without changes
|
package/dist/chunk-AFVTEAES.js
CHANGED
|
File without changes
|
|
@@ -240,6 +240,34 @@ function plugin(name) {
|
|
|
240
240
|
});
|
|
241
241
|
}
|
|
242
242
|
|
|
243
|
+
// src/server/define/ui-message-stream-response.ts
|
|
244
|
+
var UI_MESSAGE_STREAM_HEADERS = {
|
|
245
|
+
"content-type": "text/event-stream",
|
|
246
|
+
"x-vercel-ai-ui-message-stream": "v1"
|
|
247
|
+
};
|
|
248
|
+
var DONE_FRAME = "data: [DONE]\n\n";
|
|
249
|
+
function encode(text) {
|
|
250
|
+
return new TextEncoder().encode(text);
|
|
251
|
+
}
|
|
252
|
+
function uiMessageStreamResponse(chunks) {
|
|
253
|
+
const stream = new ReadableStream({
|
|
254
|
+
async start(controller) {
|
|
255
|
+
try {
|
|
256
|
+
for await (const chunk of chunks) {
|
|
257
|
+
controller.enqueue(encode(`data: ${JSON.stringify(chunk)}
|
|
258
|
+
|
|
259
|
+
`));
|
|
260
|
+
}
|
|
261
|
+
} catch {
|
|
262
|
+
} finally {
|
|
263
|
+
controller.enqueue(encode(DONE_FRAME));
|
|
264
|
+
controller.close();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
return new Response(stream, { headers: UI_MESSAGE_STREAM_HEADERS });
|
|
269
|
+
}
|
|
270
|
+
|
|
243
271
|
// src/server/define/define-channel.ts
|
|
244
272
|
function defineChannel(handler) {
|
|
245
273
|
return handler;
|
|
@@ -257,7 +285,8 @@ export {
|
|
|
257
285
|
applyTransform,
|
|
258
286
|
tool,
|
|
259
287
|
plugin,
|
|
288
|
+
uiMessageStreamResponse,
|
|
260
289
|
defineChannel,
|
|
261
290
|
defineWebChannel
|
|
262
291
|
};
|
|
263
|
-
//# sourceMappingURL=chunk-
|
|
292
|
+
//# sourceMappingURL=chunk-DMGVH3VG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/define/define-route.ts","../src/server/define/route-builder.ts","../src/server/define/define-action.ts","../src/server/define/action-builder.ts","../src/server/define/define-websocket.ts","../src/server/define/websocket-builder.ts","../src/server/define/define-middleware.ts","../src/server/define/middleware-builder.ts","../src/server/define/define-agent-tool.ts","../src/server/define/tool-builder.ts","../src/server/plugin-types.ts","../src/server/define/plugin-builder.ts","../src/server/define/ui-message-stream-response.ts","../src/server/define/define-channel.ts"],"sourcesContent":["import type { z } from 'zod'\n\n// T2.2 (architecture-cleanup) — RouteConfig type moved to core/contracts/\n// (canonical home per ADR-0001 v3). Re-export preserves the public path\n// `import { type RouteConfig } from 'theokit/server'`.\nexport type { RouteConfig } from '../../core/contracts/route-config.js'\n\nimport type { RouteConfig } from '../../core/contracts/route-config.js'\n\n/**\n * Define a typed HTTP route.\n * Identity function — provides type inference for route handlers.\n */\nexport function defineRoute<\n TQuery extends z.ZodType = z.ZodUndefined,\n TBody extends z.ZodType = z.ZodUndefined,\n TParams extends z.ZodType = z.ZodUndefined,\n TCtx = unknown,\n TResponse = unknown,\n>(\n config: RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>,\n): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse> {\n return config\n}\n","/**\n * M31 Phase 3 — `route()`, the fluent builder that replaces `defineRoute({...})`.\n *\n * Pure type-state (mirrors `tool-builder.ts`). `.query/.body/.params` set Zod schemas whose\n * `z.infer<>` flows into the handler's `ctx`; `.handler()` is required before `.build()`. `.build()`\n * delegates to the internal {@link defineRoute} (an identity fn), emitting the identical\n * `RouteConfig` — the scan/execute path is UNCHANGED (identity-shape delegation, blueprint §2).\n *\n * export const POST = route()\n * .params(z.object({ id: z.string() }))\n * .body(z.object({ text: z.string() }))\n * .handler(({ params, body }) => save(params.id, body.text))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport type { RouteConfig } from '../../core/contracts/route-config.js'\n\nimport { defineRoute } from './define-route.js'\n\n/** Compile-error carrier: `.build()` called before `.handler()`. */\ninterface MissingHandlerError {\n readonly __theokitError: 'a route needs .handler(fn) before .build()'\n}\n\n/**\n * The fluent route builder. `TQuery/TBody/TParams` track the input schemas (default `z.ZodUndefined`,\n * matching {@link RouteConfig}); `TResponse` tracks the handler return; `THandlerSet` gates `.build()`.\n */\nexport interface RouteBuilder<\n TQuery extends z.ZodType = z.ZodUndefined,\n TBody extends z.ZodType = z.ZodUndefined,\n TParams extends z.ZodType = z.ZodUndefined,\n TCtx = unknown,\n TResponse = unknown,\n THandlerSet extends boolean = false,\n> {\n /** Set the URL search-params schema. Inferred into `ctx.query`. */\n query<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<S, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Set the request-body schema. Inferred into `ctx.body`. */\n body<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<TQuery, S, TParams, TCtx, TResponse, THandlerSet>\n /** Set the path-params schema. Inferred into `ctx.params`. */\n params<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<TQuery, TBody, S, TCtx, TResponse, THandlerSet>\n /** Runtime-only validation of the handler's plain-object return (500 on mismatch). Not inferred (YAGNI). */\n response(schema: z.ZodType): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Override the HTTP status for a plain-object return (default 200; 204 for void). */\n status(code: number): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Opt out of CSRF enforcement for this route (webhooks / OAuth callbacks). */\n csrf(disabled: false): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /**\n * Set the handler. Its `ctx` infers `query/body/params` from the schemas set above. Required\n * before `.build()`.\n */\n handler<R>(\n fn: (ctx: {\n query: z.infer<TQuery>\n body: z.infer<TBody>\n params: z.infer<TParams>\n request: Request\n ctx: TCtx\n }) => R | Promise<R>,\n ): RouteBuilder<TQuery, TBody, TParams, TCtx, R, true>\n /**\n * Resolve to the `RouteConfig` — the SAME value `defineRoute({...})` returns. COMPILE ERROR when\n * `.handler()` was never called.\n */\n build(\n ...guard: THandlerSet extends true ? [] : [error: MissingHandlerError]\n ): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>\n}\n\n/**\n * Permissive internal shape — the runtime seam works with `z.ZodType` schemas (ctx fields typed\n * `unknown`); the precise per-schema types are carried to callers by the {@link RouteBuilder}\n * interface via the `as unknown as RouteBuilder` bridge. `defineRoute` is an identity fn.\n */\ntype AnyRouteConfig = RouteConfig<z.ZodType, z.ZodType, z.ZodType>\n\ninterface RouteSpecAccumulator {\n query?: z.ZodType\n body?: z.ZodType\n params?: z.ZodType\n response?: z.ZodType\n status?: number\n csrf?: false\n handler?: AnyRouteConfig['handler']\n}\n\nfunction makeRouteBuilder(spec: RouteSpecAccumulator): RouteBuilder {\n const runtime = {\n query: (schema: z.ZodType) => makeRouteBuilder({ ...spec, query: schema }),\n body: (schema: z.ZodType) => makeRouteBuilder({ ...spec, body: schema }),\n params: (schema: z.ZodType) => makeRouteBuilder({ ...spec, params: schema }),\n response: (schema: z.ZodType) => makeRouteBuilder({ ...spec, response: schema }),\n status: (code: number) => makeRouteBuilder({ ...spec, status: code }),\n csrf: (disabled: false) => makeRouteBuilder({ ...spec, csrf: disabled }),\n handler: (fn: AnyRouteConfig['handler']) => makeRouteBuilder({ ...spec, handler: fn }),\n build: (): AnyRouteConfig => {\n // Fail-fast for untyped (JS) callers — the type-state guard makes this unreachable from TS.\n if (spec.handler === undefined) {\n throw new Error('route(): call .handler(fn) before .build()')\n }\n const config: AnyRouteConfig = {\n ...(spec.query !== undefined ? { query: spec.query } : {}),\n ...(spec.body !== undefined ? { body: spec.body } : {}),\n ...(spec.params !== undefined ? { params: spec.params } : {}),\n ...(spec.response !== undefined ? { response: spec.response } : {}),\n ...(spec.status !== undefined ? { status: spec.status } : {}),\n ...(spec.csrf !== undefined ? { csrf: spec.csrf } : {}),\n handler: spec.handler,\n }\n return defineRoute(config)\n },\n }\n return runtime as unknown as RouteBuilder\n}\n\n/**\n * Start a fluent route definition. Chain `.query/.body/.params/.response/.status/.csrf` (all\n * optional), then `.handler()` (required) and `.build()` for the `RouteConfig`.\n */\nexport function route(): RouteBuilder {\n return makeRouteBuilder({})\n}\n","import type { z } from 'zod'\n\n/**\n * Action wire-protocol accept mode per plan g3-server-actions-and-useaction\n * v1.2 ADR D1. Default behavior (when omitted) is `'json'`. `'form'` opts the\n * action into FormData multipart parsing for progressive-enhancement forms;\n * the runtime in `server/http/action-execute.ts` will coerce FormData entries\n * against the `input` schema via `formDataToObject` (Astro pattern).\n */\nexport type ActionAccept = 'form' | 'json'\n\nexport interface ActionConfig<TInput extends z.ZodType, TCtx = unknown> {\n /**\n * Zod input schema. Required: every action declares its input contract via\n * Zod (architecture rule: zod-is-SSOT). The shape becomes the handler's\n * typed `input` parameter via `z.infer<TInput>`.\n */\n input: TInput\n /**\n * Wire-protocol accept mode. Defaults to `'json'` when omitted. Setting\n * `'form'` switches the runtime to FormData multipart parsing — the input\n * schema MUST be `z.object(...)` so field-by-field coercion can drive\n * boolean string / number / array coercion (Astro pattern).\n */\n accept?: ActionAccept\n /**\n * Opt OUT of CSRF enforcement for this action. Default (omitted) keeps the\n * multi-header CSRF gate active. Set `false` for endpoints intentionally\n * callable without the `X-Theo-Action` header (e.g. public webhooks). The\n * runtime in `server/http/action-execute.ts` reads this flag.\n */\n csrf?: false\n handler: (ctx: { input: z.infer<TInput>; ctx: TCtx }) => unknown\n}\n\n/**\n * Define a typed server action.\n *\n * Identity function — provides type inference for action handlers. The\n * runtime that consumes the config (validation + invocation + serialization)\n * lives in `server/http/action-execute.ts`.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.2: the new\n * `accept?: 'form' | 'json'` field is the only contract change vs the\n * pre-G3 identity. Existing callsites (`defineAction({input, handler})`)\n * continue to compile — `accept` is opt-in.\n */\nexport function defineAction<TInput extends z.ZodType, TCtx = unknown>(\n config: ActionConfig<TInput, TCtx>,\n): ActionConfig<TInput, TCtx> {\n return config\n}\n","/**\n * M31 Phase 3 — `action()`, the fluent builder that replaces `defineAction({...})`.\n *\n * Pure type-state (mirrors `route-builder.ts`). `.input()` (required) sets the Zod schema whose\n * `z.infer<>` types the handler's `ctx.input`; `.handler()` (required) closes the chain. `.build()`\n * delegates to the internal {@link defineAction} (identity) — the action-execute path is UNCHANGED.\n *\n * export const createUser = action()\n * .input(z.object({ email: z.string().email() }))\n * .handler(({ input }) => createUser(input.email))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport { defineAction, type ActionConfig, type ActionAccept } from './define-action.js'\n\n/** Compile-error carrier: `.execute`/`.build()` reached before `.input()`. */\ninterface MissingInputError {\n readonly __theokitError: 'call .input(schema) before .handler(fn)'\n}\n/** Compile-error carrier: `.build()` before both `.input()` and `.handler()` are set. */\ninterface IncompleteActionError {\n readonly __theokitError: 'an action needs .input(schema) and .handler(fn) before .build()'\n}\n\n/** A required-but-unset field. Branded so no ordinary value satisfies it (tRPC UnsetMarker). */\ntype UnsetMarker = 'theokit.unset' & { readonly __brand: 'theokit.unset' }\n\n/**\n * The fluent action builder. `TInput` tracks the Zod schema (drives `ctx.input` inference);\n * `THandlerSet` gates `.build()`.\n */\nexport interface ActionBuilder<\n TInput extends z.ZodType | UnsetMarker = UnsetMarker,\n TCtx = unknown,\n THandlerSet extends boolean = false,\n> {\n /** Set the Zod input schema. Required — every action declares its input contract (zod-is-SSOT). */\n input<S extends z.ZodType>(schema: S): ActionBuilder<S, TCtx, THandlerSet>\n /** Wire-protocol accept mode (`'json'` default, `'form'` for FormData multipart). */\n accept(mode: ActionAccept): ActionBuilder<TInput, TCtx, THandlerSet>\n /** Opt out of CSRF enforcement for this action. */\n csrf(disabled: false): ActionBuilder<TInput, TCtx, THandlerSet>\n /**\n * Set the handler. COMPILE ERROR before `.input()` — the param type collapses to\n * {@link MissingInputError}. `ctx.input` is inferred via `z.infer<TInput>`.\n */\n handler(\n fn: TInput extends z.ZodType\n ? (ctx: { input: z.infer<TInput>; ctx: TCtx }) => unknown\n : MissingInputError,\n ): ActionBuilder<TInput, TCtx, true>\n /**\n * Resolve to the `ActionConfig` — the SAME value `defineAction({...})` returns. COMPILE ERROR when\n * `.input()` or `.handler()` was never called.\n */\n build(\n ...guard: THandlerSet extends true\n ? TInput extends z.ZodType\n ? []\n : [error: IncompleteActionError]\n : [error: IncompleteActionError]\n ): ActionConfig<TInput extends z.ZodType ? TInput : z.ZodType, TCtx>\n}\n\ntype AnyActionConfig = ActionConfig<z.ZodType>\n\ninterface ActionSpecAccumulator {\n input?: z.ZodType\n accept?: ActionAccept\n csrf?: false\n handler?: AnyActionConfig['handler']\n}\n\nfunction makeActionBuilder(spec: ActionSpecAccumulator): ActionBuilder {\n const runtime = {\n input: (schema: z.ZodType) => makeActionBuilder({ ...spec, input: schema }),\n accept: (mode: ActionAccept) => makeActionBuilder({ ...spec, accept: mode }),\n csrf: (disabled: false) => makeActionBuilder({ ...spec, csrf: disabled }),\n handler: (fn: AnyActionConfig['handler']) => makeActionBuilder({ ...spec, handler: fn }),\n build: (): AnyActionConfig => {\n // Fail-fast for untyped (JS) callers — the type-state guards make this unreachable from TS.\n if (spec.input === undefined) {\n throw new Error('action(): call .input(schema) before .build()')\n }\n if (spec.handler === undefined) {\n throw new Error('action(): call .handler(fn) before .build()')\n }\n const config: AnyActionConfig = {\n input: spec.input,\n handler: spec.handler,\n ...(spec.accept !== undefined ? { accept: spec.accept } : {}),\n ...(spec.csrf !== undefined ? { csrf: spec.csrf } : {}),\n }\n return defineAction(config)\n },\n }\n return runtime as unknown as ActionBuilder\n}\n\n/**\n * Start a fluent action definition. Chain `.input()` (required), optionally `.accept()` / `.csrf()`,\n * then `.handler()` (required) and `.build()` for the `ActionConfig`.\n */\nexport function action(): ActionBuilder {\n return makeActionBuilder({})\n}\n","import type { IncomingMessage } from 'node:http'\n\nexport interface WebSocketLike {\n send(data: string | Buffer): void\n close(code?: number, reason?: string): void\n}\n\nexport interface WebSocketHandler {\n onOpen?: (ws: WebSocketLike, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, data: string | Buffer) => void\n onClose?: (ws: WebSocketLike, code: number, reason: Buffer) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Define a WebSocket endpoint handler.\n * Identity function — provides type inference for WebSocket handlers.\n */\nexport function defineWebSocket(handler: WebSocketHandler): WebSocketHandler {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 3/3 — Web-Standards WebSocket endpoint handler.\n *\n * Mirror of `WebSocketHandler` for the Web `Request` shape. `onOpen`\n * receives `request: Request` instead of `req: IncomingMessage`. The\n * rest of the lifecycle (onMessage, onClose, onError) is shape-agnostic\n * (`WebSocketLike` is already Web-standards-compatible per the existing\n * design — `send(string | Buffer)` works on both Node `ws` and Web\n * `WebSocket` instances; CF Workers / Bun / Deno coerce as needed at\n * the adapter boundary).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F (closes Phase F).\n *\n * **Architectural note — WebSocket upgrade semantics differ across runtimes:**\n * - Node + `ws`: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * `req` is `IncomingMessage`. Use `WebSocketHandler`.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request). Use `WebSocketHandlerWeb`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Cross-runtime WebSocket endpoints ship BOTH `WebSocketHandler` +\n * `WebSocketHandlerWeb` exports; the runtime adapter picks the matching\n * one. This is the canonical Hono / Nitric pattern.\n */\nexport interface WebSocketHandlerWeb {\n onOpen?: (ws: WebSocketLike, request: Request) => void\n onMessage?: (ws: WebSocketLike, data: string | Uint8Array) => void\n onClose?: (ws: WebSocketLike, code: number, reason: string) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Web-Standards `defineWebSocket` sibling. Identity function — provides\n * type inference for Web WebSocket handlers.\n *\n * **Type difference note vs Node path:**\n * - `onMessage` data is `string | Uint8Array` instead of `string | Buffer`\n * (Web standards have no `Buffer`; Node's Buffer is a Uint8Array\n * subclass so the Node path's Buffer values flow through unchanged\n * when adapters wrap them).\n * - `onClose` reason is `string` instead of `Buffer` (Web `CloseEvent`\n * exposes the reason as a UTF-8 string natively).\n */\nexport function defineWebSocketWeb(handler: WebSocketHandlerWeb): WebSocketHandlerWeb {\n return handler\n}\n","/**\n * M31 Phase 3 — `websocket()`, the fluent builder that replaces `defineWebSocket({...})`.\n *\n * Lifecycle setters (`onOpen/onMessage/onClose/onError`), all optional; `.build()` delegates to the\n * internal {@link defineWebSocket} (identity) — the ws handler loading path is UNCHANGED.\n *\n * export default websocket()\n * .onOpen((ws) => ws.send('hi'))\n * .onMessage((ws, data) => ws.send(`echo:${data}`))\n * .build()\n */\nimport { defineWebSocket, type WebSocketHandler } from './define-websocket.js'\n\n/** The fluent WebSocket builder. Each lifecycle hook is optional; `.build()` returns the handler. */\nexport interface WebSocketBuilder {\n onOpen(fn: NonNullable<WebSocketHandler['onOpen']>): WebSocketBuilder\n onMessage(fn: NonNullable<WebSocketHandler['onMessage']>): WebSocketBuilder\n onClose(fn: NonNullable<WebSocketHandler['onClose']>): WebSocketBuilder\n onError(fn: NonNullable<WebSocketHandler['onError']>): WebSocketBuilder\n /** Resolve to the `WebSocketHandler` — the SAME value `defineWebSocket({...})` returns. */\n build(): WebSocketHandler\n}\n\nfunction makeWebSocketBuilder(spec: WebSocketHandler): WebSocketBuilder {\n const runtime: WebSocketBuilder = {\n onOpen: (fn) => makeWebSocketBuilder({ ...spec, onOpen: fn }),\n onMessage: (fn) => makeWebSocketBuilder({ ...spec, onMessage: fn }),\n onClose: (fn) => makeWebSocketBuilder({ ...spec, onClose: fn }),\n onError: (fn) => makeWebSocketBuilder({ ...spec, onError: fn }),\n build: () => defineWebSocket(spec),\n }\n return runtime\n}\n\n/** Start a fluent WebSocket definition. Chain any of the lifecycle hooks, then `.build()`. */\nexport function websocket(): WebSocketBuilder {\n return makeWebSocketBuilder({})\n}\n","export type MiddlewareHandler = (\n request: Request,\n next: (request: Request) => Promise<Response>,\n) => Response | Promise<Response>\n\n/**\n * Define a middleware handler.\n * Identity function — provides type annotation for middleware.\n */\nexport function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler {\n return handler\n}\n","/**\n * M31 Phase 3 — `middleware()`, the fluent builder that replaces `defineMiddleware(fn)`.\n *\n * A middleware IS a single function `(request, next) => Response`. The builder's `.handle()` sets it\n * (required); `.build()` delegates to the internal {@link defineMiddleware} (identity) and returns\n * the handler the runtime expects.\n *\n * export default middleware()\n * .handle(async (request, next) => {\n * const res = await next(request)\n * res.headers.set('x-mw', '1')\n * return res\n * })\n * .build()\n */\nimport { defineMiddleware, type MiddlewareHandler } from './define-middleware.js'\n\n/** Compile-error carrier: `.build()` called before `.handle()`. */\ninterface MissingHandleError {\n readonly __theokitError: 'middleware needs .handle(fn) before .build()'\n}\n\n/** The fluent middleware builder. `THandleSet` gates `.build()`. */\nexport interface MiddlewareBuilder<THandleSet extends boolean = false> {\n /** Set the `(request, next) => Response` handler. Required before `.build()`. */\n handle(fn: MiddlewareHandler): MiddlewareBuilder<true>\n /** Resolve to the `MiddlewareHandler`. COMPILE ERROR when `.handle()` was never called. */\n build(...guard: THandleSet extends true ? [] : [error: MissingHandleError]): MiddlewareHandler\n}\n\nfunction makeMiddlewareBuilder(fn: MiddlewareHandler | undefined): MiddlewareBuilder {\n const runtime = {\n handle: (handler: MiddlewareHandler) => makeMiddlewareBuilder(handler),\n build: (): MiddlewareHandler => {\n // Fail-fast for untyped (JS) callers — the type-state guard makes this unreachable from TS.\n if (fn === undefined) {\n throw new Error('middleware(): call .handle(fn) before .build()')\n }\n return defineMiddleware(fn)\n },\n }\n return runtime as unknown as MiddlewareBuilder\n}\n\n/** Start a fluent middleware definition. Chain `.handle()` (required), then `.build()`. */\nexport function middleware(): MiddlewareBuilder {\n return makeMiddlewareBuilder(undefined)\n}\n","import { z } from 'zod'\n\n/**\n * Item #4 — `defineAgentTool`\n *\n * Sugar over the `@theokit/sdk` `CustomTool` contract. Takes a Zod schema +\n * handler and produces a structurally-compatible `CustomTool` that\n * `Agent.create({ tools: [...] })` accepts.\n *\n * Uses Zod v4's native `z.toJSONSchema()` to convert the input schema to\n * JSON Schema for LLM providers.\n *\n * Handler error propagation:\n * `defineAgentTool` parses the input via the Zod schema BEFORE calling the\n * user handler. Invalid input throws a `ZodError`, which the SDK's tool-\n * dispatcher treats as a tool failure and surfaces to the model as a tool\n * error (the SDK owns the wire; ADR D3).\n */\n\n/**\n * Local mirror of the SDK's `CustomTool` interface. We don't `import type`\n * from `@theokit/sdk` because the SDK is an optional peer (consumers who\n * never call `defineAgentTool` shouldn't need it installed). The shape is\n * the wire contract; any structurally-matching object is accepted by\n * `Agent.create({ tools })`.\n *\n * @public\n */\nexport interface CustomTool {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n handler: (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ) => string | Promise<string>\n /** M18 — optional per-target formatters for the app's UI/transcript (ignored by the SDK wire). */\n transform?: ToolTransform\n}\n\n/**\n * M18 — per-target formatters. `display` shapes the rich handler result for the UI; `transcript`\n * shapes it for a saved transcript. Applied by {@link applyTransform}, never by the model wire.\n */\nexport interface ToolTransform<R = unknown> {\n display?: (result: R) => unknown\n transcript?: (result: R) => unknown\n}\n\n/**\n * Spec accepted by {@link defineAgentTool}. `inputSchema` is a Zod 3 schema\n * rooted in `z.object(...)`. The `handler` argument type is inferred via\n * `z.infer<T>`.\n *\n * @public\n */\nexport interface DefineAgentToolSpec<T extends z.ZodType, R = string> {\n /** Tool name surfaced to the LLM. Must match `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$`. */\n name: string\n /** Description surfaced to the LLM. Required — drives tool-selection accuracy. */\n description: string\n /** Zod schema describing the input. Must be `z.object(...)` at the root. */\n inputSchema: T\n /**\n * Handler invoked with the parsed input and, optionally, the run `ctx` (M7). `ctx.context`\n * is the object supplied once at the agent level (`defineAgent({ context })`) or per-run —\n * read it for shared config like `projectRoot` instead of baking it into the factory.\n * `ctx.signal` is the abort signal. Optional so existing one-arg handlers keep working.\n *\n * M18 — the handler may return RICH data `R` (not just a string) when `toModelOutput` is\n * provided to map it to the model-visible string.\n */\n handler: (\n input: z.infer<T>,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ) => R | Promise<R>\n /**\n * M18 — map the rich handler result `R` to the string the model sees. Required (in practice)\n * when `handler` returns a non-string; absent ⇒ the handler must return a string.\n */\n toModelOutput?: (result: R) => string\n /** M18 — per-target formatters (`display` / `transcript`) for the app, applied by {@link applyTransform}. */\n transform?: ToolTransform<R>\n}\n\nconst TOOL_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/\n\nfunction isZodObject(schema: z.ZodType): boolean {\n // Refinements (`.refine`), transforms (`.transform`), and defaults wrap the\n // underlying schema — walk the chain until we hit a ZodObject (or give up).\n // Supports both zod 4 (`instanceof z.ZodObject`, `def.type === 'object'`,\n // wrappers via `def.innerType` / pipe via `def.in`) and zod 3\n // (`_def.typeName === 'ZodObject'`, wrappers via `_def.schema`/`_def.innerType`).\n let current: unknown = schema\n for (let depth = 0; depth < 10; depth++) {\n if (current instanceof z.ZodObject) return true\n const z4 = (current as { def?: { type?: string; innerType?: unknown; in?: unknown } }).def\n if (z4?.type === 'object') return true\n const z3 = (current as { _def?: { typeName?: string; schema?: unknown; innerType?: unknown } })\n ._def\n if (z3?.typeName === 'ZodObject') return true\n const next = z4?.innerType ?? z4?.in ?? z3?.schema ?? z3?.innerType\n if (next !== undefined) {\n current = next\n continue\n }\n return false\n }\n return false\n}\n\n/**\n * Build a {@link CustomTool} from a Zod 3 schema + handler.\n *\n * Behavior:\n * - Validates `name` matches the LLM tool-name regex.\n * - Requires `inputSchema` to be a `ZodObject` (Anthropic + SDK contract).\n * - Warns (not throws) if `description` is empty — empty descriptions\n * degrade LLM tool selection.\n * - Converts the Zod schema to JSON Schema 7 inline (no `$ref`s — LLMs handle\n * inline schemas more reliably).\n * - Strips the top-level `$schema` field (Anthropic rejects schemas with\n * `$schema` at root in some provider modes).\n * - Wraps the handler to parse the input via the Zod schema BEFORE invoking\n * the user code — bad LLM-supplied input throws `ZodError`, which the SDK\n * converts to `tool_result(isError)`.\n *\n * @public\n */\nexport function defineAgentTool<T extends z.ZodType, R = string>(\n spec: DefineAgentToolSpec<T, R>,\n): CustomTool {\n if (!TOOL_NAME_REGEX.test(spec.name)) {\n throw new Error(\n `defineAgentTool: name must match ${TOOL_NAME_REGEX.source}. Got: ${JSON.stringify(spec.name)}`,\n )\n }\n if (!isZodObject(spec.inputSchema)) {\n throw new Error('defineAgentTool: inputSchema must be a ZodObject (z.object({...}))')\n }\n if (spec.description.length === 0) {\n console.warn(\n `defineAgentTool(${JSON.stringify(spec.name)}): empty description degrades LLM tool selection — provide a one-sentence summary.`,\n )\n }\n\n // Zod v4 native JSON Schema conversion — replaces zod-to-json-schema dep.\n // Strip $schema (Anthropic + some providers reject it).\n const { $schema: _$schema, ...inputSchema } = z.toJSONSchema(spec.inputSchema) as Record<\n string,\n unknown\n > & {\n $schema?: unknown\n }\n\n return {\n name: spec.name,\n description: spec.description,\n inputSchema,\n handler: async (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ): Promise<string> => {\n const parsed = spec.inputSchema.parse(input)\n // M7 — forward the run ctx so the handler can read `ctx.context` (e.g. projectRoot).\n const result = await spec.handler(parsed, ctx)\n // M18 — shape the (possibly rich) result into the model-visible string.\n if (spec.toModelOutput) return spec.toModelOutput(result)\n if (typeof result !== 'string') {\n throw new Error(\n `defineAgentTool(${JSON.stringify(spec.name)}): handler returned a non-string; provide toModelOutput to map it to a string for the model.`,\n )\n }\n return result\n },\n // M18 — carry the per-target formatters for the app (ignored by the SDK wire).\n ...(spec.transform !== undefined ? { transform: spec.transform as ToolTransform } : {}),\n }\n}\n\n/**\n * M18 — apply a tool's `transform` for a target (`display` / `transcript`). Returns the formatted\n * value, or the raw `result` when the tool declares no transform for that target.\n */\nexport function applyTransform(\n tool: CustomTool,\n result: unknown,\n target: 'display' | 'transcript',\n): unknown {\n const fn = tool.transform?.[target]\n return fn ? fn(result) : result\n}\n","/**\n * M31 Phase 1 — `tool()`, the fluent builder that replaces `defineAgentTool({...})`.\n *\n * Pure type-state (tRPC `UnsetMarker` technique, mirroring `agent-builder.ts`). The runtime is a\n * plain accumulator; `.build()` delegates to the internal {@link defineAgentTool}, so the emitted\n * `CustomTool` is byte-for-byte the legacy shape — the SDK/agent compile path is UNCHANGED\n * (identity-shape delegation, blueprint §2).\n *\n * PURE metadata (G2 / sdk-runtime.md): a tool describes a capability; it NEVER calls an LLM.\n *\n * tool('read')\n * .describe('Read a UTF-8 file')\n * .input(z.object({ path: z.string() }))\n * .execute(async ({ path }, ctx) => readFile(resolveInProject(ctx, path)))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport { defineAgentTool, type CustomTool, type ToolTransform } from './define-agent-tool.js'\n\n/** A required-but-unset builder field. Branded so no ordinary value satisfies it (tRPC UnsetMarker). */\ntype UnsetMarker = 'theokit.unset' & { readonly __brand: 'theokit.unset' }\n\n/** Compile-error carrier: `.execute()` called before `.input()`. */\ninterface MissingInputError {\n readonly __theokitError: 'call .input(schema) before .execute(handler)'\n}\n/** Compile-error carrier: `.build()` called before both `.input()` and `.execute()` are set. */\ninterface IncompleteToolError {\n readonly __theokitError: 'a tool needs .input(schema) and .execute(handler) before .build()'\n}\n\n/** The run context a tool handler receives (M7). */\ninterface ToolCtx {\n signal?: AbortSignal\n context?: unknown\n}\n\n/**\n * The fluent tool builder. Each method returns a NEW builder type with the relevant type parameter\n * advanced. `TInput` tracks the Zod schema (drives `execute` input inference); `R` tracks the\n * handler result; `THandlerSet` gates `.build()`.\n */\nexport interface ToolBuilder<\n TName extends string = string,\n TInput extends z.ZodType | UnsetMarker = UnsetMarker,\n R = string,\n THandlerSet extends boolean = false,\n> {\n /** Set the LLM-facing description. Optional; an empty description warns at build (LLM selection). */\n describe(description: string): ToolBuilder<TName, TInput, R, THandlerSet>\n /** Set the Zod input schema (must be `z.object(...)` at the root). Required before `.execute()`. */\n input<S extends z.ZodType>(schema: S): ToolBuilder<TName, S, R, THandlerSet>\n /**\n * Set the handler. COMPILE ERROR when `.input()` was not called first — the parameter type\n * collapses to {@link MissingInputError}. The `input` argument is inferred via `z.infer<TInput>`.\n */\n execute<R2>(\n handler: TInput extends z.ZodType\n ? (input: z.infer<TInput>, ctx?: ToolCtx) => R2 | Promise<R2>\n : MissingInputError,\n ): ToolBuilder<TName, TInput, R2, true>\n /** M18 — map a rich handler result to the model-visible string. */\n toModelOutput(fn: (result: R) => string): ToolBuilder<TName, TInput, R, THandlerSet>\n /** M18 — per-target formatters (`display` / `transcript`) for the app UI/transcript. */\n transform(t: ToolTransform<R>): ToolBuilder<TName, TInput, R, THandlerSet>\n /**\n * Resolve to the `CustomTool` — the SAME value `defineAgentTool({...})` returns. COMPILE ERROR\n * when `.input()` or `.execute()` was never called.\n */\n build(\n ...guard: THandlerSet extends true\n ? TInput extends z.ZodType\n ? []\n : [error: IncompleteToolError]\n : [error: IncompleteToolError]\n ): CustomTool\n}\n\ninterface ToolSpecAccumulator {\n name: string\n description?: string\n inputSchema?: z.ZodType\n handler?: (input: unknown, ctx?: ToolCtx) => unknown\n toModelOutput?: (result: unknown) => string\n transform?: ToolTransform\n}\n\n/**\n * Build the runtime accumulator. The public method signatures carry the type-state generics + the\n * compile-time guards; the runtime cannot track generics, so the object is bridged to the typed\n * interface once here (the single, documented type-state impl seam — same technique as agent-builder).\n */\nfunction makeToolBuilder(spec: ToolSpecAccumulator): ToolBuilder {\n const runtime = {\n describe: (description: string) => makeToolBuilder({ ...spec, description }),\n input: (schema: z.ZodType) => makeToolBuilder({ ...spec, inputSchema: schema }),\n execute: (handler: (input: unknown, ctx?: ToolCtx) => unknown) =>\n makeToolBuilder({ ...spec, handler }),\n toModelOutput: (fn: (result: unknown) => string) =>\n makeToolBuilder({ ...spec, toModelOutput: fn }),\n transform: (t: ToolTransform) => makeToolBuilder({ ...spec, transform: t }),\n build: (): CustomTool => {\n // Fail-fast: the type-state guards make these unreachable from typed callers, but an untyped\n // (JS) caller could skip them — surface a clear error instead of a confusing downstream one.\n if (spec.inputSchema === undefined) {\n throw new Error(`tool(${JSON.stringify(spec.name)}): call .input(schema) before .build()`)\n }\n if (spec.handler === undefined) {\n throw new Error(\n `tool(${JSON.stringify(spec.name)}): call .execute(handler) before .build()`,\n )\n }\n return defineAgentTool({\n name: spec.name,\n description: spec.description ?? '',\n inputSchema: spec.inputSchema,\n handler: spec.handler,\n ...(spec.toModelOutput !== undefined ? { toModelOutput: spec.toModelOutput } : {}),\n ...(spec.transform !== undefined ? { transform: spec.transform } : {}),\n })\n },\n }\n return runtime as unknown as ToolBuilder\n}\n\n/**\n * Start a fluent tool definition. Chain `.input()` + `.execute()` (both required), optionally\n * `.describe()` / `.toModelOutput()` / `.transform()`, then `.build()` for the `CustomTool`.\n */\nexport function tool<TName extends string>(name: TName): ToolBuilder<TName> {\n return makeToolBuilder({ name })\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nexport interface PluginContext {\n request: IncomingMessage\n response: ServerResponse\n ctx: Record<string, unknown>\n requestId: string\n}\n\nexport interface PluginErrorContext extends PluginContext {\n error: unknown\n}\n\nexport interface RunHookOptions {\n inErrorPath?: boolean\n}\n\nexport interface HookResult {\n shortCircuited: boolean\n}\n\nexport type OnRequestHook = (ctx: PluginContext) => void | Promise<void>\nexport type PreHandlerHook = (ctx: PluginContext) => void | Promise<void>\nexport type OnResponseHook = (ctx: PluginContext) => void | Promise<void>\nexport type OnErrorHook = (ctx: PluginErrorContext) => void | Promise<void>\n\nexport type HookName = 'onRequest' | 'preHandler' | 'onResponse' | 'onError'\n\nexport type HookByName<K extends HookName> = K extends 'onError'\n ? OnErrorHook\n : K extends 'onRequest'\n ? OnRequestHook\n : K extends 'preHandler'\n ? PreHandlerHook\n : K extends 'onResponse'\n ? OnResponseHook\n : never\n\nexport interface TheoApp {\n addHook<K extends HookName>(name: K, fn: HookByName<K>): void\n // `T` lets plugin authors document the per-key shape of decorations.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the value type for plugin authors\n decorateRequest<T>(key: string, value: T): void\n}\n\nexport interface TheoPlugin {\n name: string\n register(app: TheoApp): void | Promise<void>\n}\n\n/**\n * Identity function for plugin authors. Provides auto-completion + type\n * inference at the call site (TanStack/Vite/Astro pattern). Pure runtime\n * no-op — returns the input unchanged.\n *\n * @example\n * import { definePlugin } from 'theokit/server'\n * export default definePlugin({\n * name: 'my-plugin',\n * register(app) {\n * app.addHook('onRequest', (req) => { ... })\n * },\n * })\n *\n * Equivalent to `const p: TheoPlugin = {...}` but more ergonomic. See\n * ADR-0008 (D1 + D6) for the rationale.\n */\nexport function definePlugin(plugin: TheoPlugin): TheoPlugin {\n return plugin\n}\n\n// ===== T5a.2 Phase F slice 1/3 — Web-Standards plugin context types =====\n//\n// Mirror of the IncomingMessage/ServerResponse-shaped `PluginContext` for\n// the Web `Request`/`Headers` shape. Per `docs/plans/t5a2-incoming-message-\n// to-request-shape-refactor-plan.md` v1.0 § Phase F.\n//\n// **Key difference vs IncomingMessage path:** the Web path has no\n// `ServerResponse` to mutate. Plugins instead get a `responseHeaders: Headers`\n// instance they can append to (e.g., add Set-Cookie, CORS headers) and the\n// runtime composes the final `Response` after the hook chain runs. The\n// `response` object (if any) is the in-flight Response constructed by the\n// handler — present only during `onResponse` / `onError` hooks AFTER the\n// handler returned, NOT during `onRequest` / `preHandler` (which fire BEFORE\n// the handler runs).\n//\n// This split mirrors Hono's `c.res` + Fastify's `reply.headers` semantics\n// — plugins mutate headers freely; the body is the handler's responsibility.\n\n/**\n * Web-Standards plugin context. Available during all 4 hook lifecycle\n * stages (onRequest, preHandler, onResponse, onError).\n *\n * - `request` — the incoming Web Request (read-only at the runtime level;\n * plugins can call `request.headers.get()`, `request.clone()`, etc.).\n * - `responseHeaders` — a mutable `Headers` instance the runtime threads\n * through the hook chain. Plugins append (e.g., CORS, Set-Cookie); the\n * final Response composes these.\n * - `response` — set to the handler's Response AFTER the handler returns.\n * Available during `onResponse` / `onError`. `undefined` during\n * `onRequest` / `preHandler` (which fire before the handler runs).\n * - `ctx` / `requestId` — same semantics as the IncomingMessage path.\n */\nexport interface WebPluginContext {\n request: Request\n responseHeaders: Headers\n response?: Response\n ctx: Record<string, unknown>\n requestId: string\n}\n\nexport interface WebPluginErrorContext extends WebPluginContext {\n error: unknown\n}\n\nexport type WebOnRequestHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebPreHandlerHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebOnResponseHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebOnErrorHook = (ctx: WebPluginErrorContext) => void | Promise<void>\n\nexport type WebHookByName<K extends HookName> = K extends 'onError'\n ? WebOnErrorHook\n : K extends 'onRequest'\n ? WebOnRequestHook\n : K extends 'preHandler'\n ? WebPreHandlerHook\n : K extends 'onResponse'\n ? WebOnResponseHook\n : never\n\n/**\n * Web-Standards `TheoApp` facade. Same `addHook` + `decorateRequest`\n * surface as the IncomingMessage path; only the hook function signatures\n * differ (they receive `WebPluginContext` instead of `PluginContext`).\n *\n * Plugin authors who target both shapes can branch on the context type\n * via a type guard (`'responseHeaders' in ctx`) OR ship two separate\n * `register()` exports — one for each runtime adapter. Most plugins\n * register hooks at the IncomingMessage path today (legacy); future\n * Web-native plugins will register against `WebTheoApp`.\n */\nexport interface WebTheoApp {\n addHook<K extends HookName>(name: K, fn: WebHookByName<K>): void\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the value type for plugin authors\n decorateRequest<T>(key: string, value: T): void\n}\n\n/**\n * Web-Standards plugin shape. Identical to `TheoPlugin` except the\n * `register(app)` argument is `WebTheoApp` instead of `TheoApp`.\n *\n * Cross-runtime plugins ship BOTH `TheoPlugin` + `WebTheoPlugin` exports;\n * the adapter (Node, CF Workers, Bun, Deno) picks the matching one based\n * on which runtime executes the plugin chain. This is the canonical\n * Hono/Nitro pattern.\n */\nexport interface WebTheoPlugin {\n name: string\n register(app: WebTheoApp): void | Promise<void>\n}\n\n/**\n * Identity function for Web plugin authors — same auto-completion +\n * type-inference DX as `definePlugin`, but for the Web-shaped `WebTheoApp`.\n */\nexport function defineWebPlugin(plugin: WebTheoPlugin): WebTheoPlugin {\n return plugin\n}\n","/**\n * M31 Phase 3 — `plugin()`, the fluent builder that replaces `definePlugin({...})`.\n *\n * Collects lifecycle hooks + request decorations and SYNTHESIZES the `register(app)` function, so\n * authors never write the imperative `register` body. `.build()` returns a `TheoPlugin` the plugin\n * runner consumes UNCHANGED.\n *\n * export default plugin('request-id')\n * .onRequest((ctx) => { ctx.ctx.requestId = crypto.randomUUID() })\n * .onResponse((ctx) => { ctx.response.setHeader('x-request-id', String(ctx.ctx.requestId)) })\n * .build()\n */\nimport {\n definePlugin,\n type TheoPlugin,\n type TheoApp,\n type OnRequestHook,\n type PreHandlerHook,\n type OnResponseHook,\n type OnErrorHook,\n} from '../plugin-types.js'\n\n/** The fluent plugin builder. `name` is set at entry; every hook is optional and may repeat. */\nexport interface PluginBuilder {\n /** Register an `onRequest` hook (runs before the CSRF gate). May be called multiple times. */\n onRequest(fn: OnRequestHook): PluginBuilder\n /** Register a `preHandler` hook (after CSRF, before the route handler). */\n preHandler(fn: PreHandlerHook): PluginBuilder\n /** Register an `onResponse` hook (after the handler returns). */\n onResponse(fn: OnResponseHook): PluginBuilder\n /** Register an `onError` hook (error path). */\n onError(fn: OnErrorHook): PluginBuilder\n /** Decorate every request with a key/value pair (available on `ctx.ctx[key]`). */\n decorateRequest<T>(key: string, value: T): PluginBuilder\n /** Resolve to the `TheoPlugin` — a synthesized `{ name, register }` the runner consumes. */\n build(): TheoPlugin\n}\n\ninterface PluginSpecAccumulator {\n name: string\n onRequest: OnRequestHook[]\n preHandler: PreHandlerHook[]\n onResponse: OnResponseHook[]\n onError: OnErrorHook[]\n decorations: { key: string; value: unknown }[]\n}\n\nfunction makePluginBuilder(spec: PluginSpecAccumulator): PluginBuilder {\n const runtime: PluginBuilder = {\n onRequest: (fn) => makePluginBuilder({ ...spec, onRequest: [...spec.onRequest, fn] }),\n preHandler: (fn) => makePluginBuilder({ ...spec, preHandler: [...spec.preHandler, fn] }),\n onResponse: (fn) => makePluginBuilder({ ...spec, onResponse: [...spec.onResponse, fn] }),\n onError: (fn) => makePluginBuilder({ ...spec, onError: [...spec.onError, fn] }),\n decorateRequest: (key, value) =>\n makePluginBuilder({ ...spec, decorations: [...spec.decorations, { key, value }] }),\n build: () =>\n definePlugin({\n name: spec.name,\n register(app: TheoApp): void {\n for (const fn of spec.onRequest) app.addHook('onRequest', fn)\n for (const fn of spec.preHandler) app.addHook('preHandler', fn)\n for (const fn of spec.onResponse) app.addHook('onResponse', fn)\n for (const fn of spec.onError) app.addHook('onError', fn)\n for (const d of spec.decorations) app.decorateRequest(d.key, d.value)\n },\n }),\n }\n return runtime\n}\n\n/** Start a fluent plugin definition. `name` is required; chain hooks/decorations, then `.build()`. */\nexport function plugin(name: string): PluginBuilder {\n return makePluginBuilder({\n name,\n onRequest: [],\n preHandler: [],\n onResponse: [],\n onError: [],\n decorations: [],\n })\n}\n","import type { UIMessageChunk } from 'ai'\n\n/**\n * M0 (theokit-ai-first) — serialize a stream of ai-sdk `UIMessageChunk`s into a\n * Web-Standards `Response` on the UIMessageStream wire so `@ai-sdk/react`'s\n * `useChat` consumes it WITHOUT a custom adapter.\n *\n * Wire contract (must match ai-sdk's consumer transport exactly):\n * - `content-type: text/event-stream`\n * - `x-vercel-ai-ui-message-stream: v1` — the version marker `useChat` checks\n * - each chunk framed as `data: ${JSON.stringify(chunk)}\\n\\n`\n * - a terminal `data: [DONE]\\n\\n` after the last chunk (ignored by the parser)\n *\n * Web Standards only — `Response` + `ReadableStream` (G8, no node:http). The\n * headers commit before the stream starts.\n *\n * Fail-clear (error-handling.md): if the source iterable throws mid-stream, the\n * `[DONE]` terminal is still flushed and the stream is closed — never left\n * hanging. (The translator upstream already closes gracefully; this is defense\n * in depth for any other chunk source.)\n */\nconst UI_MESSAGE_STREAM_HEADERS = {\n 'content-type': 'text/event-stream',\n 'x-vercel-ai-ui-message-stream': 'v1',\n} as const\n\nconst DONE_FRAME = 'data: [DONE]\\n\\n'\n\nfunction encode(text: string): Uint8Array {\n return new TextEncoder().encode(text)\n}\n\nexport function uiMessageStreamResponse(chunks: AsyncIterable<UIMessageChunk>): Response {\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n try {\n for await (const chunk of chunks) {\n controller.enqueue(encode(`data: ${JSON.stringify(chunk)}\\n\\n`))\n }\n } catch {\n // The source iterable aborted mid-stream. The upstream translator owns\n // error semantics (it surfaces failures as chunks + closes gracefully);\n // this transport's sole guarantee is a terminated stream — fall through\n // to the DONE terminal rather than re-throw and error an open stream.\n } finally {\n controller.enqueue(encode(DONE_FRAME))\n controller.close()\n }\n },\n })\n return new Response(stream, { headers: UI_MESSAGE_STREAM_HEADERS })\n}\n","import type { IncomingMessage } from 'node:http'\n\nimport type { WebSocketLike } from './define-websocket.js'\n\nexport interface ChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Define a channel handler for WebSocket rooms.\n * Identity function — provides type inference for channel handlers.\n */\nexport function defineChannel<TMessage = unknown>(\n handler: ChannelHandler<TMessage>,\n): ChannelHandler<TMessage> {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 2/3 — Web-Standards channel handler.\n *\n * Mirror of `ChannelHandler<TMessage>` for the Web `Request` shape.\n * `onSubscribe` receives `request: Request` instead of `req: IncomingMessage`\n * — the rest of the surface (onMessage, onUnsubscribe) is shape-agnostic\n * (WebSocketLike is already Web-standards-compatible per `define-websocket.ts`).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F.\n *\n * **Architectural note:** WebSocket upgrade semantics differ across\n * runtimes:\n * - Node: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * hands you `req: IncomingMessage` at the upgrade handshake.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request) — hands you `request: Request`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Channel handlers targeting CF/Bun/Deno use `WebChannelHandler`; legacy\n * Node consumers stay on `ChannelHandler`. Cross-runtime channels ship\n * both shapes.\n */\nexport interface WebChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, request: Request) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Web-Standards `defineChannel` sibling. Identity function — provides\n * type inference for Web channel handlers.\n */\nexport function defineWebChannel<TMessage = unknown>(\n handler: WebChannelHandler<TMessage>,\n): WebChannelHandler<TMessage> {\n return handler\n}\n"],"mappings":";AAaO,SAAS,YAOd,QACsD;AACtD,SAAO;AACT;;;ACuEA,SAAS,iBAAiB,MAA0C;AAClE,QAAM,UAAU;AAAA,IACd,OAAO,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,OAAO,OAAO,CAAC;AAAA,IACzE,MAAM,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,MAAM,OAAO,CAAC;AAAA,IACvE,QAAQ,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,QAAQ,OAAO,CAAC;AAAA,IAC3E,UAAU,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,UAAU,OAAO,CAAC;AAAA,IAC/E,QAAQ,CAAC,SAAiB,iBAAiB,EAAE,GAAG,MAAM,QAAQ,KAAK,CAAC;AAAA,IACpE,MAAM,CAAC,aAAoB,iBAAiB,EAAE,GAAG,MAAM,MAAM,SAAS,CAAC;AAAA,IACvE,SAAS,CAAC,OAAkC,iBAAiB,EAAE,GAAG,MAAM,SAAS,GAAG,CAAC;AAAA,IACrF,OAAO,MAAsB;AAE3B,UAAI,KAAK,YAAY,QAAW;AAC9B,cAAM,IAAI,MAAM,4CAA4C;AAAA,MAC9D;AACA,YAAM,SAAyB;AAAA,QAC7B,GAAI,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,QACxD,G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AAA,EAChB,CAAC;AACH;;;AC3DA,IAAM,4BAA4B;AAAA,EAChC,gBAAgB;AAAA,EAChB,iCAAiC;AACnC;AAEA,IAAM,aAAa;AAEnB,SAAS,OAAO,MAA0B;AACxC,SAAO,IAAI,YAAY,EAAE,OAAO,IAAI;AACtC;AAEO,SAAS,wBAAwB,QAAiD;AACvF,QAAM,SAAS,IAAI,eAA2B;AAAA,IAC5C,MAAM,MAAM,YAAY;AACtB,UAAI;AACF,yBAAiB,SAAS,QAAQ;AAChC,qBAAW,QAAQ,OAAO,SAAS,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA,CAAM,CAAC;AAAA,QACjE;AAAA,MACF,QAAQ;AAAA,MAKR,UAAE;AACA,mBAAW,QAAQ,OAAO,UAAU,CAAC;AACrC,mBAAW,MAAM;AAAA,MACnB;AAAA,IACF;AAAA,EACF,CAAC;AACD,SAAO,IAAI,SAAS,QAAQ,EAAE,SAAS,0BAA0B,CAAC;AACpE;;;ACrCO,SAAS,cACd,SAC0B;AAC1B,SAAO;AACT;AAoCO,SAAS,iBACd,SAC6B;AAC7B,SAAO;AACT;","names":["tool","plugin"]}
|
|
@@ -44,9 +44,6 @@ import {
|
|
|
44
44
|
import {
|
|
45
45
|
importUserModule
|
|
46
46
|
} from "./chunk-7MQOHNHE.js";
|
|
47
|
-
import {
|
|
48
|
-
uiMessageStreamResponse
|
|
49
|
-
} from "./chunk-JZHT3LW7.js";
|
|
50
47
|
import {
|
|
51
48
|
BATCH_PATH,
|
|
52
49
|
TRACE_HEADER,
|
|
@@ -1163,6 +1160,124 @@ import {
|
|
|
1163
1160
|
resolveEnabledSkills,
|
|
1164
1161
|
streamAgentUIMessages
|
|
1165
1162
|
} from "@theokit/agents";
|
|
1163
|
+
|
|
1164
|
+
// src/server/agent/durable-ui-message-stream-response.ts
|
|
1165
|
+
var SSE_BASE_HEADERS = {
|
|
1166
|
+
"content-type": "text/event-stream",
|
|
1167
|
+
"x-vercel-ai-ui-message-stream": "v1"
|
|
1168
|
+
};
|
|
1169
|
+
var RUN_ID_HEADER = "x-theokit-run-id";
|
|
1170
|
+
var SSE_DONE_FRAME = "data: [DONE]\n\n";
|
|
1171
|
+
function formatSseFrame(seq, data) {
|
|
1172
|
+
return `id: ${seq}
|
|
1173
|
+
data: ${data}
|
|
1174
|
+
|
|
1175
|
+
`;
|
|
1176
|
+
}
|
|
1177
|
+
function encodeSse(text) {
|
|
1178
|
+
return new TextEncoder().encode(text);
|
|
1179
|
+
}
|
|
1180
|
+
function durableUiMessageStreamResponse(chunks, deps) {
|
|
1181
|
+
const { runId, cache } = deps;
|
|
1182
|
+
const stream = new ReadableStream({
|
|
1183
|
+
async start(controller) {
|
|
1184
|
+
try {
|
|
1185
|
+
for await (const chunk of chunks) {
|
|
1186
|
+
const data = JSON.stringify(chunk);
|
|
1187
|
+
const seq = cache.append(runId, data);
|
|
1188
|
+
controller.enqueue(encodeSse(formatSseFrame(seq, data)));
|
|
1189
|
+
}
|
|
1190
|
+
} catch {
|
|
1191
|
+
} finally {
|
|
1192
|
+
cache.end(runId);
|
|
1193
|
+
controller.enqueue(encodeSse(SSE_DONE_FRAME));
|
|
1194
|
+
controller.close();
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
});
|
|
1198
|
+
return new Response(stream, {
|
|
1199
|
+
headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId }
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// src/server/agent/run-event-cache.ts
|
|
1204
|
+
var DEFAULT_EVICT_AFTER_MS = 5 * 6e4;
|
|
1205
|
+
var NOOP_UNSUBSCRIBE = () => {
|
|
1206
|
+
};
|
|
1207
|
+
function createInMemoryRunEventCache(opts = {}) {
|
|
1208
|
+
const evictAfterMs = opts.evictAfterMs ?? DEFAULT_EVICT_AFTER_MS;
|
|
1209
|
+
const runs = /* @__PURE__ */ new Map();
|
|
1210
|
+
function getOrCreate(runId) {
|
|
1211
|
+
let buf = runs.get(runId);
|
|
1212
|
+
if (buf === void 0) {
|
|
1213
|
+
buf = { frames: [], ended: false, listeners: /* @__PURE__ */ new Set() };
|
|
1214
|
+
runs.set(runId, buf);
|
|
1215
|
+
}
|
|
1216
|
+
return buf;
|
|
1217
|
+
}
|
|
1218
|
+
return {
|
|
1219
|
+
append(runId, data) {
|
|
1220
|
+
const buf = getOrCreate(runId);
|
|
1221
|
+
const seq = buf.frames.length;
|
|
1222
|
+
const frame = { seq, data };
|
|
1223
|
+
buf.frames.push(frame);
|
|
1224
|
+
for (const l of buf.listeners) {
|
|
1225
|
+
try {
|
|
1226
|
+
l.onFrame(frame);
|
|
1227
|
+
} catch {
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
return seq;
|
|
1231
|
+
},
|
|
1232
|
+
has(runId) {
|
|
1233
|
+
return runs.has(runId);
|
|
1234
|
+
},
|
|
1235
|
+
end(runId) {
|
|
1236
|
+
const buf = runs.get(runId);
|
|
1237
|
+
if (buf === void 0 || buf.ended) return;
|
|
1238
|
+
buf.ended = true;
|
|
1239
|
+
for (const l of buf.listeners) {
|
|
1240
|
+
try {
|
|
1241
|
+
l.onEnd();
|
|
1242
|
+
} catch {
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
buf.listeners.clear();
|
|
1246
|
+
buf.evictTimer = setTimeout(() => runs.delete(runId), evictAfterMs);
|
|
1247
|
+
buf.evictTimer.unref();
|
|
1248
|
+
},
|
|
1249
|
+
attach(runId, afterSeq, onFrame, onEnd) {
|
|
1250
|
+
const buf = runs.get(runId);
|
|
1251
|
+
if (buf === void 0) {
|
|
1252
|
+
return { known: false, replay: [], ended: false, unsubscribe: NOOP_UNSUBSCRIBE };
|
|
1253
|
+
}
|
|
1254
|
+
const replay = buf.frames.filter((f) => f.seq > afterSeq);
|
|
1255
|
+
if (buf.ended) {
|
|
1256
|
+
return { known: true, replay, ended: true, unsubscribe: NOOP_UNSUBSCRIBE };
|
|
1257
|
+
}
|
|
1258
|
+
const listener = { onFrame, onEnd };
|
|
1259
|
+
buf.listeners.add(listener);
|
|
1260
|
+
return {
|
|
1261
|
+
known: true,
|
|
1262
|
+
replay,
|
|
1263
|
+
ended: false,
|
|
1264
|
+
unsubscribe: () => {
|
|
1265
|
+
buf.listeners.delete(listener);
|
|
1266
|
+
}
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
var serverCache;
|
|
1272
|
+
function getRunEventCache() {
|
|
1273
|
+
serverCache ??= createInMemoryRunEventCache();
|
|
1274
|
+
return serverCache;
|
|
1275
|
+
}
|
|
1276
|
+
function mintRunId() {
|
|
1277
|
+
return `run-${crypto.randomUUID()}`;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// src/server/agent/mount-agent.ts
|
|
1166
1281
|
function partText(part) {
|
|
1167
1282
|
if (typeof part !== "object" || part === null) return "";
|
|
1168
1283
|
const p = part;
|
|
@@ -1226,8 +1341,10 @@ async function mountAgent(mod, request, apiKey, source = "agent module", csrfMod
|
|
|
1226
1341
|
...opts.payloadSchema !== void 0 ? { payloadSchema: opts.payloadSchema } : {}
|
|
1227
1342
|
})
|
|
1228
1343
|
} : void 0;
|
|
1229
|
-
|
|
1230
|
-
|
|
1344
|
+
const runId = mintRunId();
|
|
1345
|
+
return durableUiMessageStreamResponse(
|
|
1346
|
+
streamAgentUIMessages(compiled, apiKey, { ...input, hitl, signal: request.signal }),
|
|
1347
|
+
{ runId, cache: getRunEventCache() }
|
|
1231
1348
|
);
|
|
1232
1349
|
}
|
|
1233
1350
|
|
|
@@ -1271,6 +1388,77 @@ function resolveProvider() {
|
|
|
1271
1388
|
);
|
|
1272
1389
|
}
|
|
1273
1390
|
|
|
1391
|
+
// src/server/agent/handle-agent-run-reconnect.ts
|
|
1392
|
+
var RUN_STREAM_PATH = /^\/api\/agents\/([^/]+)\/runs\/([^/]+)\/stream$/;
|
|
1393
|
+
function isAgentRunStreamPath(urlPath) {
|
|
1394
|
+
const m = RUN_STREAM_PATH.exec(urlPath);
|
|
1395
|
+
return m ? { name: decodeURIComponent(m[1]), runId: decodeURIComponent(m[2]) } : null;
|
|
1396
|
+
}
|
|
1397
|
+
function parseLastEventId(raw) {
|
|
1398
|
+
if (raw === null) return -1;
|
|
1399
|
+
const n = Number.parseInt(raw, 10);
|
|
1400
|
+
return Number.isInteger(n) && n >= 0 ? n : -1;
|
|
1401
|
+
}
|
|
1402
|
+
function handleAgentRunReconnect(runId, request, cache) {
|
|
1403
|
+
if (!cache.has(runId)) {
|
|
1404
|
+
return new Response(
|
|
1405
|
+
JSON.stringify({ error: { code: "RUN_NOT_FOUND", message: `Unknown run '${runId}'.` } }),
|
|
1406
|
+
{
|
|
1407
|
+
status: 404,
|
|
1408
|
+
headers: { "content-type": "application/json" }
|
|
1409
|
+
}
|
|
1410
|
+
);
|
|
1411
|
+
}
|
|
1412
|
+
const afterSeq = parseLastEventId(request.headers.get("last-event-id"));
|
|
1413
|
+
const stream = new ReadableStream({
|
|
1414
|
+
start(controller) {
|
|
1415
|
+
let closed = false;
|
|
1416
|
+
const safeEnqueue = (text) => {
|
|
1417
|
+
if (closed) return;
|
|
1418
|
+
try {
|
|
1419
|
+
controller.enqueue(encodeSse(text));
|
|
1420
|
+
} catch {
|
|
1421
|
+
}
|
|
1422
|
+
};
|
|
1423
|
+
const close = () => {
|
|
1424
|
+
if (closed) return;
|
|
1425
|
+
safeEnqueue(SSE_DONE_FRAME);
|
|
1426
|
+
closed = true;
|
|
1427
|
+
try {
|
|
1428
|
+
controller.close();
|
|
1429
|
+
} catch {
|
|
1430
|
+
}
|
|
1431
|
+
};
|
|
1432
|
+
const res = cache.attach(
|
|
1433
|
+
runId,
|
|
1434
|
+
afterSeq,
|
|
1435
|
+
(frame) => {
|
|
1436
|
+
safeEnqueue(formatSseFrame(frame.seq, frame.data));
|
|
1437
|
+
},
|
|
1438
|
+
() => {
|
|
1439
|
+
close();
|
|
1440
|
+
}
|
|
1441
|
+
);
|
|
1442
|
+
if (!res.known) {
|
|
1443
|
+
close();
|
|
1444
|
+
return;
|
|
1445
|
+
}
|
|
1446
|
+
for (const frame of res.replay) {
|
|
1447
|
+
safeEnqueue(formatSseFrame(frame.seq, frame.data));
|
|
1448
|
+
}
|
|
1449
|
+
if (res.ended) {
|
|
1450
|
+
close();
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
request.signal.addEventListener("abort", () => {
|
|
1454
|
+
res.unsubscribe();
|
|
1455
|
+
close();
|
|
1456
|
+
});
|
|
1457
|
+
}
|
|
1458
|
+
});
|
|
1459
|
+
return new Response(stream, { headers: { ...SSE_BASE_HEADERS, [RUN_ID_HEADER]: runId } });
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1274
1462
|
// src/server/agent/serve-aux-routes.ts
|
|
1275
1463
|
function jsonError3(status, code, message) {
|
|
1276
1464
|
return new Response(JSON.stringify({ error: { code, message } }), {
|
|
@@ -1292,6 +1480,12 @@ async function serveAgentAuxRoute(request, urlPath, deps) {
|
|
|
1292
1480
|
if (method !== "GET") return null;
|
|
1293
1481
|
return handleListApprovals(getApprovalRegistry());
|
|
1294
1482
|
}
|
|
1483
|
+
const runStream = isAgentRunStreamPath(urlPath);
|
|
1484
|
+
if (runStream !== null) {
|
|
1485
|
+
if (method !== "GET") return null;
|
|
1486
|
+
if (!deps.agents.some((a) => a.name === runStream.name)) return null;
|
|
1487
|
+
return handleAgentRunReconnect(runStream.runId, request, getRunEventCache());
|
|
1488
|
+
}
|
|
1295
1489
|
const mcpName = isMcpPath(urlPath);
|
|
1296
1490
|
if (mcpName !== null) {
|
|
1297
1491
|
return serveMcpRoute(request, method, mcpName, deps);
|
|
@@ -3097,4 +3291,4 @@ export {
|
|
|
3097
3291
|
theoPluginAsync,
|
|
3098
3292
|
theoPlugin
|
|
3099
3293
|
};
|
|
3100
|
-
//# sourceMappingURL=chunk-
|
|
3294
|
+
//# sourceMappingURL=chunk-FARW5PH6.js.map
|