@cloudflare/codemode 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -336,7 +336,7 @@ import { Workspace } from "@cloudflare/shell";
336
336
  import { stateTools } from "@cloudflare/shell/workers";
337
337
 
338
338
  export class MyAgent extends Agent<Env> {
339
- workspace = new Workspace(this);
339
+ workspace = new Workspace({ sql: this.ctx.storage.sql });
340
340
 
341
341
  getCodemodeTool() {
342
342
  const executor = new DynamicWorkerExecutor({ loader: this.env.LOADER });
package/dist/ai.js CHANGED
@@ -211,10 +211,12 @@ function createCodeTool(options) {
211
211
  const filtered = filterTools(provider.tools);
212
212
  const types = provider.types ?? generateTypes(filtered, name);
213
213
  typeBlocks.push(types);
214
- resolvedProviders.push({
214
+ const resolved = {
215
215
  name,
216
216
  fns: extractFns(filtered)
217
- });
217
+ };
218
+ if (provider.positionalArgs) resolved.positionalArgs = true;
219
+ resolvedProviders.push(resolved);
218
220
  }
219
221
  const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
220
222
  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 { normalizeCode } from \"./normalize\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[name] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [stateTools(workspace), aiTools(myTools)],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n 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 const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n });\n}\n"],"mappings":";;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;AACrD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;AACjD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS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import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(\n tools: ToolDescriptors | ToolSet,\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[name] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [stateTools(workspace), aiTools(myTools)],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n });\n}\n"],"mappings":";;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;AACrD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;AACjD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS,oBACP,OACsC;AACtC,KAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AAExD,KAAI,gBAAgB,MAClB,QAAO;CAGT,MAAM,UAAU,OAAO,sBAAsB,MAAM;AACnD,MAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,MAAkC;AACpD,MAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,SAC9D,QAAO;;AAIX,QAAO;;;;;AAMT,SAAS,kBAAkB,SAAsC;AAC/D,KAAI,YAAY,QAAQ,OAAO,YAAY,SAAU,QAAO;AAE5D,KAAI,gBAAgB,QAClB,QAAQ,QAAwC;CAGlD,MAAM,UAAU,OAAO,sBAAsB,QAAQ;AACrD,MAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,QAAoC;AACtD,MAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,SAC9D,QAAQ,SAAyC;;AAIrD,QAAO;;;;;;AAOT,SAAS,oBAAoB,QAAyC;CACpE,MAAM,eAAuC,EAAE;CAE/C,MAAM,QAAS,OAA+C;AAC9D,KAAI,SAAS,OAAO,UAAU,UAAU;AACtC,OAAK,MAAM,CAAC,WAAW,gBAAgB,OAAO,QAAQ,MAAM,EAAE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QAAQ;AAOzB,QAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,UACD;EAIC,aAAa;EACb,SAAS,OAAO,EAAE,WAAW;GAC3B,MAAM,iBAAiB,cAAc,KAAK;GAE1C,MAAM,gBAAgB,MAAM,SAAS,QACnC,gBACA,kBACD;AAED,OAAI,cAAc,OAAO;IACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;AACJ,UAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;AACjE,OAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
@@ -160,10 +160,12 @@ function createCodeTool(options) {
160
160
  const filtered = filterTools(provider.tools);
161
161
  const types = provider.types ?? generateTypesFromRecord(filtered, providerName);
162
162
  typeBlocks.push(types);
163
- resolvedProviders.push({
163
+ const resolved = {
164
164
  name: providerName,
165
165
  fns: extractFns(filtered)
166
- });
166
+ };
167
+ if (provider.positionalArgs) resolved.positionalArgs = true;
168
+ resolvedProviders.push(resolved);
167
169
  }
168
170
  const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
169
171
  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 { normalizeCode } from \"./normalize\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => !(\"needsApproval\" in t && t.needsApproval != null)\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({ name: providerName, fns: extractFns(filtered) });\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n });\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,QAAQ,CACR,KAAK,EAAE,aAAa,8CAA8C,CAAC,EACvE,CAAC;;;;;A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AC,KAAK,OAAO;CACzD,MAAM,WAAW,QAAQ;AAazB,QANY,eAAe;EACzB,MAAM;EACN,cAPmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,UACD;EAKC,aAAa;EACd,CAAC,CAES,OAAO,OAAO,EAAE,WAAW;EACpC,MAAM,iBAAiB,cAAc,KAAK;EAE1C,MAAM,gBAAgB,MAAM,SAAS,QACnC,gBACA,kBACD;AAED,MAAI,cAAc,OAAO;GACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;AACJ,SAAM,IAAI,MAAM,0BAA0B,cAAc,QAAQ,SAAS;;EAG3E,MAAM,SAAqB;GAAE;GAAM,QAAQ,cAAc;GAAQ;AACjE,MAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,SAAO;GACP;;;;;;AAOJ,SAAS,wBACP,OACA,WACQ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;AAErB,MAAK,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;AAEN,oBAAkB,UAAU,SAAS;AACrC,oBAAkB,UAAU,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,MAAM,GACjD,YAAY,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,GACtD,YAAY,SAAS;AAE3B,oBAAkB,iBAAiB,QAAQ;AAC3C,oBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;AACpF,oBAAkB;;AAGpB,kBAAiB,mBAAmB,UAAU,KAAK,eAAe;AAElE,QAAO;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 { normalizeCode } from \"./normalize\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => !(\"needsApproval\" in t && t.needsApproval != null)\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n });\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,QAAQ,CACR,KAAK,EAAE,aAAa,8CAA8C,CAAC,EACvE,CAAC;;;;;AAMF,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,OAA6B;AACzE,KAAI,CAAC,UAAW,QAAO;AACvB,QAAO;;;;;;;;AAST,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;AAErB,MAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,KAAK;EAC5C,MAAM,WAAW,aAAa,SAAS;AAEvC,MAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,YAAY,GAC/B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,aAAa,GAChC;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBAAiB,GAAG,SAAS,OAAO,GACrD,QAAQ,SAAS;GAErB,MAAM,aAAa,mBACf,iBAAiB,kBAAkB,GAAG,SAAS,QAAQ,GACvD,QAAQ,SAAS;AAErB,qBAAkB,KAAK,UAAU,MAAM;AACvC,qBAAkB,KAAK,WAAW,MAAM;GAExC,MAAM,oBAAoB;AACxB,QAAI;AACF,SAAI,CAAC,iBAAiB,WAAY,QAAO,EAAE;AAC3C,YAAO,OAAO,QAAQ,gBAAgB,WAAW,CAC9C,QACE,GAAG,gBACF,cACA,OAAO,eAAe,YACrB,WAA2B,YAC/B,CACA,KACE,CAAC,WAAW,gBACX,gBAA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AAU,SAAS;AACrC,oBAAkB,UAAU,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,MAAM,GACjD,YAAY,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,GACtD,YAAY,SAAS;AAE3B,oBAAkB,iBAAiB,QAAQ;AAC3C,oBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;AACpF,oBAAkB;;AAGpB,kBAAiB,mBAAmB,UAAU,KAAK,eAAe;AAElE,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -18,8 +18,8 @@
18
18
  "@modelcontextprotocol/sdk": "1.26.0",
19
19
  "@playwright/test": "^1.58.2",
20
20
  "@tanstack/ai": "^0.8.1",
21
- "ai": "^6.0.134",
22
- "vitest": "4.1.0",
21
+ "ai": "^6.0.137",
22
+ "vitest": "4.1.1",
23
23
  "zod": "^4.3.6"
24
24
  },
25
25
  "peerDependencies": {