theokit 0.79.0 → 0.80.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 (55) hide show
  1. package/dist/adapters/agent-mount.js +2 -2
  2. package/dist/{agent-63GCHUHH.js → agent-OM47ZAIN.js} +2 -2
  3. package/dist/{build-DOYXIZWZ.js → build-TQAYRHJH.js} +2 -2
  4. package/dist/{chunk-3GM4GACM.js → chunk-2Z3GHQ64.js} +22 -9
  5. package/dist/{chunk-3GM4GACM.js.map → chunk-2Z3GHQ64.js.map} +1 -1
  6. package/dist/{chunk-7MCEJVGV.js → chunk-APUYC5BE.js} +2 -2
  7. package/dist/{chunk-PYEDWJF7.js → chunk-C5H2JHDW.js} +23 -10
  8. package/dist/chunk-C5H2JHDW.js.map +1 -0
  9. package/dist/{chunk-DQIY2LUG.js → chunk-CFJN5JHJ.js} +2 -2
  10. package/dist/{chunk-RAUYMVUO.js → chunk-JUJI3FZM.js} +81 -111
  11. package/dist/chunk-JUJI3FZM.js.map +1 -0
  12. package/dist/{chunk-27FXSIGE.js → chunk-QEVTZ3IH.js} +2 -2
  13. package/dist/{chunk-3L6WU7J7.js → chunk-QKWBT7IY.js} +2 -2
  14. package/dist/{chunk-TQEE36VD.js → chunk-RN5NDLUS.js} +57 -45
  15. package/dist/{chunk-TQEE36VD.js.map → chunk-RN5NDLUS.js.map} +1 -1
  16. package/dist/{chunk-BDH5GKFZ.js → chunk-TF44PW3F.js} +43 -44
  17. package/dist/chunk-TF44PW3F.js.map +1 -0
  18. package/dist/{chunk-VSK5Y4ET.js → chunk-W55B6BRC.js} +2 -2
  19. package/dist/cli/index.js +8 -8
  20. package/dist/{db-LUOLKZJA.js → db-OHFGYI5J.js} +49 -15
  21. package/dist/db-OHFGYI5J.js.map +1 -0
  22. package/dist/{dev-MRB3LXAM.js → dev-CDCYJTDM.js} +5 -5
  23. package/dist/{docker-DINW3YV6.js → docker-ED6W4ILB.js} +12 -7
  24. package/dist/docker-ED6W4ILB.js.map +1 -0
  25. package/dist/index.js +3 -3
  26. package/dist/{mcp-LZALIEGI.js → mcp-4OM4QSYT.js} +8 -5
  27. package/dist/mcp-4OM4QSYT.js.map +1 -0
  28. package/dist/{preview-WDF723U3.js → preview-C52WW62N.js} +3 -3
  29. package/dist/server/agent/index.d.ts +33 -69
  30. package/dist/server/agent/index.js +6 -2
  31. package/dist/server/cron/index.js +1 -1
  32. package/dist/server/index.d.ts +2 -1
  33. package/dist/server/index.js +7 -3
  34. package/dist/server/index.js.map +1 -1
  35. package/dist/{start-GC3KJ22H.js → start-4NBJTPCR.js} +4 -4
  36. package/dist/vite-plugin/index.js +3 -3
  37. package/dist/{vite-plugin-CCZRY57Z.js → vite-plugin-CK5E4PA5.js} +4 -4
  38. package/package.json +6 -6
  39. package/dist/chunk-BDH5GKFZ.js.map +0 -1
  40. package/dist/chunk-PYEDWJF7.js.map +0 -1
  41. package/dist/chunk-RAUYMVUO.js.map +0 -1
  42. package/dist/db-LUOLKZJA.js.map +0 -1
  43. package/dist/docker-DINW3YV6.js.map +0 -1
  44. package/dist/mcp-LZALIEGI.js.map +0 -1
  45. /package/dist/{agent-63GCHUHH.js.map → agent-OM47ZAIN.js.map} +0 -0
  46. /package/dist/{build-DOYXIZWZ.js.map → build-TQAYRHJH.js.map} +0 -0
  47. /package/dist/{chunk-7MCEJVGV.js.map → chunk-APUYC5BE.js.map} +0 -0
  48. /package/dist/{chunk-DQIY2LUG.js.map → chunk-CFJN5JHJ.js.map} +0 -0
  49. /package/dist/{chunk-27FXSIGE.js.map → chunk-QEVTZ3IH.js.map} +0 -0
  50. /package/dist/{chunk-3L6WU7J7.js.map → chunk-QKWBT7IY.js.map} +0 -0
  51. /package/dist/{chunk-VSK5Y4ET.js.map → chunk-W55B6BRC.js.map} +0 -0
  52. /package/dist/{dev-MRB3LXAM.js.map → dev-CDCYJTDM.js.map} +0 -0
  53. /package/dist/{preview-WDF723U3.js.map → preview-C52WW62N.js.map} +0 -0
  54. /package/dist/{start-GC3KJ22H.js.map → start-4NBJTPCR.js.map} +0 -0
  55. /package/dist/{vite-plugin-CCZRY57Z.js.map → vite-plugin-CK5E4PA5.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server/agent/mcp-app-resources.ts","../src/server/agent/mcp-handler.ts"],"sourcesContent":["/**\n * M30 (ADR-0041) — MCP Apps: `ui://` HTML resources for the MCP server (M16).\n *\n * A tool can declare a `ui://` HTML resource; the MCP server advertises it via `resources/list` and\n * serves the HTML via `resources/read`. The client renders it in a SANDBOXED iframe (see\n * `mcp-app-host.ts`). Pure data transforms here — no LLM, no runtime (ADR-0040 § D2 home concern).\n *\n * Security: only the `ui://` scheme is accepted (an app UI resource), never `http(s)://` — the HTML\n * is rendered sandboxed on the client, and the scheme gate keeps a tool from smuggling a remote URL\n * into the app surface.\n */\n\n/** A declared `ui://` app resource. */\nexport interface AppResource {\n uri: string\n name: string\n mimeType: 'text/html'\n html: string\n description?: string\n}\n\n/** Input to {@link defineAppResource}. */\nexport interface AppResourceInput {\n /** MUST start with `ui://`. */\n uri: string\n name: string\n html: string\n description?: string\n}\n\n/** An MCP `resources/list` descriptor (no HTML body — that comes from `resources/read`). */\nexport interface McpResourceDescriptor {\n uri: string\n name: string\n mimeType: 'text/html'\n description?: string\n}\n\n/** An MCP `resources/read` result. */\nexport interface McpResourceContents {\n contents: { uri: string; mimeType: 'text/html'; text: string }[]\n}\n\n/**\n * Declare a `ui://` HTML app resource. Fails fast if the uri is not a `ui://` scheme or the HTML is\n * empty (error-handling.md) — a misconfigured resource is caught at definition time.\n */\nexport function defineAppResource(input: AppResourceInput): AppResource {\n if (!input.uri.startsWith('ui://')) {\n throw new Error(\n `defineAppResource: uri must use the ui:// scheme (an app UI resource). Got: ${JSON.stringify(input.uri)}`,\n )\n }\n if (input.html.length === 0) {\n throw new Error(`defineAppResource(${JSON.stringify(input.uri)}): html must be non-empty.`)\n }\n return {\n uri: input.uri,\n name: input.name,\n mimeType: 'text/html',\n html: input.html,\n ...(input.description !== undefined ? { description: input.description } : {}),\n }\n}\n\n/** Map app resources to MCP `resources/list` descriptors (the HTML body is omitted from the list). */\nexport function buildResourceDescriptors(\n resources: readonly AppResource[],\n): McpResourceDescriptor[] {\n return resources.map((r) => ({\n uri: r.uri,\n name: r.name,\n mimeType: r.mimeType,\n ...(r.description !== undefined ? { description: r.description } : {}),\n }))\n}\n\n/** Serve the HTML for `uri` as an MCP `resources/read` result, or `null` when unknown. */\nexport function readAppResource(\n resources: readonly AppResource[],\n uri: string,\n): McpResourceContents | null {\n const found = resources.find((r) => r.uri === uri)\n if (!found) return null\n return { contents: [{ uri: found.uri, mimeType: 'text/html', text: found.html }] }\n}\n\n/** True when `v` is a well-formed {@link AppResource} (from `defineAppResource`). */\nfunction isAppResource(v: unknown): v is AppResource {\n if (typeof v !== 'object' || v === null) return false\n const r = v as Record<string, unknown>\n return (\n typeof r.uri === 'string' &&\n r.uri.startsWith('ui://') &&\n r.mimeType === 'text/html' &&\n typeof r.html === 'string'\n )\n}\n\n/**\n * M30 wiring — extract the App resources an agent module declares via a named `appResources` export\n * (`export const appResources = [defineAppResource(...)]`). Returns only the well-formed entries; a\n * module without the export (or with a malformed one) yields `[]`. This is how per-agent `ui://`\n * resources reach the MCP server's `resources/list` + `resources/read` without a runtime dependency\n * from `@theokit/agents` on this theo-side type (the module exports them; the serving path reads them).\n */\nexport function extractAppResources(mod: unknown): AppResource[] {\n const raw = (mod as { appResources?: unknown } | null | undefined)?.appResources\n if (!Array.isArray(raw)) return []\n return raw.filter(isAppResource)\n}\n","/**\n * M16 (theokit-ai-first) — serve an agent as an MCP server over HTTP at `/api/agents/<name>/mcp`.\n *\n * Answers the two core MCP methods over JSON-RPC 2.0: `initialize` (server info + capabilities) and\n * `tools/list` (the agent's tools as MCP descriptors, via `buildMcpToolDescriptors`). M30 adds\n * `resources/list` + `resources/read` for `ui://` App resources. Unknown methods return `-32601`\n * (method not found). Web Standards Response (G8). The stdio transport + full method set stay\n * SDK-side (sdk-runtime.md); this exposes the agent over the app's own HTTP route.\n */\nimport { type CompiledTool, compileLoadedAgentModule } from '@theokit/agents'\nimport type { CustomTool } from '@theokit/sdk'\n\nimport { type AppResource, buildResourceDescriptors, readAppResource } from './mcp-app-resources.js'\n\nconst MCP_PATH = /^\\/api\\/agents\\/([^/]+)\\/mcp$/\n\n/**\n * The MCP protocol revision THIS server transport implements (M34). The protocol version is a\n * property of the server that speaks it (this handler), not of the manifest data generator — so the\n * handler owns it. Current MCP revision (`2025-06-18`); replaces the stale `2024-11-05` the manifest\n * generator carried.\n */\nconst MCP_PROTOCOL_VERSION = '2025-06-18'\n\n/** An MCP `tools/list` descriptor with the tool's REAL input schema retained (M34 — no longer dropped). */\ninterface McpToolDescriptor {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n}\n\n/** Build tool descriptors from the compiled tools, retaining each tool's real JSON-Schema input (M34). */\nfunction toolDescriptors(tools: readonly CompiledTool[]): McpToolDescriptor[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n // The compiled tool already carries a JSON Schema (via `z.toJSONSchema()` in defineAgentTool).\n // Fall back to a permissive object only when a tool genuinely declared no schema.\n inputSchema:\n t.inputSchema && typeof t.inputSchema === 'object'\n ? (t.inputSchema as Record<string, unknown>)\n : { type: 'object', properties: {} },\n }))\n}\n\n/** An MCP `CallToolResult` — `content[]` + `isError` (the shape MCP clients expect). */\ninterface CallToolResult {\n content: { type: 'text'; text: string }[]\n isError?: boolean\n}\n\n/** Return the agent name when `urlPath` is the MCP endpoint, else `null`. */\nexport function isMcpPath(urlPath: string): string | null {\n const match = MCP_PATH.exec(urlPath)\n return match ? decodeURIComponent(match[1]) : null\n}\n\ntype JsonRpcId = number | string | null\n\ninterface JsonRpcRequest {\n jsonrpc: '2.0'\n id: JsonRpcId\n method: string\n params?: unknown\n}\n\nfunction isJsonRpcRequest(body: unknown): body is JsonRpcRequest {\n return (\n typeof body === 'object' &&\n body !== null &&\n (body as { jsonrpc?: unknown }).jsonrpc === '2.0' &&\n typeof (body as { method?: unknown }).method === 'string'\n )\n}\n\nfunction jsonResponse(payload: unknown): Response {\n return new Response(JSON.stringify(payload), {\n status: 200,\n headers: { 'content-type': 'application/json; charset=utf-8' },\n })\n}\n\n/**\n * Execute an MCP `tools/call` against the compiled tools (M34). Finds the tool by name, runs its\n * handler with the supplied `arguments`, and shapes the result into a `CallToolResult`. An unknown\n * tool or a throwing handler yields `{ isError: true }` (MCP convention — the model sees the failure)\n * rather than a JSON-RPC crash.\n */\nasync function callTool(\n tools: readonly CompiledTool[],\n toolName: unknown,\n args: unknown,\n hitl?: ReadonlyMap<string, unknown>,\n): Promise<CallToolResult> {\n if (typeof toolName !== 'string') {\n return {\n content: [{ type: 'text', text: 'tools/call requires a string `name`.' }],\n isError: true,\n }\n }\n const tool = tools.find((t) => t.name === toolName)\n if (!tool) {\n return { content: [{ type: 'text', text: `Unknown tool: ${toolName}` }], isError: true }\n }\n // #99 — REFUSE a HITL-gated tool. The approval gate (`compiled.hitl`) lives in the SDK run-loop,\n // not in the raw tool handler; executing the handler here would BYPASS the human approval the web/\n // TUI surfaces enforce. Over MCP there is no approval mechanism, so a gated tool is not callable —\n // return an error result instead of running it unguarded (fail-closed, Rule 8).\n if (hitl?.has(toolName)) {\n return {\n content: [\n {\n type: 'text',\n text: `Tool \"${toolName}\" requires human approval, which is not available over MCP. Refused.`,\n },\n ],\n isError: true,\n }\n }\n try {\n const result = await tool.handler(args)\n const text = typeof result === 'string' ? result : JSON.stringify(result)\n return { content: [{ type: 'text', text }] }\n } catch (err) {\n return {\n content: [\n { type: 'text', text: err instanceof Error ? err.message : 'Tool execution failed' },\n ],\n isError: true,\n }\n }\n}\n\n/** `resources/read` (M30) — extracted to keep `handleMcpJsonRpc` within the complexity budget. */\nfunction handleResourcesRead(\n id: JsonRpcId,\n params: unknown,\n appResources: readonly AppResource[],\n): Response {\n const uri = (params as { uri?: unknown } | undefined)?.uri\n if (typeof uri !== 'string') {\n return jsonResponse({\n jsonrpc: '2.0',\n id,\n error: { code: -32602, message: 'resources/read requires a string `uri` param.' },\n })\n }\n const contents = readAppResource(appResources, uri)\n if (contents === null) {\n return jsonResponse({\n jsonrpc: '2.0',\n id,\n error: { code: -32602, message: `Resource not found: ${uri}` },\n })\n }\n return jsonResponse({ jsonrpc: '2.0', id, result: contents })\n}\n\n/** What a JSON-RPC dispatch serves: compiled tools, their approval gate, and any App resources. */\ninterface McpServed {\n tools: readonly CompiledTool[]\n hitl?: ReadonlyMap<string, unknown>\n appResources: readonly AppResource[]\n}\n\nfunction rpcResult(id: JsonRpcId, result: unknown): Response {\n return jsonResponse({ jsonrpc: '2.0', id, result })\n}\n\nfunction initializeResult(name: string, appResources: readonly AppResource[]): unknown {\n const capabilities: Record<string, unknown> = { tools: {} }\n if (appResources.length > 0) capabilities.resources = {}\n return {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities,\n serverInfo: { name, version: '1.0' },\n }\n}\n\n/** Dispatch one validated request over the served tools. Shared by the agent and tool-list entry points. */\nasync function dispatchMcp(\n served: McpServed,\n name: string,\n { id, method, params }: JsonRpcRequest,\n): Promise<Response> {\n switch (method) {\n case 'initialize':\n return rpcResult(id, initializeResult(name, served.appResources))\n case 'tools/list':\n return rpcResult(id, { tools: toolDescriptors(served.tools) })\n case 'tools/call': {\n const p = params as { name?: unknown; arguments?: unknown } | undefined\n return rpcResult(id, await callTool(served.tools, p?.name, p?.arguments ?? {}, served.hitl))\n }\n case 'resources/list':\n return rpcResult(id, { resources: buildResourceDescriptors(served.appResources) })\n case 'resources/read':\n return handleResourcesRead(id, params, served.appResources)\n default:\n return jsonResponse({\n jsonrpc: '2.0',\n id,\n error: { code: -32601, message: `Method not found: ${method}` },\n })\n }\n}\n\n/** Validate the envelope, then run `serve` and map any throw to a `-32603` error envelope. */\nasync function runMcp(\n body: unknown,\n serve: (req: JsonRpcRequest) => Promise<Response>,\n): Promise<Response> {\n if (!isJsonRpcRequest(body)) {\n return jsonResponse({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32600, message: 'Invalid Request' },\n })\n }\n try {\n return await serve(body)\n } catch (err) {\n return jsonResponse({\n jsonrpc: '2.0',\n id: body.id,\n error: { code: -32603, message: err instanceof Error ? err.message : 'Internal error' },\n })\n }\n}\n\n/**\n * Handle one MCP JSON-RPC request for an agent module. Always returns a 200 JSON-RPC envelope.\n *\n * M30 — `appResources` (optional) are the agent's declared `ui://` App resources; when present the\n * server advertises `capabilities.resources` and answers `resources/list` + `resources/read`.\n */\nexport function handleMcpJsonRpc(\n mod: unknown,\n name: string,\n body: unknown,\n appResources: readonly AppResource[] = [],\n): Promise<Response> {\n return runMcp(body, (req) => {\n const compiled = compileLoadedAgentModule(mod, `mcp server for \"${name}\"`)\n return dispatchMcp({ tools: compiled.tools, hitl: compiled.hitl, appResources }, name, req)\n })\n}\n\n/** Throw on the first duplicate tool name: an MCP client could not tell the two apart. */\nfunction assertUniqueToolNames(tools: readonly CustomTool[]): void {\n const seen = new Set<string>()\n for (const t of tools) {\n if (seen.has(t.name)) throw new Error(`Duplicate MCP tool name: \"${t.name}\"`)\n seen.add(t.name)\n }\n}\n\n/**\n * Handle one MCP JSON-RPC request for a plain list of tools (no agent module). Same JSON-RPC\n * handling as {@link handleMcpJsonRpc}; advertises `capabilities.tools` only (no resources).\n *\n * There is NO approval gate: a list of tools carries no human-approval policy, so none is refused as\n * \"requires human approval\". Whoever passes a tool in decides it may run unattended.\n *\n * @throws when two tools share a name (checked when called, before any request is answered).\n */\nexport function handleMcpToolsJsonRpc(\n tools: readonly CustomTool[],\n name: string,\n body: unknown,\n): Promise<Response> {\n assertUniqueToolNames(tools)\n const served: McpServed = { tools: tools as readonly CompiledTool[], appResources: [] }\n return runMcp(body, (req) => dispatchMcp(served, name, req))\n}\n"],"mappings":";;;;AAkEO,SAAS,yBACd,WACyB;AACzB,SAAO,UAAU,IAAI,CAAC,OAAO;AAAA,IAC3B,KAAK,EAAE;AAAA,IACP,M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AO,aAAa;AAAA,QAClB,SAAS;AAAA,QACT;AAAA,QACA,OAAO,EAAE,MAAM,QAAQ,SAAS,qBAAqB,MAAM,GAAG;AAAA,MAChE,CAAC;AAAA,EACL;AACF;AAGA,eAAe,OACb,MACA,OACmB;AACnB,MAAI,CAAC,iBAAiB,IAAI,GAAG;AAC3B,WAAO,aAAa;AAAA,MAClB,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,OAAO,EAAE,MAAM,QAAQ,SAAS,kBAAkB;AAAA,IACpD,CAAC;AAAA,EACH;AACA,MAAI;AACF,WAAO,MAAM,MAAM,IAAI;AAAA,EACzB,SAAS,KAAK;AACZ,WAAO,aAAa;AAAA,MAClB,SAAS;AAAA,MACT,IAAI,KAAK;AAAA,MACT,OAAO,EAAE,MAAM,QAAQ,SAAS,eAAe,QAAQ,IAAI,UAAU,iBAAiB;AAAA,IACxF,CAAC;AAAA,EACH;AACF;AAQO,SAAS,iBACd,KACA,MACA,MACA,eAAuC,CAAC,GACrB;AACnB,SAAO,OAAO,MAAM,CAAC,QAAQ;AAC3B,UAAM,WAAW,yBAAyB,KAAK,mBAAmB,IAAI,GAAG;AACzE,WAAO,YAAY,EAAE,OAAO,SAAS,OAAO,MAAM,SAAS,MAAM,aAAa,GAAG,MAAM,GAAG;AAAA,EAC5F,CAAC;AACH;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  extractAppResources,
5
5
  handleMcpJsonRpc,
6
6
  isMcpPath
7
- } from "./chunk-BDH5GKFZ.js";
7
+ } from "./chunk-TF44PW3F.js";
8
8
  import {
9
9
  findRootDiv
10
10
  } from "./chunk-3PWQQWT6.js";
@@ -954,4 +954,4 @@ export {
954
954
  applyNonceToInlineScripts,
955
955
  setupSsrDevMiddleware
956
956
  };
957
- //# sourceMappingURL=chunk-VSK5Y4ET.js.map
957
+ //# sourceMappingURL=chunk-W55B6BRC.js.map
package/dist/cli/index.js CHANGED
@@ -15,7 +15,7 @@ function cliVersion() {
15
15
  // src/cli/index.ts
16
16
  var cli = cac("theokit");
17
17
  cli.command("dev", "Start development server").option("--port <port>", "Port number").option("--crons", "Schedule the crons in dev too (off by default)").action(async (options) => {
18
- const { devCommand } = await import("../dev-MRB3LXAM.js");
18
+ const { devCommand } = await import("../dev-CDCYJTDM.js");
19
19
  await devCommand({
20
20
  port: options.port ? Number(options.port) : void 0,
21
21
  crons: options.crons === true
@@ -23,7 +23,7 @@ cli.command("dev", "Start development server").option("--port <port>", "Port num
23
23
  });
24
24
  cli.command("build", "Build for production").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
25
25
  try {
26
- const { buildCommand } = await import("../build-DOYXIZWZ.js");
26
+ const { buildCommand } = await import("../build-TQAYRHJH.js");
27
27
  await buildCommand({ target: options.target });
28
28
  } catch (err) {
29
29
  const msg = err instanceof Error ? err.message : String(err);
@@ -35,7 +35,7 @@ cli.command("build", "Build for production").option("--target <target>", "Deploy
35
35
  });
36
36
  cli.command("start", "Start production server").option("--port <port>", "Port number").action(async (options) => {
37
37
  try {
38
- const { startCommand } = await import("../start-GC3KJ22H.js");
38
+ const { startCommand } = await import("../start-4NBJTPCR.js");
39
39
  await startCommand({ port: options.port ? Number(options.port) : void 0 });
40
40
  } catch (err) {
41
41
  const msg = err instanceof Error ? err.message : String(err);
@@ -47,7 +47,7 @@ cli.command("start", "Start production server").option("--port <port>", "Port nu
47
47
  });
48
48
  cli.command("preview", "Build for production, then serve it \u2014 one step (B-030)").option("--port <port>", "Port number").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
49
49
  try {
50
- const { previewCommand } = await import("../preview-WDF723U3.js");
50
+ const { previewCommand } = await import("../preview-C52WW62N.js");
51
51
  await previewCommand({
52
52
  port: options.port ? Number(options.port) : void 0,
53
53
  target: options.target
@@ -80,7 +80,7 @@ cli.command(
80
80
  "Run an agent in the terminal (stream + tool calls + approval)"
81
81
  ).action(async (name, message) => {
82
82
  try {
83
- const { agentCommand } = await import("../agent-63GCHUHH.js");
83
+ const { agentCommand } = await import("../agent-OM47ZAIN.js");
84
84
  const { sawError } = await agentCommand(name, message);
85
85
  if (sawError) process.exit(1);
86
86
  } catch (err) {
@@ -111,7 +111,7 @@ cli.command("agent sessions gc", "Collect old transcripts for this project (dry
111
111
  });
112
112
  cli.command("mcp <agent>", "Serve an agent as an MCP server over stdio (for desktop MCP clients)").action(async (agent) => {
113
113
  try {
114
- const { mcpCommand } = await import("../mcp-LZALIEGI.js");
114
+ const { mcpCommand } = await import("../mcp-4OM4QSYT.js");
115
115
  await mcpCommand(agent);
116
116
  } catch (err) {
117
117
  const msg = err instanceof Error ? err.message : String(err);
@@ -223,7 +223,7 @@ cli.command(
223
223
  });
224
224
  cli.command("docker", "Generate Dockerfile for production").option("--force", "Overwrite existing Dockerfile").action(async (options) => {
225
225
  try {
226
- const { dockerCommand } = await import("../docker-DINW3YV6.js");
226
+ const { dockerCommand } = await import("../docker-ED6W4ILB.js");
227
227
  await dockerCommand({ force: options.force });
228
228
  } catch (err) {
229
229
  const msg = err instanceof Error ? err.message : String(err);
@@ -238,7 +238,7 @@ cli.command(
238
238
  "Database commands: generate (write SQL migration files), migrate (apply them), push (diff the schema into the database, no files), seed"
239
239
  ).action(async (action) => {
240
240
  try {
241
- const { dbCommandCli } = await import("../db-LUOLKZJA.js");
241
+ const { dbCommandCli } = await import("../db-OHFGYI5J.js");
242
242
  await dbCommandCli(action);
243
243
  } catch (err) {
244
244
  const msg = err instanceof Error ? err.message : String(err);
@@ -7,15 +7,31 @@ import "./chunk-3QPVEJ7D.js";
7
7
  import "./chunk-O5JZ6ROY.js";
8
8
  import "./chunk-OS55GAM5.js";
9
9
  import "./chunk-L4V5V2TI.js";
10
- import "./chunk-MAJZ2L3A.js";
10
+ import {
11
+ storageSchema
12
+ } from "./chunk-MAJZ2L3A.js";
11
13
 
12
14
  // src/cli/commands/db.ts
13
- import { execSync } from "child_process";
14
- import { existsSync } from "fs";
15
- import { join, resolve } from "path";
15
+ import { execFileSync } from "child_process";
16
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
17
+ import { createRequire } from "module";
18
+ import { dirname, join, resolve } from "path";
16
19
  var VALID_ACTIONS = /* @__PURE__ */ new Set(["migrate", "push", "generate", "seed"]);
17
- var runInherited = (command, cwd) => {
18
- execSync(command, { cwd, stdio: "inherit" });
20
+ function resolveToolBin(cwd, tool) {
21
+ const req = createRequire(join(cwd, "package.json"));
22
+ let pkgPath;
23
+ try {
24
+ pkgPath = req.resolve(`${tool}/package.json`);
25
+ } catch {
26
+ throw new Error(`${tool} not found. Run: npm install -D ${tool}`);
27
+ }
28
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
29
+ const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.[tool];
30
+ if (rel === void 0) throw new Error(`${tool} has no "${tool}" bin in its package.json`);
31
+ return resolve(dirname(pkgPath), rel);
32
+ }
33
+ var runInherited = (tool, args, cwd) => {
34
+ execFileSync(process.execPath, [resolveToolBin(cwd, tool), ...args], { cwd, stdio: "inherit" });
19
35
  };
20
36
  function assertFileExists(cwd, relPath, hint) {
21
37
  if (!existsSync(resolve(cwd, relPath))) {
@@ -29,16 +45,33 @@ function assertBinExists(cwd, bin) {
29
45
  }
30
46
  }
31
47
  var DRIZZLE_KIT_VERBS = {
32
- migrate: { command: "npx drizzle-kit migrate", message: "Migrations applied" },
33
- push: { command: "npx drizzle-kit push", message: "Schema pushed to the database" },
34
- generate: { command: "npx drizzle-kit generate", message: "Migration files generated" }
48
+ migrate: { args: ["drizzle-kit", "migrate"], message: "Migrations applied" },
49
+ push: { args: ["drizzle-kit", "push"], message: "Schema pushed to the database" },
50
+ generate: { args: ["drizzle-kit", "generate"], message: "Migration files generated" }
35
51
  };
36
52
  async function runSeed(cwd, run) {
37
- const { serverDir } = await loadConfig(cwd);
53
+ const { serverDir, storage } = await loadConfig(cwd);
38
54
  const seedPath = join(serverDir, "db", "seed.ts");
39
55
  assertFileExists(cwd, seedPath, `Create ${seedPath} with your seed data.`);
40
56
  console.log("\n \u25B8 Running seed...\n");
41
- run(`npx tsx ${seedPath}`, cwd);
57
+ const preloadDir = resolve(cwd, "node_modules", ".cache", "theokit");
58
+ const preload = join(preloadDir, "seed-preload.mjs");
59
+ const hasStorage = storage !== void 0;
60
+ if (hasStorage) {
61
+ mkdirSync(preloadDir, { recursive: true });
62
+ const parsed = JSON.stringify(storageSchema.parse(storage));
63
+ writeFileSync(
64
+ preload,
65
+ `import { getStorageManager } from 'theokit/server/storage'
66
+ getStorageManager().configure(${parsed})
67
+ `
68
+ );
69
+ }
70
+ try {
71
+ run("tsx", hasStorage ? ["--import", preload, seedPath] : [seedPath], cwd);
72
+ } finally {
73
+ if (hasStorage) rmSync(preload, { force: true });
74
+ }
42
75
  return "Database seeded successfully";
43
76
  }
44
77
  async function dbCommand(action, cwd, run = runInherited) {
@@ -57,9 +90,9 @@ async function dbCommand(action, cwd, run = runInherited) {
57
90
  assertFileExists(cwd, "drizzle.config.ts", "Create a drizzle.config.ts for your project.");
58
91
  assertBinExists(cwd, "drizzle-kit");
59
92
  console.log(`
60
- \u25B8 Running ${verb.command.replace("npx ", "")}...
93
+ \u25B8 Running ${verb.args.join(" ")}...
61
94
  `);
62
- run(verb.command, cwd);
95
+ run("drizzle-kit", verb.args.slice(1), cwd);
63
96
  return { status: "success", message: verb.message, action: dbAction };
64
97
  } catch (err) {
65
98
  const msg = err instanceof Error ? err.message : String(err);
@@ -81,6 +114,7 @@ async function dbCommandCli(action) {
81
114
  }
82
115
  export {
83
116
  dbCommand,
84
- dbCommandCli
117
+ dbCommandCli,
118
+ resolveToolBin
85
119
  };
86
- //# sourceMappingURL=db-LUOLKZJA.js.map
120
+ //# sourceMappingURL=db-OHFGYI5J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/db.ts"],"sourcesContent":["import { execFileSync } from 'node:child_process'\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join, resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { storageSchema } from '../../config/schema.js'\n\ntype DbAction = 'migrate' | 'push' | 'generate' | 'seed'\n\nconst VALID_ACTIONS = new Set<DbAction>(['migrate', 'push', 'generate', 'seed'])\n\ninterface DbCommandResult {\n status: 'success' | 'error' | 'invalid_action'\n message: string\n action?: DbAction\n}\n\ntype DbTool = 'drizzle-kit' | 'tsx'\n\n/**\n * Runs one of the project's own tools, without a shell: the tool name and its argv, so a path with a\n * space or a quote is never parsed. Injected so a test can see the command without running it.\n */\ntype RunCommand = (tool: DbTool, args: readonly string[], cwd: string) => void\n\n/**\n * The JS entry of a tool installed in the project, read from its package.json `bin`. Running it with\n * `process.execPath` needs neither a shell nor `npx`/`.cmd` shims, which Node refuses to spawn\n * without a shell on Windows (CVE-2024-27980).\n */\nexport function resolveToolBin(cwd: string, tool: DbTool): string {\n const req = createRequire(join(cwd, 'package.json'))\n let pkgPath: string\n try {\n pkgPath = req.resolve(`${tool}/package.json`)\n } catch {\n throw new Error(`${tool} not found. Run: npm install -D ${tool}`)\n }\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[tool]\n if (rel === undefined) throw new Error(`${tool} has no \"${tool}\" bin in its package.json`)\n return resolve(dirname(pkgPath), rel)\n}\n\nconst runInherited: RunCommand = (tool, args, cwd) => {\n execFileSync(process.execPath, [resolveToolBin(cwd, tool), ...args], { cwd, stdio: 'inherit' })\n}\n\nfunction assertFileExists(cwd: string, relPath: string, hint: string): void {\n if (!existsSync(resolve(cwd, relPath))) {\n throw new Error(`${relPath} not found. ${hint}`)\n }\n}\n\nfunction assertBinExists(cwd: string, bin: string): void {\n const binPath = resolve(cwd, 'node_modules', '.bin', bin)\n if (!existsSync(binPath)) {\n throw new Error(`${bin} not found. Run: npm install -D ${bin}`)\n }\n}\n\n/**\n * Each verb runs the drizzle-kit command of the same name.\n *\n * `migrate` used to run `drizzle-kit push` (usetheokit/theokit#1021). Push diffs the schema straight\n * into the database: it never reads the files `generate` writes and keeps no\n * `drizzle.__drizzle_migrations` journal, so a deploy script calling `theokit db migrate` applied\n * an unreviewed diff with no record of it. `migrate` now applies the generated files, and the old\n * behaviour stays available, under its real name, as `push`.\n */\nconst DRIZZLE_KIT_VERBS = {\n migrate: { args: ['drizzle-kit', 'migrate'], message: 'Migrations applied' },\n push: { args: ['drizzle-kit', 'push'], message: 'Schema pushed to the database' },\n generate: { args: ['drizzle-kit', 'generate'], message: 'Migration files generated' },\n} as const\n\nasync function runSeed(cwd: string, run: RunCommand): Promise<string> {\n // The seed file lives under the configured `serverDir`; a hardcoded `server/` missed the\n // scaffold's `src/server` layout.\n const { serverDir, storage } = await loadConfig(cwd)\n const seedPath = join(serverDir, 'db', 'seed.ts')\n assertFileExists(cwd, seedPath, `Create ${seedPath} with your seed data.`)\n console.log('\\n ▸ Running seed...\\n')\n // #1439 — the seed is a bare child process, so `config.storage` never reached its storage manager\n // and any seed importing a `usePostgres('main', ...)` module threw \"Database not configured\".\n // A preload applies the parsed storage config through the project's own `theokit` instance.\n const preloadDir = resolve(cwd, 'node_modules', '.cache', 'theokit')\n const preload = join(preloadDir, 'seed-preload.mjs')\n const hasStorage = storage !== undefined\n if (hasStorage) {\n mkdirSync(preloadDir, { recursive: true })\n const parsed = JSON.stringify(storageSchema.parse(storage))\n writeFileSync(\n preload,\n `import { getStorageManager } from 'theokit/server/storage'\\ngetStorageManager().configure(${parsed})\\n`,\n )\n }\n try {\n run('tsx', hasStorage ? ['--import', preload, seedPath] : [seedPath], cwd)\n } finally {\n if (hasStorage) rmSync(preload, { force: true })\n }\n return 'Database seeded successfully'\n}\n\nexport async function dbCommand(\n action: string,\n cwd: string,\n run: RunCommand = runInherited,\n): Promise<DbCommandResult> {\n if (!VALID_ACTIONS.has(action as DbAction)) {\n return {\n status: 'invalid_action',\n message: `Unknown db action \"${action}\". Available: ${[...VALID_ACTIONS].join(', ')}`,\n }\n }\n\n const dbAction = action as DbAction\n\n try {\n if (dbAction === 'seed') {\n return { status: 'success', message: await runSeed(cwd, run), action: dbAction }\n }\n const verb = DRIZZLE_KIT_VERBS[dbAction]\n assertFileExists(cwd, 'drizzle.config.ts', 'Create a drizzle.config.ts for your project.')\n assertBinExists(cwd, 'drizzle-kit')\n console.log(`\\n ▸ Running ${verb.args.join(' ')}...\\n`)\n run('drizzle-kit', verb.args.slice(1), cwd)\n return { status: 'success', message: verb.message, action: dbAction }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { status: 'error', message: msg, action: dbAction }\n }\n}\n\nexport async function dbCommandCli(action: string): Promise<void> {\n const result = await dbCommand(action, process.cwd())\n if (result.status === 'success') {\n console.log(`\\n ✓ ${result.message}\\n`)\n } else {\n console.error(`\\n ✗ ${result.message}\\n`)\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,WAAW,cAAc,QAAQ,qBAAqB;AAC3E,SAAS,qBAAqB;AAC9B,SAAS,SAAS,MAAM,eAAe;AAOvC,IAAM,gBAAgB,oBAAI,IAAc,CAAC,WAAW,QAAQ,YAAY,MAAM,CAAC;AAqBxE,SAAS,eAAe,KAAa,MAAsB;AAChE,QAAM,MAAM,cAAc,KAAK,KAAK,cAAc,CAAC;AACnD,MAAI;AACJ,MAAI;AACF,cAAU,IAAI,QAAQ,GAAG,IAAI,eAAe;AAAA,EAC9C,QAAQ;AACN,UAAM,IAAI,MAAM,GAAG,IAAI,mCAAmC,IAAI,EAAE;AAAA,EAClE;AACA,QAAM,MAAM,KAAK,MAAM,aAAa,SAAS,MAAM,CAAC;AACpD,QAAM,MAAM,OAAO,IAAI,QAAQ,WAAW,IAAI,MAAM,IAAI,MAAM,IAAI;AAClE,MAAI,QAAQ,OAAW,OAAM,IAAI,MAAM,GAAG,IAAI,YAAY,IAAI,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I;AAAA,WAAS,OAAO,OAAO;AAAA,CAAI;AAAA,EACzC,OAAO;AACL,YAAQ,MAAM;AAAA,WAAS,OAAO,OAAO;AAAA,CAAI;AACzC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":[]}
@@ -19,15 +19,15 @@ import {
19
19
  prepareJobBackend,
20
20
  resolveListenPort,
21
21
  startJobWorker
22
- } from "./chunk-PYEDWJF7.js";
22
+ } from "./chunk-C5H2JHDW.js";
23
23
  import {
24
24
  preflightNodeAndBindings
25
25
  } from "./chunk-KTMQUYED.js";
26
26
  import {
27
27
  theoPluginAsync
28
- } from "./chunk-DQIY2LUG.js";
29
- import "./chunk-VSK5Y4ET.js";
30
- import "./chunk-BDH5GKFZ.js";
28
+ } from "./chunk-CFJN5JHJ.js";
29
+ import "./chunk-W55B6BRC.js";
30
+ import "./chunk-TF44PW3F.js";
31
31
  import "./chunk-3PWQQWT6.js";
32
32
  import "./chunk-FDOOBTXJ.js";
33
33
  import "./chunk-MSSUMKFR.js";
@@ -180,4 +180,4 @@ export {
180
180
  devCommand,
181
181
  startDevServer
182
182
  };
183
- //# sourceMappingURL=dev-MRB3LXAM.js.map
183
+ //# sourceMappingURL=dev-CDCYJTDM.js.map
@@ -63,12 +63,16 @@ function generateDockerfile(input) {
63
63
  // Inside a container `localhost` answers nobody, the image's own health check included (#402).
64
64
  "ENV HOST=0.0.0.0",
65
65
  "ENV PORT=3000",
66
- `COPY --from=builder /app/${distDir} ./${distDir}`,
67
- ...copySources,
68
- ...input.hasConfigFile ? ["COPY --from=builder /app/theo.config.ts ./theo.config.ts"] : [],
69
- ...manifests.map((file) => `COPY --from=builder /app/${file} ./${file}`),
70
- "COPY --from=builder /app/node_modules ./node_modules",
66
+ `COPY --from=builder --chown=node:node /app/${distDir} ./${distDir}`,
67
+ ...copySources.map(
68
+ (line) => line.replace("--from=builder", "--from=builder --chown=node:node")
69
+ ),
70
+ ...input.hasConfigFile ? ["COPY --from=builder --chown=node:node /app/theo.config.ts ./theo.config.ts"] : [],
71
+ ...manifests.map((file) => `COPY --from=builder --chown=node:node /app/${file} ./${file}`),
72
+ "COPY --from=builder --chown=node:node /app/node_modules ./node_modules",
71
73
  "",
74
+ // The node image ships an unprivileged `node` user; without USER the server runs as root.
75
+ "USER node",
72
76
  "EXPOSE 3000",
73
77
  `CMD ["${THEOKIT_BIN}", "start"]`,
74
78
  ""
@@ -125,6 +129,7 @@ async function dockerCommand(options) {
125
129
  `);
126
130
  }
127
131
  export {
128
- dockerCommand
132
+ dockerCommand,
133
+ generateDockerfile
129
134
  };
130
- //# sourceMappingURL=docker-DINW3YV6.js.map
135
+ //# sourceMappingURL=docker-ED6W4ILB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/docker.ts"],"sourcesContent":["import { existsSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { AUTHORED_AGENT_CONTEXT } from '../cleanup/cleanup.js'\n\nfunction detectPkgManager(cwd: string): PkgManager {\n if (existsSync(resolve(cwd, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(resolve(cwd, 'yarn.lock'))) return 'yarn'\n return 'npm'\n}\n\ntype PkgManager = 'pnpm' | 'npm' | 'yarn'\n\ninterface DockerfileInput {\n readonly pkgManager: PkgManager\n /** Top-level directories holding the server and agent sources, e.g. `['src']` for the scaffold. */\n readonly sourceRoots: readonly string[]\n /** The configured build output directory, `.theokit` by default. */\n readonly distDir: string\n readonly hasConfigFile: boolean\n readonly hasPnpmWorkspace: boolean\n}\n\n/**\n * The installed CLI, by path. `npx theo build` asked the registry for a package named `theo`, an\n * unrelated design-tokens tool, then installed and ran it inside the image build (#1069). A path\n * into `node_modules/.bin` cannot fall back to the registry under any package manager.\n */\nconst THEOKIT_BIN = './node_modules/.bin/theokit'\n\n/**\n * The top-level directory a configured path lives in. The runner copies whole roots: the scaffold's\n * `src/server` imports `src/shared`, so copying only `serverDir` would leave an import dangling.\n */\nfunction topLevelDir(path: string): string {\n return path.replace(/^\\.\\//, '').split('/')[0]\n}\n\nexport function generateDockerfile(input: DockerfileInput): string {\n const { pkgManager, distDir } = input\n const installCmd = {\n pnpm: 'RUN corepack enable && pnpm install --frozen-lockfile',\n npm: 'RUN npm ci',\n yarn: 'RUN yarn install --frozen-lockfile',\n }[pkgManager]\n\n const lockfile = {\n pnpm: 'pnpm-lock.yaml',\n npm: 'package-lock.json',\n yarn: 'yarn.lock',\n }[pkgManager]\n\n // pnpm 10 reads `allowBuilds` from pnpm-workspace.yaml; installing without it leaves esbuild unbuilt.\n const manifests = [\n 'package.json',\n lockfile,\n ...(pkgManager === 'pnpm' && input.hasPnpmWorkspace ? ['pnpm-workspace.yaml'] : []),\n ]\n\n const copySources = [...new Set(input.sourceRoots)].map(\n (root) => `COPY --from=builder /app/${root} ./${root}`,\n )\n\n return [\n '# Generated by TheoKit',\n '# Multi-stage build for production',\n '',\n '# Stage 1: Build',\n 'FROM node:22-alpine AS builder',\n 'WORKDIR /app',\n `COPY ${manifests.join(' ')} ./`,\n installCmd,\n 'COPY . .',\n `RUN ${THEOKIT_BIN} build`,\n '',\n '# Stage 2: Production',\n 'FROM node:22-alpine AS runner',\n 'WORKDIR /app',\n 'ENV NODE_ENV=production',\n // Inside a container `localhost` answers nobody, the image's own health check included (#402).\n 'ENV HOST=0.0.0.0',\n 'ENV PORT=3000',\n `COPY --from=builder --chown=node:node /app/${distDir} ./${distDir}`,\n ...copySources.map((line) =>\n line.replace('--from=builder', '--from=builder --chown=node:node'),\n ),\n ...(input.hasConfigFile\n ? ['COPY --from=builder --chown=node:node /app/theo.config.ts ./theo.config.ts']\n : []),\n ...manifests.map((file) => `COPY --from=builder --chown=node:node /app/${file} ./${file}`),\n 'COPY --from=builder --chown=node:node /app/node_modules ./node_modules',\n '',\n // The node image ships an unprivileged `node` user; without USER the server runs as root.\n 'USER node',\n 'EXPOSE 3000',\n `CMD [\"${THEOKIT_BIN}\", \"start\"]`,\n '',\n ].join('\\n')\n}\n\n/**\n * `.theokit` is both the build output and the agent context (#1079). The context a person writes\n * (THEO.md, rules, personalities ...) goes into the image; local agent state such as memory and MCP\n * tokens stays out, and so does a stale local build, which the image rebuilds anyway.\n */\nfunction generateDockerignore(distDir = '.theokit'): string {\n return [\n 'node_modules',\n '.git',\n `${distDir}/*`,\n // A re-included directory brings its contents: Docker matches a pattern against every parent.\n ...AUTHORED_AGENT_CONTEXT.map((entry) => `!${distDir}/${entry}`),\n 'dist',\n '.env',\n '.env.*',\n '!.env.example',\n '*.log',\n '.DS_Store',\n '.vscode',\n '.idea',\n 'Dockerfile',\n '.dockerignore',\n '',\n ].join('\\n')\n}\n\nexport async function dockerCommand(options?: { force?: boolean }): Promise<void> {\n const cwd = process.cwd()\n const dockerfilePath = resolve(cwd, 'Dockerfile')\n const dockerignorePath = resolve(cwd, '.dockerignore')\n\n const pkgManager = detectPkgManager(cwd)\n const { serverDir, agentsDir, distDir } = await loadConfig(cwd)\n const dockerfile = generateDockerfile({\n pkgManager,\n sourceRoots: [topLevelDir(serverDir), topLevelDir(agentsDir)],\n distDir,\n hasConfigFile: existsSync(resolve(cwd, 'theo.config.ts')),\n hasPnpmWorkspace: existsSync(resolve(cwd, 'pnpm-workspace.yaml')),\n })\n\n // `wx` refuses an existing file in the same call that creates it. A separate exists check\n // followed by a write leaves a window, wider now that the config load sits between them.\n try {\n writeFileSync(dockerfilePath, dockerfile, { flag: options?.force ? 'w' : 'wx' })\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err\n console.log('\\n ⚠ Dockerfile already exists. Use --force to overwrite.\\n')\n return\n }\n writeFileSync(dockerignorePath, generateDockerignore(distDir))\n\n console.log(`\\n ✓ Generated Dockerfile (${pkgManager})`)\n console.log(` ✓ Generated .dockerignore`)\n console.log(`\\n Next steps:`)\n console.log(` docker build -t my-app .`)\n console.log(` docker run -p 3000:3000 my-app\\n`)\n}\n"],"mappings":";;;;;;;;;;;;;;;A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,OAAO,CAAC;AAE7D,UAAQ,IAAI;AAAA,iCAA+B,UAAU,GAAG;AACxD,UAAQ,IAAI,kCAA6B;AACzC,UAAQ,IAAI;AAAA,cAAiB;AAC7B,UAAQ,IAAI,8BAA8B;AAC1C,UAAQ,IAAI;AAAA,CAAsC;AACpD;","names":[]}
package/dist/index.js CHANGED
@@ -8,11 +8,11 @@ import {
8
8
  scanRoutes,
9
9
  theoConfigSchema,
10
10
  theoPlugin
11
- } from "./chunk-27FXSIGE.js";
11
+ } from "./chunk-QEVTZ3IH.js";
12
12
  import "./chunk-7NRFZBAL.js";
13
13
  import "./chunk-SSYDEKWF.js";
14
14
  import "./chunk-SHBPXX5E.js";
15
- import "./chunk-7MCEJVGV.js";
15
+ import "./chunk-APUYC5BE.js";
16
16
  import "./chunk-4XZOUS5G.js";
17
17
  import "./chunk-OIGJOYX6.js";
18
18
  import "./chunk-U3SPBLJF.js";
@@ -39,7 +39,7 @@ import "./chunk-V6Y2SMRG.js";
39
39
  import "./chunk-ACKBVBUI.js";
40
40
  import "./chunk-IZ3TIL6K.js";
41
41
  import "./chunk-TRCJHFAX.js";
42
- import "./chunk-TQEE36VD.js";
42
+ import "./chunk-RN5NDLUS.js";
43
43
  import "./chunk-54BIQFP4.js";
44
44
  import "./chunk-ZICY2CD7.js";
45
45
  import "./chunk-YSJOZEI6.js";
@@ -2,11 +2,11 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  createAgentSsrLoader
5
- } from "./chunk-3L6WU7J7.js";
5
+ } from "./chunk-QKWBT7IY.js";
6
6
  import {
7
7
  extractAppResources,
8
8
  handleMcpJsonRpc
9
- } from "./chunk-BDH5GKFZ.js";
9
+ } from "./chunk-TF44PW3F.js";
10
10
  import "./chunk-4JRXZTVQ.js";
11
11
  import {
12
12
  scanAgents
@@ -19,7 +19,7 @@ import "./chunk-NF7LXSXZ.js";
19
19
  import { createInterface } from "readline";
20
20
 
21
21
  // src/server/agent/mcp-stdio.ts
22
- async function handleMcpStdioLine(line, mod, name, appResources = []) {
22
+ async function answerLine(line, respond) {
23
23
  const trimmed = line.trim();
24
24
  if (trimmed.length === 0) return null;
25
25
  let body;
@@ -32,10 +32,13 @@ async function handleMcpStdioLine(line, mod, name, appResources = []) {
32
32
  error: { code: -32700, message: "Parse error" }
33
33
  });
34
34
  }
35
- const response = await handleMcpJsonRpc(mod, name, body, appResources);
35
+ const response = await respond(body);
36
36
  const payload = await response.json();
37
37
  return JSON.stringify(payload);
38
38
  }
39
+ function handleMcpStdioLine(line, mod, name, appResources = []) {
40
+ return answerLine(line, (body) => handleMcpJsonRpc(mod, name, body, appResources));
41
+ }
39
42
  async function serveMcpStdio(mod, name, appResources, streams) {
40
43
  for await (const line of streams.lines) {
41
44
  const out = await handleMcpStdioLine(line, mod, name, appResources);
@@ -76,4 +79,4 @@ async function mcpCommand(name, deps = {}) {
76
79
  export {
77
80
  mcpCommand
78
81
  };
79
- //# sourceMappingURL=mcp-LZALIEGI.js.map
82
+ //# sourceMappingURL=mcp-4OM4QSYT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/mcp.ts","../src/server/agent/mcp-stdio.ts"],"sourcesContent":["/**\n * `theokit mcp <agent>` — expose a scanned agent as an MCP server over stdio.\n *\n * The stdio sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`): a desktop MCP client\n * (e.g. Claude Desktop) spawns this command and speaks newline-delimited JSON-RPC over the pipe.\n * It reuses the framework's OWN `serveMcpStdio` / `handleMcpJsonRpc` (no LLM call, no runtime — a\n * TRANSPORT, like the HTTP route). `deps` is injectable so the routing is tested without Vite/stdin.\n */\nimport { createInterface } from 'node:readline'\n\nimport { extractAppResources } from '../../server/agent/mcp-app-resources.js'\nimport { type StdioStreams, serveMcpStdio } from '../../server/agent/mcp-stdio.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\n\nimport { createAgentSsrLoader } from './agent.js'\n\ninterface McpCommandDeps {\n projectRoot?: string\n /** Load a TS agent module; defaults to the framework's Vite SSR loader (same transpile as dev). */\n loadModule?: (filePath: string) => Promise<Record<string, unknown>>\n /** stdio streams; defaults to `readline(process.stdin)` + `process.stdout`. Injected in tests. */\n streams?: StdioStreams\n /** Agents dir name (config `agentsDir`); defaults to the loaded config's value (\"agents\"). Tests inject it. */\n agentsDir?: string\n}\n\nexport async function mcpCommand(name: string, deps: McpCommandDeps = {}): Promise<void> {\n const projectRoot = deps.projectRoot ?? process.cwd()\n // #95 follow-up — resolve agents dir from config (default \"agents\") so `agentsDir` is honored here too.\n const agentsDir =\n deps.agentsDir ??\n (await (await import('../../config/load-config.js')).loadConfig(projectRoot)).agentsDir\n const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name)\n if (!agent) {\n const names = scanAgents(projectRoot, agentsDir)\n .map((a) => a.name)\n .join(', ')\n throw new Error(\n `theokit mcp: agent '${name}' not found. Available: ${names || '(none in agents/)'}`,\n )\n }\n\n let loadModule = deps.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (!loadModule) {\n const loader = await createAgentSsrLoader(projectRoot)\n loadModule = loader.load\n dispose = loader.dispose\n }\n\n const streams =\n deps.streams ??\n ({\n lines: createInterface({ input: process.stdin }),\n write: (line: string) => process.stdout.write(line),\n } satisfies StdioStreams)\n\n try {\n const mod = await loadModule(agent.filePath)\n await serveMcpStdio(mod, agent.name, extractAppResources(mod), streams)\n } finally {\n if (dispose) await dispose()\n }\n}\n","/**\n * MCP stdio transport (M16 follow-up) — expose a TheoKit agent as an MCP server over stdin/stdout,\n * the sibling of the M16 HTTP route (`POST /api/agents/<name>/mcp`). A desktop MCP client (e.g.\n * Claude Desktop) spawns `theokit mcp <agent>` and speaks newline-delimited JSON-RPC over the pipe.\n *\n * This is a TRANSPORT over the framework's OWN {@link handleMcpJsonRpc} — it reuses the exact handler\n * the HTTP route uses; it calls no LLM, spawns no MCP client, and reimplements no runtime (G2 /\n * sdk-runtime.md). Distinct from the SDK's MCP CLIENT stdio (which spawns external MCP servers via\n * `mcpServers` command/args) — that stays SDK-side. Here TheoKit is the SERVER. The framework-side\n * placement of this server-exposure transport is recorded in ADR-0042 (refining ADR-0040's M16 note).\n */\nimport type { CustomTool } from '@theokit/sdk'\n\nimport type { AppResource } from './mcp-app-resources.js'\nimport { handleMcpJsonRpc, handleMcpToolsJsonRpc } from './mcp-handler.js'\n\n/** Parse one line and answer it via `respond`; `null` for a blank line, `-32700` for bad JSON. */\nasync function answerLine(\n line: string,\n respond: (body: unknown) => Promise<Response>,\n): Promise<string | null> {\n const trimmed = line.trim()\n if (trimmed.length === 0) return null\n let body: unknown\n try {\n body = JSON.parse(trimmed)\n } catch {\n return JSON.stringify({\n jsonrpc: '2.0',\n id: null,\n error: { code: -32700, message: 'Parse error' },\n })\n }\n const response = await respond(body)\n const payload: unknown = await response.json()\n return JSON.stringify(payload)\n}\n\n/**\n * Handle one newline-delimited JSON-RPC line. Returns the response line to write to stdout, or\n * `null` for a blank line (nothing to emit). A malformed JSON line yields a `-32700` (Parse error)\n * envelope — never throws, so the stdio loop never dies on bad input.\n */\nexport function handleMcpStdioLine(\n line: string,\n mod: unknown,\n name: string,\n appResources: readonly AppResource[] = [],\n): Promise<string | null> {\n return answerLine(line, (body) => handleMcpJsonRpc(mod, name, body, appResources))\n}\n\n/** A minimal readable line source (an async iterable of lines) + a writable sink. */\nexport interface StdioStreams {\n /** Async iterable of newline-delimited input lines (e.g. `readline.createInterface({ input })`). */\n lines: AsyncIterable<string>\n /** Write a response line (the caller appends no newline). */\n write: (line: string) => void\n}\n\n/**\n * Drive the MCP stdio server loop: for each input line, dispatch via {@link handleMcpStdioLine} and\n * write the response line (with a trailing `\\n`). Returns when the input stream ends (EOF).\n */\nexport async function serveMcpStdio(\n mod: unknown,\n name: string,\n appResources: readonly AppResource[],\n streams: StdioStreams,\n): Promise<void> {\n for await (const line of streams.lines) {\n const out = await handleMcpStdioLine(line, mod, name, appResources)\n if (out !== null) streams.write(`${out}\\n`)\n }\n}\n\n/**\n * Stdio loop for a plain list of tools (no agent module), the sibling of {@link serveMcpStdio}.\n * No approval gate: whoever passes a tool in decides it may run unattended. Duplicate tool names\n * are refused (rejects) before any line is read.\n */\nexport async function serveMcpToolsStdio(\n tools: readonly CustomTool[],\n name: string,\n streams: StdioStreams,\n): Promise<void> {\n const respond = (body: unknown): Promise<Response> => handleMcpToolsJsonRpc(tools, name, body)\n // Validate eagerly so a duplicate fails the call, not the first request.\n await respond(null)\n for await (const line of streams.lines) {\n const out = await answerLine(line, respond)\n if (out !== null) streams.write(`${out}\\n`)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,SAAS,uBAAuB;;;ACShC,eAAe,WACb,MACA,SACwB;AACxB,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO,KAAK,UAAU;AAAA,MACpB,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,OAAO,EAAE,MAAM,QAAQ,SAAS,cAAc;AAAA,IAChD,CAAC;AAAA,EACH;AACA,QAAM,WAAW,MAAM,QAAQ,IAAI;AACnC,QAAM,UAAmB,MAAM,SAAS,KAAK;AAC7C,SAAO,KAAK,UAAU,OAAO;AAC/B;AAOO,SAAS,mBACd,MACA,KACA,MACA,eAAuC,CAAC,GAChB;AACxB,SAAO,WAAW,MAAM,CAAC,SAAS,iBAAiB,KAAK,MAAM,MAAM,YAAY,CAAC;AACnF;AAcA,eAAsB,cACpB,KACA,MACA,cACA,SACe;AACf,mBAAiB,QAAQ,QAAQ,OAAO;AACtC,UAAM,MAAM,MAAM,mBAAmB,MAAM,KAAK,MAAM,YAAY;AAClE,QAAI,QAAQ,KAAM,SAAQ,MAAM,GAAG,GAAG;AAAA,CAAI;AAAA,EAC5C;AACF;;;ADhDA,eAAsB,WAAW,MAAc,OAAuB,CAAC,GAAkB;AACvF,QAAM,cAAc,KAAK,eAAe,QAAQ,IAAI;AAEpD,QAAM,YACJ,KAAK,cACJ,OAAO,MAAM,OAAO,2BAA6B,GAAG,WAAW,WAAW,GAAG;AAChF,QAAM,QAAQ,WAAW,aAAa,SAAS,EAAE,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AAC5E,MAAI,CAAC,OAAO;AACV,UAAM,QAAQ,WAAW,aAAa,SAAS,EAC5C,IAAI,CAAC,MAAM,EAAE,IAAI,EACjB,KAAK,IAAI;AACZ,UAAM,IAAI;AAAA,MACR,uBAAuB,IAAI,2BAA2B,SAAS,mBAAmB;AAAA,IACpF;AAAA,EACF;AAEA,MAAI,aAAa,KAAK;AACtB,MAAI;AACJ,MAAI,CAAC,YAAY;AACf,UAAM,SAAS,MAAM,qBAAqB,WAAW;AACrD,iBAAa,OAAO;AACpB,cAAU,OAAO;AAAA,EACnB;AAEA,QAAM,UACJ,KAAK,WACJ;AAAA,IACC,OAAO,gBAAgB,EAAE,OAAO,QAAQ,MAAM,CAAC;AAAA,IAC/C,OAAO,CAAC,SAAiB,QAAQ,OAAO,MAAM,IAAI;AAAA,EACpD;AAEF,MAAI;AACF,UAAM,MAAM,MAAM,WAAW,MAAM,QAAQ;AAC3C,UAAM,cAAc,KAAK,MAAM,MAAM,oBAAoB,GAAG,GAAG,OAAO;AAAA,EACxE,UAAE;AACA,QAAI,QAAS,OAAM,QAAQ;AAAA,EAC7B;AACF;","names":[]}
@@ -4,8 +4,8 @@ import "tsx/esm";
4
4
  // src/cli/commands/preview.ts
5
5
  async function defaultSteps() {
6
6
  const [{ buildCommand }, { startCommand }] = await Promise.all([
7
- import("./build-DOYXIZWZ.js"),
8
- import("./start-GC3KJ22H.js")
7
+ import("./build-TQAYRHJH.js"),
8
+ import("./start-4NBJTPCR.js")
9
9
  ]);
10
10
  return {
11
11
  build: (opts) => buildCommand(opts),
@@ -20,4 +20,4 @@ async function previewCommand(options = {}, steps) {
20
20
  export {
21
21
  previewCommand
22
22
  };
23
- //# sourceMappingURL=preview-WDF723U3.js.map
23
+ //# sourceMappingURL=preview-C52WW62N.js.map
@@ -3,6 +3,7 @@ import { C as CustomTool } from '../../define-agent-tool-aYYLpMeo.js';
3
3
  import { CustomTool as CustomTool$1 } from '@theokit/sdk';
4
4
  import { AcpTransport } from '@theokit/agents';
5
5
  export { AgentModule, InProcessApprovalRequest, InProcessApprovalRequiredError, InProcessAwaitApproval, StreamAgentTurnDeps, StreamAgentTurnInProcessInput, streamAgentTurnInProcess } from '@theokit/agents';
6
+ export { CodeModeApi, CodeModeConfig, CodeModePermission, CodeModePermissionDeniedError, Sandbox, createCodeMode } from '@theokit/agents/code-mode';
6
7
  import { V as VerifyFn, S as SubscribeFn } from '../../whatsapp-4W2eK2ij.js';
7
8
  export { P as ProviderDescriptor, R as ResolvedProvider, l as listProviders, a as registerProvider, b as resetProviderRegistry, r as resolveProvider, t as tryResolveProvider } from '../../provider-resolver-Cc9C3-Rb.js';
8
9
 
@@ -76,7 +77,11 @@ declare class NodeAcpTransport implements AcpToolTransport {
76
77
  private readonly listeners;
77
78
  /** Settles when the process has exited (or never started). */
78
79
  private readonly exited;
79
- constructor(command: string, args?: string[], cwd?: string);
80
+ constructor(command: string, args?: string[], cwd?: string,
81
+ /** The agent's whole environment. Omitted: the parent's. Given: only these variables. */
82
+ env?: Record<string, string | undefined>,
83
+ /** Receives what the agent writes to stderr. Omitted: it goes to the parent's stderr. */
84
+ onStderr?: (chunk: string) => void);
80
85
  send(line: string): void;
81
86
  subscribe(onData: (chunk: string) => void): void;
82
87
  onClose(listener: (error: AcpTransportClosedError) => void): void;
@@ -143,6 +148,15 @@ interface AcpToolConfig {
143
148
  args?: string[];
144
149
  /** Working directory for the spawned agent. */
145
150
  cwd?: string;
151
+ /**
152
+ * The spawned agent's whole environment: when given, the agent sees exactly these variables and
153
+ * none of the parent's (so channel tokens stay out of it). Omitted, it inherits `process.env`.
154
+ */
155
+ env?: Record<string, string | undefined>;
156
+ /**
157
+ * Receives what the agent writes to its stderr. Omitted, the agent's stderr is the parent's.
158
+ */
159
+ onStderr?: (chunk: string) => void;
146
160
  /** Tool name the model calls. */
147
161
  name: string;
148
162
  /** Tool description surfaced to the model. */
@@ -216,73 +230,6 @@ interface VendorAgentToolConfig {
216
230
  */
217
231
  declare function createVendorAgentTool(config: VendorAgentToolConfig): CustomTool;
218
232
 
219
- /**
220
- * M29 (ADR-0041) — `createCodeMode`: expose a set of tools to agent-authored code run inside an
221
- * ISOLATION boundary, so the agent composes tools programmatically instead of one call at a time.
222
- *
223
- * Security posture (the whole point of this feature):
224
- * - The isolation boundary (`sandbox`) is **injected**, never hand-rolled here (Top-risk 1). The app
225
- * supplies a vetted sandbox — isolated-vm, QuickJS-WASM, or a locked-down worker. TheoKit core
226
- * ships no VM and adds no sandbox dependency (same posture as the injected deploy adapter / the
227
- * M17 transport). `node:vm` is NOT a security boundary and MUST NOT be used as the sandbox.
228
- * - TheoKit owns the **restricted API** (only the declared tools are reachable from the code — no
229
- * `fs`, `process`, `require`, or network unless a declared, permission-gated tool provides it) and
230
- * the **mandatory permission gate**: every tool call from the code passes `onPermissionRequest`
231
- * first, and there is NO default-allow (mirrors M17 `onPermissionRequest`).
232
- *
233
- * Threat model (summary): a malicious model could author code that (a) calls a dangerous tool, or
234
- * (b) tries to reach a host capability. (a) is stopped by the permission gate (deny → the API call
235
- * throws). (b) is stopped by the injected sandbox (the restricted API is the ONLY surface the code
236
- * sees). If the app injects a weak sandbox, (b) is on the app — hence the vetted-sandbox requirement.
237
- */
238
-
239
- /** The restricted API handed to sandboxed code: declared tool names → permission-gated callables. */
240
- type CodeModeApi = Record<string, (args: unknown) => Promise<unknown>>;
241
- /** The injected isolation boundary. The app supplies a vetted implementation. */
242
- interface Sandbox {
243
- /** Run `code` with access to ONLY `api` (the restricted tool surface). Resolve the code's result. */
244
- run(code: string, api: CodeModeApi): Promise<unknown>;
245
- }
246
- /** A permission decision for one tool call from sandboxed code. */
247
- interface CodeModePermission {
248
- granted: boolean;
249
- /** Optional reason surfaced to the model on denial. */
250
- reason?: string;
251
- }
252
- interface CodeModeConfig {
253
- /** The tools reachable from the code (the restricted API). */
254
- tools: CustomTool[];
255
- /** The injected isolation boundary (vetted sandbox — NEVER node:vm). */
256
- sandbox: Sandbox;
257
- /**
258
- * REQUIRED — decide each tool call the code attempts. Security by default: NO default-allow.
259
- * Return `{ granted }` (may be async). Mirrors M17 `onPermissionRequest`.
260
- */
261
- onPermissionRequest: (req: {
262
- tool: string;
263
- args: unknown;
264
- }) => CodeModePermission | Promise<CodeModePermission>;
265
- /** Tool name the model calls (default `run_code`). */
266
- name?: string;
267
- /** Tool description surfaced to the model. */
268
- description?: string;
269
- }
270
- /** Thrown when the permission gate denies a tool call from sandboxed code. */
271
- declare class CodeModePermissionDeniedError extends Error {
272
- constructor(tool: string, reason?: string);
273
- }
274
- /**
275
- * Build a code-mode tool + its generated model instructions (M40 / ADR-0049). Fails fast if
276
- * `onPermissionRequest` or `sandbox` is missing (security by default). `tool` takes `{ code }`,
277
- * assembles the permission-gated restricted API from `tools`, runs the code in the injected sandbox,
278
- * and returns the code's result. `instructions` (add it to the agent's system prompt) teaches the
279
- * model the sandboxed-code contract + the available `api.<name>(input)` calls.
280
- */
281
- declare function createCodeMode(config: CodeModeConfig): {
282
- tool: CustomTool;
283
- instructions: string;
284
- };
285
-
286
233
  /**
287
234
  * M27 (ADR-0041) — channel webhook routes: `POST /api/agents/<name>/channels/<platform>/webhook`.
288
235
  *
@@ -428,5 +375,22 @@ interface StdioStreams {
428
375
  * write the response line (with a trailing `\n`). Returns when the input stream ends (EOF).
429
376
  */
430
377
  declare function serveMcpStdio(mod: unknown, name: string, appResources: readonly AppResource[], streams: StdioStreams): Promise<void>;
378
+ /**
379
+ * Stdio loop for a plain list of tools (no agent module), the sibling of {@link serveMcpStdio}.
380
+ * No approval gate: whoever passes a tool in decides it may run unattended. Duplicate tool names
381
+ * are refused (rejects) before any line is read.
382
+ */
383
+ declare function serveMcpToolsStdio(tools: readonly CustomTool$1[], name: string, streams: StdioStreams): Promise<void>;
384
+
385
+ /**
386
+ * Handle one MCP JSON-RPC request for a plain list of tools (no agent module). Same JSON-RPC
387
+ * handling as {@link handleMcpJsonRpc}; advertises `capabilities.tools` only (no resources).
388
+ *
389
+ * There is NO approval gate: a list of tools carries no human-approval policy, so none is refused as
390
+ * "requires human approval". Whoever passes a tool in decides it may run unattended.
391
+ *
392
+ * @throws when two tools share a name (checked when called, before any request is answered).
393
+ */
394
+ declare function handleMcpToolsJsonRpc(tools: readonly CustomTool$1[], name: string, body: unknown): Promise<Response>;
431
395
 
432
- export { AcpRequestTimeoutError, type AcpToolConfig, type AcpToolTransport, AcpTransportClosedError, AcpTurnStoppedError, type AppResource, type AppResourceInput, type ChannelMessage, type ChannelWebhookConfig, type CodeModeApi, type CodeModeConfig, type CodeModePermission, CodeModePermissionDeniedError, DEFAULT_ACP_TIMEOUT_MS, type McpResourceContents, type McpResourceDescriptor, NodeAcpTransport, type Sandbox, type StdioStreams, type VendorAgentClient, type VendorAgentToolConfig, type WorkflowLike, type WorkflowToolConfig, buildResourceDescriptors, createACPTool, createCodeMode, createVendorAgentTool, createWorkflowTool, defineAppResource, extractAppResources, handleChannelWebhook, handleMcpStdioLine, isChannelPath, parseChannelPath, readAppResource, serveMcpStdio };
396
+ export { AcpRequestTimeoutError, type AcpToolConfig, type AcpToolTransport, AcpTransportClosedError, AcpTurnStoppedError, type AppResource, type AppResourceInput, type ChannelMessage, type ChannelWebhookConfig, DEFAULT_ACP_TIMEOUT_MS, type McpResourceContents, type McpResourceDescriptor, NodeAcpTransport, type StdioStreams, type VendorAgentClient, type VendorAgentToolConfig, type WorkflowLike, type WorkflowToolConfig, buildResourceDescriptors, createACPTool, createVendorAgentTool, createWorkflowTool, defineAppResource, extractAppResources, handleChannelWebhook, handleMcpStdioLine, handleMcpToolsJsonRpc, isChannelPath, parseChannelPath, readAppResource, serveMcpStdio, serveMcpToolsStdio };
@@ -15,15 +15,17 @@ import {
15
15
  isChannelPath,
16
16
  parseChannelPath,
17
17
  serveMcpStdio,
18
+ serveMcpToolsStdio,
18
19
  streamAgentTurnInProcess
19
- } from "../../chunk-RAUYMVUO.js";
20
+ } from "../../chunk-JUJI3FZM.js";
20
21
  import "../../chunk-DVUJLMTF.js";
21
22
  import {
22
23
  buildResourceDescriptors,
23
24
  defineAppResource,
24
25
  extractAppResources,
26
+ handleMcpToolsJsonRpc,
25
27
  readAppResource
26
- } from "../../chunk-TQEE36VD.js";
28
+ } from "../../chunk-RN5NDLUS.js";
27
29
  import {
28
30
  listProviders,
29
31
  registerProvider,
@@ -50,6 +52,7 @@ export {
50
52
  extractAppResources,
51
53
  handleChannelWebhook,
52
54
  handleMcpStdioLine,
55
+ handleMcpToolsJsonRpc,
53
56
  isChannelPath,
54
57
  listProviders,
55
58
  parseChannelPath,
@@ -58,6 +61,7 @@ export {
58
61
  resetProviderRegistry,
59
62
  resolveProvider,
60
63
  serveMcpStdio,
64
+ serveMcpToolsStdio,
61
65
  streamAgentTurnInProcess,
62
66
  tryResolveProvider
63
67
  };
@@ -14,7 +14,7 @@ import {
14
14
  translateCronToVercel,
15
15
  validateCronSchedule,
16
16
  writeCronManifest
17
- } from "../../chunk-3GM4GACM.js";
17
+ } from "../../chunk-2Z3GHQ64.js";
18
18
  import {
19
19
  createPostgresCronLock
20
20
  } from "../../chunk-LXV5IEBB.js";