minicode-ai 0.14.6 → 0.20.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 (142) hide show
  1. package/README.md +6 -4
  2. package/cli/args.ts +20 -8
  3. package/cli/commands/exec.ts +17 -14
  4. package/cli/commands/openwork.ts +1 -1
  5. package/cli/commands.ts +39 -23
  6. package/cli/index.ts +29 -7
  7. package/cli/model-manager.ts +1 -1
  8. package/cli/router.ts +22 -9
  9. package/cli/setup.ts +77 -35
  10. package/cli/tui.ts +179 -25
  11. package/docs/CONTROL-PLANE-MAP.md +7 -5
  12. package/docs/OUTPUT_EVENT_MODEL.md +4 -3
  13. package/docs/OUTPUT_PROTOCOL_SPEC.md +1 -1
  14. package/docs/OUTPUT_RENDERING_SPEC.md +16 -4
  15. package/docs/OUTPUT_UX_RULES.md +38 -32
  16. package/docs/P14_OPEN_WORK.md +290 -0
  17. package/docs/README.md +1 -1
  18. package/docs/SUMMARY.md +36 -22
  19. package/docs/TERMINAL_CONTRACT.md +89 -17
  20. package/docs/UI_RENDER_PIPELINE.md +47 -8
  21. package/docs/agents.md +1 -1
  22. package/docs/architecture.md +10 -8
  23. package/docs/autonomous-scheduler.md +142 -0
  24. package/docs/choosing-mode.md +4 -2
  25. package/docs/cli.md +11 -9
  26. package/docs/concepts.md +5 -5
  27. package/docs/config-providers.md +3 -3
  28. package/docs/config.md +1 -1
  29. package/docs/contributing.md +7 -9
  30. package/docs/environment.md +8 -5
  31. package/docs/getting-started.md +5 -5
  32. package/docs/mcp-lsp.md +2 -2
  33. package/docs/memory-sessions.md +3 -3
  34. package/docs/policy-sandbox.md +7 -4
  35. package/docs/pricing-budget.md +3 -3
  36. package/docs/quickstart.md +1 -1
  37. package/docs/repl.md +11 -8
  38. package/docs/security-model.md +4 -2
  39. package/docs/security.md +9 -8
  40. package/docs/skills.md +2 -2
  41. package/docs/terminal.md +10 -2
  42. package/docs/tools.md +4 -4
  43. package/docs/troubleshooting.md +3 -3
  44. package/docs/verify-benchmark.md +0 -3
  45. package/package.json +9 -18
  46. package/scripts/vendor-overlays/minicode-context.patch +1 -1
  47. package/src/app/mentions.ts +1 -1
  48. package/src/app/rag-layer.ts +11 -2
  49. package/src/app/session.ts +128 -10
  50. package/src/constants.ts +32 -1
  51. package/src/daemon/client.ts +11 -6
  52. package/src/daemon/control.ts +2 -9
  53. package/src/daemon/resource.ts +5 -4
  54. package/src/hooks/run.ts +5 -6
  55. package/src/lib/keystore.ts +11 -9
  56. package/src/lib/net.ts +8 -3
  57. package/src/lib/safe-open.ts +29 -5
  58. package/src/lib/trusted-exec.ts +4 -1
  59. package/src/lsp/client.ts +9 -10
  60. package/src/mcp/http-transport.ts +1 -1
  61. package/src/mcp/server.ts +17 -7
  62. package/src/memory/files.ts +2 -1
  63. package/src/memory/vector.ts +25 -16
  64. package/src/policy/bash-guard.ts +58 -16
  65. package/src/policy/bpe.ts +110 -0
  66. package/src/policy/compaction.ts +139 -22
  67. package/src/policy/consequence-engine.ts +3 -3
  68. package/src/policy/context-window.ts +43 -1
  69. package/src/policy/context.ts +50 -12
  70. package/src/policy/jail.ts +48 -3
  71. package/src/policy/no-progress.ts +15 -8
  72. package/src/policy/permission.ts +243 -5
  73. package/src/policy/tokenizer-registry.ts +104 -0
  74. package/src/policy/usage.ts +20 -13
  75. package/src/policy/verifier.ts +7 -4
  76. package/src/policy/work-mode.ts +9 -5
  77. package/src/presentation/adapter.ts +8 -4
  78. package/src/presentation/events.ts +2 -2
  79. package/src/presentation/label.ts +3 -3
  80. package/src/presentation/model.ts +4 -0
  81. package/src/presentation/projection.ts +10 -2
  82. package/src/presentation/store.ts +2 -2
  83. package/src/providers/anthropic.ts +13 -3
  84. package/src/providers/responses.ts +16 -6
  85. package/src/runtime/capability.ts +22 -4
  86. package/src/runtime/child-execution.ts +1 -1
  87. package/src/runtime/composition.ts +5 -5
  88. package/src/runtime/execution-journal.ts +13 -7
  89. package/src/runtime/execution-registry.ts +1 -1
  90. package/src/runtime/production-execution.ts +7 -6
  91. package/src/runtime/production-runtime.ts +2 -2
  92. package/src/runtime/runtime-capabilities.ts +1 -1
  93. package/src/runtime/runtime-status-facts.ts +1 -1
  94. package/src/runtime/runtime-task-admission.ts +2 -2
  95. package/src/sandbox/os.ts +4 -3
  96. package/src/session/checkpoint.ts +29 -4
  97. package/src/session/context-assembly.ts +8 -1
  98. package/src/session/context-identity.ts +2 -2
  99. package/src/session/context-projection.ts +36 -11
  100. package/src/session/persistence.ts +22 -11
  101. package/src/task/autonomous-context.ts +2 -3
  102. package/src/task/autonomous-policy.ts +3 -3
  103. package/src/task/model.ts +2 -2
  104. package/src/task/production-scheduler.ts +2 -2
  105. package/src/task/scheduler-observability.ts +1 -0
  106. package/src/task/scheduler.ts +3 -2
  107. package/src/task/scheduling-policy.ts +2 -1
  108. package/src/task/trigger.ts +5 -5
  109. package/src/tools/git.ts +22 -4
  110. package/src/tools/lsp.ts +10 -8
  111. package/src/tools/read_image.ts +2 -1
  112. package/src/tools/task.ts +1 -1
  113. package/src/tools/web_fetch.ts +6 -2
  114. package/src/tools/web_search.ts +2 -1
  115. package/src/ui/assistant/simple.ts +42 -33
  116. package/src/ui/contract.ts +4 -0
  117. package/src/ui/footer.ts +63 -12
  118. package/src/ui/i18n/en.ts +14 -2
  119. package/src/ui/i18n/id.ts +14 -2
  120. package/src/ui/input/prompt-engine.ts +36 -10
  121. package/src/ui/render/cells.ts +320 -0
  122. package/src/ui/render/composer-wrap.ts +73 -0
  123. package/src/ui/render/detail.ts +2 -2
  124. package/src/ui/render/diff.ts +14 -5
  125. package/src/ui/render/highlight.ts +4 -4
  126. package/src/ui/render/ledger.ts +47 -0
  127. package/src/ui/render/markdown.ts +12 -5
  128. package/src/ui/render/session-summary.ts +50 -0
  129. package/src/ui/render/table-grid.ts +134 -6
  130. package/src/ui/render/theme.ts +49 -4
  131. package/src/ui/render/width.ts +91 -4
  132. package/src/ui/render/wrap.ts +5 -3
  133. package/src/ui/runtime/screen.ts +100 -22
  134. package/src/ui/runtime/statusline.ts +26 -0
  135. package/src/ui/screens/model-manager.ts +1 -1
  136. package/src/ui/session-state.ts +27 -1
  137. package/src/ui/tui/app.ts +336 -65
  138. package/src/ui/tui/transcript.ts +335 -104
  139. package/vendor/minicore/VENDOR.md +16 -12
  140. package/vendor/minicore/src/core/events.ts +1 -0
  141. package/vendor/minicore/src/core/loop.ts +11 -1
  142. package/vendor/minicore/src/core/session.ts +39 -0
package/src/ui/i18n/en.ts CHANGED
@@ -137,9 +137,17 @@ export const en = {
137
137
  "help.cKeys":
138
138
  "Keys: Tab work-mode · Shift+Tab permission · ↑↓ history · Mouse wheel/PgUp/PgDn scroll · Ctrl+R search · Ctrl+D exit",
139
139
  "help.cMore": " /help keys = all shortcuts",
140
+ "help.gGeneral": "General",
141
+ "help.gSession": "Session",
142
+ "help.gModel": "Model",
143
+ "help.gMode": "Mode",
144
+ "help.gView": "View",
145
+ "help.gTask": "Task",
140
146
  "help.kHead": "Keyboard:",
141
147
  "help.k.submit": "submit",
142
148
  "help.k.cycleMode": "cycle work mode",
149
+ "help.k.workMode": "cycle work mode (Build/Plan/Discuss)",
150
+ "help.k.permission": "cycle permission mode (Auto/Ask)",
143
151
  "help.k.history": "prompt history (in picker: navigate)",
144
152
  "help.k.mouse": "scroll transcript with mouse wheel",
145
153
  "help.k.scroll": "scroll transcript with PgUp/PgDn (Shift+ = half page)",
@@ -155,7 +163,7 @@ export const en = {
155
163
  "help.k.compact": "toggle compact/expanded tool output",
156
164
  "help.k.thinking": "toggle expand/minimize thinking output",
157
165
  "help.k.esc": "close dropdown / picker / clear line (busy: abort turn)",
158
- "help.k.ctrlC": "clear line / cancel prompt (TUI turn: use Esc)",
166
+ "help.k.ctrlC": "copy selected text / cancel",
159
167
  "help.k.ctrlD": "exit on empty line",
160
168
  "help.desc.help": "Show commands",
161
169
  "help.desc.provider": "Manage providers",
@@ -173,7 +181,7 @@ export const en = {
173
181
  "help.desc.clear": "Clear transcript",
174
182
  "help.desc.copy": "Copy the last 1–10 turns to clipboard (OSC 52)",
175
183
  "help.desc.history": "Show recent prompt history",
176
- "help.desc.scheduler": "Inspect, trigger, or stop the autonomous scheduler",
184
+ "help.desc.scheduler": "Trigger / inspect / stop the scheduler",
177
185
 
178
186
  // [PHASE 6AB] Operator strings for `/scheduler`. The STATE line itself is
179
187
  // deliberately not localised - see `describeOperatorState`, which the
@@ -224,16 +232,20 @@ export const en = {
224
232
  "copied {turns} turns ({n} chars · OSC 52 — allow clipboard access in terminal if empty)",
225
233
  "tui.copyInvalid": "invalid turn count: {n} (use 1–{max})",
226
234
  "tui.copyNeedTty": "(clipboard needs a TTY terminal)",
235
+ "tui.copyTooLarge": "copy payload too large ({n} bytes, max {max})",
227
236
  "tui.unknownMode": "unknown mode: {a} — choices: {modes}",
228
237
  "tui.modeLine": "mode: {m}",
229
238
  "tui.workModeUnknown": "unknown work mode: {a} — choices: {modes}",
230
239
  "tui.workModeLine": "work mode: {m}",
231
240
  "tui.workModeUsage": "usage: /work-mode <DISCUSS|PLAN|BUILD> — current: {m}",
232
241
  "tui.workModeUnavailable": "work mode is not available in this session",
242
+ "tui.unrestrictedOn": "🔓 unrestricted mode enabled - full access",
243
+ "tui.unrestrictedOff": "🔓 unrestricted disabled — permission mode restored to {m}",
233
244
  "tui.langLine": "lang: {v}",
234
245
  "tui.toolCall": "tool call: {v}",
235
246
  "tui.modelSet": "model: {v}",
236
247
  "tui.thinkingSet": "thinking: {v}",
248
+ "tui.activityFold": "activity: {v}",
237
249
  "tui.sectionsMin": "sections: minimized",
238
250
  "tui.sectionsExp": "sections: expanded",
239
251
  "tui.minUse": "usage: /minimize [on|off]",
package/src/ui/i18n/id.ts CHANGED
@@ -138,9 +138,17 @@ export const id: Record<MsgKey, string> = {
138
138
  "help.cKeys":
139
139
  "Tombol: Tab work-mode · Shift+Tab izin · ↑↓ riwayat · Mouse wheel/PgUp/PgDn gulir · Ctrl+R cari · Ctrl+D keluar",
140
140
  "help.cMore": " /help tombol = semua pintasan",
141
+ "help.gGeneral": "Umum",
142
+ "help.gSession": "Sesi",
143
+ "help.gModel": "Model",
144
+ "help.gMode": "Mode",
145
+ "help.gView": "Tampilan",
146
+ "help.gTask": "Tugas",
141
147
  "help.kHead": "Papan tombol:",
142
148
  "help.k.submit": "kirim",
143
149
  "help.k.cycleMode": "putar work mode",
150
+ "help.k.workMode": "putar work mode (Build/Plan/Discuss)",
151
+ "help.k.permission": "putar mode izin (Auto/Ask)",
144
152
  "help.k.history": "riwayat prompt (di picker: navigasi)",
145
153
  "help.k.mouse": "gulir transkrip dengan mouse wheel",
146
154
  "help.k.scroll": "gulir transkrip dengan PgUp/PgDn (Shift+ = setengah halaman)",
@@ -156,7 +164,7 @@ export const id: Record<MsgKey, string> = {
156
164
  "help.k.compact": "alihkan output tool ringkas/penuh",
157
165
  "help.k.thinking": "alihkan thinking bentang/ringkas",
158
166
  "help.k.esc": "tutup dropdown/picker/hapus baris (busy: batalkan turn)",
159
- "help.k.ctrlC": "hapus baris / batalkan prompt (turn TUI: pakai Esc)",
167
+ "help.k.ctrlC": "salin teks terpilih / batalkan",
160
168
  "help.k.ctrlD": "keluar saat baris kosong",
161
169
  "help.desc.help": "Tampilkan perintah",
162
170
  "help.desc.provider": "Kelola penyedia",
@@ -174,7 +182,7 @@ export const id: Record<MsgKey, string> = {
174
182
  "help.desc.clear": "Bersihkan transkrip",
175
183
  "help.desc.copy": "Salin 1–10 turn terakhir ke clipboard (OSC 52)",
176
184
  "help.desc.history": "Tampilkan riwayat prompt",
177
- "help.desc.scheduler": "Periksa, picu, atau hentikan scheduler otonom",
185
+ "help.desc.scheduler": "Picu / periksa / hentikan scheduler",
178
186
 
179
187
  // [PHASE 6AB] Operator strings for `/scheduler`.
180
188
  "sched.usage": "pakai: /scheduler [status|run|stop]",
@@ -225,16 +233,20 @@ export const id: Record<MsgKey, string> = {
225
233
  "tersalin {turns} turn ({n} chars · OSC 52 — izinkan akses clipboard di terminal bila kosong)",
226
234
  "tui.copyInvalid": "jumlah turn tidak valid: {n} (gunakan 1–{max})",
227
235
  "tui.copyNeedTty": "(clipboard butuh terminal TTY)",
236
+ "tui.copyTooLarge": "payload salin terlalu besar ({n} byte, maks {max})",
228
237
  "tui.unknownMode": "mode tidak dikenal: {a} — pilihan: {modes}",
229
238
  "tui.modeLine": "mode: {m}",
230
239
  "tui.workModeUnknown": "work mode tidak dikenal: {a} — pilihan: {modes}",
231
240
  "tui.workModeLine": "mode kerja: {m}",
232
241
  "tui.workModeUsage": "pemakaian: /work-mode <DISCUSS|PLAN|BUILD> — aktif: {m}",
233
242
  "tui.workModeUnavailable": "work mode tidak tersedia di sesi ini",
243
+ "tui.unrestrictedOn": "🔓 mode unrestricted aktif - akses penuh",
244
+ "tui.unrestrictedOff": "🔓 unrestricted nonaktif — mode izin kembali ke {m}",
234
245
  "tui.langLine": "lang: {v}",
235
246
  "tui.toolCall": "pemanggilan tool: {v}",
236
247
  "tui.modelSet": "model: {v}",
237
248
  "tui.thinkingSet": "thinking: {v}",
249
+ "tui.activityFold": "aktivitas: {v}",
238
250
  "tui.sectionsMin": "bagian: diminimalkan",
239
251
  "tui.sectionsExp": "bagian: dibuka",
240
252
  "tui.minUse": "pakai: /minimize [on|off]",
@@ -64,10 +64,10 @@ export type PromptKey =
64
64
  | { type: "ctrl-w" } // delete previous word
65
65
  | { type: "ctrl-o" } // expand detail (TUI)
66
66
  | { type: "ctrl-r" } // reverse-i-search history
67
- | { type: "ctrl-t" } // toggle expand/minimize reasoning di REPL
67
+ | { type: "ctrl-t" } // toggle expand/minimize reasoning (TUI)
68
68
  | { type: "ctrl-n" } // tambah (model-manager: Ctrl+N = add model)
69
69
  | { type: "ctrl-j" } // sisipkan newline (multiline opt-in; Enter=\r tetap submit)
70
- | { type: "shift-tab" } // cycle mode (REPL linier) — ESC[Z didekode decodeKey
70
+ | { type: "shift-tab" } // toggle permission mode (TUI) — ESC[Z didekode decodeKey
71
71
  | { type: "ignore" } // sekuens yang sengaja dibuang (mis. byte mouse)
72
72
 
73
73
  // Terapkan satu keypress -> state baru + render spec + action (submit/cancel).
@@ -80,7 +80,22 @@ export type PromptAction = "none" | "render" | "submit" | "cancel"
80
80
  // batas grapheme sungguhan (Node 16+ / Bun tersedia); fallback ke code point
81
81
  // di runtime tanpa dukungan.
82
82
  let segmenter: Intl.Segmenter | undefined
83
- export function toGraphemes(s: string): string[] {
83
+ /**
84
+ * Pisah string menjadi grapheme. ASCII murni dilewati cepat (satu char = satu
85
+ * grapheme) dan hasilnya di-memo satu entri: satu paint memanggil ini berkali-
86
+ * kali untuk baris yang SAMA (layout, posisi kursor, dsb.), dan `Intl.Segmenter`
87
+ * adalah biaya terbesar di jalur ketik. Pemanggil MENGUBAH array hasil
88
+ * (splice), jadi cache selalu disalin keluar — bukan dikembalikan langsung.
89
+ */
90
+ function segmentInto(s: string): string[] {
91
+ let ascii = true
92
+ for (let i = 0; i < s.length; i++) {
93
+ if (s.charCodeAt(i) > 0x7f) {
94
+ ascii = false
95
+ break
96
+ }
97
+ }
98
+ if (ascii) return s.split("")
84
99
  try {
85
100
  segmenter ??= new Intl.Segmenter("und", { granularity: "grapheme" })
86
101
  return [...segmenter.segment(s)].map((seg) => seg.segment)
@@ -89,6 +104,17 @@ export function toGraphemes(s: string): string[] {
89
104
  }
90
105
  }
91
106
 
107
+ let memoInput: string | null = null
108
+ let memoOutput: string[] | null = null
109
+
110
+ export function toGraphemes(s: string): string[] {
111
+ if (memoInput === s && memoOutput !== null) return memoOutput.slice()
112
+ const out = segmentInto(s)
113
+ memoInput = s
114
+ memoOutput = out
115
+ return out.slice()
116
+ }
117
+
92
118
  /** Panjang dalam satuan grapheme (bukan code point / UTF-16 unit). */
93
119
  export function pointLength(s: string): number {
94
120
  return toGraphemes(s).length
@@ -198,8 +224,8 @@ export function applyKey(
198
224
  // Paste bisa memuat newline/tab/kontrol. Dulu "\n" digepeng jadi spasi
199
225
  // agar tidak melebihi tinggi terminal, tapi itu membuat copas code
200
226
  // multilines cuma baris pertama (keluhan nyata). Sekarang "\n" dipertahankan
201
- // sebagai baris baru — renderer `scrollableMultiline` sudah memperhitungkan
202
- // tinggi (`nInGuess`, `maxVisible - footerReserveRows`) sehingga tidak
227
+ // sebagai baris baru — renderer `buildRenderSpec` sudah memperhitungkan
228
+ // tinggi (`maxVisible`) sehingga tidak
203
229
  // menabrak footer. Tab jadi spasi; kontrol lain dibuang.
204
230
  const ins = key.ch
205
231
  .replace(/\r\n|\r/g, "\n")
@@ -277,11 +303,11 @@ export function applyKey(
277
303
  case "ctrl-c":
278
304
  case "ctrl-d":
279
305
  return { state, action: "cancel" }
280
- case "ctrl-o": // toggle compact — ditangani REPL lewat onKey askLine
306
+ case "ctrl-o": // toggle compact — ditangani host TUI (app.ts)
281
307
  case "ctrl-r": // reverse-i-search — ditangani askLine (input.ts) sebelum applyKey
282
- case "ctrl-t": // toggle expand/minimize reasoning di REPL (onKey)
308
+ case "ctrl-t": // toggle expand/minimize reasoning — ditangani host TUI (app.ts)
283
309
  case "ctrl-n": // tambah model — ditangani view yang membutuhkan (model-manager); di prompt teks diabaikan
284
- case "shift-tab": // cycle mode — ditangani REPL lewat onKey askLine
310
+ case "shift-tab": // toggle permission mode — ditangani host TUI (app.ts)
285
311
  case "ignore":
286
312
  return { state, action: "none" }
287
313
  case "ctrl-u": {
@@ -604,7 +630,7 @@ export function flushLoneEsc(state: DecoderState): DecodedKey[] {
604
630
  // panah split secara sinkron). Pompa ini membungkus pola yang dipakai SEMUA
605
631
  // konsumen interaktif (askLine/askSecret/picker/manager): decode chunk →
606
632
  // teruskan key sinkron → bila pending Esc tunggal, tunggu ~50ms (pola
607
- // lone-ESC yang sama saat busy di cli/repl.ts); byte lanjutan membatalkan
633
+ // lone-ESC yang sama saat busy di TUI, `src/ui/tui/app.ts`); byte lanjutan membatalkan
608
634
  // timer dan melengkapi sekuens, sunyi berarti Esc asli → flush sebagai esc.
609
635
  //
610
636
  // Tanpa pompa tiap konsumen harus menulis timer sendiri (duplikasi 5× dan
@@ -786,7 +812,7 @@ export function decodeKey(s: string, i: number): DecodedKey | null {
786
812
  }
787
813
  // selain itu (ESC[5;34R, ESC[5x, …) → catch-all esc di bawah
788
814
  }
789
- // Shift+Tab (backtab) ESC [ Z — dipakai REPL linier untuk cycle mode.
815
+ // Shift+Tab (backtab) ESC [ Z — dipakai TUI untuk toggle permission mode.
790
816
  // Tanpa cabang eksplisit ini ia jatuh ke catch-all "esc" di bawah,
791
817
  // sehingga tipe "shift-tab" tidak pernah dihasilkan decodeKeys.
792
818
  if (kind === "Z") return { key: { type: "shift-tab" }, width: 3 }
@@ -0,0 +1,320 @@
1
+ // Framebuffer sel untuk penulisan terminal inkremental.
2
+ //
3
+ // Kenapa ada: diff per BARIS (CUP+EL lalu tulis ulang seluruh baris) masih
4
+ // membayar O(panjang baris) untuk setiap perubahan kecil. Mengetik satu huruf
5
+ // di prompt 1.000 karakter berarti menulis ulang ±1.000 karakter ke ConPTY.
6
+ // Modul ini memecah baris menjadi SEL (grapheme + gaya SGR) lalu menghasilkan
7
+ // hanya rentang kolom yang benar-benar berubah — mekanisme yang sama dengan
8
+ // framebuffer/diff-cell OpenTUI, tetapi murni TypeScript tanpa dependency.
9
+ //
10
+ // Kontrak penting:
11
+ // - Frame LOGIS tetap penuh (pemilik layar mengirim `rows` baris utuh); modul
12
+ // ini hanya memutuskan byte FISIK apa yang ditulis.
13
+ // - Glyph lebar (CJK/emoji) menempati beberapa kolom: sel pertama membawa
14
+ // glyph, kolom lanjutan ditandai `cont` agar diff tidak memotong glyph.
15
+ // - Gaya disimpan sebagai STATE SGR, bukan riwayat sekuens mentah: terminal
16
+ // memperlakukan SGR sebagai himpunan atribut aktif, jadi `\x1b[39m` harus
17
+ // membatalkan warna foreground sebelumnya — bukan menumpuk sebagai teks.
18
+ // Tanpa normalisasi ini setiap sel sesudah reset membawa string yang terus
19
+ // memanjang, diff menganggap sel identik "berubah", dan footer ditulis ulang
20
+ // tiap detik.
21
+ import { escapeLength, graphemeWidth, segmentGraphemes } from "./width.ts"
22
+
23
+ /** Satu kolom layar. `cont` = kolom lanjutan glyph lebar (tanpa glyph sendiri). */
24
+ export interface Cell {
25
+ glyph: string
26
+ /** Sekuens SGR aktif ("" = atribut default). */
27
+ style: string
28
+ cont?: boolean
29
+ }
30
+
31
+ const BLANK: Cell = { glyph: " ", style: "" }
32
+
33
+ /** SGR saja (`ESC[...m` dengan parameter angka/`;`/`:`) — sisanya diabaikan. */
34
+ function isSgr(seq: string): boolean {
35
+ if (!seq.startsWith("\x1b[") || !seq.endsWith("m")) return false
36
+ for (let i = 2; i < seq.length - 1; i++) {
37
+ const ch = seq[i]!
38
+ if (!((ch >= "0" && ch <= "9") || ch === ";" || ch === ":")) return false
39
+ }
40
+ return true
41
+ }
42
+
43
+ /** Urutan serialisasi kanonik — hasil sama apa pun urutan SGR masukannya. */
44
+ const SGR_ORDER = [
45
+ "bold",
46
+ "dim",
47
+ "italic",
48
+ "underline",
49
+ "blink",
50
+ "inverse",
51
+ "conceal",
52
+ "strike",
53
+ "fg",
54
+ "bg",
55
+ ] as const
56
+
57
+ interface SgrState {
58
+ values: Map<string, string>
59
+ }
60
+
61
+ function setGroup(state: SgrState, group: string, value: string | null): void {
62
+ if (value === null) state.values.delete(group)
63
+ else state.values.set(group, value)
64
+ }
65
+
66
+ function serializeSgr(state: SgrState): string {
67
+ if (state.values.size === 0) return ""
68
+ const parts: string[] = []
69
+ for (const group of SGR_ORDER) {
70
+ const value = state.values.get(group)
71
+ if (value !== undefined) parts.push(value)
72
+ }
73
+ return `\x1b[${parts.join(";")}m`
74
+ }
75
+
76
+ /** Parameter warna lanjutan (`38;5;n` / `38;2;r;g;b`), atau null bila tak lengkap. */
77
+ function readExtended(
78
+ tokens: string[],
79
+ i: number,
80
+ code: number,
81
+ ): { value: string; next: number } | null {
82
+ const mode = tokens[i + 1]
83
+ if (mode === "5") {
84
+ const slot = tokens[i + 2]
85
+ if (slot === undefined) return null
86
+ return { value: `${code};5;${slot}`, next: i + 2 }
87
+ }
88
+ if (mode === "2") {
89
+ const r = tokens[i + 2]
90
+ const g = tokens[i + 3]
91
+ const b = tokens[i + 4]
92
+ if (r === undefined || g === undefined || b === undefined) return null
93
+ return { value: `${code};2;${r};${g};${b}`, next: i + 4 }
94
+ }
95
+ return null
96
+ }
97
+
98
+ /**
99
+ * Terapkan satu sekuens SGR ke state. Reset penuh (kosong/0) membuang semua.
100
+ * Parameter tak dikenal disimpan apa adanya (grup `raw:<token>`) supaya tidak
101
+ * hilang dan tetap idempoten di paint ulang.
102
+ */
103
+ function applySgrTo(state: SgrState, seq: string): void {
104
+ const body = seq.slice(2, -1)
105
+ const tokens = body === "" ? ["0"] : body.split(";")
106
+ for (let i = 0; i < tokens.length; i++) {
107
+ const token = tokens[i]!
108
+ // Bentuk titik-dua (mis. `38:5:196`) dibiarkan utuh — satu nilai warna.
109
+ const colon = token.indexOf(":")
110
+ if (colon >= 0) {
111
+ const head = token.slice(0, colon)
112
+ if (head === "38" || head === "58") setGroup(state, "fg", token)
113
+ else if (head === "48") setGroup(state, "bg", token)
114
+ else setGroup(state, `raw:${head}`, token)
115
+ continue
116
+ }
117
+ const n = token === "" ? 0 : Number(token)
118
+ if (Number.isNaN(n)) {
119
+ setGroup(state, `raw:${token}`, token)
120
+ continue
121
+ }
122
+ if (n === 0) {
123
+ state.values.clear()
124
+ continue
125
+ }
126
+ if (n === 38 || n === 48) {
127
+ const extended = readExtended(tokens, i, n)
128
+ if (!extended) {
129
+ setGroup(state, `raw:${n}`, token)
130
+ continue
131
+ }
132
+ setGroup(state, n === 38 ? "fg" : "bg", extended.value)
133
+ i = extended.next
134
+ continue
135
+ }
136
+ switch (n) {
137
+ case 1:
138
+ setGroup(state, "bold", "1")
139
+ break
140
+ case 2:
141
+ setGroup(state, "dim", "2")
142
+ break
143
+ case 22:
144
+ setGroup(state, "bold", null)
145
+ setGroup(state, "dim", null)
146
+ break
147
+ case 3:
148
+ setGroup(state, "italic", "3")
149
+ break
150
+ case 23:
151
+ setGroup(state, "italic", null)
152
+ break
153
+ case 4:
154
+ setGroup(state, "underline", "4")
155
+ break
156
+ case 24:
157
+ setGroup(state, "underline", null)
158
+ break
159
+ case 5:
160
+ case 6:
161
+ setGroup(state, "blink", String(n))
162
+ break
163
+ case 25:
164
+ setGroup(state, "blink", null)
165
+ break
166
+ case 7:
167
+ setGroup(state, "inverse", "7")
168
+ break
169
+ case 27:
170
+ setGroup(state, "inverse", null)
171
+ break
172
+ case 8:
173
+ setGroup(state, "conceal", "8")
174
+ break
175
+ case 28:
176
+ setGroup(state, "conceal", null)
177
+ break
178
+ case 9:
179
+ setGroup(state, "strike", "9")
180
+ break
181
+ case 29:
182
+ setGroup(state, "strike", null)
183
+ break
184
+ case 39:
185
+ setGroup(state, "fg", null)
186
+ break
187
+ case 49:
188
+ setGroup(state, "bg", null)
189
+ break
190
+ default:
191
+ if ((n >= 30 && n <= 37) || (n >= 90 && n <= 97)) setGroup(state, "fg", String(n))
192
+ else if ((n >= 40 && n <= 47) || (n >= 100 && n <= 107)) setGroup(state, "bg", String(n))
193
+ else setGroup(state, `raw:${n}`, String(n))
194
+ }
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Pecah satu baris frame menjadi sel kolom. Escape non-SGR diabaikan (frame
200
+ * TUI hanya membawa SGR; sanitizer membuang kontrol lain). Tab diperlakukan
201
+ * selebar 8 kolom — kebijakan yang sama dengan `charWidth`/`displayWidth`.
202
+ */
203
+ export function parseCells(line: string): Cell[] {
204
+ const cells: Cell[] = []
205
+ const sgr: SgrState = { values: new Map() }
206
+ let style = ""
207
+ let i = 0
208
+ while (i < line.length) {
209
+ if (line[i] === "\x1b") {
210
+ const len = escapeLength(line, i)
211
+ if (len > 0) {
212
+ const seq = line.slice(i, i + len)
213
+ if (isSgr(seq)) {
214
+ applySgrTo(sgr, seq)
215
+ style = serializeSgr(sgr)
216
+ }
217
+ i += len
218
+ continue
219
+ }
220
+ }
221
+ let end = line.indexOf("\x1b", i)
222
+ if (end < 0) end = line.length
223
+ if (end === i) end++
224
+ const run = line.slice(i, end)
225
+ for (const g of segmentGraphemes(run)) {
226
+ // Baris frame tidak boleh memuat newline; kalau ada, itu artefak dan
227
+ // bukan sel yang sah (menuliskannya akan menggeser baris berikut).
228
+ if (g === "\n" || g === "\r" || g === "\x1b") continue
229
+ const width = g === "\t" ? 8 : graphemeWidth(g)
230
+ if (width <= 0) {
231
+ // Grapheme nol-lebar menempel ke sel sebelumnya (mis. combining mark
232
+ // yang lolos tanpa base). Tanpa base, simpan sebagai sel selebar 1
233
+ // supaya posisi kolom berikutnya tidak meleset.
234
+ const prev = cells[cells.length - 1]
235
+ if (prev && !prev.cont) prev.glyph += g
236
+ else cells.push({ glyph: g, style })
237
+ continue
238
+ }
239
+ cells.push({ glyph: g === "\t" ? " ".repeat(8) : g, style })
240
+ for (let k = 1; k < width; k++) cells.push({ glyph: "", style, cont: true })
241
+ }
242
+ i = end
243
+ }
244
+ return cells
245
+ }
246
+
247
+ /** Sel hilang = blank default; terminal memang sudah punya blank di sana. */
248
+ function sameCell(a: Cell | undefined, b: Cell | undefined): boolean {
249
+ if (!a && !b) return true
250
+ if (!a || !b) {
251
+ const only = a ?? b!
252
+ return only.glyph === " " && only.style === "" && !only.cont
253
+ }
254
+ return a.glyph === b.glyph && a.style === b.style && Boolean(a.cont) === Boolean(b.cont)
255
+ }
256
+
257
+ /**
258
+ * Tulis ulang EKOR baris `next` mulai kolom `start` (0-based, sudah selaras
259
+ * glyph): CUP ke kolom itu, reset atribut, hapus sisa baris (EL `0K`), lalu
260
+ * render sel dari `start` sampai akhir.
261
+ *
262
+ * Kenapa hapus-lalu-tulis, bukan menulis rentang terpisah per perubahan:
263
+ * terminal (khususnya ConPTY Windows) memegang buffer sendiri. Byte yang tidak
264
+ * kita tulis TIDAK hilang dari layar — sisa glyph lebar, ekor baris lama, atau
265
+ * teks diagnostik asing (`[hooks] …` dari stderr) tetap menempel bila tidak
266
+ * dihapus. Diff per-rentang tanpa EL pernah membiarkan sampah itu bertahan
267
+ * (regresi PTY: baris emoji + prompt tertimpa fragmen asing). Menghapus dari
268
+ * kolom perubahan pertama ke akhir baris menutup celah itu sekaligus tetap
269
+ * melewati prefix yang identik — penghasilan byte fase-2 untuk prompt panjang.
270
+ */
271
+ function emitTail(next: Cell[], start: number, row: number): string {
272
+ // Reset SEBELUM EL: EL mewarisi atribut aktif (BCE), jadi tanpa reset area
273
+ // terhapus bisa tetap berwarna.
274
+ let out = `\x1b[${row};${start + 1}H\x1b[0m\x1b[0K`
275
+ // Setelah reset, atribut awal = default ("").
276
+ let active = ""
277
+ for (let col = start; col < next.length; col++) {
278
+ const cell = next[col]
279
+ // Kolom lanjutan tidak ditulis: glyph lebar di sel sebelumnya sudah
280
+ // memajukan kursor melewatinya.
281
+ if (cell?.cont) continue
282
+ const glyph = cell?.glyph ?? " "
283
+ const style = cell?.style ?? ""
284
+ if (style !== active) {
285
+ // Reset dulu agar atribut dari run sebelumnya tidak bocor ke sel ini.
286
+ out += style ? `\x1b[0m${style}` : "\x1b[0m"
287
+ active = style
288
+ }
289
+ out += glyph
290
+ }
291
+ return out
292
+ }
293
+
294
+ /**
295
+ * Hasilkan byte yang mengubah baris `prev` menjadi `next`.
296
+ *
297
+ * Prefix identik tidak ditulis (nol byte); dari kolom berbeda pertama sampai
298
+ * akhir baris ditulis ulang setelah EL. `prev`/`next` adalah keluaran
299
+ * `parseCells` untuk baris yang sama; pemanggil wajib menyimpan `prev` dari
300
+ * paint sebelumnya.
301
+ */
302
+ export function diffCellLine(prev: Cell[], next: Cell[], row: number): string {
303
+ const max = Math.max(prev.length, next.length)
304
+ let start = 0
305
+ while (start < max && sameCell(prev[start], next[start])) start++
306
+ if (start >= max) return ""
307
+ // Jangan mulai di tengah glyph lebar: mundur ke sel pembawa glyph supaya EL
308
+ // tidak membelah glyph (meninggalkan separuh sel kosong di kolom sebelumnya).
309
+ while (start > 0 && (prev[start]?.cont || next[start]?.cont)) start--
310
+ return emitTail(next, start, row)
311
+ }
312
+
313
+ /** True bila dua baris framebuffer identik secara tampilan (test/diagnostik). */
314
+ export function sameCells(a: Cell[], b: Cell[]): boolean {
315
+ if (a.length !== b.length) return false
316
+ for (let i = 0; i < a.length; i++) if (!sameCell(a[i], b[i])) return false
317
+ return true
318
+ }
319
+
320
+ export const EMPTY_CELLS: readonly Cell[] = [BLANK]
@@ -0,0 +1,73 @@
1
+ // Wrap composer INKREMENTAL.
2
+ //
3
+ // Kenapa ada: `chunkByWidth` adalah O(panjang baris). Mengetik satu huruf di
4
+ // prompt 5.000 karakter berarti membungkus ulang 5.000 karakter tiap ketukan —
5
+ // biaya itulah yang membuat ketikan panjang terasa berat. Karena composer
6
+ // menambah/menghapus SELALU di ujung baris, wrap greedy (isi tiap baris
7
+ // maksimal) hanya berubah pada baris visual TERAKHIR; baris sebelumnya sudah
8
+ // jenuh dan tak terpengaruh.
9
+ //
10
+ // Kontrak: helper di sini mengembalikan `null` bila pola tak didukung supaya
11
+ // pemanggil jatuh balik ke `chunkByWidth` penuh (jawaban aman, bukan jawaban
12
+ // salah). Teks composer tak memuat SGR (engine membuang byte kontrol), jadi
13
+ // varian tanpa riwayat SGR cukup — SGR apa pun memicu fallback.
14
+ import { displayWidth, segmentGraphemes } from "./width.ts"
15
+
16
+ /** Tabel kelipatan lebar tab, sinkron dengan `chunkByWidth`. */
17
+ const TAB_WIDTH = 8
18
+
19
+ function graphemeColumns(g: string): number {
20
+ if (g === "\t") return TAB_WIDTH
21
+ // Kolom lanjutan grapheme lebar: dihitung per grapheme (bukan per sel).
22
+ return displayWidth(g)
23
+ }
24
+
25
+ /**
26
+ * Perluas `rows` (hasil `chunkByWidth` untuk teks sebelumnya) dengan `appended`
27
+ * di UJUNG, mempertahankan wrap greedy. `null` bila tak bisa (baris kosong,
28
+ * lebar ≤ 0, atau ada newline/SGR) — pemanggil membungkus ulang penuh.
29
+ */
30
+ export function appendWrapped(rows: string[], appended: string, width: number): string[] | null {
31
+ if (!rows.length || width <= 0) return null
32
+ if (appended.includes("\n") || appended.includes("\r") || appended.includes("\x1b")) return null
33
+ const out = rows.slice(0, -1)
34
+ let buf = rows[rows.length - 1]!
35
+ for (const g of segmentGraphemes(appended)) {
36
+ const gw = graphemeColumns(g)
37
+ if (gw <= 0) {
38
+ // Grapheme nol-lebar menempel ke buf tanpa menghabiskan kolom.
39
+ buf += g
40
+ continue
41
+ }
42
+ if (displayWidth(buf) + gw > width && buf !== "") {
43
+ out.push(buf)
44
+ buf = ""
45
+ }
46
+ buf += g
47
+ }
48
+ out.push(buf)
49
+ return out
50
+ }
51
+
52
+ /**
53
+ * Buang `removed` (UTF-16, harus menjadi AKHIR baris visual terakhir) dari
54
+ * `rows`. `null` bila baris terakhir tak diakhiri `removed` (mis. batas
55
+ * grapheme berbeda) — pemanggil membungkus ulang penuh.
56
+ */
57
+ export function shaveWrapped(rows: string[], removed: string, width: number): string[] | null {
58
+ if (!rows.length || width <= 0 || !removed) return null
59
+ if (removed.includes("\x1b")) return null
60
+ const last = rows[rows.length - 1]!
61
+ if (!last.endsWith(removed)) return null
62
+ const trimmed = last.slice(0, last.length - removed.length)
63
+ if (trimmed === "") {
64
+ // Baris terakhir habis. Baris sebelumnya jenuh, jadi cukup pop — tapi bila
65
+ // ini satu-satunya baris, serahkan ke pemanggil (prefix prompt bisa hilang
66
+ // saat baris jadi kosong dan special-case `!line` yang menanganinya).
67
+ if (rows.length === 1) return null
68
+ return rows.slice(0, -1)
69
+ }
70
+ const out = rows.slice(0, -1)
71
+ out.push(trimmed)
72
+ return out
73
+ }
@@ -1,8 +1,8 @@
1
1
  // Satu sumber state "level detail tool call": expanded vs compact.
2
2
  //
3
3
  // Posisi Minicode = agentic Unix shell: tool call transparan di aliran output.
4
- // Default tergantung konteks: one-shot/exec = expanded; REPL interaktif
5
- // mengaktifkan compact saat start (lihat runRepl) kecuali env diset eksplisit.
4
+ // Default tergantung konteks: one-shot/exec = expanded; TUI interaktif
5
+ // mengaktifkan compact saat start (`cli/tui.ts`) kecuali env diset eksplisit.
6
6
  // `MINICODE_COMPACT=1`/`0` atau `/compact` selalu menang.
7
7
  //
8
8
  // [F-ENV-1] State module-local di-bootstrap SATU KALI dari env saat import; setter
@@ -1,7 +1,7 @@
1
1
  // Diff renderer - Ubuntu Server style: indentasi + warna, tanpa border.
2
2
  import { sanitizeAnsi, sanitizeAnsiLine } from "./sanitize.ts"
3
3
  import { c } from "./theme.ts"
4
- import { truncateToWidth } from "./width.ts"
4
+ import { truncateToWidth, wrapByWidth } from "./width.ts"
5
5
 
6
6
  export interface DiffLine {
7
7
  type: "add" | "delete" | "context"
@@ -147,9 +147,18 @@ export function renderDiffCard(
147
147
  const max = opts.maxLines ?? 12
148
148
  // Baris diff bisa sepanjang baris kode aslinya. Tanpa batas, satu baris 300
149
149
  // karakter membungkus sendiri di terminal dan merusak frame TUI yang
150
- // menghitung tinggi per baris. Default mengikuti lebar terminal.
150
+ // menghitung tinggi per baris. Default mengikuti lebar terminal. Baris isi
151
+ // di-WRAP (bukan truncate) agar perubahan tidak hilang — hanya path header
152
+ // yang dipotong dengan ellipsis (label pendek, semantik satu baris).
151
153
  const width = opts.width ?? (process.stdout.columns || 80)
152
154
  const cut = (s: string) => truncateToWidth(s, Math.max(8, width - 1))
155
+ const wrapDiffLine = (prefix: string, body: string, paint: (s: string) => string): string[] => {
156
+ const bodyWidth = Math.max(6, width - prefix.length)
157
+ const parts = wrapByWidth(body, bodyWidth)
158
+ return parts.map((p, i) =>
159
+ i === 0 ? paint(`${prefix}${p}`) : paint(`${" ".repeat(prefix.length)}${p}`),
160
+ )
161
+ }
153
162
 
154
163
  const lines: string[] = [c.accent(c.bold(cut(` ${safePath}`)))]
155
164
  // collect indices of changes plus 1 context line before/after
@@ -174,12 +183,12 @@ export function renderDiffCard(
174
183
  if (d.type === "add") {
175
184
  const mask = wordMask.get(i)
176
185
  const body = mask ? paintWords(d.content, mask, (s) => c.bold(s)) : d.content
177
- lines.push(c.success(cut(` + ${body}`)))
186
+ lines.push(...wrapDiffLine(" + ", body, (s) => c.success(s)))
178
187
  } else if (d.type === "delete") {
179
188
  const mask = wordMask.get(i)
180
189
  const body = mask ? paintWords(d.content, mask, (s) => c.bold(s)) : d.content
181
- lines.push(c.error(cut(` - ${body}`)))
182
- } else lines.push(c.dim(cut(` ${d.content}`)))
190
+ lines.push(...wrapDiffLine(" - ", body, (s) => c.error(s)))
191
+ } else lines.push(...wrapDiffLine(" ", d.content, (s) => c.dim(s)))
183
192
  count++
184
193
  }
185
194
  return lines.join("\n")