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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +2401 -2
  4. package/box/Dockerfile +69 -0
  5. package/box/agentrun-archil +168 -0
  6. package/box/build-daytona.py +26 -0
  7. package/box/build-e2b.mjs +32 -0
  8. package/box/build-modal.py +17 -0
  9. package/dist/actions.d.ts +18 -0
  10. package/dist/actions.js +139 -0
  11. package/dist/browser.d.ts +151 -0
  12. package/dist/browser.js +305 -0
  13. package/dist/browserbase.d.ts +139 -0
  14. package/dist/browserbase.js +408 -0
  15. package/dist/child.d.ts +40 -0
  16. package/dist/child.js +127 -0
  17. package/dist/client.d.ts +22 -0
  18. package/dist/client.js +136 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/archil.d.ts +68 -0
  22. package/dist/conformance/archil.js +152 -0
  23. package/dist/conformance/browserbase.d.ts +35 -0
  24. package/dist/conformance/browserbase.js +45 -0
  25. package/dist/conformance/cases/apps.d.ts +2 -0
  26. package/dist/conformance/cases/apps.js +155 -0
  27. package/dist/conformance/cases/browser.d.ts +4 -0
  28. package/dist/conformance/cases/browser.js +105 -0
  29. package/dist/conformance/cases/drift.d.ts +2 -0
  30. package/dist/conformance/cases/drift.js +64 -0
  31. package/dist/conformance/cases/exec.d.ts +2 -0
  32. package/dist/conformance/cases/exec.js +125 -0
  33. package/dist/conformance/cases/files.d.ts +2 -0
  34. package/dist/conformance/cases/files.js +294 -0
  35. package/dist/conformance/cases/health.d.ts +2 -0
  36. package/dist/conformance/cases/health.js +71 -0
  37. package/dist/conformance/cases/index.d.ts +9 -0
  38. package/dist/conformance/cases/index.js +37 -0
  39. package/dist/conformance/cases/input.d.ts +12 -0
  40. package/dist/conformance/cases/input.js +109 -0
  41. package/dist/conformance/cases/isolation.d.ts +21 -0
  42. package/dist/conformance/cases/isolation.js +92 -0
  43. package/dist/conformance/cases/lifetime.d.ts +2 -0
  44. package/dist/conformance/cases/lifetime.js +64 -0
  45. package/dist/conformance/cases/mount.d.ts +2 -0
  46. package/dist/conformance/cases/mount.js +252 -0
  47. package/dist/conformance/cases/process.d.ts +2 -0
  48. package/dist/conformance/cases/process.js +240 -0
  49. package/dist/conformance/cases/provider.d.ts +2 -0
  50. package/dist/conformance/cases/provider.js +302 -0
  51. package/dist/conformance/cases/screen.d.ts +9 -0
  52. package/dist/conformance/cases/screen.js +230 -0
  53. package/dist/conformance/cases/settings.d.ts +57 -0
  54. package/dist/conformance/cases/settings.js +142 -0
  55. package/dist/conformance/cases/touch.d.ts +2 -0
  56. package/dist/conformance/cases/touch.js +117 -0
  57. package/dist/conformance/cases/util.d.ts +7 -0
  58. package/dist/conformance/cases/util.js +8 -0
  59. package/dist/conformance/cdp.d.ts +13 -0
  60. package/dist/conformance/cdp.js +88 -0
  61. package/dist/conformance/cli.d.ts +29 -0
  62. package/dist/conformance/cli.js +231 -0
  63. package/dist/conformance/daytona-sweep.d.ts +18 -0
  64. package/dist/conformance/daytona-sweep.js +118 -0
  65. package/dist/conformance/daytona.d.ts +83 -0
  66. package/dist/conformance/daytona.js +107 -0
  67. package/dist/conformance/docker.d.ts +38 -0
  68. package/dist/conformance/docker.js +70 -0
  69. package/dist/conformance/drift-daemon.d.ts +8 -0
  70. package/dist/conformance/drift-daemon.js +41 -0
  71. package/dist/conformance/e2b-diagnose.d.ts +16 -0
  72. package/dist/conformance/e2b-diagnose.js +61 -0
  73. package/dist/conformance/e2b-sweep.d.ts +18 -0
  74. package/dist/conformance/e2b-sweep.js +125 -0
  75. package/dist/conformance/e2b.d.ts +74 -0
  76. package/dist/conformance/e2b.js +111 -0
  77. package/dist/conformance/fixture.d.ts +65 -0
  78. package/dist/conformance/fixture.js +98 -0
  79. package/dist/conformance/index.d.ts +8 -0
  80. package/dist/conformance/index.js +8 -0
  81. package/dist/conformance/kernel.d.ts +31 -0
  82. package/dist/conformance/kernel.js +40 -0
  83. package/dist/conformance/kind.d.ts +23 -0
  84. package/dist/conformance/kind.js +58 -0
  85. package/dist/conformance/modal-sweep.d.ts +22 -0
  86. package/dist/conformance/modal-sweep.js +190 -0
  87. package/dist/conformance/modal.d.ts +69 -0
  88. package/dist/conformance/modal.js +76 -0
  89. package/dist/conformance/orgo.d.ts +41 -0
  90. package/dist/conformance/orgo.js +69 -0
  91. package/dist/conformance/phone-harness.d.ts +61 -0
  92. package/dist/conformance/phone-harness.js +241 -0
  93. package/dist/conformance/png.d.ts +16 -0
  94. package/dist/conformance/png.js +132 -0
  95. package/dist/conformance/report.d.ts +2 -0
  96. package/dist/conformance/report.js +86 -0
  97. package/dist/conformance/runner.d.ts +11 -0
  98. package/dist/conformance/runner.js +585 -0
  99. package/dist/conformance/tar.d.ts +13 -0
  100. package/dist/conformance/tar.js +105 -0
  101. package/dist/conformance/types.d.ts +257 -0
  102. package/dist/conformance/types.js +24 -0
  103. package/dist/daemon-copy.d.ts +40 -0
  104. package/dist/daemon-copy.js +259 -0
  105. package/dist/daytona.d.ts +178 -0
  106. package/dist/daytona.js +1484 -0
  107. package/dist/desktop.d.ts +24 -0
  108. package/dist/desktop.js +68 -0
  109. package/dist/docker/egress-main.d.ts +1 -0
  110. package/dist/docker/egress-main.js +68 -0
  111. package/dist/docker/egress-proxy.d.ts +53 -0
  112. package/dist/docker/egress-proxy.js +450 -0
  113. package/dist/docker/egress-table.d.ts +39 -0
  114. package/dist/docker/egress-table.js +197 -0
  115. package/dist/docker/egress.d.ts +109 -0
  116. package/dist/docker/egress.js +318 -0
  117. package/dist/docker/image.d.ts +49 -0
  118. package/dist/docker/image.js +302 -0
  119. package/dist/docker/stage.d.ts +21 -0
  120. package/dist/docker/stage.js +290 -0
  121. package/dist/docker/volume.d.ts +24 -0
  122. package/dist/docker/volume.js +67 -0
  123. package/dist/docker.d.ts +150 -0
  124. package/dist/docker.js +1200 -0
  125. package/dist/drift.d.ts +200 -0
  126. package/dist/drift.js +416 -0
  127. package/dist/e2b.d.ts +335 -0
  128. package/dist/e2b.js +1515 -0
  129. package/dist/entry.d.ts +2 -0
  130. package/dist/entry.js +24 -0
  131. package/dist/files.d.ts +50 -0
  132. package/dist/files.js +208 -0
  133. package/dist/index.d.ts +27 -0
  134. package/dist/index.js +26 -0
  135. package/dist/isolation.d.ts +29 -0
  136. package/dist/isolation.js +71 -0
  137. package/dist/janitor.d.ts +50 -0
  138. package/dist/janitor.js +135 -0
  139. package/dist/kernel.d.ts +113 -0
  140. package/dist/kernel.js +358 -0
  141. package/dist/kinds.d.ts +79 -0
  142. package/dist/kinds.js +133 -0
  143. package/dist/labels.d.ts +23 -0
  144. package/dist/labels.js +50 -0
  145. package/dist/modal.d.ts +302 -0
  146. package/dist/modal.js +1374 -0
  147. package/dist/mount-archil.d.ts +164 -0
  148. package/dist/mount-archil.js +471 -0
  149. package/dist/mount.d.ts +57 -0
  150. package/dist/mount.js +104 -0
  151. package/dist/orgo-channel.d.ts +96 -0
  152. package/dist/orgo-channel.js +391 -0
  153. package/dist/orgo.d.ts +139 -0
  154. package/dist/orgo.js +1006 -0
  155. package/dist/phone-harness.d.ts +185 -0
  156. package/dist/phone-harness.js +1420 -0
  157. package/dist/processes.d.ts +24 -0
  158. package/dist/processes.js +40 -0
  159. package/dist/protocol.d.ts +729 -0
  160. package/dist/protocol.js +54 -0
  161. package/dist/provider.d.ts +245 -0
  162. package/dist/provider.js +37 -0
  163. package/dist/providers.d.ts +68 -0
  164. package/dist/providers.js +25 -0
  165. package/dist/result.d.ts +15 -0
  166. package/dist/result.js +2 -0
  167. package/dist/screen-watch.d.ts +150 -0
  168. package/dist/screen-watch.js +490 -0
  169. package/dist/test-connection.d.ts +17 -0
  170. package/dist/test-connection.js +26 -0
  171. package/dist/wait.d.ts +23 -0
  172. package/dist/wait.js +65 -0
  173. package/package.json +62 -4
package/dist/docker.js ADDED
@@ -0,0 +1,1200 @@
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.
3
+ import { execFile, spawn } from "node:child_process";
4
+ import { randomBytes } from "node:crypto";
5
+ import { readFileSync, statSync } from "node:fs";
6
+ import { resolve } from "node:path";
7
+ import { setTimeout as sleep } from "node:timers/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ import { DaemonClient } from "./client.js";
10
+ import { daemonCopy, defaultDaemonCache } from "./daemon-copy.js";
11
+ import { DESKTOP_GROUPS, desktopOf, startDisplay } from "./desktop.js";
12
+ import { COMPUTER_LABEL, CPU_PERIOD_US, DAEMON_DIR_IN_COMPUTER, DAEMON_IN_COMPUTER, DEADLINE_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, DEFAULT_PIDS, drift, egressShaped, helloDrift, hostOf, inspectDrift, mountOf, networkOf, samePolicy, tmpfsOf, WORK, } from "./drift.js";
13
+ import { DOCKER_RECIPE, ensureImage, imageSourceProblem } from "./docker/image.js";
14
+ import { ALLOW_PORTS, allowOf, containerSigns, EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_READY_MS, EGRESS_SOCKET, egressCode, egressCodeProblem, egressNameOf, egressRunArgs, egressVolumeArgs, hostAddresses, MAX_ALLOW, policyWords, RELAY_FLAG, } from "./docker/egress.js";
15
+ import { daemonStage, daemonVerified, egressStage, egressStaged } from "./docker/stage.js";
16
+ import { EGRESS_READY } from "./docker/egress-proxy.js";
17
+ import { OLD_ENGINE, outsideWords, subpathOf, VOLUME_SUBPATH_ENGINE, volumeMount, volumeOf } from "./docker/volume.js";
18
+ import { addressBytes } from "./docker/egress-table.js";
19
+ import { checkMount, WORKSPACE } from "./mount.js";
20
+ import { checkLifetime, } from "./provider.js";
21
+ import { fail, ok } from "./result.js";
22
+ import { daemonWatch } from "./screen-watch.js";
23
+ import { countTested } from "./test-connection.js";
24
+ /** The mount kinds a Docker computer takes, as capabilities().mount declares them: a bind of a folder on this host. */
25
+ export const MOUNT = ["bind"];
26
+ /** The machine kind and groups of each configuration: a linux computer, and one made with the desktop option. */
27
+ export const CAPABILITIES = [
28
+ { kind: "linux", groups: ["exec", "files", "processes"] },
29
+ { kind: "desktop", groups: ["exec", "files", "processes", ...DESKTOP_GROUPS] },
30
+ ];
31
+ /**
32
+ * Docker's architecture as `docker version` reports it (amd64, arm64), within timeoutMs, or an error in words. The docker
33
+ * CLI runs with this process's environment, as every call of the provider does, so it asks the Docker the provider uses.
34
+ */
35
+ export function dockerArch({ docker = "docker", timeoutMs = 30_000 } = {}) {
36
+ return new Promise((resolve, reject) => {
37
+ execFile(docker, ["version", "--format", "{{.Server.Arch}}"], { encoding: "utf8", timeout: timeoutMs, killSignal: "SIGKILL" }, (error, stdout, stderr) => {
38
+ if (!error)
39
+ return resolve(stdout.trim());
40
+ const killed = error.killed === true && error.signal === "SIGKILL";
41
+ const why = killed ? `${docker} version did not answer within ${timeoutMs / 1000} s, so it was killed` : (stderr.trim() || error.message).split("\n")[0];
42
+ reject(new Error(`cannot ask Docker its architecture (${docker} version): ${why}`));
43
+ });
44
+ });
45
+ }
46
+ /**
47
+ * A DockerProvider from its options alone; it reads no environment. Without options.daemonPath it asks Docker its
48
+ * architecture and takes this package's daemon for it, and says when that daemon is not built. The image is an option
49
+ * too (default the provider's own recipe): no image name is read from the environment.
50
+ */
51
+ export async function create(options = {}) {
52
+ const { timeoutMs, ...given } = options;
53
+ let daemonPath = given.daemonPath || undefined;
54
+ if (daemonPath === undefined) {
55
+ const arch = await dockerArch({ ...(given.docker ? { docker: given.docker } : {}), ...(timeoutMs === undefined ? {} : { timeoutMs }) });
56
+ daemonPath = fileURLToPath(new URL(`./computerd-linux-${arch}`, import.meta.url));
57
+ if (fileMode(daemonPath) === undefined)
58
+ throw new Error(`no daemon for Docker's ${arch} at ${daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer`);
59
+ }
60
+ return new DockerProvider({ ...given, daemonPath });
61
+ }
62
+ /** The conformance CLI's module for Docker: the drifted twin. */
63
+ export const conformance = () => import("./conformance/docker.js");
64
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
65
+ const NAME = /^computer-[0-9a-f]{12}$/;
66
+ /** A container id, whole or its first 12 or more hex digits. */
67
+ const ID = /^[0-9a-f]{12,64}$/;
68
+ /** A user in numbers, uid or uid:gid; (uid_t)-1 is no user. */
69
+ const USER = /^(\d+)(?::(\d+))?$/;
70
+ const MAX_ID = 4_294_967_294;
71
+ const USER_FORM = "a uid or uid:gid in numbers, such as 1000:1000; a name is refused, since the image may not have it";
72
+ /** The kernel's PID_MAX_LIMIT: a larger --pids-limit fails the create. */
73
+ const MAX_PIDS = 4_194_304;
74
+ /** Docker's least --memory. */
75
+ const MIN_MEMORY_MB = 6;
76
+ const HELLO_TIMEOUT_MS = 30_000;
77
+ /** Ids a list() inspect takes at once, so its argv and output stay bounded however many computers match. */
78
+ const INSPECT_BATCH = 50;
79
+ /** Only the fields list() reads, in inspect's own shape: a whole inspect is kilobytes a container, and execFile's
80
+ * output is capped. The user and init's command are an allowlist's read-back: its relay, and its proxy's user. */
81
+ const LIST_FORMAT = '{"Id":{{json .Id}},"Name":{{json .Name}},"State":{"Running":{{json .State.Running}}},' +
82
+ '"Config":{"Labels":{{json .Config.Labels}},"User":{{json .Config.User}},"Cmd":{{json .Config.Cmd}}},' +
83
+ '"HostConfig":{"NetworkMode":{{json .HostConfig.NetworkMode}},"Mounts":{{json .HostConfig.Mounts}}},"NetworkSettings":{"Networks":{{json .NetworkSettings.Networks}}},"Mounts":{{json .Mounts}}}';
84
+ /** The longest lifetime: 30 days. A computer meant to live longer is asked for again. No extend(): the deadline is a
85
+ * container label, and a label cannot change after create. */
86
+ const MAX_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
87
+ const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "cpus", "memoryMb", "pids", "labels", "workdir", "user", "mount"]);
88
+ const NUL = "a NUL byte cannot be passed to docker run";
89
+ /** What --mount's comma-separated fields cannot hold in a source path. */
90
+ const MOUNT_UNSAFE = /[,"\r\n]/;
91
+ /** Docker cannot move a container with no network onto one, nor take one off a network without a restart; an allowlist
92
+ * needs its volume mounted at create. */
93
+ const FIXED = "a Docker computer's network is fixed at create; create a new computer";
94
+ const NETWORKS = 'network is required: "none", "open" or { allow: [names or CIDRs] }';
95
+ /** How often create asks whether the egress proxy is ready. */
96
+ const EGRESS_POLL_MS = 100;
97
+ /** Only the fields hostOf reads, as JSON. */
98
+ const INFO_FORMAT = '{"Architecture":{{json .Architecture}},"SecurityOptions":{{json .SecurityOptions}},"MemoryLimit":{{json .MemoryLimit}},' +
99
+ '"SwapLimit":{{json .SwapLimit}},"PidsLimit":{{json .PidsLimit}},"CPUCfsQuota":{{json .CPUCfsQuota}},"CPUCfsPeriod":{{json .CPUCfsPeriod}},' +
100
+ '"ServerVersion":{{json .ServerVersion}}}';
101
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
102
+ const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
103
+ const noSuchContainer = (stderr) => /no such container/i.test(stderr);
104
+ const nameOf = (report) => (report.Name ?? "").replace(/^\//, "");
105
+ /** Only a container this provider made counts: its label, and a name of its making. */
106
+ const ours = (report) => report.Config?.Labels?.[COMPUTER_LABEL] === "1" && NAME.test(nameOf(report));
107
+ export class DockerProvider {
108
+ id = "docker";
109
+ version = VERSION;
110
+ #daemonPath;
111
+ #daemonCache;
112
+ /** The volume option: the daemon's staged directory and a run folder are its subpaths (src/docker/volume.ts). */
113
+ #volume;
114
+ #docker;
115
+ #user;
116
+ #desktop;
117
+ #image;
118
+ #egress;
119
+ /** Why this provider's own interfaces are not the Docker host's, in words, or none: read once, for the first allowlist
120
+ * with no egress.hostAddresses (#elsewhere). */
121
+ #elsewhere;
122
+ /** Where the egress proxy's code is built: this package's own build. */
123
+ #built = egressCode();
124
+ /** With the volume option: the built code's staged copy below the volume's root, once create has staged it. */
125
+ #staged;
126
+ /**
127
+ * Where the egress proxy's code is, as the proxy mounts it: this package's build, or, with the volume option, its
128
+ * staged copy below the volume's root (src/docker/stage.ts), read without writing for a read-back. A copy whose
129
+ * place cannot be read (the build is gone) is the volume's subpaths, unnamed, which the read-back holds by kind alone.
130
+ */
131
+ get #code() {
132
+ const volume = this.#volume;
133
+ if (volume === undefined)
134
+ return this.#built;
135
+ const found = egressStaged(this.#built, this.#daemonCache, volume);
136
+ // What create staged is what it runs; a read-back takes any verified copy (egressStaged's accepts) either way.
137
+ if (this.#staged?.volume !== undefined)
138
+ return { ...this.#staged, volume: { ...this.#staged.volume, ...(found.ok && found.value.volume?.accepts ? { accepts: found.value.volume.accepts } : {}) } };
139
+ return found.ok ? found.value : { ...this.#built, volume: { name: volume.name } };
140
+ }
141
+ /** The host as docker info first read it: a host's enforcement does not change under a running provider. */
142
+ #host;
143
+ constructor({ daemonPath, daemonCache, docker = "docker", user, desktop, egress, image = { recipe: DOCKER_RECIPE }, volume }) {
144
+ this.#daemonPath = resolve(daemonPath);
145
+ this.#daemonCache = resolve(daemonCache ?? defaultDaemonCache());
146
+ this.#volume = volume === undefined ? undefined : volumeOf(volume);
147
+ // The daemon's copy is mounted from the volume, so it must be there: the caller puts daemonCache below the root.
148
+ if (this.#volume !== undefined && subpathOf(this.#volume, this.#daemonCache, { orRoot: true }) === undefined) {
149
+ throw new Error(`${outsideWords(this.#volume, this.#daemonCache, "the provider's daemonCache")}: pass a daemonCache below it`);
150
+ }
151
+ this.#docker = docker;
152
+ const unusable = imageSourceProblem(image);
153
+ if (unusable !== undefined)
154
+ throw new Error(`the provider's image: ${unusable}`);
155
+ this.#image = image;
156
+ this.#desktop = desktop === undefined ? undefined : desktopOf(desktop);
157
+ this.#egress = egressOptionsOf(egress ?? {});
158
+ const given = user === undefined ? defaultUser() : userOf(user);
159
+ if (given === undefined)
160
+ throw new Error(`the provider's user ${JSON.stringify(user)} must be ${USER_FORM}`);
161
+ if (given.startsWith("0:"))
162
+ throw new Error(`the provider's user ${user} is root; a computer runs as root only when its spec asks for user "0"`);
163
+ if (given.endsWith(":0")) {
164
+ throw new Error(`the provider's user ${user} is in root's group (gid 0); a computer is in group 0 only when its spec asks, such as user "${given}"`);
165
+ }
166
+ this.#user = given;
167
+ }
168
+ /** The uid:gid a computer runs as when its spec names no user: the user a bound run folder must be writable by. */
169
+ get user() {
170
+ return this.#user;
171
+ }
172
+ capabilities() {
173
+ return {
174
+ kind: this.#desktop ? "desktop" : "linux",
175
+ lifetime: "janitor",
176
+ network: ["none", "open", "allow"],
177
+ allow: { domains: { max: MAX_ALLOW, ports: [...ALLOW_PORTS] }, cidrs: { max: MAX_ALLOW, ports: [...ALLOW_PORTS] }, mixed: true },
178
+ networkReadBack: true,
179
+ isolation: "container",
180
+ os: "linux",
181
+ daemon: "pid1",
182
+ groups: ["exec", "files", "processes", ...(this.#desktop ? DESKTOP_GROUPS : [])],
183
+ maxLifetimeMs: MAX_LIFETIME_MS,
184
+ user: ["root", "uid"],
185
+ release: ["stop", "delete"],
186
+ stopDeletes: false,
187
+ mount: [...MOUNT],
188
+ };
189
+ }
190
+ /**
191
+ * The provider's image ready in Docker, and its tag for create's spec.image: built from its recipe, or pulled, when
192
+ * Docker has none; one inspect when it has. Concurrent calls in one process share one build (ensureImage).
193
+ */
194
+ image(options = {}) {
195
+ return ensureImage(this.#image, { ...options, docker: this.#docker });
196
+ }
197
+ /** The spec's refusals, and the host's once create, attach or host() has read it: its problems, a bind or an
198
+ * allowlist on a host that remaps user ids, and an allowlist on a Docker host this provider does not run on. */
199
+ check(spec) {
200
+ const host = this.#host;
201
+ const remapped = host?.remap !== undefined && spec?.mount?.kind === "bind" ? [{ field: "mount", message: remapWords(host.remap, String(spec.mount.path)) }] : [];
202
+ const allowed = [];
203
+ if (isAllow(spec?.network)) {
204
+ if (host?.remap !== undefined)
205
+ allowed.push({ field: "network", message: remapAllowWords(host.remap) });
206
+ if (typeof this.#elsewhere === "string" && this.#egress.hostAddresses === undefined)
207
+ allowed.push({ field: "network", message: elsewhereWords(this.#elsewhere) });
208
+ }
209
+ return [...this.#checkSpec(spec), ...remapped, ...allowed, ...this.#volumeRefusals(spec, host), ...(host?.problems ?? []).map((message) => ({ field: "host", message }))];
210
+ }
211
+ /** With the volume option: a run folder not below the volume's root, and, once the host is read, an engine that
212
+ * cannot mount a volume's subpath. */
213
+ #volumeRefusals(spec, host) {
214
+ const volume = this.#volume;
215
+ if (volume === undefined)
216
+ return [];
217
+ const refusals = [];
218
+ const path = spec?.mount?.kind === "bind" ? spec.mount.path : undefined;
219
+ if (typeof path === "string" && subpathOf(volume, path) === undefined)
220
+ refusals.push({ field: "mount", message: outsideWords(volume, path, "mount.path") });
221
+ if (host !== undefined && (host.engine === undefined || host.engine < VOLUME_SUBPATH_ENGINE)) {
222
+ refusals.push({ field: "host", message: `${OLD_ENGINE} (this host's engine reads ${host.engine ?? "no version"})` });
223
+ }
224
+ return refusals;
225
+ }
226
+ #checkSpec(spec) {
227
+ const refusals = [];
228
+ const refuse = (field, message) => refusals.push({ field, message });
229
+ const given = spec;
230
+ const { image, lifetimeMs, network, cpus, memoryMb, pids, labels, workdir, user, mount } = given;
231
+ if (typeof image !== "string" || image.trim() === "" || image.startsWith("-")) {
232
+ refuse("image", "an image is required, such as debian:bookworm-slim");
233
+ }
234
+ else if (image.includes("\0"))
235
+ refuse("image", NUL);
236
+ refusals.push(...checkLifetime(lifetimeMs, this.capabilities()));
237
+ if (typeof network === "object" && network !== null && "allow" in network) {
238
+ const allow = allowOf(network.allow);
239
+ if ("problem" in allow)
240
+ refuse("network", allow.problem);
241
+ }
242
+ else if (network !== "none" && network !== "open")
243
+ refuse("network", NETWORKS);
244
+ if (cpus !== undefined && !(isNumber(cpus) && cpus >= 0.01))
245
+ refuse("cpus", "cpus must be a number of CPUs of at least 0.01");
246
+ if (memoryMb !== undefined && !(isWhole(memoryMb) && memoryMb >= MIN_MEMORY_MB)) {
247
+ refuse("memoryMb", `memoryMb must be a whole number of MiB, at least ${MIN_MEMORY_MB}`);
248
+ }
249
+ if (pids !== undefined && !(isWhole(pids) && pids > 0 && pids <= MAX_PIDS)) {
250
+ refuse("pids", `pids must be a whole number from 1 to ${MAX_PIDS}`);
251
+ }
252
+ if (labels !== undefined) {
253
+ const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
254
+ const bad = entries === undefined ? "labels must map names to strings" : entries.map(([key, value]) => labelProblem(key, value)).find(Boolean);
255
+ if (bad)
256
+ refuse("labels", bad);
257
+ }
258
+ if (workdir !== undefined && !(typeof workdir === "string" && workdir.startsWith("/"))) {
259
+ refuse("workdir", "workdir must be an absolute path in the computer");
260
+ }
261
+ else if (workdir?.includes("\0"))
262
+ refuse("workdir", NUL);
263
+ if (user !== undefined && userOf(user) === undefined)
264
+ refuse("user", `user must be ${USER_FORM}`);
265
+ const mounts = checkMount(mount, this.capabilities().mount);
266
+ refusals.push(...mounts);
267
+ const path = mount?.path;
268
+ if (mounts.length === 0 && typeof path === "string" && MOUNT_UNSAFE.test(path)) {
269
+ refuse("mount", `mount.path ${JSON.stringify(path)}: a Docker mount cannot hold a comma, a double quote or a line break in its path`);
270
+ }
271
+ for (const [field, value] of Object.entries(given)) {
272
+ if (!SPEC_FIELDS.has(field) && value !== undefined)
273
+ refuse(field, `a Docker computer does not support ${field}`);
274
+ }
275
+ return refusals;
276
+ }
277
+ async create(spec, { signal } = {}) {
278
+ const refusals = this.check(spec);
279
+ if (refusals.length > 0)
280
+ return fail("refused", refusals.map(({ field, message }) => `${field}: ${message}`).join("; "));
281
+ const user = userOf(spec.user) ?? this.#user;
282
+ const bound = spec.mount?.kind === "bind" ? spec.mount.path : undefined;
283
+ const daemon = this.#daemon();
284
+ if (!daemon.ok)
285
+ return daemon;
286
+ // How the daemon's copy and the run's folder are mounted, known before anything is made.
287
+ // With the volume option the daemon's staged directory is mounted at /opt/agentrun, its computerd at
288
+ // DAEMON_IN_COMPUTER as on every computer.
289
+ const daemonMount = this.#mountOf(daemon.value, this.#volume === undefined ? DAEMON_IN_COMPUTER : DAEMON_DIR_IN_COMPUTER, true);
290
+ if (!daemonMount.ok)
291
+ return daemonMount;
292
+ const folder = bound === undefined ? undefined : this.#mountOf(bound, WORKSPACE, false);
293
+ if (folder !== undefined && !folder.ok)
294
+ return folder;
295
+ const folderMount = folder?.value;
296
+ // An allowlist: the list as the proxy reads it, and the proxy's code, built.
297
+ const allow = typeof spec.network === "object" ? allowOf(spec.network.allow).list : undefined;
298
+ if (allow !== undefined) {
299
+ // With the volume option, the code is staged below the volume's root, where the Docker daemon can mount it from:
300
+ // the copy (0755 directories, 0644 files) is what the computer's user must read.
301
+ if (this.#volume !== undefined) {
302
+ const staged = egressStage(this.#built, this.#daemonCache, this.#volume);
303
+ if (!staged.ok)
304
+ return staged;
305
+ this.#staged = staged.value;
306
+ }
307
+ const unbuilt = egressCodeProblem(this.#code, user);
308
+ if (unbuilt !== undefined)
309
+ return fail("not_found", unbuilt);
310
+ }
311
+ if (signal?.aborted)
312
+ return fail("aborted", "create was aborted before Docker was called");
313
+ const host = await this.host({ signal });
314
+ if (!host.ok)
315
+ return host;
316
+ if (host.value.problems.length > 0)
317
+ return fail("refused", `host: ${host.value.problems.join("; ")}`);
318
+ // With the volume option, an engine that cannot mount a volume's subpath, now that the host is read.
319
+ const engine = this.#volumeRefusals(spec, host.value).filter(({ field }) => field === "host");
320
+ if (engine.length > 0)
321
+ return fail("refused", engine.map(({ field, message }) => `${field}: ${message}`).join("; "));
322
+ // Under remapped ids the egress volume and the proxy's code belong to host ids the computer's user is not.
323
+ if (allow !== undefined && host.value.remap !== undefined)
324
+ return fail("refused", `network: ${remapAllowWords(host.value.remap)}`);
325
+ // The proxy refuses the Docker host's own addresses only when it knows them: this machine's, when it is that host.
326
+ if (allow !== undefined && this.#egress.hostAddresses === undefined) {
327
+ const elsewhere = await this.#elsewhereOf(signal);
328
+ if (!elsewhere.ok)
329
+ return elsewhere;
330
+ if (elsewhere.value !== null)
331
+ return fail("refused", `network: ${elsewhereWords(elsewhere.value)}`);
332
+ }
333
+ if (bound !== undefined) {
334
+ // Under remapped ids the folder's owner on the host is not the computer's user: refuse, never guess the mapping.
335
+ if (host.value.remap !== undefined)
336
+ return fail("refused", `mount: ${remapWords(host.value.remap, bound)}`);
337
+ // The run folder is bound as it is: the computer's user, with no capabilities, must be able to write it.
338
+ const unwritable = folderProblem(bound, user);
339
+ if (unwritable !== undefined)
340
+ return fail("refused", `mount: ${unwritable}`);
341
+ }
342
+ if (allow !== undefined) {
343
+ // Both images on the host before the volume is made, so nothing from the volume to the computer pulls: the
344
+ // sweep takes a proxy with no computer past its grace for a create that died (#leftoverGraceMs).
345
+ for (const image of new Set([spec.image, this.#egress.image])) {
346
+ const pulled = await this.#pull(image, signal);
347
+ if (!pulled.ok)
348
+ return pulled;
349
+ }
350
+ }
351
+ if (signal?.aborted)
352
+ return fail("aborted", "create was aborted before docker run");
353
+ const name = `computer-${randomBytes(6).toString("hex")}`;
354
+ // The lifetime counts from here: what the proxy and docker run take comes out of it.
355
+ const lifetimeFrom = Date.now();
356
+ const deadline = new Date(lifetimeFrom + spec.lifetimeMs).toISOString();
357
+ if (allow !== undefined) {
358
+ // The proxy first, ready before the computer exists: a computer never runs with an allowlist it cannot reach.
359
+ const started = await this.#startEgress(name, user, deadline, allow, spec.labels ?? {}, signal);
360
+ if (!started.ok) {
361
+ const removed = await this.release({ id: name, name }, "delete");
362
+ const after = removed.ok ? "its proxy and volume were removed" : `its proxy and volume could not be removed (${removed.error.message})`;
363
+ return fail(started.error.code, `${started.error.message}; the computer ${name} was never run, and ${after}`);
364
+ }
365
+ }
366
+ const args = ["run", "--detach", "--name", name, "--label", `${COMPUTER_LABEL}=1`, "--label", `${DEADLINE_LABEL}=${deadline}`];
367
+ for (const [key, value] of Object.entries(spec.labels ?? {}))
368
+ args.push("--label", `${key}=${value}`);
369
+ const memoryMb = spec.memoryMb ?? DEFAULT_MEMORY_MB;
370
+ args.push("--user", user, "--env", `HOME=${WORK}`);
371
+ if (this.#desktop)
372
+ args.push("--env", `DISPLAY=${this.#desktop.display}`);
373
+ for (const [path, options] of Object.entries(tmpfsOf(user, memoryMb)))
374
+ args.push("--tmpfs", `${path}:${options}`);
375
+ args.push("--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", String(spec.pids ?? DEFAULT_PIDS));
376
+ // Not the daemon's defaults, which a host may set to shareable IPC or, on cgroup v1, the host's cgroup namespace.
377
+ args.push("--ipc", "private", "--cgroupns", "private");
378
+ // An allowlist's computer has no network either: its one way out is the proxy's socket.
379
+ args.push("--network", spec.network === "open" ? "bridge" : "none");
380
+ args.push("--cpu-period", String(CPU_PERIOD_US), "--cpu-quota", String(Math.round((spec.cpus ?? DEFAULT_CPUS) * CPU_PERIOD_US)));
381
+ // Memory and swap together are the memory: swap never adds to it.
382
+ const memory = `${memoryMb}m`;
383
+ args.push("--memory", memory, "--memory-swap", memory);
384
+ // The daemon's copy, read-only, and the run's folder, read-write at /workspace (HOME and the default workdir stay
385
+ // /work): binds of this host's paths, or, with the volume option, the volume's subpaths.
386
+ args.push("--mount", daemonMount.value, "--entrypoint", DAEMON_IN_COMPUTER);
387
+ if (folderMount !== undefined)
388
+ args.push("--mount", folderMount);
389
+ // The proxy's volume, read-only: the computer reaches its socket and cannot replace it. Its image was pulled before
390
+ // the volume was made, so this run never pulls.
391
+ if (allow !== undefined)
392
+ args.push("--mount", `type=volume,src=${egressNameOf(name)},dst=${EGRESS_MOUNT},readonly`, "--pull", "never");
393
+ args.push("--workdir", spec.workdir ?? WORK);
394
+ // PID 1 ends the computer at the deadline the label holds, so a computer the janitor misses still stops. With an
395
+ // allowlist it relays its loopback port 3128 to the proxy's socket, and names that port as every program's proxy.
396
+ args.push(spec.image, "init", "--deadline", deadline, ...(allow === undefined ? [] : [RELAY_FLAG, EGRESS_SOCKET]));
397
+ const started = await this.#run(args, signal);
398
+ const ranMs = Date.now() - lifetimeFrom;
399
+ if (!started.ok || started.value.exitCode !== 0) {
400
+ // A run that failed or was aborted may still have made the container; an allowlist's proxy and volume go with it.
401
+ await this.release({ id: name, name }, "delete");
402
+ return started.ok ? fail("docker", `docker run failed: ${started.value.stderr.trim()}`) : started;
403
+ }
404
+ const ref = { id: started.value.stdout.trim(), name };
405
+ // From here the computer exists: every step takes the caller's signal, and an abort deletes the computer.
406
+ const inspected = await this.#inspect([name], signal);
407
+ if (signal?.aborted)
408
+ return this.#abandon(ref);
409
+ const report = inspected.ok ? inspected.value[0] : undefined;
410
+ const state = report?.State;
411
+ if (state?.Running !== true) {
412
+ await this.release(ref, "delete");
413
+ // Init exits 0 at its deadline: one that passed before docker run finished is a lifetime the host's start ate.
414
+ if (state?.ExitCode === 0 && Date.now() >= lifetimeFrom + spec.lifetimeMs) {
415
+ return fail("timeout", `the computer ${name}'s lifetime of ${spec.lifetimeMs / 1000} s ended before docker run finished (it took ${Math.round(ranMs / 100) / 10} s), so init ended it and it was removed`);
416
+ }
417
+ const why = state ? `status ${state.Status}, exit code ${state.ExitCode}${state.Error ? `: ${state.Error}` : ""}` : "it could not be inspected";
418
+ return fail("docker", `the computer ${name} was not running after its start (${why}), so it was removed`);
419
+ }
420
+ if (this.#desktop) {
421
+ const shown = await this.#startDisplay(ref, this.#desktop, signal);
422
+ if (signal?.aborted)
423
+ return this.#abandon(ref);
424
+ if (!shown.ok) {
425
+ const removed = await this.release(ref, "delete");
426
+ const after = removed.ok ? "was deleted" : `could not be deleted (${removed.error.message})`;
427
+ return fail(shown.error.code, `the computer ${name} ${after}: ${shown.error.message}`);
428
+ }
429
+ }
430
+ const checked = await this.#check(spec, ref, report, host.value, deadline, user, daemon.value, signal);
431
+ // Fail closed: no create returns ok once its signal has aborted.
432
+ if (signal?.aborted)
433
+ return this.#abandon(ref);
434
+ if (checked.ok)
435
+ return ok(ref);
436
+ // Fail closed: a computer that is not what was declared, or that cannot show it is, does not outlive create.
437
+ const removed = await this.release(ref, "delete");
438
+ const after = removed.ok ? "was deleted" : `could not be deleted (${removed.error.message})`;
439
+ return fail(checked.error.code, `the computer ${name} ${after}: ${checked.error.message}`);
440
+ }
441
+ /** Makes sure `image` is on the Docker host: docker image inspect, and docker pull when it is not there. */
442
+ async #pull(image, signal) {
443
+ const aborted = () => fail("aborted", `create was aborted while it looked for or pulled the image ${image}; nothing was made`);
444
+ const found = await this.#run(["image", "inspect", "--format", "{{.Id}}", image], signal);
445
+ if (!found.ok)
446
+ return signal?.aborted ? aborted() : found;
447
+ if (found.value.exitCode === 0)
448
+ return ok(undefined);
449
+ const pulled = await this.#run(["pull", image], signal);
450
+ if (!pulled.ok)
451
+ return signal?.aborted ? aborted() : pulled;
452
+ if (pulled.value.exitCode !== 0)
453
+ return fail("docker", `docker pull ${image} failed, so nothing was made: ${pulled.value.stderr.trim()}`);
454
+ return ok(undefined);
455
+ }
456
+ /** Deletes a computer whose create was aborted after docker run; the delete itself is not signalled. */
457
+ async #abandon(ref) {
458
+ const removed = await this.release(ref, "delete");
459
+ const after = removed.ok ? "was deleted" : `could not be deleted (${removed.error.message})`;
460
+ return fail("aborted", `create was aborted after docker run; the computer ${ref.name} ${after}`);
461
+ }
462
+ /**
463
+ * Makes computer `name`'s egress volume and proxy container (src/docker/egress.ts) and waits, within the provider's
464
+ * bound, until the proxy logs its ready line. A proxy that ends first fails with its own last words. The caller
465
+ * removes whatever was made when this fails.
466
+ */
467
+ async #startEgress(name, user, deadline, allow, labels, signal) {
468
+ const proxy = egressNameOf(name);
469
+ const volume = await this.#run(egressVolumeArgs(name, user, deadline, labels), signal);
470
+ if (!volume.ok)
471
+ return volume;
472
+ if (volume.value.exitCode !== 0)
473
+ return fail("docker", `docker volume create ${proxy} failed: ${volume.value.stderr.trim()}`);
474
+ const { image, hint, readyMs } = this.#egress;
475
+ const args = egressRunArgs({ name, user, image, allow, local: this.#hostLocal(), deadline, code: this.#code, labels, ...(hint === undefined ? {} : { hint }) });
476
+ const ran = await this.#run(args, signal);
477
+ if (!ran.ok)
478
+ return ran;
479
+ if (ran.value.exitCode !== 0)
480
+ return fail("docker", `docker run of the egress proxy ${proxy} failed: ${ran.value.stderr.trim()}`);
481
+ // Every call of the poll ends at the readiness bound, so a docker that stops answering cannot hold create past it: a
482
+ // call the bound cut off is the timeout, and the caller's own abort stays aborted.
483
+ const bound = AbortSignal.timeout(readyMs);
484
+ const either = signal ? AbortSignal.any([signal, bound]) : bound;
485
+ const late = () => fail("timeout", `the egress proxy ${proxy} was not ready within ${readyMs / 1000} s`);
486
+ const cut = (result) => {
487
+ if (result.ok)
488
+ return result;
489
+ if (signal?.aborted)
490
+ return fail("aborted", `create was aborted while the egress proxy ${proxy} started`);
491
+ return bound.aborted ? late() : result;
492
+ };
493
+ for (;;) {
494
+ const logs = cut(await this.#run(["logs", proxy], either));
495
+ if (!logs.ok)
496
+ return logs;
497
+ const said = `${logs.value.stdout}\n${logs.value.stderr}`;
498
+ if (said.split("\n").some((line) => line.startsWith(EGRESS_READY)))
499
+ return ok(undefined);
500
+ const found = cut(await this.#inspect([proxy], either));
501
+ if (!found.ok)
502
+ return found;
503
+ const state = found.value[0]?.State;
504
+ if (state?.Running !== true) {
505
+ const words = said.trim().split("\n").filter(Boolean).slice(-3).join("; ");
506
+ return fail("docker", `the egress proxy ${proxy} ended (exit code ${state?.ExitCode ?? "unknown"}) before it was ready${words ? `: ${words}` : ""}`);
507
+ }
508
+ await sleep(EGRESS_POLL_MS, undefined, { signal: either }).catch(() => undefined);
509
+ if (signal?.aborted)
510
+ return fail("aborted", `create was aborted while the egress proxy ${proxy} started`);
511
+ if (bound.aborted)
512
+ return late();
513
+ }
514
+ }
515
+ /** Starts the desktop's X server through the daemon and waits until hello declares the display (startDisplay). */
516
+ async #startDisplay(ref, desktop, signal) {
517
+ const opened = await this.#open(ref, signal);
518
+ if (!opened.ok)
519
+ return opened;
520
+ try {
521
+ return await startDisplay(opened.value.client, desktop, { version: VERSION, vendor: "docker", signal });
522
+ }
523
+ finally {
524
+ await opened.value.close();
525
+ }
526
+ }
527
+ /** The drift check: the computer's own report, from inspect and from its daemon's hello, against the spec. */
528
+ async #check(spec, ref, report, host, deadline, user, daemonPath, signal) {
529
+ const proxy = await this.#proxyOf(report, signal);
530
+ if (!proxy.ok)
531
+ return proxy;
532
+ const opened = await this.#open(ref, signal);
533
+ if (!opened.ok)
534
+ return opened;
535
+ await opened.value.close();
536
+ const found = drift(spec, report, opened.value.hello, this.#expected(host, deadline, user, daemonPath, proxy.value));
537
+ return found.length === 0 ? ok(undefined) : fail("refused", `it did not match its spec: ${found.join("; ")}`);
538
+ }
539
+ /** What the drift check holds a computer to; daemonPath is the file it binds, the provider's copy of the daemon. */
540
+ #expected(host, deadline, user, daemonPath, proxy) {
541
+ const { arch, apparmor, selinux } = host;
542
+ const { kind, groups } = this.capabilities();
543
+ return {
544
+ version: VERSION, kind, groups, arch, apparmor, selinux, daemonPath, deadline, user, proxy, egressCode: this.#code, hostAddresses: this.#hostLocal(),
545
+ ...(this.#volume === undefined ? {} : { volume: this.#volume }),
546
+ };
547
+ }
548
+ /**
549
+ * The Docker host's own addresses the egress proxy refuses (its --local): this machine's public ones and
550
+ * egress.hostAddresses. Create gives them to the proxy, and every read-back holds the proxy to them as they are now.
551
+ */
552
+ #hostLocal() {
553
+ return [...new Set([...hostAddresses(), ...(this.#egress.hostAddresses ?? [])])];
554
+ }
555
+ /**
556
+ * The daemon file a computer binds: the provider's 0755 copy of daemonPath in daemonCache (daemonCopy), so a daemon
557
+ * installed under any umask runs as any computer user, and the file that is every computer's init sits where only
558
+ * this user may change it. Always the copy, even of a 0755 daemon, so create and attach have one path to compare.
559
+ */
560
+ #daemon() {
561
+ // With the volume option, a directory below the volume's root holding computerd (stage.ts), mounted whole at
562
+ // /opt/agentrun: Docker mounts a volume's subpath that is a directory, and nothing leans on a file.
563
+ let path;
564
+ if (this.#volume === undefined) {
565
+ const copied = daemonCopy(this.#daemonPath, this.#daemonCache);
566
+ if (!copied.ok)
567
+ return copied;
568
+ path = copied.value;
569
+ }
570
+ else {
571
+ const staged = daemonStage(this.#daemonPath, this.#daemonCache, this.#volume);
572
+ if (!staged.ok)
573
+ return staged;
574
+ path = staged.value.path;
575
+ }
576
+ if (MOUNT_UNSAFE.test(path)) {
577
+ return fail("invalid", `the daemon's copy ${path} has a comma, a double quote or a line break in its path, which a Docker mount cannot hold: give the provider another daemonCache`);
578
+ }
579
+ return ok(path);
580
+ }
581
+ /** With the volume option: the daemon's staged directory a computer mounts at /opt/agentrun, by its subpath in
582
+ * HostConfig.Mounts, when it is a verified copy of this provider's daemon (stage.ts daemonVerified); else undefined. */
583
+ #mountedDaemon(report) {
584
+ const volume = this.#volume;
585
+ if (volume === undefined)
586
+ return undefined;
587
+ const [mount] = (report.HostConfig?.Mounts ?? []).filter((entry) => entry.Target === DAEMON_DIR_IN_COMPUTER && entry.Type === "volume" && entry.Source === volume.name);
588
+ const subpath = mount?.VolumeOptions?.Subpath;
589
+ return typeof subpath === "string" ? daemonVerified(this.#daemonPath, this.#daemonCache, volume, subpath) : undefined;
590
+ }
591
+ /**
592
+ * The --mount value that puts `path` of this host at `dst`: a bind of it, or, with the volume option, its subpath of
593
+ * the volume (never the root); a path outside the volume is refused in words, and nothing is made.
594
+ */
595
+ #mountOf(path, dst, readonly) {
596
+ const volume = this.#volume;
597
+ if (volume === undefined)
598
+ return ok(`type=bind,src=${path},dst=${dst}${readonly ? ",readonly" : ""}`);
599
+ const subpath = subpathOf(volume, path);
600
+ if (subpath === undefined)
601
+ return fail("refused", `mount: ${outsideWords(volume, path, readonly ? "the daemon's copy" : "mount.path")}`);
602
+ return ok(volumeMount(volume, subpath, dst, readonly));
603
+ }
604
+ /** The egress proxy container's inspect for a computer that shows any part of an allowlist, null when it is gone;
605
+ * undefined, with no Docker call, for any other computer. */
606
+ async #proxyOf(report, signal) {
607
+ if (!egressShaped(report))
608
+ return ok(undefined);
609
+ const found = await this.#inspect([egressNameOf(nameOf(report))], signal);
610
+ return found.ok ? ok(found.value[0] ?? null) : found;
611
+ }
612
+ /**
613
+ * Why this provider's own interfaces are not the Docker host's, in words, or null when they are: it runs in a
614
+ * container (containerSigns), or its docker CLI talks to a daemon that is not a local unix socket, as the CLI itself
615
+ * resolves its context and DOCKER_HOST (`docker context inspect`). A CLI that cannot say is a reason too. Read once.
616
+ */
617
+ async #elsewhereOf(signal) {
618
+ if (this.#elsewhere !== undefined)
619
+ return ok(this.#elsewhere);
620
+ const sign = containerSigns(this.#egress.hostRoot);
621
+ if (sign !== undefined)
622
+ return ok((this.#elsewhere = `this provider runs in a container (${sign})`));
623
+ const ran = await this.#run(["context", "inspect", "--format", "{{json .Endpoints.docker.Host}}"], signal);
624
+ if (!ran.ok)
625
+ return ran;
626
+ let endpoint;
627
+ try {
628
+ endpoint = ran.value.exitCode === 0 ? JSON.parse(ran.value.stdout) : undefined;
629
+ }
630
+ catch {
631
+ endpoint = undefined;
632
+ }
633
+ if (typeof endpoint !== "string") {
634
+ const why = (ran.value.stderr.trim() || ran.value.stdout.trim()).split("\n")[0]?.slice(0, 200) ?? "";
635
+ return ok((this.#elsewhere = `the docker CLI could not say where its Docker daemon is (docker context inspect: ${why || `exit ${ran.value.exitCode}`})`));
636
+ }
637
+ this.#elsewhere = endpoint.startsWith("unix://") ? null : `the docker CLI talks to a Docker daemon at ${endpoint.slice(0, 200)}, not a local unix socket`;
638
+ return ok(this.#elsewhere);
639
+ }
640
+ /** The Docker host's architecture and enforcement (hostOf), read by docker info once per provider. */
641
+ async host({ signal } = {}) {
642
+ if (this.#host)
643
+ return ok(this.#host);
644
+ const ran = await this.#run(["info", "--format", INFO_FORMAT], signal);
645
+ if (!ran.ok)
646
+ return ran;
647
+ if (ran.value.exitCode !== 0)
648
+ return fail("docker", `docker info failed: ${ran.value.stderr.trim()}`);
649
+ let info;
650
+ try {
651
+ info = JSON.parse(ran.value.stdout);
652
+ }
653
+ catch {
654
+ return fail("docker", `docker info wrote what is not JSON: ${ran.value.stdout.slice(0, 200)}`);
655
+ }
656
+ this.#host = hostOf(info);
657
+ return ok(this.#host);
658
+ }
659
+ /**
660
+ * The drift check of a computer attach did not make: the spec it was made with, read back from its own report and
661
+ * held to what check() allows, then inspect and, when it runs, hello, as at create. A computer that passes is
662
+ * returned with that spec.
663
+ */
664
+ async #attached(report, signal) {
665
+ const ref = { id: report.Id ?? "", name: nameOf(report) };
666
+ const host = await this.host({ signal });
667
+ if (!host.ok)
668
+ return host;
669
+ if (host.value.problems.length > 0)
670
+ return fail("refused", `host: ${host.value.problems.join("; ")}`);
671
+ const config = report.Config ?? {};
672
+ const limits = report.HostConfig ?? {};
673
+ const found = [];
674
+ const proxy = await this.#proxyOf(report, signal);
675
+ if (!proxy.ok)
676
+ return proxy;
677
+ const network = networkOf(report, proxy.value, this.#code, this.#hostLocal());
678
+ if (typeof network !== "string" && "other" in network)
679
+ found.push(`network: ${network.other}, which this provider never makes`);
680
+ const deadline = config.Labels?.[DEADLINE_LABEL] ?? "";
681
+ const at = Date.parse(deadline);
682
+ if (Number.isNaN(at) || new Date(at).toISOString() !== deadline) {
683
+ found.push(`deadline: the label ${DEADLINE_LABEL} reads ${JSON.stringify(deadline)}, not the ISO time create writes`);
684
+ }
685
+ else if (at > Date.now() + this.capabilities().maxLifetimeMs + 60_000)
686
+ found.push(`deadline: ${deadline} is past the 30 days create allows`);
687
+ // The run's folder as the computer has it. The folder on the host is not checked again: it is what is bound.
688
+ const mount = mountOf(report, this.#volume);
689
+ if (mount !== undefined && "other" in mount)
690
+ found.push(`mount: ${mount.other}, which this provider never makes`);
691
+ const bind = mount !== undefined && "kind" in mount && mount.kind === "bind" ? mount : undefined;
692
+ const spec = {
693
+ image: config.Image,
694
+ lifetimeMs: 1,
695
+ network: typeof network === "string" || "allow" in network ? network : "none",
696
+ cpus: typeof limits.CpuQuota === "number" ? limits.CpuQuota / CPU_PERIOD_US : limits.CpuQuota,
697
+ memoryMb: typeof limits.Memory === "number" ? limits.Memory / (1024 * 1024) : limits.Memory,
698
+ pids: limits.PidsLimit,
699
+ workdir: config.WorkingDir,
700
+ user: config.User,
701
+ ...(bind === undefined ? {} : { mount: bind }),
702
+ };
703
+ found.push(...this.#checkSpec({ ...spec, mount: undefined }).map(({ field, message }) => `${field}: ${message}, read back from the computer`));
704
+ const user = userOf(config.User) ?? String(config.User);
705
+ // The copy create binds for this provider's daemon: the same bytes, from any process, have the same path. With the
706
+ // volume option, the staged directory the computer mounts when it is a verified copy (another provider may have
707
+ // published one beside a tree that no longer held), else the one staging uses now.
708
+ const daemon = this.#daemon();
709
+ if (!daemon.ok)
710
+ return daemon;
711
+ const expected = this.#expected(host.value, deadline, user, this.#mountedDaemon(report) ?? daemon.value, proxy.value);
712
+ found.push(...inspectDrift(spec, report, expected).filter((line) => typeof network === "string" || !("other" in network) || !line.startsWith("network:")));
713
+ let kind;
714
+ if (report.State?.Running === true) {
715
+ const opened = await this.#open(ref, signal);
716
+ if (!opened.ok)
717
+ return opened;
718
+ await opened.value.close();
719
+ found.push(...helloDrift(opened.value.hello, expected));
720
+ kind = opened.value.hello.kind;
721
+ }
722
+ if (found.length > 0) {
723
+ return fail("refused", `the computer ${ref.name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
724
+ }
725
+ const { image, network: read, cpus, memoryMb, pids, workdir } = spec;
726
+ const readBack = { image, user, network: read, cpus, memoryMb, pids, workdir, deadline: new Date(at), ...(kind === undefined ? {} : { kind }), ...(bind === undefined ? {} : { mount: bind }) };
727
+ return ok({ ...ref, spec: readBack });
728
+ }
729
+ /** The live view: screen.watch on a connection of the watch's own (daemonWatch); a linux computer has no screen. */
730
+ watch(ref, handlers, options) {
731
+ return daemonWatch(this, ref, handlers, options);
732
+ }
733
+ async connect(ref) {
734
+ if (!NAME.test(ref.name))
735
+ return fail("invalid", `${ref.name} is not the name of a Docker computer (computer-<12 hex digits>)`);
736
+ const opened = await this.#open(ref);
737
+ if (!opened.ok)
738
+ return opened;
739
+ const { kind, groups } = this.capabilities();
740
+ const found = helloDrift(opened.value.hello, { version: VERSION, kind, groups });
741
+ if (found.length === 0)
742
+ return opened;
743
+ await opened.value.close();
744
+ return fail("refused", `the daemon in ${ref.name} does not match this provider: ${found.join("; ")}`);
745
+ }
746
+ /** One connection to the computer's daemon, after hello, unchecked. */
747
+ async #open(ref, signal) {
748
+ const child = spawn(this.#docker, ["exec", "-i", ref.name, DAEMON_IN_COMPUTER, "stdio"], { stdio: ["pipe", "pipe", "pipe"] });
749
+ let stderr = "";
750
+ child.stderr.on("data", (chunk) => {
751
+ stderr = (stderr + chunk.toString("utf8")).slice(-4096);
752
+ });
753
+ child.on("error", (error) => {
754
+ stderr ||= error.message;
755
+ });
756
+ const exited = new Promise((done) => child.once("close", () => done()));
757
+ const client = new DaemonClient({ readable: child.stdout, writable: child.stdin });
758
+ const close = async () => {
759
+ client.close();
760
+ const timer = setTimeout(() => child.kill("SIGKILL"), 2000);
761
+ await exited;
762
+ clearTimeout(timer);
763
+ };
764
+ const timeout = AbortSignal.timeout(HELLO_TIMEOUT_MS);
765
+ const either = signal ? AbortSignal.any([signal, timeout]) : timeout;
766
+ const hello = await client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: either });
767
+ if (!hello.ok) {
768
+ await close();
769
+ if (signal?.aborted)
770
+ return fail("aborted", `hello to the daemon in ${ref.name} was aborted`);
771
+ if (hello.error.code === "aborted")
772
+ return fail("timeout", `the daemon in ${ref.name} did not answer hello within ${HELLO_TIMEOUT_MS / 1000} s`);
773
+ if (hello.error.code !== "gone")
774
+ return hello;
775
+ const words = stderr.trim() || hello.error.message;
776
+ return fail(noSuchContainer(words) ? "not_found" : "docker", `cannot reach the daemon in ${ref.name}: ${words}`);
777
+ }
778
+ return ok({ client, hello: hello.value, close });
779
+ }
780
+ async attach(ref, { signal } = {}) {
781
+ const given = (typeof ref === "object" && ref !== null ? ref : {});
782
+ if ((given.id === undefined) === (given.labels === undefined))
783
+ return fail("invalid", "attach takes { id } or { labels }, one of them");
784
+ if (given.id !== undefined) {
785
+ const id = given.id;
786
+ if (typeof id !== "string" || !(NAME.test(id) || ID.test(id))) {
787
+ return fail("invalid", `${String(id)} is neither a Docker computer's name (computer-<12 hex digits>) nor a container id (12 to 64 hex digits)`);
788
+ }
789
+ const found = await this.#inspect([id], signal);
790
+ if (!found.ok)
791
+ return found;
792
+ const [report] = found.value;
793
+ // Docker resolves a name before an id prefix, so what it found must be what was asked for.
794
+ const same = report !== undefined && (NAME.test(id) ? nameOf(report) === id : report.Id?.startsWith(id) === true);
795
+ if (!same || !ours(report) || typeof report.Id !== "string")
796
+ return fail("not_found", `no Docker computer has the id ${id}`);
797
+ return this.#attached(report, signal);
798
+ }
799
+ const problem = filterProblem(given.labels);
800
+ if (problem)
801
+ return fail("invalid", problem);
802
+ const labels = given.labels;
803
+ if (Object.keys(labels).length === 0)
804
+ return fail("invalid", "attach by labels needs at least one label");
805
+ const listed = await this.list(labels, { signal });
806
+ if (!listed.ok)
807
+ return listed;
808
+ const matches = listed.value.map((info) => info.ref);
809
+ const words = JSON.stringify(labels);
810
+ if (matches.length === 0)
811
+ return fail("not_found", `no Docker computer has the labels ${words}`);
812
+ if (matches.length > 1)
813
+ return fail("invalid", `${matches.length} computers match the labels ${words}: ${matches.map((m) => m.name).join(", ")}`);
814
+ const match = matches[0];
815
+ const found = await this.#inspect([match.id], signal);
816
+ if (!found.ok)
817
+ return found;
818
+ const [report] = found.value;
819
+ if (report === undefined || report.Id !== match.id || !ours(report))
820
+ return fail("not_found", `no Docker computer has the labels ${words}`);
821
+ return this.#attached(report, signal);
822
+ }
823
+ /**
824
+ * Settings' test: one docker ps by the provider's own label on this Docker host, which makes nothing. The count is the
825
+ * names of its making that ps lists, with no inspect of each.
826
+ */
827
+ async testConnection({ signal } = {}) {
828
+ const ran = await this.#run(["ps", "-a", "--no-trunc", "--filter", `label=${COMPUTER_LABEL}=1`, "--format", "{{.Names}}"], signal);
829
+ if (!ran.ok)
830
+ return countTested("Docker", ran);
831
+ if (ran.value.exitCode !== 0)
832
+ return countTested("Docker", fail("docker", `docker ps failed: ${ran.value.stderr.trim()}`));
833
+ const names = ran.value.stdout.split("\n").map((line) => line.trim());
834
+ return countTested("Docker", ok({ count: names.filter((name) => NAME.test(name)).length }));
835
+ }
836
+ async list(labels, { signal } = {}) {
837
+ const problem = filterProblem(labels);
838
+ if (problem)
839
+ return fail("invalid", problem);
840
+ const args = ["ps", "-a", "--no-trunc", "--filter", `label=${COMPUTER_LABEL}=1`];
841
+ for (const [key, value] of Object.entries(labels))
842
+ args.push("--filter", `label=${key}=${value}`);
843
+ const ran = await this.#run([...args, "--format", "{{.ID}}"], signal);
844
+ if (!ran.ok)
845
+ return ran;
846
+ if (ran.value.exitCode !== 0)
847
+ return fail("docker", `docker ps failed: ${ran.value.stderr.trim()}`);
848
+ const ids = ran.value.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
849
+ const infos = [];
850
+ const local = this.#hostLocal();
851
+ for (let at = 0; at < ids.length; at += INSPECT_BATCH) {
852
+ // A computer removed between ps and inspect is left out.
853
+ const found = await this.#inspect(ids.slice(at, at + INSPECT_BATCH), signal, LIST_FORMAT);
854
+ if (!found.ok)
855
+ return found;
856
+ const computers = found.value.filter(ours);
857
+ // The allowlist computers' proxies, in one inspect: each read-back holds the list its proxy runs with.
858
+ const shaped = computers.filter(egressShaped).map((report) => egressNameOf(nameOf(report)));
859
+ const proxies = new Map();
860
+ if (shaped.length > 0) {
861
+ const read = await this.#inspect(shaped, signal);
862
+ if (!read.ok)
863
+ return read;
864
+ for (const proxy of read.value)
865
+ proxies.set(nameOf(proxy), proxy);
866
+ }
867
+ infos.push(...computers.map((report) => infoOf(report, egressShaped(report) ? (proxies.get(egressNameOf(nameOf(report))) ?? null) : undefined, this.#code, local, this.#volume)));
868
+ }
869
+ return ok(infos);
870
+ }
871
+ /**
872
+ * The janitor's second pass (sweep calls it after the computers): every egress proxy container and egress volume
873
+ * labelled EGRESS_LABEL, and with all of `labels`, whose deadline label has passed (or is missing or unreadable, fail
874
+ * closed), or whose computer is gone and that is older than a create could take (#leftoverGraceMs: one under way has
875
+ * made its proxy before its computer, and pulled both images before either, so no pull happens in between). Each is
876
+ * removed by what its label found, a proxy before its volume, never by a name alone. Returns the names removed, a
877
+ * volume's as "<name> (volume)".
878
+ */
879
+ async sweepLeftovers({ labels = {}, now = new Date(), signal } = {}) {
880
+ const problem = filterProblem(labels);
881
+ if (problem)
882
+ return fail("invalid", problem);
883
+ const filters = [`label=${EGRESS_LABEL}`, ...Object.entries(labels).map(([key, value]) => `label=${key}=${value}`)].flatMap((filter) => ["--filter", filter]);
884
+ const lines = (stdout) => stdout.split("\n").map((line) => line.trim()).filter(Boolean);
885
+ const alive = await this.#run(["ps", "-a", "--no-trunc", "--filter", `label=${COMPUTER_LABEL}=1`, "--format", "{{.Names}}"], signal);
886
+ if (!alive.ok)
887
+ return alive;
888
+ if (alive.value.exitCode !== 0)
889
+ return fail("docker", `docker ps failed: ${alive.value.stderr.trim()}`);
890
+ const computers = new Set(lines(alive.value.stdout).filter((name) => NAME.test(name)));
891
+ const at = now.getTime();
892
+ const grace = this.#leftoverGraceMs();
893
+ const leftover = (labelsOf, created) => {
894
+ const owner = labelsOf?.[EGRESS_LABEL];
895
+ const deadline = Date.parse(labelsOf?.[DEADLINE_LABEL] ?? "");
896
+ if (typeof owner !== "string" || !NAME.test(owner))
897
+ return false;
898
+ if (Number.isNaN(deadline) || deadline <= at)
899
+ return true;
900
+ if (computers.has(owner))
901
+ return false;
902
+ const made = typeof created === "string" ? Date.parse(created) : Number.NaN;
903
+ return Number.isNaN(made) || at - made > grace;
904
+ };
905
+ const removed = [];
906
+ const ps = await this.#run(["ps", "-a", "--no-trunc", ...filters, "--format", "{{.ID}}"], signal);
907
+ if (!ps.ok)
908
+ return ps;
909
+ if (ps.value.exitCode !== 0)
910
+ return fail("docker", `docker ps for egress proxies failed: ${ps.value.stderr.trim()}`);
911
+ const ids = lines(ps.value.stdout);
912
+ for (let from = 0; from < ids.length; from += INSPECT_BATCH) {
913
+ const found = await this.#inspect(ids.slice(from, from + INSPECT_BATCH), signal);
914
+ if (!found.ok)
915
+ return found;
916
+ for (const proxy of found.value) {
917
+ if (!leftover(proxy.Config?.Labels, proxy.Created) || typeof proxy.Id !== "string")
918
+ continue;
919
+ const ran = await this.#run(["rm", "--force", proxy.Id], signal);
920
+ if (!ran.ok)
921
+ return ran;
922
+ if (ran.value.exitCode !== 0 && !noSuchContainer(ran.value.stderr))
923
+ return fail("docker", `docker rm of the egress proxy ${nameOf(proxy)} failed: ${ran.value.stderr.trim()}`);
924
+ removed.push(nameOf(proxy));
925
+ }
926
+ }
927
+ const ls = await this.#run(["volume", "ls", ...filters, "--format", "{{.Name}}"], signal);
928
+ if (!ls.ok)
929
+ return ls;
930
+ if (ls.value.exitCode !== 0)
931
+ return fail("docker", `docker volume ls for egress volumes failed: ${ls.value.stderr.trim()}`);
932
+ const names = lines(ls.value.stdout);
933
+ for (let from = 0; from < names.length; from += INSPECT_BATCH) {
934
+ const read = await this.#run(["volume", "inspect", "--format", "{{json .}}", ...names.slice(from, from + INSPECT_BATCH)], signal);
935
+ if (!read.ok)
936
+ return read;
937
+ for (const line of lines(read.value.stdout)) {
938
+ let volume;
939
+ try {
940
+ volume = JSON.parse(line);
941
+ }
942
+ catch {
943
+ return fail("docker", `docker volume inspect wrote a line that is not JSON: ${line.slice(0, 200)}`);
944
+ }
945
+ if (typeof volume.Name !== "string" || !leftover(volume.Labels, volume.CreatedAt))
946
+ continue;
947
+ const ran = await this.#run(["volume", "rm", "--force", volume.Name], signal);
948
+ if (!ran.ok)
949
+ return ran;
950
+ if (ran.value.exitCode !== 0)
951
+ return fail("docker", `docker volume rm ${volume.Name} failed: ${ran.value.stderr.trim()}`);
952
+ removed.push(`${volume.Name} (volume)`);
953
+ }
954
+ }
955
+ return ok(removed);
956
+ }
957
+ /**
958
+ * How long a proxy or volume with no computer may be a create under way: its ready wait, and two minutes more. It
959
+ * holds because no pull happens inside it: create pulls both images before it makes the volume, and both docker runs
960
+ * take --pull never, so from the volume to the computer it waits on the proxy's ready line and two local starts.
961
+ */
962
+ #leftoverGraceMs() {
963
+ return Math.max(this.#egress.readyMs, EGRESS_READY_MS) + 120_000;
964
+ }
965
+ async network(ref, policy, { signal } = {}) {
966
+ if (!NAME.test(ref?.name))
967
+ return fail("invalid", `${ref?.name} is not the name of a Docker computer (computer-<12 hex digits>)`);
968
+ let asked = policy;
969
+ if (typeof policy === "object" && policy !== null && "allow" in policy) {
970
+ const allow = allowOf(policy.allow);
971
+ if ("problem" in allow)
972
+ return fail("refused", `${allow.problem}; ${FIXED}`);
973
+ asked = { allow: allow.list };
974
+ }
975
+ else if (policy !== undefined && policy !== "none" && policy !== "open")
976
+ return fail("refused", `${FIXED}; ${NETWORKS}`);
977
+ const found = await this.#inspect([ref.name], signal);
978
+ if (!found.ok)
979
+ return found;
980
+ const [report] = found.value;
981
+ if (report === undefined || !ours(report))
982
+ return fail("not_found", `no Docker computer is named ${ref.name}`);
983
+ const proxy = await this.#proxyOf(report, signal);
984
+ if (!proxy.ok)
985
+ return proxy;
986
+ const current = networkOf(report, proxy.value, this.#code, this.#hostLocal());
987
+ if (asked === undefined || samePolicy(asked, current))
988
+ return ok(current);
989
+ return fail("refused", `${FIXED}: ${ref.name} has network ${policyWords(current)}, not ${policyWords(asked)}`);
990
+ }
991
+ /**
992
+ * Stops or deletes the computer, then its egress proxy, found by its label (EGRESS_LABEL=<name>), and on delete its
993
+ * egress volume, found the same way: a container or volume of the proxy's name without that label is never touched.
994
+ * Each is ok when already gone.
995
+ */
996
+ async release(ref, how) {
997
+ if (!NAME.test(ref.name))
998
+ return fail("invalid", `${ref.name} is not the name of a Docker computer (computer-<12 hex digits>)`);
999
+ if (how !== "stop" && how !== "delete")
1000
+ return fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
1001
+ const args = how === "stop" ? ["stop", ref.name] : ["rm", "--force", "--volumes", ref.name];
1002
+ const ran = await this.#run(args);
1003
+ if (!ran.ok)
1004
+ return ran;
1005
+ if (ran.value.exitCode !== 0 && !noSuchContainer(ran.value.stderr))
1006
+ return fail("docker", `docker ${args[0]} ${ref.name} failed: ${ran.value.stderr.trim()}`);
1007
+ const label = `label=${EGRESS_LABEL}=${ref.name}`;
1008
+ const proxies = await this.#run(["ps", "-a", "--no-trunc", "--filter", label, "--format", "{{.ID}}"]);
1009
+ if (!proxies.ok)
1010
+ return proxies;
1011
+ if (proxies.value.exitCode !== 0)
1012
+ return fail("docker", `docker ps for ${ref.name}'s egress proxy failed: ${proxies.value.stderr.trim()}`);
1013
+ for (const id of proxies.value.stdout.split("\n").map((line) => line.trim()).filter(Boolean)) {
1014
+ const ended = await this.#run(how === "stop" ? ["stop", id] : ["rm", "--force", id]);
1015
+ if (!ended.ok)
1016
+ return ended;
1017
+ if (ended.value.exitCode !== 0 && !noSuchContainer(ended.value.stderr))
1018
+ return fail("docker", `docker ${how === "stop" ? "stop" : "rm"} of ${ref.name}'s egress proxy failed: ${ended.value.stderr.trim()}`);
1019
+ }
1020
+ if (how === "stop")
1021
+ return ok(undefined);
1022
+ const volumes = await this.#run(["volume", "ls", "--filter", label, "--format", "{{.Name}}"]);
1023
+ if (!volumes.ok)
1024
+ return volumes;
1025
+ if (volumes.value.exitCode !== 0)
1026
+ return fail("docker", `docker volume ls for ${ref.name}'s egress volume failed: ${volumes.value.stderr.trim()}`);
1027
+ for (const volume of volumes.value.stdout.split("\n").map((line) => line.trim()).filter(Boolean)) {
1028
+ const removed = await this.#run(["volume", "rm", "--force", volume]);
1029
+ if (!removed.ok)
1030
+ return removed;
1031
+ if (removed.value.exitCode !== 0)
1032
+ return fail("docker", `docker volume rm ${volume} failed: ${removed.value.stderr.trim()}`);
1033
+ }
1034
+ return ok(undefined);
1035
+ }
1036
+ /** Inspects containers by name or id, whole or only the fields a format names; one that is gone is left out. */
1037
+ async #inspect(keys, signal, format = "{{json .}}") {
1038
+ const ran = await this.#run(["inspect", "--type", "container", "--format", format, ...keys], signal);
1039
+ if (!ran.ok)
1040
+ return ran;
1041
+ const { exitCode, stdout, stderr } = ran.value;
1042
+ const errors = stderr.split("\n").filter((line) => line.trim() !== "" && !noSuchContainer(line));
1043
+ if (exitCode !== 0 && errors.length > 0)
1044
+ return fail("docker", `docker inspect failed: ${errors.join("; ")}`);
1045
+ const found = [];
1046
+ for (const line of stdout.split("\n").filter((line) => line.trim() !== "")) {
1047
+ try {
1048
+ found.push(JSON.parse(line));
1049
+ }
1050
+ catch {
1051
+ return fail("docker", `docker inspect wrote a line that is not JSON: ${line.slice(0, 200)}`);
1052
+ }
1053
+ }
1054
+ return ok(found);
1055
+ }
1056
+ #run(args, signal) {
1057
+ return new Promise((done) => {
1058
+ execFile(this.#docker, args, { signal, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {
1059
+ if (error === null)
1060
+ return done(ok({ exitCode: 0, stdout, stderr }));
1061
+ if (error.name === "AbortError")
1062
+ return done(fail("aborted", `docker ${args[0]} was aborted`));
1063
+ if (typeof error.code === "number")
1064
+ return done(ok({ exitCode: error.code, stdout, stderr }));
1065
+ if (error.code === "ENOENT")
1066
+ return done(fail("docker", `the docker CLI (${this.#docker}) was not found`));
1067
+ done(fail("docker", `docker ${args[0]} failed: ${error.message}`));
1068
+ });
1069
+ });
1070
+ }
1071
+ }
1072
+ function labelProblem(key, value) {
1073
+ if (typeof value !== "string")
1074
+ return `the label ${key} must be a string`;
1075
+ if (key.includes("\0") || value.includes("\0"))
1076
+ return `the label ${JSON.stringify(key)}: ${NUL}`;
1077
+ if (key === "" || key.includes("="))
1078
+ return `the label name "${key}" must be non-empty and have no "="`;
1079
+ if (key === COMPUTER_LABEL || key.startsWith(`${COMPUTER_LABEL}.`))
1080
+ return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
1081
+ return undefined;
1082
+ }
1083
+ /** Why labels cannot be a docker ps filter, or undefined when they can. */
1084
+ function filterProblem(labels) {
1085
+ if (typeof labels !== "object" || labels === null || Array.isArray(labels))
1086
+ return "labels must map names to strings";
1087
+ for (const [key, value] of Object.entries(labels)) {
1088
+ if (typeof value !== "string")
1089
+ return `the label ${key} must be a string`;
1090
+ if (key.includes("\0") || value.includes("\0"))
1091
+ return `the label ${JSON.stringify(key)}: a NUL byte cannot be passed to docker`;
1092
+ if (key === "" || key.includes("="))
1093
+ return `the label name "${key}" must be non-empty and have no "="`;
1094
+ }
1095
+ return undefined;
1096
+ }
1097
+ /** A computer as list() reports it. The deadline counts only as the provider writes it, an ISO time; an allowlist's
1098
+ * proxy must refuse each of `local`, the Docker host's own addresses. */
1099
+ function infoOf(report, proxy, code, local, volume) {
1100
+ const labels = { ...(report.Config?.Labels ?? {}) };
1101
+ const written = labels[DEADLINE_LABEL];
1102
+ const at = written === undefined ? Number.NaN : Date.parse(written);
1103
+ const deadline = Number.isNaN(at) || new Date(at).toISOString() !== written ? undefined : new Date(at);
1104
+ const state = report.State?.Running === true ? "running" : "stopped";
1105
+ const mount = mountOf(report, volume);
1106
+ return { ref: { id: report.Id ?? "", name: nameOf(report) }, labels, deadline, state, network: networkOf(report, proxy, code, local), ...(mount === undefined ? {} : { mount }) };
1107
+ }
1108
+ /** The longest delay Node's timers, and so AbortSignal.timeout, hold: 2^31 - 1 ms. */
1109
+ const MAX_TIMER_MS = 2_147_483_647;
1110
+ /** The egress options with their defaults, or a throw in words. */
1111
+ function egressOptionsOf({ image = EGRESS_IMAGE, hint, readyMs = EGRESS_READY_MS, hostAddresses: given, hostRoot = "/" }) {
1112
+ if (typeof hostRoot !== "string" || !hostRoot.startsWith("/"))
1113
+ throw new Error(`the egress proxy's hostRoot must be an absolute path, not ${JSON.stringify(hostRoot)}`);
1114
+ if (typeof image !== "string" || image.trim() === "" || image.startsWith("-") || image.includes("\0")) {
1115
+ throw new Error(`the egress proxy's image ${JSON.stringify(image)} must name an image, such as ${EGRESS_IMAGE}`);
1116
+ }
1117
+ // The hint goes into a status line, which carries printable ASCII only.
1118
+ if (hint !== undefined && (typeof hint !== "string" || !/^[\x20-\x7e]*$/.test(hint)))
1119
+ throw new Error("the egress proxy's hint must be printable ASCII: it goes into a status line");
1120
+ if (!Number.isSafeInteger(readyMs) || readyMs <= 0 || readyMs > MAX_TIMER_MS) {
1121
+ throw new Error(`the egress proxy's readyMs must be a whole number of milliseconds above 0 and at most ${MAX_TIMER_MS}, not ${readyMs}`);
1122
+ }
1123
+ if (given !== undefined && !(Array.isArray(given) && given.every((address) => typeof address === "string" && addressBytes(address) !== undefined && !address.includes(",")))) {
1124
+ throw new Error(`the egress proxy's hostAddresses must be a list of IP addresses, such as ["93.184.215.20"], not ${JSON.stringify(given)}`);
1125
+ }
1126
+ return { image, readyMs, hostRoot, ...(hint === undefined ? {} : { hint }), ...(given === undefined ? {} : { hostAddresses: [...given] }) };
1127
+ }
1128
+ /**
1129
+ * Why an allowlist is refused when this provider's own interfaces are not the Docker host's: the proxy refuses the host's
1130
+ * own addresses as this-host only when it knows them, and here it does not.
1131
+ */
1132
+ function elsewhereWords(why) {
1133
+ return `${why}, so this provider's own interfaces are not the Docker host's, and the egress proxy could not refuse the host's own addresses: pass them as egress.hostAddresses, or ask for network none or open`;
1134
+ }
1135
+ /** Whether a spec's network is an allowlist. */
1136
+ const isAllow = (network) => typeof network === "object" && network !== null && "allow" in network;
1137
+ /**
1138
+ * Why an allowlist is refused on a host that remaps user ids: the egress volume's tmpfs owner and the proxy's code are
1139
+ * ids of the host, and the computer's user and its proxy run as other ones there, so the proxy could not make its socket
1140
+ * or the computer reach it. The provider does not guess the mapping.
1141
+ */
1142
+ function remapAllowWords(remap) {
1143
+ return (`this Docker host remaps user ids (${remap === "userns" ? "userns-remap" : "rootless Docker"}), so the egress volume and the proxy's code are ` +
1144
+ "owned by host ids the computer's user does not map to, and the provider cannot give it an allowlist: ask for network none or open, " +
1145
+ "or use a Docker host that does not remap ids");
1146
+ }
1147
+ /**
1148
+ * Why a bind is refused on a host that remaps user ids. The computer's uid is then another uid on the host (one Docker
1149
+ * picks from /etc/subuid), so the folder's owner and mode say nothing about whether the computer can write it; the
1150
+ * provider does not guess the mapping, and never changes the folder.
1151
+ */
1152
+ function remapWords(remap, path) {
1153
+ return (`this Docker host remaps user ids (${remap === "userns" ? "userns-remap" : "rootless Docker"}), so the run folder's owner on the host is not the ` +
1154
+ `computer's user, and the provider cannot tell whether the computer can write ${path}; it never changes the folder: ` +
1155
+ "bind the run folder on a Docker host that does not remap ids");
1156
+ }
1157
+ /**
1158
+ * Why the computer's user cannot write the run folder it would bind, or undefined when it can. The kernel picks one
1159
+ * class of the mode, the owner's, the group's or others', by the user's uid and gid; that class must allow write and
1160
+ * search. A user with no capabilities, root included, has no other way in. The provider never chowns or chmods it.
1161
+ */
1162
+ function folderProblem(path, user) {
1163
+ let stat;
1164
+ try {
1165
+ stat = statSync(path);
1166
+ }
1167
+ catch (error) {
1168
+ return `the run folder ${path} cannot be read: ${error.message}`;
1169
+ }
1170
+ const [uid, gid] = user.split(":").map(Number);
1171
+ const bits = stat.uid === uid ? (stat.mode >> 6) & 7 : stat.gid === gid ? (stat.mode >> 3) & 7 : stat.mode & 7;
1172
+ if ((bits & 3) === 3)
1173
+ return undefined;
1174
+ const mode = (stat.mode & 0o7777).toString(8).padStart(4, "0");
1175
+ return (`the run folder ${path} is not writable by the computer's user ${user}: it is owned by ${stat.uid}:${stat.gid} with mode ${mode}; ` +
1176
+ `the provider never changes it: chown it to ${user}, or give that user write and search permission`);
1177
+ }
1178
+ /** "uid:gid" for a user in numbers (a uid alone is its own gid, never root's group 0), or undefined when it is not one. */
1179
+ function userOf(value) {
1180
+ const match = typeof value === "string" ? USER.exec(value) : null;
1181
+ if (match === null)
1182
+ return undefined;
1183
+ const [uid, gid] = [Number(match[1]), Number(match[2] ?? match[1])];
1184
+ return uid <= MAX_ID && gid <= MAX_ID ? `${uid}:${gid}` : undefined;
1185
+ }
1186
+ /** This process's uid:gid, or 1000:1000 when either is 0 (root, or root's group) or unknown. */
1187
+ function defaultUser() {
1188
+ const [uid, gid] = [process.getuid?.(), process.getgid?.()];
1189
+ return uid === undefined || gid === undefined || uid === 0 || gid === 0 ? "1000:1000" : `${uid}:${gid}`;
1190
+ }
1191
+ /** The mode of a regular file, or undefined when there is none. */
1192
+ function fileMode(path) {
1193
+ try {
1194
+ const stat = statSync(path);
1195
+ return stat.isFile() ? stat.mode : undefined;
1196
+ }
1197
+ catch {
1198
+ return undefined;
1199
+ }
1200
+ }