kovence-cli 0.0.0-stage → 1.0.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.
package/tui.js ADDED
@@ -0,0 +1,1634 @@
1
+ "use strict";
2
+
3
+ const readline = require("node:readline");
4
+ const { PassThrough } = require("node:stream");
5
+ const { getSlashSuggestions, resolveSlashEnter } = require("./ui");
6
+ const { walkWorkspace } = require("./src/tools/fs_walk");
7
+ const { CONTROL_SEQ, getPalette } = require("./src/tui/themes");
8
+ const {
9
+ stripAnsi,
10
+ displayWidth,
11
+ segmentGraphemes,
12
+ prevGraphemeBoundary,
13
+ nextGraphemeBoundary,
14
+ wrapPlain,
15
+ clipToWidth,
16
+ padRight,
17
+ sliceByVisualColumns,
18
+ } = require("./src/tui/text_width");
19
+ const {
20
+ getFilteredSettings,
21
+ getFilteredPermissions,
22
+ renderSettingsScreen,
23
+ renderPermissionsScreen,
24
+ stepSettingValue,
25
+ parseSettingValue,
26
+ } = require("./src/tui/settings_panel");
27
+
28
+ function copyToClipboardOsc52(text, stdout = process.stdout) {
29
+ if (!text) return false;
30
+ const b64 = Buffer.from(text, "utf8").toString("base64");
31
+ stdout.write(`\x1b]52;c;${b64}\x07`);
32
+ return true;
33
+ }
34
+
35
+ function styleInlineMarkdown(line, ansi) {
36
+ return line
37
+ .replace(/`([^`]+)`/g, `${ansi.amber}$1${ansi.reset}${ansi.white}`)
38
+ .replace(/\*\*([^*]+)\*\*/g, `${ansi.bold}${ansi.amber}$1${ansi.reset}${ansi.white}`);
39
+ }
40
+
41
+ function formatAssistantLines(text, innerW, ansi) {
42
+ const out = [];
43
+ const rawLines = String(text || "").split(/\r?\n/);
44
+ let inCode = false;
45
+
46
+ for (const raw of rawLines) {
47
+ const fence = raw.match(/^\s*```(.*)$/);
48
+ if (fence) {
49
+ inCode = !inCode;
50
+ const lang = fence[1].trim();
51
+ out.push(
52
+ inCode
53
+ ? ` ${ansi.gray}┌─${lang ? ` ${lang} ` : ""}${"─".repeat(Math.max(4, Math.min(36, innerW - 6 - lang.length)))}${ansi.reset}`
54
+ : ` ${ansi.gray}└${"─".repeat(Math.max(6, Math.min(38, innerW - 4)))}${ansi.reset}`
55
+ );
56
+ continue;
57
+ }
58
+ if (inCode) {
59
+ for (const wl of wrapPlain(raw, innerW - 4)) {
60
+ out.push(` ${ansi.gray}│ ${ansi.amber}${wl}${ansi.reset}`);
61
+ }
62
+ continue;
63
+ }
64
+ const heading = raw.match(/^(#{1,3})\s+(.*)$/);
65
+ if (heading) {
66
+ for (const wl of wrapPlain(heading[2], innerW - 4)) {
67
+ out.push(` ${ansi.orange}┃ ${ansi.bold}${ansi.amber}${wl}${ansi.reset}`);
68
+ }
69
+ continue;
70
+ }
71
+ const bullet = raw.match(/^(\s*)[-*]\s+(.*)$/);
72
+ const normalized = bullet ? `${bullet[1]}• ${bullet[2]}` : raw;
73
+ for (const wl of wrapPlain(normalized, innerW - 4)) {
74
+ out.push(` ${ansi.orange}┃ ${ansi.white}${styleInlineMarkdown(wl, ansi)}${ansi.reset}`);
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * Lay out multi-line composer buffer with exact cursor visual row/col on grapheme boundaries.
82
+ */
83
+ function layoutComposer(text, cursorPos, availW) {
84
+ const w = Math.max(8, availW);
85
+ const lines = [];
86
+ let curRow = 0;
87
+ let curCol = 0;
88
+ let pos = 0;
89
+ const rawParts = String(text || "").split("\n");
90
+
91
+ for (let p = 0; p < rawParts.length; p++) {
92
+ const part = rawParts[p];
93
+ if (!part.length) {
94
+ if (cursorPos === pos) {
95
+ curRow = lines.length;
96
+ curCol = 0;
97
+ }
98
+ lines.push("");
99
+ pos += 1;
100
+ continue;
101
+ }
102
+
103
+ const graphemes = segmentGraphemes(part);
104
+ let gStart = 0;
105
+ while (gStart < graphemes.length) {
106
+ let lineW = 0;
107
+ let gEnd = gStart;
108
+ while (gEnd < graphemes.length) {
109
+ const gw = graphemes[gEnd].width;
110
+ if (lineW + gw > w && gEnd > gStart) break;
111
+ lineW += gw;
112
+ gEnd += 1;
113
+ }
114
+
115
+ const sliceStartChar = graphemes[gStart].index;
116
+ const sliceEndChar = gEnd < graphemes.length ? graphemes[gEnd].index : part.length;
117
+ const slice = part.slice(sliceStartChar, sliceEndChar);
118
+ const startAbs = pos + sliceStartChar;
119
+ const endAbs = pos + sliceEndChar;
120
+
121
+ if (cursorPos >= startAbs && cursorPos <= endAbs) {
122
+ curRow = lines.length;
123
+ curCol = cursorPos - startAbs;
124
+ }
125
+ lines.push(slice);
126
+ gStart = gEnd;
127
+ }
128
+ pos += part.length + 1;
129
+ }
130
+ if (!lines.length) lines.push("");
131
+ return { lines, curRow, curCol };
132
+ }
133
+
134
+ class KovenceTUI {
135
+ constructor({
136
+ onSubmit,
137
+ onCancel,
138
+ onExit,
139
+ onOpenSessions,
140
+ onNewSession,
141
+ onCycleMode,
142
+ onUpdateSetting,
143
+ onGetSettings,
144
+ onGetProviders,
145
+ onGetModels = null,
146
+ onRefreshModels = null,
147
+ onPickSettingChoice = null,
148
+ onGetPermissionRules,
149
+ onRemovePermissionRule,
150
+ workspaceRoot = process.cwd(),
151
+ initialInputHistory = [],
152
+ onSaveInputHistory = null,
153
+ stdout = process.stdout,
154
+ stdin = process.stdin,
155
+ }) {
156
+ this.onSubmit = onSubmit;
157
+ this.onCancel = onCancel;
158
+ this.onExit = onExit;
159
+ this.onOpenSessions = onOpenSessions;
160
+ this.onNewSession = onNewSession;
161
+ this.onCycleMode = onCycleMode;
162
+ this.onUpdateSetting = onUpdateSetting;
163
+ this.onGetSettings = onGetSettings;
164
+ this.onGetProviders = onGetProviders;
165
+ this.onGetModels = onGetModels;
166
+ this.onRefreshModels = onRefreshModels;
167
+ this.onPickSettingChoice = onPickSettingChoice;
168
+ this.onGetPermissionRules = onGetPermissionRules;
169
+ this.onRemovePermissionRule = onRemovePermissionRule;
170
+ this.workspaceRoot = workspaceRoot;
171
+ this.onSaveInputHistory = onSaveInputHistory;
172
+ this.stdout = stdout;
173
+ this.stdin = stdin;
174
+
175
+ this.blocks = [];
176
+ this.input = "";
177
+ this.cursor = 0;
178
+ this.selIdx = 0;
179
+ this.inputHistory = Array.isArray(initialInputHistory) ? [...initialInputHistory] : [];
180
+ this.histIdx = this.inputHistory.length;
181
+ this._fileCache = { ts: 0, files: [] };
182
+ this.scrollOffset = 0;
183
+ this.lastTotalLines = 0;
184
+
185
+ this.modal = null;
186
+ this.picker = null;
187
+ this.settingsScreen = null;
188
+ this.permScreen = null;
189
+
190
+ this.mouseTracking = true;
191
+ this.isSelecting = false;
192
+ this.selStart = null;
193
+ this.selEnd = null;
194
+ this.lastViewState = { startIdx: 0, viewHeight: 10, plainLines: [] };
195
+ this.noticeTimer = null;
196
+ this.lastCtrlCAt = 0;
197
+
198
+ this.status = {
199
+ sessionId: "default",
200
+ provider: "default",
201
+ providerType: "openai",
202
+ model: "",
203
+ ctxText: "",
204
+ agentMode: "default",
205
+ colorScheme: "amber",
206
+ tools: true,
207
+ auto: false,
208
+ showTips: true,
209
+ showActiveTasks: true,
210
+ activeBgTasks: 0,
211
+ activeTodos: 0,
212
+ notifications: true,
213
+ isBusy: false,
214
+ queueLen: 0,
215
+ busyLabel: "",
216
+ notice: "",
217
+ };
218
+
219
+ this.active = false;
220
+ this.renderPending = false;
221
+ this.rawBuf = "";
222
+ this.keyStream = null;
223
+ this.onKey = this.onKey.bind(this);
224
+ this.onRawData = this.onRawData.bind(this);
225
+ this.onResize = () => this.scheduleRender();
226
+ }
227
+
228
+ getPalette() {
229
+ return getPalette(this.status.colorScheme || "amber");
230
+ }
231
+
232
+ flashNotice(msg, ms = 2500) {
233
+ this.status.notice = msg;
234
+ if (this.noticeTimer) clearTimeout(this.noticeTimer);
235
+ this.noticeTimer = setTimeout(() => {
236
+ this.status.notice = "";
237
+ this.scheduleRender();
238
+ }, ms);
239
+ this.noticeTimer.unref?.();
240
+ this.scheduleRender();
241
+ }
242
+
243
+ toggleMouseMode() {
244
+ this.mouseTracking = !this.mouseTracking;
245
+ if (this.active) {
246
+ this.stdout.write(this.mouseTracking ? CONTROL_SEQ.mouseOn : CONTROL_SEQ.mouseOff);
247
+ }
248
+ this.flashNotice(
249
+ this.mouseTracking ? "Scroll/Select mode ON" : "Native terminal select ON (F2 to restore scroll)",
250
+ 3000
251
+ );
252
+ }
253
+
254
+ copyLastResponse() {
255
+ const lastAi = [...this.blocks].reverse().find((b) => b.kind === "assistant" && b.text.trim());
256
+ if (!lastAi) {
257
+ this.flashNotice("No AI response to copy yet");
258
+ return false;
259
+ }
260
+ copyToClipboardOsc52(lastAi.text, this.stdout);
261
+ this.flashNotice(`Copied last response (${lastAi.text.length} chars)`);
262
+ return true;
263
+ }
264
+
265
+ insertNewline() {
266
+ this.input = this.input.slice(0, this.cursor) + "\n" + this.input.slice(this.cursor);
267
+ this.cursor += 1;
268
+ this.selIdx = 0;
269
+ this.scheduleRender();
270
+ }
271
+
272
+ setInput(text) {
273
+ this.input = String(text || "");
274
+ this.cursor = this.input.length;
275
+ this.selIdx = 0;
276
+ this.scheduleRender();
277
+ }
278
+
279
+ removeQueuedBlocks() {
280
+ this.blocks = this.blocks.filter((b) => b.kind !== "queued");
281
+ this.scheduleRender();
282
+ }
283
+
284
+ openSettings() {
285
+ if (this.modal || this.picker) return;
286
+ this.permScreen = null;
287
+ this.settingsScreen = {
288
+ search: "",
289
+ selIdx: 0,
290
+ editing: null,
291
+ editError: "",
292
+ };
293
+ this.onRefreshModels?.();
294
+ this.scheduleRender();
295
+ }
296
+
297
+ openManagePermissions() {
298
+ this.permScreen = {
299
+ search: "",
300
+ selIdx: 0,
301
+ notice: "",
302
+ };
303
+ this.scheduleRender();
304
+ }
305
+
306
+ getNormalizedSelection() {
307
+ if (!this.selStart || !this.selEnd) return null;
308
+ const a = this.selStart;
309
+ const b = this.selEnd;
310
+ if (a.absLine < b.absLine || (a.absLine === b.absLine && a.col <= b.col)) {
311
+ return { start: a, end: b };
312
+ }
313
+ return { start: b, end: a };
314
+ }
315
+
316
+ extractSelectedText() {
317
+ const norm = this.getNormalizedSelection();
318
+ if (!norm) return "";
319
+ const { plainLines } = this.lastViewState;
320
+ const out = [];
321
+ for (let ln = norm.start.absLine; ln <= norm.end.absLine; ln++) {
322
+ const line = (plainLines[ln] || "").trimEnd();
323
+ const c1 = ln === norm.start.absLine ? norm.start.col : 0;
324
+ const c2 = ln === norm.end.absLine ? norm.end.col + 1 : displayWidth(line);
325
+ const sliced = sliceByVisualColumns(line, c1, Math.max(c1, c2));
326
+ out.push(sliced.selected);
327
+ }
328
+ return out.join("\n").trim();
329
+ }
330
+
331
+ handleMouseEvent(btn, x, y, kind) {
332
+ if (this.settingsScreen || this.permScreen) return;
333
+ if (btn === 64) {
334
+ this.scrollOffset += 3;
335
+ this.scheduleRender();
336
+ return;
337
+ }
338
+ if (btn === 65) {
339
+ this.scrollOffset = Math.max(0, this.scrollOffset - 3);
340
+ this.scheduleRender();
341
+ return;
342
+ }
343
+ const headerRows = 2;
344
+ const vRow = y - (headerRows + 1);
345
+ const { startIdx, viewHeight, plainLines } = this.lastViewState;
346
+ const clampedRow = Math.max(0, Math.min(viewHeight - 1, vRow));
347
+ const absLine = Math.max(0, Math.min(plainLines.length - 1, startIdx + clampedRow));
348
+ const col = Math.max(0, x - 1);
349
+
350
+ if (btn === 0 && kind === "M") {
351
+ if (vRow >= 0 && vRow < viewHeight && plainLines.length) {
352
+ this.isSelecting = true;
353
+ this.selStart = { absLine, col };
354
+ this.selEnd = { absLine, col };
355
+ } else {
356
+ this.isSelecting = false;
357
+ this.selStart = null;
358
+ this.selEnd = null;
359
+ }
360
+ this.scheduleRender();
361
+ return;
362
+ }
363
+ if ((btn === 32 || btn === 33) && kind === "M" && this.isSelecting) {
364
+ this.selEnd = { absLine, col };
365
+ this.scheduleRender();
366
+ return;
367
+ }
368
+ if ((btn === 0 || btn === 3) && kind === "m" && this.isSelecting) {
369
+ this.isSelecting = false;
370
+ const isSingleClick =
371
+ this.selStart &&
372
+ this.selEnd &&
373
+ this.selStart.absLine === this.selEnd.absLine &&
374
+ Math.abs(this.selStart.col - this.selEnd.col) <= 1;
375
+ if (isSingleClick) {
376
+ const clickedBlock = this.lastViewState.lineBlocks?.[this.selStart.absLine];
377
+ if (clickedBlock && clickedBlock.collapsible) {
378
+ this.selStart = null;
379
+ this.selEnd = null;
380
+ this.toggleBlockExpanded(clickedBlock);
381
+ return;
382
+ }
383
+ }
384
+ const text = this.extractSelectedText();
385
+ if (text) {
386
+ copyToClipboardOsc52(text, this.stdout);
387
+ this.flashNotice(`Copied ${text.length} chars to clipboard`);
388
+ }
389
+ this.scheduleRender();
390
+ }
391
+ }
392
+
393
+ onRawData(chunk) {
394
+ this.rawBuf += chunk.toString("utf8");
395
+ let out = "";
396
+ let i = 0;
397
+ while (i < this.rawBuf.length) {
398
+ if (this.rawBuf[i] === "\x1b") {
399
+ const rest = this.rawBuf.slice(i);
400
+ // Ctrl+, via Kitty / modifyOtherKeys / Alt+, -> open settings
401
+ const ctrlComma = rest.match(/^(?:\x1b\[44;5u|\x1b\[27;5;44~|\x1b,)/);
402
+ if (ctrlComma) {
403
+ this.openSettings();
404
+ i += ctrlComma[0].length;
405
+ continue;
406
+ }
407
+ // Shift+Enter / Alt+Enter sequences -> emit '\n' in order to keyStream (preserved intact)
408
+ const shiftEnter = rest.match(/^(?:\x1b\[13;2u|\x1b\[27;2;13~|\x1b\r)/);
409
+ if (shiftEnter) {
410
+ out += "\n";
411
+ i += shiftEnter[0].length;
412
+ continue;
413
+ }
414
+ // Kitty CSI-u (\x1b[code;modu) and xterm modifyOtherKeys (\x1b[27;mod;code~) normalization
415
+ // Ensures Ctrl+C, Ctrl+D, Esc, Shift+Tab, Ctrl+S/N/Y/U work in VS Code, Kitty, WezTerm, Ghostty, etc.
416
+ const csiU = rest.match(/^\x1b\[(\d+)(?:;(\d+)(?::\d+)?)?u/);
417
+ const modOther = !csiU ? rest.match(/^\x1b\[27;(\d+);(\d+)~/) : null;
418
+ if (csiU || modOther) {
419
+ const rawSeq = csiU ? csiU[0] : modOther[0];
420
+ const cp = Number(csiU ? csiU[1] : modOther[2]);
421
+ const mod = Math.max(0, (Number(csiU ? csiU[2] || 1 : modOther[1]) || 1) - 1);
422
+ const shift = Boolean(mod & 1);
423
+ const alt = Boolean(mod & 2);
424
+ const ctrl = Boolean(mod & 4);
425
+
426
+ if (cp === 13 && (shift || alt)) {
427
+ out += "\n";
428
+ } else if (cp === 13 && !ctrl) {
429
+ out += "\r";
430
+ } else if (cp === 27 && !ctrl) {
431
+ if (out && this.keyStream) {
432
+ this.keyStream.write(out);
433
+ out = "";
434
+ }
435
+ this.onKey("", { name: "escape", sequence: "\x1b" });
436
+ } else if (cp === 9 && shift && !ctrl) {
437
+ out += "\x1b[Z";
438
+ } else if (cp === 9 && !ctrl) {
439
+ out += "\t";
440
+ } else if ((cp === 127 || cp === 8) && !ctrl) {
441
+ out += "\x7f";
442
+ } else if (ctrl && cp >= 97 && cp <= 122) {
443
+ out += String.fromCharCode(cp - 96);
444
+ } else if (ctrl && cp >= 65 && cp <= 90) {
445
+ out += String.fromCharCode(cp - 64);
446
+ } else if (ctrl && cp === 44) {
447
+ this.openSettings();
448
+ } else if (!ctrl && !alt && cp >= 32 && cp <= 0x10ffff) {
449
+ out += String.fromCodePoint(cp);
450
+ }
451
+ i += rawSeq.length;
452
+ continue;
453
+ }
454
+ // Wait for incomplete CSI-u / modifyOtherKeys sequence split across chunks
455
+ if (/^\x1b\[[\d;:]*$/.test(rest) && rest.length < 18) {
456
+ break;
457
+ }
458
+ // SGR mouse sequence: \x1b[<btn;x;y[mM]
459
+ const sgr = rest.match(/^\x1b\[<(\d+);(\d+);(\d+)([mM])/);
460
+ if (sgr) {
461
+ this.handleMouseEvent(Number(sgr[1]), Number(sgr[2]), Number(sgr[3]), sgr[4]);
462
+ i += sgr[0].length;
463
+ continue;
464
+ }
465
+ if (/^\x1b\[<[\d;]*$/.test(rest) && rest.length < 24) {
466
+ break;
467
+ }
468
+ // Legacy X10 mouse packet
469
+ if (rest.startsWith("\x1b[M")) {
470
+ if (rest.length < 6) break;
471
+ const cb = rest.charCodeAt(3) - 32;
472
+ if (cb === 64) {
473
+ this.scrollOffset += 3;
474
+ this.scheduleRender();
475
+ } else if (cb === 65) {
476
+ this.scrollOffset = Math.max(0, this.scrollOffset - 3);
477
+ this.scheduleRender();
478
+ }
479
+ i += 6;
480
+ continue;
481
+ }
482
+ // Standalone Esc byte at end of chunk: wait briefly in case an escape sequence was split across chunks
483
+ if (rest === "\x1b") {
484
+ if (this.escTimer) clearTimeout(this.escTimer);
485
+ this.escTimer = setTimeout(() => {
486
+ this.escTimer = null;
487
+ if (this.rawBuf === "\x1b") {
488
+ this.rawBuf = "";
489
+ this.onKey("", { name: "escape", sequence: "\x1b" });
490
+ }
491
+ }, 25);
492
+ this.escTimer.unref?.();
493
+ break;
494
+ }
495
+ }
496
+ out += this.rawBuf[i];
497
+ i++;
498
+ }
499
+ this.rawBuf = this.rawBuf.slice(i);
500
+ if (this.rawBuf !== "\x1b" && this.escTimer) {
501
+ clearTimeout(this.escTimer);
502
+ this.escTimer = null;
503
+ }
504
+ if (out && this.keyStream) this.keyStream.write(out);
505
+ }
506
+
507
+ enter() {
508
+ if (this.active) return;
509
+ this.active = true;
510
+ this.stdout.write(CONTROL_SEQ.altOn + (this.mouseTracking ? CONTROL_SEQ.mouseOn : "") + CONTROL_SEQ.keysOn);
511
+ if (this.stdin.isTTY) {
512
+ this.keyStream = new PassThrough();
513
+ readline.emitKeypressEvents(this.keyStream);
514
+ this.keyStream.on("keypress", this.onKey);
515
+ if (this.stdin.isPaused()) this.stdin.resume();
516
+ this.stdin.setRawMode(true);
517
+ this.stdin.on("data", this.onRawData);
518
+ }
519
+ this.stdout.on("resize", this.onResize);
520
+ this.render();
521
+ }
522
+
523
+ leave() {
524
+ if (!this.active) return;
525
+ this.active = false;
526
+ if (this.noticeTimer) clearTimeout(this.noticeTimer);
527
+ this.stdin.removeListener("data", this.onRawData);
528
+ if (this.keyStream) {
529
+ this.keyStream.removeListener("keypress", this.onKey);
530
+ this.keyStream.destroy();
531
+ this.keyStream = null;
532
+ }
533
+ this.stdout.removeListener("resize", this.onResize);
534
+ if (this.stdin.isTTY) {
535
+ try {
536
+ this.stdin.setRawMode(false);
537
+ } catch {}
538
+ }
539
+ this.stdout.write(CONTROL_SEQ.keysOff + CONTROL_SEQ.mouseOff + CONTROL_SEQ.showCur + CONTROL_SEQ.altOff);
540
+ }
541
+
542
+ setStatus(patch) {
543
+ Object.assign(this.status, patch);
544
+ this.scheduleRender();
545
+ }
546
+
547
+ addBlock(kind, text, opts = {}) {
548
+ const block = {
549
+ kind,
550
+ text: String(text || ""),
551
+ collapsible: Boolean(opts.collapsible),
552
+ expanded: Boolean(opts.expanded),
553
+ details: Array.isArray(opts.details) ? opts.details : [],
554
+ statusLine: String(opts.statusLine || ""),
555
+ _ver: 1,
556
+ _cache: null,
557
+ };
558
+ this.blocks.push(block);
559
+ this.scheduleRender();
560
+ return block;
561
+ }
562
+
563
+ setBlockDetails(block, details, statusLine = undefined) {
564
+ if (!block) return;
565
+ if (Array.isArray(details)) block.details = details;
566
+ if (statusLine !== undefined) block.statusLine = String(statusLine || "");
567
+ block._ver = (block._ver || 0) + 1;
568
+ block._cache = null;
569
+ this.scheduleRender();
570
+ }
571
+
572
+ toggleBlockExpanded(block) {
573
+ if (!block || !block.collapsible) return false;
574
+ block.expanded = !block.expanded;
575
+ block._ver = (block._ver || 0) + 1;
576
+ block._cache = null;
577
+ this.scheduleRender();
578
+ return block.expanded;
579
+ }
580
+
581
+ toggleLastCollapsibleBlock() {
582
+ const target = [...this.blocks].reverse().find((b) => b.collapsible);
583
+ if (!target) return false;
584
+ return this.toggleBlockExpanded(target);
585
+ }
586
+
587
+ updateBlock(block, text) {
588
+ block.text = String(text || "");
589
+ block._ver = (block._ver || 0) + 1;
590
+ block._cache = null;
591
+ this.scheduleRender();
592
+ }
593
+
594
+ appendBlock(block, chunk) {
595
+ block.text += chunk;
596
+ block._ver = (block._ver || 0) + 1;
597
+ block._cache = null;
598
+ this.scheduleRender();
599
+ }
600
+
601
+ clearBlocks() {
602
+ this.blocks = [];
603
+ this.scrollOffset = 0;
604
+ this.lastTotalLines = 0;
605
+ this.selStart = null;
606
+ this.selEnd = null;
607
+ this.scheduleRender();
608
+ }
609
+
610
+ askModal(label, masked = false) {
611
+ return new Promise((resolve) => {
612
+ this.modal = { label, masked, buf: "", resolve };
613
+ this.scheduleRender();
614
+ });
615
+ }
616
+
617
+ cancelModal() {
618
+ if (!this.modal) return false;
619
+ const { resolve } = this.modal;
620
+ this.modal = null;
621
+ this.scheduleRender();
622
+ resolve("");
623
+ return true;
624
+ }
625
+
626
+ openPicker(title, items, { initialIdx = 0, hint = "↑/↓ select · Enter open · d delete · Esc close" } = {}) {
627
+ return new Promise((resolve) => {
628
+ let safeIdx = Math.max(0, Math.min(Number(initialIdx) || 0, Math.max(0, items.length - 1)));
629
+ if (items[safeIdx]?.type === "header") {
630
+ const nextSelectable = items.findIndex((x) => x.type !== "header");
631
+ if (nextSelectable >= 0) safeIdx = nextSelectable;
632
+ }
633
+ this.picker = { title, items, selIdx: safeIdx, hint, resolve };
634
+ this.scheduleRender();
635
+ });
636
+ }
637
+
638
+ scheduleRender() {
639
+ if (!this.active || this.renderPending) return;
640
+ this.renderPending = true;
641
+ setImmediate(() => {
642
+ this.renderPending = false;
643
+ if (this.active) this.render();
644
+ });
645
+ }
646
+
647
+ /**
648
+ * Format & cache each viewport block keyed by (version, cols, colorScheme) for O(1) incremental redraws.
649
+ */
650
+ buildViewportLines(cols) {
651
+ const ansi = this.getPalette();
652
+ const scheme = this.status.colorScheme || "amber";
653
+ const innerW = Math.max(20, cols - 4);
654
+ const lines = [];
655
+ const plainLines = [];
656
+ const lineBlocks = [];
657
+
658
+ for (const b of this.blocks) {
659
+ const ver = b._ver || 1;
660
+ const cacheKey = `${ver}:${cols}:${scheme}`;
661
+ if (!b._cache || b._cache.key !== cacheKey) {
662
+ const blockLines = [];
663
+ if (b.kind === "brand-cyan") {
664
+ for (const rawLine of String(b.text || "").split(/\r?\n/)) {
665
+ blockLines.push(`${ansi.amber}${ansi.bold}${rawLine}${ansi.reset}`);
666
+ }
667
+ } else if (b.kind === "brand-magenta") {
668
+ for (const rawLine of String(b.text || "").split(/\r?\n/)) {
669
+ blockLines.push(`${ansi.orange}${ansi.bold}${rawLine}${ansi.reset}`);
670
+ }
671
+ } else {
672
+ const wrapped = wrapPlain(b.text, innerW);
673
+ if (b.kind === "user") {
674
+ blockLines.push("");
675
+ blockLines.push(
676
+ `${ansi.barBg}${ansi.cyan}${ansi.bold}┃ YOU${" ".repeat(Math.max(0, cols - 5))}${ansi.reset}`
677
+ );
678
+ for (const wl of wrapped) {
679
+ const w = displayWidth(wl);
680
+ blockLines.push(
681
+ `${ansi.barBg}${ansi.cyan}┃ ${ansi.white}${padRight(wl, w, cols - 2)}${ansi.reset}`
682
+ );
683
+ }
684
+ blockLines.push("");
685
+ } else if (b.kind === "assistant") {
686
+ blockLines.push(` ${ansi.orange}${ansi.bold}◆ KOVENCE CLI${ansi.reset}`);
687
+ blockLines.push(...formatAssistantLines(b.text, innerW, ansi));
688
+ } else if (b.kind === "thinking") {
689
+ blockLines.push(` ${ansi.orange}${ansi.bold}◆ KOVENCE CLI${ansi.reset}`);
690
+ for (const wl of wrapped) {
691
+ blockLines.push(` ${ansi.orange}┃ ${ansi.amber}${wl}${ansi.reset}`);
692
+ }
693
+ } else if (b.kind === "tool") {
694
+ if (b.collapsible) {
695
+ const arrow = b.expanded ? "▾" : "▸";
696
+ const hint = b.expanded ? " (click to hide)" : " (click for live details)";
697
+ for (let i = 0; i < wrapped.length; i++) {
698
+ const wl = wrapped[i];
699
+ if (i === 0) {
700
+ blockLines.push(
701
+ ` ${ansi.gray}├─ ${ansi.amber}${arrow} ${wl}${ansi.reset}${ansi.dim}${ansi.gray}${hint}${ansi.reset}`
702
+ );
703
+ } else {
704
+ blockLines.push(` ${ansi.gray}│ ${ansi.amber}${wl}${ansi.reset}`);
705
+ }
706
+ }
707
+ const detailW = Math.max(12, innerW - 6);
708
+ if (b.expanded) {
709
+ const visDetails = (b.details || []).slice(-16);
710
+ if (!visDetails.length) {
711
+ const emptyMsg = b.statusLine || "… waiting for live command output …";
712
+ blockLines.push(
713
+ ` ${ansi.gray}│ ${ansi.dim}${ansi.gray}${clipToWidth(emptyMsg, detailW)}${ansi.reset}`
714
+ );
715
+ } else {
716
+ for (const dl of visDetails) {
717
+ blockLines.push(
718
+ ` ${ansi.gray}│ ${ansi.dim}${ansi.gray}${clipToWidth(dl, detailW)}${ansi.reset}`
719
+ );
720
+ }
721
+ }
722
+ } else if (b.statusLine) {
723
+ blockLines.push(
724
+ ` ${ansi.gray}│ ${ansi.dim}${ansi.gray}${clipToWidth(b.statusLine, detailW)}${ansi.reset}`
725
+ );
726
+ }
727
+ } else {
728
+ for (const wl of wrapped) {
729
+ blockLines.push(` ${ansi.gray}├─ ${ansi.amber}${wl}${ansi.reset}`);
730
+ }
731
+ }
732
+ } else if (b.kind === "meta") {
733
+ for (const wl of wrapped) {
734
+ blockLines.push(` ${ansi.gray}└─ ${wl}${ansi.reset}`);
735
+ }
736
+ if (b.text.includes("memory")) {
737
+ blockLines.push(` ${ansi.gray}${"─".repeat(Math.min(56, innerW))}${ansi.reset}`);
738
+ }
739
+ } else if (b.kind === "queued") {
740
+ for (const wl of wrapped) {
741
+ blockLines.push(` ${ansi.magenta}⏳ ${wl}${ansi.reset}`);
742
+ }
743
+ } else if (b.kind === "permission") {
744
+ blockLines.push("");
745
+ for (let i = 0; i < wrapped.length; i++) {
746
+ const wl = wrapped[i];
747
+ const color = i === 0 ? `${ansi.bold}${ansi.amber}` : ansi.white;
748
+ blockLines.push(` ${ansi.orange}┃ ${color}${wl}${ansi.reset}`);
749
+ }
750
+ } else if (b.kind === "error") {
751
+ for (const wl of wrapped) {
752
+ blockLines.push(` ${ansi.red}✖ ${wl}${ansi.reset}`);
753
+ }
754
+ blockLines.push("");
755
+ } else {
756
+ for (const wl of wrapped) {
757
+ blockLines.push(` ${ansi.dim}${wl}${ansi.reset}`);
758
+ }
759
+ }
760
+ }
761
+ b._cache = {
762
+ key: cacheKey,
763
+ lines: blockLines,
764
+ plainLines: blockLines.map(stripAnsi),
765
+ };
766
+ }
767
+ for (let i = 0; i < b._cache.lines.length; i++) {
768
+ lines.push(b._cache.lines[i]);
769
+ plainLines.push(b._cache.plainLines[i]);
770
+ lineBlocks.push(b);
771
+ }
772
+ }
773
+ return { lines, plainLines, lineBlocks };
774
+ }
775
+
776
+ render() {
777
+ const cols = this.stdout.columns || 100;
778
+ const rows = this.stdout.rows || 30;
779
+ const ansi = this.getPalette();
780
+
781
+ if (this.permScreen) {
782
+ const rules = this.onGetPermissionRules ? this.onGetPermissionRules() : [];
783
+ const frame = renderPermissionsScreen({
784
+ cols,
785
+ rows,
786
+ permState: this.permScreen,
787
+ rules,
788
+ ansi,
789
+ });
790
+ this.stdout.write(CONTROL_SEQ.syncStart + frame + CONTROL_SEQ.syncEnd);
791
+ return;
792
+ }
793
+
794
+ if (this.settingsScreen) {
795
+ const settings = this.onGetSettings ? this.onGetSettings() : {};
796
+ const frame = renderSettingsScreen({
797
+ cols,
798
+ rows,
799
+ settingsState: this.settingsScreen,
800
+ settings,
801
+ ansi,
802
+ });
803
+ this.stdout.write(CONTROL_SEQ.syncStart + frame + CONTROL_SEQ.syncEnd);
804
+ return;
805
+ }
806
+
807
+ const suggestions = this.modal || this.picker ? [] : this._getActiveSuggestions();
808
+ if (this.selIdx >= suggestions.length) this.selIdx = 0;
809
+
810
+ const promptPrefix = "> ";
811
+ let displayBuf = this.input;
812
+ let cursorPos = this.cursor;
813
+ let modalLines = [];
814
+ if (this.modal) {
815
+ modalLines = wrapPlain(this.modal.label, Math.max(12, cols - 4));
816
+ displayBuf = this.modal.masked ? "*".repeat(this.modal.buf.length) : this.modal.buf;
817
+ cursorPos = displayBuf.length;
818
+ }
819
+ const availW = Math.max(8, cols - 3 - displayWidth(promptPrefix));
820
+ const compLayout = layoutComposer(displayBuf, cursorPos, availW);
821
+ const maxCompLines = 6;
822
+ let compStart = 0;
823
+ if (compLayout.curRow >= maxCompLines) compStart = compLayout.curRow - maxCompLines + 1;
824
+ const visCompLines = compLayout.lines.slice(compStart, compStart + maxCompLines);
825
+
826
+ const pickerRows = this.picker ? Math.min(10, this.picker.items.length) + 2 : 0;
827
+ const sugRows = suggestions.length;
828
+ const composerRows = 3 + modalLines.length + visCompLines.length;
829
+ const headerRows = 2;
830
+ const viewHeight = Math.max(4, rows - headerRows - sugRows - pickerRows - composerRows);
831
+
832
+ const { lines: allViewLines, plainLines, lineBlocks } = this.buildViewportLines(cols);
833
+ // Scroll anchoring (B24): when scrolled up reading history, keep viewport anchored during streaming updates.
834
+ if (this.scrollOffset > 0 && allViewLines.length > this.lastTotalLines) {
835
+ this.scrollOffset += allViewLines.length - this.lastTotalLines;
836
+ }
837
+ this.lastTotalLines = allViewLines.length;
838
+
839
+ const maxScroll = Math.max(0, allViewLines.length - viewHeight);
840
+ if (this.scrollOffset > maxScroll) this.scrollOffset = maxScroll;
841
+ const endIdx = allViewLines.length - this.scrollOffset;
842
+ const startIdx = Math.max(0, endIdx - viewHeight);
843
+ this.lastViewState = { startIdx, viewHeight, plainLines, lineBlocks };
844
+
845
+ const normSel = this.getNormalizedSelection();
846
+ const out = [ansi.hideCur, "\x1b[H"];
847
+
848
+ // 1) Top Brand Header
849
+ const qText = this.status.queueLen ? `Queue: ${this.status.queueLen} ` : "";
850
+ const bText = this.status.notice
851
+ ? `${this.status.notice} `
852
+ : this.status.busyLabel
853
+ ? `${this.status.busyLabel} `
854
+ : "";
855
+ const rightPlain = `${qText}${bText}`;
856
+ const maxLeftHdr = Math.max(12, cols - displayWidth(rightPlain) - 1);
857
+ const rawLeftHdr = ` KOVENCE CLI · https://kovence.com · [${this.status.sessionId}]`;
858
+ const leftHdr = clipToWidth(rawLeftHdr, maxLeftHdr);
859
+ const gapHdr = Math.max(1, cols - displayWidth(leftHdr) - displayWidth(rightPlain));
860
+ const hdrPrefix = ` KOVENCE CLI`;
861
+ const hdrRest = leftHdr.startsWith(hdrPrefix) ? leftHdr.slice(hdrPrefix.length) : leftHdr;
862
+ const hdrBrand = leftHdr.startsWith(hdrPrefix)
863
+ ? `${ansi.topBg}${ansi.orange}${ansi.bold}${hdrPrefix}${ansi.reset}${ansi.topBg}${ansi.gray}${hdrRest}`
864
+ : `${ansi.topBg}${ansi.orange}${ansi.bold}${leftHdr}`;
865
+ out.push(
866
+ `${hdrBrand}${" ".repeat(gapHdr)}${ansi.amber}${qText}${this.status.notice ? ansi.green : ansi.orange}${bText}${ansi.reset}\x1b[K\n`
867
+ );
868
+ out.push(`${ansi.gray}${"─".repeat(cols)}${ansi.reset}\x1b[K\n`);
869
+
870
+ // 2) Scrollable Output Viewport
871
+ for (let i = 0; i < viewHeight; i++) {
872
+ const absIdx = startIdx + i;
873
+ let line = allViewLines[absIdx] || "";
874
+ if (
875
+ normSel &&
876
+ absIdx >= normSel.start.absLine &&
877
+ absIdx <= normSel.end.absLine &&
878
+ absIdx < plainLines.length
879
+ ) {
880
+ const pl = plainLines[absIdx];
881
+ const plW = displayWidth(pl);
882
+ const c1 = absIdx === normSel.start.absLine ? Math.min(plW, normSel.start.col) : 0;
883
+ const c2 = absIdx === normSel.end.absLine ? Math.min(plW, normSel.end.col + 1) : plW;
884
+ if (c2 > c1) {
885
+ const seg = sliceByVisualColumns(pl, c1, c2);
886
+ line = `${seg.before}${ansi.selBg}${seg.selected}${ansi.reset}${seg.after}`;
887
+ }
888
+ }
889
+ out.push(`${line}\x1b[K\n`);
890
+ }
891
+
892
+ // 3) Floating Session Picker OR Slash Suggestions
893
+ if (this.picker) {
894
+ const maxVisible = Math.min(10, this.picker.items.length);
895
+ const pStart = Math.max(
896
+ 0,
897
+ Math.min(this.picker.selIdx - Math.floor(maxVisible / 2), this.picker.items.length - maxVisible)
898
+ );
899
+ const hintText = this.picker.hint || "↑/↓ select · Enter open · d delete · Esc close";
900
+ const titleText = clipToWidth(` ${this.picker.title} · ${hintText}`, cols);
901
+ out.push(
902
+ `${ansi.topBg}${ansi.orange}${ansi.bold}${padRight(titleText, displayWidth(titleText), cols)}${ansi.reset}\x1b[K\n`
903
+ );
904
+ for (let i = 0; i < maxVisible; i++) {
905
+ const idx = pStart + i;
906
+ const it = this.picker.items[idx];
907
+ if (it.type === "header") {
908
+ const hdrText = clipToWidth(` ── ${it.label} ── ${it.desc || ""}`, cols);
909
+ out.push(
910
+ `${ansi.barBg}${ansi.orange}${ansi.bold}${padRight(hdrText, displayWidth(hdrText), cols)}${ansi.reset}\x1b[K\n`
911
+ );
912
+ continue;
913
+ }
914
+ const active = idx === this.picker.selIdx;
915
+ const left = clipToWidth(` ${it.label.padEnd(22)}`, Math.min(24, cols));
916
+ const right = clipToWidth(it.desc || "", Math.max(0, cols - displayWidth(left) - 1));
917
+ const plainLen = displayWidth(left) + 1 + displayWidth(right);
918
+ const line = active
919
+ ? `${ansi.selBg}${padRight(`${left} ${right}`, plainLen, cols)}${ansi.reset}`
920
+ : `${ansi.barBg}${it.type === "new" ? ansi.green : ansi.amber}${left} ${ansi.gray}${padRight(right, plainLen, cols)}${ansi.reset}`;
921
+ out.push(`${line}\x1b[K\n`);
922
+ }
923
+ out.push(`${ansi.gray}${"─".repeat(cols)}${ansi.reset}\x1b[K\n`);
924
+ }
925
+
926
+ for (let i = 0; i < sugRows; i++) {
927
+ const s = suggestions[i];
928
+ const active = i === this.selIdx;
929
+ const labelCol = ` ${s.label.padEnd(22)}`;
930
+ const descCol = clipToWidth(s.desc, Math.max(0, cols - displayWidth(labelCol) - 1));
931
+ const text = `${labelCol} ${descCol}`;
932
+ const line = active
933
+ ? `${ansi.selBg}${padRight(text, displayWidth(text), cols)}${ansi.reset}`
934
+ : `${ansi.barBg}${ansi.orange}${labelCol}${ansi.gray} ${padRight(descCol, displayWidth(text), cols)}${ansi.reset}`;
935
+ out.push(`${line}\x1b[K\n`);
936
+ }
937
+
938
+ // 4) Multi-Line Bottom Composer Box
939
+ const boxPad = `${ansi.barBg}${ansi.orange}┃${" ".repeat(Math.max(0, cols - 1))}${ansi.reset}\x1b[K\n`;
940
+ out.push(boxPad);
941
+
942
+ for (const ml of modalLines) {
943
+ const clippedModal = clipToWidth(ml, Math.max(8, cols - 3));
944
+ const mw = displayWidth(clippedModal);
945
+ out.push(
946
+ `${ansi.barBg}${ansi.orange}┃ ${ansi.amber}${padRight(clippedModal, mw, cols - 2)}${ansi.reset}\x1b[K\n`
947
+ );
948
+ }
949
+
950
+ const prefixSpace = " ".repeat(displayWidth(promptPrefix));
951
+ for (let i = 0; i < visCompLines.length; i++) {
952
+ const pfx = i === 0 && compStart === 0 ? promptPrefix : prefixSpace;
953
+ const txt = visCompLines[i];
954
+ const showPh =
955
+ i === 0 &&
956
+ compStart === 0 &&
957
+ !this.modal &&
958
+ !this.input &&
959
+ this.status.showTips !== false &&
960
+ cols >= 2 + displayWidth(pfx) + 52;
961
+ const phText = "Type message · Shift+Enter newline · / commands...";
962
+ const placeholder = showPh ? `${ansi.gray}${phText}${ansi.reset}` : "";
963
+ const phLen = showPh ? displayWidth(phText) : 0;
964
+ const linePlainLen = 2 + displayWidth(pfx) + displayWidth(txt);
965
+ const padComposer = Math.max(0, cols - linePlainLen - phLen);
966
+ out.push(
967
+ `${ansi.barBg}${ansi.orange}┃ ${ansi.white}${pfx}${txt}${placeholder}${" ".repeat(padComposer)}${ansi.reset}\x1b[K\n`
968
+ );
969
+ }
970
+ out.push(boxPad);
971
+
972
+ // 5) Bottom Footer Status & Keybinds
973
+ const shortModel = this.status.model.length > 20 ? `...${this.status.model.slice(-17)}` : this.status.model;
974
+ const apiTag = `${this.status.provider}(${this.status.providerType})`;
975
+ const ctxSeg = this.status.ctxText ? ` · ${this.status.ctxText}` : "";
976
+ const modeTag = this.status.agentMode || (this.status.auto ? "auto" : "default");
977
+ const taskParts = [];
978
+ if (this.status.showActiveTasks !== false) {
979
+ if (this.status.activeBgTasks > 0) taskParts.push(`Tasks:${this.status.activeBgTasks}`);
980
+ if (this.status.activeTodos > 0) taskParts.push(`Todos:${this.status.activeTodos}`);
981
+ }
982
+ const taskSeg = taskParts.length ? ` · ${taskParts.join(" ")}` : "";
983
+ const rawLeft = `Kovence CLI · Mode: ${modeTag} · ${apiTag} · ${shortModel}${ctxSeg}${taskSeg} · Tools ${this.status.tools ? "ON" : "OFF"}`;
984
+ const maxLeftW = Math.max(20, cols - 2);
985
+ const clampedLeft = clipToWidth(rawLeft, maxLeftW);
986
+ const fullHints =
987
+ this.scrollOffset > 0
988
+ ? `[Scrolled +${this.scrollOffset}] Shift+Tab mode · Ctrl+Y copy · F2 select`
989
+ : `Shift+Tab mode · Ctrl+S sessions · Ctrl+, settings · Ctrl+Y copy · F2 select`;
990
+ const maxHintW = Math.max(0, cols - displayWidth(clampedLeft) - 3);
991
+ const hintsRight = maxHintW >= 12 ? clipToWidth(fullHints, maxHintW) : "";
992
+ const footerGap = hintsRight ? Math.max(1, cols - displayWidth(clampedLeft) - displayWidth(hintsRight) - 2) : 0;
993
+ const footerBrand = clampedLeft.startsWith("Kovence CLI")
994
+ ? `${ansi.orange}${ansi.bold}Kovence CLI${ansi.reset}${ansi.gray}${clampedLeft.slice(11)}`
995
+ : `${ansi.gray}${clampedLeft}`;
996
+ out.push(` ${footerBrand}${hintsRight ? `${" ".repeat(footerGap)}${hintsRight}` : ""}${ansi.reset}\x1b[K`);
997
+
998
+ // Exact cursor placement (accounts cleanly for wrapped modal header lines)
999
+ const curLineText = compLayout.lines[compLayout.curRow] || "";
1000
+ const curColVis = displayWidth(curLineText.slice(0, compLayout.curCol));
1001
+ const inputRow =
1002
+ headerRows + viewHeight + pickerRows + sugRows + 2 + modalLines.length + (compLayout.curRow - compStart);
1003
+ const inputCol = Math.min(cols, 2 + displayWidth(promptPrefix) + curColVis + 1);
1004
+ out.push(`\x1b[${inputRow};${inputCol}H`, ansi.showCur);
1005
+
1006
+ this.stdout.write(CONTROL_SEQ.syncStart + out.join("") + CONTROL_SEQ.syncEnd);
1007
+ }
1008
+
1009
+ /**
1010
+ * Dispatch keys strictly inside the active UI mode so keys never leak across modes (B8).
1011
+ */
1012
+ onKey(str, key = {}) {
1013
+ if (this.selStart || this.selEnd) {
1014
+ this.selStart = null;
1015
+ this.selEnd = null;
1016
+ }
1017
+
1018
+ if (this.modal) return this._handleModalKey(str, key);
1019
+ if (this.permScreen) return this._handlePermissionsKey(str, key);
1020
+ if (this.settingsScreen) return this._handleSettingsKey(str, key);
1021
+ if (this.picker) return this._handlePickerKey(str, key);
1022
+ return this._handleComposerKey(str, key);
1023
+ }
1024
+
1025
+ _handleModalKey(str, key) {
1026
+ if (key.ctrl && key.name === "c") {
1027
+ const now = Date.now();
1028
+ const isDouble = now - this.lastCtrlCAt < 2500;
1029
+ this.lastCtrlCAt = now;
1030
+ const { resolve } = this.modal;
1031
+ this.modal = null;
1032
+ this.scheduleRender();
1033
+ resolve("");
1034
+ if (isDouble) {
1035
+ this.onExit?.();
1036
+ } else {
1037
+ this.onCancel?.();
1038
+ this.flashNotice("Cancelled current task (press Ctrl+C again to exit)", 2400);
1039
+ }
1040
+ return;
1041
+ }
1042
+ if (key.name === "escape") {
1043
+ const { resolve } = this.modal;
1044
+ this.modal = null;
1045
+ this.scheduleRender();
1046
+ resolve("");
1047
+ return;
1048
+ }
1049
+ if (key.name === "return" || key.name === "enter") {
1050
+ const { resolve, buf } = this.modal;
1051
+ this.modal = null;
1052
+ this.scheduleRender();
1053
+ resolve(buf);
1054
+ return;
1055
+ }
1056
+ if (key.name === "backspace") {
1057
+ const prev = prevGraphemeBoundary(this.modal.buf, this.modal.buf.length);
1058
+ this.modal.buf = this.modal.buf.slice(0, prev);
1059
+ this.scheduleRender();
1060
+ return;
1061
+ }
1062
+ if (str && !key.ctrl && !key.meta && str >= " ") {
1063
+ this.modal.buf += str;
1064
+ this.scheduleRender();
1065
+ }
1066
+ }
1067
+
1068
+ _handlePickerKey(str, key) {
1069
+ const { items, resolve } = this.picker;
1070
+ if (key.name === "escape" || (key.ctrl && key.name === "c")) {
1071
+ this.picker = null;
1072
+ this.scheduleRender();
1073
+ resolve(null);
1074
+ return;
1075
+ }
1076
+ if (!items.length) return;
1077
+ const stepPicker = (dir) => {
1078
+ let next = this.picker.selIdx;
1079
+ for (let tries = 0; tries < items.length; tries++) {
1080
+ next = (next + dir + items.length) % items.length;
1081
+ if (items[next]?.type !== "header") break;
1082
+ }
1083
+ this.picker.selIdx = next;
1084
+ };
1085
+ if (key.name === "up") {
1086
+ stepPicker(-1);
1087
+ this.scheduleRender();
1088
+ return;
1089
+ }
1090
+ if (key.name === "down") {
1091
+ stepPicker(1);
1092
+ this.scheduleRender();
1093
+ return;
1094
+ }
1095
+ if (key.name === "return" || key.name === "enter") {
1096
+ const chosen = items[this.picker.selIdx];
1097
+ if (!chosen || chosen.type === "header") return;
1098
+ this.picker = null;
1099
+ this.scheduleRender();
1100
+ resolve({ action: "select", item: chosen });
1101
+ return;
1102
+ }
1103
+ if (key.name === "delete" || str === "d") {
1104
+ const chosen = items[this.picker.selIdx];
1105
+ if (chosen && chosen.type === "session") {
1106
+ this.picker = null;
1107
+ this.scheduleRender();
1108
+ resolve({ action: "delete", item: chosen });
1109
+ }
1110
+ }
1111
+ }
1112
+
1113
+ _handlePermissionsKey(str, key) {
1114
+ const rules = this.onGetPermissionRules ? this.onGetPermissionRules() : [];
1115
+ const filtered = getFilteredPermissions(rules, this.permScreen.search);
1116
+
1117
+ if (key.ctrl && key.name === "c") {
1118
+ this.permScreen = null;
1119
+ this.scheduleRender();
1120
+ return;
1121
+ }
1122
+ if (key.name === "escape") {
1123
+ if (this.permScreen.search) {
1124
+ this.permScreen.search = "";
1125
+ this.permScreen.selIdx = 0;
1126
+ } else {
1127
+ this.permScreen = null;
1128
+ }
1129
+ this.scheduleRender();
1130
+ return;
1131
+ }
1132
+ if (key.name === "up" && filtered.length) {
1133
+ this.permScreen.selIdx = (this.permScreen.selIdx - 1 + filtered.length) % filtered.length;
1134
+ this.scheduleRender();
1135
+ return;
1136
+ }
1137
+ if (key.name === "down" && filtered.length) {
1138
+ this.permScreen.selIdx = (this.permScreen.selIdx + 1) % filtered.length;
1139
+ this.scheduleRender();
1140
+ return;
1141
+ }
1142
+ if ((key.name === "delete" || (str === "d" && !this.permScreen.search)) && filtered.length) {
1143
+ const sel = filtered[this.permScreen.selIdx];
1144
+ if (sel) {
1145
+ const removed = this.onRemovePermissionRule?.(sel);
1146
+ this.permScreen.notice = removed
1147
+ ? `Removed rule: ${sel.tool} (${sel.pattern || "*"})`
1148
+ : "Session rules reset when exiting or via /permissions reset.";
1149
+ }
1150
+ this.scheduleRender();
1151
+ return;
1152
+ }
1153
+ if (key.name === "backspace") {
1154
+ if (this.permScreen.search) {
1155
+ const prev = prevGraphemeBoundary(this.permScreen.search, this.permScreen.search.length);
1156
+ this.permScreen.search = this.permScreen.search.slice(0, prev);
1157
+ this.permScreen.selIdx = 0;
1158
+ this.scheduleRender();
1159
+ }
1160
+ return;
1161
+ }
1162
+ if (str && !key.ctrl && !key.meta && str >= " ") {
1163
+ this.permScreen.search += str;
1164
+ this.permScreen.selIdx = 0;
1165
+ this.permScreen.notice = "";
1166
+ this.scheduleRender();
1167
+ }
1168
+ }
1169
+
1170
+ _handleSettingsKey(str, key) {
1171
+ const sState = this.settingsScreen;
1172
+ const settings = this.onGetSettings ? this.onGetSettings() : {};
1173
+ const items = getFilteredSettings(settings, sState.search);
1174
+
1175
+ // Inline edit sub-mode (validation on Enter, no NaN allowed)
1176
+ if (sState.editing) {
1177
+ if (key.name === "escape" || (key.ctrl && key.name === "c")) {
1178
+ sState.editing = null;
1179
+ sState.editError = "";
1180
+ this.scheduleRender();
1181
+ return;
1182
+ }
1183
+ if (key.name === "return" || key.name === "enter") {
1184
+ const parsed = parseSettingValue(sState.editing.key, sState.editing.buf);
1185
+ if (!parsed.ok) {
1186
+ sState.editError = parsed.error;
1187
+ this.scheduleRender();
1188
+ return;
1189
+ }
1190
+ this.onUpdateSetting?.(parsed.key, parsed.value);
1191
+ sState.editing = null;
1192
+ sState.editError = "";
1193
+ this.scheduleRender();
1194
+ return;
1195
+ }
1196
+ if (key.name === "left") {
1197
+ sState.editing.cursor = prevGraphemeBoundary(sState.editing.buf, sState.editing.cursor);
1198
+ this.scheduleRender();
1199
+ return;
1200
+ }
1201
+ if (key.name === "right") {
1202
+ sState.editing.cursor = nextGraphemeBoundary(sState.editing.buf, sState.editing.cursor);
1203
+ this.scheduleRender();
1204
+ return;
1205
+ }
1206
+ if (key.name === "backspace") {
1207
+ if (sState.editing.cursor > 0) {
1208
+ const prev = prevGraphemeBoundary(sState.editing.buf, sState.editing.cursor);
1209
+ sState.editing.buf =
1210
+ sState.editing.buf.slice(0, prev) + sState.editing.buf.slice(sState.editing.cursor);
1211
+ sState.editing.cursor = prev;
1212
+ sState.editError = "";
1213
+ this.scheduleRender();
1214
+ }
1215
+ return;
1216
+ }
1217
+ if (key.ctrl && key.name === "u") {
1218
+ sState.editing.buf = "";
1219
+ sState.editing.cursor = 0;
1220
+ this.scheduleRender();
1221
+ return;
1222
+ }
1223
+ if (str && !key.ctrl && !key.meta && str >= " ") {
1224
+ const c = sState.editing.cursor;
1225
+ sState.editing.buf = sState.editing.buf.slice(0, c) + str + sState.editing.buf.slice(c);
1226
+ sState.editing.cursor = c + str.length;
1227
+ sState.editError = "";
1228
+ this.scheduleRender();
1229
+ }
1230
+ return;
1231
+ }
1232
+
1233
+ if (key.ctrl && key.name === "c") {
1234
+ this.settingsScreen = null;
1235
+ this.scheduleRender();
1236
+ return;
1237
+ }
1238
+ if (key.name === "escape") {
1239
+ if (sState.search) {
1240
+ sState.search = "";
1241
+ sState.selIdx = 0;
1242
+ sState.editError = "";
1243
+ } else {
1244
+ this.settingsScreen = null;
1245
+ }
1246
+ this.scheduleRender();
1247
+ return;
1248
+ }
1249
+ if (key.name === "up" && items.length) {
1250
+ sState.selIdx = (sState.selIdx - 1 + items.length) % items.length;
1251
+ sState.editError = "";
1252
+ this.scheduleRender();
1253
+ return;
1254
+ }
1255
+ if (key.name === "down" && items.length) {
1256
+ sState.selIdx = (sState.selIdx + 1) % items.length;
1257
+ sState.editError = "";
1258
+ this.scheduleRender();
1259
+ return;
1260
+ }
1261
+
1262
+ const current = items[sState.selIdx];
1263
+ if ((key.name === "left" || key.name === "right") && current) {
1264
+ const dir = key.name === "right" ? 1 : -1;
1265
+ if (current.meta.key === "provider" && this.onGetProviders) {
1266
+ const provNames = this.onGetProviders();
1267
+ if (provNames.length > 0) {
1268
+ const idx = Math.max(0, provNames.indexOf(current.value));
1269
+ const nextProv = provNames[(idx + dir + provNames.length) % provNames.length];
1270
+ this.onUpdateSetting?.("provider", nextProv);
1271
+ this.onRefreshModels?.();
1272
+ this.scheduleRender();
1273
+ return;
1274
+ }
1275
+ }
1276
+ if (current.meta.key === "model" && this.onGetModels) {
1277
+ const modelList = this.onGetModels();
1278
+ if (modelList.length > 0) {
1279
+ const idx = Math.max(0, modelList.indexOf(current.value));
1280
+ const nextModel = modelList[(idx + dir + modelList.length) % modelList.length];
1281
+ this.onUpdateSetting?.("model", nextModel);
1282
+ this.scheduleRender();
1283
+ return;
1284
+ }
1285
+ }
1286
+ const nextVal = stepSettingValue(current.meta.key, current.value, dir);
1287
+ if (nextVal !== null) {
1288
+ this.onUpdateSetting?.(current.meta.key, nextVal);
1289
+ sState.editError = "";
1290
+ this.scheduleRender();
1291
+ }
1292
+ return;
1293
+ }
1294
+
1295
+ if ((key.name === "return" || key.name === "enter") && current) {
1296
+ if (current.meta.key === "managePermissions") {
1297
+ this.openManagePermissions();
1298
+ return;
1299
+ }
1300
+ if ((current.meta.key === "provider" || current.meta.key === "model") && this.onPickSettingChoice) {
1301
+ this.onPickSettingChoice(current.meta.key);
1302
+ return;
1303
+ }
1304
+ if (current.meta.type === "boolean" || current.meta.type === "enum") {
1305
+ const nextVal = stepSettingValue(current.meta.key, current.value, 1);
1306
+ if (nextVal !== null) this.onUpdateSetting?.(current.meta.key, nextVal);
1307
+ this.scheduleRender();
1308
+ return;
1309
+ }
1310
+ const initBuf = current.value === null || current.value === undefined ? "" : String(current.value);
1311
+ sState.editing = {
1312
+ key: current.meta.key,
1313
+ label: current.meta.label,
1314
+ buf: initBuf,
1315
+ cursor: initBuf.length,
1316
+ };
1317
+ sState.editError = "";
1318
+ this.scheduleRender();
1319
+ return;
1320
+ }
1321
+
1322
+ if (key.name === "backspace") {
1323
+ if (sState.search) {
1324
+ const prev = prevGraphemeBoundary(sState.search, sState.search.length);
1325
+ sState.search = sState.search.slice(0, prev);
1326
+ sState.selIdx = 0;
1327
+ this.scheduleRender();
1328
+ }
1329
+ return;
1330
+ }
1331
+ if (key.ctrl && key.name === "u") {
1332
+ sState.search = "";
1333
+ sState.selIdx = 0;
1334
+ this.scheduleRender();
1335
+ return;
1336
+ }
1337
+ if (str && !key.ctrl && !key.meta && str >= " ") {
1338
+ sState.search += str;
1339
+ sState.selIdx = 0;
1340
+ sState.editError = "";
1341
+ this.scheduleRender();
1342
+ }
1343
+ }
1344
+
1345
+ _getAtFileSuggestions() {
1346
+ const before = this.input.slice(0, this.cursor);
1347
+ const match = before.match(/(?:^|\s)@([^\s]*)$/);
1348
+ if (!match) return [];
1349
+ const query = (match[1] || "").toLowerCase();
1350
+ const now = Date.now();
1351
+ if (!this._fileCache.files.length || now - this._fileCache.ts > 5000) {
1352
+ try {
1353
+ const { entries } = walkWorkspace(this.workspaceRoot, {
1354
+ maxDepth: 6,
1355
+ maxEntries: 600,
1356
+ includeDirs: false,
1357
+ cwdRoot: this.workspaceRoot,
1358
+ });
1359
+ this._fileCache = { ts: now, files: entries };
1360
+ } catch {
1361
+ this._fileCache = { ts: now, files: [] };
1362
+ }
1363
+ }
1364
+ const prefixLen = match[1].length;
1365
+ const startIdx = this.cursor - prefixLen;
1366
+ const after = this.input.slice(this.cursor);
1367
+ const hits = [];
1368
+ for (const rel of this._fileCache.files) {
1369
+ const lower = rel.toLowerCase();
1370
+ if (!query || lower.includes(query)) {
1371
+ hits.push({
1372
+ rel,
1373
+ score: lower.startsWith(query) ? 0 : lower.split("/").pop().startsWith(query) ? 1 : 2,
1374
+ });
1375
+ }
1376
+ }
1377
+ hits.sort((a, b) => a.score - b.score || a.rel.length - b.rel.length);
1378
+ return hits.slice(0, 6).map(({ rel }) => ({
1379
+ cmd: `@${rel}`,
1380
+ label: `@${rel}`,
1381
+ fill: `${this.input.slice(0, startIdx)}${rel} ${after}`,
1382
+ desc: "file",
1383
+ isFileMention: true,
1384
+ }));
1385
+ }
1386
+
1387
+ _getActiveSuggestions() {
1388
+ if (this.input.startsWith("/")) return getSlashSuggestions(this.input);
1389
+ return this._getAtFileSuggestions();
1390
+ }
1391
+
1392
+ _prevWordBoundary(pos) {
1393
+ let i = Math.max(0, pos);
1394
+ while (i > 0 && /\s/.test(this.input[i - 1])) i--;
1395
+ while (i > 0 && !/\s/.test(this.input[i - 1])) i--;
1396
+ return i;
1397
+ }
1398
+
1399
+ _nextWordBoundary(pos) {
1400
+ let i = Math.min(this.input.length, pos);
1401
+ while (i < this.input.length && !/\s/.test(this.input[i])) i++;
1402
+ while (i < this.input.length && /\s/.test(this.input[i])) i++;
1403
+ return i;
1404
+ }
1405
+
1406
+ _handleComposerKey(str, key) {
1407
+ if (key.name === "f2") {
1408
+ this.toggleMouseMode();
1409
+ return;
1410
+ }
1411
+ if (key.ctrl && key.name === "y") {
1412
+ this.copyLastResponse();
1413
+ return;
1414
+ }
1415
+ if (key.ctrl && key.name === "s") {
1416
+ this.onOpenSessions?.();
1417
+ return;
1418
+ }
1419
+ if (key.ctrl && key.name === "n") {
1420
+ this.onNewSession?.();
1421
+ return;
1422
+ }
1423
+ if (key.ctrl && key.name === "o") {
1424
+ this.toggleLastCollapsibleBlock();
1425
+ return;
1426
+ }
1427
+ if (key.ctrl && key.name === "l") {
1428
+ this.scrollOffset = 0;
1429
+ this.stdout.write("\x1b[2J\x1b[H");
1430
+ this.scheduleRender();
1431
+ return;
1432
+ }
1433
+ if (key.name === "tab" && key.shift) {
1434
+ this.onCycleMode?.();
1435
+ return;
1436
+ }
1437
+ const busy = Boolean(this.status.isBusy || this.status.busyLabel);
1438
+ if (key.name === "escape") {
1439
+ if (this.input.length > 0) {
1440
+ this.input = "";
1441
+ this.cursor = 0;
1442
+ this.selIdx = 0;
1443
+ this.scheduleRender();
1444
+ return;
1445
+ }
1446
+ if (busy) {
1447
+ this.onCancel?.();
1448
+ this.flashNotice("Cancelled task — restored to input box", 2200);
1449
+ }
1450
+ return;
1451
+ }
1452
+ if (key.ctrl && key.name === "c") {
1453
+ const now = Date.now();
1454
+ if (busy) {
1455
+ if (now - this.lastCtrlCAt < 2500) {
1456
+ this.onExit?.();
1457
+ } else {
1458
+ this.lastCtrlCAt = now;
1459
+ this.onCancel?.();
1460
+ this.flashNotice("Cancelled task — restored to input (press Ctrl+C again to exit)", 2400);
1461
+ }
1462
+ } else {
1463
+ this.onExit?.();
1464
+ }
1465
+ return;
1466
+ }
1467
+ if (key.ctrl && key.name === "d" && !this.input.length) {
1468
+ this.onExit?.();
1469
+ return;
1470
+ }
1471
+ if (key.name === "pageup") {
1472
+ this.scrollOffset += 6;
1473
+ this.scheduleRender();
1474
+ return;
1475
+ }
1476
+ if (key.name === "pagedown") {
1477
+ this.scrollOffset = Math.max(0, this.scrollOffset - 6);
1478
+ this.scheduleRender();
1479
+ return;
1480
+ }
1481
+ // Shift+Enter, Alt+Enter, or Ctrl+J -> newline inside multi-line composer (preserved intact)
1482
+ if (
1483
+ key.sequence === "\n" ||
1484
+ ((key.name === "return" || key.name === "enter") && (key.shift || key.meta)) ||
1485
+ key.name === "linefeed" ||
1486
+ (key.ctrl && key.name === "j")
1487
+ ) {
1488
+ this.insertNewline();
1489
+ return;
1490
+ }
1491
+ if (key.name === "return" || key.name === "enter") {
1492
+ const activeSugs = this._getActiveSuggestions();
1493
+ if (activeSugs.length && activeSugs[0]?.isFileMention) {
1494
+ const picked = activeSugs[Math.min(this.selIdx, activeSugs.length - 1)];
1495
+ this.input = picked.fill;
1496
+ this.cursor = this.input.length;
1497
+ this.selIdx = 0;
1498
+ this.scheduleRender();
1499
+ return;
1500
+ }
1501
+ const res = resolveSlashEnter(this.input, this.selIdx);
1502
+ if (res.action === "fill") {
1503
+ this.input = res.value;
1504
+ this.cursor = this.input.length;
1505
+ this.selIdx = 0;
1506
+ this.scheduleRender();
1507
+ return;
1508
+ }
1509
+ const val = res.value;
1510
+ this.input = "";
1511
+ this.cursor = 0;
1512
+ this.selIdx = 0;
1513
+ if (val) {
1514
+ this.scrollOffset = 0;
1515
+ if (!val.startsWith("/") && this.inputHistory[this.inputHistory.length - 1] !== val) {
1516
+ this.inputHistory.push(val);
1517
+ this.onSaveInputHistory?.(this.inputHistory);
1518
+ }
1519
+ this.histIdx = this.inputHistory.length;
1520
+ this.onSubmit?.(val);
1521
+ }
1522
+ this.scheduleRender();
1523
+ return;
1524
+ }
1525
+ if (key.name === "tab") {
1526
+ const suggestions = this._getActiveSuggestions();
1527
+ if (suggestions.length) {
1528
+ this.input = suggestions[Math.min(this.selIdx, suggestions.length - 1)].fill;
1529
+ this.cursor = this.input.length;
1530
+ this.selIdx = 0;
1531
+ this.scheduleRender();
1532
+ }
1533
+ return;
1534
+ }
1535
+ if (key.name === "up") {
1536
+ const suggestions = this._getActiveSuggestions();
1537
+ if (suggestions.length) {
1538
+ this.selIdx = (this.selIdx - 1 + suggestions.length) % suggestions.length;
1539
+ } else if (this.inputHistory.length && this.histIdx > 0) {
1540
+ this.histIdx--;
1541
+ this.input = this.inputHistory[this.histIdx];
1542
+ this.cursor = this.input.length;
1543
+ }
1544
+ this.scheduleRender();
1545
+ return;
1546
+ }
1547
+ if (key.name === "down") {
1548
+ const suggestions = this._getActiveSuggestions();
1549
+ if (suggestions.length) {
1550
+ this.selIdx = (this.selIdx + 1) % suggestions.length;
1551
+ } else if (this.histIdx < this.inputHistory.length) {
1552
+ this.histIdx++;
1553
+ this.input = this.histIdx < this.inputHistory.length ? this.inputHistory[this.histIdx] : "";
1554
+ this.cursor = this.input.length;
1555
+ }
1556
+ this.scheduleRender();
1557
+ return;
1558
+ }
1559
+ if ((key.ctrl && key.name === "left") || (key.meta && key.name === "b")) {
1560
+ this.cursor = this._prevWordBoundary(this.cursor);
1561
+ this.scheduleRender();
1562
+ return;
1563
+ }
1564
+ if ((key.ctrl && key.name === "right") || (key.meta && key.name === "f")) {
1565
+ this.cursor = this._nextWordBoundary(this.cursor);
1566
+ this.scheduleRender();
1567
+ return;
1568
+ }
1569
+ if (key.name === "left") {
1570
+ this.cursor = prevGraphemeBoundary(this.input, this.cursor);
1571
+ this.scheduleRender();
1572
+ return;
1573
+ }
1574
+ if (key.name === "right") {
1575
+ this.cursor = nextGraphemeBoundary(this.input, this.cursor);
1576
+ this.scheduleRender();
1577
+ return;
1578
+ }
1579
+ if (key.name === "home" || (key.ctrl && key.name === "a")) {
1580
+ this.cursor = 0;
1581
+ this.scheduleRender();
1582
+ return;
1583
+ }
1584
+ if (key.name === "end" || (key.ctrl && key.name === "e")) {
1585
+ this.cursor = this.input.length;
1586
+ this.scheduleRender();
1587
+ return;
1588
+ }
1589
+ if ((key.meta && key.name === "backspace") || (key.ctrl && key.name === "w")) {
1590
+ if (this.cursor > 0) {
1591
+ const prev = this._prevWordBoundary(this.cursor);
1592
+ this.input = this.input.slice(0, prev) + this.input.slice(this.cursor);
1593
+ this.cursor = prev;
1594
+ this.selIdx = 0;
1595
+ this.scheduleRender();
1596
+ }
1597
+ return;
1598
+ }
1599
+ if (key.name === "backspace") {
1600
+ if (this.cursor > 0) {
1601
+ const prev = prevGraphemeBoundary(this.input, this.cursor);
1602
+ this.input = this.input.slice(0, prev) + this.input.slice(this.cursor);
1603
+ this.cursor = prev;
1604
+ this.selIdx = 0;
1605
+ this.scheduleRender();
1606
+ }
1607
+ return;
1608
+ }
1609
+ if (key.name === "delete") {
1610
+ if (this.cursor < this.input.length) {
1611
+ const next = nextGraphemeBoundary(this.input, this.cursor);
1612
+ this.input = this.input.slice(0, this.cursor) + this.input.slice(next);
1613
+ this.selIdx = 0;
1614
+ this.scheduleRender();
1615
+ }
1616
+ return;
1617
+ }
1618
+ if (key.ctrl && key.name === "u") {
1619
+ this.input = "";
1620
+ this.cursor = 0;
1621
+ this.selIdx = 0;
1622
+ this.scheduleRender();
1623
+ return;
1624
+ }
1625
+ if (str && !key.ctrl && !key.meta && str >= " ") {
1626
+ this.input = this.input.slice(0, this.cursor) + str + this.input.slice(this.cursor);
1627
+ this.cursor += str.length;
1628
+ this.selIdx = 0;
1629
+ this.scheduleRender();
1630
+ }
1631
+ }
1632
+ }
1633
+
1634
+ module.exports = { KovenceTUI, layoutComposer };