1
/**2
* Runs the VM in another isolate, reached over an RPC boundary such as a Cloudflare Durable Object3
* stub, while tools keep running in the caller.4
*5
* Problem: a VM on the calling thread blocks that thread while the script computes. In a Durable6
* Object that serves an agent session, a CPU-heavy script would stall every other request to the7
* session (including the user's abort) for seconds. Measured on Cloudflare (October 2026), a8
* script that computed for 10 seconds delayed the session's other requests by 10 seconds when it9
* ran in the session object or in a Dynamic Worker, but by about 50 ms when it ran in a Durable10
* Object of a separately deployed Worker.11
*12
* Solution: the caller keeps the host role (`RemoteCodemodeSandbox`: tools, call records,13
* deadline, abort) and the remote side only runs the VM (`serveCodemodeRemote`, behind14
* `CodemodeSandboxDurableObject` in `@earendil-works/pi-codemode/cloudflare`).15
*16
* Protocol, one RPC call per execution:17
*18
* client remote19
* remote.execute(request, exchange) ───────▶ starts the VM (in-thread, with interrupt budget)20
* ◀─────── exchange([...outputs, call]) one call per tool call21
* runs the tool, replies with result ──────▶ VM continues22
* ◀─────── exchange([...outputs, done]) terminal, reply ignored23
* execute() resolves ◀────────────────────── VM disposed24
*25
* `exchange` is a function the client passes in; over Workers RPC it becomes a stub that calls back26
* into the client. Output is buffered on the remote side and sent with the next call or the27
* terminal message, so a script that prints in a loop does not make one RPC per line. Each28
* `exchange` carries at most one call, so concurrent tool calls are concurrent RPCs. Calls on one29
* stub are delivered in order, which keeps output ordered before the call or result that follows.30
*31
* Termination: the client cannot interrupt a remote VM that is computing. When the client finishes32
* first (deadline, abort, `close()`), it answers every pending and later `exchange` with33
* `{ type: "stop" }`, and the remote stops the VM at that point. A script that computes without34
* calling a tool runs until its interrupt budget is used up. The remote reports that as a35
* `failure` message, which the client turns into the same `kind: "timeout"` error an in-thread36
* VM produces.37
*38
* Failure: if the RPC call rejects (the remote isolate crashed, hit its CPU limit, or was39
* redeployed) or returns without a terminal message, the execution fails with `kind: "sandbox"`.40
*/41
import type { CodemodeError, CodemodeSandboxBaseOptions } from "../types.ts";42
import type { CodemodeWasmModule } from "../wasm.ts";43
import { CodemodeSandboxBase, errorMessage, type VmChannel, type VmLauncher } from "./execution.ts";44
import { DEFAULT_INTERRUPT_BUDGET, inlineLauncher } from "./inline.ts";45
import {46
type HostToWorkerMessage,47
isWorkerToHostMessage,48
type VmStartData,49
type WorkerToHostMessage,50
} from "./protocol.ts";52
export interface CodemodeRemoteRequest {53
data: VmStartData;54
/** Requested interrupt budget. The remote may lower it, see {@link CodemodeServeOptions}. */55
interruptBudget?: number;56
}58
/** What the remote sends to the client: VM messages, or a failure outside the VM bridge. */59
export type CodemodeRemoteMessage = WorkerToHostMessage | { type: "failure"; error: CodemodeError };61
/**62
* The client's answer to an exchange: the result of the call the exchange carried, `null` when it63
* carried no call, or `stop` once the client no longer wants the execution.64
*/65
export type CodemodeRemoteReply = HostToWorkerMessage | { type: "stop" } | null;67
export type CodemodeRemoteExchange = (messages: CodemodeRemoteMessage[]) => Promise<CodemodeRemoteReply>;69
/**70
* The remote end, usually a Durable Object stub for `CodemodeSandboxDurableObject`. Anything with71
* this method works, for example an in-process object in tests.72
*/73
export interface CodemodeRemote {74
execute(request: CodemodeRemoteRequest, exchange: CodemodeRemoteExchange): Promise<void>;75
}77
export interface RemoteCodemodeSandboxOptions extends CodemodeSandboxBaseOptions {78
/**79
* Returns the remote that runs one execution, called once per `execute()`. For a Durable Object,80
* pick the instance here, for example `() => env.CODEMODE_SANDBOX.getByName(sessionId)`.81
*/82
remote: () => CodemodeRemote;83
/** Interrupt budget requested from the remote. Default: the remote's default. */84
interruptBudget?: number;85
}87
/** Output buffered on the remote before it is flushed without waiting for a call. */88
const FLUSH_ITEMS = 1_000;89
const FLUSH_CHARS = 1 << 20;91
export interface CodemodeServeOptions {92
wasm: CodemodeWasmModule | Promise<CodemodeWasmModule>;93
/** Upper bound for a request's interrupt budget, and the budget when a request names none. */94
maxInterruptBudget?: number;95
/** Upper bound for a request's VM memory, and the limit when a request names none. */96
maxMemoryLimitBytes?: number;97
}99
/**100
* Remote side of {@link RemoteCodemodeSandbox}: runs one execution's VM on this thread and101
* forwards everything it reports through `exchange`. Resolves once the VM has stopped and the102
* terminal message has been delivered, or the client asked to stop. Never rejects.103
*/104
export function serveCodemodeRemote(105
request: CodemodeRemoteRequest,106
exchange: CodemodeRemoteExchange,107
options: CodemodeServeOptions,108
): Promise<void> {109
const maxBudget = options.maxInterruptBudget ?? DEFAULT_INTERRUPT_BUDGET;110
const budget = Math.min(request.interruptBudget ?? maxBudget, maxBudget);111
const requestedMemory = request.data.memoryLimitBytes;112
const maxMemory = options.maxMemoryLimitBytes;113
const memoryLimitBytes =114
requestedMemory === undefined115
? maxMemory116
: maxMemory === undefined117
? requestedMemory118
: Math.min(requestedMemory, maxMemory);119
const data: VmStartData = { ...request.data, memoryLimitBytes };121
return new Promise<void>((resolve) => {122
let channel: VmChannel | undefined;123
let ended = false;124
let buffered: CodemodeRemoteMessage[] = [];125
let bufferedChars = 0;126
/** Replies that arrived before the launcher returned the channel. */127
const unsent: HostToWorkerMessage[] = [];129
const takeBuffer = (): CodemodeRemoteMessage[] => {130
const batch = buffered;131
buffered = [];132
bufferedChars = 0;133
return batch;134
};135
const end = (terminal: CodemodeRemoteMessage | undefined): void => {136
if (ended) return;137
ended = true;138
const batch = takeBuffer();139
const delivered = terminal ? exchange([...batch, terminal]).catch(() => null) : Promise.resolve();140
void delivered141
.then(() => channel?.stop())142
.catch(() => undefined)143
.then(() => resolve());144
};145
const reply = (message: CodemodeRemoteReply): void => {146
if (ended || message === null) return;147
if (message.type === "stop") {148
end(undefined);149
return;150
}151
if (channel) channel.post(message);152
else unsent.push(message);153
};154
const onMessage = (message: unknown): void => {155
if (ended) return;156
const typed = message as WorkerToHostMessage;157
switch (typed.type) {158
case "output": {159
buffered.push(typed);160
bufferedChars += typed.item.type === "text" ? typed.item.text.length : typed.item.data.length;161
if (buffered.length >= FLUSH_ITEMS || bufferedChars >= FLUSH_CHARS) {162
exchange(takeBuffer()).then(reply, () => end(undefined));163
}164
break;165
}166
case "started":167
buffered.push(typed);168
break;169
// Sent at once: a host replaying a script waits for it to see that the script issued no further call.170
case "call":171
case "idle":172
exchange([...takeBuffer(), typed]).then(reply, () => end(undefined));173
break;174
default:175
end(typed);176
}177
};179
const launch = inlineLauncher(options.wasm, budget);180
Promise.resolve(181
launch(data, {182
message: onMessage,183
failure: (error) => end({ type: "failure", error }),184
}),185
).then(186
(started) => {187
channel = started;188
if (ended) {189
void started.stop().catch(() => undefined);190
return;191
}192
for (const message of unsent.splice(0)) started.post(message);193
},194
(error: unknown) => end({ type: "failure", error: { kind: "sandbox", message: errorMessage(error) } }),195
);196
});197
}199
function remoteLauncher(remote: () => CodemodeRemote, interruptBudget: number | undefined): VmLauncher {200
return (data, events) => {201
let stopped = false;202
let settled = false;203
const waiting = new Map<number, (reply: CodemodeRemoteReply) => void>();205
const exchange: CodemodeRemoteExchange = (messages) =>206
new Promise<CodemodeRemoteReply>((resolve) => {207
if (stopped || !Array.isArray(messages)) {208
resolve({ type: "stop" });209
return;210
}211
// Register the waiter first: the host may answer a call synchronously, for example when the212
// tool throws before returning a promise.213
const call = messages.find((message) => isWorkerToHostMessage(message) && message.type === "call");214
if (call?.type === "call") waiting.set(call.id, resolve);215
else resolve(null);216
for (const message of messages) {217
if (typeof message === "object" && message !== null && message.type === "failure") {218
settled = true;219
events.failure(message.error);220
continue;221
}222
// Malformed messages still go to the host, which fails the execution as a broken bridge.223
events.message(message);224
if (isWorkerToHostMessage(message) && (message.type === "done" || message.type === "crash"))225
settled = true;226
}227
});229
let target: CodemodeRemote;230
try {231
target = remote();232
} catch (error) {233
throw new Error(`Failed to reach the remote sandbox: ${errorMessage(error)}`);234
}235
const request: CodemodeRemoteRequest = interruptBudget === undefined ? { data } : { data, interruptBudget };236
Promise.resolve()237
.then(() => target.execute(request, exchange))238
.then(239
() => {240
if (!settled && !stopped) {241
events.failure({ kind: "sandbox", message: "Remote sandbox returned before the script settled" });242
}243
},244
(error: unknown) => {245
if (!stopped)246
events.failure({ kind: "sandbox", message: `Remote sandbox failed: ${errorMessage(error)}` });247
},248
);250
return {251
post: (message) => {252
const resolve = waiting.get(message.id);253
if (!resolve) return;254
waiting.delete(message.id);255
resolve(message);256
},257
stop: async () => {258
stopped = true;259
for (const resolve of waiting.values()) resolve({ type: "stop" });260
waiting.clear();261
},262
};263
};264
}266
/**267
* Runs each execution's VM on a remote, usually a Cloudflare Durable Object deployed with268
* `CodemodeSandboxDurableObject`, while tools run here. Same API and results as269
* `CodemodeSandbox`, so it can replace it. Differences: a script that computes without calling a270
* tool is limited by the remote's interrupt budget rather than `timeoutMs`, and after a deadline or271
* abort the remote VM keeps computing until it next calls a tool or uses up that budget.272
*/273
export class RemoteCodemodeSandbox extends CodemodeSandboxBase {274
constructor(options: RemoteCodemodeSandboxOptions) {275
super(options, remoteLauncher(options.remote, options.interruptBudget));276
}277
}