@cloudflare/codemode 0.5.4 → 0.5.6

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/mcp.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { l as Executor } from "./executor-DLwvEPC7.js";
1
+ import { l as Executor } from "./executor-xSJFaECq.js";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
4
4
  import {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  i as ToolProvider,
3
3
  u as ResolvedProvider
4
- } from "./executor-DLwvEPC7.js";
4
+ } from "./executor-xSJFaECq.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-BFB4vzhC.d.ts.map
17
+ //# sourceMappingURL=resolve-ClRJA8iy.d.ts.map
@@ -2,7 +2,7 @@ import {
2
2
  a as ToolProviderTools,
3
3
  i as ToolProvider,
4
4
  l as Executor
5
- } from "./executor-DLwvEPC7.js";
5
+ } from "./executor-xSJFaECq.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-B1Rs0ONk.d.ts.map
40
+ //# sourceMappingURL=shared-D5qepsss.d.ts.map
@@ -1,13 +1,13 @@
1
- import { i as ToolProvider } from "./executor-DLwvEPC7.js";
1
+ import { i as ToolProvider } from "./executor-xSJFaECq.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-B1Rs0ONk.js";
9
- import { t as resolveProvider } from "./resolve-BFB4vzhC.js";
10
- import { ServerTool, Tool } from "@tanstack/ai";
8
+ } from "./shared-D5qepsss.js";
9
+ import { t as resolveProvider } from "./resolve-ClRJA8iy.js";
10
+ import { SchemaInput, ServerTool, Tool } from "@tanstack/ai";
11
11
 
12
12
  //#region src/tanstack-ai.d.ts
13
13
  /**
@@ -68,7 +68,9 @@ declare function tanstackTools(tools: Tool[], name?: string): ToolProvider;
68
68
  * });
69
69
  * ```
70
70
  */
71
- declare function createCodeTool(options: CreateCodeToolOptions): ServerTool;
71
+ declare function createCodeTool(
72
+ options: CreateCodeToolOptions
73
+ ): ServerTool<SchemaInput, SchemaInput>;
72
74
  //#endregion
73
75
  export {
74
76
  type CodeInput,
@@ -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 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,CAAC,CACR,KAAK,EAAE,aAAa,6CAA6C,CAAC,EACvE,CAAC;;;;;AAMD,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,MAA4B;CACxE,IAAI,CAAC,WAAW,OAAO;CACvB,OAAO;AACT;;;;;;;AAQA,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,IAAI;EAC3C,MAAM,WAAW,aAAa,QAAQ;EAEtC,IAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,WAAW,IAC9B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,YAAY,IAC/B;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBAAiB,GAAG,SAAS,MAAM,IACpD,QAAQ,SAAS;GAErB,MAAM,aAAa,mBACf,iBAAiB,kBAAkB,GAAG,SAAS,OAAO,IACtD,QA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AAiC,cAClC,KAAA;EAEN,kBAAkB,UAAU,SAAS;EACrC,kBAAkB,UAAU,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,KAAK,IAChD,YAAY,YAAY,KAAK,CAAC,CAAC,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"}
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 SchemaInput,\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(\n options: CreateCodeToolOptions\n): ServerTool<SchemaInput, SchemaInput> {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,OAAO,CAAC,CACR,KAAK,EAAE,aAAa,6CAA6C,CAAC,EACvE,CAAC;;;;;AAMD,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,MAA4B;CACxE,IAAI,CAAC,WAAW,OAAO;CACvB,OAAO;AACT;;;;;;;AAQA,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,IAAI;EAC3C,MAAM,WAAW,aAAa,QAAQ;EAEtC,IAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,WAAW,IAC9B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,YAAY,IAC/B;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBAAiB,GAAG,SAAS,MAAM,IACpD,QAAQ,SAAS;GAErB,MAAM,aAAa,mBACf,iBAAiB,kBAAkB,GAAG,SAAS,OAAO,IACtD,QAAQ,SAAS;GAErB,kBAAkB,KAAK,UAAU,KAAK;GACtC,kBAAkB,KAA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,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,KAAK,IAChD,YAAY,YAAY,KAAK,CAAC,CAAC,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/docs/runtime.md CHANGED
@@ -138,6 +138,10 @@ In practice, model-generated code is naturally deterministic — it fetches data
138
138
 
139
139
  **Issue tool calls sequentially.** The replay cursor assigns each call its sequence number when the call reaches the host, so `await a(); await b();` is stable across runs but `await Promise.all([a(), b()])` is not — the two calls can arrive in either order. On a run that never pauses this is harmless, but if such a run later pauses and resumes, the reordered calls trip divergence detection. Await connector calls one at a time in any run that might pause for approval.
140
140
 
141
+ ## Unawaited tool calls
142
+
143
+ A program can return before a tool call it started has finished, for example `async () => { github.ping(); return 1; }`. When `execute()` settles, the sandbox gets an error for each call still pending, so it can exit and free its Dynamic Worker concurrency slot. The host keeps running those calls to completion, so fire-and-forget calls still take effect, but the program never sees their results.
144
+
141
145
  ## The tool-call log
142
146
 
143
147
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -15,15 +15,15 @@
15
15
  "acorn": "^8.17.0"
16
16
  },
17
17
  "devDependencies": {
18
- "@modelcontextprotocol/sdk": "1.32.1",
18
+ "@modelcontextprotocol/sdk": "1.32.2",
19
19
  "@playwright/test": "^1.61.1",
20
20
  "@tanstack/ai": "0.38.0",
21
21
  "ai": "^7.0.0",
22
- "zod": "^4.5.4"
22
+ "zod": "^4.6.7"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "@modelcontextprotocol/sdk": "^1.25.0",
26
- "@tanstack/ai": ">=0.8.0 <1.0.0",
26
+ "@tanstack/ai": ">=0.8.0 <2.0.0",
27
27
  "ai": "^6.0.0 || ^7.0.0",
28
28
  "zod": "^4.0.0"
29
29
  },