minicode-ai 0.9.28 → 0.10.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 (48) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/cli/args.ts +1 -0
  3. package/cli/commands.ts +219 -103
  4. package/cli/index.ts +8 -6
  5. package/cli/model-manager.ts +2 -7
  6. package/cli/provider-manager.ts +13 -13
  7. package/cli/setup.ts +10 -1
  8. package/cli/tui.ts +506 -0
  9. package/cli/wizard.ts +2 -1
  10. package/docs/ARCHITECTURE.html +41 -22
  11. package/docs/README.md +1 -0
  12. package/package.json +3 -3
  13. package/src/app/rag-layer.ts +7 -2
  14. package/src/config.ts +30 -1
  15. package/src/policy/bash-guard.ts +64 -8
  16. package/src/policy/update-check.ts +4 -1
  17. package/src/tools/bash.ts +8 -0
  18. package/src/tools/task.ts +6 -1
  19. package/src/tools/web_fetch.ts +11 -2
  20. package/src/tools/web_search.ts +4 -1
  21. package/src/ui/approval/prompt.ts +84 -18
  22. package/src/ui/assistant/simple.ts +55 -22
  23. package/src/ui/assistant/turn-status.ts +16 -7
  24. package/src/ui/footer.ts +14 -12
  25. package/src/ui/i18n/en.ts +225 -0
  26. package/src/ui/i18n/id.ts +227 -0
  27. package/src/ui/i18n/locale.ts +66 -0
  28. package/src/ui/input/input.ts +138 -77
  29. package/src/ui/input/prompt-engine.ts +97 -4
  30. package/src/ui/render/collapse.ts +8 -1
  31. package/src/ui/render/errors.ts +75 -50
  32. package/src/ui/render/format.ts +15 -5
  33. package/src/ui/render/highlight.ts +5 -2
  34. package/src/ui/render/table.ts +7 -4
  35. package/src/ui/render/theme.ts +8 -3
  36. package/src/ui/render/width.ts +17 -9
  37. package/src/ui/runtime/screen.ts +197 -0
  38. package/src/ui/screens/dialog.ts +174 -0
  39. package/src/ui/screens/form.ts +459 -0
  40. package/src/ui/screens/model-manager.ts +274 -127
  41. package/src/ui/screens/picker.ts +229 -98
  42. package/src/ui/screens/provider-manager.ts +371 -164
  43. package/src/ui/screens/wizard.ts +149 -102
  44. package/src/ui/tui/app.ts +745 -0
  45. package/src/ui/tui/transcript.ts +271 -0
  46. package/cli/repl.ts +0 -740
  47. package/src/ui/runtime/chrome.ts +0 -369
  48. package/src/ui/screens/overlay.ts +0 -61
@@ -0,0 +1,745 @@
1
+ // App TUI — pemilik tunggal layar mode `--tui` (kontrak I17-I20).
2
+ //
3
+ // Arsitektur: SATU repaint sinkron per event. Tak ada painter lain yang aktif
4
+ // bersamaan (turn berjalan = spark pada status bar, bukan painter). Frame
5
+ // selalu TEPAT `rows` baris: transkrip viewport + dropdown `/` + blok input +
6
+ // status bar. Kursor diparkir di posisi ketik setelah paint.
7
+ //
8
+ // Batas lapisan: semua yang berbau sesi/model/turn datang via TuiHost yang
9
+ // di-inject dari cli/ (composition root). src/ui TAK BOLEH impor cli/.
10
+ import type { UiBus } from "../contract.ts"
11
+ import { type FooterStatus, renderFooter } from "../footer.ts"
12
+ import { t } from "../i18n/locale.ts"
13
+ import {
14
+ applyKey,
15
+ createDecoderState,
16
+ createKeyStreamPump,
17
+ createState,
18
+ type DecoderState,
19
+ type KeyStreamPump,
20
+ type PromptKey,
21
+ type PromptState,
22
+ toGraphemes,
23
+ } from "../input/prompt-engine.ts"
24
+ import { sanitizeAnsiLine } from "../render/sanitize.ts"
25
+ import { c } from "../render/theme.ts"
26
+ import { chunkByWidth, displayWidth, truncateToWidth } from "../render/width.ts"
27
+ import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
28
+ import type { Transcript } from "./transcript.ts"
29
+
30
+ export interface TuiStatusSnapshot {
31
+ footer: FooterStatus
32
+ busy: boolean
33
+ }
34
+
35
+ export interface TuiHost {
36
+ bus: UiBus
37
+ /** Status untuk bar status (mode/model/cwd/konteks dari sumber = footer). */
38
+ getStatus(): TuiStatusSnapshot
39
+ /** Hint dropdown untuk baris "/" (slash + skill, difilter prefix). */
40
+ listCommands(prefix: string): string[]
41
+ /**
42
+ * Eksekusi baris yang di-submit: builtin (/exit, /clear, /help, …) atau
43
+ * prompt ke model. Resolve {quit:true} untuk keluar. Throw = App tampilkan
44
+ * sebagai baris error (tak ada jalur diam).
45
+ */
46
+ submit(text: string): Promise<{ quit?: boolean } | undefined>
47
+ /** Batalkan turn yang berjalan (Esc/Ctrl+C saat busy). */
48
+ abort(): void
49
+ /** Putar mode permission (Tab / Shift+Tab). */
50
+ cycleMode(dir: 1 | -1): void
51
+ /** Toggle compact / reasoning (Ctrl+O / Ctrl+T). */
52
+ toggleCompact(): void
53
+ toggleReasoning(): void
54
+ }
55
+
56
+ export interface TuiRunResult {
57
+ /** False = layar tak mampu (non-TTY/dumb/sempit) — caller fallback REPL. */
58
+ started: boolean
59
+ frames: number
60
+ }
61
+
62
+ /** Tinggi maksimum blok input (baris logis di-wrap, kursor selalu terlihat). */
63
+ const MAX_INPUT_ROWS = 5
64
+ /** Tinggi maksimum dropdown — sisa ruang di atas transcript minimum 3 baris. */
65
+ const MAX_DROPDOWN_ROWS = 8
66
+ const MIN_ROWS = 10
67
+ const MIN_COLS = 20
68
+
69
+ const PROMPT_FIRST = "minicode › "
70
+ const PROMPT_CONT = " "
71
+
72
+ interface RawStdin {
73
+ setRawMode(v: boolean): void
74
+ on(e: string, fn: (c: Buffer) => void): void
75
+ removeListener(e: string, fn: (c: Buffer) => void): void
76
+ resume(): void
77
+ pause(): void
78
+ isTTY?: boolean
79
+ }
80
+
81
+ export class TuiApp {
82
+ private state: PromptState = createState()
83
+ private scrollBack = 0
84
+ private history: string[] = []
85
+ private histIdx = -1
86
+ private draft = ""
87
+ private busy = false
88
+ private tick = 0
89
+ /** Timestamp abort terakhir (ms) — deteksi double-tap Esc/Ctrl+C = quit. */
90
+ private lastAbortAt = 0
91
+ private frames = 0
92
+ private quitRequested = false
93
+ private finish: (() => void) | null = null
94
+ private decoder: DecoderState = createDecoderState()
95
+ private pump: KeyStreamPump | null = null
96
+ private onData: ((chunk: Buffer) => void) | null = null
97
+ private onResize: (() => void) | null = null
98
+ private wasRaw = false
99
+ /**
100
+ * Kedalaman suspend (popup komposit memegang fokus). >0 = listener stdin
101
+ * dilepas + repaint ditahan — byte masuk HANYA ke view popup.
102
+ */
103
+ private suspended = 0
104
+ private stdin: RawStdin | null = null
105
+ /** True setelah releaseTerminal (spawn anak): paint/repaint ditahan. */
106
+ private released = false
107
+ /**
108
+ * Langganan bus untuk repaint live (streaming jawaban, ledger tool,
109
+ * thinking): TANPA ini layar buta selama turn — teks baru hanya tampil
110
+ * saat turn selesai / tombol ditekan. Coalesce 30ms agar burst chunk tak
111
+ * melukis ulang tiap byte.
112
+ */
113
+ private busUnsubs: (() => void)[] = []
114
+ private repaintTimer: ReturnType<typeof setTimeout> | undefined
115
+ /** Ukuran transkrip saat terakhir ikut ekor (basis indikator "baru"). */
116
+ private tailSize = 0
117
+ /** Ukuran transkrip saat mulai scroll ke atas (basis hitung baris baru). */
118
+ private scrollBase = 0
119
+
120
+ constructor(
121
+ private readonly transcript: Transcript,
122
+ private readonly host: TuiHost,
123
+ ) {}
124
+
125
+ /** Jalan sampai quit. Alt-screen enter/exit SELALU berpasangan (I17). */
126
+ async run(): Promise<TuiRunResult> {
127
+ // Cek ukuran SEBELUM enter: terminal sempit langsung fallback tanpa
128
+ // flicker masuk-keluar alt-screen (kontrak residual #7).
129
+ const preRows = process.stdout.rows || 0
130
+ const preCols = process.stdout.columns || 0
131
+ if (preRows < MIN_ROWS || preCols < MIN_COLS) return { started: false, frames: 0 }
132
+ const screen = openAltScreen()
133
+ if (!screen.ok || screen.rows < MIN_ROWS || screen.cols < MIN_COLS) {
134
+ try {
135
+ screen.close()
136
+ } catch {}
137
+ return { started: false, frames: 0 }
138
+ }
139
+ const stdin = process.stdin as unknown as RawStdin
140
+ this.stdin = stdin
141
+ try {
142
+ this.wasRaw =
143
+ (stdin as unknown as { isRaw?: boolean }).isRaw ??
144
+ (process.stdin as unknown as { isRaw?: boolean }).isRaw ??
145
+ false
146
+ } catch {
147
+ this.wasRaw = false
148
+ }
149
+ const done = new Promise<void>((resolve) => (this.finish = resolve))
150
+ this.pump = createKeyStreamPump({
151
+ state: this.decoder,
152
+ onKeys: (keys) => this.handleKeys(keys),
153
+ })
154
+ this.onData = (chunk: Buffer) => this.pump?.push(new Uint8Array(chunk))
155
+ this.onResize = () => {
156
+ // Saat popup fokus, view popup yang melukis ulang regionnya sendiri;
157
+ // repaint penuh App akan menghapus popup dari layar.
158
+ if (this.suspended > 0) return
159
+ this.paint(screen)
160
+ }
161
+ try {
162
+ stdin.setRawMode(true)
163
+ } catch {}
164
+ try {
165
+ stdin.resume()
166
+ } catch {}
167
+ stdin.on("data", this.onData)
168
+ const stdout = process.stdout as unknown as {
169
+ on(e: string, fn: () => void): void
170
+ removeListener(e: string, fn: () => void): void
171
+ }
172
+ stdout.on("resize", this.onResize)
173
+ // Repaint live mengikuti event bus (stream teks, ledger, thinking).
174
+ // Suspend menahan repaint (popup melukis sendiri); quit menahan semua.
175
+ const requestPaint = () => {
176
+ if (this.quitRequested || this.suspended > 0 || this.released) return
177
+ if (this.repaintTimer !== undefined) return
178
+ this.repaintTimer = setTimeout(() => {
179
+ this.repaintTimer = undefined
180
+ if (!this.quitRequested && this.suspended === 0 && !this.released) this.paint(screen)
181
+ }, 30)
182
+ try {
183
+ ;(this.repaintTimer as unknown as { unref?: () => void }).unref?.()
184
+ } catch {}
185
+ }
186
+ const sub = (type: Parameters<UiBus["on"]>[0]) => {
187
+ try {
188
+ this.busUnsubs.push(this.host.bus.on(type, requestPaint))
189
+ } catch {}
190
+ }
191
+ sub("provider:text")
192
+ sub("provider:extension")
193
+ sub("execution:started")
194
+ sub("execution:completed")
195
+ sub("turn:started")
196
+ sub("turn:completed")
197
+ sub("context:compacted")
198
+ this.tailSize = this.transcript.size()
199
+ this.scrollBase = this.tailSize
200
+ this.paint(screen)
201
+ await done
202
+ // Cleanup: urutan penting — lepas listener dulu agar byte liar pasca-quit
203
+ // tak memicu repaint ke layar yang sudah dikembalikan.
204
+ stdin.removeListener("data", this.onData)
205
+ stdout.removeListener("resize", this.onResize)
206
+ if (this.repaintTimer !== undefined) {
207
+ clearTimeout(this.repaintTimer)
208
+ this.repaintTimer = undefined
209
+ }
210
+ for (const u of this.busUnsubs) {
211
+ try {
212
+ u()
213
+ } catch {}
214
+ }
215
+ this.busUnsubs = []
216
+ this.suspended = 0
217
+ this.released = false
218
+ this.stdin = null
219
+ this.pump.dispose()
220
+ this.pump = null
221
+ try {
222
+ stdin.setRawMode(this.wasRaw)
223
+ } catch {}
224
+ try {
225
+ stdin.pause()
226
+ } catch {}
227
+ try {
228
+ // Tutup layar AKTIF (bisa diganti reacquireTerminal setelah spawn
229
+ // gagal — menutup handle run() yang basi akan meninggalkan alt-screen
230
+ // yatim; close() idempoten sehingga aman dua kali).
231
+ this.currentScreen?.close()
232
+ } catch {}
233
+ this.currentScreen = null
234
+ return { started: true, frames: this.frames }
235
+ }
236
+
237
+ // ── Penanganan key ──
238
+
239
+ private handleKeys(keys: { key: PromptKey }[]): boolean {
240
+ // Garda suspend: timer flush lone-ESC yang dipersenjatai SEBELUM suspend
241
+ // tetap menembak setelah popup terbuka (listener dilepas, timer tidak).
242
+ // Tanpa ini repaint penuh App 50ms kemudian menimpa region popup +
243
+ // memutasi state di belakang view. Gagal-di-kode-lama.
244
+ if (this.suspended > 0) return false
245
+ for (const { key } of keys) {
246
+ if (this.quitRequested) return true
247
+ this.handleKey(key)
248
+ }
249
+ return this.quitRequested
250
+ }
251
+
252
+ private handleKey(key: PromptKey): void {
253
+ // Terminal menciut di bawah minimum: abaikan SEMUA kecuali keluar.
254
+ // Tanpa ini layout rusak (kolom negatif, kursor melompat) dan user
255
+ // terkunci tanpa jalan keluar yang terlihat.
256
+ if (this.tooSmall()) {
257
+ if (key.type === "ctrl-d") this.quit()
258
+ return
259
+ }
260
+ // Scroll SELALU tersedia (menu buka/tutup, busy/idle) — di-intercept
261
+ // sebelum engine supaya tak jadi histori maupun teks.
262
+ if (key.type === "pageup" || key.type === "pagedown") {
263
+ this.scrollBy(key.type === "pageup" ? 1 : -1)
264
+ return
265
+ }
266
+ // Abort/batal: Esc & Ctrl+C. Saat busy = abort turn; idle = bersih baris.
267
+ // Jalan keluar saat abort macet (provider/tool non-kooperatif abaikan
268
+ // sinyal): Esc/Ctrl+C KEDUA dalam 1.5 dtk, atau Ctrl+D baris-kosong,
269
+ // = abort + quit. Tanpa ini sesi hanya bisa dibunuh kill -9 (kontrak I14).
270
+ if (key.type === "esc" || key.type === "ctrl-c") {
271
+ if (this.busy) {
272
+ try {
273
+ this.host.abort()
274
+ } catch {}
275
+ const now = Date.now()
276
+ const doubleTap = now - this.lastAbortAt < 1500
277
+ this.lastAbortAt = now
278
+ if (doubleTap) this.quit()
279
+ return
280
+ }
281
+ if (key.type === "esc" && this.state.menuOpen) {
282
+ this.applyEngine(key)
283
+ return
284
+ }
285
+ if (this.state.line) {
286
+ this.state = createState()
287
+ this.histIdx = -1
288
+ this.paintCurrent()
289
+ }
290
+ return
291
+ }
292
+ // Saat turn berjalan SEMUA input dibekukan kecuali abort (Esc/Ctrl+C),
293
+ // scroll (PgUp/PgDn di atas), dan Ctrl+D baris-kosong (= abort + quit,
294
+ // jalan keluar saat abort macet — kontrak I14).
295
+ if (this.busy) {
296
+ if (key.type === "ctrl-d" && !this.state.line) {
297
+ try {
298
+ this.host.abort()
299
+ } catch {}
300
+ this.quit()
301
+ }
302
+ return
303
+ }
304
+ if (key.type === "ctrl-d") {
305
+ // Baris kosong = keluar (konvensi EOF); berisi = abaikan (I19).
306
+ if (!this.state.line) this.quit()
307
+ return
308
+ }
309
+ if (key.type === "tab") {
310
+ this.host.cycleMode(1)
311
+ this.paintCurrent()
312
+ return
313
+ }
314
+ if (key.type === "shift-tab") {
315
+ this.host.cycleMode(-1)
316
+ this.paintCurrent()
317
+ return
318
+ }
319
+ if (key.type === "ctrl-o") {
320
+ this.host.toggleCompact()
321
+ this.paintCurrent()
322
+ return
323
+ }
324
+ if (key.type === "ctrl-t") {
325
+ this.host.toggleReasoning()
326
+ this.paintCurrent()
327
+ return
328
+ }
329
+ if (key.type === "ctrl-r") {
330
+ this.historySearch()
331
+ return
332
+ }
333
+ // Up/Down di luar menu = histori (bukan scroll — scroll milik PgUp/PgDn).
334
+ if ((key.type === "up" || key.type === "down") && !this.state.menuOpen) {
335
+ this.historyNav(key.type === "up" ? -1 : 1)
336
+ return
337
+ }
338
+ this.applyEngine(key)
339
+ }
340
+
341
+ private applyEngine(key: PromptKey): void {
342
+ const hints = (line: string) => (line.startsWith("/") ? this.host.listCommands(line) : [])
343
+ const { state, action } = applyKey(this.state, key, hints)
344
+ this.state = state
345
+ if (action === "submit") {
346
+ void this.doSubmit(state.line)
347
+ } else if (action === "cancel") {
348
+ // Engine cancel (ctrl-c/ctrl-d) sudah ditangani di atas; tak terjangkau.
349
+ } else if (action === "render" || action === "none") {
350
+ // Ketikan baru = kembali ke ekor (I18); stream turn TIDAK me-reset
351
+ // (user yang sedang membaca ke atas tak dirampas).
352
+ if (key.type === "char" || key.type === "backspace" || key.type === "delete") {
353
+ this.followTail()
354
+ }
355
+ this.paintCurrent()
356
+ }
357
+ }
358
+
359
+ private async doSubmit(rawLine: string): Promise<void> {
360
+ const line = rawLine.trim()
361
+ this.state = createState()
362
+ this.histIdx = -1
363
+ this.followTail()
364
+ if (!line) {
365
+ this.paintCurrent()
366
+ return
367
+ }
368
+ this.rememberHistory(line)
369
+ this.transcript.pushUser(rawLine)
370
+ this.busy = true
371
+ this.lastAbortAt = 0
372
+ this.paintCurrent()
373
+ try {
374
+ const res = await this.host.submit(line)
375
+ if (res?.quit) this.quit()
376
+ } catch (e) {
377
+ this.transcript.pushError(e instanceof Error ? e.message : String(e))
378
+ } finally {
379
+ this.busy = false
380
+ if (!this.quitRequested) this.paintCurrent()
381
+ }
382
+ }
383
+
384
+ private quit(): void {
385
+ if (this.quitRequested) return
386
+ this.quitRequested = true
387
+ this.finish?.()
388
+ }
389
+
390
+ /**
391
+ * Minta keluar (dipakai controller saat terminal tak bisa dihidupkan lagi
392
+ * setelah spawn gagal — daripada TUI mati tanpa layar).
393
+ */
394
+ requestQuit(): void {
395
+ this.quit()
396
+ }
397
+
398
+ /**
399
+ * Bekukan App untuk popup komposit: lepas listener stdin (byte masuk HANYA
400
+ * ke view popup — anti double-handling) + redupkan layar sebagai backdrop.
401
+ * View melukis kotaknya sendiri via paintRegion; tutup = resume().
402
+ */
403
+ suspend(): void {
404
+ if (!this.currentScreen || this.quitRequested) return
405
+ if (this.suspended++ > 0) return
406
+ try {
407
+ if (this.onData) this.stdin?.removeListener("data", this.onData)
408
+ } catch {}
409
+ this.paintDimmed()
410
+ }
411
+
412
+ /**
413
+ * Kembalikan fokus: rebut raw mode + pasang listener + repaint penuh
414
+ * (menimpa region popup). Idempoten terhadap resume berlebih. No-op bila
415
+ * terminal dilepas untuk spawn anak (releaseTerminal) — kebangkitan
416
+ * eksplisit lewat reacquireTerminal.
417
+ */
418
+ resume(): void {
419
+ if (this.released || this.suspended <= 0) return
420
+ if (--this.suspended > 0) return
421
+ try {
422
+ this.stdin?.setRawMode(true)
423
+ } catch {}
424
+ try {
425
+ if (this.onData) this.stdin?.on("data", this.onData)
426
+ } catch {}
427
+ this.paintCurrent()
428
+ }
429
+
430
+ /**
431
+ * Lepas terminal untuk spawn anak stdio-inherit (/sessions <id>): keluar
432
+ * alt-screen + cooked mode + lepas listener. Tanpa ini anak mewarisi buffer
433
+ * ?1049h + raw mode (double-ENTER, EXIT anak merobek buffer parent,
434
+ * stdin mentah macet). Gagal-di-kode-lama: layar korup + terminal rusak
435
+ * setelah anak keluar.
436
+ */
437
+ releaseTerminal(): void {
438
+ try {
439
+ if (this.onData) this.stdin?.removeListener("data", this.onData)
440
+ } catch {}
441
+ try {
442
+ this.stdin?.setRawMode(false)
443
+ } catch {}
444
+ try {
445
+ this.currentScreen?.close()
446
+ } catch {}
447
+ this.currentScreen = null
448
+ this.released = true
449
+ }
450
+
451
+ /**
452
+ * Hidupkan kembali terminal setelah release (jalur spawn GAGAL — anak tak
453
+ * jalan sehingga parent harus lanjut). No-op bila tidak dilepas. False =
454
+ * terminal tak mampu lagi → pemanggil harus quit. Listener stdin TIDAK
455
+ * dipasang di sini (tugas resume() di finally pemanggil) agar tak ganda.
456
+ */
457
+ reacquireTerminal(): boolean {
458
+ if (!this.released) return true
459
+ if (this.quitRequested) return false
460
+ const screen = openAltScreen()
461
+ if (!screen.ok) return false
462
+ this.currentScreen = screen
463
+ this.released = false
464
+ try {
465
+ this.stdin?.setRawMode(true)
466
+ } catch {}
467
+ this.paintCurrent()
468
+ return true
469
+ }
470
+
471
+ /** True saat popup/modal memegang fokus (input App dibekukan). */
472
+ isSuspended(): boolean {
473
+ return this.suspended > 0
474
+ }
475
+
476
+ /** Layar redup sebagai backdrop popup: frame normal dibungkus faint. */
477
+ private paintDimmed(): void {
478
+ const screen = this.currentScreen
479
+ if (!screen) return
480
+ const cols = screen.cols
481
+ const rows = screen.rows
482
+ const snap = this.host.getStatus()
483
+ const statusLine = renderFooter({ ...snap.footer, sparkFrame: 0 }, cols)[0] ?? ""
484
+ const menu = this.menuRows(rows, cols)
485
+ const inputAll = this.inputRows(cols)
486
+ const inputH = Math.min(MAX_INPUT_ROWS, Math.max(1, inputAll.length))
487
+ const viewH = Math.max(1, rows - 1 - inputH - menu.length)
488
+ const body = this.transcript.view(cols, viewH, this.scrollBack)
489
+ const frame: string[] = [...body, ...menu, ...inputAll.slice(-inputH), statusLine]
490
+ while (frame.length < rows) frame.unshift("")
491
+ const dimmed = frame.slice(-rows).map((ln) => `\x1b[2m${ln}\x1b[22m`)
492
+ try {
493
+ screen.paint(dimmed)
494
+ } catch {}
495
+ this.frames++
496
+ }
497
+
498
+ // ── Histori prompt (memori sesi; tak persist ke berkas REPL) ──
499
+
500
+ private rememberHistory(line: string): void {
501
+ if (this.history[this.history.length - 1] !== line) this.history.push(line)
502
+ if (this.history.length > 200) this.history.splice(0, this.history.length - 200)
503
+ }
504
+
505
+ private historyNav(dir: -1 | 1): void {
506
+ if (!this.history.length) return
507
+ if (this.histIdx === -1) {
508
+ if (dir > 0) return
509
+ this.draft = this.state.line
510
+ this.histIdx = this.history.length - 1
511
+ } else {
512
+ const next = this.histIdx + dir
513
+ if (next < 0) return
514
+ if (next >= this.history.length) {
515
+ this.histIdx = -1
516
+ this.setLine(this.draft)
517
+ return
518
+ }
519
+ this.histIdx = next
520
+ }
521
+ this.setLine(this.history[this.histIdx] ?? "")
522
+ }
523
+
524
+ private historySearch(): void {
525
+ const prefix = this.state.line
526
+ for (let i = this.history.length - 1; i >= 0; i--) {
527
+ const h = this.history[i]!
528
+ if (h !== prefix && h.startsWith(prefix)) {
529
+ this.setLine(h)
530
+ return
531
+ }
532
+ }
533
+ }
534
+
535
+ private setLine(line: string): void {
536
+ // Bangun ulang state lewat engine (aturan menu/sel ikut terjaga). Baris
537
+ // berubah = kembali ke ekor (paritas ketikan — viewport tidak diam).
538
+ this.followTail()
539
+ let s = createState()
540
+ const hints = (l: string) => (l.startsWith("/") ? this.host.listCommands(l) : [])
541
+ for (const ch of line) {
542
+ const r = applyKey(s, { type: "char", ch }, hints)
543
+ s = r.state
544
+ if (r.action !== "render" && r.action !== "none") break
545
+ }
546
+ this.state = s
547
+ this.paintCurrent()
548
+ }
549
+
550
+ // ── Scroll ──
551
+
552
+ private scrollBy(pages: number): void {
553
+ const rows = process.stdout.rows || 24
554
+ const page = Math.max(1, this.viewportHeight(rows, process.stdout.columns || 80) - 1)
555
+ // scrollBack dihitung dalam BARIS agar presisi di terminal pendek. Basis
556
+ // hitung "baris baru" dicatat saat mulai meninggalkan ekor.
557
+ if (this.scrollBack === 0 && pages > 0) this.scrollBase = this.transcript.size()
558
+ this.scrollBack = Math.max(0, this.scrollBack + pages * page)
559
+ if (this.scrollBack === 0) {
560
+ this.tailSize = this.transcript.size()
561
+ this.scrollBase = this.tailSize
562
+ }
563
+ this.paintCurrent()
564
+ }
565
+
566
+ /** Kembali ke ekor: dipakai tiap ketikan/submit baru (I18). */
567
+ private followTail(): void {
568
+ this.scrollBack = 0
569
+ this.tailSize = this.transcript.size()
570
+ this.scrollBase = this.tailSize
571
+ }
572
+
573
+ // ── Paint ──
574
+
575
+ private currentScreen: AltScreen | null = null
576
+
577
+ private paintCurrent(): void {
578
+ if (this.currentScreen) this.paint(this.currentScreen)
579
+ }
580
+
581
+ /**
582
+ * Repaint eksplisit untuk pemilik sink eksternal (approval): blok yang baru
583
+ * dicatat harus terlihat SEBELUM user menjawab. No-op bila layar belum
584
+ * jalan atau sudah quit.
585
+ */
586
+ repaint(): void {
587
+ if (!this.quitRequested) this.paintCurrent()
588
+ }
589
+
590
+ private viewportHeight(rows: number, cols: number): number {
591
+ const inputH = this.inputHeight(cols)
592
+ const menuH = this.menuHeight(rows, cols)
593
+ return Math.max(1, rows - 1 - inputH - menuH)
594
+ }
595
+
596
+ private inputRows(cols: number): string[] {
597
+ const w = Math.max(10, cols)
598
+ const out: string[] = []
599
+ // Baris kosong = placeholder redup (edukasi tanpa banjir): cara keluar
600
+ // selalu terlihat (Ctrl+D), tanpa menuh-menuhi transkrip.
601
+ if (!this.state.line) {
602
+ const hint = c.faint(truncateToWidth(t("app.placeholder"), w - PROMPT_FIRST.length))
603
+ out.push(`${PROMPT_FIRST}${hint}`)
604
+ return out
605
+ }
606
+ const logical = this.state.line.split("\n")
607
+ logical.forEach((ln, idx) => {
608
+ const prefix = idx === 0 ? PROMPT_FIRST : PROMPT_CONT
609
+ const full = `${prefix}${ln}`
610
+ const wrapped = chunkByWidth(full, w)
611
+ // Baris logis kosong tetap menempati 1 baris visual.
612
+ if (!wrapped.length) out.push(full)
613
+ else for (const r of wrapped) out.push(r)
614
+ })
615
+ return out
616
+ }
617
+
618
+ private inputHeight(cols: number): number {
619
+ return Math.min(MAX_INPUT_ROWS, Math.max(1, this.inputRows(cols).length))
620
+ }
621
+
622
+ private menuRows(rows: number, cols: number): string[] {
623
+ if (!this.state.menuOpen || !this.state.line.startsWith("/")) return []
624
+ const hints = this.host.listCommands(this.state.line)
625
+ if (!hints.length) return []
626
+ const room = Math.max(0, rows - 1 - this.inputHeight(cols) - 3)
627
+ const shown = hints.slice(0, Math.min(MAX_DROPDOWN_ROWS, room))
628
+ const w = Math.max(10, cols)
629
+ const out: string[] = [c.muted(t("app.menuHeader"))]
630
+ shown.forEach((h, i) => {
631
+ const picked = i === this.state.sel
632
+ const text = sanitizeAnsiLine(h)
633
+ out.push(picked ? c.accent(`› ${text}`) : ` ${text}`)
634
+ })
635
+ if (hints.length > shown.length)
636
+ out.push(c.muted(t("app.moreLines", { n: hints.length - shown.length })))
637
+ return out.map((l) => chunkByWidth(l, w)[0] ?? "")
638
+ }
639
+
640
+ private menuHeight(rows: number, cols: number): number {
641
+ return this.menuRows(rows, cols).length
642
+ }
643
+
644
+ /** True bila terminal menciut di bawah minimum TUI (MIN_ROWS/MIN_COLS). */
645
+ private tooSmall(): boolean {
646
+ const cols = process.stdout.columns || 0
647
+ const rows = process.stdout.rows || 0
648
+ return rows < MIN_ROWS || cols < MIN_COLS
649
+ }
650
+
651
+ private paint(screen: AltScreen): void {
652
+ this.currentScreen = screen
653
+ const cols = screen.cols
654
+ const rows = screen.rows
655
+ // Layar menciut tengah sesi: satu bingkai pesan jujur (tepat `rows`
656
+ // baris), bukan layout rusak. Kembali normal otomatis saat resize
657
+ // (onResize → paint). Gagal-di-kode-lama: wrap pecah + kursor liar.
658
+ if (this.tooSmall()) {
659
+ const w = Math.max(1, cols)
660
+ const frame = [c.warning(truncateToWidth(t("tui.tooSmall"), w))]
661
+ while (frame.length < Math.max(1, rows)) frame.push("")
662
+ try {
663
+ screen.paint(frame.slice(0, Math.max(1, rows)))
664
+ } catch {}
665
+ this.frames++
666
+ return
667
+ }
668
+ const snap = this.host.getStatus()
669
+ this.tick = snap.busy ? this.tick + 1 : 0
670
+ const statusLine =
671
+ renderFooter({ ...snap.footer, sparkFrame: snap.busy ? this.tick : 0 }, cols)[0] ?? ""
672
+ const menu = this.menuRows(rows, cols)
673
+ const inputAll = this.inputRows(cols)
674
+ const inputH = Math.min(MAX_INPUT_ROWS, Math.max(1, inputAll.length))
675
+ // Indikator "output baru di bawah": user membaca ke atas saat stream
676
+ // masuk — tanpa ini output baru lewat diam-diam. Makan 1 baris viewport.
677
+ const newCount = this.scrollBack > 0 ? this.transcript.size() - this.scrollBase : 0
678
+ const indicator = newCount > 0 ? [c.muted(t("app.newBelow", { n: newCount }))] : []
679
+ const viewH = Math.max(1, rows - 1 - inputH - menu.length - indicator.length)
680
+ const body = this.transcript.view(cols, viewH, this.scrollBack)
681
+ // Jendela input mengikuti kursor: bila kursor di atas jendela ekor
682
+ // (mis. paste 10 baris lalu Home), gulir ke atas agar kursor terlihat.
683
+ // Tanpa ini baris atas tak terjangkau visual tapi kursor diparkir di
684
+ // baris yang salah (dulu selalu slice ekor).
685
+ const cursor = this.cursorIndex(cols)
686
+ const winStart = Math.max(0, Math.min(inputAll.length - inputH, cursor.visIdx))
687
+ const shownInput = inputAll.slice(winStart, winStart + inputH)
688
+ const frame: string[] = [...body, ...menu, ...indicator, ...shownInput, statusLine]
689
+ while (frame.length < rows) frame.unshift("")
690
+ const out = frame.slice(-rows)
691
+ try {
692
+ screen.paint(out)
693
+ } catch {}
694
+ // Parkir kursor di posisi ketik (kolom terminal, bukan karakter).
695
+ const cursorRow = viewH + menu.length + indicator.length + (cursor.visIdx - winStart) + 1
696
+ try {
697
+ process.stdout.write(
698
+ `\x1b[?25l\x1b[${Math.max(1, cursorRow)};${Math.max(1, cursor.col)}H\x1b[?25h`,
699
+ )
700
+ } catch {}
701
+ this.frames++
702
+ }
703
+
704
+ /**
705
+ * Indeks baris visual kursor (koordinat PENUH inputAll) + kolom 1-based.
706
+ * Wrap-aware; CJK/emoji dihitung per kolom via displayWidth.
707
+ */
708
+ private cursorIndex(cols: number): { visIdx: number; col: number } {
709
+ // Baris kursor dalam teks logis → petakan ke baris visual (wrap-aware).
710
+ const units = toGraphemes(this.state.line)
711
+ const before = units.slice(0, Math.max(0, Math.min(this.state.cursor, units.length))).join("")
712
+ const logicalIdx = before.split("\n").length - 1
713
+ const lastLine = before.split("\n").pop() ?? ""
714
+ const prefix = logicalIdx === 0 ? PROMPT_FIRST : PROMPT_CONT
715
+ const targetWidth = displayWidth(prefix) + displayWidth(lastLine)
716
+ const w = Math.max(10, cols)
717
+ // Baris visual ke berapa (dari atas blok input) posisi kursor berada.
718
+ let visIdx = 0
719
+ const logical = this.state.line.split("\n")
720
+ for (let li = 0; li < logical.length; li++) {
721
+ const full = `${li === 0 ? PROMPT_FIRST : PROMPT_CONT}${logical[li] ?? ""}`
722
+ const wrapped = chunkByWidth(full, w)
723
+ const n = Math.max(1, wrapped.length)
724
+ if (li < logicalIdx) {
725
+ visIdx += n
726
+ continue
727
+ }
728
+ // Baris kursor: kolom ke-n dalam wrap.
729
+ let acc = 0
730
+ for (let wi = 0; wi < n; wi++) {
731
+ const ww = displayWidth(wrapped[wi] ?? "")
732
+ if (targetWidth < acc + ww || wi === n - 1) {
733
+ visIdx += wi
734
+ // Kolom 1-based dalam baris visual — SAMA untuk baris tengah
735
+ // maupun terakhir (dulu baris tengah selalu diparkir di EOL).
736
+ return { visIdx, col: Math.max(1, targetWidth - acc + 1) }
737
+ }
738
+ acc += ww
739
+ }
740
+ visIdx += n - 1
741
+ break
742
+ }
743
+ return { visIdx, col: 1 }
744
+ }
745
+ }