@parcha/agentrun-computer 0.0.0-placeholder → 0.1.0-beta.32

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