@peer2peer/cli 0.0.0-stage → 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.
Files changed (111) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +370 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +368 -0
  6. package/dist/app.js +1181 -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 +660 -0
  12. package/dist/cli.js +1787 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +159 -0
  16. package/dist/config.js +294 -0
  17. package/dist/doctor.d.ts +113 -0
  18. package/dist/doctor.js +930 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +38 -0
  22. package/dist/ext-host.js +293 -0
  23. package/dist/extensions.d.ts +487 -0
  24. package/dist/extensions.js +406 -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/graph-memory.d.ts +107 -0
  30. package/dist/graph-memory.js +393 -0
  31. package/dist/history.d.ts +155 -0
  32. package/dist/history.js +697 -0
  33. package/dist/identity.d.ts +239 -0
  34. package/dist/identity.js +759 -0
  35. package/dist/inbound.d.ts +32 -0
  36. package/dist/inbound.js +261 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +14 -0
  39. package/dist/ix-local.d.ts +76 -0
  40. package/dist/ix-local.js +203 -0
  41. package/dist/join-answers.d.ts +49 -0
  42. package/dist/join-answers.js +149 -0
  43. package/dist/outbox.d.ts +109 -0
  44. package/dist/outbox.js +337 -0
  45. package/dist/pretty.d.ts +100 -0
  46. package/dist/pretty.js +256 -0
  47. package/dist/procstart.d.ts +1 -0
  48. package/dist/procstart.js +66 -0
  49. package/dist/progress.d.ts +30 -0
  50. package/dist/progress.js +78 -0
  51. package/dist/projects.d.ts +491 -0
  52. package/dist/projects.js +1383 -0
  53. package/dist/prompt/picker.d.ts +64 -0
  54. package/dist/prompt/picker.js +152 -0
  55. package/dist/prompt/tty.d.ts +29 -0
  56. package/dist/prompt/tty.js +122 -0
  57. package/dist/readonly.d.ts +20 -0
  58. package/dist/readonly.js +50 -0
  59. package/dist/receipts.d.ts +99 -0
  60. package/dist/receipts.js +182 -0
  61. package/dist/relay-client.d.ts +277 -0
  62. package/dist/relay-client.js +873 -0
  63. package/dist/relay-info.d.ts +24 -0
  64. package/dist/relay-info.js +53 -0
  65. package/dist/rotation.d.ts +402 -0
  66. package/dist/rotation.js +2054 -0
  67. package/dist/running.d.ts +5 -0
  68. package/dist/running.js +74 -0
  69. package/dist/sessions.d.ts +355 -0
  70. package/dist/sessions.js +1247 -0
  71. package/dist/shortcode.d.ts +149 -0
  72. package/dist/shortcode.js +465 -0
  73. package/dist/social.d.ts +139 -0
  74. package/dist/social.js +485 -0
  75. package/dist/state.d.ts +509 -0
  76. package/dist/state.js +220 -0
  77. package/dist/stdin.d.ts +17 -0
  78. package/dist/stdin.js +46 -0
  79. package/dist/sync.d.ts +77 -0
  80. package/dist/sync.js +375 -0
  81. package/dist/transient.d.ts +1 -0
  82. package/dist/transient.js +28 -0
  83. package/dist/trust.d.ts +37 -0
  84. package/dist/trust.js +134 -0
  85. package/dist/tty-confirm.d.ts +2 -0
  86. package/dist/tty-confirm.js +53 -0
  87. package/dist/tui/command.d.ts +20 -0
  88. package/dist/tui/command.js +70 -0
  89. package/dist/tui/frame.d.ts +43 -0
  90. package/dist/tui/frame.js +111 -0
  91. package/dist/tui/model.d.ts +221 -0
  92. package/dist/tui/model.js +259 -0
  93. package/dist/tui/sanitize.d.ts +13 -0
  94. package/dist/tui/sanitize.js +151 -0
  95. package/dist/tui/terminal.d.ts +88 -0
  96. package/dist/tui/terminal.js +354 -0
  97. package/dist/tui/tui.d.ts +78 -0
  98. package/dist/tui/tui.js +612 -0
  99. package/dist/tui/view.d.ts +4 -0
  100. package/dist/tui/view.js +358 -0
  101. package/dist/unknown-kinds.d.ts +12 -0
  102. package/dist/unknown-kinds.js +66 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +5 -0
  105. package/dist/want-pow.d.ts +12 -0
  106. package/dist/want-pow.js +46 -0
  107. package/dist/watch.d.ts +35 -0
  108. package/dist/watch.js +331 -0
  109. package/dist/xstate.d.ts +125 -0
  110. package/dist/xstate.js +422 -0
  111. package/package.json +60 -4
@@ -0,0 +1,100 @@
1
+ import { type Style } from "./prompt/picker.js";
2
+ import type { CircleSummary } from "./circle-ops.js";
3
+ import type { CodeRow, InviteCodeResult } from "./codes.js";
4
+ import type { DoctorResult } from "./doctor.js";
5
+ import type { PeerRow } from "./sessions.js";
6
+ import type { FriendRow } from "./social.js";
7
+ export interface Pretty {
8
+ color: boolean;
9
+ cols: number;
10
+ /** Unix seconds (tests pin it). */
11
+ now?: number;
12
+ }
13
+ /** Everything a terminal could act on, except the SGR (colour) sequences this module writes. */
14
+ export declare function safePretty(s: string): string;
15
+ /** "2m ago", "3h ago", "just now"; "in 4d" for the future. */
16
+ export declare function ago(sec: number, now: number): string;
17
+ /** `name@fp`: the name first (bold), the fingerprint dimmed. */
18
+ export declare function who(address: string, st: Style, width?: number): string;
19
+ export declare function prettyPeers(rows: PeerRow[], relays: {
20
+ failed: {
21
+ url: string;
22
+ }[];
23
+ } | undefined, p: Pretty): string;
24
+ export declare function prettyFriends(r: {
25
+ friends: FriendRow[];
26
+ invites: {
27
+ outgoing: unknown[];
28
+ held: number;
29
+ };
30
+ blocked: {
31
+ address: string;
32
+ }[];
33
+ }, p: Pretty): string;
34
+ export declare function prettyCircles(rows: CircleSummary[], p: Pretty): string;
35
+ export declare function prettyHeld(rows: {
36
+ id: string;
37
+ type: string;
38
+ summary: string;
39
+ address: string;
40
+ at?: number;
41
+ }[], p: Pretty): string;
42
+ export declare function prettyCodes(rows: CodeRow[], p: Pretty): string;
43
+ /** Whole days left, rounded up: a 7-day code a few seconds old still says "7 days". */
44
+ export declare function daysLeft(exp: number, now: number): string;
45
+ export declare function prettyInvite(r: InviteCodeResult, p: Pretty): string;
46
+ export declare function prettyDoctor(r: DoctorResult, plain: string, p: Pretty): string;
47
+ export declare function prettyRelays(r: {
48
+ relays: string[];
49
+ }, status: {
50
+ connected: string[];
51
+ failed: {
52
+ url: string;
53
+ reason: string;
54
+ }[];
55
+ } | undefined, p: Pretty): string;
56
+ export declare function prettyTrust(r: {
57
+ users: {
58
+ userId: string;
59
+ address: string;
60
+ blocked: boolean;
61
+ }[];
62
+ circles: {
63
+ cid: string;
64
+ name?: string | null;
65
+ joined: boolean;
66
+ open: boolean;
67
+ members: string[];
68
+ }[];
69
+ }, p: Pretty): string;
70
+ export declare function prettyStatus(r: {
71
+ status: {
72
+ state: string;
73
+ };
74
+ delivered: unknown[];
75
+ failed: {
76
+ address: string;
77
+ }[];
78
+ roster: {
79
+ sid: string;
80
+ vis: string;
81
+ circleName?: string;
82
+ circle?: string;
83
+ parts: {
84
+ address: string;
85
+ }[];
86
+ };
87
+ }, p: Pretty): string;
88
+ export interface HomeData {
89
+ address?: string;
90
+ relays: {
91
+ url: string;
92
+ ok: boolean;
93
+ }[];
94
+ online: string[];
95
+ friends: number;
96
+ held: number;
97
+ }
98
+ export declare const HOME_COMMANDS: [string, string][];
99
+ /** `p2p` with no arguments, on a terminal. */
100
+ export declare function prettyHome(d: HomeData, p: Pretty): string;
package/dist/pretty.js ADDED
@@ -0,0 +1,256 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Human output for a terminal (stdout a TTY, no --json): aligned tables,
4
+ // colour for state, relative times, names first with the fingerprint dimmed,
5
+ // headings and empty states that say what to do next. Piped or redirected
6
+ // output keeps format.ts's plain text, unchanged.
7
+ //
8
+ // Every string from a peer, a relay or the store goes through the TUI's
9
+ // sanitiser (clean/cell) before it is laid out, and safePretty() then removes
10
+ // anything a terminal could act on except the SGR colour codes made here.
11
+ // NO_COLOR, TERM=dumb (and FORCE_COLOR) decide `color` (tui/terminal.ts colorWanted).
12
+ import { COLOR, PLAIN } from "./prompt/picker.js";
13
+ import { cell, clean, displayWidth } from "./tui/sanitize.js";
14
+ const styleOf = (p) => (p.color ? COLOR : PLAIN);
15
+ const nowOf = (p) => p.now ?? Date.now() / 1000;
16
+ /** Everything a terminal could act on, except the SGR (colour) sequences this module writes. */
17
+ export function safePretty(s) {
18
+ return s
19
+ .replace(/\u001b(?!\[[0-9;]*m)/g, "")
20
+ .replace(/[\u0000-\u0008\u000b-\u001a\u001c-\u001f\u007f-\u009f\u2028\u2029]/g, "")
21
+ .replace(/\p{Cf}/gu, "");
22
+ }
23
+ /** "2m ago", "3h ago", "just now"; "in 4d" for the future. */
24
+ export function ago(sec, now) {
25
+ const d = Math.round(now - sec);
26
+ const f = (x) => (x < 60 ? `${x}s` : x < 3600 ? `${Math.floor(x / 60)}m` : x < 86_400 ? `${Math.floor(x / 3600)}h` : `${Math.floor(x / 86_400)}d`);
27
+ if (d < 0)
28
+ return `in ${f(-d)}`;
29
+ return d < 5 ? "just now" : `${f(d)} ago`;
30
+ }
31
+ /** `name@fp`: the name first (bold), the fingerprint dimmed. */
32
+ export function who(address, st, width = 48) {
33
+ const a = cell(address, width);
34
+ const at = a.lastIndexOf("@");
35
+ return at > 0 ? `${st.bold(a.slice(0, at))}${st.dim(a.slice(at))}` : st.bold(a);
36
+ }
37
+ /** An aligned table: `head` dimmed, widths by display width, the last column never padded. */
38
+ function table(head, rows, st) {
39
+ const width = (c) => displayWidth(c.text);
40
+ const cols = head.map((h, i) => Math.max(displayWidth(h), ...rows.map((r) => (r[i] ? width(r[i]) : 0))));
41
+ const line = (cells) => cells
42
+ .map((c, i) => {
43
+ const shown = c.raw ?? (c.style ? c.style(c.text) : c.text);
44
+ return i === cells.length - 1 ? shown : shown + " ".repeat(Math.max(0, cols[i] - width(c)));
45
+ })
46
+ .join(" ")
47
+ .trimEnd();
48
+ return [st.dim(line(head.map((h) => ({ text: h })))), ...rows.map(line)].join("\n");
49
+ }
50
+ const t = (s, w = 60, style) => ({ text: cell(s, w), ...(style ? { style } : {}) });
51
+ const name = (address, st) => {
52
+ const a = cell(address, 48);
53
+ return { text: a, raw: who(a, st) };
54
+ };
55
+ const heading = (s, st) => st.bold(s);
56
+ export function prettyPeers(rows, relays, p) {
57
+ const st = styleOf(p);
58
+ const out = [];
59
+ if (rows.length === 0)
60
+ out.push(`${heading("Sessions", st)}\n${st.dim("No live sessions yet. Friends' and circle-mates' sessions show up here once they post a status.")}\nInvite someone: ${st.cyan("p2p invite")}`);
61
+ else {
62
+ const now = nowOf(p);
63
+ const state = (r) => (!r.live ? t("stale", 8, st.dim) : r.state === "busy" ? t("busy", 8, st.yellow) : t("idle", 8, st.green));
64
+ out.push(heading(`Sessions (${rows.length})`, st));
65
+ out.push(table(["WHO", "SESSION", "STATE", "WHERE", "SEEN"], rows.map((r) => [
66
+ r.self ? { text: cell(`you${r.thisDevice ? " (this device)" : ""}`, 24), style: st.bold } : name(r.address, st),
67
+ t(`${clean(r.label)} [${clean(r.ref)}]`, 28),
68
+ state(r),
69
+ t([r.repo, r.branch].filter(Boolean).map(clean).join("@") || "-", 32, st.dim),
70
+ t(ago(now - r.ageSec, now), 10, st.dim),
71
+ ]), st));
72
+ const notes = rows.filter((r) => r.summary).map((r) => ` ${who(r.self ? "you" : r.address, st)} ${st.dim("·")} ${cell(r.summary, Math.max(20, p.cols - 30))}`);
73
+ if (notes.length)
74
+ out.push("", ...notes);
75
+ }
76
+ if (relays?.failed.length)
77
+ out.push("", st.red(`! unreachable: ${relays.failed.map((f) => cell(f.url, 60)).join(", ")}`));
78
+ return out.join("\n");
79
+ }
80
+ export function prettyFriends(r, p) {
81
+ const st = styleOf(p);
82
+ const now = nowOf(p);
83
+ const out = [heading(`Friends (${r.friends.length})`, st)];
84
+ if (r.friends.length === 0)
85
+ out.push(st.dim("No friends yet."), `Invite someone: ${st.cyan("p2p invite")} (pick circles, get a link to send)`);
86
+ else
87
+ out.push(table(["FRIEND", "SINCE", "STATUS"], r.friends.map((f) => [name(f.address, st), t(ago(f.since, now), 12, st.dim), f.canMessage ? t("connected", 24, st.green) : t("waiting for their cap", 24, st.yellow)]), st));
88
+ if (r.invites.outgoing.length > 0)
89
+ out.push("", st.dim(`${r.invites.outgoing.length} open invite${r.invites.outgoing.length === 1 ? "" : "s"} of yours, not yet accepted`));
90
+ if (r.invites.held > 0)
91
+ out.push("", st.yellow(`${r.invites.held} held item${r.invites.held === 1 ? "" : "s"} waiting for you: `) + st.cyan("p2p held"));
92
+ if (r.blocked.length > 0)
93
+ out.push("", st.dim(`blocked: ${r.blocked.map((b) => cell(b.address, 48)).join(", ")}`));
94
+ return out.join("\n");
95
+ }
96
+ export function prettyCircles(rows, p) {
97
+ const st = styleOf(p);
98
+ if (rows.length === 0)
99
+ return `${heading("Circles", st)}\n${st.dim("You're in no circles yet.")}\nMake one: ${st.cyan("p2p circle create <name>")} or join one: ${st.cyan("p2p circle join <link>")}`;
100
+ return [
101
+ heading(`Circles (${rows.length})`, st),
102
+ table(["NAME", "ROLE", "MEMBERS", "POLICY", "OWNER", "ID"], rows.map((c) => [
103
+ { text: cell(`${clean(c.name)}${c.isDefault ? " (default)" : ""}`, 32), style: c.isDefault ? st.cyan : st.bold },
104
+ t(c.frozen ? `${c.role} (frozen)` : c.role, 18, c.frozen ? st.red : undefined),
105
+ t(`${c.standing}/${c.members}`, 9),
106
+ t(c.policy, 7, c.policy === "open" ? st.yellow : undefined),
107
+ name(c.ownerAddress, st),
108
+ t(c.cid, 40, st.dim),
109
+ ]), st),
110
+ ].join("\n");
111
+ }
112
+ export function prettyHeld(rows, p) {
113
+ const st = styleOf(p);
114
+ if (rows.length === 0)
115
+ return `${heading("Held", st)}\n${st.dim("Nothing is waiting for you.")}`;
116
+ const now = nowOf(p);
117
+ return [
118
+ heading(`Held (${rows.length})`, st),
119
+ table(["ID", "FROM", "WHAT", "WHEN"], rows.map((h) => [t(h.id, 24, st.cyan), name(h.address, st), t(h.summary, Math.max(24, p.cols - 60)), t(h.at ? ago(h.at / 1000, now) : "-", 10, st.dim)]), st),
120
+ "",
121
+ st.dim("Act on one: ") + st.cyan("p2p held approve") + st.dim(" or ") + st.cyan("p2p held decline") + st.dim(" (with no id, you pick from the list)"),
122
+ ].join("\n");
123
+ }
124
+ export function prettyCodes(rows, p) {
125
+ const st = styleOf(p);
126
+ if (rows.length === 0)
127
+ return `${heading("Invites", st)}\n${st.dim("No invite codes.")}\nMake one: ${st.cyan("p2p invite")}`;
128
+ const now = nowOf(p);
129
+ const status = (r) => {
130
+ switch (r.status) {
131
+ case "open":
132
+ return t(`open, ${daysLeft(r.exp, now)} left`, 24, st.green);
133
+ case "taken":
134
+ return t("taken, nobody joined yet", 28, st.yellow);
135
+ case "redeemed":
136
+ return { text: cell(`joined: ${clean(r.redeemedBy?.address ?? "?")}`, 56), raw: `${st.green("joined:")} ${who(r.redeemedBy?.address ?? "?", st)}` };
137
+ case "evicted":
138
+ return t("evicted by the relay: make a new one", 40, st.red);
139
+ default:
140
+ return t(r.status, 12, st.dim);
141
+ }
142
+ };
143
+ return [
144
+ heading(`Invites (${rows.length})`, st),
145
+ 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),
147
+ t(r.to ? clean(r.to.address) : (r.label ?? "anyone"), 28),
148
+ t(r.circles.length ? r.circles.map((c) => clean(c.name)).join(", ") : "friend only", 32),
149
+ status(r),
150
+ ]), st),
151
+ "",
152
+ st.dim("Cancel one: ") + st.cyan("p2p invites revoke <code>"),
153
+ ].join("\n");
154
+ }
155
+ /** Whole days left, rounded up: a 7-day code a few seconds old still says "7 days". */
156
+ export function daysLeft(exp, now) {
157
+ const d = Math.max(1, Math.ceil((exp - now - 60) / 86_400));
158
+ return `${d} day${d === 1 ? "" : "s"}`;
159
+ }
160
+ export function prettyInvite(r, p) {
161
+ const st = styleOf(p);
162
+ const now = nowOf(p);
163
+ const join = `p2p join${r.privateRelay ? " --allow-private-relay" : ""} '${cell(r.web, 400)}'`;
164
+ const what = r.circles.length ? `It makes them your friend and joins them to ${r.circles.map((c) => st.bold(`"${cell(c.name, 40)}"`)).join(", ")}.` : "It makes them your friend.";
165
+ return [
166
+ st.bold(`Your invite${r.label ? ` for ${cell(r.label, 40)}` : ""}`) + st.dim(` (works once, for ${daysLeft(r.expiresAt, now)}${r.to ? `, only for ${cell(r.to.address, 48)}` : ""})`),
167
+ "",
168
+ ` ${st.cyan(st.bold(cell(r.web, 400)))}`,
169
+ "",
170
+ st.dim(` or the code: ${cell(r.code, 200)} (${join})`),
171
+ "",
172
+ what,
173
+ st.yellow("Send it over a channel you trust: ") + "anyone who sees it first can use it. They see who it's from and say yes before anything happens.",
174
+ "",
175
+ st.bold("Send them this message") + st.dim(" (it says how to install Peer2Peer if they don't have it):"),
176
+ "",
177
+ ...r.message.split("\n").map((l) => ` ${cell(l, 400)}`),
178
+ "",
179
+ st.dim("Who joined: p2p invites · undo: p2p remove <user> · cancel: p2p invites revoke <code>"),
180
+ ].join("\n");
181
+ }
182
+ export function prettyDoctor(r, plain, p) {
183
+ const st = styleOf(p);
184
+ return plain
185
+ .split("\n")
186
+ .map((l, i) => {
187
+ const s = cell(l, 400);
188
+ if (i === 0)
189
+ return st.bold(s);
190
+ if (s.startsWith("✓"))
191
+ return st.green("✓") + s.slice(1);
192
+ if (s.startsWith("✗"))
193
+ return st.red("✗") + s.slice(1);
194
+ if (s.startsWith("?"))
195
+ return st.yellow("?") + s.slice(1);
196
+ if (/^\s+(fix|to tell):/.test(s))
197
+ return st.dim(s);
198
+ return s;
199
+ })
200
+ .join("\n")
201
+ .concat(r.summary.fail === 0 ? `\n${st.green("Everything checks out.")}` : "");
202
+ }
203
+ export function prettyRelays(r, status, p) {
204
+ const st = styleOf(p);
205
+ const rows = r.relays.map((u) => {
206
+ const bad = status?.failed.find((f) => f.url === u);
207
+ const ok = status?.connected.includes(u);
208
+ return [t(u, 60, st.bold), bad ? t(`unreachable: ${clean(bad.reason)}`, 60, st.red) : ok ? t("reachable", 12, st.green) : t("not checked", 12, st.dim)];
209
+ });
210
+ return [heading(`Relays (${r.relays.length})`, st), table(["RELAY", "STATUS"], rows, st), "", st.dim("Add or remove: ") + st.cyan("p2p relays add <url>") + st.dim(" · ") + st.cyan("p2p relays remove <url>")].join("\n");
211
+ }
212
+ export function prettyTrust(r, p) {
213
+ const st = styleOf(p);
214
+ if (r.users.length === 0 && r.circles.length === 0)
215
+ return `${heading("Trusted", st)}\n${st.dim("Nobody is trusted.")}\nTrust someone (their messages reach a session without the hold): ${st.cyan("p2p trust add")}`;
216
+ const rows = [
217
+ ...r.users.map((u) => [name(u.address, st), u.blocked ? t("blocked: not trusted", 24, st.red) : t("trusted", 12, st.green)]),
218
+ ...r.circles.map((c) => [
219
+ t(`circle ${clean(c.name ?? c.cid)}`, 40, st.bold),
220
+ !c.joined ? t("not joined: nobody", 24, st.dim) : c.open ? t("open now: nobody", 24, st.yellow) : t(`${c.members.length} members`, 16, st.green),
221
+ ]),
222
+ ];
223
+ return [heading("Trusted", st), table(["WHO", "STATUS"], rows, st)].join("\n");
224
+ }
225
+ export function prettyStatus(r, p) {
226
+ const st = styleOf(p);
227
+ const shared = r.roster.vis === "circle" ? `circle ${cell(r.roster.circleName ?? r.roster.circle, 40)}` : r.roster.parts.length ? r.roster.parts.map((x) => cell(x.address, 48)).join(", ") : "nobody else (private)";
228
+ return [
229
+ `${r.status.state === "busy" ? st.yellow("busy") : st.green("idle")} posted to ${st.bold(String(r.delivered.length))} peer${r.delivered.length === 1 ? "" : "s"}${r.failed.length ? st.red(`; ${r.failed.length} unreachable (${r.failed.map((f) => cell(f.address, 48)).join(", ")})`) : ""}`,
230
+ st.dim(`session ${cell(r.roster.sid, 40)}: shared with ${shared}`),
231
+ ].join("\n");
232
+ }
233
+ export const HOME_COMMANDS = [
234
+ ["p2p invite", "invite someone (pick circles, get a link)"],
235
+ ["p2p join <link>", "accept an invite someone sent you"],
236
+ ["p2p ls", "live sessions of your friends and circles"],
237
+ ["p2p held", "what is waiting for your yes"],
238
+ ["p2p tui", "everything, full screen"],
239
+ ];
240
+ /** `p2p` with no arguments, on a terminal. */
241
+ export function prettyHome(d, p) {
242
+ const st = styleOf(p);
243
+ const out = [st.bold("Peer2Peer")];
244
+ if (!d.address) {
245
+ out.push("", "No identity on this device yet.", ` ${st.cyan("p2p setup")} make one`, ` ${st.cyan("p2p join <link>")} or join with a link someone sent you`);
246
+ return out.join("\n");
247
+ }
248
+ out.push(`You are ${who(d.address, st)}`, "");
249
+ const up = d.relays.filter((r) => r.ok).length;
250
+ out.push(`${st.dim("relays ")} ${up === d.relays.length ? st.green(`${up}/${d.relays.length} reachable`) : st.red(`${up}/${d.relays.length} reachable`)}${d.relays.filter((r) => !r.ok).length ? st.dim(` (down: ${d.relays.filter((r) => !r.ok).map((r) => cell(r.url, 48)).join(", ")})`) : ""}`, `${st.dim("friends")} ${d.friends}${d.online.length ? `, ${st.green(`${d.online.length} online`)}: ${d.online.slice(0, 5).map((a) => who(a, st, 32)).join(", ")}${d.online.length > 5 ? st.dim(` +${d.online.length - 5}`) : ""}` : st.dim(", none online")}`, `${st.dim("held ")} ${d.held ? st.yellow(`${d.held} waiting for you`) + st.dim(" (p2p held)") : st.dim("nothing waiting")}`, "", st.bold("Try"));
251
+ const w = Math.max(...HOME_COMMANDS.map(([c]) => c.length));
252
+ for (const [c, what] of HOME_COMMANDS)
253
+ out.push(` ${st.cyan(c.padEnd(w))} ${st.dim(what)}`);
254
+ out.push("", st.dim("All commands: p2p --help"));
255
+ return out.join("\n");
256
+ }
@@ -0,0 +1 @@
1
+ export declare function processStartMs(pid: number): number | undefined;
@@ -0,0 +1,66 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // When another process on this machine started (ms since the epoch), so a replay claim held by a
4
+ // pid that has since been reused isn't taken for its holder's (pre-release review L-C). Only asked when a
5
+ // claim from another local process is found (rare), so a spawn is fine. Undefined when the
6
+ // platform can't say cheaply: the caller then keeps going by the pid alone.
7
+ import { execFileSync } from "node:child_process";
8
+ import { readFileSync } from "node:fs";
9
+ let bootMs;
10
+ function linuxStartMs(pid) {
11
+ // Field 22 of /proc/<pid>/stat: start time in clock ticks after boot (USER_HZ, 100 on Linux).
12
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
13
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
14
+ const ticks = Number(fields[19]);
15
+ if (!Number.isFinite(ticks))
16
+ return undefined;
17
+ if (bootMs === undefined) {
18
+ const m = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
19
+ if (!m)
20
+ return undefined;
21
+ bootMs = Number(m[1]) * 1000;
22
+ }
23
+ return bootMs + (ticks / 100) * 1000;
24
+ }
25
+ function psStartMs(pid) {
26
+ const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], env: { LC_ALL: "C", PATH: process.env.PATH ?? "" } }).trim();
27
+ const t = Date.parse(out);
28
+ return Number.isFinite(t) ? t : undefined;
29
+ }
30
+ /**
31
+ * Answers are remembered for CACHE_MS per pid. On macOS and the BSDs each answer is a `ps` spawn
32
+ * (30-100 ms, synchronous) and it is asked while the trust store's lock is held (claimReplay's
33
+ * liveness check): a watch and a short command racing for the same envelopes asked it for every
34
+ * one of them, and every other p2p process of the home waited on the lock meanwhile. A pid's
35
+ * start time doesn't change while it lives; a pid reused within CACHE_MS would only make its
36
+ * claim look alive a little longer (the envelope isn't acked, and is redelivered).
37
+ */
38
+ const CACHE_MS = 5_000;
39
+ const CACHE_MAX = 256;
40
+ const cache = new Map();
41
+ export function processStartMs(pid) {
42
+ if (!Number.isSafeInteger(pid) || pid <= 0)
43
+ return undefined;
44
+ const now = Date.now();
45
+ const hit = cache.get(pid);
46
+ if (hit && now - hit.at < CACHE_MS)
47
+ return hit.ms;
48
+ const ms = lookup(pid);
49
+ cache.delete(pid);
50
+ cache.set(pid, { at: now, ms });
51
+ if (cache.size > CACHE_MAX)
52
+ cache.delete(cache.keys().next().value);
53
+ return ms;
54
+ }
55
+ function lookup(pid) {
56
+ try {
57
+ if (process.platform === "linux")
58
+ return linuxStartMs(pid);
59
+ if (process.platform === "darwin" || process.platform.endsWith("bsd"))
60
+ return psStartMs(pid);
61
+ }
62
+ catch {
63
+ // gone, or no ps
64
+ }
65
+ return undefined;
66
+ }
@@ -0,0 +1,30 @@
1
+ import { CliError } from "./errors.js";
2
+ export interface Progress {
3
+ log(msg: string): void;
4
+ debug: boolean;
5
+ slowMs: number;
6
+ /** The step in flight (named by the command deadline's message). */
7
+ current?: string;
8
+ /**
9
+ * Hosts (`host:port` of the dial URL) this command found unreachable, with
10
+ * the error: later connects and fetches to them fail at once instead of
11
+ * waiting out another timeout each (a firewall that drops SYNs).
12
+ */
13
+ unreachable?: Map<string, CliError>;
14
+ /** Aborted when the command's deadline passes: no new network step starts after that. */
15
+ signal?: AbortSignal;
16
+ }
17
+ export declare const SILENT: Progress;
18
+ export declare function makeProgress(env: Record<string, string | undefined>, log: (msg: string) => void): Progress;
19
+ /** Runs `fn` as the step `label` (see the file comment). */
20
+ export declare function step<T>(p: Progress | undefined, label: string, fn: () => Promise<T>, opts?: {
21
+ timeoutMs?: number;
22
+ noDebug?: boolean;
23
+ }): Promise<T>;
24
+ /** `host:port` of a ws(s):// or http(s):// URL (the default port filled in). */
25
+ export declare function hostKey(url: string): {
26
+ key: string;
27
+ port: string;
28
+ };
29
+ /** A debug-only line. */
30
+ export declare function debug(p: Progress | undefined, msg: string): void;
@@ -0,0 +1,78 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // No command hangs silently: every network step runs through `step`, which
4
+ // - says what it is doing on stderr once it has taken longer than `slowMs`
5
+ // (default 3 s), e.g. "p2p: connecting to wss://relay.example/v3 (relay 1/2)…";
6
+ // - with P2P_DEBUG=1, logs every step's start, end and duration instead;
7
+ // - optionally bounds the step, failing with `timeout` and a message that
8
+ // names the step (and so the relay).
9
+ // Labels carry relay URLs, userIds and frame types only: never keys, caps,
10
+ // envelopes, codes or phrases.
11
+ import { CliError } from "./errors.js";
12
+ export const SILENT = { log: () => { }, debug: false, slowMs: 3000 };
13
+ export function makeProgress(env, log) {
14
+ const debug = /^(1|true|yes|on)$/i.test(env.P2P_DEBUG?.trim() ?? "");
15
+ const raw = env.P2P_SLOW_MS?.trim();
16
+ const slow = raw ? Number(raw) : NaN;
17
+ return { log, debug, slowMs: Number.isFinite(slow) && slow >= 0 ? slow : 3000, unreachable: new Map() };
18
+ }
19
+ const secs = (ms) => `${Math.round(ms / 100) / 10}s`;
20
+ /** Runs `fn` as the step `label` (see the file comment). */
21
+ export async function step(p, label, fn, opts = {}) {
22
+ const pr0 = p ?? SILENT;
23
+ // noDebug: a frequent step (state lock) logs only when slow, even under P2P_DEBUG.
24
+ const pr = opts.noDebug && pr0.debug ? { ...pr0, debug: false, log: pr0.log } : pr0;
25
+ // Once the command is out of time, nothing new goes on the wire (steps already running finish
26
+ // or time out on their own, so in-flight sends and writes settle).
27
+ if (pr0.signal?.aborted)
28
+ throw new CliError("aborted", `not ${label}: the command ran out of time`);
29
+ const prev = pr.current;
30
+ pr.current = label;
31
+ const t0 = Date.now();
32
+ if (pr.debug)
33
+ pr.log(`debug: ${label}…`);
34
+ let slow;
35
+ if (!pr.debug) {
36
+ slow = setTimeout(() => pr.log(`${label}…`), pr.slowMs);
37
+ slow.unref?.();
38
+ }
39
+ let to;
40
+ try {
41
+ const work = fn();
42
+ const r = opts.timeoutMs !== undefined
43
+ ? await Promise.race([
44
+ work,
45
+ new Promise((_, reject) => {
46
+ to = setTimeout(() => reject(new CliError("timeout", `${label}: no answer after ${secs(opts.timeoutMs)}`)), opts.timeoutMs);
47
+ to.unref?.();
48
+ }),
49
+ ])
50
+ : await work;
51
+ if (pr.debug)
52
+ pr.log(`debug: ${label}: done in ${Date.now() - t0}ms`);
53
+ return r;
54
+ }
55
+ catch (e) {
56
+ if (pr.debug)
57
+ pr.log(`debug: ${label}: failed after ${Date.now() - t0}ms: ${e.message}`);
58
+ throw e;
59
+ }
60
+ finally {
61
+ if (slow)
62
+ clearTimeout(slow);
63
+ if (to)
64
+ clearTimeout(to);
65
+ pr.current = prev;
66
+ }
67
+ }
68
+ /** `host:port` of a ws(s):// or http(s):// URL (the default port filled in). */
69
+ export function hostKey(url) {
70
+ const u = new URL(url);
71
+ const port = u.port || (u.protocol === "wss:" || u.protocol === "https:" ? "443" : "80");
72
+ return { key: `${u.hostname}:${port}`, port };
73
+ }
74
+ /** A debug-only line. */
75
+ export function debug(p, msg) {
76
+ if (p?.debug)
77
+ p.log(`debug: ${msg}`);
78
+ }