@cloudflare/codemode 0.1.1 → 0.1.3

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.
package/dist/ai.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as Executor, s as ToolDescriptors } from "./executor-Czw9jKZH.js";
1
+ import { i as Executor, s as ToolDescriptors } from "./executor-BYZZhAgd.js";
2
2
  import { Tool, ToolSet } from "ai";
3
3
  import { z } from "zod";
4
4
 
package/dist/ai.js CHANGED
@@ -1,8 +1,6 @@
1
- import { n as sanitizeToolName, t as generateTypes } from "./types-CpkEgXwN.js";
1
+ import { n as generateTypes, r as sanitizeToolName, t as normalizeCode } from "./normalize-Dy5d7PfI.js";
2
2
  import { asSchema, tool } from "ai";
3
3
  import { z } from "zod";
4
- import * as acorn from "acorn";
5
-
6
4
  //#region src/tool.ts
7
5
  const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
8
6
 
@@ -15,27 +13,6 @@ Do NOT define named functions then call them — just write the arrow function b
15
13
 
16
14
  Example: async () => { const r = await codemode.searchWeb({ query: "test" }); return r; }`;
17
15
  const codeSchema = z.object({ code: z.string().describe("JavaScript async arrow function to execute") });
18
- function normalizeCode(code) {
19
- const trimmed = code.trim();
20
- if (!trimmed) return "async () => {}";
21
- try {
22
- const ast = acorn.parse(trimmed, {
23
- ecmaVersion: "latest",
24
- sourceType: "module"
25
- });
26
- if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
27
- if (ast.body[0].expression.type === "ArrowFunctionExpression") return trimmed;
28
- }
29
- const last = ast.body[ast.body.length - 1];
30
- if (last?.type === "ExpressionStatement") {
31
- const exprStmt = last;
32
- return `async () => {\n${trimmed.slice(0, last.start)}return (${trimmed.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
33
- }
34
- return `async () => {\n${trimmed}\n}`;
35
- } catch {
36
- return `async () => {\n${trimmed}\n}`;
37
- }
38
- }
39
16
  /**
40
17
  * Create a codemode tool that allows LLMs to write and execute code
41
18
  * with access to your tools in a sandboxed environment.
@@ -82,7 +59,7 @@ function createCodeTool(options) {
82
59
  }
83
60
  });
84
61
  }
85
-
86
62
  //#endregion
87
63
  export { createCodeTool };
64
+
88
65
  //# sourceMappingURL=ai.js.map
package/dist/ai.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ai.js","names":[],"sources":["../src/tool.ts"],"sourcesContent":["import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport * as acorn from \"acorn\";\nimport { generateTypes, sanitizeToolName, type ToolDescriptors } from \"./types\";\nimport type { Executor } from \"./executor\";\n\nconst DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolDescriptors | ToolSet;\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\ntype CodeInput = z.infer<typeof codeSchema>;\ntype CodeOutput = { code: string; result: unknown; logs?: string[] };\n\nfunction normalizeCode(code: string): string {\n const trimmed = code.trim();\n if (!trimmed) return \"async () => {}\";\n\n try {\n const ast = acorn.parse(trimmed, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return trimmed;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = trimmed.slice(0, last.start);\n const exprText = trimmed.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${trimmed}\\n}`;\n } catch {\n return `async () => {\\n${trimmed}\\n}`;\n }\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns an AI SDK compatible tool.\n */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const tools: ToolDescriptors | ToolSet = {};\n for (const [name, t] of Object.entries(options.tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n (tools as Record<string, unknown>)[name] = t;\n }\n }\n\n const types = generateTypes(tools);\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n // Extract execute functions from tools, keyed by name.\n // Wrap each with its schema so arguments from the sandbox\n // are validated before reaching the tool function.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n // Use AI SDK's asSchema() to normalize any schema type\n // (Zod v3/v4, Standard Schema, JSON Schema) into a unified\n // Schema with an optional .validate() method.\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[sanitizeToolName(name)] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(normalizedCode, fns);\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n });\n}\n"],"mappings":";;;;;;AAOA,MAAM,sBAAsB;;;;;;;;;;AAoB5B,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE,CAAC;AAKF,SAAS,cAAc,MAAsB;CAC3C,MAAM,UAAU,KAAK,MAAM;AAC3B,KAAI,CAAC,QAAS,QAAO;AAErB,KAAI;EACF,MAAM,MAAM,MAAM,MAAM,SAAS;GAC/B,aAAa;GACb,YAAY;GACb,CAAC;AAGF,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS,uBAEhD;OADc,IAAI,KAAK,GAAiC,WAC/C,SAAS,0BAA2B,QAAO;;EAItD,MAAM,OAAO,IAAI,KAAK,IAAI,KAAK,SAAS;AACxC,MAAI,MAAM,SAAS,uBAAuB;GACxC,MAAM,WAAW;AAMjB,UAAO,kBALQ,QAAQ,MAAM,GAAG,KAAK,MAAM,CAKX,UAJf,QAAQ,MACvB,SAAS,WAAW,OACpB,SAAS,WAAW,IACrB,CACkD;;AAGrD,SAAO,kBAAkB,QAAQ;SAC3B;AACN,SAAO,kBAAkB,QAAQ;;;;;;;;;AAUrC,SAAS,iBAAiB,GAAqC;AAC7D,QAAO,mBAAmB,KAAK,EAAE,iBAAiB;;AAGpD,SAAgB,eACd,SAC6B;CAC7B,MAAM,QAAmC,EAAE;AAC3C,MAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,QAAQ,MAAM,CACnD,KAAI,CAAC,iBAAiB,EAA6B,CACjD,CAAC,MAAkC,QAAQ;CAI/C,MAAM,QAAQ,cAAc,MAAM;CAClC,MAAM,WAAW,QAAQ;AAOzB,QAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,MACD;EAIC,aAAa;EACb,SAAS,OAAO,EAAE,WAAW;GAI3B,MAAM,MAAgE,EAAE;AAExE,QAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAAE;IAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH;AACN,QAAI,SAAS;KACX,MAAM,YACJ,iBAAiB,IACb,EAAE,cACF,gBAAgB,IACb,EAA8B,aAC/B;KAKR,MAAM,SAAS,aAAa,OAAO,SAAS,UAAU,GAAG;AAEzD,SAAI,iBAAiB,KAAK,IAAI,QAAQ,WAClC,OAAO,SAAkB;MACvB,MAAM,SAAS,MAAM,OAAO,SAAU,KAAK;AAC3C,UAAI,CAAC,OAAO,QAAS,OAAM,OAAO;AAClC,aAAO,QAAQ,OAAO,MAAM;SAE9B;;;GAIR,MAAM,iBAAiB,cAAc,KAAK;GAE1C,MAAM,gBAAgB,MAAM,SAAS,QAAQ,gBAAgB,IAAI;AAEjE,OAAI,cAAc,OAAO;IACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;AACJ,UAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;AACjE,OAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
1
+ {"version":3,"file":"ai.js","names":[],"sources":["../src/tool.ts"],"sourcesContent":["import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, sanitizeToolName, type ToolDescriptors } from \"./types\";\nimport type { Executor } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nconst DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolDescriptors | ToolSet;\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\ntype CodeInput = z.infer<typeof codeSchema>;\ntype CodeOutput = { code: string; result: unknown; logs?: string[] };\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns an AI SDK compatible tool.\n */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const tools: ToolDescriptors | ToolSet = {};\n for (const [name, t] of Object.entries(options.tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n (tools as Record<string, unknown>)[name] = t;\n }\n }\n\n const types = generateTypes(tools);\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n // Extract execute functions from tools, keyed by name.\n // Wrap each with its schema so arguments from the sandbox\n // are validated before reaching the tool function.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n // Use AI SDK's asSchema() to normalize any schema type\n // (Zod v3/v4, Standard Schema, JSON Schema) into a unified\n // Schema with an optional .validate() method.\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[sanitizeToolName(name)] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(normalizedCode, fns);\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n });\n}\n"],"mappings":";;;;AAOA,MAAM,sBAAsB;;;;;;;;;;AAoB5B,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE,CAAC;;;;;;;AAWF,SAAS,iBAAiB,GAAqC;AAC7D,QAAO,mBAAmB,KAAK,EAAE,iBAAiB;;AAGpD,SAAgB,eACd,SAC6B;CAC7B,MAAM,QAAmC,EAAE;AAC3C,MAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,QAAQ,MAAM,CACnD,KAAI,CAAC,iBAAiB,EAA6B,CAChD,OAAkC,QAAQ;CAI/C,MAAM,QAAQ,cAAc,MAAM;CAClC,MAAM,WAAW,QAAQ;AAOzB,QAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,MACD;EAIC,aAAa;EACb,SAAS,OAAO,EAAE,WAAW;GAI3B,MAAM,MAAgE,EAAE;AAExE,QAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAAE;IAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH,KAAA;AACN,QAAI,SAAS;KACX,MAAM,YACJ,iBAAiB,IACb,EAAE,cACF,gBAAgB,IACb,EAA8B,aAC/B,KAAA;KAKR,MAAM,SAAS,aAAa,OAAO,SAAS,UAAU,GAAG,KAAA;AAEzD,SAAI,iBAAiB,KAAK,IAAI,QAAQ,WAClC,OAAO,SAAkB;MACvB,MAAM,SAAS,MAAM,OAAO,SAAU,KAAK;AAC3C,UAAI,CAAC,OAAO,QAAS,OAAM,OAAO;AAClC,aAAO,QAAQ,OAAO,MAAM;SAE9B;;;GAIR,MAAM,iBAAiB,cAAc,KAAK;GAE1C,MAAM,gBAAgB,MAAM,SAAS,QAAQ,gBAAgB,IAAI;AAEjE,OAAI,cAAc,OAAO;IACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;AACJ,UAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;AACjE,OAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
@@ -93,4 +93,4 @@ export {
93
93
  ToolDescriptors as s,
94
94
  DynamicWorkerExecutor as t
95
95
  };
96
- //# sourceMappingURL=executor-Czw9jKZH.d.ts.map
96
+ //# sourceMappingURL=executor-BYZZhAgd.d.ts.map
package/dist/index.d.ts CHANGED
@@ -8,7 +8,11 @@ import {
8
8
  r as ExecuteResult,
9
9
  s as ToolDescriptors,
10
10
  t as DynamicWorkerExecutor
11
- } from "./executor-Czw9jKZH.js";
11
+ } from "./executor-BYZZhAgd.js";
12
+
13
+ //#region src/normalize.d.ts
14
+ declare function normalizeCode(code: string): string;
15
+ //#endregion
12
16
  export {
13
17
  DynamicWorkerExecutor,
14
18
  type DynamicWorkerExecutorOptions,
@@ -18,5 +22,7 @@ export {
18
22
  type ToolDescriptors,
19
23
  ToolDispatcher,
20
24
  generateTypes,
25
+ normalizeCode,
21
26
  sanitizeToolName
22
27
  };
28
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
- import { n as sanitizeToolName, t as generateTypes } from "./types-CpkEgXwN.js";
1
+ import { n as generateTypes, r as sanitizeToolName, t as normalizeCode } from "./normalize-Dy5d7PfI.js";
2
2
  import { RpcTarget } from "cloudflare:workers";
3
-
4
3
  //#region src/executor.ts
5
4
  /**
6
5
  * Executor interface and DynamicWorkerExecutor implementation.
@@ -103,7 +102,7 @@ var DynamicWorkerExecutor = class {
103
102
  };
104
103
  }
105
104
  };
106
-
107
105
  //#endregion
108
- export { DynamicWorkerExecutor, ToolDispatcher, generateTypes, sanitizeToolName };
106
+ export { DynamicWorkerExecutor, ToolDispatcher, generateTypes, normalizeCode, sanitizeToolName };
107
+
109
108
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable as `codemode.*` inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n */\nexport interface Executor {\n execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// -- ToolDispatcher (RPC target for tool calls from sandboxed Workers) --\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>) {\n super();\n this.#fns = fns;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return JSON.stringify({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? JSON.parse(argsJson) : {};\n const result = await fn(args);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// -- DynamicWorkerExecutor (Cloudflare Workers) --\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes a\n * ToolDispatcher (RpcTarget) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n }\n\n async execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n const timeoutMs = this.#timeout;\n\n const modulePrefix = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(dispatcher) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n \" const codemode = new Proxy({}, {\",\n \" get: (_, toolName) => async (args) => {\",\n \" const resJson = await dispatcher.call(String(toolName), JSON.stringify(args ?? {}));\",\n \" const data = JSON.parse(resJson);\",\n \" if (data.error) throw new Error(data.error);\",\n \" return data.result;\",\n \" }\",\n \" });\",\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ].join(\"\\n\");\n\n const moduleSuffix = [\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ].join(\"\\n\");\n\n const executorModule = modulePrefix + code + moduleSuffix;\n\n const dispatcher = new ToolDispatcher(fns);\n\n const worker = this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"executor.js\",\n modules: {\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatcher: ToolDispatcher): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatcher);\n\n if (response.error) {\n return { result: undefined, error: response.error, logs: response.logs };\n }\n\n return { result: response.result, logs: response.logs };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmCA,IAAa,iBAAb,cAAoC,UAAU;CAC5C;CAEA,YAAY,KAA+D;AACzE,SAAO;AACP,QAAKA,MAAO;;CAGd,MAAM,KAAK,MAAc,UAAmC;EAC1D,MAAM,KAAK,MAAKA,IAAK;AACrB,MAAI,CAAC,GACH,QAAO,KAAK,UAAU,EAAE,OAAO,SAAS,KAAK,cAAc,CAAC;AAE9D,MAAI;GAEF,MAAM,SAAS,MAAM,GADR,WAAW,KAAK,MAAM,SAAS,GAAG,EAAE,CACpB;AAC7B,UAAO,KAAK,UAAU,EAAE,QAAQ,CAAC;WAC1B,KAAK;AACZ,UAAO,KAAK,UAAU,EACpB,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,EACxD,CAAC;;;;;;;;;;;;;AA+BR,IAAa,wBAAb,MAAuD;CACrD;CACA;CACA;CAEA,YAAY,SAAuC;AACjD,QAAKC,SAAU,QAAQ;AACvB,QAAKC,UAAW,QAAQ,WAAW;AACnC,QAAKC,iBAAkB,QAAQ,kBAAkB;;CAGnD,MAAM,QACJ,MACA,KACwB;EACxB,MAAM,YAAY,MAAKD;EAEvB,MAAM,eAAe;GACnB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK;EAEZ,MAAM,eAAe;GACnB;GACA,qGACE,YACA;GACF;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK;EAEZ,MAAM,iBAAiB,eAAe,OAAO;EAE7C,MAAM,aAAa,IAAI,eAAe,IAAI;EAmB1C,MAAM,WAAW,MAjBF,MAAKD,OAAQ,IAAI,YAAY,OAAO,YAAY,WAAW;GACxE,mBAAmB;GACnB,oBAAoB,CAAC,gBAAgB;GACrC,YAAY;GACZ,SAAS,EACP,eAAe,gBAChB;GACD,gBAAgB,MAAKE;GACtB,EAAE,CAEuB,eAAe,CAOP,SAAS,WAAW;AAEtD,MAAI,SAAS,MACX,QAAO;GAAE,QAAQ;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;AAG1E,SAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
1
+ {"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable as `codemode.*` inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n */\nexport interface Executor {\n execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// -- ToolDispatcher (RPC target for tool calls from sandboxed Workers) --\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>) {\n super();\n this.#fns = fns;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return JSON.stringify({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? JSON.parse(argsJson) : {};\n const result = await fn(args);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// -- DynamicWorkerExecutor (Cloudflare Workers) --\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes a\n * ToolDispatcher (RpcTarget) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n }\n\n async execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n const timeoutMs = this.#timeout;\n\n const modulePrefix = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(dispatcher) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n \" const codemode = new Proxy({}, {\",\n \" get: (_, toolName) => async (args) => {\",\n \" const resJson = await dispatcher.call(String(toolName), JSON.stringify(args ?? {}));\",\n \" const data = JSON.parse(resJson);\",\n \" if (data.error) throw new Error(data.error);\",\n \" return data.result;\",\n \" }\",\n \" });\",\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ].join(\"\\n\");\n\n const moduleSuffix = [\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ].join(\"\\n\");\n\n const executorModule = modulePrefix + code + moduleSuffix;\n\n const dispatcher = new ToolDispatcher(fns);\n\n const worker = this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"executor.js\",\n modules: {\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatcher: ToolDispatcher): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatcher);\n\n if (response.error) {\n return { result: undefined, error: response.error, logs: response.logs };\n }\n\n return { result: response.result, logs: response.logs };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAmCA,IAAa,iBAAb,cAAoC,UAAU;CAC5C;CAEA,YAAY,KAA+D;AACzE,SAAO;AACP,QAAA,MAAY;;CAGd,MAAM,KAAK,MAAc,UAAmC;EAC1D,MAAM,KAAK,MAAA,IAAU;AACrB,MAAI,CAAC,GACH,QAAO,KAAK,UAAU,EAAE,OAAO,SAAS,KAAK,cAAc,CAAC;AAE9D,MAAI;GAEF,MAAM,SAAS,MAAM,GADR,WAAW,KAAK,MAAM,SAAS,GAAG,EAAE,CACpB;AAC7B,UAAO,KAAK,UAAU,EAAE,QAAQ,CAAC;WAC1B,KAAK;AACZ,UAAO,KAAK,UAAU,EACpB,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,EACxD,CAAC;;;;;;;;;;;;;AA+BR,IAAa,wBAAb,MAAuD;CACrD;CACA;CACA;CAEA,YAAY,SAAuC;AACjD,QAAA,SAAe,QAAQ;AACvB,QAAA,UAAgB,QAAQ,WAAW;AACnC,QAAA,iBAAuB,QAAQ,kBAAkB;;CAGnD,MAAM,QACJ,MACA,KACwB;EACxB,MAAM,YAAY,MAAA;EAElB,MAAM,eAAe;GACnB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK;EAEZ,MAAM,eAAe;GACnB;GACA,qGACE,YACA;GACF;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK;EAEZ,MAAM,iBAAiB,eAAe,OAAO;EAE7C,MAAM,aAAa,IAAI,eAAe,IAAI;EAmB1C,MAAM,WAAW,MAjBF,MAAA,OAAa,IAAI,YAAY,OAAO,YAAY,WAAW;GACxE,mBAAmB;GACnB,oBAAoB,CAAC,gBAAgB;GACrC,YAAY;GACZ,SAAS,EACP,eAAe,gBAChB;GACD,gBAAgB,MAAA;GACjB,EAAE,CAEuB,eAAe,CAOP,SAAS,WAAW;AAEtD,MAAI,SAAS,MACX,QAAO;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;AAG1E,SAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
@@ -1,5 +1,5 @@
1
- import { createAuxiliaryTypeStore, createTypeAlias, printNode, zodToTs } from "zod-to-ts";
2
-
1
+ import { asSchema } from "ai";
2
+ import * as acorn from "acorn";
3
3
  //#region src/types.ts
4
4
  const JS_RESERVED = new Set([
5
5
  "abstract",
@@ -100,6 +100,13 @@ function isZodSchema(value) {
100
100
  return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
101
101
  }
102
102
  /**
103
+ * Check if a value conforms to the Standard Schema protocol (~standard).
104
+ * This catches Zod v3 schemas (which expose ~standard but not _zod).
105
+ */
106
+ function isStandardSchema(value) {
107
+ return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
108
+ }
109
+ /**
103
110
  * Check if a value is an AI SDK jsonSchema wrapper.
104
111
  * The jsonSchema wrapper has a [Symbol] with jsonSchema property.
105
112
  */
@@ -208,90 +215,94 @@ function jsonSchemaToTypeString(schema, indent, ctx) {
208
215
  if (typeof schema === "boolean") return schema ? "unknown" : "never";
209
216
  if (ctx.depth >= ctx.maxDepth) return "unknown";
210
217
  if (ctx.seen.has(schema)) return "unknown";
218
+ ctx.seen.add(schema);
211
219
  const nextCtx = {
212
220
  ...ctx,
213
- depth: ctx.depth + 1,
214
- seen: new Set([...ctx.seen, schema])
221
+ depth: ctx.depth + 1
215
222
  };
216
- if (schema.$ref) {
217
- const resolved = resolveRef(schema.$ref, ctx.root);
218
- if (!resolved) return "unknown";
219
- return applyNullable(jsonSchemaToTypeString(resolved, indent, nextCtx), schema);
220
- }
221
- if (schema.anyOf) return applyNullable(schema.anyOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(" | "), schema);
222
- if (schema.oneOf) return applyNullable(schema.oneOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(" | "), schema);
223
- if (schema.allOf) return applyNullable(schema.allOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(" & "), schema);
224
- if (schema.enum) {
225
- if (schema.enum.length === 0) return "never";
226
- return applyNullable(schema.enum.map((v) => {
227
- if (v === null) return "null";
228
- if (typeof v === "string") return "\"" + escapeStringLiteral(v) + "\"";
229
- if (typeof v === "object") return JSON.stringify(v) ?? "unknown";
230
- return String(v);
231
- }).join(" | "), schema);
232
- }
233
- if (schema.const !== void 0) return applyNullable(schema.const === null ? "null" : typeof schema.const === "string" ? "\"" + escapeStringLiteral(schema.const) + "\"" : typeof schema.const === "object" ? JSON.stringify(schema.const) ?? "unknown" : String(schema.const), schema);
234
- const type = schema.type;
235
- if (type === "string") return applyNullable("string", schema);
236
- if (type === "number" || type === "integer") return applyNullable("number", schema);
237
- if (type === "boolean") return applyNullable("boolean", schema);
238
- if (type === "null") return "null";
239
- if (type === "array") {
240
- const prefixItems = schema.prefixItems;
241
- if (Array.isArray(prefixItems)) return applyNullable(`[${prefixItems.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(", ")}]`, schema);
242
- if (Array.isArray(schema.items)) return applyNullable(`[${schema.items.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(", ")}]`, schema);
243
- if (schema.items) return applyNullable(`${jsonSchemaToTypeString(schema.items, indent, nextCtx)}[]`, schema);
244
- return applyNullable("unknown[]", schema);
245
- }
246
- if (type === "object" || schema.properties) {
247
- const props = schema.properties || {};
248
- const required = new Set(schema.required || []);
249
- const lines = [];
250
- for (const [propName, propSchema] of Object.entries(props)) {
251
- if (typeof propSchema === "boolean") {
252
- const boolType = propSchema ? "unknown" : "never";
253
- const optionalMark = required.has(propName) ? "" : "?";
254
- lines.push(`${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`);
255
- continue;
256
- }
257
- const isRequired = required.has(propName);
258
- const propType = jsonSchemaToTypeString(propSchema, indent + " ", nextCtx);
259
- const desc = propSchema.description;
260
- const format = propSchema.format;
261
- if (desc || format) {
262
- const descText = desc ? escapeJsDoc(desc.replace(/\r?\n/g, " ")) : void 0;
263
- const formatTag = format ? `@format ${escapeJsDoc(format)}` : void 0;
264
- if (descText && formatTag) {
265
- lines.push(`${indent} /**`);
266
- lines.push(`${indent} * ${descText}`);
267
- lines.push(`${indent} * ${formatTag}`);
268
- lines.push(`${indent} */`);
269
- } else lines.push(`${indent} /** ${descText ?? formatTag} */`);
270
- }
271
- const quotedName = quoteProp(propName);
272
- const optionalMark = isRequired ? "" : "?";
273
- lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);
223
+ try {
224
+ if (schema.$ref) {
225
+ const resolved = resolveRef(schema.$ref, ctx.root);
226
+ if (!resolved) return "unknown";
227
+ return applyNullable(jsonSchemaToTypeString(resolved, indent, nextCtx), schema);
274
228
  }
275
- if (schema.additionalProperties) {
276
- const valueType = schema.additionalProperties === true ? "unknown" : jsonSchemaToTypeString(schema.additionalProperties, indent + " ", nextCtx);
277
- lines.push(`${indent} [key: string]: ${valueType};`);
229
+ if (schema.anyOf) return applyNullable(schema.anyOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(" | "), schema);
230
+ if (schema.oneOf) return applyNullable(schema.oneOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(" | "), schema);
231
+ if (schema.allOf) return applyNullable(schema.allOf.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(" & "), schema);
232
+ if (schema.enum) {
233
+ if (schema.enum.length === 0) return "never";
234
+ return applyNullable(schema.enum.map((v) => {
235
+ if (v === null) return "null";
236
+ if (typeof v === "string") return "\"" + escapeStringLiteral(v) + "\"";
237
+ if (typeof v === "object") return JSON.stringify(v) ?? "unknown";
238
+ return String(v);
239
+ }).join(" | "), schema);
278
240
  }
279
- if (lines.length === 0) {
280
- if (schema.additionalProperties === false) return applyNullable("{}", schema);
281
- return applyNullable("Record<string, unknown>", schema);
241
+ if (schema.const !== void 0) return applyNullable(schema.const === null ? "null" : typeof schema.const === "string" ? "\"" + escapeStringLiteral(schema.const) + "\"" : typeof schema.const === "object" ? JSON.stringify(schema.const) ?? "unknown" : String(schema.const), schema);
242
+ const type = schema.type;
243
+ if (type === "string") return applyNullable("string", schema);
244
+ if (type === "number" || type === "integer") return applyNullable("number", schema);
245
+ if (type === "boolean") return applyNullable("boolean", schema);
246
+ if (type === "null") return "null";
247
+ if (type === "array") {
248
+ const prefixItems = schema.prefixItems;
249
+ if (Array.isArray(prefixItems)) return applyNullable(`[${prefixItems.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(", ")}]`, schema);
250
+ if (Array.isArray(schema.items)) return applyNullable(`[${schema.items.map((s) => jsonSchemaToTypeString(s, indent, nextCtx)).join(", ")}]`, schema);
251
+ if (schema.items) return applyNullable(`${jsonSchemaToTypeString(schema.items, indent, nextCtx)}[]`, schema);
252
+ return applyNullable("unknown[]", schema);
282
253
  }
283
- return applyNullable(`{\n${lines.join("\n")}\n${indent}}`, schema);
284
- }
285
- if (Array.isArray(type)) return applyNullable(type.map((t) => {
286
- if (t === "string") return "string";
287
- if (t === "number" || t === "integer") return "number";
288
- if (t === "boolean") return "boolean";
289
- if (t === "null") return "null";
290
- if (t === "array") return "unknown[]";
291
- if (t === "object") return "Record<string, unknown>";
254
+ if (type === "object" || schema.properties) {
255
+ const props = schema.properties || {};
256
+ const required = new Set(schema.required || []);
257
+ const lines = [];
258
+ for (const [propName, propSchema] of Object.entries(props)) {
259
+ if (typeof propSchema === "boolean") {
260
+ const boolType = propSchema ? "unknown" : "never";
261
+ const optionalMark = required.has(propName) ? "" : "?";
262
+ lines.push(`${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`);
263
+ continue;
264
+ }
265
+ const isRequired = required.has(propName);
266
+ const propType = jsonSchemaToTypeString(propSchema, indent + " ", nextCtx);
267
+ const desc = propSchema.description;
268
+ const format = propSchema.format;
269
+ if (desc || format) {
270
+ const descText = desc ? escapeJsDoc(desc.replace(/\r?\n/g, " ")) : void 0;
271
+ const formatTag = format ? `@format ${escapeJsDoc(format)}` : void 0;
272
+ if (descText && formatTag) {
273
+ lines.push(`${indent} /**`);
274
+ lines.push(`${indent} * ${descText}`);
275
+ lines.push(`${indent} * ${formatTag}`);
276
+ lines.push(`${indent} */`);
277
+ } else lines.push(`${indent} /** ${descText ?? formatTag} */`);
278
+ }
279
+ const quotedName = quoteProp(propName);
280
+ const optionalMark = isRequired ? "" : "?";
281
+ lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);
282
+ }
283
+ if (schema.additionalProperties) {
284
+ const valueType = schema.additionalProperties === true ? "unknown" : jsonSchemaToTypeString(schema.additionalProperties, indent + " ", nextCtx);
285
+ lines.push(`${indent} [key: string]: ${valueType};`);
286
+ }
287
+ if (lines.length === 0) {
288
+ if (schema.additionalProperties === false) return applyNullable("{}", schema);
289
+ return applyNullable("Record<string, unknown>", schema);
290
+ }
291
+ return applyNullable(`{\n${lines.join("\n")}\n${indent}}`, schema);
292
+ }
293
+ if (Array.isArray(type)) return applyNullable(type.map((t) => {
294
+ if (t === "string") return "string";
295
+ if (t === "number" || t === "integer") return "number";
296
+ if (t === "boolean") return "boolean";
297
+ if (t === "null") return "null";
298
+ if (t === "array") return "unknown[]";
299
+ if (t === "object") return "Record<string, unknown>";
300
+ return "unknown";
301
+ }).join(" | "), schema);
292
302
  return "unknown";
293
- }).join(" | "), schema);
294
- return "unknown";
303
+ } finally {
304
+ ctx.seen.delete(schema);
305
+ }
295
306
  }
296
307
  /**
297
308
  * Apply OpenAPI 3.0 `nullable: true` to a type result.
@@ -309,8 +320,9 @@ function extractDescriptions(schema) {
309
320
  const shape = schema.shape;
310
321
  if (shape && typeof shape === "object") {
311
322
  for (const [fieldName, fieldSchema] of Object.entries(shape)) {
312
- const desc = fieldSchema.description;
313
- if (desc) descriptions[fieldName] = desc;
323
+ let s = fieldSchema;
324
+ while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
325
+ if (s.description) descriptions[fieldName] = s.description;
314
326
  }
315
327
  return descriptions;
316
328
  }
@@ -324,12 +336,20 @@ function extractDescriptions(schema) {
324
336
  }
325
337
  /**
326
338
  * Safely convert a schema to TypeScript type string.
327
- * Handles Zod schemas and AI SDK jsonSchema wrappers.
339
+ * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
328
340
  * Returns "unknown" if the schema cannot be represented in TypeScript.
329
341
  */
330
- function safeSchemaToTs(schema, typeName, auxiliaryTypeStore) {
342
+ function safeSchemaToTs(schema, typeName) {
331
343
  try {
332
- if (isZodSchema(schema)) return printNode(createTypeAlias(zodToTs(schema, { auxiliaryTypeStore }).node, typeName));
344
+ if (isZodSchema(schema) || isStandardSchema(schema)) {
345
+ const jsonSchema = asSchema(schema).jsonSchema;
346
+ if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
347
+ root: jsonSchema,
348
+ depth: 0,
349
+ seen: /* @__PURE__ */ new Set(),
350
+ maxDepth: 20
351
+ })}`;
352
+ }
333
353
  if (isJsonSchemaWrapper(schema)) {
334
354
  const jsonSchema = extractJsonSchema(schema);
335
355
  if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
@@ -351,7 +371,6 @@ function safeSchemaToTs(schema, typeName, auxiliaryTypeStore) {
351
371
  function generateTypes(tools) {
352
372
  let availableTools = "";
353
373
  let availableTypes = "";
354
- const auxiliaryTypeStore = createAuxiliaryTypeStore();
355
374
  for (const [toolName, tool] of Object.entries(tools)) {
356
375
  const safeName = sanitizeToolName(toolName);
357
376
  const camelName = toCamelCase(safeName);
@@ -359,8 +378,8 @@ function generateTypes(tools) {
359
378
  const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
360
379
  const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
361
380
  const description = tool.description;
362
- const inputType = safeSchemaToTs(inputSchema, `${camelName}Input`, auxiliaryTypeStore);
363
- const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${camelName}Output`, auxiliaryTypeStore) : `type ${camelName}Output = unknown`;
381
+ const inputType = safeSchemaToTs(inputSchema, `${camelName}Input`);
382
+ const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${camelName}Output`) : `type ${camelName}Output = unknown`;
364
383
  availableTypes += `\n${inputType.trim()}`;
365
384
  availableTypes += `\n${outputType.trim()}`;
366
385
  const paramDescs = inputSchema ? extractParamDescriptions(inputSchema) : [];
@@ -386,7 +405,47 @@ ${availableTypes}
386
405
  ${availableTools}
387
406
  `.trim();
388
407
  }
389
-
390
408
  //#endregion
391
- export { sanitizeToolName as n, generateTypes as t };
392
- //# sourceMappingURL=types-CpkEgXwN.js.map
409
+ //#region src/normalize.ts
410
+ /**
411
+ * Strip markdown code fences that LLMs commonly wrap code in.
412
+ * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
413
+ */
414
+ function stripCodeFences(code) {
415
+ const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
416
+ return match ? match[1] : code;
417
+ }
418
+ function normalizeCode(code) {
419
+ const trimmed = stripCodeFences(code.trim());
420
+ if (!trimmed.trim()) return "async () => {}";
421
+ const source = trimmed.trim();
422
+ try {
423
+ const ast = acorn.parse(source, {
424
+ ecmaVersion: "latest",
425
+ sourceType: "module"
426
+ });
427
+ if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
428
+ if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
429
+ }
430
+ if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
431
+ const decl = ast.body[0].declaration;
432
+ const inner = source.slice(decl.start, decl.end);
433
+ if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
434
+ if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
435
+ return normalizeCode(inner);
436
+ }
437
+ if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
438
+ const last = ast.body[ast.body.length - 1];
439
+ if (last?.type === "ExpressionStatement") {
440
+ const exprStmt = last;
441
+ return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
442
+ }
443
+ return `async () => {\n${source}\n}`;
444
+ } catch {
445
+ return `async () => {\n${source}\n}`;
446
+ }
447
+ }
448
+ //#endregion
449
+ export { generateTypes as n, sanitizeToolName as r, normalizeCode as t };
450
+
451
+ //# sourceMappingURL=normalize-Dy5d7PfI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize-Dy5d7PfI.js","names":[],"sources":["../src/types.ts","../src/normalize.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\n\ninterface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\nconst JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nfunction toCamelCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n * Returns an array of `@param input.fieldName - description` lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n // AI SDK jsonSchema wrapper stores data in a symbol property\n // but also exposes jsonSchema directly in some versions\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n // Check for symbol-based storage (AI SDK internal)\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n // Direct property access\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n // Symbol-based storage\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Check if a property name needs quoting in TypeScript.\n */\nfunction needsQuotes(name: string): boolean {\n // Valid JS identifier: starts with letter, $, or _, followed by letters, digits, $, _\n return !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nfunction quoteProp(name: string): string {\n if (needsQuotes(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n * Handles backslashes, quotes, newlines, control characters, and line/paragraph separators.\n */\nfunction escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nfunction escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nfunction jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n // Multi-line JSDoc when both description and format are present\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n // NOTE: In TypeScript, an index signature [key: string]: T requires all\n // named properties to be assignable to T. If any named property has an\n // incompatible type, the generated type is invalid. We emit it anyway\n // since it's more informative for LLMs consuming these types.\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n // additionalProperties: false means no keys allowed → empty object\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n // Try Zod schema shape\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n // Unwrap optional/nullable/default wrappers to find .description\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n // Try JSON Schema properties (for jsonSchema wrapper)\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n * Returns \"unknown\" if the schema cannot be represented in TypeScript.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n // For Zod schemas (v4 via _zod, v3 via ~standard), convert to JSON Schema\n // via AI SDK's asSchema() then use jsonSchemaToTypeString()\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n // For JSON Schema wrapper, convert directly to TypeScript\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n // If the schema cannot be represented, fall back to unknown\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n */\nexport function generateTypes(tools: ToolDescriptors | ToolSet): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const camelName = toCamelCase(safeName);\n\n try {\n // Handle both our ToolDescriptor and AI SDK Tool types\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${camelName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${camelName}Output`)\n : `type ${camelName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n // Build JSDoc comment with description and param descriptions\n const paramDescs = inputSchema\n ? extractParamDescriptions(inputSchema)\n : [];\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${camelName}Input) => Promise<${camelName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n // One bad tool should not break the others — emit unknown types\n availableTypes += `\\ntype ${camelName}Input = unknown`;\n availableTypes += `\\ntype ${camelName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${camelName}Input) => Promise<${camelName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n"],"mappings":";;;AAYA,MAAM,cAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA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BACd,CAAE,KAAmC,GAErC,QAAO,0BAA0B,MAAM;AAEzC,OACE,KAAK,SAAS,sBACd,CAAE,KAAgC,GAElC,QAAO,0BAA0B,MAAM;AAGzC,UAAO,cAAc,MAAM;;AAI7B,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS,sBAGhD,QAAO,kBAAkB,OAAO,WAFrB,IAAI,KAAK,GACJ,IAAI,QAAQ,KACoB;EAIlD,MAAM,OAAO,IAAI,KAAK,IAAI,KAAK,SAAS;AACxC,MAAI,MAAM,SAAS,uBAAuB;GACxC,MAAM,WAAW;AAMjB,UAAO,kBALQ,OAAO,MAAM,GAAG,KAAK,MAAM,CAKV,UAJf,OAAO,MACtB,SAAS,WAAW,OACpB,SAAS,WAAW,IACrB,CACkD;;AAGrD,SAAO,kBAAkB,OAAO;SAC1B;AACN,SAAO,kBAAkB,OAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -11,12 +11,11 @@
11
11
  "url": "https://github.com/cloudflare/agents/issues"
12
12
  },
13
13
  "dependencies": {
14
- "acorn": "^8.16.0",
15
- "zod-to-ts": "^2.0.0"
14
+ "acorn": "^8.16.0"
16
15
  },
17
16
  "devDependencies": {
18
17
  "@playwright/test": "^1.58.2",
19
- "ai": "^6.0.97",
18
+ "ai": "^6.0.116",
20
19
  "vitest": "3.2.4",
21
20
  "zod": "^4.3.6"
22
21
  },
@@ -52,5 +51,9 @@
52
51
  ],
53
52
  "author": "Cloudflare Inc.",
54
53
  "license": "MIT",
55
- "type": "module"
54
+ "type": "module",
55
+ "files": [
56
+ "dist",
57
+ "README.md"
58
+ ]
56
59
  }