@cloudflare/codemode 0.3.7 → 0.4.0

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +251 -7
  3. package/dist/ai.d.ts +50 -7
  4. package/dist/ai.js +93 -5
  5. package/dist/ai.js.map +1 -1
  6. package/dist/base-B2amchZA.d.ts +239 -0
  7. package/dist/base-CHRR_a5j.js +156 -0
  8. package/dist/base-CHRR_a5j.js.map +1 -0
  9. package/dist/browser.d.ts +6 -6
  10. package/dist/browser.js +2 -2
  11. package/dist/browser.js.map +1 -1
  12. package/dist/{executor-BRm90XJT.d.ts → executor-BIs2dr7X.d.ts} +48 -10
  13. package/dist/index.d.ts +608 -8
  14. package/dist/index.js +1690 -17
  15. package/dist/index.js.map +1 -1
  16. package/dist/{json-schema-types-CVt4X9cw.js → json-schema-types-BGjW4KPy.js} +1 -1
  17. package/dist/{json-schema-types-CVt4X9cw.js.map → json-schema-types-BGjW4KPy.js.map} +1 -1
  18. package/dist/{json-schema-types-1OL3uao0.d.ts → json-schema-types-Cb2wClAd.d.ts} +1 -1
  19. package/dist/mcp.d.ts +1 -1
  20. package/dist/mcp.js +4 -3
  21. package/dist/mcp.js.map +1 -1
  22. package/dist/{resolve-DdyeEp3l.js → resolve-34dC47Il.js} +1 -1
  23. package/dist/{resolve-DdyeEp3l.js.map → resolve-34dC47Il.js.map} +1 -1
  24. package/dist/{resolve-DtfaKmms.d.ts → resolve-CBr_VoPl.d.ts} +4 -4
  25. package/dist/{run-code-5x8S5YWt.js → run-code-aKHcTgf9.js} +4 -4
  26. package/dist/run-code-aKHcTgf9.js.map +1 -0
  27. package/dist/{shared-TyFN6W7_.d.ts → shared-Ce-zCEBP.d.ts} +3 -3
  28. package/dist/{shared-xjl2irqK.js → shared-SMjV5yN4.js} +1 -1
  29. package/dist/{shared-xjl2irqK.js.map → shared-SMjV5yN4.js.map} +1 -1
  30. package/dist/tanstack-ai.d.ts +3 -3
  31. package/dist/tanstack-ai.js +4 -4
  32. package/dist/tanstack-ai.js.map +1 -1
  33. package/dist/vite.d.ts +7 -0
  34. package/dist/vite.js +122 -0
  35. package/dist/vite.js.map +1 -0
  36. package/package.json +19 -14
  37. package/dist/run-code-5x8S5YWt.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound","#modules"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\nexport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\n\nconst BINARY_TAG = \"__codemode_binary_v1__\";\n\ntype EncodedBinary = {\n [BINARY_TAG]: \"Uint8Array\" | \"ArrayBuffer\" | \"ArrayBufferView\";\n data: string;\n};\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength))\n );\n }\n return btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nfunction encodeCodemodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { [BINARY_TAG]: \"Uint8Array\", data: bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return {\n [BINARY_TAG]: \"ArrayBuffer\",\n data: bytesToBase64(new Uint8Array(value))\n };\n }\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return {\n [BINARY_TAG]: \"ArrayBufferView\",\n data: bytesToBase64(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n )\n };\n }\n return value;\n}\n\nfunction decodeCodemodeValue(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || !(BINARY_TAG in value)) {\n return value;\n }\n const encoded = value as EncodedBinary;\n if (typeof encoded.data !== \"string\") return value;\n const bytes = base64ToBytes(encoded.data);\n if (encoded[BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength\n );\n }\n return bytes;\n}\n\nfunction stringifyForCodemode(value: unknown): string {\n return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));\n}\n\nfunction parseForCodemode(json: string): unknown {\n return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));\n}\n\nconst SANDBOX_CODEC = String.raw`\n const __CODEMODE_BINARY_TAG = \"__codemode_binary_v1__\";\n function __bytesToBase64(bytes) {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));\n }\n return btoa(binary);\n }\n function __base64ToBytes(b64) {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n function __encodeCodemodeValue(value) {\n if (value instanceof Uint8Array) {\n return { [__CODEMODE_BINARY_TAG]: \"Uint8Array\", data: __bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBuffer\", data: __bytesToBase64(new Uint8Array(value)) };\n }\n if (ArrayBuffer.isView(value)) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBufferView\", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };\n }\n return value;\n }\n function __decodeCodemodeValue(value) {\n if (!value || typeof value !== \"object\" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== \"string\") return value;\n const bytes = __base64ToBytes(value.data);\n if (value[__CODEMODE_BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n return bytes;\n }\n function __stringifyForCodemode(value) {\n return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));\n }\n function __parseForCodemode(json) {\n return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));\n }\n`;\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n}\n\n// ── 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 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 stringifyForCodemode({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? parseForCodemode(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return stringifyForCodemode({ result });\n } catch (err) {\n return stringifyForCodemode({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// ── DynamicWorkerExecutor ─────────────────────────────────────────────\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n /**\n * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes\n * ToolDispatchers (one per namespace) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n #modules: Record<string, string>;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n const { \"executor.js\": _, ...safeModules } = options.modules ?? {};\n this.#modules = safeModules;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\n \"__dispatchers\",\n \"__logs\",\n \"__CODEMODE_BINARY_TAG\",\n \"__bytesToBase64\",\n \"__base64ToBytes\",\n \"__encodeCodemodeValue\",\n \"__decodeCodemodeValue\",\n \"__stringifyForCodemode\",\n \"__parseForCodemode\"\n ]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map(\n (p) =>\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n SANDBOX_CODEC,\n ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\n // Sanitize fn keys so raw tool names (e.g. \"github.list-issues\") become\n // valid JS identifiers (e.g. \"github_list_issues\") on the proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, fn] of Object.entries(provider.fns)) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n return {\n result: undefined,\n error:\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to ` +\n `\"${sanitizedName}\" in provider \"${provider.name}\"`\n };\n }\n sanitizedNames.set(sanitizedName, name);\n sanitizedFns[sanitizedName] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(sanitizedFns);\n }\n\n const worker = this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"executor.js\",\n modules: {\n ...this.#modules,\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\n\n if (response.error) {\n return { result: undefined, error: response.error, logs: response.logs };\n }\n\n return { result: response.result, logs: response.logs };\n }\n}\n"],"mappings":";;;;;;;;;;AAuBA,MAAM,aAAa;AAOnB,SAAS,cAAc,OAA2B;CAChD,IAAI,SAAS;CACb,MAAM,YAAY;CAClB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,YAAY,KAAK,WACzC,UAAU,OAAO,aACf,GAAG,MAAM,SAAS,GAAG,KAAK,IAAI,IAAI,WAAW,MAAM,UAAU,CAAC,CAChE;CAEF,OAAO,KAAK,MAAM;AACpB;AAEA,SAAS,cAAc,KAAyB;CAC9C,MAAM,SAAS,KAAK,GAAG;CACvB,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KACjC,MAAM,KAAK,OAAO,WAAW,CAAC;CAEhC,OAAO;AACT;AAEA,SAAS,oBAAoB,OAAyB;CACpD,IAAI,iBAAiB,YACnB,OAAO;GAAG,aAAa;EAAc,MAAM,cAAc,KAAK;CAAE;CAElE,IAAI,iBAAiB,aACnB,OAAO;GACJ,aAAa;E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,MACC,aAAa,EAAE,KAAK,oHAE2B,EAAE,KAAK,+MAkB5C;GACZ;GACA;GACA;GACA;EACF,EACG,OAAO,CAAC,UAAU,CAAC,EACnB,OAAO;GACN;GACA,qGACE,YACA;GACF;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,EACA,KAAK,IAAI;EAKZ,MAAM,cAA8C,CAAC;EACrD,KAAK,MAAM,YAAY,WAAW;GAChC,MAAM,eAGF,CAAC;GACL,MAAM,iCAAiB,IAAI,IAAoB;GAC/C,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,SAAS,GAAG,GAAG;IACrD,MAAM,gBAAgB,iBAAiB,IAAI;IAC3C,MAAM,eAAe,eAAe,IAAI,aAAa;IACrD,IAAI,gBAAgB,iBAAiB,MACnC,OAAO;KACL,QAAQ,KAAA;KACR,OACE,eAAe,aAAa,SAAS,KAAK,sBACtC,cAAc,iBAAiB,SAAS,KAAK;IACrD;IAEF,eAAe,IAAI,eAAe,IAAI;IACtC,aAAa,iBAAiB;GAChC;GACA,YAAY,SAAS,QAAQ,IAAI,eAAe,YAAY;EAC9D;EAoBA,MAAM,WAAW,MAlBF,KAAKD,QAAQ,IAAI,YAAY,OAAO,WAAW,YAAY;GACxE,mBAAmB;GACnB,oBAAoB,CAAC,eAAe;GACpC,YAAY;GACZ,SAAS;IACP,GAAG,KAAKG;IACR,eAAe;GACjB;GACA,gBAAgB,KAAKD;EACvB,EAEwB,EAAE,cAOM,EAAE,SAAS,WAAW;EAEtD,IAAI,SAAS,OACX,OAAO;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;EAAK;EAGzE,OAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;EAAK;CACxD;AACF"}
1
+ {"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound","#modules","#bindings","#pruneTerminal","#executionRow","#get","#requireRow","#logRow","#diverge","#setEntryState","#touch","#fail","#storedLogs","#assemble","#connectionPromise","#handle","#options","#runtime"],"sources":["../src/codec.ts","../src/executor.ts","../src/truncate.ts","../src/runtime.ts","../src/connectors/mcp.ts","../src/connectors/openapi.ts","../src/connectors/search.ts","../src/connectors/describe.ts","../src/proxy-tool.ts","../src/runtime-handle.ts"],"sourcesContent":["/**\n * Host-side value codec.\n *\n * Two layers share the binary encoding (a tagged base64 envelope):\n *\n * - **Transport** (`stringifyForCodemode`/`parseForCodemode`): used for the\n * host↔sandbox tool-call boundary. Must stay in lockstep with the sandbox's\n * own codec (`SANDBOX_CODEC` in executor.ts).\n * - **Storage** (`stringifyForStorage`/`parseForStorage`): used by the\n * CodemodeRuntime facet to persist args/results in SQLite. Builds on the\n * transport encoding and additionally round-trips `bigint` (which plain\n * `JSON.stringify` rejects). The bigint tag is storage-only — it never\n * crosses into the sandbox.\n */\n\nexport const BINARY_TAG = \"__codemode_binary_v1__\";\nconst BIGINT_TAG = \"__codemode_bigint_v1__\";\n\ntype EncodedBinary = {\n [BINARY_TAG]: \"Uint8Array\" | \"ArrayBuffer\" | \"ArrayBufferView\";\n data: string;\n};\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(\n ...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength))\n );\n }\n return btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nexport function encodeCodemodeValue(value: unknown): unknown {\n if (value instanceof Uint8Array) {\n return { [BINARY_TAG]: \"Uint8Array\", data: bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return {\n [BINARY_TAG]: \"ArrayBuffer\",\n data: bytesToBase64(new Uint8Array(value))\n };\n }\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return {\n [BINARY_TAG]: \"ArrayBufferView\",\n data: bytesToBase64(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n )\n };\n }\n return value;\n}\n\nexport function decodeCodemodeValue(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || !(BINARY_TAG in value)) {\n return value;\n }\n const encoded = value as EncodedBinary;\n if (typeof encoded.data !== \"string\") return value;\n const bytes = base64ToBytes(encoded.data);\n if (encoded[BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength\n );\n }\n return bytes;\n}\n\nexport function stringifyForCodemode(value: unknown): string {\n return JSON.stringify(value, (_key, nested) => encodeCodemodeValue(nested));\n}\n\nexport function parseForCodemode(json: string): unknown {\n return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));\n}\n\n// ---------------------------------------------------------------------------\n// Storage codec — binary + bigint, for the runtime's SQLite columns.\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a value for durable storage. Returns `undefined` when the value is\n * `undefined` (callers store SQL NULL — distinguishing \"no value\" from a\n * recorded `null`, which serializes to the string `\"null\"`).\n *\n * Throws on values JSON cannot represent even with the codec (e.g. cycles):\n * a durable replay log cannot faithfully store such a value, and silently\n * storing an approximation would corrupt replay.\n */\nexport function stringifyForStorage(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n return JSON.stringify(value, (_key, nested) => {\n if (typeof nested === \"bigint\") {\n return { [BIGINT_TAG]: nested.toString() };\n }\n return encodeCodemodeValue(nested);\n });\n}\n\nexport function parseForStorage(json: string | null): unknown {\n if (json === null) return undefined;\n return JSON.parse(json, (_key, nested) => {\n if (\n nested &&\n typeof nested === \"object\" &&\n BIGINT_TAG in nested &&\n typeof (nested as Record<string, unknown>)[BIGINT_TAG] === \"string\"\n ) {\n return BigInt((nested as Record<string, string>)[BIGINT_TAG]);\n }\n return decodeCodemodeValue(nested);\n });\n}\n","/**\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 ExecuteOptions,\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 ExecuteOptions,\n Executor,\n ConnectorBinding,\n ResolvedProvider\n} from \"./executor-types\";\n// ConnectorBinding re-exported for public API — used by proxy-tool and runtime.\n\nimport { stringifyForCodemode, parseForCodemode } from \"./codec\";\n\n// Control protocol between a connector binding (host) and the sandbox proxy.\n// A binding returns `{ [CONNECTOR_CONTROL_KEY]: \"pause\" }` (awaiting approval /\n// diverged) or `{ [CONNECTOR_CONTROL_KEY]: \"error\", message }` (the call threw\n// on the host) instead of throwing across RPC; the generated proxy re-throws\n// locally. Keep in sync with proxy-tool.ts (CONTROL_KEY / PAUSE_SENTINEL).\nconst CONNECTOR_CONTROL_KEY = \"__codemode_control__\";\nconst PAUSE_SENTINEL_LITERAL = \"__CODEMODE_PAUSE__\";\n\nconst SANDBOX_CODEC = String.raw`\n const __CODEMODE_BINARY_TAG = \"__codemode_binary_v1__\";\n function __bytesToBase64(bytes) {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.byteLength; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, Math.min(i + chunkSize, bytes.byteLength)));\n }\n return btoa(binary);\n }\n function __base64ToBytes(b64) {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n }\n function __encodeCodemodeValue(value) {\n if (value instanceof Uint8Array) {\n return { [__CODEMODE_BINARY_TAG]: \"Uint8Array\", data: __bytesToBase64(value) };\n }\n if (value instanceof ArrayBuffer) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBuffer\", data: __bytesToBase64(new Uint8Array(value)) };\n }\n if (ArrayBuffer.isView(value)) {\n return { [__CODEMODE_BINARY_TAG]: \"ArrayBufferView\", data: __bytesToBase64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };\n }\n return value;\n }\n function __decodeCodemodeValue(value) {\n if (!value || typeof value !== \"object\" || !(__CODEMODE_BINARY_TAG in value) || typeof value.data !== \"string\") return value;\n const bytes = __base64ToBytes(value.data);\n if (value[__CODEMODE_BINARY_TAG] === \"ArrayBuffer\") {\n return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n }\n return bytes;\n }\n function __stringifyForCodemode(value) {\n return JSON.stringify(value, (_key, nested) => __encodeCodemodeValue(nested));\n }\n function __parseForCodemode(json) {\n return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));\n }\n`;\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n}\n\n// ── 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 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 stringifyForCodemode({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? parseForCodemode(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return stringifyForCodemode({ result });\n } catch (err) {\n return stringifyForCodemode({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// ── DynamicWorkerExecutor ─────────────────────────────────────────────\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n /**\n * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n /**\n * Additional env bindings injected into the sandbox worker.\n * Use this to pass ServiceStubs (e.g. CodemodeConnector instances)\n * so sandbox code can call their RPC methods directly.\n *\n * These are available as `env.KEY` inside the sandbox worker.\n */\n bindings?: Record<string, unknown>;\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 #bindings: Record<string, unknown>;\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 this.#bindings = options.bindings ?? {};\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>,\n options?: ExecuteOptions\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. Each provider is declared as a top-level\n // `const <name>` inside the generated `evaluate()` body, so a provider\n // name must not collide with the harness's own locals/imports or with the\n // JS globals the harness relies on (e.g. `Promise.race`, `setTimeout`,\n // `new Error`, `console`) — shadowing those would break execution in\n // confusing ways.\n const RESERVED_NAMES = new Set([\n // Harness internals (locals/imports/classes in the generated module).\n \"__dispatchers\",\n \"__connectors\",\n \"__logs\",\n \"__CODEMODE_BINARY_TAG\",\n \"__bytesToBase64\",\n \"__base64ToBytes\",\n \"__encodeCodemodeValue\",\n \"__decodeCodemodeValue\",\n \"__stringifyForCodemode\",\n \"__parseForCodemode\",\n \"WorkerEntrypoint\",\n \"CodeExecutor\",\n // Globals the generated harness code depends on.\n \"Promise\",\n \"setTimeout\",\n \"Error\",\n \"console\"\n ]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Connector bindings — passed as env to the sandbox worker.\n // These use direct RPC (callTool) instead of ToolDispatcher serialization.\n const connectors = options?.connectors ?? [];\n const connectorNames = new Set(connectors.map((c) => c.name));\n\n // Validate connector names don't clash with provider names or reserved\n // names. RESERVED_NAMES includes the `evaluate(__dispatchers, __connectors)`\n // parameters, so a connector/provider can't shadow the RPC bindings its own\n // generated proxy reads from (`__connectors.<name>.callTool(...)`).\n for (const connector of connectors) {\n if (RESERVED_NAMES.has(connector.name)) {\n return {\n result: undefined,\n error: `Connector name \"${connector.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(connector.name)) {\n return {\n result: undefined,\n error: `Connector name \"${connector.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(connector.name)) {\n return {\n result: undefined,\n error: `Duplicate name \"${connector.name}\" (connector clashes with provider)`\n };\n }\n seenNames.add(connector.name);\n }\n\n // Generate Proxy globals for dispatcher-backed providers.\n // Backed by a real object so a provider's `prelude` can assign real\n // in-sandbox functions (own properties) that take precedence over dispatch.\n const proxyInits = providers\n .filter((p) => !connectorNames.has(p.name))\n .map(\n (p) =>\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (target, toolName) => {\\n` +\n ` if (Object.prototype.hasOwnProperty.call(target, toolName)) return target[toolName];\\n` +\n ` if (typeof toolName !== \"string\") return undefined;\\n` +\n ` return async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\\n` +\n ` const data = __parseForCodemode(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` };\\n` +\n ` }\\n` +\n ` });`\n );\n\n // Sandbox-side preludes (e.g. codemode.step) injected after proxy setup.\n const preludeInits = providers\n .filter((p) => !connectorNames.has(p.name) && p.prelude)\n .map((p) => p.prelude as string);\n\n // Generate Proxy globals for connector-backed namespaces.\n // These call connector.callTool(method, args) via Workers RPC — no\n // serialization layer. Connector bindings are passed as an argument to\n // evaluate() (not via env): live RPC references can be serialized as RPC\n // call arguments but NOT as Worker `env` config values.\n //\n // A binding never throws across RPC (that would leave an unhandled remote\n // rejection); instead it returns a control marker — \"pause\" (awaiting\n // approval) or \"error\" (the host call threw) — which we turn into a local\n // throw here, where the sandbox's own try/catch handles it.\n const connectorProxyInits = connectors.map(\n (c) =>\n ` const ${c.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => {\\n` +\n ` if (typeof toolName !== \"string\") return undefined;\\n` +\n ` return async (...args) => {\\n` +\n ` const __r = await __connectors.${c.name}.callTool(toolName, args[0]);\\n` +\n ` if (__r && typeof __r === \"object\") {\\n` +\n ` if (__r.${CONNECTOR_CONTROL_KEY} === \"pause\") throw new Error(\"${PAUSE_SENTINEL_LITERAL}\");\\n` +\n ` if (__r.${CONNECTOR_CONTROL_KEY} === \"error\") throw new Error(String(__r.message));\\n` +\n ` }\\n` +\n ` return __r;\\n` +\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 = {}, __connectors = {}) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n SANDBOX_CODEC,\n ...proxyInits,\n ...connectorProxyInits,\n ...preludeInits,\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(sanitizedFns);\n }\n\n // Connector bindings are passed as an evaluate() argument (RPC), not via\n // env — live RPC references can only be serialized for RPC calls.\n const connectorBindings: Record<string, unknown> = {};\n for (const connector of connectors) {\n connectorBindings[connector.name] = connector.binding;\n }\n const env = { ...this.#bindings };\n const hasEnv = Object.keys(env).length > 0;\n\n // `load()` (not `get(id, cb)`): every run produces a unique generated\n // module, so there is nothing to cache by id — `get` with a random id would\n // only churn the loader's isolate cache. `load()` is the one-shot path the\n // Worker Loader API provides for exactly this (codemode-style) use.\n const worker = this.#loader.load({\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 env: hasEnv ? env : undefined\n });\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(\n dispatchers: Record<string, ToolDispatcher>,\n connectors: Record<string, unknown>\n ): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers, connectorBindings);\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","/**\n * Result truncation utilities.\n *\n * Tool and sandbox results can be large enough to blow a model's context\n * window. These cap the serialized size of a value while leaving small,\n * structured results intact so the model can still reason over them. They are\n * the default building blocks for a `transformResult` hook (see\n * `createCodemodeRuntime`).\n */\n\n/** ~4 characters per token is a reasonable cross-model estimate. */\nconst CHARS_PER_TOKEN = 4;\nconst DEFAULT_MAX_TOKENS = 6000;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\n\nexport type TruncateOptions = {\n /**\n * Maximum characters in the (serialized) output before truncation kicks in.\n * Defaults to `maxTokens * 4`.\n */\n maxChars?: number;\n /** Token budget used to derive the default `maxChars`. Defaults to 6000. */\n maxTokens?: number;\n};\n\nfunction budget(options?: TruncateOptions): {\n maxChars: number;\n maxTokens: number;\n} {\n const maxTokens = options?.maxTokens ?? DEFAULT_MAX_TOKENS;\n const maxChars = options?.maxChars ?? maxTokens * CHARS_PER_TOKEN;\n return { maxChars, maxTokens };\n}\n\n/**\n * Truncate a text response to a character budget, appending a marker that notes\n * the original size so the model knows the output was clipped. Returns the\n * input unchanged when it is within budget.\n */\nexport function truncateResponse(\n text: string,\n options?: TruncateOptions\n): string {\n const { maxChars, maxTokens } = budget(options);\n if (text.length <= maxChars) return text;\n\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n return (\n text.slice(0, maxChars) +\n `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens ` +\n `(limit: ${maxTokens.toLocaleString()}). Narrow the request to reduce response size.`\n );\n}\n\n/**\n * Truncate a structured result. Strings are truncated directly. Other values\n * pass through unchanged when their JSON serialization is within budget; when\n * oversized, the serialized form is truncated and returned as a string, so the\n * model still gets a usable, bounded preview rather than a dropped result.\n *\n * Values that can't be serialized (cycles, bigint, `undefined`) are returned\n * unchanged.\n */\nexport function truncateResult(\n value: unknown,\n options?: TruncateOptions\n): unknown {\n if (typeof value === \"string\") return truncateResponse(value, options);\n\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value, null, 2);\n } catch {\n return value;\n }\n if (serialized === undefined) return value;\n\n const { maxChars } = budget(options);\n if (serialized.length <= maxChars) return value;\n return truncateResponse(serialized, options);\n}\n","/**\n * CodemodeRuntime — durable execution engine, implemented as a DurableObject\n * facet of the agent.\n *\n * The Executor is a simple, stateless sandbox: it runs code once and dispatches\n * tool calls back. The Runtime wraps an executor and makes execution durable via\n * abort-and-replay:\n *\n * - Every tool call AND every `codemode.step(name, fn)` is recorded in a\n * durable log (the replay spine).\n * - Reads / steps execute and their result is recorded.\n * - Actions requiring approval are recorded as pending, and the run aborts.\n * - On `continue`, the same code re-runs. Calls already in the log are served\n * from it (noop — reads/steps return recorded results, applied\n * actions return theirs). The newly-approved action executes for real, then\n * the run proceeds to the next pause or completion.\n *\n * `codemode.step(name, fn)` is the explicit side-effect boundary: any\n * nondeterministic or side-effectful work wrapped in a step is recorded once\n * and replayed thereafter, so replay correctness does not depend on the code\n * being incidentally deterministic.\n *\n * ## Statelessness (concurrency + hibernation safety)\n *\n * The facet keeps **no per-run state in instance memory**. Every method that\n * participates in a run is addressed by an explicit `executionId` and, where\n * relevant, a `seq` allocated by the host (the proxy tool) — never an in-memory\n * cursor. This means:\n *\n * - Two executions can run concurrently without clobbering each other (each\n * run threads its own id + sequence; there is no shared \"current cursor\").\n * - The facet may hibernate mid-run between tool calls without losing its\n * place: the sequence lives on the host call stack and the log lives in\n * durable storage.\n *\n * The only durable state is per-execution: the log, pending actions, result,\n * snippets. The executor and connector stubs are transient — the proxy tool\n * re-provides them on each message (they can't survive hibernation anyway).\n *\n * ## Storage layout\n *\n * The facet's own SQLite database (facets each get an isolated DB) holds three\n * tables: `cm_executions` (one row per execution: code, status, final result),\n * `cm_log` (one row per connector call / step — appends write one small row\n * instead of rewriting the whole execution), and `cm_snippets`. Args/results\n * are serialized with the storage codec (binary + bigint safe). Any single\n * serialized value is capped at `MAX_DURABLE_VALUE_BYTES`: a durable log can't\n * truncate values (replay would feed resumed code corrupted data), so an\n * oversized value fails the run with a clear, model-actionable error instead.\n */\nimport { DurableObject } from \"cloudflare:workers\";\nimport { stringifyForStorage, parseForStorage } from \"./codec\";\nimport type { Snippet, SaveSnippetOptions } from \"./snippet\";\n\n// ---------------------------------------------------------------------------\n// Durable types\n// ---------------------------------------------------------------------------\n\nexport type ToolLogEntryState =\n | \"executing\" // decided to execute; result not yet recorded (crash window)\n | \"applied\" // executed for real, result recorded\n | \"pending\" // awaiting approval — the run aborted here\n | \"reverted\" // rolled back\n | \"error\"; // failed the run (e.g. unrecordable result); side effects may have run\n\n/** Connector name used for `codemode.step(name, fn)` log entries. */\nexport const STEP_CONNECTOR = \"__step\";\n\nexport type ToolLogEntry = {\n seq: number;\n connector: string;\n method: string;\n args: unknown;\n /** Recorded result for replay. Present once applied (never for ephemeral). */\n result?: unknown;\n /** Whether this call required approval (vs. a read or step). */\n requiresApproval: boolean;\n /**\n * Ephemeral entries (`replay: \"reexecute\"` tools) re-execute on replay\n * instead of replaying a recorded result; their result is never stored.\n */\n ephemeral?: boolean;\n state: ToolLogEntryState;\n};\n\nexport type ExecutionStatus =\n | \"running\"\n | \"paused\"\n | \"completed\"\n | \"error\"\n | \"rejected\"\n | \"rolled_back\";\n\nexport type ExecutionState = {\n id: string;\n code: string;\n status: ExecutionStatus;\n log: ToolLogEntry[];\n result?: unknown;\n error?: string;\n logs?: string[];\n /**\n * Connector names the execution was started with. Recorded so a later\n * resume can verify the required connectors are still configured.\n */\n connectors?: string[];\n /** Epoch ms the execution was created. */\n createdAt: number;\n /** Epoch ms of the last state change. */\n updatedAt: number;\n};\n\nexport type PendingAction = {\n executionId: string;\n seq: number;\n connector: string;\n method: string;\n args: unknown;\n};\n\n/**\n * The decision the runtime returns for a single tool call or step during a run.\n * - \"replay\": return `result` without executing\n * - \"execute\": execute, then report the result back via `recordResult`\n * - \"pause\": stop the run (the binding throws the pause sentinel)\n */\nexport type ToolDecision =\n | { kind: \"replay\"; result: unknown }\n | { kind: \"execute\"; seq: number }\n // \"pause\" tells the host to abort the sandbox run. The reason lives on the\n // execution: status \"paused\" (awaiting approval) or \"error\" (replay\n // divergence). Routing divergence through the execution record rather than a\n // thrown sandbox error keeps it out of the cross-worker rejection path.\n | { kind: \"pause\"; seq: number };\n\nexport type BeginOptions = {\n /** Terminal executions retained per runtime. Defaults to 50. */\n maxExecutions?: number;\n /** Connector names configured on the runtime starting this execution. */\n connectors?: string[];\n};\n\n/** Default number of terminal executions to retain per runtime. */\nexport const DEFAULT_MAX_EXECUTIONS = 50;\n\n/**\n * Cap for any single serialized value stored in the durable log (args, a\n * recorded result, the final result). SQLite rows in Durable Objects max out\n * at ~2MB; 1MB leaves headroom for the rest of the row. Truncating stored\n * values is never an option — replay would feed resumed code corrupted data —\n * so a breach fails the run with a model-actionable error instead.\n */\nexport const MAX_DURABLE_VALUE_BYTES = 1_000_000;\n\n/** Default age after which a paused (awaiting-approval) run can be expired. */\nexport const DEFAULT_PAUSED_TTL_MS = 24 * 60 * 60 * 1000;\n\n/** Model-actionable error for a value too large to record durably. */\nexport function tooLargeMessage(what: string, size: number): string {\n return (\n `${what} is too large to record durably (${size} bytes > ` +\n `${MAX_DURABLE_VALUE_BYTES} byte limit). Write large data to a file or ` +\n `workspace instead and pass/return a small reference (such as a path).`\n );\n}\n\n/** Pending actions (awaiting approval) of one execution. */\nfunction pendingOf(state: ExecutionState): PendingAction[] {\n return state.log\n .filter((e) => e.state === \"pending\")\n .map((e) => ({\n executionId: state.id,\n seq: e.seq,\n connector: e.connector,\n method: e.method,\n args: e.args\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Stable serialization for replay-divergence comparison of args.\n// ---------------------------------------------------------------------------\n\n/**\n * Deterministic JSON of a value: object keys sorted recursively, BigInt tagged.\n * Used to compare a replayed call's args against the recorded args. Best-effort\n * — returns `undefined` if the value can't be serialized (e.g. a cycle), in\n * which case the caller skips the args check rather than reporting a false\n * divergence.\n */\nexport function stableStringify(value: unknown): string | undefined {\n try {\n return JSON.stringify(value, (_key, val) => {\n if (typeof val === \"bigint\") return `__bigint__:${val.toString()}`;\n if (val && typeof val === \"object\" && !Array.isArray(val)) {\n const record = val as Record<string, unknown>;\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(record).sort()) sorted[key] = record[key];\n return sorted;\n }\n return val;\n });\n } catch {\n return undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Row shapes\n// ---------------------------------------------------------------------------\n\ntype ExecutionRow = {\n id: string;\n code: string;\n status: string;\n result: string | null;\n error: string | null;\n logs: string | null;\n connectors: string | null;\n created_at: number;\n updated_at: number;\n};\n\ntype LogRow = {\n execution_id: string;\n seq: number;\n connector: string;\n method: string;\n args: string | null;\n result: string | null;\n requires_approval: number;\n ephemeral: number;\n state: string;\n};\n\ntype SnippetRow = {\n name: string;\n description: string;\n code: string;\n saved_at: number;\n input_schema: string | null;\n connectors: string | null;\n};\n\nfunction rowToEntry(row: LogRow): ToolLogEntry {\n return {\n seq: row.seq,\n connector: row.connector,\n method: row.method,\n args: parseForStorage(row.args),\n result: parseForStorage(row.result),\n requiresApproval: row.requires_approval === 1,\n ephemeral: row.ephemeral === 1 ? true : undefined,\n state: row.state as ToolLogEntryState\n };\n}\n\nfunction rowToSnippet(row: SnippetRow): Snippet {\n return {\n name: row.name,\n description: row.description,\n code: row.code,\n savedAt: row.saved_at,\n inputSchema: parseForStorage(row.input_schema),\n connectors: row.connectors\n ? (JSON.parse(row.connectors) as string[])\n : undefined\n };\n}\n\n/**\n * Serialize a value for a durable column. `undefined` → SQL NULL; throws a\n * model-actionable error when the value is too large or not serializable\n * (e.g. cyclic) — the durable log can't store an approximation.\n */\nfunction toStored(what: string, value: unknown): string | null {\n let stored: string | undefined;\n try {\n stored = stringifyForStorage(value);\n } catch (err) {\n throw new Error(\n `${what} could not be recorded durably (not serializable: ` +\n `${err instanceof Error ? err.message : String(err)}). Only ` +\n `JSON-compatible values (plus binary and bigint) can cross a ` +\n `durable replay boundary.`\n );\n }\n if (stored === undefined) return null;\n if (stored.length > MAX_DURABLE_VALUE_BYTES) {\n throw new Error(tooLargeMessage(what, stored.length));\n }\n return stored;\n}\n\n// ---------------------------------------------------------------------------\n// CodemodeRuntime facet\n// ---------------------------------------------------------------------------\n\nexport class CodemodeRuntime extends DurableObject<unknown> {\n constructor(ctx: DurableObjectState, env: unknown) {\n super(ctx, env);\n this.ctx.storage.sql.exec(`\n CREATE TABLE IF NOT EXISTS cm_executions (\n id TEXT PRIMARY KEY,\n code TEXT NOT NULL,\n status TEXT NOT NULL,\n result TEXT,\n error TEXT,\n logs TEXT,\n connectors TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS cm_executions_status\n ON cm_executions (status, created_at);\n CREATE TABLE IF NOT EXISTS cm_log (\n execution_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n connector TEXT NOT NULL,\n method TEXT NOT NULL,\n args TEXT,\n result TEXT,\n requires_approval INTEGER NOT NULL DEFAULT 0,\n ephemeral INTEGER NOT NULL DEFAULT 0,\n state TEXT NOT NULL,\n PRIMARY KEY (execution_id, seq)\n );\n CREATE TABLE IF NOT EXISTS cm_snippets (\n name TEXT PRIMARY KEY,\n description TEXT NOT NULL,\n code TEXT NOT NULL,\n saved_at INTEGER NOT NULL,\n input_schema TEXT,\n connectors TEXT\n );\n `);\n }\n\n // -----------------------------------------------------------------------\n // Run lifecycle\n //\n // Every method targets an explicit `executionId`. There is deliberately no\n // \"current execution\" pointer: it would be a single shared slot that the\n // most recent run wins, which is racy the moment two runs are in flight.\n // The host (proxy tool) holds the id for the run it is driving, and approval\n // UIs get ids from `listPending()` / `listExecutions()`.\n // -----------------------------------------------------------------------\n\n /**\n * Begin a fresh execution. Returns the execution id. Prunes old terminal\n * executions down to `maxExecutions` (newest kept). The connector names the\n * runtime was created with are recorded on the execution so a later resume\n * can verify they are still configured.\n */\n async begin(code: string, options?: BeginOptions): Promise<string> {\n if (code.length > MAX_DURABLE_VALUE_BYTES) {\n throw new Error(tooLargeMessage(\"The execution code\", code.length));\n }\n const now = Date.now();\n const id = `exec_${now.toString().padStart(16, \"0\")}_${crypto.randomUUID()}`;\n this.ctx.storage.sql.exec(\n `INSERT INTO cm_executions\n (id, code, status, connectors, created_at, updated_at)\n VALUES (?, ?, 'running', ?, ?, ?)`,\n id,\n code,\n options?.connectors ? JSON.stringify(options.connectors) : null,\n now,\n now\n );\n this.#pruneTerminal(options?.maxExecutions ?? DEFAULT_MAX_EXECUTIONS, id);\n return id;\n }\n\n /**\n * Resume an execution for a replay run. Only a `paused` run can be resumed:\n * reviving a terminal run (completed/error/rejected/rolled_back) would\n * re-offer a rejected action for approval or re-apply rolled-back side\n * effects, and restarting an already-`running` run would race. Returns `null`\n * (no state change) when the run is missing or not paused — the caller turns\n * that into a clear error.\n */\n async resume(id: string): Promise<ExecutionState | null> {\n const row = this.#executionRow(id);\n if (!row || row.status !== \"paused\") return null;\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions SET status = 'running', updated_at = ? WHERE id = ?`,\n Date.now(),\n id\n );\n return this.#get(id);\n }\n\n /**\n * Decide what to do with the next tool call or step. The host allocates and\n * passes `seq` (not an in-memory cursor), so this is safe across hibernation\n * and concurrent executions.\n *\n * If the execution is no longer \"running\" (already paused/terminal), every\n * call gets a pause decision and nothing is recorded — so model code that\n * swallows the pause sentinel can't drive further side effects.\n *\n * Replay: a log entry at `seq` must match connector + method + args\n * (divergence is a hard error). Applied → replay its result (ephemeral\n * entries re-execute instead). Pending → it was just approved, execute it.\n * Executing (crashed mid-call) / reverted → treat as a fresh call.\n *\n * New call: step or read → execute (logged \"executing\" until recordResult).\n * Approval-required → record pending, pause.\n */\n async decide(\n executionId: string,\n seq: number,\n connector: string,\n method: string,\n args: unknown,\n requiresApproval: boolean,\n ephemeral = false\n ): Promise<ToolDecision> {\n const row = this.#requireRow(executionId);\n\n // Once a run has paused (awaiting approval) or terminated (divergence,\n // rejection), refuse to make any further progress: every subsequent\n // call/step gets a pause decision and nothing new is recorded. The pause\n // sentinel is a throwable Error, so model code *could* catch it and keep\n // going — this guard makes that harmless (no further side effects, no log\n // growth past the pause) rather than relying on the throw escaping.\n if (row.status !== \"running\") {\n return { kind: \"pause\", seq };\n }\n\n const existingRow = this.#logRow(executionId, seq);\n const existing = existingRow ? rowToEntry(existingRow) : undefined;\n\n if (existing) {\n if (existing.connector !== connector || existing.method !== method) {\n return this.#diverge(\n executionId,\n seq,\n `expected ${existing.connector}.${existing.method}, got ` +\n `${connector}.${method}. Code must be deterministic up to tool ` +\n `calls and steps. Wrap nondeterministic work in codemode.step(name, fn).`\n );\n }\n const before = stableStringify(existing.args);\n const after = stableStringify(args);\n if (before !== undefined && after !== undefined && before !== after) {\n return this.#diverge(\n executionId,\n seq,\n `${connector}.${method} was called with different arguments than the ` +\n `recorded run. Arguments must be deterministic across replays. Wrap ` +\n `nondeterministic inputs in codemode.step(name, fn).`\n );\n }\n if (existing.state === \"applied\") {\n // Ephemeral entries store no result — they re-execute on replay.\n // Result divergence is harmless (divergence detection compares\n // connector/method/args only), but the value may legitimately have\n // changed underneath (e.g. a file edited between pause and resume).\n if (existing.ephemeral) {\n return { kind: \"execute\", seq };\n }\n return { kind: \"replay\", result: existing.result };\n }\n if (existing.state === \"pending\") {\n // Approved since the last run. Transition pending → executing and\n // persist BEFORE returning, so a concurrent reject() (e.g. a second UI\n // tab) sees \"executing\" and no-ops instead of reverting an action that\n // is already running on the host. Without this write the entry would\n // stay \"pending\" for the whole execution window — symmetric with the\n // fresh-call path below.\n this.#setEntryState(executionId, seq, \"executing\");\n this.#touch(executionId);\n return { kind: \"execute\", seq };\n }\n if (existing.state === \"executing\") {\n // Decided to run on a previous pass but crashed before recordResult\n // landed — re-execute. Do NOT re-pause even for an approval action: it\n // was already approved when it first reached \"executing\".\n return { kind: \"execute\", seq };\n }\n // \"reverted\" — fall through and re-execute as a fresh call.\n }\n\n // Fresh call (or a \"reverted\" entry being re-run as a fresh call).\n let storedArgs: string | null;\n try {\n storedArgs = toStored(`Arguments to ${connector}.${method}`, args);\n } catch (err) {\n // Args that can't live in the durable log (too large / unserializable)\n // are a terminal failure with a model-actionable message — recording an\n // approximation would corrupt replay.\n return this.#fail(\n executionId,\n seq,\n err instanceof Error ? err.message : String(err)\n );\n }\n\n const state: ToolLogEntryState = requiresApproval ? \"pending\" : \"executing\";\n // \"REPLACE\" covers the reverted-entry re-run; a plain fresh call inserts.\n this.ctx.storage.sql.exec(\n `INSERT OR REPLACE INTO cm_log\n (execution_id, seq, connector, method, args, result,\n requires_approval, ephemeral, state)\n VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)`,\n executionId,\n seq,\n connector,\n method,\n storedArgs,\n requiresApproval ? 1 : 0,\n ephemeral ? 1 : 0,\n state\n );\n\n if (requiresApproval) {\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions SET status = 'paused', updated_at = ? WHERE id = ?`,\n Date.now(),\n executionId\n );\n return { kind: \"pause\", seq };\n }\n this.#touch(executionId);\n return { kind: \"execute\", seq };\n }\n\n /**\n * Record the real result of an executed call or step. Ephemeral entries are\n * marked applied but their result is never stored (they re-execute on\n * replay).\n *\n * A non-ephemeral result that is too large / unserializable cannot live in\n * the durable log (truncating it would corrupt replay), so the execution is\n * marked failed with a model-actionable error — recorded on the execution\n * rather than thrown, because a rejection across the facet RPC boundary\n * would surface as an unhandled rejection on the host. The entry stays\n * \"executing\" (its side effects already happened) and the run can make no\n * further progress.\n */\n async recordResult(\n executionId: string,\n seq: number,\n result: unknown\n ): Promise<void> {\n const row = this.#logRow(executionId, seq);\n if (!row) throw new Error(`No log entry at step ${seq}`);\n let stored: string | null;\n try {\n stored =\n row.ephemeral === 1\n ? null\n : toStored(`The result of ${row.connector}.${row.method}`, result);\n } catch (err) {\n this.#fail(\n executionId,\n seq,\n err instanceof Error ? err.message : String(err)\n );\n return;\n }\n this.ctx.storage.sql.exec(\n `UPDATE cm_log SET result = ?, state = 'applied'\n WHERE execution_id = ? AND seq = ?`,\n stored,\n executionId,\n seq\n );\n this.#touch(executionId);\n }\n\n /**\n * Mark the run completed with a final result. Replay never needs the final\n * result (a resume re-derives it), so an oversized/unserializable result is\n * replaced with a placeholder note in the audit trail rather than failing a\n * run that genuinely completed.\n */\n async complete(\n executionId: string,\n result: unknown,\n logs?: string[]\n ): Promise<void> {\n this.#requireRow(executionId);\n let storedResult: string | null;\n try {\n storedResult = toStored(\"The final result\", result);\n } catch (err) {\n storedResult = stringifyForStorage(\n `[codemode: result omitted from the audit trail — ` +\n `${err instanceof Error ? err.message : String(err)}]`\n ) as string;\n }\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions\n SET status = 'completed', result = ?, logs = ?, updated_at = ?\n WHERE id = ?`,\n storedResult,\n this.#storedLogs(logs),\n Date.now(),\n executionId\n );\n }\n\n /** Mark the run errored. */\n async fail(\n executionId: string,\n error: string,\n logs?: string[]\n ): Promise<void> {\n this.#requireRow(executionId);\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions\n SET status = 'error', error = ?, logs = ?, updated_at = ?\n WHERE id = ?`,\n error.slice(0, MAX_DURABLE_VALUE_BYTES),\n this.#storedLogs(logs),\n Date.now(),\n executionId\n );\n }\n\n // -----------------------------------------------------------------------\n // Approvals\n // -----------------------------------------------------------------------\n\n /**\n * List pending actions awaiting approval. With an `executionId`, scopes to\n * that run; without one, aggregates across every **paused** run (newest\n * first) — so an approval UI sees every awaiting-approval run, not just\n * whichever happened to be started/resumed last. (Defaulting to a single\n * \"current\" run would drop pending actions when multiple runs are in flight.)\n *\n * Only **paused** runs are considered: a non-paused run can retain a stale\n * \"pending\" log entry (e.g. a resume diverged before reaching it, ending the\n * run as `error` while the later entry stays `pending`). Such an entry isn't\n * actionable — approving it is a no-op — so it must not clutter the queue.\n */\n async listPending(executionId?: string): Promise<PendingAction[]> {\n if (executionId) {\n const state = await this.#get(executionId);\n return state?.status === \"paused\" ? pendingOf(state) : [];\n }\n const paused = this.ctx.storage.sql\n .exec<ExecutionRow>(\n `SELECT * FROM cm_executions WHERE status = 'paused'\n ORDER BY created_at DESC, id DESC`\n )\n .toArray();\n const out: PendingAction[] = [];\n for (const row of paused) {\n out.push(...pendingOf(this.#assemble(row)));\n }\n return out;\n }\n\n /**\n * Reject a pending action. Ends the execution with an error.\n *\n * Returns whether it actually terminated the run: `false` when the seq isn't\n * pending (a stale/duplicate reject — e.g. the action was already handled by\n * another tab), so the caller doesn't tear down a run that's still live.\n *\n * Rejection does NOT undo actions already applied earlier in the same run —\n * call `rollback()` for that. See docs/codemode/approvals.md.\n */\n async reject(seq: number, executionId: string): Promise<boolean> {\n const entry = this.#logRow(executionId, seq);\n if (entry?.state !== \"pending\") return false;\n this.#setEntryState(executionId, seq, \"reverted\");\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions SET status = 'rejected', error = ?, updated_at = ?\n WHERE id = ?`,\n `Action ${entry.connector}.${entry.method} rejected by user`,\n Date.now(),\n executionId\n );\n return true;\n }\n\n /**\n * Expire non-terminal runs whose last state change is older than\n * `maxAgeMs`:\n *\n * - `paused` (awaiting approval) runs are marked **rejected**. A\n * never-answered approval would otherwise live forever — paused runs are\n * deliberately exempt from retention pruning.\n * - `running` runs are marked **error**. A run only stays `running` with a\n * stale `updated_at` when the host died mid-pass (every decide/record\n * touches the row), and such a run can never be resumed — without expiry\n * it would be unreclaimable and exempt from pruning forever.\n *\n * Returns the expired execution ids so the host can fire the connectors'\n * `disposeExecution` for each. Each status flip is conditional on the\n * status it observed, so an id is only returned (and disposed) when this\n * call actually terminated the run.\n */\n async expirePaused(maxAgeMs = DEFAULT_PAUSED_TTL_MS): Promise<string[]> {\n const cutoff = Date.now() - maxAgeMs;\n const rows = this.ctx.storage.sql\n .exec<{ id: string; status: string }>(\n `SELECT id, status FROM cm_executions\n WHERE status IN ('paused', 'running') AND updated_at < ?`,\n cutoff\n )\n .toArray();\n const now = Date.now();\n const expired: string[] = [];\n for (const { id, status } of rows) {\n const updated = this.ctx.storage.sql.exec(\n `UPDATE cm_executions SET status = ?, error = ?, updated_at = ?\n WHERE id = ? AND status = ?`,\n status === \"paused\" ? \"rejected\" : \"error\",\n status === \"paused\"\n ? \"Expired awaiting approval\"\n : \"Expired while running — the host never completed the pass\",\n now,\n id,\n status\n );\n if (updated.rowsWritten === 0) continue;\n this.ctx.storage.sql.exec(\n `UPDATE cm_log SET state = 'reverted'\n WHERE execution_id = ? AND state = 'pending'`,\n id\n );\n expired.push(id);\n }\n return expired;\n }\n\n // -----------------------------------------------------------------------\n // Rollback — walk the log backward; the proxy tool calls revertAction.\n // -----------------------------------------------------------------------\n\n /**\n * Return applied connector actions (not steps) in reverse order. Reads are\n * included but are harmless — the host's revertAction no-ops when a tool has\n * no `revert`, and only entries that actually reverted are marked.\n */\n async actionsToRevert(executionId: string): Promise<ToolLogEntry[]> {\n return this.ctx.storage.sql\n .exec<LogRow>(\n `SELECT * FROM cm_log\n WHERE execution_id = ? AND state = 'applied' AND connector != ?\n ORDER BY seq DESC`,\n executionId,\n STEP_CONNECTOR\n )\n .toArray()\n .map(rowToEntry);\n }\n\n /** Mark an action reverted after the proxy tool has reverted it. */\n async markReverted(seq: number, executionId: string): Promise<void> {\n if (!this.#logRow(executionId, seq)) return;\n this.#setEntryState(executionId, seq, \"reverted\");\n this.#touch(executionId);\n }\n\n /**\n * Mark a run as rolled back once the proxy tool has finished reverting its\n * actions, so the execution status reflects the rollback (rather than staying\n * \"completed\"/\"error\" with some entries quietly flipped to \"reverted\").\n */\n async markRolledBack(executionId: string): Promise<void> {\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions SET status = 'rolled_back', updated_at = ?\n WHERE id = ?`,\n Date.now(),\n executionId\n );\n }\n\n // -----------------------------------------------------------------------\n // Inspection + retention\n // -----------------------------------------------------------------------\n\n async getExecution(id: string): Promise<ExecutionState | null> {\n return this.#get(id);\n }\n\n /** List executions, newest first. Optionally cap the number returned. */\n async listExecutions(limit?: number): Promise<ExecutionState[]> {\n const rows = this.ctx.storage.sql\n .exec<ExecutionRow>(\n `SELECT * FROM cm_executions ORDER BY created_at DESC, id DESC\n LIMIT ?`,\n typeof limit === \"number\" ? limit : -1\n )\n .toArray();\n return rows.map((row) => this.#assemble(row));\n }\n\n /** Delete one execution. Returns whether it existed. */\n async deleteExecution(id: string): Promise<boolean> {\n const existed = this.#executionRow(id) !== null;\n this.ctx.storage.sql.exec(`DELETE FROM cm_log WHERE execution_id = ?`, id);\n this.ctx.storage.sql.exec(`DELETE FROM cm_executions WHERE id = ?`, id);\n return existed;\n }\n\n /**\n * Delete terminal (completed/error) executions, keeping the newest `keep`.\n * Running/paused executions are never deleted. Returns the count removed.\n */\n async pruneExecutions(keep = DEFAULT_MAX_EXECUTIONS): Promise<number> {\n return this.#pruneTerminal(keep);\n }\n\n // -----------------------------------------------------------------------\n // Snippets — durable, addressable saved scripts\n // -----------------------------------------------------------------------\n\n /**\n * Promote an execution's code to a saved, addressable snippet. This is the\n * \"save what ran\" hook — the developer calls it (via runtime.saveSnippet)\n * after a script proves useful, so the model can re-run it later with\n * `codemode.run(name)`. The execution is named explicitly (its id comes from\n * the tool's output or `listExecutions()`). The execution's recorded\n * connector requirements carry over to the snippet so a later run can verify\n * they are still configured.\n */\n async saveSnippet(\n name: string,\n options: SaveSnippetOptions\n ): Promise<Snippet> {\n const row = this.#executionRow(options.executionId);\n if (!row) {\n throw new Error(`No execution \"${options.executionId}\" to save from`);\n }\n const snippet: Snippet = {\n name,\n description: options.description ?? \"\",\n code: row.code,\n savedAt: Date.now(),\n inputSchema: options.inputSchema,\n connectors: row.connectors\n ? (JSON.parse(row.connectors) as string[])\n : undefined\n };\n this.ctx.storage.sql.exec(\n `INSERT OR REPLACE INTO cm_snippets\n (name, description, code, saved_at, input_schema, connectors)\n VALUES (?, ?, ?, ?, ?, ?)`,\n snippet.name,\n snippet.description,\n snippet.code,\n snippet.savedAt,\n // Snippet code is implicitly bounded (it is an execution's code, which\n // `begin` caps); the schema is the only unbounded input here.\n toStored(\"The snippet input schema\", snippet.inputSchema),\n row.connectors\n );\n return snippet;\n }\n\n async getSnippet(name: string): Promise<Snippet | null> {\n const rows = this.ctx.storage.sql\n .exec<SnippetRow>(`SELECT * FROM cm_snippets WHERE name = ?`, name)\n .toArray();\n return rows.length > 0 ? rowToSnippet(rows[0]) : null;\n }\n\n async listSnippets(): Promise<Snippet[]> {\n return this.ctx.storage.sql\n .exec<SnippetRow>(`SELECT * FROM cm_snippets ORDER BY name`)\n .toArray()\n .map(rowToSnippet);\n }\n\n async deleteSnippet(name: string): Promise<boolean> {\n const existed =\n this.ctx.storage.sql\n .exec(`SELECT 1 FROM cm_snippets WHERE name = ?`, name)\n .toArray().length > 0;\n this.ctx.storage.sql.exec(`DELETE FROM cm_snippets WHERE name = ?`, name);\n return existed;\n }\n\n // -----------------------------------------------------------------------\n // Internal\n // -----------------------------------------------------------------------\n\n /**\n * Record a replay divergence (or another in-run failure) as a terminal\n * failure on the execution and tell the host to abort the sandbox. The host\n * reads the failure from the execution record, so the message never travels\n * back through the sandbox's error channel (which would flag it as an\n * unhandled remote rejection).\n */\n #diverge(executionId: string, seq: number, detail: string): ToolDecision {\n return this.#fail(\n executionId,\n seq,\n `Codemode replay divergence at step ${seq}: ${detail}`\n );\n }\n\n #fail(executionId: string, seq: number, error: string): ToolDecision {\n // Mark the triggering log entry too (when one exists): an entry left\n // \"executing\"/\"pending\" under an errored execution misreads as a crash\n // window in the audit trail. Side effects may already have run, which is\n // exactly what the \"error\" state records.\n this.ctx.storage.sql.exec(\n `UPDATE cm_log SET state = 'error'\n WHERE execution_id = ? AND seq = ? AND state IN ('executing', 'pending')`,\n executionId,\n seq\n );\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions SET status = 'error', error = ?, updated_at = ?\n WHERE id = ?`,\n error.slice(0, MAX_DURABLE_VALUE_BYTES),\n Date.now(),\n executionId\n );\n return { kind: \"pause\", seq };\n }\n\n #pruneTerminal(keep: number, protectId?: string): number {\n const rows = this.ctx.storage.sql\n .exec<{ id: string }>(\n `SELECT id FROM cm_executions\n WHERE status IN ('completed', 'error', 'rejected', 'rolled_back')\n AND id != ?\n ORDER BY created_at DESC, id DESC`,\n protectId ?? \"\"\n )\n .toArray();\n if (rows.length <= keep) return 0;\n const toDelete = rows.slice(keep);\n for (const { id } of toDelete) {\n this.ctx.storage.sql.exec(\n `DELETE FROM cm_log WHERE execution_id = ?`,\n id\n );\n this.ctx.storage.sql.exec(`DELETE FROM cm_executions WHERE id = ?`, id);\n }\n return toDelete.length;\n }\n\n /** Serialize console logs; an oversized log array is truncated with a note. */\n #storedLogs(logs?: string[]): string | null {\n if (!logs || logs.length === 0) return null;\n let stored = JSON.stringify(logs);\n let entries = logs;\n while (stored.length > MAX_DURABLE_VALUE_BYTES && entries.length > 0) {\n entries = [\n \"[codemode: earlier console output dropped — too large to record]\",\n ...entries.slice(Math.ceil(entries.length / 2))\n ];\n stored = JSON.stringify(entries);\n }\n return stored.length <= MAX_DURABLE_VALUE_BYTES ? stored : null;\n }\n\n #executionRow(id: string): ExecutionRow | null {\n const rows = this.ctx.storage.sql\n .exec<ExecutionRow>(`SELECT * FROM cm_executions WHERE id = ?`, id)\n .toArray();\n return rows.length > 0 ? rows[0] : null;\n }\n\n #requireRow(id: string): ExecutionRow {\n const row = this.#executionRow(id);\n if (!row) throw new Error(`No execution \"${id}\"`);\n return row;\n }\n\n #logRow(executionId: string, seq: number): LogRow | null {\n const rows = this.ctx.storage.sql\n .exec<LogRow>(\n `SELECT * FROM cm_log WHERE execution_id = ? AND seq = ?`,\n executionId,\n seq\n )\n .toArray();\n return rows.length > 0 ? rows[0] : null;\n }\n\n #setEntryState(\n executionId: string,\n seq: number,\n state: ToolLogEntryState\n ): void {\n this.ctx.storage.sql.exec(\n `UPDATE cm_log SET state = ? WHERE execution_id = ? AND seq = ?`,\n state,\n executionId,\n seq\n );\n }\n\n #touch(executionId: string): void {\n this.ctx.storage.sql.exec(\n `UPDATE cm_executions SET updated_at = ? WHERE id = ?`,\n Date.now(),\n executionId\n );\n }\n\n #assemble(row: ExecutionRow): ExecutionState {\n const entries = this.ctx.storage.sql\n .exec<LogRow>(\n `SELECT * FROM cm_log WHERE execution_id = ? ORDER BY seq`,\n row.id\n )\n .toArray()\n .map(rowToEntry);\n const log: ToolLogEntry[] = [];\n for (const entry of entries) log[entry.seq] = entry;\n return {\n id: row.id,\n code: row.code,\n status: row.status as ExecutionStatus,\n log,\n result: parseForStorage(row.result),\n error: row.error ?? undefined,\n logs: row.logs ? (JSON.parse(row.logs) as string[]) : undefined,\n connectors: row.connectors\n ? (JSON.parse(row.connectors) as string[])\n : undefined,\n createdAt: row.created_at,\n updatedAt: row.updated_at\n };\n }\n\n async #get(id: string): Promise<ExecutionState | null> {\n const row = this.#executionRow(id);\n return row ? this.#assemble(row) : null;\n }\n}\n","import type { JSONSchema7 } from \"json-schema\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { Tool as McpTool } from \"@modelcontextprotocol/sdk/types.js\";\nimport { sanitizeToolName } from \"../utils\";\nimport { CodemodeConnector, type ConnectorTools } from \"./base\";\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\nexport interface McpConnectionLike {\n name?: string;\n client: Pick<Client, \"callTool\">;\n instructions?: string;\n tools?: McpTool[];\n fetchTools?: () => Promise<McpTool[]>;\n}\n\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) return result.toolResult;\n if (result.isError) {\n const msg =\n result.content\n ?.filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n if (result.structuredContent != null) return result.structuredContent;\n const allText =\n result.content?.length > 0 &&\n result.content.every((c) => c.type === \"text\");\n if (!allText) return result;\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Connector backed by an MCP connection. Each MCP tool becomes one entry in\n * the tools record, executing through `connection.client.callTool()`.\n *\n * Subclass and implement `createConnection()`. To mark a derived tool as\n * requiring approval or to attach a revert, override the `tool(name, t)`\n * decoration hook from the base class.\n */\nexport abstract class McpConnector<\n Env = unknown,\n Props = unknown\n> extends CodemodeConnector<Env, Props> {\n protected abstract createConnection():\n | Promise<McpConnectionLike>\n | McpConnectionLike;\n\n protected toolName(tool: McpTool): string {\n return sanitizeToolName(tool.name);\n }\n\n // Cached connection\n #connectionPromise?: Promise<McpConnectionLike>;\n protected getConnection(): Promise<McpConnectionLike> {\n return (this.#connectionPromise ??= Promise.resolve(\n this.createConnection()\n ));\n }\n\n protected async fetchTools(): Promise<McpTool[]> {\n const connection = await this.getConnection();\n if (connection.tools?.length) return connection.tools;\n if (connection.fetchTools) return connection.fetchTools();\n return [];\n }\n\n override async describe() {\n const desc = await super.describe();\n const connection = await this.getConnection();\n if (connection.instructions) {\n desc.instructions = [connection.instructions, desc.instructions]\n .filter(Boolean)\n .join(\"\\n\\n\");\n }\n return desc;\n }\n\n protected override async tools(): Promise<ConnectorTools> {\n const mcpTools = await this.fetchTools();\n const out: ConnectorTools = {};\n const sources = new Map<string, string>();\n for (const tool of mcpTools) {\n const name = this.toolName(tool);\n const existing = sources.get(name);\n if (existing !== undefined) {\n throw new Error(\n `MCP tools \"${existing}\" and \"${tool.name}\" on ${this.name()} both ` +\n `map to \"${name}\". Override toolName() to disambiguate.`\n );\n }\n sources.set(name, tool.name);\n out[name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7,\n outputSchema: tool.outputSchema as JSONSchema7 | undefined,\n execute: async (args: unknown) => {\n const connection = await this.getConnection();\n return unwrapMcpResult(\n await connection.client.callTool({\n name: tool.name,\n arguments: args as Record<string, unknown>\n })\n );\n }\n };\n }\n return out;\n }\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport { CodemodeConnector, type ConnectorTools } from \"./base\";\nimport { sanitizeToolName } from \"../utils\";\n\nexport type OpenApiRequestOptions = {\n /** Path or URL to call, with path params already substituted. */\n path: string;\n method?: string;\n /** Query parameters to append to the URL. */\n params?: Record<string, unknown>;\n body?: unknown;\n headers?: Record<string, string>;\n};\n\nconst HTTP_METHODS = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"options\",\n \"head\"\n] as const;\n\ntype OpenApiParameter = {\n name: string;\n in: \"path\" | \"query\" | \"header\" | \"cookie\";\n required?: boolean;\n description?: string;\n schema?: JSONSchema7Definition;\n};\n\ntype OpenApiOperation = {\n operationId?: string;\n summary?: string;\n description?: string;\n parameters?: OpenApiParameter[];\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: JSONSchema7Definition }>;\n };\n};\n\n/**\n * Connector backed by an OpenAPI spec.\n *\n * The base reads the spec **once, host-side** and derives one typed tool per\n * operation — so the model calls `api.get_repository({ owner, repo })` directly\n * (discoverable via `codemode.search` / `codemode.describe`, with input types)\n * instead of fetching the raw spec and hand-writing operation lookups on every\n * run. Deriving on the host costs zero prompt tokens.\n *\n * Override two methods:\n *\n * - `spec()` returns the OpenAPI document (used to derive operations)\n * - `request()` performs the authenticated HTTP call\n *\n * A low-level `request` tool is also exposed as an escape hatch for operations\n * the model can't reach through a derived tool.\n *\n * The per-operation tool's input is a single object: top-level keys are the\n * operation's path/query/header parameters, plus a `body` key when the\n * operation has a JSON request body. The derived tool substitutes path params,\n * then hands `request()` a clean `{ path, method, params, body, headers }`.\n *\n * (The sandbox-facing escape hatch is `request`, not `fetch`, because `fetch`\n * is reserved by `WorkerEntrypoint`.)\n */\nexport abstract class OpenApiConnector<\n Env = unknown,\n Props = unknown\n> extends CodemodeConnector<Env, Props> {\n protected abstract spec():\n | Record<string, unknown>\n | Promise<Record<string, unknown>>;\n\n protected abstract request(options: OpenApiRequestOptions): Promise<unknown>;\n\n /** Whether to also expose the raw `spec` document as a tool. Off by default. */\n protected exposeSpec(): boolean {\n return false;\n }\n\n protected override async tools(): Promise<ConnectorTools> {\n const doc = await this.spec();\n const operations = deriveOperations(doc);\n\n const tools: ConnectorTools = {};\n\n if (this.exposeSpec()) {\n tools.spec = {\n description: \"Return the raw OpenAPI document.\",\n inputSchema: { type: \"object\", properties: {} },\n execute: () => this.spec()\n };\n }\n\n tools.request = {\n description:\n \"Escape hatch: perform an authenticated request to a path (and optional method, params, body, headers). Prefer the per-operation tools.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n method: { type: \"string\" },\n params: { type: \"object\", additionalProperties: true },\n body: {},\n headers: { type: \"object\", additionalProperties: { type: \"string\" } }\n },\n required: [\"path\"]\n },\n execute: (args) => this.request(args as OpenApiRequestOptions)\n };\n\n // The derived operation metadata is cached (host-side, by spec identity);\n // only the `execute` closure — which must bind to *this* instance's\n // `request()` — is created fresh here.\n for (const op of operations) {\n tools[op.name] = {\n description: op.description,\n inputSchema: op.inputSchema,\n execute: (args) => this.request(toRequest(op, args))\n };\n }\n\n return tools;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Operation derivation — pure, cached host-side by spec identity.\n//\n// Parsing a spec and resolving its schemas is the expensive part, and a spec is\n// static, but connectors are reconstructed per message — so we memoize the\n// derived (closure-free) operation metadata on the spec object itself. The\n// per-instance `execute` is attached in `tools()`, never cached.\n// ---------------------------------------------------------------------------\n\ntype DerivedOperation = {\n name: string;\n description: string;\n inputSchema: JSONSchema7;\n path: string;\n method: string;\n parameters: OpenApiParameter[];\n};\n\nconst RESERVED_TOOL_NAMES = new Set([\"request\", \"spec\"]);\n\nconst operationCache = new WeakMap<object, DerivedOperation[]>();\n\nfunction deriveOperations(spec: unknown): DerivedOperation[] {\n if (!spec || typeof spec !== \"object\") return [];\n const cached = operationCache.get(spec);\n if (cached) return cached;\n const derived = buildOperations(spec as Record<string, unknown>);\n operationCache.set(spec, derived);\n return derived;\n}\n\nfunction buildOperations(doc: Record<string, unknown>): DerivedOperation[] {\n const paths = (doc.paths ?? {}) as Record<string, Record<string, unknown>>;\n const operations: DerivedOperation[] = [];\n const used = new Set<string>();\n\n for (const [path, item] of Object.entries(paths)) {\n if (!item || typeof item !== \"object\") continue;\n for (const method of HTTP_METHODS) {\n const operation = item[method] as OpenApiOperation | undefined;\n if (!operation || typeof operation !== \"object\") continue;\n const name = operationName(method, path, operation);\n if (!name) continue;\n if (RESERVED_TOOL_NAMES.has(name) || used.has(name)) {\n console.warn(\n `[OpenApiConnector] operation ${method.toUpperCase()} ${path} maps to ` +\n `tool name \"${name}\", which is ${\n RESERVED_TOOL_NAMES.has(name) ? \"reserved\" : \"already used\"\n } — skipping. Set a unique operationId to expose it.`\n );\n continue;\n }\n used.add(name);\n operations.push(buildOperation(doc, path, method, operation, name));\n }\n }\n\n return operations;\n}\n\nfunction operationName(\n method: string,\n path: string,\n operation: OpenApiOperation\n): string {\n if (operation.operationId) return sanitizeToolName(operation.operationId);\n return sanitizeToolName(`${method}_${path}`);\n}\n\nfunction buildOperation(\n doc: Record<string, unknown>,\n path: string,\n method: string,\n operation: OpenApiOperation,\n name: string\n): DerivedOperation {\n const parameters = (operation.parameters ?? []).filter(\n (p): p is OpenApiParameter => !!p && typeof p === \"object\" && !!p.name\n );\n const bodySchema = resolveRef(\n operation.requestBody?.content?.[\"application/json\"]?.schema,\n doc\n );\n const bodyRequired = operation.requestBody?.required === true;\n\n const properties: Record<string, JSONSchema7Definition> = {};\n const required: string[] = [];\n for (const param of parameters) {\n properties[param.name] = withDescription(\n resolveRef(param.schema, doc) ?? {},\n param.description\n );\n if (param.required) required.push(param.name);\n }\n if (bodySchema !== undefined) {\n properties.body = bodySchema;\n if (bodyRequired) required.push(\"body\");\n }\n\n const inputSchema: JSONSchema7 = {\n type: \"object\",\n properties,\n ...(required.length ? { required } : {})\n };\n\n return {\n name,\n description:\n operation.summary ||\n operation.description ||\n `${method.toUpperCase()} ${path}`,\n inputSchema,\n path,\n method,\n parameters\n };\n}\n\nfunction toRequest(op: DerivedOperation, args: unknown): OpenApiRequestOptions {\n const input = (args && typeof args === \"object\" ? args : {}) as Record<\n string,\n unknown\n >;\n let resolvedPath = op.path;\n const query: Record<string, unknown> = {};\n const headers: Record<string, string> = {};\n\n for (const param of op.parameters) {\n const value = input[param.name];\n if (value === undefined) continue;\n if (param.in === \"path\") {\n resolvedPath = resolvedPath.replace(\n `{${param.name}}`,\n encodeURIComponent(String(value))\n );\n } else if (param.in === \"query\") {\n query[param.name] = value;\n } else if (param.in === \"header\") {\n headers[param.name] = String(value);\n }\n }\n\n return {\n path: resolvedPath,\n method: op.method.toUpperCase(),\n ...(Object.keys(query).length ? { params: query } : {}),\n ...(\"body\" in input ? { body: input.body } : {}),\n ...(Object.keys(headers).length ? { headers } : {})\n };\n}\n\n// ---------------------------------------------------------------------------\n// Minimal local $ref inlining for input schemas.\n// ---------------------------------------------------------------------------\n\nfunction withDescription(\n schema: JSONSchema7Definition,\n description?: string\n): JSONSchema7Definition {\n if (!description || typeof schema !== \"object\") return schema;\n return { ...schema, description: schema.description ?? description };\n}\n\n/**\n * Inline local `#/...` `$ref`s so the generated input types are usable,\n * recursing through `properties`, `items`, `additionalProperties`, and the\n * `allOf`/`oneOf`/`anyOf` combinators. External refs and cycles degrade to an\n * open object rather than throwing.\n */\nfunction resolveRef(\n schema: JSONSchema7Definition | undefined,\n root: Record<string, unknown>,\n seen: Set<string> = new Set()\n): JSONSchema7Definition | undefined {\n if (schema === undefined || typeof schema === \"boolean\") return schema;\n\n if (typeof schema.$ref === \"string\") {\n const ref = schema.$ref;\n if (!ref.startsWith(\"#/\") || seen.has(ref)) return { type: \"object\" };\n const target = pointer(root, ref.slice(2).split(\"/\"));\n if (target === undefined) return { type: \"object\" };\n return resolveRef(\n target as JSONSchema7Definition,\n root,\n new Set(seen).add(ref)\n );\n }\n\n const out: JSONSchema7 = { ...schema };\n if (schema.properties) {\n out.properties = {};\n for (const [key, value] of Object.entries(schema.properties)) {\n out.properties[key] = resolveRef(value, root, seen) ?? {};\n }\n }\n if (schema.items && !Array.isArray(schema.items)) {\n out.items = resolveRef(schema.items, root, seen);\n }\n if (\n schema.additionalProperties &&\n typeof schema.additionalProperties === \"object\"\n ) {\n out.additionalProperties = resolveRef(\n schema.additionalProperties,\n root,\n seen\n );\n }\n for (const key of [\"allOf\", \"oneOf\", \"anyOf\"] as const) {\n const branch = schema[key];\n if (Array.isArray(branch)) {\n out[key] = branch.map((s) => resolveRef(s, root, seen) ?? {});\n }\n }\n return out;\n}\n\nfunction pointer(root: unknown, segments: string[]): unknown {\n let current: unknown = root;\n for (const segment of segments) {\n const key = segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n if (!current || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[key];\n }\n return current;\n}\n","/**\n * Executor-style ranked search over connector methods and saved snippets.\n *\n * Normalizes camelCase, snake_case, dots, and path separators into tokens,\n * scores fields by weight, requires token coverage, and sorts by score.\n */\nimport type { ConnectorDescription } from \"./types\";\nimport type { SearchResult, SearchOutput } from \"./types\";\nimport type { Snippet } from \"../snippet\";\n\nconst SEARCH_RESULT_LIMIT = 50;\n\nconst FIELD_WEIGHTS = {\n path: 12,\n connector: 8,\n method: 10,\n description: 5\n} as const;\n\nfunction normalizeSearchText(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[_./:-]+/g, \" \")\n .toLowerCase()\n .trim();\n}\n\nfunction tokenize(value: string): string[] {\n return normalizeSearchText(value)\n .split(/[^a-z0-9]+/)\n .map((t) => t.trim())\n .filter(Boolean);\n}\n\ntype PreparedField = { raw: string; tokens: string[] };\n\nfunction prepareField(value?: string): PreparedField {\n return {\n raw: normalizeSearchText(value ?? \"\"),\n tokens: tokenize(value ?? \"\")\n };\n}\n\nfunction scoreField(\n query: string,\n queryTokens: string[],\n field: PreparedField,\n weight: number\n): { score: number; matchedTokens: Set<string>; exactPhrase: boolean } {\n if (field.raw.length === 0)\n return { score: 0, matchedTokens: new Set(), exactPhrase: false };\n\n let score = 0;\n const matchedTokens = new Set<string>();\n const exactPhrase = query.length > 0 && field.raw.includes(query);\n\n if (query.length > 0) {\n if (field.raw === query) score += weight * 14;\n else if (field.raw.startsWith(query)) score += weight * 9;\n else if (exactPhrase) score += weight * 6;\n }\n\n for (const token of queryTokens) {\n if (field.tokens.includes(token)) {\n score += weight * 4;\n matchedTokens.add(token);\n } else if (\n field.tokens.some((c) => c.startsWith(token) || token.startsWith(c))\n ) {\n score += weight * 2;\n matchedTokens.add(token);\n } else if (field.raw.includes(token)) {\n score += weight;\n matchedTokens.add(token);\n }\n }\n\n return { score, matchedTokens, exactPhrase };\n}\n\ntype SearchableItem = {\n path: string;\n connector: string;\n method: string;\n description?: string;\n kind: \"method\" | \"snippet\";\n};\n\nfunction scoreMatch(item: SearchableItem, query: string): SearchResult | null {\n const normalizedQuery = normalizeSearchText(query);\n const queryTokens = tokenize(query);\n if (normalizedQuery.length === 0 || queryTokens.length === 0) return null;\n\n const fields = [\n scoreField(\n normalizedQuery,\n queryTokens,\n prepareField(item.path),\n FIELD_WEIGHTS.path\n ),\n scoreField(\n normalizedQuery,\n queryTokens,\n prepareField(item.connector),\n FIELD_WEIGHTS.connector\n ),\n scoreField(\n normalizedQuery,\n queryTokens,\n prepareField(item.method),\n FIELD_WEIGHTS.method\n ),\n scoreField(\n normalizedQuery,\n queryTokens,\n prepareField(item.description),\n FIELD_WEIGHTS.description\n )\n ];\n\n const matchedTokens = new Set<string>();\n let score = 0;\n let exactPhrase = false;\n\n for (const field of fields) {\n score += field.score;\n exactPhrase ||= field.exactPhrase;\n for (const t of field.matchedTokens) matchedTokens.add(t);\n }\n\n if (matchedTokens.size === 0) return null;\n\n const coverage = matchedTokens.size / queryTokens.length;\n const minimumCoverage = queryTokens.length <= 2 ? 1 : 0.6;\n if (coverage < minimumCoverage && !exactPhrase) return null;\n\n if (coverage === 1) score += 25;\n else score += Math.round(coverage * 10);\n\n const pathTokens = tokenize(item.path);\n const methodTokens = tokenize(item.method);\n if (pathTokens[0] === queryTokens[0] || methodTokens[0] === queryTokens[0])\n score += 8;\n\n if (\n normalizeSearchText(item.path) === normalizedQuery ||\n normalizeSearchText(item.method) === normalizedQuery\n )\n score += 20;\n\n return {\n path: item.path,\n connector: item.connector,\n method: item.method,\n description: item.description,\n kind: item.kind,\n score\n };\n}\n\nexport function searchConnectors(\n query: string,\n descriptions: ConnectorDescription[],\n snippets?: Snippet[]\n): SearchOutput {\n const items: SearchableItem[] = [];\n\n for (const desc of descriptions) {\n for (const [methodName, descriptor] of Object.entries(desc.descriptors)) {\n items.push({\n path: `${desc.name}.${methodName}`,\n connector: desc.name,\n method: methodName,\n description: descriptor?.description,\n kind: \"method\"\n });\n }\n }\n\n if (snippets) {\n for (const snippet of snippets) {\n items.push({\n path: snippet.name,\n connector: \"snippet\",\n method: snippet.name,\n description: snippet.description,\n kind: \"snippet\"\n });\n }\n }\n\n const ranked = items\n .map((item) => scoreMatch(item, query))\n .filter((r): r is SearchResult => r !== null)\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));\n\n const total = ranked.length;\n const results = ranked.slice(0, SEARCH_RESULT_LIMIT);\n\n return { results, total, truncated: total > SEARCH_RESULT_LIMIT };\n}\n","/**\n * Connector and snippet docs rendering — derives TypeScript documentation from\n * connector descriptors on demand. Also renders snippet source.\n */\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"../json-schema-types\";\nimport { sanitizeToolName } from \"../utils\";\nimport type { ConnectorDescription, DescribeOutput } from \"./types\";\nimport type { Snippet } from \"../snippet\";\n\nfunction renderConnectorTypes(\n connectorName: string,\n instructions: string | undefined,\n descriptors: JsonSchemaToolDescriptors\n): string {\n const types = generateTypesFromJsonSchema(descriptors).replace(\n \"declare const codemode\",\n `declare const ${sanitizeToolName(connectorName)}`\n );\n return [instructions, types].filter(Boolean).join(\"\\n\\n\");\n}\n\nfunction renderMethodTypes(\n methodName: string,\n descriptors: JsonSchemaToolDescriptors\n): string {\n const descriptor = descriptors[methodName];\n if (!descriptor) return \"\";\n const generated = generateTypesFromJsonSchema({ [methodName]: descriptor });\n return generated.slice(0, generated.indexOf(\"declare const codemode\")).trim();\n}\n\nexport function describeTarget(\n target: string,\n descriptions: ConnectorDescription[],\n snippets?: Snippet[]\n): DescribeOutput {\n // Check snippets first\n if (snippets) {\n const snippet = snippets.find((s) => s.name === target);\n if (snippet) {\n const parts = [snippet.description];\n parts.push(`\\`\\`\\`ts\\n${snippet.code}\\n\\`\\`\\``);\n return {\n path: snippet.name,\n description: snippet.description,\n types: parts.join(\"\\n\\n\"),\n kind: \"snippet\"\n };\n }\n }\n\n const [maybeConnector, maybeMethod] = target.includes(\".\")\n ? target.split(\".\", 2)\n : [target, undefined];\n\n const connector = descriptions.find((d) => d.name === maybeConnector);\n\n // Connector-level describe\n if (connector && !maybeMethod) {\n return {\n path: connector.name,\n description: connector.instructions,\n types: renderConnectorTypes(\n connector.name,\n connector.instructions,\n connector.descriptors\n ),\n kind: \"connector\"\n };\n }\n\n // Method-level describe\n const candidates = connector ? [connector] : descriptions;\n const methodName = maybeMethod ?? target;\n\n for (const candidate of candidates) {\n if (candidate.descriptors[methodName]) {\n return {\n path: `${candidate.name}.${methodName}`,\n description: candidate.descriptors[methodName]?.description,\n types: renderMethodTypes(methodName, candidate.descriptors),\n kind: \"method\"\n };\n }\n }\n\n return {\n path: target,\n description: undefined,\n types: `\"${target}\" not found.`,\n kind: \"method\"\n };\n}\n","/**\n * Model-facing proxy tool.\n *\n * One AI SDK tool with `{ code: string }`. Code runs in the Executor sandbox.\n * The CodemodeRuntime facet makes execution durable via abort-and-replay:\n * every tool call is logged; reads execute and record; approval-required\n * actions abort the run; `continue` replays the log and runs the approved action.\n *\n * Inside the sandbox:\n * - Connector SDKs as globals: `<connector>.<method>(...)`\n * - Platform SDK: `codemode.search/describe/step/run`\n *\n * ## Sequencing\n *\n * The host (this module) owns the replay cursor: a per-run counter allocates a\n * `seq` for every connector call and every `codemode.step` in the order they\n * happen, and threads `executionId` + `seq` to the facet. The facet keeps no\n * in-memory cursor, so runs are safe across hibernation and can run\n * concurrently without clobbering one another.\n */\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { tool, type Tool } from \"ai\";\nimport { z } from \"zod\";\nimport type { Executor, ResolvedProvider, ConnectorBinding } from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { normalizeCode } from \"./normalize\";\nimport type { CodemodeConnector, ConnectorDescription } from \"./connectors\";\nimport type {\n ExecutionEndStatus,\n PassEndStatus,\n ToolAnnotations\n} from \"./connectors\";\nimport { searchConnectors, describeTarget } from \"./connectors\";\nimport {\n CodemodeRuntime,\n MAX_DURABLE_VALUE_BYTES,\n STEP_CONNECTOR,\n tooLargeMessage,\n type BeginOptions,\n type PendingAction,\n type ToolDecision,\n type ToolLogEntry,\n type ExecutionState\n} from \"./runtime\";\nimport type { Snippet, SaveSnippetOptions } from \"./snippet\";\nimport type { CodeOutput } from \"./shared\";\n\n// Connector annotations, flattened to \"connector.method\" → annotation.\ntype AnnotationMap = Record<string, ToolAnnotations>;\n\n/**\n * The RPC surface of the CodemodeRuntime facet, as the proxy tool uses it.\n *\n * Declared explicitly rather than relying on `Fetcher<CodemodeRuntime>`: the\n * RPC type transform collapses discriminated unions like `ToolDecision`\n * (the `unknown` payload doesn't survive serialization inference), which would\n * break `decision.kind` narrowing. This interface keeps the domain types intact.\n */\ninterface RuntimeStub {\n begin(code: string, options?: BeginOptions): Promise<string>;\n resume(id: string): Promise<ExecutionState | null>;\n decide(\n executionId: string,\n seq: number,\n connector: string,\n method: string,\n args: unknown,\n requiresApproval: boolean,\n ephemeral?: boolean\n ): Promise<ToolDecision>;\n recordResult(\n executionId: string,\n seq: number,\n result: unknown\n ): Promise<void>;\n complete(\n executionId: string,\n result: unknown,\n logs?: string[]\n ): Promise<void>;\n fail(executionId: string, error: string, logs?: string[]): Promise<void>;\n listPending(executionId?: string): Promise<PendingAction[]>;\n reject(seq: number, executionId: string): Promise<boolean>;\n expirePaused(maxAgeMs?: number): Promise<string[]>;\n actionsToRevert(executionId: string): Promise<ToolLogEntry[]>;\n markReverted(seq: number, executionId: string): Promise<void>;\n markRolledBack(executionId: string): Promise<void>;\n getExecution(id: string): Promise<ExecutionState | null>;\n listExecutions(limit?: number): Promise<ExecutionState[]>;\n deleteExecution(id: string): Promise<boolean>;\n pruneExecutions(keep?: number): Promise<number>;\n saveSnippet(name: string, options: SaveSnippetOptions): Promise<Snippet>;\n getSnippet(name: string): Promise<Snippet | null>;\n listSnippets(): Promise<Snippet[]>;\n deleteSnippet(name: string): Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type ProxyToolInput = { code: string };\n\nexport type ProxyToolOutput =\n | {\n status: \"completed\";\n executionId: string;\n result: unknown;\n logs?: string[];\n }\n | {\n status: \"paused\";\n executionId: string;\n pending: PendingAction[];\n }\n // Execution errors (a thrown sandbox error or a replay divergence) are\n // returned, not thrown: the model sees the failure as a tool result it can\n // reason about, and the agent loop isn't broken by an exception. The failure\n // is also recorded on the execution (status \"error\") for the audit trail.\n | {\n status: \"error\";\n executionId: string;\n error: string;\n logs?: string[];\n };\n\n/**\n * Shape the final result before it is returned to the model. Runs on a\n * completed run only (not on pause/error), after the raw result is recorded on\n * the execution — so the audit trail keeps the full value while the model sees\n * the transformed one. A common use is `truncateResult` to cap response size.\n */\nexport type TransformResult = (result: unknown) => unknown | Promise<unknown>;\n\nexport type CreateProxyToolOptions = {\n ctx: DurableObjectState;\n connectors: CodemodeConnector[];\n executor: Executor;\n /**\n * Runtime name — the durable identity of this runtime's facet (executions,\n * snippets). Defaults to `\"default\"`. Use distinct names for runtimes that\n * should not share history. Adding or removing connectors does NOT change\n * the identity: each execution/snippet records the connector names it needs,\n * and resuming/re-running verifies they are still configured.\n */\n name?: string;\n description?: string;\n /**\n * One-line hints rendered next to each connector in the default tool\n * description (keyed by connector name). Use them to tell the model what a\n * namespace is for — e.g. `{ state: \"the workspace filesystem\" }` — without\n * it having to run a `codemode.search` discovery pass first. Ignored when a\n * custom `description` is given.\n */\n connectorHints?: Record<string, string>;\n /** Terminal executions retained per runtime. Defaults to 50. */\n maxExecutions?: number;\n /** Optionally reshape the model-facing result (e.g. truncate). */\n transformResult?: TransformResult;\n};\n\n// ---------------------------------------------------------------------------\n// Schema + pause sentinel\n// ---------------------------------------------------------------------------\n\nconst proxySchema = z.object({ code: z.string() });\n\n// Sandbox-side marker thrown to abort the run on a pause. The proxy tool\n// detects the pause via the facet's recorded state, not this message.\nconst PAUSE_SENTINEL = \"__CODEMODE_PAUSE__\";\n\n// Sandbox-side definition of `codemode.step(name, fn)`. Assigned as an own\n// property on the codemode namespace so it shadows the dispatch proxy. It\n// wraps the local closure: ask the host whether to replay (return recorded\n// value) or execute (run fn, record the result). This is the explicit\n// side-effect boundary that makes replay correct for arbitrary work.\nconst STEP_PRELUDE = String.raw`\n codemode.step = async (name, fn) => {\n const decision = await codemode.__stepDecide(name);\n if (decision.kind === \"replay\") return decision.result;\n // Anything other than \"execute\" (i.e. a pause from divergence) aborts\n // the run; the reason is recorded on the execution.\n if (decision.kind !== \"execute\") throw new Error(\"${PAUSE_SENTINEL}\");\n const value = await fn();\n await codemode.__stepRecord(decision.seq, value);\n return value;\n };`;\n\n// Connector bindings return a control marker — `{ [CONTROL_KEY]: \"pause\" }` or\n// `{ [CONTROL_KEY]: \"error\", message }` — rather than throwing across RPC. The\n// sandbox connector proxy (see executor.ts CONNECTOR_CONTROL_KEY) detects it and\n// throws locally. Keep these two in sync.\nconst CONTROL_KEY = \"__codemode_control__\";\n\n// ---------------------------------------------------------------------------\n// Host-side replay cursor — allocates seq per call/step, in order.\n// ---------------------------------------------------------------------------\n\ntype Cursor = { next(): number };\n\nfunction createCursor(): Cursor {\n let n = 0;\n return { next: () => n++ };\n}\n\n// ---------------------------------------------------------------------------\n// Connector binding — an RpcTarget the sandbox calls via Workers RPC.\n//\n// Live RPC references can only be serialized as RPC call arguments (not via\n// Worker env), and a plain object with a function property can't be cloned at\n// all — so the binding MUST be an RpcTarget passed as an evaluate() argument.\n// ---------------------------------------------------------------------------\n\nclass ConnectorCallTarget extends RpcTarget {\n #handle: (method: string, args: unknown) => Promise<unknown>;\n constructor(handle: (method: string, args: unknown) => Promise<unknown>) {\n super();\n this.#handle = handle;\n }\n callTool(method: string, args: unknown): Promise<unknown> {\n return this.#handle(method, args);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Setup — connectors + runtime facet\n// ---------------------------------------------------------------------------\n\ntype Setup = {\n connectorsByName: Map<string, CodemodeConnector>;\n descriptions: ConnectorDescription[];\n annotations: AnnotationMap;\n};\n\nasync function loadSetup(connectors: CodemodeConnector[]): Promise<Setup> {\n const connectorsByName = new Map<string, CodemodeConnector>();\n const descriptions: ConnectorDescription[] = [];\n const annotations: AnnotationMap = {};\n\n for (const connector of connectors) {\n const name = connector.name();\n const description = await connector.describe();\n connectorsByName.set(name, connector);\n descriptions.push(description);\n for (const [method, annotation] of Object.entries(\n description.annotations ?? {}\n )) {\n annotations[`${name}.${method}`] = annotation;\n }\n }\n\n return { connectorsByName, descriptions, annotations };\n}\n\n// ---------------------------------------------------------------------------\n// Execution teardown — fire the connector lifecycle hook on a terminal status\n// ---------------------------------------------------------------------------\n\n/**\n * Notify every connector that an execution reached a terminal state so it can\n * dispose any per-execution resource (e.g. a browser session). Deliberately\n * *not* called on pause — a paused run may resume later. Hook rejections are\n * swallowed: teardown must never turn a finished run into a failure.\n *\n * Fires for every connector regardless of whether it took part in the run —\n * connectors that own no per-execution state default to a no-op.\n */\nexport async function disposeConnectors(\n connectors: Iterable<CodemodeConnector>,\n executionId: string,\n status: ExecutionEndStatus\n): Promise<void> {\n await Promise.all(\n [...connectors].map(async (connector) => {\n try {\n await connector.disposeExecution(executionId, status);\n } catch {\n // Intentionally ignored — see doc comment.\n }\n })\n );\n}\n\n/**\n * Notify every connector that an execution pass ended — including a pause,\n * where `disposeExecution` deliberately does not fire — so per-pass resources\n * (open sockets, leases) can be released. Rejections are swallowed for the\n * same reason as `disposeConnectors`.\n */\nasync function notifyPassEnd(\n connectors: Iterable<CodemodeConnector>,\n executionId: string,\n status: PassEndStatus\n): Promise<void> {\n await Promise.all(\n [...connectors].map(async (connector) => {\n try {\n await connector.onPassEnd(executionId, status);\n } catch {\n // Intentionally ignored — see doc comment.\n }\n })\n );\n}\n\n/**\n * Reject reserved and duplicate connector namespaces up front. Duplicates\n * would silently shadow each other in the sandbox (last one wins).\n */\nexport function validateConnectorNames(\n connectors: Iterable<CodemodeConnector>\n): void {\n const seen = new Set<string>();\n for (const connector of connectors) {\n const name = connector.name();\n if (name === \"codemode\") {\n throw new Error(\n 'Connector name \"codemode\" is reserved for the codemode platform SDK.'\n );\n }\n if (seen.has(name)) {\n throw new Error(\n `Duplicate connector name \"${name}\" — each connector needs a unique ` +\n `namespace (pass a distinct \\`name\\` option).`\n );\n }\n seen.add(name);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Connector bindings — every call routes through the runtime for a decision\n// ---------------------------------------------------------------------------\n\nfunction buildConnectorBindings(\n setup: Setup,\n runtime: RuntimeStub,\n executionId: string,\n cursor: Cursor\n): ConnectorBinding[] {\n return setup.descriptions.map((desc) => ({\n name: desc.name,\n binding: new ConnectorCallTarget(async (method, args) => {\n // The RpcTarget method must ALWAYS resolve — never reject. A rejection\n // across the sandbox→host RPC boundary is tracked as an unhandled\n // rejection on the host even though the sandbox awaits it. So every\n // outcome, including a genuine error, is returned as a value: a result, a\n // pause marker, or an error marker. The sandbox proxy turns the pause/\n // error markers into a local throw, which the run's own try/catch handles\n // (and which surfaces as an \"error\" execution exactly as a raw throw did).\n try {\n const seq = cursor.next();\n const annotation = setup.annotations[`${desc.name}.${method}`];\n const requiresApproval = annotation?.requiresApproval ?? false;\n const ephemeral = annotation?.replay === \"reexecute\";\n const decision = await runtime.decide(\n executionId,\n seq,\n desc.name,\n method,\n args,\n requiresApproval,\n ephemeral\n );\n\n if (decision.kind === \"replay\") return decision.result;\n if (decision.kind === \"pause\") return { [CONTROL_KEY]: \"pause\" };\n\n const connector = setup.connectorsByName.get(desc.name);\n if (!connector) throw new Error(`Unknown connector: ${desc.name}`);\n const result = await connector.executeTool(method, args, {\n executionId\n });\n await runtime.recordResult(executionId, decision.seq, result);\n return result;\n } catch (err) {\n // Log the original error (with its stack) on the host: returning a\n // marker keeps the RPC call from rejecting, but a genuine failure still\n // deserves a host-side trace for debugging. The message also reaches the\n // model and the audit trail via the run's \"error\" outcome.\n console.error(\n `codemode: ${desc.name}.${method} failed (execution ${executionId})`,\n err\n );\n return {\n [CONTROL_KEY]: \"error\",\n message: err instanceof Error ? err.message : String(err)\n };\n }\n })\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Platform provider — codemode namespace\n// ---------------------------------------------------------------------------\n\nfunction createPlatformProvider(\n setup: Setup,\n bindings: ConnectorBinding[],\n runtime: RuntimeStub,\n executor: Executor,\n executionId: string,\n cursor: Cursor\n): ResolvedProvider {\n const { descriptions } = setup;\n const provider: ResolvedProvider = {\n name: \"codemode\",\n prelude: STEP_PRELUDE,\n fns: {\n // Discovery\n search: async (query: unknown) =>\n searchConnectors(\n String(query),\n descriptions,\n await runtime.listSnippets()\n ),\n\n describe: async (target: unknown) =>\n describeTarget(\n String(target),\n descriptions,\n await runtime.listSnippets()\n ),\n\n // Snippets — durable saved scripts the developer promoted\n run: async (...args: unknown[]) => {\n const snippet = await runtime.getSnippet(String(args[0]));\n if (!snippet) return { error: `Snippet \"${args[0]}\" not found.` };\n // The snippet recorded the connectors its source execution ran with;\n // refuse with a clear error when one is no longer configured rather\n // than failing partway through the script.\n const missing = missingConnectors(\n snippet.connectors,\n new Set(setup.connectorsByName.keys())\n );\n if (missing.length > 0) {\n return {\n error:\n `Snippet \"${args[0]}\" requires connector(s) ` +\n `${missing.map((m) => `\"${m}\"`).join(\", \")} that are not ` +\n `configured on this runtime.`\n };\n }\n // Snippets are saved execution code, so they may use the codemode\n // SDK (e.g. codemode.step) — run them with this same provider, which\n // shares the cursor so the snippet's calls continue this run's log.\n //\n // The stored snippet is the model's raw code, which may carry markdown\n // fences or be a statement block — embedding it directly as an\n // expression would be a syntax error. Normalize it to a valid arrow\n // expression first (the same transform the executor applies to a fresh\n // run); `runCode` then normalizes the outer wrapper as usual.\n const snippetExpr = normalizeCode(snippet.code);\n const result = await runCode({\n code: `async () => {\\n const snippet = (${snippetExpr});\\n return await snippet(${JSON.stringify(args[1])});\\n}`,\n executor,\n providers: [provider],\n connectors: bindings\n });\n return result.result;\n },\n\n // Host primitives backing the codemode.step() prelude. The closure\n // can't cross the RPC boundary, so step decides + records here while the\n // sandbox runs the closure locally only when told to execute.\n __stepDecide: async (name: unknown) =>\n runtime.decide(\n executionId,\n cursor.next(),\n STEP_CONNECTOR,\n String(name),\n undefined,\n false\n ),\n\n __stepRecord: async (seq: unknown, value: unknown) => {\n await runtime.recordResult(executionId, Number(seq), value);\n return true;\n }\n }\n };\n return provider;\n}\n\n// ---------------------------------------------------------------------------\n// Tool description\n// ---------------------------------------------------------------------------\n\nfunction buildDescription(\n connectors: CodemodeConnector[],\n customDescription?: string,\n connectorHints?: Record<string, string>\n): string {\n if (customDescription) return customDescription;\n\n const namespaces = connectors\n .map((c) => {\n const name = c.name();\n const hint = connectorHints?.[name];\n return hint ? `- \\`${name}\\` — ${hint}` : `- \\`${name}\\``;\n })\n .join(\"\\n\");\n\n const names = connectors.map((c) => `\\`${c.name()}\\``).join(\", \");\n\n const lines = [\n \"Execute TypeScript in a sandbox with access to connector SDKs.\",\n \"\",\n \"## Workflow\",\n \"\",\n '1. `const matches = await codemode.search(\"short intent phrase\");`',\n \"2. `const docs = await codemode.describe(matches.results[0].path);`\",\n \"3. Call the method: `await <connector>.<method>(args);`\",\n \"\",\n \"## Rules\",\n \"\",\n `- The ONLY globals are ${names} and \\`codemode\\` (plus standard JavaScript). There is no \\`host\\`, \\`fs\\`, \\`require\\`, \\`process\\`, or Node.js API — all I/O goes through the connectors below.`,\n \"- Never guess method names. If you have not used a connector in this conversation, run a discovery pass first: `codemode.search(query)` returns ranked matches across connector methods and saved snippets.\",\n '- `codemode.describe(\"connector.method\")` returns TypeScript type declarations.',\n \"- `codemode.step(name, fn)` wraps side-effectful or nondeterministic work (raw fetch, random, time) so it runs once and is replayed on resume. Use it for anything that isn't a connector call.\",\n \"- Some methods require approval. The run pauses until the user approves, then resumes automatically. Write code as if the call returns normally.\",\n '- A result with `status: \"paused\"` means the run is awaiting human approval. Tell the user what is pending and wait — do NOT re-issue the code; the run resumes on its own once approved.',\n \"- All code outside connector calls and `codemode.step` must be deterministic so resume can replay it.\",\n \"- Do not use `fetch` — use connector SDKs.\",\n \"\",\n \"## Snippets\",\n \"\",\n \"Snippets are saved scripts you can reuse.\",\n '- `codemode.run(\"name\", input)` runs a saved snippet. Snippets appear in `codemode.search` results.',\n \"- If a script may be saved as a snippet later, write it as `async (input) => { ... }` so it can take input.\",\n \"\",\n \"## Available connectors\",\n \"\",\n namespaces\n ];\n\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Run one pass of the code through the executor.\n// ---------------------------------------------------------------------------\n\nasync function runPass(\n executionId: string,\n code: string,\n setup: Setup,\n runtime: RuntimeStub,\n executor: Executor,\n transformResult?: TransformResult\n): Promise<ProxyToolOutput> {\n const cursor = createCursor();\n const bindings = buildConnectorBindings(setup, runtime, executionId, cursor);\n const platformProvider = createPlatformProvider(\n setup,\n bindings,\n runtime,\n executor,\n executionId,\n cursor\n );\n\n const connectors = [...setup.connectorsByName.values()];\n\n // Every pass — paused, completed, or errored — must end with onPassEnd so\n // connectors can release per-pass resources (sockets, leases). On terminal\n // outcomes, disposeExecution follows. `ended` makes the finally a safety net\n // for crashes inside this function itself (e.g. a facet RPC failure), not a\n // double-fire.\n let ended = false;\n const endPass = async (status: PassEndStatus) => {\n ended = true;\n await notifyPassEnd(connectors, executionId, status);\n if (status !== \"paused\") {\n await disposeConnectors(connectors, executionId, status);\n }\n };\n\n try {\n let output: CodeOutput | undefined;\n let threw: unknown;\n try {\n output = await runCode({\n code,\n executor,\n providers: [platformProvider],\n connectors: bindings\n });\n } catch (err) {\n threw = err;\n }\n\n // The facet status is the source of truth: a pause (approval or\n // divergence) records itself there before aborting the run. The\n // PAUSE_SENTINEL only stops the sandbox; it is never the deciding signal\n // here.\n const execution = await runtime.getExecution(executionId);\n if (execution?.status === \"paused\") {\n // Not terminal — the run may resume, so per-execution connector\n // resources stay open. Per-pass resources are still released.\n await endPass(\"paused\");\n return {\n status: \"paused\",\n executionId,\n pending: await runtime.listPending(executionId)\n };\n }\n if (execution?.status === \"error\") {\n // A replay divergence (or an in-run durable-log failure), already\n // recorded on the execution by the facet.\n await endPass(\"error\");\n return {\n status: \"error\",\n executionId,\n error: execution.error ?? \"Codemode execution failed\"\n };\n }\n\n if (threw) {\n const raw = threw instanceof Error ? threw.message : String(threw);\n const message = withGlobalsHint(raw, setup);\n await runtime.fail(executionId, message);\n await endPass(\"error\");\n return { status: \"error\", executionId, error: message };\n }\n\n const result = output?.result;\n await runtime.complete(executionId, result, output?.logs);\n await endPass(\"completed\");\n return {\n status: \"completed\",\n executionId,\n result: await applyTransform(transformResult, result),\n logs: output?.logs\n };\n } finally {\n if (!ended) {\n // Something inside runPass itself threw before any labeled exit — make\n // sure connectors still hear about the pass ending.\n await endPass(\"error\");\n }\n }\n}\n\n/**\n * A sandbox `ReferenceError` usually means the model invented a global (e.g.\n * `host.writeFile(...)`). Append the real globals so the retry is informed\n * instead of another guess.\n */\nfunction withGlobalsHint(message: string, setup: Setup): string {\n if (!/\\bis not defined\\b/.test(message)) return message;\n const names = [...setup.connectorsByName.keys(), \"codemode\"].join(\", \");\n return `${message} (the only globals available in the sandbox are: ${names})`;\n}\n\n/**\n * Apply the result transform, defending against a buggy transform: the run has\n * already completed and its resources are disposed, so a throwing transform\n * must not turn a successful run into a thrown tool error. Fall back to the raw\n * result (and warn) instead.\n */\nasync function applyTransform(\n transformResult: TransformResult | undefined,\n result: unknown\n): Promise<unknown> {\n if (!transformResult) return result;\n try {\n return await transformResult(result);\n } catch (err) {\n console.warn(\n \"codemode: transformResult threw; returning the raw result.\",\n err\n );\n return result;\n }\n}\n\n// ---------------------------------------------------------------------------\n// createProxyTool\n// ---------------------------------------------------------------------------\n\nexport function createProxyTool(\n options: CreateProxyToolOptions\n): Tool<ProxyToolInput, ProxyToolOutput> {\n const connectors = options.connectors;\n validateConnectorNames(connectors);\n\n // Spawn the runtime facet on the agent DO, keyed by the runtime name. The\n // connector set is data, not identity: each execution/snippet records the\n // connector names it needs, and resume/snippet-run verifies they are still\n // configured — so a runtime can gain or lose connectors without forking its\n // history.\n const runtime = getRuntime(options.ctx, options.name);\n\n let setupPromise: Promise<Setup> | undefined;\n function getSetup() {\n return (setupPromise ??= loadSetup(connectors));\n }\n\n return tool({\n description: buildDescription(\n connectors,\n options.description,\n options.connectorHints\n ),\n inputSchema: proxySchema,\n execute: async ({ code }) => {\n // Validate size host-side (the facet's own guard would surface as a\n // cross-worker unhandled rejection) and return a model-actionable\n // tool result instead of breaking the agent loop.\n if (code.length > MAX_DURABLE_VALUE_BYTES) {\n return {\n status: \"error\",\n executionId: \"\",\n error: tooLargeMessage(\"The execution code\", code.length)\n };\n }\n const setup = await getSetup();\n const executionId = await runtime.begin(code, {\n maxExecutions: options.maxExecutions,\n connectors: connectors.map((c) => c.name())\n });\n return runPass(\n executionId,\n code,\n setup,\n runtime,\n options.executor,\n options.transformResult\n );\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// Shared facet handle\n// ---------------------------------------------------------------------------\n\n/** Default runtime name when none is given. */\nconst DEFAULT_RUNTIME_NAME = \"default\";\n\n/**\n * The facet is keyed by an explicit runtime *name* (default `\"default\"`), not\n * by the connector set: a runtime keeps its executions and snippets when\n * connectors are added or removed. Staleness is handled as data instead —\n * every execution and snippet records the connector names it needs, and\n * resume/snippet-run verifies they are present, failing with a clear error\n * when one is missing.\n */\nfunction runtimeFacetName(name = DEFAULT_RUNTIME_NAME): string {\n if (!/^[a-zA-Z0-9_.-]+$/.test(name)) {\n throw new Error(\n `Invalid codemode runtime name \"${name}\" — use letters, digits, ` +\n `\"_\", \"-\" or \".\"`\n );\n }\n return `codemode:${name}`;\n}\n\n// `ctx.facets` / `ctx.exports` are facet-runtime additions not yet in the\n// public DurableObjectState types. The facet `class` must be the\n// binding-backed value from `ctx.exports` (a directly-imported class reference\n// is rejected by the runtime) — the consumer's worker must export the runtime\n// class under the name `CodemodeRuntime` (the Vite plugin does this for you).\ntype FacetCapableCtx = DurableObjectState & {\n facets: {\n get<T>(name: string, init: () => { class: unknown; id?: unknown }): T;\n };\n exports?: Record<string, unknown>;\n};\n\nfunction getRuntime(ctx: DurableObjectState, name?: string): RuntimeStub {\n const facetCtx = ctx as unknown as FacetCapableCtx;\n const runtimeClass = facetCtx.exports?.CodemodeRuntime ?? CodemodeRuntime;\n return facetCtx.facets.get<RuntimeStub>(runtimeFacetName(name), () => ({\n class: runtimeClass\n }));\n}\n\n/** Internal: the runtime handle uses this to reach the facet. Not public API. */\nexport const getCodemodeRuntime = getRuntime;\n\n// ---------------------------------------------------------------------------\n// Resume — approve a pending action and continue via replay\n// ---------------------------------------------------------------------------\n\nexport type ResumeCodemodeOptions = {\n ctx: DurableObjectState;\n connectors: CodemodeConnector[];\n executor: Executor;\n /** Runtime name (facet identity). Defaults to `\"default\"`. */\n name?: string;\n /** Execution id to resume. */\n executionId: string;\n maxExecutions?: number;\n /** Optionally reshape the model-facing result (e.g. truncate). */\n transformResult?: TransformResult;\n};\n\n/** Connectors an execution/snippet recorded but the runtime no longer has. */\nfunction missingConnectors(\n required: string[] | undefined,\n available: Set<string>\n): string[] {\n return (required ?? []).filter((name) => !available.has(name));\n}\n\n/**\n * Approve a pending action and continue the paused execution. Re-runs the\n * stored code; the runtime replays the log up to the approved action, runs it\n * for real, and proceeds to the next pause or completion.\n */\nexport async function resumeCodemode(\n options: ResumeCodemodeOptions\n): Promise<ProxyToolOutput> {\n const runtime = getRuntime(options.ctx, options.name);\n\n const setup = await loadSetup(options.connectors);\n\n // The execution recorded the connector set it started with. Refuse to\n // resume when a required connector is no longer configured — replaying its\n // logged calls would fail confusingly partway through otherwise.\n const existing = await runtime.getExecution(options.executionId);\n if (existing) {\n const missing = missingConnectors(\n existing.connectors,\n new Set(setup.connectorsByName.keys())\n );\n if (missing.length > 0) {\n return {\n status: \"error\",\n executionId: options.executionId,\n error:\n `Execution \"${options.executionId}\" requires connector(s) ` +\n `${missing.map((m) => `\"${m}\"`).join(\", \")} that are not ` +\n `configured on this runtime.`\n };\n }\n }\n\n const execution = await runtime.resume(options.executionId);\n if (!execution) {\n // resume() returns null both when the run is missing and when it isn't\n // paused. Distinguish the two so a caller can't silently revive a terminal\n // run (which would re-offer rejected actions or re-apply rolled-back work).\n // Surface this as an error *outcome* (not a throw) to match the divergence/\n // pause paths — the agent loop stays unbroken and nothing is re-executed.\n const error = existing\n ? `Execution \"${options.executionId}\" is not paused (status: ` +\n `${existing.status}); only a paused run can be approved.`\n : `No execution \"${options.executionId}\" to resume.`;\n return { status: \"error\", executionId: options.executionId, error };\n }\n\n return runPass(\n execution.id,\n execution.code,\n setup,\n runtime,\n options.executor,\n options.transformResult\n );\n}\n\n// ---------------------------------------------------------------------------\n// Reject — reject a pending action, ending the execution\n// ---------------------------------------------------------------------------\n\n/**\n * Returns whether the reject actually terminated the run — `false` when the\n * seq was no longer pending (already approved, rejected elsewhere, or\n * expired). Callers MUST check this before reporting the run as rejected:\n * approve and reject can interleave across the facet RPC await, and a no-op\n * reject means the action may have executed.\n */\nexport async function rejectCodemode(options: {\n ctx: DurableObjectState;\n connectors: CodemodeConnector[];\n name?: string;\n seq: number;\n executionId: string;\n}): Promise<boolean> {\n const terminated = await getRuntime(options.ctx, options.name).reject(\n options.seq,\n options.executionId\n );\n // Only dispose if the reject actually ended the run. A stale/duplicate reject\n // (seq no longer pending) is a no-op, and the run may still be live and\n // resumable — tearing its resources down would break the next resume.\n if (terminated) {\n await disposeConnectors(\n options.connectors,\n options.executionId,\n \"rejected\"\n );\n }\n return terminated;\n}\n\n// ---------------------------------------------------------------------------\n// Pending — list actions awaiting approval, for approval UIs\n// ---------------------------------------------------------------------------\n\nexport async function pendingCodemode(options: {\n ctx: DurableObjectState;\n name?: string;\n executionId?: string;\n}): Promise<PendingAction[]> {\n return getRuntime(options.ctx, options.name).listPending(options.executionId);\n}\n\n// ---------------------------------------------------------------------------\n// Expiry — reclaim paused runs nobody ever approved\n// ---------------------------------------------------------------------------\n\n/**\n * Expire paused (awaiting-approval) executions idle past `maxAgeMs`, marking\n * them rejected and firing each connector's `disposeExecution` so\n * per-execution resources (e.g. browser sessions) are reclaimed. Paused runs\n * are deliberately exempt from retention pruning, so without this a\n * never-answered approval would live forever. Returns the expired ids.\n * Designed to be called from a recurring alarm/scheduled task.\n */\nexport async function expireCodemode(options: {\n ctx: DurableObjectState;\n connectors: CodemodeConnector[];\n name?: string;\n /** Expire paused runs whose last state change is older than this. */\n maxAgeMs?: number;\n}): Promise<string[]> {\n const expired = await getRuntime(options.ctx, options.name).expirePaused(\n options.maxAgeMs\n );\n for (const executionId of expired) {\n await disposeConnectors(options.connectors, executionId, \"rejected\");\n }\n return expired;\n}\n\n// ---------------------------------------------------------------------------\n// Rollback — revert applied actions in reverse order\n// ---------------------------------------------------------------------------\n\nexport async function rollbackCodemode(options: {\n ctx: DurableObjectState;\n connectors: CodemodeConnector[];\n name?: string;\n executionId: string;\n}): Promise<void> {\n const runtime = getRuntime(options.ctx, options.name);\n\n const byName = new Map(options.connectors.map((c) => [c.name(), c]));\n const actions = await runtime.actionsToRevert(options.executionId);\n\n // Attempt every revert, in reverse order, even if some fail — a failing\n // compensation must not strand the actions after it as un-reverted. Failures\n // are collected and surfaced after the whole pass rather than aborting it.\n let reverted = 0;\n const failures: string[] = [];\n for (const action of actions) {\n const connector = byName.get(action.connector);\n if (!connector) continue;\n try {\n // revertAction no-ops (returns false) for reads / tools without a revert.\n const didRevert = await connector.revertAction(\n action.method,\n action.args,\n action.result,\n { executionId: options.executionId }\n );\n if (didRevert) {\n await runtime.markReverted(action.seq, options.executionId);\n reverted++;\n }\n } catch (err) {\n failures.push(\n `${action.connector}.${action.method}: ` +\n (err instanceof Error ? err.message : String(err))\n );\n }\n }\n\n // Reflect the rollback in the execution status so the audit trail doesn't\n // keep showing \"completed\" after the run's effects were undone.\n if (reverted > 0) {\n await runtime.markRolledBack(options.executionId);\n // Rolling back is terminal — dispose per-execution connector resources.\n await disposeConnectors(\n options.connectors,\n options.executionId,\n \"rolled_back\"\n );\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Rollback reverted ${reverted} action(s) but ${failures.length} failed: ` +\n failures.join(\"; \")\n );\n }\n}\n","import type { Tool } from \"ai\";\nimport type { CodemodeConnector } from \"./connectors\";\nimport type { Executor } from \"./executor\";\nimport {\n createProxyTool,\n disposeConnectors,\n expireCodemode,\n getCodemodeRuntime,\n pendingCodemode,\n rejectCodemode,\n resumeCodemode,\n rollbackCodemode,\n validateConnectorNames,\n type ProxyToolInput,\n type ProxyToolOutput,\n type TransformResult\n} from \"./proxy-tool\";\nimport type { ExecutionState, PendingAction } from \"./runtime\";\nimport type { SaveSnippetOptions, Snippet } from \"./snippet\";\n\nexport type CreateCodemodeRuntimeOptions = {\n ctx: DurableObjectState;\n connectors: CodemodeConnector[];\n executor: Executor;\n /**\n * Runtime name — the durable identity of this runtime's facet (its\n * executions and snippets). Defaults to `\"default\"`. Use distinct names for\n * runtimes that should keep separate histories. Adding or removing\n * connectors does NOT change the identity: each execution/snippet records\n * the connector names it needs, and resuming/re-running verifies they are\n * still configured.\n */\n name?: string;\n /**\n * How many terminal (completed/error) executions to retain per runtime.\n * Older ones are pruned automatically when a new run begins. Running and\n * paused executions are never pruned (see `expirePaused`). Defaults to 50.\n */\n maxExecutions?: number;\n /**\n * Optionally reshape the model-facing result of a completed run before it is\n * returned — e.g. `(r) => truncateResult(r)` to cap response size. The raw\n * result is still recorded on the execution, so the audit trail is intact.\n * Applies to both the initial run and a resume after approval.\n */\n transformResult?: TransformResult;\n};\n\nexport type CodemodeRuntimeToolOptions = {\n description?: string;\n /**\n * One-line hints rendered next to each connector in the default tool\n * description (keyed by connector name). Ignored when a custom\n * `description` is given.\n */\n connectorHints?: Record<string, string>;\n};\n\nexport type CodemodeApproveOptions = {\n /** Execution to approve and resume. Get it from `pending()` or the tool output. */\n executionId: string;\n};\n\nexport type CodemodeRejectOptions = {\n seq: number;\n /** Execution to reject within. Get it from `pending()`. */\n executionId: string;\n};\n\nexport type CodemodeRollbackOptions = {\n /** Execution to roll back. Get it from `executions()` or the tool output. */\n executionId: string;\n};\n\nexport type CodemodeExpireOptions = {\n /**\n * Expire non-terminal runs whose last state change is older than this.\n * Defaults to 24 hours.\n */\n maxAgeMs?: number;\n};\n\nexport interface CodemodeRuntimeHandle {\n tool(\n options?: CodemodeRuntimeToolOptions\n ): Tool<ProxyToolInput, ProxyToolOutput>;\n approve(options: CodemodeApproveOptions): Promise<ProxyToolOutput>;\n /**\n * Reject a pending action, ending the run. Returns whether the reject\n * actually terminated it — `false` when the action was no longer pending\n * (approved or rejected from elsewhere, or expired), in which case the run\n * was NOT rejected and the action may have executed.\n */\n reject(options: CodemodeRejectOptions): Promise<boolean>;\n rollback(options: CodemodeRollbackOptions): Promise<void>;\n pending(executionId?: string): Promise<PendingAction[]>;\n /**\n * Expire stale non-terminal runs (neither is ever auto-pruned), disposing\n * per-execution connector resources: paused runs nobody approved are marked\n * rejected; running runs whose host died mid-pass are marked error. Call\n * from a recurring alarm/scheduled task. Returns the expired ids.\n */\n expirePaused(options?: CodemodeExpireOptions): Promise<string[]>;\n /** All executions, newest first — the audit trail. Optionally capped. */\n executions(limit?: number): Promise<ExecutionState[]>;\n /**\n * Delete a single execution from the audit trail. Deleting a non-terminal\n * execution also disposes its per-execution connector resources.\n */\n deleteExecution(id: string): Promise<boolean>;\n /** Prune terminal executions, keeping the newest `keep`. */\n pruneExecutions(keep?: number): Promise<number>;\n /** Promote an execution's script to a named, reusable snippet. */\n saveSnippet(name: string, options: SaveSnippetOptions): Promise<Snippet>;\n snippets(): Promise<Snippet[]>;\n deleteSnippet(name: string): Promise<boolean>;\n}\n\nexport function createCodemodeRuntime(\n options: CreateCodemodeRuntimeOptions\n): CodemodeRuntimeHandle {\n return new DefaultCodemodeRuntimeHandle(options);\n}\n\nclass DefaultCodemodeRuntimeHandle implements CodemodeRuntimeHandle {\n #options: CreateCodemodeRuntimeOptions;\n\n constructor(options: CreateCodemodeRuntimeOptions) {\n validateConnectorNames(options.connectors);\n this.#options = options;\n }\n\n tool(\n options?: CodemodeRuntimeToolOptions\n ): Tool<ProxyToolInput, ProxyToolOutput> {\n return createProxyTool({\n ctx: this.#options.ctx,\n executor: this.#options.executor,\n connectors: this.#options.connectors,\n name: this.#options.name,\n description: options?.description,\n connectorHints: options?.connectorHints,\n maxExecutions: this.#options.maxExecutions,\n transformResult: this.#options.transformResult\n });\n }\n\n approve(options: CodemodeApproveOptions): Promise<ProxyToolOutput> {\n return resumeCodemode({\n ctx: this.#options.ctx,\n executor: this.#options.executor,\n connectors: this.#options.connectors,\n name: this.#options.name,\n executionId: options.executionId,\n maxExecutions: this.#options.maxExecutions,\n transformResult: this.#options.transformResult\n });\n }\n\n reject(options: CodemodeRejectOptions): Promise<boolean> {\n return rejectCodemode({\n ctx: this.#options.ctx,\n connectors: this.#options.connectors,\n name: this.#options.name,\n seq: options.seq,\n executionId: options.executionId\n });\n }\n\n rollback(options: CodemodeRollbackOptions): Promise<void> {\n return rollbackCodemode({\n ctx: this.#options.ctx,\n connectors: this.#options.connectors,\n name: this.#options.name,\n executionId: options.executionId\n });\n }\n\n pending(executionId?: string): Promise<PendingAction[]> {\n return pendingCodemode({\n ctx: this.#options.ctx,\n name: this.#options.name,\n executionId\n });\n }\n\n expirePaused(options?: CodemodeExpireOptions): Promise<string[]> {\n return expireCodemode({\n ctx: this.#options.ctx,\n connectors: this.#options.connectors,\n name: this.#options.name,\n maxAgeMs: options?.maxAgeMs\n });\n }\n\n executions(limit?: number): Promise<ExecutionState[]> {\n return this.#runtime().listExecutions(limit);\n }\n\n async deleteExecution(id: string): Promise<boolean> {\n const runtime = this.#runtime();\n // A non-terminal execution still owns per-execution connector resources\n // (e.g. a browser session) that `disposeExecution` would normally release\n // on its terminal transition — deleting the record must not leak them.\n const state = await runtime.getExecution(id);\n const deleted = await runtime.deleteExecution(id);\n if (\n deleted &&\n (state?.status === \"paused\" || state?.status === \"running\")\n ) {\n await disposeConnectors(this.#options.connectors, id, \"rejected\");\n }\n return deleted;\n }\n\n pruneExecutions(keep?: number): Promise<number> {\n return this.#runtime().pruneExecutions(keep);\n }\n\n saveSnippet(name: string, options: SaveSnippetOptions): Promise<Snippet> {\n return this.#runtime().saveSnippet(name, options);\n }\n\n snippets(): Promise<Snippet[]> {\n return this.#runtime().listSnippets();\n }\n\n deleteSnippet(name: string): Promise<boolean> {\n return this.#runtime().deleteSnippet(name);\n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,CAAC,cAAc,IAAI;CAC3C;CAEA,WAAW;EACT,OAAO,mBAAmB,KAAKD,SAAS,KAAK,KAAKA,SAAS,IAAI;CACjE;AACF"}
@@ -370,4 +370,4 @@ ${availableTools}
370
370
  //#endregion
371
371
  export { sanitizeToolName as a, escapeJsDoc as i, jsonSchemaToType as n, toPascalCase as o, jsonSchemaToTypeString as r, normalizeCode as s, generateTypesFromJsonSchema as t };
372
372
 
373
- //# sourceMappingURL=json-schema-types-CVt4X9cw.js.map
373
+ //# sourceMappingURL=json-schema-types-BGjW4KPy.js.map