minicode-ai 0.9.29 → 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 (47) hide show
  1. package/CHANGELOG.md +23 -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/package.json +1 -1
  12. package/src/app/rag-layer.ts +7 -2
  13. package/src/config.ts +30 -1
  14. package/src/policy/bash-guard.ts +64 -8
  15. package/src/policy/update-check.ts +4 -1
  16. package/src/tools/bash.ts +8 -0
  17. package/src/tools/task.ts +6 -1
  18. package/src/tools/web_fetch.ts +11 -2
  19. package/src/tools/web_search.ts +4 -1
  20. package/src/ui/approval/prompt.ts +84 -18
  21. package/src/ui/assistant/simple.ts +55 -22
  22. package/src/ui/assistant/turn-status.ts +16 -7
  23. package/src/ui/footer.ts +14 -12
  24. package/src/ui/i18n/en.ts +225 -0
  25. package/src/ui/i18n/id.ts +227 -0
  26. package/src/ui/i18n/locale.ts +66 -0
  27. package/src/ui/input/input.ts +138 -77
  28. package/src/ui/input/prompt-engine.ts +97 -4
  29. package/src/ui/render/collapse.ts +8 -1
  30. package/src/ui/render/errors.ts +75 -50
  31. package/src/ui/render/format.ts +15 -5
  32. package/src/ui/render/highlight.ts +5 -2
  33. package/src/ui/render/table.ts +7 -4
  34. package/src/ui/render/theme.ts +8 -3
  35. package/src/ui/render/width.ts +17 -9
  36. package/src/ui/runtime/screen.ts +197 -0
  37. package/src/ui/screens/dialog.ts +174 -0
  38. package/src/ui/screens/form.ts +459 -0
  39. package/src/ui/screens/model-manager.ts +274 -127
  40. package/src/ui/screens/picker.ts +229 -98
  41. package/src/ui/screens/provider-manager.ts +371 -164
  42. package/src/ui/screens/wizard.ts +149 -102
  43. package/src/ui/tui/app.ts +745 -0
  44. package/src/ui/tui/transcript.ts +271 -0
  45. package/cli/repl.ts +0 -740
  46. package/src/ui/runtime/chrome.ts +0 -369
  47. package/src/ui/screens/overlay.ts +0 -61
@@ -1,10 +1,19 @@
1
- // View model registry — pola overlay transient yang konsisten dengan picker/
2
- // provider-manager. Tetap shell-like: overlay sementara, hasil aksi tetap inline.
3
- import { askLine } from "../input/input.ts"
4
- import { createDecoderState, type DecoderState, decodeKeysStream } from "../input/prompt-engine.ts"
5
- import { c, glyphs } from "../render/theme.ts"
6
- import { padToWidth, truncateToWidth } from "../render/width.ts"
7
- import { clearTransientOverlay, renderTransientOverlay } from "./overlay.ts"
1
+ // View model registry — pola popup komposit yang konsisten dengan picker/// provider-manager. Tetap shell-like: overlay sementara, hasil aksi tetap inline.
2
+
3
+ import { t } from "../i18n/locale.ts"
4
+ import {
5
+ createDecoderState,
6
+ createKeyStreamPump,
7
+ type DecodedKey,
8
+ type DecoderState,
9
+ toGraphemes,
10
+ } from "../input/prompt-engine.ts"
11
+ import { sanitizeAnsiLine } from "../render/sanitize.ts"
12
+ import { c, glyphs, stripAnsi } from "../render/theme.ts"
13
+ import { displayWidth, padToWidth, truncateToWidth } from "../render/width.ts"
14
+ import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
15
+ import { boxLeftPad, dialogBox } from "./dialog.ts"
16
+ import { runForm } from "./form.ts"
8
17
  import { runPicker } from "./picker.ts"
9
18
 
10
19
  const DIM = "\x1b[2m",
@@ -23,9 +32,8 @@ export interface ModelManagerViewOptions {
23
32
  /** Filter awal (dari `/model <cari>`) — null/"" = tanpa filter. */
24
33
  initialFilter?: string
25
34
  onSelect(id: string): void | Promise<void>
26
- /** Ambil baris terbaru setelah mutasi (atau saat add batal). */
35
+ /** Ambil baris terbaru setelah mutasi. */
27
36
  loadRows(): Promise<ModelRow[]>
28
- onAdd(providerId: string, model: string): Promise<ModelRow[]>
29
37
  onDelete(id: string): Promise<ModelRow[]>
30
38
  onSetEffort?(id: string, effort: "default" | "low" | "medium" | "high"): Promise<ModelRow[]>
31
39
  /**
@@ -35,6 +43,11 @@ export interface ModelManagerViewOptions {
35
43
  * injeksi): semua opsi, perilaku lama.
36
44
  */
37
45
  getEfforts?: (id: string) => ("default" | "low" | "medium" | "high")[]
46
+ /**
47
+ * Batas waktu aksi jaringan (ms) — DI untuk test (default 60 dtk).
48
+ * Tanpa ini test watchdog menunggu semenit.
49
+ */
50
+ actionTimeoutMs?: number
38
51
  }
39
52
 
40
53
  /** Saring baris berdasarkan substring id, case-insensitive. Murni agar bisa diuji. */
@@ -44,12 +57,14 @@ export function filterModelRows(rows: ModelRow[], q: string): ModelRow[] {
44
57
  return rows.filter((r) => r.id.toLowerCase().includes(needle))
45
58
  }
46
59
 
60
+ /** Lebar kotak dialog /model: TETAP 64 kolom (keputusan rasa: geometri stabil,
61
+ * tak pernah melompat mengikuti konten). Satu sumber untuk width() dan
62
+ * maxWidth dialogBox — keduanya HARUS sepakat agar label tak terpotong ulang. */
63
+ const MODAL_BOX_W = 64
64
+
47
65
  export async function runModelManagerView(opts: ModelManagerViewOptions): Promise<void> {
48
- let rows = opts.initialRows
49
- // Mode cari: ketikan apa pun langsung jadi query (termasuk a/d — tidak ada
50
- // lagi shortcut huruf agar mengetik selalu menyaring di semua OS). Tambah =
51
- // Ctrl+N, hapus = tombol Del. Esc keluar dari mode cari, bukan tutup
52
- // manager. null = tak memfilter.
66
+ let rows = opts.initialRows // Mode cari: ketikan apa pun langsung jadi query. Hapus = tombol Del.
67
+ // Esc keluar dari mode cari, bukan tutup manager. null = tak memfilter.
53
68
  let filter: string | null = null
54
69
  const initial = opts.initialFilter?.trim()
55
70
  if (initial) filter = initial
@@ -63,15 +78,26 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
63
78
  )
64
79
  clampSel()
65
80
  let scroll = 0
66
- let prevRows = 0
81
+ // Struk aksi transient: hasil delete/Canceled/error tampil sebagai baris
82
+ // redup DALAM popup, bukan console.log ke scrollback. Dibersihkan tiap
83
+ // keypress baru — terlihat sampai tombol berikut ditekan.
84
+ let notice: string | null = null
67
85
 
68
86
  return new Promise<void>((resolve) => {
69
- const visibleRows = () => Math.max(1, Math.min((process.stdout.rows || 24) - 4, 14))
70
- // Lantai lebar tak boleh melebihi terminal (floor 12 lama membungkus di
71
- // kolom ≤13) — sama seperti picker/provider-manager.
72
- const width = () => Math.max(8, (process.stdout.columns || 80) - 2)
87
+ const visibleRows = () => {
88
+ const rows = process.stdout.rows || 24
89
+ // Popup: jatah dialog rows−4 sudah termasuk baris counter/notice, jadi
90
+ // item dibatasi rows−5 (lihat picker.ts). Dialog mungil /model: maks 8.
91
+ return Math.max(1, Math.min(rows - 5, 8))
92
+ }
93
+ // Lantai lebar tak boleh melebihi terminal. Lebar konten = lebar kotak
94
+ // tetap dikurangi chrome dialog (border+padding = 4) agar sepakat dengan
95
+ // dialogBox (tanpa potong ulang).
96
+ const width = () => Math.max(8, Math.min((process.stdout.columns || 80) - 4, MODAL_BOX_W - 4))
73
97
 
74
- const buildLines = (): string[] => {
98
+ // Isi MINIMAL dialog /model (tanpa judul/footer/hitungan/penanda —
99
+ // seleksi murni warna). Search selalu tampil, daftar tanpa `›`.
100
+ const bodyLinesModal = (): string[] => {
75
101
  const list = viewRows()
76
102
  const v = visibleRows()
77
103
  if (sel < scroll) scroll = sel
@@ -80,55 +106,83 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
80
106
  const cut = (s: string) => truncateToWidth(s, w)
81
107
  const view = list.slice(scroll, scroll + v)
82
108
  const lines: string[] = []
83
- lines.push(
84
- cut(
85
- `${DIM}─ ${c.accent(c.bold("Models"))}${rows.length ? ` ${DIM}(${rows.length})${RESTORE}` : ""} ${DIM}─${RESTORE}`,
86
- ),
87
- )
88
- if (filter != null) {
89
- lines.push(
90
- cut(
91
- `${DIM} Filter:${RESTORE} ${filter}█ ${DIM}(${list.length}/${rows.length})${RESTORE}`,
92
- ),
93
- )
94
- }
109
+ lines.push(cut(`${DIM}>${RESTORE} ${c.brightCyan(sanitizeAnsiLine(filter ?? ""))}█`))
95
110
  if (!list.length) {
96
111
  lines.push(
97
- cut(`${DIM} ${filter == null ? "No models configured" : "No models match"}${RESTORE}`),
112
+ cut(`${DIM} ${filter == null ? t("model.empty") : t("model.noMatch")}${RESTORE}`),
98
113
  )
99
114
  } else {
100
115
  for (let i = 0; i < view.length; i++) {
101
116
  const row = view[i]!
102
117
  const picked = i === sel - scroll
103
- // Badge effort hanya bila non-default — default adalah kondisi normal
104
- // yang tak perlu diumumkan tiap baris (minimalis).
105
118
  const badge = row.effort && row.effort !== "default" ? ` [${row.effort}]` : ""
106
119
  const label = truncateToWidth(
107
- `${padToWidth(`${row.id}${badge}`, w - 14)}${row.active ? " active" : ""}`,
120
+ `${padToWidth(`${sanitizeAnsiLine(row.id)}${badge}`, w - 14)}${row.active ? ` (${t("common.active")})` : ""}`,
108
121
  w - 4,
109
122
  )
110
- if (picked) lines.push(` ${c.accent("›")} ${c.accent(c.bold(label))}${RESTORE}`)
111
- else lines.push(` ${DIM}${label}${RESTORE}`)
112
- }
113
- if (list.length > scroll + v) {
114
- lines.push(cut(`${DIM}… ${c.accent(String(list.length - scroll - v))} more${RESTORE}`))
123
+ if (picked) lines.push(` ${c.accent(c.bold(label))}${RESTORE}`)
124
+ else lines.push(` ${DIM}${label}${RESTORE}`)
115
125
  }
116
126
  }
117
- lines.push("")
118
- lines.push(
119
- cut(
120
- `${DIM}Enter:${RESTORE}${c.accent("select+thinking")} ${DIM}Ctrl+N:${RESTORE}${c.accent("add")} ${DIM}Del:${RESTORE}${c.accent("delete")} ${DIM}ketik:${RESTORE}${c.accent("cari")} ${DIM}Esc:${RESTORE}${c.accent(filter == null ? "close" : "clear filter")}${RESTORE}`,
121
- ),
122
- )
127
+ if (notice) lines.push(cut(`${DIM}${sanitizeAnsiLine(notice)}${RESTORE}`))
123
128
  return lines
124
129
  }
125
130
 
126
131
  const render = () => {
127
- prevRows = renderTransientOverlay(buildLines(), prevRows)
132
+ // Popup komposit: HANYA region kotak (tanpa clear) di atas transkrip
133
+ // App. Lebar TETAP 64 (min=max) — tak pernah melompat mengikuti konten.
134
+ const box = dialogBox(
135
+ {
136
+ title: t("model.title"),
137
+ body: bodyLinesModal(),
138
+ footer: modelHint(),
139
+ minWidth: MODAL_BOX_W,
140
+ maxWidth: MODAL_BOX_W,
141
+ maxHeight: 14,
142
+ },
143
+ screen.cols,
144
+ screen.rows,
145
+ )
146
+ screen.paintRegion(box.lines, box.topRow)
147
+ // Parkir kursor di posisi ketik query (tepat sebelum penanda █ di
148
+ // baris search body[0]): kolom = padding + border + spasi + "> " +
149
+ // lebar filter + 1. Parkir di ujung baris (padding void) terlihat
150
+ // rusak — kursor melayang jauh dari █.
151
+ try {
152
+ const li = Math.min(box.lines.length - 1, box.bodyTop)
153
+ const row = box.topRow + li
154
+ const leftPad = boxLeftPad(stripAnsi(box.lines[li] ?? ""))
155
+ const col = Math.max(
156
+ 1,
157
+ Math.min(
158
+ screen.cols || 80,
159
+ leftPad + 2 + 2 + displayWidth(sanitizeAnsiLine(filter ?? "")) + 1,
160
+ ),
161
+ )
162
+ process.stdout.write(`\x1b[${row};${col}H\x1b[?25h`)
163
+ } catch {}
164
+ }
165
+
166
+ /** Hint footer /model: Del/type-to-filter jadi discoverable (dulu tanpa
167
+ * footer — user baru tak tahu cara hapus/saring). */
168
+ const modelHint = (): string =>
169
+ `${c.accent(t("model.typeFilter"))} · Del:${c.accent(t("verb.delete"))} · Enter:${c.accent(t("verb.select"))} · Esc:${c.accent(t("verb.close"))}`
170
+
171
+ // Popup butuh layar mampu; selain itu tolak BERSUARA + batal.
172
+ const screen: AltScreen = openAltScreen()
173
+ const useModal = screen.ok && (process.stdout.rows || 24) >= 10
174
+ if (!useModal) {
175
+ try {
176
+ console.log(`⚠ ${t("gate.tuiModel")}`)
177
+ } catch {}
178
+ resolve()
179
+ return
128
180
  }
129
181
 
130
182
  let busy = false
131
183
  let done = false
184
+ /** Listener stdin terpasang? Menjaga resume() idempoten (anti-ganda). */
185
+ let attached = false
132
186
  // Bun Windows: raw-mode yang ditahan tanpa input rawan digenggam selamanya
133
187
  // (lihat idleTimer 90 dtk di picker.ts — segfault setelah 133 dtk idle).
134
188
  // Manager ini sebelumnya TANPA idleTimer: bila stdin 'data' tak pernah
@@ -145,9 +199,8 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
145
199
 
146
200
  const suspend = () => {
147
201
  clearIdle()
148
- prevRows = clearTransientOverlay(prevRows)
202
+ attached = false
149
203
  process.stdout.write("\x1b[0m\x1b[?25h")
150
- // TIDAK menulis \r\n — clearTransientOverlay sudah kembali ke anchor.
151
204
  // TANPA pause — stdin mengalir seumur proses (lihat cleanup askLine).
152
205
  try {
153
206
  process.stdin.setRawMode(false)
@@ -162,18 +215,24 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
162
215
 
163
216
  const resume = () => {
164
217
  if (done) return
165
- process.stdin.setMaxListeners(0)
166
- try {
167
- process.stdin.setRawMode(true)
168
- } catch {
169
- // Raw-mode gagal (ConPTY Windows) = tak bisa baca tombol; lebih baik
170
- // tutup jujur daripada gantung dengan layar mati.
171
- finish()
172
- return
218
+ // Idempoten: tanpa garda, resume ganda (mis. watchdog timeout lalu
219
+ // aksi telat selesai) memasang listener stdin DUA kali → tiap tombol
220
+ // diproses ganda. Gagal-di-kode-lama.
221
+ if (!attached) {
222
+ process.stdin.setMaxListeners(0)
223
+ try {
224
+ process.stdin.setRawMode(true)
225
+ } catch {
226
+ // Raw-mode gagal (ConPTY Windows) = tak bisa baca tombol; lebih baik
227
+ // tutup jujur daripada gantung dengan layar mati.
228
+ finish()
229
+ return
230
+ }
231
+ process.stdin.resume()
232
+ process.stdin.on("data", onData)
233
+ process.stdout.on("resize", onResize)
234
+ attached = true
173
235
  }
174
- process.stdin.resume()
175
- process.stdin.on("data", onData)
176
- process.stdout.on("resize", onResize)
177
236
  render()
178
237
  resetIdle()
179
238
  }
@@ -182,6 +241,21 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
182
241
  if (done) return
183
242
  done = true
184
243
  clearIdle()
244
+ // Kembalikan batas listener warisan (lihat prevMaxListeners): warning
245
+ // MaxListenersExceeded kembali berguna setelah sesi ini selesai.
246
+ try {
247
+ managerPump.dispose()
248
+ } catch {}
249
+ try {
250
+ process.stdin.setMaxListeners(prevMaxListeners)
251
+ } catch {}
252
+ // Hapus region popup sendiri sebelum pemilik me-repaint (App.resume).
253
+ try {
254
+ screen.clearRegion()
255
+ } catch {}
256
+ try {
257
+ screen.close()
258
+ } catch {}
185
259
  // suspend() tak boleh menggagalkan resolve: setRawMode bisa melempar
186
260
  // di Windows bila handle sudah rusak — tanpa try/finally Promise gantung
187
261
  // selamanya (resolve tak tercapai).
@@ -213,7 +287,9 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
213
287
  try {
214
288
  await fn()
215
289
  } catch (e) {
216
- console.log(`${glyphs.cross} ${(e as Error).message}`)
290
+ // Pesan error dari controller/jaringan = input tak terpercaya:
291
+ // sanitasi (tanpa ini ESC[2J dari pesan merusak layar).
292
+ notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
217
293
  } finally {
218
294
  busy = false
219
295
  await loadRowsSafe()
@@ -221,6 +297,34 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
221
297
  }
222
298
  })()
223
299
 
300
+ /**
301
+ * Batas waktu aksi jaringan (onDelete/onSelect/onSetEffort): provider/tool
302
+ * non-kooperatif yang gantung selamanya membuat popup mati (suspend tanpa
303
+ * listener/timer). Timeout = notice jujur + UI pulih; aksi telat yang
304
+ * akhirnya selesai diabaikan hasilnya (tanpa resolve ganda — resolve
305
+ * hanya lewat finish alur normal). Bisa dioverride test via opts.
306
+ */
307
+ const withWatchdog = async <T>(fn: () => Promise<T> | T): Promise<T> => {
308
+ const ms = opts.actionTimeoutMs ?? 60_000
309
+ let timer: ReturnType<typeof setTimeout> | undefined
310
+ const p = Promise.resolve().then(fn)
311
+ // Rejection telat TANPA handler = unhandledRejection (bun: crash).
312
+ p.catch(() => {})
313
+ try {
314
+ return await Promise.race([
315
+ p,
316
+ new Promise<never>((_, reject) => {
317
+ timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
318
+ try {
319
+ ;(timer as unknown as { unref?: () => void }).unref?.()
320
+ } catch {}
321
+ }),
322
+ ])
323
+ } finally {
324
+ if (timer) clearTimeout(timer)
325
+ }
326
+ }
327
+
224
328
  const loadRowsSafe = async () => {
225
329
  try {
226
330
  rows = await opts.loadRows()
@@ -228,50 +332,34 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
228
332
  clampSel()
229
333
  }
230
334
 
231
- const addModel = () =>
232
- runAction(async () => {
233
- const providerId = await askLine({ prompt: "Provider > " })
234
- // Batal (Esc/Ctrl+C di baris kosong = null) harus berhenti DI SINI —
235
- // kalau lanjut ke prompt berikutnya, batal di prompt pertama terasa
236
- // seperti pindah pertanyaan.
237
- if (providerId == null) {
238
- console.log("Canceled")
239
- return
240
- }
241
- const model = await askLine({ prompt: "Model > " })
242
- if (model == null) {
243
- console.log("Canceled")
244
- return
245
- }
246
- if (!providerId.trim() || !model.trim()) {
247
- // Isian kosong (Enter tanpa teks) — beri tahu, jangan diam.
248
- console.log("Canceled")
249
- return
250
- }
251
- const prevCount = rows.length
252
- rows = await opts.onAdd(providerId.trim(), model.trim())
253
- // Panjang tak berubah = model sudah ada (bukan error — provider
254
- // ditemukan, onAdd tak lempar). Laporkan jujur, bukan "added".
255
- if (rows.length === prevCount)
256
- console.log(`${glyphs.dot} ${providerId.trim()}::${model.trim()} already exists`)
257
- else console.log(`${glyphs.check} added ${providerId.trim()}::${model.trim()}`)
258
- clampSel()
259
- })
260
-
261
335
  const deleteModel = () => {
262
336
  const row = viewRows()[sel]
263
337
  if (!row) return
264
338
  return runAction(async () => {
265
339
  // Model AKTIF yang dihapus membuat prompt berikutnya kehilangan model
266
- // tanpa sebab yang terlihat — sebutkan seperti provider-manager.
267
- const prefix = row.active ? "Delete ACTIVE model" : "Delete model"
268
- const answer = await askLine({ prompt: `${prefix} ${row.id}? [y/N] ` })
269
- if (answer?.trim().toLowerCase() === "y") {
270
- rows = await opts.onDelete(row.id)
271
- console.log(`${glyphs.check} deleted ${row.id}`)
340
+ // tanpa sebab yang terlihat — sebutkan. Konfirmasi dalam popup.
341
+ const form = await runForm(
342
+ {
343
+ title: t("model.deleteTitle"),
344
+ fields: [
345
+ {
346
+ id: "ok",
347
+ label: row.active
348
+ ? t("model.delActive", { id: row.id })
349
+ : t("model.del", { id: row.id }),
350
+ kind: "confirm",
351
+ },
352
+ ],
353
+ footer: t("model.deleteFooter"),
354
+ },
355
+ screen,
356
+ )
357
+ if (!form.cancelled && form.values?.ok === "y") {
358
+ rows = await withWatchdog(() => opts.onDelete(row.id))
359
+ notice = `${glyphs.check} ${t("ntc.deleted", { id: row.id })}`
272
360
  } else {
273
- console.log("Canceled")
274
- rows = await opts.loadRows()
361
+ notice = t("common.canceled")
362
+ rows = await withWatchdog(() => opts.loadRows())
275
363
  }
276
364
  clampSel()
277
365
  })
@@ -292,7 +380,7 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
292
380
  // bocor true selamanya (= manager terkunci, terlihat hang).
293
381
  try {
294
382
  void runPicker({
295
- title: "Thinking effort",
383
+ title: t("effort.title"),
296
384
  items: options.map((name) => ({ name, provider: "", value: name })),
297
385
  onPick: (v) => resolvePick(v),
298
386
  onCancel: () => resolvePick(null),
@@ -308,12 +396,18 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
308
396
  }
309
397
 
310
398
  const decoder: DecoderState = createDecoderState()
311
- const onData = (chunk: Buffer) => {
312
- if (busy) return
313
- if (done) return
314
- resetIdle()
399
+ // Batas listener warisan SEBELUM dimatikan: setMaxListeners(0) menutupi
400
+ // kebocoran listener masa depan secara global — simpan & kembalikan di
401
+ // finish agar warning Node kembali berguna setelah sesi ini.
402
+ // Guard typeof: stdin bisa stub (test) tanpa API ini — anggap default 10.
403
+ const prevMaxListeners =
404
+ typeof process.stdin.getMaxListeners === "function" ? process.stdin.getMaxListeners() : 10
405
+ const handleManagerKeys = (keys: DecodedKey[]): boolean => {
406
+ if (busy || done) return true
315
407
  try {
316
- for (const item of decodeKeysStream(chunk, decoder)) {
408
+ // Struk lama dibersihkan tiap keypress baru (transient, bukan arsip).
409
+ notice = null
410
+ for (const item of keys) {
317
411
  // Mode cari: semua ketikan masuk ke query, Esc keluar dari mode
318
412
  // cari — bukan tutup manager.
319
413
  if (filter != null) {
@@ -333,10 +427,20 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
333
427
  scroll = 0
334
428
  continue
335
429
  }
430
+ if (item.key.type === "ctrl-u") {
431
+ // Ctrl+U = clear query (paritas editor, sama dengan picker).
432
+ filter = null
433
+ sel = 0
434
+ scroll = 0
435
+ continue
436
+ }
336
437
  // Backspace & Del sama-sama memangkas query (tanpa kursor,
337
438
  // Del maju = grapheme terakhir juga). Query habis = keluar mode.
439
+ // toGraphemes: emoji/flag utuh (paritas picker/form/askLine).
338
440
  if (item.key.type === "backspace" || item.key.type === "delete") {
339
- filter = Array.from(filter).slice(0, -1).join("")
441
+ const g = toGraphemes(filter)
442
+ g.pop()
443
+ filter = g.join("")
340
444
  if (!filter) filter = null
341
445
  sel = 0
342
446
  scroll = 0
@@ -348,16 +452,37 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
348
452
  item.key.type === "ctrl-d"
349
453
  ) {
350
454
  finish()
351
- return
455
+ return true
352
456
  }
353
457
  if (item.key.type === "up") sel = Math.max(0, sel - 1)
354
458
  else if (item.key.type === "down") {
355
459
  const n = viewRows().length
356
460
  sel = n ? Math.min(n - 1, sel + 1) : 0
461
+ } else if (item.key.type === "home") {
462
+ // Home/End = lompat atas/bawah daftar (paritas picker/App).
463
+ sel = 0
464
+ scroll = 0
465
+ } else if (item.key.type === "end") {
466
+ const n = viewRows().length
467
+ sel = n ? Math.max(0, n - 1) : 0
468
+ } else if (item.key.type === "pageup" || item.key.type === "pagedown") {
469
+ // Scroll daftar per halaman (paritas picker/App). Gagal-di-kode-lama:
470
+ // memakai panjang LIST sebagai jatah visible → kondisi tak pernah
471
+ // benar → PgUp/PgDn mati total.
472
+ const list = viewRows()
473
+ const v = visibleRows()
474
+ if (list.length > v) {
475
+ const page = Math.max(1, v - 1)
476
+ const dir = item.key.type === "pageup" ? -page : page
477
+ scroll = Math.max(0, Math.min(Math.max(0, list.length - v), scroll + dir))
478
+ sel = Math.max(0, Math.min(list.length - 1, sel))
479
+ if (sel < scroll) sel = scroll
480
+ if (sel >= scroll + v) sel = scroll + v - 1
481
+ }
357
482
  } else if (item.key.type === "enter") {
358
483
  const row = viewRows()[sel]
359
- if (!row) return // daftar kosong: jangan tutup (footer bilang select)
360
- if (busy) return
484
+ if (!row) return true // daftar kosong: jangan tutup (footer bilang select)
485
+ if (busy) return true
361
486
  busy = true
362
487
  suspend()
363
488
  // Alur: picker effort DULU, baru select+simpan. Dibalik (select
@@ -373,36 +498,39 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
373
498
  return
374
499
  }
375
500
  try {
376
- await opts.onSelect(row.id)
501
+ await withWatchdog(() => opts.onSelect(row.id))
377
502
  // "skip" = model tanpa thinking: select langsung, effort
378
503
  // tersimpan tak disentuh (aman — pengiriman effort juga
379
504
  // di-gate per keluarga, jadi nilai basi tak pernah terkirim).
380
505
  if (picked !== "skip" && opts.onSetEffort) {
381
- await opts.onSetEffort(row.id, picked)
382
- console.log(`Thinking: ${picked} (next session)`)
506
+ await withWatchdog(() => opts.onSetEffort!(row.id, picked))
507
+ // Struk via notice (rute yang sama dengan receipts lain);
508
+ // manager langsung tutup sesudahnya, jadi baris ini hanya
509
+ // terlihat bila alur berubah me-resume — badge effort di
510
+ // daftar tetap sumber kebenaran yang bisa dibuka ulang.
511
+ notice = t("effort.saved", { effort: picked })
383
512
  }
384
- } catch (e) {
385
- // Jangan tutup diam-diam: pilih model yang gagal harus
386
- // terlihat, bukan dianggap sukses (manager lalu hilang).
387
- console.log(`${glyphs.cross} ${(e as Error).message}`)
388
- } finally {
389
513
  finish()
514
+ } catch (e) {
515
+ // Pilih model yang gagal HARUS terlihat dan kembali ke daftar
516
+ // untuk retry (pola resume() seperti a/d/e provider-manager),
517
+ // bukan menutup manager dan kehilangan konteks daftar.
518
+ // Pesan controller = input tak terpercaya: sanitasi.
519
+ notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
520
+ busy = false
521
+ await loadRowsSafe()
522
+ resume()
390
523
  }
391
524
  } catch {
392
525
  finish()
393
526
  }
394
527
  })()
395
- return
396
- } else if (item.key.type === "ctrl-n") {
397
- // Tambah model — shortcut non-ketik agar ketikan huruf apa pun
398
- // (termasuk a/d) selalu jadi query cari, di Windows & Linux.
399
- void addModel()
400
- return
528
+ return true
401
529
  } else if (item.key.type === "delete") {
402
530
  // Di sini filter selalu null (mode cari ditangani di atas):
403
531
  // hapus model ter-highlight (dengan konfirmasi di deleteModel).
404
532
  void deleteModel()
405
- return
533
+ return true
406
534
  } else if (item.key.type === "char") {
407
535
  // Ketik langsung menyaring — tanpa awalan apa pun.
408
536
  filter = item.key.ch
@@ -411,6 +539,17 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
411
539
  }
412
540
  }
413
541
  render()
542
+ return false
543
+ } catch {
544
+ finish()
545
+ return true
546
+ }
547
+ }
548
+ const managerPump = createKeyStreamPump({ state: decoder, onKeys: handleManagerKeys })
549
+ const onData = (chunk: Buffer) => {
550
+ resetIdle()
551
+ try {
552
+ managerPump.push(chunk)
414
553
  } catch {
415
554
  finish()
416
555
  }
@@ -425,10 +564,18 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
425
564
  process.stdin.setMaxListeners(0)
426
565
  process.stdin.on("data", onData)
427
566
  process.stdout.on("resize", onResize)
567
+ attached = true
428
568
  resetIdle()
429
569
  render()
430
- } catch {
431
- finish()
570
+ } catch (e) {
571
+ // Setup gagal = tutup + BERSUARA (Fase D): jendela kosong bisu adalah
572
+ // kelas bug yang hanya bisa diburu bila terlihat.
573
+ try {
574
+ finish()
575
+ } catch {}
576
+ try {
577
+ console.log(`⚠ ${t("model.failOpen", { msg: String((e as Error)?.message ?? e) })}`)
578
+ } catch {}
432
579
  }
433
580
  })
434
581
  }