@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,612 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // `p2p tui`: the controller. It owns the terminal, keeps the data model
4
+ // current and runs what a key press asks for.
5
+ //
6
+ // - Live updates come from the same event stream as `p2p watch`, run
7
+ // in-process (watch.ts) as this TUI's own session: a delivery, a status or
8
+ // a held item redraws within one tick. Nothing polls the network on a
9
+ // timer; the only timers re-read in-memory relay state, refresh relative
10
+ // times, and (while the Held screen is open) ask local Codex sessions what
11
+ // they hold.
12
+ // - Every change (accept, decline, trust, send) is a key press's effect
13
+ // (model.ts onKey). Loading never changes anything.
14
+ // - Receipts: none. The TUI's session is private (it posts no status and
15
+ // has no roster), so senders never ask it for receipts, and it sends
16
+ // none: a `shown` would tell a sender that this session exists and when
17
+ // its person read the message. Replies to its own sends come back like
18
+ // any message, without one.
19
+ // - The terminal is restored on quit, Ctrl-C, SIGTERM/SIGHUP and errors.
20
+ import * as codex from "@peer2peer/codex-bridge";
21
+ import { RECEIPT_OUTCOMES } from "@peer2peer/core/v3";
22
+ import { approveJoinRequest, circleMembers, joinFromHeld, listCircles } from "../circle-ops.js";
23
+ import { doctor } from "../doctor.js";
24
+ import { CliError, toErrorJson } from "../errors.js";
25
+ import { listPeers, sendSharing, tuiTaintNote } from "../sessions.js";
26
+ import { isPersonRecord, readHistory } from "../history.js";
27
+ import { sessionWorkdir, showProject } from "../projects.js";
28
+ import { accept, dropHeld, friends, getHeld, listHeld } from "../social.js";
29
+ import { trustAdd } from "../trust.js";
30
+ import { watch } from "../watch.js";
31
+ import { clean } from "./sanitize.js";
32
+ import { clampSel, initialUi, onKey } from "./model.js";
33
+ import { toAnsi } from "./frame.js";
34
+ import { render } from "./view.js";
35
+ export const TUI_SESSION = "tui";
36
+ /** A relay's `/.well-known/p2p-relay.json` read at most this far (it is a few hundred bytes). */
37
+ export const WELL_KNOWN_MAX = 64 * 1024;
38
+ /** Messages kept in memory (the newest). */
39
+ export const MESSAGES_MAX = 100;
40
+ /** A response body as text, refusing more than `max` bytes (the read stops there). */
41
+ export async function readCapped(body, max) {
42
+ const reader = body.getReader();
43
+ const parts = [];
44
+ let n = 0;
45
+ try {
46
+ for (;;) {
47
+ const { done, value } = await reader.read();
48
+ if (done)
49
+ break;
50
+ n += value.byteLength;
51
+ if (n > max)
52
+ throw new Error(`more than ${max} bytes`);
53
+ parts.push(value);
54
+ }
55
+ }
56
+ finally {
57
+ void reader.cancel().catch(() => { });
58
+ }
59
+ return Buffer.concat(parts).toString("utf8");
60
+ }
61
+ const CLAUDE_HOLD_NOTE = "Messages the Claude Code mod holds for a session stay in Claude Code (its /peers panel); the CLI can't see them, so they aren't listed here. Codex sessions' held messages and every invite or join request are.";
62
+ const asOutcome = (o) => RECEIPT_OUTCOMES.includes(String(o)) ? o : undefined;
63
+ export class Tui {
64
+ app;
65
+ o;
66
+ data;
67
+ ui = initialUi();
68
+ now;
69
+ stop = new AbortController();
70
+ renderQueued = false;
71
+ timers = [];
72
+ refreshTimers = new Map();
73
+ promptAnswer;
74
+ sent = [];
75
+ closed;
76
+ lastFrame = "";
77
+ constructor(app, o) {
78
+ this.app = app;
79
+ this.o = o;
80
+ this.now = o.now ?? Date.now;
81
+ this.data = { session: o.session ?? TUI_SESSION, people: [], held: [], heldNote: CLAUDE_HOLD_NOTE, messages: [], health: { relays: [] }, loading: true };
82
+ }
83
+ /** Runs until quit or abort; the terminal is always restored. */
84
+ async run() {
85
+ const { term } = this.o;
86
+ const onSignal = () => this.stop.abort();
87
+ process.on("SIGINT", onSignal);
88
+ process.on("SIGTERM", onSignal);
89
+ process.on("SIGHUP", onSignal);
90
+ this.o.signal?.addEventListener("abort", onSignal);
91
+ term.enter();
92
+ try {
93
+ term.onKey((k) => this.key(k));
94
+ term.onResize(() => this.draw());
95
+ this.data.me = { userId: this.app.userId, address: await this.app.addressOf(this.app.userId) };
96
+ this.draw();
97
+ const watching = this.o.noWatch ? Promise.resolve(0) : this.startWatch();
98
+ await this.loadAll();
99
+ this.every(5_000, () => this.relayState());
100
+ this.every(10_000, async () => this.draw());
101
+ this.every(30_000, async () => {
102
+ if (this.ui.screen === "held")
103
+ await this.loadHeld();
104
+ });
105
+ void this.runDoctor();
106
+ await new Promise((r) => (this.stop.signal.aborted ? r() : this.stop.signal.addEventListener("abort", () => r())));
107
+ // The terminal goes back first; the watch then closes its connections (bounded).
108
+ term.leave();
109
+ let t;
110
+ await Promise.race([watching.catch(() => 0), new Promise((r) => (t = setTimeout(r, 5000)))]);
111
+ clearTimeout(t);
112
+ }
113
+ finally {
114
+ for (const t of this.timers)
115
+ clearInterval(t);
116
+ for (const t of this.refreshTimers.values())
117
+ clearTimeout(t);
118
+ this.promptAnswer?.(undefined);
119
+ term.leave();
120
+ process.off("SIGINT", onSignal);
121
+ process.off("SIGTERM", onSignal);
122
+ process.off("SIGHUP", onSignal);
123
+ this.o.signal?.removeEventListener("abort", onSignal);
124
+ if (this.o.noWatch)
125
+ await this.app.close();
126
+ }
127
+ }
128
+ quit() {
129
+ this.stop.abort();
130
+ }
131
+ log(m) {
132
+ this.o.log?.(m);
133
+ }
134
+ every(ms, fn) {
135
+ const t = setInterval(() => void fn().catch((e) => this.log(e.message)), ms);
136
+ t.unref();
137
+ this.timers.push(t);
138
+ }
139
+ /** Coalesces refreshes of one kind triggered by bursts of events. */
140
+ soon(kind, fn, ms = 300) {
141
+ if (this.refreshTimers.has(kind))
142
+ return;
143
+ const t = setTimeout(() => {
144
+ this.refreshTimers.delete(kind);
145
+ void fn().catch((e) => this.log(e.message));
146
+ }, ms);
147
+ t.unref();
148
+ this.refreshTimers.set(kind, t);
149
+ }
150
+ draw() {
151
+ if (this.renderQueued)
152
+ return;
153
+ this.renderQueued = true;
154
+ setImmediate(() => {
155
+ this.renderQueued = false;
156
+ this.drawNow();
157
+ });
158
+ }
159
+ drawNow() {
160
+ const { term } = this.o;
161
+ this.ui = clampSel(this.ui, this.data);
162
+ const f = render(this.ui, this.data, term.cols, term.rows, this.now());
163
+ const out = toAnsi(f, term.color);
164
+ this.lastFrame = out;
165
+ term.write(out);
166
+ }
167
+ // -------------------------------------------------------------------------
168
+ // Data
169
+ startWatch() {
170
+ return watch(this.app, {
171
+ session: this.data.session,
172
+ signal: this.stop.signal,
173
+ log: (m) => this.log(m),
174
+ write: async (line) => {
175
+ try {
176
+ this.onEvent(JSON.parse(line));
177
+ }
178
+ catch (e) {
179
+ this.log(e.message);
180
+ }
181
+ return true;
182
+ },
183
+ }).catch((e) => {
184
+ this.flash(`watch stopped: ${String(toErrorJson(e).reason)}`, true);
185
+ return 1;
186
+ });
187
+ }
188
+ /** One event from the stream (already in the shared log). */
189
+ onEvent(e) {
190
+ const kind = String(e.kind);
191
+ if (kind === "p2p.message") {
192
+ const m = this.messageFromEvent(e);
193
+ if (m && !this.data.messages.some((x) => x.id === m.id)) {
194
+ this.data.messages.push(m);
195
+ this.capMessages();
196
+ }
197
+ }
198
+ else if (kind === "p2p.receipt") {
199
+ const id = String(e.receiptId ?? "");
200
+ const o = asOutcome(e.outcome);
201
+ const m = this.data.messages.find((x) => x.receiptId === id);
202
+ if (m && o && !(m.outcomes ?? []).includes(o))
203
+ m.outcomes = [...(m.outcomes ?? []), o];
204
+ }
205
+ else if (kind === "p2p.outbox") {
206
+ this.soon("messages", () => this.loadMessages());
207
+ }
208
+ if (["p2p.status", "p2p.idle", "p2p.friend", "p2p.unfriend", "p2p.circle", "p2p.roster", "p2p.joined"].includes(kind))
209
+ this.soon("people", () => this.loadPeople());
210
+ if (["p2p.held", "p2p.circle", "p2p.contact", "p2p.invite-taken"].includes(kind))
211
+ this.soon("held", () => this.loadHeld());
212
+ this.draw();
213
+ }
214
+ messageFromEvent(e) {
215
+ const from = (e.from ?? {});
216
+ if (typeof e.id !== "string")
217
+ return undefined;
218
+ const forUs = e.toSession === this.data.session || (e.toSession === undefined && e.unclaimedFor === undefined);
219
+ return {
220
+ id: e.id,
221
+ dir: "in",
222
+ at: typeof e.at === "number" ? e.at : this.now(),
223
+ who: clean(from.address) || "?",
224
+ ...(typeof from.userId === "string" ? { userId: from.userId } : {}),
225
+ ...(typeof e.own === "string" ? { own: e.own } : {}),
226
+ ...(typeof e.sid === "string" ? { sid: e.sid } : {}),
227
+ ...(typeof e.ref === "string" ? { ref: e.ref } : {}),
228
+ text: clean(e.text),
229
+ inbox: forUs,
230
+ ...(!forUs && typeof e.toSession === "string" ? { note: `for your session ${clean(e.toSession)}` } : {}),
231
+ };
232
+ }
233
+ async loadAll() {
234
+ await Promise.all([this.loadPeople(), this.loadHeld(), this.loadMessages(), this.relayState()].map((p) => p.catch((e) => this.log(e.message))));
235
+ this.data.loading = false;
236
+ this.draw();
237
+ }
238
+ async loadPeople() {
239
+ const app = this.app;
240
+ const [peers, fr, circles] = await Promise.all([listPeers(app, { all: true }), friends(app), listCircles(app)]);
241
+ const people = new Map();
242
+ const person = (userId, address) => {
243
+ let p = people.get(userId);
244
+ if (!p)
245
+ people.set(userId, (p = { userId, address, relation: "", self: userId === app.userId, live: false, sessions: [] }));
246
+ return p;
247
+ };
248
+ const rel = new Map();
249
+ const addRel = (u, r) => rel.set(u, (rel.get(u) ?? new Set()).add(r));
250
+ for (const f of fr.friends) {
251
+ person(f.userId, f.address);
252
+ addRel(f.userId, "friend");
253
+ }
254
+ for (const c of circles.filter((x) => x.joined)) {
255
+ try {
256
+ const m = await circleMembers(app, c.cid);
257
+ for (const x of m.members) {
258
+ if (x.self || !x.stands)
259
+ continue;
260
+ person(x.userId, x.address);
261
+ addRel(x.userId, `circle ${clean(c.name)}`);
262
+ }
263
+ }
264
+ catch {
265
+ // a circle that doesn't load: skip it
266
+ }
267
+ }
268
+ for (const p of peers) {
269
+ const pr = person(p.own, p.address);
270
+ const s = {
271
+ own: p.own,
272
+ sid: p.sid,
273
+ ref: p.ref,
274
+ label: p.label,
275
+ state: p.state,
276
+ live: p.live,
277
+ ageSec: p.ageSec,
278
+ files: p.files,
279
+ agents: (p.agents ?? []).map((a) => ({ id: a.id, ...(a.parent ? { parent: a.parent } : {}), type: a.type, task: a.task, state: a.state, ...(a.branch ? { branch: a.branch } : {}) })),
280
+ ...(p.summary ? { summary: p.summary } : {}),
281
+ ...(p.repo ? { repo: p.repo } : {}),
282
+ ...(p.branch ? { branch: p.branch } : {}),
283
+ ...(p.thisDevice ? { thisDevice: true } : {}),
284
+ };
285
+ pr.sessions.push(s);
286
+ if (p.live)
287
+ pr.live = true;
288
+ }
289
+ for (const p of people.values()) {
290
+ p.relation = p.self ? "you" : [...(rel.get(p.userId) ?? [])].join(" · ") || "shares a session with you";
291
+ p.sessions.sort((a, b) => Number(b.live) - Number(a.live) || a.ageSec - b.ageSec);
292
+ }
293
+ this.data.people = [...people.values()].sort((a, b) => Number(b.self) - Number(a.self) || Number(b.live) - Number(a.live) || a.address.localeCompare(b.address));
294
+ this.draw();
295
+ }
296
+ async loadHeld() {
297
+ const items = await listHeld(this.app);
298
+ const rows = items.map((h) => ({ source: "item", id: h.id, type: h.type, from: h.address, summary: h.summary, at: h.at }));
299
+ try {
300
+ const c = await codex.heldCommand({ env: this.app.env, now: this.now() });
301
+ const held = (c.json.held ?? []);
302
+ for (const h of held)
303
+ rows.push({ source: "codex", id: h.id, type: `message (${h.kind})`, from: h.from, session: h.session, summary: h.why, at: h.at });
304
+ }
305
+ catch {
306
+ // no Codex sessions, or not allowed here
307
+ }
308
+ this.data.held = rows;
309
+ this.draw();
310
+ }
311
+ /**
312
+ * Received messages from the event log, and sent ones: this run's, receipts asked for, the outbox;
313
+ * then the message history (history.ts) for what is older or was sent elsewhere. The TUI runs
314
+ * only on the person's own terminal (command.ts tuiRefusal), so it reads the person's view.
315
+ */
316
+ async loadMessages() {
317
+ const app = this.app;
318
+ const cutoff = this.now() - 7 * 86_400_000;
319
+ const log = (await app.state.get("events"))?.items ?? [];
320
+ const received = log
321
+ .filter((e) => e.kind === "p2p.message" && e.at >= cutoff && !e.data.from?.self)
322
+ .slice(-100)
323
+ .map((e) => this.messageFromEvent({ ...e.data, kind: e.kind, id: e.id, at: e.at, ...(e.toSession ? { toSession: e.toSession } : {}) }))
324
+ .filter((m) => m !== undefined);
325
+ const receipts = (await app.state.get("receipts"))?.wanted ?? {};
326
+ const outbox = (await app.state.get("outbox"))?.items ?? [];
327
+ const out = [];
328
+ for (const s of this.sent) {
329
+ const w = s.receiptId ? receipts[s.receiptId] : undefined;
330
+ if (w)
331
+ s.outcomes = w.outcomes.map((x) => x.outcome);
332
+ out.push(s);
333
+ }
334
+ for (const [id, w] of Object.entries(receipts)) {
335
+ if (w.at < cutoff || out.some((m) => m.receiptId === id))
336
+ continue;
337
+ out.push({ id: `r:${id}`, dir: "out", at: w.at, who: await app.addressOf(w.to), userId: w.to, own: w.own, ref: w.ref, text: `(sent from session ${w.fromSession}; text not kept)`, state: "sent", receiptId: id, outcomes: w.outcomes.map((x) => x.outcome), inbox: w.fromSession === this.data.session, ...(w.fromSession !== this.data.session ? { note: `from your session ${clean(w.fromSession)}` } : {}) });
338
+ }
339
+ for (const i of outbox) {
340
+ out.push({ id: `o:${i.id}`, dir: "out", at: i.queuedAt, who: i.dest.address, userId: i.dest.userId, own: i.dest.own, ref: i.dest.ref, text: `(sealed in the outbox, from session ${i.fromSession})`, state: "outbox", inbox: i.fromSession === this.data.session });
341
+ }
342
+ const hist = await readHistory(app, { person: true }, { limit: MESSAGES_MAX }, this.now()).catch(() => undefined);
343
+ for (const r of hist?.messages ?? []) {
344
+ if (r.dir === "in") {
345
+ if (!received.some((m) => m.id === r.id))
346
+ received.push(historyRow(r, this.data.session));
347
+ continue;
348
+ }
349
+ // A send already listed (this run's, a receipt's, the outbox's): the history fills in its text.
350
+ const same = out.find((m) => m.userId === r.peer.userId && Math.abs(m.at - r.at) < 60_000 && (m.text === r.text || m.text.startsWith("(")));
351
+ if (same) {
352
+ if (same.text.startsWith("("))
353
+ same.text = clean(r.text);
354
+ continue;
355
+ }
356
+ out.push(historyRow(r, this.data.session));
357
+ }
358
+ this.data.messages = [...received, ...out];
359
+ this.capMessages();
360
+ this.draw();
361
+ }
362
+ /** Keeps the newest MESSAGES_MAX messages (this run's sends are capped the same way). */
363
+ capMessages() {
364
+ if (this.data.messages.length > MESSAGES_MAX)
365
+ this.data.messages = [...this.data.messages].sort((a, b) => b.at - a.at).slice(0, MESSAGES_MAX);
366
+ if (this.sent.length > MESSAGES_MAX)
367
+ this.sent = this.sent.slice(-MESSAGES_MAX);
368
+ }
369
+ /** Relay up/down from the in-memory pool (no network). */
370
+ async relayState() {
371
+ const app = this.app;
372
+ const connected = new Set(app.pool?.connected ?? app.relayStatus?.connected ?? []);
373
+ const failed = new Map((app.relayStatus?.failed ?? []).map((f) => [f.url, f.reason]));
374
+ const prev = new Map(this.data.health.relays.map((r) => [r.url, r]));
375
+ this.data.health.relays = app.relays.map((url) => ({
376
+ ...prev.get(url),
377
+ url,
378
+ up: connected.has(url),
379
+ ...(connected.has(url) ? { reason: undefined } : failed.has(url) ? { reason: clean(failed.get(url)) } : {}),
380
+ }));
381
+ this.draw();
382
+ }
383
+ /** Each relay's `/.well-known/p2p-relay.json` (access, software, pow): read once per doctor run. */
384
+ async relayInfo() {
385
+ await Promise.all(this.app.relays.map(async (url) => {
386
+ try {
387
+ const base = new URL(this.app.transport(url).http).origin;
388
+ const res = await fetch(`${base}/.well-known/p2p-relay.json`, { signal: AbortSignal.timeout(5000) });
389
+ if (!res.ok || !res.body)
390
+ return;
391
+ const j = JSON.parse(await readCapped(res.body, WELL_KNOWN_MAX));
392
+ const r = this.data.health.relays.find((x) => x.url === url);
393
+ if (!r)
394
+ return;
395
+ if (j.access === "members" || j.access === "open")
396
+ r.access = j.access;
397
+ r.attention = j.attention === true;
398
+ if (j.software && typeof j.software.version === "string")
399
+ r.software = clean(`${String(j.software.name ?? "relay")} ${j.software.version}`).slice(0, 40);
400
+ if (typeof j.pow === "number" && Number.isSafeInteger(j.pow))
401
+ r.pow = j.pow;
402
+ }
403
+ catch {
404
+ // unreachable: the doctor says so
405
+ }
406
+ }));
407
+ }
408
+ async runDoctor(user) {
409
+ if (this.data.health.running)
410
+ return;
411
+ this.data.health.running = true;
412
+ this.draw();
413
+ try {
414
+ await this.relayState();
415
+ await this.relayInfo();
416
+ const r = await doctor(this.app, { version: this.o.version, ...(user ? { user } : {}) });
417
+ this.data.health.doctor = {
418
+ scope: r.scope,
419
+ ...(r.user ? { who: clean(r.user.address ?? r.user.input) } : {}),
420
+ checks: r.checks.map((c) => ({ status: c.status, title: c.title, detail: c.detail, ...(c.fix ? { fix: c.fix } : {}) })),
421
+ summary: r.summary,
422
+ at: this.now(),
423
+ };
424
+ }
425
+ catch (e) {
426
+ this.flash(`doctor: ${String(toErrorJson(e).reason)}`, true);
427
+ }
428
+ finally {
429
+ this.data.health.running = false;
430
+ this.draw();
431
+ }
432
+ }
433
+ // -------------------------------------------------------------------------
434
+ // Keys and effects
435
+ key(k) {
436
+ // Once quitting, nothing else is dispatched (keys after Ctrl-C in the same read included).
437
+ if (this.stop.signal.aborted)
438
+ return;
439
+ const r = onKey(this.ui, this.data, k, Math.max(1, Math.floor((this.o.term.rows - 4) / 2)));
440
+ this.ui = r.ui;
441
+ if (r.effect?.kind === "quit") {
442
+ this.quit();
443
+ return;
444
+ }
445
+ this.draw();
446
+ if (r.effect)
447
+ void this.effect(r.effect);
448
+ }
449
+ flash(text, error = false) {
450
+ this.ui = { ...this.ui, flash: { text, ...(error ? { error } : {}) } };
451
+ this.draw();
452
+ }
453
+ async busy(what, fn) {
454
+ this.ui = { ...this.ui, busy: what };
455
+ this.draw();
456
+ try {
457
+ return await fn();
458
+ }
459
+ catch (e) {
460
+ const j = toErrorJson(e);
461
+ this.ui = { ...this.ui, busy: undefined };
462
+ this.flash(`${what}: ${String(j.reason)}`, true);
463
+ return undefined;
464
+ }
465
+ finally {
466
+ if (this.ui.busy === what)
467
+ this.ui = { ...this.ui, busy: undefined };
468
+ this.draw();
469
+ }
470
+ }
471
+ /** Asks one line in a modal (Codex release codes, circle-join confirmations). */
472
+ ask(title, lines) {
473
+ this.promptAnswer?.(undefined);
474
+ this.ui = { ...this.ui, modal: { kind: "prompt", title, lines, text: "" } };
475
+ this.draw();
476
+ return new Promise((resolve) => (this.promptAnswer = resolve));
477
+ }
478
+ async effect(e) {
479
+ switch (e.kind) {
480
+ case "quit":
481
+ this.quit();
482
+ return;
483
+ case "prompt-answer":
484
+ case "prompt-cancel": {
485
+ const f = this.promptAnswer;
486
+ this.promptAnswer = undefined;
487
+ f?.(e.kind === "prompt-answer" ? e.text : undefined);
488
+ return;
489
+ }
490
+ case "accept-item": {
491
+ await this.busy("accepting", async () => {
492
+ const h = await getHeld(this.app, e.id);
493
+ if (h.type === "invite") {
494
+ const r = await accept(this.app, h.invite);
495
+ this.flash(`You and ${clean(r.friend.address)} are friends.`);
496
+ }
497
+ else if (h.type === "circle-join") {
498
+ const r = await approveJoinRequest(this.app, h);
499
+ await dropHeld(this.app, (x) => x.id === h.id);
500
+ this.flash(`Admitted ${clean(await this.app.addressOf(r.added))} (circle version ${r.ver}).`);
501
+ }
502
+ else if (h.type === "circle-invite") {
503
+ const r = await joinFromHeld(this.app, h, {
504
+ waitSec: 20,
505
+ confirm: async (q) => ((await this.ask("Join the circle?", [q, "", "Type yes to join anyway."])) ?? "").trim().toLowerCase() === "yes",
506
+ });
507
+ this.flash(`Circle ${clean(r.name ?? r.cid)}: ${r.status}.`);
508
+ }
509
+ else {
510
+ throw new CliError("usage", `a ${h.type} item needs a choice the CLI makes: \`p2p held approve ${h.id}\` or \`p2p identity\` in your terminal`);
511
+ }
512
+ await Promise.all([this.loadHeld(), this.loadPeople()]);
513
+ });
514
+ return;
515
+ }
516
+ case "decline-item": {
517
+ await this.busy("declining", async () => {
518
+ const h = await getHeld(this.app, e.id);
519
+ if (h.type === "rotation-dispute")
520
+ throw new CliError("usage", `a contested key is settled in the CLI: \`p2p identity dispute ${h.id}\``);
521
+ await dropHeld(this.app, (x) => x.id === h.id);
522
+ this.flash(`Declined.`);
523
+ await this.loadHeld();
524
+ });
525
+ return;
526
+ }
527
+ case "codex-release":
528
+ case "codex-decline":
529
+ await this.busy(e.kind === "codex-release" ? "delivering" : "declining", async () => {
530
+ const r = await codex.resolveCommand({
531
+ env: this.app.env,
532
+ id: e.id,
533
+ decline: e.kind === "codex-decline",
534
+ io: { isTTY: true, prompt: async (q) => (await this.ask("Confirmation code", [q])) ?? "" },
535
+ });
536
+ this.flash(clean(r.human));
537
+ await this.loadHeld();
538
+ });
539
+ return;
540
+ case "trust-and-release":
541
+ await this.busy("delivering", async () => {
542
+ // The release first (it asks for the code its window shows): trust is saved only once it
543
+ // went through, so a cancelled or failed release trusts nobody.
544
+ const r = await codex.resolveCommand({ env: this.app.env, id: e.id, io: { isTTY: true, prompt: async (q) => (await this.ask("Confirmation code", [q])) ?? "" } });
545
+ const t = await trustAdd(this.app, e.from);
546
+ this.flash(`${clean(r.human)} Always delivering from ${clean(t.address ?? e.from)} from now on.`);
547
+ await this.loadHeld();
548
+ });
549
+ return;
550
+ case "send":
551
+ await this.busy("sending", async () => {
552
+ const at = this.now();
553
+ const row = { id: `s:${at}:${this.sent.length}`, dir: "out", at, who: e.label, text: e.text, state: "sent", inbox: true };
554
+ try {
555
+ // As `p2p send` on a terminal: someone this session isn't shared with is added with the send
556
+ // (undone if it fails), so it lands and their replies come here; and it says so.
557
+ const { result: r, shared } = await sendSharing(this.app, { fromSession: this.data.session, to: e.to, text: e.text });
558
+ Object.assign(row, {
559
+ who: clean(r.to.address),
560
+ userId: r.to.userId,
561
+ own: r.to.own,
562
+ sid: r.to.sid,
563
+ ref: r.to.ref,
564
+ state: r.queued ? (r.state === "outbox" ? "outbox" : "offline") : "sent",
565
+ ...(r.lastSeen ? { lastSeen: r.lastSeen } : {}),
566
+ ...(r.receiptId ? { receiptId: r.receiptId } : {}),
567
+ });
568
+ const note = shared ? ` Shared session ${clean(this.data.session)} with ${clean(shared.address)}.` : "";
569
+ // Your own send crosses no project boundary; it says which one this folder has (projects.ts).
570
+ const here = await showProject(this.app, sessionWorkdir(this.app.env)).catch(() => undefined);
571
+ const boundary = here ? ` Project ${clean(here.name)} here is ${here.policy}: this send was yours.` : "";
572
+ const taint = await tuiTaintNote(this.app, r.to.userId).catch(() => undefined);
573
+ this.flash(`${r.queued ? `Queued for ${clean(r.to.address)} [${r.to.ref}]: it goes out or waits until they're back.` : `Sent to ${clean(r.to.address)} [${r.to.ref}].`}${note}${boundary}${taint ? ` Note: ${taint}.` : ""}`);
574
+ }
575
+ catch (err) {
576
+ Object.assign(row, { state: "failed", note: clean(toErrorJson(err).reason) });
577
+ throw err;
578
+ }
579
+ finally {
580
+ this.sent.push(row);
581
+ await this.loadMessages();
582
+ }
583
+ });
584
+ return;
585
+ case "doctor":
586
+ await this.runDoctor(e.user);
587
+ return;
588
+ }
589
+ }
590
+ /** For tests: resolves once the TUI stopped. */
591
+ done() {
592
+ return (this.closed ??= new Promise((r) => (this.stop.signal.aborted ? r() : this.stop.signal.addEventListener("abort", () => r()))));
593
+ }
594
+ }
595
+ /** A message history record as a row of the Messages screen (peer text cleaned for the terminal). */
596
+ export function historyRow(r, session) {
597
+ const mine = isPersonRecord(r) || r.session === session;
598
+ const where = r.session === undefined ? "" : clean(r.session);
599
+ return {
600
+ id: r.id,
601
+ dir: r.dir,
602
+ at: r.at,
603
+ who: clean(r.peer.address) || "?",
604
+ userId: r.peer.userId,
605
+ ...(r.peerSession ? { own: r.peerSession.own, sid: r.peerSession.sid, ref: r.peerSession.ref } : {}),
606
+ text: clean(r.type === "ext" ? `${r.ext ?? "extension"}: ${r.text}` : r.text),
607
+ ...(r.dir === "out" ? { state: r.state === "outbox" ? "outbox" : r.state === "offline" ? "offline" : "sent" } : {}),
608
+ fromHistory: true,
609
+ inbox: mine,
610
+ ...(!mine ? { note: r.dir === "in" ? `for your session ${where}` : `from your session ${where}` } : {}),
611
+ };
612
+ }
@@ -0,0 +1,4 @@
1
+ import { type Frame } from "./frame.js";
2
+ import { type Data, type Ui } from "./model.js";
3
+ export declare function ago(sec: number): string;
4
+ export declare function render(ui: Ui, d: Data, cols: number, rows: number, now: number): Frame;