theokit 0.15.2 → 0.17.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 (100) hide show
  1. package/dist/actions-virtual-module-G4BANOLW.js +0 -0
  2. package/dist/add-W6FNTAFS.js +0 -0
  3. package/dist/{agent-MN7XGJR3.js → agent-7DBAK65H.js} +3 -3
  4. package/dist/{agents-typed-client-SAWAAH7K.js → agents-typed-client-D3LXWGCF.js} +6 -4
  5. package/dist/agents-typed-client-D3LXWGCF.js.map +1 -0
  6. package/dist/{agents-typed-client-UTEQUA63.js → agents-typed-client-LQ36PCHL.js} +6 -4
  7. package/dist/agents-typed-client-LQ36PCHL.js.map +1 -0
  8. package/dist/app-typed-client-Z6BHD4MF.js +0 -0
  9. package/dist/aws-lambda-7GSCNLPY.js +0 -0
  10. package/dist/body-parser-web-FV5HWCY3.js +0 -0
  11. package/dist/broadcast-LUMOJIJT.js +0 -0
  12. package/dist/{build-QDAFSKKW.js → build-MTI4RAI3.js} +2 -2
  13. package/dist/build-request-body-preview-QMWD2IXK.js +0 -0
  14. package/dist/bun-KP2KES6S.js +0 -0
  15. package/dist/check-PD2FTKMM.js +0 -0
  16. package/dist/chunk-34YQOXGM.js +0 -0
  17. package/dist/{chunk-5UUOGAJH.js → chunk-3FNZG6Q3.js} +36 -1
  18. package/dist/chunk-3FNZG6Q3.js.map +1 -0
  19. package/dist/chunk-45C3WUQ7.js +0 -0
  20. package/dist/{chunk-ZJDKAD3L.js → chunk-4FOPDXKT.js} +270 -37
  21. package/dist/chunk-4FOPDXKT.js.map +1 -0
  22. package/dist/{chunk-OTFIRP6S.js → chunk-4JDYVNSY.js} +28 -6
  23. package/dist/chunk-4JDYVNSY.js.map +1 -0
  24. package/dist/chunk-567NA7Y6.js +0 -0
  25. package/dist/chunk-5ODOE6EF.js +0 -0
  26. package/dist/{chunk-KGFNWIMS.js → chunk-CWVBDUDC.js} +18 -4
  27. package/dist/chunk-CWVBDUDC.js.map +1 -0
  28. package/dist/chunk-FOZIR3TG.js +0 -0
  29. package/dist/chunk-GBXLKYIA.js +0 -0
  30. package/dist/chunk-GDN3PXFH.js +0 -0
  31. package/dist/chunk-HGZL5EOI.js +0 -0
  32. package/dist/chunk-HNBWZKIQ.js +0 -0
  33. package/dist/chunk-IEES3CHD.js +0 -0
  34. package/dist/chunk-JAIKGP3Q.js +0 -0
  35. package/dist/chunk-JQSFBJR5.js +0 -0
  36. package/dist/chunk-KXA37ONC.js +0 -0
  37. package/dist/{chunk-NBWB4S46.js → chunk-M6NMS5LR.js} +17 -7
  38. package/dist/{chunk-NBWB4S46.js.map → chunk-M6NMS5LR.js.map} +1 -1
  39. package/dist/chunk-NXTF5PPW.js +0 -0
  40. package/dist/chunk-P37RZRFV.js +0 -0
  41. package/dist/chunk-WR4F4EEZ.js +0 -0
  42. package/dist/{chunk-UOR6JTCI.js → chunk-X6COGWHN.js} +296 -48
  43. package/dist/chunk-X6COGWHN.js.map +1 -0
  44. package/dist/chunk-YJAUJXZS.js +0 -0
  45. package/dist/cli/index.js +4 -4
  46. package/dist/client/index.d.ts +59 -2
  47. package/dist/client/index.js +43 -0
  48. package/dist/client/index.js.map +1 -1
  49. package/dist/cloudflare-C6E5SPAE.js +0 -0
  50. package/dist/configure-agent-registry-ZOBVU3MV.js +0 -0
  51. package/dist/db-3UNAMSFK.js +0 -0
  52. package/dist/deno-deploy-RFZN56X4.js +0 -0
  53. package/dist/{dev-TEE4T6ZB.js → dev-SVHKR2VR.js} +4 -4
  54. package/dist/dev-emit-VJ5CFMPY.js +0 -0
  55. package/dist/dispatcher-EJHL6JMJ.js +0 -0
  56. package/dist/docker-LZZB4D5E.js +0 -0
  57. package/dist/generate-OMKHQ7OM.js +0 -0
  58. package/dist/index.js +2 -2
  59. package/dist/info-7PE2PZJI.js +0 -0
  60. package/dist/internal-api-J27TYE2I.js +0 -0
  61. package/dist/load-config-JKYO5RFK.js +0 -0
  62. package/dist/netlify-PMLHVPN4.js +0 -0
  63. package/dist/node-BPJ3Z4DT.js +0 -0
  64. package/dist/openapi-MXMLZCXC.js +0 -0
  65. package/dist/registry-XJUYD2OU.js +0 -0
  66. package/dist/router-TLEAOFID.js +0 -0
  67. package/dist/routes-NNBEZSGN.js +0 -0
  68. package/dist/scan-7MJC6PYU.js +0 -0
  69. package/dist/schema-7CAY6IZR.js +0 -0
  70. package/dist/server/define/index.d.ts +42 -6
  71. package/dist/server/define/index.js +3 -1
  72. package/dist/server/index.d.ts +278 -4
  73. package/dist/server/index.js +232 -2
  74. package/dist/server/index.js.map +1 -1
  75. package/dist/server-error-to-envelope-UUXDSLAZ.js +0 -0
  76. package/dist/server-routes-hmr-VZXOP5YT.js +0 -0
  77. package/dist/services-json-Y3XODNB5.js +0 -0
  78. package/dist/services-typed-client-32KMTTXR.js +0 -0
  79. package/dist/{start-7MQEEQH4.js → start-SDZTFJNQ.js} +3 -3
  80. package/dist/static-7ARBVDJF.js +0 -0
  81. package/dist/storage-manager-ZSQFLEYT.js +0 -0
  82. package/dist/theo-cloud-DQRP6S6M.js +0 -0
  83. package/dist/upgrade-readiness-ACGW44JC.js +0 -0
  84. package/dist/vercel-J6G7ZHYQ.js +0 -0
  85. package/dist/vite-plugin/index.js +2 -2
  86. package/dist/{vite-plugin-GC6WCU4P.js → vite-plugin-ZZYTMWZY.js} +4 -4
  87. package/package.json +12 -11
  88. package/LICENSE +0 -201
  89. package/dist/agents-typed-client-SAWAAH7K.js.map +0 -1
  90. package/dist/agents-typed-client-UTEQUA63.js.map +0 -1
  91. package/dist/chunk-5UUOGAJH.js.map +0 -1
  92. package/dist/chunk-KGFNWIMS.js.map +0 -1
  93. package/dist/chunk-OTFIRP6S.js.map +0 -1
  94. package/dist/chunk-UOR6JTCI.js.map +0 -1
  95. package/dist/chunk-ZJDKAD3L.js.map +0 -1
  96. /package/dist/{agent-MN7XGJR3.js.map → agent-7DBAK65H.js.map} +0 -0
  97. /package/dist/{build-QDAFSKKW.js.map → build-MTI4RAI3.js.map} +0 -0
  98. /package/dist/{dev-TEE4T6ZB.js.map → dev-SVHKR2VR.js.map} +0 -0
  99. /package/dist/{start-7MQEEQH4.js.map → start-SDZTFJNQ.js.map} +0 -0
  100. /package/dist/{vite-plugin-GC6WCU4P.js.map → vite-plugin-ZZYTMWZY.js.map} +0 -0
@@ -1,5 +1,5 @@
1
- import { RouteConfig } from './define/index.js';
2
- export { ActionAccept, ActionConfig, ChannelHandler, CustomTool, DefineAgentToolSpec, MiddlewareHandler, WebChannelHandler, defineAction, defineAgentTool, defineChannel, defineMiddleware, defineRoute, defineTheoPlugin, defineWebChannel, uiMessageStreamResponse } from './define/index.js';
1
+ import { RouteConfig, CustomTool } from './define/index.js';
2
+ export { ActionAccept, ActionConfig, ChannelHandler, DefineAgentToolSpec, MiddlewareHandler, ToolTransform, WebChannelHandler, applyTransform, defineAction, defineAgentTool, defineChannel, defineMiddleware, defineRoute, defineTheoPlugin, defineWebChannel, uiMessageStreamResponse } from './define/index.js';
3
3
  export { W as WebSocketHandler, a as WebSocketHandlerWeb, b as WebSocketLike, d as defineWebSocket, c as defineWebSocketWeb } from '../define-websocket-CdK94O-D.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
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';
@@ -25,8 +25,11 @@ export { a as CsrfReadinessRouteSummary, C as CsrfReadinessStore, b as CsrfReadi
25
25
  export { P as PostgresFactory, R as RedisFactory, S as StorageManager, g as getStorageManager } from '../storage-manager-C4jsO0Tp.js';
26
26
  export { Db0Database, UnstorageInstance, useDatabase, useUnstorage } from './storage/index.js';
27
27
  export { G as GenericFactory, a as PoolLike, P as PostgresDatabaseConfig, c as RedisLike, R as RedisServerConfig, S as ServerConfig, d as StorageAdapter, b as StorageConfig, T as TlsConfig } from '../storage-types-DsDTCPbp.js';
28
- export { BodyTooLargeError, DEFAULT_MAX_BODY_BYTES, DefineWebhookOptions, RawBodyResult, ReadRawBodyOptions, VerifyFn, VerifyResult, WebhookContext, WebhookDefinition, defineWebhook, dispatchWebhook, readRawBody, timingSafeEqual } from './webhook/index.js';
28
+ import { VerifyFn } from './webhook/index.js';
29
+ export { BodyTooLargeError, DEFAULT_MAX_BODY_BYTES, DefineWebhookOptions, RawBodyResult, ReadRawBodyOptions, VerifyResult, WebhookContext, WebhookDefinition, defineWebhook, dispatchWebhook, readRawBody, timingSafeEqual } from './webhook/index.js';
29
30
  import { z } from 'zod';
31
+ import { AcpTransport } from '@theokit/agents';
32
+ import { CustomTool as CustomTool$1 } from '@theokit/sdk';
30
33
  import { IncomingMessage } from 'node:http';
31
34
  import { W as WebOnRequestHook, b as WebPreHandlerHook, c as WebOnResponseHook, d as WebOnErrorHook } from '../plugin-types-DNJGxr4Z.js';
32
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';
@@ -647,6 +650,277 @@ declare const THEO_T_PREFIX = "_THEO_T_";
647
650
  declare const DEFAULT_MAX_AGE = 1;
648
651
  declare const DEFAULT_SWR_MULTIPLIER = 60;
649
652
 
653
+ /**
654
+ * M26 (ADR-0041) — `createWorkflowTool`: wrap an SDK `Workflow` as a `CustomTool`.
655
+ *
656
+ * THIN adapter. `packages/workflows/` stays G13-forbidden — the workflow ENGINE is the SDK's
657
+ * (`Workflow.create(...).run(input)`). This exposes an already-built `Workflow` to an agent as one
658
+ * callable tool: it validates the tool input, delegates to `workflow.run(input)`, and shapes the
659
+ * result for the model. It calls no LLM, dispatches no tool, and runs no orchestration of its own —
660
+ * the SDK owns all of that (sdk-runtime.md / G2).
661
+ */
662
+
663
+ /**
664
+ * Structural stand-in for the SDK `Workflow` (the adapter never imports the SDK type — keeps the
665
+ * SDK an optional peer). Any object with a `run(input)` resolving to `{ status, output }` matches.
666
+ */
667
+ interface WorkflowLike {
668
+ run(input: unknown): Promise<{
669
+ status: string;
670
+ output: unknown;
671
+ runId?: string;
672
+ }>;
673
+ }
674
+ /** Config for {@link createWorkflowTool}. `inputSchema` defaults to an open object. */
675
+ interface WorkflowToolConfig {
676
+ /** Tool name surfaced to the LLM. */
677
+ name: string;
678
+ /** Tool description surfaced to the LLM. */
679
+ description: string;
680
+ /** Zod schema for the workflow input (defaults to `z.object({}).passthrough()`). */
681
+ inputSchema?: z.ZodType;
682
+ }
683
+ /**
684
+ * Wrap an SDK `Workflow` as a {@link CustomTool}. Fails fast if `workflow` does not expose a
685
+ * `run()` method (the SDK Workflow contract), so a mis-wired call is caught at definition time, not
686
+ * at the first invocation (error-handling.md).
687
+ */
688
+ declare function createWorkflowTool(workflow: WorkflowLike, config: WorkflowToolConfig): CustomTool;
689
+
690
+ /** Stdio transport backed by a spawned subprocess (the default for {@link createACPTool}). */
691
+ declare class NodeAcpTransport implements AcpTransport {
692
+ private readonly proc;
693
+ constructor(command: string, args?: string[], cwd?: string);
694
+ send(line: string): void;
695
+ subscribe(onData: (chunk: string) => void): void;
696
+ close(): void;
697
+ }
698
+ interface AcpToolConfig {
699
+ /** Executable for the coding agent (e.g. `claude`, `amp`, `codex`). */
700
+ command: string;
701
+ /** Command-line arguments. */
702
+ args?: string[];
703
+ /** Working directory for the spawned agent. */
704
+ cwd?: string;
705
+ /** Tool name the model calls. */
706
+ name: string;
707
+ /** Tool description surfaced to the model. */
708
+ description: string;
709
+ /**
710
+ * REQUIRED — decide file/shell permission requests from the coding agent. Security by default:
711
+ * there is NO default-allow. Return `{ granted: boolean }` (may be async).
712
+ */
713
+ onPermissionRequest: (params: unknown) => {
714
+ granted: boolean;
715
+ } | Promise<{
716
+ granted: boolean;
717
+ }>;
718
+ /** Injected transport factory (defaults to spawning via {@link NodeAcpTransport}) — for tests. */
719
+ transportFactory?: (config: AcpToolConfig) => AcpTransport;
720
+ }
721
+ /** Wrap a coding agent as a `CustomTool`. Fails fast if `onPermissionRequest` is missing. */
722
+ declare function createACPTool(config: AcpToolConfig): CustomTool$1;
723
+
724
+ /**
725
+ * M28 (ADR-0041) — `createVendorAgentTool`: expose a third-party agent SDK (Claude Agent SDK,
726
+ * OpenAI, Cursor) behind a uniform `CustomTool`, mirroring the M17 ACP pattern.
727
+ *
728
+ * The vendor RUNTIME stays theirs — TheoKit only wires. The vendor client is INJECTED (the real
729
+ * vendor SDK client in prod, a fake in tests), so no vendor dependency enters core; vendor-specific
730
+ * client packages belong under `@theokit/agent-*`, never here. This calls no LLM of its own and runs
731
+ * no loop — it delegates each prompt to `client.query(...)` (sdk-runtime.md / G2). Resume is threaded
732
+ * via the vendor's own session id.
733
+ */
734
+
735
+ /**
736
+ * Structural contract a vendor agent client must satisfy (the adapter never imports a vendor type).
737
+ * `query` runs one turn; `resumeSessionId` continues a prior vendor session; the returned
738
+ * `sessionId` identifies the session to resume next.
739
+ */
740
+ interface VendorAgentClient {
741
+ query(prompt: string, opts?: {
742
+ resumeSessionId?: string;
743
+ }): Promise<{
744
+ text: string;
745
+ sessionId?: string;
746
+ }>;
747
+ }
748
+ /** Config for {@link createVendorAgentTool}. */
749
+ interface VendorAgentToolConfig {
750
+ /** Vendor label (e.g. `claude`, `openai`, `cursor`). Drives the default tool name. */
751
+ vendor: string;
752
+ /** The injected vendor client (real SDK client in prod, a fake in tests). */
753
+ client: VendorAgentClient;
754
+ /** Tool name the model calls (defaults to `<vendor>_agent`). */
755
+ name?: string;
756
+ /** Tool description surfaced to the model (defaults to a one-line delegate hint). */
757
+ description?: string;
758
+ /**
759
+ * Side-channel callback invoked with the vendor session id after each turn — lets the app capture
760
+ * it for a later resume WITHOUT leaking session bookkeeping into the model's view of the result.
761
+ */
762
+ onSession?: (sessionId: string) => void;
763
+ }
764
+ /**
765
+ * Wrap a vendor agent SDK as a {@link CustomTool}. Fails fast if `vendor` is empty or the client
766
+ * does not expose `query()` (error-handling.md) — a mis-wired call is caught at definition time.
767
+ */
768
+ declare function createVendorAgentTool(config: VendorAgentToolConfig): CustomTool;
769
+
770
+ /**
771
+ * M29 (ADR-0041) — `createCodeMode`: expose a set of tools to agent-authored code run inside an
772
+ * ISOLATION boundary, so the agent composes tools programmatically instead of one call at a time.
773
+ *
774
+ * Security posture (the whole point of this feature):
775
+ * - The isolation boundary (`sandbox`) is **injected**, never hand-rolled here (Top-risk 1). The app
776
+ * supplies a vetted sandbox — isolated-vm, QuickJS-WASM, or a locked-down worker. TheoKit core
777
+ * ships no VM and adds no sandbox dependency (same posture as the injected deploy adapter / the
778
+ * M17 transport). `node:vm` is NOT a security boundary and MUST NOT be used as the sandbox.
779
+ * - TheoKit owns the **restricted API** (only the declared tools are reachable from the code — no
780
+ * `fs`, `process`, `require`, or network unless a declared, permission-gated tool provides it) and
781
+ * the **mandatory permission gate**: every tool call from the code passes `onPermissionRequest`
782
+ * first, and there is NO default-allow (mirrors M17 `onPermissionRequest`).
783
+ *
784
+ * Threat model (summary): a malicious model could author code that (a) calls a dangerous tool, or
785
+ * (b) tries to reach a host capability. (a) is stopped by the permission gate (deny → the API call
786
+ * throws). (b) is stopped by the injected sandbox (the restricted API is the ONLY surface the code
787
+ * sees). If the app injects a weak sandbox, (b) is on the app — hence the vetted-sandbox requirement.
788
+ */
789
+
790
+ /** The restricted API handed to sandboxed code: declared tool names → permission-gated callables. */
791
+ type CodeModeApi = Record<string, (args: unknown) => Promise<unknown>>;
792
+ /** The injected isolation boundary. The app supplies a vetted implementation. */
793
+ interface Sandbox {
794
+ /** Run `code` with access to ONLY `api` (the restricted tool surface). Resolve the code's result. */
795
+ run(code: string, api: CodeModeApi): Promise<unknown>;
796
+ }
797
+ /** A permission decision for one tool call from sandboxed code. */
798
+ interface CodeModePermission {
799
+ granted: boolean;
800
+ /** Optional reason surfaced to the model on denial. */
801
+ reason?: string;
802
+ }
803
+ interface CodeModeConfig {
804
+ /** The tools reachable from the code (the restricted API). */
805
+ tools: CustomTool[];
806
+ /** The injected isolation boundary (vetted sandbox — NEVER node:vm). */
807
+ sandbox: Sandbox;
808
+ /**
809
+ * REQUIRED — decide each tool call the code attempts. Security by default: NO default-allow.
810
+ * Return `{ granted }` (may be async). Mirrors M17 `onPermissionRequest`.
811
+ */
812
+ onPermissionRequest: (req: {
813
+ tool: string;
814
+ args: unknown;
815
+ }) => CodeModePermission | Promise<CodeModePermission>;
816
+ /** Tool name the model calls (default `run_code`). */
817
+ name?: string;
818
+ /** Tool description surfaced to the model. */
819
+ description?: string;
820
+ }
821
+ /** Thrown when the permission gate denies a tool call from sandboxed code. */
822
+ declare class CodeModePermissionDeniedError extends Error {
823
+ constructor(tool: string, reason?: string);
824
+ }
825
+ /**
826
+ * Build a code-mode `CustomTool`. Fails fast if `onPermissionRequest` or `sandbox` is missing
827
+ * (security by default). The returned tool takes `{ code }`, assembles the permission-gated restricted
828
+ * API from `tools`, runs the code in the injected sandbox, and returns the code's result.
829
+ */
830
+ declare function createCodeMode(config: CodeModeConfig): CustomTool;
831
+
832
+ /**
833
+ * M27 (ADR-0041) — channel webhook routes: `POST /api/agents/<name>/channels/<platform>/webhook`.
834
+ *
835
+ * Auto-generates a per-platform inbound webhook endpoint that VALIDATES the platform signature
836
+ * (reusing the existing webhook `VerifyFn` providers — Slack/Telegram/Discord — never a hand-rolled
837
+ * scheme) and hands the parsed payload to an injected `onMessage` seam. The seam is where an app
838
+ * wires the SDK gateway package (`@theokit/gateway-*`) that translates the payload into an agent
839
+ * turn — TheoKit provides the route + signature gate, NOT the gateway's parsing (G2 / it does not
840
+ * reimplement the gateway).
841
+ */
842
+
843
+ /** Parsed `{ agent, platform }` from a channel webhook path, or `null` when it doesn't match. */
844
+ declare function parseChannelPath(urlPath: string): {
845
+ agent: string;
846
+ platform: string;
847
+ } | null;
848
+ /** True when `urlPath` targets a channel webhook (dev/prod routing branches on this). */
849
+ declare function isChannelPath(urlPath: string): boolean;
850
+ /** The inbound message handed to the app after signature validation passes. */
851
+ interface ChannelMessage {
852
+ agent: string;
853
+ platform: string;
854
+ /** The parsed JSON payload from the platform (the gateway translates this to an agent turn). */
855
+ payload: unknown;
856
+ }
857
+ interface ChannelWebhookConfig {
858
+ /** Per-platform signature validators (e.g. `{ slack: slack({...}), telegram: telegram({...}) }`). */
859
+ validators: Record<string, VerifyFn>;
860
+ /** Handoff seam — wire the SDK gateway / agent here. Invoked only after signature validation. */
861
+ onMessage: (message: ChannelMessage) => void | Promise<void>;
862
+ }
863
+ /**
864
+ * Handle one channel webhook request. Returns:
865
+ * 404 UNKNOWN_PLATFORM — no validator configured for `<platform>`
866
+ * 400 BAD_REQUEST — path is not a channel webhook, or the body is not JSON
867
+ * 401 INVALID_SIGNATURE — the platform signature check failed (negative case)
868
+ * 200 { ok: true } — validated + handed to `onMessage`
869
+ */
870
+ declare function handleChannelWebhook(request: Request, urlPath: string, config: ChannelWebhookConfig): Promise<Response>;
871
+
872
+ /**
873
+ * M30 (ADR-0041) — MCP Apps: `ui://` HTML resources for the MCP server (M16).
874
+ *
875
+ * A tool can declare a `ui://` HTML resource; the MCP server advertises it via `resources/list` and
876
+ * serves the HTML via `resources/read`. The client renders it in a SANDBOXED iframe (see
877
+ * `mcp-app-host.ts`). Pure data transforms here — no LLM, no runtime (ADR-0040 § D2 home concern).
878
+ *
879
+ * Security: only the `ui://` scheme is accepted (an app UI resource), never `http(s)://` — the HTML
880
+ * is rendered sandboxed on the client, and the scheme gate keeps a tool from smuggling a remote URL
881
+ * into the app surface.
882
+ */
883
+ /** A declared `ui://` app resource. */
884
+ interface AppResource {
885
+ uri: string;
886
+ name: string;
887
+ mimeType: 'text/html';
888
+ html: string;
889
+ description?: string;
890
+ }
891
+ /** Input to {@link defineAppResource}. */
892
+ interface AppResourceInput {
893
+ /** MUST start with `ui://`. */
894
+ uri: string;
895
+ name: string;
896
+ html: string;
897
+ description?: string;
898
+ }
899
+ /** An MCP `resources/list` descriptor (no HTML body — that comes from `resources/read`). */
900
+ interface McpResourceDescriptor {
901
+ uri: string;
902
+ name: string;
903
+ mimeType: 'text/html';
904
+ description?: string;
905
+ }
906
+ /** An MCP `resources/read` result. */
907
+ interface McpResourceContents {
908
+ contents: {
909
+ uri: string;
910
+ mimeType: 'text/html';
911
+ text: string;
912
+ }[];
913
+ }
914
+ /**
915
+ * Declare a `ui://` HTML app resource. Fails fast if the uri is not a `ui://` scheme or the HTML is
916
+ * empty (error-handling.md) — a misconfigured resource is caught at definition time.
917
+ */
918
+ declare function defineAppResource(input: AppResourceInput): AppResource;
919
+ /** Map app resources to MCP `resources/list` descriptors (the HTML body is omitted from the list). */
920
+ declare function buildResourceDescriptors(resources: readonly AppResource[]): McpResourceDescriptor[];
921
+ /** Serve the HTML for `uri` as an MCP `resources/read` result, or `null` when unknown. */
922
+ declare function readAppResource(resources: readonly AppResource[], uri: string): McpResourceContents | null;
923
+
650
924
  interface UploadedFile {
651
925
  fieldname: string;
652
926
  filename: string;
@@ -843,4 +1117,4 @@ interface LoadEnvResult {
843
1117
  declare function _resetEnvCache(): void;
844
1118
  declare function loadEnv(options?: LoadEnvOptions): LoadEnvResult;
845
1119
 
846
- export { ActionError, type ActionErrorCode, ActionInputError, type ActionManifestEntry, type ActionResult, 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 CompiledRouteRule, DEFAULT_EXCLUDED_QUERY_PARAMS, type DefineCachedFunctionOptions, FileTooLargeError, type GetOrComputeOptions, InMemoryCacheAdapter, type InMemoryCacheAdapterOptions, type KeyDerivationOptions, type LoadEnvOptions, type LoadEnvResult, type NormalizedCacheConfig, type OpenApiDocsOptions, type ParsedBody, type RevalidateResult, type RouteCacheOptions, RouteConfig, type RouteRule, type RouteRules, type SerializedActionResult, type SerializedResponse, THEO_T_PREFIX, type UniversalZodIssue, type UploadedFile, _resetCacheEngine, _resetEnvCache, compileRouteRules, createCacheEngine, createOpenApiHandler, defineCachedFunction, defineCachedRoute, deriveKey as deriveCacheKey, deserializeResponse, executeWebRequest, extractUniversalIssues, getCacheControlHeader, getCacheEngine, initCacheEngine, isActionError, isInputError, loadEnv, parseRequestBody, resolveRouteRule, revalidatePath, revalidateTag, serializeResponse, updateTag, validateExpire as validateCacheExpire, validateMaxAge as validateCacheMaxAge, validateTags as validateCacheTags };
1120
+ 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, 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, extractUniversalIssues, getCacheControlHeader, getCacheEngine, handleChannelWebhook, initCacheEngine, isActionError, isChannelPath, isInputError, loadEnv, parseChannelPath, parseRequestBody, readAppResource, resolveRouteRule, revalidatePath, revalidateTag, serializeResponse, updateTag, validateExpire as validateCacheExpire, validateMaxAge as validateCacheMaxAge, validateTags as validateCacheTags };
@@ -50,12 +50,15 @@ import {
50
50
  } from "../chunk-ESC54TAK.js";
51
51
  import {
52
52
  _resetEnvCache,
53
+ buildResourceDescriptors,
54
+ defineAppResource,
53
55
  executeWebRequest,
54
56
  jsonTransformer,
55
57
  loadEnv,
58
+ readAppResource,
56
59
  resolveTransformer,
57
60
  superjsonTransformer
58
- } from "../chunk-5UUOGAJH.js";
61
+ } from "../chunk-3FNZG6Q3.js";
59
62
  import {
60
63
  findSuggestion,
61
64
  levenshtein
@@ -160,6 +163,7 @@ import "../chunk-6NEXVBPY.js";
160
163
  import "../chunk-7MQOHNHE.js";
161
164
  import "../chunk-X2VVCJ4V.js";
162
165
  import {
166
+ applyTransform,
163
167
  defineAction,
164
168
  defineAgentTool,
165
169
  defineChannel,
@@ -169,7 +173,7 @@ import {
169
173
  defineWebChannel,
170
174
  defineWebSocket,
171
175
  defineWebSocketWeb
172
- } from "../chunk-KGFNWIMS.js";
176
+ } from "../chunk-CWVBDUDC.js";
173
177
  import {
174
178
  uiMessageStreamResponse
175
179
  } from "../chunk-JZHT3LW7.js";
@@ -1095,6 +1099,219 @@ function resolveRouteRule(path, compiled) {
1095
1099
  return void 0;
1096
1100
  }
1097
1101
 
1102
+ // src/server/agent/workflow-tool.ts
1103
+ import { z } from "zod";
1104
+ var FAILURE_STATUSES = /* @__PURE__ */ new Set(["failed", "error", "cancelled", "canceled"]);
1105
+ function createWorkflowTool(workflow, config) {
1106
+ const runFn = workflow?.run;
1107
+ if (typeof runFn !== "function") {
1108
+ throw new Error(
1109
+ "createWorkflowTool: the SDK does not expose a Workflow (expected an object with a run() method). Pass a `Workflow.create(...).\u2026build()` instance from @theokit/sdk."
1110
+ );
1111
+ }
1112
+ const inputSchema = config.inputSchema ?? z.looseObject({});
1113
+ return defineAgentTool({
1114
+ name: config.name,
1115
+ description: config.description,
1116
+ inputSchema,
1117
+ handler: async (input) => {
1118
+ const run = await workflow.run(input);
1119
+ if (FAILURE_STATUSES.has(run.status)) {
1120
+ throw new Error(
1121
+ `createWorkflowTool(${JSON.stringify(config.name)}): workflow run ${run.runId ? `'${run.runId}' ` : ""}failed with status '${run.status}'.`
1122
+ );
1123
+ }
1124
+ return typeof run.output === "string" ? run.output : JSON.stringify(run.output);
1125
+ }
1126
+ });
1127
+ }
1128
+
1129
+ // src/server/agent/acp-tool.ts
1130
+ import { spawn } from "child_process";
1131
+ import { AcpClient } from "@theokit/agents";
1132
+ import { encodeAcpMessage } from "@theokit/agents";
1133
+ var NodeAcpTransport = class {
1134
+ // stdin=pipe, stdout=pipe, stderr=inherit → the third stream is null.
1135
+ proc;
1136
+ constructor(command, args = [], cwd) {
1137
+ this.proc = spawn(command, args, { cwd, stdio: ["pipe", "pipe", "inherit"] });
1138
+ }
1139
+ send(line) {
1140
+ this.proc.stdin.write(line);
1141
+ }
1142
+ subscribe(onData) {
1143
+ this.proc.stdout.on("data", (buf) => {
1144
+ onData(buf.toString("utf8"));
1145
+ });
1146
+ }
1147
+ close() {
1148
+ this.proc.kill();
1149
+ }
1150
+ };
1151
+ function defaultTransport(config) {
1152
+ return new NodeAcpTransport(config.command, config.args, config.cwd);
1153
+ }
1154
+ function createACPTool(config) {
1155
+ if (typeof config.onPermissionRequest !== "function") {
1156
+ throw new Error("[theokit] createACPTool requires onPermissionRequest (security by default \u2014 no default-allow)");
1157
+ }
1158
+ const makeTransport = config.transportFactory ?? defaultTransport;
1159
+ return {
1160
+ name: config.name,
1161
+ description: config.description,
1162
+ inputSchema: {
1163
+ type: "object",
1164
+ properties: { message: { type: "string", description: "The task/prompt for the coding agent." } },
1165
+ required: ["message"]
1166
+ },
1167
+ handler: async (input) => {
1168
+ const message = typeof input.message === "string" ? input.message : "";
1169
+ const client = new AcpClient(makeTransport(config));
1170
+ client.onRequest("session/request_permission", (params) => config.onPermissionRequest(params));
1171
+ const result = await client.request("session/prompt", { message });
1172
+ return result.text ?? "";
1173
+ }
1174
+ };
1175
+ }
1176
+
1177
+ // src/server/agent/vendor-agent-tool.ts
1178
+ function createVendorAgentTool(config) {
1179
+ if (!config.vendor || config.vendor.length === 0) {
1180
+ throw new Error('createVendorAgentTool: `vendor` is required (e.g. "claude", "openai").');
1181
+ }
1182
+ const queryFn = config.client?.query;
1183
+ if (typeof queryFn !== "function") {
1184
+ throw new Error(
1185
+ `createVendorAgentTool(${JSON.stringify(config.vendor)}): the vendor client does not expose a query() method. Pass the vendor SDK client (or a @theokit/agent-* wrapper).`
1186
+ );
1187
+ }
1188
+ const name = config.name ?? `${config.vendor}_agent`;
1189
+ const description = config.description ?? `Delegate a task to the ${config.vendor} agent and return its answer.`;
1190
+ return {
1191
+ name,
1192
+ description,
1193
+ inputSchema: {
1194
+ type: "object",
1195
+ properties: {
1196
+ prompt: { type: "string", description: "The task/prompt for the vendor agent." },
1197
+ resumeSessionId: {
1198
+ type: "string",
1199
+ description: "Optional vendor session id to resume a prior conversation."
1200
+ }
1201
+ },
1202
+ required: ["prompt"]
1203
+ },
1204
+ handler: async (input) => {
1205
+ const prompt = typeof input.prompt === "string" ? input.prompt : "";
1206
+ const resumeSessionId = typeof input.resumeSessionId === "string" ? input.resumeSessionId : void 0;
1207
+ const result = await config.client.query(
1208
+ prompt,
1209
+ resumeSessionId !== void 0 ? { resumeSessionId } : void 0
1210
+ );
1211
+ if (result.sessionId !== void 0 && config.onSession) config.onSession(result.sessionId);
1212
+ return result.text;
1213
+ }
1214
+ };
1215
+ }
1216
+
1217
+ // src/server/agent/code-mode.ts
1218
+ var CodeModePermissionDeniedError = class extends Error {
1219
+ constructor(tool, reason) {
1220
+ const suffix = reason ? `: ${reason}` : "";
1221
+ super(`code-mode: tool '${tool}' denied by permission gate${suffix}`);
1222
+ this.name = "CodeModePermissionDeniedError";
1223
+ }
1224
+ };
1225
+ function createCodeMode(config) {
1226
+ if (typeof config.onPermissionRequest !== "function") {
1227
+ throw new Error(
1228
+ "createCodeMode requires onPermissionRequest (security by default \u2014 no default-allow for any tool)."
1229
+ );
1230
+ }
1231
+ const sandboxRun = config.sandbox?.run;
1232
+ if (typeof sandboxRun !== "function") {
1233
+ throw new Error(
1234
+ "createCodeMode requires an injected `sandbox` with a run() method (a vetted isolation boundary \u2014 never node:vm)."
1235
+ );
1236
+ }
1237
+ const api = {};
1238
+ for (const tool of config.tools) {
1239
+ api[tool.name] = async (args) => {
1240
+ const decision = await config.onPermissionRequest({ tool: tool.name, args });
1241
+ if (!decision.granted) throw new CodeModePermissionDeniedError(tool.name, decision.reason);
1242
+ return tool.handler(args);
1243
+ };
1244
+ }
1245
+ return {
1246
+ name: config.name ?? "run_code",
1247
+ description: config.description ?? "Run code that composes the available tools. Only the declared tools are callable.",
1248
+ inputSchema: {
1249
+ type: "object",
1250
+ properties: { code: { type: "string", description: "The code to run in the sandbox." } },
1251
+ required: ["code"]
1252
+ },
1253
+ handler: async (input) => {
1254
+ const code = typeof input.code === "string" ? input.code : "";
1255
+ const result = await config.sandbox.run(code, api);
1256
+ return typeof result === "string" ? result : JSON.stringify(result);
1257
+ }
1258
+ };
1259
+ }
1260
+
1261
+ // src/server/agent/channel-webhook.ts
1262
+ var CHANNEL_PATH = /^\/api\/agents\/([^/]+)\/channels\/([^/]+)\/webhook$/;
1263
+ function parseChannelPath(urlPath) {
1264
+ const match = CHANNEL_PATH.exec(urlPath);
1265
+ if (!match) return null;
1266
+ return { agent: decodeURIComponent(match[1]), platform: decodeURIComponent(match[2]) };
1267
+ }
1268
+ function isChannelPath(urlPath) {
1269
+ return CHANNEL_PATH.test(urlPath);
1270
+ }
1271
+ function jsonError(status, code, message) {
1272
+ return new Response(JSON.stringify({ error: { code, message } }), {
1273
+ status,
1274
+ headers: { "content-type": "application/json" }
1275
+ });
1276
+ }
1277
+ async function handleChannelWebhook(request, urlPath, config) {
1278
+ const parsed = parseChannelPath(urlPath);
1279
+ if (parsed === null) {
1280
+ return jsonError(
1281
+ 400,
1282
+ "BAD_REQUEST",
1283
+ "Path must be /api/agents/<name>/channels/<platform>/webhook."
1284
+ );
1285
+ }
1286
+ if (!Object.hasOwn(config.validators, parsed.platform)) {
1287
+ return jsonError(
1288
+ 404,
1289
+ "UNKNOWN_PLATFORM",
1290
+ `No validator configured for platform '${parsed.platform}'.`
1291
+ );
1292
+ }
1293
+ const verify = config.validators[parsed.platform];
1294
+ const verifyResult = await verify(request.clone());
1295
+ if (!verifyResult.ok) {
1296
+ return jsonError(
1297
+ 401,
1298
+ "INVALID_SIGNATURE",
1299
+ `Signature validation failed: ${verifyResult.reason}`
1300
+ );
1301
+ }
1302
+ let payload;
1303
+ try {
1304
+ payload = await request.json();
1305
+ } catch {
1306
+ return jsonError(400, "BAD_REQUEST", "Request body must be JSON.");
1307
+ }
1308
+ await config.onMessage({ agent: parsed.agent, platform: parsed.platform, payload });
1309
+ return new Response(JSON.stringify({ ok: true }), {
1310
+ status: 200,
1311
+ headers: { "content-type": "application/json" }
1312
+ });
1313
+ }
1314
+
1098
1315
  // src/server/serialization.ts
1099
1316
  import superjson from "superjson";
1100
1317
  function serializeResponse(data) {
@@ -1140,6 +1357,7 @@ export {
1140
1357
  CSRF_WARN_CODE,
1141
1358
  CSRF_WARN_DOCS_URL,
1142
1359
  ChannelManager,
1360
+ CodeModePermissionDeniedError,
1143
1361
  ConsoleObservabilityAdapter,
1144
1362
  CsrfReadinessStore,
1145
1363
  DEFAULT_CSP,
@@ -1162,6 +1380,7 @@ export {
1162
1380
  JOB_MANIFEST_SCHEMA_VERSION,
1163
1381
  JsonStdoutSink,
1164
1382
  MAX_ERROR_HTML_BYTES,
1383
+ NodeAcpTransport,
1165
1384
  NonRetryableError,
1166
1385
  NoopObservabilityAdapter,
1167
1386
  NoopSpan,
@@ -1185,16 +1404,20 @@ export {
1185
1404
  appendCookieToHeaders,
1186
1405
  appendDeleteCookieToHeaders,
1187
1406
  applySecurityHeaders,
1407
+ applyTransform,
1188
1408
  assertProductionSecret,
1189
1409
  buildCronManifest,
1190
1410
  buildJobManifest,
1411
+ buildResourceDescriptors,
1191
1412
  buildSecurityHeaders,
1192
1413
  checkThrottle,
1193
1414
  clearOidcCache,
1194
1415
  compilePattern,
1195
1416
  compileRouteRules,
1196
1417
  convertToAwsCron,
1418
+ createACPTool,
1197
1419
  createCacheEngine,
1420
+ createCodeMode,
1198
1421
  createCorsHandler,
1199
1422
  createCorsWebHandler,
1200
1423
  createCronScheduler,
@@ -1214,10 +1437,13 @@ export {
1214
1437
  createRouteRateLimiterWeb,
1215
1438
  createSessionManager,
1216
1439
  createSessionManagerWeb,
1440
+ createVendorAgentTool,
1217
1441
  createViteLoader,
1442
+ createWorkflowTool,
1218
1443
  decrypt,
1219
1444
  defineAction,
1220
1445
  defineAgentTool,
1446
+ defineAppResource,
1221
1447
  defineCachedFunction,
1222
1448
  defineCachedRoute,
1223
1449
  defineChannel,
@@ -1265,6 +1491,7 @@ export {
1265
1491
  getCookieFromRequest,
1266
1492
  getStorageManager,
1267
1493
  handleBatchRequest,
1494
+ handleChannelWebhook,
1268
1495
  handleCspReport,
1269
1496
  handleCspReportRequest,
1270
1497
  handleCsrfReadiness,
@@ -1273,6 +1500,7 @@ export {
1273
1500
  handleWebRequestError,
1274
1501
  initCacheEngine,
1275
1502
  isActionError,
1503
+ isChannelPath,
1276
1504
  isInputError,
1277
1505
  jsonTransformer,
1278
1506
  levenshtein,
@@ -1286,10 +1514,12 @@ export {
1286
1514
  matchesOrigin,
1287
1515
  normalizeLegacy,
1288
1516
  normalizeNew,
1517
+ parseChannelPath,
1289
1518
  parseCookieHeader,
1290
1519
  parseRequestBody,
1291
1520
  parseTraceparent,
1292
1521
  pkceChallengeFromVerifier,
1522
+ readAppResource,
1293
1523
  readRawBody,
1294
1524
  recordAttempt,
1295
1525
  requireAuth,