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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +2400 -1
  4. package/box/Dockerfile +69 -0
  5. package/box/agentrun-archil +168 -0
  6. package/box/build-daytona.py +26 -0
  7. package/box/build-e2b.mjs +32 -0
  8. package/box/build-modal.py +17 -0
  9. package/dist/actions.d.ts +18 -0
  10. package/dist/actions.js +139 -0
  11. package/dist/browser.d.ts +151 -0
  12. package/dist/browser.js +305 -0
  13. package/dist/browserbase.d.ts +139 -0
  14. package/dist/browserbase.js +408 -0
  15. package/dist/child.d.ts +40 -0
  16. package/dist/child.js +127 -0
  17. package/dist/client.d.ts +22 -0
  18. package/dist/client.js +136 -0
  19. package/dist/computerd-linux-amd64 +0 -0
  20. package/dist/computerd-linux-arm64 +0 -0
  21. package/dist/conformance/archil.d.ts +68 -0
  22. package/dist/conformance/archil.js +152 -0
  23. package/dist/conformance/browserbase.d.ts +35 -0
  24. package/dist/conformance/browserbase.js +45 -0
  25. package/dist/conformance/cases/apps.d.ts +2 -0
  26. package/dist/conformance/cases/apps.js +155 -0
  27. package/dist/conformance/cases/browser.d.ts +4 -0
  28. package/dist/conformance/cases/browser.js +105 -0
  29. package/dist/conformance/cases/drift.d.ts +2 -0
  30. package/dist/conformance/cases/drift.js +64 -0
  31. package/dist/conformance/cases/exec.d.ts +2 -0
  32. package/dist/conformance/cases/exec.js +125 -0
  33. package/dist/conformance/cases/files.d.ts +2 -0
  34. package/dist/conformance/cases/files.js +294 -0
  35. package/dist/conformance/cases/health.d.ts +2 -0
  36. package/dist/conformance/cases/health.js +71 -0
  37. package/dist/conformance/cases/index.d.ts +9 -0
  38. package/dist/conformance/cases/index.js +37 -0
  39. package/dist/conformance/cases/input.d.ts +12 -0
  40. package/dist/conformance/cases/input.js +109 -0
  41. package/dist/conformance/cases/isolation.d.ts +21 -0
  42. package/dist/conformance/cases/isolation.js +92 -0
  43. package/dist/conformance/cases/lifetime.d.ts +2 -0
  44. package/dist/conformance/cases/lifetime.js +64 -0
  45. package/dist/conformance/cases/mount.d.ts +2 -0
  46. package/dist/conformance/cases/mount.js +252 -0
  47. package/dist/conformance/cases/process.d.ts +2 -0
  48. package/dist/conformance/cases/process.js +240 -0
  49. package/dist/conformance/cases/provider.d.ts +2 -0
  50. package/dist/conformance/cases/provider.js +302 -0
  51. package/dist/conformance/cases/screen.d.ts +9 -0
  52. package/dist/conformance/cases/screen.js +230 -0
  53. package/dist/conformance/cases/settings.d.ts +57 -0
  54. package/dist/conformance/cases/settings.js +142 -0
  55. package/dist/conformance/cases/touch.d.ts +2 -0
  56. package/dist/conformance/cases/touch.js +117 -0
  57. package/dist/conformance/cases/util.d.ts +7 -0
  58. package/dist/conformance/cases/util.js +8 -0
  59. package/dist/conformance/cdp.d.ts +13 -0
  60. package/dist/conformance/cdp.js +88 -0
  61. package/dist/conformance/cli.d.ts +29 -0
  62. package/dist/conformance/cli.js +231 -0
  63. package/dist/conformance/daytona-sweep.d.ts +18 -0
  64. package/dist/conformance/daytona-sweep.js +118 -0
  65. package/dist/conformance/daytona.d.ts +83 -0
  66. package/dist/conformance/daytona.js +107 -0
  67. package/dist/conformance/docker.d.ts +38 -0
  68. package/dist/conformance/docker.js +70 -0
  69. package/dist/conformance/drift-daemon.d.ts +8 -0
  70. package/dist/conformance/drift-daemon.js +41 -0
  71. package/dist/conformance/e2b-diagnose.d.ts +16 -0
  72. package/dist/conformance/e2b-diagnose.js +61 -0
  73. package/dist/conformance/e2b-sweep.d.ts +18 -0
  74. package/dist/conformance/e2b-sweep.js +125 -0
  75. package/dist/conformance/e2b.d.ts +74 -0
  76. package/dist/conformance/e2b.js +111 -0
  77. package/dist/conformance/fixture.d.ts +65 -0
  78. package/dist/conformance/fixture.js +98 -0
  79. package/dist/conformance/index.d.ts +8 -0
  80. package/dist/conformance/index.js +8 -0
  81. package/dist/conformance/kernel.d.ts +31 -0
  82. package/dist/conformance/kernel.js +40 -0
  83. package/dist/conformance/kind.d.ts +23 -0
  84. package/dist/conformance/kind.js +58 -0
  85. package/dist/conformance/modal-sweep.d.ts +22 -0
  86. package/dist/conformance/modal-sweep.js +190 -0
  87. package/dist/conformance/modal.d.ts +69 -0
  88. package/dist/conformance/modal.js +76 -0
  89. package/dist/conformance/orgo.d.ts +41 -0
  90. package/dist/conformance/orgo.js +69 -0
  91. package/dist/conformance/phone-harness.d.ts +61 -0
  92. package/dist/conformance/phone-harness.js +241 -0
  93. package/dist/conformance/png.d.ts +16 -0
  94. package/dist/conformance/png.js +132 -0
  95. package/dist/conformance/report.d.ts +2 -0
  96. package/dist/conformance/report.js +86 -0
  97. package/dist/conformance/runner.d.ts +11 -0
  98. package/dist/conformance/runner.js +585 -0
  99. package/dist/conformance/tar.d.ts +13 -0
  100. package/dist/conformance/tar.js +105 -0
  101. package/dist/conformance/types.d.ts +257 -0
  102. package/dist/conformance/types.js +24 -0
  103. package/dist/daemon-copy.d.ts +40 -0
  104. package/dist/daemon-copy.js +259 -0
  105. package/dist/daytona.d.ts +178 -0
  106. package/dist/daytona.js +1484 -0
  107. package/dist/desktop.d.ts +24 -0
  108. package/dist/desktop.js +68 -0
  109. package/dist/docker/egress-main.d.ts +1 -0
  110. package/dist/docker/egress-main.js +68 -0
  111. package/dist/docker/egress-proxy.d.ts +53 -0
  112. package/dist/docker/egress-proxy.js +450 -0
  113. package/dist/docker/egress-table.d.ts +39 -0
  114. package/dist/docker/egress-table.js +197 -0
  115. package/dist/docker/egress.d.ts +109 -0
  116. package/dist/docker/egress.js +318 -0
  117. package/dist/docker/image.d.ts +49 -0
  118. package/dist/docker/image.js +302 -0
  119. package/dist/docker/stage.d.ts +21 -0
  120. package/dist/docker/stage.js +290 -0
  121. package/dist/docker/volume.d.ts +24 -0
  122. package/dist/docker/volume.js +67 -0
  123. package/dist/docker.d.ts +150 -0
  124. package/dist/docker.js +1200 -0
  125. package/dist/drift.d.ts +200 -0
  126. package/dist/drift.js +416 -0
  127. package/dist/e2b.d.ts +335 -0
  128. package/dist/e2b.js +1515 -0
  129. package/dist/entry.d.ts +2 -0
  130. package/dist/entry.js +24 -0
  131. package/dist/files.d.ts +50 -0
  132. package/dist/files.js +208 -0
  133. package/dist/index.d.ts +27 -0
  134. package/dist/index.js +26 -0
  135. package/dist/isolation.d.ts +29 -0
  136. package/dist/isolation.js +71 -0
  137. package/dist/janitor.d.ts +50 -0
  138. package/dist/janitor.js +135 -0
  139. package/dist/kernel.d.ts +113 -0
  140. package/dist/kernel.js +358 -0
  141. package/dist/kinds.d.ts +79 -0
  142. package/dist/kinds.js +133 -0
  143. package/dist/labels.d.ts +23 -0
  144. package/dist/labels.js +50 -0
  145. package/dist/modal.d.ts +302 -0
  146. package/dist/modal.js +1374 -0
  147. package/dist/mount-archil.d.ts +164 -0
  148. package/dist/mount-archil.js +471 -0
  149. package/dist/mount.d.ts +57 -0
  150. package/dist/mount.js +104 -0
  151. package/dist/orgo-channel.d.ts +96 -0
  152. package/dist/orgo-channel.js +391 -0
  153. package/dist/orgo.d.ts +139 -0
  154. package/dist/orgo.js +1006 -0
  155. package/dist/phone-harness.d.ts +185 -0
  156. package/dist/phone-harness.js +1420 -0
  157. package/dist/processes.d.ts +24 -0
  158. package/dist/processes.js +40 -0
  159. package/dist/protocol.d.ts +729 -0
  160. package/dist/protocol.js +54 -0
  161. package/dist/provider.d.ts +245 -0
  162. package/dist/provider.js +37 -0
  163. package/dist/providers.d.ts +68 -0
  164. package/dist/providers.js +25 -0
  165. package/dist/result.d.ts +15 -0
  166. package/dist/result.js +2 -0
  167. package/dist/screen-watch.d.ts +150 -0
  168. package/dist/screen-watch.js +490 -0
  169. package/dist/test-connection.d.ts +17 -0
  170. package/dist/test-connection.js +26 -0
  171. package/dist/wait.d.ts +23 -0
  172. package/dist/wait.js +65 -0
  173. package/package.json +64 -1
@@ -0,0 +1,49 @@
1
+ import { type Result } from "../result.js";
2
+ /** The repository every recipe's image is tagged in. */
3
+ export declare const IMAGE_REPOSITORY = "agentrun-computer";
4
+ /** The label a recipe's image carries: the recipe's whole sha256. A computer made from the image carries it too. */
5
+ export declare const RECIPE_LABEL = "agentrun.computer.recipe";
6
+ /** How long a flight, inspect and build or pull, may take before its docker is killed: 10 minutes. */
7
+ export declare const IMAGE_TIMEOUT_MS: number;
8
+ /** What the default image has, in words: serve's, for the timeline row a run shows while it is built. */
9
+ export declare const DOCKER_RECIPE_HAS = "python, git, curl, node, npm, rg";
10
+ /** The base the default image builds from: `python:3.12-slim`, pinned to the multi-arch index digest Docker Hub served
11
+ * for that tag on 2026-11-03, so a build gets the same base wherever it runs. To move it, read the tag's index digest
12
+ * again (an anonymous pull token from auth.docker.io for `repository:library/python:pull`, then a HEAD of
13
+ * registry-1.docker.io/v2/library/python/manifests/3.12-slim accepting an OCI index or a manifest list: its
14
+ * `docker-content-digest`), and put it here. The recipe's hash changes with it, and so does DEFAULT_DOCKER_IMAGE. */
15
+ export declare const DOCKER_BASE = "python:3.12-slim@sha256:b18b261e1b4974b4f321451ad5251ded85abb22c2b8b262da527dda1d031ab30";
16
+ /** The default image's recipe: python with git, curl, node, npm and rg for a model's tools, and socat, the relay to a
17
+ * computer's egress proxy when it has one. */
18
+ export declare const DOCKER_RECIPE: string;
19
+ /** Where an image comes from: a recipe, built here, or an image by name, pulled when Docker has none. */
20
+ export type ImageSource = {
21
+ recipe: string;
22
+ } | {
23
+ image: string;
24
+ };
25
+ export interface EnsureImageOptions {
26
+ /** The docker CLI. */
27
+ docker?: string;
28
+ /** Ends this caller's wait; the last caller's abort stops the build or pull. */
29
+ signal?: AbortSignal;
30
+ /** The flight's bound, when this call starts it; default IMAGE_TIMEOUT_MS. */
31
+ timeoutMs?: number;
32
+ /** Told once, before this caller waits on a build or pull, its own or one it joined; never when Docker has the image.
33
+ * A throw from it is ignored. */
34
+ onWait?: (making: Making, tag: string) => void;
35
+ }
36
+ /** What a flight does when Docker has no image of its source. */
37
+ export type Making = "build" | "pull";
38
+ export declare const recipeHash: (recipe: string) => string;
39
+ /** The tag a recipe's image has: the repository and the first 12 hex digits of the recipe's sha256. */
40
+ export declare const recipeTag: (recipe: string) => string;
41
+ /** The default image: the provider's own, built from DOCKER_RECIPE. */
42
+ export declare const DEFAULT_DOCKER_IMAGE: string;
43
+ /** Why source is not an image source, in words, or undefined when it is one. */
44
+ export declare function imageSourceProblem(source: unknown): string | undefined;
45
+ /**
46
+ * The image ready in Docker: its tag, for create's spec.image. A recipe is built when Docker has no image of it under its
47
+ * tag; an image by name is pulled when Docker has none. Concurrent callers share one flight; see the top of this file.
48
+ */
49
+ export declare function ensureImage(source: ImageSource, { docker, signal, timeoutMs, onWait }?: EnsureImageOptions): Promise<Result<string>>;
@@ -0,0 +1,302 @@
1
+ // The image a Docker computer starts from, made ready by the provider's own process: a recipe built once, or an image by
2
+ // name pulled once. There is no state file and no second process to wait on: Docker's own tag is the shared state.
3
+ //
4
+ // A recipe is a Dockerfile with no build context, built with `docker build -` (the recipe on stdin), tagged
5
+ // `agentrun-computer:<the first 12 hex digits of its sha256>` and labelled with the whole sha256 (RECIPE_LABEL). It is
6
+ // built only when Docker has no image under the tag, or has one of another recipe. Same recipe, same tag, same label: a
7
+ // build is idempotent. Two processes that both miss the tag both build, BuildKit sharing its cache. With Docker 29's
8
+ // containerd image store the first to tag wins and the others fail with "already exists"; with the classic store the
9
+ // last one wins. Either way a build or pull that fails asks Docker once more, and the tag on an image of this recipe is
10
+ // the answer. A computer made from an image that lost its tag keeps it, as Docker holds an image by its id. An image by
11
+ // name is pulled when Docker has none, and never built.
12
+ //
13
+ // In one process, concurrent callers share one flight per docker CLI and recipe (or image): the first starts it, the rest
14
+ // wait on it. A flight is forgotten once it settles, so a later call asks Docker again, and a failure is never kept: the
15
+ // next call tries again. One bound, the first caller's timeoutMs, covers a flight's inspect and its build or pull; past
16
+ // it, the docker CLI is killed. A caller's signal ends its own wait; when the last caller waiting aborts, the flight's
17
+ // docker is killed too. The words say what happened and the next step, and hold none of Docker's output: only the
18
+ // recipe's own failing step, or the line Docker could not parse, which the caller wrote.
19
+ import { execFile } from "node:child_process";
20
+ import { createHash } from "node:crypto";
21
+ import { fail, ok } from "../result.js";
22
+ /** The repository every recipe's image is tagged in. */
23
+ export const IMAGE_REPOSITORY = "agentrun-computer";
24
+ /** The label a recipe's image carries: the recipe's whole sha256. A computer made from the image carries it too. */
25
+ export const RECIPE_LABEL = "agentrun.computer.recipe";
26
+ /** How long a flight, inspect and build or pull, may take before its docker is killed: 10 minutes. */
27
+ export const IMAGE_TIMEOUT_MS = 10 * 60_000;
28
+ /** What the default image has, in words: serve's, for the timeline row a run shows while it is built. */
29
+ export const DOCKER_RECIPE_HAS = "python, git, curl, node, npm, rg";
30
+ /** The base the default image builds from: `python:3.12-slim`, pinned to the multi-arch index digest Docker Hub served
31
+ * for that tag on 2026-11-03, so a build gets the same base wherever it runs. To move it, read the tag's index digest
32
+ * again (an anonymous pull token from auth.docker.io for `repository:library/python:pull`, then a HEAD of
33
+ * registry-1.docker.io/v2/library/python/manifests/3.12-slim accepting an OCI index or a manifest list: its
34
+ * `docker-content-digest`), and put it here. The recipe's hash changes with it, and so does DEFAULT_DOCKER_IMAGE. */
35
+ export const DOCKER_BASE = "python:3.12-slim@sha256:b18b261e1b4974b4f321451ad5251ded85abb22c2b8b262da527dda1d031ab30";
36
+ /** The default image's recipe: python with git, curl, node, npm and rg for a model's tools, and socat, the relay to a
37
+ * computer's egress proxy when it has one. */
38
+ export const DOCKER_RECIPE = [
39
+ `FROM ${DOCKER_BASE}`,
40
+ "RUN apt-get update \\",
41
+ " && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends git curl ca-certificates nodejs npm ripgrep socat \\",
42
+ " && rm -rf /var/lib/apt/lists/*",
43
+ "",
44
+ ].join("\n");
45
+ export const recipeHash = (recipe) => createHash("sha256").update(recipe).digest("hex");
46
+ /** The tag a recipe's image has: the repository and the first 12 hex digits of the recipe's sha256. */
47
+ export const recipeTag = (recipe) => `${IMAGE_REPOSITORY}:${recipeHash(recipe).slice(0, 12)}`;
48
+ /** The default image: the provider's own, built from DOCKER_RECIPE. */
49
+ export const DEFAULT_DOCKER_IMAGE = recipeTag(DOCKER_RECIPE);
50
+ /** The longest delay Node's timers hold: 2^31 - 1 ms. */
51
+ const MAX_TIMER_MS = 2_147_483_647;
52
+ const SOURCE_WORDS = "an image source is { recipe } or { image }, one of them";
53
+ const RECIPE_WORDS = "a recipe is the text of a Dockerfile with a FROM line and no NUL byte; it is built with no context";
54
+ const IMAGE_WORDS = 'an image is a name such as debian:bookworm-slim: not empty, with no space or NUL byte, not starting with "-"';
55
+ const FROM = /^\s*FROM\s+(?:--\S+\s+)*(\S+)/im;
56
+ /** Docker says `No such image`; Podman, standing in for it, `image not known`. */
57
+ const MISSING = /no such image|image not known/i;
58
+ const NOT_RUNNING = /Cannot connect to the Docker daemon|Is the docker daemon running|permission denied while trying to connect/i;
59
+ const UNREACHABLE = /dial tcp|no such host|i\/o timeout|connection refused|network is unreachable|TLS handshake timeout|Client\.Timeout|Temporary failure resolving|Could not resolve|Could not connect/i;
60
+ const NO_BASE = /pull access denied|manifest unknown|not found: manifest|failed to resolve source metadata|failed to fetch anonymous token/i;
61
+ const NO_PACKAGE = /Unable to locate package|has no installation candidate|E: Package|unable to select packages/i;
62
+ const PARSE = /dockerfile parse error on line (\d+)/i;
63
+ /** A RUN step that failed, as BuildKit and as the legacy builder say it. */
64
+ const STEP = [/process "((?:[^"\\]|\\.)*)" did not complete successfully: exit code: (\d+)/, /The command '(.*?)' returned a non-zero code: (\d+)/];
65
+ const DENIED = /pull access denied|unauthorized|authentication required|denied:/i;
66
+ const NO_MANIFEST = /manifest unknown|manifest for .* not found|not found: manifest/i;
67
+ /** One flight per docker CLI and source, for as long as it runs. */
68
+ const flights = new Map();
69
+ /** Seconds or minutes, in words. */
70
+ const span = (ms) => (ms >= 60_000 && ms % 60_000 === 0 ? `${ms / 60_000} min` : ms < 1000 ? `${ms} ms` : `${Math.round(ms / 1000)} s`);
71
+ const exitOf = (answer) => (typeof answer.code === "number" ? `exit ${answer.code}` : answer.code);
72
+ /** Why source is not an image source, in words, or undefined when it is one. */
73
+ export function imageSourceProblem(source) {
74
+ const checked = sourceOf(source);
75
+ return typeof checked === "string" ? checked : undefined;
76
+ }
77
+ /** The source checked, with its tag (and a recipe's hash and base), or why it is not one. */
78
+ function sourceOf(source) {
79
+ const given = (typeof source === "object" && source !== null ? source : {});
80
+ if ((given.recipe === undefined) === (given.image === undefined))
81
+ return SOURCE_WORDS;
82
+ if (given.recipe !== undefined) {
83
+ const recipe = given.recipe;
84
+ const base = typeof recipe === "string" && !recipe.includes("\0") ? FROM.exec(recipe)?.[1] : undefined;
85
+ if (typeof recipe !== "string" || base === undefined)
86
+ return RECIPE_WORDS;
87
+ const hash = recipeHash(recipe);
88
+ return { kind: "recipe", recipe, hash, base, tag: `${IMAGE_REPOSITORY}:${hash.slice(0, 12)}` };
89
+ }
90
+ const image = given.image;
91
+ if (typeof image !== "string" || image === "" || image.startsWith("-") || /[\s\0]/.test(image))
92
+ return IMAGE_WORDS;
93
+ return { kind: "image", tag: image };
94
+ }
95
+ /**
96
+ * The image ready in Docker: its tag, for create's spec.image. A recipe is built when Docker has no image of it under its
97
+ * tag; an image by name is pulled when Docker has none. Concurrent callers share one flight; see the top of this file.
98
+ */
99
+ export async function ensureImage(source, { docker = "docker", signal, timeoutMs = IMAGE_TIMEOUT_MS, onWait } = {}) {
100
+ const checked = sourceOf(source);
101
+ if (typeof checked === "string")
102
+ return fail("invalid", checked);
103
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_MS) {
104
+ return fail("invalid", `timeoutMs must be a whole number of milliseconds above 0 and at most ${MAX_TIMER_MS}, not ${JSON.stringify(timeoutMs) ?? String(timeoutMs)}`);
105
+ }
106
+ if (signal?.aborted)
107
+ return fail("aborted", `the wait for ${checked.tag} was aborted before it began`);
108
+ const key = JSON.stringify([docker, checked.kind, checked.kind === "recipe" ? checked.hash : checked.tag]);
109
+ let flight = flights.get(key);
110
+ // A flight every caller left is stopping: a new caller starts its own.
111
+ if (flight === undefined || flight.controller.signal.aborted) {
112
+ const crew = { controller: new AbortController(), waiting: 0, toTell: new Set() };
113
+ const started = Object.assign(crew, { result: fly(docker, checked, timeoutMs, crew) });
114
+ flight = started;
115
+ flights.set(key, started);
116
+ void started.result.finally(() => {
117
+ if (flights.get(key) === started)
118
+ flights.delete(key);
119
+ });
120
+ }
121
+ const joined = flight;
122
+ joined.waiting += 1;
123
+ const tell = () => {
124
+ try {
125
+ if (joined.making !== undefined)
126
+ onWait?.(joined.making, checked.tag);
127
+ }
128
+ catch {
129
+ // The caller's listener is its own: a throw changes nothing here.
130
+ }
131
+ };
132
+ // The abort listener goes in before onWait is told, and the signal is read again after: an onWait that aborts its own
133
+ // caller's signal, told at once when the caller joins a build under way, is never missed.
134
+ let leave;
135
+ const settled = signal === undefined
136
+ ? joined.result
137
+ : new Promise((resolve) => {
138
+ let left = false;
139
+ const making = checked.kind === "recipe" ? "build" : "pull";
140
+ leave = () => {
141
+ if (left)
142
+ return;
143
+ left = true;
144
+ signal.removeEventListener("abort", onAbort);
145
+ joined.toTell.delete(tell);
146
+ joined.waiting -= 1;
147
+ if (joined.waiting > 0)
148
+ return resolve(fail("aborted", `the wait for ${checked.tag} was aborted; the ${making} goes on for the other callers waiting on it`));
149
+ joined.controller.abort();
150
+ resolve(fail("aborted", `the wait for ${checked.tag} was aborted, and the ${making}, which no other caller waited on, was stopped`));
151
+ };
152
+ const onAbort = () => leave?.();
153
+ signal.addEventListener("abort", onAbort, { once: true });
154
+ void joined.result.then((result) => {
155
+ if (left)
156
+ return;
157
+ left = true;
158
+ signal.removeEventListener("abort", onAbort);
159
+ resolve(result);
160
+ });
161
+ });
162
+ if (onWait !== undefined) {
163
+ if (joined.making !== undefined)
164
+ tell();
165
+ else
166
+ joined.toTell.add(tell);
167
+ }
168
+ if (signal?.aborted)
169
+ leave?.();
170
+ return settled;
171
+ }
172
+ /**
173
+ * The flight: inspect, then build or pull when Docker has no image of the source, all within timeoutMs. A build or pull
174
+ * that fails asks Docker once more: another process may have tagged the image first (Docker 29's containerd image store
175
+ * fails the loser of that race with "already exists"), and an image of this source under the tag is the answer.
176
+ */
177
+ async function fly(docker, source, timeoutMs, flight) {
178
+ const { controller } = flight;
179
+ let late = false;
180
+ const timer = setTimeout(() => {
181
+ late = true;
182
+ controller.abort();
183
+ }, timeoutMs);
184
+ const call = (args, input) => run(docker, args, controller.signal, () => late, input);
185
+ const inspect = () => call(["image", "inspect", "--format", "{{json .Config.Labels}}", source.tag]);
186
+ const ready = (answer) => answer.code === 0 && (source.kind === "image" || labelsOf(answer.stdout)[RECIPE_LABEL] === source.hash);
187
+ try {
188
+ const inspected = await inspect();
189
+ if (ready(inspected))
190
+ return ok(source.tag);
191
+ if (inspected.code !== 0 && !MISSING.test(inspected.stderr))
192
+ return inspectFailure(docker, source.tag, inspected, timeoutMs);
193
+ flight.making = source.kind === "image" ? "pull" : "build";
194
+ for (const tell of flight.toTell)
195
+ tell();
196
+ flight.toTell.clear();
197
+ // Every caller may have left while it was told (an onWait that aborts its own signal): then nothing is started.
198
+ if (controller.signal.aborted && !late)
199
+ return fail("aborted", "it was stopped before it began: no caller waits on it any more");
200
+ const made = source.kind === "image"
201
+ ? await call(["pull", "--quiet", source.tag])
202
+ : await call(["build", "--quiet", "--label", `${RECIPE_LABEL}=${source.hash}`, "--tag", source.tag, "-"], source.recipe);
203
+ if (made.code === 0)
204
+ return ok(source.tag);
205
+ if (typeof made.code === "number") {
206
+ const again = await inspect();
207
+ if (ready(again))
208
+ return ok(source.tag);
209
+ // The bound, or every caller's abort, stopped the second inspect: that is the answer, not the failure before it.
210
+ if (again.code === "timeout" || again.code === "aborted")
211
+ return inspectFailure(docker, source.tag, again, timeoutMs);
212
+ }
213
+ return source.kind === "image" ? pullFailure(docker, source.tag, made, timeoutMs) : buildFailure(docker, source, made, timeoutMs);
214
+ }
215
+ finally {
216
+ clearTimeout(timer);
217
+ }
218
+ }
219
+ /** `docker` with args, the input on its stdin, killed with SIGKILL when the signal aborts. */
220
+ function run(docker, args, signal, late, input) {
221
+ return new Promise((resolve) => {
222
+ const child = execFile(docker, args, { encoding: "utf8", signal, killSignal: "SIGKILL", maxBuffer: 32 * 1024 * 1024 }, (error, stdout, stderr) => {
223
+ if (error === null)
224
+ return resolve({ code: 0, stdout, stderr });
225
+ const failed = error;
226
+ const code = signal.aborted ? (late() ? "timeout" : "aborted") : typeof failed.code === "number" ? failed.code : (failed.code ?? failed.name);
227
+ resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
228
+ });
229
+ child.stdin?.on("error", () => undefined);
230
+ child.stdin?.end(input ?? "");
231
+ });
232
+ }
233
+ /** The labels `docker image inspect` gave, or none when it gave none. */
234
+ function labelsOf(stdout) {
235
+ try {
236
+ const value = JSON.parse(stdout.trim() || "null");
237
+ return value && typeof value === "object" ? value : {};
238
+ }
239
+ catch {
240
+ return {};
241
+ }
242
+ }
243
+ /** The failures every docker call shares: no CLI, the bound (in the words given), the last caller gone. */
244
+ function common(docker, answer, timedOut) {
245
+ if (answer.code === "ENOENT")
246
+ return fail("docker", `the docker CLI (${docker}) was not found`);
247
+ if (answer.code === "timeout")
248
+ return fail("timeout", timedOut);
249
+ if (answer.code === "aborted")
250
+ return fail("aborted", "it was stopped: no caller waits on it any more");
251
+ return undefined;
252
+ }
253
+ function inspectFailure(docker, tag, answer, timeoutMs) {
254
+ const shared = common(docker, answer, `docker image inspect ${tag} did not answer within ${span(timeoutMs)}, so it was stopped: call again`);
255
+ if (shared)
256
+ return shared;
257
+ if (NOT_RUNNING.test(answer.stderr))
258
+ return fail("docker", `Docker did not answer docker image inspect ${tag}: is it running, and may this user reach it?`);
259
+ return fail("docker", `docker image inspect ${tag} failed (${exitOf(answer)}): run it on this machine as this process's user to see why`);
260
+ }
261
+ function buildFailure(docker, source, answer, timeoutMs) {
262
+ const { tag, base } = source;
263
+ const shared = common(docker, answer, `the build of ${tag} did not finish within ${span(timeoutMs)}, so it was stopped: call again to build it again`);
264
+ if (shared)
265
+ return shared;
266
+ const said = answer.stderr;
267
+ if (/no space left on device/i.test(said))
268
+ return fail("docker", `the build of ${tag} ran out of disk space: free some, then call again`);
269
+ // A base that could not be fetched for want of a network says so in both ways: the network is the cause.
270
+ if (UNREACHABLE.test(said))
271
+ return fail("docker", `the build of ${tag} could not reach the network (it pulls ${base}): call again once this machine can reach it`);
272
+ if (NO_BASE.test(said))
273
+ return fail("docker", `the build of ${tag} could not pull its base, ${base}: name a base the registry has, or pull it on this machine first`);
274
+ if (NO_PACKAGE.test(said))
275
+ return fail("docker", `the recipe of ${tag} names a package its base's package manager could not install: check the names, then call again`);
276
+ const line = PARSE.exec(said)?.[1];
277
+ if (line !== undefined)
278
+ return fail("docker", `Docker could not parse the recipe of ${tag} at line ${line}: fix that line`);
279
+ for (const pattern of STEP) {
280
+ const step = pattern.exec(said);
281
+ if (step === null)
282
+ continue;
283
+ // The step is the recipe's own words, which the caller wrote: the shell's prefix off, BuildKit's quoting undone.
284
+ const command = (step[1] ?? "").replace(/\\(.)/g, "$1").replace(/^\/bin\/sh -c /, "").slice(0, 200);
285
+ return fail("docker", `the recipe of ${tag} failed at the step \`RUN ${command}\` with exit code ${step[2]}: fix that step`);
286
+ }
287
+ return fail("docker", `docker build of ${tag} failed (${exitOf(answer)}): run docker build with the recipe on this machine to see why`);
288
+ }
289
+ function pullFailure(docker, image, answer, timeoutMs) {
290
+ const see = `run docker pull ${image} on this machine to see why`;
291
+ const shared = common(docker, answer, `the pull of ${image} did not finish within ${span(timeoutMs)}, so it was stopped: run docker pull ${image} on this machine, or call again`);
292
+ if (shared)
293
+ return shared;
294
+ const said = answer.stderr;
295
+ if (DENIED.test(said))
296
+ return fail("docker", `the registry refused the pull of ${image} (no such repository, or it needs a docker login): ${see}`);
297
+ if (NO_MANIFEST.test(said))
298
+ return fail("docker", `the registry has no ${image}: name an image it has`);
299
+ if (UNREACHABLE.test(said))
300
+ return fail("docker", `the registry could not be reached to pull ${image}: ${see}`);
301
+ return fail("docker", `docker pull ${image} failed (${exitOf(answer)}): ${see}`);
302
+ }
@@ -0,0 +1,21 @@
1
+ import { type Result } from "../result.js";
2
+ import { type EgressCode } from "./egress.js";
3
+ import { type DockerVolume } from "./volume.js";
4
+ /** The daemon's tree for the daemon at `source`, staged in `directory`: its path and its subpath of the volume. */
5
+ export declare function daemonStage(source: string, directory: string, volume: DockerVolume): Result<{
6
+ path: string;
7
+ subpath: string;
8
+ }>;
9
+ /** The egress proxy's code staged in `directory`, as the proxy mounts it (EgressCode.volume). */
10
+ export declare function egressStage(code: EgressCode, directory: string, volume: DockerVolume): Result<EgressCode>;
11
+ /**
12
+ * Where the egress proxy's code staged in `directory` is, read only: for a read-back. Its `accepts` takes a mounted
13
+ * subpath that is any verified copy (verifiedTree), not only the one staging would use now: two providers that
14
+ * published copies beside a tree that no longer held each mounted their own, and both are as create makes one.
15
+ */
16
+ export declare function egressStaged(code: EgressCode, directory: string, volume: DockerVolume): Result<EgressCode>;
17
+ /**
18
+ * The daemon's tree a computer mounts at `subpath` of the volume, when it is a verified copy of the daemon at `source`
19
+ * (verifiedTree): its path. For the read-back of a computer mounted on a copy other than the one staging uses now.
20
+ */
21
+ export declare function daemonVerified(source: string, directory: string, volume: DockerVolume, subpath: string): string | undefined;
@@ -0,0 +1,290 @@
1
+ // What a provider with the volume option (src/docker/volume.ts) stages below the volume's root, so the Docker daemon can
2
+ // mount it as the volume's subpaths: paths of this process's own (the daemon's file, the egress proxy's code in this
3
+ // package's build) are not the daemon's when the provider runs in a container. Each is a DIRECTORY, mounted whole: Docker
4
+ // mounts a volume's subpath that is a directory on every engine that has volume-subpath, so nothing here leans on a file.
5
+ //
6
+ // - The daemon: `daemon-<sha256>/` holding `computerd` (0755) and an empty `egress/`, mounted read-only at /opt/agentrun,
7
+ // so the daemon is at DAEMON_IN_COMPUTER as on every computer, and an allowlist's egress volume has its mount point
8
+ // (EGRESS_MOUNT, /opt/agentrun/egress) in a tree Docker cannot write.
9
+ // - The egress proxy's code: `egress-<sha256>/` holding docker/ with the three modules and package.json beside it, the
10
+ // layout the proxy runs from, mounted read-only at /code.
11
+ //
12
+ // Each tree is in the provider's daemonCache, checked as daemonCopy checks its own (privateCacheDirectory), named by the
13
+ // sha256 of what it holds, its directories 0755 and its files 0644 (the daemon 0755); written in a temporary directory
14
+ // and renamed into place, and reused when one that holds the same is already there. A published tree is NEVER removed
15
+ // or written over: Docker may have it mounted in a running computer, which another provider sharing daemonCache could
16
+ // pull its daemon out from under. A name that holds a tree that does not hold the same is left as it is, and the new
17
+ // tree is published beside it (stageTree). A source is read only when it is a regular file, opened without blocking, so
18
+ // a named pipe at its path is refused in words, never waited on. Never throws: every failure is a Result in words.
19
+ import { createHash, randomBytes } from "node:crypto";
20
+ import { chmodSync, closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
21
+ import { dirname, join, resolve } from "node:path";
22
+ import { privateCacheDirectory } from "../daemon-copy.js";
23
+ import { fail, ok } from "../result.js";
24
+ import { CODE_FILES } from "./egress.js";
25
+ import { subpathOf } from "./volume.js";
26
+ const codeOf = (error) => error.code;
27
+ const wordsOf = (error) => error.message;
28
+ /** The sha256 over a tree's entries, in order: each one's path, mode and bytes. */
29
+ function shaOf(entries) {
30
+ const hash = createHash("sha256");
31
+ for (const { path, bytes, mode } of entries) {
32
+ hash.update(`${path}\0${mode.toString(8)}\0${bytes === undefined ? "dir" : bytes.length}\0`);
33
+ if (bytes !== undefined)
34
+ hash.update(bytes);
35
+ }
36
+ return hash.digest("hex");
37
+ }
38
+ /** Whether the tree at `at` holds every entry, with its mode and bytes; a link anywhere is not. */
39
+ function holds(at, entries) {
40
+ try {
41
+ const top = lstatSync(at);
42
+ if (!top.isDirectory() || (top.mode & 0o7777) !== 0o755)
43
+ return false;
44
+ for (const { path, bytes, mode } of entries) {
45
+ const stat = lstatSync(join(at, path));
46
+ if ((stat.mode & 0o7777) !== mode)
47
+ return false;
48
+ if (bytes === undefined ? !stat.isDirectory() : !stat.isFile() || !readFileSync(join(at, path)).equals(bytes))
49
+ return false;
50
+ }
51
+ return true;
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ /**
58
+ * The published tree in `dir` that holds `entries`: `<name>` itself, else a sibling `<name>-<random>` one was published
59
+ * under when `<name>` held a tree that did not. Undefined when none does.
60
+ */
61
+ function heldTree(dir, name, entries) {
62
+ const at = join(dir, name);
63
+ if (holds(at, entries))
64
+ return at;
65
+ let siblings;
66
+ try {
67
+ siblings = readdirSync(dir).filter((entry) => entry.startsWith(`${name}-`)).sort();
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ return siblings.map((entry) => join(dir, entry)).find((path) => holds(path, entries));
73
+ }
74
+ /**
75
+ * The tree `<prefix>-<sha>` in `directory`, made when none holding `entries` is there (see the head). A published tree
76
+ * is never removed or written over, since Docker may have it mounted in a running computer: the whole temporary tree is
77
+ * renamed into place only where nothing is (publish); when another writer published first, its tree is used if it
78
+ * holds; and when the name holds a tree that does not (a crash, a hand edit), the new one goes beside it.
79
+ */
80
+ function stageTree(directory, prefix, entries, what) {
81
+ const dir = privateCacheDirectory(directory);
82
+ if (!dir.ok)
83
+ return dir;
84
+ const sha = shaOf(entries);
85
+ const name = `${prefix}-${sha}`;
86
+ const at = join(dir.value, name);
87
+ const held = heldTree(dir.value, name, entries);
88
+ if (held !== undefined)
89
+ return ok(held);
90
+ const temp = join(dir.value, `.${prefix}-${sha}.${randomBytes(8).toString("hex")}.tmp`);
91
+ let published = at;
92
+ try {
93
+ mkdirSync(temp, { mode: 0o700 });
94
+ for (const { path, bytes, mode } of entries) {
95
+ const target = join(temp, path);
96
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
97
+ if (bytes === undefined) {
98
+ mkdirSync(target, { recursive: true, mode: 0o700 });
99
+ chmodSync(target, mode);
100
+ continue;
101
+ }
102
+ const fd = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
103
+ try {
104
+ writeFileSync(fd, bytes);
105
+ // fchmod is not narrowed by the umask.
106
+ fchmodSync(fd, mode);
107
+ fsyncSync(fd);
108
+ }
109
+ finally {
110
+ closeSync(fd);
111
+ }
112
+ }
113
+ // Each directory a file is in is 0755, the top last.
114
+ for (const { path } of entries)
115
+ for (let up = dirname(path); up !== "."; up = dirname(up))
116
+ chmodSync(join(temp, up), 0o755);
117
+ chmodSync(temp, 0o755);
118
+ published = publish(temp, at, entries);
119
+ }
120
+ catch (error) {
121
+ return fail("invalid", `cannot stage ${what} in ${at}: ${wordsOf(error)}`);
122
+ }
123
+ finally {
124
+ // Only the temporary tree, which no one else has seen, is ever removed; once renamed it is no longer here.
125
+ rmSync(temp, { recursive: true, force: true });
126
+ }
127
+ return holds(published, entries) ? ok(published) : fail("invalid", `${what} staged in ${published} did not hold its files, 0755 directories and its modes, once written`);
128
+ }
129
+ /**
130
+ * The whole temporary tree `temp` renamed into place at `at`, where nothing is: its path. When `at` is taken (another
131
+ * writer published first, or a tree that does not hold is there; a rename onto a directory that is not empty fails with
132
+ * EEXIST or ENOTEMPTY and leaves it as it was), the tree at `at` is used when it holds, and otherwise `temp` is published
133
+ * beside it under a fresh name. Nothing already published is ever removed or written over.
134
+ */
135
+ function publish(temp, at, entries) {
136
+ try {
137
+ renameSync(temp, at);
138
+ return at;
139
+ }
140
+ catch (error) {
141
+ if (!["EEXIST", "ENOTEMPTY"].includes(codeOf(error) ?? ""))
142
+ throw error;
143
+ }
144
+ if (holds(at, entries))
145
+ return at;
146
+ const beside = `${at}-${randomBytes(8).toString("hex")}`;
147
+ renameSync(temp, beside);
148
+ return beside;
149
+ }
150
+ /** Where the tree for `entries` is in `directory` (the published one that holds them, as stageTree would use it), or
151
+ * would be: read only, for a read-back. */
152
+ function treeAt(directory, prefix, entries) {
153
+ let base;
154
+ try {
155
+ base = realpathSync(directory);
156
+ }
157
+ catch {
158
+ base = resolve(directory);
159
+ }
160
+ const name = `${prefix}-${shaOf(entries)}`;
161
+ return heldTree(base, name, entries) ?? join(base, name);
162
+ }
163
+ /**
164
+ * The bytes of the regular file at `path`, as daemonCopy reads the daemon: opened with O_NONBLOCK, so a named pipe with
165
+ * no writer is not waited on, and checked to be a regular file before it is read. Anything else is refused in words;
166
+ * `what` names it, and `missing` is the advice when it is not there.
167
+ */
168
+ function readRegular(path, what, missing) {
169
+ const notFile = () => fail("not_found", `${what} at ${path} is not a regular file: ${missing}`);
170
+ let fd;
171
+ try {
172
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
173
+ }
174
+ catch (error) {
175
+ const code = codeOf(error);
176
+ return code === "ENOENT" || code === "ENOTDIR" ? fail("not_found", `${what} at ${path} is not there: ${missing}`) : fail("invalid", `${what} at ${path} cannot be read (${code ?? wordsOf(error)})`);
177
+ }
178
+ try {
179
+ if (!fstatSync(fd).isFile())
180
+ return notFile();
181
+ return ok(readFileSync(fd));
182
+ }
183
+ catch (error) {
184
+ return fail("invalid", `${what} at ${path} cannot be read (${codeOf(error) ?? wordsOf(error)})`);
185
+ }
186
+ finally {
187
+ closeSync(fd);
188
+ }
189
+ }
190
+ /** The daemon's tree's entries: computerd, 0755, read from `source`, and the egress volume's mount point. */
191
+ function daemonEntries(source) {
192
+ const bytes = readRegular(source, "the daemon", "run npm run build:daemon -w @parcha/agentrun-computer");
193
+ if (!bytes.ok)
194
+ return bytes;
195
+ return ok([
196
+ { path: "computerd", bytes: bytes.value, mode: 0o755 },
197
+ { path: "egress", mode: 0o755 },
198
+ ]);
199
+ }
200
+ /** The proxy's tree's entries: docker/<module> (0644) and package.json (0644), read from this package's build. */
201
+ function egressEntries(code) {
202
+ const entries = [];
203
+ for (const [path, source] of [...CODE_FILES.map((file) => [`docker/${file}`, join(code.dir, file)]), ["package.json", code.packageJson]]) {
204
+ const bytes = readRegular(source, "the egress proxy's code", "build it: npm run build -w @parcha/agentrun-computer");
205
+ if (!bytes.ok)
206
+ return bytes;
207
+ entries.push({ path, bytes: bytes.value, mode: 0o644 });
208
+ }
209
+ return ok(entries);
210
+ }
211
+ /** A staged tree's subpath of the volume, or a refusal: it must be below the root (daemonCache is). */
212
+ function below(volume, at, what) {
213
+ const subpath = subpathOf(volume, at);
214
+ return subpath === undefined ? fail("refused", `${what} staged in ${at} is not below the provider's volume root ${volume.root}`) : ok(subpath);
215
+ }
216
+ /** The daemon's tree for the daemon at `source`, staged in `directory`: its path and its subpath of the volume. */
217
+ export function daemonStage(source, directory, volume) {
218
+ const entries = daemonEntries(source);
219
+ if (!entries.ok)
220
+ return entries;
221
+ const at = stageTree(directory, "daemon", entries.value, "the daemon");
222
+ if (!at.ok)
223
+ return at;
224
+ const subpath = below(volume, at.value, "the daemon");
225
+ return subpath.ok ? ok({ path: at.value, subpath: subpath.value }) : subpath;
226
+ }
227
+ /** The egress proxy's code staged in `directory`, as the proxy mounts it (EgressCode.volume). */
228
+ export function egressStage(code, directory, volume) {
229
+ const entries = egressEntries(code);
230
+ if (!entries.ok)
231
+ return entries;
232
+ const at = stageTree(directory, "egress", entries.value, "the egress proxy's code");
233
+ if (!at.ok)
234
+ return at;
235
+ return codeAt(volume, at.value);
236
+ }
237
+ /**
238
+ * Where the egress proxy's code staged in `directory` is, read only: for a read-back. Its `accepts` takes a mounted
239
+ * subpath that is any verified copy (verifiedTree), not only the one staging would use now: two providers that
240
+ * published copies beside a tree that no longer held each mounted their own, and both are as create makes one.
241
+ */
242
+ export function egressStaged(code, directory, volume) {
243
+ const entries = egressEntries(code);
244
+ if (!entries.ok)
245
+ return entries;
246
+ const found = codeAt(volume, treeAt(directory, "egress", entries.value));
247
+ if (!found.ok || found.value.volume === undefined)
248
+ return found;
249
+ const accepts = (subpath) => subpath === found.value.volume?.root || verifiedTree(directory, "egress", entries.value, volume, subpath) !== undefined;
250
+ return ok({ ...found.value, volume: { ...found.value.volume, accepts } });
251
+ }
252
+ /**
253
+ * The daemon's tree a computer mounts at `subpath` of the volume, when it is a verified copy of the daemon at `source`
254
+ * (verifiedTree): its path. For the read-back of a computer mounted on a copy other than the one staging uses now.
255
+ */
256
+ export function daemonVerified(source, directory, volume, subpath) {
257
+ const entries = daemonEntries(source);
258
+ return entries.ok ? verifiedTree(directory, "daemon", entries.value, volume, subpath) : undefined;
259
+ }
260
+ /**
261
+ * The tree at `subpath` of the volume when it is a published copy of `entries` in `directory`: named `<prefix>-<sha>`
262
+ * or `<prefix>-<sha>-<anything>` (a copy published beside one that no longer held), directly in the staging directory,
263
+ * and holding every entry with its bytes and modes, as heldTree checks. Its path; else undefined.
264
+ */
265
+ function verifiedTree(directory, prefix, entries, volume, subpath) {
266
+ let base;
267
+ try {
268
+ base = realpathSync(directory);
269
+ }
270
+ catch {
271
+ base = resolve(directory);
272
+ }
273
+ const staging = subpathOf(volume, base, { orRoot: true });
274
+ const parts = subpath.split("/");
275
+ const leaf = parts.pop() ?? "";
276
+ if (staging === undefined || parts.join("/") !== staging || parts.includes("..") || parts.includes("."))
277
+ return undefined;
278
+ const name = `${prefix}-${shaOf(entries)}`;
279
+ if (leaf !== name && !leaf.startsWith(`${name}-`))
280
+ return undefined;
281
+ const path = join(base, leaf);
282
+ return holds(path, entries) ? path : undefined;
283
+ }
284
+ /** The staged proxy tree at `at` as an EgressCode: its own paths, and its subpath of the volume. */
285
+ function codeAt(volume, at) {
286
+ const subpath = below(volume, at, "the egress proxy's code");
287
+ if (!subpath.ok)
288
+ return subpath;
289
+ return ok({ dir: join(at, "docker"), packageJson: join(at, "package.json"), volume: { name: volume.name, root: subpath.value } });
290
+ }