operon-sandbox 0.1.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +55 -0
- package/README.md +51 -0
- package/dist/cloudflare/cf-api.d.ts +115 -0
- package/dist/cloudflare/cf-api.js +13 -0
- package/dist/cloudflare/lifecycle.d.ts +64 -0
- package/dist/cloudflare/lifecycle.js +88 -0
- package/dist/cloudflare/machine.d.ts +87 -0
- package/dist/cloudflare/machine.js +342 -0
- package/dist/e2b/e2b-api.d.ts +84 -0
- package/dist/e2b/e2b-api.js +10 -0
- package/dist/e2b/lifecycle.d.ts +83 -0
- package/dist/e2b/lifecycle.js +120 -0
- package/dist/e2b/machine.d.ts +69 -0
- package/dist/e2b/machine.js +281 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +5 -0
- package/dist/shared/remote-file-ops.d.ts +38 -0
- package/dist/shared/remote-file-ops.js +66 -0
- package/dist/shared/sandbox-machine.d.ts +38 -0
- package/dist/shared/sandbox-machine.js +97 -0
- package/dist/types.d.ts +39 -0
- package/dist/types.js +2 -0
- package/package.json +50 -0
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { readWindowViaShell, sliceRange } from "../shared/remote-file-ops.js";
|
|
3
|
+
import { SandboxMachine } from "../shared/sandbox-machine.js";
|
|
4
|
+
const DEFAULT_CWD = "/workspace";
|
|
5
|
+
/**
|
|
6
|
+
* A `Machine` backed directly by `@cloudflare/sandbox`'s route-transport client.
|
|
7
|
+
*
|
|
8
|
+
* Direct rather than through a general sandbox abstraction for the same reason as the E2B
|
|
9
|
+
* adapter: the vendor natively provides a per-command timeout, incremental output and a real
|
|
10
|
+
* kill, and a lowest-common-denominator layer in between can express none of the three.
|
|
11
|
+
*
|
|
12
|
+
* Backend limits, surfaced rather than papered over:
|
|
13
|
+
* - No public port URLs. The SDK implements tunnels on the RPC transport only, so
|
|
14
|
+
* `exposedPortUrl` truthfully returns `undefined` here instead of inventing a host.
|
|
15
|
+
* - `listFiles` reports directory-or-not, with no symlink kind, so `DirEntry.kind` is not
|
|
16
|
+
* strict lstat semantics (a symlink reads as its target's kind — see `listDir`).
|
|
17
|
+
* - No stat API, so `fileInfo` costs one `stat(1)` command.
|
|
18
|
+
* - Bytes move as base64: the transport takes a string, and `writeFileStream` is RPC-only.
|
|
19
|
+
*/
|
|
20
|
+
export class CloudflareMachine extends SandboxMachine {
|
|
21
|
+
name = "cloudflare";
|
|
22
|
+
osEnv;
|
|
23
|
+
clientRef;
|
|
24
|
+
cwd;
|
|
25
|
+
sessionId;
|
|
26
|
+
defaultTimeoutMs;
|
|
27
|
+
constructor(client, options = {}) {
|
|
28
|
+
super();
|
|
29
|
+
this.clientRef = typeof client === "function" ? client : () => client;
|
|
30
|
+
this.cwd = normalizeAbs(options.cwd ?? DEFAULT_CWD);
|
|
31
|
+
this.sessionId = options.sessionId ?? "default";
|
|
32
|
+
this.defaultTimeoutMs = options.defaultTimeoutMs;
|
|
33
|
+
const shellPath = options.shellPath ?? "/bin/bash";
|
|
34
|
+
this.osEnv = {
|
|
35
|
+
osKind: "Linux",
|
|
36
|
+
osArch: "unknown",
|
|
37
|
+
osVersion: "unknown",
|
|
38
|
+
shellName: posix.basename(shellPath),
|
|
39
|
+
shellPath,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
get client() {
|
|
43
|
+
return this.clientRef();
|
|
44
|
+
}
|
|
45
|
+
// ---- identity & paths ----
|
|
46
|
+
pathClass() {
|
|
47
|
+
return "posix";
|
|
48
|
+
}
|
|
49
|
+
normpath(path) {
|
|
50
|
+
return posix.normalize(path);
|
|
51
|
+
}
|
|
52
|
+
gethome() {
|
|
53
|
+
return DEFAULT_CWD;
|
|
54
|
+
}
|
|
55
|
+
getcwd() {
|
|
56
|
+
return this.cwd;
|
|
57
|
+
}
|
|
58
|
+
withCwd(cwd) {
|
|
59
|
+
const clone = new CloudflareMachine(this.clientRef, {
|
|
60
|
+
cwd: this.resolve(cwd),
|
|
61
|
+
sessionId: this.sessionId,
|
|
62
|
+
shellPath: this.osEnv.shellPath,
|
|
63
|
+
...(this.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: this.defaultTimeoutMs } : {}),
|
|
64
|
+
});
|
|
65
|
+
// One sandbox, one file namespace — clones must share write locks.
|
|
66
|
+
clone.pathLocks = this.pathLocks;
|
|
67
|
+
return clone;
|
|
68
|
+
}
|
|
69
|
+
// ---- commands ----
|
|
70
|
+
/**
|
|
71
|
+
* Two paths, because the vendor splits the capability in two:
|
|
72
|
+
*
|
|
73
|
+
* - `commands.execute` is ONE round trip with a native timeout, but hands back no handle,
|
|
74
|
+
* so nothing can cancel it mid-flight.
|
|
75
|
+
* - `processes.startProcess` returns a `processId` immediately — the handle that makes
|
|
76
|
+
* `killProcess` (and therefore abort, and a cap that actually stops the command) real —
|
|
77
|
+
* with output arriving as an SSE log stream.
|
|
78
|
+
*
|
|
79
|
+
* So a plain "run this and give me the output" takes the cheap path, and anything that
|
|
80
|
+
* asked for cancellation, incremental output or an output cap takes the process path. The
|
|
81
|
+
* caller states intent once; which mechanism delivers it stays in here.
|
|
82
|
+
*/
|
|
83
|
+
async run(argv, options = {}) {
|
|
84
|
+
if (options.signal?.aborted) {
|
|
85
|
+
return { stdout: "", stderr: "", exitCode: undefined, timedOut: false, truncated: false, terminated: true };
|
|
86
|
+
}
|
|
87
|
+
// The route transport has no stdin channel at all — neither `commands.execute` nor
|
|
88
|
+
// `processes.startProcess` accepts one. Refuse rather than drop it: a command fed no
|
|
89
|
+
// input would see EOF and "succeed" on empty data.
|
|
90
|
+
if (options.stdin !== undefined) {
|
|
91
|
+
throw new Error("CloudflareMachine: this transport has no stdin channel, so run({ stdin }) cannot be honored.");
|
|
92
|
+
}
|
|
93
|
+
const needsHandle = options.onOutput !== undefined || options.signal !== undefined || options.maxOutputBytes !== undefined;
|
|
94
|
+
return needsHandle ? await this.runViaProcess(argv, options) : await this.runViaExecute(argv, options);
|
|
95
|
+
}
|
|
96
|
+
/** Cheap path: one request, native timeout, no cancellation. */
|
|
97
|
+
async runViaExecute(argv, options) {
|
|
98
|
+
const timeoutMs = options.timeoutMs ?? this.defaultTimeoutMs;
|
|
99
|
+
const result = await this.client.commands.execute(shellJoin(argv), this.sessionId, {
|
|
100
|
+
cwd: options.cwd !== undefined ? this.resolve(options.cwd) : this.cwd,
|
|
101
|
+
...(options.env !== undefined ? { env: options.env } : {}),
|
|
102
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
103
|
+
});
|
|
104
|
+
options.onOutput?.({ stream: "stdout", data: result.stdout });
|
|
105
|
+
return {
|
|
106
|
+
stdout: result.stdout,
|
|
107
|
+
stderr: result.stderr,
|
|
108
|
+
exitCode: result.exitCode,
|
|
109
|
+
timedOut: false,
|
|
110
|
+
truncated: false,
|
|
111
|
+
terminated: false,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Cancellable path: a processId to kill, plus an SSE log stream for incremental output. */
|
|
115
|
+
async runViaProcess(argv, options) {
|
|
116
|
+
const timeoutMs = options.timeoutMs ?? this.defaultTimeoutMs;
|
|
117
|
+
const started = await this.client.processes.startProcess(shellJoin(argv), this.sessionId, {
|
|
118
|
+
cwd: options.cwd !== undefined ? this.resolve(options.cwd) : this.cwd,
|
|
119
|
+
...(options.env !== undefined ? { env: options.env } : {}),
|
|
120
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
121
|
+
});
|
|
122
|
+
const processId = started.processId;
|
|
123
|
+
const cap = options.maxOutputBytes ?? Number.POSITIVE_INFINITY;
|
|
124
|
+
let out = "";
|
|
125
|
+
let err = "";
|
|
126
|
+
let bytes = 0;
|
|
127
|
+
let truncated = false;
|
|
128
|
+
let exitCode;
|
|
129
|
+
let timedOut = false;
|
|
130
|
+
let terminated = false;
|
|
131
|
+
let stopping;
|
|
132
|
+
const stop = () => (stopping ??= this.kill(processId).then((ok) => void (terminated = ok)));
|
|
133
|
+
const collect = (stream, data) => {
|
|
134
|
+
options.onOutput?.({ stream, data });
|
|
135
|
+
if (truncated)
|
|
136
|
+
return;
|
|
137
|
+
const room = cap - bytes;
|
|
138
|
+
if (data.length >= room) {
|
|
139
|
+
const kept = data.slice(0, Math.max(0, room));
|
|
140
|
+
if (stream === "stdout")
|
|
141
|
+
out += kept;
|
|
142
|
+
else
|
|
143
|
+
err += kept;
|
|
144
|
+
bytes = cap;
|
|
145
|
+
truncated = true;
|
|
146
|
+
// Cap reached; stop the command rather than let it keep producing output nobody reads.
|
|
147
|
+
void stop();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
bytes += data.length;
|
|
151
|
+
if (stream === "stdout")
|
|
152
|
+
out += data;
|
|
153
|
+
else
|
|
154
|
+
err += data;
|
|
155
|
+
};
|
|
156
|
+
const onAbort = () => void stop();
|
|
157
|
+
options.signal?.addEventListener("abort", onAbort);
|
|
158
|
+
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
159
|
+
timedOut = true;
|
|
160
|
+
void stop();
|
|
161
|
+
}, timeoutMs);
|
|
162
|
+
try {
|
|
163
|
+
const stream = await this.client.processes.streamProcessLogs(processId);
|
|
164
|
+
for await (const event of readLogEvents(stream)) {
|
|
165
|
+
if (event.type === "stdout" || event.type === "stderr")
|
|
166
|
+
collect(event.type, event.data ?? "");
|
|
167
|
+
else if (event.type === "exit")
|
|
168
|
+
exitCode = event.exitCode;
|
|
169
|
+
}
|
|
170
|
+
// A kill makes the log stream end at once, so without joining the in-flight stop here
|
|
171
|
+
// we would read `terminated` before it resolved and under-report every termination.
|
|
172
|
+
await stopping;
|
|
173
|
+
// The stream can end without an `exit` event (killed, or the transport dropped it);
|
|
174
|
+
// ask the process registry rather than assume success.
|
|
175
|
+
if (exitCode === undefined && !terminated && !timedOut)
|
|
176
|
+
exitCode = await this.exitCodeOf(processId);
|
|
177
|
+
return {
|
|
178
|
+
stdout: out,
|
|
179
|
+
stderr: err,
|
|
180
|
+
// A killed or timed-out command has no meaningful completion status.
|
|
181
|
+
exitCode: timedOut || terminated ? undefined : exitCode,
|
|
182
|
+
timedOut,
|
|
183
|
+
truncated,
|
|
184
|
+
terminated,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
if (timer !== undefined)
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/** Real termination, reported honestly: `false` means the command may still be running. */
|
|
194
|
+
async kill(processId) {
|
|
195
|
+
try {
|
|
196
|
+
await this.client.processes.killProcess(processId);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
async exitCodeOf(processId) {
|
|
204
|
+
try {
|
|
205
|
+
return (await this.client.processes.getProcess(processId)).process.exitCode;
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
// No `spawn`: this transport hands back no OS process, so the base class's process SPI stays
|
|
212
|
+
// unimplemented and `run` above — which every caller uses — is native instead.
|
|
213
|
+
// ---- files & metadata ----
|
|
214
|
+
// `fileInfo` comes from SandboxMachine: no stat API here either, so it costs one `stat(1)`.
|
|
215
|
+
/**
|
|
216
|
+
* One `listFiles` round trip — the vendor listing already says directory-or-not, so no
|
|
217
|
+
* stat per entry.
|
|
218
|
+
*
|
|
219
|
+
* Caveat: it carries no symlink kind, so a symlink reads as its target's kind. As on E2B,
|
|
220
|
+
* `DirEntry.kind` here is not strict lstat semantics; callers that must distinguish a
|
|
221
|
+
* symlink stat explicitly. Mapped as reported rather than guessed at.
|
|
222
|
+
*/
|
|
223
|
+
async listDir(path) {
|
|
224
|
+
const { files } = await this.client.files.listFiles(this.resolve(path), this.sessionId);
|
|
225
|
+
return files.map((entry) => ({
|
|
226
|
+
name: entry.name,
|
|
227
|
+
kind: entryKind(entry.isDirectory ?? (entry.type === "directory" || entry.type === "dir")),
|
|
228
|
+
}));
|
|
229
|
+
}
|
|
230
|
+
async mkdir(path, options) {
|
|
231
|
+
const target = this.resolve(path);
|
|
232
|
+
if (options?.parents === true) {
|
|
233
|
+
await this.client.files.mkdir(target, this.sessionId, { recursive: true });
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
// Plain mkdir must fail on an existing path. The vendor call is not documented to throw
|
|
237
|
+
// EEXIST, so check first and translate — the contract promises the POSIX behaviour.
|
|
238
|
+
const existing = await this.fileInfo(target).catch(() => undefined);
|
|
239
|
+
if (existing !== undefined) {
|
|
240
|
+
if (options?.existOk === true && existing.kind === "dir")
|
|
241
|
+
return;
|
|
242
|
+
throw codedError(`EEXIST: path already exists: ${target}`, "EEXIST");
|
|
243
|
+
}
|
|
244
|
+
await this.client.files.mkdir(target, this.sessionId);
|
|
245
|
+
}
|
|
246
|
+
async readBytes(path, range) {
|
|
247
|
+
if (range !== undefined) {
|
|
248
|
+
const window = await readWindowViaShell(this, this.resolve(path), range);
|
|
249
|
+
if (window !== undefined)
|
|
250
|
+
return window;
|
|
251
|
+
// Fall through: no `tail`/`head`/`base64` in this image. Correct, just expensive.
|
|
252
|
+
}
|
|
253
|
+
const { content } = await this.client.files.readFile(this.resolve(path), this.sessionId, { encoding: "base64" });
|
|
254
|
+
return sliceRange(Buffer.from(content, "base64"), range);
|
|
255
|
+
}
|
|
256
|
+
async writeBytesRaw(path, data) {
|
|
257
|
+
// base64 is the only binary-safe route on this transport (writeFileStream is RPC-only).
|
|
258
|
+
await this.client.files.writeFile(this.resolve(path), data.toString("base64"), this.sessionId, {
|
|
259
|
+
encoding: "base64",
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Always `undefined` on this transport: the SDK implements tunnels over RPC only, and the
|
|
264
|
+
* route transport's `tunnels` accessor throws. Saying so plainly beats inventing a URL that
|
|
265
|
+
* would not resolve.
|
|
266
|
+
*/
|
|
267
|
+
async exposedPortUrl() {
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
resolve(path) {
|
|
271
|
+
return normalizeAbs(path.startsWith("/") ? path : posix.join(this.cwd, path));
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** Decode an SSE byte stream into the `LogEvent`s the process log endpoint emits. */
|
|
275
|
+
async function* readLogEvents(stream) {
|
|
276
|
+
const decoder = new TextDecoder();
|
|
277
|
+
let buffer = "";
|
|
278
|
+
const reader = stream.getReader();
|
|
279
|
+
try {
|
|
280
|
+
while (true) {
|
|
281
|
+
const { done, value } = await reader.read();
|
|
282
|
+
if (done)
|
|
283
|
+
break;
|
|
284
|
+
buffer += decoder.decode(value, { stream: true });
|
|
285
|
+
// SSE frames are separated by a blank line; a partial tail stays buffered.
|
|
286
|
+
let split;
|
|
287
|
+
while ((split = buffer.indexOf("\n\n")) !== -1) {
|
|
288
|
+
const frame = buffer.slice(0, split);
|
|
289
|
+
buffer = buffer.slice(split + 2);
|
|
290
|
+
const event = parseSseFrame(frame);
|
|
291
|
+
if (event !== undefined)
|
|
292
|
+
yield event;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const last = parseSseFrame(buffer);
|
|
296
|
+
if (last !== undefined)
|
|
297
|
+
yield last;
|
|
298
|
+
}
|
|
299
|
+
finally {
|
|
300
|
+
reader.releaseLock();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function parseSseFrame(frame) {
|
|
304
|
+
const payload = frame
|
|
305
|
+
.split("\n")
|
|
306
|
+
.filter((line) => line.startsWith("data:"))
|
|
307
|
+
.map((line) => line.slice(5).trim())
|
|
308
|
+
.join("");
|
|
309
|
+
if (payload.length === 0)
|
|
310
|
+
return undefined;
|
|
311
|
+
try {
|
|
312
|
+
const parsed = JSON.parse(payload);
|
|
313
|
+
return typeof parsed.type === "string" ? parsed : undefined;
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
// A malformed frame is dropped rather than failing the whole run — the command's own
|
|
317
|
+
// output matters more than one unreadable log record.
|
|
318
|
+
return undefined;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function entryKind(isDir) {
|
|
322
|
+
return isDir ? "dir" : "file";
|
|
323
|
+
}
|
|
324
|
+
function normalizeAbs(path) {
|
|
325
|
+
const normalized = posix.normalize(path);
|
|
326
|
+
return normalized.startsWith("/") ? normalized : `/${normalized}`;
|
|
327
|
+
}
|
|
328
|
+
/** Cloudflare takes a command STRING; quote every argv element so nothing is re-split. */
|
|
329
|
+
export function shellJoin(argv) {
|
|
330
|
+
return argv.map(shellQuote).join(" ");
|
|
331
|
+
}
|
|
332
|
+
function shellQuote(value) {
|
|
333
|
+
if (/^[A-Za-z0-9_/@%+=:,.-]+$/.test(value))
|
|
334
|
+
return value;
|
|
335
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
336
|
+
}
|
|
337
|
+
function codedError(message, code) {
|
|
338
|
+
const error = new Error(message);
|
|
339
|
+
error.code = code;
|
|
340
|
+
return error;
|
|
341
|
+
}
|
|
342
|
+
//# sourceMappingURL=machine.js.map
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slice of the E2B SDK this adapter uses, described structurally rather than imported.
|
|
3
|
+
*
|
|
4
|
+
* Structural typing keeps `e2b` an OPTIONAL peer: the package compiles without it, tests can
|
|
5
|
+
* inject a fake, and a minor SDK release cannot break our build. The shapes mirror the E2B
|
|
6
|
+
* JS SDK v1.4 reference (`Sandbox.commands` / `Sandbox.files`); anything optional here is
|
|
7
|
+
* optional in the SDK too, or is a method we degrade gracefully without.
|
|
8
|
+
*/
|
|
9
|
+
export interface E2BCommandResult {
|
|
10
|
+
readonly stdout?: string;
|
|
11
|
+
readonly stderr?: string;
|
|
12
|
+
/** null = the SDK reported no exit status (still running / killed). */
|
|
13
|
+
readonly exitCode?: number | null;
|
|
14
|
+
readonly error?: string;
|
|
15
|
+
}
|
|
16
|
+
/** `background: true` resolves to this instead of a finished result. */
|
|
17
|
+
export interface E2BCommandHandle extends E2BCommandResult {
|
|
18
|
+
readonly pid: number;
|
|
19
|
+
wait?(): Promise<E2BCommandResult>;
|
|
20
|
+
kill?(): Promise<boolean>;
|
|
21
|
+
disconnect?(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
export interface E2BRunOpts {
|
|
24
|
+
background?: boolean;
|
|
25
|
+
cwd?: string;
|
|
26
|
+
envs?: Record<string, string>;
|
|
27
|
+
user?: string;
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
/** Incremental stdout. Present natively — this is what the OpenAI adapter never passes. */
|
|
30
|
+
onStdout?: (data: string) => void | Promise<void>;
|
|
31
|
+
onStderr?: (data: string) => void | Promise<void>;
|
|
32
|
+
stdin?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface E2BCommandsApi {
|
|
35
|
+
run(command: string, opts?: E2BRunOpts): Promise<E2BCommandResult | E2BCommandHandle>;
|
|
36
|
+
/** Real SIGKILL by pid; resolves to whether a process was actually killed. */
|
|
37
|
+
kill?(pid: number, opts?: {
|
|
38
|
+
requestTimeoutMs?: number;
|
|
39
|
+
}): Promise<boolean>;
|
|
40
|
+
sendStdin?(pid: number, data: string, opts?: {
|
|
41
|
+
requestTimeoutMs?: number;
|
|
42
|
+
}): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
/** `list()` reports only file/dir — there is no symlink value and no stat method (see machine.ts). */
|
|
45
|
+
export type E2BFileType = "file" | "dir";
|
|
46
|
+
export interface E2BEntryInfo {
|
|
47
|
+
readonly name: string;
|
|
48
|
+
readonly path: string;
|
|
49
|
+
readonly type?: E2BFileType;
|
|
50
|
+
}
|
|
51
|
+
export interface E2BFilesystemApi {
|
|
52
|
+
list(path: string, opts?: Record<string, unknown>): Promise<readonly E2BEntryInfo[]>;
|
|
53
|
+
read(path: string, opts?: {
|
|
54
|
+
format?: "text" | "bytes";
|
|
55
|
+
}): Promise<string | Uint8Array>;
|
|
56
|
+
/**
|
|
57
|
+
* `data` is deliberately NOT `Uint8Array`: the SDK takes `string | ArrayBuffer | Blob |
|
|
58
|
+
* ReadableStream`, so declaring the wider type here would let a `Buffer` typecheck against
|
|
59
|
+
* a signature that rejects it. See `writeBytesRaw` for the conversion.
|
|
60
|
+
*/
|
|
61
|
+
write(path: string, data: string | ArrayBuffer, opts?: Record<string, unknown>): Promise<unknown>;
|
|
62
|
+
makeDir?(path: string): Promise<boolean>;
|
|
63
|
+
remove?(path: string): Promise<void>;
|
|
64
|
+
exists?(path: string): Promise<boolean>;
|
|
65
|
+
}
|
|
66
|
+
export interface E2BSandbox {
|
|
67
|
+
readonly sandboxId: string;
|
|
68
|
+
readonly commands: E2BCommandsApi;
|
|
69
|
+
readonly files: E2BFilesystemApi;
|
|
70
|
+
/** Public URL for a port exposed inside the sandbox. */
|
|
71
|
+
getHost?(port: number): string | Promise<string>;
|
|
72
|
+
createSnapshot?(): Promise<{
|
|
73
|
+
snapshotId?: string;
|
|
74
|
+
}>;
|
|
75
|
+
pause?(): Promise<boolean>;
|
|
76
|
+
kill(): Promise<void | boolean>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* How to obtain the CURRENT sandbox. Deliberately a function, not a value: restoring a
|
|
80
|
+
* snapshot replaces the underlying instance (the old one gets killed), so a machine holding
|
|
81
|
+
* a captured reference would keep talking to a dead sandbox.
|
|
82
|
+
*/
|
|
83
|
+
export type SandboxRef = () => E2BSandbox;
|
|
84
|
+
//# sourceMappingURL=e2b-api.d.ts.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slice of the E2B SDK this adapter uses, described structurally rather than imported.
|
|
3
|
+
*
|
|
4
|
+
* Structural typing keeps `e2b` an OPTIONAL peer: the package compiles without it, tests can
|
|
5
|
+
* inject a fake, and a minor SDK release cannot break our build. The shapes mirror the E2B
|
|
6
|
+
* JS SDK v1.4 reference (`Sandbox.commands` / `Sandbox.files`); anything optional here is
|
|
7
|
+
* optional in the SDK too, or is a method we degrade gracefully without.
|
|
8
|
+
*/
|
|
9
|
+
export {};
|
|
10
|
+
//# sourceMappingURL=e2b-api.js.map
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { SandboxWorkspace } from "../types.ts";
|
|
2
|
+
import type { E2BSandbox } from "./e2b-api.ts";
|
|
3
|
+
import { E2BMachine, type E2BMachineOptions } from "./machine.ts";
|
|
4
|
+
/**
|
|
5
|
+
* The bits of the `Sandbox` class we call. Structural, so `e2b` stays an optional peer and
|
|
6
|
+
* tests can inject a fake factory.
|
|
7
|
+
*/
|
|
8
|
+
export interface E2BSandboxFactory {
|
|
9
|
+
create(opts?: Record<string, unknown>): Promise<E2BSandbox>;
|
|
10
|
+
connect?(sandboxId: string, opts?: Record<string, unknown>): Promise<E2BSandbox>;
|
|
11
|
+
}
|
|
12
|
+
/** Persisted between sessions so a reopen reconnects instead of starting a fresh sandbox. */
|
|
13
|
+
export interface E2BMachineState {
|
|
14
|
+
readonly sandboxId: string;
|
|
15
|
+
/** Snapshot the sandbox was last restored from, if any. */
|
|
16
|
+
readonly snapshotId?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface E2BWorkspaceOptions extends E2BMachineOptions {
|
|
19
|
+
/** Usually the `Sandbox` class from the `e2b` package. */
|
|
20
|
+
readonly sandbox: E2BSandboxFactory;
|
|
21
|
+
/** Template/base image id for a fresh sandbox. */
|
|
22
|
+
readonly template?: string;
|
|
23
|
+
readonly envs?: Record<string, string>;
|
|
24
|
+
/** Sandbox-level inactivity timeout (distinct from a command's timeout). */
|
|
25
|
+
readonly timeoutMs?: number;
|
|
26
|
+
/** Prepare a fresh workspace (clone a repo, drop config files). Runs only on creation. */
|
|
27
|
+
readonly prepare?: (machine: E2BMachine) => Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Lifecycle for a directly-driven E2B sandbox: create or reconnect on open, snapshot on
|
|
31
|
+
* demand, restore by replacing the instance.
|
|
32
|
+
*
|
|
33
|
+
* Restore is the subtle part. E2B restores a snapshot by starting a NEW sandbox from it, so
|
|
34
|
+
* the old instance is dead afterwards. Everything therefore reads the sandbox through a
|
|
35
|
+
* mutable cell rather than capturing it — `E2BMachine` holds `() => current`, so a restore
|
|
36
|
+
* is transparent to every tool already holding the machine.
|
|
37
|
+
*/
|
|
38
|
+
export declare class E2BWorkspace implements SandboxWorkspace {
|
|
39
|
+
private current;
|
|
40
|
+
private readonly factory;
|
|
41
|
+
private readonly options;
|
|
42
|
+
readonly machine: E2BMachine;
|
|
43
|
+
private constructor();
|
|
44
|
+
static open(options: E2BWorkspaceOptions, state?: E2BMachineState): Promise<E2BWorkspace>;
|
|
45
|
+
get id(): string;
|
|
46
|
+
state(): E2BMachineState;
|
|
47
|
+
/** Capture the workspace. Returns undefined when the plan/template has no snapshot support. */
|
|
48
|
+
snapshot(): Promise<string | undefined>;
|
|
49
|
+
/**
|
|
50
|
+
* Restore a snapshot by starting a replacement sandbox from it and retiring the old one.
|
|
51
|
+
* The machine keeps working because it reads `current` through a closure.
|
|
52
|
+
*/
|
|
53
|
+
restore(snapshotId: string): Promise<void>;
|
|
54
|
+
/** Fork the workspace: snapshot, then start an independent sandbox from that snapshot. */
|
|
55
|
+
fork(): Promise<{
|
|
56
|
+
machine: E2BMachine;
|
|
57
|
+
dispose: () => Promise<void>;
|
|
58
|
+
} | undefined>;
|
|
59
|
+
/** E2B supports pause on some plans only; `false` means the sandbox is still running. */
|
|
60
|
+
pause(): Promise<boolean>;
|
|
61
|
+
kill(): Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* No `e2bMachineFactory` here on purpose.
|
|
65
|
+
*
|
|
66
|
+
* A factory that created a sandbox per session, stored its id in the session's state and
|
|
67
|
+
* killed it on session close got three things wrong at once: every new session started a
|
|
68
|
+
* fresh sandbox (so one user ended up with N), closing any session pulled the sandbox out
|
|
69
|
+
* from under the others, and forking a session copied the sandbox id — silently giving two
|
|
70
|
+
* "independent" sessions one shared filesystem.
|
|
71
|
+
*
|
|
72
|
+
* A sandbox is a user- or workspace-scoped resource. So the host owns it:
|
|
73
|
+
*
|
|
74
|
+
* const workspace = await E2BWorkspace.open({ sandbox: Sandbox, template: "node20" });
|
|
75
|
+
* await materializeWorkspace(workspace.machine, spec); // prepare it once
|
|
76
|
+
* const harness = new Harness({ machine: workspace.machine });
|
|
77
|
+
* // ...every session — new, resumed, forked — runs in that one sandbox, and the host
|
|
78
|
+
* // calls workspace.close() when the USER is done, not when a session is.
|
|
79
|
+
*
|
|
80
|
+
* Persisting `workspace.state().sandboxId` for a later reconnect is the host's call too;
|
|
81
|
+
* pass it back to `E2BWorkspace.open` as the second argument.
|
|
82
|
+
*/
|
|
83
|
+
//# sourceMappingURL=lifecycle.d.ts.map
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { E2BMachine } from "./machine.js";
|
|
2
|
+
/**
|
|
3
|
+
* Lifecycle for a directly-driven E2B sandbox: create or reconnect on open, snapshot on
|
|
4
|
+
* demand, restore by replacing the instance.
|
|
5
|
+
*
|
|
6
|
+
* Restore is the subtle part. E2B restores a snapshot by starting a NEW sandbox from it, so
|
|
7
|
+
* the old instance is dead afterwards. Everything therefore reads the sandbox through a
|
|
8
|
+
* mutable cell rather than capturing it — `E2BMachine` holds `() => current`, so a restore
|
|
9
|
+
* is transparent to every tool already holding the machine.
|
|
10
|
+
*/
|
|
11
|
+
export class E2BWorkspace {
|
|
12
|
+
current;
|
|
13
|
+
factory;
|
|
14
|
+
options;
|
|
15
|
+
machine;
|
|
16
|
+
constructor(sandbox, options) {
|
|
17
|
+
this.current = sandbox;
|
|
18
|
+
this.factory = options.sandbox;
|
|
19
|
+
this.options = options;
|
|
20
|
+
this.machine = new E2BMachine(() => this.current, options);
|
|
21
|
+
}
|
|
22
|
+
static async open(options, state) {
|
|
23
|
+
const sandbox = await openSandbox(options, state);
|
|
24
|
+
const workspace = new E2BWorkspace(sandbox, options);
|
|
25
|
+
if (state === undefined && options.prepare !== undefined)
|
|
26
|
+
await options.prepare(workspace.machine);
|
|
27
|
+
return workspace;
|
|
28
|
+
}
|
|
29
|
+
get id() {
|
|
30
|
+
return this.current.sandboxId;
|
|
31
|
+
}
|
|
32
|
+
state() {
|
|
33
|
+
return { sandboxId: this.current.sandboxId };
|
|
34
|
+
}
|
|
35
|
+
/** Capture the workspace. Returns undefined when the plan/template has no snapshot support. */
|
|
36
|
+
async snapshot() {
|
|
37
|
+
if (this.current.createSnapshot === undefined)
|
|
38
|
+
return undefined;
|
|
39
|
+
const { snapshotId } = await this.current.createSnapshot();
|
|
40
|
+
return snapshotId;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Restore a snapshot by starting a replacement sandbox from it and retiring the old one.
|
|
44
|
+
* The machine keeps working because it reads `current` through a closure.
|
|
45
|
+
*/
|
|
46
|
+
async restore(snapshotId) {
|
|
47
|
+
const replacement = await this.factory.create({
|
|
48
|
+
template: snapshotId,
|
|
49
|
+
...(this.options.envs !== undefined ? { envs: this.options.envs } : {}),
|
|
50
|
+
...(this.options.timeoutMs !== undefined ? { timeoutMs: this.options.timeoutMs } : {}),
|
|
51
|
+
});
|
|
52
|
+
const previous = this.current;
|
|
53
|
+
this.current = replacement;
|
|
54
|
+
// Retire the old sandbox after the swap: a failure to clean up must not cost us the
|
|
55
|
+
// restored workspace we already hold.
|
|
56
|
+
await previous.kill().catch(() => undefined);
|
|
57
|
+
}
|
|
58
|
+
/** Fork the workspace: snapshot, then start an independent sandbox from that snapshot. */
|
|
59
|
+
async fork() {
|
|
60
|
+
const snapshotId = await this.snapshot();
|
|
61
|
+
if (snapshotId === undefined)
|
|
62
|
+
return undefined;
|
|
63
|
+
const clone = await this.factory.create({
|
|
64
|
+
template: snapshotId,
|
|
65
|
+
...(this.options.envs !== undefined ? { envs: this.options.envs } : {}),
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
machine: new E2BMachine(() => clone, this.options),
|
|
69
|
+
dispose: async () => void (await clone.kill().catch(() => undefined)),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** E2B supports pause on some plans only; `false` means the sandbox is still running. */
|
|
73
|
+
async pause() {
|
|
74
|
+
if (this.current.pause === undefined)
|
|
75
|
+
return false;
|
|
76
|
+
return await this.current.pause().catch(() => false);
|
|
77
|
+
}
|
|
78
|
+
async kill() {
|
|
79
|
+
await this.current.kill().catch(() => undefined);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function openSandbox(options, state) {
|
|
83
|
+
if (state !== undefined && options.sandbox.connect !== undefined) {
|
|
84
|
+
try {
|
|
85
|
+
return await options.sandbox.connect(state.sandboxId, {
|
|
86
|
+
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
// Sandbox is gone (expired/deleted) — fall through and start a fresh one rather than
|
|
91
|
+
// failing the session open.
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return await options.sandbox.create({
|
|
95
|
+
...(options.template !== undefined ? { template: options.template } : {}),
|
|
96
|
+
...(options.envs !== undefined ? { envs: options.envs } : {}),
|
|
97
|
+
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* No `e2bMachineFactory` here on purpose.
|
|
102
|
+
*
|
|
103
|
+
* A factory that created a sandbox per session, stored its id in the session's state and
|
|
104
|
+
* killed it on session close got three things wrong at once: every new session started a
|
|
105
|
+
* fresh sandbox (so one user ended up with N), closing any session pulled the sandbox out
|
|
106
|
+
* from under the others, and forking a session copied the sandbox id — silently giving two
|
|
107
|
+
* "independent" sessions one shared filesystem.
|
|
108
|
+
*
|
|
109
|
+
* A sandbox is a user- or workspace-scoped resource. So the host owns it:
|
|
110
|
+
*
|
|
111
|
+
* const workspace = await E2BWorkspace.open({ sandbox: Sandbox, template: "node20" });
|
|
112
|
+
* await materializeWorkspace(workspace.machine, spec); // prepare it once
|
|
113
|
+
* const harness = new Harness({ machine: workspace.machine });
|
|
114
|
+
* // ...every session — new, resumed, forked — runs in that one sandbox, and the host
|
|
115
|
+
* // calls workspace.close() when the USER is done, not when a session is.
|
|
116
|
+
*
|
|
117
|
+
* Persisting `workspace.state().sandboxId` for a later reconnect is the host's call too;
|
|
118
|
+
* pass it back to `E2BWorkspace.open` as the second argument.
|
|
119
|
+
*/
|
|
120
|
+
//# sourceMappingURL=lifecycle.js.map
|