@cloudflare/codemode 0.3.8 → 0.4.1
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/LICENSE +21 -0
- package/README.md +251 -7
- package/dist/ai.d.ts +50 -7
- package/dist/ai.js +93 -5
- package/dist/ai.js.map +1 -1
- package/dist/base-B2amchZA.d.ts +239 -0
- package/dist/base-CHRR_a5j.js +156 -0
- package/dist/base-CHRR_a5j.js.map +1 -0
- package/dist/browser.d.ts +6 -6
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/{executor-BRm90XJT.d.ts → executor-BIs2dr7X.d.ts} +48 -10
- package/dist/index.d.ts +608 -8
- package/dist/index.js +1690 -17
- package/dist/index.js.map +1 -1
- package/dist/{json-schema-types-CVt4X9cw.js → json-schema-types-BGjW4KPy.js} +1 -1
- package/dist/{json-schema-types-CVt4X9cw.js.map → json-schema-types-BGjW4KPy.js.map} +1 -1
- package/dist/{json-schema-types-1OL3uao0.d.ts → json-schema-types-Cb2wClAd.d.ts} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-DdyeEp3l.js → resolve-34dC47Il.js} +1 -1
- package/dist/{resolve-DdyeEp3l.js.map → resolve-34dC47Il.js.map} +1 -1
- package/dist/{resolve-DtfaKmms.d.ts → resolve-CBr_VoPl.d.ts} +4 -4
- package/dist/{run-code-5x8S5YWt.js → run-code-aKHcTgf9.js} +4 -4
- package/dist/run-code-aKHcTgf9.js.map +1 -0
- package/dist/{shared-TyFN6W7_.d.ts → shared-Ce-zCEBP.d.ts} +3 -3
- package/dist/{shared-xjl2irqK.js → shared-SMjV5yN4.js} +1 -1
- package/dist/{shared-xjl2irqK.js.map → shared-SMjV5yN4.js.map} +1 -1
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +4 -4
- package/dist/tanstack-ai.js.map +1 -1
- package/dist/vite.d.ts +7 -0
- package/dist/vite.js +122 -0
- package/dist/vite.js.map +1 -0
- package/package.json +19 -14
- package/dist/run-code-5x8S5YWt.js.map +0 -1
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { n as JsonSchemaToolDescriptors } from "./json-schema-types-Cb2wClAd.js";
|
|
2
|
+
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
3
|
+
import { JSONSchema7 } from "json-schema";
|
|
4
|
+
|
|
5
|
+
//#region src/connectors/types.d.ts
|
|
6
|
+
type ToolAnnotations = {
|
|
7
|
+
/** Requires user approval before executing. Unannotated methods execute immediately. */ requiresApproval?: boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Replay policy for the durable log. `"reexecute"` marks the call ephemeral:
|
|
10
|
+
* its result is never stored, and a replay re-executes the call instead of
|
|
11
|
+
* replaying a recorded result. Only valid for idempotent reads — the call
|
|
12
|
+
* runs again on every resume pass. Keeps large read results (file contents,
|
|
13
|
+
* directory listings) out of the durable log. Defaults to `"log"`.
|
|
14
|
+
*/
|
|
15
|
+
replay?: "log" | "reexecute";
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Passed to a tool's `execute`/`revert` so a connector knows which codemode
|
|
19
|
+
* execution the call belongs to. The id is stable across a run's pause/resume
|
|
20
|
+
* passes, so it's the right key for a per-execution resource (e.g. a browser
|
|
21
|
+
* session) that must survive a pause.
|
|
22
|
+
*/
|
|
23
|
+
type ToolExecuteContext = {
|
|
24
|
+
/** The codemode execution this call belongs to. Stable across pause/resume. */ executionId: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Terminal outcome of a codemode execution, passed to
|
|
28
|
+
* `CodemodeConnector.disposeExecution`. These mirror the terminal subset of the
|
|
29
|
+
* runtime's `ExecutionStatus`; a `paused` run is *not* terminal — it may resume
|
|
30
|
+
* later — so it is deliberately absent here.
|
|
31
|
+
*
|
|
32
|
+
* - `completed` — the run finished and returned a result.
|
|
33
|
+
* - `error` — the run threw or hit a replay divergence.
|
|
34
|
+
* - `rejected` — a pending action was rejected by the user.
|
|
35
|
+
* - `rolled_back` — the run's applied effects were reverted.
|
|
36
|
+
*/
|
|
37
|
+
type ExecutionEndStatus = "completed" | "error" | "rejected" | "rolled_back";
|
|
38
|
+
/**
|
|
39
|
+
* Outcome of a single execution *pass*, passed to
|
|
40
|
+
* `CodemodeConnector.onPassEnd`. Unlike `ExecutionEndStatus` this includes
|
|
41
|
+
* `"paused"`: a pass that ends awaiting approval is not terminal (the
|
|
42
|
+
* execution may resume later), but the pass itself is over — per-pass
|
|
43
|
+
* resources (an open socket, a lease) should be released even though
|
|
44
|
+
* per-execution resources (a session) must survive.
|
|
45
|
+
*/
|
|
46
|
+
type PassEndStatus = ExecutionEndStatus | "paused";
|
|
47
|
+
type ConnectorDescription = {
|
|
48
|
+
name: string;
|
|
49
|
+
instructions?: string;
|
|
50
|
+
descriptors: JsonSchemaToolDescriptors;
|
|
51
|
+
annotations?: Record<string, ToolAnnotations>;
|
|
52
|
+
};
|
|
53
|
+
type SearchResult = {
|
|
54
|
+
path: string;
|
|
55
|
+
connector: string;
|
|
56
|
+
method: string;
|
|
57
|
+
description?: string;
|
|
58
|
+
kind: "method" | "snippet";
|
|
59
|
+
score: number;
|
|
60
|
+
};
|
|
61
|
+
type SearchOutput = {
|
|
62
|
+
results: SearchResult[];
|
|
63
|
+
total: number;
|
|
64
|
+
truncated: boolean;
|
|
65
|
+
};
|
|
66
|
+
type DescribeOutput = {
|
|
67
|
+
path: string;
|
|
68
|
+
description?: string;
|
|
69
|
+
types: string;
|
|
70
|
+
kind: "connector" | "method" | "snippet";
|
|
71
|
+
};
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/connectors/base.d.ts
|
|
74
|
+
/**
|
|
75
|
+
* A single connector tool — everything about it in one place: docs, schema,
|
|
76
|
+
* approval requirement, execution, and (optionally) how to undo it.
|
|
77
|
+
*
|
|
78
|
+
* AI SDK tools are shape-compatible: a `ToolSet` can be returned from
|
|
79
|
+
* `tools()` directly.
|
|
80
|
+
*/
|
|
81
|
+
type ConnectorTool = {
|
|
82
|
+
description?: string /** JSON Schema for the tool input. Defaults to an open object. */;
|
|
83
|
+
inputSchema?: JSONSchema7;
|
|
84
|
+
outputSchema?: JSONSchema7 /** Pause for user approval before executing. Omit to execute immediately. */;
|
|
85
|
+
requiresApproval?: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Replay policy for the durable log. `"reexecute"` marks the call ephemeral:
|
|
88
|
+
* its result is never stored durably, and a replay re-executes the call
|
|
89
|
+
* instead of replaying a recorded result. Use it for idempotent reads whose
|
|
90
|
+
* results are large (file contents, directory listings) — they'd otherwise
|
|
91
|
+
* bloat the replay log. Incompatible with `requiresApproval` (an approved
|
|
92
|
+
* side effect must be logged, never re-executed). Defaults to `"log"`.
|
|
93
|
+
*/
|
|
94
|
+
replay?: "log" | "reexecute";
|
|
95
|
+
execute: (
|
|
96
|
+
args: unknown,
|
|
97
|
+
ctx?: ToolExecuteContext
|
|
98
|
+
) =>
|
|
99
|
+
| Promise<unknown>
|
|
100
|
+
| unknown /** Optional compensation for rollback: undo an applied call. */;
|
|
101
|
+
revert?: (
|
|
102
|
+
args: unknown,
|
|
103
|
+
result: unknown,
|
|
104
|
+
ctx?: ToolExecuteContext
|
|
105
|
+
) => Promise<void> | void;
|
|
106
|
+
};
|
|
107
|
+
type ConnectorTools = Record<string, ConnectorTool>;
|
|
108
|
+
/**
|
|
109
|
+
* Base class for codemode connectors.
|
|
110
|
+
*
|
|
111
|
+
* A connector answers three questions: what global name does the model use
|
|
112
|
+
* (`name`), what guidance does the model get (`instructions`), and what tools
|
|
113
|
+
* exist (`tools` — each tool carries its own docs, schema, approval
|
|
114
|
+
* requirement, execution, and optional revert).
|
|
115
|
+
*
|
|
116
|
+
* The RPC surface (`describe`, `executeTool`, `revertAction`,
|
|
117
|
+
* `getTypeScriptTypes`) is wire plumbing derived from the tools record — the
|
|
118
|
+
* proxy tool calls it; connector authors don't implement it.
|
|
119
|
+
*/
|
|
120
|
+
declare abstract class CodemodeConnector<
|
|
121
|
+
Env = unknown,
|
|
122
|
+
Props = unknown
|
|
123
|
+
> extends WorkerEntrypoint<Env, Props> {
|
|
124
|
+
#private;
|
|
125
|
+
/**
|
|
126
|
+
* Connectors are used in-process by the runtime (their `name()`, `describe()`,
|
|
127
|
+
* and `executeTool()` are called directly), so they're constructed with `new`
|
|
128
|
+
* — typically from inside an Agent / Durable Object.
|
|
129
|
+
*
|
|
130
|
+
* Inside a Durable Object `this.ctx` is a `DurableObjectState`, not an
|
|
131
|
+
* `ExecutionContext`. The base `WorkerEntrypoint` constructor only stores it,
|
|
132
|
+
* so we widen the parameter to accept either — pass `this.ctx` directly with
|
|
133
|
+
* no cast:
|
|
134
|
+
*
|
|
135
|
+
* ```ts
|
|
136
|
+
* const github = new GithubConnector(this.ctx, this.env, conn);
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
constructor(ctx: DurableObjectState | ExecutionContext, env: Env);
|
|
140
|
+
abstract name(): string;
|
|
141
|
+
protected instructions(): string | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* The single authoring surface: one record, one entry per tool.
|
|
144
|
+
* Derived connectors (MCP, OpenAPI) generate this for you.
|
|
145
|
+
*/
|
|
146
|
+
protected abstract tools(): ConnectorTools | Promise<ConnectorTools>;
|
|
147
|
+
/**
|
|
148
|
+
* Decoration hook, called once per tool. Override to adjust tools you
|
|
149
|
+
* didn't author inline — e.g. mark a derived MCP tool as requiring
|
|
150
|
+
* approval, or attach a revert:
|
|
151
|
+
*
|
|
152
|
+
* ```ts
|
|
153
|
+
* protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
154
|
+
* if (name === "create_issue") {
|
|
155
|
+
* return { ...t, requiresApproval: true };
|
|
156
|
+
* }
|
|
157
|
+
* return t;
|
|
158
|
+
* }
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
protected tool(_name: string, t: ConnectorTool): ConnectorTool;
|
|
162
|
+
protected resolvedTools(): Promise<ConnectorTools>;
|
|
163
|
+
describe(): Promise<ConnectorDescription>;
|
|
164
|
+
executeTool(
|
|
165
|
+
method: string,
|
|
166
|
+
args: unknown,
|
|
167
|
+
ctx?: ToolExecuteContext
|
|
168
|
+
): Promise<unknown>;
|
|
169
|
+
/**
|
|
170
|
+
* Revert an applied action. Returns whether a revert actually ran — reads and
|
|
171
|
+
* tools without a `revert` are a no-op and return `false`, so the runtime can
|
|
172
|
+
* mark only the entries it truly reverted.
|
|
173
|
+
*/
|
|
174
|
+
revertAction(
|
|
175
|
+
method: string,
|
|
176
|
+
args: unknown,
|
|
177
|
+
result: unknown,
|
|
178
|
+
ctx?: ToolExecuteContext
|
|
179
|
+
): Promise<boolean>;
|
|
180
|
+
/**
|
|
181
|
+
* Called at the end of every execution *pass* — including a pass that ends
|
|
182
|
+
* in a pause awaiting approval, where `disposeExecution` deliberately does
|
|
183
|
+
* NOT fire. Override to release per-pass resources: an open socket, a lease,
|
|
184
|
+
* an in-memory cache entry. Per-execution resources (e.g. a browser session
|
|
185
|
+
* that must survive the pause for the resume) belong in `disposeExecution`.
|
|
186
|
+
*
|
|
187
|
+
* On a terminal pass, `onPassEnd` fires first, then `disposeExecution`.
|
|
188
|
+
*
|
|
189
|
+
* Contract for implementers: be idempotent, don't rely on instance memory
|
|
190
|
+
* (a resume may run on a fresh instance), and don't throw — the runtime
|
|
191
|
+
* ignores rejections from this hook.
|
|
192
|
+
*/
|
|
193
|
+
onPassEnd(_executionId: string, _status: PassEndStatus): Promise<void>;
|
|
194
|
+
/**
|
|
195
|
+
* Called once when a codemode execution reaches a terminal state — completed,
|
|
196
|
+
* errored, rejected, or rolled back — and will not resume. Override to tear
|
|
197
|
+
* down any per-execution resource this connector opened for that run, keyed
|
|
198
|
+
* by `executionId` (e.g. close a browser/CDP session).
|
|
199
|
+
*
|
|
200
|
+
* It is deliberately *not* called when a run pauses for approval: a paused
|
|
201
|
+
* run may resume later, possibly in a fresh Worker invocation, so a resource
|
|
202
|
+
* scoped to the whole run must outlive a pause. This hook is the single point
|
|
203
|
+
* where teardown is safe.
|
|
204
|
+
*
|
|
205
|
+
* Contract for implementers:
|
|
206
|
+
* - Be idempotent. It may fire more than once for the same execution (a
|
|
207
|
+
* completed run that is later rolled back) and a no-op is expected the
|
|
208
|
+
* second time.
|
|
209
|
+
* - Don't rely on instance memory. It may run on a different connector
|
|
210
|
+
* instance than the one that opened the resource (the host can reconstruct
|
|
211
|
+
* connectors per request, and the opening pass may have hibernated), so
|
|
212
|
+
* read what you need from durable storage keyed by `executionId`.
|
|
213
|
+
* - Don't throw. Teardown failures must not turn a finished run into a
|
|
214
|
+
* failure; the runtime ignores rejections from this hook.
|
|
215
|
+
*
|
|
216
|
+
* The default is a no-op, so connectors that own no per-execution state
|
|
217
|
+
* don't implement it.
|
|
218
|
+
*/
|
|
219
|
+
disposeExecution(
|
|
220
|
+
_executionId: string,
|
|
221
|
+
_status: ExecutionEndStatus
|
|
222
|
+
): Promise<void>;
|
|
223
|
+
getTypeScriptTypes(): Promise<string>;
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
|
226
|
+
export {
|
|
227
|
+
DescribeOutput as a,
|
|
228
|
+
SearchOutput as c,
|
|
229
|
+
ToolExecuteContext as d,
|
|
230
|
+
ConnectorDescription as i,
|
|
231
|
+
SearchResult as l,
|
|
232
|
+
ConnectorTool as n,
|
|
233
|
+
ExecutionEndStatus as o,
|
|
234
|
+
ConnectorTools as r,
|
|
235
|
+
PassEndStatus as s,
|
|
236
|
+
CodemodeConnector as t,
|
|
237
|
+
ToolAnnotations as u
|
|
238
|
+
};
|
|
239
|
+
//# sourceMappingURL=base-B2amchZA.d.ts.map
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { t as generateTypesFromJsonSchema } from "./json-schema-types-BGjW4KPy.js";
|
|
2
|
+
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
3
|
+
//#region src/connectors/base.ts
|
|
4
|
+
function toolInputSchema(t) {
|
|
5
|
+
const loose = t;
|
|
6
|
+
for (const candidate of [loose.inputSchema, loose.parameters]) if (candidate && typeof candidate === "object" && ("type" in candidate || "properties" in candidate || "$ref" in candidate)) return candidate;
|
|
7
|
+
return { type: "object" };
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Base class for codemode connectors.
|
|
11
|
+
*
|
|
12
|
+
* A connector answers three questions: what global name does the model use
|
|
13
|
+
* (`name`), what guidance does the model get (`instructions`), and what tools
|
|
14
|
+
* exist (`tools` — each tool carries its own docs, schema, approval
|
|
15
|
+
* requirement, execution, and optional revert).
|
|
16
|
+
*
|
|
17
|
+
* The RPC surface (`describe`, `executeTool`, `revertAction`,
|
|
18
|
+
* `getTypeScriptTypes`) is wire plumbing derived from the tools record — the
|
|
19
|
+
* proxy tool calls it; connector authors don't implement it.
|
|
20
|
+
*/
|
|
21
|
+
var CodemodeConnector = class extends WorkerEntrypoint {
|
|
22
|
+
/**
|
|
23
|
+
* Connectors are used in-process by the runtime (their `name()`, `describe()`,
|
|
24
|
+
* and `executeTool()` are called directly), so they're constructed with `new`
|
|
25
|
+
* — typically from inside an Agent / Durable Object.
|
|
26
|
+
*
|
|
27
|
+
* Inside a Durable Object `this.ctx` is a `DurableObjectState`, not an
|
|
28
|
+
* `ExecutionContext`. The base `WorkerEntrypoint` constructor only stores it,
|
|
29
|
+
* so we widen the parameter to accept either — pass `this.ctx` directly with
|
|
30
|
+
* no cast:
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* const github = new GithubConnector(this.ctx, this.env, conn);
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
constructor(ctx, env) {
|
|
37
|
+
super(ctx, env);
|
|
38
|
+
}
|
|
39
|
+
instructions() {}
|
|
40
|
+
/**
|
|
41
|
+
* Decoration hook, called once per tool. Override to adjust tools you
|
|
42
|
+
* didn't author inline — e.g. mark a derived MCP tool as requiring
|
|
43
|
+
* approval, or attach a revert:
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
47
|
+
* if (name === "create_issue") {
|
|
48
|
+
* return { ...t, requiresApproval: true };
|
|
49
|
+
* }
|
|
50
|
+
* return t;
|
|
51
|
+
* }
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
tool(_name, t) {
|
|
55
|
+
return t;
|
|
56
|
+
}
|
|
57
|
+
#toolsPromise;
|
|
58
|
+
resolvedTools() {
|
|
59
|
+
return this.#toolsPromise ??= (async () => {
|
|
60
|
+
const tools = await this.tools();
|
|
61
|
+
const out = {};
|
|
62
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
63
|
+
if (!t || typeof t !== "object") continue;
|
|
64
|
+
out[name] = this.tool(name, t);
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
})();
|
|
68
|
+
}
|
|
69
|
+
async describe() {
|
|
70
|
+
const tools = await this.resolvedTools();
|
|
71
|
+
const descriptors = {};
|
|
72
|
+
const annotations = {};
|
|
73
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
74
|
+
if (t.requiresApproval && t.replay === "reexecute") throw new Error(`Connector "${this.name()}" tool "${name}" cannot combine requiresApproval with replay: "reexecute" — approved actions must be logged, not re-executed.`);
|
|
75
|
+
descriptors[name] = {
|
|
76
|
+
description: t.description,
|
|
77
|
+
inputSchema: toolInputSchema(t),
|
|
78
|
+
outputSchema: t.outputSchema
|
|
79
|
+
};
|
|
80
|
+
if (t.requiresApproval || t.replay === "reexecute") annotations[name] = {
|
|
81
|
+
...t.requiresApproval ? { requiresApproval: true } : {},
|
|
82
|
+
...t.replay === "reexecute" ? { replay: "reexecute" } : {}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
name: this.name(),
|
|
87
|
+
instructions: this.instructions(),
|
|
88
|
+
descriptors,
|
|
89
|
+
annotations
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
async executeTool(method, args, ctx) {
|
|
93
|
+
const tool = (await this.resolvedTools())[method];
|
|
94
|
+
if (!tool) throw new Error(`Tool "${method}" not found on ${this.name()}`);
|
|
95
|
+
return await tool.execute(args, ctx);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Revert an applied action. Returns whether a revert actually ran — reads and
|
|
99
|
+
* tools without a `revert` are a no-op and return `false`, so the runtime can
|
|
100
|
+
* mark only the entries it truly reverted.
|
|
101
|
+
*/
|
|
102
|
+
async revertAction(method, args, result, ctx) {
|
|
103
|
+
const tool = (await this.resolvedTools())[method];
|
|
104
|
+
if (!tool?.revert) return false;
|
|
105
|
+
await tool.revert(args, result, ctx);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Called at the end of every execution *pass* — including a pass that ends
|
|
110
|
+
* in a pause awaiting approval, where `disposeExecution` deliberately does
|
|
111
|
+
* NOT fire. Override to release per-pass resources: an open socket, a lease,
|
|
112
|
+
* an in-memory cache entry. Per-execution resources (e.g. a browser session
|
|
113
|
+
* that must survive the pause for the resume) belong in `disposeExecution`.
|
|
114
|
+
*
|
|
115
|
+
* On a terminal pass, `onPassEnd` fires first, then `disposeExecution`.
|
|
116
|
+
*
|
|
117
|
+
* Contract for implementers: be idempotent, don't rely on instance memory
|
|
118
|
+
* (a resume may run on a fresh instance), and don't throw — the runtime
|
|
119
|
+
* ignores rejections from this hook.
|
|
120
|
+
*/
|
|
121
|
+
async onPassEnd(_executionId, _status) {}
|
|
122
|
+
/**
|
|
123
|
+
* Called once when a codemode execution reaches a terminal state — completed,
|
|
124
|
+
* errored, rejected, or rolled back — and will not resume. Override to tear
|
|
125
|
+
* down any per-execution resource this connector opened for that run, keyed
|
|
126
|
+
* by `executionId` (e.g. close a browser/CDP session).
|
|
127
|
+
*
|
|
128
|
+
* It is deliberately *not* called when a run pauses for approval: a paused
|
|
129
|
+
* run may resume later, possibly in a fresh Worker invocation, so a resource
|
|
130
|
+
* scoped to the whole run must outlive a pause. This hook is the single point
|
|
131
|
+
* where teardown is safe.
|
|
132
|
+
*
|
|
133
|
+
* Contract for implementers:
|
|
134
|
+
* - Be idempotent. It may fire more than once for the same execution (a
|
|
135
|
+
* completed run that is later rolled back) and a no-op is expected the
|
|
136
|
+
* second time.
|
|
137
|
+
* - Don't rely on instance memory. It may run on a different connector
|
|
138
|
+
* instance than the one that opened the resource (the host can reconstruct
|
|
139
|
+
* connectors per request, and the opening pass may have hibernated), so
|
|
140
|
+
* read what you need from durable storage keyed by `executionId`.
|
|
141
|
+
* - Don't throw. Teardown failures must not turn a finished run into a
|
|
142
|
+
* failure; the runtime ignores rejections from this hook.
|
|
143
|
+
*
|
|
144
|
+
* The default is a no-op, so connectors that own no per-execution state
|
|
145
|
+
* don't implement it.
|
|
146
|
+
*/
|
|
147
|
+
async disposeExecution(_executionId, _status) {}
|
|
148
|
+
async getTypeScriptTypes() {
|
|
149
|
+
const { descriptors } = await this.describe();
|
|
150
|
+
return generateTypesFromJsonSchema(descriptors).replace("declare const codemode", `declare const ${this.name()}`);
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
//#endregion
|
|
154
|
+
export { CodemodeConnector as t };
|
|
155
|
+
|
|
156
|
+
//# sourceMappingURL=base-CHRR_a5j.js.map
|
|
@@ -0,0 +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,MAAs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AAO;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
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
|
-
c as
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
} from "./executor-
|
|
6
|
-
import { n as CodeOutput, t as CodeInput } from "./shared-
|
|
2
|
+
c as ExecuteResult,
|
|
3
|
+
l as Executor,
|
|
4
|
+
u as ResolvedProvider
|
|
5
|
+
} from "./executor-BIs2dr7X.js";
|
|
6
|
+
import { n as CodeOutput, t as CodeInput } from "./shared-Ce-zCEBP.js";
|
|
7
7
|
import {
|
|
8
8
|
n as JsonSchemaToolDescriptors,
|
|
9
9
|
t as JsonSchemaToolDescriptor
|
|
10
|
-
} from "./json-schema-types-
|
|
10
|
+
} from "./json-schema-types-Cb2wClAd.js";
|
|
11
11
|
|
|
12
12
|
//#region src/iframe-executor.d.ts
|
|
13
13
|
interface IframeSandboxExecutorOptions {
|
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-BGjW4KPy.js";
|
|
2
|
+
import { t as runCode } from "./run-code-aKHcTgf9.js";
|
|
3
3
|
//#region src/messages.ts
|
|
4
4
|
function isRecord(value) {
|
|
5
5
|
return typeof value === "object" && value !== null;
|
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,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B;CAG/D,MAAM,aAAwC,CAAC;CAC/C,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,GAC/C,WAAW,QAAQ;EACjB,aAAa,KAAK;EAClB,aAAa,KAAK;EAClB,cAAc,KAAK;CACrB;CAEF,MAAM,QAAQ,4BAA4B,UAAU;CAEpD,MAAM,eAAe,QAAQ,eAAe,qBAAqB,QAC/D,aACA,KACF;CAGA,MAAM,MAAgE,CAAC;CACvE,MAAM,iCAAiB,IAAI,IAAoB;CAC/C,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,GAC/C,IAAI,KAAK,SAAS;EAChB,MAAM,gBAAgB,iBAAiB,IAAI;EAC3C,MAAM,eAAe,eAAe,IAAI,aAAa;EACrD,IAAI,gBAAgB,iBAAiB,MACnC,MAAM,IAAI,MACR,eAAe,aAAa,SAAS,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,S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