@peer2peer/cli 0.1.1 → 0.1.3

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.
package/dist/identity.js CHANGED
@@ -9,18 +9,33 @@ import { addIdentityVersion, b64uEncode, backupPhraseFromSeed, canonicalProofLoc
9
9
  import { capPeek, certDid, defaultLabel, defaultName, joinCapOf, newKeysDoc } from "./app.js";
10
10
  import { defaultRelays, normalizeRelays } from "./config.js";
11
11
  import { CliError } from "./errors.js";
12
+ import { isOwnRelay, isPrivateRelayHost, PRIVATE_RESOLVE_MARK, privateGuardLookup, privateRelayMessage } from "./shortcode.js";
12
13
  import { fetchTips, linkGet, linkPut, openLinkConnection, relayCode, sleep } from "./relay-client.js";
13
14
  import { exportAll, sendSync, verifiedIssuedCap } from "./sync.js";
14
15
  import { receiving } from "./inbound.js";
15
16
  import { recordJoin, resignJoin } from "./circle-ops.js";
16
17
  import { setupIx } from "./ix-local.js";
18
+ import { renewPersonToken } from "./projects.js";
19
+ /** The `p2p` command as the person types it here (Windows PowerShell blocks npm's p2p.ps1 shim; p2p.cmd works everywhere on Windows). */
20
+ export function p2pCommand(platform = process.platform) {
21
+ return platform === "win32" ? "p2p.cmd" : "p2p";
22
+ }
23
+ /**
24
+ * Why a new identity can't be made here (no relay anywhere), naming the three ways in. There is
25
+ * no default relay, by design (bring your own relay).
26
+ */
27
+ export function noRelaysReason(home, platform = process.platform) {
28
+ const p = p2pCommand(platform);
29
+ return (`no relays configured. Already use Peer2Peer on another device? Run \`p2p link start\` there, then \`${p} link join <code>\` here (one identity, not a second one). ` +
30
+ `Have an invite? \`${p} join <invite link or code>\`. ` +
31
+ `Starting a new identity? Pass --relay wss://… (1–5, your group's relay), or set P2P_DEFAULT_RELAYS, or "defaultRelays" in ${home}/config.json`);
32
+ }
17
33
  export async function init(app, opts) {
18
34
  if (await app.load(false))
19
35
  throw new CliError("already_initialized", `${app.home} already holds an identity (${app.userId})`);
20
36
  const relays = opts.relays && opts.relays.length > 0 ? normalizeRelays(opts.relays) : defaultRelays(app.env, app.file);
21
- if (relays.length === 0) {
22
- throw new CliError("no_relays", `no relays configured: pass --relay wss://… (1–5), or set P2P_DEFAULT_RELAYS, or "defaultRelays" in ${app.home}/config.json`);
23
- }
37
+ if (relays.length === 0)
38
+ throw new CliError("no_relays", noRelaysReason(app.home));
24
39
  const name = opts.name ?? defaultName();
25
40
  if (!isValidName(name))
26
41
  throw new CliError("usage", "--name must match [a-z0-9._-]{1,32}");
@@ -30,6 +45,10 @@ export async function init(app, opts) {
30
45
  const doc = createIdentityDoc(ik, { ver: 1, prev: null, name, relays, devices: [device.did], keyholders: [device.did], by: device.did, certs: [cert] });
31
46
  const keys = newKeysDoc(ik.userId, device, cert, ik);
32
47
  const self = { name, relays, createdAt: Date.now() };
48
+ // A person.key from before this identity existed no longer counts (projects.ts renewPersonToken).
49
+ // Replaced before any key is written: if that fails, no identity is made here.
50
+ renewPersonToken(app.home, keys.spk);
51
+ app.identityMadeHere = true;
33
52
  await app.state.put("keys", keys);
34
53
  await app.state.put("self", self);
35
54
  app.setKeys(keys, self);
@@ -49,10 +68,13 @@ export const BACKUP_FILE_NAME = "backup-phrase.txt";
49
68
  export async function setup(app, opts) {
50
69
  let created = false;
51
70
  let pub;
71
+ let backupMode = opts.backup;
52
72
  if (!(await app.load(false))) {
53
73
  const r = await init(app, { name: opts.name, relays: opts.relays });
54
74
  created = true;
55
75
  pub = { published: r.published, failed: r.failed };
76
+ if (backupMode === undefined && opts.chooseBackup)
77
+ backupMode = await opts.chooseBackup(r);
56
78
  }
57
79
  const v = await app.ownView();
58
80
  const out = {
@@ -65,13 +87,13 @@ export async function setup(app, opts) {
65
87
  ...(pub ?? {}),
66
88
  };
67
89
  try {
68
- out.ix = await setupIx(app, created);
90
+ out.ix = await setupIx(app, created, { reoffer: opts.ix === true });
69
91
  }
70
92
  catch (e) {
71
93
  // Never fails a setup: Ix is optional.
72
- out.ix = { found: false, enabled: false, hint: `couldn't check for Ix: ${sanitizePeerText(e.message, 200)}` };
94
+ out.ix = { found: false, installed: false, recommended: false, enabled: false, hint: `couldn't check for Ix: ${sanitizePeerText(e.message, 200)}` };
73
95
  }
74
- if (opts.backup === "file") {
96
+ if (backupMode === "file") {
75
97
  const path = opts.backupFile ?? join(app.home, BACKUP_FILE_NAME);
76
98
  const { phrase } = await backupShow(app);
77
99
  try {
@@ -86,9 +108,12 @@ export async function setup(app, opts) {
86
108
  await chmod(path, 0o600);
87
109
  out.backup = { file: path };
88
110
  }
89
- else if (opts.backup === "print") {
111
+ else if (backupMode === "print") {
90
112
  out.backup = { phrase: (await backupShow(app)).phrase };
91
113
  }
114
+ // This device is the only key holder and its phrase was never shown: losing it loses the identity.
115
+ if (!out.backup && app.isKeyholder && v.head.keyholders.length < 2 && !app.self?.backupShown)
116
+ out.backupNeeded = true;
92
117
  return out;
93
118
  }
94
119
  // ---------------------------------------------------------------------------
@@ -96,12 +121,14 @@ export async function setup(app, opts) {
96
121
  export async function relaysList(app) {
97
122
  return { relays: [...(await app.ownView()).head.relays] };
98
123
  }
99
- async function changeRelays(app, f) {
124
+ async function changeRelays(app, f, removing = []) {
100
125
  app.requireKeyholder("Changing your relays");
101
126
  await app.connectAndDrain();
102
127
  const pub = await app.publishNext((p) => {
103
128
  p.relays = f(p.relays);
104
- });
129
+ },
130
+ // #67: removing a relay must work even while it serves versions that don't connect (App.ownStrictFallback).
131
+ { removing });
105
132
  const re = await reissueForRelays(app);
106
133
  return { relays: [...(await app.ownView()).head.relays], ver: pub.ver, published: pub.ok, failed: pub.failed, ...re };
107
134
  }
@@ -169,28 +196,39 @@ export async function relaysAdd(app, url) {
169
196
  throw new CliError("bad_relay", `at most ${MAX_RELAYS} relays: remove one first`);
170
197
  return changeRelays(app, (list) => [...list.filter((x) => x !== r), r]);
171
198
  }
172
- /** Removes a relay (at least one must stay). The removed relay gets the new version too, so it stops admitting removed state. */
173
- export async function relaysRemove(app, url) {
174
- const r = normalizeRelays([url])[0];
199
+ /**
200
+ * Removes relays (at least one must stay), in one new version. The removed relays get it too, so they stop
201
+ * admitting removed state. Several at once (#78 review): two relays that both went silent while holding a
202
+ * newer version each hold up removing the other one alone (App.ownPendingGuard).
203
+ */
204
+ export async function relaysRemove(app, urls) {
205
+ const rs = [...new Set(normalizeRelays(typeof urls === "string" ? [urls] : [...urls]))];
206
+ if (rs.length === 0)
207
+ throw new CliError("usage", "name the relay to remove");
175
208
  const cur = (await app.ownView()).head.relays;
176
- if (!cur.includes(r))
177
- throw new CliError("not_found", `${r} is not one of your relays`);
178
- if (cur.length === 1)
179
- throw new CliError("usage", "that is your only relay: add another first");
180
- // Caps naming the dropped relay, captured before the re-issue adds new ones.
181
- const old = (await app.store.listCapsIssued()).filter((c) => c.iss === app.userId && c.relays.includes(r));
182
- const out = await changeRelays(app, (list) => list.filter((x) => x !== r));
183
- // review L2: revoke them at the dropped relay only (our devices are still in its allowlist). Other
209
+ for (const r of rs)
210
+ if (!cur.includes(r))
211
+ throw new CliError("not_found", `${r} is not one of your relays`);
212
+ if (cur.every((r) => rs.includes(r)))
213
+ throw new CliError("usage", cur.length === 1 ? "that is your only relay: add another first" : "at least one relay must stay: add another first");
214
+ // Caps naming a dropped relay, captured before the re-issue adds new ones.
215
+ const old = (await app.store.listCapsIssued()).filter((c) => c.iss === app.userId && c.relays.some((r) => rs.includes(r)));
216
+ const out = await changeRelays(app, (list) => list.filter((x) => !rs.includes(x)), rs);
217
+ // review L2: revoke them at the dropped relays only (our devices are still in their allowlists). Other
184
218
  // relays keep honouring them, so friends who haven't picked up the new caps stay covered.
185
219
  // Best effort: the relay may be down.
186
220
  let revokedAtRemoved = 0;
221
+ let tried = 0;
187
222
  const pool = app.pool ?? (await app.connect({ allowNone: true }));
188
223
  for (const c of old) {
189
- if ((await pool.revoke(c.capid, [r]).catch(() => [])).length > 0)
190
- revokedAtRemoved++;
224
+ for (const r of rs.filter((x) => c.relays.includes(x))) {
225
+ tried++;
226
+ if ((await pool.revoke(c.capid, [r]).catch(() => [])).length > 0)
227
+ revokedAtRemoved++;
228
+ }
191
229
  }
192
- if (revokedAtRemoved < old.length)
193
- app.warn(`couldn't revoke ${old.length - revokedAtRemoved} of your old caps at ${r}; they expire on their own`);
230
+ if (revokedAtRemoved < tried)
231
+ app.warn(`couldn't revoke ${tried - revokedAtRemoved} of your old caps at ${rs.join(", ")}; they expire on their own`);
194
232
  return { ...out, revokedAtRemoved };
195
233
  }
196
234
  export async function devices(app) {
@@ -397,12 +435,37 @@ export async function linkJoin(app, code, opts = {}) {
397
435
  throw new CliError("usage", "that is not a link code (p2p-link:…@relay)");
398
436
  }
399
437
  const { secret, relay } = parsed;
438
+ // A link code someone else gave connects to its relay before anyone confirms anything: the same
439
+ // private-address rule as an invite code's relay, unless it is one of the person's own relays
440
+ // (P2P_DEFAULT_RELAYS or config.json: no identity here yet) or they opted in.
441
+ const allowPrivate = opts.allowPrivateRelay || app.env.P2P_ALLOW_PRIVATE_RELAY === "1";
442
+ let own = [];
443
+ try {
444
+ own = defaultRelays(app.env, app.file);
445
+ }
446
+ catch {
447
+ // a broken config: no own relays
448
+ }
449
+ const guard = !allowPrivate && !isOwnRelay(relay, own);
450
+ if (guard && isPrivateRelayHost(new URL(relay).hostname)) {
451
+ throw new CliError("private_relay", privateRelayMessage("link code's relay", new URL(relay).hostname));
452
+ }
400
453
  const device = generateDeviceKeysV3("p2p:pending");
401
454
  const x = generateDeviceKeysV3("p2p:pending");
402
455
  const label = (opts.label ?? defaultLabel()).slice(0, 64);
403
456
  const req = createLinkRequest(secret, device, x.agreementPublicKey, label);
404
457
  const lid = linkId(secret);
405
- const conn = await openLinkConnection(relay, app.transport, app.tun.connectTimeoutMs, app.progress);
458
+ let conn;
459
+ try {
460
+ conn = await openLinkConnection(relay, app.transport, app.tun.connectTimeoutMs, app.progress, guard ? { lookup: privateGuardLookup() } : {});
461
+ }
462
+ catch (e) {
463
+ if (e.message?.includes(PRIVATE_RESOLVE_MARK)) {
464
+ const at = /\(([^()]+)\)\s*$/.exec(e.message)?.[1];
465
+ throw new CliError("private_relay", privateRelayMessage("link code's relay", new URL(relay).hostname, at ? { detail: `it resolves to ${at}` } : {}));
466
+ }
467
+ throw e;
468
+ }
406
469
  try {
407
470
  await linkPut(conn, lid, "req", JSON.stringify(req));
408
471
  }
@@ -413,7 +476,7 @@ export async function linkJoin(app, code, opts = {}) {
413
476
  return {
414
477
  compareCode: linkCompareCode(secret, device.did),
415
478
  did: device.did,
416
- wait: async () => {
479
+ wait: async (confirm) => {
417
480
  const deadline = Date.now() + Math.min(LINK_TTL_SEC * 1000, opts.maxWaitMs ?? Infinity);
418
481
  let frame;
419
482
  try {
@@ -435,8 +498,18 @@ export async function linkJoin(app, code, opts = {}) {
435
498
  }
436
499
  const opened = openLinkResponse(secret, device, x.agreementSecretKey, JSON.parse(frame));
437
500
  const userId = opened.doc.iss;
501
+ // Nothing is kept before the person says this is their identity: a code from someone else
502
+ // would make this device theirs.
503
+ if (confirm) {
504
+ const who = { userId, address: displayAddress(userId, opened.doc.name), fingerprint: displayFingerprint(userId), keyholder: !!opened.ik };
505
+ if (!(await confirm(who))) {
506
+ throw new CliError("link_declined", `not linked: nothing was kept on this device. The other device's identity (${who.address}) now lists a device that will never be used: if it is yours after all, remove it there with \`p2p devices revoke ${device.did}\``);
507
+ }
508
+ }
438
509
  const keys = newKeysDoc(userId, { ...device, userId }, opened.cert.jws, opened.ik);
439
510
  const self = { name: opened.doc.name, relays: opened.doc.relays, createdAt: Date.now() };
511
+ renewPersonToken(app.home, keys.spk);
512
+ app.identityMadeHere = true;
440
513
  await app.state.put("keys", keys);
441
514
  await app.state.put("self", self);
442
515
  app.setKeys(keys, self);
@@ -531,6 +604,8 @@ async function restoreInto(app, phrase, opts) {
531
604
  if (found === 0) {
532
605
  const name = opts.name ?? defaultName();
533
606
  const doc = createIdentityDoc(ik, { ver: 1, prev: null, name, relays, devices: [device.did], keyholders: [device.did], by: device.did, certs: [cert] });
607
+ renewPersonToken(app.home, keys.spk);
608
+ app.identityMadeHere = true;
534
609
  await app.state.put("keys", keys);
535
610
  await app.state.put("self", { ...self, name });
536
611
  app.setKeys(keys, { ...self, name });
@@ -553,6 +628,8 @@ async function restoreInto(app, phrase, opts) {
553
628
  const existing = await app.refreshIdentity(ik.userId, relays, { force: true, strict: true });
554
629
  if (!existing)
555
630
  throw new CliError("refresh_failed", "couldn't fit the relays' identity document");
631
+ renewPersonToken(app.home, keys.spk);
632
+ app.identityMadeHere = true;
556
633
  await app.state.put("keys", keys);
557
634
  await app.store.putDeviceCert({ userId: ik.userId, did: device.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
558
635
  await app.state.put("self", { ...self, name: existing.head.name, relays: existing.head.relays });
@@ -1,8 +1,42 @@
1
1
  import type { App } from "./app.js";
2
- import type { Env } from "./config.js";
2
+ import { type Env, type FileConfig } from "./config.js";
3
3
  import { type GraphTarget } from "./projects.js";
4
4
  /** Where to get Ix (and how p2p says it): never installed for the person. */
5
5
  export declare const IX_INSTALL_URL = "https://github.com/ix-infrastructure/Ix";
6
+ /**
7
+ * The command(s) that install Ix on this platform, from the Ix README, for the person to run in their
8
+ * own terminal: Peer2Peer prints them and never runs them (it doesn't run a downloaded script). Intel
9
+ * Macs have no pre-built Ix package, so Homebrew builds it.
10
+ */
11
+ export declare function ixInstallCommands(platform?: NodeJS.Platform, arch?: string): string[];
12
+ /** The install command(s) as one line (`&&` between steps; Windows has one). */
13
+ export declare function ixInstallLine(platform?: NodeJS.Platform, arch?: string): string;
14
+ /** What Ix adds, in a few lines, said when `p2p setup` recommends it. */
15
+ export declare const IX_PITCH: string[];
16
+ /** The person said no to Ix at `p2p setup` (FileConfig.ixDeclined): not asked again until `p2p setup --ix`. */
17
+ export declare function ixDeclined(file: Pick<FileConfig, "ixDeclined">): boolean;
18
+ /** Records the person's answer to the Ix offer (config.json `ixDeclined`); only `p2p setup`, at a terminal, writes it. */
19
+ export declare function setIxDeclined(home: string, declined: boolean): void;
20
+ /** CI set (anything but empty, 0 or false): never a prompt. */
21
+ export declare function ciEnv(env: Env): boolean;
22
+ /**
23
+ * Whether p2p recommends Ix here (`p2p setup --json`, `p2p extensions --json`, and the hint the front
24
+ * ends give their agent): the Ix CLI isn't found and the person hasn't said no. `install` is the
25
+ * command for the person to run; nothing is ever installed for them.
26
+ */
27
+ export interface IxAdvice {
28
+ /** The Ix CLI was found. */
29
+ installed: boolean;
30
+ /** The person said no at `p2p setup` (`p2p setup --ix` asks again). */
31
+ declined: boolean;
32
+ /** Ix isn't installed and the person hasn't said no. */
33
+ recommended: boolean;
34
+ /** The command that installs Ix on this platform, for the person to run themselves. */
35
+ install: string;
36
+ }
37
+ export declare function ixAdvice(env: Env, file: Pick<FileConfig, "ixDeclined">, o?: {
38
+ reoffer?: boolean;
39
+ }): IxAdvice;
6
40
  /**
7
41
  * `name` resolved to an absolute path through PATH's absolute entries (the same rule as ext-ix's
8
42
  * which.ts: on Windows the current directory is searched before PATH, so a cloned repository's
@@ -41,6 +75,14 @@ export declare function extIxInstalled(env: Env): boolean;
41
75
  export interface SetupIx {
42
76
  /** The Ix CLI was found (its absolute path is local only, never sent anywhere). */
43
77
  found: boolean;
78
+ /** The same as `found` (IxAdvice's name). */
79
+ installed: boolean;
80
+ /** Ix isn't installed and the person hasn't said no: p2p recommends it (it never installs it). */
81
+ recommended: boolean;
82
+ /** The person said no to Ix at an earlier `p2p setup` (`--ix` asks again). */
83
+ declined?: true;
84
+ /** The command that installs Ix on this platform, for the person to run themselves (when it isn't installed). */
85
+ install?: string;
44
86
  /** The `ix` extension is enabled now (by this setup, or already). */
45
87
  enabled: boolean;
46
88
  /** This setup turned it on (a new install, Ix present, ext-ix installed, the person running it). */
@@ -49,19 +91,29 @@ export interface SetupIx {
49
91
  hint?: string;
50
92
  }
51
93
  /**
52
- * Ix on by default, for `p2p setup`. A new install (`created`) gets the `ix` extension enabled when
53
- * the Ix CLI and ext-ix are both there and the person agrees: their front end's token (the Claude
54
- * mod's typed `/peers setup`), or, outside any agent's session (its environment or a Claude Code or
55
- * Codex ancestor), their "yes" typed on the controlling terminal, as for every other person-only
56
- * action (projects.ts). Otherwise nothing changes: an existing install is never switched silently
57
- * (it gets the one-time notice, ixNotice), an agent never enables an extension, and
58
- * P2P_EXTENSIONS, when set, decides alone.
94
+ * What to do about Ix when it isn't installed: the person runs the command themselves; read by an
95
+ * agent (not the person), it says to ask the user instead, since installing is theirs alone.
96
+ */
97
+ export declare function ixInstallHint(line: string, person: boolean): string;
98
+ /**
99
+ * Ix for `p2p setup`: optional and recommended, never installed. Without the Ix CLI it says what to
100
+ * run (`recommended`, `install`), unless the person said no before (`--ix`, `reoffer`, asks again).
101
+ * With it, a new install (`created`; or any install, with `reoffer`) gets the `ix` extension enabled
102
+ * when ext-ix is there too and the person agrees: their front end's token (the Claude mod's typed
103
+ * `/peers setup`), or, outside any agent's session (its environment or a Claude Code or Codex
104
+ * ancestor), their "yes" typed on the controlling terminal, as for every other person-only action
105
+ * (projects.ts). Otherwise nothing changes: an existing install is never switched silently (it gets
106
+ * the one-time notice, ixNotice), an agent never enables an extension, and P2P_EXTENSIONS, when
107
+ * set, decides alone.
59
108
  */
60
- export declare function setupIx(app: App, created: boolean): Promise<SetupIx>;
109
+ export declare function setupIx(app: App, created: boolean, o?: {
110
+ reoffer?: boolean;
111
+ }): Promise<SetupIx>;
61
112
  /**
62
113
  * The one-time notice for an existing install (shown once per device, to the person at a terminal):
63
- * new installs turn the Ix extension on when Ix is present; this one wasn't changed. Undefined when
64
- * it was shown already, Ix isn't installed, or the extension is on (or P2P_EXTENSIONS decides).
114
+ * new installs offer to turn the Ix extension on when Ix is present; this one wasn't changed.
115
+ * Undefined when it was shown already, Ix isn't installed, the person said no to Ix, or the
116
+ * extension is on (or P2P_EXTENSIONS decides).
65
117
  */
66
118
  export declare function ixNotice(app: App): Promise<string | undefined>;
67
119
  /**
package/dist/ix-local.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // Copyright 2026 Ix Infrastructure Inc.
2
2
  //
3
- // Ix on by default (epic #41 piece 1): finding the local Ix CLI, asking it about this machine
4
- // (version, backend, whether a checkout is mapped), and turning the `ix` extension on for a new
5
- // install when Ix is there. The CLI never imports an extension (scripts/check-boundaries.mjs), so
3
+ // Ix: optional and recommended, never installed for the person (epic #41 piece 1): finding the
4
+ // local Ix CLI, asking it about this machine (version, backend, whether a checkout is mapped),
5
+ // recommending it when it isn't there (the person installs it, or says no and isn't asked again),
6
+ // and turning the `ix` extension on for a new install, with the person's yes, when Ix is there. The CLI never imports an extension (scripts/check-boundaries.mjs), so
6
7
  // it runs `ix` itself here, the same way ext-ix does: by absolute path from PATH's absolute
7
8
  // entries (never a binary planted in the repository), by argv with no shell, bounded, with an
8
9
  // allowlisted environment pinned to the graph target (projects.ts), never the caller's IX_*
@@ -11,10 +12,51 @@ import { execFile } from "node:child_process";
11
12
  import { accessSync, constants, statSync } from "node:fs";
12
13
  import { delimiter, isAbsolute, join } from "node:path";
13
14
  import { sanitizePeerText } from "@peer2peer/core/v3";
15
+ import { setFileConfigField } from "./config.js";
14
16
  import { enabledNamespaces, extensionDirs, extensionPackageName, resolveIn, setExtensionEnabled } from "./extensions.js";
15
17
  import { personHere } from "./projects.js";
16
18
  /** Where to get Ix (and how p2p says it): never installed for the person. */
17
19
  export const IX_INSTALL_URL = "https://github.com/ix-infrastructure/Ix";
20
+ /**
21
+ * The command(s) that install Ix on this platform, from the Ix README, for the person to run in their
22
+ * own terminal: Peer2Peer prints them and never runs them (it doesn't run a downloaded script). Intel
23
+ * Macs have no pre-built Ix package, so Homebrew builds it.
24
+ */
25
+ export function ixInstallCommands(platform = process.platform, arch = process.arch) {
26
+ if (platform === "win32")
27
+ return ["irm https://ix-infra.com/install.ps1 | iex"];
28
+ if (platform === "darwin" && arch === "x64")
29
+ return ["brew tap ix-infrastructure/ix https://github.com/ix-infrastructure/Ix", "brew install ix"];
30
+ return ["curl -fsSL https://ix-infra.com/install.sh | sh"];
31
+ }
32
+ /** The install command(s) as one line (`&&` between steps; Windows has one). */
33
+ export function ixInstallLine(platform = process.platform, arch = process.arch) {
34
+ return ixInstallCommands(platform, arch).join(" && ");
35
+ }
36
+ /** What Ix adds, in a few lines, said when `p2p setup` recommends it. */
37
+ export const IX_PITCH = [
38
+ "Ix (optional, recommended) maps your code into a local graph. With it, Peer2Peer can flag when a peer's",
39
+ "session works on code that overlaps yours, show a change's blast radius, and keep your sessions' context",
40
+ "as local graph memory. Everything stays on this machine. Peer2Peer works without it and never installs it for you.",
41
+ ];
42
+ /** The person said no to Ix at `p2p setup` (FileConfig.ixDeclined): not asked again until `p2p setup --ix`. */
43
+ export function ixDeclined(file) {
44
+ return file.ixDeclined === true;
45
+ }
46
+ /** Records the person's answer to the Ix offer (config.json `ixDeclined`); only `p2p setup`, at a terminal, writes it. */
47
+ export function setIxDeclined(home, declined) {
48
+ setFileConfigField(home, "ixDeclined", declined);
49
+ }
50
+ /** CI set (anything but empty, 0 or false): never a prompt. */
51
+ export function ciEnv(env) {
52
+ const v = env.CI?.trim().toLowerCase();
53
+ return Boolean(v) && v !== "0" && v !== "false";
54
+ }
55
+ export function ixAdvice(env, file, o = {}) {
56
+ const installed = ixBinary(env) !== undefined;
57
+ const declined = ixDeclined(file) && o.reoffer !== true;
58
+ return { installed, declined, recommended: !installed && !declined, install: ixInstallLine() };
59
+ }
18
60
  /**
19
61
  * `name` resolved to an absolute path through PATH's absolute entries (the same rule as ext-ix's
20
62
  * which.ts: on Windows the current directory is searched before PATH, so a cloned repository's
@@ -121,45 +163,60 @@ export function extIxInstalled(env) {
121
163
  }
122
164
  /** P2P_EXTENSIONS decides which extensions load (anything but unset or `config`, which defers to config.json). */
123
165
  const envDecides = (env) => env.P2P_EXTENSIONS !== undefined && env.P2P_EXTENSIONS.trim() !== "config";
124
- const INSTALL_IX = `Ix (the local code graph peers' agents point into) isn't installed: get it from ${IX_INSTALL_URL}, then run \`p2p extensions enable ix\` (Peer2Peer works without it)`;
166
+ /**
167
+ * What to do about Ix when it isn't installed: the person runs the command themselves; read by an
168
+ * agent (not the person), it says to ask the user instead, since installing is theirs alone.
169
+ */
170
+ export function ixInstallHint(line, person) {
171
+ const what = "Ix (optional, recommended: a local code graph for overlap, blast radius and graph memory) isn't installed";
172
+ return person
173
+ ? `${what}. Peer2Peer never installs it for you: to add it, run \`${line}\` yourself (or see ${IX_INSTALL_URL}), then \`p2p setup --ix\``
174
+ : `${what}. Installing it is your user's decision: don't install it yourself; you may ask your user whether they want it, and they run \`${line}\` in their own terminal, then \`p2p setup --ix\``;
175
+ }
176
+ const DECLINED_IX = "Ix isn't installed (you said no; `p2p setup --ix` offers it again). Peer2Peer works without it";
125
177
  const INSTALL_EXT = "Ix is installed, but the Ix extension isn't: `npm i -g @peer2peer/ext-ix`, then `p2p extensions enable ix` (the Claude Code mod ships it: `/peers setup` there turns it on)";
126
178
  /**
127
- * Ix on by default, for `p2p setup`. A new install (`created`) gets the `ix` extension enabled when
128
- * the Ix CLI and ext-ix are both there and the person agrees: their front end's token (the Claude
129
- * mod's typed `/peers setup`), or, outside any agent's session (its environment or a Claude Code or
130
- * Codex ancestor), their "yes" typed on the controlling terminal, as for every other person-only
131
- * action (projects.ts). Otherwise nothing changes: an existing install is never switched silently
132
- * (it gets the one-time notice, ixNotice), an agent never enables an extension, and
133
- * P2P_EXTENSIONS, when set, decides alone.
179
+ * Ix for `p2p setup`: optional and recommended, never installed. Without the Ix CLI it says what to
180
+ * run (`recommended`, `install`), unless the person said no before (`--ix`, `reoffer`, asks again).
181
+ * With it, a new install (`created`; or any install, with `reoffer`) gets the `ix` extension enabled
182
+ * when ext-ix is there too and the person agrees: their front end's token (the Claude mod's typed
183
+ * `/peers setup`), or, outside any agent's session (its environment or a Claude Code or Codex
184
+ * ancestor), their "yes" typed on the controlling terminal, as for every other person-only action
185
+ * (projects.ts). Otherwise nothing changes: an existing install is never switched silently (it gets
186
+ * the one-time notice, ixNotice), an agent never enables an extension, and P2P_EXTENSIONS, when
187
+ * set, decides alone.
134
188
  */
135
- export async function setupIx(app, created) {
136
- const found = ixBinary(app.env) !== undefined;
189
+ export async function setupIx(app, created, o = {}) {
190
+ const adv = ixAdvice(app.env, app.file, o);
191
+ const found = adv.installed;
192
+ const base = { found, installed: found, recommended: adv.recommended, ...(adv.declined ? { declined: true } : {}) };
137
193
  const { enabled } = enabledNamespaces(app.env, app.file);
138
194
  if (enabled.includes("ix"))
139
- return { found, enabled: true };
195
+ return { ...base, enabled: true };
140
196
  if (!found)
141
- return { found, enabled: false, hint: INSTALL_IX };
197
+ return { ...base, enabled: false, install: adv.install, hint: adv.declined ? DECLINED_IX : ixInstallHint(adv.install, personHere(app)) };
142
198
  if (!extIxInstalled(app.env))
143
- return { found, enabled: false, hint: INSTALL_EXT };
199
+ return { ...base, enabled: false, hint: INSTALL_EXT };
144
200
  const chose = Array.isArray(app.file.extensions);
145
- if (!created || chose || envDecides(app.env) || !personHere(app)) {
146
- return { found, enabled: false, hint: "Ix is installed: `p2p extensions enable ix` lets your sessions share Ix context (notes, subgraph references, blast radius, footprints)" };
201
+ if ((!created && o.reoffer !== true) || chose || envDecides(app.env) || !personHere(app)) {
202
+ return { ...base, enabled: false, hint: "Ix is installed: `p2p extensions enable ix` lets your sessions share Ix context (notes, subgraph references, blast radius, footprints)" };
147
203
  }
148
204
  if (app.front !== true) {
149
205
  const yes = app.confirmTty ? await app.confirmTty("Ix is installed. Turn on the Ix extension, so your sessions can share Ix context with the people you share a project with? (Ix calls stay on this machine.)").catch(() => false) : false;
150
206
  if (!yes)
151
- return { found, enabled: false, hint: "Ix is installed: `p2p extensions enable ix` lets your sessions share Ix context (notes, subgraph references, blast radius, footprints)" };
207
+ return { ...base, enabled: false, hint: "Ix is installed: `p2p extensions enable ix` lets your sessions share Ix context (notes, subgraph references, blast radius, footprints)" };
152
208
  }
153
209
  setExtensionEnabled(app.home, "ix", true);
154
- return { found, enabled: true, enabledNow: true };
210
+ return { ...base, enabled: true, enabledNow: true };
155
211
  }
156
212
  /**
157
213
  * The one-time notice for an existing install (shown once per device, to the person at a terminal):
158
- * new installs turn the Ix extension on when Ix is present; this one wasn't changed. Undefined when
159
- * it was shown already, Ix isn't installed, or the extension is on (or P2P_EXTENSIONS decides).
214
+ * new installs offer to turn the Ix extension on when Ix is present; this one wasn't changed.
215
+ * Undefined when it was shown already, Ix isn't installed, the person said no to Ix, or the
216
+ * extension is on (or P2P_EXTENSIONS decides).
160
217
  */
161
218
  export async function ixNotice(app) {
162
- if (envDecides(app.env))
219
+ if (envDecides(app.env) || ixDeclined(app.file))
163
220
  return undefined;
164
221
  if (enabledNamespaces(app.env, app.file).enabled.includes("ix"))
165
222
  return undefined;
@@ -171,7 +228,7 @@ export async function ixNotice(app) {
171
228
  if (!shown)
172
229
  return undefined;
173
230
  const how = extIxInstalled(app.env) ? "`p2p extensions enable ix`" : "`npm i -g @peer2peer/ext-ix`, then `p2p extensions enable ix`";
174
- return `Ix: new installs now turn the Ix extension on when Ix is installed, so sessions can share Ix context. Yours wasn't changed; to turn it on, run ${how}. Ix calls stay on this machine (\`p2p doctor\` shows each project's graph: local only)`;
231
+ return `Ix: \`p2p setup\` now offers to turn the Ix extension on when Ix is installed, so sessions can share Ix context. Yours wasn't changed; to turn it on, run ${how}. Ix calls stay on this machine (\`p2p doctor\` shows each project's graph: local only)`;
175
232
  }
176
233
  /**
177
234
  * Which `ix note` / `ix session` this Ix has, from `ix --help` (graph memory, graph-memory.ts):
package/dist/pretty.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Style } from "./prompt/picker.js";
2
2
  import type { CircleSummary } from "./circle-ops.js";
3
3
  import type { CodeRow, InviteCodeResult } from "./codes.js";
4
- import type { DoctorResult } from "./doctor.js";
4
+ import { type DoctorResult } from "./doctor.js";
5
5
  import type { PeerRow } from "./sessions.js";
6
6
  import type { FriendRow } from "./social.js";
7
7
  export interface Pretty {
@@ -43,6 +43,8 @@ export declare function prettyCodes(rows: CodeRow[], p: Pretty): string;
43
43
  /** Whole days left, rounded up: a 7-day code a few seconds old still says "7 days". */
44
44
  export declare function daysLeft(exp: number, now: number): string;
45
45
  export declare function prettyInvite(r: InviteCodeResult, p: Pretty): string;
46
+ /** A "Where your data goes" row is cut only past this many columns (a graph row: name, endpoint, reason, note). */
47
+ export declare const DATA_FLOW_WIDTH = 2000;
46
48
  export declare function prettyDoctor(r: DoctorResult, plain: string, p: Pretty): string;
47
49
  export declare function prettyRelays(r: {
48
50
  relays: string[];
package/dist/pretty.js CHANGED
@@ -11,6 +11,8 @@
11
11
  // NO_COLOR, TERM=dumb (and FORCE_COLOR) decide `color` (tui/terminal.ts colorWanted).
12
12
  import { COLOR, PLAIN } from "./prompt/picker.js";
13
13
  import { cell, clean, displayWidth } from "./tui/sanitize.js";
14
+ import { shortCode } from "./format.js";
15
+ import { DATA_FLOW_HEADING } from "./doctor.js";
14
16
  const styleOf = (p) => (p.color ? COLOR : PLAIN);
15
17
  const nowOf = (p) => p.now ?? Date.now() / 1000;
16
18
  /** Everything a terminal could act on, except the SGR (colour) sequences this module writes. */
@@ -143,7 +145,7 @@ export function prettyCodes(rows, p) {
143
145
  return [
144
146
  heading(`Invites (${rows.length})`, st),
145
147
  table(["CODE", "FOR", "JOINS", "STATUS"], rows.map((r) => [
146
- t(r.status === "open" || r.status === "taken" ? r.code : r.code.replace(/[^/]*$/, (c) => `${c.slice(0, 4)}…`), 44, st.dim),
148
+ t((r.status === "open" || r.status === "taken") && !r.redacted ? r.code : shortCode(r.code), 44, st.dim),
147
149
  t(r.to ? clean(r.to.address) : (r.label ?? "anyone"), 28),
148
150
  t(r.circles.length ? r.circles.map((c) => clean(c.name)).join(", ") : "friend only", 32),
149
151
  status(r),
@@ -179,13 +181,19 @@ export function prettyInvite(r, p) {
179
181
  st.dim("Who joined: p2p invites · undo: p2p remove <user> · cancel: p2p invites revoke <code>"),
180
182
  ].join("\n");
181
183
  }
184
+ /** A "Where your data goes" row is cut only past this many columns (a graph row: name, endpoint, reason, note). */
185
+ export const DATA_FLOW_WIDTH = 2000;
182
186
  export function prettyDoctor(r, plain, p) {
183
187
  const st = styleOf(p);
188
+ let flow = false;
184
189
  return plain
185
190
  .split("\n")
186
191
  .map((l, i) => {
187
- const s = cell(l, 400);
188
- if (i === 0)
192
+ // "Where your data goes" rows (a graph target with its reason) can be long: wider, not cut short.
193
+ if (l.startsWith(DATA_FLOW_HEADING))
194
+ flow = true;
195
+ const s = cell(l, flow ? DATA_FLOW_WIDTH : 400);
196
+ if (i === 0 || s.startsWith(DATA_FLOW_HEADING))
189
197
  return st.bold(s);
190
198
  if (s.startsWith("✓"))
191
199
  return st.green("✓") + s.slice(1);