@peer2peer/cli 0.1.0 → 0.1.1

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.
@@ -1,5 +1,6 @@
1
1
  import { type DisplayProfile, type ProofFetchers } from "@peer2peer/core/v3";
2
2
  import { type App } from "./app.js";
3
+ import { type SetupIx } from "./ix-local.js";
3
4
  export interface InitResult {
4
5
  userId: string;
5
6
  address: string;
@@ -34,6 +35,8 @@ export interface SetupResult {
34
35
  file?: string;
35
36
  phrase?: string;
36
37
  };
38
+ /** Ix on by default (ix-local.ts setupIx): found, enabled, and what to do when it isn't. */
39
+ ix?: SetupIx;
37
40
  }
38
41
  export declare const BACKUP_FILE_NAME = "backup-phrase.txt";
39
42
  export declare function setup(app: App, opts: {
package/dist/identity.js CHANGED
@@ -13,6 +13,7 @@ import { fetchTips, linkGet, linkPut, openLinkConnection, relayCode, sleep } fro
13
13
  import { exportAll, sendSync, verifiedIssuedCap } from "./sync.js";
14
14
  import { receiving } from "./inbound.js";
15
15
  import { recordJoin, resignJoin } from "./circle-ops.js";
16
+ import { setupIx } from "./ix-local.js";
16
17
  export async function init(app, opts) {
17
18
  if (await app.load(false))
18
19
  throw new CliError("already_initialized", `${app.home} already holds an identity (${app.userId})`);
@@ -63,6 +64,13 @@ export async function setup(app, opts) {
63
64
  created,
64
65
  ...(pub ?? {}),
65
66
  };
67
+ try {
68
+ out.ix = await setupIx(app, created);
69
+ }
70
+ catch (e) {
71
+ // Never fails a setup: Ix is optional.
72
+ out.ix = { found: false, enabled: false, hint: `couldn't check for Ix: ${sanitizePeerText(e.message, 200)}` };
73
+ }
66
74
  if (opts.backup === "file") {
67
75
  const path = opts.backupFile ?? join(app.home, BACKUP_FILE_NAME);
68
76
  const { phrase } = await backupShow(app);
package/dist/inbound.js CHANGED
@@ -14,6 +14,7 @@ export { isTransient } from "./transient.js";
14
14
  import { decodeEnvelopeV3, jwsHash, P2PError, sanitizePeerText, verifyIncomingV3 } from "@peer2peer/core/v3";
15
15
  import { answerDeferredWants, onCircleEnvelope } from "./circle-ops.js";
16
16
  import { onSessionEnvelope } from "./sessions.js";
17
+ import { recordEvents } from "./history.js";
17
18
  import { onReceipt } from "./receipts.js";
18
19
  import { onUnknownKind } from "./unknown-kinds.js";
19
20
  import { onContact, onUnfriendKind } from "./social.js";
@@ -174,7 +175,9 @@ async function processClaimed(app, env, relay, token) {
174
175
  await r.releaseReplay?.({ uncount: true }).catch(() => undefined);
175
176
  return "keep";
176
177
  }
177
- await app.state.addEvents(events);
178
+ const added = await app.state.addEvents(events);
179
+ // Message history (history.ts): the messages just logged, once each (a redelivery adds none).
180
+ await recordEvents(app, added);
178
181
  }
179
182
  catch (e) {
180
183
  const what = `applying ${sanitizePeerText(r.envelope.kind, 40)} from ${r.envelope.from} failed: ${sanitizePeerText(e.message, 300)}`;
@@ -0,0 +1,76 @@
1
+ import type { App } from "./app.js";
2
+ import type { Env } from "./config.js";
3
+ import { type GraphTarget } from "./projects.js";
4
+ /** Where to get Ix (and how p2p says it): never installed for the person. */
5
+ export declare const IX_INSTALL_URL = "https://github.com/ix-infrastructure/Ix";
6
+ /**
7
+ * `name` resolved to an absolute path through PATH's absolute entries (the same rule as ext-ix's
8
+ * which.ts: on Windows the current directory is searched before PATH, so a cloned repository's
9
+ * `ix.exe` would otherwise run). An absolute name is used as given when it runs.
10
+ */
11
+ export declare function whichAbsolute(name: string, env?: Record<string, string | undefined>, platform?: NodeJS.Platform): string | undefined;
12
+ /** The Ix CLI: IX_BIN when it is an absolute path that runs (or a bare name found on PATH), else `ix` on PATH. */
13
+ export declare function ixBinary(env: Env): string | undefined;
14
+ /**
15
+ * The environment `ix` runs with: IX_CHILD_ALLOW from `env`, then IX_ENDPOINT from the target
16
+ * (never the caller's), no background `ix map` from a reader (Ix Pro routes a map to the cloud
17
+ * whenever an org session is active), no update check. Names compare case-insensitively, as on
18
+ * Windows. The same rule as ext-ix's ixEnv (ix.ts).
19
+ */
20
+ export declare function ixChildEnv(env: Record<string, string | undefined>, target: Pick<GraphTarget, "endpoint">): NodeJS.ProcessEnv;
21
+ /** PATH with its relative and empty entries dropped (they mean the current directory: a repository's own `node`). */
22
+ export declare function absolutePath(v: string, platform?: NodeJS.Platform): string;
23
+ export interface IxRun {
24
+ code: number;
25
+ stdout: string;
26
+ stderr: string;
27
+ timedOut?: true;
28
+ }
29
+ /** One bounded `ix` call (argv, no shell, SIGKILL on timeout, output capped). Read-only commands only. */
30
+ export declare function runIx(bin: string, argv: readonly string[], o: {
31
+ env: Record<string, string | undefined>;
32
+ target: Pick<GraphTarget, "endpoint">;
33
+ cwd?: string;
34
+ timeoutMs: number;
35
+ }): Promise<IxRun>;
36
+ /** `ix --version`'s first line, sanitized; undefined when it fails. */
37
+ export declare function ixVersion(bin: string, env: Env, target: Pick<GraphTarget, "endpoint">, timeoutMs: number): Promise<string | undefined>;
38
+ /** Whether @peer2peer/ext-ix is where this p2p loads extensions from (resolved, never imported). */
39
+ export declare function extIxInstalled(env: Env): boolean;
40
+ /** What `p2p setup` did about Ix (SetupResult.ix). */
41
+ export interface SetupIx {
42
+ /** The Ix CLI was found (its absolute path is local only, never sent anywhere). */
43
+ found: boolean;
44
+ /** The `ix` extension is enabled now (by this setup, or already). */
45
+ enabled: boolean;
46
+ /** This setup turned it on (a new install, Ix present, ext-ix installed, the person running it). */
47
+ enabledNow?: true;
48
+ /** What the person can do, when it isn't on. */
49
+ hint?: string;
50
+ }
51
+ /**
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.
59
+ */
60
+ export declare function setupIx(app: App, created: boolean): Promise<SetupIx>;
61
+ /**
62
+ * 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).
65
+ */
66
+ export declare function ixNotice(app: App): Promise<string | undefined>;
67
+ /**
68
+ * Which `ix note` / `ix session` this Ix has, from `ix --help` (graph memory, graph-memory.ts):
69
+ * "oss" (the local backend: Ix after 0.13.0, ix-infrastructure/Ix#916, with Ix Pro not loaded: its
70
+ * help then lists them under "Memory:"), "pro" (Ix Pro loaded: its "Pro:" section; its note and
71
+ * session go to the cloud org), "none" (neither). The same reading as ext-ix's parseMemorySupport
72
+ * (ix.ts), which decides; this one only reports (`p2p doctor`).
73
+ */
74
+ export declare function parseIxMemorySupport(help: string): "oss" | "pro" | "none";
75
+ /** `ix --help` read as parseIxMemorySupport; undefined when it doesn't answer. */
76
+ export declare function ixMemorySupport(bin: string, env: Env, target: Pick<GraphTarget, "endpoint">, timeoutMs: number): Promise<"oss" | "pro" | "none" | undefined>;
@@ -0,0 +1,203 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
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
6
+ // it runs `ix` itself here, the same way ext-ix does: by absolute path from PATH's absolute
7
+ // entries (never a binary planted in the repository), by argv with no shell, bounded, with an
8
+ // allowlisted environment pinned to the graph target (projects.ts), never the caller's IX_*
9
+ // cloud settings. Nothing is ever installed: the person is told how.
10
+ import { execFile } from "node:child_process";
11
+ import { accessSync, constants, statSync } from "node:fs";
12
+ import { delimiter, isAbsolute, join } from "node:path";
13
+ import { sanitizePeerText } from "@peer2peer/core/v3";
14
+ import { enabledNamespaces, extensionDirs, extensionPackageName, resolveIn, setExtensionEnabled } from "./extensions.js";
15
+ import { personHere } from "./projects.js";
16
+ /** Where to get Ix (and how p2p says it): never installed for the person. */
17
+ export const IX_INSTALL_URL = "https://github.com/ix-infrastructure/Ix";
18
+ /**
19
+ * `name` resolved to an absolute path through PATH's absolute entries (the same rule as ext-ix's
20
+ * which.ts: on Windows the current directory is searched before PATH, so a cloned repository's
21
+ * `ix.exe` would otherwise run). An absolute name is used as given when it runs.
22
+ */
23
+ export function whichAbsolute(name, env = process.env, platform = process.platform) {
24
+ const runnable = (p) => {
25
+ try {
26
+ if (!statSync(p).isFile())
27
+ return false;
28
+ if (platform !== "win32")
29
+ accessSync(p, constants.X_OK);
30
+ return true;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ };
36
+ if (isAbsolute(name))
37
+ return runnable(name) ? name : undefined;
38
+ if (/[\\/]/.test(name))
39
+ return undefined;
40
+ const win = platform === "win32";
41
+ const sep = win ? ";" : delimiter;
42
+ const path = env.PATH ?? env.Path ?? "";
43
+ const exts = win ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
44
+ const hasExt = win && exts.some((e) => name.toLowerCase().endsWith(e.toLowerCase()));
45
+ for (const dir of path.split(sep)) {
46
+ const d = dir.trim().replace(/^"|"$/g, "");
47
+ if (d === "" || !isAbsolute(d))
48
+ continue;
49
+ for (const ext of hasExt ? [""] : exts) {
50
+ const p = join(d, name + ext);
51
+ if (runnable(p))
52
+ return p;
53
+ }
54
+ }
55
+ return undefined;
56
+ }
57
+ /** The Ix CLI: IX_BIN when it is an absolute path that runs (or a bare name found on PATH), else `ix` on PATH. */
58
+ export function ixBinary(env) {
59
+ const name = env.IX_BIN?.trim() || "ix";
60
+ return whichAbsolute(name, env);
61
+ }
62
+ /** 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. */
63
+ 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"];
64
+ /**
65
+ * The environment `ix` runs with: IX_CHILD_ALLOW from `env`, then IX_ENDPOINT from the target
66
+ * (never the caller's), no background `ix map` from a reader (Ix Pro routes a map to the cloud
67
+ * whenever an org session is active), no update check. Names compare case-insensitively, as on
68
+ * Windows. The same rule as ext-ix's ixEnv (ix.ts).
69
+ */
70
+ export function ixChildEnv(env, target) {
71
+ const allow = new Set(IX_CHILD_ALLOW);
72
+ const out = {};
73
+ for (const [k, v] of Object.entries(env))
74
+ if (typeof v === "string" && allow.has(k.toUpperCase()))
75
+ out[k] = k.toUpperCase() === "PATH" ? absolutePath(v) : v;
76
+ out.IX_ENDPOINT = target.endpoint;
77
+ out.IX_MAP_BACKGROUND_REFRESH = "0";
78
+ out.IX_NO_UPDATE_CHECK = "1";
79
+ return out;
80
+ }
81
+ /** PATH with its relative and empty entries dropped (they mean the current directory: a repository's own `node`). */
82
+ export function absolutePath(v, platform = process.platform) {
83
+ const sep = platform === "win32" ? ";" : delimiter;
84
+ return v
85
+ .split(sep)
86
+ .filter((d) => {
87
+ const x = d.trim().replace(/^"|"$/g, "");
88
+ return x !== "" && (platform === "win32" ? /^(?:[A-Za-z]:[\\/]|\\\\)/.test(x) : isAbsolute(x));
89
+ })
90
+ .join(sep);
91
+ }
92
+ /** One bounded `ix` call (argv, no shell, SIGKILL on timeout, output capped). Read-only commands only. */
93
+ export function runIx(bin, argv, o) {
94
+ return new Promise((resolve) => {
95
+ 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) => {
96
+ const e = err;
97
+ resolve({ code: e ? (typeof e.code === "number" ? e.code : 1) : 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), ...(e?.killed ? { timedOut: true } : {}) });
98
+ });
99
+ });
100
+ }
101
+ /** `ix --version`'s first line, sanitized; undefined when it fails. */
102
+ export async function ixVersion(bin, env, target, timeoutMs) {
103
+ const r = await runIx(bin, ["--version"], { env, target, timeoutMs });
104
+ if (r.code !== 0)
105
+ return undefined;
106
+ const v = sanitizePeerText(r.stdout.split("\n")[0]?.trim() ?? "", 64);
107
+ return v || undefined;
108
+ }
109
+ /** Whether @peer2peer/ext-ix is where this p2p loads extensions from (resolved, never imported). */
110
+ export function extIxInstalled(env) {
111
+ for (const dir of extensionDirs(env, import.meta.url)) {
112
+ try {
113
+ if (resolveIn(dir, extensionPackageName("ix")))
114
+ return true;
115
+ }
116
+ catch {
117
+ // a malformed copy is not an installed one
118
+ }
119
+ }
120
+ return false;
121
+ }
122
+ /** P2P_EXTENSIONS decides which extensions load (anything but unset or `config`, which defers to config.json). */
123
+ 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)`;
125
+ 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
+ /**
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.
134
+ */
135
+ export async function setupIx(app, created) {
136
+ const found = ixBinary(app.env) !== undefined;
137
+ const { enabled } = enabledNamespaces(app.env, app.file);
138
+ if (enabled.includes("ix"))
139
+ return { found, enabled: true };
140
+ if (!found)
141
+ return { found, enabled: false, hint: INSTALL_IX };
142
+ if (!extIxInstalled(app.env))
143
+ return { found, enabled: false, hint: INSTALL_EXT };
144
+ 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)" };
147
+ }
148
+ if (app.front !== true) {
149
+ 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
+ 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)" };
152
+ }
153
+ setExtensionEnabled(app.home, "ix", true);
154
+ return { found, enabled: true, enabledNow: true };
155
+ }
156
+ /**
157
+ * 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).
160
+ */
161
+ export async function ixNotice(app) {
162
+ if (envDecides(app.env))
163
+ return undefined;
164
+ if (enabledNamespaces(app.env, app.file).enabled.includes("ix"))
165
+ return undefined;
166
+ if ((await app.state.get("ixNotice"))?.at !== undefined)
167
+ return undefined;
168
+ if (!ixBinary(app.env))
169
+ return undefined;
170
+ const shown = await app.state.update("ixNotice", (cur) => (cur?.at !== undefined ? { result: false } : { next: { at: Date.now() }, result: true }));
171
+ if (!shown)
172
+ return undefined;
173
+ 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)`;
175
+ }
176
+ /**
177
+ * Which `ix note` / `ix session` this Ix has, from `ix --help` (graph memory, graph-memory.ts):
178
+ * "oss" (the local backend: Ix after 0.13.0, ix-infrastructure/Ix#916, with Ix Pro not loaded: its
179
+ * help then lists them under "Memory:"), "pro" (Ix Pro loaded: its "Pro:" section; its note and
180
+ * session go to the cloud org), "none" (neither). The same reading as ext-ix's parseMemorySupport
181
+ * (ix.ts), which decides; this one only reports (`p2p doctor`).
182
+ */
183
+ export function parseIxMemorySupport(help) {
184
+ const lines = help.replace(/\u001b\[[0-9;]*m/g, "").split(/\r?\n/);
185
+ if (lines.some((l) => /^Pro:\s*$/.test(l)))
186
+ return "pro";
187
+ const at = lines.findIndex((l) => /^Memory:\s*$/.test(l));
188
+ if (at < 0)
189
+ return "none";
190
+ const section = [];
191
+ for (const l of lines.slice(at + 1)) {
192
+ if (!/^\s+\S/.test(l))
193
+ break;
194
+ section.push(l);
195
+ }
196
+ const has = (name) => section.some((l) => new RegExp(`^\\s+${name}\\s`).test(l));
197
+ return has("note") && has("session") ? "oss" : "none";
198
+ }
199
+ /** `ix --help` read as parseIxMemorySupport; undefined when it doesn't answer. */
200
+ export async function ixMemorySupport(bin, env, target, timeoutMs) {
201
+ const r = await runIx(bin, ["--help"], { env, target, timeoutMs });
202
+ return r.code === 0 ? parseIxMemorySupport(r.stdout) : undefined;
203
+ }