@cloudflare/codemode 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -35
- package/dist/ai.d.ts +14 -48
- package/dist/ai.js +2 -216
- package/dist/executor-C1NPN-nW.d.ts +186 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +72 -23
- package/dist/index.js.map +1 -1
- package/dist/{normalize-xNh5CsfI.js → json-schema-types-DoQ0VISs.js} +2 -43
- package/dist/json-schema-types-DoQ0VISs.js.map +1 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +314 -0
- package/dist/mcp.js.map +1 -0
- package/dist/tool-B0ZYASro.js +342 -0
- package/dist/tool-B0ZYASro.js.map +1 -0
- package/dist/tool-BQ5SO4OJ.d.ts +59 -0
- package/package.json +11 -1
- package/dist/ai.js.map +0 -1
- package/dist/executor-BjlGw-Dd.d.ts +0 -70
- package/dist/normalize-xNh5CsfI.js.map +0 -1
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { RpcTarget } from "cloudflare:workers";
|
|
2
|
+
import { ToolSet } from "ai";
|
|
3
|
+
import { ZodType } from "zod";
|
|
4
|
+
|
|
5
|
+
//#region src/tool-types.d.ts
|
|
6
|
+
interface ToolDescriptor {
|
|
7
|
+
description?: string;
|
|
8
|
+
inputSchema: ZodType;
|
|
9
|
+
outputSchema?: ZodType;
|
|
10
|
+
execute?: (args: unknown) => Promise<unknown>;
|
|
11
|
+
}
|
|
12
|
+
type ToolDescriptors = Record<string, ToolDescriptor>;
|
|
13
|
+
/**
|
|
14
|
+
* Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
|
|
15
|
+
* These types can be included in tool descriptions to help LLMs write correct code.
|
|
16
|
+
*
|
|
17
|
+
* Requires the `ai` peer dependency. For a version that works with plain JSON Schema
|
|
18
|
+
* objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
|
|
19
|
+
*/
|
|
20
|
+
declare function generateTypes(
|
|
21
|
+
tools: ToolDescriptors | ToolSet,
|
|
22
|
+
namespace?: string
|
|
23
|
+
): string;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/executor.d.ts
|
|
26
|
+
interface ExecuteResult {
|
|
27
|
+
result: unknown;
|
|
28
|
+
error?: string;
|
|
29
|
+
logs?: string[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A minimal tool record — just a description and an execute function.
|
|
33
|
+
* Use this for providers that supply their own `types` and don't need
|
|
34
|
+
* schema-based type generation (e.g. stateTools).
|
|
35
|
+
*/
|
|
36
|
+
type SimpleToolRecord = Record<
|
|
37
|
+
string,
|
|
38
|
+
{
|
|
39
|
+
description?: string;
|
|
40
|
+
execute: (args: unknown) => Promise<unknown>;
|
|
41
|
+
}
|
|
42
|
+
>;
|
|
43
|
+
/**
|
|
44
|
+
* All tool record types accepted by a ToolProvider.
|
|
45
|
+
*/
|
|
46
|
+
type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;
|
|
47
|
+
/**
|
|
48
|
+
* A ToolProvider contributes tools to the codemode sandbox under a namespace.
|
|
49
|
+
*
|
|
50
|
+
* Each provider's tools are accessible as `name.toolName()` in sandbox code.
|
|
51
|
+
* If `name` is omitted, tools are exposed under the default `codemode.*` namespace.
|
|
52
|
+
*
|
|
53
|
+
* @example Multiple providers with different namespaces
|
|
54
|
+
* ```ts
|
|
55
|
+
* createCodeTool({
|
|
56
|
+
* tools: [
|
|
57
|
+
* { name: "github", tools: githubTools },
|
|
58
|
+
* { name: "shell", tools: shellTools },
|
|
59
|
+
* { tools: aiTools }, // default "codemode" namespace
|
|
60
|
+
* ],
|
|
61
|
+
* executor,
|
|
62
|
+
* });
|
|
63
|
+
* // sandbox: github.listIssues(), shell.exec(), codemode.search()
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
interface ToolProvider {
|
|
67
|
+
/** Namespace prefix in the sandbox (e.g. "state", "mcp"). Defaults to "codemode". */
|
|
68
|
+
name?: string;
|
|
69
|
+
/** Tools exposed as `namespace.toolName()` in the sandbox. */
|
|
70
|
+
tools: ToolProviderTools;
|
|
71
|
+
/** Type declarations for the LLM. Auto-generated from `tools` if omitted. */
|
|
72
|
+
types?: string;
|
|
73
|
+
/**
|
|
74
|
+
* When true, tools accept positional args instead of a single object arg.
|
|
75
|
+
* The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.
|
|
76
|
+
*
|
|
77
|
+
* Default tools use single-object args: `codemode.search({ query: "test" })`
|
|
78
|
+
* Positional tools use normal args: `state.readFile("/path")`
|
|
79
|
+
*/
|
|
80
|
+
positionalArgs?: boolean;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Internal resolved form of a ToolProvider, ready for execution.
|
|
84
|
+
* The tool functions have been extracted and keyed by sanitized name.
|
|
85
|
+
*/
|
|
86
|
+
interface ResolvedProvider {
|
|
87
|
+
name: string;
|
|
88
|
+
fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
|
|
89
|
+
positionalArgs?: boolean;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* An executor runs LLM-generated code in a sandbox, making the provided
|
|
93
|
+
* tool functions callable under their namespace inside the sandbox.
|
|
94
|
+
*
|
|
95
|
+
* Implementations should never throw — errors are returned in `ExecuteResult.error`.
|
|
96
|
+
*
|
|
97
|
+
* @param code - The code to execute in the sandbox.
|
|
98
|
+
* @param providersOrFns - An array of `ResolvedProvider` (preferred), or a
|
|
99
|
+
* plain `Record<string, fn>` for backwards compatibility (deprecated — will
|
|
100
|
+
* be removed in the next major version).
|
|
101
|
+
*/
|
|
102
|
+
interface Executor {
|
|
103
|
+
execute(
|
|
104
|
+
code: string,
|
|
105
|
+
providersOrFns:
|
|
106
|
+
| ResolvedProvider[]
|
|
107
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
108
|
+
): Promise<ExecuteResult>;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* An RpcTarget that dispatches tool calls from the sandboxed Worker
|
|
112
|
+
* back to the host. Passed via Workers RPC to the dynamic Worker's
|
|
113
|
+
* evaluate() method — no globalOutbound or Fetcher bindings needed.
|
|
114
|
+
*/
|
|
115
|
+
declare class ToolDispatcher extends RpcTarget {
|
|
116
|
+
#private;
|
|
117
|
+
constructor(
|
|
118
|
+
fns: Record<string, (...args: unknown[]) => Promise<unknown>>,
|
|
119
|
+
positionalArgs?: boolean
|
|
120
|
+
);
|
|
121
|
+
call(name: string, argsJson: string): Promise<string>;
|
|
122
|
+
}
|
|
123
|
+
interface DynamicWorkerExecutorOptions {
|
|
124
|
+
loader: WorkerLoader;
|
|
125
|
+
/**
|
|
126
|
+
* Timeout in milliseconds for code execution. Defaults to 30000 (30s).
|
|
127
|
+
*/
|
|
128
|
+
timeout?: number;
|
|
129
|
+
/**
|
|
130
|
+
* Controls outbound network access from sandboxed code.
|
|
131
|
+
* - `null` (default): fetch() and connect() throw — sandbox is fully isolated.
|
|
132
|
+
* - `undefined`: inherits parent Worker's network access (full internet).
|
|
133
|
+
* - A `Fetcher`: all outbound requests route through this handler.
|
|
134
|
+
*/
|
|
135
|
+
globalOutbound?: Fetcher | null;
|
|
136
|
+
/**
|
|
137
|
+
* Additional modules to make available in the sandbox.
|
|
138
|
+
* Keys are module specifiers (e.g. `"mylib.js"`), values are module source code.
|
|
139
|
+
*
|
|
140
|
+
* Note: the key `"executor.js"` is reserved and will be ignored if provided.
|
|
141
|
+
*/
|
|
142
|
+
modules?: Record<string, string>;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Executes code in an isolated Cloudflare Worker via WorkerLoader.
|
|
146
|
+
* Tool calls are dispatched via Workers RPC — the host passes
|
|
147
|
+
* ToolDispatchers (one per namespace) to the Worker's evaluate() method.
|
|
148
|
+
*
|
|
149
|
+
* External fetch() and connect() are blocked by default via
|
|
150
|
+
* `globalOutbound: null` (runtime-enforced). Pass a Fetcher to
|
|
151
|
+
* `globalOutbound` to allow controlled outbound access.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```ts
|
|
155
|
+
* const result = await executor.execute(code, [
|
|
156
|
+
* { name: "codemode", fns: { search: searchFn } },
|
|
157
|
+
* { name: "state", fns: { readFile: readFileFn } },
|
|
158
|
+
* ]);
|
|
159
|
+
* // sandbox has both codemode.search() and state.readFile()
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
declare class DynamicWorkerExecutor implements Executor {
|
|
163
|
+
#private;
|
|
164
|
+
constructor(options: DynamicWorkerExecutorOptions);
|
|
165
|
+
execute(
|
|
166
|
+
code: string,
|
|
167
|
+
providersOrFns:
|
|
168
|
+
| ResolvedProvider[]
|
|
169
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
170
|
+
): Promise<ExecuteResult>;
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
export {
|
|
174
|
+
ResolvedProvider as a,
|
|
175
|
+
ToolProviderTools as c,
|
|
176
|
+
generateTypes as d,
|
|
177
|
+
Executor as i,
|
|
178
|
+
ToolDescriptor as l,
|
|
179
|
+
DynamicWorkerExecutorOptions as n,
|
|
180
|
+
ToolDispatcher as o,
|
|
181
|
+
ExecuteResult as r,
|
|
182
|
+
ToolProvider as s,
|
|
183
|
+
DynamicWorkerExecutor as t,
|
|
184
|
+
ToolDescriptors as u
|
|
185
|
+
};
|
|
186
|
+
//# sourceMappingURL=executor-C1NPN-nW.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
|
-
a as
|
|
2
|
+
a as ResolvedProvider,
|
|
3
3
|
i as Executor,
|
|
4
4
|
n as DynamicWorkerExecutorOptions,
|
|
5
|
+
o as ToolDispatcher,
|
|
5
6
|
r as ExecuteResult,
|
|
7
|
+
s as ToolProvider,
|
|
6
8
|
t as DynamicWorkerExecutor
|
|
7
|
-
} from "./executor-
|
|
9
|
+
} from "./executor-C1NPN-nW.js";
|
|
10
|
+
import { i as resolveProvider } from "./tool-BQ5SO4OJ.js";
|
|
8
11
|
import { JSONSchema7 } from "json-schema";
|
|
9
12
|
|
|
10
13
|
//#region src/utils.d.ts
|
|
@@ -54,10 +57,13 @@ export {
|
|
|
54
57
|
type Executor,
|
|
55
58
|
type JsonSchemaToolDescriptor,
|
|
56
59
|
type JsonSchemaToolDescriptors,
|
|
60
|
+
type ResolvedProvider,
|
|
57
61
|
ToolDispatcher,
|
|
62
|
+
type ToolProvider,
|
|
58
63
|
generateTypesFromJsonSchema,
|
|
59
64
|
jsonSchemaToType,
|
|
60
65
|
normalizeCode,
|
|
66
|
+
resolveProvider,
|
|
61
67
|
sanitizeToolName
|
|
62
68
|
};
|
|
63
69
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as normalizeCode, r as resolveProvider } from "./tool-B0ZYASro.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
|
/**
|
|
@@ -14,14 +15,21 @@ import { RpcTarget } from "cloudflare:workers";
|
|
|
14
15
|
*/
|
|
15
16
|
var ToolDispatcher = class extends RpcTarget {
|
|
16
17
|
#fns;
|
|
17
|
-
|
|
18
|
+
#positionalArgs;
|
|
19
|
+
constructor(fns, positionalArgs = false) {
|
|
18
20
|
super();
|
|
19
21
|
this.#fns = fns;
|
|
22
|
+
this.#positionalArgs = positionalArgs;
|
|
20
23
|
}
|
|
21
24
|
async call(name, argsJson) {
|
|
22
25
|
const fn = this.#fns[name];
|
|
23
26
|
if (!fn) return JSON.stringify({ error: `Tool "${name}" not found` });
|
|
24
27
|
try {
|
|
28
|
+
if (this.#positionalArgs) {
|
|
29
|
+
const args = argsJson ? JSON.parse(argsJson) : [];
|
|
30
|
+
const result = await fn(...Array.isArray(args) ? args : [args]);
|
|
31
|
+
return JSON.stringify({ result });
|
|
32
|
+
}
|
|
25
33
|
const result = await fn(argsJson ? JSON.parse(argsJson) : {});
|
|
26
34
|
return JSON.stringify({ result });
|
|
27
35
|
} catch (err) {
|
|
@@ -31,47 +39,81 @@ var ToolDispatcher = class extends RpcTarget {
|
|
|
31
39
|
};
|
|
32
40
|
/**
|
|
33
41
|
* Executes code in an isolated Cloudflare Worker via WorkerLoader.
|
|
34
|
-
* Tool calls are dispatched via Workers RPC — the host passes
|
|
35
|
-
*
|
|
42
|
+
* Tool calls are dispatched via Workers RPC — the host passes
|
|
43
|
+
* ToolDispatchers (one per namespace) to the Worker's evaluate() method.
|
|
36
44
|
*
|
|
37
45
|
* External fetch() and connect() are blocked by default via
|
|
38
46
|
* `globalOutbound: null` (runtime-enforced). Pass a Fetcher to
|
|
39
47
|
* `globalOutbound` to allow controlled outbound access.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* const result = await executor.execute(code, [
|
|
52
|
+
* { name: "codemode", fns: { search: searchFn } },
|
|
53
|
+
* { name: "state", fns: { readFile: readFileFn } },
|
|
54
|
+
* ]);
|
|
55
|
+
* // sandbox has both codemode.search() and state.readFile()
|
|
56
|
+
* ```
|
|
40
57
|
*/
|
|
41
58
|
var DynamicWorkerExecutor = class {
|
|
42
59
|
#loader;
|
|
43
60
|
#timeout;
|
|
44
61
|
#globalOutbound;
|
|
62
|
+
#modules;
|
|
45
63
|
constructor(options) {
|
|
46
64
|
this.#loader = options.loader;
|
|
47
65
|
this.#timeout = options.timeout ?? 3e4;
|
|
48
66
|
this.#globalOutbound = options.globalOutbound ?? null;
|
|
67
|
+
const { "executor.js": _, ...safeModules } = options.modules ?? {};
|
|
68
|
+
this.#modules = safeModules;
|
|
49
69
|
}
|
|
50
|
-
async execute(code,
|
|
70
|
+
async execute(code, providersOrFns) {
|
|
71
|
+
let providers;
|
|
72
|
+
if (!Array.isArray(providersOrFns)) {
|
|
73
|
+
console.warn("[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. Use ResolvedProvider[] instead. This will be removed in the next major version.");
|
|
74
|
+
providers = [{
|
|
75
|
+
name: "codemode",
|
|
76
|
+
fns: providersOrFns
|
|
77
|
+
}];
|
|
78
|
+
} else providers = providersOrFns;
|
|
79
|
+
const normalized = normalizeCode(code);
|
|
51
80
|
const timeoutMs = this.#timeout;
|
|
52
|
-
const
|
|
81
|
+
const RESERVED_NAMES = new Set(["__dispatchers", "__logs"]);
|
|
82
|
+
const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
83
|
+
const seenNames = /* @__PURE__ */ new Set();
|
|
84
|
+
for (const provider of providers) {
|
|
85
|
+
if (RESERVED_NAMES.has(provider.name)) return {
|
|
86
|
+
result: void 0,
|
|
87
|
+
error: `Provider name "${provider.name}" is reserved`
|
|
88
|
+
};
|
|
89
|
+
if (!VALID_IDENT.test(provider.name)) return {
|
|
90
|
+
result: void 0,
|
|
91
|
+
error: `Provider name "${provider.name}" is not a valid JavaScript identifier`
|
|
92
|
+
};
|
|
93
|
+
if (seenNames.has(provider.name)) return {
|
|
94
|
+
result: void 0,
|
|
95
|
+
error: `Duplicate provider name "${provider.name}"`
|
|
96
|
+
};
|
|
97
|
+
seenNames.add(provider.name);
|
|
98
|
+
}
|
|
99
|
+
const executorModule = [
|
|
53
100
|
"import { WorkerEntrypoint } from \"cloudflare:workers\";",
|
|
54
101
|
"",
|
|
55
102
|
"export default class CodeExecutor extends WorkerEntrypoint {",
|
|
56
|
-
" async evaluate(
|
|
103
|
+
" async evaluate(__dispatchers = {}) {",
|
|
57
104
|
" const __logs = [];",
|
|
58
105
|
" console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };",
|
|
59
106
|
" console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };",
|
|
60
107
|
" console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };",
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
" if (data.error) throw new Error(data.error);",
|
|
66
|
-
" return data.result;",
|
|
67
|
-
" }",
|
|
68
|
-
" });",
|
|
108
|
+
...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), JSON.stringify(args));\n const data = JSON.parse(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n }\n });`;
|
|
110
|
+
return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (args) => {\n const resJson = await __dispatchers.${p.name}.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 });`;
|
|
111
|
+
}),
|
|
69
112
|
"",
|
|
70
113
|
" try {",
|
|
71
114
|
" const result = await Promise.race([",
|
|
72
115
|
" ("
|
|
73
|
-
].
|
|
74
|
-
const moduleSuffix = [
|
|
116
|
+
].concat([normalized]).concat([
|
|
75
117
|
")(),",
|
|
76
118
|
" new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), " + timeoutMs + "))",
|
|
77
119
|
" ]);",
|
|
@@ -81,16 +123,23 @@ var DynamicWorkerExecutor = class {
|
|
|
81
123
|
" }",
|
|
82
124
|
" }",
|
|
83
125
|
"}"
|
|
84
|
-
].join("\n");
|
|
85
|
-
const
|
|
86
|
-
const
|
|
126
|
+
]).join("\n");
|
|
127
|
+
const dispatchers = {};
|
|
128
|
+
for (const provider of providers) {
|
|
129
|
+
const sanitizedFns = {};
|
|
130
|
+
for (const [name, fn] of Object.entries(provider.fns)) sanitizedFns[sanitizeToolName(name)] = fn;
|
|
131
|
+
dispatchers[provider.name] = new ToolDispatcher(sanitizedFns, provider.positionalArgs);
|
|
132
|
+
}
|
|
87
133
|
const response = await this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({
|
|
88
134
|
compatibilityDate: "2025-06-01",
|
|
89
135
|
compatibilityFlags: ["nodejs_compat"],
|
|
90
136
|
mainModule: "executor.js",
|
|
91
|
-
modules: {
|
|
137
|
+
modules: {
|
|
138
|
+
...this.#modules,
|
|
139
|
+
"executor.js": executorModule
|
|
140
|
+
},
|
|
92
141
|
globalOutbound: this.#globalOutbound
|
|
93
|
-
})).getEntrypoint().evaluate(
|
|
142
|
+
})).getEntrypoint().evaluate(dispatchers);
|
|
94
143
|
if (response.error) return {
|
|
95
144
|
result: void 0,
|
|
96
145
|
error: response.error,
|
|
@@ -103,6 +152,6 @@ var DynamicWorkerExecutor = class {
|
|
|
103
152
|
}
|
|
104
153
|
};
|
|
105
154
|
//#endregion
|
|
106
|
-
export { DynamicWorkerExecutor, ToolDispatcher, generateTypesFromJsonSchema, jsonSchemaToType, normalizeCode, sanitizeToolName };
|
|
155
|
+
export { DynamicWorkerExecutor, ToolDispatcher, generateTypesFromJsonSchema, jsonSchemaToType, normalizeCode, resolveProvider, sanitizeToolName };
|
|
107
156
|
|
|
108
157
|
//# 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 + code + moduleSuffix;\n\n const dispatcher = new ToolDispatcher(fns);\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 \"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 };\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EAAE,CAEuB,eAAe,CAOP,SAAS,WAAW;AAEtD,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 { 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,MAAM,SAAS,MAAM,GADR,WAAW,KAAK,MAAM,SAAS,GAAG,EAAE,CACpB;AAC7B,UAAO,KAAK,UAAU,EAAE,QAAQ,CAAC;WAC1B,KAAK;AACZ,UAAO,KAAK,UAAU,EACpB,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,EACxD,CAAC;;;;;;;;;;;;;;;;;;;;;;AA+CR,IAAa,wBAAb,MAAuD;CACrD;CACA;CACA;CACA;CAEA,YAAY,SAAuC;AACjD,QAAA,SAAe,QAAQ;AACvB,QAAA,UAAgB,QAAQ,WAAW;AACnC,QAAA,iBAAuB,QAAQ,kBAAkB;EACjD,MAAM,EAAE,eAAe,GAAG,GAAG,gBAAgB,QAAQ,WAAW,EAAE;AAClE,QAAA,UAAg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I,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,4 +1,3 @@
|
|
|
1
|
-
import * as acorn from "acorn";
|
|
2
1
|
//#region src/utils.ts
|
|
3
2
|
const JS_RESERVED = new Set([
|
|
4
3
|
"abstract",
|
|
@@ -328,46 +327,6 @@ ${availableTools}
|
|
|
328
327
|
`.trim();
|
|
329
328
|
}
|
|
330
329
|
//#endregion
|
|
331
|
-
|
|
332
|
-
/**
|
|
333
|
-
* Strip markdown code fences that LLMs commonly wrap code in.
|
|
334
|
-
* Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
|
|
335
|
-
*/
|
|
336
|
-
function stripCodeFences(code) {
|
|
337
|
-
const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
|
|
338
|
-
return match ? match[1] : code;
|
|
339
|
-
}
|
|
340
|
-
function normalizeCode(code) {
|
|
341
|
-
const trimmed = stripCodeFences(code.trim());
|
|
342
|
-
if (!trimmed.trim()) return "async () => {}";
|
|
343
|
-
const source = trimmed.trim();
|
|
344
|
-
try {
|
|
345
|
-
const ast = acorn.parse(source, {
|
|
346
|
-
ecmaVersion: "latest",
|
|
347
|
-
sourceType: "module"
|
|
348
|
-
});
|
|
349
|
-
if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
|
|
350
|
-
if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
|
|
351
|
-
}
|
|
352
|
-
if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
|
|
353
|
-
const decl = ast.body[0].declaration;
|
|
354
|
-
const inner = source.slice(decl.start, decl.end);
|
|
355
|
-
if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
|
|
356
|
-
if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
|
|
357
|
-
return normalizeCode(inner);
|
|
358
|
-
}
|
|
359
|
-
if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
|
|
360
|
-
const last = ast.body[ast.body.length - 1];
|
|
361
|
-
if (last?.type === "ExpressionStatement") {
|
|
362
|
-
const exprStmt = last;
|
|
363
|
-
return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
|
|
364
|
-
}
|
|
365
|
-
return `async () => {\n${source}\n}`;
|
|
366
|
-
} catch {
|
|
367
|
-
return `async () => {\n${source}\n}`;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
//#endregion
|
|
371
|
-
export { escapeJsDoc as a, jsonSchemaToTypeString as i, generateTypesFromJsonSchema as n, sanitizeToolName as o, jsonSchemaToType as r, toPascalCase as s, normalizeCode as t };
|
|
330
|
+
export { sanitizeToolName as a, escapeJsDoc as i, jsonSchemaToType as n, toPascalCase as o, jsonSchemaToTypeString as r, generateTypesFromJsonSchema as t };
|
|
372
331
|
|
|
373
|
-
//# sourceMappingURL=
|
|
332
|
+
//# sourceMappingURL=json-schema-types-DoQ0VISs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-schema-types-DoQ0VISs.js","names":[],"sources":["../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["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":";AAAA,MAAM,cAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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BAAkB,UAAU,SAAS;AACrC,qBAAkB,UAAU,SAAS;AAErC,qBAAkB,iBAAiB,YAAY,SAAS,CAAC;AACzD,qBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;AACpF,qBAAkB;;;AAItB,kBAAiB,8BAA8B,eAAe;AAE9D,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { i as Executor } from "./executor-C1NPN-nW.js";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
|
|
4
|
+
//#region src/mcp.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Wrap an existing MCP server with a single codemode `code` tool.
|
|
7
|
+
*
|
|
8
|
+
* Connects to the upstream server via in-memory transport, discovers its
|
|
9
|
+
* tools, and returns a new MCP server with a `code` tool that exposes
|
|
10
|
+
* all upstream tools as typed methods.
|
|
11
|
+
*/
|
|
12
|
+
interface CodeMcpServerOptions {
|
|
13
|
+
server: McpServer;
|
|
14
|
+
executor: Executor;
|
|
15
|
+
}
|
|
16
|
+
declare function codeMcpServer(
|
|
17
|
+
options: CodeMcpServerOptions
|
|
18
|
+
): Promise<McpServer>;
|
|
19
|
+
interface RequestOptions {
|
|
20
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
21
|
+
path: string;
|
|
22
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
23
|
+
body?: unknown;
|
|
24
|
+
contentType?: string;
|
|
25
|
+
rawBody?: boolean;
|
|
26
|
+
}
|
|
27
|
+
interface OpenApiMcpServerOptions {
|
|
28
|
+
spec: Record<string, unknown>;
|
|
29
|
+
executor: Executor;
|
|
30
|
+
request: (options: RequestOptions) => Promise<unknown>;
|
|
31
|
+
name?: string;
|
|
32
|
+
version?: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Create an MCP server with search + execute tools from an OpenAPI spec.
|
|
37
|
+
*
|
|
38
|
+
* The search tool lets the LLM query the spec to find endpoints.
|
|
39
|
+
* The execute tool lets the LLM call the API via a user-provided
|
|
40
|
+
* request function that runs on the host (auth never enters the sandbox).
|
|
41
|
+
*/
|
|
42
|
+
declare function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer;
|
|
43
|
+
//#endregion
|
|
44
|
+
export {
|
|
45
|
+
CodeMcpServerOptions,
|
|
46
|
+
OpenApiMcpServerOptions,
|
|
47
|
+
RequestOptions,
|
|
48
|
+
codeMcpServer,
|
|
49
|
+
openApiMcpServer
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=mcp.d.ts.map
|