@cloudflare/codemode 0.2.2 → 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.
- package/README.md +57 -7
- package/dist/ai.d.ts +34 -6
- package/dist/ai.js +242 -1
- package/dist/ai.js.map +1 -0
- package/dist/{executor-C1NPN-nW.d.ts → executor-wZjYdqEX.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/resolve-DIQRkRqQ.js +85 -0
- package/dist/resolve-DIQRkRqQ.js.map +1 -0
- package/dist/resolve-DULSpsq2.d.ts +17 -0
- package/dist/shared-Hnh_Idta.d.ts +41 -0
- package/dist/shared-ra3HW2ti.js +30 -0
- package/dist/shared-ra3HW2ti.js.map +1 -0
- package/dist/tanstack-ai.d.ts +84 -0
- package/dist/tanstack-ai.js +216 -0
- package/dist/tanstack-ai.js.map +1 -0
- package/package.json +14 -4
- package/dist/tool-B0ZYASro.js +0 -342
- package/dist/tool-B0ZYASro.js.map +0 -1
- package/dist/tool-BQ5SO4OJ.d.ts +0 -59
|
@@ -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 ${nam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S,oBAAoB,SAAS;AACpF,oBAAkB;;AAGpB,kBAAiB,mBAAmB,UAAU,KAAK,eAAe;AAElE,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/codemode",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"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": "^
|
|
21
|
-
"
|
|
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": "^
|
|
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": {
|