@parcha/agentrun-serve 0.1.0-beta.32 → 0.1.0-beta.33

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 (163) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +78 -46
  3. package/dist/adapters.d.ts +0 -3
  4. package/dist/adapters.js +0 -7
  5. package/dist/agents.d.ts +1 -1
  6. package/dist/api-only.d.ts +14 -0
  7. package/dist/api-only.js +33 -0
  8. package/dist/archil-routes.d.ts +1 -1
  9. package/dist/box-egress-vm.d.ts +0 -8
  10. package/dist/box-egress-vm.js +0 -10
  11. package/dist/box-egress.d.ts +0 -4
  12. package/dist/box-egress.js +1 -16
  13. package/dist/box-paths.d.ts +25 -2
  14. package/dist/box-paths.js +79 -11
  15. package/dist/box-relay.d.ts +0 -11
  16. package/dist/box-relay.js +0 -20
  17. package/dist/box-settings.d.ts +46 -0
  18. package/dist/box-settings.js +107 -0
  19. package/dist/boxes.d.ts +4 -1
  20. package/dist/browser-cost.js +2 -1
  21. package/dist/browser-person.d.ts +0 -2
  22. package/dist/browser-person.js +0 -2
  23. package/dist/budget.d.ts +0 -4
  24. package/dist/budget.js +0 -7
  25. package/dist/cap.d.ts +0 -7
  26. package/dist/cap.js +0 -22
  27. package/dist/cli.js +23 -8
  28. package/dist/computers.d.ts +1 -1
  29. package/dist/console/assets/index-Dn0ngwG9.js +535 -0
  30. package/dist/console/assets/index-DvW6Aled.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/daytona-api.d.ts +0 -11
  33. package/dist/daytona-api.js +1 -82
  34. package/dist/docker-host-addresses.d.ts +37 -0
  35. package/dist/docker-host-addresses.js +110 -0
  36. package/dist/files.d.ts +0 -8
  37. package/dist/files.js +0 -17
  38. package/dist/github-connection.d.ts +1 -1
  39. package/dist/github-connection.js +1 -1
  40. package/dist/harness-install.d.ts +23 -0
  41. package/dist/harness-install.js +99 -4
  42. package/dist/harness.d.ts +4 -3
  43. package/dist/harness.js +16 -1
  44. package/dist/import.js +52 -13
  45. package/dist/learn/secrets.d.ts +2 -1
  46. package/dist/learn/secrets.js +19 -6
  47. package/dist/learned-workflow.d.ts +5 -4
  48. package/dist/learned-workflow.js +6 -3
  49. package/dist/learning-routes.d.ts +9 -46
  50. package/dist/learning-routes.js +25 -29
  51. package/dist/learning-run.d.ts +4 -231
  52. package/dist/learning-run.js +7 -651
  53. package/dist/live/translate.js +1 -1
  54. package/dist/mcp-gateway.d.ts +0 -3
  55. package/dist/mcp-gateway.js +0 -13
  56. package/dist/mcp-probe.d.ts +2 -2
  57. package/dist/mcp-probe.js +2 -2
  58. package/dist/mcp-servers-store.js +1 -1
  59. package/dist/openapi.js +3 -3
  60. package/dist/page.js +3 -1
  61. package/dist/paid-calls.js +3 -2
  62. package/dist/pause.d.ts +0 -2
  63. package/dist/pause.js +1 -8
  64. package/dist/place.d.ts +0 -5
  65. package/dist/place.js +0 -10
  66. package/dist/print.d.ts +2 -1
  67. package/dist/print.js +4 -2
  68. package/dist/run-db.d.ts +0 -2
  69. package/dist/run-db.js +0 -4
  70. package/dist/run-learning-served.d.ts +38 -0
  71. package/dist/run-learning-served.js +9 -0
  72. package/dist/run-secrets.d.ts +33 -0
  73. package/dist/run-secrets.js +53 -0
  74. package/dist/run-timeline-served.js +5 -2
  75. package/dist/run-view.d.ts +5 -9
  76. package/dist/run-view.js +4 -22
  77. package/dist/runner/adapter-loop.d.ts +8 -2
  78. package/dist/runner/adapter-loop.js +44 -12
  79. package/dist/runner/adapter-run-spec.d.ts +8 -0
  80. package/dist/runner/adapter-run-spec.js +6 -5
  81. package/dist/runner/adapters/pi.d.ts +4 -0
  82. package/dist/runner/adapters/pi.js +4 -1
  83. package/dist/runner/beside.js +19 -8
  84. package/dist/runner/claim-secrets.js +1 -1
  85. package/dist/runner/cli-run-spec.js +15 -1
  86. package/dist/runner/journal-kinds.d.ts +6 -0
  87. package/dist/runner/live-ticker.d.ts +1 -1
  88. package/dist/runner/live-ticker.js +28 -4
  89. package/dist/runner/loop-contract.d.ts +3 -2
  90. package/dist/runner/main.d.ts +11 -4
  91. package/dist/runner/main.js +39 -10
  92. package/dist/runner/mcp-claim.d.ts +1 -1
  93. package/dist/runner/mcp-claim.js +1 -1
  94. package/dist/runner/model-route.js +21 -2
  95. package/dist/runner/redact.d.ts +8 -2
  96. package/dist/runner/redact.js +11 -2
  97. package/dist/runner/workflow-spec.js +5 -9
  98. package/dist/runs-over-store.d.ts +1 -1
  99. package/dist/runs-over-store.js +16 -5
  100. package/dist/seal-key.d.ts +54 -15
  101. package/dist/seal-key.js +272 -84
  102. package/dist/sealed-settings.d.ts +2 -2
  103. package/dist/sealed-settings.js +3 -10
  104. package/dist/secrets.d.ts +2 -10
  105. package/dist/secrets.js +21 -17
  106. package/dist/server-secrets-store.js +1 -1
  107. package/dist/server-secrets.js +3 -0
  108. package/dist/server.d.ts +10 -6
  109. package/dist/server.js +89 -41
  110. package/dist/store/index.d.ts +1 -1
  111. package/dist/store/index.js +1 -1
  112. package/dist/store/open.d.ts +12 -2
  113. package/dist/store/open.js +23 -3
  114. package/dist/store/postgres/migrate.js +18 -1
  115. package/dist/store/sqlite/store.js +23 -8
  116. package/dist/store/store.d.ts +3 -0
  117. package/dist/store-reads/journal.d.ts +16 -0
  118. package/dist/store-reads/journal.js +82 -6
  119. package/dist/store-view.js +38 -5
  120. package/dist/tool-keys.d.ts +4 -3
  121. package/dist/tool-keys.js +7 -4
  122. package/dist/tools.d.ts +1 -1
  123. package/dist/tools.js +4 -1
  124. package/dist/trigger-schedule.js +2 -1
  125. package/dist/trigger-secrets-shown.js +5 -1
  126. package/dist/workspace/computer-deps.d.ts +29 -0
  127. package/dist/workspace/computer-deps.js +48 -1
  128. package/dist/workspace/computer-for-claim.d.ts +7 -3
  129. package/dist/workspace/computer-for-claim.js +1 -1
  130. package/dist/workspace/computer-providers.d.ts +6 -2
  131. package/dist/workspace/computer-providers.js +1 -1
  132. package/dist/workspace/index.d.ts +1 -1
  133. package/dist/workspace/index.js +1 -1
  134. package/dist/workspace.d.ts +0 -3
  135. package/dist/workspace.js +0 -3
  136. package/launcher/agentrun-serve +6 -33
  137. package/package.json +14 -14
  138. package/templates/inbound-lead/agent.md +1 -1
  139. package/templates/kyb/agent.md +1 -1
  140. package/dist/app.d.ts +0 -5
  141. package/dist/app.js +0 -514
  142. package/dist/bounds.d.ts +0 -26
  143. package/dist/bounds.js +0 -137
  144. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  145. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  146. package/dist/content-filter.d.ts +0 -7
  147. package/dist/content-filter.js +0 -23
  148. package/dist/disk.d.ts +0 -33
  149. package/dist/disk.js +0 -85
  150. package/dist/door-line.d.ts +0 -23
  151. package/dist/door-line.js +0 -83
  152. package/dist/harness-app.d.ts +0 -69
  153. package/dist/harness-app.js +0 -1162
  154. package/dist/request-start.d.ts +0 -27
  155. package/dist/request-start.js +0 -381
  156. package/dist/run-box.d.ts +0 -205
  157. package/dist/run-box.js +0 -661
  158. package/dist/run-holder.d.ts +0 -52
  159. package/dist/run-holder.js +0 -139
  160. package/dist/runs.d.ts +0 -1200
  161. package/dist/runs.js +0 -4103
  162. package/dist/served-only.d.ts +0 -5
  163. package/dist/served-only.js +0 -12
package/dist/run-box.js DELETED
@@ -1,661 +0,0 @@
1
- // A sandbox run's box: one per run, made on the first call that runs in it and labelled with the run's id, so the label
2
- // is the record (a bound box's read, write and edit run on this machine: bound-files.ts). A Docker box is labelled with
3
- // the epoch of the claim its process holds too (EPOCH_LABEL): a run's process that starts again, under a later epoch,
4
- // destroys every box of the run of an earlier one before it makes its own, and its model is told once that the box was
5
- // replaced (BOX_REPLACED_NOTE). Serve destroys it at
6
- // every settle (a cancel included) and at archive, and its start sweeps the boxes of runs that have ended. A box gets the
7
- // run's work/ only, at BOX_WORK, a fixed environment (never this process's, so no key or token enters it), no network
8
- // (or, on Docker with the server's host list set, those hosts alone, through this process's egress proxy: box-egress.ts),
9
- // and limits on its CPUs, memory and processes. pi-transport is an optional peer of this package: it is loaded only for a
10
- // run whose place is a box.
11
- //
12
- // Docker's box is made here, in the run's process, as this server's user, with work/ bound. A Daytona box is remote: it
13
- // cannot bind work/, and its key is the server's alone. The server makes it (through the box relay, box-relay.ts), seeds
14
- // it with work/, pulls work/ back at each turn's end and once more before the run's end is recorded, and destroys it
15
- // after that pull; the run's process reaches it through the relay, which holds the key. What the run's own host tools
16
- // file in work/ meanwhile (writeInWork) is copied into the box too, so its tools read it. The VM box is remote the same
17
- // way: the server makes, seeds, pulls and ends it with its own client, and the run's process runs pi-transport's VM
18
- // provider over the relay's VM half (box-relay-vm.ts), which holds the client and the token. It has no network.
19
- import { createHash } from "node:crypto";
20
- import { appendFile, lstat, readFile, realpath, rm, writeFile } from "node:fs/promises";
21
- import { isAbsolute, join, posix, relative, sep } from "node:path";
22
- import { pathToFileURL } from "node:url";
23
- import { BACKGROUND_CONTEXT as BACKGROUND } from "@earendil-works/chord/context";
24
- import { EGRESS_MOUNT, egressBlockedBy, forwarderStart, hostEgress, PROXY_ENV, relayFailed, runBoxAllowOf } from "./box-egress.js";
25
- import { runBoxVolumeOf, vmDocker, vmEgress } from "./box-egress-vm.js";
26
- import { awaitImage, boxImageOf } from "./box-image.js";
27
- import { egressParentOf, runBoxPathsOf } from "./box-paths.js";
28
- import { RELAYED_KEY, relayedBox, relayFetch } from "./box-relay.js";
29
- import { VM_PROVIDER } from "./boxes.js";
30
- import { readJson, writeDurable } from "./files.js";
31
- import { FAUX_ENV } from "./model.js";
32
- import { agentWorkDir, BOX_WORK } from "./place.js";
33
- /** The label a run's box carries: the run's id. */
34
- export const RUN_LABEL = "agentrun.run";
35
- /** And, on a box made with a network list, this one: the list's hash (netLabelOf). A box with none carries no such label,
36
- * so its `docker run` is as it was. */
37
- export const NET_LABEL = "agentrun.net";
38
- /** The network label's value for a list: the same hosts give the same label, in whatever order and case the setting
39
- * names them, each once. */
40
- export const netLabelOf = (allow) => createHash("sha256").update([...new Set(allow.map((host) => host.toLowerCase()))].sort().join(",")).digest("hex").slice(0, 16);
41
- /** And this one, the same on every run's box, which the start's sweep lists them by. */
42
- export const KIND_LABEL = "agentrun.box";
43
- /** And, on a Docker box, the epoch of the run's claim its process held when it made it (runs.ts launch, RUN_EPOCH_ENV). */
44
- export const EPOCH_LABEL = "agentrun.epoch";
45
- /** What a run's model is told, once, after its process made a new box in place of the one an earlier process left: the
46
- * run's files are the same, but whatever the old box held outside them is not. */
47
- export const BOX_REPLACED_NOTE = "this run's box was replaced after a restart: /workspace is kept; packages installed outside it and /tmp are gone; reinstall what you need";
48
- /** The whole environment of a box's programs: a constant, never this process's. */
49
- export const BOX_ENV = Object.freeze({ LANG: "C.UTF-8", HOME: "/tmp" });
50
- /** How long a box lives whatever happens to the server: a bound on a leaked box, never its clean end. */
51
- export const BOX_LIFETIME_MS = 24 * 60 * 60_000;
52
- /** A box command's deadline when its call names none: bash's own default (coding-tools.ts BASH_DEFAULT_TIMEOUT_S), which
53
- * bash always names, so this is the backstop for any other command. */
54
- export const BASH_TIMEOUT_MS = 120_000;
55
- /** The image a Docker box starts from (box-image.ts, where the server makes it ready). */
56
- export { DEFAULT_DOCKER_IMAGE, DOCKER_IMAGE_ENV } from "./box-image.js";
57
- /** The settings that bound a Docker box; unset, their defaults: enough for a build, and safe on a laptop, where one run's
58
- * runaway build or fork bomb would otherwise starve everything else. */
59
- export const BOX_CPUS_ENV = "AGENTRUN_BOX_CPUS";
60
- export const BOX_MEMORY_ENV = "AGENTRUN_BOX_MEMORY";
61
- export const BOX_PIDS_ENV = "AGENTRUN_BOX_PIDS";
62
- /** 2 CPUs' time: a CFS quota (pi-transport's Docker provider), which holds whatever CPU count Docker's VM has. */
63
- export const DEFAULT_BOX_CPUS = 2;
64
- /** 4 GiB, swap included (--memory-swap the same). */
65
- export const DEFAULT_BOX_MEMORY = "4g";
66
- /** Processes and threads at once. */
67
- export const DEFAULT_BOX_PIDS = 1024;
68
- /** The fewest CPUs a quota gives: the kernel's least quota is 1 ms of each 100 ms period. A quota is also a whole number of
69
- * µs, so a count too large for one (or a long string of digits, which reads as Infinity) is refused too. */
70
- const MIN_BOX_CPUS = 0.01;
71
- const MIB = 1024 * 1024;
72
- /** A size's units as Docker reads them, each 1024 of the one before. */
73
- const SIZE_UNITS = { b: 1, k: 1024, m: MIB, g: 1024 * MIB };
74
- /** The least memory Docker gives a container. */
75
- const MIN_BOX_MEMORY = 6 * MIB;
76
- /** The most processes a cgroup may be given (the kernel's PID_MAX_LIMIT); above it, every create fails. */
77
- const MAX_BOX_PIDS = 4_194_304;
78
- /** A Docker box's limits from `env`: each setting's value, or its default when unset or empty. A value that is not one, or
79
- * that every create would fail on (less than a 1 ms quota, less memory than Docker gives, more processes than the kernel
80
- * allows), throws, naming its setting: the start checks them (startServe), so no run meets one. */
81
- export function boxLimitsOf(env) {
82
- const read = (name, what, takes) => {
83
- const value = env[name];
84
- if (!value)
85
- return undefined;
86
- if (!takes(value))
87
- throw new Error(`${name} is ${what}; it is ${JSON.stringify(value)}`);
88
- return value;
89
- };
90
- const cpus = read(BOX_CPUS_ENV, "a number of CPUs of at least 0.01, such as 2 or 1.5", (value) => /^\d+(\.\d+)?$/.test(value) && Number(value) >= MIN_BOX_CPUS && Number.isSafeInteger(Math.round(Number(value) * 100_000)));
91
- const memory = read(BOX_MEMORY_ENV, "a size of at least 6m with its unit (b, k, m or g), such as 512m or 4g", (value) => {
92
- const size = /^(\d+(?:\.\d+)?)([bkmg])$/i.exec(value);
93
- // Its bytes as Docker reads them, and pi-transport's Docker provider: the number times the unit, the fraction dropped.
94
- const bytes = size ? Math.floor(Number(size[1]) * SIZE_UNITS[size[2].toLowerCase()]) : 0;
95
- return Number.isSafeInteger(bytes) && bytes >= MIN_BOX_MEMORY;
96
- });
97
- const pids = read(BOX_PIDS_ENV, "a whole number from 1 to 4194304, such as 1024", (value) => /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= MAX_BOX_PIDS);
98
- return { cpus: cpus === undefined ? DEFAULT_BOX_CPUS : Number(cpus), memory: memory ?? DEFAULT_BOX_MEMORY, pidsLimit: pids === undefined ? DEFAULT_BOX_PIDS : Number(pids) };
99
- }
100
- /** The setting that names the hosts a box may reach: a comma list of hosts, each a name or `*.` and a name, which
101
- * replaces the default list; `none` for no network at all. Unset or empty, the default. */
102
- export const BOX_ALLOW_ENV = "AGENTRUN_BOX_ALLOW";
103
- /** The hosts a box reaches when the setting names none: the package registries pip and npm (and yarn) install from, and
104
- * GitHub for a clone or an archive. */
105
- export const DEFAULT_BOX_ALLOW = Object.freeze(["pypi.org", "files.pythonhosted.org", "registry.npmjs.org", "registry.yarnpkg.com", "github.com", "codeload.github.com"]);
106
- /** The most hosts the list may hold: Daytona's own limit on a sandbox's domain list. */
107
- export const MAX_BOX_ALLOW = 100;
108
- /** A host name, or `*.` and one: letters, digits and hyphens in dotted labels, the last one starting with a letter, so no
109
- * IP address is one. */
110
- const ALLOW_HOST = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
111
- /** The hosts a box may reach, from `env`'s AGENTRUN_BOX_ALLOW: its list, lower-cased, each host once; the default list when
112
- * unset or empty; `none` for no network. `*`, an IP address, a CIDR, a port, a URL, or more than 100 hosts throws, saying
113
- * what the setting takes: the start checks it (startServe), so no run meets one. */
114
- export function boxAllowOf(env) {
115
- const value = (env[BOX_ALLOW_ENV] ?? "").trim();
116
- if (!value)
117
- return DEFAULT_BOX_ALLOW;
118
- if (value.toLowerCase() === "none")
119
- return "none";
120
- const hosts = [...new Set(value.split(",").map((host) => host.trim().toLowerCase()).filter(Boolean))];
121
- const takes = "a comma list of host names (such as pypi.org or *.pythonhosted.org), or none for no network";
122
- const bad = hosts.find((host) => !ALLOW_HOST.test(host));
123
- if (bad !== undefined)
124
- throw new Error(`${BOX_ALLOW_ENV} is ${takes}: ${JSON.stringify(bad)} is not a host name${bad === "*" ? " (a box never reaches every host)" : ""}`);
125
- if (hosts.length === 0)
126
- throw new Error(`${BOX_ALLOW_ENV} is ${takes}; it is ${JSON.stringify(value)}`);
127
- if (hosts.length > MAX_BOX_ALLOW)
128
- throw new Error(`${BOX_ALLOW_ENV} names ${hosts.length} hosts; it takes at most ${MAX_BOX_ALLOW}`);
129
- return Object.freeze(hosts);
130
- }
131
- /** What a server's Docker boxes reach, resolved once at its start: the setting's list (boxAllowOf) where egressBlockedBy
132
- * (box-egress.ts) finds the daemon is this Linux machine's own, else none with the reason; `none` from the setting, with
133
- * it as the reason. */
134
- export async function boxNetworkOf(env, options = {}) {
135
- const allow = boxAllowOf(env);
136
- if (allow === "none")
137
- return { allow: "none", reason: `${BOX_ALLOW_ENV} is none` };
138
- const blocked = await egressBlockedBy(env, options);
139
- if (!blocked)
140
- return { allow };
141
- // On a Mac only: a Docker that docker info names as a VM runtime this server knows gets the proxy container
142
- // (box-egress-vm.ts); any other stays none, saying why.
143
- if ((options.platform ?? process.platform) !== "darwin")
144
- return { allow: "none", reason: blocked };
145
- const vm = await vmDocker(env, { ...(options.platform ? { platform: options.platform } : {}), ...(options.kernel ? { kernel: options.kernel } : {}), ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}) });
146
- return "runtime" in vm ? { allow, vm: vm.runtime } : { allow: "none", reason: vm.reason };
147
- }
148
- /** Under `--faux` only: a module whose default export, given the data root, is the provider runs' boxes come from in
149
- * place of Docker (the tests' faux box). */
150
- export const FAUX_BOX_ENV = "AGENTRUN_SERVE_FAUX_BOX";
151
- /** A remote box's sync mark in its run's directory: the box's id and the listing its seed or last pull left. The
152
- * server alone writes it. */
153
- export const BOX_SYNC_FILE = "box-sync.json";
154
- /** What the run's process copied into its remote box after the seed (a file its host tools filed in work/): one JSON line
155
- * per file, `{path, sha256, bytes}`, appended by that process alone. The mark has one writer, the server, so the
156
- * process never writes it; a pull folds these lines into the mark it compares against, for paths the mark lacks, so
157
- * the box's later edit of such a file comes back instead of reading as a change the server made. */
158
- export const BOX_MIRRORED_FILE = "box-mirrored.jsonl";
159
- /** In a run's directory while the box the server destroyed for a new one has no successor yet (ensureRemoteBox): the
160
- * attempt that makes one says the box was replaced, though the one that destroyed the old box failed after it. */
161
- export const BOX_REPLACED_FILE = "box-replaced";
162
- /** `source`, when it is below `root` through no link and is its own canonical path; else a refusal naming the link.
163
- * `root`, the data root, is canonical already (startServe), so a link above it is the operator's choice. */
164
- export async function mountSource(root, source) {
165
- const below = relative(root, source);
166
- if (!below || below.startsWith("..") || isAbsolute(below))
167
- throw new Error(`the mount source ${source} is not below the data root ${root}`);
168
- let at = root;
169
- for (const part of below.split(sep)) {
170
- at = join(at, part);
171
- if ((await lstat(at)).isSymbolicLink())
172
- throw new Error(`the mount source ${source} is refused: ${at} is a link`);
173
- }
174
- if ((await realpath(source)) !== source)
175
- throw new Error(`the mount source ${source} is refused: it is not its own canonical path`);
176
- return source;
177
- }
178
- /** Every mount a run's box gets, each through mountSource: its work/ only, read-write, at BOX_WORK. A run's home joins
179
- * this list (read-only parts included) when it comes; nothing else of the data root does. */
180
- export async function boxMounts(root, runDir, place) {
181
- return [{ source: await mountSource(root, join(runDir, "work")), target: agentWorkDir(runDir, place) }];
182
- }
183
- /** The provider runs' boxes come from: under `--faux` with a faux box, its module's; else Docker on this machine, run as
184
- * this process's user (serve's: a run's process is its child), so what a box writes in work/ stays serve's, within the
185
- * box limits the server's settings give (boxLimitsOf), and whose create first waits while the server pulls its image
186
- * (box-image.ts). */
187
- export async function runBoxProvider(place, env, root) {
188
- const faux = env[FAUX_ENV] ? env[FAUX_BOX_ENV] : undefined;
189
- if (faux)
190
- return fauxBoxes(faux, root);
191
- if (place.mode !== "sandbox" || place.box !== "docker")
192
- throw new Error(`runs in the ${place.mode === "sandbox" ? place.box : "runner"} place have no box`);
193
- const { dockerBoxes } = await import("@parcha/pi-transport/box/docker");
194
- const user = process.getuid && process.getgid ? `${process.getuid()}:${process.getgid()}` : undefined;
195
- // With no capability and no way to gain one (no program in a run's box changes user): as root (serve run as uid 0) a
196
- // box could otherwise make a device node in work/.
197
- const image = boxImageOf(env);
198
- // The list the server resolved for this run's box (box-egress.ts boxNetworkOf), or none.
199
- const allow = runBoxAllowOf(env);
200
- // A server in a container: where its Docker has the data directory (box-paths.ts), which a box's mounts come from, the
201
- // egress proxy's directory with them. On a host, none: a box binds this machine's paths.
202
- const paths = runBoxPathsOf(env);
203
- // On a Mac, the server's proxy container's volume (box-egress-vm.ts), which every box mounts read-only.
204
- const volume = allow === "none" ? undefined : runBoxVolumeOf(env);
205
- return {
206
- ...dockerBoxes({ image, ...(user ? { user } : {}), ...boxLimitsOf(env), dropCapabilities: true, ...(paths ? { paths } : {}), ...(volume ? { volumes: [{ name: volume, target: EGRESS_MOUNT, readOnly: true }] } : {}) }),
207
- ready: (context, note) => awaitImage(root, image, context, note),
208
- // Where the proxy runs: the one line that picks it (box-egress.ts BoxEgress).
209
- ...(allow === "none" ? {} : { egress: volume ? vmEgress : hostEgress(allow, env, egressLog, paths ? egressParentOf(root) : undefined), net: netLabelOf(allow) }),
210
- };
211
- }
212
- /** The tests' faux box provider, from its module. */
213
- export const fauxBoxes = async (module, root) => (await import(pathToFileURL(module).href)).default(root);
214
- export function runBox(given, run) {
215
- const source = typeof given === "function" ? { provider: given } : given;
216
- let held;
217
- // Whether this process destroyed a box of an earlier one, until its model is told (replaced).
218
- let replaced;
219
- const fenced = (destroyed) => void (destroyed > 0 && replaced === undefined && (replaced = "untold"));
220
- // What the host tools filed while no box was open in this process: a box a process before it made has no seed now, so
221
- // these go in when it opens (and to a new box, whose seed carries them anyway, again: the same bytes).
222
- const filed = new Map();
223
- const open = async (context, note) => {
224
- const { boxEnv, endLeftCommands } = await import("@parcha/pi-transport/hands");
225
- const opened = "relay" in source ? await relayedRunBox(source.relay, run, context) : await localRunBox(await source.provider(), run, context, note, fenced);
226
- const { box, made } = opened;
227
- // A remote box the server made in place of the run's (another list, or its files at an older place): told as a
228
- // Docker box an earlier process left is.
229
- if ("replaced" in opened && opened.replaced)
230
- fenced(1);
231
- if (!made) {
232
- // A process before this one left it: what it still runs is killed first, since its calls were answered interrupted.
233
- const ended = await endLeftCommands(box, context);
234
- if (!ended.ok)
235
- throw new Error(`the run's box could not be taken over: ${ended.error.message}`);
236
- }
237
- if (filed.size) {
238
- const queued = [...filed];
239
- filed.clear();
240
- const sent = await box.upload(queued.map(([path, bytes]) => ({ path: posix.join(BOX_WORK, path), bytes })), context);
241
- if (!sent.ok)
242
- mirrorFailed(queued.map(([path]) => path).join(", "), sent.error);
243
- else
244
- for (const [path, bytes] of queued)
245
- await mirrored(run.dir, path, bytes);
246
- }
247
- return { box, env: boxEnv(box, { maxExecMs: BASH_TIMEOUT_MS, onLost: () => void (held = undefined) }) };
248
- };
249
- const opened = (context, note = () => undefined) => {
250
- held ??= open(context, note).catch((error) => {
251
- held = undefined;
252
- throw error;
253
- });
254
- return held;
255
- };
256
- let binds;
257
- let checked;
258
- const env = async (context, note) => (await opened(context, note)).env;
259
- return {
260
- // The bind's source, or what a remote box is seeded from: a path another harness names under it is the same file in
261
- // the box (coding-tools.ts boxPath).
262
- hostWork: join(run.dir, "work"),
263
- env,
264
- // Whether the provider binds it (BoxProvider.mounts): then the file tools may work on it here (bound-files.ts). A
265
- // remote box binds nothing.
266
- bound() {
267
- if ("relay" in source)
268
- return Promise.resolve(false);
269
- const provider = source.provider;
270
- binds ??= provider().then((boxes) => boxes.mounts === true, (error) => {
271
- binds = undefined;
272
- throw error;
273
- });
274
- return binds;
275
- },
276
- // Before a file tool works on work/ here, once a process: a box an earlier process of the run left may still run a
277
- // command that changes work/, so that box is taken over (env: its left commands killed first). None, none is made.
278
- // A remote box's file tools never work here.
279
- leftEnded(context) {
280
- if ("relay" in source)
281
- return Promise.resolve();
282
- const provider = source.provider;
283
- checked ??= (async () => {
284
- if (held)
285
- return void (await held);
286
- // An earlier process's box is destroyed (fenceRunBoxes), and none made for a file tool; one of this epoch's own
287
- // (opened before, then lost) is taken over.
288
- const boxes = await provider();
289
- fenced(await fenceRunBoxes(boxes, run, context));
290
- const listed = await boxes.list({ [RUN_LABEL]: run.id }, context);
291
- if (!listed.ok)
292
- throw listed.error;
293
- if (listed.value.length)
294
- await env(context);
295
- })().catch((error) => {
296
- checked = undefined;
297
- throw error;
298
- });
299
- return checked;
300
- },
301
- replaced() {
302
- if (replaced !== "untold")
303
- return undefined;
304
- replaced = "told";
305
- return BOX_REPLACED_NOTE;
306
- },
307
- ...("relay" in source
308
- ? {
309
- // An open (or opening) box is written now; with none, the file waits for the box's open.
310
- mirror: async (path, data) => {
311
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
312
- const box = held && (await held.catch(() => undefined))?.box;
313
- if (!box)
314
- return void filed.set(path, bytes);
315
- const sent = await box.upload([{ path: posix.join(BOX_WORK, path), bytes }], BACKGROUND);
316
- if (!sent.ok)
317
- throw sent.error;
318
- await mirrored(run.dir, path, bytes);
319
- },
320
- }
321
- : {}),
322
- };
323
- }
324
- /** Notes in BOX_MIRRORED_FILE that `bytes` at `path` (below work/) went into the run's box: one appended line. */
325
- async function mirrored(runDir, path, bytes) {
326
- const line = { path, sha256: createHash("sha256").update(bytes).digest("hex"), bytes: bytes.length };
327
- await appendFile(join(runDir, BOX_MIRRORED_FILE), `${JSON.stringify(line)}\n`, { mode: 0o600 });
328
- }
329
- /** `mark` with each file the run's process mirrored into the box since (BOX_MIRRORED_FILE) that it lacks: as the bytes
330
- * both sides held, so the box's edit of it is a change to fetch and this machine's copy is not a change of its own. */
331
- async function withMirrored(runDir, mark) {
332
- const text = await readFile(join(runDir, BOX_MIRRORED_FILE), "utf8").catch(() => "");
333
- const held = new Set(mark.entries.map((entry) => entry.path));
334
- const added = new Map();
335
- for (const line of text.split("\n")) {
336
- let entry;
337
- try {
338
- entry = JSON.parse(line);
339
- }
340
- catch {
341
- continue;
342
- }
343
- if (typeof entry.path !== "string" || typeof entry.sha256 !== "string" || typeof entry.bytes !== "number" || held.has(entry.path))
344
- continue;
345
- // The newest line for a path wins; its listed fields never match the box's, so the pull lists it as changed.
346
- added.set(entry.path, { path: entry.path, kind: "file", bytes: entry.bytes, sha256: entry.sha256, mode: 0o644, mtime: "0" });
347
- }
348
- if (!added.size)
349
- return mark;
350
- const entries = [...mark.entries, ...added.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
351
- return { entries, bytes: entries.reduce((sum, entry) => sum + entry.bytes, 0) };
352
- }
353
- /** Said in the run's process log: a file the host tools filed in work/ that its remote box did not get. */
354
- function mirrorFailed(paths, error) {
355
- process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), event: "box_mirror_failed", message: `${paths} filed in work/ but not copied into the run's box: ${error.message}` })}\n`);
356
- }
357
- /** Said in the run's process log: one of its egress proxy's decisions (the host, port, address and class). */
358
- const egressLog = (line) => void process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), event: "box_egress", line })}\n`);
359
- /** A box of this process's provider: the run's, by its label, or one made now with work/ bound, once its image is in
360
- * (the provider's `ready`, `note` writing the one timeline row while it is built or pulled). A box that reaches the
361
- * server's host list has the run's egress proxy started first, its directory bound read-only and the proxy variables
362
- * in its environment, and, made or found, its relay started (startRelay). */
363
- async function localRunBox(boxes, run, context, note, fenced) {
364
- let egress;
365
- try {
366
- egress = boxes.egress ? await boxes.egress(run.id) : undefined;
367
- }
368
- catch (error) {
369
- throw new Error(`the run's box could not have its network: ${error.message}`);
370
- }
371
- // A box an earlier process made, under an earlier epoch, goes first: its mounts are the same folder, so its writer is
372
- // gone before this one starts. Never taken over.
373
- fenced(await fenceRunBoxes(boxes, run, context));
374
- // A box a process before this one made with another network (none, or another list: the server's setting changed
375
- // since) is made again: its mounts and environment are fixed at its create. Its work/ is this machine's, bound.
376
- await destroyListed(boxes, { [RUN_LABEL]: run.id }, (labels) => labels[NET_LABEL] !== boxes.net, context);
377
- // And so is one bound to a proxy directory this process had to make again (the start's sweep took the old one once its
378
- // proxy was gone): the box's bind holds the old directory, which no proxy listens in.
379
- if (egress?.fresh)
380
- await destroyListed(boxes, { [RUN_LABEL]: run.id }, () => true, context);
381
- const found = await attachRunBox(boxes, run.id, context);
382
- if (found) {
383
- if (egress)
384
- await startRelay(found, egress.socket, context, note);
385
- return { box: found, made: false };
386
- }
387
- // A box made while the server builds or pulls its image waits for the image, not for a `docker run` that pulls it.
388
- if (boxes.ready) {
389
- try {
390
- await boxes.ready(context, note);
391
- }
392
- catch (error) {
393
- if (context.abortSignal?.aborted)
394
- throw error;
395
- throw new Error(`the run's box could not be made: ${error.message}`);
396
- }
397
- }
398
- // Docker's network stays none either way: the box's only way out is the proxy's socket, which checks everything.
399
- const spec = {
400
- env: egress ? { ...BOX_ENV, ...PROXY_ENV } : BOX_ENV, workspace: agentWorkDir(run.dir, run.place),
401
- mounts: [...(await boxMounts(run.root, run.dir, run.place)), ...(egress?.mount ? [egress.mount] : [])],
402
- labels: { [RUN_LABEL]: run.id, [KIND_LABEL]: "run", [EPOCH_LABEL]: String(run.epoch), ...(boxes.net ? { [NET_LABEL]: boxes.net } : {}) }, network: "none", maxLifetimeMs: BOX_LIFETIME_MS,
403
- };
404
- // Of the run's boxes, the ones this process may destroy: its own epoch's and lower ones, never a later process's.
405
- const notLater = (labels) => !(Number(labels[EPOCH_LABEL]) > run.epoch);
406
- const made = await boxes.create(spec, context);
407
- if (!made.ok) {
408
- // A create that failed may still have left a box (a client cut off while the daemon made it): it carries the label.
409
- await destroyListed(boxes, { [RUN_LABEL]: run.id }, notLater, context).catch(() => undefined);
410
- throw new Error(`the run's box could not be made: ${made.error.message}`);
411
- }
412
- // The fence and the create are not one step: an earlier process's own create, still in flight when it was killed, may
413
- // have landed since. Its box goes now, not at the end of its lifetime.
414
- await destroyListed(boxes, { [RUN_LABEL]: run.id }, (labels) => !(Number(labels[EPOCH_LABEL]) >= run.epoch), context);
415
- if (egress)
416
- await startRelay(made.value, egress.socket, context, note);
417
- return { box: made.value, made: true };
418
- }
419
- /** The box's relay to its proxy's `socket` (box-egress.ts forwarder), started in the background and answered once it
420
- * listens. One that cannot start (an image with no socat or setsid, or a relay not listening in time) leaves the box with
421
- * no network, nothing listening on its proxy port, and the run's timeline says why (`note`). */
422
- async function startRelay(box, socket, context, note) {
423
- const started = await box.exec(forwarderStart(socket), undefined, context);
424
- if (!started.ok)
425
- throw new Error(`the run's box could not start its network relay: ${started.error.message}`);
426
- let said = "";
427
- const drain = async (stream, keep) => {
428
- for await (const chunk of stream)
429
- if (keep && said.length < 1000)
430
- said += new TextDecoder().decode(chunk);
431
- };
432
- const [ended] = await Promise.all([started.value.wait(), drain(started.value.stdout, false), drain(started.value.stderr, true)]);
433
- if (!ended.ok)
434
- throw new Error(`the run's box could not start its network relay: ${ended.error.message}`);
435
- if (ended.value !== 0)
436
- await Promise.resolve(note(relayFailed(ended.value, said))).catch(() => undefined);
437
- }
438
- /** A remote box, which the server finds or makes and seeds (ensureRemoteBox), reached through its relay: this process's
439
- * provider holds no key, and every call it makes goes to the relay, which sends it on with the server's (Daytona's key;
440
- * the VM box's client, box-relay-vm.ts). */
441
- async function relayedRunBox(root, run, context) {
442
- const { id: runId, dir: runDir } = run;
443
- const given = await relayedBox(root, runDir, runId, context.abortSignal);
444
- const boxes = run.place.mode === "sandbox" && run.place.box === VM_PROVIDER.id ? await relayedVmBoxes(root, runDir, runId) : await relayedDaytona(root, runDir, runId, given.apiUrl);
445
- const attached = await boxes.attach(given.id, context);
446
- if (!attached.ok)
447
- throw new Error(`the run's box could not be reached: ${attached.error.message}`);
448
- if (!attached.value)
449
- throw new Error(`the run's box ${given.id} is not running`);
450
- return { box: attached.value, made: given.made, ...(given.replaced ? { replaced: true } : {}) };
451
- }
452
- /** The run's process's Daytona provider: its calls go to the relay, which adds the key. */
453
- async function relayedDaytona(root, runDir, runId, apiUrl) {
454
- if (!apiUrl)
455
- throw new Error("the server gave the run's Daytona box no API address");
456
- const { daytonaBoxes } = await import("@parcha/pi-transport/box/daytona");
457
- return daytonaBoxes({ apiKey: RELAYED_KEY, apiUrl, fetch: relayFetch(root, runDir, runId) });
458
- }
459
- /** The run's process's VM provider: pi-transport's, over the relay's client (box-relay-vm.ts). It only attaches. */
460
- async function relayedVmBoxes(root, runDir, runId) {
461
- const [{ relayedVmSdk }, transport] = await Promise.all([import("./box-relay-vm.js"), import(`@parcha/pi-transport/box/${VM_PROVIDER.id}`)]);
462
- return transport.modalBoxes(relayedVmSdk(root, runDir, runId), { appName: "relayed" });
463
- }
464
- /** A Docker size (boxLimitsOf's memory) in MiB, the fraction dropped. */
465
- export const memoryMbOf = (memory) => {
466
- const size = /^(\d+(?:\.\d+)?)([bkmg])$/i.exec(memory);
467
- return size ? Math.floor((Number(size[1]) * SIZE_UNITS[size[2].toLowerCase()]) / MIB) : 0;
468
- };
469
- /** The spec of a run's remote box: its work/ comes with its seed, never a mount; its network the hosts `allow` names, or
470
- * none; its limits, where its provider takes them. */
471
- const remoteSpec = (runId, allow, limits = {}) => ({
472
- env: BOX_ENV, workspace: BOX_WORK, labels: { [RUN_LABEL]: runId, [KIND_LABEL]: "run" }, network: allow === "none" ? "none" : { allow }, maxLifetimeMs: BOX_LIFETIME_MS,
473
- ...(limits.cpus === undefined ? {} : { cpus: limits.cpus }), ...(limits.memoryMb ? { memoryMb: limits.memoryMb } : {}),
474
- });
475
- /** Whether a box's hosts, as its provider reads them (undefined: it does not say), are the hosts asked, as a set. */
476
- const sameHosts = (hosts, asked) => {
477
- if (!hosts)
478
- return false;
479
- const have = new Set(hosts.map((host) => host.toLowerCase()));
480
- const want = new Set(asked.map((host) => host.toLowerCase()));
481
- return have.size === want.size && [...want].every((host) => have.has(host));
482
- };
483
- /** The refusals of a create with a host list that say the provider cannot keep one here, so a box with no network is made
484
- * in its place: Daytona did not keep the list (`unsupported`), or refused it (`invalid`, `unauthorized`: a tier that takes
485
- * none). Never a refusal a closed box would meet too, such as a timeout. */
486
- const NO_LIST = new Set(["unsupported", "invalid", "unauthorized"]);
487
- const markOf = async (runDir) => {
488
- const kept = (await readJson(join(runDir, BOX_SYNC_FILE)));
489
- return typeof kept?.box === "string" && kept.mark && Array.isArray(kept.mark.entries) ? kept : undefined;
490
- };
491
- const keepMark = (runDir, mark) => writeDurable(join(runDir, BOX_SYNC_FILE), `${JSON.stringify(mark)}\n`);
492
- export async function ensureRemoteBox(boxes, run, context, options = {}) {
493
- const { wake, allow = "none", onNoList, pull = pullRemoteBox, limits } = options;
494
- let asked = allow === "none" ? "none" : "allowlist";
495
- let box = await runningRunBox(boxes, run.id, context, wake);
496
- let made = false;
497
- const facts = box?.facts();
498
- // Kept with its network as asked, and its work/ where every box has it now (BOX_WORK): one made when boxes had it
499
- // elsewhere is pulled from there, whole, and made again.
500
- const keep = facts?.workspace === BOX_WORK && (facts?.network === "none" || (facts?.network === "allowlist" && allow !== "none" && sameHosts(facts.allow, allow)));
501
- if (box && !keep) {
502
- // Its files first, whole: a box replaced here holds nothing only it had. One whose copy back fails, or is not whole,
503
- // is kept for a later copy, and the call refused, so no tool runs in it.
504
- try {
505
- await pull(boxes, run, context, wake);
506
- }
507
- catch (error) {
508
- throw new Error(`the run's box has another host list than this server's now (or a network it does not ask for, or its files outside /workspace), and its files could not all be copied back, so it is kept and not used: ${error.message}`);
509
- }
510
- // Noted before the old box goes: should what follows fail, the attempt that makes its successor still says so.
511
- await writeFile(join(run.dir, BOX_REPLACED_FILE), "");
512
- await destroyRunBoxes(boxes, run.id, context);
513
- box = undefined;
514
- }
515
- if (!box) {
516
- let created = await boxes.create(remoteSpec(run.id, allow, limits), context);
517
- if (!created.ok && asked === "allowlist" && NO_LIST.has(created.error.code)) {
518
- asked = "none";
519
- onNoList?.(created.error.code, created.error.message);
520
- await destroyRunBoxes(boxes, run.id, context).catch(() => undefined);
521
- created = await boxes.create(remoteSpec(run.id, "none", limits), context);
522
- }
523
- if (!created.ok) {
524
- await destroyRunBoxes(boxes, run.id, context).catch(() => undefined);
525
- throw new Error(`the run's box could not be made: ${created.error.message}`);
526
- }
527
- box = created.value;
528
- made = true;
529
- if (box.facts().network !== asked) {
530
- await box.destroy(context);
531
- throw new Error(`the run's box was made with its network ${box.facts().network ?? "unknown"}, not ${asked === "none" ? "closed" : "its host list"}, so it is not used`);
532
- }
533
- }
534
- // A box found without its seed's mark was made by a server that went down before it seeded it: seeded now.
535
- if ((await markOf(run.dir))?.box !== box.id) {
536
- const { seedDir } = await import("@parcha/pi-transport/sync");
537
- const seeded = await seedDir(box, { from: join(run.dir, "work"), to: BOX_WORK }, context);
538
- if (!seeded.ok) {
539
- await box.destroy(context).catch(() => undefined);
540
- throw new Error(`the run's files could not be copied into its box: ${seeded.error.message}`);
541
- }
542
- await keepMark(run.dir, { box: box.id, mark: seeded.value.mark });
543
- }
544
- // `replaced`: a box the run had was destroyed for this one (in this attempt or a failed one before it), and what it
545
- // held outside the run's files with it. Said once.
546
- const replaced = await rm(join(run.dir, BOX_REPLACED_FILE)).then(() => true, (error) => (error.code === "ENOENT" ? false : Promise.reject(error)));
547
- return { id: box.id, made, ...(replaced ? { replaced } : {}) };
548
- }
549
- /** A pull that did not bring the box's work/ back whole: what it wrote is kept, with its mark, and the box must stay.
550
- * `lasting`: a stop another pull will meet again (an archive the extractor cannot read, or a limit a pull that wrote
551
- * nothing reached); else the copy failed, and a later pull may land. */
552
- export class PullIncomplete extends Error {
553
- lasting;
554
- /** The box that keeps what did not come back. */
555
- box;
556
- constructor(message, lasting, box) {
557
- super(message);
558
- this.lasting = lasting;
559
- this.box = box;
560
- }
561
- }
562
- /** How many pulls one copy back takes at most: each pull past a limit brings the next part, up to the limit again. */
563
- const PULL_ROUNDS = 8;
564
- /** The server's side of a remote box: what changed in the box's work/ since its mark, pulled into the run's work/ by the
565
- * safe extractor (nothing outside work/, no link, safe names only). A file this machine changed since the mark stays
566
- * (`if_unchanged`), and what the box removed is removed here too. A pull a limit stopped after it wrote something is
567
- * followed by another, which asks only for the rest. Throws when the copy fails (the mark kept), and PullIncomplete when
568
- * it is not whole: a caller then keeps the box. */
569
- export async function pullRemoteBox(boxes, run, context, wake) {
570
- const box = await runningRunBox(boxes, run.id, context, wake);
571
- if (!box)
572
- return undefined;
573
- const { pullDir } = await import("@parcha/pi-transport/sync");
574
- const total = { changed: 0, files: 0, bytes: 0, removed: 0 };
575
- for (let round = 1;; round++) {
576
- const kept = await markOf(run.dir);
577
- const since = kept?.box === box.id ? await withMirrored(run.dir, kept.mark) : undefined;
578
- // From where this box has the run's work/: BOX_WORK, or, for one made before every box had it there, its own.
579
- const pulled = await pullDir(box, { from: box.facts().workspace ?? BOX_WORK, to: join(run.dir, "work"), ...(since ? { since } : {}), mirrorDeletes: true, overwrite: "if_unchanged" }, context);
580
- if (!pulled.ok)
581
- throw new Error(`the run's files could not be copied back from its box: ${pulled.error.message}`);
582
- // What it wrote is whole and in the mark, a stopped pull's too: the next pull asks only for the rest.
583
- await keepMark(run.dir, { box: box.id, mark: pulled.value.mark });
584
- const { changed, files, directories, bytes, removed, stopped } = pulled.value;
585
- if (round === 1)
586
- total.changed = changed;
587
- total.files += files;
588
- total.bytes += bytes;
589
- total.removed += removed;
590
- if (!stopped)
591
- return total;
592
- const wrote = files + directories + removed > 0;
593
- if (stopped.reason === "copy_failed")
594
- throw new PullIncomplete(`the copy back from the run's box stopped: ${stopped.message}`, false, box.id);
595
- if (stopped.reason === "malformed" || !wrote || round >= PULL_ROUNDS)
596
- throw new PullIncomplete(`the copy back from the run's box stopped (${stopped.reason}): ${stopped.message}`, true, box.id);
597
- }
598
- }
599
- /** The running box labelled with run `runId`; with none running, one `wake` started (Daytona stopped or paused it), else none. */
600
- async function runningRunBox(boxes, runId, context, wake) {
601
- const box = await attachRunBox(boxes, runId, context);
602
- if (box || !wake || (await wake()) === 0)
603
- return box;
604
- return attachRunBox(boxes, runId, context);
605
- }
606
- /** The running box labelled with run `runId`, if any. */
607
- async function attachRunBox(boxes, runId, context) {
608
- const listed = await boxes.list({ [RUN_LABEL]: runId }, context);
609
- if (!listed.ok)
610
- throw listed.error;
611
- for (const ref of listed.value) {
612
- const attached = await boxes.attach(ref.id, context);
613
- if (!attached.ok)
614
- throw attached.error;
615
- if (attached.value)
616
- return attached.value;
617
- }
618
- return undefined;
619
- }
620
- /** The fence of a run's boxes for a process under claim epoch `run.epoch`: every box of the run whose epoch is lower (or
621
- * that has none: made before boxes had one) is destroyed; how many. One of a higher epoch is a later process's: this
622
- * one is not the run's holder, so it throws, and makes and destroys nothing. */
623
- export async function fenceRunBoxes(boxes, run, context) {
624
- const listed = await boxes.list({ [RUN_LABEL]: run.id }, context);
625
- if (!listed.ok)
626
- throw listed.error;
627
- const later = listed.value.find((ref) => Number(ref.labels[EPOCH_LABEL]) > run.epoch);
628
- if (later)
629
- throw new Error(`the run's box ${later.id} is a later launch's (epoch ${later.labels[EPOCH_LABEL]}, this process's ${run.epoch}): this process no longer holds the run`);
630
- return destroyListed(boxes, { [RUN_LABEL]: run.id }, (labels) => !(Number(labels[EPOCH_LABEL]) >= run.epoch), context);
631
- }
632
- /** Destroys every box labelled with run `runId`; how many it destroyed. */
633
- export async function destroyRunBoxes(boxes, runId, context) {
634
- return destroyListed(boxes, { [RUN_LABEL]: runId }, () => true, context);
635
- }
636
- /** The start's sweep: destroys every run's box whose run `ended` says is over, once `before` (a remote box's pull) for its
637
- * run says it may go. A box of a run this server does not know is left to its lifetime: another server's, or one being
638
- * made. */
639
- export async function sweepRunBoxes(boxes, ended, context, before) {
640
- return destroyListed(boxes, { [KIND_LABEL]: "run" }, (labels) => typeof labels[RUN_LABEL] === "string" && ended(labels[RUN_LABEL]), context, before);
641
- }
642
- async function destroyListed(boxes, labels, pick, context, before) {
643
- const listed = await boxes.list(labels, context);
644
- if (!listed.ok)
645
- throw listed.error;
646
- let destroyed = 0;
647
- for (const ref of listed.value.filter((r) => pick(r.labels))) {
648
- const box = await boxes.attach(ref.id, context);
649
- if (!box.ok)
650
- throw box.error;
651
- if (!box.value)
652
- continue;
653
- if (before && !(await before(ref.labels[RUN_LABEL], ref.id)))
654
- continue;
655
- const gone = await box.value.destroy(context);
656
- if (!gone.ok)
657
- throw gone.error;
658
- destroyed++;
659
- }
660
- return destroyed;
661
- }