@parcha/agentrun-computer 0.1.0-beta.36 → 0.1.0-beta.38
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 +547 -478
- package/box/Dockerfile +18 -1
- package/box/README.md +13 -0
- package/box/build-agent37.mjs +158 -0
- package/box/build-daytona.py +2 -2
- package/box/build-e2b.mjs +41 -18
- package/box/recipe.mjs +43 -0
- package/dist/agent37-ssh.d.ts +89 -0
- package/dist/agent37-ssh.js +445 -0
- package/dist/agent37.d.ts +104 -0
- package/dist/agent37.js +402 -0
- package/dist/attach.d.ts +146 -0
- package/dist/attach.js +469 -0
- package/dist/browserbase.d.ts +2 -10
- package/dist/browserbase.js +3 -6
- package/dist/client.d.ts +45 -4
- package/dist/client.js +92 -4
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/computerd.json +4 -0
- package/dist/conformance/agent37.d.ts +96 -0
- package/dist/conformance/agent37.js +154 -0
- package/dist/conformance/cases/apps.d.ts +11 -0
- package/dist/conformance/cases/apps.js +173 -73
- package/dist/conformance/cases/health.js +14 -0
- package/dist/conformance/cases/index.js +2 -0
- package/dist/conformance/cases/isolation.d.ts +7 -5
- package/dist/conformance/cases/isolation.js +44 -14
- package/dist/conformance/cases/mount.js +1 -1
- 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 +94 -9
- package/dist/conformance/daytona.d.ts +9 -20
- package/dist/conformance/daytona.js +12 -21
- package/dist/conformance/e2b.d.ts +6 -0
- package/dist/conformance/e2b.js +9 -2
- package/dist/conformance/exec-stream.d.ts +45 -0
- package/dist/conformance/exec-stream.js +486 -0
- 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 +13 -5
- 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 +20 -133
- package/dist/daytona.js +405 -1449
- package/dist/descriptor.d.ts +11 -1
- package/dist/descriptor.js +9 -0
- package/dist/descriptors/agent37.d.ts +41 -0
- package/dist/descriptors/agent37.js +28 -0
- package/dist/descriptors/daytona.d.ts +6 -5
- package/dist/descriptors/daytona.js +9 -5
- package/dist/descriptors/index.d.ts +42 -7
- 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/descriptors/shared.d.ts +1 -1
- package/dist/descriptors/shared.js +2 -2
- package/dist/desktop.d.ts +18 -4
- package/dist/desktop.js +89 -9
- package/dist/docker.d.ts +7 -10
- package/dist/docker.js +272 -34
- package/dist/drift.js +4 -4
- package/dist/e2b.d.ts +16 -290
- package/dist/e2b.js +230 -1393
- package/dist/fake-ui-driver.d.ts +97 -0
- package/dist/fake-ui-driver.js +717 -0
- package/dist/host.d.ts +201 -0
- package/dist/host.js +8 -0
- package/dist/hosted/process.d.ts +81 -0
- package/dist/hosted/process.js +259 -0
- package/dist/hosted/provider.d.ts +160 -0
- package/dist/hosted/provider.js +1415 -0
- package/dist/hosted/rest.d.ts +66 -0
- package/dist/hosted/rest.js +121 -0
- package/dist/hosted/scripts.d.ts +82 -0
- package/dist/{child.js → hosted/scripts.js} +118 -12
- package/dist/hosted/values.d.ts +5 -0
- package/dist/hosted/values.js +8 -0
- package/dist/index.d.ts +7 -3
- package/dist/index.js +7 -4
- package/dist/kernel.d.ts +2 -10
- package/dist/kernel.js +3 -6
- package/dist/kinds.d.ts +11 -2
- package/dist/kinds.js +20 -4
- package/dist/local-chrome.d.ts +2 -10
- package/dist/local-chrome.js +3 -6
- package/dist/modal.d.ts +22 -257
- package/dist/modal.js +183 -1280
- package/dist/mount-archil.d.ts +8 -4
- package/dist/mount-archil.js +22 -11
- package/dist/mount.d.ts +10 -4
- package/dist/mount.js +8 -4
- 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 -13
- package/dist/orgo.js +32 -21
- package/dist/phone-harness.d.ts +31 -28
- package/dist/phone-harness.js +510 -702
- package/dist/png.d.ts +4 -0
- package/dist/png.js +27 -0
- package/dist/protocol.d.ts +339 -33
- package/dist/protocol.js +97 -3
- package/dist/provider.d.ts +36 -8
- package/dist/provider.js +16 -0
- package/dist/providers.d.ts +11 -12
- package/dist/result.d.ts +1 -1
- package/dist/screen-watch.js +34 -6
- package/dist/surface/api.d.ts +260 -0
- package/dist/surface/api.js +1 -0
- package/dist/surface/core.d.ts +55 -0
- package/dist/surface/core.js +475 -0
- package/dist/surface/index.d.ts +5 -0
- package/dist/surface/index.js +3 -0
- package/dist/surface/outline.d.ts +10 -0
- package/dist/surface/outline.js +51 -0
- package/dist/surface/script.d.ts +10 -0
- package/dist/surface/script.js +94 -0
- package/dist/ui-engine.d.ts +114 -0
- package/dist/ui-engine.js +814 -0
- package/package.json +18 -3
- package/dist/child.d.ts +0 -42
- package/dist/conformance/daytona-sweep.d.ts +0 -18
- package/dist/conformance/daytona-sweep.js +0 -126
- 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,35 +1,13 @@
|
|
|
1
|
-
// The E2B provisioner: E2B Desktop sandboxes (kind desktop) or E2B's plain template (kind linux), every call through
|
|
2
|
-
// the host's own E2B JS SDK (the `e2b` package), of which this package names only the slice it uses (E2BSandboxClass)
|
|
3
|
-
// and 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 init starts as a background command, dropped to a user with no capabilities;
|
|
5
|
-
// connect() carries stdio over a background command's stdin and stdout. Every SDK fact used here is cited in the
|
|
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";
|
|
15
1
|
import { E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE } from "./descriptors/e2b.js";
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
|
|
23
|
-
import { failFor, ok, vendorFail } from "./result.js";
|
|
24
|
-
import { daemonWatch } from "./screen-watch.js";
|
|
25
|
-
import { countTested } from "./test-connection.js";
|
|
26
|
-
import { waitUntil } from "./wait.js";
|
|
27
|
-
/** This module's failures: one with code vendor names E2B. */
|
|
28
|
-
const fail = failFor("e2b");
|
|
2
|
+
import { DEADLINE_LABEL, show } from "./drift.js";
|
|
3
|
+
import { HostError } from "./host.js";
|
|
4
|
+
import { deadlineOf, HostedProvider, isoOf, MAX_LABEL, timeoutsOf } from "./hosted/provider.js";
|
|
5
|
+
import { shellLine } from "./hosted/scripts.js";
|
|
6
|
+
import { dateOf, DOMAIN, isWhole } from "./hosted/values.js";
|
|
7
|
+
import { PassThrough } from "node:stream";
|
|
29
8
|
/** Not a literal, so no type checker or bundler resolves the SDK from this package. */
|
|
30
9
|
const E2B_PACKAGE = "e2b";
|
|
31
10
|
const DEFAULT_DOMAIN = "e2b.app";
|
|
32
|
-
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
33
11
|
/** The connection options every SDK call is given. Exported for the test that hands them to the real SDK. */
|
|
34
12
|
export function connectionOptions({ apiKey, domain }) {
|
|
35
13
|
return { apiKey, domain, apiUrl: `https://api.${domain}`, debug: false };
|
|
@@ -53,113 +31,36 @@ function ambientProblem() {
|
|
|
53
31
|
* never echoing the key.
|
|
54
32
|
*/
|
|
55
33
|
export async function create(options) {
|
|
56
|
-
const {
|
|
57
|
-
if (typeof apiKey !== "string" || apiKey === "")
|
|
58
|
-
throw new Error("options.apiKey, the E2B API key, is required: the provider reads no environment, so the caller passes it");
|
|
59
|
-
const ambient = ambientProblem();
|
|
60
|
-
if (ambient)
|
|
61
|
-
throw new Error(ambient);
|
|
34
|
+
const { Sandbox: given, ...rest } = options ?? {};
|
|
62
35
|
const Sandbox = given ?? (await import(E2B_PACKAGE)).Sandbox;
|
|
63
|
-
return new E2BProvider({ ...rest,
|
|
36
|
+
return new E2BProvider({ ...rest, Sandbox });
|
|
64
37
|
}
|
|
65
38
|
/** The conformance CLI's module for E2B: its live switch, the run's 30-minute cap, its template and the drifted twin. */
|
|
66
39
|
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
40
|
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
41
|
/** 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;
|
|
42
|
+
const TIMEOUT_LABEL = "agentrun.computer.timeout-ms";
|
|
80
43
|
/** E2B Hobby's longest sandbox: 1 h (index.d.mts:10169-10172). */
|
|
81
44
|
const HOBBY_MAX_MS = 60 * 60_000;
|
|
82
45
|
/** E2B Pro's: 24 h. */
|
|
83
46
|
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
47
|
const MAX_PAGES = 100;
|
|
112
48
|
const PAGE = 100;
|
|
113
49
|
/** 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
50
|
const END_SLACK_MS = 2_000;
|
|
115
|
-
/** The longest a Node timer or AbortSignal.timeout holds. */
|
|
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";
|
|
134
51
|
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
52
|
/** envd's port in the sandbox (e2b@2.63.0 dist/index.mjs:1213, ConnectionConfig.envdPort). */
|
|
136
53
|
const ENVD_PORT = 49983;
|
|
137
|
-
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
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
|
-
/** The SDK names its errors (index.mjs:86-360). */
|
|
54
|
+
/** envd's user for a process: root, as the SDK's authenticationHeader writes it (index.mjs:1896-1900). */
|
|
55
|
+
const ROOT = `Basic ${Buffer.from("root:").toString("base64")}`;
|
|
56
|
+
/** envd sends a keepalive event this often on a process stream, as the SDK asks (index.mjs:923, 5141). */
|
|
57
|
+
const KEEPALIVE_HEADER = "Keepalive-Ping-Interval";
|
|
58
|
+
const KEEPALIVE_S = "50";
|
|
59
|
+
/** The Connect codes envd's process calls answer (connectrpc Code), as this provider's codes. */
|
|
60
|
+
const CONNECT_CODES = { 1: "aborted", 3: "invalid", 4: "timeout", 5: "not_found", 7: "denied", 8: "limit", 16: "denied" };
|
|
61
|
+
/** The SDK names its errors (index.mjs:86-360); Connect's carry a code. */
|
|
159
62
|
function codeOf(error) {
|
|
160
63
|
const name = error?.name;
|
|
161
|
-
if (name === "AbortError")
|
|
162
|
-
return "aborted";
|
|
163
64
|
if (name === "SandboxNotFoundError" || name === "NotFoundError" || name === "FileNotFoundError")
|
|
164
65
|
return "not_found";
|
|
165
66
|
if (name === "AuthenticationError")
|
|
@@ -168,1346 +69,282 @@ function codeOf(error) {
|
|
|
168
69
|
return "invalid";
|
|
169
70
|
if (name === "RateLimitError" || name === "NotEnoughSpaceError")
|
|
170
71
|
return "limit";
|
|
171
|
-
if (name === "
|
|
72
|
+
if (name === "SandboxUnreachableError")
|
|
172
73
|
return "timeout";
|
|
74
|
+
// envd's process stream, called through the SDK's Connect client (exec), throws Connect's own errors.
|
|
75
|
+
if (name === "ConnectError")
|
|
76
|
+
return CONNECT_CODES[error.code] ?? "vendor";
|
|
173
77
|
return "vendor";
|
|
174
78
|
}
|
|
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
79
|
/** E2B's end as create set it: its start plus the timeout create gave, by E2B's clock; undefined when unread. */
|
|
249
80
|
function createdEnd({ metadata, startedAt }) {
|
|
250
81
|
const timeout = Number(metadata[TIMEOUT_LABEL]);
|
|
251
|
-
const start = startedAt
|
|
252
|
-
return isWhole(timeout) && timeout > 0 &&
|
|
82
|
+
const start = dateOf(startedAt)?.getTime();
|
|
83
|
+
return isWhole(timeout) && timeout > 0 && start !== undefined ? start + timeout : undefined;
|
|
253
84
|
}
|
|
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. */
|
|
85
|
+
/** The earliest end a moved timer gives E2B: a second past create's end and its rounding, so deadlineOf reads it as moved. */
|
|
272
86
|
const clearOf = (created) => created + END_SLACK_MS + 1_000;
|
|
273
87
|
/**
|
|
274
|
-
* A sandbox
|
|
275
|
-
*
|
|
276
|
-
*
|
|
88
|
+
* A sandbox as the adapter reads a machine, from getInfo or the listing alike: E2B's state (a paused one is stopped), its
|
|
89
|
+
* start, its end. E2B keeps no metadata change, so once an extend moved its timer clear of create's end (setTimer), the
|
|
90
|
+
* deadline label reads that end, up to the most the computer may live: a restarted provider reads the extend all the same.
|
|
277
91
|
*/
|
|
278
|
-
function
|
|
279
|
-
const
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
if (network.allowPublicTraffic !== false) {
|
|
291
|
-
return { other: network.allowPublicTraffic === true ? "public traffic is let in" : "E2B did not report allowPublicTraffic false: public traffic may be let in" };
|
|
292
|
-
}
|
|
293
|
-
return blocked ? "none" : "open";
|
|
92
|
+
function machineOf(info) {
|
|
93
|
+
const labels = { ...(info.metadata ?? {}) };
|
|
94
|
+
const end = dateOf(info.endAt);
|
|
95
|
+
const created = createdEnd({ metadata: labels, startedAt: info.startedAt });
|
|
96
|
+
// An end within END_SLACK_MS of create's is create's own, rounded: a moved timer never leaves E2B's end there (clearOf).
|
|
97
|
+
if (end !== undefined && created !== undefined && end.getTime() > created + END_SLACK_MS && isoOf(labels[DEADLINE_LABEL]) !== undefined) {
|
|
98
|
+
const most = isoOf(labels[MAX_LABEL])?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
99
|
+
labels[DEADLINE_LABEL] = new Date(Math.min(end.getTime(), most)).toISOString();
|
|
100
|
+
}
|
|
101
|
+
const started = dateOf(info.startedAt);
|
|
102
|
+
const state = info.state === "running" ? "running" : info.state === "paused" ? "stopped" : "gone";
|
|
103
|
+
return { id: info.sandboxId, labels, state, ...(started ? { createdAt: started } : {}), ...(end ? { endsAt: end } : {}) };
|
|
294
104
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
* The network diagnostic: one sandbox made exactly as create makes one for network none (the same options, read-back,
|
|
311
|
-
* upload and sha256 check, daemon and display start, and the provider's own check from inside, recorded), then
|
|
312
|
-
* `computerd probe --diagnose` in it, and the sandbox killed and read back gone whatever happened, an abort included.
|
|
313
|
-
* Its E2B timeout is 10 minutes. It never relaxes create: create still refuses what the check refuses.
|
|
314
|
-
*/
|
|
315
|
-
export function diagnoseNetworkNone(provider, { image, signal }) {
|
|
316
|
-
return diagnoseWith(provider, image, signal);
|
|
317
|
-
}
|
|
318
|
-
/** Why ref is not an E2B computer's ref, or undefined. */
|
|
319
|
-
function refProblem(ref) {
|
|
320
|
-
if (typeof ref?.name !== "string" || !NAME.test(ref.name))
|
|
321
|
-
return `${String(ref?.name)} is not the name of an E2B computer (computer-<12 hex digits>)`;
|
|
322
|
-
if (typeof ref.id !== "string" || !SANDBOX_ID.test(ref.id))
|
|
323
|
-
return `${String(ref.id)} is not an E2B sandbox id`;
|
|
324
|
-
return undefined;
|
|
325
|
-
}
|
|
326
|
-
/**
|
|
327
|
-
* Computers that are E2B sandboxes. A spec's image is an E2B template (its name or id): "desktop" is E2B Desktop's, with
|
|
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 {
|
|
332
|
-
id = "e2b";
|
|
333
|
-
version = VERSION;
|
|
105
|
+
/** One chunk of the SDK's output into a stream, unless the stream has ended. */
|
|
106
|
+
const push = (stream, data) => void (stream.writableEnded || stream.write(data));
|
|
107
|
+
/** E2B's sandboxes as a MachineHost (../host.ts). */
|
|
108
|
+
class E2BHost {
|
|
109
|
+
descriptor = E2B;
|
|
110
|
+
facts = {
|
|
111
|
+
daemon: "child",
|
|
112
|
+
isolation: "microvm",
|
|
113
|
+
lifetime: "vendor",
|
|
114
|
+
maxLifetimeMs: PRO_MAX_MS,
|
|
115
|
+
arch: "amd64",
|
|
116
|
+
vendorAgentPorts: [ENVD_PORT],
|
|
117
|
+
// E2B Desktop's template has xfwm4, which its own desktop runs: the apps an agent opens are framed and focused.
|
|
118
|
+
windowManager: true,
|
|
119
|
+
};
|
|
334
120
|
#Sandbox;
|
|
335
121
|
#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
|
-
}
|
|
122
|
+
#requestMs;
|
|
123
|
+
/** Each sandbox create or connect gave, by id, for envd's commands and files: let go of at its delete. */
|
|
124
|
+
#sandboxes = new Map();
|
|
125
|
+
constructor(Sandbox, connection, requestMs) {
|
|
384
126
|
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];
|
|
393
|
-
}
|
|
394
|
-
/**
|
|
395
|
-
* daemon child: E2B's envd is the sandbox's first process, under systemd with Restart=always (e2b-dev/infra
|
|
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
|
-
};
|
|
127
|
+
this.#connection = connection;
|
|
128
|
+
this.#requestMs = requestMs;
|
|
416
129
|
}
|
|
417
|
-
|
|
418
|
-
|
|
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;
|
|
130
|
+
errorCode(error) {
|
|
131
|
+
return codeOf(error);
|
|
454
132
|
}
|
|
455
133
|
/** The connection options with a bound and, when given, the caller's signal. */
|
|
456
134
|
#api(ms, signal) {
|
|
457
135
|
return { ...this.#connection, requestTimeoutMs: ms, ...(signal ? { signal } : {}) };
|
|
458
136
|
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
if (!
|
|
462
|
-
return
|
|
463
|
-
const { sandbox, ref, made } = launched.value;
|
|
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`);
|
|
137
|
+
/** An E2B template is a name or id: letters, digits and ._:/- (no shell word, no path out). */
|
|
138
|
+
check({ image }) {
|
|
139
|
+
if (typeof image === "string" && image !== "" && !TEMPLATE.test(image)) {
|
|
140
|
+
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
141
|
}
|
|
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
|
-
};
|
|
142
|
+
return [];
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Sandbox.create with the lifetime as its timeout in the whole seconds E2B takes (index.mjs:502-504), recorded in a
|
|
146
|
+
* label for its end's arithmetic; no internet access unless the adapter asks open (an Archil computer's root), no
|
|
147
|
+
* public traffic (a project's default may let it in: E2B docs, network/restrict-public-access), and kill at the
|
|
148
|
+
* timeout, never a pause that keeps the computer (index.mjs:5674-5699).
|
|
149
|
+
*/
|
|
150
|
+
async create(req, ctx) {
|
|
151
|
+
const timeoutMs = Math.ceil((req.lifetimeMs ?? 0) / 1000) * 1000;
|
|
504
152
|
const options = {
|
|
505
|
-
...this.#api(
|
|
153
|
+
...this.#api(ctx.timeoutMs),
|
|
506
154
|
timeoutMs,
|
|
507
|
-
metadata,
|
|
155
|
+
metadata: { ...req.labels, [TIMEOUT_LABEL]: String(timeoutMs) },
|
|
508
156
|
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).
|
|
157
|
+
allowInternetAccess: req.network === "open",
|
|
513
158
|
network: { allowPublicTraffic: false },
|
|
514
|
-
// Explicit kill at the timeout, never a pause that keeps the computer (index.mjs:5674-5699).
|
|
515
159
|
lifecycle: { onTimeout: "kill" },
|
|
516
160
|
};
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
creating = Promise.resolve(this.#Sandbox.create(spec.image, options));
|
|
521
|
-
}
|
|
522
|
-
catch (error) {
|
|
523
|
-
return fail(codeOf(error), `Sandbox.create failed: ${words(error)}`);
|
|
524
|
-
}
|
|
525
|
-
const created = await race(creating, "Sandbox.create", this.#timeouts.createMs + CALL_SLACK_MS, signal);
|
|
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}`);
|
|
537
|
-
}
|
|
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
|
-
}
|
|
552
|
-
/**
|
|
553
|
-
* Every sandbox carrying a name create gave, killed and read back gone: for a create whose answer never came. The
|
|
554
|
-
* listing shows a new sandbox a moment after E2B makes it, so it is read for the name until one shows or listedMs
|
|
555
|
-
* passes. Best effort, in words.
|
|
556
|
-
*/
|
|
557
|
-
async #killNamed(name) {
|
|
558
|
-
const { listedMs, pollMs } = this.#timeouts;
|
|
559
|
-
const until = Date.now() + listedMs;
|
|
560
|
-
let found;
|
|
561
|
-
for (;;) {
|
|
562
|
-
const listed = await this.#listPages({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name });
|
|
563
|
-
if (!listed.ok)
|
|
564
|
-
return `; a sandbox named ${name} may be left (${listed.error.message}), which E2B ends at its timeout`;
|
|
565
|
-
found = listed.value;
|
|
566
|
-
if (found.length > 0 || Date.now() >= until)
|
|
567
|
-
break;
|
|
568
|
-
await pause(Math.min(LISTED_POLL_MS, pollMs));
|
|
569
|
-
}
|
|
570
|
-
if (found.length === 0)
|
|
571
|
-
return `; no sandbox named ${name} was listed within ${seconds(listedMs)}, and E2B ends any it made at its timeout`;
|
|
572
|
-
const said = [];
|
|
573
|
-
for (const sb of found) {
|
|
574
|
-
const killed = await this.#kill(sb.sandboxId);
|
|
575
|
-
const gone = killed.ok ? await this.#settle({ id: sb.sandboxId, name }) : killed;
|
|
576
|
-
said.push(gone.ok ? `${sb.sandboxId} was killed and read back gone` : `${sb.sandboxId} may be left (${gone.error.message}), which E2B ends at its timeout`);
|
|
577
|
-
}
|
|
578
|
-
return `; the sandbox named ${name} it made: ${said.join("; ")}`;
|
|
579
|
-
}
|
|
580
|
-
/** Sandbox.kill, never signalled: a kill that cleans up after an abort must outlive it. Not found is done. */
|
|
581
|
-
async #kill(id) {
|
|
582
|
-
const killed = await call(`Sandbox.kill of ${id}`, () => this.#Sandbox.kill(id, this.#api(this.#timeouts.requestMs)), this.#timeouts.requestMs + CALL_SLACK_MS);
|
|
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;
|
|
635
|
-
try {
|
|
636
|
-
const opened = await this.#openWhenListening(sandbox, ref.name, signal);
|
|
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;
|
|
664
|
-
}
|
|
665
|
-
finally {
|
|
666
|
-
await init.value.disconnect().catch(() => { });
|
|
667
|
-
}
|
|
161
|
+
const sandbox = await this.#Sandbox.create(req.image, options);
|
|
162
|
+
this.#sandboxes.set(sandbox.sandboxId, sandbox);
|
|
163
|
+
return { id: sandbox.sandboxId };
|
|
668
164
|
}
|
|
669
|
-
/**
|
|
670
|
-
|
|
671
|
-
|
|
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("; ")}`);
|
|
165
|
+
/** getInfo; a sandbox E2B does not have (SandboxNotFoundError, index.mjs:5431) is not_found, which the adapter reads as none. */
|
|
166
|
+
async get(id, ctx) {
|
|
167
|
+
return machineOf(await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal)));
|
|
707
168
|
}
|
|
708
169
|
/**
|
|
709
|
-
*
|
|
710
|
-
*
|
|
170
|
+
* Every sandbox E2B lists with these metadata pairs (running and paused, index.d.mts:10289), all pages within
|
|
171
|
+
* ctx.timeoutMs, each as getInfo reads it (the listing carries its end too).
|
|
711
172
|
*/
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
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 ?? "" };
|
|
775
|
-
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})`);
|
|
173
|
+
async list(labels, ctx) {
|
|
174
|
+
const until = Date.now() + ctx.timeoutMs;
|
|
175
|
+
const left = () => Math.max(1, Math.min(this.#requestMs, until - Date.now()));
|
|
176
|
+
const paginator = this.#Sandbox.list({ ...this.#connection, requestTimeoutMs: this.#requestMs, query: { metadata: labels }, limit: PAGE });
|
|
177
|
+
const found = new Map();
|
|
178
|
+
for (let page = 0; paginator.hasNext; page++) {
|
|
179
|
+
if (page >= MAX_PAGES)
|
|
180
|
+
throw new Error(`Sandbox.list ran past ${MAX_PAGES} pages`);
|
|
181
|
+
const items = await paginator.nextItems({ requestTimeoutMs: left(), ...(ctx.signal ? { signal: ctx.signal } : {}) });
|
|
182
|
+
if (!Array.isArray(items))
|
|
183
|
+
throw new Error("Sandbox.list: a page that is not a list of sandboxes");
|
|
184
|
+
for (const sb of items)
|
|
185
|
+
if (typeof sb?.sandboxId === "string")
|
|
186
|
+
found.set(sb.sandboxId, sb);
|
|
789
187
|
}
|
|
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);
|
|
188
|
+
return [...found.values()].map(machineOf);
|
|
823
189
|
}
|
|
824
|
-
/**
|
|
825
|
-
async
|
|
826
|
-
|
|
827
|
-
|
|
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;
|
|
190
|
+
/** Sandbox.kill, never signalled: a kill that cleans up after an abort must outlive it. */
|
|
191
|
+
async delete(id, ctx) {
|
|
192
|
+
this.#sandboxes.delete(id);
|
|
193
|
+
await this.#Sandbox.kill(id, this.#api(ctx.timeoutMs));
|
|
832
194
|
}
|
|
833
195
|
/**
|
|
834
|
-
* A connected Sandbox for envd's commands and files
|
|
835
|
-
*
|
|
836
|
-
*
|
|
196
|
+
* A connected Sandbox for envd's commands and files: the one create gave, or Sandbox.connect, whose timeout is a
|
|
197
|
+
* little under what is left: E2B moves a running sandbox's timer only to a longer one (index.d.mts:10250-10255), so
|
|
198
|
+
* connecting never moves the end. The adapter connects only to a sandbox it read running: connect resumes a paused one.
|
|
837
199
|
*/
|
|
838
|
-
async #
|
|
839
|
-
const
|
|
200
|
+
async #sandbox(id, ctx) {
|
|
201
|
+
const known = this.#sandboxes.get(id);
|
|
202
|
+
if (known !== undefined)
|
|
203
|
+
return known;
|
|
204
|
+
const info = await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal));
|
|
840
205
|
const left = info.endAt instanceof Date ? info.endAt.getTime() - Date.now() : 0;
|
|
841
206
|
const timeoutMs = Math.max(1_000, Math.floor(left / 1000) * 1000 - 2_000);
|
|
842
|
-
|
|
207
|
+
const sandbox = await this.#Sandbox.connect(id, { ...this.#api(ctx.timeoutMs, ctx.signal), timeoutMs });
|
|
208
|
+
this.#sandboxes.set(id, sandbox);
|
|
209
|
+
return sandbox;
|
|
843
210
|
}
|
|
844
|
-
/**
|
|
845
|
-
async
|
|
846
|
-
const
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
if (opened.ok || !opened.notListening || signal?.aborted || Date.now() + LISTEN_RETRY_MS >= until)
|
|
850
|
-
return opened;
|
|
851
|
-
await pause(LISTEN_RETRY_MS, signal);
|
|
852
|
-
}
|
|
211
|
+
/** files.write as root (index.mjs:2332-2435). */
|
|
212
|
+
async upload(id, path, bytes, ctx) {
|
|
213
|
+
const sandbox = await this.#sandbox(id, ctx);
|
|
214
|
+
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
215
|
+
await sandbox.files.write(path, buffer, { user: "root", requestTimeoutMs: ctx.timeoutMs, ...(ctx.signal ? { signal: ctx.signal } : {}) });
|
|
853
216
|
}
|
|
854
217
|
/**
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
-
*
|
|
858
|
-
*
|
|
218
|
+
* A process as root through envd's Process.Start stream, as commands.run starts one (index.mjs:5123-5146): `bash -l -c`
|
|
219
|
+
* and the argv quoted, root by the Basic header (authenticationHeader, index.mjs:1896-1900), and envd's keepalive
|
|
220
|
+
* every 50 s. Its stdout and stderr are the bytes each data event carries, passed on as they come: commands.run would
|
|
221
|
+
* decode them as UTF-8 text first. No deadline on the stream (timeoutMs 0, which the Connect transport reads as none,
|
|
222
|
+
* connect-web connect-transport.js:145-150), so envd never ends it (start.go:39-44); the start alone is bounded by
|
|
223
|
+
* ctx. Writes go one sendStdin at a time, in order; end is closeStdin; kill SIGKILLs it and lets go of its stream.
|
|
859
224
|
*/
|
|
860
|
-
async
|
|
861
|
-
const
|
|
862
|
-
const
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
const
|
|
866
|
-
|
|
867
|
-
let
|
|
225
|
+
async exec(id, argv, ctx) {
|
|
226
|
+
const sandbox = await this.#sandbox(id, ctx);
|
|
227
|
+
const out = new PassThrough();
|
|
228
|
+
const err = new PassThrough();
|
|
229
|
+
const requestTimeoutMs = this.#requestMs;
|
|
230
|
+
const stream = new AbortController();
|
|
231
|
+
const events = sandbox.commands.rpc.start({ process: { cmd: "/bin/bash", args: ["-l", "-c", shellLine(argv)], envs: {} }, stdin: true }, { headers: { Authorization: ROOT, [KEEPALIVE_HEADER]: KEEPALIVE_S }, signal: stream.signal, timeoutMs: 0 })[Symbol.asyncIterator]();
|
|
232
|
+
// The start, within ctx: a stream that gives no start event in time, or the caller's abort, is let go of.
|
|
233
|
+
const startAbort = () => stream.abort(ctx.signal?.reason);
|
|
234
|
+
ctx.signal?.addEventListener("abort", startAbort, { once: true });
|
|
235
|
+
const startTimer = setTimeout(() => stream.abort(), ctx.timeoutMs);
|
|
236
|
+
let pid;
|
|
868
237
|
try {
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
requestTimeoutMs: requestMs,
|
|
875
|
-
retainOutput: false,
|
|
876
|
-
onStdout: (data) => {
|
|
877
|
-
if (!readable.destroyed)
|
|
878
|
-
readable.write(Buffer.from(data, "utf8"));
|
|
879
|
-
},
|
|
880
|
-
onStderr: (data) => {
|
|
881
|
-
stderr = (stderr + data).slice(-4096);
|
|
882
|
-
},
|
|
883
|
-
}));
|
|
238
|
+
const first = await events.next();
|
|
239
|
+
const event = first.done ? undefined : first.value.event?.event;
|
|
240
|
+
if (event?.case !== "start")
|
|
241
|
+
throw new Error(`envd's process stream began with ${event?.case ?? "nothing"}, not its start`);
|
|
242
|
+
pid = event.value.pid;
|
|
884
243
|
}
|
|
885
244
|
catch (error) {
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
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
|
-
},
|
|
904
|
-
});
|
|
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.
|
|
245
|
+
const why = stream.signal.aborted ? (ctx.signal?.aborted ? "AbortError" : "TimeoutError") : undefined;
|
|
246
|
+
stream.abort();
|
|
247
|
+
if (why === undefined)
|
|
248
|
+
throw error;
|
|
249
|
+
throw Object.assign(new Error(why === "AbortError" ? "the exec was aborted before envd started it" : `envd did not start the process within ${ctx.timeoutMs / 1000} s`), { name: why });
|
|
1017
250
|
}
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
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);
|
|
251
|
+
finally {
|
|
252
|
+
clearTimeout(startTimer);
|
|
253
|
+
ctx.signal?.removeEventListener("abort", startAbort);
|
|
1061
254
|
}
|
|
1062
|
-
const
|
|
1063
|
-
|
|
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;
|
|
255
|
+
const exited = (async () => {
|
|
256
|
+
let code = -1;
|
|
1110
257
|
try {
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
258
|
+
for (;;) {
|
|
259
|
+
const next = await events.next();
|
|
260
|
+
if (next.done)
|
|
261
|
+
break;
|
|
262
|
+
const event = next.value.event?.event;
|
|
263
|
+
if (event?.case === "data") {
|
|
264
|
+
const { output } = event.value;
|
|
265
|
+
if (output.case === "stdout")
|
|
266
|
+
push(out, output.value);
|
|
267
|
+
else if (output.case === "stderr")
|
|
268
|
+
push(err, output.value);
|
|
269
|
+
}
|
|
270
|
+
else if (event?.case === "end") {
|
|
271
|
+
code = event.value.exitCode;
|
|
272
|
+
break;
|
|
273
|
+
}
|
|
1119
274
|
}
|
|
1120
275
|
}
|
|
1121
|
-
|
|
1122
|
-
|
|
276
|
+
catch {
|
|
277
|
+
// A stream that broke, or one kill let go of: no exit code was read.
|
|
1123
278
|
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
...(mount === undefined ? {} : { mount }),
|
|
279
|
+
out.end();
|
|
280
|
+
err.end();
|
|
281
|
+
stream.abort();
|
|
282
|
+
return code;
|
|
283
|
+
})();
|
|
284
|
+
return {
|
|
285
|
+
stdout: out,
|
|
286
|
+
stderr: err,
|
|
287
|
+
write: (bytes) => sandbox.commands.sendStdin(pid, bytes, { requestTimeoutMs }),
|
|
288
|
+
end: () => sandbox.commands.closeStdin(pid, { requestTimeoutMs }),
|
|
289
|
+
wait: () => exited,
|
|
290
|
+
kill: async () => {
|
|
291
|
+
await sandbox.commands.kill(pid, { requestTimeoutMs }).catch(() => false);
|
|
292
|
+
stream.abort();
|
|
293
|
+
out.end();
|
|
294
|
+
err.end();
|
|
1141
295
|
},
|
|
1142
|
-
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1145
|
-
/**
|
|
1146
|
-
* Every sandbox E2B lists with these metadata pairs (running and paused, index.d.mts:10289), all pages, within listMs,
|
|
1147
|
-
* or by until when the caller's own bound is given; then a page's timeout whose bound was what was left of it is
|
|
1148
|
-
* marked listBound.
|
|
1149
|
-
*/
|
|
1150
|
-
async #listPages(metadata, signal, given) {
|
|
1151
|
-
const { requestMs } = this.#timeouts;
|
|
1152
|
-
const until = given ?? Date.now() + this.#timeouts.listMs;
|
|
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` };
|
|
296
|
+
};
|
|
1316
297
|
}
|
|
1317
298
|
/**
|
|
1318
|
-
* Moves E2B's timer
|
|
1319
|
-
*
|
|
1320
|
-
*
|
|
1321
|
-
*
|
|
1322
|
-
* before it left, so a slow, shorter extend never pulls E2B's timer under a longer one's.
|
|
299
|
+
* Moves E2B's timer (setTimeout, index.mjs:5529-5541) in the whole seconds E2B takes: up to clear create's end, so
|
|
300
|
+
* the end reads as moved (deadlineOf), and down at the most the computer may live (its max-deadline label), so E2B's
|
|
301
|
+
* timer never passes it by this machine's clock. A timer that would end before the deadline held now, or within
|
|
302
|
+
* create's rounding, is refused as limit, and nothing moves.
|
|
1323
303
|
*/
|
|
1324
|
-
async extend(
|
|
1325
|
-
const
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
if (
|
|
1329
|
-
|
|
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;
|
|
304
|
+
async extend(id, end, ctx) {
|
|
305
|
+
const info = await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal));
|
|
306
|
+
const machine = machineOf(info);
|
|
307
|
+
const most = new Date(machine.labels[MAX_LABEL] ?? Number.NaN);
|
|
308
|
+
if (Number.isNaN(most.getTime()))
|
|
309
|
+
throw new HostError("refused", `${id}'s label ${MAX_LABEL} reads ${show(machine.labels[MAX_LABEL])}, so the most it may live is unknown; nothing moved`);
|
|
1354
310
|
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.
|
|
311
|
+
const target = end.getTime();
|
|
1363
312
|
const created = createdEnd(info);
|
|
1364
313
|
const want = created === undefined ? target : Math.max(target, clearOf(created));
|
|
1365
314
|
const timerMs = Math.min(Math.ceil((want - now) / 1000) * 1000, Math.floor((most.getTime() - now) / 1000) * 1000);
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
const
|
|
1369
|
-
const
|
|
315
|
+
const vendorEnd = machine.endsAt?.getTime() ?? Number.NaN;
|
|
316
|
+
const current = (deadlineOf(machine) ?? machine.endsAt)?.getTime() ?? now;
|
|
317
|
+
const held = Number.isNaN(vendorEnd) ? current : Math.max(current, vendorEnd);
|
|
318
|
+
const name = info.metadata?.["agentrun.computer.name"] ?? id;
|
|
1370
319
|
if (now + timerMs < held) {
|
|
1371
|
-
|
|
320
|
+
throw new HostError("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
321
|
}
|
|
1373
322
|
if (created !== undefined && now + timerMs < clearOf(created)) {
|
|
1374
|
-
|
|
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();
|
|
1400
|
-
}
|
|
1401
|
-
return ok({ deadline: took });
|
|
1402
|
-
}
|
|
1403
|
-
/**
|
|
1404
|
-
* delete reads the sandbox back to check it is this provider's, then kills it, both never signalled, so a release
|
|
1405
|
-
* after an abort, or one aborted during the read, still sends the kill; it is idempotent: one E2B no longer has is ok.
|
|
1406
|
-
* E2B answers a kill before the sandbox is gone, so release then waits (#settle) until E2B reads it gone and no longer
|
|
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.
|
|
1411
|
-
*/
|
|
1412
|
-
async release(ref, how, { signal } = {}) {
|
|
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);
|
|
1441
|
-
try {
|
|
1442
|
-
return await archilRelease({ root: this.#root(sandbox.value, name), client: opened.ok ? opened.value.client : undefined, timeoutMs: this.#timeouts.mountMs, ...(signal ? { signal } : {}) });
|
|
1443
|
-
}
|
|
1444
|
-
finally {
|
|
1445
|
-
if (opened.ok)
|
|
1446
|
-
await opened.value.close();
|
|
323
|
+
throw new HostError("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`);
|
|
1447
324
|
}
|
|
325
|
+
await this.#Sandbox.setTimeout(id, timerMs, this.#api(ctx.timeoutMs, ctx.signal));
|
|
1448
326
|
}
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
let
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
if (!listed.ok) {
|
|
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");
|
|
1511
|
-
}
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Computers that are E2B sandboxes, on the shared adapter. A spec's image is an E2B template (its name or id):
|
|
330
|
+
* "desktop" is E2B Desktop's, with Xvfb, x11vnc and noVNC (e2b-dev/desktop template.py:21-65).
|
|
331
|
+
*/
|
|
332
|
+
export class E2BProvider extends HostedProvider {
|
|
333
|
+
constructor(options) {
|
|
334
|
+
// A caller who still names the option is told it is gone, whatever its value: it once let public traffic in.
|
|
335
|
+
if (typeof options === "object" && options !== null && Object.hasOwn(options, "publicStream"))
|
|
336
|
+
throw new Error(PUBLIC);
|
|
337
|
+
const { apiKey, Sandbox, domain = DEFAULT_DOMAIN, kind = "desktop", maxLifetimeMs = HOBBY_MAX_MS, ...rest } = options;
|
|
338
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
339
|
+
throw new Error("options.apiKey, the E2B API key, is required: the provider reads no environment, so the caller passes it");
|
|
340
|
+
const lacks = ["create", "connect", "getInfo", "setTimeout", "kill", "list"].filter((name) => typeof Sandbox?.[name] !== "function");
|
|
341
|
+
if (lacks.length > 0)
|
|
342
|
+
throw new Error(`options.Sandbox must be the e2b SDK's Sandbox class; it lacks ${lacks.join(", ")}`);
|
|
343
|
+
const ambient = ambientProblem();
|
|
344
|
+
if (ambient)
|
|
345
|
+
throw new Error(ambient);
|
|
346
|
+
if (typeof domain !== "string" || !DOMAIN.test(domain))
|
|
347
|
+
throw new Error(`the E2B domain must be a host name such as ${DEFAULT_DOMAIN}, not ${JSON.stringify(domain)}`);
|
|
348
|
+
super(new E2BHost(Sandbox, connectionOptions({ apiKey, domain }), timeoutsOf(rest.timeouts).requestMs), { ...rest, kind, maxLifetimeMs });
|
|
1512
349
|
}
|
|
1513
350
|
}
|