@quietrobot/sandboxes 0.0.0-stage → 0.2.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 +201 -0
- package/README.md +139 -2
- package/dist/e2b.d.ts +238 -0
- package/dist/e2b.js +353 -0
- package/dist/index.d.ts +692 -0
- package/dist/index.js +639 -0
- package/dist/kernel.d.ts +1 -0
- package/dist/kernel.js +2 -0
- package/package.json +48 -4
package/dist/e2b.js
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* E2B-compatible mode. Switch with one line:
|
|
3
|
+
*
|
|
4
|
+
* - import { Sandbox } from "e2b"; // or "@e2b/code-interpreter"
|
|
5
|
+
* + import { Sandbox } from "@quietrobot/sandboxes/e2b";
|
|
6
|
+
*
|
|
7
|
+
* The common calls keep their names and shapes: Sandbox.create, connect, kill,
|
|
8
|
+
* commands.run (foreground and background, onStdout/onStderr), files.read /
|
|
9
|
+
* write / list / remove / exists / makeDir, getHost, setTimeout, runCode,
|
|
10
|
+
* pause. Reads QR_API_KEY. Every command still goes through your
|
|
11
|
+
* organization's policy, so one a rule holds waits for a person's approval.
|
|
12
|
+
*
|
|
13
|
+
* Differences worth knowing:
|
|
14
|
+
* - Templates are ours (base, minimal) or a snapshot id; E2B template names
|
|
15
|
+
* fall back to base.
|
|
16
|
+
* - getHost(port) exposes the port as a public preview URL the first time
|
|
17
|
+
* you ask for it. Use exposePort(port, "private") for a private one.
|
|
18
|
+
* - allowInternetAccess maps to egress; left out, your policy's default applies.
|
|
19
|
+
*/
|
|
20
|
+
import { CommandDeniedError, Sandboxes, SandboxesError, } from "./index.js";
|
|
21
|
+
export { CommandDeniedError, SandboxesError };
|
|
22
|
+
export class CommandExitError extends SandboxesError {
|
|
23
|
+
result;
|
|
24
|
+
constructor(result) {
|
|
25
|
+
super(0, "command_exit", result.error ?? `Command exited with code ${result.exitCode}`);
|
|
26
|
+
this.result = result;
|
|
27
|
+
this.name = "CommandExitError";
|
|
28
|
+
}
|
|
29
|
+
get exitCode() {
|
|
30
|
+
return this.result.exitCode;
|
|
31
|
+
}
|
|
32
|
+
get error() {
|
|
33
|
+
return this.result.error;
|
|
34
|
+
}
|
|
35
|
+
get stdout() {
|
|
36
|
+
return this.result.stdout;
|
|
37
|
+
}
|
|
38
|
+
get stderr() {
|
|
39
|
+
return this.result.stderr;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export class TimeoutError extends SandboxesError {
|
|
43
|
+
constructor(message) {
|
|
44
|
+
super(408, "timeout", message);
|
|
45
|
+
this.name = "TimeoutError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function toResult(e) {
|
|
49
|
+
const exitCode = e.exitCode ?? (e.status === "completed" ? 0 : 1);
|
|
50
|
+
const error = e.status === "failed" || e.timedOut ? (e.timedOut ? "Command timed out" : e.stderr || "Command failed") : undefined;
|
|
51
|
+
return { exitCode, error, stdout: e.stdout ?? "", stderr: e.stderr ?? "" };
|
|
52
|
+
}
|
|
53
|
+
function check(r) {
|
|
54
|
+
if (r.exitCode !== 0)
|
|
55
|
+
throw new CommandExitError(r);
|
|
56
|
+
return r;
|
|
57
|
+
}
|
|
58
|
+
/** A background command: what commands.run({ background: true }) returns. */
|
|
59
|
+
export class CommandHandle {
|
|
60
|
+
proc;
|
|
61
|
+
opts;
|
|
62
|
+
stdout = "";
|
|
63
|
+
stderr = "";
|
|
64
|
+
result;
|
|
65
|
+
constructor(proc, opts) {
|
|
66
|
+
this.proc = proc;
|
|
67
|
+
this.opts = opts;
|
|
68
|
+
}
|
|
69
|
+
/** Our execution id. E2B calls it pid; pass it to commands.connect / kill. */
|
|
70
|
+
get pid() {
|
|
71
|
+
return this.proc.id;
|
|
72
|
+
}
|
|
73
|
+
get exitCode() {
|
|
74
|
+
return this.proc.done ? (this.proc.exitCode ?? undefined) : undefined;
|
|
75
|
+
}
|
|
76
|
+
/** Waits for the end. Throws CommandExitError on a non-zero exit, like E2B. */
|
|
77
|
+
wait() {
|
|
78
|
+
this.result ??= this.proc
|
|
79
|
+
.wait({
|
|
80
|
+
onStdout: (d) => {
|
|
81
|
+
this.stdout += d;
|
|
82
|
+
void this.opts.onStdout?.(d);
|
|
83
|
+
},
|
|
84
|
+
onStderr: (d) => {
|
|
85
|
+
this.stderr += d;
|
|
86
|
+
void this.opts.onStderr?.(d);
|
|
87
|
+
},
|
|
88
|
+
})
|
|
89
|
+
.then(toResult);
|
|
90
|
+
return this.result.then(check);
|
|
91
|
+
}
|
|
92
|
+
async sendStdin(data) {
|
|
93
|
+
await this.proc.sendStdin(data);
|
|
94
|
+
}
|
|
95
|
+
async kill() {
|
|
96
|
+
await this.proc.kill("KILL");
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
/** Stop reading output; the command keeps running. */
|
|
100
|
+
async disconnect() { }
|
|
101
|
+
}
|
|
102
|
+
class Commands {
|
|
103
|
+
sbx;
|
|
104
|
+
constructor(sbx) {
|
|
105
|
+
this.sbx = sbx;
|
|
106
|
+
}
|
|
107
|
+
async run(cmd, opts = {}) {
|
|
108
|
+
if (opts.background || opts.stdin) {
|
|
109
|
+
const p = await this.sbx.spawn(cmd, { cwd: opts.cwd, env: opts.envs, timeoutMs: opts.timeoutMs ?? (opts.background ? 0 : 60_000), interactive: opts.stdin });
|
|
110
|
+
const h = new CommandHandle(p, opts);
|
|
111
|
+
if (opts.background) {
|
|
112
|
+
// E2B starts delivering output to the callbacks at once.
|
|
113
|
+
if (opts.onStdout || opts.onStderr)
|
|
114
|
+
void h.wait().catch(() => { });
|
|
115
|
+
return h;
|
|
116
|
+
}
|
|
117
|
+
return h.wait();
|
|
118
|
+
}
|
|
119
|
+
const e = await this.sbx.exec(cmd, {
|
|
120
|
+
cwd: opts.cwd,
|
|
121
|
+
env: opts.envs,
|
|
122
|
+
timeoutMs: opts.timeoutMs ?? 60_000,
|
|
123
|
+
onStdout: opts.onStdout ? (d) => void opts.onStdout(d) : undefined,
|
|
124
|
+
onStderr: opts.onStderr ? (d) => void opts.onStderr(d) : undefined,
|
|
125
|
+
});
|
|
126
|
+
return check(toResult(e));
|
|
127
|
+
}
|
|
128
|
+
/** Reattach to a background command by its pid (our execution id). */
|
|
129
|
+
async connect(pid, opts = {}) {
|
|
130
|
+
const h = new CommandHandle(await this.sbx.process(pid), opts);
|
|
131
|
+
if (opts.onStdout || opts.onStderr)
|
|
132
|
+
void h.wait().catch(() => { });
|
|
133
|
+
return h;
|
|
134
|
+
}
|
|
135
|
+
async kill(pid) {
|
|
136
|
+
await (await this.sbx.process(pid)).kill("KILL");
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
async sendStdin(pid, data) {
|
|
140
|
+
await (await this.sbx.process(pid)).sendStdin(data);
|
|
141
|
+
}
|
|
142
|
+
/** Commands this sandbox has run, newest first. */
|
|
143
|
+
async list() {
|
|
144
|
+
return (await this.sbx.executions()).map((e) => ({ pid: e.id, cmd: e.cmd, status: e.status }));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
|
|
148
|
+
class Filesystem {
|
|
149
|
+
sbx;
|
|
150
|
+
constructor(sbx) {
|
|
151
|
+
this.sbx = sbx;
|
|
152
|
+
}
|
|
153
|
+
async read(path, opts = {}) {
|
|
154
|
+
const b = await this.sbx.files.read(path);
|
|
155
|
+
if (opts.format === "bytes")
|
|
156
|
+
return b;
|
|
157
|
+
if (opts.format === "blob")
|
|
158
|
+
return new Blob([b]);
|
|
159
|
+
return new TextDecoder().decode(b);
|
|
160
|
+
}
|
|
161
|
+
async write(a, data) {
|
|
162
|
+
const one = async (path, d) => {
|
|
163
|
+
const body = d instanceof Blob ? new Uint8Array(await d.arrayBuffer()) : d;
|
|
164
|
+
const r = await this.sbx.files.write(path, body);
|
|
165
|
+
return { name: r.path.split("/").pop() ?? r.path, type: "file", path: r.path, size: r.bytes };
|
|
166
|
+
};
|
|
167
|
+
if (typeof a === "string")
|
|
168
|
+
return one(a, data);
|
|
169
|
+
const out = [];
|
|
170
|
+
for (const f of a)
|
|
171
|
+
out.push(await one(f.path, f.data));
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
async list(path) {
|
|
175
|
+
const r = await this.sbx.files.list(path);
|
|
176
|
+
return r.entries.map((e) => ({
|
|
177
|
+
name: e.name,
|
|
178
|
+
type: e.type === "dir" || e.type === "directory" ? "dir" : "file",
|
|
179
|
+
path: e.path,
|
|
180
|
+
size: e.size,
|
|
181
|
+
modifiedTime: e.modified ? new Date(e.modified) : undefined,
|
|
182
|
+
}));
|
|
183
|
+
}
|
|
184
|
+
async exists(path) {
|
|
185
|
+
return (await this.sbx.exec(`test -e ${q(path)}`)).exitCode === 0;
|
|
186
|
+
}
|
|
187
|
+
async makeDir(path) {
|
|
188
|
+
const existed = await this.exists(path);
|
|
189
|
+
if (!existed)
|
|
190
|
+
await this.sbx.exec(`mkdir -p ${q(path)}`);
|
|
191
|
+
return !existed;
|
|
192
|
+
}
|
|
193
|
+
async remove(path) {
|
|
194
|
+
await this.sbx.files.remove(path);
|
|
195
|
+
}
|
|
196
|
+
async rename(oldPath, newPath) {
|
|
197
|
+
const e = await this.sbx.exec(`mv ${q(oldPath)} ${q(newPath)}`);
|
|
198
|
+
if (e.exitCode !== 0)
|
|
199
|
+
throw new SandboxesError(400, "rename_failed", e.stderr || "rename failed");
|
|
200
|
+
return { name: newPath.split("/").pop() ?? newPath, type: "file", path: newPath, size: 0 };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** runCode()'s answer, shaped like @e2b/code-interpreter's Execution. */
|
|
204
|
+
export class CodeExecution {
|
|
205
|
+
results;
|
|
206
|
+
logs;
|
|
207
|
+
error;
|
|
208
|
+
constructor(results, logs, error) {
|
|
209
|
+
this.results = results;
|
|
210
|
+
this.logs = logs;
|
|
211
|
+
this.error = error;
|
|
212
|
+
}
|
|
213
|
+
/** The main result's text, if any. */
|
|
214
|
+
get text() {
|
|
215
|
+
return this.results.find((r) => r.isMainResult)?.text;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function makeClient(o = {}) {
|
|
219
|
+
return new Sandboxes({ apiKey: o.apiKey, baseUrl: o.domain });
|
|
220
|
+
}
|
|
221
|
+
function createBody(template, o) {
|
|
222
|
+
const t = template ?? o.template;
|
|
223
|
+
const ours = {
|
|
224
|
+
timeoutSec: Math.max(10, Math.round((o.timeoutMs ?? 300_000) / 1000)),
|
|
225
|
+
env: o.envs,
|
|
226
|
+
metadata: o.metadata,
|
|
227
|
+
cpus: o.cpuCount,
|
|
228
|
+
memoryMb: o.memoryMB,
|
|
229
|
+
...(o.allowInternetAccess === true ? { egress: { mode: "open" } } : o.allowInternetAccess === false ? { egress: { mode: "deny" } } : {}),
|
|
230
|
+
};
|
|
231
|
+
if (t?.startsWith("snap_"))
|
|
232
|
+
ours.snapshotId = t;
|
|
233
|
+
else if (t === "minimal" || t === "base")
|
|
234
|
+
ours.template = t;
|
|
235
|
+
return { ...ours, ...o.quietrobot };
|
|
236
|
+
}
|
|
237
|
+
export class Sandbox {
|
|
238
|
+
commands;
|
|
239
|
+
files;
|
|
240
|
+
/** For E2B code that reads sandbox.pty: our terminals are on sandbox.raw.terminal(). */
|
|
241
|
+
raw;
|
|
242
|
+
exposed = new Map();
|
|
243
|
+
/** Use Sandbox.create() or Sandbox.connect(). */
|
|
244
|
+
constructor(sbx) {
|
|
245
|
+
this.raw = sbx;
|
|
246
|
+
this.commands = new Commands(sbx);
|
|
247
|
+
this.files = new Filesystem(sbx);
|
|
248
|
+
}
|
|
249
|
+
get sandboxId() {
|
|
250
|
+
return this.raw.id;
|
|
251
|
+
}
|
|
252
|
+
/** Our domain for preview URLs. */
|
|
253
|
+
get sandboxDomain() {
|
|
254
|
+
return this.raw.host(0).split(".").slice(1).join(".");
|
|
255
|
+
}
|
|
256
|
+
static async create(a, b) {
|
|
257
|
+
const template = typeof a === "string" ? a : undefined;
|
|
258
|
+
const o = (typeof a === "string" ? b : a) ?? {};
|
|
259
|
+
const sbx = await makeClient(o).create(createBody(template, o));
|
|
260
|
+
return new this(sbx);
|
|
261
|
+
}
|
|
262
|
+
static async connect(sandboxId, opts = {}) {
|
|
263
|
+
const sbx = await makeClient(opts).get(sandboxId);
|
|
264
|
+
if (sbx.info.status === "paused")
|
|
265
|
+
await sbx.resume();
|
|
266
|
+
return new this(sbx);
|
|
267
|
+
}
|
|
268
|
+
static async kill(sandboxId, opts = {}) {
|
|
269
|
+
try {
|
|
270
|
+
await (await makeClient(opts).get(sandboxId)).destroy();
|
|
271
|
+
return true;
|
|
272
|
+
}
|
|
273
|
+
catch (e) {
|
|
274
|
+
if (e instanceof SandboxesError && e.status === 404)
|
|
275
|
+
return false;
|
|
276
|
+
throw e;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
static async setTimeout(sandboxId, timeoutMs, opts = {}) {
|
|
280
|
+
await (await makeClient(opts).get(sandboxId)).setTimeout(Math.round(timeoutMs / 1000));
|
|
281
|
+
}
|
|
282
|
+
static async list(opts = {}) {
|
|
283
|
+
const rows = await makeClient(opts).list();
|
|
284
|
+
return rows.map((s) => ({
|
|
285
|
+
sandboxId: s.id,
|
|
286
|
+
templateId: s.template,
|
|
287
|
+
name: s.name ?? undefined,
|
|
288
|
+
metadata: s.metadata,
|
|
289
|
+
startedAt: new Date(s.startedAt ?? s.createdAt),
|
|
290
|
+
endAt: new Date(s.deadlineAt),
|
|
291
|
+
state: s.status,
|
|
292
|
+
}));
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* The preview host for a port, like E2B's: `${port}-${id}.quietrobot.dev`.
|
|
296
|
+
* The first call exposes the port publicly (it is live within a moment);
|
|
297
|
+
* await exposePort() to be sure, or to make it private.
|
|
298
|
+
*/
|
|
299
|
+
getHost(port) {
|
|
300
|
+
if (!this.exposed.has(port))
|
|
301
|
+
this.exposed.set(port, this.raw.ports.expose(port, "public").catch(() => this.exposed.delete(port)));
|
|
302
|
+
return this.raw.host(port);
|
|
303
|
+
}
|
|
304
|
+
/** Exposes a port and returns its full URL. Private URLs need the token or the share link. */
|
|
305
|
+
async exposePort(port, access = "public") {
|
|
306
|
+
const p = this.raw.ports.expose(port, access);
|
|
307
|
+
this.exposed.set(port, p);
|
|
308
|
+
return p;
|
|
309
|
+
}
|
|
310
|
+
async setTimeout(timeoutMs) {
|
|
311
|
+
await this.raw.setTimeout(Math.max(10, Math.round(timeoutMs / 1000)));
|
|
312
|
+
}
|
|
313
|
+
async isRunning() {
|
|
314
|
+
return (await this.raw.refresh()).status === "running";
|
|
315
|
+
}
|
|
316
|
+
async getInfo() {
|
|
317
|
+
const s = await this.raw.refresh();
|
|
318
|
+
return { sandboxId: s.id, templateId: s.template, name: s.name ?? undefined, metadata: s.metadata, startedAt: new Date(s.startedAt ?? s.createdAt), endAt: new Date(s.deadlineAt), state: s.status };
|
|
319
|
+
}
|
|
320
|
+
/** Pauses (memory, files and processes kept). Resume with Sandbox.connect(id). */
|
|
321
|
+
async pause() {
|
|
322
|
+
await this.raw.pause();
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
/** Same as pause(), under E2B's older name. */
|
|
326
|
+
betaPause() {
|
|
327
|
+
return this.pause();
|
|
328
|
+
}
|
|
329
|
+
async kill() {
|
|
330
|
+
await this.raw.destroy();
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Runs Python in a kernel that keeps variables between calls, like
|
|
335
|
+
* @e2b/code-interpreter. Only Python is supported.
|
|
336
|
+
*/
|
|
337
|
+
async runCode(code, opts = {}) {
|
|
338
|
+
if (opts.language && !/^py(thon)?3?$/i.test(opts.language))
|
|
339
|
+
throw new SandboxesError(400, "unsupported_language", `runCode supports Python only, not ${opts.language}`);
|
|
340
|
+
const r = await this.raw.runCode(code, { env: opts.envs, timeoutMs: opts.timeoutMs });
|
|
341
|
+
const lines = (s) => (s ? s.split(/(?<=\n)/) : []);
|
|
342
|
+
const stdout = lines(r.stdout);
|
|
343
|
+
const stderr = lines(r.stderr);
|
|
344
|
+
stdout.forEach((line) => opts.onStdout?.({ line }));
|
|
345
|
+
stderr.forEach((line) => opts.onStderr?.({ line }));
|
|
346
|
+
const results = r.results.map((x, i) => ({ ...x, isMainResult: i === 0 && x.text !== "<Figure>" }));
|
|
347
|
+
results.forEach((x) => opts.onResult?.(x));
|
|
348
|
+
if (r.error)
|
|
349
|
+
opts.onError?.(r.error);
|
|
350
|
+
return new CodeExecution(results, { stdout, stderr }, r.error ?? undefined);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
export default Sandbox;
|