@cloudflare/codemode 0.2.2 → 0.3.1

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.
@@ -1,342 +0,0 @@
1
- import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-DoQ0VISs.js";
2
- import * as acorn from "acorn";
3
- import { asSchema, tool } from "ai";
4
- import { z } from "zod";
5
- //#region src/normalize.ts
6
- /**
7
- * Strip markdown code fences that LLMs commonly wrap code in.
8
- * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
9
- */
10
- function stripCodeFences(code) {
11
- const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
12
- return match ? match[1] : code;
13
- }
14
- function normalizeCode(code) {
15
- const trimmed = stripCodeFences(code.trim());
16
- if (!trimmed.trim()) return "async () => {}";
17
- const source = trimmed.trim();
18
- try {
19
- const ast = acorn.parse(source, {
20
- ecmaVersion: "latest",
21
- sourceType: "module"
22
- });
23
- if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
24
- if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
25
- }
26
- if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
27
- const decl = ast.body[0].declaration;
28
- const inner = source.slice(decl.start, decl.end);
29
- if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
30
- if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
31
- return normalizeCode(inner);
32
- }
33
- if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
34
- const last = ast.body[ast.body.length - 1];
35
- if (last?.type === "ExpressionStatement") {
36
- const exprStmt = last;
37
- return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
38
- }
39
- return `async () => {\n${source}\n}`;
40
- } catch {
41
- return `async () => {\n${source}\n}`;
42
- }
43
- }
44
- //#endregion
45
- //#region src/tool-types.ts
46
- /**
47
- * Check if a value is a Zod schema (has _zod property).
48
- */
49
- function isZodSchema(value) {
50
- return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
51
- }
52
- /**
53
- * Check if a value conforms to the Standard Schema protocol (~standard).
54
- * This catches Zod v3 schemas (which expose ~standard but not _zod).
55
- */
56
- function isStandardSchema(value) {
57
- return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
58
- }
59
- /**
60
- * Check if a value is an AI SDK jsonSchema wrapper.
61
- * The jsonSchema wrapper has a [Symbol] with jsonSchema property.
62
- */
63
- function isJsonSchemaWrapper(value) {
64
- if (value === null || typeof value !== "object") return false;
65
- if ("jsonSchema" in value) return true;
66
- const symbols = Object.getOwnPropertySymbols(value);
67
- for (const sym of symbols) {
68
- const symValue = value[sym];
69
- if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return true;
70
- }
71
- return false;
72
- }
73
- /**
74
- * Extract JSON schema from an AI SDK jsonSchema wrapper.
75
- */
76
- function extractJsonSchema(wrapper) {
77
- if (wrapper === null || typeof wrapper !== "object") return null;
78
- if ("jsonSchema" in wrapper) return wrapper.jsonSchema;
79
- const symbols = Object.getOwnPropertySymbols(wrapper);
80
- for (const sym of symbols) {
81
- const symValue = wrapper[sym];
82
- if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return symValue.jsonSchema;
83
- }
84
- return null;
85
- }
86
- /**
87
- * Extract field descriptions from a schema.
88
- * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).
89
- */
90
- function extractDescriptions(schema) {
91
- const descriptions = {};
92
- const shape = schema.shape;
93
- if (shape && typeof shape === "object") {
94
- for (const [fieldName, fieldSchema] of Object.entries(shape)) {
95
- let s = fieldSchema;
96
- while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
97
- if (s.description) descriptions[fieldName] = s.description;
98
- }
99
- return descriptions;
100
- }
101
- if (isJsonSchemaWrapper(schema)) {
102
- const jsonSchema = extractJsonSchema(schema);
103
- if (jsonSchema?.properties) {
104
- for (const [fieldName, propSchema] of Object.entries(jsonSchema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
105
- }
106
- }
107
- return descriptions;
108
- }
109
- /**
110
- * Extract field descriptions from a schema and format as @param lines.
111
- */
112
- function extractParamDescriptions(schema) {
113
- const descriptions = extractDescriptions(schema);
114
- return Object.entries(descriptions).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
115
- }
116
- /**
117
- * Safely convert a schema to TypeScript type string.
118
- * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
119
- */
120
- function safeSchemaToTs(schema, typeName) {
121
- try {
122
- if (isZodSchema(schema) || isStandardSchema(schema)) {
123
- const jsonSchema = asSchema(schema).jsonSchema;
124
- if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
125
- root: jsonSchema,
126
- depth: 0,
127
- seen: /* @__PURE__ */ new Set(),
128
- maxDepth: 20
129
- })}`;
130
- }
131
- if (isJsonSchemaWrapper(schema)) {
132
- const jsonSchema = extractJsonSchema(schema);
133
- if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
134
- root: jsonSchema,
135
- depth: 0,
136
- seen: /* @__PURE__ */ new Set(),
137
- maxDepth: 20
138
- })}`;
139
- }
140
- return `type ${typeName} = unknown`;
141
- } catch {
142
- return `type ${typeName} = unknown`;
143
- }
144
- }
145
- /**
146
- * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
147
- * These types can be included in tool descriptions to help LLMs write correct code.
148
- *
149
- * Requires the `ai` peer dependency. For a version that works with plain JSON Schema
150
- * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
151
- */
152
- function generateTypes(tools, namespace = "codemode") {
153
- let availableTools = "";
154
- let availableTypes = "";
155
- for (const [toolName, tool] of Object.entries(tools)) {
156
- const safeName = sanitizeToolName(toolName);
157
- const typeName = toPascalCase(safeName);
158
- try {
159
- const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
160
- const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
161
- const description = tool.description;
162
- const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);
163
- const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
164
- availableTypes += `\n${inputType.trim()}`;
165
- availableTypes += `\n${outputType.trim()}`;
166
- const paramDescs = (() => {
167
- try {
168
- return inputSchema ? extractParamDescriptions(inputSchema) : [];
169
- } catch {
170
- return [];
171
- }
172
- })();
173
- const jsdocLines = [];
174
- if (description?.trim()) jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
175
- else jsdocLines.push(escapeJsDoc(toolName));
176
- for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
177
- const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
178
- availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
179
- availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
180
- availableTools += "\n";
181
- } catch {
182
- availableTypes += `\ntype ${typeName}Input = unknown`;
183
- availableTypes += `\ntype ${typeName}Output = unknown`;
184
- availableTools += `\n\t/**\n\t * ${escapeJsDoc(toolName)}\n\t */`;
185
- availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
186
- availableTools += "\n";
187
- }
188
- }
189
- availableTools = `\ndeclare const ${namespace}: {${availableTools}}`;
190
- return `
191
- ${availableTypes}
192
- ${availableTools}
193
- `.trim();
194
- }
195
- //#endregion
196
- //#region src/tool.ts
197
- const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
198
-
199
- Available:
200
- {{types}}
201
-
202
- Write an async arrow function in JavaScript that returns the result.
203
- Do NOT use TypeScript syntax — no type annotations, interfaces, or generics.
204
- Do NOT define named functions then call them — just write the arrow function body directly.
205
-
206
- Example: async () => { const r = await codemode.searchWeb({ query: "test" }); return r; }`;
207
- const codeSchema = z.object({ code: z.string().describe("JavaScript async arrow function to execute") });
208
- /**
209
- * Create a codemode tool that allows LLMs to write and execute code
210
- * with access to your tools in a sandboxed environment.
211
- *
212
- * Returns an AI SDK compatible tool.
213
- *
214
- * @example Raw tools (backwards compatible)
215
- * ```ts
216
- * createCodeTool({ tools: myToolSet, executor });
217
- * ```
218
- *
219
- * @example ToolProvider array with namespaces
220
- * ```ts
221
- * createCodeTool({
222
- * tools: [
223
- * { name: "github", tools: githubTools },
224
- * { name: "state", tools: stateTools },
225
- * { tools: aiTools }, // default "codemode" namespace
226
- * ],
227
- * executor,
228
- * });
229
- * ```
230
- */
231
- function hasNeedsApproval(t) {
232
- return "needsApproval" in t && t.needsApproval != null;
233
- }
234
- /**
235
- * Check if the tools option is an array of ToolProviders.
236
- * A plain ToolSet/ToolDescriptors is a Record (not an array).
237
- */
238
- function isToolProviderArray(tools) {
239
- return Array.isArray(tools);
240
- }
241
- /**
242
- * Normalize the tools option into a list of ToolProviders.
243
- * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.
244
- */
245
- function normalizeProviders(tools) {
246
- if (isToolProviderArray(tools)) return tools;
247
- return [{ tools }];
248
- }
249
- /**
250
- * Filter out tools with needsApproval and return a clean copy.
251
- */
252
- function filterTools(tools) {
253
- const filtered = {};
254
- for (const [name, t] of Object.entries(tools)) if (!hasNeedsApproval(t)) filtered[name] = t;
255
- return filtered;
256
- }
257
- /**
258
- * Extract execute functions from tools, keyed by name.
259
- * Wraps each with schema validation when available.
260
- * Note: tool name sanitization happens in the executor, not here.
261
- */
262
- function extractFns(tools) {
263
- const fns = {};
264
- for (const [name, t] of Object.entries(tools)) {
265
- const execute = "execute" in t ? t.execute : void 0;
266
- if (execute) {
267
- const rawSchema = "inputSchema" in t ? t.inputSchema : "parameters" in t ? t.parameters : void 0;
268
- const schema = rawSchema != null ? asSchema(rawSchema) : void 0;
269
- fns[name] = schema?.validate ? async (args) => {
270
- const result = await schema.validate(args);
271
- if (!result.success) throw result.error;
272
- return execute(result.value);
273
- } : execute;
274
- }
275
- }
276
- return fns;
277
- }
278
- /**
279
- * Resolve a ToolProvider into a ResolvedProvider ready for execution.
280
- * Filters out tools with `needsApproval`, validates schemas, and sanitizes names.
281
- */
282
- /**
283
- * Wrap raw AI SDK tools into a ToolProvider under the default "codemode" namespace.
284
- *
285
- * @example
286
- * ```ts
287
- * createCodeTool({
288
- * tools: [stateTools(workspace), aiTools(myTools)],
289
- * executor,
290
- * });
291
- * ```
292
- */
293
- function aiTools(tools) {
294
- return { tools };
295
- }
296
- function resolveProvider(provider) {
297
- const resolved = {
298
- name: provider.name ?? "codemode",
299
- fns: extractFns(filterTools(provider.tools))
300
- };
301
- if (provider.positionalArgs) resolved.positionalArgs = true;
302
- return resolved;
303
- }
304
- function createCodeTool(options) {
305
- const providers = normalizeProviders(options.tools);
306
- const typeBlocks = [];
307
- const resolvedProviders = [];
308
- for (const provider of providers) {
309
- const name = provider.name ?? "codemode";
310
- const filtered = filterTools(provider.tools);
311
- const types = provider.types ?? generateTypes(filtered, name);
312
- typeBlocks.push(types);
313
- resolvedProviders.push({
314
- name,
315
- fns: extractFns(filtered)
316
- });
317
- }
318
- const typeBlock = typeBlocks.filter(Boolean).join("\n\n");
319
- const executor = options.executor;
320
- return tool({
321
- description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
322
- inputSchema: codeSchema,
323
- execute: async ({ code }) => {
324
- const normalizedCode = normalizeCode(code);
325
- const executeResult = await executor.execute(normalizedCode, resolvedProviders);
326
- if (executeResult.error) {
327
- const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
328
- throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
329
- }
330
- const output = {
331
- code,
332
- result: executeResult.result
333
- };
334
- if (executeResult.logs) output.logs = executeResult.logs;
335
- return output;
336
- }
337
- });
338
- }
339
- //#endregion
340
- export { normalizeCode as a, generateTypes as i, createCodeTool as n, resolveProvider as r, aiTools as t };
341
-
342
- //# sourceMappingURL=tool-B0ZYASro.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tool-B0ZYASro.js","names":[],"sources":["../src/normalize.ts","../src/tool-types.ts","../src/tool.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","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 Executor,\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nconst 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\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\ntype CodeInput = z.infer<typeof codeSchema>;\ntype CodeOutput = { code: string; result: unknown; logs?: string[] };\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 an AI SDK compatible tool.\n *\n * @example Raw tools (backwards compatible)\n * ```ts\n * createCodeTool({ tools: myToolSet, executor });\n * ```\n *\n * @example ToolProvider array with namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"state\", tools: stateTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * ```\n */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\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 */\nfunction normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nfunction 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 * Wraps each with schema validation when available.\n * Note: tool name sanitization happens in the executor, not here.\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 * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`, validates schemas, and sanitizes names.\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\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":";;;;;;;;;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;AAE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as ToolProvider,
6
- u as ToolDescriptors
7
- } from "./executor-C1NPN-nW.js";
8
- import { Tool, ToolSet } from "ai";
9
- import { z } from "zod";
10
-
11
- //#region src/tool.d.ts
12
- interface CreateCodeToolOptions {
13
- tools: ToolProviderTools | ToolProvider[];
14
- executor: Executor;
15
- /**
16
- * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.
17
- */
18
- description?: string;
19
- }
20
- declare const codeSchema: z.ZodObject<
21
- {
22
- code: z.ZodString;
23
- },
24
- z.core.$strip
25
- >;
26
- type CodeInput = z.infer<typeof codeSchema>;
27
- type CodeOutput = {
28
- code: string;
29
- result: unknown;
30
- logs?: string[];
31
- };
32
- /**
33
- * Resolve a ToolProvider into a ResolvedProvider ready for execution.
34
- * Filters out tools with `needsApproval`, validates schemas, and sanitizes names.
35
- */
36
- /**
37
- * Wrap raw AI SDK tools into a ToolProvider under the default "codemode" namespace.
38
- *
39
- * @example
40
- * ```ts
41
- * createCodeTool({
42
- * tools: [stateTools(workspace), aiTools(myTools)],
43
- * executor,
44
- * });
45
- * ```
46
- */
47
- declare function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider;
48
- declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
49
- declare function createCodeTool(
50
- options: CreateCodeToolOptions
51
- ): Tool<CodeInput, CodeOutput>;
52
- //#endregion
53
- export {
54
- resolveProvider as i,
55
- aiTools as n,
56
- createCodeTool as r,
57
- CreateCodeToolOptions as t
58
- };
59
- //# sourceMappingURL=tool-BQ5SO4OJ.d.ts.map