@cloudflare/codemode 0.3.3 → 0.3.5

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.
@@ -0,0 +1,36 @@
1
+ //#region src/executor-types.d.ts
2
+ /**
3
+ * Shared executor contract used by all codemode runtimes.
4
+ */
5
+ interface ExecuteResult {
6
+ result: unknown;
7
+ error?: string;
8
+ logs?: string[];
9
+ }
10
+ /**
11
+ * Internal resolved form of a tool provider, ready for execution.
12
+ * The tool functions are keyed by tool name and exposed under `name.*`
13
+ * inside the sandbox.
14
+ */
15
+ interface ResolvedProvider {
16
+ name: string;
17
+ fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
18
+ positionalArgs?: boolean;
19
+ }
20
+ /**
21
+ * An executor runs LLM-generated code in a sandbox, making the provided
22
+ * tool functions callable under their namespace inside the sandbox.
23
+ *
24
+ * Implementations should never throw — errors are returned in `ExecuteResult.error`.
25
+ */
26
+ interface Executor {
27
+ execute(
28
+ code: string,
29
+ providersOrFns:
30
+ | ResolvedProvider[]
31
+ | Record<string, (...args: unknown[]) => Promise<unknown>>
32
+ ): Promise<ExecuteResult>;
33
+ }
34
+ //#endregion
35
+ export { Executor as n, ResolvedProvider as r, ExecuteResult as t };
36
+ //# sourceMappingURL=executor-types-CJ06IBzw.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,14 +1,21 @@
1
1
  import {
2
- a as ResolvedProvider,
3
- i as Executor,
2
+ i as ToolProvider,
4
3
  n as DynamicWorkerExecutorOptions,
5
- o as ToolDispatcher,
6
- r as ExecuteResult,
7
- s as ToolProvider,
4
+ r as ToolDispatcher,
8
5
  t as DynamicWorkerExecutor
9
- } from "./executor-wZjYdqEX.js";
10
- import { t as resolveProvider } from "./resolve-DULSpsq2.js";
11
- import { JSONSchema7 } from "json-schema";
6
+ } from "./executor-C-DgAHLS.js";
7
+ import {
8
+ n as Executor,
9
+ r as ResolvedProvider,
10
+ t as ExecuteResult
11
+ } from "./executor-types-CJ06IBzw.js";
12
+ import {
13
+ i as jsonSchemaToType,
14
+ n as JsonSchemaToolDescriptors,
15
+ r as generateTypesFromJsonSchema,
16
+ t as JsonSchemaToolDescriptor
17
+ } from "./json-schema-types-1OL3uao0.js";
18
+ import { t as resolveProvider } from "./resolve-E1SKV37h.js";
12
19
 
13
20
  //#region src/utils.d.ts
14
21
  /**
@@ -18,35 +25,6 @@ import { JSONSchema7 } from "json-schema";
18
25
  */
19
26
  declare function sanitizeToolName(name: string): string;
20
27
  //#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
28
  //#region src/normalize.d.ts
51
29
  declare function normalizeCode(code: string): string;
52
30
  //#endregion
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { i as normalizeCode, r as resolveProvider } from "./resolve-DIQRkRqQ.js";
2
- import { a as sanitizeToolName, n as jsonSchemaToType, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
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
  /**
@@ -127,7 +127,17 @@ var DynamicWorkerExecutor = class {
127
127
  const dispatchers = {};
128
128
  for (const provider of providers) {
129
129
  const sanitizedFns = {};
130
- for (const [name, fn] of Object.entries(provider.fns)) sanitizedFns[sanitizeToolName(name)] = fn;
130
+ const sanitizedNames = /* @__PURE__ */ new Map();
131
+ for (const [name, fn] of Object.entries(provider.fns)) {
132
+ const sanitizedName = sanitizeToolName(name);
133
+ const existingName = sanitizedNames.get(sanitizedName);
134
+ if (existingName && existingName !== name) return {
135
+ result: void 0,
136
+ error: `Tool names "${existingName}" and "${name}" both sanitize to "${sanitizedName}" in provider "${provider.name}"`
137
+ };
138
+ sanitizedNames.set(sanitizedName, name);
139
+ sanitizedFns[sanitizedName] = fn;
140
+ }
131
141
  dispatchers[provider.name] = new ToolDispatcher(sanitizedFns, provider.positionalArgs);
132
142
  }
133
143
  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,UAA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EA6B9B,MAAM,iBAAiB;GACrB;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\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 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 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":";;;;;;;;;;;;;;;AAsFA,IAAa,iBAAb,cAAoC,UAAU;CAC5C;CACA;CAEA,YACE,KACA,iBAAiB,OACjB;EACA,OAAO;EACP,KAAKA,OAAO;EACZ,KAAKC,kBAAkB;;CAGzB,MAAM,KAAK,MAAc,UAAmC;EAC1D,MAAM,KAAK,KAAKD,KAAK;EACrB,IAAI,CAAC,IACH,OAAO,KAAK,UAAU,EAAE,OAAO,SAAS,KAAK,cAAc,CAAC;EAE9D,IAAI;GACF,IAAI,KAAKC,iBAAiB;IACxB,MAAM,OAAO,WAAW,KAAK,MAAM,SAAS,GAAG,EAAE;IACjD,MAAM,SAAS,MAAM,GAAG,GAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC,KAAK,CAAE;IACjE,OAAO,KAA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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-DoQ0VISs.js.map
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":";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AK,YAAY,GAAG,QAAQ,UAAU,IAAI,CAAC,CAAC;GAGzD,MAAM,YAAY,WAAW,KAAK,MAAM,QAAQ,IAAI,CAAC,KAAK,KAAK;GAC/D,kBAAkB,YAAY,UAAU;GACxC,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;GACpF,kBAAkB;UACZ;GACN,kBAAkB,UAAU,SAAS;GACrC,kBAAkB,UAAU,SAAS;GAErC,kBAAkB,iBAAiB,YAAY,SAAS,CAAC;GACzD,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;GACpF,kBAAkB;;;CAItB,iBAAiB,8BAA8B,eAAe;CAE9D,OAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
package/dist/mcp.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as Executor } from "./executor-wZjYdqEX.js";
1
+ import { n as Executor } from "./executor-types-CJ06IBzw.js";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
 
4
4
  //#region src/mcp.d.ts
@@ -12,6 +12,12 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12
12
  interface CodeMcpServerOptions {
13
13
  server: McpServer;
14
14
  executor: Executor;
15
+ /**
16
+ * Custom tool description. Use `{{types}}` as a placeholder for the
17
+ * auto-generated type definitions and `{{example}}` for the example snippet.
18
+ * Falls back to a generic default when omitted.
19
+ */
20
+ description?: string;
15
21
  }
16
22
  declare function codeMcpServer(
17
23
  options: CodeMcpServerOptions
package/dist/mcp.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as sanitizeToolName, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
1
+ import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-CVt4X9cw.js";
2
2
  import { z } from "zod";
3
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
@@ -7,10 +7,17 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
7
7
  const CHARS_PER_TOKEN = 4;
8
8
  const MAX_TOKENS = 6e3;
9
9
  const MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;
10
+ const TRUNCATION_MARKER = "--- TRUNCATED ---";
11
+ const TRUNCATION_FOOTER_PREFIX = `\n\n${TRUNCATION_MARKER}\nResponse was ~`;
12
+ const MAX_SANDBOX_TRUNCATED_CHARS = MAX_CHARS + 512;
10
13
  function truncateResponse(content) {
11
14
  const text = typeof content === "string" ? content : JSON.stringify(content, null, 2) ?? "undefined";
12
15
  if (text.length <= MAX_CHARS) return text;
13
- return `${text.slice(0, MAX_CHARS)}\n\n--- TRUNCATED ---\nResponse was ~${Math.ceil(text.length / CHARS_PER_TOKEN).toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;
16
+ return `${text.slice(0, MAX_CHARS)}\n\n${TRUNCATION_MARKER}\nResponse was ~${Math.ceil(text.length / CHARS_PER_TOKEN).toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;
17
+ }
18
+ function sandboxResponseText(content) {
19
+ if (typeof content === "string" && content.length <= MAX_SANDBOX_TRUNCATED_CHARS && content.slice(MAX_CHARS).startsWith(TRUNCATION_FOOTER_PREFIX)) return content;
20
+ return truncateResponse(content);
14
21
  }
15
22
  function formatError(error) {
16
23
  return error instanceof Error ? error.message : String(error);
@@ -55,7 +62,7 @@ Do NOT define named functions then call them — just write the arrow function b
55
62
 
56
63
  {{example}}`;
57
64
  async function codeMcpServer(options) {
58
- const { server, executor } = options;
65
+ const { server, executor, description } = options;
59
66
  const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
60
67
  await server.connect(serverTransport);
61
68
  const client = new Client({
@@ -91,13 +98,13 @@ async function codeMcpServer(options) {
91
98
  const args = parts.length > 0 ? `{ ${parts.join(", ")} }` : "{}";
92
99
  example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;
93
100
  }
94
- const description = CODE_DESCRIPTION.replace("{{types}}", types).replace("{{example}}", example);
101
+ const codeDescription = (description ?? CODE_DESCRIPTION).replace("{{types}}", types).replace("{{example}}", example);
95
102
  const codemodeServer = new McpServer({
96
103
  name: "codemode",
97
104
  version: "1.0.0"
98
105
  });
99
106
  codemodeServer.registerTool("code", {
100
- description,
107
+ description: codeDescription,
101
108
  inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
102
109
  }, async ({ code }) => {
103
110
  try {
@@ -128,31 +135,6 @@ async function codeMcpServer(options) {
128
135
  });
129
136
  return codemodeServer;
130
137
  }
131
- /**
132
- * Resolve internal $ref pointers in a JSON object against the root document.
133
- * Only handles `#/` internal refs. External file refs are left as-is.
134
- */
135
- function resolveRefs(obj, root, seen = /* @__PURE__ */ new Set()) {
136
- if (obj === null || obj === void 0) return obj;
137
- if (typeof obj !== "object") return obj;
138
- if (Array.isArray(obj)) return obj.map((item) => resolveRefs(item, root, seen));
139
- const record = obj;
140
- if ("$ref" in record && typeof record.$ref === "string") {
141
- const ref = record.$ref;
142
- if (seen.has(ref)) return { $circular: ref };
143
- if (!ref.startsWith("#/")) return record;
144
- seen.add(ref);
145
- const parts = ref.slice(2).split("/").map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
146
- let resolved = root;
147
- for (const part of parts) resolved = resolved?.[part];
148
- const result = resolveRefs(resolved, root, seen);
149
- seen.delete(ref);
150
- return result;
151
- }
152
- const result = {};
153
- for (const [key, value] of Object.entries(record)) result[key] = resolveRefs(value, root, seen);
154
- return result;
155
- }
156
138
  const SPEC_TYPES = `
157
139
  // OpenAPI 3.x spec with $refs resolved inline.
158
140
  // The spec object follows the standard OpenAPI 3.x structure.
@@ -204,7 +186,8 @@ interface OpenApiSpec {
204
186
  components?: Record<string, unknown>;
205
187
  tags?: Array<{ name: string; description?: string }>;
206
188
  }
207
-
189
+ `;
190
+ const SEARCH_TYPES = `${SPEC_TYPES}
208
191
  declare const codemode: {
209
192
  spec(): Promise<OpenApiSpec>;
210
193
  };
@@ -219,10 +202,63 @@ interface RequestOptions {
219
202
  rawBody?: boolean;
220
203
  }
221
204
 
205
+ ${SPEC_TYPES}
206
+
222
207
  declare const codemode: {
208
+ spec(): Promise<OpenApiSpec>;
223
209
  request(options: RequestOptions): Promise<unknown>;
224
210
  };
225
211
  `;
212
+ function createOpenApiSandboxCode(code, spec, includeRequest) {
213
+ const normalized = normalizeCode(code);
214
+ const specJson = JSON.stringify(spec).replace(/</g, "\\u003c");
215
+ const requestFn = includeRequest ? `request: async (options) => await __openapiHost.request(options)` : "";
216
+ return `async () => {
217
+ const __rawSpec = ${specJson};
218
+ const __refCache = new Map();
219
+ const __cloneResolvedRef = (value) => structuredClone(value);
220
+ const __resolveRefs = (obj, root, seen = new Set()) => {
221
+ if (obj === null || obj === undefined) return obj;
222
+ if (typeof obj !== "object") return obj;
223
+ if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));
224
+
225
+ if (Object.prototype.hasOwnProperty.call(obj, "$ref") && typeof obj.$ref === "string") {
226
+ const ref = obj.$ref;
227
+ if (seen.has(ref)) return { $circular: ref };
228
+ if (!ref.startsWith("#/")) return obj;
229
+ if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));
230
+ seen.add(ref);
231
+
232
+ const parts = ref
233
+ .slice(2)
234
+ .split("/")
235
+ .map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
236
+ let resolved = root;
237
+ for (const part of parts) resolved = resolved?.[part];
238
+ const result = __resolveRefs(resolved, root, seen);
239
+ seen.delete(ref);
240
+ __refCache.set(ref, result);
241
+ return __cloneResolvedRef(result);
242
+ }
243
+
244
+ const result = {};
245
+ for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);
246
+ return result;
247
+ };
248
+ let __resolvedSpec;
249
+ const __truncateResponse = (content) => {
250
+ const text = typeof content === "string" ? content : (JSON.stringify(content, null, 2) ?? "undefined");
251
+ if (text.length <= ${MAX_CHARS}) return text;
252
+ const truncated = text.slice(0, ${MAX_CHARS});
253
+ const estimatedTokens = Math.ceil(text.length / ${CHARS_PER_TOKEN});
254
+ return truncated + "\\n\\n${TRUNCATION_MARKER}\\nResponse was ~" + estimatedTokens.toLocaleString() + " tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.";
255
+ };
256
+ const codemode = {
257
+ spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\n ${requestFn}` : ""}
258
+ };
259
+ return __truncateResponse(await (${normalized})());
260
+ }`;
261
+ }
226
262
  /**
227
263
  * Create an MCP server with search + execute tools from an OpenAPI spec.
228
264
  *
@@ -232,16 +268,16 @@ declare const codemode: {
232
268
  */
233
269
  function openApiMcpServer(options) {
234
270
  const { executor, request: requestFn, name = "openapi", version = "1.0.0", description } = options;
235
- const resolved = resolveRefs(options.spec, options.spec);
271
+ const spec = options.spec;
236
272
  const server = new McpServer({
237
273
  name,
238
274
  version
239
275
  });
240
276
  server.registerTool("search", {
241
- description: `Search the OpenAPI spec. All $refs are pre-resolved inline.
277
+ description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.
242
278
 
243
279
  Types:
244
- ${SPEC_TYPES}
280
+ ${SEARCH_TYPES}
245
281
 
246
282
  Your code must be an async arrow function that returns the result.
247
283
 
@@ -269,10 +305,7 @@ async () => {
269
305
  inputSchema: { code: z.string().describe("JavaScript async arrow function to search the spec") }
270
306
  }, async ({ code }) => {
271
307
  try {
272
- const result = await executor.execute(code, [{
273
- name: "codemode",
274
- fns: { spec: async () => resolved }
275
- }]);
308
+ const result = await executor.execute(createOpenApiSandboxCode(code, spec, false), []);
276
309
  if (result.error) return {
277
310
  content: [{
278
311
  type: "text",
@@ -282,7 +315,7 @@ async () => {
282
315
  };
283
316
  return { content: [{
284
317
  type: "text",
285
- text: truncateResponse(result.result)
318
+ text: sandboxResponseText(result.result)
286
319
  }] };
287
320
  } catch (error) {
288
321
  return {
@@ -310,8 +343,8 @@ async () => {
310
343
  inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
311
344
  }, async ({ code }) => {
312
345
  try {
313
- const result = await executor.execute(code, [{
314
- name: "codemode",
346
+ const result = await executor.execute(createOpenApiSandboxCode(code, spec, true), [{
347
+ name: "__openapiHost",
315
348
  fns: { request: (args) => requestFn(args) }
316
349
  }]);
317
350
  if (result.error) return {
@@ -323,7 +356,7 @@ async () => {
323
356
  };
324
357
  return { content: [{
325
358
  type: "text",
326
- text: truncateResponse(result.result)
359
+ text: sandboxResponseText(result.result)
327
360
  }] };
328
361
  } catch (error) {
329
362
  return {