Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat(uploader): record the session's environment context beside the conversation

ogsamrat92b489e05011
diff --git a/apps/server/node_modules b/apps/server/node_modules
new file mode 120000
index 00000000..ef02035a
--- /dev/null
+++ b/apps/server/node_modules
@@ -0,0 +1 @@
+/home/ubuntu/omnirush/wt/gui-toolchain/apps/server/node_modules
\ No newline at end of file
diff --git a/apps/server/src/capture-client.test.ts b/apps/server/src/capture-client.test.ts
index d168d35f..94061193 100644
--- a/apps/server/src/capture-client.test.ts
+++ b/apps/server/src/capture-client.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from "bun:test";
+import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
import { execFile } from "node:child_process";
import { randomBytes } from "node:crypto";
import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
@@ -117,6 +117,16 @@ async function until(check: () => boolean | Promise<boolean>, timeoutMs: number,
}
describe("capture worker", () => {
+ // These pin the worker's exact envelope sequence; capture context would add a trace of its own.
+ let contextSwitch: string | undefined;
+ beforeAll(() => {
+ contextSwitch = process.env.OMNIRUSH_CAPTURE_CONTEXT;
+ process.env.OMNIRUSH_CAPTURE_CONTEXT = "0";
+ });
+ afterAll(() => {
+ if (contextSwitch === undefined) delete process.env.OMNIRUSH_CAPTURE_CONTEXT;
+ else process.env.OMNIRUSH_CAPTURE_CONTEXT = contextSwitch;
+ });
test("a 6,000-file start snapshot is read, scrubbed, compressed and uploaded without a main-loop stall over 100 ms", async () => {
const root = await syntheticWorkspace(6_000);
const sink = uploadSink();
diff --git a/apps/server/src/capture-context.test.ts b/apps/server/src/capture-context.test.ts
new file mode 100644
index 00000000..3cc17261
--- /dev/null
+++ b/apps/server/src/capture-context.test.ts
@@ -0,0 +1,681 @@
+// @ts-nocheck -- ported from the CLI suite (test/capture-context.test.js); exercises loosely typed fakes.
+import { test } from "bun:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import net from "node:net";
+import os from "node:os";
+import path from "node:path";
+import zlib from "node:zlib";
+
+import * as privacy from "./context/privacy.js";
+import * as exec from "./context/exec.js";
+import * as systemPackages from "./context/system-packages.js";
+import * as processes from "./context/processes.js";
+import * as services from "./context/services.js";
+import * as setup from "./context/setup.js";
+import * as pmConfig from "./context/pm-config.js";
+import * as shellAliases from "./context/shell-aliases.js";
+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 context from "./context/index.js";
+import * as uploader from "./session-uploader.js";
+
+// Capture context (capture v2): machine context recorded as trace events —
+// system packages (#5), services (#7), outside folders (#10), the agent's
+// setup (#16), package-manager config (#17), shell aliases (#18), processes
+// and ports (#19), network hosts per tool call (#20), reused temp files
+// (#21) and on-the-fly tools (#22). Every item is scrubbed, `~` replaces
+// the home directory, and OMNIRUSH_CAPTURE_CONTEXT=0 turns it all off.
+const hasZstd = typeof zlib.zstdDecompressSync === "function";
+
+/** The uploader's real CONFIG scrub. */
+const SCRUB = {
+ text: (text) => uploader.redactUploadText(text).text,
+ json: (value) => uploader.redactUploadJson(value).value,
+ content: (file, text) => uploader.redactUploadContent(file, text),
+};
+
+// Real-looking secrets (synthetic).
+const GH_TOKEN = "ghp_R4nd0mT0k3nV4lu3F0rT3st1ngPurp0s3sXyZ";
+const NPM_TOKEN = "npm_9fK2LmQ8rT1vX4zB7nC3dE6gH0jP5sW2yA1u";
+const AWS_SECRET = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
+const PASSWORD = "Hunter2-Sup3rS3cret!";
+
+function tmp(prefix) {
+ return fs.mkdtempSync(path.join(os.tmpdir(), `omnirush-ctx-${prefix}-`));
+}
+
+function write(root, files) {
+ for (const [name, content] of Object.entries(files)) {
+ const file = path.join(root, name);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, content);
+ }
+ return root;
+}
+
+const ok = (stdout, stderr = "") => ({ code: 0, stdout, stderr, truncated: false, timedOut: false });
+
+function fakeRun(outputs, calls = []) {
+ return async (file, args) => {
+ calls.push({ file, args });
+ const output = outputs[path.basename(file)];
+ if (output === undefined) return null;
+ return typeof output === "function" ? output(args) : output;
+ };
+}
+
+function assertNoSecrets(value, secrets = [GH_TOKEN, NPM_TOKEN, AWS_SECRET, PASSWORD]) {
+ const text = JSON.stringify(value);
+ for (const secret of secrets) assert.ok(!text.includes(secret), `leaked ${secret.slice(0, 8)}…: ${text.slice(0, 400)}`);
+}
+
+// --- privacy ------------------------------------------------------------------------
+
+test("privacy: the home directory and the account name become ~; URLs lose userinfo; addresses become classes", () => {
+ const ctx = { home: "/home/alice", user: "alice" };
+ assert.equal(privacy.tildeText("cd /home/alice/proj && ls /home/alice", ctx), "cd ~/proj && ls ~");
+ assert.equal(privacy.tildeText("/home/alicex/a stays", ctx), "/home/alicex/a stays");
+ assert.equal(privacy.tildeText("C:\\Users\\alice\\x and /Users/alice/y", { home: "C:\\Users\\alice", user: "alice" }), "~\\x and ~/y");
+ assert.equal(privacy.cleanUrl("https://bob:[email protected]/npm/?token=abc&x=1"), "https://registry.example.com/npm/?token=[REDACTED]&x=1");
+ assert.equal(privacy.cleanUrl("https://conda.anaconda.org/t/abc-123/mychannel"), "https://conda.anaconda.org/t/[REDACTED]/mychannel");
+ assert.equal(privacy.addressClass("127.0.0.1"), "loopback");
+ assert.equal(privacy.addressClass("::1"), "loopback");
+ assert.equal(privacy.addressClass("0.0.0.0"), "any");
+ assert.equal(privacy.addressClass("192.168.1.4"), "private");
+ assert.equal(privacy.addressClass("140.82.112.3"), "public");
+ assert.ok(privacy.isSecretKey("//registry.npmjs.org/:_authToken"));
+ assert.ok(privacy.isSecretKey("_auth"));
+ assert.ok(privacy.isSecretKey("npmAuthToken"));
+ assert.ok(!privacy.isSecretKey("registry"));
+ assert.ok(!privacy.isSecretKey("index-url"));
+});
+
+test("context switches: OMNIRUSH_CAPTURE_CONTEXT=0 turns everything off, OMNIRUSH_CAPTURE_NETWORK=0 only the network observer", () => {
+ assert.equal(context.captureContextEnabled({}), true);
+ assert.equal(context.captureContextEnabled({ OMNIRUSH_CAPTURE_CONTEXT: "0" }), false);
+ assert.equal(context.captureContextEnabled({ OMNIRUSH_CAPTURE_CONTEXT: "off" }), false);
+ assert.equal(context.captureNetworkEnabled({ OMNIRUSH_CAPTURE_NETWORK: "0" }), false);
+ assert.equal(context.captureNetworkEnabled({ OMNIRUSH_CAPTURE_CONTEXT: "0" }), false);
+ const capture = new context.ContextCapture({ client: "cli", scrub: SCRUB, record: () => assert.fail("nothing is recorded"), env: { OMNIRUSH_CAPTURE_CONTEXT: "0" } });
+ assert.equal(capture.enabled, false);
+ capture.sessionStarted("s1-aaaaaaaa", tmp("off"));
+ capture.turnStarted("s1-aaaaaaaa");
+ capture.turnMessages("s1-aaaaaaaa", []);
+});
+
+// --- exec / CLT guard ----------------------------------------------------------------
+
+test("exec: a missing tool is never spawned; a /usr/bin CLT shim is never run on a Mac without the tools", async () => {
+ const calls = [];
+ assert.equal(await exec.runTool("nope", [], { resolve: () => null, run: fakeRun({}, calls) }), null);
+ exec.configureContextCltProbe({ platform: "darwin", xcodeSelect: async () => false });
+ try {
+ assert.equal(await exec.runTool("git", ["--version"], { resolve: () => "/usr/bin/git", run: fakeRun({ git: ok("git 2") }, calls) }), null);
+ assert.deepEqual((await exec.runTool("git", ["--version"], { resolve: () => "/opt/homebrew/bin/git", run: fakeRun({ git: ok("git 2") }, calls) })).stdout, "git 2");
+ } finally {
+ exec.configureContextCltProbe(null);
+ }
+ assert.equal(calls.length, 1);
+});
+
+test.skipIf(process.platform === "win32")("exec: a hanging command is killed at its timeout, its group included", async () => {
+ const started = Date.now();
+ const result = await exec.runCommand("/bin/sh", ["-c", "(sleep 30) & sleep 30"], { timeoutMs: 300 });
+ assert.equal(result.timedOut, true);
+ assert.ok(Date.now() - started < 2_000);
+});
+
+// --- #5 system packages ------------------------------------------------------------------
+
+test("#5 system packages: dpkg/apk/winget parsing, 256 KiB cap, once a day per machine", async () => {
+ assert.deepEqual(systemPackages.parseNameVersionLines("bash 5.2.21-2ubuntu4\nzlib1g 1:1.3\n"), [{ name: "bash", version: "5.2.21-2ubuntu4" }, { name: "zlib1g", version: "1:1.3" }]);
+ assert.deepEqual(systemPackages.parseApk("musl-1.2.4-r2\nca-certificates-bundle-20230506-r0\n"), [{ name: "musl", version: "1.2.4-r2" }, { name: "ca-certificates-bundle", version: "20230506-r0" }]);
+ const winget = "Name Id Version Source\n--------------------------------------------------------------\nGit Git.Git 2.44.0 winget\nNode.js LTS OpenJS.NodeJS.LTS 20.11.1 winget\n";
+ assert.deepEqual(systemPackages.parseWinget(winget), [{ name: "Git.Git", version: "2.44.0" }, { name: "OpenJS.NodeJS.LTS", version: "20.11.1" }]);
+ assert.equal(systemPackages.wingetWouldPrompt({ code: 1, stdout: "Do you agree to all the source agreements terms? [Y] Yes", stderr: "" }), true);
+
+ const big = Array.from({ length: 20_000 }, (_, i) => `package-number-${i} 1.0.${i}-ubuntu1`).join("\n");
+ const calls = [];
+ const cacheDir = tmp("pkgcache");
+ let day = new Date(2026, 9, 4, 10);
+ const options = { platform: "linux", cacheDir, machine: "box/linux", now: () => day, resolve: (c) => (c === "dpkg-query" ? "/usr/bin/dpkg-query" : null), run: fakeRun({ "dpkg-query": ok(big) }, calls) };
+ const first = await systemPackages.systemPackages(options);
+ assert.equal(first.manager, "dpkg");
+ assert.equal(first.count, 20_000);
+ assert.equal(first.truncated, true);
+ assert.ok(Buffer.byteLength(JSON.stringify(first.packages)) <= 256 * 1024);
+ assert.deepEqual(calls[0].args, ["-W", "-f", "${Package} ${Version}\\n"]);
+ await systemPackages.systemPackages(options);
+ assert.equal(calls.length, 1, "the same day reuses the cache");
+ day = new Date(2026, 9, 5, 9);
+ await systemPackages.systemPackages(options);
+ assert.equal(calls.length, 2, "the next day lists again");
+ assert.deepEqual(await systemPackages.listSystemPackages({ platform: "darwin", resolve: () => null }), { skipped: "not_found" });
+ const winCalls = [];
+ const prompted = await systemPackages.listSystemPackages({ platform: "win32", resolve: () => "C:\\winget.exe", run: fakeRun({ "C:\\winget.exe": { code: 1, stdout: "You must accept the source agreements [Y] Yes [N] No", stderr: "", truncated: false, timedOut: false } }, winCalls) });
+ assert.deepEqual(prompted, { skipped: "would_prompt" });
+ assert.ok(winCalls[0].args.includes("--disable-interactivity"));
+});
+
+// --- #19 processes ---------------------------------------------------------------------
+
+test("#19 parsers: /proc stat and addresses, ss, lsof, netstat, ps", () => {
+ assert.deepEqual(processes.parseProcStat("123 (node server) S 45 123 123 0 -1 4194560 1 0 0 0 0 0 0 0 20 0 11 0 9876 1 1"), { comm: "node server", ppid: 45, startTicks: 9876 });
+ assert.deepEqual(processes.parseProcAddress("0100007F:1F90"), { address: "127.0.0.1", port: 8080 });
+ assert.deepEqual(processes.parseProcAddress("00000000000000000000000001000000:0050"), { address: "::1", port: 80 });
+ assert.deepEqual(processes.parseSsListening('LISTEN 0 4096 127.0.0.1:5432 0.0.0.0:* users:(("postgres",pid=812,fd=6))\nLISTEN 0 511 [::]:3000 [::]:*\n'), [
+ { proto: "tcp", address: "127.0.0.1", port: 5432, pid: 812, process: "postgres" },
+ { proto: "tcp", address: "::", port: 3000, pid: null, process: null },
+ ]);
+ assert.deepEqual(processes.parseLsofListen("p501\ncnode\nn*:3000\nn127.0.0.1:9229\n"), [
+ { proto: "tcp", address: "0.0.0.0", port: 3000, pid: 501, process: "node" },
+ { proto: "tcp", address: "127.0.0.1", port: 9229, pid: 501, process: "node" },
+ ]);
+ assert.deepEqual(processes.parseNetstat(" TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1044\n TCP 10.0.0.2:5000 1.2.3.4:443 ESTABLISHED 77\n"), [{ local: "0.0.0.0:135", remote: "0.0.0.0:0", pid: 1044 }]);
+ assert.equal(processes.isDevProcess("python3.12"), true);
+ assert.equal(processes.isDevProcess("bash", "node server.js"), true);
+ assert.equal(processes.isDevProcess("Xorg"), false);
+});
+
+test.skipIf(process.platform !== "linux")("#19 snapshot: dev processes with scrubbed arguments, listening ports as address classes, own engine left out", async () => {
+ const server = net.createServer().listen(0, "127.0.0.1");
+ await new Promise((resolve) => server.once("listening", resolve));
+ const port = server.address().port;
+ const child = spawn(process.execPath, ["-e", "setTimeout(()=>{}, 20000)", "--", `--token=${GH_TOKEN}`, `--password`, PASSWORD, `AWS_SECRET_ACCESS_KEY=${AWS_SECRET}`], { stdio: "ignore" });
+ try {
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ const snapshot = await processes.processSnapshot("turn_start", 3, { privacy: privacy.currentPrivacy(), scrub: SCRUB });
+ assert.equal(snapshot.phase, "turn_start");
+ assert.equal(snapshot.turn, 3);
+ const mine = snapshot.processes.find((entry) => entry.pid === child.pid);
+ assert.ok(mine, "the node child is a dev process");
+ assert.ok(mine.command.includes("--token=[REDACTED]"));
+ assertNoSecrets(snapshot);
+ assert.ok(!snapshot.processes.some((entry) => entry.pid === process.pid), "capture's own process is left out");
+ const listening = snapshot.listening.find((entry) => entry.port === port);
+ assert.ok(listening, `port ${port} is listed`);
+ assert.equal(listening.address, "loopback");
+ assert.ok(snapshot.processes.length <= processes.MAX_PROCESSES);
+ assert.ok(!JSON.stringify(snapshot).includes(os.homedir() + "/"), "no home path");
+ } finally {
+ child.kill();
+ server.close();
+ }
+});
+
+// --- #7 services -------------------------------------------------------------------------
+
+test("#7 services: docker containers with image digests, local databases by port with client versions, compose files", async () => {
+ assert.deepEqual(services.composeFilesOfLabels("com.docker.compose.project=demo,com.docker.compose.project.config_files=/srv/demo/compose.yaml,com.docker.compose.service=db"), ["/srv/demo/compose.yaml"]);
+ const root = write(tmp("svc"), { "docker-compose.yml": "services: {}\n", "deploy/compose.prod.yaml": "services: {}\n", "node_modules/x/compose.yml": "" });
+ const calls = [];
+ const run = fakeRun({
+ docker: (args) => {
+ if (args[0] === "ps") return ok(`${JSON.stringify({ ID: "abc123", Names: "demo-db-1", Image: "postgres:16", Ports: "127.0.0.1:5432->5432/tcp", Status: "Up 2 hours", Labels: "com.docker.compose.project.config_files=/srv/demo/compose.yaml" })}\n`);
+ if (args[0] === "inspect") return ok("abc123 sha256:img1\n");
+ if (args[0] === "image") return ok('sha256:img1 ["postgres@sha256:deadbeef"]\n');
+ return null;
+ },
+ psql: ok("psql (PostgreSQL) 16.3\n"),
+ "redis-server": ok("Redis server v=7.2.4 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=abc\n"),
+ }, calls);
+ const result = await services.collectServices({
+ root,
+ listening: [
+ { proto: "tcp", address: "127.0.0.1", port: 5432, pid: 1, process: "docker-proxy" },
+ { proto: "tcp", address: "0.0.0.0", port: 6379, pid: 2, process: "redis-server" },
+ { proto: "tcp", address: "127.0.0.1", port: 3000, pid: 3, process: "node" },
+ ],
+ processes: [],
+ privacy: privacy.currentPrivacy(),
+ scrub: SCRUB,
+ platform: "darwin",
+ run,
+ resolve: (command) => (["docker", "psql", "redis-server"].includes(command) ? `/usr/local/bin/${command}` : null),
+ });
+ assert.equal(result.docker.reachable, true);
+ assert.deepEqual(result.docker.containers, [{ name: "demo-db-1", image: "postgres:16", image_digest: "postgres@sha256:deadbeef", ports: "127.0.0.1:5432->5432/tcp".replace("127.0.0.1", uploader.redactUploadText("127.0.0.1").text), status: "Up 2 hours" }]);
+ assert.deepEqual(result.databases, [
+ { kind: "postgres", port: 5432, address: "loopback", client_version: "psql (PostgreSQL) 16.3", process: "docker-proxy" },
+ { kind: "redis", port: 6379, address: "any", client_version: "Redis server v=7.2.4 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=abc", process: "redis-server" },
+ ]);
+ assert.ok(calls.filter((call) => /psql|redis/.test(call.file)).every((call) => call.args.length === 1 && call.args[0] === "--version"), "clients are only asked their version");
+ assert.deepEqual(result.compose_files.sort(), ["$PROJECT/deploy/compose.prod.yaml", "$PROJECT/docker-compose.yml", "/srv/demo/compose.yaml"]);
+ const noDocker = await services.collectServices({ root, listening: [], processes: [], privacy: privacy.currentPrivacy(), scrub: SCRUB, platform: "linux", resolve: () => null });
+ assert.deepEqual(noDocker.docker, { reachable: false, containers: [], skipped: "not_installed" });
+});
+
+// --- #16 setup -----------------------------------------------------------------------------
+
+test("#16 setup: skills/plugins with scrubbed texts, MCP servers with names only for env, secret args redacted, versions resolved", async () => {
+ const home = tmp("home");
+ const root = tmp("proj");
+ const bundled = write(tmp("bundled"), { "omnirush-build/SKILL.md": "---\nname: omnirush-build\nversion: 1.2.0\n---\nBuild.\n" });
+ write(home, {
+ ".config/opencode/skills/deploy/SKILL.md": `---\nname: deploy\nversion: 0.3.1\n---\nexport GITHUB_TOKEN=${GH_TOKEN}\n`,
+ ".config/opencode/skills/deploy/scripts/run.sh": `#!/bin/sh\ncurl -H "Authorization: Bearer ${NPM_TOKEN}" https://api.example.com\n`,
+ ".config/opencode/skills/deploy/.env": `SECRET=${PASSWORD}\n`,
+ ".config/opencode/plugin/notify.ts": `export const apiKey = "${GH_TOKEN}";\n`,
+ ".config/opencode/opencode.json": JSON.stringify({
+ model: "omnirush/gpt",
+ plugin: ["[email protected]", "opencode-other"],
+ agent: { build: { model: "omnirush/gpt", variant: "high", options: { reasoningEffort: "high", apiKey: GH_TOKEN } } },
+ mcp: {
+ github: { type: "local", command: ["npx", "-y", "@modelcontextprotocol/[email protected]", "--token", GH_TOKEN], environment: { GITHUB_PERSONAL_ACCESS_TOKEN: GH_TOKEN } },
+ remote: { type: "remote", url: `https://user:${PASSWORD}@mcp.example.com/sse?api_key=${NPM_TOKEN}`, headers: { Authorization: `Bearer ${NPM_TOKEN}` } },
+ },
+ }),
+ ".cache/opencode/node_modules/opencode-other/package.json": JSON.stringify({ name: "opencode-other", version: "3.1.4" }),
+ });
+ const installed = write(tmp("mcpinst"), { "node_modules/@acme/mcp-db/package.json": JSON.stringify({ name: "@acme/mcp-db", version: "0.9.2" }), "node_modules/@acme/mcp-db/dist/index.js": "" });
+ write(root, { ".mcp.json": JSON.stringify({ mcpServers: { db: { command: "node", args: [path.join(installed, "node_modules/@acme/mcp-db/dist/index.js"), `--password=${PASSWORD}`], env: { DB_PASSWORD: PASSWORD } } } }) });
+ const ctx = { home, user: path.basename(home) };
+ const { setup: result, files } = await setup.collectSetup({
+ root,
+ client: "cli",
+ appVersion: "omnirush-cli/2.0.9",
+ engineVersion: "1.18.32",
+ model: { provider_id: "omnirush", model_id: "gpt", variant: "high", agent: "build" },
+ bundledSkillDirs: [bundled],
+ privacy: ctx,
+ scrub: SCRUB,
+ denied: (rel) => uploader.isUploadPathDenied(rel),
+ env: { XDG_CONFIG_HOME: path.join(home, ".config") },
+ });
+ assert.equal(result.app_version, "omnirush-cli/2.0.9");
+ assert.deepEqual(result.bundled_skills.map((s) => [s.name, s.version]), [["omnirush-build", "1.2.0"]]);
+ assert.equal(result.skills.length, 1);
+ assert.equal(result.skills[0].name, "deploy");
+ assert.equal(result.skills[0].version, "0.3.1");
+ assert.equal(result.skills[0].root, "~/.config/opencode/skills/deploy");
+ assert.deepEqual(files.filter((f) => f.kind === "skill").map((f) => f.rel).sort(), ["SKILL.md", "scripts/run.sh"], "the .env file is denied");
+ assert.ok(files.find((f) => f.rel === "SKILL.md").content.includes("Build") === false);
+ assert.deepEqual(result.plugins.map((p) => [p.name, p.version, p.source]).sort(), [["notify", null, "file"], ["opencode-other", "3.1.4", "npm"], ["opencode-wakatime", "1.4.0", "npm"]]);
+ const github = result.mcp_servers.find((s) => s.name === "github");
+ assert.deepEqual([github.package, github.version, github.version_source], ["@modelcontextprotocol/server-github", "2025.4.8", "spec"]);
+ assert.deepEqual(github.env_names, ["GITHUB_PERSONAL_ACCESS_TOKEN"]);
+ assert.deepEqual(github.args.slice(-2), ["--token", "[REDACTED]"]);
+ const remote = result.mcp_servers.find((s) => s.name === "remote");
+ assert.equal(remote.type, "remote");
+ assert.deepEqual(remote.header_names, ["Authorization"]);
+ assert.ok(remote.url.startsWith("https://mcp.example.com/sse"));
+ const db = result.mcp_servers.find((s) => s.name === "db");
+ assert.deepEqual([db.package, db.version, db.version_source, db.scope], ["@acme/mcp-db", "0.9.2", "installed", "project"]);
+ assert.ok(db.args.includes("--password=[REDACTED]"));
+ assert.equal(result.settings.agent.build.reasoningEffort, "high");
+ assert.equal(result.settings.agent.build.variant, "high");
+ assertNoSecrets({ result, files });
+ assert.ok(!JSON.stringify({ result, files }).includes(home), "home is ~");
+});
+
+// --- #17 package-manager config -------------------------------------------------------------
+
+test("#17 package-manager config: keys and safe values kept, every credential key dropped, URLs stripped, scrub on top", async () => {
+ const home = tmp("pmhome");
+ write(home, {
+ ".npmrc": `registry=https://registry.npmjs.org/\n@acme:registry=https://npm.acme.dev/\n//npm.acme.dev/:_authToken=${NPM_TOKEN}\n//registry.npmjs.org/:_auth=${Buffer.from(`u:${PASSWORD}`).toString("base64")}\n_password=${PASSWORD}\[email protected]\nstrict-ssl=true\nproxy=http://proxyuser:${PASSWORD}@proxy.acme.dev:8080\n`,
+ ".yarnrc.yml": `npmRegistryServer: "https://npm.acme.dev"\nnpmAuthToken: ${NPM_TOKEN}\nnpmScopes:\n acme:\n npmRegistryServer: https://npm.acme.dev\n npmAuthToken: ${NPM_TOKEN}\nenableTelemetry: false\n`,
+ ".config/pip/pip.conf": `[global]\nindex-url = https://pypi-user:${PASSWORD}@pypi.acme.dev/simple\nextra-index-url = https://pypi.org/simple\ntrusted-host = pypi.acme.dev\n`,
+ ".config/uv/uv.toml": `index-url = "https://__token__:${GH_TOKEN}@pypi.acme.dev/simple"\n[[index]]\nname = "acme"\nurl = "https://pypi.acme.dev/simple"\n`,
+ ".cargo/config.toml": `[registries.acme]\nindex = "sparse+https://cargo.acme.dev/index/"\ntoken = "${GH_TOKEN}"\n[net]\ngit-fetch-with-cli = true\n`,
+ ".gradle/gradle.properties": `org.gradle.jvmargs=-Xmx2g\nsigning.password=${PASSWORD}\nmavenPassword=${PASSWORD}\nsonatypeToken=${NPM_TOKEN}\n`,
+ ".m2/settings.xml": `<settings><mirrors><mirror><id>acme</id><url>https://repo.acme.dev/maven</url><mirrorOf>*</mirrorOf></mirror></mirrors><servers><server><id>acme</id><username>deploy</username><password>${PASSWORD}</password></server></servers></settings>`,
+ ".condarc": `channels:\n - https://conda.anaconda.org/t/${GH_TOKEN}/acme\n - conda-forge\nssl_verify: true\n`,
+ });
+ const result = await pmConfig.collectPmConfig({
+ privacy: { home, user: null },
+ scrub: SCRUB,
+ platform: "linux",
+ env: {},
+ resolve: (command) => (command === "go" ? "/usr/local/go/bin/go" : null),
+ run: fakeRun({ go: ok(JSON.stringify({ GOPROXY: `https://gouser:${PASSWORD}@goproxy.acme.dev,direct`, GOPRIVATE: "github.com/acme/*", GOFLAGS: "-mod=mod" })) }),
+ });
+ const byTool = Object.fromEntries(result.files.map((file) => [`${file.tool}:${file.path}`, file]));
+ const npm = byTool["npm:~/.npmrc"];
+ assert.deepEqual(npm.entries, { registry: "https://registry.npmjs.org/", "@acme:registry": "https://npm.acme.dev/", "strict-ssl": "true", proxy: "http://proxy.acme.dev:8080" });
+ assert.equal(npm.dropped_keys, 4);
+ assert.equal(byTool["yarn:~/.yarnrc.yml"].entries["npmScopes.acme.npmRegistryServer"], "https://npm.acme.dev");
+ assert.equal(byTool["pip:~/.config/pip/pip.conf"].entries["global.index-url"], "https://pypi.acme.dev/simple");
+ assert.equal(byTool["uv:~/.config/uv/uv.toml"].entries["index[0].url"], "https://pypi.acme.dev/simple");
+ assert.equal(byTool["cargo:~/.cargo/config.toml"].entries["registries.acme.index"], "sparse+https://cargo.acme.dev/index/");
+ assert.equal("registries.acme.token" in byTool["cargo:~/.cargo/config.toml"].entries, false);
+ assert.deepEqual(byTool["gradle:~/.gradle/gradle.properties"].entries, { "org.gradle.jvmargs": "-Xmx2g" });
+ assert.deepEqual(byTool["maven:~/.m2/settings.xml"].entries, { "mirrors[0].id": "acme", "mirrors[0].url": "https://repo.acme.dev/maven", "mirrors[0].mirrorOf": "*", "servers[0].id": "acme" });
+ assert.equal(byTool["conda:~/.condarc"].entries["channels[0]"], "https://conda.anaconda.org/t/[REDACTED]/acme");
+ assert.deepEqual(result.go_env, { GOPROXY: "https://goproxy.acme.dev,direct", GOPRIVATE: "github.com/acme/*", GOFLAGS: "-mod=mod" });
+ assertNoSecrets(result);
+ assert.ok(!JSON.stringify(result).includes("[email protected]"), "email is dropped");
+ assert.ok(!JSON.stringify(result).includes(home));
+});
+
+// --- #18 shell aliases -----------------------------------------------------------------------
+
+test("#18 shell aliases: toolchain aliases and functions from rc files (never sourced), scrubbed; shims on PATH", async () => {
+ const home = tmp("rc");
+ write(home, {
+ ".bashrc": `alias python=python3\nalias pip='pip3'\nalias ll='ls -la'\nalias gh-api="curl -H 'Authorization: token ${GH_TOKEN}'"\nnode() { /opt/node20/bin/node "$@"; }\nexport PATH=$PATH:~/bin\n`,
+ ".zshrc": "alias -g npmi='npm install'\nalias k=kubectl\n",
+ ".config/fish/config.fish": "alias py 'python3'\nabbr -a gco git checkout\n",
+ });
+ const bin = tmp("bin");
+ fs.writeFileSync(path.join(bin, "python3.12"), "");
+ fs.symlinkSync(path.join(bin, "python3.12"), path.join(bin, "python"));
+ const result = await shellAliases.collectShellAliases({
+ privacy: { home, user: null },
+ scrub: SCRUB,
+ platform: "linux",
+ env: {},
+ resolve: (command) => exec.resolveCommand(command, { pathEnv: bin, platform: "linux" }),
+ });
+ const names = result.aliases.map((alias) => `${alias.name}=${alias.value}@${alias.file}:${alias.kind}`);
+ assert.ok(names.includes("python=python3@~/.bashrc:alias"));
+ assert.ok(names.includes("pip=pip3@~/.bashrc:alias"));
+ assert.ok(names.includes("node=/opt/node20/bin/node \"$@\"@~/.bashrc:function"));
+ assert.ok(names.includes("npmi=npm install@~/.zshrc:alias"));
+ assert.ok(names.includes("k=kubectl@~/.zshrc:alias"));
+ assert.ok(names.includes("py=python3@~/.config/fish/config.fish:alias"));
+ assert.ok(names.includes("gco=git checkout@~/.config/fish/config.fish:abbr"));
+ assert.ok(!names.some((name) => name.startsWith("ll=")), "non-toolchain aliases are left out");
+ assert.ok(!names.some((name) => name.startsWith("gh-api=")), "curl aliases are not toolchain aliases");
+ assert.deepEqual(result.shims, [{ name: "python", target: "python3.12", kind: "symlink" }]);
+ assert.deepEqual(shellAliases.parsePowerShellRc("Set-Alias python py\nNew-Alias -Name pip -Value 'py -m pip'\nfunction node { & 'C:\\node\\node.exe' @args }\n").map((a) => a.name), ["python", "pip", "node"]);
+ const leaky = shellAliases.parsePosixRc(`alias npmpub="NPM_TOKEN=${NPM_TOKEN} npm publish"\n`);
+ const cleaned = await shellAliases.collectShellAliases({ privacy: { home: write(tmp("rc2"), { ".bashrc": `alias npmpub="NPM_TOKEN=${NPM_TOKEN} npm publish"\n` }), user: null }, scrub: SCRUB, platform: "linux", env: {}, resolve: () => null });
+ assert.equal(leaky[0].name, "npmpub");
+ assert.ok(cleaned.aliases.length === 0 || !JSON.stringify(cleaned).includes(NPM_TOKEN));
+});
+
+// --- shell command parsing (#10/#21/#22) -------------------------------------------------------
+
+test("command effects: cd chains, created folders, writes, executed scripts, heredocs and on-the-fly tools", () => {
+ const home = "/home/u";
+ const e = commands.commandEffects(
+ "mkdir -p ~/apps/demo && cd ~/apps/demo && git clone --depth 1 https://github.com/acme/tool.git && npm create vite@latest web -- --template react\n"
+ + "cat > /tmp/gen.py <<'EOF'\nprint('x')\nrm -rf /\nEOF\npython3 /tmp/gen.py > out.txt; bash ../run.sh; ./bin/build --fast; source ~/.venvrc\n"
+ + "npx -y [email protected] hi | pnpm dlx create-next-app my-app; uvx ruff==0.6.9 check .; pipx run black --version; bunx prettier; go run golang.org/x/tools/cmd/[email protected] -h; deno run npm:[email protected]",
+ "/proj",
+ home,
+ );
+ assert.deepEqual(e.folders.map((f) => [f.path, f.via, f.created]), [
+ ["/home/u/apps/demo", "mkdir", true],
+ ["/home/u/apps/demo", "cd", false],
+ ["/home/u/apps/demo/tool", "git clone", true],
+ ["/home/u/apps/demo/web", "create", true],
+ ["/home/u/apps/demo/my-app", "create", true],
+ ]);
+ assert.ok(e.writes.includes("/tmp/gen.py"));
+ assert.ok(e.writes.includes("/home/u/apps/demo/out.txt"));
+ assert.ok(!e.writes.includes("/"), "heredoc bodies are not commands");
+ assert.deepEqual(e.executed, ["/tmp/gen.py", "/home/u/apps/run.sh", "/home/u/apps/demo/bin/build", "/home/u/.venvrc"]);
+ assert.deepEqual(e.ephemeral.map((t) => [t.runner, t.package, t.requested]), [
+ ["npx", "cowsay", "1.6.0"],
+ ["pnpm dlx", "create-next-app", null],
+ ["uvx", "ruff", "0.6.9"],
+ ["pipx run", "black", null],
+ ["bunx", "prettier", null],
+ ["go run", "golang.org/x/tools/cmd/stringer", "v0.24.0"],
+ ["deno run", "chalk", "5.3.0"],
+ ]);
+ const calls = commands.toolCallsOf([{ info: { role: "assistant" }, parts: [
+ { type: "tool", tool: "bash", callID: "c2", state: { status: "completed", input: { command: "ls", workdir: "~/x" }, time: { start: 20, end: 30 } } },
+ { type: "tool", tool: "write", callID: "c1", state: { status: "completed", input: { filePath: "/tmp/a.txt" }, time: { start: 10, end: 11 } } },
+ ] }], "/proj", home);
+ assert.deepEqual(calls.map((c) => [c.callId, c.command, c.cwd]), [["c1", null, "/proj"], ["c2", "ls", "/home/u/x"]]);
+});
+
+// --- #10 / #21 outside folders and files ------------------------------------------------------
+
+function tracker(root, temp, extra = {}) {
+ const reported = [];
+ const t = new outside.OutsideTracker({
+ root,
+ sessionStartMs: Date.now() - 1_000,
+ privacy: privacy.currentPrivacy(),
+ scrub: SCRUB,
+ exclusion: (abs) => (uploader.isUploadPathDenied(abs.replace(/^\/+/, "")) ? "credential" : null),
+ reportPath: (abs) => reported.push(abs),
+ tempRoots: [temp],
+ ...extra,
+ });
+ return { t, reported };
+}
+
+const shellCall = (callId, command, cwd, start) => ({ callId, tool: "bash", input: { command }, status: "completed", start, end: start + 1, command, cwd });
+
+test("#10 outside folders: a created folder is reported whole (minus regenerable dirs), with the session cap; executed scripts are inlined, scrubbed", async () => {
+ const root = tmp("proj10");
+ const base = tmp("outside10");
+ const temp = tmp("temp10");
+ const app = path.join(base, "demo");
+ write(app, { "package.json": "{}", "src/index.js": "console.log(1)\n", "node_modules/left-pad/index.js": "x", ".git/HEAD": "ref", "big.bin": Buffer.alloc(2048), ".env": `TOKEN=${GH_TOKEN}\n` });
+ const script = write(base, { "deploy.sh": `#!/bin/sh\nexport AWS_SECRET_ACCESS_KEY=${AWS_SECRET}\necho deploying\n` });
+ const { t, reported } = tracker(root, temp, { maxFolderBytes: 1024 });
+ const result = await t.processCalls([shellCall("call-1", `mkdir -p ${app} && cd ${app} && npm init -y && sh ${path.join(base, "deploy.sh")}`, root, 1)]);
+ assert.equal(result.folders.length, 1);
+ const folder = result.folders[0];
+ assert.equal(folder.reason, "created");
+ assert.equal(folder.via, "mkdir");
+ assert.equal(folder.tool_call_id, "call-1");
+ assert.equal(folder.truncated, true, "the 2 KiB file does not fit the 1 KiB cap");
+ assert.deepEqual(reported.filter((p) => p.startsWith(app)).map((p) => path.relative(app, p)).sort(), ["package.json", "src/index.js"]);
+ assert.ok(folder.excluded_regenerable >= 2, "node_modules and .git are left out");
+ const executed = result.files.find((file) => file.kind === "executed");
+ assert.ok(executed && executed.content.includes("echo deploying"));
+ assertNoSecrets(result);
+ assert.ok(reported.includes(path.join(base, "deploy.sh")));
+ // A later turn adds a file: only the new one is reported.
+ write(app, { "src/extra.js": "1\n" });
+ const again = await t.processCalls([shellCall("call-2", `cd ${app} && ls`, root, 5)]);
+ assert.deepEqual(again.folders.map((f) => f.files), [3]);
+ // The project itself, the home directory and a file system root are never expanded.
+ const safe = await tracker(root, temp).t.processCalls([shellCall("c", `cd ${os.homedir()} && cd / && cd ${root}/sub`, root, 1)]);
+ assert.deepEqual(safe.folders, []);
+});
+
+test("#10 an existing folder the agent worked in contributes only the files changed during the session", async () => {
+ const root = tmp("proj10b");
+ const other = write(tmp("other10"), { "old.txt": "old\n" });
+ const past = new Date(Date.now() - 3_600_000);
+ fs.utimesSync(path.join(other, "old.txt"), past, past);
+ const { t, reported } = tracker(root, tmp("temp10b"), { sessionStartMs: Date.now() - 100 });
+ write(other, { "new.txt": "new\n" });
+ const result = await t.processCalls([shellCall("c1", `cd ${other} && echo new > new.txt`, root, 1)]);
+ assert.equal(result.folders[0].reason, "modified");
+ assert.deepEqual(reported.map((p) => path.basename(p)), ["new.txt"]);
+});
+
+test("#21 temp files: written by one call and read or run by a later one are inlined (scrubbed); a temp file never reused is not", async () => {
+ const root = tmp("proj21");
+ const temp = tmp("temp21");
+ const script = path.join(temp, "probe.py");
+ const unused = path.join(temp, "scratch.txt");
+ const { t } = tracker(root, temp);
+ fs.writeFileSync(script, `import os\nAPI_KEY = "${GH_TOKEN}"\nprint(os.getcwd())\n`);
+ fs.writeFileSync(unused, "never read\n");
+ const first = await t.processCalls([
+ { callId: "w1", tool: "write", input: { filePath: script }, status: "completed", start: 1, end: 2, command: null, cwd: root },
+ shellCall("w2", `echo hi > ${unused}`, root, 3),
+ ]);
+ assert.deepEqual(first.files, [], "writing alone records nothing");
+ const second = await t.processCalls([shellCall("r1", `python3 ${script}`, root, 10)]);
+ assert.equal(second.files.length, 1);
+ const file = second.files[0];
+ assert.equal(file.kind, "temp");
+ assert.equal(file.written_by, "w1");
+ assert.equal(file.tool_call_id, "r1");
+ assert.ok(file.content.includes("print(os.getcwd())"));
+ assertNoSecrets(second);
+ const third = await t.processCalls([{ callId: "r2", tool: "read", input: { filePath: unused }, status: "completed", start: 20, end: 21, command: null, cwd: root }]);
+ assert.equal(third.files.length, 1, "a read of an earlier-written temp file counts");
+ const repeat = await t.processCalls([shellCall("r3", `cat ${unused}`, root, 30)]);
+ assert.equal(repeat.files.length, 0, "the same content is recorded once");
+ assert.equal(outside.isTempPath("/private/var/folders/ab/cdefg/T/x.py", []), true);
+});
+
+// --- #22 ephemeral tools --------------------------------------------------------------------------
+
+test("#22 on-the-fly tools: exact versions, cache lookups per runner, registry fallback only without a cache hit", async () => {
+ const home = tmp("eph");
+ write(home, {
+ ".npm/_npx/1a2b/node_modules/cowsay/package.json": JSON.stringify({ name: "cowsay", version: "1.6.0" }),
+ ".npm/_npx/3c4d/node_modules/@scope/tool/package.json": JSON.stringify({ name: "@scope/tool", version: "2.3.4" }),
+ ".bun/install/cache/[email protected]@@@1/package.json": "{}",
+ ".cache/uv/archive-v0/xyz/lib/python3.12/site-packages/ruff-0.6.9.dist-info/METADATA": "",
+ ".local/share/pipx/.cache/abc/lib/python3.11/site-packages/black-24.8.0.dist-info/METADATA": "",
+ "go/pkg/mod/cache/download/golang.org/x/tools/@v/v0.24.0.info": "{}",
+ ".cache/pnpm/dlx/hash1/1700000000/node_modules/create-next-app/package.json": JSON.stringify({ version: "14.2.5" }),
+ ".cache/deno/npm/registry.npmjs.org/chalk/5.3.0/package.json": "{}",
+ });
+ const opts = { home, platform: "linux", env: {}, registryFallback: false };
+ const r = (runner, pkg, requested = null) => ephemeral.resolveEphemeral({ tool_call_id: "c", runner, package: pkg, requested }, opts);
+ assert.deepEqual(await r("npx", "cowsay", "1.6.0"), { tool_call_id: "c", runner: "npx", package: "cowsay", requested: "1.6.0", version: "1.6.0", resolved: "exact", source: null });
+ assert.equal((await r("npx", "cowsay")).source, "npx_cache");
+ assert.equal((await r("npx", "@scope/tool", "latest")).version, "2.3.4");
+ assert.deepEqual([(await r("bunx", "prettier")).version, (await r("bunx", "prettier")).source], ["3.3.3", "bun_cache"]);
+ assert.deepEqual([(await r("uvx", "ruff")).version, (await r("uvx", "ruff")).source], ["0.6.9", "uv_cache"]);
+ assert.deepEqual([(await r("pipx run", "black")).version, (await r("pipx run", "black")).source], ["24.8.0", "pipx_venv"]);
+ assert.deepEqual([(await r("go run", "golang.org/x/tools/cmd/stringer", "latest")).version, (await r("go run", "golang.org/x/tools/cmd/stringer", "latest")).source], ["v0.24.0", "go_modcache"]);
+ assert.equal((await r("pnpm dlx", "create-next-app")).version, "14.2.5");
+ assert.equal((await r("deno run", "chalk")).version, "5.3.0");
+ assert.equal((await r("uvx", "not-cached")).resolved, "unresolved");
+ const calls = [];
+ const viaRegistry = await ephemeral.resolveEphemeral({ tool_call_id: "c", runner: "npx", package: "left-pad", requested: null }, {
+ home, platform: "linux", env: {}, resolve: () => "/usr/bin/npm", run: fakeRun({ npm: ok("1.3.0\n") }, calls),
+ });
+ assert.deepEqual([viaRegistry.version, viaRegistry.resolved, viaRegistry.source], ["1.3.0", "registry_latest", "registry"]);
+ assert.deepEqual(calls[0].args, ["view", "left-pad", "version"]);
+ const cached = await ephemeral.resolveEphemeral({ tool_call_id: "c", runner: "npx", package: "cowsay", requested: null }, { home, platform: "linux", env: {}, run: () => assert.fail("no registry call on a cache hit") });
+ assert.equal(cached.resolved, "cache");
+ assert.equal((await ephemeral.resolveEphemeral({ tool_call_id: "c", runner: "npx", package: "bad name; rm -rf /", requested: null }, { home, run: () => assert.fail("never") })).resolved, "unresolved");
+});
+
+// --- #20 network -------------------------------------------------------------------------------
+
+test("#20 parsing: tool shells, lsof connections, hostnames in a command (credentials never kept)", () => {
+ assert.equal(network.shellCommandOf(["/bin/bash", "-c", "curl https://x.dev"]), "curl https://x.dev");
+ assert.equal(network.shellCommandOf(["/usr/bin/zsh", "-lc", "ls"]), "ls");
+ assert.equal(network.shellCommandOf(["C:\\Windows\\System32\\cmd.exe", "/d", "/s", "/c", "dir"]), "dir");
+ assert.equal(network.shellCommandOf(["node", "-c", "x"]), null);
+ assert.deepEqual(network.splitArgs("/bin/bash -c curl -s 'https://a.dev' | jq ."), ["/bin/bash", "-c", "curl -s 'https://a.dev' | jq ."]);
+ assert.deepEqual(network.parseLsofConnections("p12\nn10.0.0.2:50000->140.82.112.3:443\nn*:3000\n"), [{ pid: 12, ip: "140.82.112.3", port: 443 }]);
+ assert.deepEqual(network.hostnamesInCommand(`curl -H "Authorization: Bearer ${GH_TOKEN}" https://user:${PASSWORD}@api.github.com/repos && git clone [email protected]:acme/x.git && cat main.py && ping example.org`), ["api.github.com", "gitlab.com", "example.org"]);
+});
+
+test("#20 attribution: a tool shell's connections go to the call that ran its command; unmatched shells to the turn; no IPs, no secrets", async () => {
+ const resolver = { lookup: async (host) => (host === "api.github.com" ? ["140.82.112.3"] : []), reverse: async (ip) => (ip === "151.101.1.69" ? ["dualstack.n.sni.global.fastly.net"] : []) };
+ const now = Date.now();
+ const command = `curl -H "Authorization: Bearer ${GH_TOKEN}" https://api.github.com/user`;
+ const roots = [
+ { pid: 10, command, firstSeen: now, connections: new Map([["140.82.112.3|443", { ip: "140.82.112.3", port: 443, first: now }], ["127.0.0.1|5432", { ip: "127.0.0.1", port: 5432, first: now }]]) },
+ { pid: 11, command: "some-daemon", firstSeen: now, connections: new Map([["151.101.1.69|443", { ip: "151.101.1.69", port: 443, first: now }]]) },
+ ];
+ const calls = [shellCall("call-net", command, "/proj", now - 100)];
+ const events = await network.attributeConnections(roots, calls, { turn: 2, method: "proc", pollMs: 250, resolver });
+ assert.equal(events.length, 2);
+ const call = events.find((e) => e.scope === "call");
+ assert.equal(call.tool_call_id, "call-net");
+ assert.deepEqual(call.connections.map((c) => [c.host, c.port, c.address_class, c.resolved_by]), [["api.github.com", 443, "public", "command"], ["localhost", 5432, "loopback", "loopback"]]);
+ const turn = events.find((e) => e.scope === "turn");
+ assert.equal(turn.tool_call_id, null);
+ assert.deepEqual(turn.connections.map((c) => [c.host, c.resolved_by]), [["dualstack.n.sni.global.fastly.net", "reverse"]]);
+ const scrubbed = SCRUB.json(events);
+ assertNoSecrets(scrubbed);
+ assert.ok(!JSON.stringify(scrubbed).includes("140.82.112.3"));
+});
+
+test.skipIf(process.platform !== "linux")("#20 live (Linux /proc): a bash call that connects to a local server is seen and attributed to its call", async () => {
+ const server = net.createServer((socket) => setTimeout(() => socket.end(), 1_500)).listen(0, "127.0.0.1");
+ await new Promise((resolve) => server.once("listening", resolve));
+ const port = server.address().port;
+ const command = `node -e "const s=require('net').connect(${port},'127.0.0.1');s.on('data',()=>{});s.on('close',()=>process.exit(0))"`;
+ const observer = new network.NetworkObserver({ sampler: network.linuxSampler("/proc", 100) });
+ observer.start();
+ const started = Date.now();
+ await new Promise((resolve) => setTimeout(resolve, 150)); // the turn's first sample notes what already runs
+ const child = spawn("/bin/bash", ["-c", command], { stdio: "ignore" });
+ await new Promise((resolve) => child.on("exit", resolve));
+ const roots = await observer.stop();
+ server.close();
+ const events = await network.attributeConnections(roots, [shellCall("call-live", command, "/proj", started)], { turn: 1, method: "proc", pollMs: 100 });
+ const event = events.find((e) => e.tool_call_id === "call-live");
+ assert.ok(event, `attributed: ${JSON.stringify(events)}`);
+ assert.deepEqual(event.connections.map((c) => [c.host, c.port, c.address_class]), [["localhost", port, "loopback"]]);
+ assert.ok(observer.samples >= 1);
+});
+
+// --- the uploader end to end ----------------------------------------------------------------------
+
+function traceEventsOf(envelopes) {
+ const out = [];
+ for (const envelope of envelopes) {
+ // Schema 2 carries the events in __omnirush__/trace.json (and mirrors them in `trace`).
+ const file = (envelope.files ?? []).find((entry) => entry.path === "__omnirush__/trace.json");
+ out.push(...(file ? JSON.parse(file.content).events ?? [] : envelope.trace ?? []));
+ }
+ return out;
+}
+
+async function runSession(contextOptions) {
+ const root = write(tmp("e2e"), { "package.json": "{}", "src/a.js": "1\n" });
+ const stateDir = tmp("e2e-state");
+ const envelopes = [];
+ const touched = [];
+ const syncer = new uploader.SessionUploader({
+ stateDir,
+ fallbackScanMs: 60_000,
+ capabilities: async () => ({ schema_versions: [2], canonical_trace: false }),
+ upload: async (_sessionId, compressed) => {
+ envelopes.push(JSON.parse(zlib.zstdDecompressSync(Buffer.from(compressed)).toString("utf8")));
+ return new Response("{}", { status: 201 });
+ },
+ onPathTouched: (_sessionId, p) => touched.push(p),
+ context: { sections: { system_packages: false, services: false, pm_config: false }, sampler: null, ephemeral: { registryFallback: false }, env: {}, ...contextOptions },
+ });
+ const sessionId = "01a0dcd2-d8ee-7222-80eb-240063770431";
+ syncer.startSession(sessionId, "ws", root);
+ syncer.captureSnapshot(sessionId, "prompt");
+ syncer.recordTrace(sessionId, "turn.messages", { messages: [{ info: { role: "assistant" }, parts: [
+ { type: "tool", tool: "bash", callID: "call-e2e", state: { status: "completed", input: { command: `npx -y [email protected] "token ${GH_TOKEN}"` }, time: { start: Date.now(), end: Date.now() + 1 } } },
+ ] }] });
+ syncer.captureSnapshot(sessionId, "turn_completed");
+ // A loaded machine may take longer than the 1 s the session end waits for context.
+ await syncer.context?.settled(sessionId, 30_000);
+ syncer.finishSession(sessionId);
+ await syncer.idle(sessionId);
+ await syncer.stop();
+ return { events: traceEventsOf(envelopes), envelopes, touched };
+}
+
+test.skipIf(!hasZstd)("uploader: the session's trace carries the context events, scrubbed; OMNIRUSH_CAPTURE_CONTEXT=0 sends none", async () => {
+ const { events } = await runSession({});
+ const types = events.map((event) => event.type).filter((type) => type.startsWith("context."));
+ assert.ok(types.includes("context.environment"), types.join(","));
+ assert.equal(types.filter((type) => type === "context.processes").length, 2, "session start and turn start");
+ assert.ok(types.includes("context.ephemeral_tool"));
+ const environment = events.find((event) => event.type === "context.environment").data;
+ assert.equal(environment.schema, 1);
+ assert.equal(environment.setup.client, "gui");
+ assert.ok("shell_aliases" in environment && !("system_packages" in environment));
+ const tool = events.find((event) => event.type === "context.ephemeral_tool").data;
+ assert.deepEqual([tool.tool_call_id, tool.package, tool.version, tool.resolved], ["call-e2e", "cowsay", "1.6.0", "exact"]);
+ assertNoSecrets(events);
+ assert.ok(!JSON.stringify(events.filter((e) => e.type.startsWith("context."))).includes(os.homedir() + path.sep), "no home path in context events");
+
+ const off = await runSession({ env: { OMNIRUSH_CAPTURE_CONTEXT: "0" } });
+ assert.deepEqual(off.events.filter((event) => event.type.startsWith("context.")), []);
+ assert.ok(off.events.length > 0, "the rest of the trace is unchanged");
+});
+
+test("CLI/desktop parity: the context modules match PARITY.sha256 (the same list ships in the CLI)", async () => {
+ const { createHash } = await import("node:crypto");
+ const contextDir = path.join(import.meta.dir, "context");
+ const lines = fs.readFileSync(path.join(contextDir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));
+ const listed = new Map(lines.map((line) => { const [hash, name] = line.split(/\s+/); return [name, hash]; }));
+ const files = fs.readdirSync(contextDir).filter((name) => name.endsWith(".ts")).sort();
+ assert.deepEqual([...listed.keys()].sort(), files);
+ for (const name of files) assert.equal(createHash("sha256").update(fs.readFileSync(path.join(contextDir, name))).digest("hex"), listed.get(name), `${name} changed: port it to the CLI and update PARITY.sha256 in both`);
+});
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index dd85aa43..2fc8782a 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -8,6 +8,7 @@
* same behaviour. Every call takes and returns plain data, so the same calls
* cross the thread boundary unchanged.
*/
+import type { ContextOptions } from "./context/index.js";
import { readPromptAttachments, promptBodyForTrace, v2PromptBodyForTrace } from "./session-upload-attachments.js";
import {
createSessionObservers,
@@ -65,6 +66,8 @@ export type CaptureHostOptions = {
fetch?: (input: string, init?: RequestInit) => Promise<Response>;
gatewayUrl?: string;
accessToken?: string;
+ /** Capture context (context/): false turns it off, an object overrides its options. */
+ context?: false | Partial<ContextOptions>;
};
archive: Pick<SessionArchiverOptions, "request" | "refreshAccessToken" | "fetch" | "gatewayUrl" | "accessToken" | "folderGate"> & {
/** Archiving is on for this device (OMNIRUSH_ARCHIVE_ENABLED) and an account is connected. */
@@ -108,6 +111,8 @@ export class CaptureHost {
appVersion: options.appVersion,
engineVersion: options.engineVersion,
log: options.log,
+ // Capture context (context/); OMNIRUSH_CAPTURE_CONTEXT=0 turns it off.
+ context: options.sessionUploader?.context ?? {},
...(options.onSessionClosed ? { onSessionClosed: options.onSessionClosed } : {}),
// The touched-files archive hears of every path a session touches, here on the same thread.
onPathTouched: (sessionId, path) => this.archive.pathTouched(sessionId, path),
diff --git a/apps/server/src/context/PARITY.sha256 b/apps/server/src/context/PARITY.sha256
new file mode 100644
index 00000000..ac4bad0a
--- /dev/null
+++ b/apps/server/src/context/PARITY.sha256
@@ -0,0 +1,15 @@
+# The capture-context modules are the same files in omnirush-cli (assets/extensions/omnirush/capture/context/)
+# and omnirush-gui (apps/server/src/context/). A change to one must be ported to the other and this list updated in both.
+67b853751c5a32e0fc62d626837fa4be571362b26e11a6d23544db8bf8cce76c commands.ts
+e13f86577014b52affc4c2336630eedcac277b974939c6741119a62b7fda439b ephemeral.ts
+af6d1f36cabedab4239e3fa2d9dc025955f708a1df2278b6a9dc463d6f2ba098 exec.ts
+ba6537419d99dda42bd2d685767adfc3c16e020cb5f84b7366d7cfb674a8c6b0 index.ts
+b4460fb7279e273fbb28d42b8636d598793e4b07ff8beb7d57eb127c897136c8 network.ts
+0826cb0f15b4ac712ff0a8c0e974fe07a3527df4b2d0c55074340b4fba899f75 outside.ts
+dd4c7925b536bf48872fcad9e4659c5d39dcc0658adc517b5c44b3e5c38a6bcc pm-config.ts
+c29dffc857ae3dfb258247fbadd30deccef6a2cf2883605145d7c6983cbc2e53 privacy.ts
+d21e8ba20f64148c69d07363d23f8ab27524ed61abbfc9dfdb8634d3734f5560 processes.ts
+04e135b3fdab1e8427c7279672f9896a65ff1fd8c5790d2ad3b417850a13e662 services.ts
+92030e186fcd58a6acaeb9acbaac67c8003d12d0c2eb9e29113faa701885b0eb setup.ts
+d51d434283f757f0ed45bb6996a74fb5bf9e1d56f34146e99df3c392cde5ea19 shell-aliases.ts
+5af6e3e4d75e62e0dfc0fee53c583f34463871f9a4d5693e4bc13f688ed2142e system-packages.ts
diff --git a/apps/server/src/context/commands.ts b/apps/server/src/context/commands.ts
new file mode 100644
index 00000000..c197ea62
--- /dev/null
+++ b/apps/server/src/context/commands.ts
@@ -0,0 +1,486 @@
+// The tool calls of a turn (from the engine's messages) and what a shell
+// command does to the file system, by a light parse of the command text:
+// the folders it changes into or creates (cd, mkdir, git clone, npm create,
+// cargo new, …), the files it writes (redirections, tee, cp/mv targets,
+// curl -o, …), the scripts it runs (bash x.sh, python x.py, ./x, source x),
+// the paths it names, and the on-the-fly tools it runs (npx, uvx, …).
+// Nothing is executed; the parse errs on the side of naming too much (each
+// path is checked on disk later).
+
+import { basename, isAbsolute, join, resolve } from "node:path";
+
+import { packageOfCommand } from "./setup.js";
+
+export type ToolCall = {
+ callId: string | null;
+ tool: string;
+ input: Record<string, unknown>;
+ status: string | null;
+ start: number | null;
+ end: number | null;
+ /** The shell command of a shell tool. */
+ command: string | null;
+ /** The directory the tool ran in (its workdir input), absolute. */
+ cwd: string;
+};
+
+const SHELL_TOOLS = new Set(["bash", "shell", "sh", "zsh", "run_command", "run_shell_command", "exec", "terminal", "local_shell", "powershell", "cmd"]);
+const READ_TOOLS = new Set(["read", "view", "cat", "file_read", "read_file", "open", "read_many_files", "readfile", "grep", "glob", "list", "ls"]);
+const WRITE_TOOLS = new Set(["write", "edit", "multiedit", "multi_edit", "create", "file_write", "write_file", "patch", "apply_patch", "str_replace", "str_replace_editor", "notebook_edit", "notebookedit", "replace"]);
+const PATH_KEYS = ["filePath", "file_path", "filepath", "path", "filename", "notebook_path", "absolute_path"];
+const MAX_COMMAND_CHARS = 64 * 1024;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function toolKind(tool: string): "shell" | "read" | "write" | "other" {
+ const name = tool.trim().toLowerCase().split(/[.:/]/).at(-1) ?? "";
+ if (SHELL_TOOLS.has(name)) return "shell";
+ if (READ_TOOLS.has(name)) return "read";
+ if (WRITE_TOOLS.has(name)) return "write";
+ return "other";
+}
+
+export function expandHome(path: string, home: string | null): string | null {
+ if (path === "~") return home;
+ if (path.startsWith("~/") || path.startsWith("~\\")) return home ? join(home, path.slice(2)) : null;
+ if (path.startsWith("~")) return null;
+ return path;
+}
+
+/** The tool calls of a turn's messages, in the order they started. */
+export function toolCallsOf(messages: unknown, root: string, home: string | null): ToolCall[] {
+ const list = Array.isArray(messages) ? messages : isRecord(messages) && Array.isArray(messages.messages) ? messages.messages : [];
+ const out: ToolCall[] = [];
+ for (const message of list) {
+ if (!isRecord(message) || !Array.isArray(message.parts)) continue;
+ for (const part of message.parts) {
+ if (!isRecord(part) || part.type !== "tool") continue;
+ const tool = typeof part.tool === "string" ? part.tool : typeof part.name === "string" ? part.name : "";
+ if (!tool) continue;
+ const state = isRecord(part.state) ? part.state : {};
+ const input = isRecord(state.input) ? state.input : isRecord(part.input) ? part.input : {};
+ const time = isRecord(state.time) ? state.time : {};
+ const workdir = ["workdir", "cwd", "directory", "working_directory"].map((key) => input[key]).find((value) => typeof value === "string" && value.trim()) as string | undefined;
+ const expanded = workdir ? expandHome(workdir.trim(), home) : null;
+ const rawCommand = input.command ?? input.cmd ?? input.script;
+ const command = typeof rawCommand === "string" ? rawCommand : Array.isArray(rawCommand) && rawCommand.every((item) => typeof item === "string") ? rawCommand.join(" ") : null;
+ out.push({
+ callId: typeof part.callID === "string" ? part.callID : typeof part.callId === "string" ? part.callId : typeof part.id === "string" ? part.id : null,
+ tool,
+ input,
+ status: typeof state.status === "string" ? state.status : null,
+ start: typeof time.start === "number" ? time.start : null,
+ end: typeof time.end === "number" ? time.end : null,
+ command: toolKind(tool) === "shell" ? command : null,
+ cwd: expanded ? resolve(root, expanded) : root,
+ });
+ }
+ }
+ return out.map((call, index) => ({ call, index })).sort((a, b) => (a.call.start ?? 0) - (b.call.start ?? 0) || a.index - b.index).map(({ call }) => call);
+}
+
+/** File paths a read or write tool names (absolute). */
+export function toolPaths(call: ToolCall, home: string | null): string[] {
+ const out: string[] = [];
+ const add = (value: unknown) => {
+ if (typeof value !== "string" || !value.trim() || value.includes("\n") || value.length > 4096) return;
+ const expanded = expandHome(value.trim(), home);
+ if (expanded) out.push(resolve(call.cwd, expanded));
+ };
+ for (const key of PATH_KEYS) add(call.input[key]);
+ if (Array.isArray(call.input.paths)) for (const value of call.input.paths) add(value);
+ for (const key of ["patchText", "patch"]) {
+ const body = call.input[key];
+ if (typeof body === "string") for (const match of body.matchAll(/^\*\*\* (?:(?:Update|Add) File|Move to):[ \t]*(.+)$/gm)) add(match[1]);
+ }
+ return out;
+}
+
+// --- shell parsing --------------------------------------------------------------------
+
+export type Token = { word: string } | { op: string };
+
+/** Words and control/redirection operators; quotes and backslashes honoured; heredoc bodies skipped. */
+export function tokenize(command: string): Token[] {
+ const text = command.length > MAX_COMMAND_CHARS ? command.slice(0, MAX_COMMAND_CHARS) : command;
+ const tokens: Token[] = [];
+ let word = "";
+ let started = false;
+ let quote: "'" | '"' | null = null;
+ const heredocs: string[] = [];
+ const end = () => {
+ if (started) tokens.push({ word });
+ word = "";
+ started = false;
+ };
+ for (let i = 0; i < text.length; i += 1) {
+ const char = text[i]!;
+ if (quote === "'") {
+ if (char === "'") quote = null;
+ else word += char;
+ continue;
+ }
+ if (quote === '"') {
+ if (char === '"') quote = null;
+ else if (char === "\\" && '"\\$`'.includes(text[i + 1] ?? "")) word += text[++i]!;
+ else word += char;
+ continue;
+ }
+ if (char === "'" || char === '"') {
+ quote = char;
+ started = true;
+ continue;
+ }
+ if (char === "\\" && text[i + 1] !== undefined && text[i + 1] !== "\n") {
+ word += text[++i]!;
+ started = true;
+ continue;
+ }
+ if (char === "\n") {
+ end();
+ tokens.push({ op: "\n" });
+ // Heredoc bodies: skip lines until each delimiter.
+ while (heredocs.length > 0) {
+ const delimiter = heredocs.shift()!;
+ let next = text.indexOf("\n", i + 1);
+ while (true) {
+ const line = text.slice(i + 1, next < 0 ? undefined : next);
+ i = next < 0 ? text.length : next;
+ if (line.trim() === delimiter || next < 0) break;
+ next = text.indexOf("\n", i + 1);
+ }
+ }
+ continue;
+ }
+ if (char === "#" && !started) {
+ while (i + 1 < text.length && text[i + 1] !== "\n") i += 1;
+ continue;
+ }
+ if (/\s/.test(char)) {
+ end();
+ continue;
+ }
+ const three = text.slice(i, i + 3);
+ const two = text.slice(i, i + 2);
+ if (two === "<<" && three !== "<<<") {
+ end();
+ let j = i + 2;
+ if (text[j] === "-") j += 1;
+ while (text[j] === " ") j += 1;
+ const match = /^(['"]?)([\w.-]+)\1/.exec(text.slice(j));
+ if (match) {
+ heredocs.push(match[2]!);
+ i = j + match[0].length - 1;
+ } else {
+ i += 1;
+ }
+ tokens.push({ op: "<<" });
+ continue;
+ }
+ const ops = ["&>>", "2>>", "&&", "||", ">>", "2>", "&>", ">|", ";", "|", "&", ">", "<", "(", ")", "`"];
+ const op = ops.find((candidate) => text.startsWith(candidate, i));
+ if (op && !(op === "2>" && started) && !(op === "2>>" && started)) {
+ end();
+ if (op === "&" && text[i + 1] === ">") continue;
+ tokens.push({ op });
+ i += op.length - 1;
+ continue;
+ }
+ word += char;
+ started = true;
+ }
+ end();
+ return tokens;
+}
+
+const SEPARATORS = new Set([";", "&&", "||", "|", "&", "\n", "(", ")", "`"]);
+const REDIRECT_WRITE = new Set([">", ">>", "2>", "2>>", "&>", "&>>", ">|"]);
+
+/** Simple commands: words, the files they redirect into, and the operator before each. */
+export function simpleCommands(command: string): Array<{ words: string[]; writes: string[]; reads: string[]; after: string | null }> {
+ const out: Array<{ words: string[]; writes: string[]; reads: string[]; after: string | null }> = [];
+ let current = { words: [] as string[], writes: [] as string[], reads: [] as string[], after: null as string | null };
+ let pending: "write" | "read" | "skip" | null = null;
+ for (const token of tokenize(command)) {
+ if ("op" in token) {
+ if (SEPARATORS.has(token.op)) {
+ if (current.words.length || current.writes.length) out.push(current);
+ current = { words: [], writes: [], reads: [], after: token.op };
+ pending = null;
+ } else if (REDIRECT_WRITE.has(token.op)) pending = "write";
+ else if (token.op === "<") pending = "read";
+ else if (token.op === "<<") pending = null;
+ continue;
+ }
+ if (pending) {
+ if (pending === "write" && !/^&\d$|^\/dev\//.test(token.word)) current.writes.push(token.word);
+ if (pending === "read" && !token.word.startsWith("/dev/")) current.reads.push(token.word);
+ pending = null;
+ continue;
+ }
+ // Leading assignments (FOO=bar cmd) are not the command.
+ if (current.words.length === 0 && /^[A-Za-z_][\w]*=/.test(token.word)) continue;
+ current.words.push(token.word);
+ }
+ if (current.words.length || current.writes.length) out.push(current);
+ return out;
+}
+
+export type FolderVia = "cd" | "mkdir" | "git clone" | "create" | "cargo new" | "init" | "copy" | "extract" | "workdir";
+export type CommandEffects = {
+ /** Folders the command changes into (`cd`) or creates. */
+ folders: Array<{ path: string; via: FolderVia; created: boolean }>;
+ /** Files it writes or modifies. */
+ writes: string[];
+ /** Scripts it runs (interpreted or executed by path). */
+ executed: string[];
+ /** Every path-like word, resolved (read/used candidates). */
+ named: string[];
+ /** On-the-fly tools. */
+ ephemeral: Array<{ runner: string; package: string; requested: string | null }>;
+};
+
+const INTERPRETERS = new Set(["bash", "sh", "zsh", "dash", "ksh", "fish", "python", "python2", "python3", "node", "nodejs", "ruby", "perl", "php", "tsx", "ts-node", "pwsh", "powershell", "Rscript", "lua", "osascript", "groovy"]);
+const VALUE_FLAGS: Record<string, Set<string>> = {
+ git: new Set(["-b", "--branch", "--depth", "-o", "--origin", "-c", "--config", "--reference", "--filter", "-j", "--jobs", "--template", "--separate-git-dir", "-u", "--upload-pack", "--shallow-since", "--shallow-exclude"]),
+};
+
+function isPathLike(word: string): boolean {
+ if (!word || word.length > 4096 || word.includes("://") || /[*?{}$]/.test(word) || word.startsWith("-")) return false;
+ return /^(?:\/|~[\\/]|~$|\.{1,2}[\\/]|[A-Za-z]:[\\/])/.test(word) || word.includes("/") || /^[^\\/=:@]+\.[A-Za-z0-9]{1,12}$/.test(word);
+}
+
+/** The folder name `git clone <url>` makes when no directory is given. */
+export function cloneDirName(url: string): string | null {
+ const trimmed = url.replace(/[\\/]+$/, "").replace(/\.git$/, "");
+ const name = trimmed.split(/[\\/:]/).at(-1);
+ return name && name !== "." && name !== ".." ? name : null;
+}
+
+/**
+ * What a shell command does to the file system, resolved against `cwd`
+ * (which `cd` moves for the rest of an `&&`/`;` chain).
+ */
+export function commandEffects(command: string, cwd: string, home: string | null): CommandEffects {
+ const effects: CommandEffects = { folders: [], writes: [], executed: [], named: [], ephemeral: [] };
+ let dir = cwd;
+ const abs = (value: string): string | null => {
+ const expanded = expandHome(value, home);
+ if (!expanded || expanded.includes("\0")) return null;
+ return isAbsolute(expanded) ? resolve(expanded) : resolve(dir, expanded);
+ };
+ const folder = (value: string | undefined, via: FolderVia, created: boolean) => {
+ if (!value || value.startsWith("-")) return;
+ const path = abs(value);
+ if (path) effects.folders.push({ path, via, created });
+ };
+ const nonFlags = (words: string[], from: number, valueFlags: Set<string> = new Set()) => {
+ const out: string[] = [];
+ for (let i = from; i < words.length; i += 1) {
+ const word = words[i]!;
+ if (word === "--") continue;
+ if (word.startsWith("-")) {
+ if (valueFlags.has(word)) i += 1;
+ continue;
+ }
+ out.push(word);
+ }
+ return out;
+ };
+ for (const simple of simpleCommands(command)) {
+ for (const target of simple.writes) {
+ const path = abs(target);
+ if (path) effects.writes.push(path);
+ }
+ for (const source of simple.reads) {
+ const path = abs(source);
+ if (path) effects.named.push(path);
+ }
+ let words = simple.words;
+ // sudo/env/time/nohup/exec prefixes.
+ while (words.length > 1 && ["sudo", "env", "time", "nohup", "exec", "command", "nice", "xargs"].includes(words[0]!)) {
+ words = words.slice(1);
+ while (words.length > 1 && (words[0]!.startsWith("-") || /^[A-Za-z_]\w*=/.test(words[0]!))) words = words.slice(1);
+ }
+ if (words.length === 0) continue;
+ const head = basename(words[0]!).replace(/\.(?:exe|cmd)$/i, "");
+ for (const word of words.slice(1)) {
+ const value = word.startsWith("-") && word.includes("=") ? word.slice(word.indexOf("=") + 1) : word;
+ if (isPathLike(value)) {
+ const path = abs(value);
+ if (path) effects.named.push(path);
+ }
+ }
+ const spec = packageOfCommand(words);
+ if (spec) {
+ const runner = words[0] && ["pnpm", "yarn", "npm", "bun", "pipx", "uv"].includes(head) ? `${head} ${words[1]}` : head;
+ effects.ephemeral.push({ runner: runner === "npm exec" ? "npx" : runner === "uv tool" ? "uvx" : runner, package: spec.package, requested: spec.version });
+ }
+ switch (head) {
+ case "cd":
+ case "pushd":
+ case "Set-Location":
+ case "sl": {
+ const target = nonFlags(words, 1)[0];
+ const path = target ? abs(target) : home;
+ if (path) {
+ effects.folders.push({ path, via: "cd", created: false });
+ dir = path;
+ }
+ break;
+ }
+ case "mkdir":
+ case "md":
+ case "New-Item":
+ for (const target of nonFlags(words, 1, new Set(["-m", "--mode", "-ItemType", "-Path"]))) folder(target, "mkdir", true);
+ break;
+ case "git": {
+ const sub = nonFlags(words, 1, new Set(["-C", "-c"]));
+ if (sub[0] === "clone") {
+ const args = nonFlags(words, words.indexOf("clone") + 1, VALUE_FLAGS.git);
+ const target = args[1] ?? (args[0] ? cloneDirName(args[0]) ?? undefined : undefined);
+ folder(target, "git clone", true);
+ } else if (sub[0] === "init" && sub[1]) folder(sub[1], "init", true);
+ break;
+ }
+ case "npm":
+ case "pnpm":
+ case "yarn":
+ case "bun": {
+ const sub = words[1];
+ if (sub === "dlx") {
+ const args = nonFlags(words, 2);
+ if (args[0] && /(?:^|\/)create-/.test(args[0])) folder(args[1], "create", true);
+ } else if (sub === "create" || (sub === "init" && words[2] && !words[2].startsWith("-"))) {
+ const args = nonFlags(words, 2);
+ folder(args[1], "create", true);
+ }
+ break;
+ }
+ case "npx":
+ case "pnpx":
+ case "bunx": {
+ const args = nonFlags(words, 1);
+ if (args[0] && /(?:^|\/)create-/.test(args[0])) folder(args[1], "create", true);
+ break;
+ }
+ case "cargo":
+ if (words[1] === "new" || words[1] === "init") folder(nonFlags(words, 2, new Set(["--name", "--vcs", "--edition"]))[0], "cargo new", true);
+ break;
+ case "uv":
+ case "poetry":
+ if (words[1] === "init" || words[1] === "new") folder(nonFlags(words, 2)[0], "init", true);
+ break;
+ case "rails":
+ case "django-admin":
+ if (words[1] === "new" || words[1] === "startproject") folder(nonFlags(words, 2)[head === "rails" ? 0 : 1] ?? nonFlags(words, 2)[0], "create", true);
+ break;
+ case "composer":
+ if (words[1] === "create-project") folder(nonFlags(words, 2)[1], "create", true);
+ break;
+ case "dotnet": {
+ const at = words.findIndex((word) => word === "-o" || word === "--output");
+ if (words[1] === "new" && at > 0) folder(words[at + 1], "create", true);
+ break;
+ }
+ case "cp":
+ case "rsync":
+ case "Copy-Item": {
+ const args = nonFlags(words, 1, new Set(["-t", "--target-directory", "-e"]));
+ const target = args.at(-1);
+ if (target && args.length >= 2) {
+ const recursive = words.some((word) => /^-[a-zA-Z]*[rRa]/.test(word) || word === "--recursive" || word === "-Recurse") || head === "rsync";
+ if (recursive) folder(target, "copy", true);
+ else {
+ const path = abs(target);
+ if (path) effects.writes.push(path);
+ }
+ }
+ break;
+ }
+ case "mv":
+ case "Move-Item": {
+ const args = nonFlags(words, 1);
+ const path = args.length >= 2 ? abs(args.at(-1)!) : null;
+ if (path) effects.writes.push(path);
+ break;
+ }
+ case "tee":
+ case "touch":
+ case "Out-File":
+ case "Set-Content":
+ for (const target of nonFlags(words, 1)) {
+ const path = abs(target);
+ if (path) effects.writes.push(path);
+ }
+ break;
+ case "sed":
+ case "perl":
+ if (words.some((word) => /^-[a-zA-Z]*i/.test(word))) {
+ const target = nonFlags(words, 1, new Set(["-e", "-f"])).at(-1);
+ const path = target ? abs(target) : null;
+ if (path) effects.writes.push(path);
+ }
+ break;
+ case "curl":
+ case "wget": {
+ const at = words.findIndex((word) => word === "-o" || word === "--output" || word === "-O" && head === "wget" || word === "--output-document");
+ const value = at > 0 ? words[at + 1] : words.find((word) => /^--output(?:-document)?=/.test(word))?.split("=").slice(1).join("=");
+ const path = value && value !== "-" ? abs(value) : null;
+ if (path) effects.writes.push(path);
+ break;
+ }
+ case "tar": {
+ const at = words.findIndex((word) => word === "-C" || word === "--directory");
+ if (at > 0 && words.some((word) => /^-?[a-zA-Z]*x/.test(word) || word === "--extract")) folder(words[at + 1], "extract", true);
+ break;
+ }
+ case "unzip": {
+ const at = words.indexOf("-d");
+ if (at > 0) folder(words[at + 1], "extract", true);
+ break;
+ }
+ case "source":
+ case ".": {
+ const path = words[1] ? abs(words[1]) : null;
+ if (path) effects.executed.push(path);
+ break;
+ }
+ default:
+ break;
+ }
+ // Scripts run by an interpreter or by path.
+ if (INTERPRETERS.has(head) || /^python\d+(?:\.\d+)*$/.test(head)) {
+ const args = nonFlags(words, 1, new Set(["-m", "-c", "-e", "--eval", "-r", "--require", "-W", "-X", "--import", "--loader"]));
+ if (!words.includes("-c") && !words.includes("-m") && !words.includes("-e") && !words.includes("--eval") && args[0]) {
+ const path = abs(args[0]);
+ if (path) effects.executed.push(path);
+ }
+ } else if (/[\\/]/.test(words[0]!) && !words[0]!.endsWith("/")) {
+ const path = abs(words[0]!);
+ if (path) effects.executed.push(path);
+ } else if ((head === "deno" || head === "bun") && words[1] === "run" && words[2] && isPathLike(words[2])) {
+ const path = abs(words[2]);
+ if (path) effects.executed.push(path);
+ }
+ // Deno npm:/jsr: specifiers and `go run pkg@version` are on-the-fly tools too.
+ if (head === "deno") {
+ const spec = words.find((word) => /^(?:npm|jsr):/.test(word));
+ if (spec) {
+ const body = spec.replace(/^(?:npm|jsr):/, "");
+ const at = body.lastIndexOf("@");
+ effects.ephemeral.push({ runner: "deno run", package: `${spec.startsWith("jsr:") ? "jsr:" : ""}${at > 0 ? body.slice(0, at) : body}`, requested: at > 0 ? body.slice(at + 1).split("/")[0] || null : null });
+ }
+ }
+ if (head === "go" && words[1] === "run") {
+ const target = nonFlags(words, 2).find((word) => /^[\w.-]+\.[\w-]+\/[^@\s]+@\S+$/.test(word));
+ if (target) {
+ const at = target.lastIndexOf("@");
+ effects.ephemeral.push({ runner: "go run", package: target.slice(0, at), requested: target.slice(at + 1) });
+ }
+ }
+ }
+ return effects;
+}
diff --git a/apps/server/src/context/ephemeral.ts b/apps/server/src/context/ephemeral.ts
new file mode 100644
index 00000000..5ae1b0a8
--- /dev/null
+++ b/apps/server/src/context/ephemeral.ts
@@ -0,0 +1,267 @@
+// #22 On-the-fly tools (npx, pnpm dlx, yarn dlx, bunx, uvx, pipx run,
+// go run pkg@version, deno run npm:/jsr:): the package and the exact
+// version that ran. An exact requested version is taken as is; otherwise
+// the version is read from the runner's cache after the call (the npx
+// cache, pnpm's dlx cache, bun's install cache, uv's cache and tool
+// environments, pipx's run cache, the go module cache, deno's npm cache).
+// Only when no cache has it, `npm view <pkg> version` is asked once for an
+// npm package (marked `registry_latest`); anything else stays unresolved.
+
+import { readdir, readFile, stat } from "node:fs/promises";
+import { join } from "node:path";
+
+import { runTool, type Runner } from "./exec.js";
+
+export type EphemeralTool = {
+ tool_call_id: string | null;
+ runner: string;
+ package: string;
+ requested: string | null;
+ version: string | null;
+ resolved: "exact" | "cache" | "registry_latest" | "unresolved";
+ source: "npx_cache" | "pnpm_cache" | "bun_cache" | "uv_cache" | "pipx_venv" | "go_modcache" | "deno_cache" | "registry" | null;
+};
+
+const EXACT = /^v?\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/;
+const NPM_NAME = /^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/i;
+const PY_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
+const MAX_SCAN_DIRS = 2_000;
+
+export function normalizePyName(name: string): string {
+ return name.toLowerCase().replace(/[-_.]+/g, "_");
+}
+
+/** The ecosystem of a runner. */
+export function ecosystemOf(runner: string): "npm" | "pypi" | "go" | "deno" {
+ if (runner === "uvx" || runner === "pipx run" || runner === "uv tool" || runner === "pipx") return "pypi";
+ if (runner === "go run") return "go";
+ if (runner === "deno run") return "deno";
+ return "npm";
+}
+
+async function newestFirst(dirs: string[]): Promise<string[]> {
+ const stamped = await Promise.all(dirs.map(async (dir) => ({ dir, at: await stat(dir).then((s) => s.mtimeMs, () => 0) })));
+ return stamped.sort((a, b) => b.at - a.at).map((entry) => entry.dir);
+}
+
+async function listDirs(dir: string): Promise<string[]> {
+ try {
+ return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).slice(0, MAX_SCAN_DIRS).map((entry) => join(dir, entry.name));
+ } catch {
+ return [];
+ }
+}
+
+async function packageVersion(manifest: string): Promise<string | null> {
+ try {
+ const parsed = JSON.parse(await readFile(manifest, "utf8")) as { version?: unknown };
+ return typeof parsed.version === "string" ? parsed.version : null;
+ } catch {
+ return null;
+ }
+}
+
+export type CacheDirs = {
+ home: string | null;
+ platform: NodeJS.Platform;
+ env: NodeJS.ProcessEnv;
+};
+
+function npmCache({ home, platform, env }: CacheDirs): string | null {
+ if (env.npm_config_cache) return env.npm_config_cache;
+ if (platform === "win32") return env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "npm-cache") : null;
+ return home ? join(home, ".npm") : null;
+}
+
+function cacheHome({ home, platform, env }: CacheDirs): string | null {
+ if (env.XDG_CACHE_HOME) return env.XDG_CACHE_HOME;
+ if (platform === "darwin") return home ? join(home, "Library", "Caches") : null;
+ if (platform === "win32") return env.LOCALAPPDATA ?? null;
+ return home ? join(home, ".cache") : null;
+}
+
+/** The newest npx cache entry holding `pkg` (~/.npm/_npx/<hash>/node_modules/<pkg>/package.json). */
+export async function npxCacheVersion(pkg: string, dirs: CacheDirs, wanted: string | null = null): Promise<string | null> {
+ const cache = npmCache(dirs);
+ if (!cache) return null;
+ for (const entry of await newestFirst(await listDirs(join(cache, "_npx")))) {
+ const version = await packageVersion(join(entry, "node_modules", pkg, "package.json"));
+ if (version && (!wanted || version === wanted || !EXACT.test(wanted))) return version;
+ }
+ return null;
+}
+
+/** pnpm dlx: <cache>/pnpm/dlx/<hash>/<stamp>/node_modules/<pkg>/package.json (and the older flat layout). */
+export async function pnpmDlxVersion(pkg: string, dirs: CacheDirs): Promise<string | null> {
+ const bases = [cacheHome(dirs) ? join(cacheHome(dirs)!, "pnpm", "dlx") : null, dirs.platform === "win32" && dirs.env.LOCALAPPDATA ? join(dirs.env.LOCALAPPDATA, "pnpm-cache", "dlx") : null].filter(Boolean) as string[];
+ for (const base of bases) {
+ for (const hash of await newestFirst(await listDirs(base))) {
+ const direct = await packageVersion(join(hash, "node_modules", pkg, "package.json"));
+ if (direct) return direct;
+ for (const stamp of await newestFirst(await listDirs(hash))) {
+ const version = await packageVersion(join(stamp, "node_modules", pkg, "package.json"));
+ if (version) return version;
+ }
+ }
+ }
+ return null;
+}
+
+/** bunx: ~/.bun/install/cache/<pkg>@<version>@@@1 folders. */
+export async function bunCacheVersion(pkg: string, dirs: CacheDirs): Promise<string | null> {
+ const base = dirs.env.BUN_INSTALL_CACHE_DIR ?? (dirs.home ? join(dirs.home, ".bun", "install", "cache") : null);
+ if (!base) return null;
+ const scoped = pkg.startsWith("@") ? pkg.split("/") : null;
+ const dir = scoped ? join(base, scoped[0]!) : base;
+ const prefix = `${scoped ? scoped[1] : pkg}@`;
+ const candidates = (await listDirs(dir)).filter((path) => path.split(/[\\/]/).at(-1)!.startsWith(prefix));
+ for (const entry of await newestFirst(candidates)) {
+ const match = /@(\d[^@]*)@@@/.exec(entry.split(/[\\/]/).at(-1)!);
+ if (match) return match[1]!;
+ }
+ return null;
+}
+
+/** A `<name>-<version>.dist-info` folder for the package, searched breadth-first under `base` (bounded). */
+async function distInfoVersion(base: string, pkg: string, maxDepth: number): Promise<string | null> {
+ const wanted = normalizePyName(pkg);
+ let level = [base];
+ let visited = 0;
+ for (let depth = 0; depth <= maxDepth && level.length > 0; depth += 1) {
+ const next: string[] = [];
+ const found: string[] = [];
+ for (const dir of level) {
+ if (visited++ > MAX_SCAN_DIRS) return null;
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const match = /^(.+)-([^-]+)\.dist-info$/.exec(entry.name);
+ if (match && normalizePyName(match[1]!) === wanted) found.push(join(dir, entry.name));
+ else if (!entry.name.endsWith(".dist-info") && entry.name !== "__pycache__") next.push(join(dir, entry.name));
+ }
+ }
+ if (found.length > 0) {
+ const newest = (await newestFirst(found))[0]!;
+ return /-([^-]+)\.dist-info$/.exec(newest)![1]!;
+ }
+ level = next;
+ }
+ return null;
+}
+
+/** uvx: uv's tool environments, then its archive cache. */
+export async function uvVersion(pkg: string, dirs: CacheDirs): Promise<string | null> {
+ const data = dirs.env.UV_TOOL_DIR ?? (dirs.platform === "win32" ? (dirs.env.APPDATA ? join(dirs.env.APPDATA, "uv", "tools") : null) : dirs.home ? join(dirs.env.XDG_DATA_HOME ?? join(dirs.home, ".local", "share"), "uv", "tools") : null);
+ if (data) {
+ const version = await distInfoVersion(join(data, pkg), pkg, 5);
+ if (version) return version;
+ }
+ const cache = dirs.env.UV_CACHE_DIR ?? (dirs.platform === "win32" ? (dirs.env.LOCALAPPDATA ? join(dirs.env.LOCALAPPDATA, "uv", "cache") : null) : dirs.home ? join(dirs.env.XDG_CACHE_HOME ?? join(dirs.home, ".cache"), "uv") : null);
+ if (!cache) return null;
+ // archive-v0/<hash>/lib/python3.x/site-packages/<pkg>-<v>.dist-info (Windows: Lib/site-packages).
+ for (const archive of (await listDirs(cache)).filter((dir) => /archive-v\d+$/.test(dir))) {
+ for (const entry of (await newestFirst(await listDirs(archive))).slice(0, 200)) {
+ const version = await distInfoVersion(entry, pkg, 4);
+ if (version) return version;
+ }
+ }
+ return null;
+}
+
+/** pipx run: <pipx home>/.cache/<hash>/ venvs. */
+export async function pipxVersion(pkg: string, dirs: CacheDirs): Promise<string | null> {
+ const homes = [dirs.env.PIPX_HOME, dirs.home ? join(dirs.home, ".local", "pipx") : null, dirs.home ? join(dirs.env.XDG_DATA_HOME ?? join(dirs.home, ".local", "share"), "pipx") : null].filter(Boolean) as string[];
+ for (const home of homes) {
+ for (const venv of await newestFirst(await listDirs(join(home, ".cache")))) {
+ const version = await distInfoVersion(venv, pkg, 5);
+ if (version) return version;
+ }
+ const installed = await distInfoVersion(join(home, "venvs", pkg), pkg, 5);
+ if (installed) return installed;
+ }
+ return null;
+}
+
+/** go run pkg@latest: the newest version the module cache downloaded for the module or one of its parents. */
+export async function goModVersion(pkg: string, dirs: CacheDirs): Promise<string | null> {
+ const modcache = dirs.env.GOMODCACHE ?? (dirs.env.GOPATH ? join(dirs.env.GOPATH.split(dirs.platform === "win32" ? ";" : ":")[0]!, "pkg", "mod") : dirs.home ? join(dirs.home, "go", "pkg", "mod") : null);
+ if (!modcache) return null;
+ const parts = pkg.split("/");
+ for (let n = parts.length; n >= 2; n -= 1) {
+ // Upper-case letters are escaped as !lower in the module cache.
+ const module = parts.slice(0, n).join("/").replace(/[A-Z]/g, (c) => `!${c.toLowerCase()}`);
+ const dir = join(modcache, "cache", "download", ...module.split("/"), "@v");
+ let names: string[];
+ try {
+ names = (await readdir(dir)).filter((name) => name.endsWith(".info"));
+ } catch {
+ continue;
+ }
+ const newest = await newestFirst(names.map((name) => join(dir, name)));
+ if (newest[0]) return newest[0].split(/[\\/]/).at(-1)!.replace(/\.info$/, "");
+ }
+ return null;
+}
+
+/** deno run npm:pkg: <DENO_DIR>/npm/registry.npmjs.org/<pkg>/<version>. */
+export async function denoNpmVersion(pkg: string, dirs: CacheDirs): Promise<string | null> {
+ const denoDir = dirs.env.DENO_DIR ?? (cacheHome(dirs) ? join(cacheHome(dirs)!, "deno") : null);
+ if (!denoDir || pkg.startsWith("jsr:")) return null;
+ const newest = await newestFirst(await listDirs(join(denoDir, "npm", "registry.npmjs.org", ...pkg.split("/"))));
+ return newest[0] ? newest[0].split(/[\\/]/).at(-1)! : null;
+}
+
+export type ResolveEphemeralOptions = Partial<CacheDirs> & { run?: Runner; resolve?: (command: string) => string | null; registryFallback?: boolean };
+
+/** The exact version of one on-the-fly tool run (see the module comment). */
+export async function resolveEphemeral(
+ call: { tool_call_id: string | null; runner: string; package: string; requested: string | null },
+ options: ResolveEphemeralOptions = {},
+): Promise<EphemeralTool> {
+ const dirs: CacheDirs = { home: options.home ?? null, platform: options.platform ?? process.platform, env: options.env ?? process.env };
+ const base = { tool_call_id: call.tool_call_id, runner: call.runner, package: call.package, requested: call.requested };
+ const ecosystem = ecosystemOf(call.runner);
+ const validName = ecosystem === "pypi" ? PY_NAME.test(call.package) : ecosystem === "go" ? /^[\w.~/-]+$/.test(call.package) : NPM_NAME.test(call.package.replace(/^jsr:/, ""));
+ if (!validName) return { ...base, version: null, resolved: "unresolved", source: null };
+ if (call.requested && EXACT.test(call.requested)) return { ...base, version: call.requested.replace(/^v(?=\d)/, ecosystem === "go" ? "v" : ""), resolved: "exact", source: null };
+ let version: string | null = null;
+ let source: EphemeralTool["source"] = null;
+ const attempt = async (value: Promise<string | null>, from: NonNullable<EphemeralTool["source"]>) => {
+ if (version) return;
+ version = await value.catch(() => null);
+ if (version) source = from;
+ };
+ if (ecosystem === "npm") {
+ if (call.runner === "pnpm dlx") await attempt(pnpmDlxVersion(call.package, dirs), "pnpm_cache");
+ if (call.runner === "bunx" || call.runner === "bun x") await attempt(bunCacheVersion(call.package, dirs), "bun_cache");
+ await attempt(npxCacheVersion(call.package, dirs, call.requested), "npx_cache");
+ } else if (ecosystem === "pypi") {
+ if (call.runner === "pipx run") await attempt(pipxVersion(call.package, dirs), "pipx_venv");
+ await attempt(uvVersion(call.package, dirs), "uv_cache");
+ } else if (ecosystem === "go") {
+ await attempt(goModVersion(call.package, dirs), "go_modcache");
+ } else {
+ await attempt(denoNpmVersion(call.package, dirs), "deno_cache");
+ }
+ if (version) return { ...base, version, resolved: "cache", source };
+ const npmName = ecosystem === "npm" ? call.package : ecosystem === "deno" && !call.package.startsWith("jsr:") ? call.package : null;
+ if (npmName && options.registryFallback !== false) {
+ const spec = call.requested && !EXACT.test(call.requested) && /^[\w.^~<>=*|-]+$/.test(call.requested) ? `${npmName}@${call.requested}` : npmName;
+ const result = await runTool("npm", ["view", spec, "version"], {
+ timeoutMs: 8_000,
+ maxBytes: 64 * 1024,
+ ...(options.run ? { run: options.run } : {}),
+ ...(options.resolve ? { resolve: options.resolve } : {}),
+ });
+ const lines = result && result.code === 0 ? result.stdout.trim().split(/\r?\n/) : [];
+ // A range lists `[email protected] '1.2.3'` per match: the last one is the highest.
+ const last = lines.at(-1)?.replace(/^.*\s'?|'$/g, "").trim() ?? "";
+ if (EXACT.test(last)) return { ...base, version: last, resolved: "registry_latest", source: "registry" };
+ }
+ return { ...base, version: null, resolved: "unresolved", source: null };
+}
diff --git a/apps/server/src/context/exec.ts b/apps/server/src/context/exec.ts
new file mode 100644
index 00000000..7706d5a5
--- /dev/null
+++ b/apps/server/src/context/exec.ts
@@ -0,0 +1,167 @@
+// Running the external commands capture context needs: resolved on PATH
+// first (a tool that is not installed is never spawned), at the lowest CPU
+// priority, with stdin closed, a hard timeout that kills the whole process
+// group, and a cap on what is read back. Never throws: a failure is null.
+//
+// macOS: a /usr/bin Command Line Tools shim is never run when the tools are
+// missing (the guard of capture/command-guard.ts).
+
+import { spawn } from "node:child_process";
+import { setPriority } from "node:os";
+
+import { cltSkipReason, configureCltProbe, resolveCommand, type ResolveOptions } from "../command-guard.js";
+
+export type RunResult = { code: number | null; stdout: string; stderr: string; truncated: boolean; timedOut: boolean };
+
+export type RunOptions = {
+ timeoutMs?: number;
+ maxBytes?: number;
+ cwd?: string;
+ env?: NodeJS.ProcessEnv;
+};
+
+export type Runner = (file: string, args: string[], options?: RunOptions) => Promise<RunResult | null>;
+
+const DEFAULT_TIMEOUT_MS = 5_000;
+const DEFAULT_MAX_BYTES = 1024 * 1024;
+
+/** The child environment: the user's, without anything that could make a tool prompt or page. */
+export function quietEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
+ return {
+ ...process.env,
+ PAGER: "cat",
+ GIT_PAGER: "cat",
+ GIT_TERMINAL_PROMPT: "0",
+ NO_COLOR: "1",
+ TERM: "dumb",
+ HOMEBREW_NO_AUTO_UPDATE: "1",
+ HOMEBREW_NO_ANALYTICS: "1",
+ HOMEBREW_NO_ENV_HINTS: "1",
+ DEBIAN_FRONTEND: "noninteractive",
+ npm_config_update_notifier: "false",
+ ...extra,
+ };
+}
+
+/** Runs `file` (an absolute path) and resolves with its output, or null when it could not start. */
+export const runCommand: Runner = (file, args, options = {}) => {
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
+ return new Promise((resolvePromise) => {
+ let child: ReturnType<typeof spawn>;
+ // A .cmd/.bat (npm.cmd) only runs through cmd.exe; every argument capture passes is a plain word.
+ if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(file)) {
+ if (args.some((arg) => /["%^&|<>\r\n]/.test(arg))) {
+ resolvePromise(null);
+ return;
+ }
+ args = ["/d", "/s", "/c", `"${[file, ...args].map((arg) => (/\s/.test(arg) ? `"${arg}"` : arg)).join(" ")}"`];
+ file = process.env.ComSpec || "cmd.exe";
+ }
+ try {
+ child = spawn(file, args, {
+ windowsVerbatimArguments: process.platform === "win32" && /cmd\.exe$/i.test(file),
+ cwd: options.cwd,
+ env: options.env ?? quietEnv(),
+ stdio: ["ignore", "pipe", "pipe"],
+ windowsHide: true,
+ detached: process.platform !== "win32",
+ });
+ } catch {
+ resolvePromise(null);
+ return;
+ }
+ if (typeof child.pid === "number") {
+ try {
+ setPriority(child.pid, 19);
+ } catch {
+ // Not permitted or already gone: it runs at the normal priority.
+ }
+ }
+ const out: Buffer[] = [];
+ const err: Buffer[] = [];
+ let outBytes = 0;
+ let errBytes = 0;
+ let truncated = false;
+ let timedOut = false;
+ let settled = false;
+ const kill = () => {
+ try {
+ if (process.platform !== "win32" && typeof child.pid === "number") process.kill(-child.pid, "SIGKILL");
+ else child.kill("SIGKILL");
+ } catch {
+ try {
+ child.kill("SIGKILL");
+ } catch {
+ // Gone.
+ }
+ }
+ };
+ const finish = (code: number | null) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolvePromise({
+ code,
+ stdout: Buffer.concat(out).toString("utf8"),
+ stderr: Buffer.concat(err).toString("utf8"),
+ truncated,
+ timedOut,
+ });
+ };
+ const timer = setTimeout(() => {
+ timedOut = true;
+ kill();
+ finish(null);
+ }, timeoutMs);
+ timer.unref?.();
+ child.stdout?.on("data", (chunk: Buffer) => {
+ if (outBytes >= maxBytes) return;
+ const room = maxBytes - outBytes;
+ if (chunk.length > room) {
+ truncated = true;
+ out.push(chunk.subarray(0, room));
+ outBytes = maxBytes;
+ kill();
+ return;
+ }
+ out.push(chunk);
+ outBytes += chunk.length;
+ });
+ child.stderr?.on("data", (chunk: Buffer) => {
+ if (errBytes >= 64 * 1024) return;
+ err.push(chunk);
+ errBytes += chunk.length;
+ });
+ child.on("error", () => {
+ if (!settled) {
+ settled = true;
+ clearTimeout(timer);
+ resolvePromise(null);
+ }
+ });
+ child.on("close", (code) => finish(code));
+ });
+};
+
+// --- PATH lookup and the Command Line Tools guard: capture/command-guard.ts ---------
+
+export { resolveCommand, type ResolveOptions };
+/** Test hook: the guard's platform and xcode-select check (command-guard.ts configureCltProbe). */
+export const configureContextCltProbe = configureCltProbe;
+
+/** Whether running `resolvedPath` as `command` would open the Command Line Tools install dialog. */
+export async function wouldPromptClt(command: string, resolvedPath: string | null): Promise<boolean> {
+ return (await cltSkipReason(command, resolvedPath)) !== null;
+}
+
+/**
+ * Resolves `command` on PATH and runs it, unless it is not installed or is a
+ * Command Line Tools shim on a Mac without them (null either way).
+ */
+export async function runTool(command: string, args: string[], options: RunOptions & { run?: Runner; resolve?: (command: string) => string | null } = {}): Promise<RunResult | null> {
+ const resolved = (options.resolve ?? resolveCommand)(command);
+ if (!resolved) return null;
+ if (await wouldPromptClt(command, resolved)) return null;
+ return (options.run ?? runCommand)(resolved, args, options);
+}
diff --git a/apps/server/src/context/index.ts b/apps/server/src/context/index.ts
new file mode 100644
index 00000000..627bf3af
--- /dev/null
+++ b/apps/server/src/context/index.ts
@@ -0,0 +1,375 @@
+// Capture context (capture v2): what the session's machine looked like
+// around the agent, recorded as trace events beside the conversation.
+//
+// session start context.environment (system packages #5, services #7,
+// setup #16, package-manager config #17, shell aliases
+// #18), context.setup_files (#16 skill/plugin texts) and
+// context.processes (#19, phase session_start)
+// turn start context.processes (#19, phase turn_start); the network
+// observer starts (#20)
+// turn messages context.outside_folder / context.outside_file (#10,
+// #21) and context.ephemeral_tool (#22) from its tool calls
+// turn end context.network (#20) per shell call (or per turn)
+//
+// Everything runs in the background with timeouts and never delays a turn
+// or an upload; every item is capped, has the home directory as `~`, and
+// goes through the uploader's CONFIG secret scrub (here, and again when the
+// trace is uploaded). OMNIRUSH_CAPTURE_CONTEXT=0 turns the whole module off;
+// OMNIRUSH_CAPTURE_NETWORK=0 only the network observer.
+
+import { toolCallsOf, commandEffects, toolKind, type ToolCall } from "./commands.js";
+import { resolveEphemeral, type ResolveEphemeralOptions } from "./ephemeral.js";
+import { attributeConnections, defaultSampler, NetworkObserver, type HostResolver, type Sampler } from "./network.js";
+import { OutsideTracker } from "./outside.js";
+import { collectPmConfig } from "./pm-config.js";
+import { currentPrivacy, type PrivacyContext, type Scrubber } from "./privacy.js";
+import { processSnapshot, processTable, listeningPorts, type ProcessInfo, type ListeningPort } from "./processes.js";
+import { collectServices } from "./services.js";
+import { collectSetup, type SetupFile, type SetupModel } from "./setup.js";
+import { collectShellAliases } from "./shell-aliases.js";
+import { systemPackages } from "./system-packages.js";
+
+export const CONTEXT_SCHEMA = 1;
+const SECTION_TIMEOUT_MS = 30_000;
+const SETTLE_TIMEOUT_MS = 1_000;
+const MAX_SETUP_FILES_EVENT_BYTES = 512 * 1024;
+const MAX_EPHEMERAL_PER_SESSION = 500;
+
+export type ContextEventType =
+ | "context.environment"
+ | "context.setup_files"
+ | "context.processes"
+ | "context.network"
+ | "context.ephemeral_tool"
+ | "context.outside_folder"
+ | "context.outside_file";
+
+/** Whether capture context is on: OMNIRUSH_CAPTURE_CONTEXT=0 (or false/off/no) turns it off. */
+export function captureContextEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
+ return !/^(?:0|false|off|no)$/i.test((env.OMNIRUSH_CAPTURE_CONTEXT ?? "").trim());
+}
+
+/** Whether the network observer (#20) is on: OMNIRUSH_CAPTURE_NETWORK=0 turns it off. */
+export function captureNetworkEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
+ return captureContextEnabled(env) && !/^(?:0|false|off|no)$/i.test((env.OMNIRUSH_CAPTURE_NETWORK ?? "").trim());
+}
+
+export type ContextOptions = {
+ client: "cli" | "gui";
+ appVersion?: string | null;
+ engineVersion?: string | null;
+ /** Where the once-a-day system package list is cached (the app's state directory). */
+ cacheDir?: string | null;
+ scrub: Scrubber;
+ /** Appends a trace event to the session (the uploader's trace, scrubbed again on upload). */
+ record: (sessionId: string, type: ContextEventType, data: unknown) => void;
+ /** Reports an absolute outside file to the project archive (byte-exact copy). */
+ reportPath?: (sessionId: string, absolute: string) => void;
+ /** The archive's exclusion of an absolute outside path (credential, app state, dependency, system), else null. */
+ exclusion?: (absolute: string) => string | null;
+ /** The upload denylist for a relative path (credential files), applied to skill/plugin files. */
+ denied?: (relPath: string) => boolean;
+ /** The session's latest model (the uploader's session.model). */
+ model?: (sessionId: string) => SetupModel | null;
+ settings?: () => Record<string, unknown>;
+ bundledSkillDirs?: string[];
+ bundledSkills?: Array<{ name: string; version: string | null; sha256: string }>;
+ configFiles?: string[];
+ mcpFiles?: string[];
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ /** Tests: overrides. */
+ enabled?: boolean;
+ network?: boolean;
+ sampler?: Sampler | null;
+ resolver?: HostResolver;
+ privacy?: PrivacyContext;
+ ephemeral?: ResolveEphemeralOptions;
+ /** Tests: skip the slow machine-wide sections. */
+ sections?: Partial<Record<"system_packages" | "services" | "setup" | "pm_config" | "shell_aliases" | "processes", boolean>>;
+ log?: (level: "info" | "warn", message: string, data?: Record<string, unknown>) => void;
+};
+
+type SessionContext = {
+ id: string;
+ root: string;
+ startedAt: number;
+ turn: number;
+ outside: OutsideTracker;
+ observer: NetworkObserver | null;
+ /** Tool calls of the current turn, by call id (or position). */
+ calls: Map<string, ToolCall>;
+ processedCalls: Set<string>;
+ ephemeral: number;
+ pending: Set<Promise<unknown>>;
+ ended: boolean;
+};
+
+/** Overhead bookkeeping (milliseconds of wall time spent in each phase). */
+export type ContextTimings = { session_start: number[]; turn_start: number[]; turn_messages: number[]; turn_end: number[]; network_sample_ms: number; network_samples: number };
+
+/** Active turns across every capture in this process: an unmatched tool shell is only a turn's when one turn runs. */
+const activeTurns = new Set<string>();
+
+function withTimeout<T>(promise: Promise<T>, ms: number): Promise<{ value: T } | { timeout: true } | { error: true }> {
+ return Promise.race([
+ promise.then((value) => ({ value }), () => ({ error: true as const })),
+ new Promise<{ timeout: true }>((resolve) => setTimeout(() => resolve({ timeout: true }), ms).unref?.()),
+ ]);
+}
+
+export class ContextCapture {
+ readonly enabled: boolean;
+ readonly networkEnabled: boolean;
+ readonly timings: ContextTimings = { session_start: [], turn_start: [], turn_messages: [], turn_end: [], network_sample_ms: 0, network_samples: 0 };
+ private readonly sessions = new Map<string, SessionContext>();
+ private readonly privacy: PrivacyContext;
+ private readonly platform: NodeJS.Platform;
+ private readonly env: NodeJS.ProcessEnv;
+
+ constructor(private readonly options: ContextOptions) {
+ this.env = options.env ?? process.env;
+ this.enabled = options.enabled ?? captureContextEnabled(this.env);
+ this.networkEnabled = this.enabled && (options.network ?? captureNetworkEnabled(this.env));
+ this.privacy = options.privacy ?? currentPrivacy();
+ this.platform = options.platform ?? process.platform;
+ }
+
+ private section(name: keyof NonNullable<ContextOptions["sections"]>): boolean {
+ return this.options.sections?.[name] !== false;
+ }
+
+ private emit(sessionId: string, type: ContextEventType, data: unknown): void {
+ try {
+ this.options.record(sessionId, type, this.options.scrub.json(data));
+ } catch (error) {
+ this.options.log?.("warn", "capture context: event dropped", { type, error: error instanceof Error ? error.message : String(error) });
+ }
+ }
+
+ private track(state: SessionContext, work: Promise<unknown>): void {
+ const guarded = work.catch((error) => this.options.log?.("warn", "capture context failed", { error: error instanceof Error ? error.message : String(error) }));
+ state.pending.add(guarded);
+ void guarded.finally(() => state.pending.delete(guarded));
+ }
+
+ sessionStarted(sessionId: string, root: string): void {
+ if (!this.enabled || this.sessions.has(sessionId)) return;
+ const state: SessionContext = {
+ id: sessionId,
+ root,
+ startedAt: Date.now(),
+ turn: 0,
+ outside: new OutsideTracker({
+ root,
+ sessionStartMs: Date.now(),
+ privacy: this.privacy,
+ scrub: this.options.scrub,
+ exclusion: this.options.exclusion ?? (() => null),
+ reportPath: (absolute) => this.options.reportPath?.(sessionId, absolute),
+ }),
+ observer: null,
+ calls: new Map(),
+ processedCalls: new Set(),
+ ephemeral: 0,
+ pending: new Set(),
+ ended: false,
+ };
+ if (this.networkEnabled) {
+ const sampler = this.options.sampler === undefined ? defaultSampler(this.platform) : this.options.sampler;
+ if (sampler) state.observer = new NetworkObserver({ sampler });
+ }
+ this.sessions.set(sessionId, state);
+ this.track(state, this.collectSessionStart(state));
+ }
+
+ private async collectSessionStart(state: SessionContext): Promise<void> {
+ const started = performance.now();
+ const timings: Record<string, number> = {};
+ const errors: Record<string, string> = {};
+ const timed = async <T>(name: string, work: () => Promise<T>): Promise<T | undefined> => {
+ const at = performance.now();
+ const result = await withTimeout(work(), SECTION_TIMEOUT_MS);
+ timings[name] = Math.round(performance.now() - at);
+ if ("value" in result) return result.value;
+ errors[name] = "timeout" in result ? "timeout" : "failed";
+ return undefined;
+ };
+ const { privacy } = this;
+ const scrub = this.options.scrub;
+ const runOpts = { platform: this.platform };
+
+ // Processes and ports first: services reads the listening ports.
+ let table: ProcessInfo[] = [];
+ let listening: ListeningPort[] = [];
+ if (this.section("processes")) {
+ const snapshot = await timed("processes", async () => {
+ const { processes, method } = await processTable(runOpts);
+ table = processes;
+ const ports = await listeningPorts(processes, runOpts);
+ listening = ports.ports;
+ return processSnapshot("session_start", 0, { ...runOpts, privacy, scrub, precomputed: { processes, listening, method: `${method}+${ports.method}` } });
+ });
+ if (snapshot) this.emit(state.id, "context.processes", snapshot);
+ }
+
+ const [packages, services, setup, pmConfig, aliases] = await Promise.all([
+ this.section("system_packages") ? timed("system_packages", () => systemPackages({ platform: this.platform, cacheDir: this.options.cacheDir ?? null })) : undefined,
+ this.section("services") ? timed("services", () => collectServices({ root: state.root, listening, processes: table, privacy, scrub, platform: this.platform })) : undefined,
+ this.section("setup")
+ ? timed("setup", () => collectSetup({
+ root: state.root,
+ client: this.options.client,
+ appVersion: this.options.appVersion ?? null,
+ engineVersion: this.options.engineVersion ?? null,
+ model: this.options.model?.(state.id) ?? null,
+ settings: this.options.settings?.() ?? {},
+ bundledSkillDirs: this.options.bundledSkillDirs ?? [],
+ bundledSkills: this.options.bundledSkills ?? [],
+ configFiles: this.options.configFiles ?? [],
+ mcpFiles: this.options.mcpFiles ?? [],
+ privacy,
+ scrub,
+ ...(this.options.denied ? { denied: this.options.denied } : {}),
+ env: this.env,
+ }))
+ : undefined,
+ this.section("pm_config") ? timed("pm_config", () => collectPmConfig({ privacy, scrub, platform: this.platform, env: this.env })) : undefined,
+ this.section("shell_aliases") ? timed("shell_aliases", () => collectShellAliases({ privacy, scrub, platform: this.platform, env: this.env })) : undefined,
+ ]);
+ timings.total = Math.round(performance.now() - started);
+ this.timings.session_start.push(timings.total);
+ this.emit(state.id, "context.environment", {
+ schema: CONTEXT_SCHEMA,
+ collected_at: new Date().toISOString(),
+ platform: this.platform,
+ ...(packages ? { system_packages: packages } : {}),
+ ...(services ? { services } : {}),
+ ...(setup ? { setup: setup.setup } : {}),
+ ...(pmConfig ? { pm_config: pmConfig } : {}),
+ ...(aliases ? { shell_aliases: aliases } : {}),
+ timings_ms: timings,
+ ...(Object.keys(errors).length > 0 ? { errors } : {}),
+ });
+ if (setup && setup.files.length > 0) this.emitSetupFiles(state.id, setup.files);
+ }
+
+ /** The skill/plugin texts in events of at most ~512 KiB each. */
+ private emitSetupFiles(sessionId: string, files: SetupFile[]): void {
+ const parts: SetupFile[][] = [[]];
+ let bytes = 0;
+ for (const file of files) {
+ const size = Buffer.byteLength(JSON.stringify(file));
+ if (bytes + size > MAX_SETUP_FILES_EVENT_BYTES && parts[parts.length - 1]!.length > 0) {
+ parts.push([]);
+ bytes = 0;
+ }
+ parts[parts.length - 1]!.push(file);
+ bytes += size;
+ }
+ parts.forEach((part, index) => this.emit(sessionId, "context.setup_files", { files: part, part: index + 1, parts: parts.length }));
+ }
+
+ /**
+ * A prompt was dispatched. `after`: work the turn's own capture does first
+ * (the uploader's artifact baseline listing); the process snapshot waits
+ * for it so the two never compete for the disk and the event loop.
+ */
+ turnStarted(sessionId: string, after?: Promise<unknown>): void {
+ const state = this.sessions.get(sessionId);
+ if (!state || state.ended) return;
+ state.turn += 1;
+ state.calls = new Map();
+ if (state.observer) {
+ activeTurns.add(sessionId);
+ state.observer.start();
+ }
+ if (!this.section("processes")) return;
+ const turn = state.turn;
+ 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 }), SECTION_TIMEOUT_MS);
+ this.timings.turn_start.push(Math.round(performance.now() - started));
+ if ("value" in snapshot) this.emit(sessionId, "context.processes", snapshot.value);
+ })());
+ }
+
+ /** The turn's engine messages (possibly in several parts): its tool calls feed #10, #21 and #22. */
+ turnMessages(sessionId: string, messages: unknown): void {
+ const state = this.sessions.get(sessionId);
+ if (!state) return;
+ const calls = toolCallsOf(messages, state.root, this.privacy.home);
+ const fresh: ToolCall[] = [];
+ calls.forEach((call, index) => {
+ const key = call.callId ?? `${state.turn}:${index}:${call.tool}:${call.start ?? ""}`;
+ state.calls.set(key, call);
+ if (state.processedCalls.has(key) || (call.status !== null && call.status !== "completed" && call.status !== "error")) return;
+ state.processedCalls.add(key);
+ fresh.push(call);
+ });
+ if (fresh.length === 0) return;
+ this.track(state, (async () => {
+ const started = performance.now();
+ const outside = await state.outside.processCalls(fresh);
+ for (const folder of outside.folders) this.emit(sessionId, "context.outside_folder", folder);
+ for (const file of outside.files) this.emit(sessionId, "context.outside_file", file);
+ for (const call of fresh) {
+ if (toolKind(call.tool) !== "shell" || !call.command) continue;
+ for (const tool of commandEffects(call.command, call.cwd, this.privacy.home).ephemeral) {
+ if (state.ephemeral >= MAX_EPHEMERAL_PER_SESSION) break;
+ state.ephemeral += 1;
+ const runner = tool.runner === "bun x" ? "bunx" : tool.runner;
+ const resolved = await resolveEphemeral(
+ { tool_call_id: call.callId, runner, package: tool.package, requested: tool.requested },
+ { home: this.privacy.home, platform: this.platform, env: this.env, ...(this.options.ephemeral ?? {}) },
+ );
+ this.emit(sessionId, "context.ephemeral_tool", resolved);
+ }
+ }
+ this.timings.turn_messages.push(Math.round(performance.now() - started));
+ })());
+ }
+
+ /** The turn ended: the network observer stops and its connections are attributed to the turn's calls. */
+ turnEnded(sessionId: string): void {
+ const state = this.sessions.get(sessionId);
+ if (!state || !state.observer) return;
+ const observer = state.observer;
+ const calls = [...state.calls.values()];
+ const turn = state.turn;
+ const alone = activeTurns.size <= 1;
+ activeTurns.delete(sessionId);
+ this.track(state, (async () => {
+ const started = performance.now();
+ const roots = await observer.stop();
+ this.timings.network_sample_ms = observer.sampleMs;
+ this.timings.network_samples = observer.samples;
+ const events = await attributeConnections(roots, calls, { turn, method: observer.method, pollMs: observer.pollMs, ...(this.options.resolver ? { resolver: this.options.resolver } : {}) });
+ for (const event of events) {
+ // Another session's turn ran at the same time: an unmatched shell may be its.
+ if (event.scope === "turn" && !alone) continue;
+ this.emit(sessionId, "context.network", event);
+ }
+ this.timings.turn_end.push(Math.round(performance.now() - started));
+ })());
+ }
+
+ /** Resolves once the session's background work is done (or after `timeoutMs`). */
+ async settled(sessionId: string, timeoutMs = SETTLE_TIMEOUT_MS): Promise<void> {
+ const state = this.sessions.get(sessionId);
+ if (!state) return;
+ const deadline = Date.now() + timeoutMs;
+ while (state.pending.size > 0 && Date.now() < deadline) {
+ await withTimeout(Promise.all([...state.pending]), Math.max(1, deadline - Date.now()));
+ }
+ }
+
+ sessionEnded(sessionId: string): void {
+ const state = this.sessions.get(sessionId);
+ if (!state || state.ended) return;
+ if (state.observer && activeTurns.has(sessionId)) this.turnEnded(sessionId);
+ state.ended = true;
+ void this.settled(sessionId, SETTLE_TIMEOUT_MS).finally(() => this.sessions.delete(sessionId));
+ }
+}
diff --git a/apps/server/src/context/network.ts b/apps/server/src/context/network.ts
new file mode 100644
index 00000000..62a08506
--- /dev/null
+++ b/apps/server/src/context/network.ts
@@ -0,0 +1,575 @@
+// #20 The network hosts each shell tool call reached. While a turn runs, a
+// cheap observer samples the app's process tree: every shell the engine
+// starts for a tool call (`<shell> -c <command>`) is a tool root, and the
+// TCP connections of the root and its descendants are recorded.
+//
+// Linux: /proc/<pid>/task/*/children for the tree, /proc/<pid>/fd socket
+// inodes matched against /proc/net/tcp{,6}; no process is spawned.
+// macOS: `ps` for the tree and `lsof -nP -a -iTCP -p <pids>` for the
+// connections, only while a tool shell is running.
+// Windows: one PowerShell CIM query for the tree and `netstat -ano`.
+//
+// After the turn each root is matched to the tool call that ran its
+// command (and started within its time); connections of a root no call
+// matches are recorded for the whole turn (`scope: "turn"`). Sampling
+// misses a connection shorter than the poll interval. Hosts are named from
+// the hostnames in the command (resolved with the system resolver, so the
+// same DNS answers the tool saw, usually from cache), else by reverse DNS
+// with a short timeout. Raw IP addresses are never recorded, only their
+// class. OMNIRUSH_CAPTURE_NETWORK=0 turns the observer off.
+
+import { promises as dns } from "node:dns";
+import { readdir, readFile, readlink } from "node:fs/promises";
+import { basename } from "node:path";
+
+import type { ToolCall } from "./commands.js";
+import { runTool, type Runner } from "./exec.js";
+import { addressClass, type AddressClass } from "./privacy.js";
+import { parseNetstat, parsePs, parseProcNetTcp, parseProcStat, parseWindowsProcesses, splitHostPort, type ProcessInfo } from "./processes.js";
+
+export const MAX_CONNECTIONS_PER_CALL = 100;
+const MAX_ROOTS_PER_TURN = 500;
+const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh", "fish", "pwsh", "powershell", "cmd", "busybox"]);
+
+export type Connection = { host: string | null; port: number; address_class: AddressClass; resolved_by: "command" | "known_host" | "reverse" | "loopback" | null; first_seen: string };
+export type NetworkEvent = {
+ tool_call_id: string | null;
+ tool: string;
+ scope: "call" | "turn";
+ turn: number;
+ method: string;
+ poll_ms: number;
+ connections: Connection[];
+ truncated: boolean;
+};
+
+type Seen = { ip: string; port: number; first: number };
+type Root = { pid: number; command: string; firstSeen: number; connections: Map<string, Seen> };
+
+/** The engine that runs the tools (`opencode serve`, the app's engine binary). */
+export function isEngineProcess(argv: string[]): boolean {
+ const line = argv.join(" ");
+ return /(?:^|[\\/\s])(?:opencode|omnirush[-\w]*)(?:\.exe)?\b.*\bserve\b/i.test(line);
+}
+
+/** The command a tool shell runs: argv `[shell, …, -c, <command>]`, else null. */
+export function shellCommandOf(argv: string[]): string | null {
+ if (argv.length < 3) return null;
+ const shell = (argv[0]!.split(/[\\/]/).at(-1) ?? "").replace(/\.exe$/i, "").toLowerCase();
+ if (!SHELLS.has(shell)) return null;
+ for (let i = 1; i < argv.length - 1; i += 1) {
+ const flag = argv[i]!;
+ if (/^-[a-z]*c$/i.test(flag) || /^-command$/i.test(flag) || /^\/c$/i.test(flag)) return argv.slice(i + 1).join(" ");
+ }
+ return null;
+}
+
+export type ProcSample = { pid: number; ppid: number; argv: string[] };
+export type Sampler = {
+ method: string;
+ /** Interval between samples while no tool shell runs. */
+ pollMs: number;
+ /** Interval while a tool shell runs (short connections are only seen by a sample taken during them). */
+ activePollMs?: number;
+ /** Processes below `selfPid` (pid, parent, argv). */
+ tree(selfPid: number): Promise<ProcSample[]>;
+ /** Remote endpoints of the given processes' TCP connections. */
+ connections(pids: number[]): Promise<Array<{ pid: number; ip: string; port: number }>>;
+};
+
+// --- Linux ---------------------------------------------------------------------------
+
+async function linuxChildren(pid: number, procRoot: string): Promise<number[] | null> {
+ let tasks: string[];
+ try {
+ tasks = await readdir(`${procRoot}/${pid}/task`);
+ } catch {
+ return [];
+ }
+ const out: number[] = [];
+ let supported = false;
+ await Promise.all(tasks.map(async (task) => {
+ try {
+ const text = await readFile(`${procRoot}/${pid}/task/${task}/children`, "utf8");
+ supported = true;
+ for (const child of text.trim().split(/\s+/)) if (child) out.push(Number(child));
+ } catch {
+ // No children file (kernel without CONFIG_PROC_CHILDREN) or the task ended.
+ }
+ }));
+ return supported ? out : null;
+}
+
+export function linuxSampler(procRoot = "/proc", pollMs = 250, activePollMs = 100): Sampler {
+ // Socket inode -> its remote endpoint (null: not a TCP socket with a peer, after a few looks).
+ const known = new Map<number, { ip: string; port: number } | { misses: number }>();
+ return {
+ method: "proc",
+ pollMs,
+ activePollMs,
+ async tree(selfPid) {
+ const out: ProcSample[] = [];
+ const readArgv = async (pid: number) => {
+ try {
+ const raw = await readFile(`${procRoot}/${pid}/cmdline`);
+ return raw.toString("utf8").replace(/\0+$/, "").split("\0");
+ } catch {
+ return null;
+ }
+ };
+ const queue: Array<{ pid: number; ppid: number }> = [];
+ const first = await linuxChildren(selfPid, procRoot);
+ if (first === null) {
+ // Full scan: parent links from /proc/<pid>/stat.
+ const parents = new Map<number, number>();
+ for (const name of await readdir(procRoot).catch(() => [] as string[])) {
+ if (!/^\d+$/.test(name)) continue;
+ const stat = await readFile(`${procRoot}/${name}/stat`, "utf8").catch(() => null);
+ const parsed = stat ? parseProcStat(stat) : null;
+ if (parsed) parents.set(Number(name), parsed.ppid);
+ }
+ const below = new Set([selfPid]);
+ let grew = true;
+ while (grew) {
+ grew = false;
+ for (const [pid, ppid] of parents) if (!below.has(pid) && below.has(ppid)) {
+ below.add(pid);
+ grew = true;
+ }
+ }
+ for (const pid of below) if (pid !== selfPid) {
+ const argv = await readArgv(pid);
+ if (argv) out.push({ pid, ppid: parents.get(pid)!, argv });
+ }
+ return out;
+ }
+ for (const child of first) queue.push({ pid: child, ppid: selfPid });
+ const seen = new Set<number>();
+ while (queue.length > 0 && seen.size < 5_000) {
+ const { pid, ppid } = queue.shift()!;
+ if (seen.has(pid)) continue;
+ seen.add(pid);
+ const argv = await readArgv(pid);
+ if (!argv) continue;
+ out.push({ pid, ppid, argv });
+ for (const child of (await linuxChildren(pid, procRoot)) ?? []) queue.push({ pid: child, ppid: pid });
+ }
+ return out;
+ },
+ async connections(pids) {
+ const owners = new Map<number, number>();
+ await Promise.all(pids.map(async (pid) => {
+ let fds: string[];
+ try {
+ fds = await readdir(`${procRoot}/${pid}/fd`);
+ } catch {
+ return;
+ }
+ await Promise.all(fds.slice(0, 2048).map(async (fd) => {
+ try {
+ const match = /^socket:\[(\d+)\]$/.exec(await readlink(`${procRoot}/${pid}/fd/${fd}`));
+ if (match) owners.set(Number(match[1]), pid);
+ } catch {
+ // Closed.
+ }
+ }));
+ }));
+ if (owners.size === 0) return [];
+ // The socket tables are read only when a socket appeared that is not known yet (cheap steady state).
+ const unknown = [...owners.keys()].filter((inode) => {
+ const entry = known.get(inode);
+ return entry === undefined || ("misses" in entry && entry.misses < 3);
+ });
+ if (unknown.length > 0) {
+ const found = new Set<number>();
+ for (const name of ["tcp", "tcp6"]) {
+ const text = await readFile(`${procRoot}/net/${name}`, "utf8").catch(() => "");
+ for (const socket of parseProcNetTcp(text)) {
+ if (!owners.has(socket.inode) || socket.state === "0A" || socket.remote.port === 0) continue;
+ known.set(socket.inode, { ip: socket.remote.address, port: socket.remote.port });
+ found.add(socket.inode);
+ }
+ }
+ for (const inode of unknown) {
+ if (found.has(inode)) continue;
+ const entry = known.get(inode);
+ known.set(inode, { misses: entry && "misses" in entry ? entry.misses + 1 : 1 });
+ }
+ if (known.size > 20_000) known.clear();
+ }
+ const out: Array<{ pid: number; ip: string; port: number }> = [];
+ for (const [inode, pid] of owners) {
+ const entry = known.get(inode);
+ if (entry && "ip" in entry) out.push({ pid, ip: entry.ip, port: entry.port });
+ }
+ return out;
+ },
+ };
+}
+
+// --- macOS ---------------------------------------------------------------------------
+
+/** `lsof -F pn` connection rows: `n10.0.0.2:51234->140.82.112.3:443`. */
+export function parseLsofConnections(text: string): Array<{ pid: number; ip: string; port: number }> {
+ const out: Array<{ pid: number; ip: string; port: number }> = [];
+ let pid = 0;
+ for (const line of text.split(/\r?\n/)) {
+ if (line.startsWith("p")) pid = Number(line.slice(1));
+ else if (line.startsWith("n") && line.includes("->")) {
+ const remote = splitHostPort(line.slice(1).split("->")[1]!.split(" ")[0]!);
+ if (remote && remote.port > 0) out.push({ pid, ip: remote.address, port: remote.port });
+ }
+ }
+ return out;
+}
+
+function descendantsOf(selfPid: number, processes: ProcessInfo[]): ProcSample[] {
+ const children = new Map<number, ProcessInfo[]>();
+ for (const info of processes) {
+ const list = children.get(info.ppid) ?? [];
+ list.push(info);
+ children.set(info.ppid, list);
+ }
+ const out: ProcSample[] = [];
+ const queue = [...(children.get(selfPid) ?? [])];
+ const seen = new Set<number>();
+ while (queue.length > 0) {
+ const info = queue.shift()!;
+ if (seen.has(info.pid)) continue;
+ seen.add(info.pid);
+ out.push({ pid: info.pid, ppid: info.ppid, argv: splitArgs(info.command) });
+ queue.push(...(children.get(info.pid) ?? []));
+ }
+ return out;
+}
+
+/** A `ps args` / Windows CommandLine split back into words (quotes honoured; `-c` keeps the rest whole). */
+export function splitArgs(command: string): string[] {
+ const words: string[] = [];
+ const pattern = /"([^"]*)"|'([^']*)'|(\S+)/g;
+ let match: RegExpExecArray | null;
+ while ((match = pattern.exec(command))) {
+ const word = match[1] ?? match[2] ?? match[3]!;
+ words.push(word);
+ if (words.length >= 2 && /^(?:-[a-z]*c|-command|\/c)$/i.test(word) && SHELLS.has(basename(words[0]!).replace(/\.exe$/i, "").toLowerCase())) {
+ words.push(command.slice(pattern.lastIndex).trim().replace(/^"(.*)"$/s, "$1"));
+ break;
+ }
+ }
+ return words;
+}
+
+export function macSampler(run?: Runner, pollMs = 1_000, activePollMs = 500): Sampler {
+ const runOpt = run ? { run } : {};
+ return {
+ method: "lsof",
+ pollMs,
+ activePollMs,
+ async tree(selfPid) {
+ const result = await runTool("ps", ["-axww", "-o", "pid=,ppid=,args="], { timeoutMs: 3_000, maxBytes: 4 * 1024 * 1024, ...runOpt });
+ return result && result.code === 0 ? descendantsOf(selfPid, parsePs(result.stdout)) : [];
+ },
+ async connections(pids) {
+ if (pids.length === 0) return [];
+ const result = await runTool("lsof", ["-nP", "-a", "-iTCP", "-p", pids.slice(0, 200).join(","), "-F", "pn"], { timeoutMs: 3_000, maxBytes: 1024 * 1024, ...runOpt });
+ return result ? parseLsofConnections(result.stdout) : [];
+ },
+ };
+}
+
+const WINDOWS_TREE_QUERY =
+ "$ErrorActionPreference='SilentlyContinue';[Console]::OutputEncoding=[Text.Encoding]::UTF8;"
+ + "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.Name)`t$($_.CommandLine)\" }";
+
+export function windowsSampler(run?: Runner, pollMs = 3_000): Sampler {
+ const runOpt = run ? { run } : {};
+ return {
+ method: "netstat",
+ pollMs,
+ async tree(selfPid) {
+ const result = await runTool("powershell", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_TREE_QUERY], { timeoutMs: 8_000, maxBytes: 4 * 1024 * 1024, ...runOpt });
+ return result && result.code === 0 ? descendantsOf(selfPid, parseWindowsProcesses(result.stdout)) : [];
+ },
+ async connections(pids) {
+ const wanted = new Set(pids);
+ const out: Array<{ pid: number; ip: string; port: number }> = [];
+ for (const family of ["TCP", "TCPv6"]) {
+ const result = await runTool("netstat", ["-ano", "-p", family], { timeoutMs: 5_000, maxBytes: 2 * 1024 * 1024, ...runOpt });
+ for (const row of parseNetstat(result?.stdout ?? "", "ESTABLISHED")) {
+ const remote = splitHostPort(row.remote);
+ if (remote && wanted.has(row.pid)) out.push({ pid: row.pid, ip: remote.address, port: remote.port });
+ }
+ }
+ return out;
+ },
+ };
+}
+
+export function defaultSampler(platform: NodeJS.Platform = process.platform): Sampler | null {
+ if (platform === "linux") return linuxSampler();
+ if (platform === "darwin") return macSampler();
+ if (platform === "win32") return windowsSampler();
+ return null;
+}
+
+// --- the observer -----------------------------------------------------------------------
+
+export type ObserverOptions = { sampler: Sampler; selfPid?: number; now?: () => number };
+
+/** Samples the tool shells' connections while a turn runs. */
+export class NetworkObserver {
+ private timer: ReturnType<typeof setTimeout> | null = null;
+ private roots = new Map<number, Root>();
+ private sampling: Promise<void> = Promise.resolve();
+ private active = false;
+ /** Processes already running when the turn began (a language server, an earlier turn's dev server): never a tool root. */
+ private preexisting: Set<number> | null = null;
+ /** Whether the last sample saw a tool shell running (sample faster then). */
+ private busy = false;
+ /** Time spent sampling (overhead measurement). */
+ sampleMs = 0;
+ samples = 0;
+
+ constructor(private readonly options: ObserverOptions) {}
+
+ get method(): string {
+ return this.options.sampler.method;
+ }
+
+ get pollMs(): number {
+ return this.options.sampler.pollMs;
+ }
+
+ start(): void {
+ this.stopTimer();
+ this.roots = new Map();
+ this.preexisting = null;
+ this.active = true;
+ this.schedule(0);
+ }
+
+ private schedule(delay: number): void {
+ if (!this.active) return;
+ this.timer = setTimeout(() => {
+ this.sampling = this.sample().catch(() => undefined).finally(() => this.schedule(this.busy ? this.options.sampler.activePollMs ?? this.options.sampler.pollMs : this.options.sampler.pollMs));
+ }, delay);
+ this.timer.unref?.();
+ }
+
+ private stopTimer(): void {
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = null;
+ }
+
+ /** One sample: the tool roots under this process and their connections. */
+ async sample(): Promise<void> {
+ const started = performance.now();
+ const now = (this.options.now ?? Date.now)();
+ const self = this.options.selfPid ?? process.pid;
+ const tree = await this.options.sampler.tree(self);
+ const byPid = new Map(tree.map((entry) => [entry.pid, entry]));
+ if (this.preexisting === null) {
+ // The first sample of the turn only notes what already runs.
+ this.preexisting = new Set(tree.map((entry) => entry.pid));
+ this.samples += 1;
+ this.sampleMs += performance.now() - started;
+ return;
+ }
+ // A tool root is the engine's direct child (bash may exec a lone command, so it need not be a shell),
+ // or the topmost `<shell> -c` when no engine is in the tree; without an engine, this process's children.
+ const engines = new Set(tree.filter((entry) => isEngineProcess(entry.argv)).map((entry) => entry.pid));
+ if (engines.size === 0) engines.add(self);
+ const rootOf = new Map<number, number>();
+ const findRoot = (pid: number): number => {
+ const known = rootOf.get(pid);
+ if (known !== undefined) return known;
+ const chain: number[] = [];
+ let current: ProcSample | undefined = byPid.get(pid);
+ let root = -1;
+ let shell = -1;
+ while (current) {
+ chain.push(current.pid);
+ if (shellCommandOf(current.argv) !== null) shell = current.pid;
+ if (engines.has(current.ppid)) {
+ root = current.pid;
+ break;
+ }
+ current = byPid.get(current.ppid);
+ }
+ if (root === -1) root = shell;
+ if (root !== -1 && (this.preexisting!.has(root) || engines.has(root))) root = -1;
+ for (const member of chain) if (!rootOf.has(member)) rootOf.set(member, root);
+ return root;
+ };
+ const members: number[] = [];
+ for (const entry of tree) {
+ const root = findRoot(entry.pid);
+ if (root === -1) continue;
+ members.push(entry.pid);
+ if (!this.roots.has(root) && this.roots.size < MAX_ROOTS_PER_TURN) {
+ const argv = byPid.get(root)!.argv;
+ this.roots.set(root, { pid: root, command: shellCommandOf(argv) ?? argv.join(" "), firstSeen: now, connections: new Map() });
+ }
+ }
+ this.busy = members.length > 0;
+ if (members.length > 0) {
+ for (const connection of await this.options.sampler.connections(members)) {
+ const root = rootOf.get(connection.pid);
+ const record = root !== undefined && root !== -1 ? this.roots.get(root) : undefined;
+ if (!record || record.connections.size >= MAX_CONNECTIONS_PER_CALL * 2) continue;
+ const key = `${connection.ip}|${connection.port}`;
+ if (!record.connections.has(key)) record.connections.set(key, { ip: connection.ip, port: connection.port, first: now });
+ }
+ }
+ this.samples += 1;
+ this.sampleMs += performance.now() - started;
+ }
+
+ /** Stops sampling (after one last sample) and hands back what the turn's tool shells reached. */
+ async stop(): Promise<Root[]> {
+ this.active = false;
+ this.stopTimer();
+ await this.sampling;
+ await this.sample().catch(() => undefined);
+ const roots = [...this.roots.values()];
+ this.roots = new Map();
+ return roots;
+ }
+}
+
+// --- naming hosts and attributing roots to calls -------------------------------------
+
+const HOST_IN_COMMAND = /(?:[a-z][a-z0-9+.-]*:\/\/(?:[^@/\s]*@)?([^/:\s"'?#]+))|(?:[\w.-]+@([a-z0-9.-]+\.[a-z]{2,}):)|(?<![\w/.@:-])((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,24})\b/gi;
+const FILE_EXTENSIONS = new Set(["git", "js", "ts", "py", "json", "md", "txt", "sh", "yml", "yaml", "toml", "lock", "tsx", "jsx", "go", "rs", "rb", "html", "css", "log", "cfg", "ini", "zip", "gz", "tgz", "tar", "whl", "csv", "xml", "env", "mjs", "cjs", "map", "so", "dll", "exe", "pyc", "java", "kt", "c", "h", "cpp", "php", "sql"]);
+
+/** Registries a package manager or tool reaches without naming them in the command. */
+const KNOWN_HOSTS: Array<[RegExp, string[]]> = [
+ [/\b(?:npm|npx|pnpm|pnpx|yarn|bun|bunx|corepack)\b/, ["registry.npmjs.org", "registry.yarnpkg.com"]],
+ [/\b(?:pip3?|uv|uvx|pipx|poetry|pipenv|twine)\b/, ["pypi.org", "files.pythonhosted.org"]],
+ [/\bgo\b/, ["proxy.golang.org", "sum.golang.org"]],
+ [/\b(?:cargo|rustup)\b/, ["index.crates.io", "static.crates.io", "static.rust-lang.org"]],
+ [/\b(?:gem|bundle|bundler)\b/, ["rubygems.org", "index.rubygems.org"]],
+ [/\b(?:git|gh)\b/, ["github.com", "api.github.com", "codeload.github.com", "objects.githubusercontent.com"]],
+ [/\b(?:docker|podman)\b/, ["registry-1.docker.io", "auth.docker.io", "production.cloudflare.docker.com"]],
+ [/\b(?:mvn|gradle|gradlew)\b/, ["repo.maven.apache.org", "repo1.maven.org", "plugins.gradle.org"]],
+ [/\bcomposer\b/, ["repo.packagist.org"]],
+ [/\bdeno\b/, ["jsr.io", "deno.land", "registry.npmjs.org"]],
+];
+
+export function knownHostsOf(command: string): string[] {
+ const out = new Set<string>();
+ for (const [pattern, hosts] of KNOWN_HOSTS) if (pattern.test(command)) for (const host of hosts) out.add(host);
+ return [...out];
+}
+
+/** Hostnames a command names (URLs, git@host:, bare domain names; file names excluded). */
+export function hostnamesInCommand(command: string): string[] {
+ const out = new Set<string>();
+ for (const match of command.matchAll(HOST_IN_COMMAND)) {
+ const host = (match[1] ?? match[2] ?? match[3] ?? "").toLowerCase().replace(/\.$/, "");
+ if (!host || /^\d+(?:\.\d+)*$/.test(host)) continue;
+ const tld = host.split(".").at(-1)!;
+ if (!match[1] && !match[2] && FILE_EXTENSIONS.has(tld)) continue;
+ out.add(host);
+ if (out.size >= 20) break;
+ }
+ return [...out];
+}
+
+function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {
+ return Promise.race([promise.catch(() => null), new Promise<null>((resolve) => setTimeout(() => resolve(null), ms).unref?.())]);
+}
+
+export type HostResolver = { lookup: (host: string) => Promise<string[]>; reverse: (ip: string) => Promise<string[]> };
+export const SYSTEM_RESOLVER: HostResolver = {
+ lookup: async (host) => (await dns.lookup(host, { all: true, verbatim: true })).map((entry) => entry.address),
+ reverse: (ip) => dns.reverse(ip),
+};
+
+function normalizeIp(ip: string): string {
+ return ip.toLowerCase().replace(/^::ffff:(?=\d+\.)/, "");
+}
+
+/** Names the remote endpoints: from the command's hostnames, else reverse DNS (short timeout); never the raw address. */
+export async function nameConnections(seen: Seen[], command: string, resolver: HostResolver = SYSTEM_RESOLVER): Promise<Connection[]> {
+ const byIp = new Map<string, { host: string; by: "command" | "known_host" }>();
+ const named = hostnamesInCommand(command);
+ const candidates: Array<[string, "command" | "known_host"]> = [...named.map((host) => [host, "command"] as [string, "command"]), ...knownHostsOf(command).filter((host) => !named.includes(host)).map((host) => [host, "known_host"] as [string, "known_host"])];
+ // Looked up together, assigned in order: a host the command names wins, then the first known registry.
+ const answers = await Promise.all(candidates.map(([host]) => withTimeout(resolver.lookup(host), 1_000)));
+ candidates.forEach(([host, by], index) => {
+ for (const ip of answers[index] ?? []) {
+ const key = normalizeIp(ip);
+ if (!byIp.has(key)) byIp.set(key, { host, by });
+ }
+ });
+ const reverse = new Map<string, Promise<string | null>>();
+ const out: Connection[] = [];
+ for (const entry of seen.slice(0, MAX_CONNECTIONS_PER_CALL)) {
+ const ip = normalizeIp(entry.ip);
+ const cls = addressClass(ip);
+ const match = byIp.get(ip);
+ let host: string | null = match?.host ?? null;
+ let by: Connection["resolved_by"] = match?.by ?? null;
+ if (!host && cls === "loopback") {
+ host = "localhost";
+ by = "loopback";
+ }
+ if (!host && cls !== "any") {
+ if (!reverse.has(ip)) reverse.set(ip, withTimeout(resolver.reverse(ip), 500).then((names) => names?.[0] ?? null));
+ host = await reverse.get(ip)!;
+ if (host) by = "reverse";
+ }
+ out.push({ host, port: entry.port, address_class: cls, resolved_by: by, first_seen: new Date(entry.first).toISOString() });
+ }
+ // One row per (host or class, port).
+ const unique = new Map<string, Connection>();
+ for (const connection of out) {
+ const key = `${connection.host ?? connection.address_class}|${connection.port}`;
+ if (!unique.has(key)) unique.set(key, connection);
+ }
+ return [...unique.values()];
+}
+
+function normalizeCommand(command: string): string {
+ return command.replace(/["'\\]/g, "").replace(/\s+/g, " ").trim();
+}
+
+function sameCommand(left: string, right: string): boolean {
+ const a = normalizeCommand(left);
+ const b = normalizeCommand(right);
+ return a === b || (a.length > 0 && b.length > 0 && (a.includes(b) || b.includes(a)));
+}
+
+/** Matches the turn's tool shells to its shell calls; what matches no call is the turn's. */
+export async function attributeConnections(
+ roots: Root[],
+ calls: ToolCall[],
+ context: { turn: number; method: string; pollMs: number; resolver?: HostResolver },
+): Promise<NetworkEvent[]> {
+ const shellCalls = calls.filter((call) => call.command);
+ const perCall = new Map<ToolCall, Seen[]>();
+ const turn: Seen[] = [];
+ const turnCommands: string[] = [];
+ for (const root of roots) {
+ if (root.connections.size === 0) continue;
+ const candidates = shellCalls.filter((call) => sameCommand(call.command!, root.command));
+ const timed = candidates.filter((call) => call.start === null || (root.firstSeen >= call.start - 2_000 && (call.end === null || root.firstSeen <= call.end + 2_000)));
+ const call = (timed.length > 0 ? timed : candidates)[0];
+ if (call) perCall.set(call, [...(perCall.get(call) ?? []), ...root.connections.values()]);
+ else {
+ turn.push(...root.connections.values());
+ turnCommands.push(root.command);
+ }
+ }
+ const events: NetworkEvent[] = [];
+ for (const [call, seen] of perCall) {
+ const connections = await nameConnections(seen, call.command ?? "", context.resolver);
+ events.push({ tool_call_id: call.callId, tool: call.tool, scope: "call", turn: context.turn, method: context.method, poll_ms: context.pollMs, connections, truncated: seen.length > MAX_CONNECTIONS_PER_CALL });
+ }
+ if (turn.length > 0) {
+ const connections = await nameConnections(turn, turnCommands.join("\n"), context.resolver);
+ events.push({ tool_call_id: null, tool: "bash", scope: "turn", turn: context.turn, method: context.method, poll_ms: context.pollMs, connections, truncated: turn.length > MAX_CONNECTIONS_PER_CALL });
+ }
+ return events;
+}
diff --git a/apps/server/src/context/outside.ts b/apps/server/src/context/outside.ts
new file mode 100644
index 00000000..87f16015
--- /dev/null
+++ b/apps/server/src/context/outside.ts
@@ -0,0 +1,370 @@
+// #10 Folders outside the project the agent built or ran things in, and the
+// scripts outside the project it executed; #21 files it wrote under a temp
+// folder and used again later.
+//
+// - A folder a command created (mkdir, git clone, npm create, cargo new, a
+// recursive copy, an extraction) is captured whole; a folder it only
+// worked in (cd, a tool's workdir) contributes the files created or
+// changed since the session started. Each file is reported to the
+// project archive (byte-exact under `__outside__/`, with the archive's
+// policy, denylist and caps), regenerable folders (node_modules, .venv,
+// build output, .git, …) are left out, and the session's total is capped
+// (200 MiB). A `context.outside_folder` event describes each folder.
+// - A script outside the project the agent ran (bash x.sh, python x.py,
+// ./x, source x) and a temp file it wrote and later read or ran are
+// recorded as `context.outside_file` with their text (scrubbed, 256 KiB
+// per file, 4 MiB per session) and reported to the archive too.
+
+import { createHash } from "node:crypto";
+import { lstat, readdir, readFile, realpath } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { isAbsolute, join, relative, resolve, sep } from "node:path";
+
+import { commandEffects, toolKind, toolPaths, type FolderVia, type ToolCall } from "./commands.js";
+import { capUtf8, isTextBuffer, tildePath, tildeText, type PrivacyContext, type Scrubber } from "./privacy.js";
+
+export const MAX_OUTSIDE_FOLDER_TOTAL_BYTES = 200 * 1024 * 1024;
+export const MAX_OUTSIDE_FOLDER_FILE_BYTES = 100 * 1024 * 1024;
+export const MAX_INLINE_FILE_BYTES = 256 * 1024;
+export const MAX_INLINE_TOTAL_BYTES = 4 * 1024 * 1024;
+const MAX_FOLDER_ENTRIES = 20_000;
+const MAX_FOLDER_DEPTH = 12;
+const MAX_FOLDERS = 100;
+const MAX_TRACKED_TEMP = 5_000;
+
+export const SKIPPED_DIR_NAMES = new Set([
+ ".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__", ".tox", ".nox", ".mypy_cache", ".pytest_cache", ".ruff_cache",
+ "dist", "build", "target", "out", ".next", ".nuxt", ".svelte-kit", ".turbo", ".parcel-cache", ".cache", ".gradle", ".dart_tool",
+ "Pods", "DerivedData", "vendor", "bower_components", "site-packages", ".pnpm-store", ".yarn",
+]);
+
+export type OutsideFolderEvent = {
+ path: string;
+ reason: "created" | "modified";
+ via: FolderVia;
+ tool_call_id: string | null;
+ files: number;
+ bytes: number;
+ truncated: boolean;
+ excluded_regenerable: number;
+};
+
+export type OutsideFileEvent = {
+ kind: "temp" | "executed";
+ path: string;
+ tool_call_id: string | null;
+ written_by: string | null;
+ sha256: string;
+ bytes: number;
+ content: string | null;
+ binary?: true;
+ truncated?: true;
+};
+
+/** The temp folders of this machine (as given and as real paths). */
+export function tempRoots(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string[] {
+ const roots = new Set<string>();
+ const add = (value: string | undefined) => {
+ if (value && isAbsolute(value)) roots.add(resolve(value));
+ };
+ add(tmpdir());
+ add(env.TMPDIR);
+ add(env.TEMP);
+ add(env.TMP);
+ if (platform !== "win32") {
+ add("/tmp");
+ add("/var/tmp");
+ add("/private/tmp");
+ add("/private/var/tmp");
+ } else {
+ add(env.SystemRoot ? join(env.SystemRoot, "Temp") : "C:\\Windows\\Temp");
+ }
+ return [...roots];
+}
+
+function within(parent: string, child: string): boolean {
+ const rel = relative(parent, child);
+ return rel === "" || (!!rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
+}
+
+/** macOS per-user temp folders: /private/var/folders/xx/yyyy/T (and /var/folders/…). */
+export function isTempPath(path: string, roots: readonly string[]): boolean {
+ if (/^(?:\/private)?\/var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/.test(path)) return true;
+ return roots.some((root) => within(root, path) && path !== root);
+}
+
+export type OutsideOptions = {
+ root: string;
+ sessionStartMs: number;
+ privacy: PrivacyContext;
+ scrub: Scrubber;
+ /**
+ * The archive's exclusion of an absolute path (credential files and
+ * stores, the app's state, dependency/cache folders, pseudo file systems),
+ * or null when it may be archived.
+ */
+ exclusion: (absolute: string) => string | null;
+ /** Reports a file to the project archive (byte-exact copy under `__outside__/`). */
+ reportPath: (absolute: string) => void;
+ tempRoots?: string[];
+ maxFolderBytes?: number;
+ maxInlineBytes?: number;
+};
+
+type Folder = { path: string; via: FolderVia; created: boolean; callId: string | null; reported: Set<string>; bytes: number; regenerable: number; truncated: boolean };
+
+/** Per-session tracker; feed it each turn's tool calls in order. */
+export class OutsideTracker {
+ private readonly roots: string[];
+ private readonly temps: string[];
+ private readonly folders = new Map<string, Folder>();
+ private readonly tempWrites = new Map<string, string | null>();
+ private readonly tempFolders = new Map<string, string | null>();
+ private readonly inlined = new Set<string>();
+ private folderBytes = 0;
+ private inlineBytes = 0;
+ private realRoot: string | null = null;
+
+ constructor(private readonly options: OutsideOptions) {
+ this.roots = [resolve(options.root)];
+ this.temps = options.tempRoots ?? tempRoots();
+ }
+
+ private outsideProject(path: string): boolean {
+ return !this.roots.some((root) => within(root, path)) && !(this.realRoot && within(this.realRoot, path));
+ }
+
+ /** A folder that must never be expanded: the home, a file system root, an ancestor of the project, a system or excluded folder. */
+ private unsafeFolder(path: string): boolean {
+ const home = this.options.privacy.home;
+ if (home && (path === resolve(home) || within(path, resolve(home)))) return true;
+ if (resolve(path) === resolve(path, "/") || /^[A-Za-z]:\\?$/.test(path)) return true;
+ if (this.roots.some((root) => within(path, root))) return true;
+ if (this.temps.some((temp) => path === temp || within(path, temp))) return true;
+ if (/^\/[^/]*$/.test(path)) return true;
+ if (/^\/(?:usr|etc|bin|sbin|lib|lib32|lib64|proc|sys|dev|run|boot|System|Library|private\/etc|private\/var\/db)(?:\/|$)/.test(path)) return true;
+ if (/^[A-Za-z]:\\(?:Windows|Program Files|Program Files \(x86\)|ProgramData)(?:\\|$)/i.test(path)) return true;
+ return this.options.exclusion(path) !== null;
+ }
+
+ /** Processes one turn's tool calls; returns the events to record. */
+ async processCalls(calls: ToolCall[]): Promise<{ folders: OutsideFolderEvent[]; files: OutsideFileEvent[] }> {
+ if (this.realRoot === null) {
+ try {
+ this.realRoot = await realpath(this.options.root);
+ } catch {
+ this.realRoot = resolve(this.options.root);
+ }
+ }
+ const home = this.options.privacy.home;
+ const files: OutsideFileEvent[] = [];
+ const touchedFolders = new Set<Folder>();
+ const useTemp = async (path: string, call: ToolCall, kind: "temp" | "executed") => {
+ const writer = this.tempWrites.get(path) ?? [...this.tempFolders].find(([folder]) => within(folder, path))?.[1];
+ const known = this.tempWrites.has(path) || [...this.tempFolders.keys()].some((folder) => within(folder, path));
+ if (!known) return;
+ const event = await this.inline(path, kind === "executed" ? "temp" : kind, call.callId, writer ?? null);
+ if (event) files.push(event);
+ };
+ for (const call of calls) {
+ const kind = toolKind(call.tool);
+ if (call.cwd && this.outsideProject(call.cwd) && resolve(call.cwd) !== resolve(this.options.root)) {
+ const folder = this.addFolder(call.cwd, "workdir", false, call.callId);
+ if (folder) touchedFolders.add(folder);
+ }
+ if (kind === "write") {
+ for (const path of toolPaths(call, home)) if (isTempPath(path, this.temps)) this.trackTemp(path, call.callId);
+ continue;
+ }
+ if (kind === "read") {
+ for (const path of toolPaths(call, home)) await useTemp(path, call, "temp");
+ continue;
+ }
+ if (kind !== "shell" || !call.command) continue;
+ const effects = commandEffects(call.command, call.cwd, home);
+ // Uses first (a read of a file written by an earlier call), then this call's own writes.
+ for (const path of new Set(effects.named)) if (!effects.writes.includes(path)) await useTemp(path, call, "temp");
+ for (const path of effects.writes) if (isTempPath(path, this.temps)) this.trackTemp(path, call.callId);
+ for (const entry of effects.folders) {
+ if (isTempPath(entry.path, this.temps) && entry.created) this.tempFolders.set(entry.path, call.callId);
+ if (!this.outsideProject(entry.path)) continue;
+ const folder = this.addFolder(entry.path, entry.via, entry.created, call.callId);
+ if (folder) touchedFolders.add(folder);
+ }
+ for (const path of new Set(effects.executed)) {
+ if (!this.outsideProject(path)) continue;
+ if (isTempPath(path, this.temps)) {
+ await useTemp(path, call, "temp");
+ if (!this.tempWrites.has(path)) {
+ const event = await this.inline(path, "executed", call.callId, null);
+ if (event) files.push(event);
+ }
+ continue;
+ }
+ const event = await this.inline(path, "executed", call.callId, null);
+ if (event) files.push(event);
+ }
+ }
+ const folders: OutsideFolderEvent[] = [];
+ for (const folder of touchedFolders) {
+ const event = await this.scanFolder(folder);
+ if (event) folders.push(event);
+ }
+ return { folders, files };
+ }
+
+ private trackTemp(path: string, callId: string | null): void {
+ if (this.tempWrites.size >= MAX_TRACKED_TEMP) return;
+ this.tempWrites.set(path, callId);
+ }
+
+ private addFolder(path: string, via: FolderVia, created: boolean, callId: string | null): Folder | null {
+ const existing = this.folders.get(path);
+ if (existing) {
+ if (created && !existing.created) {
+ existing.created = true;
+ existing.via = via;
+ }
+ return existing;
+ }
+ // Inside a folder already tracked: that one covers it.
+ for (const folder of this.folders.values()) if (within(folder.path, path) && (folder.created || !created)) return folder;
+ if (this.folders.size >= MAX_FOLDERS || this.unsafeFolder(path)) return null;
+ const folder: Folder = { path, via, created, callId, reported: new Set(), bytes: 0, regenerable: 0, truncated: false };
+ this.folders.set(path, folder);
+ return folder;
+ }
+
+ /** Reports the folder's files (all for a created folder, those changed this session otherwise) within the budget. */
+ private async scanFolder(folder: Folder): Promise<OutsideFolderEvent | null> {
+ const limit = this.options.maxFolderBytes ?? MAX_OUTSIDE_FOLDER_TOTAL_BYTES;
+ let rootStats;
+ try {
+ rootStats = await lstat(folder.path);
+ } catch {
+ return null;
+ }
+ if (!rootStats.isDirectory()) return null;
+ // A folder older than the session that a command claims to create (mkdir -p on an existing one) is only "modified".
+ const createdNow = folder.created && (rootStats.birthtimeMs || rootStats.ctimeMs) >= this.options.sessionStartMs - 1_000;
+ let entries = 0;
+ let regenerable = 0;
+ let added = 0;
+ const walk = async (dir: string, depth: number): Promise<void> => {
+ if (depth > MAX_FOLDER_DEPTH || entries >= MAX_FOLDER_ENTRIES) {
+ folder.truncated = true;
+ return;
+ }
+ let children;
+ try {
+ children = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ children.sort((a, b) => a.name.localeCompare(b.name));
+ for (const child of children) {
+ entries += 1;
+ if (entries >= MAX_FOLDER_ENTRIES) {
+ folder.truncated = true;
+ return;
+ }
+ const path = join(dir, child.name);
+ if (child.isDirectory()) {
+ if (SKIPPED_DIR_NAMES.has(child.name)) {
+ regenerable += 1;
+ continue;
+ }
+ await walk(path, depth + 1);
+ continue;
+ }
+ if (!child.isFile() || folder.reported.has(path)) continue;
+ let stats;
+ try {
+ stats = await lstat(path);
+ } catch {
+ continue;
+ }
+ // Modified: written since the session started (mtime; ctime also moves on a chmod or a metadata change).
+ if (!createdNow && stats.mtimeMs < this.options.sessionStartMs) continue;
+ if (stats.size > MAX_OUTSIDE_FOLDER_FILE_BYTES || this.options.exclusion(path) !== null) continue;
+ if (this.folderBytes + stats.size > limit) {
+ folder.truncated = true;
+ continue;
+ }
+ this.folderBytes += stats.size;
+ folder.bytes += stats.size;
+ folder.reported.add(path);
+ added += 1;
+ try {
+ this.options.reportPath(path);
+ } catch {
+ // The archive's bookkeeping never stops capture.
+ }
+ }
+ };
+ await walk(folder.path, 0);
+ folder.regenerable = Math.max(folder.regenerable, regenerable);
+ if (added === 0 && folder.reported.size === 0) return null;
+ if (added === 0) return null;
+ return {
+ path: tildePath(folder.path, this.options.privacy),
+ reason: createdNow ? "created" : "modified",
+ via: folder.via,
+ tool_call_id: folder.callId,
+ files: folder.reported.size,
+ bytes: folder.bytes,
+ truncated: folder.truncated,
+ excluded_regenerable: folder.regenerable,
+ };
+ }
+
+ /** One file's text for the record (once per content), reported to the archive as well. */
+ private async inline(path: string, kind: "temp" | "executed", callId: string | null, writer: string | null): Promise<OutsideFileEvent | null> {
+ const reason = this.options.exclusion(path);
+ if (reason && !(reason === "dependency" && isTempPath(path, this.temps))) return null;
+ let buffer: Buffer;
+ try {
+ const stats = await lstat(path);
+ if (!stats.isFile() || stats.size > 64 * 1024 * 1024) return null;
+ buffer = await readFile(path);
+ } catch {
+ return null;
+ }
+ const sha256 = createHash("sha256").update(buffer).digest("hex");
+ const key = `${path}\0${sha256}`;
+ if (this.inlined.has(key)) return null;
+ this.inlined.add(key);
+ if (!reason) {
+ try {
+ this.options.reportPath(path);
+ } catch {
+ // Ignored.
+ }
+ }
+ const text = isTextBuffer(buffer);
+ let content: string | null = null;
+ let truncated = false;
+ if (text) {
+ const room = Math.min(MAX_INLINE_FILE_BYTES, (this.options.maxInlineBytes ?? MAX_INLINE_TOTAL_BYTES) - this.inlineBytes);
+ if (room > 0) {
+ const capped = capUtf8(buffer.toString("utf8"), room);
+ truncated = capped.truncated;
+ this.inlineBytes += Buffer.byteLength(capped.text);
+ content = tildeText(this.options.scrub.content(path, capped.text), this.options.privacy);
+ } else {
+ truncated = true;
+ }
+ }
+ return {
+ kind,
+ path: tildePath(path, this.options.privacy),
+ tool_call_id: callId,
+ written_by: writer,
+ sha256,
+ bytes: buffer.length,
+ content,
+ ...(text ? {} : { binary: true as const }),
+ ...(truncated ? { truncated: true as const } : {}),
+ };
+ }
+}
diff --git a/apps/server/src/context/pm-config.ts b/apps/server/src/context/pm-config.ts
new file mode 100644
index 00000000..b3be253f
--- /dev/null
+++ b/apps/server/src/context/pm-config.ts
@@ -0,0 +1,280 @@
+// #17 Package-manager and toolchain configuration outside the project:
+// ~/.npmrc, ~/.yarnrc(.yml), pip.conf / pip.ini, uv.toml,
+// ~/.cargo/config.toml, ~/.gradle/gradle.properties, ~/.m2/settings.xml,
+// .condarc and `go env`. Only keys and non-secret values are kept: every
+// key naming a credential (auth, token, password, _auth, credential, …) is
+// dropped entirely, URLs lose their userinfo and secret query values, and
+// the secret scrub runs on top of what is left.
+
+import { readFile, stat } from "node:fs/promises";
+import { join } from "node:path";
+
+import { runTool, type Runner } from "./exec.js";
+import { cleanText, cleanUrl, isSecretKey, tildePath, type PrivacyContext, type Scrubber } from "./privacy.js";
+
+const MAX_CONFIG_FILE_BYTES = 256 * 1024;
+const MAX_ENTRIES_PER_FILE = 200;
+const MAX_VALUE_CHARS = 1_000;
+
+export type PmTool = "npm" | "yarn" | "pip" | "uv" | "cargo" | "gradle" | "maven" | "conda";
+export type PmConfigFile = { tool: PmTool; path: string; entries: Record<string, string>; dropped_keys: number };
+export type PmConfig = { files: PmConfigFile[]; go_env?: Record<string, string> };
+
+export const GO_ENV_KEYS = ["GOPROXY", "GOPRIVATE", "GONOPROXY", "GONOSUMDB", "GONOSUMCHECK", "GOSUMDB", "GOINSECURE", "GOFLAGS", "GO111MODULE", "GOTOOLCHAIN"];
+
+/** `key=value` lines (npmrc, gradle.properties); `#` and `;` comments; [sections] prefix their keys. */
+export function parseIni(text: string, separators = /[=:]/): Array<[string, string]> {
+ const out: Array<[string, string]> = [];
+ let section = "";
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line || line.startsWith("#") || line.startsWith(";")) continue;
+ const header = /^\[([^\]]+)\]$/.exec(line);
+ if (header) {
+ section = header[1]!.trim();
+ continue;
+ }
+ const match = separators.exec(line);
+ if (!match || match.index === 0) continue;
+ const key = line.slice(0, match.index).trim();
+ let value = line.slice(match.index + 1).trim();
+ value = value.replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
+ out.push([section ? `${section}.${key}` : key, value]);
+ }
+ return out;
+}
+
+/** npmrc keys may hold `=` in a scoped registry (`//host/:_authToken=x`): the first `=` separates. */
+export function parseNpmrc(text: string): Array<[string, string]> {
+ return parseIni(text, /=/);
+}
+
+/** Yarn 1 `.yarnrc`: `key "value"` or `key value`. */
+export function parseYarnrc(text: string): Array<[string, string]> {
+ const out: Array<[string, string]> = [];
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line || line.startsWith("#")) continue;
+ const match = /^("?)([^"\s]+)\1\s+(.+)$/.exec(line);
+ if (match) out.push([match[2]!, match[3]!.trim().replace(/^"(.*)"$/, "$1")]);
+ }
+ return out;
+}
+
+/**
+ * A light YAML reader for the flat configs (.yarnrc.yml, .condarc): nested
+ * mappings become dotted keys, `- item` lists become `key[0]`, values are
+ * taken as written (quotes dropped). Anchors, flow maps and multi-line
+ * scalars are kept as raw text.
+ */
+export function parseSimpleYaml(text: string): Array<[string, string]> {
+ const out: Array<[string, string]> = [];
+ const stack: Array<{ indent: number; key: string; index: number }> = [];
+ for (const raw of text.split(/\r?\n/)) {
+ if (!raw.trim() || raw.trim().startsWith("#")) continue;
+ const indent = raw.length - raw.trimStart().length;
+ const line = raw.trim();
+ while (stack.length > 0 && stack[stack.length - 1]!.indent >= indent && !(line.startsWith("- ") && stack[stack.length - 1]!.indent === indent)) stack.pop();
+ const prefix = stack.map((entry) => entry.key).join(".");
+ if (line.startsWith("- ")) {
+ const parent = stack[stack.length - 1];
+ const index = parent ? parent.index++ : 0;
+ const value = line.slice(2).trim().replace(/^["'](.*)["']$/, "$1");
+ out.push([`${prefix}[${index}]`, value]);
+ continue;
+ }
+ const match = /^("?)([^":]+)\1\s*:(?:\s+(.*))?$/.exec(line);
+ if (!match) continue;
+ const key = match[2]!.trim();
+ const value = (match[3] ?? "").trim().replace(/\s+#.*$/, "");
+ if (value === "" || value === "|" || value === ">") {
+ stack.push({ indent, key, index: 0 });
+ continue;
+ }
+ out.push([prefix ? `${prefix}.${key}` : key, value.replace(/^["'](.*)["']$/, "$1")]);
+ }
+ return out;
+}
+
+/** A light TOML reader (uv.toml, cargo config): `[table]`, `[[array]]` and `key = value`. */
+export function parseSimpleToml(text: string): Array<[string, string]> {
+ const out: Array<[string, string]> = [];
+ let table = "";
+ const arrays = new Map<string, number>();
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line || line.startsWith("#")) continue;
+ const arrayHeader = /^\[\[([^\]]+)\]\]$/.exec(line);
+ if (arrayHeader) {
+ const name = arrayHeader[1]!.trim();
+ const index = arrays.get(name) ?? 0;
+ arrays.set(name, index + 1);
+ table = `${name}[${index}]`;
+ continue;
+ }
+ const header = /^\[([^\]]+)\]$/.exec(line);
+ if (header) {
+ table = header[1]!.trim().replace(/"/g, "");
+ continue;
+ }
+ const match = /^([^=]+?)\s*=\s*(.*)$/.exec(line);
+ if (!match) continue;
+ const key = match[1]!.trim().replace(/"/g, "");
+ const value = match[2]!.trim().replace(/\s+#[^"']*$/, "").replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
+ out.push([table ? `${table}.${key}` : key, value]);
+ }
+ return out;
+}
+
+/**
+ * Maven settings.xml: mirrors (id, url, mirrorOf), proxies (protocol, host,
+ * port, nonProxyHosts), repository URLs, server ids and the offline/local
+ * repository flags. Usernames, passwords, private keys and passphrases are
+ * never read.
+ */
+export function parseMavenSettings(text: string): Array<[string, string]> {
+ const out: Array<[string, string]> = [];
+ const noComments = text.replace(/<!--[\s\S]*?-->/g, "");
+ const tag = (block: string, name: string) => new RegExp(`<${name}>\\s*([^<]*?)\\s*</${name}>`).exec(block)?.[1] ?? null;
+ const blocks = (name: string) => [...noComments.matchAll(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`, "g"))].map((m) => m[1]!);
+ for (const flag of ["localRepository", "offline", "interactiveMode"]) {
+ const value = tag(noComments, flag);
+ if (value !== null) out.push([flag, value]);
+ }
+ blocks("mirror").forEach((block, index) => {
+ for (const name of ["id", "url", "mirrorOf"]) {
+ const value = tag(block, name);
+ if (value !== null) out.push([`mirrors[${index}].${name}`, value]);
+ }
+ });
+ blocks("proxy").forEach((block, index) => {
+ for (const name of ["id", "active", "protocol", "host", "port", "nonProxyHosts"]) {
+ const value = tag(block, name);
+ if (value !== null) out.push([`proxies[${index}].${name}`, value]);
+ }
+ });
+ blocks("repository").concat(blocks("pluginRepository")).forEach((block, index) => {
+ for (const name of ["id", "url"]) {
+ const value = tag(block, name);
+ if (value !== null) out.push([`repositories[${index}].${name}`, value]);
+ }
+ });
+ blocks("server").forEach((block, index) => {
+ const id = tag(block, "id");
+ if (id !== null) out.push([`servers[${index}].id`, id]);
+ });
+ return out;
+}
+
+/** Whether a config entry must be dropped whole: its key names a credential. */
+export function isDroppedKey(key: string): boolean {
+ // `//registry.npmjs.org/:_authToken`, `npmScopes.acme.npmAuthToken`, `registries.x.token`, `pip.index-url` stays.
+ const parts = key.split(/[.:/[\]]+/).filter(Boolean);
+ return parts.some((part) => isSecretKey(part)) || isSecretKey(key.split(/[:/]/).at(-1) ?? key);
+}
+
+/** A kept value: URLs cleaned, the home as `~`, secrets scrubbed, at most 1000 chars. */
+function cleanValue(value: string, privacy: PrivacyContext, scrub: Scrubber): string {
+ const urls = value.replace(/[a-z][a-z0-9+.-]*:\/\/[^\s,;"']+/gi, (url) => cleanUrl(url));
+ const cleaned = cleanText(urls, privacy, scrub);
+ return cleaned.length > MAX_VALUE_CHARS ? `${cleaned.slice(0, MAX_VALUE_CHARS)}…` : cleaned;
+}
+
+export function filterEntries(pairs: Array<[string, string]>, privacy: PrivacyContext, scrub: Scrubber): { entries: Record<string, string>; dropped: number } {
+ const entries: Record<string, string> = {};
+ let dropped = 0;
+ for (const [key, value] of pairs) {
+ if (isDroppedKey(key)) {
+ dropped += 1;
+ continue;
+ }
+ if (Object.keys(entries).length >= MAX_ENTRIES_PER_FILE) break;
+ const cleanKey = cleanText(key, privacy, scrub);
+ entries[cleanKey] = cleanValue(value, privacy, scrub);
+ }
+ return { entries, dropped };
+}
+
+type Source = { tool: PmTool; path: string; parse: (text: string) => Array<[string, string]> };
+
+/** The user/global config files each tool reads, for this platform. */
+export function configSources(home: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv = process.env): Source[] {
+ const appData = env.APPDATA ?? join(home, "AppData", "Roaming");
+ const xdg = env.XDG_CONFIG_HOME ?? join(home, ".config");
+ const sources: Source[] = [
+ { tool: "npm", path: env.NPM_CONFIG_USERCONFIG ?? env.npm_config_userconfig ?? join(home, ".npmrc"), parse: parseNpmrc },
+ { tool: "yarn", path: join(home, ".yarnrc"), parse: parseYarnrc },
+ { tool: "yarn", path: join(home, ".yarnrc.yml"), parse: parseSimpleYaml },
+ { tool: "uv", path: join(platform === "win32" ? appData : xdg, "uv", "uv.toml"), parse: parseSimpleToml },
+ { tool: "cargo", path: join(env.CARGO_HOME ?? join(home, ".cargo"), "config.toml"), parse: parseSimpleToml },
+ { tool: "cargo", path: join(env.CARGO_HOME ?? join(home, ".cargo"), "config"), parse: parseSimpleToml },
+ { tool: "gradle", path: join(env.GRADLE_USER_HOME ?? join(home, ".gradle"), "gradle.properties"), parse: (text) => parseIni(text) },
+ { tool: "maven", path: join(home, ".m2", "settings.xml"), parse: parseMavenSettings },
+ { tool: "conda", path: join(home, ".condarc"), parse: parseSimpleYaml },
+ { tool: "conda", path: join(home, ".conda", ".condarc"), parse: parseSimpleYaml },
+ { tool: "conda", path: join(xdg, "conda", ".condarc"), parse: parseSimpleYaml },
+ ];
+ if (platform === "win32") {
+ sources.push({ tool: "pip", path: join(appData, "pip", "pip.ini"), parse: (text) => parseIni(text) });
+ sources.push({ tool: "pip", path: join(home, "pip", "pip.ini"), parse: (text) => parseIni(text) });
+ } else {
+ sources.push({ tool: "pip", path: join(xdg, "pip", "pip.conf"), parse: (text) => parseIni(text) });
+ sources.push({ tool: "pip", path: join(home, ".pip", "pip.conf"), parse: (text) => parseIni(text) });
+ sources.push({ tool: "pip", path: "/etc/pip.conf", parse: (text) => parseIni(text) });
+ if (platform === "darwin") sources.push({ tool: "pip", path: join(home, "Library", "Application Support", "pip", "pip.conf"), parse: (text) => parseIni(text) });
+ }
+ if (env.PIP_CONFIG_FILE) sources.push({ tool: "pip", path: env.PIP_CONFIG_FILE, parse: (text) => parseIni(text) });
+ if (env.UV_CONFIG_FILE) sources.push({ tool: "uv", path: env.UV_CONFIG_FILE, parse: parseSimpleToml });
+ if (env.CONDARC) sources.push({ tool: "conda", path: env.CONDARC, parse: parseSimpleYaml });
+ return sources;
+}
+
+export type PmConfigOptions = {
+ privacy: PrivacyContext;
+ scrub: Scrubber;
+ platform?: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ run?: Runner;
+ resolve?: (command: string) => string | null;
+};
+
+export async function collectPmConfig(options: PmConfigOptions): Promise<PmConfig> {
+ const home = options.privacy.home;
+ const platform = options.platform ?? process.platform;
+ const files: PmConfigFile[] = [];
+ if (home) {
+ const seen = new Set<string>();
+ for (const source of configSources(home, platform, options.env)) {
+ if (seen.has(source.path)) continue;
+ seen.add(source.path);
+ try {
+ const info = await stat(source.path);
+ if (!info.isFile() || info.size > MAX_CONFIG_FILE_BYTES) continue;
+ const text = await readFile(source.path, "utf8");
+ const { entries, dropped } = filterEntries(source.parse(text), options.privacy, options.scrub);
+ if (Object.keys(entries).length === 0 && dropped === 0) continue;
+ files.push({ tool: source.tool, path: tildePath(source.path, options.privacy), entries, dropped_keys: dropped });
+ } catch {
+ // Not there.
+ }
+ }
+ }
+ const result: PmConfig = { files };
+ const go = await runTool("go", ["env", "-json", ...GO_ENV_KEYS], {
+ timeoutMs: 5_000,
+ maxBytes: 64 * 1024,
+ ...(options.run ? { run: options.run } : {}),
+ ...(options.resolve ? { resolve: options.resolve } : {}),
+ });
+ if (go && go.code === 0) {
+ try {
+ const parsed = JSON.parse(go.stdout) as Record<string, unknown>;
+ const pairs = Object.entries(parsed).filter(([, value]) => typeof value === "string" && value !== "") as Array<[string, string]>;
+ const { entries } = filterEntries(pairs, options.privacy, options.scrub);
+ if (Object.keys(entries).length > 0) result.go_env = entries;
+ } catch {
+ // Not JSON (a very old go).
+ }
+ }
+ return result;
+}
diff --git a/apps/server/src/context/privacy.ts b/apps/server/src/context/privacy.ts
new file mode 100644
index 00000000..8ecf46bf
--- /dev/null
+++ b/apps/server/src/context/privacy.ts
@@ -0,0 +1,189 @@
+// What every capture-context item goes through before it is recorded: the
+// home directory (and the account name wherever it appears in a path) becomes
+// `~`, URLs lose their userinfo and secret-looking query values, and the
+// text runs through the uploader's CONFIG secret scrub (injected, so this
+// module is the same in the CLI and the desktop app).
+
+import { homedir, userInfo } from "node:os";
+
+/** The uploader's scrubbers: free text (CONFIG mode) and whole JSON values. */
+export type Scrubber = {
+ text: (text: string) => string;
+ json: <T>(value: T) => T;
+ /** A file's content for upload, scrubbed by its path (source vs config rules). */
+ content: (path: string, text: string) => string;
+};
+
+/** No scrubbing (tests that look at the raw shapes). */
+export const IDENTITY_SCRUBBER: Scrubber = { text: (text) => text, json: (value) => value, content: (_path, text) => text };
+
+export type PrivacyContext = { home: string | null; user: string | null };
+
+export function currentPrivacy(): PrivacyContext {
+ let home: string | null = null;
+ let user: string | null = null;
+ try {
+ home = homedir() || null;
+ } catch {
+ home = null;
+ }
+ try {
+ user = userInfo().username || null;
+ } catch {
+ user = null;
+ }
+ return { home, user };
+}
+
+function escapeRegExp(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+const homeRegexCache = new Map<string, RegExp>();
+
+/**
+ * Replaces the home directory with `~` wherever it appears in `text` (both
+ * slash styles on Windows), and any other home-style path of the account
+ * (`/home/<user>`, `/Users/<user>`, `C:\Users\<user>`) the same way.
+ */
+export function tildeText(text: string, privacy: PrivacyContext): string {
+ if (!text) return text;
+ let out = text;
+ const homes = new Set<string>();
+ if (privacy.home && privacy.home.length > 1) {
+ homes.add(privacy.home);
+ homes.add(privacy.home.replaceAll("\\", "/"));
+ homes.add(privacy.home.replaceAll("/", "\\"));
+ }
+ for (const home of [...homes].sort((a, b) => b.length - a.length)) {
+ let pattern = homeRegexCache.get(home);
+ if (!pattern) {
+ pattern = new RegExp(`${escapeRegExp(home)}(?=$|[\\\\/\\s"'\`:;,)\\]}>]|$)`, /^[A-Za-z]:/.test(home) ? "gi" : "g");
+ homeRegexCache.set(home, pattern);
+ }
+ out = out.replace(pattern, "~");
+ }
+ const user = privacy.user;
+ if (user && user.length >= 2 && /^[\w.@-]+$/.test(user)) {
+ const name = escapeRegExp(user);
+ out = out
+ .replace(new RegExp(`(?:/home|/Users|/var/home)/${name}(?=$|[/\\s"'\`:;,)\\]}>])`, "g"), "~")
+ .replace(new RegExp(`[A-Za-z]:[\\\\/]Users[\\\\/]${name}(?=$|[\\\\/\\s"'\`:;,)\\]}>])`, "gi"), "~");
+ }
+ return out;
+}
+
+/** A path for the record: the home directory as `~`. */
+export function tildePath(path: string, privacy: PrivacyContext): string {
+ return tildeText(path, privacy);
+}
+
+const SECRET_QUERY_KEY = /(?:token|key|secret|password|passwd|pwd|auth|sig|signature|credential|session|code)/i;
+
+/** A URL without userinfo and without secret-looking query values (unparseable: returned scrub-ready as given). */
+export function cleanUrl(raw: string): string {
+ const trimmed = raw.trim();
+ try {
+ const url = new URL(trimmed);
+ if (url.username || url.password) {
+ url.username = "";
+ url.password = "";
+ }
+ for (const key of [...url.searchParams.keys()]) {
+ if (SECRET_QUERY_KEY.test(key)) url.searchParams.set(key, "[REDACTED]");
+ }
+ // Anaconda-style tokens live in the path: https://conda.anaconda.org/t/<token>/channel.
+ url.pathname = url.pathname.replace(/\/t\/[^/]+/g, "/t/[REDACTED]");
+ let out = url.toString().replace(/%5BREDACTED%5D/g, "[REDACTED]");
+ // URL adds a "/" path to a bare origin; keep the value as it was written.
+ if (!/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*[/]/i.test(trimmed) && out.endsWith("/") && !url.search && !url.hash) out = out.slice(0, -1);
+ return out;
+ } catch {
+ return trimmed.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@\s]*@/i, "$1");
+ }
+}
+
+/** Every URL inside free text without userinfo. */
+export function stripUrlUserinfo(text: string): string {
+ return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/@\s"'`]+@/gi, "$1");
+}
+
+/** A string for the record: URL userinfo stripped, the home as `~`, then the secret scrub. */
+export function cleanText(text: string, privacy: PrivacyContext, scrub: Scrubber): string {
+ return scrub.text(tildeText(stripUrlUserinfo(text), privacy));
+}
+
+/** UTF-8 byte length. */
+export function utf8Bytes(text: string): number {
+ return Buffer.byteLength(text, "utf8");
+}
+
+/** `text` cut to at most `maxBytes` UTF-8 bytes on a character boundary. */
+export function capUtf8(text: string, maxBytes: number): { text: string; truncated: boolean } {
+ if (utf8Bytes(text) <= maxBytes) return { text, truncated: false };
+ const buffer = Buffer.from(text, "utf8").subarray(0, Math.max(0, maxBytes));
+ let cut = buffer.toString("utf8");
+ if (cut.endsWith("\uFFFD")) cut = cut.slice(0, -1);
+ return { text: cut, truncated: true };
+}
+
+/** Keeps leading items of `items` while their JSON stays within `maxBytes`. */
+export function capList<T>(items: readonly T[], maxBytes: number): { items: T[]; truncated: boolean } {
+ const kept: T[] = [];
+ let bytes = 2;
+ for (const item of items) {
+ const size = utf8Bytes(JSON.stringify(item)) + 1;
+ if (bytes + size > maxBytes) return { items: kept, truncated: true };
+ bytes += size;
+ kept.push(item);
+ }
+ return { items: kept, truncated: false };
+}
+
+/** Whether a buffer holds text (no NUL in its first 8 KiB, valid UTF-8). */
+export function isTextBuffer(buffer: Buffer): boolean {
+ const head = buffer.subarray(0, 8192);
+ if (head.includes(0)) return false;
+ try {
+ new TextDecoder("utf-8", { fatal: true }).decode(buffer.length > 1024 * 1024 ? buffer.subarray(0, 1024 * 1024 - 4) : buffer);
+ return true;
+ } catch {
+ return buffer.length > 1024 * 1024 - 4;
+ }
+}
+
+/** A key that names a credential: its value is never recorded. */
+export const SECRET_KEY = /(?:^|[_.\-:\s/]|(?<=[a-z]))(?:_?auth|authtoken|auth[_-]?token|token|password|passwd|pass|pwd|secret|credential|credentials|apikey|api[_-]?key|private[_-]?key|privatekey|passphrase|cert|certfile|keyfile|signing|session|cookie|bearer|client[_-]?secret)(?:$|[_.\-:\s/]|(?=[A-Z]))/i;
+
+/** Whether a config key names a credential (`_auth`, `//registry/:_authToken`, `npmAuthToken`, `password`…). */
+export function isSecretKey(key: string): boolean {
+ const lower = key.toLowerCase();
+ if (/_auth|authtoken|authident|token|password|passwd|secret|credential|apikey|api_key|api-key|privatekey|private_key|private-key|passphrase|cookie|bearer|signing\.|signing_|keyfile|certfile|\bcert\b|clientsecret|client_secret/.test(lower)) return true;
+ if (/(^|[._:\-/])(auth|key|pass|pwd|username|user|email|login)$/.test(lower)) return true;
+ return SECRET_KEY.test(key);
+}
+
+export type AddressClass = "loopback" | "any" | "private" | "link-local" | "public";
+
+/**
+ * The kind of an IP address. Raw addresses are never recorded (the secret
+ * scrub treats every IP literal as personal data); the class says what a
+ * port is bound to or where a connection went.
+ */
+export function addressClass(address: string): AddressClass {
+ const ip = address.replace(/^\[|\]$/g, "").replace(/%.*$/, "").toLowerCase();
+ const v4 = /^(?:::ffff:)?(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(ip);
+ if (v4) {
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
+ if (a === 127) return "loopback";
+ if (a === 0) return "any";
+ if (a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127)) return "private";
+ if (a === 169 && b === 254) return "link-local";
+ return "public";
+ }
+ if (ip === "::1") return "loopback";
+ if (ip === "::" || ip === "*" || ip === "") return "any";
+ if (/^fe[89ab]/.test(ip)) return "link-local";
+ if (/^f[cd]/.test(ip)) return "private";
+ return "public";
+}
diff --git a/apps/server/src/context/processes.ts b/apps/server/src/context/processes.ts
new file mode 100644
index 00000000..1c3cfd24
--- /dev/null
+++ b/apps/server/src/context/processes.ts
@@ -0,0 +1,366 @@
+// #19 Listening TCP ports (with the owning process) and the running
+// development processes (name + command line, arguments scrubbed, never the
+// environment), at session start and at each turn start. Linux reads /proc
+// (no spawn) plus `ss -Hltnp` for the port owners; macOS `ps` and `lsof`;
+// Windows `netstat -ano` and one PowerShell CIM query.
+
+import { readdir, readFile, readlink } from "node:fs/promises";
+
+import { runTool, type Runner } from "./exec.js";
+import { addressClass, cleanText, type PrivacyContext, type Scrubber } from "./privacy.js";
+
+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 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. */
+const DEV_NAMES = [
+ "node", "nodejs", "deno", "bun", "npm", "npx", "pnpm", "yarn", "tsx", "ts-node", "vite", "next", "nuxt", "webpack", "esbuild", "turbo",
+ "python", "python2", "python3", "pypy", "uvicorn", "gunicorn", "hypercorn", "celery", "flask", "django", "jupyter", "ipython", "uv", "poetry",
+ "java", "javaw", "kotlin", "gradle", "gradlew", "mvn", "sbt", "ruby", "rails", "puma", "unicorn", "sidekiq", "bundle", "irb",
+ "go", "gopls", "air", "dlv", "cargo", "rustc", "rust-analyzer", "php", "php-fpm", "composer", "dotnet", "elixir", "beam.smp", "erl", "mix",
+ "docker", "dockerd", "containerd", "containerd-shim", "docker-proxy", "com.docker.backend", "podman", "kubectl", "minikube", "kind", "k3s", "colima", "lima",
+ "postgres", "postmaster", "mysqld", "mariadbd", "mongod", "mongos", "redis-server", "valkey-server", "memcached", "elasticsearch", "opensearch",
+ "rabbitmq-server", "kafka", "zookeeper", "clickhouse", "clickhouse-server", "cockroach", "neo4j", "influxd", "etcd", "minio", "sqlservr", "oracle",
+ "nginx", "httpd", "apache2", "caddy", "traefik", "envoy", "haproxy", "ollama", "localstack", "mailhog", "mailpit",
+ "make", "cmake", "ninja", "bazel", "gcc", "clang", "lldb", "gdb", "playwright", "chromedriver", "geckodriver",
+];
+const DEV_NAME_SET = new Set(DEV_NAMES);
+
+function baseName(raw: string): string {
+ const name = raw.split(/[\\/]/).at(-1) ?? raw;
+ return name.replace(/\.exe$/i, "").toLowerCase();
+}
+
+/** Whether a process is a development tool, runtime, database or server (by name, or by its interpreter's script). */
+export function isDevProcess(name: string, command = ""): boolean {
+ const base = baseName(name);
+ if (DEV_NAME_SET.has(base)) return true;
+ if (/^(?:python|pypy)\d+(?:\.\d+)*$/.test(base) || /^node\d*$/.test(base) || /^java\d*$/.test(base) || /^ruby\d+(?:\.\d+)*$/.test(base) || /^php\d+(?:\.\d+)*$/.test(base)) return true;
+ if (/^postgres:|^postgres$/.test(base)) return true;
+ const first = command.trim().split(/\s+/)[0] ?? "";
+ return first !== "" && DEV_NAME_SET.has(baseName(first));
+}
+
+/** The engine and app processes capture itself runs (their command lines carry loopback secrets). */
+function isOwnProcess(info: ProcessInfo, selfPid: number): boolean {
+ if (info.pid === selfPid) return true;
+ return /\b(?:opencode|omnirush-engine|omnirush-server)\b.*\bserve\b/i.test(info.command);
+}
+
+/** A command line for the record: home as `~`, URL userinfo dropped, secrets scrubbed, at most 2000 chars. */
+export function cleanCommand(command: string, privacy: PrivacyContext, scrub: Scrubber): string {
+ const flat = command.replace(/\s+/g, " ").trim();
+ // `--token value` / `--password=value`: the value after a secret-named flag goes, whatever it looks like.
+ const flagged = flat
+ .replace(/(--?[\w-]*(?:token|password|passwd|secret|api[-_]?key|auth|credential)[\w-]*)(=|\s+)("[^"]*"|'[^']*'|\S+)/gi, "$1$2[REDACTED]");
+ const cleaned = cleanText(flagged, privacy, scrub);
+ return cleaned.length > MAX_COMMAND_CHARS ? `${cleaned.slice(0, MAX_COMMAND_CHARS)}…` : cleaned;
+}
+
+// --- Linux ------------------------------------------------------------------------
+
+/** /proc/<pid>/stat: comm (between the outer parentheses) and the parent pid. */
+export function parseProcStat(text: string): { comm: string; ppid: number; startTicks: number } | null {
+ const open = text.indexOf("(");
+ const close = text.lastIndexOf(")");
+ if (open < 0 || close < open) return null;
+ const rest = text.slice(close + 2).split(" ");
+ const ppid = Number(rest[1]);
+ const startTicks = Number(rest[19]);
+ if (!Number.isInteger(ppid)) return null;
+ return { comm: text.slice(open + 1, close), ppid, startTicks: Number.isFinite(startTicks) ? startTicks : 0 };
+}
+
+export async function linuxProcesses(procRoot = "/proc"): Promise<ProcessInfo[]> {
+ let names: string[];
+ try {
+ names = await readdir(procRoot);
+ } catch {
+ return [];
+ }
+ const out: ProcessInfo[] = [];
+ await Promise.all(names.filter((name) => /^\d+$/.test(name)).map(async (name) => {
+ try {
+ const [stat, cmdline] = await Promise.all([
+ readFile(`${procRoot}/${name}/stat`, "utf8"),
+ readFile(`${procRoot}/${name}/cmdline`).catch(() => Buffer.alloc(0)),
+ ]);
+ const parsed = parseProcStat(stat);
+ if (!parsed) return;
+ const command = cmdline.toString("utf8").replace(/\0+$/, "").split("\0").join(" ");
+ out.push({ pid: Number(name), ppid: parsed.ppid, name: parsed.comm, command: command || `[${parsed.comm}]` });
+ } catch {
+ // Gone or not ours.
+ }
+ }));
+ return out.sort((a, b) => a.pid - b.pid);
+}
+
+/** An address of /proc/net/tcp{,6} (little-endian hex) as text. */
+export function parseProcAddress(hex: string): { address: string; port: number } | null {
+ const [ip, port] = hex.split(":");
+ if (!ip || !port) return null;
+ const portNumber = parseInt(port, 16);
+ if (ip.length === 8) {
+ const bytes = [0, 1, 2, 3].map((i) => parseInt(ip.slice(i * 2, i * 2 + 2), 16)).reverse();
+ return { address: bytes.join("."), port: portNumber };
+ }
+ if (ip.length === 32) {
+ const words: string[] = [];
+ for (let w = 0; w < 4; w += 1) {
+ const chunk = ip.slice(w * 8, w * 8 + 8);
+ const bytes = [0, 1, 2, 3].map((i) => chunk.slice(i * 2, i * 2 + 2)).reverse().join("");
+ words.push(bytes.slice(0, 4), bytes.slice(4, 8));
+ }
+ const groups = words.map((word) => word.replace(/^0+(?=.)/, "").toLowerCase());
+ let address = groups.join(":");
+ if (address.startsWith("0:0:0:0:0:ffff:")) {
+ const v4 = ip.slice(24);
+ address = [0, 1, 2, 3].map((i) => parseInt(v4.slice(i * 2, i * 2 + 2), 16)).reverse().join(".");
+ } else {
+ address = address.replace(/(^|:)0(:0)+(:|$)/, "::").replace(/:{3,}/, "::");
+ }
+ return { address, port: portNumber };
+ }
+ return null;
+}
+
+export type ProcSocket = { local: { address: string; port: number }; remote: { address: string; port: number }; state: string; inode: number };
+
+/** The rows of /proc/net/tcp or tcp6. */
+export function parseProcNetTcp(text: string): ProcSocket[] {
+ const out: ProcSocket[] = [];
+ for (const line of text.split("\n").slice(1)) {
+ const fields = line.trim().split(/\s+/);
+ if (fields.length < 10) continue;
+ const local = parseProcAddress(fields[1]!);
+ const remote = parseProcAddress(fields[2]!);
+ if (!local || !remote) continue;
+ out.push({ local, remote, state: fields[3]!, inode: Number(fields[9]) });
+ }
+ return out;
+}
+
+export async function readProcSockets(procNet = "/proc/net"): Promise<ProcSocket[]> {
+ const files = await Promise.all(["tcp", "tcp6"].map((name) => readFile(`${procNet}/${name}`, "utf8").catch(() => "")));
+ return files.flatMap(parseProcNetTcp);
+}
+
+/** Socket inode -> pid for the given processes (only those whose fds are readable: the user's own). */
+export async function socketOwners(pids: readonly number[], procRoot = "/proc"): Promise<Map<number, number>> {
+ const owners = new Map<number, number>();
+ await Promise.all(pids.map(async (pid) => {
+ let fds: string[];
+ try {
+ fds = await readdir(`${procRoot}/${pid}/fd`);
+ } catch {
+ return;
+ }
+ await Promise.all(fds.slice(0, 4096).map(async (fd) => {
+ try {
+ const target = await readlink(`${procRoot}/${pid}/fd/${fd}`);
+ const match = /^socket:\[(\d+)\]$/.exec(target);
+ if (match) owners.set(Number(match[1]), pid);
+ } catch {
+ // Closed meanwhile.
+ }
+ }));
+ }));
+ return owners;
+}
+
+/** `ss -Hltnp` rows: `LISTEN 0 4096 127.0.0.1:5432 0.0.0.0:* users:(("postgres",pid=12,fd=6))`. */
+export function parseSsListening(text: string): ListeningPort[] {
+ const out: ListeningPort[] = [];
+ for (const line of text.split(/\r?\n/)) {
+ const fields = line.trim().split(/\s+/);
+ if (fields.length < 4) continue;
+ const local = fields.find((field, index) => index >= 3 && /:\d+$/.test(field));
+ if (!local) continue;
+ const at = local.lastIndexOf(":");
+ const address = local.slice(0, at).replace(/^\[|\]$/g, "").replace(/%.*$/, "");
+ const port = Number(local.slice(at + 1));
+ const users = /users:\(\("([^"]+)",pid=(\d+)/.exec(line);
+ out.push({ proto: "tcp", address, port, pid: users ? Number(users[2]) : null, process: users ? users[1]! : null });
+ }
+ return out;
+}
+
+async function linuxListening(processes: ProcessInfo[], run?: Runner): Promise<{ ports: ListeningPort[]; method: string }> {
+ const ss = await runTool("ss", ["-Hltnp"], { timeoutMs: 3_000, maxBytes: 512 * 1024, ...(run ? { run } : {}) });
+ if (ss && ss.code === 0 && ss.stdout.trim()) return { ports: parseSsListening(ss.stdout), method: "ss" };
+ const sockets = (await readProcSockets()).filter((socket) => socket.state === "0A");
+ const owners = await socketOwners(processes.map((p) => p.pid));
+ const byPid = new Map(processes.map((p) => [p.pid, p]));
+ return {
+ method: "proc",
+ ports: sockets.map((socket) => {
+ const pid = owners.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 };
+ }),
+ };
+}
+
+// --- macOS --------------------------------------------------------------------------
+
+/** `ps -axww -o pid=,ppid=,comm=,args=`: comm is the executable path on macOS. */
+export function parsePs(text: string): ProcessInfo[] {
+ const out: ProcessInfo[] = [];
+ for (const line of text.split(/\r?\n/)) {
+ const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
+ if (!match) continue;
+ const rest = match[3]!;
+ out.push({ pid: Number(match[1]), ppid: Number(match[2]), name: baseName(rest.split(/\s+/)[0] ?? ""), command: rest.trim() });
+ }
+ return out;
+}
+
+/** `lsof -nP -iTCP -sTCP:LISTEN -F pcn`: p<pid>, c<command>, n<addr:port> fields. */
+export function parseLsofListen(text: string): ListeningPort[] {
+ const out: ListeningPort[] = [];
+ let pid: number | null = null;
+ let command: string | null = null;
+ for (const line of text.split(/\r?\n/)) {
+ if (line.startsWith("p")) pid = Number(line.slice(1)) || null;
+ else if (line.startsWith("c")) command = line.slice(1);
+ else if (line.startsWith("n")) {
+ const value = line.slice(1).split("->")[0]!;
+ const at = value.lastIndexOf(":");
+ if (at < 0) continue;
+ const address = value.slice(0, at).replace(/^\[|\]$/g, "");
+ out.push({ proto: "tcp", address: address === "*" ? "0.0.0.0" : address, port: Number(value.slice(at + 1)), pid, process: command });
+ }
+ }
+ return out;
+}
+
+// --- Windows ------------------------------------------------------------------------
+
+/** `netstat -ano -p TCP` LISTENING rows (and both families with -p TCPv6). */
+export function parseNetstat(text: string, state = "LISTENING"): Array<{ local: string; remote: string; pid: number }> {
+ const out: Array<{ local: string; remote: string; pid: number }> = [];
+ for (const line of text.split(/\r?\n/)) {
+ const fields = line.trim().split(/\s+/);
+ if (fields.length < 5 || !/^TCP/i.test(fields[0]!)) continue;
+ if (fields[3]!.toUpperCase() !== state) continue;
+ out.push({ local: fields[1]!, remote: fields[2]!, pid: Number(fields[4]) });
+ }
+ return out;
+}
+
+export function splitHostPort(value: string): { address: string; port: number } | null {
+ const at = value.lastIndexOf(":");
+ if (at < 0) return null;
+ return { address: value.slice(0, at).replace(/^\[|\]$/g, "").replace(/%.*$/, ""), port: Number(value.slice(at + 1)) };
+}
+
+const WINDOWS_PROCESS_QUERY =
+ "$ErrorActionPreference='SilentlyContinue';[Console]::OutputEncoding=[Text.Encoding]::UTF8;"
+ + "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.Name)`t$($_.CommandLine)\" }";
+
+export function parseWindowsProcesses(text: string): ProcessInfo[] {
+ const out: ProcessInfo[] = [];
+ for (const line of text.split(/\r?\n/)) {
+ const [pid, ppid, name, ...command] = line.split("\t");
+ if (!pid || !/^\d+$/.test(pid)) continue;
+ out.push({ pid: Number(pid), ppid: Number(ppid) || 0, name: name ?? "", command: command.join("\t") || name || "" });
+ }
+ return out;
+}
+
+// --- all platforms --------------------------------------------------------------------
+
+export type ProcessTableOptions = { platform?: NodeJS.Platform; run?: Runner };
+
+/** Every process visible to the user: pid, parent, name and command line. */
+export async function processTable(options: ProcessTableOptions = {}): Promise<{ processes: ProcessInfo[]; method: string }> {
+ const platform = options.platform ?? process.platform;
+ const runOpt = options.run ? { run: options.run } : {};
+ if (platform === "linux") return { processes: await linuxProcesses(), method: "proc" };
+ if (platform === "win32") {
+ const result = await runTool("powershell", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROCESS_QUERY], { timeoutMs: 10_000, maxBytes: 4 * 1024 * 1024, ...runOpt });
+ return { processes: result && result.code === 0 ? parseWindowsProcesses(result.stdout) : [], method: "powershell" };
+ }
+ const result = await runTool("ps", ["-axww", "-o", "pid=,ppid=,args="], { timeoutMs: 5_000, maxBytes: 4 * 1024 * 1024, ...runOpt });
+ return { processes: result && result.code === 0 ? parsePs(result.stdout) : [], method: "ps" };
+}
+
+export async function listeningPorts(processes: ProcessInfo[], options: ProcessTableOptions = {}): Promise<{ ports: ListeningPort[]; method: string }> {
+ const platform = options.platform ?? process.platform;
+ const runOpt = options.run ? { run: options.run } : {};
+ const byPid = new Map(processes.map((p) => [p.pid, p]));
+ let ports: ListeningPort[] = [];
+ let method = "none";
+ if (platform === "linux") {
+ ({ ports, method } = await linuxListening(processes, options.run));
+ } else if (platform === "win32") {
+ const result = await runTool("netstat", ["-ano", "-p", "TCP"], { timeoutMs: 5_000, maxBytes: 2 * 1024 * 1024, ...runOpt });
+ const v6 = await runTool("netstat", ["-ano", "-p", "TCPv6"], { timeoutMs: 5_000, maxBytes: 2 * 1024 * 1024, ...runOpt });
+ method = "netstat";
+ for (const row of [...parseNetstat(result?.stdout ?? ""), ...parseNetstat(v6?.stdout ?? "")]) {
+ const local = splitHostPort(row.local);
+ if (local) ports.push({ proto: "tcp", ...local, pid: row.pid, process: byPid.get(row.pid)?.name ?? null });
+ }
+ } else {
+ const result = await runTool("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN", "-F", "pcn"], { timeoutMs: 5_000, maxBytes: 2 * 1024 * 1024, ...runOpt });
+ method = "lsof";
+ ports = parseLsofListen(result?.stdout ?? "");
+ }
+ // One row per (address, port), filled in from the process table.
+ const seen = new Set<string>();
+ const out: ListeningPort[] = [];
+ for (const port of ports.sort((a, b) => a.port - b.port || a.address.localeCompare(b.address))) {
+ const key = `${port.address}|${port.port}`;
+ if (seen.has(key) || !Number.isInteger(port.port) || port.port <= 0) continue;
+ seen.add(key);
+ out.push({ ...port, process: port.process ?? (port.pid !== null ? byPid.get(port.pid)?.name ?? null : null) });
+ }
+ return { ports: out, method };
+}
+
+export type ProcessSnapshot = {
+ phase: "session_start" | "turn_start";
+ turn: number;
+ collected_at: string;
+ listening: ListeningPort[];
+ processes: Array<{ pid: number; name: string; command: string }>;
+ total_processes: number;
+ truncated: boolean;
+ method: string;
+};
+
+export type SnapshotOptions = ProcessTableOptions & {
+ privacy: PrivacyContext;
+ scrub: Scrubber;
+ selfPid?: number;
+ now?: () => Date;
+ /** A process table and port list already taken (session start shares them with services). */
+ precomputed?: { processes: ProcessInfo[]; listening: ListeningPort[]; method?: string };
+};
+
+/** One #19 snapshot: listening ports and the dev-relevant processes, scrubbed and capped. */
+export async function processSnapshot(phase: ProcessSnapshot["phase"], turn: number, options: SnapshotOptions): Promise<ProcessSnapshot> {
+ const { processes, method } = options.precomputed ? { processes: options.precomputed.processes, method: options.precomputed.method ?? "shared" } : await processTable(options);
+ const { ports, method: portMethod } = options.precomputed ? { ports: options.precomputed.listening, method: "shared" } : await listeningPorts(processes, options);
+ const self = options.selfPid ?? process.pid;
+ const dev = processes.filter((info) => !isOwnProcess(info, self) && isDevProcess(info.name, info.command));
+ const kept = dev.slice(0, MAX_PROCESSES).map((info) => ({
+ pid: info.pid,
+ name: cleanText(info.name, options.privacy, options.scrub),
+ command: cleanCommand(info.command, options.privacy, options.scrub),
+ }));
+ return {
+ phase,
+ turn,
+ collected_at: (options.now ?? (() => new Date()))().toISOString(),
+ listening: ports.slice(0, MAX_LISTENING).map((port) => ({ ...port, address: addressClass(port.address), process: port.process ? cleanText(port.process, options.privacy, options.scrub) : null })),
+ processes: kept,
+ total_processes: processes.length,
+ truncated: dev.length > MAX_PROCESSES || ports.length > MAX_LISTENING,
+ method: options.precomputed ? method : `${method}+${portMethod}`,
+ };
+}
diff --git a/apps/server/src/context/services.ts b/apps/server/src/context/services.ts
new file mode 100644
index 00000000..14dac1a6
--- /dev/null
+++ b/apps/server/src/context/services.ts
@@ -0,0 +1,237 @@
+// #7 Services: the running docker containers (when docker answers without
+// sudo), the local databases listening on this machine with the version of
+// their command-line client (never connecting, never with credentials), and
+// the compose files of the project and of the running compose projects.
+
+import { constants } from "node:fs";
+import { access, readdir } from "node:fs/promises";
+import { join, relative } from "node:path";
+
+import { resolveCommand, runTool, type Runner } from "./exec.js";
+import { addressClass, cleanText, tildePath, type PrivacyContext, type Scrubber } from "./privacy.js";
+import type { ListeningPort, ProcessInfo } from "./processes.js";
+
+export const MAX_CONTAINERS = 100;
+const MAX_COMPOSE_FILES = 50;
+const COMPOSE_NAME = /^(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml$/i;
+const SKIP_DIRS = new Set(["node_modules", ".git", ".venv", "venv", "dist", "build", "target", ".next", "vendor", "__pycache__", ".cache"]);
+
+export type DockerContainer = { name: string; image: string; image_digest: string | null; ports: string; status: string };
+export type LocalDatabase = { kind: string; port: number; address: string; client_version: string | null; process: string | null };
+export type Services = {
+ docker: { reachable: boolean; containers: DockerContainer[]; truncated?: boolean; skipped?: string };
+ databases: LocalDatabase[];
+ compose_files: string[];
+};
+
+/** Well-known database ports, and the client that names the version. */
+export const DATABASE_PORTS: Record<number, { kind: string; probes?: Array<{ command: string; args: string[] }> }> = {
+ 5432: { kind: "postgres", probes: [{ command: "psql", args: ["--version"] }, { command: "postgres", args: ["--version"] }] },
+ 3306: { kind: "mysql", probes: [{ command: "mysql", args: ["--version"] }, { command: "mysqld", args: ["--version"] }, { command: "mariadb", args: ["--version"] }] },
+ 33060: { kind: "mysql-x" },
+ 27017: { kind: "mongodb", probes: [{ command: "mongod", args: ["--version"] }, { command: "mongosh", args: ["--version"] }] },
+ 6379: { kind: "redis", probes: [{ command: "redis-server", args: ["--version"] }, { command: "redis-cli", args: ["--version"] }, { command: "valkey-server", args: ["--version"] }] },
+ 11211: { kind: "memcached", probes: [{ command: "memcached", args: ["-V"] }] },
+ 9200: { kind: "elasticsearch" },
+ 5672: { kind: "rabbitmq" },
+ 1433: { kind: "mssql" },
+ 1521: { kind: "oracle" },
+ 9042: { kind: "cassandra" },
+ 26257: { kind: "cockroachdb", probes: [{ command: "cockroach", args: ["version", "--build-tag"] }] },
+ 7687: { kind: "neo4j" },
+ 5984: { kind: "couchdb" },
+ 8086: { kind: "influxdb", probes: [{ command: "influxd", args: ["version"] }] },
+ 8123: { kind: "clickhouse", probes: [{ command: "clickhouse", args: ["--version"] }] },
+};
+
+/** Database server process names, for a database on a port other than its usual one. */
+const DATABASE_PROCESSES: Record<string, number> = {
+ postgres: 5432, postmaster: 5432, mysqld: 3306, mariadbd: 3306, mongod: 27017, "redis-server": 6379, "valkey-server": 6379,
+ memcached: 11211, "clickhouse-server": 8123, cockroach: 26257, influxd: 8086,
+};
+
+/** `docker ps --format '{{json .}}'` lines. */
+export function parseDockerPs(text: string): Array<{ id: string; name: string; image: string; ports: string; status: string; labels: string }> {
+ const out: Array<{ id: string; name: string; image: string; ports: string; status: string; labels: string }> = [];
+ for (const line of text.split(/\r?\n/)) {
+ if (!line.trim()) continue;
+ try {
+ const row = JSON.parse(line) as Record<string, unknown>;
+ out.push({
+ id: String(row.ID ?? ""),
+ name: String(row.Names ?? ""),
+ image: String(row.Image ?? ""),
+ ports: String(row.Ports ?? ""),
+ status: String(row.Status ?? ""),
+ labels: String(row.Labels ?? ""),
+ });
+ } catch {
+ // Not a JSON row.
+ }
+ }
+ return out;
+}
+
+/** The compose files a container's labels name (`com.docker.compose.project.config_files=a.yml,b.yml`). */
+export function composeFilesOfLabels(labels: string): string[] {
+ const match = /(?:^|,)com\.docker\.compose\.project\.config_files=([^,]*(?:,[^=,]*(?=,|$))*)/.exec(labels);
+ if (!match) return [];
+ return match[1]!.split(",").map((file) => file.trim()).filter((file) => /\.ya?ml$/i.test(file));
+}
+
+/** Whether docker can be asked without sudo: a reachable socket, a DOCKER_HOST, or a platform where the CLI talks to a desktop VM. */
+async function dockerReachable(platform: NodeJS.Platform): Promise<boolean> {
+ if (platform !== "linux" || process.env.DOCKER_HOST) return true;
+ for (const socket of ["/var/run/docker.sock", "/run/docker.sock", join(process.env.XDG_RUNTIME_DIR ?? "/nonexistent", "docker.sock")]) {
+ try {
+ await access(socket, constants.R_OK | constants.W_OK);
+ return true;
+ } catch {
+ // Next.
+ }
+ }
+ return false;
+}
+
+export function firstVersionLine(text: string): string | null {
+ const line = text.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
+ return line ? line.slice(0, 200) : null;
+}
+
+async function findComposeFiles(root: string, maxDepth = 3): Promise<string[]> {
+ const out: string[] = [];
+ const walk = async (dir: string, depth: number) => {
+ if (out.length >= MAX_COMPOSE_FILES) return;
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (out.length >= MAX_COMPOSE_FILES) return;
+ if (entry.isFile() && COMPOSE_NAME.test(entry.name)) out.push(join(dir, entry.name));
+ else if (entry.isDirectory() && depth < maxDepth && !SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) await walk(join(dir, entry.name), depth + 1);
+ }
+ };
+ await walk(root, 0);
+ return out;
+}
+
+export type ServicesOptions = {
+ root: string;
+ listening: ListeningPort[];
+ processes: ProcessInfo[];
+ privacy: PrivacyContext;
+ scrub: Scrubber;
+ platform?: NodeJS.Platform;
+ run?: Runner;
+ resolve?: (command: string) => string | null;
+};
+
+/** A path for the record: inside the project as `$PROJECT/...`, else with the home as `~`. */
+export function recordPath(path: string, root: string, privacy: PrivacyContext): string {
+ const rel = relative(root, path);
+ if (rel && !rel.startsWith("..") && !/^[A-Za-z]:/.test(rel) && !rel.startsWith("/")) return `$PROJECT/${rel.split(/[\\/]/).join("/")}`;
+ if (rel === "") return "$PROJECT";
+ return tildePath(path, privacy);
+}
+
+export async function collectServices(options: ServicesOptions): Promise<Services> {
+ const platform = options.platform ?? process.platform;
+ const tool = (command: string, args: string[], timeoutMs = 5_000) => runTool(command, args, {
+ timeoutMs,
+ maxBytes: 1024 * 1024,
+ ...(options.run ? { run: options.run } : {}),
+ ...(options.resolve ? { resolve: options.resolve } : {}),
+ });
+ const clean = (text: string) => cleanText(text, options.privacy, options.scrub);
+
+ // Docker.
+ const docker: Services["docker"] = { reachable: false, containers: [] };
+ const composeFiles = new Set<string>();
+ if (!(options.resolve ?? resolveCommand)("docker")) {
+ docker.skipped = "not_installed";
+ } else if (!(await dockerReachable(platform))) {
+ docker.skipped = "no_access";
+ } else {
+ const ps = await tool("docker", ["ps", "--no-trunc", "--format", "{{json .}}"], 8_000);
+ if (ps && ps.code === 0) {
+ docker.reachable = true;
+ const rows = parseDockerPs(ps.stdout);
+ const kept = rows.slice(0, MAX_CONTAINERS);
+ if (rows.length > MAX_CONTAINERS) docker.truncated = true;
+ // Image digests: container -> image id -> repo digest, in two calls.
+ const digests = new Map<string, string>();
+ if (kept.length > 0) {
+ const images = await tool("docker", ["inspect", "--format", "{{.Id}} {{.Image}}", ...kept.map((row) => row.id)], 8_000);
+ const imageOf = new Map<string, string>();
+ for (const line of images?.stdout.split(/\r?\n/) ?? []) {
+ const [id, image] = line.trim().split(/\s+/);
+ if (id && image) imageOf.set(id, image);
+ }
+ const imageIds = [...new Set(imageOf.values())];
+ if (imageIds.length > 0) {
+ const repo = await tool("docker", ["image", "inspect", "--format", "{{.Id}} {{json .RepoDigests}}", ...imageIds], 8_000);
+ const repoDigest = new Map<string, string>();
+ for (const line of repo?.stdout.split(/\r?\n/) ?? []) {
+ const at = line.indexOf(" ");
+ if (at < 0) continue;
+ try {
+ const list = JSON.parse(line.slice(at + 1)) as string[];
+ if (Array.isArray(list) && typeof list[0] === "string") repoDigest.set(line.slice(0, at), list[0]);
+ } catch {
+ // No digests.
+ }
+ }
+ for (const [container, image] of imageOf) digests.set(container, repoDigest.get(image) ?? image);
+ }
+ }
+ docker.containers = kept.map((row) => ({
+ name: clean(row.name),
+ image: clean(row.image),
+ image_digest: [...digests].find(([id]) => id.startsWith(row.id) || row.id.startsWith(id))?.[1] ?? null,
+ ports: clean(row.ports),
+ status: clean(row.status),
+ }));
+ for (const row of rows) for (const file of composeFilesOfLabels(row.labels)) composeFiles.add(file);
+ } else {
+ docker.skipped = ps?.timedOut ? "timeout" : "unreachable";
+ }
+ }
+
+ // Local databases: by well-known port, or by a database server process listening anywhere.
+ const databases: LocalDatabase[] = [];
+ const versions = new Map<string, Promise<string | null>>();
+ const seen = new Set<string>();
+ for (const port of options.listening) {
+ const byPort = DATABASE_PORTS[port.port];
+ const processName = (port.process ?? "").toLowerCase().replace(/\.exe$/, "");
+ const byProcessPort = DATABASE_PROCESSES[processName];
+ const known = byPort ?? (byProcessPort !== undefined ? DATABASE_PORTS[byProcessPort] : undefined);
+ if (!known) continue;
+ const key = `${known.kind}|${port.port}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ // The first installed client (or server binary) that names its version; never connects.
+ const version: Promise<string | null> = versions.get(known.kind) ?? (async () => {
+ for (const probe of known.probes ?? []) {
+ const result = await tool(probe.command, probe.args, 4_000);
+ const line = result && result.code === 0 ? firstVersionLine(result.stdout || result.stderr) : null;
+ if (line) return line;
+ }
+ return null;
+ })();
+ versions.set(known.kind, version);
+ databases.push({ kind: known.kind, port: port.port, address: addressClass(port.address), client_version: null, process: port.process });
+ const entry = databases[databases.length - 1]!;
+ entry.client_version = await version.then((v) => (v ? clean(v) : null));
+ }
+
+ for (const file of await findComposeFiles(options.root)) composeFiles.add(file);
+ return {
+ docker,
+ databases,
+ compose_files: [...composeFiles].slice(0, MAX_COMPOSE_FILES).map((file) => clean(recordPath(file, options.root, options.privacy))),
+ };
+}
diff --git a/apps/server/src/context/setup.ts b/apps/server/src/context/setup.ts
new file mode 100644
index 00000000..58f5fad0
--- /dev/null
+++ b/apps/server/src/context/setup.ts
@@ -0,0 +1,557 @@
+// #16 The agent's own setup: client and engine version, the bundled skills
+// (name, version, hash), the skills and plugins installed for the user or
+// the project (with their text files, capped), the configured MCP servers
+// (name, command, arguments with secrets scrubbed, the package version when
+// it can be resolved; environment and header NAMES only, never their
+// values), and the model and non-secret settings (effort, variant).
+
+import { createHash } from "node:crypto";
+import { readdir, readFile, stat } from "node:fs/promises";
+import { basename, join, relative, sep } from "node:path";
+
+import { cleanText, cleanUrl, isTextBuffer, tildePath, tildeText, type PrivacyContext, type Scrubber } from "./privacy.js";
+
+export const MAX_SETUP_FILE_BYTES = 256 * 1024;
+export const MAX_SETUP_TOTAL_BYTES = 2 * 1024 * 1024;
+const MAX_FILES_PER_ITEM = 200;
+const MAX_ITEMS = 200;
+const MAX_CONFIG_BYTES = 1024 * 1024;
+const SKIP_DIRS = new Set(["node_modules", ".git", "__pycache__", ".venv", "venv", "dist", "build", ".cache"]);
+
+export type SetupModel = { provider_id: string | null; model_id: string | null; variant: string | null; agent: string | null };
+export type SetupItem = { name: string; scope: "user" | "project" | "bundled"; root: string | null; version: string | null; files: number; bytes: number; sha256: string | null; source?: "file" | "npm" };
+export type McpServer = {
+ name: string;
+ scope: string;
+ type: "local" | "remote";
+ command: string | null;
+ args: string[];
+ url: string | null;
+ env_names: string[];
+ header_names: string[];
+ package: string | null;
+ version: string | null;
+ version_source: "spec" | "installed" | null;
+ enabled: boolean;
+};
+export type SetupFile = { kind: "skill" | "plugin"; owner: string; scope: string; rel: string; sha256: string; bytes: number; content: string | null; binary?: true; truncated?: true };
+export type Setup = {
+ client: string;
+ app_version: string | null;
+ engine_version: string | null;
+ model: SetupModel | null;
+ settings: Record<string, unknown>;
+ bundled_skills: Array<{ name: string; version: string | null; sha256: string }>;
+ skills: SetupItem[];
+ plugins: SetupItem[];
+ mcp_servers: McpServer[];
+};
+
+/** JSON with comments and trailing commas (opencode.jsonc). */
+export function parseJsonc(text: string): unknown {
+ let out = "";
+ let inString = false;
+ for (let i = 0; i < text.length; i += 1) {
+ const char = text[i]!;
+ if (inString) {
+ out += char;
+ if (char === "\\") out += text[++i] ?? "";
+ else if (char === '"') inString = false;
+ continue;
+ }
+ if (char === '"') {
+ inString = true;
+ out += char;
+ } else if (char === "/" && text[i + 1] === "/") {
+ while (i < text.length && text[i] !== "\n") i += 1;
+ out += "\n";
+ } else if (char === "/" && text[i + 1] === "*") {
+ i += 2;
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i += 1;
+ i += 1;
+ } else {
+ out += char;
+ }
+ }
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+async function readJsonFile(path: string): Promise<unknown> {
+ try {
+ const info = await stat(path);
+ if (!info.isFile() || info.size > MAX_CONFIG_BYTES) return null;
+ return parseJsonc(await readFile(path, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+// --- packages of on-the-fly MCP commands -------------------------------------------
+
+const RUNNERS: Record<string, "npm" | "pypi"> = { npx: "npm", bunx: "npm", pnpx: "npm", uvx: "pypi", pipx: "pypi" };
+
+/** `npx -y @scope/[email protected] --flag` → { package, version }; `uvx pkg==1.0` likewise. */
+export function packageOfCommand(argv: string[]): { package: string; version: string | null; ecosystem: "npm" | "pypi" } | null {
+ if (argv.length === 0) return null;
+ let index = 0;
+ let runner = basename(argv[0]!).replace(/\.(?:cmd|exe)$/i, "");
+ if ((runner === "pnpm" || runner === "yarn") && argv[1] === "dlx") {
+ runner = "npx";
+ index = 1;
+ } else if (runner === "npm" && argv[1] === "exec") {
+ runner = "npx";
+ index = 1;
+ } else if (runner === "bun" && argv[1] === "x") {
+ runner = "bunx";
+ index = 1;
+ } else if (runner === "pipx" && argv[1] === "run") {
+ index = 1;
+ } else if (runner === "uv" && argv[1] === "tool" && argv[2] === "run") {
+ runner = "uvx";
+ index = 2;
+ }
+ const ecosystem = RUNNERS[runner];
+ if (!ecosystem) return null;
+ for (let i = index + 1; i < argv.length; i += 1) {
+ const word = argv[i]!;
+ if (word === "--") continue;
+ if (word.startsWith("-")) {
+ if (/^--(?:package|from|with)$/.test(word) || word === "-p") {
+ const value = argv[i + 1];
+ if (value) return { ...splitSpec(value, ecosystem), ecosystem };
+ }
+ const eq = /^--(?:package|from)=(.+)$/.exec(word);
+ if (eq) return { ...splitSpec(eq[1]!, ecosystem), ecosystem };
+ continue;
+ }
+ return { ...splitSpec(word, ecosystem), ecosystem };
+ }
+ return null;
+}
+
+/** `@scope/[email protected]` → (@scope/pkg, 1.2.3); `pkg==1.0` / `[email protected]` (PyPI). */
+export function splitSpec(spec: string, ecosystem: "npm" | "pypi"): { package: string; version: string | null } {
+ if (ecosystem === "pypi") {
+ const match = /^([A-Za-z0-9._\-[\],]+?)(?:==|@)([^\s]+)$/.exec(spec);
+ return match ? { package: match[1]!, version: match[2]! } : { package: spec, version: null };
+ }
+ const at = spec.lastIndexOf("@");
+ if (at > 0) return { package: spec.slice(0, at), version: spec.slice(at + 1) || null };
+ return { package: spec, version: null };
+}
+
+/** The version of a package installed under a `node_modules` the command path points into. */
+async function installedVersionOf(command: string, args: string[]): Promise<{ package: string; version: string } | null> {
+ for (const word of [command, ...args]) {
+ const match = /^(.*[\\/]node_modules[\\/])((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(word);
+ if (!match) continue;
+ const manifest = await readJsonFile(join(match[1]!, match[2]!, "package.json"));
+ if (isRecord(manifest) && typeof manifest.name === "string" && typeof manifest.version === "string") return { package: manifest.name, version: manifest.version };
+ }
+ return null;
+}
+
+/** An MCP argument for the record: secret-named flags' values dropped, URLs cleaned, home as `~`, scrubbed. */
+export function cleanArgs(args: string[], privacy: PrivacyContext, scrub: Scrubber): string[] {
+ const out: string[] = [];
+ const secretFlag = /^--?[\w-]*(?:token|password|passwd|secret|api[-_]?key|apikey|auth|credential|bearer|private[-_]?key)[\w-]*$/i;
+ for (let i = 0; i < args.length && i < 100; i += 1) {
+ const arg = String(args[i]);
+ const eq = /^(--?[\w-]+)=(.*)$/.exec(arg);
+ if (eq && secretFlag.test(eq[1]!)) {
+ out.push(`${eq[1]}=[REDACTED]`);
+ continue;
+ }
+ if (secretFlag.test(arg) && i + 1 < args.length) {
+ out.push(arg, "[REDACTED]");
+ i += 1;
+ continue;
+ }
+ const urls = arg.replace(/[a-z][a-z0-9+.-]*:\/\/[^\s"']+/gi, (url) => cleanUrl(url));
+ out.push(cleanText(urls, privacy, scrub).slice(0, 1000));
+ }
+ return out;
+}
+
+type RawServer = { name: string; scope: string; command: string | null; args: string[]; url: string | null; env: string[]; headers: string[]; enabled: boolean; type?: string };
+
+/** opencode `mcp` entries: `{type: "local", command: [..], environment}` / `{type: "remote", url, headers}`. */
+export function serversOfOpencodeConfig(config: unknown, scope: string): RawServer[] {
+ if (!isRecord(config) || !isRecord(config.mcp)) return [];
+ const out: RawServer[] = [];
+ for (const [name, raw] of Object.entries(config.mcp)) {
+ if (!isRecord(raw)) continue;
+ const argv = Array.isArray(raw.command) ? raw.command.map(String) : typeof raw.command === "string" ? [raw.command, ...(Array.isArray(raw.args) ? raw.args.map(String) : [])] : [];
+ out.push({
+ name,
+ scope,
+ type: typeof raw.type === "string" ? raw.type : argv.length > 0 ? "local" : "remote",
+ command: argv[0] ?? null,
+ args: argv.slice(1),
+ url: typeof raw.url === "string" ? raw.url : null,
+ env: isRecord(raw.environment) ? Object.keys(raw.environment) : isRecord(raw.env) ? Object.keys(raw.env) : [],
+ headers: isRecord(raw.headers) ? Object.keys(raw.headers) : [],
+ enabled: raw.enabled !== false,
+ });
+ }
+ return out;
+}
+
+/** Claude-style `{mcpServers: {name: {command, args, env} | {url, headers}}}` (also a bare map). */
+export function serversOfClaudeConfig(config: unknown, scope: string): RawServer[] {
+ if (!isRecord(config)) return [];
+ const map = isRecord(config.mcpServers) ? config.mcpServers : isRecord(config.servers) ? config.servers : null;
+ if (!map) return [];
+ const out: RawServer[] = [];
+ for (const [name, raw] of Object.entries(map)) {
+ if (!isRecord(raw)) continue;
+ out.push({
+ name,
+ scope,
+ command: typeof raw.command === "string" ? raw.command : null,
+ args: Array.isArray(raw.args) ? raw.args.map(String) : [],
+ url: typeof raw.url === "string" ? raw.url : null,
+ env: isRecord(raw.env) ? Object.keys(raw.env) : [],
+ headers: isRecord(raw.headers) ? Object.keys(raw.headers) : [],
+ enabled: raw.disabled !== true && raw.enabled !== false,
+ });
+ }
+ return out;
+}
+
+async function describeServer(raw: RawServer, privacy: PrivacyContext, scrub: Scrubber): Promise<McpServer> {
+ let pkg: string | null = null;
+ let version: string | null = null;
+ let versionSource: McpServer["version_source"] = null;
+ if (raw.command) {
+ const spec = packageOfCommand([raw.command, ...raw.args]);
+ if (spec) {
+ pkg = spec.package;
+ if (spec.version && spec.version !== "latest") {
+ version = spec.version;
+ versionSource = "spec";
+ }
+ }
+ if (!version) {
+ const installed = await installedVersionOf(raw.command, raw.args);
+ if (installed) {
+ pkg = pkg ?? installed.package;
+ version = installed.version;
+ versionSource = "installed";
+ }
+ }
+ }
+ const nameOnly = (name: string) => cleanText(name, privacy, scrub).slice(0, 200);
+ return {
+ name: nameOnly(raw.name),
+ scope: raw.scope,
+ type: raw.url && !raw.command ? "remote" : "local",
+ command: raw.command ? cleanText(raw.command, privacy, scrub).slice(0, 1000) : null,
+ args: cleanArgs(raw.args, privacy, scrub),
+ url: raw.url ? cleanText(cleanUrl(raw.url), privacy, scrub) : null,
+ env_names: raw.env.slice(0, 100).map(nameOnly),
+ header_names: raw.headers.slice(0, 100).map(nameOnly),
+ package: pkg ? nameOnly(pkg) : null,
+ version: version ? nameOnly(version) : null,
+ version_source: versionSource,
+ enabled: raw.enabled,
+ };
+}
+
+// --- skills and plugins --------------------------------------------------------------
+
+type Budget = { bytes: number };
+
+async function walkFiles(root: string, limit = MAX_FILES_PER_ITEM): Promise<string[]> {
+ const out: string[] = [];
+ const walk = async (dir: string, depth: number) => {
+ if (out.length >= limit || depth > 6) return;
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ entries.sort((a, b) => a.name.localeCompare(b.name));
+ for (const entry of entries) {
+ if (out.length >= limit) return;
+ const path = join(dir, entry.name);
+ if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) await walk(path, depth + 1);
+ else if (entry.isFile()) out.push(path);
+ }
+ };
+ await walk(root, 0);
+ return out;
+}
+
+/** Reads an item's files: hashes all, keeps the text of each (scrubbed) while the session budget lasts. */
+async function readItem(
+ kind: SetupFile["kind"],
+ owner: string,
+ scope: string,
+ root: string,
+ paths: string[],
+ options: { privacy: PrivacyContext; scrub: Scrubber; denied?: (path: string) => boolean },
+ budget: Budget,
+ files: SetupFile[],
+): Promise<{ files: number; bytes: number; sha256: string }> {
+ const itemHash = createHash("sha256");
+ let bytes = 0;
+ let count = 0;
+ for (const path of paths) {
+ const rel = relative(root, path).split(sep).join("/") || basename(path);
+ if (options.denied?.(rel)) continue;
+ let buffer: Buffer;
+ try {
+ const info = await stat(path);
+ if (info.size > 16 * MAX_SETUP_FILE_BYTES) continue;
+ buffer = await readFile(path);
+ } catch {
+ continue;
+ }
+ const sha256 = createHash("sha256").update(buffer).digest("hex");
+ itemHash.update(`${rel}\0${sha256}\n`);
+ bytes += buffer.length;
+ count += 1;
+ const text = isTextBuffer(buffer);
+ let content: string | null = null;
+ let truncated = false;
+ if (text && budget.bytes > 0) {
+ let raw = buffer.toString("utf8");
+ if (Buffer.byteLength(raw) > MAX_SETUP_FILE_BYTES) {
+ raw = buffer.subarray(0, MAX_SETUP_FILE_BYTES).toString("utf8").replace(/�$/, "");
+ truncated = true;
+ }
+ if (Buffer.byteLength(raw) <= budget.bytes) {
+ content = tildeText(options.scrub.content(rel, raw), options.privacy);
+ budget.bytes -= Buffer.byteLength(raw);
+ } else {
+ truncated = true;
+ }
+ }
+ files.push({
+ kind,
+ owner,
+ scope,
+ rel,
+ sha256,
+ bytes: buffer.length,
+ content,
+ ...(text ? {} : { binary: true as const }),
+ ...(truncated ? { truncated: true as const } : {}),
+ });
+ }
+ return { files: count, bytes, sha256: itemHash.digest("hex") };
+}
+
+/** Front-matter `version:` of a SKILL.md, else null. */
+export function skillVersion(text: string): string | null {
+ const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
+ const version = front ? /^\s*version:\s*["']?([^"'\n]+)["']?\s*$/m.exec(front[1]!) : null;
+ return version ? version[1]!.trim() : null;
+}
+
+export type SetupOptions = {
+ root: string;
+ client: "cli" | "gui";
+ appVersion?: string | null;
+ engineVersion?: string | null;
+ model?: SetupModel | null;
+ settings?: Record<string, unknown>;
+ /** Directories of the skills the app ships (each subfolder with a SKILL.md is one). */
+ bundledSkillDirs?: string[];
+ /** Skills the app ships inside its own bundle (name, version, hash), beside bundledSkillDirs. */
+ bundledSkills?: Array<{ name: string; version: string | null; sha256: string }>;
+ /** Extra opencode config files (the engine config the app writes: OPENCODE_CONFIG). */
+ configFiles?: string[];
+ /** Extra Claude-style MCP config files (the CLI's ~/.omnirush/mcp.json). */
+ mcpFiles?: string[];
+ privacy: PrivacyContext;
+ scrub: Scrubber;
+ /** The upload denylist (credential files): such a file is neither read nor hashed. */
+ denied?: (relPath: string) => boolean;
+ env?: NodeJS.ProcessEnv;
+};
+
+/** Non-secret engine settings: model, agents' model/variant/effort, and a few behaviour flags. */
+export function settingsOfConfig(config: unknown): Record<string, unknown> {
+ if (!isRecord(config)) return {};
+ const out: Record<string, unknown> = {};
+ for (const key of ["model", "small_model", "default_agent", "share", "autoupdate", "snapshot", "theme", "username"]) {
+ if (key === "username") continue;
+ if (typeof config[key] === "string" || typeof config[key] === "boolean") out[key] = config[key];
+ }
+ if (isRecord(config.agent)) {
+ const agents: Record<string, unknown> = {};
+ for (const [name, agent] of Object.entries(config.agent)) {
+ if (!isRecord(agent)) continue;
+ const picked: Record<string, unknown> = {};
+ for (const key of ["model", "variant", "reasoningEffort", "temperature", "top_p", "mode", "disable"]) if (agent[key] !== undefined && typeof agent[key] !== "object") picked[key] = agent[key];
+ if (isRecord(agent.options)) for (const key of ["reasoningEffort", "textVerbosity", "thinking"]) if (agent.options[key] !== undefined && typeof agent.options[key] !== "object") picked[key] = agent.options[key];
+ if (Object.keys(picked).length > 0) agents[name] = picked;
+ }
+ if (Object.keys(agents).length > 0) out.agent = agents;
+ }
+ if (isRecord(config.permission)) out.permission = JSON.parse(JSON.stringify(config.permission));
+ return out;
+}
+
+export async function collectSetup(options: SetupOptions): Promise<{ setup: Setup; files: SetupFile[] }> {
+ const { privacy, scrub } = options;
+ const env = options.env ?? process.env;
+ const home = privacy.home;
+ const xdg = env.XDG_CONFIG_HOME ?? (home ? join(home, ".config") : null);
+ const files: SetupFile[] = [];
+ const budget: Budget = { bytes: MAX_SETUP_TOTAL_BYTES };
+ const where = (path: string) => (path.startsWith(options.root) ? `$PROJECT/${relative(options.root, path).split(sep).join("/")}` : tildePath(path, privacy));
+
+ // Bundled skills: name, version and hash only (their text is the app's own).
+ const bundled: Setup["bundled_skills"] = [...(options.bundledSkills ?? [])];
+ for (const dir of options.bundledSkillDirs ?? []) {
+ let names: string[] = [];
+ try {
+ names = (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
+ } catch {
+ continue;
+ }
+ for (const name of names) {
+ try {
+ const text = await readFile(join(dir, name, "SKILL.md"));
+ bundled.push({ name, version: skillVersion(text.toString("utf8")), sha256: createHash("sha256").update(text).digest("hex") });
+ } catch {
+ // No SKILL.md.
+ }
+ }
+ }
+
+ // Installed skills: every folder with a SKILL.md under the skill roots opencode (and Claude-style tools) read.
+ const skillRoots: Array<{ dir: string; scope: "user" | "project" }> = [];
+ for (const name of ["skill", "skills"]) {
+ if (xdg) skillRoots.push({ dir: join(xdg, "opencode", name), scope: "user" });
+ if (env.OPENCODE_CONFIG_DIR) skillRoots.push({ dir: join(env.OPENCODE_CONFIG_DIR, name), scope: "user" });
+ skillRoots.push({ dir: join(options.root, ".opencode", name), scope: "project" });
+ }
+ if (home) {
+ skillRoots.push({ dir: join(home, ".claude", "skills"), scope: "user" });
+ skillRoots.push({ dir: join(home, ".agents", "skills"), scope: "user" });
+ }
+ skillRoots.push({ dir: join(options.root, ".claude", "skills"), scope: "project" });
+ skillRoots.push({ dir: join(options.root, ".agents", "skills"), scope: "project" });
+ const skills: SetupItem[] = [];
+ const seenSkillDirs = new Set<string>();
+ for (const { dir, scope } of skillRoots) {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (!entry.isDirectory() || skills.length >= MAX_ITEMS) continue;
+ const skillDir = join(dir, entry.name);
+ if (seenSkillDirs.has(skillDir)) continue;
+ seenSkillDirs.add(skillDir);
+ let version: string | null = null;
+ try {
+ version = skillVersion(await readFile(join(skillDir, "SKILL.md"), "utf8"));
+ } catch {
+ continue;
+ }
+ const summary = await readItem("skill", entry.name, scope, skillDir, await walkFiles(skillDir), options, budget, files);
+ skills.push({ name: entry.name, scope, root: where(skillDir), version, ...summary });
+ }
+ }
+
+ // Config files: opencode (global, project, the app's engine config) and Claude-style MCP files.
+ const opencodeConfigs: Array<{ path: string; scope: string }> = [];
+ for (const name of ["opencode.json", "opencode.jsonc", "config.json"]) {
+ if (xdg) opencodeConfigs.push({ path: join(xdg, "opencode", name), scope: "user" });
+ }
+ for (const name of ["opencode.json", "opencode.jsonc", ".opencode/opencode.json", ".opencode/opencode.jsonc"]) opencodeConfigs.push({ path: join(options.root, name), scope: "project" });
+ if (env.OPENCODE_CONFIG) opencodeConfigs.push({ path: env.OPENCODE_CONFIG, scope: "app" });
+ for (const path of options.configFiles ?? []) opencodeConfigs.push({ path, scope: "app" });
+ const claudeConfigs: Array<{ path: string; scope: string }> = [{ path: join(options.root, ".mcp.json"), scope: "project" }];
+ for (const path of options.mcpFiles ?? []) claudeConfigs.push({ path, scope: "app" });
+
+ const rawServers: RawServer[] = [];
+ const pluginSpecs: Array<{ spec: string; scope: string }> = [];
+ let settings: Record<string, unknown> = { ...(options.settings ?? {}) };
+ const seenConfigs = new Set<string>();
+ for (const { path, scope } of opencodeConfigs) {
+ if (seenConfigs.has(path)) continue;
+ seenConfigs.add(path);
+ const config = await readJsonFile(path);
+ if (!config) continue;
+ rawServers.push(...serversOfOpencodeConfig(config, scope));
+ if (isRecord(config) && Array.isArray(config.plugin)) for (const spec of config.plugin) if (typeof spec === "string") pluginSpecs.push({ spec, scope });
+ const picked = settingsOfConfig(config);
+ if (Object.keys(picked).length > 0) settings = { ...picked, ...settings, ...(scope === "app" ? {} : { [`${scope}_config`]: picked }) };
+ }
+ for (const { path, scope } of claudeConfigs) {
+ if (seenConfigs.has(path)) continue;
+ seenConfigs.add(path);
+ rawServers.push(...serversOfClaudeConfig(await readJsonFile(path), scope));
+ }
+ const mcpServers: McpServer[] = [];
+ for (const raw of rawServers.slice(0, MAX_ITEMS)) mcpServers.push(await describeServer(raw, privacy, scrub));
+
+ // Plugins: npm plugins named in the config (version from the spec or the engine's install cache), and plugin files.
+ const plugins: SetupItem[] = [];
+ const cacheDirs = [env.XDG_CACHE_HOME ? join(env.XDG_CACHE_HOME, "opencode") : null, home ? join(home, ".cache", "opencode") : null].filter(Boolean) as string[];
+ for (const { spec, scope } of pluginSpecs.slice(0, MAX_ITEMS)) {
+ if (spec.startsWith("file:") || spec.startsWith("/") || spec.startsWith(".")) continue;
+ const { package: name, version: wanted } = splitSpec(spec, "npm");
+ let version = wanted && wanted !== "latest" ? wanted : null;
+ if (!version) {
+ for (const dir of cacheDirs) {
+ const manifest = await readJsonFile(join(dir, "node_modules", name, "package.json"));
+ if (isRecord(manifest) && typeof manifest.version === "string") {
+ version = manifest.version;
+ break;
+ }
+ }
+ }
+ plugins.push({ name: cleanText(name, privacy, scrub), scope: scope === "app" ? "user" : (scope as "user" | "project"), root: null, version, files: 0, bytes: 0, sha256: null, source: "npm" });
+ }
+ const pluginRoots: Array<{ dir: string; scope: "user" | "project" }> = [];
+ for (const name of ["plugin", "plugins"]) {
+ if (xdg) pluginRoots.push({ dir: join(xdg, "opencode", name), scope: "user" });
+ pluginRoots.push({ dir: join(options.root, ".opencode", name), scope: "project" });
+ }
+ for (const { dir, scope } of pluginRoots) {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (plugins.length >= MAX_ITEMS) break;
+ const path = join(dir, entry.name);
+ const paths = entry.isDirectory() ? await walkFiles(path) : entry.isFile() ? [path] : [];
+ if (paths.length === 0) continue;
+ const owner = entry.name.replace(/\.(?:[cm]?[jt]s)$/, "");
+ const summary = await readItem("plugin", owner, scope, entry.isDirectory() ? path : dir, paths, options, budget, files);
+ plugins.push({ name: owner, scope, root: where(path), version: null, ...summary, source: "file" });
+ }
+ }
+
+ return {
+ setup: {
+ client: options.client,
+ app_version: options.appVersion ?? null,
+ engine_version: options.engineVersion ?? null,
+ model: options.model ?? null,
+ settings: scrub.json(JSON.parse(JSON.stringify(settings))) as Record<string, unknown>,
+ bundled_skills: bundled,
+ skills,
+ plugins,
+ mcp_servers: mcpServers,
+ },
+ files,
+ };
+}
diff --git a/apps/server/src/context/shell-aliases.ts b/apps/server/src/context/shell-aliases.ts
new file mode 100644
index 00000000..af550c87
--- /dev/null
+++ b/apps/server/src/context/shell-aliases.ts
@@ -0,0 +1,185 @@
+// #18 Shell aliases and shims that change which toolchain a command runs
+// (`alias python=python3`, `pip() { pip3 "$@"; }`, `Set-Alias python py`,
+// `python` on PATH being a symlink to python3.12 or a version-manager shim).
+// The rc files are read as text and lightly parsed; nothing is sourced or
+// run. Values go through the secret scrub (an alias can carry a token).
+
+import { lstat, readFile, readlink } from "node:fs/promises";
+import { basename, join } from "node:path";
+
+import { resolveCommand } from "./exec.js";
+import { cleanText, tildePath, type PrivacyContext, type Scrubber } from "./privacy.js";
+
+const MAX_RC_BYTES = 512 * 1024;
+const MAX_ALIASES = 200;
+const MAX_VALUE_CHARS = 500;
+
+/** Commands whose aliases matter to a toolchain. */
+export const TOOLCHAIN_COMMANDS = new Set([
+ "python", "python2", "python3", "py", "pip", "pip3", "pipx", "uv", "uvx", "poetry", "pipenv", "conda", "mamba", "virtualenv", "pyenv",
+ "node", "npm", "npx", "yarn", "pnpm", "pnpx", "bun", "bunx", "deno", "tsc", "ts-node", "tsx", "nvm", "volta", "fnm", "corepack",
+ "git", "go", "gofmt", "cargo", "rustc", "rustup", "java", "javac", "mvn", "gradle", "kotlin", "scala", "sbt",
+ "ruby", "gem", "bundle", "rake", "rails", "php", "composer", "dotnet", "swift", "make", "cmake", "cc", "gcc", "g++", "clang", "clang++",
+ "docker", "docker-compose", "podman", "kubectl", "helm", "terraform", "mise", "asdf", "rbenv", "sdk",
+]);
+
+export type ShellAlias = { name: string; value: string; file: string; kind: "alias" | "function" | "doskey" | "set-alias" | "abbr" };
+export type ShellShim = { name: string; target: string; kind: "symlink" | "shim" };
+export type ShellAliases = { aliases: ShellAlias[]; shims: ShellShim[] };
+
+function firstWord(value: string): string {
+ const word = value.trim().replace(/^(?:command|builtin|exec|env|noglob|nocorrect)\s+/, "").split(/\s+/)[0] ?? "";
+ return basename(word.replace(/^["']|["']$/g, ""));
+}
+
+function relevant(name: string, value: string): boolean {
+ return TOOLCHAIN_COMMANDS.has(name) || TOOLCHAIN_COMMANDS.has(firstWord(value).replace(/\.exe$/i, ""));
+}
+
+function unquote(value: string): string {
+ const trimmed = value.trim();
+ if ((trimmed.startsWith("'") && trimmed.endsWith("'")) || (trimmed.startsWith('"') && trimmed.endsWith('"'))) return trimmed.slice(1, -1);
+ return trimmed;
+}
+
+/** Aliases of POSIX shells (bash, zsh, sh): `alias a=b`, `alias -g a='b c'`, one-line functions `a() { b "$@"; }`. */
+export function parsePosixRc(text: string): Array<{ name: string; value: string; kind: ShellAlias["kind"] }> {
+ const out: Array<{ name: string; value: string; kind: ShellAlias["kind"] }> = [];
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line || line.startsWith("#")) continue;
+ for (const statement of line.split(/;\s*(?=alias\s)/)) {
+ const alias = /^alias\s+(?:-[a-zA-Z]+\s+)*([\w.+-]+)=(.*)$/.exec(statement.trim());
+ if (alias) {
+ out.push({ name: alias[1]!, value: unquote(alias[2]!.replace(/\s+#.*$/, "")), kind: "alias" });
+ continue;
+ }
+ }
+ const fn = /^(?:function\s+)?([\w.+-]+)\s*(?:\(\s*\))?\s*\{\s*(.+?);?\s*\}\s*$/.exec(line);
+ if (fn && (line.includes("()") || line.startsWith("function"))) out.push({ name: fn[1]!, value: fn[2]!.trim(), kind: "function" });
+ }
+ return out;
+}
+
+/** fish: `alias a 'b'`, `alias a=b`, `abbr -a a b`. */
+export function parseFishRc(text: string): Array<{ name: string; value: string; kind: ShellAlias["kind"] }> {
+ const out: Array<{ name: string; value: string; kind: ShellAlias["kind"] }> = [];
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ const alias = /^alias\s+([\w.+-]+)(?:=|\s+)(.+)$/.exec(line);
+ if (alias) out.push({ name: alias[1]!, value: unquote(alias[2]!), kind: "alias" });
+ const abbr = /^abbr\s+(?:-a\s+|--add\s+)?(?:-g\s+)?([\w.+-]+)\s+(.+)$/.exec(line);
+ if (abbr) out.push({ name: abbr[1]!, value: unquote(abbr[2]!), kind: "abbr" });
+ }
+ return out;
+}
+
+/** PowerShell: `Set-Alias python py`, `New-Alias -Name x -Value y`, `function python { py @args }`. */
+export function parsePowerShellRc(text: string): Array<{ name: string; value: string; kind: ShellAlias["kind"] }> {
+ const out: Array<{ name: string; value: string; kind: ShellAlias["kind"] }> = [];
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ const named = /^(?:Set|New)-Alias\s+(?:-Name\s+)?([\w.+-]+)\s+(?:-Value\s+)?(\S+)/i.exec(line);
+ if (named) out.push({ name: named[1]!, value: unquote(named[2]!), kind: "set-alias" });
+ const fn = /^function\s+([\w.+-]+)\s*\{\s*(.+?)\s*\}\s*$/i.exec(line);
+ if (fn) out.push({ name: fn[1]!, value: fn[2]!, kind: "function" });
+ }
+ return out;
+}
+
+/** cmd.exe autorun macros: `doskey python=py $*`. */
+export function parseDoskey(text: string): Array<{ name: string; value: string; kind: ShellAlias["kind"] }> {
+ const out: Array<{ name: string; value: string; kind: ShellAlias["kind"] }> = [];
+ for (const raw of text.split(/\r?\n/)) {
+ const match = /^(?:@?doskey\s+)?([\w.+-]+)=(.+)$/i.exec(raw.trim());
+ if (match && !/^\s*(?:rem|::)/i.test(raw)) out.push({ name: match[1]!, value: match[2]!.trim(), kind: "doskey" });
+ }
+ return out;
+}
+
+type RcFile = { path: string; parse: (text: string) => Array<{ name: string; value: string; kind: ShellAlias["kind"] }> };
+
+export function rcFiles(home: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv = process.env): RcFile[] {
+ const zdot = env.ZDOTDIR ?? home;
+ const xdg = env.XDG_CONFIG_HOME ?? join(home, ".config");
+ const files: RcFile[] = [
+ ...[".bashrc", ".bash_profile", ".bash_aliases", ".bash_login", ".profile", ".aliases", ".shrc", ".kshrc"].map((name) => ({ path: join(home, name), parse: parsePosixRc })),
+ ...[".zshrc", ".zprofile", ".zshenv", ".zlogin", ".zsh_aliases"].map((name) => ({ path: join(zdot, name), parse: parsePosixRc })),
+ { path: join(xdg, "fish", "config.fish"), parse: parseFishRc },
+ ];
+ if (platform === "win32") {
+ const documents = join(env.USERPROFILE ?? home, "Documents");
+ for (const dir of ["PowerShell", "WindowsPowerShell"]) {
+ for (const name of ["Microsoft.PowerShell_profile.ps1", "profile.ps1"]) files.push({ path: join(documents, dir, name), parse: parsePowerShellRc });
+ }
+ if (env.MACROS_FILE) files.push({ path: env.MACROS_FILE, parse: parseDoskey });
+ files.push({ path: join(home, "macros.doskey"), parse: parseDoskey });
+ } else {
+ files.push({ path: join(xdg, "powershell", "Microsoft.PowerShell_profile.ps1"), parse: parsePowerShellRc });
+ }
+ return files;
+}
+
+const SHIM_DIRS = /[\\/](?:\.pyenv|\.rbenv|\.nodenv|\.goenv|\.jenv|\.asdf|\.local[\\/]share[\\/]mise|\.volta|\.proto|\.rye)[\\/](?:shims|bin)(?:[\\/]|$)|[\\/]shims[\\/]/;
+const SHIM_NAMES = ["python", "python3", "pip", "pip3", "node", "npm", "npx", "java", "ruby", "go", "cargo", "cc", "gcc", "yarn", "pnpm"];
+
+/** `python` → `python3.12` when it is a symlink on PATH; a version manager's shim as such. */
+export async function pathShims(resolve: (command: string) => string | null = resolveCommand): Promise<ShellShim[]> {
+ const out: ShellShim[] = [];
+ for (const name of SHIM_NAMES) {
+ const path = resolve(name);
+ if (!path) continue;
+ if (SHIM_DIRS.test(path)) {
+ const manager = /\.(pyenv|rbenv|nodenv|goenv|jenv|asdf|volta|proto|rye)|mise/.exec(path)?.[0]?.replace(/^\./, "") ?? "shim";
+ out.push({ name, target: manager, kind: "shim" });
+ continue;
+ }
+ try {
+ if (!(await lstat(path)).isSymbolicLink()) continue;
+ const target = basename(await readlink(path));
+ if (target && target !== name) out.push({ name, target, kind: "symlink" });
+ } catch {
+ // Not readable.
+ }
+ }
+ return out;
+}
+
+export type ShellAliasOptions = {
+ privacy: PrivacyContext;
+ scrub: Scrubber;
+ platform?: NodeJS.Platform;
+ env?: NodeJS.ProcessEnv;
+ resolve?: (command: string) => string | null;
+};
+
+export async function collectShellAliases(options: ShellAliasOptions): Promise<ShellAliases> {
+ const home = options.privacy.home;
+ const aliases: ShellAlias[] = [];
+ if (home) {
+ const seen = new Set<string>();
+ for (const file of rcFiles(home, options.platform ?? process.platform, options.env)) {
+ if (seen.has(file.path) || aliases.length >= MAX_ALIASES) continue;
+ seen.add(file.path);
+ let text: string;
+ try {
+ const buffer = await readFile(file.path);
+ if (buffer.length > MAX_RC_BYTES) continue;
+ text = buffer.toString("utf8");
+ } catch {
+ continue;
+ }
+ for (const entry of file.parse(text)) {
+ if (!relevant(entry.name, entry.value) || aliases.length >= MAX_ALIASES) continue;
+ const value = cleanText(entry.value, options.privacy, options.scrub);
+ aliases.push({
+ name: entry.name,
+ value: value.length > MAX_VALUE_CHARS ? `${value.slice(0, MAX_VALUE_CHARS)}…` : value,
+ file: tildePath(file.path, options.privacy),
+ kind: entry.kind,
+ });
+ }
+ }
+ }
+ return { aliases, shims: await pathShims(options.resolve) };
+}
diff --git a/apps/server/src/context/system-packages.ts b/apps/server/src/context/system-packages.ts
new file mode 100644
index 00000000..db38d2f8
--- /dev/null
+++ b/apps/server/src/context/system-packages.ts
@@ -0,0 +1,193 @@
+// #5 System packages: the OS package manager's installed list, taken at most
+// once a day per machine (cached in the app's state directory) and capped at
+// 256 KiB. Linux: dpkg, rpm, apk or pacman (the first installed); macOS:
+// Homebrew when it is installed (never a /usr/bin Command Line Tools shim);
+// Windows: winget, non-interactive (a winget that would ask to accept its
+// source agreements is skipped).
+
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { hostname } from "node:os";
+import { join } from "node:path";
+
+import { runTool, type RunResult, type Runner } from "./exec.js";
+import { capList } from "./privacy.js";
+
+export const MAX_SYSTEM_PACKAGES_BYTES = 256 * 1024;
+const LIST_TIMEOUT_MS = 30_000;
+const LIST_MAX_BYTES = 8 * 1024 * 1024;
+const CACHE_FILE = "system-packages.json";
+
+export type SystemPackageManager = "dpkg" | "rpm" | "apk" | "pacman" | "brew" | "winget";
+export type SystemPackage = { name: string; version: string };
+export type SystemPackages =
+ | { manager: SystemPackageManager; collected_at: string; count: number; packages: SystemPackage[]; truncated: boolean }
+ | { skipped: "not_found" | "would_prompt" | "timeout" | "failed" | "clt_shim" };
+
+type Lister = { manager: SystemPackageManager; command: string; args: string[]; parse: (result: RunResult) => SystemPackage[] | null };
+
+function lines(text: string): string[] {
+ return text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
+}
+
+/** `name version` per line (dpkg-query format, pacman -Q, brew list --versions keeps every version). */
+export function parseNameVersionLines(text: string): SystemPackage[] {
+ const out: SystemPackage[] = [];
+ for (const line of lines(text)) {
+ const [name, ...rest] = line.split(/\s+/);
+ if (name && rest.length > 0) out.push({ name, version: rest.join(" ") });
+ }
+ return out;
+}
+
+/** rpm -qa --queryformat '%{NAME} %{VERSION}-%{RELEASE}\n'. */
+export const parseRpm = parseNameVersionLines;
+
+/** apk info -v: `name-1.2.3-r0` per line (the version starts at the last-but-one dash group). */
+export function parseApk(text: string): SystemPackage[] {
+ const out: SystemPackage[] = [];
+ for (const line of lines(text)) {
+ const match = /^(.+?)-(\d[^-]*-r\d+)$/.exec(line);
+ if (match) out.push({ name: match[1]!, version: match[2]! });
+ }
+ return out;
+}
+
+/**
+ * winget list: a fixed-width table under a `Name Id Version Available Source`
+ * header (localized headers are recognised by the dashed rule under them; the
+ * Id column is used as the name since it is stable across languages).
+ */
+export function parseWinget(text: string): SystemPackage[] {
+ const all = text.split(/\r?\n/).map((line) => line.replace(/^\s*[-\\|/]\s*$/, "").replace(/\u001b\[[0-9;]*[A-Za-z]/g, ""));
+ const ruleIndex = all.findIndex((line) => /^-{10,}\s*$/.test(line.trim()));
+ if (ruleIndex < 1) return [];
+ const header = all[ruleIndex - 1]!;
+ const starts: number[] = [];
+ for (const match of header.matchAll(/\S+(?:\s\S+)*/g)) starts.push(match.index!);
+ if (starts.length < 3) return [];
+ const column = (line: string, index: number) => line.slice(starts[index], index + 1 < starts.length ? starts[index + 1] : undefined).trim();
+ const out: SystemPackage[] = [];
+ for (const line of all.slice(ruleIndex + 1)) {
+ if (!line.trim()) continue;
+ const id = column(line, 1);
+ const version = column(line, 2);
+ const name = id || column(line, 0);
+ if (name && version) out.push({ name, version });
+ }
+ return out;
+}
+
+export function listersFor(platform: NodeJS.Platform): Lister[] {
+ if (platform === "darwin") {
+ return [{ manager: "brew", command: "brew", args: ["list", "--versions"], parse: (r) => (r.code === 0 ? parseNameVersionLines(r.stdout) : null) }];
+ }
+ if (platform === "win32") {
+ return [{
+ manager: "winget",
+ command: "winget",
+ args: ["list", "--accept-source-agreements", "--disable-interactivity"],
+ parse: (r) => (r.code === 0 ? parseWinget(r.stdout) : null),
+ }];
+ }
+ return [
+ { manager: "dpkg", command: "dpkg-query", args: ["-W", "-f", "${Package} ${Version}\\n"], parse: (r) => (r.code === 0 ? parseNameVersionLines(r.stdout) : null) },
+ { manager: "rpm", command: "rpm", args: ["-qa", "--queryformat", "%{NAME} %{VERSION}-%{RELEASE}\\n"], parse: (r) => (r.code === 0 ? parseRpm(r.stdout) : null) },
+ { manager: "apk", command: "apk", args: ["info", "-v"], parse: (r) => (r.code === 0 ? parseApk(r.stdout) : null) },
+ { manager: "pacman", command: "pacman", args: ["-Q"], parse: (r) => (r.code === 0 ? parseNameVersionLines(r.stdout) : null) },
+ ];
+}
+
+/** Whether winget stopped to ask for something (source agreements, a store login) instead of listing. */
+export function wingetWouldPrompt(result: RunResult): boolean {
+ return result.code !== 0 && /agreement|accept|\[Y\]|\(Y\/N\)|press any key/i.test(`${result.stdout}\n${result.stderr}`);
+}
+
+export type SystemPackagesOptions = {
+ platform?: NodeJS.Platform;
+ run?: Runner;
+ resolve?: (command: string) => string | null;
+ /** Directory holding the once-a-day cache (the app's state directory); none: no cache. */
+ cacheDir?: string | null;
+ now?: () => Date;
+ machine?: string;
+};
+
+type CacheFile = { machine: string; day: string; value: SystemPackages };
+
+function localDay(date: Date): string {
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+}
+
+async function readCache(dir: string, machine: string, day: string): Promise<SystemPackages | null> {
+ try {
+ const parsed = JSON.parse(await readFile(join(dir, CACHE_FILE), "utf8")) as CacheFile;
+ if (parsed && parsed.machine === machine && parsed.day === day && parsed.value && typeof parsed.value === "object") return parsed.value;
+ } catch {
+ // No cache yet, or unreadable: list again.
+ }
+ return null;
+}
+
+async function writeCache(dir: string, entry: CacheFile): Promise<void> {
+ try {
+ await mkdir(dir, { recursive: true, mode: 0o700 });
+ const target = join(dir, CACHE_FILE);
+ const temp = `${target}.${process.pid}.tmp`;
+ await writeFile(temp, JSON.stringify(entry), { mode: 0o600 });
+ await rename(temp, target);
+ } catch {
+ // The list is taken again next session.
+ }
+}
+
+/** Lists the installed system packages without any cache. */
+export async function listSystemPackages(options: SystemPackagesOptions = {}): Promise<SystemPackages> {
+ const platform = options.platform ?? process.platform;
+ const now = options.now ?? (() => new Date());
+ for (const lister of listersFor(platform)) {
+ const resolved = (options.resolve ?? undefined)?.(lister.command);
+ const result = await runTool(lister.command, lister.args, {
+ timeoutMs: LIST_TIMEOUT_MS,
+ maxBytes: LIST_MAX_BYTES,
+ ...(options.run ? { run: options.run } : {}),
+ ...(options.resolve ? { resolve: () => resolved ?? null } : {}),
+ });
+ if (!result) continue;
+ if (result.timedOut) return { skipped: "timeout" };
+ if (lister.manager === "winget" && wingetWouldPrompt(result)) return { skipped: "would_prompt" };
+ const packages = lister.parse(result);
+ if (!packages) return { skipped: "failed" };
+ packages.sort((left, right) => left.name.localeCompare(right.name));
+ const capped = capList(packages, MAX_SYSTEM_PACKAGES_BYTES);
+ return {
+ manager: lister.manager,
+ collected_at: now().toISOString(),
+ count: packages.length,
+ packages: capped.items,
+ truncated: capped.truncated || result.truncated,
+ };
+ }
+ return { skipped: "not_found" };
+}
+
+/** The installed system packages, from today's cache for this machine when there is one. */
+export async function systemPackages(options: SystemPackagesOptions = {}): Promise<SystemPackages> {
+ const now = options.now ?? (() => new Date());
+ const machine = options.machine ?? `${safeHostname()}/${options.platform ?? process.platform}`;
+ const day = localDay(now());
+ if (options.cacheDir) {
+ const cached = await readCache(options.cacheDir, machine, day);
+ if (cached) return cached;
+ }
+ const value = await listSystemPackages(options);
+ if (options.cacheDir && !("skipped" in value && value.skipped === "timeout")) await writeCache(options.cacheDir, { machine, day, value });
+ return value;
+}
+
+function safeHostname(): string {
+ try {
+ return hostname();
+ } catch {
+ return "unknown";
+ }
+}
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index ed212587..9797e1f3 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -2,7 +2,7 @@ import { createHash, randomBytes } from "node:crypto";
import { execFile, spawn } from "node:child_process";
import { createReadStream, createWriteStream, watch, type FSWatcher, type WriteStream } from "node:fs";
import { lstat, mkdir, open, readFile, readdir, readlink, rename, rm, stat } from "node:fs/promises";
-import { release as osRelease, tmpdir } from "node:os";
+import { homedir, release as osRelease, tmpdir } from "node:os";
import nodePath, { basename, dirname, extname, join, relative, resolve, sep, type PlatformPath } from "node:path";
import { promisify } from "node:util";
import { createZstdCompress } from "node:zlib";
@@ -27,6 +27,8 @@ 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 { ToolchainCache, type CollectOptions as ToolchainOptions, type UploadToolchain } from "./toolchain.js";
+import { ContextCapture, type ContextOptions } from "./context/index.js";
+import bundledBestPractices from "./bundled-best-practices.json" with { type: "json" };
const execFileAsync = promisify(execFile);
@@ -545,6 +547,11 @@ type SessionUploaderOptions = {
* byte-exact project archive.
*/
onBinaryFile?: (sessionId: string, path: string) => void;
+ /**
+ * Capture context (context/): an object turns it on (the capture host
+ * always passes one) and overrides its options; absent or false: off.
+ */
+ context?: false | Partial<ContextOptions>;
};
export type TraceCapabilities = {
@@ -3985,6 +3992,8 @@ export class SessionUploader {
private traceSchemaProbe: Promise<2 | 3> | null = null;
/** Work counters for tests and profiling. */
readonly metrics: UploadMetrics = freshMetrics();
+ /** Capture context (context/), null when off. */
+ readonly context: ContextCapture | null;
constructor(options: SessionUploaderOptions = {}) {
this.uploadUrl = resolveUploadUrl(options.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL);
@@ -4035,6 +4044,7 @@ export class SessionUploader {
this.stateMigrated,
);
void this.stateMigrated.then(() => this.cleanTempDir(60 * 60_000)).catch(() => undefined);
+ this.context = !options.context || !this.enabled ? null : this.createContext(stateDir, options.context);
if (this.spoolDir) {
if (this.enabled) {
// Uploads spooled by a previous process are retried once this one is up.
@@ -4047,6 +4057,59 @@ export class SessionUploader {
}
}
+ /** Capture context wired to this uploader: its trace, its scrub, the project archive and the archive's exclusions. */
+ private createContext(stateDir: string | null, overrides: Partial<ContextOptions>): ContextCapture | null {
+ let exclusion: ((absolute: string) => string | null) | null = null;
+ // Loaded lazily: session-archive/outside.ts imports this module.
+ void import("./session-archive/outside.js").then((module) => {
+ const home = (() => {
+ try {
+ return homedir() || null;
+ } catch {
+ return null;
+ }
+ })();
+ const appDirs = stateDir ? [stateDir] : [];
+ exclusion = (absolute) => module.outsideExclusion(absolute, { appDirs, home });
+ }, () => undefined);
+ const bundle = bundledBestPractices as { source?: { commit?: string }; skills?: Array<{ name?: string; content?: string }> };
+ const bundledSkills = (bundle.skills ?? []).filter((skill) => typeof skill.name === "string" && typeof skill.content === "string").map((skill) => ({
+ name: skill.name!,
+ version: bundle.source?.commit ? bundle.source.commit.slice(0, 12) : null,
+ sha256: createHash("sha256").update(skill.content!).digest("hex"),
+ }));
+ const capture = new ContextCapture({
+ client: "gui",
+ appVersion: this.appVersion ?? null,
+ engineVersion: this.engineVersion ?? null,
+ cacheDir: stateDir ? join(stateDir, "context") : null,
+ scrub: {
+ text: (text) => redactUploadText(text).text,
+ json: (value) => redactUploadJson(value).value as typeof value,
+ content: (path, text) => redactUploadContent(path, text),
+ },
+ record: (sessionId, type, data) => this.recordContext(sessionId, type, data),
+ reportPath: (sessionId, absolute) => this.onPathTouched?.(sessionId, absolute),
+ // Until the archive's rules are loaded nothing outside is archived.
+ exclusion: (absolute) => (exclusion ? exclusion(absolute) : "pending"),
+ denied: (relPath) => isUploadPathDenied(relPath),
+ model: (sessionId) => this.sessions.get(sessionId)?.model ?? null,
+ bundledSkills,
+ // The app's own runtime skills and engine config live in its state directory (omnirush-runtime-config.ts).
+ bundledSkillDirs: stateDir ? [join(stateDir, "skills")] : [],
+ configFiles: stateDir ? [join(stateDir, "runtime-opencode-config.json")] : [],
+ log: this.log,
+ ...overrides,
+ });
+ return capture.enabled ? capture : null;
+ }
+
+ /** Appends a capture-context event; also while a finished session's last upload is being prepared. */
+ private recordContext(sessionId: string, type: string, data: unknown): void {
+ const state = this.sessions.get(sessionId);
+ if (state) this.appendTrace(state, type, data);
+ }
+
private async loadLedger(): Promise<void> {
this.ledger = await readSessionLedger(this.ledgerPath);
}
@@ -4297,6 +4360,7 @@ export class SessionUploader {
};
state.ready = this.prepareSession(state);
this.sessions.set(sessionId, state);
+ this.context?.sessionStarted(sessionId, root);
this.enqueue(state, async () => {
await state.ready;
try {
@@ -4734,6 +4798,7 @@ export class SessionUploader {
}
}
this.appendTrace(state, type, data);
+ if (type === "turn.messages" && isRecord(data)) this.context?.turnMessages(sessionId, data.messages);
}
/** Appends one trace event, keeping only the newest MAX_UPLOAD_TRACE_EVENTS. */
@@ -4928,6 +4993,10 @@ export class SessionUploader {
if (trigger === "prompt") {
state.relevance.clear();
state.turnWrittenPaths.clear();
+ // After the turn's artifact baseline (set just below) is listed.
+ this.context?.turnStarted(sessionId, Promise.resolve().then(() => state.artifactBaseline));
+ } else {
+ this.context?.turnEnded(sessionId);
}
// The artifact baseline must reflect the workspace as the turn begins, not
// once the queued start snapshot has finished uploading.
@@ -5066,6 +5135,7 @@ export class SessionUploader {
}
}
state.finished = true;
+ this.context?.sessionEnded(sessionId);
if (state.changeTimer) clearTimeout(state.changeTimer);
if (state.deferTimer) clearTimeout(state.deferTimer);
state.changeTimer = null;
@@ -5076,6 +5146,8 @@ export class SessionUploader {
void this.flushIgnoreBatch(state);
this.enqueue(state, async () => {
await state.ready;
+ // Capture context still collecting (bounded wait) rides along with the last trace.
+ await this.context?.settled(sessionId);
if (state.trace.length > 0) pendingTrace.push(...state.trace.splice(0));
await state.changeCaptureTail;
if (finalTrace !== undefined) pendingTrace.push({ at: new Date().toISOString(), type: "session.completed", data: finalTrace });