@cloudflare/codemode 0.3.6 → 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
@@ -4,12 +4,12 @@ import {
4
4
  i as ToolProvider,
5
5
  l as ToolDescriptor,
6
6
  u as ToolDescriptors
7
- } from "./executor-BWtTiHBV.js";
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-CcZcDoiO.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,5 +1,5 @@
1
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-BU1FGVYs.js";
2
+ import { n as filterTools } from "./resolve-DdyeEp3l.js";
3
3
  import { t as runCode } from "./run-code-5x8S5YWt.js";
4
4
  import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-xjl2irqK.js";
5
5
  import { asSchema, tool } from "ai";
@@ -196,12 +196,10 @@ function aiTools(tools) {
196
196
  * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.
197
197
  */
198
198
  function resolveProvider(provider) {
199
- const resolved = {
199
+ return {
200
200
  name: provider.name ?? "codemode",
201
201
  fns: extractFns(filterTools(provider.tools))
202
202
  };
203
- if (provider.positionalArgs) resolved.positionalArgs = true;
204
- return resolved;
205
203
  }
206
204
  function createCodeTool(options) {
207
205
  const providers = normalizeProviders(options.tools);
@@ -212,12 +210,10 @@ function createCodeTool(options) {
212
210
  const filtered = filterTools(provider.tools);
213
211
  const types = provider.types ?? generateTypes(filtered, name);
214
212
  typeBlocks.push(types);
215
- const resolved = {
213
+ resolvedProviders.push({
216
214
  name,
217
215
  fns: extractFns(filtered)
218
- };
219
- if (provider.positionalArgs) resolved.positionalArgs = true;
220
- resolvedProviders.push(resolved);
216
+ });
221
217
  }
222
218
  const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
223
219
  const executor = options.executor;
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 { runCode } from \"./run-code\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[name] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [stateTools(workspace), aiTools(myTools)],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n });\n}\n"],"mappings":";;;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;CACjD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS,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,EA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AW,QAAQ;CAOzB,OAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,UAIW;EACX,aAAa;EACb,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;GAAmB,CAAC;EAC5D,CAAC"}
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,KAAK,MAAM,CAAC,WAAW,gBAAgB,OAAO,QAAQ,KAAK,GAAG;GAC5D,IAAI,IAAI;GACR,OAAO,CAAC,EAAE,eAAe,OAAO,EAAE,WAAW,YAC3C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ACV,aAAa;EACb,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;EAAkB,CAAC;CAC5D,CAAC;AACH"}
package/dist/browser.d.ts CHANGED
@@ -2,8 +2,8 @@ import {
2
2
  c as ResolvedProvider,
3
3
  o as ExecuteResult,
4
4
  s as Executor
5
- } from "./executor-BWtTiHBV.js";
6
- import { n as CodeOutput, t as CodeInput } from "./shared-CcZcDoiO.js";
5
+ } from "./executor-BRm90XJT.js";
6
+ import { n as CodeOutput, t as CodeInput } from "./shared-TyFN6W7_.js";
7
7
  import {
8
8
  n as JsonSchemaToolDescriptors,
9
9
  t as JsonSchemaToolDescriptor
package/dist/browser.js CHANGED
@@ -60,41 +60,22 @@ function iframeSandboxRuntimeMain() {
60
60
  logs.push("[error] " + values.join(" "));
61
61
  };
62
62
  function createProviderProxy(nonce, provider) {
63
- return new Proxy({}, { get: (_, toolName) => {
64
- if (provider.positionalArgs) return (...args) => {
65
- const id = nextId++;
66
- return new Promise((resolve, reject) => {
67
- pending[id] = {
68
- resolve,
69
- reject
70
- };
71
- post({
72
- type: "tool-call",
73
- nonce,
74
- id,
75
- provider: provider.name,
76
- name: String(toolName),
77
- args
78
- });
79
- });
80
- };
81
- return (args) => {
82
- const id = nextId++;
83
- return new Promise((resolve, reject) => {
84
- pending[id] = {
85
- resolve,
86
- reject
87
- };
88
- post({
89
- type: "tool-call",
90
- nonce,
91
- id,
92
- provider: provider.name,
93
- name: String(toolName),
94
- args: args ?? {}
95
- });
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
96
77
  });
97
- };
78
+ });
98
79
  } });
99
80
  }
100
81
  function isToolResultMessage(message) {
@@ -105,7 +86,7 @@ function iframeSandboxRuntimeMain() {
105
86
  function isExecuteRequestMessage(message) {
106
87
  if (typeof message !== "object" || message === null) return false;
107
88
  const candidate = message;
108
- 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");
109
90
  }
110
91
  function executeCode(nonce, code, providers) {
111
92
  try {
@@ -277,12 +258,10 @@ var IframeSandboxExecutor = class {
277
258
  sanitizedNames.set(sanitizedName, name);
278
259
  sanitizedFns[sanitizedName] = fn;
279
260
  }
280
- const resolved = {
261
+ resolvedProviders.push({
281
262
  name: provider.name,
282
263
  fns: sanitizedFns
283
- };
284
- if (provider.positionalArgs) resolved.positionalArgs = true;
285
- resolvedProviders.push(resolved);
264
+ });
286
265
  }
287
266
  const providerMap = new Map(resolvedProviders.map((provider) => [provider.name, provider]));
288
267
  const nonce = createExecutionNonce();
@@ -290,18 +269,11 @@ var IframeSandboxExecutor = class {
290
269
  type: "execute-request",
291
270
  nonce,
292
271
  code: normalizedCode,
293
- providers: resolvedProviders.map((provider) => {
294
- if (provider.positionalArgs) return {
295
- name: provider.name,
296
- positionalArgs: true
297
- };
298
- return { name: provider.name };
299
- })
272
+ providers: resolvedProviders.map((provider) => ({ name: provider.name }))
300
273
  };
301
274
  const invokeProviderTool = async (provider, args, name) => {
302
275
  const fn = provider.fns[name];
303
276
  if (!fn) throw new Error(`Tool "${name}" not found`);
304
- if (!provider.positionalArgs) return fn(args);
305
277
  return fn(...Array.isArray(args) ? args : [args]);
306
278
  };
307
279
  const iframe = document.createElement("iframe");
@@ -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 { runCode } from \"./run-code\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor, ResolvedProvider } from \"./executor-types\";\nimport type { CodeInput, CodeOutput } from \"./shared\";\nimport { IframeSandboxExecutor } from \"./iframe-executor\";\n\n// -- Types --\n\n/**\n * A JSON Schema tool descriptor with an execute function attached.\n */\nexport interface JsonSchemaExecutableToolDescriptor extends JsonSchemaToolDescriptor {\n name?: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type JsonSchemaExecutableToolDescriptors = Record<\n string,\n JsonSchemaExecutableToolDescriptor\n>;\n\ninterface ApprovalAwareJsonSchemaExecutableToolDescriptor extends JsonSchemaExecutableToolDescriptor {\n needsApproval?: boolean | ((...args: unknown[]) => unknown);\n}\n\ntype ApprovalAwareJsonSchemaExecutableToolDescriptors = Record<\n string,\n ApprovalAwareJsonSchemaExecutableToolDescriptor\n>;\n\nexport interface BrowserCodeToolDescriptor {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: {\n code: { type: \"string\"; description: string };\n };\n required: [\"code\"];\n };\n outputSchema: {\n type: \"object\";\n properties: {\n result: { description: string };\n logs: {\n type: \"array\";\n items: { type: \"string\" };\n description: string;\n };\n };\n required: [\"result\"];\n };\n execute: (args: CodeInput) => Promise<CodeOutput>;\n}\n\nexport interface CreateBrowserCodeToolOptions {\n /**\n * Tools available inside the sandbox via `codemode.*`.\n *\n * Accepts either an array (like `listTools()` returns) with `name` on each item,\n * or an object keyed by tool name (like `createCodeTool` expects).\n */\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors;\n /**\n * Executor to use. Defaults to a new `IframeSandboxExecutor`.\n */\n executor?: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for generated type definitions.\n */\n description?: string;\n}\n\n// -- Implementation --\n\nconst DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nfunction toRecord(\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors\n): ApprovalAwareJsonSchemaExecutableToolDescriptors {\n if (!Array.isArray(tools)) return tools;\n\n const record: ApprovalAwareJsonSchemaExecutableToolDescriptors = {};\n for (const tool of tools) {\n if (!tool.name) {\n throw new Error(\n \"Tool descriptors in array form must have a `name` property\"\n );\n }\n record[tool.name] = tool;\n }\n return record;\n}\n\nfunction hasNeedsApproval(tool: Record<string, unknown>): boolean {\n return (\n tool.needsApproval === true || typeof tool.needsApproval === \"function\"\n );\n}\n\n/**\n * Create a codemode tool descriptor using only JSON Schema and browser APIs.\n *\n * This is the browser counterpart to `createCodeTool` from\n * `@cloudflare/codemode/ai`.\n * It returns a plain object with `{ name, description, inputSchema, outputSchema, execute }`\n * that can be passed to any framework — including\n * `navigator.modelContext.registerTool()`.\n *\n * Tools with `needsApproval` are excluded, matching the current codemode\n * behavior for approval-gated tools. JSON Schema is used for prompt/type\n * generation only and is not enforced at runtime.\n */\nexport function createBrowserCodeTool(\n options: CreateBrowserCodeToolOptions\n): BrowserCodeToolDescriptor {\n const allTools = toRecord(options.tools);\n const toolMap: JsonSchemaExecutableToolDescriptors = {};\n for (const [name, tool] of Object.entries(allTools)) {\n if (!hasNeedsApproval(tool as unknown as Record<string, unknown>)) {\n toolMap[name] = tool;\n }\n }\n const executor = options.executor ?? new IframeSandboxExecutor();\n\n // Generate TypeScript type descriptions for the LLM prompt\n const schemaOnly: JsonSchemaToolDescriptors = {};\n for (const [name, tool] of Object.entries(toolMap)) {\n schemaOnly[name] = {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema\n };\n }\n const types = generateTypesFromJsonSchema(schemaOnly);\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n // Extract execute functions, keyed by sanitized name\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, tool] of Object.entries(toolMap)) {\n if (tool.execute) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n throw new Error(\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to \"${sanitizedName}\"`\n );\n }\n sanitizedNames.set(sanitizedName, name);\n fns[sanitizedName] = tool.execute as (args: unknown) => Promise<unknown>;\n }\n }\n const resolvedProviders: ResolvedProvider[] = [{ name: \"codemode\", fns }];\n\n return {\n name: \"codemode\",\n description,\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"JavaScript async arrow function to execute\"\n }\n },\n required: [\"code\"]\n },\n outputSchema: {\n type: \"object\",\n properties: {\n result: {\n description: \"The return value of the executed code\"\n },\n logs: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Console output captured during execution\"\n }\n },\n required: [\"result\"]\n },\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n };\n}\n"],"mappings":";;;AAYA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;;AAiDhD,SAAgB,sBACd,MAC6B;CAC7B,OAAO,SAAS,KAAK,IAAI,KAAK,SAAS;;AAGzC,SAAgB,kBAAkB,MAAwC;CACxE,OACE,SAAS,KAAK,IACd,KAAK,SAAS,eACd,OAAO,KAAK,UAAU,YACtB,OAAO,KAAK,OAAO,YACnB,OAAO,KAAK,aAAa,YACzB,OAAO,KAAK,SAAS;;AAIzB,SAAgB,yBACd,MACgC;CAChC,IAAI,CAAC,SAAS,KAAK,EAAE,OAAO;CAC5B,IAAI,KAAK,SAAS,oBAAoB,OAAO;CAC7C,IAAI,OAAO,KAAK,UAAU,UAAU,OAAO;CAC3C,IAAI,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW,MAAM,OAAO;CACpE,OAAO;;;;;;;;;;;;;;;;;;ACvET,SAAS,2BAAiC;CACxC,MAAM,gBAAgB;CAGtB,IAAI,cAAc,6BAChB;CAGF,cAAc,8BAA8B;CAE5C,MAAM,OAAiB,EAAE;CACzB,MAAM,UAGF,EAAE;CACN,IAAI,SAAS;CACb,IAAI;CAEJ,SAAS,KAAK,SAAkB;EAC9B,OAAO,YAAY,SAAS,IAAI;;CAIlC,QAAQ,OAAO,GAAG,SAAoB;EACpC,MAAM,SAAS,EAAE;EACjB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,OAAO,KAAK,OAAO,KAAK,GAAG,CAAC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ACnC,MAAM,IAAI,MACR,eAAe,aAAa,SAAS,KAAK,sBAAsB,cAAc,GAC/E;EAEH,eAAe,IAAI,eAAe,KAAK;EACvC,IAAI,iBAAiB,KAAK;;CAG9B,MAAM,oBAAwC,CAAC;EAAE,MAAM;EAAY;EAAK,CAAC;CAEzE,OAAO;EACL,MAAM;EACN;EACA,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACd,EACF;GACD,UAAU,CAAC,OAAO;GACnB;EACD,cAAc;GACZ,MAAM;GACN,YAAY;IACV,QAAQ,EACN,aAAa,yCACd;IACD,MAAM;KACJ,MAAM;KACN,OAAO,EAAE,MAAM,UAAU;KACzB,aAAa;KACd;IACF;GACD,UAAU,CAAC,SAAS;GACrB;EACD,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;GAAmB,CAAC;EAC5D"}
1
+ {"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({ code, executor, providers: resolvedProviders })\n };\n}\n"],"mappings":";;;AAYA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAgDA,SAAgB,sBACd,MAC6B;CAC7B,OAAO,SAAS,IAAI,KAAK,KAAK,SAAS;AACzC;AAEA,SAAgB,kBAAkB,MAAwC;CACxE,OACE,SAAS,IAAI,KACb,KAAK,SAAS,eACd,OAAO,KAAK,UAAU,YACtB,OAAO,KAAK,OAAO,YACnB,OAAO,KAAK,aAAa,YACzB,OAAO,KAAK,SAAS;AAEzB;AAEA,SAAgB,yBACd,MACgC;CAChC,IAAI,CAAC,SAAS,IAAI,GAAG,OAAO;CAC5B,IAAI,KAAK,SAAS,oBAAoB,OAAO;CAC7C,IAAI,OAAO,KAAK,UAAU,UAAU,OAAO;CAC3C,IAAI,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW,MAAM,OAAO;CACpE,OAAO;AACT;;;;;;;;;;;;;;;;;ACxEA,SAAS,2BAAiC;CACxC,MAAM,gBAAgB;CAGtB,IAAI,cAAc,6BAChB;CAGF,cAAc,8BAA8B;CAE5C,MAAM,OAAiB,CAAC;CACxB,MAAM,UAGF,CAAC;CACL,IAAI,SAAS;CACb,IAAI;CAEJ,SAAS,KAAK,SAAkB;EAC9B,OAAO,YAAY,SAAS,GAAG;CACjC;CAGA,QAAQ,OAAO,GAAG,SAAoB;EACp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,CAAC;CAExE,OAAO;EACL,MAAM;EACN;EACA,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACf,EACF;GACA,UAAU,CAAC,MAAM;EACnB;EACA,cAAc;GACZ,MAAM;GACN,YAAY;IACV,QAAQ,EACN,aAAa,wCACf;IACA,MAAM;KACJ,MAAM;KACN,OAAO,EAAE,MAAM,SAAS;KACxB,aAAa;IACf;GACF;GACA,UAAU,CAAC,QAAQ;EACrB;EACA,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;EAAkB,CAAC;CAC5D;AACF"}
@@ -39,7 +39,6 @@ interface ExecuteResult {
39
39
  interface ResolvedProvider {
40
40
  name: string;
41
41
  fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
42
- positionalArgs?: boolean;
43
42
  }
44
43
  /**
45
44
  * An executor runs LLM-generated code in a sandbox, making the provided
@@ -99,14 +98,6 @@ interface ToolProvider {
99
98
  tools: ToolProviderTools;
100
99
  /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */
101
100
  types?: string;
102
- /**
103
- * When true, tools accept positional args instead of a single object arg.
104
- * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.
105
- *
106
- * Default tools use single-object args: `codemode.search({ query: "test" })`
107
- * Positional tools use normal args: `state.readFile("/path")`
108
- */
109
- positionalArgs?: boolean;
110
101
  }
111
102
  /**
112
103
  * An RpcTarget that dispatches tool calls from the sandboxed Worker
@@ -115,11 +106,8 @@ interface ToolProvider {
115
106
  */
116
107
  declare class ToolDispatcher extends RpcTarget {
117
108
  #private;
118
- constructor(
119
- fns: Record<string, (...args: unknown[]) => Promise<unknown>>,
120
- positionalArgs?: boolean
121
- );
122
- call(name: string, argsJson: string): Promise<string>;
109
+ constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>);
110
+ call(name: string, argsJson?: string): Promise<string>;
123
111
  }
124
112
  interface DynamicWorkerExecutorOptions {
125
113
  loader: WorkerLoader;
@@ -184,4 +172,4 @@ export {
184
172
  DynamicWorkerExecutor as t,
185
173
  ToolDescriptors as u
186
174
  };
187
- //# sourceMappingURL=executor-BWtTiHBV.d.ts.map
175
+ //# sourceMappingURL=executor-BRm90XJT.d.ts.map
package/dist/index.d.ts CHANGED
@@ -6,14 +6,14 @@ import {
6
6
  r as ToolDispatcher,
7
7
  s as Executor,
8
8
  t as DynamicWorkerExecutor
9
- } from "./executor-BWtTiHBV.js";
9
+ } from "./executor-BRm90XJT.js";
10
10
  import {
11
11
  i as jsonSchemaToType,
12
12
  n as JsonSchemaToolDescriptors,
13
13
  r as generateTypesFromJsonSchema,
14
14
  t as JsonSchemaToolDescriptor
15
15
  } from "./json-schema-types-1OL3uao0.js";
16
- import { t as resolveProvider } from "./resolve-9VUW-grI.js";
16
+ import { t as resolveProvider } from "./resolve-DtfaKmms.js";
17
17
 
18
18
  //#region src/utils.d.ts
19
19
  /**
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as sanitizeToolName, n as jsonSchemaToType, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-CVt4X9cw.js";
2
- import { r as resolveProvider } from "./resolve-BU1FGVYs.js";
2
+ import { r as resolveProvider } from "./resolve-DdyeEp3l.js";
3
3
  import { RpcTarget } from "cloudflare:workers";
4
4
  //#region src/executor.ts
5
5
  /**
@@ -103,21 +103,16 @@ const SANDBOX_CODEC = String.raw`
103
103
  */
104
104
  var ToolDispatcher = class extends RpcTarget {
105
105
  #fns;
106
- #positionalArgs;
107
- constructor(fns, positionalArgs = false) {
106
+ constructor(fns) {
108
107
  super();
109
108
  this.#fns = fns;
110
- this.#positionalArgs = positionalArgs;
111
109
  }
112
110
  async call(name, argsJson) {
113
111
  const fn = this.#fns[name];
114
112
  if (!fn) return stringifyForCodemode({ error: `Tool "${name}" not found` });
115
113
  try {
116
- if (this.#positionalArgs) {
117
- const args = argsJson ? parseForCodemode(argsJson) : [];
118
- return stringifyForCodemode({ result: await fn(...Array.isArray(args) ? args : [args]) });
119
- }
120
- return stringifyForCodemode({ result: await fn(argsJson ? parseForCodemode(argsJson) : {}) });
114
+ const args = argsJson ? parseForCodemode(argsJson) : [];
115
+ return stringifyForCodemode({ result: await fn(...Array.isArray(args) ? args : [args]) });
121
116
  } catch (err) {
122
117
  return stringifyForCodemode({ error: err instanceof Error ? err.message : String(err) });
123
118
  }
@@ -202,10 +197,7 @@ var DynamicWorkerExecutor = class {
202
197
  " console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };",
203
198
  " console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };",
204
199
  SANDBOX_CODEC,
205
- ...providers.map((p) => {
206
- if (p.positionalArgs) return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (...args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`;
207
- return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args ?? {}));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`;
208
- }),
200
+ ...providers.map((p) => ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (...args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`),
209
201
  "",
210
202
  " try {",
211
203
  " const result = await Promise.race([",
@@ -235,7 +227,7 @@ var DynamicWorkerExecutor = class {
235
227
  sanitizedNames.set(sanitizedName, name);
236
228
  sanitizedFns[sanitizedName] = fn;
237
229
  }
238
- dispatchers[provider.name] = new ToolDispatcher(sanitizedFns, provider.positionalArgs);
230
+ dispatchers[provider.name] = new ToolDispatcher(sanitizedFns);
239
231
  }
240
232
  const response = await this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({
241
233
  compatibilityDate: "2025-06-01",
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#fns","#positionalArgs","#loader","#timeout","#globalOutbound","#modules"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\nexport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\n\nconst BINARY_TAG = \"__codemode_binary_v1__\";\n\ntype EncodedBinary = {\n [BINARY_TAG]: \"Uint8Array\" | \"ArrayBuffer\" | \"ArrayBufferView\";\n data: string;\n};\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength))\n );\n }\n return btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nfunction encodeCodemodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { [BINARY_TAG]: \"Uint8Array\", data: bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return {\n [BINARY_TAG]: \"ArrayBuffer\",\n data: bytesToBase64(new Uint8Array(value))\n };\n }\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return {\n [BINARY_TAG]: \"ArrayBufferView\",\n data: bytesToBase64(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n )\n };\n }\n return value;\n}\n\nfunction decodeCodemodeValue(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || !(BINARY_TAG in value)) {\n return value;\n }\n const encoded = value as EncodedBinary;\n if (typeof encoded.data !== \"string\") return value;\n const bytes = base64ToBytes(encoded.data);\n if (encoded[BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength\n );\n }\n return bytes;\n}\n\nfunction stringifyForCodemode(value: unknown): string {\n return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));\n}\n\nfunction parseForCodemode(json: string): unknown {\n return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));\n}\n\nconst SANDBOX_CODEC = String.raw`\n const __CODEMODE_BINARY_TAG = \"__codemode_binary_v1__\";\n function __bytesToBase64(bytes) {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));\n }\n return btoa(binary);\n }\n function __base64ToBytes(b64) {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n function __encodeCodemodeValue(value) {\n if (value instanceof Uint8Array) {\n return { [__CODEMODE_BINARY_TAG]: \"Uint8Array\", data: __bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBuffer\", data: __bytesToBase64(new Uint8Array(value)) };\n }\n if (ArrayBuffer.isView(value)) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBufferView\", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };\n }\n return value;\n }\n function __decodeCodemodeValue(value) {\n if (!value || typeof value !== \"object\" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== \"string\") return value;\n const bytes = __base64ToBytes(value.data);\n if (value[__CODEMODE_BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n return bytes;\n }\n function __stringifyForCodemode(value) {\n return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));\n }\n function __parseForCodemode(json) {\n return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));\n }\n`;\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n\n /**\n * When true, tools accept positional args instead of a single object arg.\n * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.\n *\n * Default tools use single-object args: `codemode.search({ query: \"test\" })`\n * Positional tools use normal args: `state.readFile(\"/path\")`\n */\n positionalArgs?: boolean;\n}\n\n// ── ToolDispatcher ────────────────────────────────────────────────────\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n #positionalArgs: boolean;\n\n constructor(\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>,\n positionalArgs = false\n ) {\n super();\n this.#fns = fns;\n this.#positionalArgs = positionalArgs;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return stringifyForCodemode({ error: `Tool \"${name}\" not found` });\n }\n try {\n if (this.#positionalArgs) {\n const args = argsJson ? parseForCodemode(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return stringifyForCodemode({ result });\n }\n const args = argsJson ? parseForCodemode(argsJson) : {};\n const result = await fn(args);\n return stringifyForCodemode({ result });\n } catch (err) {\n return stringifyForCodemode({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// ── DynamicWorkerExecutor ─────────────────────────────────────────────\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n /**\n * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes\n * ToolDispatchers (one per namespace) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n #modules: Record<string, string>;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n const { \"executor.js\": _, ...safeModules } = options.modules ?? {};\n this.#modules = safeModules;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\n \"__dispatchers\",\n \"__logs\",\n \"__CODEMODE_BINARY_TAG\",\n \"__bytesToBase64\",\n \"__base64ToBytes\",\n \"__encodeCodemodeValue\",\n \"__decodeCodemodeValue\",\n \"__stringifyForCodemode\",\n \"__parseForCodemode\"\n ]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map((p) => {\n if (p.positionalArgs) {\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n }\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args ?? {}));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n });\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n SANDBOX_CODEC,\n ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\n // Sanitize fn keys so raw tool names (e.g. \"github.list-issues\") become\n // valid JS identifiers (e.g. \"github_list_issues\") on the proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(\n sanitizedFns,\n provider.positionalArgs\n );\n }\n\n const worker = this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"executor.js\",\n modules: {\n ...this.#modules,\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\n\n if (response.error) {\n return { result: undefined, error: response.error, logs: response.logs };\n }\n\n return { result: response.result, logs: response.logs };\n }\n}\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,aAAa;AAOnB,SAAS,cAAc,OAA2B;CAChD,IAAI,SAAS;CACb,MAAM,YAAY;CAClB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,YAAY,KAAK,WACzC,UAAU,OAAO,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EH,eAAe,IAAI,eAAe,KAAK;IACvC,aAAa,iBAAiB;;GAEhC,YAAY,SAAS,QAAQ,IAAI,eAC/B,cACA,SAAS,eACV;;EAqBH,MAAM,WAAW,MAlBF,KAAKD,QAAQ,IAAI,YAAY,OAAO,YAAY,WAAW;GACxE,mBAAmB;GACnB,oBAAoB,CAAC,gBAAgB;GACrC,YAAY;GACZ,SAAS;IACP,GAAG,KAAKG;IACR,eAAe;IAChB;GACD,gBAAgB,KAAKD;GACtB,EAEwB,CAAC,eAOO,CAAC,SAAS,YAAY;EAEvD,IAAI,SAAS,OACX,OAAO;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;EAG1E,OAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
1
+ {"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound","#modules"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\nexport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\n\nconst BINARY_TAG = \"__codemode_binary_v1__\";\n\ntype EncodedBinary = {\n [BINARY_TAG]: \"Uint8Array\" | \"ArrayBuffer\" | \"ArrayBufferView\";\n data: string;\n};\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength))\n );\n }\n return btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nfunction encodeCodemodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { [BINARY_TAG]: \"Uint8Array\", data: bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return {\n [BINARY_TAG]: \"ArrayBuffer\",\n data: bytesToBase64(new Uint8Array(value))\n };\n }\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return {\n [BINARY_TAG]: \"ArrayBufferView\",\n data: bytesToBase64(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n )\n };\n }\n return value;\n}\n\nfunction decodeCodemodeValue(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || !(BINARY_TAG in value)) {\n return value;\n }\n const encoded = value as EncodedBinary;\n if (typeof encoded.data !== \"string\") return value;\n const bytes = base64ToBytes(encoded.data);\n if (encoded[BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength\n );\n }\n return bytes;\n}\n\nfunction stringifyForCodemode(value: unknown): string {\n return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));\n}\n\nfunction parseForCodemode(json: string): unknown {\n return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));\n}\n\nconst SANDBOX_CODEC = String.raw`\n const __CODEMODE_BINARY_TAG = \"__codemode_binary_v1__\";\n function __bytesToBase64(bytes) {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));\n }\n return btoa(binary);\n }\n function __base64ToBytes(b64) {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n function __encodeCodemodeValue(value) {\n if (value instanceof Uint8Array) {\n return { [__CODEMODE_BINARY_TAG]: \"Uint8Array\", data: __bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBuffer\", data: __bytesToBase64(new Uint8Array(value)) };\n }\n if (ArrayBuffer.isView(value)) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBufferView\", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };\n }\n return value;\n }\n function __decodeCodemodeValue(value) {\n if (!value || typeof value !== \"object\" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== \"string\") return value;\n const bytes = __base64ToBytes(value.data);\n if (value[__CODEMODE_BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n return bytes;\n }\n function __stringifyForCodemode(value) {\n return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));\n }\n function __parseForCodemode(json) {\n return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));\n }\n`;\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n}\n\n// ── ToolDispatcher ────────────────────────────────────────────────────\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>) {\n super();\n this.#fns = fns;\n }\n\n async call(name: string, argsJson?: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return stringifyForCodemode({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? parseForCodemode(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return stringifyForCodemode({ result });\n } catch (err) {\n return stringifyForCodemode({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// ── DynamicWorkerExecutor ─────────────────────────────────────────────\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n /**\n * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes\n * ToolDispatchers (one per namespace) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n #modules: Record<string, string>;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n const { \"executor.js\": _, ...safeModules } = options.modules ?? {};\n this.#modules = safeModules;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\n \"__dispatchers\",\n \"__logs\",\n \"__CODEMODE_BINARY_TAG\",\n \"__bytesToBase64\",\n \"__base64ToBytes\",\n \"__encodeCodemodeValue\",\n \"__decodeCodemodeValue\",\n \"__stringifyForCodemode\",\n \"__parseForCodemode\"\n ]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map(\n (p) =>\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n SANDBOX_CODEC,\n ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\n // Sanitize fn keys so raw tool names (e.g. \"github.list-issues\") become\n // valid JS identifiers (e.g. \"github_list_issues\") on the proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(sanitizedFns);\n }\n\n const worker = this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"executor.js\",\n modules: {\n ...this.#modules,\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\n\n if (response.error) {\n return { result: undefined, error: response.error, logs: response.logs };\n }\n\n return { result: response.result, logs: response.logs };\n }\n}\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,aAAa;AAOnB,SAAS,cAAc,OAA2B;CAChD,IAAI,SAAS;CACb,MAAM,YAAY;CAClB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,YAAY,KAAK,WACzC,UAAU,OAAO,aACf,GAAG,MAAM,SAAS,GAAG,KAAK,IAAI,IAAI,WAAW,MAAM,UAAU,CAAC,CAChE;CAEF,OAAO,KAAK,MAAM;AACpB;AAEA,SAAS,cAAc,KAAyB;CAC9C,MAAM,SAAS,KAAK,GAAG;CACvB,MAAM,QAAQ,IAAI,WAAW,OAAO,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AAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;EAAK;EAGzE,OAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;EAAK;CACxD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"json-schema-types-CVt4X9cw.js","names":[],"sources":["../src/normalize.ts","../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n","const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\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 inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramLines) {\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 codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MAAM,qEAAO;CAChC,OAAO,QAAQ,MAAM,KAAK;;AAG5B,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,MAAM,CAAC;CAC5C,IAAI,CAAC,QAAQ,MAAM,EAAE,OAAO;CAE5B,MAAM,SAAS,QAAQ,MAAM;CAE7B,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;GACb,CAAC;EAGF,IAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS;OAClC,IAAI,KAAK,GAAiC,WAC/C,SAAS,2BAA2B,OAAO;;EAItD,IACE,IAAI,KAAK,WAAW,KACpB,IAAI,KAAK,GAAG,SAAS,4BACrB;GACA,MAAM,OAAQ,IAAI,KAAK,GAAsC;GAC7D,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,IAAI;GAIhD,IACE,KAAK,SAAS,yBACd,CAAE,KAAmC,IAErC,OAAO,0BAA0B,MAAM;GAEzC,IACE,KAAK,SAAS,sBACd,CAAE,KAAgC,IAElC,OAAO,0BAA0B,MAAM;GAGzC,OAAO,cAAc,MAAM;;EAI7B,IAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS,uBAGhD,OAAO,kBAAkB,OAAO,WAFrB,IAAI,KAAK,GACJ,IAAI,QAAQ,KACoB;EAIlD,MAAM,OAAO,IAAI,KAAK,IAAI,KAAK,SAAS;EACxC,IAAI,MAAM,SAAS,uBAAuB;GACxC,MAAM,WAAW;GAMjB,OAAO,kBALQ,OAAO,MAAM,GAAG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/B,IAAI,KAAK,aAAa,MAAM,EAC1B,WAAW,KACT,YAAY,KAAK,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,CAC5D;QAED,WAAW,KAAK,YAAY,SAAS,CAAC;GAExC,KAAK,MAAM,MAAM,YACf,WAAW,KAAK,YAAY,GAAG,QAAQ,UAAU,IAAI,CAAC,CAAC;GAGzD,MAAM,YAAY,WAAW,KAAK,MAAM,QAAQ,IAAI,CAAC,KAAK,KAAK;GAC/D,kBAAkB,YAAY,UAAU;GACxC,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;GACpF,kBAAkB;UACZ;GACN,kBAAkB,UAAU,SAAS;GACrC,kBAAkB,UAAU,SAAS;GAErC,kBAAkB,iBAAiB,YAAY,SAAS,CAAC;GACzD,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;GACpF,kBAAkB;;;CAItB,iBAAiB,8BAA8B,eAAe;CAE9D,OAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
1
+ {"version":3,"file":"json-schema-types-CVt4X9cw.js","names":[],"sources":["../src/normalize.ts","../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n","const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\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 inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramLines) {\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 codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MAAM,oEAAM;CAC/B,OAAO,QAAQ,MAAM,KAAK;AAC5B;AAEA,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,KAAK,CAAC;CAC3C,IAAI,CAAC,QAAQ,KAAK,GAAG,OAAO;CAE5B,MAAM,SAAS,QAAQ,KAAK;CAE5B,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;EACd,CAAC;EAGD,IAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS;OAClC,IAAI,KAAK,GAAiC,WAC/C,SAAS,2BAA2B,OAAO;EAAA;EAItD,IACE,IAAI,KAAK,WAAW,KACpB,IAAI,KAAK,GAAG,SAAS,4BACrB;GACA,MAAM,OAAQ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B;EACpB;CACF;CAEA,iBAAiB,8BAA8B,eAAe;CAE9D,OAAO;EACP,eAAe;EACf,eAAe;IACb,KAAK;AACT"}
package/dist/mcp.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { s as Executor } from "./executor-BWtTiHBV.js";
1
+ import { s as Executor } from "./executor-BRm90XJT.js";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
 
4
4
  //#region src/mcp.d.ts
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\nconst CHARS_PER_TOKEN = 4;\nconst MAX_TOKENS = 6000;\nconst MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\nconst TRUNCATION_FOOTER_PREFIX = `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~`;\nconst MAX_SANDBOX_TRUNCATED_CHARS = MAX_CHARS + 512;\n\nfunction truncateResponse(content: unknown): string {\n const text =\n typeof content === \"string\"\n ? content\n : (JSON.stringify(content, null, 2) ?? \"undefined\");\n\n if (text.length <= MAX_CHARS) {\n return text;\n }\n\n const truncated = text.slice(0, MAX_CHARS);\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n\n return `${truncated}\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;\n}\n\nfunction sandboxResponseText(content: unknown): string {\n if (\n typeof content === \"string\" &&\n content.length <= MAX_SANDBOX_TRUNCATED_CHARS &&\n content.slice(MAX_CHARS).startsWith(TRUNCATION_FOOTER_PREFIX)\n ) {\n return content;\n }\n return truncateResponse(content);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_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\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client({ name: \"codemode-proxy\", version: \"1.0.0\" });\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n request: (options: RequestOptions) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n`;\n\nconst SEARCH_TYPES = `${SPEC_TYPES}\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n${SPEC_TYPES}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\nfunction createOpenApiSandboxCode(\n code: string,\n spec: Record<string, unknown>,\n includeRequest: boolean\n): string {\n const normalized = normalizeCode(code);\n const specJson = JSON.stringify(spec).replace(/</g, \"\\\\u003c\");\n const requestFn = includeRequest\n ? `request: async (options) => await __openapiHost.request(options)`\n : \"\";\n\n return `async () => {\nconst __rawSpec = ${specJson};\nconst __refCache = new Map();\nconst __cloneResolvedRef = (value) => structuredClone(value);\nconst __resolveRefs = (obj, root, seen = new Set()) => {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));\n\n if (Object.prototype.hasOwnProperty.call(obj, \"$ref\") && typeof obj.$ref === \"string\") {\n const ref = obj.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return obj;\n if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved = root;\n for (const part of parts) resolved = resolved?.[part];\n const result = __resolveRefs(resolved, root, seen);\n seen.delete(ref);\n __refCache.set(ref, result);\n return __cloneResolvedRef(result);\n }\n\n const result = {};\n for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);\n return result;\n};\nlet __resolvedSpec;\nconst __truncateResponse = (content) => {\n const text = typeof content === \"string\" ? content : (JSON.stringify(content, null, 2) ?? \"undefined\");\n if (text.length <= ${MAX_CHARS}) return text;\n const truncated = text.slice(0, ${MAX_CHARS});\n const estimatedTokens = Math.ceil(text.length / ${CHARS_PER_TOKEN});\n return truncated + \"\\\\n\\\\n${TRUNCATION_MARKER}\\\\nResponse was ~\" + estimatedTokens.toLocaleString() + \" tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.\";\n};\nconst codemode = {\n spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\\n ${requestFn}` : \"\"}\n};\nreturn __truncateResponse(await (${normalized})());\n}`;\n}\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const spec = options.spec;\n\n const server = new McpServer({ name, version });\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.\n\nTypes:\n${SEARCH_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, false),\n []\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) => requestFn(args as RequestOptions)\n }\n }\n ]\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAC/B,MAAM,oBAAoB;AAC1B,M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M;KAAiB,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;CAED,OAAO"}
1
+ {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\nconst CHARS_PER_TOKEN = 4;\nconst MAX_TOKENS = 6000;\nconst MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\nconst TRUNCATION_FOOTER_PREFIX = `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~`;\nconst MAX_SANDBOX_TRUNCATED_CHARS = MAX_CHARS + 512;\n\nfunction truncateResponse(content: unknown): string {\n const text =\n typeof content === \"string\"\n ? content\n : (JSON.stringify(content, null, 2) ?? \"undefined\");\n\n if (text.length <= MAX_CHARS) {\n return text;\n }\n\n const truncated = text.slice(0, MAX_CHARS);\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n\n return `${truncated}\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;\n}\n\nfunction sandboxResponseText(content: unknown): string {\n if (\n typeof content === \"string\" &&\n content.length <= MAX_SANDBOX_TRUNCATED_CHARS &&\n content.slice(MAX_CHARS).startsWith(TRUNCATION_FOOTER_PREFIX)\n ) {\n return content;\n }\n return truncateResponse(content);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_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\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client({ name: \"codemode-proxy\", version: \"1.0.0\" });\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n request: (options: RequestOptions) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n`;\n\nconst SEARCH_TYPES = `${SPEC_TYPES}\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n${SPEC_TYPES}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\nfunction createOpenApiSandboxCode(\n code: string,\n spec: Record<string, unknown>,\n includeRequest: boolean\n): string {\n const normalized = normalizeCode(code);\n const specJson = JSON.stringify(spec).replace(/</g, \"\\\\u003c\");\n const requestFn = includeRequest\n ? `request: async (options) => await __openapiHost.request(options)`\n : \"\";\n\n return `async () => {\nconst __rawSpec = ${specJson};\nconst __refCache = new Map();\nconst __cloneResolvedRef = (value) => structuredClone(value);\nconst __resolveRefs = (obj, root, seen = new Set()) => {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));\n\n if (Object.prototype.hasOwnProperty.call(obj, \"$ref\") && typeof obj.$ref === \"string\") {\n const ref = obj.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return obj;\n if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved = root;\n for (const part of parts) resolved = resolved?.[part];\n const result = __resolveRefs(resolved, root, seen);\n seen.delete(ref);\n __refCache.set(ref, result);\n return __cloneResolvedRef(result);\n }\n\n const result = {};\n for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);\n return result;\n};\nlet __resolvedSpec;\nconst __truncateResponse = (content) => {\n const text = typeof content === \"string\" ? content : (JSON.stringify(content, null, 2) ?? \"undefined\");\n if (text.length <= ${MAX_CHARS}) return text;\n const truncated = text.slice(0, ${MAX_CHARS});\n const estimatedTokens = Math.ceil(text.length / ${CHARS_PER_TOKEN});\n return truncated + \"\\\\n\\\\n${TRUNCATION_MARKER}\\\\nResponse was ~\" + estimatedTokens.toLocaleString() + \" tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.\";\n};\nconst codemode = {\n spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\\n ${requestFn}` : \"\"}\n};\nreturn __truncateResponse(await (${normalized})());\n}`;\n}\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const spec = options.spec;\n\n const server = new McpServer({ name, version });\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.\n\nTypes:\n${SEARCH_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, false),\n []\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) => requestFn(args as RequestOptions)\n }\n }\n ]\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAC/B,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B,OAAO,kBAAkB;AAC1D,MAAM,8BAA8B,YAAY;AAEhD,SAAS,iBAAiB,SAA0B;CAClD,MAAM,OACJ,OAAO,YAAY,WACf,UACC,KAAK,UAAU,SAAS,MAAM,CAAC,KAAK;CAE3C,IAAI,KAAK,UAAU,WACjB,OAAO;CAMT,OAAO,GAHW,KAAK,MAAM,GAAG,SA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oDAAoD,EAClE;CACF,GACA,OAAO,EAAE,WAAW;EAClB,IAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAC5B,yBAAyB,MAAM,MAAM,KAAK,GAC1C,CAAC,CACH;GACA,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;IAAQ,CAC1D;IACA,SAAS;GACX;GAEF,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,oBAAoB,OAAO,MAAM;GAAE,CACpE,EACF;EACF,SAAS,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,KAAK;IAAI,CAChE;IACA,SAAS;GACX;EACF;CACF,CACF;CAGA,MAAM,qBAAqB;;;EAG3B,cAAc;;;;;;;GAOb,cAAc,OAAO,gBAAgB;CAEtC,OAAO,aACL,WACA;EACE,aAAa;EACb,aAAa,EACX,MAAM,EAAE,OAAO,EAAE,SAAS,4CAA4C,EACxE;CACF,GACA,OAAO,EAAE,WAAW;EAClB,IAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAC5B,yBAAyB,MAAM,MAAM,IAAI,GACzC,CACE;IACE,MAAM;IACN,KAAK,EACH,UAAU,SAAkB,UAAU,IAAsB,EAC9D;GACF,CACF,CACF;GACA,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;IAAQ,CAC1D;IACA,SAAS;GACX;GAEF,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,oBAAoB,OAAO,MAAM;GAAE,CACpE,EACF;EACF,SAAS,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,KAAK;IAAI,CAChE;IACA,SAAS;GACX;EACF;CACF,CACF;CAEA,OAAO;AACT"}
@@ -31,14 +31,12 @@ function extractFns(tools) {
31
31
  * Import from `@cloudflare/codemode/ai` for the schema-validating version.
32
32
  */
33
33
  function resolveProvider(provider) {
34
- const resolved = {
34
+ return {
35
35
  name: provider.name ?? "codemode",
36
36
  fns: extractFns(filterTools(provider.tools))
37
37
  };
38
- if (provider.positionalArgs) resolved.positionalArgs = true;
39
- return resolved;
40
38
  }
41
39
  //#endregion
42
40
  export { filterTools as n, resolveProvider as r, extractFns as t };
43
41
 
44
- //# sourceMappingURL=resolve-BU1FGVYs.js.map
42
+ //# sourceMappingURL=resolve-DdyeEp3l.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-BU1FGVYs.js","names":[],"sources":["../src/resolve.ts"],"sourcesContent":["/**\n * Framework-agnostic tool resolution.\n *\n * Extracts execute functions from tool records and resolves ToolProviders\n * into ResolvedProviders — no dependency on the AI SDK or Zod.\n *\n * The AI SDK entry point (`./ai`) layers on schema validation via `asSchema`.\n */\n\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\n\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return t.needsApproval === true || typeof t.needsApproval === \"function\";\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nexport function filterTools(tools: ToolProviderTools): ToolProviderTools {\n const filtered: Record<string, unknown> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n filtered[name] = t;\n }\n }\n return filtered as ToolProviderTools;\n}\n\n/**\n * Extract execute functions from tools, keyed by name.\n * This is the base version — no schema validation.\n * The AI SDK entry point overrides this with `asSchema`-based validation.\n */\nexport function 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 fns[name] = execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`.\n *\n * This version does NOT perform schema validation on inputs.\n * Import from `@cloudflare/codemode/ai` for the schema-validating version.\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"],"mappings":";AAeA,SAAS,iBAAiB,GAAqC;CAC7D,OAAO,EAAE,kBAAkB,QAAQ,OAAO,EAAE,kBAAkB;;;;;AAMhE,SAAgB,YAAY,OAA6C;CACvE,MAAM,WAAoC,EAAE;CAC5C,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAC3C,IAAI,CAAC,iBAAiB,EAA6B,EACjD,SAAS,QAAQ;CAGrB,OAAO;;;;;;;AAQT,SAAgB,WACd,OAC0D;CAC1D,MAAM,MAAgE,EAAE;CAExE,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAAE;EAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH,KAAA;EACN,IAAI,SACF,IAAI,QAAQ;;CAIhB,OAAO;;;;;;;;;AAUT,SAAgB,gBAAgB,UAA0C;CAGxE,MAAM,WAA6B;EAAE,MAFxB,SAAS,QAAQ;EAEa,KAAK,WAD/B,YAAY,SAAS,MAC6B,CAAC;EAAE;CACtE,IAAI,SAAS,gBAAgB,SAAS,iBAAiB;CACvD,OAAO"}
1
+ {"version":3,"file":"resolve-DdyeEp3l.js","names":[],"sources":["../src/resolve.ts"],"sourcesContent":["/**\n * Framework-agnostic tool resolution.\n *\n * Extracts execute functions from tool records and resolves ToolProviders\n * into ResolvedProviders — no dependency on the AI SDK or Zod.\n *\n * The AI SDK entry point (`./ai`) layers on schema validation via `asSchema`.\n */\n\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\n\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return t.needsApproval === true || typeof t.needsApproval === \"function\";\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nexport function filterTools(tools: ToolProviderTools): ToolProviderTools {\n const filtered: Record<string, unknown> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n filtered[name] = t;\n }\n }\n return filtered as ToolProviderTools;\n}\n\n/**\n * Extract execute functions from tools, keyed by name.\n * This is the base version — no schema validation.\n * The AI SDK entry point overrides this with `asSchema`-based validation.\n */\nexport function 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 fns[name] = execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`.\n *\n * This version does NOT perform schema validation on inputs.\n * Import from `@cloudflare/codemode/ai` for the schema-validating version.\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"],"mappings":";AAeA,SAAS,iBAAiB,GAAqC;CAC7D,OAAO,EAAE,kBAAkB,QAAQ,OAAO,EAAE,kBAAkB;AAChE;;;;AAKA,SAAgB,YAAY,OAA6C;CACvE,MAAM,WAAoC,CAAC;CAC3C,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,KAAK,GAC1C,IAAI,CAAC,iBAAiB,CAA4B,GAChD,SAAS,QAAQ;CAGrB,OAAO;AACT;;;;;;AAOA,SAAgB,WACd,OAC0D;CAC1D,MAAM,MAAgE,CAAC;CAEvE,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,KAAK,GAAG;EAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH,KAAA;EACN,IAAI,SACF,IAAI,QAAQ;CAEhB;CAEA,OAAO;AACT;;;;;;;;AASA,SAAgB,gBAAgB,UAA0C;CAIxE,OAAO;EAD8B,MAFxB,SAAS,QAAQ;EAEa,KAAK,WAD/B,YAAY,SAAS,KAC4B,CAAC;CACrD;AAChB"}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  c as ResolvedProvider,
3
3
  i as ToolProvider
4
- } from "./executor-BWtTiHBV.js";
4
+ } from "./executor-BRm90XJT.js";
5
5
 
6
6
  //#region src/resolve.d.ts
7
7
  /**
@@ -14,4 +14,4 @@ import {
14
14
  declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
15
15
  //#endregion
16
16
  export { resolveProvider as t };
17
- //# sourceMappingURL=resolve-9VUW-grI.d.ts.map
17
+ //# sourceMappingURL=resolve-DtfaKmms.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-code-5x8S5YWt.js","names":[],"sources":["../src/run-code.ts"],"sourcesContent":["import type { CodeOutput } from \"./shared\";\nimport type { Executor, ResolvedProvider } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nexport async function runCode({\n code,\n executor,\n providers\n}: {\n code: string;\n executor: Executor;\n providers: ResolvedProvider[];\n}): Promise<CodeOutput> {\n const executeResult = await executor.execute(normalizeCode(code), providers);\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n return executeResult.logs?.length\n ? { result: executeResult.result, logs: executeResult.logs }\n : { result: executeResult.result };\n}\n"],"mappings":";;AAIA,eAAsB,QAAQ,EAC5B,MACA,UACA,aAKsB;CACtB,MAAM,gBAAgB,MAAM,SAAS,QAAQ,cAAc,KAAK,EAAE,UAAU;CAE5E,IAAI,cAAc,OAAO;EACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;EACJ,MAAM,IAAI,MAAM,0BAA0B,cAAc,QAAQ,SAAS;;CAG3E,OAAO,cAAc,MAAM,SACvB;EAAE,QAAQ,cAAc;EAAQ,MAAM,cAAc;EAAM,GAC1D,EAAE,QAAQ,cAAc,QAAQ"}
1
+ {"version":3,"file":"run-code-5x8S5YWt.js","names":[],"sources":["../src/run-code.ts"],"sourcesContent":["import type { CodeOutput } from \"./shared\";\nimport type { Executor, ResolvedProvider } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nexport async function runCode({\n code,\n executor,\n providers\n}: {\n code: string;\n executor: Executor;\n providers: ResolvedProvider[];\n}): Promise<CodeOutput> {\n const executeResult = await executor.execute(normalizeCode(code), providers);\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n return executeResult.logs?.length\n ? { result: executeResult.result, logs: executeResult.logs }\n : { result: executeResult.result };\n}\n"],"mappings":";;AAIA,eAAsB,QAAQ,EAC5B,MACA,UACA,aAKsB;CACtB,MAAM,gBAAgB,MAAM,SAAS,QAAQ,cAAc,IAAI,GAAG,SAAS;CAE3E,IAAI,cAAc,OAAO;EACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,IAAI,MACpD;EACJ,MAAM,IAAI,MAAM,0BAA0B,cAAc,QAAQ,QAAQ;CAC1E;CAEA,OAAO,cAAc,MAAM,SACvB;EAAE,QAAQ,cAAc;EAAQ,MAAM,cAAc;CAAK,IACzD,EAAE,QAAQ,cAAc,OAAO;AACrC"}
@@ -2,7 +2,7 @@ import {
2
2
  a as ToolProviderTools,
3
3
  i as ToolProvider,
4
4
  s as Executor
5
- } from "./executor-BWtTiHBV.js";
5
+ } from "./executor-BRm90XJT.js";
6
6
 
7
7
  //#region src/shared.d.ts
8
8
  declare const DEFAULT_DESCRIPTION =
@@ -37,4 +37,4 @@ export {
37
37
  CreateCodeToolOptions as r,
38
38
  CodeInput as t
39
39
  };
40
- //# sourceMappingURL=shared-CcZcDoiO.d.ts.map
40
+ //# sourceMappingURL=shared-TyFN6W7_.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-xjl2irqK.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;CACzB,OAAO,MAAM,QAAQ,MAAM;;;;;;AAO7B,SAAgB,mBACd,OACgB;CAChB,IAAI,oBAAoB,MAAM,EAC5B,OAAO;CAET,OAAO,CAAC,EAAE,OAAO,CAAC"}
1
+ {"version":3,"file":"shared-xjl2irqK.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;CACzB,OAAO,MAAM,QAAQ,KAAK;AAC5B;;;;;AAMA,SAAgB,mBACd,OACgB;CAChB,IAAI,oBAAoB,KAAK,GAC3B,OAAO;CAET,OAAO,CAAC,EAAE,MAAM,CAAC;AACnB"}
@@ -1,12 +1,12 @@
1
- import { i as ToolProvider } from "./executor-BWtTiHBV.js";
1
+ import { i as ToolProvider } from "./executor-BRm90XJT.js";
2
2
  import {
3
3
  a as normalizeProviders,
4
4
  i as DEFAULT_DESCRIPTION,
5
5
  n as CodeOutput,
6
6
  r as CreateCodeToolOptions,
7
7
  t as CodeInput
8
- } from "./shared-CcZcDoiO.js";
9
- import { t as resolveProvider } from "./resolve-9VUW-grI.js";
8
+ } from "./shared-TyFN6W7_.js";
9
+ import { t as resolveProvider } from "./resolve-DtfaKmms.js";
10
10
  import { ServerTool, Tool } from "@tanstack/ai";
11
11
 
12
12
  //#region src/tanstack-ai.d.ts
@@ -1,5 +1,5 @@
1
1
  import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase } from "./json-schema-types-CVt4X9cw.js";
2
- import { n as filterTools, r as resolveProvider, t as extractFns } from "./resolve-BU1FGVYs.js";
2
+ import { n as filterTools, r as resolveProvider, t as extractFns } from "./resolve-DdyeEp3l.js";
3
3
  import { t as runCode } from "./run-code-5x8S5YWt.js";
4
4
  import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-xjl2irqK.js";
5
5
  import { z } from "zod";
@@ -161,12 +161,10 @@ function createCodeTool(options) {
161
161
  const filtered = filterTools(provider.tools);
162
162
  const types = provider.types ?? generateTypesFromRecord(filtered, providerName);
163
163
  typeBlocks.push(types);
164
- const resolved = {
164
+ resolvedProviders.push({
165
165
  name: providerName,
166
166
  fns: extractFns(filtered)
167
- };
168
- if (provider.positionalArgs) resolved.positionalArgs = true;
169
- resolvedProviders.push(resolved);
167
+ });
170
168
  }
171
169
  const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
172
170
  const executor = options.executor;
@@ -1 +1 @@
1
- {"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => t.needsApproval !== true && typeof t.needsApproval !== \"function\"\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n );\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\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,SAAS,SAAS,wBAAwB,UAAU,aAAa;EACnE,WAAW,KAAK,MAAM;EAEtB,MAAM,WAA6B;GACjC,MAAM;GACN,KAAK,WAAW,SAAS;GAC1B;EACD,IAAI,SAAS,gBAAgB,SAAS,iBAAiB;EACvD,kBAAkB,KAAK,SAAS;;CAGlC,MAAM,YAAY,WAAW,OAAO,QAAQ,CAAC,KAAK,OAAO;CACzD,MAAM,WAAW,QAAQ;CAazB,OANY,eAAe;EACzB,MAAM;EACN,cAPmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,UAKW;EACX,aAAa;EACd,CAES,CAAC,OAAO,OAAO,EAAE,WACzB,QAAQ;EAAE;EAAM;EAAU,WAAW;EAAmB,CAAC,CAC1D;;;;;;AAOH,SAAS,wBACP,OACA,WACQ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,CAAC,UAAU,SAAS,OAAO,QAAQ,MAAM,EAAE;EACpD,MAAM,WAAW,iBAAiB,SAAS;EAC3C,MAAM,WAAW,aAAa,SAAS;EACvC,MAAM,cACJ,iBAAiB,OACZ,KAAiC,cAClC,KAAA;EAEN,kBAAkB,UAAU,SAAS;EACrC,kBAAkB,UAAU,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,MAAM,GACjD,YAAY,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,GACtD,YAAY,SAAS;EAE3B,kBAAkB,iBAAiB,QAAQ;EAC3C,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;EACpF,kBAAkB;;CAGpB,iBAAiB,mBAAmB,UAAU,KAAK,eAAe;CAElE,OAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
1
+ {"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => t.needsApproval !== true && typeof t.needsApproval !== \"function\"\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n resolvedProviders.push({\n name: providerName,\n fns: extractFns(filtered)\n });\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n );\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,OAAO,EACP,KAAK,EAAE,aAAa,6CAA6C,CAAC,EACvE,CAAC;;;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;EAC1B,CAAC;CACH;CAEA,MAAM,YAAY,WAAW,OAAO,OAAO,EAAE,KAAK,MAAM;CACxD,MAAM,WAAW,QAAQ;CAazB,OANY,eAAe;EACzB,MAAM;EACN,cAPmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,SAKU;EACV,aAAa;CACf,CAES,EAAE,OAAO,OAAO,EAAE,WACzB,QAAQ;EAAE;EAAM;EAAU,WAAW;CAAkB,CAAC,CAC1D;AACF;;;;;AAMA,SAAS,wBACP,OACA,WACQ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,CAAC,UAAU,SAAS,OAAO,QAAQ,KAAK,GAAG;EACpD,MAAM,WAAW,iBAAiB,QAAQ;EAC1C,MAAM,WAAW,aAAa,QAAQ;EACtC,MAAM,cACJ,iBAAiB,OACZ,KAAiC,cAClC,KAAA;EAEN,kBAAkB,UAAU,SAAS;EACrC,kBAAkB,UAAU,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,KAAK,IAChD,YAAY,YAAY,KAAK,EAAE,QAAQ,UAAU,GAAG,CAAC,IACrD,YAAY,QAAQ;EAE1B,kBAAkB,iBAAiB,QAAQ;EAC3C,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;EACpF,kBAAkB;CACpB;CAEA,iBAAiB,mBAAmB,UAAU,KAAK,eAAe;CAElE,OAAO;EACP,eAAe;EACf,eAAe;IACb,KAAK;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.3.6",
3
+ "version": "0.3.7",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -17,8 +17,8 @@
17
17
  "devDependencies": {
18
18
  "@modelcontextprotocol/sdk": "1.29.0",
19
19
  "@playwright/test": "^1.60.0",
20
- "@tanstack/ai": "^0.16.0",
21
- "ai": "^6.0.180",
20
+ "@tanstack/ai": "^0.18.0",
21
+ "ai": "^6.0.185",
22
22
  "vitest": "4.1.6",
23
23
  "zod": "^4.4.3"
24
24
  },