@cloudflare/codemode 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
 
@@ -47,9 +50,7 @@ const tools = {
47
50
  };
48
51
 
49
52
  // 2. Create an executor (runs code in an isolated Worker)
50
- const executor = new DynamicWorkerExecutor({
51
- loader: env.LOADER
52
- });
53
+ const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
53
54
 
54
55
  // 3. Create the codemode tool
55
56
  const codemode = createCodeTool({ tools, executor });
@@ -79,31 +80,144 @@ async () => {
79
80
  };
80
81
  ```
81
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
+
129
+ ## Tool Providers
130
+
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.
132
+
133
+ ```ts
134
+ import { createCodeTool } from "@cloudflare/codemode/ai";
135
+ import { DynamicWorkerExecutor } from "@cloudflare/codemode";
136
+ import { stateTools } from "@cloudflare/shell/workers";
137
+
138
+ const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
139
+
140
+ const codemode = createCodeTool({
141
+ tools: [
142
+ { tools: myTools }, // codemode.myTool({ query: "test" })
143
+ stateTools(workspace) // state.readFile("/path")
144
+ ],
145
+ executor
146
+ });
147
+ ```
148
+
149
+ The sandbox has both `codemode.*` and `state.*`:
150
+
151
+ ```js
152
+ async () => {
153
+ const files = await state.glob("/src/**/*.ts");
154
+ const results = await Promise.all(
155
+ files.map((f) => codemode.analyzeFile({ path: f }))
156
+ );
157
+ await state.writeJson("/report.json", results);
158
+ return results.length;
159
+ };
160
+ ```
161
+
162
+ ### The `ToolProvider` interface
163
+
164
+ Any package can provide tools to the sandbox. A `ToolProvider` describes:
165
+
166
+ - an optional **name** (the namespace in the sandbox, e.g. `"state"`, `"db"` — defaults to `"codemode"`)
167
+ - **tools** — AI SDK tools, tool descriptors, or simple `{ execute }` records
168
+ - optional **types** for LLM context (auto-generated from tools if omitted)
169
+ - optional **positionalArgs** flag (e.g. `state.readFile("/path")` vs `codemode.search({ query })`)
170
+
171
+ ```ts
172
+ import type { ToolProvider } from "@cloudflare/codemode";
173
+
174
+ const dbProvider: ToolProvider = {
175
+ name: "db",
176
+ tools: {
177
+ query: {
178
+ description: "Run a SQL query",
179
+ execute: async (sql: unknown) => db.prepare(sql as string).all()
180
+ }
181
+ },
182
+ positionalArgs: true
183
+ };
184
+ ```
185
+
186
+ Pass providers as the `tools` array in `createCodeTool`, or resolve them for direct executor use:
187
+
188
+ ```ts
189
+ import { resolveProvider } from "@cloudflare/codemode";
190
+
191
+ await executor.execute(code, [resolveProvider(dbProvider)]);
192
+ ```
193
+
82
194
  ## Architecture
83
195
 
84
196
  ### How it works
85
197
 
86
198
  ```
87
- ┌─────────────┐ ┌──────────────────────────────────────┐
88
- │ │ │ Dynamic Worker (isolated sandbox) │
89
- │ Host │ RPC │ │
90
- │ Worker │◄──────►│ LLM-generated code runs here │
91
- │ │ │ codemode.myTool() → dispatcher.call()│
92
- │ ToolDispatcher │ │
93
- │ holds tool fns │ fetch() blocked by default │
94
- └─────────────┘ └──────────────────────────────────────┘
199
+ ┌─────────────────────┐ ┌─────────────────────────────────────────────┐
200
+ │ │ │ Dynamic Worker (isolated sandbox) │
201
+ │ Host Worker │ RPC │ │
202
+ │ │◄──────►│ LLM-generated code runs here │
203
+ │ ToolDispatchers │ │ codemode.myTool() → dispatcher.call() │
204
+ │ (one per namespace)│ │ state.readFile() → dispatcher.call() │
205
+ │ │ │ db.query() → dispatcher.call() │
206
+ │ │ │ │
207
+ │ │ │ fetch() blocked by default │
208
+ └─────────────────────┘ └─────────────────────────────────────────────┘
95
209
  ```
96
210
 
97
- 1. `createCodeTool` generates TypeScript type definitions from your tools and builds a description the LLM can read
98
- 2. The LLM writes an async arrow function that calls `codemode.toolName(args)`
211
+ 1. `createCodeTool` generates TypeScript type definitions from your tool providers and builds a description the LLM can read
212
+ 2. The LLM writes an async arrow function that calls `codemode.toolName(args)` and any provider namespaces (`state.*`, `db.*`, etc.)
99
213
  3. Code is normalized via AST parsing (acorn) and sent to the executor
100
- 4. `DynamicWorkerExecutor` spins up an isolated Worker via `WorkerLoader`
101
- 5. Inside the sandbox, a `Proxy` intercepts `codemode.*` calls and routes them back to the host via Workers RPC (`ToolDispatcher extends RpcTarget`)
214
+ 4. `DynamicWorkerExecutor` spins up an isolated Worker via `WorkerLoader`, with one `ToolDispatcher` per namespace
215
+ 5. Inside the sandbox, a `Proxy` per namespace intercepts calls and routes them back via Workers RPC
102
216
  6. Console output is captured and returned alongside the result
103
217
 
104
218
  ### Network isolation
105
219
 
106
- External `fetch()` and `connect()` are **blocked by default** — enforced at the Workers runtime level via `globalOutbound: null`. Sandboxed code can only interact with the host through `codemode.*` tool calls.
220
+ External `fetch()` and `connect()` are **blocked by default** — enforced at the Workers runtime level via `globalOutbound: null`. Sandboxed code can only interact with the host through namespaced tool calls.
107
221
 
108
222
  To allow controlled outbound access, pass a `Fetcher`:
109
223
 
@@ -123,7 +237,9 @@ The `Executor` interface is deliberately minimal — implement it to run code in
123
237
  interface Executor {
124
238
  execute(
125
239
  code: string,
126
- fns: Record<string, (...args: unknown[]) => Promise<unknown>>
240
+ providers:
241
+ | ResolvedProvider[]
242
+ | Record<string, (...args: unknown[]) => Promise<unknown>>
127
243
  ): Promise<ExecuteResult>;
128
244
  }
129
245
 
@@ -165,11 +281,12 @@ class NodeVMExecutor implements Executor {
165
281
 
166
282
  ### DynamicWorkerExecutor options
167
283
 
168
- | Option | Type | Default | Description |
169
- | ---------------- | ----------------- | -------- | ------------------------------------------------------------ |
170
- | `loader` | `WorkerLoader` | required | Worker Loader binding from `env.LOADER` |
171
- | `timeout` | `number` | `30000` | Execution timeout in ms |
172
- | `globalOutbound` | `Fetcher \| null` | `null` | Network access control. `null` = blocked, `Fetcher` = routed |
284
+ | Option | Type | Default | Description |
285
+ | ---------------- | ------------------------ | -------- | ------------------------------------------------------------ |
286
+ | `loader` | `WorkerLoader` | required | Worker Loader binding from `env.LOADER` |
287
+ | `timeout` | `number` | `30000` | Execution timeout in ms |
288
+ | `globalOutbound` | `Fetcher \| null` | `null` | Network access control. `null` = blocked, `Fetcher` = routed |
289
+ | `modules` | `Record<string, string>` | `{}` | Extra modules importable in the sandbox |
173
290
 
174
291
  ### createCodeTool options
175
292
 
@@ -191,14 +308,9 @@ import { streamText, convertToModelMessages, stepCountIs } from "ai";
191
308
 
192
309
  export class MyAgent extends Agent<Env, State> {
193
310
  async onChatMessage() {
194
- const executor = new DynamicWorkerExecutor({
195
- loader: this.env.LOADER
196
- });
311
+ const executor = new DynamicWorkerExecutor({ loader: this.env.LOADER });
197
312
 
198
- const codemode = createCodeTool({
199
- tools: myTools,
200
- executor
201
- });
313
+ const codemode = createCodeTool({ tools: myTools, executor });
202
314
 
203
315
  const result = streamText({
204
316
  model,
@@ -213,6 +325,29 @@ export class MyAgent extends Agent<Env, State> {
213
325
  }
214
326
  ```
215
327
 
328
+ ### With filesystem access (via `@cloudflare/shell`)
329
+
330
+ Combine `codemode.*` tools with `state.*` filesystem operations:
331
+
332
+ ```ts
333
+ import { createCodeTool } from "@cloudflare/codemode/ai";
334
+ import { DynamicWorkerExecutor } from "@cloudflare/codemode";
335
+ import { Workspace } from "@cloudflare/shell";
336
+ import { stateTools } from "@cloudflare/shell/workers";
337
+
338
+ export class MyAgent extends Agent<Env> {
339
+ workspace = new Workspace(this);
340
+
341
+ getCodemodeTool() {
342
+ const executor = new DynamicWorkerExecutor({ loader: this.env.LOADER });
343
+ return createCodeTool({
344
+ tools: [{ tools: myDomainTools }, stateTools(this.workspace)],
345
+ executor
346
+ });
347
+ }
348
+ }
349
+ ```
350
+
216
351
  ### With MCP tools
217
352
 
218
353
  MCP tools work the same way — just merge them into the tool set:
@@ -288,10 +423,11 @@ const types = generateTypes(myAiSdkTools);
288
423
 
289
424
  ## Module Structure
290
425
 
291
- | Module | Requires `ai`/`zod` | Exports |
292
- | ------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
293
- | `@cloudflare/codemode` | No | `sanitizeToolName`, `normalizeCode`, `generateTypesFromJsonSchema`, `jsonSchemaToType`, `DynamicWorkerExecutor`, `ToolDispatcher` |
294
- | `@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` |
295
431
 
296
432
  ## Limitations
297
433
 
package/dist/ai.d.ts CHANGED
@@ -1,54 +1,48 @@
1
- import { i as Executor } from "./executor-6RSFUhUk.js";
1
+ import {
2
+ a as ResolvedProvider,
3
+ d as generateTypes,
4
+ l as ToolDescriptor,
5
+ s as ToolProvider,
6
+ u as ToolDescriptors
7
+ } from "./executor-wZjYdqEX.js";
8
+ import {
9
+ n as CodeOutput,
10
+ r as CreateCodeToolOptions,
11
+ t as CodeInput
12
+ } from "./shared-Hnh_Idta.js";
2
13
  import { Tool, ToolSet } from "ai";
3
- import { ZodType, z } from "zod";
4
14
 
5
- //#region src/tool-types.d.ts
6
- interface ToolDescriptor {
7
- description?: string;
8
- inputSchema: ZodType;
9
- outputSchema?: ZodType;
10
- execute?: (args: unknown) => Promise<unknown>;
11
- }
12
- type ToolDescriptors = Record<string, ToolDescriptor>;
15
+ //#region src/tool.d.ts
13
16
  /**
14
- * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
15
- * These types can be included in tool descriptions to help LLMs write correct code.
17
+ * Wrap raw AI SDK tools into a ToolProvider under the default "codemode" namespace.
16
18
  *
17
- * Requires the `ai` peer dependency. For a version that works with plain JSON Schema
18
- * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
19
+ * @example
20
+ * ```ts
21
+ * createCodeTool({
22
+ * tools: [stateTools(workspace), aiTools(myTools)],
23
+ * executor,
24
+ * });
25
+ * ```
19
26
  */
20
- declare function generateTypes(tools: ToolDescriptors | ToolSet): string;
21
- //#endregion
22
- //#region src/tool.d.ts
23
- interface CreateCodeToolOptions {
24
- tools: ToolDescriptors | ToolSet;
25
- executor: Executor;
26
- /**
27
- * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.
28
- */
29
- description?: string;
30
- }
31
- declare const codeSchema: z.ZodObject<
32
- {
33
- code: z.ZodString;
34
- },
35
- z.core.$strip
36
- >;
37
- type CodeInput = z.infer<typeof codeSchema>;
38
- type CodeOutput = {
39
- code: string;
40
- result: unknown;
41
- logs?: string[];
42
- };
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;
43
33
  declare function createCodeTool(
44
34
  options: CreateCodeToolOptions
45
35
  ): Tool<CodeInput, CodeOutput>;
46
36
  //#endregion
47
37
  export {
38
+ type CodeInput,
39
+ type CodeOutput,
48
40
  type CreateCodeToolOptions,
49
41
  type ToolDescriptor,
50
42
  type ToolDescriptors,
43
+ aiTools,
51
44
  createCodeTool,
52
- generateTypes
45
+ generateTypes,
46
+ resolveProvider
53
47
  };
54
48
  //# sourceMappingURL=ai.d.ts.map
package/dist/ai.js CHANGED
@@ -1,5 +1,6 @@
1
- import { t as normalizeCode } from "./normalize-DnrE6oKV.js";
1
+ import { i as normalizeCode, n as filterTools } from "./resolve-DIQRkRqQ.js";
2
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";
3
4
  import { asSchema, tool } from "ai";
4
5
  import { z } from "zod";
5
6
  //#region src/tool-types.ts
@@ -109,7 +110,7 @@ function safeSchemaToTs(schema, typeName) {
109
110
  * Requires the `ai` peer dependency. For a version that works with plain JSON Schema
110
111
  * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
111
112
  */
112
- function generateTypes(tools) {
113
+ function generateTypes(tools, namespace = "codemode") {
113
114
  let availableTools = "";
114
115
  let availableTypes = "";
115
116
  for (const [toolName, tool] of Object.entries(tools)) {
@@ -146,7 +147,7 @@ function generateTypes(tools) {
146
147
  availableTools += "\n";
147
148
  }
148
149
  }
149
- availableTools = `\ndeclare const codemode: {${availableTools}}`;
150
+ availableTools = `\ndeclare const ${namespace}: {${availableTools}}`;
150
151
  return `
151
152
  ${availableTypes}
152
153
  ${availableTools}
@@ -154,50 +155,75 @@ ${availableTools}
154
155
  }
155
156
  //#endregion
156
157
  //#region src/tool.ts
157
- const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
158
-
159
- Available:
160
- {{types}}
161
-
162
- Write an async arrow function in JavaScript that returns the result.
163
- Do NOT use TypeScript syntax — no type annotations, interfaces, or generics.
164
- Do NOT define named functions then call them — just write the arrow function body directly.
165
-
166
- Example: async () => { const r = await codemode.searchWeb({ query: "test" }); return r; }`;
167
158
  const codeSchema = z.object({ code: z.string().describe("JavaScript async arrow function to execute") });
168
159
  /**
169
- * Create a codemode tool that allows LLMs to write and execute code
170
- * with access to your tools in a sandboxed environment.
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.
171
181
  *
172
- * Returns an AI SDK compatible tool.
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`.
173
196
  */
174
- function hasNeedsApproval(t) {
175
- return "needsApproval" in t && t.needsApproval != null;
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;
176
204
  }
177
205
  function createCodeTool(options) {
178
- const tools = {};
179
- for (const [name, t] of Object.entries(options.tools)) if (!hasNeedsApproval(t)) tools[name] = t;
180
- const types = generateTypes(tools);
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");
181
220
  const executor = options.executor;
182
221
  return tool({
183
- description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", types),
222
+ description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
184
223
  inputSchema: codeSchema,
185
224
  execute: async ({ code }) => {
186
- const fns = {};
187
- for (const [name, t] of Object.entries(tools)) {
188
- const execute = "execute" in t ? t.execute : void 0;
189
- if (execute) {
190
- const rawSchema = "inputSchema" in t ? t.inputSchema : "parameters" in t ? t.parameters : void 0;
191
- const schema = rawSchema != null ? asSchema(rawSchema) : void 0;
192
- fns[sanitizeToolName(name)] = schema?.validate ? async (args) => {
193
- const result = await schema.validate(args);
194
- if (!result.success) throw result.error;
195
- return execute(result.value);
196
- } : execute;
197
- }
198
- }
199
225
  const normalizedCode = normalizeCode(code);
200
- const executeResult = await executor.execute(normalizedCode, fns);
226
+ const executeResult = await executor.execute(normalizedCode, resolvedProviders);
201
227
  if (executeResult.error) {
202
228
  const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
203
229
  throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
@@ -212,6 +238,6 @@ function createCodeTool(options) {
212
238
  });
213
239
  }
214
240
  //#endregion
215
- export { createCodeTool, generateTypes };
241
+ export { aiTools, createCodeTool, generateTypes, resolveProvider };
216
242
 
217
243
  //# sourceMappingURL=ai.js.map
package/dist/ai.js.map CHANGED
@@ -1 +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(tools: ToolDescriptors | ToolSet): 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 codemode: {${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 { sanitizeToolName } from \"./utils\";\nimport type { Executor } 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: ToolDescriptors | ToolSet;\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 */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const tools: ToolDescriptors | ToolSet = {};\n for (const [name, t] of Object.entries(options.tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n (tools as Record<string, unknown>)[name] = t;\n }\n }\n\n const types = generateTypes(tools);\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n // Extract execute functions from tools, keyed by name.\n // Wrap each with its schema so arguments from the sandbox\n // are validated before reaching the tool function.\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 // Use AI SDK's asSchema() to normalize any schema type\n // (Zod v3/v4, Standard Schema, JSON Schema) into a unified\n // Schema with an optional .validate() method.\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[sanitizeToolName(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 const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(normalizedCode, fns);\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,iBAAiB,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C,aAAa;EACb,SAAS,OAAO,EAAE,WAAW;GAI3B,MAAM,MAAgE,EAAE;AAExE,QAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAAE;IAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH,KAAA;AACN,QAAI,SAAS;KACX,MAAM,YACJ,iBAAiB,IACb,EAAE,cACF,gBAAgB,IACb,EAA8B,aAC/B,KAAA;KAKR,MAAM,SAAS,aAAa,OAAO,SAAS,UAAU,GAAG,KAAA;AAEzD,SAAI,iBAAiB,KAAK,IAAI,QAAQ,WAClC,OAAO,SAAkB;MACvB,MAAM,SAAS,MAAM,OAAO,SAAU,KAAK;AAC3C,UAAI,CAAC,OAAO,QAAS,OAAM,OAAO;AAClC,aAAO,QAAQ,OAAO,MAAM;SAE9B;;;GAIR,MAAM,iBAAiB,cAAc,KAAK;GAE1C,MAAM,gBAAgB,MAAM,SAAS,QAAQ,gBAAgB,IAAI;AAEjE,OAAI,cAAc,OAAO;IACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;AACJ,UAAM,IAAI,MACR,0BAA0B,cAAc,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;AACjE,OAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
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,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