@cloudflare/codemode 0.1.3 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -12
- package/dist/ai.d.ts +26 -3
- package/dist/ai.js +154 -2
- package/dist/ai.js.map +1 -1
- package/dist/{executor-BYZZhAgd.d.ts → executor-6RSFUhUk.d.ts} +9 -27
- package/dist/index.d.ts +43 -8
- package/dist/index.js +15 -5
- package/dist/index.js.map +1 -1
- package/dist/{normalize-Dy5d7PfI.js → json-schema-types-DoQ0VISs.js} +50 -169
- package/dist/json-schema-types-DoQ0VISs.js.map +1 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +305 -0
- package/dist/mcp.js.map +1 -0
- package/dist/normalize-DnrE6oKV.js +44 -0
- package/dist/normalize-DnrE6oKV.js.map +1 -0
- package/package.json +20 -1
- package/dist/normalize-Dy5d7PfI.js.map +0 -1
package/README.md
CHANGED
|
@@ -9,9 +9,15 @@ 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
13
|
npm install @cloudflare/codemode agents ai zod
|
|
14
|
+
|
|
15
|
+
# Utilities only (no ai/zod peer deps needed)
|
|
16
|
+
npm install @cloudflare/codemode
|
|
13
17
|
```
|
|
14
18
|
|
|
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`.
|
|
20
|
+
|
|
15
21
|
## Quick Start
|
|
16
22
|
|
|
17
23
|
`createCodeTool` takes your tools and an executor, and returns a single AI SDK tool that lets the LLM write code instead of making individual tool calls.
|
|
@@ -223,31 +229,70 @@ const codemode = createCodeTool({
|
|
|
223
229
|
|
|
224
230
|
## Utilities
|
|
225
231
|
|
|
226
|
-
### `
|
|
232
|
+
### `sanitizeToolName(name)`
|
|
227
233
|
|
|
228
|
-
|
|
234
|
+
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.
|
|
229
235
|
|
|
230
236
|
```ts
|
|
231
|
-
import {
|
|
237
|
+
import { sanitizeToolName } from "@cloudflare/codemode";
|
|
238
|
+
|
|
239
|
+
sanitizeToolName("my-tool"); // "my_tool"
|
|
240
|
+
sanitizeToolName("3d-render"); // "_3d_render"
|
|
241
|
+
sanitizeToolName("delete"); // "delete_"
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### `normalizeCode(code)`
|
|
245
|
+
|
|
246
|
+
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
|
+
|
|
248
|
+
````ts
|
|
249
|
+
import { normalizeCode } from "@cloudflare/codemode";
|
|
250
|
+
|
|
251
|
+
normalizeCode("```js\nconst x = 1;\nx\n```");
|
|
252
|
+
// "async () => {\nconst x = 1;\nreturn (x)\n}"
|
|
253
|
+
````
|
|
232
254
|
|
|
233
|
-
|
|
255
|
+
### `generateTypesFromJsonSchema(tools)`
|
|
256
|
+
|
|
257
|
+
Generates TypeScript type definitions from tool descriptors with plain JSON Schema. No AI SDK or Zod dependency required.
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
import { generateTypesFromJsonSchema } from "@cloudflare/codemode";
|
|
261
|
+
|
|
262
|
+
const types = generateTypesFromJsonSchema({
|
|
263
|
+
getWeather: {
|
|
264
|
+
description: "Get weather for a city",
|
|
265
|
+
inputSchema: {
|
|
266
|
+
type: "object",
|
|
267
|
+
properties: {
|
|
268
|
+
city: { type: "string", description: "City name" }
|
|
269
|
+
},
|
|
270
|
+
required: ["city"]
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
});
|
|
234
274
|
// Returns TypeScript declarations like:
|
|
235
|
-
// type
|
|
236
|
-
// declare const codemode: {
|
|
275
|
+
// type GetWeatherInput = { city: string }
|
|
276
|
+
// declare const codemode: { getWeather: (input: GetWeatherInput) => Promise<...>; }
|
|
237
277
|
```
|
|
238
278
|
|
|
239
|
-
### `
|
|
279
|
+
### `generateTypes(tools)` (AI SDK)
|
|
240
280
|
|
|
241
|
-
|
|
281
|
+
Generates TypeScript type definitions from AI SDK tools or Zod-based tool descriptors. Requires `ai` and `zod` peer dependencies.
|
|
242
282
|
|
|
243
283
|
```ts
|
|
244
|
-
import {
|
|
284
|
+
import { generateTypes } from "@cloudflare/codemode/ai";
|
|
245
285
|
|
|
246
|
-
|
|
247
|
-
sanitizeToolName("3d-render"); // "_3d_render"
|
|
248
|
-
sanitizeToolName("delete"); // "delete_"
|
|
286
|
+
const types = generateTypes(myAiSdkTools);
|
|
249
287
|
```
|
|
250
288
|
|
|
289
|
+
## Module Structure
|
|
290
|
+
|
|
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` |
|
|
295
|
+
|
|
251
296
|
## Limitations
|
|
252
297
|
|
|
253
298
|
- **Tool approval (`needsApproval`) is not supported yet.** Tools with `needsApproval: true` execute immediately inside the sandbox without pausing for approval. Support for approval flows within codemode is planned. For now, do not pass approval-required tools to `createCodeTool` — use them through standard AI SDK tool calling instead.
|
package/dist/ai.d.ts
CHANGED
|
@@ -1,7 +1,24 @@
|
|
|
1
|
-
import { i as Executor
|
|
1
|
+
import { i as Executor } from "./executor-6RSFUhUk.js";
|
|
2
2
|
import { Tool, ToolSet } from "ai";
|
|
3
|
-
import { z } from "zod";
|
|
3
|
+
import { ZodType, z } from "zod";
|
|
4
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(tools: ToolDescriptors | ToolSet): string;
|
|
21
|
+
//#endregion
|
|
5
22
|
//#region src/tool.d.ts
|
|
6
23
|
interface CreateCodeToolOptions {
|
|
7
24
|
tools: ToolDescriptors | ToolSet;
|
|
@@ -27,5 +44,11 @@ declare function createCodeTool(
|
|
|
27
44
|
options: CreateCodeToolOptions
|
|
28
45
|
): Tool<CodeInput, CodeOutput>;
|
|
29
46
|
//#endregion
|
|
30
|
-
export {
|
|
47
|
+
export {
|
|
48
|
+
type CreateCodeToolOptions,
|
|
49
|
+
type ToolDescriptor,
|
|
50
|
+
type ToolDescriptors,
|
|
51
|
+
createCodeTool,
|
|
52
|
+
generateTypes
|
|
53
|
+
};
|
|
31
54
|
//# sourceMappingURL=ai.d.ts.map
|
package/dist/ai.js
CHANGED
|
@@ -1,6 +1,158 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as normalizeCode } from "./normalize-DnrE6oKV.js";
|
|
2
|
+
import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-DoQ0VISs.js";
|
|
2
3
|
import { asSchema, tool } from "ai";
|
|
3
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
|
|
4
156
|
//#region src/tool.ts
|
|
5
157
|
const DEFAULT_DESCRIPTION = `Execute code to achieve a goal.
|
|
6
158
|
|
|
@@ -60,6 +212,6 @@ function createCodeTool(options) {
|
|
|
60
212
|
});
|
|
61
213
|
}
|
|
62
214
|
//#endregion
|
|
63
|
-
export { createCodeTool };
|
|
215
|
+
export { createCodeTool, generateTypes };
|
|
64
216
|
|
|
65
217
|
//# sourceMappingURL=ai.js.map
|
package/dist/ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.js","names":[],"sources":["../src/tool.ts"],"sourcesContent":["import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, sanitizeToolName, type ToolDescriptors } from \"./types\";\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":";;;;AAOA,MAAM,sBAAsB;;;;;;;;;;AAoB5B,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE,CAAC;;;;;;;AAWF,SAAS,iBAAiB,GAAqC;AAC7D,QAAO,mBAAmB,KAAK,EAAE,iBAAiB;;AAGpD,SAAgB,eACd,SAC6B;CAC7B,MAAM,QAAmC,EAAE;AAC3C,MAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,QAAQ,MAAM,CACnD,KAAI,CAAC,iBAAiB,EAA6B,CAChD,OAAkC,QAAQ;CAI/C,MAAM,QAAQ,cAAc,MAAM;CAClC,MAAM,WAAW,QAAQ;AAOzB,QAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,MACD;EAIC,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(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,OAAyB;AACjD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,e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M,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,27 +1,5 @@
|
|
|
1
1
|
import { RpcTarget } from "cloudflare:workers";
|
|
2
|
-
import { ToolSet } from "ai";
|
|
3
|
-
import { ZodType } from "zod";
|
|
4
2
|
|
|
5
|
-
//#region src/types.d.ts
|
|
6
|
-
/**
|
|
7
|
-
* Sanitize a tool name into a valid JavaScript identifier.
|
|
8
|
-
* Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,
|
|
9
|
-
* prefixes digit-leading names with `_`, and appends `_` to JS reserved words.
|
|
10
|
-
*/
|
|
11
|
-
declare function sanitizeToolName(name: string): string;
|
|
12
|
-
interface ToolDescriptor {
|
|
13
|
-
description?: string;
|
|
14
|
-
inputSchema: ZodType;
|
|
15
|
-
outputSchema?: ZodType;
|
|
16
|
-
execute?: (args: unknown) => Promise<unknown>;
|
|
17
|
-
}
|
|
18
|
-
type ToolDescriptors = Record<string, ToolDescriptor>;
|
|
19
|
-
/**
|
|
20
|
-
* Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
|
|
21
|
-
* These types can be included in tool descriptions to help LLMs write correct code.
|
|
22
|
-
*/
|
|
23
|
-
declare function generateTypes(tools: ToolDescriptors | ToolSet): string;
|
|
24
|
-
//#endregion
|
|
25
3
|
//#region src/executor.d.ts
|
|
26
4
|
interface ExecuteResult {
|
|
27
5
|
result: unknown;
|
|
@@ -63,6 +41,14 @@ interface DynamicWorkerExecutorOptions {
|
|
|
63
41
|
* - A `Fetcher`: all outbound requests route through this handler.
|
|
64
42
|
*/
|
|
65
43
|
globalOutbound?: Fetcher | null;
|
|
44
|
+
/**
|
|
45
|
+
* Additional modules to make available in the sandbox.
|
|
46
|
+
* Keys are module specifiers (e.g. `"mylib.js"`), values are module source code.
|
|
47
|
+
* Sandbox code can import from these via `import { ... } from "mylib.js"`.
|
|
48
|
+
*
|
|
49
|
+
* Note: the key `"executor.js"` is reserved and will be ignored if provided.
|
|
50
|
+
*/
|
|
51
|
+
modules?: Record<string, string>;
|
|
66
52
|
}
|
|
67
53
|
/**
|
|
68
54
|
* Executes code in an isolated Cloudflare Worker via WorkerLoader.
|
|
@@ -84,13 +70,9 @@ declare class DynamicWorkerExecutor implements Executor {
|
|
|
84
70
|
//#endregion
|
|
85
71
|
export {
|
|
86
72
|
ToolDispatcher as a,
|
|
87
|
-
generateTypes as c,
|
|
88
73
|
Executor as i,
|
|
89
|
-
sanitizeToolName as l,
|
|
90
74
|
DynamicWorkerExecutorOptions as n,
|
|
91
|
-
ToolDescriptor as o,
|
|
92
75
|
ExecuteResult as r,
|
|
93
|
-
ToolDescriptors as s,
|
|
94
76
|
DynamicWorkerExecutor as t
|
|
95
77
|
};
|
|
96
|
-
//# sourceMappingURL=executor-
|
|
78
|
+
//# sourceMappingURL=executor-6RSFUhUk.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,49 @@
|
|
|
1
1
|
import {
|
|
2
2
|
a as ToolDispatcher,
|
|
3
|
-
c as generateTypes,
|
|
4
3
|
i as Executor,
|
|
5
|
-
l as sanitizeToolName,
|
|
6
4
|
n as DynamicWorkerExecutorOptions,
|
|
7
|
-
o as ToolDescriptor,
|
|
8
5
|
r as ExecuteResult,
|
|
9
|
-
s as ToolDescriptors,
|
|
10
6
|
t as DynamicWorkerExecutor
|
|
11
|
-
} from "./executor-
|
|
7
|
+
} from "./executor-6RSFUhUk.js";
|
|
8
|
+
import { JSONSchema7 } from "json-schema";
|
|
12
9
|
|
|
10
|
+
//#region src/utils.d.ts
|
|
11
|
+
/**
|
|
12
|
+
* Sanitize a tool name into a valid JavaScript identifier.
|
|
13
|
+
* Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,
|
|
14
|
+
* prefixes digit-leading names with `_`, and appends `_` to JS reserved words.
|
|
15
|
+
*/
|
|
16
|
+
declare function sanitizeToolName(name: string): string;
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/json-schema-types.d.ts
|
|
19
|
+
/**
|
|
20
|
+
* Convert a JSON Schema to a TypeScript type declaration.
|
|
21
|
+
*/
|
|
22
|
+
declare function jsonSchemaToType(
|
|
23
|
+
schema: JSONSchema7,
|
|
24
|
+
typeName: string
|
|
25
|
+
): string;
|
|
26
|
+
/**
|
|
27
|
+
* A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).
|
|
28
|
+
*/
|
|
29
|
+
interface JsonSchemaToolDescriptor {
|
|
30
|
+
description?: string;
|
|
31
|
+
inputSchema: JSONSchema7;
|
|
32
|
+
outputSchema?: JSONSchema7;
|
|
33
|
+
}
|
|
34
|
+
type JsonSchemaToolDescriptors = Record<string, JsonSchemaToolDescriptor>;
|
|
35
|
+
/**
|
|
36
|
+
* Generate TypeScript type definitions from tool descriptors with JSON Schema.
|
|
37
|
+
* This function has NO dependency on the AI SDK or Zod — it works purely with
|
|
38
|
+
* JSON Schema objects.
|
|
39
|
+
*
|
|
40
|
+
* Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool
|
|
41
|
+
* definitions, etc.) and don't need the AI SDK.
|
|
42
|
+
*/
|
|
43
|
+
declare function generateTypesFromJsonSchema(
|
|
44
|
+
tools: JsonSchemaToolDescriptors
|
|
45
|
+
): string;
|
|
46
|
+
//#endregion
|
|
13
47
|
//#region src/normalize.d.ts
|
|
14
48
|
declare function normalizeCode(code: string): string;
|
|
15
49
|
//#endregion
|
|
@@ -18,10 +52,11 @@ export {
|
|
|
18
52
|
type DynamicWorkerExecutorOptions,
|
|
19
53
|
type ExecuteResult,
|
|
20
54
|
type Executor,
|
|
21
|
-
type
|
|
22
|
-
type
|
|
55
|
+
type JsonSchemaToolDescriptor,
|
|
56
|
+
type JsonSchemaToolDescriptors,
|
|
23
57
|
ToolDispatcher,
|
|
24
|
-
|
|
58
|
+
generateTypesFromJsonSchema,
|
|
59
|
+
jsonSchemaToType,
|
|
25
60
|
normalizeCode,
|
|
26
61
|
sanitizeToolName
|
|
27
62
|
};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as normalizeCode } from "./normalize-DnrE6oKV.js";
|
|
2
|
+
import { a as sanitizeToolName, n as jsonSchemaToType, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
|
|
2
3
|
import { RpcTarget } from "cloudflare:workers";
|
|
3
4
|
//#region src/executor.ts
|
|
4
5
|
/**
|
|
@@ -42,13 +43,19 @@ var DynamicWorkerExecutor = class {
|
|
|
42
43
|
#loader;
|
|
43
44
|
#timeout;
|
|
44
45
|
#globalOutbound;
|
|
46
|
+
#modules;
|
|
45
47
|
constructor(options) {
|
|
46
48
|
this.#loader = options.loader;
|
|
47
49
|
this.#timeout = options.timeout ?? 3e4;
|
|
48
50
|
this.#globalOutbound = options.globalOutbound ?? null;
|
|
51
|
+
const { "executor.js": _, ...safeModules } = options.modules ?? {};
|
|
52
|
+
this.#modules = safeModules;
|
|
49
53
|
}
|
|
50
54
|
async execute(code, fns) {
|
|
55
|
+
const normalized = normalizeCode(code);
|
|
51
56
|
const timeoutMs = this.#timeout;
|
|
57
|
+
const sanitizedFns = {};
|
|
58
|
+
for (const [name, fn] of Object.entries(fns)) sanitizedFns[sanitizeToolName(name)] = fn;
|
|
52
59
|
const modulePrefix = [
|
|
53
60
|
"import { WorkerEntrypoint } from \"cloudflare:workers\";",
|
|
54
61
|
"",
|
|
@@ -82,13 +89,16 @@ var DynamicWorkerExecutor = class {
|
|
|
82
89
|
" }",
|
|
83
90
|
"}"
|
|
84
91
|
].join("\n");
|
|
85
|
-
const executorModule = modulePrefix +
|
|
86
|
-
const dispatcher = new ToolDispatcher(
|
|
92
|
+
const executorModule = modulePrefix + normalized + moduleSuffix;
|
|
93
|
+
const dispatcher = new ToolDispatcher(sanitizedFns);
|
|
87
94
|
const response = await this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({
|
|
88
95
|
compatibilityDate: "2025-06-01",
|
|
89
96
|
compatibilityFlags: ["nodejs_compat"],
|
|
90
97
|
mainModule: "executor.js",
|
|
91
|
-
modules: {
|
|
98
|
+
modules: {
|
|
99
|
+
...this.#modules,
|
|
100
|
+
"executor.js": executorModule
|
|
101
|
+
},
|
|
92
102
|
globalOutbound: this.#globalOutbound
|
|
93
103
|
})).getEntrypoint().evaluate(dispatcher);
|
|
94
104
|
if (response.error) return {
|
|
@@ -103,6 +113,6 @@ var DynamicWorkerExecutor = class {
|
|
|
103
113
|
}
|
|
104
114
|
};
|
|
105
115
|
//#endregion
|
|
106
|
-
export { DynamicWorkerExecutor, ToolDispatcher,
|
|
116
|
+
export { DynamicWorkerExecutor, ToolDispatcher, generateTypesFromJsonSchema, jsonSchemaToType, normalizeCode, sanitizeToolName };
|
|
107
117
|
|
|
108
118
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable as `codemode.*` inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n */\nexport interface Executor {\n execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// -- ToolDispatcher (RPC target for tool calls from sandboxed Workers) --\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>) {\n super();\n this.#fns = fns;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return JSON.stringify({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? JSON.parse(argsJson) : {};\n const result = await fn(args);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// -- DynamicWorkerExecutor (Cloudflare Workers) --\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes a\n * ToolDispatcher (RpcTarget) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n }\n\n async execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n const timeoutMs = this.#timeout;\n\n const modulePrefix = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(dispatcher) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n \" const codemode = new Proxy({}, {\",\n \" get: (_, toolName) => async (args) => {\",\n \" const resJson = await dispatcher.call(String(toolName), JSON.stringify(args ?? {}));\",\n \" const data = JSON.parse(resJson);\",\n \" if (data.error) throw new Error(data.error);\",\n \" return data.result;\",\n \" }\",\n \" });\",\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ].join(\"\\n\");\n\n const moduleSuffix = [\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ].join(\"\\n\");\n\n const executorModule = modulePrefix +
|
|
1
|
+
{"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound","#modules"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable as `codemode.*` inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n */\nexport interface Executor {\n execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// -- ToolDispatcher (RPC target for tool calls from sandboxed Workers) --\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>) {\n super();\n this.#fns = fns;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return JSON.stringify({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? JSON.parse(argsJson) : {};\n const result = await fn(args);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// -- DynamicWorkerExecutor (Cloudflare Workers) --\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n /**\n * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n * Sandbox code can import from these via `import { ... } from \"mylib.js\"`.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes a\n * ToolDispatcher (RpcTarget) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n #modules: Record<string, string>;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n const { \"executor.js\": _, ...safeModules } = options.modules ?? {};\n this.#modules = safeModules;\n }\n\n async execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Sanitize fn keys so raw tool names (e.g. \"github.list-issues\") become\n // valid JS identifiers (e.g. \"github_list_issues\") on the codemode proxy.\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n for (const [name, fn] of Object.entries(fns)) {\n sanitizedFns[sanitizeToolName(name)] = fn;\n }\n\n const modulePrefix = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(dispatcher) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n \" const codemode = new Proxy({}, {\",\n \" get: (_, toolName) => async (args) => {\",\n \" const resJson = await dispatcher.call(String(toolName), JSON.stringify(args ?? {}));\",\n \" const data = JSON.parse(resJson);\",\n \" if (data.error) throw new Error(data.error);\",\n \" return data.result;\",\n \" }\",\n \" });\",\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ].join(\"\\n\");\n\n const moduleSuffix = [\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ].join(\"\\n\");\n\n const executorModule = modulePrefix + normalized + moduleSuffix;\n\n const dispatcher = new ToolDispatcher(sanitizedFns);\n\n const worker = this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"executor.js\",\n modules: {\n ...this.#modules,\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatcher: ToolDispatcher): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatcher);\n\n if (response.error) {\n return { result: undefined, error: response.error, logs: response.logs };\n }\n\n return { result: response.result, logs: response.logs };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,IAAa,iBAAb,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