minicode-ai 0.13.0 → 0.14.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 (83) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -0
  4. package/cli/args.ts +50 -2
  5. package/cli/commands/acp.ts +18 -3
  6. package/cli/commands/daemon.ts +114 -19
  7. package/cli/commands/exec.ts +95 -7
  8. package/cli/commands/mcp.ts +66 -5
  9. package/cli/commands/memory.ts +46 -14
  10. package/cli/commands.ts +5 -0
  11. package/cli/index.ts +30 -5
  12. package/cli/minicode.js +6 -0
  13. package/cli/setup.ts +365 -24
  14. package/cli/tui.ts +72 -27
  15. package/docs/TERMINAL_CONTRACT.md +91 -24
  16. package/docs/agents.md +2 -2
  17. package/docs/cli.md +1 -0
  18. package/docs/environment.md +1 -0
  19. package/docs/memory-sessions.md +5 -0
  20. package/package.json +3 -2
  21. package/src/app/session.ts +153 -35
  22. package/src/app/tool-layer.ts +67 -61
  23. package/src/daemon/approvals.ts +25 -1
  24. package/src/daemon/client.ts +51 -1
  25. package/src/daemon/control.ts +8 -0
  26. package/src/daemon/protocol.ts +47 -1
  27. package/src/daemon/server.ts +45 -9
  28. package/src/daemon/subscription.ts +25 -1
  29. package/src/daemon/telemetry.ts +4 -0
  30. package/src/hooks/run.ts +5 -1
  31. package/src/mcp/client.ts +349 -90
  32. package/src/mcp/http-transport.ts +7 -0
  33. package/src/mcp/transport.ts +5 -0
  34. package/src/memory/files.ts +69 -3
  35. package/src/memory/vector.ts +556 -160
  36. package/src/policy/approval-binding.ts +199 -0
  37. package/src/policy/context.ts +20 -1
  38. package/src/policy/executor.ts +44 -5
  39. package/src/policy/permission.ts +243 -26
  40. package/src/policy/tool-contract.ts +77 -0
  41. package/src/policy/usage.ts +3 -1
  42. package/src/policy/work-mode.ts +49 -1
  43. package/src/presentation/adapter.ts +157 -7
  44. package/src/presentation/events.ts +173 -1
  45. package/src/presentation/model.ts +37 -0
  46. package/src/presentation/projection.ts +107 -18
  47. package/src/presentation/reducer.ts +134 -10
  48. package/src/sandbox/os.ts +18 -1
  49. package/src/session/persistence.ts +153 -11
  50. package/src/task/store.ts +43 -3
  51. package/src/tools/memory.ts +70 -10
  52. package/src/tools/task.ts +7 -1
  53. package/src/tools/todo.ts +14 -4
  54. package/src/ui/approval/prompt.ts +52 -7
  55. package/src/ui/assistant/simple.ts +160 -57
  56. package/src/ui/contract.ts +46 -0
  57. package/src/ui/footer.ts +14 -5
  58. package/src/ui/i18n/en.ts +9 -0
  59. package/src/ui/i18n/id.ts +9 -0
  60. package/src/ui/render/collapse.ts +24 -52
  61. package/src/ui/render/detail.ts +14 -9
  62. package/src/ui/render/errors.ts +8 -0
  63. package/src/ui/render/reasoning.ts +13 -8
  64. package/src/ui/session-state.ts +243 -0
  65. package/src/ui/tui/app.ts +7 -3
  66. package/src/ui/tui/transcript.ts +271 -30
  67. package/vendor/minicore/src/core/budget.ts +25 -25
  68. package/vendor/minicore/src/core/compact.ts +75 -75
  69. package/vendor/minicore/src/core/errors.ts +59 -59
  70. package/vendor/minicore/src/core/events.ts +73 -73
  71. package/vendor/minicore/src/core/executor.ts +139 -139
  72. package/vendor/minicore/src/core/history.ts +31 -31
  73. package/vendor/minicore/src/core/index.ts +41 -41
  74. package/vendor/minicore/src/core/loop.ts +355 -355
  75. package/vendor/minicore/src/core/permission.ts +22 -22
  76. package/vendor/minicore/src/core/provider.ts +39 -39
  77. package/vendor/minicore/src/core/recovery.ts +35 -35
  78. package/vendor/minicore/src/core/session.ts +327 -327
  79. package/vendor/minicore/src/core/snapshot.ts +146 -146
  80. package/vendor/minicore/src/core/tokens.ts +107 -107
  81. package/vendor/minicore/src/core/tool.ts +115 -115
  82. package/vendor/minicore/src/core/types.ts +50 -50
  83. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
@@ -10,6 +10,7 @@
10
10
  import type {
11
11
  PresentationPolicy,
12
12
  UiBus,
13
+ UiPresentationActivity,
13
14
  UiPresentationEvent,
14
15
  UiPresentationSnapshot,
15
16
  UiToolStatus,
@@ -17,11 +18,11 @@ import type {
17
18
  import { t } from "../i18n/locale.ts"
18
19
  import { parseFence, renderInline } from "../render/markdown.ts"
19
20
  import { type MarkdownTable, parseMarkdownBlocks } from "../render/markdown-table.ts"
20
- import { reasoning } from "../render/reasoning.ts"
21
21
  import { sanitizeAnsi, sanitizeAnsiLine, stripSgr } from "../render/sanitize.ts"
22
22
  import { renderMarkdownTable } from "../render/table-grid.ts"
23
23
  import { c, glyphs } from "../render/theme.ts"
24
24
  import { chunkByWidth, displayWidth, truncateToWidth } from "../render/width.ts"
25
+ import { defaultUiState, type UiSessionState } from "../session-state.ts"
25
26
 
26
27
  /** Cap memori: baris logis tertua dibuang diam-diam (kontrak I12). */
27
28
  export const TRANSCRIPT_CAP = 5000
@@ -70,6 +71,12 @@ export interface TranscriptOptions {
70
71
  /** Kebijakan kanonik dari composition root; absen = logika inline legacy. */
71
72
  policy?: PresentationPolicy
72
73
  maxPendingChars?: number
74
+ /**
75
+ * [Area A · PROMPT 06] State UI milik SESI ini (visibility reasoning).
76
+ * Absen = instance default modul. Permukaan produksi wajib mengoper state
77
+ * sesinya supaya dua sesi dalam satu proses tak saling menimpa.
78
+ */
79
+ uiState?: UiSessionState
73
80
  }
74
81
 
75
82
  export interface TranscriptPoint {
@@ -93,6 +100,19 @@ export interface TranscriptViewport {
93
100
  totalRows: number
94
101
  }
95
102
 
103
+ /** P2.2: hasil proyeksi satu baris logis + input yang memengaruhinya. */
104
+ interface ProjectedLineCache {
105
+ width: number
106
+ id: number
107
+ raw: string
108
+ assistant: boolean
109
+ source: string
110
+ prefix: string
111
+ table: MarkdownTable | null
112
+ fenceState: FenceState
113
+ rows: TranscriptRow[]
114
+ }
115
+
96
116
  function formatElapsed(ms: number): string {
97
117
  const seconds = Math.max(0, Math.floor(ms / 1000))
98
118
  if (seconds < 60) return `${seconds}s`
@@ -141,6 +161,13 @@ function offsetAtColumn(text: string, start: number, end: number, column: number
141
161
  export class Transcript {
142
162
  private lines: string[] = []
143
163
  private tables: (MarkdownTable | null)[] = []
164
+ /**
165
+ * P2.2: cache proyeksi PER BARIS logis. Transkrip append-only, jadi baris
166
+ * lama tidak perlu di-wrap/markdown ulang setiap frame. Cache di-key oleh
167
+ * semua input yang memengaruhi hasil (width, teks, source, prefix, tabel,
168
+ * fence state) dan dibuang saat eviction (index bergeser) atau clear.
169
+ */
170
+ private rowCache = new Map<number, ProjectedLineCache>()
144
171
  private ids: number[] = []
145
172
  private sourcePrefixes: string[] = []
146
173
  private sourceTexts = new Map<number, string>()
@@ -163,6 +190,8 @@ export class Transcript {
163
190
  private hasEvictMarker = false
164
191
  private getSnapshot: (() => UiPresentationSnapshot | null) | undefined
165
192
  private policy: PresentationPolicy | undefined
193
+ // [Area A · PROMPT 06] State UI sesi ini; default = instance modul.
194
+ private uiState: UiSessionState
166
195
  private presentationUnsub: (() => void) | null = null
167
196
  private presentedTerminals = new Set<string>()
168
197
  private presentedVerifications = new Set<string>()
@@ -172,6 +201,7 @@ export class Transcript {
172
201
  constructor(bus: UiBus, opts: TranscriptOptions = {}) {
173
202
  this.getSnapshot = opts.getSnapshot
174
203
  this.policy = opts.policy
204
+ this.uiState = opts.uiState ?? defaultUiState
175
205
  this.maxPendingChars = Math.max(1, opts.maxPendingChars ?? TRANSCRIPT_TEXT_MAX_CHARS)
176
206
  // Gagal subscribe = transcript mati total; biarkan throw (fail-closed).
177
207
  this.unsubs = [
@@ -224,7 +254,7 @@ export class Transcript {
224
254
  const text = (e.data as { text?: string } | null)?.text ?? ""
225
255
  if (!text) return
226
256
  const clean = sanitizeAnsi(text)
227
- if (reasoning.visible) {
257
+ if (this.uiState.reasoningVisible) {
228
258
  // Expanded: alir redup per baris (line-buffered, ekor hidup).
229
259
  this.thinkingTail += clean
230
260
  const parts = this.thinkingTail.split("\n")
@@ -291,6 +321,7 @@ export class Transcript {
291
321
  /** Kosongkan transkrip (`/clear`): viewport kembali ke layar kosong. */
292
322
  clear(): void {
293
323
  this.lines = []
324
+ this.rowCache.clear()
294
325
  this.tables = []
295
326
  this.ids = []
296
327
  this.sourcePrefixes = []
@@ -446,25 +477,43 @@ export class Transcript {
446
477
  const rows: TranscriptRow[] = []
447
478
  const committedFence = this.fenceTracker()
448
479
  for (let i = 0; i < this.lines.length; i++) {
449
- const table = this.tables[i]
480
+ const table = this.tables[i] ?? null
450
481
  const id = this.ids[i] ?? -1
451
482
  const raw = this.lines[i] ?? ""
452
483
  const assistant = this.meta[i]?.kind === "assistant"
453
484
  const fenceState = assistant ? committedFence(raw) : "outside"
454
- if (table) rows.push(...this.projectTable(table, id, w))
455
- else
456
- rows.push(
457
- ...this.projectText(
458
- raw,
459
- this.sourceTexts.get(id) ?? "",
460
- id,
461
- w,
462
- true,
463
- this.sourcePrefixes[i] ?? "",
464
- assistant,
465
- fenceState,
466
- ),
467
- )
485
+ const source = this.sourceTexts.get(id) ?? ""
486
+ const prefix = this.sourcePrefixes[i] ?? ""
487
+ const cached = this.rowCache.get(i)
488
+ if (
489
+ cached &&
490
+ cached.width === w &&
491
+ cached.id === id &&
492
+ cached.raw === raw &&
493
+ cached.assistant === assistant &&
494
+ cached.source === source &&
495
+ cached.prefix === prefix &&
496
+ cached.table === table &&
497
+ cached.fenceState === fenceState
498
+ ) {
499
+ rows.push(...cached.rows)
500
+ continue
501
+ }
502
+ const produced = table
503
+ ? this.projectTable(table, id, w)
504
+ : this.projectText(raw, source, id, w, true, prefix, assistant, fenceState)
505
+ this.rowCache.set(i, {
506
+ width: w,
507
+ id,
508
+ raw,
509
+ assistant,
510
+ source,
511
+ prefix,
512
+ table,
513
+ fenceState,
514
+ rows: produced,
515
+ })
516
+ rows.push(...produced)
468
517
  }
469
518
  if (this.pending) {
470
519
  const pendingFence = this.fenceTracker()
@@ -648,6 +697,29 @@ export class Transcript {
648
697
  this.turnSummary(event.summary, event)
649
698
  return
650
699
  }
700
+ // F-TASK-1: status task kanonik (t<n>) + DAG dirender sebagai baris ledger,
701
+ // bukan ditelan — event ini sebelumnya hanya hidup di machine envelope.
702
+ if (event.type === "task.status") {
703
+ this.taskStatusLedger(event)
704
+ return
705
+ }
706
+ // P1.6: event observability non-tool yang sebelumnya diblokir oleh guard
707
+ // `!event.type.startsWith("tool.")` — consequence, context, verification
708
+ // kini dirender sebagai baris ledger informatif.
709
+ if (event.type === "consequence.decided") {
710
+ this.consequenceLedger(event)
711
+ return
712
+ }
713
+ if (event.type === "context.cutoff" || event.type === "context.window") {
714
+ this.contextLedger(event)
715
+ return
716
+ }
717
+ // P1.5: observasi verifikasi bukan `tool.*`, jadi sebelumnya ditelan guard
718
+ // di bawah dan `verificationLedger` menjadi kode mati. Render sebelum guard.
719
+ if (event.type === "verification.observed") {
720
+ this.verificationLedger(event)
721
+ return
722
+ }
651
723
  if (!event.type.startsWith("tool.")) return
652
724
  if (event.type === "tool.started") {
653
725
  this.commit()
@@ -698,7 +770,16 @@ export class Transcript {
698
770
  this.presentedTerminals.add(event.toolCallId)
699
771
  }
700
772
  const activity = this.snapshotActivity(event.toolCallId)
701
- if (activity?.parentToolCallId) return
773
+ // F-AGENT-1: baris per-run HANYA bila activity membawa identitas run anak
774
+ // (childSessionId/runId — data nyata dari ChildSessionLink). Tool anak yang
775
+ // cuma punya `parentToolCallId` (jalur grouping legacy) tetap SEPENUHNYA
776
+ // ditelan hitungan induk "n child tools" — kontrak P5 satu baris ledger
777
+ // induk. `parentToolCallId` = taut ke pemanggil, BUKAN identitas run; jangan
778
+ // disamakan dengan childSessionId/runId.
779
+ if (activity?.parentToolCallId) {
780
+ if (activity.childSessionId || activity.runId) this.childLedger(event, activity)
781
+ return
782
+ }
702
783
  this.commit()
703
784
  const snapshot = this.presentationSnapshot()
704
785
  const children = activity
@@ -732,18 +813,62 @@ export class Transcript {
732
813
  : provenance === "replay"
733
814
  ? " [replay]"
734
815
  : ""
816
+ // Denial reason wajib terlihat di TUI: linear + machine sudah menampilkannya,
817
+ // dan operator butuh tahu MENGAPA tool ditolak tanpa membaca log.
818
+ const denyReason =
819
+ status === "denied"
820
+ ? (desc?.denyReason ?? activity?.denyReason ?? (event.reason ? String(event.reason) : ""))
821
+ : ""
822
+ const message = event.message
823
+ ? `: ${truncateToWidth(sanitizeAnsi(String(event.message)), 200, "…").split("\n")[0] ?? ""}`
824
+ : denyReason
825
+ ? `: ${truncateToWidth(sanitizeAnsi(denyReason), 200, "…").split("\n")[0] ?? ""}`
826
+ : ""
827
+ const line = ` ${this.statusGlyph(status)} ${name}${targetText} ${this.statusWord(status)}${retry}${child}${verificationMark}${provenanceMark}${message}`
828
+ this.append(this.statusPaint(status, line), {
829
+ kind: "activity",
830
+ ...(event.seq !== undefined ? { seq: event.seq } : {}),
831
+ ...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
832
+ ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
833
+ status,
834
+ ...(activity?.expandRef ? { expandRef: activity.expandRef } : {}),
835
+ })
836
+ }
837
+
838
+ /** F-AGENT-1: label run pendek stabil (`run_<8>` | `sub_<8>`) — identitas anak. */
839
+ private runMarker(activity: UiPresentationActivity): string {
840
+ const id = activity.runId ?? activity.childSessionId
841
+ if (!id) return ""
842
+ const prefix = id.startsWith("run_") ? "run_" : id.startsWith("sub_") ? "sub_" : ""
843
+ const bare = id.slice(prefix.length).replace(/-/g, "")
844
+ return prefix + bare.slice(0, 8)
845
+ }
846
+
847
+ /**
848
+ * F-AGENT-1: baris terminal tool anak — identitas run + tool + status.
849
+ * Paralel dipisah via runMarker (data aktual runId/childSessionId), bukan
850
+ * hitungan "n tool anak" yang menyatukan run berbeda.
851
+ */
852
+ private childLedger(event: UiPresentationEvent, activity: UiPresentationActivity): void {
853
+ this.commit()
854
+ const marker = this.runMarker(activity)
855
+ const name = sanitizeAnsiLine(activity.name ?? event.name ?? "tool")
856
+ const target = activity.target ?? event.target
857
+ const targetText = target ? ` ${truncateToWidth(sanitizeAnsiLine(target), 120, "")}` : ""
858
+ const status = activity.status ?? event.status ?? "completed"
735
859
  const message =
736
860
  status === "failed" && event.message
737
861
  ? `: ${truncateToWidth(sanitizeAnsi(String(event.message)), 200, "…").split("\n")[0] ?? ""}`
738
862
  : ""
739
- const line = ` ${this.statusGlyph(status)} ${name}${targetText} ${this.statusWord(status)}${retry}${child}${verificationMark}${provenanceMark}${message}`
863
+ const markerText = marker ? `${marker} ` : ""
864
+ const line = ` ↳ ${markerText}${name}${targetText} ${this.statusWord(status)}${message}`
740
865
  this.append(this.statusPaint(status, line), {
741
866
  kind: "activity",
742
867
  ...(event.seq !== undefined ? { seq: event.seq } : {}),
743
868
  ...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
744
869
  ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
745
870
  status,
746
- ...(activity?.expandRef ? { expandRef: activity.expandRef } : {}),
871
+ ...(activity.expandRef ? { expandRef: activity.expandRef } : {}),
747
872
  })
748
873
  }
749
874
 
@@ -773,6 +898,111 @@ export class Transcript {
773
898
  )
774
899
  }
775
900
 
901
+ /**
902
+ * P1.6: baris ledger consequence.decided — menampilkan verdict ACE/policy
903
+ * agar operator tahu keputusan yang diambil runtime (PASS/FAIL/BLOCKED/
904
+ * INCONCLUSIVE). Sebelumnya diblokir oleh guard `!startsWith("tool.")`.
905
+ */
906
+ private consequenceLedger(event: UiPresentationEvent): void {
907
+ this.commit()
908
+ const verdict = String(event.verdict ?? "UNKNOWN")
909
+ const rule = event.failureClass ? ` class=${sanitizeAnsiLine(String(event.failureClass))}` : ""
910
+ const rationale = event.message ?? event.reason
911
+ const reason = rationale
912
+ ? `: ${truncateToWidth(sanitizeAnsiLine(String(rationale)), 200, "…")}`
913
+ : ""
914
+ const next = event.nextAction ? ` next=${sanitizeAnsiLine(String(event.nextAction))}` : ""
915
+ const glyph =
916
+ verdict === "PASS"
917
+ ? glyphs.check
918
+ : verdict === "FAIL" || verdict === "BLOCKED"
919
+ ? glyphs.cross
920
+ : "?"
921
+ const line = ` ${glyph} consequence ${sanitizeAnsiLine(verdict)}${rule}${next}${reason}`
922
+ const paint =
923
+ verdict === "FAIL" || verdict === "BLOCKED"
924
+ ? c.error(line)
925
+ : verdict === "PASS"
926
+ ? c.success(line)
927
+ : c.warning(line)
928
+ this.append(paint, {
929
+ kind: "activity",
930
+ ...(event.seq !== undefined ? { seq: event.seq } : {}),
931
+ ...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
932
+ })
933
+ }
934
+
935
+ /**
936
+ * P1.6: baris ledger context.cutoff / context.window — memberitahu operator
937
+ * saat konteks dipotong (compaction) atau mendekati batas jendela.
938
+ * Sebelumnya diblokir oleh guard `!startsWith("tool.")`.
939
+ */
940
+ private contextLedger(event: UiPresentationEvent): void {
941
+ this.commit()
942
+ if (event.type === "context.cutoff") {
943
+ const reason = event.reason ? `: ${sanitizeAnsiLine(String(event.reason))}` : ""
944
+ const line = ` ▪ context cutoff${reason}`
945
+ this.append(c.warning(line), {
946
+ kind: "system",
947
+ ...(event.seq !== undefined ? { seq: event.seq } : {}),
948
+ ...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
949
+ })
950
+ } else {
951
+ // context.window — occupancy aktual vs kapasitas (bukan session spend).
952
+ const used = event.usedTokens
953
+ const window = event.windowTokens
954
+ const pct = event.percent != null ? ` ${Math.round(event.percent)}%` : ""
955
+ const tokens =
956
+ used != null
957
+ ? ` ${used.toLocaleString()}${window ? `/${window.toLocaleString()}` : ""} tokens`
958
+ : ""
959
+ const line = ` ▪ context window${tokens}${pct}`
960
+ this.append(c.muted(line), {
961
+ kind: "system",
962
+ ...(event.seq !== undefined ? { seq: event.seq } : {}),
963
+ ...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
964
+ })
965
+ }
966
+ }
967
+
968
+ /**
969
+ * F-TASK-1: baris ledger status task kanonik (`t<n>`) + DAG. Id/status/parent/
970
+ * dependsOn dibawa apa adanya dari TaskStore; tak ada status yang diarang.
971
+ */
972
+ private taskStatusLedger(event: UiPresentationEvent): void {
973
+ const id = event.taskId
974
+ const raw = event.taskStatus
975
+ if (id === undefined || raw === undefined) return
976
+ this.commit()
977
+ const status = sanitizeAnsiLine(String(raw).toLowerCase())
978
+ const parent = event.parentId ? ` parent=${sanitizeAnsiLine(event.parentId)}` : ""
979
+ const deps = event.dependsOn?.length
980
+ ? ` dependsOn=[${event.dependsOn.map((d) => sanitizeAnsiLine(d)).join(",")}]`
981
+ : ""
982
+ const rev = event.revision !== undefined ? ` r${event.revision}` : ""
983
+ // P1.5: COMPLETED tanpa verification passed bukan PASS. Tandai eksplisit.
984
+ const verify =
985
+ raw === "COMPLETED"
986
+ ? event.taskVerification?.verdict === "passed"
987
+ ? " [verified]"
988
+ : ` [${event.taskVerification?.verdict ?? "unverified"}]`
989
+ : ""
990
+ const line = ` ▪ ${sanitizeAnsiLine(id)} ${status}${parent}${deps}${rev}${verify}`
991
+ const paint =
992
+ raw === "FAILED"
993
+ ? c.error(line)
994
+ : raw === "BLOCKED"
995
+ ? c.warning(line)
996
+ : raw === "COMPLETED"
997
+ ? c.success(line)
998
+ : c.muted(line)
999
+ this.append(paint, {
1000
+ kind: "activity",
1001
+ ...(event.seq !== undefined ? { seq: event.seq } : {}),
1002
+ ...(event.turnId !== undefined ? { turnId: event.turnId } : {}),
1003
+ })
1004
+ }
1005
+
776
1006
  private turnSummary(summary: UiPresentationEvent["summary"], event: UiPresentationEvent): void {
777
1007
  if (!summary) return
778
1008
  const snapshot = this.presentationSnapshot()
@@ -816,8 +1046,7 @@ export class Transcript {
816
1046
  if (!snapshot) return []
817
1047
  const running = snapshot.activities.filter((a) => a.status === "running")
818
1048
  const roots = running.filter((a) => !a.parentToolCallId)
819
- const rootIds = new Set(roots.map((a) => a.toolCallId))
820
- const row = (activity: (typeof running)[number], child: boolean): string => {
1049
+ const row = (activity: (typeof running)[number], child: boolean, marker: string): string => {
821
1050
  const name = sanitizeAnsiLine(activity.name)
822
1051
  const target = activity.target
823
1052
  ? ` ${truncateToWidth(sanitizeAnsiLine(activity.target), 120, "")}`
@@ -828,17 +1057,27 @@ export class Transcript {
828
1057
  : elapsed >= 2000
829
1058
  const elapsedText = showElapsed ? ` (${formatElapsed(elapsed)})` : ""
830
1059
  const retry = activity.supersedes ? ` ${t("ts.retry")}` : ""
1060
+ const markerText = marker ? `${marker} ` : ""
831
1061
  const prefix = child ? " ↳ " : ` ${glyphs.arrow} `
832
- return c.info(`${prefix}${name}${target} … ${t("ts.statusRunning")}${elapsedText}${retry}`)
1062
+ return c.info(
1063
+ `${prefix}${markerText}${name}${target} … ${t("ts.statusRunning")}${elapsedText}${retry}`,
1064
+ )
833
1065
  }
834
- const out = roots.map((activity) => {
835
- const childCount = running.filter((a) => a.parentToolCallId === activity.toolCallId).length
836
- const suffix = childCount > 0 ? ` ${t("ts.childGroup", { n: childCount })}` : ""
837
- return `${row(activity, false)}${suffix}`
838
- })
1066
+ // F-AGENT-1: tiap run anak = baris sendiri, bukan hitungan "n tool anak".
1067
+ const out: string[] = []
1068
+ for (const activity of roots) {
1069
+ out.push(row(activity, false, ""))
1070
+ for (const child of running.filter((a) => a.parentToolCallId === activity.toolCallId))
1071
+ out.push(row(child, true, this.runMarker(child)))
1072
+ }
1073
+ // Anak yatim (parent tak lagi running/root): tetap tampil, jangan hilang.
839
1074
  for (const activity of running) {
840
- if (!activity.parentToolCallId || rootIds.has(activity.parentToolCallId)) continue
841
- out.push(row(activity, true))
1075
+ if (
1076
+ !activity.parentToolCallId ||
1077
+ roots.some((r) => r.toolCallId === activity.parentToolCallId)
1078
+ )
1079
+ continue
1080
+ out.push(row(activity, true, this.runMarker(activity)))
842
1081
  }
843
1082
  return out
844
1083
  }
@@ -890,6 +1129,7 @@ export class Transcript {
890
1129
  this.tables.splice(0, overflow)
891
1130
  this.sourcePrefixes.splice(0, overflow)
892
1131
  this.meta.splice(0, overflow)
1132
+ this.rowCache.clear() // index bergeser setelah eviction
893
1133
  this.evicted += overflow
894
1134
  this.lines.unshift(c.muted(t("ts.evictMarker", { n: this.evicted })))
895
1135
  this.tables.unshift(null)
@@ -910,6 +1150,7 @@ export class Transcript {
910
1150
  this.tables.splice(1, overflow)
911
1151
  this.sourcePrefixes.splice(1, overflow)
912
1152
  this.meta.splice(1, overflow)
1153
+ this.rowCache.clear() // index bergeser setelah eviction
913
1154
  this.evicted += overflow
914
1155
  this.lines[0] = c.muted(t("ts.evictMarker", { n: this.evicted }))
915
1156
  }
@@ -1,26 +1,26 @@
1
- // Token budget policy: pure functions over a budget state. No storage, no side effects.
2
-
3
- export type PressureLevel = "low" | "medium" | "high" | "critical";
4
-
5
- export interface BudgetState {
6
- usedTokens: number;
7
- limitTokens: number;
8
- }
9
-
10
- export interface BudgetPolicy {
11
- evaluate(state: BudgetState): PressureLevel;
12
- shouldCompact(pressure: PressureLevel): boolean;
13
- }
14
-
15
- export const defaultBudgetPolicy: BudgetPolicy = {
16
- evaluate({ usedTokens, limitTokens }) {
17
- const ratio = usedTokens / Math.max(1, limitTokens);
18
- if (ratio >= 1) return "critical";
19
- if (ratio >= 0.9) return "high";
20
- if (ratio >= 0.75) return "medium";
21
- return "low";
22
- },
23
- shouldCompact(pressure) {
24
- return pressure === "medium" || pressure === "high" || pressure === "critical";
25
- },
1
+ // Token budget policy: pure functions over a budget state. No storage, no side effects.
2
+
3
+ export type PressureLevel = "low" | "medium" | "high" | "critical";
4
+
5
+ export interface BudgetState {
6
+ usedTokens: number;
7
+ limitTokens: number;
8
+ }
9
+
10
+ export interface BudgetPolicy {
11
+ evaluate(state: BudgetState): PressureLevel;
12
+ shouldCompact(pressure: PressureLevel): boolean;
13
+ }
14
+
15
+ export const defaultBudgetPolicy: BudgetPolicy = {
16
+ evaluate({ usedTokens, limitTokens }) {
17
+ const ratio = usedTokens / Math.max(1, limitTokens);
18
+ if (ratio >= 1) return "critical";
19
+ if (ratio >= 0.9) return "high";
20
+ if (ratio >= 0.75) return "medium";
21
+ return "low";
22
+ },
23
+ shouldCompact(pressure) {
24
+ return pressure === "medium" || pressure === "high" || pressure === "critical";
25
+ },
26
26
  };
@@ -1,76 +1,76 @@
1
- // Compaction: a deterministic, LLM-free strategy. Replaces old turns with a
2
- // bounded summary while preserving the recent tail verbatim. It never splits
3
- // an assistant tool_call message from its following tool results.
4
-
5
- import type { ContextStore } from "./history.ts";
6
- import type { Message } from "./types.ts";
7
- import { contentToText, safeStringify } from "./tokens.ts";
8
-
9
- export interface CompactionStrategy {
10
- readonly kind: string;
11
- compact(store: ContextStore, opts: { keepRecentTurns: number }): readonly Message[];
12
- /**
13
- * Optional async compaction. If present, the loop prefers this over `compact`
14
- * (sync). Must return the new messages array (or same if no compaction needed).
15
- * The loop expects this to respect `signal` (abort → reject). If it throws,
16
- * the loop falls back to `compact` (sync mechanical) — never crash the loop.
17
- * The signal is the turn's abort signal (user abort, session.abort, timeout).
18
- */
19
- compactAsync?(store: ContextStore, opts: { keepRecentTurns: number }, signal: AbortSignal): Promise<readonly Message[]>;
20
- }
21
-
22
- export const mechanicalCompaction: CompactionStrategy = {
23
- kind: "mechanical",
24
- compact(store, { keepRecentTurns }) {
25
- const messages = store.messages;
26
- let kept = 0;
27
- let turns = 0;
28
- for (let i = messages.length - 1; i >= 0; i--) {
29
- kept++;
30
- if (messages[i]!.role === "user") turns++;
31
- if (turns >= keepRecentTurns) break;
32
- }
33
- // Never leave a tool result dangling: extend the kept region across a
34
- // tool's call batch (assistant → tool results) so results stay paired.
35
- while (kept < messages.length) {
36
- const cut = messages.length - kept;
37
- const firstKept = messages[cut]!;
38
- const prev = messages[cut - 1];
39
- const extendsPair =
40
- firstKept.role === "tool" &&
41
- prev !== undefined &&
42
- (prev.role === "tool" || (prev.role === "assistant" && prev.toolCalls !== undefined && prev.toolCalls.length > 0));
43
- if (extendsPair) kept++;
44
- else break;
45
- }
46
- if (kept >= messages.length) return messages;
47
- const prefix = messages.slice(0, messages.length - kept);
48
- const summary: Message = {
49
- role: "user",
50
- content: `Previous context:\n${prefix.map(compactLine).join("\n")}`,
51
- };
52
- return [summary, ...messages.slice(-kept)];
53
- },
54
- };
55
-
56
- function compactLine(message: Message): string {
57
- switch (message.role) {
58
- case "user":
59
- return `- user: ${head(contentToText(message.content), 400)}`;
60
- case "assistant": {
61
- const calls = (message.toolCalls ?? [])
62
- .map((call) => `${call.name}(${head(safeStringify(call.args), 80)})`)
63
- .join(", ");
64
- return `- assistant${calls ? ` [calls: ${calls}]` : ""}: ${head(contentToText(message.content), 400)}`;
65
- }
66
- case "tool":
67
- if (message.isError) return `- tool(${message.name}): ${head(String(message.content), 200)}`;
68
- return `- tool(${message.name}): <result omitted>`;
69
- default:
70
- return "";
71
- }
72
- }
73
-
74
- function head(text: string, max: number): string {
75
- return text.length <= max ? text : `${text.slice(0, max)}…`;
1
+ // Compaction: a deterministic, LLM-free strategy. Replaces old turns with a
2
+ // bounded summary while preserving the recent tail verbatim. It never splits
3
+ // an assistant tool_call message from its following tool results.
4
+
5
+ import type { ContextStore } from "./history.ts";
6
+ import type { Message } from "./types.ts";
7
+ import { contentToText, safeStringify } from "./tokens.ts";
8
+
9
+ export interface CompactionStrategy {
10
+ readonly kind: string;
11
+ compact(store: ContextStore, opts: { keepRecentTurns: number }): readonly Message[];
12
+ /**
13
+ * Optional async compaction. If present, the loop prefers this over `compact`
14
+ * (sync). Must return the new messages array (or same if no compaction needed).
15
+ * The loop expects this to respect `signal` (abort → reject). If it throws,
16
+ * the loop falls back to `compact` (sync mechanical) — never crash the loop.
17
+ * The signal is the turn's abort signal (user abort, session.abort, timeout).
18
+ */
19
+ compactAsync?(store: ContextStore, opts: { keepRecentTurns: number }, signal: AbortSignal): Promise<readonly Message[]>;
20
+ }
21
+
22
+ export const mechanicalCompaction: CompactionStrategy = {
23
+ kind: "mechanical",
24
+ compact(store, { keepRecentTurns }) {
25
+ const messages = store.messages;
26
+ let kept = 0;
27
+ let turns = 0;
28
+ for (let i = messages.length - 1; i >= 0; i--) {
29
+ kept++;
30
+ if (messages[i]!.role === "user") turns++;
31
+ if (turns >= keepRecentTurns) break;
32
+ }
33
+ // Never leave a tool result dangling: extend the kept region across a
34
+ // tool's call batch (assistant → tool results) so results stay paired.
35
+ while (kept < messages.length) {
36
+ const cut = messages.length - kept;
37
+ const firstKept = messages[cut]!;
38
+ const prev = messages[cut - 1];
39
+ const extendsPair =
40
+ firstKept.role === "tool" &&
41
+ prev !== undefined &&
42
+ (prev.role === "tool" || (prev.role === "assistant" && prev.toolCalls !== undefined && prev.toolCalls.length > 0));
43
+ if (extendsPair) kept++;
44
+ else break;
45
+ }
46
+ if (kept >= messages.length) return messages;
47
+ const prefix = messages.slice(0, messages.length - kept);
48
+ const summary: Message = {
49
+ role: "user",
50
+ content: `Previous context:\n${prefix.map(compactLine).join("\n")}`,
51
+ };
52
+ return [summary, ...messages.slice(-kept)];
53
+ },
54
+ };
55
+
56
+ function compactLine(message: Message): string {
57
+ switch (message.role) {
58
+ case "user":
59
+ return `- user: ${head(contentToText(message.content), 400)}`;
60
+ case "assistant": {
61
+ const calls = (message.toolCalls ?? [])
62
+ .map((call) => `${call.name}(${head(safeStringify(call.args), 80)})`)
63
+ .join(", ");
64
+ return `- assistant${calls ? ` [calls: ${calls}]` : ""}: ${head(contentToText(message.content), 400)}`;
65
+ }
66
+ case "tool":
67
+ if (message.isError) return `- tool(${message.name}): ${head(String(message.content), 200)}`;
68
+ return `- tool(${message.name}): <result omitted>`;
69
+ default:
70
+ return "";
71
+ }
72
+ }
73
+
74
+ function head(text: string, max: number): string {
75
+ return text.length <= max ? text : `${text.slice(0, max)}…`;
76
76
  }