@cloudflare/codemode 0.2.0 → 0.2.2
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 +121 -35
- package/dist/ai.d.ts +14 -48
- package/dist/ai.js +2 -216
- package/dist/executor-C1NPN-nW.d.ts +186 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +72 -23
- package/dist/index.js.map +1 -1
- package/dist/{normalize-xNh5CsfI.js → json-schema-types-DoQ0VISs.js} +2 -43
- package/dist/json-schema-types-DoQ0VISs.js.map +1 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +314 -0
- package/dist/mcp.js.map +1 -0
- package/dist/tool-B0ZYASro.js +342 -0
- package/dist/tool-B0ZYASro.js.map +1 -0
- package/dist/tool-BQ5SO4OJ.d.ts +59 -0
- package/package.json +11 -1
- package/dist/ai.js.map +0 -1
- package/dist/executor-BjlGw-Dd.d.ts +0 -70
- package/dist/normalize-xNh5CsfI.js.map +0 -1
package/README.md
CHANGED
|
@@ -47,9 +47,7 @@ const tools = {
|
|
|
47
47
|
};
|
|
48
48
|
|
|
49
49
|
// 2. Create an executor (runs code in an isolated Worker)
|
|
50
|
-
const executor = new DynamicWorkerExecutor({
|
|
51
|
-
loader: env.LOADER
|
|
52
|
-
});
|
|
50
|
+
const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
|
|
53
51
|
|
|
54
52
|
// 3. Create the codemode tool
|
|
55
53
|
const codemode = createCodeTool({ tools, executor });
|
|
@@ -79,31 +77,98 @@ async () => {
|
|
|
79
77
|
};
|
|
80
78
|
```
|
|
81
79
|
|
|
80
|
+
## Tool Providers
|
|
81
|
+
|
|
82
|
+
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.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { createCodeTool } from "@cloudflare/codemode/ai";
|
|
86
|
+
import { DynamicWorkerExecutor } from "@cloudflare/codemode";
|
|
87
|
+
import { stateTools } from "@cloudflare/shell/workers";
|
|
88
|
+
|
|
89
|
+
const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
|
|
90
|
+
|
|
91
|
+
const codemode = createCodeTool({
|
|
92
|
+
tools: [
|
|
93
|
+
{ tools: myTools }, // codemode.myTool({ query: "test" })
|
|
94
|
+
stateTools(workspace) // state.readFile("/path")
|
|
95
|
+
],
|
|
96
|
+
executor
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The sandbox has both `codemode.*` and `state.*`:
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
async () => {
|
|
104
|
+
const files = await state.glob("/src/**/*.ts");
|
|
105
|
+
const results = await Promise.all(
|
|
106
|
+
files.map((f) => codemode.analyzeFile({ path: f }))
|
|
107
|
+
);
|
|
108
|
+
await state.writeJson("/report.json", results);
|
|
109
|
+
return results.length;
|
|
110
|
+
};
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### The `ToolProvider` interface
|
|
114
|
+
|
|
115
|
+
Any package can provide tools to the sandbox. A `ToolProvider` describes:
|
|
116
|
+
|
|
117
|
+
- an optional **name** (the namespace in the sandbox, e.g. `"state"`, `"db"` — defaults to `"codemode"`)
|
|
118
|
+
- **tools** — AI SDK tools, tool descriptors, or simple `{ execute }` records
|
|
119
|
+
- optional **types** for LLM context (auto-generated from tools if omitted)
|
|
120
|
+
- optional **positionalArgs** flag (e.g. `state.readFile("/path")` vs `codemode.search({ query })`)
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import type { ToolProvider } from "@cloudflare/codemode";
|
|
124
|
+
|
|
125
|
+
const dbProvider: ToolProvider = {
|
|
126
|
+
name: "db",
|
|
127
|
+
tools: {
|
|
128
|
+
query: {
|
|
129
|
+
description: "Run a SQL query",
|
|
130
|
+
execute: async (sql: unknown) => db.prepare(sql as string).all()
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
positionalArgs: true
|
|
134
|
+
};
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Pass providers as the `tools` array in `createCodeTool`, or resolve them for direct executor use:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import { resolveProvider } from "@cloudflare/codemode";
|
|
141
|
+
|
|
142
|
+
await executor.execute(code, [resolveProvider(dbProvider)]);
|
|
143
|
+
```
|
|
144
|
+
|
|
82
145
|
## Architecture
|
|
83
146
|
|
|
84
147
|
### How it works
|
|
85
148
|
|
|
86
149
|
```
|
|
87
|
-
|
|
88
|
-
│
|
|
89
|
-
│ Host
|
|
90
|
-
│
|
|
91
|
-
│
|
|
92
|
-
│
|
|
93
|
-
│
|
|
94
|
-
|
|
150
|
+
┌─────────────────────┐ ┌─────────────────────────────────────────────┐
|
|
151
|
+
│ │ │ Dynamic Worker (isolated sandbox) │
|
|
152
|
+
│ Host Worker │ RPC │ │
|
|
153
|
+
│ │◄──────►│ LLM-generated code runs here │
|
|
154
|
+
│ ToolDispatchers │ │ codemode.myTool() → dispatcher.call() │
|
|
155
|
+
│ (one per namespace)│ │ state.readFile() → dispatcher.call() │
|
|
156
|
+
│ │ │ db.query() → dispatcher.call() │
|
|
157
|
+
│ │ │ │
|
|
158
|
+
│ │ │ fetch() blocked by default │
|
|
159
|
+
└─────────────────────┘ └─────────────────────────────────────────────┘
|
|
95
160
|
```
|
|
96
161
|
|
|
97
|
-
1. `createCodeTool` generates TypeScript type definitions from your
|
|
98
|
-
2. The LLM writes an async arrow function that calls `codemode.toolName(args)`
|
|
162
|
+
1. `createCodeTool` generates TypeScript type definitions from your tool providers and builds a description the LLM can read
|
|
163
|
+
2. The LLM writes an async arrow function that calls `codemode.toolName(args)` and any provider namespaces (`state.*`, `db.*`, etc.)
|
|
99
164
|
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
|
|
165
|
+
4. `DynamicWorkerExecutor` spins up an isolated Worker via `WorkerLoader`, with one `ToolDispatcher` per namespace
|
|
166
|
+
5. Inside the sandbox, a `Proxy` per namespace intercepts calls and routes them back via Workers RPC
|
|
102
167
|
6. Console output is captured and returned alongside the result
|
|
103
168
|
|
|
104
169
|
### Network isolation
|
|
105
170
|
|
|
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
|
|
171
|
+
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
172
|
|
|
108
173
|
To allow controlled outbound access, pass a `Fetcher`:
|
|
109
174
|
|
|
@@ -123,7 +188,9 @@ The `Executor` interface is deliberately minimal — implement it to run code in
|
|
|
123
188
|
interface Executor {
|
|
124
189
|
execute(
|
|
125
190
|
code: string,
|
|
126
|
-
|
|
191
|
+
providers:
|
|
192
|
+
| ResolvedProvider[]
|
|
193
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
127
194
|
): Promise<ExecuteResult>;
|
|
128
195
|
}
|
|
129
196
|
|
|
@@ -165,11 +232,12 @@ class NodeVMExecutor implements Executor {
|
|
|
165
232
|
|
|
166
233
|
### DynamicWorkerExecutor options
|
|
167
234
|
|
|
168
|
-
| Option | Type
|
|
169
|
-
| ---------------- |
|
|
170
|
-
| `loader` | `WorkerLoader`
|
|
171
|
-
| `timeout` | `number`
|
|
172
|
-
| `globalOutbound` | `Fetcher \| null`
|
|
235
|
+
| Option | Type | Default | Description |
|
|
236
|
+
| ---------------- | ------------------------ | -------- | ------------------------------------------------------------ |
|
|
237
|
+
| `loader` | `WorkerLoader` | required | Worker Loader binding from `env.LOADER` |
|
|
238
|
+
| `timeout` | `number` | `30000` | Execution timeout in ms |
|
|
239
|
+
| `globalOutbound` | `Fetcher \| null` | `null` | Network access control. `null` = blocked, `Fetcher` = routed |
|
|
240
|
+
| `modules` | `Record<string, string>` | `{}` | Extra modules importable in the sandbox |
|
|
173
241
|
|
|
174
242
|
### createCodeTool options
|
|
175
243
|
|
|
@@ -191,14 +259,9 @@ import { streamText, convertToModelMessages, stepCountIs } from "ai";
|
|
|
191
259
|
|
|
192
260
|
export class MyAgent extends Agent<Env, State> {
|
|
193
261
|
async onChatMessage() {
|
|
194
|
-
const executor = new DynamicWorkerExecutor({
|
|
195
|
-
loader: this.env.LOADER
|
|
196
|
-
});
|
|
262
|
+
const executor = new DynamicWorkerExecutor({ loader: this.env.LOADER });
|
|
197
263
|
|
|
198
|
-
const codemode = createCodeTool({
|
|
199
|
-
tools: myTools,
|
|
200
|
-
executor
|
|
201
|
-
});
|
|
264
|
+
const codemode = createCodeTool({ tools: myTools, executor });
|
|
202
265
|
|
|
203
266
|
const result = streamText({
|
|
204
267
|
model,
|
|
@@ -213,6 +276,29 @@ export class MyAgent extends Agent<Env, State> {
|
|
|
213
276
|
}
|
|
214
277
|
```
|
|
215
278
|
|
|
279
|
+
### With filesystem access (via `@cloudflare/shell`)
|
|
280
|
+
|
|
281
|
+
Combine `codemode.*` tools with `state.*` filesystem operations:
|
|
282
|
+
|
|
283
|
+
```ts
|
|
284
|
+
import { createCodeTool } from "@cloudflare/codemode/ai";
|
|
285
|
+
import { DynamicWorkerExecutor } from "@cloudflare/codemode";
|
|
286
|
+
import { Workspace } from "@cloudflare/shell";
|
|
287
|
+
import { stateTools } from "@cloudflare/shell/workers";
|
|
288
|
+
|
|
289
|
+
export class MyAgent extends Agent<Env> {
|
|
290
|
+
workspace = new Workspace(this);
|
|
291
|
+
|
|
292
|
+
getCodemodeTool() {
|
|
293
|
+
const executor = new DynamicWorkerExecutor({ loader: this.env.LOADER });
|
|
294
|
+
return createCodeTool({
|
|
295
|
+
tools: [{ tools: myDomainTools }, stateTools(this.workspace)],
|
|
296
|
+
executor
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
```
|
|
301
|
+
|
|
216
302
|
### With MCP tools
|
|
217
303
|
|
|
218
304
|
MCP tools work the same way — just merge them into the tool set:
|
|
@@ -231,7 +317,7 @@ const codemode = createCodeTool({
|
|
|
231
317
|
|
|
232
318
|
### `sanitizeToolName(name)`
|
|
233
319
|
|
|
234
|
-
Converts tool names into valid JavaScript identifiers. Handles hyphens, dots, digits, reserved words.
|
|
320
|
+
Converts tool names into valid JavaScript identifiers. Handles hyphens, dots, digits, reserved words. Called automatically by `DynamicWorkerExecutor` on `fns` keys — you only need this for custom use cases.
|
|
235
321
|
|
|
236
322
|
```ts
|
|
237
323
|
import { sanitizeToolName } from "@cloudflare/codemode";
|
|
@@ -243,7 +329,7 @@ sanitizeToolName("delete"); // "delete_"
|
|
|
243
329
|
|
|
244
330
|
### `normalizeCode(code)`
|
|
245
331
|
|
|
246
|
-
Normalizes LLM-generated code into a valid async arrow function. Strips markdown code fences, handles various function formats.
|
|
332
|
+
Normalizes LLM-generated code into a valid async arrow function. Strips markdown code fences, handles various function formats. Called automatically by `DynamicWorkerExecutor` — you only need this for custom use cases.
|
|
247
333
|
|
|
248
334
|
````ts
|
|
249
335
|
import { normalizeCode } from "@cloudflare/codemode";
|
|
@@ -288,10 +374,10 @@ const types = generateTypes(myAiSdkTools);
|
|
|
288
374
|
|
|
289
375
|
## Module Structure
|
|
290
376
|
|
|
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`
|
|
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` |
|
|
295
381
|
|
|
296
382
|
## Limitations
|
|
297
383
|
|
package/dist/ai.d.ts
CHANGED
|
@@ -1,54 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
type ToolDescriptors = Record<string, ToolDescriptor>;
|
|
13
|
-
/**
|
|
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.
|
|
16
|
-
*
|
|
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
|
-
*/
|
|
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
|
-
};
|
|
43
|
-
declare function createCodeTool(
|
|
44
|
-
options: CreateCodeToolOptions
|
|
45
|
-
): Tool<CodeInput, CodeOutput>;
|
|
46
|
-
//#endregion
|
|
1
|
+
import {
|
|
2
|
+
d as generateTypes,
|
|
3
|
+
l as ToolDescriptor,
|
|
4
|
+
u as ToolDescriptors
|
|
5
|
+
} from "./executor-C1NPN-nW.js";
|
|
6
|
+
import {
|
|
7
|
+
i as resolveProvider,
|
|
8
|
+
n as aiTools,
|
|
9
|
+
r as createCodeTool,
|
|
10
|
+
t as CreateCodeToolOptions
|
|
11
|
+
} from "./tool-BQ5SO4OJ.js";
|
|
47
12
|
export {
|
|
48
13
|
type CreateCodeToolOptions,
|
|
49
14
|
type ToolDescriptor,
|
|
50
15
|
type ToolDescriptors,
|
|
16
|
+
aiTools,
|
|
51
17
|
createCodeTool,
|
|
52
|
-
generateTypes
|
|
18
|
+
generateTypes,
|
|
19
|
+
resolveProvider
|
|
53
20
|
};
|
|
54
|
-
//# sourceMappingURL=ai.d.ts.map
|
package/dist/ai.js
CHANGED
|
@@ -1,216 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { z } from "zod";
|
|
4
|
-
//#region src/tool-types.ts
|
|
5
|
-
/**
|
|
6
|
-
* Check if a value is a Zod schema (has _zod property).
|
|
7
|
-
*/
|
|
8
|
-
function isZodSchema(value) {
|
|
9
|
-
return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Check if a value conforms to the Standard Schema protocol (~standard).
|
|
13
|
-
* This catches Zod v3 schemas (which expose ~standard but not _zod).
|
|
14
|
-
*/
|
|
15
|
-
function isStandardSchema(value) {
|
|
16
|
-
return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* Check if a value is an AI SDK jsonSchema wrapper.
|
|
20
|
-
* The jsonSchema wrapper has a [Symbol] with jsonSchema property.
|
|
21
|
-
*/
|
|
22
|
-
function isJsonSchemaWrapper(value) {
|
|
23
|
-
if (value === null || typeof value !== "object") return false;
|
|
24
|
-
if ("jsonSchema" in value) return true;
|
|
25
|
-
const symbols = Object.getOwnPropertySymbols(value);
|
|
26
|
-
for (const sym of symbols) {
|
|
27
|
-
const symValue = value[sym];
|
|
28
|
-
if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return true;
|
|
29
|
-
}
|
|
30
|
-
return false;
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Extract JSON schema from an AI SDK jsonSchema wrapper.
|
|
34
|
-
*/
|
|
35
|
-
function extractJsonSchema(wrapper) {
|
|
36
|
-
if (wrapper === null || typeof wrapper !== "object") return null;
|
|
37
|
-
if ("jsonSchema" in wrapper) return wrapper.jsonSchema;
|
|
38
|
-
const symbols = Object.getOwnPropertySymbols(wrapper);
|
|
39
|
-
for (const sym of symbols) {
|
|
40
|
-
const symValue = wrapper[sym];
|
|
41
|
-
if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return symValue.jsonSchema;
|
|
42
|
-
}
|
|
43
|
-
return null;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Extract field descriptions from a schema.
|
|
47
|
-
* Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).
|
|
48
|
-
*/
|
|
49
|
-
function extractDescriptions(schema) {
|
|
50
|
-
const descriptions = {};
|
|
51
|
-
const shape = schema.shape;
|
|
52
|
-
if (shape && typeof shape === "object") {
|
|
53
|
-
for (const [fieldName, fieldSchema] of Object.entries(shape)) {
|
|
54
|
-
let s = fieldSchema;
|
|
55
|
-
while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
|
|
56
|
-
if (s.description) descriptions[fieldName] = s.description;
|
|
57
|
-
}
|
|
58
|
-
return descriptions;
|
|
59
|
-
}
|
|
60
|
-
if (isJsonSchemaWrapper(schema)) {
|
|
61
|
-
const jsonSchema = extractJsonSchema(schema);
|
|
62
|
-
if (jsonSchema?.properties) {
|
|
63
|
-
for (const [fieldName, propSchema] of Object.entries(jsonSchema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
return descriptions;
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Extract field descriptions from a schema and format as @param lines.
|
|
70
|
-
*/
|
|
71
|
-
function extractParamDescriptions(schema) {
|
|
72
|
-
const descriptions = extractDescriptions(schema);
|
|
73
|
-
return Object.entries(descriptions).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Safely convert a schema to TypeScript type string.
|
|
77
|
-
* Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
|
|
78
|
-
*/
|
|
79
|
-
function safeSchemaToTs(schema, typeName) {
|
|
80
|
-
try {
|
|
81
|
-
if (isZodSchema(schema) || isStandardSchema(schema)) {
|
|
82
|
-
const jsonSchema = asSchema(schema).jsonSchema;
|
|
83
|
-
if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
|
|
84
|
-
root: jsonSchema,
|
|
85
|
-
depth: 0,
|
|
86
|
-
seen: /* @__PURE__ */ new Set(),
|
|
87
|
-
maxDepth: 20
|
|
88
|
-
})}`;
|
|
89
|
-
}
|
|
90
|
-
if (isJsonSchemaWrapper(schema)) {
|
|
91
|
-
const jsonSchema = extractJsonSchema(schema);
|
|
92
|
-
if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
|
|
93
|
-
root: jsonSchema,
|
|
94
|
-
depth: 0,
|
|
95
|
-
seen: /* @__PURE__ */ new Set(),
|
|
96
|
-
maxDepth: 20
|
|
97
|
-
})}`;
|
|
98
|
-
}
|
|
99
|
-
return `type ${typeName} = unknown`;
|
|
100
|
-
} catch {
|
|
101
|
-
return `type ${typeName} = unknown`;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
/**
|
|
105
|
-
* Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
|
|
106
|
-
* These types can be included in tool descriptions to help LLMs write correct code.
|
|
107
|
-
*
|
|
108
|
-
* Requires the `ai` peer dependency. For a version that works with plain JSON Schema
|
|
109
|
-
* objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
|
|
110
|
-
*/
|
|
111
|
-
function generateTypes(tools) {
|
|
112
|
-
let availableTools = "";
|
|
113
|
-
let availableTypes = "";
|
|
114
|
-
for (const [toolName, tool] of Object.entries(tools)) {
|
|
115
|
-
const safeName = sanitizeToolName(toolName);
|
|
116
|
-
const typeName = toPascalCase(safeName);
|
|
117
|
-
try {
|
|
118
|
-
const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
|
|
119
|
-
const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
|
|
120
|
-
const description = tool.description;
|
|
121
|
-
const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);
|
|
122
|
-
const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
|
|
123
|
-
availableTypes += `\n${inputType.trim()}`;
|
|
124
|
-
availableTypes += `\n${outputType.trim()}`;
|
|
125
|
-
const paramDescs = (() => {
|
|
126
|
-
try {
|
|
127
|
-
return inputSchema ? extractParamDescriptions(inputSchema) : [];
|
|
128
|
-
} catch {
|
|
129
|
-
return [];
|
|
130
|
-
}
|
|
131
|
-
})();
|
|
132
|
-
const jsdocLines = [];
|
|
133
|
-
if (description?.trim()) jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
|
|
134
|
-
else jsdocLines.push(escapeJsDoc(toolName));
|
|
135
|
-
for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
|
|
136
|
-
const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
|
|
137
|
-
availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
|
|
138
|
-
availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
|
|
139
|
-
availableTools += "\n";
|
|
140
|
-
} catch {
|
|
141
|
-
availableTypes += `\ntype ${typeName}Input = unknown`;
|
|
142
|
-
availableTypes += `\ntype ${typeName}Output = unknown`;
|
|
143
|
-
availableTools += `\n\t/**\n\t * ${escapeJsDoc(toolName)}\n\t */`;
|
|
144
|
-
availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
|
|
145
|
-
availableTools += "\n";
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
availableTools = `\ndeclare const codemode: {${availableTools}}`;
|
|
149
|
-
return `
|
|
150
|
-
${availableTypes}
|
|
151
|
-
${availableTools}
|
|
152
|
-
`.trim();
|
|
153
|
-
}
|
|
154
|
-
//#endregion
|
|
155
|
-
//#region src/tool.ts
|
|
156
|
-
const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
|
|
157
|
-
|
|
158
|
-
Available:
|
|
159
|
-
{{types}}
|
|
160
|
-
|
|
161
|
-
Write an async arrow function in JavaScript that returns the result.
|
|
162
|
-
Do NOT use TypeScript syntax — no type annotations, interfaces, or generics.
|
|
163
|
-
Do NOT define named functions then call them — just write the arrow function body directly.
|
|
164
|
-
|
|
165
|
-
Example: async () => { const r = await codemode.searchWeb({ query: "test" }); return r; }`;
|
|
166
|
-
const codeSchema = z.object({ code: z.string().describe("JavaScript async arrow function to execute") });
|
|
167
|
-
/**
|
|
168
|
-
* Create a codemode tool that allows LLMs to write and execute code
|
|
169
|
-
* with access to your tools in a sandboxed environment.
|
|
170
|
-
*
|
|
171
|
-
* Returns an AI SDK compatible tool.
|
|
172
|
-
*/
|
|
173
|
-
function hasNeedsApproval(t) {
|
|
174
|
-
return "needsApproval" in t && t.needsApproval != null;
|
|
175
|
-
}
|
|
176
|
-
function createCodeTool(options) {
|
|
177
|
-
const tools = {};
|
|
178
|
-
for (const [name, t] of Object.entries(options.tools)) if (!hasNeedsApproval(t)) tools[name] = t;
|
|
179
|
-
const types = generateTypes(tools);
|
|
180
|
-
const executor = options.executor;
|
|
181
|
-
return tool({
|
|
182
|
-
description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", types),
|
|
183
|
-
inputSchema: codeSchema,
|
|
184
|
-
execute: async ({ code }) => {
|
|
185
|
-
const fns = {};
|
|
186
|
-
for (const [name, t] of Object.entries(tools)) {
|
|
187
|
-
const execute = "execute" in t ? t.execute : void 0;
|
|
188
|
-
if (execute) {
|
|
189
|
-
const rawSchema = "inputSchema" in t ? t.inputSchema : "parameters" in t ? t.parameters : void 0;
|
|
190
|
-
const schema = rawSchema != null ? asSchema(rawSchema) : void 0;
|
|
191
|
-
fns[sanitizeToolName(name)] = schema?.validate ? async (args) => {
|
|
192
|
-
const result = await schema.validate(args);
|
|
193
|
-
if (!result.success) throw result.error;
|
|
194
|
-
return execute(result.value);
|
|
195
|
-
} : execute;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
const normalizedCode = normalizeCode(code);
|
|
199
|
-
const executeResult = await executor.execute(normalizedCode, fns);
|
|
200
|
-
if (executeResult.error) {
|
|
201
|
-
const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
|
|
202
|
-
throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
|
|
203
|
-
}
|
|
204
|
-
const output = {
|
|
205
|
-
code,
|
|
206
|
-
result: executeResult.result
|
|
207
|
-
};
|
|
208
|
-
if (executeResult.logs) output.logs = executeResult.logs;
|
|
209
|
-
return output;
|
|
210
|
-
}
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
//#endregion
|
|
214
|
-
export { createCodeTool, generateTypes };
|
|
215
|
-
|
|
216
|
-
//# sourceMappingURL=ai.js.map
|
|
1
|
+
import { i as generateTypes, n as createCodeTool, r as resolveProvider, t as aiTools } from "./tool-B0ZYASro.js";
|
|
2
|
+
export { aiTools, createCodeTool, generateTypes, resolveProvider };
|