t3code-session-manager 0.0.0-stage → 0.4.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 (172) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +19 -0
  3. package/CHANGELOG.md +138 -0
  4. package/LICENSE +21 -0
  5. package/README.md +660 -2
  6. package/README.pt.md +616 -0
  7. package/bin/entry.d.mts +2 -0
  8. package/bin/entry.mjs +19 -0
  9. package/bin/t3sm.mjs +44 -0
  10. package/commands/import.md +30 -0
  11. package/commands/organize.md +36 -0
  12. package/commands/status.md +24 -0
  13. package/commands/sync.md +26 -0
  14. package/dist/apply/apply.js +993 -0
  15. package/dist/apply/claudeWriter.js +168 -0
  16. package/dist/apply/copyTranscript.js +116 -0
  17. package/dist/apply/importer.js +697 -0
  18. package/dist/apply/materialize.js +335 -0
  19. package/dist/apply/waves.js +108 -0
  20. package/dist/assistant/core.js +295 -0
  21. package/dist/assistant/deps.js +256 -0
  22. package/dist/assistant/i18n.js +38 -0
  23. package/dist/assistant/messages.en.js +494 -0
  24. package/dist/assistant/messages.pt.js +495 -0
  25. package/dist/assistant/runner.js +64 -0
  26. package/dist/assistant/steps.js +1362 -0
  27. package/dist/build.json +1 -0
  28. package/dist/cli/applyScreen.js +158 -0
  29. package/dist/cli/commands/accounts.js +254 -0
  30. package/dist/cli/commands/apply.js +199 -0
  31. package/dist/cli/commands/changelog.js +61 -0
  32. package/dist/cli/commands/doctor.js +105 -0
  33. package/dist/cli/commands/help.js +158 -0
  34. package/dist/cli/commands/merge.js +224 -0
  35. package/dist/cli/commands/organize.js +872 -0
  36. package/dist/cli/commands/plan.js +161 -0
  37. package/dist/cli/commands/projects.js +430 -0
  38. package/dist/cli/commands/quarantine.js +203 -0
  39. package/dist/cli/commands/recover.js +230 -0
  40. package/dist/cli/commands/rollback.js +281 -0
  41. package/dist/cli/commands/scan.js +117 -0
  42. package/dist/cli/commands/schedule.js +288 -0
  43. package/dist/cli/commands/start.js +45 -0
  44. package/dist/cli/commands/status.js +615 -0
  45. package/dist/cli/commands/sync.js +336 -0
  46. package/dist/cli/commands/update.js +398 -0
  47. package/dist/cli/errors.js +53 -0
  48. package/dist/cli/failures.js +91 -0
  49. package/dist/cli/flags.js +53 -0
  50. package/dist/cli/help.en.js +549 -0
  51. package/dist/cli/help.pt.js +566 -0
  52. package/dist/cli/helpText.js +211 -0
  53. package/dist/cli/helpTopics.js +58 -0
  54. package/dist/cli/locked.js +12 -0
  55. package/dist/cli/main.js +155 -0
  56. package/dist/cli/screen.js +3 -0
  57. package/dist/cli/ui.js +111 -0
  58. package/dist/cli/words.js +2 -0
  59. package/dist/core/activity.js +16 -0
  60. package/dist/core/changelog.js +47 -0
  61. package/dist/core/config.js +530 -0
  62. package/dist/core/fsutil.js +171 -0
  63. package/dist/core/glob.js +34 -0
  64. package/dist/core/history.js +32 -0
  65. package/dist/core/journal.js +274 -0
  66. package/dist/core/lock.js +337 -0
  67. package/dist/core/mask.js +31 -0
  68. package/dist/core/paths.js +68 -0
  69. package/dist/core/pid.js +101 -0
  70. package/dist/core/run.js +4 -0
  71. package/dist/core/semver.js +18 -0
  72. package/dist/core/sysroot.js +29 -0
  73. package/dist/core/types.js +229 -0
  74. package/dist/core/uuid.js +29 -0
  75. package/dist/core/version.js +72 -0
  76. package/dist/help/convert.md +20 -0
  77. package/dist/help/convert.pt.md +21 -0
  78. package/dist/help/cwd-unreadable.md +22 -0
  79. package/dist/help/cwd-unreadable.pt.md +22 -0
  80. package/dist/help/decisions.md +20 -0
  81. package/dist/help/decisions.pt.md +20 -0
  82. package/dist/help/errors.md +20 -0
  83. package/dist/help/errors.pt.md +22 -0
  84. package/dist/help/held.md +20 -0
  85. package/dist/help/held.pt.md +20 -0
  86. package/dist/help/history.md +27 -0
  87. package/dist/help/history.pt.md +29 -0
  88. package/dist/help/instance-unavailable.md +18 -0
  89. package/dist/help/instance-unavailable.pt.md +19 -0
  90. package/dist/help/not-imported.md +19 -0
  91. package/dist/help/not-imported.pt.md +19 -0
  92. package/dist/help/orphaned.md +19 -0
  93. package/dist/help/orphaned.pt.md +19 -0
  94. package/dist/help/project-mismatch.md +15 -0
  95. package/dist/help/project-mismatch.pt.md +15 -0
  96. package/dist/help/t3-native.md +22 -0
  97. package/dist/help/t3-native.pt.md +22 -0
  98. package/dist/help/updates.md +26 -0
  99. package/dist/help/updates.pt.md +28 -0
  100. package/dist/help/watcher.md +24 -0
  101. package/dist/help/watcher.pt.md +25 -0
  102. package/dist/i18n/cli.js +41 -0
  103. package/dist/i18n/lang.js +55 -0
  104. package/dist/i18n/messages.en.js +1140 -0
  105. package/dist/i18n/messages.pt.js +1149 -0
  106. package/dist/i18n/words.js +12 -0
  107. package/dist/ops/accounts.js +170 -0
  108. package/dist/ops/autoUpdate.js +223 -0
  109. package/dist/ops/discoverAccounts.js +343 -0
  110. package/dist/ops/doctor.js +811 -0
  111. package/dist/ops/elevated.js +47 -0
  112. package/dist/ops/errorCodes.js +39 -0
  113. package/dist/ops/follow.js +558 -0
  114. package/dist/ops/merge.js +830 -0
  115. package/dist/ops/notify.js +249 -0
  116. package/dist/ops/plugin.js +92 -0
  117. package/dist/ops/projects.js +113 -0
  118. package/dist/ops/quarantine.js +415 -0
  119. package/dist/ops/rollback.js +868 -0
  120. package/dist/ops/schedule.js +464 -0
  121. package/dist/ops/successor.js +51 -0
  122. package/dist/ops/sync.js +859 -0
  123. package/dist/ops/syncStatus.js +290 -0
  124. package/dist/ops/update.js +273 -0
  125. package/dist/ops/updater.js +641 -0
  126. package/dist/ops/watch.js +676 -0
  127. package/dist/ops/watcherControl.js +212 -0
  128. package/dist/ops/watcherHealth.js +75 -0
  129. package/dist/organize/apply.js +495 -0
  130. package/dist/organize/history.js +192 -0
  131. package/dist/organize/plan.js +283 -0
  132. package/dist/organize/rename.js +58 -0
  133. package/dist/organize/sessions.js +100 -0
  134. package/dist/organize/titles.js +70 -0
  135. package/dist/organize/types.js +73 -0
  136. package/dist/plan/categories.js +104 -0
  137. package/dist/plan/dedupe.js +137 -0
  138. package/dist/plan/folders.js +82 -0
  139. package/dist/plan/names.js +93 -0
  140. package/dist/plan/ownership.js +316 -0
  141. package/dist/plan/planner.js +669 -0
  142. package/dist/plan/rehome.js +101 -0
  143. package/dist/plan/report.js +407 -0
  144. package/dist/sources/cache.js +89 -0
  145. package/dist/sources/claude.js +297 -0
  146. package/dist/sources/codex.js +496 -0
  147. package/dist/sources/flatten.js +23 -0
  148. package/dist/sources/jsonl.js +169 -0
  149. package/dist/sources/native.js +233 -0
  150. package/dist/sources/opencode.js +483 -0
  151. package/dist/sources/pi.js +133 -0
  152. package/dist/sources/registry.js +67 -0
  153. package/dist/sources/types.js +80 -0
  154. package/dist/t3/api.js +492 -0
  155. package/dist/t3/auth.js +248 -0
  156. package/dist/t3/compat.js +62 -0
  157. package/dist/t3/decode.js +408 -0
  158. package/dist/t3/errors.js +185 -0
  159. package/dist/t3/rpc.js +185 -0
  160. package/dist/t3/runtime.js +80 -0
  161. package/dist/ui/caps.js +56 -0
  162. package/dist/ui/components.js +202 -0
  163. package/dist/ui/layout.js +205 -0
  164. package/dist/ui/list.js +423 -0
  165. package/dist/ui/locale.js +73 -0
  166. package/dist/ui/organizePreview.js +72 -0
  167. package/dist/ui/progress.js +237 -0
  168. package/dist/ui/style.js +32 -0
  169. package/dist/ui/terminal.js +126 -0
  170. package/dist/ui/text.js +186 -0
  171. package/package.json +58 -4
  172. package/skills/t3code-sessions/SKILL.md +183 -0
@@ -0,0 +1,205 @@
1
+ // Small layout helpers the command screens share on top of the UI kit (src/ui/components.ts): a line that may be wider
2
+ // than the window is wrapped (its styling dropped, as the components do), and a lead line is a symbol plus a word.
3
+
4
+
5
+ import { kv, table, } from "./components.js";
6
+ import { displayWidth, stripAnsi, truncateEnd, wrapText } from "./text.js";
7
+
8
+ /** `line` as it is when it fits `width`, else wrapped plain (continuation lines indented by `hang`). */
9
+ export function fitLine(line , width , hang = 0) {
10
+ const w = Math.max(1, width);
11
+ if (displayWidth(line) <= w) return [line];
12
+ const plain = stripAnsi(line).replace(/[\r\n\t]+/g, " ");
13
+ // A leading indent stays on every line (when it leaves room to wrap in).
14
+ const lead = /^ */.exec(plain) [0].length;
15
+ const ind = lead > 0 && w - lead >= 8 ? lead : 0;
16
+ return wrapText(plain.slice(ind), w - ind, { hang: Math.min(hang, Math.max(0, w - ind - 2)) }).map((l) => (" ".repeat(ind) + l).replace(/ +$/, ""));
17
+ }
18
+
19
+ /** Every line fitted to `width`. */
20
+ export function fitAll(lines , width , hang = 0) {
21
+ return lines.flatMap((l) => fitLine(l, width, hang));
22
+ }
23
+
24
+ /**
25
+ * `✓ All good · t3sm does not need anything from you`: the symbol and the word in the tone, then a muted note on the
26
+ * same line when it fits; on a narrow window the note goes on the lines below, indented under the word and wrapped,
27
+ * never cut.
28
+ */
29
+ export function leadLines(s , o , width ) {
30
+ const w = Math.max(1, width);
31
+ const head = `${o.sym} ${o.word}`;
32
+ if (displayWidth(head) >= w) return [s(o.tone, truncateEnd(head, w, s.sym.ellipsis))];
33
+ const first = s(o.tone, o.sym) + " " + s("title", o.word);
34
+ if (!o.note) return [first];
35
+ const sep = ` ${s.sym.sep} `;
36
+ if (displayWidth(head) + displayWidth(sep) + displayWidth(o.note) <= w) return [first + s("muted", sep + o.note)];
37
+ const hang = displayWidth(`${o.sym} `);
38
+ return [first, ...wrapText(o.note, Math.max(1, w - hang)).map((l) => " ".repeat(hang) + s("muted", l))];
39
+ }
40
+
41
+ /**
42
+ * Atoms laid out to `width`, one space between them: an atom (a command, a help topic) is never split across lines, a
43
+ * continuation line is indented by `hang`. Only an atom wider than a whole line is broken (plain).
44
+ */
45
+ export function flowAtoms(atoms , width , hang = 2) {
46
+ const w = Math.max(1, width);
47
+ const h = Math.min(Math.max(0, hang), Math.max(0, w - 2));
48
+ const out = [];
49
+ let line = "";
50
+ for (const a of atoms) {
51
+ if (a === "") continue;
52
+ if (line !== "" && line.trim() !== "" && displayWidth(line) + 1 + displayWidth(a) <= w) { line += " " + a; continue; }
53
+ if (line.trim() !== "") { out.push(line); line = " ".repeat(h); }
54
+ if (displayWidth(line) + displayWidth(a) <= w) { line += a; continue; }
55
+ // Wider than a line: broken plain, the rest continues after it.
56
+ const pieces = wrapText(stripAnsi(a), Math.max(1, w - displayWidth(line)));
57
+ line += pieces[0] ;
58
+ for (const p of pieces.slice(1)) { out.push(line); line = " ".repeat(h) + p; }
59
+ }
60
+ if (line.trim() !== "") out.push(line);
61
+ return out.map((l) => l.replace(/ +$/, ""));
62
+ }
63
+
64
+ /**
65
+ * Text with `backticked` commands as atoms: the words, and each command whole and in the `key` style, without its
66
+ * backticks (punctuation right after a command stays with it).
67
+ */
68
+ export function richAtoms(s , text ) {
69
+ const atoms = [];
70
+ const parts = text.split(/`([^`]*)`/);
71
+ parts.forEach((part, i) => {
72
+ if (i % 2 === 1) {
73
+ // Punctuation right before a command stays with it too ("(`t3sm runs`)").
74
+ if (atoms.length > 0 && parts[i - 1] !== "" && !/\s$/.test(parts[i - 1] )) atoms[atoms.length - 1] += s("key", part);
75
+ else atoms.push(s("key", part));
76
+ return;
77
+ }
78
+ const glue = atoms.length > 0 && part !== "" && !/^\s/.test(part);
79
+ const words = part.split(/\s+/).filter((x) => x !== "");
80
+ if (glue && words.length > 0) atoms[atoms.length - 1] += words.shift() ;
81
+ atoms.push(...words);
82
+ });
83
+ return atoms;
84
+ }
85
+
86
+ /** A panel as wide as its content (title and body) needs, up to `width`: no wide empty block beside short rows. */
87
+ export function snugWidth(title , body , width ) {
88
+ const content = Math.max(0, ...body.map(displayWidth)) + 4;
89
+ const head = displayWidth(title) + 8;
90
+ return Math.max(1, Math.min(width, Math.max(content, head, 24)));
91
+ }
92
+
93
+ /**
94
+ * Atoms (styled words, commands) wrapped greedily: the first line holds at most `first` cells, every other `rest`. An
95
+ * atom is never split unless it is wider than a whole line: a command then wraps at its own spaces (plain, each word
96
+ * whole: `t3sm rollback --run <id>` never cuts the run id), and only a single word wider than a line is broken. Lines
97
+ * carry no indent and no trailing space; the caller indents them.
98
+ */
99
+ export function wrapAtoms(atoms , first , rest ) {
100
+ const out = [];
101
+ let line = "";
102
+ const room = () => Math.max(1, out.length === 0 ? first : rest);
103
+ const queue = [...atoms];
104
+ while (queue.length > 0) {
105
+ const a = queue.shift() ;
106
+ if (a === "") continue;
107
+ if (line !== "" && displayWidth(line) + 1 + displayWidth(a) <= room()) { line += " " + a; continue; }
108
+ if (displayWidth(a) > room() && /\S\s+\S/.test(stripAnsi(a))) {
109
+ // A command wider than a line: its words, plain, wrapped like the others (the first may still join this line).
110
+ queue.unshift(...stripAnsi(a).trim().split(/\s+/));
111
+ continue;
112
+ }
113
+ if (line !== "") { out.push(line); line = ""; }
114
+ if (displayWidth(a) <= room()) { line = a; continue; }
115
+ // Wider than a line: broken plain; what is left continues after it.
116
+ let rem = stripAnsi(a);
117
+ while (displayWidth(rem) > room()) {
118
+ const piece = truncateEnd(rem, room(), "") || [...rem][0] ;
119
+ out.push(piece);
120
+ rem = rem.slice(piece.length);
121
+ }
122
+ line = rem;
123
+ }
124
+ if (line !== "") out.push(line);
125
+ return out.map((l) => l.replace(/ +$/, ""));
126
+ }
127
+
128
+ /** A bullet: ` • text`, wrapped with the text hanging under itself; `backticked` commands stay whole, in the key style. */
129
+ export function bulletLines(s , text , width , indent = 2) {
130
+ const lead = " ".repeat(indent) + s.sym.bullet + " ";
131
+ const hang = displayWidth(lead);
132
+ return wrapAtoms(richAtoms(s, text), width - hang, width - hang).map((l, i) => (i === 0 ? s("muted", lead) : " ".repeat(hang)) + l);
133
+ }
134
+
135
+ /**
136
+ * A titled list: "Title (n)" in bold, then each item as a bullet; at most `max` items (default 50), then "… and N
137
+ * more" (`more`, already worded in the user's language). An empty list gives no lines.
138
+ */
139
+ export function sectionLines(s , title , items , width , o = {}) {
140
+ if (items.length === 0) return [];
141
+ const max = o.max ?? 50;
142
+ const out = fitLine(s("title", `${title} (${items.length})`), width, 2);
143
+ for (const x of items.slice(0, max)) out.push(...bulletLines(s, x, width));
144
+ if (items.length > max) out.push(...fitLine(s("muted", ` ${s.sym.ellipsis} ${o.more ? o.more(items.length - max) : `+${items.length - max}`}`), width, 4));
145
+ return out;
146
+ }
147
+
148
+ /** One statement with its symbol (✓ done, ! warning, ✗ failed, › next), wrapped; `backticked` commands in the key style. */
149
+ export function noteLines(s , tone , text , width ) {
150
+ const sym = tone === "ok" ? s("ok", s.sym.ok) : tone === "warn" ? s("warn", s.sym.warn) : tone === "err" ? s("err", s.sym.err) : s("accent", s.sym.arrow);
151
+ return wrapAtoms(richAtoms(s, text), width - 2, width - 2).map((l, i) => (i === 0 ? sym + " " : " ") + l);
152
+ }
153
+
154
+ /**
155
+ * `prefix` then `text` (a path: no spaces to wrap at), broken wherever the width ends; continuation lines are indented
156
+ * by `hang`. Used where a path must be shown whole.
157
+ */
158
+ export function hardLines(prefix , text , width , hang ) {
159
+ const out = [];
160
+ let line = prefix;
161
+ for (const ch of text) {
162
+ if (displayWidth(line) + displayWidth(ch) > Math.max(hang + 1, width)) { out.push(line); line = " ".repeat(hang); }
163
+ line += ch;
164
+ }
165
+ out.push(line);
166
+ return out;
167
+ }
168
+
169
+ /** Plain text wrapped to `width` (commands in the key style), no symbol. */
170
+ export function textLines(s , text , width , indent = 0) {
171
+ return wrapAtoms(richAtoms(s, text), width - indent, width - indent).map((l) => " ".repeat(indent) + l);
172
+ }
173
+
174
+ /** Every spelling of the home folder in `text` (either separator, any case) shown as `~`: shorter, and no user name. */
175
+ export function homeAsTilde(text , home ) {
176
+ const h = home.replace(/[\\/]+$/, "");
177
+ if (h === "") return text;
178
+ const esc = (v ) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
179
+ const variants = [...new Set([h, h.replace(/\\/g, "/"), h.replace(/\//g, "\\")])].map(esc);
180
+ // Followed by a separator, the end, or anything that ends a word (a quote, a bracket, a space): never a longer name.
181
+ return text.replace(new RegExp(`(?:${variants.join("|")})(?=[\\\\/]|\\b|$)`, "gi"), "~");
182
+ }
183
+
184
+ /**
185
+ * Rows as a table when it fits, else one block per row (its first column as the heading, the others as aligned
186
+ * "header value" rows), so a narrow window never cuts a value or loses a column. It fits when every column has its
187
+ * full width, or, with `allowMin`, its `min` (only for a column whose cut is harmless, such as a path cut in the
188
+ * middle: the table shrinks it).
189
+ */
190
+ export function tableOrBlocks(s , cols , rows , width , o = {}) {
191
+ const w = Math.max(1, width);
192
+ const need = cols.reduce((n, c) => {
193
+ const natural = Math.max(displayWidth(c.header), ...rows.map((r) => displayWidth(c.get(r))));
194
+ return n + (o.allowMin && c.min !== undefined ? Math.min(natural, c.min) : natural) + 2;
195
+ }, -2);
196
+ if (need <= w) return table(s, cols, rows, w);
197
+ const out = [];
198
+ for (const r of rows) {
199
+ if (out.length > 0) out.push("");
200
+ const [head, ...rest] = cols;
201
+ out.push(...fitLine(s("title", head .get(r)), w, 2));
202
+ out.push(...kv(s, rest.filter((c) => c.header !== "" && c.get(r) !== "").map((c) => [c.header, c.get(r)]), Math.max(1, w - 2)).map((l) => " " + l));
203
+ }
204
+ return out;
205
+ }
@@ -0,0 +1,423 @@
1
+ // The review list: long lists (folders to decide, conversations to move, project names, organize changes) reviewed
2
+ // with the keys instead of typed numbers. Zero dependencies, driven through an injectable Term. Without a terminal
3
+ // (or with `plain`) the same decisions are taken from numbered lines.
4
+ //
5
+ // Every caller string (label, detail, meta, prompts, edited values) is untrusted text: it goes through `shownText`
6
+ // once, before anything is drawn, so no escape or bidi character reaches the terminal. Per frame only one page of
7
+ // lines is built, and a filter keystroke is one pass over the items (lower-cased text is kept from the start).
8
+
9
+ import { CATALOGUES, fmt, wrap, } from "../assistant/i18n.js";
10
+ import { cleanText, shownText } from "../plan/names.js";
11
+
12
+ import { wrapTo } from "./text.js";
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+ /** Work counters for tests (rows per frame, filter passes), never wall-clock time. */
22
+
23
+
24
+
25
+
26
+ const MIN_WIDTH = 40;
27
+ /** Lines of a frame that are not list rows: title, help, status, two detail lines, footer, one spare. */
28
+ const CHROME = 7;
29
+ const HIDE = "\x1b[?25l";
30
+ const SHOW = "\x1b[?25h";
31
+ const ERASE_LINE = "\x1b[2K";
32
+ const ERASE_BELOW = "\x1b[J";
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+ export async function reviewList(term , o ) {
45
+ const m = CATALOGUES[o.lang];
46
+ const rows = o.items.map((it) => {
47
+ if (o.stats) o.stats.sanitized++;
48
+ const value = it.editable ? it.editable.value : null;
49
+ const label = shownText(it.label);
50
+ const detail = shownText(it.detail);
51
+ return {
52
+ src: it, checked: it.checked, value, label, detail, meta: shownText(it.meta ?? ""),
53
+ shownValue: value === null ? "" : shownText(value), prompt: it.editable ? shownText(it.editable.prompt) : "",
54
+ choices: it.editable?.choices?.map((c) => shownText(c)) ?? [],
55
+ hay: `${label}\n${detail}`.toLowerCase(),
56
+ };
57
+ });
58
+ const result = (confirmed ) => ({
59
+ confirmed,
60
+ items: rows.map((r) => {
61
+ const out = { ...r.src, checked: confirmed ? r.checked : r.src.checked };
62
+ if (r.src.editable) out.editable = { ...r.src.editable, value: confirmed && r.value !== null ? r.value : r.src.editable.value };
63
+ return out;
64
+ }),
65
+ });
66
+ const ctx = { term, m, title: shownText(o.title), help: shownText(o.help), rows, stats: o.stats };
67
+ return o.plain || !term.isTTY ? plainList(ctx) : interactiveList(ctx, result);
68
+ }
69
+
70
+
71
+
72
+ // ---------------- interactive ----------------
73
+
74
+
75
+
76
+ const isPrintable = (k ) => k.ch !== "" && !k.ctrl && !k.meta && k.ch >= " " && k.ch !== "";
77
+
78
+ /** At most `w` columns: cut with an ellipsis. */
79
+ function clip(s , w , ell ) {
80
+ const cs = Array.from(s);
81
+ if (cs.length <= w) return s;
82
+ if (w <= ell.length) return cs.slice(0, w).join("");
83
+ return cs.slice(0, w - ell.length).join("") + ell;
84
+ }
85
+
86
+ async function interactiveList(c , result ) {
87
+ const { term, rows } = c;
88
+ const uni = term.unicode;
89
+ const sym = { on: uni ? "[✓]" : "[x]", off: "[ ]", cur: uni ? "›" : ">", ell: uni ? "…" : "...", arrow: uni ? "→" : "->" };
90
+ const paint = (s , code ) => (term.color ? `\x1b[${code}m${s}\x1b[0m` : s);
91
+
92
+ let mode = "list";
93
+ let filter = "";
94
+ let vis = rows.map((_, i) => i);
95
+ let cursor = 0;
96
+ let top = 0;
97
+ let buf = "";
98
+ let choice = 0;
99
+ let note = "";
100
+ let prevLines = 0;
101
+ let done = false;
102
+ const sub = {};
103
+
104
+ const width = () => Math.max(MIN_WIDTH, term.columns);
105
+ const pageSize = () => Math.max(3, term.rows - CHROME);
106
+ const cur = () => (vis[cursor] === undefined ? undefined : rows[vis[cursor] ]);
107
+
108
+ /** One pass over every row; the cursor stays on the same row when it is still shown. */
109
+ const refilter = (text ) => {
110
+ const keep = vis[cursor];
111
+ const q = text.toLowerCase();
112
+ if (c.stats) c.stats.filterPasses++;
113
+ const next = [];
114
+ for (let i = 0; i < rows.length; i++) {
115
+ if (c.stats) c.stats.filterVisits++;
116
+ if (q === "" || rows[i] .hay.includes(q)) next.push(i);
117
+ }
118
+ vis = next;
119
+ const at = keep === undefined ? -1 : vis.indexOf(keep);
120
+ cursor = at >= 0 ? at : 0;
121
+ top = 0;
122
+ };
123
+ const move = (to ) => { cursor = Math.max(0, Math.min(vis.length - 1, to)); };
124
+ const marked = () => rows.reduce((n, r) => n + (r.checked ? 1 : 0), 0);
125
+
126
+ const rowLine = (r , selected , w ) => {
127
+ const prefix = `${selected ? sym.cur : " "} ${r.checked ? sym.on : sym.off} `;
128
+ const text = r.value !== null ? `${r.label} ${sym.arrow} ${r.shownValue}` : r.label;
129
+ const avail = w - 1 - Array.from(prefix).length;
130
+ let body ;
131
+ if (r.meta !== "" && Array.from(text).length + 2 + Array.from(r.meta).length <= avail) {
132
+ body = text + " ".repeat(avail - Array.from(text).length - Array.from(r.meta).length) + r.meta;
133
+ } else if (r.meta !== "" && avail - Array.from(r.meta).length - 2 >= 10) {
134
+ body = clip(text, avail - Array.from(r.meta).length - 2, sym.ell) + " " + r.meta;
135
+ } else body = clip(text, avail, sym.ell);
136
+ const line = prefix + body;
137
+ return selected ? paint(line, "7") : line;
138
+ };
139
+
140
+ const footer = (w ) => {
141
+ const full = c.m.listFooter;
142
+ return Array.from(full).length <= w - 1 ? full : c.m.listFooterShort;
143
+ };
144
+
145
+ const frame = () => {
146
+ const w = width();
147
+ const line = (s ) => clip(s, w - 1, sym.ell);
148
+ const L = [];
149
+ if (mode === "help") {
150
+ L.push(paint(line(c.m.listHelpTitle), "1"));
151
+ for (const l of wrap(c.m.listHelpBody, w - 3)) L.push(line(` ${l}`));
152
+ L.push(paint(line(c.m.listAnyKey), "2"));
153
+ return L;
154
+ }
155
+ const ps = pageSize();
156
+ L.push(paint(line(c.title), "1"));
157
+ L.push(paint(line(c.help), "2"));
158
+
159
+ // status line
160
+ let status ;
161
+ if (mode === "filter") status = `${c.m.listFilterPrompt}: ${shownText(buf)}_`;
162
+ else if (mode === "edit") status = `${cur()?.prompt ?? ""}: ${shownText(buf)}_`;
163
+ else if (mode === "choice") status = cur()?.prompt ?? "";
164
+ else {
165
+ status = filter === "" ? fmt(c.m.listStatus, { marked: marked(), total: rows.length })
166
+ : `${fmt(c.m.listStatusFiltered, { marked: marked(), total: rows.length, shown: vis.length })} (${c.m.listFilterPrompt}: ${shownText(filter)})`;
167
+ if (note !== "") status = note;
168
+ }
169
+ L.push(line(status));
170
+
171
+ // the page of lines
172
+ let drawn = 0;
173
+ if (mode === "choice") {
174
+ const r = cur();
175
+ const cs = r?.choices ?? [];
176
+ const from = choice >= ps ? choice - ps + 1 : 0;
177
+ for (let i = from; i < Math.min(cs.length, from + ps); i++) {
178
+ const l = `${i === choice ? sym.cur : " "} ${cs[i] }`;
179
+ L.push(line(i === choice ? paint(l, "7") : l));
180
+ drawn++;
181
+ }
182
+ } else if (rows.length === 0) {
183
+ L.push(line(c.m.listEmpty));
184
+ } else if (vis.length === 0) {
185
+ L.push(line(c.m.listNoMatches));
186
+ } else {
187
+ if (cursor < top) top = cursor;
188
+ if (cursor >= top + ps) top = cursor - ps + 1;
189
+ const end = Math.min(vis.length, top + ps);
190
+ for (let i = top; i < end; i++) { L.push(rowLine(rows[vis[i] ] , i === cursor, w)); drawn++; }
191
+ }
192
+ if (c.stats) { c.stats.frames++; c.stats.rowsRendered += drawn; c.stats.maxRowsInFrame = Math.max(c.stats.maxRowsInFrame, drawn); }
193
+
194
+ // detail of the selected line, or the hint of the current mode
195
+ if (mode === "list") {
196
+ const r = cur();
197
+ if (r !== undefined && r.detail !== "") {
198
+ const parts = wrap(r.detail, w - 3);
199
+ const shown = parts.slice(0, 2).map((p, i) => (i === 1 && parts.length > 2 ? p + sym.ell : p));
200
+ for (const p of shown) L.push(paint(line(` ${p}`), "2"));
201
+ }
202
+ } else {
203
+ const hint = mode === "filter" ? c.m.listFilterHint : mode === "edit" ? c.m.listEditHint : c.m.listChoiceHint;
204
+ L.push(paint(line(` ${hint}`), "2"));
205
+ }
206
+ L.push(paint(line(footer(w)), "2"));
207
+ return L;
208
+ };
209
+
210
+ const draw = () => {
211
+ const lines = frame();
212
+ const up = prevLines > 1 ? `\x1b[${prevLines - 1}A` : "";
213
+ term.write((prevLines > 0 ? `\r${up}` : "") + lines.map((l) => ERASE_LINE + l).join("\n") + ERASE_BELOW);
214
+ prevLines = lines.length;
215
+ };
216
+
217
+ const erase = () => {
218
+ if (prevLines === 0) return;
219
+ const up = prevLines > 1 ? `\x1b[${prevLines - 1}A` : "";
220
+ term.write(`\r${up}${ERASE_BELOW}`);
221
+ prevLines = 0;
222
+ };
223
+
224
+ const startEdit = () => {
225
+ const r = cur();
226
+ note = "";
227
+ if (r === undefined || r.value === null) { note = c.m.listNoEdit; return; }
228
+ if (r.choices.length > 0) {
229
+ const at = (r.src.editable .choices ?? []).indexOf(r.value);
230
+ choice = at >= 0 ? at : 0;
231
+ mode = "choice";
232
+ } else { buf = r.shownValue; mode = "edit"; }
233
+ };
234
+
235
+ /** Returns the result when the key ends the list. */
236
+ const onKey = (k ) => {
237
+ if (k.ctrl && k.name === "c") return result(false);
238
+ if (mode === "help") { mode = "list"; return null; }
239
+ if (mode === "filter") {
240
+ if (k.name === "return") { filter = buf; mode = "list"; }
241
+ else if (k.name === "escape") { filter = ""; buf = ""; refilter(""); mode = "list"; }
242
+ else if (k.name === "backspace") { buf = Array.from(buf).slice(0, -1).join(""); refilter(buf); }
243
+ else if (isPrintable(k)) { buf += k.ch; refilter(buf); }
244
+ return null;
245
+ }
246
+ if (mode === "edit") {
247
+ const r = cur();
248
+ if (k.name === "return") {
249
+ const v = cleanText(buf);
250
+ if (r !== undefined && v !== "") { r.value = v; r.shownValue = shownText(v); }
251
+ mode = "list";
252
+ } else if (k.name === "escape") mode = "list";
253
+ else if (k.name === "backspace") buf = Array.from(buf).slice(0, -1).join("");
254
+ else if (isPrintable(k)) buf += k.ch;
255
+ return null;
256
+ }
257
+ if (mode === "choice") {
258
+ const r = cur();
259
+ const n = r?.choices.length ?? 0;
260
+ if (k.name === "up") choice = Math.max(0, choice - 1);
261
+ else if (k.name === "down") choice = Math.min(n - 1, choice + 1);
262
+ else if (k.name === "return") {
263
+ const v = r?.src.editable?.choices?.[choice];
264
+ if (r !== undefined && v !== undefined) { r.value = v; r.shownValue = r.choices[choice] ; }
265
+ mode = "list";
266
+ } else if (k.name === "escape") mode = "list";
267
+ return null;
268
+ }
269
+ // list
270
+ note = "";
271
+ const ps = pageSize();
272
+ if (k.ctrl || k.meta) return null;
273
+ switch (k.name) {
274
+ case "up": move(cursor - 1); return null;
275
+ case "down": move(cursor + 1); return null;
276
+ case "pageup": move(cursor - ps); return null;
277
+ case "pagedown": move(cursor + ps); return null;
278
+ case "home": move(0); return null;
279
+ case "end": move(vis.length - 1); return null;
280
+ case "space": { const r = cur(); if (r) r.checked = !r.checked; return null; }
281
+ case "return": return result(true);
282
+ case "escape": return result(false);
283
+ default: break;
284
+ }
285
+ switch (k.ch) {
286
+ case "k": move(cursor - 1); break;
287
+ case "j": move(cursor + 1); break;
288
+ case "a": for (const i of vis) rows[i] .checked = true; break;
289
+ case "n": for (const i of vis) rows[i] .checked = false; break;
290
+ case "e": startEdit(); break;
291
+ case "/": buf = ""; mode = "filter"; break;
292
+ case "?": mode = "help"; break;
293
+ case "q": return result(false);
294
+ default: break;
295
+ }
296
+ return null;
297
+ };
298
+
299
+ term.setRaw(true);
300
+ try {
301
+ term.write(HIDE);
302
+ return await new Promise ((resolve, reject) => {
303
+ const finish = (r ) => { if (!done) { done = true; resolve(r); } };
304
+ const fail = (e ) => { if (!done) { done = true; reject(e); } };
305
+ sub.off = term.onKey((k) => {
306
+ if (done) return;
307
+ try {
308
+ const r = onKey(k);
309
+ if (r) finish(r); else draw();
310
+ } catch (e) { fail(e); }
311
+ }, () => finish(result(false))); // input closed: cancel
312
+ try { draw(); } catch (e) { fail(e); }
313
+ });
314
+ } finally {
315
+ done = true;
316
+ try { sub.off?.(); } catch { /* keep restoring */ }
317
+ try { erase(); } catch { /* the terminal may be gone; the cursor and raw mode still go back */ }
318
+ try { term.write(SHOW); } catch { /* same */ }
319
+ term.setRaw(false);
320
+ }
321
+ }
322
+
323
+ // ---------------- plain (no terminal, or --plain) ----------------
324
+
325
+ /** "2 5-7" -> [2, 5, 6, 7]; null when a token is not a number or a range inside 1..max. */
326
+ function parseNumbers(text , max ) {
327
+ const out = [];
328
+ for (const tok of text.split(/[\s,]+/).filter((t) => t !== "")) {
329
+ const mm = /^(\d+)(?:-(\d+))?$/.exec(tok);
330
+ if (!mm) return null;
331
+ const a = Number(mm[1]);
332
+ const b = mm[2] === undefined ? a : Number(mm[2]);
333
+ if (a < 1 || b > max || a > b) return null;
334
+ for (let i = a; i <= b; i++) out.push(i);
335
+ }
336
+ return out;
337
+ }
338
+
339
+ async function plainList(c ) {
340
+ const { term, m, rows } = c;
341
+ // Every line fits the terminal: a longer one is wrapped, its continuation under its text (a narrow window, a pipe).
342
+ const cols = () => Math.max(1, Math.floor(term.columns) || 80);
343
+ const fit = (s ) => {
344
+ // A numbered line ("1. [x] label") hangs under its label; anything else as wrapTo does it.
345
+ const item = /^ *\d+\. \[[x ]\] /.exec(s);
346
+ return wrapTo(s, cols(), item ? { hang: item[0].trimStart().length } : {});
347
+ };
348
+ const say = (s ) => term.write(fit(s).map((l) => l + "\n").join(""));
349
+ /** A question: the lines before its last one are printed, the last one is the prompt (with room for the answer). */
350
+ const ask = (q ) => {
351
+ const ls = wrapTo(q.trimEnd(), Math.max(1, cols() - 4));
352
+ if (ls.length > 1) term.write(ls.slice(0, -1).map((l) => l + "\n").join(""));
353
+ return term.readLine(ls.at(-1) + (q.endsWith(" ") ? " " : ""));
354
+ };
355
+ const original = rows.map((r) => ({ checked: r.checked, value: r.value }));
356
+ const show = () => {
357
+ say(c.title);
358
+ if (c.help !== "") say(c.help);
359
+ say("");
360
+ rows.forEach((r, i) => {
361
+ const text = r.value !== null ? `${r.label} -> ${r.shownValue}` : r.label;
362
+ say(`${String(i + 1).padStart(String(rows.length).length)}. ${r.checked ? "[x]" : "[ ]"} ${text}${r.meta !== "" ? ` (${r.meta})` : ""}`);
363
+ if (r.detail !== "") say(`${" ".repeat(String(rows.length).length + 2)}${r.detail}`);
364
+ });
365
+ if (rows.length === 0) say(m.listEmpty);
366
+ say("");
367
+ say(m.listPlainMore);
368
+ };
369
+ const out = (confirmed ) => ({
370
+ confirmed,
371
+ items: rows.map((r, i) => {
372
+ const o = { ...r.src, checked: confirmed ? r.checked : original[i] .checked };
373
+ if (r.src.editable) o.editable = { ...r.src.editable, value: confirmed && r.value !== null ? r.value : r.src.editable.value };
374
+ return o;
375
+ }),
376
+ });
377
+
378
+ try {
379
+ return await plainLoop();
380
+ } finally {
381
+ term.dispose?.();
382
+ }
383
+
384
+ async function plainLoop() {
385
+ show();
386
+ for (;;) {
387
+ const line = await ask(`${m.listPlainPrompt}: `);
388
+ if (line === null) return out(false);
389
+ const t = line.trim();
390
+ if (t === "") return out(true);
391
+ const lower = t.toLowerCase();
392
+ if (lower === "q") return out(false);
393
+ if (lower === "a" || lower === "n") { for (const r of rows) r.checked = lower === "a"; show(); continue; }
394
+ const ed = /^e\s*(\d+)$/i.exec(t);
395
+ if (ed) {
396
+ const n = Number(ed[1]);
397
+ const r = rows[n - 1];
398
+ if (r === undefined) { say(fmt(m.listPlainBad, { text: shownText(t, 40) })); continue; }
399
+ if (r.value === null) { say(fmt(m.listPlainNoEdit, { n })); continue; }
400
+ if (r.choices.length > 0) {
401
+ r.choices.forEach((ch, i) => say(` ${i + 1}. ${ch}`));
402
+ const ans = await ask(m.listPlainChoiceAsk);
403
+ if (ans === null) return out(false);
404
+ if (ans.trim() === "") continue;
405
+ const pick = parseNumbers(ans.trim(), r.choices.length);
406
+ const v = pick && pick.length === 1 ? r.src.editable .choices?.[pick[0] - 1] : undefined;
407
+ if (v === undefined) say(m.listPlainBadChoice);
408
+ else { r.value = v; r.shownValue = r.choices[pick [0] - 1] ; }
409
+ } else {
410
+ const ans = await ask(fmt(m.listPlainEditAsk, { prompt: r.prompt, value: r.shownValue }));
411
+ if (ans === null) return out(false);
412
+ const v = cleanText(ans);
413
+ if (v !== "") { r.value = v; r.shownValue = shownText(v); }
414
+ }
415
+ continue;
416
+ }
417
+ const nums = parseNumbers(t, rows.length);
418
+ if (nums === null || nums.length === 0) { say(fmt(m.listPlainBad, { text: shownText(t, 40) })); continue; }
419
+ for (const n of nums) rows[n - 1] .checked = !rows[n - 1] .checked;
420
+ show();
421
+ }
422
+ }
423
+ }