minicode-ai 0.27.0 → 0.30.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 (145) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +184 -57
  3. package/cli/bootstrap/presentation-bridge.ts +383 -0
  4. package/cli/commands/acp.ts +45 -29
  5. package/cli/commands/auth.ts +17 -17
  6. package/cli/commands/config.ts +65 -66
  7. package/cli/commands/daemon.ts +44 -16
  8. package/cli/commands/doctor.ts +18 -15
  9. package/cli/commands/exec.ts +41 -89
  10. package/cli/commands/mcp.ts +25 -8
  11. package/cli/commands/memory.ts +16 -24
  12. package/cli/commands/openwork.ts +6 -2
  13. package/cli/commands/pricing.ts +14 -12
  14. package/cli/commands/providers.ts +36 -57
  15. package/cli/commands/sessions.ts +24 -18
  16. package/cli/commands/skills.ts +33 -18
  17. package/cli/commands/stats.ts +15 -30
  18. package/cli/commands.ts +73 -44
  19. package/cli/context-command-run.ts +30 -18
  20. package/cli/index.ts +51 -100
  21. package/cli/model-manager.ts +7 -2
  22. package/cli/provider-manager.ts +33 -18
  23. package/cli/router.ts +41 -12
  24. package/cli/setup.ts +241 -485
  25. package/cli/tui.ts +303 -100
  26. package/docs/TERMINAL_CONTRACT.md +258 -73
  27. package/docs/UI_RENDER_PIPELINE.md +9 -1
  28. package/docs/agents.md +2 -2
  29. package/docs/architecture.md +17 -32
  30. package/docs/choosing-mode.md +7 -9
  31. package/docs/cli.md +3 -5
  32. package/docs/environment.md +1 -2
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +2 -2
  35. package/docs/tools.md +1 -1
  36. package/package.json +1 -1
  37. package/src/app/mentions.ts +60 -13
  38. package/src/app/rag-layer.ts +17 -20
  39. package/src/app/session.ts +144 -68
  40. package/src/app/tool-layer.ts +38 -16
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +4 -6
  43. package/src/daemon/capability.ts +8 -1
  44. package/src/daemon/control.ts +3 -2
  45. package/src/daemon/server.ts +57 -0
  46. package/src/hooks/run.ts +73 -41
  47. package/src/lib/atomic-write.ts +31 -59
  48. package/src/lib/db-path.ts +47 -0
  49. package/src/lib/process-tree.ts +62 -0
  50. package/src/lib/public-http.ts +88 -23
  51. package/src/lib/trusted-exec.ts +48 -1
  52. package/src/lsp/client.ts +62 -17
  53. package/src/mcp/client.ts +85 -38
  54. package/src/mcp/http-transport.ts +28 -16
  55. package/src/mcp/transport.ts +42 -6
  56. package/src/memory/files.ts +164 -134
  57. package/src/memory/vector.ts +371 -420
  58. package/src/policy/approval-binding.ts +122 -45
  59. package/src/policy/bash-guard.ts +18 -7
  60. package/src/policy/compaction.ts +51 -18
  61. package/src/policy/context-window.ts +31 -8
  62. package/src/policy/context.ts +62 -36
  63. package/src/policy/executor.ts +17 -7
  64. package/src/policy/jail.ts +6 -8
  65. package/src/policy/microcompact.ts +4 -3
  66. package/src/policy/no-progress.ts +103 -22
  67. package/src/policy/permission.ts +36 -12
  68. package/src/policy/tool-contract.ts +74 -416
  69. package/src/policy/usage.ts +24 -2
  70. package/src/policy/verifier.ts +50 -2
  71. package/src/policy/work-mode.ts +28 -54
  72. package/src/presentation/adapter.ts +24 -16
  73. package/src/providers/anthropic.ts +16 -5
  74. package/src/providers/provision.ts +6 -56
  75. package/src/providers/responses.ts +38 -7
  76. package/src/providers/sse-bounds.ts +6 -4
  77. package/src/runtime/execution-journal.ts +4 -29
  78. package/src/sandbox/docker.ts +58 -34
  79. package/src/sandbox/mask.ts +157 -0
  80. package/src/sandbox/os.ts +107 -73
  81. package/src/session/authority.ts +29 -10
  82. package/src/session/context-projection.ts +6 -5
  83. package/src/session/db/runs.ts +397 -0
  84. package/src/session/db/schema.ts +358 -0
  85. package/src/session/open-work.ts +26 -3
  86. package/src/session/persistence.ts +74 -998
  87. package/src/session/verification.ts +170 -20
  88. package/src/skills/loader.ts +31 -16
  89. package/src/task/db/schema.ts +325 -0
  90. package/src/task/db/types.ts +269 -0
  91. package/src/task/production-scheduler.ts +13 -1
  92. package/src/task/store.ts +92 -1021
  93. package/src/telemetry/trace.ts +27 -0
  94. package/src/tools/ask_user.ts +1 -13
  95. package/src/tools/bash.ts +27 -92
  96. package/src/tools/code_run.ts +1 -1
  97. package/src/tools/context.ts +133 -0
  98. package/src/tools/delete_file.ts +3 -2
  99. package/src/tools/edit.ts +37 -72
  100. package/src/tools/git.ts +86 -9
  101. package/src/tools/glob.ts +26 -51
  102. package/src/tools/grep.ts +67 -57
  103. package/src/tools/hashline.ts +4 -0
  104. package/src/tools/lsp.ts +11 -8
  105. package/src/tools/mcp_call.ts +9 -6
  106. package/src/tools/memory.ts +56 -33
  107. package/src/tools/move_file.ts +36 -10
  108. package/src/tools/patch.ts +13 -21
  109. package/src/tools/read_file.ts +18 -25
  110. package/src/tools/read_image.ts +35 -33
  111. package/src/tools/submit_result.ts +29 -8
  112. package/src/tools/task.ts +74 -17
  113. package/src/tools/todo.ts +181 -74
  114. package/src/tools/web_fetch.ts +42 -2
  115. package/src/tools/web_search.ts +47 -8
  116. package/src/ui/approval/prompt.ts +206 -47
  117. package/src/ui/assistant/turn-status.ts +14 -5
  118. package/src/ui/footer.ts +4 -4
  119. package/src/ui/i18n/en.ts +47 -23
  120. package/src/ui/i18n/id.ts +76 -51
  121. package/src/ui/input/input.ts +4 -3
  122. package/src/ui/input/prompt-engine.ts +35 -5
  123. package/src/ui/render/activity-panel.ts +4 -2
  124. package/src/ui/render/hint.ts +7 -4
  125. package/src/ui/render/list.ts +32 -0
  126. package/src/ui/render/markdown.ts +6 -3
  127. package/src/ui/render/notice.ts +19 -0
  128. package/src/ui/render/table-grid.ts +7 -8
  129. package/src/ui/render/theme.ts +113 -39
  130. package/src/ui/runtime/screen.ts +74 -10
  131. package/src/ui/runtime/spinner.ts +19 -6
  132. package/src/ui/screens/dialog.ts +19 -1
  133. package/src/ui/screens/form.ts +80 -35
  134. package/src/ui/screens/model-manager.ts +82 -61
  135. package/src/ui/screens/output-window.ts +263 -0
  136. package/src/ui/screens/picker.ts +94 -81
  137. package/src/ui/screens/provider-manager.ts +100 -69
  138. package/src/ui/screens/wizard.ts +117 -28
  139. package/src/ui/tui/app.ts +196 -33
  140. package/src/ui/tui/transcript.ts +158 -25
  141. package/vendor/minicore/src/core/executor.ts +2 -0
  142. package/vendor/minicore/src/core/loop.ts +17 -6
  143. package/vendor/minicore/src/core/session.ts +3 -0
  144. package/vendor/minicore/src/core/tool.ts +1 -0
  145. package/vendor/minicore/src/providers/openai-compat.ts +35 -19
package/cli/tui.ts CHANGED
@@ -37,14 +37,17 @@ import type { UiBus } from "../src/ui/contract.ts"
37
37
  import { t } from "../src/ui/i18n/locale.ts"
38
38
  import { loadHistory } from "../src/ui/input/input.ts"
39
39
  import { formatUsd } from "../src/ui/render/money.ts"
40
+ import { sanitizeAnsiLine } from "../src/ui/render/sanitize.ts"
40
41
  import { c, glyphs } from "../src/ui/render/theme.ts"
42
+ import { canRenderModal, dialogBox, popupBoxWidth } from "../src/ui/screens/dialog.ts"
43
+ import { runOutputWindow } from "../src/ui/screens/output-window.ts"
41
44
  // [Area A · PROMPT 06] State UI milik SESI ini. TUI + printer linier sesi yang
42
45
  // sama berbagi state (satu instance), sesi lain di proses yang sama tak
43
46
  // tersentuh. Absen = instance default (fixture tes partial).
44
47
  import { defaultUiState, type UiSessionState } from "../src/ui/session-state.ts"
45
48
  import { TuiApp, type TuiHost } from "../src/ui/tui/app.ts"
46
49
  import { Transcript } from "../src/ui/tui/transcript.ts"
47
- import { displayWorkMode, parseWorkModeValue } from "./args.ts"
50
+ import { displayWorkMode, parseToggleArg, parseWorkModeValue } from "./args.ts"
48
51
  import {
49
52
  BUILTIN_COMMANDS,
50
53
  type CommandContext,
@@ -57,19 +60,25 @@ import {
57
60
  import type { CliSession } from "./setup.ts"
58
61
 
59
62
  // [mode-architecture] Approval axis (PermissionMode) = AUTO/ASK; operating axis
60
- // (WorkMode) = DISCUSS/PLAN/BUILD, dikelola terpisah via /work-mode. Nilai
63
+ // (WorkMode) = DISCUSS/BUILD, dikelola terpisah via /work-mode. Nilai
61
64
  // internal tetap lowercase (auto/ask) dan EXECUTE (identitas BUILD).
62
65
  const PERMISSION_MODES = ["auto", "ask"] as const
63
- const WORK_MODE_CYCLE = ["DISCUSS", "PLAN", "EXECUTE"] as const
66
+ const WORK_MODE_CYCLE = ["DISCUSS", "EXECUTE"] as const
64
67
  // /expand [id]: tanpa arg = semua entry store; dengan id = satu tool.
65
68
  const DRIVER_COMMANDS = [
66
69
  "/compact",
67
70
  "/thinking",
68
- "/expand [id]",
71
+ "/expand",
69
72
  "/minimize",
70
73
  "/fold",
71
74
  "/mode",
72
75
  "/work-mode",
76
+ "/lang",
77
+ "/clear",
78
+ "/copy",
79
+ "/history",
80
+ "/undo",
81
+ "/redo",
73
82
  ]
74
83
 
75
84
  function fmtCtx(n: number): string | undefined {
@@ -93,7 +102,11 @@ function fmtCtx(n: number): string | undefined {
93
102
  */
94
103
  function fmtUsageMetrics(ctx: CliSession, used: number): string | undefined {
95
104
  const cost: number | undefined = ctx.usage.getSession().cost
96
- const windowTokens: number | undefined = ctx.getContextWindowTokens?.() ?? ctx.contextWindowTokens
105
+ // Utamakan getter `contextWindowTokens` bila ada agar `safe-default` (`undefined`)
106
+ // tidak menampilkan % palsu di footer, sambil fallback ke `getContextWindowTokens()`
107
+ // untuk stub/test minimal yang tidak mendefinisikan properti getter tersebut.
108
+ const windowTokens: number | undefined =
109
+ "contextWindowTokens" in ctx ? ctx.contextWindowTokens : ctx.getContextWindowTokens?.()
97
110
  const parts: string[] = []
98
111
  if (cost !== undefined && Number.isFinite(cost) && cost > 0) parts.push(formatUsd(cost))
99
112
  if (
@@ -184,7 +197,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
184
197
  // Mode permission sebelum /unrestric diaktifkan — dipakai untuk memulihkan
185
198
  // saat operator menonaktifkannya kembali (toggle, per-sesi).
186
199
  let modeBeforeUnrestricted: string | null = null
187
- let workModeBeforeUnrestricted: "DISCUSS" | "PLAN" | "EXECUTE" | null = null
200
+ let workModeBeforeUnrestricted: "DISCUSS" | "EXECUTE" | null = null
188
201
  if (process.env.MINICODE_COMPACT === undefined) ui.setCompactMode(true)
189
202
  if (process.env.MINICODE_MINIMIZE_TOOL === undefined) ui.setSectionMinimized("tool", true)
190
203
  // Grouping aktivitas tool jadi satu baris (opencode-like): default ON di TUI;
@@ -214,26 +227,36 @@ export async function runTui(ctx: CliSession): Promise<void> {
214
227
  const uiBus = session.events as unknown as UiBus
215
228
  try {
216
229
  liveContextUnsubs.push(
217
- uiBus.on("provider:extension", (e: { kind?: unknown; data?: unknown }) => {
218
- if (e?.kind !== "context-window") return
219
- const d = e.data as { usedTokens?: unknown } | undefined
220
- if (typeof d?.usedTokens === "number") liveContextTokens = d.usedTokens
221
- }),
222
- )
223
- } catch {}
224
- try {
225
- liveContextUnsubs.push(
226
- uiBus.on("turn:started", () => {
227
- liveContextTokens = undefined
228
- }),
230
+ uiBus.on(
231
+ "provider:extension",
232
+ (e: { kind?: unknown; data?: unknown; forwardedChild?: unknown }) => {
233
+ if (e?.forwardedChild != null) return
234
+ if (e?.kind !== "context-window") return
235
+ const d = e.data as { usedTokens?: unknown } | undefined
236
+ if (typeof d?.usedTokens === "number") liveContextTokens = d.usedTokens
237
+ },
238
+ ),
229
239
  )
230
240
  } catch {}
241
+ for (const evName of ["turn:started", "turn:completed", "context:compacted"] as const) {
242
+ try {
243
+ liveContextUnsubs.push(
244
+ uiBus.on(evName, () => {
245
+ liveContextTokens = undefined
246
+ cachedContext = null
247
+ }),
248
+ )
249
+ } catch {}
250
+ }
231
251
  try {
232
- liveContextUnsubs.push(
233
- uiBus.on("turn:completed", () => {
234
- liveContextTokens = undefined
235
- }),
236
- )
252
+ // Kernel memancarkan `turn:interrupted` saat abort/error meski tidak ada di subset UiBus.
253
+ const unsubInterrupted = (
254
+ session.events as unknown as { on?: (t: string, fn: () => void) => () => void }
255
+ ).on?.("turn:interrupted", () => {
256
+ liveContextTokens = undefined
257
+ cachedContext = null
258
+ })
259
+ if (typeof unsubInterrupted === "function") liveContextUnsubs.push(unsubInterrupted)
237
260
  } catch {}
238
261
  const getContextTokens = (): number => {
239
262
  // Live (per-step) menang saat turn berjalan; idle → committed (cache).
@@ -322,14 +345,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
322
345
  }
323
346
  : {}),
324
347
  get currentModel() {
325
- return modelRef.current ?? cfg.providers[0]?.models[0]
348
+ if (modelRef.current) return modelRef.current
349
+ const first = cfg.providers[0]
350
+ const m = first?.models[0]
351
+ return first && m ? `${first.id}::${m}` : m
326
352
  },
327
353
  set currentModel(v) {
328
354
  modelRef.current = v
329
355
  },
330
356
  usage,
331
357
  skills: allLoadedSkills,
332
- toolsCount: sessionTools.length,
358
+ // CMD-07: toolsCount & providerHint dibaca live agar perubahan WorkMode
359
+ // (DISCUSS ↔ BUILD) atau pergantian model tercermin di /status.
360
+ get toolsCount() {
361
+ return sessionTools.length
362
+ },
333
363
  // P1.2: dua dimensi selalu terbaca live di /status — bukan snapshot boot.
334
364
  // [mode-architecture] /status memakai nilai PRODUK (BUILD/AUTO/ASK).
335
365
  get workMode() {
@@ -338,12 +368,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
338
368
  get permissionMode() {
339
369
  return (permissions?.getMode() ?? mode).toUpperCase()
340
370
  },
341
- providerHint: cfg.providers[0]?.providerHint,
371
+ get providerHint() {
372
+ const cur = modelRef.current
373
+ const pid = cur?.includes("::") ? cur.slice(0, cur.indexOf("::")) : undefined
374
+ return (
375
+ (pid ? cfg.providers.find((p) => p.id === pid)?.providerHint : undefined) ??
376
+ cfg.providers[0]?.providerHint
377
+ )
378
+ },
342
379
  setModelOverride: (m) => persistModelChoice(m, modelRef),
343
380
  // Spawn anak stdio-inherit (/sessions <id>): keluar alt-screen + cooked
344
- // mode DULU — anak mewarisi terminal apa adanya. Tanpa ini: double-ENTER,
345
- // EXIT anak merobek buffer parent, stdin mentah macet. Gagal-di-kode-lama.
346
- onBeforeSpawn: () => app.releaseTerminal(),
381
+ // mode DULU dan tutup lease sesi induk agar anak tidak ditolak WRITER_REFUSED.
382
+ onBeforeSpawn: async () => {
383
+ app.releaseTerminal()
384
+ await close().catch(() => {})
385
+ },
347
386
  getContextTokens: () => session.contextTokens,
348
387
  budgetState: () => {
349
388
  const u = usage.getSession()
@@ -391,13 +430,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
391
430
  workModeControl.setWorkMode(next)
392
431
  }
393
432
 
394
- // Shift+Tab: toggle PermissionMode (AUTO ↔ ASK). Tidak ada privilege change
395
- // diam — hanya sumbu persetujuan.
433
+ const clearUnrestrictedBackup = (wasUnrestricted: boolean): void => {
434
+ if (!wasUnrestricted) return
435
+ if (workModeBeforeUnrestricted) workModeControl?.setWorkMode(workModeBeforeUnrestricted)
436
+ modeBeforeUnrestricted = null
437
+ workModeBeforeUnrestricted = null
438
+ }
439
+
440
+ // Shift+Tab: toggle PermissionMode (AUTO ↔ ASK); pulihkan WorkMode bila keluar unrestricted.
396
441
  const togglePermissionMode = (): void => {
397
442
  if (!permissions) return
443
+ const wasUnrestricted = mode === "unrestricted"
398
444
  const next = permissions.getMode() === "ask" ? "auto" : "ask"
399
445
  permissions.setMode(next)
400
446
  mode = next
447
+ clearUnrestrictedBackup(wasUnrestricted)
401
448
  }
402
449
 
403
450
  async function runBuiltin(
@@ -423,9 +470,71 @@ export async function runTui(ctx: CliSession): Promise<void> {
423
470
  return { lines, shouldExit, handled }
424
471
  }
425
472
 
473
+ /** Judul jendela hasil command — satu sumber untuk semua readout. */
474
+ function commandWindowTitle(q: string): string {
475
+ const name = (q.trim().split(/\s+/)[0] ?? "").replace(/^\/+/, "").toLowerCase()
476
+ switch (name) {
477
+ case "help":
478
+ return t("out.titleHelp")
479
+ case "status":
480
+ case "cost":
481
+ case "usage":
482
+ return t("out.titleStatus")
483
+ case "context":
484
+ return t("ctx.title")
485
+ case "history":
486
+ return t("out.titleHistory")
487
+ case "sync":
488
+ return t("out.titleSync")
489
+ case "init":
490
+ return t("out.titleInit")
491
+ case "expand":
492
+ return t("out.titleExpand")
493
+ case "scheduler":
494
+ return t("sched.title")
495
+ case "sessions":
496
+ case "resume":
497
+ return t("sess.title")
498
+ case "model":
499
+ case "models":
500
+ return t("out.titleModels")
501
+ case "provider":
502
+ case "providers":
503
+ return t("out.titleProviders")
504
+ default:
505
+ return t("out.titleCommand")
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Output command readout tampil sebagai JENDELA di atas chat, bukan dicetak
511
+ * ke transkrip. Bila layar tak mampu, fallback ke transkrip agar data tidak
512
+ * hilang. App dibekukan selama jendela hidup (pola popupBuiltin).
513
+ */
514
+ async function showCommandOutput(title: string, lines: string[]): Promise<boolean> {
515
+ if (!lines.length) return true
516
+ app.suspend()
517
+ let opened = false
518
+ try {
519
+ opened = await runOutputWindow({
520
+ title,
521
+ lines,
522
+ onCopy: (text) => writeClipboardOsc52(text),
523
+ })
524
+ } catch {
525
+ opened = false
526
+ } finally {
527
+ app.resume()
528
+ }
529
+ if (!opened) transcript.pushInfo(lines)
530
+ return opened
531
+ }
532
+
426
533
  async function delegateBuiltin(q: string, recordOutput = true): Promise<{ quit?: boolean }> {
427
534
  const { lines, shouldExit } = await runBuiltin(q, recordOutput)
428
- if (recordOutput && lines.length) transcript.pushInfo(lines)
535
+ if (recordOutput && lines.length) {
536
+ await showCommandOutput(commandWindowTitle(q), lines)
537
+ }
429
538
  return shouldExit ? { quit: true } : {}
430
539
  }
431
540
 
@@ -437,9 +546,13 @@ export async function runTui(ctx: CliSession): Promise<void> {
437
546
  * kembali; transkrip tidak mengarsipkan pilihan UI yang sudah selesai.
438
547
  */
439
548
  async function popupBuiltin(q: string): Promise<{ quit?: boolean }> {
549
+ let lines: string[] = []
550
+ let shouldExit = false
440
551
  app.suspend()
441
552
  try {
442
- return await delegateBuiltin(q, false)
553
+ const res = await runBuiltin(q, true)
554
+ lines = res.lines
555
+ shouldExit = res.shouldExit
443
556
  } catch (e) {
444
557
  // Spawn anak gagal (terminal sudah dilepas onBeforeSpawn): hidupkan
445
558
  // kembali atau keluar bersih — jangan biarkan TUI mati tanpa layar.
@@ -448,6 +561,12 @@ export async function runTui(ctx: CliSession): Promise<void> {
448
561
  } finally {
449
562
  app.resume()
450
563
  }
564
+ const clean = lines.filter((l) => l.trim().length > 0)
565
+ if (clean.length > 0) {
566
+ if (clean.length <= 3) transcript.pushInfo(clean)
567
+ else await showCommandOutput(commandWindowTitle(q), lines)
568
+ }
569
+ return shouldExit ? { quit: true } : {}
451
570
  }
452
571
 
453
572
  async function runTurn(prompt: string): Promise<void> {
@@ -493,16 +612,16 @@ export async function runTui(ctx: CliSession): Promise<void> {
493
612
  ) {
494
613
  warned80 = true
495
614
  transcript.pushInfo([
496
- c.muted(t("tui.budget80", { spent: formatUsd(sess.cost), budget: formatUsd(budget) })),
615
+ c.warning(t("tui.budget80", { spent: formatUsd(sess.cost), budget: formatUsd(budget) })),
497
616
  ])
498
617
  }
499
618
  }
500
619
 
501
620
  /**
502
- * /help ringkas (≤6 baris): daftar perintah muat viewport tanpa
503
- * membanjiri transkrip. Detail penuh = `/help tombol` (delegasi).
621
+ * /help ringkas: daftar perintah per grup, ditampilkan di jendela output
622
+ * command (bukan transkrip). Detail penuh = `/help tombol` (delegasi).
504
623
  */
505
- function helpConcise(): void {
624
+ async function helpConcise(): Promise<void> {
506
625
  // Grup kurasi (sengaja bukan dump flat dari registry): label + baris pendek
507
626
  // per kategori supaya /help mudah dipindai. Sumber daftarnya SATU —
508
627
  // `HELP_GROUPS` di `cli/commands.ts` — karena sebelumnya grup di sini dan
@@ -510,7 +629,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
510
629
  // meninggalkan sisi lain basi (persis yang terjadi pada `/context`).
511
630
  const group = (label: string, names: readonly string[]): string =>
512
631
  ` ${label.padEnd(9)}${names.map((n) => `/${n}`).join(" ")}`
513
- transcript.pushInfo([
632
+ await showCommandOutput(t("out.titleHelp"), [
514
633
  t("help.cHead"),
515
634
  ...HELP_GROUPS.map((g) => group(t(g.key), g.names)),
516
635
  t("help.cKeys"),
@@ -562,11 +681,11 @@ export async function runTui(ctx: CliSession): Promise<void> {
562
681
  const args = spaceIdx === -1 ? "" : line.slice(spaceIdx + 1).trim()
563
682
 
564
683
  if (name === "") {
565
- helpConcise()
684
+ await helpConcise()
566
685
  return
567
686
  }
568
687
  if (name === "help" && !args) {
569
- helpConcise()
688
+ await helpConcise()
570
689
  return
571
690
  }
572
691
  if (name === "exit" || name === "quit") return { quit: true }
@@ -584,11 +703,16 @@ export async function runTui(ctx: CliSession): Promise<void> {
584
703
  transcript.pushInfo([c.muted(t("tui.unknownMode", { a: args, modes: "AUTO, ASK" }))])
585
704
  return
586
705
  }
706
+ const wasUnrestricted = mode === "unrestricted"
587
707
  mode = norm
588
708
  permissions?.setMode(norm as (typeof PERMISSION_MODES)[number])
709
+ clearUnrestrictedBackup(wasUnrestricted)
589
710
  } else {
590
711
  togglePermissionMode()
591
712
  }
713
+ const modeLabel = mode ? `${mode[0]!.toUpperCase()}${mode.slice(1)}` : ""
714
+ transcript.pushInfo([c.muted(t("tui.modeLine", { m: mode }))])
715
+ if (modeLabel) app.showToast(t("tui.modeLine", { m: modeLabel }))
592
716
  return
593
717
  }
594
718
  // [mode-architecture] /work-mode = WorkMode (operating mode) SAJA.
@@ -603,7 +727,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
603
727
  const next = parseWorkModeValue(args)
604
728
  if (!next) {
605
729
  transcript.pushInfo([
606
- c.muted(t("tui.workModeUnknown", { a: args, modes: "DISCUSS, PLAN, BUILD" })),
730
+ c.muted(t("tui.workModeUnknown", { a: args, modes: "DISCUSS, BUILD" })),
607
731
  ])
608
732
  return
609
733
  }
@@ -614,14 +738,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
614
738
  return
615
739
  }
616
740
  workModeControl.setWorkMode(next)
741
+ const label = displayWorkMode(next)
742
+ transcript.pushInfo([c.muted(t("tui.workModeLine", { m: label }))])
743
+ app.showToast(t("tui.workModeLine", { m: label }))
617
744
  return
618
745
  }
619
746
  // /unrestric — full akses tanpa gerbang (jail + bash-guard + sandbox/allowlist).
620
747
  // HIDDEN dari daftar "/" dan /help: operator yang tahu perintahnya yang bisa
621
748
  // memanggil. Berlaku per-sesi, toggle. Gerbang keamanan = kepercayaan operator.
622
749
  if (name === "unrestric" || name === "unrestrict") {
623
- const norm = args.trim().toLowerCase()
624
- const next = norm === "" ? mode !== "unrestricted" : norm === "on" || norm === "1"
750
+ const parsed = parseToggleArg(args)
751
+ if (parsed === "invalid") {
752
+ transcript.pushInfo([c.muted(t("tui.unrestrictedUsage"))])
753
+ return
754
+ }
755
+ const next = parsed === undefined ? mode !== "unrestricted" : parsed
625
756
  if (next) {
626
757
  if (mode !== "unrestricted") {
627
758
  modeBeforeUnrestricted = mode
@@ -629,18 +760,19 @@ export async function runTui(ctx: CliSession): Promise<void> {
629
760
  }
630
761
  mode = "unrestricted"
631
762
  permissions?.setMode("unrestricted")
632
- // WorkMode EXECUTE (BUILD) agar ceiling DISCUSS/PLAN tak menahan tulis.
763
+ // WorkMode EXECUTE (BUILD) agar ceiling DISCUSS tak menahan tulis.
633
764
  workModeControl?.setWorkMode("EXECUTE")
634
765
  app.repaint()
635
766
  transcript.pushInfo([c.warning(`${c.red(glyphs.unlock)} ${t("tui.unrestrictedOn")}`)])
636
767
  return
637
768
  }
769
+ if (mode !== "unrestricted") {
770
+ transcript.pushInfo([c.muted(`${glyphs.lock} ${t("tui.unrestrictedOff", { m: mode })}`)])
771
+ return
772
+ }
638
773
  mode = modeBeforeUnrestricted ?? "auto"
639
- // modeBeforeUnrestricted adalah nilai sebelum /unrestric: auto/ask (via /mode)
640
- // atau allow-all/allowlist (via flag start). Tidak pernah readonly/plan/
641
- // unrestricted — cast jujur ke himpunan yang memang bisa dipegang `mode`.
642
774
  permissions?.setMode(mode as "auto" | "ask" | "allow-all" | "allowlist")
643
- // Pulihkan juga WorkMode semula (DISCUSS/PLAN) agar ceiling read-only
775
+ // Pulihkan juga WorkMode semula (DISCUSS) agar ceiling read-only
644
776
  // kembali berlaku — tanpa ini toggle-off meninggalkan BUILD (tulis bebas).
645
777
  workModeControl?.setWorkMode(workModeBeforeUnrestricted ?? "DISCUSS")
646
778
  modeBeforeUnrestricted = null
@@ -666,73 +798,87 @@ export async function runTui(ctx: CliSession): Promise<void> {
666
798
  const { saveLang } = await import("../src/config.ts")
667
799
  await saveLang(next)
668
800
  } catch {}
801
+ transcript.pushInfo([c.muted(t("tui.langLine", { v: next }))])
802
+ app.showToast(t("tui.langLine", { v: next }))
669
803
  return
670
804
  }
671
- if (name === "compact") {
672
- const next = args === "" ? undefined : args === "on" || args === "1"
673
- ui.setCompactMode(next)
674
- return
675
- }
676
- if (name === "thinking") {
677
- const next = args === "" ? undefined : args === "on" || args === "1"
678
- ui.setReasoningVisible(next)
679
- return
680
- }
681
- if (name === "fold") {
682
- // [Fase 2] /fold = toggle PANEL AKTIVITAS (thinking + grup tool).
683
- // Perilaku lama (minimizeActivity) tetap hidup saat panel off; `/fold`
684
- // sekarang mengontrol panel. i18n key sama (folded/expanded).
685
- const next = args === "" ? undefined : args === "on" || args === "1"
686
- const on = ui.setActivityPanel(next)
687
- transcript.pushInfo([c.muted(t("tui.activityFold", { v: on ? "folded" : "expanded" }))])
805
+ if (name === "compact" || name === "thinking" || name === "fold") {
806
+ const parsed = parseToggleArg(args)
807
+ if (parsed === "invalid") {
808
+ transcript.pushInfo([c.muted(t("tui.toggleUse", { cmd: name }))])
809
+ return
810
+ }
811
+ const toggleLine =
812
+ name === "compact"
813
+ ? t("tui.compactLine", {
814
+ v: t(ui.setCompactMode(parsed) ? "state.compact" : "state.expanded"),
815
+ })
816
+ : name === "thinking"
817
+ ? t("tui.thinkingSet", {
818
+ v: t(ui.setReasoningVisible(parsed) ? "state.expanded" : "state.minimized"),
819
+ })
820
+ : t("tui.activityFold", {
821
+ v: t(ui.setActivityPanel(parsed) ? "state.expanded" : "state.folded"),
822
+ })
823
+ transcript.pushInfo([c.muted(toggleLine)])
688
824
  return
689
825
  }
690
826
  if (name === "expand") {
691
827
  const sections = args ? ctx.expandContent(args) : ctx.expandAllContent()
692
828
  const views = args ? [] : ui.collapsedSectionsSnapshot()
693
- if (!args) ui.clearCollapsedSections()
694
829
  if (!sections.length && !views.length) {
695
- transcript.pushInfo([c.muted(t("tui.expandEmpty"))])
830
+ transcript.pushInfo([
831
+ c.muted(
832
+ args ? t("tui.expandNotFound", { id: sanitizeAnsiLine(args) }) : t("tui.expandEmpty"),
833
+ ),
834
+ ])
696
835
  return
697
836
  }
698
837
  const lines: string[] = []
838
+ const dash = glyphs.hLine.repeat(2)
699
839
  for (const s of sections) {
700
840
  if (s.meta.source === "retention") {
701
841
  lines.push(c.muted(t("tui.expandRetention")))
702
842
  continue
703
843
  }
704
- const label = args ?? s.ref?.toolCallId ?? t("tui.expandContent")
844
+ const label = sanitizeAnsiLine(args ?? s.ref?.toolCallId ?? t("tui.expandContent"))
705
845
  const src = s.meta.source === "durable" ? ` [${t("tui.expandDurable")}]` : ""
706
- lines.push(c.muted(` ── ${label}${src} ──`))
707
- for (const ln of s.text.split("\n")) lines.push(` ${ln}`)
846
+ lines.push(c.muted(` ${dash} ${label}${src} ${dash}`))
847
+ for (const ln of s.text.split("\n")) lines.push(` ${sanitizeAnsiLine(ln)}`)
708
848
  }
709
849
  for (const view of views) {
710
- lines.push(c.muted(` ── ${view.label} ──`))
711
- for (const ln of view.text.split("\n")) lines.push(` ${ln}`)
850
+ lines.push(c.muted(` ${dash} ${sanitizeAnsiLine(view.label)} ${dash}`))
851
+ for (const ln of view.text.split("\n")) lines.push(` ${sanitizeAnsiLine(ln)}`)
712
852
  }
713
- transcript.pushInfo(lines)
853
+ await showCommandOutput(t("out.titleExpand"), lines)
714
854
  return
715
855
  }
716
856
  if (name === "minimize") {
717
- const arg = args.trim().toLowerCase()
718
- let next: boolean | undefined
719
- if (arg === "") next = !(ui.sectionMinimized("tool") && ui.sectionMinimized("answer"))
720
- else if (arg === "on" || arg === "1") next = true
721
- else if (arg === "off" || arg === "0") next = false
722
- else {
857
+ const parsed = parseToggleArg(args)
858
+ if (parsed === "invalid") {
723
859
  transcript.pushInfo([c.muted(t("tui.minUse"))])
724
860
  return
725
861
  }
862
+ const next =
863
+ parsed === undefined
864
+ ? !(ui.sectionMinimized("tool") && ui.sectionMinimized("answer"))
865
+ : parsed
726
866
  ui.setSectionMinimized("tool", next)
727
867
  ui.setSectionMinimized("answer", next)
868
+ transcript.pushInfo([c.muted(t(next ? "tui.sectionsMin" : "tui.sectionsExp"))])
728
869
  return
729
870
  }
730
- if (name === "undo") {
731
- const res = await undoLastCheckpoint(sessionId, cwd)
732
- transcript.pushInfo([res.message, ...res.restoredFiles])
733
- return
734
- }
735
- if (name === "redo") {
871
+ if (name === "undo" || name === "redo") {
872
+ const currentWm = workModeControl ? workModeControl.getWorkMode() : "EXECUTE"
873
+ if (currentWm !== "EXECUTE") {
874
+ transcript.pushInfo([c.muted(t("tui.undoInDiscuss"))])
875
+ return
876
+ }
877
+ if (name === "undo") {
878
+ const res = await undoLastCheckpoint(sessionId, cwd)
879
+ transcript.pushInfo([res.message, ...res.restoredFiles])
880
+ return
881
+ }
736
882
  const res = await redoLastCheckpoint(sessionId, cwd)
737
883
  transcript.pushInfo([res.message, ...res.reappliedFiles])
738
884
  return
@@ -751,22 +897,70 @@ export async function runTui(ctx: CliSession): Promise<void> {
751
897
  return popupBuiltin(`/model${args ? ` ${args}` : ""}`)
752
898
  if (name === "providers" || name === "provider") return popupBuiltin("/provider")
753
899
  if (name === "history") {
754
- const lines = (await loadHistory()).slice(-20)
755
- transcript.pushInfo(lines.length ? lines : [t("tui.historyEmpty")])
900
+ const disk = await loadHistory().catch(() => [])
901
+ const inMem = app.getHistory().filter((h) => h !== "/history")
902
+ const merged: string[] = []
903
+ for (const entry of [...disk, ...inMem]) {
904
+ if (merged[merged.length - 1] !== entry) merged.push(entry)
905
+ }
906
+ const lines = merged.slice(-20)
907
+ await showCommandOutput(t("out.titleHistory"), lines.length ? lines : [t("tui.historyEmpty")])
908
+ return
909
+ }
910
+ if (name === "sessions" || name === "resume")
911
+ return popupBuiltin(`/${name}${args ? ` ${args}` : ""}`)
912
+ if (name === "sync") {
913
+ // Tampilkan progres "Syncing models…" langsung di kotak Layer 2 selama
914
+ // probe jaringan berjalan, lalu transisi ke jendela hasil tanpa kedip.
915
+ app.suspend()
916
+ const paintSyncProgress = () => {
917
+ const cols = process.stdout.columns || 80
918
+ const rows = process.stdout.rows || 24
919
+ if (!canRenderModal(cols, rows)) return
920
+ const w = popupBoxWidth(cols)
921
+ const box = dialogBox(
922
+ {
923
+ title: t("out.titleSync"),
924
+ body: [c.muted(t("cmd.syncing"))],
925
+ minWidth: w,
926
+ maxWidth: w,
927
+ },
928
+ cols,
929
+ rows,
930
+ )
931
+ app.paintRegion(box.lines, box.topRow)
932
+ app.setCursorVisible(false)
933
+ }
934
+ const onResize = () => paintSyncProgress()
935
+ process.stdout.on("resize", onResize)
936
+ let syncLines: string[] = []
937
+ try {
938
+ paintSyncProgress()
939
+ ;({ lines: syncLines } = await runBuiltin("/sync"))
940
+ } finally {
941
+ process.stdout.removeListener("resize", onResize)
942
+ app.clearRegion()
943
+ }
944
+ try {
945
+ const nonBlank = syncLines.filter((l) => l.trim().length > 0)
946
+ const out =
947
+ nonBlank.length > 1 && nonBlank[0]?.trim() === t("cmd.syncing")
948
+ ? nonBlank.slice(1)
949
+ : syncLines
950
+ if (out.length) await showCommandOutput(t("out.titleSync"), out)
951
+ } finally {
952
+ app.resume()
953
+ }
756
954
  return
757
955
  }
758
- if (name === "resume" && !args) return popupBuiltin("/sessions")
759
- if (name === "sessions" && !args) return popupBuiltin("/sessions")
760
-
761
- // Builtin yang bisa membuka popup (/sessions <id> = resume-spawn,
762
- // /model dengan filter) dibungkus suspend; yang murni cetak langsung.
763
- const MODAL = new Set(["model", "provider", "sessions", "resume"])
764
- if (MODAL.has(name)) return popupBuiltin(line)
765
956
  const { lines, shouldExit, handled } = await runBuiltin(line)
766
957
  if (shouldExit) return { quit: true }
767
958
  // handled tanpa cetakan = murni modal (tak ada yang perlu ke transkrip).
768
959
  if (handled) {
769
- if (lines.length) transcript.pushInfo(lines)
960
+ // Readout command (/help full, /status, /context, /sync, /init,
961
+ // /scheduler) tampil sebagai jendela di atas chat, bukan dicetak ke
962
+ // transkrip. Fallback transkrip bila layar tak mampu.
963
+ if (lines.length) await showCommandOutput(commandWindowTitle(line), lines)
770
964
  return
771
965
  }
772
966
  // handleBuiltinCommand tak menangani → skill atau unknown (paritas REPL).
@@ -791,6 +985,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
791
985
  ])
792
986
  return
793
987
  }
988
+ transcript.pushUser(line)
794
989
  await runTurn(await renderSkill(skill, args))
795
990
  }
796
991
 
@@ -847,11 +1042,15 @@ export async function runTui(ctx: CliSession): Promise<void> {
847
1042
  },
848
1043
  toggleCompact: () => {
849
1044
  const compact = ui.setCompactMode()
850
- transcript.pushInfo([c.muted(t("tui.toolCall", { v: compact ? "compact" : "expanded" }))])
1045
+ transcript.pushInfo([
1046
+ c.muted(t("tui.compactLine", { v: t(compact ? "state.compact" : "state.expanded") })),
1047
+ ])
851
1048
  },
852
1049
  toggleReasoning: () => {
853
1050
  const vis = ui.setReasoningVisible()
854
- transcript.pushInfo([c.muted(t("tui.thinkingSet", { v: vis ? "expanded" : "minimized" }))])
1051
+ transcript.pushInfo([
1052
+ c.muted(t("tui.thinkingSet", { v: t(vis ? "state.expanded" : "state.minimized") })),
1053
+ ])
855
1054
  },
856
1055
  }
857
1056
 
@@ -867,11 +1066,14 @@ export async function runTui(ctx: CliSession): Promise<void> {
867
1066
  try {
868
1067
  if (resumedJobs.has(id)) return
869
1068
  resumedJobs.add(id)
1069
+ if (autoResumeEnabled) {
1070
+ transcript.pushInfo([c.muted(t("tui.bgFinished", { id, code: code ?? "?" }))])
1071
+ }
870
1072
  app.repaint()
871
1073
  if (!autoResumeEnabled) return
872
- // Abort-aware: jangan menyela turn berjalan atau memulai saat quitting.
873
- transcript.pushInfo([c.muted(t("tui.bgFinished", { id, code: code ?? "?" }))])
874
- if (abort !== null) return
1074
+ // Abort-aware & modal-aware: jangan menyela turn berjalan atau membuka
1075
+ // turn baru saat popup masih aktif.
1076
+ if (abort !== null || app.isSuspended()) return
875
1077
  void runTurn(t("tui.bgFinishedAuto", { id, code: code ?? "?" })).catch(() => {})
876
1078
  } catch {}
877
1079
  })
@@ -882,6 +1084,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
882
1084
  suspend: () => app.suspend(),
883
1085
  resume: () => app.resume(),
884
1086
  paintRegion: (lines, topRow) => app.paintRegion(lines, topRow),
1087
+ moveCursor: (row, col) => app.moveCursor(row, col),
885
1088
  clearRegion: () => app.clearRegion(),
886
1089
  })
887
1090
  const res = await app.run()