minicode-ai 0.23.0 → 0.26.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 (104) hide show
  1. package/README.md +5 -3
  2. package/cli/commands/config.ts +123 -0
  3. package/cli/setup.ts +107 -8
  4. package/cli/tui.ts +28 -2
  5. package/docs/README.md +2 -2
  6. package/docs/SUMMARY.md +10 -19
  7. package/docs/TERMINAL_CONTRACT.md +113 -28
  8. package/docs/architecture.md +1 -1
  9. package/docs/autonomous-scheduler.md +283 -2
  10. package/docs/choosing-mode.md +4 -4
  11. package/docs/concepts.md +39 -3
  12. package/docs/config.md +103 -5
  13. package/docs/environment.md +4 -0
  14. package/docs/getting-started.md +69 -5
  15. package/docs/repl.md +1 -1
  16. package/docs/security.md +49 -2
  17. package/docs/tools.md +2 -1
  18. package/package.json +2 -36
  19. package/src/app/provider-layer.ts +1 -1
  20. package/src/app/session.ts +187 -17
  21. package/src/config.ts +21 -8
  22. package/src/constants.ts +17 -1
  23. package/src/lib/net.ts +6 -15
  24. package/src/lib/public-http.ts +128 -0
  25. package/src/lib/safe-open.ts +21 -12
  26. package/src/memory/vector.ts +0 -31
  27. package/src/policy/auto-resume.ts +63 -0
  28. package/src/policy/compaction.ts +354 -70
  29. package/src/policy/context-budget.ts +4 -6
  30. package/src/policy/context-window-assign.ts +114 -0
  31. package/src/policy/context-window-catalog.ts +4 -1
  32. package/src/policy/context-window-presets.ts +165 -0
  33. package/src/policy/context-window.ts +19 -37
  34. package/src/policy/context.ts +11 -9
  35. package/src/policy/executor.ts +69 -27
  36. package/src/policy/microcompact.ts +76 -15
  37. package/src/policy/no-progress.ts +1 -1
  38. package/src/policy/permission.ts +5 -0
  39. package/src/policy/recovery-budget.ts +281 -0
  40. package/src/policy/scrub.ts +15 -2
  41. package/src/policy/step-escalation.ts +82 -0
  42. package/src/policy/tokenizer-registry.ts +1 -0
  43. package/src/policy/tool-contract.ts +11 -9
  44. package/src/presentation/reducer.ts +1 -0
  45. package/src/providers/anthropic.ts +3 -3
  46. package/src/providers/detect.ts +40 -7
  47. package/src/providers/provision.ts +23 -1
  48. package/src/runtime/child-execution.ts +4 -2
  49. package/src/runtime/execution-backend.ts +3 -0
  50. package/src/sandbox/os.ts +53 -9
  51. package/src/session/context-assembly.ts +11 -7
  52. package/src/session/persistence.ts +19 -3
  53. package/src/task/autonomous-policy.ts +7 -0
  54. package/src/task/graph-validate.ts +1 -1
  55. package/src/task/session-authority.ts +0 -5
  56. package/src/task/store.ts +0 -4
  57. package/src/tools/ask_user.ts +14 -1
  58. package/src/tools/bash.ts +68 -17
  59. package/src/tools/code_run.ts +19 -20
  60. package/src/tools/context.ts +10 -0
  61. package/src/tools/delete_file.ts +3 -2
  62. package/src/tools/edit.ts +5 -4
  63. package/src/tools/git.ts +70 -12
  64. package/src/tools/glob.ts +13 -5
  65. package/src/tools/grep.ts +26 -10
  66. package/src/tools/index.ts +3 -2
  67. package/src/tools/lsp.ts +15 -9
  68. package/src/tools/move_file.ts +4 -3
  69. package/src/tools/patch.ts +5 -4
  70. package/src/tools/read_file.ts +3 -2
  71. package/src/tools/read_image.ts +3 -2
  72. package/src/tools/task.ts +5 -1
  73. package/src/tools/todo.ts +4 -8
  74. package/src/tools/web_fetch.ts +13 -19
  75. package/src/tools/write_file.ts +4 -3
  76. package/src/ui/approval/prompt.ts +226 -77
  77. package/src/ui/assistant/simple.ts +61 -10
  78. package/src/ui/footer.ts +41 -29
  79. package/src/ui/i18n/en.ts +7 -0
  80. package/src/ui/i18n/id.ts +7 -0
  81. package/src/ui/input/prompt-engine.ts +53 -21
  82. package/src/ui/render/activity-group.ts +9 -0
  83. package/src/ui/render/activity-panel.ts +20 -2
  84. package/src/ui/render/ledger.ts +1 -9
  85. package/src/ui/render/logo.ts +0 -5
  86. package/src/ui/render/markdown-table.ts +0 -3
  87. package/src/ui/render/table-grid.ts +0 -3
  88. package/src/ui/render/theme.ts +31 -5
  89. package/src/ui/runtime/screen.ts +7 -1
  90. package/src/ui/screens/dialog.ts +45 -81
  91. package/src/ui/screens/form.ts +10 -10
  92. package/src/ui/screens/model-manager.ts +7 -10
  93. package/src/ui/screens/picker.ts +8 -11
  94. package/src/ui/screens/provider-manager.ts +9 -13
  95. package/src/ui/tui/app.ts +118 -20
  96. package/src/ui/tui/transcript.ts +179 -29
  97. package/vendor/minicore/src/core/loop.ts +20 -1
  98. package/vendor/minicore/src/core/session.ts +6 -0
  99. package/docs/P14_OPEN_WORK.md +0 -290
  100. package/docs/config-providers.md +0 -87
  101. package/docs/glossary.md +0 -39
  102. package/docs/quickstart.md +0 -60
  103. package/docs/security-model.md +0 -96
  104. package/docs/terminal.md +0 -91
@@ -54,6 +54,10 @@ export interface ApprovalSink {
54
54
  repaint(): void
55
55
  suspend(): void
56
56
  resume(): void
57
+ /** Lukis kotak modal di atas transkrip (popup komposit). Opsional: sink warisan (mock/test) boleh tanpa. */
58
+ paintRegion?(lines: string[], topRow: number): void
59
+ /** Hapus kotak modal sebelum resume. Opsional. */
60
+ clearRegion?(): void
57
61
  }
58
62
 
59
63
  let approvalSink: ApprovalSink | null = null
@@ -125,6 +129,38 @@ interface ProjectedLineCache {
125
129
  rows: TranscriptRow[]
126
130
  }
127
131
 
132
+ /**
133
+ * Ringkas alasan gagal ringkasan LLM menjadi SEBAB yang bisa dibaca.
134
+ *
135
+ * Contoh nyata dari lapangan: `server error (503): {"error":{"origin":
136
+ * "tiprouter","code":"overloaded","requestId":"c38699cf-...","message":
137
+ * "The gateway is overloaded ()"}}`. Yang berguna: "503 · gateway overloaded".
138
+ * Tanpa ini, satu baris ledger menyeret JSON gateway (dan id request) ke
139
+ * transkrip, mendorong konteks lain keluar layar.
140
+ */
141
+ function shortLlmFailureReason(raw: string): string {
142
+ const body = raw.slice("llm-failed:".length).trim()
143
+ // Status HTTP + kode mesin-terbaca bila ada di JSON gateway.
144
+ const status = /(?:^|[^0-9])([0-9]{3})(?:[^0-9]|$)/.exec(body)?.[1]
145
+ const code = /"code"\s*:\s*"([^"]{1,40})"/.exec(body)?.[1]
146
+ const message = /"message"\s*:\s*"([^"]{1,120})"/.exec(body)?.[1]
147
+ const parts: string[] = []
148
+ if (status) parts.push(status)
149
+ if (code && code !== status) parts.push(code)
150
+ if (message)
151
+ parts.push(
152
+ message
153
+ .replace(/\(\)/g, "")
154
+ .replace(/[,;:]+$/, "")
155
+ .trim(),
156
+ )
157
+ if (parts.length > 0) return parts.join(" · ")
158
+ // Teks biasa (timeout, auth): ambil kalimat pertama saja.
159
+ const firstBreak = body.indexOf("\n")
160
+ const firstLine = firstBreak >= 0 ? body.slice(0, firstBreak) : body
161
+ return firstLine.replace(/\r$/, "").slice(0, 120)
162
+ }
163
+
128
164
  function formatElapsed(ms: number): string {
129
165
  const seconds = Math.max(0, Math.floor(ms / 1000))
130
166
  if (seconds < 60) return `${seconds}s`
@@ -210,7 +246,7 @@ export class Transcript {
210
246
  * P2.2: cache proyeksi PER BARIS logis. Transkrip append-only, jadi baris
211
247
  * lama tidak perlu di-wrap/markdown ulang setiap frame. Cache di-key oleh
212
248
  * semua input yang memengaruhi hasil (width, teks, source, prefix, tabel,
213
- * fence state) dan dibuang saat eviction (index bergeser) atau clear.
249
+ * fence state), memakai ID stabil; eviction hanya membuang ID yang hilang.
214
250
  */
215
251
  private rowCache = new Map<number, ProjectedLineCache>()
216
252
  private ids: number[] = []
@@ -238,6 +274,17 @@ export class Transcript {
238
274
  /** Baris thinking turn berjalan (mode AREA, Fase 3): dirender sebagai blok
239
275
  * live maks 10 baris, bukan di-commit per baris. Diringkas saat turn selesai. */
240
276
  private thinkingArea: string[] = []
277
+ /** Id baris ringkasan thinking turn berjalan (null = belum ada). Dipakai
278
+ * untuk MENGGANTI baris yang sama saat segmen thinking berikutnya datang,
279
+ * bukan menambah baris baru. */
280
+ private thinkingRowId: number | null = null
281
+ /** True bila ada segmen reasoning yang sudah ditutup (commit) dalam turn
282
+ * berjalan — dipakai untuk memisahkan baris segmen baru dari sisa tail. */
283
+ private thinkingSeenSegment = false
284
+ /** Total baris thinking yang SUDAH ditampilkan untuk turn berjalan — sumber
285
+ * angka pada baris ringkasan. Sengaja tidak dinolkan saat turn ditutup supaya
286
+ * angka yang sudah tercetak tetap benar. */
287
+ private thinkingTurnRows = 0
241
288
  private meta: TranscriptMeta[] = []
242
289
  private evicted = 0
243
290
  private hasEvictMarker = false
@@ -310,12 +357,21 @@ export class Transcript {
310
357
  bus.on("provider:text", (e: { text: string }) => this.stream(e.text)),
311
358
  bus.on("turn:started", () => {
312
359
  this.commit()
313
- this.commitThinking()
360
+ // Akhiri akumulasi thinking turn sebelumnya: turn baru = baris baru.
361
+ this.commitThinking(true)
362
+ // Angka total dinolkan DI SINI (bukan saat turn ditutup) supaya baris
363
+ // turn yang baru selesai tetap menunjukkan panjangnya sendiri. Tanpa
364
+ // reset ini, turn kedua melanjutkan hitungan turn pertama dan
365
+ // melaporkan "4 lines" untuk penalaran 2 baris.
366
+ this.thinkingTurnRows = 0
314
367
  this.activityFold = []
315
368
  }),
316
369
  bus.on("turn:completed", () => {
370
+ // Satu panggilan `turnEnd`: flush sisa segmen DAN menutup akumulasi.
371
+ // Dua panggilan terpisah seperti sebelumnya membuang segmen terakhir
372
+ // yang belum sempat di-flush (hitungan jadi kurang dari kenyataan).
373
+ this.commitThinking(true)
317
374
  this.commit()
318
- this.commitThinking()
319
375
  }),
320
376
  bus.on("execution:started", () => {
321
377
  this.commit()
@@ -357,8 +413,13 @@ export class Transcript {
357
413
  fixed: impossible[1] ?? "0",
358
414
  trigger: impossible[2] ?? "0",
359
415
  })
360
- if (clean.startsWith("llm-failed:"))
361
- return t("ts.compactedLlmFailed", { reason: clean.slice("llm-failed:".length) })
416
+ if (clean.startsWith("llm-failed:")) {
417
+ // Alasan mentah provider dipangkas ke SEBAB saja: pesan 503 penuh berisi
418
+ // JSON gateway (`{"error":{"origin":"tiprouter",...,"requestId":"..."}}`)
419
+ // yang membingungkan dan mendorong baris lain keluar layar. Yang
420
+ // berguna bagi pengguna hanya "kenapa", bukan id request gateway.
421
+ return t("ts.compactedLlmFailed", { reason: shortLlmFailureReason(clean) })
422
+ }
362
423
  return t("ts.compacted", { reason: clean })
363
424
  }
364
425
 
@@ -430,6 +491,16 @@ export class Transcript {
430
491
  // Mode AREA (Fase 3): tahan baris di buffer, dirender sebagai blok live
431
492
  // terbatas (projectAll). JANGAN di-commit per baris — area yang
432
493
  // menggantikannya + ringkasan saat turn selesai.
494
+ // Segmen reasoning BARU setelah tool call harus memulai baris sendiri:
495
+ // sisa `thinkingTail` dari segmen sebelumnya (teks tanpa `\n` terakhir)
496
+ // di-flush dulu. Tanpa ini dua segmen pendek bergabung dan baris
497
+ // penutupnya hilang dari hitungan (baris terlihat lebih sedikit dari
498
+ // yang sebenarnya dipikirkan model).
499
+ if (this.thinkingSeenSegment) {
500
+ if (this.thinkingTail.length > 0) this.thinkingArea.push(this.thinkingTail)
501
+ this.thinkingTail = ""
502
+ this.thinkingSeenSegment = false
503
+ }
433
504
  this.thinkingTail += clean
434
505
  const parts = this.thinkingTail.split("\n")
435
506
  for (let i = 0; i < parts.length - 1; i++) this.thinkingArea.push(parts[i] ?? "")
@@ -461,10 +532,15 @@ export class Transcript {
461
532
  }
462
533
 
463
534
  /** Selesaikan fase thinking.
464
- * - Mode area: ringkas jadi SATU baris (detail penuh di `/expand`).
535
+ * - Mode area: ringkas jadi SATU baris (detail penuh di `/expand`),
536
+ * diakumulasi per TURN dan diperbarui di tempat.
465
537
  * - Legacy: flush ekor berindentasi.
466
- * - Minimized: penanda hilang. */
467
- private commitThinking(): void {
538
+ * - Minimized: penanda hilang.
539
+ *
540
+ * `turnEnd = true` menutup akumulasi sehingga turn berikutnya memulai baris
541
+ * baru; pemanggil di tengah turn (mis. `execution:started`) memakai default
542
+ * agar segmen berikutnya menambah hitungan pada baris yang sama. */
543
+ private commitThinking(turnEnd = false): void {
468
544
  if (this.thinkingAreaMode()) {
469
545
  const lines = [...this.thinkingArea]
470
546
  if (this.thinkingTail) {
@@ -473,13 +549,38 @@ export class Transcript {
473
549
  }
474
550
  this.thinkingArea = []
475
551
  this.thinkingBuf = ""
552
+ this.thinkingSeenSegment = true
476
553
  if (lines.length > 0) {
477
554
  // Detail penuh tidak hilang: masuk buffer `/expand`.
478
555
  this.uiState.rememberCollapsedSection("thinking", lines.join("\n"))
479
- this.append(
480
- c.thinking(` + ${t("panel.thinking")} · ${t("panel.lines", { n: lines.length })}`),
481
- { kind: "diagnostic" },
556
+ // ── Satu baris thinking per TURN, bukan per segmen ──────────────────
557
+ // `execution:started` menyala setiap tool call, jadi model yang pola
558
+ // pikirannya pendek-pendek menghasilkan deretan `+ thinking · 3 lines`
559
+ // berulang tanpa jeda (keluhan "jendela thinking bocor / semrawut").
560
+ // Segmen berikutnya dalam turn yang sama menambah HITUNGAN pada baris
561
+ // yang sama alih-alih mencetak baris baru: pembaca melihat total
562
+ // panjang penalaran turn itu, bukan sepuluh fragmen.
563
+ this.thinkingTurnRows += lines.length
564
+ const label = c.thinking(
565
+ ` + ${t("panel.thinking")} · ${t("panel.lines", { n: this.thinkingTurnRows })}`,
482
566
  )
567
+ if (this.thinkingRowId !== null && this.replaceEntry(this.thinkingRowId, label)) {
568
+ // Baris lama masih ada: perbarui di tempat (id tetap → tinggi tetap).
569
+ } else {
570
+ // Baris lama TIDAK ada lagi — bisa karena eviction `TRANSCRIPT_CAP`
571
+ // saat turn sangat panjang. Tanpa cabang ini, `thinkingRowId` basi
572
+ // membuat `replaceEntry` no-op selamanya dan seluruh thinking sisa
573
+ // turn HILANG tanpa jejak (penalaran model tak terlihat).
574
+ this.thinkingRowId = this.appendWithId(label, { kind: "diagnostic" })
575
+ }
576
+ }
577
+ // `turnEnd` hanya menutup BARIS (agar turn berikutnya membuat baris
578
+ // baru). Angka totalnya sengaja TIDAK dinolkan di sini: baris yang sudah
579
+ // tercetak harus tetap menunjukkan panjang penalaran turn yang baru
580
+ // selesai. Reset terjadi saat `turn:started` berikutnya.
581
+ if (turnEnd) {
582
+ this.thinkingRowId = null
583
+ this.thinkingSeenSegment = false
483
584
  }
484
585
  return
485
586
  }
@@ -852,7 +953,7 @@ export class Transcript {
852
953
  const fenceState = assistant ? committedFence(raw) : "outside"
853
954
  const source = this.sourceTexts.get(id) ?? ""
854
955
  const prefix = this.sourcePrefixes[i] ?? ""
855
- const cached = this.rowCache.get(i)
956
+ const cached = this.rowCache.get(id)
856
957
  if (
857
958
  cached &&
858
959
  cached.width === w &&
@@ -870,7 +971,7 @@ export class Transcript {
870
971
  const produced = table
871
972
  ? this.projectTable(table, id, w)
872
973
  : this.projectText(raw, source, id, w, true, prefix, assistant, fenceState)
873
- this.rowCache.set(i, {
974
+ this.rowCache.set(id, {
874
975
  width: w,
875
976
  id,
876
977
  raw,
@@ -1159,12 +1260,15 @@ export class Transcript {
1159
1260
  private presentationEvent(event: UiPresentationEvent): void {
1160
1261
  if (event.type === "turn.started") {
1161
1262
  this.commit()
1162
- this.commitThinking()
1263
+ // Turn baru: tutup akumulasi turn sebelumnya supaya baris thinkingnya
1264
+ // mandiri (tidak menyambung hitungan turn yang sudah lewat).
1265
+ this.commitThinking(true)
1266
+ this.thinkingTurnRows = 0
1163
1267
  this.activityFold = []
1164
1268
  return
1165
1269
  }
1166
1270
  if (event.type === "turn.completed") {
1167
- this.commitThinking()
1271
+ this.commitThinking(true)
1168
1272
  // Flush panel SEBELUM commit jawaban agar urutan persist = transient (panel di
1169
1273
  // atas jawaban; tanpa ini panel "lompat" ke bawah saat turn selesai).
1170
1274
  this.flushActivityFold()
@@ -1177,7 +1281,7 @@ export class Transcript {
1177
1281
  return
1178
1282
  }
1179
1283
  if (event.type === "turn.failed" || event.type === "turn.cancelled") {
1180
- this.commitThinking()
1284
+ this.commitThinking(true)
1181
1285
  this.flushActivityFold()
1182
1286
  this.commit()
1183
1287
  return
@@ -1287,8 +1391,16 @@ export class Transcript {
1287
1391
  status === "denied"
1288
1392
  ? (desc?.denyReason ?? activity?.denyReason ?? (event.reason ? String(event.reason) : ""))
1289
1393
  : ""
1290
- const message = event.message
1291
- ? `: ${truncateToWidth(sanitizeAnsi(String(event.message)), 200, "…").split("\n")[0] ?? ""}`
1394
+ const errorMessage = event.message ?? desc?.message ?? activity?.error?.message
1395
+ // Pesan error WAJIB satu baris: ledger adalah ringkasan, bukan dump. Teks
1396
+ // datang dari provider/tool (tak terpercaya) dan bisa multi-baris. Potong
1397
+ // di sini SEBELUM sanitasi: `sanitizeAnsiLine` memang sengaja mengubah \n
1398
+ // menjadi spasi (untuk teks alir), jadi memotong sesudahnya tidak berguna —
1399
+ // pesannya sudah tergabung menjadi satu baris panjang. Tanpa potongan awal,
1400
+ // satu error ikut menyeret sisa pesannya ke dalam ledger.
1401
+ const firstLine = String(errorMessage ?? "").split(/[\r\n]/)[0] ?? ""
1402
+ const message = errorMessage
1403
+ ? `: ${truncateToWidth(sanitizeAnsiLine(firstLine), 200, "…")}`
1292
1404
  : denyReason
1293
1405
  ? `: ${truncateToWidth(sanitizeAnsi(denyReason), 200, "…").split("\n")[0] ?? ""}`
1294
1406
  : ""
@@ -1297,9 +1409,17 @@ export class Transcript {
1297
1409
  // aktivitas aktif, baris ledger per-tool TIDAK boleh menghilang diam-diam
1298
1410
  // — ditahan lalu dirangkum saat turn selesai (panel: per keluarga tool;
1299
1411
  // minimize: satu baris nama+hitungan). Detail via /expand.
1412
+ //
1413
+ // Tool gagal/ditolak TETAP dicetak individual supaya alasannya langsung
1414
+ // terbaca (menyembunyikannya = pengguna tak tahu kenapa tool berhenti).
1415
+ // Kegagalan JUGA masuk fold agar baris grup tetap melaporkan agregatnya
1416
+ // (`1 failed`) — angka itu informasi nyata, bukan duplikasi teks. Yang
1417
+ // tidak boleh dobel adalah PESANNYA; di baris grup hanya ada hitungan,
1418
+ // jadi tidak ada teks alasan yang tercetak dua kali.
1300
1419
  if (this.uiState.minimizeActivity || this.uiState.activityPanel) {
1301
1420
  this.activityFold.push({ name, status, line })
1302
- return
1421
+ // Yang berhasil sudah diwakili baris grup → tak perlu baris individual.
1422
+ if (status === "completed") return
1303
1423
  }
1304
1424
  this.append(paintLedger(status, line), {
1305
1425
  kind: "activity",
@@ -1517,7 +1637,20 @@ export class Transcript {
1517
1637
  const fold = this.activityFold
1518
1638
  this.activityFold = []
1519
1639
  if (fold.length === 0) return
1520
- // Panel ON: render per-grup (sumber: event tool yang sudah dikumpulkan).
1640
+ // Detail per-tool selalu disimpan untuk /expand — tidak ada yang dibuang.
1641
+ this.uiState.rememberCollapsedSection("activity", fold.map((e) => e.line).join("\n"))
1642
+ const count = (status: string) => fold.reduce((n, e) => n + (e.status === status ? 1 : 0), 0)
1643
+ const ok = count("completed")
1644
+ const failed = count("failed")
1645
+ const denied = count("denied")
1646
+ // ── Panel ON: SATU baris ringkas, bukan salinan panel ──────────────────
1647
+ // Panel aktivitas sudah merender grup secara LIVE selama turn (`panelRows`).
1648
+ // Mencetak ulang 10 baris grup yang sama ke transkrip permanen membuat
1649
+ // setiap turn meninggalkan salinan panel di belakangnya: setelah beberapa
1650
+ // turn layar penuh blok `+ explore 143 tools …`, `+ execute 14 tools …`
1651
+ // yang berulang dan mendorong jawaban keluar layar (keluhan "tool numpuk").
1652
+ // Yang dicetak permanen cukup satu baris: setelah turn selesai panel hidup
1653
+ // hilang, dan baris ini yang menjadi jejaknya.
1521
1654
  if (this.uiState.activityPanel) {
1522
1655
  const activities = fold.map((e) => ({
1523
1656
  toolCallId: "",
@@ -1527,14 +1660,9 @@ export class Transcript {
1527
1660
  }))
1528
1661
  const lines = renderActivityPanel(activities, { maxRows: 10 })
1529
1662
  if (lines.length === 0) return
1530
- this.uiState.rememberCollapsedSection("activity", fold.map((e) => e.line).join("\n"))
1531
1663
  for (const line of lines) this.append(line, { kind: "activity" })
1532
1664
  return
1533
1665
  }
1534
- const count = (status: string) => fold.reduce((n, e) => n + (e.status === status ? 1 : 0), 0)
1535
- const ok = count("completed")
1536
- const failed = count("failed")
1537
- const denied = count("denied")
1538
1666
  const names = [...new Set(fold.map((e) => e.name))]
1539
1667
  const shown = names.slice(0, 3).join(", ")
1540
1668
  const more = names.length - 3
@@ -1548,8 +1676,6 @@ export class Transcript {
1548
1676
  .join(", ")
1549
1677
  const statPart = stats ? ` · ${stats}` : ""
1550
1678
  const line = ` ${glyphs.check} ${fold.length} tool${fold.length > 1 ? "s" : ""}${namePart}${statPart}`
1551
- // Detail tetap tersedia via /expand (tidak dibuang).
1552
- this.uiState.rememberCollapsedSection("activity", fold.map((e) => e.line).join("\n"))
1553
1679
  this.append(line, { kind: "activity" })
1554
1680
  }
1555
1681
 
@@ -1608,6 +1734,30 @@ export class Transcript {
1608
1734
  this.appendWithSource(line, meta, stripSgr(sanitizeAnsi(line)))
1609
1735
  }
1610
1736
 
1737
+ /** Seperti `append`, tetapi MENGEMBALIKAN id baris — dipakai baris yang
1738
+ * nanti diperbarui di tempat (ringkasan thinking per turn). */
1739
+ private appendWithId(line: string, meta: TranscriptMeta): number {
1740
+ const id = this.nextId
1741
+ this.append(line, meta)
1742
+ return id
1743
+ }
1744
+
1745
+ /**
1746
+ * Ganti teks baris yang sudah ada TANPA menambah tinggi transkrip.
1747
+ *
1748
+ * KENAPA bukan append: baris ringkasan thinking diperbarui setiap segmen
1749
+ * penalaran (bisa puluhan kali per turn). Kalau tiap pembaruan jadi baris
1750
+ * baru, transkrip penuh fragmen `+ thinking · N lines` dan konten bergeser
1751
+ * terus — keluhan "thinking bocor" dan "teks naik-turun".
1752
+ */
1753
+ private replaceEntry(id: number, line: string): boolean {
1754
+ const index = this.ids.indexOf(id)
1755
+ if (index < 0) return false
1756
+ this.lines[index] = line
1757
+ this.rowCache.delete(id)
1758
+ return true
1759
+ }
1760
+
1611
1761
  private appendWithSource(
1612
1762
  line: string,
1613
1763
  meta: TranscriptMeta,
@@ -1643,6 +1793,7 @@ export class Transcript {
1643
1793
  const overflow = this.lines.length - TRANSCRIPT_CAP
1644
1794
  const removed = this.ids.splice(0, overflow)
1645
1795
  for (const removedId of removed) {
1796
+ this.rowCache.delete(removedId)
1646
1797
  this.sourceTexts.delete(removedId)
1647
1798
  this.assistantDisplay.delete(removedId)
1648
1799
  this.sourceOrders.delete(removedId)
@@ -1651,7 +1802,6 @@ export class Transcript {
1651
1802
  this.tables.splice(0, overflow)
1652
1803
  this.sourcePrefixes.splice(0, overflow)
1653
1804
  this.meta.splice(0, overflow)
1654
- this.rowCache.clear() // index bergeser setelah eviction
1655
1805
  this.evicted += overflow
1656
1806
  this.lines.unshift(c.muted(t("ts.evictMarker", { n: this.evicted })))
1657
1807
  this.tables.unshift(null)
@@ -1664,6 +1814,7 @@ export class Transcript {
1664
1814
  const overflow = this.lines.length - (TRANSCRIPT_CAP + 1)
1665
1815
  const removed = this.ids.splice(1, overflow)
1666
1816
  for (const removedId of removed) {
1817
+ this.rowCache.delete(removedId)
1667
1818
  this.sourceTexts.delete(removedId)
1668
1819
  this.assistantDisplay.delete(removedId)
1669
1820
  this.sourceOrders.delete(removedId)
@@ -1672,7 +1823,6 @@ export class Transcript {
1672
1823
  this.tables.splice(1, overflow)
1673
1824
  this.sourcePrefixes.splice(1, overflow)
1674
1825
  this.meta.splice(1, overflow)
1675
- this.rowCache.clear() // index bergeser setelah eviction
1676
1826
  this.evicted += overflow
1677
1827
  this.lines[0] = c.muted(t("ts.evictMarker", { n: this.evicted }))
1678
1828
  }
@@ -69,9 +69,28 @@ export async function executeTurn(
69
69
  // the kernel's context guard.
70
70
  }
71
71
 
72
+ // Resolve once for the turn, same rationale: the host may raise the step
73
+ // limit after a previous `max_steps_exceeded`, and the whole turn must see
74
+ // one consistent ceiling. Invalid values keep the validated numeric fallback.
75
+ let maxSteps = s.maxSteps;
76
+ try {
77
+ const resolved = s.maxStepsForRun?.();
78
+ if (typeof resolved === "number" && Number.isSafeInteger(resolved) && resolved >= 1) {
79
+ maxSteps = resolved;
80
+ }
81
+ } catch {
82
+ // Keep the validated numeric fallback.
83
+ }
84
+
72
85
  while (true) {
73
86
  if (signal.aborted) throw abortError(signal);
74
- if (stepIndex >= s.maxSteps) throw new AgentError("max_steps_exceeded", `exceeded ${s.maxSteps} steps`);
87
+ if (stepIndex >= maxSteps)
88
+ throw new AgentError("max_steps_exceeded", `exceeded ${maxSteps} steps`, {
89
+ // Host memakai jumlah langkah terpakai untuk menaikkan batas secara
90
+ // adaptif (T-008). Tanpa ini, host hanya tahu batasnya, bukan kebutuhan
91
+ // nyatanya, dan tangga bisa naik lebih sedikit daripada yang diperlukan.
92
+ details: { steps: stepIndex, maxSteps },
93
+ });
75
94
 
76
95
  // Budget policy → compaction strategy (separate concerns, orchestrated here).
77
96
  // The budget counts messages plus the fixed per-request cost of the system
@@ -64,6 +64,10 @@ export interface SessionConfig {
64
64
  /** Resolve a model-specific context limit for each run. Additive app seam;
65
65
  * the numeric option remains the fallback for existing library callers. */
66
66
  contextWindowTokensForModel?: (model?: string) => number;
67
+ /** Resolve the step limit for each run. Additive app seam (mirrors
68
+ * `contextWindowTokensForModel`): the host may raise the limit as the session
69
+ * proves it needs more steps, while `maxSteps` stays the validated fallback. */
70
+ maxStepsForRun?: () => number;
67
71
  /** Batas output model (`max_output_tokens`) bila endpoint melaporkannya.
68
72
  * Seam aditif: dipakai loop untuk menghitung reserve output proporsional —
69
73
  * tanpa ini kernel hanya bisa memakai reserve angka tetap, yang terlalu
@@ -158,6 +162,7 @@ export interface SessionInternal {
158
162
  readonly compaction: CompactionStrategy;
159
163
  readonly recovery: RecoveryPolicy;
160
164
  readonly maxSteps: number;
165
+ readonly maxStepsForRun?: () => number;
161
166
  readonly contextWindowTokens: number;
162
167
  readonly contextWindowTokensForModel?: (model?: string) => number;
163
168
  readonly maxOutputTokensForModel?: (model?: string) => number | undefined;
@@ -201,6 +206,7 @@ export function createSession(config: SessionConfig): Session {
201
206
  compaction: config.compaction ?? mechanicalCompaction,
202
207
  recovery: config.recovery ?? defaultRecoveryPolicy,
203
208
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS,
209
+ maxStepsForRun: config.maxStepsForRun,
204
210
  contextWindowTokens: config.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS,
205
211
  contextWindowTokensForModel: config.contextWindowTokensForModel,
206
212
  maxOutputTokensForModel: config.maxOutputTokensForModel,