@parcha/agentrun-serve 0.1.0-beta.29 → 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 (172) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/README.md +739 -116
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +18 -7
  6. package/dist/agents.js +19 -10
  7. package/dist/app.js +101 -26
  8. package/dist/background.d.ts +29 -0
  9. package/dist/background.js +397 -0
  10. package/dist/box-egress-vm.d.ts +125 -0
  11. package/dist/box-egress-vm.js +350 -0
  12. package/dist/box-egress.d.ts +99 -0
  13. package/dist/box-egress.js +259 -0
  14. package/dist/box-image.d.ts +1 -1
  15. package/dist/box-image.js +9 -7
  16. package/dist/box-relay-vm.d.ts +84 -0
  17. package/dist/box-relay-vm.js +410 -0
  18. package/dist/box-relay.d.ts +8 -5
  19. package/dist/box-relay.js +14 -9
  20. package/dist/boxes.d.ts +28 -5
  21. package/dist/boxes.js +44 -18
  22. package/dist/browser-cost.d.ts +41 -0
  23. package/dist/browser-cost.js +158 -0
  24. package/dist/cap.d.ts +130 -21
  25. package/dist/cap.js +339 -67
  26. package/dist/cli.js +30 -4
  27. package/dist/coding-tools.d.ts +7 -3
  28. package/dist/coding-tools.js +16 -10
  29. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  30. package/dist/console/assets/index-CnJBf7Lc.js +486 -0
  31. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/content-filter.d.ts +7 -0
  34. package/dist/content-filter.js +23 -0
  35. package/dist/decision-rows.d.ts +11 -3
  36. package/dist/decision-rows.js +18 -11
  37. package/dist/decisions.d.ts +3 -3
  38. package/dist/decisions.js +4 -3
  39. package/dist/errors.d.ts +2 -0
  40. package/dist/errors.js +5 -2
  41. package/dist/files.d.ts +9 -1
  42. package/dist/files.js +10 -2
  43. package/dist/grade.d.ts +11 -11
  44. package/dist/grade.js +43 -55
  45. package/dist/graph-served.d.ts +23 -0
  46. package/dist/graph-served.js +75 -0
  47. package/dist/graph-view.d.ts +7 -5
  48. package/dist/graph-view.js +10 -3
  49. package/dist/harness-app.d.ts +4 -2
  50. package/dist/harness-app.js +110 -19
  51. package/dist/harness-opencode/adapter.d.ts +45 -0
  52. package/dist/harness-opencode/adapter.js +272 -0
  53. package/dist/harness-opencode/binary.d.ts +18 -0
  54. package/dist/harness-opencode/binary.js +87 -0
  55. package/dist/harness-opencode/config.d.ts +24 -0
  56. package/dist/harness-opencode/config.js +61 -0
  57. package/dist/harness-opencode/harness.d.ts +77 -0
  58. package/dist/harness-opencode/harness.js +620 -0
  59. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  60. package/dist/harness-opencode/host/mcp.js +208 -0
  61. package/dist/harness-opencode/host/policy.d.ts +71 -0
  62. package/dist/harness-opencode/host/policy.js +419 -0
  63. package/dist/harness-opencode/host/server.d.ts +55 -0
  64. package/dist/harness-opencode/host/server.js +165 -0
  65. package/dist/harness-opencode/index.d.ts +9 -0
  66. package/dist/harness-opencode/index.js +6 -0
  67. package/dist/harness-opencode/verify.d.ts +32 -0
  68. package/dist/harness-opencode/verify.js +75 -0
  69. package/dist/harness-opencode/versions.d.ts +33 -0
  70. package/dist/harness-opencode/versions.js +64 -0
  71. package/dist/harness.d.ts +4 -1
  72. package/dist/harness.js +5 -2
  73. package/dist/host-check.d.ts +12 -0
  74. package/dist/host-check.js +34 -0
  75. package/dist/host-tools.d.ts +12 -2
  76. package/dist/host-tools.js +26 -12
  77. package/dist/host.js +6 -2
  78. package/dist/hosted-search.js +5 -1
  79. package/dist/import.d.ts +2 -2
  80. package/dist/import.js +4 -3
  81. package/dist/key-check.d.ts +3 -2
  82. package/dist/key-check.js +7 -3
  83. package/dist/key-refusal.js +8 -4
  84. package/dist/key-words.d.ts +37 -0
  85. package/dist/key-words.js +40 -0
  86. package/dist/learn/check.d.ts +10 -1
  87. package/dist/learn/check.js +19 -1
  88. package/dist/learn/grade.d.ts +6 -2
  89. package/dist/learn/grade.js +28 -14
  90. package/dist/learn/index.d.ts +3 -3
  91. package/dist/learn/index.js +3 -3
  92. package/dist/learn/notes.js +2 -1
  93. package/dist/learn/reflect.d.ts +2 -2
  94. package/dist/learn/reflect.js +53 -5
  95. package/dist/learn/secrets.js +28 -8
  96. package/dist/learn/skills.d.ts +19 -4
  97. package/dist/learn/skills.js +95 -6
  98. package/dist/learned-workflow.d.ts +59 -0
  99. package/dist/learned-workflow.js +191 -0
  100. package/dist/learning-routes.d.ts +30 -1
  101. package/dist/learning-routes.js +173 -19
  102. package/dist/learning-run.d.ts +8 -6
  103. package/dist/learning-run.js +70 -27
  104. package/dist/learning-words.d.ts +12 -5
  105. package/dist/learning-words.js +34 -13
  106. package/dist/learning.d.ts +52 -3
  107. package/dist/learning.js +204 -4
  108. package/dist/mcp-gateway.d.ts +96 -0
  109. package/dist/mcp-gateway.js +408 -0
  110. package/dist/mcp-meta.d.ts +17 -0
  111. package/dist/mcp-meta.js +38 -0
  112. package/dist/mcp-servers.d.ts +33 -9
  113. package/dist/mcp-servers.js +58 -10
  114. package/dist/mcp.js +5 -5
  115. package/dist/model.d.ts +13 -11
  116. package/dist/model.js +11 -10
  117. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  118. package/dist/openapi.js +407 -54
  119. package/dist/page.d.ts +2 -0
  120. package/dist/page.js +3 -0
  121. package/dist/paid-calls.d.ts +5 -1
  122. package/dist/paid-calls.js +1 -1
  123. package/dist/pause.d.ts +2 -0
  124. package/dist/place.d.ts +29 -5
  125. package/dist/place.js +51 -11
  126. package/dist/print.d.ts +7 -0
  127. package/dist/print.js +13 -0
  128. package/dist/propose.d.ts +2 -0
  129. package/dist/propose.js +38 -8
  130. package/dist/request-start.d.ts +12 -4
  131. package/dist/request-start.js +139 -15
  132. package/dist/run-box.d.ts +56 -4
  133. package/dist/run-box.js +183 -23
  134. package/dist/runnable.d.ts +13 -3
  135. package/dist/runnable.js +63 -6
  136. package/dist/runs.d.ts +266 -37
  137. package/dist/runs.js +884 -90
  138. package/dist/secrets.d.ts +27 -0
  139. package/dist/secrets.js +38 -2
  140. package/dist/server.d.ts +141 -36
  141. package/dist/server.js +562 -118
  142. package/dist/sign-ins.d.ts +99 -0
  143. package/dist/sign-ins.js +288 -0
  144. package/dist/skills.d.ts +16 -4
  145. package/dist/skills.js +35 -7
  146. package/dist/stats.d.ts +7 -2
  147. package/dist/stats.js +28 -7
  148. package/dist/tool-gate.d.ts +281 -0
  149. package/dist/tool-gate.js +585 -0
  150. package/dist/tool-keys.d.ts +48 -11
  151. package/dist/tool-keys.js +46 -8
  152. package/dist/tool-plane.d.ts +116 -27
  153. package/dist/tool-plane.js +232 -50
  154. package/dist/tools.d.ts +69 -14
  155. package/dist/tools.js +148 -26
  156. package/dist/trigger-secrets.d.ts +32 -0
  157. package/dist/trigger-secrets.js +143 -0
  158. package/dist/triggers.d.ts +439 -0
  159. package/dist/triggers.js +863 -0
  160. package/dist/turn-end.d.ts +3 -2
  161. package/dist/turn-end.js +3 -2
  162. package/dist/usage-lines.d.ts +26 -0
  163. package/dist/usage-lines.js +28 -0
  164. package/dist/validate.d.ts +2 -0
  165. package/dist/validate.js +11 -2
  166. package/dist/web-fetch.js +3 -3
  167. package/dist/webhooks.d.ts +11 -4
  168. package/dist/webhooks.js +17 -1
  169. package/launcher/agentrun-serve +1 -1
  170. package/package.json +16 -14
  171. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  172. package/dist/console/assets/index-By-jkqki.css +0 -1
@@ -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 });
@@ -0,0 +1,99 @@
1
+ /** Where the proxy's directory is in the box, read-only. */
2
+ export declare const EGRESS_MOUNT = "/run/agentrun/egress";
3
+ /** The proxy's socket, in its directory. */
4
+ export declare const EGRESS_SOCKET = "egress.sock";
5
+ /** The box's loopback port socat relays to the socket. */
6
+ export declare const EGRESS_PORT = 3128;
7
+ /** What a box with a list adds to its fixed environment (run-box.ts BOX_ENV): constants, no user, no password. */
8
+ export declare const PROXY_ENV: Readonly<Record<string, string>>;
9
+ /** The box's relay to the proxy's socket `socket` (in EGRESS_MOUNT), started once each time the run's box opens (made
10
+ * or found): a second one finds the port taken and exits. Each connection opens the socket by its path, so a proxy
11
+ * started again is reached with no new relay. */
12
+ export declare const forwarder: (socket?: string) => string[];
13
+ /** The relay's start, in the box, answered once it listens: exit 127 when the image has no socat, 126 when it has no
14
+ * setsid, and 124 when the relay is not listening within 3 s (its own error, if it gave one, on stderr). A relay a
15
+ * process before this one started still listens, so a second start finds the port taken and answers at once. */
16
+ export declare const forwarderStart: (socket?: string) => string[];
17
+ /** The timeline row of a box whose relay could not start, by the start's exit (forwarderStart): the box keeps no network. */
18
+ export declare function relayFailed(code: number, said: string): string;
19
+ /** The row for an image with no socat (relayFailed 127). */
20
+ export declare const NO_SOCAT: string;
21
+ /** What a refusal of a host off the list says to do, after its words. */
22
+ export declare const ALLOW_HINT = "use web_fetch for web pages, or ask the operator to add it to AGENTRUN_BOX_ALLOW";
23
+ /** Each run's proxy: connections open at once, and in all. */
24
+ export declare const MAX_TUNNELS = 64;
25
+ export declare const MAX_CONNECTIONS = 20000;
26
+ /** Under `--faux` only: a module whose default export gives the proxy's `lookup` and `dial` (the tests' fake network), so
27
+ * a test's box reaches no host but its fake. */
28
+ export declare const FAUX_EGRESS_ENV = "AGENTRUN_SERVE_FAUX_EGRESS";
29
+ /** The proxy's directory for run `runId`: short, so its socket's path stays within a Unix socket's limit (107 bytes)
30
+ * wherever the data root is, and the same each time the run's process starts, since the box keeps its bind. */
31
+ export declare function egressDir(runId: string, uid?: number): string;
32
+ /** Removes a run's proxy directory once its box is gone. */
33
+ export declare const removeEgressDir: (runId: string) => Promise<void>;
34
+ /** Where a run's box finds its proxy: what is mounted read-only at EGRESS_MOUNT, and the socket's name there. The one
35
+ * seam between the box's side, which is the same wherever the proxy runs (the mount, the relay, the proxy variables),
36
+ * and where the proxy runs. Today that is hostEgress: the run's own process, its socket's directory on this machine
37
+ * bound into the box. */
38
+ export type BoxEgress = (runId: string) => Promise<{
39
+ mount?: {
40
+ source: string;
41
+ target: typeof EGRESS_MOUNT;
42
+ readOnly: true;
43
+ };
44
+ socket: string;
45
+ fresh: boolean;
46
+ }>;
47
+ /** The proxy in the run's process (hostEgress): for a Docker daemon on this Linux machine, which can reach a socket in a
48
+ * directory of this machine bound into a container. */
49
+ export declare const hostEgress: (allow: readonly string[], env: NodeJS.ProcessEnv, log: (line: string) => void) => BoxEgress;
50
+ /** How long `docker info` may take to say where this Docker runs. */
51
+ export declare const INFO_TIMEOUT_MS = 5000;
52
+ /** What `docker info` is asked: the daemon's OS type, its kernel, where it keeps its data, and the name it gives its OS. */
53
+ export declare const INFO_FORMAT = "{{.OSType}}|{{.KernelVersion}}|{{.DockerRootDir}}|{{.OperatingSystem}}";
54
+ /** `docker info`'s answer to INFO_FORMAT, its stdout, or a throw that says why there is none. */
55
+ export type DockerInfo = (env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<string>;
56
+ /** `docker info` in the server's environment through the cut a run's takes, nothing on its stdin, within `timeoutMs`. */
57
+ export declare const dockerInfo: DockerInfo;
58
+ /**
59
+ * 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
60
+ * machine bound into the box, which only a Docker daemon on this same Linux machine can connect to: a daemon in a VM
61
+ * (Docker Desktop, OrbStack and their kin) sees the socket and is refused. So the network goes on only with positive
62
+ * evidence that the daemon is this machine's: this machine is Linux; the docker CLI's endpoint is a local unix socket
63
+ * (no DOCKER_HOST or a unix:// one, and the default context or a unix one: pi-transport's dockerDaemon); and `docker
64
+ * info` answers within its bound with OS type linux and this machine's own kernel (os.release()): the same kernel, so no
65
+ * VM in between; and the directory it keeps its data in (DockerRootDir) is one this server sees. A server in a container
66
+ * given the host's docker socket shares the host's kernel, but not its files: it would bind a directory the daemon does
67
+ * not have, so every box would fail to start. Anything else is no network, and the reason says what was seen, naming the
68
+ * runtime docker info gives. A kernel is the evidence, not a runtime's name: Docker Desktop on WSL2 runs the kernel this
69
+ * server does, but keeps its data outside the distro, so it passes only where the distro has that directory too.
70
+ */
71
+ export declare function egressBlockedBy(env: NodeJS.ProcessEnv, options?: {
72
+ info?: DockerInfo;
73
+ platform?: string;
74
+ kernel?: string;
75
+ timeoutMs?: number;
76
+ sees?: (dir: string) => boolean;
77
+ }): Promise<string | undefined>;
78
+ /** How old a run's proxy directory with no live socket must be before the start's sweep takes it: one just made, whose
79
+ * proxy is still starting, is not yet listening. */
80
+ export declare const STALE_EGRESS_MS = 60000;
81
+ /**
82
+ * The start's sweep of this user's proxy directories (egressDir's parent): each whose socket refuses a connect (or has
83
+ * 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
84
+ * whose socket answers is a live run's, this server's or another's under this uid, and stays. Returns how many went.
85
+ */
86
+ export declare function sweepEgressDirs(uid?: number, now?: number): Promise<number>;
87
+ /** What a server's Docker boxes reach, resolved once at its start (run-box.ts boxNetworkOf): the list, or none and why. */
88
+ export type DockerNetwork = {
89
+ allow: readonly string[]; /** On a Mac, the VM runtime whose proxy container serves the list (box-egress-vm.ts). */
90
+ vm?: string;
91
+ } | {
92
+ allow: "none";
93
+ reason: string;
94
+ };
95
+ /** What the server hands a run's process: the list its box reaches, resolved (boxNetworkOf), or `none`. The run's
96
+ * process reads this, never AGENTRUN_BOX_ALLOW: unset, it is none. */
97
+ export declare const RUN_BOX_ALLOW_ENV = "AGENTRUN_RUN_BOX_ALLOW";
98
+ /** 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. */
99
+ export declare function runBoxAllowOf(env: NodeJS.ProcessEnv): readonly string[] | "none";