theokit 0.11.4 → 0.11.6

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.
@@ -29,19 +29,25 @@ function resolveAbortSignal(request) {
29
29
  return new AbortController().signal;
30
30
  }
31
31
  const r = request;
32
- if (typeof r.signal === "object" && r.signal !== null && "aborted" in r.signal && typeof r.signal.addEventListener === "function") {
32
+ const isNodeRequest = typeof r.on === "function";
33
+ if (!isNodeRequest && typeof r.signal === "object" && r.signal !== null && "aborted" in r.signal && typeof r.signal.addEventListener === "function") {
33
34
  return r.signal;
34
35
  }
35
36
  const controller = new AbortController();
37
+ const abort = () => {
38
+ if (!controller.signal.aborted) controller.abort();
39
+ };
36
40
  if (r.aborted === true) controller.abort();
37
41
  if (typeof r.on === "function") {
42
+ r.on("aborted", abort);
38
43
  r.on("close", () => {
39
- if (!controller.signal.aborted) controller.abort();
40
- });
41
- r.on("aborted", () => {
42
- if (!controller.signal.aborted) controller.abort();
44
+ if (r.complete !== true) abort();
43
45
  });
44
46
  }
47
+ const socket = r.socket;
48
+ if (socket && typeof socket.on === "function") {
49
+ socket.on("close", abort);
50
+ }
45
51
  return controller.signal;
46
52
  }
47
53
  function defineAgentEndpoint(config) {
@@ -199,4 +205,4 @@ export {
199
205
  defineWebChannel,
200
206
  defineTheoPlugin
201
207
  };
202
- //# sourceMappingURL=chunk-6XUR4ZSA.js.map
208
+ //# sourceMappingURL=chunk-GEEMNDPH.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` (`.socket` close + `'aborted'`/'close' 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 *\n * Node ≥23 regression (empty-SSE-stream): Node 23 added\n * `http.IncomingMessage.prototype.signal` — a Web `AbortSignal` that fires\n * `abort` the instant the request body is fully received (`req.complete ===\n * true`), NOT when the client disconnects. The earlier duck-type\n * (\"has `.signal` with `aborted` + `addEventListener`\") matched a genuine Web\n * `Request` AND, on Node ≥23, the Node `IncomingMessage` — so the helper\n * returned the request-lifecycle signal, already aborted by the time the\n * handler primes, and EVERY agent stream produced 0 bytes on Node 24.\n *\n * Discriminator: a Node `IncomingMessage` is an `EventEmitter` (`typeof\n * r.on === 'function'`); a Web `Request` is not. So `r.signal` is trusted\n * directly ONLY when this is not a Node request. For the Node path the only\n * lifecycle event that means \"client disconnected\" (rather than \"request body\n * finished\") is the underlying SOCKET closing — `req`'s own `.signal`/`'close'`\n * fire at body-end on Node ≥23 and would kill a long-lived SSE response.\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 complete?: boolean\n on?: (event: string, cb: () => void) => void\n socket?: { on?: (event: string, cb: () => void) => void }\n }\n\n // A genuine Web `Request` exposes `.signal` and is NOT a Node EventEmitter.\n const isNodeRequest = typeof r.on === 'function'\n if (\n !isNodeRequest &&\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 const abort = () => {\n if (!controller.signal.aborted) controller.abort()\n }\n if (r.aborted === true) controller.abort()\n if (typeof r.on === 'function') {\n // Explicit client abort (request reset mid-flight).\n r.on('aborted', abort)\n // `req`'s own 'close' fires at request-completion on Node ≥23 (body fully\n // received), which is NOT a disconnect — guard with `complete`. A close\n // while the request already completed normally is body-end noise.\n r.on('close', () => {\n if (r.complete !== true) abort()\n })\n }\n // The underlying socket closes only on real connection teardown (client\n // gone), never at request-body-end — the correct disconnect signal for a\n // long-lived SSE response.\n const socket = r.socket\n if (socket && typeof socket.on === 'function') {\n socket.on('close', abort)\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":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,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":[]}
@@ -9,7 +9,7 @@ import {
9
9
  defineWebChannel,
10
10
  defineWebSocket,
11
11
  defineWebSocketWeb
12
- } from "../../chunk-6XUR4ZSA.js";
12
+ } from "../../chunk-GEEMNDPH.js";
13
13
  import {
14
14
  HEALTH_PATH,
15
15
  READY_PATH,
@@ -258,7 +258,7 @@ import {
258
258
  defineWebChannel,
259
259
  defineWebSocket,
260
260
  defineWebSocketWeb
261
- } from "../chunk-6XUR4ZSA.js";
261
+ } from "../chunk-GEEMNDPH.js";
262
262
  import {
263
263
  HEALTH_PATH,
264
264
  READY_PATH,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "theokit",
3
- "version": "0.11.4",
3
+ "version": "0.11.6",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "license": "Apache-2.0",
@@ -109,7 +109,7 @@
109
109
  "dist"
110
110
  ],
111
111
  "dependencies": {
112
- "@theokit/agents": "^0.24.0",
112
+ "@theokit/agents": "^0.25.0",
113
113
  "@theokit/http": "^0.5.4",
114
114
  "@vitejs/plugin-react": "^4.7.0",
115
115
  "busboy": "^1.6.0",
@@ -1 +0,0 @@
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;A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