@cloudflare/codemode 0.2.1 → 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 +119 -33
- package/dist/ai.d.ts +14 -48
- package/dist/ai.js +2 -217
- package/dist/executor-C1NPN-nW.d.ts +186 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +63 -24
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +12 -3
- package/dist/mcp.js.map +1 -1
- 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 +1 -1
- package/dist/ai.js.map +0 -1
- package/dist/executor-6RSFUhUk.d.ts +0 -78
- package/dist/normalize-DnrE6oKV.js +0 -44
- package/dist/normalize-DnrE6oKV.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:
|
|
@@ -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,217 +1,2 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
|
|
3
|
-
import { asSchema, tool } from "ai";
|
|
4
|
-
import { z } from "zod";
|
|
5
|
-
//#region src/tool-types.ts
|
|
6
|
-
/**
|
|
7
|
-
* Check if a value is a Zod schema (has _zod property).
|
|
8
|
-
*/
|
|
9
|
-
function isZodSchema(value) {
|
|
10
|
-
return value !== null && typeof value === "object" && "_zod" in value && value._zod !== void 0;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Check if a value conforms to the Standard Schema protocol (~standard).
|
|
14
|
-
* This catches Zod v3 schemas (which expose ~standard but not _zod).
|
|
15
|
-
*/
|
|
16
|
-
function isStandardSchema(value) {
|
|
17
|
-
return value !== null && typeof value === "object" && "~standard" in value && value["~standard"] !== void 0;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Check if a value is an AI SDK jsonSchema wrapper.
|
|
21
|
-
* The jsonSchema wrapper has a [Symbol] with jsonSchema property.
|
|
22
|
-
*/
|
|
23
|
-
function isJsonSchemaWrapper(value) {
|
|
24
|
-
if (value === null || typeof value !== "object") return false;
|
|
25
|
-
if ("jsonSchema" in value) return true;
|
|
26
|
-
const symbols = Object.getOwnPropertySymbols(value);
|
|
27
|
-
for (const sym of symbols) {
|
|
28
|
-
const symValue = value[sym];
|
|
29
|
-
if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return true;
|
|
30
|
-
}
|
|
31
|
-
return false;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Extract JSON schema from an AI SDK jsonSchema wrapper.
|
|
35
|
-
*/
|
|
36
|
-
function extractJsonSchema(wrapper) {
|
|
37
|
-
if (wrapper === null || typeof wrapper !== "object") return null;
|
|
38
|
-
if ("jsonSchema" in wrapper) return wrapper.jsonSchema;
|
|
39
|
-
const symbols = Object.getOwnPropertySymbols(wrapper);
|
|
40
|
-
for (const sym of symbols) {
|
|
41
|
-
const symValue = wrapper[sym];
|
|
42
|
-
if (symValue && typeof symValue === "object" && "jsonSchema" in symValue) return symValue.jsonSchema;
|
|
43
|
-
}
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Extract field descriptions from a schema.
|
|
48
|
-
* Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).
|
|
49
|
-
*/
|
|
50
|
-
function extractDescriptions(schema) {
|
|
51
|
-
const descriptions = {};
|
|
52
|
-
const shape = schema.shape;
|
|
53
|
-
if (shape && typeof shape === "object") {
|
|
54
|
-
for (const [fieldName, fieldSchema] of Object.entries(shape)) {
|
|
55
|
-
let s = fieldSchema;
|
|
56
|
-
while (!s.description && typeof s.unwrap === "function") s = s.unwrap();
|
|
57
|
-
if (s.description) descriptions[fieldName] = s.description;
|
|
58
|
-
}
|
|
59
|
-
return descriptions;
|
|
60
|
-
}
|
|
61
|
-
if (isJsonSchemaWrapper(schema)) {
|
|
62
|
-
const jsonSchema = extractJsonSchema(schema);
|
|
63
|
-
if (jsonSchema?.properties) {
|
|
64
|
-
for (const [fieldName, propSchema] of Object.entries(jsonSchema.properties)) if (propSchema && typeof propSchema === "object" && propSchema.description) descriptions[fieldName] = propSchema.description;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return descriptions;
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Extract field descriptions from a schema and format as @param lines.
|
|
71
|
-
*/
|
|
72
|
-
function extractParamDescriptions(schema) {
|
|
73
|
-
const descriptions = extractDescriptions(schema);
|
|
74
|
-
return Object.entries(descriptions).map(([fieldName, desc]) => `@param input.${fieldName} - ${desc}`);
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Safely convert a schema to TypeScript type string.
|
|
78
|
-
* Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.
|
|
79
|
-
*/
|
|
80
|
-
function safeSchemaToTs(schema, typeName) {
|
|
81
|
-
try {
|
|
82
|
-
if (isZodSchema(schema) || isStandardSchema(schema)) {
|
|
83
|
-
const jsonSchema = asSchema(schema).jsonSchema;
|
|
84
|
-
if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
|
|
85
|
-
root: jsonSchema,
|
|
86
|
-
depth: 0,
|
|
87
|
-
seen: /* @__PURE__ */ new Set(),
|
|
88
|
-
maxDepth: 20
|
|
89
|
-
})}`;
|
|
90
|
-
}
|
|
91
|
-
if (isJsonSchemaWrapper(schema)) {
|
|
92
|
-
const jsonSchema = extractJsonSchema(schema);
|
|
93
|
-
if (jsonSchema) return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, "", {
|
|
94
|
-
root: jsonSchema,
|
|
95
|
-
depth: 0,
|
|
96
|
-
seen: /* @__PURE__ */ new Set(),
|
|
97
|
-
maxDepth: 20
|
|
98
|
-
})}`;
|
|
99
|
-
}
|
|
100
|
-
return `type ${typeName} = unknown`;
|
|
101
|
-
} catch {
|
|
102
|
-
return `type ${typeName} = unknown`;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
|
|
107
|
-
* These types can be included in tool descriptions to help LLMs write correct code.
|
|
108
|
-
*
|
|
109
|
-
* Requires the `ai` peer dependency. For a version that works with plain JSON Schema
|
|
110
|
-
* objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
|
|
111
|
-
*/
|
|
112
|
-
function generateTypes(tools) {
|
|
113
|
-
let availableTools = "";
|
|
114
|
-
let availableTypes = "";
|
|
115
|
-
for (const [toolName, tool] of Object.entries(tools)) {
|
|
116
|
-
const safeName = sanitizeToolName(toolName);
|
|
117
|
-
const typeName = toPascalCase(safeName);
|
|
118
|
-
try {
|
|
119
|
-
const inputSchema = "inputSchema" in tool ? tool.inputSchema : tool.parameters;
|
|
120
|
-
const outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
|
|
121
|
-
const description = tool.description;
|
|
122
|
-
const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);
|
|
123
|
-
const outputType = outputSchema ? safeSchemaToTs(outputSchema, `${typeName}Output`) : `type ${typeName}Output = unknown`;
|
|
124
|
-
availableTypes += `\n${inputType.trim()}`;
|
|
125
|
-
availableTypes += `\n${outputType.trim()}`;
|
|
126
|
-
const paramDescs = (() => {
|
|
127
|
-
try {
|
|
128
|
-
return inputSchema ? extractParamDescriptions(inputSchema) : [];
|
|
129
|
-
} catch {
|
|
130
|
-
return [];
|
|
131
|
-
}
|
|
132
|
-
})();
|
|
133
|
-
const jsdocLines = [];
|
|
134
|
-
if (description?.trim()) jsdocLines.push(escapeJsDoc(description.trim().replace(/\r?\n/g, " ")));
|
|
135
|
-
else jsdocLines.push(escapeJsDoc(toolName));
|
|
136
|
-
for (const pd of paramDescs) jsdocLines.push(escapeJsDoc(pd.replace(/\r?\n/g, " ")));
|
|
137
|
-
const jsdocBody = jsdocLines.map((l) => `\t * ${l}`).join("\n");
|
|
138
|
-
availableTools += `\n\t/**\n${jsdocBody}\n\t */`;
|
|
139
|
-
availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
|
|
140
|
-
availableTools += "\n";
|
|
141
|
-
} catch {
|
|
142
|
-
availableTypes += `\ntype ${typeName}Input = unknown`;
|
|
143
|
-
availableTypes += `\ntype ${typeName}Output = unknown`;
|
|
144
|
-
availableTools += `\n\t/**\n\t * ${escapeJsDoc(toolName)}\n\t */`;
|
|
145
|
-
availableTools += `\n\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;
|
|
146
|
-
availableTools += "\n";
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
availableTools = `\ndeclare const codemode: {${availableTools}}`;
|
|
150
|
-
return `
|
|
151
|
-
${availableTypes}
|
|
152
|
-
${availableTools}
|
|
153
|
-
`.trim();
|
|
154
|
-
}
|
|
155
|
-
//#endregion
|
|
156
|
-
//#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
|
-
const codeSchema = z.object({ code: z.string().describe("JavaScript async arrow function to execute") });
|
|
168
|
-
/**
|
|
169
|
-
* Create a codemode tool that allows LLMs to write and execute code
|
|
170
|
-
* with access to your tools in a sandboxed environment.
|
|
171
|
-
*
|
|
172
|
-
* Returns an AI SDK compatible tool.
|
|
173
|
-
*/
|
|
174
|
-
function hasNeedsApproval(t) {
|
|
175
|
-
return "needsApproval" in t && t.needsApproval != null;
|
|
176
|
-
}
|
|
177
|
-
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);
|
|
181
|
-
const executor = options.executor;
|
|
182
|
-
return tool({
|
|
183
|
-
description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", types),
|
|
184
|
-
inputSchema: codeSchema,
|
|
185
|
-
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
|
-
const normalizedCode = normalizeCode(code);
|
|
200
|
-
const executeResult = await executor.execute(normalizedCode, fns);
|
|
201
|
-
if (executeResult.error) {
|
|
202
|
-
const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
|
|
203
|
-
throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
|
|
204
|
-
}
|
|
205
|
-
const output = {
|
|
206
|
-
code,
|
|
207
|
-
result: executeResult.result
|
|
208
|
-
};
|
|
209
|
-
if (executeResult.logs) output.logs = executeResult.logs;
|
|
210
|
-
return output;
|
|
211
|
-
}
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
//#endregion
|
|
215
|
-
export { createCodeTool, generateTypes };
|
|
216
|
-
|
|
217
|
-
//# 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 };
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { RpcTarget } from "cloudflare:workers";
|
|
2
|
+
import { ToolSet } from "ai";
|
|
3
|
+
import { ZodType } from "zod";
|
|
4
|
+
|
|
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>;
|
|
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(
|
|
21
|
+
tools: ToolDescriptors | ToolSet,
|
|
22
|
+
namespace?: string
|
|
23
|
+
): string;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/executor.d.ts
|
|
26
|
+
interface ExecuteResult {
|
|
27
|
+
result: unknown;
|
|
28
|
+
error?: string;
|
|
29
|
+
logs?: string[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A minimal tool record — just a description and an execute function.
|
|
33
|
+
* Use this for providers that supply their own `types` and don't need
|
|
34
|
+
* schema-based type generation (e.g. stateTools).
|
|
35
|
+
*/
|
|
36
|
+
type SimpleToolRecord = Record<
|
|
37
|
+
string,
|
|
38
|
+
{
|
|
39
|
+
description?: string;
|
|
40
|
+
execute: (args: unknown) => Promise<unknown>;
|
|
41
|
+
}
|
|
42
|
+
>;
|
|
43
|
+
/**
|
|
44
|
+
* All tool record types accepted by a ToolProvider.
|
|
45
|
+
*/
|
|
46
|
+
type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;
|
|
47
|
+
/**
|
|
48
|
+
* A ToolProvider contributes tools to the codemode sandbox under a namespace.
|
|
49
|
+
*
|
|
50
|
+
* Each provider's tools are accessible as `name.toolName()` in sandbox code.
|
|
51
|
+
* If `name` is omitted, tools are exposed under the default `codemode.*` namespace.
|
|
52
|
+
*
|
|
53
|
+
* @example Multiple providers with different namespaces
|
|
54
|
+
* ```ts
|
|
55
|
+
* createCodeTool({
|
|
56
|
+
* tools: [
|
|
57
|
+
* { name: "github", tools: githubTools },
|
|
58
|
+
* { name: "shell", tools: shellTools },
|
|
59
|
+
* { tools: aiTools }, // default "codemode" namespace
|
|
60
|
+
* ],
|
|
61
|
+
* executor,
|
|
62
|
+
* });
|
|
63
|
+
* // sandbox: github.listIssues(), shell.exec(), codemode.search()
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
interface ToolProvider {
|
|
67
|
+
/** Namespace prefix in the sandbox (e.g. "state", "mcp"). Defaults to "codemode". */
|
|
68
|
+
name?: string;
|
|
69
|
+
/** Tools exposed as `namespace.toolName()` in the sandbox. */
|
|
70
|
+
tools: ToolProviderTools;
|
|
71
|
+
/** Type declarations for the LLM. Auto-generated from `tools` if omitted. */
|
|
72
|
+
types?: string;
|
|
73
|
+
/**
|
|
74
|
+
* When true, tools accept positional args instead of a single object arg.
|
|
75
|
+
* The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.
|
|
76
|
+
*
|
|
77
|
+
* Default tools use single-object args: `codemode.search({ query: "test" })`
|
|
78
|
+
* Positional tools use normal args: `state.readFile("/path")`
|
|
79
|
+
*/
|
|
80
|
+
positionalArgs?: boolean;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Internal resolved form of a ToolProvider, ready for execution.
|
|
84
|
+
* The tool functions have been extracted and keyed by sanitized name.
|
|
85
|
+
*/
|
|
86
|
+
interface ResolvedProvider {
|
|
87
|
+
name: string;
|
|
88
|
+
fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
|
|
89
|
+
positionalArgs?: boolean;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* An executor runs LLM-generated code in a sandbox, making the provided
|
|
93
|
+
* tool functions callable under their namespace inside the sandbox.
|
|
94
|
+
*
|
|
95
|
+
* Implementations should never throw — errors are returned in `ExecuteResult.error`.
|
|
96
|
+
*
|
|
97
|
+
* @param code - The code to execute in the sandbox.
|
|
98
|
+
* @param providersOrFns - An array of `ResolvedProvider` (preferred), or a
|
|
99
|
+
* plain `Record<string, fn>` for backwards compatibility (deprecated — will
|
|
100
|
+
* be removed in the next major version).
|
|
101
|
+
*/
|
|
102
|
+
interface Executor {
|
|
103
|
+
execute(
|
|
104
|
+
code: string,
|
|
105
|
+
providersOrFns:
|
|
106
|
+
| ResolvedProvider[]
|
|
107
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
108
|
+
): Promise<ExecuteResult>;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* An RpcTarget that dispatches tool calls from the sandboxed Worker
|
|
112
|
+
* back to the host. Passed via Workers RPC to the dynamic Worker's
|
|
113
|
+
* evaluate() method — no globalOutbound or Fetcher bindings needed.
|
|
114
|
+
*/
|
|
115
|
+
declare class ToolDispatcher extends RpcTarget {
|
|
116
|
+
#private;
|
|
117
|
+
constructor(
|
|
118
|
+
fns: Record<string, (...args: unknown[]) => Promise<unknown>>,
|
|
119
|
+
positionalArgs?: boolean
|
|
120
|
+
);
|
|
121
|
+
call(name: string, argsJson: string): Promise<string>;
|
|
122
|
+
}
|
|
123
|
+
interface DynamicWorkerExecutorOptions {
|
|
124
|
+
loader: WorkerLoader;
|
|
125
|
+
/**
|
|
126
|
+
* Timeout in milliseconds for code execution. Defaults to 30000 (30s).
|
|
127
|
+
*/
|
|
128
|
+
timeout?: number;
|
|
129
|
+
/**
|
|
130
|
+
* Controls outbound network access from sandboxed code.
|
|
131
|
+
* - `null` (default): fetch() and connect() throw — sandbox is fully isolated.
|
|
132
|
+
* - `undefined`: inherits parent Worker's network access (full internet).
|
|
133
|
+
* - A `Fetcher`: all outbound requests route through this handler.
|
|
134
|
+
*/
|
|
135
|
+
globalOutbound?: Fetcher | null;
|
|
136
|
+
/**
|
|
137
|
+
* Additional modules to make available in the sandbox.
|
|
138
|
+
* Keys are module specifiers (e.g. `"mylib.js"`), values are module source code.
|
|
139
|
+
*
|
|
140
|
+
* Note: the key `"executor.js"` is reserved and will be ignored if provided.
|
|
141
|
+
*/
|
|
142
|
+
modules?: Record<string, string>;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Executes code in an isolated Cloudflare Worker via WorkerLoader.
|
|
146
|
+
* Tool calls are dispatched via Workers RPC — the host passes
|
|
147
|
+
* ToolDispatchers (one per namespace) to the Worker's evaluate() method.
|
|
148
|
+
*
|
|
149
|
+
* External fetch() and connect() are blocked by default via
|
|
150
|
+
* `globalOutbound: null` (runtime-enforced). Pass a Fetcher to
|
|
151
|
+
* `globalOutbound` to allow controlled outbound access.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```ts
|
|
155
|
+
* const result = await executor.execute(code, [
|
|
156
|
+
* { name: "codemode", fns: { search: searchFn } },
|
|
157
|
+
* { name: "state", fns: { readFile: readFileFn } },
|
|
158
|
+
* ]);
|
|
159
|
+
* // sandbox has both codemode.search() and state.readFile()
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
declare class DynamicWorkerExecutor implements Executor {
|
|
163
|
+
#private;
|
|
164
|
+
constructor(options: DynamicWorkerExecutorOptions);
|
|
165
|
+
execute(
|
|
166
|
+
code: string,
|
|
167
|
+
providersOrFns:
|
|
168
|
+
| ResolvedProvider[]
|
|
169
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
170
|
+
): Promise<ExecuteResult>;
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
export {
|
|
174
|
+
ResolvedProvider as a,
|
|
175
|
+
ToolProviderTools as c,
|
|
176
|
+
generateTypes as d,
|
|
177
|
+
Executor as i,
|
|
178
|
+
ToolDescriptor as l,
|
|
179
|
+
DynamicWorkerExecutorOptions as n,
|
|
180
|
+
ToolDispatcher as o,
|
|
181
|
+
ExecuteResult as r,
|
|
182
|
+
ToolProvider as s,
|
|
183
|
+
DynamicWorkerExecutor as t,
|
|
184
|
+
ToolDescriptors as u
|
|
185
|
+
};
|
|
186
|
+
//# sourceMappingURL=executor-C1NPN-nW.d.ts.map
|