@cloudflare/codemode 0.3.3 → 0.3.5

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/README.md CHANGED
@@ -237,12 +237,18 @@ The `Executor` interface is deliberately minimal — implement it to run code in
237
237
  interface Executor {
238
238
  execute(
239
239
  code: string,
240
- providers:
240
+ providersOrFns:
241
241
  | ResolvedProvider[]
242
242
  | Record<string, (...args: unknown[]) => Promise<unknown>>
243
243
  ): Promise<ExecuteResult>;
244
244
  }
245
245
 
246
+ interface ResolvedProvider {
247
+ name: string;
248
+ fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
249
+ positionalArgs?: boolean;
250
+ }
251
+
246
252
  interface ExecuteResult {
247
253
  result: unknown;
248
254
  error?: string;
@@ -288,6 +294,16 @@ class NodeVMExecutor implements Executor {
288
294
  | `globalOutbound` | `Fetcher \| null` | `null` | Network access control. `null` = blocked, `Fetcher` = routed |
289
295
  | `modules` | `Record<string, string>` | `{}` | Extra modules importable in the sandbox |
290
296
 
297
+ ### IframeSandboxExecutor options
298
+
299
+ Import from `@cloudflare/codemode/browser` when code should run in the browser
300
+ against browser-owned tools.
301
+
302
+ | Option | Type | Default | Description |
303
+ | --------- | -------- | --------------------------------------------------------------- | ------------------------------------------------------------------------ |
304
+ | `timeout` | `number` | `30000` | Execution timeout in ms. Cannot preempt tight synchronous browser loops. |
305
+ | `csp` | `string` | `default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval';` | Content Security Policy applied to the sandbox iframe document. |
306
+
291
307
  ### createCodeTool options
292
308
 
293
309
  | Option | Type | Default | Description |
@@ -428,16 +444,19 @@ const types = generateTypes(myAiSdkTools);
428
444
  | `@cloudflare/codemode` | None | `sanitizeToolName`, `normalizeCode`, `generateTypesFromJsonSchema`, `jsonSchemaToType`, `DynamicWorkerExecutor`, `ToolDispatcher`, `ToolProvider`, `resolveProvider` |
429
445
  | `@cloudflare/codemode/ai` | `ai`, `zod` | `createCodeTool`, `generateTypes`, `aiTools`, `resolveProvider`, `ToolDescriptor`, `ToolDescriptors` |
430
446
  | `@cloudflare/codemode/tanstack-ai` | `@tanstack/ai`, `zod` | `createCodeTool`, `generateTypes`, `tanstackTools`, `resolveProvider` |
447
+ | `@cloudflare/codemode/browser` | None | `createBrowserCodeTool`, `IframeSandboxExecutor`, `Executor`, `ExecuteResult`, `ResolvedProvider`, JSON Schema tool descriptor types |
431
448
 
432
449
  ## Limitations
433
450
 
434
- - **Tool approval (`needsApproval`) is not supported yet.** Tools with `needsApproval: true` execute immediately inside the sandbox without pausing for approval. Support for approval flows within codemode is planned. For now, do not pass approval-required tools to `createCodeTool` — use them through standard AI SDK tool calling instead.
451
+ - **Tool approval (`needsApproval`) is not supported yet.** Tools with `needsApproval: true` or a `needsApproval` function are excluded from codemode instead of pausing execution for approval. Support for approval flows within codemode is planned. For now, use approval-required tools through standard AI SDK tool calling instead.
452
+ - Browser iframe execution uses nonce-scoped internal messages, but its timeout cannot preempt tight synchronous loops like `while (true) {}` because those block the browser event loop.
435
453
  - Requires Cloudflare Workers environment for `DynamicWorkerExecutor`
436
454
  - Limited to JavaScript execution
437
455
 
438
456
  ## Examples
439
457
 
440
458
  - [`examples/codemode/`](../../examples/codemode/) — Full working example with task management tools
459
+ - [`examples/codemode-browser/`](../../examples/codemode-browser/) — Browser iframe executor example with dynamic client tools
441
460
 
442
461
  ## License
443
462
 
package/dist/ai.d.ts CHANGED
@@ -1,15 +1,15 @@
1
1
  import {
2
- a as ResolvedProvider,
3
- d as generateTypes,
4
- l as ToolDescriptor,
5
- s as ToolProvider,
6
- u as ToolDescriptors
7
- } from "./executor-wZjYdqEX.js";
2
+ c as generateTypes,
3
+ 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";
8
8
  import {
9
9
  n as CodeOutput,
10
10
  r as CreateCodeToolOptions,
11
11
  t as CodeInput
12
- } from "./shared-Hnh_Idta.js";
12
+ } from "./shared-C3CDOc8T.js";
13
13
  import { Tool, ToolSet } from "ai";
14
14
 
15
15
  //#region src/tool.d.ts
package/dist/ai.js CHANGED
@@ -1,5 +1,5 @@
1
- import { i as normalizeCode, n as filterTools } from "./resolve-DIQRkRqQ.js";
2
- import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-DoQ0VISs.js";
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
3
  import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-ra3HW2ti.js";
4
4
  import { asSchema, tool } from "ai";
5
5
  import { z } from "zod";
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;AACrD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;AACjD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS,oBACP,OACsC;AACtC,KAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AAExD,KAAI,gBAAgB,MAClB,QAAO;CAGT,MAA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CAGxE,MAAM,WAA6B;EAAE,MAFxB,SAAS,QAAQ;EAEa,KAAK,WAD/B,YAAY,SAAS,MAAM,CACwB;EAAE;AACtE,KAAI,SAAS,eAAgB,UAAS,iBAAiB;AACvD,QAAO;;AAGT,SAAgB,eACd,SAC6B;CAC7B,MAAM,YAAY,mBAAmB,QAAQ,MAAM;CAGnD,MAAM,aAAuB,EAAE;CAC/B,MAAM,oBAAwC,EAAE;AAEhD,MAAK,MAAM,YAAY,WAAW;EAChC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,WAAW,YAAY,SAAS,MAAM;EAC5C,MAAM,QACJ,SAAS,SAAS,cAAc,UAA6B,KAAK;AACpE,aAAW,KAAK,MAAM;EACtB,MAAM,WAA6B;GAAE;GAAM,KAAK,WAAW,SAAS;GAAE;AACtE,MAAI,SAAS,eAAgB,UAAS,iBAAiB;AACvD,oBAAkB,KAAK,SAAS;;CAGlC,MAAM,YAAY,WAAW,OAAO,QAAQ,CAAC,KAAK,OAAO;CAEzD,MAAM,WAAW,QAAQ;AAOzB,QAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,UACD;EAIC,aAAa;EACb,SAAS,OAAO,EAAE,WAAW;GAC3B,MAAM,iBAAiB,cAAc,KAAK;GAE1C,MAAM,gBAAgB,MAAM,SAAS,QACnC,gBACA,kBACD;AAED,OAAI,cAAc,OAAO;IACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;AACJ,UAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;AACjE,OAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
1
+ {"version":3,"file":"ai.js","names":[],"sources":["../src/tool-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,eA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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"}
@@ -0,0 +1,149 @@
1
+ import {
2
+ n as Executor,
3
+ r as ResolvedProvider,
4
+ t as ExecuteResult
5
+ } from "./executor-types-CJ06IBzw.js";
6
+ import {
7
+ n as JsonSchemaToolDescriptors,
8
+ t as JsonSchemaToolDescriptor
9
+ } from "./json-schema-types-1OL3uao0.js";
10
+
11
+ //#region src/iframe-executor.d.ts
12
+ interface IframeSandboxExecutorOptions {
13
+ /** Maximum execution time in milliseconds. Defaults to `30000`. */
14
+ timeout?: number;
15
+ /**
16
+ * Content Security Policy applied to the iframe document.
17
+ *
18
+ * When omitted, defaults to a restrictive policy that only allows
19
+ * inline scripts and eval (needed for code execution).
20
+ */
21
+ csp?: string;
22
+ }
23
+ /**
24
+ * Executes LLM-generated code in a browser iframe sandbox.
25
+ *
26
+ * For each execution, a hidden iframe is created with `sandbox="allow-scripts"`,
27
+ * the runtime is injected via `srcdoc`, and the iframe is removed after completion.
28
+ * Tool calls are dispatched via `postMessage`.
29
+ */
30
+ declare class IframeSandboxExecutor implements Executor {
31
+ #private;
32
+ constructor(options?: IframeSandboxExecutorOptions);
33
+ execute(
34
+ code: string,
35
+ providersOrFns:
36
+ | ResolvedProvider[]
37
+ | Record<string, (...args: unknown[]) => Promise<unknown>>
38
+ ): Promise<ExecuteResult>;
39
+ }
40
+ //#endregion
41
+ //#region src/browser-tool.d.ts
42
+ /**
43
+ * A JSON Schema tool descriptor with an execute function attached.
44
+ */
45
+ interface JsonSchemaExecutableToolDescriptor extends JsonSchemaToolDescriptor {
46
+ name?: string;
47
+ execute: (args: Record<string, unknown>) => Promise<unknown>;
48
+ }
49
+ type JsonSchemaExecutableToolDescriptors = Record<
50
+ string,
51
+ JsonSchemaExecutableToolDescriptor
52
+ >;
53
+ interface ApprovalAwareJsonSchemaExecutableToolDescriptor extends JsonSchemaExecutableToolDescriptor {
54
+ needsApproval?: boolean | ((...args: unknown[]) => unknown);
55
+ }
56
+ type ApprovalAwareJsonSchemaExecutableToolDescriptors = Record<
57
+ string,
58
+ ApprovalAwareJsonSchemaExecutableToolDescriptor
59
+ >;
60
+ interface BrowserCodeToolDescriptor {
61
+ name: string;
62
+ description: string;
63
+ inputSchema: {
64
+ type: "object";
65
+ properties: {
66
+ code: {
67
+ type: "string";
68
+ description: string;
69
+ };
70
+ };
71
+ required: ["code"];
72
+ };
73
+ outputSchema: {
74
+ type: "object";
75
+ properties: {
76
+ code: {
77
+ type: "string";
78
+ description: string;
79
+ };
80
+ result: {
81
+ description: string;
82
+ };
83
+ logs: {
84
+ type: "array";
85
+ items: {
86
+ type: "string";
87
+ };
88
+ description: string;
89
+ };
90
+ };
91
+ required: ["code", "result"];
92
+ };
93
+ execute: (args: { code: string }) => Promise<{
94
+ code: string;
95
+ result: unknown;
96
+ logs?: string[];
97
+ }>;
98
+ }
99
+ interface CreateBrowserCodeToolOptions {
100
+ /**
101
+ * Tools available inside the sandbox via `codemode.*`.
102
+ *
103
+ * Accepts either an array (like `listTools()` returns) with `name` on each item,
104
+ * or an object keyed by tool name (like `createCodeTool` expects).
105
+ */
106
+ tools:
107
+ | ApprovalAwareJsonSchemaExecutableToolDescriptor[]
108
+ | ApprovalAwareJsonSchemaExecutableToolDescriptors;
109
+ /**
110
+ * Executor to use. Defaults to a new `IframeSandboxExecutor`.
111
+ */
112
+ executor?: Executor;
113
+ /**
114
+ * Custom tool description. Use `{{types}}` as a placeholder for generated type definitions.
115
+ */
116
+ description?: string;
117
+ }
118
+ /**
119
+ * Create a codemode tool descriptor using only JSON Schema and browser APIs.
120
+ *
121
+ * This is the browser counterpart to `createCodeTool` from
122
+ * `@cloudflare/codemode/ai`.
123
+ * It returns a plain object with `{ name, description, inputSchema, outputSchema, execute }`
124
+ * that can be passed to any framework — including
125
+ * `navigator.modelContext.registerTool()`.
126
+ *
127
+ * Tools with `needsApproval` are excluded, matching the current codemode
128
+ * behavior for approval-gated tools. JSON Schema is used for prompt/type
129
+ * generation only and is not enforced at runtime.
130
+ */
131
+ declare function createBrowserCodeTool(
132
+ options: CreateBrowserCodeToolOptions
133
+ ): BrowserCodeToolDescriptor;
134
+ //#endregion
135
+ export {
136
+ type BrowserCodeToolDescriptor,
137
+ type CreateBrowserCodeToolOptions,
138
+ type ExecuteResult,
139
+ type Executor,
140
+ IframeSandboxExecutor,
141
+ type IframeSandboxExecutorOptions,
142
+ type JsonSchemaExecutableToolDescriptor,
143
+ type JsonSchemaExecutableToolDescriptors,
144
+ type JsonSchemaToolDescriptor,
145
+ type JsonSchemaToolDescriptors,
146
+ type ResolvedProvider,
147
+ createBrowserCodeTool
148
+ };
149
+ //# sourceMappingURL=browser.d.ts.map