@peer2peer/cli 0.0.0-stage → 0.1.0

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 (105) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +366 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +363 -0
  6. package/dist/app.js +1177 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +611 -0
  12. package/dist/cli.js +1650 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +112 -0
  16. package/dist/config.js +243 -0
  17. package/dist/doctor.d.ts +99 -0
  18. package/dist/doctor.js +817 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +32 -0
  22. package/dist/ext-host.js +259 -0
  23. package/dist/extensions.d.ts +386 -0
  24. package/dist/extensions.js +395 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/identity.d.ts +236 -0
  30. package/dist/identity.js +751 -0
  31. package/dist/inbound.d.ts +32 -0
  32. package/dist/inbound.js +258 -0
  33. package/dist/index.d.ts +8 -0
  34. package/dist/index.js +14 -0
  35. package/dist/join-answers.d.ts +49 -0
  36. package/dist/join-answers.js +149 -0
  37. package/dist/outbox.d.ts +109 -0
  38. package/dist/outbox.js +337 -0
  39. package/dist/pretty.d.ts +100 -0
  40. package/dist/pretty.js +256 -0
  41. package/dist/procstart.d.ts +1 -0
  42. package/dist/procstart.js +66 -0
  43. package/dist/progress.d.ts +30 -0
  44. package/dist/progress.js +78 -0
  45. package/dist/projects.d.ts +240 -0
  46. package/dist/projects.js +699 -0
  47. package/dist/prompt/picker.d.ts +64 -0
  48. package/dist/prompt/picker.js +152 -0
  49. package/dist/prompt/tty.d.ts +29 -0
  50. package/dist/prompt/tty.js +122 -0
  51. package/dist/readonly.d.ts +20 -0
  52. package/dist/readonly.js +50 -0
  53. package/dist/receipts.d.ts +99 -0
  54. package/dist/receipts.js +180 -0
  55. package/dist/relay-client.d.ts +277 -0
  56. package/dist/relay-client.js +873 -0
  57. package/dist/relay-info.d.ts +24 -0
  58. package/dist/relay-info.js +53 -0
  59. package/dist/rotation.d.ts +402 -0
  60. package/dist/rotation.js +2054 -0
  61. package/dist/running.d.ts +5 -0
  62. package/dist/running.js +74 -0
  63. package/dist/sessions.d.ts +340 -0
  64. package/dist/sessions.js +1152 -0
  65. package/dist/shortcode.d.ts +149 -0
  66. package/dist/shortcode.js +465 -0
  67. package/dist/social.d.ts +139 -0
  68. package/dist/social.js +485 -0
  69. package/dist/state.d.ts +483 -0
  70. package/dist/state.js +217 -0
  71. package/dist/stdin.d.ts +17 -0
  72. package/dist/stdin.js +46 -0
  73. package/dist/sync.d.ts +77 -0
  74. package/dist/sync.js +375 -0
  75. package/dist/transient.d.ts +1 -0
  76. package/dist/transient.js +28 -0
  77. package/dist/trust.d.ts +37 -0
  78. package/dist/trust.js +134 -0
  79. package/dist/tty-confirm.d.ts +2 -0
  80. package/dist/tty-confirm.js +53 -0
  81. package/dist/tui/command.d.ts +20 -0
  82. package/dist/tui/command.js +70 -0
  83. package/dist/tui/frame.d.ts +43 -0
  84. package/dist/tui/frame.js +111 -0
  85. package/dist/tui/model.d.ts +215 -0
  86. package/dist/tui/model.js +255 -0
  87. package/dist/tui/sanitize.d.ts +13 -0
  88. package/dist/tui/sanitize.js +151 -0
  89. package/dist/tui/terminal.d.ts +88 -0
  90. package/dist/tui/terminal.js +354 -0
  91. package/dist/tui/tui.d.ts +71 -0
  92. package/dist/tui/tui.js +571 -0
  93. package/dist/tui/view.d.ts +4 -0
  94. package/dist/tui/view.js +356 -0
  95. package/dist/unknown-kinds.d.ts +12 -0
  96. package/dist/unknown-kinds.js +66 -0
  97. package/dist/version.d.ts +1 -0
  98. package/dist/version.js +5 -0
  99. package/dist/want-pow.d.ts +12 -0
  100. package/dist/want-pow.js +46 -0
  101. package/dist/watch.d.ts +35 -0
  102. package/dist/watch.js +325 -0
  103. package/dist/xstate.d.ts +125 -0
  104. package/dist/xstate.js +422 -0
  105. package/package.json +60 -4
@@ -0,0 +1,699 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Project boundaries (docs/concepts.md "Projects", threat model "Project boundaries").
4
+ //
5
+ // - A project is a git repository, keyed by its normalised remote URL (if any) and its git
6
+ // common dir, so every worktree and subfolder of one clone is the same project. Outside git,
7
+ // the real path of the folder.
8
+ // - Its policy lives only in this user's state (`<home>/cli/projects`): shared with circles and
9
+ // named people, or private. A project with no policy is private: only this user's own devices
10
+ // see its sessions. Nothing in a repository can widen that; a committed `.p2p-private` file at
11
+ // the repository's top level can only make it private.
12
+ // - Each session is bound to every project it has worked in (its directories, the files it
13
+ // touched): sticky until the session ends. Its ceiling is the intersection of those projects'
14
+ // policies, the most restrictive, so a session that touched a private project stays private.
15
+ // - The ceiling caps the session's signed roster (sessions.ts getSession), so who sees its status,
16
+ // footprints and summary, and who may message it, follows it everywhere a roster is checked: on
17
+ // this device, on the user's other devices and at every peer, old clients included. Sends from a
18
+ // session (messages, extension kinds, offline copies) are refused to anyone outside it.
19
+ // - `p2p tui` and `p2p send` typed at a terminal with no --from-session are the person's own
20
+ // session: never bound, no ceiling.
21
+ import { agentAncestor, isAgentProcess } from "./ancestry.js";
22
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
23
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
24
+ import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
25
+ import { circlePolicy, liveFriendshipsV3, loadCircle, sanitizePeerText, standsLookup } from "@peer2peer/core/v3";
26
+ import { CliError } from "./errors.js";
27
+ /** The person's own terminal session (`p2p tui`, `p2p send` with no --from-session). */
28
+ export const PERSON_SESSION = "tui";
29
+ /** The committed file a repository may carry to ask for privacy (it can never widen anything). */
30
+ export const PRIVATE_MARKER = ".p2p-private";
31
+ /**
32
+ * The directory a session works in, as the CLI sees it: P2P_WORKDIR when it names an existing
33
+ * absolute directory (the Claude mod and the Codex bridge run p2p from elsewhere and pass the
34
+ * session's folder there), else the process's own.
35
+ */
36
+ export function sessionWorkdir(env) {
37
+ const w = env.P2P_WORKDIR?.trim();
38
+ if (w && isAbsolute(w)) {
39
+ try {
40
+ if (statSync(w).isDirectory())
41
+ return w;
42
+ }
43
+ catch {
44
+ // not there: the process's own
45
+ }
46
+ }
47
+ return process.cwd();
48
+ }
49
+ /**
50
+ * Every folder a session works in, as its front end tells the CLI: its working directory
51
+ * (sessionWorkdir) and P2P_PROJECT_DIRS (path-delimited: folders it moved to, files it touched
52
+ * elsewhere). Anyone may add to these: a binding only ever narrows who the session reaches.
53
+ */
54
+ export function sessionDirs(env) {
55
+ const extra = (env.P2P_PROJECT_DIRS ?? "").split(delimiter).filter((x) => x.trim() !== "" && isAbsolute(x.trim()));
56
+ // Past the cap (or when the front end says it dropped some): private, never "the first N".
57
+ const over = extra.length > MAX_SESSION_DIRS || env.P2P_PROJECT_DIRS_OVER === "1";
58
+ return { dirs: [sessionWorkdir(env), ...extra.slice(0, MAX_SESSION_DIRS)], over };
59
+ }
60
+ /** At most this many folders a front end passes per call; past it the session is private. */
61
+ export const MAX_SESSION_DIRS = 512;
62
+ /** At most this many projects per session; past it the session is private. */
63
+ export const MAX_SESSION_PROJECTS = 16;
64
+ /** Bindings of sessions not seen for this long are dropped. */
65
+ export const SESSION_BINDING_TTL_MS = 30 * 24 * 3600 * 1000;
66
+ /** At most this many circles and people in one project's policy. */
67
+ export const MAX_PROJECT_SHARES = 32;
68
+ /** At most this many constraints a session keeps; past it, private. */
69
+ export const MAX_SESSION_CONSTRAINTS = 16;
70
+ // ---------------------------------------------------------------------------
71
+ // Project identity
72
+ const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex");
73
+ /** The real path, with the case the file system stores (realpathSync.native), else as given. */
74
+ function real(p) {
75
+ try {
76
+ return realpathSync.native(p);
77
+ }
78
+ catch {
79
+ try {
80
+ return realpathSync(p);
81
+ }
82
+ catch {
83
+ return p;
84
+ }
85
+ }
86
+ }
87
+ /** The nearest existing directory at or above `p`, as a real path. */
88
+ function existingDir(p) {
89
+ let cur = resolve(p);
90
+ for (let i = 0; i < 4096; i++) {
91
+ try {
92
+ const st = statSync(cur);
93
+ return real(st.isDirectory() ? cur : dirname(cur));
94
+ }
95
+ catch {
96
+ const up = dirname(cur);
97
+ if (up === cur)
98
+ return cur;
99
+ cur = up;
100
+ }
101
+ }
102
+ return cur;
103
+ }
104
+ /**
105
+ * A remote URL as one canonical string: scheme, credentials, port-less ssh form, trailing `.git`
106
+ * and slashes dropped, host lower-cased. `https://u:t@GitHub.com/a/b.git` and `git@github.com:a/b`
107
+ * are both `github.com/a/b`. A local path stays a path.
108
+ */
109
+ export function normalizeRemote(url) {
110
+ let u = url.trim();
111
+ if (u === "" || u.length > 2048 || /[\0\n\r]/.test(u))
112
+ return undefined;
113
+ let host;
114
+ let path;
115
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\/(.*)$/i.exec(u);
116
+ if (scheme) {
117
+ const rest = scheme[2];
118
+ if (scheme[1].toLowerCase() === "file")
119
+ return u.replace(/^file:\/\//i, "").replace(/\/+$/, "").replace(/\.git$/, "") || undefined;
120
+ const slash = rest.indexOf("/");
121
+ host = slash < 0 ? rest : rest.slice(0, slash);
122
+ path = slash < 0 ? "" : rest.slice(slash + 1);
123
+ host = host.replace(/^.*@/, "").replace(/:\d+$/, "");
124
+ }
125
+ else {
126
+ const scp = /^(?:[^@/:]+@)?([^/:]+):(.*)$/.exec(u);
127
+ if (scp && !/^[A-Za-z]:[\\/]/.test(u)) {
128
+ host = scp[1];
129
+ path = scp[2];
130
+ }
131
+ else {
132
+ u = u.replace(/\\/g, "/").replace(/\/+$/, "").replace(/\.git$/, "");
133
+ return u || undefined;
134
+ }
135
+ }
136
+ path = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").replace(/\/+$/, "");
137
+ host = host.toLowerCase();
138
+ return host ? `${host}/${path}` : undefined;
139
+ }
140
+ /** The remote URLs in a git config file's text: `origin` first, then the others in order. */
141
+ function remotesOf(config) {
142
+ const out = [];
143
+ let section;
144
+ for (const raw of config.split(/\r?\n/)) {
145
+ const line = raw.trim();
146
+ const sec = /^\[\s*remote\s+"([^"]*)"\s*\]$/.exec(line);
147
+ if (sec) {
148
+ section = sec[1];
149
+ continue;
150
+ }
151
+ if (line.startsWith("[")) {
152
+ section = undefined;
153
+ continue;
154
+ }
155
+ const kv = /^url\s*=\s*(.*)$/.exec(line);
156
+ if (section !== undefined && kv)
157
+ out.push({ name: section, url: kv[1].replace(/^"|"$/g, "") });
158
+ }
159
+ out.sort((a, b) => Number(b.name === "origin") - Number(a.name === "origin"));
160
+ return out.map((r) => r.url);
161
+ }
162
+ function readSmall(file) {
163
+ try {
164
+ const st = statSync(file);
165
+ if (!st.isFile() || st.size > 256 * 1024)
166
+ return undefined;
167
+ return readFileSync(file, "utf8");
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ }
173
+ /**
174
+ * The project `dir` belongs to, read from the files alone (git is never run: no hook, fsmonitor
175
+ * or config of the repository's can execute). A `.git` directory or `gitdir:` file up the tree
176
+ * marks a working tree; its common dir (`commondir` for a linked worktree) identifies the clone.
177
+ */
178
+ export function projectOf(dir) {
179
+ const start = existingDir(isAbsolute(dir) ? dir : resolve(dir));
180
+ let cur = start;
181
+ for (let i = 0; i < 4096; i++) {
182
+ const dotgit = join(cur, ".git");
183
+ // Anything named .git here (a folder, a file, a symlink, even a broken or unreadable one) ends
184
+ // the walk: this folder is its own project, never the parent repository's.
185
+ let present;
186
+ try {
187
+ lstatSync(dotgit);
188
+ present = true;
189
+ }
190
+ catch {
191
+ present = false;
192
+ }
193
+ if (present) {
194
+ let st;
195
+ try {
196
+ st = statSync(dotgit);
197
+ }
198
+ catch {
199
+ st = undefined;
200
+ }
201
+ let gitDir;
202
+ if (st?.isDirectory())
203
+ gitDir = dotgit;
204
+ else if (st?.isFile()) {
205
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readSmall(dotgit) ?? "");
206
+ if (m)
207
+ gitDir = resolve(cur, m[1]);
208
+ }
209
+ if (!gitDir || !existsSync(gitDir)) {
210
+ // A .git that can't be read as one: a folder project at this level (private until shared).
211
+ return { id: `pj_${sha(`dir\n${cur}`).slice(0, 24)}`, name: clean(basename(cur)) || "folder", kind: "dir", root: cur };
212
+ }
213
+ {
214
+ let common = gitDir;
215
+ const cd = readSmall(join(gitDir, "commondir"))?.trim();
216
+ if (cd)
217
+ common = resolve(gitDir, cd);
218
+ common = real(common);
219
+ const urls = remotesOf(readSmall(join(common, "config")) ?? "");
220
+ const remote = urls.map(normalizeRemote).find((x) => x !== undefined);
221
+ const main = basename(common) === ".git" ? dirname(common) : common;
222
+ const name = clean(remote ? (remote.split("/").pop() ?? "") : basename(main)) || clean(basename(cur)) || "project";
223
+ return {
224
+ id: `pj_${sha(`git\n${remote ?? ""}\n${common}`).slice(0, 24)}`,
225
+ name,
226
+ kind: "git",
227
+ root: cur,
228
+ ...(remote ? { remote } : {}),
229
+ ...(existsSync(join(cur, PRIVATE_MARKER)) ? { repoPrivate: true } : {}),
230
+ };
231
+ }
232
+ }
233
+ const up = dirname(cur);
234
+ if (up === cur)
235
+ break;
236
+ cur = up;
237
+ }
238
+ return { id: `pj_${sha(`dir\n${start}`).slice(0, 24)}`, name: clean(basename(start)) || "folder", kind: "dir", root: start };
239
+ }
240
+ const clean = (s) => sanitizePeerText(s, 64).replace(/[^\w.@+-]/g, "").slice(0, 64);
241
+ // ---------------------------------------------------------------------------
242
+ // Policies
243
+ export async function projectsDoc(app) {
244
+ const d = (await app.state.get("projects"));
245
+ return d && d.v === 1 && d.projects && typeof d.projects === "object" ? d : { v: 1, projects: {} };
246
+ }
247
+ /** A project's share as stored, or `private` (no policy: private by default). */
248
+ export function shareOf(doc, id) {
249
+ const r = doc.projects[id];
250
+ if (!r || r.share === "private" || typeof r.share !== "object")
251
+ return "private";
252
+ const circles = Array.isArray(r.share.circles) ? r.share.circles.filter((x) => typeof x === "string") : [];
253
+ const people = Array.isArray(r.share.people) ? r.share.people.filter((x) => typeof x === "string") : [];
254
+ return circles.length + people.length > 0 ? { circles, people } : "private";
255
+ }
256
+ export async function projectView(app, ref, doc) {
257
+ const d = doc ?? (await projectsDoc(app));
258
+ const share = shareOf(d, ref.id);
259
+ const circles = [];
260
+ const people = [];
261
+ if (share !== "private") {
262
+ for (const cid of share.circles) {
263
+ const rec = await app.store.getCircle(cid);
264
+ const c = await loadCircle(app.store, cid).catch(() => undefined);
265
+ circles.push({ cid, ...(c ? { name: sanitizePeerText(c.chain.head.name, 64) } : {}), ...(c && circlePolicy(c.chain.head) === "open" ? { open: true } : {}), joined: rec?.joinedByMe === true });
266
+ }
267
+ for (const u of share.people)
268
+ people.push({ userId: u, address: await app.addressOf(u) });
269
+ }
270
+ const policy = share === "private" || ref.repoPrivate ? "private" : "shared";
271
+ const why = ref.repoPrivate ? `the repository asks to stay private (${PRIVATE_MARKER} at its top level)` : !d.projects[ref.id] ? "unmapped" : undefined;
272
+ return {
273
+ id: ref.id,
274
+ name: ref.name,
275
+ kind: ref.kind,
276
+ root: ref.root,
277
+ ...(ref.remote ? { remote: ref.remote } : {}),
278
+ policy,
279
+ circles,
280
+ people,
281
+ ...(why ? { why } : {}),
282
+ ...(ref.repoPrivate ? { repoPrivate: true } : {}),
283
+ };
284
+ }
285
+ /**
286
+ * `p2p project share`: share the project at `dir` with circles you joined and friends. Replaces the
287
+ * project's shares with exactly these (`add` keeps the ones it has). Only ever the person's
288
+ * command: no session or file can run it for them (the mod and the Codex bridge refuse it from a
289
+ * model).
290
+ */
291
+ export async function shareProject(app, dir, targets) {
292
+ const ref = projectOf(dir);
293
+ if (ref.repoPrivate) {
294
+ throw new CliError("repo_private", `${ref.name} asks to stay private: its repository has ${PRIVATE_MARKER} at the top level. Peer2Peer never shares it; remove that file from your copy first if you mean to`);
295
+ }
296
+ const { resolveCircle } = await import("./circle-ops.js");
297
+ const circles = [];
298
+ const warnings = [];
299
+ for (const c of targets.circles ?? []) {
300
+ const r = await resolveCircle(app, c);
301
+ if (!r.record.joinedByMe)
302
+ throw new CliError("usage", `you haven't joined circle ${c}`);
303
+ if (!circles.includes(r.record.cid))
304
+ circles.push(r.record.cid);
305
+ const lc = await loadCircle(app.store, r.record.cid).catch(() => undefined);
306
+ if (lc && circlePolicy(lc.chain.head) === "open")
307
+ warnings.push(`circle ${r.record.cid} is open: anyone its owner admits will see ${ref.name}'s sessions`);
308
+ }
309
+ const people = [];
310
+ if ((targets.people ?? []).length > 0) {
311
+ const friends = await liveFriendshipsV3(app.store, app.signerCtx());
312
+ for (const p of targets.people ?? []) {
313
+ const u = await app.resolveUser(p);
314
+ if (u === app.userId)
315
+ continue;
316
+ if (await app.store.isBlocked(u))
317
+ throw new CliError("blocked", `you blocked ${p}`);
318
+ if (!friends.some((f) => f.inviter === u || f.invitee === u))
319
+ throw new CliError("usage", `${await app.addressOf(u)} isn't your friend: share with a circle they're in, or befriend them first`);
320
+ if (!people.includes(u))
321
+ people.push(u);
322
+ }
323
+ }
324
+ if (circles.length + people.length === 0)
325
+ throw new CliError("usage", "name a circle or a friend to share with (or `p2p project private`)");
326
+ const doc = await app.state.update("projects", (cur) => {
327
+ const d = cur?.v === 1 ? cur : { v: 1, projects: {} };
328
+ const old = shareOf(d, ref.id);
329
+ const keep = targets.add && old !== "private" ? old : { circles: [], people: [] };
330
+ const share = { circles: [...new Set([...keep.circles, ...circles])], people: [...new Set([...keep.people, ...people])] };
331
+ if (share.circles.length + share.people.length > MAX_PROJECT_SHARES)
332
+ throw new CliError("usage", `a project is shared with at most ${MAX_PROJECT_SHARES} circles and people`);
333
+ const next = { ...d, projects: { ...d.projects, [ref.id]: { name: ref.name, root: ref.root, ...(ref.remote ? { remote: ref.remote } : {}), share, at: Date.now() } } };
334
+ return { next: next, result: next };
335
+ });
336
+ return { project: await projectView(app, ref, doc), warnings };
337
+ }
338
+ /** `p2p project private`: only your own devices see the project's sessions (the default). */
339
+ export async function makeProjectPrivate(app, dir) {
340
+ const ref = projectOf(dir);
341
+ const doc = await app.state.update("projects", (cur) => {
342
+ const d = cur?.v === 1 ? cur : { v: 1, projects: {} };
343
+ const next = { ...d, projects: { ...d.projects, [ref.id]: { name: ref.name, root: ref.root, ...(ref.remote ? { remote: ref.remote } : {}), share: "private", at: Date.now() } } };
344
+ return { next: next, result: next };
345
+ });
346
+ return projectView(app, ref, doc);
347
+ }
348
+ /** `p2p project ls`: every project with a policy on this device. */
349
+ export async function listProjects(app) {
350
+ const doc = await projectsDoc(app);
351
+ const out = [];
352
+ for (const [id, r] of Object.entries(doc.projects)) {
353
+ out.push(await projectView(app, { id, name: r.name, kind: r.remote !== undefined || existsSync(join(r.root, ".git")) ? "git" : "dir", root: r.root, ...(r.remote ? { remote: r.remote } : {}) }, doc));
354
+ }
355
+ return out.sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
356
+ }
357
+ /** `p2p project show`: the project at `dir`, its policy and why. */
358
+ export async function showProject(app, dir) {
359
+ return projectView(app, projectOf(dir));
360
+ }
361
+ // ---------------------------------------------------------------------------
362
+ // Sessions
363
+ /**
364
+ * Binds a session to the projects of `dirs` (sticky: a session's projects only ever grow until it
365
+ * ends), plus a constraint an own-device message carried. The person's own session is never
366
+ * bound; another caller naming it is refused. A session an agent names (agentContext) that no
367
+ * front end of this user has registered (personTokenOk) starts private.
368
+ */
369
+ export async function bindSession(app, sid, dirs, o = {}) {
370
+ if (sid === PERSON_SESSION) {
371
+ if (o.person)
372
+ return undefined;
373
+ throw new CliError("usage", `session ${PERSON_SESSION} is your own terminal's (p2p tui, or p2p send typed with no --from-session); an agent sends from its own session`);
374
+ }
375
+ const refs = new Map();
376
+ for (const d of dirs) {
377
+ if (typeof d !== "string" || d.trim() === "")
378
+ continue;
379
+ const r = projectOf(d);
380
+ refs.set(r.id, r);
381
+ }
382
+ // Who may speak for a session (statuses, sends): its front end (the person token), or, for a session
383
+ // no front end registered, a caller outside any agent's session. An agent's own shell never may.
384
+ const front = app.front === true;
385
+ if (!o.inbound && !front && agentContext(app.env)) {
386
+ throw new CliError("refused", `session ${sid}: inside an agent's session only its front end speaks for a session (the Claude mod's SendMessage, the Codex bridge's p2p_send), never the shell`);
387
+ }
388
+ // A session nobody has used yet, without the front end's token: the person confirms it on their own
389
+ // terminal (a status, a send, an extension send or state alike; a detached process can't).
390
+ if (!o.inbound && !front && !(await sessionBinding(app, sid))) {
391
+ if (!(await app.confirmTty(`p2p is about to speak for a new session ${sid}.`))) {
392
+ throw new CliError("refused", `session ${sid} is new: without your front end's token, confirm it with "yes" on your own terminal (read from the terminal itself, never stdin or a flag)`);
393
+ }
394
+ }
395
+ const now = Date.now();
396
+ return app.state.update("sessionProjects", (cur) => {
397
+ const all = { ...(cur ?? {}) };
398
+ for (const [k, v] of Object.entries(all))
399
+ if (!v || typeof v.at !== "number" || now - v.at > SESSION_BINDING_TTL_MS)
400
+ delete all[k];
401
+ const have = all[sid];
402
+ // A session a front end registered is that front end's: nobody else acts on it, not even to narrow it.
403
+ if (!o.inbound && !front && have?.registered) {
404
+ throw new CliError("refused", `session ${sid} belongs to a front end of yours (the Claude mod or the Codex bridge): only it speaks for that session`);
405
+ }
406
+ const projects = { ...(have?.projects ?? {}) };
407
+ let over = have?.over === true || o.over === true;
408
+ for (const r of refs.values()) {
409
+ const prev = projects[r.id];
410
+ if (!prev && Object.keys(projects).length >= MAX_SESSION_PROJECTS) {
411
+ over = true;
412
+ continue;
413
+ }
414
+ // Once a repository asked for privacy, it stays asked for this session.
415
+ projects[r.id] = { name: r.name, ...(r.repoPrivate || prev?.repoPrivate ? { repoPrivate: true } : {}) };
416
+ }
417
+ const constraints = [...(have?.constraints ?? [])];
418
+ if (o.constraint !== undefined && !constraints.some((c) => JSON.stringify(c) === JSON.stringify(o.constraint))) {
419
+ if (constraints.length >= MAX_SESSION_CONSTRAINTS)
420
+ over = true;
421
+ else
422
+ constraints.push(o.constraint);
423
+ }
424
+ const registered = front || have?.registered === true;
425
+ const unregistered = !registered && have?.unregistered === true;
426
+ const next = {
427
+ projects,
428
+ ...(over ? { over: true } : {}),
429
+ ...(constraints.length ? { constraints } : {}),
430
+ ...(unregistered ? { unregistered: true } : {}),
431
+ ...(registered ? { registered: true } : {}),
432
+ at: now,
433
+ };
434
+ return { next: { ...all, [sid]: next }, result: next };
435
+ });
436
+ }
437
+ // ---------------------------------------------------------------------------
438
+ // Who is calling: the person's front end, or an agent
439
+ /**
440
+ * The variables Claude Code and Codex set in the commands their agents run (an allow-list, from
441
+ * their documentation and source: docs/security/threat-model.md "Project boundaries"). Variables a
442
+ * person sets in their own shell (CODEX_HOME, CODEX_API_KEY, CODEX_PROFILE) never count.
443
+ */
444
+ export const AGENT_ENV_VARS = [
445
+ // Claude Code (code.claude.com/docs/en/env-vars): its Bash, PowerShell and Monitor tools, hooks.
446
+ "CLAUDECODE",
447
+ "CLAUDE_CODE_CHILD_SESSION",
448
+ // Codex (openai/codex codex-rs core/src/unified_exec/process_manager.rs, exec_env.rs, sandboxing/mod.rs):
449
+ // every model tool call, the sandbox markers, and the thread (its user `!` shell sets the last two too).
450
+ "CODEX_TOOL_CALL_ID",
451
+ "CODEX_CI",
452
+ "CODEX_SANDBOX",
453
+ "CODEX_SANDBOX_NETWORK_DISABLED",
454
+ "CODEX_THREAD_ID",
455
+ "CODEX_SESSION_ID",
456
+ ];
457
+ /** Whether the environment says this runs inside an agent's tool call. */
458
+ export function agentEnv(env) {
459
+ if (!env)
460
+ return false;
461
+ return AGENT_ENV_VARS.some((k) => (env[k] ?? "") !== "");
462
+ }
463
+ /** Whether this call runs on an agent's behalf: its environment, or a Claude Code or Codex ancestor (ancestry.ts). */
464
+ export function agentContext(env) {
465
+ return agentEnv(env) || agentAncestor();
466
+ }
467
+ export { isAgentProcess };
468
+ /** `<home>/cli/person.key`: a random secret the person's front ends (the Claude mod, the Codex bridge) pass back as P2P_PERSON_TOKEN. */
469
+ export function personTokenFile(home) {
470
+ return join(home, "cli", "person.key");
471
+ }
472
+ const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
473
+ /** The person token, made once (exclusively, 0600, in the CLI's own folder, which the mod's guards keep from the model). */
474
+ export function personToken(home) {
475
+ const f = personTokenFile(home);
476
+ const read = () => {
477
+ try {
478
+ const t = readFileSync(f, "utf8").trim();
479
+ return TOKEN_RE.test(t) ? t : undefined;
480
+ }
481
+ catch {
482
+ return undefined;
483
+ }
484
+ };
485
+ const have = read();
486
+ if (have)
487
+ return have;
488
+ mkdirSync(join(home, "cli"), { recursive: true, mode: 0o700 });
489
+ const t = randomBytes(32).toString("base64url");
490
+ try {
491
+ writeFileSync(f, t, { mode: 0o600, flag: "wx" });
492
+ return t;
493
+ }
494
+ catch {
495
+ // Made meanwhile by another process (or a file in the way): that one, if it is a token.
496
+ const again = read();
497
+ if (again)
498
+ return again;
499
+ throw new CliError("conflict", `${f} isn't a person token: remove it and run the command again`);
500
+ }
501
+ }
502
+ /** Whether P2P_PERSON_TOKEN is this home's person token (read only: a missing file is no match). */
503
+ export function personTokenOk(env, home) {
504
+ const given = env?.P2P_PERSON_TOKEN?.trim();
505
+ if (!given || typeof home !== "string" || home === "")
506
+ return false;
507
+ let t;
508
+ try {
509
+ t = readFileSync(personTokenFile(home), "utf8").trim();
510
+ }
511
+ catch {
512
+ return false;
513
+ }
514
+ const a = Buffer.from(given);
515
+ const b = Buffer.from(t);
516
+ return a.length === b.length && b.length >= 32 && timingSafeEqual(a, b);
517
+ }
518
+ /**
519
+ * Checks the person token once, at the start of a command, and takes it out of the environment
520
+ * (this object and the process's), so no child (git, ix, an extension's tool) ever inherits it.
521
+ */
522
+ export function takePersonToken(env, home) {
523
+ const ok = personTokenOk(env, home);
524
+ delete env.P2P_PERSON_TOKEN;
525
+ delete process.env.P2P_PERSON_TOKEN;
526
+ return ok;
527
+ }
528
+ /**
529
+ * Lets a command that widens who reaches this user (sharing a project, a session, a default
530
+ * circle, invites, joins, trust, friends) run only for the person: their front end's token; or,
531
+ * outside any agent's session, their "yes" typed on the controlling terminal (never stdin, never a
532
+ * flag: a process detached from every terminal can't give it). Reads are never asked.
533
+ */
534
+ export async function assertPersonForWidening(app, what, confirm) {
535
+ if (app.front === true)
536
+ return;
537
+ if (agentContext(app.env)) {
538
+ throw new CliError("refused", `\`p2p ${what}\` changes who reaches you, so only you run it: in your own terminal (not inside Claude Code or Codex), or with /peers in Claude Code. It was refused here because it runs inside an agent's session`);
539
+ }
540
+ if (!(await confirm(`p2p ${what} changes who reaches you.`))) {
541
+ throw new CliError("refused", `\`p2p ${what}\` changes who reaches you: confirm it with "yes" on your own terminal (it is read from the terminal itself, so a script or a process without one can't)`);
542
+ }
543
+ }
544
+ /** Whether a person-only path (session `tui`) may run here: the person's front end, or no agent in sight (then a terminal "yes" too). */
545
+ export function personHere(app) {
546
+ return app.front === true || !agentContext(app.env);
547
+ }
548
+ export async function sessionBinding(app, sid) {
549
+ return (await app.state.get("sessionProjects"))?.[sid];
550
+ }
551
+ /**
552
+ * The most a session may reach: the intersection of every bound project's policy. Unmapped,
553
+ * private and repository-private projects make it private, and so does an empty intersection.
554
+ */
555
+ export async function sessionCeiling(app, sid, binding) {
556
+ if (sid === PERSON_SESSION)
557
+ return { kind: "none" };
558
+ const b = binding === null ? undefined : (binding ?? (await sessionBinding(app, sid)));
559
+ if (!b || (Object.keys(b.projects).length === 0 && !b.constraints?.length && !b.unregistered && !b.over))
560
+ return { kind: "none" };
561
+ if (b.over)
562
+ return { kind: "private", why: `it worked in more than ${MAX_SESSION_PROJECTS} projects (or ${MAX_SESSION_DIRS} folders)` };
563
+ if (b.unregistered)
564
+ return { kind: "private", why: "an agent named it, and no front end of yours has registered it" };
565
+ const doc = await projectsDoc(app);
566
+ let circles;
567
+ let people;
568
+ const shares = [];
569
+ for (const [id, p] of Object.entries(b.projects)) {
570
+ if (p.repoPrivate)
571
+ return { kind: "private", why: `${p.name} asks to stay private (${PRIVATE_MARKER})` };
572
+ const share = shareOf(doc, id);
573
+ if (share === "private")
574
+ return { kind: "private", why: doc.projects[id] ? `${p.name} is private` : `${p.name} isn't shared (projects are private until you share them)` };
575
+ shares.push({ name: p.name, share });
576
+ }
577
+ for (const c of b.constraints ?? []) {
578
+ if (c === "private")
579
+ return { kind: "private", why: "a private session of yours sent it a message" };
580
+ shares.push({ name: "a session of yours that sent it a message", share: c });
581
+ }
582
+ for (const { share } of shares) {
583
+ if (share === "private")
584
+ continue;
585
+ circles = circles ? new Set(share.circles.filter((c) => circles.has(c))) : new Set(share.circles);
586
+ people = people ? new Set(share.people.filter((u) => people.has(u))) : new Set(share.people);
587
+ }
588
+ const joined = [];
589
+ for (const c of circles ?? [])
590
+ if ((await app.store.getCircle(c))?.joinedByMe === true)
591
+ joined.push(c);
592
+ const blocks = new Set((await app.store.listBlocks()).map((x) => x.userId));
593
+ // People only while they are still friends (an unfriend ends a share as it ends everything else).
594
+ const friends = (people?.size ?? 0) > 0 ? await friendIds(app) : new Set();
595
+ const ppl = [...(people ?? [])].filter((u) => !blocks.has(u) && u !== app.userId && friends.has(u));
596
+ if (joined.length + ppl.length === 0) {
597
+ const names = shares.map((x) => x.name);
598
+ return { kind: "private", why: names.length > 1 ? `its projects (${names.join(", ")}) share nobody in common` : `${names[0]} shares nobody you can reach` };
599
+ }
600
+ return { kind: "shared", circles: joined.sort(), people: ppl.sort() };
601
+ }
602
+ /** Everyone a ceiling lets in (besides this user): members of its circles who stand in them, and its people. */
603
+ export async function ceilingAudience(app, c) {
604
+ if (c.kind === "none")
605
+ return undefined;
606
+ const out = new Set();
607
+ if (c.kind === "private")
608
+ return out;
609
+ const stands = await standsLookup(app.store, app.userId);
610
+ for (const cid of c.circles) {
611
+ const lc = await loadCircle(app.store, cid).catch(() => undefined);
612
+ if (!lc || !stands(app.userId, cid))
613
+ continue;
614
+ for (const m of lc.chain.head.members)
615
+ if (m !== app.userId && stands(m, cid))
616
+ out.add(m);
617
+ }
618
+ for (const u of c.people)
619
+ out.add(u);
620
+ const blocks = new Set((await app.store.listBlocks()).map((x) => x.userId));
621
+ for (const u of [...out])
622
+ if (blocks.has(u))
623
+ out.delete(u);
624
+ return out;
625
+ }
626
+ /** How to tell the person to share, for an error a model may read: the person's command, never a flag for the caller. */
627
+ export function shareHint(names) {
628
+ const what = names.length === 1 ? `the project ${names[0]}` : `each of ${names.join(", ")}`;
629
+ return `only the person can widen this, by sharing ${what} themselves: \`p2p project share <circle or friend>\` run in it (or /peers project share in Claude Code)`;
630
+ }
631
+ /**
632
+ * The exfiltration barrier: may session `sid` send to `userId`? Your own devices always; the
633
+ * person's own session always; anyone else only within the session's project ceiling.
634
+ */
635
+ export async function assertMayReach(app, sid, userId, o = {}) {
636
+ if (userId === app.userId || o.person || sid === PERSON_SESSION)
637
+ return;
638
+ const c = await sessionCeiling(app, sid);
639
+ if (c.kind === "none")
640
+ return;
641
+ const aud = await ceilingAudience(app, c);
642
+ if (aud?.has(userId))
643
+ return;
644
+ const b = await sessionBinding(app, sid);
645
+ const names = Object.values(b?.projects ?? {}).map((p) => p.name);
646
+ const who = o.address ?? (await app.addressOf(userId));
647
+ const why = c.kind === "private" ? c.why : `${who} isn't in the circles or people ${names.length > 1 ? "all its projects share" : "its project shares"}`;
648
+ throw new CliError("not_shared", `session ${sid} works in ${names.join(", ") || "a project"}, and Peer2Peer won't carry anything from it to ${who}: ${why}. ${shareHint(names).replace(/^o/, "O")}`, {
649
+ delivered: false,
650
+ project: { names, policy: c.kind },
651
+ });
652
+ }
653
+ /** Friends of this user (live friendships), for the roster's named parts. */
654
+ export async function friendIds(app) {
655
+ const out = new Set();
656
+ for (const f of await liveFriendshipsV3(app.store, app.signerCtx()))
657
+ out.add(f.inviter === app.userId ? f.invitee : f.inviter);
658
+ return out;
659
+ }
660
+ export async function sessionProjectView(app, sid) {
661
+ const b = await sessionBinding(app, sid);
662
+ const c = await sessionCeiling(app, sid, b ?? null);
663
+ const projects = Object.entries(b?.projects ?? {}).map(([id, p]) => ({ id, name: p.name, ...(p.repoPrivate ? { repoPrivate: true } : {}) }));
664
+ if (c.kind === "private")
665
+ return { projects, policy: "private", why: c.why };
666
+ if (c.kind === "shared")
667
+ return { projects, policy: "shared", circles: c.circles, people: c.people };
668
+ return { projects, policy: "none" };
669
+ }
670
+ /**
671
+ * The one-time notice for a user who relied on the default circle: shown once per device, the
672
+ * first time a session of theirs is private only because its project was never shared.
673
+ */
674
+ export async function defaultCircleNotice(app, sid) {
675
+ const def = app.self?.defaultCircle;
676
+ if (!def || (await app.store.getCircle(def))?.joinedByMe !== true)
677
+ return undefined;
678
+ const b = await sessionBinding(app, sid);
679
+ if (!b)
680
+ return undefined;
681
+ const doc = await projectsDoc(app);
682
+ if (doc.noticeAt !== undefined)
683
+ return undefined;
684
+ const unmapped = Object.entries(b.projects).filter(([id, p]) => !doc.projects[id] && !p.repoPrivate);
685
+ if (unmapped.length === 0)
686
+ return undefined;
687
+ const shown = await app.state.update("projects", (cur) => {
688
+ const d = cur?.v === 1 ? cur : { v: 1, projects: {} };
689
+ if (d.noticeAt !== undefined)
690
+ return { result: false };
691
+ return { next: { ...d, noticeAt: Date.now() }, result: true };
692
+ });
693
+ if (!shown)
694
+ return undefined;
695
+ const name = unmapped[0][1].name;
696
+ return `project boundaries: sessions no longer follow your default circle (${def}). Each project is private until you share it, so this session in ${name} is seen only by your own devices. To share ${name} with that circle, run \`p2p project share ${def}\` in it (or /peers project share in Claude Code); \`p2p project ls\` lists what you shared`;
697
+ }
698
+ /** The text of the one-time notice starts so (the mod and the Codex bridge match it). */
699
+ export const PROJECT_NOTICE_PREFIX = "project boundaries:";