minicode-ai 0.26.0 → 0.28.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 (139) hide show
  1. package/cli/args.ts +120 -16
  2. package/cli/commands/acp.ts +38 -28
  3. package/cli/commands/auth.ts +17 -17
  4. package/cli/commands/config.ts +65 -66
  5. package/cli/commands/daemon.ts +44 -16
  6. package/cli/commands/doctor.ts +11 -12
  7. package/cli/commands/exec.ts +35 -73
  8. package/cli/commands/mcp.ts +25 -8
  9. package/cli/commands/memory.ts +16 -24
  10. package/cli/commands/openwork.ts +6 -2
  11. package/cli/commands/pricing.ts +14 -12
  12. package/cli/commands/providers.ts +36 -57
  13. package/cli/commands/sessions.ts +24 -18
  14. package/cli/commands/skills.ts +33 -18
  15. package/cli/commands/stats.ts +15 -30
  16. package/cli/commands.ts +96 -46
  17. package/cli/context-command-run.ts +171 -0
  18. package/cli/context-command.ts +87 -0
  19. package/cli/index.ts +96 -98
  20. package/cli/model-manager.ts +7 -2
  21. package/cli/provider-manager.ts +33 -18
  22. package/cli/router.ts +41 -12
  23. package/cli/setup.ts +246 -123
  24. package/cli/tui.ts +311 -109
  25. package/docs/TERMINAL_CONTRACT.md +254 -69
  26. package/docs/UI_RENDER_PIPELINE.md +9 -1
  27. package/docs/agents.md +2 -2
  28. package/docs/architecture.md +3 -3
  29. package/docs/choosing-mode.md +7 -9
  30. package/docs/cli.md +3 -5
  31. package/docs/config.md +16 -0
  32. package/docs/environment.md +3 -3
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +3 -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 +119 -66
  40. package/src/app/tool-layer.ts +12 -17
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +23 -9
  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/db-path.ts +47 -0
  48. package/src/lib/process-tree.ts +62 -0
  49. package/src/lib/public-http.ts +88 -23
  50. package/src/lib/trusted-exec.ts +48 -1
  51. package/src/lsp/client.ts +62 -17
  52. package/src/mcp/client.ts +85 -38
  53. package/src/mcp/http-transport.ts +28 -16
  54. package/src/mcp/transport.ts +42 -6
  55. package/src/memory/files.ts +164 -134
  56. package/src/memory/vector.ts +371 -420
  57. package/src/policy/approval-binding.ts +122 -45
  58. package/src/policy/bash-guard.ts +18 -7
  59. package/src/policy/compaction.ts +51 -18
  60. package/src/policy/context-window.ts +109 -0
  61. package/src/policy/context.ts +78 -37
  62. package/src/policy/executor.ts +17 -7
  63. package/src/policy/microcompact.ts +4 -3
  64. package/src/policy/no-progress.ts +103 -22
  65. package/src/policy/permission.ts +36 -12
  66. package/src/policy/tool-contract.ts +74 -416
  67. package/src/policy/usage.ts +24 -2
  68. package/src/policy/verifier.ts +50 -2
  69. package/src/policy/work-mode.ts +28 -54
  70. package/src/presentation/adapter.ts +24 -16
  71. package/src/providers/guards.ts +41 -2
  72. package/src/providers/provision.ts +6 -60
  73. package/src/providers/responses.ts +1 -0
  74. package/src/repo/repomap.ts +180 -23
  75. package/src/runtime/execution-journal.ts +4 -29
  76. package/src/sandbox/docker.ts +58 -34
  77. package/src/sandbox/mask.ts +157 -0
  78. package/src/sandbox/os.ts +107 -73
  79. package/src/session/authority.ts +29 -10
  80. package/src/session/context-projection.ts +6 -5
  81. package/src/session/open-work.ts +26 -3
  82. package/src/session/persistence.ts +25 -58
  83. package/src/session/verification.ts +170 -20
  84. package/src/skills/loader.ts +31 -16
  85. package/src/task/production-scheduler.ts +13 -1
  86. package/src/task/store.ts +20 -37
  87. package/src/telemetry/trace.ts +27 -0
  88. package/src/tools/ask_user.ts +1 -13
  89. package/src/tools/bash.ts +27 -92
  90. package/src/tools/code_run.ts +1 -1
  91. package/src/tools/context.ts +133 -0
  92. package/src/tools/delete_file.ts +3 -2
  93. package/src/tools/edit.ts +37 -72
  94. package/src/tools/git.ts +86 -9
  95. package/src/tools/glob.ts +26 -51
  96. package/src/tools/grep.ts +67 -57
  97. package/src/tools/hashline.ts +4 -0
  98. package/src/tools/lsp.ts +11 -8
  99. package/src/tools/mcp_call.ts +9 -6
  100. package/src/tools/memory.ts +56 -33
  101. package/src/tools/move_file.ts +36 -10
  102. package/src/tools/patch.ts +13 -21
  103. package/src/tools/read_file.ts +18 -25
  104. package/src/tools/read_image.ts +35 -33
  105. package/src/tools/submit_result.ts +29 -8
  106. package/src/tools/task.ts +74 -17
  107. package/src/tools/todo.ts +181 -74
  108. package/src/tools/web_fetch.ts +42 -2
  109. package/src/tools/web_search.ts +47 -8
  110. package/src/ui/approval/prompt.ts +206 -47
  111. package/src/ui/assistant/turn-status.ts +14 -5
  112. package/src/ui/footer.ts +4 -4
  113. package/src/ui/i18n/en.ts +59 -23
  114. package/src/ui/i18n/id.ts +88 -51
  115. package/src/ui/input/input.ts +4 -3
  116. package/src/ui/input/prompt-engine.ts +35 -5
  117. package/src/ui/render/activity-panel.ts +4 -2
  118. package/src/ui/render/hint.ts +7 -4
  119. package/src/ui/render/list.ts +32 -0
  120. package/src/ui/render/markdown.ts +6 -3
  121. package/src/ui/render/notice.ts +19 -0
  122. package/src/ui/render/table-grid.ts +7 -8
  123. package/src/ui/render/theme.ts +113 -39
  124. package/src/ui/runtime/screen.ts +74 -10
  125. package/src/ui/runtime/spinner.ts +19 -6
  126. package/src/ui/screens/dialog.ts +19 -1
  127. package/src/ui/screens/form.ts +80 -35
  128. package/src/ui/screens/model-manager.ts +88 -62
  129. package/src/ui/screens/output-window.ts +263 -0
  130. package/src/ui/screens/picker.ts +94 -81
  131. package/src/ui/screens/provider-manager.ts +100 -69
  132. package/src/ui/screens/wizard.ts +117 -28
  133. package/src/ui/tui/app.ts +196 -33
  134. package/src/ui/tui/transcript.ts +154 -25
  135. package/vendor/minicore/src/core/executor.ts +2 -0
  136. package/vendor/minicore/src/core/loop.ts +17 -6
  137. package/vendor/minicore/src/core/session.ts +3 -0
  138. package/vendor/minicore/src/core/tool.ts +1 -0
  139. package/vendor/minicore/src/providers/openai-compat.ts +28 -19
package/cli/tui.ts CHANGED
@@ -37,18 +37,22 @@ 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,
51
54
  DRIVER_HELP_COMMANDS,
55
+ HELP_GROUPS,
52
56
  handleBuiltinCommand,
53
57
  persistModelChoice,
54
58
  suggestSimilar,
@@ -56,19 +60,25 @@ import {
56
60
  import type { CliSession } from "./setup.ts"
57
61
 
58
62
  // [mode-architecture] Approval axis (PermissionMode) = AUTO/ASK; operating axis
59
- // (WorkMode) = DISCUSS/PLAN/BUILD, dikelola terpisah via /work-mode. Nilai
63
+ // (WorkMode) = DISCUSS/BUILD, dikelola terpisah via /work-mode. Nilai
60
64
  // internal tetap lowercase (auto/ask) dan EXECUTE (identitas BUILD).
61
65
  const PERMISSION_MODES = ["auto", "ask"] as const
62
- const WORK_MODE_CYCLE = ["DISCUSS", "PLAN", "EXECUTE"] as const
66
+ const WORK_MODE_CYCLE = ["DISCUSS", "EXECUTE"] as const
63
67
  // /expand [id]: tanpa arg = semua entry store; dengan id = satu tool.
64
68
  const DRIVER_COMMANDS = [
65
69
  "/compact",
66
70
  "/thinking",
67
- "/expand [id]",
71
+ "/expand",
68
72
  "/minimize",
69
73
  "/fold",
70
74
  "/mode",
71
75
  "/work-mode",
76
+ "/lang",
77
+ "/clear",
78
+ "/copy",
79
+ "/history",
80
+ "/undo",
81
+ "/redo",
72
82
  ]
73
83
 
74
84
  function fmtCtx(n: number): string | undefined {
@@ -92,7 +102,11 @@ function fmtCtx(n: number): string | undefined {
92
102
  */
93
103
  function fmtUsageMetrics(ctx: CliSession, used: number): string | undefined {
94
104
  const cost: number | undefined = ctx.usage.getSession().cost
95
- 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?.()
96
110
  const parts: string[] = []
97
111
  if (cost !== undefined && Number.isFinite(cost) && cost > 0) parts.push(formatUsd(cost))
98
112
  if (
@@ -183,7 +197,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
183
197
  // Mode permission sebelum /unrestric diaktifkan — dipakai untuk memulihkan
184
198
  // saat operator menonaktifkannya kembali (toggle, per-sesi).
185
199
  let modeBeforeUnrestricted: string | null = null
186
- let workModeBeforeUnrestricted: "DISCUSS" | "PLAN" | "EXECUTE" | null = null
200
+ let workModeBeforeUnrestricted: "DISCUSS" | "EXECUTE" | null = null
187
201
  if (process.env.MINICODE_COMPACT === undefined) ui.setCompactMode(true)
188
202
  if (process.env.MINICODE_MINIMIZE_TOOL === undefined) ui.setSectionMinimized("tool", true)
189
203
  // Grouping aktivitas tool jadi satu baris (opencode-like): default ON di TUI;
@@ -213,26 +227,36 @@ export async function runTui(ctx: CliSession): Promise<void> {
213
227
  const uiBus = session.events as unknown as UiBus
214
228
  try {
215
229
  liveContextUnsubs.push(
216
- uiBus.on("provider:extension", (e: { kind?: unknown; data?: unknown }) => {
217
- if (e?.kind !== "context-window") return
218
- const d = e.data as { usedTokens?: unknown } | undefined
219
- if (typeof d?.usedTokens === "number") liveContextTokens = d.usedTokens
220
- }),
221
- )
222
- } catch {}
223
- try {
224
- liveContextUnsubs.push(
225
- uiBus.on("turn:started", () => {
226
- liveContextTokens = undefined
227
- }),
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
+ ),
228
239
  )
229
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
+ }
230
251
  try {
231
- liveContextUnsubs.push(
232
- uiBus.on("turn:completed", () => {
233
- liveContextTokens = undefined
234
- }),
235
- )
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)
236
260
  } catch {}
237
261
  const getContextTokens = (): number => {
238
262
  // Live (per-step) menang saat turn berjalan; idle → committed (cache).
@@ -321,14 +345,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
321
345
  }
322
346
  : {}),
323
347
  get currentModel() {
324
- 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
325
352
  },
326
353
  set currentModel(v) {
327
354
  modelRef.current = v
328
355
  },
329
356
  usage,
330
357
  skills: allLoadedSkills,
331
- 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
+ },
332
363
  // P1.2: dua dimensi selalu terbaca live di /status — bukan snapshot boot.
333
364
  // [mode-architecture] /status memakai nilai PRODUK (BUILD/AUTO/ASK).
334
365
  get workMode() {
@@ -337,12 +368,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
337
368
  get permissionMode() {
338
369
  return (permissions?.getMode() ?? mode).toUpperCase()
339
370
  },
340
- 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
+ },
341
379
  setModelOverride: (m) => persistModelChoice(m, modelRef),
342
380
  // Spawn anak stdio-inherit (/sessions <id>): keluar alt-screen + cooked
343
- // mode DULU — anak mewarisi terminal apa adanya. Tanpa ini: double-ENTER,
344
- // EXIT anak merobek buffer parent, stdin mentah macet. Gagal-di-kode-lama.
345
- 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
+ },
346
386
  getContextTokens: () => session.contextTokens,
347
387
  budgetState: () => {
348
388
  const u = usage.getSession()
@@ -390,13 +430,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
390
430
  workModeControl.setWorkMode(next)
391
431
  }
392
432
 
393
- // Shift+Tab: toggle PermissionMode (AUTO ↔ ASK). Tidak ada privilege change
394
- // 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.
395
441
  const togglePermissionMode = (): void => {
396
442
  if (!permissions) return
443
+ const wasUnrestricted = mode === "unrestricted"
397
444
  const next = permissions.getMode() === "ask" ? "auto" : "ask"
398
445
  permissions.setMode(next)
399
446
  mode = next
447
+ clearUnrestrictedBackup(wasUnrestricted)
400
448
  }
401
449
 
402
450
  async function runBuiltin(
@@ -422,9 +470,71 @@ export async function runTui(ctx: CliSession): Promise<void> {
422
470
  return { lines, shouldExit, handled }
423
471
  }
424
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
+
425
533
  async function delegateBuiltin(q: string, recordOutput = true): Promise<{ quit?: boolean }> {
426
534
  const { lines, shouldExit } = await runBuiltin(q, recordOutput)
427
- if (recordOutput && lines.length) transcript.pushInfo(lines)
535
+ if (recordOutput && lines.length) {
536
+ await showCommandOutput(commandWindowTitle(q), lines)
537
+ }
428
538
  return shouldExit ? { quit: true } : {}
429
539
  }
430
540
 
@@ -436,9 +546,13 @@ export async function runTui(ctx: CliSession): Promise<void> {
436
546
  * kembali; transkrip tidak mengarsipkan pilihan UI yang sudah selesai.
437
547
  */
438
548
  async function popupBuiltin(q: string): Promise<{ quit?: boolean }> {
549
+ let lines: string[] = []
550
+ let shouldExit = false
439
551
  app.suspend()
440
552
  try {
441
- return await delegateBuiltin(q, false)
553
+ const res = await runBuiltin(q, true)
554
+ lines = res.lines
555
+ shouldExit = res.shouldExit
442
556
  } catch (e) {
443
557
  // Spawn anak gagal (terminal sudah dilepas onBeforeSpawn): hidupkan
444
558
  // kembali atau keluar bersih — jangan biarkan TUI mati tanpa layar.
@@ -447,6 +561,12 @@ export async function runTui(ctx: CliSession): Promise<void> {
447
561
  } finally {
448
562
  app.resume()
449
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 } : {}
450
570
  }
451
571
 
452
572
  async function runTurn(prompt: string): Promise<void> {
@@ -492,28 +612,26 @@ export async function runTui(ctx: CliSession): Promise<void> {
492
612
  ) {
493
613
  warned80 = true
494
614
  transcript.pushInfo([
495
- 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) })),
496
616
  ])
497
617
  }
498
618
  }
499
619
 
500
620
  /**
501
- * /help ringkas (≤6 baris): daftar perintah muat viewport tanpa
502
- * 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).
503
623
  */
504
- function helpConcise(): void {
624
+ async function helpConcise(): Promise<void> {
505
625
  // Grup kurasi (sengaja bukan dump flat dari registry): label + baris pendek
506
- // per kategori supaya /help mudah dipindai. Daftar tetap 1:1 dengan command
507
- // yang ditangani di `submit` (bila ada command baru, tambahkan ke grup yang
508
- // tepat di sini). Tab completion tetap diturunkan dari registry (suggestions).
509
- const group = (label: string, cmds: string): string => ` ${label.padEnd(9)}${cmds}`
510
- transcript.pushInfo([
626
+ // per kategori supaya /help mudah dipindai. Sumber daftarnya SATU —
627
+ // `HELP_GROUPS` di `cli/commands.ts` — karena sebelumnya grup di sini dan
628
+ // grup di /help lengkap terpelihara terpisah: menambah perintah ke satu sisi
629
+ // meninggalkan sisi lain basi (persis yang terjadi pada `/context`).
630
+ const group = (label: string, names: readonly string[]): string =>
631
+ ` ${label.padEnd(9)}${names.map((n) => `/${n}`).join(" ")}`
632
+ await showCommandOutput(t("out.titleHelp"), [
511
633
  t("help.cHead"),
512
- group(t("help.gSession"), "/status /sessions /history /clear /copy /init /exit"),
513
- group(t("help.gModel"), "/model /provider /sync"),
514
- group(t("help.gMode"), "/mode /work-mode /undo /redo /lang"),
515
- group(t("help.gView"), "/compact /thinking /expand /minimize /fold"),
516
- group(t("help.gTask"), "/scheduler"),
634
+ ...HELP_GROUPS.map((g) => group(t(g.key), g.names)),
517
635
  t("help.cKeys"),
518
636
  t("help.cMore"),
519
637
  ])
@@ -563,11 +681,11 @@ export async function runTui(ctx: CliSession): Promise<void> {
563
681
  const args = spaceIdx === -1 ? "" : line.slice(spaceIdx + 1).trim()
564
682
 
565
683
  if (name === "") {
566
- helpConcise()
684
+ await helpConcise()
567
685
  return
568
686
  }
569
687
  if (name === "help" && !args) {
570
- helpConcise()
688
+ await helpConcise()
571
689
  return
572
690
  }
573
691
  if (name === "exit" || name === "quit") return { quit: true }
@@ -585,11 +703,16 @@ export async function runTui(ctx: CliSession): Promise<void> {
585
703
  transcript.pushInfo([c.muted(t("tui.unknownMode", { a: args, modes: "AUTO, ASK" }))])
586
704
  return
587
705
  }
706
+ const wasUnrestricted = mode === "unrestricted"
588
707
  mode = norm
589
708
  permissions?.setMode(norm as (typeof PERMISSION_MODES)[number])
709
+ clearUnrestrictedBackup(wasUnrestricted)
590
710
  } else {
591
711
  togglePermissionMode()
592
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 }))
593
716
  return
594
717
  }
595
718
  // [mode-architecture] /work-mode = WorkMode (operating mode) SAJA.
@@ -604,7 +727,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
604
727
  const next = parseWorkModeValue(args)
605
728
  if (!next) {
606
729
  transcript.pushInfo([
607
- c.muted(t("tui.workModeUnknown", { a: args, modes: "DISCUSS, PLAN, BUILD" })),
730
+ c.muted(t("tui.workModeUnknown", { a: args, modes: "DISCUSS, BUILD" })),
608
731
  ])
609
732
  return
610
733
  }
@@ -615,14 +738,21 @@ export async function runTui(ctx: CliSession): Promise<void> {
615
738
  return
616
739
  }
617
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 }))
618
744
  return
619
745
  }
620
746
  // /unrestric — full akses tanpa gerbang (jail + bash-guard + sandbox/allowlist).
621
747
  // HIDDEN dari daftar "/" dan /help: operator yang tahu perintahnya yang bisa
622
748
  // memanggil. Berlaku per-sesi, toggle. Gerbang keamanan = kepercayaan operator.
623
749
  if (name === "unrestric" || name === "unrestrict") {
624
- const norm = args.trim().toLowerCase()
625
- 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
626
756
  if (next) {
627
757
  if (mode !== "unrestricted") {
628
758
  modeBeforeUnrestricted = mode
@@ -630,18 +760,19 @@ export async function runTui(ctx: CliSession): Promise<void> {
630
760
  }
631
761
  mode = "unrestricted"
632
762
  permissions?.setMode("unrestricted")
633
- // WorkMode EXECUTE (BUILD) agar ceiling DISCUSS/PLAN tak menahan tulis.
763
+ // WorkMode EXECUTE (BUILD) agar ceiling DISCUSS tak menahan tulis.
634
764
  workModeControl?.setWorkMode("EXECUTE")
635
765
  app.repaint()
636
766
  transcript.pushInfo([c.warning(`${c.red(glyphs.unlock)} ${t("tui.unrestrictedOn")}`)])
637
767
  return
638
768
  }
769
+ if (mode !== "unrestricted") {
770
+ transcript.pushInfo([c.muted(`${glyphs.lock} ${t("tui.unrestrictedOff", { m: mode })}`)])
771
+ return
772
+ }
639
773
  mode = modeBeforeUnrestricted ?? "auto"
640
- // modeBeforeUnrestricted adalah nilai sebelum /unrestric: auto/ask (via /mode)
641
- // atau allow-all/allowlist (via flag start). Tidak pernah readonly/plan/
642
- // unrestricted — cast jujur ke himpunan yang memang bisa dipegang `mode`.
643
774
  permissions?.setMode(mode as "auto" | "ask" | "allow-all" | "allowlist")
644
- // Pulihkan juga WorkMode semula (DISCUSS/PLAN) agar ceiling read-only
775
+ // Pulihkan juga WorkMode semula (DISCUSS) agar ceiling read-only
645
776
  // kembali berlaku — tanpa ini toggle-off meninggalkan BUILD (tulis bebas).
646
777
  workModeControl?.setWorkMode(workModeBeforeUnrestricted ?? "DISCUSS")
647
778
  modeBeforeUnrestricted = null
@@ -667,73 +798,87 @@ export async function runTui(ctx: CliSession): Promise<void> {
667
798
  const { saveLang } = await import("../src/config.ts")
668
799
  await saveLang(next)
669
800
  } catch {}
801
+ transcript.pushInfo([c.muted(t("tui.langLine", { v: next }))])
802
+ app.showToast(t("tui.langLine", { v: next }))
670
803
  return
671
804
  }
672
- if (name === "compact") {
673
- const next = args === "" ? undefined : args === "on" || args === "1"
674
- ui.setCompactMode(next)
675
- return
676
- }
677
- if (name === "thinking") {
678
- const next = args === "" ? undefined : args === "on" || args === "1"
679
- ui.setReasoningVisible(next)
680
- return
681
- }
682
- if (name === "fold") {
683
- // [Fase 2] /fold = toggle PANEL AKTIVITAS (thinking + grup tool).
684
- // Perilaku lama (minimizeActivity) tetap hidup saat panel off; `/fold`
685
- // sekarang mengontrol panel. i18n key sama (folded/expanded).
686
- const next = args === "" ? undefined : args === "on" || args === "1"
687
- const on = ui.setActivityPanel(next)
688
- 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)])
689
824
  return
690
825
  }
691
826
  if (name === "expand") {
692
827
  const sections = args ? ctx.expandContent(args) : ctx.expandAllContent()
693
828
  const views = args ? [] : ui.collapsedSectionsSnapshot()
694
- if (!args) ui.clearCollapsedSections()
695
829
  if (!sections.length && !views.length) {
696
- 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
+ ])
697
835
  return
698
836
  }
699
837
  const lines: string[] = []
838
+ const dash = glyphs.hLine.repeat(2)
700
839
  for (const s of sections) {
701
840
  if (s.meta.source === "retention") {
702
841
  lines.push(c.muted(t("tui.expandRetention")))
703
842
  continue
704
843
  }
705
- const label = args ?? s.ref?.toolCallId ?? t("tui.expandContent")
844
+ const label = sanitizeAnsiLine(args ?? s.ref?.toolCallId ?? t("tui.expandContent"))
706
845
  const src = s.meta.source === "durable" ? ` [${t("tui.expandDurable")}]` : ""
707
- lines.push(c.muted(` ── ${label}${src} ──`))
708
- 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)}`)
709
848
  }
710
849
  for (const view of views) {
711
- lines.push(c.muted(` ── ${view.label} ──`))
712
- 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)}`)
713
852
  }
714
- transcript.pushInfo(lines)
853
+ await showCommandOutput(t("out.titleExpand"), lines)
715
854
  return
716
855
  }
717
856
  if (name === "minimize") {
718
- const arg = args.trim().toLowerCase()
719
- let next: boolean | undefined
720
- if (arg === "") next = !(ui.sectionMinimized("tool") && ui.sectionMinimized("answer"))
721
- else if (arg === "on" || arg === "1") next = true
722
- else if (arg === "off" || arg === "0") next = false
723
- else {
857
+ const parsed = parseToggleArg(args)
858
+ if (parsed === "invalid") {
724
859
  transcript.pushInfo([c.muted(t("tui.minUse"))])
725
860
  return
726
861
  }
862
+ const next =
863
+ parsed === undefined
864
+ ? !(ui.sectionMinimized("tool") && ui.sectionMinimized("answer"))
865
+ : parsed
727
866
  ui.setSectionMinimized("tool", next)
728
867
  ui.setSectionMinimized("answer", next)
868
+ transcript.pushInfo([c.muted(t(next ? "tui.sectionsMin" : "tui.sectionsExp"))])
729
869
  return
730
870
  }
731
- if (name === "undo") {
732
- const res = await undoLastCheckpoint(sessionId, cwd)
733
- transcript.pushInfo([res.message, ...res.restoredFiles])
734
- return
735
- }
736
- 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
+ }
737
882
  const res = await redoLastCheckpoint(sessionId, cwd)
738
883
  transcript.pushInfo([res.message, ...res.reappliedFiles])
739
884
  return
@@ -752,22 +897,70 @@ export async function runTui(ctx: CliSession): Promise<void> {
752
897
  return popupBuiltin(`/model${args ? ` ${args}` : ""}`)
753
898
  if (name === "providers" || name === "provider") return popupBuiltin("/provider")
754
899
  if (name === "history") {
755
- const lines = (await loadHistory()).slice(-20)
756
- 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
+ }
757
954
  return
758
955
  }
759
- if (name === "resume" && !args) return popupBuiltin("/sessions")
760
- if (name === "sessions" && !args) return popupBuiltin("/sessions")
761
-
762
- // Builtin yang bisa membuka popup (/sessions <id> = resume-spawn,
763
- // /model dengan filter) dibungkus suspend; yang murni cetak langsung.
764
- const MODAL = new Set(["model", "provider", "sessions", "resume"])
765
- if (MODAL.has(name)) return popupBuiltin(line)
766
956
  const { lines, shouldExit, handled } = await runBuiltin(line)
767
957
  if (shouldExit) return { quit: true }
768
958
  // handled tanpa cetakan = murni modal (tak ada yang perlu ke transkrip).
769
959
  if (handled) {
770
- 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)
771
964
  return
772
965
  }
773
966
  // handleBuiltinCommand tak menangani → skill atau unknown (paritas REPL).
@@ -792,6 +985,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
792
985
  ])
793
986
  return
794
987
  }
988
+ transcript.pushUser(line)
795
989
  await runTurn(await renderSkill(skill, args))
796
990
  }
797
991
 
@@ -848,11 +1042,15 @@ export async function runTui(ctx: CliSession): Promise<void> {
848
1042
  },
849
1043
  toggleCompact: () => {
850
1044
  const compact = ui.setCompactMode()
851
- 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
+ ])
852
1048
  },
853
1049
  toggleReasoning: () => {
854
1050
  const vis = ui.setReasoningVisible()
855
- 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
+ ])
856
1054
  },
857
1055
  }
858
1056
 
@@ -868,11 +1066,14 @@ export async function runTui(ctx: CliSession): Promise<void> {
868
1066
  try {
869
1067
  if (resumedJobs.has(id)) return
870
1068
  resumedJobs.add(id)
1069
+ if (autoResumeEnabled) {
1070
+ transcript.pushInfo([c.muted(t("tui.bgFinished", { id, code: code ?? "?" }))])
1071
+ }
871
1072
  app.repaint()
872
1073
  if (!autoResumeEnabled) return
873
- // Abort-aware: jangan menyela turn berjalan atau memulai saat quitting.
874
- transcript.pushInfo([c.muted(t("tui.bgFinished", { id, code: code ?? "?" }))])
875
- 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
876
1077
  void runTurn(t("tui.bgFinishedAuto", { id, code: code ?? "?" })).catch(() => {})
877
1078
  } catch {}
878
1079
  })
@@ -883,6 +1084,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
883
1084
  suspend: () => app.suspend(),
884
1085
  resume: () => app.resume(),
885
1086
  paintRegion: (lines, topRow) => app.paintRegion(lines, topRow),
1087
+ moveCursor: (row, col) => app.moveCursor(row, col),
886
1088
  clearRegion: () => app.clearRegion(),
887
1089
  })
888
1090
  const res = await app.run()