theokit 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/adapters/web-shim.d.ts +67 -0
  2. package/dist/adapters/ws-shim.d.ts +55 -0
  3. package/dist/agent-events-DosDXkSV.d.ts +94 -0
  4. package/dist/audit-log-BQWM5YLG.d.ts +60 -0
  5. package/dist/boot/index.d.ts +39 -0
  6. package/dist/client/index.d.ts +362 -0
  7. package/dist/csrf-BBrEZSBW.d.ts +107 -0
  8. package/dist/csrf-readiness-store-CjIoub3U.d.ts +43 -0
  9. package/dist/define-websocket-CdK94O-D.d.ts +64 -0
  10. package/dist/devtools/entry.d.ts +5 -0
  11. package/dist/error-envelope-BsNzzAV5.d.ts +62 -0
  12. package/dist/health-route-C0hk64_U.d.ts +57 -0
  13. package/dist/index-B40qUSrQ.d.ts +575 -0
  14. package/dist/index.d.ts +361 -0
  15. package/dist/job-backend-CgC8Xf33.d.ts +68 -0
  16. package/dist/match-CfbEFRG4.d.ts +26 -0
  17. package/dist/plugin-runner-BGBkzgi0.d.ts +95 -0
  18. package/dist/plugin-types-DNJGxr4Z.d.ts +79 -0
  19. package/dist/rate-limit-BdNDZ3vt.d.ts +58 -0
  20. package/dist/rate-limit-store-BEJnhWdw.d.ts +72 -0
  21. package/dist/react-query/index.d.ts +33 -0
  22. package/dist/schema-BpH6ivDY.d.ts +74 -0
  23. package/dist/server/agent/index.d.ts +229 -0
  24. package/dist/server/auth/index.d.ts +419 -0
  25. package/dist/server/cost/index.d.ts +177 -0
  26. package/dist/server/cron/index.d.ts +208 -0
  27. package/dist/server/define/index.d.ts +313 -0
  28. package/dist/server/http/index.d.ts +11 -0
  29. package/dist/server/index.d.ts +848 -0
  30. package/dist/server/jobs/index.d.ts +348 -0
  31. package/dist/server/observability/index.d.ts +324 -0
  32. package/dist/server/plugins/index.d.ts +17 -0
  33. package/dist/server/rate-limit/index.d.ts +105 -0
  34. package/dist/server/realtime/index.d.ts +15 -0
  35. package/dist/server/scan/index.d.ts +106 -0
  36. package/dist/server/security/index.d.ts +193 -0
  37. package/dist/server/storage/index.d.ts +22 -0
  38. package/dist/server/webhook/index.d.ts +148 -0
  39. package/dist/storage-manager-C4jsO0Tp.d.ts +89 -0
  40. package/dist/storage-types-DsDTCPbp.d.ts +96 -0
  41. package/dist/vite-plugin/index.d.ts +115 -0
  42. package/package.json +4 -4
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Cron primitive types (R0.5.4).
3
+ *
4
+ * @see docs/adr/0004-cron-schedule-5-field-utc-strict.md
5
+ */
6
+ type CronConcurrencyPolicy = 'forbid' | 'allow';
7
+ interface CronContext {
8
+ /** W3C trace_id propagated from the scheduler invocation. */
9
+ readonly traceId: string;
10
+ /** UTC instant the cron was scheduled to fire. */
11
+ readonly scheduledAt: Date;
12
+ /** Abort signal triggered when the scheduler stops or shuts down. */
13
+ readonly signal: AbortSignal;
14
+ }
15
+ interface CronOptions {
16
+ /** 5-field UTC cron expression (ADR-0004). */
17
+ schedule: string;
18
+ /** Handler invoked on each fire. May return Promise. */
19
+ handler: (ctx: CronContext) => unknown;
20
+ /**
21
+ * Concurrency policy when previous handler is still running:
22
+ * - 'forbid' (default) — skip the next fire + log a warning
23
+ * - 'allow' — run concurrently
24
+ */
25
+ concurrency?: CronConcurrencyPolicy;
26
+ }
27
+ interface CronDefinition {
28
+ readonly name: string;
29
+ readonly schedule: string;
30
+ readonly handler: (ctx: CronContext) => unknown;
31
+ readonly concurrency: CronConcurrencyPolicy;
32
+ }
33
+
34
+ /**
35
+ * Declare a time-triggered handler. Pure identity helper — no
36
+ * registration side effect; the build-time scanner (T1.3) discovers
37
+ * definitions by walking `server/crons/` and emits a manifest the
38
+ * adapters translate at deploy.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * // server/crons/morning-summary.ts
43
+ * export default defineCron('morning-summary', {
44
+ * schedule: '0 9 * * *', // 09:00 UTC
45
+ * async handler({ traceId, scheduledAt, signal }) {
46
+ * // ...
47
+ * },
48
+ * })
49
+ * ```
50
+ */
51
+ declare function defineCron(name: string, options: CronOptions): CronDefinition;
52
+
53
+ /**
54
+ * Validate a cron schedule string per ADR-0004 — 5-field UTC strict.
55
+ *
56
+ * Accepts:
57
+ * - Standard 5-field expressions: `minute hour dayOfMonth month dayOfWeek`
58
+ * - Step (`*\/15`), range (`1-5`), list (`MON,TUE,FRI`), wildcards
59
+ *
60
+ * Rejects:
61
+ * - 6-field with seconds (`* * * * * *`)
62
+ * - 7-field with year
63
+ * - Shorthand (`@daily`, `@hourly`, `@yearly`, `@reboot`)
64
+ * - Timezone suffix
65
+ * - Empty / whitespace-only
66
+ * - Malformed grammar
67
+ *
68
+ * Throws on every invalid input. Every error message includes the
69
+ * original input and the fix.
70
+ *
71
+ * @see docs/adr/0004-cron-schedule-5-field-utc-strict.md
72
+ */
73
+ declare function validateCronSchedule(schedule: string): void;
74
+
75
+ /**
76
+ * One discovered cron from build-time scan. The handler is intentionally
77
+ * NOT included — manifest is platform-neutral and consumed by adapters
78
+ * that emit static config. Runtime dispatch loads the handler at fire time.
79
+ */
80
+ interface CronNode {
81
+ readonly name: string;
82
+ readonly filePath: string;
83
+ readonly schedule: string;
84
+ readonly concurrency: CronConcurrencyPolicy;
85
+ }
86
+ declare class DuplicateCronNameError extends Error {
87
+ readonly cronName: string;
88
+ readonly filePaths: readonly string[];
89
+ readonly code = "DUPLICATE_CRON_NAME";
90
+ constructor(cronName: string, filePaths: readonly string[]);
91
+ }
92
+ /**
93
+ * Scan a directory for cron definition files and return the discovered
94
+ * `CronNode[]` sorted by name. Throws `DuplicateCronNameError` on name
95
+ * collision and `Error` on missing default export.
96
+ *
97
+ * Sequential by design — module imports are awaited one-by-one to keep
98
+ * error messages anchored to the file that failed.
99
+ */
100
+ declare function scanCrons(cronsDir: string): Promise<CronNode[]>;
101
+
102
+ declare const CRON_MANIFEST_SCHEMA_VERSION: 1;
103
+ interface CronManifestEntry {
104
+ readonly name: string;
105
+ readonly filePath: string;
106
+ readonly schedule: string;
107
+ readonly concurrency: 'forbid' | 'allow';
108
+ }
109
+ interface CronManifest {
110
+ readonly schemaVersion: typeof CRON_MANIFEST_SCHEMA_VERSION;
111
+ readonly generatedAt: string;
112
+ readonly crons: readonly CronManifestEntry[];
113
+ }
114
+ /**
115
+ * Build a `CronManifest` from scanned `CronNode[]`. Filepaths are kept
116
+ * relative to the caller's project root for portability.
117
+ */
118
+ declare function buildCronManifest(nodes: readonly CronNode[], projectRoot?: string): CronManifest;
119
+ /**
120
+ * Write the cron manifest to `path` atomically (EC-106).
121
+ *
122
+ * Accepts either a pre-built `CronManifest` OR an array of `CronNode[]`
123
+ * (which gets converted via `buildCronManifest`). The atomic-write
124
+ * helper guarantees `path` always contains valid JSON, even under
125
+ * concurrent writes (e.g., dev-server rescan + build).
126
+ */
127
+ declare function writeCronManifest(path: string, input: readonly CronNode[] | CronManifest, projectRoot?: string): void;
128
+
129
+ /**
130
+ * Thrown when an existing platform-config file (vercel.json, wrangler.toml,
131
+ * serverless.yml) cannot be parsed. Caller must fix the file before
132
+ * re-running `theokit build`. We NEVER silently overwrite a user's config.
133
+ */
134
+ declare class ExistingConfigUnparseableError extends Error {
135
+ readonly filePath: string;
136
+ readonly parseError: string;
137
+ readonly code = "EXISTING_CONFIG_UNPARSEABLE";
138
+ constructor(filePath: string, parseError: string);
139
+ }
140
+ /**
141
+ * Translate a TheoKit cron manifest into `vercel.json crons[]`.
142
+ *
143
+ * EC-105: existing fields (functions, headers, redirects, rewrites, env,
144
+ * etc.) are preserved verbatim — ONLY the `crons[]` slice is replaced.
145
+ */
146
+ declare function translateCronToVercel(vercelJsonPath: string, crons: readonly CronManifestEntry[]): void;
147
+ /**
148
+ * Translate a TheoKit cron manifest into `wrangler.toml [triggers] crons`.
149
+ *
150
+ * EC-105: regex-based mutation that preserves comments + other sections
151
+ * verbatim. Replaces only the `[triggers]` block (or appends if absent).
152
+ */
153
+ declare function translateCronToCloudflare(wranglerTomlPath: string, crons: readonly CronManifestEntry[]): void;
154
+ /**
155
+ * Convert TheoKit's 5-field UTC cron to AWS EventBridge's 6-field format.
156
+ * EventBridge requires `?` in EITHER day-of-month OR day-of-week (not both `*`).
157
+ *
158
+ * Algorithm:
159
+ * - If DOM is "*" and DOW is "*" → insert ? in DOW (default)
160
+ * - If DOM is "*" and DOW is specific → insert ? in DOM
161
+ * - If DOM is specific and DOW is "*" → insert ? in DOW
162
+ * - Append "*" year field at end.
163
+ */
164
+ declare function convertToAwsCron(schedule: string): string;
165
+ /**
166
+ * Translate a TheoKit cron manifest into a `serverless.yml` functions
167
+ * map with `events: - schedule: cron(...)` entries.
168
+ *
169
+ * EC-105: appends to `functions:` block, preserving all existing
170
+ * functions/sections. Cron functions are named `cron_<name>` to avoid
171
+ * collision with user-declared functions.
172
+ */
173
+ declare function translateCronToAws(serverlessYmlPath: string, crons: readonly CronManifestEntry[]): void;
174
+ /**
175
+ * Emit a Deno entry file that registers each cron via `Deno.cron`.
176
+ *
177
+ * Unlike Vercel/CF/AWS, Deno.cron is an in-process runtime API — the
178
+ * entry file is a managed artifact (overwritten each build), not a user
179
+ * config (so EC-105 doesn't apply here).
180
+ */
181
+ declare function translateCronToDeno(entryPath: string, crons: readonly CronManifestEntry[]): void;
182
+
183
+ /**
184
+ * In-memory cron scheduler for `theokit dev` (T1.4).
185
+ *
186
+ * Algorithm:
187
+ * - For each cron, compute `nextFireAt = cron-parser.next()`.
188
+ * - Schedule a `setTimeout(handler, nextFireAt - now)`.
189
+ * - After handler invocation (sync return or Promise scheduled), recompute
190
+ * next fire from CURRENT time (drift-free vs scheduled time).
191
+ *
192
+ * Per-cron isolation (EC-109):
193
+ * - Each cron's handler invocation is fire-and-forget (`void` scheduled).
194
+ * A hanging handler does NOT block the scheduler loop nor other crons.
195
+ * - `concurrency: 'forbid'` (default) tracks an in-flight flag per-cron;
196
+ * subsequent ticks skip + warn while the in-flight flag is set.
197
+ * - `concurrency: 'allow'` runs handlers concurrently — caller's responsibility.
198
+ *
199
+ * Production deploys use platform-native triggers (T1.5 adapter translators);
200
+ * this scheduler exists only for local dev iteration.
201
+ */
202
+ interface CronScheduler {
203
+ start(): void;
204
+ stop(): void;
205
+ }
206
+ declare function createCronScheduler(definitions: readonly CronDefinition[]): CronScheduler;
207
+
208
+ export { CRON_MANIFEST_SCHEMA_VERSION, type CronConcurrencyPolicy, type CronContext, type CronDefinition, type CronManifest, type CronManifestEntry, type CronNode, type CronOptions, type CronScheduler, DuplicateCronNameError, ExistingConfigUnparseableError, buildCronManifest, convertToAwsCron, createCronScheduler, defineCron, scanCrons, translateCronToAws, translateCronToCloudflare, translateCronToDeno, translateCronToVercel, validateCronSchedule, writeCronManifest };
@@ -0,0 +1,313 @@
1
+ import { z } from 'zod';
2
+ import { A as AgentEvent } from '../../agent-events-DosDXkSV.js';
3
+ import { UIMessageChunk } from 'ai';
4
+ import { b as WebSocketLike } from '../../define-websocket-CdK94O-D.js';
5
+ export { W as WebSocketHandler, a as WebSocketHandlerWeb, d as defineWebSocket, c as defineWebSocketWeb } from '../../define-websocket-CdK94O-D.js';
6
+ import { IncomingMessage } from 'node:http';
7
+ import { T as TheoPlugin } from '../../plugin-types-DNJGxr4Z.js';
8
+ export { H as HEALTH_PATH, a as HealthRouteConfig, b as READY_PATH, c as ReadyRouteConfig, d as ReservedResponse, R as ReservedRoutes, e as defineHealthRoute, f as defineReadyRoute, s as serveReservedRoute } from '../../health-route-C0hk64_U.js';
9
+
10
+ /**
11
+ * core/contracts/route-config.ts
12
+ *
13
+ * Canonical home for `RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>` —
14
+ * the contract shape consumed by `defineRoute()` (server) and
15
+ * `defineCachedRoute()` (cache).
16
+ *
17
+ * Moved here in T2.2 of architecture-cleanup so `cache → core/contracts`
18
+ * is the legal edge (replacing the prior `cache → server` violation).
19
+ *
20
+ * GAP-4 (plan v1.1): the 5-arity generic shape `<TQuery, TBody, TParams, TCtx, TResponse>`
21
+ * MUST be preserved byte-by-byte. Type tests assert this in
22
+ * `tests/unit/route-config-generic-arity.test.ts`.
23
+ */
24
+
25
+ interface RouteConfig<TQuery extends z.ZodType = z.ZodUndefined, TBody extends z.ZodType = z.ZodUndefined, TParams extends z.ZodType = z.ZodUndefined, TCtx = unknown, TResponse = unknown> {
26
+ query?: TQuery;
27
+ body?: TBody;
28
+ params?: TParams;
29
+ status?: number;
30
+ /**
31
+ * Optional Zod schema for the handler's plain-object return value. When
32
+ * present, BOTH runtimes (Node `executeRoute` + Web `executeWebRequest`)
33
+ * validate the handler's plain-object return against it BEFORE serializing.
34
+ *
35
+ * A mismatch is a SERVER fault (the handler violated its own declared
36
+ * contract) → 500 `INTERNAL_SERVER_ERROR`, distinct from the 400 used for
37
+ * input (`query`/`body`/`params`) validation failures.
38
+ *
39
+ * `Response`-instance returns (and `undefined`/`null` → 204) are NOT
40
+ * validated. This is a plain optional field — runtime validation only; the
41
+ * handler return type is NOT statically inferred from `response` (YAGNI).
42
+ */
43
+ response?: z.ZodType;
44
+ /**
45
+ * Opt out of CSRF enforcement for this route. Use for endpoints that
46
+ * legitimately receive third-party POSTs (Stripe webhooks, GitHub
47
+ * webhooks, OAuth callbacks). Defaults to enforced per `config.security.csrf`.
48
+ *
49
+ * Setting `csrf: false` only disables the per-route check — it does NOT
50
+ * disable the global mode setting for other routes.
51
+ */
52
+ csrf?: false;
53
+ handler: (ctx: {
54
+ query: z.infer<TQuery>;
55
+ body: z.infer<TBody>;
56
+ params: z.infer<TParams>;
57
+ request: Request;
58
+ ctx: TCtx;
59
+ }) => TResponse | Promise<TResponse>;
60
+ }
61
+
62
+ /**
63
+ * Define a typed HTTP route.
64
+ * Identity function — provides type inference for route handlers.
65
+ */
66
+ declare function defineRoute<TQuery extends z.ZodType = z.ZodUndefined, TBody extends z.ZodType = z.ZodUndefined, TParams extends z.ZodType = z.ZodUndefined, TCtx = unknown, TResponse = unknown>(config: RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>;
67
+
68
+ /**
69
+ * Action wire-protocol accept mode per plan g3-server-actions-and-useaction
70
+ * v1.2 ADR D1. Default behavior (when omitted) is `'json'`. `'form'` opts the
71
+ * action into FormData multipart parsing for progressive-enhancement forms;
72
+ * the runtime in `server/http/action-execute.ts` will coerce FormData entries
73
+ * against the `input` schema via `formDataToObject` (Astro pattern).
74
+ */
75
+ type ActionAccept = 'form' | 'json';
76
+ interface ActionConfig<TInput extends z.ZodType, TCtx = unknown> {
77
+ /**
78
+ * Zod input schema. Required: every action declares its input contract via
79
+ * Zod (architecture rule: zod-is-SSOT). The shape becomes the handler's
80
+ * typed `input` parameter via `z.infer<TInput>`.
81
+ */
82
+ input: TInput;
83
+ /**
84
+ * Wire-protocol accept mode. Defaults to `'json'` when omitted. Setting
85
+ * `'form'` switches the runtime to FormData multipart parsing — the input
86
+ * schema MUST be `z.object(...)` so field-by-field coercion can drive
87
+ * boolean string / number / array coercion (Astro pattern).
88
+ */
89
+ accept?: ActionAccept;
90
+ /**
91
+ * Opt OUT of CSRF enforcement for this action. Default (omitted) keeps the
92
+ * multi-header CSRF gate active. Set `false` for endpoints intentionally
93
+ * callable without the `X-Theo-Action` header (e.g. public webhooks). The
94
+ * runtime in `server/http/action-execute.ts` reads this flag.
95
+ */
96
+ csrf?: false;
97
+ handler: (ctx: {
98
+ input: z.infer<TInput>;
99
+ ctx: TCtx;
100
+ }) => unknown;
101
+ }
102
+ /**
103
+ * Define a typed server action.
104
+ *
105
+ * Identity function — provides type inference for action handlers. The
106
+ * runtime that consumes the config (validation + invocation + serialization)
107
+ * lives in `server/http/action-execute.ts`.
108
+ *
109
+ * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.2: the new
110
+ * `accept?: 'form' | 'json'` field is the only contract change vs the
111
+ * pre-G3 identity. Existing callsites (`defineAction({input, handler})`)
112
+ * continue to compile — `accept` is opt-in.
113
+ */
114
+ declare function defineAction<TInput extends z.ZodType, TCtx = unknown>(config: ActionConfig<TInput, TCtx>): ActionConfig<TInput, TCtx>;
115
+
116
+ type MiddlewareHandler = (request: Request, next: (request: Request) => Promise<Response>) => Response | Promise<Response>;
117
+ /**
118
+ * Define a middleware handler.
119
+ * Identity function — provides type annotation for middleware.
120
+ */
121
+ declare function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler;
122
+
123
+ /**
124
+ * T5.1 — defineAgentEndpoint
125
+ *
126
+ * Sugar over defineRoute (ADR D4). Accepts an async generator that yields
127
+ * AgentEvents and produces a RouteConfig whose handler returns a Response
128
+ * streaming Server-Sent Events (SSE).
129
+ *
130
+ * Wire format: `data: <JSON>\n\n` per event. Standards-compliant.
131
+ *
132
+ * The generator may throw — the wrapper catches and emits a final
133
+ * `{ type: 'error', message }` event before closing the stream.
134
+ *
135
+ * The wrapper observes `request.signal` (EC-7) — when aborted, the
136
+ * underlying generator is told to `return()` and the stream closes
137
+ * promptly.
138
+ *
139
+ * Note (EC-12, Out of Scope): SSE backpressure (slow consumer) is not
140
+ * handled here. For high-frequency token streaming consider a different
141
+ * transport (WS) or a buffer policy. This MVP enqueues each event
142
+ * immediately.
143
+ */
144
+ interface AgentEndpointHandlerArgs<TCtx = unknown, TBody = unknown, TParams extends z.ZodType = z.ZodUndefined> {
145
+ query: undefined;
146
+ body: TBody;
147
+ params: z.infer<TParams>;
148
+ request: Request;
149
+ ctx: TCtx;
150
+ /**
151
+ * Mutable headers bag that the wrapper merges into the SSE response BEFORE
152
+ * the stream starts. Used by `createConversationHistory` to issue a
153
+ * conversation-id cookie on first request. Append entries via
154
+ * `cookieHeaders.append('set-cookie', '<cookie-string>')`.
155
+ *
156
+ * Cookies appended AFTER the first yield are NOT applied — the response
157
+ * headers commit when the wrapper constructs the Response, before the
158
+ * async generator runs. This is per HTTP semantics, not a wrapper choice.
159
+ */
160
+ cookieHeaders: Headers;
161
+ /**
162
+ * Phase 3 (Production-Readiness #5) — request abort signal.
163
+ *
164
+ * Fires when the SSE client disconnects (browser closes tab, abort fetch,
165
+ * etc.). Thread this to `agent.send(msg, { signal })` so the SDK cancels
166
+ * the in-flight provider call — STOPS TOKENS FROM CHARGING for output
167
+ * the user will never receive.
168
+ *
169
+ * EC-1 (MUST FIX): the signal is derived via duck-type detection
170
+ * (`'aborted' in r.signal && typeof r.signal.addEventListener === 'function'`)
171
+ * to survive cross-realm scenarios (Node 18 polyfills, undici, Edge
172
+ * runtimes with their own AbortSignal globals). `instanceof AbortSignal`
173
+ * would fail in those cases.
174
+ */
175
+ signal: AbortSignal;
176
+ }
177
+ interface AgentEndpointConfig<TCtx = unknown, TBody = unknown, TParams extends z.ZodType = z.ZodUndefined> {
178
+ /**
179
+ * Optional Zod schema for path params (e.g. `z.object({ id: z.string() })`).
180
+ * When present, the runner validates path params and returns 400 on mismatch
181
+ * BEFORE the generator runs; the validated params are threaded to the
182
+ * generator typed as `z.infer<TParams>` (D4).
183
+ */
184
+ params?: TParams;
185
+ handler: (args: AgentEndpointHandlerArgs<TCtx, TBody, TParams>) => AsyncGenerator<AgentEvent, void, unknown>;
186
+ }
187
+ declare function defineAgentEndpoint<TBody = unknown, TCtx = unknown, TParams extends z.ZodType = z.ZodUndefined>(config: AgentEndpointConfig<TCtx, TBody, TParams>): RouteConfig<z.ZodUndefined, z.ZodUndefined, TParams, TCtx, Response>;
188
+
189
+ declare function uiMessageStreamResponse(chunks: AsyncIterable<UIMessageChunk>): Response;
190
+
191
+ /**
192
+ * Item #4 — `defineAgentTool`
193
+ *
194
+ * Sugar over the `@theokit/sdk` `CustomTool` contract. Takes a Zod schema +
195
+ * handler and produces a structurally-compatible `CustomTool` that
196
+ * `Agent.create({ tools: [...] })` accepts.
197
+ *
198
+ * Uses Zod v4's native `z.toJSONSchema()` to convert the input schema to
199
+ * JSON Schema for LLM providers.
200
+ *
201
+ * Handler error propagation:
202
+ * `defineAgentTool` parses the input via the Zod schema BEFORE calling the
203
+ * user handler. Invalid input throws a `ZodError`, which the SDK's tool-
204
+ * dispatcher (or the `streamAgentRun` adapter) sees as a tool failure and
205
+ * surfaces as an `error` AgentEvent on the SSE wire (ADR D3).
206
+ */
207
+ /**
208
+ * Local mirror of the SDK's `CustomTool` interface. We don't `import type`
209
+ * from `@theokit/sdk` because the SDK is an optional peer (consumers who
210
+ * never call `defineAgentTool` shouldn't need it installed). The shape is
211
+ * the wire contract; any structurally-matching object is accepted by
212
+ * `Agent.create({ tools })`.
213
+ *
214
+ * @public
215
+ */
216
+ interface CustomTool {
217
+ name: string;
218
+ description: string;
219
+ inputSchema: Record<string, unknown>;
220
+ handler: (input: Record<string, unknown>) => string | Promise<string>;
221
+ }
222
+ /**
223
+ * Spec accepted by {@link defineAgentTool}. `inputSchema` is a Zod 3 schema
224
+ * rooted in `z.object(...)`. The `handler` argument type is inferred via
225
+ * `z.infer<T>`.
226
+ *
227
+ * @public
228
+ */
229
+ interface DefineAgentToolSpec<T extends z.ZodType> {
230
+ /** Tool name surfaced to the LLM. Must match `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$`. */
231
+ name: string;
232
+ /** Description surfaced to the LLM. Required — drives tool-selection accuracy. */
233
+ description: string;
234
+ /** Zod schema describing the input. Must be `z.object(...)` at the root. */
235
+ inputSchema: T;
236
+ /** Handler invoked with the parsed input. */
237
+ handler: (input: z.infer<T>) => string | Promise<string>;
238
+ }
239
+ /**
240
+ * Build a {@link CustomTool} from a Zod 3 schema + handler.
241
+ *
242
+ * Behavior:
243
+ * - Validates `name` matches the LLM tool-name regex.
244
+ * - Requires `inputSchema` to be a `ZodObject` (Anthropic + SDK contract).
245
+ * - Warns (not throws) if `description` is empty — empty descriptions
246
+ * degrade LLM tool selection.
247
+ * - Converts the Zod schema to JSON Schema 7 inline (no `$ref`s — LLMs handle
248
+ * inline schemas more reliably).
249
+ * - Strips the top-level `$schema` field (Anthropic rejects schemas with
250
+ * `$schema` at root in some provider modes).
251
+ * - Wraps the handler to parse the input via the Zod schema BEFORE invoking
252
+ * the user code — bad LLM-supplied input throws `ZodError`, which the SDK
253
+ * converts to `tool_result(isError)`.
254
+ *
255
+ * @public
256
+ */
257
+ declare function defineAgentTool<T extends z.ZodType>(spec: DefineAgentToolSpec<T>): CustomTool;
258
+
259
+ interface ChannelHandler<TMessage = unknown> {
260
+ onSubscribe?: (ws: WebSocketLike, room: string, req: IncomingMessage) => void;
261
+ onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void;
262
+ onUnsubscribe?: (ws: WebSocketLike, room: string) => void;
263
+ }
264
+ /**
265
+ * Define a channel handler for WebSocket rooms.
266
+ * Identity function — provides type inference for channel handlers.
267
+ */
268
+ declare function defineChannel<TMessage = unknown>(handler: ChannelHandler<TMessage>): ChannelHandler<TMessage>;
269
+ /**
270
+ * T5a.2 Phase F slice 2/3 — Web-Standards channel handler.
271
+ *
272
+ * Mirror of `ChannelHandler<TMessage>` for the Web `Request` shape.
273
+ * `onSubscribe` receives `request: Request` instead of `req: IncomingMessage`
274
+ * — the rest of the surface (onMessage, onUnsubscribe) is shape-agnostic
275
+ * (WebSocketLike is already Web-standards-compatible per `define-websocket.ts`).
276
+ *
277
+ * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`
278
+ * v1.0 § Phase F.
279
+ *
280
+ * **Architectural note:** WebSocket upgrade semantics differ across
281
+ * runtimes:
282
+ * - Node: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —
283
+ * hands you `req: IncomingMessage` at the upgrade handshake.
284
+ * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade
285
+ * handshake IS a Web Request) — hands you `request: Request`.
286
+ * - Bun: `server.upgrade(request, { data })` — same Web Request shape.
287
+ * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.
288
+ *
289
+ * Channel handlers targeting CF/Bun/Deno use `WebChannelHandler`; legacy
290
+ * Node consumers stay on `ChannelHandler`. Cross-runtime channels ship
291
+ * both shapes.
292
+ */
293
+ interface WebChannelHandler<TMessage = unknown> {
294
+ onSubscribe?: (ws: WebSocketLike, room: string, request: Request) => void;
295
+ onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void;
296
+ onUnsubscribe?: (ws: WebSocketLike, room: string) => void;
297
+ }
298
+ /**
299
+ * Web-Standards `defineChannel` sibling. Identity function — provides
300
+ * type inference for Web channel handlers.
301
+ */
302
+ declare function defineWebChannel<TMessage = unknown>(handler: WebChannelHandler<TMessage>): WebChannelHandler<TMessage>;
303
+
304
+ /**
305
+ * Identity function for defining a Theo plugin.
306
+ *
307
+ * **Note:** Prefer `definePlugin` (shorter, canonical name per ADR-0008 D6).
308
+ * Both functions are identical — `defineTheoPlugin` is kept as an alias for
309
+ * existing in-tree consumers without forcing a migration sweep.
310
+ */
311
+ declare function defineTheoPlugin(plugin: TheoPlugin): TheoPlugin;
312
+
313
+ export { type ActionAccept, type ActionConfig, type AgentEndpointConfig, type AgentEndpointHandlerArgs, type ChannelHandler, type CustomTool, type DefineAgentToolSpec, type MiddlewareHandler, type RouteConfig, type WebChannelHandler, WebSocketLike, defineAction, defineAgentEndpoint, defineAgentTool, defineChannel, defineMiddleware, defineRoute, defineTheoPlugin, defineWebChannel, uiMessageStreamResponse };
@@ -0,0 +1,11 @@
1
+ export { B as BATCH_PATH, a as BatchExecuteFn, b as BatchPathConflictError, c as BatchPayload, d as BatchRequestItem, e as BatchResponse, f as BatchResultItem, C as CookieOptions, g as CorsConfig, h as CorsHandler, i as CorsOrigin, j as CorsWebHandler, k as CustomErrorPages, E as ExecuteActionOptions, l as ExecuteRouteContext, H as HandleBatchOptions, M as MAX_ERROR_HTML_BYTES, m as MiddlewareResult, N as NotFoundError, S as STRIPPED_HEADERS, n as SendErrorInput, o as SendErrorOptions, T as TRACE_HEADER, p as TRACE_PARENT_HEADER, q as TheoError, _ as _resetMiddlewareCacheForTests, s as appendCookieToHeaders, t as appendDeleteCookieToHeaders, u as createCorsHandler, v as createCorsWebHandler, w as deleteCookie, x as envelopeCodeToStatus, y as executeAction, z as executeRoute, A as extractTraceId, D as extractTraceIdFromRequest, F as fromUnknown, G as getCookie, I as getCookieFromRequest, J as handleBatchRequest, K as handleRequestError, L as handleWebRequestError, P as loadCustomErrorPages, Q as matchesOrigin, R as parseCookieHeader, U as parseTraceparent, W as runMiddlewareAndContext, X as sendError, Y as sendJson, Z as serializeCookie, $ as serveStaticFile, a0 as serverErrorToEnvelope, a1 as setCookie } from '../../index-B40qUSrQ.js';
2
+ import '../../error-envelope-BsNzzAV5.js';
3
+ import 'node:http';
4
+ import '../../plugin-types-DNJGxr4Z.js';
5
+ import '../../plugin-runner-BGBkzgi0.js';
6
+ import '../../job-backend-CgC8Xf33.js';
7
+ import '../../match-CfbEFRG4.js';
8
+ import 'vite';
9
+ import '../../csrf-BBrEZSBW.js';
10
+ import '../../audit-log-BQWM5YLG.js';
11
+ import 'zod';