minicode-ai 0.9.29 → 0.11.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 (141) hide show
  1. package/AGENTS.md +45 -0
  2. package/CHANGELOG.md +79 -1
  3. package/PLAN.md +491 -0
  4. package/README.md +2 -2
  5. package/cli/args.ts +1 -0
  6. package/cli/commands/acp.ts +485 -0
  7. package/cli/commands/auth.ts +7 -4
  8. package/cli/commands/config.ts +41 -27
  9. package/cli/commands/exec.ts +33 -12
  10. package/cli/commands/mcp.ts +3 -2
  11. package/cli/commands/memory.ts +1 -1
  12. package/cli/commands/pricing.ts +6 -4
  13. package/cli/commands/providers.ts +18 -8
  14. package/cli/commands/sessions.ts +11 -4
  15. package/cli/commands/skills.ts +3 -3
  16. package/cli/commands/stats.ts +3 -1
  17. package/cli/commands.ts +225 -103
  18. package/cli/index.ts +89 -62
  19. package/cli/model-manager.ts +8 -8
  20. package/cli/provider-manager.ts +13 -13
  21. package/cli/router.ts +7 -0
  22. package/cli/setup.ts +349 -4
  23. package/cli/tui.ts +542 -0
  24. package/cli/wizard.ts +2 -1
  25. package/docs/ARCHITECTURE.html +62 -36
  26. package/docs/CONTROL-PLANE-MAP.md +139 -0
  27. package/docs/HARNESS.md +150 -0
  28. package/docs/PLAN_UIUX_V6.md +209 -0
  29. package/docs/README.md +1 -1
  30. package/docs/SUMMARY.md +52 -0
  31. package/docs/TERMINAL_CONTRACT.md +367 -0
  32. package/docs/UI_RENDER_PIPELINE.md +165 -0
  33. package/docs/USAGE.md +11 -0
  34. package/docs/agents.md +31 -0
  35. package/docs/architecture.md +3 -3
  36. package/docs/choosing-mode.md +34 -0
  37. package/docs/cli.md +130 -0
  38. package/docs/concepts.md +53 -0
  39. package/docs/config-providers.md +87 -0
  40. package/docs/config.md +63 -0
  41. package/docs/contributing.md +79 -0
  42. package/docs/environment.md +95 -0
  43. package/docs/exec.md +73 -0
  44. package/docs/getting-started.md +102 -0
  45. package/docs/glossary.md +37 -0
  46. package/docs/mcp-lsp.md +54 -0
  47. package/docs/memory-sessions.md +63 -0
  48. package/docs/policy-sandbox.md +72 -0
  49. package/docs/pricing-budget.md +49 -0
  50. package/docs/quickstart.md +60 -0
  51. package/docs/repl.md +67 -0
  52. package/docs/security-model.md +95 -0
  53. package/docs/security.md +91 -0
  54. package/docs/skills.md +48 -0
  55. package/docs/terminal.md +79 -0
  56. package/docs/tools.md +123 -0
  57. package/docs/troubleshooting.md +40 -0
  58. package/docs/verify-benchmark.md +58 -0
  59. package/package.json +8 -5
  60. package/src/app/provider-layer.ts +12 -4
  61. package/src/app/rag-layer.ts +7 -2
  62. package/src/app/session.ts +6 -0
  63. package/src/app/tool-layer.ts +2 -1
  64. package/src/config.ts +30 -1
  65. package/src/constants.ts +35 -0
  66. package/src/lib/net.ts +6 -1
  67. package/src/lsp/client.ts +41 -8
  68. package/src/mcp/http-transport.ts +52 -15
  69. package/src/mcp/transport.ts +32 -1
  70. package/src/memory/files.ts +6 -5
  71. package/src/policy/allowlist.ts +1 -1
  72. package/src/policy/bash-guard.ts +213 -17
  73. package/src/policy/compaction.ts +57 -3
  74. package/src/policy/context.ts +4 -0
  75. package/src/policy/jail.ts +49 -4
  76. package/src/policy/permission.ts +152 -12
  77. package/src/policy/pricing.ts +12 -9
  78. package/src/policy/update-check.ts +4 -1
  79. package/src/presentation/adapter.ts +721 -0
  80. package/src/presentation/events.ts +324 -0
  81. package/src/presentation/label.ts +140 -0
  82. package/src/presentation/model.ts +172 -0
  83. package/src/presentation/reducer.ts +486 -0
  84. package/src/presentation/store.ts +256 -0
  85. package/src/providers/anthropic.ts +22 -4
  86. package/src/providers/detect.ts +2 -1
  87. package/src/providers/router.ts +13 -0
  88. package/src/repo/repomap.ts +2 -29
  89. package/src/session/checkpoint.ts +27 -9
  90. package/src/session/journal.ts +27 -5
  91. package/src/skills/loader.ts +88 -5
  92. package/src/telemetry/trace.ts +36 -15
  93. package/src/tools/ask_user.ts +73 -4
  94. package/src/tools/bash.ts +23 -17
  95. package/src/tools/glob.ts +10 -11
  96. package/src/tools/lsp.ts +3 -56
  97. package/src/tools/memory.ts +13 -12
  98. package/src/tools/task.ts +7 -1
  99. package/src/tools/web_fetch.ts +11 -2
  100. package/src/tools/web_search.ts +4 -1
  101. package/src/ui/approval/prompt.ts +96 -22
  102. package/src/ui/assistant/simple.ts +188 -44
  103. package/src/ui/assistant/turn-status.ts +32 -10
  104. package/src/ui/contract.ts +119 -0
  105. package/src/ui/footer.ts +35 -14
  106. package/src/ui/i18n/en.ts +253 -0
  107. package/src/ui/i18n/id.ts +255 -0
  108. package/src/ui/i18n/locale.ts +68 -0
  109. package/src/ui/input/input.ts +189 -81
  110. package/src/ui/input/prompt-engine.ts +139 -4
  111. package/src/ui/render/collapse.ts +20 -13
  112. package/src/ui/render/diff.ts +7 -2
  113. package/src/ui/render/errors.ts +75 -50
  114. package/src/ui/render/format.ts +26 -8
  115. package/src/ui/render/highlight.ts +12 -5
  116. package/src/ui/render/markdown.ts +5 -1
  117. package/src/ui/render/sanitize.ts +29 -2
  118. package/src/ui/render/table.ts +12 -6
  119. package/src/ui/render/theme.ts +23 -4
  120. package/src/ui/render/width.ts +104 -17
  121. package/src/ui/runtime/motion.ts +16 -0
  122. package/src/ui/runtime/screen.ts +242 -0
  123. package/src/ui/runtime/spinner.ts +50 -4
  124. package/src/ui/runtime/statusline.ts +50 -1
  125. package/src/ui/screens/dialog.ts +174 -0
  126. package/src/ui/screens/form.ts +486 -0
  127. package/src/ui/screens/model-manager.ts +289 -134
  128. package/src/ui/screens/picker.ts +264 -109
  129. package/src/ui/screens/provider-manager.ts +385 -172
  130. package/src/ui/screens/wizard.ts +165 -102
  131. package/src/ui/tui/app.ts +951 -0
  132. package/src/ui/tui/transcript.ts +475 -0
  133. package/vendor/minicore/LICENSE +21 -0
  134. package/vendor/minicore/VENDOR.md +6 -3
  135. package/vendor/minicore/package.json +6 -3
  136. package/vendor/minicore/src/core/loop.ts +12 -2
  137. package/vendor/minicore/src/core/snapshot.ts +4 -0
  138. package/vendor/minicore/src/providers/openai-compat.ts +76 -25
  139. package/cli/repl.ts +0 -740
  140. package/src/ui/runtime/chrome.ts +0 -369
  141. package/src/ui/screens/overlay.ts +0 -61
package/cli/tui.ts ADDED
@@ -0,0 +1,542 @@
1
+ // Driver TUI — komposisi: CliSession + Transcript + TuiApp. Satu-satunya
2
+ // tampilan interaktif (tanpa mode).
3
+ //
4
+ // Peran: TERJEMAHKAN dunia cli/ (budget, skill, mention, mode, clipboard)
5
+ // menjadi TuiHost, lalu jalankan App fullscreen. Semua output user-visible
6
+ // masuk Transcript (bukan console) — console.log mentah di sini akan menimpa
7
+ // frame alt-screen. Satu-satunya console yang tersisa: fallback non-mampu
8
+ // (belum start) dan error fatal.
9
+ //
10
+ // Perilaku khas TUI (kontrak I17-I24):
11
+ // - histori prompt = memori sesi (tak persist ke berkas).
12
+ // - /clear = kosongkan transkrip (bukan penanda scrollback).
13
+ // - /status, /history & /help ringkas = readout ke transkrip (bukan jendela
14
+ // modal) — transkrip fullscreen SUDAH permukaan baca; modal untuk info
15
+ // statis hanya menambah langkah. /model & /provider & /sessions = popup
16
+ // komposit (butuh interaksi pilih).
17
+ // - busy = input beku total kecuali abort (Esc/Ctrl+C) dan scroll.
18
+ import { expandMentions } from "../src/app/mentions.ts"
19
+ import { budgetStatus } from "../src/policy/usage.ts"
20
+ import { redoLastCheckpoint, undoLastCheckpoint } from "../src/session/checkpoint.ts"
21
+ import { renderSkill } from "../src/skills/loader.ts"
22
+ import { getLastTurnText, writeClipboardOsc52 } from "../src/ui/assistant/simple.ts"
23
+ import type { UiBus } from "../src/ui/contract.ts"
24
+ import { t } from "../src/ui/i18n/locale.ts"
25
+ import { loadHistory } from "../src/ui/input/input.ts"
26
+ import {
27
+ clearCollapsedSections,
28
+ collapsedSectionsSnapshot,
29
+ sectionMinimized,
30
+ setSectionMinimized,
31
+ } from "../src/ui/render/collapse.ts"
32
+ import { setCompactMode } from "../src/ui/render/detail.ts"
33
+ import { formatUsd } from "../src/ui/render/money.ts"
34
+ import { setReasoningVisible } from "../src/ui/render/reasoning.ts"
35
+ import { c } from "../src/ui/render/theme.ts"
36
+ import { TuiApp, type TuiHost } from "../src/ui/tui/app.ts"
37
+ import { Transcript } from "../src/ui/tui/transcript.ts"
38
+ import {
39
+ BUILTIN_COMMANDS,
40
+ type CommandContext,
41
+ DRIVER_HELP_COMMANDS,
42
+ handleBuiltinCommand,
43
+ persistModelChoice,
44
+ suggestSimilar,
45
+ } from "./commands.ts"
46
+ import type { CliSession } from "./setup.ts"
47
+
48
+ const MODES = ["auto", "ask", "plan", "allowlist", "allow-all"] as const
49
+ // /expand [id]: tanpa arg = semua entry store; dengan id = satu tool.
50
+ const DRIVER_COMMANDS = ["/compact", "/thinking", "/expand [id]", "/minimize"]
51
+
52
+ function fmtCtx(n: number): string | undefined {
53
+ if (!Number.isFinite(n) || n <= 0) return undefined
54
+ if (n < 1000) return String(n)
55
+ if (n < 10000) return `${(n / 1000).toFixed(1)}k`
56
+ if (n < 1000000) return `${Math.round(n / 1000)}k`
57
+ return `${(n / 1000000).toFixed(1)}m`
58
+ }
59
+
60
+ /**
61
+ * Tangkap console.log/error selama `fn` → baris teks (tanpa warna liar:
62
+ * caller yang mewarnai). Dipakai membungkus handleBuiltinCommand supaya
63
+ * readout warisan (/help, pin jendela, pesan undo) mendarat di transkrip,
64
+ * bukan menimpa frame alt-screen. View modal menulis via stdout.write
65
+ * langsung (bukan console) sehingga tak ikut tertangkap — layarnya tetap
66
+ * tampil normal (nested refcount screen.ts). Baris yang sudah tercetak
67
+ * SEBELUM fn melempar tetap dikembalikan via capturedLines (ditempel ke
68
+ * error) — tanpa ini kegagalan di tengah readout (/sync) diam-diam
69
+ * membuang output parsial.
70
+ */
71
+ async function captureConsole(fn: () => Promise<void>): Promise<string[]> {
72
+ const lines: string[] = []
73
+ const origLog = console.log
74
+ const origErr = console.error
75
+ console.log = (...args: unknown[]) => {
76
+ lines.push(args.map((a) => (typeof a === "string" ? a : String(a))).join(" "))
77
+ }
78
+ console.error = (...args: unknown[]) => {
79
+ lines.push(args.map((a) => (typeof a === "string" ? a : String(a))).join(" "))
80
+ }
81
+ const flush = () => lines.flatMap((l) => l.split("\n"))
82
+ try {
83
+ await fn()
84
+ } catch (e) {
85
+ ;(e as { capturedLines?: string[] }).capturedLines = flush()
86
+ throw e
87
+ } finally {
88
+ console.log = origLog
89
+ console.error = origErr
90
+ }
91
+ return flush()
92
+ }
93
+
94
+ export async function runTui(ctx: CliSession): Promise<void> {
95
+ const {
96
+ cfg,
97
+ cwd,
98
+ sessionId,
99
+ modelRef,
100
+ permissionMode,
101
+ permissions,
102
+ sessionTools,
103
+ allLoadedSkills,
104
+ allowLocalConfig,
105
+ usage,
106
+ budget,
107
+ budgetStrict,
108
+ persistCurrent,
109
+ runPromptWithVerify,
110
+ close,
111
+ } = ctx
112
+ const { session } = ctx
113
+ const getPresentationSnapshot = () =>
114
+ typeof ctx.getPresentationSnapshot === "function"
115
+ ? ctx.getPresentationSnapshot()
116
+ : { activities: [], turns: [] }
117
+
118
+ let mode: string = permissions?.getMode() ?? permissionMode ?? "auto"
119
+ if (process.env.MINICODE_COMPACT === undefined) setCompactMode(true)
120
+ if (process.env.MINICODE_MINIMIZE_TOOL === undefined) setSectionMinimized("tool", true)
121
+ let warned80 = false
122
+ let abort: AbortController | null = null
123
+
124
+ // Bahasa UI: state.json (sesi bisa menimpa via /lang). Gagal baca = default.
125
+ const { setConfigLocale } = await import("../src/ui/i18n/locale.ts")
126
+ try {
127
+ const { loadLang } = await import("../src/config.ts")
128
+ setConfigLocale((await loadLang().catch(() => undefined)) ?? null)
129
+ } catch {}
130
+
131
+ const transcript = new Transcript(session.events as unknown as UiBus, {
132
+ getSnapshot: getPresentationSnapshot,
133
+ onPresentationEvent: ctx.onPresentationEvent,
134
+ })
135
+
136
+ const commandCtx: CommandContext = {
137
+ cwd,
138
+ sessionId,
139
+ allowLocalConfig,
140
+ get currentModel() {
141
+ return modelRef.current ?? cfg.providers[0]?.models[0]
142
+ },
143
+ set currentModel(v) {
144
+ modelRef.current = v
145
+ },
146
+ usage,
147
+ skills: allLoadedSkills,
148
+ toolsCount: sessionTools.length,
149
+ providerHint: cfg.providers[0]?.providerHint,
150
+ setModelOverride: (m) => persistModelChoice(m, modelRef),
151
+ // Spawn anak stdio-inherit (/sessions <id>): keluar alt-screen + cooked
152
+ // mode DULU — anak mewarisi terminal apa adanya. Tanpa ini: double-ENTER,
153
+ // EXIT anak merobek buffer parent, stdin mentah macet. Gagal-di-kode-lama.
154
+ onBeforeSpawn: () => app.releaseTerminal(),
155
+ getContextTokens: () => session.contextTokens,
156
+ budgetState: () => {
157
+ const u = usage.getSession()
158
+ return budgetStatus(budget, u.cost, budgetStrict ?? false, u.totalTokens)
159
+ },
160
+ }
161
+
162
+ const suggestions = (line: string): string[] => {
163
+ if (!line.startsWith("/")) return []
164
+ const all = [
165
+ ...BUILTIN_COMMANDS.map((b) => `/${b.name}`),
166
+ ...DRIVER_COMMANDS,
167
+ ...allLoadedSkills.map((s) => `/${s.name}`),
168
+ ]
169
+ return all.filter((t) => t.startsWith(line))
170
+ }
171
+
172
+ const cycleMode = (dir: 1 | -1): void => {
173
+ const idx = (MODES as readonly string[]).indexOf(mode)
174
+ // allow-all hanya via flag --allow-all (paritas REPL).
175
+ let next = MODES[(idx + dir + MODES.length) % MODES.length]!
176
+ if (next === "allow-all") next = MODES[(idx + dir * 2 + MODES.length * 2) % MODES.length]!
177
+ mode = next
178
+ if (permissions) permissions.setMode(mode as (typeof MODES)[number])
179
+ else mode = permissionMode ?? mode
180
+ }
181
+
182
+ async function runBuiltin(
183
+ q: string,
184
+ ): Promise<{ lines: string[]; shouldExit: boolean; handled: boolean }> {
185
+ let shouldExit = false
186
+ let handled = false
187
+ let lines: string[] = []
188
+ try {
189
+ lines = await captureConsole(async () => {
190
+ const r = await handleBuiltinCommand(q, commandCtx)
191
+ shouldExit = !!r.shouldExit
192
+ handled = r.handled
193
+ })
194
+ } catch (e) {
195
+ // Baris parsial yang sempat tercetak sebelum throw tetap tampil —
196
+ // tanpa ini hanya pesan error generik yang keluar (data-loss diam).
197
+ lines = (e as { capturedLines?: string[] }).capturedLines ?? []
198
+ if (lines.length) transcript.pushInfo(lines)
199
+ throw e
200
+ }
201
+ return { lines, shouldExit, handled }
202
+ }
203
+
204
+ async function delegateBuiltin(q: string): Promise<{ quit?: boolean }> {
205
+ const { lines, shouldExit } = await runBuiltin(q)
206
+ if (lines.length) transcript.pushInfo(lines)
207
+ return shouldExit ? { quit: true } : {}
208
+ }
209
+
210
+ /**
211
+ * Builtin yang membuka popup: bekukan App (input dilepas + layar redup),
212
+ * view melukis regionnya sendiri, App repaint saat kembali. Tanpa ini
213
+ * byte masuk ke dua tempat (App + popup) dan frame App menimpa popup.
214
+ * Struk mutasi: model/provider yang berubah saat popup terbuka dicatat
215
+ * ke transkrip (jejak audit — scroll ke atas selalu menunjukkan ganti).
216
+ */
217
+ async function popupBuiltin(q: string): Promise<{ quit?: boolean }> {
218
+ const before = commandCtx.currentModel
219
+ app.suspend()
220
+ try {
221
+ return await delegateBuiltin(q)
222
+ } catch (e) {
223
+ // Spawn anak gagal (terminal sudah dilepas onBeforeSpawn): hidupkan
224
+ // kembali atau keluar bersih — jangan biarkan TUI mati tanpa layar.
225
+ if (!app.reacquireTerminal()) app.requestQuit()
226
+ throw e
227
+ } finally {
228
+ app.resume()
229
+ const after = commandCtx.currentModel
230
+ if (after && after !== before) transcript.pushInfo([c.muted(t("tui.modelSet", { v: after }))])
231
+ }
232
+ }
233
+
234
+ async function runTurn(prompt: string): Promise<void> {
235
+ const spent = usage.getSession(modelRef.current)
236
+ const preStatus = budgetStatus(budget, spent.cost, budgetStrict ?? false, spent.totalTokens)
237
+ if (preStatus === "over" && spent.cost != null && budget != null) {
238
+ transcript.pushError(
239
+ t("tui.budgetOver", { spent: formatUsd(spent.cost), budget: formatUsd(budget) }),
240
+ )
241
+ return
242
+ }
243
+ if (preStatus === "unknown-strict") {
244
+ transcript.pushError(t("tui.budgetUnknown", { tokens: spent.totalTokens }))
245
+ return
246
+ }
247
+ let finalPrompt = prompt
248
+ if (prompt.includes("@")) {
249
+ const expanded = await expandMentions(prompt, cwd ?? process.cwd())
250
+ finalPrompt = expanded.prompt
251
+ if (expanded.notes.length)
252
+ transcript.pushInfo(expanded.notes.map((n) => c.muted(` [@mention] ${n}`)))
253
+ }
254
+ const ctrl = new AbortController()
255
+ abort = ctrl
256
+ try {
257
+ await runPromptWithVerify(finalPrompt, ctrl.signal)
258
+ if (ctrl.signal.aborted) transcript.pushInfo([c.muted(t("tui.stopped"))])
259
+ } finally {
260
+ abort = null
261
+ }
262
+ const u = usage.get(modelRef.current)
263
+ await persistCurrent(u)
264
+ usage.reset()
265
+ const sess = usage.getSession(modelRef.current)
266
+ if (
267
+ budget != null &&
268
+ sess.cost != null &&
269
+ sess.cost > budget * 0.8 &&
270
+ sess.cost <= budget &&
271
+ !warned80
272
+ ) {
273
+ warned80 = true
274
+ transcript.pushInfo([
275
+ c.muted(t("tui.budget80", { spent: formatUsd(sess.cost), budget: formatUsd(budget) })),
276
+ ])
277
+ }
278
+ }
279
+
280
+ /**
281
+ * /help ringkas (≤6 baris): daftar perintah muat viewport tanpa
282
+ * membanjiri transkrip. Detail penuh = `/help tombol` (delegasi).
283
+ */
284
+ function helpConcise(): void {
285
+ // Diturunkan dari registry (BUILTIN + driver) — perintah baru tak bisa
286
+ // hilang dari /help diam-diam (satu sumber, bukan daftar hardcode).
287
+ const builtin = BUILTIN_COMMANDS.map((b) => `/${b.name}`).join(" ")
288
+ const driver = [...DRIVER_COMMANDS, ...DRIVER_HELP_COMMANDS.map((b) => `/${b.name}`)].join(" ")
289
+ transcript.pushInfo([
290
+ t("help.cHead"),
291
+ ` ${builtin}`,
292
+ ` ${driver}`,
293
+ t("help.cKeys"),
294
+ t("help.cMore"),
295
+ ])
296
+ }
297
+
298
+ async function copyLastTurn(): Promise<void> {
299
+ const txt = getLastTurnText().trim()
300
+ if (!txt) {
301
+ transcript.pushInfo([c.muted(t("tui.copyNone"))])
302
+ return
303
+ }
304
+ if (writeClipboardOsc52(txt)) transcript.pushInfo([c.muted(t("tui.copyOk", { n: txt.length }))])
305
+ else transcript.pushInfo([c.muted(t("tui.copyNeedTty"))])
306
+ }
307
+
308
+ async function submit(line: string): Promise<{ quit?: boolean } | undefined> {
309
+ if (!line.startsWith("/")) {
310
+ await runTurn(line)
311
+ return
312
+ }
313
+ const spaceIdx = line.indexOf(" ")
314
+ const name = (spaceIdx === -1 ? line.slice(1) : line.slice(1, spaceIdx)).toLowerCase()
315
+ const args = spaceIdx === -1 ? "" : line.slice(spaceIdx + 1).trim()
316
+
317
+ if (name === "") {
318
+ helpConcise()
319
+ return
320
+ }
321
+ if (name === "help" && !args) {
322
+ helpConcise()
323
+ return
324
+ }
325
+ if (name === "exit" || name === "quit") return { quit: true }
326
+ if (name === "clear") {
327
+ // Reset via App (bukan transcript.clear langsung) agar scrollBack dan
328
+ // basis indikator ikut kembali ke ekor — tanpa ini viewport basi.
329
+ app.clearView()
330
+ return
331
+ }
332
+ if (name === "mode") {
333
+ if (args) {
334
+ if (!(MODES as readonly string[]).includes(args)) {
335
+ transcript.pushInfo([c.muted(t("tui.unknownMode", { a: args, modes: MODES.join(", ") }))])
336
+ return
337
+ }
338
+ mode = args
339
+ permissions?.setMode(args as (typeof MODES)[number])
340
+ } else {
341
+ cycleMode(1)
342
+ }
343
+ transcript.pushInfo([c.muted(t("tui.modeLine", { m: mode }))])
344
+ return
345
+ }
346
+ if (name === "lang") {
347
+ const { currentLocale, setSessionLocale } = await import("../src/ui/i18n/locale.ts")
348
+ if (!args) {
349
+ transcript.pushInfo([c.muted(t("tui.langLine", { v: `${currentLocale()} (en|id)` }))])
350
+ return
351
+ }
352
+ const next = args.trim().toLowerCase()
353
+ if (next !== "en" && next !== "id") {
354
+ transcript.pushInfo([c.muted(t("tui.langUnknown", { a: args }))])
355
+ return
356
+ }
357
+ setSessionLocale(next)
358
+ // Simpan permanen (best-effort); sesi ini langsung berlaku via session.
359
+ try {
360
+ const { saveLang } = await import("../src/config.ts")
361
+ await saveLang(next)
362
+ } catch {}
363
+ transcript.pushInfo([c.muted(t("tui.langLine", { v: next }))])
364
+ return
365
+ }
366
+ if (name === "compact") {
367
+ const next = args === "" ? undefined : args === "on" || args === "1"
368
+ const compact = setCompactMode(next)
369
+ transcript.pushInfo([c.muted(t("tui.toolCall", { v: compact ? "compact" : "expanded" }))])
370
+ return
371
+ }
372
+ if (name === "thinking") {
373
+ const next = args === "" ? undefined : args === "on" || args === "1"
374
+ const vis = setReasoningVisible(next)
375
+ transcript.pushInfo([c.muted(t("tui.thinkingSet", { v: vis ? "expanded" : "minimized" }))])
376
+ return
377
+ }
378
+ if (name === "expand") {
379
+ const sections = args ? ctx.expandContent(args) : ctx.expandAllContent()
380
+ const views = args ? [] : collapsedSectionsSnapshot()
381
+ if (!args) clearCollapsedSections()
382
+ if (!sections.length && !views.length) {
383
+ transcript.pushInfo([c.muted(t("tui.expandEmpty"))])
384
+ return
385
+ }
386
+ const lines: string[] = []
387
+ for (const s of sections) {
388
+ if (s.meta.source === "retention") {
389
+ lines.push(c.muted(t("tui.expandRetention")))
390
+ continue
391
+ }
392
+ const label = args ?? s.ref?.toolCallId ?? t("tui.expandContent")
393
+ const src = s.meta.source === "durable" ? ` [${t("tui.expandDurable")}]` : ""
394
+ lines.push(c.muted(` ── ${label}${src} ──`))
395
+ for (const ln of s.text.split("\n")) lines.push(` ${ln}`)
396
+ }
397
+ for (const view of views) {
398
+ lines.push(c.muted(` ── ${view.label} ──`))
399
+ for (const ln of view.text.split("\n")) lines.push(` ${ln}`)
400
+ }
401
+ transcript.pushInfo(lines)
402
+ return
403
+ }
404
+ if (name === "minimize") {
405
+ const arg = args.trim().toLowerCase()
406
+ let next: boolean | undefined
407
+ if (arg === "") next = !(sectionMinimized("tool") && sectionMinimized("answer"))
408
+ else if (arg === "on" || arg === "1") next = true
409
+ else if (arg === "off" || arg === "0") next = false
410
+ else {
411
+ transcript.pushInfo([c.muted(t("tui.minUse"))])
412
+ return
413
+ }
414
+ setSectionMinimized("tool", next)
415
+ setSectionMinimized("answer", next)
416
+ transcript.pushInfo([c.muted(t(next ? "tui.sectionsMin" : "tui.sectionsExp"))])
417
+ return
418
+ }
419
+ if (name === "undo") {
420
+ const res = await undoLastCheckpoint(sessionId, cwd)
421
+ transcript.pushInfo([res.message, ...res.restoredFiles])
422
+ return
423
+ }
424
+ if (name === "redo") {
425
+ const res = await redoLastCheckpoint(sessionId, cwd)
426
+ transcript.pushInfo([res.message, ...res.reappliedFiles])
427
+ return
428
+ }
429
+ if (name === "copy") {
430
+ await copyLastTurn()
431
+ return
432
+ }
433
+ if (name === "cost" || name === "usage") return delegateBuiltin("/status")
434
+ if (name === "models" || name === "model")
435
+ return popupBuiltin(`/model${args ? ` ${args}` : ""}`)
436
+ if (name === "providers" || name === "provider") return popupBuiltin("/provider")
437
+ if (name === "history") {
438
+ const lines = (await loadHistory()).slice(-20)
439
+ transcript.pushInfo(lines.length ? lines : [t("tui.historyEmpty")])
440
+ return
441
+ }
442
+ if (name === "resume" && !args) return popupBuiltin("/sessions")
443
+ if (name === "sessions" && !args) return popupBuiltin("/sessions")
444
+
445
+ // Builtin yang bisa membuka popup (/sessions <id> = resume-spawn,
446
+ // /model dengan filter) dibungkus suspend; yang murni cetak langsung.
447
+ const MODAL = new Set(["model", "provider", "sessions", "resume"])
448
+ if (MODAL.has(name)) return popupBuiltin(line)
449
+ const { lines, shouldExit, handled } = await runBuiltin(line)
450
+ if (shouldExit) return { quit: true }
451
+ // handled tanpa cetakan = murni modal (tak ada yang perlu ke transkrip).
452
+ if (handled) {
453
+ if (lines.length) transcript.pushInfo(lines)
454
+ return
455
+ }
456
+ // handleBuiltinCommand tak menangani → skill atau unknown (paritas REPL).
457
+ const skill = allLoadedSkills.find((s) => s.name === name)
458
+ if (!skill) {
459
+ const hint = suggestSimilar(name, [
460
+ ...BUILTIN_COMMANDS.map((b) => b.name),
461
+ ...DRIVER_COMMANDS.map((d) => d.slice(1)),
462
+ ...DRIVER_HELP_COMMANDS.map((b) => b.name),
463
+ "cost",
464
+ "usage",
465
+ "resume",
466
+ ...allLoadedSkills.map((s) => s.name),
467
+ ])
468
+ transcript.pushInfo([
469
+ c.muted(
470
+ t("tui.unknownCmd", {
471
+ name,
472
+ tail: hint ? t("tui.didYou", { hint }) : t("tui.tryHelp"),
473
+ }),
474
+ ),
475
+ ])
476
+ return
477
+ }
478
+ await runTurn(await renderSkill(skill, args))
479
+ }
480
+
481
+ const host: TuiHost = {
482
+ bus: session.events as unknown as TuiHost["bus"],
483
+ getStatus: () => {
484
+ const status = {
485
+ footer: {
486
+ mode,
487
+ model: modelRef.current ?? cfg.providers[0]?.models[0] ?? t("tui.noModel"),
488
+ cwd: cwd ?? process.cwd(),
489
+ context: fmtCtx(session.contextTokens),
490
+ },
491
+ busy: abort != null,
492
+ }
493
+ const activities = getPresentationSnapshot().activities
494
+
495
+ return {
496
+ ...status,
497
+ pinnedActivity:
498
+ activities.find(
499
+ (activity) => activity.status === "running" && !activity.parentToolCallId,
500
+ ) ?? activities.find((activity) => activity.status === "running"),
501
+ }
502
+ },
503
+ listCommands: (prefix) => suggestions(prefix),
504
+ submit,
505
+ abort: () => {
506
+ abort?.abort()
507
+ },
508
+ cycleMode: (dir) => {
509
+ cycleMode(dir)
510
+ },
511
+ toggleCompact: () => {
512
+ const compact = setCompactMode()
513
+ transcript.pushInfo([c.muted(t("tui.toolCall", { v: compact ? "compact" : "expanded" }))])
514
+ },
515
+ toggleReasoning: () => {
516
+ const vis = setReasoningVisible()
517
+ transcript.pushInfo([c.muted(t("tui.thinkingSet", { v: vis ? "expanded" : "minimized" }))])
518
+ },
519
+ }
520
+
521
+ const app = new TuiApp(transcript, host)
522
+ // Approval sebagai warga TUI: blok pertanyaan + keputusan tercatat di
523
+ // transkrip dan terlihat sebelum menjawab (tanpa sink = tulis langsung).
524
+ const { setApprovalSink } = await import("../src/ui/tui/transcript.ts")
525
+ setApprovalSink({
526
+ pushBlock: (lines) => transcript.pushInfo(lines),
527
+ repaint: () => app.repaint(),
528
+ suspend: () => app.suspend(),
529
+ resume: () => app.resume(),
530
+ })
531
+ const res = await app.run()
532
+ setApprovalSink(null)
533
+ if (!res.started) {
534
+ // Terminal tak mampu (non-TTY/dumb/sempit): tak ada tampilan yang bisa
535
+ // dibuka. Satu baris jujur, bukan fallback setengah (REPL dihapus).
536
+ console.log(t("tui.noTty"))
537
+ await close()
538
+ return
539
+ }
540
+ transcript.dispose()
541
+ await close()
542
+ }
package/cli/wizard.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // tampilannya di src/ui/screens/wizard.ts.
3
3
  import { GATEWAY_PRESETS } from "../src/providers/presets.ts"
4
4
  import { detectAndSave } from "../src/providers/provision.ts"
5
+ import { t } from "../src/ui/i18n/locale.ts"
5
6
  import { runSetupWizardView } from "../src/ui/screens/wizard.ts"
6
7
 
7
8
  export async function runSetupWizard(): Promise<boolean> {
@@ -15,7 +16,7 @@ export async function runSetupWizard(): Promise<boolean> {
15
16
  preset?.fallbackModels ??
16
17
  (baseUrl.includes("anthropic") ? ["claude-sonnet-4"] : ["gpt-4o-mini"])
17
18
  const entry = await detectAndSave(baseUrl, apiKey, undefined, { fallbackModels })
18
- return `Provider "${entry.id}" saved — ${entry.models.length} models`
19
+ return t("ntc.saved", { id: entry.id, n: entry.models.length, scope: "global" })
19
20
  },
20
21
  })
21
22
  }