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

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 (152) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +564 -97
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +11 -5
  6. package/dist/agents.js +16 -10
  7. package/dist/app.js +80 -20
  8. package/dist/background.d.ts +28 -0
  9. package/dist/background.js +376 -0
  10. package/dist/box-egress.d.ts +98 -0
  11. package/dist/box-egress.js +259 -0
  12. package/dist/box-image.d.ts +1 -1
  13. package/dist/box-image.js +9 -7
  14. package/dist/box-relay-vm.d.ts +80 -0
  15. package/dist/box-relay-vm.js +389 -0
  16. package/dist/box-relay.d.ts +8 -5
  17. package/dist/box-relay.js +14 -9
  18. package/dist/boxes.d.ts +21 -3
  19. package/dist/boxes.js +14 -7
  20. package/dist/browser-cost.d.ts +41 -0
  21. package/dist/browser-cost.js +158 -0
  22. package/dist/cap.d.ts +129 -21
  23. package/dist/cap.js +338 -67
  24. package/dist/coding-tools.d.ts +7 -3
  25. package/dist/coding-tools.js +16 -10
  26. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  27. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  28. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  29. package/dist/console/index.html +2 -2
  30. package/dist/content-filter.d.ts +7 -0
  31. package/dist/content-filter.js +23 -0
  32. package/dist/decision-rows.d.ts +11 -3
  33. package/dist/decision-rows.js +18 -11
  34. package/dist/errors.d.ts +2 -0
  35. package/dist/errors.js +5 -2
  36. package/dist/files.d.ts +6 -1
  37. package/dist/files.js +7 -2
  38. package/dist/grade.d.ts +7 -10
  39. package/dist/grade.js +31 -51
  40. package/dist/graph-served.d.ts +23 -0
  41. package/dist/graph-served.js +75 -0
  42. package/dist/graph-view.d.ts +7 -5
  43. package/dist/graph-view.js +10 -3
  44. package/dist/harness-app.d.ts +4 -2
  45. package/dist/harness-app.js +101 -19
  46. package/dist/harness-opencode/adapter.d.ts +45 -0
  47. package/dist/harness-opencode/adapter.js +272 -0
  48. package/dist/harness-opencode/binary.d.ts +18 -0
  49. package/dist/harness-opencode/binary.js +87 -0
  50. package/dist/harness-opencode/config.d.ts +24 -0
  51. package/dist/harness-opencode/config.js +61 -0
  52. package/dist/harness-opencode/harness.d.ts +77 -0
  53. package/dist/harness-opencode/harness.js +620 -0
  54. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  55. package/dist/harness-opencode/host/mcp.js +208 -0
  56. package/dist/harness-opencode/host/policy.d.ts +71 -0
  57. package/dist/harness-opencode/host/policy.js +419 -0
  58. package/dist/harness-opencode/host/server.d.ts +55 -0
  59. package/dist/harness-opencode/host/server.js +165 -0
  60. package/dist/harness-opencode/index.d.ts +9 -0
  61. package/dist/harness-opencode/index.js +6 -0
  62. package/dist/harness-opencode/verify.d.ts +32 -0
  63. package/dist/harness-opencode/verify.js +75 -0
  64. package/dist/harness-opencode/versions.d.ts +33 -0
  65. package/dist/harness-opencode/versions.js +64 -0
  66. package/dist/harness.d.ts +4 -1
  67. package/dist/harness.js +5 -2
  68. package/dist/host-tools.d.ts +12 -2
  69. package/dist/host-tools.js +26 -12
  70. package/dist/host.js +6 -2
  71. package/dist/hosted-search.js +5 -1
  72. package/dist/import.d.ts +2 -2
  73. package/dist/import.js +4 -3
  74. package/dist/key-check.d.ts +3 -2
  75. package/dist/key-check.js +7 -3
  76. package/dist/key-refusal.js +8 -4
  77. package/dist/learn/check.d.ts +10 -1
  78. package/dist/learn/check.js +19 -1
  79. package/dist/learn/grade.d.ts +3 -2
  80. package/dist/learn/grade.js +25 -13
  81. package/dist/learn/index.d.ts +2 -2
  82. package/dist/learn/index.js +2 -2
  83. package/dist/learn/notes.js +2 -1
  84. package/dist/learn/reflect.d.ts +2 -2
  85. package/dist/learn/reflect.js +51 -5
  86. package/dist/learn/secrets.js +28 -8
  87. package/dist/learn/skills.d.ts +17 -4
  88. package/dist/learn/skills.js +79 -6
  89. package/dist/learned-workflow.d.ts +59 -0
  90. package/dist/learned-workflow.js +191 -0
  91. package/dist/learning-run.d.ts +7 -5
  92. package/dist/learning-run.js +45 -23
  93. package/dist/learning-words.d.ts +6 -3
  94. package/dist/learning-words.js +8 -5
  95. package/dist/learning.d.ts +44 -3
  96. package/dist/learning.js +148 -3
  97. package/dist/mcp-servers.d.ts +7 -4
  98. package/dist/mcp-servers.js +5 -0
  99. package/dist/mcp.js +5 -5
  100. package/dist/model.d.ts +13 -11
  101. package/dist/model.js +11 -10
  102. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  103. package/dist/openapi.js +358 -48
  104. package/dist/paid-calls.d.ts +5 -1
  105. package/dist/paid-calls.js +1 -1
  106. package/dist/pause.d.ts +2 -0
  107. package/dist/place.d.ts +27 -4
  108. package/dist/place.js +42 -10
  109. package/dist/propose.d.ts +2 -0
  110. package/dist/propose.js +38 -8
  111. package/dist/request-start.d.ts +12 -4
  112. package/dist/request-start.js +139 -15
  113. package/dist/run-box.d.ts +56 -4
  114. package/dist/run-box.js +173 -23
  115. package/dist/runnable.d.ts +5 -2
  116. package/dist/runnable.js +12 -4
  117. package/dist/runs.d.ts +258 -36
  118. package/dist/runs.js +830 -89
  119. package/dist/secrets.d.ts +12 -0
  120. package/dist/secrets.js +18 -0
  121. package/dist/server.d.ts +131 -35
  122. package/dist/server.js +467 -105
  123. package/dist/sign-ins.d.ts +99 -0
  124. package/dist/sign-ins.js +288 -0
  125. package/dist/skills.d.ts +16 -4
  126. package/dist/skills.js +35 -7
  127. package/dist/stats.d.ts +7 -2
  128. package/dist/stats.js +28 -7
  129. package/dist/tool-gate.d.ts +266 -0
  130. package/dist/tool-gate.js +554 -0
  131. package/dist/tool-keys.d.ts +46 -10
  132. package/dist/tool-keys.js +44 -2
  133. package/dist/tool-plane.d.ts +112 -27
  134. package/dist/tool-plane.js +205 -47
  135. package/dist/tools.d.ts +69 -14
  136. package/dist/tools.js +143 -24
  137. package/dist/trigger-secrets.d.ts +32 -0
  138. package/dist/trigger-secrets.js +143 -0
  139. package/dist/triggers.d.ts +439 -0
  140. package/dist/triggers.js +863 -0
  141. package/dist/turn-end.d.ts +3 -2
  142. package/dist/turn-end.js +3 -2
  143. package/dist/usage-lines.d.ts +26 -0
  144. package/dist/usage-lines.js +28 -0
  145. package/dist/validate.d.ts +2 -0
  146. package/dist/validate.js +11 -2
  147. package/dist/webhooks.d.ts +11 -4
  148. package/dist/webhooks.js +17 -1
  149. package/launcher/agentrun-serve +1 -1
  150. package/package.json +19 -13
  151. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  152. package/dist/console/assets/index-By-jkqki.css +0 -1
@@ -0,0 +1,259 @@
1
+ // A Docker box's way out to the network: the hosts on the server's list (AGENTRUN_BOX_ALLOW), and nothing else. The box
2
+ // stays `--network none`, with its own loopback alone. The run's process starts the kernel's egress proxy with the list
3
+ // (@parcha/agentrun-kernel/host), on a Unix socket in a directory of its own, which is bound into the box read-only at
4
+ // EGRESS_MOUNT; a socat in the box relays its own loopback port EGRESS_PORT to it, and the box's fixed environment
5
+ // names that port as its HTTP(S) proxy. The proxy refuses, before any lookup, a host off the list, an IP literal and any port but 80 and
6
+ // 443, and a listed name that resolves to a private or metadata address; it holds no key and adds none. A program in the
7
+ // box that ignores the proxy variables has no route and no resolver: its connection is unreachable. The list is the
8
+ // setting's one reading (run-box.ts boxAllowOf), as the server resolves it for this machine (boxNetworkOf); with `none`,
9
+ // a box is as it was: no proxy, no mount, no proxy variables. The proxy is never started without an explicit list: one
10
+ // with none would reach every public host.
11
+ import { execFile } from "node:child_process";
12
+ import { createHash } from "node:crypto";
13
+ import { statSync } from "node:fs";
14
+ import { lstat, mkdir, readdir, rm } from "node:fs/promises";
15
+ import { connect } from "node:net";
16
+ import { release } from "node:os";
17
+ import { join } from "node:path";
18
+ import { pathToFileURL } from "node:url";
19
+ import { parseAllow, startEgressProxy } from "@parcha/agentrun-kernel/host";
20
+ import { FAUX_ENV } from "./model.js";
21
+ import { withoutSecrets } from "./secrets.js";
22
+ /** Where the proxy's directory is in the box, read-only. */
23
+ export const EGRESS_MOUNT = "/run/agentrun/egress";
24
+ /** The proxy's socket, in its directory. */
25
+ export const EGRESS_SOCKET = "egress.sock";
26
+ /** The box's loopback port socat relays to the socket. */
27
+ export const EGRESS_PORT = 3128;
28
+ /** The box's own loopback, where its relay listens: never a service of this machine's. */
29
+ const BOX_LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule the box own loopback where its relay listens
30
+ /** The proxy's address in the box: EGRESS_PORT on its loopback. */
31
+ const PROXY_URL = `http://${BOX_LOOPBACK}:${EGRESS_PORT}`;
32
+ const NO_PROXY = "localhost,127.0.0.1,::1"; // key-gate: loopback-rule the box own loopback names the proxy leaves out
33
+ /** What a box with a list adds to its fixed environment (run-box.ts BOX_ENV): constants, no user, no password. */
34
+ export const PROXY_ENV = Object.freeze({ HTTP_PROXY: PROXY_URL, HTTPS_PROXY: PROXY_URL, http_proxy: PROXY_URL, https_proxy: PROXY_URL, NO_PROXY, no_proxy: NO_PROXY });
35
+ /** The box's relay to the proxy's socket `socket` (in EGRESS_MOUNT), started once each time the run's box opens (made
36
+ * or found): a second one finds the port taken and exits. Each connection opens the socket by its path, so a proxy
37
+ * started again is reached with no new relay. */
38
+ export const forwarder = (socket = EGRESS_SOCKET) => ["socat", `TCP-LISTEN:${EGRESS_PORT},bind=127.0.0.1,reuseaddr,fork`, `UNIX-CONNECT:${EGRESS_MOUNT}/${socket}`]; // key-gate: loopback-rule the box own proxy port inside the box
39
+ /** How long the relay has to listen once started, in tenths of a second. */
40
+ const RELAY_WAIT_TENTHS = 30;
41
+ /** EGRESS_PORT on the box's loopback as /proc/net/tcp writes a listening socket: address and port in hex, state 0A. */
42
+ const LISTENING = ` 0100007F:${EGRESS_PORT.toString(16).toUpperCase().padStart(4, "0")} 00000000:0000 0A `;
43
+ /** The relay's start, in the box, answered once it listens: exit 127 when the image has no socat, 126 when it has no
44
+ * setsid, and 124 when the relay is not listening within 3 s (its own error, if it gave one, on stderr). A relay a
45
+ * process before this one started still listens, so a second start finds the port taken and answers at once. */
46
+ export const forwarderStart = (socket = EGRESS_SOCKET) => ["sh", "-c", [
47
+ "command -v socat >/dev/null 2>&1 || exit 127",
48
+ "command -v setsid >/dev/null 2>&1 || exit 126",
49
+ `listening() { grep -q '${LISTENING}' /proc/net/tcp 2>/dev/null; }`,
50
+ "listening && exit 0",
51
+ `log=$(mktemp); setsid ${forwarder(socket).join(" ")} </dev/null >/dev/null 2>"$log" &`,
52
+ `i=0; while [ "$i" -lt ${RELAY_WAIT_TENTHS} ]; do listening && { rm -f "$log"; exit 0; }; i=$((i + 1)); sleep 0.1; done`,
53
+ `head -c 300 "$log" >&2; rm -f "$log"; exit 124`,
54
+ ].join("\n")];
55
+ /** The timeline row of a box whose relay could not start, by the start's exit (forwarderStart): the box keeps no network. */
56
+ export function relayFailed(code, said) {
57
+ if (code === 127)
58
+ return "This box's image has no socat, so it has no network. Add socat to the image, or set AGENTRUN_BOX_ALLOW=none to silence this.";
59
+ if (code === 126)
60
+ return "This box's image has no setsid, so it has no network. Add util-linux's setsid to the image, or set AGENTRUN_BOX_ALLOW=none to silence this.";
61
+ const why = said.trim().replace(/[\u0000-\u001f]+/g, " ").slice(0, 200);
62
+ return `This box's network relay did not start within 3 s (${code === 124 ? why || "it was not listening" : `exit ${code}`}), so it has no network.`;
63
+ }
64
+ /** The row for an image with no socat (relayFailed 127). */
65
+ export const NO_SOCAT = relayFailed(127, "");
66
+ /** What a refusal of a host off the list says to do, after its words. */
67
+ export const ALLOW_HINT = `use web_fetch for web pages, or ask the operator to add it to AGENTRUN_BOX_ALLOW`;
68
+ /** Each run's proxy: connections open at once, and in all. */
69
+ export const MAX_TUNNELS = 64;
70
+ export const MAX_CONNECTIONS = 20_000;
71
+ /** Under `--faux` only: a module whose default export gives the proxy's `lookup` and `dial` (the tests' fake network), so
72
+ * a test's box reaches no host but its fake. */
73
+ export const FAUX_EGRESS_ENV = "AGENTRUN_SERVE_FAUX_EGRESS";
74
+ /** The proxy's directory for run `runId`: short, so its socket's path stays within a Unix socket's limit (107 bytes)
75
+ * wherever the data root is, and the same each time the run's process starts, since the box keeps its bind. */
76
+ export function egressDir(runId, uid = process.getuid?.() ?? 0) {
77
+ return join("/tmp", `agentrun-egress-${uid}`, createHash("sha256").update(runId).digest("hex").slice(0, 16));
78
+ }
79
+ /** Removes a run's proxy directory once its box is gone. */
80
+ export const removeEgressDir = (runId) => rm(egressDir(runId), { recursive: true, force: true });
81
+ /** This user's parent directory in /tmp: made 0700, and refused unless it is a directory of this user's, not a link. */
82
+ async function ownParent(dir) {
83
+ await mkdir(dir, { recursive: true, mode: 0o700 });
84
+ const at = await lstat(dir);
85
+ const uid = process.getuid?.();
86
+ if (!at.isDirectory() || at.isSymbolicLink() || (uid !== undefined && at.uid !== uid) || (at.mode & 0o077) !== 0) {
87
+ throw new Error(`the box's network directory ${dir} is not a directory of this user's alone (0700, not a link): remove it, or set AGENTRUN_BOX_ALLOW=none`);
88
+ }
89
+ }
90
+ /** The proxy in the run's process (hostEgress): for a Docker daemon on this Linux machine, which can reach a socket in a
91
+ * directory of this machine bound into a container. */
92
+ export const hostEgress = (allow, env, log) => async (runId) => {
93
+ const { dir, fresh } = await runProxy(runId, allow, env, log);
94
+ return { mount: { source: dir, target: EGRESS_MOUNT, readOnly: true }, socket: EGRESS_SOCKET, fresh };
95
+ };
96
+ const started = new Map();
97
+ const opened = new Set();
98
+ /** Run `runId`'s proxy in this process, with `allow`, started once: its directory, to bind into the box, and whether that
99
+ * directory was made now (`fresh`): a box bound to one an earlier process made, which the start's sweep took since, holds
100
+ * the old directory, not this one. Its decisions go to `log`. */
101
+ async function runProxy(runId, allow, env, log) {
102
+ const dir = egressDir(runId);
103
+ let proxy = started.get(runId);
104
+ if (!proxy) {
105
+ proxy = (async () => {
106
+ await ownParent(join(dir, ".."));
107
+ const fresh = await mkdir(dir, { mode: 0o700 }).then(() => true, (error) => {
108
+ if (error.code !== "EEXIST")
109
+ throw error;
110
+ return false;
111
+ });
112
+ const proxy = await startEgressProxy({ socketPath: join(dir, EGRESS_SOCKET), maxTunnels: MAX_TUNNELS, maxConnections: MAX_CONNECTIONS, log, allow: [...allow], allowHint: ALLOW_HINT, ...(await fauxSeams(env)) });
113
+ log(`egress start allow=${allow.join(",")}`);
114
+ return { proxy, fresh };
115
+ })();
116
+ started.set(runId, proxy);
117
+ proxy.catch(() => started.delete(runId));
118
+ }
119
+ // Fresh once: a later open in this process binds what the first one did.
120
+ const fresh = (await proxy).fresh && !opened.has(runId);
121
+ opened.add(runId);
122
+ return { dir, fresh };
123
+ }
124
+ /** The tests' seams, under `--faux` with FAUX_EGRESS_ENV set: its module's. */
125
+ async function fauxSeams(env) {
126
+ const module = env[FAUX_ENV] ? env[FAUX_EGRESS_ENV] : undefined;
127
+ if (!module)
128
+ return {};
129
+ return (await import(pathToFileURL(module).href)).default();
130
+ }
131
+ /** How long `docker info` may take to say where this Docker runs. */
132
+ export const INFO_TIMEOUT_MS = 5_000;
133
+ /** A platform by the name people use. */
134
+ const PLATFORM_NAMES = { darwin: "macOS", win32: "Windows" };
135
+ /** What `docker info` is asked: the daemon's OS type, its kernel, where it keeps its data, and the name it gives its OS. */
136
+ export const INFO_FORMAT = "{{.OSType}}|{{.KernelVersion}}|{{.DockerRootDir}}|{{.OperatingSystem}}";
137
+ /** `docker info` in the server's environment through the cut a run's takes, nothing on its stdin, within `timeoutMs`. */
138
+ export const dockerInfo = (env, timeoutMs) => new Promise((resolve, reject) => execFile("docker", ["info", "--format", INFO_FORMAT], { env: withoutSecrets(env), timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 64 * 1024 }, (error, stdout) => {
139
+ if (!error)
140
+ return resolve(String(stdout));
141
+ const failed = error;
142
+ reject(new Error(failed.killed ? `it did not answer within ${Math.round(timeoutMs / 1000)} s` : typeof failed.code === "number" ? `it failed (exit ${failed.code})` : `it failed (${failed.code ?? failed.name})`));
143
+ }).stdin?.end());
144
+ /**
145
+ * Why a Docker box on this server cannot reach its proxy, or undefined when it can. The proxy's socket is a file of this
146
+ * machine bound into the box, which only a Docker daemon on this same Linux machine can connect to: a daemon in a VM
147
+ * (Docker Desktop, OrbStack and their kin) sees the socket and is refused. So the network goes on only with positive
148
+ * evidence that the daemon is this machine's: this machine is Linux; the docker CLI's endpoint is a local unix socket
149
+ * (no DOCKER_HOST or a unix:// one, and the default context or a unix one: pi-transport's dockerDaemon); and `docker
150
+ * info` answers within its bound with OS type linux and this machine's own kernel (os.release()): the same kernel, so no
151
+ * VM in between; and the directory it keeps its data in (DockerRootDir) is one this server sees. A server in a container
152
+ * given the host's docker socket shares the host's kernel, but not its files: it would bind a directory the daemon does
153
+ * not have, so every box would fail to start. Anything else is no network, and the reason says what was seen, naming the
154
+ * runtime docker info gives. A kernel is the evidence, not a runtime's name: Docker Desktop on WSL2 runs the kernel this
155
+ * server does, but keeps its data outside the distro, so it passes only where the distro has that directory too.
156
+ */
157
+ export async function egressBlockedBy(env, options = {}) {
158
+ const platform = options.platform ?? process.platform;
159
+ if (platform !== "linux")
160
+ return `this server runs on ${PLATFORM_NAMES[platform] ?? platform}, where Docker runs in a VM that can't reach this server's egress proxy yet`;
161
+ const { dockerDaemon } = await import("@parcha/pi-transport/box/docker");
162
+ const daemon = dockerDaemon(env);
163
+ if (!daemon.local)
164
+ return `this Docker (${daemon.named}) is not on this machine, so it can't reach this server's egress proxy`;
165
+ let answer;
166
+ try {
167
+ answer = await (options.info ?? dockerInfo)(env, options.timeoutMs ?? INFO_TIMEOUT_MS);
168
+ }
169
+ catch (error) {
170
+ return `docker info did not say where this Docker runs (${error.message}), so this server can't tell it is on this machine`;
171
+ }
172
+ const fields = answer.trim().split("|");
173
+ const [osType, kernel, root, name] = fields.map((field) => field.trim());
174
+ const shown = (text) => JSON.stringify(text.slice(0, 80));
175
+ if (fields.length !== 4 || !osType || !kernel || !root)
176
+ return `docker info's answer could not be read (${shown(answer.trim())}), so this server can't tell this Docker is on this machine`;
177
+ const runtime = name ? `this Docker (${name.slice(0, 80)})` : "this Docker";
178
+ if (osType !== "linux")
179
+ return `${runtime} runs ${shown(osType)} containers, not Linux ones on this machine, so it can't reach this server's egress proxy`;
180
+ const here = options.kernel ?? release();
181
+ if (kernel !== here)
182
+ return `${runtime} runs in a VM (its kernel is ${shown(kernel)}, this machine's ${shown(here)}) that can't reach this server's egress proxy yet`;
183
+ const sees = options.sees ?? ((dir) => {
184
+ try {
185
+ return statSync(dir).isDirectory();
186
+ }
187
+ catch {
188
+ return false;
189
+ }
190
+ });
191
+ if (!sees(root))
192
+ return `${runtime} keeps its data in ${shown(root)}, which this server can't see: it runs on another machine's files (this server in a container, given the host's docker socket), so it can't reach this server's egress proxy`;
193
+ return undefined;
194
+ }
195
+ /** How old a run's proxy directory with no live socket must be before the start's sweep takes it: one just made, whose
196
+ * proxy is still starting, is not yet listening. */
197
+ export const STALE_EGRESS_MS = 60_000;
198
+ /**
199
+ * The start's sweep of this user's proxy directories (egressDir's parent): each whose socket refuses a connect (or has
200
+ * none) and that is older than STALE_EGRESS_MS is a run's process that is gone, and is removed, by its exact path. One
201
+ * whose socket answers is a live run's, this server's or another's under this uid, and stays. Returns how many went.
202
+ */
203
+ export async function sweepEgressDirs(uid = process.getuid?.() ?? 0, now = Date.now()) {
204
+ const parent = join("/tmp", `agentrun-egress-${uid}`);
205
+ let names;
206
+ try {
207
+ const at = await lstat(parent);
208
+ if (!at.isDirectory() || at.isSymbolicLink() || at.uid !== uid)
209
+ return 0;
210
+ names = await readdir(parent);
211
+ }
212
+ catch {
213
+ return 0;
214
+ }
215
+ let removed = 0;
216
+ for (const name of names) {
217
+ if (!/^[0-9a-f]{16}$/.test(name))
218
+ continue;
219
+ const dir = join(parent, name);
220
+ try {
221
+ const at = await lstat(dir);
222
+ if (!at.isDirectory() || at.isSymbolicLink() || at.uid !== uid || now - at.mtimeMs < STALE_EGRESS_MS)
223
+ continue;
224
+ }
225
+ catch {
226
+ continue;
227
+ }
228
+ if (await answers(join(dir, EGRESS_SOCKET)))
229
+ continue;
230
+ await rm(dir, { recursive: true, force: true });
231
+ removed++;
232
+ }
233
+ return removed;
234
+ }
235
+ /** Whether a Unix socket at `path` takes a connection: no for a refusal or no such file, yes for anything else. */
236
+ function answers(path) {
237
+ return new Promise((resolve) => {
238
+ const socket = connect(path);
239
+ const timer = setTimeout(() => (socket.destroy(), resolve(true)), 2_000);
240
+ socket.once("connect", () => (clearTimeout(timer), socket.destroy(), resolve(true)));
241
+ socket.once("error", (error) => (clearTimeout(timer), resolve(error.code !== "ECONNREFUSED" && error.code !== "ENOENT")));
242
+ });
243
+ }
244
+ /** What the server hands a run's process: the list its box reaches, resolved (boxNetworkOf), or `none`. The run's
245
+ * process reads this, never AGENTRUN_BOX_ALLOW: unset, it is none. */
246
+ export const RUN_BOX_ALLOW_ENV = "AGENTRUN_RUN_BOX_ALLOW";
247
+ /** The run's process's reading of RUN_BOX_ALLOW_ENV: the list, or `none` when it says so, is unset or is not a list. */
248
+ export function runBoxAllowOf(env) {
249
+ const value = env[RUN_BOX_ALLOW_ENV]?.trim();
250
+ if (!value || value === "none")
251
+ return "none";
252
+ try {
253
+ const list = parseAllow(value);
254
+ return list.length ? list : "none";
255
+ }
256
+ catch {
257
+ return "none";
258
+ }
259
+ }
@@ -3,7 +3,7 @@ import { type BoxOffer } from "./boxes.js";
3
3
  /** The setting that names another image for Docker boxes than this server's own. */
4
4
  export declare const DOCKER_IMAGE_ENV = "AGENTRUN_DOCKER_IMAGE";
5
5
  /** What the default image has, in words. */
6
- export declare const RECIPE_HAS = "python, git, curl, node, rg";
6
+ export declare const RECIPE_HAS = "python, git, curl, node, npm, rg";
7
7
  /** The base the default image builds from: `python:3.12-slim`, pinned to the multi-arch index digest Docker Hub served
8
8
  * 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
9
9
  * again (an anonymous pull token from auth.docker.io for `repository:library/python:pull`, then a HEAD of
package/dist/box-image.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // The image a Docker box starts from, made ready at the server's start, so a run's first tool call is never a silent pull
2
- // or build. By default it is this server's own, built here from BOX_RECIPE (python 3.12 with git and curl), tagged
2
+ // or build. By default it is this server's own, built here from BOX_RECIPE (python 3.12 with git, curl, node, npm and rg,
3
+ // and socat, the relay to the box's network proxy when it has one: box-egress.ts), tagged
3
4
  // `agentrun-box:<the recipe's hash>` and labelled with the whole hash (RECIPE_LABEL): built on first use, and again only
4
5
  // when the recipe changes. AGENTRUN_DOCKER_IMAGE names another image instead, which is pulled when Docker has none.
5
6
  //
@@ -10,7 +11,8 @@
10
11
  // RETRY_AFTER_MS later, docker preparing meanwhile with why ("trying once more: <the failure>"); one that fails again, or
11
12
  // does not finish in time, makes docker unavailable with the reason, until a restart tries again. Docker's own output
12
13
  // is never in a reason, as for the probes: the reason says what kind of failure it was, and what to do. The build
13
- // reaches the network (the base image, apt); a box never does (`--network none`, run-box.ts).
14
+ // reaches the network (the base image, apt); a box never does by Docker's network (`--network none`, run-box.ts), only,
15
+ // with the server's host list, through its egress proxy (box-egress.ts).
14
16
  //
15
17
  // The state is written to IMAGE_STATE_FILE in the data directory at each change, for the run's processes: a run's first
16
18
  // box create reads it there (awaitImage, from run-box.ts) and, while the image is coming, waits for it, with one row on
@@ -29,7 +31,7 @@ import { BOX_KEYS } from "./boxes.js";
29
31
  /** The setting that names another image for Docker boxes than this server's own. */
30
32
  export const DOCKER_IMAGE_ENV = "AGENTRUN_DOCKER_IMAGE";
31
33
  /** What the default image has, in words. */
32
- export const RECIPE_HAS = "python, git, curl, node, rg";
34
+ export const RECIPE_HAS = "python, git, curl, node, npm, rg";
33
35
  /** The base the default image builds from: `python:3.12-slim`, pinned to the multi-arch index digest Docker Hub served
34
36
  * 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
35
37
  * again (an anonymous pull token from auth.docker.io for `repository:library/python:pull`, then a HEAD of
@@ -42,7 +44,7 @@ export const BOX_BASE = "python:3.12-slim@sha256:b18b261e1b4974b4f321451ad5251de
42
44
  export const BOX_RECIPE = [
43
45
  `FROM ${BOX_BASE}`,
44
46
  "RUN apt-get update \\",
45
- " && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends git curl ca-certificates nodejs ripgrep \\",
47
+ " && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends git curl ca-certificates nodejs npm ripgrep socat \\",
46
48
  " && rm -rf /var/lib/apt/lists/*",
47
49
  "",
48
50
  ].join("\n");
@@ -96,11 +98,11 @@ function buildFailure(answer, timeoutMs) {
96
98
  return { cause: "the build of the box image ran out of disk space", next: "free some, then restart the server" };
97
99
  // A base that could not be fetched for want of a network says so in both ways: the network is the cause.
98
100
  if (UNREACHABLE.test(answer.stderr))
99
- return { cause: "the build of the box image could not reach the network (it pulls python:3.12-slim and installs git, curl, nodejs and ripgrep with apt)", next };
101
+ return { cause: "the build of the box image could not reach the network (it pulls python:3.12-slim and installs git, curl, nodejs, npm, ripgrep and socat with apt)", next };
100
102
  if (/pull access denied|manifest unknown|not found: manifest|failed to resolve source metadata|failed to fetch anonymous token/i.test(answer.stderr))
101
103
  return { cause: "the build of the box image could not pull its base, python:3.12-slim", next };
102
104
  if (/Unable to locate package|has no installation candidate|E: Package/i.test(answer.stderr))
103
- return { cause: "apt could not install what the box image needs (git, curl, nodejs, ripgrep)", next };
105
+ return { cause: "apt could not install what the box image needs (git, curl, nodejs, npm, ripgrep, socat)", next };
104
106
  return { cause: `docker build of the box image failed (${exitOf(answer)})`, next };
105
107
  }
106
108
  /** Why a pull failed, and the next step. */
@@ -185,7 +187,7 @@ export async function dockerImage(env, data, image, options = {}) {
185
187
  const row = built ? `Preparing the box image: building it (${RECIPE_HAS})…` : `Preparing the box image: pulling ${image}…`;
186
188
  await write({ until: started + timeoutMs, row });
187
189
  const retryAfterMs = options.retryAfterMs ?? RETRY_AFTER_MS;
188
- // The build's network is Docker's default, for the base image and apt; a box made from it has none (run-box.ts).
190
+ // The build's network is Docker's default, for the base image and apt; a box made from it has none of Docker's (run-box.ts).
189
191
  const attempt = () => built
190
192
  ? buildContext(env, image, timeoutMs, controller.signal).catch((error) => ({ code: error.code ?? error.name, stdout: "", stderr: "" }))
191
193
  : docker(env, ["pull", "--quiet", image], timeoutMs, { signal: controller.signal });
@@ -0,0 +1,80 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ /** One program started in a VM sandbox, in binary mode: the part of the SDK's process the relay carries. */
3
+ export type VmProcess = {
4
+ readonly stdin: {
5
+ writeBytes(bytes: Uint8Array): Promise<void>;
6
+ close(): Promise<void>;
7
+ };
8
+ readonly stdout: AsyncIterable<Uint8Array>;
9
+ readonly stderr: AsyncIterable<Uint8Array>;
10
+ wait(): Promise<number>;
11
+ };
12
+ /** The part of the SDK's sandbox the relay calls. */
13
+ export type VmSandbox = {
14
+ readonly sandboxId: string;
15
+ exec(command: string[], params: {
16
+ mode: "binary";
17
+ timeoutMs?: number;
18
+ workdir?: string;
19
+ }): Promise<VmProcess>;
20
+ poll(): Promise<number | null>;
21
+ getTags(): Promise<Record<string, string>>;
22
+ };
23
+ /** The part of the SDK's client the relay calls: a sandbox by its id. */
24
+ export type VmSdk = {
25
+ readonly sandboxes: {
26
+ fromId(id: string): Promise<VmSandbox>;
27
+ };
28
+ };
29
+ /** The relay's handler of a run's VM calls, over the server's client `sdk`: `handle(runId, path, req, res)` answers the
30
+ * call at `path` (what follows `/runs/<id>/vm/`), the caller's token already checked. `drop(runId)` lets go of the run's
31
+ * programs (at its end). */
32
+ export declare function vmRelay(sdk: VmSdk, secrets?: () => readonly string[]): {
33
+ handle(runId: string, path: string, req: IncomingMessage, res: ServerResponse): Promise<void>;
34
+ drop(runId: string): void;
35
+ };
36
+ /** 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
+ * its output streams take as long as the program runs, which its caller bounds (bash's timeout, and pi-transport's
38
+ * backstop over it); Node's own fetch would give up after 300 s with no answer or no bytes, failing a longer command
39
+ * as lost. */
40
+ export declare const RELAY_AGENT_OPTIONS: Readonly<{
41
+ headersTimeout: 0;
42
+ bodyTimeout: 0;
43
+ }>;
44
+ /** The SDK client a run's process hands pi-transport's VM provider: each call it makes of a box goes to the relay in data
45
+ * root `root`, with the run's own door token. It finds a sandbox and runs programs in it; it makes, lists and ends none. */
46
+ export declare function relayedVmSdk(root: string, runDir: string, runId: string, agentOptions?: {
47
+ headersTimeout: number;
48
+ bodyTimeout: number;
49
+ }): {
50
+ apps: {
51
+ fromName: () => never;
52
+ };
53
+ images: {
54
+ fromRegistry: () => never;
55
+ fromId: () => never;
56
+ };
57
+ sandboxes: {
58
+ create: () => never;
59
+ list: () => never;
60
+ fromId: (id: string) => Promise<{
61
+ sandboxId: string;
62
+ poll: () => Promise<number | null>;
63
+ getTags: () => Promise<Record<string, string>>;
64
+ terminate: () => Promise<number>;
65
+ exec: (command: string[], params: {
66
+ mode: "binary";
67
+ timeoutMs?: number;
68
+ workdir?: string;
69
+ }) => Promise<{
70
+ stdin: {
71
+ writeBytes: (bytes: Uint8Array) => Promise<void>;
72
+ close: () => Promise<undefined>;
73
+ };
74
+ stdout: AsyncIterable<Uint8Array<ArrayBufferLike>>;
75
+ stderr: AsyncIterable<Uint8Array<ArrayBufferLike>>;
76
+ wait: () => Promise<number>;
77
+ }>;
78
+ }>;
79
+ };
80
+ };