@peer2peer/cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
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
7
+ // it runs `ix` itself here, the same way ext-ix does: by absolute path from PATH's absolute
8
+ // entries (never a binary planted in the repository), by argv with no shell, bounded, with an
9
+ // allowlisted environment pinned to the graph target (projects.ts), never the caller's IX_*
10
+ // cloud settings. Nothing is ever installed: the person is told how.
11
+ import { execFile } from "node:child_process";
12
+ import { accessSync, constants, statSync } from "node:fs";
13
+ import { delimiter, isAbsolute, join } from "node:path";
14
+ import { sanitizePeerText } from "@peer2peer/core/v3";
15
+ import { setFileConfigField } from "./config.js";
16
+ import { enabledNamespaces, extensionDirs, extensionPackageName, resolveIn, setExtensionEnabled } from "./extensions.js";
17
+ import { personHere } from "./projects.js";
18
+ /** Where to get Ix (and how p2p says it): never installed for the person. */
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
+ }
60
+ /**
61
+ * `name` resolved to an absolute path through PATH's absolute entries (the same rule as ext-ix's
62
+ * which.ts: on Windows the current directory is searched before PATH, so a cloned repository's
63
+ * `ix.exe` would otherwise run). An absolute name is used as given when it runs.
64
+ */
65
+ export function whichAbsolute(name, env = process.env, platform = process.platform) {
66
+ const runnable = (p) => {
67
+ try {
68
+ if (!statSync(p).isFile())
69
+ return false;
70
+ if (platform !== "win32")
71
+ accessSync(p, constants.X_OK);
72
+ return true;
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ };
78
+ if (isAbsolute(name))
79
+ return runnable(name) ? name : undefined;
80
+ if (/[\\/]/.test(name))
81
+ return undefined;
82
+ const win = platform === "win32";
83
+ const sep = win ? ";" : delimiter;
84
+ const path = env.PATH ?? env.Path ?? "";
85
+ const exts = win ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
86
+ const hasExt = win && exts.some((e) => name.toLowerCase().endsWith(e.toLowerCase()));
87
+ for (const dir of path.split(sep)) {
88
+ const d = dir.trim().replace(/^"|"$/g, "");
89
+ if (d === "" || !isAbsolute(d))
90
+ continue;
91
+ for (const ext of hasExt ? [""] : exts) {
92
+ const p = join(d, name + ext);
93
+ if (runnable(p))
94
+ return p;
95
+ }
96
+ }
97
+ return undefined;
98
+ }
99
+ /** The Ix CLI: IX_BIN when it is an absolute path that runs (or a bare name found on PATH), else `ix` on PATH. */
100
+ export function ixBinary(env) {
101
+ const name = env.IX_BIN?.trim() || "ix";
102
+ return whichAbsolute(name, env);
103
+ }
104
+ /** What an `ix` child may see of the environment (besides the pinned IX_ENDPOINT): no IX_* cloud setting, no P2P_*, no loader or proxy variables. */
105
+ const IX_CHILD_ALLOW = ["PATH", "PATHEXT", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA", "LOCALAPPDATA", "SYSTEMROOT", "WINDIR", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "TZ", "TERM", "NO_COLOR", "IX_HOME", "IX_TOKEN"];
106
+ /**
107
+ * The environment `ix` runs with: IX_CHILD_ALLOW from `env`, then IX_ENDPOINT from the target
108
+ * (never the caller's), no background `ix map` from a reader (Ix Pro routes a map to the cloud
109
+ * whenever an org session is active), no update check. Names compare case-insensitively, as on
110
+ * Windows. The same rule as ext-ix's ixEnv (ix.ts).
111
+ */
112
+ export function ixChildEnv(env, target) {
113
+ const allow = new Set(IX_CHILD_ALLOW);
114
+ const out = {};
115
+ for (const [k, v] of Object.entries(env))
116
+ if (typeof v === "string" && allow.has(k.toUpperCase()))
117
+ out[k] = k.toUpperCase() === "PATH" ? absolutePath(v) : v;
118
+ out.IX_ENDPOINT = target.endpoint;
119
+ out.IX_MAP_BACKGROUND_REFRESH = "0";
120
+ out.IX_NO_UPDATE_CHECK = "1";
121
+ return out;
122
+ }
123
+ /** PATH with its relative and empty entries dropped (they mean the current directory: a repository's own `node`). */
124
+ export function absolutePath(v, platform = process.platform) {
125
+ const sep = platform === "win32" ? ";" : delimiter;
126
+ return v
127
+ .split(sep)
128
+ .filter((d) => {
129
+ const x = d.trim().replace(/^"|"$/g, "");
130
+ return x !== "" && (platform === "win32" ? /^(?:[A-Za-z]:[\\/]|\\\\)/.test(x) : isAbsolute(x));
131
+ })
132
+ .join(sep);
133
+ }
134
+ /** One bounded `ix` call (argv, no shell, SIGKILL on timeout, output capped). Read-only commands only. */
135
+ export function runIx(bin, argv, o) {
136
+ return new Promise((resolve) => {
137
+ execFile(bin, [...argv], { cwd: o.cwd, env: ixChildEnv(o.env, o.target), timeout: o.timeoutMs, killSignal: "SIGKILL", maxBuffer: 1 << 20, windowsHide: true }, (err, stdout, stderr) => {
138
+ const e = err;
139
+ resolve({ code: e ? (typeof e.code === "number" ? e.code : 1) : 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), ...(e?.killed ? { timedOut: true } : {}) });
140
+ });
141
+ });
142
+ }
143
+ /** `ix --version`'s first line, sanitized; undefined when it fails. */
144
+ export async function ixVersion(bin, env, target, timeoutMs) {
145
+ const r = await runIx(bin, ["--version"], { env, target, timeoutMs });
146
+ if (r.code !== 0)
147
+ return undefined;
148
+ const v = sanitizePeerText(r.stdout.split("\n")[0]?.trim() ?? "", 64);
149
+ return v || undefined;
150
+ }
151
+ /** Whether @peer2peer/ext-ix is where this p2p loads extensions from (resolved, never imported). */
152
+ export function extIxInstalled(env) {
153
+ for (const dir of extensionDirs(env, import.meta.url)) {
154
+ try {
155
+ if (resolveIn(dir, extensionPackageName("ix")))
156
+ return true;
157
+ }
158
+ catch {
159
+ // a malformed copy is not an installed one
160
+ }
161
+ }
162
+ return false;
163
+ }
164
+ /** P2P_EXTENSIONS decides which extensions load (anything but unset or `config`, which defers to config.json). */
165
+ const envDecides = (env) => env.P2P_EXTENSIONS !== undefined && env.P2P_EXTENSIONS.trim() !== "config";
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";
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)";
178
+ /**
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.
188
+ */
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 } : {}) };
193
+ const { enabled } = enabledNamespaces(app.env, app.file);
194
+ if (enabled.includes("ix"))
195
+ return { ...base, enabled: true };
196
+ if (!found)
197
+ return { ...base, enabled: false, install: adv.install, hint: adv.declined ? DECLINED_IX : ixInstallHint(adv.install, personHere(app)) };
198
+ if (!extIxInstalled(app.env))
199
+ return { ...base, enabled: false, hint: INSTALL_EXT };
200
+ const chose = Array.isArray(app.file.extensions);
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)" };
203
+ }
204
+ if (app.front !== true) {
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;
206
+ if (!yes)
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)" };
208
+ }
209
+ setExtensionEnabled(app.home, "ix", true);
210
+ return { ...base, enabled: true, enabledNow: true };
211
+ }
212
+ /**
213
+ * The one-time notice for an existing install (shown once per device, to the person at a terminal):
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).
217
+ */
218
+ export async function ixNotice(app) {
219
+ if (envDecides(app.env) || ixDeclined(app.file))
220
+ return undefined;
221
+ if (enabledNamespaces(app.env, app.file).enabled.includes("ix"))
222
+ return undefined;
223
+ if ((await app.state.get("ixNotice"))?.at !== undefined)
224
+ return undefined;
225
+ if (!ixBinary(app.env))
226
+ return undefined;
227
+ const shown = await app.state.update("ixNotice", (cur) => (cur?.at !== undefined ? { result: false } : { next: { at: Date.now() }, result: true }));
228
+ if (!shown)
229
+ return undefined;
230
+ const how = extIxInstalled(app.env) ? "`p2p extensions enable ix`" : "`npm i -g @peer2peer/ext-ix`, then `p2p extensions enable ix`";
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)`;
232
+ }
233
+ /**
234
+ * Which `ix note` / `ix session` this Ix has, from `ix --help` (graph memory, graph-memory.ts):
235
+ * "oss" (the local backend: Ix after 0.13.0, ix-infrastructure/Ix#916, with Ix Pro not loaded: its
236
+ * help then lists them under "Memory:"), "pro" (Ix Pro loaded: its "Pro:" section; its note and
237
+ * session go to the cloud org), "none" (neither). The same reading as ext-ix's parseMemorySupport
238
+ * (ix.ts), which decides; this one only reports (`p2p doctor`).
239
+ */
240
+ export function parseIxMemorySupport(help) {
241
+ const lines = help.replace(/\u001b\[[0-9;]*m/g, "").split(/\r?\n/);
242
+ if (lines.some((l) => /^Pro:\s*$/.test(l)))
243
+ return "pro";
244
+ const at = lines.findIndex((l) => /^Memory:\s*$/.test(l));
245
+ if (at < 0)
246
+ return "none";
247
+ const section = [];
248
+ for (const l of lines.slice(at + 1)) {
249
+ if (!/^\s+\S/.test(l))
250
+ break;
251
+ section.push(l);
252
+ }
253
+ const has = (name) => section.some((l) => new RegExp(`^\\s+${name}\\s`).test(l));
254
+ return has("note") && has("session") ? "oss" : "none";
255
+ }
256
+ /** `ix --help` read as parseIxMemorySupport; undefined when it doesn't answer. */
257
+ export async function ixMemorySupport(bin, env, target, timeoutMs) {
258
+ const r = await runIx(bin, ["--help"], { env, target, timeoutMs });
259
+ return r.code === 0 ? parseIxMemorySupport(r.stdout) : undefined;
260
+ }
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,7 @@
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 { DATA_FLOW_HEADING } from "./doctor.js";
14
15
  const styleOf = (p) => (p.color ? COLOR : PLAIN);
15
16
  const nowOf = (p) => p.now ?? Date.now() / 1000;
16
17
  /** Everything a terminal could act on, except the SGR (colour) sequences this module writes. */
@@ -179,13 +180,19 @@ export function prettyInvite(r, p) {
179
180
  st.dim("Who joined: p2p invites · undo: p2p remove <user> · cancel: p2p invites revoke <code>"),
180
181
  ].join("\n");
181
182
  }
183
+ /** A "Where your data goes" row is cut only past this many columns (a graph row: name, endpoint, reason, note). */
184
+ export const DATA_FLOW_WIDTH = 2000;
182
185
  export function prettyDoctor(r, plain, p) {
183
186
  const st = styleOf(p);
187
+ let flow = false;
184
188
  return plain
185
189
  .split("\n")
186
190
  .map((l, i) => {
187
- const s = cell(l, 400);
188
- if (i === 0)
191
+ // "Where your data goes" rows (a graph target with its reason) can be long: wider, not cut short.
192
+ if (l.startsWith(DATA_FLOW_HEADING))
193
+ flow = true;
194
+ const s = cell(l, flow ? DATA_FLOW_WIDTH : 400);
195
+ if (i === 0 || s.startsWith(DATA_FLOW_HEADING))
189
196
  return st.bold(s);
190
197
  if (s.startsWith("✓"))
191
198
  return st.green("✓") + s.slice(1);