theokit 0.9.14 → 0.10.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.
Files changed (44) hide show
  1. package/dist/{actions-virtual-module-TESQ2T4F.js → actions-virtual-module-PNPRCEOS.js} +2 -2
  2. package/dist/{actions-virtual-module-WNA77RHT.js → actions-virtual-module-SQDY3V5X.js} +4 -4
  3. package/dist/{app-typed-client-AJ65YXJM.js → app-typed-client-5GYEOYP3.js} +2 -2
  4. package/dist/{app-typed-client-XGCP563T.js → app-typed-client-QG7BVZYW.js} +4 -4
  5. package/dist/{build-B7B5Q7TV.js → build-LVN3KIE3.js} +2 -2
  6. package/dist/{chunk-4EL6OX3P.js → chunk-6XUR4ZSA.js} +2 -1
  7. package/dist/chunk-6XUR4ZSA.js.map +1 -0
  8. package/dist/{chunk-7BJ6YLKV.js → chunk-7CBRKNQA.js} +4 -4
  9. package/dist/{chunk-AUNPGO2V.js → chunk-BYS3OYZV.js} +5 -5
  10. package/dist/{chunk-BLT7PPII.js → chunk-GFMQJHXX.js} +16 -3
  11. package/dist/chunk-GFMQJHXX.js.map +1 -0
  12. package/dist/{chunk-WS67ONGI.js → chunk-HGZL5EOI.js} +2 -1
  13. package/dist/{chunk-HTNVOG34.js → chunk-NAZ4E2GT.js} +2 -2
  14. package/dist/{chunk-BB4ISKOB.js → chunk-TGTNRUH3.js} +16 -2
  15. package/dist/chunk-TGTNRUH3.js.map +1 -0
  16. package/dist/cli/index.js +3 -3
  17. package/dist/{dev-KHBWZUY3.js → dev-HFOVZWYL.js} +5 -5
  18. package/dist/index.js +2 -2
  19. package/dist/server/define/index.d.ts +26 -5
  20. package/dist/server/define/index.js +1 -1
  21. package/dist/server/http/index.js +1 -1
  22. package/dist/server/index.js +20 -7
  23. package/dist/server/index.js.map +1 -1
  24. package/dist/{server-error-to-envelope-OHQCV66V.js → server-error-to-envelope-UUXDSLAZ.js} +2 -2
  25. package/dist/{start-ETABX6ZK.js → start-N7K7J5OE.js} +3 -3
  26. package/dist/vite-plugin/index.js +2 -2
  27. package/dist/{vite-plugin-AYWW2YTE.js → vite-plugin-V5PVDJZW.js} +5 -5
  28. package/package.json +2 -2
  29. package/dist/chunk-4EL6OX3P.js.map +0 -1
  30. package/dist/chunk-BB4ISKOB.js.map +0 -1
  31. package/dist/chunk-BLT7PPII.js.map +0 -1
  32. /package/dist/{actions-virtual-module-TESQ2T4F.js.map → actions-virtual-module-PNPRCEOS.js.map} +0 -0
  33. /package/dist/{actions-virtual-module-WNA77RHT.js.map → actions-virtual-module-SQDY3V5X.js.map} +0 -0
  34. /package/dist/{app-typed-client-AJ65YXJM.js.map → app-typed-client-5GYEOYP3.js.map} +0 -0
  35. /package/dist/{app-typed-client-XGCP563T.js.map → app-typed-client-QG7BVZYW.js.map} +0 -0
  36. /package/dist/{build-B7B5Q7TV.js.map → build-LVN3KIE3.js.map} +0 -0
  37. /package/dist/{chunk-7BJ6YLKV.js.map → chunk-7CBRKNQA.js.map} +0 -0
  38. /package/dist/{chunk-AUNPGO2V.js.map → chunk-BYS3OYZV.js.map} +0 -0
  39. /package/dist/{chunk-WS67ONGI.js.map → chunk-HGZL5EOI.js.map} +0 -0
  40. /package/dist/{chunk-HTNVOG34.js.map → chunk-NAZ4E2GT.js.map} +0 -0
  41. /package/dist/{dev-KHBWZUY3.js.map → dev-HFOVZWYL.js.map} +0 -0
  42. /package/dist/{server-error-to-envelope-OHQCV66V.js.map → server-error-to-envelope-UUXDSLAZ.js.map} +0 -0
  43. /package/dist/{start-ETABX6ZK.js.map → start-N7K7J5OE.js.map} +0 -0
  44. /package/dist/{vite-plugin-AYWW2YTE.js.map → vite-plugin-V5PVDJZW.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  import "./chunk-PPPR5DGR.js";
2
- import "./chunk-BB4ISKOB.js";
2
+ import "./chunk-TGTNRUH3.js";
3
3
  import "./chunk-GY5Q27BJ.js";
4
4
  import "./chunk-5QW7IQQU.js";
5
5
  import "./chunk-WFNLNIJX.js";
@@ -221,4 +221,4 @@ export const actions = manifest
221
221
  export {
222
222
  actionsVirtualModule
223
223
  };
224
- //# sourceMappingURL=actions-virtual-module-TESQ2T4F.js.map
224
+ //# sourceMappingURL=actions-virtual-module-PNPRCEOS.js.map
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-HTNVOG34.js";
4
- import "./chunk-BLT7PPII.js";
5
- import "./chunk-WS67ONGI.js";
3
+ import "./chunk-NAZ4E2GT.js";
4
+ import "./chunk-GFMQJHXX.js";
5
+ import "./chunk-HGZL5EOI.js";
6
6
  import "./chunk-3LVRAGAZ.js";
7
7
  import {
8
8
  scanServerActionsEnriched
@@ -209,4 +209,4 @@ export const actions = manifest
209
209
  export {
210
210
  actionsVirtualModule
211
211
  };
212
- //# sourceMappingURL=actions-virtual-module-WNA77RHT.js.map
212
+ //# sourceMappingURL=actions-virtual-module-SQDY3V5X.js.map
@@ -1,5 +1,5 @@
1
1
  import "./chunk-PPPR5DGR.js";
2
- import "./chunk-BB4ISKOB.js";
2
+ import "./chunk-TGTNRUH3.js";
3
3
  import "./chunk-GY5Q27BJ.js";
4
4
  import "./chunk-5QW7IQQU.js";
5
5
  import "./chunk-WFNLNIJX.js";
@@ -296,4 +296,4 @@ export {
296
296
  emitClientDts,
297
297
  generateClientDts
298
298
  };
299
- //# sourceMappingURL=app-typed-client-AJ65YXJM.js.map
299
+ //# sourceMappingURL=app-typed-client-5GYEOYP3.js.map
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
- import "./chunk-HTNVOG34.js";
4
- import "./chunk-BLT7PPII.js";
5
- import "./chunk-WS67ONGI.js";
3
+ import "./chunk-NAZ4E2GT.js";
4
+ import "./chunk-GFMQJHXX.js";
5
+ import "./chunk-HGZL5EOI.js";
6
6
  import {
7
7
  generateManifest
8
8
  } from "./chunk-3LVRAGAZ.js";
@@ -284,4 +284,4 @@ export {
284
284
  emitClientDts,
285
285
  generateClientDts
286
286
  };
287
- //# sourceMappingURL=app-typed-client-XGCP563T.js.map
287
+ //# sourceMappingURL=app-typed-client-QG7BVZYW.js.map
@@ -527,7 +527,7 @@ async function buildCommand(options) {
527
527
  `);
528
528
  }
529
529
  async function runAdapterBuild(target, config, cwd) {
530
- const { theoPluginAsync } = await import("./vite-plugin-AYWW2YTE.js");
530
+ const { theoPluginAsync } = await import("./vite-plugin-V5PVDJZW.js");
531
531
  const { default: react } = await import("@vitejs/plugin-react");
532
532
  const ctx = {
533
533
  // `react()` may return Plugin or Plugin[] depending on version; spread the
@@ -602,4 +602,4 @@ function relativize3(absPath, root) {
602
602
  export {
603
603
  buildCommand
604
604
  };
605
- //# sourceMappingURL=build-B7B5Q7TV.js.map
605
+ //# sourceMappingURL=build-LVN3KIE3.js.map
@@ -46,6 +46,7 @@ function resolveAbortSignal(request) {
46
46
  }
47
47
  function defineAgentEndpoint(config) {
48
48
  return {
49
+ params: config.params,
49
50
  handler: async ({ request, ctx, body, query, params }) => {
50
51
  const cookieHeaders = new Headers();
51
52
  const signal = resolveAbortSignal(request);
@@ -198,4 +199,4 @@ export {
198
199
  defineWebChannel,
199
200
  defineTheoPlugin
200
201
  };
201
- //# sourceMappingURL=chunk-4EL6OX3P.js.map
202
+ //# sourceMappingURL=chunk-6XUR4ZSA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/define/define-route.ts","../src/server/define/define-action.ts","../src/server/define/define-middleware.ts","../src/server/define/define-agent-endpoint.ts","../src/server/define/define-agent-tool.ts","../src/server/define/define-websocket.ts","../src/server/define/define-channel.ts","../src/server/define/define-plugin.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","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","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","import type { z } from 'zod'\n\nimport type { AgentEvent } from '../agent/agent-types.js'\n\nimport type { RouteConfig } from './define-route.js'\n\n/**\n * T5.1 — defineAgentEndpoint\n *\n * Sugar over defineRoute (ADR D4). Accepts an async generator that yields\n * AgentEvents and produces a RouteConfig whose handler returns a Response\n * streaming Server-Sent Events (SSE).\n *\n * Wire format: `data: <JSON>\\n\\n` per event. Standards-compliant.\n *\n * The generator may throw — the wrapper catches and emits a final\n * `{ type: 'error', message }` event before closing the stream.\n *\n * The wrapper observes `request.signal` (EC-7) — when aborted, the\n * underlying generator is told to `return()` and the stream closes\n * promptly.\n *\n * Note (EC-12, Out of Scope): SSE backpressure (slow consumer) is not\n * handled here. For high-frequency token streaming consider a different\n * transport (WS) or a buffer policy. This MVP enqueues each event\n * immediately.\n */\n\nexport interface AgentEndpointHandlerArgs<\n TCtx = unknown,\n TBody = unknown,\n TParams extends z.ZodType = z.ZodUndefined,\n> {\n query: undefined\n body: TBody\n params: z.infer<TParams>\n request: Request\n ctx: TCtx\n /**\n * Mutable headers bag that the wrapper merges into the SSE response BEFORE\n * the stream starts. Used by `createConversationHistory` to issue a\n * conversation-id cookie on first request. Append entries via\n * `cookieHeaders.append('set-cookie', '<cookie-string>')`.\n *\n * Cookies appended AFTER the first yield are NOT applied — the response\n * headers commit when the wrapper constructs the Response, before the\n * async generator runs. This is per HTTP semantics, not a wrapper choice.\n */\n cookieHeaders: Headers\n /**\n * Phase 3 (Production-Readiness #5) — request abort signal.\n *\n * Fires when the SSE client disconnects (browser closes tab, abort fetch,\n * etc.). Thread this to `agent.send(msg, { signal })` so the SDK cancels\n * the in-flight provider call — STOPS TOKENS FROM CHARGING for output\n * the user will never receive.\n *\n * EC-1 (MUST FIX): the signal is derived via duck-type detection\n * (`'aborted' in r.signal && typeof r.signal.addEventListener === 'function'`)\n * to survive cross-realm scenarios (Node 18 polyfills, undici, Edge\n * runtimes with their own AbortSignal globals). `instanceof AbortSignal`\n * would fail in those cases.\n */\n signal: AbortSignal\n}\n\nexport interface AgentEndpointConfig<\n TCtx = unknown,\n TBody = unknown,\n TParams extends z.ZodType = z.ZodUndefined,\n> {\n /**\n * Optional Zod schema for path params (e.g. `z.object({ id: z.string() })`).\n * When present, the runner validates path params and returns 400 on mismatch\n * BEFORE the generator runs; the validated params are threaded to the\n * generator typed as `z.infer<TParams>` (D4).\n */\n params?: TParams\n handler: (\n args: AgentEndpointHandlerArgs<TCtx, TBody, TParams>,\n ) => AsyncGenerator<AgentEvent, void, unknown>\n}\n\nconst SSE_HEADERS = {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n} as const\n\nfunction encodeSSE(event: AgentEvent): Uint8Array {\n return new TextEncoder().encode(`data: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Resolve an AbortSignal from either a Web `Request` (`.signal`) or a\n * Node `IncomingMessage` (`.aborted` flag + `'close'`/'aborted' events).\n *\n * The framework's `executeRoute` passes IncomingMessage to route handlers\n * today, but `defineAgentEndpoint` was designed for the Web Standards\n * `Request` shape. This helper bridges both — preventing a runtime crash\n * (`Cannot read properties of undefined (reading 'aborted')`) that would\n * otherwise abort the SSE stream silently before the first yield.\n */\nfunction resolveAbortSignal(request: unknown): AbortSignal {\n if (typeof request !== 'object' || request === null) {\n return new AbortController().signal\n }\n const r = request as {\n signal?: unknown\n aborted?: boolean\n on?: (event: string, cb: () => void) => void\n }\n if (\n typeof r.signal === 'object' &&\n r.signal !== null &&\n 'aborted' in r.signal &&\n typeof (r.signal as AbortSignal).addEventListener === 'function'\n ) {\n return r.signal as AbortSignal\n }\n\n const controller = new AbortController()\n if (r.aborted === true) controller.abort()\n if (typeof r.on === 'function') {\n r.on('close', () => {\n if (!controller.signal.aborted) controller.abort()\n })\n r.on('aborted', () => {\n if (!controller.signal.aborted) controller.abort()\n })\n }\n return controller.signal\n}\n\nexport function defineAgentEndpoint<\n TBody = unknown,\n TCtx = unknown,\n TParams extends z.ZodType = z.ZodUndefined,\n>(\n config: AgentEndpointConfig<TCtx, TBody, TParams>,\n): RouteConfig<z.ZodUndefined, z.ZodUndefined, TParams, TCtx, Response> {\n return {\n params: config.params,\n handler: async ({ request, ctx, body, query, params }) => {\n const cookieHeaders = new Headers()\n const signal = resolveAbortSignal(request)\n const generator = config.handler({\n request,\n ctx: ctx,\n body: body as TBody,\n query: query,\n params: params,\n cookieHeaders,\n signal,\n })\n\n // Prime the generator to its first yield. This forces the handler's\n // synchronous + async setup (including `createConversationHistory` if\n // used) to run BEFORE the Response headers commit, so any Set-Cookie\n // lines appended to `cookieHeaders` land in the actual response.\n //\n // First-byte latency cost: bounded by the work up to the first yield\n // (typically 100-500ms for an LLM chat with `agent.send`). Acceptable\n // for the use case; alternative (heuristic detection of cookie writes)\n // is brittle.\n let firstResult: IteratorResult<AgentEvent, void>\n let primeError: unknown\n try {\n firstResult = await generator.next()\n } catch (err) {\n primeError = err\n firstResult = { value: undefined, done: true }\n }\n\n // Merge any cookies the handler issued into the response headers.\n const responseHeaders = new Headers(SSE_HEADERS)\n for (const value of cookieHeaders.getSetCookie()) {\n responseHeaders.append('set-cookie', value)\n }\n\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const onAbort = () => {\n void generator.return(undefined)\n }\n\n if (signal.aborted) {\n controller.close()\n return\n }\n signal.addEventListener('abort', onAbort, { once: true })\n\n try {\n // If priming threw, yield a final error event and close.\n if (primeError !== undefined) {\n let message: string\n if (primeError instanceof Error) {\n message = primeError.message\n } else if (typeof primeError === 'string') {\n message = primeError\n } else {\n message = 'agent handler failed during setup'\n }\n controller.enqueue(encodeSSE({ type: 'error', message }))\n return\n }\n // Enqueue the primed first value (if any).\n if (firstResult.done !== true) {\n controller.enqueue(encodeSSE(firstResult.value))\n } else {\n return\n }\n // Continue iterating remaining events.\n for await (const event of generator) {\n // `signal.aborted` can flip true asynchronously via the\n // listener registered above. ESLint's narrowing only sees\n // the false assertion at line 114; the dynamic abort is\n // legitimate and the guard prevents enqueue-after-close.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (signal.aborted) break\n controller.enqueue(encodeSSE(event))\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n controller.enqueue(encodeSSE({ type: 'error', message }))\n } finally {\n signal.removeEventListener('abort', onAbort)\n controller.close()\n }\n },\n cancel() {\n void generator.return(undefined)\n },\n })\n\n return new Response(stream, { headers: responseHeaders })\n },\n }\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 (or the `streamAgentRun` adapter) sees as a tool failure and\n * surfaces as an `error` AgentEvent on the SSE 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: (input: Record<string, unknown>) => string | Promise<string>\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> {\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 /** Handler invoked with the parsed input. */\n handler: (input: z.infer<T>) => string | Promise<string>\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>(spec: DefineAgentToolSpec<T>): 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 (input: Record<string, unknown>): Promise<string> => {\n const parsed = spec.inputSchema.parse(input)\n return await spec.handler(parsed)\n },\n }\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","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","import type { TheoPlugin } from '../plugin-types.js'\n\n/**\n * Identity function for defining a Theo plugin.\n *\n * **Note:** Prefer `definePlugin` (shorter, canonical name per ADR-0008 D6).\n * Both functions are identical — `defineTheoPlugin` is kept as an alias for\n * existing in-tree consumers without forcing a migration sweep.\n */\nexport function defineTheoPlugin(plugin: TheoPlugin): TheoPlugin {\n return plugin\n}\n"],"mappings":";AAaO,SAAS,YAOd,QACsD;AACtD,SAAO;AACT;;;ACwBO,SAAS,aACd,QAC4B;AAC5B,SAAO;AACT;;;AC1CO,SAAS,iBAAiB,SAA+C;AAC9E,SAAO;AACT;;;ACwEA,IAAM,cAAc;AAAA,EAClB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,YAAY;AACd;AAEA,SAAS,UAAU,OAA+B;AAChD,SAAO,IAAI,YAAY,EAAE,OAAO,SAAS,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA,CAAM;AACtE;AAYA,SAAS,mBAAmB,SAA+B;AACzD,MAAI,OAAO,YAAY,YAAY,YAAY,MAAM;AACnD,WAAO,IAAI,gBAAgB,EAAE;AAAA,EAC/B;AACA,QAAM,IAAI;AAKV,MACE,OAAO,EAAE,WAAW,YACpB,EAAE,WAAW,QACb,aAAa,EAAE,UACf,OAAQ,EAAE,OAAuB,qBAAqB,YACtD;AACA,WAAO,EAAE;AAAA,EACX;AAEA,QAAM,aAAa,IAAI,gBAAgB;AACvC,MAAI,EAAE,YAAY,KAAM,YAAW,MAAM;AACzC,MAAI,OAAO,EAAE,OAAO,YAAY;AAC9B,MAAE,GAAG,SAAS,MAAM;AAClB,UAAI,CAAC,WAAW,OAAO,QAAS,YAAW,MAAM;AAAA,IACnD,CAAC;AACD,MAAE,GAAG,WAAW,MAAM;AACpB,UAAI,CAAC,WAAW,OAAO,QAAS,YAAW,MAAM;AAAA,IACnD,CAAC;AAAA,EACH;AACA,SAAO,WAAW;AACpB;AAEO,SAAS,oBAKd,QACsE;AACt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ACjC,YAAQ;AAAA,MACN,mBAAmB,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,IAC9C;AAAA,EACF;AAIA,QAAM,EAAE,SAAS,UAAU,GAAG,YAAY,IAAI,EAAE,aAAa,KAAK,WAAW;AAO7E,SAAO;AAAA,IACL,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB;AAAA,IACA,SAAS,OAAO,UAAoD;AAClE,YAAM,SAAS,KAAK,YAAY,MAAM,KAAK;AAC3C,aAAO,MAAM,KAAK,QAAQ,MAAM;AAAA,IAClC;AAAA,EACF;AACF;;;AChHO,SAAS,gBAAgB,SAA6C;AAC3E,SAAO;AACT;AA+CO,SAAS,mBAAmB,SAAmD;AACpF,SAAO;AACT;;;ACvDO,SAAS,cACd,SAC0B;AAC1B,SAAO;AACT;AAoCO,SAAS,iBACd,SAC6B;AAC7B,SAAO;AACT;;;ACjDO,SAAS,iBAAiB,QAAgC;AAC/D,SAAO;AACT;","names":[]}
@@ -18,7 +18,7 @@ import {
18
18
  extractTraceId,
19
19
  handleBatchRequest,
20
20
  sendError
21
- } from "./chunk-BB4ISKOB.js";
21
+ } from "./chunk-TGTNRUH3.js";
22
22
  import {
23
23
  findSuggestion
24
24
  } from "./chunk-5QW7IQQU.js";
@@ -2334,13 +2334,13 @@ async function theoPluginAsync(rootOrOptions) {
2334
2334
  })
2335
2335
  );
2336
2336
  }
2337
- const { appTypedClientPlugin } = await import("./app-typed-client-AJ65YXJM.js");
2337
+ const { appTypedClientPlugin } = await import("./app-typed-client-5GYEOYP3.js");
2338
2338
  const appClientPlugin = appTypedClientPlugin({
2339
2339
  cwd: projectRoot,
2340
2340
  serverDir: resolve9(projectRoot, "server"),
2341
2341
  distDir: resolve9(projectRoot, ".theokit")
2342
2342
  });
2343
- const { actionsVirtualModule } = await import("./actions-virtual-module-TESQ2T4F.js");
2343
+ const { actionsVirtualModule } = await import("./actions-virtual-module-PNPRCEOS.js");
2344
2344
  const actionsPlugin = actionsVirtualModule({
2345
2345
  serverDir: resolve9(projectRoot, "server"),
2346
2346
  distDir: resolve9(projectRoot, ".theokit")
@@ -2514,4 +2514,4 @@ export {
2514
2514
  theoPluginAsync,
2515
2515
  theoPlugin
2516
2516
  };
2517
- //# sourceMappingURL=chunk-7BJ6YLKV.js.map
2517
+ //# sourceMappingURL=chunk-7CBRKNQA.js.map
@@ -16,7 +16,7 @@ import {
16
16
  handleBatchRequest,
17
17
  handleCspReport,
18
18
  handleCsrfReadiness
19
- } from "./chunk-HTNVOG34.js";
19
+ } from "./chunk-NAZ4E2GT.js";
20
20
  import {
21
21
  applySecurityHeaders,
22
22
  createPluginRunnerFromConfig,
@@ -28,7 +28,7 @@ import {
28
28
  generateNonce,
29
29
  logRequest,
30
30
  sendError
31
- } from "./chunk-BLT7PPII.js";
31
+ } from "./chunk-GFMQJHXX.js";
32
32
  import {
33
33
  buildServicesProxyConfig
34
34
  } from "./chunk-CCVC6P6B.js";
@@ -1738,13 +1738,13 @@ async function theoPluginAsync(rootOrOptions) {
1738
1738
  })
1739
1739
  );
1740
1740
  }
1741
- const { appTypedClientPlugin } = await import("./app-typed-client-XGCP563T.js");
1741
+ const { appTypedClientPlugin } = await import("./app-typed-client-QG7BVZYW.js");
1742
1742
  const appClientPlugin = appTypedClientPlugin({
1743
1743
  cwd: projectRoot,
1744
1744
  serverDir: resolve7(projectRoot, "server"),
1745
1745
  distDir: resolve7(projectRoot, ".theokit")
1746
1746
  });
1747
- const { actionsVirtualModule } = await import("./actions-virtual-module-WNA77RHT.js");
1747
+ const { actionsVirtualModule } = await import("./actions-virtual-module-SQDY3V5X.js");
1748
1748
  const actionsPlugin = actionsVirtualModule({
1749
1749
  serverDir: resolve7(projectRoot, "server"),
1750
1750
  distDir: resolve7(projectRoot, ".theokit")
@@ -1910,4 +1910,4 @@ export {
1910
1910
  theoPluginAsync,
1911
1911
  theoPlugin
1912
1912
  };
1913
- //# sourceMappingURL=chunk-AUNPGO2V.js.map
1913
+ //# sourceMappingURL=chunk-BYS3OYZV.js.map
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
3
  import {
4
+ TheoError,
4
5
  serverErrorToEnvelope
5
- } from "./chunk-WS67ONGI.js";
6
+ } from "./chunk-HGZL5EOI.js";
6
7
 
7
8
  // src/server/plugins/plugin-runner.ts
8
9
  var DuplicatePluginError = class extends Error {
@@ -1247,7 +1248,19 @@ async function executeRoute(ctx) {
1247
1248
  if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx2));
1248
1249
  return;
1249
1250
  }
1250
- sendJson(res, handlerResult, rc.status ?? 200, transformer);
1251
+ let responseBody = handlerResult;
1252
+ if (isZodLike(rc.response)) {
1253
+ const parsed = rc.response.safeParse(handlerResult);
1254
+ if (!parsed.success) {
1255
+ throw new TheoError({
1256
+ code: "INTERNAL_SERVER_ERROR",
1257
+ message: "response validation failed",
1258
+ ext: { issues: parsed.error?.issues }
1259
+ });
1260
+ }
1261
+ responseBody = parsed.data;
1262
+ }
1263
+ sendJson(res, responseBody, rc.status ?? 200, transformer);
1251
1264
  if (pluginRunner) await pluginRunner.runOnResponse(buildPluginCtx(ctx2));
1252
1265
  } catch (err) {
1253
1266
  if (pluginRunner) {
@@ -2082,4 +2095,4 @@ export {
2082
2095
  applySecurityHeaders,
2083
2096
  generateNonce
2084
2097
  };
2085
- //# sourceMappingURL=chunk-BLT7PPII.js.map
2098
+ //# sourceMappingURL=chunk-GFMQJHXX.js.map