@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,259 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The TUI's state and its key handling, as pure functions: a key press turns
4
+ // (ui, data) into a new ui and, at most, one effect for the controller
5
+ // (tui.ts) to run. Only key presses produce effects that change anything
6
+ // (accept, decline, trust, send); loading data and live updates
7
+ // never do.
8
+ export const SCREENS = ["people", "held", "messages", "send", "health"];
9
+ export const SCREEN_TITLES = { people: "People", held: "Held", messages: "Messages", send: "Send", health: "Health" };
10
+ export function initialUi() {
11
+ return { screen: "people", sel: { people: 0, held: 0, messages: 0, send: 0, health: 0 } };
12
+ }
13
+ export function peopleItems(d) {
14
+ const out = [];
15
+ for (const p of d.people) {
16
+ out.push({ kind: "person", person: p });
17
+ for (const s of p.sessions)
18
+ out.push({ kind: "session", person: p, session: s });
19
+ }
20
+ return out;
21
+ }
22
+ /** Send targets: live sessions first (not this TUI's own), then each person (their one session, or our session). */
23
+ export function sendTargets(d) {
24
+ const sessions = [];
25
+ const people = [];
26
+ for (const p of d.people) {
27
+ for (const s of p.sessions) {
28
+ if (p.self && s.thisDevice && s.sid === d.session)
29
+ continue;
30
+ sessions.push({ label: `${p.address} [${s.ref}] ${s.label}${s.live ? "" : " (offline)"}`, to: `${p.userId} [${s.ref}]` });
31
+ }
32
+ if (!p.self)
33
+ people.push({ label: `${p.address} (any session)`, to: p.userId });
34
+ }
35
+ return [...sessions, ...people];
36
+ }
37
+ export function messagesSorted(d, ui) {
38
+ return d.messages.filter((m) => !ui?.inboxOnly || m.inbox !== false).sort((a, b) => b.at - a.at);
39
+ }
40
+ function count(ui, d) {
41
+ switch (ui.screen) {
42
+ case "people":
43
+ return peopleItems(d).length;
44
+ case "held":
45
+ return d.held.length;
46
+ case "messages":
47
+ return messagesSorted(d, ui).length;
48
+ case "send":
49
+ return sendTargets(d).length;
50
+ case "health":
51
+ return d.health.relays.length + (d.health.doctor?.checks.length ?? 0);
52
+ }
53
+ }
54
+ export function clampSel(ui, d) {
55
+ const n = count(ui, d);
56
+ const cur = ui.sel[ui.screen];
57
+ const v = n === 0 ? 0 : Math.max(0, Math.min(cur, n - 1));
58
+ return v === cur ? ui : { ...ui, sel: { ...ui.sel, [ui.screen]: v } };
59
+ }
60
+ const flash = (ui, text, error = false) => ({ ...ui, flash: { text, ...(error ? { error } : {}) } });
61
+ /** One key press. Returns the next ui and, at most, one effect. */
62
+ export function onKey(ui0, d, key, page = 10) {
63
+ const ui = { ...ui0, flash: undefined };
64
+ if (key.ctrl && key.name === "c")
65
+ return { ui, effect: { kind: "quit" } };
66
+ // Modals take every key.
67
+ const m = ui.modal;
68
+ if (m) {
69
+ if (m.kind === "typed") {
70
+ if (key.name === "escape")
71
+ return { ui: flash({ ...ui, modal: undefined }, "Cancelled.") };
72
+ if (key.paste)
73
+ return { ui: { ...ui, flash: { text: "Type it: a paste doesn't count here.", error: true } } };
74
+ if (key.name === "return") {
75
+ if (m.text.trim().toLowerCase() === m.word.toLowerCase())
76
+ return { ui: { ...ui, modal: undefined }, effect: m.effect };
77
+ return { ui: { ...ui, modal: { ...m, text: "" }, flash: { text: `Type ${m.word} exactly, or Esc to cancel.`, error: true } } };
78
+ }
79
+ if (key.name === "backspace")
80
+ return { ui: { ...ui, modal: { ...m, text: [...m.text].slice(0, -1).join("") } } };
81
+ if (key.ch && !key.ctrl && m.text.length < 32)
82
+ return { ui: { ...ui, modal: { ...m, text: m.text + key.ch } } };
83
+ return { ui };
84
+ }
85
+ // A paste never answers a confirmation or closes a dialog.
86
+ if (key.paste && m.kind !== "prompt")
87
+ return { ui };
88
+ if (m.kind === "confirm") {
89
+ if (key.ch === "y" || key.ch === "Y")
90
+ return { ui: { ...ui, modal: undefined }, effect: m.effect };
91
+ if (key.ch === "n" || key.ch === "N" || key.name === "escape" || key.ch === "q")
92
+ return { ui: flash({ ...ui, modal: undefined }, "Cancelled.") };
93
+ return { ui: { ...ui, flash: { text: "Press y to confirm, n to cancel." } } };
94
+ }
95
+ if (m.kind === "prompt") {
96
+ if (key.name === "escape")
97
+ return { ui: { ...ui, modal: undefined }, effect: { kind: "prompt-cancel" } };
98
+ if (key.name === "return")
99
+ return { ui: { ...ui, modal: undefined }, effect: { kind: "prompt-answer", text: m.text } };
100
+ if (key.name === "backspace")
101
+ return { ui: { ...ui, modal: { ...m, text: [...m.text].slice(0, -1).join("") } } };
102
+ if (key.ch && !key.ctrl && m.text.length < 64)
103
+ return { ui: { ...ui, modal: { ...m, text: m.text + key.ch } } };
104
+ return { ui };
105
+ }
106
+ // detail, help: any of these closes.
107
+ if (key.name === "escape" || key.name === "return" || key.ch === "q" || key.ch === "?" || key.name === "space")
108
+ return { ui: { ...ui, modal: undefined } };
109
+ return { ui };
110
+ }
111
+ // Typing a message.
112
+ if (ui.screen === "send" && ui.compose) {
113
+ const c = ui.compose;
114
+ if (key.name === "escape")
115
+ return { ui: flash({ ...ui, compose: undefined }, "Not sent.") };
116
+ if (key.name === "return") {
117
+ const text = c.text.trim();
118
+ if (!text)
119
+ return { ui: flash(ui, "Type a message first (Esc to cancel).", true) };
120
+ return { ui: { ...ui, compose: undefined }, effect: { kind: "send", to: c.target.to, label: c.target.label, text } };
121
+ }
122
+ if (key.name === "backspace")
123
+ return { ui: { ...ui, compose: { ...c, text: [...c.text].slice(0, -1).join("") } } };
124
+ if (key.ctrl && key.name === "u")
125
+ return { ui: { ...ui, compose: { ...c, text: "" } } };
126
+ if (key.ch && !key.ctrl && Buffer.byteLength(c.text + key.ch) <= 4000)
127
+ return { ui: { ...ui, compose: { ...c, text: c.text + key.ch } } };
128
+ return { ui };
129
+ }
130
+ // Pasted text outside a message or prompt is dropped: it must never act as command keys.
131
+ if (key.paste)
132
+ return { ui: { ...ui, flash: { text: "A paste only goes into a message: pick someone on Send first." } } };
133
+ if (key.ch === "q")
134
+ return { ui, effect: { kind: "quit" } };
135
+ if (key.ch === "?")
136
+ return { ui: { ...ui, modal: { kind: "help" } } };
137
+ const n = Number(key.ch);
138
+ if (key.ch && n >= 1 && n <= SCREENS.length)
139
+ return { ui: clampSel({ ...ui, screen: SCREENS[n - 1] }, d) };
140
+ if (key.name === "tab") {
141
+ const i = SCREENS.indexOf(ui.screen);
142
+ const next = SCREENS[(i + (key.shift ? SCREENS.length - 1 : 1)) % SCREENS.length];
143
+ return { ui: clampSel({ ...ui, screen: next }, d) };
144
+ }
145
+ const move = (delta) => clampSel({ ...ui, sel: { ...ui.sel, [ui.screen]: ui.sel[ui.screen] + delta } }, d);
146
+ if (key.name === "up" || key.ch === "k")
147
+ return { ui: move(-1) };
148
+ if (key.name === "down" || key.ch === "j")
149
+ return { ui: move(1) };
150
+ if (key.name === "pageup")
151
+ return { ui: move(-page) };
152
+ if (key.name === "pagedown")
153
+ return { ui: move(page) };
154
+ if (key.name === "home" || key.ch === "g")
155
+ return { ui: move(-1e9) };
156
+ if (key.name === "end" || key.ch === "G")
157
+ return { ui: move(1e9) };
158
+ const sel = ui.sel[ui.screen];
159
+ switch (ui.screen) {
160
+ case "people": {
161
+ const it = peopleItems(d)[sel];
162
+ if (!it)
163
+ return { ui };
164
+ if (key.ch === "m" || key.name === "return") {
165
+ if (it.person.self && it.kind === "person")
166
+ return { ui: flash(ui, "Pick one of your sessions, or someone else.") };
167
+ const target = it.kind === "session" ? { label: `${it.person.address} [${it.session.ref}] ${it.session.label}`, to: `${it.person.userId} [${it.session.ref}]` } : { label: `${it.person.address} (any session)`, to: it.person.userId };
168
+ return { ui: { ...ui, screen: "send", compose: { target, text: "" } } };
169
+ }
170
+ if (key.ch === "d")
171
+ return { ui: { ...ui, screen: "health" }, effect: { kind: "doctor", user: it.person.self ? undefined : it.person.userId } };
172
+ return { ui };
173
+ }
174
+ case "held": {
175
+ const h = d.held[sel];
176
+ if (!h)
177
+ return { ui };
178
+ if (key.ch === "a") {
179
+ // A Codex release asks for the code its window shows; everything else confirms here.
180
+ if (h.source === "codex")
181
+ return { ui, effect: { kind: "codex-release", id: h.id } };
182
+ const what = h.type === "circle-join"
183
+ ? `Admit ${h.from} to your circle?`
184
+ : h.type === "invite"
185
+ ? `Accept the friend invite from ${h.from}? You will be friends.`
186
+ : h.type === "circle-invite"
187
+ ? `Join the circle ${h.from} invited you to?`
188
+ : `Act on the ${h.type} from ${h.from}?`;
189
+ return { ui: { ...ui, modal: { kind: "confirm", title: "Accept", lines: [what, h.summary], effect: { kind: "accept-item", id: h.id } } } };
190
+ }
191
+ if (key.ch === "x") {
192
+ return {
193
+ ui: {
194
+ ...ui,
195
+ modal: { kind: "confirm", title: "Decline", lines: [`Decline ${h.type} from ${h.from}?`], effect: h.source === "codex" ? { kind: "codex-decline", id: h.id } : { kind: "decline-item", id: h.id } },
196
+ },
197
+ };
198
+ }
199
+ if (key.ch === "t") {
200
+ if (h.source !== "codex")
201
+ return { ui: flash(ui, "Always deliver applies to held messages, not to invites or join requests.", true) };
202
+ const fp = h.from.split("@")[1] ?? "";
203
+ if (!/^[a-z2-7]{4}(-[a-z2-7]{4}){3}$/.test(fp))
204
+ return { ui: flash(ui, "That sender has no fingerprint to check: trust them from your terminal instead.", true) };
205
+ const word = fp.slice(0, 4);
206
+ return {
207
+ ui: {
208
+ ...ui,
209
+ modal: {
210
+ kind: "typed",
211
+ title: "Always deliver",
212
+ lines: [
213
+ `Always deliver messages from ${h.from}?`,
214
+ `Check the fingerprint with them, out of band: ${fp}`,
215
+ "Their messages then reach sessions that approve their own tool calls without the hold.",
216
+ "Trust only skips the hold: their messages are still their words, never your instructions.",
217
+ "",
218
+ `To trust them, type the fingerprint's first four characters (${word}) and press Enter. Esc cancels.`,
219
+ ],
220
+ word,
221
+ text: "",
222
+ effect: { kind: "trust-and-release", id: h.id, from: h.from },
223
+ },
224
+ },
225
+ };
226
+ }
227
+ return { ui };
228
+ }
229
+ case "messages": {
230
+ if (key.ch === "h") {
231
+ const next = clampSel({ ...ui, inboxOnly: !ui.inboxOnly }, d);
232
+ return { ui: flash(next, next.inboxOnly ? "Your inbox only: messages to you and this window's session." : "Every session on this device: your inbox and your agent sessions' messages.") };
233
+ }
234
+ const msg = messagesSorted(d, ui)[sel];
235
+ if (!msg)
236
+ return { ui };
237
+ if (key.name === "return" || key.name === "space") {
238
+ const head = msg.dir === "in" ? `From ${msg.who}${msg.ref ? ` [${msg.ref}]` : ""}` : `To ${msg.who}${msg.ref ? ` [${msg.ref}]` : ""}`;
239
+ // No receipt goes out from here: the TUI's session is private (see tui.ts).
240
+ return { ui: { ...ui, modal: { kind: "detail", title: head, lines: [msg.text] } } };
241
+ }
242
+ if (key.ch === "r" && msg.dir === "in" && msg.userId) {
243
+ const target = msg.ref ? { label: `${msg.who} [${msg.ref}]`, to: `${msg.userId} [${msg.ref}]` } : { label: `${msg.who} (any session)`, to: msg.userId };
244
+ return { ui: { ...ui, screen: "send", compose: { target, text: "" } } };
245
+ }
246
+ return { ui };
247
+ }
248
+ case "send": {
249
+ const t = sendTargets(d)[sel];
250
+ if (t && key.name === "return")
251
+ return { ui: { ...ui, compose: { target: t, text: "" } } };
252
+ return { ui };
253
+ }
254
+ case "health":
255
+ if (key.ch === "r")
256
+ return { ui, effect: { kind: "doctor" } };
257
+ return { ui };
258
+ }
259
+ }
@@ -0,0 +1,13 @@
1
+ /** Display width of one code point: 0 (combining), 2 (wide / emoji) or 1. */
2
+ export declare function cpWidth(cp: number): number;
3
+ export declare function displayWidth(s: string): number;
4
+ /** Peer-safe text: escapes and invisible or control characters removed, whitespace collapsed and trimmed. No width limit. */
5
+ export declare function clean(s: unknown): string;
6
+ /** clean() without the trim: the renderer's own spacing (" Peer2Peer ", "files: ") survives. */
7
+ export declare function cleanKeep(s: unknown): string;
8
+ /** clean(), then cut to `width` columns ("…" marks a cut). */
9
+ export declare function cell(s: unknown, width: number): string;
10
+ /** cell(), padded with spaces to exactly `width` columns. */
11
+ export declare function pad(s: unknown, width: number): string;
12
+ /** Word-wraps clean text into lines of at most `width` columns (at most `maxLines`, the last one cut). */
13
+ export declare function wrap(s: unknown, width: number, maxLines?: number): string[];
@@ -0,0 +1,151 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The TUI's one gate for text on its way to the terminal. Everything a peer
4
+ // controls (names, labels, statuses, file paths, message text, kinds, relay
5
+ // answers) and everything else too passes through cell() before the renderer
6
+ // sees it: the frame is built only from what this module returns.
7
+ //
8
+ // - Escape sequences (CSI, OSC including OSC 8 links, DCS/SOS/PM/APC, and
9
+ // their 8-bit C1 forms) are removed whole, then every remaining C0/C1
10
+ // control, DEL, line and paragraph separator, format character (bidi
11
+ // overrides and isolates, zero-width characters, tags), lone surrogate,
12
+ // noncharacter and invisible filler goes.
13
+ // - Line breaks and tabs become spaces; runs of whitespace collapse.
14
+ // - Private-use and unassigned code points become "?" (their width is unknown).
15
+ // - Combining marks are kept, at most two in a row (no "zalgo" towers).
16
+ // - The result is cut to a display width (wide CJK and emoji count two),
17
+ // with "…" when it was longer.
18
+ /** Whole escape sequences: CSI, OSC (BEL or ST terminated), DCS/SOS/PM/APC, two-byte ESC sequences; 7- and 8-bit forms. */
19
+ const ESCAPES = /(?:\u001b\[|\u009b)[ -?]*[@-~]?|(?:\u001b[\]P^_X]|[\u009d\u0090\u009e\u009f\u0098])[\s\S]*?(?:\u0007|\u001b\\|\u009c|$)|\u001b[ -/]*[0-~]?/g;
20
+ const BREAKS = /[\t\n\v\f\r\u0085\u2028\u2029]/g;
21
+ /** Controls, format characters (incl. bidi and zero-width), surrogates, noncharacters, invisible fillers. */
22
+ const STRIP = /[\u0000-\u001f\u007f-\u009fᅟᅠㅤᅠ-﷐-﷯￾￿]|͏|឴|឵|\p{Cf}|\p{Cs}/gu;
23
+ /** Private use and unassigned: rendered as "?". */
24
+ const UNKNOWN = /[\p{Co}\p{Cn}]/gu;
25
+ const MARK = /\p{M}/u;
26
+ /** Display width of one code point: 0 (combining), 2 (wide / emoji) or 1. */
27
+ export function cpWidth(cp) {
28
+ if (cp === 0x200d)
29
+ return 0;
30
+ if (MARK.test(String.fromCodePoint(cp)))
31
+ return 0;
32
+ if ((cp >= 0x1100 && cp <= 0x115f) ||
33
+ (cp >= 0x2e80 && cp <= 0x303e) ||
34
+ (cp >= 0x3041 && cp <= 0x33ff) ||
35
+ (cp >= 0x3400 && cp <= 0x4dbf) ||
36
+ (cp >= 0x4e00 && cp <= 0x9fff) ||
37
+ (cp >= 0xa000 && cp <= 0xa4cf) ||
38
+ (cp >= 0xac00 && cp <= 0xd7a3) ||
39
+ (cp >= 0xf900 && cp <= 0xfaff) ||
40
+ (cp >= 0xfe30 && cp <= 0xfe4f) ||
41
+ (cp >= 0xff00 && cp <= 0xff60) ||
42
+ (cp >= 0xffe0 && cp <= 0xffe6) ||
43
+ (cp >= 0x1f300 && cp <= 0x1f64f) ||
44
+ (cp >= 0x1f900 && cp <= 0x1f9ff) ||
45
+ (cp >= 0x1f680 && cp <= 0x1f6ff) ||
46
+ (cp >= 0x20000 && cp <= 0x3fffd)) {
47
+ return 2;
48
+ }
49
+ return 1;
50
+ }
51
+ export function displayWidth(s) {
52
+ let w = 0;
53
+ for (const ch of s)
54
+ w += cpWidth(ch.codePointAt(0));
55
+ return w;
56
+ }
57
+ /** Peer-safe text: escapes and invisible or control characters removed, whitespace collapsed and trimmed. No width limit. */
58
+ export function clean(s) {
59
+ return cleanKeep(s).trim();
60
+ }
61
+ /** clean() without the trim: the renderer's own spacing (" Peer2Peer ", "files: ") survives. */
62
+ export function cleanKeep(s) {
63
+ const str = typeof s === "string" ? s : s === undefined || s === null ? "" : String(s);
64
+ let out = str.replace(ESCAPES, "").replace(BREAKS, " ").replace(STRIP, "").replace(UNKNOWN, "?").replace(/\s+/gu, " ");
65
+ // At most two combining marks after a base character.
66
+ let marks = 0;
67
+ let kept = "";
68
+ for (const ch of out) {
69
+ if (MARK.test(ch)) {
70
+ if (++marks > 2)
71
+ continue;
72
+ }
73
+ else
74
+ marks = 0;
75
+ kept += ch;
76
+ }
77
+ out = kept;
78
+ // A leading combining mark would attach to whatever the renderer drew before it.
79
+ return out.replace(/^\p{M}+/u, "");
80
+ }
81
+ /** clean(), then cut to `width` columns ("…" marks a cut). */
82
+ export function cell(s, width) {
83
+ const t = cleanKeep(s);
84
+ if (width <= 0)
85
+ return "";
86
+ if (displayWidth(t) <= width)
87
+ return t;
88
+ let w = 0;
89
+ let out = "";
90
+ for (const ch of t) {
91
+ const cw = cpWidth(ch.codePointAt(0));
92
+ if (w + cw > width - 1)
93
+ break;
94
+ out += ch;
95
+ w += cw;
96
+ }
97
+ return `${out}…`;
98
+ }
99
+ /** cell(), padded with spaces to exactly `width` columns. */
100
+ export function pad(s, width) {
101
+ const t = cell(s, width);
102
+ return t + " ".repeat(Math.max(0, width - displayWidth(t)));
103
+ }
104
+ /** Word-wraps clean text into lines of at most `width` columns (at most `maxLines`, the last one cut). */
105
+ export function wrap(s, width, maxLines = 50) {
106
+ const t = clean(s);
107
+ if (width <= 0)
108
+ return [];
109
+ const lines = [];
110
+ let line = "";
111
+ for (const word of t.split(" ")) {
112
+ let w = word;
113
+ while (displayWidth(w) > width) {
114
+ // A word longer than the line: hard-cut it.
115
+ if (line) {
116
+ lines.push(line);
117
+ line = "";
118
+ }
119
+ let head = "";
120
+ let hw = 0;
121
+ const chars = [...w];
122
+ let i = 0;
123
+ for (; i < chars.length; i++) {
124
+ const cw = cpWidth(chars[i].codePointAt(0));
125
+ // Always at least one character per line (a wide one on a 1-column line), so this ends.
126
+ if (hw + cw > width && i > 0)
127
+ break;
128
+ head += chars[i];
129
+ hw += cw;
130
+ }
131
+ lines.push(head);
132
+ w = chars.slice(i).join("");
133
+ }
134
+ if (!line)
135
+ line = w;
136
+ else if (displayWidth(line) + 1 + displayWidth(w) <= width)
137
+ line += ` ${w}`;
138
+ else {
139
+ lines.push(line);
140
+ line = w;
141
+ }
142
+ }
143
+ if (line)
144
+ lines.push(line);
145
+ if (lines.length > maxLines) {
146
+ const cut = lines.slice(0, maxLines);
147
+ cut[maxLines - 1] = cell(`${cut[maxLines - 1]} ${lines[maxLines]}`, width);
148
+ return cut;
149
+ }
150
+ return lines;
151
+ }
@@ -0,0 +1,88 @@
1
+ import type { ReadStream, WriteStream } from "node:tty";
2
+ import type { Key } from "./model.js";
3
+ export interface Terminal {
4
+ readonly cols: number;
5
+ readonly rows: number;
6
+ readonly color: boolean;
7
+ enter(): void;
8
+ leave(): void;
9
+ write(s: string): void;
10
+ onKey(fn: (k: Key) => void): void;
11
+ onResize(fn: () => void): void;
12
+ }
13
+ /** NO_COLOR (any non-empty value) and TERM=dumb turn colour off; otherwise the terminal says. */
14
+ export declare function colorWanted(env: Record<string, string | undefined>, out: {
15
+ hasColors?: (n?: number) => boolean;
16
+ isTTY?: boolean;
17
+ }): boolean;
18
+ /** After a paste ends, keys this soon after it count as pasted too (a fake end marker inside the paste). */
19
+ export declare const PASTE_QUIET_MS = 150;
20
+ /** A paste, or a terminal answer, with no input for this long is over (its end marker never came). */
21
+ export declare const STUCK_MS = 1000;
22
+ /** A lone ESC with nothing after it for this long is the Escape key. */
23
+ export declare const ESC_MS = 50;
24
+ /**
25
+ * Splits raw input into keys, keeping state between chunks: a terminal's
26
+ * answer or a key's escape sequence split across reads is completed by the
27
+ * next one, never leaked as typed characters.
28
+ *
29
+ * - Escape sequences of the keys we use are recognised; any other escape
30
+ * or string sequence is dropped whole, however long (a string sequence
31
+ * is discarded up to its terminator, across chunks).
32
+ * - Text inside a bracketed paste comes through with `paste: true` (line
33
+ * breaks as spaces, controls dropped): the model types it only into a
34
+ * message or a prompt, never as command keys. For PASTE_QUIET_MS after
35
+ * a paste ends, keys still count as pasted: a paste carrying its own
36
+ * end marker (`ESC[201~ay`) can't press `a` or `y`.
37
+ * - Ctrl-C always gets through, even mid-paste or mid-answer: the way out.
38
+ * - Time-outs (idle(), called by the terminal after waitMs of no input): a
39
+ * lone ESC is the Escape key; a paste or answer whose end never came is
40
+ * over (STUCK_MS), so the TUI can't lock up.
41
+ */
42
+ export declare class KeyParser {
43
+ private readonly now;
44
+ private pending;
45
+ private pasting;
46
+ /** Inside a string sequence (OSC, DCS, ...) whose terminator hasn't come: dropping input. */
47
+ private discarding;
48
+ private quietUntil;
49
+ constructor(now?: () => number);
50
+ feed(chunk: string): Key[];
51
+ /** How long the terminal should wait for more input before calling idle() (0: no need). */
52
+ get waitMs(): number;
53
+ /** No more input came: a lone ESC is Escape, and a paste or answer whose end never came is over. */
54
+ idle(): Key[];
55
+ /** idle(), for callers that just want what's held. */
56
+ flush(): Key[];
57
+ get waiting(): boolean;
58
+ /**
59
+ * Text after a paste's start marker: the paste ends at its end marker (the rest is returned, to be
60
+ * read as keys), or waits for more (undefined). Ctrl-C before the end drops the paste and the rest
61
+ * of the read (undefined).
62
+ */
63
+ private paste;
64
+ private endPaste;
65
+ }
66
+ /** One chunk on its own (tests): parse, then flush. */
67
+ export declare function parseKeys(data: string): Key[];
68
+ export declare class TtyTerminal implements Terminal {
69
+ private readonly input;
70
+ private readonly output;
71
+ readonly color: boolean;
72
+ private active;
73
+ private readonly exitHook;
74
+ private keyFn?;
75
+ private readonly parser;
76
+ /** Multi-byte characters split across reads stay whole. */
77
+ private readonly decoder;
78
+ private escTimer?;
79
+ private readonly onData;
80
+ constructor(input: ReadStream, output: WriteStream, env: Record<string, string | undefined>);
81
+ get cols(): number;
82
+ get rows(): number;
83
+ enter(): void;
84
+ leave(): void;
85
+ write(s: string): void;
86
+ onKey(fn: (k: Key) => void): void;
87
+ onResize(fn: () => void): void;
88
+ }