@parcha/agentrun-computer 0.1.0-beta.35 → 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 (148) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +423 -323
  3. package/box/Dockerfile +3 -1
  4. package/box/agentrun-archil +59 -7
  5. package/box/build-agent37.mjs +177 -0
  6. package/box/build-daytona.py +20 -4
  7. package/dist/agent37.d.ts +165 -0
  8. package/dist/agent37.js +759 -0
  9. package/dist/attach.d.ts +146 -0
  10. package/dist/attach.js +469 -0
  11. package/dist/browser.d.ts +61 -10
  12. package/dist/browser.js +125 -3
  13. package/dist/browserbase.d.ts +46 -23
  14. package/dist/browserbase.js +162 -17
  15. package/dist/chrome.d.ts +3 -4
  16. package/dist/chrome.js +6 -11
  17. package/dist/client.d.ts +33 -1
  18. package/dist/client.js +53 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/agent37.d.ts +96 -0
  22. package/dist/conformance/agent37.js +154 -0
  23. package/dist/conformance/cases/apps.d.ts +5 -0
  24. package/dist/conformance/cases/apps.js +160 -73
  25. package/dist/conformance/cases/health.js +14 -0
  26. package/dist/conformance/cases/index.js +2 -0
  27. package/dist/conformance/cases/provider.js +27 -1
  28. package/dist/conformance/cases/screen.d.ts +3 -0
  29. package/dist/conformance/cases/screen.js +18 -0
  30. package/dist/conformance/cases/settings.d.ts +29 -23
  31. package/dist/conformance/cases/settings.js +76 -58
  32. package/dist/conformance/cases/touch.js +19 -17
  33. package/dist/conformance/cases/ui.d.ts +2 -0
  34. package/dist/conformance/cases/ui.js +475 -0
  35. package/dist/conformance/cli.d.ts +9 -0
  36. package/dist/conformance/cli.js +28 -3
  37. package/dist/conformance/daytona.d.ts +4 -0
  38. package/dist/conformance/daytona.js +5 -0
  39. package/dist/conformance/e2b.d.ts +6 -0
  40. package/dist/conformance/e2b.js +9 -2
  41. package/dist/conformance/fixture.d.ts +1 -1
  42. package/dist/conformance/fixture.js +25 -1
  43. package/dist/conformance/modal.d.ts +17 -13
  44. package/dist/conformance/modal.js +18 -9
  45. package/dist/conformance/orgo.d.ts +3 -3
  46. package/dist/conformance/orgo.js +6 -8
  47. package/dist/conformance/phone-harness.d.ts +6 -2
  48. package/dist/conformance/phone-harness.js +21 -4
  49. package/dist/conformance/report.js +1 -1
  50. package/dist/conformance/runner.js +23 -4
  51. package/dist/conformance/sweep.d.ts +50 -0
  52. package/dist/conformance/sweep.js +187 -0
  53. package/dist/conformance/types.d.ts +11 -3
  54. package/dist/conformance/ui-fixture.d.ts +56 -0
  55. package/dist/conformance/ui-fixture.js +43 -0
  56. package/dist/create-requests.d.ts +51 -0
  57. package/dist/create-requests.js +121 -0
  58. package/dist/daytona.d.ts +15 -5
  59. package/dist/daytona.js +58 -38
  60. package/dist/descriptor.d.ts +29 -2
  61. package/dist/descriptor.js +13 -0
  62. package/dist/descriptors/agent37.d.ts +41 -0
  63. package/dist/descriptors/agent37.js +28 -0
  64. package/dist/descriptors/browserbase.d.ts +1 -0
  65. package/dist/descriptors/browserbase.js +2 -0
  66. package/dist/descriptors/daytona.d.ts +23 -2
  67. package/dist/descriptors/daytona.js +34 -2
  68. package/dist/descriptors/index.d.ts +66 -3
  69. package/dist/descriptors/index.js +5 -3
  70. package/dist/descriptors/kernel.d.ts +1 -0
  71. package/dist/descriptors/kernel.js +2 -0
  72. package/dist/descriptors/modal.d.ts +4 -0
  73. package/dist/descriptors/modal.js +11 -1
  74. package/dist/descriptors/orgo.d.ts +13 -1
  75. package/dist/descriptors/orgo.js +9 -3
  76. package/dist/descriptors/phone-harness.d.ts +6 -1
  77. package/dist/descriptors/phone-harness.js +5 -2
  78. package/dist/docker/egress.d.ts +4 -3
  79. package/dist/docker/egress.js +7 -6
  80. package/dist/docker.d.ts +7 -4
  81. package/dist/docker.js +278 -34
  82. package/dist/e2b.d.ts +9 -165
  83. package/dist/e2b.js +282 -1342
  84. package/dist/fake-ui-driver.d.ts +97 -0
  85. package/dist/fake-ui-driver.js +717 -0
  86. package/dist/host.d.ts +182 -0
  87. package/dist/host.js +1 -0
  88. package/dist/hosted/process.d.ts +67 -0
  89. package/dist/hosted/process.js +228 -0
  90. package/dist/hosted/provider.d.ts +146 -0
  91. package/dist/hosted/provider.js +1364 -0
  92. package/dist/hosted/scripts.d.ts +76 -0
  93. package/dist/{child.js → hosted/scripts.js} +93 -12
  94. package/dist/index.d.ts +11 -7
  95. package/dist/index.js +10 -7
  96. package/dist/janitor.d.ts +5 -4
  97. package/dist/janitor.js +1 -1
  98. package/dist/kernel.d.ts +17 -27
  99. package/dist/kernel.js +94 -18
  100. package/dist/kinds.d.ts +17 -5
  101. package/dist/kinds.js +20 -4
  102. package/dist/labels.d.ts +10 -2
  103. package/dist/labels.js +30 -7
  104. package/dist/local-chrome.d.ts +5 -5
  105. package/dist/local-chrome.js +10 -5
  106. package/dist/modal.d.ts +23 -181
  107. package/dist/modal.js +273 -1232
  108. package/dist/mount-archil.d.ts +25 -3
  109. package/dist/mount-archil.js +39 -8
  110. package/dist/orgo-channel.d.ts +3 -2
  111. package/dist/orgo-channel.js +5 -2
  112. package/dist/orgo-desktop.d.ts +23 -9
  113. package/dist/orgo-desktop.js +328 -66
  114. package/dist/orgo-names.d.ts +129 -3
  115. package/dist/orgo-names.js +211 -8
  116. package/dist/orgo-workspaces.d.ts +47 -0
  117. package/dist/orgo-workspaces.js +94 -0
  118. package/dist/orgo.d.ts +27 -10
  119. package/dist/orgo.js +411 -81
  120. package/dist/phone-harness.d.ts +31 -21
  121. package/dist/phone-harness.js +510 -681
  122. package/dist/png.d.ts +4 -0
  123. package/dist/png.js +27 -0
  124. package/dist/protocol.d.ts +338 -30
  125. package/dist/protocol.js +96 -3
  126. package/dist/provider.d.ts +97 -7
  127. package/dist/provider.js +24 -3
  128. package/dist/result.d.ts +1 -1
  129. package/dist/surface/api.d.ts +248 -0
  130. package/dist/surface/api.js +1 -0
  131. package/dist/surface/core.d.ts +42 -0
  132. package/dist/surface/core.js +393 -0
  133. package/dist/surface/index.d.ts +5 -0
  134. package/dist/surface/index.js +3 -0
  135. package/dist/surface/outline.d.ts +8 -0
  136. package/dist/surface/outline.js +50 -0
  137. package/dist/surface/script.d.ts +10 -0
  138. package/dist/surface/script.js +92 -0
  139. package/dist/ui-engine.d.ts +114 -0
  140. package/dist/ui-engine.js +798 -0
  141. package/package.json +17 -1
  142. package/dist/child.d.ts +0 -42
  143. package/dist/conformance/e2b-diagnose.d.ts +0 -16
  144. package/dist/conformance/e2b-diagnose.js +0 -61
  145. package/dist/conformance/e2b-sweep.d.ts +0 -18
  146. package/dist/conformance/e2b-sweep.js +0 -132
  147. package/dist/conformance/modal-sweep.d.ts +0 -22
  148. package/dist/conformance/modal-sweep.js +0 -213
@@ -1,8 +1,9 @@
1
1
  import type { DockerInspect } from "./inspect.js";
2
2
  import type { NetworkPolicy } from "../provider.js";
3
- /** The proxy container's image: node:22.23.4-bookworm-slim, pinned to its multi-arch index digest (as serve pins its
4
- * own), so every host runs the same Node. The provider's `egress.image` replaces it. */
5
- export declare const EGRESS_IMAGE = "node:22.23.4-bookworm-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d";
3
+ /** The proxy container's image: node:22.23.5-trixie-slim (Node 22's November 2026 security release), pinned to its
4
+ * multi-arch index digest (amd64 and arm64 both listed), so every host runs the same Node. serve's macOS proxy pins the
5
+ * same image. The provider's `egress.image` replaces it. */
6
+ export declare const EGRESS_IMAGE = "node:22.23.5-trixie-slim@sha256:68c76cfad89921b927eae28ba21407475e29d0ce450afcdbe70c1532db042b64";
6
7
  /** The label the proxy container and the volume carry: the computer's name. In the provider's own namespace, which a
7
8
  * spec's labels cannot use. */
8
9
  export declare const EGRESS_LABEL = "agentrun.computer.egress";
@@ -1,8 +1,8 @@
1
1
  // A Docker computer's way out to the network when its spec asks for an allowlist ({ allow: [names or CIDRs] }): the
2
2
  // computer stays `--network none`, and its own egress proxy runs in a second container the provider makes, reads back
3
- // and removes with it. Moved from serve's box-egress.ts and rewritten onto the provider: the proxy no longer lives in the
4
- // process that made the computer, so the computer keeps its network when that process ends, and attach and list read it
5
- // back from Docker anywhere.
3
+ // and removes with it. The proxy does not live in the process that
4
+ // made the computer, so the computer keeps its network when that process ends, and attach and list read it back from
5
+ // Docker anywhere.
6
6
  //
7
7
  // - The volume `<computer>-egress`: a tmpfs of 1 MiB, mode 0700, owned by the computer's uid:gid. The proxy's Unix
8
8
  // socket is made in it; the computer mounts it read-only at EGRESS_MOUNT.
@@ -20,9 +20,10 @@ import { fileURLToPath } from "node:url";
20
20
  import { DEADLINE_LABEL } from "../drift.js";
21
21
  import { LISTED_PORTS, parseAllow } from "./egress-proxy.js";
22
22
  import { checkAddress } from "./egress-table.js";
23
- /** The proxy container's image: node:22.23.4-bookworm-slim, pinned to its multi-arch index digest (as serve pins its
24
- * own), so every host runs the same Node. The provider's `egress.image` replaces it. */
25
- export const EGRESS_IMAGE = "node:22.23.4-bookworm-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d";
23
+ /** The proxy container's image: node:22.23.5-trixie-slim (Node 22's November 2026 security release), pinned to its
24
+ * multi-arch index digest (amd64 and arm64 both listed), so every host runs the same Node. serve's macOS proxy pins the
25
+ * same image. The provider's `egress.image` replaces it. */
26
+ export const EGRESS_IMAGE = "node:22.23.5-trixie-slim@sha256:68c76cfad89921b927eae28ba21407475e29d0ce450afcdbe70c1532db042b64";
26
27
  /** The label the proxy container and the volume carry: the computer's name. In the provider's own namespace, which a
27
28
  * spec's labels cannot use. */
28
29
  export const EGRESS_LABEL = "agentrun.computer.egress";
package/dist/docker.d.ts CHANGED
@@ -3,7 +3,7 @@ import { type DockerHost } from "./docker/inspect.js";
3
3
  import { type EnsureImageOptions, type ImageSource } from "./docker/image.js";
4
4
  import type { KindCapabilities } from "./kinds.js";
5
5
  import { type MountKind } from "./mount.js";
6
- import { type AttachedComputer, type CallContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
6
+ import { type AttachedComputer, type CallContext, type CreateContext, type ComputerCapabilities, type ComputerConnection, type ComputerInfo, type ComputerProvider, type ComputerRef, type ComputerSpec, type NetworkPolicy, type NetworkSpec, type Refusal, type ReleaseHow } from "./provider.js";
7
7
  import { type Result } from "./result.js";
8
8
  import { type ScreenWatch, type ScreenWatchHandlers, type WatchOptions } from "./screen-watch.js";
9
9
  /**
@@ -114,9 +114,12 @@ export declare class DockerProvider implements ComputerProvider {
114
114
  /** The spec's refusals, and the host's once create, attach or host() has read it: its problems, a bind or an
115
115
  * allowlist on a host that remaps user ids, and an allowlist on a Docker host this provider does not run on. */
116
116
  check(spec: ComputerSpec): Refusal[];
117
- create(spec: ComputerSpec, { signal }?: {
118
- signal?: AbortSignal;
119
- }): Promise<Result<ComputerRef>>;
117
+ /**
118
+ * Makes a computer, once per request (provider.md, Idempotent create): context.requestId names the container
119
+ * (computerNameFor). A request Docker holds a container for already answers that one (#taken); one whose computer
120
+ * was deleted here is refused exists; a create of a request in flight here waits for the first (CreateRequests).
121
+ */
122
+ create(spec: ComputerSpec, context: CreateContext): Promise<Result<ComputerRef>>;
120
123
  /** The Docker host's architecture and enforcement (hostOf), read by docker info once per provider. */
121
124
  host({ signal }?: CallContext): Promise<Result<DockerHost>>;
122
125
  /** The live view: screen.watch on a connection of the watch's own (daemonWatch); a linux computer has no screen. */
package/dist/docker.js CHANGED
@@ -1,7 +1,6 @@
1
- // The Docker provisioner: every call through the docker CLI with execFile or spawn, never a shell. The hardening flags
2
- // and the inspect reading follow pi-transport's Docker box.
1
+ // The Docker provisioner: every call through the docker CLI with execFile or spawn, never a shell.
3
2
  import { execFile, spawn } from "node:child_process";
4
- import { randomBytes } from "node:crypto";
3
+ import { randomUUID } from "node:crypto";
5
4
  import { readFileSync, statSync } from "node:fs";
6
5
  import { resolve } from "node:path";
7
6
  import { setTimeout as sleep } from "node:timers/promises";
@@ -21,6 +20,7 @@ import { addressBytes } from "./docker/egress-table.js";
21
20
  import { checkMount, WORKSPACE } from "./mount.js";
22
21
  import { checkGpu, checkTenure, runLifetimeMs, } from "./provider.js";
23
22
  import { failFor, ok, vendorFail } from "./result.js";
23
+ import { CreateRequests, endedWords, otherSpecWords } from "./create-requests.js";
24
24
  import { daemonWatch } from "./screen-watch.js";
25
25
  import { countTested } from "./test-connection.js";
26
26
  /** This module's failures: one with code vendor names Docker. */
@@ -80,10 +80,13 @@ const HELLO_TIMEOUT_MS = 30_000;
80
80
  /** Ids a list() inspect takes at once, so its argv and output stay bounded however many computers match. */
81
81
  const INSPECT_BATCH = 50;
82
82
  /** Only the fields list() reads, in inspect's own shape: a whole inspect is kilobytes a container, and execFile's
83
- * output is capped. The user and init's command are an allowlist's read-back: its relay, and its proxy's user. */
83
+ * output is capped. The user and init's command are an allowlist's read-back: its relay, and its proxy's user.
84
+ * Docker runs the template on the inspect's JSON as a map and a missing key fails the whole inspect, so a field Docker
85
+ * leaves out when empty is read with index, which reads null: HostConfig.Mounts is absent from a container made with no
86
+ * --mount (one the label filter matches yet this provider never made), and one such container would fail the list. */
84
87
  const LIST_FORMAT = '{"Id":{{json .Id}},"Name":{{json .Name}},"State":{"Running":{{json .State.Running}}},' +
85
88
  '"Config":{"Labels":{{json .Config.Labels}},"User":{{json .Config.User}},"Cmd":{{json .Config.Cmd}}},' +
86
- '"HostConfig":{"NetworkMode":{{json .HostConfig.NetworkMode}},"Mounts":{{json .HostConfig.Mounts}}},"NetworkSettings":{"Networks":{{json .NetworkSettings.Networks}}},"Mounts":{{json .Mounts}}}';
89
+ '"HostConfig":{"NetworkMode":{{json .HostConfig.NetworkMode}},"Mounts":{{json (index .HostConfig "Mounts")}}},"NetworkSettings":{"Networks":{{json .NetworkSettings.Networks}}},"Mounts":{{json .Mounts}}}';
87
90
  /** The longest lifetime: 30 days. A computer meant to live longer is asked for again. No extend(): the deadline is a
88
91
  * container label, and a label cannot change after create. */
89
92
  const MAX_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
@@ -97,11 +100,23 @@ const FIXED = "a Docker computer's network is fixed at create; create a new comp
97
100
  const NETWORKS = 'network is required: "none", "open" or { allow: [names or CIDRs] }';
98
101
  /** How often create asks whether the egress proxy is ready. */
99
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;
100
107
  /** After a docker run cut off before its own exit: how long, at most, the leftovers are removed and looked for again,
101
108
  * how often, and for how long in a row the looks must find none of them before they count as gone (#settle). */
102
109
  const SETTLE_MS = 10_000;
103
110
  const SETTLE_EVERY_MS = 500;
104
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}}}}';
105
120
  /**
106
121
  * Why #settle could not show its leftovers gone within SETTLE_MS, in words that always name them: `there`, what its
107
122
  * last look still found; or, when the last look found none but the quiet window was not complete, every name it
@@ -120,6 +135,8 @@ const INFO_FORMAT = '{"Architecture":{{json .Architecture}},"SecurityOptions":{{
120
135
  const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
121
136
  const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
122
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);
123
140
  const nameOf = (report) => (report.Name ?? "").replace(/^\//, "");
124
141
  /** Only a container this provider made counts: its label, and a name of its making. */
125
142
  const ours = (report) => report.Config?.Labels?.[COMPUTER_LABEL] === "1" && NAME.test(nameOf(report));
@@ -135,6 +152,8 @@ export class DockerProvider {
135
152
  #desktop;
136
153
  #image;
137
154
  #egress;
155
+ /** Each create in flight, and the names of the computers this provider deleted (create-requests.ts). */
156
+ #requests = new CreateRequests();
138
157
  /** Why this provider's own interfaces are not the Docker host's, in words, or none: read once, for the first allowlist
139
158
  * with no egress.hostAddresses (#elsewhere). */
140
159
  #elsewhere;
@@ -250,7 +269,7 @@ export class DockerProvider {
250
269
  const refusals = [];
251
270
  const refuse = (field, message) => refusals.push({ field, message });
252
271
  const given = spec;
253
- const { image, lifetimeMs, network, cpus, memoryMb, pids, labels, workdir, user, mount } = given;
272
+ const { image, network, cpus, memoryMb, pids, labels, workdir, user, mount } = given;
254
273
  if (typeof image !== "string" || image.trim() === "" || image.startsWith("-")) {
255
274
  refuse("image", "an image is required, such as debian:bookworm-slim");
256
275
  }
@@ -301,11 +320,115 @@ export class DockerProvider {
301
320
  }
302
321
  return refusals;
303
322
  }
304
- 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) {
305
329
  const refusals = this.check(spec);
306
- if (refusals.length > 0)
307
- return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
308
- 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);
309
432
  const bound = spec.mount?.kind === "bind" ? spec.mount.path : undefined;
310
433
  const daemon = this.#daemon();
311
434
  if (!daemon.ok)
@@ -377,20 +500,28 @@ export class DockerProvider {
377
500
  }
378
501
  if (signal?.aborted)
379
502
  return fail("aborted", "create was aborted before docker run");
380
- 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();
381
506
  // The lifetime counts from here: what the proxy and docker run take comes out of it.
382
507
  const lifetimeFrom = Date.now();
383
508
  const deadline = new Date(lifetimeFrom + runLifetimeMs(spec)).toISOString();
384
509
  if (allow !== undefined) {
385
510
  // The proxy first, ready before the computer exists: a computer never runs with an allowlist it cannot reach.
386
- 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);
387
512
  if (!started.ok) {
388
- 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);
389
519
  const after = removed.ok ? "its proxy and volume were removed" : `its proxy and volume could not be removed (${removed.error.message})`;
390
520
  return fail(started.error.code, `${started.error.message}; the computer ${name} was never run, and ${after}`);
391
521
  }
392
522
  }
393
- 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}`];
394
525
  for (const [key, value] of Object.entries(spec.labels ?? {}))
395
526
  args.push("--label", `${key}=${value}`);
396
527
  const memoryMb = spec.memoryMb ?? DEFAULT_MEMORY_MB;
@@ -423,17 +554,32 @@ export class DockerProvider {
423
554
  args.push(spec.image, "init", "--deadline", deadline, ...(allow === undefined ? [] : [RELAY_FLAG, EGRESS_SOCKET]));
424
555
  const started = await this.#run(args, signal);
425
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
+ }
426
564
  if (!started.ok || started.value.exitCode !== 0) {
427
565
  // A run that failed or was aborted may still have made the container; an allowlist's proxy and volume go with it.
428
- 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);
429
569
  if (started.ok)
430
570
  return vendorFail("docker", `docker run failed: ${started.value.stderr.trim()}`);
431
571
  // Cut off before its own exit: the daemon may still make the computer after release looked, and then its egress
432
572
  // volume with it (#settle).
433
- const left = await this.#settle([name], allow === undefined ? [] : [egressNameOf(name)]);
573
+ const left = await this.#settle([name], allow === undefined ? [] : [egressNameOf(name)], attempt);
434
574
  const what = allow === undefined ? `the computer ${name}` : `the computer ${name}, its proxy and its volume`;
435
575
  const removed = allow === undefined ? "was removed, if Docker made it after" : "were removed, if Docker made them after";
436
- 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}`;
437
583
  return fail(started.error.code, `${started.error.message === "docker run was aborted" ? "create was aborted during docker run" : started.error.message}; ${words}`);
438
584
  }
439
585
  const ref = { id: started.value.stdout.trim(), name };
@@ -498,8 +644,12 @@ export class DockerProvider {
498
644
  * confirmed gone, in words (settleWords). A create later than that is the janitor's: sweepLeftovers takes it at the
499
645
  * next sweep, past #leftoverGraceMs, which stays the backstop.
500
646
  */
501
- async #settle(containers, volumes) {
647
+ async #settle(containers, volumes, attempt) {
502
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));
503
653
  // When the looks first found none of them in the current run of empty looks; there, what the last look found.
504
654
  let quietSince;
505
655
  // Each named as what it is: a container and a volume may share a name (the egress proxy's).
@@ -509,23 +659,24 @@ export class DockerProvider {
509
659
  let there = checked;
510
660
  while (!bound.aborted) {
511
661
  // --volumes, as release removes a computer: a late container of an image that declares a VOLUME has its own.
512
- for (const container of containers)
513
- await this.#run(["rm", "--force", "--volumes", container], bound);
514
- for (const volume of volumes)
515
- await this.#run(["volume", "rm", "--force", volume], bound);
516
- const found = containers.length === 0 ? ok([]) : await this.#inspect(containers, bound, "{{json .Name}}");
517
- 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);
518
673
  // A look the bound cut off says nothing: what the last whole look found stands.
519
674
  if (bound.aborted)
520
675
  break;
521
- // A read that fails for any reason but "no such" counts as all still there.
522
- const unread = (ran) => ran.exitCode !== 0 && ran.stderr.split("\n").some((line) => line.trim() !== "" && !/no such volume/i.test(line));
523
- const foundNames = found.ok ? found.value.map((name) => String(name).replace(/^\//, "")) : containers;
524
- const listedText = listed === undefined ? "" : listed.ok && !unread(listed.value) ? listed.value.stdout : undefined;
525
- there = [
526
- ...containers.filter((name) => foundNames.includes(name)).map(containerWords),
527
- ...volumes.filter((name) => listedText === undefined || listedText.split("\n").some((line) => line.includes(name))).map(volumeWords),
528
- ];
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)];
529
680
  if (there.length > 0)
530
681
  quietSince = undefined;
531
682
  else {
@@ -548,8 +699,10 @@ export class DockerProvider {
548
699
  * bound, until the proxy logs its ready line. A proxy that ends first fails with its own last words. The caller
549
700
  * removes whatever was made when this fails.
550
701
  */
551
- async #startEgress(name, user, deadline, allow, labels, signal) {
702
+ async #startEgress(name, user, deadline, allow, specLabels, attempt, signal) {
552
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 };
553
706
  const volume = await this.#run(egressVolumeArgs(name, user, deadline, labels), signal);
554
707
  if (!volume.ok)
555
708
  return volume;
@@ -560,7 +713,7 @@ export class DockerProvider {
560
713
  const ran = await this.#run(args, signal);
561
714
  if (!ran.ok) {
562
715
  // Cut off before its own exit: the daemon may still make the proxy after the caller's cleanup looked (#settle).
563
- const left = await this.#settle([proxy], [proxy]);
716
+ const left = await this.#settle([proxy], [proxy], attempt);
564
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}`;
565
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}`);
566
719
  }
@@ -1087,6 +1240,97 @@ export class DockerProvider {
1087
1240
  return fail("invalid", `${ref.name} is not the name of a Docker computer (computer-<12 hex digits>)`);
1088
1241
  if (how !== "stop" && how !== "delete")
1089
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) {
1090
1334
  const args = how === "stop" ? ["stop", ref.name] : ["rm", "--force", "--volumes", ref.name];
1091
1335
  const ran = await this.#run(args);
1092
1336
  if (!ran.ok)