theokit 0.20.0 → 0.22.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 (57) hide show
  1. package/dist/{agent-76WK2CZJ.js → agent-GXPTQTCU.js} +2 -2
  2. package/dist/{build-6UDZJIHD.js → build-2JDQBBWN.js} +3 -3
  3. package/dist/{chunk-DXF64KS5.js → chunk-4QXVTX3X.js} +30 -12
  4. package/dist/chunk-4QXVTX3X.js.map +1 -0
  5. package/dist/{chunk-WLKFWVOM.js → chunk-5PY3QPVM.js} +32 -47
  6. package/dist/chunk-5PY3QPVM.js.map +1 -0
  7. package/dist/{chunk-3WOODHXK.js → chunk-D7D6V6FN.js} +12 -6
  8. package/dist/chunk-D7D6V6FN.js.map +1 -0
  9. package/dist/{chunk-W4YO6S4I.js → chunk-FO2KMFAE.js} +101 -67
  10. package/dist/chunk-FO2KMFAE.js.map +1 -0
  11. package/dist/{chunk-23T4CO4M.js → chunk-JRYP7KNS.js} +2 -2
  12. package/dist/{chunk-7PFHQ56Q.js → chunk-RQCZTDCX.js} +39 -15
  13. package/dist/chunk-RQCZTDCX.js.map +1 -0
  14. package/dist/{chunk-DMC6HYUR.js → chunk-VS6LJM2V.js} +69 -47
  15. package/dist/chunk-VS6LJM2V.js.map +1 -0
  16. package/dist/cli/index.js +6 -6
  17. package/dist/{define-websocket-CdK94O-D.d.ts → define-websocket-CPQcQK9h.d.ts} +1 -19
  18. package/dist/{dev-NHHTXOA4.js → dev-7AW7FBNH.js} +4 -4
  19. package/dist/{generate-OMKHQ7OM.js → generate-373DALPY.js} +62 -70
  20. package/dist/generate-373DALPY.js.map +1 -0
  21. package/dist/{index-B40qUSrQ.d.ts → index-C3ged4mn.d.ts} +2 -2
  22. package/dist/index.d.ts +1 -8
  23. package/dist/index.js +2 -3
  24. package/dist/{mcp-HP5RVOOZ.js → mcp-MOKIIMJ6.js} +4 -4
  25. package/dist/{mcp-HP5RVOOZ.js.map → mcp-MOKIIMJ6.js.map} +1 -1
  26. package/dist/{plugin-runner-BGBkzgi0.d.ts → plugin-runner-CMprWWHZ.d.ts} +1 -1
  27. package/dist/{plugin-types-DNJGxr4Z.d.ts → plugin-types-L49QYMb5.d.ts} +1 -19
  28. package/dist/{registry-XSRSTH33.js → registry-3NB7KOUI.js} +2 -2
  29. package/dist/server/define/index.d.ts +169 -221
  30. package/dist/server/define/index.js +1 -15
  31. package/dist/server/http/index.d.ts +3 -3
  32. package/dist/server/index.d.ts +168 -7
  33. package/dist/server/index.js +61 -19
  34. package/dist/server/index.js.map +1 -1
  35. package/dist/server/plugins/index.d.ts +3 -3
  36. package/dist/server/realtime/index.d.ts +1 -1
  37. package/dist/{start-ILT6E25Q.js → start-4VHDT4TN.js} +6 -4
  38. package/dist/{start-ILT6E25Q.js.map → start-4VHDT4TN.js.map} +1 -1
  39. package/dist/{static-CYG2WGYP.js → static-MB2CD5Y3.js} +1 -1
  40. package/dist/static-MB2CD5Y3.js.map +1 -0
  41. package/dist/vite-plugin/index.js +2 -2
  42. package/dist/{vite-plugin-3UDOJGO5.js → vite-plugin-5WTU62ZH.js} +4 -4
  43. package/package.json +2 -2
  44. package/dist/chunk-3WOODHXK.js.map +0 -1
  45. package/dist/chunk-7PFHQ56Q.js.map +0 -1
  46. package/dist/chunk-DMC6HYUR.js.map +0 -1
  47. package/dist/chunk-DXF64KS5.js.map +0 -1
  48. package/dist/chunk-W4YO6S4I.js.map +0 -1
  49. package/dist/chunk-WLKFWVOM.js.map +0 -1
  50. package/dist/generate-OMKHQ7OM.js.map +0 -1
  51. package/dist/static-CYG2WGYP.js.map +0 -1
  52. /package/dist/{agent-76WK2CZJ.js.map → agent-GXPTQTCU.js.map} +0 -0
  53. /package/dist/{build-6UDZJIHD.js.map → build-2JDQBBWN.js.map} +0 -0
  54. /package/dist/{chunk-23T4CO4M.js.map → chunk-JRYP7KNS.js.map} +0 -0
  55. /package/dist/{dev-NHHTXOA4.js.map → dev-7AW7FBNH.js.map} +0 -0
  56. /package/dist/{registry-XSRSTH33.js.map → registry-3NB7KOUI.js.map} +0 -0
  57. /package/dist/{vite-plugin-3UDOJGO5.js.map → vite-plugin-5WTU62ZH.js.map} +0 -0
@@ -1,8 +1,8 @@
1
1
  import { RouteConfig, CustomTool } from './define/index.js';
2
- export { ActionAccept, ActionBuilder, ActionConfig, ChannelHandler, DefineAgentToolSpec, MiddlewareBuilder, MiddlewareHandler, PluginBuilder, RouteBuilder, ToolBuilder, ToolTransform, WebChannelHandler, WebSocketBuilder, action, applyTransform, defineAction, defineAgentTool, defineChannel, defineMiddleware, defineRoute, defineTheoPlugin, defineWebChannel, middleware, plugin, route, tool, uiMessageStreamResponse, websocket } from './define/index.js';
3
- export { W as WebSocketHandler, a as WebSocketHandlerWeb, b as WebSocketLike, d as defineWebSocket, c as defineWebSocketWeb } from '../define-websocket-CdK94O-D.js';
2
+ export { ActionAccept, ActionBuilder, ActionConfig, ChannelHandler, DefineAgentToolSpec, MiddlewareBuilder, MiddlewareHandler, PluginBuilder, RouteBuilder, ToolBuilder, ToolTransform, WebChannelHandler, WebSocketBuilder, action, applyTransform, defineChannel, defineWebChannel, middleware, plugin, route, tool, uiMessageStreamResponse, websocket } from './define/index.js';
3
+ export { W as WebSocketHandler, a as WebSocketHandlerWeb, b as WebSocketLike } from '../define-websocket-CPQcQK9h.js';
4
4
  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';
5
- 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, r as TheoTransformer, _ 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, O as jsonTransformer, P as loadCustomErrorPages, Q as matchesOrigin, R as parseCookieHeader, U as parseTraceparent, V as resolveTransformer, W as runMiddlewareAndContext, X as sendError, Y as sendJson, Z as serializeCookie, $ as serveStaticFile, a0 as serverErrorToEnvelope, a1 as setCookie, a2 as superjsonTransformer } from '../index-B40qUSrQ.js';
5
+ 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, r as TheoTransformer, _ 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, O as jsonTransformer, P as loadCustomErrorPages, Q as matchesOrigin, R as parseCookieHeader, U as parseTraceparent, V as resolveTransformer, W as runMiddlewareAndContext, X as sendError, Y as sendJson, Z as serializeCookie, $ as serveStaticFile, a0 as serverErrorToEnvelope, a1 as setCookie, a2 as superjsonTransformer } from '../index-C3ged4mn.js';
6
6
  export { ActionNode, ActionScanError, LoadedManifest, ManifestAction, ManifestAgent, ManifestRoute, ManifestWebSocket, TheoManifest, WebSocketRouteNode, generateManifest, loadManifest, scanMiddlewares, scanServerActions, scanServerActionsEnriched, scanServerRoutes, scanWebSocketRoutes, writeManifest } from './scan/index.js';
7
7
  export { L as LoadModule, S as ServerRouteNode, c as compilePattern, a as createProductionLoader, b as createViteLoader, m as matchRoute } from '../match-CfbEFRG4.js';
8
8
  import { T as TheoErrorEnvelope, a as TheoErrorCode, V as ValidationFieldsExt } from '../error-envelope-BsNzzAV5.js';
@@ -13,7 +13,7 @@ export { DuplicateContextKeyError, DuplicateJobNameError, EnqueueOptions, InMemo
13
13
  export { J as JobBackend, a as JobEnqueueInput, b as JobLease, N as NonRetryableError } from '../job-backend-CgC8Xf33.js';
14
14
  export { ConsoleObservabilityAdapter, LogLevel, LoggerFn, NoopObservabilityAdapter, NoopSpan, ObservabilityAdapter, RequestLog, SpanAttributes, SpanHandle, SpanImpl, StructuredLog, TheoCloudObservabilityAdapter, TheoLogger, _resetWarnOnceForTests, createLogger, createObservabilityPlugin, defineObservabilityAdapter, findSuggestion, levenshtein, logRequest, resolveAdapter, serializeSpansToOtlp, warnOnce } from './observability/index.js';
15
15
  export { a as AuditEvent, A as AuditLogger, J as JsonStdoutSink, c as createNoOpLogger, s as safeAudit } from '../audit-log-BQWM5YLG.js';
16
- export { D as DuplicateDecorationError, a as DuplicatePluginError, P as PluginRunner } from '../plugin-runner-BGBkzgi0.js';
16
+ export { D as DuplicateDecorationError, a as DuplicatePluginError, P as PluginRunner } from '../plugin-runner-CMprWWHZ.js';
17
17
  export { InvalidPluginShapeError, createPluginRunnerFromConfig } from './plugins/index.js';
18
18
  export { R as RateLimitConfig, a as RateLimitResult, c as createRateLimiter, b as createRateLimiterWeb } from '../rate-limit-BdNDZ3vt.js';
19
19
  export { I as InMemoryStore, a as RateLimitState, R as RateLimitStore } from '../rate-limit-store-BEJnhWdw.js';
@@ -31,8 +31,8 @@ import { z } from 'zod';
31
31
  import { AcpTransport } from '@theokit/agents';
32
32
  import { CustomTool as CustomTool$1 } from '@theokit/sdk';
33
33
  import { IncomingMessage } from 'node:http';
34
- import { W as WebOnRequestHook, b as WebPreHandlerHook, c as WebOnResponseHook, d as WebOnErrorHook } from '../plugin-types-DNJGxr4Z.js';
35
- export { e as HookName, H as HookResult, O as OnErrorHook, f as OnRequestHook, g as OnResponseHook, P as PluginContext, h as PluginErrorContext, i as PreHandlerHook, R as RunHookOptions, a as TheoApp, T as TheoPlugin, j as definePlugin } from '../plugin-types-DNJGxr4Z.js';
34
+ import { W as WebOnRequestHook, b as WebPreHandlerHook, c as WebOnResponseHook, d as WebOnErrorHook } from '../plugin-types-L49QYMb5.js';
35
+ export { e as HookName, H as HookResult, O as OnErrorHook, f as OnRequestHook, g as OnResponseHook, P as PluginContext, h as PluginErrorContext, i as PreHandlerHook, R as RunHookOptions, a as TheoApp, T as TheoPlugin } from '../plugin-types-L49QYMb5.js';
36
36
  export { a as ServiceDefinition, S as ServicesConfig, b as ServicesConfigInput, c as ServicesConfigOutput } from '../schema-BpH6ivDY.js';
37
37
  import 'ai';
38
38
  import 'vite';
@@ -1115,6 +1115,167 @@ interface ExecuteWebRequestOptions {
1115
1115
  }
1116
1116
  declare function executeWebRequest(request: Request, routeModule: WebRouteModule, opts?: ExecuteWebRequestOptions): Promise<Response>;
1117
1117
 
1118
+ /**
1119
+ * M33 — the SINGLE route-input validation pipeline, shared by the HTTP path (`web-handler.ts`
1120
+ * `runHandler`) and the in-process caller (`in-process-caller.ts` `callProcedure`).
1121
+ *
1122
+ * Both surfaces validate the same three channels (`query`/`body`/`params`) against the same
1123
+ * `RouteConfig` Zod schemas. Extracting the logic here means there is ONE validation pipeline
1124
+ * (no duplication, no drift) — each caller only differs in how it MAPS a failure: the HTTP path
1125
+ * emits a 400 Response, the in-process path throws a typed error.
1126
+ */
1127
+
1128
+ /** The three request-input channels a route may declare a Zod schema for. */
1129
+ type RouteInputChannel = 'query' | 'body' | 'params';
1130
+ /**
1131
+ * The minimal structural shape the validator needs: the three optional channel schemas. Both
1132
+ * `RouteConfig` (the 5-arity generic contract) and `WebRouteHandlerConfig` (the Web runtime shape)
1133
+ * satisfy this — the validator depends only on the schemas, not the full route generic.
1134
+ */
1135
+ interface RouteInputSchemas {
1136
+ query?: z.ZodType;
1137
+ body?: z.ZodType;
1138
+ params?: z.ZodType;
1139
+ }
1140
+ /** Raw (pre-validation) channel values. A channel absent from the config passes through unchanged. */
1141
+ interface RawRouteInput {
1142
+ query?: unknown;
1143
+ body?: unknown;
1144
+ params?: unknown;
1145
+ }
1146
+ /** Discriminated result — each caller maps `ok:false` to its own surface (Response vs throw). */
1147
+ type RouteInputValidation = {
1148
+ ok: true;
1149
+ query: unknown;
1150
+ body: unknown;
1151
+ params: unknown;
1152
+ } | {
1153
+ ok: false;
1154
+ channel: RouteInputChannel;
1155
+ error: z.ZodError;
1156
+ };
1157
+ /**
1158
+ * Validate the three input channels against the route's declared Zod schemas. A channel with no
1159
+ * declared schema passes its raw value through. First failing channel short-circuits (query → body
1160
+ * → params order, matching `runHandler`).
1161
+ */
1162
+ declare function validateRouteInput(config: RouteInputSchemas, raw: RawRouteInput): RouteInputValidation;
1163
+
1164
+ /**
1165
+ * M33 Phase 1 — `callProcedure`, the in-process typed caller.
1166
+ *
1167
+ * The load-bearing seam for non-HTTP surfaces (TUI / Tauri / MCP-tools): invoke a route's shared
1168
+ * logic with STRUCTURED input, WITHOUT going through the HTTP transport (no URL/body parsing, no
1169
+ * middleware chain, no Response). It reuses the SAME Zod validation pipeline as the HTTP path
1170
+ * (`validateRouteInput`) so there is no drift, and reuses the SAME `config.response` server-fault
1171
+ * check. Failures throw typed errors (there is no HTTP status off-web).
1172
+ *
1173
+ * Prior art: tRPC `callProcedure` / `createCallerFactory`
1174
+ * (`.claude/knowledge-base/references/trpc/packages/server/src/unstable-core-do-not-import/router.ts:401,441`).
1175
+ *
1176
+ * Design (ADR-0044 / blueprint §5.4): the AUTHOR passes structured input `{query?, body?, params?}`
1177
+ * — never synthesizes a Request. A minimal in-process `Request` is provided to the handler ONLY so
1178
+ * handlers that read `request.headers`/`request.url` still work (opencode's proven pattern); the
1179
+ * input itself is NOT parsed from it.
1180
+ */
1181
+
1182
+ /** Structured input for an in-process procedure call — one object per declared channel. */
1183
+ type ProcedureInput = RawRouteInput;
1184
+ /**
1185
+ * Thrown when structured input fails the route's Zod validation. The in-process analog of the HTTP
1186
+ * 400 — carries the failing channel + the Zod issues (typed error, not a magic value; Rule 8).
1187
+ */
1188
+ declare class ProcedureInputError extends Error {
1189
+ readonly channel: RouteInputChannel;
1190
+ readonly issues: z.core.$ZodIssue[];
1191
+ constructor(channel: RouteInputChannel, error: z.ZodError);
1192
+ }
1193
+ /**
1194
+ * Thrown when the handler's plain-object return drifts from `config.response` — a SERVER fault
1195
+ * (the handler violated its own declared contract), mirroring the HTTP path's 500 as a throw.
1196
+ */
1197
+ declare class ProcedureOutputError extends Error {
1198
+ readonly issues: z.core.$ZodIssue[];
1199
+ constructor(error: z.ZodError);
1200
+ }
1201
+ /**
1202
+ * Invoke a route/procedure's handler in-process with structured, Zod-validated input.
1203
+ *
1204
+ * @param config the `RouteConfig` (what `route().build()` produces).
1205
+ * @param input structured `{query?, body?, params?}` — validated by the route's schemas.
1206
+ * @param ctx the typed run-context the handler receives (built by the CALLER — a TUI/Tauri/MCP
1207
+ * surface supplies its own ctx factory; there is no HTTP middleware chain here).
1208
+ * @returns the handler's result (validated against `config.response` when declared).
1209
+ * @throws ProcedureInputError on invalid structured input (the off-web analog of a 400).
1210
+ * @throws ProcedureOutputError on a handler output that drifts from `config.response` (server fault).
1211
+ */
1212
+ declare function callProcedure(config: RouteConfig<z.ZodType, z.ZodType, z.ZodType>, input?: ProcedureInput, ctx?: unknown): Promise<unknown>;
1213
+
1214
+ /**
1215
+ * M33 Phase 1 — the ctx reconciliation contract (ADR-0044 D4 / blueprint §5.2, §8.5).
1216
+ *
1217
+ * ## The problem the deep research verified against our own code
1218
+ *
1219
+ * At runtime (`execute.ts:122-165`) the handler's `ctx` is written by THREE sources, not one:
1220
+ *
1221
+ * 1. **the user `context.ts` factory** — via `runMiddlewareAndContext` (`execute.ts:131`). This is
1222
+ * the ONLY writer the author controls + declares a shape for. **This is the typed surface.**
1223
+ * 2. **plugin decorations** — `pluginRunner.applyDecorations(ctx)` (`execute.ts:124,136`). Plugins
1224
+ * add arbitrary keys (`decorateRequest`) whose types the route author does not see.
1225
+ * 3. **the jobs backend** — `ctx.queue` injected when `jobs.backend` is configured (`execute.ts:141-150`).
1226
+ *
1227
+ * A naive "infer `TCtx` from everything on `ctx`" would LIE — it cannot see writers (2) and (3), so
1228
+ * `ctx.queue` / plugin keys would be typed as present when they are not (or vice-versa). That is the
1229
+ * exact Hono/global-augmentation failure the blueprint refuted (§8.5). oRPC/tRPC avoid it only
1230
+ * because middleware is their SOLE ctx writer; TheoKit is multi-writer.
1231
+ *
1232
+ * ## The reconciliation (what this contract locks)
1233
+ *
1234
+ * The typed `TCtx` a route handler sees reflects **only writer (1)** — the user `context.ts` factory
1235
+ * (`ContextValue` below). Writers (2) and (3) are **explicitly untyped** on the route surface:
1236
+ *
1237
+ * - `ctx.queue` (jobs) is reached through the dedicated {@link JobsAugmentedCtx} helper, NOT the
1238
+ * inferred `TCtx` — a handler that needs the queue opts into the augmented type explicitly.
1239
+ * - plugin-decorated keys are `unknown` by design (a plugin is a cross-cutting, per-app concern;
1240
+ * typing them into every route's `TCtx` would couple routes to plugin internals — G5).
1241
+ *
1242
+ * This keeps the LOCKED 5-arity `RouteConfig` generic (`route-config-generic-arity.test.ts`, GAP-4)
1243
+ * intact — `TCtx` stays the single typed ctx slot; we only define WHICH writer it corresponds to,
1244
+ * so `runtime ⊇ type` holds honestly (the type is a sound subset of the runtime ctx, never a lie).
1245
+ *
1246
+ * Type-tests proving this live in `tests/ctx-reconciliation.test-d.ts`.
1247
+ */
1248
+ /**
1249
+ * The typed run-context a route handler sees = the return of the user `context.ts` factory.
1250
+ * `TValue` is inferred from that factory at the web adapter seam; it EXCLUDES plugin decorations and
1251
+ * `ctx.queue` (those are not part of the author-declared shape).
1252
+ */
1253
+ type ContextValue<TValue extends Record<string, unknown> = Record<string, unknown>> = TValue;
1254
+ /** The `ctx.queue` client shape injected by the jobs backend (writer 3). Reached explicitly. */
1255
+ interface QueueClientLike {
1256
+ enqueue(name: string, input: unknown): void | Promise<void>;
1257
+ }
1258
+ /**
1259
+ * Opt-in augmentation for handlers that read `ctx.queue`. A route that uses the jobs queue annotates
1260
+ * its ctx as `JobsAugmentedCtx<MyCtx>` — making the jobs dependency explicit in the type, instead of
1261
+ * silently assuming `ctx.queue` exists on every route (which would lie when `jobs.backend` is unset).
1262
+ */
1263
+ type JobsAugmentedCtx<TValue extends Record<string, unknown> = Record<string, unknown>> = TValue & {
1264
+ queue: QueueClientLike;
1265
+ };
1266
+ /**
1267
+ * The three runtime ctx writers, named for documentation + the type-test. This is the reconciliation
1268
+ * artifact the plan requires as a deliverable (not a footnote).
1269
+ */
1270
+ declare const CTX_WRITERS: {
1271
+ /** Writer 1 — user `context.ts` factory. THE typed surface (`TCtx`). execute.ts:131 */
1272
+ readonly contextFactory: "context.ts";
1273
+ /** Writer 2 — plugin `decorateRequest`. Untyped on the route surface. execute.ts:124,136 */
1274
+ readonly pluginDecorations: "pluginRunner.applyDecorations";
1275
+ /** Writer 3 — jobs backend `ctx.queue`. Reached via JobsAugmentedCtx, not TCtx. execute.ts:141-150 */
1276
+ readonly jobsQueue: "jobBackend";
1277
+ };
1278
+
1118
1279
  /**
1119
1280
  * Types for `loadEnv()` — env auto-load utility (Phase 1 of
1120
1281
  * docs/plans/framework-zero-config-polish-plan.md).
@@ -1156,4 +1317,4 @@ interface LoadEnvResult {
1156
1317
  declare function _resetEnvCache(): void;
1157
1318
  declare function loadEnv(options?: LoadEnvOptions): LoadEnvResult;
1158
1319
 
1159
- export { type AcpToolConfig, ActionError, type ActionErrorCode, ActionInputError, type ActionManifestEntry, type ActionResult, type AppResource, type AppResourceInput, type BodyParserOptions, DEFAULT_MAX_AGE as CACHE_DEFAULT_MAX_AGE, DEFAULT_MAX_ENTRY_SIZE as CACHE_DEFAULT_MAX_ENTRY_SIZE, DEFAULT_SWR_MULTIPLIER as CACHE_DEFAULT_SWR_MULTIPLIER, CACHE_TAG_MAX_ITEMS, CACHE_TAG_MAX_LENGTH, type CacheControlInput, type CacheEngine, type CacheEngineOptions, type CacheEntry, type CacheStatus, type CacheStorageAdapter, type CacheStore, type CacheStoreAdmin, type ValidationResult as CacheValidationResult, type CachedFunction, type CachedRouteConfig, type ChannelMessage, type ChannelWebhookConfig, type CodeModeApi, type CodeModeConfig, type CodeModePermission, CodeModePermissionDeniedError, type CompiledRouteRule, CustomTool, DEFAULT_EXCLUDED_QUERY_PARAMS, type DefineCachedFunctionOptions, FileTooLargeError, type GetOrComputeOptions, InMemoryCacheAdapter, type InMemoryCacheAdapterOptions, type KeyDerivationOptions, type LoadEnvOptions, type LoadEnvResult, type McpResourceContents, type McpResourceDescriptor, NodeAcpTransport, type NormalizedCacheConfig, type OpenApiDocsOptions, type ParsedBody, type RevalidateResult, type RouteCacheOptions, RouteConfig, type RouteRule, type RouteRules, type Sandbox, type SerializedActionResult, type SerializedResponse, type StdioStreams, THEO_T_PREFIX, type UniversalZodIssue, type UploadedFile, type VendorAgentClient, type VendorAgentToolConfig, VerifyFn, type WorkflowLike, type WorkflowToolConfig, _resetCacheEngine, _resetEnvCache, buildResourceDescriptors, compileRouteRules, createACPTool, createCacheEngine, createCodeMode, createOpenApiHandler, createVendorAgentTool, createWorkflowTool, defineAppResource, defineCachedFunction, defineCachedRoute, deriveKey as deriveCacheKey, deserializeResponse, executeWebRequest, extractAppResources, extractUniversalIssues, getCacheControlHeader, getCacheEngine, handleChannelWebhook, handleMcpStdioLine, initCacheEngine, isActionError, isChannelPath, isInputError, loadEnv, parseChannelPath, parseRequestBody, readAppResource, resolveRouteRule, revalidatePath, revalidateTag, serializeResponse, serveMcpStdio, updateTag, validateExpire as validateCacheExpire, validateMaxAge as validateCacheMaxAge, validateTags as validateCacheTags };
1320
+ export { type AcpToolConfig, ActionError, type ActionErrorCode, ActionInputError, type ActionManifestEntry, type ActionResult, type AppResource, type AppResourceInput, type BodyParserOptions, DEFAULT_MAX_AGE as CACHE_DEFAULT_MAX_AGE, DEFAULT_MAX_ENTRY_SIZE as CACHE_DEFAULT_MAX_ENTRY_SIZE, DEFAULT_SWR_MULTIPLIER as CACHE_DEFAULT_SWR_MULTIPLIER, CACHE_TAG_MAX_ITEMS, CACHE_TAG_MAX_LENGTH, CTX_WRITERS, type CacheControlInput, type CacheEngine, type CacheEngineOptions, type CacheEntry, type CacheStatus, type CacheStorageAdapter, type CacheStore, type CacheStoreAdmin, type ValidationResult as CacheValidationResult, type CachedFunction, type CachedRouteConfig, type ChannelMessage, type ChannelWebhookConfig, type CodeModeApi, type CodeModeConfig, type CodeModePermission, CodeModePermissionDeniedError, type CompiledRouteRule, type ContextValue, CustomTool, DEFAULT_EXCLUDED_QUERY_PARAMS, type DefineCachedFunctionOptions, FileTooLargeError, type GetOrComputeOptions, InMemoryCacheAdapter, type InMemoryCacheAdapterOptions, type JobsAugmentedCtx, type KeyDerivationOptions, type LoadEnvOptions, type LoadEnvResult, type McpResourceContents, type McpResourceDescriptor, NodeAcpTransport, type NormalizedCacheConfig, type OpenApiDocsOptions, type ParsedBody, type ProcedureInput, ProcedureInputError, ProcedureOutputError, type QueueClientLike, type RawRouteInput, type RevalidateResult, type RouteCacheOptions, RouteConfig, type RouteInputChannel, type RouteInputSchemas, type RouteInputValidation, type RouteRule, type RouteRules, type Sandbox, type SerializedActionResult, type SerializedResponse, type StdioStreams, THEO_T_PREFIX, type UniversalZodIssue, type UploadedFile, type VendorAgentClient, type VendorAgentToolConfig, VerifyFn, type WorkflowLike, type WorkflowToolConfig, _resetCacheEngine, _resetEnvCache, buildResourceDescriptors, callProcedure, compileRouteRules, createACPTool, createCacheEngine, createCodeMode, createOpenApiHandler, createVendorAgentTool, createWorkflowTool, defineAppResource, defineCachedFunction, defineCachedRoute, deriveKey as deriveCacheKey, deserializeResponse, executeWebRequest, extractAppResources, extractUniversalIssues, getCacheControlHeader, getCacheEngine, handleChannelWebhook, handleMcpStdioLine, initCacheEngine, isActionError, isChannelPath, isInputError, loadEnv, parseChannelPath, parseRequestBody, readAppResource, resolveRouteRule, revalidatePath, revalidateTag, serializeResponse, serveMcpStdio, updateTag, validateExpire as validateCacheExpire, validateMaxAge as validateCacheMaxAge, validateTags as validateCacheTags, validateRouteInput };
@@ -59,8 +59,9 @@ import {
59
59
  loadEnv,
60
60
  readAppResource,
61
61
  resolveTransformer,
62
- superjsonTransformer
63
- } from "../chunk-W4YO6S4I.js";
62
+ superjsonTransformer,
63
+ validateRouteInput
64
+ } from "../chunk-FO2KMFAE.js";
64
65
  import {
65
66
  findSuggestion,
66
67
  levenshtein
@@ -167,22 +168,15 @@ import "../chunk-X2VVCJ4V.js";
167
168
  import {
168
169
  action,
169
170
  applyTransform,
170
- defineAction,
171
171
  defineAgentTool,
172
172
  defineChannel,
173
- defineMiddleware,
174
- definePlugin,
175
- defineRoute,
176
- defineTheoPlugin,
177
173
  defineWebChannel,
178
- defineWebSocket,
179
- defineWebSocketWeb,
180
174
  middleware,
181
175
  plugin,
182
176
  route,
183
177
  tool,
184
178
  websocket
185
- } from "../chunk-WLKFWVOM.js";
179
+ } from "../chunk-5PY3QPVM.js";
186
180
  import {
187
181
  uiMessageStreamResponse
188
182
  } from "../chunk-JZHT3LW7.js";
@@ -1335,7 +1329,7 @@ async function handleMcpStdioLine(line, mod, name, appResources = []) {
1335
1329
  error: { code: -32700, message: "Parse error" }
1336
1330
  });
1337
1331
  }
1338
- const response = handleMcpJsonRpc(mod, name, body, appResources);
1332
+ const response = await handleMcpJsonRpc(mod, name, body, appResources);
1339
1333
  const payload = await response.json();
1340
1334
  return JSON.stringify(payload);
1341
1335
  }
@@ -1356,6 +1350,57 @@ function deserializeResponse(serialized) {
1356
1350
  return superjson.deserialize(serialized);
1357
1351
  }
1358
1352
 
1353
+ // src/server/http/in-process-caller.ts
1354
+ var ProcedureInputError = class extends Error {
1355
+ channel;
1356
+ issues;
1357
+ constructor(channel, error) {
1358
+ super(`Invalid ${channel} for in-process procedure call: ${error.message}`);
1359
+ this.name = "ProcedureInputError";
1360
+ this.channel = channel;
1361
+ this.issues = error.issues;
1362
+ }
1363
+ };
1364
+ var ProcedureOutputError = class extends Error {
1365
+ issues;
1366
+ constructor(error) {
1367
+ super(`In-process procedure output failed its response schema: ${error.message}`);
1368
+ this.name = "ProcedureOutputError";
1369
+ this.issues = error.issues;
1370
+ }
1371
+ };
1372
+ function inProcessRequest() {
1373
+ return new Request("theo://in-process/procedure", { method: "POST" });
1374
+ }
1375
+ async function callProcedure(config, input = {}, ctx) {
1376
+ const validated = validateRouteInput(config, input);
1377
+ if (!validated.ok) throw new ProcedureInputError(validated.channel, validated.error);
1378
+ const result = await config.handler({
1379
+ query: validated.query,
1380
+ body: validated.body,
1381
+ params: validated.params,
1382
+ request: inProcessRequest(),
1383
+ ctx
1384
+ });
1385
+ const responseSchema = config.response;
1386
+ if (responseSchema !== void 0 && !(result instanceof Response)) {
1387
+ const parsed = responseSchema.safeParse(result);
1388
+ if (!parsed.success) throw new ProcedureOutputError(parsed.error);
1389
+ return parsed.data;
1390
+ }
1391
+ return result;
1392
+ }
1393
+
1394
+ // src/server/http/ctx-reconciliation.ts
1395
+ var CTX_WRITERS = {
1396
+ /** Writer 1 — user `context.ts` factory. THE typed surface (`TCtx`). execute.ts:131 */
1397
+ contextFactory: "context.ts",
1398
+ /** Writer 2 — plugin `decorateRequest`. Untyped on the route surface. execute.ts:124,136 */
1399
+ pluginDecorations: "pluginRunner.applyDecorations",
1400
+ /** Writer 3 — jobs backend `ctx.queue`. Reached via JobsAugmentedCtx, not TCtx. execute.ts:141-150 */
1401
+ jobsQueue: "jobBackend"
1402
+ };
1403
+
1359
1404
  // src/server/index.ts
1360
1405
  if (typeof globalThis !== "undefined") {
1361
1406
  const WARN_KEY = "__theokit_server_umbrella_warn_emitted__";
@@ -1386,6 +1431,7 @@ export {
1386
1431
  CSRF_READINESS_RESET_PATH,
1387
1432
  CSRF_WARN_CODE,
1388
1433
  CSRF_WARN_DOCS_URL,
1434
+ CTX_WRITERS,
1389
1435
  ChannelManager,
1390
1436
  CodeModePermissionDeniedError,
1391
1437
  ConsoleObservabilityAdapter,
@@ -1417,6 +1463,8 @@ export {
1417
1463
  NotFoundError,
1418
1464
  PluginRunner,
1419
1465
  PostgresJobBackend,
1466
+ ProcedureInputError,
1467
+ ProcedureOutputError,
1420
1468
  READY_PATH,
1421
1469
  STRIPPED_HEADERS,
1422
1470
  SpanImpl,
@@ -1441,6 +1489,7 @@ export {
1441
1489
  buildJobManifest,
1442
1490
  buildResourceDescriptors,
1443
1491
  buildSecurityHeaders,
1492
+ callProcedure,
1444
1493
  checkThrottle,
1445
1494
  clearOidcCache,
1446
1495
  compilePattern,
@@ -1472,8 +1521,6 @@ export {
1472
1521
  createViteLoader,
1473
1522
  createWorkflowTool,
1474
1523
  decrypt,
1475
- defineAction,
1476
- defineAgentTool,
1477
1524
  defineAppResource,
1478
1525
  defineCachedFunction,
1479
1526
  defineCachedRoute,
@@ -1481,15 +1528,9 @@ export {
1481
1528
  defineCron,
1482
1529
  defineHealthRoute,
1483
1530
  defineJob,
1484
- defineMiddleware,
1485
1531
  defineObservabilityAdapter,
1486
- definePlugin,
1487
1532
  defineReadyRoute,
1488
- defineRoute,
1489
- defineTheoPlugin,
1490
1533
  defineWebChannel,
1491
- defineWebSocket,
1492
- defineWebSocketWeb,
1493
1534
  defineWebhook,
1494
1535
  deleteCookie,
1495
1536
  deriveKey2 as deriveCacheKey,
@@ -1605,6 +1646,7 @@ export {
1605
1646
  validateCronSchedule,
1606
1647
  validateCsrf,
1607
1648
  validateCsrfRequest,
1649
+ validateRouteInput,
1608
1650
  verifyBackupCode,
1609
1651
  verifyOAuthState,
1610
1652
  verifyTotp,