minicode-ai 0.22.0 → 0.23.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 (46) hide show
  1. package/cli/commands.ts +10 -0
  2. package/cli/index.ts +11 -0
  3. package/cli/setup.ts +64 -33
  4. package/cli/tui.ts +3 -3
  5. package/docs/TERMINAL_CONTRACT.md +39 -6
  6. package/docs/environment.md +3 -0
  7. package/package.json +1 -1
  8. package/src/app/session.ts +129 -20
  9. package/src/config.ts +100 -2
  10. package/src/constants.ts +29 -4
  11. package/src/policy/compaction.ts +27 -0
  12. package/src/policy/context-budget.ts +132 -0
  13. package/src/policy/context-escalation.ts +140 -0
  14. package/src/policy/context-window.ts +47 -9
  15. package/src/policy/context.ts +10 -1
  16. package/src/policy/microcompact.ts +162 -0
  17. package/src/providers/anthropic.ts +17 -3
  18. package/src/providers/detect.ts +128 -13
  19. package/src/providers/provision.ts +78 -1
  20. package/src/providers/responses.ts +13 -1
  21. package/src/session/persistence.ts +56 -0
  22. package/src/ui/assistant/simple.ts +1 -1
  23. package/src/ui/i18n/en.ts +19 -4
  24. package/src/ui/i18n/id.ts +21 -4
  25. package/src/ui/input/input.ts +2 -2
  26. package/src/ui/render/activity-panel.ts +21 -3
  27. package/src/ui/render/hint.ts +28 -0
  28. package/src/ui/render/logo.ts +91 -0
  29. package/src/ui/render/session-summary.ts +22 -1
  30. package/src/ui/render/theme.ts +5 -0
  31. package/src/ui/runtime/screen.ts +4 -2
  32. package/src/ui/screens/form.ts +19 -23
  33. package/src/ui/screens/lifecycle.ts +80 -0
  34. package/src/ui/screens/model-manager.ts +77 -81
  35. package/src/ui/screens/picker.ts +28 -22
  36. package/src/ui/screens/provider-manager.ts +47 -52
  37. package/src/ui/screens/watchdog.ts +27 -0
  38. package/src/ui/screens/wizard.ts +3 -20
  39. package/src/ui/tui/app.ts +5 -2
  40. package/src/ui/tui/transcript.ts +51 -16
  41. package/vendor/minicore/src/core/compact.ts +10 -0
  42. package/vendor/minicore/src/core/errors.ts +11 -1
  43. package/vendor/minicore/src/core/executor.ts +6 -1
  44. package/vendor/minicore/src/core/loop.ts +92 -2
  45. package/vendor/minicore/src/core/session.ts +8 -0
  46. package/vendor/minicore/src/providers/openai-compat.ts +15 -2
package/src/ui/i18n/en.ts CHANGED
@@ -37,9 +37,15 @@ export const en = {
37
37
  "appr.tier.unknown": "unknown effect",
38
38
  "dlg.more": "… {n} more",
39
39
  "ts.compacted": "… compacted: {reason}",
40
+ "ts.compactedNoOp": "… compacted: nothing evictable ({reason}) — context did not shrink",
41
+ "ts.compactedFixpoint": "… compaction stopped: target unreachable with only {kept} messages left",
42
+ "ts.compactedImpossible":
43
+ "… compaction impossible: fixed instructions + tool schemas ({fixed}) already exceed the {trigger} threshold",
44
+ "ts.compactedLlmFailed": "… LLM summary failed ({reason}), using mechanical summary",
45
+ "ts.contextWindowSource": "context {tokens} tokens ({source})",
40
46
  "ts.providerAttemptDiscarded": "provider attempt {attempt} failed; partial output was discarded",
41
47
  "ts.thinking": "… thinking",
42
- "ts.evictMarker": "… {n} early lines outside viewport — full history in model",
48
+ "ts.evictMarker": "… {n} early lines outside viewport",
43
49
  "ts.statusRunning": "running",
44
50
  "ts.statusCompleted": "completed",
45
51
  "ts.statusFailed": "failed",
@@ -72,7 +78,7 @@ export const en = {
72
78
  "model.del": 'Delete model "{id}"?',
73
79
  "model.failOpen": "model manager failed to open: {msg}",
74
80
  "effort.title": "Thinking effort",
75
- "effort.saved": "Thinking: {effort} (next session)",
81
+ "effort.saved": "Thinking effort: {effort} (next session)",
76
82
  "prov.empty": "No providers",
77
83
  "prov.addTitle": "Add provider",
78
84
  "prov.customUrl": "Custom URL",
@@ -128,11 +134,20 @@ export const en = {
128
134
  "st.input": " Input: {v} (provider usage)",
129
135
  "st.output": " Output: {v} (provider usage)",
130
136
  "st.total": " Total: {v} (session cumulative)",
137
+ "st.cache": " Cache: {read} hit · {write} write (prompt cache)",
131
138
  "st.cost": " Cost: {v} (estimated from price table)",
132
139
  "st.budget": " Budget: {v}{extra}",
133
140
  "st.costUnknown": " (cost unknown — model without pricing)",
134
141
  "help.head": "Commands:",
135
142
  "help.keysLine": "Mouse wheel/PgUp/PgDn scroll (Shift = half) · /help keys = all shortcuts",
143
+ "hint.move": "move",
144
+ "hint.select": "select",
145
+ "hint.close": "close",
146
+ "hint.filter": "filter",
147
+ "hint.delete": "delete",
148
+ "hint.edit": "edit",
149
+ "hint.add": "add",
150
+ "hint.effort": "effort",
136
151
  "help.cHead": "Commands:",
137
152
  "help.cKeys":
138
153
  "Keys: Tab work-mode · Shift+Tab permission · ↑↓ history · Mouse wheel/PgUp/PgDn scroll · Ctrl+R search · Ctrl+D exit",
@@ -239,8 +254,8 @@ export const en = {
239
254
  "tui.workModeLine": "work mode: {m}",
240
255
  "tui.workModeUsage": "usage: /work-mode <DISCUSS|PLAN|BUILD> — current: {m}",
241
256
  "tui.workModeUnavailable": "work mode is not available in this session",
242
- "tui.unrestrictedOn": "🔓 unrestricted mode enabled - full access",
243
- "tui.unrestrictedOff": "🔓 unrestricted disabled — permission mode restored to {m}",
257
+ "tui.unrestrictedOn": "unrestricted mode enabled - full access",
258
+ "tui.unrestrictedOff": "unrestricted disabled — permission mode restored to {m}",
244
259
  "tui.langLine": "lang: {v}",
245
260
  "tui.toolCall": "tool call: {v}",
246
261
  "tui.modelSet": "model: {v}",
package/src/ui/i18n/id.ts CHANGED
@@ -38,9 +38,17 @@ export const id: Record<MsgKey, string> = {
38
38
  "appr.tier.unknown": "efek tidak diketahui",
39
39
  "dlg.more": "… {n} lagi",
40
40
  "ts.compacted": "… dipadatkan: {reason}",
41
+ "ts.compactedNoOp":
42
+ "… dipadatkan: tidak ada yang bisa dibuang ({reason}) — konteks tidak menyusut",
43
+ "ts.compactedFixpoint":
44
+ "… kompaksi berhenti: target tak tercapai meski hanya {kept} pesan tersisa",
45
+ "ts.compactedImpossible":
46
+ "… kompaksi mustahil: instruksi tetap + skema tool ({fixed}) sudah melebihi ambang {trigger}",
47
+ "ts.compactedLlmFailed": "… ringkasan LLM gagal ({reason}), memakai ringkasan mekanikal",
48
+ "ts.contextWindowSource": "konteks {tokens} token ({source})",
41
49
  "ts.providerAttemptDiscarded": "percobaan provider {attempt} gagal; output parsial dibuang",
42
50
  "ts.thinking": "… berpikir",
43
- "ts.evictMarker": "… {n} baris awal di luar viewport — riwayat penuh di model",
51
+ "ts.evictMarker": "… {n} baris awal di luar viewport",
44
52
  "ts.statusRunning": "berjalan",
45
53
  "ts.statusCompleted": "selesai",
46
54
  "ts.statusFailed": "gagal",
@@ -73,7 +81,7 @@ export const id: Record<MsgKey, string> = {
73
81
  "model.del": 'Hapus model "{id}"?',
74
82
  "model.failOpen": "model manager gagal dibuka: {msg}",
75
83
  "effort.title": "Upaya berpikir",
76
- "effort.saved": "Thinking: {effort} (sesi berikut)",
84
+ "effort.saved": "Upaya berpikir: {effort} (sesi berikut)",
77
85
  "prov.empty": "Belum ada penyedia",
78
86
  "prov.addTitle": "Tambah penyedia",
79
87
  "prov.customUrl": "URL kustom",
@@ -129,11 +137,20 @@ export const id: Record<MsgKey, string> = {
129
137
  "st.input": " Masukan: {v} (pemakaian provider)",
130
138
  "st.output": " Keluaran: {v} (pemakaian provider)",
131
139
  "st.total": " Total: {v} (kumulatif sesi)",
140
+ "st.cache": " Cache: {read} hit · {write} tulis (prompt cache)",
132
141
  "st.cost": " Biaya: {v} (estimasi tabel harga)",
133
142
  "st.budget": " Budget: {v}{extra}",
134
143
  "st.costUnknown": " (biaya tak diketahui — model tanpa harga)",
135
144
  "help.head": "Perintah:",
136
145
  "help.keysLine": "Mouse wheel/PgUp/PgDn gulir (Shift = ½) · /help tombol = semua pintasan",
146
+ "hint.move": "gerak",
147
+ "hint.select": "pilih",
148
+ "hint.close": "tutup",
149
+ "hint.filter": "saring",
150
+ "hint.delete": "hapus",
151
+ "hint.edit": "ubah",
152
+ "hint.add": "tambah",
153
+ "hint.effort": "upaya",
137
154
  "help.cHead": "Perintah:",
138
155
  "help.cKeys":
139
156
  "Tombol: Tab work-mode · Shift+Tab izin · ↑↓ riwayat · Mouse wheel/PgUp/PgDn gulir · Ctrl+R cari · Ctrl+D keluar",
@@ -240,8 +257,8 @@ export const id: Record<MsgKey, string> = {
240
257
  "tui.workModeLine": "mode kerja: {m}",
241
258
  "tui.workModeUsage": "pemakaian: /work-mode <DISCUSS|PLAN|BUILD> — aktif: {m}",
242
259
  "tui.workModeUnavailable": "work mode tidak tersedia di sesi ini",
243
- "tui.unrestrictedOn": "🔓 mode unrestricted aktif - akses penuh",
244
- "tui.unrestrictedOff": "🔓 unrestricted nonaktif — mode izin kembali ke {m}",
260
+ "tui.unrestrictedOn": "mode unrestricted aktif - akses penuh",
261
+ "tui.unrestrictedOff": "unrestricted nonaktif — mode izin kembali ke {m}",
245
262
  "tui.langLine": "lang: {v}",
246
263
  "tui.toolCall": "pemanggilan tool: {v}",
247
264
  "tui.modelSet": "model: {v}",
@@ -3,7 +3,7 @@ import { homedir } from "node:os"
3
3
  import { join } from "node:path"
4
4
  import { createInterface } from "node:readline"
5
5
  import { t } from "../i18n/locale.ts"
6
- import { stripAnsi } from "../render/theme.ts"
6
+ import { glyphs, stripAnsi } from "../render/theme.ts"
7
7
  import { displayWidth, escapeLength, truncateToWidth } from "../render/width.ts"
8
8
  import { beginInteractiveScreen } from "../runtime/statusline.ts"
9
9
  import {
@@ -877,7 +877,7 @@ export async function askSecret(
877
877
  .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "")
878
878
  if (clean) {
879
879
  secret += clean
880
- process.stdout.write("*".repeat(toGraphemes(clean).length))
880
+ process.stdout.write(glyphs.mask.repeat(toGraphemes(clean).length))
881
881
  }
882
882
  }
883
883
  }
@@ -10,6 +10,7 @@ import type { UiPresentationActivity } from "../contract.ts"
10
10
  import { t } from "../i18n/locale.ts"
11
11
  import { activityGroup } from "./activity-group.ts"
12
12
  import { sanitizeAnsiLine, stripSgr } from "./sanitize.ts"
13
+ import { c } from "./theme.ts"
13
14
  import { truncateToWidth } from "./width.ts"
14
15
  /** Satu grup teragregasi (dipakai renderer + /expand buffer). */
15
16
  export interface ActivityGroupView {
@@ -22,6 +23,8 @@ export interface ActivityGroupView {
22
23
  denied: number
23
24
  /** Nama tool pertama (indikator; sudah tersanitasi & terpotong). */
24
25
  names: string[]
26
+ /** Total nama tool unik (sebelum dibatasi 3) untuk penanda `+N`. */
27
+ nameTotal: number
25
28
  }
26
29
 
27
30
  const MAX_PANEL_LABEL = 40
@@ -32,12 +35,15 @@ export function groupActivities(
32
35
  activities: readonly UiPresentationActivity[],
33
36
  ): Map<string, ActivityGroupView> {
34
37
  const groups = new Map<string, ActivityGroupView>()
38
+ // Nama unik per grup (untuk penanda `+N` saat > 3 nama berbeda).
39
+ const uniqueNames = new Map<string, Set<string>>()
35
40
  for (const a of activities) {
36
41
  const kind = activityGroup(a.name)
37
42
  let g = groups.get(kind)
38
43
  if (!g) {
39
- g = { kind, count: 0, ok: 0, failed: 0, running: 0, denied: 0, names: [] }
44
+ g = { kind, count: 0, ok: 0, failed: 0, running: 0, denied: 0, names: [], nameTotal: 0 }
40
45
  groups.set(kind, g)
46
+ uniqueNames.set(kind, new Set())
41
47
  }
42
48
  g.count++
43
49
  const status = a.status
@@ -48,11 +54,21 @@ export function groupActivities(
48
54
  // Nama tool dari model/provider = input tak-terpercaya: buang SEMUA ANSI
49
55
  // (termasuk SGR) saat masuk — styling ditambahkan renderer sendiri.
50
56
  const cleanName = stripSgr(sanitizeAnsiLine(a.name))
57
+ const seen = uniqueNames.get(kind)!
58
+ seen.add(cleanName)
59
+ g.nameTotal = seen.size
51
60
  if (g.names.length < 3 && !g.names.includes(cleanName)) g.names.push(cleanName)
52
61
  }
53
62
  return groups
54
63
  }
55
64
 
65
+ /** Warna grup: gagal → merah, ditolak → kuning, sisanya → redup (tenang). */
66
+ function groupPaint(g: ActivityGroupView): (s: string) => string {
67
+ if (g.failed > 0) return c.error
68
+ if (g.denied > 0) return c.warning
69
+ return c.muted
70
+ }
71
+
56
72
  /** Satu baris grup (`+ explore · 3 tools · 2 ok · 1 failed`). */
57
73
  export function groupLine(g: ActivityGroupView): string {
58
74
  // Kunci i18n literal (bukan template) — MsgKey adalah union, bukan string.
@@ -69,8 +85,10 @@ export function groupLine(g: ActivityGroupView): string {
69
85
  if (g.failed > 0) parts.push(t("panel.failed", { n: g.failed }))
70
86
  if (g.running > 0) parts.push(t("panel.running", { n: g.running }))
71
87
  const names = g.names.map((n) => sanitizeAnsiLine(n)).join(", ")
72
- if (names) parts.push(`· ${truncateToWidth(names, MAX_PANEL_LABEL, "…")}`)
73
- return parts.join(" ")
88
+ const more = Math.max(0, g.nameTotal - g.names.length)
89
+ if (names)
90
+ parts.push(`· ${truncateToWidth(names, MAX_PANEL_LABEL, "…")}${more > 0 ? ` +${more}` : ""}`)
91
+ return groupPaint(g)(parts.join(" "))
74
92
  }
75
93
 
76
94
  /** Baris panel lengkap (header + satu baris per grup). Kosong bila tak ada
@@ -0,0 +1,28 @@
1
+ // Petunjuk aksi minimalis untuk jendela pilihan / manager / form.
2
+ //
3
+ // Bentuk sengaja "a add" (bukan "a: add"): kunci pendek, pemisah satu SPASI,
4
+ // label redup — kunci yang bisa ditekan lebih terang. Ini menyeragamkan seluruh
5
+ // jendela MiniCode yang sebelumnya menulis hint dengan gaya berbeda-beda
6
+ // ("a add · d delete" vs footer form vs tanpa hint sama sekali), dan tetap
7
+ // mematuhi kontrak v7.8 (tanpa judul, tanpa footer dekoratif di dalam kotak):
8
+ // hint ditaruh sebagai baris body paling bawah, bukan chrome kotak.
9
+ import { c } from "../render/theme.ts"
10
+
11
+ export interface HintItem {
12
+ /** Tombol yang benar-benar berlaku di permukaan ini. */
13
+ key: string
14
+ /** Label pendek, title case/lowercase mengikuti bahasa. */
15
+ label: string
16
+ }
17
+
18
+ /** Warna kunci (lebih terang) vs label (redup) — aksesibel tanpa warna. */
19
+ export function paintHint(item: HintItem): string {
20
+ return `${c.accent(item.key)} ${c.dim(item.label)}`
21
+ }
22
+
23
+ /** Satu baris hint: `a add · d hapus · Esc tutup` (tanpa awalan/akhiran).
24
+ * Tanpa pembungkus faint di seluruh baris: itu akan meredupkan KUNCI juga
25
+ * (SGR 2 tak dibatalkan warna). Kunci = accent (lebih terang), label = dim. */
26
+ export function hintLine(items: readonly HintItem[]): string {
27
+ return items.map(paintHint).join(` ${c.faint("·")} `)
28
+ }
@@ -0,0 +1,91 @@
1
+ // Block logo minicode: mark wordmark pemilik, dikonversi dari SVG vektor
2
+ // (CorelDRAW) menjadi grid 17 kolom × 9 baris sel.
3
+ //
4
+ // ASPEK PER-SEL — inti modul ini. Satu karakter terminal TIDAK persegi:
5
+ // tingginya ±2× lebarnya. Menggambar satu sel = satu karakter penuh membuat
6
+ // setiap "kotak" logo tampak persegi panjang (tinggi > lebar). Solusi: setiap
7
+ // sel logis dipetakan ke SETENGAH sel karakter (upper/lower half block), yang
8
+ // kotak tintanya persegi di terminal tipikal (lebar 1 kolom, tinggi ½ baris).
9
+ //
10
+ // Komposisi 2 sel logis bertumpuk → 1 baris karakter, memakai glyph set yang
11
+ // sudah ada (U+2580–U+2584):
12
+ // atas∅ bawah∅ → ' '
13
+ // atas█ bawah█ → '█' (kedua sel terisi)
14
+ // atas█ bawah∅ → '▀' (hanya sel atas)
15
+ // atas∅ bawah█ → '▄' (hanya sel bawah)
16
+ // Hasil: 17 kolom × 5 baris karakter (baris terakhir hanya berisi sel ke-9,
17
+ // karena tinggi logis 9 sel — ganjil). Rasio kotak fisik ≈ 17:9, sama dengan
18
+ // SVG asli; tidak lagi "dipipihkan" seperti blok karakter penuh.
19
+ //
20
+ // Fallback: terminal tanpa UTF-8 (MINICODE_ASCII/mini console legacy) memakai
21
+ // '#' 9 baris — aspek setengah-sel tidak tersedia di sana, jadi bentuk penuh
22
+ // dipertahankan agar pola tidak terpotong.
23
+ //
24
+ // Dimensi DIVERIFIKASI terhadap SVG (viewBox 8418.09 × 4456.66): 8418.09 =
25
+ // 495.18 × 17 kolom, 4456.66 = 495.18 × 9 baris (sel seragam 495.18²).
26
+ // Setiap '#' = satu sel terisi (75 polygon → 75 sel).
27
+
28
+ import { supportsUtf8 } from "./theme.ts"
29
+
30
+ const ROWS = [
31
+ " ##### ",
32
+ " ### #######",
33
+ "##### ## ##",
34
+ "## ### ## ##",
35
+ "## ## ##",
36
+ "## ## ##",
37
+ "## ## ### ##",
38
+ "###### ### ###",
39
+ " #### ##### ",
40
+ ] as const
41
+
42
+ /** Dimensi logis logo (sel), untuk pemanggil yang butuh geometri/centering. */
43
+ export const LOGO_WIDTH = 17
44
+ export const LOGO_HEIGHT = 9
45
+
46
+ /** Glyph sel terisi (fallback ASCII). */
47
+ export function logoBlock(): string {
48
+ return supportsUtf8() ? "█" : "#"
49
+ }
50
+
51
+ /** Apakah terminal mampu glyph half-block (U+2580/U+2584/U+2588)? */
52
+ export function supportsHalfBlocks(): boolean {
53
+ return supportsUtf8()
54
+ }
55
+
56
+ function halfLine(top: string, bottom: string): string {
57
+ let out = ""
58
+ for (let x = 0; x < LOGO_WIDTH; x++) {
59
+ const up = top[x] === "#"
60
+ const down = bottom[x] === "#"
61
+ if (up && down) out += "█"
62
+ else if (up) out += "▀"
63
+ else if (down) out += "▄"
64
+ else out += " "
65
+ }
66
+ return out
67
+ }
68
+
69
+ /**
70
+ * Baris logo, kotak-per-sel:
71
+ * - UTF-8: gabungkan 2 sel logis per baris dengan glyph half-block (5 baris).
72
+ * - ASCII/legacy: tetap 1 sel per karakter (9 baris) supaya pola tidak hilang.
73
+ */
74
+ export function renderLogoRows(): string[] {
75
+ if (!supportsUtf8()) {
76
+ const block = logoBlock()
77
+ return ROWS.map((row) => row.replace(/#/g, block))
78
+ }
79
+ const out: string[] = []
80
+ for (let y = 0; y < ROWS.length; y += 2) {
81
+ const top = ROWS[y] ?? " ".repeat(LOGO_WIDTH)
82
+ const bottom = ROWS[y + 1] ?? " ".repeat(LOGO_WIDTH)
83
+ out.push(halfLine(top, bottom))
84
+ }
85
+ return out
86
+ }
87
+
88
+ /** Jumlah baris hasil render (bukan tinggi grid logis). */
89
+ export function renderLogoLineCount(): number {
90
+ return supportsUtf8() ? Math.ceil(LOGO_HEIGHT / 2) : LOGO_HEIGHT
91
+ }
@@ -9,6 +9,7 @@
9
9
  // via `c` menjamin selalu terlihat + hormati NO_COLOR.
10
10
 
11
11
  import { t } from "../i18n/locale.ts"
12
+ import { renderLogoRows } from "./logo.ts"
12
13
  import { formatUsd } from "./money.ts"
13
14
  import { sanitizeAnsiLine, stripSgr } from "./sanitize.ts"
14
15
  import { c } from "./theme.ts"
@@ -20,12 +21,22 @@ function paintWordmark(): string {
20
21
  return c.bold(WORDMARK)
21
22
  }
22
23
 
24
+ /** Block logo pemilik (9×19) dicat dengan aksen brand — jatuh ke plain saat
25
+ * NO_COLOR, dan ke '#' saat terminal tanpa UTF-8 (fallback di logo.ts). */
26
+ function paintLogo(): string[] {
27
+ return renderLogoRows().map((row) => c.accent(row))
28
+ }
29
+
23
30
  export interface SessionSummary {
24
31
  sessionId: string
25
32
  model: string
26
33
  totalTokens: number
27
34
  cost?: number
28
35
  durationMs: number
36
+ /** Input token (Fase 7 ukur): penyebut hit-rate cache. */
37
+ inputTokens?: number
38
+ /** Token yang dibaca dari prompt cache (Fase 7 ukur). 0/undefined = nol. */
39
+ cacheReadTokens?: number
29
40
  }
30
41
 
31
42
  /** "3m 12s" / "1m 5s" / "45s" untuk durasi manusia. */
@@ -40,17 +51,27 @@ export function renderSessionSummary(s: SessionSummary): string {
40
51
  // Parameter dinamai `text`, bukan `t`: `t` sudah dipakai untuk i18n.
41
52
  const label = (text: string): string => c.muted(text.padEnd(7))
42
53
  const cost = s.cost != null ? formatUsd(s.cost) : null
54
+ // Fase 7 ukur: fraksi input dari cache; tampil hanya bila cache read > 0.
55
+ const cacheRead = s.cacheReadTokens ?? 0
56
+ const input = s.inputTokens ?? 0
57
+ const cachePart =
58
+ cacheRead > 0 && input > 0
59
+ ? ` · cache ${cacheRead.toLocaleString()} (${Math.round((cacheRead / input) * 100)}%)`
60
+ : ""
43
61
  // sessionId/model = input tak-terpercaya (config/network): buang SEMUA ANSI
44
62
  // (termasuk SGR) sebelum dibungkus style — nilai mentah hanya boleh muncul
45
63
  // sebagai teks polos, styling ditambahkan pemanggil (aturan repo).
46
64
  const clean = (v: string): string => stripSgr(sanitizeAnsiLine(v))
47
65
  return `${[
66
+ "",
67
+ ...paintLogo(),
68
+ "",
48
69
  paintWordmark(),
49
70
  `${label(t("summary.session"))} ${c.gray(clean(s.sessionId))}`,
50
71
  `${label(t("summary.model"))} ${c.gray(clean(s.model))}`,
51
72
  `${label(t("summary.usage"))} ${s.totalTokens.toLocaleString()} ${t("summary.tokens")}${
52
73
  cost != null ? ` · ${cost}` : ""
53
- } · ${formatDuration(s.durationMs)}`,
74
+ }${cachePart} · ${formatDuration(s.durationMs)}`,
54
75
  ]
55
76
  .join("\r\n")
56
77
  .concat("\r\n")}`
@@ -345,6 +345,11 @@ export const glyphs = {
345
345
  get spinnerFrames() {
346
346
  return supportsUtf8() ? ["·", "··", "···"] : [".", "..", "..."]
347
347
  },
348
+ /** Karakter mask field secret (form & prompt inline) — satu sumber.
349
+ * Sengaja getter (bukan const): MINICODE_ASCII bisa berubah saat runtime. */
350
+ get mask() {
351
+ return supportsUtf8() ? "•" : "*"
352
+ },
348
353
  // Blok progress bar loading (baris tunggal). Fallback ASCII untuk terminal
349
354
  // tanpa UTF-8 (MINICODE_ASCII / konsol Windows legacy).
350
355
  get blockFilled() {
@@ -214,7 +214,9 @@ export function openAltScreen(): AltScreen {
214
214
  if (cursor) {
215
215
  const row = Math.max(1, Math.floor(cursor.row))
216
216
  const col = Math.max(1, Math.floor(cursor.col))
217
- out += `\x1b[?25l\x1b[${row};${col}H\x1b[?25h`
217
+ // DECSCUSR `6 q` = bar tegak stabil (tak berkedip): caret tak menutupi
218
+ // karakter di bawahnya (blok penuh), dan lebih tenang = clean & minimal.
219
+ out += `\x1b[?25l\x1b[${row};${col}H\x1b[6 q\x1b[?25h`
218
220
  }
219
221
  out += SYNC_END
220
222
  process.stdout.write(out)
@@ -226,7 +228,7 @@ export function openAltScreen(): AltScreen {
226
228
  // Sync block + reset atribut: kursor tak boleh mewarisi warna run
227
229
  // sebelumnya, dan perpindahan kursor tak perlu menyentuh satu sel pun.
228
230
  process.stdout.write(
229
- `${SYNC_START}${RESET_ATTRS}\x1b[?25l\x1b[${r};${c}H\x1b[?25h${SYNC_END}`,
231
+ `${SYNC_START}${RESET_ATTRS}\x1b[?25l\x1b[${r};${c}H\x1b[6 q\x1b[?25h${SYNC_END}`,
230
232
  )
231
233
  },
232
234
  paintRegion(lines: string[], topRow: number): void {
@@ -19,10 +19,11 @@ import {
19
19
  toGraphemes,
20
20
  } from "../input/prompt-engine.ts"
21
21
  import { sanitizeAnsiLine } from "../render/sanitize.ts"
22
- import { c, stripAnsi } from "../render/theme.ts"
22
+ import { c, glyphs, stripAnsi } from "../render/theme.ts"
23
23
  import { displayWidth, truncateToWidth } from "../render/width.ts"
24
24
  import { type AltScreen, SYNC_UPDATE_END, SYNC_UPDATE_START } from "../runtime/screen.ts"
25
25
  import { boxLeftPad, dialogBox } from "./dialog.ts"
26
+ import { createIdleTimer } from "./lifecycle.ts"
26
27
 
27
28
  export interface FormField {
28
29
  id: string
@@ -156,29 +157,23 @@ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormRe
156
157
  const fields = spec.fields.map(toState)
157
158
  let idx = 0
158
159
  let done = false
159
- let idleTimer: ReturnType<typeof setTimeout> | undefined
160
160
  let idleWarned = false
161
- const clearIdle = () => {
162
- if (idleTimer) clearTimeout(idleTimer)
163
- idleTimer = undefined
164
- }
165
- const resetIdle = () => {
166
- if (done) return
167
- clearIdle()
168
- idleWarned = false
169
- idleTimer = setTimeout(() => {
170
- // Tahap 1: peringatan (draft TIDAK dibuang — render footer merah).
161
+ // Idle dua-fase via helper bersama (audit D1): 80 dtk diam → peringatan
162
+ // di footer kotak (draft TIDAK dibuang); 10 dtk lagi hening → batal.
163
+ // TOTAL tetap 90 dtk (semantik anti-hang dipertahankan). `finish`/`render`
164
+ // dirujuk sebagai closure — dievaluasi jauh setelah keduanya terdefinisi.
165
+ const idle = createIdleTimer({
166
+ warnMs: IDLE_WARN_MS,
167
+ cancelMs: IDLE_CANCEL_MS,
168
+ onWarn: () => {
171
169
  idleWarned = true
172
170
  render()
173
- // Tahap 2: batal — hanya bila tetap hening.
174
- idleTimer = setTimeout(() => finish(true), IDLE_CANCEL_MS)
175
- try {
176
- ;(idleTimer as unknown as { unref?: () => void }).unref?.()
177
- } catch {}
178
- }, IDLE_WARN_MS)
179
- try {
180
- ;(idleTimer as unknown as { unref?: () => void }).unref?.()
181
- } catch {}
171
+ },
172
+ onCancel: () => finish(true),
173
+ })
174
+ const resetIdle = () => {
175
+ idleWarned = false
176
+ idle.reset()
182
177
  }
183
178
 
184
179
  // Lebar konten = lebar kotak TETAP (64) dikurangi chrome (border+padding
@@ -196,7 +191,8 @@ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormRe
196
191
  fields.forEach((st, fi) => {
197
192
  const active = fi === idx
198
193
  if (st.def.kind === "text" || st.def.kind === "secret") {
199
- const shown = st.def.kind === "secret" ? "•".repeat(toGraphemes(st.text).length) : st.text
194
+ const shown =
195
+ st.def.kind === "secret" ? glyphs.mask.repeat(toGraphemes(st.text).length) : st.text
200
196
  // Scroll horizontal dalam KOLOM (bukan grapheme): CJK/emoji 2 kolom,
201
197
  // jadi hitung lebar tampil, bukan jumlah unit. Gagal-di-kode-lama:
202
198
  // kursor meleset 1 per glyph lebar + scroll prematur/terlambat.
@@ -290,7 +286,7 @@ export async function runForm(spec: FormSpec, screen: AltScreen): Promise<FormRe
290
286
  const finish = (cancelled: boolean) => {
291
287
  if (done) return
292
288
  done = true
293
- clearIdle()
289
+ idle.dispose()
294
290
  try {
295
291
  formPump.dispose()
296
292
  } catch {}
@@ -0,0 +1,80 @@
1
+ // Lifecycle popup bersama — satu sumber untuk idle-timer jendela interaktif
2
+ // (picker, form, model/provider manager, wizard).
3
+ //
4
+ // Masalah yang dipecahkan (audit D1): keempat layar menulis ulang pola idle
5
+ // yang sama dengan nuansa kecil berbeda — raw-mode digenggam tanpa input saat
6
+ // ConPTY mati/fokus hilang membuat popup "macet" (dan Bun Windows rawan
7
+ // segfault setelah ±133 dtk idle, lihat picker.ts). Dengan satu helper,
8
+ // semantiknya seragam: SEMUA timer di-unref (tak menahan proses), fase batal
9
+ // selalu ada, dan `dispose()` membuat reset berikutnya no-op (anti-timer-bocor
10
+ // sesudah selesai).
11
+ //
12
+ // Dua gaya yang didukung:
13
+ // 1. Satu tahap (picker/manager): cancelMs tercapai → langsung batal.
14
+ // 2. Dua tahap (form, audit TUI-004): warnMs → peringatan (draft DIPERTAHAN-
15
+ // kan, render footer merah); cancelMs lagi tanpa keypress → batal.
16
+ // TOTAL tetap warnMs + cancelMs.
17
+
18
+ export interface IdleTimerOptions {
19
+ /** Fase 1 (opsional): jeda diam → peringatan. Tanpa ini = langsung batal. */
20
+ warnMs?: number
21
+ /** Fase 1 (tanpa warnMs) / fase 2 (dengan warnMs): jeda → batal. */
22
+ cancelMs: number
23
+ /** Dipanggil saat peringatan (hanya bila warnMs diisi). */
24
+ onWarn?: () => void
25
+ /** Dipanggil saat batal karena diam. Wajib. */
26
+ onCancel: () => void
27
+ }
28
+
29
+ export interface IdleTimer {
30
+ /** Restart timer (dipanggil tiap keypress/aktivitas). No-op sesudah dispose. */
31
+ reset(): void
32
+ /** Hentikan timer tanpa mematikan (dipanggil suspend/pause). */
33
+ clear(): void
34
+ /** Matikan selamanya: clear + reset berikutnya no-op (dipakai saat finish). */
35
+ dispose(): void
36
+ }
37
+
38
+ /** Buat idle-timer dua-fase dengan unref otomatis. */
39
+ export function createIdleTimer(opts: IdleTimerOptions): IdleTimer {
40
+ let timer: ReturnType<typeof setTimeout> | undefined
41
+ let disposed = false
42
+ const unref = (t: ReturnType<typeof setTimeout>) => {
43
+ // jangan tahan proses hidup hanya karena timer ini (stdin stub test bisa
44
+ // tanpa API unref — anggap aman).
45
+ try {
46
+ ;(t as unknown as { unref?: () => void }).unref?.()
47
+ } catch {}
48
+ }
49
+ const clear = () => {
50
+ if (timer) clearTimeout(timer)
51
+ timer = undefined
52
+ }
53
+ const fireCancel = () => {
54
+ if (disposed) return
55
+ opts.onCancel()
56
+ }
57
+ const reset = () => {
58
+ if (disposed) return
59
+ clear()
60
+ if (opts.warnMs != null) {
61
+ timer = setTimeout(() => {
62
+ // Tahap 1: peringatan — konten tidak dibuang, render ulang oleh caller.
63
+ if (disposed) return
64
+ try {
65
+ opts.onWarn?.()
66
+ } catch {}
67
+ timer = setTimeout(fireCancel, opts.cancelMs)
68
+ unref(timer)
69
+ }, opts.warnMs)
70
+ } else {
71
+ timer = setTimeout(fireCancel, opts.cancelMs)
72
+ }
73
+ unref(timer)
74
+ }
75
+ const dispose = () => {
76
+ disposed = true
77
+ clear()
78
+ }
79
+ return { reset, clear, dispose }
80
+ }