@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 CHANGED
@@ -9,14 +9,17 @@ Code Mode generates TypeScript type definitions from your tools for LLM context,
9
9
  ## Installation
10
10
 
11
11
  ```sh
12
- # Full AI SDK integration
12
+ # With Vercel AI SDK
13
13
  npm install @cloudflare/codemode agents ai zod
14
14
 
15
- # Utilities only (no ai/zod peer deps needed)
15
+ # With TanStack AI
16
+ npm install @cloudflare/codemode agents @tanstack/ai zod
17
+
18
+ # Utilities only (no framework peer deps needed)
16
19
  npm install @cloudflare/codemode
17
20
  ```
18
21
 
19
- The main entry point (`@cloudflare/codemode`) has **no peer dependency on `ai` or `zod`**. The `ai` and `zod` packages are only required when importing from `@cloudflare/codemode/ai`.
22
+ The main entry point (`@cloudflare/codemode`) has **no peer dependency on `ai`, `@tanstack/ai`, or `zod`**. Framework-specific packages are only required when importing from `@cloudflare/codemode/ai` or `@cloudflare/codemode/tanstack-ai`.
20
23
 
21
24
  ## Quick Start
22
25
 
@@ -77,6 +80,52 @@ async () => {
77
80
  };
78
81
  ```
79
82
 
83
+ ## TanStack AI
84
+
85
+ If you're using TanStack AI instead of the Vercel AI SDK, import from `@cloudflare/codemode/tanstack-ai`:
86
+
87
+ ```ts
88
+ import {
89
+ createCodeTool,
90
+ tanstackTools
91
+ } from "@cloudflare/codemode/tanstack-ai";
92
+ import { DynamicWorkerExecutor } from "@cloudflare/codemode";
93
+ import { chat } from "@tanstack/ai";
94
+ import { openaiText } from "@tanstack/ai-openai";
95
+ import { toolDefinition } from "@tanstack/ai";
96
+ import { z } from "zod";
97
+
98
+ // 1. Define your tools using TanStack AI's toolDefinition()
99
+ const getWeather = toolDefinition({
100
+ name: "get_weather",
101
+ description: "Get weather for a location",
102
+ inputSchema: z.object({ location: z.string() })
103
+ }).server(async ({ location }) => `Weather in ${location}: 72°F, sunny`);
104
+
105
+ // 2. Create the codemode tool
106
+ const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
107
+ const codeTool = createCodeTool({
108
+ tools: [tanstackTools([getWeather])],
109
+ executor
110
+ });
111
+
112
+ // 3. Use it with TanStack AI's chat()
113
+ const stream = chat({
114
+ adapter: openaiText("gpt-4o"),
115
+ tools: [codeTool],
116
+ messages
117
+ });
118
+ ```
119
+
120
+ `tanstackTools()` converts TanStack AI tools (array-based) into the record-based `ToolProvider` format. It also accepts an optional namespace:
121
+
122
+ ```ts
123
+ createCodeTool({
124
+ tools: [tanstackTools(weatherTools, "weather"), tanstackTools(dbTools, "db")],
125
+ executor
126
+ });
127
+ ```
128
+
80
129
  ## Tool Providers
81
130
 
82
131
  Tool providers let you compose capabilities from different packages into a single sandbox execution. Each provider contributes tools under a namespace — the LLM can use all of them in the same code block.
@@ -374,10 +423,11 @@ const types = generateTypes(myAiSdkTools);
374
423
 
375
424
  ## Module Structure
376
425
 
377
- | Module | Requires `ai`/`zod` | Exports |
378
- | ------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
379
- | `@cloudflare/codemode` | No | `sanitizeToolName`, `normalizeCode`, `generateTypesFromJsonSchema`, `jsonSchemaToType`, `DynamicWorkerExecutor`, `ToolDispatcher`, `ToolProvider`, `resolveProvider` |
380
- | `@cloudflare/codemode/ai` | Yes | `createCodeTool`, `generateTypes`, `ToolDescriptor`, `ToolDescriptors` |
426
+ | Module | Peer deps | Exports |
427
+ | ---------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
428
+ | `@cloudflare/codemode` | None | `sanitizeToolName`, `normalizeCode`, `generateTypesFromJsonSchema`, `jsonSchemaToType`, `DynamicWorkerExecutor`, `ToolDispatcher`, `ToolProvider`, `resolveProvider` |
429
+ | `@cloudflare/codemode/ai` | `ai`, `zod` | `createCodeTool`, `generateTypes`, `aiTools`, `resolveProvider`, `ToolDescriptor`, `ToolDescriptors` |
430
+ | `@cloudflare/codemode/tanstack-ai` | `@tanstack/ai`, `zod` | `createCodeTool`, `generateTypes`, `tanstackTools`, `resolveProvider` |
381
431
 
382
432
  ## Limitations
383
433
 
package/dist/ai.d.ts CHANGED
@@ -1,15 +1,42 @@
1
1
  import {
2
+ a as ResolvedProvider,
2
3
  d as generateTypes,
3
4
  l as ToolDescriptor,
5
+ s as ToolProvider,
4
6
  u as ToolDescriptors
5
- } from "./executor-C1NPN-nW.js";
7
+ } from "./executor-wZjYdqEX.js";
6
8
  import {
7
- i as resolveProvider,
8
- n as aiTools,
9
- r as createCodeTool,
10
- t as CreateCodeToolOptions
11
- } from "./tool-BQ5SO4OJ.js";
9
+ n as CodeOutput,
10
+ r as CreateCodeToolOptions,
11
+ t as CodeInput
12
+ } from "./shared-Hnh_Idta.js";
13
+ import { Tool, ToolSet } from "ai";
14
+
15
+ //#region src/tool.d.ts
16
+ /**
17
+ * Wrap raw AI SDK tools into a ToolProvider under the default "codemode" namespace.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * createCodeTool({
22
+ * tools: [stateTools(workspace), aiTools(myTools)],
23
+ * executor,
24
+ * });
25
+ * ```
26
+ */
27
+ declare function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider;
28
+ /**
29
+ * Resolve a ToolProvider into a ResolvedProvider ready for execution.
30
+ * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.
31
+ */
32
+ declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
33
+ declare function createCodeTool(
34
+ options: CreateCodeToolOptions
35
+ ): Tool<CodeInput, CodeOutput>;
36
+ //#endregion
12
37
  export {
38
+ type CodeInput,
39
+ type CodeOutput,
13
40
  type CreateCodeToolOptions,
14
41
  type ToolDescriptor,
15
42
  type ToolDescriptors,
@@ -18,3 +45,4 @@ export {
18
45
  generateTypes,
19
46
  resolveProvider
20
47
  };
48
+ //# sourceMappingURL=ai.d.ts.map
package/dist/ai.js CHANGED
@@ -1,2 +1,243 @@
1
- import { i as generateTypes, n as createCodeTool, r as resolveProvider, t as aiTools } from "./tool-B0ZYASro.js";
1
+ import { i as normalizeCode, n as filterTools } from "./resolve-DIQRkRqQ.js";
2
+ import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-DoQ0VISs.js";
3
+ import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-ra3HW2ti.js";
4
+ import { asSchema, tool } from "ai";
5
+ import { z } from "zod";
6
+ //#region src/tool-types.ts
7
+ /**
8
+ * Check if a value is a Zod schema (has _zod property).
9
+ */
10
+ function isZodSchema(value) {
11
+ return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
12
+ }
13
+ /**
14
+ * Check if a value conforms to the Standard Schema protocol (~standard).
15
+ * This catches Zod v3 schemas (which expose ~standard but not _zod).
16
+ */
17
+ function isStandardSchema(value) {
18
+ return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
19
+ }
20
+ /**
21
+ * Check if a value is an AI SDK jsonSchema wrapper.
22
+ * The jsonSchema wrapper has a [Symbol] with jsonSchema property.
23
+ */
24
+ function isJsonSchemaWrapper(value) {
25
+ if (value === null || typeof value !== "object") return false;
26
+ if ("jsonSchema" in value) return true;
27
+ const symbols = Object.getOwnPropertySymbols(value);
28
+ for (const sym of symbols) {
29
+ const symValue = value[sym];
30
+ if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return true;
31
+ }
32
+ return false;
33
+ }
34
+ /**
35
+ * Extract JSON schema from an AI SDK jsonSchema wrapper.
36
+ */
37
+ function extractJsonSchema(wrapper) {
38
+ if (wrapper === null || typeof wrapper !== "object") return null;
39
+ if ("jsonSchema" in wrapper) return wrapper.jsonSchema;
40
+ const symbols = Object.getOwnPropertySymbols(wrapper);
41
+ for (const sym of symbols) {
42
+ const symValue = wrapper[sym];
43
+ if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return symValue.jsonSchema;
44
+ }
45
+ return null;
46
+ }
47
+ /**
48
+ * Extract field descriptions from a schema.
49
+ * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).
50
+ */
51
+ function extractDescriptions(schema) {
52
+ const descriptions = {};
53
+ const shape = schema.shape;
54
+ if (shape && typeof shape === "object") {
55
+ for (const [fieldName, fieldSchema] of Object.entries(shape)) {
56
+ let s = fieldSchema;
57
+ while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
58
+ if (s.description) descriptions[fieldName] = s.description;
59
+ }
60
+ return descriptions;
61
+ }
62
+ if (isJsonSchemaWrapper(schema)) {
63
+ const jsonSchema = extractJsonSchema(schema);
64
+ if (jsonSchema?.properties) {
65
+ for (const [fieldName, propSchema] of Object.entries(jsonSchema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
66
+ }
67
+ }
68
+ return descriptions;
69
+ }
70
+ /**
71
+ * Extract field descriptions from a schema and format as @param lines.
72
+ */
73
+ function extractParamDescriptions(schema) {
74
+ const descriptions = extractDescriptions(schema);
75
+ return Object.entries(descriptions).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
76
+ }
77
+ /**
78
+ * Safely convert a schema to TypeScript type string.
79
+ * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
80
+ */
81
+ function safeSchemaToTs(schema, typeName) {
82
+ try {
83
+ if (isZodSchema(schema) || isStandardSchema(schema)) {
84
+ const jsonSchema = asSchema(schema).jsonSchema;
85
+ if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
86
+ root: jsonSchema,
87
+ depth: 0,
88
+ seen: /* @__PURE__ */ new Set(),
89
+ maxDepth: 20
90
+ })}`;
91
+ }
92
+ if (isJsonSchemaWrapper(schema)) {
93
+ const jsonSchema = extractJsonSchema(schema);
94
+ if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
95
+ root: jsonSchema,
96
+ depth: 0,
97
+ seen: /* @__PURE__ */ new Set(),
98
+ maxDepth: 20
99
+ })}`;
100
+ }
101
+ return `type ${typeName} = unknown`;
102
+ } catch {
103
+ return `type ${typeName} = unknown`;
104
+ }
105
+ }
106
+ /**
107
+ * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
108
+ * These types can be included in tool descriptions to help LLMs write correct code.
109
+ *
110
+ * Requires the `ai` peer dependency. For a version that works with plain JSON Schema
111
+ * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
112
+ */
113
+ function generateTypes(tools, namespace = "codemode") {
114
+ let availableTools = "";
115
+ let availableTypes = "";
116
+ for (const [toolName, tool] of Object.entries(tools)) {
117
+ const safeName = sanitizeToolName(toolName);
118
+ const typeName = toPascalCase(safeName);
119
+ try {
120
+ const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
121
+ const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
122
+ const description = tool.description;
123
+ const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);
124
+ const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
125
+ availableTypes += `\n${inputType.trim()}`;
126
+ availableTypes += `\n${outputType.trim()}`;
127
+ const paramDescs = (() => {
128
+ try {
129
+ return inputSchema ? extractParamDescriptions(inputSchema) : [];
130
+ } catch {
131
+ return [];
132
+ }
133
+ })();
134
+ const jsdocLines = [];
135
+ if (description?.trim()) jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
136
+ else jsdocLines.push(escapeJsDoc(toolName));
137
+ for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
138
+ const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
139
+ availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
140
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
141
+ availableTools += "\n";
142
+ } catch {
143
+ availableTypes += `\ntype ${typeName}Input = unknown`;
144
+ availableTypes += `\ntype ${typeName}Output = unknown`;
145
+ availableTools += `\n\t/**\n\t * ${escapeJsDoc(toolName)}\n\t */`;
146
+ availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
147
+ availableTools += "\n";
148
+ }
149
+ }
150
+ availableTools = `\ndeclare const ${namespace}: {${availableTools}}`;
151
+ return `
152
+ ${availableTypes}
153
+ ${availableTools}
154
+ `.trim();
155
+ }
156
+ //#endregion
157
+ //#region src/tool.ts
158
+ const codeSchema = z.object({ code: z.string().describe("JavaScript async arrow function to execute") });
159
+ /**
160
+ * Extract execute functions from tools, keyed by name.
161
+ * Wraps each with schema validation via AI SDK's `asSchema` when available.
162
+ */
163
+ function extractFns(tools) {
164
+ const fns = {};
165
+ for (const [name, t] of Object.entries(tools)) {
166
+ const execute = "execute" in t ? t.execute : void 0;
167
+ if (execute) {
168
+ const rawSchema = "inputSchema" in t ? t.inputSchema : "parameters" in t ? t.parameters : void 0;
169
+ const schema = rawSchema != null ? asSchema(rawSchema) : void 0;
170
+ fns[name] = schema?.validate ? async (args) => {
171
+ const result = await schema.validate(args);
172
+ if (!result.success) throw result.error;
173
+ return execute(result.value);
174
+ } : execute;
175
+ }
176
+ }
177
+ return fns;
178
+ }
179
+ /**
180
+ * Wrap raw AI SDK tools into a ToolProvider under the default "codemode" namespace.
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * createCodeTool({
185
+ * tools: [stateTools(workspace), aiTools(myTools)],
186
+ * executor,
187
+ * });
188
+ * ```
189
+ */
190
+ function aiTools(tools) {
191
+ return { tools };
192
+ }
193
+ /**
194
+ * Resolve a ToolProvider into a ResolvedProvider ready for execution.
195
+ * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.
196
+ */
197
+ function resolveProvider(provider) {
198
+ const resolved = {
199
+ name: provider.name ?? "codemode",
200
+ fns: extractFns(filterTools(provider.tools))
201
+ };
202
+ if (provider.positionalArgs) resolved.positionalArgs = true;
203
+ return resolved;
204
+ }
205
+ function createCodeTool(options) {
206
+ const providers = normalizeProviders(options.tools);
207
+ const typeBlocks = [];
208
+ const resolvedProviders = [];
209
+ for (const provider of providers) {
210
+ const name = provider.name ?? "codemode";
211
+ const filtered = filterTools(provider.tools);
212
+ const types = provider.types ?? generateTypes(filtered, name);
213
+ typeBlocks.push(types);
214
+ resolvedProviders.push({
215
+ name,
216
+ fns: extractFns(filtered)
217
+ });
218
+ }
219
+ const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
220
+ const executor = options.executor;
221
+ return tool({
222
+ description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
223
+ inputSchema: codeSchema,
224
+ execute: async ({ code }) => {
225
+ const normalizedCode = normalizeCode(code);
226
+ const executeResult = await executor.execute(normalizedCode, resolvedProviders);
227
+ if (executeResult.error) {
228
+ const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
229
+ throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
230
+ }
231
+ const output = {
232
+ code,
233
+ result: executeResult.result
234
+ };
235
+ if (executeResult.logs) output.logs = executeResult.logs;
236
+ return output;
237
+ }
238
+ });
239
+ }
240
+ //#endregion
2
241
  export { aiTools, createCodeTool, generateTypes, resolveProvider };
242
+
243
+ //# sourceMappingURL=ai.js.map
package/dist/ai.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai.js","names":[],"sources":["../src/tool-types.ts","../src/tool.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(\n tools: ToolDescriptors | ToolSet,\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[name] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [stateTools(workspace), aiTools(myTools)],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n resolvedProviders.push({ name, fns: extractFns(filtered) });\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n }\n });\n}\n"],"mappings":";;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;AACrD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS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AO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
@@ -183,4 +183,4 @@ export {
183
183
  DynamicWorkerExecutor as t,
184
184
  ToolDescriptors as u
185
185
  };
186
- //# sourceMappingURL=executor-C1NPN-nW.d.ts.map
186
+ //# sourceMappingURL=executor-wZjYdqEX.d.ts.map
package/dist/index.d.ts CHANGED
@@ -6,8 +6,8 @@ import {
6
6
  r as ExecuteResult,
7
7
  s as ToolProvider,
8
8
  t as DynamicWorkerExecutor
9
- } from "./executor-C1NPN-nW.js";
10
- import { i as resolveProvider } from "./tool-BQ5SO4OJ.js";
9
+ } from "./executor-wZjYdqEX.js";
10
+ import { t as resolveProvider } from "./resolve-DULSpsq2.js";
11
11
  import { JSONSchema7 } from "json-schema";
12
12
 
13
13
  //#region src/utils.d.ts
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as normalizeCode, r as resolveProvider } from "./tool-B0ZYASro.js";
1
+ import { i as normalizeCode, r as resolveProvider } from "./resolve-DIQRkRqQ.js";
2
2
  import { a as sanitizeToolName, n as jsonSchemaToType, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
3
3
  import { RpcTarget } from "cloudflare:workers";
4
4
  //#region src/executor.ts
package/dist/mcp.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as Executor } from "./executor-C1NPN-nW.js";
1
+ import { i as Executor } from "./executor-wZjYdqEX.js";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
 
4
4
  //#region src/mcp.d.ts
@@ -0,0 +1,85 @@
1
+ import * as acorn from "acorn";
2
+ //#region src/normalize.ts
3
+ /**
4
+ * Strip markdown code fences that LLMs commonly wrap code in.
5
+ * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
6
+ */
7
+ function stripCodeFences(code) {
8
+ const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
9
+ return match ? match[1] : code;
10
+ }
11
+ function normalizeCode(code) {
12
+ const trimmed = stripCodeFences(code.trim());
13
+ if (!trimmed.trim()) return "async () => {}";
14
+ const source = trimmed.trim();
15
+ try {
16
+ const ast = acorn.parse(source, {
17
+ ecmaVersion: "latest",
18
+ sourceType: "module"
19
+ });
20
+ if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
21
+ if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
22
+ }
23
+ if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
24
+ const decl = ast.body[0].declaration;
25
+ const inner = source.slice(decl.start, decl.end);
26
+ if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
27
+ if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
28
+ return normalizeCode(inner);
29
+ }
30
+ if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
31
+ const last = ast.body[ast.body.length - 1];
32
+ if (last?.type === "ExpressionStatement") {
33
+ const exprStmt = last;
34
+ return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
35
+ }
36
+ return `async () => {\n${source}\n}`;
37
+ } catch {
38
+ return `async () => {\n${source}\n}`;
39
+ }
40
+ }
41
+ //#endregion
42
+ //#region src/resolve.ts
43
+ function hasNeedsApproval(t) {
44
+ return "needsApproval" in t && t.needsApproval != null;
45
+ }
46
+ /**
47
+ * Filter out tools with needsApproval and return a clean copy.
48
+ */
49
+ function filterTools(tools) {
50
+ const filtered = {};
51
+ for (const [name, t] of Object.entries(tools)) if (!hasNeedsApproval(t)) filtered[name] = t;
52
+ return filtered;
53
+ }
54
+ /**
55
+ * Extract execute functions from tools, keyed by name.
56
+ * This is the base version — no schema validation.
57
+ * The AI SDK entry point overrides this with `asSchema`-based validation.
58
+ */
59
+ function extractFns(tools) {
60
+ const fns = {};
61
+ for (const [name, t] of Object.entries(tools)) {
62
+ const execute = "execute" in t ? t.execute : void 0;
63
+ if (execute) fns[name] = execute;
64
+ }
65
+ return fns;
66
+ }
67
+ /**
68
+ * Resolve a ToolProvider into a ResolvedProvider ready for execution.
69
+ * Filters out tools with `needsApproval`.
70
+ *
71
+ * This version does NOT perform schema validation on inputs.
72
+ * Import from `@cloudflare/codemode/ai` for the schema-validating version.
73
+ */
74
+ function resolveProvider(provider) {
75
+ const resolved = {
76
+ name: provider.name ?? "codemode",
77
+ fns: extractFns(filterTools(provider.tools))
78
+ };
79
+ if (provider.positionalArgs) resolved.positionalArgs = true;
80
+ return resolved;
81
+ }
82
+ //#endregion
83
+ export { normalizeCode as i, filterTools as n, resolveProvider as r, extractFns as t };
84
+
85
+ //# sourceMappingURL=resolve-DIQRkRqQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-DIQRkRqQ.js","names":[],"sources":["../src/normalize.ts","../src/resolve.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","/**\n * Framework-agnostic tool resolution.\n *\n * Extracts execute functions from tool records and resolves ToolProviders\n * into ResolvedProviders — no dependency on the AI SDK or Zod.\n *\n * The AI SDK entry point (`./ai`) layers on schema validation via `asSchema`.\n */\n\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\n\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nexport function filterTools(tools: ToolProviderTools): ToolProviderTools {\n const filtered: Record<string, unknown> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n filtered[name] = t;\n }\n }\n return filtered as ToolProviderTools;\n}\n\n/**\n * Extract execute functions from tools, keyed by name.\n * This is the base version — no schema validation.\n * The AI SDK entry point overrides this with `asSchema`-based validation.\n */\nexport function 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 fns[name] = execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`.\n *\n * This version does NOT perform schema validation on inputs.\n * Import from `@cloudflare/codemode/ai` for the schema-validating version.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n"],"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,KAA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S,iBAAiB;AACvD,QAAO"}
@@ -0,0 +1,17 @@
1
+ import {
2
+ a as ResolvedProvider,
3
+ s as ToolProvider
4
+ } from "./executor-wZjYdqEX.js";
5
+
6
+ //#region src/resolve.d.ts
7
+ /**
8
+ * Resolve a ToolProvider into a ResolvedProvider ready for execution.
9
+ * Filters out tools with `needsApproval`.
10
+ *
11
+ * This version does NOT perform schema validation on inputs.
12
+ * Import from `@cloudflare/codemode/ai` for the schema-validating version.
13
+ */
14
+ declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
15
+ //#endregion
16
+ export { resolveProvider as t };
17
+ //# sourceMappingURL=resolve-DULSpsq2.d.ts.map
@@ -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"}