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
@@ -0,0 +1,174 @@
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.
7
+
8
+ import { t } from "../i18n/locale.ts"
9
+ import { sanitizeAnsiLine } from "../render/sanitize.ts"
10
+ import { c, supportsUtf8 } from "../render/theme.ts"
11
+ import { displayWidth, padToWidth, truncateToWidth } from "../render/width.ts"
12
+
13
+ export interface DialogSpec {
14
+ /** Judul baris atas. String kosong = tanpa baris judul (chrome menyesuaikan). */
15
+ title: string
16
+ /** Baris konten polos (sudah di-clamp view; di sini dipotong defensif). */
17
+ body: string[]
18
+ /** Baris hint bawah (tombol). Kosong = tanpa footer. */
19
+ footer?: string
20
+ /** Lebar kotak maksimum (inklusif border+padding). Default: selebar layar. */
21
+ 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
+ */
28
+ minWidth?: number
29
+ /** Tinggi kotak maksimum (inklusif border). Default: setinggi layar. */
30
+ maxHeight?: number
31
+ }
32
+
33
+ interface BoxChars {
34
+ tl: string
35
+ tr: string
36
+ bl: string
37
+ br: string
38
+ h: string
39
+ v: string
40
+ }
41
+
42
+ function boxChars(): BoxChars {
43
+ // supportsUtf8() dibaca TIAP paint (getter runtime, bukan cache module) —
44
+ // aturan yang sama dengan c/glyphs (theme.ts).
45
+ // Tanpa bayangan: kolom `▓` redup terlihat seperti strip berpasir di
46
+ // Windows Terminal (keluhan visual nyata) — kedalaman diganti backdrop
47
+ // redup + kotak terpusat saja.
48
+ if (!supportsUtf8()) return { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" }
49
+ return { tl: "┌", tr: "┐", bl: "└", br: "┘", h: "─", v: "│" }
50
+ }
51
+
52
+ /** Kotak popup tanpa backdrop: untuk paintRegion di atas konten pemilik layar. */
53
+ export interface DialogBox {
54
+ /** Baris kotak (sudah center-horizontal, satu-baris-tersanitasi). */
55
+ lines: string[]
56
+ /** Baris layar 1-based tempat baris pertama ditulis. */
57
+ topRow: number
58
+ height: number
59
+ /**
60
+ * Indeks 0-based dalam `lines` tempat body[0] berada (= 1 border +
61
+ * 1 judul bila ada). View WAJIB memakai ini untuk parkir kursor —
62
+ * menebak offset manual meleset 1-2 baris begitu judul ditambah/dihapus
63
+ * (bug nyata di 4 view).
64
+ */
65
+ bodyTop: number
66
+ }
67
+
68
+ /**
69
+ * Padding kiri (spasi) baris box — box.lines sudah ter-center saat dibangun.
70
+ * Kolom absolut = leftPad + offset-dalam-konten + 1. JANGAN hitung ulang
71
+ * center dari displayWidth (lupa padding = off-by-N, bug nyata).
72
+ */
73
+ export function boxLeftPad(strippedLine: string): number {
74
+ const m = /^ */.exec(strippedLine)
75
+ return m ? m[0].length : 0
76
+ }
77
+
78
+ /**
79
+ * Bangun KOTAK saja (tanpa backdrop): dipakai popup komposit App TUI lewat
80
+ * paintRegion — transkrip di belakang tetap tampil. Lebar mengikuti konten
81
+ * (clamp maxWidth); tinggi mengikuti body (clamp maxHeight).
82
+ */
83
+ export function dialogBox(spec: DialogSpec, cols: number, rows: number): DialogBox {
84
+ const c0 = Math.max(20, Math.floor(cols) || 80)
85
+ const r0 = Math.max(5, Math.floor(rows) || 24)
86
+ const box = boxChars()
87
+ const title = sanitizeAnsiLine(spec.title)
88
+ const footer = spec.footer != null && spec.footer !== "" ? sanitizeAnsiLine(spec.footer) : null
89
+
90
+ // Lebar dalam = konten terlebar, clamp ke layar. Chrome total per baris:
91
+ // v(1) + sp(1) + innerW + sp(1) + v(1) = innerW + 4. View membangun baris
92
+ // selebar itu (width() modal-aware) sehingga tak ada potong ulang di sini.
93
+ // maxWidth opsional mengecilkan kotak (dialog mungil) — kurangi SEBELUM
94
+ // hitung isi. Judul kosong = tanpa baris judul (chrome vertikal menyesuaikan).
95
+ const hasTitle = title !== ""
96
+ let innerMax = c0 - 2 - 4
97
+ if (spec.maxWidth != null && Number.isFinite(spec.maxWidth))
98
+ innerMax = Math.min(innerMax, Math.max(8, Math.floor(spec.maxWidth) - 4))
99
+ if (innerMax < 8) innerMax = 8
100
+ let innerMin = 8
101
+ if (spec.minWidth != null && Number.isFinite(spec.minWidth))
102
+ innerMin = Math.min(innerMax, Math.max(8, Math.floor(spec.minWidth) - 4))
103
+ let contentW = displayWidth(title)
104
+ for (const ln of spec.body) {
105
+ const w = displayWidth(sanitizeAnsiLine(ln))
106
+ if (w > contentW) contentW = w
107
+ }
108
+ if (footer != null) {
109
+ const w = displayWidth(footer)
110
+ if (w > contentW) contentW = w
111
+ }
112
+ const innerW = Math.min(Math.max(innerMin, contentW), innerMax)
113
+ const cut = (s: string) => truncateToWidth(sanitizeAnsiLine(s), innerW)
114
+ // +2 border, +2 padding: "│ text │".
115
+ const boxW = innerW + 4
116
+ const row = (left: string, mid: string, right: string) => left + mid + right
117
+
118
+ const bar = box.h.repeat(Math.max(0, boxW - 2))
119
+ const boxed: string[] = []
120
+ boxed.push(row(box.tl, bar, box.tr))
121
+ // Judul aksen (paritas visual dengan overlay inline); footer redup.
122
+ // Judul kosong = baris judul dilewati seluruhnya (bukan baris kosong).
123
+ if (hasTitle) boxed.push(`${box.v} ${padToWidth(c.accent(c.bold(cut(title))), innerW)} ${box.v}`)
124
+ // Isi: chrome tetap = 2 border + (judul ? 1 : 0) + (footer ? 1 : 0); baris
125
+ // marker ("… N more") ikut dihitung BILA terpotong. maxHeight opsional
126
+ // membatasi tinggi KOTAK (bukan frame — padding backdrop menyerap sisa).
127
+ const chromeFixed = 2 + (hasTitle ? 1 : 0) + (footer != null ? 1 : 0)
128
+ const boxBudget =
129
+ spec.maxHeight != null && Number.isFinite(spec.maxHeight)
130
+ ? Math.min(r0, Math.max(5, Math.floor(spec.maxHeight)))
131
+ : r0
132
+ const room = Math.max(0, boxBudget - chromeFixed)
133
+ const clipped = spec.body.length > room
134
+ const shown = clipped ? Math.max(0, room - 1) : spec.body.length
135
+ const body = spec.body.slice(0, shown)
136
+ for (const ln of body) boxed.push(`${box.v} ${padToWidth(cut(ln), innerW)} ${box.v}`)
137
+ if (clipped)
138
+ boxed.push(
139
+ `${box.v} ${padToWidth(cut(t("dlg.more", { n: spec.body.length - shown })), innerW)} ${box.v}`,
140
+ )
141
+ if (footer != null) boxed.push(`${box.v} ${padToWidth(c.dim(cut(footer)), innerW)} ${box.v}`)
142
+ boxed.push(row(box.bl, bar, box.br))
143
+
144
+ // Pusatkan horizontal; vertikal via topRow (1-based) untuk paintRegion.
145
+ // displayWidth mengabaikan SGR (nol kolom) sehingga ANSI tak merusak hitungan.
146
+ const topRow = Math.max(1, Math.floor((r0 - boxed.length) / 2) + 1)
147
+ const lines = boxed.map((ln) => {
148
+ const left = Math.max(0, Math.floor((c0 - displayWidth(ln)) / 2))
149
+ return `${" ".repeat(left)}${ln}`
150
+ })
151
+ return { lines, topRow, height: boxed.length, bodyTop: 1 + (hasTitle ? 1 : 0) }
152
+ }
153
+
154
+ /**
155
+ * Bangun frame SELAYAR: tepat `rows` string (backdrop redup + kotak terpusat).
156
+ * Tak pernah melempar; tak menulis IO (view yang paint via screen).
157
+ * Dipakai layar yang memiliki buffer sendiri (wizard first-run); popup di
158
+ * atas konten App memakai dialogBox + paintRegion (tanpa clear).
159
+ */
160
+ export function dialogFrame(spec: DialogSpec, cols: number, rows: number): string[] {
161
+ const c0 = Math.max(20, Math.floor(cols) || 80)
162
+ const r0 = Math.max(5, Math.floor(rows) || 24)
163
+ const box = dialogBox(spec, c0, r0)
164
+ // Backdrop REDUP (bukan hitam polos): pola ░ faint memenuhi layar sehingga
165
+ // kotak terbaca sebagai jendela di depan, bukan screen baru. Fallback ASCII
166
+ // "." bila glyph shade tak didukung.
167
+ const shade = supportsUtf8() ? "░".repeat(c0) : ".".repeat(c0)
168
+ const dim = c.faint(shade)
169
+ const out: string[] = []
170
+ for (let i = 1; i < box.topRow; i++) out.push(dim)
171
+ for (const ln of box.lines) out.push(ln)
172
+ while (out.length < r0) out.push(dim)
173
+ return out.slice(0, r0)
174
+ }
@@ -0,0 +1,459 @@
1
+ // Form dalam popup — SEMUA input teks/pilihan terjadi DI DALAM kotak.
2
+ //
3
+ // Latar: popup komposit hanya bisa melukis daftar; tiap input teks memakai
4
+ // askLine warisan yang menggambar di kursor terminal (di LUAR kotak).
5
+ // Hasilnya jendela yang mengusir user keluar untuk mengetik. Form ini
6
+ // menggantikannya: field berlabel + validasi + error inline, satu kotak,
7
+ // Tab pindah field, Enter simpan, Esc batal. Secret di-mask `•`.
8
+ //
9
+ // Pemilik layar (App/popup parent) tetap di luar: form melukis regionnya via
10
+ // screen.handle sendiri (openAltScreen nested = paint-through) dan memarkir
11
+ // kursor terminal di posisi ketik. Tutup = clearRegion + close.
12
+
13
+ import { t } from "../i18n/locale.ts"
14
+ import {
15
+ createDecoderState,
16
+ createKeyStreamPump,
17
+ type DecodedKey,
18
+ type DecoderState,
19
+ toGraphemes,
20
+ } from "../input/prompt-engine.ts"
21
+ import { sanitizeAnsiLine } from "../render/sanitize.ts"
22
+ import { c, stripAnsi } from "../render/theme.ts"
23
+ import { displayWidth, truncateToWidth } from "../render/width.ts"
24
+ import type { AltScreen } from "../runtime/screen.ts"
25
+ import { boxLeftPad, dialogBox } from "./dialog.ts"
26
+
27
+ export interface FormField {
28
+ id: string
29
+ label: string
30
+ kind: "text" | "secret" | "select" | "confirm"
31
+ /** Nilai awal (text/secret) atau indeks opsi (select). Confirm: boolean. */
32
+ initial?: string | number | boolean
33
+ /** Pilihan untuk select (min 1). Confirm memakai Ya/Tidak bawaan. */
34
+ options?: string[]
35
+ /** Validasi: pesan error Indonesia atau null bila sah. */
36
+ validate?: (value: string) => string | null
37
+ }
38
+
39
+ export interface FormSpec {
40
+ title: string
41
+ fields: FormField[]
42
+ footer?: string
43
+ }
44
+
45
+ export interface FormResult {
46
+ cancelled: boolean
47
+ values?: Record<string, string>
48
+ }
49
+
50
+ /** Validasi umum: wajib isi. */
51
+ export function validateRequired(v: string): string | null {
52
+ return v.trim() ? null : t("form.required")
53
+ }
54
+
55
+ /** Validasi umum: URL http(s) yang sah. */
56
+ export function validateUrl(v: string): string | null {
57
+ if (!v.trim()) return t("form.required")
58
+ try {
59
+ const u = new URL(v.trim())
60
+ if (!["http:", "https:"].includes(u.protocol)) return t("form.httpOnly")
61
+ } catch {
62
+ return t("form.invalidUrl")
63
+ }
64
+ return null
65
+ }
66
+
67
+ interface FieldState {
68
+ def: FormField
69
+ /** Text/secret: nilai ketik. Select: indeks opsi. Confirm: boolean. */
70
+ text: string
71
+ cursor: number // grapheme
72
+ selectIdx: number
73
+ confirmed: boolean
74
+ error: string | null
75
+ /** Offset scroll horizontal nilai (kursor selalu terlihat). */
76
+ viewStart: number
77
+ }
78
+
79
+ const DIM = "\x1b[2m"
80
+ const RESTORE = "\x1b[22m"
81
+
82
+ /** Lebar kotak form TETAP (keputusan rasa: geometri stabil). */
83
+ const FORM_BOX_W = 64
84
+
85
+ function toState(def: FormField): FieldState {
86
+ if (def.kind === "select") {
87
+ const n = Math.max(1, def.options?.length ?? 1)
88
+ const init = typeof def.initial === "number" ? def.initial : 0
89
+ return {
90
+ def,
91
+ text: "",
92
+ cursor: 0,
93
+ selectIdx: Math.min(Math.max(0, init), n - 1),
94
+ confirmed: false,
95
+ error: null,
96
+ viewStart: 0,
97
+ }
98
+ }
99
+ if (def.kind === "confirm") {
100
+ return {
101
+ def,
102
+ text: "",
103
+ cursor: 0,
104
+ selectIdx: 0,
105
+ confirmed: typeof def.initial === "boolean" ? def.initial : false,
106
+ error: null,
107
+ viewStart: 0,
108
+ }
109
+ }
110
+ return {
111
+ def,
112
+ text: typeof def.initial === "string" ? def.initial : "",
113
+ cursor: 0,
114
+ selectIdx: 0,
115
+ confirmed: false,
116
+ error: null,
117
+ viewStart: 0,
118
+ }
119
+ }
120
+
121
+ function fieldValue(st: FieldState): string {
122
+ if (st.def.kind === "select") return st.def.options?.[st.selectIdx] ?? ""
123
+ if (st.def.kind === "confirm") return st.confirmed ? "y" : "n"
124
+ return st.text
125
+ }
126
+
127
+ /**
128
+ * Potong deretan grapheme agar muat dalam `maxV` KOLOM (CJK/emoji = 2).
129
+ * Dipakai jendela nilai field: slice grapheme mentah bisa meluap 2×.
130
+ */
131
+ function sliceByWidth(pts: string[], start: number, maxV: number): string[] {
132
+ const out: string[] = []
133
+ let w = 0
134
+ for (let i = start; i < pts.length; i++) {
135
+ const cw = displayWidth(pts[i] ?? "")
136
+ if (w + cw > maxV) break
137
+ out.push(pts[i]!)
138
+ w += cw
139
+ }
140
+ return out
141
+ }
142
+
143
+ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormResult> {
144
+ if (!spec.fields.length) return { cancelled: true }
145
+ return new Promise<FormResult>((resolve) => {
146
+ const fields = spec.fields.map(toState)
147
+ let idx = 0
148
+ let done = false
149
+ let idleTimer: ReturnType<typeof setTimeout> | undefined
150
+ const clearIdle = () => {
151
+ if (idleTimer) clearTimeout(idleTimer)
152
+ idleTimer = undefined
153
+ }
154
+ const resetIdle = () => {
155
+ if (done) return
156
+ clearIdle()
157
+ idleTimer = setTimeout(() => finish(true), 90_000)
158
+ try {
159
+ ;(idleTimer as unknown as { unref?: () => void }).unref?.()
160
+ } catch {}
161
+ }
162
+
163
+ // Lebar konten = lebar kotak TETAP (64) dikurangi chrome (border+padding
164
+ // = 4) — sepakat dengan dialogBox min=max 64 (tanpa potong-ganda).
165
+ const width = () => Math.max(20, Math.min((screen.cols || 80) - 6, FORM_BOX_W))
166
+ const innerW = () => Math.max(8, width() - 4)
167
+
168
+ // Baris nilai field aktif (indeks dalam body) untuk parkir kursor.
169
+ const render = (): { activeRow: number; activeCol: number } => {
170
+ const w = innerW()
171
+ const cut = (s: string) => truncateToWidth(s, w)
172
+ const body: string[] = []
173
+ let activeRow = -1
174
+ let activeCol = -1
175
+ fields.forEach((st, fi) => {
176
+ const active = fi === idx
177
+ if (st.def.kind === "text" || st.def.kind === "secret") {
178
+ const shown = st.def.kind === "secret" ? "•".repeat(toGraphemes(st.text).length) : st.text
179
+ // Scroll horizontal dalam KOLOM (bukan grapheme): CJK/emoji 2 kolom,
180
+ // jadi hitung lebar tampil, bukan jumlah unit. Gagal-di-kode-lama:
181
+ // kursor meleset 1 per glyph lebar + scroll prematur/terlambat.
182
+ const maxV = Math.max(8, w - displayWidth(sanitizeAnsiLine(st.def.label)) - 4)
183
+ const pts = toGraphemes(shown)
184
+ let start = Math.max(0, Math.min(st.viewStart, st.cursor))
185
+ if (st.cursor < start) start = st.cursor
186
+ while (start < st.cursor && displayWidth(pts.slice(start, st.cursor).join("")) > maxV - 1)
187
+ start++
188
+ st.viewStart = start
189
+ const vis = sliceByWidth(pts, start, maxV).join("")
190
+ const prefix = `${active ? c.accent("›") : " "} ${sanitizeAnsiLine(st.def.label)}: `
191
+ // Kolom kursor terminal = lebar tampil prefix + lebar tampil nilai
192
+ // sebelum kursor (BUKAN jumlah grapheme).
193
+ if (active) {
194
+ activeCol =
195
+ displayWidth(stripAnsi(prefix)) +
196
+ displayWidth(pts.slice(start, st.cursor).join("")) +
197
+ 1
198
+ }
199
+ body.push(cut(`${prefix}${vis}`))
200
+ activeRow = active ? body.length - 1 : activeRow
201
+ } else if (st.def.kind === "select") {
202
+ const opts = st.def.options ?? []
203
+ const cur = sanitizeAnsiLine(opts[st.selectIdx] ?? "")
204
+ const marker = active ? c.accent("›") : " "
205
+ if (active) activeCol = -1 // select tanpa kursor ketik
206
+ body.push(
207
+ cut(
208
+ `${marker} ${sanitizeAnsiLine(st.def.label)}: ${DIM}‹${RESTORE} ${cur} ${DIM}›${RESTORE}`,
209
+ ),
210
+ )
211
+ activeRow = active ? body.length - 1 : activeRow
212
+ } else {
213
+ // Confirm: Ya/Tidak toggle.
214
+ const marker = active ? c.accent("›") : " "
215
+ const val = st.confirmed ? c.accent(t("form.yes")) : t("form.no")
216
+ if (active) activeCol = -1
217
+ body.push(cut(`${marker} ${sanitizeAnsiLine(st.def.label)}: ${val}`))
218
+ activeRow = active ? body.length - 1 : activeRow
219
+ }
220
+ if (st.error) body.push(cut(c.error(` ${sanitizeAnsiLine(st.error)}`)))
221
+ })
222
+ const box = dialogBox(
223
+ {
224
+ title: spec.title,
225
+ body,
226
+ footer: spec.footer ?? t("form.footerDefault"),
227
+ // Lebar TETAP (paritas picker/manager — geometri stabil, tak
228
+ // bernapas saat error muncul/hilang).
229
+ minWidth: FORM_BOX_W,
230
+ maxWidth: FORM_BOX_W,
231
+ },
232
+ screen.cols,
233
+ screen.rows,
234
+ )
235
+ screen.paintRegion(box.lines, box.topRow)
236
+ // Parkir kursor terminal di posisi ketik field aktif (select/confirm:
237
+ // sembunyikan di ujung baris). Kolom absolut = padding kiri + border +
238
+ // spasi + offset konten + 1; clamp ke layar. Menghitung ulang center
239
+ // dari lebar baris (yang sudah termasuk padding) terbukti off-by-N.
240
+ try {
241
+ if (activeRow >= 0) {
242
+ const li = Math.min(box.lines.length - 1, box.bodyTop + activeRow)
243
+ const row = box.topRow + li
244
+ const stripped = stripAnsi(box.lines[li] ?? "")
245
+ const leftPad = boxLeftPad(stripped)
246
+ const contentW = displayWidth(stripped) - leftPad
247
+ const raw = activeCol >= 0 ? leftPad + activeCol + 2 : leftPad + contentW + 1
248
+ const col = Math.max(1, Math.min(screen.cols || 80, raw))
249
+ process.stdout.write(`\x1b[${row};${col}H\x1b[?25h`)
250
+ }
251
+ } catch {}
252
+ return { activeRow, activeCol }
253
+ }
254
+
255
+ const finish = (cancelled: boolean) => {
256
+ if (done) return
257
+ done = true
258
+ clearIdle()
259
+ try {
260
+ formPump.dispose()
261
+ } catch {}
262
+ try {
263
+ screen.clearRegion()
264
+ } catch {}
265
+ try {
266
+ process.stdin.setRawMode(false)
267
+ } catch {}
268
+ if (onData) process.stdin.removeListener("data", onData)
269
+ if (onResize) process.stdout.removeListener("resize", onResize)
270
+ if (cancelled) resolve({ cancelled: true })
271
+ else {
272
+ const values: Record<string, string> = {}
273
+ for (const st of fields) values[st.def.id] = fieldValue(st)
274
+ resolve({ cancelled: false, values })
275
+ }
276
+ }
277
+
278
+ const validateAll = (): boolean => {
279
+ let firstBad = -1
280
+ fields.forEach((st, fi) => {
281
+ st.error = null
282
+ if (st.def.kind === "text" || st.def.kind === "secret") {
283
+ const err = st.def.validate?.(st.text) ?? null
284
+ if (err) {
285
+ st.error = err
286
+ if (firstBad < 0) firstBad = fi
287
+ }
288
+ }
289
+ })
290
+ if (firstBad >= 0) {
291
+ idx = firstBad
292
+ render()
293
+ return false
294
+ }
295
+ return true
296
+ }
297
+
298
+ const moveCursor = (st: FieldState, d: number) => {
299
+ const n = toGraphemes(st.text).length
300
+ st.cursor = Math.max(0, Math.min(n, st.cursor + d))
301
+ }
302
+
303
+ const insertText = (st: FieldState, ins: string) => {
304
+ const clean = ins
305
+ .replace(/\r\n|\r/g, " ")
306
+ .replace(/\t/g, " ")
307
+ // Kontrol dibuang (kecuali newline yang sudah jadi spasi).
308
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: sanitasi input form
309
+ .replace(/[\u0000-\u001f\u007f]/g, "")
310
+ if (!clean) return
311
+ const pts = toGraphemes(st.text)
312
+ const at = Math.max(0, Math.min(st.cursor, pts.length))
313
+ pts.splice(at, 0, ...toGraphemes(clean))
314
+ st.text = pts.join("")
315
+ st.cursor = at + toGraphemes(clean).length
316
+ st.error = null
317
+ }
318
+
319
+ const deletePrev = (st: FieldState) => {
320
+ const pts = toGraphemes(st.text)
321
+ const at = Math.max(0, Math.min(st.cursor, pts.length))
322
+ if (at === 0) return
323
+ // Hapus satu grapheme (emoji/ZWJ/flag utuh).
324
+ const head = pts.slice(0, at - 1)
325
+ const tail = pts.slice(at)
326
+ st.text = [...head, ...tail].join("")
327
+ st.cursor = at - 1
328
+ st.error = null
329
+ }
330
+
331
+ const handleKeys = (keys: DecodedKey[]): boolean => {
332
+ if (done) return true
333
+ resetIdle()
334
+ const st = fields[idx]!
335
+ for (const d of keys) {
336
+ const k = d.key
337
+ // Esc/Ctrl+C dua-tahap (anti-hilang draft): field berisi → bersihkan
338
+ // field aktif saja; kosong → batal total. Ctrl+D = batal langsung
339
+ // (konvensi EOF, tidak dipakai menghapus).
340
+ if (k.type === "esc" || k.type === "ctrl-c") {
341
+ const cur = fields[idx]!
342
+ if ((cur.def.kind === "text" || cur.def.kind === "secret") && cur.text.length > 0) {
343
+ cur.text = ""
344
+ cur.cursor = 0
345
+ cur.viewStart = 0
346
+ cur.error = null
347
+ render()
348
+ continue
349
+ }
350
+ finish(true)
351
+ return true
352
+ }
353
+ if (k.type === "ctrl-d") {
354
+ finish(true)
355
+ return true
356
+ }
357
+ if (k.type === "enter") {
358
+ if (validateAll()) finish(false)
359
+ return false
360
+ }
361
+ if (k.type === "tab") {
362
+ idx = (idx + 1) % fields.length
363
+ continue
364
+ }
365
+ if (k.type === "shift-tab") {
366
+ idx = (idx - 1 + fields.length) % fields.length
367
+ continue
368
+ }
369
+ if (k.type === "up") {
370
+ idx = (idx - 1 + fields.length) % fields.length
371
+ continue
372
+ }
373
+ if (k.type === "down") {
374
+ idx = (idx + 1) % fields.length
375
+ continue
376
+ }
377
+ if (st.def.kind === "select") {
378
+ const n = Math.max(1, st.def.options?.length ?? 1)
379
+ if (k.type === "left") st.selectIdx = (st.selectIdx - 1 + n) % n
380
+ else if (k.type === "right") st.selectIdx = (st.selectIdx + 1) % n
381
+ continue
382
+ }
383
+ if (st.def.kind === "confirm") {
384
+ if (k.type === "left" || k.type === "right") {
385
+ st.confirmed = !st.confirmed
386
+ continue
387
+ }
388
+ if (k.type === "char") {
389
+ // Terima dwibahasa (label tampil per locale): y/yes/ya, n/no/tidak/t.
390
+ const ch = k.ch.toLowerCase()
391
+ if (ch === "y" || ch === "ya") st.confirmed = true
392
+ else if (ch === "n" || ch === "t") st.confirmed = false
393
+ continue
394
+ }
395
+ continue
396
+ }
397
+ // Text/secret editing.
398
+ if (k.type === "char") insertText(st, k.ch)
399
+ else if (k.type === "backspace") deletePrev(st)
400
+ else if (k.type === "delete") {
401
+ const pts = toGraphemes(st.text)
402
+ const at = Math.max(0, Math.min(st.cursor, pts.length))
403
+ if (at < pts.length) {
404
+ pts.splice(at, 1)
405
+ st.text = pts.join("")
406
+ st.error = null
407
+ }
408
+ } else if (k.type === "left") moveCursor(st, -1)
409
+ else if (k.type === "right") moveCursor(st, 1)
410
+ else if (k.type === "home") st.cursor = 0
411
+ else if (k.type === "end") st.cursor = toGraphemes(st.text).length
412
+ else if (k.type === "ctrl-u") {
413
+ st.text = ""
414
+ st.cursor = 0
415
+ st.viewStart = 0
416
+ st.error = null
417
+ } else if (k.type === "ctrl-w") {
418
+ const pts = toGraphemes(st.text)
419
+ const at = Math.max(0, Math.min(st.cursor, pts.length))
420
+ const before = pts.slice(0, at).join("")
421
+ const trimmed = before.replace(/\S+\s*$/, "")
422
+ st.text = trimmed + pts.slice(at).join("")
423
+ st.cursor = toGraphemes(trimmed).length
424
+ st.error = null
425
+ }
426
+ }
427
+ render()
428
+ return false
429
+ }
430
+
431
+ const decoder: DecoderState = createDecoderState()
432
+ const formPump = createKeyStreamPump({ state: decoder, onKeys: handleKeys })
433
+ let onData!: (chunk: Buffer) => void
434
+ let onResize!: () => void
435
+ onData = (chunk: Buffer) => {
436
+ resetIdle()
437
+ try {
438
+ formPump.push(chunk)
439
+ } catch {
440
+ finish(true)
441
+ }
442
+ }
443
+ onResize = () => render()
444
+
445
+ // Form berjalan di atas screen milik pemanggil (view membuka
446
+ // openAltScreen sendiri; nested = paint-through). Listener stdin milik
447
+ // form selama hidup — pemanggil wajib suspend dulu (pola popup komposit).
448
+ try {
449
+ process.stdin.setRawMode(true)
450
+ process.stdin.resume()
451
+ process.stdin.on("data", onData)
452
+ process.stdout.on("resize", onResize)
453
+ resetIdle()
454
+ render()
455
+ } catch {
456
+ finish(true)
457
+ }
458
+ })
459
+ }