@parcha/agentrun-serve 0.1.0-beta.30 → 0.1.0-beta.31

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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +182 -26
  3. package/dist/agents.d.ts +8 -3
  4. package/dist/agents.js +4 -1
  5. package/dist/app.js +23 -8
  6. package/dist/background.d.ts +2 -1
  7. package/dist/background.js +41 -20
  8. package/dist/box-egress-vm.d.ts +125 -0
  9. package/dist/box-egress-vm.js +350 -0
  10. package/dist/box-egress.d.ts +3 -2
  11. package/dist/box-relay-vm.d.ts +4 -0
  12. package/dist/box-relay-vm.js +76 -55
  13. package/dist/boxes.d.ts +7 -2
  14. package/dist/boxes.js +30 -11
  15. package/dist/cap.d.ts +2 -1
  16. package/dist/cap.js +2 -1
  17. package/dist/cli.js +30 -4
  18. package/dist/console/assets/{index-34jfpIbQ.js → index-CnJBf7Lc.js} +90 -85
  19. package/dist/console/index.html +1 -1
  20. package/dist/decisions.d.ts +3 -3
  21. package/dist/decisions.js +4 -3
  22. package/dist/files.d.ts +3 -0
  23. package/dist/files.js +3 -0
  24. package/dist/grade.d.ts +5 -2
  25. package/dist/grade.js +13 -5
  26. package/dist/harness-app.js +10 -1
  27. package/dist/host-check.d.ts +12 -0
  28. package/dist/host-check.js +34 -0
  29. package/dist/key-words.d.ts +37 -0
  30. package/dist/key-words.js +40 -0
  31. package/dist/learn/grade.d.ts +3 -0
  32. package/dist/learn/grade.js +3 -1
  33. package/dist/learn/index.d.ts +1 -1
  34. package/dist/learn/index.js +1 -1
  35. package/dist/learn/reflect.js +2 -0
  36. package/dist/learn/skills.d.ts +2 -0
  37. package/dist/learn/skills.js +16 -0
  38. package/dist/learning-routes.d.ts +30 -1
  39. package/dist/learning-routes.js +173 -19
  40. package/dist/learning-run.d.ts +1 -1
  41. package/dist/learning-run.js +25 -4
  42. package/dist/learning-words.d.ts +7 -3
  43. package/dist/learning-words.js +26 -8
  44. package/dist/learning.d.ts +9 -1
  45. package/dist/learning.js +57 -2
  46. package/dist/mcp-gateway.d.ts +96 -0
  47. package/dist/mcp-gateway.js +408 -0
  48. package/dist/mcp-meta.d.ts +17 -0
  49. package/dist/mcp-meta.js +38 -0
  50. package/dist/mcp-servers.d.ts +26 -5
  51. package/dist/mcp-servers.js +53 -10
  52. package/dist/openapi.js +52 -9
  53. package/dist/page.d.ts +2 -0
  54. package/dist/page.js +3 -0
  55. package/dist/place.d.ts +3 -2
  56. package/dist/place.js +11 -3
  57. package/dist/print.d.ts +7 -0
  58. package/dist/print.js +13 -0
  59. package/dist/run-box.js +15 -5
  60. package/dist/runnable.d.ts +8 -1
  61. package/dist/runnable.js +51 -2
  62. package/dist/runs.d.ts +15 -8
  63. package/dist/runs.js +66 -13
  64. package/dist/secrets.d.ts +15 -0
  65. package/dist/secrets.js +20 -2
  66. package/dist/server.d.ts +10 -1
  67. package/dist/server.js +111 -29
  68. package/dist/tool-gate.d.ts +18 -3
  69. package/dist/tool-gate.js +44 -13
  70. package/dist/tool-keys.d.ts +2 -1
  71. package/dist/tool-keys.js +4 -8
  72. package/dist/tool-plane.d.ts +5 -1
  73. package/dist/tool-plane.js +30 -6
  74. package/dist/tools.js +8 -5
  75. package/dist/web-fetch.js +3 -3
  76. package/package.json +12 -16
@@ -0,0 +1,350 @@
1
+ // A Docker box's way out on a Mac, where Docker runs in a VM: the Linux path (box-egress.ts) binds a socket of this
2
+ // machine into the box, and a Mac's file-sharing layer carries files, not sockets, so the box sees it and is refused. Here
3
+ // the kernel's egress proxy runs instead in ONE container per server, inside the VM: the pinned EGRESS_IMAGE, the proxy's
4
+ // two dependency-free files and an entry (MAIN) bound read-only from the data root, the host list as its one variable, and
5
+ // a Unix socket in a tmpfs named volume owned by the server's uid. The box mounts that volume read-only at EGRESS_MOUNT
6
+ // and keeps `--network none`, its socat and its proxy variables, as on Linux. The proxy container is the only container
7
+ // with a network (Docker's default), and it publishes no port.
8
+ //
9
+ // This path is for a Mac alone, and only for a Docker that `docker info` names as a VM runtime this server knows
10
+ // (vmDockerOf): Docker Desktop, OrbStack or colima, on a kernel other than this machine's. Anything else stays offline, and
11
+ // the reason says what was seen. Linux keeps its own path, unchanged.
12
+ //
13
+ // Lifecycle (startEgressContainer): at the server's start, the volume is made if missing, every container of this
14
+ // server's label is removed (a crashed server's), the image is pulled if Docker lacks it, and the container is started
15
+ // and waited on until it logs EGRESS_READY (EGRESS_READY_MS). Docker restarts it if it dies (`--restart unless-stopped`);
16
+ // if it is gone (removed by hand), the server's watch starts it again. The server's stop removes it. Until it is ready,
17
+ // and when it cannot start, the box's network is none, and capabilities say why.
18
+ import { execFile } from "node:child_process";
19
+ import { createHash, randomBytes } from "node:crypto";
20
+ import { chmod, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
21
+ import { release } from "node:os";
22
+ import { dirname, join } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import { ALLOW_HINT, EGRESS_SOCKET, INFO_TIMEOUT_MS } from "./box-egress.js";
25
+ import { withoutSecrets } from "./secrets.js";
26
+ /** What `docker info` is asked on a Mac: the daemon's OS type, its kernel, the name it gives its OS, and its host name. */
27
+ export const VM_INFO_FORMAT = "{{.OSType}}|{{.KernelVersion}}|{{.OperatingSystem}}|{{.Name}}";
28
+ /** The VM runtimes a box's network goes on for, on a Mac. */
29
+ export const VM_RUNTIMES = ["Docker Desktop", "OrbStack", "colima"];
30
+ /** A colima VM's host name, which `docker info` gives as its Name: `colima` for the default profile, `colima-<profile>`
31
+ * for another (colima's config.ProfileName / CurrentProfile; its VM's hostname is the profile's ID). */
32
+ const COLIMA_NAME = /^colima(-[A-Za-z0-9][A-Za-z0-9._-]*)?$/;
33
+ /** Where this Docker runs, by `docker info`'s answer to VM_INFO_FORMAT (`answer`), on a server with `platform` and
34
+ * `kernel` (os.release()): a VM runtime this server knows, or why not. Pure. A runtime counts only when docker info
35
+ * names it (OperatingSystem `Docker Desktop` or `OrbStack`, or a colima host Name) AND its kernel is not this
36
+ * machine's: a VM in between. Anything else is a reason, never a guess. */
37
+ export function vmDockerOf(answer, here) {
38
+ if (here.platform !== "darwin")
39
+ return { reason: `this server runs on ${here.platform}, not a Mac, so a Docker in a VM gets no box network here` };
40
+ const fields = answer.trim().split("|");
41
+ const [osType, kernel, os, name] = fields.map((field) => field.trim());
42
+ const shown = (text) => JSON.stringify(text.slice(0, 80));
43
+ if (fields.length !== 4 || !osType || !kernel)
44
+ return { reason: `docker info's answer could not be read (${shown(answer.trim())}), so this server can't tell which VM this Docker runs in` };
45
+ const runtime = os ? `this Docker (${os.slice(0, 80)})` : "this Docker";
46
+ if (osType !== "linux")
47
+ return { reason: `${runtime} runs ${shown(osType)} containers, not Linux ones, so its boxes get no network` };
48
+ if (kernel === here.kernel)
49
+ return { reason: `${runtime} runs on this machine's own kernel, not in a VM this server knows, so its boxes get no network` };
50
+ const known = os === "Docker Desktop" ? "Docker Desktop" : os === "OrbStack" ? "OrbStack" : COLIMA_NAME.test(name ?? "") ? "colima" : undefined;
51
+ if (!known)
52
+ return { reason: `${runtime} runs in a VM this server does not know (its kernel is ${shown(kernel)}, its name ${shown(name ?? "")}), so its boxes get no network: on a Mac, a box's network goes on only for Docker Desktop, OrbStack or colima` };
53
+ return { runtime: known };
54
+ }
55
+ export const dockerCall = (env) => (args, timeoutMs, signal) => new Promise((resolve) => {
56
+ const child = execFile("docker", args, { env: withoutSecrets(env), timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 8 * 1024 * 1024, ...(signal ? { signal } : {}) }, (error, stdout, stderr) => {
57
+ const failed = error;
58
+ resolve({ code: !failed ? 0 : failed.killed ? "timeout" : typeof failed.code === "number" ? failed.code : (failed.code ?? failed.name), stdout: String(stdout), stderr: String(stderr) });
59
+ });
60
+ child.stdin?.on("error", () => undefined);
61
+ child.stdin?.end();
62
+ });
63
+ /** Where this Mac's Docker runs (vmDockerOf), asked of `docker info` within its bound; a daemon the docker CLI does not
64
+ * reach by a local unix socket (DOCKER_HOST, or a context, elsewhere) is not this Mac's VM, and gets no network. */
65
+ export async function vmDocker(env, options = {}) {
66
+ const platform = options.platform ?? process.platform;
67
+ if (platform !== "darwin")
68
+ return vmDockerOf("", { platform, kernel: "" });
69
+ const { dockerDaemon } = await import("@parcha/pi-transport/box/docker");
70
+ const daemon = dockerDaemon(env);
71
+ if (!daemon.local)
72
+ return { reason: `this Docker (${daemon.named}) is not on this machine, so its boxes get no network` };
73
+ const timeoutMs = options.timeoutMs ?? INFO_TIMEOUT_MS;
74
+ const answer = await (options.docker ?? dockerCall(env))(["info", "--format", VM_INFO_FORMAT], timeoutMs);
75
+ if (answer.code !== 0)
76
+ return { reason: `docker info did not say where this Docker runs (${answer.code === "timeout" ? `it did not answer within ${Math.round(timeoutMs / 1000)} s` : `it failed (${typeof answer.code === "number" ? `exit ${answer.code}` : answer.code})`}), so its boxes get no network` };
77
+ return vmDockerOf(answer.stdout, { platform, kernel: options.kernel ?? release() });
78
+ }
79
+ /** The proxy container's image: `node:22-bookworm-slim` (the kernel needs Node 22.19 or later), pinned to the multi-arch
80
+ * index digest Docker Hub served for that tag on 2026-11-05 (Node 22.23.4), as BOX_BASE is pinned (box-image.ts), so every Mac runs the
81
+ * same Node. To move it, read the tag's index digest again the way BOX_BASE says, and put it here. */
82
+ export const EGRESS_IMAGE = "node:22-bookworm-slim@sha256:4b150b48b4116e2a22f2c39cc27025fbf4f153e2078fd3b14d159fdb5c7279da";
83
+ /** The label the proxy container and its volume carry: the server's key (egressKeyOf). */
84
+ export const EGRESS_LABEL = "agentrun.egress";
85
+ /** Where the volume is in the proxy container, and its code. */
86
+ export const EGRESS_VOLUME_MOUNT = "/egress";
87
+ export const EGRESS_CODE_MOUNT = "/code";
88
+ /** What the entry logs once its socket listens. */
89
+ export const EGRESS_READY = "egress ready";
90
+ /** How long the start waits for EGRESS_READY once the container runs. */
91
+ export const EGRESS_READY_MS = 10_000;
92
+ /** How often the server looks for its proxy container, to start it again when it is gone. */
93
+ export const EGRESS_WATCH_MS = 5_000;
94
+ /** How long the start's pull of EGRESS_IMAGE may take. */
95
+ export const EGRESS_PULL_MS = 10 * 60_000;
96
+ /** Connections open at once through the server's one proxy, every run's together. */
97
+ export const VM_MAX_TUNNELS = 256;
98
+ /** The setting the proxy container gets, and nothing else: the host list. */
99
+ const ALLOW_VAR = "AGENTRUN_BOX_ALLOW";
100
+ /** This server's key: its data root's hash, so two servers on one daemon get two proxies and two volumes. */
101
+ export const egressKeyOf = (data) => createHash("sha256").update(data).digest("hex").slice(0, 12);
102
+ /** The proxy container's name, and its volume's, for a key. */
103
+ export const egressNameOf = (key) => `agentrun-egress-${key}`;
104
+ /** The entry the proxy container runs (`node /code/main.js <socket>`): it refuses to start with no list, for a proxy with
105
+ * none would reach every public host, and logs EGRESS_READY once its socket listens. Its decisions go to its log. */
106
+ export const MAIN = `// The box network proxy's entry, written by the server that runs it (agentrun serve), in its container.
107
+ import { parseAllow, startEgressProxy } from "./egress-proxy.js";
108
+ const say = (line) => process.stdout.write(line + "\\n");
109
+ let allow = [];
110
+ try {
111
+ allow = parseAllow(process.env.${ALLOW_VAR} ?? "");
112
+ } catch (error) {
113
+ say("egress: ${ALLOW_VAR} is not a host list (" + error.message + "), so the proxy does not start");
114
+ process.exit(2);
115
+ }
116
+ if (allow.length === 0) {
117
+ say("egress: no host list, so the proxy does not start: one with none would reach every public host");
118
+ process.exit(2);
119
+ }
120
+ const socketPath = process.argv[2];
121
+ if (!socketPath) {
122
+ say("egress: no socket path, so the proxy does not start");
123
+ process.exit(2);
124
+ }
125
+ const proxy = await startEgressProxy({ socketPath, maxTunnels: ${VM_MAX_TUNNELS}, maxConnections: Number.MAX_SAFE_INTEGER, log: say, allow, allowHint: ${JSON.stringify(ALLOW_HINT)} });
126
+ say("${EGRESS_READY} allow=" + allow.join(","));
127
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => void proxy.close().finally(() => process.exit(0)));
128
+ `;
129
+ /** The kernel's two proxy files, as built: they import only `node:` modules and each other. */
130
+ export const PROXY_FILES = ["egress-proxy.js", "egress-table.js"];
131
+ /** The code the proxy container binds read-only: PROXY_FILES from the kernel this server runs, and MAIN, written into
132
+ * `<data>/egress/<12 hex of their hash>/` once (a directory per version, so a running container's code never changes
133
+ * under it). Its path, real (Docker binds it by that). */
134
+ export async function egressCode(data) {
135
+ const host = dirname(fileURLToPath(import.meta.resolve("@parcha/agentrun-kernel/host")));
136
+ const files = [...(await Promise.all(PROXY_FILES.map(async (name) => [name, await readFile(join(host, name), "utf8")]))), ["main.js", MAIN]];
137
+ const hash = createHash("sha256");
138
+ for (const [name, text] of files)
139
+ hash.update(`${name}\0${text}\0`);
140
+ const parent = join(await realpath(data), "egress");
141
+ const dir = join(parent, hash.digest("hex").slice(0, 12));
142
+ if (await readFile(join(dir, "main.js"), "utf8").then((text) => text === MAIN, () => false))
143
+ return dir;
144
+ await mkdir(parent, { recursive: true, mode: 0o755 });
145
+ const making = `${dir}.${randomBytes(4).toString("hex")}.partial`;
146
+ await mkdir(making, { mode: 0o755 });
147
+ try {
148
+ for (const [name, text] of files)
149
+ await writeFile(join(making, name), text, { mode: 0o644 });
150
+ await chmod(making, 0o755);
151
+ await rename(making, dir).catch(async (error) => {
152
+ // Another start made it first: the same bytes.
153
+ if (error.code !== "ENOTEMPTY" && error.code !== "EEXIST")
154
+ throw error;
155
+ });
156
+ }
157
+ finally {
158
+ await rm(making, { recursive: true, force: true }).catch(() => undefined);
159
+ }
160
+ return dir;
161
+ }
162
+ /** `docker volume create` of the server's volume: tmpfs, so no stale socket outlives the VM, and owned by the server's
163
+ * uid:gid with mode 0700, as the proxy's socket (0600) and the box (both run as that uid) need. */
164
+ export const egressVolumeArgs = (key, uid, gid) => ["volume", "create", "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", `o=size=1m,uid=${uid},gid=${gid},mode=0700`, "--label", `${EGRESS_LABEL}=${key}`, egressNameOf(key)];
165
+ /** `docker run` of the proxy container. Docker's default network, the only container with one; no published port, no
166
+ * Docker socket, no variable but the list; a read-only root, no capability, no privilege to gain, the server's uid:gid;
167
+ * bounded memory, processes and log. Pinned by a golden test. */
168
+ export const egressRunArgs = (options) => [
169
+ "run", "--detach", "--name", egressNameOf(options.key), "--restart", "unless-stopped",
170
+ "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--user", `${options.uid}:${options.gid}`,
171
+ "--memory", "256m", "--pids-limit", "256", "--log-driver", "json-file", "--log-opt", "max-size=1m", "--log-opt", "max-file=2",
172
+ "--label", `${EGRESS_LABEL}=${options.key}`,
173
+ "--mount", `type=volume,source=${egressNameOf(options.key)},target=${EGRESS_VOLUME_MOUNT}`,
174
+ "--mount", `type=bind,source=${options.code},target=${EGRESS_CODE_MOUNT},readonly`,
175
+ "--env", `${ALLOW_VAR}=${options.allow.join(",")}`,
176
+ "--entrypoint", "node", EGRESS_IMAGE, `${EGRESS_CODE_MOUNT}/main.js`, `${EGRESS_VOLUME_MOUNT}/${EGRESS_SOCKET}`,
177
+ ];
178
+ const OWN_WORDS = /^egress: [\x20-\x7e]{1,200}$/;
179
+ /**
180
+ * The server's proxy container (see the head of this file): made ready now when Docker has its image (within
181
+ * EGRESS_READY_MS), else pulled and started in the background; then watched every `watchMs`, and started again when it
182
+ * is gone or stopped. `onChange` is told each new state. `close` stops the watch and removes the container; its volume
183
+ * stays, for boxes still mounting it and the next start.
184
+ */
185
+ export async function startEgressContainer(options) {
186
+ if (!options.allow.length)
187
+ throw new Error("the box network proxy needs a host list: one with none would reach every public host");
188
+ const docker = options.docker ?? dockerCall(options.env);
189
+ const key = egressKeyOf(await realpath(options.data));
190
+ const name = egressNameOf(key);
191
+ const readyMs = options.readyMs ?? EGRESS_READY_MS;
192
+ let state = { state: "preparing", reason: "the box network proxy is starting" };
193
+ let closed = false;
194
+ // Aborted at close: a pull or a wait in progress ends with the server.
195
+ const stopping = new AbortController();
196
+ const set = (next) => {
197
+ if (closed || (next.state === state.state && ("reason" in next ? next.reason : "") === ("reason" in state ? state.reason : "")))
198
+ return;
199
+ state = next;
200
+ options.onChange?.(state);
201
+ };
202
+ const failed = (why) => ({ state: "unavailable", reason: `the box network proxy did not start (${why}), so boxes have no network: restart the server to try again` });
203
+ /** Removes every container of this server's label: a crashed server's, or one being replaced. */
204
+ const sweep = async () => {
205
+ const listed = await docker(["ps", "--all", "--quiet", "--filter", `label=${EGRESS_LABEL}=${key}`], 10_000);
206
+ if (listed.code !== 0)
207
+ throw new Error(`docker ps failed (${listed.code})`);
208
+ for (const id of listed.stdout.split("\n").map((line) => line.trim()).filter(Boolean)) {
209
+ const removed = await docker(["rm", "--force", id], 10_000);
210
+ if (removed.code !== 0 && !/no such container/i.test(removed.stderr))
211
+ throw new Error(`docker rm of an old proxy failed (${removed.code})`);
212
+ }
213
+ };
214
+ /** Makes the server's volume, unless it is there with this server's label: why not, or undefined. One of its name
215
+ * without the label (Docker makes a volume a box names with its own defaults: root's, not tmpfs) is replaced when
216
+ * nothing holds it, and is a failure, saying how to remove it, when something does. */
217
+ const ensureVolume = async () => {
218
+ const seen = await docker(["volume", "inspect", "--format", `{{index .Labels "${EGRESS_LABEL}"}}`, name], 10_000);
219
+ if (seen.code === 0 && seen.stdout.trim() === key)
220
+ return undefined;
221
+ if (seen.code === 0 && (await docker(["volume", "rm", name], 10_000)).code !== 0)
222
+ return `a volume ${name} that this server did not make is in use: stop what uses it and run docker volume rm ${name}`;
223
+ const made = await docker(egressVolumeArgs(key, options.uid, options.gid), 10_000);
224
+ return made.code === 0 ? undefined : `docker volume create failed (${made.code})`;
225
+ };
226
+ // The proxy container this server started, by the id `docker run` printed: what the watch looks at and the close
227
+ // removes. Never its name, which a container that is not this server's may hold.
228
+ let ours;
229
+ /** Removes the container this server started, by its id. */
230
+ const removeOurs = async () => {
231
+ if (ours)
232
+ await docker(["rm", "--force", ours], 10_000);
233
+ ours = undefined;
234
+ };
235
+ /** Starts the container, the image already in, and waits for its ready line. */
236
+ const run = async () => {
237
+ const volume = await ensureVolume();
238
+ if (volume)
239
+ return failed(volume);
240
+ // A close since: nothing is removed or started, so a server that took this data root after it keeps its own proxy.
241
+ if (closed)
242
+ return state;
243
+ await sweep();
244
+ const code = await egressCode(options.data);
245
+ if (closed)
246
+ return state;
247
+ const started = await docker(egressRunArgs({ key, uid: options.uid, gid: options.gid, code, allow: options.allow }), 30_000);
248
+ // A name another container holds fails here (Docker's conflict), and that container is left as it is.
249
+ if (started.code !== 0)
250
+ return failed(`docker run failed (${started.code})`);
251
+ ours = started.stdout.trim().split("\n").at(-1)?.trim() || undefined;
252
+ if (!ours)
253
+ return failed("docker run printed no container id");
254
+ // A close while it started: what it started goes too.
255
+ if (closed)
256
+ return (await removeOurs(), state);
257
+ const until = Date.now() + readyMs;
258
+ for (;;) {
259
+ const logs = await docker(["logs", "--tail", "20", ours], 5_000);
260
+ const lines = `${logs.stdout}\n${logs.stderr}`.split("\n").map((line) => line.trim());
261
+ if (lines.some((line) => line.startsWith(EGRESS_READY)))
262
+ return { state: "ready" };
263
+ if (closed)
264
+ return state;
265
+ if (Date.now() > until) {
266
+ const own = lines.filter((line) => OWN_WORDS.test(line)).at(-1);
267
+ return failed(own ?? `it did not say it was ready within ${Math.round(readyMs / 1000)} s`);
268
+ }
269
+ await new Promise((resolve) => setTimeout(resolve, 200));
270
+ }
271
+ };
272
+ const start = async () => {
273
+ try {
274
+ return await run();
275
+ }
276
+ catch (error) {
277
+ return failed(error.message);
278
+ }
279
+ };
280
+ let busy;
281
+ const once = (step) => (busy ??= step().finally(() => (busy = undefined)));
282
+ // The volume first, before any run is handed its name: a box that mounted a missing one would have Docker make it
283
+ // with its own defaults.
284
+ const noVolume = await ensureVolume().catch((error) => error.message);
285
+ if (noVolume) {
286
+ state = failed(noVolume);
287
+ return { state: () => state, close: async () => void (closed = true) };
288
+ }
289
+ const inspected = await docker(["image", "inspect", "--format", "{{.Id}}", EGRESS_IMAGE], 10_000);
290
+ if (inspected.code === 0)
291
+ set(await start());
292
+ else {
293
+ set({ state: "preparing", reason: `the box network proxy is pulling its image, ${EGRESS_IMAGE.split("@")[0]}` });
294
+ void once(async () => {
295
+ const pulled = await docker(["pull", "--quiet", EGRESS_IMAGE], options.pullMs ?? EGRESS_PULL_MS, stopping.signal);
296
+ if (closed)
297
+ return;
298
+ set(pulled.code === 0 ? await start() : failed(`docker pull ${EGRESS_IMAGE.split("@")[0]} failed (${pulled.code}): run it on this machine to see why`));
299
+ });
300
+ }
301
+ // Docker restarts a proxy that dies; one that is gone, or stopped, makes the network none at the first look, and the
302
+ // watch starts it again at the second in a row.
303
+ let misses = 0;
304
+ const watch = setInterval(() => {
305
+ if (closed || busy || state.state === "unavailable")
306
+ return;
307
+ void once(async () => {
308
+ const running = ours ? await docker(["inspect", "--format", "{{.State.Running}}", ours], 5_000) : undefined;
309
+ if (running?.code === 0 && running.stdout.trim() === "true") {
310
+ misses = 0;
311
+ if (state.state !== "ready")
312
+ set({ state: "ready" });
313
+ return;
314
+ }
315
+ set({ state: "preparing", reason: "the box network proxy is not running" });
316
+ if (++misses < 2)
317
+ return;
318
+ misses = 0;
319
+ set({ state: "preparing", reason: "the box network proxy was gone, and is starting again" });
320
+ set(await start());
321
+ });
322
+ }, options.watchMs ?? EGRESS_WATCH_MS);
323
+ watch.unref();
324
+ return {
325
+ volume: name,
326
+ state: () => state,
327
+ async close() {
328
+ closed = true;
329
+ clearInterval(watch);
330
+ stopping.abort();
331
+ // What was under way ends first (a pull or a wait is aborted; a start checks `closed`), so nothing of this server's
332
+ // touches Docker after its close.
333
+ await busy?.catch(() => undefined);
334
+ await removeOurs();
335
+ },
336
+ };
337
+ }
338
+ /** What the server hands a run's process on a Mac with the proxy container: its volume's name, which the run's Docker
339
+ * boxes mount read-only at EGRESS_MOUNT. Unset on Linux, where the run's process starts its own proxy (box-egress.ts). */
340
+ export const RUN_BOX_VOLUME_ENV = "AGENTRUN_RUN_BOX_VOLUME";
341
+ /** The run's process's reading of RUN_BOX_VOLUME_ENV: the volume, or undefined when it is unset or not a name this
342
+ * server makes. */
343
+ export function runBoxVolumeOf(env) {
344
+ const value = env[RUN_BOX_VOLUME_ENV]?.trim();
345
+ return value && /^agentrun-egress-[0-9a-f]{12}$/.test(value) ? value : undefined;
346
+ }
347
+ /** A run's box's egress on a Mac: the server's proxy container, its socket in the volume the Docker provider mounts on
348
+ * every box (run-box.ts), so nothing for the run's process to start or bind. The volume outlives each proxy, so a box
349
+ * made before one started again reaches the new one. */
350
+ export const vmEgress = async () => ({ socket: EGRESS_SOCKET, fresh: false });
@@ -36,7 +36,7 @@ export declare const removeEgressDir: (runId: string) => Promise<void>;
36
36
  * and where the proxy runs. Today that is hostEgress: the run's own process, its socket's directory on this machine
37
37
  * bound into the box. */
38
38
  export type BoxEgress = (runId: string) => Promise<{
39
- mount: {
39
+ mount?: {
40
40
  source: string;
41
41
  target: typeof EGRESS_MOUNT;
42
42
  readOnly: true;
@@ -86,7 +86,8 @@ export declare const STALE_EGRESS_MS = 60000;
86
86
  export declare function sweepEgressDirs(uid?: number, now?: number): Promise<number>;
87
87
  /** What a server's Docker boxes reach, resolved once at its start (run-box.ts boxNetworkOf): the list, or none and why. */
88
88
  export type DockerNetwork = {
89
- allow: readonly string[];
89
+ allow: readonly string[]; /** On a Mac, the VM runtime whose proxy container serves the list (box-egress-vm.ts). */
90
+ vm?: string;
90
91
  } | {
91
92
  allow: "none";
92
93
  reason: string;
@@ -32,6 +32,10 @@ export type VmSdk = {
32
32
  export declare function vmRelay(sdk: VmSdk, secrets?: () => readonly string[]): {
33
33
  handle(runId: string, path: string, req: IncomingMessage, res: ServerResponse): Promise<void>;
34
34
  drop(runId: string): void;
35
+ footprint(): {
36
+ programs: number;
37
+ starting: number;
38
+ };
35
39
  };
36
40
  /** How the run's process's relay client waits on the relay: never on a clock of its own. A program's exit (`wait`) and
37
41
  * its output streams take as long as the program runs, which its caller bounds (bash's timeout, and pi-transport's
@@ -22,7 +22,7 @@ const MAX_BUFFERED_BYTES = 16 * 2 ** 20;
22
22
  /** How long a program the run's process stopped asking about is held, once it exited. A program is let go:
23
23
  * - once its exit was read (or failed to be) and both its output replies ended, whole or broken (settle);
24
24
  * - at once when a caller goes away mid-read (the reply's close);
25
- * - at the run's end (drop), whatever it is doing;
25
+ * - at the run's end (drop), whatever it is doing, a program still starting then included, as it lands;
26
26
  * - else EXEC_KEEP_MS after its exit: an exit or an output not read yet is still the caller's to read.
27
27
  * A program still running holds its slot until it exits or the run ends. */
28
28
  const EXEC_KEEP_MS = 10 * 60_000;
@@ -80,8 +80,23 @@ function pump(source) {
80
80
  export function vmRelay(sdk, secrets = () => []) {
81
81
  const known = new Map();
82
82
  const execs = new Map();
83
- /** The programs each run is starting now: counted with those it holds, so starts at once cannot pass the limit. */
83
+ /** The program starts each run has under way, from the moment its request is taken (before the sandbox's lookup): each
84
+ * counts toward the run's limit, and one its run's end (drop) marks is let go as it lands, never held. A run is here
85
+ * only while it has one, so an ended run leaves nothing behind. */
84
86
  const starting = new Map();
87
+ const startOf = (runId) => {
88
+ const start = { dropped: false };
89
+ const starts = starting.get(runId) ?? new Set();
90
+ starts.add(start);
91
+ starting.set(runId, starts);
92
+ return start;
93
+ };
94
+ const started = (runId, start) => {
95
+ const starts = starting.get(runId);
96
+ starts?.delete(start);
97
+ if (starts && !starts.size)
98
+ starting.delete(runId);
99
+ };
85
100
  /** Sandbox `id` and the run its label names, as the provider says; undefined when it has none. */
86
101
  const sandboxOf = async (id) => {
87
102
  const held = known.get(id);
@@ -126,65 +141,67 @@ export function vmRelay(sdk, secrets = () => []) {
126
141
  if (req.method !== "POST")
127
142
  return answer(res, 405, { message: "the Modal sandbox relay takes POST" });
128
143
  const onSandbox = /^sandbox\/([^/]+)\/(find|poll|tags|exec)$/.exec(path);
129
- if (onSandbox) {
130
- const id = decodeURIComponent(onSandbox[1]);
131
- let found;
132
- try {
133
- found = await sandboxOf(id);
134
- }
135
- catch (error) {
136
- return failureOf(error).name === "NotFoundError" || failureOf(error).code === 5 ? notThere(res) : failed(res, error);
137
- }
138
- // A sandbox of another run, or of none, is not there for this one: as the provider answers one it does not have.
139
- if (found.run !== runId)
140
- return notThere(res);
144
+ // A start is under way from here: a run's end while its sandbox is looked up, or its program started, still finds it.
145
+ const start = onSandbox?.[2] === "exec" ? startOf(runId) : undefined;
146
+ if (onSandbox)
141
147
  try {
142
- switch (onSandbox[2]) {
143
- case "find":
144
- return answer(res, 200, { id });
145
- case "poll":
146
- return answer(res, 200, { code: await found.sandbox.poll() });
147
- case "tags":
148
- return answer(res, 200, { tags: await found.sandbox.getTags() });
149
- default: {
150
- const body = (await jsonOf(req));
151
- const command = body?.command;
152
- if (!Array.isArray(command) || !command.length || !command.every((part) => typeof part === "string"))
153
- return answer(res, 400, { message: "exec names its command: a list of strings" });
154
- const pending = starting.get(runId) ?? 0;
155
- if ([...execs.values()].filter((held) => held.run === runId).length + pending >= MAX_EXECS_PER_RUN)
156
- return answer(res, 429, { message: `a run holds at most ${MAX_EXECS_PER_RUN} programs in its box at once` });
157
- // Its slot is taken before the start is awaited, and given back once the program is held or did not start.
158
- starting.set(runId, pending + 1);
159
- let process;
160
- try {
161
- process = await found.sandbox.exec(command, { mode: "binary", ...(typeof body?.workdir === "string" ? { workdir: body.workdir } : {}), ...(typeof body?.timeoutMs === "number" ? { timeoutMs: body.timeoutMs } : {}) });
162
- }
163
- finally {
164
- const left = (starting.get(runId) ?? 1) - 1;
165
- if (left > 0)
166
- starting.set(runId, left);
167
- else
168
- starting.delete(runId);
148
+ const id = decodeURIComponent(onSandbox[1]);
149
+ let found;
150
+ try {
151
+ found = await sandboxOf(id);
152
+ }
153
+ catch (error) {
154
+ return failureOf(error).name === "NotFoundError" || failureOf(error).code === 5 ? notThere(res) : failed(res, error);
155
+ }
156
+ // A sandbox of another run, or of none, is not there for this one: as the provider answers one it does not have.
157
+ if (found.run !== runId)
158
+ return notThere(res);
159
+ try {
160
+ switch (onSandbox[2]) {
161
+ case "find":
162
+ return answer(res, 200, { id });
163
+ case "poll":
164
+ return answer(res, 200, { code: await found.sandbox.poll() });
165
+ case "tags":
166
+ return answer(res, 200, { tags: await found.sandbox.getTags() });
167
+ default: {
168
+ const body = (await jsonOf(req));
169
+ const command = body?.command;
170
+ if (!Array.isArray(command) || !command.length || !command.every((part) => typeof part === "string"))
171
+ return answer(res, 400, { message: "exec names its command: a list of strings" });
172
+ // Its slot was taken as the request came (startOf), and is given back once the program is held or did not start.
173
+ const others = (starting.get(runId)?.size ?? 1) - 1;
174
+ if ([...execs.values()].filter((held) => held.run === runId).length + others >= MAX_EXECS_PER_RUN)
175
+ return answer(res, 429, { message: `a run holds at most ${MAX_EXECS_PER_RUN} programs in its box at once` });
176
+ const process = await found.sandbox.exec(command, { mode: "binary", ...(typeof body?.workdir === "string" ? { workdir: body.workdir } : {}), ...(typeof body?.timeoutMs === "number" ? { timeoutMs: body.timeoutMs } : {}) });
177
+ // The run's programs were let go while this one started (its end): it is let go too, its output never read.
178
+ if (start.dropped) {
179
+ for (const stream of [process.stdout, process.stderr])
180
+ void Promise.resolve(stream[Symbol.asyncIterator]().return?.()).catch(() => undefined);
181
+ return answer(res, 410, { message: "the run ended while the program started: it is not held" });
182
+ }
183
+ const exec = randomUUID();
184
+ const held = { run: runId, process, streams: { stdout: pump(process.stdout), stderr: pump(process.stderr) }, waited: false, read: new Set(), finished: new Set() };
185
+ execs.set(exec, held);
186
+ process.wait().then((code) => {
187
+ held.exited = code;
188
+ settle(exec);
189
+ }, () => {
190
+ held.exited = -1;
191
+ settle(exec);
192
+ });
193
+ return answer(res, 200, { exec });
169
194
  }
170
- const exec = randomUUID();
171
- const held = { run: runId, process, streams: { stdout: pump(process.stdout), stderr: pump(process.stderr) }, waited: false, read: new Set(), finished: new Set() };
172
- execs.set(exec, held);
173
- process.wait().then((code) => {
174
- held.exited = code;
175
- settle(exec);
176
- }, () => {
177
- held.exited = -1;
178
- settle(exec);
179
- });
180
- return answer(res, 200, { exec });
181
195
  }
182
196
  }
197
+ catch (error) {
198
+ return failed(res, error);
199
+ }
183
200
  }
184
- catch (error) {
185
- return failed(res, error);
201
+ finally {
202
+ if (start)
203
+ started(runId, start);
186
204
  }
187
- }
188
205
  const onExec = /^exec\/([^/]+)\/(stdin|stdin-close|stdout|stderr|wait)$/.exec(path);
189
206
  if (!onExec)
190
207
  return refused(res, path);
@@ -277,10 +294,14 @@ export function vmRelay(sdk, secrets = () => []) {
277
294
  return {
278
295
  handle,
279
296
  drop(runId) {
297
+ for (const start of starting.get(runId) ?? [])
298
+ start.dropped = true;
280
299
  for (const [id, held] of execs)
281
300
  if (held.run === runId)
282
301
  forget(id);
283
302
  },
303
+ /** What the relay holds now, for the tests: its programs, and the runs with a start under way. */
304
+ footprint: () => ({ programs: execs.size, starting: starting.size }),
284
305
  };
285
306
  }
286
307
  async function bytesOf(req) {
package/dist/boxes.d.ts CHANGED
@@ -46,8 +46,10 @@ export type BoxRegistryOptions = {
46
46
  timeoutMs?: number;
47
47
  vmSdk?: () => Promise<Record<string, unknown>>;
48
48
  };
49
- /** The setting that lists the boxes to set up: a comma list of box ids. */
49
+ /** The setting that lists the boxes to set up: a comma list of box ids, empty or `none` for no box. */
50
50
  export declare const BOXES_ENV = "AGENTRUN_BOXES";
51
+ /** The boxes a server sets up when AGENTRUN_BOXES is not set at all: Docker, probed as if listed. */
52
+ export declare const DEFAULT_BOXES: readonly BoxId[];
51
53
  /** The VM provider's app, which its sandboxes live in (made when missing). */
52
54
  export declare const BOX_APP_ENV = "AGENTRUN_BOX_APP";
53
55
  /** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
@@ -62,7 +64,10 @@ export declare function daytonaApi(env: NodeJS.ProcessEnv): {
62
64
  export declare const BOX_KEYS: readonly string[];
63
65
  /** How long one box's probe may take; the probes run at once, so this bounds them all. */
64
66
  export declare const PROBE_TIMEOUT_MS = 5000;
65
- /** The boxes `env` lists in AGENTRUN_BOXES; a name that is no box throws, naming it. */
67
+ /** Whether `env` leaves the boxes to this server's default (DEFAULT_BOXES): AGENTRUN_BOXES is not set at all. */
68
+ export declare const boxesByDefault: (env: NodeJS.ProcessEnv) => boolean;
69
+ /** The boxes `env` lists in AGENTRUN_BOXES, DEFAULT_BOXES when it is not set, none when it is empty or `none`; a name
70
+ * that is no box throws, naming it, and so does `none` with another. */
66
71
  export declare function enabledBoxes(env: NodeJS.ProcessEnv): Set<BoxId>;
67
72
  /** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
68
73
  * `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box