@peer2peer/cli 0.1.2 → 0.1.4

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.
@@ -0,0 +1,763 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Sandbox by default: the agents' own sandboxes deny their commands read and write access to
4
+ // P2P_HOME (`~/.p2p`: the identity key, the person token, config.json's trust, the CLI's state).
5
+ // The CLI's gates (the widening and person-only ones, projects.ts) and the front ends' shell guards
6
+ // stop an agent that runs `p2p`; they can't stop one that reads the key files directly. The OS
7
+ // sandbox can.
8
+ //
9
+ // - `p2p sandbox`: whether Claude Code's and Codex's sandboxes deny P2P_HOME (read-only).
10
+ // - `p2p sandbox enable [--claude] [--codex] [--yes]`: adds the deny to the person's own config
11
+ // (Claude Code's user settings.json, Codex's config.toml), asking about each agent on its own
12
+ // after saying what changes, how to undo it and exactly what it writes (default Yes). Writes
13
+ // only a file that still holds what was shown; backs it up beside itself (0600) first, writes
14
+ // atomically, keeps everything else. `--yes` is refused on Windows (no process-tree check).
15
+ // - `p2p setup` (at a terminal) and `p2p codex install --write` offer the same once; a "no" is
16
+ // remembered per agent (config.json `sandboxDeclined`) and `p2p sandbox enable` asks again.
17
+ // - `p2p doctor` reports both (doctor.ts), and the Claude Code mod tells the person once.
18
+ //
19
+ // Only the person changes these files, and only outside every agent's session: the front ends'
20
+ // token doesn't count here (an agent's front end changing its own sandbox is what this is
21
+ // about), and an unreadable process tree refuses (fail closed). An agent can still read this
22
+ // command's output; it never contains a settings file's contents, only what this edit adds.
23
+ //
24
+ // What each sandbox enforces (docs/security/threat-model.md has the sources):
25
+ // - Claude Code: `sandbox.filesystem.denyRead|denyWrite` are enforced by the OS (Seatbelt on
26
+ // macOS, bubblewrap on Linux and WSL2) on Bash commands and every process they start; native
27
+ // Windows has no sandbox. The built-in file tools (Read, Edit, Grep, Glob) follow permission
28
+ // rules instead, hence `Read(…)`/`Edit(…)` deny rules too. Hooks, MCP servers and processes a
29
+ // mod starts run outside the sandbox, so the mod's own `p2p` runs keep working.
30
+ // - Codex: a permissions profile's `"deny"` entry, enforced by the OS on the commands Codex runs
31
+ // (codex-bridge sandbox.ts). MCP servers and hooks aren't sandboxed by it, so the bridge keeps
32
+ // working.
33
+ import { randomBytes } from "node:crypto";
34
+ import { closeSync, constants, existsSync, fstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
35
+ import { homedir } from "node:os";
36
+ import { dirname, isAbsolute, join, normalize, resolve, sep } from "node:path";
37
+ import * as codex from "@peer2peer/codex-bridge";
38
+ import { ancestryUnknown, ancestryWhy } from "./ancestry.js";
39
+ import { readFileConfig, resolveHome, setFileConfigField } from "./config.js";
40
+ import { CliError } from "./errors.js";
41
+ import { agentContext, sessionWorkdir } from "./projects.js";
42
+ /** The person's home folder, as the agents expand `~` (HOME, USERPROFILE on Windows). */
43
+ export function userHomeOf(env) {
44
+ return env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();
45
+ }
46
+ /** P2P_HOME, absolute, and its real path when that differs (a symbolic link on the way). */
47
+ export function p2pHomePaths(env) {
48
+ const home = normalize(resolve(resolveHome(env)));
49
+ try {
50
+ const real = realpathSync(home);
51
+ return real !== home ? { home, real } : { home };
52
+ }
53
+ catch {
54
+ return { home };
55
+ }
56
+ }
57
+ /** Whether `path` is `root` or inside it (normalized; case-insensitive on macOS and Windows). */
58
+ function within(path, root) {
59
+ const caseless = process.platform === "darwin" || process.platform === "win32";
60
+ const a = caseless ? path.toLowerCase() : path;
61
+ const b = caseless ? root.toLowerCase() : root;
62
+ const r = b.endsWith(sep) ? b : b + sep;
63
+ return a === b || a.startsWith(r);
64
+ }
65
+ /** `~/…` for a path under the home folder, else the path itself. */
66
+ function tildeForm(abs, userHome) {
67
+ const h = normalize(resolve(userHome));
68
+ return abs.startsWith(h + sep) ? `~/${abs.slice(h.length + 1).split(sep).join("/")}` : abs;
69
+ }
70
+ // ── Claude Code ─────────────────────────────────────────────────────────────
71
+ /** Claude Code's user settings file: `$CLAUDE_CONFIG_DIR/settings.json`, else `~/.claude/settings.json`. */
72
+ export function claudeSettingsPath(env) {
73
+ const dir = env.CLAUDE_CONFIG_DIR?.trim();
74
+ return join(dir ? resolve(dir) : join(userHomeOf(env), ".claude"), "settings.json");
75
+ }
76
+ /** Managed settings (what an organization deploys): read for the status only, never written. */
77
+ export function claudeManagedPath(platform = process.platform) {
78
+ if (platform === "darwin")
79
+ return "/Library/Application Support/ClaudeCode/managed-settings.json";
80
+ if (platform === "linux")
81
+ return "/etc/claude-code/managed-settings.json";
82
+ return undefined;
83
+ }
84
+ /** What Claude Code's settings should hold for P2P_HOME: the sandbox paths, and the file tools' rules. */
85
+ export function claudeWanted(paths, userHome) {
86
+ const homes = [paths.home, ...(paths.real ? [paths.real] : [])];
87
+ const sandbox = homes.map((h) => tildeForm(h, userHome));
88
+ // Permission rules: `~/x` from the home folder, `//abs` for an absolute path.
89
+ const rule = (h) => {
90
+ const t = tildeForm(h, userHome);
91
+ return t.startsWith("~/") ? `${t}/**` : `/${h.split(sep).join("/")}/**`;
92
+ };
93
+ return { sandbox, read: homes.map((h) => `Read(${rule(h)})`), edit: homes.map((h) => `Edit(${rule(h)})`) };
94
+ }
95
+ /** `s` without its trailing slashes and backslashes (a loop: no regular expression on settings text). */
96
+ function trimSlashes(s) {
97
+ let end = s.length;
98
+ while (end > 1 && (s[end - 1] === "/" || s[end - 1] === "\\"))
99
+ end--;
100
+ return s.slice(0, end);
101
+ }
102
+ /**
103
+ * A sandbox path entry as an absolute path (`~/x`, `/x`, `//x`), or undefined for a relative one.
104
+ * `base` resolves a relative entry (a project's settings resolve it against the project root).
105
+ */
106
+ function sandboxPath(entry, userHome, base) {
107
+ const e = trimSlashes(entry.trim());
108
+ if (e === "~")
109
+ return normalize(userHome);
110
+ if (e.startsWith("~/"))
111
+ return normalize(join(userHome, e.slice(2)));
112
+ if (e.startsWith("//"))
113
+ return normalize(e.slice(1));
114
+ if (isAbsolute(e))
115
+ return normalize(e);
116
+ return base && e !== "" ? normalize(resolve(base, e)) : undefined;
117
+ }
118
+ /** A `Read(…)`/`Edit(…)` rule's folder when it covers everything under it (`P` or `P/**`, no other glob), else undefined. */
119
+ function ruleFolder(rule, tool, userHome) {
120
+ if (!rule.startsWith(`${tool}(`) || !rule.endsWith(")"))
121
+ return undefined;
122
+ let p = rule.slice(tool.length + 1, -1).trim();
123
+ if (p.endsWith("/**"))
124
+ p = p.slice(0, -3);
125
+ if (p === "" || /[*?[\]{}]/.test(p))
126
+ return undefined;
127
+ if (p === "~")
128
+ return normalize(userHome);
129
+ if (p.startsWith("~/"))
130
+ return normalize(join(userHome, p.slice(2)));
131
+ if (p.startsWith("//"))
132
+ return normalize(p.slice(1));
133
+ return undefined;
134
+ }
135
+ const obj = (v) => (typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined);
136
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
137
+ /** The most a config file read here may hold: anything bigger is treated as unreadable. */
138
+ export const MAX_CONFIG_BYTES = 1024 * 1024;
139
+ /**
140
+ * Reads a config file safely, whoever put it there (a cloned repository's `.claude` or `.codex`):
141
+ * opened non-blocking (a FIFO can't hang the read), it must be a regular file once a symbolic link
142
+ * is followed (not a FIFO, a device such as /dev/zero, or a folder), and at most MAX_CONFIG_BYTES.
143
+ * null when it doesn't exist; throws a CliError when it can't be read that way.
144
+ */
145
+ export function readConfigFile(path) {
146
+ let fd;
147
+ try {
148
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
149
+ }
150
+ catch (e) {
151
+ if (e.code === "ENOENT")
152
+ return null;
153
+ throw new CliError("config", `${path} couldn't be read: ${e.message}`);
154
+ }
155
+ try {
156
+ const st = fstatSync(fd);
157
+ if (!st.isFile())
158
+ throw new CliError("config", `${path} isn't a regular file, so it wasn't read`);
159
+ if (st.size > MAX_CONFIG_BYTES)
160
+ throw new CliError("config", `${path} is larger than ${MAX_CONFIG_BYTES} bytes, so it wasn't read`);
161
+ const buf = Buffer.alloc(MAX_CONFIG_BYTES + 1);
162
+ let n = 0;
163
+ for (;;) {
164
+ const r = readSync(fd, buf, n, buf.length - n, null);
165
+ if (r === 0)
166
+ break;
167
+ n += r;
168
+ if (n > MAX_CONFIG_BYTES)
169
+ throw new CliError("config", `${path} is larger than ${MAX_CONFIG_BYTES} bytes, so it wasn't read`);
170
+ }
171
+ return buf.subarray(0, n).toString("utf8");
172
+ }
173
+ finally {
174
+ closeSync(fd);
175
+ }
176
+ }
177
+ /** Reads a JSON settings file: undefined when it doesn't exist, "bad" when it isn't a readable JSON object. */
178
+ function readJson(path) {
179
+ if (!path)
180
+ return undefined;
181
+ let text;
182
+ try {
183
+ const t = readConfigFile(path);
184
+ if (t === null)
185
+ return undefined;
186
+ text = t;
187
+ }
188
+ catch {
189
+ return "bad";
190
+ }
191
+ if (text.trim() === "")
192
+ return {};
193
+ try {
194
+ return obj(JSON.parse(text)) ?? "bad";
195
+ }
196
+ catch {
197
+ return "bad";
198
+ }
199
+ }
200
+ /** The folders whose `.claude` settings a session here loads: its working directory and, in a git repository, the repository root. */
201
+ export function projectRoots(workdir) {
202
+ const out = [normalize(workdir)];
203
+ let d = normalize(workdir);
204
+ for (let i = 0; i < 64; i++) {
205
+ if (existsSync(join(d, ".git"))) {
206
+ if (!out.includes(d))
207
+ out.push(d);
208
+ break;
209
+ }
210
+ const up = dirname(d);
211
+ if (up === d)
212
+ break;
213
+ d = up;
214
+ }
215
+ return out;
216
+ }
217
+ /** Whether `name` is an executable file in one of PATH's absolute folders. */
218
+ function onPath(name, env) {
219
+ for (const dir of (env.PATH ?? "").split(":")) {
220
+ if (!dir || !isAbsolute(dir))
221
+ continue;
222
+ try {
223
+ if (statSync(join(dir, name)).isFile())
224
+ return true;
225
+ }
226
+ catch {
227
+ // not here
228
+ }
229
+ }
230
+ return false;
231
+ }
232
+ /**
233
+ * Whether Claude Code's sandbox denies its commands (and its file tools) P2P_HOME: from the user,
234
+ * managed and this folder's project settings (`.claude/settings.json` and `.claude/settings.local.json`
235
+ * in the session's folder and its repository root), and, on Linux, whether bubblewrap is there.
236
+ */
237
+ export function claudeSandboxStatus(env, o = {}) {
238
+ const settings = claudeSettingsPath(env);
239
+ const platform = o.platform ?? process.platform;
240
+ const base = { settings, missing: [], notes: [] };
241
+ if (platform === "win32")
242
+ return { ...base, state: "unavailable", detail: "Claude Code has no sandbox on native Windows (it runs commands unsandboxed); use WSL2" };
243
+ const problem = p2pHomeProblem(env);
244
+ if (problem)
245
+ return { ...base, state: "unknown", detail: problem };
246
+ const user = readJson(settings);
247
+ if (user === "bad")
248
+ return { ...base, state: "unknown", detail: `${settings} isn't a JSON object, so it couldn't be read` };
249
+ const managedFile = o.managedPath === null ? undefined : (o.managedPath ?? claudeManagedPath(platform));
250
+ const managed = readJson(managedFile);
251
+ // Project settings, highest first (local over shared, the session's folder over the repository root).
252
+ const project = [];
253
+ const unreadable = [];
254
+ for (const root of projectRoots(o.workdir ?? sessionWorkdir(env))) {
255
+ for (const name of ["settings.local.json", "settings.json"]) {
256
+ const file = join(root, ".claude", name);
257
+ if (file === settings)
258
+ continue;
259
+ const doc = readJson(file);
260
+ if (doc === "bad")
261
+ unreadable.push(file);
262
+ else if (doc)
263
+ project.push({ file, root, doc });
264
+ }
265
+ }
266
+ const managedDoc = managed && managed !== "bad" ? managed : undefined;
267
+ const userHome = userHomeOf(env);
268
+ const want = claudeWanted(p2pHomePaths(env), userHome);
269
+ const homes = want.sandbox.map((s) => sandboxPath(s, userHome));
270
+ const sb = (s) => obj(s.sandbox) ?? {};
271
+ const fs = (s) => obj(sb(s).filesystem) ?? {};
272
+ // Every source with the folder its relative paths resolve against.
273
+ const sources = [
274
+ ...(managedDoc ? [{ doc: managedDoc }] : []),
275
+ ...project.map((p) => ({ doc: p.doc, base: p.root, file: p.file })),
276
+ ...(user ? [{ doc: user, base: dirname(settings) }] : []),
277
+ ];
278
+ // Booleans: the highest source that sets one decides (managed, project local, project, user).
279
+ const flag = (k) => {
280
+ for (const src of sources)
281
+ if (typeof sb(src.doc)[k] === "boolean")
282
+ return { value: sb(src.doc)[k], ...(src.file ? { file: src.file } : {}) };
283
+ return { value: undefined };
284
+ };
285
+ const deny = sources.flatMap((src) => strs(obj(src.doc.permissions)?.deny));
286
+ const ruleCovers = (tool) => (h) => deny.some((r) => {
287
+ const p = ruleFolder(r, tool, userHome);
288
+ return p !== undefined && within(h, p);
289
+ });
290
+ const covered = (key, tool) => (h) => sources.some((src) => strs(fs(src.doc)[key]).some((e) => {
291
+ const p = sandboxPath(e, userHome, src.base);
292
+ return p !== undefined && within(h, p);
293
+ })) || ruleCovers(tool)(h);
294
+ const missing = [];
295
+ const enabled = flag("enabled");
296
+ if (enabled.value !== true)
297
+ missing.push(enabled.file ? `sandbox.enabled (${enabled.file} turns it off in this project)` : "sandbox.enabled");
298
+ const retry = flag("allowUnsandboxedCommands");
299
+ if (retry.value !== false)
300
+ missing.push(retry.file ? `sandbox.allowUnsandboxedCommands = false (${retry.file} allows the retry in this project)` : "sandbox.allowUnsandboxedCommands = false");
301
+ if (!homes.every(covered("denyRead", "Read")))
302
+ missing.push(`sandbox.filesystem.denyRead ${want.sandbox.join(", ")}`);
303
+ if (!homes.every(covered("denyWrite", "Edit")))
304
+ missing.push(`sandbox.filesystem.denyWrite ${want.sandbox.join(", ")}`);
305
+ if (!homes.every(ruleCovers("Read")))
306
+ missing.push(`permissions.deny ${want.read.join(", ")}`);
307
+ if (!homes.every(ruleCovers("Edit")))
308
+ missing.push(`permissions.deny ${want.edit.join(", ")}`);
309
+ const notes = [];
310
+ // A narrower allow inside the denied folder opens it again ("the rule with the narrower path applies").
311
+ for (const k of ["allowRead", "allowWrite"]) {
312
+ for (const src of sources) {
313
+ for (const e of strs(fs(src.doc)[k])) {
314
+ const p = sandboxPath(e, userHome, src.base);
315
+ if (p && homes.some((h) => within(p, h)))
316
+ missing.push(`no sandbox.filesystem.${k} inside P2P_HOME (${e}${src.file ? ` in ${src.file}` : ""})`);
317
+ }
318
+ }
319
+ }
320
+ if (platform === "linux" && (!onPath("bwrap", env) || !onPath("socat", env))) {
321
+ missing.push("bubblewrap and socat (Claude Code's sandbox needs both on Linux; without them it runs commands unsandboxed unless sandbox.failIfUnavailable is set)");
322
+ }
323
+ const excluded = sources.flatMap((src) => strs(sb(src.doc).excludedCommands));
324
+ if (excluded.length > 0)
325
+ notes.push(`sandbox.excludedCommands lists ${excluded.length} command pattern${excluded.length === 1 ? "" : "s"}: those run outside the sandbox, P2P_HOME included`);
326
+ if (managed === "bad")
327
+ notes.push(`${managedFile} couldn't be read`);
328
+ for (const f of unreadable)
329
+ notes.push(`${f} couldn't be read, so what it sets isn't known`);
330
+ if (missing.length === 0 && unreadable.length > 0) {
331
+ return { settings, missing, notes, state: "unknown", detail: `the user settings deny ${want.sandbox.join(" and ")}, but a project settings file here couldn't be read` };
332
+ }
333
+ if (missing.length === 0)
334
+ return { settings, missing, notes, state: "on", detail: `Claude Code's sandbox denies its commands ${want.sandbox.join(" and ")}, and its file tools have deny rules for it` };
335
+ return { settings, missing, notes, state: "off", detail: `Claude Code's sandbox doesn't keep its commands out of ${want.sandbox.join(" and ")}: missing ${missing.join("; ")}` };
336
+ }
337
+ /** The indentation a JSON text uses (its first indented line), else two spaces. */
338
+ function indentOf(text) {
339
+ // A loop, not a regular expression, over the person's file.
340
+ for (const line of text.split("\n")) {
341
+ let i = 0;
342
+ while (i < line.length && (line[i] === " " || line[i] === "\t"))
343
+ i++;
344
+ if (i > 0 && (line[i] === '"' || line[i] === "}" || line[i] === "]"))
345
+ return line.slice(0, i);
346
+ }
347
+ return " ";
348
+ }
349
+ /**
350
+ * The edit to Claude Code's user settings (`text`, null when the file doesn't exist) that denies
351
+ * P2P_HOME to its sandboxed commands and file tools, keeping every other key and the file's
352
+ * indentation. Idempotent: entries already there (or a folder above P2P_HOME) aren't added again.
353
+ */
354
+ export function planClaudeSandbox(text, env) {
355
+ let doc = {};
356
+ if (text !== null && text.trim() !== "") {
357
+ let v;
358
+ try {
359
+ v = JSON.parse(text);
360
+ }
361
+ catch {
362
+ return { kind: "manual", reason: "settings.json isn't valid JSON (Claude Code reads it as strict JSON): fix it first" };
363
+ }
364
+ const o = obj(v);
365
+ if (!o)
366
+ return { kind: "manual", reason: "settings.json doesn't hold a JSON object" };
367
+ doc = o;
368
+ }
369
+ for (const [k, parent] of [["sandbox", doc], ["permissions", doc]]) {
370
+ if (parent[k] !== undefined && !obj(parent[k]))
371
+ return { kind: "manual", reason: `"${k}" in settings.json isn't an object` };
372
+ }
373
+ const sandbox = doc.sandbox ?? {};
374
+ if (sandbox.filesystem !== undefined && !obj(sandbox.filesystem))
375
+ return { kind: "manual", reason: `"sandbox.filesystem" in settings.json isn't an object` };
376
+ const fs = sandbox.filesystem ?? {};
377
+ const permissions = doc.permissions ?? {};
378
+ for (const [k, v] of [["sandbox.filesystem.denyRead", fs.denyRead], ["sandbox.filesystem.denyWrite", fs.denyWrite], ["permissions.deny", permissions.deny]]) {
379
+ if (v !== undefined && !Array.isArray(v))
380
+ return { kind: "manual", reason: `"${k}" in settings.json isn't a list` };
381
+ }
382
+ const userHome = userHomeOf(env);
383
+ const want = claudeWanted(p2pHomePaths(env), userHome);
384
+ const edits = [];
385
+ if (sandbox.enabled !== true) {
386
+ edits.push({ key: "sandbox.enabled", value: true, ...(sandbox.enabled !== undefined ? { was: sandbox.enabled } : {}) });
387
+ sandbox.enabled = true;
388
+ }
389
+ // Older Claude Code releases ran sandboxed commands without a prompt by default (before v2.1.324):
390
+ // the person's own approvals stay, unless they set this themselves.
391
+ if (sandbox.autoAllowBashIfSandboxed === undefined) {
392
+ edits.push({ key: "sandbox.autoAllowBashIfSandboxed", value: false });
393
+ sandbox.autoAllowBashIfSandboxed = false;
394
+ }
395
+ if (sandbox.allowUnsandboxedCommands !== false) {
396
+ edits.push({ key: "sandbox.allowUnsandboxedCommands", value: false, ...(sandbox.allowUnsandboxedCommands !== undefined ? { was: sandbox.allowUnsandboxedCommands } : {}) });
397
+ sandbox.allowUnsandboxedCommands = false;
398
+ }
399
+ const addPaths = (key) => {
400
+ const list = strs(fs[key]);
401
+ const cur = Array.isArray(fs[key]) ? fs[key] : [];
402
+ for (const p of want.sandbox) {
403
+ const abs = sandboxPath(p, userHome);
404
+ if (list.some((e) => {
405
+ const q = sandboxPath(e, userHome);
406
+ return q !== undefined && within(abs, q);
407
+ }))
408
+ continue;
409
+ cur.push(p);
410
+ edits.push({ key: `sandbox.filesystem.${key}`, value: p, append: true });
411
+ }
412
+ if (cur.length > 0)
413
+ fs[key] = cur;
414
+ };
415
+ addPaths("denyRead");
416
+ addPaths("denyWrite");
417
+ const deny = Array.isArray(permissions.deny) ? permissions.deny : [];
418
+ for (const [tool, rules] of [["Read", want.read], ["Edit", want.edit]]) {
419
+ rules.forEach((r, i) => {
420
+ const abs = sandboxPath(want.sandbox[i], userHome);
421
+ if (strs(deny).some((e) => {
422
+ const q = ruleFolder(e, tool, userHome);
423
+ return q !== undefined && within(abs, q);
424
+ }))
425
+ return;
426
+ deny.push(r);
427
+ edits.push({ key: "permissions.deny", value: r, append: true });
428
+ });
429
+ }
430
+ if (edits.length === 0)
431
+ return { kind: "already" };
432
+ if (Object.keys(fs).length > 0)
433
+ sandbox.filesystem = fs;
434
+ doc.sandbox = sandbox;
435
+ if (deny.length > 0)
436
+ doc.permissions = { ...permissions, deny };
437
+ const after = `${JSON.stringify(doc, null, text ? indentOf(text) : 2)}\n`;
438
+ return { kind: "edit", after, edits };
439
+ }
440
+ function readText(path) {
441
+ return readConfigFile(path);
442
+ }
443
+ const isDir = (p) => {
444
+ try {
445
+ return statSync(p).isDirectory();
446
+ }
447
+ catch {
448
+ return false;
449
+ }
450
+ };
451
+ /** The Codex home (CODEX_HOME, else ~/.codex) and its config.toml. */
452
+ export function codexConfigPath(env) {
453
+ const h = env.CODEX_HOME?.trim();
454
+ return join(h ? resolve(h) : join(userHomeOf(env), ".codex"), "config.toml");
455
+ }
456
+ /** The deny paths for Codex's config (`~/…` under the home folder). */
457
+ export function codexDenyPathsOf(env) {
458
+ const p = p2pHomePaths(env);
459
+ return codex.codexDenyPaths(p.home, userHomeOf(env), p.real);
460
+ }
461
+ /** Characters that mean something in a permission rule or a glob: a P2P_HOME holding one isn't written into a rule. */
462
+ const RULE_CHARS = new Set(["[", "]", "{", "}", "*", "?", "(", ")"]);
463
+ /**
464
+ * Why P2P_HOME can't be denied safely, or undefined: a path with rule or glob characters (it would
465
+ * match something else, or break the rule), or the home folder itself, `/` or a folder above the home
466
+ * folder (denying it would lock the agents out of everything).
467
+ */
468
+ export function p2pHomeProblem(env) {
469
+ const paths = p2pHomePaths(env);
470
+ const userHome = normalize(resolve(userHomeOf(env)));
471
+ for (const h of [paths.home, ...(paths.real ? [paths.real] : [])]) {
472
+ if ([...h].some((c) => RULE_CHARS.has(c)))
473
+ return `P2P_HOME (${h}) has a character that means something in a sandbox rule ([ ] { } * ? ( )): move it to a plain path, then run this again`;
474
+ if (h === sep || within(userHome, h))
475
+ return `P2P_HOME (${h}) is your home folder or a folder above it: denying it would shut your agents out of everything. Point P2P_HOME at its own folder`;
476
+ }
477
+ return undefined;
478
+ }
479
+ /** The project `.codex/config.toml` files Codex loads here when the project is trusted (repository root down to the folder). */
480
+ function codexProjectConfigs(workdir) {
481
+ const roots = projectRoots(workdir);
482
+ const top = roots[roots.length - 1];
483
+ const out = [];
484
+ let d = normalize(workdir);
485
+ for (let i = 0; i < 64; i++) {
486
+ const f = join(d, ".codex", "config.toml");
487
+ if (existsSync(f))
488
+ out.push(f);
489
+ if (d === top)
490
+ break;
491
+ const up = dirname(d);
492
+ if (up === d)
493
+ break;
494
+ d = up;
495
+ }
496
+ return out;
497
+ }
498
+ export function codexStatus(env, o = {}) {
499
+ const path = codexConfigPath(env);
500
+ const problem = p2pHomeProblem(env);
501
+ if (problem)
502
+ return { state: "unknown", detail: problem, notes: [], settings: path };
503
+ let text;
504
+ try {
505
+ text = readText(path);
506
+ }
507
+ catch {
508
+ return { state: "unknown", detail: `${path} couldn't be read`, notes: [], settings: path };
509
+ }
510
+ const st = { ...codex.codexSandboxStatus(text, codexDenyPathsOf(env), userHomeOf(env)), settings: path };
511
+ // A trusted project's own config.toml can choose another sandbox here; whether Codex trusts the
512
+ // project isn't known from outside, so "on" becomes "?" when one does.
513
+ const overriding = [];
514
+ for (const f of codexProjectConfigs(o.workdir ?? sessionWorkdir(env))) {
515
+ if (f === path)
516
+ continue;
517
+ let t;
518
+ try {
519
+ t = readText(f);
520
+ }
521
+ catch {
522
+ overriding.push(`${f} (unreadable)`);
523
+ continue;
524
+ }
525
+ const lines = t === null ? [] : codex.scanTomlLines(t);
526
+ if (lines === null) {
527
+ overriding.push(`${f} (unreadable)`);
528
+ continue;
529
+ }
530
+ if (lines.some((l) => l.kind === "kv" && (["sandbox_mode", "default_permissions", "permissions"].includes([...l.table, ...l.key][0]))))
531
+ overriding.push(f);
532
+ else if (lines.some((l) => l.kind === "header" && l.table[0] === "permissions"))
533
+ overriding.push(f);
534
+ }
535
+ if (overriding.length === 0)
536
+ return st;
537
+ const note = `${overriding.join(", ")} sets its own sandbox or permissions: when Codex trusts this project, that applies here instead`;
538
+ return st.state === "on" ? { ...st, state: "unknown", detail: `${st.detail}, but a project config may override it here`, notes: [...st.notes, note] } : { ...st, notes: [...st.notes, note] };
539
+ }
540
+ const show = (v) => JSON.stringify(v);
541
+ /** What `enable` would do for one front end (computed, nothing written). */
542
+ export function planFront(front, env, o = {}) {
543
+ const path = front === "claude" ? claudeSettingsPath(env) : codexConfigPath(env);
544
+ const present = isDir(dirname(path));
545
+ const problem = p2pHomeProblem(env);
546
+ if (front === "claude") {
547
+ const status = claudeSandboxStatus(env, o);
548
+ if (status.state === "unavailable")
549
+ return { front, path, present, status, plan: { kind: "unavailable" } };
550
+ if (problem)
551
+ return { front, path, present, status, plan: { kind: "manual", reason: problem } };
552
+ let before;
553
+ try {
554
+ before = readText(path);
555
+ }
556
+ catch (e) {
557
+ return { front, path, present, status, plan: { kind: "manual", reason: e.message } };
558
+ }
559
+ const p = planClaudeSandbox(before, env);
560
+ if (p.kind !== "edit")
561
+ return { front, path, present, status, plan: p };
562
+ const preview = p.edits.map((e) => (e.append ? ` ${e.key} += ${show(e.value)}` : ` ${e.key} = ${show(e.value)}${e.was !== undefined ? ` (was ${show(e.was)})` : ""}`));
563
+ return { front, path, present, status, plan: { kind: "edit", before, after: p.after, preview } };
564
+ }
565
+ const status = codexStatus(env, o);
566
+ if (problem)
567
+ return { front, path, present, status, plan: { kind: "manual", reason: problem } };
568
+ let before;
569
+ try {
570
+ before = readText(path);
571
+ }
572
+ catch (e) {
573
+ return { front, path, present, status, plan: { kind: "manual", reason: e.message } };
574
+ }
575
+ const p = codex.planCodexSandbox(before, codexDenyPathsOf(env), userHomeOf(env), o.codexBase ? { baseWhenUnset: o.codexBase } : {});
576
+ if (p.kind === "already")
577
+ return { front, path, present, status, plan: { kind: "already" } };
578
+ if (p.kind === "manual")
579
+ return { front, path, present, status, plan: { kind: "manual", reason: p.reason, snippet: p.snippet } };
580
+ const preview = p.edits.map((e) => ("add" in e ? ` + ${e.add}` : ` - ${e.before}\n + ${e.after}`));
581
+ return { front, path, present, status, plan: { kind: "edit", before, after: p.after, preview, ...(p.base ? { base: p.base } : {}), ...(p.assumed ? { assumed: true } : {}) } };
582
+ }
583
+ /** The name the person knows each front end's agent by. */
584
+ export const AGENT_NAME = { claude: "Claude Code", codex: "Codex" };
585
+ /** What one agent's edit does, in full, then the exact lines: asked about on its own. */
586
+ export function frontPreview(f, p2pHome, userHome) {
587
+ if (f.plan.kind !== "edit")
588
+ return "";
589
+ const home = tildeForm(p2pHome, userHome);
590
+ const why = f.front === "claude"
591
+ ? [
592
+ `Your agents run as you, so Claude Code can read ${home} (your identity key and person token) unless its`,
593
+ "sandbox denies it. This adds that deny to your Claude Code user settings, and changes, in every project:",
594
+ " - Claude's shell commands run in Claude Code's sandbox: they write only inside the project (and folders",
595
+ " you add to sandbox.filesystem.allowWrite) and reach only network hosts you allow (Claude Code asks for",
596
+ " a new host). A build or tool that writes elsewhere (a global cache, say) may fail or ask.",
597
+ " - No retry outside the sandbox (allowUnsandboxedCommands: false): a command the sandbox blocks just fails.",
598
+ " - Your permission prompts stay as they are (autoAllowBashIfSandboxed: false, unless you set it already).",
599
+ ` - Claude's shell and its Read/Edit tools can't open ${home}, so they can't run p2p any more either; Claude`,
600
+ " uses ListAgents, SendMessage and /peers. The Peer2Peer mod isn't affected (what a mod starts runs outside",
601
+ " the sandbox).",
602
+ ` - To undo: put the backup back (${f.path}.p2p-backup-<time>), or remove the keys below.`,
603
+ ]
604
+ : [
605
+ `Your agents run as you, so Codex can read ${home} (your identity key and person token) unless its sandbox`,
606
+ "denies it. This has Codex's commands run under a permissions profile that denies it:",
607
+ ...(f.plan.assumed
608
+ ? [
609
+ " - Your config sets no sandbox, and Codex then picks one per folder (workspace-write in a version-controlled",
610
+ ` folder, read-only elsewhere), which a profile can't. This one extends ${f.plan.base}${f.plan.base === ":read-only" ? ": Codex's commands can't write (it asks first under an on-request approval policy; under \"never\", a write just fails)" : ": Codex's commands write in the workspace, in every folder, including ones Codex hasn't trusted"}.`,
611
+ ` ${f.plan.base === ":read-only" ? "`p2p sandbox enable --codex --codex-base workspace` lets them write in the workspace instead (in folders Codex hasn't trusted too)." : "`--codex-base read-only` keeps them read-only instead."}`,
612
+ ]
613
+ : [" - It extends the sandbox you use now, so writes and network stay as they were."]),
614
+ " - Codex's shell can't open it, so it can't run p2p any more either; Codex uses the bridge's p2p_* tools.",
615
+ " The bridge isn't affected (Codex doesn't sandbox MCP servers or hooks). Restart open Codex sessions.",
616
+ ` - To undo: put the backup back (${f.path}.p2p-backup-<time>), or remove the lines marked p2p sandbox.`,
617
+ ];
618
+ return [`${AGENT_NAME[f.front]}: ${f.path}`, ...why, "", "Exactly what is written (the file is backed up first; everything else in it stays):", ...f.plan.preview].join("\n");
619
+ }
620
+ /** The question for one agent. */
621
+ export function frontQuestion(f) {
622
+ return f.front === "claude" ? "Turn on Claude Code's sandbox with this deny?" : "Add this to Codex's config?";
623
+ }
624
+ /**
625
+ * Writes the planned edits. Each file must still hold what the preview was made from (else nothing
626
+ * is written). The backup sits next to the path as named (a symbolic link's own folder, not its
627
+ * target's), 0600, created exclusively; the new content is written atomically to the link's target,
628
+ * keeping its mode.
629
+ */
630
+ export function applyPlans(plans, now = new Date()) {
631
+ const changes = plans.flatMap((f) => (f.plan.kind === "edit" ? [{ path: f.path, before: f.plan.before, after: f.plan.after }] : []));
632
+ for (const c of changes) {
633
+ if (readText(c.path) !== c.before)
634
+ throw new CliError("changed", `${c.path} changed after it was shown: nothing was written. Run the command again to see the changes`);
635
+ }
636
+ const stamp = now.toISOString().replace(/[:.]/g, "-");
637
+ const done = [];
638
+ for (const c of changes) {
639
+ const target = codex.resolveLink(c.path);
640
+ mkdirSync(dirname(target), { recursive: true });
641
+ let backup;
642
+ if (c.before !== null) {
643
+ backup = `${c.path}.p2p-backup-${stamp}`;
644
+ writeFileSync(backup, c.before, { mode: 0o600, flag: "wx" });
645
+ }
646
+ let mode = 0o600;
647
+ try {
648
+ mode = statSync(target).mode & 0o777;
649
+ }
650
+ catch {
651
+ // a new file: 0600
652
+ }
653
+ const tmp = `${target}.p2p-tmp-${randomBytes(8).toString("hex")}`;
654
+ rmSync(tmp, { force: true });
655
+ writeFileSync(tmp, c.after, { mode, flag: "wx" });
656
+ renameSync(tmp, target);
657
+ done.push({ path: c.path, ...(backup ? { backup } : {}) });
658
+ }
659
+ return done;
660
+ }
661
+ /**
662
+ * Only the person changes an agent's sandbox, at their own terminal, outside every agent's session:
663
+ * never with a front end's token (that would be an agent's front end changing its own sandbox), and
664
+ * never when the process tree can't be read (fail closed).
665
+ */
666
+ export function assertPersonOutsideAgents(app, what) {
667
+ const why = `\`p2p ${what}\` changes your agents' sandbox, so only you run it, in your own terminal (not inside Claude Code or Codex)`;
668
+ if (app.front === true)
669
+ throw new CliError("refused", `${why}. A front end (the Claude Code mod, the Codex bridge) never changes its own agent's sandbox`);
670
+ if (agentContext(app.env))
671
+ throw new CliError("refused", `${why}. It was refused here because it runs inside an agent's session`);
672
+ if (ancestryUnknown())
673
+ throw new CliError("refused", `${why}. It was refused here because p2p couldn't read its process tree to tell whether it runs inside an agent's session${ancestryWhy() ? ` (${ancestryWhy()})` : ""}`);
674
+ }
675
+ /** Which agents the person said no for (FileConfig.sandboxDeclined: `true` for both, as an older answer, or a list). */
676
+ export function sandboxDeclined(file, front) {
677
+ const v = file.sandboxDeclined;
678
+ if (v === true)
679
+ return true;
680
+ if (!Array.isArray(v))
681
+ return false;
682
+ return front ? v.includes(front) : v.length > 0;
683
+ }
684
+ /** Records the person's answer for one agent. */
685
+ export function setSandboxDeclined(home, front, declined) {
686
+ let cur = [];
687
+ try {
688
+ const v = readFileConfig(home).sandboxDeclined;
689
+ cur = v === true ? ["claude", "codex"] : Array.isArray(v) ? v.filter((x) => x === "claude" || x === "codex") : [];
690
+ }
691
+ catch {
692
+ // unreadable: start over
693
+ }
694
+ const next = declined ? [...new Set([...cur, front])] : cur.filter((f) => f !== front);
695
+ setFileConfigField(home, "sandboxDeclined", next);
696
+ }
697
+ /** The front ends worth offering: installed here (their config folder exists), with an edit to make. */
698
+ export function offerablePlans(env, only, o = {}) {
699
+ const fronts = only ?? ["claude", "codex"];
700
+ return fronts.map((f) => planFront(f, env, o)).filter((f) => (only ? true : f.present) && f.plan.kind === "edit");
701
+ }
702
+ /** Whether the person said no before, for `front` (any, without one); config.json unreadable counts as no answer. */
703
+ export function declinedHere(env, front) {
704
+ try {
705
+ return sandboxDeclined(readFileConfig(resolveHome(env)), front);
706
+ }
707
+ catch {
708
+ return false;
709
+ }
710
+ }
711
+ /** Whether a front end's config folder is here at all. */
712
+ export function frontPresent(front, env) {
713
+ return existsSync(dirname(front === "claude" ? claudeSettingsPath(env) : codexConfigPath(env)));
714
+ }
715
+ /**
716
+ * The one-time notice a front end shows its person (never its model) when its agent's sandbox
717
+ * doesn't deny P2P_HOME: the command to run in their own terminal. Undefined when the sandbox
718
+ * already does, the person said no before, it was shown already (once per device and front end),
719
+ * or the caller is neither the person's front end nor the person. An agent's shell without the token
720
+ * can't use it up; one that already reads P2P_HOME (no sandbox yet) can take the token and can.
721
+ */
722
+ export async function sandboxNotice(app, front) {
723
+ if (app.front !== true && agentContext(app.env))
724
+ return undefined;
725
+ if (declinedHere(app.env, front))
726
+ return undefined;
727
+ const st = front === "claude" ? claudeSandboxStatus(app.env) : codexStatus(app.env);
728
+ if (st.state !== "off")
729
+ return undefined;
730
+ const shown = await app.state.update("sandboxNotice", (cur) => (cur?.[front] !== undefined ? { result: false } : { next: { ...(cur ?? {}), [front]: Date.now() }, result: true }));
731
+ if (!shown)
732
+ return undefined;
733
+ const agent = front === "claude" ? "Claude Code" : "Codex";
734
+ return `${agent}'s sandbox doesn't keep its commands out of ${tildeForm(p2pHomePaths(app.env).home, userHomeOf(app.env))}, where your identity key and person token live. In your own terminal (not inside ${agent}), run \`p2p sandbox enable\`: it shows what it adds to your ${agent} config and asks first. \`p2p doctor\` shows the details.`;
735
+ }
736
+ /** Both front ends' sandbox status (read-only; whoever asks). */
737
+ export function sandboxReport(env, o = {}) {
738
+ return {
739
+ p2pHome: p2pHomePaths(env).home,
740
+ declined: declinedHere(env),
741
+ claude: { ...claudeSandboxStatus(env, o), present: frontPresent("claude", env) },
742
+ codex: { ...codexStatus(env, o), present: frontPresent("codex", env) },
743
+ };
744
+ }
745
+ /** The fix, said to the person, or to an agent (which never runs it). */
746
+ export function sandboxFix(person) {
747
+ return person
748
+ ? "run `p2p sandbox enable` in your own terminal (not inside Claude Code or Codex): it shows what it adds and asks first"
749
+ : "`p2p sandbox enable`, run by the person in their own terminal (outside Claude Code and Codex): an agent never changes its own sandbox, so ask your user";
750
+ }
751
+ export function sandboxHuman(r, person) {
752
+ const row = (name, s, present, path) => {
753
+ if (!present && s.state !== "on")
754
+ return [`${name}: not set up here (${path})`];
755
+ const mark = s.state === "on" ? "✓" : s.state === "off" ? "✗" : "?";
756
+ return [`${mark} ${name}: ${s.detail}`, ...s.notes.map((n) => ` note: ${n}`)];
757
+ };
758
+ const lines = [`P2P_HOME is ${r.p2pHome}.`, ...row("Claude Code", r.claude, r.claude.present, r.claude.settings), ...row("Codex", r.codex, r.codex.present, r.codex.settings)];
759
+ const off = (r.claude.present && r.claude.state === "off") || (r.codex.present && r.codex.state === "off");
760
+ if (off)
761
+ lines.push("", `Fix: ${sandboxFix(person)}.${r.declined ? " (You said no when `p2p setup` offered it.)" : ""}`);
762
+ return lines.join("\n");
763
+ }