podster 0.0.1-test.6 → 0.0.1-test.9

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.
@@ -86,6 +86,11 @@ export const RELAY_SOCKET_IN_CONTAINER = "/relay/runner.sock";
86
86
  /** The listener socket's name in the run's folder. Short, so the whole path fits a socket's limit. */
87
87
  export const SOCKET_NAME = "r.sock";
88
88
  export { LABEL_ROLE };
89
+ /**
90
+ * The driver's own network, by role: never the run's egress network, which the task sandbox opens and removes with the
91
+ * task's container, so the two never remove one network at once.
92
+ */
93
+ const OWN_NETWORK = `label=${LABEL_ROLE}=network`;
89
94
  /** How long Claude Code's containers may outlive a run's time cap, as the task container may. */
90
95
  const CONTAINER_MARGIN_S = 60;
91
96
  /** The names of a run's Claude Code container, relay and network. */
@@ -291,7 +296,7 @@ const TOOL_SHAPES = {
291
296
  search: { description: "Search the task's folder, or a folder in it given by a relative path, for a regular expression.", shape: { pattern: z.string(), path: z.string().optional() } },
292
297
  write: { description: "Write a whole file in the task's folder. Its path is relative to the folder, such as notes.txt.", shape: { path: z.string(), content: z.string() } },
293
298
  edit: { description: "Replace one exact piece of text, which must appear once, in a file in the task's folder. Its path is relative to the folder.", shape: { path: z.string(), old: z.string(), new: z.string() } },
294
- shell: { description: "Run a shell command in the task's container, in its folder, with no network.", shape: { command: z.string() } },
299
+ shell: { description: "Run a shell command in the task's container, in its folder. It reaches no network but the hosts the run's instructions name, if any.", shape: { command: z.string() } },
295
300
  };
296
301
  /** The same input, written the same way, whatever its key order. */
297
302
  function canonical(v) {
@@ -418,7 +423,7 @@ export class ClaudeDriver {
418
423
  throw new Error("run_ref_invalid");
419
424
  const run = [`label=${LABEL_RUN}=${ref}`];
420
425
  await removeContainers(this.deps.docker, await this.own(run), () => this.own(run), this.wait);
421
- await this.removeNetworks(run);
426
+ await this.removeNetworks([...run, OWN_NETWORK]);
422
427
  }
423
428
  /** Each network matching `filters`: attached containers disconnected, removed, then confirmed gone. */
424
429
  async removeNetworks(filters) {
@@ -535,7 +540,7 @@ export class ClaudeDriver {
535
540
  checked.add(call_id);
536
541
  const key = keyOf(name, input.tool_input);
537
542
  pending.set(key, [...(pending.get(key) ?? []), call_id]);
538
- return decision.allow ? {} : deny(refusalText(decision.reason));
543
+ return decision.allow ? {} : deny(refusalText(decision.reason, decision.rule));
539
544
  };
540
545
  const handler = (name) => async (args, extra) => {
541
546
  const meta = extra?._meta?.["claudecode/toolUseId"];
@@ -693,7 +698,7 @@ export class ClaudeDriver {
693
698
  try {
694
699
  if ((await this.own([`label=${LABEL_RUN}=${run_ref}`])).length > 0)
695
700
  return false;
696
- if ((await this.list("network", [`label=${LABEL_RUN}=${run_ref}`])).length > 0)
701
+ if ((await this.list("network", [`label=${LABEL_RUN}=${run_ref}`, OWN_NETWORK])).length > 0)
697
702
  return false;
698
703
  }
699
704
  catch {
@@ -713,7 +718,7 @@ export class ClaudeDriver {
713
718
  async reapAll() {
714
719
  const home = [`label=${LABEL_HOME}=${this.homeLabel}`];
715
720
  await removeContainers(this.deps.docker, await this.own(home), () => this.own(home), this.wait);
716
- await this.removeNetworks(home);
721
+ await this.removeNetworks([...home, OWN_NETWORK]);
717
722
  }
718
723
  }
719
724
  /** The real exec client: from an argument array, never a shell, its errors drained. */
@@ -5,8 +5,9 @@
5
5
  * Before anything runs, it refuses unless:
6
6
  * - the installed SDK and its bundled Claude Code are exactly the pinned pair (S-48);
7
7
  * - the key file is a regular file, not a link, owned by the owner and readable by no one else, holding one key;
8
- * - Runner's two images are pinned: `task-image` and `claude-image` in Runner's home each name an image ID
9
- * (`sha256:…`), built from `apps/runner/sandbox` and `apps/runner/claude-image`. A pin that's missing, or names an
8
+ * - Runner's three images are pinned: `task-image`, `claude-image` and `proxy-image` in Runner's home each name an image
9
+ * ID (`sha256:…`), built from `apps/runner/sandbox`, `apps/runner/claude-image` and `apps/runner/proxy-image` (the
10
+ * egress proxy's, for rooms that list hosts). A pin that's missing, or names an
10
11
  * image Docker no longer has, is built from the Dockerfile in Runner's own package and pinned (`ensureImage`, the
11
12
  * ruling on #470); a build that fails stops `run` before anything runs;
12
13
  * - `docker` is installed in a fixed place;
@@ -32,6 +33,7 @@ import { CLAUDE_PROFILE } from "../core/claude-profile.js";
32
33
  import { ClaudeDriver } from "./claude-driver.js";
33
34
  import { DockerSandbox, dockerCli, dockerHost, findDocker, IMAGE_ID } from "./docker-sandbox.js";
34
35
  import { dockerReachable, homeLengthRefusal, homeRefusal, isWsl, linuxCheckFailure, readMounts, readProcVersion, relayModeFor, resolvedPath } from "./platform.js";
36
+ import { loadProxyProgram } from "./egress-network.js";
35
37
  import { ProviderKeyTransport } from "./provider-transport.js";
36
38
  import { ensureFolder, readNoFollow, writeNew } from "./safe-fs.js";
37
39
  /** The installed SDK's version and its bundled Claude Code's, from its own manifest. */
@@ -84,25 +86,37 @@ export async function claudeImage(home) {
84
86
  throw new Error("Runner's Claude Code image isn't pinned. Build apps/runner/claude-image and write its image ID (sha256:…) to claude-image in Runner's home.");
85
87
  return text;
86
88
  }
89
+ /** Runner's pinned egress proxy image, from `proxy-image` in its home. */
90
+ export async function proxyImage(home) {
91
+ const text = (await readNoFollow(join(home, "proxy-image"), 256))?.trim();
92
+ if (!text || !IMAGE_ID.test(text))
93
+ throw new Error("Runner's egress proxy image isn't pinned. Build apps/runner/proxy-image and write its image ID (sha256:…) to proxy-image in Runner's home.");
94
+ return text;
95
+ }
96
+ const PINNED = { "task-image": taskImage, "claude-image": claudeImage, "proxy-image": proxyImage };
87
97
  /** Each image's build folder, in Runner's own package: its Dockerfile, which copies nothing from the folder. */
88
98
  export const IMAGE_SOURCES = {
89
99
  "task-image": fileURLToPath(new URL("../../sandbox", import.meta.url)),
90
100
  "claude-image": fileURLToPath(new URL("../../claude-image", import.meta.url)),
101
+ "proxy-image": fileURLToPath(new URL("../../proxy-image", import.meta.url)),
91
102
  };
92
103
  /** The fixed line said before a build. */
93
104
  export const BUILDING = {
94
105
  "task-image": "Building Runner's task image from its packaged Dockerfile. This happens once and takes a few minutes.",
95
106
  "claude-image": "Building Runner's Claude Code image from its packaged Dockerfile. This happens once and takes a few minutes.",
107
+ "proxy-image": "Building Runner's egress proxy image from its packaged Dockerfile. This happens once and takes a few minutes.",
96
108
  };
97
109
  /** The fixed message a failed build stops `run` with. Docker's own output never reaches it. */
98
110
  export const BUILD_FAILED = {
99
111
  "task-image": "Runner couldn't build its task image, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
100
112
  "claude-image": "Runner couldn't build its Claude Code image, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
113
+ "proxy-image": "Runner couldn't build its egress proxy image, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
101
114
  };
102
115
  /** The fixed message when Docker can't say whether a pinned image exists. Nothing is built or re-pinned. */
103
116
  export const INSPECT_FAILED = {
104
117
  "task-image": "Runner couldn't check its task image with Docker, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
105
118
  "claude-image": "Runner couldn't check its Claude Code image with Docker, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
119
+ "proxy-image": "Runner couldn't check its egress proxy image with Docker, so nothing ran. Check that Docker Desktop is running, then start `run` again.",
106
120
  };
107
121
  /** Docker's own answer for an image it doesn't have, from `docker image inspect`. */
108
122
  const NO_SUCH_IMAGE = /^(Error: |Error response from daemon: )?No such image: /m;
@@ -145,7 +159,7 @@ export async function ensureImage(name, opts) {
145
159
  const path = join(opts.home, name);
146
160
  const pinned = (await readNoFollow(path, 256))?.trim();
147
161
  if (pinned) {
148
- const pinnedId = name === "task-image" ? await taskImage(opts.home) : await claudeImage(opts.home);
162
+ const pinnedId = await PINNED[name](opts.home);
149
163
  const present = await opts.docker(["image", "inspect", "--format", "{{.Id}}", pinnedId], { timeoutMs: 60_000, maxOutputBytes: 4096 });
150
164
  if (present.code === 0)
151
165
  return pinnedId;
@@ -192,6 +206,8 @@ export async function claudeEngine(opts) {
192
206
  const notify = opts.notify ?? (() => undefined);
193
207
  const image = await ensureImage("task-image", { home: opts.home, docker, notify });
194
208
  const ccImage = await ensureImage("claude-image", { home: opts.home, docker, notify });
209
+ // The egress proxy's, for rooms whose run policy lists hosts; its program is Runner's own built file, read when needed.
210
+ const pxImage = await ensureImage("proxy-image", { home: opts.home, docker, notify });
195
211
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
196
212
  const gid = typeof process.getgid === "function" ? process.getgid() : 0;
197
213
  // Never bare: under bare mode the SDK's PreToolUse callback, Runner's decision point, never fires (the fifth real run
@@ -208,7 +224,7 @@ export async function claudeEngine(opts) {
208
224
  }
209
225
  opts.log("adapter.platform", "linux_checked", {});
210
226
  }
211
- const sandbox = new DockerSandbox({ docker, image, uid, gid, home: opts.home, wait: opts.wait, ...(relay === "unix" ? { mounts: () => (opts.mounts !== undefined ? opts.mounts : readMounts()) } : {}) });
227
+ const sandbox = new DockerSandbox({ docker, image, uid, gid, home: opts.home, wait: opts.wait, log: opts.log, proxy: { image: pxImage, program: () => loadProxyProgram() }, ...(relay === "unix" ? { mounts: () => (opts.mounts !== undefined ? opts.mounts : readMounts()) } : {}) });
212
228
  return {
213
229
  drivers: { claude_agent_sdk: driver },
214
230
  sandbox,
package/build/node/cli.js CHANGED
@@ -26,6 +26,8 @@
26
26
  * container, the key's transport), reaps what a previous process left, then opens the lifecycle (`run-command.ts`).
27
27
  * Without a key file it opens no lifecycle and accepts nothing it couldn't run.
28
28
  */
29
+ import { whyCommand } from "./diagnostics.js";
30
+ import { runLogger } from "./explaining-log.js";
29
31
  import { homedir } from "node:os";
30
32
  import { join, resolve } from "node:path";
31
33
  import { createInterface } from "node:readline/promises";
@@ -63,6 +65,8 @@ const USAGE = `Podster Runner (M7: pairing, the inbox loop, and tasks through th
63
65
  stop Stop the Runner running from this home at once, and any run.
64
66
  It polls nothing until you start it again.
65
67
  status Show this Runner's record, by IDs.
68
+ why <tsk_…> Show the newest failure recorded for a task on this machine:
69
+ what happened, what to do, and the local details.
66
70
  forget Delete this Runner's keys and record. The agent stays
67
71
  connected in Podster until you disconnect it there.
68
72
 
@@ -105,6 +109,10 @@ async function main(argv) {
105
109
  say(JSON.stringify({ gateway: record.gateway, agent: record.agent_id, phase: record.phase, stopped: record.stopped, inbox_cursor: record.inbox_cursor, offers: Object.keys(record.offers).length, last_contact_at: record.last_contact_at, reconciled_at: record.reconciled_at, runs: phases }));
106
110
  return 0;
107
111
  }
112
+ if (command === "why") {
113
+ // The newest failure recorded for a task on this machine, from the local diagnostics file. Nothing is sent anywhere.
114
+ return whyCommand(home, args[args.indexOf("why") + 1], say);
115
+ }
108
116
  if (command === "stop") {
109
117
  // A local stop: no call to Podster, no signal to a process ID. The running Runner sees the request at once.
110
118
  say((await requestStop(home)) ? "Asked the Runner running here to stop. Any run ends at once, and it polls nothing until started again." : "No Runner is running from this home.");
@@ -193,6 +201,8 @@ async function locked(command, args, home, state, nonce) {
193
201
  }
194
202
  }
195
203
  if (command === "run") {
204
+ // Each failure's raw cause goes to the local diagnostics file only; the terminal explains its code in fixed words.
205
+ const { log, diagnostics } = runLogger(home, (line) => process.stderr.write(`${line}\n`));
196
206
  const record = await state.load();
197
207
  if (!record.gateway)
198
208
  throw new Error("This Runner isn't paired yet. Run `pair` first.");
@@ -231,7 +241,7 @@ async function locked(command, args, home, state, nonce) {
231
241
  // Polling starts first; the nudge's setup, if the owner asked for it, runs beside it (the ruling on #473).
232
242
  outcome = await alongsidePolling(async (bell) => {
233
243
  try {
234
- return await runInbox({ home, poller, clock: systemClock, log, signal: stop.signal, terminal: processTerminal(), engine, ...(bell ? { bell } : {}) });
244
+ return await runInbox({ home, poller, clock: systemClock, log, diagnostics, signal: stop.signal, terminal: processTerminal(), engine, ...(bell ? { bell } : {}) });
235
245
  }
236
246
  finally {
237
247
  // Shutdown closes the nudge endpoint at once (R-15), even while its setup is still waiting on Podster.
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Runner's local diagnostics file (the owner's request of 2026-11-20): `logs/errors.jsonl` in Runner's home, one JSON
3
+ * line per failure, keyed by time and the run's IDs, with the raw error's message and stack and, for a Docker command,
4
+ * its exit code and the tail of its error output. It is for the machine's owner only:
5
+ *
6
+ * - **Local only.** Nothing reads it but `podster why`; it is never sent to Podster or any network.
7
+ * - **Scrubbed and bounded.** Every text has the exact secret values Runner holds (`known-secrets.ts`: the run's broker
8
+ * token, a task's GitHub token) redacted, then Runner's secret patterns (`redactSecrets`), and each field is cut to
9
+ * `MAX_FIELD_BYTES`, 4 KiB (the error output keeps its tail). Error output Docker cut at its own cap has its last word,
10
+ * which may be the start of a secret, redacted too.
11
+ * - **Private.** The folder is mode 0700, owned by this user and not a link; the file is 0600 (set before the first
12
+ * write to one that exists), owned by this user, with one link, opened without following a link. Reads check the same.
13
+ * - **Rotated.** Past `MAX_FILE_BYTES` the file moves to `errors.jsonl.1` (and that to `.2`), so at most three are kept.
14
+ *
15
+ * A write that fails is dropped: diagnostics never stop Runner.
16
+ */
17
+ import { chmodSync, closeSync, constants, existsSync, fchmodSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { DetailedError } from "../core/errors.js";
20
+ import { RepoPathError } from "../core/repository.js";
21
+ import { explain } from "../core/explain.js";
22
+ import { redactKnown } from "../core/known-secrets.js";
23
+ import { markHidden, redactSecrets } from "../core/results.js";
24
+ import { ownFileSync, ownFolderSync } from "./safe-fs.js";
25
+ export const MAX_FILE_BYTES = 1024 * 1024;
26
+ export const KEPT_FILES = 3;
27
+ export const MAX_FIELD_BYTES = 4096;
28
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
29
+ const CODE = /^[a-z][a-z0-9_.]{0,63}$/;
30
+ /** Text redacted, then cut to `max` UTF-8 bytes: its head, or its tail for an error output. */
31
+ export function scrub(text, max = MAX_FIELD_BYTES, keep = "head") {
32
+ const clean = redactSecrets(redactKnown(text).text).text;
33
+ const bytes = Buffer.from(clean, "utf8");
34
+ if (bytes.byteLength <= max)
35
+ return clean;
36
+ const cut = keep === "head" ? bytes.subarray(0, max) : bytes.subarray(bytes.byteLength - max);
37
+ // A cut inside a character drops it rather than writing half of one.
38
+ return (keep === "head" ? "" : "[cut]") + cut.toString("utf8").replace(/�/g, "") + (keep === "head" ? "[cut]" : "");
39
+ }
40
+ /**
41
+ * Output cut at a head cap: its last word, if the cut went through one, is replaced, since it may be the start of a
42
+ * secret too short for any pattern to match (`ghs_`, `sk-ant-`, part of a hex token).
43
+ */
44
+ export function cutEdge(text) {
45
+ return text.replace(/[^\s"'`<>()[\]{},;]+$/u, "[cut: partial word redacted]");
46
+ }
47
+ /** The line written for a failure. */
48
+ export function diagnosticLine(failure, now) {
49
+ const line = { time: new Date(now).toISOString(), at: CODE.test(failure.at) ? failure.at : "runner", code: /^[a-z][a-z0-9_]{0,63}$/.test(failure.code) ? failure.code : "unknown" };
50
+ if (failure.workspace && ID.test(failure.workspace))
51
+ line.workspace = failure.workspace;
52
+ if (failure.task && ID.test(failure.task))
53
+ line.task = failure.task;
54
+ if (failure.run_ref && ID.test(failure.run_ref))
55
+ line.run_ref = failure.run_ref;
56
+ const error = failure.error;
57
+ if (error instanceof Error) {
58
+ line.message = scrub(error.message);
59
+ if (typeof error.stack === "string")
60
+ line.stack = scrub(error.stack);
61
+ if (error instanceof DetailedError) {
62
+ if (typeof error.detail.exit_code === "number" && Number.isSafeInteger(error.detail.exit_code))
63
+ line.exit_code = error.detail.exit_code;
64
+ if (typeof error.detail.stderr === "string")
65
+ line.stderr_tail = scrub(error.detail.cut ? cutEdge(error.detail.stderr) : error.detail.stderr, MAX_FIELD_BYTES, "tail");
66
+ if (typeof error.detail.errno === "string")
67
+ line.errno = scrub(error.detail.errno, 64);
68
+ }
69
+ if (error instanceof RepoPathError)
70
+ line.transient = error.transient ? 1 : 0;
71
+ }
72
+ else if (error !== undefined) {
73
+ line.message = scrub(String(error));
74
+ }
75
+ return JSON.stringify(line);
76
+ }
77
+ export class FileDiagnostics {
78
+ folder;
79
+ file;
80
+ now;
81
+ constructor(home, now = () => Date.now()) {
82
+ this.folder = join(home, "logs");
83
+ this.file = join(this.folder, "errors.jsonl");
84
+ this.now = now;
85
+ }
86
+ record(failure) {
87
+ try {
88
+ this.write(`${diagnosticLine(failure, this.now())}\n`);
89
+ }
90
+ catch {
91
+ // Diagnostics never stop Runner.
92
+ }
93
+ }
94
+ write(line) {
95
+ if (!existsSync(this.folder))
96
+ mkdirSync(this.folder, { mode: 0o700 });
97
+ // Checked first, so nothing is ever changed through a link: a real folder, the owner's, writable by no one else.
98
+ ownFolderSync(this.folder);
99
+ chmodSync(this.folder, 0o700);
100
+ let size;
101
+ const fd = openSync(this.file, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
102
+ try {
103
+ size = ownFileSync(fd).size;
104
+ }
105
+ finally {
106
+ closeSync(fd);
107
+ }
108
+ if (size > 0 && size + Buffer.byteLength(line) > MAX_FILE_BYTES)
109
+ this.rotate();
110
+ const out = openSync(this.file, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
111
+ try {
112
+ ownFileSync(out);
113
+ // Private before anything is written, whatever mode a file that was there had.
114
+ fchmodSync(out, 0o600);
115
+ writeSync(out, line);
116
+ }
117
+ finally {
118
+ closeSync(out);
119
+ }
120
+ }
121
+ rotate() {
122
+ const oldest = `${this.file}.${KEPT_FILES - 1}`;
123
+ if (existsSync(oldest))
124
+ rmSync(oldest);
125
+ for (let n = KEPT_FILES - 2; n >= 1; n--)
126
+ if (existsSync(`${this.file}.${n}`))
127
+ renameSync(`${this.file}.${n}`, `${this.file}.${n + 1}`);
128
+ renameSync(this.file, `${this.file}.1`);
129
+ }
130
+ /** The newest failure recorded for a task, as written, or null. Reads this machine's files only. */
131
+ lastFor(task) {
132
+ if (!ID.test(task))
133
+ return null;
134
+ try {
135
+ ownFolderSync(this.folder);
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ for (const path of [this.file, ...Array.from({ length: KEPT_FILES - 1 }, (_, i) => `${this.file}.${i + 1}`)]) {
141
+ let text;
142
+ try {
143
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
144
+ try {
145
+ ownFileSync(fd);
146
+ text = readFileSync(fd, "utf8");
147
+ }
148
+ finally {
149
+ closeSync(fd);
150
+ }
151
+ }
152
+ catch {
153
+ continue;
154
+ }
155
+ const lines = text.split("\n").filter((l) => l !== "");
156
+ for (let i = lines.length - 1; i >= 0; i--) {
157
+ try {
158
+ const entry = JSON.parse(lines[i]);
159
+ if (entry.task === task)
160
+ return entry;
161
+ }
162
+ catch {
163
+ // A torn line is skipped.
164
+ }
165
+ }
166
+ }
167
+ return null;
168
+ }
169
+ }
170
+ const TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
171
+ const AT = /^[a-z][a-z0-9_.]{0,63}$/;
172
+ const FAILURE_CODE = /^[a-z][a-z0-9_]{0,63}$/;
173
+ /** A field read back from the file, shown only when it has its fixed shape. */
174
+ const shaped = (v, re) => (typeof v === "string" && re.test(v) ? v : "invalid");
175
+ /**
176
+ * `podster why`'s lines for a task's newest failure: its time, place and code, each shown only in its fixed shape, the
177
+ * table's explanation, and the entry itself with every control, format and bidi character written as a visible mark, so
178
+ * nothing in the file can rewrite the terminal.
179
+ */
180
+ export function whyLines(task, entry, file) {
181
+ if (!entry)
182
+ return [`No failure is recorded for ${task} in ${file}.`];
183
+ const code = shaped(entry.code, FAILURE_CODE);
184
+ const e = explain(code);
185
+ return [
186
+ `${shaped(entry.time, TIME)} at ${shaped(entry.at, AT)}: ${e.what} ${e.todo} (code ${code})`,
187
+ `From ${file}, local to this machine and redacted:`,
188
+ markHidden(JSON.stringify(entry, null, 2)),
189
+ ];
190
+ }
191
+ /** `podster why <task>`: prints the lines and answers the exit code. A task that isn't an ID is refused. */
192
+ export function whyCommand(home, task, say) {
193
+ if (!task || !ID.test(task)) {
194
+ say("Name a task: `why <tsk_…>`.");
195
+ return 2;
196
+ }
197
+ const diagnostics = new FileDiagnostics(home);
198
+ for (const line of whyLines(task, diagnostics.lastFor(task), diagnostics.file))
199
+ say(line);
200
+ return 0;
201
+ }
@@ -6,9 +6,16 @@
6
6
  * non-root UID (the owner's, so the task folder Runner made 0700 stays theirs); `--cap-drop ALL`;
7
7
  * `no-new-privileges`; a read-only root; `/tmp` a bounded tmpfs; PID, memory, swap and CPU limits; a disk bound (a
8
8
  * per-file size limit, a bounded tmpfs and a host-side size check of the task folder after every tool that writes);
9
- * `--network none`; no Docker socket, no device and no other mount than the task's folder; a fixed environment; and
10
- * labels naming the run and this Runner's home, so a stop or a restart finds it.
11
- * - **Network:** none. A policy that lists hosts is refused until an egress proxy exists.
9
+ * `--network none` unless the room lists hosts; no Docker socket, no device and no other mount than the task's folder;
10
+ * a fixed environment; and labels naming the run and this Runner's home, so a stop or a restart finds it.
11
+ * - **Network:** none, unless the room's run policy lists hosts (the owner's approval of 2026-11-20). Then the container
12
+ * joins only the run's internal network, whose one other peer is the run's egress proxy (`egress-network.ts`,
13
+ * `egress-proxy.ts`), gets the proxy's address in its fixed environment, and a resolver that answers nothing outside
14
+ * that network: Docker 26 and later answer no outside name on an internal network, older Engines are refused
15
+ * (`docker_engine_too_old`), and its upstream resolver is an address that is never routed (`BLACKHOLE_DNS`). The
16
+ * internal network has no host address (`inhibit_ipv4`), so nothing on the machine is reachable from it. The proxy allows HTTPS `CONNECT`
17
+ * to port 443 of exactly the listed hosts, at public addresses only. Without a pinned proxy image, such a run is
18
+ * refused (`egress_proxy_unavailable`), never widened.
12
19
  * - **The disk bound for the whole run** (M2 on #460): the folder's size is checked on a timer, every
13
20
  * `LIMITS.watch_ms`, independent of tool calls, so a process left running can't fill the disk between them, and a
14
21
  * breach the timer finds halts the run too (re-review item 5); and after each shell call every process in the
@@ -25,18 +32,22 @@
25
32
  * reads, replaces one exact match in Runner, and writes the same way. Only the `shell` tool, when the policy names it,
26
33
  * runs `/bin/sh -c`, which is what that tool is.
27
34
  * - **Stop:** `kill` removes every container carrying the run's label (killing a `docker exec` client leaves its process
28
- * running, so the container goes). At startup `reapAll` removes every container of this Runner's home, since one
29
- * Runner holds the home at a time and anything left is a previous process's.
35
+ * running, so the container goes), then the run's egress proxy and network, after logging the proxy's decisions. At
36
+ * startup `reapAll` removes every container and egress network of this Runner's home, since one Runner holds the home
37
+ * at a time and anything left is a previous process's.
30
38
  *
31
39
  * The `docker` program is a seam (`DockerCli`), so tests run no Docker. It gets the allow-listed environment plus its
32
40
  * own settings: a throwaway `DOCKER_CONFIG`, and the daemon's address. Logs carry IDs and codes only.
33
41
  */
42
+ import { DetailedError } from "../core/errors.js";
34
43
  import { spawn } from "node:child_process";
35
44
  import { createHash } from "node:crypto";
36
45
  import { existsSync } from "node:fs";
37
46
  import { homedir } from "node:os";
38
47
  import { dirname, join } from "node:path";
39
- import { checkContainerSpec, CONTAINER_ENV, CONTAINER_WORKDIR, MAX_TOOL_OUTPUT_BYTES } from "../core/run-interface.js";
48
+ import { checkContainerSpec, CONTAINER_ENV, CONTAINER_WORKDIR, EGRESS_ENV, MAX_TOOL_OUTPUT_BYTES } from "../core/run-interface.js";
49
+ import { silentLogger } from "../core/runtime.js";
50
+ import { egressNames, logProxyDecisions, openEgress, removeNetworks, ROLE_NETWORK, ROLE_PROXY } from "./egress-network.js";
40
51
  import { onWindowsDrive } from "../core/policy.js";
41
52
  import { onWindowsFilesystem } from "./platform.js";
42
53
  import { childEnv } from "./child-env.js";
@@ -122,7 +133,10 @@ const containerName = (ref) => `podster-run-${ref.toLowerCase()}`;
122
133
  export const homeLabel = (home) => createHash("sha256").update(home).digest("hex").slice(0, 32);
123
134
  /** `docker run`'s arguments for a spec: the whole hardening list, and nothing from the task. */
124
135
  export function runArgs(spec, opts) {
125
- const env = Object.entries(CONTAINER_ENV).flatMap(([name, value]) => ["--env", `${name}=${value}`]);
136
+ const allowlist = spec.network.kind === "allowlist";
137
+ const env = Object.entries(allowlist ? { ...CONTAINER_ENV, ...EGRESS_ENV } : CONTAINER_ENV).flatMap(([name, value]) => ["--env", `${name}=${value}`]);
138
+ // Only the run's internal network, never a route out; its resolver answers only that network's names.
139
+ const network = allowlist ? ["--network", egressNames(spec.run_ref).network, "--dns", BLACKHOLE_DNS] : ["--network", "none"];
126
140
  return [
127
141
  "run",
128
142
  "--detach",
@@ -159,8 +173,7 @@ export function runArgs(spec, opts) {
159
173
  "nofile=1024:1024",
160
174
  "--ulimit",
161
175
  "core=0",
162
- "--network",
163
- "none",
176
+ ...network,
164
177
  "--ipc",
165
178
  "none",
166
179
  ...env,
@@ -187,7 +200,26 @@ export function toolArgv(call) {
187
200
  return null;
188
201
  }
189
202
  }
190
- const REFUSED_NETWORK = "network_allowlist_unsupported";
203
+ /** A run whose room lists hosts, on a Runner with no pinned egress proxy: refused, never widened to the internet. */
204
+ export const EGRESS_UNAVAILABLE = "egress_proxy_unavailable";
205
+ /** A run whose room lists hosts, on a Docker Engine older than `MIN_EGRESS_ENGINE`: refused. */
206
+ export const ENGINE_TOO_OLD = "docker_engine_too_old";
207
+ /**
208
+ * The oldest Docker Engine an allowlist runs on: 26.0, whose resolver no longer forwards a container's lookups outside
209
+ * an internal network. An older one could carry a task's DNS queries out, a channel past the proxy.
210
+ */
211
+ export const MIN_EGRESS_ENGINE = 26;
212
+ /**
213
+ * The task container's upstream resolver when its room lists hosts: an address of TEST-NET-1 (RFC 5737), which is never
214
+ * routed, isn't loopback (Docker forwards to a loopback resolver from the host's own namespace), and is outside every
215
+ * network the container is on. So even an engine that forwarded outside names would send them nowhere.
216
+ */
217
+ export const BLACKHOLE_DNS = "192.0.2.1";
218
+ /** The Engine's major version from `docker version --format {{.Server.Version}}`, or null. */
219
+ export function engineMajor(stdout) {
220
+ const m = stdout.trim().match(/^(\d{1,4})\.\d{1,4}/);
221
+ return m ? Number(m[1]) : null;
222
+ }
191
223
  /** The most `/proc` listings one stray-reap may take before it ends the container instead. **Proposed** figure. */
192
224
  export const STRAY_LISTINGS = 6;
193
225
  /** The PIDs an `ls -l -- /proc` shows, leaving out the listing's own (the target of `/proc/self`). */
@@ -209,9 +241,14 @@ export class DockerSandbox {
209
241
  limits;
210
242
  wait;
211
243
  mounts;
244
+ egress;
245
+ engineChecked = false;
246
+ log;
212
247
  constructor(opts) {
213
248
  if (!IMAGE_ID.test(opts.image))
214
249
  throw new Error("Runner's task image must be pinned by its sha256 image ID");
250
+ if (opts.proxy && !IMAGE_ID.test(opts.proxy.image))
251
+ throw new Error("Runner's egress proxy image must be pinned by its sha256 image ID");
215
252
  if (!Number.isSafeInteger(opts.uid) || !Number.isSafeInteger(opts.gid) || opts.uid <= 0 || opts.gid < 0)
216
253
  throw new Error("Runner won't run a task container as root");
217
254
  this.docker = opts.docker;
@@ -225,6 +262,8 @@ export class DockerSandbox {
225
262
  // The system's mounts, read at each open; none (no check by type) where there's no /proc, as on a Mac.
226
263
  this.mounts = opts.mounts ?? (() => null);
227
264
  this.limits = { folder_bytes: opts.limits?.folder_bytes ?? LIMITS.folder_bytes, folder_entries: opts.limits?.folder_entries ?? LIMITS.folder_entries };
265
+ this.log = opts.log ?? silentLogger;
266
+ this.egress = opts.proxy ? { docker: opts.docker, image: opts.proxy.image, program: opts.proxy.program, uid: opts.uid, gid: opts.gid, home_label: this.homeLabel, wait: this.wait } : null;
228
267
  }
229
268
  async overBound(opened) {
230
269
  return (await folderBytes(opened.spec.task_folder, this.limits.folder_bytes, this.limits.folder_entries).catch(() => this.limits.folder_bytes + 1)) > this.limits.folder_bytes;
@@ -237,9 +276,9 @@ export class DockerSandbox {
237
276
  // Never the Windows file system under WSL2, where modes aren't enforced (S-47); the run policy refuses it first.
238
277
  if (onWindowsDrive(spec.task_folder))
239
278
  throw new Error("workspace_on_windows_drive");
240
- // No allowlist without an egress proxy to hold it (step 9(b)'s ruling): refused, never widened to the internet.
241
- if (spec.network.kind !== "none")
242
- throw new Error(REFUSED_NETWORK);
279
+ // No allowlist without an egress proxy to hold it: refused, never widened to the internet.
280
+ if (spec.network.kind !== "none" && !this.egress)
281
+ throw new Error(EGRESS_UNAVAILABLE);
243
282
  // Runner makes the task's folder itself, mode 0700, checking every segment for links (L3).
244
283
  await ensureFolder(this.workspaceRoot(spec), spec.task_folder, { makeRoot: true });
245
284
  // By its real path and its mount's type too (L1 on #471's review): a link, or a drive mounted somewhere other than
@@ -249,12 +288,33 @@ export class DockerSandbox {
249
288
  throw new Error("workspace_on_windows_drive");
250
289
  if (signal.aborted)
251
290
  throw new Error("halted");
291
+ if (spec.network.kind === "allowlist" && this.egress) {
292
+ // Once per process: an Engine too old to keep DNS inside an internal network refuses every allowlist run.
293
+ if (!this.engineChecked) {
294
+ const v = await this.docker(["version", "--format", "{{.Server.Version}}"], { signal, timeoutMs: LIMITS.docker_ms, maxOutputBytes: 4096 });
295
+ const major = v.code === 0 && !v.cut ? engineMajor(v.stdout) : null;
296
+ if (major === null)
297
+ throw dockerFailure("version", v.code);
298
+ if (major < MIN_EGRESS_ENGINE)
299
+ throw new Error(ENGINE_TOO_OLD);
300
+ this.engineChecked = true;
301
+ }
302
+ // Recorded first, so a kill reaches a network or proxy a failed step still made.
303
+ this.opened.set(spec.run_ref, { name: containerName(spec.run_ref), spec, sleep_pid: null, unwatch: () => undefined, events: events ?? null });
304
+ try {
305
+ await openEgress(this.egress, spec.run_ref, spec.network.hosts, spec.max_seconds, signal);
306
+ }
307
+ catch (error) {
308
+ await this.kill(spec.run_ref).catch(() => undefined);
309
+ throw error;
310
+ }
311
+ }
252
312
  const run = await this.docker(runArgs(spec, { image: this.image, uid: this.uid, gid: this.gid, home_label: this.homeLabel }), { signal, timeoutMs: LIMITS.docker_ms, maxOutputBytes: 4096 });
253
313
  // Recorded either way, so a kill reaches a container a failed or aborted `docker run` still made.
254
314
  const opened = { name: containerName(spec.run_ref), spec, sleep_pid: null, unwatch: () => undefined, events: events ?? null };
255
315
  this.opened.set(spec.run_ref, opened);
256
316
  if (run.code !== 0)
257
- throw new Error("container_failed");
317
+ throw new DetailedError("container_failed", { exit_code: run.code, stderr: run.stderr, cut: run.cut });
258
318
  // The disk bound, for the whole run, whatever runs in the container (M2).
259
319
  opened.unwatch = this.every(LIMITS.watch_ms, async () => {
260
320
  if (this.opened.get(spec.run_ref) === opened && (await this.overBound(opened)))
@@ -265,7 +325,7 @@ export class DockerSandbox {
265
325
  const pids = children.stdout.trim().split(/\s+/).filter((p) => p !== "");
266
326
  if (children.code !== 0 || pids.length !== 1 || !/^\d+$/.test(pids[0])) {
267
327
  await this.kill(spec.run_ref).catch(() => undefined);
268
- throw new Error("container_failed");
328
+ throw new DetailedError("container_failed", { exit_code: children.code, stderr: children.stderr, cut: children.cut });
269
329
  }
270
330
  opened.sleep_pid = pids[0];
271
331
  }
@@ -374,27 +434,64 @@ export class DockerSandbox {
374
434
  this.opened.get(run_ref)?.unwatch();
375
435
  // By labels and by name, resolved to IDs and each named once, then confirmed gone.
376
436
  const left = async () => [...new Set([...(await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=task`])), ...(await this.list([`name=^/${containerName(run_ref)}$`]))])];
377
- await removeContainers(this.docker, await left(), left, this.wait);
437
+ // Each step is tried even if one before it threw, so a task container Docker won't remove never leaves the proxy
438
+ // and networks behind; the first failure is thrown at the end, so the stop is never taken as done.
439
+ const failures = [];
440
+ const attempt = async (step) => {
441
+ try {
442
+ await step();
443
+ }
444
+ catch (error) {
445
+ failures.push(error);
446
+ }
447
+ };
448
+ await attempt(async () => removeContainers(this.docker, await left(), left, this.wait));
449
+ // Then the run's egress proxy, its decisions logged first, and its two networks.
450
+ const proxies = async () => [...new Set([...(await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_PROXY}`])), ...(await this.list([`name=^/${egressNames(run_ref).proxy}$`]))])];
451
+ await attempt(async () => {
452
+ const found = await proxies();
453
+ if (found.length > 0)
454
+ await logProxyDecisions(this.docker, run_ref, this.log).catch(() => undefined);
455
+ await removeContainers(this.docker, found, proxies, this.wait);
456
+ });
457
+ await attempt(() => removeNetworks(this.docker, [`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_NETWORK}`], this.wait));
458
+ if (failures.length > 0)
459
+ throw failures[0];
378
460
  }
379
- /** Nothing of the run's task container is listed, by its labels or by its name (Docker names carry a leading slash). */
461
+ /** Nothing of the run's task container or egress is listed, by labels or by name (Docker names carry a leading slash). */
380
462
  async gone(run_ref) {
381
463
  if (!REF.test(run_ref))
382
464
  throw new Error("run_ref_invalid");
383
- const left = (await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=task`])).length === 0 && (await this.list([`name=^/${containerName(run_ref)}$`])).length === 0;
465
+ const left = (await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=task`])).length === 0 &&
466
+ (await this.list([`name=^/${containerName(run_ref)}$`])).length === 0 &&
467
+ (await this.list([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_PROXY}`])).length === 0 &&
468
+ (await this.list([`name=^/${egressNames(run_ref).proxy}$`])).length === 0 &&
469
+ (await this.listNetworks([`label=${LABEL_RUN}=${run_ref}`, `label=${LABEL_ROLE}=${ROLE_NETWORK}`])).length === 0;
384
470
  if (left) {
385
471
  this.opened.get(run_ref)?.unwatch();
386
472
  this.opened.delete(run_ref);
387
473
  }
388
474
  return left;
389
475
  }
390
- /** At startup, before any stop is confirmed (M4 on #459): every container of this home goes. */
476
+ /** At startup, before any stop is confirmed (M4 on #459): every container of this home goes, then its egress networks. */
391
477
  async reapAll() {
392
478
  const ids = await this.list([`label=${LABEL_HOME}=${this.homeLabel}`]);
393
- if (ids.length === 0)
394
- return 0;
395
- await removeContainers(this.docker, ids, () => this.list([`label=${LABEL_HOME}=${this.homeLabel}`]), this.wait);
479
+ if (ids.length > 0)
480
+ await removeContainers(this.docker, ids, () => this.list([`label=${LABEL_HOME}=${this.homeLabel}`]), this.wait);
481
+ await removeNetworks(this.docker, [`label=${LABEL_HOME}=${this.homeLabel}`, `label=${LABEL_ROLE}=${ROLE_NETWORK}`], this.wait);
396
482
  return ids.length;
397
483
  }
484
+ async listNetworks(filters) {
485
+ const r = await this.docker(["network", "ls", "--quiet", "--no-trunc", ...filters.flatMap((f) => ["--filter", f])], { timeoutMs: LIMITS.docker_ms, maxOutputBytes: 64 * 1024 });
486
+ if (r.code !== 0)
487
+ throw dockerFailure("network_ls", r.code);
488
+ if (r.cut)
489
+ throw new Error("docker_network_ls_cut");
490
+ const ids = r.stdout.split("\n").map((l) => l.trim()).filter((l) => l !== "");
491
+ if (!ids.every((id) => /^[A-Za-z0-9_.-]{1,128}$/.test(id)))
492
+ throw new Error("docker_network_ls_output");
493
+ return ids;
494
+ }
398
495
  async list(filters) {
399
496
  const r = await this.docker(["ps", "--all", "--quiet", "--no-trunc", ...filters.flatMap((f) => ["--filter", f])], { timeoutMs: LIMITS.docker_ms, maxOutputBytes: 64 * 1024 });
400
497
  if (r.code !== 0)
@@ -452,7 +549,7 @@ export function dockerCli(program, opts) {
452
549
  child.on("error", (error) => {
453
550
  clearTimeout(timer);
454
551
  signal?.removeEventListener("abort", onAbort);
455
- reject(new Error(`docker couldn't start (${error.code ?? "error"})`));
552
+ reject(new DetailedError("docker_unavailable", { errno: String(error.code ?? "error") }));
456
553
  });
457
554
  child.on("close", (code) => {
458
555
  clearTimeout(timer);