@cloudflare/codemode 0.2.1 → 0.3.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.
@@ -0,0 +1,41 @@
1
+ import {
2
+ c as ToolProviderTools,
3
+ i as Executor,
4
+ s as ToolProvider
5
+ } from "./executor-wZjYdqEX.js";
6
+
7
+ //#region src/shared.d.ts
8
+ declare const DEFAULT_DESCRIPTION =
9
+ 'Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax \u2014 no type annotations, interfaces, or generics.\nDo NOT define named functions then call them \u2014 just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: "test" }); return r; }';
10
+ interface CreateCodeToolOptions {
11
+ tools: ToolProviderTools | ToolProvider[];
12
+ executor: Executor;
13
+ /**
14
+ * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.
15
+ */
16
+ description?: string;
17
+ }
18
+ type CodeInput = {
19
+ code: string;
20
+ };
21
+ type CodeOutput = {
22
+ code: string;
23
+ result: unknown;
24
+ logs?: string[];
25
+ };
26
+ /**
27
+ * Normalize the tools option into a list of ToolProviders.
28
+ * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.
29
+ */
30
+ declare function normalizeProviders(
31
+ tools: ToolProviderTools | ToolProvider[]
32
+ ): ToolProvider[];
33
+ //#endregion
34
+ export {
35
+ normalizeProviders as a,
36
+ DEFAULT_DESCRIPTION as i,
37
+ CodeOutput as n,
38
+ CreateCodeToolOptions as r,
39
+ CodeInput as t
40
+ };
41
+ //# sourceMappingURL=shared-Hnh_Idta.d.ts.map
@@ -0,0 +1,30 @@
1
+ //#region src/shared.ts
2
+ const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
3
+
4
+ Available:
5
+ {{types}}
6
+
7
+ Write an async arrow function in JavaScript that returns the result.
8
+ Do NOT use TypeScript syntax — no type annotations, interfaces, or generics.
9
+ Do NOT define named functions then call them — just write the arrow function body directly.
10
+
11
+ Example: async () => { const r = await codemode.searchWeb({ query: "test" }); return r; }`;
12
+ /**
13
+ * Check if the tools option is an array of ToolProviders.
14
+ * A plain ToolSet/ToolDescriptors is a Record (not an array).
15
+ */
16
+ function isToolProviderArray(tools) {
17
+ return Array.isArray(tools);
18
+ }
19
+ /**
20
+ * Normalize the tools option into a list of ToolProviders.
21
+ * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.
22
+ */
23
+ function normalizeProviders(tools) {
24
+ if (isToolProviderArray(tools)) return tools;
25
+ return [{ tools }];
26
+ }
27
+ //#endregion
28
+ export { normalizeProviders as n, DEFAULT_DESCRIPTION as t };
29
+
30
+ //# sourceMappingURL=shared-ra3HW2ti.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared-ra3HW2ti.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { code: string; result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;AACzB,QAAO,MAAM,QAAQ,MAAM;;;;;;AAO7B,SAAgB,mBACd,OACgB;AAChB,KAAI,oBAAoB,MAAM,CAC5B,QAAO;AAET,QAAO,CAAC,EAAE,OAAO,CAAC"}
@@ -0,0 +1,84 @@
1
+ import { s as ToolProvider } from "./executor-wZjYdqEX.js";
2
+ import {
3
+ a as normalizeProviders,
4
+ i as DEFAULT_DESCRIPTION,
5
+ n as CodeOutput,
6
+ r as CreateCodeToolOptions,
7
+ t as CodeInput
8
+ } from "./shared-Hnh_Idta.js";
9
+ import { t as resolveProvider } from "./resolve-DULSpsq2.js";
10
+ import { ServerTool, Tool } from "@tanstack/ai";
11
+
12
+ //#region src/tanstack-ai.d.ts
13
+ /**
14
+ * Generate TypeScript type definitions from an array of TanStack AI tools.
15
+ *
16
+ * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type
17
+ * declarations that the LLM sees in the code-tool description.
18
+ */
19
+ declare function generateTypes(tools: Tool[], namespace?: string): string;
20
+ /**
21
+ * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.
22
+ *
23
+ * Converts the array-based TanStack tool format into the record-based
24
+ * ToolProvider that the codemode executor expects.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import { createCodeTool, tanstackTools } from "@cloudflare/codemode/tanstack-ai";
29
+ *
30
+ * const codeTool = createCodeTool({
31
+ * tools: [
32
+ * tanstackTools(myServerTools),
33
+ * tanstackTools(otherTools, "other"),
34
+ * ],
35
+ * executor,
36
+ * });
37
+ * ```
38
+ */
39
+ declare function tanstackTools(tools: Tool[], name?: string): ToolProvider;
40
+ /**
41
+ * Create a codemode tool that allows LLMs to write and execute code
42
+ * with access to your tools in a sandboxed environment.
43
+ *
44
+ * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.
45
+ *
46
+ * @example Basic usage
47
+ * ```ts
48
+ * const codeTool = createCodeTool({
49
+ * tools: [tanstackTools(myTools)],
50
+ * executor,
51
+ * });
52
+ *
53
+ * const stream = chat({
54
+ * adapter: openaiText("gpt-4o"),
55
+ * tools: [codeTool],
56
+ * messages,
57
+ * });
58
+ * ```
59
+ *
60
+ * @example Multiple namespaces
61
+ * ```ts
62
+ * createCodeTool({
63
+ * tools: [
64
+ * tanstackTools(githubTools, "github"),
65
+ * tanstackTools(dbTools, "db"),
66
+ * ],
67
+ * executor,
68
+ * });
69
+ * ```
70
+ */
71
+ declare function createCodeTool(options: CreateCodeToolOptions): ServerTool;
72
+ //#endregion
73
+ export {
74
+ type CodeInput,
75
+ type CodeOutput,
76
+ type CreateCodeToolOptions,
77
+ DEFAULT_DESCRIPTION,
78
+ createCodeTool,
79
+ generateTypes,
80
+ normalizeProviders,
81
+ resolveProvider,
82
+ tanstackTools
83
+ };
84
+ //# sourceMappingURL=tanstack-ai.d.ts.map
@@ -0,0 +1,216 @@
1
+ import { i as normalizeCode, n as filterTools, r as resolveProvider, t as extractFns } from "./resolve-DIQRkRqQ.js";
2
+ import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase } from "./json-schema-types-DoQ0VISs.js";
3
+ import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-ra3HW2ti.js";
4
+ import { z } from "zod";
5
+ import { convertSchemaToJsonSchema, toolDefinition } from "@tanstack/ai";
6
+ //#region src/tanstack-ai.ts
7
+ /**
8
+ * TanStack AI integration for codemode.
9
+ *
10
+ * Provides the same capabilities as `@cloudflare/codemode/ai` but returns
11
+ * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { createCodeTool, tanstackTools } from "@cloudflare/codemode/tanstack-ai";
16
+ * import { chat } from "@tanstack/ai";
17
+ *
18
+ * const codeTool = createCodeTool({
19
+ * tools: [tanstackTools(myServerTools)],
20
+ * executor,
21
+ * });
22
+ *
23
+ * const stream = chat({
24
+ * adapter: openaiText("gpt-4o"),
25
+ * tools: [codeTool],
26
+ * messages,
27
+ * });
28
+ * ```
29
+ */
30
+ const codeSchema = z.object({ code: z.string().meta({ description: "JavaScript async arrow function to execute" }) });
31
+ /**
32
+ * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to
33
+ * a JSON Schema 7 object usable by the core type generator.
34
+ */
35
+ function toJsonSchema7(schema) {
36
+ const converted = convertSchemaToJsonSchema(schema);
37
+ if (!converted) return null;
38
+ return converted;
39
+ }
40
+ /**
41
+ * Generate TypeScript type definitions from an array of TanStack AI tools.
42
+ *
43
+ * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type
44
+ * declarations that the LLM sees in the code-tool description.
45
+ */
46
+ function generateTypes(tools, namespace = "codemode") {
47
+ let availableTools = "";
48
+ let availableTypes = "";
49
+ for (const tool of tools) {
50
+ const safeName = sanitizeToolName(tool.name);
51
+ const typeName = toPascalCase(safeName);
52
+ try {
53
+ const inputJsonSchema = tool.inputSchema ? toJsonSchema7(tool.inputSchema) : null;
54
+ const outputJsonSchema = tool.outputSchema ? toJsonSchema7(tool.outputSchema) : null;
55
+ const inputType = inputJsonSchema ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`) : `type ${typeName}Input = unknown`;
56
+ const outputType = outputJsonSchema ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
57
+ availableTypes += `\n${inputType.trim()}`;
58
+ availableTypes += `\n${outputType.trim()}`;
59
+ const paramDescs = (() => {
60
+ try {
61
+ if (!inputJsonSchema?.properties) return [];
62
+ return Object.entries(inputJsonSchema.properties).filter(([, propSchema]) => propSchema && typeof propSchema === "object" && propSchema.description).map(([fieldName, propSchema]) => `@param input.${fieldName} - ${propSchema.description}`);
63
+ } catch {
64
+ return [];
65
+ }
66
+ })();
67
+ const jsdocLines = [];
68
+ if (tool.description?.trim()) jsdocLines.push(escapeJsDoc(tool.description.trim().replace(/\r?\n/g, " ")));
69
+ else jsdocLines.push(escapeJsDoc(tool.name));
70
+ for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
71
+ const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
72
+ availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
73
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
74
+ availableTools += "\n";
75
+ } catch {
76
+ availableTypes += `\ntype ${typeName}Input = unknown`;
77
+ availableTypes += `\ntype ${typeName}Output = unknown`;
78
+ availableTools += `\n\t/**\n\t * ${escapeJsDoc(tool.name)}\n\t */`;
79
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
80
+ availableTools += "\n";
81
+ }
82
+ }
83
+ availableTools = `\ndeclare const ${namespace}: {${availableTools}}`;
84
+ return `
85
+ ${availableTypes}
86
+ ${availableTools}
87
+ `.trim();
88
+ }
89
+ /**
90
+ * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.
91
+ *
92
+ * Converts the array-based TanStack tool format into the record-based
93
+ * ToolProvider that the codemode executor expects.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * import { createCodeTool, tanstackTools } from "@cloudflare/codemode/tanstack-ai";
98
+ *
99
+ * const codeTool = createCodeTool({
100
+ * tools: [
101
+ * tanstackTools(myServerTools),
102
+ * tanstackTools(otherTools, "other"),
103
+ * ],
104
+ * executor,
105
+ * });
106
+ * ```
107
+ */
108
+ function tanstackTools(tools, name) {
109
+ const filtered = tools.filter((t) => !("needsApproval" in t && t.needsApproval != null));
110
+ const toolRecord = {};
111
+ for (const tool of filtered) if (tool.execute) toolRecord[tool.name] = {
112
+ description: tool.description,
113
+ execute: async (args) => tool.execute(args)
114
+ };
115
+ const ns = name ?? "codemode";
116
+ const types = generateTypes(filtered, ns);
117
+ return {
118
+ name: ns === "codemode" ? void 0 : ns,
119
+ tools: toolRecord,
120
+ types
121
+ };
122
+ }
123
+ /**
124
+ * Create a codemode tool that allows LLMs to write and execute code
125
+ * with access to your tools in a sandboxed environment.
126
+ *
127
+ * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.
128
+ *
129
+ * @example Basic usage
130
+ * ```ts
131
+ * const codeTool = createCodeTool({
132
+ * tools: [tanstackTools(myTools)],
133
+ * executor,
134
+ * });
135
+ *
136
+ * const stream = chat({
137
+ * adapter: openaiText("gpt-4o"),
138
+ * tools: [codeTool],
139
+ * messages,
140
+ * });
141
+ * ```
142
+ *
143
+ * @example Multiple namespaces
144
+ * ```ts
145
+ * createCodeTool({
146
+ * tools: [
147
+ * tanstackTools(githubTools, "github"),
148
+ * tanstackTools(dbTools, "db"),
149
+ * ],
150
+ * executor,
151
+ * });
152
+ * ```
153
+ */
154
+ function createCodeTool(options) {
155
+ const providers = normalizeProviders(options.tools);
156
+ const typeBlocks = [];
157
+ const resolvedProviders = [];
158
+ for (const provider of providers) {
159
+ const providerName = provider.name ?? "codemode";
160
+ const filtered = filterTools(provider.tools);
161
+ const types = provider.types ?? generateTypesFromRecord(filtered, providerName);
162
+ typeBlocks.push(types);
163
+ resolvedProviders.push({
164
+ name: providerName,
165
+ fns: extractFns(filtered)
166
+ });
167
+ }
168
+ const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
169
+ const executor = options.executor;
170
+ return toolDefinition({
171
+ name: "codemode_execute",
172
+ description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
173
+ inputSchema: codeSchema
174
+ }).server(async ({ code }) => {
175
+ const normalizedCode = normalizeCode(code);
176
+ const executeResult = await executor.execute(normalizedCode, resolvedProviders);
177
+ if (executeResult.error) {
178
+ const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
179
+ throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
180
+ }
181
+ const output = {
182
+ code,
183
+ result: executeResult.result
184
+ };
185
+ if (executeResult.logs) output.logs = executeResult.logs;
186
+ return output;
187
+ });
188
+ }
189
+ /**
190
+ * Generate types from a ToolProviderTools record.
191
+ * Falls back to the JSON Schema generator for SimpleToolRecord.
192
+ */
193
+ function generateTypesFromRecord(tools, namespace) {
194
+ let availableTools = "";
195
+ let availableTypes = "";
196
+ for (const [toolName, tool] of Object.entries(tools)) {
197
+ const safeName = sanitizeToolName(toolName);
198
+ const typeName = toPascalCase(safeName);
199
+ const description = "description" in tool ? tool.description : void 0;
200
+ availableTypes += `\ntype ${typeName}Input = unknown`;
201
+ availableTypes += `\ntype ${typeName}Output = unknown`;
202
+ const descStr = typeof description === "string" && description.trim() ? escapeJsDoc(description.trim().replace(/\r?\n/g, " ")) : escapeJsDoc(toolName);
203
+ availableTools += `\n\t/**\n\t * ${descStr}\n\t */`;
204
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
205
+ availableTools += "\n";
206
+ }
207
+ availableTools = `\ndeclare const ${namespace}: {${availableTools}}`;
208
+ return `
209
+ ${availableTypes}
210
+ ${availableTools}
211
+ `.trim();
212
+ }
213
+ //#endregion
214
+ export { DEFAULT_DESCRIPTION, createCodeTool, generateTypes, normalizeProviders, resolveProvider, tanstackTools };
215
+
216
+ //# sourceMappingURL=tanstack-ai.js.map
@@ -0,0 +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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AGpB,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.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -17,19 +17,24 @@
17
17
  "devDependencies": {
18
18
  "@modelcontextprotocol/sdk": "1.26.0",
19
19
  "@playwright/test": "^1.58.2",
20
- "ai": "^6.0.116",
21
- "vitest": "3.2.4",
20
+ "@tanstack/ai": "^0.8.1",
21
+ "ai": "^6.0.134",
22
+ "vitest": "4.1.0",
22
23
  "zod": "^4.3.6"
23
24
  },
24
25
  "peerDependencies": {
25
26
  "@modelcontextprotocol/sdk": "^1.25.0",
27
+ "@tanstack/ai": "^0.8.0",
26
28
  "ai": "^6.0.0",
27
- "zod": "^3.25.0 || ^4.0.0"
29
+ "zod": "^4.0.0"
28
30
  },
29
31
  "peerDependenciesMeta": {
30
32
  "@modelcontextprotocol/sdk": {
31
33
  "optional": true
32
34
  },
35
+ "@tanstack/ai": {
36
+ "optional": true
37
+ },
33
38
  "ai": {
34
39
  "optional": true
35
40
  },
@@ -53,6 +58,11 @@
53
58
  "types": "./dist/mcp.d.ts",
54
59
  "import": "./dist/mcp.js",
55
60
  "require": "./dist/mcp.js"
61
+ },
62
+ "./tanstack-ai": {
63
+ "types": "./dist/tanstack-ai.d.ts",
64
+ "import": "./dist/tanstack-ai.js",
65
+ "require": "./dist/tanstack-ai.js"
56
66
  }
57
67
  },
58
68
  "scripts": {
@@ -1,78 +0,0 @@
1
- import { RpcTarget } from "cloudflare:workers";
2
-
3
- //#region src/executor.d.ts
4
- interface ExecuteResult {
5
- result: unknown;
6
- error?: string;
7
- logs?: string[];
8
- }
9
- /**
10
- * An executor runs LLM-generated code in a sandbox, making the provided
11
- * tool functions callable as `codemode.*` inside the sandbox.
12
- *
13
- * Implementations should never throw — errors are returned in `ExecuteResult.error`.
14
- */
15
- interface Executor {
16
- execute(
17
- code: string,
18
- fns: Record<string, (...args: unknown[]) => Promise<unknown>>
19
- ): Promise<ExecuteResult>;
20
- }
21
- /**
22
- * An RpcTarget that dispatches tool calls from the sandboxed Worker
23
- * back to the host. Passed via Workers RPC to the dynamic Worker's
24
- * evaluate() method — no globalOutbound or Fetcher bindings needed.
25
- */
26
- declare class ToolDispatcher extends RpcTarget {
27
- #private;
28
- constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>);
29
- call(name: string, argsJson: string): Promise<string>;
30
- }
31
- interface DynamicWorkerExecutorOptions {
32
- loader: WorkerLoader;
33
- /**
34
- * Timeout in milliseconds for code execution. Defaults to 30000 (30s).
35
- */
36
- timeout?: number;
37
- /**
38
- * Controls outbound network access from sandboxed code.
39
- * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.
40
- * - `undefined`: inherits parent Worker's network access (full internet).
41
- * - A `Fetcher`: all outbound requests route through this handler.
42
- */
43
- globalOutbound?: Fetcher | null;
44
- /**
45
- * Additional modules to make available in the sandbox.
46
- * Keys are module specifiers (e.g. `"mylib.js"`), values are module source code.
47
- * Sandbox code can import from these via `import { ... } from "mylib.js"`.
48
- *
49
- * Note: the key `"executor.js"` is reserved and will be ignored if provided.
50
- */
51
- modules?: Record<string, string>;
52
- }
53
- /**
54
- * Executes code in an isolated Cloudflare Worker via WorkerLoader.
55
- * Tool calls are dispatched via Workers RPC — the host passes a
56
- * ToolDispatcher (RpcTarget) to the Worker's evaluate() method.
57
- *
58
- * External fetch() and connect() are blocked by default via
59
- * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to
60
- * `globalOutbound` to allow controlled outbound access.
61
- */
62
- declare class DynamicWorkerExecutor implements Executor {
63
- #private;
64
- constructor(options: DynamicWorkerExecutorOptions);
65
- execute(
66
- code: string,
67
- fns: Record<string, (...args: unknown[]) => Promise<unknown>>
68
- ): Promise<ExecuteResult>;
69
- }
70
- //#endregion
71
- export {
72
- ToolDispatcher as a,
73
- Executor as i,
74
- DynamicWorkerExecutorOptions as n,
75
- ExecuteResult as r,
76
- DynamicWorkerExecutor as t
77
- };
78
- //# sourceMappingURL=executor-6RSFUhUk.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"normalize-DnrE6oKV.js","names":[],"sources":["../src/normalize.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MADjB,qEAC8B;AAChC,QAAO,QAAQ,MAAM,KAAK;;AAG5B,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,MAAM,CAAC;AAC5C,KAAI,CAAC,QAAQ,MAAM,CAAE,QAAO;CAE5B,MAAM,SAAS,QAAQ,MAAM;AAE7B,KAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;GACb,CAAC;AAGF,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS;OAClC,IAAI,KAAK,GAAiC,WAC/C,SAAS,0BAA2B,QAAO;;AAItD,MACE,IAAI,KAAK,WAAW,KACpB,IAAI,KAAK,GAAG,SAAS,4BACrB;GACA,MAAM,OAAQ,IAAI,KAAK,GAAsC;GAC7D,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,IAAI;AAIhD,OACE,KAAK,SAAS,yBACd,CAAE,KAAmC,GAErC,QAAO,0BAA0B,MAAM;AAEzC,OACE,KAAK,SAAS,sBACd,CAAE,KAAgC,GAElC,QAAO,0BAA0B,MAAM;AAGzC,UAAO,cAAc,MAAM;;AAI7B,MAAI,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