minicode-ai 0.9.26

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 (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,339 @@
1
+ import { displayWidth } from "./width.ts"
2
+
3
+ // Semantic color system - Ubuntu Server style.
4
+ // Warna by function, bukan appearance. Satu palet (dark); NO_COLOR > truecolor
5
+ // > 256 > 16 > mono tetap auto-detect. Fitur tema (--theme, /theme, preset)
6
+ // dihapus: tampilan tunggal, tidak ada state tema mutable.
7
+
8
+ const isWindows = process.platform === "win32"
9
+
10
+ /**
11
+ * Apakah terminal menampilkan karakter Unicode non-ASCII dengan benar?
12
+ *
13
+ * Dievaluasi LAZY (bukan saat import) supaya perubahan env di runtime dan di
14
+ * test tetap berpengaruh — sama alasannya dengan deteksi warna di bawah.
15
+ * Sebelumnya dibekukan saat import, jadi `glyphs` selalu memakai nilai yang
16
+ * ditentukan oleh env pada saat modul pertama dimuat.
17
+ */
18
+ function supportsUtf8(): boolean {
19
+ if (process.env.MINICODE_ASCII === "1") return false
20
+ if (!isWindows) return true
21
+ return (
22
+ process.env.WT_SESSION != null ||
23
+ process.env.TERM_PROGRAM != null ||
24
+ (process.env.LANG?.includes("UTF-8") ?? false) ||
25
+ (process.env.LC_ALL?.includes("UTF-8") ?? false)
26
+ )
27
+ }
28
+
29
+ // ── Color support detection ──
30
+ // Dievaluasi LAZY (bukan saat import) supaya perubahan NO_COLOR/COLORTERM di
31
+ // runtime dan pengujian tetap berpengaruh; hasilnya murah karena hanya baca env.
32
+ function noColorEnv(): boolean {
33
+ return process.env.NO_COLOR != null && process.env.NO_COLOR !== "0"
34
+ }
35
+ function hasTruecolorEnv(): boolean {
36
+ return process.env.COLORTERM === "truecolor" || process.env.COLORTERM === "24bit"
37
+ }
38
+ /** 0=mono, 1=16-color, 2=256-color, 3=truecolor */
39
+ function colorLevel(): number {
40
+ if (noColorEnv()) return 0
41
+ // Determinisme Unix: output ke pipe/redirect/file tidak boleh memuat ANSI,
42
+ // apa pun TERM/COLORTERM di env (env sesi interaktif sering bocor ke proses
43
+ // yang di-pipe). Warna hanya untuk stdout yang benar-benar terminal.
44
+ if (!process.stdout.isTTY) return 0
45
+ if (hasTruecolorEnv()) return 3
46
+ if (process.env.TERM?.includes("256color")) return 2
47
+ return 1
48
+ }
49
+
50
+ type Paint = (s: string) => string
51
+ const identity: Paint = (s) => s
52
+
53
+ function wrap(open: number | string, close: number | string): Paint {
54
+ if (colorLevel() === 0) return identity
55
+ const o = `\x1b[${open}m`
56
+ const cl =
57
+ typeof close === "number"
58
+ ? `\x1b[${close}m`
59
+ : String(close).startsWith("\x1b[")
60
+ ? String(close)
61
+ : `\x1b[${close}m`
62
+ return (s: string) => `${o}${s}${cl}`
63
+ }
64
+
65
+ /** Warna dari kode SGR mentah (mis. "38;2;137;209;133" atau "39"). */
66
+ function paintFrom(code: string): Paint {
67
+ if (colorLevel() === 0) return identity
68
+ return (s: string) => `\x1b[${code}m${s}\x1b[39m`
69
+ }
70
+
71
+ // ── Token palet tunggal (VS Code Dark+ inspired) ──
72
+ const TOKENS = {
73
+ success: "38;2;137;209;133",
74
+ error: "38;2;244;135;113",
75
+ warning: "38;2;204;167;0",
76
+ info: "38;2;117;190;255",
77
+ accent: "38;2;0;122;204",
78
+ // Faint: abu gelap untuk garis footer — lebih redup dari `gray` (bright-black)
79
+ // dan dari `muted` (dim). Dipakai elemen yang harus ada tapi hampir tak
80
+ // terlihat, seperti separator baris dasar.
81
+ faint: "38;2;72;72;72",
82
+ }
83
+
84
+ // ── Slot warna ──
85
+ //
86
+ // PENTING: slot ini WAJIB dievaluasi saat dipanggil, bukan saat modul di-import.
87
+ // Versi sebelumnya menulis `success: trueWrap(tk("success"))` di module scope,
88
+ // sehingga token warna dibekukan pada import pertama — termasuk warna `mono`
89
+ // yang seharusnya menjadi jalur aksesibilitas. Slot kini getter dengan hasil
90
+ // di-cache per level warna supaya jalur render panas tidak mengalokasi closure
91
+ // tiap panggilan.
92
+ interface Palette {
93
+ success: Paint
94
+ error: Paint
95
+ warning: Paint
96
+ info: Paint
97
+ accent: Paint
98
+ accentAlt: Paint
99
+ accentBold: Paint
100
+ gray: Paint
101
+ faint: Paint
102
+ red: Paint
103
+ green: Paint
104
+ yellow: Paint
105
+ cyan: Paint
106
+ blue: Paint
107
+ magenta: Paint
108
+ white: Paint
109
+ brightYellow: Paint
110
+ brightMagenta: Paint
111
+ brightCyan: Paint
112
+ }
113
+
114
+ const paletteCache = new Map<string, Palette>()
115
+
116
+ function buildPalette(): Palette {
117
+ const truecolor = hasTruecolorEnv()
118
+ const mono = colorLevel() === 0
119
+ // Aksen: 16-color fallback saat truecolor tak tersedia.
120
+ const accent = truecolor ? paintFrom(TOKENS.accent) : wrap(94, 39)
121
+ return {
122
+ success: paintFrom(TOKENS.success),
123
+ error: paintFrom(TOKENS.error),
124
+ warning: paintFrom(TOKENS.warning),
125
+ info: paintFrom(TOKENS.info),
126
+ accent,
127
+ accentAlt: truecolor ? paintFrom(TOKENS.info) : wrap(95, 39),
128
+ accentBold: truecolor ? paintFrom(`1;${TOKENS.accent}`) : wrap(94, 39),
129
+ // Saat mono, `gray` memakai dim (SGR 2) alih-alih bright-black (SGR 90):
130
+ // 90 adalah warna, dan mono adalah jalur aksesibilitas yang seharusnya
131
+ // monokrom. Dim tetap memberi hierarki visual tanpa memakai kanal warna.
132
+ gray: mono ? attr(2, 22) : wrap(90, 39),
133
+ // Faint: garis footer hampir tak terlihat. Mono (aksesibilitas) jatuh ke
134
+ // dim agar tetap ada hierarki tanpa kanal warna.
135
+ faint: mono ? attr(2, 22) : paintFrom(TOKENS.faint),
136
+ // Alias legacy: dipetakan ke token, bukan hex hardcoded.
137
+ red: paintFrom(TOKENS.error),
138
+ green: paintFrom(TOKENS.success),
139
+ yellow: paintFrom(TOKENS.warning),
140
+ cyan: paintFrom(TOKENS.info),
141
+ blue: accent,
142
+ magenta: mono ? identity : wrap(35, 39),
143
+ white: mono ? identity : wrap(37, 39),
144
+ // Slot syntax highlight — saat mono semuanya jadi teks biasa.
145
+ brightYellow: mono ? identity : truecolor ? wrap("38;2;215;186;125", 39) : wrap(93, 39),
146
+ brightMagenta: mono ? identity : truecolor ? wrap("38;2;197;134;192", 39) : wrap(95, 39),
147
+ brightCyan: mono ? identity : truecolor ? wrap("38;2;78;201;176", 39) : wrap(96, 39),
148
+ }
149
+ }
150
+
151
+ function palette(): Palette {
152
+ // Kunci cache memuat level warna: NO_COLOR / COLORTERM bisa berubah antar
153
+ // proses (dan antar test), dan palette mono vs truecolor berbeda isi.
154
+ const key = `${colorLevel()}:${hasTruecolorEnv() ? 1 : 0}`
155
+ const cached = paletteCache.get(key)
156
+ if (cached) return cached
157
+ const built = buildPalette()
158
+ paletteCache.set(key, built)
159
+ return built
160
+ }
161
+
162
+ // Atribut non-warna (dim/bold/italic) tetap lazy juga: NO_COLOR harus
163
+ // mematikannya, dan itu dievaluasi saat pakai.
164
+ const attrCache = new Map<string, Paint>()
165
+ function attr(open: number, close: number): Paint {
166
+ const key = `${open}:${close}:${colorLevel()}`
167
+ const hit = attrCache.get(key)
168
+ if (hit) return hit
169
+ const built = wrap(open, close)
170
+ attrCache.set(key, built)
171
+ return built
172
+ }
173
+
174
+ /**
175
+ * Slot warna semantik.
176
+ *
177
+ * GETTER — JANGAN simpan ke `const` di module scope; lihat PLAN.md P0.1.
178
+ * Setiap properti membaca level warna saat DIPANGGIL. Menulis
179
+ * `const HEADER = c.dim(...)` di module scope membekukan hasilnya pada import
180
+ * pertama (NO_COLOR, COLORTERM tidak lagi berpengaruh). Kesalahan ini sudah
181
+ * terjadi dua kali (V6, V8). Dijaga oleh
182
+ * `test/no-frozen-runtime-value.test.ts`.
183
+ *
184
+ * Benar: `() => c.dim(x)`, `get header() { return c.dim(x) }`, atau baca di
185
+ * dalam fungsi render.
186
+ */
187
+ export const c = {
188
+ // Text hierarchy — tidak bergantung warna.
189
+ text: identity,
190
+ get muted() {
191
+ return attr(2, 22) // dim - secondary info, borders
192
+ },
193
+ get bold() {
194
+ return attr(1, 22)
195
+ },
196
+ get italic() {
197
+ return attr(3, 23)
198
+ },
199
+ get dim() {
200
+ return attr(2, 22)
201
+ },
202
+
203
+ // Status
204
+ get success() {
205
+ return palette().success
206
+ },
207
+ get error() {
208
+ return palette().error
209
+ },
210
+ get warning() {
211
+ return palette().warning
212
+ },
213
+ get info() {
214
+ return palette().info
215
+ },
216
+
217
+ // Accent
218
+ get accent() {
219
+ return palette().accent
220
+ },
221
+ get accentAlt() {
222
+ return palette().accentAlt
223
+ },
224
+ get accentBold() {
225
+ return palette().accentBold
226
+ },
227
+ get gray() {
228
+ return palette().gray
229
+ },
230
+ get faint() {
231
+ return palette().faint
232
+ },
233
+
234
+ // Legacy compat (dipakai renderer lama) — kini mengikuti token.
235
+ get red() {
236
+ return palette().red
237
+ },
238
+ get green() {
239
+ return palette().green
240
+ },
241
+ get yellow() {
242
+ return palette().yellow
243
+ },
244
+ get cyan() {
245
+ return palette().cyan
246
+ },
247
+ get blue() {
248
+ return palette().blue
249
+ },
250
+ get magenta() {
251
+ return palette().magenta
252
+ },
253
+ get white() {
254
+ return palette().white
255
+ },
256
+
257
+ // Syntax highlight
258
+ get brightYellow() {
259
+ return palette().brightYellow
260
+ },
261
+ get brightMagenta() {
262
+ return palette().brightMagenta
263
+ },
264
+ get brightCyan() {
265
+ return palette().brightCyan
266
+ },
267
+ }
268
+
269
+ // ── Glyphs - minimal, Ubuntu Server style ──
270
+ //
271
+ // GETTER — JANGAN simpan ke `const` di module scope; lihat PLAN.md P0.1.
272
+ // `supportsUtf8()` dievaluasi saat dipakai supaya `MINICODE_ASCII=1` dan
273
+ // perubahan env di test langsung berlaku. `const OK = glyphs.check` di
274
+ // `cli/commands.ts` pernah membekukannya (V8) sehingga fallback ASCII tidak
275
+ // pernah aktif. Dijaga oleh `test/no-frozen-runtime-value.test.ts`.
276
+ export const glyphs = {
277
+ get check() {
278
+ return supportsUtf8() ? "✓" : "[OK]"
279
+ },
280
+ get cross() {
281
+ return supportsUtf8() ? "✗" : "[FAIL]"
282
+ },
283
+ get arrow() {
284
+ return supportsUtf8() ? "›" : ">"
285
+ },
286
+ get prompt() {
287
+ return supportsUtf8() ? "❯" : ">"
288
+ },
289
+ get dot() {
290
+ return supportsUtf8() ? "·" : "."
291
+ },
292
+ get bullet() {
293
+ return supportsUtf8() ? "●" : "*"
294
+ },
295
+ get ellipsis() {
296
+ return supportsUtf8() ? "…" : "..."
297
+ },
298
+ get sparkle() {
299
+ return supportsUtf8() ? "✦" : "*"
300
+ },
301
+ get spinnerFrames() {
302
+ return supportsUtf8() ? ["·", "··", "···"] : [".", "..", "..."]
303
+ },
304
+ get thinkingIcon() {
305
+ // Sparkle ✦ (bintang) — indikator thinking yang "kelip-kelip": glyph
306
+ // monokrom, jadi warna ANSI (putih ↔ abu di turn-status) terlihat.
307
+ // Fallback * untuk terminal tanpa UTF-8.
308
+ return supportsUtf8() ? "✦" : "*"
309
+ },
310
+ }
311
+
312
+ // ── Section separator ──
313
+ export function section(title: string): string {
314
+ const width = getTerminalWidth()
315
+ const label = ` ${title} `
316
+ // Lebar pemisah dihitung per KOLOM terminal: CJK/emoji bisa 2 kolom.
317
+ // Clamp agar garis tak memicu wrap sendiri di terminal sempit.
318
+ const dashes = Math.min(Math.max(4, width - displayWidth(label)), Math.max(4, width - 4))
319
+ return c.dim(label + "─".repeat(dashes))
320
+ }
321
+
322
+ export function getTerminalWidth(): number {
323
+ return process.stdout.columns || 80
324
+ }
325
+
326
+ // Satu sumber pola ANSI. Dibangun via `new RegExp` dari String.fromCharCode(27)
327
+ // alih-alih literal /\x1b…/ supaya tidak menyisipkan control character mentah ke
328
+ // source (lint/suspicious/noControlCharactersInRegex) — perilaku identik.
329
+ export const ESC = String.fromCharCode(27)
330
+ // CSI dengan parameter privat (`?`, `<`, `=`, `>`) juga harus tertangkap:
331
+ // ESC[?25l, ESC[?2026h, ESC[?1049h dipakai untuk kursor/sync/alternate-screen.
332
+ // Tanpa itu sekuens kontrol lolos ke teks yang seharusnya sudah bersih —
333
+ // terlihat saat output ditangkap/disanitasi untuk tampilan.
334
+ export const ANSI_PATTERN = `${ESC}(?:\\[[0-9;?<=>]*[a-zA-Z]|\\[[0-9;?<=>]*|\\][^${ESC}\\u0007]*(?:\\u0007|${ESC}\\\\)|\\[P_\\^X][^${ESC}\\u0007]*(?:\\u0007|${ESC}\\\\)|[()#][0-9A-Za-z]|[0-9A-Za-z])`
335
+
336
+ export function stripAnsi(str: string): string {
337
+ // regex baru per panggilan: aman dari lastIndex bersama antar pemanggil
338
+ return str.replace(new RegExp(ANSI_PATTERN, "g"), "")
339
+ }
@@ -0,0 +1,256 @@
1
+ // Lebar tampil karakter di terminal.
2
+ //
3
+ // Semua kode UI sebelumnya menganggap 1 karakter = 1 kolom. Itu salah untuk CJK,
4
+ // Hangul, kana, emoji, dan simbol lebar-penuh — semuanya memakan DUA kolom.
5
+ // Akibatnya nyata: 38 code point CJK menempati 73 kolom di terminal 40 kolom,
6
+ // baris membungkus sendiri, dan frame TUI (yang dihitung per baris) rusak.
7
+ //
8
+ // Karakter penggabung (combining marks, variation selector, ZWJ) sebaliknya
9
+ // memakan NOL kolom — "é" sebagai e+U+0301 adalah satu kolom, bukan dua.
10
+ //
11
+ // Referensi: EastAsianWidth (UAX #11) kategori W dan F. Rentang di bawah adalah
12
+ // blok utama yang relevan untuk keluaran terminal; tidak perlu tabel lengkap
13
+ // Unicode karena kesalahan pada blok langka jauh lebih murah daripada
14
+ // menyeret dependensi.
15
+
16
+ /** Rentang lebar-ganda (UAX #11 kategori W/F). */
17
+ const WIDE: [number, number][] = [
18
+ [0x1100, 0x115f], // Hangul Jamo awal
19
+ [0x2e80, 0x303e], // CJK Radicals, Kangxi, simbol CJK
20
+ [0x3041, 0x33ff], // Hiragana, Katakana, Bopomofo, Hangul Compat, CJK Compat
21
+ [0x3400, 0x4dbf], // CJK Ext A
22
+ [0x4e00, 0x9fff], // CJK Unified
23
+ [0xa000, 0xa4cf], // Yi
24
+ [0xa960, 0xa97f], // Hangul Jamo Ext A
25
+ [0xac00, 0xd7a3], // Hangul Syllables
26
+ [0xf900, 0xfaff], // CJK Compat Ideographs
27
+ [0xfe10, 0xfe19], // Vertical forms
28
+ [0xfe30, 0xfe6f], // CJK Compat Forms
29
+ [0xff00, 0xff60], // Fullwidth Forms
30
+ [0xffe0, 0xffe6], // Fullwidth signs
31
+ [0x1f300, 0x1f64f], // Emoji: simbol & pictograph, emoticon
32
+ [0x1f680, 0x1f6ff], // Transport
33
+ [0x1f900, 0x1f9ff], // Supplemental symbols
34
+ [0x1fa70, 0x1faff], // Extended-A
35
+ [0x20000, 0x2fffd], // CJK Ext B+
36
+ [0x30000, 0x3fffd],
37
+ ]
38
+
39
+ /** Rentang lebar-nol: combining marks, variation selector, ZWJ, kontrol format. */
40
+ const ZERO: [number, number][] = [
41
+ [0x0300, 0x036f], // Combining Diacritical Marks
42
+ [0x0483, 0x0489],
43
+ [0x0591, 0x05bd],
44
+ [0x0610, 0x061a],
45
+ [0x064b, 0x065f],
46
+ [0x0670, 0x0670],
47
+ [0x06d6, 0x06dc],
48
+ [0x0900, 0x0903],
49
+ [0x093a, 0x093a],
50
+ [0x0e31, 0x0e31],
51
+ [0x0e34, 0x0e3a],
52
+ [0x1ab0, 0x1aff], // Combining Diacritical Marks Extended
53
+ [0x1dc0, 0x1dff], // Combining Diacritical Marks Supplement
54
+ [0x200b, 0x200f], // ZWSP, ZWNJ, ZWJ, LRM, RLM
55
+ [0x2028, 0x202e], // separator & bidi
56
+ [0x20d0, 0x20f0], // Combining Diacritical Marks for Symbols
57
+ [0xfe00, 0xfe0f], // Variation Selectors
58
+ [0xfe20, 0xfe2f], // Combining Half Marks
59
+ [0xfeff, 0xfeff], // BOM / ZWNBSP
60
+ [0xe0100, 0xe01ef], // Variation Selectors Supplement
61
+ ]
62
+
63
+ function inRanges(cp: number, ranges: [number, number][]): boolean {
64
+ let lo = 0
65
+ let hi = ranges.length - 1
66
+ while (lo <= hi) {
67
+ const mid = (lo + hi) >> 1
68
+ const [start, end] = ranges[mid]!
69
+ if (cp < start) hi = mid - 1
70
+ else if (cp > end) lo = mid + 1
71
+ else return true
72
+ }
73
+ return false
74
+ }
75
+
76
+ /** Lebar kolom satu code point: 0, 1, atau 2. */
77
+ export function charWidth(cp: number): number {
78
+ if (cp === 0) return 0
79
+ // C0/C1 control: tidak menempati kolom (dan seharusnya tidak sampai ke layar).
80
+ if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 0
81
+ if (inRanges(cp, ZERO)) return 0
82
+ if (inRanges(cp, WIDE)) return 2
83
+ return 1
84
+ }
85
+
86
+ /**
87
+ * Lebar tampil string dalam kolom terminal. Sekuens ANSI dan karakter
88
+ * penggabung tidak dihitung; CJK/emoji dihitung dua.
89
+ */
90
+ export function displayWidth(s: string): number {
91
+ let w = 0
92
+ let i = 0
93
+ while (i < s.length) {
94
+ // Lewati sekuens escape — tidak menempati kolom.
95
+ if (s[i] === "\x1b") {
96
+ const len = escapeLength(s, i)
97
+ if (len > 0) {
98
+ i += len
99
+ continue
100
+ }
101
+ }
102
+ const cp = s.codePointAt(i)!
103
+ w += charWidth(cp)
104
+ i += cp > 0xffff ? 2 : 1
105
+ }
106
+ return w
107
+ }
108
+
109
+ // Klasifikasi byte di dalam CSI: parameter (digit/;/:/</=/>/?), intermediate
110
+ // (!#$%&'()*+,-./), atau final (A-Z a-z @ [ \ ] ^ _ ` { | } ~). SPASI sengaja
111
+ // TIDAK dianggap intermediate: jauh lebih sering itu teks biasa yang mengikuti
112
+ // sekuens yang terpotong daripada bagian dari sekuens itu sendiri.
113
+ function csiByteKind(b: number): "param" | "inter" | "final" | "other" {
114
+ if (b >= 0x40 && b <= 0x7e) return "final"
115
+ if (b >= 0x30 && b <= 0x3f) return "param"
116
+ if (b >= 0x21 && b <= 0x2f) return "inter"
117
+ return "other"
118
+ }
119
+
120
+ /** Panjang sekuens escape yang mulai di `i`, atau 0 bila bukan escape. */
121
+ export function escapeLength(s: string, i: number): number {
122
+ if (s[i] !== "\x1b") return 0
123
+ const next = s[i + 1]
124
+ if (next === "[") {
125
+ // CSI: ESC [ params intermediate* final-byte
126
+ let j = i + 2
127
+ while (j < s.length) {
128
+ const kind = csiByteKind(s.charCodeAt(j)!)
129
+ if (kind === "param" || kind === "inter") j++
130
+ else break
131
+ }
132
+ if (j < s.length && csiByteKind(s.charCodeAt(j)!) === "final") return j - i + 1
133
+ // Tidak ada byte final yang sah: konsumsi HANYA parameter yang sudah
134
+ // terbaca. Sebelumnya scan meneruskan sampai huruf berikutnya di TEKS
135
+ // ("a ESC[33 world" → 'w' ikut ditelan jadi "a orld") — data loss.
136
+ return Math.min(j, s.length) - i
137
+ }
138
+ if (next === "]") {
139
+ // OSC: ESC ] ... BEL | ESC \
140
+ const bel = s.indexOf("\u0007", i + 2)
141
+ const st = s.indexOf("\x1b\\", i + 2)
142
+ if (bel !== -1 && (st === -1 || bel < st)) return bel - i + 1
143
+ if (st !== -1) return st - i + 2
144
+ return s.length - i
145
+ }
146
+ if (next === "P" || next === "_" || next === "^" || next === "X") {
147
+ // DCS/APC/PM/SOS: ESC P/_/^/X ... BEL | ESC \
148
+ const bel = s.indexOf("\u0007", i + 2)
149
+ const st = s.indexOf("\x1b\\", i + 2)
150
+ if (bel !== -1 && (st === -1 || bel < st)) return bel - i + 1
151
+ if (st !== -1) return st - i + 2
152
+ return s.length - i
153
+ }
154
+ // ESC ( B, ESC ) 0, ESC # 8 — charset & DEC line size, 3 byte.
155
+ if (next === "(" || next === ")" || next === "#") return 3
156
+ // ESC diikuti byte final tunggal (ESC 7, ESC =, ESC M, …) = 2 byte.
157
+ // ESC di ujung string = 1 byte. Karakter setelahnya yang BUKAN bagian
158
+ // sekuens (mis. huruf biasa) tidak boleh ikut ditelan — itu membuat teks
159
+ // hilang, jadi hanya byte final yang sah (0x30–0x7E) yang dihitung.
160
+ if (next === undefined) return 1
161
+ const code = next.charCodeAt(0)
162
+ return code >= 0x30 && code <= 0x7e ? 2 : 1
163
+ }
164
+
165
+ /**
166
+ * Potong string ke `width` KOLOM (bukan jumlah karakter), pertahankan sekuens
167
+ * ANSI utuh, dan tutup atribut yang masih terbuka. Tidak pernah membelah
168
+ * surrogate pair atau memisahkan combining mark dari basisnya.
169
+ */
170
+ export function truncateToWidth(s: string, width: number, ellipsis = "..."): string {
171
+ if (width <= 0) return ""
172
+ if (displayWidth(s) <= width) return s
173
+
174
+ const ellW = displayWidth(ellipsis)
175
+ const budget = width > ellW ? width - ellW : width
176
+ let out = ""
177
+ let w = 0
178
+ let sawSgr = false
179
+ let i = 0
180
+ while (i < s.length) {
181
+ if (s[i] === "\x1b") {
182
+ const len = escapeLength(s, i)
183
+ if (len > 0) {
184
+ const seq = s.slice(i, i + len)
185
+ if (seq.endsWith("m")) sawSgr = true
186
+ out += seq
187
+ i += len
188
+ continue
189
+ }
190
+ }
191
+ const cp = s.codePointAt(i)!
192
+ const cw = charWidth(cp)
193
+ if (w + cw > budget) break
194
+ const size = cp > 0xffff ? 2 : 1
195
+ out += s.slice(i, i + size)
196
+ w += cw
197
+ i += size
198
+ }
199
+ const tail = width > ellW ? ellipsis : ""
200
+ return sawSgr ? `${out}\x1b[0m${tail}` : out + tail
201
+ }
202
+
203
+ /** Sisipkan spasi agar lebar tampil mencapai `width`. */
204
+ export function padToWidth(s: string, width: number, align: "left" | "right" = "left"): string {
205
+ const diff = width - displayWidth(s)
206
+ if (diff <= 0) return s
207
+ const pad = " ".repeat(diff)
208
+ return align === "right" ? pad + s : s + pad
209
+ }
210
+
211
+ /**
212
+ * Pecah string menjadi potongan yang masing-masing <= `width` kolom.
213
+ * Dipakai untuk teks tanpa spasi (CJK, URL panjang, hash) yang tidak bisa
214
+ * dipecah di batas kata.
215
+ */
216
+ export function chunkByWidth(s: string, width: number): string[] {
217
+ if (width <= 0) return [s]
218
+ const out: string[] = []
219
+ let cur = ""
220
+ let w = 0
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 = ""
225
+ while (i < s.length) {
226
+ if (s[i] === "\x1b") {
227
+ const len = escapeLength(s, i)
228
+ if (len > 0) {
229
+ const seq = s.slice(i, i + len)
230
+ 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
+ }
237
+ cur += seq
238
+ i += len
239
+ continue
240
+ }
241
+ }
242
+ const cp = s.codePointAt(i)!
243
+ const cw = charWidth(cp)
244
+ const size = cp > 0xffff ? 2 : 1
245
+ if (w + cw > width && cur !== "") {
246
+ out.push(cur)
247
+ cur = openSgr // lanjutkan warna ke potongan berikutnya
248
+ w = 0
249
+ }
250
+ cur += s.slice(i, i + size)
251
+ w += cw
252
+ i += size
253
+ }
254
+ if (cur !== "") out.push(cur)
255
+ return out.length ? out : [""]
256
+ }