minicode-ai 0.14.1 → 0.14.2

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 (79) hide show
  1. package/README.md +1 -1
  2. package/cli/auto-update.ts +32 -2
  3. package/cli/index.ts +10 -2
  4. package/cli/setup.ts +8 -3
  5. package/cli/tui.ts +18 -15
  6. package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
  7. package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
  8. package/docs/README.md +2 -2
  9. package/docs/TERMINAL_CONTRACT.md +52 -26
  10. package/docs/getting-started.md +14 -12
  11. package/docs/glossary.md +1 -1
  12. package/docs/mcp-lsp.md +1 -1
  13. package/docs/policy-sandbox.md +7 -1
  14. package/docs/security-model.md +2 -2
  15. package/docs/security.md +7 -1
  16. package/docs/tools.md +4 -4
  17. package/docs/verify-benchmark.md +16 -0
  18. package/package.json +1 -3
  19. package/src/app/mentions.ts +4 -3
  20. package/src/app/session.ts +13 -9
  21. package/src/app/tool-layer.ts +6 -0
  22. package/src/constants.ts +17 -0
  23. package/src/lib/git-hardening.ts +27 -22
  24. package/src/lib/safe-open.ts +73 -19
  25. package/src/lib/trusted-exec.ts +7 -4
  26. package/src/mcp/client.ts +34 -9
  27. package/src/mcp/transport.ts +96 -42
  28. package/src/memory/files.ts +15 -4
  29. package/src/memory/vector.ts +5 -1
  30. package/src/policy/context.ts +21 -13
  31. package/src/policy/tool-contract.ts +4 -10
  32. package/src/policy/update-check.ts +83 -6
  33. package/src/policy/usage.ts +17 -7
  34. package/src/presentation/adapter.ts +64 -2
  35. package/src/presentation/events.ts +6 -0
  36. package/src/presentation/model.ts +1 -0
  37. package/src/presentation/projection.ts +2 -0
  38. package/src/presentation/reducer.ts +1 -0
  39. package/src/providers/anthropic.ts +52 -19
  40. package/src/providers/guards.ts +98 -13
  41. package/src/providers/responses.ts +61 -23
  42. package/src/providers/sse-bounds.ts +170 -0
  43. package/src/repo/repomap.ts +10 -11
  44. package/src/runtime/execution-backend.ts +7 -8
  45. package/src/sandbox/docker.ts +113 -9
  46. package/src/session/checkpoint.ts +9 -2
  47. package/src/session/persistence.ts +5 -2
  48. package/src/session/verification.ts +55 -16
  49. package/src/skills/loader.ts +16 -3
  50. package/src/tools/bash.ts +6 -3
  51. package/src/tools/code_run.ts +6 -5
  52. package/src/tools/context.ts +8 -0
  53. package/src/tools/delete_file.ts +2 -1
  54. package/src/tools/edit.ts +2 -1
  55. package/src/tools/git.ts +128 -54
  56. package/src/tools/glob.ts +2 -1
  57. package/src/tools/grep.ts +31 -6
  58. package/src/tools/lsp.ts +5 -4
  59. package/src/tools/mcp_call.ts +3 -1
  60. package/src/tools/memory.ts +175 -180
  61. package/src/tools/move_file.ts +2 -1
  62. package/src/tools/patch.ts +2 -1
  63. package/src/tools/read_file.ts +94 -1
  64. package/src/tools/read_image.ts +2 -1
  65. package/src/tools/task.ts +2 -1
  66. package/src/tools/todo.ts +4 -5
  67. package/src/tools/web_fetch.ts +28 -12
  68. package/src/tools/web_search.ts +28 -9
  69. package/src/tools/write_file.ts +2 -1
  70. package/src/ui/assistant/simple.ts +72 -3
  71. package/src/ui/i18n/en.ts +3 -0
  72. package/src/ui/i18n/id.ts +3 -0
  73. package/src/ui/render/width.ts +107 -79
  74. package/src/ui/runtime/screen.ts +49 -37
  75. package/src/ui/tui/app.ts +255 -205
  76. package/src/ui/tui/transcript.ts +39 -0
  77. package/CHANGELOG.md +0 -1185
  78. package/docs/PLAN_UIUX_V6.md +0 -209
  79. package/docs/changelog.md +0 -3
@@ -5,28 +5,41 @@ import { fenceUntrustedToolOutput, isAlreadyFenced, scrubSecrets } from "../poli
5
5
 
6
6
  const MAX_REDIRECTS = LIMITS.WEB_FETCH_MAX_REDIRECTS
7
7
  // Hard-cap pembacaan body SEBELUM slicing — cegah OOM dari response raksasa.
8
- const BODY_HARD_CAP_CHARS = LIMITS.WEB_FETCH_BODY_HARD_CAP_CHARS
8
+ const BODY_HARD_CAP_BYTES = LIMITS.WEB_RESPONSE_BODY_HARD_CAP_BYTES
9
9
 
10
10
  // Diekspor untuk web_search (jalur DDG): satu kebijakan cap untuk semua fetch.
11
- export async function readBodyCapped(res: Response, controller: AbortController): Promise<string> {
12
- if (!res.body) return ""
11
+ export async function readBodyCapped(
12
+ res: Response,
13
+ controller: AbortController,
14
+ ): Promise<{ text: string; truncated: boolean }> {
15
+ if (!res.body) return { text: "", truncated: false }
13
16
  const reader = res.body.getReader()
14
17
  const decoder = new TextDecoder()
15
18
  let out = ""
19
+ let bytesRead = 0
20
+ let truncated = false
16
21
  try {
17
22
  while (true) {
18
23
  const { done, value } = await reader.read()
19
- if (done) break
20
- out += decoder.decode(value, { stream: true })
21
- if (out.length > BODY_HARD_CAP_CHARS) {
22
- controller.abort(new Error("response exceeds body hard cap"))
24
+ if (done) {
25
+ out += decoder.decode()
23
26
  break
24
27
  }
28
+ const remaining = BODY_HARD_CAP_BYTES - bytesRead
29
+ if (value.byteLength > remaining) {
30
+ if (remaining > 0) out += decoder.decode(value.subarray(0, remaining), { stream: true })
31
+ truncated = true
32
+ controller.abort(new Error("response exceeds body byte cap"))
33
+ await reader.cancel().catch(() => {})
34
+ break
35
+ }
36
+ bytesRead += value.byteLength
37
+ out += decoder.decode(value, { stream: true })
25
38
  }
26
39
  } finally {
27
40
  reader.releaseLock()
28
41
  }
29
- return out
42
+ return { text: out, truncated }
30
43
  }
31
44
 
32
45
  // Snippet body error dengan cap streaming (F-15): cukup untuk diagnosis,
@@ -147,11 +160,14 @@ export const webFetchTool: Tool = {
147
160
  }
148
161
 
149
162
  const contentType = res.headers.get("content-type") ?? ""
150
- const raw = await readBodyCapped(res, controller)
151
- const scrubbed = scrubSecrets(raw)
163
+ const body = await readBodyCapped(res, controller)
164
+ const scrubbed = scrubSecrets(body.text)
152
165
  const sliced = scrubbed.slice(0, limit)
153
- const truncated =
166
+ const outputTruncation =
154
167
  scrubbed.length > limit ? `\n\n… truncated ${scrubbed.length - limit} chars` : ""
168
+ const byteTruncation = body.truncated
169
+ ? `\n\n… response truncated at ${BODY_HARD_CAP_BYTES} bytes`
170
+ : ""
155
171
  // Header tak boleh menggema kredensial: userinfo dihapus STRUKTURAL
156
172
  // (scrub pola tak kenal `user:pass@`), query disamarkan via scrubSecrets
157
173
  // (pola sama seperti body). Divalidasi e2e bug-hunt 2026-09-19 F4:
@@ -161,7 +177,7 @@ export const webFetchTool: Tool = {
161
177
  shown.username = ""
162
178
  shown.password = ""
163
179
  const header = `[${scrubSecrets(shown.toString())} ${res.status} ${contentType}]\n`
164
- const content = (header + sliced + truncated).slice(0, limit + 500)
180
+ const content = (header + sliced + outputTruncation + byteTruncation).slice(0, limit + 500)
165
181
  // [Fase 4 / TOOL-05] Pagar data tak-terpercaya pada output web_fetch
166
182
  return isAlreadyFenced(content) ? content : fenceUntrustedToolOutput("web_fetch", content)
167
183
  } finally {
@@ -54,15 +54,21 @@ export const webSearchTool: Tool = {
54
54
  signal: controller.signal,
55
55
  })
56
56
  if (res.ok) {
57
- const data = (await res.json()) as {
57
+ const body = await readBodyCapped(res, controller)
58
+ if (body.truncated) throw new Error("Tavily response exceeds body byte cap")
59
+ const data = JSON.parse(body.text) as {
58
60
  results?: { title: string; url: string; content: string }[]
59
61
  }
60
62
  const results = (data.results ?? []).slice(0, n)
61
63
  const out = results
62
64
  .map((r, i) => `${i + 1}. ${r.title}\n ${r.url}\n ${cutSnippet(r.content)}`)
63
65
  .join("\n\n")
64
- return capTotal(`[tavily ${results.length} results for "${q}"]\n${out}`, 20000)
66
+ const content = capTotal(`[tavily ${results.length} results for "${q}"]\n${out}`, 20000)
67
+ return isAlreadyFenced(content)
68
+ ? content
69
+ : fenceUntrustedToolOutput("web_search", content)
65
70
  }
71
+ await res.body?.cancel().catch(() => {})
66
72
  } finally {
67
73
  clearTimeout(t)
68
74
  ctx.signal.removeEventListener("abort", onAbort)
@@ -88,7 +94,9 @@ export const webSearchTool: Tool = {
88
94
  },
89
95
  )
90
96
  if (res.ok) {
91
- const data = (await res.json()) as {
97
+ const body = await readBodyCapped(res, controller)
98
+ if (body.truncated) throw new Error("Brave response exceeds body byte cap")
99
+ const data = JSON.parse(body.text) as {
92
100
  web?: { results?: { title: string; url: string; description: string }[] }
93
101
  }
94
102
  const results = (data.web?.results ?? []).slice(0, n)
@@ -99,9 +107,16 @@ export const webSearchTool: Tool = {
99
107
  `${i + 1}. ${r.title}\n ${r.url}\n ${cutSnippet(r.description ?? "")}`,
100
108
  )
101
109
  .join("\n\n")
102
- return capTotal(`[brave ${results.length} results for "${q}"]\n${out}`, 20000)
110
+ const content = capTotal(
111
+ `[brave ${results.length} results for "${q}"]\n${out}`,
112
+ 20000,
113
+ )
114
+ return isAlreadyFenced(content)
115
+ ? content
116
+ : fenceUntrustedToolOutput("web_search", content)
103
117
  }
104
118
  }
119
+ await res.body?.cancel().catch(() => {})
105
120
  } finally {
106
121
  clearTimeout(t)
107
122
  ctx.signal.removeEventListener("abort", onAbort)
@@ -125,7 +140,8 @@ export const webSearchTool: Tool = {
125
140
  })
126
141
  // Cap streaming seperti web_fetch (bug-hunt 2026-09-19: res.text()
127
142
  // tanpa batas = transient ~2x body di heap untuk halaman raksasa).
128
- const html = await readBodyCapped(res, controller)
143
+ const body = await readBodyCapped(res, controller)
144
+ const html = body.text
129
145
  const scrubbed = scrubSecrets(html)
130
146
  // DDG markup berubah-ubah; coba dua pola kelas umum.
131
147
  const resRe = /<a[^>]+class="result__url"[^>]*href="([^"]+)"[^>]*>([^<]+)<\/a>/g
@@ -142,18 +158,21 @@ export const webSearchTool: Tool = {
142
158
  }
143
159
  }
144
160
  if (results.length) {
161
+ const truncation = body.truncated ? " · response truncated at byte cap" : ""
145
162
  const content = capTotal(
146
- `[duckduckgo ${results.length} results for "${q}"]\n${results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}`).join("\n")}`,
163
+ `[duckduckgo ${results.length} results for "${q}"${truncation}]\n${results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}`).join("\n")}`,
147
164
  8000,
148
165
  )
149
166
  return isAlreadyFenced(content)
150
167
  ? content
151
- : fenceUntrustedToolOutput("web_search", content, `query=${q}`)
168
+ : fenceUntrustedToolOutput("web_search", content)
152
169
  }
153
- const fallback = `[web_search] no structured results for "${q}" — coba set TAVILY_API_KEY atau BRAVE_API_KEY untuk hasil lebih baik.`
170
+ const fallback = body.truncated
171
+ ? `[web_search] DuckDuckGo response exceeded the byte cap before structured results could be parsed for "${q}" — coba set TAVILY_API_KEY atau BRAVE_API_KEY.`
172
+ : `[web_search] no structured results for "${q}" — coba set TAVILY_API_KEY atau BRAVE_API_KEY untuk hasil lebih baik.`
154
173
  return isAlreadyFenced(fallback)
155
174
  ? fallback
156
- : fenceUntrustedToolOutput("web_search", fallback, `query=${q}`)
175
+ : fenceUntrustedToolOutput("web_search", fallback)
157
176
  } finally {
158
177
  clearTimeout(t)
159
178
  ctx.signal.removeEventListener("abort", onAbort)
@@ -5,6 +5,7 @@ import { LIMITS } from "../constants.ts"
5
5
  import { atomicWriteText } from "../lib/atomic-write.ts"
6
6
  import { assertSafeWriteTarget, resolveSafePath } from "../lib/safe-open.ts"
7
7
  import { appendLspDiagnostics } from "../policy/verifier.ts"
8
+ import { requireToolCwd } from "./context.ts"
8
9
 
9
10
  export const writeFileTool: Tool = {
10
11
  name: "write_file",
@@ -22,7 +23,7 @@ export const writeFileTool: Tool = {
22
23
  async execute({ path, content }, ctx) {
23
24
  ctx.signal.throwIfAborted()
24
25
  const p = path as string
25
- const root = ctx.cwd ?? process.cwd()
26
+ const root = requireToolCwd(ctx)
26
27
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
27
28
  const { real: realAbs } = await resolveSafePath(p, root)
28
29
  // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
@@ -176,8 +176,8 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
176
176
  // aliran (model/reasoning/bash) agar state ekor tak tercampur. Ekor yang
177
177
  // tersisa saat turn selesai/detach DIBUANG (flush di bawah): escape tanpa
178
178
  // teks lanjutan tak punya efek tampak kecuali mutasi state terminal.
179
- const textSan = createStreamSanitizer()
180
- const reasoningSan = createStreamSanitizer()
179
+ let textSan = createStreamSanitizer()
180
+ let reasoningSan = createStreamSanitizer()
181
181
  const bashSan = createStreamSanitizer()
182
182
  // State fence dipegang DI SINI, bukan di decorateMarkdown: baris datang per
183
183
  // event streaming, sedangkan decorateMarkdown memproses satu teks utuh.
@@ -206,6 +206,14 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
206
206
  // /copy tak tersentuh (rememberTurn selalu jalan sebelum sink).
207
207
  let answerBuf = ""
208
208
  let answerTruncated = false
209
+ let activeProviderAttempt: number | null = null
210
+ let attemptCopyText = ""
211
+ let attemptAnswerBuf = ""
212
+ let attemptAnswerTruncated = false
213
+ let attemptThinkingBuf = ""
214
+ let attemptReasoningLine = ""
215
+ let attemptThinkState: "off" | "min" | "exp" = "off"
216
+ let attemptFence: FenceMatch | null = null
209
217
  const ANSWER_BUF_MAX = 1_000_000
210
218
  // Jawaban tak pernah disembunyikan di pipa/CI (output mesin harus utuh)
211
219
  // dan --verbose selalu menampilkan semua.
@@ -565,6 +573,8 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
565
573
  reasoningLine = ""
566
574
  answerBuf = ""
567
575
  answerTruncated = false
576
+ activeProviderAttempt = null
577
+ attemptCopyText = ""
568
578
  ui.clearCollapsedSections()
569
579
  ui.setActiveSection(null)
570
580
  archiveTurn(ui)
@@ -605,12 +615,71 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
605
615
  answerTruncated = false
606
616
  }
607
617
  const clean = cleanUntrusted(textSan.push(e.text), !!process.stdout.isTTY)
608
- rememberTurn(ui, clean)
618
+ if (activeProviderAttempt === null) {
619
+ // Kompatibilitas untuk bus provider legacy yang tidak melewati guard.
620
+ rememberTurn(ui, clean)
621
+ } else if (attemptCopyText.length < ANSWER_BUF_MAX) {
622
+ attemptCopyText += clean.slice(0, ANSWER_BUF_MAX - attemptCopyText.length)
623
+ }
609
624
  consumeTableEvents(tableStream.push(clean))
610
625
  }),
611
626
  )
612
627
  offs.push(
613
628
  bus.on("provider:extension", (e) => {
629
+ if (e.kind === "minicode:attempt") {
630
+ const data = e.data as {
631
+ phase?: unknown
632
+ attemptId?: unknown
633
+ hadVisibleOutput?: unknown
634
+ } | null
635
+ const id = data?.attemptId
636
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id < 1) return
637
+ if (data?.phase === "started") {
638
+ // Batas attempt juga menjadi batas stream markdown dan ANSI. Teks
639
+ // attempt sebelumnya yang sudah diterima dipertahankan; state parsial
640
+ // yang belum dirender diselesaikan sebelum attempt baru dimulai.
641
+ flushTableStream()
642
+ tableStream.reset()
643
+ activeProviderAttempt = id
644
+ attemptCopyText = ""
645
+ attemptAnswerBuf = answerBuf
646
+ attemptAnswerTruncated = answerTruncated
647
+ attemptThinkingBuf = thinkingBuf
648
+ attemptReasoningLine = reasoningLine
649
+ attemptThinkState = thinkState
650
+ attemptFence = fence ? { ...fence } : null
651
+ textSan = createStreamSanitizer()
652
+ reasoningSan = createStreamSanitizer()
653
+ } else if (id === activeProviderAttempt && data?.phase === "completed") {
654
+ rememberTurn(ui, attemptCopyText)
655
+ activeProviderAttempt = null
656
+ attemptCopyText = ""
657
+ textSan.flush()
658
+ reasoningSan.flush()
659
+ textSan = createStreamSanitizer()
660
+ reasoningSan = createStreamSanitizer()
661
+ } else if (id === activeProviderAttempt && data?.phase === "invalidated") {
662
+ answerBuf = attemptAnswerBuf
663
+ answerTruncated = attemptAnswerTruncated
664
+ thinkingBuf = attemptThinkingBuf
665
+ reasoningLine = attemptReasoningLine
666
+ thinkState = attemptThinkState
667
+ fence = attemptFence ? { ...attemptFence } : null
668
+ plainLineBuffer = ""
669
+ tableStream.reset()
670
+ textSan.flush()
671
+ reasoningSan.flush()
672
+ textSan = createStreamSanitizer()
673
+ reasoningSan = createStreamSanitizer()
674
+ ui.setActiveSection(thinkState === "off" ? null : "thinking")
675
+ activeProviderAttempt = null
676
+ attemptCopyText = ""
677
+ if (data.hadVisibleOutput === true) {
678
+ wErr(c.warning(t("one.providerAttemptDiscarded", { attempt: id })))
679
+ }
680
+ }
681
+ return
682
+ }
614
683
  if (e.kind === "reasoning") {
615
684
  // Section thinking: reasoning.visible = expanded (stream), else
616
685
  // minimized (satu baris ` + thinking`, isi di-buffer untuk /expand).
package/src/ui/i18n/en.ts CHANGED
@@ -39,6 +39,7 @@ export const en = {
39
39
  "appr.tier.unknown": "unknown effect",
40
40
  "dlg.more": "… {n} more",
41
41
  "ts.compacted": "… compacted: {reason}",
42
+ "ts.providerAttemptDiscarded": "provider attempt {attempt} failed; partial output was discarded",
42
43
  "ts.thinking": "… thinking",
43
44
  "ts.evictMarker": "… {n} early lines outside viewport — full history in model",
44
45
  "ts.statusRunning": "running",
@@ -277,6 +278,8 @@ export const en = {
277
278
  "one.answerOpen": " − answer\n",
278
279
  "one.answerMin": " + answer ({n} chars{cap}) — /expand to read\n",
279
280
  "one.answerCap": ", capped 1MB",
281
+ "one.providerAttemptDiscarded":
282
+ "\n[provider attempt {attempt} failed; partial output above is excluded from the final response]\n",
280
283
  "one.thinkOpen": " − thinking\n",
281
284
  "one.thinkMin": " + thinking\n",
282
285
  "one.more3": "\n ... ({n} more)",
package/src/ui/i18n/id.ts CHANGED
@@ -40,6 +40,7 @@ export const id: Record<MsgKey, string> = {
40
40
  "appr.tier.unknown": "efek tidak diketahui",
41
41
  "dlg.more": "… {n} lagi",
42
42
  "ts.compacted": "… dipadatkan: {reason}",
43
+ "ts.providerAttemptDiscarded": "percobaan provider {attempt} gagal; output parsial dibuang",
43
44
  "ts.thinking": "… berpikir",
44
45
  "ts.evictMarker": "… {n} baris awal di luar viewport — riwayat penuh di model",
45
46
  "ts.statusRunning": "berjalan",
@@ -279,6 +280,8 @@ export const id: Record<MsgKey, string> = {
279
280
  "one.answerOpen": " − jawaban\n",
280
281
  "one.answerMin": " + jawaban ({n} karakter{cap}) — /expand untuk baca\n",
281
282
  "one.answerCap": ", dibatasi 1MB",
283
+ "one.providerAttemptDiscarded":
284
+ "\n[percobaan provider {attempt} gagal; output parsial di atas tidak termasuk jawaban akhir]\n",
282
285
  "one.thinkOpen": " − berpikir\n",
283
286
  "one.thinkMin": " + berpikir\n",
284
287
  "one.more3": "\n ... ({n} lagi)",
@@ -1,12 +1,8 @@
1
- // Lebar tampil karakter di terminal.
1
+ // Lebar tampil teks dalam kolom terminal.
2
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.
3
+ // Ukur per grapheme, bukan per code point: satu emoji keluarga atau flag
4
+ // tersusun dari beberapa scalar tetapi tampil sebagai satu glyph dua kolom.
5
+ // Combining marks melekat pada base dan tidak menambah lebar sendiri.
10
6
  //
11
7
  // Referensi: EastAsianWidth (UAX #11) kategori W dan F. Rentang di bawah adalah
12
8
  // blok utama yang relevan untuk keluaran terminal; tidak perlu tabel lengkap
@@ -58,8 +54,77 @@ const ZERO: [number, number][] = [
58
54
  [0xfe20, 0xfe2f], // Combining Half Marks
59
55
  [0xfeff, 0xfeff], // BOM / ZWNBSP
60
56
  [0xe0100, 0xe01ef], // Variation Selectors Supplement
57
+ [0xe0020, 0xe007f], // Tag characters used by emoji flag sequences
61
58
  ]
62
59
 
60
+ const UNICODE_MARK = /\p{Mark}/u
61
+ const EMOJI = /\p{Emoji}/u
62
+ const EMOJI_PRESENTATION = /\p{Emoji_Presentation}/u
63
+ const EXTENDED_PICTOGRAPHIC = /\p{Extended_Pictographic}/u
64
+ let widthSegmenter: Intl.Segmenter | undefined
65
+
66
+ function segmentGraphemes(text: string): string[] {
67
+ try {
68
+ widthSegmenter ??= new Intl.Segmenter("und", { granularity: "grapheme" })
69
+ return Array.from(widthSegmenter.segment(text), (part) => part.segment)
70
+ } catch {
71
+ // Bun yang didukung MiniCode menyediakan Intl.Segmenter; fallback ini
72
+ // menjaga module tetap bisa dipakai di runtime tertanam yang lebih tua.
73
+ return Array.from(text)
74
+ }
75
+ }
76
+
77
+ function graphemeWidth(grapheme: string): number {
78
+ const points = Array.from(grapheme, (part) => part.codePointAt(0)!)
79
+ const has = (from: number, to: number): boolean => points.some((cp) => cp >= from && cp <= to)
80
+ const containsEmoji = points.some((cp) => EMOJI.test(String.fromCodePoint(cp)))
81
+ const containsPictograph = points.some((cp) =>
82
+ EXTENDED_PICTOGRAPHIC.test(String.fromCodePoint(cp)),
83
+ )
84
+ if (
85
+ has(0x20e3, 0x20e3) || // keycap
86
+ has(0x1f1e6, 0x1f1ff) || // regional-indicator flag (including a lone RI, conservatively)
87
+ has(0x1f3fb, 0x1f3ff) || // skin-tone modifier
88
+ (has(0x200d, 0x200d) && containsPictograph) || // emoji ZWJ sequence
89
+ (has(0xfe0f, 0xfe0f) && containsEmoji) || // explicit emoji presentation
90
+ points.some((cp) => EMOJI_PRESENTATION.test(String.fromCodePoint(cp)))
91
+ ) {
92
+ return 2
93
+ }
94
+ let width = 0
95
+ for (const cp of points) width += charWidth(cp)
96
+ return width
97
+ }
98
+
99
+ interface DisplayToken {
100
+ text: string
101
+ width: number
102
+ escape: boolean
103
+ }
104
+
105
+ /** Token terminal: escape utuh atau grapheme utuh dengan lebar display yang sama. */
106
+ function* displayTokens(s: string): Generator<DisplayToken> {
107
+ let i = 0
108
+ while (i < s.length) {
109
+ if (s[i] === "\x1b") {
110
+ const length = escapeLength(s, i)
111
+ if (length > 0) {
112
+ yield { text: s.slice(i, i + length), width: 0, escape: true }
113
+ i += length
114
+ continue
115
+ }
116
+ }
117
+ let end = s.indexOf("\x1b", i)
118
+ if (end < 0) end = s.length
119
+ if (end === i) end = i + 1
120
+ const run = s.slice(i, end)
121
+ for (const text of segmentGraphemes(run)) {
122
+ yield { text, width: graphemeWidth(text), escape: false }
123
+ }
124
+ i = end
125
+ }
126
+ }
127
+
63
128
  function inRanges(cp: number, ranges: [number, number][]): boolean {
64
129
  let lo = 0
65
130
  let hi = ranges.length - 1
@@ -83,31 +148,19 @@ export function charWidth(cp: number): number {
83
148
  if (cp === 0x09) return 8
84
149
  // C0/C1 control: tidak menempati kolom (dan seharusnya tidak sampai ke layar).
85
150
  if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 0
86
- if (inRanges(cp, ZERO)) return 0
151
+ if (inRanges(cp, ZERO) || UNICODE_MARK.test(String.fromCodePoint(cp))) return 0
87
152
  if (inRanges(cp, WIDE)) return 2
88
153
  return 1
89
154
  }
90
155
 
91
156
  /**
92
157
  * Lebar tampil string dalam kolom terminal. Sekuens ANSI dan karakter
93
- * penggabung tidak dihitung; CJK/emoji dihitung dua.
158
+ * penggabung tidak dihitung; CJK/fullwidth dan emoji presentation dihitung
159
+ * dua kolom per grapheme. Lebar glyph spesifik terminal tidak diprobe.
94
160
  */
95
161
  export function displayWidth(s: string): number {
96
162
  let w = 0
97
- let i = 0
98
- while (i < s.length) {
99
- // Lewati sekuens escape — tidak menempati kolom.
100
- if (s[i] === "\x1b") {
101
- const len = escapeLength(s, i)
102
- if (len > 0) {
103
- i += len
104
- continue
105
- }
106
- }
107
- const cp = s.codePointAt(i)!
108
- w += charWidth(cp)
109
- i += cp > 0xffff ? 2 : 1
110
- }
163
+ for (const token of displayTokens(s)) if (!token.escape) w += token.width
111
164
  return w
112
165
  }
113
166
 
@@ -237,36 +290,23 @@ export function truncateToWidth(s: string, width: number, ellipsis = "..."): str
237
290
  let w = 0
238
291
  let sawSgr = false
239
292
  let cut = false
240
- let i = 0
241
- while (i < s.length) {
242
- if (s[i] === "\x1b") {
243
- const len = escapeLength(s, i)
244
- if (len > 0) {
245
- const seq = s.slice(i, i + len)
246
- // Hanya SGR yang disalin — sekuens kontrol lain (clear, alternate
247
- // screen, OSC) DIBUANG di sini agar satu pemanggil yang lupa sanitasi
248
- // tidak menjadi injeksi terminal (defense-in-depth, bukan pengganti
249
- // sanitizeAnsi di batas input tak-terpercaya).
250
- if (!isSgrSeq(seq)) {
251
- i += len
252
- continue
253
- }
254
- if (seq.endsWith("m")) sawSgr = true
255
- out += seq
256
- i += len
257
- continue
258
- }
293
+ for (const token of displayTokens(s)) {
294
+ if (token.escape) {
295
+ // Hanya SGR yang disalin — sekuens kontrol lain (clear, alternate
296
+ // screen, OSC) DIBUANG di sini agar satu pemanggil yang lupa sanitasi
297
+ // tidak menjadi injeksi terminal (defense-in-depth, bukan pengganti
298
+ // sanitizeAnsi di batas input tak-terpercaya).
299
+ if (!isSgrSeq(token.text)) continue
300
+ if (token.text.endsWith("m")) sawSgr = true
301
+ out += token.text
302
+ continue
259
303
  }
260
- const cp = s.codePointAt(i)!
261
- const cw = charWidth(cp)
262
- if (w + cw > budget) {
304
+ if (w + token.width > budget) {
263
305
  cut = true
264
306
  break
265
307
  }
266
- const size = cp > 0xffff ? 2 : 1
267
- out += s.slice(i, i + size)
268
- w += cw
269
- i += size
308
+ out += token.text
309
+ w += token.width
270
310
  }
271
311
  const tail = cut && width > ellW ? ellipsis : ""
272
312
  return sawSgr ? `${out}\x1b[0m${tail}` : out + tail
@@ -290,7 +330,6 @@ export function chunkByWidth(s: string, width: number): string[] {
290
330
  const out: string[] = []
291
331
  let cur = ""
292
332
  let w = 0
293
- let i = 0
294
333
  // Sekuens SGR yang masih "terbuka" — disuntikkan ke potongan berikutnya
295
334
  // agar warna tidak hilang saat kata berwarna panjang dipecah. SEMUA pembuka
296
335
  // diingat (bukan satu): `\x1b[1m\x1b[31m…` yang terbelah harus membawa bold
@@ -304,39 +343,28 @@ export function chunkByWidth(s: string, width: number): string[] {
304
343
  cur = openSgr.join("") // lanjutkan warna ke potongan berikutnya
305
344
  w = 0
306
345
  }
307
- while (i < s.length) {
308
- if (s[i] === "\x1b") {
309
- const len = escapeLength(s, i)
310
- if (len > 0) {
311
- const seq = s.slice(i, i + len)
312
- if (!isSgrSeq(seq)) {
313
- i += len
314
- continue
315
- }
316
- if (seq.endsWith("m")) {
317
- const params = seq.slice(2, -1).split(/[:;]/)
318
- if (params.some((p) => SGR_OFF.has(p) || p === "")) openSgr = []
319
- if (params.some((p) => p !== "" && !SGR_OFF.has(p))) {
320
- openSgr.push(seq)
321
- // Batas tumpukan: input patologis (ganti warna tiap karakter tanpa
322
- // reset) tak boleh membuat tiap potongan membawa ratusan sekuens.
323
- if (openSgr.length > 8) openSgr = openSgr.slice(-8)
324
- }
346
+ for (const token of displayTokens(s)) {
347
+ if (token.escape) {
348
+ const seq = token.text
349
+ if (!isSgrSeq(seq)) continue
350
+ if (seq.endsWith("m")) {
351
+ const params = seq.slice(2, -1).split(/[:;]/)
352
+ if (params.some((p) => SGR_OFF.has(p) || p === "")) openSgr = []
353
+ if (params.some((p) => p !== "" && !SGR_OFF.has(p))) {
354
+ openSgr.push(seq)
355
+ // Batas tumpukan: input patologis (ganti warna tiap karakter tanpa
356
+ // reset) tak boleh membuat tiap potongan membawa ratusan sekuens.
357
+ if (openSgr.length > 8) openSgr = openSgr.slice(-8)
325
358
  }
326
- cur += seq
327
- i += len
328
- continue
329
359
  }
360
+ cur += seq
361
+ continue
330
362
  }
331
- const cp = s.codePointAt(i)!
332
- const cw = charWidth(cp)
333
- const size = cp > 0xffff ? 2 : 1
334
- if (w + cw > width && cur !== "") {
363
+ if (w + token.width > width && cur !== "") {
335
364
  pushChunk()
336
365
  }
337
- cur += s.slice(i, i + size)
338
- w += cw
339
- i += size
366
+ cur += token.text
367
+ w += token.width
340
368
  }
341
369
  if (cur !== "") pushChunk()
342
370
  return out.length ? out : [""]