minicode-ai 0.21.0 → 0.23.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 (72) hide show
  1. package/README.md +1 -1
  2. package/cli/commands/exec.ts +44 -1
  3. package/cli/commands.ts +15 -2
  4. package/cli/index.ts +11 -0
  5. package/cli/setup.ts +88 -33
  6. package/cli/tui.ts +3 -3
  7. package/docs/TERMINAL_CONTRACT.md +69 -13
  8. package/docs/architecture.md +9 -5
  9. package/docs/concepts.md +1 -1
  10. package/docs/contributing.md +2 -1
  11. package/docs/environment.md +4 -0
  12. package/docs/policy-sandbox.md +6 -1
  13. package/docs/security.md +12 -4
  14. package/docs/skills.md +1 -1
  15. package/package.json +2 -2
  16. package/src/app/session.ts +129 -20
  17. package/src/config.ts +108 -8
  18. package/src/constants.ts +29 -4
  19. package/src/daemon/discovery.ts +24 -0
  20. package/src/policy/bash-guard.ts +170 -6
  21. package/src/policy/compaction.ts +61 -7
  22. package/src/policy/context-budget.ts +132 -0
  23. package/src/policy/context-escalation.ts +140 -0
  24. package/src/policy/context-window.ts +47 -9
  25. package/src/policy/context.ts +10 -1
  26. package/src/policy/jail.ts +10 -22
  27. package/src/policy/microcompact.ts +162 -0
  28. package/src/policy/permission.ts +9 -6
  29. package/src/presentation/projection.ts +1 -1
  30. package/src/providers/anthropic.ts +31 -7
  31. package/src/providers/detect.ts +128 -13
  32. package/src/providers/provision.ts +78 -1
  33. package/src/providers/responses.ts +14 -2
  34. package/src/providers/sse-bounds.ts +16 -2
  35. package/src/session/persistence.ts +56 -0
  36. package/src/ui/approval/prompt.ts +17 -6
  37. package/src/ui/assistant/simple.ts +1 -1
  38. package/src/ui/footer.ts +2 -2
  39. package/src/ui/i18n/en.ts +28 -5
  40. package/src/ui/i18n/id.ts +30 -5
  41. package/src/ui/input/input.ts +2 -2
  42. package/src/ui/input/prompt-engine.ts +6 -0
  43. package/src/ui/render/activity-panel.ts +21 -3
  44. package/src/ui/render/diff.ts +51 -2
  45. package/src/ui/render/highlight.ts +68 -37
  46. package/src/ui/render/hint.ts +28 -0
  47. package/src/ui/render/logo.ts +91 -0
  48. package/src/ui/render/sanitize.ts +5 -1
  49. package/src/ui/render/session-summary.ts +28 -5
  50. package/src/ui/render/table-grid.ts +123 -13
  51. package/src/ui/render/table.ts +4 -2
  52. package/src/ui/render/theme.ts +16 -3
  53. package/src/ui/render/width.ts +35 -6
  54. package/src/ui/render/wrap.ts +28 -6
  55. package/src/ui/runtime/loading-bar.ts +17 -5
  56. package/src/ui/runtime/screen.ts +4 -2
  57. package/src/ui/screens/dialog.ts +23 -2
  58. package/src/ui/screens/form.ts +71 -33
  59. package/src/ui/screens/lifecycle.ts +80 -0
  60. package/src/ui/screens/model-manager.ts +85 -83
  61. package/src/ui/screens/picker.ts +39 -25
  62. package/src/ui/screens/provider-manager.ts +58 -55
  63. package/src/ui/screens/watchdog.ts +27 -0
  64. package/src/ui/screens/wizard.ts +12 -1
  65. package/src/ui/tui/app.ts +62 -22
  66. package/src/ui/tui/transcript.ts +93 -23
  67. package/vendor/minicore/src/core/compact.ts +10 -0
  68. package/vendor/minicore/src/core/errors.ts +11 -1
  69. package/vendor/minicore/src/core/executor.ts +6 -1
  70. package/vendor/minicore/src/core/loop.ts +92 -2
  71. package/vendor/minicore/src/core/session.ts +8 -0
  72. package/vendor/minicore/src/providers/openai-compat.ts +45 -3
@@ -8,13 +8,16 @@ import {
8
8
  type DecoderState,
9
9
  toGraphemes,
10
10
  } from "../input/prompt-engine.ts"
11
- import { sanitizeAnsiLine } from "../render/sanitize.ts"
11
+ import { hintLine } from "../render/hint.ts"
12
+ import { cleanUntrusted, sanitizeAnsiLine } from "../render/sanitize.ts"
12
13
  import { c, glyphs, stripAnsi } from "../render/theme.ts"
13
14
  import { displayWidth, truncateToWidth } from "../render/width.ts"
14
15
  import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
15
16
  import { boxLeftPad, dialogBox } from "./dialog.ts"
16
17
  import { runForm } from "./form.ts"
18
+ import { createIdleTimer } from "./lifecycle.ts"
17
19
  import { runPicker } from "./picker.ts"
20
+ import { withTimeout } from "./watchdog.ts"
18
21
 
19
22
  const dim = (s: string): string => c.dim(s)
20
23
 
@@ -85,8 +88,12 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
85
88
  return new Promise<void>((resolve) => {
86
89
  const visibleRows = () => {
87
90
  const rows = process.stdout.rows || 24
88
- // Dialog tanpa judul/footer; satu baris dipakai untuk pencarian.
89
- return Math.max(1, Math.min(rows - 3, 8))
91
+ // Chrome tetap: 2 border + 1 baris pencarian + 1 baris hint aksi;
92
+ // struk notice (transient) menyusutkan daftar satu baris agar tak
93
+ // pernah menyingkirkan hint/marker "… more" (dialogBox memotong body
94
+ // dari atas). Semua angka pas dengan `room = rows − 2` di dialogBox.
95
+ const fixed = 4 + (notice ? 1 : 0)
96
+ return Math.max(1, Math.min(rows - fixed, 8))
90
97
  }
91
98
  // Lantai lebar tak boleh melebihi terminal. Lebar konten = lebar kotak
92
99
  // tetap dikurangi chrome dialog (border+padding = 4) agar sepakat dengan
@@ -125,6 +132,20 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
125
132
  }
126
133
  }
127
134
  if (notice) lines.push(cut(dim(sanitizeAnsiLine(notice))))
135
+ // Hint aksi minimalis (kunci terang, label redup) — satu sumber dengan
136
+ // picker/form agar seluruh jendela /model konsisten. Sengaja TANPA
137
+ // judul/footer dekoratif (kontrak v7.8); ini baris body terakhir.
138
+ lines.push(
139
+ cut(
140
+ hintLine([
141
+ { key: "↑↓", label: t("hint.move") },
142
+ { key: "Enter", label: t("hint.select") },
143
+ { key: "Tab", label: t("hint.effort") },
144
+ { key: "Del", label: t("hint.delete") },
145
+ { key: "Esc", label: t("hint.close") },
146
+ ]),
147
+ ),
148
+ )
128
149
  return lines
129
150
  }
130
151
 
@@ -187,17 +208,15 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
187
208
  // Manager ini sebelumnya TANPA idleTimer: bila stdin 'data' tak pernah
188
209
  // datang (ConPTY macet/fokus hilang/busy bocor), Promise tak pernah settle
189
210
  // dan raw-mode dipegang selamanya = "masuk list model macet". Samakan
190
- // dengan picker: idle 90 dtk = batal otomatis.
191
- let idleTimer: ReturnType<typeof setTimeout> | undefined
192
- const clearIdle = () => {
193
- if (idleTimer) clearTimeout(idleTimer)
194
- idleTimer = undefined
195
- }
196
- // Didefinisikan di bawah (function hoisting via let) — dipanggil finish.
197
- let resetIdle: () => void = () => {}
211
+ // dengan picker: idle 90 dtk = batal otomatis (helper bersama, audit D1).
212
+ // `finish` dirujuk sebagai closure — dievaluasi saat timer fire.
213
+ const idle = createIdleTimer({
214
+ cancelMs: 90_000,
215
+ onCancel: () => finish(),
216
+ })
198
217
 
199
218
  const suspend = () => {
200
- clearIdle()
219
+ idle.clear()
201
220
  attached = false
202
221
  process.stdout.write("\x1b[0m\x1b[?25h")
203
222
  // TANPA pause — stdin mengalir seumur proses (lihat cleanup askLine).
@@ -233,13 +252,13 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
233
252
  attached = true
234
253
  }
235
254
  render()
236
- resetIdle()
255
+ idle.reset()
237
256
  }
238
257
 
239
258
  const finish = () => {
240
259
  if (done) return
241
260
  done = true
242
- clearIdle()
261
+ idle.dispose()
243
262
  // Kembalikan batas listener warisan (lihat prevMaxListeners): warning
244
263
  // MaxListenersExceeded kembali berguna setelah sesi ini selesai.
245
264
  try {
@@ -266,18 +285,6 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
266
285
  }
267
286
  }
268
287
 
269
- resetIdle = () => {
270
- if (done) return
271
- clearIdle()
272
- idleTimer = setTimeout(() => {
273
- finish()
274
- }, 90_000)
275
- // Jangan tahan process hidup hanya karena timer ini.
276
- try {
277
- ;(idleTimer as unknown as { unref?: () => void }).unref?.()
278
- } catch {}
279
- }
280
-
281
288
  const runAction = (fn: () => Promise<void>) =>
282
289
  (async () => {
283
290
  if (busy) return
@@ -303,26 +310,8 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
303
310
  * akhirnya selesai diabaikan hasilnya (tanpa resolve ganda — resolve
304
311
  * hanya lewat finish alur normal). Bisa dioverride test via opts.
305
312
  */
306
- const withWatchdog = async <T>(fn: () => Promise<T> | T): Promise<T> => {
307
- const ms = opts.actionTimeoutMs ?? 60_000
308
- let timer: ReturnType<typeof setTimeout> | undefined
309
- const p = Promise.resolve().then(fn)
310
- // Rejection telat TANPA handler = unhandledRejection (bun: crash).
311
- p.catch(() => {})
312
- try {
313
- return await Promise.race([
314
- p,
315
- new Promise<never>((_, reject) => {
316
- timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
317
- try {
318
- ;(timer as unknown as { unref?: () => void }).unref?.()
319
- } catch {}
320
- }),
321
- ])
322
- } finally {
323
- if (timer) clearTimeout(timer)
324
- }
325
- }
313
+ const withWatchdog = <T>(fn: () => Promise<T> | T): Promise<T> =>
314
+ withTimeout(fn, opts.actionTimeoutMs ?? 60_000)
326
315
 
327
316
  const loadRowsSafe = async () => {
328
317
  try {
@@ -486,44 +475,51 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
486
475
  if (busy) return true
487
476
  busy = true
488
477
  suspend()
489
- // Alur: picker effort DULU, baru select+simpan. Dibalik (select
490
- // dulu) akan butuh rollback saat Esc — dipilih yang tanpa rollback:
491
- // Esc = batal total, kembali ke daftar tanpa select/simpan.
478
+ // B4 (audit UI/UX): Enter = SATU langkah — pilih & simpan model
479
+ // langsung. Picker effort tidak lagi langkah wajib tiap Enter
480
+ // (dulu: Esc di effort = batal total, dua tekan untuk ganti model).
481
+ // Effort kini aksi terpisah lewat Tab (lihat cabang `tab` di bawah).
482
+ ;(async () => {
483
+ try {
484
+ await withWatchdog(() => opts.onSelect(row.id))
485
+ finish()
486
+ } catch (e) {
487
+ // Pilih model yang gagal HARUS terlihat dan kembali ke daftar
488
+ // untuk retry (pola resume() seperti a/d/e provider-manager),
489
+ // bukan menutup manager dan kehilangan konteks daftar.
490
+ // Pesan controller = input tak terpercaya: sanitasi.
491
+ notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
492
+ busy = false
493
+ await loadRowsSafe()
494
+ resume()
495
+ }
496
+ })()
497
+ return true
498
+ } else if (item.key.type === "tab") {
499
+ // B4: ubah thinking effort TANPA mengganti model. Tab = aksi
500
+ // eksplisit (bukan langkah wajib), Esc pada picker = batal dan
501
+ // kembali ke daftar — manajer tidak pernah menutup diri di sini.
502
+ const row = viewRows()[sel]
503
+ if (!row || busy || !opts.onSetEffort) return true
504
+ busy = true
505
+ suspend()
492
506
  ;(async () => {
493
507
  try {
494
508
  const picked = await pickEffort(row.id)
495
- if (!picked) {
496
- busy = false
497
- await loadRowsSafe()
498
- resume()
499
- return
509
+ if (picked && picked !== "skip") {
510
+ await withWatchdog(() => opts.onSetEffort!(row.id, picked))
511
+ // Notice terlihat di daftar (manager tetap terbuka) —
512
+ // inilah kehidupan baru `effort.saved` setelah A5.
513
+ notice = t("effort.saved", { effort: picked })
500
514
  }
501
- try {
502
- await withWatchdog(() => opts.onSelect(row.id))
503
- // "skip" = model tanpa thinking: select langsung, effort
504
- // tersimpan tak disentuh (aman — pengiriman effort juga
505
- // di-gate per keluarga, jadi nilai basi tak pernah terkirim).
506
- if (picked !== "skip" && opts.onSetEffort) {
507
- await withWatchdog(() => opts.onSetEffort!(row.id, picked))
508
- // Struk via notice (rute yang sama dengan receipts lain);
509
- // manager langsung tutup sesudahnya, jadi baris ini hanya
510
- // terlihat bila alur berubah me-resume — badge effort di
511
- // daftar tetap sumber kebenaran yang bisa dibuka ulang.
512
- notice = t("effort.saved", { effort: picked })
513
- }
514
- finish()
515
- } catch (e) {
516
- // Pilih model yang gagal HARUS terlihat dan kembali ke daftar
517
- // untuk retry (pola resume() seperti a/d/e provider-manager),
518
- // bukan menutup manager dan kehilangan konteks daftar.
519
- // Pesan controller = input tak terpercaya: sanitasi.
520
- notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
521
- busy = false
522
- await loadRowsSafe()
523
- resume()
524
- }
525
- } catch {
526
- finish()
515
+ busy = false
516
+ await loadRowsSafe()
517
+ resume()
518
+ } catch (e) {
519
+ notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
520
+ busy = false
521
+ await loadRowsSafe()
522
+ resume()
527
523
  }
528
524
  })()
529
525
  return true
@@ -548,7 +544,7 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
548
544
  }
549
545
  const managerPump = createKeyStreamPump({ state: decoder, onKeys: handleManagerKeys })
550
546
  const onData = (chunk: Buffer) => {
551
- resetIdle()
547
+ idle.reset()
552
548
  try {
553
549
  managerPump.push(chunk)
554
550
  } catch {
@@ -566,7 +562,7 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
566
562
  process.stdin.on("data", onData)
567
563
  process.stdout.on("resize", onResize)
568
564
  attached = true
569
- resetIdle()
565
+ idle.reset()
570
566
  render()
571
567
  } catch (e) {
572
568
  // Setup gagal = tutup + BERSUARA (Fase D): jendela kosong bisu adalah
@@ -575,7 +571,13 @@ export async function runModelManagerView(opts: ModelManagerViewOptions): Promis
575
571
  finish()
576
572
  } catch {}
577
573
  try {
578
- console.log(`⚠ ${t("model.failOpen", { msg: String((e as Error)?.message ?? e) })}`)
574
+ // Pesan error bisa memuat body jaringan (tak-terpercaya): sanitasi
575
+ // sebelum ditulis ke stdout agar escape tak membersihkan layar.
576
+ console.log(
577
+ `⚠ ${t("model.failOpen", {
578
+ msg: cleanUntrusted(String((e as Error)?.message ?? e), !!process.stdout.isTTY),
579
+ })}`,
580
+ )
579
581
  } catch {}
580
582
  }
581
583
  })
@@ -8,12 +8,14 @@ import {
8
8
  type DecoderState,
9
9
  toGraphemes,
10
10
  } from "../input/prompt-engine.ts"
11
- import { sanitizeAnsiLine } from "../render/sanitize.ts"
11
+ import { hintLine } from "../render/hint.ts"
12
+ import { cleanUntrusted, sanitizeAnsiLine } from "../render/sanitize.ts"
12
13
  import { c, stripAnsi } from "../render/theme.ts"
13
14
  import { displayWidth, truncateToWidth } from "../render/width.ts"
14
15
  import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
15
16
  import { beginInteractiveScreen } from "../runtime/statusline.ts"
16
17
  import { boxLeftPad, dialogBox } from "./dialog.ts"
18
+ import { createIdleTimer } from "./lifecycle.ts"
17
19
 
18
20
  export interface PickerItem {
19
21
  name: string
@@ -87,9 +89,10 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
87
89
  // dicetak — keduanya membungkus dan merusak tampilan.
88
90
  const visibleRows = () => {
89
91
  const rows = process.stdout.rows || 24
90
- // Modal tanpa judul/footer; sisakan border dan baris pencarian bila ada.
91
- if (useModal) return Math.max(1, Math.min(rows - (isFilterable ? 3 : 2), 12))
92
- const chrome = isFilterable ? 3 : 2
92
+ // Modal tanpa judul/footer dekoratif; sisakan border, baris pencarian
93
+ // (bila ada), DAN satu baris hint aksi di dasar.
94
+ if (useModal) return Math.max(1, Math.min(rows - (isFilterable ? 4 : 3), 12))
95
+ const chrome = isFilterable ? 4 : 3
93
96
  return Math.max(1, Math.min(rows - chrome, 12))
94
97
  }
95
98
  // Lebar konten = lebar kotak TETAP (min=max, keputusan rasa: geometri
@@ -98,10 +101,18 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
98
101
  const width = () =>
99
102
  Math.max(8, Math.min((process.stdout.columns || 80) - 2 - 4, PICKER_BOX_W - 4))
100
103
 
101
- // Isi untuk dialog popup (tanpa judul/hint — dialog yang membingkai).
104
+ // Isi untuk dialog popup (tanpa judul; hint aksi satu baris di dasar).
102
105
  const bodyLines = (): string[] => {
103
106
  const items = filteredItems()
104
107
  const v = visibleRows()
108
+ // Hint minimalis: kunci terang, label redup (satu sumber `hintLine`).
109
+ // Selalu tampil agar navigasi tak perlu ditebak; tidak memakan tinggi
110
+ // daftar karena `visibleRows` sudah menyisihkan satu baris untuknya.
111
+ const hint = hintLine([
112
+ { key: "↑↓", label: t("hint.move") },
113
+ { key: "Enter", label: t("hint.select") },
114
+ { key: "Esc", label: t("hint.close") },
115
+ ])
105
116
  if (sel >= items.length) sel = Math.max(0, items.length - 1)
106
117
  if (sel < 0) sel = 0
107
118
  if (sel < scroll) scroll = sel
@@ -118,6 +129,7 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
118
129
  }
119
130
  if (items.length === 0) {
120
131
  lines.push(cut(dim(` ${t("pick.noMatch", { q: sanitizeAnsiLine(filter) })}`)))
132
+ lines.push(cut(hint))
121
133
  return lines
122
134
  }
123
135
  for (let i = 0; i < rows.length; i++) {
@@ -133,7 +145,8 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
133
145
  if (picked) lines.push(` ${c.accent("›")} ${c.accent(c.bold(label))}`)
134
146
  else lines.push(` ${dim(label)}`)
135
147
  }
136
- return lines.slice(0, v + (isFilterable ? 1 : 0))
148
+ lines.push(cut(hint))
149
+ return lines
137
150
  }
138
151
 
139
152
  const render = () => {
@@ -180,23 +193,16 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
180
193
  // 133 dtk idle di picker). Timer idle 90 dtk auto-batal agar raw-mode
181
194
  // tidak digenggam selamanya — tanpa ini picker bisa crash Bun sebelum
182
195
  // user menekan apa pun. Bukan perubahan perilaku: idle sepanjang itu
183
- // memang harusnya batal.
184
- let idleTimer: ReturnType<typeof setTimeout> | undefined
185
- const resetIdle = () => {
186
- if (idleTimer) clearTimeout(idleTimer)
187
- idleTimer = setTimeout(() => {
196
+ // memang harusnya batal. Satu sumber idle via helper bersama (audit D1).
197
+ // `cleanup`/`resolve` dirujuk sebagai closure (dievaluasi saat timer fire).
198
+ const idle = createIdleTimer({
199
+ cancelMs: 90_000,
200
+ onCancel: () => {
188
201
  cleanup()
189
202
  opts.onCancel()
190
203
  resolve()
191
- }, 90_000)
192
- // jangan tahan process tetap hidup hanya karena timer ini
193
- if (
194
- idleTimer &&
195
- typeof (idleTimer as unknown as { unref?: () => void }).unref === "function"
196
- ) {
197
- ;(idleTimer as unknown as { unref: () => void }).unref!()
198
- }
199
- }
204
+ },
205
+ })
200
206
  const decoder: DecoderState = createDecoderState()
201
207
  // Seperti manager: simpan batas listener warisan (guard: stdin stub test
202
208
  // tak punya getMaxListeners), kembalikan di cleanup agar warning Node
@@ -240,7 +246,7 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
240
246
  try {
241
247
  process.stdin.setMaxListeners(prevMaxListeners)
242
248
  } catch {}
243
- if (idleTimer) clearTimeout(idleTimer)
249
+ idle.dispose()
244
250
  // Lepas kepemilikan layar: painter boleh melukis lagi setelah ini
245
251
  // (kursor sudah kembali ke anchor, overlay sudah dibersihkan).
246
252
  endScreen()
@@ -394,7 +400,7 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
394
400
  const pickerPump = createKeyStreamPump({ state: decoder, onKeys: handlePickerKeys })
395
401
 
396
402
  onData = (chunk: Buffer) => {
397
- resetIdle()
403
+ idle.reset()
398
404
  try {
399
405
  pickerPump.push(chunk)
400
406
  } catch (e) {
@@ -406,7 +412,11 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
406
412
  cleanup()
407
413
  } catch {}
408
414
  try {
409
- console.log(`⚠ ${t("pick.fail", { msg: String((e as Error)?.message ?? e) })}`)
415
+ console.log(
416
+ `⚠ ${t("pick.fail", {
417
+ msg: cleanUntrusted(String((e as Error)?.message ?? e), !!process.stdout.isTTY),
418
+ })}`,
419
+ )
410
420
  } catch {}
411
421
  try {
412
422
  opts.onCancel()
@@ -424,7 +434,7 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
424
434
  process.stdin.setMaxListeners(0)
425
435
  process.stdin.on("data", onData)
426
436
  process.stdout.on("resize", onResize)
427
- resetIdle()
437
+ idle.reset()
428
438
  render()
429
439
  } catch (e) {
430
440
  // Sama seperti di atas: setup gagal (raw-mode ConPTY rusak) harus
@@ -434,7 +444,11 @@ export async function runPicker(opts: PickerOptions): Promise<void> {
434
444
  cleanup()
435
445
  } catch {}
436
446
  try {
437
- console.log(`⚠ ${t("pick.failOpen", { msg: String((e as Error)?.message ?? e) })}`)
447
+ console.log(
448
+ `⚠ ${t("pick.failOpen", {
449
+ msg: cleanUntrusted(String((e as Error)?.message ?? e), !!process.stdout.isTTY),
450
+ })}`,
451
+ )
438
452
  } catch {}
439
453
  try {
440
454
  opts.onCancel()
@@ -9,18 +9,24 @@ import {
9
9
  type DecodedKey,
10
10
  type DecoderState,
11
11
  } from "../input/prompt-engine.ts"
12
- import { sanitizeAnsiLine } from "../render/sanitize.ts"
12
+ import { hintLine } from "../render/hint.ts"
13
+ import { cleanUntrusted, sanitizeAnsiLine } from "../render/sanitize.ts"
13
14
  import { c, glyphs, stripAnsi } from "../render/theme.ts"
14
15
  import { truncateToWidth } from "../render/width.ts"
15
16
  import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
16
17
  import { boxLeftPad, dialogBox } from "./dialog.ts"
17
18
  import { runForm, validateRequired, validateUrl } from "./form.ts"
19
+ import { createIdleTimer } from "./lifecycle.ts"
18
20
  import { runPicker } from "./picker.ts"
21
+ import { withTimeout } from "./watchdog.ts"
19
22
 
20
23
  const dim = (s: string): string => c.dim(s)
21
24
 
22
25
  /** Lebar tetap popup provider setelah daftar diringkas ke nama provider. */
23
- const PROVIDER_BOX_W = 52
26
+ /** Lebar kotak dialog /providers: TETAP 64 kolom — paritas picker/model/wizard
27
+ * (audit B3: 52 terlalu sempit; nama provider/ID panjang + baris hint aksi
28
+ * terpotong). Geometri tetap (min=max), tak pernah melompat mengikuti konten. */
29
+ const PROVIDER_BOX_W = 64
24
30
 
25
31
  export interface ProviderRow {
26
32
  id: string
@@ -90,7 +96,11 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
90
96
  // kemungkinan notice tetap masuk ke perhitungan tinggi.
91
97
  const visibleRows = () => {
92
98
  const rows = process.stdout.rows || 24
93
- return Math.max(1, Math.min(rows - 3, 14))
99
+ // Chrome tetap: 2 border + 1 baris hint aksi; notice (transient)
100
+ // menyusutkan daftar satu baris — paritas model-manager, agar hint
101
+ // tak pernah jadi korban potong atas dialogBox.
102
+ const fixed = 3 + (notice ? 1 : 0)
103
+ return Math.max(1, Math.min(rows - fixed, 14))
94
104
  }
95
105
  // Lebar konten = lebar kotak TETAP (min=max, paritas picker/model) —
96
106
  // dikurangi chrome dialog (lihat picker.ts).
@@ -124,12 +134,25 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
124
134
  }
125
135
  // Struk transient (jalur legacy maupun modal).
126
136
  if (notice) lines.push(cut(dim(sanitizeAnsiLine(notice))))
137
+ // Hint aksi minimalis (kunci terang, label redup) — paritas /model.
138
+ lines.push(
139
+ cut(
140
+ hintLine([
141
+ { key: "Enter", label: t("hint.select") },
142
+ { key: "a", label: t("hint.add") },
143
+ { key: "e", label: t("hint.edit") },
144
+ { key: "d", label: t("hint.delete") },
145
+ { key: "Esc", label: t("hint.close") },
146
+ ]),
147
+ ),
148
+ )
127
149
  return lines
128
150
  }
129
151
 
130
152
  const render = () => {
131
153
  // Popup komposit: HANYA region kotak (tanpa clear) di atas konten
132
- // pemilik layar. Lebar tetap 52 agar daftar tidak kosong terlalu lebar.
154
+ // pemilik layar. Lebar TETAP 64 (min=max, paritas picker/model) —
155
+ // tak pernah melompat mengikuti konten.
133
156
  const box = dialogBox(
134
157
  {
135
158
  title: "",
@@ -172,13 +195,20 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
172
195
  let busy = false
173
196
  // Idle-timeout 90 dtk seperti picker/model-manager: tanpa ini raw-mode
174
197
  // digenggam selamanya bila stdin 'data' tak pernah datang di Windows
175
- // (ConPTY macet) = "masuk list macet". Timer di-unref agar tak menahan exit.
176
- let idleTimer: ReturnType<typeof setTimeout> | undefined
177
- const clearIdle = () => {
178
- if (idleTimer) clearTimeout(idleTimer)
179
- idleTimer = undefined
180
- }
181
- let resetIdle: () => void = () => {}
198
+ // (ConPTY macet) = "masuk list macet". Timer di-unref agar tak menahan
199
+ // exit — satu sumber idle via helper bersama (audit D1). `cleanup`
200
+ // dirujuk sebagai closure (dievaluasi saat timer fire).
201
+ const idle = createIdleTimer({
202
+ cancelMs: 90_000,
203
+ onCancel: () => {
204
+ try {
205
+ cleanup()
206
+ } catch {}
207
+ try {
208
+ resolve()
209
+ } catch {}
210
+ },
211
+ })
182
212
  /** Listener stdin terpasang? Menjaga resume() idempoten (anti-ganda). */
183
213
  let attached = false
184
214
 
@@ -186,7 +216,7 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
186
216
  // di a/d/e). Tidak menyentuh `done` - manager tetap hidup; resume()
187
217
  // menggambar ulang region popup.
188
218
  const suspend = () => {
189
- clearIdle()
219
+ idle.clear()
190
220
  attached = false
191
221
  process.stdout.write("\x1b[0m\x1b[?25h")
192
222
  // setRawMode dibungkus try/catch: di Windows handle bisa rusak dan
@@ -223,14 +253,14 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
223
253
  attached = true
224
254
  }
225
255
  render()
226
- resetIdle()
256
+ idle.reset()
227
257
  }
228
258
  // Close final: suspend + tandai selesai (manager tidak bisa dibuka lagi).
229
259
  // Selalu resolve walau suspend melempar — tanpa try/finally Promise gantung.
230
260
  const cleanup = () => {
231
261
  if (done) return
232
262
  done = true
233
- clearIdle()
263
+ idle.dispose()
234
264
  try {
235
265
  providerPump.dispose()
236
266
  } catch {}
@@ -249,23 +279,6 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
249
279
  } catch {}
250
280
  }
251
281
 
252
- resetIdle = () => {
253
- if (done) return
254
- clearIdle()
255
- idleTimer = setTimeout(() => {
256
- // Idle 90 dtk tanpa input = batal otomatis (samakan picker).
257
- try {
258
- cleanup()
259
- } catch {}
260
- try {
261
- resolve()
262
- } catch {}
263
- }, 90_000)
264
- try {
265
- ;(idleTimer as unknown as { unref?: () => void }).unref?.()
266
- } catch {}
267
- }
268
-
269
282
  // SEMUA aksi a/d/e lewat sini: busy guard + suspend, lalu SELALU resume di
270
283
  // finally. Tanpa finally, exception di onAdd/askLine (atau loadRows) membuat
271
284
  // busy tetap true → onData menolak semua input → manager terkunci selamanya.
@@ -292,26 +305,8 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
292
305
  * pulih; aksi telat yang akhirnya selesai diabaikan hasilnya. Tunggu
293
306
  * interaksi user (form/picker) TIDAK dibatasi — hanya await jaringan.
294
307
  */
295
- const withWatchdog = async <T>(fn: () => Promise<T> | T): Promise<T> => {
296
- const ms = opts.actionTimeoutMs ?? 60_000
297
- let timer: ReturnType<typeof setTimeout> | undefined
298
- const p = Promise.resolve().then(fn)
299
- // Rejection telat TANPA handler = unhandledRejection (bun: crash).
300
- p.catch(() => {})
301
- try {
302
- return await Promise.race([
303
- p,
304
- new Promise<never>((_, reject) => {
305
- timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
306
- try {
307
- ;(timer as unknown as { unref?: () => void }).unref?.()
308
- } catch {}
309
- }),
310
- ])
311
- } finally {
312
- if (timer) clearTimeout(timer)
313
- }
314
- }
308
+ const withWatchdog = <T>(fn: () => Promise<T> | T): Promise<T> =>
309
+ withTimeout(fn, opts.actionTimeoutMs ?? 60_000)
315
310
 
316
311
  const doAdd = () => {
317
312
  if (busy) return
@@ -400,7 +395,10 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
400
395
  if (res.ok) notice = `${glyphs.check} ${sanitizeAnsiLine(res.ok)}`
401
396
  else if (res.err) notice = `${glyphs.cross} ${sanitizeAnsiLine(res.err)}`
402
397
  } catch (e) {
403
- notice = `${glyphs.cross} ${(e as Error).message}`
398
+ // Pesan error jaringan/controller = input tak-terpercaya: tanpa
399
+ // sanitasi, body provider bisa menyuntik `ESC[2J` ke popup dan
400
+ // menghapus layar TUI (audit 2026-11-12, MEDIUM-2).
401
+ notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
404
402
  } finally {
405
403
  busy = false
406
404
  await reload().catch(() => {})
@@ -600,7 +598,7 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
600
598
  }
601
599
  const providerPump = createKeyStreamPump({ state: decoder, onKeys: handleProviderKeys })
602
600
  const onData = (chunk: Buffer) => {
603
- resetIdle()
601
+ idle.reset()
604
602
  try {
605
603
  providerPump.push(chunk)
606
604
  } catch {
@@ -623,7 +621,7 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
623
621
  process.stdin.on("data", onData)
624
622
  process.stdout.on("resize", onResize)
625
623
  attached = true
626
- resetIdle()
624
+ idle.reset()
627
625
  render()
628
626
  } catch (e) {
629
627
  // Setup gagal = tutup + BERSUARA (Fase D): jendela kosong bisu adalah
@@ -632,7 +630,12 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
632
630
  cleanup()
633
631
  } catch {}
634
632
  try {
635
- console.log(`⚠ ${t("prov.failOpen", { msg: String((e as Error)?.message ?? e) })}`)
633
+ // Pesan setup gagal (bisa memuat body jaringan) = teks tak-terpercaya.
634
+ console.log(
635
+ `⚠ ${t("prov.failOpen", {
636
+ msg: cleanUntrusted(String((e as Error)?.message ?? e), !!process.stdout.isTTY),
637
+ })}`,
638
+ )
636
639
  } catch {}
637
640
  try {
638
641
  resolve()
@@ -0,0 +1,27 @@
1
+ // Batas waktu aksi jaringan (deteksi model, save/delete provider/model, submit
2
+ // wizard). Provider/tool non-kooperatif yang gantung selamanya membuat popup
3
+ // mati (suspend tanpa listener/timer, raw-mode digenggam) — timeout = error
4
+ // jujur + UI pulih; aksi telat yang akhirnya selesai diabaikan hasilnya.
5
+ //
6
+ // Dipakai bersamaan oleh picker/model-manager/provider-manager/wizard sehingga
7
+ // semantik timeout TIDAK drift antar jendela (dulu tiga salinan nyaris identik
8
+ // yang berisiko melenceng per permukaan — kelas OAP-001).
9
+ import { t } from "../i18n/locale.ts"
10
+
11
+ export function withTimeout<T>(fn: () => Promise<T> | T, ms: number): Promise<T> {
12
+ let timer: ReturnType<typeof setTimeout> | undefined
13
+ const pending = Promise.resolve().then(fn)
14
+ // Rejection telat TANPA handler = unhandledRejection (Bun: crash proses).
15
+ pending.catch(() => {})
16
+ return Promise.race([
17
+ pending,
18
+ new Promise<never>((_, reject) => {
19
+ timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
20
+ try {
21
+ ;(timer as unknown as { unref?: () => void }).unref?.()
22
+ } catch {}
23
+ }),
24
+ ]).finally(() => {
25
+ if (timer) clearTimeout(timer)
26
+ })
27
+ }