minicode-ai 0.9.28 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/cli/args.ts +1 -0
  3. package/cli/commands.ts +219 -103
  4. package/cli/index.ts +8 -6
  5. package/cli/model-manager.ts +2 -7
  6. package/cli/provider-manager.ts +13 -13
  7. package/cli/setup.ts +10 -1
  8. package/cli/tui.ts +506 -0
  9. package/cli/wizard.ts +2 -1
  10. package/docs/ARCHITECTURE.html +41 -22
  11. package/docs/README.md +1 -0
  12. package/package.json +3 -3
  13. package/src/app/rag-layer.ts +7 -2
  14. package/src/config.ts +30 -1
  15. package/src/policy/bash-guard.ts +64 -8
  16. package/src/policy/update-check.ts +4 -1
  17. package/src/tools/bash.ts +8 -0
  18. package/src/tools/task.ts +6 -1
  19. package/src/tools/web_fetch.ts +11 -2
  20. package/src/tools/web_search.ts +4 -1
  21. package/src/ui/approval/prompt.ts +84 -18
  22. package/src/ui/assistant/simple.ts +55 -22
  23. package/src/ui/assistant/turn-status.ts +16 -7
  24. package/src/ui/footer.ts +14 -12
  25. package/src/ui/i18n/en.ts +225 -0
  26. package/src/ui/i18n/id.ts +227 -0
  27. package/src/ui/i18n/locale.ts +66 -0
  28. package/src/ui/input/input.ts +138 -77
  29. package/src/ui/input/prompt-engine.ts +97 -4
  30. package/src/ui/render/collapse.ts +8 -1
  31. package/src/ui/render/errors.ts +75 -50
  32. package/src/ui/render/format.ts +15 -5
  33. package/src/ui/render/highlight.ts +5 -2
  34. package/src/ui/render/table.ts +7 -4
  35. package/src/ui/render/theme.ts +8 -3
  36. package/src/ui/render/width.ts +17 -9
  37. package/src/ui/runtime/screen.ts +197 -0
  38. package/src/ui/screens/dialog.ts +174 -0
  39. package/src/ui/screens/form.ts +459 -0
  40. package/src/ui/screens/model-manager.ts +274 -127
  41. package/src/ui/screens/picker.ts +229 -98
  42. package/src/ui/screens/provider-manager.ts +371 -164
  43. package/src/ui/screens/wizard.ts +149 -102
  44. package/src/ui/tui/app.ts +745 -0
  45. package/src/ui/tui/transcript.ts +271 -0
  46. package/cli/repl.ts +0 -740
  47. package/src/ui/runtime/chrome.ts +0 -369
  48. package/src/ui/screens/overlay.ts +0 -61
@@ -2,16 +2,27 @@
2
2
  // loop keyboard, dan dialog a/d/e; semua akses config lewat callback yang
3
3
  // di-inject controller (cli/provider-manager.ts).
4
4
 
5
- import { askLine, askSecret } from "../input/input.ts"
6
- import { createDecoderState, type DecoderState, decodeKeysStream } from "../input/prompt-engine.ts"
5
+ import { t } from "../i18n/locale.ts"
6
+ import {
7
+ createDecoderState,
8
+ createKeyStreamPump,
9
+ type DecodedKey,
10
+ type DecoderState,
11
+ } from "../input/prompt-engine.ts"
7
12
  import { sanitizeAnsiLine } from "../render/sanitize.ts"
8
- import { c, glyphs } from "../render/theme.ts"
13
+ import { c, glyphs, stripAnsi } from "../render/theme.ts"
9
14
  import { padToWidth, truncateToWidth } from "../render/width.ts"
10
- import { clearTransientOverlay, renderTransientOverlay } from "./overlay.ts"
15
+ import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
16
+ import { boxLeftPad, dialogBox } from "./dialog.ts"
17
+ import { runForm, validateRequired, validateUrl } from "./form.ts"
18
+ import { runPicker } from "./picker.ts"
11
19
 
12
20
  const DIM = "\x1b[2m",
13
21
  RESTORE = "\x1b[22m"
14
22
 
23
+ /** Lebar kotak popup provider TETAP (lebih lebar: kolom URL panjang). */
24
+ const PROVIDER_BOX_W = 76
25
+
15
26
  export interface ProviderRow {
16
27
  id: string
17
28
  baseUrl: string
@@ -52,13 +63,22 @@ export interface ProviderManagerViewOptions {
52
63
  row: ProviderRow,
53
64
  input: { baseUrl: string; apiKey: string },
54
65
  ): Promise<ProviderActionResult>
66
+ /**
67
+ * Batas waktu aksi jaringan (ms) — DI untuk test (default 60 dtk).
68
+ * Tanpa ini test watchdog menunggu semenit.
69
+ */
70
+ actionTimeoutMs?: number
55
71
  }
56
72
 
57
73
  export async function runProviderManagerView(opts: ProviderManagerViewOptions): Promise<void> {
58
74
  let providers: ProviderRow[] = opts.initialRows
59
75
  let sel = 0
60
76
  let scroll = 0
61
- let prevRows = 0
77
+ // Struk aksi transient: hasil/Canceled/error tampil sebagai baris redup
78
+ // DALAM popup, bukan console.log ke scrollback. Dibersihkan tiap keypress
79
+ // baru. Pengecualian sadar: "Detecting models…" (progres jaringan saat
80
+ // popup tersuspend — tanpa itu tunggu terasa hang).
81
+ let notice: string | null = null
62
82
 
63
83
  async function reload() {
64
84
  providers = await opts.loadRows()
@@ -68,12 +88,19 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
68
88
 
69
89
  return new Promise<void>((resolve) => {
70
90
  // Ukuran mengikuti terminal SUNGGUHAN (lihat picker.ts untuk alasan sama).
71
- // Lantai lebar tak boleh MELEBIHI terminal: floor 12 lama membungkus di
72
- // kolom ≤13 (overlay tak bisa menulis lebih lebar dari layar).
73
- const visibleRows = () => Math.max(1, Math.min((process.stdout.rows || 24) - 4, 14))
74
- const width = () => Math.max(8, (process.stdout.columns || 80) - 2)
91
+ // Popup: jatah dialog rows−4 sudah termasuk baris counter/notice, jadi
92
+ // item dibatasi rows−5 (lihat picker.ts).
93
+ const visibleRows = () => {
94
+ const rows = process.stdout.rows || 24
95
+ return Math.max(1, Math.min(rows - 5, 14))
96
+ }
97
+ // Lebar konten = lebar kotak TETAP (min=max, paritas picker/model) —
98
+ // dikurangi chrome dialog (lihat picker.ts).
99
+ const width = () =>
100
+ Math.max(8, Math.min((process.stdout.columns || 80) - 2 - 4, PROVIDER_BOX_W - 4))
75
101
 
76
- const buildLines = (): string[] => {
102
+ // Isi popup (judul + hint dibingkai dialog).
103
+ const bodyLines = (): string[] => {
77
104
  const v = visibleRows()
78
105
  if (sel < scroll) scroll = sel
79
106
  if (sel >= scroll + v) scroll = sel - v + 1
@@ -81,44 +108,78 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
81
108
  const cut = (s: string) => truncateToWidth(s, w)
82
109
  const rows = providers.slice(scroll, scroll + v)
83
110
  const lines: string[] = []
84
- lines.push(
85
- cut(
86
- `${DIM}─ ${c.accent(c.bold("Providers"))}${providers.length ? ` ${DIM}(${providers.length})${RESTORE}` : ""} ${DIM}─${RESTORE}`,
87
- ),
88
- )
89
111
  if (providers.length === 0) {
90
- lines.push(cut(`${DIM} No providers${RESTORE}`))
112
+ lines.push(cut(`${DIM} ${t("prov.empty")}${RESTORE}`))
91
113
  } else {
92
114
  for (let i = 0; i < rows.length; i++) {
93
115
  const it = rows[i]!
94
116
  const picked = i === sel - scroll
95
117
  // Tandai provider yang sedang aktif supaya user tahu apa yang akan
96
- // hilang bila ia menekan d.
97
- const aktif = opts.currentModel?.startsWith(`${it.id}::`) ? " (active)" : ""
118
+ // hilang bila ia menekan d. ID/URL dari config (data kotor mungkin)
119
+ // disanitasi seperti label picker.
120
+ const aktif = opts.currentModel?.startsWith(`${it.id}::`)
121
+ ? ` (${t("common.active")})`
122
+ : ""
98
123
  const label = truncateToWidth(
99
- `${padToWidth(it.id, 18)} ${padToWidth(String(it.models), 3, "right")} models ${it.baseUrl}${aktif}`,
124
+ `${padToWidth(sanitizeAnsiLine(it.id), 18)} ${padToWidth(String(it.models), 3, "right")} models ${sanitizeAnsiLine(it.baseUrl)}${aktif}`,
100
125
  w - 4,
101
126
  )
102
127
  if (picked) lines.push(` ${c.accent("›")} ${c.accent(c.bold(label))}${RESTORE}`)
103
128
  else lines.push(` ${DIM}${label}${RESTORE}`)
104
129
  }
105
130
  if (providers.length > scroll + v) {
106
- lines.push(
107
- cut(`${DIM}… ${c.accent(String(providers.length - scroll - v))} more${RESTORE}`),
108
- )
131
+ lines.push(cut(`${DIM}${t("dlg.more", { n: providers.length - scroll - v })}${RESTORE}`))
109
132
  }
110
133
  }
111
- lines.push("")
112
- lines.push(
113
- cut(
114
- `${DIM}Enter:${RESTORE}${c.accent("select")} ${DIM}a:${RESTORE}${c.accent("add")} ${DIM}d:${RESTORE}${c.accent("delete")} ${DIM}e:${RESTORE}${c.accent("edit")} ${DIM}Esc:${RESTORE}${c.accent("close")}${RESTORE}`,
115
- ),
116
- )
134
+ // Struk transient (jalur legacy maupun modal).
135
+ if (notice) lines.push(cut(`${DIM}${sanitizeAnsiLine(notice)}${RESTORE}`))
117
136
  return lines
118
137
  }
119
138
 
139
+ const hintText = (): string =>
140
+ t("prov.hint", {
141
+ select: c.accent(t("verb.select")),
142
+ add: c.accent(t("verb.add")),
143
+ delete: c.accent(t("verb.delete")),
144
+ edit: c.accent(t("verb.edit")),
145
+ close: c.accent(t("verb.close")),
146
+ })
147
+
120
148
  const render = () => {
121
- prevRows = renderTransientOverlay(buildLines(), prevRows)
149
+ // Popup komposit: HANYA region kotak (tanpa clear) di atas konten
150
+ // pemilik layar. Lebar TETAP 76 (min=max) — tak bernapas.
151
+ const box = dialogBox(
152
+ {
153
+ title: t("prov.title"),
154
+ body: bodyLines(),
155
+ footer: hintText(),
156
+ minWidth: PROVIDER_BOX_W,
157
+ maxWidth: PROVIDER_BOX_W,
158
+ },
159
+ screen.cols,
160
+ screen.rows,
161
+ )
162
+ screen.paintRegion(box.lines, box.topRow)
163
+ // Parkir kursor di baris item aktif (paritas picker/form). Indeks via
164
+ // box.bodyTop — tebak manual meleset tiap judul berubah.
165
+ const itemRow = Math.min(Math.max(0, sel - scroll), Math.max(0, visibleRows() - 1))
166
+ const li = Math.min(box.lines.length - 1, box.bodyTop + itemRow)
167
+ const row = box.topRow + li
168
+ try {
169
+ const leftPad = boxLeftPad(stripAnsi(box.lines[li] ?? ""))
170
+ process.stdout.write(`\x1b[${row};${Math.max(1, leftPad + 1)}H\x1b[?25h`)
171
+ } catch {}
172
+ }
173
+
174
+ // Popup butuh layar mampu; selain itu tolak BERSUARA + batal.
175
+ const screen: AltScreen = openAltScreen()
176
+ const useModal = screen.ok && (process.stdout.rows || 24) >= 10
177
+ if (!useModal) {
178
+ try {
179
+ console.log(`⚠ ${t("gate.tuiProvider")}`)
180
+ } catch {}
181
+ resolve()
182
+ return
122
183
  }
123
184
 
124
185
  let done = false
@@ -132,17 +193,16 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
132
193
  idleTimer = undefined
133
194
  }
134
195
  let resetIdle: () => void = () => {}
196
+ /** Listener stdin terpasang? Menjaga resume() idempoten (anti-ganda). */
197
+ let attached = false
135
198
 
136
- // Suspend: hapus overlay + lepas raw mode + listener sementara
137
- // (untuk askLine/askSecret di a/d/e). Tidak menyentuh `done` - manager
138
- // tetap hidup; resume() menggambar ulang overlay dari posisi kursor kini.
199
+ // Suspend: lepas raw mode + listener sementara (untuk askLine/askSecret
200
+ // di a/d/e). Tidak menyentuh `done` - manager tetap hidup; resume()
201
+ // menggambar ulang region popup.
139
202
  const suspend = () => {
140
203
  clearIdle()
141
- prevRows = clearTransientOverlay(prevRows)
204
+ attached = false
142
205
  process.stdout.write("\x1b[0m\x1b[?25h")
143
- // TIDAK menulis \r\n di sini: clearTransientOverlay sudah menaruh kursor
144
- // kembali ke anchor. \r\n sebelumnya membuat baris kosong permanen di
145
- // scrollback (append-only) — gap 1 baris tiap kali a/d/e dipakai.
146
206
  // setRawMode dibungkus try/catch: di Windows handle bisa rusak dan
147
207
  // melempar — tanpa ini suspend melempar lalu Promise tak pernah settle.
148
208
  // TANPA pause — stdin mengalir seumur proses (lihat cleanup askLine).
@@ -156,21 +216,26 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
156
216
  process.stdout.removeListener("resize", onResize)
157
217
  } catch {}
158
218
  }
159
- // Resume: pasang ulang raw mode + listener + render.
219
+ // Resume: pasang ulang raw mode + listener + render. Idempoten: tanpa
220
+ // garda, resume ganda (watchdog timeout lalu aksi telat selesai) memasang
221
+ // listener stdin DUA kali → tiap tombol diproses ganda.
160
222
  const resume = () => {
161
223
  if (done) return
162
- process.stdin.setMaxListeners(0)
163
- try {
164
- process.stdin.setRawMode(true)
165
- } catch {
166
- // Raw-mode gagal = tak bisa baca tombol; tutup jujur daripada gantung.
167
- cleanup()
168
- resolve()
169
- return
224
+ if (!attached) {
225
+ process.stdin.setMaxListeners(0)
226
+ try {
227
+ process.stdin.setRawMode(true)
228
+ } catch {
229
+ // Raw-mode gagal = tak bisa baca tombol; tutup jujur daripada gantung.
230
+ cleanup()
231
+ resolve()
232
+ return
233
+ }
234
+ process.stdin.resume()
235
+ process.stdin.on("data", onData)
236
+ process.stdout.on("resize", onResize)
237
+ attached = true
170
238
  }
171
- process.stdin.resume()
172
- process.stdin.on("data", onData)
173
- process.stdout.on("resize", onResize)
174
239
  render()
175
240
  resetIdle()
176
241
  }
@@ -180,6 +245,19 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
180
245
  if (done) return
181
246
  done = true
182
247
  clearIdle()
248
+ try {
249
+ providerPump.dispose()
250
+ } catch {}
251
+ try {
252
+ process.stdin.setMaxListeners(prevMaxListeners)
253
+ } catch {}
254
+ // Hapus region popup sendiri sebelum pemilik me-repaint (App.resume).
255
+ try {
256
+ screen.clearRegion()
257
+ } catch {}
258
+ try {
259
+ screen.close()
260
+ } catch {}
183
261
  try {
184
262
  suspend()
185
263
  } catch {}
@@ -213,7 +291,8 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
213
291
  try {
214
292
  await fn()
215
293
  } catch (e) {
216
- console.log(`${glyphs.cross} ${(e as Error).message}`)
294
+ // Pesan controller/jaringan = input tak terpercaya: sanitasi.
295
+ notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
217
296
  } finally {
218
297
  busy = false
219
298
  await reload().catch(() => {})
@@ -221,80 +300,129 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
221
300
  }
222
301
  })()
223
302
 
224
- const doAdd = () =>
225
- runAction(async () => {
226
- console.log("\nAdd provider\n")
227
- opts.presets.forEach((p, i) => {
228
- console.log(` [${i}] ${p.label}`)
229
- })
230
- const customIdx = opts.presets.length
231
- console.log(` [${customIdx}] Custom URL\n`)
232
- const selStr = await askLine({ prompt: "Gateway > " })
233
- // Batal (Esc/Ctrl+C) ATAU isian kosong = batal, bukan "pilih [0]".
234
- // Dulu Enter kosong diam-diam memilih preset pertama (Number("")===0)
235
- // — user yang mau batal malah masuk alur tambah provider.
236
- if (selStr == null || !selStr.trim()) {
237
- console.log("Canceled")
238
- return
239
- }
240
- const pick = selStr.trim()
241
- const idx = Number(pick)
242
- let preset: ProviderPresetView | undefined
243
- let baseUrl: string
244
- if (Number.isInteger(idx) && idx >= 0 && idx < customIdx) {
245
- preset = opts.presets[idx]!
246
- baseUrl = preset.baseUrl
247
- } else if (idx === customIdx || !Number.isInteger(idx)) {
248
- const url = await askLine({ prompt: "Base URL > " })
249
- if (url == null) {
250
- console.log("Canceled")
251
- return
252
- }
253
- if (!url.trim()) {
254
- console.log("Base URL is required.")
303
+ /**
304
+ * Batas waktu aksi jaringan: provider non-kooperatif yang gantung membuat
305
+ * popup mati (suspend tanpa listener/timer). Timeout = notice jujur + UI
306
+ * pulih; aksi telat yang akhirnya selesai diabaikan hasilnya. Tunggu
307
+ * interaksi user (form/picker) TIDAK dibatasi — hanya await jaringan.
308
+ */
309
+ const withWatchdog = async <T>(fn: () => Promise<T> | T): Promise<T> => {
310
+ const ms = opts.actionTimeoutMs ?? 60_000
311
+ let timer: ReturnType<typeof setTimeout> | undefined
312
+ const p = Promise.resolve().then(fn)
313
+ // Rejection telat TANPA handler = unhandledRejection (bun: crash).
314
+ p.catch(() => {})
315
+ try {
316
+ return await Promise.race([
317
+ p,
318
+ new Promise<never>((_, reject) => {
319
+ timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
320
+ try {
321
+ ;(timer as unknown as { unref?: () => void }).unref?.()
322
+ } catch {}
323
+ }),
324
+ ])
325
+ } finally {
326
+ if (timer) clearTimeout(timer)
327
+ }
328
+ }
329
+
330
+ const doAdd = () => {
331
+ if (busy) return
332
+ busy = true
333
+ suspend()
334
+ ;(async () => {
335
+ try {
336
+ // Langkah 1: preset via picker (daftar + filter, dalam popup).
337
+ const CUSTOM = "custom-url"
338
+ const picked: string | null = await new Promise((resolvePick) => {
339
+ try {
340
+ void runPicker({
341
+ title: t("prov.addTitle"),
342
+ items: [
343
+ ...opts.presets.map((p) => ({ name: p.label, provider: "", value: p.id })),
344
+ { name: t("prov.customUrl"), provider: "", value: CUSTOM },
345
+ ],
346
+ filterable: true,
347
+ placeholder: t("pick.placeholder"),
348
+ onPick: (v) => resolvePick(v),
349
+ onCancel: () => resolvePick(null),
350
+ }).catch(() => resolvePick(null))
351
+ } catch {
352
+ resolvePick(null)
353
+ }
354
+ })
355
+ if (picked == null) {
356
+ notice = t("common.canceled")
255
357
  return
256
358
  }
257
- baseUrl = url.trim()
258
- } else {
259
- console.log(`${glyphs.cross} Unknown selection`)
260
- return
261
- }
262
- // Tambah dengan id yang SUDAH ADA menimpa key+models tanpa konfirmasi
263
- // (deriveProviderId memakai id apa adanya) — tanya dulu, karena hapus
264
- // saja butuh konfirmasi.
265
- if (preset && providers.some((r) => r.id === preset.id)) {
266
- const ok = await askLine({
267
- prompt: `Provider "${preset.id}" exists — overwrite its key and models? [y/N] `,
268
- })
269
- if (ok?.trim().toLowerCase() !== "y") {
270
- console.log("Canceled")
359
+ const preset = picked === CUSTOM ? undefined : opts.presets.find((p) => p.id === picked)
360
+ // Langkah 2: form dalam popup (URL + key + scope + konfirmasi
361
+ // timpa bila duplikat). SEMUA ketikan di dalam kotak.
362
+ const duplicate = preset && providers.some((r) => r.id === preset.id)
363
+ const fields = [
364
+ {
365
+ id: "url",
366
+ label: t("prov.urlLabel"),
367
+ kind: "text" as const,
368
+ initial: preset?.baseUrl ?? "",
369
+ validate: validateUrl,
370
+ },
371
+ {
372
+ id: "key",
373
+ label: t("prov.keyLabel"),
374
+ kind: "secret" as const,
375
+ validate: validateRequired,
376
+ },
377
+ ...(opts.askScope
378
+ ? [
379
+ {
380
+ id: "scope",
381
+ label: t("prov.scopeLabel"),
382
+ kind: "select" as const,
383
+ options: ["global", "local"],
384
+ },
385
+ ]
386
+ : []),
387
+ ...(duplicate
388
+ ? [
389
+ {
390
+ id: "overwrite",
391
+ label: t("prov.overwriteLabel", { id: preset.id }),
392
+ kind: "confirm" as const,
393
+ },
394
+ ]
395
+ : []),
396
+ ]
397
+ const form = await runForm({ title: t("prov.addTitle"), fields }, screen)
398
+ if (form.cancelled || !form.values) {
399
+ notice = t("common.canceled")
271
400
  return
272
401
  }
273
- }
274
- const apiKey = await askSecret("API key: ")
275
- if (apiKey == null) {
276
- console.log("Canceled")
277
- return
278
- }
279
- if (!apiKey) {
280
- console.log("API key is required.")
281
- return
282
- }
283
- let scope: "global" | "local" = "global"
284
- if (opts.askScope) {
285
- const ans = await askLine({ prompt: "Save globally? [Y/n] " })
286
- if (ans == null) {
287
- console.log("Canceled")
402
+ if (duplicate && form.values.overwrite !== "y") {
403
+ notice = t("common.canceled")
288
404
  return
289
405
  }
290
- scope = ans?.trim().toLowerCase() === "n" ? "local" : "global"
406
+ const baseUrl = (form.values.url ?? "").trim()
407
+ const apiKey = form.values.key ?? ""
408
+ const scope = form.values.scope === "local" ? "local" : "global"
409
+ // Progres terlihat: render notice DULU (masih suspend = tanpa
410
+ // listener ganda), baru await jaringan.
411
+ notice = t("ntc.detecting")
412
+ render()
413
+ const res = await withWatchdog(() => opts.onAdd({ preset, baseUrl, apiKey, scope }))
414
+ // Hasil dari jaringan/config — sanitasi sebelum tampil.
415
+ if (res.ok) notice = `${glyphs.check} ${sanitizeAnsiLine(res.ok)}`
416
+ else if (res.err) notice = `${glyphs.cross} ${sanitizeAnsiLine(res.err)}`
417
+ } catch (e) {
418
+ notice = `${glyphs.cross} ${(e as Error).message}`
419
+ } finally {
420
+ busy = false
421
+ await reload().catch(() => {})
422
+ resume()
291
423
  }
292
- console.log("Detecting models…")
293
- const res = await opts.onAdd({ preset, baseUrl, apiKey, scope })
294
- // Hasil dari jaringan/config — sanitasi sebelum tampil di scrollback.
295
- if (res.ok) console.log(`${glyphs.check} ${sanitizeAnsiLine(res.ok)}`)
296
- else if (res.err) console.log(`${glyphs.cross} ${sanitizeAnsiLine(res.err)}`)
297
- })
424
+ })()
425
+ }
298
426
 
299
427
  const doDelete = () => {
300
428
  if (providers.length === 0) return
@@ -302,25 +430,33 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
302
430
  if (!target) return
303
431
  return runAction(async () => {
304
432
  // Konfirmasi menyebut DAMPAK, bukan hanya nama: berapa model ikut hilang,
305
- // dan apakah provider ini yang sedang dipakai. Tanpa itu user menekan "y"
306
- // tanpa tahu prompt berikutnya akan gagal.
433
+ // dan apakah provider ini yang sedang dipakai. Form confirm dalam popup
434
+ // (konteks terlihat saat menjawab).
307
435
  const active = opts.currentModel?.startsWith(`${target.id}::`)
308
- console.log(`\nDelete provider "${target.id}" and ${target.models} models?`)
309
- if (active) {
310
- console.log(`${glyphs.cross} Provider is active (${opts.currentModel}).`)
311
- }
312
- const ans = await askLine({ prompt: "Delete? [y/N] " })
313
- if (ans == null) {
314
- console.log("Canceled")
436
+ const form = await runForm(
437
+ {
438
+ title: t("prov.deleteTitle"),
439
+ fields: [
440
+ {
441
+ id: "ok",
442
+ label:
443
+ t("prov.deleteLabel", { id: target.id, n: target.models }) +
444
+ (active ? t("prov.deleteActive", { model: opts.currentModel ?? "" }) : "") +
445
+ t("prov.deleteAsk"),
446
+ kind: "confirm",
447
+ },
448
+ ],
449
+ footer: t("prov.deleteFooter"),
450
+ },
451
+ screen,
452
+ )
453
+ if (form.cancelled || form.values?.ok !== "y") {
454
+ notice = t("common.canceled")
315
455
  return
316
456
  }
317
- if (ans.trim().toLowerCase() === "y") {
318
- const res = await opts.onDelete(target)
319
- if (res.ok) console.log(`${glyphs.check} ${sanitizeAnsiLine(res.ok)}`)
320
- else if (res.err) console.log(`${glyphs.cross} ${sanitizeAnsiLine(res.err)}`)
321
- } else {
322
- console.log("Canceled")
323
- }
457
+ const res = await withWatchdog(() => opts.onDelete(target))
458
+ if (res.ok) notice = `${glyphs.check} ${sanitizeAnsiLine(res.ok)}`
459
+ else if (res.err) notice = `${glyphs.cross} ${sanitizeAnsiLine(res.err)}`
324
460
  })
325
461
  }
326
462
 
@@ -331,43 +467,61 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
331
467
  return runAction(async () => {
332
468
  const defaults = await opts.onEditDefaults(target)
333
469
  if (!defaults) {
334
- console.log("Provider not found")
335
- return
336
- }
337
- console.log(`\nEdit provider "${target.id}"\n`)
338
- // Batal di prompt pertama/kedua harus benar-benar batal — dulu
339
- // Ctrl+C jatuh ke "pertahankan nilai lama" lalu "No changes", tanpa
340
- // jalan keluar dari dialog edit.
341
- const newUrl = await askLine({ prompt: `Base URL [${defaults.baseUrl}]: ` })
342
- if (newUrl == null) {
343
- console.log("Canceled")
470
+ notice = t("ntc.notFound")
344
471
  return
345
472
  }
346
- const newKey = await askSecret("API key [****]: ")
347
- if (newKey == null) {
348
- console.log("Canceled")
473
+ // Form edit dalam popup (prefill defaults). Batal di mana pun =
474
+ // batal total (tanpa jatuh ke "pertahankan nilai lama").
475
+ const form = await runForm(
476
+ {
477
+ title: t("prov.editTitle", { id: target.id }),
478
+ fields: [
479
+ {
480
+ id: "url",
481
+ label: t("prov.urlLabel"),
482
+ kind: "text",
483
+ initial: defaults.baseUrl,
484
+ validate: validateUrl,
485
+ },
486
+ // Key kosong = pertahankan lama (tanpa validate required).
487
+ { id: "key", label: t("prov.keyKeepLabel"), kind: "secret", initial: "" },
488
+ ],
489
+ footer: t("form.footerDefault"),
490
+ },
491
+ screen,
492
+ )
493
+ if (form.cancelled || !form.values) {
494
+ notice = t("common.canceled")
349
495
  return
350
496
  }
351
- const baseUrl = newUrl.trim() ? newUrl.trim() : defaults.baseUrl
352
- const apiKey = newKey.trim() ? newKey.trim() : defaults.apiKey
497
+ // Key kosong = pertahankan lama (placeholder [****] memberi tahu).
498
+ const baseUrl = (form.values.url ?? "").trim() || defaults.baseUrl
499
+ const apiKey = (form.values.key ?? "").trim() || defaults.apiKey
353
500
  if (baseUrl === defaults.baseUrl && apiKey === defaults.apiKey) {
354
- console.log("No changes.")
501
+ notice = t("ntc.noChange")
355
502
  } else {
356
- console.log("Detecting models…")
357
- const res = await opts.onEditSave(target, { baseUrl, apiKey })
358
- if (res.ok) console.log(`${glyphs.check} ${sanitizeAnsiLine(res.ok)}`)
359
- else if (res.err) console.log(`${glyphs.cross} ${sanitizeAnsiLine(res.err)}`)
503
+ notice = t("ntc.detecting")
504
+ render()
505
+ const res = await withWatchdog(() => opts.onEditSave(target, { baseUrl, apiKey }))
506
+ if (res.ok) notice = `${glyphs.check} ${sanitizeAnsiLine(res.ok)}`
507
+ else if (res.err) notice = `${glyphs.cross} ${sanitizeAnsiLine(res.err)}`
360
508
  }
361
509
  })
362
510
  }
363
511
 
364
512
  const decoder: DecoderState = createDecoderState()
365
- const onData = (chunk: Buffer) => {
366
- if (busy) return
367
- if (done) return
368
- resetIdle()
513
+ // Seperti model-manager: simpan batas listener warisan, kembalikan di
514
+ // cleanup agar warning MaxListenersExceeded tetap berguna setelahnya.
515
+ // Guard typeof: stdin bisa stub (test) tanpa API ini — anggap default 10.
516
+ const prevMaxListeners =
517
+ typeof process.stdin.getMaxListeners === "function" ? process.stdin.getMaxListeners() : 10
518
+ // Jalur tunggal key (sinkron + flush lone-ESC 50ms). True = selesai.
519
+ const handleProviderKeys = (keys: DecodedKey[]): boolean => {
520
+ if (busy || done) return true
521
+ // Struk lama dibersihkan tiap keypress baru (transient, bukan arsip).
522
+ notice = null
369
523
  try {
370
- for (const d of decodeKeysStream(chunk, decoder)) {
524
+ for (const d of keys) {
371
525
  switch (d.key.type) {
372
526
  case "up":
373
527
  sel = Math.max(0, sel - 1)
@@ -378,44 +532,76 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
378
532
  sel = providers.length ? Math.min(providers.length - 1, sel + 1) : 0
379
533
  render()
380
534
  break
535
+ case "home":
536
+ // Home/End = lompat atas/bawah daftar (paritas picker/App).
537
+ sel = 0
538
+ scroll = 0
539
+ render()
540
+ break
541
+ case "end":
542
+ sel = providers.length ? Math.max(0, providers.length - 1) : 0
543
+ render()
544
+ break
545
+ case "pageup":
546
+ case "pagedown": {
547
+ // Scroll daftar per halaman (paritas picker/App). Gagal-di-kode-lama:
548
+ // tombol ini tak ditangani sama sekali padahal ada baris `… more`.
549
+ const v = visibleRows()
550
+ if (providers.length > v) {
551
+ const page = Math.max(1, v - 1)
552
+ scroll = Math.max(
553
+ 0,
554
+ Math.min(
555
+ Math.max(0, providers.length - v),
556
+ scroll + (d.key.type === "pageup" ? -page : page),
557
+ ),
558
+ )
559
+ sel = Math.max(0, Math.min(providers.length - 1, sel))
560
+ if (sel < scroll) sel = scroll
561
+ if (sel >= scroll + v) sel = scroll + v - 1
562
+ render()
563
+ }
564
+ break
565
+ }
381
566
  case "char": {
382
567
  const ch = d.key.ch.toLowerCase()
383
568
  if (ch === "a") {
384
569
  void doAdd()
385
- return
570
+ return true
386
571
  }
387
572
  if (ch === "d") {
388
573
  void doDelete()
389
- return
574
+ return true
390
575
  }
391
576
  if (ch === "e") {
392
577
  void doEdit()
393
- return
578
+ return true
394
579
  }
395
580
  break
396
581
  }
397
582
  case "enter": {
398
583
  // Footer bilang "select"; daftar kosong tak boleh menutup layar.
399
584
  const p = providers[sel]
400
- if (!p) return
585
+ if (!p) return true
401
586
  try {
402
587
  opts.onSelect(p)
403
588
  } catch {}
404
589
  cleanup()
405
590
  resolve()
406
- return
591
+ return true
407
592
  }
408
593
  case "esc":
409
594
  case "ctrl-c":
410
595
  case "ctrl-d":
411
596
  cleanup()
412
597
  resolve()
413
- return
598
+ return true
414
599
  default:
415
600
  break
416
601
  }
417
602
  }
418
603
  render()
604
+ return false
419
605
  } catch {
420
606
  // Tanpa resolve Promise gantung selamanya (bug: cleanup saja tak cukup).
421
607
  try {
@@ -424,6 +610,21 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
424
610
  try {
425
611
  resolve()
426
612
  } catch {}
613
+ return true
614
+ }
615
+ }
616
+ const providerPump = createKeyStreamPump({ state: decoder, onKeys: handleProviderKeys })
617
+ const onData = (chunk: Buffer) => {
618
+ resetIdle()
619
+ try {
620
+ providerPump.push(chunk)
621
+ } catch {
622
+ try {
623
+ cleanup()
624
+ } catch {}
625
+ try {
626
+ resolve()
627
+ } catch {}
427
628
  }
428
629
  }
429
630
 
@@ -436,12 +637,18 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
436
637
  process.stdin.setMaxListeners(0)
437
638
  process.stdin.on("data", onData)
438
639
  process.stdout.on("resize", onResize)
640
+ attached = true
439
641
  resetIdle()
440
642
  render()
441
- } catch {
643
+ } catch (e) {
644
+ // Setup gagal = tutup + BERSUARA (Fase D): jendela kosong bisu adalah
645
+ // kelas bug yang hanya bisa diburu bila terlihat.
442
646
  try {
443
647
  cleanup()
444
648
  } catch {}
649
+ try {
650
+ console.log(`⚠ ${t("prov.failOpen", { msg: String((e as Error)?.message ?? e) })}`)
651
+ } catch {}
445
652
  try {
446
653
  resolve()
447
654
  } catch {}