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,120 @@
1
+ // Word-wrap + justify (rata kanan-kiri) - untuk output teks AI.
2
+ //
3
+ // Semua pengukuran memakai KOLOM terminal (src/ui/render/width.ts), bukan jumlah
4
+ // karakter: CJK/emoji memakan dua kolom, combining mark nol, dan sekuens ANSI
5
+ // tidak menempati kolom sama sekali.
6
+ //
7
+ // stripAnsi di-re-export dari theme.ts: dulu ada dua implementasi terpisah, dan
8
+ // yang di sini tidak ikut diperbaiki saat pola ANSI diperluas untuk sekuens
9
+ // private-mode (ESC[?25l dsb.).
10
+
11
+ import { stripAnsi } from "./theme.ts"
12
+ import { chunkByWidth, displayWidth } from "./width.ts"
13
+
14
+ export { stripAnsi }
15
+
16
+ /** Lebar tampil dalam kolom terminal. */
17
+ export function visibleLen(s: string): number {
18
+ return displayWidth(s)
19
+ }
20
+
21
+ /**
22
+ * Wrap teks ke baris-baris <= `width` KOLOM, dipotong di batas spasi.
23
+ *
24
+ * Kata yang sendirian sudah lebih lebar dari `width` (URL panjang, hash, atau
25
+ * teks CJK yang memang tidak punya spasi) dipecah per kolom — sebelumnya
26
+ * dibiarkan utuh sehingga baris membungkus sendiri di terminal dan merusak
27
+ * frame TUI yang menghitung tinggi per baris.
28
+ */
29
+ export function wordWrap(text: string, width: number): string {
30
+ if (width <= 0) return text
31
+ const out: string[] = []
32
+ for (const line of text.split("\n")) {
33
+ if (displayWidth(line) <= width) {
34
+ out.push(line)
35
+ continue
36
+ }
37
+ let current = ""
38
+ const flush = () => {
39
+ if (current !== "") {
40
+ // Spasi pemisah di ujung tidak ikut tampil.
41
+ out.push(current.trimEnd())
42
+ current = ""
43
+ }
44
+ }
45
+ // Pisah dengan pemisah tertangkap agar spasi ganda (ASCII art/tabel)
46
+ // tetap utuh — run whitespace menempel ke kata berikut, wrap hanya putus
47
+ // di batas run (spasi di ujung baris dibuang saat flush).
48
+ for (const tok of line.split(/(\s+)/)) {
49
+ if (tok === "") continue
50
+ if (/^\s+$/.test(tok)) {
51
+ if (current !== "") current += tok
52
+ continue
53
+ }
54
+ const word = tok
55
+ // Kata tunggal lebih lebar dari baris: pecah paksa per kolom.
56
+ if (displayWidth(word) > width) {
57
+ flush()
58
+ const pieces = chunkByWidth(word, width)
59
+ for (let i = 0; i < pieces.length - 1; i++) out.push(pieces[i]!)
60
+ current = pieces[pieces.length - 1] ?? ""
61
+ continue
62
+ }
63
+ // `current` sudah memuat run whitespace aslinya; tambah satu spasi
64
+ // hanya bila tidak ada pemisah di antara dua kata.
65
+ const glued = !current || /\s$/.test(current) ? `${current}${word}` : `${current} ${word}`
66
+ if (displayWidth(glued) > width && current) {
67
+ out.push(current.trimEnd())
68
+ current = word
69
+ } else {
70
+ current = glued
71
+ }
72
+ }
73
+ flush()
74
+ }
75
+ return out.join("\n")
76
+ }
77
+
78
+ // Justify satu baris: distribusi spasi ekstra supaya ujung kiri & kanan rata.
79
+ // Baris kosong / <2 kata / baris yang sudah penuh dibiarkan.
80
+ export function justifyLine(line: string, width: number): string {
81
+ const clean = displayWidth(line)
82
+ if (clean >= width || width <= 0) return line
83
+ const words = line.split(" ")
84
+ if (words.length < 2) return line
85
+ const gaps = words.length - 1
86
+ const extra = width - clean
87
+ const perGap = Math.floor(extra / gaps)
88
+ const extraGap = extra % gaps
89
+ return words
90
+ .map((w, i) => {
91
+ if (i >= gaps) return w
92
+ const spaces = 1 + perGap + (i < extraGap ? 1 : 0)
93
+ return w + " ".repeat(spaces)
94
+ })
95
+ .join("")
96
+ }
97
+
98
+ // Wrap + justify: untuk output streaming per paragraf.
99
+ //
100
+ // Baris TERAKHIR paragraf tidak dijustify — menjustifikasinya menghasilkan
101
+ // "sungai" spasi seperti `dengan lebar tertentu`, kesalahan tipografi
102
+ // klasik. MINICODE_JUSTIFY=0 mematikan justify sepenuhnya.
103
+ export function formatWrapped(text: string, width: number, justify = true): string {
104
+ const wrapped = wordWrap(text, width)
105
+ if (!justify || process.env.MINICODE_JUSTIFY === "0") return wrapped
106
+ const lines = wrapped.split("\n")
107
+ return lines
108
+ .map((line, i) => {
109
+ const plain = stripAnsi(line)
110
+ if (/^\s*(```|#|[-*] |>\s)/.test(plain) || /^\s*$/.test(plain)) return line
111
+ // Baris dengan spasi ganda (tabel ASCII/art) jangan dijustify —
112
+ // justifyLine akan meratakan ulang run spasi yang disengaja.
113
+ if (plain.includes(" ")) return line
114
+ // Baris terakhir, atau baris tepat sebelum baris kosong (= akhir paragraf).
115
+ const isParagraphEnd = i === lines.length - 1 || /^\s*$/.test(lines[i + 1] ?? "")
116
+ if (isParagraphEnd) return line
117
+ return justifyLine(line, width)
118
+ })
119
+ .join("\n")
120
+ }
@@ -0,0 +1,83 @@
1
+ import type { UiBus, UiEvent, UiEventType } from "../contract.ts"
2
+
3
+ // Diagnosis event bus per turn: MINICODE_DEBUG_BUS=1 mencetak satu baris
4
+ // ringkas per event bus ke stderr (`[bus] ...`). Dipakai membedakan dua
5
+ // penyebab "macet" yang gejalanya identik: (a) event yatim turn lama yang
6
+ // bocor ke sesi prompt baru (pagar turn di runPromptWithVerify seharusnya
7
+ // membuatnya hening — bila dump tetap menunjukkan event, pagarnya yang bocor),
8
+ // vs (b) stdin yang benar-benar mati (dump hening total).
9
+ //
10
+ // SENGAJA tanpa isi konten: hanya tipe, nama tool, dan PANJANG teks —
11
+ // tak ada payload model/tool yang bisa membawa secret ke log. Tanpa env =
12
+ // tanpa subscribe sama sekali (zero-cost, zero-noise).
13
+ // Dipasang sekali per sesi (bukan per turn) agar justru event yatim pun
14
+ // terlihat; dilepas di close().
15
+
16
+ const MAX_LINE = 300
17
+
18
+ function summarize(type: string, e: unknown): string {
19
+ try {
20
+ switch (type) {
21
+ case "turn:started": {
22
+ const t = (e as { turn?: unknown }).turn
23
+ return `turn:started #${typeof t === "number" ? t : "?"}`
24
+ }
25
+ case "turn:completed":
26
+ return "turn:completed"
27
+ case "provider:text": {
28
+ const t = (e as { text?: unknown }).text
29
+ return `text ${typeof t === "string" ? t.length : 0}ch`
30
+ }
31
+ case "provider:extension": {
32
+ const k = (e as { kind?: unknown }).kind
33
+ const d = (e as { data?: unknown }).data as { text?: unknown } | undefined
34
+ const n = typeof d?.text === "string" ? d.text.length : 0
35
+ return `ext:${String(k ?? "?")} ${n}ch`
36
+ }
37
+ case "execution:started": {
38
+ const c = (e as { execution?: { call?: { name?: unknown } } }).execution?.call
39
+ return `start:${String(c?.name ?? "?")}`
40
+ }
41
+ case "execution:completed": {
42
+ const x = (
43
+ e as { execution?: { call?: { name?: unknown }; result?: { isError?: unknown } } }
44
+ ).execution
45
+ return `done:${String(x?.call?.name ?? "?")}${x?.result?.isError ? ":err" : ""}`
46
+ }
47
+ case "step:started":
48
+ return "step:started"
49
+ default:
50
+ return type
51
+ }
52
+ } catch {
53
+ return "?"
54
+ }
55
+ }
56
+
57
+ const TYPES: UiEventType[] = [
58
+ "turn:started",
59
+ "turn:completed",
60
+ "provider:text",
61
+ "provider:extension",
62
+ "execution:started",
63
+ "execution:completed",
64
+ "step:started",
65
+ ]
66
+
67
+ export function attachBusDebug(bus: UiBus): () => void {
68
+ if (process.env.MINICODE_DEBUG_BUS !== "1") return () => {}
69
+ const offs = TYPES.map((t) =>
70
+ bus.on(t, (e: UiEvent) => {
71
+ try {
72
+ process.stderr.write(`[bus] ${summarize(t, e).slice(0, MAX_LINE)}\n`)
73
+ } catch {}
74
+ }),
75
+ )
76
+ return () => {
77
+ for (const off of offs) {
78
+ try {
79
+ off()
80
+ } catch {}
81
+ }
82
+ }
83
+ }
@@ -0,0 +1,301 @@
1
+ // Footer lengket (sticky) — chrome terminal REPL.
2
+ //
3
+ // Mengunci 2 baris dasar terminal untuk footer (blank + status, tanpa garis)
4
+ // lewat scroll-region DECSTBM (`\x1b[1;{top}r`): output turn hanya di area
5
+ // atas, footer tidak pernah ikut scroll. Sama dengan kontrak transient
6
+ // statusline.ts: TIDAK pernah melempar, fail-closed, self-disable bila runtime
7
+ // bermasalah, dan selalui reset region pada detach/exit agar terminal tidak
8
+ // ditinggalkan rusak.
9
+ //
10
+ // Gaya `MINICODE_FOOTER`:
11
+ // off → tanpa footer sama sekali (dan pipa selalu none: 0 byte)
12
+ // print → footer dicetak sebagai baris scrollback biasa (tidak lengket)
13
+ // sticky → paksa lengket (bila terminal mampu; selain itu jatuh ke print)
14
+ // auto → lengket bila mampu, print bila tidak (DEFAULT)
15
+ //
16
+ // Mengapa DECSTBM dan bukan alternate screen: alternaate screen menyembunyikan
17
+ // seluruh scrollback pengguna — melanggar kontrak shell-native. Scroll-region
18
+ // justru TIDAK memindahkan scrollback: region adalah jendela scroll TAMBAHAN,
19
+ // konten lama tetap utuh di atasnya.
20
+ import { type FooterStatus, renderFooter } from "../footer.ts"
21
+
22
+ export type FooterMode = "off" | "print" | "sticky" | "auto"
23
+
24
+ export interface FooterChromeOptions {
25
+ /** Status yang dirender tiap present — di-resolve pemanggil (mode live, cwd). */
26
+ status: () => FooterStatus
27
+ /** Non-interactive (exec/pipe): pemanggil mematikan footer total. */
28
+ enabled?: boolean
29
+ }
30
+
31
+ export interface FooterChrome {
32
+ readonly mode: "sticky" | "print" | "none"
33
+ /** Baris dasar yang wajib disisakan editor/prompt (sticky=2, lainnya 0). */
34
+ reserveRows(): number
35
+ /**
36
+ * Panggil tepat sebelum prompt idle: sticky → pastikan region + repaint
37
+ * footer + posisikan kursor di baris input; print → cetak footer sebagai
38
+ * baris scrollback. Idempotent; tidak pernah melempar.
39
+ */
40
+ present(): void
41
+ /**
42
+ * Repaint footer DI TEMPAT tanpa memindahkan kursor — dipakai perubahan
43
+ * status saat prompt aktif (mis. Shift+Tab ganti mode). Sticky: repaint 2
44
+ * baris dasar; print/none: no-op (footer berikutnya dicetak di idle).
45
+ */
46
+ refresh(): void
47
+ /**
48
+ * Tandai turn berjalan/selesai. Busy → spark di footer berdenyut (timer
49
+ * repaint ~150ms, fail-safe: tak pernah melempar, mati sendiri bila runtime
50
+ * rewel); idle → spark redup statis. Dipanggil dari controller turn, jadi
51
+ * abort (Ctrl+C/Esc) otomatis kembali redup lewat finally.
52
+ */
53
+ setBusy(busy: boolean): void
54
+ /**
55
+ * Reset region + restore scrollback, lalu cetak footer sekali sebagai baris
56
+ * normal. Panggil di SEMUA jalur keluar (close/exit/SIGINT/on("exit")).
57
+ */
58
+ detach(): void
59
+ }
60
+
61
+ // ── State pemilih mode (module-level agar input.ts bisa baca jatah baris) ──
62
+
63
+ let activeReserve = 0
64
+
65
+ /** Jatah baris dasar yang sedang dipakai chrome (0 bila tidak lengket). */
66
+ export function footerReserveRows(): number {
67
+ return activeReserve
68
+ }
69
+
70
+ const RESET_REGION = "\x1b[r"
71
+ const CLEAR = "\x1b[2K"
72
+ const SYNC_START = "\x1b[?2026h"
73
+ const SYNC_END = "\x1b[?2026l"
74
+ // DECSC/DECRC (save/restore cursor). Dipakai agar penulisan direct-address
75
+ // footer + DECSTBM tidak pernah menggeser posisi ketik: sebagian terminal
76
+ // (emulasi VT100) memindahkan kursor ke home saat scroll-region di-set, dan
77
+ // `refresh()` dipanggil saat prompt aktif — tanpa save/restore, repaint
78
+ // berikutnya menimpa baris footer.
79
+ const SAVE_CURSOR = "\x1b7"
80
+ const RESTORE_CURSOR = "\x1b8"
81
+
82
+ function isWinLegacy(): boolean {
83
+ return (
84
+ process.platform === "win32" &&
85
+ !(
86
+ process.env.WT_SESSION ||
87
+ process.env.TERM_PROGRAM ||
88
+ process.env.ANSICON ||
89
+ process.env.ConEmuANSI
90
+ )
91
+ )
92
+ }
93
+
94
+ /** Sticky butuh VT DECSTBM + baris cukup (2 dasar + ≥9 area kerja). */
95
+ function capable(rows: number): boolean {
96
+ if (isWinLegacy()) return false
97
+ if (rows < 10) return false
98
+ return true
99
+ }
100
+
101
+ /** Posisi 1-indexed dari 2 baris dasar (blank + status, tanpa garis). */
102
+ const FOOTER_ROWS = 2
103
+
104
+ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
105
+ // Pipa/redirect: nol byte — kontrak deterministik machine output.
106
+ if (!opts.enabled || !process.stdout.isTTY) return makeNone()
107
+ const env = (process.env.MINICODE_FOOTER ?? "auto") as string
108
+ const want: FooterMode = env === "off" || env === "print" || env === "sticky" ? env : "auto"
109
+ const rows = () => process.stdout.rows || 24
110
+
111
+ const sticky = want === "sticky" || want === "auto"
112
+ const useSticky = sticky && capable(rows())
113
+ // sticky yang diminta tapi terminal tak mampu → print (tetap ada footer,
114
+ // hanya tidak lengket) — bukan none.
115
+ const mode: "sticky" | "print" | "none" =
116
+ !sticky && want === "off" ? "none" : useSticky ? "sticky" : "print"
117
+ if (mode === "none") return makeNone()
118
+ if (mode === "print") return makePrint(opts)
119
+
120
+ // ── Sticky ──
121
+ let regionOn = false
122
+ let detached = false
123
+ let resizeBound: (() => void) | null = null
124
+ // Pulse spark: frame naik saat busy. Timer HANYA hidup selama turn; idle =
125
+ // frame 0 (spark redup). Fail-safe: callback timer dibungkus try/catch dan
126
+ // tak pernah menyentuh jalur turn — animasi mati, turn tetap jalan.
127
+ let frame = 0
128
+ let pulseTimer: ReturnType<typeof setInterval> | undefined
129
+ const stopPulse = (): void => {
130
+ if (pulseTimer) {
131
+ clearInterval(pulseTimer)
132
+ pulseTimer = undefined
133
+ }
134
+ }
135
+
136
+ // Lukis 2 baris dasar TANPA menggeser kursor pemanggil (DECSC/DECRC).
137
+ // Penting untuk refresh() saat prompt aktif: repaint footer tidak boleh
138
+ // memindahkan posisi ketik, kalau tidak render berikutnya menimpa footer.
139
+ const paintFooter = (r: number): void => {
140
+ const cols = process.stdout.columns || 80
141
+ const [status] = renderFooter({ ...opts.status(), sparkFrame: frame }, cols)
142
+ process.stdout.write(SAVE_CURSOR)
143
+ // Blank di r-1, status di r (tanpa garis — clean).
144
+ process.stdout.write(`\x1b[${r - 1};1H${CLEAR}`)
145
+ process.stdout.write(`\x1b[${r};1H${CLEAR}${status}`)
146
+ process.stdout.write(RESTORE_CURSOR)
147
+ }
148
+
149
+ const enableRegion = (r: number): void => {
150
+ if (detached) return
151
+ // DECSTBM memindahkan kursor ke home di sebagian emulasi VT — simpan/
152
+ // kembalikan agar set region tidak melompatkan kursor ketik.
153
+ process.stdout.write(SAVE_CURSOR)
154
+ // Region atas = 1..r-2 (footer blank+status menempati r-1..r).
155
+ process.stdout.write(`\x1b[1;${r - 2}r`)
156
+ process.stdout.write(RESTORE_CURSOR)
157
+ regionOn = true
158
+ }
159
+
160
+ const onResize = (): void => {
161
+ try {
162
+ if (!regionOn || detached) return
163
+ const r = rows()
164
+ if (r < 10) {
165
+ // Terlalu pendek: lepas region agar tidak aneh; present berikutnya
166
+ // akan me-reset ulang bila sudah muat. DECSTBM reset juga bisa
167
+ // memindahkan kursor → save/restore seperti enableRegion.
168
+ process.stdout.write(SAVE_CURSOR)
169
+ process.stdout.write(RESET_REGION)
170
+ process.stdout.write(RESTORE_CURSOR)
171
+ regionOn = false
172
+ return
173
+ }
174
+ enableRegion(r)
175
+ paintFooter(r)
176
+ } catch {}
177
+ }
178
+
179
+ const handle: FooterChrome = {
180
+ mode,
181
+ reserveRows() {
182
+ // Setelah detach, tidak ada jatah lagi (reset region sudah lepas).
183
+ return detached ? 0 : FOOTER_ROWS
184
+ },
185
+ refresh() {
186
+ if (detached) return
187
+ try {
188
+ const r = rows()
189
+ if (r < 10 || !regionOn) return
190
+ paintFooter(r)
191
+ } catch {}
192
+ },
193
+ setBusy(busy: boolean) {
194
+ if (detached) return
195
+ try {
196
+ if (busy) {
197
+ if (pulseTimer) return
198
+ // Frame naik pelan (2 tick/frame) agar glow halus, bukan strobo.
199
+ pulseTimer = setInterval(() => {
200
+ try {
201
+ frame += 1
202
+ const r = rows()
203
+ if (regionOn && r >= 10) paintFooter(r)
204
+ } catch {
205
+ // Runtime rewel: matikan animasi, jangan pernah gagalkan turn.
206
+ stopPulse()
207
+ }
208
+ }, 150)
209
+ } else {
210
+ stopPulse()
211
+ frame = 0
212
+ const r = rows()
213
+ if (regionOn && r >= 10) paintFooter(r) // kembali redup seketika
214
+ }
215
+ } catch {}
216
+ },
217
+ present() {
218
+ if (detached) return
219
+ try {
220
+ const r = rows()
221
+ if (r < 10) return // terminal terlalu pendek — jangan sentuh apa pun
222
+ if (!regionOn) {
223
+ enableRegion(r)
224
+ if (!resizeBound) {
225
+ resizeBound = onResize
226
+ try {
227
+ process.stdout.on("resize", onResize)
228
+ } catch {}
229
+ }
230
+ }
231
+ // Satu frame sinkron agar repaint footer tidak robek.
232
+ process.stdout.write(SYNC_START)
233
+ paintFooter(r)
234
+ // Kursor ke baris input (tepat di atas blank footer — kini 2 baris total).
235
+ process.stdout.write(`\x1b[${r - 2};1H`)
236
+ process.stdout.write(SYNC_END)
237
+ } catch {}
238
+ },
239
+ detach() {
240
+ if (detached) return
241
+ detached = true
242
+ stopPulse()
243
+ try {
244
+ if (resizeBound) {
245
+ try {
246
+ process.stdout.off("resize", onResize)
247
+ } catch {}
248
+ resizeBound = null
249
+ }
250
+ if (regionOn) {
251
+ process.stdout.write(RESET_REGION)
252
+ regionOn = false
253
+ }
254
+ if (activeReserve === FOOTER_ROWS) activeReserve = 0
255
+ // Cetak footer sekali sebagai baris normal agar layar terakhir tetap
256
+ // memberi konteks tanpa region.
257
+ if (mode === "sticky") {
258
+ const cols = process.stdout.columns || 80
259
+ const [status] = renderFooter(opts.status(), cols)
260
+ process.stdout.write(`\n${status}\n`)
261
+ }
262
+ } catch {}
263
+ },
264
+ }
265
+ activeReserve = FOOTER_ROWS
266
+ return handle
267
+ }
268
+
269
+ function makePrint(opts: FooterChromeOptions): FooterChrome {
270
+ activeReserve = 0
271
+ const handle: FooterChrome = {
272
+ mode: "print",
273
+ reserveRows() {
274
+ return 0
275
+ },
276
+ refresh() {},
277
+ setBusy() {},
278
+ present() {
279
+ try {
280
+ if (!process.stdout.isTTY) return
281
+ const cols = process.stdout.columns || 80
282
+ const [status] = renderFooter(opts.status(), cols)
283
+ process.stdout.write(`\n${status}\n`)
284
+ } catch {}
285
+ },
286
+ detach() {},
287
+ }
288
+ return handle
289
+ }
290
+
291
+ function makeNone(): FooterChrome {
292
+ activeReserve = 0
293
+ return {
294
+ mode: "none",
295
+ reserveRows: () => 0,
296
+ present() {},
297
+ refresh() {},
298
+ setBusy() {},
299
+ detach() {},
300
+ }
301
+ }
@@ -0,0 +1,77 @@
1
+ import { sanitizeAnsiLine } from "../render/sanitize.ts"
2
+ import { c, glyphs } from "../render/theme.ts"
3
+ import { acquireTransientPaint, paintWrite } from "./statusline.ts"
4
+
5
+ // Jaga agar kursor terminal selalu ter-restore meski proses dihentikan (SIGINT/dll).
6
+ process.on("exit", () => {
7
+ if (process.stderr.isTTY) process.stderr.write("\x1b[?25h")
8
+ })
9
+
10
+ export interface Spinner {
11
+ update: (message: string) => void
12
+ stop: (finalMessage?: string) => void
13
+ success: (message: string) => void
14
+ error: (message: string) => void
15
+ }
16
+
17
+ export function createSpinner(initialMessage: string = ""): Spinner {
18
+ const isTTY = process.stderr.isTTY
19
+ // Pesan spinner bisa datang dari hasil tool yang tidak terpercaya — SGR boleh
20
+ // lewat, sekuens lain (mis. \x1b[2J) dibuang agar tidak merusak layar.
21
+ let message = sanitizeAnsiLine(initialMessage)
22
+ let frameIdx = 0
23
+ let intervalId: ReturnType<typeof setInterval> | undefined
24
+ // Kepemilikan transient stderr selama animasi — mutual exclusion dengan
25
+ // garis status turn di-enforce statusline.ts (warning overlap, bukan crash).
26
+ let owned: { release(): void } | null = null
27
+
28
+ const frames = glyphs.spinnerFrames
29
+
30
+ const tick = () => {
31
+ const frame = c.info(frames[frameIdx % frames.length]!)
32
+ frameIdx++
33
+ paintWrite(`\r${frame} ${message}\x1b[K`)
34
+ }
35
+
36
+ if (isTTY) {
37
+ // Hide cursor during spin
38
+ paintWrite("\x1b[?25l")
39
+ owned = acquireTransientPaint("spinner", tick)
40
+ tick()
41
+ intervalId = setInterval(tick, 120)
42
+ }
43
+
44
+ const stopTimer = () => {
45
+ if (owned) {
46
+ owned.release()
47
+ owned = null
48
+ }
49
+ if (intervalId) {
50
+ clearInterval(intervalId)
51
+ intervalId = undefined
52
+ }
53
+ if (isTTY) {
54
+ paintWrite("\r\x1b[K\x1b[?25h")
55
+ }
56
+ }
57
+
58
+ return {
59
+ update(newMessage: string) {
60
+ message = sanitizeAnsiLine(newMessage)
61
+ },
62
+ stop(finalMessage?: string) {
63
+ stopTimer()
64
+ if (finalMessage) {
65
+ process.stderr.write(`${sanitizeAnsiLine(finalMessage)}\n`)
66
+ }
67
+ },
68
+ success(msg: string) {
69
+ stopTimer()
70
+ process.stderr.write(`${c.green(glyphs.check)} ${sanitizeAnsiLine(msg)}\n`)
71
+ },
72
+ error(msg: string) {
73
+ stopTimer()
74
+ process.stderr.write(`${c.red(glyphs.cross)} ${sanitizeAnsiLine(msg)}\n`)
75
+ },
76
+ }
77
+ }