@cloudflare/codemode 0.3.4 → 0.3.6
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 +21 -2
- package/dist/ai.d.ts +4 -4
- package/dist/ai.js +9 -17
- package/dist/ai.js.map +1 -1
- package/dist/browser.d.ts +142 -0
- package/dist/browser.js +509 -0
- package/dist/browser.js.map +1 -0
- package/dist/{executor-wZjYdqEX.d.ts → executor-BWtTiHBV.d.ts} +37 -36
- package/dist/index.d.ts +13 -37
- package/dist/index.js +120 -13
- package/dist/index.js.map +1 -1
- package/dist/json-schema-types-1OL3uao0.d.ts +38 -0
- package/dist/{json-schema-types-DoQ0VISs.js → json-schema-types-CVt4X9cw.js} +43 -2
- package/dist/json-schema-types-CVt4X9cw.js.map +1 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +72 -39
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-DULSpsq2.d.ts → resolve-9VUW-grI.d.ts} +4 -4
- package/dist/resolve-BU1FGVYs.js +44 -0
- package/dist/resolve-BU1FGVYs.js.map +1 -0
- package/dist/run-code-5x8S5YWt.js +17 -0
- package/dist/run-code-5x8S5YWt.js.map +1 -0
- package/dist/{shared-Hnh_Idta.d.ts → shared-CcZcDoiO.d.ts} +5 -6
- package/dist/{shared-ra3HW2ti.js → shared-xjl2irqK.js} +1 -1
- package/dist/{shared-ra3HW2ti.js.map → shared-xjl2irqK.js.map} +1 -1
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +10 -18
- package/dist/tanstack-ai.js.map +1 -1
- package/package.json +14 -8
- package/dist/json-schema-types-DoQ0VISs.js.map +0 -1
- package/dist/resolve-DIQRkRqQ.js +0 -85
- package/dist/resolve-DIQRkRqQ.js.map +0 -1
|
@@ -22,12 +22,41 @@ declare function generateTypes(
|
|
|
22
22
|
namespace?: string
|
|
23
23
|
): string;
|
|
24
24
|
//#endregion
|
|
25
|
-
//#region src/executor.d.ts
|
|
25
|
+
//#region src/executor-types.d.ts
|
|
26
|
+
/**
|
|
27
|
+
* Shared executor contract used by all codemode runtimes.
|
|
28
|
+
*/
|
|
26
29
|
interface ExecuteResult {
|
|
27
30
|
result: unknown;
|
|
28
31
|
error?: string;
|
|
29
32
|
logs?: string[];
|
|
30
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Internal resolved form of a tool provider, ready for execution.
|
|
36
|
+
* The tool functions are keyed by tool name and exposed under `name.*`
|
|
37
|
+
* inside the sandbox.
|
|
38
|
+
*/
|
|
39
|
+
interface ResolvedProvider {
|
|
40
|
+
name: string;
|
|
41
|
+
fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
|
|
42
|
+
positionalArgs?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* An executor runs LLM-generated code in a sandbox, making the provided
|
|
46
|
+
* tool functions callable under their namespace inside the sandbox.
|
|
47
|
+
*
|
|
48
|
+
* Implementations should never throw — errors are returned in `ExecuteResult.error`.
|
|
49
|
+
*/
|
|
50
|
+
interface Executor {
|
|
51
|
+
execute(
|
|
52
|
+
code: string,
|
|
53
|
+
providersOrFns:
|
|
54
|
+
| ResolvedProvider[]
|
|
55
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
56
|
+
): Promise<ExecuteResult>;
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/executor.d.ts
|
|
31
60
|
/**
|
|
32
61
|
* A minimal tool record — just a description and an execute function.
|
|
33
62
|
* Use this for providers that supply their own `types` and don't need
|
|
@@ -79,34 +108,6 @@ interface ToolProvider {
|
|
|
79
108
|
*/
|
|
80
109
|
positionalArgs?: boolean;
|
|
81
110
|
}
|
|
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
|
/**
|
|
111
112
|
* An RpcTarget that dispatches tool calls from the sandboxed Worker
|
|
112
113
|
* back to the host. Passed via Workers RPC to the dynamic Worker's
|
|
@@ -171,16 +172,16 @@ declare class DynamicWorkerExecutor implements Executor {
|
|
|
171
172
|
}
|
|
172
173
|
//#endregion
|
|
173
174
|
export {
|
|
174
|
-
|
|
175
|
-
|
|
175
|
+
ToolProviderTools as a,
|
|
176
|
+
ResolvedProvider as c,
|
|
176
177
|
generateTypes as d,
|
|
177
|
-
|
|
178
|
+
ToolProvider as i,
|
|
178
179
|
ToolDescriptor as l,
|
|
179
180
|
DynamicWorkerExecutorOptions as n,
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
181
|
+
ExecuteResult as o,
|
|
182
|
+
ToolDispatcher as r,
|
|
183
|
+
Executor as s,
|
|
183
184
|
DynamicWorkerExecutor as t,
|
|
184
185
|
ToolDescriptors as u
|
|
185
186
|
};
|
|
186
|
-
//# sourceMappingURL=executor-
|
|
187
|
+
//# sourceMappingURL=executor-BWtTiHBV.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
i as
|
|
2
|
+
c as ResolvedProvider,
|
|
3
|
+
i as ToolProvider,
|
|
4
4
|
n as DynamicWorkerExecutorOptions,
|
|
5
|
-
o as
|
|
6
|
-
r as
|
|
7
|
-
s as
|
|
5
|
+
o as ExecuteResult,
|
|
6
|
+
r as ToolDispatcher,
|
|
7
|
+
s as Executor,
|
|
8
8
|
t as DynamicWorkerExecutor
|
|
9
|
-
} from "./executor-
|
|
10
|
-
import {
|
|
11
|
-
|
|
9
|
+
} from "./executor-BWtTiHBV.js";
|
|
10
|
+
import {
|
|
11
|
+
i as jsonSchemaToType,
|
|
12
|
+
n as JsonSchemaToolDescriptors,
|
|
13
|
+
r as generateTypesFromJsonSchema,
|
|
14
|
+
t as JsonSchemaToolDescriptor
|
|
15
|
+
} from "./json-schema-types-1OL3uao0.js";
|
|
16
|
+
import { t as resolveProvider } from "./resolve-9VUW-grI.js";
|
|
12
17
|
|
|
13
18
|
//#region src/utils.d.ts
|
|
14
19
|
/**
|
|
@@ -18,35 +23,6 @@ import { JSONSchema7 } from "json-schema";
|
|
|
18
23
|
*/
|
|
19
24
|
declare function sanitizeToolName(name: string): string;
|
|
20
25
|
//#endregion
|
|
21
|
-
//#region src/json-schema-types.d.ts
|
|
22
|
-
/**
|
|
23
|
-
* Convert a JSON Schema to a TypeScript type declaration.
|
|
24
|
-
*/
|
|
25
|
-
declare function jsonSchemaToType(
|
|
26
|
-
schema: JSONSchema7,
|
|
27
|
-
typeName: string
|
|
28
|
-
): string;
|
|
29
|
-
/**
|
|
30
|
-
* A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).
|
|
31
|
-
*/
|
|
32
|
-
interface JsonSchemaToolDescriptor {
|
|
33
|
-
description?: string;
|
|
34
|
-
inputSchema: JSONSchema7;
|
|
35
|
-
outputSchema?: JSONSchema7;
|
|
36
|
-
}
|
|
37
|
-
type JsonSchemaToolDescriptors = Record<string, JsonSchemaToolDescriptor>;
|
|
38
|
-
/**
|
|
39
|
-
* Generate TypeScript type definitions from tool descriptors with JSON Schema.
|
|
40
|
-
* This function has NO dependency on the AI SDK or Zod — it works purely with
|
|
41
|
-
* JSON Schema objects.
|
|
42
|
-
*
|
|
43
|
-
* Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool
|
|
44
|
-
* definitions, etc.) and don't need the AI SDK.
|
|
45
|
-
*/
|
|
46
|
-
declare function generateTypesFromJsonSchema(
|
|
47
|
-
tools: JsonSchemaToolDescriptors
|
|
48
|
-
): string;
|
|
49
|
-
//#endregion
|
|
50
26
|
//#region src/normalize.d.ts
|
|
51
27
|
declare function normalizeCode(code: string): string;
|
|
52
28
|
//#endregion
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { a as sanitizeToolName, n as jsonSchemaToType, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-CVt4X9cw.js";
|
|
2
|
+
import { r as resolveProvider } from "./resolve-BU1FGVYs.js";
|
|
3
3
|
import { RpcTarget } from "cloudflare:workers";
|
|
4
4
|
//#region src/executor.ts
|
|
5
5
|
/**
|
|
@@ -8,6 +8,94 @@ import { RpcTarget } from "cloudflare:workers";
|
|
|
8
8
|
* The Executor interface is the core abstraction — implement it to run
|
|
9
9
|
* LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).
|
|
10
10
|
*/
|
|
11
|
+
const BINARY_TAG = "__codemode_binary_v1__";
|
|
12
|
+
function bytesToBase64(bytes) {
|
|
13
|
+
let binary = "";
|
|
14
|
+
const chunkSize = 32768;
|
|
15
|
+
for (let i = 0; i < bytes.byteLength; i += chunkSize) binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));
|
|
16
|
+
return btoa(binary);
|
|
17
|
+
}
|
|
18
|
+
function base64ToBytes(b64) {
|
|
19
|
+
const binary = atob(b64);
|
|
20
|
+
const bytes = new Uint8Array(binary.length);
|
|
21
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
22
|
+
return bytes;
|
|
23
|
+
}
|
|
24
|
+
function encodeCodemodeValue(value) {
|
|
25
|
+
if (value instanceof Uint8Array) return {
|
|
26
|
+
[BINARY_TAG]: "Uint8Array",
|
|
27
|
+
data: bytesToBase64(value)
|
|
28
|
+
};
|
|
29
|
+
if (value instanceof ArrayBuffer) return {
|
|
30
|
+
[BINARY_TAG]: "ArrayBuffer",
|
|
31
|
+
data: bytesToBase64(new Uint8Array(value))
|
|
32
|
+
};
|
|
33
|
+
if (ArrayBuffer.isView(value)) {
|
|
34
|
+
const view = value;
|
|
35
|
+
return {
|
|
36
|
+
[BINARY_TAG]: "ArrayBufferView",
|
|
37
|
+
data: bytesToBase64(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function decodeCodemodeValue(value) {
|
|
43
|
+
if (!value || typeof value !== "object" || !(BINARY_TAG in value)) return value;
|
|
44
|
+
const encoded = value;
|
|
45
|
+
if (typeof encoded.data !== "string") return value;
|
|
46
|
+
const bytes = base64ToBytes(encoded.data);
|
|
47
|
+
if (encoded[BINARY_TAG] === "ArrayBuffer") return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
48
|
+
return bytes;
|
|
49
|
+
}
|
|
50
|
+
function stringifyForCodemode(value) {
|
|
51
|
+
return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));
|
|
52
|
+
}
|
|
53
|
+
function parseForCodemode(json) {
|
|
54
|
+
return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));
|
|
55
|
+
}
|
|
56
|
+
const SANDBOX_CODEC = String.raw`
|
|
57
|
+
const __CODEMODE_BINARY_TAG = "__codemode_binary_v1__";
|
|
58
|
+
function __bytesToBase64(bytes) {
|
|
59
|
+
let binary = "";
|
|
60
|
+
const chunkSize = 0x8000;
|
|
61
|
+
for (let i = 0; i < bytes.byteLength; i += chunkSize) {
|
|
62
|
+
binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));
|
|
63
|
+
}
|
|
64
|
+
return btoa(binary);
|
|
65
|
+
}
|
|
66
|
+
function __base64ToBytes(b64) {
|
|
67
|
+
const binary = atob(b64);
|
|
68
|
+
const bytes = new Uint8Array(binary.length);
|
|
69
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
70
|
+
return bytes;
|
|
71
|
+
}
|
|
72
|
+
function __encodeCodemodeValue(value) {
|
|
73
|
+
if (value instanceof Uint8Array) {
|
|
74
|
+
return { [__CODEMODE_BINARY_TAG]: "Uint8Array", data: __bytesToBase64(value) };
|
|
75
|
+
}
|
|
76
|
+
if (value instanceof ArrayBuffer) {
|
|
77
|
+
return { [__CODEMODE_BINARY_TAG]: "ArrayBuffer", data: __bytesToBase64(new Uint8Array(value)) };
|
|
78
|
+
}
|
|
79
|
+
if (ArrayBuffer.isView(value)) {
|
|
80
|
+
return { [__CODEMODE_BINARY_TAG]: "ArrayBufferView", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };
|
|
81
|
+
}
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
function __decodeCodemodeValue(value) {
|
|
85
|
+
if (!value || typeof value !== "object" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== "string") return value;
|
|
86
|
+
const bytes = __base64ToBytes(value.data);
|
|
87
|
+
if (value[__CODEMODE_BINARY_TAG] === "ArrayBuffer") {
|
|
88
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
89
|
+
}
|
|
90
|
+
return bytes;
|
|
91
|
+
}
|
|
92
|
+
function __stringifyForCodemode(value) {
|
|
93
|
+
return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));
|
|
94
|
+
}
|
|
95
|
+
function __parseForCodemode(json) {
|
|
96
|
+
return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));
|
|
97
|
+
}
|
|
98
|
+
`;
|
|
11
99
|
/**
|
|
12
100
|
* An RpcTarget that dispatches tool calls from the sandboxed Worker
|
|
13
101
|
* back to the host. Passed via Workers RPC to the dynamic Worker's
|
|
@@ -23,17 +111,15 @@ var ToolDispatcher = class extends RpcTarget {
|
|
|
23
111
|
}
|
|
24
112
|
async call(name, argsJson) {
|
|
25
113
|
const fn = this.#fns[name];
|
|
26
|
-
if (!fn) return
|
|
114
|
+
if (!fn) return stringifyForCodemode({ error: `Tool "${name}" not found` });
|
|
27
115
|
try {
|
|
28
116
|
if (this.#positionalArgs) {
|
|
29
|
-
const args = argsJson ?
|
|
30
|
-
|
|
31
|
-
return JSON.stringify({ result });
|
|
117
|
+
const args = argsJson ? parseForCodemode(argsJson) : [];
|
|
118
|
+
return stringifyForCodemode({ result: await fn(...Array.isArray(args) ? args : [args]) });
|
|
32
119
|
}
|
|
33
|
-
|
|
34
|
-
return JSON.stringify({ result });
|
|
120
|
+
return stringifyForCodemode({ result: await fn(argsJson ? parseForCodemode(argsJson) : {}) });
|
|
35
121
|
} catch (err) {
|
|
36
|
-
return
|
|
122
|
+
return stringifyForCodemode({ error: err instanceof Error ? err.message : String(err) });
|
|
37
123
|
}
|
|
38
124
|
}
|
|
39
125
|
};
|
|
@@ -78,7 +164,17 @@ var DynamicWorkerExecutor = class {
|
|
|
78
164
|
} else providers = providersOrFns;
|
|
79
165
|
const normalized = normalizeCode(code);
|
|
80
166
|
const timeoutMs = this.#timeout;
|
|
81
|
-
const RESERVED_NAMES = new Set([
|
|
167
|
+
const RESERVED_NAMES = new Set([
|
|
168
|
+
"__dispatchers",
|
|
169
|
+
"__logs",
|
|
170
|
+
"__CODEMODE_BINARY_TAG",
|
|
171
|
+
"__bytesToBase64",
|
|
172
|
+
"__base64ToBytes",
|
|
173
|
+
"__encodeCodemodeValue",
|
|
174
|
+
"__decodeCodemodeValue",
|
|
175
|
+
"__stringifyForCodemode",
|
|
176
|
+
"__parseForCodemode"
|
|
177
|
+
]);
|
|
82
178
|
const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
83
179
|
const seenNames = /* @__PURE__ */ new Set();
|
|
84
180
|
for (const provider of providers) {
|
|
@@ -105,9 +201,10 @@ var DynamicWorkerExecutor = class {
|
|
|
105
201
|
" console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };",
|
|
106
202
|
" console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };",
|
|
107
203
|
" console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };",
|
|
204
|
+
SANDBOX_CODEC,
|
|
108
205
|
...providers.map((p) => {
|
|
109
|
-
if (p.positionalArgs) return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (...args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName),
|
|
110
|
-
return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName),
|
|
206
|
+
if (p.positionalArgs) return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (...args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`;
|
|
207
|
+
return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args ?? {}));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`;
|
|
111
208
|
}),
|
|
112
209
|
"",
|
|
113
210
|
" try {",
|
|
@@ -127,7 +224,17 @@ var DynamicWorkerExecutor = class {
|
|
|
127
224
|
const dispatchers = {};
|
|
128
225
|
for (const provider of providers) {
|
|
129
226
|
const sanitizedFns = {};
|
|
130
|
-
|
|
227
|
+
const sanitizedNames = /* @__PURE__ */ new Map();
|
|
228
|
+
for (const [name, fn] of Object.entries(provider.fns)) {
|
|
229
|
+
const sanitizedName = sanitizeToolName(name);
|
|
230
|
+
const existingName = sanitizedNames.get(sanitizedName);
|
|
231
|
+
if (existingName && existingName !== name) return {
|
|
232
|
+
result: void 0,
|
|
233
|
+
error: `Tool names "${existingName}" and "${name}" both sanitize to "${sanitizedName}" in provider "${provider.name}"`
|
|
234
|
+
};
|
|
235
|
+
sanitizedNames.set(sanitizedName, name);
|
|
236
|
+
sanitizedFns[sanitizedName] = fn;
|
|
237
|
+
}
|
|
131
238
|
dispatchers[provider.name] = new ToolDispatcher(sanitizedFns, provider.positionalArgs);
|
|
132
239
|
}
|
|
133
240
|
const response = await this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#fns","#positionalArgs","#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\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n\n /**\n * When true, tools accept positional args instead of a single object arg.\n * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.\n *\n * Default tools use single-object args: `codemode.search({ query: \"test\" })`\n * Positional tools use normal args: `state.readFile(\"/path\")`\n */\n positionalArgs?: boolean;\n}\n\n// ── ResolvedProvider ──────────────────────────────────────────────────\n\n/**\n * Internal resolved form of a ToolProvider, ready for execution.\n * The tool functions have been extracted and keyed by sanitized name.\n */\nexport interface ResolvedProvider {\n name: string;\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n positionalArgs?: boolean;\n}\n\n// ── Executor ──────────────────────────────────────────────────────────\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable under their namespace inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n *\n * @param code - The code to execute in the sandbox.\n * @param providersOrFns - An array of `ResolvedProvider` (preferred), or a\n * plain `Record<string, fn>` for backwards compatibility (deprecated — will\n * be removed in the next major version).\n */\nexport interface Executor {\n execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// ── ToolDispatcher ────────────────────────────────────────────────────\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 #positionalArgs: boolean;\n\n constructor(\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>,\n positionalArgs = false\n ) {\n super();\n this.#fns = fns;\n this.#positionalArgs = positionalArgs;\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 if (this.#positionalArgs) {\n const args = argsJson ? JSON.parse(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return JSON.stringify({ result });\n }\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 ─────────────────────────────────────────────\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 *\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\n * ToolDispatchers (one per namespace) 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 *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\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 providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\"__dispatchers\", \"__logs\"]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map((p) => {\n if (p.positionalArgs) {\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), JSON.stringify(args));\\n` +\n ` const data = JSON.parse(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n }\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), JSON.stringify(args ?? {}));\\n` +\n ` const data = JSON.parse(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n });\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\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 ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\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 ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\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 proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n for (const [name, fn] of Object.entries(provider.fns)) {\n sanitizedFns[sanitizeToolName(name)] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(\n sanitizedFns,\n provider.positionalArgs\n );\n }\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(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\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":";;;;;;;;;;;;;;;AAoHA,IAAa,iBAAb,cAAoC,UAAU;CAC5C;CACA;CAEA,YACE,KACA,iBAAiB,OACjB;AACA,SAAO;AACP,QAAA,MAAY;AACZ,QAAA,iBAAuB;;CAGzB,MAAM,KAAK,MAAc,UAAmC;EAC1D,MAAM,KAAK,MAAA,IAAU;AACrB,MAAI,CAAC,GACH,QAAO,KAAK,UAAU,EAAE,OAAO,SAAS,KAAK,cAAc,CAAC;AAE9D,MAAI;AACF,OAAI,MAAA,gBAAsB;IACxB,MAAM,OAAO,WAAW,KAAK,MAAM,SAAS,GAAG,EAAE;IACjD,MAAM,SAAS,MAAM,GAAG,GAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,KAAK,CAAE;AACjE,WAAO,KAAK,UAAU,EAAE,QAAQ,CAAC;;GAGnC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GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,GAlCiB,UAAU,KAAK,MAAM;AACtC,QAAI,EAAE,eACJ,QACE,aAAa,EAAE,KAAK,oHAE2B,EAAE,KAAK;AAQ1D,WACE,aAAa,EAAE,KAAK,iHAE2B,EAAE,KAAK;KAOxD;GAYA;GACA;GACA;GACA;GACD,CACE,OAAO,CAAC,WAAW,CAAC,CACpB,OAAO;GACN;GACA,qGACE,YACA;GACF;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,CACD,KAAK,KAAK;EAKb,MAAM,cAA8C,EAAE;AACtD,OAAK,MAAM,YAAY,WAAW;GAChC,MAAM,eAGF,EAAE;AACN,QAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,SAAS,IAAI,CACnD,cAAa,iBAAiB,KAAK,IAAI;AAEzC,eAAY,SAAS,QAAQ,IAAI,eAC/B,cACA,SAAS,eACV;;EAqBH,MAAM,WAAW,MAlBF,MAAA,OAAa,IAAI,YAAY,OAAO,YAAY,WAAW;GACxE,mBAAmB;GACnB,oBAAoB,CAAC,gBAAgB;GACrC,YAAY;GACZ,SAAS;IACP,GAAG,MAAA;IACH,eAAe;IAChB;GACD,gBAAgB,MAAA;GACjB,EAAE,CAEuB,eAAe,CAOP,SAAS,YAAY;AAEvD,MAAI,SAAS,MACX,QAAO;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;AAG1E,SAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#fns","#positionalArgs","#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 type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\nexport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\n\nconst BINARY_TAG = \"__codemode_binary_v1__\";\n\ntype EncodedBinary = {\n [BINARY_TAG]: \"Uint8Array\" | \"ArrayBuffer\" | \"ArrayBufferView\";\n data: string;\n};\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength))\n );\n }\n return btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nfunction encodeCodemodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { [BINARY_TAG]: \"Uint8Array\", data: bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return {\n [BINARY_TAG]: \"ArrayBuffer\",\n data: bytesToBase64(new Uint8Array(value))\n };\n }\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return {\n [BINARY_TAG]: \"ArrayBufferView\",\n data: bytesToBase64(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n )\n };\n }\n return value;\n}\n\nfunction decodeCodemodeValue(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || !(BINARY_TAG in value)) {\n return value;\n }\n const encoded = value as EncodedBinary;\n if (typeof encoded.data !== \"string\") return value;\n const bytes = base64ToBytes(encoded.data);\n if (encoded[BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength\n );\n }\n return bytes;\n}\n\nfunction stringifyForCodemode(value: unknown): string {\n return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));\n}\n\nfunction parseForCodemode(json: string): unknown {\n return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));\n}\n\nconst SANDBOX_CODEC = String.raw`\n const __CODEMODE_BINARY_TAG = \"__codemode_binary_v1__\";\n function __bytesToBase64(bytes) {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));\n }\n return btoa(binary);\n }\n function __base64ToBytes(b64) {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n function __encodeCodemodeValue(value) {\n if (value instanceof Uint8Array) {\n return { [__CODEMODE_BINARY_TAG]: \"Uint8Array\", data: __bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBuffer\", data: __bytesToBase64(new Uint8Array(value)) };\n }\n if (ArrayBuffer.isView(value)) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBufferView\", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };\n }\n return value;\n }\n function __decodeCodemodeValue(value) {\n if (!value || typeof value !== \"object\" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== \"string\") return value;\n const bytes = __base64ToBytes(value.data);\n if (value[__CODEMODE_BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n return bytes;\n }\n function __stringifyForCodemode(value) {\n return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));\n }\n function __parseForCodemode(json) {\n return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));\n }\n`;\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n\n /**\n * When true, tools accept positional args instead of a single object arg.\n * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.\n *\n * Default tools use single-object args: `codemode.search({ query: \"test\" })`\n * Positional tools use normal args: `state.readFile(\"/path\")`\n */\n positionalArgs?: boolean;\n}\n\n// ── ToolDispatcher ────────────────────────────────────────────────────\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 #positionalArgs: boolean;\n\n constructor(\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>,\n positionalArgs = false\n ) {\n super();\n this.#fns = fns;\n this.#positionalArgs = positionalArgs;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return stringifyForCodemode({ error: `Tool \"${name}\" not found` });\n }\n try {\n if (this.#positionalArgs) {\n const args = argsJson ? parseForCodemode(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return stringifyForCodemode({ result });\n }\n const args = argsJson ? parseForCodemode(argsJson) : {};\n const result = await fn(args);\n return stringifyForCodemode({ result });\n } catch (err) {\n return stringifyForCodemode({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// ── DynamicWorkerExecutor ─────────────────────────────────────────────\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 *\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\n * ToolDispatchers (one per namespace) 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 *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\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 providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\n \"__dispatchers\",\n \"__logs\",\n \"__CODEMODE_BINARY_TAG\",\n \"__bytesToBase64\",\n \"__base64ToBytes\",\n \"__encodeCodemodeValue\",\n \"__decodeCodemodeValue\",\n \"__stringifyForCodemode\",\n \"__parseForCodemode\"\n ]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map((p) => {\n if (p.positionalArgs) {\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n }\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args ?? {}));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n });\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\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 SANDBOX_CODEC,\n ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\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 ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\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 proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(\n sanitizedFns,\n provider.positionalArgs\n );\n }\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(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\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":";;;;;;;;;;AAuBA,MAAM,aAAa;AAOnB,SAAS,cAAc,OAA2B;CAChD,IAAI,SAAS;CACb,MAAM,YAAY;CAClB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,YAAY,KAAK,WACzC,UAAU,OAAO,aACf,GAAG,MAAM,SAAS,GAAG,KAAK,IAAI,IAAI,WAAW,MAAM,WAAW,CAAC,CAChE;CAEH,OAAO,KAAK,OAAO;;AAGrB,SAAS,cAAc,KAAyB;CAC9C,MAAM,SAAS,KAAK,IAAI;CACxB,MAAM,QAAQ,IAAI,WAAW,OAAO,OAAO;CAC3C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KACjC,MAAM,KAAK,OAAO,WAAW,EAAE;CAEjC,OAAO;;AAGT,SAAS,oBAAoB,OAAyB;CACpD,IAAI,iBAAiB,YACnB,OAAO;GAAG,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O;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;EAG1E,OAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { JSONSchema7 } from "json-schema";
|
|
2
|
+
|
|
3
|
+
//#region src/json-schema-types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Convert a JSON Schema to a TypeScript type declaration.
|
|
6
|
+
*/
|
|
7
|
+
declare function jsonSchemaToType(
|
|
8
|
+
schema: JSONSchema7,
|
|
9
|
+
typeName: string
|
|
10
|
+
): string;
|
|
11
|
+
/**
|
|
12
|
+
* A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).
|
|
13
|
+
*/
|
|
14
|
+
interface JsonSchemaToolDescriptor {
|
|
15
|
+
description?: string;
|
|
16
|
+
inputSchema: JSONSchema7;
|
|
17
|
+
outputSchema?: JSONSchema7;
|
|
18
|
+
}
|
|
19
|
+
type JsonSchemaToolDescriptors = Record<string, JsonSchemaToolDescriptor>;
|
|
20
|
+
/**
|
|
21
|
+
* Generate TypeScript type definitions from tool descriptors with JSON Schema.
|
|
22
|
+
* This function has NO dependency on the AI SDK or Zod — it works purely with
|
|
23
|
+
* JSON Schema objects.
|
|
24
|
+
*
|
|
25
|
+
* Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool
|
|
26
|
+
* definitions, etc.) and don't need the AI SDK.
|
|
27
|
+
*/
|
|
28
|
+
declare function generateTypesFromJsonSchema(
|
|
29
|
+
tools: JsonSchemaToolDescriptors
|
|
30
|
+
): string;
|
|
31
|
+
//#endregion
|
|
32
|
+
export {
|
|
33
|
+
jsonSchemaToType as i,
|
|
34
|
+
JsonSchemaToolDescriptors as n,
|
|
35
|
+
generateTypesFromJsonSchema as r,
|
|
36
|
+
JsonSchemaToolDescriptor as t
|
|
37
|
+
};
|
|
38
|
+
//# sourceMappingURL=json-schema-types-1OL3uao0.d.ts.map
|
|
@@ -1,3 +1,44 @@
|
|
|
1
|
+
import * as acorn from "acorn";
|
|
2
|
+
//#region src/normalize.ts
|
|
3
|
+
/**
|
|
4
|
+
* Strip markdown code fences that LLMs commonly wrap code in.
|
|
5
|
+
* Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
|
|
6
|
+
*/
|
|
7
|
+
function stripCodeFences(code) {
|
|
8
|
+
const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
|
|
9
|
+
return match ? match[1] : code;
|
|
10
|
+
}
|
|
11
|
+
function normalizeCode(code) {
|
|
12
|
+
const trimmed = stripCodeFences(code.trim());
|
|
13
|
+
if (!trimmed.trim()) return "async () => {}";
|
|
14
|
+
const source = trimmed.trim();
|
|
15
|
+
try {
|
|
16
|
+
const ast = acorn.parse(source, {
|
|
17
|
+
ecmaVersion: "latest",
|
|
18
|
+
sourceType: "module"
|
|
19
|
+
});
|
|
20
|
+
if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
|
|
21
|
+
if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
|
|
22
|
+
}
|
|
23
|
+
if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
|
|
24
|
+
const decl = ast.body[0].declaration;
|
|
25
|
+
const inner = source.slice(decl.start, decl.end);
|
|
26
|
+
if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
|
|
27
|
+
if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
|
|
28
|
+
return normalizeCode(inner);
|
|
29
|
+
}
|
|
30
|
+
if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
|
|
31
|
+
const last = ast.body[ast.body.length - 1];
|
|
32
|
+
if (last?.type === "ExpressionStatement") {
|
|
33
|
+
const exprStmt = last;
|
|
34
|
+
return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
|
|
35
|
+
}
|
|
36
|
+
return `async () => {\n${source}\n}`;
|
|
37
|
+
} catch {
|
|
38
|
+
return `async () => {\n${source}\n}`;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
1
42
|
//#region src/utils.ts
|
|
2
43
|
const JS_RESERVED = new Set([
|
|
3
44
|
"abstract",
|
|
@@ -327,6 +368,6 @@ ${availableTools}
|
|
|
327
368
|
`.trim();
|
|
328
369
|
}
|
|
329
370
|
//#endregion
|
|
330
|
-
export { sanitizeToolName as a, escapeJsDoc as i, jsonSchemaToType as n, toPascalCase as o, jsonSchemaToTypeString as r, generateTypesFromJsonSchema as t };
|
|
371
|
+
export { sanitizeToolName as a, escapeJsDoc as i, jsonSchemaToType as n, toPascalCase as o, jsonSchemaToTypeString as r, normalizeCode as s, generateTypesFromJsonSchema as t };
|
|
331
372
|
|
|
332
|
-
//# sourceMappingURL=json-schema-types-
|
|
373
|
+
//# sourceMappingURL=json-schema-types-CVt4X9cw.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-schema-types-CVt4X9cw.js","names":[],"sources":["../src/normalize.ts","../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n","const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramLines) {\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"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MAAM,qEAAO;CAChC,OAAO,QAAQ,MAAM,KAAK;;AAG5B,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,MAAM,CAAC;CAC5C,IAAI,CAAC,QAAQ,MAAM,EAAE,OAAO;CAE5B,MAAM,SAAS,QAAQ,MAAM;CAE7B,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;GACb,CAAC;EAGF,IAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS;OAClC,IAAI,KAAK,GAAiC,WAC/C,SAAS,2BAA2B,OAAO;;EAItD,IACE,IAAI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