A desktop coding agent with free access to frontier models.
TypeScript
feat: read box chat processes, ports and runtimes
ogsamrat8b68ad1337cb
diff --git a/apps/server/src/box/capture.ts b/apps/server/src/box/capture.tsindex 07fb195e..704f4d02 100644--- a/apps/server/src/box/capture.ts+++ b/apps/server/src/box/capture.ts@@ -8,6 +8,7 @@ import { exec } from "./client.js";import { boxHome, readRecord } from "./box.js";import { mapToBox } from "./launch.js";import type { BoxCaptureInfo } from "./service.js";+import type { Runner } from "../context/exec.js";export type BoxProbeResult = { code: number | null; stdout: string; stderr: string } | null;@@ -35,3 +36,16 @@ export function boxProbeRunner(boxFor: (cwd: string) => BoxCaptureInfo | null, p}};}++/**+ * The same probe runner in the capture context's Runner shape+ * (context/exec.ts), for one chat's box: its processes, listening ports and+ * runtimes are read inside it (context.processes, context.env_turn).+ */+export function boxContextRunner(boxFor: () => BoxCaptureInfo | null, probeEnv: Record<string, string> = {}, env: NodeJS.ProcessEnv = process.env): Runner {+ const probe = boxProbeRunner(() => boxFor(), probeEnv, env);+ return async (file, args, options = {}) => {+ const result = await probe(file, args, { cwd: options.cwd ?? boxFor()?.root ?? "/", timeoutMs: options.timeoutMs ?? 5_000, maxBytes: options.maxBytes ?? 1024 * 1024 });+ return result ? { ...result, truncated: false, timedOut: false } : null;+ };+}diff --git a/apps/server/src/capture-context.test.ts b/apps/server/src/capture-context.test.tsindex 73eb4f31..7aef3e4b 100644--- a/apps/server/src/capture-context.test.ts+++ b/apps/server/src/capture-context.test.ts@@ -20,6 +20,7 @@ import * as commands from "./context/commands.js";import * as outside from "./context/outside.js";import * as ephemeral from "./context/ephemeral.js";import * as network from "./context/network.js";+import * as installLog from "./context/install-log.js";import * as context from "./context/index.js";import * as uploader from "./session-uploader.js";@@ -231,6 +232,137 @@ test.skipIf(process.platform !== "linux")("#19 snapshot: dev processes with scru}});+// --- #19 in an OmniRush box ---------------------------------------------------------------++/** What a box answers (a fake of the runner that runs commands inside it). */+const BOX_PS = [+ " 1 0 /opt/omnirush/boxd",+ " 40 1 /bin/bash -c npm run dev",+ ` 41 40 node server.js --token=${GH_TOKEN}`,+ " 55 1 node -v",+ " 76 1 sh -c ps -eww -o pid=,ppid=,args=; echo \"#probes\"; ...",+ " 77 76 ps -eww -o pid=,ppid=,args=",+ "#probes",+ "/proc/55/environ",+ "/proc/77/environ",+ "#cwds",+ "/proc/1 /",+ `/proc/40 ${os.homedir()}/app`,+ `/proc/41 ${os.homedir()}/app/web`,+].join("\n");+const TCP_HEADER = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n";+const BOX_NET = TCP_HEADER+ + " 0: 0100007F:0BB8 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5551 1 0 100 0 0 10 0\n"+ + " 1: 0100007F:0BB8 0100007F:A2C4 01 00000000:00000000 00:00000000 00000000 0 0 5552 1 0 20 4 30 10 -1\n"+ + TCP_HEADER+ + " 0: 00000000000000000000000000000000:1F90 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5553 1 0 100 0 0 10 0\n"+ + "#owners\n/proc/41/fd socket:[5551]\n41 5552\n";+const boxRunner = (answers: Record<string, string>): exec.Runner => async (file, args) => {+ const key = file === "sh" ? (args[1]!.includes("#owners") ? "sockets" : args[1]!.includes("#probes") ? "table" : "which") : `${file} ${args.join(" ")}`;+ const stdout = answers[key];+ return stdout === undefined ? null : { code: 0, stdout, stderr: "", truncated: false, timedOut: false };+};++test("#19 in a box: the box's processes and listening ports, through its runner; its helper and the probes left out", async () => {+ const run = boxRunner({ table: BOX_PS, sockets: BOX_NET });+ const snapshot = await processes.boxProcessSnapshot("turn_start", 2, run, { privacy: privacy.currentPrivacy(), scrub: SCRUB });+ assert.ok(snapshot);+ assert.equal(snapshot.phase, "turn_start");+ assert.equal(snapshot.turn, 2);+ assert.equal(snapshot.method, "box-ps+box-proc");+ assert.deepEqual(snapshot.processes.map((entry) => entry.pid).sort(), [40, 41], "the helper and every OmniRush probe (OMNIRUSH_LEDGER_OFF=1) left out");+ assert.ok(snapshot.processes.every((entry) => entry.scope === "session"));+ assert.ok(snapshot.processes.find((entry) => entry.pid === 41)!.command.includes("--token=[REDACTED]"));+ assert.equal(snapshot.processes.find((entry) => entry.pid === 41)!.cwd, "~/app/web", "the working folder, home as ~");+ assertNoSecrets(snapshot);+ const ports = snapshot.listening.map((entry) => [entry.port, "address" in entry ? entry.address : undefined, "pid" in entry ? entry.pid : undefined]);+ assert.deepEqual(ports, [[3000, "loopback", 41], [8080, undefined, undefined]], "only LISTEN sockets; one whose owner is unknown is not the session's (port only)");+ // A box that does not answer (stopped, paused) gives no snapshot, never an empty one or a throw.+ assert.equal(await processes.boxProcessSnapshot("session_start", 0, async () => null, { privacy: privacy.currentPrivacy(), scrub: SCRUB }), null);+ assert.equal(await processes.boxProcessSnapshot("session_start", 0, async () => ({ code: 127, stdout: "", stderr: "", truncated: false, timedOut: false }), { privacy: privacy.currentPrivacy(), scrub: SCRUB }), null);+});++test("#19 in a box: the socket table parses tcp and tcp6 with their headers", () => {+ const ports = processes.parseBoxSockets(BOX_NET, [{ pid: 41, ppid: 40, name: "node", command: "node server.js" }]);+ assert.deepEqual(ports, [+ { proto: "tcp", address: "127.0.0.1", port: 3000, pid: 41, process: "node" },+ { proto: "tcp", address: "::", port: 8080, pid: null, process: null },+ ]);+});++test("env_turn in a box: the box's OS, architecture and runtimes, not this machine's", async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "omnirush-boxenv-"));+ try {+ fs.writeFileSync(path.join(root, ".nvmrc"), "22\n");+ const box = boxRunner({+ which: "x86_64\n6.8.0-45-generic\nnode /usr/local/bin/node\npython3 /usr/bin/python3\n",+ "/usr/local/bin/node --version": "v22.23.3\n",+ "/usr/bin/python3 --version": "Python 3.11.2\n",+ });+ const host: exec.Runner = async () => { throw new Error("this machine must not be probed"); };+ const options = { root, pathValue: "/nowhere", skipDir: null, env: {}, platform: "darwin" as const, arch: "arm64", osVersion: "25.6.0", privacy: privacy.currentPrivacy(), run: host, box };+ const first = await installLog.envFingerprint(options);+ assert.equal(first.os, "linux");+ assert.equal(first.arch, "x64");+ assert.equal(first.os_version, "6.8.0-45-generic");+ assert.deepEqual(first.runtimes, { node: "22.23.3", python: "3.11.2" });+ assert.deepEqual(first.paths, { node: "/usr/local/bin/node", python: "/usr/bin/python3" });+ assert.deepEqual(first.pins, { ".nvmrc": "22" });+ assert.equal(first.changed, true);+ const again = await installLog.envFingerprint(options);+ assert.equal(again.changed, false, "probed again only when the box's runtimes or pins change");+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++/** A runner that really runs the command here, as boxd runs it in a box (sh, the probes' env). */+const shellRunnerWith = (env: Record<string, string | undefined>): exec.Runner => async (file, args, options = {}) => {+ const { spawnSync } = await import("node:child_process");+ const res = spawnSync(file, args, { cwd: options.cwd && fs.existsSync(options.cwd) ? options.cwd : undefined, timeout: options.timeoutMs ?? 5_000, encoding: "utf8", maxBuffer: options.maxBytes ?? 1 << 20, env: { ...process.env, ...env, OMNIRUSH_LEDGER_OFF: "1" } });+ if (res.error || res.status === null || (res.status >= 125 && res.status <= 127)) return null;+ return { code: res.status, stdout: res.stdout, stderr: res.stderr, truncated: false, timedOut: false };+};+const shellRunner = shellRunnerWith({});++test.skipIf(process.platform === "win32")("env_turn in a box: the real which script exits 0 when some runtimes are missing", async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "omnirush-boxsh-"));+ try {+ const found = await installLog.envFingerprint({ root, pathValue: "", skipDir: null, env: {}, platform: "darwin", arch: "arm64", osVersion: null, privacy: privacy.currentPrivacy(), run: async () => null, box: shellRunner });+ assert.notEqual(found.arch, "unknown", "uname answered: the script's status is not its last missing command's");+ assert.ok(found.os_version);+ // The install log's wrappers on PATH are not the runtime.+ const shims = path.join(root, ".omnirush", "pkglog", "bin-0123abcd");+ fs.mkdirSync(shims, { recursive: true });+ fs.writeFileSync(path.join(shims, "node"), "#!/bin/sh\nexec node \"$@\"\n", { mode: 0o755 });+ const wrapped: exec.Runner = (file, args, options) => shellRunnerWith({ PATH: `${shims}:${process.env.PATH}` })(file, args, options);+ const behind = await installLog.envFingerprint({ root: path.join(root, "p2"), pathValue: "", skipDir: null, env: {}, platform: "darwin", arch: "arm64", osVersion: null, privacy: privacy.currentPrivacy(), run: async () => null, box: wrapped });+ assert.ok(behind.paths.node && !behind.paths.node.includes("pkglog"), `the real node, not the wrapper: ${behind.paths.node}`);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test.skipIf(process.platform !== "linux")("#19 in a box: the real table and socket scripts (Linux /proc): a listening child with its folder, the probes left out", async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omnirush-boxproc-"));+ const child = spawn(process.execPath, ["-e", "require('net').createServer().listen(0, '127.0.0.1', function () { console.log(this.address().port) })"], { cwd: dir, stdio: ["ignore", "pipe", "ignore"] });+ try {+ const port = Number(await new Promise<string>((resolve) => child.stdout.once("data", (chunk) => resolve(String(chunk).trim()))));+ // The table itself (a snapshot keeps 200 processes: this machine runs more than a box).+ const table = await processes.boxProcessTable(shellRunner);+ assert.ok(table);+ const mine = table.processes.find((entry) => entry.pid === child.pid);+ assert.ok(mine, "the listening child is in the table");+ assert.equal(mine.cwd, fs.realpathSync(dir));+ assert.ok(!table.processes.some((entry) => /#probes|#owners|^ps -eww/.test(entry.command)), "the probe never lists itself");+ const { ports } = await processes.boxListeningPorts(shellRunner, table.processes);+ assert.equal(ports.find((entry) => entry.port === port)?.pid, child.pid, "its socket's owner read from /proc/<pid>/fd");+ } finally {+ child.kill();+ fs.rmSync(dir, { recursive: true, force: true });+ }+});+// --- #7 services -------------------------------------------------------------------------test("#7 services: docker containers with image digests, local databases by port with client versions, compose files", async () => {diff --git a/apps/server/src/context/PARITY.sha256 b/apps/server/src/context/PARITY.sha256index 1bbe4c09..3bc26628 100644--- a/apps/server/src/context/PARITY.sha256+++ b/apps/server/src/context/PARITY.sha256@@ -3,15 +3,15 @@b7d4fad94c133cb4303db934a5bb8e84dcb09dcc6720dc9cc7245d7c8205fa11 commands.tse13f86577014b52affc4c2336630eedcac277b974939c6741119a62b7fda439b ephemeral.ts5f89ff17f225ac47700d31f34c358591c8fbde794a45c156d607e5a675a2ba73 exec.ts-867bef745ac809a6d6fa8eddf4bc56dea902093274ccb1219d9d50885caa436f index.ts+6a0aef5537b449d31aff2751cf45d844f978cd5d37197998dfb029a10483709c index.ts57c97292c7ca65cb1a024e0206af27ae6d3fbdf06c2973dfbfd3760183d02892 install-log-assets.ts-8235435bff3f95bd9c9303d078a0c2ed6dcd7e67fe87a31a7e3daef0b5cb667e install-log.ts+d204176a44609f7c3da5bcedfada71fdd79703d0c854e3c9632b94e9be007a6f install-log.tsa9474cc5087b39e56f79bcd7e4cdfa9fcb748f26505bf6ad0f891c17393407ac network.tsf626d385059c042f7ac3e0dbaee8315973c8c8a6296184fb5f53cabba95e9af2 outside-files.tsd772119f2785b6926cd765a44589c171542d5e79b3677bfa076851775d794480 outside.tsd7c5638ca9204a9c51a4552e7a9b09cf7beeae9c63d9352d5950118fd5536967 pm-config.ts932c1eff09d540590abf99ede63447f4e0af9396096d325fa5fcfbcde49eda10 privacy.ts-0e04845a2d0ad2136c01a61d3ed1193b62ef99f5b82e1f555b7c97bb6dc18773 processes.ts+d67e99ceab9f67ebe7c0aa028b585208c37198e4fef5250608e677bce3f3c79c processes.ts741f4327c70500feb644c8e0820060097e282ff1f121dba8ce1979604867bbc0 redact-policy.ts820d0a976b16769db789e9b5b3162f3cff096ab7948dcac54d009943a4557492 redact-vectors.jsond8c0636406c8cd9d55f9fb06af8827b3d1b73247393f48aaca2ef053ccf5a1ff services.tsdiff --git a/apps/server/src/context/index.ts b/apps/server/src/context/index.tsindex 99ca3420..78504a4d 100644--- a/apps/server/src/context/index.ts+++ b/apps/server/src/context/index.ts@@ -53,7 +53,7 @@ import {} from "./install-log.js";import { collectPmConfig } from "./pm-config.js";import { cleanUrl, currentPrivacy, tildeText, type PrivacyContext, type Scrubber } from "./privacy.js";-import { processSnapshot, processTable, listeningPorts, type ProcessInfo, type ListeningPort, type SnapshotScope } from "./processes.js";+import { boxProcessSnapshot, processSnapshot, processTable, listeningPorts, type ProcessInfo, type ListeningPort, type SnapshotScope } from "./processes.js";import { collectServices } from "./services.js";import { collectSetup, type SetupFile, type SetupModel } from "./setup.js";import { collectShellAliases } from "./shell-aliases.js";@@ -134,6 +134,13 @@ export type ContextOptions = {installRun?: Runner;/** The app's own state folders: never listed as files a turn wrote. */appDirs?: string[];+ /**+ * The OmniRush box a session's shell tool runs in (src/box): a runner for+ * commands inside it, else null. The session's processes, servers and+ * runtimes are the box's, so `context.processes` and `context.env_turn`+ * read them there instead of on this machine.+ */+ box?: (sessionId: string, root: string) => Runner | null;};/** Shell call windows kept per session for matching the install log's noted calls. */@@ -229,6 +236,10 @@ export class ContextCapture {}/** The session's processes: the app's process tree, and processes working in the project or its outside folders. */+ private boxOf(state: SessionContext): Runner | null {+ return this.options.box?.(state.id, state.root) ?? null;+ }+private scopeOf(state: SessionContext): SnapshotScope {return { rootPid: this.options.rootPid ?? process.pid, folders: () => [state.root, ...state.outside.folderPaths()] };}@@ -539,6 +550,7 @@ export class ContextCapture {})(),privacy: this.privacy,run: this.options.installRun ?? runCommand,+ box: this.boxOf(state),});timings.fingerprint = Math.round(performance.now() - at);at = performance.now();@@ -589,7 +601,9 @@ export class ContextCapture {let table: ProcessInfo[] = [];let listening: ListeningPort[] = [];if (this.section("processes")) {+ const box = this.boxOf(state);const snapshot = await timed("processes", async () => {+ if (box) return boxProcessSnapshot("session_start", 0, box, { ...runOpts, privacy, scrub });const { processes, method } = await processTable(runOpts);table = processes;const ports = await listeningPorts(processes, runOpts);@@ -683,9 +697,13 @@ export class ContextCapture {this.track(state, (async () => {if (after) await withTimeout(after, SECTION_TIMEOUT_MS);const started = performance.now();- const snapshot = await withTimeout(processSnapshot("turn_start", turn, { platform: this.platform, privacy: this.privacy, scrub: this.options.scrub, scope: this.scopeOf(state) }), SECTION_TIMEOUT_MS);+ const box = this.boxOf(state);+ const snapshot = await withTimeout(box+ ? boxProcessSnapshot("turn_start", turn, box, { platform: this.platform, privacy: this.privacy, scrub: this.options.scrub })+ : processSnapshot("turn_start", turn, { platform: this.platform, privacy: this.privacy, scrub: this.options.scrub, scope: this.scopeOf(state) }), SECTION_TIMEOUT_MS);this.timings.turn_start.push(Math.round(performance.now() - started));- if ("value" in snapshot) this.emit(sessionId, "context.processes", snapshot.value);+ // A box that did not answer gives no snapshot (null), never an empty one.+ if ("value" in snapshot && snapshot.value) this.emit(sessionId, "context.processes", snapshot.value);})());}diff --git a/apps/server/src/context/install-log.ts b/apps/server/src/context/install-log.tsindex b7430f22..59f7bfe2 100644--- a/apps/server/src/context/install-log.ts+++ b/apps/server/src/context/install-log.ts@@ -1515,7 +1515,76 @@ export type EnvTurn = {/** Runtime versions are probed again only when this key (binaries on PATH, their mtime, the version pins) changes. */const fingerprintCache = new Map<string, { key: string; runtimes: Record<string, string> }>();-export async function envFingerprint(options: { root: string; pathValue: string; skipDir: string | null; env: NodeJS.ProcessEnv; platform: NodeJS.Platform; arch: string; osVersion: string | null; privacy: PrivacyContext; run: Runner }): Promise<Omit<EnvTurn, "schema" | "turn" | "at" | "installs" | "outside_writes" | "outside_truncated" | "timings_ms">> {+type EnvFingerprint = Omit<EnvTurn, "schema" | "turn" | "at" | "installs" | "outside_writes" | "outside_truncated" | "timings_ms">;++/** The box's machine, kernel and the runtimes on its PATH (`<command> <path>` lines). */+// PATH is walked by hand so the install log's wrappers (~/.omnirush/pkglog/bin-*, the box's+// /opt/omnirush/pkglog) are skipped, as `skipDir` does on this machine. It always exits 0: a+// loop whose last command is missing would end 127, which reads as "no box".+const BOX_WHICH = `uname -m; uname -r; IFS=:; for c in ${[...new Set(["mise", ...RUNTIMES.flatMap((runtime) => runtime.commands)])].join(" ")}; do for d in $PATH; do case "$d" in */pkglog|*/pkglog/*) continue;; esac; if [ -f "$d/$c" ] && [ -x "$d/$c" ]; then echo "$c $d/$c"; break; fi; done; done; true`;++/**+ * The fingerprint of a session whose shell tool runs in its box (src/box):+ * the runtimes the agent's commands run with are the box's, so they are+ * found and probed there (`run`: a runner for commands inside it); the+ * version pins are the project's files, the same in and out of the box.+ */+async function boxEnvFingerprint(options: { root: string; privacy: PrivacyContext; run: Runner }): Promise<EnvFingerprint> {+ const result = await options.run("sh", ["-c", BOX_WHICH], { timeoutMs: 5_000, cwd: options.root, maxBytes: 64 * 1024 });+ const lines = (result && result.code === 0 ? result.stdout : "").split("\n").map((line) => line.trim());+ const machine = lines[0] ?? "";+ const found = new Map<string, string>();+ for (const line of lines.slice(2)) {+ const match = /^(\S+) (\/\S+)$/.exec(line);+ if (match) found.set(match[1]!, match[2]!);+ }+ const paths: Record<string, string> = {};+ for (const runtime of RUNTIMES) {+ const command = runtime.commands.find((name) => found.has(name));+ if (command) paths[runtime.name] = found.get(command)!;+ }+ const pins: Record<string, string> = {};+ for (const name of PIN_FILES) {+ const text = await readText(path.join(options.root, name), 4096);+ if (text !== null) pins[name] = text.trim().slice(0, 512);+ }+ const managers = new Set<string>();+ for (const file of Object.values(paths)) for (const [pattern, manager] of MANAGER_PATH) if (pattern.test(file)) managers.add(manager);+ if (found.has("mise")) managers.add("mise");+ const key = `${JSON.stringify(paths)}|${JSON.stringify(pins)}`;+ const cacheKey = `box\0${options.root}`;+ const cached = fingerprintCache.get(cacheKey);+ let runtimes: Record<string, string>;+ let changed = true;+ if (cached && cached.key === key) {+ runtimes = cached.runtimes;+ changed = false;+ } else {+ runtimes = {};+ await Promise.all(RUNTIMES.map(async (runtime) => {+ const file = paths[runtime.name];+ if (!file) return;+ const probe = await options.run(file, runtime.args, { timeoutMs: 5_000, cwd: options.root, maxBytes: 64 * 1024 });+ const match = runtime.pattern.exec(`${probe?.stdout ?? ""}\n${probe?.stderr ?? ""}`);+ if (match) runtimes[runtime.name] = match[1]!;+ }));+ fingerprintCache.set(cacheKey, { key, runtimes });+ changed = !cached || JSON.stringify(cached.runtimes) !== JSON.stringify(runtimes);+ }+ return {+ os: "linux",+ arch: machine === "x86_64" ? "x64" : machine === "aarch64" ? "arm64" : machine || "unknown",+ os_version: lines[1] || null,+ runtimes,+ paths: Object.fromEntries(Object.entries(paths).map(([name, file]) => [name, tildeText(file, options.privacy)])),+ managers: [...managers].sort(),+ pins,+ changed,+ };+}++export async function envFingerprint(options: { root: string; pathValue: string; skipDir: string | null; env: NodeJS.ProcessEnv; platform: NodeJS.Platform; arch: string; osVersion: string | null; privacy: PrivacyContext; run: Runner; box?: Runner | null }): Promise<EnvFingerprint> {+ if (options.box) return boxEnvFingerprint({ root: options.root, privacy: options.privacy, run: options.box });const paths: Record<string, string> = {};const keyParts: string[] = [];for (const runtime of RUNTIMES) {diff --git a/apps/server/src/context/processes.ts b/apps/server/src/context/processes.tsindex a9d5c308..60961d31 100644--- a/apps/server/src/context/processes.ts+++ b/apps/server/src/context/processes.ts@@ -13,7 +13,7 @@ export const MAX_PROCESSES = 200;export const MAX_LISTENING = 200;const MAX_COMMAND_CHARS = 2_000;-export type ProcessInfo = { pid: number; ppid: number; name: string; command: string };+export type ProcessInfo = { pid: number; ppid: number; name: string; command: string; /** Its working folder, where the source knows it (a box). */ cwd?: string };export type ListeningPort = { proto: "tcp"; address: string; port: number; pid: number | null; process: string | null };/** Process names (or name prefixes) that matter to a developer's environment. */@@ -332,7 +332,7 @@ export type ProcessSnapshot = {/** Ports of the session's processes (address class, pid, name) and of any other process (port and base name only). */listening: Array<ListeningPort | ForeignListeningPort>;/** The session's own processes and those working in its folders, with scrubbed command lines. */- processes: Array<{ pid: number; name: string; command: string; scope: "session" | "folder" }>;+ processes: Array<{ pid: number; name: string; command: string; scope: "session" | "folder"; /** The working folder (home as `~`), in a box. */ cwd?: string }>;/** How many processes the machine runs (none of the others is named). */total_processes: number;truncated: boolean;@@ -359,6 +359,109 @@ export type SnapshotOptions = ProcessTableOptions & {cwdOf?: (pids: number[]) => Promise<Map<number, string>>;};+// --- an OmniRush box ------------------------------------------------------------------+//+// A session whose shell tool runs in its project's box (src/box) has its+// processes and servers there, in their own PID namespace, out of this+// machine's process table. They are read through the box's helper: `ps`+// for the table, the box's /proc for the listening sockets and their+// owners. Every process in the box is the session's, but the box's own+// helper and these probes.++/** The box's own helper and init, never the session's. */+const BOX_OWN = /^(?:boxd|boxrun|docker-init|tini|catatonit)$/;+/** `args` only: the name is its program (parsePs). */+const BOX_PS_ARGS = ["-eww", "-o", "pid=,ppid=,args="];+/**+ * The table, then the processes OmniRush's own probes run (this one, the+ * toolchain's and env_turn's, all started with OMNIRUSH_LEDGER_OFF=1; read+ * before and after the table, so a probe as short as `gcc --version` that+ * ends meanwhile is still known), then each process's working folder. One+ * process per section (no fork per entry), and the script always exits 0.+ */+const BOX_PROBES = "grep -las OMNIRUSH_LEDGER_OFF=1 /proc/[0-9]*/environ";+const BOX_TABLE = `b=$(${BOX_PROBES}); ps ${BOX_PS_ARGS.join(" ")}; echo "#probes"; echo "$b"; ${BOX_PROBES}; echo "#cwds"; find /proc/[0-9]* -maxdepth 1 -name cwd -printf '%h %l\\n' 2>/dev/null; true`;+/**+ * Listening sockets (/proc/net/tcp, tcp6), then `/proc/<pid>/fd socket:[<inode>]`+ * for every socket a process holds (`<pid> <inode>` from the loop where the+ * box has no find). A readlink per fd costs ~1.3 ms: 1.6 s in a box with+ * 1,200 fds, against ~15 ms for one find.+ */+const BOX_SOCKETS = 'cat /proc/net/tcp /proc/net/tcp6 2>/dev/null; echo "#owners"; if command -v find >/dev/null 2>&1; then find /proc/[0-9]*/fd -lname "socket:*" -printf "%h %l\\n" 2>/dev/null; else for f in /proc/[0-9]*/fd/*; do l=$(readlink "$f" 2>/dev/null) || continue; case "$l" in socket:*) p=${f#/proc/}; i=${l#socket:[}; echo "${p%%/*} ${i%]}";; esac; done; fi; true';++/** `BOX_TABLE` output: the session's processes (the box's helper and OmniRush's probes left out), with their working folders. */+export function parseBoxTable(text: string): ProcessInfo[] {+ const [table = "", probes = "", cwds = ""] = text.split(/^#(?:probes|cwds)$/m);+ const probing = new Set<number>();+ for (const line of probes.split("\n")) {+ const match = /^\/proc\/(\d+)\/environ$/.exec(line.trim());+ if (match) probing.add(Number(match[1]));+ }+ const cwdOf = new Map<number, string>();+ for (const line of cwds.split("\n")) {+ const match = /^\/proc\/(\d+) (\/.*)$/.exec(line.trim());+ if (match) cwdOf.set(Number(match[1]), match[2]!);+ }+ return parsePs(table)+ // `ps` itself has exited by the time its environment could be read: it is known by its command line.+ .filter((info) => !BOX_OWN.test(info.name) && !probing.has(info.pid) && !info.command.startsWith(`ps ${BOX_PS_ARGS.join(" ")}`) && !info.command.includes("#probes") && !info.command.includes("#owners"))+ .map((info) => (cwdOf.has(info.pid) ? { ...info, cwd: cwdOf.get(info.pid)! } : info));+}++/** The box's process table through `run` (a runner for commands inside the box); null when the box did not answer. */+export async function boxProcessTable(run: Runner): Promise<{ processes: ProcessInfo[]; method: string } | null> {+ const result = await run("sh", ["-c", BOX_TABLE], { timeoutMs: 5_000, maxBytes: 2 * 1024 * 1024 });+ if (!result || result.code !== 0 || !result.stdout.trim()) return null;+ return { processes: parseBoxTable(result.stdout), method: "box-ps" };+}++/** The box's listening TCP sockets and their owners (`BOX_SOCKETS` output). */+export function parseBoxSockets(text: string, processes: readonly ProcessInfo[]): ListeningPort[] {+ const [table = "", owners = ""] = text.split(/^#owners$/m);+ const byInode = new Map<number, number>();+ for (const line of owners.split("\n")) {+ const match = /^(?:\/proc\/)?(\d+)(?:\/fd)? (?:socket:\[)?(\d+)\]?$/.exec(line.trim());+ if (match) byInode.set(Number(match[2]), Number(match[1]));+ }+ const byPid = new Map(processes.map((p) => [p.pid, p]));+ // /proc/net/tcp and tcp6 each start with a header line: parse them one by one.+ const rows = table.split(/^(?=\s*sl\s)/m).flatMap(parseProcNetTcp);+ return rows.filter((socket) => socket.state === "0A").map((socket) => {+ const pid = byInode.get(socket.inode) ?? null;+ return { proto: "tcp" as const, address: socket.local.address, port: socket.local.port, pid, process: pid !== null ? byPid.get(pid)?.name ?? null : null };+ });+}++export async function boxListeningPorts(run: Runner, processes: readonly ProcessInfo[]): Promise<{ ports: ListeningPort[]; method: string }> {+ const result = await run("sh", ["-c", BOX_SOCKETS], { timeoutMs: 5_000, maxBytes: 4 * 1024 * 1024 });+ return { ports: result && result.code === 0 ? parseBoxSockets(result.stdout, processes) : [], method: "box-proc" };+}++/**+ * A `context.processes` snapshot of a box: every process in it is the+ * session's (scope: the box's whole tree), each with its working folder.+ * Null when the box did not answer (stopped, paused, gone): no snapshot is+ * better than one saying nothing ran.+ */+export async function boxProcessSnapshot(phase: ProcessSnapshot["phase"], turn: number, run: Runner, options: Omit<SnapshotOptions, "precomputed" | "scope" | "selfPid">): Promise<ProcessSnapshot | null> {+ const read = await boxProcessTable(run);+ if (!read) return null;+ const { processes: table, method } = read;+ // The box's helper is left out of the table: what it started hangs from the box's root (0).+ const pids = new Set(table.map((info) => info.pid));+ const processes = table.map((info) => (pids.has(info.ppid) ? info : { ...info, ppid: 0 }));+ const ports = await boxListeningPorts(run, processes);+ return processSnapshot(phase, turn, {+ ...options,+ scope: { rootPid: 0, folders: () => [] },+ selfPid: -1,+ // A socket whose owner could not be read stays unowned (port only), as on this machine: it is the+ // box's helper (root's, the probe is not), a root process of the agent's, or, where the box shares+ // this machine's network (bubblewrap, the WSL distro), any process of this machine's.+ precomputed: { processes, listening: ports.ports, method: `${method}+${ports.method}` },+ });+}+/** The descendants of `rootPid` in a process table. */export function descendantsOf(rootPid: number, processes: readonly ProcessInfo[]): Set<number> {const children = new Map<number, number[]>();@@ -444,6 +547,7 @@ export async function processSnapshot(phase: ProcessSnapshot["phase"], turn: numname: cleanText(baseNameOnly(info.name) ?? info.name, options.privacy, options.scrub),command: cleanCommand(info.command, options.privacy, options.scrub),scope: tree.has(info.pid) ? ("session" as const) : ("folder" as const),+ ...(info.cwd ? { cwd: cleanText(info.cwd, options.privacy, options.scrub) } : {}),}));const owned = (pid: number | null) => pid !== null && (tree.has(pid) || inFolders.has(pid) || pid === scope.rootPid);const listening = ports.slice(0, MAX_LISTENING).map((port): ListeningPort | ForeignListeningPort => (owned(port.pid)diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.tsindex e49d5699..bd61aa00 100644--- a/apps/server/src/session-uploader.ts+++ b/apps/server/src/session-uploader.ts@@ -29,7 +29,7 @@ import { writeFileAtomic } from "./atomic-write.js";import { XCODE_CLT_MISSING, gitSkipReason } from "./command-guard.js";import { ExcludedFiles, listGitIgnored, type HashCache } from "./excluded-files.js";import { PROBE_ENV_OVERRIDES, ToolchainCache, type CollectOptions as ToolchainOptions, type UploadToolchain } from "./toolchain.js";-import { boxProbeRunner } from "./box/capture.js";+import { boxContextRunner, boxProbeRunner } from "./box/capture.js";import type { BoxLabel } from "./box/box.js";import type { BoxCaptureInfo } from "./box/service.js";import { engine2ImportedFrom } from "./engine2/imported.js";@@ -4767,10 +4767,15 @@ export class SessionUploader {);void this.stateMigrated.then(() => this.cleanTempDir(60 * 60_000)).catch(() => undefined);this.context = !options.context || !this.enabled ? null : this.createContext(stateDir, options.context);+ // A box chat: its processes, listening ports and runtimes are read inside its box+ // (context.processes, context.env_turn); this machine's packages, services, network+ // and package-manager config are not the chat's. The network observer samples this+ // machine only: off here.this.boxContext = !options.context || !this.enabled ? null : this.createContext(stateDir, {...options.context,- sections: { ...options.context.sections, system_packages: false, services: false, pm_config: false, shell_aliases: false, processes: false },+ sections: { ...options.context.sections, system_packages: false, services: false, pm_config: false, shell_aliases: false },network: false,+ box: (_sessionId, root) => boxContextRunner(() => this.boxForPath(root), PROBE_ENV_OVERRIDES),}, options.boxInstallLog ?? null);// Uploads spooled by a previous process are retried once this one is up.// Without an account they wait (up to the spool's age limit) for the