@parcha/agentrun-computer 0.1.0-beta.37 → 0.1.0-beta.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +259 -203
  2. package/box/Dockerfile +18 -1
  3. package/box/README.md +13 -0
  4. package/box/build-agent37.mjs +8 -27
  5. package/box/build-daytona.py +2 -2
  6. package/box/build-e2b.mjs +41 -18
  7. package/box/recipe.mjs +43 -0
  8. package/dist/agent37-ssh.d.ts +89 -0
  9. package/dist/agent37-ssh.js +445 -0
  10. package/dist/agent37.d.ts +2 -63
  11. package/dist/agent37.js +104 -461
  12. package/dist/browserbase.d.ts +0 -6
  13. package/dist/browserbase.js +1 -5
  14. package/dist/client.d.ts +12 -3
  15. package/dist/client.js +39 -4
  16. package/dist/computerd-linux-amd64 +0 -0
  17. package/dist/computerd-linux-arm64 +0 -0
  18. package/dist/computerd.json +4 -0
  19. package/dist/conformance/cases/apps.d.ts +6 -0
  20. package/dist/conformance/cases/apps.js +18 -5
  21. package/dist/conformance/cases/isolation.d.ts +7 -5
  22. package/dist/conformance/cases/isolation.js +44 -14
  23. package/dist/conformance/cases/mount.js +1 -1
  24. package/dist/conformance/cli.js +66 -6
  25. package/dist/conformance/daytona.d.ts +9 -20
  26. package/dist/conformance/daytona.js +12 -21
  27. package/dist/conformance/exec-stream.d.ts +45 -0
  28. package/dist/conformance/exec-stream.js +486 -0
  29. package/dist/conformance/sweep.js +8 -8
  30. package/dist/conformance/types.d.ts +2 -2
  31. package/dist/create-requests.d.ts +1 -1
  32. package/dist/daytona.d.ts +20 -131
  33. package/dist/daytona.js +405 -1450
  34. package/dist/descriptor.d.ts +6 -1
  35. package/dist/descriptor.js +7 -0
  36. package/dist/descriptors/agent37.d.ts +1 -1
  37. package/dist/descriptors/agent37.js +1 -1
  38. package/dist/descriptors/daytona.d.ts +6 -5
  39. package/dist/descriptors/daytona.js +9 -5
  40. package/dist/descriptors/index.d.ts +4 -5
  41. package/dist/descriptors/shared.d.ts +1 -1
  42. package/dist/descriptors/shared.js +2 -2
  43. package/dist/desktop.d.ts +18 -4
  44. package/dist/desktop.js +89 -9
  45. package/dist/docker.d.ts +0 -6
  46. package/dist/docker.js +1 -5
  47. package/dist/drift.js +4 -4
  48. package/dist/e2b.d.ts +10 -128
  49. package/dist/e2b.js +130 -233
  50. package/dist/host.d.ts +106 -87
  51. package/dist/host.js +8 -1
  52. package/dist/hosted/process.d.ts +22 -8
  53. package/dist/hosted/process.js +75 -44
  54. package/dist/hosted/provider.d.ts +35 -21
  55. package/dist/hosted/provider.js +312 -261
  56. package/dist/hosted/rest.d.ts +66 -0
  57. package/dist/hosted/rest.js +121 -0
  58. package/dist/hosted/scripts.d.ts +8 -2
  59. package/dist/hosted/scripts.js +27 -2
  60. package/dist/hosted/values.d.ts +5 -0
  61. package/dist/hosted/values.js +8 -0
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.js +1 -1
  64. package/dist/kernel.d.ts +0 -6
  65. package/dist/kernel.js +1 -5
  66. package/dist/kinds.d.ts +3 -1
  67. package/dist/local-chrome.d.ts +0 -6
  68. package/dist/local-chrome.js +1 -5
  69. package/dist/modal.d.ts +7 -84
  70. package/dist/modal.js +50 -174
  71. package/dist/mount-archil.d.ts +8 -4
  72. package/dist/mount-archil.js +22 -11
  73. package/dist/mount.d.ts +10 -4
  74. package/dist/mount.js +8 -4
  75. package/dist/orgo.d.ts +0 -9
  76. package/dist/orgo.js +2 -9
  77. package/dist/phone-harness.d.ts +0 -6
  78. package/dist/phone-harness.js +0 -4
  79. package/dist/protocol.d.ts +4 -1
  80. package/dist/protocol.js +1 -0
  81. package/dist/provider.d.ts +2 -2
  82. package/dist/providers.d.ts +11 -12
  83. package/dist/screen-watch.js +34 -6
  84. package/dist/surface/api.d.ts +14 -2
  85. package/dist/surface/core.d.ts +16 -3
  86. package/dist/surface/core.js +95 -13
  87. package/dist/surface/outline.d.ts +2 -0
  88. package/dist/surface/outline.js +2 -1
  89. package/dist/surface/script.js +2 -0
  90. package/dist/ui-engine.js +19 -3
  91. package/package.json +2 -3
  92. package/dist/conformance/daytona-sweep.d.ts +0 -18
  93. package/dist/conformance/daytona-sweep.js +0 -126
package/dist/e2b.js CHANGED
@@ -1,21 +1,13 @@
1
- // The E2B host: E2B Desktop sandboxes (kind desktop) or E2B's plain template (kind linux), every call through the
2
- // host's own E2B JS SDK (the `e2b` package), of which this package names only the slice it uses (E2BSandboxClass) and
3
- // imports nothing at load. E2B's envd is the sandbox's first process (under systemd), so computerd is a child: its
4
- // upload goes through envd's file API and every command (install, init's start, the stdio bridge) is a background
5
- // command as root. The rest of the computer is the shared machine-host adapter's (./hosted/provider.ts). Every SDK fact
6
- // used here is cited in the README's E2B section, from e2b@2.63.0 (dist/index.mjs) and e2b-dev/infra@ff3922213 (envd).
7
1
  import { E2B, E2B_BASE_TEMPLATE, E2B_DESKTOP_TEMPLATE } from "./descriptors/e2b.js";
8
- import { deadlineOf, HostedProvider, IMAGE_LABEL, ours } from "./hosted/provider.js";
9
- import { words } from "./hosted/process.js";
2
+ import { DEADLINE_LABEL, show } from "./drift.js";
3
+ import { HostError } from "./host.js";
4
+ import { deadlineOf, HostedProvider, isoOf, MAX_LABEL, timeoutsOf } from "./hosted/provider.js";
10
5
  import { shellLine } from "./hosted/scripts.js";
11
- import { failFor, ok } from "./result.js";
12
- import { countTested } from "./test-connection.js";
13
- /** This module's failures: one with code vendor names E2B. */
14
- const fail = failFor("e2b");
6
+ import { dateOf, DOMAIN, isWhole } from "./hosted/values.js";
7
+ import { PassThrough } from "node:stream";
15
8
  /** Not a literal, so no type checker or bundler resolves the SDK from this package. */
16
9
  const E2B_PACKAGE = "e2b";
17
10
  const DEFAULT_DOMAIN = "e2b.app";
18
- const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
19
11
  /** The connection options every SDK call is given. Exported for the test that hands them to the real SDK. */
20
12
  export function connectionOptions({ apiKey, domain }) {
21
13
  return { apiKey, domain, apiUrl: `https://api.${domain}`, debug: false };
@@ -39,14 +31,9 @@ function ambientProblem() {
39
31
  * never echoing the key.
40
32
  */
41
33
  export async function create(options) {
42
- const { apiKey, Sandbox: given, ...rest } = options ?? {};
43
- if (typeof apiKey !== "string" || apiKey === "")
44
- throw new Error("options.apiKey, the E2B API key, is required: the provider reads no environment, so the caller passes it");
45
- const ambient = ambientProblem();
46
- if (ambient)
47
- throw new Error(ambient);
34
+ const { Sandbox: given, ...rest } = options ?? {};
48
35
  const Sandbox = given ?? (await import(E2B_PACKAGE)).Sandbox;
49
- return new E2BProvider({ ...rest, apiKey, Sandbox });
36
+ return new E2BProvider({ ...rest, Sandbox });
50
37
  }
51
38
  /** The conformance CLI's module for E2B: its live switch, the run's 30-minute cap, its template and the drifted twin. */
52
39
  export const conformance = () => import("./conformance/e2b.js");
@@ -61,21 +48,19 @@ const MAX_PAGES = 100;
61
48
  const PAGE = 100;
62
49
  /** E2B's end, read back, is its start plus the timeout create gave it, to the second it rounds to (index.mjs:502-504). */
63
50
  const END_SLACK_MS = 2_000;
64
- const DEFAULT_REQUEST_MS = 30_000;
65
51
  const PUBLIC = "publicStream is no longer an option: an E2B computer never takes public traffic, which would open every port in it to anyone with its address, and its screen is streamed through agentrun, never a vendor URL";
66
52
  /** envd's port in the sandbox (e2b@2.63.0 dist/index.mjs:1213, ConnectionConfig.envdPort). */
67
53
  const ENVD_PORT = 49983;
68
- /** The mount kinds an E2B computer takes, as capabilities().mount declares them: the run's folder on an Archil disk. */
69
- export const MOUNT = E2B.mounts;
70
- /** The machine kind and groups of each configuration: kind linux (the plain template), and kind desktop (the default). */
71
- export const CAPABILITIES = E2B.capabilities;
72
- const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
73
- const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
74
- /** The SDK names its errors (index.mjs:86-360). */
54
+ /** envd's user for a process: root, as the SDK's authenticationHeader writes it (index.mjs:1896-1900). */
55
+ const ROOT = `Basic ${Buffer.from("root:").toString("base64")}`;
56
+ /** envd sends a keepalive event this often on a process stream, as the SDK asks (index.mjs:923, 5141). */
57
+ const KEEPALIVE_HEADER = "Keepalive-Ping-Interval";
58
+ const KEEPALIVE_S = "50";
59
+ /** The Connect codes envd's process calls answer (connectrpc Code), as this provider's codes. */
60
+ const CONNECT_CODES = { 1: "aborted", 3: "invalid", 4: "timeout", 5: "not_found", 7: "denied", 8: "limit", 16: "denied" };
61
+ /** The SDK names its errors (index.mjs:86-360); Connect's carry a code. */
75
62
  function codeOf(error) {
76
63
  const name = error?.name;
77
- if (name === "AbortError")
78
- return "aborted";
79
64
  if (name === "SandboxNotFoundError" || name === "NotFoundError" || name === "FileNotFoundError")
80
65
  return "not_found";
81
66
  if (name === "AuthenticationError")
@@ -84,123 +69,44 @@ function codeOf(error) {
84
69
  return "invalid";
85
70
  if (name === "RateLimitError" || name === "NotEnoughSpaceError")
86
71
  return "limit";
87
- if (name === "TimeoutError" || name === "SandboxUnreachableError")
72
+ if (name === "SandboxUnreachableError")
88
73
  return "timeout";
74
+ // envd's process stream, called through the SDK's Connect client (exec), throws Connect's own errors.
75
+ if (name === "ConnectError")
76
+ return CONNECT_CODES[error.code] ?? "vendor";
89
77
  return "vendor";
90
78
  }
91
79
  /** E2B's end as create set it: its start plus the timeout create gave, by E2B's clock; undefined when unread. */
92
80
  function createdEnd({ metadata, startedAt }) {
93
81
  const timeout = Number(metadata[TIMEOUT_LABEL]);
94
- const start = startedAt instanceof Date ? startedAt.getTime() : Number.NaN;
95
- return isWhole(timeout) && timeout > 0 && !Number.isNaN(start) ? start + timeout : undefined;
82
+ const start = dateOf(startedAt)?.getTime();
83
+ return isWhole(timeout) && timeout > 0 && start !== undefined ? start + timeout : undefined;
96
84
  }
97
85
  /** The earliest end a moved timer gives E2B: a second past create's end and its rounding, so deadlineOf reads it as moved. */
98
86
  const clearOf = (created) => created + END_SLACK_MS + 1_000;
99
87
  /**
100
- * A sandbox's network as E2B reports it. None is no internet access (E2B: the same as denyOut 0.0.0.0/0,
101
- * index.d.mts:10179) with no allow list and no public traffic in; open is internet access with none of those either.
102
- * Anything else is another network in words, never one it might widen to.
88
+ * A sandbox as the adapter reads a machine, from getInfo or the listing alike: E2B's state (a paused one is stopped), its
89
+ * start, its end. E2B keeps no metadata change, so once an extend moved its timer clear of create's end (setTimer), the
90
+ * deadline label reads that end, up to the most the computer may live: a restarted provider reads the extend all the same.
103
91
  */
104
- function networkOf(info) {
105
- const network = info.network ?? {};
106
- if (network.egressProxy !== undefined && network.egressProxy !== null)
107
- return { other: "an egress proxy is set on it" };
108
- if (Array.isArray(network.allowOut) && network.allowOut.length > 0)
109
- return { other: `an allowOut list (${network.allowOut.length} entries), which this provider never makes` };
110
- if (network.rules !== undefined && network.rules !== null && Object.keys(network.rules).length > 0)
111
- return { other: "transform rules, which this provider never makes" };
112
- const denied = Array.isArray(network.denyOut) ? network.denyOut : [];
113
- const blocked = info.allowInternetAccess === false || denied.includes("0.0.0.0/0");
114
- if (!blocked && denied.length > 0)
115
- return { other: `a denyOut list short of all traffic (${denied.join(", ")})` };
116
- if (network.allowPublicTraffic !== false) {
117
- return { other: network.allowPublicTraffic === true ? "public traffic is let in" : "E2B did not report allowPublicTraffic false: public traffic may be let in" };
118
- }
119
- return blocked ? "none" : "open";
120
- }
121
- /** A sandbox as the adapter reads a machine: E2B's states, its network, its template, its timer, and its create's drift. */
122
92
  function machineOf(info) {
123
- const metadata = { ...(info.metadata ?? {}) };
124
- const end = info.endAt instanceof Date ? info.endAt.getTime() : Number.NaN;
125
- const created = createdEnd({ metadata, startedAt: info.startedAt });
126
- const drift = [];
127
- const mismatch = (field, declared, actual) => drift.push(`${field}: declared ${show(declared)}, read back ${show(actual)}`);
128
- // E2B reports the template's id, and its alias when it has one (index.mjs:5435-5437): a template asked for by an
129
- // alias E2B does not report back cannot be held to it, and its label records what was asked.
130
- const asked = metadata[IMAGE_LABEL];
131
- const alias = info.name;
132
- if (asked !== undefined && info.templateId !== asked && alias !== undefined && alias !== asked && !alias.startsWith(`${asked}:`)) {
133
- drift.push(`template: declared ${show(asked)}, read back ${show(info.templateId)} (${alias})`);
93
+ const labels = { ...(info.metadata ?? {}) };
94
+ const end = dateOf(info.endAt);
95
+ const created = createdEnd({ metadata: labels, startedAt: info.startedAt });
96
+ // An end within END_SLACK_MS of create's is create's own, rounded: a moved timer never leaves E2B's end there (clearOf).
97
+ if (end !== undefined && created !== undefined && end.getTime() > created + END_SLACK_MS && isoOf(labels[DEADLINE_LABEL]) !== undefined) {
98
+ const most = isoOf(labels[MAX_LABEL])?.getTime() ?? Number.POSITIVE_INFINITY;
99
+ labels[DEADLINE_LABEL] = new Date(Math.min(end.getTime(), most)).toISOString();
134
100
  }
135
- if (info.lifecycle?.onTimeout !== undefined && info.lifecycle.onTimeout !== "kill")
136
- mismatch("lifecycle onTimeout", "kill", info.lifecycle.onTimeout);
137
- if (info.lifecycle?.autoResume === true)
138
- mismatch("lifecycle autoResume", false, true);
139
- // An end later than create's is a moved timer (timerMoved: an extend's, or one create refuses on a machine it just
140
- // made); only an end it cannot read, or one earlier than create gave, is drift, at create and at attach alike.
141
- if (Number.isNaN(end) || created === undefined)
142
- drift.push(`endAt: E2B reported ${show(info.endAt)} from a start of ${show(info.startedAt)}, so it might not end the computer`);
143
- else if (end < created - END_SLACK_MS)
144
- drift.push(`endAt: ${info.endAt.toISOString()} is earlier than E2B's start plus the ${metadata[TIMEOUT_LABEL]} ms timeout create gave`);
145
- return {
146
- id: info.sandboxId,
147
- labels: metadata,
148
- state: info.state === "running" ? "running" : info.state === "paused" ? "stopped" : "going",
149
- network: networkOf(info),
150
- image: { resolved: info.templateId },
151
- ...(info.startedAt instanceof Date && !Number.isNaN(info.startedAt.getTime()) ? { createdAt: new Date(info.startedAt) } : {}),
152
- ...(Number.isNaN(end) ? {} : { endsAt: new Date(end) }),
153
- // An end within END_SLACK_MS of create's is create's own, rounded: a moved timer never leaves E2B's end there (clearOf).
154
- timerMoved: !Number.isNaN(end) && created !== undefined && end > created + END_SLACK_MS,
155
- ...(drift.length > 0 ? { drift } : {}),
156
- };
157
- }
158
- /** A listed sandbox whose read-back E2B no longer has: still listed, so it is going, not gone. */
159
- const listedOnly = (sb) => ({
160
- id: sb.sandboxId,
161
- labels: { ...(sb.metadata ?? {}) },
162
- state: "going",
163
- ...(sb.startedAt instanceof Date && !Number.isNaN(sb.startedAt.getTime()) ? { createdAt: new Date(sb.startedAt) } : {}),
164
- });
165
- /** A stream fed by the SDK's callbacks, read as an async iterable until it ends. */
166
- function feed() {
167
- const queue = [];
168
- let ended = false;
169
- let wake;
170
- const nudge = () => {
171
- const waiting = wake;
172
- wake = undefined;
173
- waiting?.();
174
- };
175
- return {
176
- push(bytes) {
177
- if (ended)
178
- return;
179
- queue.push(bytes);
180
- nudge();
181
- },
182
- end() {
183
- ended = true;
184
- nudge();
185
- },
186
- iterable: {
187
- async *[Symbol.asyncIterator]() {
188
- for (;;) {
189
- const next = queue.shift();
190
- if (next !== undefined)
191
- yield next;
192
- else if (ended)
193
- return;
194
- else
195
- await new Promise((done) => (wake = done));
196
- }
197
- },
198
- },
199
- };
101
+ const started = dateOf(info.startedAt);
102
+ const state = info.state === "running" ? "running" : info.state === "paused" ? "stopped" : "gone";
103
+ return { id: info.sandboxId, labels, state, ...(started ? { createdAt: started } : {}), ...(end ? { endsAt: end } : {}) };
200
104
  }
105
+ /** One chunk of the SDK's output into a stream, unless the stream has ended. */
106
+ const push = (stream, data) => void (stream.writableEnded || stream.write(data));
201
107
  /** E2B's sandboxes as a MachineHost (../host.ts). */
202
108
  class E2BHost {
203
- id = "e2b";
109
+ descriptor = E2B;
204
110
  facts = {
205
111
  daemon: "child",
206
112
  isolation: "microvm",
@@ -208,10 +114,8 @@ class E2BHost {
208
114
  maxLifetimeMs: PRO_MAX_MS,
209
115
  arch: "amd64",
210
116
  vendorAgentPorts: [ENVD_PORT],
211
- networkReadBack: true,
212
- network: [...E2B.network],
213
- mounts: [...MOUNT],
214
- release: ["delete"],
117
+ // E2B Desktop's template has xfwm4, which its own desktop runs: the apps an agent opens are framed and focused.
118
+ windowManager: true,
215
119
  };
216
120
  #Sandbox;
217
121
  #connection;
@@ -231,8 +135,7 @@ class E2BHost {
231
135
  return { ...this.#connection, requestTimeoutMs: ms, ...(signal ? { signal } : {}) };
232
136
  }
233
137
  /** An E2B template is a name or id: letters, digits and ._:/- (no shell word, no path out). */
234
- check(spec) {
235
- const image = spec?.image;
138
+ check({ image }) {
236
139
  if (typeof image === "string" && image !== "" && !TEMPLATE.test(image)) {
237
140
  return [{ field: "image", message: `an image is the name or id of an E2B template, such as "${E2B_DESKTOP_TEMPLATE}" (E2B Desktop) or "${E2B_BASE_TEMPLATE}"` }];
238
141
  }
@@ -257,22 +160,15 @@ class E2BHost {
257
160
  };
258
161
  const sandbox = await this.#Sandbox.create(req.image, options);
259
162
  this.#sandboxes.set(sandbox.sandboxId, sandbox);
260
- return ok({ id: sandbox.sandboxId });
163
+ return { id: sandbox.sandboxId };
261
164
  }
262
- /** getInfo; a sandbox E2B does not have (SandboxNotFoundError, index.mjs:5431) is none. */
165
+ /** getInfo; a sandbox E2B does not have (SandboxNotFoundError, index.mjs:5431) is not_found, which the adapter reads as none. */
263
166
  async get(id, ctx) {
264
- try {
265
- return ok(machineOf(await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal))));
266
- }
267
- catch (error) {
268
- if (codeOf(error) === "not_found")
269
- return ok(undefined);
270
- throw error;
271
- }
167
+ return machineOf(await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal)));
272
168
  }
273
169
  /**
274
- * Every sandbox E2B lists with these metadata pairs (running and paused, index.d.mts:10289), all pages, each read
275
- * back by getInfo, since a listing does not carry the network; one bound, ctx.timeoutMs, for every page and read.
170
+ * Every sandbox E2B lists with these metadata pairs (running and paused, index.d.mts:10289), all pages within
171
+ * ctx.timeoutMs, each as getInfo reads it (the listing carries its end too).
276
172
  */
277
173
  async list(labels, ctx) {
278
174
  const until = Date.now() + ctx.timeoutMs;
@@ -281,36 +177,20 @@ class E2BHost {
281
177
  const found = new Map();
282
178
  for (let page = 0; paginator.hasNext; page++) {
283
179
  if (page >= MAX_PAGES)
284
- return fail("vendor", `Sandbox.list ran past ${MAX_PAGES} pages`);
180
+ throw new Error(`Sandbox.list ran past ${MAX_PAGES} pages`);
285
181
  const items = await paginator.nextItems({ requestTimeoutMs: left(), ...(ctx.signal ? { signal: ctx.signal } : {}) });
286
182
  if (!Array.isArray(items))
287
- return fail("vendor", "Sandbox.list: a page that is not a list of sandboxes");
183
+ throw new Error("Sandbox.list: a page that is not a list of sandboxes");
288
184
  for (const sb of items)
289
185
  if (typeof sb?.sandboxId === "string")
290
186
  found.set(sb.sandboxId, sb);
291
187
  }
292
- const machines = [];
293
- for (const sb of found.values()) {
294
- if (Date.now() >= until)
295
- return fail("timeout", `${machines.length} sandboxes were read back, ${sb.sandboxId} and any after it were not`);
296
- const read = await this.get(sb.sandboxId, { timeoutMs: left(), ...(ctx.signal ? { signal: ctx.signal } : {}) });
297
- if (!read.ok)
298
- return read;
299
- machines.push(read.value ?? listedOnly(sb));
300
- }
301
- return ok(machines);
188
+ return [...found.values()].map(machineOf);
302
189
  }
303
- /** Sandbox.kill, never signalled: a kill that cleans up after an abort must outlive it. Not found is done. */
190
+ /** Sandbox.kill, never signalled: a kill that cleans up after an abort must outlive it. */
304
191
  async delete(id, ctx) {
305
192
  this.#sandboxes.delete(id);
306
- try {
307
- await this.#Sandbox.kill(id, this.#api(ctx.timeoutMs));
308
- }
309
- catch (error) {
310
- if (codeOf(error) !== "not_found")
311
- throw error;
312
- }
313
- return ok(undefined);
193
+ await this.#Sandbox.kill(id, this.#api(ctx.timeoutMs));
314
194
  }
315
195
  /**
316
196
  * A connected Sandbox for envd's commands and files: the one create gave, or Sandbox.connect, whose timeout is a
@@ -333,60 +213,100 @@ class E2BHost {
333
213
  const sandbox = await this.#sandbox(id, ctx);
334
214
  const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
335
215
  await sandbox.files.write(path, buffer, { user: "root", requestTimeoutMs: ctx.timeoutMs, ...(ctx.signal ? { signal: ctx.signal } : {}) });
336
- return ok(undefined);
337
216
  }
338
217
  /**
339
- * A background command as root (index.mjs:5123-5146), its line the argv quoted. No command timeout, so envd never
340
- * kills it (start.go:39-44); no retained output, so a long one keeps no copy of its stdout (index.mjs:2708-2711).
341
- * Writes go one sendStdin at a time, in order; end is closeStdin; kill kills it and lets go of its stream.
218
+ * A process as root through envd's Process.Start stream, as commands.run starts one (index.mjs:5123-5146): `bash -l -c`
219
+ * and the argv quoted, root by the Basic header (authenticationHeader, index.mjs:1896-1900), and envd's keepalive
220
+ * every 50 s. Its stdout and stderr are the bytes each data event carries, passed on as they come: commands.run would
221
+ * decode them as UTF-8 text first. No deadline on the stream (timeoutMs 0, which the Connect transport reads as none,
222
+ * connect-web connect-transport.js:145-150), so envd never ends it (start.go:39-44); the start alone is bounded by
223
+ * ctx. Writes go one sendStdin at a time, in order; end is closeStdin; kill SIGKILLs it and lets go of its stream.
342
224
  */
343
- async exec(id, argv, { stdin }, ctx) {
225
+ async exec(id, argv, ctx) {
344
226
  const sandbox = await this.#sandbox(id, ctx);
345
- const out = feed();
346
- const err = feed();
227
+ const out = new PassThrough();
228
+ const err = new PassThrough();
347
229
  const requestTimeoutMs = this.#requestMs;
348
- const handle = await sandbox.commands.run(shellLine(argv), {
349
- background: true,
350
- stdin,
351
- user: "root",
352
- timeoutMs: 0,
353
- requestTimeoutMs: ctx.timeoutMs,
354
- retainOutput: false,
355
- onStdout: (data) => out.push(new Uint8Array(Buffer.from(data, "utf8"))),
356
- onStderr: (data) => err.push(new Uint8Array(Buffer.from(data, "utf8"))),
357
- });
358
- const exited = handle.wait().then((done) => done.exitCode, (error) => {
359
- const code = error?.exitCode;
360
- return typeof code === "number" ? code : -1;
361
- });
362
- void exited.then(() => {
230
+ const stream = new AbortController();
231
+ const events = sandbox.commands.rpc.start({ process: { cmd: "/bin/bash", args: ["-l", "-c", shellLine(argv)], envs: {} }, stdin: true }, { headers: { Authorization: ROOT, [KEEPALIVE_HEADER]: KEEPALIVE_S }, signal: stream.signal, timeoutMs: 0 })[Symbol.asyncIterator]();
232
+ // The start, within ctx: a stream that gives no start event in time, or the caller's abort, is let go of.
233
+ const startAbort = () => stream.abort(ctx.signal?.reason);
234
+ ctx.signal?.addEventListener("abort", startAbort, { once: true });
235
+ const startTimer = setTimeout(() => stream.abort(), ctx.timeoutMs);
236
+ let pid;
237
+ try {
238
+ const first = await events.next();
239
+ const event = first.done ? undefined : first.value.event?.event;
240
+ if (event?.case !== "start")
241
+ throw new Error(`envd's process stream began with ${event?.case ?? "nothing"}, not its start`);
242
+ pid = event.value.pid;
243
+ }
244
+ catch (error) {
245
+ const why = stream.signal.aborted ? (ctx.signal?.aborted ? "AbortError" : "TimeoutError") : undefined;
246
+ stream.abort();
247
+ if (why === undefined)
248
+ throw error;
249
+ throw Object.assign(new Error(why === "AbortError" ? "the exec was aborted before envd started it" : `envd did not start the process within ${ctx.timeoutMs / 1000} s`), { name: why });
250
+ }
251
+ finally {
252
+ clearTimeout(startTimer);
253
+ ctx.signal?.removeEventListener("abort", startAbort);
254
+ }
255
+ const exited = (async () => {
256
+ let code = -1;
257
+ try {
258
+ for (;;) {
259
+ const next = await events.next();
260
+ if (next.done)
261
+ break;
262
+ const event = next.value.event?.event;
263
+ if (event?.case === "data") {
264
+ const { output } = event.value;
265
+ if (output.case === "stdout")
266
+ push(out, output.value);
267
+ else if (output.case === "stderr")
268
+ push(err, output.value);
269
+ }
270
+ else if (event?.case === "end") {
271
+ code = event.value.exitCode;
272
+ break;
273
+ }
274
+ }
275
+ }
276
+ catch {
277
+ // A stream that broke, or one kill let go of: no exit code was read.
278
+ }
363
279
  out.end();
364
280
  err.end();
365
- void handle.disconnect().catch(() => { });
366
- });
367
- return ok({
368
- stdout: out.iterable,
369
- stderr: err.iterable,
370
- write: (bytes) => sandbox.commands.sendStdin(handle.pid, bytes, { requestTimeoutMs }),
371
- end: () => sandbox.commands.closeStdin(handle.pid, { requestTimeoutMs }),
281
+ stream.abort();
282
+ return code;
283
+ })();
284
+ return {
285
+ stdout: out,
286
+ stderr: err,
287
+ write: (bytes) => sandbox.commands.sendStdin(pid, bytes, { requestTimeoutMs }),
288
+ end: () => sandbox.commands.closeStdin(pid, { requestTimeoutMs }),
372
289
  wait: () => exited,
373
290
  kill: async () => {
374
- await handle.kill().catch(() => false);
375
- await handle.disconnect().catch(() => { });
291
+ await sandbox.commands.kill(pid, { requestTimeoutMs }).catch(() => false);
292
+ stream.abort();
376
293
  out.end();
377
294
  err.end();
378
295
  },
379
- });
296
+ };
380
297
  }
381
298
  /**
382
299
  * Moves E2B's timer (setTimeout, index.mjs:5529-5541) in the whole seconds E2B takes: up to clear create's end, so
383
- * the end reads as moved (deadlineOf), and down at the most the computer may live, so E2B's timer never passes it by
384
- * this machine's clock. A timer that would end before the deadline held now, or within create's rounding, is refused
385
- * as limit, and nothing moves.
300
+ * the end reads as moved (deadlineOf), and down at the most the computer may live (its max-deadline label), so E2B's
301
+ * timer never passes it by this machine's clock. A timer that would end before the deadline held now, or within
302
+ * create's rounding, is refused as limit, and nothing moves.
386
303
  */
387
- async setTimer(id, { end, most }, ctx) {
304
+ async extend(id, end, ctx) {
388
305
  const info = await this.#Sandbox.getInfo(id, this.#api(ctx.timeoutMs, ctx.signal));
389
306
  const machine = machineOf(info);
307
+ const most = new Date(machine.labels[MAX_LABEL] ?? Number.NaN);
308
+ if (Number.isNaN(most.getTime()))
309
+ throw new HostError("refused", `${id}'s label ${MAX_LABEL} reads ${show(machine.labels[MAX_LABEL])}, so the most it may live is unknown; nothing moved`);
390
310
  const now = Date.now();
391
311
  const target = end.getTime();
392
312
  const created = createdEnd(info);
@@ -397,31 +317,12 @@ class E2BHost {
397
317
  const held = Number.isNaN(vendorEnd) ? current : Math.max(current, vendorEnd);
398
318
  const name = info.metadata?.["agentrun.computer.name"] ?? id;
399
319
  if (now + timerMs < held) {
400
- return fail("limit", `no whole number of seconds E2B takes moves ${name}'s end from ${new Date(held).toISOString()} to ${end.toISOString()} without passing ${most.toISOString()}, the most this computer may live; nothing moved`);
320
+ throw new HostError("limit", `no whole number of seconds E2B takes moves ${name}'s end from ${new Date(held).toISOString()} to ${end.toISOString()} without passing ${most.toISOString()}, the most this computer may live; nothing moved`);
401
321
  }
402
322
  if (created !== undefined && now + timerMs < clearOf(created)) {
403
- return fail("limit", `${end.toISOString()} is within E2B's rounding of the end create gave ${name}, and moving E2B's end clear of it would pass ${most.toISOString()}, the most this computer may live`);
323
+ throw new HostError("limit", `${end.toISOString()} is within E2B's rounding of the end create gave ${name}, and moving E2B's end clear of it would pass ${most.toISOString()}, the most this computer may live`);
404
324
  }
405
325
  await this.#Sandbox.setTimeout(id, timerMs, this.#api(ctx.timeoutMs, ctx.signal));
406
- return ok(undefined);
407
- }
408
- /**
409
- * Settings' test: one page of the account's sandboxes by the adapter's own metadata, which makes nothing. The count is
410
- * read from the listing, with no getInfo of each: a busy account answers as fast, and one sandbox's read never fails a
411
- * working key. A further page is "or more".
412
- */
413
- async testConnection(ctx) {
414
- try {
415
- const paginator = this.#Sandbox.list({ ...this.#connection, requestTimeoutMs: ctx.timeoutMs, query: { metadata: { "agentrun.computer": "1" } }, limit: PAGE });
416
- const items = await paginator.nextItems({ requestTimeoutMs: ctx.timeoutMs, ...(ctx.signal ? { signal: ctx.signal } : {}) });
417
- if (!Array.isArray(items))
418
- return countTested("E2B", fail("vendor", "Sandbox.list: a page that is not a list of sandboxes"));
419
- const count = items.filter((sb) => typeof sb?.sandboxId === "string" && ours(sb.metadata)).length;
420
- return countTested("E2B", ok({ count, more: paginator.hasNext }));
421
- }
422
- catch (error) {
423
- return countTested("E2B", fail(codeOf(error), `Sandbox.list failed: ${words(error)}`));
424
- }
425
326
  }
426
327
  }
427
328
  /**
@@ -435,7 +336,7 @@ export class E2BProvider extends HostedProvider {
435
336
  throw new Error(PUBLIC);
436
337
  const { apiKey, Sandbox, domain = DEFAULT_DOMAIN, kind = "desktop", maxLifetimeMs = HOBBY_MAX_MS, ...rest } = options;
437
338
  if (typeof apiKey !== "string" || apiKey === "")
438
- throw new Error("an E2B API key is required");
339
+ throw new Error("options.apiKey, the E2B API key, is required: the provider reads no environment, so the caller passes it");
439
340
  const lacks = ["create", "connect", "getInfo", "setTimeout", "kill", "list"].filter((name) => typeof Sandbox?.[name] !== "function");
440
341
  if (lacks.length > 0)
441
342
  throw new Error(`options.Sandbox must be the e2b SDK's Sandbox class; it lacks ${lacks.join(", ")}`);
@@ -444,10 +345,6 @@ export class E2BProvider extends HostedProvider {
444
345
  throw new Error(ambient);
445
346
  if (typeof domain !== "string" || !DOMAIN.test(domain))
446
347
  throw new Error(`the E2B domain must be a host name such as ${DEFAULT_DOMAIN}, not ${JSON.stringify(domain)}`);
447
- if (!isWhole(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > PRO_MAX_MS) {
448
- throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most 24 h (${PRO_MAX_MS} ms), E2B Pro's longest sandbox; Hobby's is 1 h`);
449
- }
450
- const requestMs = rest.timeouts?.requestMs ?? DEFAULT_REQUEST_MS;
451
- super(new E2BHost(Sandbox, connectionOptions({ apiKey, domain }), requestMs), { ...rest, label: "E2B", kind, maxLifetimeMs });
348
+ super(new E2BHost(Sandbox, connectionOptions({ apiKey, domain }), timeoutsOf(rest.timeouts).requestMs), { ...rest, kind, maxLifetimeMs });
452
349
  }
453
350
  }