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
@@ -7,6 +7,10 @@
7
7
  // berisi `metadata`, `provider_error_code`, `limit_source`, dan URL dokumentasi
8
8
  // — di dalam frame TUI selebar 100 kolom.
9
9
 
10
+ import { t } from "../i18n/locale.ts"
11
+ import { sanitizeAnsiLine } from "./sanitize.ts"
12
+ import { truncateToWidth } from "./width.ts"
13
+
10
14
  export interface FriendlyError {
11
15
  message: string
12
16
  fix?: string
@@ -45,7 +49,9 @@ export function extractProviderDetail(raw: string): { detail?: string; hint?: st
45
49
  }
46
50
  // HTML: judul halaman error biasanya sudah menjelaskan.
47
51
  const title = /<title>([^<]{1,120})<\/title>/i.exec(trimmed)
48
- if (title) return { detail: title[1]!.trim() }
52
+ // Judul HTML dari provider tak terpercaya — sanitasi satu-baris agar tag
53
+ // / escape tak lolos via jalur error.
54
+ if (title) return { detail: sanitizeAnsiLine(title[1]!.trim()) }
49
55
  // Regex terakhir untuk body yang TERPOTONG (stream terputus di tengah JSON).
50
56
  // `raw` didahulukan: pada OpenRouter itu yang memuat alasan sebenarnya,
51
57
  // sementara `message` hanya "Provider returned error". Kutip penutup dibuat
@@ -66,7 +72,11 @@ function firstSentence(s?: string, max = 150): string | undefined {
66
72
  if (!clean) return undefined
67
73
  const cut = /^(.{20,}?[.!?])\s/.exec(clean)
68
74
  const one = cut ? cut[1]! : clean
69
- return one.length > max ? `${one.slice(0, max - 1)}…` : one
75
+ // Potong per KOLOM terminal (CJK/emoji = 2) dan jangan belah SGR/surrogate;
76
+ // input di sini belum tentu sanitize, jadi sanitasi satu-baris dulu agar
77
+ // ESC[2J/OSC tak lolos via pesan error provider yang tak terpercaya.
78
+ const safe = sanitizeAnsiLine(one)
79
+ return truncateToWidth(safe, max, "…")
70
80
  }
71
81
 
72
82
  /**
@@ -95,24 +105,38 @@ function redactSecrets(s: string): string {
95
105
  // Identifier/type-word (`string`, `graphemes`, `?`) lolos; token realistis kena.
96
106
  // `=` termasuk agar nilai cookie berbentuk pasangan kunci-nilai utuh tersamarkan.
97
107
  const V = `(?:"[^"]+"|'[^']+'|[A-Za-z0-9_~+/=-]*\\d[A-Za-z0-9_~+/=-]*|[A-Za-z0-9_~+/=-]{12,})`
98
- const V4 = `(?:"[^"]+"|'[^']+'|[A-Za-z0-9_~+/=-]*\\d[A-Za-z0-9_~+/=-]*|[A-Za-z0-9_~+/=-]{4,})`
99
- return s
100
- .replace(/\bbearer\s+["']?[A-Za-z0-9._~+/-]{6,}["']?/gi, "Bearer [redacted]")
101
- .replace(
102
- new RegExp(
103
- `((?:api[_-]?key|token|authorization|secret|password|client[_-]?secret|cookie)\\s*[:=]\\s*)(?!\\[redacted\\])(${V})`,
104
- "gi",
105
- ),
106
- "$1[redacted]",
107
- )
108
- .replace(new RegExp(`(\\bsession[-_]?id\\s*[:=]\\s*)(${V4})`, "g"), "$1[redacted]")
108
+ const V4 = `(?:"[^"]+"|'[^']+'|[A-Za-z0-9_~+/=-]*\\d[A-Za-z0-9_~+/-]*|[A-Za-z0-9_~+/=-]{4,})`
109
+ return (
110
+ s
111
+ // Format kunci provider konkret (subset scrub.ts — ui-boundary melarang
112
+ // impor policy/scrub; pola generik di bawah tak menangkap `sk-ant-…`,
113
+ // `thk_live_…`, `hf_…`, JWT tanpa konteks kv). Divalidasi bug-hunt
114
+ // 2026-09-19: echo proxy key-key ini lolos mentah ke layar sebelumnya.
115
+ .replace(/\b(sk-[A-Za-z0-9_-]{20,})\b/g, "[redacted]")
116
+ .replace(/\b(thk_live_[A-Za-z0-9_-]{16,})\b/g, "[redacted]")
117
+ .replace(/\b(hf_[A-Za-z0-9]{20,})\b/g, "[redacted]")
118
+ .replace(/\b(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b/g, "[redacted]")
119
+ .replace(/([?&](?:api[_-]?key|apikey|token|secret|password)=)[^&\s"'<>]*/gi, "$1[redacted]")
120
+ .replace(/\bbearer\s+["']?[A-Za-z0-9._~+/-]{6,}["']?/gi, "Bearer [redacted]")
121
+ .replace(
122
+ new RegExp(
123
+ `((?:api[_-]?key|token|authorization|secret|password|client[_-]?secret|cookie)\\s*[:=]\\s*)(?!\\[redacted\\])(${V})`,
124
+ "gi",
125
+ ),
126
+ "$1[redacted]",
127
+ )
128
+ .replace(new RegExp(`(\\bsession[-_]?id\\s*[:=]\\s*)(${V4})`, "g"), "$1[redacted]")
129
+ )
109
130
  }
110
131
 
111
132
  // Mapping kategori formal -> pesan user-friendly. Detail provider disertakan
112
133
  // sebagai satu kalimat bila ada (itu yang memberi tahu model mana yang limit,
113
134
  // atau tool mana yang tidak didukung) — bukan seluruh body.
114
135
  export function friendlyFromCategory(category: string, detail: string): FriendlyError {
115
- const truth = redactSecrets(detail.trim())
136
+ // Detail datang dari body error provider (proxy tak terpercaya): redact dulu
137
+ // lalu sanitasi satu-baris agar ESC[2J/OSC/alternate-screen tak bisa lolos
138
+ // via jalur error yang dicetak writer mentah di cli/.
139
+ const truth = sanitizeAnsiLine(redactSecrets(detail.trim()))
116
140
  const { detail: providerDetail, hint } = extractProviderDetail(truth)
117
141
  const withDetail = (base: string) =>
118
142
  providerDetail && providerDetail.toLowerCase() !== base.toLowerCase()
@@ -120,10 +144,12 @@ export function friendlyFromCategory(category: string, detail: string): Friendly
120
144
  : base
121
145
 
122
146
  switch (category) {
147
+ // Deteksi kata kunci TETAP Inggris: body error provider berbahasa Inggris
148
+ // apa pun locale UI. Yang diterjemahkan hanya pesan/fix tampil.
123
149
  case "rate_limit":
124
150
  return {
125
- message: withDetail("Provider is rate-limiting requests"),
126
- fix: hint ?? "Wait a moment and try again, or use --ratelimit to throttle requests.",
151
+ message: withDetail(t("err.rateLimit")),
152
+ fix: hint ?? t("err.rateLimitFix"),
127
153
  }
128
154
  case "auth": {
129
155
  const low = truth.toLowerCase()
@@ -135,41 +161,39 @@ export function friendlyFromCategory(category: string, detail: string): Friendly
135
161
  low.includes("credit limit")
136
162
  ) {
137
163
  return {
138
- message: withDetail("API key balance or quota is exhausted"),
139
- fix: hint ?? "Switch provider via /model, or top up credits.",
164
+ message: withDetail(t("err.balance")),
165
+ fix: hint ?? t("err.balanceFix"),
140
166
  }
141
167
  }
142
168
  return {
143
- message: withDetail("Provider rejected authentication"),
144
- fix: hint ?? "Check your API key, or switch provider via /model.",
169
+ message: withDetail(t("err.auth")),
170
+ fix: hint ?? t("err.authFix"),
145
171
  }
146
172
  }
147
173
  case "server":
148
174
  return {
149
- message: withDetail("Provider is temporarily unavailable"),
150
- fix: hint ?? "Wait a moment and try again, or switch provider via /model.",
175
+ message: withDetail(t("err.server")),
176
+ fix: hint ?? t("err.serverFix"),
151
177
  }
152
178
  case "network":
153
179
  return {
154
- message: withDetail("Failed to reach provider"),
155
- fix: hint ?? "Check your connection and try again.",
180
+ message: withDetail(t("err.network")),
181
+ fix: hint ?? t("err.networkFix"),
156
182
  }
157
183
  case "invalid_request":
158
184
  return {
159
- message: withDetail("Request was rejected by provider"),
160
- fix: hint ?? "Check the model name or select another model with /model.",
185
+ message: withDetail(t("err.invalid")),
186
+ fix: hint ?? t("err.invalidFix"),
161
187
  }
162
188
  case "context_length_exceeded":
163
189
  return {
164
- message: withDetail("Context window exceeded"),
165
- fix:
166
- hint ??
167
- "Start a new session (/exit then minicode), or use a model with a larger context window.",
190
+ message: withDetail(t("err.context")),
191
+ fix: hint ?? t("err.contextFix"),
168
192
  }
169
193
  case "content_filter":
170
194
  return {
171
- message: withDetail("Request was blocked by provider content filter"),
172
- fix: hint ?? "Rewrite the prompt, or switch provider via /model.",
195
+ message: withDetail(t("err.filter")),
196
+ fix: hint ?? t("err.filterFix"),
173
197
  }
174
198
  default: {
175
199
  // Kategori "unknown" menampung status HTTP lain (mis. 402 dari vendor
@@ -186,8 +210,8 @@ export function friendlyFromCategory(category: string, detail: string): Friendly
186
210
  low.includes("fewer max_tokens")
187
211
  ) {
188
212
  return {
189
- message: withDetail("API key balance or quota is exhausted"),
190
- fix: hint ?? "Switch provider via /model, or top up credits.",
213
+ message: withDetail(t("err.balance")),
214
+ fix: hint ?? t("err.balanceFix"),
191
215
  }
192
216
  }
193
217
  if (
@@ -198,13 +222,14 @@ export function friendlyFromCategory(category: string, detail: string): Friendly
198
222
  low.includes("try again later")
199
223
  ) {
200
224
  return {
201
- message: withDetail("Provider is rate-limiting requests"),
202
- fix: hint ?? "Wait a moment and try again, or use --ratelimit to throttle requests.",
225
+ message: withDetail(t("err.rateLimit")),
226
+ fix: hint ?? t("err.rateLimitFix"),
203
227
  }
204
228
  }
205
229
  if (providerDetail) return { message: providerDetail, ...(hint ? { fix: hint } : {}) }
206
- const cut = truth.length > 160 ? `${truth.slice(0, 157)}…` : truth
207
- return { message: cut }
230
+ // truth sudah sanitize satu-baris; potong per kolom agar CJK/emoji tak
231
+ // meluap dan tak belah SGR/surrogate.
232
+ return { message: truncateToWidth(truth, 160, "…") }
208
233
  }
209
234
  }
210
235
  }
@@ -214,23 +239,23 @@ export function friendlyError(raw: string): FriendlyError {
214
239
  const lower = raw.toLowerCase()
215
240
  if (lower.includes("timed out") || lower.includes("timeout"))
216
241
  return {
217
- message: "Run exceeded timeout",
218
- fix: "Increase --timeout or use a faster model.",
242
+ message: t("err.timeout"),
243
+ fix: t("err.timeoutFix"),
219
244
  }
220
245
  if (lower.includes("max steps") || lower.includes("max_steps"))
221
246
  return {
222
- message: "Tool step limit reached",
223
- fix: "Split the task into smaller prompts.",
247
+ message: t("err.steps"),
248
+ fix: t("err.stepsFix"),
224
249
  }
225
- if (lower.includes("budget"))
226
- return { message: "Session budget exceeded", fix: "Start a new session or increase --budget." }
227
- if (lower.includes("busy"))
228
- return { message: "A run is still in progress", fix: "Wait for the current run to finish." }
229
- if (lower.includes("aborted")) return { message: "Run was aborted" }
250
+ if (lower.includes("budget")) return { message: t("err.budget"), fix: t("err.budgetFix") }
251
+ if (lower.includes("busy")) return { message: t("err.busy"), fix: t("err.busyFix") }
252
+ if (lower.includes("aborted")) return { message: t("err.aborted") }
230
253
  const { detail } = extractProviderDetail(raw)
231
- if (detail) return { message: redactSecrets(detail) }
232
- const cut = raw.length > 160 ? `${raw.slice(0, 157)}…` : raw
233
- return { message: redactSecrets(cut) }
254
+ // detail sudah sanitize via firstSentence; redact tak menambah ANSI, tapi
255
+ // bungkus lagi agar idempoten bila pemanggil mengirim mentah di masa depan.
256
+ if (detail) return { message: sanitizeAnsiLine(redactSecrets(detail)) }
257
+ const safe = sanitizeAnsiLine(redactSecrets(raw))
258
+ return { message: truncateToWidth(safe, 160, "…") }
234
259
  }
235
260
 
236
261
  /** Satu baris siap tampil: pesan + saran. Dipakai renderer TUI & one-shot. */
@@ -4,23 +4,33 @@ import type { UiToolCallRef } from "../contract.ts"
4
4
  import { formatFriendly, friendlyFromCategory } from "./errors.ts"
5
5
  import { formatUsd } from "./money.ts"
6
6
 
7
+ /**
8
+ * Potong per code point (bukan UTF-16 unit): slice mentah membelah surrogate
9
+ * pair emoji menjadi U+FFFD di label. Batas di sini adalah cap KONTEN (bukan
10
+ * kolom terminal) — pemotongan kolom terjadi di hilir via truncateToWidth.
11
+ */
12
+ function safeSlice(s: string, n: number): string {
13
+ if (s.length <= n) return s
14
+ return Array.from(s).slice(0, n).join("")
15
+ }
16
+
7
17
  export function formatArgsPreview(args: unknown): string {
8
18
  try {
9
19
  const a = args as Record<string, unknown>
10
20
  if (a.path) return String(a.path)
11
- if (a.command) return String(a.command).slice(0, 60)
12
- if (a.cmd) return String(a.cmd).slice(0, 60)
21
+ if (a.command) return safeSlice(String(a.command), 60)
22
+ if (a.cmd) return safeSlice(String(a.cmd), 60)
13
23
  if (a.pattern) return String(a.pattern)
14
24
  if (a.query) return String(a.query)
15
- if (a.prompt) return String(a.prompt).slice(0, 40)
16
- return JSON.stringify(a).slice(0, 40)
25
+ if (a.prompt) return safeSlice(String(a.prompt), 40)
26
+ return safeSlice(JSON.stringify(a), 40)
17
27
  } catch {
18
28
  return "[args]"
19
29
  }
20
30
  }
21
31
 
22
32
  export function formatStepCalls(calls: readonly UiToolCallRef[], argCap = 35): string {
23
- return calls.map((tc) => `${tc.name}(${JSON.stringify(tc.args).slice(0, argCap)})`).join(", ")
33
+ return calls.map((tc) => `${tc.name}(${safeSlice(JSON.stringify(tc.args), argCap)})`).join(", ")
24
34
  }
25
35
 
26
36
  export function formatUsage(parts: {
@@ -1,3 +1,4 @@
1
+ import { t } from "../i18n/locale.ts"
1
2
  import { c } from "./theme.ts"
2
3
 
3
4
  const TS_KEYWORDS = new Set([
@@ -254,8 +255,10 @@ function highlightShellLine(line: string): string {
254
255
  }
255
256
 
256
257
  function highlightShellTokens(text: string): string {
258
+ // Alternatif flag (`-x`/`--long`) WAJIB sebelum kata: tanpa itu `-` tak pernah
259
+ // jadi awal token (cabang yellow di bawah mati — dulu flag tampil polos).
257
260
  return text.replace(
258
- /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\$[A-Za-z0-9_]+|\b[A-Za-z_][A-Za-z0-9_-]*\b|\s+)/g,
261
+ /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\$[A-Za-z0-9_]+|-{1,2}[A-Za-z0-9][A-Za-z0-9_-]*|\b[A-Za-z_][A-Za-z0-9_-]*\b|\s+)/g,
259
262
  (token) => {
260
263
  if (token.startsWith('"') || token.startsWith("'")) return c.green(token)
261
264
  if (token.startsWith("$")) return c.brightCyan(token)
@@ -278,7 +281,7 @@ export function formatCodeBlock(code: string, lang: string = "", maxLines?: numb
278
281
  const lines = highlighted.split("\n")
279
282
  const displayLines =
280
283
  maxLines && lines.length > maxLines
281
- ? [...lines.slice(0, maxLines), c.dim(` ... (${lines.length - maxLines} more lines)`)]
284
+ ? [...lines.slice(0, maxLines), c.dim(t("hl.moreLines", { n: lines.length - maxLines }))]
282
285
  : lines
283
286
 
284
287
  const header = lang ? ` ${lang.toLowerCase()} ` : " code "
@@ -43,10 +43,13 @@ export function renderTable(columns: ColumnDef[], data: Record<string, unknown>[
43
43
  return data
44
44
  .map((row) =>
45
45
  columns
46
- .map(
47
- (col) =>
48
- `${c.bold(col.header)}: ${truncateToWidth(sanitizeCell(row[col.key]), termW, ELLIPSIS)}`,
49
- )
46
+ .map((col) => {
47
+ // Nilai dipotong dari sisa budget SETELAH header: tanpa ini
48
+ // header+": "+value pasti > termW di terminal sempit (jalur
49
+ // penyelamat yang malah wrap sendiri).
50
+ const budget = Math.max(4, termW - displayWidth(col.header) - 2)
51
+ return `${c.bold(col.header)}: ${truncateToWidth(sanitizeCell(row[col.key]), budget, ELLIPSIS)}`
52
+ })
50
53
  .join("\n"),
51
54
  )
52
55
  .join("\n\n")
@@ -1,4 +1,4 @@
1
- import { displayWidth } from "./width.ts"
1
+ import { displayWidth, truncateToWidth } from "./width.ts"
2
2
 
3
3
  // Semantic color system - Ubuntu Server style.
4
4
  // Warna by function, bukan appearance. Satu palet (dark); NO_COLOR > truecolor
@@ -15,7 +15,7 @@ const isWindows = process.platform === "win32"
15
15
  * Sebelumnya dibekukan saat import, jadi `glyphs` selalu memakai nilai yang
16
16
  * ditentukan oleh env pada saat modul pertama dimuat.
17
17
  */
18
- function supportsUtf8(): boolean {
18
+ export function supportsUtf8(): boolean {
19
19
  if (process.env.MINICODE_ASCII === "1") return false
20
20
  if (!isWindows) return true
21
21
  return (
@@ -312,7 +312,12 @@ export const glyphs = {
312
312
  // ── Section separator ──
313
313
  export function section(title: string): string {
314
314
  const width = getTerminalWidth()
315
- const label = ` ${title} `
315
+ // Label lebih panjang dari terminal (judul CJK/emoji panjang): potong dulu
316
+ // per kolom — tanpa ini dashes jatuh ke 4 dan total label+4 tetap meluap.
317
+ const label =
318
+ displayWidth(` ${title} `) > Math.max(4, width - 4)
319
+ ? truncateToWidth(` ${title} `, Math.max(4, width - 4), "…")
320
+ : ` ${title} `
316
321
  // Lebar pemisah dihitung per KOLOM terminal: CJK/emoji bisa 2 kolom.
317
322
  // Clamp agar garis tak memicu wrap sendiri di terminal sempit.
318
323
  const dashes = Math.min(Math.max(4, width - displayWidth(label)), Math.max(4, width - 4))
@@ -219,20 +219,28 @@ export function chunkByWidth(s: string, width: number): string[] {
219
219
  let cur = ""
220
220
  let w = 0
221
221
  let i = 0
222
- // Sekuens SGR yang masih "terbuka" (bukan reset) — disuntikkan ke potongan
223
- // berikutnya agar warna tidak hilang saat kata berwarna panjang dipecah.
224
- let openSgr = ""
222
+ // Sekuens SGR yang masih "terbuka" — disuntikkan ke potongan berikutnya
223
+ // agar warna tidak hilang saat kata berwarna panjang dipecah. SEMUA pembuka
224
+ // diingat (bukan satu): `\x1b[1m\x1b[31m…` yang terbelah harus membawa bold
225
+ // DAN merah ke potongan berikut. Reset/off (0, 22–29, 39, 49) mengosongkan
226
+ // tumpukan — arah aman: potongan berikut mulai tanpa gaya daripada dengan
227
+ // gaya basi yang salah.
228
+ const SGR_OFF = new Set(["0", "22", "23", "24", "25", "27", "28", "29", "39", "49"])
229
+ let openSgr: string[] = []
225
230
  while (i < s.length) {
226
231
  if (s[i] === "\x1b") {
227
232
  const len = escapeLength(s, i)
228
233
  if (len > 0) {
229
234
  const seq = s.slice(i, i + len)
230
235
  if (seq.endsWith("m")) {
231
- // Reset/close menutup atribut; selain itu ingat sekuens pembuka.
232
- const params = seq.slice(2, -1).split(";")
233
- openSgr = params.some((p) => p === "0" || p === "22" || p === "39" || p === "49")
234
- ? ""
235
- : seq
236
+ const params = seq.slice(2, -1).split(/[:;]/)
237
+ if (params.some((p) => SGR_OFF.has(p) || p === "")) openSgr = []
238
+ if (params.some((p) => p !== "" && !SGR_OFF.has(p))) {
239
+ openSgr.push(seq)
240
+ // Batas tumpukan: input patologis (ganti warna tiap karakter tanpa
241
+ // reset) tak boleh membuat tiap potongan membawa ratusan sekuens.
242
+ if (openSgr.length > 8) openSgr = openSgr.slice(-8)
243
+ }
236
244
  }
237
245
  cur += seq
238
246
  i += len
@@ -244,7 +252,7 @@ export function chunkByWidth(s: string, width: number): string[] {
244
252
  const size = cp > 0xffff ? 2 : 1
245
253
  if (w + cw > width && cur !== "") {
246
254
  out.push(cur)
247
- cur = openSgr // lanjutkan warna ke potongan berikutnya
255
+ cur = openSgr.join("") // lanjutkan warna ke potongan berikutnya
248
256
  w = 0
249
257
  }
250
258
  cur += s.slice(i, i + size)
@@ -0,0 +1,197 @@
1
+ // Layar alternate-screen — pemilik `?1049h/?1049l` (kontrak I16). TUI
2
+ // fullscreen hidup di sini dari start sampai quit; popup komposit (dialog
3
+ // ala popup) dilukis TANPA clear via paintRegion di atas konten pemilik
4
+ // layar, sehingga transkrip di belakang tetap tampil.
5
+ //
6
+ // Aturan pakai (lihat dialog.ts untuk isi, view memanggil):
7
+ // const screen = openAltScreen()
8
+ // if (!screen.ok) { /* tolak bersuara + batal */ return }
9
+ // try { ... screen.paint(frame) ... } finally { screen.close() }
10
+ // Refcount menutup modal nested (effort-picker di dalam manager): tulis
11
+ // enter/exit fisik hanya di lapis terluar; handle dalam = no-op paint-through.
12
+ const ENTER = "\x1b[?1049h"
13
+ const EXIT = "\x1b[?1049l"
14
+ const HOME = "\x1b[H"
15
+ const CLEAR_ALL = "\x1b[2J"
16
+ // Reset scroll-region — unconditional + idempoten: region aktif peninggalan
17
+ // akan memotong paint fullscreen; tulis SEBELUM enter dan SESUDAH exit agar
18
+ // buffer utama kembali steril apa pun yang terjadi di dalam.
19
+ // region aktif akan memotong paint fullscreen modal; tulis SEBELUM enter dan
20
+ // SESUDAH exit agar buffer utama kembali steril apa pun yang terjadi di dalam.
21
+ const RESET_REGION = "\x1b[r"
22
+ const SYNC_START = "\x1b[?2026h"
23
+ const SYNC_END = "\x1b[?2026l"
24
+
25
+ let depth = 0
26
+ let exitHookInstalled = false
27
+
28
+ function installExitHook(): void {
29
+ if (exitHookInstalled) return
30
+ exitHookInstalled = true
31
+ // Jaring terakhir (best-effort, sinkron): modal yatim mengunci layar di
32
+ // buffer alt. `kill -9` tak tercakup — ketik `reset` (residual kontrak).
33
+ process.on("exit", () => {
34
+ if (depth > 0) {
35
+ try {
36
+ process.stdout.write(EXIT)
37
+ } catch {}
38
+ depth = 0
39
+ }
40
+ })
41
+ }
42
+
43
+ export interface AltScreen {
44
+ /** False = tak mampu (non-TTY/dumb) — paint/close no-op, caller fallback. */
45
+ readonly ok: boolean
46
+ readonly cols: number
47
+ readonly rows: number
48
+ /** Lukis satu frame penuh (tepat `rows` baris dari dialog.ts). */
49
+ paint(lines: string[]): void
50
+ /**
51
+ * Lukis REGION TANPA clear: popup di atas konten pemilik layar (App TUI).
52
+ * Tiap baris ditulis di `topRow+i` (1-based) setelah hapus-baris; baris di
53
+ * luar region TAK tersentuh sehingga transkrip di belakang tetap tampil.
54
+ * Siklus hidup region: handle mengingat region terakhir; render yang
55
+ * menyusut/bergeser membersihkan union lama+baru (tanpa ini sisa kotak
56
+ * lama tertinggal sebagai baris hantu). Pemilik layar me-repaint penuh
57
+ * saat popup tutup (App.resume).
58
+ */
59
+ paintRegion(lines: string[], topRow: number): void
60
+ /**
61
+ * Hapus region terakhir yang dilukis handle ini (spasi) — dipanggil view
62
+ * saat tutup sebelum pemilik me-repaint. Idempoten, tak pernah melempar.
63
+ */
64
+ clearRegion(): void
65
+ /** Idempoten; exit fisik hanya di lapis terluar. Tak pernah melempar. */
66
+ close(): void
67
+ }
68
+
69
+ const NULL_COLS = 80
70
+ const NULL_ROWS = 24
71
+
72
+ function nullScreen(): AltScreen {
73
+ return {
74
+ ok: false,
75
+ cols: process.stdout.columns || NULL_COLS,
76
+ rows: process.stdout.rows || NULL_ROWS,
77
+ paint: () => {},
78
+ paintRegion: () => {},
79
+ clearRegion: () => {},
80
+ close: () => {},
81
+ }
82
+ }
83
+
84
+ /** Buka layar modal. Fail-closed: kembalikan null-screen bila tak mampu. */
85
+ export function openAltScreen(): AltScreen {
86
+ installExitHook()
87
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return nullScreen()
88
+ if ((process.env.TERM ?? "") === "dumb") return nullScreen()
89
+ let closed = false
90
+ const nested = depth > 0
91
+ if (!nested) {
92
+ try {
93
+ process.stdout.write(RESET_REGION)
94
+ process.stdout.write(ENTER)
95
+ } catch {
96
+ return nullScreen()
97
+ }
98
+ }
99
+ depth++
100
+ // Region terakhir handle ini (siklus hidup popup komposit) — per-handle
101
+ // (closure), bukan global: popup nested (effort di dalam manager) melacak
102
+ // areanya masing-masing.
103
+ let lastRegion: { top: number; height: number } | null = null
104
+ return {
105
+ ok: true,
106
+ // Getter LIVE (bukan snapshot saat open) — resize di tengah modal wajib
107
+ // memakai geometri saat paint (kontrak I11); snapshot membeku = bingkai
108
+ // meluap setelah resize (pelajaran sama seperti c/glyphs di theme.ts).
109
+ get cols() {
110
+ return process.stdout.columns || NULL_COLS
111
+ },
112
+ get rows() {
113
+ return process.stdout.rows || NULL_ROWS
114
+ },
115
+ paint(lines: string[]): void {
116
+ if (closed) return
117
+ try {
118
+ process.stdout.write(SYNC_START)
119
+ process.stdout.write(HOME)
120
+ process.stdout.write(CLEAR_ALL)
121
+ process.stdout.write(lines.join("\r\n"))
122
+ process.stdout.write(SYNC_END)
123
+ } catch {}
124
+ },
125
+ paintRegion(lines: string[], topRow: number): void {
126
+ if (closed) return
127
+ // Melukis nol baris = no-op murni (bukan clear): pemanggil yang ingin
128
+ // menghapus memakai clearRegion() eksplisit.
129
+ if (!lines.length) return
130
+ try {
131
+ const top = Math.max(1, Math.floor(topRow) || 1)
132
+ const h = lines.length
133
+ // Union region lama + baru: kotak yang menyusut/bergeser (filter,
134
+ // notice hilang) harus menghapus sisa bingkainya sendiri — pemilik
135
+ // layar tak tahu geometri popup.
136
+ let clearTop = top
137
+ let clearBottom = top + Math.max(0, h - 1)
138
+ if (lastRegion) {
139
+ clearTop = Math.min(clearTop, lastRegion.top)
140
+ clearBottom = Math.max(clearBottom, lastRegion.top + lastRegion.height - 1)
141
+ }
142
+ let out = SYNC_START
143
+ for (let r = clearTop; r <= clearBottom; r++) {
144
+ const i = r - top
145
+ // Baris diasumsi satu-baris-tersanitasi dari dialogBox (tanpa \n —
146
+ // \n akan menggeser kursor dan merusak baris berikut; split defensif).
147
+ const row = i >= 0 && i < h ? ((lines[i] ?? "").split("\n")[0] ?? "") : ""
148
+ out += `\x1b[${r};1H\x1b[2K${row}`
149
+ }
150
+ out += SYNC_END
151
+ process.stdout.write(out)
152
+ lastRegion = h > 0 ? { top, height: h } : null
153
+ } catch {}
154
+ },
155
+ clearRegion(): void {
156
+ if (closed) return
157
+ if (!lastRegion) return
158
+ try {
159
+ let out = SYNC_START
160
+ for (let r = lastRegion.top; r < lastRegion.top + lastRegion.height; r++) {
161
+ out += `\x1b[${r};1H\x1b[2K`
162
+ }
163
+ out += SYNC_END
164
+ process.stdout.write(out)
165
+ } catch {}
166
+ lastRegion = null
167
+ },
168
+ close(): void {
169
+ if (closed) return
170
+ closed = true
171
+ lastRegion = null
172
+ depth = Math.max(0, depth - 1)
173
+ if (depth === 0) {
174
+ try {
175
+ process.stdout.write(EXIT)
176
+ } catch {}
177
+ try {
178
+ process.stdout.write(RESET_REGION)
179
+ } catch {}
180
+ }
181
+ },
182
+ }
183
+ }
184
+
185
+ /** Introspeksi untuk test: kedalaman modal aktif. */
186
+ export function altScreenDepth(): number {
187
+ return depth
188
+ }
189
+
190
+ /**
191
+ * Reset kedalaman (HANYA untuk isolasi test antar-file): view yang gagal
192
+ * di tengah test bisa meninggalkan depth > 0 sehingga file test berikutnya
193
+ * melihat open() sebagai nested dan tak ada ENTER fisik tertulis.
194
+ */
195
+ export function resetAltScreenDepth(): void {
196
+ depth = 0
197
+ }