toolroll 0.9.125 → 0.9.127

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +1 -1
  3. package/dist/agent-detect.js +23 -3
  4. package/dist/assignment.js +14 -4
  5. package/dist/bounded-spawn.js +5 -36
  6. package/dist/browser/workspace.css +1 -1
  7. package/dist/browser/workspace.js +29 -29
  8. package/dist/browser-open.js +49 -0
  9. package/dist/chat-acceptance.js +1 -1
  10. package/dist/check-only.js +1 -1
  11. package/dist/cli.js +2 -2
  12. package/dist/connect-cli.js +2 -8
  13. package/dist/contracts/engine-api.js +8 -0
  14. package/dist/direct-chat.js +26 -18
  15. package/dist/doctor.js +30 -3
  16. package/dist/easy-start.js +44 -17
  17. package/dist/engine-reads.js +34 -1
  18. package/dist/evals.js +17 -19
  19. package/dist/first-run.js +5 -1
  20. package/dist/flexible-conversation.js +79 -1
  21. package/dist/flexible-import.js +162 -4
  22. package/dist/flexible-save.js +51 -4
  23. package/dist/flexible-session.js +34 -8
  24. package/dist/flexible-start.js +2 -1
  25. package/dist/flow-code.js +2 -2
  26. package/dist/invoke.js +4 -4
  27. package/dist/landed-rows.js +138 -0
  28. package/dist/laptop-background.js +2 -11
  29. package/dist/linux-packages.js +46 -0
  30. package/dist/local-landing.js +46 -7
  31. package/dist/merge-checklist.js +62 -8
  32. package/dist/operate.js +90 -33
  33. package/dist/preflight.js +14 -0
  34. package/dist/process-identity.js +155 -0
  35. package/dist/quick-start.js +6 -1
  36. package/dist/release.js +8 -0
  37. package/dist/result-follow-ups.js +8 -1
  38. package/dist/revision-catch-up.js +98 -0
  39. package/dist/runner-process.js +9 -25
  40. package/dist/sandbox-launch.js +3 -2
  41. package/dist/sandbox-runtime.js +115 -15
  42. package/dist/sandbox-tools.js +91 -6
  43. package/dist/server/direct-chat.js +4 -3
  44. package/dist/server/engine-api.js +13 -8
  45. package/dist/server/merge-ready-view.js +4 -2
  46. package/dist/server/pages.js +5 -2
  47. package/dist/server/render-pages.js +1 -0
  48. package/dist/server/render-results.js +9 -7
  49. package/dist/server/render-tasks.js +2 -2
  50. package/dist/server/task-views.js +16 -9
  51. package/dist/server/tasks.js +2 -2
  52. package/dist/shown-text.js +14 -0
  53. package/dist/skill-library.js +2 -12
  54. package/dist/status-probe.js +32 -0
  55. package/dist/task-base.js +13 -2
  56. package/dist/task-status.js +18 -8
  57. package/dist/teardown-git.js +6 -0
  58. package/dist/telegram-status.js +1 -1
  59. package/dist/toolroll-update-cli.js +2 -1
  60. package/dist/toolroll-update.js +4 -0
  61. package/dist/trust-repair.js +187 -0
  62. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  63. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  64. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  65. package/dist/tui/linux-x64/toolroll-tui +0 -0
  66. package/dist/unreachable.js +15 -0
  67. package/dist/work-index.js +51 -3
  68. package/dist/workspace-ui.js +4 -2
  69. package/package.json +1 -1
@@ -0,0 +1,155 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ const LSTART = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{1,2}) (\d{2}:\d{2}:\d{2}) (\d{4})$/;
5
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
6
+ const PROC_ID = /^proc:[0-9a-f-]{36}:\d{1,20}$/;
7
+ const BOOT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
8
+ export function lstartToIso(raw) {
9
+ const match = LSTART.exec(raw.trim().replace(/ +/g, " "));
10
+ if (match === null)
11
+ return null;
12
+ const utc = `${match[1]}, ${match[3].padStart(2, "0")} ${match[2]} ${match[5]} ${match[4]} GMT`;
13
+ const at = Date.parse(utc);
14
+ if (!Number.isFinite(at) || new Date(at).toUTCString() !== utc)
15
+ return null;
16
+ return new Date(at).toISOString();
17
+ }
18
+ export function identityProvider(recorded) {
19
+ if (PROC_ID.test(recorded))
20
+ return "proc";
21
+ if (ISO.test(recorded) || lstartToIso(recorded) !== null)
22
+ return "ps";
23
+ return null;
24
+ }
25
+ export function procStatFields(stat) {
26
+ const close = stat.lastIndexOf(")");
27
+ if (close < 0 || stat.indexOf("(") < 0 || stat.indexOf("(") > close)
28
+ return null;
29
+ const fields = stat.slice(close + 1).trim().split(/\s+/);
30
+ return fields.length >= 20 && /^[A-Za-z]$/.test(fields[0]) ? fields : null;
31
+ }
32
+ const defaultRead = (file) => readFileSync(file, "utf8");
33
+ const defaultPs = (pid, field) => {
34
+ try {
35
+ return execFileSync("/bin/ps", ["-p", String(pid), "-o", `${field}=`], {
36
+ encoding: "utf8", env: { PATH: "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" }, stdio: ["ignore", "pipe", "ignore"],
37
+ maxBuffer: 4096, timeout: 2_000, killSignal: "SIGKILL",
38
+ });
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ };
44
+ function procFields(pid, io) {
45
+ if ((io.platform ?? process.platform) !== "linux")
46
+ return null;
47
+ try {
48
+ return procStatFields((io.read ?? defaultRead)(join(io.procRoot ?? "/proc", String(pid), "stat")));
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ export function processIdentity(pid, provider, io = {}) {
55
+ const platform = io.platform ?? process.platform;
56
+ if (!Number.isSafeInteger(pid) || pid <= 1 || platform === "win32")
57
+ return null;
58
+ if (provider !== "ps" && platform === "linux") {
59
+ const fields = procFields(pid, io);
60
+ let boot = null;
61
+ try {
62
+ boot = (io.read ?? defaultRead)(join(io.procRoot ?? "/proc", "sys", "kernel", "random", "boot_id")).trim();
63
+ }
64
+ catch {
65
+ boot = null;
66
+ }
67
+ const ticks = fields?.[19];
68
+ if (fields !== null && boot !== null && BOOT_ID.test(boot) && ticks !== undefined && /^\d{1,20}$/.test(ticks))
69
+ return `proc:${boot}:${ticks}`;
70
+ if (provider === "proc")
71
+ return null;
72
+ }
73
+ const raw = (io.ps ?? defaultPs)(pid, "lstart");
74
+ return raw === null ? null : lstartToIso(raw);
75
+ }
76
+ export function sameProcess(pid, recorded, io = {}) {
77
+ const provider = identityProvider(recorded);
78
+ if (provider === null)
79
+ return "unknown";
80
+ const now = processIdentity(pid, provider, io);
81
+ if (now === null)
82
+ return "unknown";
83
+ const was = provider === "ps" && !ISO.test(recorded) ? lstartToIso(recorded) : recorded;
84
+ return now === was ? "same" : "other";
85
+ }
86
+ export function processParentId(pid, io = {}) {
87
+ if (!Number.isSafeInteger(pid) || pid <= 1 || (io.platform ?? process.platform) === "win32")
88
+ return null;
89
+ const fields = procFields(pid, io);
90
+ const raw = fields !== null ? fields[1] : (io.ps ?? defaultPs)(pid, "ppid")?.trim() ?? "";
91
+ const parent = Number(raw);
92
+ return /^\d+$/.test(raw) && Number.isSafeInteger(parent) && parent > 0 ? parent : null;
93
+ }
94
+ export function processGroupId(pid, io = {}) {
95
+ if (!Number.isSafeInteger(pid) || pid <= 1 || (io.platform ?? process.platform) === "win32")
96
+ return null;
97
+ const fields = procFields(pid, io);
98
+ const raw = fields !== null ? fields[2] : (io.ps ?? defaultPs)(pid, "pgid")?.trim() ?? "";
99
+ const group = Number(raw);
100
+ return /^\d+$/.test(raw) && Number.isSafeInteger(group) && group > 1 ? group : null;
101
+ }
102
+ export function processGroupRss(pgid, io = {}) {
103
+ if ((io.platform ?? process.platform) === "linux") {
104
+ const root = io.procRoot ?? "/proc";
105
+ const read = io.read ?? defaultRead;
106
+ let names;
107
+ try {
108
+ names = (io.list ?? readdirSync)(root).filter(name => /^\d+$/.test(name));
109
+ }
110
+ catch {
111
+ names = null;
112
+ }
113
+ if (names !== null && names.length > 0) {
114
+ let kilobytes = 0;
115
+ for (const name of names) {
116
+ try {
117
+ const fields = procStatFields(read(join(root, name, "stat")));
118
+ if (fields === null || Number(fields[2]) !== pgid)
119
+ continue;
120
+ const rss = /^VmRSS:\s+(\d+) kB$/m.exec(read(join(root, name, "status")));
121
+ if (rss !== null)
122
+ kilobytes += Number(rss[1]);
123
+ }
124
+ catch { }
125
+ }
126
+ return kilobytes * 1024;
127
+ }
128
+ }
129
+ let out;
130
+ try {
131
+ out = execFileSync("/bin/ps", ["-A", "-o", "pgid=,rss="], { encoding: "utf8", env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 4 * 1024 * 1024, timeout: 2_000, killSignal: "SIGKILL" });
132
+ }
133
+ catch {
134
+ out = null;
135
+ }
136
+ if (out === null)
137
+ return null;
138
+ let kilobytes = 0;
139
+ for (const line of out.split("\n")) {
140
+ const [group, rss] = line.trim().split(/\s+/);
141
+ if (Number(group) === pgid)
142
+ kilobytes += Number(rss) || 0;
143
+ }
144
+ return kilobytes * 1024;
145
+ }
146
+ export function processIdentityProblem(io = {}) {
147
+ const platform = io.platform ?? process.platform;
148
+ if (platform === "win32")
149
+ return "Toolroll can't read when a process started on Windows, so it can't start its worker here";
150
+ if (processIdentity(process.pid, undefined, io) !== null)
151
+ return null;
152
+ return platform === "linux"
153
+ ? "Toolroll can't read when a process started here: /proc can't be read and this `ps` has no `-o lstart` (busybox). Install procps (Debian, Ubuntu, Alpine: procps; Fedora: procps-ng), or make /proc readable"
154
+ : "Toolroll can't read when a process started here: `ps -o lstart` doesn't work";
155
+ }
@@ -91,8 +91,13 @@ export async function runQuickStart(argv, write, seams) {
91
91
  write(`Toolroll can't attach: ${proof.message}.`);
92
92
  return EXIT.refused;
93
93
  }
94
- if (!proof.ok)
94
+ if (!proof.ok) {
95
+ if (seams.setUp !== undefined && !(await seams.setUp())) {
96
+ write(`Toolroll isn't set up on this computer yet. Run \`toolroll\` in a terminal to set it up without a password, or \`toolroll up\` to start it with one.`);
97
+ return EXIT.refused;
98
+ }
95
99
  return seams.startUp();
100
+ }
96
101
  if (!enrolled) {
97
102
  const admitted = await seams.admit(repo);
98
103
  if (admitted !== 0)
package/dist/release.js CHANGED
@@ -37,6 +37,14 @@ export const ADVISORY_PR_CHECKS = {
37
37
  "upgrade path": ".github/workflows/upgrade-path.yml",
38
38
  "install smoke · ubuntu-24.04": ".github/workflows/install-smoke.yml",
39
39
  "install smoke · macos-latest": ".github/workflows/install-smoke.yml",
40
+ "install smoke · ubuntu umask 0002": ".github/workflows/install-smoke.yml",
41
+ "install smoke · ubuntu umask 0002 · arm64": ".github/workflows/install-smoke.yml",
42
+ "install smoke · no user namespaces": ".github/workflows/install-smoke.yml",
43
+ "install smoke · alpine": ".github/workflows/install-smoke.yml",
44
+ "install smoke · fedora": ".github/workflows/install-smoke.yml",
45
+ "install smoke · debian 12": ".github/workflows/install-smoke.yml",
46
+ "install smoke · debian 13": ".github/workflows/install-smoke.yml",
47
+ "install smoke · node 26": ".github/workflows/install-smoke.yml",
40
48
  "wire budgets": ".github/workflows/wire-budgets.yml",
41
49
  "rust · ubuntu-latest": ".github/workflows/rust.yml",
42
50
  "rust · macos-latest": ".github/workflows/rust.yml",
@@ -87,7 +87,14 @@ export function followUpChecksOf(store, runId, now = new Date(), root, asOf) {
87
87
  return { ...base, state: "not-run", note: "The saved check result could not be verified." };
88
88
  }
89
89
  const exit = /exit (\d+)/.exec(finished.detail ?? "");
90
- return { ...base, state: status === "passed" ? "passed" : status === "failed" ? "failed" : "not-run",
90
+ const outdated = status === "failed" && root !== undefined && asOf === undefined && repo !== null && !stillApproved(base.level, digest)
91
+ && (() => { try {
92
+ return checkCommandFor(store, repo, base.level).command !== null;
93
+ }
94
+ catch {
95
+ return false;
96
+ } })();
97
+ return { ...base, ...(outdated ? { outdated: true } : {}), state: status === "passed" ? "passed" : status === "failed" ? "failed" : "not-run",
91
98
  exitCode: exit === null ? sealed?.exitCode ?? null : Number(exit[1]), logArtifactId: sealed?.log ?? null, note: status === "not-run" ? finished.detail : null,
92
99
  ...(sealed === null ? {} : { tested: sealed.ran ? sealed.tested : null, batch: sealed.batch }) };
93
100
  }
@@ -0,0 +1,98 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { recordActionWhole } from "./action-ledger.js";
6
+ export const CATCH_UP_ACTION = "revision brought up to date";
7
+ const OID = /^[0-9a-f]{40}$/;
8
+ const IDENTITY = "Toolroll <update@toolroll.invalid>";
9
+ const PLAIN_BRANCH = /^[A-Za-z0-9._/-]{1,100}$/;
10
+ function mergeBody(tree, head, main, time, message) {
11
+ const who = `${IDENTITY} ${time} +0000`;
12
+ return `tree ${tree}\nparent ${head}\nparent ${main}\nauthor ${who}\ncommitter ${who}\n\n${message}\n`;
13
+ }
14
+ const commitIdOf = (body) => createHash("sha1").update(`commit ${Buffer.byteLength(body, "utf8")}\0`).update(body, "utf8").digest("hex");
15
+ export async function catchUpRevision(git, repo, head, branch, taskId, now, scratch) {
16
+ const run = (args) => git("git", ["--no-replace-objects", ...args], { cwd: repo, timeoutMs: 120_000 });
17
+ if (!OID.test(head) || !PLAIN_BRANCH.test(branch))
18
+ return { kind: "unavailable" };
19
+ const read = await run(["rev-parse", "--verify", "-q", `refs/heads/${branch}^{commit}`]);
20
+ const main = read.stdout.trim();
21
+ if (read.code !== 0 || !OID.test(main))
22
+ return { kind: "unavailable" };
23
+ const contained = await run(["merge-base", "--is-ancestor", main, head]);
24
+ if (contained.code === 0)
25
+ return { kind: "current", main };
26
+ if (contained.code !== 1)
27
+ return { kind: "unavailable" };
28
+ const merged = await run(["merge-tree", "--write-tree", "--name-only", "--no-messages", "-z", head, main]);
29
+ const [tree = "", ...names] = merged.stdout.split("\0");
30
+ if (merged.code === 1)
31
+ return { kind: "conflict", main, files: [...new Set(names.filter(one => one !== ""))].slice(0, 20) };
32
+ if (merged.code !== 0 || !OID.test(tree))
33
+ return { kind: "unavailable" };
34
+ const message = `Bring ${taskId} up to date with ${branch} (${main.slice(0, 8)})`;
35
+ const body = mergeBody(tree, head, main, Math.floor(now.getTime() / 1000), message);
36
+ const folder = mkdtempSync(join(scratch ?? tmpdir(), "toolroll-catch-up-"));
37
+ let written;
38
+ try {
39
+ const file = join(folder, "commit");
40
+ writeFileSync(file, body, { encoding: "utf8", mode: 0o600, flag: "wx" });
41
+ written = await run(["hash-object", "-t", "commit", "-w", "--", file]);
42
+ }
43
+ finally {
44
+ rmSync(folder, { recursive: true, force: true });
45
+ }
46
+ const commit = written.stdout.trim();
47
+ if (written.code !== 0 || commit !== commitIdOf(body))
48
+ return { kind: "unavailable" };
49
+ const shown = await run(["cat-file", "commit", commit]);
50
+ const header = shown.stdout.split("\n\n")[0] ?? "";
51
+ const parents = header.split("\n").filter(line => line.startsWith("parent ")).map(line => line.slice("parent ".length));
52
+ if (shown.code !== 0 || !header.startsWith(`tree ${tree}\n`) || parents.length !== 2 || parents[0] !== head || parents[1] !== main)
53
+ return { kind: "unavailable" };
54
+ return { kind: "merged", commit, main };
55
+ }
56
+ export async function catchUpMergeOf(git, repo, commit, head, branch) {
57
+ const run = (args) => git("git", ["--no-replace-objects", ...args], { cwd: repo, timeoutMs: 120_000 });
58
+ if (!OID.test(commit) || !OID.test(head) || !PLAIN_BRANCH.test(branch))
59
+ return null;
60
+ const shown = await run(["cat-file", "commit", commit]);
61
+ if (shown.code !== 0)
62
+ return null;
63
+ const header = (shown.stdout.split("\n\n")[0] ?? "").split("\n");
64
+ const parents = header.filter(line => line.startsWith("parent ")).map(line => line.slice("parent ".length));
65
+ const who = (field) => header.filter(line => line.startsWith(`${field} `)).map(line => line.slice(field.length + 1).replace(/ \d+ [+-]\d{4}$/, ""));
66
+ if (parents.length !== 2 || parents[0] !== head || !OID.test(parents[1]))
67
+ return null;
68
+ if (who("author").join() !== IDENTITY || who("committer").join() !== IDENTITY)
69
+ return null;
70
+ const onBranch = await run(["merge-base", "--is-ancestor", parents[1], `refs/heads/${branch}`]);
71
+ return onBranch.code === 0 ? parents[1] : null;
72
+ }
73
+ export function recordCatchUp(store, at, caught, now) {
74
+ if (caught.kind !== "merged" && caught.kind !== "conflict")
75
+ return;
76
+ recordActionWhole(store.handle, { at: now.toISOString(), actor: "toolroll", repo: at.repo, taskId: at.taskId, runId: at.runId, action: CATCH_UP_ACTION, outcome: caught.kind, source: "work" }, { v: 1, branch: at.branch, head: at.head, onto: at.onto, main: caught.main, ...(caught.kind === "merged" ? { commit: caught.commit } : { files: caught.files }) });
77
+ store.addRunNote(at.runId, "Toolroll", caught.kind === "merged"
78
+ ? `Started from the earlier attempt's work with the current ${at.onto} (${caught.main.slice(0, 8)}) merged in, so its checks run on both together.`
79
+ : `The current ${at.onto} (${caught.main.slice(0, 8)}) conflicts with the earlier attempt's work${caught.files.length === 0 ? "" : ` in ${caught.files.length === 1 ? "1 file" : `${caught.files.length} files`}`}, so this attempt starts from that work as it was.`, now);
80
+ }
81
+ export function catchUpConflictOf(store, taskId, main) {
82
+ const chain = store.revisionAncestryStatus(taskId).chain;
83
+ if (chain.length === 0 || !OID.test(main))
84
+ return null;
85
+ const row = store.handle.prepare(`SELECT outcome, detail FROM action_ledger WHERE action = ? AND task_id IN (${chain.map(() => "?").join(",")}) ORDER BY id DESC LIMIT 1`)
86
+ .get(CATCH_UP_ACTION, ...chain);
87
+ if (row === undefined || row["outcome"] !== "conflict")
88
+ return null;
89
+ try {
90
+ const detail = JSON.parse(String(row["detail"] ?? "null"));
91
+ if (detail === null || detail.main !== main)
92
+ return null;
93
+ return Array.isArray(detail.files) ? detail.files.filter((one) => typeof one === "string") : [];
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
@@ -1,6 +1,6 @@
1
1
  import { sameMachineHost } from "./machine-identity.js";
2
2
  import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
3
- import { execFileSync } from "node:child_process";
3
+ import { identityProvider, lstartToIso, processIdentity } from "./process-identity.js";
4
4
  import { closeSync, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, rmSync, writeFileSync, fsyncSync, constants } from "node:fs";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  export const RUNNER_PROCESS_DIR = "runner-processes";
@@ -38,30 +38,11 @@ export function runnerProcessFile(databaseFile, runner) {
38
38
  export function credentialDigest(credentialHash) {
39
39
  return createHash("sha256").update(`runner-process:${credentialHash}`, "utf8").digest("hex").slice(0, 32);
40
40
  }
41
- const LSTART = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{1,2}) (\d{2}:\d{2}:\d{2}) (\d{4})$/;
42
41
  export function parseProcessStart(raw) {
43
- const match = LSTART.exec(raw.trim().replace(/ +/g, " "));
44
- if (match === null)
45
- return null;
46
- const utc = `${match[1]}, ${match[3].padStart(2, "0")} ${match[2]} ${match[5]} ${match[4]} GMT`;
47
- const at = Date.parse(utc);
48
- if (!Number.isFinite(at) || new Date(at).toUTCString() !== utc)
49
- return null;
50
- return new Date(at).toISOString();
42
+ return lstartToIso(raw);
51
43
  }
52
- export function processStart(pid) {
53
- if (!Number.isSafeInteger(pid) || pid <= 1 || process.platform === "win32")
54
- return null;
55
- try {
56
- const raw = execFileSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], {
57
- encoding: "utf8", env: { PATH: "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" }, stdio: ["ignore", "pipe", "ignore"],
58
- maxBuffer: 1024, timeout: 2_000, killSignal: "SIGKILL",
59
- });
60
- return parseProcessStart(raw);
61
- }
62
- catch {
63
- return null;
64
- }
44
+ export function processStart(pid, provider) {
45
+ return processIdentity(pid, provider);
65
46
  }
66
47
  export const realProcessProbe = {
67
48
  exists: pid => {
@@ -82,7 +63,10 @@ export function processGone(entry, probe = realProcessProbe) {
82
63
  return true;
83
64
  if (exists === "unknown")
84
65
  return false;
85
- const started = probe.start(entry.pid);
66
+ const provider = identityProvider(entry.started);
67
+ if (provider === null)
68
+ return false;
69
+ const started = probe.start(entry.pid, provider);
86
70
  if (started === null)
87
71
  return probe.exists(entry.pid) === "absent";
88
72
  return started !== entry.started;
@@ -137,7 +121,7 @@ function parseRecord(value) {
137
121
  if (typeof one !== "object" || one === null)
138
122
  return null;
139
123
  const p = one;
140
- if (!Number.isSafeInteger(p["pid"]) || p["pid"] <= 1 || !ROLES.has(p["role"]) || !text(p["started"], 32) || !ISO.test(p["started"]))
124
+ if (!Number.isSafeInteger(p["pid"]) || p["pid"] <= 1 || !ROLES.has(p["role"]) || !text(p["started"], 80) || identityProvider(p["started"]) === null || !(ISO.test(p["started"]) || p["started"].startsWith("proc:")))
141
125
  return null;
142
126
  processes.push({ pid: p["pid"], role: p["role"], started: p["started"] });
143
127
  }
@@ -1,3 +1,4 @@
1
+ import { shownText } from "./shown-text.js";
1
2
  import { spawn } from "node:child_process";
2
3
  import { checkLinuxDependencies, cleanupBwrapMountPoints, getLinuxDependencyStatus, initializeLinuxNetworkBridge, wrapCommandWithSandboxLinux } from "@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js";
3
4
  import { SANDBOX_LAUNCH_SPEC, shellQuote, withRuntimeTemp } from "./sandbox-runtime.js";
@@ -31,7 +32,7 @@ async function main() {
31
32
  const spec = JSON.parse(raw);
32
33
  const problem = toolsProblem(spec);
33
34
  if (problem !== null) {
34
- process.stderr.write(`toolroll sandbox: nothing was started: ${problem}\n`);
35
+ process.stderr.write(`toolroll sandbox: nothing was started: ${shownText(problem)}\n`);
35
36
  return REFUSED;
36
37
  }
37
38
  const tools = spec.tools;
@@ -135,7 +136,7 @@ async function main() {
135
136
  }
136
137
  catch (error) {
137
138
  if (child === null) {
138
- process.stderr.write(`toolroll sandbox: nothing was started: ${error instanceof Error ? error.message : String(error)}\n`);
139
+ process.stderr.write(`toolroll sandbox: nothing was started: ${shownText(error instanceof Error ? error.message : String(error))}\n`);
139
140
  return REFUSED;
140
141
  }
141
142
  return 1;
@@ -5,7 +5,10 @@ import { delimiter, dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { wrapCommandWithSandboxMacOS } from "@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js";
7
7
  import { checkLinuxDependencies, getLinuxDependencyStatus } from "@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js";
8
- import { linuxSandboxTools, sandboxToolExclusions } from "./sandbox-tools.js";
8
+ import { linuxSandboxTools, sandboxToolExclusions, sandboxToolsRepair } from "./sandbox-tools.js";
9
+ import { trustRepairLines } from "./trust-repair.js";
10
+ import { shownText } from "./shown-text.js";
11
+ import { installLine, packageSystem } from "./linux-packages.js";
9
12
  const require = createRequire(import.meta.url);
10
13
  export const SANDBOX_RUNTIME = (() => {
11
14
  const name = "@anthropic-ai/sandbox-runtime";
@@ -20,38 +23,135 @@ export const SANDBOX_RUNTIME = (() => {
20
23
  export const sandboxRuntimeWords = () => `Anthropic's sandbox-runtime ${SANDBOX_RUNTIME.version}`;
21
24
  const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
22
25
  export const SEATBELT_PROBE = "(version 1)(deny default)(allow process-exec)(allow process-fork)(allow file-read*)(allow sysctl-read)(allow mach-lookup)";
26
+ const DETAIL_MAX = 300;
27
+ const bounded = (text) => shownText(text.trim()).slice(0, DETAIL_MAX);
23
28
  export function sandboxRuntimeProblem(platform = process.platform) {
29
+ const diagnosis = sandboxRuntimeDiagnosis(platform);
30
+ return diagnosis.ok ? null : diagnosis.why;
31
+ }
32
+ export function sandboxRuntimeDiagnosis(platform = process.platform, io = {}) {
33
+ const found = diagnose(platform, io);
34
+ return found.ok ? found : { ...found, why: shownText(found.why) };
35
+ }
36
+ function diagnose(platform, io) {
24
37
  if (platform === "darwin") {
25
38
  if (!existsSync(SANDBOX_EXEC))
26
- return "this Mac has no sandbox-exec";
27
- const probe = spawnSync(SANDBOX_EXEC, ["-p", SEATBELT_PROBE, "/usr/bin/true"], { timeout: 5_000, stdio: "ignore" });
28
- return probe.status === 0 ? null : "sandbox-exec can't start a sandbox here (is this already inside one?)";
39
+ return { ok: false, kind: "missing-tool", why: "this Mac has no sandbox-exec" };
40
+ const probe = spawnSync(SANDBOX_EXEC, ["-p", SEATBELT_PROBE, "/usr/bin/true"], { timeout: 5_000, stdio: ["ignore", "ignore", "pipe"], encoding: "utf8" });
41
+ return probe.status === 0 ? { ok: true } : { ok: false, kind: "sandbox-denied", why: "sandbox-exec can't start a sandbox here (is this already inside one?)", detail: bounded(probe.stderr ?? "") };
29
42
  }
30
43
  if (platform === "linux") {
31
44
  const missing = missingLinuxSandboxTools();
32
45
  if (missing.length > 0)
33
- return `${toolWords(missing)} ${missing.length === 1 ? "is" : "are"} not installed (${linuxSandboxInstallLine(missing)})`;
46
+ return { ok: false, kind: "missing-tool", why: `${toolWords(missing)} ${missing.length === 1 ? "is" : "are"} not installed (${linuxSandboxInstallLine(missing)})` };
34
47
  const resolved = linuxSandboxTools();
35
- if (!resolved.ok)
36
- return resolved.why;
48
+ if (!resolved.ok) {
49
+ const kind = resolved.failure === "unsupported-arch" ? "unsupported-arch" : resolved.failure === "missing" ? "missing-tool" : "trust";
50
+ return { ok: false, kind, why: resolved.why };
51
+ }
37
52
  const { tools } = resolved;
38
53
  const paths = { bwrapPath: tools.bwrap.real, socatPath: tools.socat.real, seccompConfig: { applyPath: tools.seccomp.real } };
39
54
  const checked = checkLinuxDependencies(paths);
40
55
  if (checked.errors.length > 0)
41
- return checked.errors.join("; ");
56
+ return { ok: false, kind: "launch-error", why: checked.errors.join("; ") };
42
57
  if (!getLinuxDependencyStatus(paths).hasSeccompApply)
43
- return "the sandbox runtime's seccomp helper isn't available for this processor";
58
+ return { ok: false, kind: "unsupported-arch", why: "the sandbox runtime's seccomp helper isn't available for this processor" };
44
59
  if (spawnSync(tools.rg.real, ["--version"], { timeout: 5_000, stdio: "ignore" }).status !== 0)
45
- return `ripgrep (${tools.rg.real}) doesn't run`;
46
- const probe = spawnSync(tools.bwrap.real, ["--ro-bind", "/", "/", "--unshare-pid", "--unshare-user", "--proc", "/proc", "--new-session", "--", "true"], { timeout: 5_000, stdio: "ignore" });
47
- return probe.status === 0 ? null : "bubblewrap can't start a sandbox here (unprivileged user namespaces may be off)";
60
+ return { ok: false, kind: "launch-error", why: `ripgrep (${tools.rg.real}) doesn't run` };
61
+ const probe = spawnSync(tools.bwrap.real, ["--ro-bind", "/", "/", "--unshare-pid", "--unshare-user", "--proc", "/proc", "--new-session", "--", "true"], { timeout: 5_000, stdio: ["ignore", "ignore", "pipe"], encoding: "utf8", maxBuffer: 64 * 1024 });
62
+ if (probe.status === 0)
63
+ return { ok: true };
64
+ const detail = bounded(probe.stderr ?? "");
65
+ const code = probe.error?.code;
66
+ if (code === "ETIMEDOUT")
67
+ return { ok: false, kind: "timeout", why: "bubblewrap didn't finish starting a sandbox in time", detail };
68
+ if (probe.error !== undefined)
69
+ return { ok: false, kind: "launch-error", why: `bubblewrap (${tools.bwrap.real}) couldn't be started (${code ?? "error"})`, detail };
70
+ return deniedDiagnosis(detail, io);
48
71
  }
49
- return `the sandbox runtime has no sandbox for ${platform}`;
72
+ return { ok: false, kind: "unsupported-platform", why: `the sandbox runtime has no sandbox for ${platform}` };
73
+ }
74
+ export function deniedDiagnosis(detail, io = {}) {
75
+ return { ok: false, kind: "sandbox-denied", context: userNamespaceSettings(io), detail,
76
+ why: "this system denied the user namespace the sandbox needs; the cause isn't visible from inside this machine" };
77
+ }
78
+ export function userNamespaceSettings(io = {}) {
79
+ const found = [];
80
+ const read = (file) => { try {
81
+ return (io.read ?? (one => readFileSync(one, "utf8")))(file).trim();
82
+ }
83
+ catch {
84
+ return null;
85
+ } };
86
+ if (read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns") === "1")
87
+ found.push({
88
+ words: "kernel.apparmor_restrict_unprivileged_userns = 1 (AppArmor restricts unprivileged user namespaces)",
89
+ fix: "an administrator can give bubblewrap an AppArmor profile that allows user namespaces (a profile for /usr/bin/bwrap with `userns,`), rather than lifting the restriction for every program",
90
+ });
91
+ if (read("/proc/sys/kernel/unprivileged_userns_clone") === "0")
92
+ found.push({
93
+ words: "kernel.unprivileged_userns_clone = 0 (unprivileged user namespaces off)",
94
+ fix: "an administrator can turn them on: `sudo sysctl -w kernel.unprivileged_userns_clone=1`, kept in a file under /etc/sysctl.d/",
95
+ });
96
+ if (read("/proc/sys/user/max_user_namespaces") === "0")
97
+ found.push({
98
+ words: "user.max_user_namespaces = 0 (no user namespaces at all)",
99
+ fix: "an administrator can allow them: `sudo sysctl -w user.max_user_namespaces=15000`, kept in a file under /etc/sysctl.d/",
100
+ });
101
+ return found;
102
+ }
103
+ function looksContained(io) {
104
+ const exists = io.exists ?? existsSync;
105
+ if (exists("/.dockerenv") || exists("/run/.containerenv"))
106
+ return true;
107
+ try {
108
+ return /^Seccomp:\s*2$/m.test((io.read ?? (one => readFileSync(one, "utf8")))("/proc/self/status"));
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ }
114
+ export function sandboxRemedyLines(diagnosis, io = {}) {
115
+ if (diagnosis.ok || diagnosis.kind === "missing-tool" || diagnosis.kind === "trust")
116
+ return [];
117
+ const lines = [];
118
+ if (diagnosis.kind === "sandbox-denied")
119
+ for (const setting of diagnosis.context ?? [])
120
+ lines.push(`This machine shows ${setting.words}, which may be what denies it; if so, ${setting.fix}.`);
121
+ if (diagnosis.kind === "sandbox-denied" && looksContained(io)) {
122
+ lines.push("In a container (Docker, a devcontainer, Codespaces) its seccomp or AppArmor profile usually denies user namespaces: an administrator can allow them with a profile for this container. Starting it with `--security-opt seccomp=unconfined --security-opt apparmor=unconfined` also works, but weakens the container's own protection.");
123
+ }
124
+ if (diagnosis.kind === "unsupported-arch")
125
+ lines.push("This processor has no sandbox helper: Toolroll's sandbox runs on 64-bit Intel/AMD (x64) and ARM (arm64) Linux.");
126
+ lines.push(UNCONFINED_OPT_IN);
127
+ return lines;
128
+ }
129
+ export const UNCONFINED_OPT_IN = "Or an instance operator can let agents run without OS confinement: `toolroll config unconfined-agents allow` (their password, logged; refused while Toolroll runs without a password).";
130
+ export function sandboxAdviceLines(diagnosis, io = {}) {
131
+ if (diagnosis.ok || diagnosis.kind === "missing-tool")
132
+ return [];
133
+ if (diagnosis.kind === "trust")
134
+ return sandboxRuntimeRepair();
135
+ const said = diagnosis.detail === undefined || diagnosis.detail === "" ? [] : [`(${diagnosis.kind === "sandbox-denied" || diagnosis.kind === "timeout" ? "bubblewrap" : "it"} said: ${diagnosis.detail})`];
136
+ return [...said, ...sandboxRemedyLines(diagnosis, io)].map(shownText);
137
+ }
138
+ export function noConfinementWords(what, done, diagnosis = sandboxRuntimeDiagnosis()) {
139
+ const why = diagnosis.ok ? "its sandbox isn't available to this run" : diagnosis.why;
140
+ const fix = diagnosis.ok || diagnosis.kind === "missing-tool" ? "" : diagnosis.kind === "trust" ? " `toolroll doctor` prints the exact fix." : "";
141
+ return shownText(`This machine can't confine ${what}, so ${done}: ${why}.${fix} ${UNCONFINED_OPT_IN}`);
142
+ }
143
+ export function sandboxRuntimeRepair(platform = process.platform) {
144
+ if (platform !== "linux")
145
+ return [];
146
+ const repair = sandboxToolsRepair();
147
+ return repair === null ? [] : trustRepairLines(repair);
50
148
  }
51
149
  export const LINUX_SANDBOX_TOOLS = [
52
150
  { command: "bwrap", package: "bubblewrap" },
53
151
  { command: "socat", package: "socat" },
54
152
  { command: "rg", package: "ripgrep" },
153
+ { command: "bash", package: "bash" },
154
+ { command: "which", package: "which" },
55
155
  ];
56
156
  function toolWords(packages) {
57
157
  return packages.length <= 1 ? packages.join("") : `${packages.slice(0, -1).join(", ")} and ${packages.at(-1)}`;
@@ -69,8 +169,8 @@ export function missingLinuxSandboxTools(path = process.env["PATH"] ?? "") {
69
169
  });
70
170
  return LINUX_SANDBOX_TOOLS.filter(tool => !found(tool.command)).map(tool => tool.package);
71
171
  }
72
- export function linuxSandboxInstallLine(packages = LINUX_SANDBOX_TOOLS.map(tool => tool.package)) {
73
- return `sudo apt update && sudo apt install ${packages.join(" ")} (Fedora: sudo dnf install ${packages.join(" ")})`;
172
+ export function linuxSandboxInstallLine(packages = LINUX_SANDBOX_TOOLS.map(tool => tool.package), system = packageSystem()) {
173
+ return installLine(packages, system);
74
174
  }
75
175
  export const linuxSandboxToolsWords = () => toolWords(LINUX_SANDBOX_TOOLS.map(tool => tool.package));
76
176
  export function missingSandboxToolsWords(missing) {