@cloudflare/codemode 0.4.4 → 0.5.0

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
@@ -60,7 +60,7 @@ const codemode = createCodeTool({ tools, executor });
60
60
  // 4. Use it with streamText — the LLM writes code that calls your tools
61
61
  const result = streamText({
62
62
  model,
63
- system: "You are a helpful assistant.",
63
+ instructions: "You are a helpful assistant.",
64
64
  messages,
65
65
  tools: { codemode }
66
66
  });
@@ -577,7 +577,7 @@ The user sends a message, the agent passes it to an LLM with the codemode tool,
577
577
  import { Agent } from "agents";
578
578
  import { createCodeTool } from "@cloudflare/codemode/ai";
579
579
  import { DynamicWorkerExecutor } from "@cloudflare/codemode";
580
- import { streamText, convertToModelMessages, stepCountIs } from "ai";
580
+ import { streamText, convertToModelMessages, isStepCount } from "ai";
581
581
 
582
582
  export class MyAgent extends Agent<Env, State> {
583
583
  async onChatMessage() {
@@ -587,10 +587,10 @@ export class MyAgent extends Agent<Env, State> {
587
587
 
588
588
  const result = streamText({
589
589
  model,
590
- system: "You are a helpful assistant.",
590
+ instructions: "You are a helpful assistant.",
591
591
  messages: await convertToModelMessages(this.state.messages),
592
592
  tools: { codemode },
593
- stopWhen: stepCountIs(10)
593
+ stopWhen: isStepCount(10)
594
594
  });
595
595
 
596
596
  // Stream response back to client...
package/dist/ai.js CHANGED
@@ -288,7 +288,7 @@ var ToolSetConnector = class extends CodemodeConnector {
288
288
  const needsApproval = t.needsApproval;
289
289
  const requiresApproval = needsApproval !== void 0 && needsApproval !== false;
290
290
  out[name] = {
291
- description: t.description,
291
+ description: typeof t.description === "function" ? void 0 : t.description,
292
292
  inputSchema: schema?.jsonSchema,
293
293
  ...requiresApproval ? { requiresApproval: true } : {},
294
294
  execute: schema?.validate ? async (args) => {
package/dist/ai.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ai.js","names":["#options","#warnedSkipped","#executableTools"],"sources":["../src/tool-types.ts","../src/tool.ts","../src/connectors/toolset.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","/**\n * ToolSetConnector — adapt an AI SDK `ToolSet` to the connector model.\n *\n * Each tool in the set becomes one connector tool under a single namespace\n * (default `\"tools\"`). Tools with `needsApproval` map to `requiresApproval`:\n * calling one pauses the run durably until the host approves\n * (`runtime.approve()`), then the run resumes where it stopped — the\n * runtime's pause/approve/resume flow, not the AI SDK's per-call approval.\n * A function-valued `needsApproval` cannot be evaluated against sandbox\n * arguments ahead of time, so it conservatively always requires approval.\n *\n * Lives in the `/ai` entry because schema handling (`asSchema`) needs the\n * `ai` peer dependency.\n */\nimport { asSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { generateTypes } from \"../tool-types\";\nimport { sanitizeToolName } from \"../utils\";\nimport { CodemodeConnector, type ConnectorTools } from \"./base\";\n\nexport interface ToolSetConnectorOptions {\n /**\n * The namespace the sandbox sees, e.g. `\"tools\"` → `tools.getWeather(...)`.\n * Defaults to `\"tools\"`. (`\"codemode\"` is reserved for the platform SDK.)\n */\n name?: string;\n /** Extra model guidance, surfaced with the connector's type block. */\n instructions?: string;\n /** The AI SDK tools to expose. */\n tools: ToolSet;\n}\n\nexport class ToolSetConnector extends CodemodeConnector {\n #options: ToolSetConnectorOptions;\n #warnedSkipped = false;\n\n constructor(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n ) {\n super(ctx, {});\n this.#options = options;\n }\n\n /**\n * Only tools with an `execute` function can run inside the sandbox.\n * Execute-less tools (client-side / provider-executed) are excluded from\n * both the runtime bindings and the generated types — advertising a method\n * the sandbox can't call would send the model down a dead end.\n */\n #executableTools(): ToolSet {\n const executable: ToolSet = {};\n const skipped: string[] = [];\n for (const [toolName, t] of Object.entries(this.#options.tools)) {\n if (\"execute\" in t && typeof t.execute === \"function\") {\n executable[toolName] = t;\n } else {\n skipped.push(toolName);\n }\n }\n if (skipped.length > 0 && !this.#warnedSkipped) {\n this.#warnedSkipped = true;\n console.warn(\n `[codemode] ToolSetConnector \"${this.name()}\" skipped tools without ` +\n `an execute function (client-side or provider-executed): ` +\n `${skipped.join(\", \")}. They are not callable from sandboxed code.`\n );\n }\n return executable;\n }\n\n override name(): string {\n return this.#options.name ?? \"tools\";\n }\n\n protected override instructions(): string | undefined {\n return this.#options.instructions;\n }\n\n protected override tools(): ConnectorTools {\n const out: ConnectorTools = {};\n const sources = new Map<string, string>();\n for (const [toolName, t] of Object.entries(this.#executableTools())) {\n const execute = t.execute as (args: unknown) => Promise<unknown>;\n\n const name = sanitizeToolName(toolName);\n const existing = sources.get(name);\n if (existing !== undefined) {\n throw new Error(\n `Tools \"${existing}\" and \"${toolName}\" on ${this.name()} both ` +\n `map to \"${name}\" — rename one of them.`\n );\n }\n sources.set(name, toolName);\n\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : (t as Record<string, unknown>).parameters;\n const schema =\n rawSchema != null\n ? asSchema(rawSchema as Parameters<typeof asSchema>[0])\n : undefined;\n\n // boolean `false` means no approval; `true` or a function (which can't\n // be pre-evaluated against sandbox args) gates the call behind the\n // runtime's durable pause/approve/resume flow.\n const needsApproval = (t as { needsApproval?: unknown }).needsApproval;\n const requiresApproval =\n needsApproval !== undefined && needsApproval !== false;\n\n out[name] = {\n description: t.description,\n inputSchema: schema?.jsonSchema as JSONSchema7 | undefined,\n ...(requiresApproval ? { requiresApproval: true } : {}),\n execute: 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 : (args: unknown) => execute(args)\n };\n }\n return out;\n }\n\n /**\n * Generate the sandbox type block from the original AI SDK schemas (Zod or\n * `jsonSchema()` wrappers) rather than the converted JSON Schema, preserving\n * field descriptions as `@param` lines. Restricted to the same executable\n * subset that `tools()` exposes, so the types never advertise a method the\n * sandbox can't call.\n */\n override async getTypeScriptTypes(): Promise<string> {\n return generateTypes(this.#executableTools(), this.name());\n }\n}\n\n/** Convenience constructor mirroring `stateConnector` / `new BrowserConnector`. */\nexport function toolSetConnector(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n): ToolS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,MAAM,mBACJ,kBAAkB,KAAA,KAAa,kBAAkB;GAEnD,IAAI,QAAQ;IACV,aAAa,EAAE;IACf,aAAa,QAAQ;IACrB,GAAI,mBAAmB,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACrD,SAAS,QAAQ,WACb,OAAO,SAAkB;KACvB,MAAM,SAAS,MAAM,OAAO,SAAU,IAAI;KAC1C,IAAI,CAAC,OAAO,SAAS,MAAM,OAAO;KAClC,OAAO,QAAQ,OAAO,KAAK;IAC7B,KACC,SAAkB,QAAQ,IAAI;GACrC;EACF;EACA,OAAO;CACT;;;;;;;;CASA,MAAe,qBAAsC;EACnD,OAAO,cAAc,KAAKA,iBAAiB,GAAG,KAAK,KAAK,CAAC;CAC3D;AACF;;AAGA,SAAgB,iBACd,KACA,SACkB;CAClB,OAAO,IAAI,iBAAiB,KAAK,OAAO;AAC1C"}
1
+ {"version":3,"file":"ai.js","names":["#options","#warnedSkipped","#executableTools"],"sources":["../src/tool-types.ts","../src/tool.ts","../src/connectors/toolset.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","/**\n * ToolSetConnector — adapt an AI SDK `ToolSet` to the connector model.\n *\n * Each tool in the set becomes one connector tool under a single namespace\n * (default `\"tools\"`). Tools with `needsApproval` map to `requiresApproval`:\n * calling one pauses the run durably until the host approves\n * (`runtime.approve()`), then the run resumes where it stopped — the\n * runtime's pause/approve/resume flow, not the AI SDK's per-call approval.\n * A function-valued `needsApproval` cannot be evaluated against sandbox\n * arguments ahead of time, so it conservatively always requires approval.\n *\n * Lives in the `/ai` entry because schema handling (`asSchema`) needs the\n * `ai` peer dependency.\n */\nimport { asSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { generateTypes } from \"../tool-types\";\nimport { sanitizeToolName } from \"../utils\";\nimport { CodemodeConnector, type ConnectorTools } from \"./base\";\n\nexport interface ToolSetConnectorOptions {\n /**\n * The namespace the sandbox sees, e.g. `\"tools\"` → `tools.getWeather(...)`.\n * Defaults to `\"tools\"`. (`\"codemode\"` is reserved for the platform SDK.)\n */\n name?: string;\n /** Extra model guidance, surfaced with the connector's type block. */\n instructions?: string;\n /** The AI SDK tools to expose. */\n tools: ToolSet;\n}\n\nexport class ToolSetConnector extends CodemodeConnector {\n #options: ToolSetConnectorOptions;\n #warnedSkipped = false;\n\n constructor(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n ) {\n super(ctx, {});\n this.#options = options;\n }\n\n /**\n * Only tools with an `execute` function can run inside the sandbox.\n * Execute-less tools (client-side / provider-executed) are excluded from\n * both the runtime bindings and the generated types — advertising a method\n * the sandbox can't call would send the model down a dead end.\n */\n #executableTools(): ToolSet {\n const executable: ToolSet = {};\n const skipped: string[] = [];\n for (const [toolName, t] of Object.entries(this.#options.tools)) {\n if (\"execute\" in t && typeof t.execute === \"function\") {\n executable[toolName] = t;\n } else {\n skipped.push(toolName);\n }\n }\n if (skipped.length > 0 && !this.#warnedSkipped) {\n this.#warnedSkipped = true;\n console.warn(\n `[codemode] ToolSetConnector \"${this.name()}\" skipped tools without ` +\n `an execute function (client-side or provider-executed): ` +\n `${skipped.join(\", \")}. They are not callable from sandboxed code.`\n );\n }\n return executable;\n }\n\n override name(): string {\n return this.#options.name ?? \"tools\";\n }\n\n protected override instructions(): string | undefined {\n return this.#options.instructions;\n }\n\n protected override tools(): ConnectorTools {\n const out: ConnectorTools = {};\n const sources = new Map<string, string>();\n for (const [toolName, t] of Object.entries(this.#executableTools())) {\n const execute = t.execute as (args: unknown) => Promise<unknown>;\n\n const name = sanitizeToolName(toolName);\n const existing = sources.get(name);\n if (existing !== undefined) {\n throw new Error(\n `Tools \"${existing}\" and \"${toolName}\" on ${this.name()} both ` +\n `map to \"${name}\" — rename one of them.`\n );\n }\n sources.set(name, toolName);\n\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : (t as Record<string, unknown>).parameters;\n const schema =\n rawSchema != null\n ? asSchema(rawSchema as Parameters<typeof asSchema>[0])\n : undefined;\n\n // boolean `false` means no approval; `true` or a function (which can't\n // be pre-evaluated against sandbox args) gates the call behind the\n // runtime's durable pause/approve/resume flow.\n const needsApproval = (t as { needsApproval?: unknown }).needsApproval;\n const requiresApproval =\n needsApproval !== undefined && needsApproval !== false;\n\n out[name] = {\n description:\n typeof t.description === \"function\" ? undefined : t.description,\n inputSchema: schema?.jsonSchema as JSONSchema7 | undefined,\n ...(requiresApproval ? { requiresApproval: true } : {}),\n execute: 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 : (args: unknown) => execute(args)\n };\n }\n return out;\n }\n\n /**\n * Generate the sandbox type block from the original AI SDK schemas (Zod or\n * `jsonSchema()` wrappers) rather than the converted JSON Schema, preserving\n * field descriptions as `@param` lines. Restricted to the same executable\n * subset that `tools()` exposes, so the types never advertise a method the\n * sandbox can't call.\n */\n override async getTypeScriptTypes(): Promise<string> {\n return generateTypes(this.#executableTools(), this.name());\n }\n}\n\n/** Convenience constructor mirroring `stateConnector` / `new BrowserConnector`. */\nexport function toolSetConnector(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n): ToolSetConnector {\n return new ToolSetConnector(ctx, options);\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,IA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-1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.4.4",
3
+ "version": "0.5.0",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -18,14 +18,14 @@
18
18
  "@modelcontextprotocol/sdk": "1.29.0",
19
19
  "@playwright/test": "^1.61.1",
20
20
  "@tanstack/ai": "0.38.0",
21
- "ai": "^6.0.202",
21
+ "ai": "^7.0.0",
22
22
  "vitest": "4.1.9",
23
23
  "zod": "^4.4.3"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "@modelcontextprotocol/sdk": "^1.25.0",
27
27
  "@tanstack/ai": ">=0.8.0 <1.0.0",
28
- "ai": "^6.0.0",
28
+ "ai": "^6.0.0 || ^7.0.0",
29
29
  "zod": "^4.0.0"
30
30
  },
31
31
  "peerDependenciesMeta": {