@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
package/dist/cli.js ADDED
@@ -0,0 +1,1650 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The `p2p` command line. Every command:
4
+ // --json prints exactly one JSON object on stdout and exits 0, or prints
5
+ // `{error, reason, ...}` and exits 1;
6
+ // default prints readable text (diagnostics on stderr).
7
+ // `watch --jsonl` prints one JSON line per event instead (see watch.ts).
8
+ //
9
+ // Daemon-free: each command opens the stores, does its work and exits.
10
+ import { realpathSync } from "node:fs";
11
+ import { resolve } from "node:path";
12
+ import * as codex from "@peer2peer/codex-bridge";
13
+ import { Command, CommanderError, Option } from "commander";
14
+ import { App } from "./app.js";
15
+ import { readFileConfig, resolveHome, updateFileConfigField } from "./config.js";
16
+ import { receiptsSetting, sendReceipt } from "./receipts.js";
17
+ import * as trustOps from "./trust.js";
18
+ import { CliError, toErrorJson } from "./errors.js";
19
+ import * as fmt from "./format.js";
20
+ import { safeJson, safeTerminal } from "./format.js";
21
+ import * as circles from "./circle-ops.js";
22
+ import { registerExtensionCommands } from "./ext-host.js";
23
+ import { ExtensionRegistry, loadExtensions } from "./extensions.js";
24
+ import * as codes from "./codes.js";
25
+ import * as identity from "./identity.js";
26
+ import { receiving } from "./inbound.js";
27
+ import * as rotation from "./rotation.js";
28
+ import * as sessions from "./sessions.js";
29
+ import * as projects from "./projects.js";
30
+ import { confirmOnTty } from "./tty-confirm.js";
31
+ import * as social from "./social.js";
32
+ import { watch } from "./watch.js";
33
+ import * as doctorOps from "./doctor.js";
34
+ import { tuiCommand } from "./tui/command.js";
35
+ import { TUI_SESSION } from "./tui/tui.js";
36
+ import * as pretty from "./pretty.js";
37
+ import { VERSION } from "./version.js";
38
+ export { VERSION };
39
+ /** How long a command that ran out of time waits for in-flight sends and writes to settle. */
40
+ export const SETTLE_MS = 5000;
41
+ /** The operations the commands call: real modules by default, fakes in parser tests. */
42
+ export const realOps = { ...identity, ...social, ...circles, ...sessions, ...codes, ...rotation, ...projects, watch, doctor: doctorOps.doctor };
43
+ const collect = (v, prev = []) => [...prev, v];
44
+ /**
45
+ * Commands that widen who reaches this user: refused inside an agent's session unless the
46
+ * person's front end passes its token (projects.ts assertPersonForWidening). Reads never are.
47
+ */
48
+ const WIDENING = new Set(["project share", "circle default", "invite", "join", "accept", "trust add", "held approve", "circle invite", "circle join", "circle policy", "unblock", "link start", "link join", "identity follow", "extensions enable"]);
49
+ /** The widening command `cmd` is (its path from the program, with `session roster` only when it adds), or undefined. */
50
+ export function wideningOf(cmd) {
51
+ const path = [];
52
+ for (let c = cmd; c && c.parent; c = c.parent)
53
+ path.unshift(c.name());
54
+ const p = path.join(" ");
55
+ if (WIDENING.has(p))
56
+ return p;
57
+ if (p === "session roster") {
58
+ const o = cmd.opts();
59
+ if ((o.add?.length ?? 0) > 0 || o.circle !== undefined)
60
+ return p;
61
+ }
62
+ return undefined;
63
+ }
64
+ const posInt = (name) => (v) => {
65
+ const n = Number(v);
66
+ if (!Number.isSafeInteger(n) || n < 0)
67
+ throw new CliError("usage", `${name} must be a non-negative integer`);
68
+ return n;
69
+ };
70
+ export function buildProgram(deps) {
71
+ const ops = { ...realOps, ...deps.ops };
72
+ const confirmTty = deps.confirmTty ?? confirmOnTty;
73
+ // review M2: every diagnostic goes through safeTerminal; human stdout too (below); JSON through safeJson.
74
+ // Time spent waiting on the user (prompts, stdin) doesn't count against the command deadline.
75
+ let waitingOnUser = 0;
76
+ const onUser = (f) => async () => {
77
+ const t0 = Date.now();
78
+ try {
79
+ return await f();
80
+ }
81
+ finally {
82
+ waitingOnUser += Date.now() - t0;
83
+ }
84
+ };
85
+ // --no-input: no picker and no question at all (a script's behaviour, on a terminal too).
86
+ const { select: rawSelect, prompt: rawPrompt, promptSecret: rawSecret, ...rest } = deps.io;
87
+ const inIo = deps.noInput ? rest : deps.io;
88
+ const base = { ...rest, out: (s) => deps.io.out(safeTerminal(s)), err: (s) => deps.io.err(safeTerminal(s)) };
89
+ void rawSelect;
90
+ void rawPrompt;
91
+ void rawSecret;
92
+ const io = {
93
+ ...base,
94
+ ...(inIo.prompt ? { prompt: (q) => onUser(() => inIo.prompt(q))() } : {}),
95
+ ...(inIo.promptSecret ? { promptSecret: (q) => onUser(() => inIo.promptSecret(q))() } : {}),
96
+ ...(inIo.select ? { select: (s) => onUser(() => inIo.select(s))() } : {}),
97
+ ...(deps.io.readStdin ? { readStdin: (o) => onUser(() => deps.io.readStdin(o))() } : {}),
98
+ };
99
+ const extensions = deps.extensions ?? new ExtensionRegistry();
100
+ const baseMakeApp = deps.makeApp ?? ((env, i, o) => new App({ env, io: i, ...(o?.readOnly ? { readOnly: true } : {}) }));
101
+ // Every context renders inbound `x:<ns>.*` kinds with the installed extensions (extensions.ts).
102
+ const makeApp = (env, i, o) => {
103
+ const app = baseMakeApp(env, i, o);
104
+ app.extensions ??= extensions;
105
+ app.front = deps.front === true;
106
+ app.confirmTty = confirmTty;
107
+ return app;
108
+ };
109
+ const program = new Command("p2p")
110
+ .description("Peer2Peer: an account-free network for AI agent sessions and the people who run them")
111
+ .version(VERSION)
112
+ .showHelpAfterError()
113
+ .enablePositionalOptions()
114
+ .exitOverride()
115
+ .configureOutput({ writeOut: (s) => io.out(s.replace(/\n$/, "")), writeErr: (s) => io.err(s.replace(/\n$/, "")) });
116
+ /** Runs one command: JSON or human output, exit code 1 on failure. */
117
+ const run = (fn, opts = {}) => async (...args) => {
118
+ const cmd = args[args.length - 1];
119
+ const json = Boolean(cmd.opts().json);
120
+ const app = makeApp(deps.env, io, opts.readOnly ? { readOnly: true } : undefined);
121
+ let stop = () => { };
122
+ try {
123
+ // §2.8 (L4): a follow that died mid-swap finishes before anything reads this home (not for a
124
+ // read-only command, which must leave the home exactly as it found it).
125
+ if (typeof app.home === "string" && !opts.readOnly)
126
+ await rotation.recoverInterruptedFollow(app.home).catch(() => false);
127
+ // An agent can't widen who reaches this user, however it runs p2p (projects.ts).
128
+ const widening = wideningOf(cmd);
129
+ if (widening)
130
+ await projects.assertPersonForWidening(app, widening, confirmTty);
131
+ if (opts.requireIdentity !== false)
132
+ await app.load(true);
133
+ // The person token the person's front ends pass back (projects.ts), made once, in the CLI's own folder.
134
+ if (app.keys && !opts.readOnly && typeof app.home === "string")
135
+ projects.personToken(app.home);
136
+ if (app.keys)
137
+ receiving(app);
138
+ // The whole command is bounded (P2P_COMMAND_TIMEOUT_SEC, default 60 s, plus any --wait),
139
+ // so it can't hang without a word: on expiry it fails naming the step it was on.
140
+ const wait = cmd.opts().wait;
141
+ const base = app.tun?.commandTimeoutSec ?? 0;
142
+ const limitMs = opts.noDeadline || base <= 0 ? 0 : (base + (typeof wait === "number" ? wait : (opts.waitDefault ?? 0))) * 1000;
143
+ const work = fn(app, ...args);
144
+ let out;
145
+ if (limitMs > 0) {
146
+ work.catch(() => { });
147
+ const start = Date.now();
148
+ const user0 = waitingOnUser;
149
+ const expired = await Promise.race([
150
+ work.then((o) => ({ o }), (e) => ({ e })),
151
+ new Promise((resolve) => {
152
+ const t = setInterval(() => {
153
+ if (Date.now() - start - (waitingOnUser - user0) < limitMs)
154
+ return;
155
+ clearInterval(t);
156
+ resolve("expired");
157
+ }, 200);
158
+ t.unref?.();
159
+ stop = () => clearInterval(t);
160
+ }),
161
+ ]);
162
+ if (expired !== "expired") {
163
+ if ("e" in expired)
164
+ throw expired.e;
165
+ out = expired.o;
166
+ }
167
+ else {
168
+ const at = app.progress?.current;
169
+ // review L1: stop the work (no new network step starts), then let what is already on the
170
+ // wire settle, bounded, before closing.
171
+ app.abort?.abort();
172
+ await Promise.race([work.catch(() => undefined), new Promise((r) => setTimeout(r, SETTLE_MS).unref())]);
173
+ const secs = Math.round(limitMs / 1000);
174
+ if (opts.sends) {
175
+ throw new CliError("outcome_unknown", `outcome unknown: it may have been delivered; check before resending (\`p2p ${cmd.name()}\` ran out of time after ${secs}s${at ? ` while ${at}` : ""})`);
176
+ }
177
+ throw new CliError("timeout", `\`p2p ${cmd.name()}\` gave up after ${secs}s${at ? ` while ${at}` : ""}. Check your network and relays; P2P_DEBUG=1 shows each step`);
178
+ }
179
+ }
180
+ else
181
+ out = await work;
182
+ if (json)
183
+ io.out(safeJson(out.json));
184
+ else if (deps.io.pretty && out.pretty)
185
+ deps.io.out(pretty.safePretty(out.pretty(deps.io.pretty)));
186
+ else if (out.human)
187
+ io.out(safeTerminal(out.human));
188
+ }
189
+ catch (e) {
190
+ const j = toErrorJson(e);
191
+ if (json)
192
+ io.out(safeJson(j));
193
+ else
194
+ io.err(`p2p: ${String(j.error)}: ${String(j.reason)}`);
195
+ process.exitCode = j.error === "restore_incomplete" ? 2 : 1;
196
+ }
197
+ finally {
198
+ stop();
199
+ await app.close().catch(() => { });
200
+ }
201
+ };
202
+ const confirmPrompt = async (q, yes, labels = ["Yes", "No"]) => {
203
+ if (yes)
204
+ return true;
205
+ if (io.select) {
206
+ // A picker: the question's last line is asked, the lines before it are shown above.
207
+ const lines = q.split("\n");
208
+ const r = await io.select({ intro: lines.slice(0, -1), message: lines[lines.length - 1] || "Continue?", choices: [{ value: "yes", label: labels[0] }, { value: "no", label: labels[1] }], initial: "no" });
209
+ return r?.[0] === "yes";
210
+ }
211
+ if (!io.prompt)
212
+ return false;
213
+ const a = (await io.prompt(`${q} [y/N] `)).trim().toLowerCase();
214
+ return a === "y" || a === "yes";
215
+ };
216
+ /** The command whose options `o` are (commander passes the same object it keeps). */
217
+ const cmdOf = (o) => ({ opts: () => o });
218
+ // ── pickers (prompt/): only with io.select, never with --json or --yes ──
219
+ const canAsk = (cmd) => Boolean(io.select) && !cmd.opts().json && !cmd.opts().yes;
220
+ const ask = async (spec) => {
221
+ const r = await io.select(spec);
222
+ if (r === undefined)
223
+ throw new CliError("cancelled", "cancelled: nothing was done");
224
+ return r;
225
+ };
226
+ const pickOne = async (message, choices, empty) => {
227
+ if (choices.length === 0)
228
+ throw new CliError("usage", empty);
229
+ return (await ask({ message, choices }))[0];
230
+ };
231
+ /**
232
+ * A command whose positional arguments may be picked: without a picker (a script, a pipe, --json,
233
+ * --no-input, CI), a missing one is the same commander error, help and exit code as before.
234
+ */
235
+ const pickable = (names, action) => async (...args) => {
236
+ const cmd = args[args.length - 1];
237
+ if (!canAsk(cmd)) {
238
+ names.forEach((n, i) => {
239
+ if (args[i] === undefined)
240
+ cmd.error(`error: missing required argument '${n}'`, { code: "commander.missingArgument" });
241
+ });
242
+ }
243
+ return action(...args);
244
+ };
245
+ const friendChoices = async (app) => (await ops.friends(app)).friends.map((f) => ({ value: f.userId, label: f.address, detail: f.canMessage ? "connected" : "waiting for their cap" }));
246
+ const circleChoices = async (app, which) => (await ops.listCircles(app)).filter(which).map((c) => ({ value: c.cid, label: c.name, detail: `${fmt.plural(c.members, "member")} · ${c.policy} · ${c.role}${c.isDefault ? " · default" : ""}` }));
247
+ const heldChoices = async (app) => (await ops.listHeld(app)).map((h) => ({ value: h.id, label: `${h.address}: ${h.summary}`, detail: h.type }));
248
+ // ── identity ──────────────────────────────────────────────────────────────
249
+ program
250
+ .command("init")
251
+ .description("Create your identity key and first device, and publish your identity document")
252
+ .option("--name <name>", "Your display name ([a-z0-9._-], not unique)")
253
+ .option("--relay <url>", "A relay to use (repeat for up to 5); default: P2P_DEFAULT_RELAYS or config.json", collect)
254
+ .option("-y, --yes", "Don't prompt about the backup (scripts); still prints a warning")
255
+ .option("--json", "JSON output")
256
+ .action(run(async (app, o) => {
257
+ if (!o.yes && !io.prompt)
258
+ throw new CliError("usage", "init asks about a backup: run it in a terminal, or pass --yes in scripts");
259
+ const r = await ops.init(app, { name: o.name, relays: o.relay });
260
+ const lines = [
261
+ `Created ${r.address}`,
262
+ ` userId ${r.userId}`,
263
+ ` device ${r.did} (key holder)`,
264
+ ` ${r.published.length > 0 ? `published to ${fmt.plural(r.published.length, "relay")}: ${r.published.join(", ")}` : "not published yet: no relay answered (it will be retried)"}`,
265
+ ];
266
+ const warn = "Only this device holds your identity key. If you lose it without a backup, the identity is gone for good (§2.5).";
267
+ let backup;
268
+ if (o.yes) {
269
+ io.err(`warning: ${warn} Run \`p2p backup show\` or link a second key holder.`);
270
+ }
271
+ else {
272
+ io.out(lines.join("\n"));
273
+ lines.length = 0;
274
+ io.out(`\n${warn}\n [b] show a 24-word backup phrase now (recommended)\n [l] I'll link a second key-holding device (p2p link start --keyholder)\n [s] skip for now`);
275
+ const a = (await io.prompt("Choose b, l or s: ")).trim().toLowerCase();
276
+ if (a === "b" || a === "") {
277
+ backup = (await ops.backupShow(app)).phrase;
278
+ io.out(`\nWrite these 24 words down and keep them offline. Anyone with them is you:\n\n${backup}\n`);
279
+ }
280
+ else if (a === "l")
281
+ io.out("Run `p2p link start --keyholder` on this device when the other one is ready.");
282
+ else
283
+ io.err(`warning: ${warn}`);
284
+ }
285
+ return { json: { ...r, backupShown: backup !== undefined }, human: lines.join("\n") };
286
+ }, { requireIdentity: false }));
287
+ program
288
+ .command("setup")
289
+ .description("Get started: create your identity with sensible defaults (safe to run again)")
290
+ .option("--name <name>", "Your display name (default: your OS user name)")
291
+ .option("--relay <url>", "A relay to use (repeat for up to 5); default: P2P_DEFAULT_RELAYS, config.json, or the relays shipped with the CLI", collect)
292
+ .option("--backup-file [path]", "Save the 24-word backup phrase to a 0600 file (default <home>/backup-phrase.txt)")
293
+ .option("--print-backup", "Print the backup phrase (in --json, as backup.phrase)")
294
+ .option("--no-backup", "Don't save or print the backup phrase now")
295
+ .option("--json", "JSON output")
296
+ .action(run(async (app, o) => {
297
+ let mode = o.backupFile !== undefined ? "file" : o.printBackup ? "print" : o.backup === false ? "none" : undefined;
298
+ const existed = await app.load(false);
299
+ if (mode === undefined && !existed && !o.json && io.prompt) {
300
+ io.out("Your identity key will live only on this device. A 24-word backup phrase restores it if the device is lost.\n [f] save it to a file only you can read (0600), on this device: copy it off later\n [p] print it now, for a password manager or paper (best)\n [s] skip for now (p2p backup show later)");
301
+ const a = (await io.prompt("Choose f, p or s: ")).trim().toLowerCase();
302
+ mode = a === "p" ? "print" : a === "s" ? "none" : "file";
303
+ }
304
+ const r = await ops.setup(app, { name: o.name, relays: o.relay, backup: mode, ...(typeof o.backupFile === "string" ? { backupFile: o.backupFile } : {}) });
305
+ const lines = [r.created ? `Created ${r.address}` : `Already set up: ${r.address}`, ` relays ${r.relays.join(", ")}`];
306
+ if (r.backup?.file) {
307
+ lines.push(` backup saved to ${r.backup.file}`);
308
+ // review L4: the default file sits next to the key it backs up.
309
+ io.err(`warning: the backup file is on this same device, so it doesn't protect you if the device is lost. Put the 24 words in a password manager (or on paper), then delete ${r.backup.file}.`);
310
+ }
311
+ if (r.backup?.phrase)
312
+ lines.push(`\nWrite these 24 words down and keep them offline. Anyone with them is you:\n\n${r.backup.phrase}\n`);
313
+ if (r.created && !r.backup)
314
+ io.err("warning: no backup yet: if you lose this device, the identity is gone. Run `p2p backup show`.");
315
+ lines.push("", "Invite someone: p2p invite <their name> Join with a code: p2p join <code>");
316
+ return { json: r, human: lines.join("\n") };
317
+ },
318
+ // review L1: never cut short half-way through creating an identity (each step is still bounded).
319
+ { requireIdentity: false, noDeadline: true }));
320
+ program
321
+ .command("whoami")
322
+ .description("Your address, fingerprint, devices, relays and document expiry")
323
+ .option("--json", "JSON output")
324
+ .action(run(async (app) => {
325
+ const r = await ops.whoami(app);
326
+ return { json: r, human: fmt.formatWhoami(r) };
327
+ }));
328
+ const backup = program.command("backup").description("The 24-word backup phrase of your identity key (§2.7)");
329
+ backup
330
+ .command("show")
331
+ .description("Show the backup phrase (key-holding devices only)")
332
+ .option("--json", "JSON output")
333
+ .action(run(async (app) => {
334
+ const r = await ops.backupShow(app);
335
+ return { json: r, human: `Keep these 24 words offline. Anyone who has them can act as you:\n\n${r.phrase}` };
336
+ }));
337
+ backup
338
+ .command("restore")
339
+ .description("Restore your identity on this (fresh) device from the backup phrase")
340
+ .option("--relay <url>", "A relay your identity uses (repeatable)", collect)
341
+ .option("--name <name>", "Change your display name")
342
+ .option("--keep-devices", "Keep your other devices listed (default: revoke them, as lost)")
343
+ .option("--new-chain", "When the relays hold no document for this identity, start a new history at version 1")
344
+ .option("--json", "JSON output")
345
+ .action(run(async (app, o) => {
346
+ // review L4: never on the command line (argv is visible to other local users and shell history).
347
+ let phrase;
348
+ if (io.promptSecret)
349
+ phrase = await io.promptSecret("Backup phrase (24 words, not shown): ");
350
+ else if (io.prompt)
351
+ throw new CliError("usage", "this terminal can't hide input: pipe the phrase on stdin instead");
352
+ else if (io.readStdin)
353
+ phrase = await io.readStdin();
354
+ if (!phrase?.trim())
355
+ throw new CliError("usage", "type the phrase when asked, or pipe it on stdin");
356
+ const r = await ops.backupRestore(app, phrase, { relays: o.relay, name: o.name, keepDevices: o.keepDevices, newChain: o.newChain });
357
+ // R4-M2: committed locally, but some listed relay refused: a distinct error (exit 2), with the full result.
358
+ if ((r.failed ?? []).length > 0) {
359
+ throw new CliError("restore_incomplete", `restored locally, but ${r.failed.length} relay(s) didn't take the new document: run \`p2p identity republish\``, { ...r });
360
+ }
361
+ return {
362
+ json: r,
363
+ human: `Restored ${r.address} on this device (${r.did}), document version ${r.ver}.${r.revoked.length ? `\nRevoked ${fmt.plural(r.revoked.length, "old device")}.` : ""}\nFriendships aren't in the phrase: invite your friends again.`,
364
+ };
365
+ },
366
+ // review L1: a restore is never cut short by the command deadline (each step is still bounded).
367
+ { requireIdentity: false, noDeadline: true }));
368
+ const relays = program
369
+ .command("relays")
370
+ .description("The relays your identity document lists; `relays add|remove <url>` publishes the next version")
371
+ .option("--json", "JSON output")
372
+ .action(run(async (app) => {
373
+ const r = await ops.relaysList(app);
374
+ // On a terminal: each relay's health too (a bounded connect; piped output stays the plain list).
375
+ if (io.pretty)
376
+ await app.connect({ allowNone: true }).catch(() => undefined);
377
+ return { json: r, human: r.relays.join("\n"), pretty: (p) => pretty.prettyRelays(r, app.relayStatus, p) };
378
+ }));
379
+ for (const verb of ["add", "remove"]) {
380
+ relays
381
+ .command(`${verb} <url>`)
382
+ .description(verb === "add" ? "Add a relay (1-5 in all)" : "Remove a relay (one must stay)")
383
+ .option("--json", "JSON output")
384
+ .action(run(async (app, url) => {
385
+ const r = verb === "add" ? await ops.relaysAdd(app, url) : await ops.relaysRemove(app, url);
386
+ const failed = r.failed.length ? `; not yet on ${r.failed.map((f) => f.relay).join(", ")} (retried later)` : "";
387
+ return { json: r, human: `Your relays (document version ${r.ver}): ${r.relays.join(", ")}${failed}.` };
388
+ }));
389
+ }
390
+ const ident = program.command("identity").description("Your identity document");
391
+ ident
392
+ .command("republish")
393
+ .description("Publish your current identity document again to every relay it lists (after a restore, or a relay that was down)")
394
+ .option("--json", "JSON output")
395
+ .action(run(async (app) => {
396
+ const r = await app.republish();
397
+ if (r.failed.length > 0)
398
+ throw new CliError("not_published", `${r.failed.length} relay(s) still refused: ${r.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")}`, { ...r });
399
+ return { json: r, human: `Version ${r.ver} is on ${fmt.plural(r.ok.length, "relay")}: ${r.ok.join(", ")}.` };
400
+ }));
401
+ ident
402
+ .command("rotate")
403
+ .description("Move to a new identity key: the remedy for a lost or stolen key-holding device (§2.8)")
404
+ .option("--plan", "Make the new key and show the plan (its fingerprint, which devices would follow); publish nothing")
405
+ .option("--resume", "Accept a plan made with --plan, or finish a rotation that was interrupted")
406
+ .option("--cancel", "Drop a plan that wasn't accepted (nothing was published)")
407
+ .option("--exclude <did>", "A device that must NOT follow (the lost or stolen one): revoked first; repeatable", collect)
408
+ .option("--keep <did>", "Let a device the plan dropped by default follow anyway (added by a version you didn't publish, or not seen lately); repeatable", collect)
409
+ .option("--invite <user>", "Invite a friend the plan leaves out by default (a friendship made by a device it drops, or one that doesn't verify now); repeatable", collect)
410
+ .option("--keep-keyholders", "Devices that held the old identity key also get the new one (default: they follow as ordinary devices)")
411
+ .option("--wait <seconds>", "How long to wait for your other devices to follow (default 600, the link code's life)", posInt("--wait"))
412
+ .option("--backup-file [path]", "Save the new key's 24-word backup phrase to a 0600 file (default <home>/backup-phrase-<fingerprint>.txt)")
413
+ .option("--contest", "On a key holder: answer a rotation of your identity this device didn't publish with a competing one, so your friends see a conflict and apply neither")
414
+ .option("--resend", "After a rotation: send the new identity's invite again to the friends it didn't reach (throttled)")
415
+ .option("-y, --yes", "Accept the plan without asking (scripts)")
416
+ .option("--json", "JSON output")
417
+ .addHelpText("after", [
418
+ "",
419
+ "What happens: a new identity key and device keys for this device; the plan (the new fingerprint, the devices",
420
+ "that would follow: drop a lost one with --exclude, it is revoked first) for you to accept; a statement signed",
421
+ "by the old and the new key; the new identity is published on your relays; each other device gets a held",
422
+ "rotation it follows only when you say so there (`p2p identity follow <id>`; an offline one re-links later with",
423
+ "`p2p link join <code> --rotated`); every friend gets a fresh invite they approve as \"<you> moved to a new key\";",
424
+ "circles you own are handed to the new key and circles you are in get your new identity's join; proofs are",
425
+ "re-signed (update the gist or DNS record it prints). Last, once the new key has a backup (--backup-file) or a",
426
+ "key-holding device followed (--keep-keyholders), the old identity publishes a final version with no devices:",
427
+ "relays then refuse its devices.",
428
+ "",
429
+ "Security: someone who also has your old identity key can publish a competing rotation. Your devices alert;",
430
+ "a key holder contests it (--contest). Your friends then see a conflict and nothing is applied: they check with",
431
+ "you out of band (petnames, proofs) and exchange a fresh invite. Friends act only on a rotation the old",
432
+ "identity's own final version carries. Rotation can't recover circles whose owner key was compromised:",
433
+ "re-create those (§3.3).",
434
+ ].join("\n"))
435
+ .action(run(async (app, o) => {
436
+ const backupFile = o.backupFile === undefined ? undefined : typeof o.backupFile === "string" ? o.backupFile : true;
437
+ const backup = backupFile === true ? { backupFileDefault: true } : backupFile ? { backupFile } : {};
438
+ if (o.cancel) {
439
+ const r = await ops.rotateCancel(app);
440
+ return { json: r, human: r.cancelled ? "Dropped the rotation plan: nothing was published." : "No rotation plan to drop." };
441
+ }
442
+ if (o.resend) {
443
+ const r = await ops.rotateResend(app);
444
+ return {
445
+ json: r,
446
+ human: `Sent your new identity's invite to ${fmt.plural(r.sent, "friend")}${r.failed.length ? `; ${r.failed.length} still not reached` : ""}${r.throttled ? ` (${r.remaining} wait for the relays' hourly limit: run it again later)` : ""}.`,
447
+ };
448
+ }
449
+ const opts = { resume: o.resume, exclude: o.exclude, keep: o.keep, invite: o.invite, keepKeyholders: o.keepKeyholders, contest: o.contest, ...backup };
450
+ if (o.plan) {
451
+ const plan = await ops.rotatePlan(app, opts);
452
+ return { json: { plan: true, ...plan }, human: `${fmt.formatRotationPlan(plan)}\nAccept it with \`p2p identity rotate --resume\` (add --exclude <did> to drop a device), or drop it with --cancel.` };
453
+ }
454
+ const r = await ops.rotate(app, {
455
+ ...opts,
456
+ waitSec: o.wait,
457
+ yes: o.yes,
458
+ ...(io.prompt
459
+ ? {
460
+ confirm: async (plan) => {
461
+ // Never on stdout with --json: that carries exactly one JSON object.
462
+ (o.json ? io.err : io.out)(fmt.formatRotationPlan(plan));
463
+ return confirmPrompt("Rotate your identity to this new key?");
464
+ },
465
+ }
466
+ : {}),
467
+ });
468
+ return { json: r, human: fmt.formatRotation(r) };
469
+ }, { requireIdentity: false }));
470
+ ident
471
+ .command("dispute <id>")
472
+ .description("Settle a contested move to a new key (§2.8): keep the identity that is really them, or neither")
473
+ .option("--keep <user>", "The new identity you confirmed out of band")
474
+ .option("--neither", "Keep neither (both stay suspended)")
475
+ .option("--json", "JSON output")
476
+ .action(run(async (app, id, o) => {
477
+ if (!!o.keep === !!o.neither)
478
+ throw new CliError("usage", "give exactly one of --keep <user> or --neither");
479
+ const r = await ops.resolveDispute(app, id, { keep: o.keep, neither: o.neither });
480
+ return { json: r, human: r.keep ? `Kept ${await app.addressOf(String(r.keep))}; the other${r.rejected.length === 1 ? "" : "s"} stay suspended.` : "Kept neither: all of them stay suspended." };
481
+ }));
482
+ ident
483
+ .command("follow <id>")
484
+ .description("On this (not key-holding) device: follow a rotation of your identity that one of your key holders started (§2.8)")
485
+ .option("--json", "JSON output")
486
+ .action(run(async (app, id) => {
487
+ const r = await ops.followHeld(app, id);
488
+ return { json: r, human: `This device moved with your identity: it is now ${r.address} (${r.did}).` };
489
+ }));
490
+ const link = program.command("link").description("Link another device to your identity (§2.4)");
491
+ link
492
+ .command("start")
493
+ .description("On a key-holding device: show a one-time link code for the new device")
494
+ .option("--keyholder", "Make the new device key-holding (it gets your identity key)")
495
+ .option("--relay <url>", "Relay for the link mailbox (default: your first relay)")
496
+ .option("--expect-compare <code>", "Proceed only if the answering device's compare code is this (for scripts; read it off the new device)")
497
+ .option("--json", "JSON output")
498
+ .action(run(async (app, o) => {
499
+ // review N-M1: never accept whichever device answers first. Without a terminal to ask, the
500
+ // expected compare code must be given.
501
+ const expect = o.expectCompare?.trim().toLowerCase();
502
+ if (expect === undefined && !io.prompt)
503
+ throw new CliError("usage", "link start confirms the compare code: run it in a terminal, or pass --expect-compare <code>");
504
+ const s = await ops.linkStart(app, { keyholder: o.keyholder, relay: o.relay });
505
+ if (o.json)
506
+ io.err(JSON.stringify({ event: "code", code: s.code, relay: s.relay, expiresAt: s.expiresAt }));
507
+ else {
508
+ io.out(`On the new device run:\n\n p2p link join ${s.code}\n`);
509
+ const code = fmt.qr(s.code);
510
+ if (code)
511
+ io.out(code);
512
+ io.out("Show this only on a screen you control: never paste it into a chat or a screen share. It works once, for 10 minutes.\nWaiting for the new device…");
513
+ }
514
+ let shown = "";
515
+ const r = await s.wait(async (req) => {
516
+ shown = req.compareCode;
517
+ if (o.json)
518
+ io.err(JSON.stringify({ event: "answered", label: req.label, compareCode: req.compareCode, did: req.did }));
519
+ else
520
+ io.out(`\nA device "${req.label}" answered. Its compare code: ${req.compareCode}`);
521
+ if (expect !== undefined)
522
+ return req.compareCode.toLowerCase() === expect;
523
+ return confirmPrompt(`Does the new device show ${req.compareCode}?`);
524
+ });
525
+ return { json: { ...r, compareCode: shown }, human: `Linked ${r.did}${r.label ? ` (${r.label})` : ""}${r.keyholder ? " as a key holder" : ""}; your document is now version ${r.ver}.` };
526
+ }, { noDeadline: true }));
527
+ link
528
+ .command("join <code>")
529
+ .description("On the new device: join with the code the other device shows")
530
+ .option("--label <label>", "A name for this device")
531
+ .option("--rotated", "This device's identity was rotated while it was offline: re-link it to the new identity (§2.8)")
532
+ .option("--json", "JSON output")
533
+ .action(run(async (app, code, o) => {
534
+ const j = o.rotated ? await ops.relinkRotated(app, code, { label: o.label }) : await ops.linkJoin(app, code, { label: o.label });
535
+ if (o.json)
536
+ io.err(JSON.stringify({ compareCode: j.compareCode, did: j.did }));
537
+ else
538
+ io.out(`Compare code: ${j.compareCode}\nCheck the other device shows the same code, and confirm there. Waiting…`);
539
+ const r = await j.wait();
540
+ return { json: r, human: `This device is now ${r.address} (${r.did})${r.keyholder ? ", a key holder" : ""}.` };
541
+ },
542
+ // Linking waits up to 10 minutes for the other device, by design.
543
+ { requireIdentity: false, noDeadline: true }));
544
+ const devices = program
545
+ .command("devices")
546
+ .description("Your devices; `devices revoke <did>` removes one")
547
+ .option("--json", "JSON output")
548
+ .action(run(async (app) => {
549
+ const r = await ops.devices(app);
550
+ return { json: { devices: r }, human: fmt.formatDevices(r) };
551
+ }));
552
+ devices
553
+ .command("revoke <did>")
554
+ .description("Revoke a device: publish the next document version without it")
555
+ .option("--json", "JSON output")
556
+ .action(run(async (app, did) => {
557
+ const r = await ops.revokeDevice(app, did);
558
+ return { json: r, human: `Revoked ${r.revoked} (document version ${r.ver}). Re-issued ${fmt.plural(r.capsReissued, "cap")}${r.rejoined.length ? `, re-signed ${fmt.plural(r.rejoined.length, "circle membership")}` : ""}.` };
559
+ }));
560
+ const profile = program.command("profile").description("Your public profile (bio, avatar, links)");
561
+ profile
562
+ .command("set")
563
+ .description("Set profile fields (an empty value clears one)")
564
+ .option("--bio <text>", "At most 280 characters")
565
+ .option("--avatar <url|file>", "An https URL, or a PNG/JPEG/WebP/GIF file of at most 4 KiB as a data: URI")
566
+ .option("--link <url>", "An https link (repeat for up to 5; replaces the list)", collect)
567
+ .option("--clear", "Start from an empty profile")
568
+ .option("--json", "JSON output")
569
+ .action(run(async (app, o) => {
570
+ const r = await ops.profileSet(app, { bio: o.bio, avatar: o.avatar, links: o.link, clear: o.clear });
571
+ return { json: r, human: `Profile updated (document version ${r.ver}).` };
572
+ }));
573
+ profile
574
+ .command("show [user]")
575
+ .description("Show a profile (yours by default)")
576
+ .option("--json", "JSON output")
577
+ .action(run(async (app, user) => {
578
+ const r = await ops.profileShow(app, user);
579
+ const p = r.profile;
580
+ const lines = [r.address, ...(p.bio ? [` ${p.bio}`] : []), ...p.links.map((l) => ` ${l}`)];
581
+ if (p.avatar)
582
+ lines.push(p.avatar.kind === "inline" ? " avatar: inline image" : ` avatar: ${p.avatar.url} (not fetched)`);
583
+ return { json: r, human: lines.join("\n") };
584
+ }));
585
+ const proof = program.command("proof").description("Proofs that you also control a GitHub account or a domain (§2.6)");
586
+ proof
587
+ .command("add <kind> <claim>")
588
+ .description("kind github <handle> [--gist <id>], or dns <domain>: prints what to publish")
589
+ .option("--gist <id>", "The id of the public gist that will hold the proof")
590
+ .option("--json", "JSON output")
591
+ .action(run(async (app, kind, claim, o) => {
592
+ const r = await ops.proofAdd(app, kind, claim, { gist: o.gist });
593
+ return { json: r, human: r.pending ? r.publish : `Added ${kind}: ${r.claim} to your identity document (version ${r.ver}).\n${r.publish}` };
594
+ }));
595
+ proof
596
+ .command("verify <user>")
597
+ .description("Check a user's proofs against GitHub and DNS")
598
+ .option("--json", "JSON output")
599
+ .action(run(async (app, user) => {
600
+ await app.connect({ allowNone: true });
601
+ const r = await ops.proofVerify(app, user);
602
+ const lines = [r.address, ...(r.proofs.length ? r.proofs.map((p) => (p.verified ? ` ${p.display}` : ` ✗ ${p.kind}: ${p.claim} (${p.error})`)) : [" no proofs"])];
603
+ return { json: r, human: lines.join("\n") };
604
+ }));
605
+ // ── friends ───────────────────────────────────────────────────────────────
606
+ program
607
+ .command("invite [label]")
608
+ .description("Make a one-time invite code (and its https link): they open the link or run `p2p join <code>`, and are your friend (and in the code's circles) at once")
609
+ .option("--circle <cid>", "A circle the code joins; repeat for up to 5 (default: your default circle, when you own or administer it)", collect)
610
+ .option("--no-circle", "A friend invite only")
611
+ .option("--to <user>", "Only this user may redeem it")
612
+ .option("--ttl-days <n>", "Days the code lives (1-7, default 7)", posInt("--ttl-days"))
613
+ .option("--relay <url>", "The relay holding the code (default: your first relay that takes it)")
614
+ .option("--web", "Print only the code's web link (https://ix-infra.com/p2p/invite#…)")
615
+ .option("--link", "Make the long friend-only invite link instead (`p2p accept <link>`)")
616
+ .option("--uses <n>", "With --link: first-contact envelopes the link's cap admits per relay", posInt("--uses"))
617
+ .option("--json", "JSON output")
618
+ .action(run(async (app, label, o) => {
619
+ if (o.link) {
620
+ await app.connect({ allowNone: true });
621
+ const r = await ops.invite(app, { to: o.to, uses: o.uses, ttlDays: o.ttlDays });
622
+ return {
623
+ json: r,
624
+ human: `Send this link to ${r.invite.aud === "*" ? "the person you're inviting" : await app.addressOf(r.invite.aud)} over a channel you trust:\n\n${r.link}\n\nor, for a browser: ${r.web}\n\nThey run: p2p accept <link>${r.delivered ? `\n(also ${fmt.formatDelivery(r.delivered)})` : ""}`,
625
+ };
626
+ }
627
+ if (o.uses !== undefined)
628
+ throw new CliError("usage", "--uses goes with --link (a code works once)");
629
+ if (o.link && o.web)
630
+ throw new CliError("usage", "--web is the code's link; --link is the long friend-only one: pick one");
631
+ let chosen;
632
+ let noCircle = o.circle === false;
633
+ let ttlDays = o.ttlDays;
634
+ if (o.circle === undefined && canAsk(cmdOf(o))) {
635
+ // No --circle: pick the circles (yours or ones you administer; open ones can't take a code).
636
+ await app.connectAndDrain().catch(() => undefined);
637
+ const list = (await ops.listCircles(app)).filter((c) => c.joined && (c.role === "owner" || c.role === "admin"));
638
+ const choices = [
639
+ { value: "", label: "Friend only (no circle)", exclusive: true },
640
+ ...list.map((c) => ({
641
+ value: c.cid,
642
+ label: c.name,
643
+ detail: `${fmt.plural(c.members, "member")} · ${c.policy}${c.isDefault ? " · default" : ""}`,
644
+ ...(c.policy === "open" ? { disabled: "open: share its own link (p2p circle invite <cid> --link)" } : c.role === "owner" && !app.isKeyholder ? { disabled: "this device doesn't hold your identity key" } : {}),
645
+ ...(c.isDefault ? { checked: true } : {}),
646
+ })),
647
+ ];
648
+ if (!choices.some((c) => c.checked))
649
+ choices[0].checked = true;
650
+ const picked = await ask({ message: `What should the invite${label ? ` for ${label}` : ""} join?`, choices, multi: true, max: 5 });
651
+ chosen = picked.filter((v) => v !== "");
652
+ noCircle = chosen.length === 0;
653
+ if (ttlDays === undefined) {
654
+ ttlDays = Number((await ask({ message: "How long should it work?", choices: [{ value: "7", label: "7 days" }, { value: "3", label: "3 days" }, { value: "1", label: "1 day" }], initial: "7" }))[0]);
655
+ }
656
+ }
657
+ const r = await ops.inviteCode(app, {
658
+ label,
659
+ ...(Array.isArray(o.circle) ? { circles: o.circle } : chosen?.length ? { circles: chosen } : {}),
660
+ noCircle,
661
+ to: o.to,
662
+ ttlDays,
663
+ relay: o.relay,
664
+ });
665
+ if (o.web)
666
+ return { json: r, human: r.web };
667
+ const days = Math.max(1, Math.round((r.expiresAt - Date.now() / 1000) / 86_400));
668
+ const circles = r.circles.map((c) => `"${c.name}"`);
669
+ return {
670
+ json: r,
671
+ pretty: (p) => pretty.prettyInvite(r, p),
672
+ human: [
673
+ `Your invite${r.label ? ` for ${r.label}` : ""} (works once, for ${fmt.plural(days, "day")}${r.to ? `, only for ${r.to.address}` : ""}):`,
674
+ "",
675
+ ` ${r.web}`,
676
+ "",
677
+ `or the code: ${r.code} (${ops.joinCommandFor(r.web, r.privateRelay)})`,
678
+ "",
679
+ "Send them this message (it says how to install Peer2Peer if they don't have it):",
680
+ "",
681
+ ...r.message.split("\n").map((l) => ` ${l}`),
682
+ "",
683
+ `${circles.length ? `It makes them your friend and joins them to ${circles.join(", ")}. ` : "It makes them your friend. "}They see who it's from and what it joins, and say yes, before anything happens. Anyone who sees it before them can use it: you'll be told who joined, \`p2p remove <user>\` undoes it, and \`p2p invites revoke <code>\` cancels it before then.`,
684
+ ].join("\n"),
685
+ };
686
+ }));
687
+ program
688
+ .command("join <code>")
689
+ .description("Redeem an invite code or its link (https://ix-infra.com/p2p/invite#…): shows who made it and the circles it joins, and on your yes makes you friends and joins them (creates your identity if there is none)")
690
+ .option("--wait <seconds>", "How long to wait for the circles (default 15)", posInt("--wait"))
691
+ .option("--preview", "Only show who made the code and what it joins; accept nothing (the code is then used up for anyone else)")
692
+ .option("--confirmed", "You saw what the code offers (--preview) and want it: don't ask again")
693
+ .option("-y, --yes", "For scripts: join without being asked, and join a circle even when no second member could confirm it (§3.3)")
694
+ .option("--name <name>", "Your display name, if this creates your identity")
695
+ .option("--allow-private-relay", "Accept a code whose relay is a loopback, link-local or private address (your own relay on your network; also P2P_ALLOW_PRIVATE_RELAY=1)")
696
+ .option("--json", "JSON output")
697
+ .action(run(async (app, code, o) => {
698
+ if (o.preview) {
699
+ const p = await ops.previewCode(app, code, { allowPrivateRelay: o.allowPrivateRelay });
700
+ return { json: { preview: p }, human: `${ops.previewText(p)}\nTo join: p2p join --confirmed ${ops.shownCode(code)}` };
701
+ }
702
+ // An identity already here: what the relays deliver while the join waits (the inviter's adds of
703
+ // us to the code's circles) is handled at once, so the join finishes now, not on the next command.
704
+ if (app.keys || (await app.load(false)))
705
+ receiving(app);
706
+ const r = await ops.joinCode(app, code, {
707
+ waitSec: o.wait,
708
+ yes: o.yes,
709
+ consent: o.confirmed,
710
+ allowPrivateRelay: o.allowPrivateRelay,
711
+ name: o.name,
712
+ confirm: o.json || (!io.prompt && !io.select) ? undefined : (q) => confirmPrompt(q, false, ["Join", "Cancel"]),
713
+ create: async (a, x) => {
714
+ const c = await ops.init(a, x);
715
+ receiving(a);
716
+ io.err(`Created your identity ${c.address}. Only this device holds its key: save a backup with \`p2p backup show\`.`);
717
+ return { userId: c.userId, address: c.address, relays: c.relays };
718
+ },
719
+ });
720
+ const lines = [`You and ${r.friend.address} are friends${r.delivered && r.delivered.relays.length === 0 ? " (they'll know once the accept is delivered: run this again later)" : ""}.`];
721
+ for (const c of r.circles) {
722
+ if (c.status === "joined" || c.status === "already")
723
+ lines.push(`${c.status === "joined" ? "Joined" : "Already in"} "${c.name}"${c.default ? "; it is your default circle (new sessions start in it; running ones stay as they are)" : ""}.`);
724
+ else if (c.status === "pending")
725
+ lines.push(`${r.friend.address} adds you to "${c.name}" when their client next runs; your next p2p command finishes the join.`);
726
+ else if (c.status === "held")
727
+ lines.push(`Not joined "${c.name}" from this code (${c.reason}): if its invite comes, \`p2p held\` lists it for you to approve on its own.`);
728
+ else
729
+ lines.push(`"${c.name}" couldn't be confirmed with a second member (§3.3): \`p2p held approve ${c.held}\` to join anyway.`);
730
+ }
731
+ return { json: r, human: lines.join("\n") };
732
+ }, { requireIdentity: false, waitDefault: 15 }));
733
+ const invites = program
734
+ .command("invites")
735
+ .description("Your invite codes and what became of them; `invites revoke <code>` cancels one")
736
+ .option("--json", "JSON output")
737
+ .action(run(async (app) => {
738
+ const r = await ops.listCodes(app);
739
+ return { json: { invites: r }, human: fmt.formatCodes(r), pretty: (p) => pretty.prettyCodes(r, p) };
740
+ }));
741
+ invites
742
+ .command("revoke [code]")
743
+ .description("Cancel a code (the full code, or its first 4+ characters)")
744
+ .option("--json", "JSON output")
745
+ .action(pickable(["code"], run(async (app, picked) => {
746
+ const code = picked ??
747
+ (await pickOne("Which invite should be cancelled?", (await ops.listCodes(app)).filter((c) => c.status === "open" || c.status === "taken").map((c) => ({ value: c.code, label: c.code, detail: [c.label, c.circles.map((x) => x.name).join(", ") || "friend only"].filter(Boolean).join(" · ") })), "no open invite to cancel"));
748
+ const r = await ops.revokeCode(app, code);
749
+ return { json: r, human: r.revoked ? `Revoked ${r.code}${r.wasOpen ? "" : " (someone had already taken it: their join will be refused)"}.` : `${r.code} was already redeemed; use p2p remove.` };
750
+ })));
751
+ program
752
+ .command("remove [user]")
753
+ .description("Undo a code redemption: unfriend them and take them out of the circles your codes added them to")
754
+ .option("--json", "JSON output")
755
+ .action(pickable(["user"], run(async (app, picked) => {
756
+ const u = picked ?? (await pickOne("Who should be removed (unfriended, and out of the circles your codes added them to)?", await friendChoices(app), "no friends to remove"));
757
+ const r = await ops.removeUser(app, u);
758
+ const cs = r.circles.filter((c) => c.result === "removed" || c.result === "proposed");
759
+ return { json: r, human: `Removed ${r.address}${r.unfriended ? " (unfriended)" : ""}${cs.length ? `; out of ${fmt.plural(cs.length, "circle")}` : ""}.` };
760
+ })));
761
+ program
762
+ .command("accept <link>")
763
+ .description("Accept an invite link")
764
+ .option("--allow-private-relay", "Accept a link whose relays are on loopback, link-local or private addresses (also P2P_ALLOW_PRIVATE_RELAY=1)")
765
+ .option("--json", "JSON output")
766
+ .action(run(async (app, l, o) => {
767
+ await ops.guardInviteLink(app, l, { allowPrivateRelay: o.allowPrivateRelay });
768
+ const r = await ops.accept(app, l);
769
+ return { json: r, human: `You and ${r.friend.address} are friends (accept ${fmt.formatDelivery(r.delivered)}).` };
770
+ }));
771
+ program
772
+ .command("friends")
773
+ .description("Your friends, open invites and blocks")
774
+ .option("--json", "JSON output")
775
+ .action(run(async (app) => {
776
+ await app.connectAndDrain().catch((e) => io.err(`p2p: offline: ${e.message}`));
777
+ const r = await ops.friends(app);
778
+ return { json: r, human: fmt.formatFriends(r), pretty: (p) => pretty.prettyFriends(r, p) };
779
+ }));
780
+ program
781
+ .command("unfriend [user]")
782
+ .description("End a friendship (circle standing is unaffected, §3.2)")
783
+ .option("--json", "JSON output")
784
+ .action(pickable(["user"], run(async (app, picked) => {
785
+ const u = picked ?? (await pickOne("Unfriend whom?", await friendChoices(app), "no friends yet"));
786
+ const r = await ops.unfriend(app, u);
787
+ return { json: r, human: `Unfriended ${r.address}; revoked ${fmt.plural(r.revoked, "cap")}.` };
788
+ })));
789
+ program
790
+ .command("block [user]")
791
+ .description("Reject everything from a user, under every rule, and revoke their caps")
792
+ .option("--json", "JSON output")
793
+ .action(pickable(["user"], run(async (app, picked) => {
794
+ const u = picked ?? (await pickOne("Block whom?", await friendChoices(app), "no friends to pick from: name the user"));
795
+ const r = await ops.block(app, u);
796
+ return { json: r, human: `Blocked ${r.address}; revoked ${fmt.plural(r.revoked, "cap")}.` };
797
+ })));
798
+ program
799
+ .command("unblock [user]")
800
+ .description("Remove a block")
801
+ .option("--json", "JSON output")
802
+ .action(pickable(["user"], run(async (app, picked) => {
803
+ const u = picked ??
804
+ (await pickOne("Unblock whom?", (await ops.friends(app)).blocked.map((b) => ({ value: b.userId, label: b.address })), "nobody is blocked"));
805
+ const r = await ops.unblock(app, u);
806
+ return { json: r, human: `Unblocked ${r.address}.` };
807
+ })));
808
+ program
809
+ .command("petname <user> [name]")
810
+ .description("Your own name for a user, shown instead of theirs (always with the fingerprint)")
811
+ .option("--clear", "Remove the petname")
812
+ .option("--json", "JSON output")
813
+ .action(run(async (app, u, name, o) => {
814
+ if (!name && !o.clear)
815
+ throw new CliError("usage", "give a name, or --clear");
816
+ const r = await ops.petname(app, u, o.clear ? undefined : name);
817
+ return { json: r, human: r.petname ? `${r.userId} is now shown as ${r.address}.` : `Cleared the petname: ${r.address}.` };
818
+ }));
819
+ // ── held ──────────────────────────────────────────────────────────────────
820
+ const trust = program
821
+ .command("trust")
822
+ .description("Who may message a session that approves its own tool calls without the hold (the Claude mod reads this)");
823
+ trust
824
+ .command("ls")
825
+ .description("Trusted users and circles, and everyone trusted right now")
826
+ .option("--json", "JSON output")
827
+ .action(run(async (app) => {
828
+ const r = await trustOps.trustList(app);
829
+ const lines = [
830
+ ...r.users.map((u) => `${u.address} (${u.userId})${u.blocked ? " [blocked: not trusted]" : ""}`),
831
+ ...r.circles.map((c) => `circle ${c.cid}${c.name ? ` "${c.name}"` : ""}: ${!c.joined ? "not joined: nobody" : c.open ? "open now (anyone who asks gets in): nobody" : `${c.members.length} members`}`),
832
+ ];
833
+ return { json: r, human: lines.length === 0 ? "Nobody is trusted." : lines.join("\n"), pretty: (p) => pretty.prettyTrust(r, p) };
834
+ }));
835
+ for (const verb of ["add", "remove"]) {
836
+ trust
837
+ .command(`${verb} [target]`)
838
+ .description(verb === "add" ? "Trust a user (full userId or name@fingerprint) or circle:<cid|name>" : "Stop trusting a user or circle:<cid|name>")
839
+ .option("--json", "JSON output")
840
+ .action(pickable(["target"], run(async (app, picked) => {
841
+ let target = picked;
842
+ if (target === undefined && verb === "add") {
843
+ const friendsList = (await ops.friends(app)).friends;
844
+ const cs = await circleChoices(app, (c) => c.joined);
845
+ target = await pickOne("Trust whom? (their messages reach a session that approves its own tool calls, without the hold)",
846
+ // Names (or petnames) only: the fingerprint is what the person types below, from what they got
847
+ // out of band, not something read off this list.
848
+ [
849
+ ...friendsList.map((f) => ({ value: f.userId, label: f.address.slice(0, Math.max(0, f.address.lastIndexOf("@"))) || f.address, detail: `friend since ${fmt.formatDate(f.since)}` })),
850
+ ...cs.map((c) => ({ ...c, value: `circle:${c.value}`, label: `circle ${c.label}` })),
851
+ ], "no friends or circles to trust yet");
852
+ if (!target.startsWith("circle:")) {
853
+ // Kept from the typed form: trusting someone takes their fingerprint, typed, not a pick alone.
854
+ const f = friendsList.find((x) => x.userId === target);
855
+ const fp = f.address.slice(f.address.lastIndexOf("@") + 1);
856
+ if (!io.prompt)
857
+ throw new CliError("usage", "trust add needs their fingerprint typed: run `p2p trust add <name@fingerprint>`");
858
+ const typed = (await io.prompt(`Type ${f.address.slice(0, f.address.lastIndexOf("@"))}'s fingerprint, as they gave it to you (xxxx-xxxx-xxxx-xxxx): `)).trim().toLowerCase().replace(/[\s-]/g, "");
859
+ if (typed !== fp.toLowerCase().replace(/-/g, ""))
860
+ throw new CliError("usage", "that fingerprint doesn't match: nobody was trusted");
861
+ }
862
+ }
863
+ else if (target === undefined) {
864
+ const r = await trustOps.trustList(app);
865
+ target = await pickOne("Stop trusting whom?", [...r.users.map((u) => ({ value: u.userId, label: u.address })), ...r.circles.map((c) => ({ value: `circle:${c.cid}`, label: `circle ${c.name ?? c.cid}` }))], "nobody is trusted");
866
+ }
867
+ if (verb === "add") {
868
+ const r = await trustOps.trustAdd(app, target);
869
+ return { json: r, human: r.kind === "circle" ? `Trusted circle ${r.added}: its members, while they are in it.` : `Trusted ${r.address} (${r.added}).` };
870
+ }
871
+ const r = await trustOps.trustRemove(app, target);
872
+ return { json: r, human: r.removed ? `No longer trusted: ${r.removed}.` : "That wasn't trusted." };
873
+ })));
874
+ }
875
+ trust
876
+ .command("check <userId>")
877
+ .description("Whether a user is trusted right now (judged from the verified circle state)")
878
+ .option("--json", "JSON output")
879
+ .action(run(async (app, userId) => {
880
+ const r = await trustOps.trustCheck(app, userId);
881
+ return { json: r, human: r.trusted ? `Trusted (${r.via}).` : "Not trusted." };
882
+ }));
883
+ const held = program
884
+ .command("held")
885
+ .description("First contacts and circle invites waiting for you")
886
+ .option("--json", "JSON output")
887
+ .action(run(async (app) => {
888
+ await app.connectAndDrain().catch((e) => io.err(`p2p: offline: ${e.message}`));
889
+ const r = await ops.listHeld(app);
890
+ return {
891
+ json: { held: r },
892
+ pretty: (p) => pretty.prettyHeld(r, p),
893
+ human: r.length === 0 ? "Nothing held." : r.map((h) => `${h.id} ${h.summary} from ${h.address}`).join("\n") + "\n\n`p2p held approve <id>` or `p2p held decline <id>`",
894
+ };
895
+ }));
896
+ held
897
+ .command("approve [id]")
898
+ .description("Act on a held item (accept the invite, join the circle, admit the joiner)")
899
+ .option("--wait <seconds>", "Joining: how long to wait for confirmation answers", posInt("--wait"))
900
+ .option("-y, --yes", "Joining: join even without a second confirmation")
901
+ .option("--json", "JSON output")
902
+ .action(pickable(["id"], run(async (app, picked, o) => {
903
+ await (picked === undefined ? app.connectAndDrain().catch(() => undefined) : undefined);
904
+ const id = picked ?? (await pickOne("Approve which?", await heldChoices(app), "nothing is held"));
905
+ const h = await ops.getHeld(app, id);
906
+ if (h.type === "rotation-dispute") {
907
+ throw new CliError("usage", `choose who is really them: \`p2p identity dispute ${h.id} --keep <userId>\` or \`--neither\``);
908
+ }
909
+ if (h.type === "rotation-follow") {
910
+ const r = await ops.followHeld(app, h);
911
+ return { json: { type: h.type, ...r }, human: `This device moved with your identity: it is now ${r.address} (${r.did}).` };
912
+ }
913
+ if (h.type === "rotation") {
914
+ const r = await ops.approveRotation(app, h);
915
+ return { json: r, human: `You and ${String(r.friend.address)} (formerly ${await app.addressOf(String(r.from))}) are friends again under the new key; the old friendship ended.` };
916
+ }
917
+ if (h.type === "rotation-join") {
918
+ const r = await ops.approveRotationJoin(app, h);
919
+ return { json: r, human: `${await app.addressOf(String(r.member))} took ${await app.addressOf(String(r.old))}'s place in ${String(r.cid)} (circle version ${String(r.ver)}).` };
920
+ }
921
+ if (h.type === "invite") {
922
+ const r = await ops.accept(app, h.invite);
923
+ return { json: { type: h.type, ...r }, human: `You and ${r.friend.address} are friends.` };
924
+ }
925
+ if (h.type === "circle-join") {
926
+ const r = await ops.approveJoinRequest(app, h);
927
+ await ops.dropHeld(app, (x) => x.id === h.id);
928
+ return { json: { type: h.type, ...r }, human: `Admitted ${await app.addressOf(r.added)} (circle version ${r.ver}).` };
929
+ }
930
+ const r = await ops.joinFromHeld(app, h, { waitSec: o.wait ?? 20, yes: o.yes, confirm: (q) => confirmPrompt(q) });
931
+ return { json: { type: h.type, ...r }, human: fmt.formatJoin(r) };
932
+ }, { waitDefault: 20 })));
933
+ held
934
+ .command("decline [id]")
935
+ .description("Drop a held item")
936
+ .option("--json", "JSON output")
937
+ .action(pickable(["id"], run(async (app, picked) => {
938
+ await (picked === undefined ? app.connectAndDrain().catch(() => undefined) : undefined);
939
+ const id = picked ?? (await pickOne("Decline which?", await heldChoices(app), "nothing is held"));
940
+ const h = await ops.getHeld(app, id);
941
+ if (h.type === "rotation-dispute") {
942
+ // Declining a contest keeps neither identity (both stay suspended).
943
+ const r = await ops.resolveDispute(app, h.id, { neither: true });
944
+ return { json: { declined: h.id, count: 1, ...r }, human: `Kept neither: both new keys stay suspended.` };
945
+ }
946
+ const gone = await ops.dropHeld(app, (x) => x.id === h.id);
947
+ return { json: { declined: h.id, count: gone.length }, human: `Declined ${h.id}.` };
948
+ })));
949
+ // ── circles ───────────────────────────────────────────────────────────────
950
+ const circle = program.command("circle").description("Circles: groups whose members see each other's sessions (§3.3)");
951
+ circle
952
+ .command("create <name>")
953
+ .description("Found a circle (you are its owner)")
954
+ .option("--open", "Anyone with the link can join (policy open)")
955
+ .option("--json", "JSON output")
956
+ .action(run(async (app, name, o) => {
957
+ const r = await ops.createCircleCmd(app, name, { open: o.open });
958
+ return { json: r, human: `Created "${r.name}" (${r.cid}), policy ${r.policy}.${r.link ? `\nAnyone with this link can join:\n\n${r.link}` : `\nInvite people: p2p circle invite ${r.cid} <user> (or --link)`}` };
959
+ }));
960
+ circle
961
+ .command("invite [cid] [user]")
962
+ .description("Invite a user (owner or admin), or print a link with --link")
963
+ .option("--link", "Print a circle link instead")
964
+ .option("--json", "JSON output")
965
+ .action(pickable(["cid"], run(async (app, pickedCid, pickedUser, o) => {
966
+ const cid = pickedCid ?? (await pickOne("Invite to which circle?", await circleChoices(app, (c) => c.joined && (c.role === "owner" || c.role === "admin")), "you own or administer no circle: p2p circle create <name>"));
967
+ let user = pickedUser;
968
+ if (!user && !o.link && canAsk(cmdOf(o))) {
969
+ const who = await pickOne("Invite whom?", [{ value: "", label: "Make a link instead (anyone with it can ask to join)" }, ...(await friendChoices(app))], "");
970
+ if (who === "")
971
+ o.link = true;
972
+ else
973
+ user = who;
974
+ }
975
+ if (o.link || !user) {
976
+ if (!o.link)
977
+ throw new CliError("usage", "name a user, or pass --link");
978
+ const r = await ops.circleLink(app, cid);
979
+ return { json: r, human: `${r.policy === "open" ? "Anyone with this link can join" : "This link lets people ask to join (you approve them)"}:\n\n${r.link}\n\nor, for a browser: ${r.web}` };
980
+ }
981
+ const r = await ops.inviteToCircle(app, cid, user);
982
+ return { json: r, human: `Invited ${r.address} to ${r.cid}${r.added ? " (added to the members)" : ""}; ${fmt.formatDelivery(r.delivered)}.` };
983
+ })));
984
+ circle
985
+ .command("join <link>")
986
+ .description("Join a circle from a link (confirms the circle with its owner first)")
987
+ .option("--wait <seconds>", "How long to wait for answers (default 20)", posInt("--wait"))
988
+ .option("-y, --yes", "Join even without a second confirmation")
989
+ .option("--allow-private-relay", "Accept a link whose relays are on loopback, link-local or private addresses (also P2P_ALLOW_PRIVATE_RELAY=1)")
990
+ .option("--json", "JSON output")
991
+ .action(run(async (app, l, o) => {
992
+ const r = await ops.joinFromLink(app, l, { waitSec: o.wait ?? 20, yes: o.yes, confirm: (q) => confirmPrompt(q), allowPrivateRelay: o.allowPrivateRelay });
993
+ if (r.status === "unconfirmed" || r.status === "waiting")
994
+ process.exitCode = r.status === "waiting" ? 0 : 1;
995
+ return { json: r, human: fmt.formatJoin(r) };
996
+ }, { waitDefault: 20 }));
997
+ circle
998
+ .command("leave [cid]")
999
+ .description("Leave a circle (every member is told)")
1000
+ .option("--json", "JSON output")
1001
+ .action(pickable(["cid"], run(async (app, picked) => {
1002
+ const cid = picked ?? (await pickOne("Leave which circle? (every member is told)", await circleChoices(app, (c) => c.joined && c.role !== "owner"), "you're in no circle you could leave"));
1003
+ const r = await ops.leaveCircle(app, cid);
1004
+ return { json: r, human: `Left ${r.cid}; told ${fmt.plural(r.told, "member")}.` };
1005
+ })));
1006
+ circle
1007
+ .command("ls")
1008
+ .description("Your circles")
1009
+ .option("--json", "JSON output")
1010
+ .action(run(async (app) => {
1011
+ await app.connectAndDrain().catch((e) => io.err(`p2p: offline: ${e.message}`));
1012
+ const r = await ops.listCircles(app);
1013
+ return { json: { circles: r }, human: fmt.formatCircles(r), pretty: (p) => pretty.prettyCircles(r, p) };
1014
+ }));
1015
+ circle
1016
+ .command("members [cid]")
1017
+ .description("A circle's members and who stands in it")
1018
+ .option("--json", "JSON output")
1019
+ .action(pickable(["cid"], run(async (app, picked) => {
1020
+ await app.connectAndDrain().catch((e) => io.err(`p2p: offline: ${e.message}`));
1021
+ const cid = picked ?? (await pickOne("Which circle?", await circleChoices(app, (c) => c.joined), "you're in no circle"));
1022
+ const r = await ops.circleMembers(app, cid);
1023
+ return { json: r, human: fmt.formatMembers(r) };
1024
+ })));
1025
+ circle
1026
+ .command("propose <cid> <op> <arg>")
1027
+ .description("add|remove|promote|demote <user>, or rename <name> (the owner applies it at once)")
1028
+ .option("--json", "JSON output")
1029
+ .action(run(async (app, cid, op, arg) => {
1030
+ const r = await ops.propose(app, cid, op, arg);
1031
+ return { json: r, human: r.applied ? `Applied: ${op} (circle version ${r.ver}).` : r.sentTo ? `Proposed ${op} to the owner, ${await app.addressOf(r.sentTo)}.` : "Nothing to change." };
1032
+ }));
1033
+ circle
1034
+ .command("transfer <cid> [user]")
1035
+ .description("Hand the circle to a member (they consent first with --accept)")
1036
+ .option("--accept", "As the new owner: consent to take over")
1037
+ .option("--consent <jws>", "A consent you received another way")
1038
+ .option("--json", "JSON output")
1039
+ .action(run(async (app, cid, user, o) => {
1040
+ const r = await ops.transfer(app, cid, user, o);
1041
+ return { json: r, human: o.accept ? `Sent your consent to the owner. They finish with: p2p circle transfer ${cid} <you>` : `Handed ${cid} to ${String(r.address)} (version ${String(r.ver)}).` };
1042
+ }));
1043
+ circle
1044
+ .command("hold <cid> [state]")
1045
+ .description("on|off: hold admins' proposals and rotated members for your approval (`p2p held`), as the owner")
1046
+ .option("--json", "JSON output")
1047
+ .action(run(async (app, cid, state) => {
1048
+ if (state !== undefined && state !== "on" && state !== "off")
1049
+ throw new CliError("usage", "state is on or off");
1050
+ const r = await ops.setCircleHold(app, cid, state === undefined ? undefined : state === "on");
1051
+ return { json: r, human: `${r.cid}: changes ${r.hold ? "wait for your approval" : "apply by themselves"}.` };
1052
+ }));
1053
+ circle
1054
+ .command("policy <cid> <policy>")
1055
+ .description("invite (you approve joins) or open (anyone with the link joins)")
1056
+ .option("--json", "JSON output")
1057
+ .action(run(async (app, cid, policy) => {
1058
+ const r = await ops.setPolicy(app, cid, policy);
1059
+ return { json: r, human: `${r.cid} is now ${r.policy} (version ${r.ver}).` };
1060
+ }));
1061
+ circle
1062
+ .command("default [cid]")
1063
+ .description("Your default circle: what invites join, and what `p2p project share` with no circle shares a project with (sessions follow their project, never this); --none for none")
1064
+ .option("--none", "No default circle")
1065
+ .option("--json", "JSON output")
1066
+ .action(run(async (app, picked, o) => {
1067
+ let cid = picked;
1068
+ if (!cid && !o.none && canAsk(cmdOf(o))) {
1069
+ const v = await pickOne("Which circle is your default (for invites, and for `p2p project share` with no circle)?", [...(await circleChoices(app, (c) => c.joined)).map((c) => ({ ...c, ...(c.detail?.includes("open") ? { detail: `${c.detail} · anyone its owner admits sees them` } : {}) })), { value: "", label: "None" }], "");
1070
+ if (v === "")
1071
+ o.none = true;
1072
+ else
1073
+ cid = v;
1074
+ }
1075
+ if (!cid && !o.none)
1076
+ throw new CliError("usage", "name a circle, or --none");
1077
+ const r = await ops.setDefaultCircle(app, o.none ? undefined : cid);
1078
+ return {
1079
+ json: r,
1080
+ human: r.defaultCircle
1081
+ ? `Default circle: ${r.defaultCircle} (invites join it; \`p2p project share\` with no circle shares a project with it). Sessions follow their project: \`p2p project share\` in a repository shares its sessions.`
1082
+ : "No default circle. Sessions follow their project: `p2p project share` in a repository shares its sessions.",
1083
+ };
1084
+ }));
1085
+ // ── sessions ──────────────────────────────────────────────────────────────
1086
+ program
1087
+ .command("ls")
1088
+ .description("Live sessions of your friends, circle-mates and other devices")
1089
+ .option("--all", "Include sessions that aren't live")
1090
+ .option("--json", "JSON output")
1091
+ .action(run(async (app, o) => {
1092
+ await app.connectAndDrain().catch((e) => io.err(`p2p: offline: ${e.message}`));
1093
+ const r = await ops.listPeers(app, { all: o.all });
1094
+ const relays = app.relayStatus ?? { listed: app.relays, connected: [], failed: app.relays.map((u) => ({ url: u, reason: "not connected" })) };
1095
+ return { json: { peers: r, relays }, human: fmt.formatPeers(r) + (relays.failed.length ? `\n\n! unreachable: ${relays.failed.map((f) => f.url).join(", ")}` : ""), pretty: (p) => pretty.prettyPeers(r, relays, p) };
1096
+ }));
1097
+ program
1098
+ .command("send [text...]")
1099
+ .description("Send a message to a peer session (text from args or stdin)")
1100
+ .option("--from-session <sid>", "Your session id (on a terminal: default tui, as `p2p tui` sends)")
1101
+ .option("--to <address>", "name@fingerprint, userId or petname, optionally \"[ref]\" or /sid (on a terminal: picked from a list)")
1102
+ .option("--notify-when-idle", "Tell this session when the target next goes idle")
1103
+ .option("--stdin", "Read the text from stdin (also: a single `-` as the text)")
1104
+ .option("--project-dir <dir>", "Another folder the session works in (repeatable): binds it to that project too, which only ever narrows who it may reach", collect)
1105
+ .option("--project-dirs-over", "The front end dropped folders past its cap: the session is private")
1106
+ .option("--json", "JSON output")
1107
+ .action(async (text, o, cmd) => {
1108
+ // Without a picker these stay required, with commander's own error (as before they were requiredOption).
1109
+ if (!canAsk(cmd)) {
1110
+ if (o.fromSession === undefined)
1111
+ cmd.error("error: required option '--from-session <sid>' not specified", { code: "commander.missingMandatoryOptionValue" });
1112
+ if (o.to === undefined)
1113
+ cmd.error("error: required option '--to <address>' not specified", { code: "commander.missingMandatoryOptionValue" });
1114
+ }
1115
+ return sendAction(text, o, cmd);
1116
+ });
1117
+ const sendAction = run(async (app, text, o) => {
1118
+ if (o.to === undefined) {
1119
+ await app.connectAndDrain().catch(() => undefined);
1120
+ const peers = await ops.listPeers(app, { all: true });
1121
+ const targets = [];
1122
+ for (const p of peers.filter((x) => !x.self))
1123
+ targets.push({ value: `${p.own} [${p.ref}]`, label: `${p.address} [${p.ref}] ${p.label}`, detail: [p.live ? p.state : "offline", p.summary].filter(Boolean).join(" · ") });
1124
+ for (const f of (await ops.friends(app)).friends)
1125
+ targets.push({ value: f.userId, label: `${f.address} (any session)` });
1126
+ o.to = await pickOne("Send to whom?", targets, "nobody to send to yet: p2p invite");
1127
+ }
1128
+ // On a terminal with no --from-session: sent as `p2p tui` sends, and said so.
1129
+ const fromTui = o.fromSession === undefined;
1130
+ if (fromTui)
1131
+ o.fromSession = TUI_SESSION;
1132
+ // The person's own session (projects.ts): only from a terminal. Named by a script or an agent, it is refused.
1133
+ // And never from inside an agent's session (its environment, or a Claude Code or Codex ancestor),
1134
+ // even under a pseudo-terminal: only the person's own terminal, or their front end's token.
1135
+ const personOk = projects.personHere(app);
1136
+ if (fromTui && !personOk)
1137
+ throw new CliError("refused", "`p2p send` with no --from-session sends as you, from your own terminal; inside an agent's session, send from that session (--from-session)");
1138
+ const person = o.fromSession === TUI_SESSION && canAsk(cmdOf(o)) && personOk;
1139
+ // Without the front end's token, the person confirms on their own terminal: a send as them, or the
1140
+ // first send from a session nobody has used yet (a process detached from every terminal can't).
1141
+ // (A first send from a new session is confirmed where every new session is: projects.ts bindSession.)
1142
+ if (!app.front && (person || fromTui)) {
1143
+ if (!(await confirmTty(`p2p send from session ${o.fromSession} to ${o.to}.`))) {
1144
+ throw new CliError("refused", "this send needs your \"yes\" on your own terminal (read from the terminal itself, never stdin or a flag)");
1145
+ }
1146
+ }
1147
+ if (text.length === 0 && !o.stdin && !o.notifyWhenIdle && io.prompt) {
1148
+ text = [(await io.prompt("Message: ")).trim()];
1149
+ if (text[0] === "")
1150
+ throw new CliError("cancelled", "no message: nothing was sent");
1151
+ }
1152
+ // Text: the arguments; or stdin with --stdin / `-`; or, with neither and no --notify-when-idle,
1153
+ // stdin when it isn't a terminal. A pure subscription never waits on a pipe that may not close.
1154
+ const fromStdin = o.stdin || (text.length === 1 && text[0] === "-");
1155
+ let body = fromStdin ? "" : text.join(" ");
1156
+ if ((fromStdin || (body === "" && !o.notifyWhenIdle)) && io.readStdin)
1157
+ body = (await io.readStdin({ implicit: !fromStdin })).replace(/\n$/, "");
1158
+ if (fromStdin && body === "" && !o.notifyWhenIdle)
1159
+ throw new CliError("usage", "stdin was empty");
1160
+ if (!fromStdin && body === "" && !o.notifyWhenIdle) {
1161
+ // review L2: without --stdin, stdin is only waited on briefly.
1162
+ throw new CliError("usage", "no message text: give it as arguments, or pipe it in with --stdin (or `-` as the text), which waits for the whole input");
1163
+ }
1164
+ // Sending from the tui session (a person at a terminal, no --from-session): the recipient is added to
1165
+ // that session's roster first, so the message can land there and their replies reach `p2p tui`.
1166
+ // Never with --from-session, and never off a terminal (fromTui is only reachable through a picker).
1167
+ // Shared only with the send (undone if it fails): sessions.sendSharing.
1168
+ let shared = "";
1169
+ let r;
1170
+ if (fromTui) {
1171
+ const s = await ops.sendSharing(app, { fromSession: o.fromSession, to: o.to, text: body, notifyWhenIdle: o.notifyWhenIdle });
1172
+ r = s.result;
1173
+ if (s.shared)
1174
+ shared = `shared session tui with ${s.shared.address}\n`;
1175
+ }
1176
+ else
1177
+ r = await ops.sendMessage(app, { fromSession: o.fromSession, to: o.to, text: body, notifyWhenIdle: o.notifyWhenIdle, ...(o.projectDir ? { projectDirs: o.projectDir } : {}), ...(o.projectDirsOver ? { projectDirsOver: true } : {}), ...(person ? { person: true } : {}) });
1178
+ const tail = r.notifyWhenIdle ? `; will notify when ${r.to.address} [${r.to.ref}] is idle` : "";
1179
+ const where = r.to.own === r.to.userId ? `${r.to.address} [${r.to.ref}]` : `${r.to.address} (in your session ${r.to.sid})`;
1180
+ const ago = (ms) => {
1181
+ const m = Math.max(0, Math.round((Date.now() - ms) / 60_000));
1182
+ return m < 1 ? "just now" : m < 120 ? `${m} min ago` : `${Math.round(m / 60)} h ago`;
1183
+ };
1184
+ const until = (ms) => `expires in ${Math.max(1, Math.round((ms - Date.now()) / 86_400_000))} days`;
1185
+ // The person's own sends cross no project boundary, but say which one this folder has (projects.ts).
1186
+ const here = person ? await ops.showProject(app, projects.sessionWorkdir(app.env)).catch(() => undefined) : undefined;
1187
+ const boundary = here ? `\nproject ${here.name} here is ${here.policy === "private" ? "private (agent sessions in it reach only your own devices)" : "shared"}; this send was yours, from your terminal` : "";
1188
+ const from = fromTui ? `\nsent from session tui; replies show in \`p2p tui\`${boundary}` : "";
1189
+ if (r.queued && r.state === "outbox") {
1190
+ return { json: r, human: `${shared}Queued for ${where}: this device can't reach a relay right now; it goes out when one is back (${until(r.expiresAt)})${tail}.${from}` };
1191
+ }
1192
+ if (r.queued) {
1193
+ return { json: r, human: `${shared}Sent to ${where}, which is offline (last seen ${ago(r.lastSeen)}): delivered via ${fmt.plural(r.relays, "relay")}, held there until it reconnects (${until(r.expiresAt)})${tail}.${from}` };
1194
+ }
1195
+ return { json: r, human: `${shared}${r.delivered ? `Sent to ${where}: delivered via ${fmt.plural(r.relays, "relay")}${tail}.` : `Subscribed${tail}.`}${from}` };
1196
+ }, { sends: true });
1197
+ program
1198
+ .command("receipt <event>")
1199
+ .description("Send a delivery receipt for a message this session has (§4.3; the front end that shows messages reports the outcome)")
1200
+ .requiredOption("--from-session <sid>", "The session that has the message")
1201
+ .requiredOption("--outcome <outcome>", "shown | held | declined | expired | ended")
1202
+ .option("--json", "JSON output")
1203
+ .action(run(async (app, event, o) => {
1204
+ const r = await sendReceipt(app, { eventId: event, fromSession: sessions.checkSid(o.fromSession, "--from-session"), outcome: o.outcome });
1205
+ return { json: r, human: r.sent ? `Receipt sent: ${r.outcome}.` : `No receipt sent (${r.reason}).` };
1206
+ }));
1207
+ program
1208
+ .command("receipts [state]")
1209
+ .description("Whether this user sends delivery receipts: `on` or `off` sets it (config.json; P2P_RECEIPTS overrides)")
1210
+ .option("--json", "JSON output")
1211
+ .action(run(async (app, state) => {
1212
+ if (state !== undefined && state !== "on" && state !== "off")
1213
+ throw new CliError("usage", "p2p receipts [on|off]");
1214
+ if (state !== undefined)
1215
+ await updateFileConfigField(app, "receipts", () => ({ next: state === "on", result: undefined }));
1216
+ const r = receiptsSetting(app);
1217
+ const note = r.overridden ? " (P2P_RECEIPTS is set and overrides config.json)" : "";
1218
+ return { json: r, human: `Delivery receipts are ${r.receipts ? "on" : "off"}${note}.` };
1219
+ }, { requireIdentity: false }));
1220
+ program
1221
+ .command("status")
1222
+ .description("Post this session's status to everyone its roster allows (safe every 60 s)")
1223
+ .requiredOption("--session <sid>", "Your session id")
1224
+ .addOption(new Option("--state <state>", "busy or idle").choices(["busy", "idle"]).makeOptionMandatory())
1225
+ .option("--summary <text>", "What the session is working on (one line)")
1226
+ .option("--file <path>", "A repo-relative file being changed (repeatable)", collect)
1227
+ .option("--label <label>", "Short session name (default: the directory name)")
1228
+ .option("--repo <repo>", "Repository")
1229
+ .option("--branch <branch>", "Branch")
1230
+ .option("--mode <mode>", "Permission mode")
1231
+ .option("--cap <cap>", "Something this session's client understands, e.g. agents.v1 (repeatable)", collect)
1232
+ .option("--agents-json <json>", "The session's subagents as a JSON array (`-` reads it from stdin); sent only to peers that understand agents.v1")
1233
+ .option("--project-dir <dir>", "Another folder the session works in (repeatable): binds it to that project too, which only ever narrows who sees it", collect)
1234
+ .option("--project-dirs-over", "The front end dropped folders past its cap: the session is private")
1235
+ .option("--json", "JSON output")
1236
+ .action(run(async (app, o) => {
1237
+ let agents;
1238
+ if (o.agentsJson !== undefined) {
1239
+ const text = o.agentsJson === "-" ? (io.readStdin ? await io.readStdin() : "") : o.agentsJson;
1240
+ if (Buffer.byteLength(text, "utf8") > 64 * 1024)
1241
+ throw new CliError("usage", "--agents-json is at most 64 KiB");
1242
+ try {
1243
+ agents = JSON.parse(text);
1244
+ }
1245
+ catch {
1246
+ throw new CliError("usage", "--agents-json must be a JSON array of agents");
1247
+ }
1248
+ }
1249
+ const r = await ops.sendStatus(app, { session: o.session, state: o.state, summary: o.summary, files: o.file, label: o.label, repo: o.repo, branch: o.branch, mode: o.mode, caps: o.cap, agents, ...(o.projectDir ? { projectDirs: o.projectDir } : {}), ...(o.projectDirsOver ? { projectDirsOver: true } : {}) });
1250
+ for (const w of r.warnings ?? [])
1251
+ io.err(`p2p: ${w}`);
1252
+ const n = r.delivered.length;
1253
+ return {
1254
+ json: r,
1255
+ human: `${r.status.state} posted to ${fmt.plural(n, "peer")}${r.failed.length ? `; ${r.failed.length} unreachable (${r.failed.map((f) => f.address).join(", ")})` : ""}.\n${fmt.formatRoster(r.roster)}`,
1256
+ pretty: (p) => pretty.prettyStatus(r, p),
1257
+ };
1258
+ }));
1259
+ const session = program.command("session").description("Session settings");
1260
+ session
1261
+ .command("roster <sid>")
1262
+ .description("Who may see and message this session: within what its project allows (`p2p project`), private until shared")
1263
+ .option("--circle <cid>", "Share with a circle you joined")
1264
+ .option("--private", "Only the listed people")
1265
+ .option("--add <user>", "Add a participant (repeatable)", collect)
1266
+ .option("--remove <user>", "Remove a participant (repeatable)", collect)
1267
+ .option("--json", "JSON output")
1268
+ .action(run(async (app, sid, o) => {
1269
+ const r = await ops.roster(app, sid, o);
1270
+ return { json: { roster: r }, human: fmt.formatRoster(r) };
1271
+ }));
1272
+ // ── projects (projects.ts): who sees sessions working in a repository ──────
1273
+ const project = program
1274
+ .command("project")
1275
+ .description("Who sees sessions working in this project (a git repository, or a folder): private until you share it")
1276
+ .addHelpText("after", [
1277
+ "",
1278
+ "A project is private until you share it: only your own devices see its sessions, their files,",
1279
+ "footprints and summaries, and none of its sessions can send to anyone else. A session that works",
1280
+ "in several projects reaches only who all of them share. Policies live only on this device;",
1281
+ `nothing in a repository can widen them (a committed ${projects.PRIVATE_MARKER} can only make it private).`,
1282
+ ].join("\n"));
1283
+ const projectView = (v) => {
1284
+ const lines = [`${v.name} ${v.policy === "private" ? "private" : "shared"}${v.kind === "git" ? (v.remote ? ` (${v.remote})` : " (git, no remote)") : " (folder)"}`, ` ${v.root}`];
1285
+ if (v.policy === "private")
1286
+ lines.push(` only your own devices see its sessions${v.why === "unmapped" ? " (never shared: `p2p project share <circle>` in it)" : v.why ? ` (${v.why})` : ""}`);
1287
+ for (const c of v.circles)
1288
+ lines.push(` circle ${c.name ?? c.cid} (${c.cid})${c.open ? ", open: anyone its owner admits" : ""}${c.joined ? "" : ", not joined: ignored"}`);
1289
+ for (const p of v.people)
1290
+ lines.push(` ${p.address}`);
1291
+ return lines.join("\n");
1292
+ };
1293
+ project
1294
+ .command("share [circles...]")
1295
+ .description("Share the project here with circles you joined (and friends with --person); on a terminal with none named, pick them")
1296
+ .option("--person <user>", "A friend to share it with too (repeatable)", collect)
1297
+ .option("--add", "Keep what it is shared with already (default: replace it)")
1298
+ .option("--dir <path>", "The project's folder (default: P2P_WORKDIR, else the current directory)")
1299
+ .option("--json", "JSON output")
1300
+ .action(run(async (app, named, o) => {
1301
+ const dir = o.dir ?? projects.sessionWorkdir(app.env);
1302
+ let circlesIn = [...named];
1303
+ let people = [...(o.person ?? [])];
1304
+ if (circlesIn.length + people.length === 0 && canAsk(cmdOf(o))) {
1305
+ const here = await ops.showProject(app, dir);
1306
+ const cs = await circleChoices(app, (c) => c.joined);
1307
+ const fs = (await friendChoices(app)).map((f) => ({ ...f, value: `person:${f.value}` }));
1308
+ const picked = await ask({
1309
+ intro: [`Project ${here.name} (${here.root}) is ${here.policy}.`, "Everyone you pick sees its sessions: status, summary, files and footprints, and its agents may message them."],
1310
+ message: `Share ${here.name} with:`,
1311
+ choices: [...cs.map((c) => ({ ...c, checked: c.value === app.self?.defaultCircle || here.circles.some((x) => x.cid === c.value) })), ...fs],
1312
+ multi: true,
1313
+ max: projects.MAX_PROJECT_SHARES,
1314
+ });
1315
+ circlesIn = picked.filter((v) => !v.startsWith("person:"));
1316
+ people = picked.filter((v) => v.startsWith("person:")).map((v) => v.slice("person:".length));
1317
+ if (circlesIn.length + people.length === 0)
1318
+ throw new CliError("cancelled", "nothing picked: nothing was shared");
1319
+ }
1320
+ else if (circlesIn.length + people.length === 0) {
1321
+ // The quick way for someone who relied on the default circle: share this project with it.
1322
+ const def = app.self?.defaultCircle;
1323
+ if (!def)
1324
+ throw new CliError("usage", "name a circle (or --person <friend>) to share this project with");
1325
+ circlesIn = [def];
1326
+ }
1327
+ const r = await ops.shareProject(app, dir, { circles: circlesIn, people, ...(o.add ? { add: true } : {}) });
1328
+ for (const w of r.warnings)
1329
+ io.err(`p2p: warning: ${w}`);
1330
+ return { json: { project: r.project, ...(r.warnings.length ? { warnings: r.warnings } : {}) }, human: `Shared. Sessions in ${r.project.name} are seen by:\n${projectView(r.project)}` };
1331
+ }));
1332
+ project
1333
+ .command("private")
1334
+ .description("Make the project here private: only your own devices see its sessions (the default)")
1335
+ .option("--dir <path>", "The project's folder (default: P2P_WORKDIR, else the current directory)")
1336
+ .option("--json", "JSON output")
1337
+ .action(run(async (app, o) => {
1338
+ const v = await ops.makeProjectPrivate(app, o.dir ?? projects.sessionWorkdir(app.env));
1339
+ return { json: { project: v }, human: `${v.name} is private: sessions in it reach only your own devices, from their next status on (a session that worked in it stays private until it ends).` };
1340
+ }));
1341
+ project
1342
+ .command("ls")
1343
+ .description("Projects with a policy on this device, and who sees each")
1344
+ .option("--json", "JSON output")
1345
+ .action(run(async (app) => {
1346
+ const all = await ops.listProjects(app);
1347
+ return { json: { projects: all }, human: all.length === 0 ? "No project is shared: every session is seen only by your own devices. `p2p project share <circle>` in a repository shares it." : all.map(projectView).join("\n\n") };
1348
+ }));
1349
+ project
1350
+ .command("show")
1351
+ .description("The project here (its id, root, remote) and who sees its sessions")
1352
+ .option("--dir <path>", "The project's folder (default: P2P_WORKDIR, else the current directory)")
1353
+ .option("--json", "JSON output")
1354
+ .action(run(async (app, o) => {
1355
+ const v = await ops.showProject(app, o.dir ?? projects.sessionWorkdir(app.env));
1356
+ return { json: { project: v }, human: projectView(v) };
1357
+ }));
1358
+ session
1359
+ .command("bound <sid>")
1360
+ .description("Bind a session to the bound an own-session message it took carried (front ends call it on Deliver; narrowing only)")
1361
+ .requiredOption("--bound <json>", '"private" or {"circles": [...], "people": [...]}, as the message carried it')
1362
+ .option("--json", "JSON output")
1363
+ .action(run(async (app, sid, o) => {
1364
+ let v;
1365
+ try {
1366
+ v = JSON.parse(o.bound);
1367
+ }
1368
+ catch {
1369
+ throw new CliError("usage", "--bound must be JSON");
1370
+ }
1371
+ const r = await ops.bindBound(app, sid, v);
1372
+ return { json: { project: r }, human: `session ${sid}: ${r.policy}${r.why ? ` (${r.why})` : ""}` };
1373
+ }));
1374
+ program
1375
+ .command("doctor [user]")
1376
+ .description("Explain why sessions are or aren't visible: this device's identity, relays, clock, circle and sharing, or (with a user) whether you can see them")
1377
+ .option("--json", "JSON output")
1378
+ .addHelpText("after", [
1379
+ "",
1380
+ "Each check is ✓ (fine), ✗ (a problem, with a fix) or ? (unknown, with what would tell). Read-only: it",
1381
+ "publishes and sends nothing. Every network step is bounded (P2P_DOCTOR_TIMEOUT_MS, default 5000).",
1382
+ "<user> is a name@fingerprint, petname, name or userId.",
1383
+ ].join("\n"))
1384
+ .action(run(async (app, user) => {
1385
+ const r = await ops.doctor(app, { version: VERSION, ...(user !== undefined ? { user } : {}) });
1386
+ const plain = doctorOps.formatDoctor(r);
1387
+ return { json: r, human: plain, pretty: (p) => pretty.prettyDoctor(r, plain, p) };
1388
+ }, { requireIdentity: false, readOnly: true }));
1389
+ program
1390
+ .command("watch")
1391
+ .description("Stream accepted events as JSON lines (reconnects silently; Ctrl-C to stop)")
1392
+ .requiredOption("--session <sid>", "Your session id")
1393
+ .option("--jsonl", "One compact JSON line per event (the default)")
1394
+ .option("--json", "Alias for --jsonl")
1395
+ .action(async (o) => {
1396
+ const app = makeApp(deps.env, io);
1397
+ try {
1398
+ await app.load(true);
1399
+ sessions.checkSid(o.session);
1400
+ }
1401
+ catch (e) {
1402
+ const j = toErrorJson(e);
1403
+ io.err(`p2p watch: ${String(j.error)}: ${String(j.reason)}`);
1404
+ process.exitCode = 1;
1405
+ return;
1406
+ }
1407
+ const ctl = new AbortController();
1408
+ const onSignal = () => ctl.abort();
1409
+ process.on("SIGINT", onSignal);
1410
+ process.on("SIGTERM", onSignal);
1411
+ deps.signal?.addEventListener("abort", onSignal);
1412
+ try {
1413
+ const code = await ops.watch(app, {
1414
+ session: o.session,
1415
+ signal: ctl.signal,
1416
+ log: (m) => io.err(m),
1417
+ write: deps.writeLine ?? stdoutWriter(ctl),
1418
+ });
1419
+ process.exitCode = code;
1420
+ }
1421
+ catch (e) {
1422
+ const j = toErrorJson(e);
1423
+ io.err(`p2p watch: ${String(j.error)}: ${String(j.reason)}`);
1424
+ process.exitCode = 1;
1425
+ }
1426
+ finally {
1427
+ process.off("SIGINT", onSignal);
1428
+ process.off("SIGTERM", onSignal);
1429
+ }
1430
+ });
1431
+ program
1432
+ .command("tui")
1433
+ .description("Full-screen terminal UI: people and their sessions, held items, messages, send, health (your own terminal only)")
1434
+ .option("--session <sid>", "This TUI's session id (default: tui)")
1435
+ .action(async (o) => {
1436
+ process.exitCode = await tuiCommand({ env: deps.env, io, version: VERSION, makeApp: (env, i) => makeApp(env, i), front: deps.front === true, ...(deps.isTTY !== undefined ? { isTTY: deps.isTTY } : {}), ...(deps.terminal ? { terminal: deps.terminal } : {}), ...(deps.signal ? { signal: deps.signal } : {}) }, o);
1437
+ });
1438
+ // `p2p` with no arguments on a terminal (main maps it here): who you are, relay health, friends
1439
+ // online, held items, the commands to try. Piped, `p2p` alone still prints the help.
1440
+ program
1441
+ .command("home", { hidden: true })
1442
+ .description("The home screen")
1443
+ .action(run(async (app) => {
1444
+ if (!(await app.load(false)))
1445
+ return { json: {}, human: "", pretty: (p) => pretty.prettyHome({ relays: [], online: [], friends: 0, held: 0 }, p) };
1446
+ await app.connectAndDrain().catch(() => undefined);
1447
+ const st = app.relayStatus;
1448
+ const relays = app.relays.map((u) => ({ url: u, ok: st ? st.connected.includes(u) : false }));
1449
+ const peers = await ops.listPeers(app, {}).catch(() => []);
1450
+ const f = await ops.friends(app).catch(() => ({ friends: [] }));
1451
+ const held = await ops.listHeld(app).catch(() => []);
1452
+ const online = [...new Set(peers.filter((p) => p.live && !p.self).map((p) => p.address))];
1453
+ const d = { address: app.self ? await app.addressOf(app.userId) : undefined, relays, online, friends: f.friends.length, held: held.length };
1454
+ return { json: d, human: "", pretty: (p) => pretty.prettyHome(d, p) };
1455
+ }, { requireIdentity: false }));
1456
+ registerExtensionCommands(program, extensions, { io, run, confirm: confirmPrompt, collect });
1457
+ codexCommands(program, deps, io);
1458
+ return program;
1459
+ }
1460
+ /** The running `p2p` script (the bundled p2p.mjs, or dist/bin.js), for Codex to start. */
1461
+ function selfScript(deps) {
1462
+ const p = deps.scriptPath ?? process.argv[1] ?? "";
1463
+ try {
1464
+ return realpathSync(p);
1465
+ }
1466
+ catch {
1467
+ return resolve(p);
1468
+ }
1469
+ }
1470
+ /**
1471
+ * `p2p codex …`: the Codex bridge (@peer2peer/codex-bridge). The MCP server
1472
+ * and hooks run from this same script, so the single-file p2p.mjs carries
1473
+ * everything Codex needs.
1474
+ */
1475
+ function codexCommands(program, deps, io) {
1476
+ const out = (json, o) => {
1477
+ if (json)
1478
+ io.out(safeJson(o.json));
1479
+ else if (o.human)
1480
+ io.out(safeTerminal(o.human));
1481
+ };
1482
+ const fail = (json, e) => {
1483
+ const err = e instanceof codex.CodexCommandError ? { error: e.code, reason: e.message } : toErrorJson(e);
1484
+ if (json)
1485
+ io.out(safeJson(err));
1486
+ else
1487
+ io.err(`p2p codex: ${String(err.error)}: ${String(err.reason)}`);
1488
+ process.exitCode = 1;
1489
+ };
1490
+ const self = () => [process.execPath, selfScript(deps)];
1491
+ const c = program.command("codex").description("Peer2Peer for OpenAI Codex: MCP server, hooks, installer, held messages");
1492
+ c.command("install")
1493
+ .description("Print the Codex config (MCP server, hooks, AGENTS.md lines); --write applies it (backs up first, idempotent)")
1494
+ .option("--write", "Edit config.toml, hooks.json and AGENTS.md in the Codex home")
1495
+ .option("--remove", "Remove the peer2peer entries instead (with --write)")
1496
+ .option("--codex-home <dir>", "The Codex home (default: CODEX_HOME, else ~/.codex)")
1497
+ .option("--json", "JSON output")
1498
+ .action(async (o) => {
1499
+ try {
1500
+ const script = selfScript(deps);
1501
+ out(Boolean(o.json), codex.installCommand({ env: deps.env, node: deps.nodeCommand ?? process.execPath, script, ...(o.codexHome ? { codexHome: resolve(o.codexHome) } : {}), write: o.write, remove: o.remove }));
1502
+ }
1503
+ catch (e) {
1504
+ fail(Boolean(o.json), e);
1505
+ }
1506
+ });
1507
+ c.command("mcp")
1508
+ .description("The stdio MCP server Codex starts for each session (not for interactive use)")
1509
+ .action(async () => {
1510
+ const stdin = deps.stdin ?? process.stdin;
1511
+ const stop = () => stdin.destroy();
1512
+ process.once("SIGTERM", stop);
1513
+ process.once("SIGINT", stop);
1514
+ try {
1515
+ // P2P_BIN applies only from the user-level Codex config (the server checks).
1516
+ await codex.runMcpServer({ bin: self(), env: deps.env, stdin, stdout: deps.stdout ?? process.stdout, stderr: process.stderr });
1517
+ }
1518
+ finally {
1519
+ process.off("SIGTERM", stop);
1520
+ process.off("SIGINT", stop);
1521
+ }
1522
+ });
1523
+ c.command("hook <event>")
1524
+ .description("A Codex hook: reads the event's JSON on stdin (configured by `p2p codex install`)")
1525
+ .option("--managed-by <installer>", "Marks the hook entries `p2p codex install` wrote (ignored when run)")
1526
+ .action(async (event) => {
1527
+ try {
1528
+ const stdin = io.readStdin ? await io.readStdin() : "";
1529
+ const binNames = [deps.env.P2P_BIN?.trim(), selfScript(deps)].filter((v) => !!v);
1530
+ const answer = await codex.runHook(event, stdin, { home: codex.bridgeHome(deps.env), binNames, ...((deps.env.HOME ?? deps.env.USERPROFILE) ? { homeDir: deps.env.HOME ?? deps.env.USERPROFILE } : {}) });
1531
+ if (answer)
1532
+ io.out(answer);
1533
+ }
1534
+ catch {
1535
+ // A hook never breaks Codex: no output, exit 0.
1536
+ }
1537
+ process.exitCode = 0;
1538
+ });
1539
+ c.command("sessions")
1540
+ .description("This machine's live Codex sessions on Peer2Peer (sid, who sees them, held messages)")
1541
+ .option("--json", "JSON output")
1542
+ .action(async (o) => {
1543
+ try {
1544
+ out(Boolean(o.json), await codex.sessionsCommand({ env: deps.env }));
1545
+ }
1546
+ catch (e) {
1547
+ fail(Boolean(o.json), e);
1548
+ }
1549
+ });
1550
+ c.command("held")
1551
+ .description("Messages your Codex sessions hold for you, with previews (run in your own terminal)")
1552
+ .option("--json", "JSON output")
1553
+ .action(async (o) => {
1554
+ try {
1555
+ out(Boolean(o.json), await codex.heldCommand({ env: deps.env }));
1556
+ }
1557
+ catch (e) {
1558
+ fail(Boolean(o.json), e);
1559
+ }
1560
+ });
1561
+ for (const verb of ["release", "decline"]) {
1562
+ c.command(`${verb} <id>`)
1563
+ .description(verb === "release" ? "Hand a held message to its Codex session's model" : "Drop a held message (its sender gets one notice)")
1564
+ .option("--json", "JSON output")
1565
+ .action(async (id, o) => {
1566
+ try {
1567
+ const isTTY = deps.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
1568
+ out(Boolean(o.json), await codex.resolveCommand({ env: deps.env, id, decline: verb === "decline", io: { isTTY, ...(io.prompt ? { prompt: io.prompt } : {}) } }));
1569
+ }
1570
+ catch (e) {
1571
+ fail(Boolean(o.json), e);
1572
+ }
1573
+ });
1574
+ }
1575
+ }
1576
+ /** Writes a line to stdout; resolves false once the reader is gone (EPIPE). */
1577
+ export function stdoutWriter(ctl) {
1578
+ let gone = false;
1579
+ process.stdout.on("error", () => {
1580
+ gone = true;
1581
+ ctl.abort();
1582
+ });
1583
+ return (line) => new Promise((resolve) => {
1584
+ if (gone || ctl.signal.aborted)
1585
+ return resolve(false);
1586
+ try {
1587
+ process.stdout.write(line + "\n", (err) => resolve(!err && !gone));
1588
+ }
1589
+ catch {
1590
+ resolve(false);
1591
+ }
1592
+ });
1593
+ }
1594
+ /** The extensions the user enabled (P2P_EXTENSIONS, else config.json `extensions`); see extensions.ts. */
1595
+ async function loadInstalled(deps) {
1596
+ const home = resolveHome(deps.env);
1597
+ let config = {};
1598
+ try {
1599
+ config = readFileConfig(home);
1600
+ }
1601
+ catch {
1602
+ // a broken config.json is reported by the command itself
1603
+ }
1604
+ const say = (m) => deps.io.err(safeTerminal(m));
1605
+ return loadExtensions({ env: deps.env, home, config, warn: say, log: say });
1606
+ }
1607
+ /** Parses and runs; returns the exit code. */
1608
+ export async function main(argvIn, deps) {
1609
+ // The person token: checked once, then taken out of the environment before anything runs, so no
1610
+ // child process (git, ix, an extension's tool) can read it (projects.ts).
1611
+ {
1612
+ // A copy without it (an embedder's object is left as it was); the process's own environment loses it too.
1613
+ const env = { ...deps.env };
1614
+ const front = deps.front === true || projects.takePersonToken(env, resolveHome(env));
1615
+ if (deps.env === process.env)
1616
+ delete process.env.P2P_PERSON_TOKEN;
1617
+ deps = { ...deps, front, env };
1618
+ }
1619
+ // `--no-input` anywhere before `--`: no pickers, no questions (as a script would run).
1620
+ const end = argvIn.indexOf("--");
1621
+ const head = end < 0 ? argvIn : argvIn.slice(0, end);
1622
+ let argv = argvIn;
1623
+ if (head.includes("--no-input")) {
1624
+ argv = [...head.filter((a) => a !== "--no-input"), ...(end < 0 ? [] : argvIn.slice(end))];
1625
+ deps = { ...deps, noInput: true };
1626
+ }
1627
+ // `p2p` alone on a terminal: the home screen. Piped, it prints the help as before.
1628
+ if (argv.length === 0 && deps.io.pretty && !deps.noInput)
1629
+ argv = ["home"];
1630
+ // `doctor` is read-only and needs no extension: loading one records where it came from
1631
+ // (<home>/extension-locations.json) and runs its code, so it is skipped.
1632
+ const isDoctor = argv.find((a) => !a.startsWith("-")) === "doctor";
1633
+ const extensions = deps.extensions ?? (isDoctor ? new ExtensionRegistry() : await loadInstalled(deps));
1634
+ const program = buildProgram({ ...deps, extensions });
1635
+ process.exitCode = 0;
1636
+ try {
1637
+ await program.parseAsync(argv, { from: "user" });
1638
+ }
1639
+ catch (e) {
1640
+ if (e instanceof CommanderError) {
1641
+ if (e.code === "commander.helpDisplayed" || e.code === "commander.version" || e.code === "commander.help")
1642
+ return 0;
1643
+ return 1;
1644
+ }
1645
+ const j = toErrorJson(e);
1646
+ deps.io.err(safeTerminal(`p2p: ${String(j.error)}: ${String(j.reason)}`));
1647
+ return 1;
1648
+ }
1649
+ return typeof process.exitCode === "number" ? process.exitCode : 0;
1650
+ }