@cloudflare/codemode 0.3.5 → 0.3.7

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-BRm90XJT.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-TyFN6W7_.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";
2
- import { n as filterTools } from "./resolve-BU1FGVYs.js";
3
- import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-ra3HW2ti.js";
1
+ import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-CVt4X9cw.js";
2
+ import { n as filterTools } from "./resolve-DdyeEp3l.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
@@ -195,12 +196,10 @@ function aiTools(tools) {
195
196
  * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.
196
197
  */
197
198
  function resolveProvider(provider) {
198
- const resolved = {
199
+ return {
199
200
  name: provider.name ?? "codemode",
200
201
  fns: extractFns(filterTools(provider.tools))
201
202
  };
202
- if (provider.positionalArgs) resolved.positionalArgs = true;
203
- return resolved;
204
203
  }
205
204
  function createCodeTool(options) {
206
205
  const providers = normalizeProviders(options.tools);
@@ -211,32 +210,21 @@ function createCodeTool(options) {
211
210
  const filtered = filterTools(provider.tools);
212
211
  const types = provider.types ?? generateTypes(filtered, name);
213
212
  typeBlocks.push(types);
214
- const resolved = {
213
+ resolvedProviders.push({
215
214
  name,
216
215
  fns: extractFns(filtered)
217
- };
218
- if (provider.positionalArgs) resolved.positionalArgs = true;
219
- resolvedProviders.push(resolved);
216
+ });
220
217
  }
221
218
  const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
222
219
  const executor = options.executor;
223
220
  return tool({
224
221
  description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
225
222
  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
- }
223
+ execute: async ({ code }) => runCode({
224
+ code,
225
+ executor,
226
+ providers: resolvedProviders
227
+ })
240
228
  });
241
229
  }
242
230
  //#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;CAC/D,IAAI,YAAY,QAAQ,OAAO,YAAY,UAAU,OAAO;CAE5D,IAAI,gBAAgB,SAClB,OAAQ,QAAwC;CAGlD,MAAM,UAAU,OAAO,sBAAsB,QAAQ;CACrD,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,QAAoC;EACtD,IAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,UAC9D,OAAQ,SAAyC;;CAIrD,OAAO;;;;;;AAOT,SAAS,oBAAoB,QAAyC;CACpE,MAAM,eAAuC,EAAE;CAE/C,MAAM,QAAS,OAA+C;CAC9D,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,KAAK,MAAM,CAAC,WAAW,gBAAgB,OAAO,QAAQ,MAAM,EAAE;GAC5D,IAAI,IAAI;GACR,OAAO,CAAC,EAAE,eAAe,OAAO,EAAE,WAAW,YAC3C,IAAI,EAAE,QAAQ;GAEhB,IAAI,EAAE,aACJ,aAAa,aAAa,EAAE;;EAGhC,OAAO;;CAGT,IAAI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,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 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 resolvedProviders.push({ name, fns: extractFns(filtered) });\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;AAE3C;;;;;AAMA,SAAS,iBAAiB,OAAyB;CACjD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;AAExD;;;;;AAMA,SAAS,oBACP,OACsC;CACtC,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CAExD,IAAI,gBAAgB,OAClB,OAAO;CAGT,MAAM,UAAU,OAAO,sBAAsB,KAAK;CAClD,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,MAAkC;EACpD,IAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,UAC9D,OAAO;CAEX;CAEA,OAAO;AACT;;;;AAKA,SAAS,kBAAkB,SAAsC;CAC/D,IAAI,YAAY,QAAQ,OAAO,YAAY,UAAU,OAAO;CAE5D,IAAI,gBAAgB,SAClB,OAAQ,QAAwC;CAGlD,MAAM,UAAU,OAAO,sBAAsB,OAAO;CACpD,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,QAAoC;EACtD,IAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,UAC9D,OAAQ,SAAyC;CAErD;CAEA,OAAO;AACT;;;;;AAMA,SAAS,oBAAoB,QAAyC;CACpE,MAAM,eAAuC,CAAC;CAE9C,MAAM,QAAS,OAA+C;CAC9D,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC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AAW,OAAO,OAAO,EAAE,KAAK,MAAM;CAExD,MAAM,WAAW,QAAQ;CAOzB,OAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,SAIU;EACV,aAAa;EACb,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;EAAkB,CAAC;CAC5D,CAAC;AACH"}
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-BRm90XJT.js";
6
+ import { n as CodeOutput, t as CodeInput } from "./shared-TyFN6W7_.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;
@@ -59,41 +60,22 @@ function iframeSandboxRuntimeMain() {
59
60
  logs.push("[error] " + values.join(" "));
60
61
  };
61
62
  function createProviderProxy(nonce, provider) {
62
- return new Proxy({}, { get: (_, toolName) => {
63
- if (provider.positionalArgs) return (...args) => {
64
- const id = nextId++;
65
- return new Promise((resolve, reject) => {
66
- pending[id] = {
67
- resolve,
68
- reject
69
- };
70
- post({
71
- type: "tool-call",
72
- nonce,
73
- id,
74
- provider: provider.name,
75
- name: String(toolName),
76
- args
77
- });
78
- });
79
- };
80
- return (args) => {
81
- const id = nextId++;
82
- return new Promise((resolve, reject) => {
83
- pending[id] = {
84
- resolve,
85
- reject
86
- };
87
- post({
88
- type: "tool-call",
89
- nonce,
90
- id,
91
- provider: provider.name,
92
- name: String(toolName),
93
- args: args ?? {}
94
- });
63
+ return new Proxy({}, { get: (_, toolName) => (...args) => {
64
+ const id = nextId++;
65
+ return new Promise((resolve, reject) => {
66
+ pending[id] = {
67
+ resolve,
68
+ reject
69
+ };
70
+ post({
71
+ type: "tool-call",
72
+ nonce,
73
+ id,
74
+ provider: provider.name,
75
+ name: String(toolName),
76
+ args
95
77
  });
96
- };
78
+ });
97
79
  } });
98
80
  }
99
81
  function isToolResultMessage(message) {
@@ -104,7 +86,7 @@ function iframeSandboxRuntimeMain() {
104
86
  function isExecuteRequestMessage(message) {
105
87
  if (typeof message !== "object" || message === null) return false;
106
88
  const candidate = message;
107
- return candidate.type === "execute-request" && typeof candidate.nonce === "string" && typeof candidate.code === "string" && Array.isArray(candidate.providers) && candidate.providers.every((provider) => typeof provider === "object" && provider !== null && typeof provider.name === "string" && (provider.positionalArgs === void 0 || typeof provider.positionalArgs === "boolean"));
89
+ return candidate.type === "execute-request" && typeof candidate.nonce === "string" && typeof candidate.code === "string" && Array.isArray(candidate.providers) && candidate.providers.every((provider) => typeof provider === "object" && provider !== null && typeof provider.name === "string");
108
90
  }
109
91
  function executeCode(nonce, code, providers) {
110
92
  try {
@@ -276,12 +258,10 @@ var IframeSandboxExecutor = class {
276
258
  sanitizedNames.set(sanitizedName, name);
277
259
  sanitizedFns[sanitizedName] = fn;
278
260
  }
279
- const resolved = {
261
+ resolvedProviders.push({
280
262
  name: provider.name,
281
263
  fns: sanitizedFns
282
- };
283
- if (provider.positionalArgs) resolved.positionalArgs = true;
284
- resolvedProviders.push(resolved);
264
+ });
285
265
  }
286
266
  const providerMap = new Map(resolvedProviders.map((provider) => [provider.name, provider]));
287
267
  const nonce = createExecutionNonce();
@@ -289,18 +269,11 @@ var IframeSandboxExecutor = class {
289
269
  type: "execute-request",
290
270
  nonce,
291
271
  code: normalizedCode,
292
- providers: resolvedProviders.map((provider) => {
293
- if (provider.positionalArgs) return {
294
- name: provider.name,
295
- positionalArgs: true
296
- };
297
- return { name: provider.name };
298
- })
272
+ providers: resolvedProviders.map((provider) => ({ name: provider.name }))
299
273
  };
300
274
  const invokeProviderTool = async (provider, args, name) => {
301
275
  const fn = provider.fns[name];
302
276
  if (!fn) throw new Error(`Tool "${name}" not found`);
303
- if (!provider.positionalArgs) return fn(args);
304
277
  return fn(...Array.isArray(args) ? args : [args]);
305
278
  };
306
279
  const iframe = document.createElement("iframe");
@@ -486,10 +459,6 @@ function createBrowserCodeTool(options) {
486
459
  outputSchema: {
487
460
  type: "object",
488
461
  properties: {
489
- code: {
490
- type: "string",
491
- description: "The original code that was executed"
492
- },
493
462
  result: { description: "The return value of the executed code" },
494
463
  logs: {
495
464
  type: "array",
@@ -497,22 +466,13 @@ function createBrowserCodeTool(options) {
497
466
  description: "Console output captured during execution"
498
467
  }
499
468
  },
500
- required: ["code", "result"]
469
+ required: ["result"]
501
470
  },
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
- }
471
+ execute: async ({ code }) => runCode({
472
+ code,
473
+ executor,
474
+ providers: resolvedProviders
475
+ })
516
476
  };
517
477
  }
518
478
  //#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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B,wBAAwB,cAAc,KAAK,KAAK,KAAK,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 }[];\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) => isRecord(provider) && typeof provider.name === \"string\"\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(nonce: string, provider: { name: string }) {\n return new Proxy(\n {},\n {\n get:\n (_, toolName) =>\n (...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 }\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 }[];\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 )\n );\n }\n\n function executeCode(\n nonce: string,\n code: string,\n providers: { name: string }[]\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 resolvedProviders.push({\n name: provider.name,\n fns: sanitizedFns\n });\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) => ({ name: provider.name }))\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 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({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WAAW;EAAkB,CAAC;CAC5D;AACF"}
@@ -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,39 @@ 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
+ }
43
+ /**
44
+ * An executor runs LLM-generated code in a sandbox, making the provided
45
+ * tool functions callable under their namespace inside the sandbox.
46
+ *
47
+ * Implementations should never throw — errors are returned in `ExecuteResult.error`.
48
+ */
49
+ interface Executor {
50
+ execute(
51
+ code: string,
52
+ providersOrFns:
53
+ | ResolvedProvider[]
54
+ | Record<string, (...args: unknown[]) => Promise<unknown>>
55
+ ): Promise<ExecuteResult>;
56
+ }
57
+ //#endregion
30
58
  //#region src/executor.d.ts
31
59
  /**
32
60
  * A minimal tool record — just a description and an execute function.
@@ -70,14 +98,6 @@ interface ToolProvider {
70
98
  tools: ToolProviderTools;
71
99
  /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */
72
100
  types?: string;
73
- /**
74
- * When true, tools accept positional args instead of a single object arg.
75
- * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.
76
- *
77
- * Default tools use single-object args: `codemode.search({ query: "test" })`
78
- * Positional tools use normal args: `state.readFile("/path")`
79
- */
80
- positionalArgs?: boolean;
81
101
  }
82
102
  /**
83
103
  * An RpcTarget that dispatches tool calls from the sandboxed Worker
@@ -86,11 +106,8 @@ interface ToolProvider {
86
106
  */
87
107
  declare class ToolDispatcher extends RpcTarget {
88
108
  #private;
89
- constructor(
90
- fns: Record<string, (...args: unknown[]) => Promise<unknown>>,
91
- positionalArgs?: boolean
92
- );
93
- call(name: string, argsJson: string): Promise<string>;
109
+ constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>);
110
+ call(name: string, argsJson?: string): Promise<string>;
94
111
  }
95
112
  interface DynamicWorkerExecutorOptions {
96
113
  loader: WorkerLoader;
@@ -144,12 +161,15 @@ declare class DynamicWorkerExecutor implements Executor {
144
161
  //#endregion
145
162
  export {
146
163
  ToolProviderTools as a,
147
- generateTypes as c,
164
+ ResolvedProvider as c,
165
+ generateTypes as d,
148
166
  ToolProvider as i,
167
+ ToolDescriptor as l,
149
168
  DynamicWorkerExecutorOptions as n,
150
- ToolDescriptor as o,
169
+ ExecuteResult as o,
151
170
  ToolDispatcher as r,
152
- ToolDescriptors as s,
153
- DynamicWorkerExecutor as t
171
+ Executor as s,
172
+ DynamicWorkerExecutor as t,
173
+ ToolDescriptors as u
154
174
  };
155
- //# sourceMappingURL=executor-C-DgAHLS.d.ts.map
175
+ //# sourceMappingURL=executor-BRm90XJT.d.ts.map