@parcha/agentrun-computer 0.1.0-beta.36 → 0.1.0-beta.37
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/NOTICE +2 -0
- package/README.md +321 -308
- package/box/build-agent37.mjs +177 -0
- package/dist/agent37.d.ts +165 -0
- package/dist/agent37.js +759 -0
- package/dist/attach.d.ts +146 -0
- package/dist/attach.js +469 -0
- package/dist/browserbase.d.ts +2 -4
- package/dist/browserbase.js +2 -1
- package/dist/client.d.ts +33 -1
- package/dist/client.js +53 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/agent37.d.ts +96 -0
- package/dist/conformance/agent37.js +154 -0
- package/dist/conformance/cases/apps.d.ts +5 -0
- package/dist/conformance/cases/apps.js +160 -73
- package/dist/conformance/cases/health.js +14 -0
- package/dist/conformance/cases/index.js +2 -0
- package/dist/conformance/cases/provider.js +27 -1
- package/dist/conformance/cases/screen.d.ts +3 -0
- package/dist/conformance/cases/screen.js +18 -0
- package/dist/conformance/cases/settings.d.ts +29 -23
- package/dist/conformance/cases/settings.js +76 -58
- package/dist/conformance/cases/touch.js +19 -17
- package/dist/conformance/cases/ui.d.ts +2 -0
- package/dist/conformance/cases/ui.js +475 -0
- package/dist/conformance/cli.d.ts +9 -0
- package/dist/conformance/cli.js +28 -3
- package/dist/conformance/e2b.d.ts +6 -0
- package/dist/conformance/e2b.js +9 -2
- package/dist/conformance/fixture.d.ts +1 -1
- package/dist/conformance/fixture.js +25 -1
- package/dist/conformance/modal.d.ts +17 -13
- package/dist/conformance/modal.js +18 -9
- package/dist/conformance/orgo.d.ts +3 -3
- package/dist/conformance/orgo.js +6 -8
- package/dist/conformance/phone-harness.d.ts +6 -2
- package/dist/conformance/phone-harness.js +21 -4
- package/dist/conformance/report.js +1 -1
- package/dist/conformance/runner.js +23 -4
- package/dist/conformance/sweep.d.ts +50 -0
- package/dist/conformance/sweep.js +187 -0
- package/dist/conformance/types.d.ts +11 -3
- package/dist/conformance/ui-fixture.d.ts +56 -0
- package/dist/conformance/ui-fixture.js +43 -0
- package/dist/create-requests.d.ts +51 -0
- package/dist/create-requests.js +121 -0
- package/dist/daytona.d.ts +2 -4
- package/dist/daytona.js +3 -2
- package/dist/descriptor.d.ts +5 -0
- package/dist/descriptor.js +2 -0
- package/dist/descriptors/agent37.d.ts +41 -0
- package/dist/descriptors/agent37.js +28 -0
- package/dist/descriptors/index.d.ts +38 -2
- package/dist/descriptors/index.js +4 -2
- package/dist/descriptors/orgo.d.ts +2 -1
- package/dist/descriptors/orgo.js +3 -2
- package/dist/descriptors/phone-harness.d.ts +1 -1
- package/dist/descriptors/phone-harness.js +2 -2
- package/dist/docker.d.ts +7 -4
- package/dist/docker.js +271 -29
- package/dist/e2b.d.ts +9 -165
- package/dist/e2b.js +282 -1342
- package/dist/fake-ui-driver.d.ts +97 -0
- package/dist/fake-ui-driver.js +717 -0
- package/dist/host.d.ts +182 -0
- package/dist/host.js +1 -0
- package/dist/hosted/process.d.ts +67 -0
- package/dist/hosted/process.js +228 -0
- package/dist/hosted/provider.d.ts +146 -0
- package/dist/hosted/provider.js +1364 -0
- package/dist/hosted/scripts.d.ts +76 -0
- package/dist/{child.js → hosted/scripts.js} +93 -12
- package/dist/index.d.ts +7 -3
- package/dist/index.js +7 -4
- package/dist/kernel.d.ts +2 -4
- package/dist/kernel.js +2 -1
- package/dist/kinds.d.ts +8 -1
- package/dist/kinds.js +20 -4
- package/dist/local-chrome.d.ts +2 -4
- package/dist/local-chrome.js +2 -1
- package/dist/modal.d.ts +23 -181
- package/dist/modal.js +271 -1244
- package/dist/orgo-channel.d.ts +3 -2
- package/dist/orgo-channel.js +5 -2
- package/dist/orgo-desktop.d.ts +9 -4
- package/dist/orgo-desktop.js +33 -13
- package/dist/orgo-workspaces.d.ts +47 -0
- package/dist/orgo-workspaces.js +94 -0
- package/dist/orgo.d.ts +10 -4
- package/dist/orgo.js +30 -12
- package/dist/phone-harness.d.ts +31 -22
- package/dist/phone-harness.js +510 -698
- package/dist/png.d.ts +4 -0
- package/dist/png.js +27 -0
- package/dist/protocol.d.ts +335 -32
- package/dist/protocol.js +96 -3
- package/dist/provider.d.ts +34 -6
- package/dist/provider.js +16 -0
- package/dist/result.d.ts +1 -1
- package/dist/surface/api.d.ts +248 -0
- package/dist/surface/api.js +1 -0
- package/dist/surface/core.d.ts +42 -0
- package/dist/surface/core.js +393 -0
- package/dist/surface/index.d.ts +5 -0
- package/dist/surface/index.js +3 -0
- package/dist/surface/outline.d.ts +8 -0
- package/dist/surface/outline.js +50 -0
- package/dist/surface/script.d.ts +10 -0
- package/dist/surface/script.js +92 -0
- package/dist/ui-engine.d.ts +114 -0
- package/dist/ui-engine.js +798 -0
- package/package.json +17 -1
- package/dist/child.d.ts +0 -42
- package/dist/conformance/e2b-diagnose.d.ts +0 -16
- package/dist/conformance/e2b-diagnose.js +0 -61
- package/dist/conformance/e2b-sweep.d.ts +0 -18
- package/dist/conformance/e2b-sweep.js +0 -132
- package/dist/conformance/modal-sweep.d.ts +0 -22
- package/dist/conformance/modal-sweep.js +0 -213
package/dist/e2b.js
CHANGED
|
@@ -1,29 +1,15 @@
|
|
|
1
|
-
// The E2B
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// upload goes through envd's file API and
|
|
5
|
-
//
|
|
6
|
-
// README's E2B section, from e2b@2.63.0 (dist/index.mjs) and e2b-dev/infra@ff3922213 (envd).
|
|
7
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
-
import { readFileSync } from "node:fs";
|
|
9
|
-
import { resolve } from "node:path";
|
|
10
|
-
import { PassThrough, Writable } from "node:stream";
|
|
11
|
-
import { fileURLToPath } from "node:url";
|
|
12
|
-
import { childCommands, daemonDrift } from "./child.js";
|
|
13
|
-
import { OWN_NETWORK_ONLY, readOwnNetwork, TOOL_USER } from "./isolation.js";
|
|
14
|
-
import { DaemonClient } from "./client.js";
|
|
1
|
+
// The E2B host: E2B Desktop sandboxes (kind desktop) or E2B's plain template (kind linux), every call through the
|
|
2
|
+
// host's own E2B JS SDK (the `e2b` package), of which this package names only the slice it uses (E2BSandboxClass) and
|
|
3
|
+
// imports nothing at load. E2B's envd is the sandbox's first process (under systemd), so computerd is a child: its
|
|
4
|
+
// upload goes through envd's file API and every command (install, init's start, the stdio bridge) is a background
|
|
5
|
+
// command as root. The rest of the computer is the shared machine-host adapter's (./hosted/provider.ts). Every SDK fact
|
|
6
|
+
// used here is cited in the README's E2B section, from e2b@2.63.0 (dist/index.mjs) and e2b-dev/infra@ff3922213 (envd).
|
|
15
7
|
import { E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE } from "./descriptors/e2b.js";
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import { checkMount, readBackOf } from "./mount.js";
|
|
21
|
-
import { ARCHIL_HELPER, ARCHIL_MOUNT_LABEL, ARCHIL_TOOL_UID, archilLabels, archilMount, archilRefusals, archilRelease, claimEpoch, mountDrift, readArchilMount, recordedArchil as recordedArchilOf, recordedMount, syncingClient, } from "./mount-archil.js";
|
|
22
|
-
import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
|
|
23
|
-
import { failFor, ok, vendorFail } from "./result.js";
|
|
24
|
-
import { daemonWatch } from "./screen-watch.js";
|
|
8
|
+
import { deadlineOf, HostedProvider, IMAGE_LABEL, ours } from "./hosted/provider.js";
|
|
9
|
+
import { words } from "./hosted/process.js";
|
|
10
|
+
import { shellLine } from "./hosted/scripts.js";
|
|
11
|
+
import { failFor, ok } from "./result.js";
|
|
25
12
|
import { countTested } from "./test-connection.js";
|
|
26
|
-
import { waitUntil } from "./wait.js";
|
|
27
13
|
/** This module's failures: one with code vendor names E2B. */
|
|
28
14
|
const fail = failFor("e2b");
|
|
29
15
|
/** Not a literal, so no type checker or bundler resolves the SDK from this package. */
|
|
@@ -64,97 +50,27 @@ export async function create(options) {
|
|
|
64
50
|
}
|
|
65
51
|
/** The conformance CLI's module for E2B: its live switch, the run's 30-minute cap, its template and the drifted twin. */
|
|
66
52
|
export const conformance = () => import("./conformance/e2b.js");
|
|
67
|
-
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
68
|
-
const NAME = /^computer-[0-9a-f]{12}$/;
|
|
69
|
-
const SANDBOX_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
70
53
|
const TEMPLATE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
|
|
71
|
-
const NAME_LABEL = `${COMPUTER_LABEL}.name`;
|
|
72
|
-
/** The template create was asked for: E2B reports its id, and the alias only sometimes. */
|
|
73
|
-
const IMAGE_LABEL = `${COMPUTER_LABEL}.image`;
|
|
74
|
-
/** The most extend may move the deadline to: create's time plus the cap, by this machine's clock, as init was given. */
|
|
75
|
-
const MAX_LABEL = `${COMPUTER_LABEL}.max-deadline`;
|
|
76
54
|
/** The timeout create gave E2B, in ms: E2B's own end, startedAt plus this, until extend moves it. */
|
|
77
|
-
const TIMEOUT_LABEL =
|
|
78
|
-
const USER = /^(\d+):(\d+)$/;
|
|
79
|
-
const MAX_ID = 4_294_967_294;
|
|
55
|
+
const TIMEOUT_LABEL = "agentrun.computer.timeout-ms";
|
|
80
56
|
/** E2B Hobby's longest sandbox: 1 h (index.d.mts:10169-10172). */
|
|
81
57
|
const HOBBY_MAX_MS = 60 * 60_000;
|
|
82
58
|
/** E2B Pro's: 24 h. */
|
|
83
59
|
const PRO_MAX_MS = 24 * 60 * 60_000;
|
|
84
|
-
/** E2B runs x86-64 Firecracker VMs; the desktop template installs amd64 packages (e2b-dev/desktop template.py:67-78). */
|
|
85
|
-
const ARCH = "amd64";
|
|
86
|
-
const DEFAULT_DAEMON_PATH = fileURLToPath(new URL(`./computerd-linux-${ARCH}`, import.meta.url));
|
|
87
|
-
const DEFAULTS = {
|
|
88
|
-
requestMs: 30_000,
|
|
89
|
-
createMs: 120_000,
|
|
90
|
-
uploadMs: 120_000,
|
|
91
|
-
execMs: 60_000,
|
|
92
|
-
helloMs: 30_000,
|
|
93
|
-
probeMs: 30_000,
|
|
94
|
-
listMs: 60_000,
|
|
95
|
-
goneMs: 120_000,
|
|
96
|
-
pollMs: 1_000,
|
|
97
|
-
listedMs: 15_000,
|
|
98
|
-
mountMs: 120_000,
|
|
99
|
-
};
|
|
100
|
-
/** The mount kinds an E2B computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
|
|
101
|
-
export const MOUNT = E2B.mounts;
|
|
102
|
-
/** The user an Archil computer's tools run as: the image's agentrun-tool, with no sudo and no capability. */
|
|
103
|
-
const ARCHIL_USER = `${ARCHIL_TOOL_UID}:${ARCHIL_TOOL_UID}`;
|
|
104
|
-
/** The machine kind and groups of each configuration: kind linux (the plain template), and kind desktop (the default). */
|
|
105
|
-
export const CAPABILITIES = E2B.capabilities;
|
|
106
|
-
const RELEASE_POLL_MAX_MS = 5_000;
|
|
107
|
-
const LISTED_POLL_MS = 150;
|
|
108
|
-
const LISTED_ROUNDS = 2;
|
|
109
|
-
const LISTED_POLL_MAX_MS = 1_000;
|
|
110
|
-
const LISTEN_RETRY_MS = 250;
|
|
111
60
|
const MAX_PAGES = 100;
|
|
112
61
|
const PAGE = 100;
|
|
113
62
|
/** E2B's end, read back, is its start plus the timeout create gave it, to the second it rounds to (index.mjs:502-504). */
|
|
114
63
|
const END_SLACK_MS = 2_000;
|
|
115
|
-
|
|
116
|
-
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
117
|
-
/** What a call's race adds to its SDK request's own bound, so the SDK's timeout, not the race, reports a slow call. */
|
|
118
|
-
const CALL_SLACK_MS = 5_000;
|
|
119
|
-
/** The longest timeout the provider takes: the race of a call bounded by it must still fit a Node timer. */
|
|
120
|
-
const MAX_TIMEOUT_MS = MAX_TIMER_MS - CALL_SLACK_MS;
|
|
121
|
-
const STAGING = "/tmp/agentrun-computerd-";
|
|
122
|
-
/**
|
|
123
|
-
* Public anycast resolvers, by address, as Modal's: TCP to 443, and DNS over UDP to 53, the classic path out where TCP
|
|
124
|
-
* is dropped, over IPv4 and IPv6. E2B's firewall drops non-TCP to the deny set denyOut fills, in nftables
|
|
125
|
-
* (e2b-dev/infra@ff3922213 pkg/sandbox/network/firewall.go, installRules rule 5): with no internet access a UDP target
|
|
126
|
-
* gets no reply, refused.
|
|
127
|
-
*/
|
|
128
|
-
const DEFAULT_PROBE_TARGETS = ["1.1.1.1:443", "8.8.8.8:443", "[2606:4700:4700::1111]:443", "1.1.1.1:53/udp", "[2606:4700:4700::1111]:53/udp"];
|
|
129
|
-
/** A probe target: host:port, over TCP, or host:port/udp, a DNS query over UDP. */
|
|
130
|
-
const TARGET = /^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+):[0-9]{1,5}(?:\/udp)?$/;
|
|
131
|
-
const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "mount", "gpu"]);
|
|
132
|
-
const NUL = "a NUL byte cannot be sent to E2B";
|
|
133
|
-
const FIXED = "an E2B computer's network is fixed at create: create a new computer";
|
|
64
|
+
const DEFAULT_REQUEST_MS = 30_000;
|
|
134
65
|
const PUBLIC = "publicStream is no longer an option: an E2B computer never takes public traffic, which would open every port in it to anyone with its address, and its screen is streamed through agentrun, never a vendor URL";
|
|
135
66
|
/** envd's port in the sandbox (e2b@2.63.0 dist/index.mjs:1213, ConnectionConfig.envdPort). */
|
|
136
67
|
const ENVD_PORT = 49983;
|
|
137
|
-
|
|
68
|
+
/** The mount kinds an E2B computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
|
|
69
|
+
export const MOUNT = E2B.mounts;
|
|
70
|
+
/** The machine kind and groups of each configuration: kind linux (the plain template), and kind desktop (the default). */
|
|
71
|
+
export const CAPABILITIES = E2B.capabilities;
|
|
138
72
|
const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
|
|
139
73
|
const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
|
|
140
|
-
const seconds = (ms) => `${ms / 1000} s`;
|
|
141
|
-
const pause = (ms, signal) => new Promise((done) => {
|
|
142
|
-
const timer = setTimeout(finish, ms);
|
|
143
|
-
function finish() {
|
|
144
|
-
clearTimeout(timer);
|
|
145
|
-
signal?.removeEventListener("abort", finish);
|
|
146
|
-
done();
|
|
147
|
-
}
|
|
148
|
-
if (signal?.aborted)
|
|
149
|
-
finish();
|
|
150
|
-
else
|
|
151
|
-
signal?.addEventListener("abort", finish, { once: true });
|
|
152
|
-
});
|
|
153
|
-
const words = (error) => {
|
|
154
|
-
const name = error?.name;
|
|
155
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
156
|
-
return `${typeof name === "string" && name !== "Error" ? `${name}: ` : ""}${message}`.replace(/\s+/g, " ").slice(0, 300);
|
|
157
|
-
};
|
|
158
74
|
/** The SDK names its errors (index.mjs:86-360). */
|
|
159
75
|
function codeOf(error) {
|
|
160
76
|
const name = error?.name;
|
|
@@ -172,103 +88,13 @@ function codeOf(error) {
|
|
|
172
88
|
return "timeout";
|
|
173
89
|
return "vendor";
|
|
174
90
|
}
|
|
175
|
-
/** Settles with the promise's result, or a timeout or abort in words once ms pass or signal aborts. */
|
|
176
|
-
function race(promise, what, ms, signal) {
|
|
177
|
-
if (signal?.aborted) {
|
|
178
|
-
promise.catch(() => { });
|
|
179
|
-
return Promise.resolve(fail("aborted", `${what} was aborted`));
|
|
180
|
-
}
|
|
181
|
-
return new Promise((settle) => {
|
|
182
|
-
const timer = setTimeout(() => done(fail("timeout", `${what} did not answer within ${seconds(ms)}`)), ms);
|
|
183
|
-
const onAbort = () => done(fail("aborted", `${what} was aborted`));
|
|
184
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
185
|
-
let settled = false;
|
|
186
|
-
function done(result) {
|
|
187
|
-
if (settled)
|
|
188
|
-
return;
|
|
189
|
-
settled = true;
|
|
190
|
-
clearTimeout(timer);
|
|
191
|
-
signal?.removeEventListener("abort", onAbort);
|
|
192
|
-
settle(result);
|
|
193
|
-
}
|
|
194
|
-
promise.then((value) => done(ok(value)), (error) => done(signal?.aborted ? fail("aborted", `${what} was aborted`) : fail(codeOf(error), `${what} failed: ${words(error)}`)));
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
/** Calls run and races it; a run that throws at once is an error like one that rejects. */
|
|
198
|
-
function call(what, run, ms, signal) {
|
|
199
|
-
if (signal?.aborted)
|
|
200
|
-
return Promise.resolve(fail("aborted", `${what} was aborted before it was called`));
|
|
201
|
-
let promise;
|
|
202
|
-
try {
|
|
203
|
-
promise = Promise.resolve(run());
|
|
204
|
-
}
|
|
205
|
-
catch (error) {
|
|
206
|
-
return Promise.resolve(fail(codeOf(error), `${what} failed: ${words(error)}`));
|
|
207
|
-
}
|
|
208
|
-
return race(promise, what, ms, signal);
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Marks result's timeout listBound when left, what was left of a listing's deadline as the call began, was its bound,
|
|
212
|
-
* not its own requestMs: then the listing's deadline ended it, whatever Date.now() reads a moment after.
|
|
213
|
-
*/
|
|
214
|
-
function boundBy(result, left, requestMs) {
|
|
215
|
-
return !result.ok && result.error.code === "timeout" && left !== undefined && left <= requestMs ? { ...result, listBound: true } : result;
|
|
216
|
-
}
|
|
217
|
-
function labelProblem(key, value) {
|
|
218
|
-
if (typeof value !== "string")
|
|
219
|
-
return `the label ${key} must be a string`;
|
|
220
|
-
if (key.includes("\0") || value.includes("\0"))
|
|
221
|
-
return `the label ${JSON.stringify(key)}: ${NUL}`;
|
|
222
|
-
if (key === "")
|
|
223
|
-
return "a label name must be non-empty";
|
|
224
|
-
if (key === COMPUTER_LABEL || key.startsWith(`${COMPUTER_LABEL}.`))
|
|
225
|
-
return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
|
|
226
|
-
if (key === ARCHIL_MOUNT_LABEL)
|
|
227
|
-
return `the label ${key} is the provider's own: it records an Archil computer's mount`;
|
|
228
|
-
return undefined;
|
|
229
|
-
}
|
|
230
|
-
function filterProblem(labels) {
|
|
231
|
-
if (typeof labels !== "object" || labels === null || Array.isArray(labels))
|
|
232
|
-
return "labels must map names to strings";
|
|
233
|
-
for (const [key, value] of Object.entries(labels)) {
|
|
234
|
-
if (typeof value !== "string")
|
|
235
|
-
return `the label ${key} must be a string`;
|
|
236
|
-
if (key === "" || key.includes("\0") || value.includes("\0"))
|
|
237
|
-
return `the label ${JSON.stringify(key)} must be a non-empty name with no NUL byte`;
|
|
238
|
-
}
|
|
239
|
-
return undefined;
|
|
240
|
-
}
|
|
241
|
-
/** Only a sandbox this provider made counts: its label, a name of its making, and the name asked for when one is. */
|
|
242
|
-
const ours = (metadata, name) => metadata?.[COMPUTER_LABEL] === "1" && NAME.test(metadata[NAME_LABEL] ?? "") && (name === undefined || metadata[NAME_LABEL] === name);
|
|
243
|
-
/** An ISO time a label holds, or undefined when it is missing or not the ISO time create writes. */
|
|
244
|
-
function isoOf(written) {
|
|
245
|
-
const at = written === undefined ? Number.NaN : Date.parse(written);
|
|
246
|
-
return Number.isNaN(at) || new Date(at).toISOString() !== written ? undefined : new Date(at);
|
|
247
|
-
}
|
|
248
91
|
/** E2B's end as create set it: its start plus the timeout create gave, by E2B's clock; undefined when unread. */
|
|
249
92
|
function createdEnd({ metadata, startedAt }) {
|
|
250
93
|
const timeout = Number(metadata[TIMEOUT_LABEL]);
|
|
251
94
|
const start = startedAt instanceof Date ? startedAt.getTime() : Number.NaN;
|
|
252
95
|
return isWhole(timeout) && timeout > 0 && !Number.isNaN(start) ? start + timeout : undefined;
|
|
253
96
|
}
|
|
254
|
-
/**
|
|
255
|
-
* When a computer ends: the deadline create wrote, or, once extend has moved E2B's end past where create set it, that
|
|
256
|
-
* end up to the most the computer may live, which is what extend gave init. E2B keeps no metadata change (it has no call
|
|
257
|
-
* for one), so the vendor's end, read back, stands for a moved deadline. An end within END_SLACK_MS of create's is
|
|
258
|
-
* create's own, rounded: extend never leaves E2B's end there (clearOf).
|
|
259
|
-
*/
|
|
260
|
-
function deadlineOf(sb) {
|
|
261
|
-
const written = isoOf(sb.metadata[DEADLINE_LABEL]);
|
|
262
|
-
if (written === undefined)
|
|
263
|
-
return undefined;
|
|
264
|
-
const end = sb.endAt instanceof Date ? sb.endAt.getTime() : Number.NaN;
|
|
265
|
-
const created = createdEnd(sb);
|
|
266
|
-
if (Number.isNaN(end) || created === undefined || end <= created + END_SLACK_MS)
|
|
267
|
-
return written;
|
|
268
|
-
const most = isoOf(sb.metadata[MAX_LABEL]);
|
|
269
|
-
return new Date(most === undefined ? end : Math.min(end, most.getTime()));
|
|
270
|
-
}
|
|
271
|
-
/** The earliest end extend gives E2B: a second past create's end and its rounding, so deadlineOf reads it as moved. */
|
|
97
|
+
/** The earliest end a moved timer gives E2B: a second past create's end and its rounding, so deadlineOf reads it as moved. */
|
|
272
98
|
const clearOf = (created) => created + END_SLACK_MS + 1_000;
|
|
273
99
|
/**
|
|
274
100
|
* A sandbox's network as E2B reports it. None is no internet access (E2B: the same as denyOut 0.0.0.0/0,
|
|
@@ -292,1222 +118,336 @@ function networkOf(info) {
|
|
|
292
118
|
}
|
|
293
119
|
return blocked ? "none" : "open";
|
|
294
120
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
121
|
+
/** A sandbox as the adapter reads a machine: E2B's states, its network, its template, its timer, and its create's drift. */
|
|
122
|
+
function machineOf(info) {
|
|
123
|
+
const metadata = { ...(info.metadata ?? {}) };
|
|
124
|
+
const end = info.endAt instanceof Date ? info.endAt.getTime() : Number.NaN;
|
|
125
|
+
const created = createdEnd({ metadata, startedAt: info.startedAt });
|
|
126
|
+
const drift = [];
|
|
127
|
+
const mismatch = (field, declared, actual) => drift.push(`${field}: declared ${show(declared)}, read back ${show(actual)}`);
|
|
128
|
+
// E2B reports the template's id, and its alias when it has one (index.mjs:5435-5437): a template asked for by an
|
|
129
|
+
// alias E2B does not report back cannot be held to it, and its label records what was asked.
|
|
130
|
+
const asked = metadata[IMAGE_LABEL];
|
|
131
|
+
const alias = info.name;
|
|
132
|
+
if (asked !== undefined && info.templateId !== asked && alias !== undefined && alias !== asked && !alias.startsWith(`${asked}:`)) {
|
|
133
|
+
drift.push(`template: declared ${show(asked)}, read back ${show(info.templateId)} (${alias})`);
|
|
134
|
+
}
|
|
135
|
+
if (info.lifecycle?.onTimeout !== undefined && info.lifecycle.onTimeout !== "kill")
|
|
136
|
+
mismatch("lifecycle onTimeout", "kill", info.lifecycle.onTimeout);
|
|
137
|
+
if (info.lifecycle?.autoResume === true)
|
|
138
|
+
mismatch("lifecycle autoResume", false, true);
|
|
139
|
+
// An end later than create's is a moved timer (timerMoved: an extend's, or one create refuses on a machine it just
|
|
140
|
+
// made); only an end it cannot read, or one earlier than create gave, is drift, at create and at attach alike.
|
|
141
|
+
if (Number.isNaN(end) || created === undefined)
|
|
142
|
+
drift.push(`endAt: E2B reported ${show(info.endAt)} from a start of ${show(info.startedAt)}, so it might not end the computer`);
|
|
143
|
+
else if (end < created - END_SLACK_MS)
|
|
144
|
+
drift.push(`endAt: ${info.endAt.toISOString()} is earlier than E2B's start plus the ${metadata[TIMEOUT_LABEL]} ms timeout create gave`);
|
|
145
|
+
return {
|
|
146
|
+
id: info.sandboxId,
|
|
147
|
+
labels: metadata,
|
|
148
|
+
state: info.state === "running" ? "running" : info.state === "paused" ? "stopped" : "going",
|
|
149
|
+
network: networkOf(info),
|
|
150
|
+
image: { resolved: info.templateId },
|
|
151
|
+
...(info.startedAt instanceof Date && !Number.isNaN(info.startedAt.getTime()) ? { createdAt: new Date(info.startedAt) } : {}),
|
|
152
|
+
...(Number.isNaN(end) ? {} : { endsAt: new Date(end) }),
|
|
153
|
+
// An end within END_SLACK_MS of create's is create's own, rounded: a moved timer never leaves E2B's end there (clearOf).
|
|
154
|
+
timerMoved: !Number.isNaN(end) && created !== undefined && end > created + END_SLACK_MS,
|
|
155
|
+
...(drift.length > 0 ? { drift } : {}),
|
|
156
|
+
};
|
|
317
157
|
}
|
|
318
|
-
/**
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
158
|
+
/** A listed sandbox whose read-back E2B no longer has: still listed, so it is going, not gone. */
|
|
159
|
+
const listedOnly = (sb) => ({
|
|
160
|
+
id: sb.sandboxId,
|
|
161
|
+
labels: { ...(sb.metadata ?? {}) },
|
|
162
|
+
state: "going",
|
|
163
|
+
...(sb.startedAt instanceof Date && !Number.isNaN(sb.startedAt.getTime()) ? { createdAt: new Date(sb.startedAt) } : {}),
|
|
164
|
+
});
|
|
165
|
+
/** A stream fed by the SDK's callbacks, read as an async iterable until it ends. */
|
|
166
|
+
function feed() {
|
|
167
|
+
const queue = [];
|
|
168
|
+
let ended = false;
|
|
169
|
+
let wake;
|
|
170
|
+
const nudge = () => {
|
|
171
|
+
const waiting = wake;
|
|
172
|
+
wake = undefined;
|
|
173
|
+
waiting?.();
|
|
174
|
+
};
|
|
175
|
+
return {
|
|
176
|
+
push(bytes) {
|
|
177
|
+
if (ended)
|
|
178
|
+
return;
|
|
179
|
+
queue.push(bytes);
|
|
180
|
+
nudge();
|
|
181
|
+
},
|
|
182
|
+
end() {
|
|
183
|
+
ended = true;
|
|
184
|
+
nudge();
|
|
185
|
+
},
|
|
186
|
+
iterable: {
|
|
187
|
+
async *[Symbol.asyncIterator]() {
|
|
188
|
+
for (;;) {
|
|
189
|
+
const next = queue.shift();
|
|
190
|
+
if (next !== undefined)
|
|
191
|
+
yield next;
|
|
192
|
+
else if (ended)
|
|
193
|
+
return;
|
|
194
|
+
else
|
|
195
|
+
await new Promise((done) => (wake = done));
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
};
|
|
325
200
|
}
|
|
326
|
-
/**
|
|
327
|
-
|
|
328
|
-
* Xvfb, x11vnc and noVNC (e2b-dev/desktop template.py:21-65). See the README's E2B section for every call and its
|
|
329
|
-
* citation.
|
|
330
|
-
*/
|
|
331
|
-
export class E2BProvider {
|
|
201
|
+
/** E2B's sandboxes as a MachineHost (../host.ts). */
|
|
202
|
+
class E2BHost {
|
|
332
203
|
id = "e2b";
|
|
333
|
-
|
|
204
|
+
facts = {
|
|
205
|
+
daemon: "child",
|
|
206
|
+
isolation: "microvm",
|
|
207
|
+
lifetime: "vendor",
|
|
208
|
+
maxLifetimeMs: PRO_MAX_MS,
|
|
209
|
+
arch: "amd64",
|
|
210
|
+
vendorAgentPorts: [ENVD_PORT],
|
|
211
|
+
networkReadBack: true,
|
|
212
|
+
network: [...E2B.network],
|
|
213
|
+
mounts: [...MOUNT],
|
|
214
|
+
release: ["delete"],
|
|
215
|
+
};
|
|
334
216
|
#Sandbox;
|
|
335
217
|
#connection;
|
|
336
|
-
#
|
|
337
|
-
|
|
338
|
-
#
|
|
339
|
-
|
|
340
|
-
#uid;
|
|
341
|
-
#gid;
|
|
342
|
-
#timeouts;
|
|
343
|
-
#probeTargets;
|
|
344
|
-
#onNote;
|
|
345
|
-
/** Each computer's last extend, by sandbox id, while one runs: the next waits for it. */
|
|
346
|
-
#extending = new Map();
|
|
347
|
-
constructor(options) {
|
|
348
|
-
// A caller who still names the option is told it is gone, whatever its value: it once let public traffic in.
|
|
349
|
-
if (typeof options === "object" && options !== null && Object.hasOwn(options, "publicStream"))
|
|
350
|
-
throw new Error(PUBLIC);
|
|
351
|
-
const { apiKey, onNote, Sandbox, domain = DEFAULT_DOMAIN, daemonPath = DEFAULT_DAEMON_PATH, kind = "desktop", desktop = {}, maxLifetimeMs = HOBBY_MAX_MS, daemonUser = TOOL_USER, timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS, } = options;
|
|
352
|
-
this.#onNote = onNote;
|
|
353
|
-
if (typeof apiKey !== "string" || apiKey === "")
|
|
354
|
-
throw new Error("an E2B API key is required");
|
|
355
|
-
const lacks = ["create", "connect", "getInfo", "setTimeout", "kill", "list"].filter((name) => typeof Sandbox?.[name] !== "function");
|
|
356
|
-
if (lacks.length > 0)
|
|
357
|
-
throw new Error(`options.Sandbox must be the e2b SDK's Sandbox class; it lacks ${lacks.join(", ")}`);
|
|
358
|
-
const ambient = ambientProblem();
|
|
359
|
-
if (ambient)
|
|
360
|
-
throw new Error(ambient);
|
|
361
|
-
if (typeof domain !== "string" || !DOMAIN.test(domain))
|
|
362
|
-
throw new Error(`the E2B domain must be a host name such as ${DEFAULT_DOMAIN}, not ${JSON.stringify(domain)}`);
|
|
363
|
-
if (kind !== "desktop" && kind !== "linux")
|
|
364
|
-
throw new Error(`kind is desktop or linux, not ${String(kind)}`);
|
|
365
|
-
if (!isWhole(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > PRO_MAX_MS) {
|
|
366
|
-
throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most 24 h (${PRO_MAX_MS} ms), E2B Pro's longest sandbox; Hobby's is 1 h`);
|
|
367
|
-
}
|
|
368
|
-
const user = USER.exec(daemonUser);
|
|
369
|
-
if (user === null || Number(user[1]) > MAX_ID || Number(user[2]) > MAX_ID)
|
|
370
|
-
throw new Error(`the daemon user ${daemonUser} must be uid:gid in numbers, such as 1000:1000`);
|
|
371
|
-
// The numbers, not the text: "00" is root as much as "0" is.
|
|
372
|
-
if (Number(user[1]) === 0 || Number(user[2]) === 0)
|
|
373
|
-
throw new Error(`the daemon user ${daemonUser} is root or in root's group; an E2B computer's daemon runs as neither`);
|
|
374
|
-
const merged = { ...DEFAULTS, ...timeouts };
|
|
375
|
-
// AbortSignal.timeout and Node's timers take whole ms up to 2^31 - 1 (a fraction throws, a longer one fires at
|
|
376
|
-
// once), and a call's race adds CALL_SLACK_MS to its bound: refused here, before any sandbox exists, not in create.
|
|
377
|
-
for (const [key, value] of Object.entries(merged)) {
|
|
378
|
-
if (!isWhole(value) || value <= 0 || value > MAX_TIMEOUT_MS)
|
|
379
|
-
throw new Error(`timeouts.${key} must be a whole number of ms above 0 and at most ${MAX_TIMEOUT_MS}, not ${value}`);
|
|
380
|
-
}
|
|
381
|
-
if (!Array.isArray(probeTargets) || probeTargets.length === 0 || probeTargets.some((target) => typeof target !== "string" || !TARGET.test(target))) {
|
|
382
|
-
throw new Error("probeTargets must name at least one address for the probe, each host:port or host:port/udp");
|
|
383
|
-
}
|
|
218
|
+
#requestMs;
|
|
219
|
+
/** Each sandbox create or connect gave, by id, for envd's commands and files: let go of at its delete. */
|
|
220
|
+
#sandboxes = new Map();
|
|
221
|
+
constructor(Sandbox, connection, requestMs) {
|
|
384
222
|
this.#Sandbox = Sandbox;
|
|
385
|
-
this.#connection =
|
|
386
|
-
this.#
|
|
387
|
-
this.#kind = kind;
|
|
388
|
-
this.#desktop = kind === "desktop" ? desktopOf(desktop) : undefined;
|
|
389
|
-
this.#maxLifetimeMs = maxLifetimeMs;
|
|
390
|
-
[this.#uid, this.#gid] = [String(Number(user[1])), String(Number(user[2]))];
|
|
391
|
-
this.#timeouts = merged;
|
|
392
|
-
this.#probeTargets = [...probeTargets];
|
|
223
|
+
this.#connection = connection;
|
|
224
|
+
this.#requestMs = requestMs;
|
|
393
225
|
}
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
* envd.service.tpl:26-30), and init is a background command it runs (#prepare), so init's exit leaves the sandbox. Its
|
|
397
|
-
* cap is E2B's: Hobby's 1 h unless the provider was made with more, up to Pro's 24 h. envd runs as root and answers on
|
|
398
|
-
* 49983, so init starts with --own-network, and network none is all a computer takes until a proxy carries open out
|
|
399
|
-
* of the daemon's own network.
|
|
400
|
-
*/
|
|
401
|
-
capabilities() {
|
|
402
|
-
return {
|
|
403
|
-
kind: this.#kind,
|
|
404
|
-
lifetime: "vendor",
|
|
405
|
-
network: [...E2B.network],
|
|
406
|
-
networkReadBack: true,
|
|
407
|
-
isolation: "microvm",
|
|
408
|
-
os: "linux",
|
|
409
|
-
daemon: "child",
|
|
410
|
-
groups: ["exec", "files", "processes", ...(this.#desktop ? DESKTOP_GROUPS : [])],
|
|
411
|
-
maxLifetimeMs: this.#maxLifetimeMs,
|
|
412
|
-
release: ["delete"],
|
|
413
|
-
mount: [...MOUNT],
|
|
414
|
-
vendorAgentPorts: [ENVD_PORT],
|
|
415
|
-
};
|
|
416
|
-
}
|
|
417
|
-
check(spec) {
|
|
418
|
-
const refusals = [];
|
|
419
|
-
const refuse = (field, message) => refusals.push({ field, message });
|
|
420
|
-
const given = (typeof spec === "object" && spec !== null ? spec : {});
|
|
421
|
-
const { image, network, labels, mount } = given;
|
|
422
|
-
refusals.push(...checkMount(mount, MOUNT), ...archilRefusals(given));
|
|
423
|
-
const daemonUser = `${this.#uid}:${this.#gid}`;
|
|
424
|
-
if (mount?.kind === "archil" && daemonUser !== ARCHIL_USER) {
|
|
425
|
-
refuse("mount", `a computer with an Archil mount runs its tools as agentrun-tool, ${ARCHIL_USER}, the user its image makes with no way to root; this provider's daemon user is ${daemonUser}: make it with daemonUser ${ARCHIL_USER}`);
|
|
426
|
-
}
|
|
427
|
-
if (typeof image !== "string" || !TEMPLATE.test(image))
|
|
428
|
-
refuse("image", `an image is required: the name or id of an E2B template, such as "${E2B_DESKTOP_TEMPLATE}" (E2B Desktop) or "${E2B_BASE_TEMPLATE}"`);
|
|
429
|
-
refusals.push(...checkTenure(given, this.capabilities(), "E2B"));
|
|
430
|
-
if (network === "open" || (typeof network === "object" && network !== null && "allow" in network))
|
|
431
|
-
refuse("network", OWN_NETWORK_ONLY);
|
|
432
|
-
else if (network !== "none")
|
|
433
|
-
refuse("network", 'network is required: "none"');
|
|
434
|
-
if (labels !== undefined) {
|
|
435
|
-
const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
|
|
436
|
-
const bad = entries === undefined ? "labels must map names to strings" : entries.map(([key, value]) => labelProblem(key, value)).find(Boolean);
|
|
437
|
-
if (bad)
|
|
438
|
-
refuse("labels", bad);
|
|
439
|
-
}
|
|
440
|
-
refusals.push(...checkGpu(given.gpu, this.capabilities()));
|
|
441
|
-
for (const [field, value] of Object.entries(given)) {
|
|
442
|
-
if (SPEC_FIELDS.has(field) || value === undefined)
|
|
443
|
-
continue;
|
|
444
|
-
if (field === "cpus" || field === "memoryMb" || field === "pids")
|
|
445
|
-
refuse(field, `an E2B computer has the size of its template: name a template of the size you need, not ${field}`);
|
|
446
|
-
else if (field === "user")
|
|
447
|
-
refuse(field, `an E2B computer's daemon runs as the provider's daemon user (${this.#uid}:${this.#gid}), never as one a spec names`);
|
|
448
|
-
else if (field === "workdir")
|
|
449
|
-
refuse(field, `an E2B computer works in ${WORK}, its home; a spec cannot name another`);
|
|
450
|
-
else
|
|
451
|
-
refuse(field, `an E2B computer does not support ${field}`);
|
|
452
|
-
}
|
|
453
|
-
return refusals;
|
|
226
|
+
errorCode(error) {
|
|
227
|
+
return codeOf(error);
|
|
454
228
|
}
|
|
455
229
|
/** The connection options with a bound and, when given, the caller's signal. */
|
|
456
230
|
#api(ms, signal) {
|
|
457
231
|
return { ...this.#connection, requestTimeoutMs: ms, ...(signal ? { signal } : {}) };
|
|
458
232
|
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
// From here the sandbox exists: every step takes the caller's signal, and a failure or an abort kills it.
|
|
465
|
-
const prepared = await this.#prepare(spec, ref, sandbox, made, signal);
|
|
466
|
-
if (signal?.aborted)
|
|
467
|
-
return this.#abandon(ref, { code: "aborted", message: "create was aborted" }, signal);
|
|
468
|
-
if (prepared.ok)
|
|
469
|
-
return ok(prepared.value.length > 0 ? { ...ref, notes: prepared.value } : ref);
|
|
470
|
-
return this.#abandon(ref, prepared.error, signal);
|
|
471
|
-
}
|
|
472
|
-
/** Everything create does up to E2B's answer: the spec checked, the daemon read, the sandbox made, by its options. */
|
|
473
|
-
async #launch(spec, signal) {
|
|
474
|
-
const refusals = this.check(spec);
|
|
475
|
-
if (refusals.length > 0)
|
|
476
|
-
return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
|
|
477
|
-
let daemon;
|
|
478
|
-
try {
|
|
479
|
-
daemon = readFileSync(this.#daemonPath);
|
|
480
|
-
}
|
|
481
|
-
catch {
|
|
482
|
-
return fail("not_found", `no daemon binary at ${this.#daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer`);
|
|
233
|
+
/** An E2B template is a name or id: letters, digits and ._:/- (no shell word, no path out). */
|
|
234
|
+
check(spec) {
|
|
235
|
+
const image = spec?.image;
|
|
236
|
+
if (typeof image === "string" && image !== "" && !TEMPLATE.test(image)) {
|
|
237
|
+
return [{ field: "image", message: `an image is the name or id of an E2B template, such as "${E2B_DESKTOP_TEMPLATE}" (E2B Desktop) or "${E2B_BASE_TEMPLATE}"` }];
|
|
483
238
|
}
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
const
|
|
494
|
-
...spec.labels,
|
|
495
|
-
[COMPUTER_LABEL]: "1",
|
|
496
|
-
[NAME_LABEL]: name,
|
|
497
|
-
[DEADLINE_LABEL]: deadline,
|
|
498
|
-
[IMAGE_LABEL]: spec.image,
|
|
499
|
-
[MAX_LABEL]: maxDeadline,
|
|
500
|
-
[TIMEOUT_LABEL]: String(timeoutMs),
|
|
501
|
-
// An Archil computer's mount, kind and source, never the token: what list() reports and attach reads back against.
|
|
502
|
-
...(spec.mount?.kind === "archil" ? archilLabels(spec.mount) : {}),
|
|
503
|
-
};
|
|
239
|
+
return [];
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Sandbox.create with the lifetime as its timeout in the whole seconds E2B takes (index.mjs:502-504), recorded in a
|
|
243
|
+
* label for its end's arithmetic; no internet access unless the adapter asks open (an Archil computer's root), no
|
|
244
|
+
* public traffic (a project's default may let it in: E2B docs, network/restrict-public-access), and kill at the
|
|
245
|
+
* timeout, never a pause that keeps the computer (index.mjs:5674-5699).
|
|
246
|
+
*/
|
|
247
|
+
async create(req, ctx) {
|
|
248
|
+
const timeoutMs = Math.ceil((req.lifetimeMs ?? 0) / 1000) * 1000;
|
|
504
249
|
const options = {
|
|
505
|
-
...this.#api(
|
|
250
|
+
...this.#api(ctx.timeoutMs),
|
|
506
251
|
timeoutMs,
|
|
507
|
-
metadata,
|
|
252
|
+
metadata: { ...req.labels, [TIMEOUT_LABEL]: String(timeoutMs) },
|
|
508
253
|
envs: {},
|
|
509
|
-
|
|
510
|
-
// own, read back by the probe from inside, as the tool user, like every network none here.
|
|
511
|
-
allowInternetAccess: spec.network === "open" || spec.mount?.kind === "archil",
|
|
512
|
-
// Explicit: a project's default may let public traffic in (E2B docs, network/restrict-public-access).
|
|
254
|
+
allowInternetAccess: req.network === "open",
|
|
513
255
|
network: { allowPublicTraffic: false },
|
|
514
|
-
// Explicit kill at the timeout, never a pause that keeps the computer (index.mjs:5674-5699).
|
|
515
256
|
lifecycle: { onTimeout: "kill" },
|
|
516
257
|
};
|
|
517
|
-
|
|
518
|
-
|
|
258
|
+
const sandbox = await this.#Sandbox.create(req.image, options);
|
|
259
|
+
this.#sandboxes.set(sandbox.sandboxId, sandbox);
|
|
260
|
+
return ok({ id: sandbox.sandboxId });
|
|
261
|
+
}
|
|
262
|
+
/** getInfo; a sandbox E2B does not have (SandboxNotFoundError, index.mjs:5431) is none. */
|
|
263
|
+
async get(id, ctx) {
|
|
519
264
|
try {
|
|
520
|
-
|
|
265
|
+
return ok(machineOf(await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal))));
|
|
521
266
|
}
|
|
522
267
|
catch (error) {
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
if (!created.ok) {
|
|
527
|
-
if (created.error.code === "aborted" || created.error.code === "timeout") {
|
|
528
|
-
// One that lands is killed by its id; one whose answer never comes, by its name label.
|
|
529
|
-
creating.then((sandbox) => this.#kill(sandbox.sandboxId), () => this.#killNamed(name));
|
|
530
|
-
return fail(created.error.code, `${created.error.message}; a sandbox it makes after this is killed as it lands, and E2B ends it by ${deadline} either way`);
|
|
531
|
-
}
|
|
532
|
-
// A create E2B refused (4xx) made nothing. One that failed otherwise may have: it goes by its name label.
|
|
533
|
-
if (["invalid", "denied", "limit", "not_found"].includes(created.error.code))
|
|
534
|
-
return created;
|
|
535
|
-
const swept = await this.#killNamed(name);
|
|
536
|
-
return fail(created.error.code, `E2B did not create the sandbox: ${created.error.message}${swept}`);
|
|
268
|
+
if (codeOf(error) === "not_found")
|
|
269
|
+
return ok(undefined);
|
|
270
|
+
throw error;
|
|
537
271
|
}
|
|
538
|
-
const sandbox = created.value;
|
|
539
|
-
return ok({ sandbox, ref: { id: sandbox.sandboxId, name }, made: { deadline, maxDeadline, metadata, daemon, sha256 } });
|
|
540
|
-
}
|
|
541
|
-
/** Kills a sandbox create gives up on, then waits, under the caller's signal, until E2B reads it gone. */
|
|
542
|
-
async #abandon(ref, error, signal) {
|
|
543
|
-
const killed = await this.#kill(ref.id);
|
|
544
|
-
const gone = killed.ok ? await this.#settle(ref, signal) : killed;
|
|
545
|
-
const after = gone.ok
|
|
546
|
-
? "was deleted"
|
|
547
|
-
: killed.ok && gone.error.code === "aborted"
|
|
548
|
-
? "was killed, and the wait for it to go was aborted; E2B ends it at its timeout if the kill did not take"
|
|
549
|
-
: `could not be deleted (${gone.error.message}); E2B ends it at its timeout`;
|
|
550
|
-
return fail(error.code, `the computer ${ref.name} ${after}: ${error.message}`);
|
|
551
272
|
}
|
|
552
273
|
/**
|
|
553
|
-
* Every sandbox
|
|
554
|
-
*
|
|
555
|
-
* passes. Best effort, in words.
|
|
274
|
+
* Every sandbox E2B lists with these metadata pairs (running and paused, index.d.mts:10289), all pages, each read
|
|
275
|
+
* back by getInfo, since a listing does not carry the network; one bound, ctx.timeoutMs, for every page and read.
|
|
556
276
|
*/
|
|
557
|
-
async
|
|
558
|
-
const
|
|
559
|
-
const
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
if (
|
|
564
|
-
return
|
|
565
|
-
|
|
566
|
-
if (
|
|
567
|
-
|
|
568
|
-
|
|
277
|
+
async list(labels, ctx) {
|
|
278
|
+
const until = Date.now() + ctx.timeoutMs;
|
|
279
|
+
const left = () => Math.max(1, Math.min(this.#requestMs, until - Date.now()));
|
|
280
|
+
const paginator = this.#Sandbox.list({ ...this.#connection, requestTimeoutMs: this.#requestMs, query: { metadata: labels }, limit: PAGE });
|
|
281
|
+
const found = new Map();
|
|
282
|
+
for (let page = 0; paginator.hasNext; page++) {
|
|
283
|
+
if (page >= MAX_PAGES)
|
|
284
|
+
return fail("vendor", `Sandbox.list ran past ${MAX_PAGES} pages`);
|
|
285
|
+
const items = await paginator.nextItems({ requestTimeoutMs: left(), ...(ctx.signal ? { signal: ctx.signal } : {}) });
|
|
286
|
+
if (!Array.isArray(items))
|
|
287
|
+
return fail("vendor", "Sandbox.list: a page that is not a list of sandboxes");
|
|
288
|
+
for (const sb of items)
|
|
289
|
+
if (typeof sb?.sandboxId === "string")
|
|
290
|
+
found.set(sb.sandboxId, sb);
|
|
569
291
|
}
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
const
|
|
575
|
-
|
|
576
|
-
|
|
292
|
+
const machines = [];
|
|
293
|
+
for (const sb of found.values()) {
|
|
294
|
+
if (Date.now() >= until)
|
|
295
|
+
return fail("timeout", `${machines.length} sandboxes were read back, ${sb.sandboxId} and any after it were not`);
|
|
296
|
+
const read = await this.get(sb.sandboxId, { timeoutMs: left(), ...(ctx.signal ? { signal: ctx.signal } : {}) });
|
|
297
|
+
if (!read.ok)
|
|
298
|
+
return read;
|
|
299
|
+
machines.push(read.value ?? listedOnly(sb));
|
|
577
300
|
}
|
|
578
|
-
return
|
|
301
|
+
return ok(machines);
|
|
579
302
|
}
|
|
580
303
|
/** Sandbox.kill, never signalled: a kill that cleans up after an abort must outlive it. Not found is done. */
|
|
581
|
-
async
|
|
582
|
-
|
|
583
|
-
return killed.ok || killed.error.code === "not_found" ? ok(undefined) : killed;
|
|
584
|
-
}
|
|
585
|
-
/**
|
|
586
|
-
* Everything between the create's answer and a computer that passed the drift check, whose value is what the check
|
|
587
|
-
* recorded that does not refuse it (notes). The diagnostic (#diagnose) is given every step alike up to the daemon's
|
|
588
|
-
* first connection, then runs its own inside step in place of the check and the listing's wait, and sees the
|
|
589
|
-
* read-back.
|
|
590
|
-
*/
|
|
591
|
-
async #prepare(spec, ref, sandbox, { deadline, maxDeadline, metadata, daemon, sha256 }, signal, diagnostic) {
|
|
592
|
-
const { uploadMs, execMs } = this.#timeouts;
|
|
593
|
-
const info = await this.#info(ref.id, signal);
|
|
594
|
-
if (!info.ok)
|
|
595
|
-
return info;
|
|
596
|
-
diagnostic?.readBack(info.value);
|
|
597
|
-
const vendor = this.#sandboxDrift(spec, info.value, metadata);
|
|
598
|
-
if (vendor.length > 0)
|
|
599
|
-
return fail("refused", `it did not match its spec: ${vendor.join("; ")}`);
|
|
600
|
-
const staging = `${STAGING}${randomBytes(8).toString("hex")}`;
|
|
601
|
-
const bytes = daemon.buffer.slice(daemon.byteOffset, daemon.byteOffset + daemon.byteLength);
|
|
602
|
-
const uploaded = await call(`the daemon's upload into ${ref.name}`, () => sandbox.files.write(staging, bytes, { user: "root", requestTimeoutMs: uploadMs, ...(signal ? { signal } : {}) }), uploadMs + CALL_SLACK_MS, signal);
|
|
603
|
-
if (!uploaded.ok)
|
|
604
|
-
return fail(uploaded.error.code, `the daemon's upload was refused: ${uploaded.error.message}`);
|
|
605
|
-
const commands = childCommands({ staging, deadline, user: `${this.#uid}:${this.#gid}`, display: this.#desktop?.display ?? "", maxDeadline });
|
|
606
|
-
const install = await this.#run(sandbox, commands.install, execMs, signal);
|
|
607
|
-
if (!install.ok)
|
|
608
|
-
return install;
|
|
609
|
-
if (install.value.exitCode !== 0)
|
|
610
|
-
return fail("refused", `installing the daemon failed (exit ${install.value.exitCode}): ${`${install.value.stdout} ${install.value.stderr}`.trim().slice(0, 500)}`);
|
|
611
|
-
const read = /^sha256 ([0-9a-f]{64})$/m.exec(install.value.stdout)?.[1];
|
|
612
|
-
if (read !== sha256)
|
|
613
|
-
return fail("refused", `it did not match its spec: daemon: uploaded sha256 ${sha256}, the installed binary reads back ${show(read)}`);
|
|
614
|
-
// The run's folder, after the daemon is in place (serve runs it) and before init starts: no tool program runs before
|
|
615
|
-
// it is mounted. A folder mounted for a computer create then gives up on is let go before the kill, never signalled.
|
|
616
|
-
if (spec.mount?.kind !== "archil")
|
|
617
|
-
return this.#start(spec, ref, sandbox, commands, signal, diagnostic);
|
|
618
|
-
const root = this.#root(sandbox, ref.name);
|
|
619
|
-
const mounted = await this.#mountArchil(root, ref, { mount: spec.mount, run: spec.labels?.[RUN_LABEL], epoch: claimEpoch(spec.labels) }, signal);
|
|
620
|
-
if (!mounted.ok)
|
|
621
|
-
return mounted;
|
|
622
|
-
const started = await this.#start(spec, ref, sandbox, commands, signal, diagnostic);
|
|
623
|
-
if (!started.ok || signal?.aborted)
|
|
624
|
-
await archilRelease({ root, client: undefined, timeoutMs: this.#timeouts.mountMs });
|
|
625
|
-
return started;
|
|
626
|
-
}
|
|
627
|
-
/** The rest of #prepare from the daemon's install on: init started, its first connection checked, the listing waited for. */
|
|
628
|
-
async #start(spec, ref, sandbox, commands, signal, diagnostic) {
|
|
629
|
-
const { requestMs } = this.#timeouts;
|
|
630
|
-
// No command timeout: envd kills a command when its timeout passes (e2b-dev/infra envd process/start.go:39-44).
|
|
631
|
-
// Never cancelled: envd keeps a command running when its stream ends (start.go:39-40); create disconnects after.
|
|
632
|
-
const init = await call(`starting the daemon in ${ref.name}`, () => sandbox.commands.run(commands.init, { background: true, user: "root", timeoutMs: 0, requestTimeoutMs: requestMs }), requestMs + CALL_SLACK_MS, signal);
|
|
633
|
-
if (!init.ok)
|
|
634
|
-
return init;
|
|
304
|
+
async delete(id, ctx) {
|
|
305
|
+
this.#sandboxes.delete(id);
|
|
635
306
|
try {
|
|
636
|
-
|
|
637
|
-
if (!opened.ok) {
|
|
638
|
-
const why = init.value.stderr.trim().slice(-500);
|
|
639
|
-
return opened.error.code === "aborted" ? opened : fail(opened.error.code, `the daemon did not answer: ${opened.error.message}${why ? `; init wrote: ${why}` : ""}`);
|
|
640
|
-
}
|
|
641
|
-
let notes = [];
|
|
642
|
-
try {
|
|
643
|
-
if (diagnostic) {
|
|
644
|
-
const inside = await diagnostic.inside(opened.value);
|
|
645
|
-
if (!inside.ok)
|
|
646
|
-
return inside;
|
|
647
|
-
}
|
|
648
|
-
else {
|
|
649
|
-
const archil = spec.mount?.kind === "archil" ? { mount: { kind: "archil", disk: spec.mount.disk, region: spec.mount.region, folder: spec.mount.folder }, epoch: claimEpoch(spec.labels) } : undefined;
|
|
650
|
-
const expected = archil === undefined ? undefined : { ...archil, expected: readBackOf({ ...archil.mount, token: "" }, archil.epoch) };
|
|
651
|
-
const inside = await this.#checkInside(opened.value, ref.name, spec.network, true, signal, expected);
|
|
652
|
-
if (!inside.ok)
|
|
653
|
-
return inside;
|
|
654
|
-
notes = inside.value;
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
finally {
|
|
658
|
-
await opened.value.close();
|
|
659
|
-
}
|
|
660
|
-
if (diagnostic)
|
|
661
|
-
return ok([]);
|
|
662
|
-
const listed = await this.#waitListed(ref, signal);
|
|
663
|
-
return listed.ok ? ok(notes) : listed;
|
|
307
|
+
await this.#Sandbox.kill(id, this.#api(ctx.timeoutMs));
|
|
664
308
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
/**
|
|
670
|
-
* Inside the computer: for a desktop just made, the X server started through the daemon and hello declaring the
|
|
671
|
-
* display; then the daemon's own report (hello, credentials, home, binary) and, for network none, the probe, which
|
|
672
|
-
* refuses on an answer and records a silent accept in the notes it returns (README, "Network none, read from inside");
|
|
673
|
-
* and, for an Archil computer, the mount read back from inside, held to the one expected. Its value says what was
|
|
674
|
-
* read back of the mount (mount), apart from the notes.
|
|
675
|
-
*/
|
|
676
|
-
async #checkInside(connection, name, network, starting, signal, archil) {
|
|
677
|
-
let current = connection;
|
|
678
|
-
if (starting && this.#desktop) {
|
|
679
|
-
const shown = await startDisplay(connection.client, this.#desktop, { version: VERSION, vendor: "e2b", signal });
|
|
680
|
-
if (!shown.ok)
|
|
681
|
-
return shown;
|
|
682
|
-
const hello = await connection.client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: this.#bounded(this.#timeouts.helloMs, signal) });
|
|
683
|
-
if (!hello.ok)
|
|
684
|
-
return hello.error.code === "aborted" && !signal?.aborted ? fail("timeout", `the daemon in ${name} did not answer hello within ${seconds(this.#timeouts.helloMs)}`) : hello;
|
|
685
|
-
current = { ...connection, hello: hello.value };
|
|
686
|
-
}
|
|
687
|
-
const found = await daemonDrift(current, this.#daemonExpected(), this.#timeouts.helloMs, signal);
|
|
688
|
-
if (!found.ok)
|
|
689
|
-
return found;
|
|
690
|
-
const drift = [...found.value];
|
|
691
|
-
const notes = [];
|
|
692
|
-
if (network === "none") {
|
|
693
|
-
const probe = await this.#probe(current, name, signal);
|
|
694
|
-
if (!probe.ok)
|
|
695
|
-
return probe;
|
|
696
|
-
drift.push(...probeNetworkDrift(probe.value));
|
|
697
|
-
notes.push(...probeNotes(probe.value, network));
|
|
698
|
-
}
|
|
699
|
-
if (archil === undefined)
|
|
700
|
-
return drift.length === 0 ? ok(notes) : fail("refused", `it did not match its spec: ${drift.join("; ")}`);
|
|
701
|
-
const mount = await this.#readMount(current, name, archil, signal);
|
|
702
|
-
if (!mount.ok)
|
|
703
|
-
return mount;
|
|
704
|
-
drift.push(...mountDrift(archil.expected, mount.value));
|
|
705
|
-
const read = mount.value === undefined ? {} : { mount: mount.value };
|
|
706
|
-
return drift.length === 0 ? { ...ok(notes), ...read } : fail("refused", `it did not match its spec: ${drift.join("; ")}`);
|
|
707
|
-
}
|
|
708
|
-
/**
|
|
709
|
-
* What is mounted at /workspace, read from inside through computerd (its /proc/self/mounts), exclusive when the
|
|
710
|
-
* resident serve answers a sync; undefined when nothing is mounted there.
|
|
711
|
-
*/
|
|
712
|
-
#readMount(connection, name, archil, signal) {
|
|
713
|
-
return readArchilMount(connection.client, archil, { name, timeoutMs: this.#timeouts.helloMs, ...(signal ? { signal } : {}) });
|
|
714
|
-
}
|
|
715
|
-
/**
|
|
716
|
-
* The root channel into a sandbox: a background command as root with stdin (index.mjs:5123-5146), its command line
|
|
717
|
-
* the argv quoted, bounded by timeoutMs (envd kills it then). stdin, when given, goes in with sendStdin; then
|
|
718
|
-
* closeStdin, so it reads end of file. What it printed is both streams, stdout first; a non-zero exit is a result.
|
|
719
|
-
* An error is the SDK's, in words that never hold what stdin was given.
|
|
720
|
-
*/
|
|
721
|
-
#root(sandbox, name) {
|
|
722
|
-
const { requestMs } = this.#timeouts;
|
|
723
|
-
return {
|
|
724
|
-
run: (argv, { stdin, timeoutMs, signal }) => call(`root's ${argv[0] === ARCHIL_HELPER ? `agentrun-archil ${argv[1]}` : argv[0]} in ${name}`, async () => {
|
|
725
|
-
// Stdin only for a step given one (mount and revoke's token). A step that reads none (serve, which detaches and
|
|
726
|
-
// exits at once; checkin; the preflight) may end before its stdin could be closed, and E2B then knows no such pid.
|
|
727
|
-
const handle = await sandbox.commands.run(argv.map(quote).join(" "), { background: true, stdin: stdin !== undefined, user: "root", timeoutMs, requestTimeoutMs: requestMs });
|
|
728
|
-
if (stdin !== undefined) {
|
|
729
|
-
try {
|
|
730
|
-
await sandbox.commands.sendStdin(handle.pid, new Uint8Array(Buffer.from(stdin, "utf8")), { requestTimeoutMs: requestMs });
|
|
731
|
-
await sandbox.commands.closeStdin(handle.pid, { requestTimeoutMs: requestMs });
|
|
732
|
-
}
|
|
733
|
-
catch (error) {
|
|
734
|
-
await handle.kill().catch(() => false);
|
|
735
|
-
throw error;
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
try {
|
|
739
|
-
const done = await handle.wait();
|
|
740
|
-
return { exitCode: done.exitCode, output: `${done.stdout}${done.stderr}` };
|
|
741
|
-
}
|
|
742
|
-
catch (error) {
|
|
743
|
-
const exited = error;
|
|
744
|
-
if (exited?.name === "CommandExitError" && typeof exited.exitCode === "number")
|
|
745
|
-
return { exitCode: exited.exitCode, output: `${exited.stdout ?? ""}${exited.stderr ?? ""}` };
|
|
746
|
-
throw error;
|
|
747
|
-
}
|
|
748
|
-
finally {
|
|
749
|
-
await handle.disconnect().catch(() => { });
|
|
750
|
-
}
|
|
751
|
-
}, timeoutMs + CALL_SLACK_MS, signal),
|
|
752
|
-
};
|
|
753
|
-
}
|
|
754
|
-
/** The shared Archil steps (archilMount) through root, with the takeover of this provider's lower epochs. */
|
|
755
|
-
#mountArchil(root, computer, { mount, run, epoch }, signal) {
|
|
756
|
-
return archilMount({ root, mount, self: computer, releaseOlder: () => releaseOlder(this, run, epoch, signal ? { signal } : {}), timeoutMs: this.#timeouts.mountMs, ...(signal ? { signal } : {}) });
|
|
757
|
-
}
|
|
758
|
-
#daemonExpected() {
|
|
759
|
-
const { kind, groups } = this.capabilities();
|
|
760
|
-
return { version: VERSION, uid: this.#uid, gid: this.#gid, arch: ARCH, kind, groups };
|
|
761
|
-
}
|
|
762
|
-
#bounded(ms, signal) {
|
|
763
|
-
return signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
|
|
764
|
-
}
|
|
765
|
-
/** A foreground command as root; a non-zero exit is a result with its code, not an error (index.mjs:2642-2660). */
|
|
766
|
-
async #run(sandbox, command, ms, signal) {
|
|
767
|
-
const ran = await call("a command in the sandbox", async () => {
|
|
768
|
-
try {
|
|
769
|
-
return await sandbox.commands.run(command, { user: "root", timeoutMs: ms, requestTimeoutMs: ms, ...(signal ? { signal } : {}) });
|
|
770
|
-
}
|
|
771
|
-
catch (error) {
|
|
772
|
-
const exited = error;
|
|
773
|
-
if (exited?.name === "CommandExitError" && typeof exited.exitCode === "number")
|
|
774
|
-
return { exitCode: exited.exitCode, stdout: exited.stdout ?? "", stderr: exited.stderr ?? "" };
|
|
309
|
+
catch (error) {
|
|
310
|
+
if (codeOf(error) !== "not_found")
|
|
775
311
|
throw error;
|
|
776
|
-
}
|
|
777
|
-
}, ms + CALL_SLACK_MS, signal);
|
|
778
|
-
return ran;
|
|
779
|
-
}
|
|
780
|
-
/** Every way a sandbox, as E2B reads it back, differs from what create asked for. Pure: no call. */
|
|
781
|
-
#sandboxDrift(spec, info, metadata) {
|
|
782
|
-
const found = [];
|
|
783
|
-
const mismatch = (field, declared, actual) => found.push(`${field}: declared ${show(declared)}, read back ${show(actual)}`);
|
|
784
|
-
// E2B reports the template's id, and its alias when it has one (index.mjs:5435-5437): a template asked for by an
|
|
785
|
-
// alias E2B does not report back cannot be held to it, and its label (below) records what was asked.
|
|
786
|
-
const alias = info.name;
|
|
787
|
-
if (info.templateId !== spec.image && alias !== undefined && alias !== spec.image && !alias.startsWith(`${spec.image}:`)) {
|
|
788
|
-
found.push(`template: declared ${show(spec.image)}, read back ${show(info.templateId)} (${alias})`);
|
|
789
312
|
}
|
|
790
|
-
|
|
791
|
-
if (info.metadata?.[key] !== value)
|
|
792
|
-
mismatch(`label ${key}`, value, info.metadata?.[key]);
|
|
793
|
-
const network = networkOf(info);
|
|
794
|
-
// An Archil computer's vendor network is open, for root to reach Archil; its tools' none is read from inside.
|
|
795
|
-
const vendor = spec.mount?.kind === "archil" ? "open" : spec.network;
|
|
796
|
-
if (network !== vendor)
|
|
797
|
-
found.push(`network: declared ${policyWords(vendor)}${spec.mount?.kind === "archil" ? " (E2B's, for root to reach Archil)" : ""}, read back ${policyWords(network)}`);
|
|
798
|
-
if (info.lifecycle?.onTimeout !== undefined && info.lifecycle.onTimeout !== "kill")
|
|
799
|
-
mismatch("lifecycle onTimeout", "kill", info.lifecycle.onTimeout);
|
|
800
|
-
if (info.lifecycle?.autoResume === true)
|
|
801
|
-
mismatch("lifecycle autoResume", false, true);
|
|
802
|
-
if (info.state !== "running")
|
|
803
|
-
mismatch("state", "running", info.state);
|
|
804
|
-
const end = info.endAt instanceof Date ? info.endAt.getTime() : Number.NaN;
|
|
805
|
-
const created = createdEnd(info);
|
|
806
|
-
if (Number.isNaN(end) || created === undefined)
|
|
807
|
-
found.push(`endAt: E2B reported ${show(info.endAt)} from a start of ${show(info.startedAt)}, so it might not end the computer`);
|
|
808
|
-
else if (Math.abs(end - created) > END_SLACK_MS)
|
|
809
|
-
found.push(`endAt: ${info.endAt.toISOString()} is not E2B's start plus the ${metadata[TIMEOUT_LABEL]} ms timeout create gave`);
|
|
810
|
-
return found;
|
|
811
|
-
}
|
|
812
|
-
/**
|
|
813
|
-
* getInfo, bounded by requestMs; not_found for a sandbox E2B does not have. With until, a time a whole listing must
|
|
814
|
-
* end by, the read is bounded by what is left of it as well, its race included, and a timeout of a read whose bound
|
|
815
|
-
* was that remainder is marked listBound: the listing's deadline ended it, whatever Date.now() reads after.
|
|
816
|
-
*/
|
|
817
|
-
async #info(id, signal, until) {
|
|
818
|
-
const { requestMs } = this.#timeouts;
|
|
819
|
-
const left = until === undefined ? undefined : Math.max(1, until - Date.now());
|
|
820
|
-
const ms = left === undefined ? requestMs : Math.min(requestMs, left);
|
|
821
|
-
const read = await call(`Sandbox.getInfo of ${id}`, () => this.#Sandbox.getInfo(id, this.#api(ms, signal)), left === undefined ? requestMs + CALL_SLACK_MS : left, signal);
|
|
822
|
-
return boundBy(read, left, requestMs);
|
|
823
|
-
}
|
|
824
|
-
/** This provider's sandbox for ref, as E2B reads it, or why not. */
|
|
825
|
-
async #own(ref, signal) {
|
|
826
|
-
const found = await this.#info(ref.id, signal);
|
|
827
|
-
if (!found.ok)
|
|
828
|
-
return found.error.code === "not_found" ? fail("not_found", `no E2B computer is ${ref.name} (${ref.id})`) : found;
|
|
829
|
-
if (!ours(found.value.metadata, ref.name))
|
|
830
|
-
return fail("not_found", `no E2B computer named ${ref.name} has the id ${ref.id}`);
|
|
831
|
-
return found;
|
|
313
|
+
return ok(undefined);
|
|
832
314
|
}
|
|
833
315
|
/**
|
|
834
|
-
* A connected Sandbox for envd's commands and files
|
|
835
|
-
*
|
|
836
|
-
*
|
|
316
|
+
* A connected Sandbox for envd's commands and files: the one create gave, or Sandbox.connect, whose timeout is a
|
|
317
|
+
* little under what is left: E2B moves a running sandbox's timer only to a longer one (index.d.mts:10250-10255), so
|
|
318
|
+
* connecting never moves the end. The adapter connects only to a sandbox it read running: connect resumes a paused one.
|
|
837
319
|
*/
|
|
838
|
-
async #
|
|
839
|
-
const
|
|
320
|
+
async #sandbox(id, ctx) {
|
|
321
|
+
const known = this.#sandboxes.get(id);
|
|
322
|
+
if (known !== undefined)
|
|
323
|
+
return known;
|
|
324
|
+
const info = await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal));
|
|
840
325
|
const left = info.endAt instanceof Date ? info.endAt.getTime() - Date.now() : 0;
|
|
841
326
|
const timeoutMs = Math.max(1_000, Math.floor(left / 1000) * 1000 - 2_000);
|
|
842
|
-
|
|
327
|
+
const sandbox = await this.#Sandbox.connect(id, { ...this.#api(ctx.timeoutMs, ctx.signal), timeoutMs });
|
|
328
|
+
this.#sandboxes.set(id, sandbox);
|
|
329
|
+
return sandbox;
|
|
843
330
|
}
|
|
844
|
-
/**
|
|
845
|
-
async
|
|
846
|
-
const
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
return opened;
|
|
851
|
-
await pause(LISTEN_RETRY_MS, signal);
|
|
852
|
-
}
|
|
331
|
+
/** files.write as root (index.mjs:2332-2435). */
|
|
332
|
+
async upload(id, path, bytes, ctx) {
|
|
333
|
+
const sandbox = await this.#sandbox(id, ctx);
|
|
334
|
+
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
335
|
+
await sandbox.files.write(path, buffer, { user: "root", requestTimeoutMs: ctx.timeoutMs, ...(ctx.signal ? { signal: ctx.signal } : {}) });
|
|
336
|
+
return ok(undefined);
|
|
853
337
|
}
|
|
854
338
|
/**
|
|
855
|
-
*
|
|
856
|
-
* (
|
|
857
|
-
*
|
|
858
|
-
* in order; close kills the bridge.
|
|
339
|
+
* A background command as root (index.mjs:5123-5146), its line the argv quoted. No command timeout, so envd never
|
|
340
|
+
* kills it (start.go:39-44); no retained output, so a long one keeps no copy of its stdout (index.mjs:2708-2711).
|
|
341
|
+
* Writes go one sendStdin at a time, in order; end is closeStdin; kill kills it and lets go of its stream.
|
|
859
342
|
*/
|
|
860
|
-
async
|
|
861
|
-
const
|
|
862
|
-
const
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
const
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
}));
|
|
884
|
-
}
|
|
885
|
-
catch (error) {
|
|
886
|
-
return fail(codeOf(error), `${what} failed: ${words(error)}`);
|
|
887
|
-
}
|
|
888
|
-
const started = await race(starting, what, requestMs + CALL_SLACK_MS, signal);
|
|
889
|
-
if (!started.ok) {
|
|
890
|
-
// The bridge has no command timeout: one envd starts after this was given up on is killed as it lands.
|
|
891
|
-
if (started.error.code === "timeout" || started.error.code === "aborted") {
|
|
892
|
-
starting.then((late) => void this.#endBridge(late), () => { });
|
|
893
|
-
return fail(started.error.code, `${started.error.message}; a bridge that starts after this is killed`);
|
|
894
|
-
}
|
|
895
|
-
return started;
|
|
896
|
-
}
|
|
897
|
-
const handle = started.value;
|
|
898
|
-
// The bridge's end, for any reason, ends what the client reads.
|
|
899
|
-
handle.wait().then(() => readable.end(), () => readable.end());
|
|
900
|
-
const writable = new Writable({
|
|
901
|
-
write(chunk, _encoding, done) {
|
|
902
|
-
sandbox.commands.sendStdin(handle.pid, new Uint8Array(chunk), { requestTimeoutMs: requestMs }).then(() => done(), (error) => done(error instanceof Error ? error : new Error(String(error))));
|
|
903
|
-
},
|
|
343
|
+
async exec(id, argv, { stdin }, ctx) {
|
|
344
|
+
const sandbox = await this.#sandbox(id, ctx);
|
|
345
|
+
const out = feed();
|
|
346
|
+
const err = feed();
|
|
347
|
+
const requestTimeoutMs = this.#requestMs;
|
|
348
|
+
const handle = await sandbox.commands.run(shellLine(argv), {
|
|
349
|
+
background: true,
|
|
350
|
+
stdin,
|
|
351
|
+
user: "root",
|
|
352
|
+
timeoutMs: 0,
|
|
353
|
+
requestTimeoutMs: ctx.timeoutMs,
|
|
354
|
+
retainOutput: false,
|
|
355
|
+
onStdout: (data) => out.push(new Uint8Array(Buffer.from(data, "utf8"))),
|
|
356
|
+
onStderr: (data) => err.push(new Uint8Array(Buffer.from(data, "utf8"))),
|
|
357
|
+
});
|
|
358
|
+
const exited = handle.wait().then((done) => done.exitCode, (error) => {
|
|
359
|
+
const code = error?.exitCode;
|
|
360
|
+
return typeof code === "number" ? code : -1;
|
|
361
|
+
});
|
|
362
|
+
void exited.then(() => {
|
|
363
|
+
out.end();
|
|
364
|
+
err.end();
|
|
365
|
+
void handle.disconnect().catch(() => { });
|
|
904
366
|
});
|
|
905
|
-
const client = new DaemonClient({ readable, writable });
|
|
906
|
-
let closed;
|
|
907
|
-
const close = () => (closed ??= (async () => {
|
|
908
|
-
client.close();
|
|
909
|
-
await this.#endBridge(handle);
|
|
910
|
-
})());
|
|
911
|
-
const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: this.#bounded(helloMs, signal) });
|
|
912
|
-
if (!hello.ok) {
|
|
913
|
-
await close();
|
|
914
|
-
if (signal?.aborted)
|
|
915
|
-
return fail("aborted", `hello to the daemon in ${name} was aborted`);
|
|
916
|
-
if (hello.error.code === "aborted")
|
|
917
|
-
return fail("timeout", `the daemon in ${name} did not answer hello within ${seconds(helloMs)}`);
|
|
918
|
-
if (hello.error.code !== "gone")
|
|
919
|
-
return hello;
|
|
920
|
-
return { ...vendorFail("e2b", `cannot reach the daemon in ${name}: ${stderr.trim() || hello.error.message}`), notListening: true };
|
|
921
|
-
}
|
|
922
|
-
return ok({ client, hello: hello.value, close });
|
|
923
|
-
}
|
|
924
|
-
/** Kills a stdio bridge and lets go of its stream, each bounded and never thrown: a connection's close, or a late start. */
|
|
925
|
-
async #endBridge(handle) {
|
|
926
|
-
await call("the stdio bridge's kill", () => handle.kill(), this.#timeouts.requestMs).catch(() => { });
|
|
927
|
-
await call("the stdio bridge's disconnect", () => handle.disconnect(), this.#timeouts.requestMs).catch(() => { });
|
|
928
|
-
}
|
|
929
|
-
/** `computerd probe` through the daemon, so it runs as the computer's own user. */
|
|
930
|
-
async #probe(connection, name, signal) {
|
|
931
|
-
const { probeMs } = this.#timeouts;
|
|
932
|
-
const argv = [DAEMON_IN_COMPUTER, "probe", ...this.#probeTargets.flatMap((target) => ["--connect", target])];
|
|
933
|
-
const ran = await connection.client.call("exec.run", { argv, timeoutMs: probeMs }, { signal: this.#bounded(probeMs + CALL_SLACK_MS, signal) });
|
|
934
|
-
if (!ran.ok) {
|
|
935
|
-
if (signal?.aborted)
|
|
936
|
-
return fail("aborted", `the probe in ${name} was aborted`);
|
|
937
|
-
if (ran.error.code === "aborted")
|
|
938
|
-
return fail("timeout", `the probe in ${name} did not answer within ${seconds(probeMs)}`);
|
|
939
|
-
return fail(ran.error.code, `the probe in ${name} failed: ${ran.error.message}`);
|
|
940
|
-
}
|
|
941
|
-
const { exitCode, stdout, stderr, timedOut } = ran.value;
|
|
942
|
-
if (timedOut)
|
|
943
|
-
return fail("timeout", `the probe in ${name} did not end within ${seconds(probeMs)}`);
|
|
944
|
-
if (exitCode !== 0)
|
|
945
|
-
return fail("refused", `the probe in ${name} exited with ${exitCode}: ${Buffer.from(stderr, "base64").toString("utf8").trim().slice(0, 300)}`);
|
|
946
|
-
const report = probeReportOf(stdout);
|
|
947
|
-
return "not" in report ? fail("refused", `the probe in ${name} ${report.not}`) : ok(report);
|
|
948
|
-
}
|
|
949
|
-
static {
|
|
950
|
-
diagnoseWith = (provider, image, signal) => provider.#diagnose(image, signal);
|
|
951
|
-
}
|
|
952
|
-
/**
|
|
953
|
-
* See diagnoseNetworkNone. Create is awaited, never raced by the signal (bounded by createMs), so a sandbox it makes is
|
|
954
|
-
* known by id; every step after it takes the signal; the kill and the wait for gone take none, bounded by goneMs.
|
|
955
|
-
*/
|
|
956
|
-
async #diagnose(image, signal) {
|
|
957
|
-
const report = { template: image, released: { gone: true, words: "nothing was made" } };
|
|
958
|
-
const spec = { image, lifetimeMs: DIAGNOSE_LIFETIME_MS, network: "none" };
|
|
959
|
-
if (signal?.aborted)
|
|
960
|
-
return { ...report, error: { code: "aborted", message: "the diagnostic was aborted before E2B was called" } };
|
|
961
|
-
const launched = await this.#launch(spec);
|
|
962
|
-
if (!launched.ok) {
|
|
963
|
-
const madeNothing = ["refused", "invalid", "denied", "limit", "not_found"].includes(launched.error.code);
|
|
964
|
-
return { ...report, error: launched.error, released: madeNothing ? report.released : { gone: false, words: launched.error.message } };
|
|
965
|
-
}
|
|
966
|
-
const { sandbox, ref, made } = launched.value;
|
|
967
|
-
report.computer = ref;
|
|
968
|
-
const prepared = signal?.aborted
|
|
969
|
-
? fail("aborted", "the diagnostic was aborted")
|
|
970
|
-
: await this.#prepare(spec, ref, sandbox, made, signal, {
|
|
971
|
-
readBack: ({ allowInternetAccess, network }) => {
|
|
972
|
-
report.readBack = { allowInternetAccess, allowPublicTraffic: network?.allowPublicTraffic, allowOut: network?.allowOut, denyOut: network?.denyOut };
|
|
973
|
-
},
|
|
974
|
-
inside: async (connection) => {
|
|
975
|
-
const checked = await this.#checkInside(connection, ref.name, "none", true, signal);
|
|
976
|
-
if (signal?.aborted)
|
|
977
|
-
return fail("aborted", "the diagnostic was aborted");
|
|
978
|
-
report.check = checked.ok ? "passed" : checked.error.message;
|
|
979
|
-
if (checked.ok && checked.value.length > 0)
|
|
980
|
-
report.notes = checked.value;
|
|
981
|
-
const diagnosed = await this.#probeDiagnose(connection, ref.name, signal);
|
|
982
|
-
if (!diagnosed.ok)
|
|
983
|
-
return diagnosed;
|
|
984
|
-
report.diagnosis = diagnosed.value;
|
|
985
|
-
return ok(undefined);
|
|
986
|
-
},
|
|
987
|
-
});
|
|
988
|
-
if (!prepared.ok)
|
|
989
|
-
report.error = signal?.aborted ? { code: "aborted", message: `the diagnostic was aborted: ${prepared.error.message}` } : prepared.error;
|
|
990
|
-
const killed = await this.#kill(ref.id);
|
|
991
|
-
const gone = killed.ok ? await this.#settle(ref) : killed;
|
|
992
|
-
report.released = gone.ok ? { gone: true, words: `${ref.name} was killed, and E2B reads it gone` } : { gone: false, words: `${ref.name}: ${gone.error.message}; E2B ends it at its 10-minute timeout` };
|
|
993
|
-
return report;
|
|
994
|
-
}
|
|
995
|
-
/** `computerd probe --diagnose` through the daemon, as the computer's own user: its JSON line, or why not. */
|
|
996
|
-
async #probeDiagnose(connection, name, signal) {
|
|
997
|
-
const { probeMs } = this.#timeouts;
|
|
998
|
-
const what = `probe --diagnose in ${name}`;
|
|
999
|
-
const ran = await connection.client.call("exec.run", { argv: [DAEMON_IN_COMPUTER, "probe", "--diagnose"], timeoutMs: probeMs }, { signal: this.#bounded(probeMs + CALL_SLACK_MS, signal) });
|
|
1000
|
-
if (!ran.ok) {
|
|
1001
|
-
if (signal?.aborted)
|
|
1002
|
-
return fail("aborted", `${what} was aborted`);
|
|
1003
|
-
return fail(ran.error.code === "aborted" ? "timeout" : ran.error.code, `${what} failed: ${ran.error.message}`);
|
|
1004
|
-
}
|
|
1005
|
-
const { exitCode, stdout, stderr, timedOut } = ran.value;
|
|
1006
|
-
if (timedOut)
|
|
1007
|
-
return fail("timeout", `${what} did not end within ${seconds(probeMs)}`);
|
|
1008
|
-
if (exitCode !== 0)
|
|
1009
|
-
return fail("refused", `${what} exited with ${exitCode}: ${Buffer.from(stderr, "base64").toString("utf8").trim().slice(0, 300)}`);
|
|
1010
|
-
try {
|
|
1011
|
-
const value = JSON.parse(Buffer.from(stdout, "base64").toString("utf8"));
|
|
1012
|
-
if (typeof value?.verdict === "string" && Array.isArray(value.results))
|
|
1013
|
-
return ok(value);
|
|
1014
|
-
}
|
|
1015
|
-
catch {
|
|
1016
|
-
// Not the diagnosis: below.
|
|
1017
|
-
}
|
|
1018
|
-
return fail("refused", `${what} wrote what is not its report`);
|
|
1019
|
-
}
|
|
1020
|
-
/** The live view: screen.watch on a connection of the watch's own (daemonWatch); a linux computer has no screen. */
|
|
1021
|
-
watch(ref, handlers, options) {
|
|
1022
|
-
return daemonWatch(this, ref, handlers, options);
|
|
1023
|
-
}
|
|
1024
|
-
async connect(ref) {
|
|
1025
|
-
const problem = refProblem(ref);
|
|
1026
|
-
if (problem)
|
|
1027
|
-
return fail("invalid", problem);
|
|
1028
|
-
const found = await this.#own(ref);
|
|
1029
|
-
if (!found.ok)
|
|
1030
|
-
return found;
|
|
1031
|
-
if (found.value.state !== "running")
|
|
1032
|
-
return fail("refused", `${ref.name} is ${found.value.state}, not running: its daemon does not run, and a connect would resume it`);
|
|
1033
|
-
const sandbox = await this.#connected(found.value);
|
|
1034
|
-
if (!sandbox.ok)
|
|
1035
|
-
return sandbox;
|
|
1036
|
-
const opened = await this.#open(sandbox.value, ref.name);
|
|
1037
|
-
if (!opened.ok)
|
|
1038
|
-
return opened;
|
|
1039
|
-
const { kind, groups } = this.capabilities();
|
|
1040
|
-
const drifted = helloDrift(opened.value.hello, { version: VERSION, kind, groups, arch: ARCH, fence: true });
|
|
1041
|
-
// An Archil computer's client syncs the run's folder after every call that may change it, before it answers.
|
|
1042
|
-
if (drifted.length === 0)
|
|
1043
|
-
return recordedArchil(found.value.metadata) === undefined ? opened : ok({ ...opened.value, client: syncingClient(opened.value.client) });
|
|
1044
|
-
await opened.value.close();
|
|
1045
|
-
return fail("refused", `the daemon in ${ref.name} does not match this provider: ${drifted.join("; ")}`);
|
|
1046
|
-
}
|
|
1047
|
-
async attach(ref, { signal } = {}) {
|
|
1048
|
-
const given = (typeof ref === "object" && ref !== null ? ref : {});
|
|
1049
|
-
if ((given.id === undefined) === (given.labels === undefined))
|
|
1050
|
-
return fail("invalid", "attach takes { id } or { labels }, one of them");
|
|
1051
|
-
if (given.id !== undefined) {
|
|
1052
|
-
const id = given.id;
|
|
1053
|
-
if (typeof id !== "string" || !SANDBOX_ID.test(id))
|
|
1054
|
-
return fail("invalid", `${String(id)} is not an E2B sandbox id`);
|
|
1055
|
-
const found = await this.#info(id, signal);
|
|
1056
|
-
if (!found.ok)
|
|
1057
|
-
return found.error.code === "not_found" ? fail("not_found", `no E2B computer has the id ${id}`) : found;
|
|
1058
|
-
if (!ours(found.value.metadata))
|
|
1059
|
-
return fail("not_found", `no E2B computer has the id ${id}`);
|
|
1060
|
-
return this.#attached(found.value, signal);
|
|
1061
|
-
}
|
|
1062
|
-
const problem = filterProblem(given.labels);
|
|
1063
|
-
if (problem)
|
|
1064
|
-
return fail("invalid", problem);
|
|
1065
|
-
const labels = given.labels;
|
|
1066
|
-
if (Object.keys(labels).length === 0)
|
|
1067
|
-
return fail("invalid", "attach by labels needs at least one label");
|
|
1068
|
-
const listed = await this.list(labels, { signal });
|
|
1069
|
-
if (!listed.ok)
|
|
1070
|
-
return listed;
|
|
1071
|
-
const words = JSON.stringify(labels);
|
|
1072
|
-
if (listed.value.length === 0)
|
|
1073
|
-
return fail("not_found", `no E2B computer has the labels ${words}`);
|
|
1074
|
-
if (listed.value.length > 1)
|
|
1075
|
-
return fail("invalid", `${listed.value.length} computers match the labels ${words}: ${listed.value.map((info) => info.ref.name).join(", ")}`);
|
|
1076
|
-
const found = await this.#own(listed.value[0].ref, signal);
|
|
1077
|
-
if (!found.ok)
|
|
1078
|
-
return found;
|
|
1079
|
-
return this.#attached(found.value, signal);
|
|
1080
|
-
}
|
|
1081
|
-
/**
|
|
1082
|
-
* The drift check of a computer attach did not make: its spec read back from E2B and held to what check() allows,
|
|
1083
|
-
* and, when it runs, its daemon, as at create. One that drifts is refused and left as it is.
|
|
1084
|
-
*/
|
|
1085
|
-
async #attached(info, signal) {
|
|
1086
|
-
const name = info.metadata[NAME_LABEL];
|
|
1087
|
-
const ref = { id: info.sandboxId, name };
|
|
1088
|
-
const found = [];
|
|
1089
|
-
const deadline = deadlineOf(info);
|
|
1090
|
-
if (deadline === undefined)
|
|
1091
|
-
found.push(`deadline: the label ${DEADLINE_LABEL} reads ${show(info.metadata[DEADLINE_LABEL])}, not the ISO time create writes`);
|
|
1092
|
-
const archil = recordedArchil(info.metadata);
|
|
1093
|
-
const network = this.#toolsNetwork(info);
|
|
1094
|
-
if (typeof network === "object")
|
|
1095
|
-
found.push(`network: ${policyWords(network)}, which this provider never makes`);
|
|
1096
|
-
const labels = Object.fromEntries(Object.entries(info.metadata).filter(([key]) => key !== COMPUTER_LABEL && !key.startsWith(`${COMPUTER_LABEL}.`) && key !== ARCHIL_MOUNT_LABEL));
|
|
1097
|
-
const image = info.metadata[IMAGE_LABEL] ?? info.templateId;
|
|
1098
|
-
const spec = { image, lifetimeMs: 1, network: typeof network === "object" ? "open" : network, labels };
|
|
1099
|
-
found.push(...this.check(spec).map(({ field, message }) => `${field}: ${message}, read back from the computer`));
|
|
1100
|
-
let kind;
|
|
1101
|
-
let notes = [];
|
|
1102
|
-
let mount;
|
|
1103
|
-
if (info.state === "running") {
|
|
1104
|
-
const sandbox = await this.#connected(info, signal);
|
|
1105
|
-
if (!sandbox.ok)
|
|
1106
|
-
return sandbox;
|
|
1107
|
-
const opened = await this.#open(sandbox.value, name, signal);
|
|
1108
|
-
if (!opened.ok)
|
|
1109
|
-
return opened;
|
|
1110
|
-
try {
|
|
1111
|
-
const inside = await this.#checkInside(opened.value, name, network, false, signal, archil);
|
|
1112
|
-
if (!inside.ok && inside.error.code !== "refused")
|
|
1113
|
-
return inside;
|
|
1114
|
-
if (!inside.ok)
|
|
1115
|
-
found.push(inside.error.message.replace(/^it did not match its spec: /, ""));
|
|
1116
|
-
else {
|
|
1117
|
-
notes = inside.value;
|
|
1118
|
-
mount = inside.mount;
|
|
1119
|
-
}
|
|
1120
|
-
}
|
|
1121
|
-
finally {
|
|
1122
|
-
await opened.value.close();
|
|
1123
|
-
}
|
|
1124
|
-
kind = opened.value.hello.kind;
|
|
1125
|
-
}
|
|
1126
|
-
else if (archil !== undefined)
|
|
1127
|
-
found.push(`mount: ${name} is ${info.state}, so its mount cannot be read back from inside`);
|
|
1128
|
-
if (found.length > 0)
|
|
1129
|
-
return fail("refused", `the computer ${name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
|
|
1130
367
|
return ok({
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
368
|
+
stdout: out.iterable,
|
|
369
|
+
stderr: err.iterable,
|
|
370
|
+
write: (bytes) => sandbox.commands.sendStdin(handle.pid, bytes, { requestTimeoutMs }),
|
|
371
|
+
end: () => sandbox.commands.closeStdin(handle.pid, { requestTimeoutMs }),
|
|
372
|
+
wait: () => exited,
|
|
373
|
+
kill: async () => {
|
|
374
|
+
await handle.kill().catch(() => false);
|
|
375
|
+
await handle.disconnect().catch(() => { });
|
|
376
|
+
out.end();
|
|
377
|
+
err.end();
|
|
1141
378
|
},
|
|
1142
|
-
...(notes.length > 0 ? { notes } : {}),
|
|
1143
379
|
});
|
|
1144
380
|
}
|
|
1145
381
|
/**
|
|
1146
|
-
*
|
|
1147
|
-
*
|
|
1148
|
-
*
|
|
382
|
+
* Moves E2B's timer (setTimeout, index.mjs:5529-5541) in the whole seconds E2B takes: up to clear create's end, so
|
|
383
|
+
* the end reads as moved (deadlineOf), and down at the most the computer may live, so E2B's timer never passes it by
|
|
384
|
+
* this machine's clock. A timer that would end before the deadline held now, or within create's rounding, is refused
|
|
385
|
+
* as limit, and nothing moves.
|
|
1149
386
|
*/
|
|
1150
|
-
async
|
|
1151
|
-
const
|
|
1152
|
-
const
|
|
1153
|
-
let paginator;
|
|
1154
|
-
try {
|
|
1155
|
-
paginator = this.#Sandbox.list({ ...this.#connection, requestTimeoutMs: requestMs, query: { metadata }, limit: PAGE });
|
|
1156
|
-
}
|
|
1157
|
-
catch (error) {
|
|
1158
|
-
return fail(codeOf(error), `Sandbox.list failed: ${words(error)}`);
|
|
1159
|
-
}
|
|
1160
|
-
const found = new Map();
|
|
1161
|
-
for (let page = 0; paginator.hasNext; page++) {
|
|
1162
|
-
if (page >= MAX_PAGES)
|
|
1163
|
-
return vendorFail("e2b", `Sandbox.list ran past ${MAX_PAGES} pages`);
|
|
1164
|
-
const left = Math.max(1, until - Date.now());
|
|
1165
|
-
const items = await call("Sandbox.list", () => paginator.nextItems({ requestTimeoutMs: Math.min(requestMs, left), ...(signal ? { signal } : {}) }), left, signal);
|
|
1166
|
-
if (!items.ok)
|
|
1167
|
-
return boundBy(items, given === undefined ? undefined : left, requestMs);
|
|
1168
|
-
if (!Array.isArray(items.value))
|
|
1169
|
-
return vendorFail("e2b", "Sandbox.list: a page that is not a list of sandboxes");
|
|
1170
|
-
for (const sb of items.value)
|
|
1171
|
-
if (typeof sb?.sandboxId === "string")
|
|
1172
|
-
found.set(sb.sandboxId, sb);
|
|
1173
|
-
}
|
|
1174
|
-
return ok([...found.values()]);
|
|
1175
|
-
}
|
|
1176
|
-
/**
|
|
1177
|
-
* Settings' test: one page of the account's sandboxes by the provider's own metadata, which makes nothing. The count is
|
|
1178
|
-
* read from the listing, with no getInfo of each: a busy account answers as fast, and one sandbox's read never fails a
|
|
1179
|
-
* working key. A further page is "or more".
|
|
1180
|
-
*/
|
|
1181
|
-
async testConnection({ signal } = {}) {
|
|
1182
|
-
const { requestMs } = this.#timeouts;
|
|
1183
|
-
let paginator;
|
|
1184
|
-
try {
|
|
1185
|
-
paginator = this.#Sandbox.list({ ...this.#connection, requestTimeoutMs: requestMs, query: { metadata: { [COMPUTER_LABEL]: "1" } }, limit: PAGE });
|
|
1186
|
-
}
|
|
1187
|
-
catch (error) {
|
|
1188
|
-
return countTested("E2B", fail(codeOf(error), `Sandbox.list failed: ${words(error)}`));
|
|
1189
|
-
}
|
|
1190
|
-
const items = await call("Sandbox.list", () => paginator.nextItems({ requestTimeoutMs: requestMs, ...(signal ? { signal } : {}) }), requestMs, signal);
|
|
1191
|
-
if (!items.ok)
|
|
1192
|
-
return countTested("E2B", fail(items.error.code, items.error.message));
|
|
1193
|
-
if (!Array.isArray(items.value))
|
|
1194
|
-
return countTested("E2B", vendorFail("e2b", "Sandbox.list: a page that is not a list of sandboxes"));
|
|
1195
|
-
const count = items.value.filter((sb) => typeof sb?.sandboxId === "string" && ours(sb.metadata)).length;
|
|
1196
|
-
return countTested("E2B", ok({ count, more: paginator.hasNext }));
|
|
1197
|
-
}
|
|
1198
|
-
/**
|
|
1199
|
-
* Every computer this provider made that carries all of these labels, running or paused (stopped), each one's
|
|
1200
|
-
* network read back by getInfo, since a listing does not carry it. One deadline, listMs from the call, bounds every
|
|
1201
|
-
* page and every read-back.
|
|
1202
|
-
*/
|
|
1203
|
-
async list(labels, { signal } = {}) {
|
|
1204
|
-
const problem = filterProblem(labels);
|
|
1205
|
-
if (problem)
|
|
1206
|
-
return fail("invalid", problem);
|
|
1207
|
-
const { listMs } = this.#timeouts;
|
|
1208
|
-
const until = Date.now() + listMs;
|
|
1209
|
-
const late = (why) => fail("timeout", `list did not finish within ${seconds(listMs)}: ${why}`);
|
|
1210
|
-
// A call the listing's deadline bounded (listBound) failed because that deadline passed, whichever of its timer and
|
|
1211
|
-
// Date.now() reads first; one bounded by its own requestMs, with time left, keeps its own words.
|
|
1212
|
-
const failed = ({ error, listBound }) => error.code === "timeout" && (listBound === true || Date.now() >= until) ? late(error.message) : fail(error.code, error.message);
|
|
1213
|
-
const listed = await this.#listPages({ ...labels, [COMPUTER_LABEL]: "1" }, signal, until);
|
|
1214
|
-
if (!listed.ok)
|
|
1215
|
-
return failed(listed);
|
|
1216
|
-
const infos = [];
|
|
1217
|
-
for (const item of listed.value) {
|
|
1218
|
-
if (!ours(item.metadata) || !Object.entries(labels).every(([key, value]) => item.metadata[key] === value))
|
|
1219
|
-
continue;
|
|
1220
|
-
if (Date.now() >= until)
|
|
1221
|
-
return late(`${infos.length} computers were read back, ${item.sandboxId} and any after it were not`);
|
|
1222
|
-
const read = await this.#info(item.sandboxId, signal, until);
|
|
1223
|
-
if (!read.ok) {
|
|
1224
|
-
if (read.error.code === "not_found")
|
|
1225
|
-
continue;
|
|
1226
|
-
return failed(read);
|
|
1227
|
-
}
|
|
1228
|
-
const info = read.value;
|
|
1229
|
-
if (info.state !== "running" && info.state !== "paused")
|
|
1230
|
-
continue;
|
|
1231
|
-
// list runs nothing in a computer: an Archil computer's mount is the one its label records, under its epoch label.
|
|
1232
|
-
const archil = recordedArchil(info.metadata);
|
|
1233
|
-
infos.push({
|
|
1234
|
-
ref: { id: info.sandboxId, name: info.metadata[NAME_LABEL] },
|
|
1235
|
-
labels: { ...info.metadata },
|
|
1236
|
-
deadline: deadlineOf(info),
|
|
1237
|
-
state: info.state === "running" ? "running" : "stopped",
|
|
1238
|
-
network: this.#toolsNetwork(info),
|
|
1239
|
-
...(archil === undefined ? {} : { mount: archil.expected }),
|
|
1240
|
-
});
|
|
1241
|
-
}
|
|
1242
|
-
return ok(infos);
|
|
1243
|
-
}
|
|
1244
|
-
/** For the sweep: every sandbox E2B lists with agentrun.computer=1, whatever its name, as E2B reports it, with its
|
|
1245
|
-
* metadata as its labels (the sweep kills only a conformance run's). */
|
|
1246
|
-
async listLabelled({ signal } = {}) {
|
|
1247
|
-
const listed = await this.#listPages({ [COMPUTER_LABEL]: "1" }, signal);
|
|
1248
|
-
return listed.ok ? ok(listed.value.map((sb) => ({ id: sb.sandboxId, state: sb.state, labels: { ...(sb.metadata ?? {}) } }))) : listed;
|
|
1249
|
-
}
|
|
1250
|
-
/** For the sweep: whether E2B still has a sandbox, read once by getInfo; not_found is gone. */
|
|
1251
|
-
async probeGone(id, { signal } = {}) {
|
|
1252
|
-
if (typeof id !== "string" || !SANDBOX_ID.test(id))
|
|
1253
|
-
return fail("invalid", `${String(id)} is not an E2B sandbox id`);
|
|
1254
|
-
const read = await this.#info(id, signal);
|
|
1255
|
-
if (!read.ok)
|
|
1256
|
-
return read.error.code === "not_found" ? ok({ gone: true }) : read;
|
|
1257
|
-
return ok({ gone: read.value.state !== "running" && read.value.state !== "paused", state: read.value.state });
|
|
1258
|
-
}
|
|
1259
|
-
/** For the sweep: Sandbox.kill of any sandbox the label query listed. Not found is done. */
|
|
1260
|
-
killById(id) {
|
|
1261
|
-
if (typeof id !== "string" || !SANDBOX_ID.test(id))
|
|
1262
|
-
return Promise.resolve(fail("invalid", `${String(id)} is not an E2B sandbox id`));
|
|
1263
|
-
return this.#kill(id);
|
|
1264
|
-
}
|
|
1265
|
-
/** E2B reads the policy back (getInfo). A change is refused: the provider fixes the network at create. */
|
|
1266
|
-
async network(ref, policy, { signal } = {}) {
|
|
1267
|
-
const problem = refProblem(ref);
|
|
1268
|
-
if (problem)
|
|
1269
|
-
return fail("invalid", problem);
|
|
1270
|
-
if (policy !== undefined && policy !== "none") {
|
|
1271
|
-
const wider = policy === "open" || (typeof policy === "object" && policy !== null && "allow" in policy);
|
|
1272
|
-
return fail("refused", wider ? `${OWN_NETWORK_ONLY}; ${FIXED}` : `${FIXED}; a network is "none"`);
|
|
1273
|
-
}
|
|
1274
|
-
const found = await this.#own(ref, signal);
|
|
1275
|
-
if (!found.ok)
|
|
1276
|
-
return found;
|
|
1277
|
-
let read = this.#toolsNetwork(found.value);
|
|
1278
|
-
// An Archil computer's E2B network is root's: its tools' none is read from inside, as the tool user: the daemon's own
|
|
1279
|
-
// network namespace's live interfaces are lo alone, none can be raised (computerd probe), and no probe target answers.
|
|
1280
|
-
if (read === "none" && recordedArchil(found.value.metadata) !== undefined && found.value.state === "running") {
|
|
1281
|
-
const sandbox = await this.#connected(found.value, signal);
|
|
1282
|
-
const opened = sandbox.ok ? await this.#open(sandbox.value, ref.name, signal) : sandbox;
|
|
1283
|
-
if (!opened.ok)
|
|
1284
|
-
return opened;
|
|
1285
|
-
try {
|
|
1286
|
-
const drift = await readOwnNetwork(opened.value.client, this.#timeouts.helloMs, this.#bounded(this.#timeouts.helloMs, signal));
|
|
1287
|
-
if (!drift.ok)
|
|
1288
|
-
return fail(drift.error.code, `${ref.name}: ${drift.error.message}`);
|
|
1289
|
-
if (drift.value.length > 0)
|
|
1290
|
-
read = { other: drift.value.join("; ") };
|
|
1291
|
-
const probe = await this.#probe(opened.value, ref.name, signal);
|
|
1292
|
-
if (!probe.ok)
|
|
1293
|
-
return probe;
|
|
1294
|
-
if (probe.value.reached.length > 0)
|
|
1295
|
-
read = { other: `its tools' network was created none, yet from inside an answer came back from ${probe.value.reached.join(", ")}` };
|
|
1296
|
-
}
|
|
1297
|
-
finally {
|
|
1298
|
-
await opened.value.close();
|
|
1299
|
-
}
|
|
1300
|
-
}
|
|
1301
|
-
if (policy === undefined || policy === read)
|
|
1302
|
-
return ok(read);
|
|
1303
|
-
return fail("refused", `${FIXED}: ${ref.name} reads back network ${policyWords(read)}, not ${policy}`);
|
|
1304
|
-
}
|
|
1305
|
-
/**
|
|
1306
|
-
* The tools' network as E2B's policy shows it: E2B's own, except for an Archil computer, whose open E2B network is
|
|
1307
|
-
* root's, to reach Archil: its tools' network is init's own, none, which network() and attach read from inside.
|
|
1308
|
-
*/
|
|
1309
|
-
#toolsNetwork(info) {
|
|
1310
|
-
const vendor = networkOf(info);
|
|
1311
|
-
if (recordedArchil(info.metadata) === undefined)
|
|
1312
|
-
return vendor;
|
|
1313
|
-
if (vendor === "open")
|
|
1314
|
-
return "none";
|
|
1315
|
-
return { other: `an Archil computer whose E2B network reads ${policyWords(vendor)}, not the open one create makes for root to reach Archil` };
|
|
1316
|
-
}
|
|
1317
|
-
/**
|
|
1318
|
-
* Moves E2B's timer to now + ttlMs (setTimeout, index.mjs:5529-5541), then init's own deadline to the end E2B reads
|
|
1319
|
-
* back, and returns the deadline init took; never earlier than the current end, never past create's time plus the
|
|
1320
|
-
* cap, which init was given as its maximum. There is no label to move: E2B has no call that changes metadata, and
|
|
1321
|
-
* list() reads the vendor's end. A provider runs one extend of a computer at a time, each reading the deadline the one
|
|
1322
|
-
* before it left, so a slow, shorter extend never pulls E2B's timer under a longer one's.
|
|
1323
|
-
*/
|
|
1324
|
-
async extend(ref, ttlMs, { signal } = {}) {
|
|
1325
|
-
const problem = refProblem(ref);
|
|
1326
|
-
if (problem)
|
|
1327
|
-
return fail("invalid", problem);
|
|
1328
|
-
if (!isWhole(ttlMs) || ttlMs <= 0)
|
|
1329
|
-
return fail("invalid", "extend takes ttlMs, a whole number of milliseconds above 0");
|
|
1330
|
-
const before = this.#extending.get(ref.id) ?? Promise.resolve();
|
|
1331
|
-
const mine = before.then(() => this.#extend(ref, ttlMs, signal));
|
|
1332
|
-
const done = mine.then(() => { }, () => { });
|
|
1333
|
-
this.#extending.set(ref.id, done);
|
|
1334
|
-
try {
|
|
1335
|
-
return await mine;
|
|
1336
|
-
}
|
|
1337
|
-
finally {
|
|
1338
|
-
if (this.#extending.get(ref.id) === done)
|
|
1339
|
-
this.#extending.delete(ref.id);
|
|
1340
|
-
}
|
|
1341
|
-
}
|
|
1342
|
-
/** One extend, run when the one before it on the same computer has ended: see extend. */
|
|
1343
|
-
async #extend(ref, ttlMs, signal) {
|
|
1344
|
-
const found = await this.#own(ref, signal);
|
|
1345
|
-
if (!found.ok)
|
|
1346
|
-
return found;
|
|
1347
|
-
const info = found.value;
|
|
1348
|
-
if (info.state !== "running")
|
|
1349
|
-
return fail("refused", `${ref.name} is ${info.state}, not running`);
|
|
1350
|
-
const most = isoOf(info.metadata[MAX_LABEL]);
|
|
1351
|
-
if (most === undefined)
|
|
1352
|
-
return fail("refused", `${ref.name}'s label ${MAX_LABEL} reads ${show(info.metadata[MAX_LABEL])}, so the most it may live is unknown`);
|
|
1353
|
-
const current = deadlineOf(info) ?? info.endAt;
|
|
387
|
+
async setTimer(id, { end, most }, ctx) {
|
|
388
|
+
const info = await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal));
|
|
389
|
+
const machine = machineOf(info);
|
|
1354
390
|
const now = Date.now();
|
|
1355
|
-
const target =
|
|
1356
|
-
if (target > most.getTime()) {
|
|
1357
|
-
return fail("limit", `${new Date(target).toISOString()} is past ${most.toISOString()}, the most this computer may live: create's time plus this provider's ${seconds(this.#maxLifetimeMs)} cap`);
|
|
1358
|
-
}
|
|
1359
|
-
if (target <= current.getTime())
|
|
1360
|
-
return ok({ deadline: current });
|
|
1361
|
-
// E2B takes whole seconds (index.mjs:502-504): up to clear create's end, so list() reads the move (deadlineOf), and
|
|
1362
|
-
// down at the most this computer may live, so E2B's timer never passes it by this machine's clock.
|
|
391
|
+
const target = end.getTime();
|
|
1363
392
|
const created = createdEnd(info);
|
|
1364
393
|
const want = created === undefined ? target : Math.max(target, clearOf(created));
|
|
1365
394
|
const timerMs = Math.min(Math.ceil((want - now) / 1000) * 1000, Math.floor((most.getTime() - now) / 1000) * 1000);
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
const
|
|
1369
|
-
const
|
|
395
|
+
const vendorEnd = machine.endsAt?.getTime() ?? Number.NaN;
|
|
396
|
+
const current = (deadlineOf(machine) ?? machine.endsAt)?.getTime() ?? now;
|
|
397
|
+
const held = Number.isNaN(vendorEnd) ? current : Math.max(current, vendorEnd);
|
|
398
|
+
const name = info.metadata?.["agentrun.computer.name"] ?? id;
|
|
1370
399
|
if (now + timerMs < held) {
|
|
1371
|
-
return fail("limit", `no whole number of seconds E2B takes moves ${
|
|
400
|
+
return fail("limit", `no whole number of seconds E2B takes moves ${name}'s end from ${new Date(held).toISOString()} to ${end.toISOString()} without passing ${most.toISOString()}, the most this computer may live; nothing moved`);
|
|
1372
401
|
}
|
|
1373
402
|
if (created !== undefined && now + timerMs < clearOf(created)) {
|
|
1374
|
-
return fail("limit", `${
|
|
1375
|
-
}
|
|
1376
|
-
const { requestMs } = this.#timeouts;
|
|
1377
|
-
const moved = await call(`Sandbox.setTimeout of ${ref.name}`, () => this.#Sandbox.setTimeout(ref.id, timerMs, this.#api(requestMs, signal)), requestMs + CALL_SLACK_MS, signal);
|
|
1378
|
-
if (!moved.ok)
|
|
1379
|
-
return fail(moved.error.code, `E2B's timer did not move, so nothing did: ${moved.error.message}`);
|
|
1380
|
-
const after = await this.#info(ref.id, signal);
|
|
1381
|
-
if (!after.ok)
|
|
1382
|
-
return fail(after.error.code, `E2B's timer was asked to move, and reading it back failed: ${after.error.message}; init's deadline did not move`);
|
|
1383
|
-
const end = after.value.endAt;
|
|
1384
|
-
const sandbox = await this.#connected(after.value, signal);
|
|
1385
|
-
const opened = sandbox.ok ? await this.#open(sandbox.value, ref.name, signal) : sandbox;
|
|
1386
|
-
if (!opened.ok)
|
|
1387
|
-
return fail(opened.error.code, `E2B's timer moved to ${end.toISOString()}, and init's deadline did not: ${opened.error.message}`);
|
|
1388
|
-
let took;
|
|
1389
|
-
try {
|
|
1390
|
-
// E2B's end is its clock, and the setTimeout's own transit adds to it: init's never goes past the maximum it was given.
|
|
1391
|
-
const at = new Date(Math.min(end.getTime(), most.getTime())).toISOString();
|
|
1392
|
-
const extended = await opened.value.client.call("deadline.extend", { at }, { signal: this.#bounded(this.#timeouts.helloMs, signal) });
|
|
1393
|
-
if (!extended.ok)
|
|
1394
|
-
return fail(extended.error.code, `E2B's timer moved to ${end.toISOString()}, and init's deadline did not: ${extended.error.message}`);
|
|
1395
|
-
const answered = Date.parse(extended.value.at);
|
|
1396
|
-
took = new Date(Number.isNaN(answered) ? at : answered);
|
|
1397
|
-
}
|
|
1398
|
-
finally {
|
|
1399
|
-
await opened.value.close();
|
|
403
|
+
return fail("limit", `${end.toISOString()} is within E2B's rounding of the end create gave ${name}, and moving E2B's end clear of it would pass ${most.toISOString()}, the most this computer may live`);
|
|
1400
404
|
}
|
|
1401
|
-
|
|
405
|
+
await this.#Sandbox.setTimeout(id, timerMs, this.#api(ctx.timeoutMs, ctx.signal));
|
|
406
|
+
return ok(undefined);
|
|
1402
407
|
}
|
|
1403
408
|
/**
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1406
|
-
*
|
|
1407
|
-
* lists it, within goneMs and the caller's signal, the one step the signal ends. A running Archil computer lets go of
|
|
1408
|
-
* the run's folder first (archilRelease: the final sync through computerd, then checkin as root); the kill runs
|
|
1409
|
-
* whatever that answers. A folder not let go cleanly loses nothing (every call that changed it synced, and the next
|
|
1410
|
-
* claim revokes the hold), so it is said through onNote, and the release succeeds once the sandbox is gone.
|
|
409
|
+
* Settings' test: one page of the account's sandboxes by the adapter's own metadata, which makes nothing. The count is
|
|
410
|
+
* read from the listing, with no getInfo of each: a busy account answers as fast, and one sandbox's read never fails a
|
|
411
|
+
* working key. A further page is "or more".
|
|
1411
412
|
*/
|
|
1412
|
-
async
|
|
1413
|
-
const problem = refProblem(ref);
|
|
1414
|
-
if (problem)
|
|
1415
|
-
return fail("invalid", problem);
|
|
1416
|
-
if (how !== "stop" && how !== "delete")
|
|
1417
|
-
return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
|
|
1418
|
-
if (how === "stop")
|
|
1419
|
-
return fail("unsupported", STOP);
|
|
1420
|
-
const found = await this.#info(ref.id);
|
|
1421
|
-
if (!found.ok)
|
|
1422
|
-
return found.error.code === "not_found" ? ok(undefined) : found;
|
|
1423
|
-
if (!ours(found.value.metadata, ref.name))
|
|
1424
|
-
return fail("not_found", `no E2B computer is ${ref.name} (${ref.id}): the sandbox is not this provider's, so it is left as it is`);
|
|
1425
|
-
const letGo = recordedArchil(found.value.metadata) !== undefined && found.value.state === "running" ? await this.#letGo(found.value, ref.name, signal) : ok(undefined);
|
|
1426
|
-
const killed = await this.#kill(ref.id);
|
|
1427
|
-
const gone = killed.ok ? await this.#settle(ref, signal) : killed;
|
|
1428
|
-
if (letGo.ok)
|
|
1429
|
-
return gone;
|
|
1430
|
-
if (!gone.ok)
|
|
1431
|
-
return fail(gone.error.code, `${gone.error.message}; and ${letGo.error.message}`);
|
|
1432
|
-
this.#onNote?.({ computer: ref.name, note: `${ref.name} was killed, and ${letGo.error.message}` });
|
|
1433
|
-
return gone;
|
|
1434
|
-
}
|
|
1435
|
-
/** A running Archil computer's folder let go: the final sync through a connection when it answers, then checkin as root. */
|
|
1436
|
-
async #letGo(info, name, signal) {
|
|
1437
|
-
const sandbox = await this.#connected(info, signal);
|
|
1438
|
-
if (!sandbox.ok)
|
|
1439
|
-
return fail(sandbox.error.code, `the run's folder was not let go: ${sandbox.error.message}`);
|
|
1440
|
-
const opened = await this.#open(sandbox.value, name, signal);
|
|
413
|
+
async testConnection(ctx) {
|
|
1441
414
|
try {
|
|
1442
|
-
|
|
415
|
+
const paginator = this.#Sandbox.list({ ...this.#connection, requestTimeoutMs: ctx.timeoutMs, query: { metadata: { "agentrun.computer": "1" } }, limit: PAGE });
|
|
416
|
+
const items = await paginator.nextItems({ requestTimeoutMs: ctx.timeoutMs, ...(ctx.signal ? { signal: ctx.signal } : {}) });
|
|
417
|
+
if (!Array.isArray(items))
|
|
418
|
+
return countTested("E2B", fail("vendor", "Sandbox.list: a page that is not a list of sandboxes"));
|
|
419
|
+
const count = items.filter((sb) => typeof sb?.sandboxId === "string" && ours(sb.metadata)).length;
|
|
420
|
+
return countTested("E2B", ok({ count, more: paginator.hasNext }));
|
|
1443
421
|
}
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
await opened.value.close();
|
|
422
|
+
catch (error) {
|
|
423
|
+
return countTested("E2B", fail(codeOf(error), `Sandbox.list failed: ${words(error)}`));
|
|
1447
424
|
}
|
|
1448
425
|
}
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
let
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
if (listed.error.code === "aborted")
|
|
1473
|
-
return { last };
|
|
1474
|
-
return { failed: fail(listed.error.code, `release of ${ref.name}: the listing failed (${listed.error.message}); it last read ${last}`) };
|
|
1475
|
-
}
|
|
1476
|
-
if (listed.value.some((sb) => sb.sandboxId === ref.id)) {
|
|
1477
|
-
agreed = 0;
|
|
1478
|
-
last = `${last}, still listed`;
|
|
1479
|
-
return { last };
|
|
1480
|
-
}
|
|
1481
|
-
return ++agreed >= LISTED_ROUNDS ? { settled: true } : { last };
|
|
1482
|
-
};
|
|
1483
|
-
const { pollMs, goneMs } = this.#timeouts;
|
|
1484
|
-
const waited = await waitUntil(read, (state) => !("last" in state), {
|
|
1485
|
-
boundMs: goneMs,
|
|
1486
|
-
...(signal ? { signal } : {}),
|
|
1487
|
-
minMs: Math.min(pollMs, RELEASE_POLL_MAX_MS),
|
|
1488
|
-
maxMs: RELEASE_POLL_MAX_MS,
|
|
1489
|
-
what: `${ref.name} to be gone after its kill`,
|
|
1490
|
-
describe: (state) => ("last" in state ? `E2B read it ${state.last}` : "done"),
|
|
1491
|
-
});
|
|
1492
|
-
if (!waited.ok)
|
|
1493
|
-
return waited;
|
|
1494
|
-
return "failed" in waited.value ? waited.value.failed : ok(undefined);
|
|
1495
|
-
}
|
|
1496
|
-
/** Create waits until the listing shows the new computer, twice running, so list() shows it once create returns. */
|
|
1497
|
-
async #waitListed(ref, signal) {
|
|
1498
|
-
const until = Date.now() + this.#timeouts.listedMs;
|
|
1499
|
-
for (let hits = 0;;) {
|
|
1500
|
-
const listed = await this.#listPages({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: ref.name }, signal);
|
|
1501
|
-
if (!listed.ok)
|
|
1502
|
-
return listed;
|
|
1503
|
-
hits = listed.value.some((sb) => sb.sandboxId === ref.id) ? hits + 1 : 0;
|
|
1504
|
-
if (hits >= LISTED_ROUNDS)
|
|
1505
|
-
return ok(undefined);
|
|
1506
|
-
if (Date.now() >= until)
|
|
1507
|
-
return fail("timeout", `the computer was not listed within ${seconds(this.#timeouts.listedMs)} of its creation`);
|
|
1508
|
-
await pause(Math.min(LISTED_POLL_MS, LISTED_POLL_MAX_MS, this.#timeouts.pollMs), signal);
|
|
1509
|
-
if (signal?.aborted)
|
|
1510
|
-
return fail("aborted", "create was aborted while it waited for the listing");
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Computers that are E2B sandboxes, on the shared adapter. A spec's image is an E2B template (its name or id):
|
|
429
|
+
* "desktop" is E2B Desktop's, with Xvfb, x11vnc and noVNC (e2b-dev/desktop template.py:21-65).
|
|
430
|
+
*/
|
|
431
|
+
export class E2BProvider extends HostedProvider {
|
|
432
|
+
constructor(options) {
|
|
433
|
+
// A caller who still names the option is told it is gone, whatever its value: it once let public traffic in.
|
|
434
|
+
if (typeof options === "object" && options !== null && Object.hasOwn(options, "publicStream"))
|
|
435
|
+
throw new Error(PUBLIC);
|
|
436
|
+
const { apiKey, Sandbox, domain = DEFAULT_DOMAIN, kind = "desktop", maxLifetimeMs = HOBBY_MAX_MS, ...rest } = options;
|
|
437
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
438
|
+
throw new Error("an E2B API key is required");
|
|
439
|
+
const lacks = ["create", "connect", "getInfo", "setTimeout", "kill", "list"].filter((name) => typeof Sandbox?.[name] !== "function");
|
|
440
|
+
if (lacks.length > 0)
|
|
441
|
+
throw new Error(`options.Sandbox must be the e2b SDK's Sandbox class; it lacks ${lacks.join(", ")}`);
|
|
442
|
+
const ambient = ambientProblem();
|
|
443
|
+
if (ambient)
|
|
444
|
+
throw new Error(ambient);
|
|
445
|
+
if (typeof domain !== "string" || !DOMAIN.test(domain))
|
|
446
|
+
throw new Error(`the E2B domain must be a host name such as ${DEFAULT_DOMAIN}, not ${JSON.stringify(domain)}`);
|
|
447
|
+
if (!isWhole(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > PRO_MAX_MS) {
|
|
448
|
+
throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most 24 h (${PRO_MAX_MS} ms), E2B Pro's longest sandbox; Hobby's is 1 h`);
|
|
1511
449
|
}
|
|
450
|
+
const requestMs = rest.timeouts?.requestMs ?? DEFAULT_REQUEST_MS;
|
|
451
|
+
super(new E2BHost(Sandbox, connectionOptions({ apiKey, domain }), requestMs), { ...rest, label: "E2B", kind, maxLifetimeMs });
|
|
1512
452
|
}
|
|
1513
453
|
}
|