minicode-ai 0.22.0 → 0.25.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 (100) hide show
  1. package/README.md +2 -2
  2. package/cli/commands.ts +10 -0
  3. package/cli/index.ts +11 -0
  4. package/cli/setup.ts +64 -33
  5. package/cli/tui.ts +29 -3
  6. package/docs/README.md +2 -2
  7. package/docs/SUMMARY.md +10 -19
  8. package/docs/TERMINAL_CONTRACT.md +119 -32
  9. package/docs/architecture.md +1 -1
  10. package/docs/autonomous-scheduler.md +283 -2
  11. package/docs/choosing-mode.md +4 -4
  12. package/docs/concepts.md +39 -3
  13. package/docs/config.md +90 -4
  14. package/docs/environment.md +6 -0
  15. package/docs/getting-started.md +58 -2
  16. package/docs/repl.md +1 -1
  17. package/docs/security.md +49 -2
  18. package/docs/tools.md +2 -1
  19. package/package.json +2 -36
  20. package/src/app/provider-layer.ts +1 -1
  21. package/src/app/session.ts +129 -20
  22. package/src/config.ts +102 -2
  23. package/src/constants.ts +32 -4
  24. package/src/lib/safe-open.ts +21 -12
  25. package/src/memory/vector.ts +0 -31
  26. package/src/policy/compaction.ts +27 -0
  27. package/src/policy/context-budget.ts +132 -0
  28. package/src/policy/context-escalation.ts +140 -0
  29. package/src/policy/context-window.ts +14 -9
  30. package/src/policy/context.ts +10 -1
  31. package/src/policy/microcompact.ts +162 -0
  32. package/src/policy/no-progress.ts +1 -1
  33. package/src/policy/permission.ts +5 -0
  34. package/src/policy/scrub.ts +15 -2
  35. package/src/policy/tool-contract.ts +11 -9
  36. package/src/presentation/reducer.ts +1 -0
  37. package/src/providers/anthropic.ts +17 -3
  38. package/src/providers/detect.ts +155 -13
  39. package/src/providers/provision.ts +92 -1
  40. package/src/providers/responses.ts +13 -1
  41. package/src/session/persistence.ts +56 -0
  42. package/src/task/autonomous-policy.ts +7 -0
  43. package/src/task/graph-validate.ts +1 -1
  44. package/src/task/session-authority.ts +0 -5
  45. package/src/task/store.ts +0 -4
  46. package/src/tools/ask_user.ts +14 -1
  47. package/src/tools/bash.ts +57 -9
  48. package/src/tools/context.ts +10 -0
  49. package/src/tools/delete_file.ts +3 -2
  50. package/src/tools/edit.ts +5 -4
  51. package/src/tools/git.ts +70 -12
  52. package/src/tools/glob.ts +13 -5
  53. package/src/tools/grep.ts +26 -10
  54. package/src/tools/index.ts +3 -2
  55. package/src/tools/lsp.ts +15 -9
  56. package/src/tools/move_file.ts +4 -3
  57. package/src/tools/patch.ts +5 -4
  58. package/src/tools/read_file.ts +3 -2
  59. package/src/tools/read_image.ts +3 -2
  60. package/src/tools/task.ts +1 -0
  61. package/src/tools/todo.ts +4 -8
  62. package/src/tools/write_file.ts +4 -3
  63. package/src/ui/approval/prompt.ts +226 -77
  64. package/src/ui/assistant/simple.ts +1 -1
  65. package/src/ui/footer.ts +41 -29
  66. package/src/ui/i18n/en.ts +23 -4
  67. package/src/ui/i18n/id.ts +25 -4
  68. package/src/ui/input/input.ts +2 -2
  69. package/src/ui/render/activity-group.ts +1 -0
  70. package/src/ui/render/activity-panel.ts +21 -3
  71. package/src/ui/render/hint.ts +28 -0
  72. package/src/ui/render/ledger.ts +1 -9
  73. package/src/ui/render/logo.ts +86 -0
  74. package/src/ui/render/markdown-table.ts +0 -3
  75. package/src/ui/render/session-summary.ts +22 -1
  76. package/src/ui/render/table-grid.ts +0 -3
  77. package/src/ui/render/theme.ts +36 -5
  78. package/src/ui/runtime/screen.ts +11 -3
  79. package/src/ui/screens/dialog.ts +45 -81
  80. package/src/ui/screens/form.ts +29 -33
  81. package/src/ui/screens/lifecycle.ts +80 -0
  82. package/src/ui/screens/model-manager.ts +84 -91
  83. package/src/ui/screens/picker.ts +36 -33
  84. package/src/ui/screens/provider-manager.ts +50 -59
  85. package/src/ui/screens/watchdog.ts +27 -0
  86. package/src/ui/screens/wizard.ts +3 -20
  87. package/src/ui/tui/app.ts +97 -11
  88. package/src/ui/tui/transcript.ts +55 -16
  89. package/vendor/minicore/src/core/compact.ts +10 -0
  90. package/vendor/minicore/src/core/errors.ts +11 -1
  91. package/vendor/minicore/src/core/executor.ts +6 -1
  92. package/vendor/minicore/src/core/loop.ts +92 -2
  93. package/vendor/minicore/src/core/session.ts +8 -0
  94. package/vendor/minicore/src/providers/openai-compat.ts +15 -2
  95. package/docs/P14_OPEN_WORK.md +0 -290
  96. package/docs/config-providers.md +0 -87
  97. package/docs/glossary.md +0 -39
  98. package/docs/quickstart.md +0 -60
  99. package/docs/security-model.md +0 -96
  100. package/docs/terminal.md +0 -91
@@ -1,9 +1,7 @@
1
- // Bingkai dialog modal: backdrop + kotak terpusat (border, judul, bayangan).
2
- //
3
- // View membangun KONTEN (state + tombol, seperti sekarang); dialog.ts hanya
4
- // menata konten menjadi frame SELAYAR (`rows` baris tepat) untuk `screen.paint`.
5
- // Teks disanitasi satu-baris + potong per kolom di sini (defense-in-depth di
6
- // atas sanitasi view — idempoten, murah). Fallback ASCII bila MINICODE_ASCII=1.
1
+ // Kotak dialog: border, judul, footer, terpusat. View membangun KONTEN; di
2
+ // sini konten ditata jadi baris kotak (paintRegion melukis region-nya saja).
3
+ // Teks disanitasi + dipotong per kolom (defense-in-depth, idempoten). ASCII
4
+ // bila MINICODE_ASCII=1.
7
5
 
8
6
  import { t } from "../i18n/locale.ts"
9
7
  import { sanitizeAnsiLine } from "../render/sanitize.ts"
@@ -13,27 +11,17 @@ import { displayWidth, padToWidth, truncateToWidth } from "../render/width.ts"
13
11
  export interface DialogSpec {
14
12
  /** Judul baris atas. String kosong = tanpa baris judul (chrome menyesuaikan). */
15
13
  title: string
16
- /** Baris konten polos (sudah di-clamp view; di sini dipotong defensif). */
14
+ /** Baris konten polos. */
17
15
  body: string[]
18
16
  /** Baris hint bawah (tombol). Kosong = tanpa footer. */
19
17
  footer?: string
20
- /** Lebar kotak maksimum (inklusif border+padding). Default: selebar layar. */
18
+ /** Lebar maksimum (inklusif border+padding). Default: popup terhitung. */
21
19
  maxWidth?: number
22
- /**
23
- * Lebar kotak MINIMUM (inklusif border+padding): kotak tak pernah lebih
24
- * sempit dari ini walau konten pendek — geometri stabil, tak melompat
25
- * mengikuti data (keputusan rasa: presisi). Samakan dengan maxWidth untuk
26
- * lebar TETAP.
27
- */
20
+ /** Lebar MINIMUM (inklusif border+padding). Default: skala dari `cols`. */
28
21
  minWidth?: number
29
- /** Tinggi kotak maksimum (inklusif border). Default: setinggi layar. */
22
+ /** Tinggi maksimum (inklusif border). Default: setinggi layar. */
30
23
  maxHeight?: number
31
- /**
32
- * Indeks body (0-based) yang WAJIB terlihat, mis. field aktif form. Bila
33
- * body melebihi tinggi kotak, jendela digeser agar baris ini ikut tampil —
34
- * tanpa ini user mengetik ke field yang tidak ada di layar (audit
35
- * 2026-11-12, HIGH-2).
36
- */
24
+ /** Indeks body yang WAJIB terlihat; jendela digeser agar tak mengetik buta (HIGH-2). */
37
25
  focusRow?: number
38
26
  }
39
27
 
@@ -46,14 +34,24 @@ interface BoxChars {
46
34
  v: string
47
35
  }
48
36
 
37
+ /** Lebar kotak popup: skala dari layar; pemanggil membekukan saat mount. */
38
+ export function popupBoxWidth(cols: number): number {
39
+ const safeCols = Math.max(10, cols)
40
+ const scaled = Math.floor(safeCols * 0.6)
41
+ // Margin 4 kolom menang atas lantai 40 (AUD-011: `max(40,…)` dulu
42
+ // membungkus clamp sehingga terminal sempit overflow).
43
+ const room = safeCols - 4
44
+ return Math.min(Math.max(40, Math.min(88, scaled)), room)
45
+ }
46
+
49
47
  function boxChars(): BoxChars {
50
- // supportsUtf8() dibaca TIAP paint (getter runtime, bukan cache module) —
51
- // aturan yang sama dengan c/glyphs (theme.ts).
52
- // Tanpa bayangan: kolom `▓` redup terlihat seperti strip berpasir di
53
- // Windows Terminal (keluhan visual nyata) — kedalaman diganti backdrop
54
- // redup + kotak terpusat saja.
55
- if (!supportsUtf8()) return { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" }
56
- return { tl: "┌", tr: "┐", bl: "└", br: "┘", h: "─", v: "│" }
48
+ // Kapabilitas dan kill-switch dibaca tiap render agar perubahan env runtime
49
+ // (terutama test/aksesibilitas) langsung berlaku, bukan membeku saat import.
50
+ const style = process.env.MINICODE_BOX?.toLowerCase()
51
+ if (process.env.MINICODE_ASCII === "1" || style === "ascii" || !supportsUtf8())
52
+ return { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" }
53
+ if (style === "square") return { tl: "┌", tr: "┐", bl: "└", br: "┘", h: "─", v: "│" }
54
+ return { tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│" }
57
55
  }
58
56
 
59
57
  /** Kotak popup tanpa backdrop: untuk paintRegion di atas konten pemilik layar. */
@@ -87,11 +85,7 @@ export function boxLeftPad(strippedLine: string): number {
87
85
  return m ? m[0].length : 0
88
86
  }
89
87
 
90
- /**
91
- * Bangun KOTAK saja (tanpa backdrop): dipakai popup komposit App TUI lewat
92
- * paintRegion — transkrip di belakang tetap tampil. Lebar mengikuti konten
93
- * (clamp maxWidth); tinggi mengikuti body (clamp maxHeight).
94
- */
88
+ /** Bangun KOTAK saja (tanpa backdrop); minWidth==maxWidth = lebar beku. */
95
89
  export function dialogBox(spec: DialogSpec, cols: number, rows: number): DialogBox {
96
90
  const c0 = Math.max(20, Math.floor(cols) || 80)
97
91
  const r0 = Math.max(5, Math.floor(rows) || 24)
@@ -99,19 +93,22 @@ export function dialogBox(spec: DialogSpec, cols: number, rows: number): DialogB
99
93
  const title = sanitizeAnsiLine(spec.title)
100
94
  const footer = spec.footer != null && spec.footer !== "" ? sanitizeAnsiLine(spec.footer) : null
101
95
 
102
- // Lebar dalam = konten terlebar, clamp ke layar. Chrome total per baris:
103
- // v(1) + sp(1) + innerW + sp(1) + v(1) = innerW + 4. View membangun baris
104
- // selebar itu (width() modal-aware) sehingga tak ada potong ulang di sini.
105
- // maxWidth opsional mengecilkan kotak (dialog mungil) — kurangi SEBELUM
106
- // hitung isi. Judul kosong = tanpa baris judul (chrome vertikal menyesuaikan).
107
96
  const hasTitle = title !== ""
108
- let innerMax = c0 - 2 - 4
109
- if (spec.maxWidth != null && Number.isFinite(spec.maxWidth))
110
- innerMax = Math.min(innerMax, Math.max(8, Math.floor(spec.maxWidth) - 4))
111
- if (innerMax < 8) innerMax = 8
112
- let innerMin = 8
113
- if (spec.minWidth != null && Number.isFinite(spec.minWidth))
114
- innerMin = Math.min(innerMax, Math.max(8, Math.floor(spec.minWidth) - 4))
97
+ const maxInner = Math.max(10, c0 - 6)
98
+ const def = Math.max(10, popupBoxWidth(c0) - 4)
99
+ const capInner = Math.min(
100
+ spec.maxWidth != null && Number.isFinite(spec.maxWidth)
101
+ ? Math.max(10, Math.floor(spec.maxWidth) - 4)
102
+ : def,
103
+ maxInner,
104
+ )
105
+ const floorInner = Math.min(
106
+ spec.minWidth != null && Number.isFinite(spec.minWidth)
107
+ ? Math.max(10, Math.floor(spec.minWidth) - 4)
108
+ : def,
109
+ capInner,
110
+ )
111
+
115
112
  let contentW = displayWidth(title)
116
113
  for (const ln of spec.body) {
117
114
  const w = displayWidth(sanitizeAnsiLine(ln))
@@ -121,21 +118,16 @@ export function dialogBox(spec: DialogSpec, cols: number, rows: number): DialogB
121
118
  const w = displayWidth(footer)
122
119
  if (w > contentW) contentW = w
123
120
  }
124
- const innerW = Math.min(Math.max(innerMin, contentW), innerMax)
121
+ const innerW = Math.max(10, Math.min(Math.max(contentW, floorInner), capInner, maxInner))
125
122
  const cut = (s: string) => truncateToWidth(sanitizeAnsiLine(s), innerW)
126
- // +2 border, +2 padding: "│ text │".
127
123
  const boxW = innerW + 4
128
- const row = (left: string, mid: string, right: string) => left + mid + right
124
+ const row = (l: string, m: string, r: string) => l + m + r
129
125
 
130
126
  const bar = box.h.repeat(Math.max(0, boxW - 2))
131
127
  const boxed: string[] = []
132
128
  boxed.push(row(box.tl, bar, box.tr))
133
- // Judul aksen (paritas visual dengan overlay inline); footer redup.
134
- // Judul kosong = baris judul dilewati seluruhnya (bukan baris kosong).
135
129
  if (hasTitle) boxed.push(`${box.v} ${padToWidth(c.accent(c.bold(cut(title))), innerW)} ${box.v}`)
136
- // Isi: chrome tetap = 2 border + (judul ? 1 : 0) + (footer ? 1 : 0); baris
137
- // marker ("… N more") ikut dihitung BILA terpotong. maxHeight opsional
138
- // membatasi tinggi KOTAK (bukan frame — padding backdrop menyerap sisa).
130
+
139
131
  const chromeFixed = 2 + (hasTitle ? 1 : 0) + (footer != null ? 1 : 0)
140
132
  const boxBudget =
141
133
  spec.maxHeight != null && Number.isFinite(spec.maxHeight)
@@ -144,10 +136,6 @@ export function dialogBox(spec: DialogSpec, cols: number, rows: number): DialogB
144
136
  const room = Math.max(0, boxBudget - chromeFixed)
145
137
  const clipped = spec.body.length > room
146
138
  const shown = clipped ? Math.max(0, room - 1) : spec.body.length
147
- // Jendela body: default dari atas, tapi bila pemanggil menandai baris fokus
148
- // (form: field aktif) jendela digeser agar baris itu terlihat. Tanpa ini
149
- // `activeRow` menunjuk baris di luar yang dirender sehingga kursor parkir di
150
- // marker/border dan ketikan user tak terlihat (audit 2026-11-12, HIGH-2).
151
139
  const focus = spec.focusRow
152
140
  const bodyStart =
153
141
  clipped && focus != null && shown > 0 && Number.isFinite(focus)
@@ -162,8 +150,6 @@ export function dialogBox(spec: DialogSpec, cols: number, rows: number): DialogB
162
150
  if (footer != null) boxed.push(`${box.v} ${padToWidth(c.dim(cut(footer)), innerW)} ${box.v}`)
163
151
  boxed.push(row(box.bl, bar, box.br))
164
152
 
165
- // Pusatkan horizontal; vertikal via topRow (1-based) untuk paintRegion.
166
- // displayWidth mengabaikan SGR (nol kolom) sehingga ANSI tak merusak hitungan.
167
153
  const topRow = Math.max(1, Math.floor((r0 - boxed.length) / 2) + 1)
168
154
  const lines = boxed.map((ln) => {
169
155
  const left = Math.max(0, Math.floor((c0 - displayWidth(ln)) / 2))
@@ -171,25 +157,3 @@ export function dialogBox(spec: DialogSpec, cols: number, rows: number): DialogB
171
157
  })
172
158
  return { lines, topRow, height: boxed.length, bodyTop: 1 + (hasTitle ? 1 : 0), bodyStart }
173
159
  }
174
-
175
- /**
176
- * Bangun frame SELAYAR: tepat `rows` string (backdrop redup + kotak terpusat).
177
- * Tak pernah melempar; tak menulis IO (view yang paint via screen).
178
- * Dipakai layar yang memiliki buffer sendiri (wizard first-run); popup di
179
- * atas konten App memakai dialogBox + paintRegion (tanpa clear).
180
- */
181
- export function dialogFrame(spec: DialogSpec, cols: number, rows: number): string[] {
182
- const c0 = Math.max(20, Math.floor(cols) || 80)
183
- const r0 = Math.max(5, Math.floor(rows) || 24)
184
- const box = dialogBox(spec, c0, r0)
185
- // Backdrop REDUP (bukan hitam polos): pola ░ faint memenuhi layar sehingga
186
- // kotak terbaca sebagai jendela di depan, bukan screen baru. Fallback ASCII
187
- // "." bila glyph shade tak didukung.
188
- const shade = supportsUtf8() ? "░".repeat(c0) : ".".repeat(c0)
189
- const dim = c.faint(shade)
190
- const out: string[] = []
191
- for (let i = 1; i < box.topRow; i++) out.push(dim)
192
- for (const ln of box.lines) out.push(ln)
193
- while (out.length < r0) out.push(dim)
194
- return out.slice(0, r0)
195
- }
@@ -19,10 +19,11 @@ import {
19
19
  toGraphemes,
20
20
  } from "../input/prompt-engine.ts"
21
21
  import { sanitizeAnsiLine } from "../render/sanitize.ts"
22
- import { c, stripAnsi } from "../render/theme.ts"
22
+ import { c, glyphs, stripAnsi } from "../render/theme.ts"
23
23
  import { displayWidth, truncateToWidth } from "../render/width.ts"
24
24
  import { type AltScreen, SYNC_UPDATE_END, SYNC_UPDATE_START } from "../runtime/screen.ts"
25
- import { boxLeftPad, dialogBox } from "./dialog.ts"
25
+ import { boxLeftPad, dialogBox, popupBoxWidth } from "./dialog.ts"
26
+ import { createIdleTimer } from "./lifecycle.ts"
26
27
 
27
28
  export interface FormField {
28
29
  id: string
@@ -78,8 +79,8 @@ interface FieldState {
78
79
 
79
80
  const dim = (s: string): string => c.dim(s)
80
81
 
81
- /** Lebar kotak form TETAP (keputusan rasa: geometri stabil). */
82
- const FORM_BOX_W = 64
82
+ /** Lebar kotak form: `popupBoxWidth` — paritas picker/model/provider (AUD-006). */
83
+ const formBoxWidth = (cols: number): number => popupBoxWidth(cols)
83
84
 
84
85
  function toState(def: FormField): FieldState {
85
86
  if (def.kind === "select") {
@@ -156,34 +157,28 @@ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormRe
156
157
  const fields = spec.fields.map(toState)
157
158
  let idx = 0
158
159
  let done = false
159
- let idleTimer: ReturnType<typeof setTimeout> | undefined
160
160
  let idleWarned = false
161
- const clearIdle = () => {
162
- if (idleTimer) clearTimeout(idleTimer)
163
- idleTimer = undefined
164
- }
165
- const resetIdle = () => {
166
- if (done) return
167
- clearIdle()
168
- idleWarned = false
169
- idleTimer = setTimeout(() => {
170
- // Tahap 1: peringatan (draft TIDAK dibuang — render footer merah).
161
+ // Idle dua-fase via helper bersama (audit D1): 80 dtk diam → peringatan
162
+ // di footer kotak (draft TIDAK dibuang); 10 dtk lagi hening → batal.
163
+ // TOTAL tetap 90 dtk (semantik anti-hang dipertahankan). `finish`/`render`
164
+ // dirujuk sebagai closure — dievaluasi jauh setelah keduanya terdefinisi.
165
+ const idle = createIdleTimer({
166
+ warnMs: IDLE_WARN_MS,
167
+ cancelMs: IDLE_CANCEL_MS,
168
+ onWarn: () => {
171
169
  idleWarned = true
172
170
  render()
173
- // Tahap 2: batal — hanya bila tetap hening.
174
- idleTimer = setTimeout(() => finish(true), IDLE_CANCEL_MS)
175
- try {
176
- ;(idleTimer as unknown as { unref?: () => void }).unref?.()
177
- } catch {}
178
- }, IDLE_WARN_MS)
179
- try {
180
- ;(idleTimer as unknown as { unref?: () => void }).unref?.()
181
- } catch {}
171
+ },
172
+ onCancel: () => finish(true),
173
+ })
174
+ const resetIdle = () => {
175
+ idleWarned = false
176
+ idle.reset()
182
177
  }
183
178
 
184
- // Lebar konten = lebar kotak TETAP (64) dikurangi chrome (border+padding
185
- // = 4) — sepakat dengan dialogBox min=max 64 (tanpa potong-ganda).
186
- const width = () => Math.max(20, Math.min((screen.cols || 80) - 6, FORM_BOX_W))
179
+ // Lebar konten = lebar kotak minus chrome border+padding (4).
180
+ const boxW = formBoxWidth(screen.cols || 80)
181
+ const width = () => boxW
187
182
  const innerW = () => Math.max(8, width() - 4)
188
183
 
189
184
  // Baris nilai field aktif (indeks dalam body) untuk parkir kursor.
@@ -196,7 +191,8 @@ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormRe
196
191
  fields.forEach((st, fi) => {
197
192
  const active = fi === idx
198
193
  if (st.def.kind === "text" || st.def.kind === "secret") {
199
- const shown = st.def.kind === "secret" ? "•".repeat(toGraphemes(st.text).length) : st.text
194
+ const shown =
195
+ st.def.kind === "secret" ? glyphs.mask.repeat(toGraphemes(st.text).length) : st.text
200
196
  // Scroll horizontal dalam KOLOM (bukan grapheme): CJK/emoji 2 kolom,
201
197
  // jadi hitung lebar tampil, bukan jumlah unit. Gagal-di-kode-lama:
202
198
  // kursor meleset 1 per glyph lebar + scroll prematur/terlambat.
@@ -248,10 +244,10 @@ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormRe
248
244
  footer: idleWarned
249
245
  ? c.error(t("form.idleWarning", { s: Math.ceil(IDLE_CANCEL_MS / 1000) }))
250
246
  : (spec.footer ?? t("form.footerDefault")),
251
- // Lebar TETAP (paritas picker/manager — geometri stabil, tak
252
- // bernapas saat error muncul/hilang).
253
- minWidth: FORM_BOX_W,
254
- maxWidth: FORM_BOX_W,
247
+ // Lebar beku (paritas picker/manager — tak bernapas saat error
248
+ // muncul/hilang).
249
+ minWidth: width(),
250
+ maxWidth: width(),
255
251
  // Field aktif WAJIB terlihat: dialog menggeser jendela body bila
256
252
  // muat-tidaknya terpaksa memotong (audit 2026-11-12, HIGH-2).
257
253
  focusRow: activeRow >= 0 ? activeRow : undefined,
@@ -290,7 +286,7 @@ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormRe
290
286
  const finish = (cancelled: boolean) => {
291
287
  if (done) return
292
288
  done = true
293
- clearIdle()
289
+ idle.dispose()
294
290
  try {
295
291
  formPump.dispose()
296
292
  } catch {}
@@ -0,0 +1,80 @@
1
+ // Lifecycle popup bersama — satu sumber untuk idle-timer jendela interaktif
2
+ // (picker, form, model/provider manager, wizard).
3
+ //
4
+ // Masalah yang dipecahkan (audit D1): keempat layar menulis ulang pola idle
5
+ // yang sama dengan nuansa kecil berbeda — raw-mode digenggam tanpa input saat
6
+ // ConPTY mati/fokus hilang membuat popup "macet" (dan Bun Windows rawan
7
+ // segfault setelah ±133 dtk idle, lihat picker.ts). Dengan satu helper,
8
+ // semantiknya seragam: SEMUA timer di-unref (tak menahan proses), fase batal
9
+ // selalu ada, dan `dispose()` membuat reset berikutnya no-op (anti-timer-bocor
10
+ // sesudah selesai).
11
+ //
12
+ // Dua gaya yang didukung:
13
+ // 1. Satu tahap (picker/manager): cancelMs tercapai → langsung batal.
14
+ // 2. Dua tahap (form, audit TUI-004): warnMs → peringatan (draft DIPERTAHAN-
15
+ // kan, render footer merah); cancelMs lagi tanpa keypress → batal.
16
+ // TOTAL tetap warnMs + cancelMs.
17
+
18
+ export interface IdleTimerOptions {
19
+ /** Fase 1 (opsional): jeda diam → peringatan. Tanpa ini = langsung batal. */
20
+ warnMs?: number
21
+ /** Fase 1 (tanpa warnMs) / fase 2 (dengan warnMs): jeda → batal. */
22
+ cancelMs: number
23
+ /** Dipanggil saat peringatan (hanya bila warnMs diisi). */
24
+ onWarn?: () => void
25
+ /** Dipanggil saat batal karena diam. Wajib. */
26
+ onCancel: () => void
27
+ }
28
+
29
+ export interface IdleTimer {
30
+ /** Restart timer (dipanggil tiap keypress/aktivitas). No-op sesudah dispose. */
31
+ reset(): void
32
+ /** Hentikan timer tanpa mematikan (dipanggil suspend/pause). */
33
+ clear(): void
34
+ /** Matikan selamanya: clear + reset berikutnya no-op (dipakai saat finish). */
35
+ dispose(): void
36
+ }
37
+
38
+ /** Buat idle-timer dua-fase dengan unref otomatis. */
39
+ export function createIdleTimer(opts: IdleTimerOptions): IdleTimer {
40
+ let timer: ReturnType<typeof setTimeout> | undefined
41
+ let disposed = false
42
+ const unref = (t: ReturnType<typeof setTimeout>) => {
43
+ // jangan tahan proses hidup hanya karena timer ini (stdin stub test bisa
44
+ // tanpa API unref — anggap aman).
45
+ try {
46
+ ;(t as unknown as { unref?: () => void }).unref?.()
47
+ } catch {}
48
+ }
49
+ const clear = () => {
50
+ if (timer) clearTimeout(timer)
51
+ timer = undefined
52
+ }
53
+ const fireCancel = () => {
54
+ if (disposed) return
55
+ opts.onCancel()
56
+ }
57
+ const reset = () => {
58
+ if (disposed) return
59
+ clear()
60
+ if (opts.warnMs != null) {
61
+ timer = setTimeout(() => {
62
+ // Tahap 1: peringatan — konten tidak dibuang, render ulang oleh caller.
63
+ if (disposed) return
64
+ try {
65
+ opts.onWarn?.()
66
+ } catch {}
67
+ timer = setTimeout(fireCancel, opts.cancelMs)
68
+ unref(timer)
69
+ }, opts.warnMs)
70
+ } else {
71
+ timer = setTimeout(fireCancel, opts.cancelMs)
72
+ }
73
+ unref(timer)
74
+ }
75
+ const dispose = () => {
76
+ disposed = true
77
+ clear()
78
+ }
79
+ return { reset, clear, dispose }
80
+ }