minicode-ai 0.25.0 → 0.27.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 (56) hide show
  1. package/README.md +3 -1
  2. package/cli/commands/config.ts +123 -0
  3. package/cli/commands.ts +23 -2
  4. package/cli/context-command-run.ts +159 -0
  5. package/cli/context-command.ts +87 -0
  6. package/cli/index.ts +48 -0
  7. package/cli/setup.ts +107 -8
  8. package/cli/tui.ts +8 -9
  9. package/docs/TERMINAL_CONTRACT.md +32 -1
  10. package/docs/config.md +29 -1
  11. package/docs/environment.md +3 -1
  12. package/docs/getting-started.md +11 -3
  13. package/docs/repl.md +1 -0
  14. package/package.json +1 -1
  15. package/src/app/session.ts +187 -17
  16. package/src/config.ts +19 -8
  17. package/src/constants.ts +33 -4
  18. package/src/lib/net.ts +6 -15
  19. package/src/lib/public-http.ts +128 -0
  20. package/src/policy/auto-resume.ts +63 -0
  21. package/src/policy/compaction.ts +354 -70
  22. package/src/policy/context-budget.ts +4 -6
  23. package/src/policy/context-window-assign.ts +114 -0
  24. package/src/policy/context-window-catalog.ts +4 -1
  25. package/src/policy/context-window-presets.ts +165 -0
  26. package/src/policy/context-window.ts +105 -4
  27. package/src/policy/context.ts +27 -10
  28. package/src/policy/executor.ts +69 -27
  29. package/src/policy/microcompact.ts +76 -15
  30. package/src/policy/recovery-budget.ts +281 -0
  31. package/src/policy/step-escalation.ts +82 -0
  32. package/src/policy/tokenizer-registry.ts +1 -0
  33. package/src/providers/detect.ts +13 -7
  34. package/src/providers/guards.ts +41 -2
  35. package/src/providers/provision.ts +8 -4
  36. package/src/repo/repomap.ts +180 -23
  37. package/src/runtime/child-execution.ts +4 -2
  38. package/src/runtime/execution-backend.ts +3 -0
  39. package/src/sandbox/os.ts +53 -9
  40. package/src/session/context-assembly.ts +11 -7
  41. package/src/session/persistence.ts +19 -3
  42. package/src/tools/bash.ts +12 -9
  43. package/src/tools/code_run.ts +19 -20
  44. package/src/tools/task.ts +4 -1
  45. package/src/tools/web_fetch.ts +13 -19
  46. package/src/ui/assistant/simple.ts +61 -10
  47. package/src/ui/i18n/en.ts +15 -0
  48. package/src/ui/i18n/id.ts +15 -0
  49. package/src/ui/input/prompt-engine.ts +53 -21
  50. package/src/ui/render/activity-group.ts +8 -0
  51. package/src/ui/render/activity-panel.ts +20 -2
  52. package/src/ui/screens/model-manager.ts +6 -1
  53. package/src/ui/tui/app.ts +26 -11
  54. package/src/ui/tui/transcript.ts +175 -29
  55. package/vendor/minicore/src/core/loop.ts +20 -1
  56. package/vendor/minicore/src/core/session.ts +6 -0
@@ -129,6 +129,38 @@ interface ProjectedLineCache {
129
129
  rows: TranscriptRow[]
130
130
  }
131
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
+
132
164
  function formatElapsed(ms: number): string {
133
165
  const seconds = Math.max(0, Math.floor(ms / 1000))
134
166
  if (seconds < 60) return `${seconds}s`
@@ -214,7 +246,7 @@ export class Transcript {
214
246
  * P2.2: cache proyeksi PER BARIS logis. Transkrip append-only, jadi baris
215
247
  * lama tidak perlu di-wrap/markdown ulang setiap frame. Cache di-key oleh
216
248
  * semua input yang memengaruhi hasil (width, teks, source, prefix, tabel,
217
- * fence state) dan dibuang saat eviction (index bergeser) atau clear.
249
+ * fence state), memakai ID stabil; eviction hanya membuang ID yang hilang.
218
250
  */
219
251
  private rowCache = new Map<number, ProjectedLineCache>()
220
252
  private ids: number[] = []
@@ -242,6 +274,17 @@ export class Transcript {
242
274
  /** Baris thinking turn berjalan (mode AREA, Fase 3): dirender sebagai blok
243
275
  * live maks 10 baris, bukan di-commit per baris. Diringkas saat turn selesai. */
244
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
245
288
  private meta: TranscriptMeta[] = []
246
289
  private evicted = 0
247
290
  private hasEvictMarker = false
@@ -314,12 +357,21 @@ export class Transcript {
314
357
  bus.on("provider:text", (e: { text: string }) => this.stream(e.text)),
315
358
  bus.on("turn:started", () => {
316
359
  this.commit()
317
- 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
318
367
  this.activityFold = []
319
368
  }),
320
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)
321
374
  this.commit()
322
- this.commitThinking()
323
375
  }),
324
376
  bus.on("execution:started", () => {
325
377
  this.commit()
@@ -361,8 +413,13 @@ export class Transcript {
361
413
  fixed: impossible[1] ?? "0",
362
414
  trigger: impossible[2] ?? "0",
363
415
  })
364
- if (clean.startsWith("llm-failed:"))
365
- 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
+ }
366
423
  return t("ts.compacted", { reason: clean })
367
424
  }
368
425
 
@@ -434,6 +491,16 @@ export class Transcript {
434
491
  // Mode AREA (Fase 3): tahan baris di buffer, dirender sebagai blok live
435
492
  // terbatas (projectAll). JANGAN di-commit per baris — area yang
436
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
+ }
437
504
  this.thinkingTail += clean
438
505
  const parts = this.thinkingTail.split("\n")
439
506
  for (let i = 0; i < parts.length - 1; i++) this.thinkingArea.push(parts[i] ?? "")
@@ -465,10 +532,15 @@ export class Transcript {
465
532
  }
466
533
 
467
534
  /** Selesaikan fase thinking.
468
- * - 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.
469
537
  * - Legacy: flush ekor berindentasi.
470
- * - Minimized: penanda hilang. */
471
- 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 {
472
544
  if (this.thinkingAreaMode()) {
473
545
  const lines = [...this.thinkingArea]
474
546
  if (this.thinkingTail) {
@@ -477,13 +549,38 @@ export class Transcript {
477
549
  }
478
550
  this.thinkingArea = []
479
551
  this.thinkingBuf = ""
552
+ this.thinkingSeenSegment = true
480
553
  if (lines.length > 0) {
481
554
  // Detail penuh tidak hilang: masuk buffer `/expand`.
482
555
  this.uiState.rememberCollapsedSection("thinking", lines.join("\n"))
483
- this.append(
484
- c.thinking(` + ${t("panel.thinking")} · ${t("panel.lines", { n: lines.length })}`),
485
- { 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 })}`,
486
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
487
584
  }
488
585
  return
489
586
  }
@@ -856,7 +953,7 @@ export class Transcript {
856
953
  const fenceState = assistant ? committedFence(raw) : "outside"
857
954
  const source = this.sourceTexts.get(id) ?? ""
858
955
  const prefix = this.sourcePrefixes[i] ?? ""
859
- const cached = this.rowCache.get(i)
956
+ const cached = this.rowCache.get(id)
860
957
  if (
861
958
  cached &&
862
959
  cached.width === w &&
@@ -874,7 +971,7 @@ export class Transcript {
874
971
  const produced = table
875
972
  ? this.projectTable(table, id, w)
876
973
  : this.projectText(raw, source, id, w, true, prefix, assistant, fenceState)
877
- this.rowCache.set(i, {
974
+ this.rowCache.set(id, {
878
975
  width: w,
879
976
  id,
880
977
  raw,
@@ -1163,12 +1260,15 @@ export class Transcript {
1163
1260
  private presentationEvent(event: UiPresentationEvent): void {
1164
1261
  if (event.type === "turn.started") {
1165
1262
  this.commit()
1166
- 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
1167
1267
  this.activityFold = []
1168
1268
  return
1169
1269
  }
1170
1270
  if (event.type === "turn.completed") {
1171
- this.commitThinking()
1271
+ this.commitThinking(true)
1172
1272
  // Flush panel SEBELUM commit jawaban agar urutan persist = transient (panel di
1173
1273
  // atas jawaban; tanpa ini panel "lompat" ke bawah saat turn selesai).
1174
1274
  this.flushActivityFold()
@@ -1181,7 +1281,7 @@ export class Transcript {
1181
1281
  return
1182
1282
  }
1183
1283
  if (event.type === "turn.failed" || event.type === "turn.cancelled") {
1184
- this.commitThinking()
1284
+ this.commitThinking(true)
1185
1285
  this.flushActivityFold()
1186
1286
  this.commit()
1187
1287
  return
@@ -1291,8 +1391,16 @@ export class Transcript {
1291
1391
  status === "denied"
1292
1392
  ? (desc?.denyReason ?? activity?.denyReason ?? (event.reason ? String(event.reason) : ""))
1293
1393
  : ""
1294
- const message = event.message
1295
- ? `: ${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, "…")}`
1296
1404
  : denyReason
1297
1405
  ? `: ${truncateToWidth(sanitizeAnsi(denyReason), 200, "…").split("\n")[0] ?? ""}`
1298
1406
  : ""
@@ -1301,9 +1409,17 @@ export class Transcript {
1301
1409
  // aktivitas aktif, baris ledger per-tool TIDAK boleh menghilang diam-diam
1302
1410
  // — ditahan lalu dirangkum saat turn selesai (panel: per keluarga tool;
1303
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.
1304
1419
  if (this.uiState.minimizeActivity || this.uiState.activityPanel) {
1305
1420
  this.activityFold.push({ name, status, line })
1306
- return
1421
+ // Yang berhasil sudah diwakili baris grup → tak perlu baris individual.
1422
+ if (status === "completed") return
1307
1423
  }
1308
1424
  this.append(paintLedger(status, line), {
1309
1425
  kind: "activity",
@@ -1521,7 +1637,20 @@ export class Transcript {
1521
1637
  const fold = this.activityFold
1522
1638
  this.activityFold = []
1523
1639
  if (fold.length === 0) return
1524
- // 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.
1525
1654
  if (this.uiState.activityPanel) {
1526
1655
  const activities = fold.map((e) => ({
1527
1656
  toolCallId: "",
@@ -1531,14 +1660,9 @@ export class Transcript {
1531
1660
  }))
1532
1661
  const lines = renderActivityPanel(activities, { maxRows: 10 })
1533
1662
  if (lines.length === 0) return
1534
- this.uiState.rememberCollapsedSection("activity", fold.map((e) => e.line).join("\n"))
1535
1663
  for (const line of lines) this.append(line, { kind: "activity" })
1536
1664
  return
1537
1665
  }
1538
- const count = (status: string) => fold.reduce((n, e) => n + (e.status === status ? 1 : 0), 0)
1539
- const ok = count("completed")
1540
- const failed = count("failed")
1541
- const denied = count("denied")
1542
1666
  const names = [...new Set(fold.map((e) => e.name))]
1543
1667
  const shown = names.slice(0, 3).join(", ")
1544
1668
  const more = names.length - 3
@@ -1552,8 +1676,6 @@ export class Transcript {
1552
1676
  .join(", ")
1553
1677
  const statPart = stats ? ` · ${stats}` : ""
1554
1678
  const line = ` ${glyphs.check} ${fold.length} tool${fold.length > 1 ? "s" : ""}${namePart}${statPart}`
1555
- // Detail tetap tersedia via /expand (tidak dibuang).
1556
- this.uiState.rememberCollapsedSection("activity", fold.map((e) => e.line).join("\n"))
1557
1679
  this.append(line, { kind: "activity" })
1558
1680
  }
1559
1681
 
@@ -1612,6 +1734,30 @@ export class Transcript {
1612
1734
  this.appendWithSource(line, meta, stripSgr(sanitizeAnsi(line)))
1613
1735
  }
1614
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
+
1615
1761
  private appendWithSource(
1616
1762
  line: string,
1617
1763
  meta: TranscriptMeta,
@@ -1647,6 +1793,7 @@ export class Transcript {
1647
1793
  const overflow = this.lines.length - TRANSCRIPT_CAP
1648
1794
  const removed = this.ids.splice(0, overflow)
1649
1795
  for (const removedId of removed) {
1796
+ this.rowCache.delete(removedId)
1650
1797
  this.sourceTexts.delete(removedId)
1651
1798
  this.assistantDisplay.delete(removedId)
1652
1799
  this.sourceOrders.delete(removedId)
@@ -1655,7 +1802,6 @@ export class Transcript {
1655
1802
  this.tables.splice(0, overflow)
1656
1803
  this.sourcePrefixes.splice(0, overflow)
1657
1804
  this.meta.splice(0, overflow)
1658
- this.rowCache.clear() // index bergeser setelah eviction
1659
1805
  this.evicted += overflow
1660
1806
  this.lines.unshift(c.muted(t("ts.evictMarker", { n: this.evicted })))
1661
1807
  this.tables.unshift(null)
@@ -1668,6 +1814,7 @@ export class Transcript {
1668
1814
  const overflow = this.lines.length - (TRANSCRIPT_CAP + 1)
1669
1815
  const removed = this.ids.splice(1, overflow)
1670
1816
  for (const removedId of removed) {
1817
+ this.rowCache.delete(removedId)
1671
1818
  this.sourceTexts.delete(removedId)
1672
1819
  this.assistantDisplay.delete(removedId)
1673
1820
  this.sourceOrders.delete(removedId)
@@ -1676,7 +1823,6 @@ export class Transcript {
1676
1823
  this.tables.splice(1, overflow)
1677
1824
  this.sourcePrefixes.splice(1, overflow)
1678
1825
  this.meta.splice(1, overflow)
1679
- this.rowCache.clear() // index bergeser setelah eviction
1680
1826
  this.evicted += overflow
1681
1827
  this.lines[0] = c.muted(t("ts.evictMarker", { n: this.evicted }))
1682
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,