@cloudflare/codemode 0.3.5 → 0.3.6

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,15 +1,15 @@
1
1
  import {
2
- c as generateTypes,
2
+ c as ResolvedProvider,
3
+ d as generateTypes,
3
4
  i as ToolProvider,
4
- o as ToolDescriptor,
5
- s as ToolDescriptors
6
- } from "./executor-C-DgAHLS.js";
7
- import { r as ResolvedProvider } from "./executor-types-CJ06IBzw.js";
5
+ l as ToolDescriptor,
6
+ u as ToolDescriptors
7
+ } from "./executor-BWtTiHBV.js";
8
8
  import {
9
9
  n as CodeOutput,
10
10
  r as CreateCodeToolOptions,
11
11
  t as CodeInput
12
- } from "./shared-C3CDOc8T.js";
12
+ } from "./shared-CcZcDoiO.js";
13
13
  import { Tool, ToolSet } from "ai";
14
14
 
15
15
  //#region src/tool.d.ts
package/dist/ai.js CHANGED
@@ -1,6 +1,7 @@
1
- import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString, s as normalizeCode } from "./json-schema-types-CVt4X9cw.js";
1
+ import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-CVt4X9cw.js";
2
2
  import { n as filterTools } from "./resolve-BU1FGVYs.js";
3
- import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-ra3HW2ti.js";
3
+ import { t as runCode } from "./run-code-5x8S5YWt.js";
4
+ import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-xjl2irqK.js";
4
5
  import { asSchema, tool } from "ai";
5
6
  import { z } from "zod";
6
7
  //#region src/tool-types.ts
@@ -223,20 +224,11 @@ function createCodeTool(options) {
223
224
  return tool({
224
225
  description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
225
226
  inputSchema: codeSchema,
226
- execute: async ({ code }) => {
227
- const normalizedCode = normalizeCode(code);
228
- const executeResult = await executor.execute(normalizedCode, resolvedProviders);
229
- if (executeResult.error) {
230
- const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
231
- throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
232
- }
233
- const output = {
234
- code,
235
- result: executeResult.result
236
- };
237
- if (executeResult.logs) output.logs = executeResult.logs;
238
- return output;
239
- }
227
+ execute: async ({ code }) => runCode({
228
+ code,
229
+ executor,
230
+ providers: resolvedProviders
231
+ })
240
232
  });
241
233
  }
242
234
  //#endregion
package/dist/ai.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ai.js","names":[],"sources":["../src/tool-types.ts","../src/tool.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\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 if (\"jsonSchema\" in value) {\n return true;\n }\n\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 if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\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 * 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 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 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 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 * Extract field descriptions from a schema and format as @param 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\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\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 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 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 *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(\n tools: ToolDescriptors | ToolSet,\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\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, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\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: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\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 const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[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 return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [stateTools(workspace), aiTools(myTools)],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\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":";;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;CACjD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS,oBACP,OACsC;CACtC,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CAExD,IAAI,gBAAgB,OAClB,OAAO;CAGT,MAAM,UAAU,OAAO,sBAAsB,MAAM;CACnD,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,MAAkC;EACpD,IAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,UAC9D,OAAO;;CAIX,OAAO;;;;;AAMT,SAAS,kBAAkB,SAAsC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,YAAY,mBAAmB,QAAQ,MAAM;CAGnD,MAAM,aAAuB,EAAE;CAC/B,MAAM,oBAAwC,EAAE;CAEhD,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,WAAW,YAAY,SAAS,MAAM;EAC5C,MAAM,QACJ,SAAS,SAAS,cAAc,UAA6B,KAAK;EACpE,WAAW,KAAK,MAAM;EACtB,MAAM,WAA6B;GAAE;GAAM,KAAK,WAAW,SAAS;GAAE;EACtE,IAAI,SAAS,gBAAgB,SAAS,iBAAiB;EACvD,kBAAkB,KAAK,SAAS;;CAGlC,MAAM,YAAY,WAAW,OAAO,QAAQ,CAAC,KAAK,OAAO;CAEzD,MAAM,WAAW,QAAQ;CAOzB,OAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,UAIW;EACX,aAAa;EACb,SAAS,OAAO,EAAE,WAAW;GAC3B,MAAM,iBAAiB,cAAc,KAAK;GAE1C,MAAM,gBAAgB,MAAM,SAAS,QACnC,gBACA,kBACD;GAED,IAAI,cAAc,OAAO;IACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;IACJ,MAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;GACjE,IAAI,cAAc,MAAM,OAAO,OAAO,cAAc;GACpD,OAAO;;EAEV,CAAC"}
1
+ {"version":3,"file":"ai.js","names":[],"sources":["../src/tool-types.ts","../src/tool.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\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 if (\"jsonSchema\" in value) {\n return true;\n }\n\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 if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\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 * 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 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 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 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 * Extract field descriptions from a schema and format as @param 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\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\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 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 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 *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(\n tools: ToolDescriptors | ToolSet,\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\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, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\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: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\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 const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[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 return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [stateTools(workspace), aiTools(myTools)],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n });\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;CACjD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS,o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;;;;;;;;;;AAcT,SAAgB,QAAQ,OAAgD;CACtE,OAAO,EAAE,OAAO;;;;;;AAOlB,SAAgB,gBAAgB,UAA0C;CAGxE,MAAM,WAA6B;EAAE,MAFxB,SAAS,QAAQ;EAEa,KAAK,WAD/B,YAAY,SAAS,MAC6B,CAAC;EAAE;CACtE,IAAI,SAAS,gBAAgB,SAAS,iBAAiB;CACvD,OAAO;;AAGT,SAAgB,eACd,SAC6B;CAC7B,MAAM,YAAY,mBAAmB,QAAQ,MAAM;CAGnD,MAAM,aAAuB,EAAE;CAC/B,MAAM,oBAAwC,EAAE;CAEhD,KAAK,MAAM,YAAY,WAAW;EAChC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,WAAW,YAAY,SAAS,MAAM;EAC5C,MAAM,QACJ,SAAS,SAAS,cAAc,UAA6B,KAAK;EACpE,WAAW,KAAK,MAAM;EACtB,MAAM,WAA6B;GAAE;GAAM,KAAK,WAAW,SAAS;GAAE;EACtE,IAAI,SAAS,gBAAgB,SAAS,iBAAiB;EACvD,kBAAkB,KAAK,SAAS;;CAGlC,MAAM,YAAY,WAAW,OAAO,QAAQ,CAAC,KAAK,OAAO;CAEzD,MAAM,WAAW,QAAQ;CAOzB,OAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,UAIW;EACX,aAAa;EACb,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;GAAmB,CAAC;EAC5D,CAAC"}
package/dist/browser.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import {
2
- n as Executor,
3
- r as ResolvedProvider,
4
- t as ExecuteResult
5
- } from "./executor-types-CJ06IBzw.js";
2
+ c as ResolvedProvider,
3
+ o as ExecuteResult,
4
+ s as Executor
5
+ } from "./executor-BWtTiHBV.js";
6
+ import { n as CodeOutput, t as CodeInput } from "./shared-CcZcDoiO.js";
6
7
  import {
7
8
  n as JsonSchemaToolDescriptors,
8
9
  t as JsonSchemaToolDescriptor
@@ -73,10 +74,6 @@ interface BrowserCodeToolDescriptor {
73
74
  outputSchema: {
74
75
  type: "object";
75
76
  properties: {
76
- code: {
77
- type: "string";
78
- description: string;
79
- };
80
77
  result: {
81
78
  description: string;
82
79
  };
@@ -88,13 +85,9 @@ interface BrowserCodeToolDescriptor {
88
85
  description: string;
89
86
  };
90
87
  };
91
- required: ["code", "result"];
88
+ required: ["result"];
92
89
  };
93
- execute: (args: { code: string }) => Promise<{
94
- code: string;
95
- result: unknown;
96
- logs?: string[];
97
- }>;
90
+ execute: (args: CodeInput) => Promise<CodeOutput>;
98
91
  }
99
92
  interface CreateBrowserCodeToolOptions {
100
93
  /**
package/dist/browser.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-CVt4X9cw.js";
2
+ import { t as runCode } from "./run-code-5x8S5YWt.js";
2
3
  //#region src/messages.ts
3
4
  function isRecord(value) {
4
5
  return typeof value === "object" && value !== null;
@@ -486,10 +487,6 @@ function createBrowserCodeTool(options) {
486
487
  outputSchema: {
487
488
  type: "object",
488
489
  properties: {
489
- code: {
490
- type: "string",
491
- description: "The original code that was executed"
492
- },
493
490
  result: { description: "The return value of the executed code" },
494
491
  logs: {
495
492
  type: "array",
@@ -497,22 +494,13 @@ function createBrowserCodeTool(options) {
497
494
  description: "Console output captured during execution"
498
495
  }
499
496
  },
500
- required: ["code", "result"]
497
+ required: ["result"]
501
498
  },
502
- execute: async ({ code }) => {
503
- const normalizedCode = normalizeCode(code);
504
- const executeResult = await executor.execute(normalizedCode, resolvedProviders);
505
- if (executeResult.error) {
506
- const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
507
- throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
508
- }
509
- const output = {
510
- code,
511
- result: executeResult.result
512
- };
513
- if (executeResult.logs) output.logs = executeResult.logs;
514
- return output;
515
- }
499
+ execute: async ({ code }) => runCode({
500
+ code,
501
+ executor,
502
+ providers: resolvedProviders
503
+ })
516
504
  };
517
505
  }
518
506
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"browser.js","names":["#timeout","#csp"],"sources":["../src/messages.ts","../src/iframe-runtime.ts","../src/iframe-executor.ts","../src/browser-tool.ts"],"sourcesContent":["/**\n * Typed postMessage protocol for host ↔ iframe sandbox communication.\n *\n * Messages flow in two directions:\n * - Sandbox → Host: tool calls and execution results\n * - Host → Sandbox: tool results and execute requests\n */\n\nimport type { ExecuteResult } from \"./executor-types\";\n\n// -- Helpers --\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n// -- Sandbox → Host messages --\n\nexport interface ToolCallMessage {\n type: \"tool-call\";\n nonce: string;\n id: number;\n provider: string;\n name: string;\n args: unknown;\n}\n\nexport interface ExecutionResultMessage {\n type: \"execution-result\";\n nonce: string;\n result: ExecuteResult;\n}\n\nexport interface SandboxReadyMessage {\n type: \"sandbox-ready\";\n}\n\n// -- Host → Sandbox messages --\n\nexport interface ToolResultSuccessMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result: unknown;\n}\n\nexport interface ToolResultErrorMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n error: string;\n}\n\nexport interface ExecuteRequestMessage {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string; positionalArgs?: boolean }[];\n}\n\n// -- Type guards --\n\nexport function isSandboxReadyMessage(\n data: unknown\n): data is SandboxReadyMessage {\n return isRecord(data) && data.type === \"sandbox-ready\";\n}\n\nexport function isToolCallMessage(data: unknown): data is ToolCallMessage {\n return (\n isRecord(data) &&\n data.type === \"tool-call\" &&\n typeof data.nonce === \"string\" &&\n typeof data.id === \"number\" &&\n typeof data.provider === \"string\" &&\n typeof data.name === \"string\"\n );\n}\n\nexport function isExecutionResultMessage(\n data: unknown\n): data is ExecutionResultMessage {\n if (!isRecord(data)) return false;\n if (data.type !== \"execution-result\") return false;\n if (typeof data.nonce !== \"string\") return false;\n if (typeof data.result !== \"object\" || data.result === null) return false;\n return true;\n}\n\nexport function isExecuteRequestMessageShape(\n data: unknown\n): data is ExecuteRequestMessage {\n return (\n isRecord(data) &&\n data.type === \"execute-request\" &&\n typeof data.nonce === \"string\" &&\n typeof data.code === \"string\" &&\n Array.isArray(data.providers) &&\n data.providers.every(\n (provider) =>\n isRecord(provider) &&\n typeof provider.name === \"string\" &&\n (provider.positionalArgs === undefined ||\n typeof provider.positionalArgs === \"boolean\")\n )\n );\n}\n","/**\n * Self-contained runtime that boots inside the sandboxed iframe.\n *\n * The `iframeSandboxRuntimeMain` function is serialized via `.toString()`\n * and injected into the iframe's `srcdoc`. It MUST be fully self-contained —\n * no closures over module-level variables, no imported values at runtime.\n * (Type-only imports are safe because they are erased at compile time.)\n */\n\n/**\n * The iframe-side runtime entry point.\n *\n * This function is stringified and injected into the iframe via srcdoc.\n * Everything it needs must be defined inside its own scope.\n */\nfunction iframeSandboxRuntimeMain(): void {\n const runtimeWindow = window as Window &\n typeof globalThis & { __codemodeIframeInitialized?: boolean };\n\n if (runtimeWindow.__codemodeIframeInitialized) {\n return;\n }\n\n runtimeWindow.__codemodeIframeInitialized = true;\n\n const logs: string[] = [];\n const pending: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n > = {};\n let nextId = 0;\n let activeNonce: string | undefined;\n\n function post(message: unknown) {\n parent.postMessage(message, \"*\");\n }\n\n // Capture console output\n console.log = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(values.join(\" \"));\n };\n console.warn = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[warn] \" + values.join(\" \"));\n };\n console.error = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[error] \" + values.join(\" \"));\n };\n\n function createProviderProxy(\n nonce: string,\n provider: {\n name: string;\n positionalArgs?: boolean;\n }\n ) {\n return new Proxy(\n {},\n {\n get: (_, toolName) => {\n if (provider.positionalArgs) {\n return (...args: unknown[]) => {\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending[id] = { resolve, reject };\n post({\n type: \"tool-call\",\n nonce,\n id,\n provider: provider.name,\n name: String(toolName),\n args\n });\n });\n };\n }\n\n return (args: unknown) => {\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending[id] = { resolve, reject };\n post({\n type: \"tool-call\",\n nonce,\n id,\n provider: provider.name,\n name: String(toolName),\n args: args ?? {}\n });\n });\n };\n }\n }\n );\n }\n\n function isToolResultMessage(message: unknown): message is {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result?: unknown;\n error?: string;\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"tool-result\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.id === \"number\"\n );\n }\n\n function isExecuteRequestMessage(message: unknown): message is {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string; positionalArgs?: boolean }[];\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"execute-request\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.code === \"string\" &&\n Array.isArray(candidate.providers) &&\n candidate.providers.every(\n (provider) =>\n typeof provider === \"object\" &&\n provider !== null &&\n typeof (provider as { name?: unknown }).name === \"string\" &&\n ((provider as { positionalArgs?: unknown }).positionalArgs ===\n undefined ||\n typeof (provider as { positionalArgs?: unknown }).positionalArgs ===\n \"boolean\")\n )\n );\n }\n\n function executeCode(\n nonce: string,\n code: string,\n providers: { name: string; positionalArgs?: boolean }[]\n ) {\n try {\n activeNonce = nonce;\n const providerNames: string[] = [];\n const providerProxies: unknown[] = [];\n for (const provider of providers) {\n providerNames.push(provider.name);\n providerProxies.push(createProviderProxy(nonce, provider));\n }\n\n const fn = new Function(...providerNames, \"return (\" + code + \")\")(\n ...providerProxies\n );\n Promise.resolve(fn())\n .then((result: unknown) => {\n post({ type: \"execution-result\", nonce, result: { result, logs } });\n })\n .catch((err: Error) => {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err.message || String(err),\n logs\n }\n });\n });\n } catch (err) {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err instanceof Error ? err.message : String(err),\n logs\n }\n });\n }\n }\n\n window.addEventListener(\"message\", (event) => {\n if (event.source !== parent) return;\n\n const message = event.data;\n\n if (isToolResultMessage(message)) {\n if (message.nonce !== activeNonce) return;\n const request = pending[message.id];\n if (!request) return;\n\n delete pending[message.id];\n if (\"error\" in message)\n request.reject(new Error(message.error as string));\n else request.resolve(message.result);\n return;\n }\n\n if (isExecuteRequestMessage(message)) {\n executeCode(message.nonce, message.code, message.providers);\n }\n });\n\n post({ type: \"sandbox-ready\" });\n}\n\n/**\n * Returns a self-contained script string that boots the codemode iframe runtime.\n */\nexport function createIframeSandboxRuntimeScript(): string {\n return `;(${iframeSandboxRuntimeMain.toString()})();`;\n}\n","/**\n * IframeSandboxExecutor — a browser-native Executor that runs LLM-generated\n * code in a sandboxed iframe using postMessage for tool dispatch.\n *\n * Zero dependencies — uses only browser APIs (iframe, postMessage, CSP).\n */\n\nimport {\n type ExecuteRequestMessage,\n isExecutionResultMessage,\n isSandboxReadyMessage,\n isToolCallMessage,\n type ToolResultErrorMessage,\n type ToolResultSuccessMessage\n} from \"./messages\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { createIframeSandboxRuntimeScript } from \"./iframe-runtime\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\n\nexport interface IframeSandboxExecutorOptions {\n /** Maximum execution time in milliseconds. Defaults to `30000`. */\n timeout?: number;\n /**\n * Content Security Policy applied to the iframe document.\n *\n * When omitted, defaults to a restrictive policy that only allows\n * inline scripts and eval (needed for code execution).\n */\n csp?: string;\n}\n\nconst DEFAULT_CSP =\n \"default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval';\";\nconst DEFAULT_TIMEOUT = 30000;\n\nfunction escapeHtmlAttribute(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n}\n\nfunction escapeInlineScript(value: string): string {\n return value.replace(/<\\/script/gi, \"<\\\\/script\");\n}\n\nfunction buildSrcdoc(csp: string): string {\n const runtimeScript = escapeInlineScript(createIframeSandboxRuntimeScript());\n const safeCsp = escapeHtmlAttribute(csp);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content=\"${safeCsp}\">\n</head>\n<body>\n<script>\n${runtimeScript}\n</script>\n</body>\n</html>`;\n}\n\nfunction createToolResultMessage(\n nonce: string,\n id: number,\n value: unknown,\n isError: boolean\n): ToolResultSuccessMessage | ToolResultErrorMessage {\n if (isError) {\n return {\n type: \"tool-result\",\n nonce,\n id,\n error: value instanceof Error ? value.message : String(value)\n };\n }\n return { type: \"tool-result\", nonce, id, result: value };\n}\n\nfunction createExecutionNonce(): string {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\"\n );\n}\n\n/**\n * Executes LLM-generated code in a browser iframe sandbox.\n *\n * For each execution, a hidden iframe is created with `sandbox=\"allow-scripts\"`,\n * the runtime is injected via `srcdoc`, and the iframe is removed after completion.\n * Tool calls are dispatched via `postMessage`.\n */\nexport class IframeSandboxExecutor implements Executor {\n #timeout: number;\n #csp: string;\n\n constructor(options?: IframeSandboxExecutorOptions) {\n this.#timeout = options?.timeout ?? DEFAULT_TIMEOUT;\n this.#csp = options?.csp ?? DEFAULT_CSP;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const reservedNames = new Set([\"__dispatchers\", \"__logs\"]);\n const validIdent = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (reservedNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!validIdent.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n const normalizedCode = normalizeCode(code);\n const resolvedProviders: ResolvedProvider[] = [];\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n const resolved: ResolvedProvider = {\n name: provider.name,\n fns: sanitizedFns\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n const providerMap = new Map(\n resolvedProviders.map((provider) => [provider.name, provider] as const)\n );\n const nonce = createExecutionNonce();\n\n const executeRequest: ExecuteRequestMessage = {\n type: \"execute-request\",\n nonce,\n code: normalizedCode,\n providers: resolvedProviders.map((provider) => {\n if (provider.positionalArgs) {\n return { name: provider.name, positionalArgs: true };\n }\n return { name: provider.name };\n })\n };\n\n const invokeProviderTool = async (\n provider: ResolvedProvider,\n args: unknown,\n name: string\n ) => {\n const fn = provider.fns[name];\n if (!fn) {\n throw new Error(`Tool \"${name}\" not found`);\n }\n if (!provider.positionalArgs) {\n return fn(args);\n }\n const positionalArgs = Array.isArray(args) ? args : [args];\n return fn(...positionalArgs);\n };\n\n const iframe = document.createElement(\"iframe\");\n iframe.sandbox.add(\"allow-scripts\");\n iframe.style.display = \"none\";\n iframe.style.width = \"0\";\n iframe.style.height = \"0\";\n iframe.style.border = \"none\";\n iframe.srcdoc = buildSrcdoc(this.#csp);\n\n return new Promise<ExecuteResult>((resolve) => {\n let settled = false;\n let ready = false;\n const warnedInvalidNonceTypes = new Set<string>();\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n window.removeEventListener(\"message\", handler);\n iframe.removeEventListener(\"error\", handleLoadError);\n iframe.remove();\n };\n\n const resolveError = (message: string) => {\n cleanup();\n resolve({ result: undefined, error: message, logs: [] });\n };\n\n const postToChild = (\n message:\n | ToolResultSuccessMessage\n | ToolResultErrorMessage\n | ExecuteRequestMessage\n ): boolean => {\n const child = iframe.contentWindow;\n if (!child) {\n resolveError(\"Sandbox iframe is not available\");\n return false;\n }\n\n try {\n child.postMessage(message, \"*\");\n return true;\n } catch (err) {\n resolveError(err instanceof Error ? err.message : String(err));\n return false;\n }\n };\n\n const warnInvalidNonce = (messageType: string) => {\n if (warnedInvalidNonceTypes.has(messageType)) return;\n warnedInvalidNonceTypes.add(messageType);\n console.warn(\n `[@cloudflare/codemode] Ignoring sandbox ${messageType} message with invalid execution nonce`\n );\n };\n\n const handler = async (event: MessageEvent) => {\n if (event.source !== iframe.contentWindow) return;\n\n const data: unknown = event.data;\n\n if (isSandboxReadyMessage(data)) {\n if (ready) return;\n ready = true;\n postToChild(executeRequest);\n return;\n }\n\n if (isToolCallMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"tool-call\");\n return;\n }\n const provider = providerMap.get(data.provider);\n if (!provider) {\n postToChild(\n createToolResultMessage(\n nonce,\n data.id,\n `Provider \"${data.provider}\" not found`,\n true\n )\n );\n return;\n }\n try {\n const result = await invokeProviderTool(\n provider,\n data.args,\n data.name\n );\n postToChild(createToolResultMessage(nonce, data.id, result, false));\n } catch (err) {\n postToChild(createToolResultMessage(nonce, data.id, err, true));\n }\n return;\n }\n\n if (isExecutionResultMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"execution-result\");\n return;\n }\n cleanup();\n resolve(data.result);\n }\n };\n\n const handleLoadError = () => {\n resolveError(\"Sandbox iframe failed to load\");\n };\n\n window.addEventListener(\"message\", handler);\n iframe.addEventListener(\"error\", handleLoadError);\n\n const timer = setTimeout(() => {\n cleanup();\n resolve({ result: undefined, error: \"Execution timed out\", logs: [] });\n }, this.#timeout);\n\n document.body.appendChild(iframe);\n });\n }\n}\n","/**\n * Zero-dependency browser counterpart to `createCodeTool` from `./ai`.\n *\n * Returns a plain JSON Schema tool descriptor instead of an AI SDK `Tool`.\n * No `ai`, no `zod` — just JSON Schema and browser APIs. JSON Schema is used\n * for generated types only; this helper does not perform runtime validation.\n */\n\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptor,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor, ResolvedProvider } from \"./executor-types\";\nimport { IframeSandboxExecutor } from \"./iframe-executor\";\n\n// -- Types --\n\n/**\n * A JSON Schema tool descriptor with an execute function attached.\n */\nexport interface JsonSchemaExecutableToolDescriptor extends JsonSchemaToolDescriptor {\n name?: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type JsonSchemaExecutableToolDescriptors = Record<\n string,\n JsonSchemaExecutableToolDescriptor\n>;\n\ninterface ApprovalAwareJsonSchemaExecutableToolDescriptor extends JsonSchemaExecutableToolDescriptor {\n needsApproval?: boolean | ((...args: unknown[]) => unknown);\n}\n\ntype ApprovalAwareJsonSchemaExecutableToolDescriptors = Record<\n string,\n ApprovalAwareJsonSchemaExecutableToolDescriptor\n>;\n\nexport interface BrowserCodeToolDescriptor {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: {\n code: { type: \"string\"; description: string };\n };\n required: [\"code\"];\n };\n outputSchema: {\n type: \"object\";\n properties: {\n code: { type: \"string\"; description: string };\n result: { description: string };\n logs: {\n type: \"array\";\n items: { type: \"string\" };\n description: string;\n };\n };\n required: [\"code\", \"result\"];\n };\n execute: (args: {\n code: string;\n }) => Promise<{ code: string; result: unknown; logs?: string[] }>;\n}\n\nexport interface CreateBrowserCodeToolOptions {\n /**\n * Tools available inside the sandbox via `codemode.*`.\n *\n * Accepts either an array (like `listTools()` returns) with `name` on each item,\n * or an object keyed by tool name (like `createCodeTool` expects).\n */\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors;\n /**\n * Executor to use. Defaults to a new `IframeSandboxExecutor`.\n */\n executor?: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for generated type definitions.\n */\n description?: string;\n}\n\n// -- Implementation --\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\nfunction toRecord(\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors\n): ApprovalAwareJsonSchemaExecutableToolDescriptors {\n if (!Array.isArray(tools)) return tools;\n\n const record: ApprovalAwareJsonSchemaExecutableToolDescriptors = {};\n for (const tool of tools) {\n if (!tool.name) {\n throw new Error(\n \"Tool descriptors in array form must have a `name` property\"\n );\n }\n record[tool.name] = tool;\n }\n return record;\n}\n\nfunction hasNeedsApproval(tool: Record<string, unknown>): boolean {\n return (\n tool.needsApproval === true || typeof tool.needsApproval === \"function\"\n );\n}\n\n/**\n * Create a codemode tool descriptor using only JSON Schema and browser APIs.\n *\n * This is the browser counterpart to `createCodeTool` from\n * `@cloudflare/codemode/ai`.\n * It returns a plain object with `{ name, description, inputSchema, outputSchema, execute }`\n * that can be passed to any framework — including\n * `navigator.modelContext.registerTool()`.\n *\n * Tools with `needsApproval` are excluded, matching the current codemode\n * behavior for approval-gated tools. JSON Schema is used for prompt/type\n * generation only and is not enforced at runtime.\n */\nexport function createBrowserCodeTool(\n options: CreateBrowserCodeToolOptions\n): BrowserCodeToolDescriptor {\n const allTools = toRecord(options.tools);\n const toolMap: JsonSchemaExecutableToolDescriptors = {};\n for (const [name, tool] of Object.entries(allTools)) {\n if (!hasNeedsApproval(tool as unknown as Record<string, unknown>)) {\n toolMap[name] = tool;\n }\n }\n const executor = options.executor ?? new IframeSandboxExecutor();\n\n // Generate TypeScript type descriptions for the LLM prompt\n const schemaOnly: JsonSchemaToolDescriptors = {};\n for (const [name, tool] of Object.entries(toolMap)) {\n schemaOnly[name] = {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema\n };\n }\n const types = generateTypesFromJsonSchema(schemaOnly);\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n // Extract execute functions, keyed by sanitized name\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, tool] of Object.entries(toolMap)) {\n if (tool.execute) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n throw new Error(\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to \"${sanitizedName}\"`\n );\n }\n sanitizedNames.set(sanitizedName, name);\n fns[sanitizedName] = tool.execute as (args: unknown) => Promise<unknown>;\n }\n }\n const resolvedProviders: ResolvedProvider[] = [{ name: \"codemode\", fns }];\n\n return {\n name: \"codemode\",\n description,\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"JavaScript async arrow function to execute\"\n }\n },\n required: [\"code\"]\n },\n outputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"The original code that was executed\"\n },\n result: {\n description: \"The return value of the executed code\"\n },\n logs: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Console output captured during execution\"\n }\n },\n required: [\"code\", \"result\"]\n },\n execute: async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\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: { code: string; result: unknown; logs?: string[] } = {\n code,\n result: executeResult.result\n };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n };\n}\n"],"mappings":";;AAYA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;;AAiDhD,SAAgB,sBACd,MAC6B;CAC7B,OAAO,SAAS,KAAK,IAAI,KAAK,SAAS;;AAGzC,SAAgB,kBAAkB,MAAwC;CACxE,OACE,SAAS,KAAK,IACd,KAAK,SAAS,eACd,OAAO,KAAK,UAAU,YACtB,OAAO,KAAK,OAAO,YACnB,OAAO,KAAK,aAAa,YACzB,OAAO,KAAK,SAAS;;AAIzB,SAAgB,yBACd,MACgC;CAChC,IAAI,CAAC,SAAS,KAAK,EAAE,OAAO;CAC5B,IAAI,KAAK,SAAS,oBAAoB,OAAO;CAC7C,IAA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K,KACrD;IACJ,MAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAA6D;IACjE;IACA,QAAQ,cAAc;IACvB;GACD,IAAI,cAAc,MAAM,OAAO,OAAO,cAAc;GACpD,OAAO;;EAEV"}
1
+ {"version":3,"file":"browser.js","names":["#timeout","#csp"],"sources":["../src/messages.ts","../src/iframe-runtime.ts","../src/iframe-executor.ts","../src/browser-tool.ts"],"sourcesContent":["/**\n * Typed postMessage protocol for host ↔ iframe sandbox communication.\n *\n * Messages flow in two directions:\n * - Sandbox → Host: tool calls and execution results\n * - Host → Sandbox: tool results and execute requests\n */\n\nimport type { ExecuteResult } from \"./executor-types\";\n\n// -- Helpers --\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n// -- Sandbox → Host messages --\n\nexport interface ToolCallMessage {\n type: \"tool-call\";\n nonce: string;\n id: number;\n provider: string;\n name: string;\n args: unknown;\n}\n\nexport interface ExecutionResultMessage {\n type: \"execution-result\";\n nonce: string;\n result: ExecuteResult;\n}\n\nexport interface SandboxReadyMessage {\n type: \"sandbox-ready\";\n}\n\n// -- Host → Sandbox messages --\n\nexport interface ToolResultSuccessMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result: unknown;\n}\n\nexport interface ToolResultErrorMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n error: string;\n}\n\nexport interface ExecuteRequestMessage {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string; positionalArgs?: boolean }[];\n}\n\n// -- Type guards --\n\nexport function isSandboxReadyMessage(\n data: unknown\n): data is SandboxReadyMessage {\n return isRecord(data) && data.type === \"sandbox-ready\";\n}\n\nexport function isToolCallMessage(data: unknown): data is ToolCallMessage {\n return (\n isRecord(data) &&\n data.type === \"tool-call\" &&\n typeof data.nonce === \"string\" &&\n typeof data.id === \"number\" &&\n typeof data.provider === \"string\" &&\n typeof data.name === \"string\"\n );\n}\n\nexport function isExecutionResultMessage(\n data: unknown\n): data is ExecutionResultMessage {\n if (!isRecord(data)) return false;\n if (data.type !== \"execution-result\") return false;\n if (typeof data.nonce !== \"string\") return false;\n if (typeof data.result !== \"object\" || data.result === null) return false;\n return true;\n}\n\nexport function isExecuteRequestMessageShape(\n data: unknown\n): data is ExecuteRequestMessage {\n return (\n isRecord(data) &&\n data.type === \"execute-request\" &&\n typeof data.nonce === \"string\" &&\n typeof data.code === \"string\" &&\n Array.isArray(data.providers) &&\n data.providers.every(\n (provider) =>\n isRecord(provider) &&\n typeof provider.name === \"string\" &&\n (provider.positionalArgs === undefined ||\n typeof provider.positionalArgs === \"boolean\")\n )\n );\n}\n","/**\n * Self-contained runtime that boots inside the sandboxed iframe.\n *\n * The `iframeSandboxRuntimeMain` function is serialized via `.toString()`\n * and injected into the iframe's `srcdoc`. It MUST be fully self-contained —\n * no closures over module-level variables, no imported values at runtime.\n * (Type-only imports are safe because they are erased at compile time.)\n */\n\n/**\n * The iframe-side runtime entry point.\n *\n * This function is stringified and injected into the iframe via srcdoc.\n * Everything it needs must be defined inside its own scope.\n */\nfunction iframeSandboxRuntimeMain(): void {\n const runtimeWindow = window as Window &\n typeof globalThis & { __codemodeIframeInitialized?: boolean };\n\n if (runtimeWindow.__codemodeIframeInitialized) {\n return;\n }\n\n runtimeWindow.__codemodeIframeInitialized = true;\n\n const logs: string[] = [];\n const pending: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n > = {};\n let nextId = 0;\n let activeNonce: string | undefined;\n\n function post(message: unknown) {\n parent.postMessage(message, \"*\");\n }\n\n // Capture console output\n console.log = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(values.join(\" \"));\n };\n console.warn = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[warn] \" + values.join(\" \"));\n };\n console.error = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[error] \" + values.join(\" \"));\n };\n\n function createProviderProxy(\n nonce: string,\n provider: {\n name: string;\n positionalArgs?: boolean;\n }\n ) {\n return new Proxy(\n {},\n {\n get: (_, toolName) => {\n if (provider.positionalArgs) {\n return (...args: unknown[]) => {\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending[id] = { resolve, reject };\n post({\n type: \"tool-call\",\n nonce,\n id,\n provider: provider.name,\n name: String(toolName),\n args\n });\n });\n };\n }\n\n return (args: unknown) => {\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending[id] = { resolve, reject };\n post({\n type: \"tool-call\",\n nonce,\n id,\n provider: provider.name,\n name: String(toolName),\n args: args ?? {}\n });\n });\n };\n }\n }\n );\n }\n\n function isToolResultMessage(message: unknown): message is {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result?: unknown;\n error?: string;\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"tool-result\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.id === \"number\"\n );\n }\n\n function isExecuteRequestMessage(message: unknown): message is {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string; positionalArgs?: boolean }[];\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"execute-request\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.code === \"string\" &&\n Array.isArray(candidate.providers) &&\n candidate.providers.every(\n (provider) =>\n typeof provider === \"object\" &&\n provider !== null &&\n typeof (provider as { name?: unknown }).name === \"string\" &&\n ((provider as { positionalArgs?: unknown }).positionalArgs ===\n undefined ||\n typeof (provider as { positionalArgs?: unknown }).positionalArgs ===\n \"boolean\")\n )\n );\n }\n\n function executeCode(\n nonce: string,\n code: string,\n providers: { name: string; positionalArgs?: boolean }[]\n ) {\n try {\n activeNonce = nonce;\n const providerNames: string[] = [];\n const providerProxies: unknown[] = [];\n for (const provider of providers) {\n providerNames.push(provider.name);\n providerProxies.push(createProviderProxy(nonce, provider));\n }\n\n const fn = new Function(...providerNames, \"return (\" + code + \")\")(\n ...providerProxies\n );\n Promise.resolve(fn())\n .then((result: unknown) => {\n post({ type: \"execution-result\", nonce, result: { result, logs } });\n })\n .catch((err: Error) => {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err.message || String(err),\n logs\n }\n });\n });\n } catch (err) {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err instanceof Error ? err.message : String(err),\n logs\n }\n });\n }\n }\n\n window.addEventListener(\"message\", (event) => {\n if (event.source !== parent) return;\n\n const message = event.data;\n\n if (isToolResultMessage(message)) {\n if (message.nonce !== activeNonce) return;\n const request = pending[message.id];\n if (!request) return;\n\n delete pending[message.id];\n if (\"error\" in message)\n request.reject(new Error(message.error as string));\n else request.resolve(message.result);\n return;\n }\n\n if (isExecuteRequestMessage(message)) {\n executeCode(message.nonce, message.code, message.providers);\n }\n });\n\n post({ type: \"sandbox-ready\" });\n}\n\n/**\n * Returns a self-contained script string that boots the codemode iframe runtime.\n */\nexport function createIframeSandboxRuntimeScript(): string {\n return `;(${iframeSandboxRuntimeMain.toString()})();`;\n}\n","/**\n * IframeSandboxExecutor — a browser-native Executor that runs LLM-generated\n * code in a sandboxed iframe using postMessage for tool dispatch.\n *\n * Zero dependencies — uses only browser APIs (iframe, postMessage, CSP).\n */\n\nimport {\n type ExecuteRequestMessage,\n isExecutionResultMessage,\n isSandboxReadyMessage,\n isToolCallMessage,\n type ToolResultErrorMessage,\n type ToolResultSuccessMessage\n} from \"./messages\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { createIframeSandboxRuntimeScript } from \"./iframe-runtime\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\n\nexport interface IframeSandboxExecutorOptions {\n /** Maximum execution time in milliseconds. Defaults to `30000`. */\n timeout?: number;\n /**\n * Content Security Policy applied to the iframe document.\n *\n * When omitted, defaults to a restrictive policy that only allows\n * inline scripts and eval (needed for code execution).\n */\n csp?: string;\n}\n\nconst DEFAULT_CSP =\n \"default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval';\";\nconst DEFAULT_TIMEOUT = 30000;\n\nfunction escapeHtmlAttribute(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n}\n\nfunction escapeInlineScript(value: string): string {\n return value.replace(/<\\/script/gi, \"<\\\\/script\");\n}\n\nfunction buildSrcdoc(csp: string): string {\n const runtimeScript = escapeInlineScript(createIframeSandboxRuntimeScript());\n const safeCsp = escapeHtmlAttribute(csp);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content=\"${safeCsp}\">\n</head>\n<body>\n<script>\n${runtimeScript}\n</script>\n</body>\n</html>`;\n}\n\nfunction createToolResultMessage(\n nonce: string,\n id: number,\n value: unknown,\n isError: boolean\n): ToolResultSuccessMessage | ToolResultErrorMessage {\n if (isError) {\n return {\n type: \"tool-result\",\n nonce,\n id,\n error: value instanceof Error ? value.message : String(value)\n };\n }\n return { type: \"tool-result\", nonce, id, result: value };\n}\n\nfunction createExecutionNonce(): string {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\"\n );\n}\n\n/**\n * Executes LLM-generated code in a browser iframe sandbox.\n *\n * For each execution, a hidden iframe is created with `sandbox=\"allow-scripts\"`,\n * the runtime is injected via `srcdoc`, and the iframe is removed after completion.\n * Tool calls are dispatched via `postMessage`.\n */\nexport class IframeSandboxExecutor implements Executor {\n #timeout: number;\n #csp: string;\n\n constructor(options?: IframeSandboxExecutorOptions) {\n this.#timeout = options?.timeout ?? DEFAULT_TIMEOUT;\n this.#csp = options?.csp ?? DEFAULT_CSP;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const reservedNames = new Set([\"__dispatchers\", \"__logs\"]);\n const validIdent = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (reservedNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!validIdent.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n const normalizedCode = normalizeCode(code);\n const resolvedProviders: ResolvedProvider[] = [];\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n const resolved: ResolvedProvider = {\n name: provider.name,\n fns: sanitizedFns\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n const providerMap = new Map(\n resolvedProviders.map((provider) => [provider.name, provider] as const)\n );\n const nonce = createExecutionNonce();\n\n const executeRequest: ExecuteRequestMessage = {\n type: \"execute-request\",\n nonce,\n code: normalizedCode,\n providers: resolvedProviders.map((provider) => {\n if (provider.positionalArgs) {\n return { name: provider.name, positionalArgs: true };\n }\n return { name: provider.name };\n })\n };\n\n const invokeProviderTool = async (\n provider: ResolvedProvider,\n args: unknown,\n name: string\n ) => {\n const fn = provider.fns[name];\n if (!fn) {\n throw new Error(`Tool \"${name}\" not found`);\n }\n if (!provider.positionalArgs) {\n return fn(args);\n }\n const positionalArgs = Array.isArray(args) ? args : [args];\n return fn(...positionalArgs);\n };\n\n const iframe = document.createElement(\"iframe\");\n iframe.sandbox.add(\"allow-scripts\");\n iframe.style.display = \"none\";\n iframe.style.width = \"0\";\n iframe.style.height = \"0\";\n iframe.style.border = \"none\";\n iframe.srcdoc = buildSrcdoc(this.#csp);\n\n return new Promise<ExecuteResult>((resolve) => {\n let settled = false;\n let ready = false;\n const warnedInvalidNonceTypes = new Set<string>();\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n window.removeEventListener(\"message\", handler);\n iframe.removeEventListener(\"error\", handleLoadError);\n iframe.remove();\n };\n\n const resolveError = (message: string) => {\n cleanup();\n resolve({ result: undefined, error: message, logs: [] });\n };\n\n const postToChild = (\n message:\n | ToolResultSuccessMessage\n | ToolResultErrorMessage\n | ExecuteRequestMessage\n ): boolean => {\n const child = iframe.contentWindow;\n if (!child) {\n resolveError(\"Sandbox iframe is not available\");\n return false;\n }\n\n try {\n child.postMessage(message, \"*\");\n return true;\n } catch (err) {\n resolveError(err instanceof Error ? err.message : String(err));\n return false;\n }\n };\n\n const warnInvalidNonce = (messageType: string) => {\n if (warnedInvalidNonceTypes.has(messageType)) return;\n warnedInvalidNonceTypes.add(messageType);\n console.warn(\n `[@cloudflare/codemode] Ignoring sandbox ${messageType} message with invalid execution nonce`\n );\n };\n\n const handler = async (event: MessageEvent) => {\n if (event.source !== iframe.contentWindow) return;\n\n const data: unknown = event.data;\n\n if (isSandboxReadyMessage(data)) {\n if (ready) return;\n ready = true;\n postToChild(executeRequest);\n return;\n }\n\n if (isToolCallMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"tool-call\");\n return;\n }\n const provider = providerMap.get(data.provider);\n if (!provider) {\n postToChild(\n createToolResultMessage(\n nonce,\n data.id,\n `Provider \"${data.provider}\" not found`,\n true\n )\n );\n return;\n }\n try {\n const result = await invokeProviderTool(\n provider,\n data.args,\n data.name\n );\n postToChild(createToolResultMessage(nonce, data.id, result, false));\n } catch (err) {\n postToChild(createToolResultMessage(nonce, data.id, err, true));\n }\n return;\n }\n\n if (isExecutionResultMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"execution-result\");\n return;\n }\n cleanup();\n resolve(data.result);\n }\n };\n\n const handleLoadError = () => {\n resolveError(\"Sandbox iframe failed to load\");\n };\n\n window.addEventListener(\"message\", handler);\n iframe.addEventListener(\"error\", handleLoadError);\n\n const timer = setTimeout(() => {\n cleanup();\n resolve({ result: undefined, error: \"Execution timed out\", logs: [] });\n }, this.#timeout);\n\n document.body.appendChild(iframe);\n });\n }\n}\n","/**\n * Zero-dependency browser counterpart to `createCodeTool` from `./ai`.\n *\n * Returns a plain JSON Schema tool descriptor instead of an AI SDK `Tool`.\n * No `ai`, no `zod` — just JSON Schema and browser APIs. JSON Schema is used\n * for generated types only; this helper does not perform runtime validation.\n */\n\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptor,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { runCode } from \"./run-code\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor, ResolvedProvider } from \"./executor-types\";\nimport type { CodeInput, CodeOutput } from \"./shared\";\nimport { IframeSandboxExecutor } from \"./iframe-executor\";\n\n// -- Types --\n\n/**\n * A JSON Schema tool descriptor with an execute function attached.\n */\nexport interface JsonSchemaExecutableToolDescriptor extends JsonSchemaToolDescriptor {\n name?: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type JsonSchemaExecutableToolDescriptors = Record<\n string,\n JsonSchemaExecutableToolDescriptor\n>;\n\ninterface ApprovalAwareJsonSchemaExecutableToolDescriptor extends JsonSchemaExecutableToolDescriptor {\n needsApproval?: boolean | ((...args: unknown[]) => unknown);\n}\n\ntype ApprovalAwareJsonSchemaExecutableToolDescriptors = Record<\n string,\n ApprovalAwareJsonSchemaExecutableToolDescriptor\n>;\n\nexport interface BrowserCodeToolDescriptor {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: {\n code: { type: \"string\"; description: string };\n };\n required: [\"code\"];\n };\n outputSchema: {\n type: \"object\";\n properties: {\n result: { description: string };\n logs: {\n type: \"array\";\n items: { type: \"string\" };\n description: string;\n };\n };\n required: [\"result\"];\n };\n execute: (args: CodeInput) => Promise<CodeOutput>;\n}\n\nexport interface CreateBrowserCodeToolOptions {\n /**\n * Tools available inside the sandbox via `codemode.*`.\n *\n * Accepts either an array (like `listTools()` returns) with `name` on each item,\n * or an object keyed by tool name (like `createCodeTool` expects).\n */\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors;\n /**\n * Executor to use. Defaults to a new `IframeSandboxExecutor`.\n */\n executor?: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for generated type definitions.\n */\n description?: string;\n}\n\n// -- Implementation --\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\nfunction toRecord(\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors\n): ApprovalAwareJsonSchemaExecutableToolDescriptors {\n if (!Array.isArray(tools)) return tools;\n\n const record: ApprovalAwareJsonSchemaExecutableToolDescriptors = {};\n for (const tool of tools) {\n if (!tool.name) {\n throw new Error(\n \"Tool descriptors in array form must have a `name` property\"\n );\n }\n record[tool.name] = tool;\n }\n return record;\n}\n\nfunction hasNeedsApproval(tool: Record<string, unknown>): boolean {\n return (\n tool.needsApproval === true || typeof tool.needsApproval === \"function\"\n );\n}\n\n/**\n * Create a codemode tool descriptor using only JSON Schema and browser APIs.\n *\n * This is the browser counterpart to `createCodeTool` from\n * `@cloudflare/codemode/ai`.\n * It returns a plain object with `{ name, description, inputSchema, outputSchema, execute }`\n * that can be passed to any framework — including\n * `navigator.modelContext.registerTool()`.\n *\n * Tools with `needsApproval` are excluded, matching the current codemode\n * behavior for approval-gated tools. JSON Schema is used for prompt/type\n * generation only and is not enforced at runtime.\n */\nexport function createBrowserCodeTool(\n options: CreateBrowserCodeToolOptions\n): BrowserCodeToolDescriptor {\n const allTools = toRecord(options.tools);\n const toolMap: JsonSchemaExecutableToolDescriptors = {};\n for (const [name, tool] of Object.entries(allTools)) {\n if (!hasNeedsApproval(tool as unknown as Record<string, unknown>)) {\n toolMap[name] = tool;\n }\n }\n const executor = options.executor ?? new IframeSandboxExecutor();\n\n // Generate TypeScript type descriptions for the LLM prompt\n const schemaOnly: JsonSchemaToolDescriptors = {};\n for (const [name, tool] of Object.entries(toolMap)) {\n schemaOnly[name] = {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema\n };\n }\n const types = generateTypesFromJsonSchema(schemaOnly);\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n // Extract execute functions, keyed by sanitized name\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, tool] of Object.entries(toolMap)) {\n if (tool.execute) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n throw new Error(\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to \"${sanitizedName}\"`\n );\n }\n sanitizedNames.set(sanitizedName, name);\n fns[sanitizedName] = tool.execute as (args: unknown) => Promise<unknown>;\n }\n }\n const resolvedProviders: ResolvedProvider[] = [{ name: \"codemode\", fns }];\n\n return {\n name: \"codemode\",\n description,\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"JavaScript async arrow function to execute\"\n }\n },\n required: [\"code\"]\n },\n outputSchema: {\n type: \"object\",\n properties: {\n result: {\n description: \"The return value of the executed code\"\n },\n logs: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Console output captured during execution\"\n }\n },\n required: [\"result\"]\n },\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n };\n}\n"],"mappings":";;;AAYA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;;AAiDhD,SAAgB,sBACd,MAC6B;CAC7B,OAAO,SAAS,KAAK,IAAI,KAAK,SAAS;;AAGzC,SAAgB,kBAAkB,MAAwC;CACxE,OACE,SAAS,KAAK,IACd,KAAK,SAAS,eACd,OAAO,KAAK,UAAU,YACtB,OAAO,KAAK,OAAO,YACnB,OAAO,KAAK,aAAa,YACzB,OAAO,KAAK,SAAS;;AAIzB,SAAgB,yBACd,MACgC;CAChC,IAAI,CAAC,SAAS,KAAK,EAAE,OAAO;CAC5B,IAAI,KAAK,SAAS,oBAAoB,OAAO;CAC7C,IAAI,OAAO,KAAK,UAAU,UAAU,OAAO;CAC3C,IAAI,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW,MAAM,OAAO;CACpE,OAAO;;;;;;;;;;;;;;;;;;ACvET,SAAS,2BAAiC;CACxC,MAAM,gBAAgB;CAGtB,IAAI,cAAc,6BAChB;CAGF,cAAc,8BAA8B;CAE5C,MAAM,OAAiB,EAAE;CACzB,MAAM,UAGF,EAAE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MAAM,MAAgE,EAAE;CACxE,MAAM,iCAAiB,IAAI,KAAqB;CAChD,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,QAAQ,EAChD,IAAI,KAAK,SAAS;EAChB,MAAM,gBAAgB,iBAAiB,KAAK;EAC5C,MAAM,eAAe,eAAe,IAAI,cAAc;EACtD,IAAI,gBAAgB,iBAAiB,MACnC,MAAM,IAAI,MACR,eAAe,aAAa,SAAS,KAAK,sBAAsB,cAAc,GAC/E;EAEH,eAAe,IAAI,eAAe,KAAK;EACvC,IAAI,iBAAiB,KAAK;;CAG9B,MAAM,oBAAwC,CAAC;EAAE,MAAM;EAAY;EAAK,CAAC;CAEzE,OAAO;EACL,MAAM;EACN;EACA,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACd,EACF;GACD,UAAU,CAAC,OAAO;GACnB;EACD,cAAc;GACZ,MAAM;GACN,YAAY;IACV,QAAQ,EACN,aAAa,yCACd;IACD,MAAM;KACJ,MAAM;KACN,OAAO,EAAE,MAAM,UAAU;KACzB,aAAa;KACd;IACF;GACD,UAAU,CAAC,SAAS;GACrB;EACD,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;GAAmB,CAAC;EAC5D"}
@@ -1,8 +1,3 @@
1
- import {
2
- n as Executor,
3
- r as ResolvedProvider,
4
- t as ExecuteResult
5
- } from "./executor-types-CJ06IBzw.js";
6
1
  import { RpcTarget } from "cloudflare:workers";
7
2
  import { ToolSet } from "ai";
8
3
  import { ZodType } from "zod";
@@ -27,6 +22,40 @@ declare function generateTypes(
27
22
  namespace?: string
28
23
  ): string;
29
24
  //#endregion
25
+ //#region src/executor-types.d.ts
26
+ /**
27
+ * Shared executor contract used by all codemode runtimes.
28
+ */
29
+ interface ExecuteResult {
30
+ result: unknown;
31
+ error?: string;
32
+ logs?: string[];
33
+ }
34
+ /**
35
+ * Internal resolved form of a tool provider, ready for execution.
36
+ * The tool functions are keyed by tool name and exposed under `name.*`
37
+ * inside the sandbox.
38
+ */
39
+ interface ResolvedProvider {
40
+ name: string;
41
+ fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
42
+ positionalArgs?: boolean;
43
+ }
44
+ /**
45
+ * An executor runs LLM-generated code in a sandbox, making the provided
46
+ * tool functions callable under their namespace inside the sandbox.
47
+ *
48
+ * Implementations should never throw — errors are returned in `ExecuteResult.error`.
49
+ */
50
+ interface Executor {
51
+ execute(
52
+ code: string,
53
+ providersOrFns:
54
+ | ResolvedProvider[]
55
+ | Record<string, (...args: unknown[]) => Promise<unknown>>
56
+ ): Promise<ExecuteResult>;
57
+ }
58
+ //#endregion
30
59
  //#region src/executor.d.ts
31
60
  /**
32
61
  * A minimal tool record — just a description and an execute function.
@@ -144,12 +173,15 @@ declare class DynamicWorkerExecutor implements Executor {
144
173
  //#endregion
145
174
  export {
146
175
  ToolProviderTools as a,
147
- generateTypes as c,
176
+ ResolvedProvider as c,
177
+ generateTypes as d,
148
178
  ToolProvider as i,
179
+ ToolDescriptor as l,
149
180
  DynamicWorkerExecutorOptions as n,
150
- ToolDescriptor as o,
181
+ ExecuteResult as o,
151
182
  ToolDispatcher as r,
152
- ToolDescriptors as s,
153
- DynamicWorkerExecutor as t
183
+ Executor as s,
184
+ DynamicWorkerExecutor as t,
185
+ ToolDescriptors as u
154
186
  };
155
- //# sourceMappingURL=executor-C-DgAHLS.d.ts.map
187
+ //# sourceMappingURL=executor-BWtTiHBV.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,21 +1,19 @@
1
1
  import {
2
+ c as ResolvedProvider,
2
3
  i as ToolProvider,
3
4
  n as DynamicWorkerExecutorOptions,
5
+ o as ExecuteResult,
4
6
  r as ToolDispatcher,
7
+ s as Executor,
5
8
  t as DynamicWorkerExecutor
6
- } from "./executor-C-DgAHLS.js";
7
- import {
8
- n as Executor,
9
- r as ResolvedProvider,
10
- t as ExecuteResult
11
- } from "./executor-types-CJ06IBzw.js";
9
+ } from "./executor-BWtTiHBV.js";
12
10
  import {
13
11
  i as jsonSchemaToType,
14
12
  n as JsonSchemaToolDescriptors,
15
13
  r as generateTypesFromJsonSchema,
16
14
  t as JsonSchemaToolDescriptor
17
15
  } from "./json-schema-types-1OL3uao0.js";
18
- import { t as resolveProvider } from "./resolve-E1SKV37h.js";
16
+ import { t as resolveProvider } from "./resolve-9VUW-grI.js";
19
17
 
20
18
  //#region src/utils.d.ts
21
19
  /**
package/dist/index.js CHANGED
@@ -8,6 +8,94 @@ import { RpcTarget } from "cloudflare:workers";
8
8
  * The Executor interface is the core abstraction — implement it to run
9
9
  * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).
10
10
  */
11
+ const BINARY_TAG = "__codemode_binary_v1__";
12
+ function bytesToBase64(bytes) {
13
+ let binary = "";
14
+ const chunkSize = 32768;
15
+ for (let i = 0; i < bytes.byteLength; i += chunkSize) binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));
16
+ return btoa(binary);
17
+ }
18
+ function base64ToBytes(b64) {
19
+ const binary = atob(b64);
20
+ const bytes = new Uint8Array(binary.length);
21
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
22
+ return bytes;
23
+ }
24
+ function encodeCodemodeValue(value) {
25
+ if (value instanceof Uint8Array) return {
26
+ [BINARY_TAG]: "Uint8Array",
27
+ data: bytesToBase64(value)
28
+ };
29
+ if (value instanceof ArrayBuffer) return {
30
+ [BINARY_TAG]: "ArrayBuffer",
31
+ data: bytesToBase64(new Uint8Array(value))
32
+ };
33
+ if (ArrayBuffer.isView(value)) {
34
+ const view = value;
35
+ return {
36
+ [BINARY_TAG]: "ArrayBufferView",
37
+ data: bytesToBase64(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))
38
+ };
39
+ }
40
+ return value;
41
+ }
42
+ function decodeCodemodeValue(value) {
43
+ if (!value || typeof value !== "object" || !(BINARY_TAG in value)) return value;
44
+ const encoded = value;
45
+ if (typeof encoded.data !== "string") return value;
46
+ const bytes = base64ToBytes(encoded.data);
47
+ if (encoded[BINARY_TAG] === "ArrayBuffer") return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
48
+ return bytes;
49
+ }
50
+ function stringifyForCodemode(value) {
51
+ return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));
52
+ }
53
+ function parseForCodemode(json) {
54
+ return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));
55
+ }
56
+ const SANDBOX_CODEC = String.raw`
57
+ const __CODEMODE_BINARY_TAG = "__codemode_binary_v1__";
58
+ function __bytesToBase64(bytes) {
59
+ let binary = "";
60
+ const chunkSize = 0x8000;
61
+ for (let i = 0; i < bytes.byteLength; i += chunkSize) {
62
+ binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));
63
+ }
64
+ return btoa(binary);
65
+ }
66
+ function __base64ToBytes(b64) {
67
+ const binary = atob(b64);
68
+ const bytes = new Uint8Array(binary.length);
69
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
70
+ return bytes;
71
+ }
72
+ function __encodeCodemodeValue(value) {
73
+ if (value instanceof Uint8Array) {
74
+ return { [__CODEMODE_BINARY_TAG]: "Uint8Array", data: __bytesToBase64(value) };
75
+ }
76
+ if (value instanceof ArrayBuffer) {
77
+ return { [__CODEMODE_BINARY_TAG]: "ArrayBuffer", data: __bytesToBase64(new Uint8Array(value)) };
78
+ }
79
+ if (ArrayBuffer.isView(value)) {
80
+ return { [__CODEMODE_BINARY_TAG]: "ArrayBufferView", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };
81
+ }
82
+ return value;
83
+ }
84
+ function __decodeCodemodeValue(value) {
85
+ if (!value || typeof value !== "object" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== "string") return value;
86
+ const bytes = __base64ToBytes(value.data);
87
+ if (value[__CODEMODE_BINARY_TAG] === "ArrayBuffer") {
88
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
89
+ }
90
+ return bytes;
91
+ }
92
+ function __stringifyForCodemode(value) {
93
+ return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));
94
+ }
95
+ function __parseForCodemode(json) {
96
+ return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));
97
+ }
98
+ `;
11
99
  /**
12
100
  * An RpcTarget that dispatches tool calls from the sandboxed Worker
13
101
  * back to the host. Passed via Workers RPC to the dynamic Worker's
@@ -23,17 +111,15 @@ var ToolDispatcher = class extends RpcTarget {
23
111
  }
24
112
  async call(name, argsJson) {
25
113
  const fn = this.#fns[name];
26
- if (!fn) return JSON.stringify({ error: `Tool "${name}" not found` });
114
+ if (!fn) return stringifyForCodemode({ error: `Tool "${name}" not found` });
27
115
  try {
28
116
  if (this.#positionalArgs) {
29
- const args = argsJson ? JSON.parse(argsJson) : [];
30
- const result = await fn(...Array.isArray(args) ? args : [args]);
31
- return JSON.stringify({ result });
117
+ const args = argsJson ? parseForCodemode(argsJson) : [];
118
+ return stringifyForCodemode({ result: await fn(...Array.isArray(args) ? args : [args]) });
32
119
  }
33
- const result = await fn(argsJson ? JSON.parse(argsJson) : {});
34
- return JSON.stringify({ result });
120
+ return stringifyForCodemode({ result: await fn(argsJson ? parseForCodemode(argsJson) : {}) });
35
121
  } catch (err) {
36
- return JSON.stringify({ error: err instanceof Error ? err.message : String(err) });
122
+ return stringifyForCodemode({ error: err instanceof Error ? err.message : String(err) });
37
123
  }
38
124
  }
39
125
  };
@@ -78,7 +164,17 @@ var DynamicWorkerExecutor = class {
78
164
  } else providers = providersOrFns;
79
165
  const normalized = normalizeCode(code);
80
166
  const timeoutMs = this.#timeout;
81
- const RESERVED_NAMES = new Set(["__dispatchers", "__logs"]);
167
+ const RESERVED_NAMES = new Set([
168
+ "__dispatchers",
169
+ "__logs",
170
+ "__CODEMODE_BINARY_TAG",
171
+ "__bytesToBase64",
172
+ "__base64ToBytes",
173
+ "__encodeCodemodeValue",
174
+ "__decodeCodemodeValue",
175
+ "__stringifyForCodemode",
176
+ "__parseForCodemode"
177
+ ]);
82
178
  const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
83
179
  const seenNames = /* @__PURE__ */ new Set();
84
180
  for (const provider of providers) {
@@ -105,9 +201,10 @@ var DynamicWorkerExecutor = class {
105
201
  " console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };",
106
202
  " console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };",
107
203
  " console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };",
204
+ SANDBOX_CODEC,
108
205
  ...providers.map((p) => {
109
- if (p.positionalArgs) return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (...args) => {\n const resJson = await __dispatchers.${p.name}.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 });`;
110
- return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (args) => {\n const resJson = await __dispatchers.${p.name}.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 });`;
206
+ if (p.positionalArgs) return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (...args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`;
207
+ return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args ?? {}));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`;
111
208
  }),
112
209
  "",
113
210
  " try {",
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#fns","#positionalArgs","#loader","#timeout","#globalOutbound","#modules"],"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\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\nexport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n\n /**\n * When true, tools accept positional args instead of a single object arg.\n * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.\n *\n * Default tools use single-object args: `codemode.search({ query: \"test\" })`\n * Positional tools use normal args: `state.readFile(\"/path\")`\n */\n positionalArgs?: boolean;\n}\n\n// ── ToolDispatcher ────────────────────────────────────────────────────\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 #positionalArgs: boolean;\n\n constructor(\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>,\n positionalArgs = false\n ) {\n super();\n this.#fns = fns;\n this.#positionalArgs = positionalArgs;\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 if (this.#positionalArgs) {\n const args = argsJson ? JSON.parse(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return JSON.stringify({ result });\n }\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 ─────────────────────────────────────────────\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 * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes\n * ToolDispatchers (one per namespace) 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 *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n #modules: Record<string, string>;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n const { \"executor.js\": _, ...safeModules } = options.modules ?? {};\n this.#modules = safeModules;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\"__dispatchers\", \"__logs\"]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map((p) => {\n if (p.positionalArgs) {\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), JSON.stringify(args));\\n` +\n ` const data = JSON.parse(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n }\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), JSON.stringify(args ?? {}));\\n` +\n ` const data = JSON.parse(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n });\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\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 ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\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 ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\n // Sanitize fn keys so raw tool names (e.g. \"github.list-issues\") become\n // valid JS identifiers (e.g. \"github_list_issues\") on the proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(\n sanitizedFns,\n provider.positionalArgs\n );\n }\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 ...this.#modules,\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\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":";;;;;;;;;;;;;;;AAsFA,IAAa,iBAAb,cAAoC,UAAU;CAC5C;CACA;CAEA,YACE,KACA,iBAAiB,OACjB;EACA,OAAO;EACP,KAAKA,OAAO;EACZ,KAAKC,kBAAkB;;CAGzB,MAAM,KAAK,MAAc,UAAmC;EAC1D,MAAM,KAAK,KAAKD,KAAK;EACrB,IAAI,CAAC,IACH,OAAO,KAAK,UAAU,EAAE,OAAO,SAAS,KAA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AKG;IACR,eAAe;IAChB;GACD,gBAAgB,KAAKD;GACtB,EAEwB,CAAC,eAOO,CAAC,SAAS,YAAY;EAEvD,IAAI,SAAS,OACX,OAAO;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;EAG1E,OAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
1
+ {"version":3,"file":"index.js","names":["#fns","#positionalArgs","#loader","#timeout","#globalOutbound","#modules"],"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\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\nexport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\n\nconst BINARY_TAG = \"__codemode_binary_v1__\";\n\ntype EncodedBinary = {\n [BINARY_TAG]: \"Uint8Array\" | \"ArrayBuffer\" | \"ArrayBufferView\";\n data: string;\n};\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength))\n );\n }\n return btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nfunction encodeCodemodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { [BINARY_TAG]: \"Uint8Array\", data: bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return {\n [BINARY_TAG]: \"ArrayBuffer\",\n data: bytesToBase64(new Uint8Array(value))\n };\n }\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return {\n [BINARY_TAG]: \"ArrayBufferView\",\n data: bytesToBase64(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n )\n };\n }\n return value;\n}\n\nfunction decodeCodemodeValue(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || !(BINARY_TAG in value)) {\n return value;\n }\n const encoded = value as EncodedBinary;\n if (typeof encoded.data !== \"string\") return value;\n const bytes = base64ToBytes(encoded.data);\n if (encoded[BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength\n );\n }\n return bytes;\n}\n\nfunction stringifyForCodemode(value: unknown): string {\n return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));\n}\n\nfunction parseForCodemode(json: string): unknown {\n return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));\n}\n\nconst SANDBOX_CODEC = String.raw`\n const __CODEMODE_BINARY_TAG = \"__codemode_binary_v1__\";\n function __bytesToBase64(bytes) {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));\n }\n return btoa(binary);\n }\n function __base64ToBytes(b64) {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n function __encodeCodemodeValue(value) {\n if (value instanceof Uint8Array) {\n return { [__CODEMODE_BINARY_TAG]: \"Uint8Array\", data: __bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBuffer\", data: __bytesToBase64(new Uint8Array(value)) };\n }\n if (ArrayBuffer.isView(value)) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBufferView\", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };\n }\n return value;\n }\n function __decodeCodemodeValue(value) {\n if (!value || typeof value !== \"object\" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== \"string\") return value;\n const bytes = __base64ToBytes(value.data);\n if (value[__CODEMODE_BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n return bytes;\n }\n function __stringifyForCodemode(value) {\n return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));\n }\n function __parseForCodemode(json) {\n return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));\n }\n`;\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n\n /**\n * When true, tools accept positional args instead of a single object arg.\n * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.\n *\n * Default tools use single-object args: `codemode.search({ query: \"test\" })`\n * Positional tools use normal args: `state.readFile(\"/path\")`\n */\n positionalArgs?: boolean;\n}\n\n// ── ToolDispatcher ────────────────────────────────────────────────────\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 #positionalArgs: boolean;\n\n constructor(\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>,\n positionalArgs = false\n ) {\n super();\n this.#fns = fns;\n this.#positionalArgs = positionalArgs;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return stringifyForCodemode({ error: `Tool \"${name}\" not found` });\n }\n try {\n if (this.#positionalArgs) {\n const args = argsJson ? parseForCodemode(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return stringifyForCodemode({ result });\n }\n const args = argsJson ? parseForCodemode(argsJson) : {};\n const result = await fn(args);\n return stringifyForCodemode({ result });\n } catch (err) {\n return stringifyForCodemode({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// ── DynamicWorkerExecutor ─────────────────────────────────────────────\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 * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes\n * ToolDispatchers (one per namespace) 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 *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n #modules: Record<string, string>;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n const { \"executor.js\": _, ...safeModules } = options.modules ?? {};\n this.#modules = safeModules;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\n \"__dispatchers\",\n \"__logs\",\n \"__CODEMODE_BINARY_TAG\",\n \"__bytesToBase64\",\n \"__base64ToBytes\",\n \"__encodeCodemodeValue\",\n \"__decodeCodemodeValue\",\n \"__stringifyForCodemode\",\n \"__parseForCodemode\"\n ]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map((p) => {\n if (p.positionalArgs) {\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n }\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args ?? {}));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n });\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\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 SANDBOX_CODEC,\n ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\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 ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\n // Sanitize fn keys so raw tool names (e.g. \"github.list-issues\") become\n // valid JS identifiers (e.g. \"github_list_issues\") on the proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(\n sanitizedFns,\n provider.positionalArgs\n );\n }\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 ...this.#modules,\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\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":";;;;;;;;;;AAuBA,MAAM,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AAc;IACtD,IAAI,gBAAgB,iBAAiB,MACnC,OAAO;KACL,QAAQ,KAAA;KACR,OACE,eAAe,aAAa,SAAS,KAAK,sBACtC,cAAc,iBAAiB,SAAS,KAAK;KACpD;IAEH,eAAe,IAAI,eAAe,KAAK;IACvC,aAAa,iBAAiB;;GAEhC,YAAY,SAAS,QAAQ,IAAI,eAC/B,cACA,SAAS,eACV;;EAqBH,MAAM,WAAW,MAlBF,KAAKD,QAAQ,IAAI,YAAY,OAAO,YAAY,WAAW;GACxE,mBAAmB;GACnB,oBAAoB,CAAC,gBAAgB;GACrC,YAAY;GACZ,SAAS;IACP,GAAG,KAAKG;IACR,eAAe;IAChB;GACD,gBAAgB,KAAKD;GACtB,EAEwB,CAAC,eAOO,CAAC,SAAS,YAAY;EAEvD,IAAI,SAAS,OACX,OAAO;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;EAG1E,OAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
package/dist/mcp.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as Executor } from "./executor-types-CJ06IBzw.js";
1
+ import { s as Executor } from "./executor-BWtTiHBV.js";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
 
4
4
  //#region src/mcp.d.ts
@@ -1,5 +1,7 @@
1
- import { i as ToolProvider } from "./executor-C-DgAHLS.js";
2
- import { r as ResolvedProvider } from "./executor-types-CJ06IBzw.js";
1
+ import {
2
+ c as ResolvedProvider,
3
+ i as ToolProvider
4
+ } from "./executor-BWtTiHBV.js";
3
5
 
4
6
  //#region src/resolve.d.ts
5
7
  /**
@@ -12,4 +14,4 @@ import { r as ResolvedProvider } from "./executor-types-CJ06IBzw.js";
12
14
  declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
13
15
  //#endregion
14
16
  export { resolveProvider as t };
15
- //# sourceMappingURL=resolve-E1SKV37h.d.ts.map
17
+ //# sourceMappingURL=resolve-9VUW-grI.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { s as normalizeCode } from "./json-schema-types-CVt4X9cw.js";
2
+ //#region src/run-code.ts
3
+ async function runCode({ code, executor, providers }) {
4
+ const executeResult = await executor.execute(normalizeCode(code), providers);
5
+ if (executeResult.error) {
6
+ const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
7
+ throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
8
+ }
9
+ return executeResult.logs?.length ? {
10
+ result: executeResult.result,
11
+ logs: executeResult.logs
12
+ } : { result: executeResult.result };
13
+ }
14
+ //#endregion
15
+ export { runCode as t };
16
+
17
+ //# sourceMappingURL=run-code-5x8S5YWt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-code-5x8S5YWt.js","names":[],"sources":["../src/run-code.ts"],"sourcesContent":["import type { CodeOutput } from \"./shared\";\nimport type { Executor, ResolvedProvider } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nexport async function runCode({\n code,\n executor,\n providers\n}: {\n code: string;\n executor: Executor;\n providers: ResolvedProvider[];\n}): Promise<CodeOutput> {\n const executeResult = await executor.execute(normalizeCode(code), providers);\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(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n return executeResult.logs?.length\n ? { result: executeResult.result, logs: executeResult.logs }\n : { result: executeResult.result };\n}\n"],"mappings":";;AAIA,eAAsB,QAAQ,EAC5B,MACA,UACA,aAKsB;CACtB,MAAM,gBAAgB,MAAM,SAAS,QAAQ,cAAc,KAAK,EAAE,UAAU;CAE5E,IAAI,cAAc,OAAO;EACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;EACJ,MAAM,IAAI,MAAM,0BAA0B,cAAc,QAAQ,SAAS;;CAG3E,OAAO,cAAc,MAAM,SACvB;EAAE,QAAQ,cAAc;EAAQ,MAAM,cAAc;EAAM,GAC1D,EAAE,QAAQ,cAAc,QAAQ"}
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  a as ToolProviderTools,
3
- i as ToolProvider
4
- } from "./executor-C-DgAHLS.js";
5
- import { n as Executor } from "./executor-types-CJ06IBzw.js";
3
+ i as ToolProvider,
4
+ s as Executor
5
+ } from "./executor-BWtTiHBV.js";
6
6
 
7
7
  //#region src/shared.d.ts
8
8
  declare const DEFAULT_DESCRIPTION =
@@ -19,7 +19,6 @@ type CodeInput = {
19
19
  code: string;
20
20
  };
21
21
  type CodeOutput = {
22
- code: string;
23
22
  result: unknown;
24
23
  logs?: string[];
25
24
  };
@@ -38,4 +37,4 @@ export {
38
37
  CreateCodeToolOptions as r,
39
38
  CodeInput as t
40
39
  };
41
- //# sourceMappingURL=shared-C3CDOc8T.d.ts.map
40
+ //# sourceMappingURL=shared-CcZcDoiO.d.ts.map
@@ -27,4 +27,4 @@ function normalizeProviders(tools) {
27
27
  //#endregion
28
28
  export { normalizeProviders as n, DEFAULT_DESCRIPTION as t };
29
29
 
30
- //# sourceMappingURL=shared-ra3HW2ti.js.map
30
+ //# sourceMappingURL=shared-xjl2irqK.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-ra3HW2ti.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const 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: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { code: string; result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;CACzB,OAAO,MAAM,QAAQ,MAAM;;;;;;AAO7B,SAAgB,mBACd,OACgB;CAChB,IAAI,oBAAoB,MAAM,EAC5B,OAAO;CAET,OAAO,CAAC,EAAE,OAAO,CAAC"}
1
+ {"version":3,"file":"shared-xjl2irqK.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const 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: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;CACzB,OAAO,MAAM,QAAQ,MAAM;;;;;;AAO7B,SAAgB,mBACd,OACgB;CAChB,IAAI,oBAAoB,MAAM,EAC5B,OAAO;CAET,OAAO,CAAC,EAAE,OAAO,CAAC"}
@@ -1,12 +1,12 @@
1
- import { i as ToolProvider } from "./executor-C-DgAHLS.js";
1
+ import { i as ToolProvider } from "./executor-BWtTiHBV.js";
2
2
  import {
3
3
  a as normalizeProviders,
4
4
  i as DEFAULT_DESCRIPTION,
5
5
  n as CodeOutput,
6
6
  r as CreateCodeToolOptions,
7
7
  t as CodeInput
8
- } from "./shared-C3CDOc8T.js";
9
- import { t as resolveProvider } from "./resolve-E1SKV37h.js";
8
+ } from "./shared-CcZcDoiO.js";
9
+ import { t as resolveProvider } from "./resolve-9VUW-grI.js";
10
10
  import { ServerTool, Tool } from "@tanstack/ai";
11
11
 
12
12
  //#region src/tanstack-ai.d.ts
@@ -1,6 +1,7 @@
1
- import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase, s as normalizeCode } from "./json-schema-types-CVt4X9cw.js";
1
+ import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase } from "./json-schema-types-CVt4X9cw.js";
2
2
  import { n as filterTools, r as resolveProvider, t as extractFns } from "./resolve-BU1FGVYs.js";
3
- import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-ra3HW2ti.js";
3
+ import { t as runCode } from "./run-code-5x8S5YWt.js";
4
+ import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-xjl2irqK.js";
4
5
  import { z } from "zod";
5
6
  import { convertSchemaToJsonSchema, toolDefinition } from "@tanstack/ai";
6
7
  //#region src/tanstack-ai.ts
@@ -173,20 +174,11 @@ function createCodeTool(options) {
173
174
  name: "codemode_execute",
174
175
  description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
175
176
  inputSchema: codeSchema
176
- }).server(async ({ code }) => {
177
- const normalizedCode = normalizeCode(code);
178
- const executeResult = await executor.execute(normalizedCode, resolvedProviders);
179
- if (executeResult.error) {
180
- const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
181
- throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
182
- }
183
- const output = {
184
- code,
185
- result: executeResult.result
186
- };
187
- if (executeResult.logs) output.logs = executeResult.logs;
188
- return output;
189
- });
177
+ }).server(async ({ code }) => runCode({
178
+ code,
179
+ executor,
180
+ providers: resolvedProviders
181
+ }));
190
182
  }
191
183
  /**
192
184
  * Generate types from a ToolProviderTools record.
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\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: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => t.needsApproval !== true && typeof t.needsApproval !== \"function\"\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\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 a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\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(`Code execution failed: ${executeResult.error}${logCtx}`);\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/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;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oBAAoB,SAAS;EACpF,kBAAkB;;CAGpB,iBAAiB,mBAAmB,UAAU,KAAK,eAAe;CAElE,OAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
1
+ {"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\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: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => t.needsApproval !== true && typeof t.needsApproval !== \"function\"\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\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 a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n );\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,QAAQ,CACR,KAAK,EAAE,aAAa,8CAA8C,CAAC,EACvE,CAAC;;;;;AAMF,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,OAA6B;CACzE,IAAI,CAAC,WAAW,OAAO;CACvB,OAAO;;;;;;;;AAST,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,KAAK;EAC5C,MAAM,WAAW,aAAa,SAAS;EAEvC,IAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,YAAY,GAC/B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,aAAa,GAChC;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBAAiB,GAAG,SAAS,OAAO,GACrD,QAAQ,SAAS;GAErB,MAAM,aAAa,mBACf,iBAAiB,kBAAkB,GAAG,SAAS,QAAQ,GACvD,QAAQ,SAAS;GAErB,kBAAkB,KAAK,UAAU,MAAM;GACvC,kBAAkB,KAAK,WAAW,MAAM;GAExC,MAAM,oBAAoB;IACxB,IAAI;KACF,IAAI,CAAC,iBAAiB,YAAY,OAAO,EAAE;KAC3C,OAAO,OAAO,QAAQ,gBAAgB,WAAW,CAC9C,QACE,GAAG,gBACF,cACA,OAAO,eAAe,YACrB,WAA2B,YAC/B,CACA,KACE,CAAC,WAAW,gBACX,gBAAgB,UAAU,KAAM,WAA2B,cAC9D;YACG;KACN,OAA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,eAAe;IACb,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -1,36 +0,0 @@
1
- //#region src/executor-types.d.ts
2
- /**
3
- * Shared executor contract used by all codemode runtimes.
4
- */
5
- interface ExecuteResult {
6
- result: unknown;
7
- error?: string;
8
- logs?: string[];
9
- }
10
- /**
11
- * Internal resolved form of a tool provider, ready for execution.
12
- * The tool functions are keyed by tool name and exposed under `name.*`
13
- * inside the sandbox.
14
- */
15
- interface ResolvedProvider {
16
- name: string;
17
- fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
18
- positionalArgs?: boolean;
19
- }
20
- /**
21
- * An executor runs LLM-generated code in a sandbox, making the provided
22
- * tool functions callable under their namespace inside the sandbox.
23
- *
24
- * Implementations should never throw — errors are returned in `ExecuteResult.error`.
25
- */
26
- interface Executor {
27
- execute(
28
- code: string,
29
- providersOrFns:
30
- | ResolvedProvider[]
31
- | Record<string, (...args: unknown[]) => Promise<unknown>>
32
- ): Promise<ExecuteResult>;
33
- }
34
- //#endregion
35
- export { Executor as n, ResolvedProvider as r, ExecuteResult as t };
36
- //# sourceMappingURL=executor-types-CJ06IBzw.d.ts.map