@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,358 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Renders (ui, data) into a frame. Pure: the same inputs give the same frame,
4
+ // so tests snapshot it at fixed sizes. Every string goes through Line.add
5
+ // (frame.ts → sanitize.ts); this file never writes raw text to a terminal.
6
+ import { Line, makeFrame } from "./frame.js";
7
+ import { wrap } from "./sanitize.js";
8
+ import { messagesSorted, peopleItems, SCREEN_TITLES, SCREENS, sendTargets } from "./model.js";
9
+ const DIM = { dim: true, fg: "gray" };
10
+ const OK = { fg: "green" };
11
+ const BAD = { fg: "red", bold: true };
12
+ const WARN = { fg: "yellow" };
13
+ const HEAD = { bold: true };
14
+ export function ago(sec) {
15
+ if (sec < 60)
16
+ return `${Math.max(0, Math.round(sec))}s`;
17
+ if (sec < 3600)
18
+ return `${Math.round(sec / 60)}m`;
19
+ if (sec < 86_400 * 2)
20
+ return `${Math.round(sec / 3600)}h`;
21
+ return `${Math.round(sec / 86_400)}d`;
22
+ }
23
+ const HELP = {
24
+ people: "↑↓ move · m message · d doctor · 1-5 screens · ? help · q quit",
25
+ held: "↑↓ move · a accept/deliver · x decline · t always deliver · ? help · q quit",
26
+ messages: "↑↓ move · Enter open · r reply · h inbox/all · 1-5 screens · ? help · q quit",
27
+ send: "↑↓ pick · Enter write · then Enter send, Esc cancel, Ctrl-U clear · q quit",
28
+ health: "r run doctor · d on People: one person · 1-5 screens · ? help · q quit",
29
+ };
30
+ /** A scrolling window over `n` rows of `h` lines that keeps `sel` visible. */
31
+ function window(n, sel, h) {
32
+ if (n <= h)
33
+ return [0, n];
34
+ const top = Math.max(0, Math.min(sel - Math.floor(h / 2), n - h));
35
+ return [top, top + h];
36
+ }
37
+ export function render(ui, d, cols, rows, now) {
38
+ const f = makeFrame(cols, rows);
39
+ const line = () => new Line(cols);
40
+ if (cols < 40 || rows < 10) {
41
+ f.lines.push(line().add("window too small (40x10 min)", BAD));
42
+ return f;
43
+ }
44
+ // Tab bar.
45
+ const tabs = line().add(" Peer2Peer ", { bold: true, inverse: true }).gap();
46
+ SCREENS.forEach((s, i) => {
47
+ const n = s === "held" && d.held.length > 0 ? ` (${d.held.length})` : "";
48
+ tabs.add(`${i + 1} ${SCREEN_TITLES[s]}${n}`, s === ui.screen ? { bold: true, inverse: true } : s === "held" && n ? WARN : undefined).gap(2);
49
+ });
50
+ const up = d.health.relays.filter((r) => r.up).length;
51
+ const relaysTxt = `${up}/${d.health.relays.length} relays`;
52
+ const who = d.me ? d.me.address : "";
53
+ const right = `${who} ${relaysTxt}`;
54
+ if (tabs.remaining > right.length + 2) {
55
+ tabs.gap(tabs.remaining - right.length - 1);
56
+ tabs.add(who, DIM).gap(2).add(relaysTxt, up === 0 ? BAD : up < d.health.relays.length ? WARN : OK);
57
+ }
58
+ f.lines.push(tabs.fill());
59
+ f.lines.push(line().add("─".repeat(cols), DIM));
60
+ const bodyH = rows - 4;
61
+ const body = [];
62
+ switch (ui.screen) {
63
+ case "people":
64
+ people(ui, d, cols, bodyH, body);
65
+ break;
66
+ case "held":
67
+ held(ui, d, cols, bodyH, body, now);
68
+ break;
69
+ case "messages":
70
+ messages(ui, d, cols, bodyH, body, now);
71
+ break;
72
+ case "send":
73
+ send(ui, d, cols, bodyH, body);
74
+ break;
75
+ case "health":
76
+ health(ui, d, cols, bodyH, body, now);
77
+ break;
78
+ }
79
+ for (let i = 0; i < bodyH; i++)
80
+ f.lines.push(body[i] ?? line());
81
+ // Status line, then the help bar.
82
+ const st = line();
83
+ if (ui.busy)
84
+ st.add(`… ${ui.busy}`, WARN);
85
+ else if (ui.flash)
86
+ st.add(ui.flash.text, ui.flash.error ? BAD : OK);
87
+ else if (d.loading)
88
+ st.add("loading…", DIM);
89
+ f.lines.push(st);
90
+ f.lines.push(line().add(` ${HELP[ui.screen]}`, { inverse: true }).fill({ inverse: true }));
91
+ if (ui.modal)
92
+ overlay(f, ui, cols, rows);
93
+ return f;
94
+ }
95
+ function people(ui, d, cols, h, out) {
96
+ const items = peopleItems(d);
97
+ if (items.length === 0) {
98
+ out.push(new Line(cols).add(d.loading ? "Loading…" : "No friends or circle-mates yet. `p2p invite` makes a code to send someone.", DIM));
99
+ return;
100
+ }
101
+ // Each item can take several lines (summary, files, agents): lay out, then window by item.
102
+ const blocks = items.map((it) => {
103
+ const ls = [];
104
+ if (it.kind === "person") {
105
+ const p = it.person;
106
+ ls.push(new Line(cols).add(p.live ? "●" : "○", p.live ? OK : DIM).gap().add(p.address, HEAD).gap(2).add(p.relation, DIM));
107
+ }
108
+ else {
109
+ const s = it.session;
110
+ const l = new Line(cols).gap(2).add(s.live ? (s.state === "busy" ? "●" : "○") : "·", s.live ? (s.state === "busy" ? WARN : OK) : DIM).gap();
111
+ l.add(`[${s.ref}]`, DIM).gap().add(s.label, { bold: true }, 24).gap().add(s.live ? s.state : "offline", s.live ? undefined : DIM).gap(2);
112
+ const where = [s.repo, s.branch].filter(Boolean).join("@");
113
+ if (where)
114
+ l.add(where, { fg: "cyan" }, 40).gap(2);
115
+ l.add(`${ago(s.ageSec)} ago`, DIM);
116
+ if (s.thisDevice)
117
+ l.gap(2).add("(this device)", DIM);
118
+ ls.push(l);
119
+ if (s.summary)
120
+ ls.push(new Line(cols).gap(6).add(s.summary));
121
+ if (s.files.length > 0) {
122
+ const more = s.files.length > 6 ? ` +${s.files.length - 6}` : "";
123
+ ls.push(new Line(cols).gap(6).add("files: ", DIM).add(s.files.slice(0, 6).join(", "), undefined, Math.max(10, cols - 20)).add(more, DIM));
124
+ }
125
+ for (const a of s.agents) {
126
+ ls.push(new Line(cols).gap(a.parent ? 8 : 6).add("↳ ", DIM).add(a.id, DIM, 16).gap().add(a.type, { fg: "magenta" }, 20).gap().add(`"${a.task}"`, undefined, 60).gap().add(`(${a.state}${a.branch ? `, ${a.branch}` : ""})`, DIM));
127
+ }
128
+ }
129
+ return ls;
130
+ });
131
+ const sel = ui.sel.people;
132
+ // Window over items so the selected one is fully visible.
133
+ let top = 0;
134
+ const heightOf = (i) => blocks[i].length;
135
+ let used = 0;
136
+ for (let i = sel; i >= 0; i--) {
137
+ if (used + heightOf(i) > h)
138
+ break;
139
+ used += heightOf(i);
140
+ top = i;
141
+ }
142
+ // Prefer showing from the start when everything up to sel fits.
143
+ let total = 0;
144
+ for (let i = 0; i <= sel; i++)
145
+ total += heightOf(i);
146
+ if (total <= h)
147
+ top = 0;
148
+ for (let i = top; i < blocks.length && out.length < h; i++) {
149
+ for (const [k, l] of blocks[i].entries()) {
150
+ if (out.length >= h)
151
+ break;
152
+ out.push(i === sel && k === 0 ? l.selected() : l);
153
+ }
154
+ }
155
+ }
156
+ function held(ui, d, cols, h, out, now) {
157
+ const note = wrap(d.heldNote, cols - 2, 3);
158
+ const listH = h - note.length - 1;
159
+ if (d.held.length === 0)
160
+ out.push(new Line(cols).add("Nothing held.", DIM));
161
+ const [a, b] = window(d.held.length, ui.sel.held, Math.max(1, Math.floor(listH / 2)));
162
+ for (let i = a; i < b; i++) {
163
+ const r = d.held[i];
164
+ const l = new Line(cols).add(r.source === "codex" ? "msg " : "item", r.source === "codex" ? { fg: "cyan" } : WARN).gap().col(r.type, 14).add(r.from, HEAD, 48).gap(2);
165
+ if (r.session)
166
+ l.add(`to ${r.session}`, DIM, 30).gap(2);
167
+ l.add(`${ago((now - r.at) / 1000)} ago`, DIM);
168
+ out.push(i === ui.sel.held ? l.selected() : l);
169
+ out.push(new Line(cols).gap(5).add(r.summary, DIM));
170
+ }
171
+ while (out.length < h - note.length)
172
+ out.push(new Line(cols));
173
+ for (const n of note)
174
+ out.push(new Line(cols).gap().add(n, DIM));
175
+ }
176
+ function outcomeText(m, now) {
177
+ if (m.state === "outbox")
178
+ return { text: `queued here (no relay)${m.lastSeen ? `, last seen ${ago((now - m.lastSeen) / 1000)} ago` : ""}`, style: WARN };
179
+ if (m.state === "offline")
180
+ return { text: `waiting at relays (offline${m.lastSeen ? `, last seen ${ago((now - m.lastSeen) / 1000)} ago` : ""})`, style: WARN };
181
+ if (m.state === "failed")
182
+ return { text: `not sent${m.note ? `: ${m.note}` : ""}`, style: BAD };
183
+ if (m.state === "expired")
184
+ return { text: "expired unsent", style: BAD };
185
+ const o = m.outcomes ?? [];
186
+ if (o.length > 0) {
187
+ const last = o[o.length - 1];
188
+ return { text: o.join(" → "), style: last === "shown" ? OK : last === "held" ? WARN : last === "declined" || last === "expired" || last === "ended" ? BAD : undefined };
189
+ }
190
+ return { text: m.receiptId ? "sent, no receipt yet" : "sent", style: DIM };
191
+ }
192
+ function messages(ui, d, cols, h, out, now) {
193
+ const list = messagesSorted(d, ui);
194
+ if (list.length === 0) {
195
+ out.push(new Line(cols).add(ui.inboxOnly ? "Nothing in your inbox yet (h shows every session's messages)." : "No messages yet. Messages to this TUI's session, replies and your sends appear here.", DIM));
196
+ return;
197
+ }
198
+ const [a, b] = window(list.length, ui.sel.messages, Math.floor(h / 2));
199
+ for (let i = a; i < b; i++) {
200
+ const m = list[i];
201
+ const t = new Date(m.at);
202
+ const hhmm = `${String(t.getHours()).padStart(2, "0")}:${String(t.getMinutes()).padStart(2, "0")}`;
203
+ const l = new Line(cols).add(m.dir === "in" ? "←" : "→", m.dir === "in" ? { fg: "cyan" } : { fg: "magenta" }).gap().add(hhmm, DIM).gap();
204
+ l.add(m.dir === "in" ? m.who : `to ${m.who}`, HEAD, 40);
205
+ if (m.ref)
206
+ l.gap().add(`[${m.ref}]`, DIM);
207
+ l.gap(2);
208
+ if (m.dir === "out") {
209
+ const o = outcomeText(m, now);
210
+ l.add(o.text, o.style);
211
+ if (m.note)
212
+ l.gap(2).add(m.note, DIM);
213
+ }
214
+ else {
215
+ if (m.note)
216
+ l.add(m.note, DIM).gap(2);
217
+ }
218
+ out.push(i === ui.sel.messages ? l.selected() : l);
219
+ out.push(new Line(cols).gap(8).add(m.text));
220
+ }
221
+ }
222
+ function send(ui, d, cols, h, out) {
223
+ if (ui.compose) {
224
+ out.push(new Line(cols).add("To: ", DIM).add(ui.compose.target.label, HEAD));
225
+ out.push(new Line(cols));
226
+ const lines = wrap(ui.compose.text, cols - 4, Math.max(1, h - 5));
227
+ if (lines.length === 0)
228
+ lines.push("");
229
+ lines.forEach((t, i) => out.push(new Line(cols).add(i === 0 ? "> " : " ", { fg: "cyan" }).add(t).add(i === lines.length - 1 ? "▏" : "", { fg: "cyan" })));
230
+ out.push(new Line(cols));
231
+ out.push(new Line(cols).add("Enter sends through your relays as this session; Esc cancels.", DIM));
232
+ return;
233
+ }
234
+ const targets = sendTargets(d);
235
+ out.push(new Line(cols).add("Pick who to message (Enter):", HEAD));
236
+ if (targets.length === 0)
237
+ out.push(new Line(cols).add("Nobody to message yet.", DIM));
238
+ const [a, b] = window(targets.length, ui.sel.send, h - 1);
239
+ for (let i = a; i < b; i++) {
240
+ const l = new Line(cols).gap(2).add(targets[i].label);
241
+ out.push(i === ui.sel.send ? l.selected() : l);
242
+ }
243
+ }
244
+ const MARK = { ok: "✓", fail: "✗", unknown: "?" };
245
+ function health(ui, d, cols, h, out, now) {
246
+ out.push(new Line(cols).add("Relays", HEAD));
247
+ for (const r of d.health.relays) {
248
+ const l = new Line(cols).gap(2).add(r.up ? "●" : "○", r.up ? OK : BAD).gap().add(r.url, undefined, 48).gap(2).add(r.up ? "connected" : `down${r.reason ? `: ${r.reason}` : ""}`, r.up ? OK : BAD, 40);
249
+ if (r.access)
250
+ l.gap(2).add(r.access === "members" ? "members-only" : "open", DIM);
251
+ if (r.attention)
252
+ l.gap(2).add("needs operator attention", WARN);
253
+ if (r.software)
254
+ l.gap(2).add(r.software, DIM, 30);
255
+ if (r.pow)
256
+ l.gap(2).add(`pow ${r.pow}`, DIM);
257
+ out.push(l);
258
+ }
259
+ if (d.health.relays.length === 0)
260
+ out.push(new Line(cols).gap(2).add("no relays configured", BAD));
261
+ out.push(new Line(cols));
262
+ const doc = d.health.doctor;
263
+ const title = new Line(cols).add(doc?.who ? `Doctor: can you see ${doc.who}?` : "Doctor: this device", HEAD);
264
+ if (doc)
265
+ title.gap(2).add(`${doc.summary.ok} ✓ ${doc.summary.fail} ✗ ${doc.summary.unknown} ?`, doc.summary.fail > 0 ? BAD : OK).gap(2).add(`(${ago((now - doc.at) / 1000)} ago)`, DIM);
266
+ if (d.health.running)
267
+ title.gap(2).add("running…", WARN);
268
+ out.push(title);
269
+ if (!doc) {
270
+ out.push(new Line(cols).gap(2).add(d.health.running ? "Checking identity, relays, clock and sharing…" : "Press r to run the checks.", DIM));
271
+ return;
272
+ }
273
+ // One group per check (its line, and its fix when not ok); failures first when they don't all fit.
274
+ const groups = doc.checks.map((c) => {
275
+ const g = [new Line(cols).gap(2).add(MARK[c.status], c.status === "ok" ? OK : c.status === "fail" ? BAD : WARN).gap().add(c.title, HEAD, 28).add(": ", DIM).add(c.detail)];
276
+ if (c.fix && c.status !== "ok")
277
+ g.push(new Line(cols).gap(6).add(`${c.status === "unknown" ? "to tell" : "fix"}: `, DIM).add(c.fix, DIM));
278
+ return { status: c.status, lines: g };
279
+ });
280
+ const room = h - out.length;
281
+ const all = groups.flatMap((g) => g.lines);
282
+ const order = all.length > room ? [...groups.filter((g) => g.status === "fail"), ...groups.filter((g) => g.status === "unknown"), ...groups.filter((g) => g.status === "ok")] : groups;
283
+ for (const g of order) {
284
+ if (out.length + g.lines.length > h)
285
+ break;
286
+ out.push(...g.lines);
287
+ }
288
+ }
289
+ function overlay(f, ui, cols, rows) {
290
+ const m = ui.modal;
291
+ const w = Math.min(cols - 4, 76);
292
+ let title;
293
+ let body;
294
+ let footer;
295
+ if (m.kind === "help") {
296
+ title = "Keys";
297
+ body = [
298
+ "1 People 2 Held 3 Messages 4 Send 5 Health (Tab cycles)",
299
+ "↑/↓ or j/k move, PgUp/PgDn, g/G first/last",
300
+ "People: m or Enter message a person or session; d doctor for them",
301
+ "Held: a accept (invites, joins) or deliver (held messages); x decline; t always deliver from the sender (asks first)",
302
+ "Messages: Enter opens one; r replies (this window sends no read receipts); h your inbox only or every session (history: kept encrypted on this device, 30 days by default)",
303
+ "Send: pick, write, Enter sends; Esc cancels",
304
+ "Health: r runs the doctor again",
305
+ "q or Ctrl-C quits. Nothing is accepted, sent or trusted except on your key press.",
306
+ ];
307
+ footer = "Esc closes";
308
+ }
309
+ else if (m.kind === "confirm") {
310
+ title = m.title;
311
+ body = m.lines;
312
+ footer = "y confirm n cancel";
313
+ }
314
+ else if (m.kind === "typed") {
315
+ title = m.title;
316
+ body = [...m.lines, "", `> ${m.text}▏`];
317
+ footer = "Enter confirm Esc cancel";
318
+ }
319
+ else if (m.kind === "prompt") {
320
+ title = m.title;
321
+ body = [...m.lines, "", `> ${m.secret ? "•".repeat([...m.text].length) : m.text}▏`];
322
+ footer = "Enter answer Esc cancel";
323
+ }
324
+ else {
325
+ title = m.title;
326
+ body = m.lines;
327
+ footer = "Esc closes";
328
+ }
329
+ const wrapped = body.flatMap((b) => (b === "" ? [""] : wrap(b, w - 4, 30)));
330
+ const maxBody = rows - 6;
331
+ const shown = wrapped.slice(0, maxBody);
332
+ const top = Math.max(1, Math.floor((rows - shown.length - 4) / 2));
333
+ const left = Math.floor((cols - w) / 2);
334
+ const box = [];
335
+ const frameRow = (inner, style) => {
336
+ const l = new Line(cols).gap(left);
337
+ const content = new Line(w - 4);
338
+ inner(content);
339
+ l.add("│ ", style);
340
+ for (const s of content.spans)
341
+ l.add(s.text, s.style);
342
+ // Padding as raw gaps: add() collapses runs of spaces.
343
+ l.gap(content.remaining);
344
+ l.add(" │", style);
345
+ return l;
346
+ };
347
+ box.push(new Line(cols).gap(left).add(`┌─ ${title} ${"─".repeat(Math.max(0, w - 5 - [...title].length))}┐`, HEAD));
348
+ for (const b of shown)
349
+ box.push(frameRow((l) => l.add(b)));
350
+ if (wrapped.length > shown.length)
351
+ box.push(frameRow((l) => l.add(`… (${wrapped.length - shown.length} more lines)`, DIM)));
352
+ box.push(frameRow((l) => l.add(footer, DIM)));
353
+ box.push(new Line(cols).gap(left).add(`└${"─".repeat(w - 2)}┘`, HEAD));
354
+ box.forEach((l, i) => {
355
+ if (top + i < rows)
356
+ f.lines[top + i] = l;
357
+ });
358
+ }
@@ -0,0 +1,12 @@
1
+ import { type AcceptedMessageV3 } from "@peer2peer/core/v3";
2
+ import type { App } from "./app.js";
3
+ import { type NewEvent } from "./inbound.js";
4
+ /** One notice per (sender, kind) in this long. */
5
+ export declare const UNKNOWN_KIND_NOTICE_MS: number;
6
+ /** Notices remembered at most (the oldest go first). */
7
+ export declare const UNKNOWN_KIND_KEPT = 256;
8
+ /** At most this many notices per sender a day, whatever kinds they send (kind names are theirs to make up). */
9
+ export declare const UNKNOWN_KIND_PER_SENDER = 3;
10
+ /** The log line: once per (sender, kind) in this long, in this process. */
11
+ export declare const UNKNOWN_KIND_LOG_MS: number;
12
+ export declare function onUnknownKind(app: App, env: string, r: AcceptedMessageV3): Promise<NewEvent[]>;
@@ -0,0 +1,66 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Envelopes of a kind this version doesn't know (protocol.md "Forward compatibility", core's
4
+ // rule "unknown-kind"). Core verified the envelope like any other (signature, sender, blocks, the
5
+ // replay window), and opened it; nothing in it is parsed or acted on. This logs it, and tells the
6
+ // user once (per sender and kind, a day) that a peer sent something this version can't show:
7
+ // never dropped silently, never shown as anything but that sentence. The caller commits the replay
8
+ // claim afterwards, as for every applied envelope.
9
+ import { sanitizePeerText, standsLookup, unfriendApplies } from "@peer2peer/core/v3";
10
+ import { fromOf, makeEvent } from "./inbound.js";
11
+ import { sessKey } from "./state.js";
12
+ /** One notice per (sender, kind) in this long. */
13
+ export const UNKNOWN_KIND_NOTICE_MS = 24 * 3600 * 1000;
14
+ /** Notices remembered at most (the oldest go first). */
15
+ export const UNKNOWN_KIND_KEPT = 256;
16
+ /** At most this many notices per sender a day, whatever kinds they send (kind names are theirs to make up). */
17
+ export const UNKNOWN_KIND_PER_SENDER = 3;
18
+ /** The log line: once per (sender, kind) in this long, in this process. */
19
+ export const UNKNOWN_KIND_LOG_MS = 3600 * 1000;
20
+ const logged = new Map();
21
+ /** Whether the user knows this sender: their own device, a friend (not unfriended), or someone who stands in a circle with them. */
22
+ async function isKnownSender(app, from) {
23
+ if (from === app.userId)
24
+ return true;
25
+ const unfriends = await app.store.listUnfriends();
26
+ const friends = (await app.store.listFriendships()).filter((f) => (f.inviter === from || f.invitee === from) && !unfriends.some((u) => unfriendApplies(f, u)));
27
+ if (friends.length > 0)
28
+ return true;
29
+ const stands = await standsLookup(app.store, app.userId);
30
+ return (await app.store.listCircles()).some((c) => c.joinedByMe && stands(from, c.cid));
31
+ }
32
+ export async function onUnknownKind(app, env, r) {
33
+ const e = r.envelope;
34
+ const kind = sanitizePeerText(r.plaintext.envKind ?? String(e.kind), 32);
35
+ // Someone the user doesn't know gets nothing: no notice, no log line, and their device cert isn't kept
36
+ // (a stranger can't use an unknown kind to reach the user, fill the store or flood the log).
37
+ if (!(await isKnownSender(app, e.from)))
38
+ return [];
39
+ await app.store.putDeviceCert({ userId: r.sender.iss, did: r.sender.did, exp: r.sender.exp, jws: r.sender.jws });
40
+ const from = await fromOf(app, r);
41
+ const key = `${e.from}|${kind}`;
42
+ const now = Date.now();
43
+ if (now - (logged.get(key) ?? -Infinity) >= UNKNOWN_KIND_LOG_MS) {
44
+ logged.set(key, now);
45
+ if (logged.size > UNKNOWN_KIND_KEPT)
46
+ logged.delete(logged.keys().next().value);
47
+ app.io.err(`p2p: ${from.address} sent a "${kind}" envelope this version doesn't understand: update to see it`);
48
+ }
49
+ const fresh = await app.state.update("unknownKinds", (cur = {}) => {
50
+ if (now - (cur[key] ?? -Infinity) < UNKNOWN_KIND_NOTICE_MS)
51
+ return { result: false };
52
+ const recent = Object.entries(cur).filter(([k, at]) => k.startsWith(`${e.from}|`) && now - at < UNKNOWN_KIND_NOTICE_MS).length;
53
+ if (recent >= UNKNOWN_KIND_PER_SENDER)
54
+ return { result: false };
55
+ const kept = Object.entries({ ...cur, [key]: now })
56
+ .sort(([, a], [, b]) => b - a)
57
+ .slice(0, UNKNOWN_KIND_KEPT);
58
+ return { next: Object.fromEntries(kept), result: true };
59
+ });
60
+ if (!fresh)
61
+ return [];
62
+ // To the session it was meant for when that is one of ours (or one ours spoke to); else to no session.
63
+ const spoke = (await app.state.get("spoke")) ?? {};
64
+ const toSession = e.own === app.userId ? e.sid : spoke[sessKey(e.own, e.sid)];
65
+ return [makeEvent(env, "p2p.unknown", e.ts, { from, envKind: kind, own: e.own, sid: e.sid }, toSession ? { toSession } : {})];
66
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION = "0.1.1";
@@ -0,0 +1,5 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // This CLI's version (scripts/set-version.mjs writes it), on its own so the status and identity
4
+ // code can advertise it (features.ts) without importing the command line.
5
+ export const VERSION = "0.1.1";
@@ -0,0 +1,12 @@
1
+ /** Leading zero bits a want's proof needs (about 260k hashes, a fraction of a second). */
2
+ export declare const WANT_POW_BITS = 18;
3
+ /** How far a proof's `at` may be from the member's clock (the usual skew plus delivery). */
4
+ export declare const WANT_POW_WINDOW_SEC = 600;
5
+ export interface WantPow {
6
+ at: number;
7
+ nonce: string;
8
+ }
9
+ /** Finds a proof for `from`'s want to member `to` (at `at`, seconds). */
10
+ export declare function solveWantPow(from: string, to: string, cid: string, fromVer: number, at: number, bits?: number): WantPow;
11
+ /** The proof's id (its digest, hex) when it is valid for this want to `to` now, else undefined. */
12
+ export declare function checkWantPow(pow: WantPow | undefined, from: string, to: string, cid: string, fromVer: number, nowSec: number, bits?: number): string | undefined;
@@ -0,0 +1,46 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Proof of work on a non-member's `want` (docs/protocol.md §3.3, re-review
4
+ // N3). An open circle's link is meant to be shared, so nothing a link carries
5
+ // can tell one joiner from a thousand throwaway identities; a per-joiner token
6
+ // signed by the owner would need the owner online to mint one per joiner,
7
+ // which a public link can't do. What the member can ask instead is work: each
8
+ // want from a non-member that wants the reserved budget carries a nonce bound
9
+ // to the asker, the member asked (its userId, the hash of its `ik`: one proof
10
+ // can't be spent at several members, review F1), the circle, `fromVer` and the
11
+ // asker's time, so filling the reserve costs CPU per want and per member, and
12
+ // each proof is accepted once. It raises the cost of draining the reserve; it
13
+ // can't stop a determined attacker from throttling open-circle joins (§3.3).
14
+ import { createHash, randomBytes } from "node:crypto";
15
+ /** Leading zero bits a want's proof needs (about 260k hashes, a fraction of a second). */
16
+ export const WANT_POW_BITS = 18;
17
+ /** How far a proof's `at` may be from the member's clock (the usual skew plus delivery). */
18
+ export const WANT_POW_WINDOW_SEC = 600;
19
+ const digest = (from, to, cid, fromVer, at, nonce) => createHash("sha256").update(`p2p/v3/want-pow|${from}|${to}|${cid}|${fromVer}|${at}|${nonce}`).digest();
20
+ function leadingZeroBits(b) {
21
+ let n = 0;
22
+ for (const byte of b) {
23
+ if (byte === 0) {
24
+ n += 8;
25
+ continue;
26
+ }
27
+ return n + Math.clz32(byte) - 24;
28
+ }
29
+ return n;
30
+ }
31
+ /** Finds a proof for `from`'s want to member `to` (at `at`, seconds). */
32
+ export function solveWantPow(from, to, cid, fromVer, at, bits = WANT_POW_BITS) {
33
+ const prefix = randomBytes(6).toString("base64url");
34
+ for (let i = 0;; i++) {
35
+ const nonce = `${prefix}${i.toString(36)}`;
36
+ if (leadingZeroBits(digest(from, to, cid, fromVer, at, nonce)) >= bits)
37
+ return { at, nonce };
38
+ }
39
+ }
40
+ /** The proof's id (its digest, hex) when it is valid for this want to `to` now, else undefined. */
41
+ export function checkWantPow(pow, from, to, cid, fromVer, nowSec, bits = WANT_POW_BITS) {
42
+ if (!pow || Math.abs(nowSec - pow.at) > WANT_POW_WINDOW_SEC)
43
+ return undefined;
44
+ const d = digest(from, to, cid, fromVer, pow.at, pow.nonce);
45
+ return leadingZeroBits(d) >= bits ? d.toString("hex") : undefined;
46
+ }
@@ -0,0 +1,35 @@
1
+ import type { App } from "./app.js";
2
+ import type { EventRec } from "./state.js";
3
+ export interface WatchOptions {
4
+ session: string;
5
+ /** Hands one line to the reader; resolves false when it is gone. */
6
+ write: (line: string) => Promise<boolean>;
7
+ signal: AbortSignal;
8
+ log: (msg: string) => void;
9
+ /**
10
+ * Event log poll interval. A backstop only: the watch wakes at once when this process appends
11
+ * events, and when the log file changes (another `p2p` process handled a delivery).
12
+ */
13
+ pollMs?: number;
14
+ }
15
+ interface Cursor {
16
+ /** Last printed log position. */
17
+ n: number;
18
+ /** Log position when the cursor was created: older events print only if addressed to this session. */
19
+ start: number;
20
+ }
21
+ /** Does session `sid` of `self` see this event? */
22
+ export declare function eventFor(e: EventRec, sid: string, self: string, cursor: Cursor): boolean;
23
+ /**
24
+ * The JSON line for an event: `{kind, id, at, ...data, toSession?}`. Fields
25
+ * starting with `_` are local-only (an extension's kept body) and never printed.
26
+ */
27
+ export declare function eventLine(e: EventRec): string;
28
+ /** How long a stopped watch waits for its own clean-up (the running marker, the app's close) before returning. */
29
+ export declare const WATCH_EXIT_MS: number;
30
+ export declare function watch(app: App, opts: WatchOptions): Promise<number>;
31
+ /** §2.5: refresh friends' and co-members' documents (revocations spread this way). */
32
+ export declare function refreshContacts(app: App): Promise<void>;
33
+ /** Key holders keep the document and certificates fresh (§2.3 renewal, §2.5 re-publish, single writer). */
34
+ export declare function maintain(app: App): Promise<void>;
35
+ export {};