@peer2peer/cli 0.0.0-stage → 0.1.0

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