minicode-ai 0.9.29 → 0.10.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 (47) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/cli/args.ts +1 -0
  3. package/cli/commands.ts +219 -103
  4. package/cli/index.ts +8 -6
  5. package/cli/model-manager.ts +2 -7
  6. package/cli/provider-manager.ts +13 -13
  7. package/cli/setup.ts +10 -1
  8. package/cli/tui.ts +506 -0
  9. package/cli/wizard.ts +2 -1
  10. package/docs/ARCHITECTURE.html +41 -22
  11. package/package.json +1 -1
  12. package/src/app/rag-layer.ts +7 -2
  13. package/src/config.ts +30 -1
  14. package/src/policy/bash-guard.ts +64 -8
  15. package/src/policy/update-check.ts +4 -1
  16. package/src/tools/bash.ts +8 -0
  17. package/src/tools/task.ts +6 -1
  18. package/src/tools/web_fetch.ts +11 -2
  19. package/src/tools/web_search.ts +4 -1
  20. package/src/ui/approval/prompt.ts +84 -18
  21. package/src/ui/assistant/simple.ts +55 -22
  22. package/src/ui/assistant/turn-status.ts +16 -7
  23. package/src/ui/footer.ts +14 -12
  24. package/src/ui/i18n/en.ts +225 -0
  25. package/src/ui/i18n/id.ts +227 -0
  26. package/src/ui/i18n/locale.ts +66 -0
  27. package/src/ui/input/input.ts +138 -77
  28. package/src/ui/input/prompt-engine.ts +97 -4
  29. package/src/ui/render/collapse.ts +8 -1
  30. package/src/ui/render/errors.ts +75 -50
  31. package/src/ui/render/format.ts +15 -5
  32. package/src/ui/render/highlight.ts +5 -2
  33. package/src/ui/render/table.ts +7 -4
  34. package/src/ui/render/theme.ts +8 -3
  35. package/src/ui/render/width.ts +17 -9
  36. package/src/ui/runtime/screen.ts +197 -0
  37. package/src/ui/screens/dialog.ts +174 -0
  38. package/src/ui/screens/form.ts +459 -0
  39. package/src/ui/screens/model-manager.ts +274 -127
  40. package/src/ui/screens/picker.ts +229 -98
  41. package/src/ui/screens/provider-manager.ts +371 -164
  42. package/src/ui/screens/wizard.ts +149 -102
  43. package/src/ui/tui/app.ts +745 -0
  44. package/src/ui/tui/transcript.ts +271 -0
  45. package/cli/repl.ts +0 -740
  46. package/src/ui/runtime/chrome.ts +0 -369
  47. package/src/ui/screens/overlay.ts +0 -61
@@ -5,6 +5,7 @@ import { reloadProviders } from "../src/app/provider-layer.ts"
5
5
  import { loadConfig, type MinicodeConfig } from "../src/config.ts"
6
6
  import { GATEWAY_PRESETS } from "../src/providers/presets.ts"
7
7
  import { detectAndSave, removeProvider } from "../src/providers/provision.ts"
8
+ import { t } from "../src/ui/i18n/locale.ts"
8
9
  import {
9
10
  type ProviderActionResult,
10
11
  type ProviderRow,
@@ -29,16 +30,15 @@ export async function runProviderManager(opts: {
29
30
  }): Promise<void> {
30
31
  if (!process.stdin.isTTY) {
31
32
  const cfg = await loadConfig(opts.cwd, { allowLocal: opts.allowLocalConfig })
32
- console.log("\nProviders:")
33
+ console.log(`\n${t("prov.title")}:`)
33
34
  for (const p of cfg.providers)
34
- console.log(` ${p.id} - ${p.baseUrl} (${p.models.length} models)`)
35
+ console.log(` ${p.id} - ${p.baseUrl} (${t("prov.models", { n: p.models.length })})`)
35
36
  return
36
37
  }
37
38
 
38
39
  // Router runtime gagal dimuat ulang (config IO) — jangan lapor sukses palsu:
39
40
  // tanpa pesan, user mengira pilihan langsung berlaku padahal butuh restart.
40
- const warnReloadFail = () =>
41
- process.stderr.write("[warn] provider reload failed — restart to apply changes\n")
41
+ const warnReloadFail = () => process.stderr.write(`[warn] ${t("prov.reloadFail")}\n`)
42
42
 
43
43
  await runProviderManagerView({
44
44
  initialRows: rowsFrom(await loadConfig(opts.cwd, { allowLocal: opts.allowLocalConfig })),
@@ -63,18 +63,18 @@ export async function runProviderManager(opts: {
63
63
  allowLocal: opts.allowLocalConfig,
64
64
  })
65
65
  await reloadProviders(opts.cwd, { allowLocal: opts.allowLocalConfig }).catch(warnReloadFail)
66
- return { ok: `Provider "${entry.id}" saved (${entry.models.length} models, ${scope}).` }
66
+ return {
67
+ ok: t("ntc.saved", { id: entry.id, n: entry.models.length, scope }),
68
+ }
67
69
  } catch (e) {
68
- return { err: `Model detection failed: ${(e as Error).message.slice(0, 80)}` }
70
+ return { err: t("prov.detectFail", { msg: (e as Error).message.slice(0, 80) }) }
69
71
  }
70
72
  },
71
73
  onDelete: async (row): Promise<ProviderActionResult> => {
72
74
  await removeProvider(row.id, { global: true })
73
75
  if (opts.cwd) await removeProvider(row.id, { global: false, cwd: opts.cwd })
74
- await reloadProviders(opts.cwd, { allowLocal: opts.allowLocalConfig }).catch(() =>
75
- process.stderr.write("[warn] provider reload failed — restart to apply changes\n"),
76
- )
77
- return { ok: `Provider "${row.id}" deleted.` }
76
+ await reloadProviders(opts.cwd, { allowLocal: opts.allowLocalConfig }).catch(warnReloadFail)
77
+ return { ok: t("prov.deleted", { id: row.id }) }
78
78
  },
79
79
  onEditDefaults: async (row) => {
80
80
  const cfg = await loadConfig(opts.cwd, { allowLocal: opts.allowLocalConfig })
@@ -85,7 +85,7 @@ export async function runProviderManager(opts: {
85
85
  onEditSave: async (row, { baseUrl, apiKey }): Promise<ProviderActionResult> => {
86
86
  const cfg = await loadConfig(opts.cwd, { allowLocal: opts.allowLocalConfig })
87
87
  const cur = cfg.providers.find((p) => p.id === row.id)
88
- if (!cur) return { err: "Provider not found" }
88
+ if (!cur) return { err: t("ntc.notFound") }
89
89
  try {
90
90
  await removeProvider(row.id, { global: true })
91
91
  if (opts.cwd) await removeProvider(row.id, { global: false, cwd: opts.cwd })
@@ -96,7 +96,7 @@ export async function runProviderManager(opts: {
96
96
  allowLocal: opts.allowLocalConfig,
97
97
  })
98
98
  await reloadProviders(opts.cwd, { allowLocal: opts.allowLocalConfig }).catch(warnReloadFail)
99
- return { ok: `Provider "${entry.id}" updated (${entry.models.length} models)` }
99
+ return { ok: t("ntc.updated", { id: entry.id, n: entry.models.length }) }
100
100
  } catch (e) {
101
101
  await detectAndSave(cur.baseUrl, cur.apiKey, cur.id, {
102
102
  global: true,
@@ -104,7 +104,7 @@ export async function runProviderManager(opts: {
104
104
  fallbackModels: cur.models,
105
105
  }).catch(() => {})
106
106
  await reloadProviders(opts.cwd, { allowLocal: opts.allowLocalConfig }).catch(warnReloadFail)
107
- return { err: `Update failed: ${(e as Error).message.slice(0, 80)}` }
107
+ return { err: t("prov.updateFail", { msg: (e as Error).message.slice(0, 80) }) }
108
108
  }
109
109
  },
110
110
  })
package/cli/setup.ts CHANGED
@@ -696,7 +696,16 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
696
696
  const richStatus = process.env.MINICODE_STATUSLINE === "rich"
697
697
  const attachUI = () => {
698
698
  detachUI()
699
- detachSimple = attachSimpleLogger(session.events, { verbose })
699
+ // Mode interaktif = TUI fullscreen memiliki layar (kontrak I3: App
700
+ // penulis tunggal). Printer linier + spinner turn-status DITEKAN agar tak
701
+ // mengotori alt-screen — state tetap jalan (quiet: rememberTurn untuk
702
+ // /copy, bufferSection untuk /expand). One-shot/exec (enterRepl false)
703
+ // tetap melukis seperti dulu.
704
+ detachSimple = attachSimpleLogger(session.events, { verbose, quiet: enterRepl === true })
705
+ if (enterRepl === true) {
706
+ turnStatus = null
707
+ return
708
+ }
700
709
  turnStatus = attachTurnStatus(session.events, {
701
710
  initialModel: effectiveInitialModel,
702
711
  getModel: () => modelRef.current ?? effectiveInitialModel,
package/cli/tui.ts ADDED
@@ -0,0 +1,506 @@
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 { sectionMinimized, setSectionMinimized } from "../src/ui/render/collapse.ts"
27
+ import { setCompactMode } from "../src/ui/render/detail.ts"
28
+ import { formatUsd } from "../src/ui/render/money.ts"
29
+ import { setReasoningVisible } from "../src/ui/render/reasoning.ts"
30
+ import { c } from "../src/ui/render/theme.ts"
31
+ import { TuiApp, type TuiHost } from "../src/ui/tui/app.ts"
32
+ import { Transcript } from "../src/ui/tui/transcript.ts"
33
+ import {
34
+ BUILTIN_COMMANDS,
35
+ type CommandContext,
36
+ DRIVER_HELP_COMMANDS,
37
+ handleBuiltinCommand,
38
+ persistModelChoice,
39
+ suggestSimilar,
40
+ } from "./commands.ts"
41
+ import type { CliSession } from "./setup.ts"
42
+
43
+ const MODES = ["auto", "ask", "plan", "allowlist", "allow-all"] as const
44
+ const DRIVER_COMMANDS = ["/compact", "/thinking", "/expand", "/minimize"]
45
+
46
+ function fmtCtx(n: number): string | undefined {
47
+ if (!Number.isFinite(n) || n <= 0) return undefined
48
+ if (n < 1000) return String(n)
49
+ if (n < 10000) return `${(n / 1000).toFixed(1)}k`
50
+ if (n < 1000000) return `${Math.round(n / 1000)}k`
51
+ return `${(n / 1000000).toFixed(1)}m`
52
+ }
53
+
54
+ /**
55
+ * Tangkap console.log/error selama `fn` → baris teks (tanpa warna liar:
56
+ * caller yang mewarnai). Dipakai membungkus handleBuiltinCommand supaya
57
+ * readout warisan (/help, pin jendela, pesan undo) mendarat di transkrip,
58
+ * bukan menimpa frame alt-screen. View modal menulis via stdout.write
59
+ * langsung (bukan console) sehingga tak ikut tertangkap — layarnya tetap
60
+ * tampil normal (nested refcount screen.ts). Baris yang sudah tercetak
61
+ * SEBELUM fn melempar tetap dikembalikan via capturedLines (ditempel ke
62
+ * error) — tanpa ini kegagalan di tengah readout (/sync) diam-diam
63
+ * membuang output parsial.
64
+ */
65
+ async function captureConsole(fn: () => Promise<void>): Promise<string[]> {
66
+ const lines: string[] = []
67
+ const origLog = console.log
68
+ const origErr = console.error
69
+ console.log = (...args: unknown[]) => {
70
+ lines.push(args.map((a) => (typeof a === "string" ? a : String(a))).join(" "))
71
+ }
72
+ console.error = (...args: unknown[]) => {
73
+ lines.push(args.map((a) => (typeof a === "string" ? a : String(a))).join(" "))
74
+ }
75
+ const flush = () => lines.flatMap((l) => l.split("\n"))
76
+ try {
77
+ await fn()
78
+ } catch (e) {
79
+ ;(e as { capturedLines?: string[] }).capturedLines = flush()
80
+ throw e
81
+ } finally {
82
+ console.log = origLog
83
+ console.error = origErr
84
+ }
85
+ return flush()
86
+ }
87
+
88
+ export async function runTui(ctx: CliSession): Promise<void> {
89
+ const {
90
+ cfg,
91
+ cwd,
92
+ sessionId,
93
+ modelRef,
94
+ permissionMode,
95
+ permissions,
96
+ sessionTools,
97
+ allLoadedSkills,
98
+ allowLocalConfig,
99
+ usage,
100
+ budget,
101
+ budgetStrict,
102
+ persistCurrent,
103
+ runPromptWithVerify,
104
+ close,
105
+ } = ctx
106
+ const { session } = ctx
107
+
108
+ let mode: string = permissions?.getMode() ?? permissionMode ?? "auto"
109
+ if (process.env.MINICODE_COMPACT === undefined) setCompactMode(true)
110
+ if (process.env.MINICODE_MINIMIZE_TOOL === undefined) setSectionMinimized("tool", true)
111
+ let warned80 = false
112
+ let abort: AbortController | null = null
113
+
114
+ // Bahasa UI: state.json (sesi bisa menimpa via /lang). Gagal baca = default.
115
+ const { setConfigLocale } = await import("../src/ui/i18n/locale.ts")
116
+ try {
117
+ const { loadLang } = await import("../src/config.ts")
118
+ setConfigLocale((await loadLang().catch(() => undefined)) ?? null)
119
+ } catch {}
120
+
121
+ const transcript = new Transcript(session.events as unknown as UiBus)
122
+
123
+ const commandCtx: CommandContext = {
124
+ cwd,
125
+ sessionId,
126
+ allowLocalConfig,
127
+ get currentModel() {
128
+ return modelRef.current ?? cfg.providers[0]?.models[0]
129
+ },
130
+ set currentModel(v) {
131
+ modelRef.current = v
132
+ },
133
+ usage,
134
+ skills: allLoadedSkills,
135
+ toolsCount: sessionTools.length,
136
+ providerHint: cfg.providers[0]?.providerHint,
137
+ setModelOverride: (m) => persistModelChoice(m, modelRef),
138
+ // Spawn anak stdio-inherit (/sessions <id>): keluar alt-screen + cooked
139
+ // mode DULU — anak mewarisi terminal apa adanya. Tanpa ini: double-ENTER,
140
+ // EXIT anak merobek buffer parent, stdin mentah macet. Gagal-di-kode-lama.
141
+ onBeforeSpawn: () => app.releaseTerminal(),
142
+ getContextTokens: () => session.contextTokens,
143
+ budgetState: () => {
144
+ const u = usage.getSession()
145
+ return budgetStatus(budget, u.cost, budgetStrict ?? false, u.totalTokens)
146
+ },
147
+ }
148
+
149
+ const suggestions = (line: string): string[] => {
150
+ if (!line.startsWith("/")) return []
151
+ const all = [
152
+ ...BUILTIN_COMMANDS.map((b) => `/${b.name}`),
153
+ ...DRIVER_COMMANDS,
154
+ ...allLoadedSkills.map((s) => `/${s.name}`),
155
+ ]
156
+ return all.filter((t) => t.startsWith(line))
157
+ }
158
+
159
+ const cycleMode = (dir: 1 | -1): void => {
160
+ const idx = (MODES as readonly string[]).indexOf(mode)
161
+ // allow-all hanya via flag --allow-all (paritas REPL).
162
+ let next = MODES[(idx + dir + MODES.length) % MODES.length]!
163
+ if (next === "allow-all") next = MODES[(idx + dir * 2 + MODES.length * 2) % MODES.length]!
164
+ mode = next
165
+ if (permissions) permissions.setMode(mode as (typeof MODES)[number])
166
+ else mode = permissionMode ?? mode
167
+ }
168
+
169
+ async function runBuiltin(
170
+ q: string,
171
+ ): Promise<{ lines: string[]; shouldExit: boolean; handled: boolean }> {
172
+ let shouldExit = false
173
+ let handled = false
174
+ let lines: string[] = []
175
+ try {
176
+ lines = await captureConsole(async () => {
177
+ const r = await handleBuiltinCommand(q, commandCtx)
178
+ shouldExit = !!r.shouldExit
179
+ handled = r.handled
180
+ })
181
+ } catch (e) {
182
+ // Baris parsial yang sempat tercetak sebelum throw tetap tampil —
183
+ // tanpa ini hanya pesan error generik yang keluar (data-loss diam).
184
+ lines = (e as { capturedLines?: string[] }).capturedLines ?? []
185
+ if (lines.length) transcript.pushInfo(lines)
186
+ throw e
187
+ }
188
+ return { lines, shouldExit, handled }
189
+ }
190
+
191
+ async function delegateBuiltin(q: string): Promise<{ quit?: boolean }> {
192
+ const { lines, shouldExit } = await runBuiltin(q)
193
+ if (lines.length) transcript.pushInfo(lines)
194
+ return shouldExit ? { quit: true } : {}
195
+ }
196
+
197
+ /**
198
+ * Builtin yang membuka popup: bekukan App (input dilepas + layar redup),
199
+ * view melukis regionnya sendiri, App repaint saat kembali. Tanpa ini
200
+ * byte masuk ke dua tempat (App + popup) dan frame App menimpa popup.
201
+ * Struk mutasi: model/provider yang berubah saat popup terbuka dicatat
202
+ * ke transkrip (jejak audit — scroll ke atas selalu menunjukkan ganti).
203
+ */
204
+ async function popupBuiltin(q: string): Promise<{ quit?: boolean }> {
205
+ const before = commandCtx.currentModel
206
+ app.suspend()
207
+ try {
208
+ return await delegateBuiltin(q)
209
+ } catch (e) {
210
+ // Spawn anak gagal (terminal sudah dilepas onBeforeSpawn): hidupkan
211
+ // kembali atau keluar bersih — jangan biarkan TUI mati tanpa layar.
212
+ if (!app.reacquireTerminal()) app.requestQuit()
213
+ throw e
214
+ } finally {
215
+ app.resume()
216
+ const after = commandCtx.currentModel
217
+ if (after && after !== before) transcript.pushInfo([c.muted(t("tui.modelSet", { v: after }))])
218
+ }
219
+ }
220
+
221
+ async function runTurn(prompt: string): Promise<void> {
222
+ const spent = usage.getSession(modelRef.current)
223
+ const preStatus = budgetStatus(budget, spent.cost, budgetStrict ?? false, spent.totalTokens)
224
+ if (preStatus === "over" && spent.cost != null && budget != null) {
225
+ transcript.pushError(
226
+ t("tui.budgetOver", { spent: formatUsd(spent.cost), budget: formatUsd(budget) }),
227
+ )
228
+ return
229
+ }
230
+ if (preStatus === "unknown-strict") {
231
+ transcript.pushError(t("tui.budgetUnknown", { tokens: spent.totalTokens }))
232
+ return
233
+ }
234
+ let finalPrompt = prompt
235
+ if (prompt.includes("@")) {
236
+ const expanded = await expandMentions(prompt, cwd ?? process.cwd())
237
+ finalPrompt = expanded.prompt
238
+ if (expanded.notes.length)
239
+ transcript.pushInfo(expanded.notes.map((n) => c.muted(` [@mention] ${n}`)))
240
+ }
241
+ const ctrl = new AbortController()
242
+ abort = ctrl
243
+ try {
244
+ await runPromptWithVerify(finalPrompt, ctrl.signal)
245
+ if (ctrl.signal.aborted) transcript.pushInfo([c.muted(t("tui.stopped"))])
246
+ } finally {
247
+ abort = null
248
+ }
249
+ const u = usage.get(modelRef.current)
250
+ await persistCurrent(u)
251
+ usage.reset()
252
+ const sess = usage.getSession(modelRef.current)
253
+ if (
254
+ budget != null &&
255
+ sess.cost != null &&
256
+ sess.cost > budget * 0.8 &&
257
+ sess.cost <= budget &&
258
+ !warned80
259
+ ) {
260
+ warned80 = true
261
+ transcript.pushInfo([
262
+ c.muted(t("tui.budget80", { spent: formatUsd(sess.cost), budget: formatUsd(budget) })),
263
+ ])
264
+ }
265
+ }
266
+
267
+ /**
268
+ * /help ringkas (≤6 baris): daftar perintah muat viewport tanpa
269
+ * membanjiri transkrip. Detail penuh = `/help tombol` (delegasi).
270
+ */
271
+ function helpConcise(): void {
272
+ // Diturunkan dari registry (BUILTIN + driver) — perintah baru tak bisa
273
+ // hilang dari /help diam-diam (satu sumber, bukan daftar hardcode).
274
+ const builtin = BUILTIN_COMMANDS.map((b) => `/${b.name}`).join(" ")
275
+ const driver = [...DRIVER_COMMANDS, ...DRIVER_HELP_COMMANDS.map((b) => `/${b.name}`)].join(" ")
276
+ transcript.pushInfo([
277
+ t("help.cHead"),
278
+ ` ${builtin}`,
279
+ ` ${driver}`,
280
+ t("help.cKeys"),
281
+ t("help.cMore"),
282
+ ])
283
+ }
284
+
285
+ async function copyLastTurn(): Promise<void> {
286
+ const txt = getLastTurnText().trim()
287
+ if (!txt) {
288
+ transcript.pushInfo([c.muted(t("tui.copyNone"))])
289
+ return
290
+ }
291
+ if (writeClipboardOsc52(txt)) transcript.pushInfo([c.muted(t("tui.copyOk", { n: txt.length }))])
292
+ else transcript.pushInfo([c.muted(t("tui.copyNeedTty"))])
293
+ }
294
+
295
+ async function submit(line: string): Promise<{ quit?: boolean } | undefined> {
296
+ if (!line.startsWith("/")) {
297
+ await runTurn(line)
298
+ return
299
+ }
300
+ const spaceIdx = line.indexOf(" ")
301
+ const name = (spaceIdx === -1 ? line.slice(1) : line.slice(1, spaceIdx)).toLowerCase()
302
+ const args = spaceIdx === -1 ? "" : line.slice(spaceIdx + 1).trim()
303
+
304
+ if (name === "") {
305
+ helpConcise()
306
+ return
307
+ }
308
+ if (name === "help" && !args) {
309
+ helpConcise()
310
+ return
311
+ }
312
+ if (name === "exit" || name === "quit") return { quit: true }
313
+ if (name === "clear") {
314
+ transcript.clear()
315
+ return
316
+ }
317
+ if (name === "mode") {
318
+ if (args) {
319
+ if (!(MODES as readonly string[]).includes(args)) {
320
+ transcript.pushInfo([c.muted(t("tui.unknownMode", { a: args, modes: MODES.join(", ") }))])
321
+ return
322
+ }
323
+ mode = args
324
+ permissions?.setMode(args as (typeof MODES)[number])
325
+ } else {
326
+ cycleMode(1)
327
+ }
328
+ transcript.pushInfo([c.muted(t("tui.modeLine", { m: mode }))])
329
+ return
330
+ }
331
+ if (name === "lang") {
332
+ const { currentLocale, setSessionLocale } = await import("../src/ui/i18n/locale.ts")
333
+ if (!args) {
334
+ transcript.pushInfo([c.muted(t("tui.langLine", { v: `${currentLocale()} (en|id)` }))])
335
+ return
336
+ }
337
+ const next = args.trim().toLowerCase()
338
+ if (next !== "en" && next !== "id") {
339
+ transcript.pushInfo([c.muted(t("tui.langUnknown", { a: args }))])
340
+ return
341
+ }
342
+ setSessionLocale(next)
343
+ // Simpan permanen (best-effort); sesi ini langsung berlaku via session.
344
+ try {
345
+ const { saveLang } = await import("../src/config.ts")
346
+ await saveLang(next)
347
+ } catch {}
348
+ transcript.pushInfo([c.muted(t("tui.langLine", { v: next }))])
349
+ return
350
+ }
351
+ if (name === "compact") {
352
+ const next = args === "" ? undefined : args === "on" || args === "1"
353
+ const compact = setCompactMode(next)
354
+ transcript.pushInfo([c.muted(t("tui.toolCall", { v: compact ? "compact" : "expanded" }))])
355
+ return
356
+ }
357
+ if (name === "thinking") {
358
+ const next = args === "" ? undefined : args === "on" || args === "1"
359
+ const vis = setReasoningVisible(next)
360
+ transcript.pushInfo([c.muted(t("tui.thinkingSet", { v: vis ? "expanded" : "minimized" }))])
361
+ return
362
+ }
363
+ if (name === "expand") {
364
+ // Buka isi tool yang disembunyikan ledger compact. Sekali ambil = habis
365
+ // (arsip dibuka); butuh buffer baru = turn baru.
366
+ const sections = transcript.takeBufferedSections()
367
+ if (!sections.length) {
368
+ transcript.pushInfo([c.muted(t("tui.expandEmpty"))])
369
+ return
370
+ }
371
+ const lines: string[] = []
372
+ for (const s of sections) {
373
+ lines.push(c.muted(` ── ${s.label} ──`))
374
+ for (const ln of s.text.split("\n")) lines.push(` ${ln}`)
375
+ }
376
+ transcript.pushInfo(lines)
377
+ return
378
+ }
379
+ if (name === "minimize") {
380
+ const arg = args.trim().toLowerCase()
381
+ let next: boolean | undefined
382
+ if (arg === "") next = !(sectionMinimized("tool") && sectionMinimized("answer"))
383
+ else if (arg === "on" || arg === "1") next = true
384
+ else if (arg === "off" || arg === "0") next = false
385
+ else {
386
+ transcript.pushInfo([c.muted(t("tui.minUse"))])
387
+ return
388
+ }
389
+ setSectionMinimized("tool", next)
390
+ setSectionMinimized("answer", next)
391
+ transcript.pushInfo([c.muted(t(next ? "tui.sectionsMin" : "tui.sectionsExp"))])
392
+ return
393
+ }
394
+ if (name === "undo") {
395
+ const res = await undoLastCheckpoint(sessionId, cwd)
396
+ transcript.pushInfo([res.message, ...res.restoredFiles])
397
+ return
398
+ }
399
+ if (name === "redo") {
400
+ const res = await redoLastCheckpoint(sessionId, cwd)
401
+ transcript.pushInfo([res.message, ...res.reappliedFiles])
402
+ return
403
+ }
404
+ if (name === "copy") {
405
+ await copyLastTurn()
406
+ return
407
+ }
408
+ if (name === "cost" || name === "usage") return delegateBuiltin("/status")
409
+ if (name === "models" || name === "model")
410
+ return popupBuiltin(`/model${args ? ` ${args}` : ""}`)
411
+ if (name === "providers" || name === "provider") return popupBuiltin("/provider")
412
+ if (name === "history") {
413
+ const lines = (await loadHistory()).slice(-20)
414
+ transcript.pushInfo(lines.length ? lines : [t("tui.historyEmpty")])
415
+ return
416
+ }
417
+ if (name === "resume" && !args) return popupBuiltin("/sessions")
418
+ if (name === "sessions" && !args) return popupBuiltin("/sessions")
419
+
420
+ // Builtin yang bisa membuka popup (/sessions <id> = resume-spawn,
421
+ // /model dengan filter) dibungkus suspend; yang murni cetak langsung.
422
+ const MODAL = new Set(["model", "provider", "sessions", "resume"])
423
+ if (MODAL.has(name)) return popupBuiltin(line)
424
+ const { lines, shouldExit, handled } = await runBuiltin(line)
425
+ if (shouldExit) return { quit: true }
426
+ // handled tanpa cetakan = murni modal (tak ada yang perlu ke transkrip).
427
+ if (handled) {
428
+ if (lines.length) transcript.pushInfo(lines)
429
+ return
430
+ }
431
+ // handleBuiltinCommand tak menangani → skill atau unknown (paritas REPL).
432
+ const skill = allLoadedSkills.find((s) => s.name === name)
433
+ if (!skill) {
434
+ const hint = suggestSimilar(name, [
435
+ ...BUILTIN_COMMANDS.map((b) => b.name),
436
+ ...DRIVER_COMMANDS.map((d) => d.slice(1)),
437
+ ...DRIVER_HELP_COMMANDS.map((b) => b.name),
438
+ "cost",
439
+ "usage",
440
+ "resume",
441
+ ...allLoadedSkills.map((s) => s.name),
442
+ ])
443
+ transcript.pushInfo([
444
+ c.muted(
445
+ t("tui.unknownCmd", {
446
+ name,
447
+ tail: hint ? t("tui.didYou", { hint }) : t("tui.tryHelp"),
448
+ }),
449
+ ),
450
+ ])
451
+ return
452
+ }
453
+ await runTurn(await renderSkill(skill, args))
454
+ }
455
+
456
+ const host: TuiHost = {
457
+ bus: session.events as unknown as TuiHost["bus"],
458
+ getStatus: () => ({
459
+ footer: {
460
+ mode,
461
+ model: modelRef.current ?? cfg.providers[0]?.models[0] ?? t("tui.noModel"),
462
+ cwd: cwd ?? process.cwd(),
463
+ context: fmtCtx(session.contextTokens),
464
+ },
465
+ busy: abort != null,
466
+ }),
467
+ listCommands: (prefix) => suggestions(prefix),
468
+ submit,
469
+ abort: () => {
470
+ abort?.abort()
471
+ },
472
+ cycleMode: (dir) => {
473
+ cycleMode(dir)
474
+ },
475
+ toggleCompact: () => {
476
+ const compact = setCompactMode()
477
+ transcript.pushInfo([c.muted(t("tui.toolCall", { v: compact ? "compact" : "expanded" }))])
478
+ },
479
+ toggleReasoning: () => {
480
+ const vis = setReasoningVisible()
481
+ transcript.pushInfo([c.muted(t("tui.thinkingSet", { v: vis ? "expanded" : "minimized" }))])
482
+ },
483
+ }
484
+
485
+ const app = new TuiApp(transcript, host)
486
+ // Approval sebagai warga TUI: blok pertanyaan + keputusan tercatat di
487
+ // transkrip dan terlihat sebelum menjawab (tanpa sink = tulis langsung).
488
+ const { setApprovalSink } = await import("../src/ui/tui/transcript.ts")
489
+ setApprovalSink({
490
+ pushBlock: (lines) => transcript.pushInfo(lines),
491
+ repaint: () => app.repaint(),
492
+ suspend: () => app.suspend(),
493
+ resume: () => app.resume(),
494
+ })
495
+ const res = await app.run()
496
+ setApprovalSink(null)
497
+ if (!res.started) {
498
+ // Terminal tak mampu (non-TTY/dumb/sempit): tak ada tampilan yang bisa
499
+ // dibuka. Satu baris jujur, bukan fallback setengah (REPL dihapus).
500
+ console.log(t("tui.noTty"))
501
+ await close()
502
+ return
503
+ }
504
+ transcript.dispose()
505
+ await close()
506
+ }
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
  }