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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +321 -308
  3. package/box/build-agent37.mjs +177 -0
  4. package/dist/agent37.d.ts +165 -0
  5. package/dist/agent37.js +759 -0
  6. package/dist/attach.d.ts +146 -0
  7. package/dist/attach.js +469 -0
  8. package/dist/browserbase.d.ts +2 -4
  9. package/dist/browserbase.js +2 -1
  10. package/dist/client.d.ts +33 -1
  11. package/dist/client.js +53 -0
  12. package/dist/computerd-linux-amd64 +0 -0
  13. package/dist/computerd-linux-arm64 +0 -0
  14. package/dist/conformance/agent37.d.ts +96 -0
  15. package/dist/conformance/agent37.js +154 -0
  16. package/dist/conformance/cases/apps.d.ts +5 -0
  17. package/dist/conformance/cases/apps.js +160 -73
  18. package/dist/conformance/cases/health.js +14 -0
  19. package/dist/conformance/cases/index.js +2 -0
  20. package/dist/conformance/cases/provider.js +27 -1
  21. package/dist/conformance/cases/screen.d.ts +3 -0
  22. package/dist/conformance/cases/screen.js +18 -0
  23. package/dist/conformance/cases/settings.d.ts +29 -23
  24. package/dist/conformance/cases/settings.js +76 -58
  25. package/dist/conformance/cases/touch.js +19 -17
  26. package/dist/conformance/cases/ui.d.ts +2 -0
  27. package/dist/conformance/cases/ui.js +475 -0
  28. package/dist/conformance/cli.d.ts +9 -0
  29. package/dist/conformance/cli.js +28 -3
  30. package/dist/conformance/e2b.d.ts +6 -0
  31. package/dist/conformance/e2b.js +9 -2
  32. package/dist/conformance/fixture.d.ts +1 -1
  33. package/dist/conformance/fixture.js +25 -1
  34. package/dist/conformance/modal.d.ts +17 -13
  35. package/dist/conformance/modal.js +18 -9
  36. package/dist/conformance/orgo.d.ts +3 -3
  37. package/dist/conformance/orgo.js +6 -8
  38. package/dist/conformance/phone-harness.d.ts +6 -2
  39. package/dist/conformance/phone-harness.js +21 -4
  40. package/dist/conformance/report.js +1 -1
  41. package/dist/conformance/runner.js +23 -4
  42. package/dist/conformance/sweep.d.ts +50 -0
  43. package/dist/conformance/sweep.js +187 -0
  44. package/dist/conformance/types.d.ts +11 -3
  45. package/dist/conformance/ui-fixture.d.ts +56 -0
  46. package/dist/conformance/ui-fixture.js +43 -0
  47. package/dist/create-requests.d.ts +51 -0
  48. package/dist/create-requests.js +121 -0
  49. package/dist/daytona.d.ts +2 -4
  50. package/dist/daytona.js +3 -2
  51. package/dist/descriptor.d.ts +5 -0
  52. package/dist/descriptor.js +2 -0
  53. package/dist/descriptors/agent37.d.ts +41 -0
  54. package/dist/descriptors/agent37.js +28 -0
  55. package/dist/descriptors/index.d.ts +38 -2
  56. package/dist/descriptors/index.js +4 -2
  57. package/dist/descriptors/orgo.d.ts +2 -1
  58. package/dist/descriptors/orgo.js +3 -2
  59. package/dist/descriptors/phone-harness.d.ts +1 -1
  60. package/dist/descriptors/phone-harness.js +2 -2
  61. package/dist/docker.d.ts +7 -4
  62. package/dist/docker.js +271 -29
  63. package/dist/e2b.d.ts +9 -165
  64. package/dist/e2b.js +282 -1342
  65. package/dist/fake-ui-driver.d.ts +97 -0
  66. package/dist/fake-ui-driver.js +717 -0
  67. package/dist/host.d.ts +182 -0
  68. package/dist/host.js +1 -0
  69. package/dist/hosted/process.d.ts +67 -0
  70. package/dist/hosted/process.js +228 -0
  71. package/dist/hosted/provider.d.ts +146 -0
  72. package/dist/hosted/provider.js +1364 -0
  73. package/dist/hosted/scripts.d.ts +76 -0
  74. package/dist/{child.js → hosted/scripts.js} +93 -12
  75. package/dist/index.d.ts +7 -3
  76. package/dist/index.js +7 -4
  77. package/dist/kernel.d.ts +2 -4
  78. package/dist/kernel.js +2 -1
  79. package/dist/kinds.d.ts +8 -1
  80. package/dist/kinds.js +20 -4
  81. package/dist/local-chrome.d.ts +2 -4
  82. package/dist/local-chrome.js +2 -1
  83. package/dist/modal.d.ts +23 -181
  84. package/dist/modal.js +271 -1244
  85. package/dist/orgo-channel.d.ts +3 -2
  86. package/dist/orgo-channel.js +5 -2
  87. package/dist/orgo-desktop.d.ts +9 -4
  88. package/dist/orgo-desktop.js +33 -13
  89. package/dist/orgo-workspaces.d.ts +47 -0
  90. package/dist/orgo-workspaces.js +94 -0
  91. package/dist/orgo.d.ts +10 -4
  92. package/dist/orgo.js +30 -12
  93. package/dist/phone-harness.d.ts +31 -22
  94. package/dist/phone-harness.js +510 -698
  95. package/dist/png.d.ts +4 -0
  96. package/dist/png.js +27 -0
  97. package/dist/protocol.d.ts +335 -32
  98. package/dist/protocol.js +96 -3
  99. package/dist/provider.d.ts +34 -6
  100. package/dist/provider.js +16 -0
  101. package/dist/result.d.ts +1 -1
  102. package/dist/surface/api.d.ts +248 -0
  103. package/dist/surface/api.js +1 -0
  104. package/dist/surface/core.d.ts +42 -0
  105. package/dist/surface/core.js +393 -0
  106. package/dist/surface/index.d.ts +5 -0
  107. package/dist/surface/index.js +3 -0
  108. package/dist/surface/outline.d.ts +8 -0
  109. package/dist/surface/outline.js +50 -0
  110. package/dist/surface/script.d.ts +10 -0
  111. package/dist/surface/script.js +92 -0
  112. package/dist/ui-engine.d.ts +114 -0
  113. package/dist/ui-engine.js +798 -0
  114. package/package.json +17 -1
  115. package/dist/child.d.ts +0 -42
  116. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  117. package/dist/conformance/e2b-diagnose.js +0 -61
  118. package/dist/conformance/e2b-sweep.d.ts +0 -18
  119. package/dist/conformance/e2b-sweep.js +0 -132
  120. package/dist/conformance/modal-sweep.d.ts +0 -22
  121. package/dist/conformance/modal-sweep.js +0 -213
package/dist/docker.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // The Docker provisioner: every call through the docker CLI with execFile or spawn, never a shell.
2
2
  import { execFile, spawn } from "node:child_process";
3
- import { randomBytes } from "node:crypto";
3
+ import { randomUUID } from "node:crypto";
4
4
  import { readFileSync, statSync } from "node:fs";
5
5
  import { resolve } from "node:path";
6
6
  import { setTimeout as sleep } from "node:timers/promises";
@@ -20,6 +20,7 @@ import { addressBytes } from "./docker/egress-table.js";
20
20
  import { checkMount, WORKSPACE } from "./mount.js";
21
21
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
22
22
  import { failFor, ok, vendorFail } from "./result.js";
23
+ import { CreateRequests, endedWords, otherSpecWords } from "./create-requests.js";
23
24
  import { daemonWatch } from "./screen-watch.js";
24
25
  import { countTested } from "./test-connection.js";
25
26
  /** This module's failures: one with code vendor names Docker. */
@@ -99,11 +100,23 @@ const FIXED = "a Docker computer's network is fixed at create; create a new comp
99
100
  const NETWORKS = 'network is required: "none", "open" or { allow: [names or CIDRs] }';
100
101
  /** How often create asks whether the egress proxy is ready. */
101
102
  const EGRESS_POLL_MS = 100;
103
+ /** How long a create of a request whose computer another create is still making waits for it, and how often it looks:
104
+ * the image is on the host by then, so what is left is docker run, the display and the read-back. */
105
+ const REQUEST_WAIT_MS = 120_000;
106
+ const REQUEST_POLL_MS = 500;
102
107
  /** After a docker run cut off before its own exit: how long, at most, the leftovers are removed and looked for again,
103
108
  * how often, and for how long in a row the looks must find none of them before they count as gone (#settle). */
104
109
  const SETTLE_MS = 10_000;
105
110
  const SETTLE_EVERY_MS = 500;
106
111
  const SETTLE_QUIET_MS = 3_000;
112
+ /** The label naming which create made a computer's container: after its own docker run failed or was cut off, a create
113
+ * removes the container it made, never one another create of the same request made under the name. */
114
+ const ATTEMPT_LABEL = "agentrun.computer.attempt";
115
+ /** The label naming the spec's own labels (a JSON array of their keys, sorted): a container's labels also hold its image's,
116
+ * so only this says which a create asked for, and a retry of the request that drops one is another spec (#differs). */
117
+ const ASKED_LABEL = "agentrun.computer.labels";
118
+ /** What #settle reads of each container it looks for: its id, its name, and its labels (whose attempt it is). */
119
+ const SETTLE_FORMAT = '{"Id":{{json .Id}},"Name":{{json .Name}},"Config":{"Labels":{{json .Config.Labels}}}}';
107
120
  /**
108
121
  * Why #settle could not show its leftovers gone within SETTLE_MS, in words that always name them: `there`, what its
109
122
  * last look still found; or, when the last look found none but the quiet window was not complete, every name it
@@ -122,6 +135,8 @@ const INFO_FORMAT = '{"Architecture":{{json .Architecture}},"SecurityOptions":{{
122
135
  const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
123
136
  const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
124
137
  const noSuchContainer = (stderr) => /no such container/i.test(stderr);
138
+ /** Docker's words for a docker run whose --name another container holds. */
139
+ const nameTaken = (stderr) => /Conflict\. The container name "[^"]*" is already in use/.test(stderr);
125
140
  const nameOf = (report) => (report.Name ?? "").replace(/^\//, "");
126
141
  /** Only a container this provider made counts: its label, and a name of its making. */
127
142
  const ours = (report) => report.Config?.Labels?.[COMPUTER_LABEL] === "1" && NAME.test(nameOf(report));
@@ -137,6 +152,8 @@ export class DockerProvider {
137
152
  #desktop;
138
153
  #image;
139
154
  #egress;
155
+ /** Each create in flight, and the names of the computers this provider deleted (create-requests.ts). */
156
+ #requests = new CreateRequests();
140
157
  /** Why this provider's own interfaces are not the Docker host's, in words, or none: read once, for the first allowlist
141
158
  * with no egress.hostAddresses (#elsewhere). */
142
159
  #elsewhere;
@@ -303,11 +320,115 @@ export class DockerProvider {
303
320
  }
304
321
  return refusals;
305
322
  }
306
- async create(spec, { signal } = {}) {
323
+ /**
324
+ * Makes a computer, once per request (provider.md, Idempotent create): context.requestId names the container
325
+ * (computerNameFor). A request Docker holds a container for already answers that one (#taken); one whose computer
326
+ * was deleted here is refused exists; a create of a request in flight here waits for the first (CreateRequests).
327
+ */
328
+ async create(spec, context) {
307
329
  const refusals = this.check(spec);
308
- if (refusals.length > 0)
309
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
310
- const user = userOf(spec.user) ?? this.#user;
330
+ return this.#requests.create(spec, context, {
331
+ refuse: fail,
332
+ ...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
333
+ userOf: (asked) => this.#userFor(asked),
334
+ make: (name) => this.#createNamed(spec, name, context.signal),
335
+ });
336
+ }
337
+ /** The user a spec's computer runs as: the spec's, or the provider's. */
338
+ #userFor(spec) {
339
+ return userOf(spec.user) ?? this.#user;
340
+ }
341
+ /**
342
+ * How spec differs from report, the container Docker holds under its request's name: every way create's own drift
343
+ * check would find it differs from spec (inspectDrift: each label asked, the image, user, network, mount, sizes and
344
+ * workdir among them), and each label the computer was made with that spec does not ask for (ASKED_LABEL). Empty
345
+ * when it is the same.
346
+ */
347
+ async #differs(spec, report, signal) {
348
+ const host = await this.host({ signal });
349
+ if (!host.ok)
350
+ return host;
351
+ const proxy = await this.#proxyOf(report, signal);
352
+ if (!proxy.ok)
353
+ return proxy;
354
+ const daemon = this.#daemon();
355
+ if (!daemon.ok)
356
+ return daemon;
357
+ const expected = this.#expected(host.value, report.Config?.Labels?.[DEADLINE_LABEL] ?? "", this.#userFor(spec), this.#mountedDaemon(report) ?? daemon.value, proxy.value);
358
+ const labels = report.Config?.Labels ?? {};
359
+ let made;
360
+ try {
361
+ made = JSON.parse(labels[ASKED_LABEL] ?? "");
362
+ }
363
+ catch {
364
+ made = undefined;
365
+ }
366
+ const asked = Object.keys(spec.labels ?? {});
367
+ const dropped = Array.isArray(made)
368
+ ? made.filter((key) => typeof key === "string" && !asked.includes(key)).map((key) => `label ${key}: not declared, made with ${JSON.stringify(labels[key])}`)
369
+ : [`label ${ASKED_LABEL}: the spec's label keys, read back ${JSON.stringify(labels[ASKED_LABEL])}`];
370
+ return ok([...inspectDrift(spec, report, expected), ...dropped]);
371
+ }
372
+ /**
373
+ * A create of a request whose name Docker holds already: its docker run (of the computer, or of the allowlist's proxy)
374
+ * found the name taken, by a create of the same request in another process or before this one. A container of
375
+ * another spec, one stopped, or one past its deadline is refused exists; one running is returned once attach reads it
376
+ * as create made it, and one not there yet is waited for, within REQUEST_WAIT_MS. None by then is exists: a create
377
+ * that took the name and removed what it made has ended.
378
+ */
379
+ async #taken(spec, name, signal) {
380
+ const until = Date.now() + REQUEST_WAIT_MS;
381
+ let last;
382
+ for (;;) {
383
+ const found = await this.#inspect([name], signal);
384
+ if (!found.ok)
385
+ return found;
386
+ const report = found.value.find((one) => nameOf(one) === name);
387
+ if (report !== undefined) {
388
+ if (!ours(report))
389
+ return fail("exists", `a container named ${name} is on the Docker host and this provider did not make it: create with a new request id`);
390
+ const status = report.State?.Status;
391
+ const deadline = Date.parse(report.Config?.Labels?.[DEADLINE_LABEL] ?? "");
392
+ if (status === "exited" || status === "dead" || status === "removing" || deadline <= Date.now())
393
+ return fail("exists", endedWords(name));
394
+ if (report.State?.Running === true) {
395
+ const attached = await this.attach({ id: name }, { signal });
396
+ if (attached.ok) {
397
+ // Up and sound: returned only when it is the computer this spec asks for, as create would have made it.
398
+ const differ = await this.#differs(spec, report, signal);
399
+ if (!differ.ok)
400
+ return differ;
401
+ if (differ.value.length > 0)
402
+ return fail("exists", otherSpecWords(name, "was made", differ.value));
403
+ // Still the one read, running and within its deadline after those reads: attach checks a stopped
404
+ // container by inspect alone, so one that stopped or ended since would pass it.
405
+ const again = await this.#inspect([name], signal);
406
+ if (!again.ok)
407
+ return again;
408
+ const now = again.value.find((one) => nameOf(one) === name);
409
+ if (now === undefined || now.Id !== report.Id || now.State?.Running !== true || Date.parse(now.Config?.Labels?.[DEADLINE_LABEL] ?? "") <= Date.now())
410
+ return fail("exists", endedWords(name));
411
+ return ok({ id: attached.value.id, name });
412
+ }
413
+ if (attached.error.code === "aborted")
414
+ return attached;
415
+ // Its display or its daemon is not up yet: the first create is still making it.
416
+ last = attached.error;
417
+ }
418
+ }
419
+ if (Date.now() + REQUEST_POLL_MS >= until) {
420
+ if (report === undefined)
421
+ return fail("exists", endedWords(name));
422
+ return fail("timeout", `${name}, made for this request, was not up within ${REQUEST_WAIT_MS / 1000} s${last ? `: ${last.message}` : ""}`);
423
+ }
424
+ await sleep(REQUEST_POLL_MS, undefined, { signal }).catch(() => undefined);
425
+ if (signal?.aborted)
426
+ return fail("aborted", `create was aborted while ${name}, made for this request, came up`);
427
+ }
428
+ }
429
+ /** Everything create does under the request's name: the computer Docker holds under it, or a new one. */
430
+ async #createNamed(spec, name, signal) {
431
+ const user = this.#userFor(spec);
311
432
  const bound = spec.mount?.kind === "bind" ? spec.mount.path : undefined;
312
433
  const daemon = this.#daemon();
313
434
  if (!daemon.ok)
@@ -379,20 +500,28 @@ export class DockerProvider {
379
500
  }
380
501
  if (signal?.aborted)
381
502
  return fail("aborted", "create was aborted before docker run");
382
- const name = `computer-${randomBytes(6).toString("hex")}`;
503
+ // This create's own mark on the container it runs: what a failed or cut-off run leaves is removed by it, never a
504
+ // container another create of the request made under the name.
505
+ const attempt = randomUUID();
383
506
  // The lifetime counts from here: what the proxy and docker run take comes out of it.
384
507
  const lifetimeFrom = Date.now();
385
508
  const deadline = new Date(lifetimeFrom + runLifetimeMs(spec)).toISOString();
386
509
  if (allow !== undefined) {
387
510
  // The proxy first, ready before the computer exists: a computer never runs with an allowlist it cannot reach.
388
- const started = await this.#startEgress(name, user, deadline, allow, spec.labels ?? {}, signal);
511
+ const started = await this.#startEgress(name, user, deadline, allow, spec.labels ?? {}, attempt, signal);
389
512
  if (!started.ok) {
390
- const removed = await this.release({ id: name, name }, "delete");
513
+ // Another create of this request, in another process, runs its proxy: what it makes is the request's.
514
+ if (nameTaken(started.error.message))
515
+ return this.#taken(spec, name, signal);
516
+ // The computer was never run by this create: only the proxy and volume it made go, never a container under the
517
+ // name, nor a proxy or volume another create of the request made.
518
+ const removed = await this.#removeProxy(name, attempt);
391
519
  const after = removed.ok ? "its proxy and volume were removed" : `its proxy and volume could not be removed (${removed.error.message})`;
392
520
  return fail(started.error.code, `${started.error.message}; the computer ${name} was never run, and ${after}`);
393
521
  }
394
522
  }
395
- const args = ["run", "--detach", "--name", name, "--label", `${COMPUTER_LABEL}=1`, "--label", `${DEADLINE_LABEL}=${deadline}`];
523
+ const asked = JSON.stringify(Object.keys(spec.labels ?? {}).sort());
524
+ const args = ["run", "--detach", "--name", name, "--label", `${COMPUTER_LABEL}=1`, "--label", `${DEADLINE_LABEL}=${deadline}`, "--label", `${ATTEMPT_LABEL}=${attempt}`, "--label", `${ASKED_LABEL}=${asked}`];
396
525
  for (const [key, value] of Object.entries(spec.labels ?? {}))
397
526
  args.push("--label", `${key}=${value}`);
398
527
  const memoryMb = spec.memoryMb ?? DEFAULT_MEMORY_MB;
@@ -425,17 +554,32 @@ export class DockerProvider {
425
554
  args.push(spec.image, "init", "--deadline", deadline, ...(allow === undefined ? [] : [RELAY_FLAG, EGRESS_SOCKET]));
426
555
  const started = await this.#run(args, signal);
427
556
  const ranMs = Date.now() - lifetimeFrom;
557
+ if (started.ok && started.value.exitCode !== 0 && nameTaken(started.value.stderr)) {
558
+ // Another create of this request, in another process, ran first: its computer is the request's, and this one's
559
+ // proxy, made for a computer that never ran, goes.
560
+ if (allow !== undefined)
561
+ await this.#removeProxy(name, attempt);
562
+ return this.#taken(spec, name, signal);
563
+ }
428
564
  if (!started.ok || started.value.exitCode !== 0) {
429
565
  // A run that failed or was aborted may still have made the container; an allowlist's proxy and volume go with it.
430
- const released = await this.release({ id: name, name }, "delete");
566
+ // Only what this create made goes: a container another create of the request made under the name stays (a retry
567
+ // cut off before Docker answered that the name is taken).
568
+ const released = await this.#removeAttempt(name, attempt);
431
569
  if (started.ok)
432
570
  return vendorFail("docker", `docker run failed: ${started.value.stderr.trim()}`);
433
571
  // Cut off before its own exit: the daemon may still make the computer after release looked, and then its egress
434
572
  // volume with it (#settle).
435
- const left = await this.#settle([name], allow === undefined ? [] : [egressNameOf(name)]);
573
+ const left = await this.#settle([name], allow === undefined ? [] : [egressNameOf(name)], attempt);
436
574
  const what = allow === undefined ? `the computer ${name}` : `the computer ${name}, its proxy and its volume`;
437
575
  const removed = allow === undefined ? "was removed, if Docker made it after" : "were removed, if Docker made them after";
438
- const words = !released.ok ? `${what} could not all be removed: ${released.error.message}` : left === undefined ? `${what} ${removed}` : `${what} could not all be removed: ${left}`;
576
+ const words = !released.ok
577
+ ? `${what} could not all be removed: ${released.error.message}`
578
+ : released.value
579
+ ? `the computer ${name} that another create of this request made is left as it is${allow === undefined ? "" : `, and this create's proxy and volume ${left === undefined ? "were removed" : `could not all be removed: ${left}`}`}`
580
+ : left === undefined
581
+ ? `${what} ${removed}`
582
+ : `${what} could not all be removed: ${left}`;
439
583
  return fail(started.error.code, `${started.error.message === "docker run was aborted" ? "create was aborted during docker run" : started.error.message}; ${words}`);
440
584
  }
441
585
  const ref = { id: started.value.stdout.trim(), name };
@@ -500,8 +644,12 @@ export class DockerProvider {
500
644
  * confirmed gone, in words (settleWords). A create later than that is the janitor's: sweepLeftovers takes it at the
501
645
  * next sweep, past #leftoverGraceMs, which stays the backstop.
502
646
  */
503
- async #settle(containers, volumes) {
647
+ async #settle(containers, volumes, attempt) {
504
648
  const bound = AbortSignal.timeout(SETTLE_MS);
649
+ // Only what that create made (ATTEMPT_LABEL) is removed and waited for: a container or a volume another create of the
650
+ // request made under the name is not this create's leftover.
651
+ const mine = (reports) => reports.filter((one) => one.Config?.Labels?.[ATTEMPT_LABEL] === attempt);
652
+ const look = () => (containers.length === 0 ? Promise.resolve(ok([])) : this.#inspect(containers, bound, SETTLE_FORMAT));
505
653
  // When the looks first found none of them in the current run of empty looks; there, what the last look found.
506
654
  let quietSince;
507
655
  // Each named as what it is: a container and a volume may share a name (the egress proxy's).
@@ -511,23 +659,24 @@ export class DockerProvider {
511
659
  let there = checked;
512
660
  while (!bound.aborted) {
513
661
  // --volumes, as release removes a computer: a late container of an image that declares a VOLUME has its own.
514
- for (const container of containers)
515
- await this.#run(["rm", "--force", "--volumes", container], bound);
516
- for (const volume of volumes)
517
- await this.#run(["volume", "rm", "--force", volume], bound);
518
- const found = containers.length === 0 ? ok([]) : await this.#inspect(containers, bound, "{{json .Name}}");
519
- const listed = volumes.length === 0 ? undefined : await this.#run(["volume", "inspect", "--format", "{{.Name}}", ...volumes], bound);
662
+ // By id, the one looked at: never whatever holds the name by the time rm runs.
663
+ const seen = await look();
664
+ if (seen.ok)
665
+ for (const one of mine(seen.value))
666
+ await this.#run(["rm", "--force", "--volumes", String(one.Id)], bound);
667
+ const owned = await this.#volumesOf(volumes, attempt, bound);
668
+ if (owned.ok)
669
+ for (const volume of owned.value)
670
+ await this.#run(["volume", "rm", "--force", volume], bound);
671
+ const found = await look();
672
+ const listed = await this.#volumesOf(volumes, attempt, bound);
520
673
  // A look the bound cut off says nothing: what the last whole look found stands.
521
674
  if (bound.aborted)
522
675
  break;
523
- // A read that fails for any reason but "no such" counts as all still there.
524
- const unread = (ran) => ran.exitCode !== 0 && ran.stderr.split("\n").some((line) => line.trim() !== "" && !/no such volume/i.test(line));
525
- const foundNames = found.ok ? found.value.map((name) => String(name).replace(/^\//, "")) : containers;
526
- const listedText = listed === undefined ? "" : listed.ok && !unread(listed.value) ? listed.value.stdout : undefined;
527
- there = [
528
- ...containers.filter((name) => foundNames.includes(name)).map(containerWords),
529
- ...volumes.filter((name) => listedText === undefined || listedText.split("\n").some((line) => line.includes(name))).map(volumeWords),
530
- ];
676
+ // A read that fails counts as all still there.
677
+ const foundNames = found.ok ? mine(found.value).map(nameOf) : containers;
678
+ const listedNames = listed.ok ? listed.value : volumes;
679
+ there = [...containers.filter((name) => foundNames.includes(name)).map(containerWords), ...volumes.filter((name) => listedNames.includes(name)).map(volumeWords)];
531
680
  if (there.length > 0)
532
681
  quietSince = undefined;
533
682
  else {
@@ -550,8 +699,10 @@ export class DockerProvider {
550
699
  * bound, until the proxy logs its ready line. A proxy that ends first fails with its own last words. The caller
551
700
  * removes whatever was made when this fails.
552
701
  */
553
- async #startEgress(name, user, deadline, allow, labels, signal) {
702
+ async #startEgress(name, user, deadline, allow, specLabels, attempt, signal) {
554
703
  const proxy = egressNameOf(name);
704
+ // The proxy and its volume carry the create's attempt too: its cleanup removes only what it made.
705
+ const labels = { ...specLabels, [ATTEMPT_LABEL]: attempt };
555
706
  const volume = await this.#run(egressVolumeArgs(name, user, deadline, labels), signal);
556
707
  if (!volume.ok)
557
708
  return volume;
@@ -562,7 +713,7 @@ export class DockerProvider {
562
713
  const ran = await this.#run(args, signal);
563
714
  if (!ran.ok) {
564
715
  // Cut off before its own exit: the daemon may still make the proxy after the caller's cleanup looked (#settle).
565
- const left = await this.#settle([proxy], [proxy]);
716
+ const left = await this.#settle([proxy], [proxy], attempt);
566
717
  const words = left === undefined ? "the proxy and its volume, if Docker made them after, were removed" : `the proxy and its volume could not all be removed: ${left}`;
567
718
  return fail(ran.error.code, `${ran.error.message === "docker run was aborted" ? "create was aborted during docker run of the egress proxy" : ran.error.message}; ${words}`);
568
719
  }
@@ -1089,6 +1240,97 @@ export class DockerProvider {
1089
1240
  return fail("invalid", `${ref.name} is not the name of a Docker computer (computer-<12 hex digits>)`);
1090
1241
  if (how !== "stop" && how !== "delete")
1091
1242
  return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
1243
+ // A deleted computer's request is spent: the same request id again is refused, never made a second time.
1244
+ if (how === "delete")
1245
+ this.#requests.end(ref.name);
1246
+ return this.#remove(ref, how);
1247
+ }
1248
+ /**
1249
+ * An allowlist proxy and its volume that one create made for a computer it never ran: each only when it carries that
1250
+ * create's attempt (ATTEMPT_LABEL) with the computer's egress label, found by both as release finds a proxy, the
1251
+ * proxy removed by its id. One another create of the request made stays. Bounded by SETTLE_MS, never the caller's
1252
+ * signal, which may have ended.
1253
+ */
1254
+ async #removeProxy(name, attempt) {
1255
+ const proxy = egressNameOf(name);
1256
+ const bound = AbortSignal.timeout(SETTLE_MS);
1257
+ const filters = ["--filter", `label=${EGRESS_LABEL}=${name}`, "--filter", `label=${ATTEMPT_LABEL}=${attempt}`];
1258
+ const lines = (text) => text.split("\n").map((line) => line.trim()).filter(Boolean);
1259
+ const found = await this.#run(["ps", "-a", "--no-trunc", ...filters, "--format", "{{.ID}}"], bound);
1260
+ if (!found.ok)
1261
+ return found;
1262
+ if (found.value.exitCode !== 0)
1263
+ return vendorFail("docker", `docker ps for ${proxy} failed: ${found.value.stderr.trim()}`);
1264
+ for (const id of lines(found.value.stdout)) {
1265
+ const container = await this.#run(["rm", "--force", id], bound);
1266
+ if (!container.ok)
1267
+ return container;
1268
+ if (container.value.exitCode !== 0 && !noSuchContainer(container.value.stderr))
1269
+ return vendorFail("docker", `docker rm ${proxy} failed: ${container.value.stderr.trim()}`);
1270
+ }
1271
+ const volumes = await this.#run(["volume", "ls", ...filters, "--format", "{{.Name}}"], bound);
1272
+ if (!volumes.ok)
1273
+ return volumes;
1274
+ if (volumes.value.exitCode !== 0)
1275
+ return vendorFail("docker", `docker volume ls for ${proxy} failed: ${volumes.value.stderr.trim()}`);
1276
+ for (const volume of lines(volumes.value.stdout)) {
1277
+ const removed = await this.#run(["volume", "rm", "--force", volume], bound);
1278
+ if (!removed.ok)
1279
+ return removed;
1280
+ if (removed.value.exitCode !== 0)
1281
+ return vendorFail("docker", `docker volume rm ${volume} failed: ${removed.value.stderr.trim()}`);
1282
+ }
1283
+ return ok(undefined);
1284
+ }
1285
+ /** Of the volumes named, the ones there that carry the attempt (ATTEMPT_LABEL); one that is not there is left out. */
1286
+ async #volumesOf(names, attempt, signal) {
1287
+ if (names.length === 0)
1288
+ return ok([]);
1289
+ const ran = await this.#run(["volume", "inspect", "--format", "{{json .}}", ...names], signal);
1290
+ if (!ran.ok)
1291
+ return ran;
1292
+ const errors = ran.value.stderr.split("\n").filter((line) => line.trim() !== "" && !/no such volume/i.test(line));
1293
+ if (ran.value.exitCode !== 0 && errors.length > 0)
1294
+ return vendorFail("docker", `docker volume inspect failed: ${errors.join("; ")}`);
1295
+ const mine = [];
1296
+ for (const line of ran.value.stdout.split("\n").filter((one) => one.trim() !== "")) {
1297
+ let volume;
1298
+ try {
1299
+ volume = JSON.parse(line);
1300
+ }
1301
+ catch {
1302
+ return vendorFail("docker", `docker volume inspect wrote a line that is not JSON: ${line.slice(0, 200)}`);
1303
+ }
1304
+ if (typeof volume.Name === "string" && volume.Labels?.[ATTEMPT_LABEL] === attempt)
1305
+ mine.push(volume.Name);
1306
+ }
1307
+ return ok(mine);
1308
+ }
1309
+ /**
1310
+ * What one create made under the name, removed after its computer's docker run failed or was cut off: the container
1311
+ * that carries its attempt (ATTEMPT_LABEL), and the allowlist proxy and volume it made (#removeProxy). A container
1312
+ * another create of the request made under the name, in another process or before this one, is left as it is, with
1313
+ * its proxy and volume: true then. The look is bounded (SETTLE_MS), never the caller's signal, which may have ended.
1314
+ */
1315
+ async #removeAttempt(name, attempt) {
1316
+ const found = await this.#inspect([name], AbortSignal.timeout(SETTLE_MS));
1317
+ if (!found.ok)
1318
+ return found;
1319
+ const report = found.value.find((one) => nameOf(one) === name);
1320
+ const mine = report?.Config?.Labels?.[ATTEMPT_LABEL] === attempt;
1321
+ // By the id looked at, never by the name, which another create may hold by the time rm runs.
1322
+ if (mine) {
1323
+ const removed = await this.#run(["rm", "--force", "--volumes", String(report.Id)], AbortSignal.timeout(SETTLE_MS));
1324
+ if (!removed.ok)
1325
+ return removed;
1326
+ if (removed.value.exitCode !== 0 && !noSuchContainer(removed.value.stderr))
1327
+ return vendorFail("docker", `docker rm ${name} failed: ${removed.value.stderr.trim()}`);
1328
+ }
1329
+ const proxy = await this.#removeProxy(name, attempt);
1330
+ return proxy.ok ? ok(report !== undefined && !mine) : proxy;
1331
+ }
1332
+ /** release's work, which create also does for what it made before its computer ran (its request is not spent). */
1333
+ async #remove(ref, how) {
1092
1334
  const args = how === "stop" ? ["stop", ref.name] : ["rm", "--force", "--volumes", ref.name];
1093
1335
  const ran = await this.#run(args);
1094
1336
  if (!ran.ok)
package/dist/e2b.d.ts CHANGED
@@ -1,10 +1,6 @@
1
- import { type DesktopOptions } from "./desktop.js";
1
+ import { HostedProvider, type HostedOptions, type HostedTimeouts } from "./hosted/provider.js";
2
2
  import type { KindCapabilities } from "./kinds.js";
3
- import { type MountKind } from "./mount.js";
4
- import { type ProviderNote } from "./mount-archil.js";
5
- import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type CreatedComputer, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
6
- import { type ComputerErrorCode, type Result } from "./result.js";
7
- import { type ScreenWatch, type ScreenWatchHandlers, type WatchOptions } from "./screen-watch.js";
3
+ import type { MountKind } from "./mount.js";
8
4
  /** What every SDK call is given: the key, the domain and the API URL explicitly, and debug false (index.mjs:1126-1152). */
9
5
  export interface E2BConnectionOptions {
10
6
  apiKey: string;
@@ -132,59 +128,19 @@ export interface E2BSandboxClass {
132
128
  limit: number;
133
129
  }): E2BPaginator;
134
130
  }
135
- /** The longest each kind of call may take, and the pauses between polls. */
136
- export interface E2BTimeouts {
137
- /** One control-plane or envd call: getInfo, kill, setTimeout, connect, a page of list, a bridge's start. */
138
- requestMs: number;
139
- /** Sandbox.create. */
140
- createMs: number;
141
- /** The daemon's upload. */
142
- uploadMs: number;
143
- /** The install command. */
144
- execMs: number;
145
- /** From a connect's start to the daemon's hello, and each read-back call after it. */
146
- helloMs: number;
147
- /** The probe, run through the daemon: it takes at most 20 s (10 s to connect, 10 s to answer, every target at once). */
148
- probeMs: number;
149
- /** One whole list, every page and every sandbox's read-back. */
150
- listMs: number;
151
- /** From a kill to a sandbox E2B no longer has and no longer lists. */
152
- goneMs: number;
153
- /** The first pause between two reads while release waits; the pauses double up to 5 s. */
154
- pollMs: number;
155
- /** How long create waits for the listing to show the new computer. */
156
- listedMs: number;
157
- /** Each root step of an Archil mount (the preflight, mount or revoke, serve), and its checkin at release. */
158
- mountMs: number;
159
- }
160
- export interface E2BProviderOptions {
131
+ /** The E2B provider's options: the key and the SDK, then the shared adapter's (HostedOptions). */
132
+ export interface E2BProviderOptions extends Omit<HostedOptions, "label" | "maxLifetimeMs"> {
161
133
  /** The E2B API key. The caller passes it; this provider never reads it from the environment or puts it in a computer. */
162
134
  apiKey: string;
163
- /** Told what is no failure of the call it came from: a release that did not let an Archil folder go cleanly. */
164
- onNote?: ProviderNote;
165
- /** The SDK's Sandbox class: the host's `e2b` package's, or a fake. */
135
+ /** The SDK's Sandbox class: the host's `e2b` package's, or anything with the same slice. */
166
136
  Sandbox: E2BSandboxClass;
167
137
  /** E2B's domain: the API is https://api.<domain>. Default e2b.app. */
168
138
  domain?: string;
169
- /** The daemon binary for linux/amd64 on this machine. Default this package's dist/computerd-linux-amd64. */
170
- daemonPath?: string;
171
139
  /** desktop (default): a template with an X server, started through the daemon; linux: no screen. */
172
140
  kind?: "desktop" | "linux";
173
- /** The display and its X server, for kind desktop. Default Xvfb on :0, 1280x800. */
174
- desktop?: DesktopOptions;
175
141
  /** The longest lifetime check takes: E2B Hobby's 1 h by default, Pro's 24 h at most. */
176
142
  maxLifetimeMs?: number;
177
- /**
178
- * Who the daemon runs as, uid:gid in numbers, never root. Default 2510:2510 (TOOL_USER), a uid no process of E2B's
179
- * holds: init refuses to start while another process does.
180
- */
181
- daemonUser?: string;
182
- timeouts?: Partial<E2BTimeouts>;
183
- /**
184
- * The addresses the probe tries, to show none of them answers a computer with network none: host:port over TCP, or
185
- * host:port/udp, a DNS query over UDP.
186
- */
187
- probeTargets?: string[];
143
+ timeouts?: Partial<HostedTimeouts>;
188
144
  }
189
145
  /**
190
146
  * What create() takes: the provider's options, the SDK's Sandbox class optional (default the host's e2b package's).
@@ -212,122 +168,10 @@ export declare const conformance: () => Promise<typeof import("./conformance/e2b
212
168
  export declare const MOUNT: readonly MountKind[];
213
169
  /** The machine kind and groups of each configuration: kind linux (the plain template), and kind desktop (the default). */
214
170
  export declare const CAPABILITIES: readonly KindCapabilities[];
215
- /** The E2B timeout of the diagnostic's sandbox: E2B ends it at 10 minutes whatever happens to the run. */
216
- export declare const DIAGNOSE_LIFETIME_MS: number;
217
- /**
218
- * What diagnoseNetworkNone learned, one JSON object: the sandbox it made (none when create made nothing), E2B's
219
- * read-back of its network, the provider's own network-none check from inside (`passed`, or its refusal in words, which
220
- * stands: the diagnostic never relaxes it), what `computerd probe --diagnose` printed, why it stopped short of that, and
221
- * whether the sandbox was killed and read back gone.
222
- */
223
- export interface E2BNetworkDiagnosis {
224
- template: string;
225
- computer?: ComputerRef;
226
- readBack?: {
227
- allowInternetAccess?: boolean;
228
- allowPublicTraffic?: boolean;
229
- allowOut?: string[];
230
- denyOut?: string[];
231
- };
232
- check?: string;
233
- /** What the provider's check recorded that does not refuse the sandbox: its silent accepts, in words. */
234
- notes?: string[];
235
- diagnosis?: unknown;
236
- error?: {
237
- code: ComputerErrorCode;
238
- message: string;
239
- };
240
- released: {
241
- gone: boolean;
242
- words: string;
243
- };
244
- }
245
- /**
246
- * The network diagnostic: one sandbox made exactly as create makes one for network none (the same options, read-back,
247
- * upload and sha256 check, daemon and display start, and the provider's own check from inside, recorded), then
248
- * `computerd probe --diagnose` in it, and the sandbox killed and read back gone whatever happened, an abort included.
249
- * Its E2B timeout is 10 minutes. It never relaxes create: create still refuses what the check refuses.
250
- */
251
- export declare function diagnoseNetworkNone(provider: E2BProvider, { image, signal }: {
252
- image: string;
253
- signal?: AbortSignal;
254
- }): Promise<E2BNetworkDiagnosis>;
255
171
  /**
256
- * Computers that are E2B sandboxes. A spec's image is an E2B template (its name or id): "desktop" is E2B Desktop's, with
257
- * Xvfb, x11vnc and noVNC (e2b-dev/desktop template.py:21-65). See the README's E2B section for every call and its
258
- * citation.
172
+ * Computers that are E2B sandboxes, on the shared adapter. A spec's image is an E2B template (its name or id):
173
+ * "desktop" is E2B Desktop's, with Xvfb, x11vnc and noVNC (e2b-dev/desktop template.py:21-65).
259
174
  */
260
- export declare class E2BProvider implements ComputerProvider {
261
- #private;
262
- readonly id = "e2b";
263
- readonly version: string;
175
+ export declare class E2BProvider extends HostedProvider {
264
176
  constructor(options: E2BProviderOptions);
265
- /**
266
- * daemon child: E2B's envd is the sandbox's first process, under systemd with Restart=always (e2b-dev/infra
267
- * envd.service.tpl:26-30), and init is a background command it runs (#prepare), so init's exit leaves the sandbox. Its
268
- * 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
269
- * 49983, so init starts with --own-network, and network none is all a computer takes until a proxy carries open out
270
- * of the daemon's own network.
271
- */
272
- capabilities(): ComputerCapabilities;
273
- check(spec: ComputerSpec): Refusal[];
274
- create(spec: ComputerSpec, { signal }?: CallContext): Promise<Result<CreatedComputer>>;
275
- /** The live view: screen.watch on a connection of the watch's own (daemonWatch); a linux computer has no screen. */
276
- watch(ref: ComputerRef, handlers: ScreenWatchHandlers, options?: WatchOptions): Promise<Result<ScreenWatch>>;
277
- connect(ref: ComputerRef): Promise<Result<ComputerConnection>>;
278
- attach(ref: {
279
- id: string;
280
- } | {
281
- labels: Record<string, string>;
282
- }, { signal }?: CallContext): Promise<Result<AttachedComputer>>;
283
- /**
284
- * Settings' test: one page of the account's sandboxes by the provider's own metadata, which makes nothing. The count is
285
- * read from the listing, with no getInfo of each: a busy account answers as fast, and one sandbox's read never fails a
286
- * working key. A further page is "or more".
287
- */
288
- testConnection({ signal }?: CallContext): Promise<Result<{
289
- detail: string;
290
- }>>;
291
- /**
292
- * Every computer this provider made that carries all of these labels, running or paused (stopped), each one's
293
- * network read back by getInfo, since a listing does not carry it. One deadline, listMs from the call, bounds every
294
- * page and every read-back.
295
- */
296
- list(labels: Record<string, string>, { signal }?: CallContext): Promise<Result<ComputerInfo[]>>;
297
- /** For the sweep: every sandbox E2B lists with agentrun.computer=1, whatever its name, as E2B reports it, with its
298
- * metadata as its labels (the sweep kills only a conformance run's). */
299
- listLabelled({ signal }?: CallContext): Promise<Result<Array<{
300
- id: string;
301
- state: string;
302
- labels: Record<string, string>;
303
- }>>>;
304
- /** For the sweep: whether E2B still has a sandbox, read once by getInfo; not_found is gone. */
305
- probeGone(id: string, { signal }?: CallContext): Promise<Result<{
306
- gone: boolean;
307
- state?: string;
308
- }>>;
309
- /** For the sweep: Sandbox.kill of any sandbox the label query listed. Not found is done. */
310
- killById(id: string): Promise<Result<void>>;
311
- /** E2B reads the policy back (getInfo). A change is refused: the provider fixes the network at create. */
312
- network(ref: ComputerRef, policy?: NetworkSpec, { signal }?: CallContext): Promise<Result<NetworkPolicy>>;
313
- /**
314
- * Moves E2B's timer to now + ttlMs (setTimeout, index.mjs:5529-5541), then init's own deadline to the end E2B reads
315
- * back, and returns the deadline init took; never earlier than the current end, never past create's time plus the
316
- * cap, which init was given as its maximum. There is no label to move: E2B has no call that changes metadata, and
317
- * list() reads the vendor's end. A provider runs one extend of a computer at a time, each reading the deadline the one
318
- * before it left, so a slow, shorter extend never pulls E2B's timer under a longer one's.
319
- */
320
- extend(ref: ComputerRef, ttlMs: number, { signal }?: CallContext): Promise<Result<{
321
- deadline: Date;
322
- }>>;
323
- /**
324
- * delete reads the sandbox back to check it is this provider's, then kills it, both never signalled, so a release
325
- * after an abort, or one aborted during the read, still sends the kill; it is idempotent: one E2B no longer has is ok.
326
- * E2B answers a kill before the sandbox is gone, so release then waits (#settle) until E2B reads it gone and no longer
327
- * lists it, within goneMs and the caller's signal, the one step the signal ends. A running Archil computer lets go of
328
- * the run's folder first (archilRelease: the final sync through computerd, then checkin as root); the kill runs
329
- * whatever that answers. A folder not let go cleanly loses nothing (every call that changed it synced, and the next
330
- * claim revokes the hold), so it is said through onNote, and the release succeeds once the sandbox is gone.
331
- */
332
- release(ref: ComputerRef, how: ReleaseHow, { signal }?: CallContext): Promise<Result<void>>;
333
177
  }