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
@@ -2,16 +2,17 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"
2
2
  import { homedir } from "node:os"
3
3
  import { join } from "node:path"
4
4
  import { createInterface } from "node:readline"
5
+ import { t } from "../i18n/locale.ts"
5
6
  import { stripAnsi } from "../render/theme.ts"
6
7
  import { displayWidth, escapeLength, truncateToWidth } from "../render/width.ts"
7
- import { footerReserveRows } from "../runtime/chrome.ts"
8
8
  import {
9
9
  applyKey,
10
10
  buildRenderSpec,
11
11
  createDecoderState,
12
+ createKeyStreamPump,
12
13
  createState,
14
+ type DecodedKey,
13
15
  type DecoderState,
14
- decodeKeysStream,
15
16
  MAX_VISIBLE,
16
17
  type PromptKey,
17
18
  pointLength,
@@ -174,7 +175,7 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
174
175
  const base = promptOf()
175
176
  if (!search) return base
176
177
  const ok = searchMatches().length > 0
177
- return `${ok ? "(reverse-i-search)" : "(failed reverse-i-search)"}\`${search.query}': `
178
+ return t(ok ? "ask.search" : "ask.searchFail", { q: search.query })
178
179
  }
179
180
 
180
181
  return new Promise((resolve, reject) => {
@@ -194,6 +195,12 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
194
195
  if (done) return
195
196
  done = true
196
197
  clearIdle()
198
+ // Flush lone-ESC yang tertunda tak boleh jalan setelah selesai (batal
199
+ // ganda). pump didefinisikan di bawah — cleanup selalu dipanggil
200
+ // setelah init, jadi aman dari TDZ.
201
+ try {
202
+ pump.dispose()
203
+ } catch {}
197
204
  try {
198
205
  process.stdin.setRawMode(false)
199
206
  } catch {}
@@ -209,6 +216,13 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
209
216
  resolve(v)
210
217
  }
211
218
  const fail = (e: unknown) => {
219
+ // Overlay dropdown WAJIB terhapus juga di jalur gagal (bukan cuma
220
+ // submit) — tanpanya sisa daftar menempel permanen di scrollback.
221
+ // clearOverlay didefinisikan di bawah; fail hanya jalan pasca-setup
222
+ // sehingga aman dari TDZ.
223
+ try {
224
+ clearOverlay()
225
+ } catch {}
212
226
  cleanup()
213
227
  reject(e)
214
228
  }
@@ -336,17 +350,18 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
336
350
  // Baris input visual ikut memakan tinggi: kurangi jatah dropdown agar
337
351
  // blok input + dropdown tetap muat di terminal pendek.
338
352
  const nInGuess = state.line.split("\n").length
339
- // Sisakan ruang untuk prompt + 1 baris status + jatah footer lengket
340
- // (chrome sticky = 3 baris dasar) agar dropdown tidak membungkus maupun
341
- // menimpa footer di terminal pendek.
342
- const maxVisible = Math.max(
343
- 1,
344
- Math.min(MAX_VISIBLE, rows - 3 - footerReserveRows() - (nInGuess - 1)),
345
- )
353
+ // Sisakan ruang untuk prompt + 1 baris status agar dropdown tidak
354
+ // membungkus di terminal pendek. (Footer lengket/chrome.ts dihapus
355
+ // bersama REPL linier — tak ada reserve.)
356
+ const maxVisible = Math.max(1, Math.min(MAX_VISIBLE, rows - 3 - (nInGuess - 1)))
346
357
  const spec = buildRenderSpec(state, effPrompt(), matches(), opts.groupOf, maxVisible)
347
358
  const view = scrollableMultiline(effPrompt(), state.line, state.cursor)
348
359
  const nIn = view.texts.length
349
- const maxRows = Math.max(prevRows, spec.totalRows)
360
+ // Mini-window: bingkai garis di atas-bawah daftar agar terbaca sebagai
361
+ // jendela, bukan tulisan inline. +2 baris ikut akuntansi maxRows/prevRows
362
+ // dan matematika kursor agar tak ada sisa saat susut/tutup.
363
+ const ddRows = spec.rows.length > 0 ? spec.totalRows + 2 : 0
364
+ const maxRows = Math.max(prevRows, ddRows)
350
365
  const maxIn = Math.max(prevInputRows, nIn)
351
366
  // Kembali ke anchor: render lalu menaruh kursor di baris R.
352
367
  if (prevCursorRow > 0) process.stdout.write(`\x1b[${prevCursorRow}A`)
@@ -363,9 +378,16 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
363
378
 
364
379
  if (spec.rows.length > 0) {
365
380
  const cols = process.stdout.columns || 80
381
+ const rule = `${DIM}${"─".repeat(Math.max(8, Math.min(28, cols - 1)))}${RESTORE}`
382
+ // Tiap baris visual diawali \r\n sendiri (termasuk item pertama):
383
+ // total newline = 1(rule) + rows + (more?1) + 1(rule) = ddRows,
384
+ // seimbang dengan cursor-up di bawah. Pola lama (newline SEBAGAI
385
+ // pemisah) membuat item pertama menimpa garis bingkai.
366
386
  process.stdout.write("\r\n")
387
+ process.stdout.write(CLEAR + rule)
367
388
  for (let i = 0; i < spec.rows.length; i++) {
368
389
  const row = spec.rows[i]!
390
+ process.stdout.write("\r\n")
369
391
  if (row.kind === "header") {
370
392
  process.stdout.write(
371
393
  CLEAR + c.accent(c.bold(truncateToWidth(row.text, cols))) + RESTORE,
@@ -382,14 +404,17 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
382
404
  process.stdout.write(CLEAR + DIM + prefix + text + RESTORE)
383
405
  }
384
406
  }
385
- if (i < spec.rows.length - 1) process.stdout.write("\r\n")
386
407
  }
387
408
  if (spec.moreCount > 0) {
388
409
  process.stdout.write("\r\n")
389
- process.stdout.write(`${CLEAR + DIM} … ${spec.moreCount} more${RESTORE}`)
410
+ process.stdout.write(
411
+ `${CLEAR + DIM} ${t("ask.more", { n: spec.moreCount })}${RESTORE}`,
412
+ )
390
413
  }
391
- // Kembali ke anchor (melewati dropdown + baris input lanjutan).
392
- process.stdout.write(`\x1b[${spec.totalRows + (nIn - 1)}A`)
414
+ process.stdout.write("\r\n")
415
+ process.stdout.write(CLEAR + rule)
416
+ // Kembali ke anchor (melewati dropdown + bingkai + baris input lanjutan).
417
+ process.stdout.write(`\x1b[${ddRows + (nIn - 1)}A`)
393
418
  // Gambar ulang blok input (pastikan bersih setelah naik).
394
419
  process.stdout.write(`\r${CLEAR}${view.texts[0]}`)
395
420
  for (let k = 1; k < nIn; k++) process.stdout.write(`\r\n${CLEAR}${view.texts[k]!}`)
@@ -401,7 +426,7 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
401
426
  // Kursor sungguhan di posisi logis — bukan selalu di ujung baris.
402
427
  placeCursor(view.cursorCol)
403
428
  process.stdout.write(SYNC_END)
404
- prevRows = spec.totalRows
429
+ prevRows = ddRows
405
430
  prevInputRows = nIn
406
431
  prevCursorRow = view.cursorRow
407
432
  }
@@ -504,9 +529,10 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
504
529
  } catch {}
505
530
  }
506
531
 
507
- onData = (chunk: Buffer) => {
508
- resetIdle()
509
- const keys = decodeKeysStream(chunk, decoder)
532
+ // Jalur tunggal key (sinkron + flush lone-ESC via pump): hook → search →
533
+ // empty-cancel → history → applyKey → render. True = selesai via doSubmit
534
+ // (pemanggil wajib berhenti dan tak me-render lagi).
535
+ const handleKeys = (keys: DecodedKey[]): boolean => {
510
536
  for (const d of keys) {
511
537
  // Hook pemanggil: key yang ditangani sendiri (return truthy) dilewati
512
538
  // dari logika bawaan; render() di akhir chunk tetap menggambar efeknya.
@@ -537,7 +563,7 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
537
563
  historyIdx = -1
538
564
  savedLine = ""
539
565
  doSubmit(false)
540
- return
566
+ return true
541
567
  }
542
568
  if (d.key.type === "esc" || d.key.type === "ctrl-c" || d.key.type === "ctrl-d") {
543
569
  // Batal cari saja (bukan batal baris): kembalikan draf. Ctrl+D ikut
@@ -600,7 +626,7 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
600
626
  // hilang karena salah tekan (menu yang terbuka tetap ditutup applyKey).
601
627
  if (!search && d.key.type === "esc" && !state.menuOpen && state.line === "") {
602
628
  doSubmit(true)
603
- return
629
+ return true
604
630
  }
605
631
  // Navigasi history saat dropdown tertutup.
606
632
  //
@@ -653,12 +679,32 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
653
679
  if (r.action === "submit" || r.action === "cancel") {
654
680
  // Empty Enter = "" (not null) - REPL continues; null = cancel (break)
655
681
  doSubmit(r.action === "cancel")
656
- return
682
+ return true
657
683
  }
658
684
  }
659
- // Satu render per chunk - paste 50+ char tidak meng-redraw 50 kali.
685
+ // Satu render per batch - paste 50+ char tidak meng-redraw 50 kali.
660
686
  try {
661
687
  render()
688
+ } catch (e) {
689
+ fail(e)
690
+ return true
691
+ }
692
+ return false
693
+ }
694
+ // Pompa decode + flush lone-ESC 50ms: panah split tak lagi jadi esc+"[A",
695
+ // Esc tunggal tetap batal (terlambat ≤50ms). resetIdle di sini agar
696
+ // flush (aktivitas user) juga memperpanjang idle, sama seperti chunk.
697
+ const pump = createKeyStreamPump({
698
+ state: decoder,
699
+ onKeys: (keys) => {
700
+ resetIdle()
701
+ return handleKeys(keys)
702
+ },
703
+ })
704
+
705
+ onData = (chunk: Buffer) => {
706
+ try {
707
+ pump.push(chunk)
662
708
  } catch (e) {
663
709
  fail(e)
664
710
  }
@@ -699,6 +745,9 @@ export async function askSecret(
699
745
  if (done) return
700
746
  done = true
701
747
  clearIdle()
748
+ try {
749
+ secretPump.dispose()
750
+ } catch {}
702
751
  try {
703
752
  process.stdin.setRawMode(false)
704
753
  } catch {}
@@ -731,62 +780,74 @@ export async function askSecret(
731
780
  process.stdout.write(promptText)
732
781
  let secret = ""
733
782
 
734
- onData = (chunk: Buffer) => {
735
- resetIdle()
736
- try {
737
- for (const d of decodeKeysStream(chunk, decoder)) {
738
- const k = d.key
739
- if (k.type === "enter") {
740
- finish(secret.trim())
741
- return
742
- } else if (k.type === "esc" || k.type === "ctrl-c" || k.type === "ctrl-d") {
743
- // Esc/Ctrl+C/Ctrl+D = BATALKAN PROMPT, bukan matikan proses.
744
- //
745
- // Dulu di sini `process.exit(130)`. Di raw mode Ctrl+C tidak
746
- // menghasilkan SIGINT, jadi itu emulasi manual — tapi `askSecret`
747
- // dipanggil dari `runProviderManager`, sebuah dialog di dalam REPL
748
- // yang hidup. Menekan Ctrl+C saat salah ketik API key mematikan
749
- // seluruh sesi beserta riwayatnya, bukan menutup dialognya.
750
- finish(null)
751
- return
752
- } else if (k.type === "backspace") {
753
- // Hapus satu GRAPHEME (bukan code point/UTF-16 unit): emoji ZWJ
754
- // dan flag tidak meninggalkan setengah.
755
- const graphemes = toGraphemes(secret)
756
- if (graphemes.length > 0) {
757
- graphemes.pop()
758
- secret = graphemes.join("")
759
- process.stdout.write("\b \b")
760
- }
761
- } else if (k.type === "ctrl-u") {
762
- // Hapus SEMUA (mis. salah paste API key) — tanpa ini satu-satunya
763
- // jalan adalah Backspace satu-satu.
764
- const n = toGraphemes(secret).length
765
- secret = ""
766
- if (n > 0) process.stdout.write(`${"\b \b".repeat(n)}`)
767
- } else if (k.type === "ctrl-w") {
768
- // Hapus satu "kata" (sampai spasi terakhir) — sama dengan prompt
769
- // teks biasa.
770
- const graphemes = toGraphemes(secret)
771
- const cut = secret.replace(/\S+\s*$/, "")
772
- const removed = graphemes.length - toGraphemes(cut).length
773
- if (removed > 0) {
774
- secret = cut
775
- process.stdout.write(`${"\b \b".repeat(removed)}`)
776
- }
777
- } else if (k.type === "char") {
778
- // Sekuens kontrol dari paste dibuang — secret tidak boleh
779
- // mengandung newline/C0 (Enter adalah satu-satunya terminasi).
780
- const clean = k.ch
781
- .replace(/\r\n|\r|\n|\t/g, "")
782
- // biome-ignore lint/suspicious/noControlCharactersInRegex: membuang kontrol dari paste
783
- .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "")
784
- if (clean) {
785
- secret += clean
786
- process.stdout.write("*".repeat(toGraphemes(clean).length))
787
- }
783
+ // Jalur tunggal key seperti askLine (sinkron + flush lone-ESC 50ms).
784
+ const handleSecretKeys = (keys: DecodedKey[]): boolean => {
785
+ for (const d of keys) {
786
+ const k = d.key
787
+ if (k.type === "enter") {
788
+ finish(secret.trim())
789
+ return true
790
+ } else if (k.type === "esc" || k.type === "ctrl-c" || k.type === "ctrl-d") {
791
+ // Esc/Ctrl+C/Ctrl+D = BATALKAN PROMPT, bukan matikan proses.
792
+ //
793
+ // Dulu di sini `process.exit(130)`. Di raw mode Ctrl+C tidak
794
+ // menghasilkan SIGINT, jadi itu emulasi manual — tapi `askSecret`
795
+ // dipanggil dari `runProviderManager`, sebuah dialog di dalam REPL
796
+ // yang hidup. Menekan Ctrl+C saat salah ketik API key mematikan
797
+ // seluruh sesi beserta riwayatnya, bukan menutup dialognya.
798
+ finish(null)
799
+ return true
800
+ } else if (k.type === "backspace") {
801
+ // Hapus satu GRAPHEME (bukan code point/UTF-16 unit): emoji ZWJ
802
+ // dan flag tidak meninggalkan setengah.
803
+ const graphemes = toGraphemes(secret)
804
+ if (graphemes.length > 0) {
805
+ graphemes.pop()
806
+ secret = graphemes.join("")
807
+ process.stdout.write("\b \b")
808
+ }
809
+ } else if (k.type === "ctrl-u") {
810
+ // Hapus SEMUA (mis. salah paste API key) — tanpa ini satu-satunya
811
+ // jalan adalah Backspace satu-satu.
812
+ const n = toGraphemes(secret).length
813
+ secret = ""
814
+ if (n > 0) process.stdout.write(`${"\b \b".repeat(n)}`)
815
+ } else if (k.type === "ctrl-w") {
816
+ // Hapus satu "kata" (sampai spasi terakhir) — sama dengan prompt
817
+ // teks biasa.
818
+ const graphemes = toGraphemes(secret)
819
+ const cut = secret.replace(/\S+\s*$/, "")
820
+ const removed = graphemes.length - toGraphemes(cut).length
821
+ if (removed > 0) {
822
+ secret = cut
823
+ process.stdout.write(`${"\b \b".repeat(removed)}`)
824
+ }
825
+ } else if (k.type === "char") {
826
+ // Sekuens kontrol dari paste dibuang — secret tidak boleh
827
+ // mengandung newline/C0 (Enter adalah satu-satunya terminasi).
828
+ const clean = k.ch
829
+ .replace(/\r\n|\r|\n|\t/g, "")
830
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: membuang kontrol dari paste
831
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "")
832
+ if (clean) {
833
+ secret += clean
834
+ process.stdout.write("*".repeat(toGraphemes(clean).length))
788
835
  }
789
836
  }
837
+ }
838
+ return false
839
+ }
840
+ const secretPump = createKeyStreamPump({
841
+ state: decoder,
842
+ onKeys: (keys) => {
843
+ resetIdle()
844
+ return handleSecretKeys(keys)
845
+ },
846
+ })
847
+
848
+ onData = (chunk: Buffer) => {
849
+ try {
850
+ secretPump.push(chunk)
790
851
  } catch (e) {
791
852
  fail(e)
792
853
  }
@@ -43,6 +43,9 @@ export type PromptKey =
43
43
  | { type: "end" }
44
44
  | { type: "up" }
45
45
  | { type: "down" }
46
+ // PgUp/PgDn (ESC[5~/[6~) — di TUI scroll viewport transkrip, bukan histori.
47
+ | { type: "pageup" }
48
+ | { type: "pagedown" }
46
49
  | { type: "tab" }
47
50
  | { type: "enter" }
48
51
  | { type: "esc" }
@@ -264,6 +267,11 @@ export function applyKey(
264
267
  if (!state.line.length) return { state, action: "none" }
265
268
  return { state: createState(), action: "render" }
266
269
  }
270
+ // PgUp/PgDn: scroll viewport transkrip — ditangani App TUI SEBELUM
271
+ // applyKey; engine netral (tanpa ini switch tak exhaustive → tsc merah).
272
+ case "pageup":
273
+ case "pagedown":
274
+ return { state, action: "none" }
267
275
  case "ctrl-w": {
268
276
  if (state.cursor === 0) return { state, action: "none" }
269
277
  const at = unitIndex(state.line, state.cursor)
@@ -423,6 +431,13 @@ export function decodeKeysStream(chunk: Uint8Array, state: DecoderState): Decode
423
431
  const b = buf[i]!
424
432
  if (b === 0x1b) {
425
433
  const n1 = buf[i + 1]
434
+ // ESC di ujung chunk = awal sekuens yang terbelah (panah ESC[A jadi
435
+ // [0x1b]+[0x5b,0x41]) ATAU Esc tunggal. Tak bisa dibedakan sinkron —
436
+ // TAHAN di pending; pemanggil (input.ts) flush sebagai esc bila tak ada
437
+ // byte lanjutan dalam ~50ms (pola lone-ESC yang sama saat busy).
438
+ // Emisi langsung di sini mengubah panah split jadi esc+"[A" (batal prompt
439
+ // + teks nyasar).
440
+ if (n1 === undefined) break
426
441
  // Bracketed paste start: ESC[200~ … ESC[201~ — tahan sampai penutup.
427
442
  if (
428
443
  n1 === 0x5b &&
@@ -484,10 +499,11 @@ export function decodeKeysStream(chunk: Uint8Array, state: DecoderState): Decode
484
499
  continue
485
500
  }
486
501
  if (j === i + 2) {
487
- // Hanya "ESC["/"ESC O" tanpa apa pun → ESC biasa, lengkap.
488
- out.push({ key: { type: "esc" }, width: 0 })
489
- i += 2
490
- continue
502
+ // "ESC["/"ESC O" di ujung chunk = CSI belum lengkap (final di chunk
503
+ // berikut), BUKAN Esc biasa. Tahan agar panah split tak jadi esc.
504
+ // (ESC[ yang benar-benar lengkap selalu punya byte final dan sudah
505
+ // ditangani di atas.)
506
+ break
491
507
  }
492
508
  break // ada parameter tapi belum ada byte final — tahan
493
509
  }
@@ -519,6 +535,80 @@ export function decodeKeysStream(chunk: Uint8Array, state: DecoderState): Decode
519
535
  return out
520
536
  }
521
537
 
538
+ /**
539
+ * Pending berupa Esc tunggal yang tertahan di ujung chunk ([0x1b])?
540
+ * Hanya kasus ini yang di-flush via timer ~50ms oleh pemanggil: sekuens lain
541
+ * yang tertahan (UTF-8/paste/mouse/CSI berparameter) menunggu chunk berikut
542
+ * dan tak boleh dipaksa jadi esc.
543
+ */
544
+ export function hasPendingLoneEsc(state: DecoderState): boolean {
545
+ return state.pending.length === 1 && state.pending[0] === 0x1b
546
+ }
547
+
548
+ /**
549
+ * Paksa pending Esc tunggal menjadi key esc (dipanggil timer pemanggil bila
550
+ * tak ada byte lanjutan). No-op bila pending bukan Esc tunggal.
551
+ */
552
+ export function flushLoneEsc(state: DecoderState): DecodedKey[] {
553
+ if (!hasPendingLoneEsc(state)) return []
554
+ state.pending = []
555
+ return [{ key: { type: "esc" }, width: 0 }]
556
+ }
557
+
558
+ // ── Pompa key stream + flush lone-ESC ──
559
+ //
560
+ // Decoder menahan ESC di ujung chunk (tak bisa bedakan Esc tunggal vs paruh
561
+ // panah split secara sinkron). Pompa ini membungkus pola yang dipakai SEMUA
562
+ // konsumen interaktif (askLine/askSecret/picker/manager): decode chunk →
563
+ // teruskan key sinkron → bila pending Esc tunggal, tunggu ~50ms (pola
564
+ // lone-ESC yang sama saat busy di cli/repl.ts); byte lanjutan membatalkan
565
+ // timer dan melengkapi sekuens, sunyi berarti Esc asli → flush sebagai esc.
566
+ //
567
+ // Tanpa pompa tiap konsumen harus menulis timer sendiri (duplikasi 5× dan
568
+ // drift); tanpa timer panah split jadi esc+"[A" (batal prompt + teks nyasar).
569
+ // Timer di-unref agar tak menahan exit proses/test.
570
+ export interface KeyStreamPump {
571
+ /** Decode chunk + kirim key sinkron; arm flush bila Esc tertahan. */
572
+ push(chunk: Uint8Array): void
573
+ /** Matikan timer (panggil di cleanup agar flush tak jalan setelah selesai). */
574
+ dispose(): void
575
+ }
576
+
577
+ export function createKeyStreamPump(opts: {
578
+ state: DecoderState
579
+ /** Dipanggil untuk key sinkron maupun hasil flush; return true = selesai. */
580
+ onKeys: (keys: DecodedKey[]) => boolean
581
+ escMs?: number
582
+ }): KeyStreamPump {
583
+ let timer: ReturnType<typeof setTimeout> | undefined
584
+ const clear = () => {
585
+ if (timer !== undefined) {
586
+ clearTimeout(timer)
587
+ timer = undefined
588
+ }
589
+ }
590
+ return {
591
+ push(chunk: Uint8Array): void {
592
+ clear()
593
+ const done = opts.onKeys(decodeKeysStream(chunk, opts.state))
594
+ if (done) return
595
+ if (hasPendingLoneEsc(opts.state)) {
596
+ timer = setTimeout(() => {
597
+ timer = undefined
598
+ const flushed = flushLoneEsc(opts.state)
599
+ if (flushed.length) opts.onKeys(flushed)
600
+ }, opts.escMs ?? 50)
601
+ try {
602
+ ;(timer as unknown as { unref?: () => void }).unref?.()
603
+ } catch {}
604
+ }
605
+ },
606
+ dispose(): void {
607
+ clear()
608
+ },
609
+ }
610
+ }
611
+
522
612
  export function decodeKey(s: string, i: number): DecodedKey | null {
523
613
  const c = s[i]!
524
614
  const code = c.charCodeAt(0)
@@ -559,6 +649,9 @@ export function decodeKey(s: string, i: number): DecodedKey | null {
559
649
  if (kind === "4" && s[i + 3] === "~") return { key: { type: "end" }, width: 4 }
560
650
  if (kind === "8" && s[i + 3] === "~") return { key: { type: "end" }, width: 4 }
561
651
  if (kind === "3" && s[i + 3] === "~") return { key: { type: "delete" }, width: 4 }
652
+ // PgUp/PgDn — App TUI memakainya untuk scroll transkrip (I18).
653
+ if (kind === "5" && s[i + 3] === "~") return { key: { type: "pageup" }, width: 4 }
654
+ if (kind === "6" && s[i + 3] === "~") return { key: { type: "pagedown" }, width: 4 }
562
655
  // Shift+Tab (backtab) ESC [ Z — dipakai REPL linier untuk cycle mode.
563
656
  // Tanpa cabang eksplisit ini ia jatuh ke catch-all "esc" di bawah,
564
657
  // sehingga tipe "shift-tab" tidak pernah dihasilkan decodeKeys.
@@ -8,6 +8,7 @@
8
8
  // /expand. Thinking memakai reasoning.visible sebagai invers dari minimize
9
9
  // (expanded = visible), jadi /thinking/Ctrl+T lama tetap satu arti.
10
10
  import { reasoning, setReasoningVisible } from "./reasoning.ts"
11
+ import { splitTrailingEscape } from "./sanitize.ts"
11
12
 
12
13
  export type CollapseSection = "thinking" | "tool" | "answer"
13
14
 
@@ -62,7 +63,13 @@ export function bufferSection(
62
63
  stream: BufferedSection["stream"] = "stderr",
63
64
  ): void {
64
65
  if (!text) return
65
- bufferedSections.push({ label, text: text.slice(0, MAX_SECTION_CHARS), stream })
66
+ // Cap jangan belah surrogate pair (U+FFFD di /expand) dan jangan sisakan
67
+ // ekor escape parsial (SGR gantung ikut tercetak saat /expand).
68
+ let cut = text.length > MAX_SECTION_CHARS ? text.slice(0, MAX_SECTION_CHARS) : text
69
+ const last = cut.charCodeAt(cut.length - 1)
70
+ if (cut.length > 0 && last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1)
71
+ cut = splitTrailingEscape(cut).head
72
+ bufferedSections.push({ label, text: cut, stream })
66
73
  // Buang yang tertua sampai total dalam budget — terbaru selalu dipertahankan.
67
74
  let total = 0
68
75
  let keepFrom = bufferedSections.length