minicode-ai 0.10.0 → 0.11.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 (128) hide show
  1. package/AGENTS.md +45 -0
  2. package/CHANGELOG.md +59 -4
  3. package/PLAN.md +491 -0
  4. package/README.md +2 -2
  5. package/cli/commands/acp.ts +485 -0
  6. package/cli/commands/auth.ts +7 -4
  7. package/cli/commands/config.ts +41 -27
  8. package/cli/commands/exec.ts +33 -12
  9. package/cli/commands/mcp.ts +3 -2
  10. package/cli/commands/memory.ts +1 -1
  11. package/cli/commands/pricing.ts +6 -4
  12. package/cli/commands/providers.ts +18 -8
  13. package/cli/commands/sessions.ts +11 -4
  14. package/cli/commands/skills.ts +3 -3
  15. package/cli/commands/stats.ts +3 -1
  16. package/cli/commands.ts +6 -0
  17. package/cli/index.ts +82 -57
  18. package/cli/model-manager.ts +6 -1
  19. package/cli/router.ts +7 -0
  20. package/cli/setup.ts +341 -5
  21. package/cli/tui.ts +54 -18
  22. package/docs/ARCHITECTURE.html +29 -22
  23. package/docs/CONTROL-PLANE-MAP.md +139 -0
  24. package/docs/HARNESS.md +150 -0
  25. package/docs/PLAN_UIUX_V6.md +209 -0
  26. package/docs/README.md +1 -1
  27. package/docs/SUMMARY.md +52 -0
  28. package/docs/TERMINAL_CONTRACT.md +367 -0
  29. package/docs/UI_RENDER_PIPELINE.md +165 -0
  30. package/docs/USAGE.md +11 -0
  31. package/docs/agents.md +31 -0
  32. package/docs/architecture.md +3 -3
  33. package/docs/choosing-mode.md +34 -0
  34. package/docs/cli.md +130 -0
  35. package/docs/concepts.md +53 -0
  36. package/docs/config-providers.md +87 -0
  37. package/docs/config.md +63 -0
  38. package/docs/contributing.md +79 -0
  39. package/docs/environment.md +95 -0
  40. package/docs/exec.md +73 -0
  41. package/docs/getting-started.md +102 -0
  42. package/docs/glossary.md +37 -0
  43. package/docs/mcp-lsp.md +54 -0
  44. package/docs/memory-sessions.md +63 -0
  45. package/docs/policy-sandbox.md +72 -0
  46. package/docs/pricing-budget.md +49 -0
  47. package/docs/quickstart.md +60 -0
  48. package/docs/repl.md +67 -0
  49. package/docs/security-model.md +95 -0
  50. package/docs/security.md +91 -0
  51. package/docs/skills.md +48 -0
  52. package/docs/terminal.md +79 -0
  53. package/docs/tools.md +123 -0
  54. package/docs/troubleshooting.md +40 -0
  55. package/docs/verify-benchmark.md +58 -0
  56. package/package.json +8 -5
  57. package/src/app/provider-layer.ts +12 -4
  58. package/src/app/session.ts +6 -0
  59. package/src/app/tool-layer.ts +2 -1
  60. package/src/constants.ts +35 -0
  61. package/src/lib/net.ts +6 -1
  62. package/src/lsp/client.ts +41 -8
  63. package/src/mcp/http-transport.ts +52 -15
  64. package/src/mcp/transport.ts +32 -1
  65. package/src/memory/files.ts +6 -5
  66. package/src/policy/allowlist.ts +1 -1
  67. package/src/policy/bash-guard.ts +154 -14
  68. package/src/policy/compaction.ts +57 -3
  69. package/src/policy/context.ts +4 -0
  70. package/src/policy/jail.ts +49 -4
  71. package/src/policy/permission.ts +152 -12
  72. package/src/policy/pricing.ts +12 -9
  73. package/src/presentation/adapter.ts +721 -0
  74. package/src/presentation/events.ts +324 -0
  75. package/src/presentation/label.ts +140 -0
  76. package/src/presentation/model.ts +172 -0
  77. package/src/presentation/reducer.ts +486 -0
  78. package/src/presentation/store.ts +256 -0
  79. package/src/providers/anthropic.ts +22 -4
  80. package/src/providers/detect.ts +2 -1
  81. package/src/providers/router.ts +13 -0
  82. package/src/repo/repomap.ts +2 -29
  83. package/src/session/checkpoint.ts +27 -9
  84. package/src/session/journal.ts +27 -5
  85. package/src/skills/loader.ts +88 -5
  86. package/src/telemetry/trace.ts +36 -15
  87. package/src/tools/ask_user.ts +73 -4
  88. package/src/tools/bash.ts +15 -17
  89. package/src/tools/glob.ts +10 -11
  90. package/src/tools/lsp.ts +3 -56
  91. package/src/tools/memory.ts +13 -12
  92. package/src/tools/task.ts +1 -0
  93. package/src/ui/approval/prompt.ts +14 -6
  94. package/src/ui/assistant/simple.ts +137 -26
  95. package/src/ui/assistant/turn-status.ts +16 -3
  96. package/src/ui/contract.ts +119 -0
  97. package/src/ui/footer.ts +21 -2
  98. package/src/ui/i18n/en.ts +34 -6
  99. package/src/ui/i18n/id.ts +34 -6
  100. package/src/ui/i18n/locale.ts +3 -1
  101. package/src/ui/input/input.ts +51 -4
  102. package/src/ui/input/prompt-engine.ts +46 -4
  103. package/src/ui/render/collapse.ts +13 -13
  104. package/src/ui/render/diff.ts +7 -2
  105. package/src/ui/render/format.ts +16 -8
  106. package/src/ui/render/highlight.ts +7 -3
  107. package/src/ui/render/markdown.ts +5 -1
  108. package/src/ui/render/sanitize.ts +29 -2
  109. package/src/ui/render/table.ts +8 -5
  110. package/src/ui/render/theme.ts +18 -4
  111. package/src/ui/render/width.ts +89 -10
  112. package/src/ui/runtime/motion.ts +16 -0
  113. package/src/ui/runtime/screen.ts +45 -0
  114. package/src/ui/runtime/spinner.ts +50 -4
  115. package/src/ui/runtime/statusline.ts +50 -1
  116. package/src/ui/screens/form.ts +42 -15
  117. package/src/ui/screens/model-manager.ts +26 -18
  118. package/src/ui/screens/picker.ts +47 -23
  119. package/src/ui/screens/provider-manager.ts +18 -12
  120. package/src/ui/screens/wizard.ts +24 -8
  121. package/src/ui/tui/app.ts +233 -27
  122. package/src/ui/tui/transcript.ts +269 -65
  123. package/vendor/minicore/LICENSE +21 -0
  124. package/vendor/minicore/VENDOR.md +6 -3
  125. package/vendor/minicore/package.json +6 -3
  126. package/vendor/minicore/src/core/loop.ts +12 -2
  127. package/vendor/minicore/src/core/snapshot.ts +4 -0
  128. package/vendor/minicore/src/providers/openai-compat.ts +76 -25
package/src/ui/i18n/id.ts CHANGED
@@ -7,8 +7,14 @@ export const id: Record<MsgKey, string> = {
7
7
  "app.menuHeader": "─ perintah ─",
8
8
  "app.moreLines": " … {n} lagi",
9
9
  "app.newBelow": "↓ {n} baris baru di bawah · PgDn ke ekor",
10
+ "app.abortHint": "abort terkirim — tekan Esc/Ctrl+C sekali lagi untuk keluar",
11
+ "form.idleWarning": "diam — dibatalkan dalam {s} dtk (tekan sembarang tombol untuk lanjut)",
10
12
  "appr.title": "Perlu persetujuan",
11
13
  "appr.tool": "Alat:",
14
+ "appr.cmdLabel": "Perintah:",
15
+ "appr.fileLabel": "Berkas:",
16
+ "appr.queryLabel": "Kueri:",
17
+ "appr.argsLabel": "Argumen:",
12
18
  "appr.allowOnce": "[y] Izinkan sekali",
13
19
  "appr.always": "[a] Selalu",
14
20
  "appr.deny": "[n] Tolak",
@@ -21,7 +27,18 @@ export const id: Record<MsgKey, string> = {
21
27
  "dlg.more": "… {n} lagi",
22
28
  "ts.compacted": "… dipadatkan: {reason}",
23
29
  "ts.thinking": "… berpikir",
24
- "form.footerDefault": "Tab pindah · Enter simpan · Esc batal",
30
+ "ts.evictMarker": "… {n} baris awal di luar viewport — riwayat penuh di model",
31
+ "ts.statusRunning": "berjalan",
32
+ "ts.statusCompleted": "selesai",
33
+ "ts.statusFailed": "gagal",
34
+ "ts.statusDenied": "ditolak",
35
+ "ts.statusCancelled": "dibatalkan",
36
+ "ts.statusInterrupted": "terhenti",
37
+ "ts.retry": "↻ ulangi",
38
+ "ts.childGroup": "{n} tool anak",
39
+ "ts.turnSummary":
40
+ "turn {turn} · {ok} ok · {failed} gagal · {denied} ditolak · {cancelled} dibatalkan · {interrupted} terhenti · {files} berkas · ckpt {ckpt} · {secs}",
41
+ "form.footerDefault": "Tab:{move} · Enter:{save} · Esc:{cancel}",
25
42
  "form.required": "wajib diisi",
26
43
  "form.invalidUrl": "URL tidak valid",
27
44
  "form.httpOnly": "harus http(s)",
@@ -36,7 +53,7 @@ export const id: Record<MsgKey, string> = {
36
53
  "pick.placeholder": "ketik untuk saring",
37
54
  "pick.noMatch": 'Tidak cocok untuk "{q}"',
38
55
  "pick.matches": "{n}/{total} cocok",
39
- "pick.hint": "ketik untuk saring · ↑↓ pilih · Enter konfirmasi · Esc kembali",
56
+ "pick.hint": "↑↓:{select} · Enter:{confirm} · Esc:{back}",
40
57
  "pick.fail": "picker gagal: {msg}",
41
58
  "pick.failOpen": "picker gagal dibuka: {msg}",
42
59
  "model.empty": "Belum ada model",
@@ -52,7 +69,7 @@ export const id: Record<MsgKey, string> = {
52
69
  "effort.saved": "Thinking: {effort} (sesi berikut)",
53
70
  "prov.title": "Penyedia",
54
71
  "prov.empty": "Belum ada penyedia",
55
- "prov.hint": "Enter:{select} a:{add} d:{delete} e:{edit} Esc:{close}",
72
+ "prov.hint": "Enter:{select} · a:{add} · d:{delete} · e:{edit} · Esc:{close}",
56
73
  "prov.addTitle": "Tambah penyedia",
57
74
  "prov.customUrl": "URL kustom",
58
75
  "prov.editTitle": 'Ubah "{id}"',
@@ -76,7 +93,9 @@ export const id: Record<MsgKey, string> = {
76
93
  "sess.listHead": "Sesi",
77
94
  "sess.listHint": " Pilih sesi untuk dilanjutkan.",
78
95
  "sess.notFound": 'Sesi "{id}" tidak ditemukan atau kosong.',
79
- "wiz.gateway": "Penyiapan Minicode — Pilih gateway",
96
+ "wiz.gateway": "Penyiapan Minicode [1/3] — Pilih gateway",
97
+ "wiz.stepUrl": "Penyiapan Minicode [2/3] — URL dasar",
98
+ "wiz.stepKey": "Penyiapan Minicode [3/3] — Kunci API",
80
99
  "wiz.title": "Penyiapan Minicode",
81
100
  "wiz.urlLabel": "URL dasar",
82
101
  "wiz.keyLabel": "Kunci API untuk {url}",
@@ -100,6 +119,7 @@ export const id: Record<MsgKey, string> = {
100
119
  "st.provider": " Penyedia: {v}",
101
120
  "st.tools": " Perkakas: {v}",
102
121
  "st.context": " Konteks: ~{v} tok (estimasi jendela)",
122
+ "st.turn": " Turn: {v} (turn terakhir saja)",
103
123
  "st.input": " Masukan: {v} (pemakaian provider)",
104
124
  "st.output": " Keluaran: {v} (pemakaian provider)",
105
125
  "st.total": " Total: {v} (kumulatif sesi)",
@@ -107,7 +127,7 @@ export const id: Record<MsgKey, string> = {
107
127
  "st.budget": " Budget: {v}{extra}",
108
128
  "st.costUnknown": " (biaya tak diketahui — model tanpa harga)",
109
129
  "help.head": "Perintah:",
110
- "help.keysLine": "Enter · Tab/Shift+Tab mode · Ctrl+R cari · PgUp/PgDn gulir · Ctrl+D keluar",
130
+ "help.keysLine": "PgUp/PgDn gulir (Shift = ½) · /help tombol = semua pintasan",
111
131
  "help.cHead": "Perintah:",
112
132
  "help.cKeys": "Tombol: Tab mode · ↑↓ riwayat · PgUp/PgDn gulir · Ctrl+R cari · Ctrl+D keluar",
113
133
  "help.cMore": " /help tombol = semua pintasan",
@@ -115,7 +135,8 @@ export const id: Record<MsgKey, string> = {
115
135
  "help.k.submit": "kirim",
116
136
  "help.k.cycleMode": "putar mode izin",
117
137
  "help.k.history": "riwayat prompt (di picker: navigasi)",
118
- "help.k.scroll": "gulir transkrip",
138
+ "help.k.scroll": "gulir transkrip (Shift+ = setengah halaman)",
139
+ "help.k.jumpTop": "lompat ke atas transkrip / kembali ke ekor (hanya prompt kosong)",
119
140
  "help.k.move": "geser kursor",
120
141
  "help.k.jump": "lompat ke awal/akhir baris",
121
142
  "help.k.delChar": "hapus karakter di kursor",
@@ -166,6 +187,10 @@ export const id: Record<MsgKey, string> = {
166
187
  "tui.didYou": " Maksudmu /{hint}?",
167
188
  "tui.tryHelp": " Coba /help.",
168
189
  "tui.expandEmpty": "(tidak ada yang dibuka — semua sudah terlihat)",
190
+ "tui.expandContent": "konten",
191
+ "tui.expandRetention":
192
+ "(konten di luar retensi — lihat .minicode/step-traces.jsonl / sesi sqlite)",
193
+ "tui.expandDurable": "persisten",
169
194
  "tui.historyEmpty": "(riwayat kosong)",
170
195
  "tui.langUnknown": "bahasa tak dikenal: {a} — pilihan: en, id",
171
196
  "tui.noTty": "Terminal tidak mendukung TUI fullscreen — interaktif butuh TTY dengan ≥10 baris.",
@@ -193,6 +218,9 @@ export const id: Record<MsgKey, string> = {
193
218
  "one.thinkMin": " + berpikir\n",
194
219
  "one.more3": "\n ... ({n} lagi)",
195
220
  "one.moreLines": "\n … ({n} baris lagi)",
221
+ "one.duration": "durasi {v} md",
222
+ "one.denyReason": "tolak:{reason}",
223
+ "one.receipt": "bukti {paths}",
196
224
  "one.contentBlocked": "\n! Filter konten diblokir\n",
197
225
  "one.step": " Langkah {i}: {calls}\n",
198
226
  "hl.moreLines": " ... ({n} baris lagi)",
@@ -46,7 +46,9 @@ export function currentLocale(): Locale {
46
46
  const env = parseLocale(process.env.MINICODE_LANG)
47
47
  if (env) return env
48
48
  if (configLocale) return configLocale
49
- const sys = process.env.LANG ?? process.env.LC_ALL ?? ""
49
+ const sys = process.env.LC_ALL || process.env.LANG || ""
50
+ // Urutan POSIX: LC_ALL mengalahkan LANG; string kosong diabaikan agar tak
51
+ // memblokir fallback (dulu `??` membuat LANG="" menang atas LC_ALL=id).
50
52
  // Prefix `id` (id_ID.UTF-8, id_ID, id): sistem berbahasa Indonesia.
51
53
  if (/^id([_.@-]|$)/i.test(sys.trim())) return "id"
52
54
  return "en"
@@ -5,6 +5,7 @@ import { createInterface } from "node:readline"
5
5
  import { t } from "../i18n/locale.ts"
6
6
  import { stripAnsi } from "../render/theme.ts"
7
7
  import { displayWidth, escapeLength, truncateToWidth } from "../render/width.ts"
8
+ import { beginInteractiveScreen } from "../runtime/statusline.ts"
8
9
  import {
9
10
  applyKey,
10
11
  buildRenderSpec,
@@ -19,10 +20,16 @@ import {
19
20
  toGraphemes,
20
21
  } from "./prompt-engine.ts"
21
22
 
22
- const HISTORY_FILE = join(homedir(), ".minicode", "history")
23
+ // Lokasi histori: MINICODE_HOME diperioritaskan (test hermetic, XDG-ish).
24
+ // Fungsi alih-alih const statis: homedir() terkunci saat module-load,
25
+ // MINICODE_HOME bisa diset sesudahnya (pola sama dengan homeDir() di
26
+ // src/lib/db-path.ts, tanpa impor lintas-lapisan — batas ui dijaga).
27
+ function historyFile(): string {
28
+ return join(process.env.MINICODE_HOME || homedir(), ".minicode", "history")
29
+ }
23
30
  const MAX_HISTORY = 1000
24
31
 
25
- export async function loadHistory(file = HISTORY_FILE): Promise<string[]> {
32
+ export async function loadHistory(file = historyFile()): Promise<string[]> {
26
33
  try {
27
34
  const content = await readFile(file, "utf8")
28
35
  const out: string[] = []
@@ -50,7 +57,7 @@ export async function loadHistory(file = HISTORY_FILE): Promise<string[]> {
50
57
  }
51
58
  }
52
59
 
53
- export async function appendHistory(entry: string, file = HISTORY_FILE): Promise<void> {
60
+ export async function appendHistory(entry: string, file = historyFile()): Promise<void> {
54
61
  const clean = entry.trim()
55
62
  if (!clean) return
56
63
  try {
@@ -58,7 +65,9 @@ export async function appendHistory(entry: string, file = HISTORY_FILE): Promise
58
65
  const filtered = existing.filter((e) => e !== clean)
59
66
  filtered.push(clean)
60
67
  const capped = filtered.slice(-MAX_HISTORY)
61
- await mkdir(join(homedir(), ".minicode"), { recursive: true }).catch(() => {})
68
+ await mkdir(join(process.env.MINICODE_HOME || homedir(), ".minicode"), {
69
+ recursive: true,
70
+ }).catch(() => {})
62
71
  await writeFile(file, `${capped.map((e) => JSON.stringify(e)).join("\n")}\n`, "utf8")
63
72
  } catch {}
64
73
  }
@@ -179,6 +188,11 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
179
188
  }
180
189
 
181
190
  return new Promise((resolve, reject) => {
191
+ // Raw mode + overlay prompt (stdout) = layar mengambil alih terminal:
192
+ // painter transient stderr (spinner setup, garis status turn) berhenti
193
+ // selama prompt hidup. Tanpa ini tick `\r\x1b[2K` dari spinner menghapus
194
+ // baris prompt — user tak melihat apa yang diketiknya.
195
+ const endScreen = beginInteractiveScreen()
182
196
  // Raw mode harus dikembalikan BAGI BAGIAN body yang error: bila renderAnsi
183
197
  // melempar (mis. lebar terminal abnormal), terminal tidak boleh tertinggal
184
198
  // dalam raw + listener lama menumpuk (dulu REPL catch{continue} lalu
@@ -210,6 +224,9 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
210
224
  // Kepemilikan = siapa yang memegang listener; melepas listener cukup.
211
225
  // Pause hanya di teardown sesi (close()) agar one-shot bisa exit.
212
226
  if (onData) process.stdin.removeListener("data", onData)
227
+ // Lepas kepemilikan layar di cleanup (semua jalur): drag raw-mode yang
228
+ // dilepas tanpa ini membuat painter diam selamanya.
229
+ endScreen()
213
230
  }
214
231
  const finish = (v: string | null) => {
215
232
  cleanup()
@@ -240,6 +257,18 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
240
257
  let prevInputRows = 1 // jumlah baris input visual frame lalu (multiline)
241
258
  let prevCursorRow = 0 // baris kursor frame lalu (0 = anchor)
242
259
  let printedW = 0 // lebar teks yang ditulis (fallback inline)
260
+ // Geometri terakhir yang dipakai render. BUKAN cache performa — tugasnya
261
+ // mendeteksi resize/reflow: hitungan baris di atas mengasumsikan grid
262
+ // pra-reflow, jadi render pertama sesudah geometri berubah WAJIB me-reset
263
+ // ketiganya (jangkar relatif tak lagi menunjuk anchor). Tanpa ini render
264
+ // dari jangkar basi mendarat di baris salah: kopi di area ketik/output
265
+ // dan hapus baris salah via clearOverlay (temuan snap kiri/kanan).
266
+ // 0 = belum pernah render (render pertama selalu "berubah" → reset ke
267
+ // nilai awal di atas, alias no-op). printedW SENGAJA tak ikut: nilainya
268
+ // konservatif (kelebihan spasi pulih frame berikut; mengosongkannya
269
+ // justru membiarkan ekor lama).
270
+ let lastGeoCols = 0
271
+ let lastGeoRows = 0
243
272
 
244
273
  const matches = (): string[] => hints(state.line)
245
274
 
@@ -342,6 +371,20 @@ export async function askLine(opts: AskLineOptions = {}): Promise<string | null>
342
371
  }
343
372
 
344
373
  const renderAnsi = () => {
374
+ // Invalidasi jangkar saat geometri berubah (lihat lastGeoCols/Rows):
375
+ // render dari hitungan basi mendarat di baris salah. Mulai dari kursor
376
+ // saat ini; render berikut menjangkar ulang dengan benar (prev* di
377
+ // bawah). Tanpa keypress tak ada render — frame basi cukup ditimpa
378
+ // render berikutnya, bukan listener baru.
379
+ const colsNow = process.stdout.columns || 80
380
+ const rowsNow = process.stdout.rows || 24
381
+ if (colsNow !== lastGeoCols || rowsNow !== lastGeoRows) {
382
+ prevRows = 0
383
+ prevInputRows = 1
384
+ prevCursorRow = 0
385
+ lastGeoCols = colsNow
386
+ lastGeoRows = rowsNow
387
+ }
345
388
  // Satu frame = satu unit sinkron: terminal menahan tampil sampai SYNC_END,
346
389
  // sehingga navigasi dropdown (atas/bawah) tak berkedip/robek. Terminal
347
390
  // tanpa dukungan mengabaikan sekuens ini (sudah dipakai clearOverlay).
@@ -733,6 +776,9 @@ export async function askSecret(
733
776
  if (!process.stdin.isTTY) return null
734
777
 
735
778
  return new Promise((resolve, reject) => {
779
+ // Layar raw-mode (sama seperti askLine): prompt API key juga menghalangi
780
+ // painter transient stderr melukis di baris yang sama.
781
+ const endScreen = beginInteractiveScreen()
736
782
  const decoder: DecoderState = createDecoderState()
737
783
  let done = false
738
784
  let onData!: (chunk: Buffer) => void
@@ -753,6 +799,7 @@ export async function askSecret(
753
799
  } catch {}
754
800
  // Tanpa pause — lihat cleanup askLine (stdin mengalir seumur proses).
755
801
  if (onData) process.stdin.removeListener("data", onData)
802
+ endScreen()
756
803
  }
757
804
  const finish = (value: string | null) => {
758
805
  cleanup()
@@ -44,8 +44,10 @@ export type PromptKey =
44
44
  | { type: "up" }
45
45
  | { type: "down" }
46
46
  // PgUp/PgDn (ESC[5~/[6~) — di TUI scroll viewport transkrip, bukan histori.
47
- | { type: "pageup" }
48
- | { type: "pagedown" }
47
+ // modifier (kode xterm, 0 = polos): 2 = shift — Shift+PgUp/PgDn = setengah
48
+ // halaman (temuan audit TUI-002).
49
+ | { type: "pageup"; modifier?: number }
50
+ | { type: "pagedown"; modifier?: number }
49
51
  | { type: "tab" }
50
52
  | { type: "enter" }
51
53
  | { type: "esc" }
@@ -85,6 +87,21 @@ export function pointLength(s: string): number {
85
87
  return toGraphemes(s).length
86
88
  }
87
89
 
90
+ /** Menghitung jumlah baris logis dalam teks prompt (berdasarkan separator \n). */
91
+ export function countLogicalLines(text: string): number {
92
+ return text.split("\n").length
93
+ }
94
+
95
+ /** Menghitung indeks baris kursor (0-based) dan offset kolom dalam baris tersebut. */
96
+ export function cursorLineIndex(text: string, cursor: number): { lineIdx: number; colIdx: number } {
97
+ const units = toGraphemes(text)
98
+ const before = units.slice(0, Math.max(0, Math.min(cursor, units.length))).join("")
99
+ const lines = before.split("\n")
100
+ const lineIdx = lines.length - 1
101
+ const colIdx = toGraphemes(lines[lineIdx] ?? "").length
102
+ return { lineIdx, colIdx }
103
+ }
104
+
88
105
  // Tanda diakritik Thai/Lao yang menempel: satu grapheme Thai bisa terdiri
89
106
  // dari konsonan + 1-2 tanda (mis. U+0E19 U+0E49 U+0E33 = satu suku kata).
90
107
  // Menghapus per grapheme (aturan emoji ZWJ) membuat satu backspace menelan
@@ -271,6 +288,8 @@ export function applyKey(
271
288
  // applyKey; engine netral (tanpa ini switch tak exhaustive → tsc merah).
272
289
  case "pageup":
273
290
  case "pagedown":
291
+ // Scroll ditangani App TUI SEBELUM applyKey (I18); engine netral
292
+ // (tanpa ini switch tak exhaustive → tsc merah).
274
293
  return { state, action: "none" }
275
294
  case "ctrl-w": {
276
295
  if (state.cursor === 0) return { state, action: "none" }
@@ -650,8 +669,31 @@ export function decodeKey(s: string, i: number): DecodedKey | null {
650
669
  if (kind === "8" && s[i + 3] === "~") return { key: { type: "end" }, width: 4 }
651
670
  if (kind === "3" && s[i + 3] === "~") return { key: { type: "delete" }, width: 4 }
652
671
  // 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 }
672
+ // Dua varian sah: polos ESC[5~ (4 byte) dan bermodifier ESC[5;<m>~
673
+ // (modifier bisa multi-digit: 2=shift, 5=ctrl, 3=alt, kombinasi >9
674
+ // seperti 23). HANYA terminator '~' yang dianggap PgUp/PgDn — response
675
+ // DSR kursor (ESC[5;34R) dsb. harus jatuh ke catch-all esc di bawah;
676
+ // tanpa guard ini, response DSR baris-5/6 dibajak jadi pageup + residu
677
+ // char bocor ke prompt (bug ditemukan audit typing, probe ESC[5;34R).
678
+ // Width dihitung dari posisi terminator — width tetap 5 membuat sisa
679
+ // '~' ter-decode jadi keystroke char (prompt tiba-tiba berisi '~').
680
+ if (kind === "5" || kind === "6") {
681
+ const type = kind === "5" ? "pageup" : "pagedown"
682
+ if (s[i + 3] === "~") return { key: { type, modifier: 0 }, width: 4 }
683
+ if (s[i + 3] === ";") {
684
+ let j = i + 4
685
+ let ch: string | undefined = s[j]
686
+ while (ch !== undefined && ch >= "0" && ch <= "9") {
687
+ j++
688
+ ch = s[j]
689
+ }
690
+ if (ch === "~") {
691
+ const mod = Number.parseInt(s.slice(i + 4, j), 10) || 0
692
+ return { key: { type, modifier: mod }, width: j + 1 - i }
693
+ }
694
+ }
695
+ // selain itu (ESC[5;34R, ESC[5x, …) → catch-all esc di bawah
696
+ }
655
697
  // Shift+Tab (backtab) ESC [ Z — dipakai REPL linier untuk cycle mode.
656
698
  // Tanpa cabang eksplisit ini ia jatuh ke catch-all "esc" di bawah,
657
699
  // sehingga tipe "shift-tab" tidak pernah dihasilkan decodeKeys.
@@ -15,7 +15,7 @@ export type CollapseSection = "thinking" | "tool" | "answer"
15
15
  let activeSection: CollapseSection | null = null
16
16
 
17
17
  // Buffer konten yang dikecilkan pada turn terakhir — dibuka via /expand.
18
- export interface BufferedSection {
18
+ export interface CollapsedSectionView {
19
19
  label: string
20
20
  text: string
21
21
  /** Stream asal konten (kontrak Unix dipertahankan saat /expand mencetak). */
@@ -23,7 +23,7 @@ export interface BufferedSection {
23
23
  }
24
24
  const MAX_SECTION_CHARS = 200_000
25
25
  const MAX_BUFFER_TOTAL = 500_000
26
- const bufferedSections: BufferedSection[] = []
26
+ const collapsedSectionViews: CollapsedSectionView[] = []
27
27
 
28
28
  export const collapse = {
29
29
  /** Section yang sedang aktif — keputusan tombol + / - saat turn berjalan. */
@@ -57,10 +57,10 @@ export function setSectionMinimized(section: CollapseSection, next?: boolean): b
57
57
  }
58
58
 
59
59
  /** Simpan isi section yang dikecilkan (cap per-entry + total). */
60
- export function bufferSection(
60
+ export function rememberCollapsedSection(
61
61
  label: string,
62
62
  text: string,
63
- stream: BufferedSection["stream"] = "stderr",
63
+ stream: CollapsedSectionView["stream"] = "stderr",
64
64
  ): void {
65
65
  if (!text) return
66
66
  // Cap jangan belah surrogate pair (U+FFFD di /expand) dan jangan sisakan
@@ -69,23 +69,23 @@ export function bufferSection(
69
69
  const last = cut.charCodeAt(cut.length - 1)
70
70
  if (cut.length > 0 && last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1)
71
71
  cut = splitTrailingEscape(cut).head
72
- bufferedSections.push({ label, text: cut, stream })
72
+ collapsedSectionViews.push({ label, text: cut, stream })
73
73
  // Buang yang tertua sampai total dalam budget — terbaru selalu dipertahankan.
74
74
  let total = 0
75
- let keepFrom = bufferedSections.length
76
- for (let i = bufferedSections.length - 1; i >= 0; i--) {
77
- total += bufferedSections[i]!.text.length
75
+ let keepFrom = collapsedSectionViews.length
76
+ for (let i = collapsedSectionViews.length - 1; i >= 0; i--) {
77
+ total += collapsedSectionViews[i]!.text.length
78
78
  if (total > MAX_BUFFER_TOTAL) break
79
79
  keepFrom = i
80
80
  }
81
- if (keepFrom > 0) bufferedSections.splice(0, keepFrom)
81
+ if (keepFrom > 0) collapsedSectionViews.splice(0, keepFrom)
82
82
  }
83
83
 
84
- export function resetBufferedSections(): void {
85
- bufferedSections.length = 0
84
+ export function clearCollapsedSections(): void {
85
+ collapsedSectionViews.length = 0
86
86
  }
87
87
 
88
88
  /** Konten section yang dikecilkan pada turn terakhir (untuk /expand). */
89
- export function getBufferedSections(): BufferedSection[] {
90
- return bufferedSections
89
+ export function collapsedSectionsSnapshot(): CollapsedSectionView[] {
90
+ return [...collapsedSectionViews]
91
91
  }
@@ -1,4 +1,5 @@
1
1
  // Diff renderer - Ubuntu Server style: indentasi + warna, tanpa border.
2
+ import { sanitizeAnsi, sanitizeAnsiLine } from "./sanitize.ts"
2
3
  import { c } from "./theme.ts"
3
4
  import { truncateToWidth } from "./width.ts"
4
5
 
@@ -107,7 +108,11 @@ export function renderDiffCard(
107
108
  newText: string,
108
109
  opts: { maxLines?: number; width?: number } = {},
109
110
  ): string {
110
- const diff = computeLineDiff(oldText, newText)
111
+ // Path & isi dari tool/model/berkas = tak-terpercaya: sanitasi sebelum
112
+ // dirender. Tanpa ini `\n` di path menjadi baris diff palsu dan `ESC[2J`
113
+ // lolos via `cut` (truncate menyalin escape apa pun sebelum F-04).
114
+ const safePath = sanitizeAnsiLine(filePath)
115
+ const diff = computeLineDiff(sanitizeAnsi(oldText), sanitizeAnsi(newText))
111
116
  const changes = diff.filter((d) => d.type !== "context")
112
117
  if (changes.length === 0) return c.muted(" (no changes)")
113
118
  // Pasangan del/add untuk sorot kata: kelompokkan run perubahan beruntun,
@@ -146,7 +151,7 @@ export function renderDiffCard(
146
151
  const width = opts.width ?? (process.stdout.columns || 80)
147
152
  const cut = (s: string) => truncateToWidth(s, Math.max(8, width - 1))
148
153
 
149
- const lines: string[] = [c.accent(c.bold(cut(` ${filePath}`)))]
154
+ const lines: string[] = [c.accent(c.bold(cut(` ${safePath}`)))]
150
155
  // collect indices of changes plus 1 context line before/after
151
156
  const include = new Set<number>()
152
157
  diff.forEach((d, i) => {
@@ -3,6 +3,7 @@
3
3
  import type { UiToolCallRef } from "../contract.ts"
4
4
  import { formatFriendly, friendlyFromCategory } from "./errors.ts"
5
5
  import { formatUsd } from "./money.ts"
6
+ import { sanitizeAnsiLine } from "./sanitize.ts"
6
7
 
7
8
  /**
8
9
  * Potong per code point (bukan UTF-16 unit): slice mentah membelah surrogate
@@ -15,22 +16,29 @@ function safeSlice(s: string, n: number): string {
15
16
  }
16
17
 
17
18
  export function formatArgsPreview(args: unknown): string {
19
+ // Nilai arg berasal dari model/MCP (tak-terpercaya) dan tampil di baris
20
+ // status satu-baris: sanitasi agar `\n`/ANSI tak memecah baris/menyuntik.
18
21
  try {
19
22
  const a = args as Record<string, unknown>
20
- if (a.path) return String(a.path)
21
- if (a.command) return safeSlice(String(a.command), 60)
22
- if (a.cmd) return safeSlice(String(a.cmd), 60)
23
- if (a.pattern) return String(a.pattern)
24
- if (a.query) return String(a.query)
25
- if (a.prompt) return safeSlice(String(a.prompt), 40)
26
- return safeSlice(JSON.stringify(a), 40)
23
+ if (a.path) return sanitizeAnsiLine(String(a.path))
24
+ if (a.command) return safeSlice(sanitizeAnsiLine(String(a.command)), 60)
25
+ if (a.cmd) return safeSlice(sanitizeAnsiLine(String(a.cmd)), 60)
26
+ if (a.pattern) return sanitizeAnsiLine(String(a.pattern))
27
+ if (a.query) return sanitizeAnsiLine(String(a.query))
28
+ if (a.prompt) return safeSlice(sanitizeAnsiLine(String(a.prompt)), 40)
29
+ return safeSlice(sanitizeAnsiLine(JSON.stringify(a)), 40)
27
30
  } catch {
28
31
  return "[args]"
29
32
  }
30
33
  }
31
34
 
32
35
  export function formatStepCalls(calls: readonly UiToolCallRef[], argCap = 35): string {
33
- return calls.map((tc) => `${tc.name}(${safeSlice(JSON.stringify(tc.args), argCap)})`).join(", ")
36
+ return calls
37
+ .map(
38
+ (tc) =>
39
+ `${sanitizeAnsiLine(tc.name)}(${safeSlice(sanitizeAnsiLine(JSON.stringify(tc.args)), argCap)})`,
40
+ )
41
+ .join(", ")
34
42
  }
35
43
 
36
44
  export function formatUsage(parts: {
@@ -1,4 +1,5 @@
1
1
  import { t } from "../i18n/locale.ts"
2
+ import { sanitizeAnsi, sanitizeAnsiLine } from "./sanitize.ts"
2
3
  import { c } from "./theme.ts"
3
4
 
4
5
  const TS_KEYWORDS = new Set([
@@ -121,8 +122,11 @@ const SH_KEYWORDS = new Set([
121
122
  ])
122
123
 
123
124
  export function highlightCode(code: string, lang: string = ""): string {
124
- const language = lang.trim().toLowerCase()
125
- const lines = code.split("\n")
125
+ // Kode adalah input tak-terpercaya (model/tool/berkas): sanitasi DULU agar
126
+ // tokenizer tak membelah SGR (merusak warna sah) dan sekuens non-SGR tak
127
+ // lolos ke terminal. sanitizeAnsi membuang \r sehingga CR-overwrite mati.
128
+ const language = sanitizeAnsiLine(lang).trim().toLowerCase()
129
+ const lines = sanitizeAnsi(code).split("\n")
126
130
 
127
131
  return lines
128
132
  .map((line) => {
@@ -284,7 +288,7 @@ export function formatCodeBlock(code: string, lang: string = "", maxLines?: numb
284
288
  ? [...lines.slice(0, maxLines), c.dim(t("hl.moreLines", { n: lines.length - maxLines }))]
285
289
  : lines
286
290
 
287
- const header = lang ? ` ${lang.toLowerCase()} ` : " code "
291
+ const header = sanitizeAnsiLine(lang) ? ` ${sanitizeAnsiLine(lang).toLowerCase()} ` : " code "
288
292
  const topBorder = c.muted(`── ${header.trim()}`)
289
293
  const bottomBorder = c.muted("──")
290
294
 
@@ -3,6 +3,7 @@
3
3
  // Inline: **bold**, *italic*, `code`, ~~strike~~, [text](url) -> teks accent (no underline).
4
4
 
5
5
  import { highlightCode } from "./highlight.ts"
6
+ import { sanitizeAnsi } from "./sanitize.ts"
6
7
  import { c } from "./theme.ts"
7
8
 
8
9
  export interface FenceMatch {
@@ -59,7 +60,10 @@ export function renderInline(text: string): string {
59
60
  }
60
61
 
61
62
  export function decorateMarkdown(text: string): string {
62
- const lines = text.split("\n")
63
+ // Teks model tak-terpercaya: sanitasi SEKALI di hulu agar fence-content,
64
+ // renderInline, dan highlight tak pernah melihat escape mentah. Urutan ini
65
+ // juga melindungi placeholder `\u0000` (sanitize membuang null model).
66
+ const lines = sanitizeAnsi(text).split("\n")
63
67
  const out: string[] = []
64
68
  let inFence = false
65
69
  let fenceLang = ""
@@ -65,6 +65,30 @@ export function sanitizeAnsi(s: string): string {
65
65
  i += 1
66
66
  continue
67
67
  }
68
+ // Kontrol C1 (0x80–0x9F): di terminal modern 0x9B bertindak sebagai CSI —
69
+ // tanpa ini model bisa menyelundupkan sekuens kontrol tanpa byte ESC.
70
+ if (code >= 0x80 && code <= 0x9f) {
71
+ i += 1
72
+ continue
73
+ }
74
+ // Format tak-terlihat yang mengubah tampilan tanpa menempati kolom:
75
+ // bidi override/isolate (202A–202E, 2066–2069) membalik urutan tampil
76
+ // path/perintah; soft hyphen (00AD) dan word joiner/invisible (2060–2064)
77
+ // menyembunyikan teks. ZWJ/ZWNJ (200D/200C) dan ZWSP (200B) SENGAJA
78
+ // dipertahankan — dibutuhkan emoji ZWJ-sequence dan sebagian skrip;
79
+ // risikonya ditutup hitungan lebar-nol di width.ts.
80
+ // Tag E0020–E007F astral (surrogate pair) dicek via codePointAt agar
81
+ // kedua unit ikut dibuang — charCodeAt hanya melihat separuhnya.
82
+ const cp = s.codePointAt(i)!
83
+ if (
84
+ code === 0xad ||
85
+ (code >= 0x202a && code <= 0x202e) ||
86
+ (code >= 0x2060 && code <= 0x2069) ||
87
+ (cp >= 0xe0020 && cp <= 0xe007f)
88
+ ) {
89
+ i += cp > 0xffff ? 2 : 1
90
+ continue
91
+ }
68
92
  out += ch
69
93
  i += 1
70
94
  }
@@ -175,9 +199,12 @@ export function stripSgr(s: string): string {
175
199
  * Satu pintu kebijakan ANSI teks tak-terpercaya: TTY → SGR dipertahankan
176
200
  * (renderer mewarnai); non-TTY → semua ANSI dibuang agar pipe/CI
177
201
  * deterministik. Cerminan colorLevel() di theme.ts yang mengacu
178
- * stdout.isTTY — satu aturan untuk semua stream.
202
+ * stdout.isTTY — satu aturan untuk semua stream. NO_COLOR menang di kedua
203
+ * jalur (aturan aksesibilitas yang sama dengan theme.noColorEnv).
179
204
  */
180
205
  export function cleanUntrusted(s: string, stdoutTty: boolean): string {
181
206
  const clean = sanitizeAnsi(s)
182
- return stdoutTty ? clean : stripSgr(clean)
207
+ if (!stdoutTty) return stripSgr(clean)
208
+ if (process.env.NO_COLOR != null && process.env.NO_COLOR !== "0") return stripSgr(clean)
209
+ return clean
183
210
  }
@@ -35,6 +35,9 @@ export function renderTable(columns: ColumnDef[], data: Record<string, unknown>[
35
35
  if (data.length === 0) return c.muted("(no entries)")
36
36
 
37
37
  const cells = data.map((row) => columns.map((col) => sanitizeCell(row[col.key])))
38
+ // Header bisa berasal dari frontmatter/config (tak-terpercaya): sanitasi
39
+ // seperti sel agar `\n`/ANSI tak memecah baris vertikal atau lolos.
40
+ const heads = columns.map((col) => sanitizeCell(col.header))
38
41
 
39
42
  const termW = getTerminalWidth()
40
43
  // Terminal sangat sempit + banyak kolom: budget per kolom (~10) membuat
@@ -43,12 +46,12 @@ export function renderTable(columns: ColumnDef[], data: Record<string, unknown>[
43
46
  return data
44
47
  .map((row) =>
45
48
  columns
46
- .map((col) => {
49
+ .map((col, ci) => {
47
50
  // Nilai dipotong dari sisa budget SETELAH header: tanpa ini
48
51
  // header+": "+value pasti > termW di terminal sempit (jalur
49
52
  // penyelamat yang malah wrap sendiri).
50
- const budget = Math.max(4, termW - displayWidth(col.header) - 2)
51
- return `${c.bold(col.header)}: ${truncateToWidth(sanitizeCell(row[col.key]), budget, ELLIPSIS)}`
53
+ const budget = Math.max(4, termW - displayWidth(heads[ci] ?? "") - 2)
54
+ return `${c.bold(heads[ci] ?? "")}: ${truncateToWidth(sanitizeCell(row[col.key]), budget, ELLIPSIS)}`
52
55
  })
53
56
  .join("\n"),
54
57
  )
@@ -62,7 +65,7 @@ export function renderTable(columns: ColumnDef[], data: Record<string, unknown>[
62
65
  const widths = columns.map((col, i) => {
63
66
  // Nilai negatif/NaN dari pemanggil tidak boleh membuat "".repeat() melempar.
64
67
  if (col.width != null && Number.isFinite(col.width)) return Math.max(0, Math.trunc(col.width))
65
- let max = displayWidth(col.header)
68
+ let max = displayWidth(heads[i] ?? "")
66
69
  for (const row of cells) {
67
70
  const w = displayWidth(row[i] ?? "")
68
71
  if (w > max) max = w
@@ -76,7 +79,7 @@ export function renderTable(columns: ColumnDef[], data: Record<string, unknown>[
76
79
  padToWidth(truncateToWidth(text, width, ELLIPSIS), width, align)
77
80
 
78
81
  const header = columns
79
- .map((col, i) => ` ${c.bold(c.accent(cell(col.header, widths[i]!, col.align)))} `)
82
+ .map((col, i) => ` ${c.bold(c.accent(cell(heads[i] ?? "", widths[i]!, col.align)))} `)
80
83
  .join(" ")
81
84
 
82
85
  // Separator (─ antara header dan body). Lebarnya harus SAMA dengan baris
@@ -1,3 +1,4 @@
1
+ import { sanitizeAnsiLine } from "./sanitize.ts"
1
2
  import { displayWidth, truncateToWidth } from "./width.ts"
2
3
 
3
4
  // Semantic color system - Ubuntu Server style.
@@ -280,6 +281,12 @@ export const glyphs = {
280
281
  get cross() {
281
282
  return supportsUtf8() ? "✗" : "[FAIL]"
282
283
  },
284
+ get denied() {
285
+ return supportsUtf8() ? "⊘" : "[DENY]"
286
+ },
287
+ get circle() {
288
+ return supportsUtf8() ? "○" : "[CANCEL]"
289
+ },
283
290
  get arrow() {
284
291
  return supportsUtf8() ? "›" : ">"
285
292
  },
@@ -312,12 +319,15 @@ export const glyphs = {
312
319
  // ── Section separator ──
313
320
  export function section(title: string): string {
314
321
  const width = getTerminalWidth()
322
+ // Judul bisa berasal dari model/berkas: sanitasi satu-baris agar `\n`/ANSI
323
+ // tak memecah separator menjadi multi-baris atau menyuntik kontrol.
324
+ const clean = sanitizeAnsiLine(title)
315
325
  // Label lebih panjang dari terminal (judul CJK/emoji panjang): potong dulu
316
326
  // per kolom — tanpa ini dashes jatuh ke 4 dan total label+4 tetap meluap.
317
327
  const label =
318
- displayWidth(` ${title} `) > Math.max(4, width - 4)
319
- ? truncateToWidth(` ${title} `, Math.max(4, width - 4), "…")
320
- : ` ${title} `
328
+ displayWidth(` ${clean} `) > Math.max(4, width - 4)
329
+ ? truncateToWidth(` ${clean} `, Math.max(4, width - 4), "…")
330
+ : ` ${clean} `
321
331
  // Lebar pemisah dihitung per KOLOM terminal: CJK/emoji bisa 2 kolom.
322
332
  // Clamp agar garis tak memicu wrap sendiri di terminal sempit.
323
333
  const dashes = Math.min(Math.max(4, width - displayWidth(label)), Math.max(4, width - 4))
@@ -336,7 +346,11 @@ export const ESC = String.fromCharCode(27)
336
346
  // ESC[?25l, ESC[?2026h, ESC[?1049h dipakai untuk kursor/sync/alternate-screen.
337
347
  // Tanpa itu sekuens kontrol lolos ke teks yang seharusnya sudah bersih —
338
348
  // terlihat saat output ditangkap/disanitasi untuk tampilan.
339
- export const ANSI_PATTERN = `${ESC}(?:\\[[0-9;?<=>]*[a-zA-Z]|\\[[0-9;?<=>]*|\\][^${ESC}\\u0007]*(?:\\u0007|${ESC}\\\\)|\\[P_\\^X][^${ESC}\\u0007]*(?:\\u0007|${ESC}\\\\)|[()#][0-9A-Za-z]|[0-9A-Za-z])`
349
+ // Final CSI = 0x40–0x7E (`[@-~]`), bukan hanya huruf — tanpanya `ESC[3~`
350
+ // menyisakan `~` dan merusak hitungan kolom. DCS/APC/PM/SOS = `ESC` + satu
351
+ // huruf `P/_/^/X` (BUKAN `ESC[` + kelas karakter) — pola lama `\[P_\^X]`
352
+ // hanya cocok untuk `ESC[P`/`ESC[_` dst. sehingga payload DCS bocor.
353
+ export const ANSI_PATTERN = `${ESC}(?:\\[[0-9;?<=>]*[@-~]|\\[[0-9;?<=>]*|\\][^${ESC}\\u0007]*(?:\\u0007|${ESC}\\\\)|(?:P|_|\\^|X)[^${ESC}\\u0007]*(?:\\u0007|${ESC}\\\\)|[()#][0-~]|[0-~])`
340
354
 
341
355
  export function stripAnsi(str: string): string {
342
356
  // regex baru per panggilan: aman dari lastIndex bersama antar pemanggil