@cloudflare/codemode 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -11
- package/dist/ai.d.ts +2 -2
- package/dist/ai.js +3 -3
- package/dist/{base-CHRR_a5j.js → base-BqhlNCSH.js} +2 -2
- package/dist/{base-CHRR_a5j.js.map → base-BqhlNCSH.js.map} +1 -1
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +4 -4
- package/dist/browser.js.map +1 -1
- package/dist/{executor-BIs2dr7X.d.ts → executor-DkMGH_7-.d.ts} +2 -2
- package/dist/index.d.ts +54 -12
- package/dist/index.js +79 -27
- package/dist/index.js.map +1 -1
- package/dist/{json-schema-types-BGjW4KPy.js → json-schema-types-D_m9tVnI.js} +2 -2
- package/dist/{json-schema-types-BGjW4KPy.js.map → json-schema-types-D_m9tVnI.js.map} +1 -1
- package/dist/mcp.d.ts +35 -2
- package/dist/mcp.js +3 -3
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-CBr_VoPl.d.ts → resolve-tqDt6Djo.d.ts} +2 -2
- package/dist/{run-code-aKHcTgf9.js → run-code-Q3Jh6Dcu.js} +2 -2
- package/dist/{run-code-aKHcTgf9.js.map → run-code-Q3Jh6Dcu.js.map} +1 -1
- package/dist/{shared-Ce-zCEBP.d.ts → shared-BOF2IKt-.d.ts} +2 -2
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +2 -2
- package/dist/vite.js +19 -91
- package/dist/vite.js.map +1 -1
- package/docs/approvals.md +169 -0
- package/docs/connectors.md +343 -0
- package/docs/index.md +192 -0
- package/docs/runtime.md +263 -0
- package/docs/snippets.md +96 -0
- package/docs/vite-plugin.md +60 -0
- package/package.json +22 -4
package/README.md
CHANGED
|
@@ -4,6 +4,8 @@ Instead of asking LLMs to call tools directly, Code Mode lets them write executa
|
|
|
4
4
|
|
|
5
5
|
Code Mode generates TypeScript type definitions from your tools for LLM context, and executes the generated JavaScript in secure, isolated sandboxes with millisecond startup times.
|
|
6
6
|
|
|
7
|
+
The published package includes the Codemode guides at `docs/index.md`.
|
|
8
|
+
|
|
7
9
|
> **Experimental** — may have breaking changes. Use with caution in production.
|
|
8
10
|
|
|
9
11
|
## Installation
|
|
@@ -193,7 +195,7 @@ await executor.execute(code, [resolveProvider(dbProvider)]);
|
|
|
193
195
|
|
|
194
196
|
## Connectors
|
|
195
197
|
|
|
196
|
-
Connectors are class-based integrations that bridge external services into the codemode sandbox.
|
|
198
|
+
Connectors are class-based integrations that bridge external services into the codemode sandbox.
|
|
197
199
|
|
|
198
200
|
Create a runtime with an executor and connectors, then expose `runtime.tool()` to the model:
|
|
199
201
|
|
|
@@ -330,7 +332,7 @@ const raw = await stripe.request({ path: "/v1/charges", method: "GET" });
|
|
|
330
332
|
|
|
331
333
|
### `CodemodeConnector` (base class)
|
|
332
334
|
|
|
333
|
-
|
|
335
|
+
A connector is three things — `name()`, optional `instructions()`, and `tools()`. Each tool carries its own docs, schema, approval requirement, execution, and optional revert, so everything about a tool lives in one place:
|
|
334
336
|
|
|
335
337
|
```ts
|
|
336
338
|
import { CodemodeConnector } from "@cloudflare/codemode";
|
|
@@ -400,7 +402,7 @@ Snippets appear in `codemode.search` results (with `kind: "snippet"`) and are do
|
|
|
400
402
|
|
|
401
403
|
### Vite plugin
|
|
402
404
|
|
|
403
|
-
The `@cloudflare/codemode/vite` plugin
|
|
405
|
+
The `@cloudflare/codemode/vite` plugin exports the `CodemodeRuntime` facet class from the Worker entry module, making it available as `ctx.exports.CodemodeRuntime` for facet spawning:
|
|
404
406
|
|
|
405
407
|
```ts
|
|
406
408
|
// vite.config.ts
|
|
@@ -408,11 +410,11 @@ import codemode from "@cloudflare/codemode/vite";
|
|
|
408
410
|
export default { plugins: [codemode()] };
|
|
409
411
|
```
|
|
410
412
|
|
|
411
|
-
|
|
413
|
+
Connector classes are ordinary TypeScript imports:
|
|
412
414
|
|
|
413
415
|
```ts
|
|
414
|
-
import { GithubConnector } from "./github.codemode"
|
|
415
|
-
import { StripeConnector } from "./stripe.codemode"
|
|
416
|
+
import { GithubConnector } from "./github.codemode";
|
|
417
|
+
import { StripeConnector } from "./stripe.codemode";
|
|
416
418
|
```
|
|
417
419
|
|
|
418
420
|
### How connector calls work
|
|
@@ -422,9 +424,9 @@ import { StripeConnector } from "./stripe.codemode" with { type: "connectors" };
|
|
|
422
424
|
│ │ │ Dynamic Worker (isolated sandbox) │
|
|
423
425
|
│ Host Worker │ RPC │ │
|
|
424
426
|
│ │◄──────►│ github.list_pull_requests(args) │
|
|
425
|
-
│ Connectors are │ │ →
|
|
426
|
-
│
|
|
427
|
-
│
|
|
427
|
+
│ Connectors are │ │ → __connectors.github.callTool(...) │
|
|
428
|
+
│ host-side RPC │ │ → Workers RPC │
|
|
429
|
+
│ targets │ │ │
|
|
428
430
|
│ │ │ codemode.search("query") │
|
|
429
431
|
│ Platform SDK uses │ │ → __dispatchers.codemode.call(...) │
|
|
430
432
|
│ ToolDispatcher │ │ → host-side search │
|
|
@@ -432,7 +434,7 @@ import { StripeConnector } from "./stripe.codemode" with { type: "connectors" };
|
|
|
432
434
|
└─────────────────────┘ └─────────────────────────────────────────────┘
|
|
433
435
|
```
|
|
434
436
|
|
|
435
|
-
Connector calls go via **Workers RPC** directly to the connector
|
|
437
|
+
Connector calls go via **Workers RPC** directly to the host-side connector binding — no JSON serialization through ToolDispatcher. The platform SDK (`codemode.search`, `codemode.describe`, etc.) uses the traditional ToolDispatcher path since it's host-created.
|
|
436
438
|
|
|
437
439
|
## Architecture
|
|
438
440
|
|
|
@@ -533,7 +535,7 @@ class NodeVMExecutor implements Executor {
|
|
|
533
535
|
| Option | Type | Default | Description |
|
|
534
536
|
| ---------------- | ------------------------ | -------- | ------------------------------------------------------------ |
|
|
535
537
|
| `loader` | `WorkerLoader` | required | Worker Loader binding from `env.LOADER` |
|
|
536
|
-
| `timeout` | `number` | `
|
|
538
|
+
| `timeout` | `number` | `60000` | Execution timeout in ms |
|
|
537
539
|
| `globalOutbound` | `Fetcher \| null` | `null` | Network access control. `null` = blocked, `Fetcher` = routed |
|
|
538
540
|
| `modules` | `Record<string, string>` | `{}` | Extra modules importable in the sandbox |
|
|
539
541
|
|
package/dist/ai.d.ts
CHANGED
|
@@ -4,12 +4,12 @@ import {
|
|
|
4
4
|
i as ToolProvider,
|
|
5
5
|
p as generateTypes,
|
|
6
6
|
u as ResolvedProvider
|
|
7
|
-
} from "./executor-
|
|
7
|
+
} from "./executor-DkMGH_7-.js";
|
|
8
8
|
import {
|
|
9
9
|
n as CodeOutput,
|
|
10
10
|
r as CreateCodeToolOptions,
|
|
11
11
|
t as CodeInput
|
|
12
|
-
} from "./shared-
|
|
12
|
+
} from "./shared-BOF2IKt-.js";
|
|
13
13
|
import {
|
|
14
14
|
r as ConnectorTools,
|
|
15
15
|
t as CodemodeConnector
|
package/dist/ai.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-
|
|
2
|
-
import { t as runCode } from "./run-code-
|
|
1
|
+
import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-D_m9tVnI.js";
|
|
2
|
+
import { t as runCode } from "./run-code-Q3Jh6Dcu.js";
|
|
3
3
|
import { n as filterTools } from "./resolve-34dC47Il.js";
|
|
4
|
-
import { t as CodemodeConnector } from "./base-
|
|
4
|
+
import { t as CodemodeConnector } from "./base-BqhlNCSH.js";
|
|
5
5
|
import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-SMjV5yN4.js";
|
|
6
6
|
import { asSchema, tool } from "ai";
|
|
7
7
|
import { z } from "zod";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as generateTypesFromJsonSchema } from "./json-schema-types-
|
|
1
|
+
import { t as generateTypesFromJsonSchema } from "./json-schema-types-D_m9tVnI.js";
|
|
2
2
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
3
3
|
//#region src/connectors/base.ts
|
|
4
4
|
function toolInputSchema(t) {
|
|
@@ -153,4 +153,4 @@ var CodemodeConnector = class extends WorkerEntrypoint {
|
|
|
153
153
|
//#endregion
|
|
154
154
|
export { CodemodeConnector as t };
|
|
155
155
|
|
|
156
|
-
//# sourceMappingURL=base-
|
|
156
|
+
//# sourceMappingURL=base-BqhlNCSH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-CHRR_a5j.js","names":["#toolsPromise"],"sources":["../src/connectors/base.ts"],"sourcesContent":["import { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"../json-schema-types\";\nimport type {\n ConnectorDescription,\n ExecutionEndStatus,\n PassEndStatus,\n ToolAnnotations,\n ToolExecuteContext\n} from \"./types\";\n\n/**\n * A single connector tool — everything about it in one place: docs, schema,\n * approval requirement, execution, and (optionally) how to undo it.\n *\n * AI SDK tools are shape-compatible: a `ToolSet` can be returned from\n * `tools()` directly.\n */\nexport type ConnectorTool = {\n description?: string;\n /** JSON Schema for the tool input. Defaults to an open object. */\n inputSchema?: JSONSchema7;\n outputSchema?: JSONSchema7;\n /** Pause for user approval before executing. Omit to execute immediately. */\n requiresApproval?: boolean;\n /**\n * Replay policy for the durable log. `\"reexecute\"` marks the call ephemeral:\n * its result is never stored durably, and a replay re-executes the call\n * instead of replaying a recorded result. Use it for idempotent reads whose\n * results are large (file contents, directory listings) — they'd otherwise\n * bloat the replay log. Incompatible with `requiresApproval` (an approved\n * side effect must be logged, never re-executed). Defaults to `\"log\"`.\n */\n replay?: \"log\" | \"reexecute\";\n execute: (\n args: unknown,\n ctx?: ToolExecuteContext\n ) => Promise<unknown> | unknown;\n /** Optional compensation for rollback: undo an applied call. */\n revert?: (\n args: unknown,\n result: unknown,\n ctx?: ToolExecuteContext\n ) => Promise<void> | void;\n};\n\nexport type ConnectorTools = Record<string, ConnectorTool>;\n\n// AI SDK v4 tools carry the schema as `parameters`; v5 as `inputSchema`\n// (possibly a zod schema rather than JSON Schema). Use whichever looks like\n// JSON Schema; fall back to an open object.\nfunction toolInputSchema(t: ConnectorTool): JSONSchema7 {\n const loose = t as { inputSchema?: unknown; parameters?: unknown };\n for (const candidate of [loose.inputSchema, loose.parameters]) {\n if (\n candidate &&\n typeof candidate === \"object\" &&\n (\"type\" in candidate || \"properties\" in candidate || \"$ref\" in candidate)\n ) {\n return candidate as JSONSchema7;\n }\n }\n return { type: \"object\" };\n}\n\n/**\n * Base class for codemode connectors.\n *\n * A connector answers three questions: what global name does the model use\n * (`name`), what guidance does the model get (`instructions`), and what tools\n * exist (`tools` — each tool carries its own docs, schema, approval\n * requirement, execution, and optional revert).\n *\n * The RPC surface (`describe`, `executeTool`, `revertAction`,\n * `getTypeScriptTypes`) is wire plumbing derived from the tools record — the\n * proxy tool calls it; connector authors don't implement it.\n */\nexport abstract class CodemodeConnector<\n Env = unknown,\n Props = unknown\n> extends WorkerEntrypoint<Env, Props> {\n /**\n * Connectors are used in-process by the runtime (their `name()`, `describe()`,\n * and `executeTool()` are called directly), so they're constructed with `new`\n * — typically from inside an Agent / Durable Object.\n *\n * Inside a Durable Object `this.ctx` is a `DurableObjectState`, not an\n * `ExecutionContext`. The base `WorkerEntrypoint` constructor only stores it,\n * so we widen the parameter to accept either — pass `this.ctx` directly with\n * no cast:\n *\n * ```ts\n * const github = new GithubConnector(this.ctx, this.env, conn);\n * ```\n */\n constructor(ctx: DurableObjectState | ExecutionContext, env: Env) {\n super(ctx as ExecutionContext, env);\n }\n\n abstract name(): string;\n\n protected instructions(): string | undefined {\n return undefined;\n }\n\n /**\n * The single authoring surface: one record, one entry per tool.\n * Derived connectors (MCP, OpenAPI) generate this for you.\n */\n protected abstract tools(): ConnectorTools | Promise<ConnectorTools>;\n\n /**\n * Decoration hook, called once per tool. Override to adjust tools you\n * didn't author inline — e.g. mark a derived MCP tool as requiring\n * approval, or attach a revert:\n *\n * ```ts\n * protected tool(name: string, t: ConnectorTool): ConnectorTool {\n * if (name === \"create_issue\") {\n * return { ...t, requiresApproval: true };\n * }\n * return t;\n * }\n * ```\n */\n protected tool(_name: string, t: ConnectorTool): ConnectorTool {\n return t;\n }\n\n #toolsPromise?: Promise<ConnectorTools>;\n\n protected resolvedTools(): Promise<ConnectorTools> {\n return (this.#toolsPromise ??= (async () => {\n const tools = await this.tools();\n const out: ConnectorTools = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!t || typeof t !== \"object\") continue;\n out[name] = this.tool(name, t);\n }\n return out;\n })());\n }\n\n // -------------------------------------------------------------------------\n // RPC surface — derived from the tools record, called by the proxy tool.\n // -------------------------------------------------------------------------\n\n async describe(): Promise<ConnectorDescription> {\n const tools = await this.resolvedTools();\n const descriptors: JsonSchemaToolDescriptors = {};\n const annotations: Record<string, ToolAnnotations> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (t.requiresApproval && t.replay === \"reexecute\") {\n // An approved action is a side effect; replaying it by re-executing\n // would re-apply the side effect on every later resume of the run.\n throw new Error(\n `Connector \"${this.name()}\" tool \"${name}\" cannot combine ` +\n `requiresApproval with replay: \"reexecute\" — approved actions ` +\n `must be logged, not re-executed.`\n );\n }\n descriptors[name] = {\n description: t.description,\n inputSchema: toolInputSchema(t),\n outputSchema: t.outputSchema\n };\n if (t.requiresApproval || t.replay === \"reexecute\") {\n annotations[name] = {\n ...(t.requiresApproval ? { requiresApproval: true } : {}),\n ...(t.replay === \"reexecute\" ? { replay: \"reexecute\" as const } : {})\n };\n }\n }\n return {\n name: this.name(),\n instructions: this.instructions(),\n descriptors,\n annotations\n };\n }\n\n async executeTool(\n method: string,\n args: unknown,\n ctx?: ToolExecuteContext\n ): Promise<unknown> {\n const tool = (await this.resolvedTools())[method];\n if (!tool) throw new Error(`Tool \"${method}\" not found on ${this.name()}`);\n // `return await` (not `return`) so a synchronously-rejected promise gets\n // its handler attached in the same tick — workerd otherwise reports a\n // false-positive unhandled rejection during promise adoption.\n return await tool.execute(args, ctx);\n }\n\n /**\n * Revert an applied action. Returns whether a revert actually ran — reads and\n * tools without a `revert` are a no-op and return `false`, so the runtime can\n * mark only the entries it truly reverted.\n */\n async revertAction(\n method: string,\n args: unknown,\n result: unknown,\n ctx?: ToolExecuteContext\n ): Promise<boolean> {\n const tool = (await this.resolvedTools())[method];\n if (!tool?.revert) return false;\n await tool.revert(args, result, ctx);\n return true;\n }\n\n /**\n * Called at the end of every execution *pass* — including a pass that ends\n * in a pause awaiting approval, where `disposeExecution` deliberately does\n * NOT fire. Override to release per-pass resources: an open socket, a lease,\n * an in-memory cache entry. Per-execution resources (e.g. a browser session\n * that must survive the pause for the resume) belong in `disposeExecution`.\n *\n * On a terminal pass, `onPassEnd` fires first, then `disposeExecution`.\n *\n * Contract for implementers: be idempotent, don't rely on instance memory\n * (a resume may run on a fresh instance), and don't throw — the runtime\n * ignores rejections from this hook.\n */\n async onPassEnd(\n _executionId: string,\n _status: PassEndStatus\n ): Promise<void> {}\n\n /**\n * Called once when a codemode execution reaches a terminal state — completed,\n * errored, rejected, or rolled back — and will not resume. Override to tear\n * down any per-execution resource this connector opened for that run, keyed\n * by `executionId` (e.g. close a browser/CDP session).\n *\n * It is deliberately *not* called when a run pauses for approval: a paused\n * run may resume later, possibly in a fresh Worker invocation, so a resource\n * scoped to the whole run must outlive a pause. This hook is the single point\n * where teardown is safe.\n *\n * Contract for implementers:\n * - Be idempotent. It may fire more than once for the same execution (a\n * completed run that is later rolled back) and a no-op is expected the\n * second time.\n * - Don't rely on instance memory. It may run on a different connector\n * instance than the one that opened the resource (the host can reconstruct\n * connectors per request, and the opening pass may have hibernated), so\n * read what you need from durable storage keyed by `executionId`.\n * - Don't throw. Teardown failures must not turn a finished run into a\n * failure; the runtime ignores rejections from this hook.\n *\n * The default is a no-op, so connectors that own no per-execution state\n * don't implement it.\n */\n async disposeExecution(\n _executionId: string,\n _status: ExecutionEndStatus\n ): Promise<void> {}\n\n async getTypeScriptTypes(): Promise<string> {\n const { descriptors } = await this.describe();\n return generateTypesFromJsonSchema(descriptors).replace(\n \"declare const codemode\",\n `declare const ${this.name()}`\n );\n }\n}\n"],"mappings":";;;AAsDA,SAAS,gBAAgB,GAA+B;CACtD,MAAM,QAAQ;CACd,KAAK,MAAM,aAAa,CAAC,MAAM,aAAa,MAAM,UAAU,GAC1D,IACE,aACA,OAAO,cAAc,aACpB,UAAU,aAAa,gBAAgB,aAAa,UAAU,YAE/D,OAAO;CAGX,OAAO,EAAE,MAAM,SAAS;AAC1B;;;;;;;;;;;;;AAcA,IAAsB,oBAAtB,cAGU,iBAA6B;;;;;;;;;;;;;;;CAerC,YAAY,KAA4C,KAAU;EAChE,MAAM,KAAyB,GAAG;CACpC;CAIA,eAA6C,CAE7C;;;;;;;;;;;;;;;CAsBA,KAAe,OAAe,GAAiC;EAC7D,OAAO;CACT;CAEA;CAEA,gBAAmD;EACjD,OAAQ,KAAKA,mBAAmB,YAAY;GAC1C,MAAM,QAAQ,MAAM,KAAK,MAAM;GAC/B,MAAM,MAAsB,CAAC;GAC7B,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,KAAK,GAAG;IAC7C,IAAI,CAAC,KAAK,OAAO,MAAM,UAAU;IACjC,IAAI,QAAQ,KAAK,KAAK,MAAM,CAAC;GAC/B;GACA,OAAO;EACT,EAAA,CAAG;CACL;CAMA,MAAM,WAA0C;EAC9C,MAAM,QAAQ,MAAM,KAAK,cAAc;EACvC,MAAM,cAAyC,CAAC;EAChD,MAAM,cAA+C,CAAC;EACtD,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,KAAK,GAAG;GAC7C,IAAI,EAAE,oBAAoB,EAAE,WAAW,aAGrC,MAAM,IAAI,MACR,cAAc,KAAK,KAAK,EAAE,UAAU,KAAK,+GAG3C;GAEF,YAAY,QAAQ;IAClB,aAAa,EAAE;IACf,aAAa,gBAAgB,CAAC;IAC9B,cAAc,EAAE;GAClB;GACA,IAAI,EAAE,oBAAoB,EAAE,WAAW,aACrC,YAAY,QAAQ;IAClB,GAAI,EAAE,mBAAmB,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACvD,GAAI,EAAE,WAAW,cAAc,EAAE,QAAQ,YAAqB,IAAI,CAAC;GACrE;EAEJ;EACA,OAAO;GACL,MAAM,KAAK,KAAK;GAChB,cAAc,KAAK,aAAa;GAChC;GACA;EACF;CACF;CAEA,MAAM,YACJ,QACA,MACA,KACkB;EAClB,MAAM,QAAQ,MAAM,KAAK,cAAc,EAAA,CAAG;EAC1C,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,SAAS,OAAO,iBAAiB,KAAK,KAAK,GAAG;EAIzE,OAAO,MAAM,KAAK,QAAQ,MAAM,GAAG;CACrC;;;;;;CAOA,MAAM,aACJ,QACA,MACA,QACA,KACkB;EAClB,MAAM,QAAQ,MAAM,KAAK,cAAc,EAAA,CAAG;EAC1C,IAAI,CAAC,MAAM,QAAQ,OAAO;EAC1B,MAAM,KAAK,OAAO,MAAM,QAAQ,GAAG;EACnC,OAAO;CACT;;;;;;;;;;;;;;CAeA,MAAM,UACJ,cACA,SACe,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BlB,MAAM,iBACJ,cACA,SACe,CAAC;CAElB,MAAM,qBAAsC;EAC1C,MAAM,EAAE,gBAAgB,MAAM,KAAK,SAAS;EAC5C,OAAO,4BAA4B,WAAW,CAAC,CAAC,QAC9C,0BACA,iBAAiB,KAAK,KAAK,GAC7B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base-BqhlNCSH.js","names":["#toolsPromise"],"sources":["../src/connectors/base.ts"],"sourcesContent":["import { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"../json-schema-types\";\nimport type {\n ConnectorDescription,\n ExecutionEndStatus,\n PassEndStatus,\n ToolAnnotations,\n ToolExecuteContext\n} from \"./types\";\n\n/**\n * A single connector tool — everything about it in one place: docs, schema,\n * approval requirement, execution, and (optionally) how to undo it.\n *\n * AI SDK tools are shape-compatible: a `ToolSet` can be returned from\n * `tools()` directly.\n */\nexport type ConnectorTool = {\n description?: string;\n /** JSON Schema for the tool input. Defaults to an open object. */\n inputSchema?: JSONSchema7;\n outputSchema?: JSONSchema7;\n /** Pause for user approval before executing. Omit to execute immediately. */\n requiresApproval?: boolean;\n /**\n * Replay policy for the durable log. `\"reexecute\"` marks the call ephemeral:\n * its result is never stored durably, and a replay re-executes the call\n * instead of replaying a recorded result. Use it for idempotent reads whose\n * results are large (file contents, directory listings) — they'd otherwise\n * bloat the replay log. Incompatible with `requiresApproval` (an approved\n * side effect must be logged, never re-executed). Defaults to `\"log\"`.\n */\n replay?: \"log\" | \"reexecute\";\n execute: (\n args: unknown,\n ctx?: ToolExecuteContext\n ) => Promise<unknown> | unknown;\n /** Optional compensation for rollback: undo an applied call. */\n revert?: (\n args: unknown,\n result: unknown,\n ctx?: ToolExecuteContext\n ) => Promise<void> | void;\n};\n\nexport type ConnectorTools = Record<string, ConnectorTool>;\n\n// AI SDK v4 tools carry the schema as `parameters`; v5 as `inputSchema`\n// (possibly a zod schema rather than JSON Schema). Use whichever looks like\n// JSON Schema; fall back to an open object.\nfunction toolInputSchema(t: ConnectorTool): JSONSchema7 {\n const loose = t as { inputSchema?: unknown; parameters?: unknown };\n for (const candidate of [loose.inputSchema, loose.parameters]) {\n if (\n candidate &&\n typeof candidate === \"object\" &&\n (\"type\" in candidate || \"properties\" in candidate || \"$ref\" in candidate)\n ) {\n return candidate as JSONSchema7;\n }\n }\n return { type: \"object\" };\n}\n\n/**\n * Base class for codemode connectors.\n *\n * A connector answers three questions: what global name does the model use\n * (`name`), what guidance does the model get (`instructions`), and what tools\n * exist (`tools` — each tool carries its own docs, schema, approval\n * requirement, execution, and optional revert).\n *\n * The RPC surface (`describe`, `executeTool`, `revertAction`,\n * `getTypeScriptTypes`) is wire plumbing derived from the tools record — the\n * proxy tool calls it; connector authors don't implement it.\n */\nexport abstract class CodemodeConnector<\n Env = unknown,\n Props = unknown\n> extends WorkerEntrypoint<Env, Props> {\n /**\n * Connectors are used in-process by the runtime (their `name()`, `describe()`,\n * and `executeTool()` are called directly), so they're constructed with `new`\n * — typically from inside an Agent / Durable Object.\n *\n * Inside a Durable Object `this.ctx` is a `DurableObjectState`, not an\n * `ExecutionContext`. The base `WorkerEntrypoint` constructor only stores it,\n * so we widen the parameter to accept either — pass `this.ctx` directly with\n * no cast:\n *\n * ```ts\n * const github = new GithubConnector(this.ctx, this.env, conn);\n * ```\n */\n constructor(ctx: DurableObjectState | ExecutionContext, env: Env) {\n super(ctx as ExecutionContext, env);\n }\n\n abstract name(): string;\n\n protected instructions(): string | undefined {\n return undefined;\n }\n\n /**\n * The single authoring surface: one record, one entry per tool.\n * Derived connectors (MCP, OpenAPI) generate this for you.\n */\n protected abstract tools(): ConnectorTools | Promise<ConnectorTools>;\n\n /**\n * Decoration hook, called once per tool. Override to adjust tools you\n * didn't author inline — e.g. mark a derived MCP tool as requiring\n * approval, or attach a revert:\n *\n * ```ts\n * protected tool(name: string, t: ConnectorTool): ConnectorTool {\n * if (name === \"create_issue\") {\n * return { ...t, requiresApproval: true };\n * }\n * return t;\n * }\n * ```\n */\n protected tool(_name: string, t: ConnectorTool): ConnectorTool {\n return t;\n }\n\n #toolsPromise?: Promise<ConnectorTools>;\n\n protected resolvedTools(): Promise<ConnectorTools> {\n return (this.#toolsPromise ??= (async () => {\n const tools = await this.tools();\n const out: ConnectorTools = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!t || typeof t !== \"object\") continue;\n out[name] = this.tool(name, t);\n }\n return out;\n })());\n }\n\n // -------------------------------------------------------------------------\n // RPC surface — derived from the tools record, called by the proxy tool.\n // -------------------------------------------------------------------------\n\n async describe(): Promise<ConnectorDescription> {\n const tools = await this.resolvedTools();\n const descriptors: JsonSchemaToolDescriptors = {};\n const annotations: Record<string, ToolAnnotations> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (t.requiresApproval && t.replay === \"reexecute\") {\n // An approved action is a side effect; replaying it by re-executing\n // would re-apply the side effect on every later resume of the run.\n throw new Error(\n `Connector \"${this.name()}\" tool \"${name}\" cannot combine ` +\n `requiresApproval with replay: \"reexecute\" — approved actions ` +\n `must be logged, not re-executed.`\n );\n }\n descriptors[name] = {\n description: t.description,\n inputSchema: toolInputSchema(t),\n outputSchema: t.outputSchema\n };\n if (t.requiresApproval || t.replay === \"reexecute\") {\n annotations[name] = {\n ...(t.requiresApproval ? { requiresApproval: true } : {}),\n ...(t.replay === \"reexecute\" ? { replay: \"reexecute\" as const } : {})\n };\n }\n }\n return {\n name: this.name(),\n instructions: this.instructions(),\n descriptors,\n annotations\n };\n }\n\n async executeTool(\n method: string,\n args: unknown,\n ctx?: ToolExecuteContext\n ): Promise<unknown> {\n const tool = (await this.resolvedTools())[method];\n if (!tool) throw new Error(`Tool \"${method}\" not found on ${this.name()}`);\n // `return await` (not `return`) so a synchronously-rejected promise gets\n // its handler attached in the same tick — workerd otherwise reports a\n // false-positive unhandled rejection during promise adoption.\n return await tool.execute(args, ctx);\n }\n\n /**\n * Revert an applied action. Returns whether a revert actually ran — reads and\n * tools without a `revert` are a no-op and return `false`, so the runtime can\n * mark only the entries it truly reverted.\n */\n async revertAction(\n method: string,\n args: unknown,\n result: unknown,\n ctx?: ToolExecuteContext\n ): Promise<boolean> {\n const tool = (await this.resolvedTools())[method];\n if (!tool?.revert) return false;\n await tool.revert(args, result, ctx);\n return true;\n }\n\n /**\n * Called at the end of every execution *pass* — including a pass that ends\n * in a pause awaiting approval, where `disposeExecution` deliberately does\n * NOT fire. Override to release per-pass resources: an open socket, a lease,\n * an in-memory cache entry. Per-execution resources (e.g. a browser session\n * that must survive the pause for the resume) belong in `disposeExecution`.\n *\n * On a terminal pass, `onPassEnd` fires first, then `disposeExecution`.\n *\n * Contract for implementers: be idempotent, don't rely on instance memory\n * (a resume may run on a fresh instance), and don't throw — the runtime\n * ignores rejections from this hook.\n */\n async onPassEnd(\n _executionId: string,\n _status: PassEndStatus\n ): Promise<void> {}\n\n /**\n * Called once when a codemode execution reaches a terminal state — completed,\n * errored, rejected, or rolled back — and will not resume. Override to tear\n * down any per-execution resource this connector opened for that run, keyed\n * by `executionId` (e.g. close a browser/CDP session).\n *\n * It is deliberately *not* called when a run pauses for approval: a paused\n * run may resume later, possibly in a fresh Worker invocation, so a resource\n * scoped to the whole run must outlive a pause. This hook is the single point\n * where teardown is safe.\n *\n * Contract for implementers:\n * - Be idempotent. It may fire more than once for the same execution (a\n * completed run that is later rolled back) and a no-op is expected the\n * second time.\n * - Don't rely on instance memory. It may run on a different connector\n * instance than the one that opened the resource (the host can reconstruct\n * connectors per request, and the opening pass may have hibernated), so\n * read what you need from durable storage keyed by `executionId`.\n * - Don't throw. Teardown failures must not turn a finished run into a\n * failure; the runtime ignores rejections from this hook.\n *\n * The default is a no-op, so connectors that own no per-execution state\n * don't implement it.\n */\n async disposeExecution(\n _executionId: string,\n _status: ExecutionEndStatus\n ): Promise<void> {}\n\n async getTypeScriptTypes(): Promise<string> {\n const { descriptors } = await this.describe();\n return generateTypesFromJsonSchema(descriptors).replace(\n \"declare const codemode\",\n `declare const ${this.name()}`\n );\n }\n}\n"],"mappings":";;;AAsDA,SAAS,gBAAgB,GAA+B;CACtD,MAAM,QAAQ;CACd,KAAK,MAAM,aAAa,CAAC,MAAM,aAAa,MAAM,UAAU,GAC1D,IACE,aACA,OAAO,cAAc,aACpB,UAAU,aAAa,gBAAgB,aAAa,UAAU,YAE/D,OAAO;CAGX,OAAO,EAAE,MAAM,SAAS;AAC1B;;;;;;;;;;;;;AAcA,IAAsB,oBAAtB,cAGU,iBAA6B;;;;;;;;;;;;;;;CAerC,YAAY,KAA4C,KAAU;EAChE,MAAM,KAAyB,GAAG;CACpC;CAIA,eAA6C,CA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CAOA,MAAM,aACJ,QACA,MACA,QACA,KACkB;EAClB,MAAM,QAAQ,MAAM,KAAK,cAAc,EAAA,CAAG;EAC1C,IAAI,CAAC,MAAM,QAAQ,OAAO;EAC1B,MAAM,KAAK,OAAO,MAAM,QAAQ,GAAG;EACnC,OAAO;CACT;;;;;;;;;;;;;;CAeA,MAAM,UACJ,cACA,SACe,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BlB,MAAM,iBACJ,cACA,SACe,CAAC;CAElB,MAAM,qBAAsC;EAC1C,MAAM,EAAE,gBAAgB,MAAM,KAAK,SAAS;EAC5C,OAAO,4BAA4B,WAAW,CAAC,CAAC,QAC9C,0BACA,iBAAiB,KAAK,KAAK,GAC7B;CACF;AACF"}
|
package/dist/browser.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import {
|
|
|
2
2
|
c as ExecuteResult,
|
|
3
3
|
l as Executor,
|
|
4
4
|
u as ResolvedProvider
|
|
5
|
-
} from "./executor-
|
|
6
|
-
import { n as CodeOutput, t as CodeInput } from "./shared-
|
|
5
|
+
} from "./executor-DkMGH_7-.js";
|
|
6
|
+
import { n as CodeOutput, t as CodeInput } from "./shared-BOF2IKt-.js";
|
|
7
7
|
import {
|
|
8
8
|
n as JsonSchemaToolDescriptors,
|
|
9
9
|
t as JsonSchemaToolDescriptor
|
package/dist/browser.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-
|
|
2
|
-
import { t as runCode } from "./run-code-
|
|
1
|
+
import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-D_m9tVnI.js";
|
|
2
|
+
import { t as runCode } from "./run-code-Q3Jh6Dcu.js";
|
|
3
3
|
//#region src/messages.ts
|
|
4
4
|
function isRecord(value) {
|
|
5
5
|
return typeof value === "object" && value !== null;
|
|
@@ -198,7 +198,7 @@ function createToolResultMessage(nonce, id, value, isError) {
|
|
|
198
198
|
}
|
|
199
199
|
function createExecutionNonce() {
|
|
200
200
|
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
|
|
201
|
-
const bytes = new Uint8Array(16);
|
|
201
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
202
202
|
globalThis.crypto.getRandomValues(bytes);
|
|
203
203
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
204
204
|
}
|
|
@@ -225,7 +225,7 @@ var IframeSandboxExecutor = class {
|
|
|
225
225
|
fns: providersOrFns
|
|
226
226
|
}];
|
|
227
227
|
} else providers = providersOrFns;
|
|
228
|
-
const reservedNames = new Set(["__dispatchers", "__logs"]);
|
|
228
|
+
const reservedNames = /* @__PURE__ */ new Set(["__dispatchers", "__logs"]);
|
|
229
229
|
const validIdent = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
230
230
|
const seenNames = /* @__PURE__ */ new Set();
|
|
231
231
|
for (const provider of providers) {
|
package/dist/browser.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser.js","names":["#timeout","#csp"],"sources":["../src/messages.ts","../src/iframe-runtime.ts","../src/iframe-executor.ts","../src/browser-tool.ts"],"sourcesContent":["/**\n * Typed postMessage protocol for host ↔ iframe sandbox communication.\n *\n * Messages flow in two directions:\n * - Sandbox → Host: tool calls and execution results\n * - Host → Sandbox: tool results and execute requests\n */\n\nimport type { ExecuteResult } from \"./executor-types\";\n\n// -- Helpers --\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n// -- Sandbox → Host messages --\n\nexport interface ToolCallMessage {\n type: \"tool-call\";\n nonce: string;\n id: number;\n provider: string;\n name: string;\n args: unknown;\n}\n\nexport interface ExecutionResultMessage {\n type: \"execution-result\";\n nonce: string;\n result: ExecuteResult;\n}\n\nexport interface SandboxReadyMessage {\n type: \"sandbox-ready\";\n}\n\n// -- Host → Sandbox messages --\n\nexport interface ToolResultSuccessMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result: unknown;\n}\n\nexport interface ToolResultErrorMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n error: string;\n}\n\nexport interface ExecuteRequestMessage {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string }[];\n}\n\n// -- Type guards --\n\nexport function isSandboxReadyMessage(\n data: unknown\n): data is SandboxReadyMessage {\n return isRecord(data) && data.type === \"sandbox-ready\";\n}\n\nexport function isToolCallMessage(data: unknown): data is ToolCallMessage {\n return (\n isRecord(data) &&\n data.type === \"tool-call\" &&\n typeof data.nonce === \"string\" &&\n typeof data.id === \"number\" &&\n typeof data.provider === \"string\" &&\n typeof data.name === \"string\"\n );\n}\n\nexport function isExecutionResultMessage(\n data: unknown\n): data is ExecutionResultMessage {\n if (!isRecord(data)) return false;\n if (data.type !== \"execution-result\") return false;\n if (typeof data.nonce !== \"string\") return false;\n if (typeof data.result !== \"object\" || data.result === null) return false;\n return true;\n}\n\nexport function isExecuteRequestMessageShape(\n data: unknown\n): data is ExecuteRequestMessage {\n return (\n isRecord(data) &&\n data.type === \"execute-request\" &&\n typeof data.nonce === \"string\" &&\n typeof data.code === \"string\" &&\n Array.isArray(data.providers) &&\n data.providers.every(\n (provider) => isRecord(provider) && typeof provider.name === \"string\"\n )\n );\n}\n","/**\n * Self-contained runtime that boots inside the sandboxed iframe.\n *\n * The `iframeSandboxRuntimeMain` function is serialized via `.toString()`\n * and injected into the iframe's `srcdoc`. It MUST be fully self-contained —\n * no closures over module-level variables, no imported values at runtime.\n * (Type-only imports are safe because they are erased at compile time.)\n */\n\n/**\n * The iframe-side runtime entry point.\n *\n * This function is stringified and injected into the iframe via srcdoc.\n * Everything it needs must be defined inside its own scope.\n */\nfunction iframeSandboxRuntimeMain(): void {\n const runtimeWindow = window as Window &\n typeof globalThis & { __codemodeIframeInitialized?: boolean };\n\n if (runtimeWindow.__codemodeIframeInitialized) {\n return;\n }\n\n runtimeWindow.__codemodeIframeInitialized = true;\n\n const logs: string[] = [];\n const pending: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n > = {};\n let nextId = 0;\n let activeNonce: string | undefined;\n\n function post(message: unknown) {\n parent.postMessage(message, \"*\");\n }\n\n // Capture console output\n console.log = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(values.join(\" \"));\n };\n console.warn = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[warn] \" + values.join(\" \"));\n };\n console.error = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[error] \" + values.join(\" \"));\n };\n\n function createProviderProxy(nonce: string, provider: { name: string }) {\n return new Proxy(\n {},\n {\n get:\n (_, toolName) =>\n (...args: unknown[]) => {\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending[id] = { resolve, reject };\n post({\n type: \"tool-call\",\n nonce,\n id,\n provider: provider.name,\n name: String(toolName),\n args\n });\n });\n }\n }\n );\n }\n\n function isToolResultMessage(message: unknown): message is {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result?: unknown;\n error?: string;\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"tool-result\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.id === \"number\"\n );\n }\n\n function isExecuteRequestMessage(message: unknown): message is {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string }[];\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"execute-request\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.code === \"string\" &&\n Array.isArray(candidate.providers) &&\n candidate.providers.every(\n (provider) =>\n typeof provider === \"object\" &&\n provider !== null &&\n typeof (provider as { name?: unknown }).name === \"string\"\n )\n );\n }\n\n function executeCode(\n nonce: string,\n code: string,\n providers: { name: string }[]\n ) {\n try {\n activeNonce = nonce;\n const providerNames: string[] = [];\n const providerProxies: unknown[] = [];\n for (const provider of providers) {\n providerNames.push(provider.name);\n providerProxies.push(createProviderProxy(nonce, provider));\n }\n\n const fn = new Function(...providerNames, \"return (\" + code + \")\")(\n ...providerProxies\n );\n Promise.resolve(fn())\n .then((result: unknown) => {\n post({ type: \"execution-result\", nonce, result: { result, logs } });\n })\n .catch((err: Error) => {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err.message || String(err),\n logs\n }\n });\n });\n } catch (err) {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err instanceof Error ? err.message : String(err),\n logs\n }\n });\n }\n }\n\n window.addEventListener(\"message\", (event) => {\n if (event.source !== parent) return;\n\n const message = event.data;\n\n if (isToolResultMessage(message)) {\n if (message.nonce !== activeNonce) return;\n const request = pending[message.id];\n if (!request) return;\n\n delete pending[message.id];\n if (\"error\" in message)\n request.reject(new Error(message.error as string));\n else request.resolve(message.result);\n return;\n }\n\n if (isExecuteRequestMessage(message)) {\n executeCode(message.nonce, message.code, message.providers);\n }\n });\n\n post({ type: \"sandbox-ready\" });\n}\n\n/**\n * Returns a self-contained script string that boots the codemode iframe runtime.\n */\nexport function createIframeSandboxRuntimeScript(): string {\n return `;(${iframeSandboxRuntimeMain.toString()})();`;\n}\n","/**\n * IframeSandboxExecutor — a browser-native Executor that runs LLM-generated\n * code in a sandboxed iframe using postMessage for tool dispatch.\n *\n * Zero dependencies — uses only browser APIs (iframe, postMessage, CSP).\n */\n\nimport {\n type ExecuteRequestMessage,\n isExecutionResultMessage,\n isSandboxReadyMessage,\n isToolCallMessage,\n type ToolResultErrorMessage,\n type ToolResultSuccessMessage\n} from \"./messages\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { createIframeSandboxRuntimeScript } from \"./iframe-runtime\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\n\nexport interface IframeSandboxExecutorOptions {\n /** Maximum execution time in milliseconds. Defaults to `30000`. */\n timeout?: number;\n /**\n * Content Security Policy applied to the iframe document.\n *\n * When omitted, defaults to a restrictive policy that only allows\n * inline scripts and eval (needed for code execution).\n */\n csp?: string;\n}\n\nconst DEFAULT_CSP =\n \"default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval';\";\nconst DEFAULT_TIMEOUT = 30000;\n\nfunction escapeHtmlAttribute(value: string): string {\n return value.replace(/&/g, \"&\").replace(/\"/g, \""\");\n}\n\nfunction escapeInlineScript(value: string): string {\n return value.replace(/<\\/script/gi, \"<\\\\/script\");\n}\n\nfunction buildSrcdoc(csp: string): string {\n const runtimeScript = escapeInlineScript(createIframeSandboxRuntimeScript());\n const safeCsp = escapeHtmlAttribute(csp);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content=\"${safeCsp}\">\n</head>\n<body>\n<script>\n${runtimeScript}\n</script>\n</body>\n</html>`;\n}\n\nfunction createToolResultMessage(\n nonce: string,\n id: number,\n value: unknown,\n isError: boolean\n): ToolResultSuccessMessage | ToolResultErrorMessage {\n if (isError) {\n return {\n type: \"tool-result\",\n nonce,\n id,\n error: value instanceof Error ? value.message : String(value)\n };\n }\n return { type: \"tool-result\", nonce, id, result: value };\n}\n\nfunction createExecutionNonce(): string {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\"\n );\n}\n\n/**\n * Executes LLM-generated code in a browser iframe sandbox.\n *\n * For each execution, a hidden iframe is created with `sandbox=\"allow-scripts\"`,\n * the runtime is injected via `srcdoc`, and the iframe is removed after completion.\n * Tool calls are dispatched via `postMessage`.\n */\nexport class IframeSandboxExecutor implements Executor {\n #timeout: number;\n #csp: string;\n\n constructor(options?: IframeSandboxExecutorOptions) {\n this.#timeout = options?.timeout ?? DEFAULT_TIMEOUT;\n this.#csp = options?.csp ?? DEFAULT_CSP;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\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 reservedNames = new Set([\"__dispatchers\", \"__logs\"]);\n const validIdent = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (reservedNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!validIdent.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 const normalizedCode = normalizeCode(code);\n const resolvedProviders: ResolvedProvider[] = [];\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 resolvedProviders.push({\n name: provider.name,\n fns: sanitizedFns\n });\n }\n const providerMap = new Map(\n resolvedProviders.map((provider) => [provider.name, provider] as const)\n );\n const nonce = createExecutionNonce();\n\n const executeRequest: ExecuteRequestMessage = {\n type: \"execute-request\",\n nonce,\n code: normalizedCode,\n providers: resolvedProviders.map((provider) => ({ name: provider.name }))\n };\n\n const invokeProviderTool = async (\n provider: ResolvedProvider,\n args: unknown,\n name: string\n ) => {\n const fn = provider.fns[name];\n if (!fn) {\n throw new Error(`Tool \"${name}\" not found`);\n }\n const positionalArgs = Array.isArray(args) ? args : [args];\n return fn(...positionalArgs);\n };\n\n const iframe = document.createElement(\"iframe\");\n iframe.sandbox.add(\"allow-scripts\");\n iframe.style.display = \"none\";\n iframe.style.width = \"0\";\n iframe.style.height = \"0\";\n iframe.style.border = \"none\";\n iframe.srcdoc = buildSrcdoc(this.#csp);\n\n return new Promise<ExecuteResult>((resolve) => {\n let settled = false;\n let ready = false;\n const warnedInvalidNonceTypes = new Set<string>();\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n window.removeEventListener(\"message\", handler);\n iframe.removeEventListener(\"error\", handleLoadError);\n iframe.remove();\n };\n\n const resolveError = (message: string) => {\n cleanup();\n resolve({ result: undefined, error: message, logs: [] });\n };\n\n const postToChild = (\n message:\n | ToolResultSuccessMessage\n | ToolResultErrorMessage\n | ExecuteRequestMessage\n ): boolean => {\n const child = iframe.contentWindow;\n if (!child) {\n resolveError(\"Sandbox iframe is not available\");\n return false;\n }\n\n try {\n child.postMessage(message, \"*\");\n return true;\n } catch (err) {\n resolveError(err instanceof Error ? err.message : String(err));\n return false;\n }\n };\n\n const warnInvalidNonce = (messageType: string) => {\n if (warnedInvalidNonceTypes.has(messageType)) return;\n warnedInvalidNonceTypes.add(messageType);\n console.warn(\n `[@cloudflare/codemode] Ignoring sandbox ${messageType} message with invalid execution nonce`\n );\n };\n\n const handler = async (event: MessageEvent) => {\n if (event.source !== iframe.contentWindow) return;\n\n const data: unknown = event.data;\n\n if (isSandboxReadyMessage(data)) {\n if (ready) return;\n ready = true;\n postToChild(executeRequest);\n return;\n }\n\n if (isToolCallMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"tool-call\");\n return;\n }\n const provider = providerMap.get(data.provider);\n if (!provider) {\n postToChild(\n createToolResultMessage(\n nonce,\n data.id,\n `Provider \"${data.provider}\" not found`,\n true\n )\n );\n return;\n }\n try {\n const result = await invokeProviderTool(\n provider,\n data.args,\n data.name\n );\n postToChild(createToolResultMessage(nonce, data.id, result, false));\n } catch (err) {\n postToChild(createToolResultMessage(nonce, data.id, err, true));\n }\n return;\n }\n\n if (isExecutionResultMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"execution-result\");\n return;\n }\n cleanup();\n resolve(data.result);\n }\n };\n\n const handleLoadError = () => {\n resolveError(\"Sandbox iframe failed to load\");\n };\n\n window.addEventListener(\"message\", handler);\n iframe.addEventListener(\"error\", handleLoadError);\n\n const timer = setTimeout(() => {\n cleanup();\n resolve({ result: undefined, error: \"Execution timed out\", logs: [] });\n }, this.#timeout);\n\n document.body.appendChild(iframe);\n });\n }\n}\n","/**\n * Zero-dependency browser counterpart to `createCodeTool` from `./ai`.\n *\n * Returns a plain JSON Schema tool descriptor instead of an AI SDK `Tool`.\n * No `ai`, no `zod` — just JSON Schema and browser APIs. JSON Schema is used\n * for generated types only; this helper does not perform runtime validation.\n */\n\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptor,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { runCode } from \"./run-code\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor, ResolvedProvider } from \"./executor-types\";\nimport type { CodeInput, CodeOutput } from \"./shared\";\nimport { IframeSandboxExecutor } from \"./iframe-executor\";\n\n// -- Types --\n\n/**\n * A JSON Schema tool descriptor with an execute function attached.\n */\nexport interface JsonSchemaExecutableToolDescriptor extends JsonSchemaToolDescriptor {\n name?: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type JsonSchemaExecutableToolDescriptors = Record<\n string,\n JsonSchemaExecutableToolDescriptor\n>;\n\ninterface ApprovalAwareJsonSchemaExecutableToolDescriptor extends JsonSchemaExecutableToolDescriptor {\n needsApproval?: boolean | ((...args: unknown[]) => unknown);\n}\n\ntype ApprovalAwareJsonSchemaExecutableToolDescriptors = Record<\n string,\n ApprovalAwareJsonSchemaExecutableToolDescriptor\n>;\n\nexport interface BrowserCodeToolDescriptor {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: {\n code: { type: \"string\"; description: string };\n };\n required: [\"code\"];\n };\n outputSchema: {\n type: \"object\";\n properties: {\n result: { description: string };\n logs: {\n type: \"array\";\n items: { type: \"string\" };\n description: string;\n };\n };\n required: [\"result\"];\n };\n execute: (args: CodeInput) => Promise<CodeOutput>;\n}\n\nexport interface CreateBrowserCodeToolOptions {\n /**\n * Tools available inside the sandbox via `codemode.*`.\n *\n * Accepts either an array (like `listTools()` returns) with `name` on each item,\n * or an object keyed by tool name (like `createCodeTool` expects).\n */\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors;\n /**\n * Executor to use. Defaults to a new `IframeSandboxExecutor`.\n */\n executor?: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for generated type definitions.\n */\n description?: string;\n}\n\n// -- Implementation --\n\nconst DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nfunction toRecord(\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors\n): ApprovalAwareJsonSchemaExecutableToolDescriptors {\n if (!Array.isArray(tools)) return tools;\n\n const record: ApprovalAwareJsonSchemaExecutableToolDescriptors = {};\n for (const tool of tools) {\n if (!tool.name) {\n throw new Error(\n \"Tool descriptors in array form must have a `name` property\"\n );\n }\n record[tool.name] = tool;\n }\n return record;\n}\n\nfunction hasNeedsApproval(tool: Record<string, unknown>): boolean {\n return (\n tool.needsApproval === true || typeof tool.needsApproval === \"function\"\n );\n}\n\n/**\n * Create a codemode tool descriptor using only JSON Schema and browser APIs.\n *\n * This is the browser counterpart to `createCodeTool` from\n * `@cloudflare/codemode/ai`.\n * It returns a plain object with `{ name, description, inputSchema, outputSchema, execute }`\n * that can be passed to any framework — including\n * `navigator.modelContext.registerTool()`.\n *\n * Tools with `needsApproval` are excluded, matching the current codemode\n * behavior for approval-gated tools. JSON Schema is used for prompt/type\n * generation only and is not enforced at runtime.\n */\nexport function createBrowserCodeTool(\n options: CreateBrowserCodeToolOptions\n): BrowserCodeToolDescriptor {\n const allTools = toRecord(options.tools);\n const toolMap: JsonSchemaExecutableToolDescriptors = {};\n for (const [name, tool] of Object.entries(allTools)) {\n if (!hasNeedsApproval(tool as unknown as Record<string, unknown>)) {\n toolMap[name] = tool;\n }\n }\n const executor = options.executor ?? new IframeSandboxExecutor();\n\n // Generate TypeScript type descriptions for the LLM prompt\n const schemaOnly: JsonSchemaToolDescriptors = {};\n for (const [name, tool] of Object.entries(toolMap)) {\n schemaOnly[name] = {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema\n };\n }\n const types = generateTypesFromJsonSchema(schemaOnly);\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n // Extract execute functions, keyed by sanitized name\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, tool] of Object.entries(toolMap)) {\n if (tool.execute) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n throw new Error(\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to \"${sanitizedName}\"`\n );\n }\n sanitizedNames.set(sanitizedName, name);\n fns[sanitizedName] = tool.execute as (args: unknown) => Promise<unknown>;\n }\n }\n const resolvedProviders: ResolvedProvider[] = [{ name: \"codemode\", fns }];\n\n return {\n name: \"codemode\",\n description,\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"JavaScript async arrow function to execute\"\n }\n },\n required: [\"code\"]\n },\n outputSchema: {\n type: \"object\",\n properties: {\n result: {\n description: \"The return value of the executed code\"\n },\n logs: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Console output captured during execution\"\n }\n },\n required: [\"result\"]\n },\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n };\n}\n"],"mappings":";;;AAYA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAgDA,SAAgB,sBACd,MAC6B;CAC7B,OAAO,SAAS,IAAI,KAAK,KAAK,SAAS;AACzC;AAEA,SAAgB,kBAAkB,MAAwC;CACxE,OACE,SAAS,IAAI,KACb,KAAK,SAAS,eACd,OAAO,KAAK,UAAU,YACtB,OAAO,KAAK,OAAO,YACnB,OAAO,KAAK,aAAa,YACzB,OAAO,KAAK,SAAS;AAEzB;AAEA,SAAgB,yBACd,MACgC;CAChC,IAAI,CAAC,SAAS,IAAI,GAAG,OAAO;CAC5B,IAAI,KAAK,SAAS,oBAAoB,OAAO;CAC7C,IAAI,OAAO,KAAK,UAAU,UAAU,OAAO;CAC3C,IAAI,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW,MAAM,OAAO;CACpE,OAAO;AACT;;;;;;;;;;;;;;;;;ACxEA,SAAS,2BAAiC;CACxC,MAAM,gBAAgB;CAGtB,IAAI,cAAc,6BAChB;CAGF,cAAc,8BAA8B;CAE5C,MAAM,OAAiB,CAAC;CACxB,MAAM,UAGF,CAAC;CACL,IAAI,SAAS;CACb,IAAI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S,KAAK,sBAAsB,cAAc,EAChF;EAEF,eAAe,IAAI,eAAe,IAAI;EACtC,IAAI,iBAAiB,KAAK;CAC5B;CAEF,MAAM,oBAAwC,CAAC;EAAE,MAAM;EAAY;CAAI,CAAC;CAExE,OAAO;EACL,MAAM;EACN;EACA,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACf,EACF;GACA,UAAU,CAAC,MAAM;EACnB;EACA,cAAc;GACZ,MAAM;GACN,YAAY;IACV,QAAQ,EACN,aAAa,wCACf;IACA,MAAM;KACJ,MAAM;KACN,OAAO,EAAE,MAAM,SAAS;KACxB,aAAa;IACf;GACF;GACA,UAAU,CAAC,QAAQ;EACrB;EACA,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;EAAkB,CAAC;CAC5D;AACF"}
|
|
1
|
+
{"version":3,"file":"browser.js","names":["#timeout","#csp"],"sources":["../src/messages.ts","../src/iframe-runtime.ts","../src/iframe-executor.ts","../src/browser-tool.ts"],"sourcesContent":["/**\n * Typed postMessage protocol for host ↔ iframe sandbox communication.\n *\n * Messages flow in two directions:\n * - Sandbox → Host: tool calls and execution results\n * - Host → Sandbox: tool results and execute requests\n */\n\nimport type { ExecuteResult } from \"./executor-types\";\n\n// -- Helpers --\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n// -- Sandbox → Host messages --\n\nexport interface ToolCallMessage {\n type: \"tool-call\";\n nonce: string;\n id: number;\n provider: string;\n name: string;\n args: unknown;\n}\n\nexport interface ExecutionResultMessage {\n type: \"execution-result\";\n nonce: string;\n result: ExecuteResult;\n}\n\nexport interface SandboxReadyMessage {\n type: \"sandbox-ready\";\n}\n\n// -- Host → Sandbox messages --\n\nexport interface ToolResultSuccessMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result: unknown;\n}\n\nexport interface ToolResultErrorMessage {\n type: \"tool-result\";\n nonce: string;\n id: number;\n error: string;\n}\n\nexport interface ExecuteRequestMessage {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string }[];\n}\n\n// -- Type guards --\n\nexport function isSandboxReadyMessage(\n data: unknown\n): data is SandboxReadyMessage {\n return isRecord(data) && data.type === \"sandbox-ready\";\n}\n\nexport function isToolCallMessage(data: unknown): data is ToolCallMessage {\n return (\n isRecord(data) &&\n data.type === \"tool-call\" &&\n typeof data.nonce === \"string\" &&\n typeof data.id === \"number\" &&\n typeof data.provider === \"string\" &&\n typeof data.name === \"string\"\n );\n}\n\nexport function isExecutionResultMessage(\n data: unknown\n): data is ExecutionResultMessage {\n if (!isRecord(data)) return false;\n if (data.type !== \"execution-result\") return false;\n if (typeof data.nonce !== \"string\") return false;\n if (typeof data.result !== \"object\" || data.result === null) return false;\n return true;\n}\n\nexport function isExecuteRequestMessageShape(\n data: unknown\n): data is ExecuteRequestMessage {\n return (\n isRecord(data) &&\n data.type === \"execute-request\" &&\n typeof data.nonce === \"string\" &&\n typeof data.code === \"string\" &&\n Array.isArray(data.providers) &&\n data.providers.every(\n (provider) => isRecord(provider) && typeof provider.name === \"string\"\n )\n );\n}\n","/**\n * Self-contained runtime that boots inside the sandboxed iframe.\n *\n * The `iframeSandboxRuntimeMain` function is serialized via `.toString()`\n * and injected into the iframe's `srcdoc`. It MUST be fully self-contained —\n * no closures over module-level variables, no imported values at runtime.\n * (Type-only imports are safe because they are erased at compile time.)\n */\n\n/**\n * The iframe-side runtime entry point.\n *\n * This function is stringified and injected into the iframe via srcdoc.\n * Everything it needs must be defined inside its own scope.\n */\nfunction iframeSandboxRuntimeMain(): void {\n const runtimeWindow = window as Window &\n typeof globalThis & { __codemodeIframeInitialized?: boolean };\n\n if (runtimeWindow.__codemodeIframeInitialized) {\n return;\n }\n\n runtimeWindow.__codemodeIframeInitialized = true;\n\n const logs: string[] = [];\n const pending: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n > = {};\n let nextId = 0;\n let activeNonce: string | undefined;\n\n function post(message: unknown) {\n parent.postMessage(message, \"*\");\n }\n\n // Capture console output\n console.log = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(values.join(\" \"));\n };\n console.warn = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[warn] \" + values.join(\" \"));\n };\n console.error = (...args: unknown[]) => {\n const values = [];\n for (let i = 0; i < args.length; i++) values.push(String(args[i]));\n logs.push(\"[error] \" + values.join(\" \"));\n };\n\n function createProviderProxy(nonce: string, provider: { name: string }) {\n return new Proxy(\n {},\n {\n get:\n (_, toolName) =>\n (...args: unknown[]) => {\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending[id] = { resolve, reject };\n post({\n type: \"tool-call\",\n nonce,\n id,\n provider: provider.name,\n name: String(toolName),\n args\n });\n });\n }\n }\n );\n }\n\n function isToolResultMessage(message: unknown): message is {\n type: \"tool-result\";\n nonce: string;\n id: number;\n result?: unknown;\n error?: string;\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"tool-result\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.id === \"number\"\n );\n }\n\n function isExecuteRequestMessage(message: unknown): message is {\n type: \"execute-request\";\n nonce: string;\n code: string;\n providers: { name: string }[];\n } {\n if (typeof message !== \"object\" || message === null) return false;\n const candidate = message as Record<string, unknown>;\n return (\n candidate.type === \"execute-request\" &&\n typeof candidate.nonce === \"string\" &&\n typeof candidate.code === \"string\" &&\n Array.isArray(candidate.providers) &&\n candidate.providers.every(\n (provider) =>\n typeof provider === \"object\" &&\n provider !== null &&\n typeof (provider as { name?: unknown }).name === \"string\"\n )\n );\n }\n\n function executeCode(\n nonce: string,\n code: string,\n providers: { name: string }[]\n ) {\n try {\n activeNonce = nonce;\n const providerNames: string[] = [];\n const providerProxies: unknown[] = [];\n for (const provider of providers) {\n providerNames.push(provider.name);\n providerProxies.push(createProviderProxy(nonce, provider));\n }\n\n const fn = new Function(...providerNames, \"return (\" + code + \")\")(\n ...providerProxies\n );\n Promise.resolve(fn())\n .then((result: unknown) => {\n post({ type: \"execution-result\", nonce, result: { result, logs } });\n })\n .catch((err: Error) => {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err.message || String(err),\n logs\n }\n });\n });\n } catch (err) {\n post({\n type: \"execution-result\",\n nonce,\n result: {\n result: undefined,\n error: err instanceof Error ? err.message : String(err),\n logs\n }\n });\n }\n }\n\n window.addEventListener(\"message\", (event) => {\n if (event.source !== parent) return;\n\n const message = event.data;\n\n if (isToolResultMessage(message)) {\n if (message.nonce !== activeNonce) return;\n const request = pending[message.id];\n if (!request) return;\n\n delete pending[message.id];\n if (\"error\" in message)\n request.reject(new Error(message.error as string));\n else request.resolve(message.result);\n return;\n }\n\n if (isExecuteRequestMessage(message)) {\n executeCode(message.nonce, message.code, message.providers);\n }\n });\n\n post({ type: \"sandbox-ready\" });\n}\n\n/**\n * Returns a self-contained script string that boots the codemode iframe runtime.\n */\nexport function createIframeSandboxRuntimeScript(): string {\n return `;(${iframeSandboxRuntimeMain.toString()})();`;\n}\n","/**\n * IframeSandboxExecutor — a browser-native Executor that runs LLM-generated\n * code in a sandboxed iframe using postMessage for tool dispatch.\n *\n * Zero dependencies — uses only browser APIs (iframe, postMessage, CSP).\n */\n\nimport {\n type ExecuteRequestMessage,\n isExecutionResultMessage,\n isSandboxReadyMessage,\n isToolCallMessage,\n type ToolResultErrorMessage,\n type ToolResultSuccessMessage\n} from \"./messages\";\nimport type {\n ExecuteResult,\n Executor,\n ResolvedProvider\n} from \"./executor-types\";\nimport { createIframeSandboxRuntimeScript } from \"./iframe-runtime\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\n\nexport interface IframeSandboxExecutorOptions {\n /** Maximum execution time in milliseconds. Defaults to `30000`. */\n timeout?: number;\n /**\n * Content Security Policy applied to the iframe document.\n *\n * When omitted, defaults to a restrictive policy that only allows\n * inline scripts and eval (needed for code execution).\n */\n csp?: string;\n}\n\nconst DEFAULT_CSP =\n \"default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval';\";\nconst DEFAULT_TIMEOUT = 30000;\n\nfunction escapeHtmlAttribute(value: string): string {\n return value.replace(/&/g, \"&\").replace(/\"/g, \""\");\n}\n\nfunction escapeInlineScript(value: string): string {\n return value.replace(/<\\/script/gi, \"<\\\\/script\");\n}\n\nfunction buildSrcdoc(csp: string): string {\n const runtimeScript = escapeInlineScript(createIframeSandboxRuntimeScript());\n const safeCsp = escapeHtmlAttribute(csp);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content=\"${safeCsp}\">\n</head>\n<body>\n<script>\n${runtimeScript}\n</script>\n</body>\n</html>`;\n}\n\nfunction createToolResultMessage(\n nonce: string,\n id: number,\n value: unknown,\n isError: boolean\n): ToolResultSuccessMessage | ToolResultErrorMessage {\n if (isError) {\n return {\n type: \"tool-result\",\n nonce,\n id,\n error: value instanceof Error ? value.message : String(value)\n };\n }\n return { type: \"tool-result\", nonce, id, result: value };\n}\n\nfunction createExecutionNonce(): string {\n if (globalThis.crypto?.randomUUID) {\n return globalThis.crypto.randomUUID();\n }\n\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\"\n );\n}\n\n/**\n * Executes LLM-generated code in a browser iframe sandbox.\n *\n * For each execution, a hidden iframe is created with `sandbox=\"allow-scripts\"`,\n * the runtime is injected via `srcdoc`, and the iframe is removed after completion.\n * Tool calls are dispatched via `postMessage`.\n */\nexport class IframeSandboxExecutor implements Executor {\n #timeout: number;\n #csp: string;\n\n constructor(options?: IframeSandboxExecutorOptions) {\n this.#timeout = options?.timeout ?? DEFAULT_TIMEOUT;\n this.#csp = options?.csp ?? DEFAULT_CSP;\n }\n\n async execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\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 reservedNames = new Set([\"__dispatchers\", \"__logs\"]);\n const validIdent = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (reservedNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!validIdent.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 const normalizedCode = normalizeCode(code);\n const resolvedProviders: ResolvedProvider[] = [];\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 resolvedProviders.push({\n name: provider.name,\n fns: sanitizedFns\n });\n }\n const providerMap = new Map(\n resolvedProviders.map((provider) => [provider.name, provider] as const)\n );\n const nonce = createExecutionNonce();\n\n const executeRequest: ExecuteRequestMessage = {\n type: \"execute-request\",\n nonce,\n code: normalizedCode,\n providers: resolvedProviders.map((provider) => ({ name: provider.name }))\n };\n\n const invokeProviderTool = async (\n provider: ResolvedProvider,\n args: unknown,\n name: string\n ) => {\n const fn = provider.fns[name];\n if (!fn) {\n throw new Error(`Tool \"${name}\" not found`);\n }\n const positionalArgs = Array.isArray(args) ? args : [args];\n return fn(...positionalArgs);\n };\n\n const iframe = document.createElement(\"iframe\");\n iframe.sandbox.add(\"allow-scripts\");\n iframe.style.display = \"none\";\n iframe.style.width = \"0\";\n iframe.style.height = \"0\";\n iframe.style.border = \"none\";\n iframe.srcdoc = buildSrcdoc(this.#csp);\n\n return new Promise<ExecuteResult>((resolve) => {\n let settled = false;\n let ready = false;\n const warnedInvalidNonceTypes = new Set<string>();\n\n const cleanup = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n window.removeEventListener(\"message\", handler);\n iframe.removeEventListener(\"error\", handleLoadError);\n iframe.remove();\n };\n\n const resolveError = (message: string) => {\n cleanup();\n resolve({ result: undefined, error: message, logs: [] });\n };\n\n const postToChild = (\n message:\n | ToolResultSuccessMessage\n | ToolResultErrorMessage\n | ExecuteRequestMessage\n ): boolean => {\n const child = iframe.contentWindow;\n if (!child) {\n resolveError(\"Sandbox iframe is not available\");\n return false;\n }\n\n try {\n child.postMessage(message, \"*\");\n return true;\n } catch (err) {\n resolveError(err instanceof Error ? err.message : String(err));\n return false;\n }\n };\n\n const warnInvalidNonce = (messageType: string) => {\n if (warnedInvalidNonceTypes.has(messageType)) return;\n warnedInvalidNonceTypes.add(messageType);\n console.warn(\n `[@cloudflare/codemode] Ignoring sandbox ${messageType} message with invalid execution nonce`\n );\n };\n\n const handler = async (event: MessageEvent) => {\n if (event.source !== iframe.contentWindow) return;\n\n const data: unknown = event.data;\n\n if (isSandboxReadyMessage(data)) {\n if (ready) return;\n ready = true;\n postToChild(executeRequest);\n return;\n }\n\n if (isToolCallMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"tool-call\");\n return;\n }\n const provider = providerMap.get(data.provider);\n if (!provider) {\n postToChild(\n createToolResultMessage(\n nonce,\n data.id,\n `Provider \"${data.provider}\" not found`,\n true\n )\n );\n return;\n }\n try {\n const result = await invokeProviderTool(\n provider,\n data.args,\n data.name\n );\n postToChild(createToolResultMessage(nonce, data.id, result, false));\n } catch (err) {\n postToChild(createToolResultMessage(nonce, data.id, err, true));\n }\n return;\n }\n\n if (isExecutionResultMessage(data)) {\n if (data.nonce !== nonce) {\n warnInvalidNonce(\"execution-result\");\n return;\n }\n cleanup();\n resolve(data.result);\n }\n };\n\n const handleLoadError = () => {\n resolveError(\"Sandbox iframe failed to load\");\n };\n\n window.addEventListener(\"message\", handler);\n iframe.addEventListener(\"error\", handleLoadError);\n\n const timer = setTimeout(() => {\n cleanup();\n resolve({ result: undefined, error: \"Execution timed out\", logs: [] });\n }, this.#timeout);\n\n document.body.appendChild(iframe);\n });\n }\n}\n","/**\n * Zero-dependency browser counterpart to `createCodeTool` from `./ai`.\n *\n * Returns a plain JSON Schema tool descriptor instead of an AI SDK `Tool`.\n * No `ai`, no `zod` — just JSON Schema and browser APIs. JSON Schema is used\n * for generated types only; this helper does not perform runtime validation.\n */\n\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptor,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { runCode } from \"./run-code\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor, ResolvedProvider } from \"./executor-types\";\nimport type { CodeInput, CodeOutput } from \"./shared\";\nimport { IframeSandboxExecutor } from \"./iframe-executor\";\n\n// -- Types --\n\n/**\n * A JSON Schema tool descriptor with an execute function attached.\n */\nexport interface JsonSchemaExecutableToolDescriptor extends JsonSchemaToolDescriptor {\n name?: string;\n execute: (args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport type JsonSchemaExecutableToolDescriptors = Record<\n string,\n JsonSchemaExecutableToolDescriptor\n>;\n\ninterface ApprovalAwareJsonSchemaExecutableToolDescriptor extends JsonSchemaExecutableToolDescriptor {\n needsApproval?: boolean | ((...args: unknown[]) => unknown);\n}\n\ntype ApprovalAwareJsonSchemaExecutableToolDescriptors = Record<\n string,\n ApprovalAwareJsonSchemaExecutableToolDescriptor\n>;\n\nexport interface BrowserCodeToolDescriptor {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: {\n code: { type: \"string\"; description: string };\n };\n required: [\"code\"];\n };\n outputSchema: {\n type: \"object\";\n properties: {\n result: { description: string };\n logs: {\n type: \"array\";\n items: { type: \"string\" };\n description: string;\n };\n };\n required: [\"result\"];\n };\n execute: (args: CodeInput) => Promise<CodeOutput>;\n}\n\nexport interface CreateBrowserCodeToolOptions {\n /**\n * Tools available inside the sandbox via `codemode.*`.\n *\n * Accepts either an array (like `listTools()` returns) with `name` on each item,\n * or an object keyed by tool name (like `createCodeTool` expects).\n */\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors;\n /**\n * Executor to use. Defaults to a new `IframeSandboxExecutor`.\n */\n executor?: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for generated type definitions.\n */\n description?: string;\n}\n\n// -- Implementation --\n\nconst DEFAULT_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nfunction toRecord(\n tools:\n | ApprovalAwareJsonSchemaExecutableToolDescriptor[]\n | ApprovalAwareJsonSchemaExecutableToolDescriptors\n): ApprovalAwareJsonSchemaExecutableToolDescriptors {\n if (!Array.isArray(tools)) return tools;\n\n const record: ApprovalAwareJsonSchemaExecutableToolDescriptors = {};\n for (const tool of tools) {\n if (!tool.name) {\n throw new Error(\n \"Tool descriptors in array form must have a `name` property\"\n );\n }\n record[tool.name] = tool;\n }\n return record;\n}\n\nfunction hasNeedsApproval(tool: Record<string, unknown>): boolean {\n return (\n tool.needsApproval === true || typeof tool.needsApproval === \"function\"\n );\n}\n\n/**\n * Create a codemode tool descriptor using only JSON Schema and browser APIs.\n *\n * This is the browser counterpart to `createCodeTool` from\n * `@cloudflare/codemode/ai`.\n * It returns a plain object with `{ name, description, inputSchema, outputSchema, execute }`\n * that can be passed to any framework — including\n * `navigator.modelContext.registerTool()`.\n *\n * Tools with `needsApproval` are excluded, matching the current codemode\n * behavior for approval-gated tools. JSON Schema is used for prompt/type\n * generation only and is not enforced at runtime.\n */\nexport function createBrowserCodeTool(\n options: CreateBrowserCodeToolOptions\n): BrowserCodeToolDescriptor {\n const allTools = toRecord(options.tools);\n const toolMap: JsonSchemaExecutableToolDescriptors = {};\n for (const [name, tool] of Object.entries(allTools)) {\n if (!hasNeedsApproval(tool as unknown as Record<string, unknown>)) {\n toolMap[name] = tool;\n }\n }\n const executor = options.executor ?? new IframeSandboxExecutor();\n\n // Generate TypeScript type descriptions for the LLM prompt\n const schemaOnly: JsonSchemaToolDescriptors = {};\n for (const [name, tool] of Object.entries(toolMap)) {\n schemaOnly[name] = {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema\n };\n }\n const types = generateTypesFromJsonSchema(schemaOnly);\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n // Extract execute functions, keyed by sanitized name\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n const sanitizedNames = new Map<string, string>();\n for (const [name, tool] of Object.entries(toolMap)) {\n if (tool.execute) {\n const sanitizedName = sanitizeToolName(name);\n const existingName = sanitizedNames.get(sanitizedName);\n if (existingName && existingName !== name) {\n throw new Error(\n `Tool names \"${existingName}\" and \"${name}\" both sanitize to \"${sanitizedName}\"`\n );\n }\n sanitizedNames.set(sanitizedName, name);\n fns[sanitizedName] = tool.execute as (args: unknown) => Promise<unknown>;\n }\n }\n const resolvedProviders: ResolvedProvider[] = [{ name: \"codemode\", fns }];\n\n return {\n name: \"codemode\",\n description,\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"JavaScript async arrow function to execute\"\n }\n },\n required: [\"code\"]\n },\n outputSchema: {\n type: \"object\",\n properties: {\n result: {\n description: \"The return value of the executed code\"\n },\n logs: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Console output captured during execution\"\n }\n },\n required: [\"result\"]\n },\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n };\n}\n"],"mappings":";;;AAYA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAgDA,SAAgB,sBACd,MAC6B;CAC7B,OAAO,SAAS,IAAI,KAAK,KAAK,SAAS;AACzC;AAEA,SAAgB,kBAAkB,MAAwC;CACxE,OACE,SAAS,IAAI,KACb,KAAK,SAAS,eACd,OAAO,KAAK,UAAU,YACtB,OAAO,KAAK,OAAO,YACnB,OAAO,KAAK,aAAa,YACzB,OAAO,KAAK,SAAS;AAEzB;AAEA,SAAgB,yBACd,MACgC;CAChC,IAAI,CAAC,SAAS,IAAI,GAAG,OAAO;CAC5B,IAAI,KAAK,SAAS,oBAAoB,OAAO;CAC7C,IAAI,OAAO,KAAK,UAAU,UAAU,OAAO;CAC3C,IAAI,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW,MAAM,OAAO;CACpE,OAAO;AACT;;;;;;;;;;;;;;;;;ACxEA,SAAS,2BAAiC;CACxC,MAAM,gBAAgB;CAGtB,IAAI,cAAc,6BAChB;CAGF,cAAc,8BAA8B;CAE5C,MAAM,OAAiB,CAAC;CACxB,MAAM,UAGF,CAAC;CACL,IAAI,SAAS;CACb,IAAI;CAEJ,SAAS,KAAK,SAAkB;EAC9B,OAAO,YAAY,SAAS,GAAG;CACjC;CAGA,QAAQ,OAAO,GAAG,SAAoB;EACpC,MAAM,SAAS,CAAC;EAChB,KAA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;EAAY;CAAI,CAAC;CAExE,OAAO;EACL,MAAM;EACN;EACA,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;GACf,EACF;GACA,UAAU,CAAC,MAAM;EACnB;EACA,cAAc;GACZ,MAAM;GACN,YAAY;IACV,QAAQ,EACN,aAAa,wCACf;IACA,MAAM;KACJ,MAAM;KACN,OAAO,EAAE,MAAM,SAAS;KACxB,aAAa;IACf;GACF;GACA,UAAU,CAAC,QAAQ;EACrB;EACA,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;EAAkB,CAAC;CAC5D;AACF"}
|
|
@@ -139,7 +139,7 @@ declare class ToolDispatcher extends RpcTarget {
|
|
|
139
139
|
interface DynamicWorkerExecutorOptions {
|
|
140
140
|
loader: WorkerLoader;
|
|
141
141
|
/**
|
|
142
|
-
* Timeout in milliseconds for code execution. Defaults to
|
|
142
|
+
* Timeout in milliseconds for code execution. Defaults to 60000 (60s).
|
|
143
143
|
*/
|
|
144
144
|
timeout?: number;
|
|
145
145
|
/**
|
|
@@ -210,4 +210,4 @@ export {
|
|
|
210
210
|
DynamicWorkerExecutor as t,
|
|
211
211
|
ResolvedProvider as u
|
|
212
212
|
};
|
|
213
|
-
//# sourceMappingURL=executor-
|
|
213
|
+
//# sourceMappingURL=executor-DkMGH_7-.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -8,8 +8,8 @@ import {
|
|
|
8
8
|
s as ExecuteOptions,
|
|
9
9
|
t as DynamicWorkerExecutor,
|
|
10
10
|
u as ResolvedProvider
|
|
11
|
-
} from "./executor-
|
|
12
|
-
import { n as CodeOutput } from "./shared-
|
|
11
|
+
} from "./executor-DkMGH_7-.js";
|
|
12
|
+
import { n as CodeOutput } from "./shared-BOF2IKt-.js";
|
|
13
13
|
import {
|
|
14
14
|
i as jsonSchemaToType,
|
|
15
15
|
n as JsonSchemaToolDescriptors,
|
|
@@ -29,11 +29,10 @@ import {
|
|
|
29
29
|
t as CodemodeConnector,
|
|
30
30
|
u as ToolAnnotations
|
|
31
31
|
} from "./base-B2amchZA.js";
|
|
32
|
-
import { t as resolveProvider } from "./resolve-
|
|
32
|
+
import { t as resolveProvider } from "./resolve-tqDt6Djo.js";
|
|
33
33
|
import { DurableObject } from "cloudflare:workers";
|
|
34
|
-
import { Tool } from "ai";
|
|
35
34
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
36
|
-
import { Tool
|
|
35
|
+
import { Tool } from "@modelcontextprotocol/sdk/types.js";
|
|
37
36
|
|
|
38
37
|
//#region src/run-code.d.ts
|
|
39
38
|
declare function runCode({
|
|
@@ -388,8 +387,8 @@ interface McpConnectionLike {
|
|
|
388
387
|
name?: string;
|
|
389
388
|
client: Pick<Client, "callTool">;
|
|
390
389
|
instructions?: string;
|
|
391
|
-
tools?: Tool
|
|
392
|
-
fetchTools?: () => Promise<Tool
|
|
390
|
+
tools?: Tool[];
|
|
391
|
+
fetchTools?: () => Promise<Tool[]>;
|
|
393
392
|
}
|
|
394
393
|
/**
|
|
395
394
|
* Connector backed by an MCP connection. Each MCP tool becomes one entry in
|
|
@@ -407,9 +406,9 @@ declare abstract class McpConnector<
|
|
|
407
406
|
protected abstract createConnection():
|
|
408
407
|
| Promise<McpConnectionLike>
|
|
409
408
|
| McpConnectionLike;
|
|
410
|
-
protected toolName(tool: Tool
|
|
409
|
+
protected toolName(tool: Tool): string;
|
|
411
410
|
protected getConnection(): Promise<McpConnectionLike>;
|
|
412
|
-
protected fetchTools(): Promise<Tool
|
|
411
|
+
protected fetchTools(): Promise<Tool[]>;
|
|
413
412
|
describe(): Promise<ConnectorDescription>;
|
|
414
413
|
protected tools(): Promise<ConnectorTools>;
|
|
415
414
|
}
|
|
@@ -470,17 +469,20 @@ type ProxyToolOutput =
|
|
|
470
469
|
executionId: string;
|
|
471
470
|
result: unknown;
|
|
472
471
|
logs?: string[];
|
|
472
|
+
calls?: ToolLogEntry[];
|
|
473
473
|
}
|
|
474
474
|
| {
|
|
475
475
|
status: "paused";
|
|
476
476
|
executionId: string;
|
|
477
477
|
pending: PendingAction[];
|
|
478
|
+
calls?: ToolLogEntry[];
|
|
478
479
|
}
|
|
479
480
|
| {
|
|
480
481
|
status: "error";
|
|
481
482
|
executionId: string;
|
|
482
483
|
error: string;
|
|
483
484
|
logs?: string[];
|
|
485
|
+
calls?: ToolLogEntry[];
|
|
484
486
|
};
|
|
485
487
|
/**
|
|
486
488
|
* Shape the final result before it is returned to the model. Runs on a
|
|
@@ -489,6 +491,48 @@ type ProxyToolOutput =
|
|
|
489
491
|
* the transformed one. A common use is `truncateResult` to cap response size.
|
|
490
492
|
*/
|
|
491
493
|
type TransformResult = (result: unknown) => unknown | Promise<unknown>;
|
|
494
|
+
type StandardSchemaIssue = {
|
|
495
|
+
readonly message: string;
|
|
496
|
+
readonly path?: ReadonlyArray<PropertyKey>;
|
|
497
|
+
};
|
|
498
|
+
type ProxyToolInputSchema = {
|
|
499
|
+
readonly "~standard": {
|
|
500
|
+
readonly version: 1;
|
|
501
|
+
readonly vendor: "@cloudflare/codemode";
|
|
502
|
+
readonly validate: (value: unknown) =>
|
|
503
|
+
| {
|
|
504
|
+
readonly value: ProxyToolInput;
|
|
505
|
+
}
|
|
506
|
+
| {
|
|
507
|
+
readonly issues: ReadonlyArray<StandardSchemaIssue>;
|
|
508
|
+
};
|
|
509
|
+
readonly jsonSchema: {
|
|
510
|
+
readonly input: (options: {
|
|
511
|
+
readonly target: string;
|
|
512
|
+
}) => Record<string, unknown>;
|
|
513
|
+
readonly output: (options: {
|
|
514
|
+
readonly target: string;
|
|
515
|
+
}) => Record<string, unknown>;
|
|
516
|
+
};
|
|
517
|
+
};
|
|
518
|
+
};
|
|
519
|
+
/**
|
|
520
|
+
* Notify every connector that an execution reached a terminal state so it can
|
|
521
|
+
* dispose any per-execution resource (e.g. a browser session). Deliberately
|
|
522
|
+
* *not* called on pause — a paused run may resume later. Hook rejections are
|
|
523
|
+
* swallowed: teardown must never turn a finished run into a failure.
|
|
524
|
+
*
|
|
525
|
+
* Fires for every connector regardless of whether it took part in the run —
|
|
526
|
+
* connectors that own no per-execution state default to a no-op.
|
|
527
|
+
*/
|
|
528
|
+
type CodemodeTool = {
|
|
529
|
+
description: string;
|
|
530
|
+
inputSchema: ProxyToolInputSchema;
|
|
531
|
+
execute: (
|
|
532
|
+
input: ProxyToolInput,
|
|
533
|
+
options: unknown
|
|
534
|
+
) => Promise<ProxyToolOutput>;
|
|
535
|
+
};
|
|
492
536
|
//#endregion
|
|
493
537
|
//#region src/runtime-handle.d.ts
|
|
494
538
|
type CreateCodemodeRuntimeOptions = {
|
|
@@ -545,9 +589,7 @@ type CodemodeExpireOptions = {
|
|
|
545
589
|
maxAgeMs?: number;
|
|
546
590
|
};
|
|
547
591
|
interface CodemodeRuntimeHandle {
|
|
548
|
-
tool(
|
|
549
|
-
options?: CodemodeRuntimeToolOptions
|
|
550
|
-
): Tool<ProxyToolInput, ProxyToolOutput>;
|
|
592
|
+
tool(options?: CodemodeRuntimeToolOptions): CodemodeTool;
|
|
551
593
|
approve(options: CodemodeApproveOptions): Promise<ProxyToolOutput>;
|
|
552
594
|
/**
|
|
553
595
|
* Reject a pending action, ending the run. Returns whether the reject
|