minicode-ai 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/AGENTS.md +45 -0
  2. package/CHANGELOG.md +59 -4
  3. package/PLAN.md +491 -0
  4. package/README.md +2 -2
  5. package/cli/commands/acp.ts +485 -0
  6. package/cli/commands/auth.ts +7 -4
  7. package/cli/commands/config.ts +41 -27
  8. package/cli/commands/exec.ts +33 -12
  9. package/cli/commands/mcp.ts +3 -2
  10. package/cli/commands/memory.ts +1 -1
  11. package/cli/commands/pricing.ts +6 -4
  12. package/cli/commands/providers.ts +18 -8
  13. package/cli/commands/sessions.ts +11 -4
  14. package/cli/commands/skills.ts +3 -3
  15. package/cli/commands/stats.ts +3 -1
  16. package/cli/commands.ts +6 -0
  17. package/cli/index.ts +82 -57
  18. package/cli/model-manager.ts +6 -1
  19. package/cli/router.ts +7 -0
  20. package/cli/setup.ts +341 -5
  21. package/cli/tui.ts +54 -18
  22. package/docs/ARCHITECTURE.html +29 -22
  23. package/docs/CONTROL-PLANE-MAP.md +139 -0
  24. package/docs/HARNESS.md +150 -0
  25. package/docs/PLAN_UIUX_V6.md +209 -0
  26. package/docs/README.md +1 -1
  27. package/docs/SUMMARY.md +52 -0
  28. package/docs/TERMINAL_CONTRACT.md +367 -0
  29. package/docs/UI_RENDER_PIPELINE.md +165 -0
  30. package/docs/USAGE.md +11 -0
  31. package/docs/agents.md +31 -0
  32. package/docs/architecture.md +3 -3
  33. package/docs/choosing-mode.md +34 -0
  34. package/docs/cli.md +130 -0
  35. package/docs/concepts.md +53 -0
  36. package/docs/config-providers.md +87 -0
  37. package/docs/config.md +63 -0
  38. package/docs/contributing.md +79 -0
  39. package/docs/environment.md +95 -0
  40. package/docs/exec.md +73 -0
  41. package/docs/getting-started.md +102 -0
  42. package/docs/glossary.md +37 -0
  43. package/docs/mcp-lsp.md +54 -0
  44. package/docs/memory-sessions.md +63 -0
  45. package/docs/policy-sandbox.md +72 -0
  46. package/docs/pricing-budget.md +49 -0
  47. package/docs/quickstart.md +60 -0
  48. package/docs/repl.md +67 -0
  49. package/docs/security-model.md +95 -0
  50. package/docs/security.md +91 -0
  51. package/docs/skills.md +48 -0
  52. package/docs/terminal.md +79 -0
  53. package/docs/tools.md +123 -0
  54. package/docs/troubleshooting.md +40 -0
  55. package/docs/verify-benchmark.md +58 -0
  56. package/package.json +8 -5
  57. package/src/app/provider-layer.ts +12 -4
  58. package/src/app/session.ts +6 -0
  59. package/src/app/tool-layer.ts +2 -1
  60. package/src/constants.ts +35 -0
  61. package/src/lib/net.ts +6 -1
  62. package/src/lsp/client.ts +41 -8
  63. package/src/mcp/http-transport.ts +52 -15
  64. package/src/mcp/transport.ts +32 -1
  65. package/src/memory/files.ts +6 -5
  66. package/src/policy/allowlist.ts +1 -1
  67. package/src/policy/bash-guard.ts +154 -14
  68. package/src/policy/compaction.ts +57 -3
  69. package/src/policy/context.ts +4 -0
  70. package/src/policy/jail.ts +49 -4
  71. package/src/policy/permission.ts +152 -12
  72. package/src/policy/pricing.ts +12 -9
  73. package/src/presentation/adapter.ts +721 -0
  74. package/src/presentation/events.ts +324 -0
  75. package/src/presentation/label.ts +140 -0
  76. package/src/presentation/model.ts +172 -0
  77. package/src/presentation/reducer.ts +486 -0
  78. package/src/presentation/store.ts +256 -0
  79. package/src/providers/anthropic.ts +22 -4
  80. package/src/providers/detect.ts +2 -1
  81. package/src/providers/router.ts +13 -0
  82. package/src/repo/repomap.ts +2 -29
  83. package/src/session/checkpoint.ts +27 -9
  84. package/src/session/journal.ts +27 -5
  85. package/src/skills/loader.ts +88 -5
  86. package/src/telemetry/trace.ts +36 -15
  87. package/src/tools/ask_user.ts +73 -4
  88. package/src/tools/bash.ts +15 -17
  89. package/src/tools/glob.ts +10 -11
  90. package/src/tools/lsp.ts +3 -56
  91. package/src/tools/memory.ts +13 -12
  92. package/src/tools/task.ts +1 -0
  93. package/src/ui/approval/prompt.ts +14 -6
  94. package/src/ui/assistant/simple.ts +137 -26
  95. package/src/ui/assistant/turn-status.ts +16 -3
  96. package/src/ui/contract.ts +119 -0
  97. package/src/ui/footer.ts +21 -2
  98. package/src/ui/i18n/en.ts +34 -6
  99. package/src/ui/i18n/id.ts +34 -6
  100. package/src/ui/i18n/locale.ts +3 -1
  101. package/src/ui/input/input.ts +51 -4
  102. package/src/ui/input/prompt-engine.ts +46 -4
  103. package/src/ui/render/collapse.ts +13 -13
  104. package/src/ui/render/diff.ts +7 -2
  105. package/src/ui/render/format.ts +16 -8
  106. package/src/ui/render/highlight.ts +7 -3
  107. package/src/ui/render/markdown.ts +5 -1
  108. package/src/ui/render/sanitize.ts +29 -2
  109. package/src/ui/render/table.ts +8 -5
  110. package/src/ui/render/theme.ts +18 -4
  111. package/src/ui/render/width.ts +89 -10
  112. package/src/ui/runtime/motion.ts +16 -0
  113. package/src/ui/runtime/screen.ts +45 -0
  114. package/src/ui/runtime/spinner.ts +50 -4
  115. package/src/ui/runtime/statusline.ts +50 -1
  116. package/src/ui/screens/form.ts +42 -15
  117. package/src/ui/screens/model-manager.ts +26 -18
  118. package/src/ui/screens/picker.ts +47 -23
  119. package/src/ui/screens/provider-manager.ts +18 -12
  120. package/src/ui/screens/wizard.ts +24 -8
  121. package/src/ui/tui/app.ts +233 -27
  122. package/src/ui/tui/transcript.ts +269 -65
  123. package/vendor/minicore/LICENSE +21 -0
  124. package/vendor/minicore/VENDOR.md +6 -3
  125. package/vendor/minicore/package.json +6 -3
  126. package/vendor/minicore/src/core/loop.ts +12 -2
  127. package/vendor/minicore/src/core/snapshot.ts +4 -0
  128. package/vendor/minicore/src/providers/openai-compat.ts +76 -25
package/cli/setup.ts CHANGED
@@ -31,6 +31,19 @@ import {
31
31
  runVerify,
32
32
  runWithSelfHeal,
33
33
  } from "../src/policy/verifier.ts"
34
+ import { createPresentationAdapter, type PresentationAdapter } from "../src/presentation/adapter.ts"
35
+ import type { DomainEvent } from "../src/presentation/events.ts"
36
+ import { createInitialState, type PresentationState } from "../src/presentation/model.ts"
37
+ import {
38
+ createReducerDiagnostics,
39
+ type ReducerDiagnostics,
40
+ reduce,
41
+ } from "../src/presentation/reducer.ts"
42
+ import {
43
+ type ContentEntry,
44
+ type ContentStore,
45
+ createContentStore,
46
+ } from "../src/presentation/store.ts"
34
47
  import {
35
48
  beginTurnSnapshot,
36
49
  reconcileUndoRedoPointer,
@@ -53,12 +66,20 @@ import {
53
66
  summarizeArgs,
54
67
  writeStepTrace,
55
68
  } from "../src/telemetry/trace.ts"
56
- import { setAskTextFn } from "../src/tools/ask_user.ts"
69
+ import { setAskApprovalHook, setAskTextFn } from "../src/tools/ask_user.ts"
57
70
  import { killAllBackgroundJobs } from "../src/tools/bash.ts"
58
71
  import { setSubAgentParentRouting } from "../src/tools/task.ts"
59
72
  import { todoSession } from "../src/tools/todo.ts"
60
73
  import { promptAsk, promptAskText } from "../src/ui/approval/prompt.ts"
61
74
  import { attachSimpleLogger } from "../src/ui/assistant/simple.ts"
75
+ import type {
76
+ UiPresentationActivity,
77
+ UiPresentationEvent,
78
+ UiPresentationSnapshot,
79
+ UiPresentationTurn,
80
+ UiToolStatus,
81
+ UiTurnSummary,
82
+ } from "../src/ui/contract.ts"
62
83
  import { c } from "../src/ui/render/theme.ts"
63
84
  import { runSetupWizard } from "./wizard.ts"
64
85
 
@@ -87,6 +108,11 @@ export interface CliSessionOptions {
87
108
  toolScope?: "full" | "explore"
88
109
  maxSteps?: number
89
110
  contextWindowTokens?: number
111
+ /** F3.2: override keepRecentTurns kompaksi kernel (berapa turn terakhir
112
+ * dipertahankan saat kompaksi). Default = kernel (DEFAULT_KEEP_RECENT_TURNS).
113
+ * Diisi dari env MINICODE_COMPACT_KEEP_TURNS (bilangan >=1, selain itu
114
+ * diabaikan + warn di composition root). */
115
+ keepRecentTurns?: number
90
116
  timeoutMs?: number
91
117
  rateLimiter?: RateLimiter
92
118
  concurrency?: number
@@ -124,6 +150,21 @@ export interface CliSession {
124
150
  /** Kontrol mode permission saat runtime (Shift+Tab / /mode di REPL). */
125
151
  permissions?: PermissionControl
126
152
  close: () => Promise<void>
153
+ /** Fase 3 dark-launch: counter shadow reducer (divergensi harus 0). */
154
+ getShadowDiagnostics: () => {
155
+ divergence: number
156
+ eventsIn: number
157
+ duplicateTerminal: number
158
+ lateEvent: number
159
+ orphanTool: number
160
+ orphanApproval: number
161
+ duplicateTurn: number
162
+ }
163
+ /** Content store untuk /expand [id]. */
164
+ expandContent: (toolCallId: string) => ContentEntry[]
165
+ expandAllContent: () => ContentEntry[]
166
+ getPresentationSnapshot: () => UiPresentationSnapshot
167
+ onPresentationEvent: (handler: (event: UiPresentationEvent) => void) => () => void
127
168
  }
128
169
 
129
170
  export async function createCliSession(opts: CliSessionOptions): Promise<CliSession> {
@@ -147,6 +188,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
147
188
  allowLocalConfig,
148
189
  maxSteps,
149
190
  contextWindowTokens,
191
+ keepRecentTurns,
150
192
  timeoutMs,
151
193
  rateLimiter,
152
194
  sandboxNotice,
@@ -322,6 +364,184 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
322
364
  let sessionEvents: {
323
365
  emit: (e: { type: "provider:extension"; kind: string; data: unknown }) => void
324
366
  } | null = null
367
+ // Adaptor semantik presentasi Fase 1 (AGENT_PRESENTATION_ARCHITECTURE_V2_1):
368
+ // mengamati bus kernel dan memancarkan DomainEvent ke subscriber-nya sendiri.
369
+ // Dual-subscribe dengan sink lama — perilaku user NOL berubah pada Fase 1.
370
+ let presentation: PresentationAdapter | null = null
371
+ // Fase 3 dark-launch: reducer berjalan paralel (shadow) — hasil DIBUANG,
372
+ // tidak mengontrol output. Divergensi = reduce melempar (harusnya 0).
373
+ let shadowState: PresentationState | null = null
374
+ let shadowDiag: ReducerDiagnostics | null = null
375
+ let shadowDivergence = 0
376
+ let shadowUnsub: (() => void) | null = null
377
+ const presentationSubscribers = new Set<(event: UiPresentationEvent) => void>()
378
+ // Content store in-memory untuk query /expand; presentation V2 adalah jalur
379
+ // production setelah cleanup Fase 7.
380
+ let contentStore: ContentStore | null = null
381
+ const getShadowDiagnostics = (): {
382
+ divergence: number
383
+ eventsIn: number
384
+ duplicateTerminal: number
385
+ lateEvent: number
386
+ orphanTool: number
387
+ orphanApproval: number
388
+ duplicateTurn: number
389
+ } => ({
390
+ divergence: shadowDivergence,
391
+ eventsIn: shadowDiag?.eventsIn ?? 0,
392
+ duplicateTerminal: shadowDiag?.duplicateTerminal ?? 0,
393
+ lateEvent: shadowDiag?.lateEvent ?? 0,
394
+ orphanTool: shadowDiag?.orphanTool ?? 0,
395
+ orphanApproval: shadowDiag?.orphanApproval ?? 0,
396
+ duplicateTurn: shadowDiag?.duplicateTurn ?? 0,
397
+ })
398
+ const getPresentationSnapshot = (): UiPresentationSnapshot => {
399
+ if (!shadowState) return { activities: [], turns: [] }
400
+ const activities: UiPresentationActivity[] = [...shadowState.activities.values()].map((a) => ({
401
+ seq: a.seq,
402
+ turnId: a.turnId,
403
+ sessionId: a.sessionId,
404
+ toolCallId: a.toolCallId,
405
+ name: a.identity.name,
406
+ qualified: a.identity.qualified,
407
+ ...(a.target ? { target: a.target } : {}),
408
+ status: a.status as UiToolStatus,
409
+ tsStart: a.tsStart,
410
+ ...(a.tsEnd !== undefined ? { tsEnd: a.tsEnd } : {}),
411
+ ...(a.durationMs !== undefined ? { durationMs: a.durationMs } : {}),
412
+ ...(a.summary ? { summary: a.summary } : {}),
413
+ ...(a.error
414
+ ? {
415
+ error: {
416
+ cause: a.error.cause,
417
+ message: a.error.message,
418
+ ...(a.error.hint ? { hint: a.error.hint } : {}),
419
+ },
420
+ }
421
+ : {}),
422
+ ...(a.denyReason ? { denyReason: a.denyReason } : {}),
423
+ ...(a.receipt
424
+ ? {
425
+ receipt: {
426
+ ...(a.receipt.paths ? { paths: a.receipt.paths } : {}),
427
+ ...(a.receipt.checkpointId ? { checkpointId: a.receipt.checkpointId } : {}),
428
+ ...(a.receipt.stats ? { stats: a.receipt.stats } : {}),
429
+ ...(a.receipt.test ? { test: a.receipt.test } : {}),
430
+ ...(a.receipt.cmd ? { cmd: a.receipt.cmd } : {}),
431
+ },
432
+ }
433
+ : {}),
434
+ ...(a.parentToolCallId ? { parentToolCallId: a.parentToolCallId } : {}),
435
+ ...(a.supersedes ? { supersedes: a.supersedes } : {}),
436
+ ...(a.expandRef
437
+ ? { expandRef: { toolCallId: a.expandRef.toolCallId, idx: a.expandRef.idx } }
438
+ : {}),
439
+ }))
440
+ const turns: UiPresentationTurn[] = [...shadowState.turns.values()].map((turn) => ({
441
+ turnId: turn.turnId,
442
+ status: turn.status,
443
+ ...(turn.summary ? { summary: turn.summary as UiTurnSummary } : {}),
444
+ }))
445
+ return { activities, turns }
446
+ }
447
+ const toPresentationEvent = (event: DomainEvent): UiPresentationEvent | null => {
448
+ switch (event.type) {
449
+ case "turn.started":
450
+ return { type: event.type, seq: event.eventSeq, turnId: event.turnId }
451
+ case "turn.completed":
452
+ return {
453
+ type: event.type,
454
+ seq: event.eventSeq,
455
+ turnId: event.turnId,
456
+ summary: event.summary,
457
+ }
458
+ case "turn.failed":
459
+ return {
460
+ type: event.type,
461
+ seq: event.eventSeq,
462
+ turnId: event.turnId,
463
+ error: event.error.message,
464
+ cause: event.error.cause,
465
+ }
466
+ case "turn.cancelled":
467
+ return {
468
+ type: event.type,
469
+ seq: event.eventSeq,
470
+ turnId: event.turnId,
471
+ reason: event.reason,
472
+ }
473
+ case "tool.started":
474
+ return {
475
+ type: event.type,
476
+ seq: event.eventSeq,
477
+ turnId: event.turnId,
478
+ toolCallId: event.toolCallId,
479
+ name: event.identity.name,
480
+ qualified: event.identity.qualified,
481
+ target: event.argsSummary.target,
482
+ status: "running",
483
+ tsStart: event.ts,
484
+ }
485
+ case "tool.completed":
486
+ case "tool.failed":
487
+ case "tool.denied":
488
+ case "tool.cancelled":
489
+ return {
490
+ type: event.type,
491
+ seq: event.eventSeq,
492
+ turnId: event.turnId,
493
+ toolCallId: event.toolCallId,
494
+ status:
495
+ event.type === "tool.completed"
496
+ ? "completed"
497
+ : event.type === "tool.failed"
498
+ ? "failed"
499
+ : event.type === "tool.denied"
500
+ ? "denied"
501
+ : "cancelled",
502
+ ...("durationMs" in event ? { durationMs: event.durationMs } : {}),
503
+ ...("message" in event ? { message: event.message } : {}),
504
+ ...("cause" in event ? { cause: event.cause } : {}),
505
+ ...("reason" in event ? { reason: event.reason } : {}),
506
+ }
507
+ case "approval.requested":
508
+ return {
509
+ type: event.type,
510
+ seq: event.eventSeq,
511
+ turnId: event.turnId,
512
+ approvalId: event.approvalId,
513
+ toolCallId: event.toolCallId,
514
+ name: event.identity.name,
515
+ qualified: event.identity.qualified,
516
+ target: event.argsSummary.target,
517
+ via: event.via,
518
+ }
519
+ case "approval.settled":
520
+ return {
521
+ type: event.type,
522
+ seq: event.eventSeq,
523
+ turnId: event.turnId,
524
+ approvalId: event.approvalId,
525
+ toolCallId: event.toolCallId,
526
+ outcome: event.outcome,
527
+ }
528
+ default:
529
+ return null
530
+ }
531
+ }
532
+ const onPresentationEvent = (handler: (event: UiPresentationEvent) => void): (() => void) => {
533
+ presentationSubscribers.add(handler)
534
+ return () => presentationSubscribers.delete(handler)
535
+ }
536
+ const publishPresentationEvent = (event: Parameters<typeof toPresentationEvent>[0]): void => {
537
+ const projected = toPresentationEvent(event)
538
+ if (!projected) return
539
+ for (const handler of [...presentationSubscribers]) {
540
+ try {
541
+ handler(projected)
542
+ } catch {}
543
+ }
544
+ }
325
545
  const compaction = process.env.DEEPSEEK_API_KEY
326
546
  ? createLlmCompaction({
327
547
  apiKey: process.env.DEEPSEEK_API_KEY,
@@ -354,6 +574,10 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
354
574
  // View pertanyaan ask_user — composition root meng-inject, tool menolak
355
575
  // jalan tanpanya (fail-closed, sama seperti `ask` pada permission).
356
576
  setAskTextFn(promptAskText)
577
+ // Cermin observability ask_user → adaptor presentasi (perilaku tool utuh).
578
+ setAskApprovalHook((e) => {
579
+ presentation?.publishApproval(e)
580
+ })
357
581
  // Warisan routing sub-agen (audit #14): anak memakai limiter BERSAMA
358
582
  // (satu bucket — tak memicu 429 yang baru dihindari parent) dan menghormati
359
583
  // --provider parent. Model diwarisi live via ToolContext (lihat task.ts).
@@ -382,6 +606,11 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
382
606
  systemExtra: (systemExtra ?? "") + recoveryAppendix,
383
607
  model: modelRef.current,
384
608
  ask: promptAsk,
609
+ // Cermin observability persetujuan → adaptor presentasi. Keputusan gate
610
+ // tetap milik permission handler; hook ini hanya melaporkan.
611
+ onApprovalEvent: (e) => {
612
+ presentation?.publishApproval(e)
613
+ },
385
614
  onPermissions: (ctl) => {
386
615
  permissions = ctl
387
616
  },
@@ -389,6 +618,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
389
618
  ...(resumeTurnCount !== undefined ? { turnCount: resumeTurnCount } : {}),
390
619
  ...(maxSteps ? { maxSteps } : {}),
391
620
  ...(contextWindowTokens ? { contextWindowTokens } : {}),
621
+ ...(keepRecentTurns ? { keepRecentTurns } : {}),
392
622
  ...(safeConcurrency ? { concurrency: safeConcurrency } : {}),
393
623
  ...(safeWriteConcurrency ? { writeConcurrency: safeWriteConcurrency } : {}),
394
624
  timeoutMs: effectiveTimeoutMs === 0 ? Infinity : effectiveTimeoutMs,
@@ -398,13 +628,48 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
398
628
  // Kontrak control-plane (Phase 6): late-binding bus untuk usage kompaksi —
399
629
  // onUsage dipanggil di tengah turn, saat bus sudah hidup.
400
630
  sessionEvents = session.events
631
+ // Content store Fase 4: adapter menaruh konten completed ke store (put
632
+ // selalu jalan); expand(id) di tui di belakang flag.
633
+ contentStore = createContentStore()
634
+ // Adaptor mulai mengamati sejak bus hidup (closure onApprovalEvent di atas
635
+ // aman: check() pertama selalu terjadi setelah wiring ini, saat run()).
636
+ presentation = createPresentationAdapter(session.events, {
637
+ sessionId,
638
+ ...(contentStore ? { contentStore } : {}),
639
+ })
640
+ // Shadow reducer (Fase 3): consume DomainEvent yang sama, hasil dibuang.
641
+ // Shadow reducer berjalan paralel (observability), output TUI/linear memakai
642
+ // proyeksi presentasi yang sama.
643
+ try {
644
+ shadowState = createInitialState(sessionId)
645
+ shadowDiag = createReducerDiagnostics()
646
+ shadowUnsub = presentation.onEvent((e) => {
647
+ try {
648
+ if (shadowState && shadowDiag) reduce(shadowState, e, shadowDiag)
649
+ } catch {
650
+ shadowDivergence++
651
+ }
652
+ publishPresentationEvent(e)
653
+ })
654
+ } catch {
655
+ shadowDivergence++
656
+ }
401
657
 
402
658
  const effectiveInitialModel = modelRef.current ?? cfg.providers[0]?.models[0] ?? "default"
403
659
 
404
660
  // ── Mutation journal wiring (AUDIT #01C): intent di execution:started,
405
661
  // terminal di execution:completed — keduanya post-gate kernel. Total:
406
662
  // kegagalan tulis jurnal tak pernah menggagalkan turn (degraded-loud).
407
- attachMutationJournal(session, { sessionId, cwd })
663
+ // Fase 4: onCommitted → file.changed (receipt paths+journalSeq) ke adapter.
664
+ attachMutationJournal(session, {
665
+ sessionId,
666
+ cwd,
667
+ onCommitted: (info) => {
668
+ try {
669
+ presentation?.noteFileChanged(info)
670
+ } catch {}
671
+ },
672
+ })
408
673
 
409
674
  // ── Shadow checkpoint ──
410
675
  // Repo git: simpan SHA tree pre/post turn (O(delta), tanpa cap file, tidak
@@ -485,6 +750,10 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
485
750
  ...(t0 !== undefined ? { durationMs: Date.now() - t0 } : {}),
486
751
  args: summarizeArgs(call.args),
487
752
  sandbox: process.env.MINICODE_SANDBOX ?? "none",
753
+ // F1.2: token kumulatif sesi saat tool selesai — bahan kurva token.
754
+ // `usage` dideklarasikan di bawah, tapi callback ini baru jalan setelah
755
+ // createCliSession selesai — aman dari TDZ.
756
+ totalTokens: usage.getSession().totalTokens,
488
757
  }).catch(() => {})
489
758
  } catch {}
490
759
  })
@@ -499,6 +768,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
499
768
  tools: s.toolCalls.length,
500
769
  errors: s.results.filter((r) => r.isError).length,
501
770
  sandbox: process.env.MINICODE_SANDBOX ?? "none",
771
+ // F1.2: sama seperti baris tool — kumulatif sesi saat step selesai.
772
+ totalTokens: usage.getSession().totalTokens,
502
773
  }).catch(() => {})
503
774
  } catch {}
504
775
  })
@@ -595,7 +866,22 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
595
866
  },
596
867
  })
597
868
  try {
598
- await session.run(prompt, { model: modelRef.current, signal: ctl.signal })
869
+ try {
870
+ await session.run(prompt, { model: modelRef.current, signal: ctl.signal })
871
+ } catch (e) {
872
+ // Kernel diam pada gagal/abort/timeout (turn:completed hanya sukses):
873
+ // adaptor merekonstruksi turn.failed/cancelled dari sini. Error asli
874
+ // selalu dilempar ulang — observability tak menutupi kegagalan.
875
+ try {
876
+ presentation?.noteRunSettled(e, {
877
+ aborted: ctl.signal.aborted,
878
+ parentAborted: s?.aborted === true,
879
+ })
880
+ } catch {
881
+ // Diagnostik adaptor tak boleh menutupi error turn.
882
+ }
883
+ throw e
884
+ }
599
885
  } finally {
600
886
  stopWatch()
601
887
  if (s) s.removeEventListener("abort", onParentAbort)
@@ -699,9 +985,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
699
985
  // Mode interaktif = TUI fullscreen memiliki layar (kontrak I3: App
700
986
  // penulis tunggal). Printer linier + spinner turn-status DITEKAN agar tak
701
987
  // mengotori alt-screen — state tetap jalan (quiet: rememberTurn untuk
702
- // /copy, bufferSection untuk /expand). One-shot/exec (enterRepl false)
988
+ // /copy, collapsed view untuk /expand). One-shot/exec (enterRepl false)
703
989
  // tetap melukis seperti dulu.
704
- detachSimple = attachSimpleLogger(session.events, { verbose, quiet: enterRepl === true })
990
+ detachSimple = attachSimpleLogger(session.events, {
991
+ verbose,
992
+ quiet: enterRepl === true,
993
+ getSnapshot: getPresentationSnapshot,
994
+ onPresentationEvent,
995
+ })
705
996
  if (enterRepl === true) {
706
997
  turnStatus = null
707
998
  return
@@ -748,6 +1039,19 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
748
1039
  async function close(): Promise<void> {
749
1040
  detachUI()
750
1041
  detachBusDebug()
1042
+ try {
1043
+ shadowUnsub?.()
1044
+ } catch {}
1045
+ shadowUnsub = null
1046
+ presentationSubscribers.clear()
1047
+ shadowState = null
1048
+ shadowDiag = null
1049
+ contentStore = null
1050
+ try {
1051
+ presentation?.dispose()
1052
+ } catch {}
1053
+ presentation = null
1054
+ setAskApprovalHook(undefined)
751
1055
  // background job harus mati bersama CLI — jangan tinggalkan proses yatim
752
1056
  killAllBackgroundJobs()
753
1057
  await mcpCloseAll()
@@ -785,5 +1089,37 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
785
1089
  runPromptWithVerify,
786
1090
  permissions,
787
1091
  close,
1092
+ /** Fase 3 dark-launch: counter shadow reducer (divergensi harus 0). */
1093
+ getShadowDiagnostics,
1094
+ getPresentationSnapshot,
1095
+ onPresentationEvent,
1096
+ expandAllContent: (): ContentEntry[] => contentStore?.expandAll() ?? [],
1097
+ /** Query content store untuk /expand [id] (buka-ulang identik). */
1098
+ expandContent: (toolCallId: string): ContentEntry[] => {
1099
+ if (!contentStore) return []
1100
+ // Durable fallback: sqlite tool result full (hanya output; reasoning
1101
+ // di luar retensi = penanda). Best-effort — miss = tanpa konten.
1102
+ const durable = (id: string): string | undefined => {
1103
+ try {
1104
+ const sess = loadSession(resumeId ?? sessionId, cwd)
1105
+ if (!sess) return undefined
1106
+ for (const m of sess.messages as {
1107
+ role?: string
1108
+ toolCallId?: string
1109
+ content?: unknown
1110
+ }[]) {
1111
+ if (m.role === "tool" && m.toolCallId === id) {
1112
+ return typeof m.content === "string"
1113
+ ? m.content
1114
+ : m.content != null
1115
+ ? JSON.stringify(m.content)
1116
+ : undefined
1117
+ }
1118
+ }
1119
+ } catch {}
1120
+ return undefined
1121
+ }
1122
+ return contentStore.expand(toolCallId, durable)
1123
+ },
788
1124
  }
789
1125
  }
package/cli/tui.ts CHANGED
@@ -23,7 +23,12 @@ import { getLastTurnText, writeClipboardOsc52 } from "../src/ui/assistant/simple
23
23
  import type { UiBus } from "../src/ui/contract.ts"
24
24
  import { t } from "../src/ui/i18n/locale.ts"
25
25
  import { loadHistory } from "../src/ui/input/input.ts"
26
- import { sectionMinimized, setSectionMinimized } from "../src/ui/render/collapse.ts"
26
+ import {
27
+ clearCollapsedSections,
28
+ collapsedSectionsSnapshot,
29
+ sectionMinimized,
30
+ setSectionMinimized,
31
+ } from "../src/ui/render/collapse.ts"
27
32
  import { setCompactMode } from "../src/ui/render/detail.ts"
28
33
  import { formatUsd } from "../src/ui/render/money.ts"
29
34
  import { setReasoningVisible } from "../src/ui/render/reasoning.ts"
@@ -41,7 +46,8 @@ import {
41
46
  import type { CliSession } from "./setup.ts"
42
47
 
43
48
  const MODES = ["auto", "ask", "plan", "allowlist", "allow-all"] as const
44
- const DRIVER_COMMANDS = ["/compact", "/thinking", "/expand", "/minimize"]
49
+ // /expand [id]: tanpa arg = semua entry store; dengan id = satu tool.
50
+ const DRIVER_COMMANDS = ["/compact", "/thinking", "/expand [id]", "/minimize"]
45
51
 
46
52
  function fmtCtx(n: number): string | undefined {
47
53
  if (!Number.isFinite(n) || n <= 0) return undefined
@@ -104,6 +110,10 @@ export async function runTui(ctx: CliSession): Promise<void> {
104
110
  close,
105
111
  } = ctx
106
112
  const { session } = ctx
113
+ const getPresentationSnapshot = () =>
114
+ typeof ctx.getPresentationSnapshot === "function"
115
+ ? ctx.getPresentationSnapshot()
116
+ : { activities: [], turns: [] }
107
117
 
108
118
  let mode: string = permissions?.getMode() ?? permissionMode ?? "auto"
109
119
  if (process.env.MINICODE_COMPACT === undefined) setCompactMode(true)
@@ -118,7 +128,10 @@ export async function runTui(ctx: CliSession): Promise<void> {
118
128
  setConfigLocale((await loadLang().catch(() => undefined)) ?? null)
119
129
  } catch {}
120
130
 
121
- const transcript = new Transcript(session.events as unknown as UiBus)
131
+ const transcript = new Transcript(session.events as unknown as UiBus, {
132
+ getSnapshot: getPresentationSnapshot,
133
+ onPresentationEvent: ctx.onPresentationEvent,
134
+ })
122
135
 
123
136
  const commandCtx: CommandContext = {
124
137
  cwd,
@@ -311,7 +324,9 @@ export async function runTui(ctx: CliSession): Promise<void> {
311
324
  }
312
325
  if (name === "exit" || name === "quit") return { quit: true }
313
326
  if (name === "clear") {
314
- transcript.clear()
327
+ // Reset via App (bukan transcript.clear langsung) agar scrollBack dan
328
+ // basis indikator ikut kembali ke ekor — tanpa ini viewport basi.
329
+ app.clearView()
315
330
  return
316
331
  }
317
332
  if (name === "mode") {
@@ -361,18 +376,28 @@ export async function runTui(ctx: CliSession): Promise<void> {
361
376
  return
362
377
  }
363
378
  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) {
379
+ const sections = args ? ctx.expandContent(args) : ctx.expandAllContent()
380
+ const views = args ? [] : collapsedSectionsSnapshot()
381
+ if (!args) clearCollapsedSections()
382
+ if (!sections.length && !views.length) {
368
383
  transcript.pushInfo([c.muted(t("tui.expandEmpty"))])
369
384
  return
370
385
  }
371
386
  const lines: string[] = []
372
387
  for (const s of sections) {
373
- lines.push(c.muted(` ── ${s.label} ──`))
388
+ if (s.meta.source === "retention") {
389
+ lines.push(c.muted(t("tui.expandRetention")))
390
+ continue
391
+ }
392
+ const label = args ?? s.ref?.toolCallId ?? t("tui.expandContent")
393
+ const src = s.meta.source === "durable" ? ` [${t("tui.expandDurable")}]` : ""
394
+ lines.push(c.muted(` ── ${label}${src} ──`))
374
395
  for (const ln of s.text.split("\n")) lines.push(` ${ln}`)
375
396
  }
397
+ for (const view of views) {
398
+ lines.push(c.muted(` ── ${view.label} ──`))
399
+ for (const ln of view.text.split("\n")) lines.push(` ${ln}`)
400
+ }
376
401
  transcript.pushInfo(lines)
377
402
  return
378
403
  }
@@ -455,15 +480,26 @@ export async function runTui(ctx: CliSession): Promise<void> {
455
480
 
456
481
  const host: TuiHost = {
457
482
  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
- }),
483
+ getStatus: () => {
484
+ const status = {
485
+ footer: {
486
+ mode,
487
+ model: modelRef.current ?? cfg.providers[0]?.models[0] ?? t("tui.noModel"),
488
+ cwd: cwd ?? process.cwd(),
489
+ context: fmtCtx(session.contextTokens),
490
+ },
491
+ busy: abort != null,
492
+ }
493
+ const activities = getPresentationSnapshot().activities
494
+
495
+ return {
496
+ ...status,
497
+ pinnedActivity:
498
+ activities.find(
499
+ (activity) => activity.status === "running" && !activity.parentToolCallId,
500
+ ) ?? activities.find((activity) => activity.status === "running"),
501
+ }
502
+ },
467
503
  listCommands: (prefix) => suggestions(prefix),
468
504
  submit,
469
505
  abort: () => {