minicode-ai 0.21.0 → 0.23.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 (72) hide show
  1. package/README.md +1 -1
  2. package/cli/commands/exec.ts +44 -1
  3. package/cli/commands.ts +15 -2
  4. package/cli/index.ts +11 -0
  5. package/cli/setup.ts +88 -33
  6. package/cli/tui.ts +3 -3
  7. package/docs/TERMINAL_CONTRACT.md +69 -13
  8. package/docs/architecture.md +9 -5
  9. package/docs/concepts.md +1 -1
  10. package/docs/contributing.md +2 -1
  11. package/docs/environment.md +4 -0
  12. package/docs/policy-sandbox.md +6 -1
  13. package/docs/security.md +12 -4
  14. package/docs/skills.md +1 -1
  15. package/package.json +2 -2
  16. package/src/app/session.ts +129 -20
  17. package/src/config.ts +108 -8
  18. package/src/constants.ts +29 -4
  19. package/src/daemon/discovery.ts +24 -0
  20. package/src/policy/bash-guard.ts +170 -6
  21. package/src/policy/compaction.ts +61 -7
  22. package/src/policy/context-budget.ts +132 -0
  23. package/src/policy/context-escalation.ts +140 -0
  24. package/src/policy/context-window.ts +47 -9
  25. package/src/policy/context.ts +10 -1
  26. package/src/policy/jail.ts +10 -22
  27. package/src/policy/microcompact.ts +162 -0
  28. package/src/policy/permission.ts +9 -6
  29. package/src/presentation/projection.ts +1 -1
  30. package/src/providers/anthropic.ts +31 -7
  31. package/src/providers/detect.ts +128 -13
  32. package/src/providers/provision.ts +78 -1
  33. package/src/providers/responses.ts +14 -2
  34. package/src/providers/sse-bounds.ts +16 -2
  35. package/src/session/persistence.ts +56 -0
  36. package/src/ui/approval/prompt.ts +17 -6
  37. package/src/ui/assistant/simple.ts +1 -1
  38. package/src/ui/footer.ts +2 -2
  39. package/src/ui/i18n/en.ts +28 -5
  40. package/src/ui/i18n/id.ts +30 -5
  41. package/src/ui/input/input.ts +2 -2
  42. package/src/ui/input/prompt-engine.ts +6 -0
  43. package/src/ui/render/activity-panel.ts +21 -3
  44. package/src/ui/render/diff.ts +51 -2
  45. package/src/ui/render/highlight.ts +68 -37
  46. package/src/ui/render/hint.ts +28 -0
  47. package/src/ui/render/logo.ts +91 -0
  48. package/src/ui/render/sanitize.ts +5 -1
  49. package/src/ui/render/session-summary.ts +28 -5
  50. package/src/ui/render/table-grid.ts +123 -13
  51. package/src/ui/render/table.ts +4 -2
  52. package/src/ui/render/theme.ts +16 -3
  53. package/src/ui/render/width.ts +35 -6
  54. package/src/ui/render/wrap.ts +28 -6
  55. package/src/ui/runtime/loading-bar.ts +17 -5
  56. package/src/ui/runtime/screen.ts +4 -2
  57. package/src/ui/screens/dialog.ts +23 -2
  58. package/src/ui/screens/form.ts +71 -33
  59. package/src/ui/screens/lifecycle.ts +80 -0
  60. package/src/ui/screens/model-manager.ts +85 -83
  61. package/src/ui/screens/picker.ts +39 -25
  62. package/src/ui/screens/provider-manager.ts +58 -55
  63. package/src/ui/screens/watchdog.ts +27 -0
  64. package/src/ui/screens/wizard.ts +12 -1
  65. package/src/ui/tui/app.ts +62 -22
  66. package/src/ui/tui/transcript.ts +93 -23
  67. package/vendor/minicore/src/core/compact.ts +10 -0
  68. package/vendor/minicore/src/core/errors.ts +11 -1
  69. package/vendor/minicore/src/core/executor.ts +6 -1
  70. package/vendor/minicore/src/core/loop.ts +92 -2
  71. package/vendor/minicore/src/core/session.ts +8 -0
  72. package/vendor/minicore/src/providers/openai-compat.ts +45 -3
@@ -10,6 +10,17 @@ import { openAltScreen } from "../runtime/screen.ts"
10
10
  import { dialogBox } from "./dialog.ts"
11
11
  import { runForm, validateUrl } from "./form.ts"
12
12
  import { runPicker } from "./picker.ts"
13
+ import { withTimeout } from "./watchdog.ts"
14
+
15
+ /**
16
+ * Batas tunggu simpan-provider (audit 2026-11-12, MEDIUM-7).
17
+ *
18
+ * `detect()` sendiri punya timeout, tapi callback controller juga melakukan
19
+ * I/O config (kunci, tulis disk) yang bisa lambat; tanpa batas, kotak
20
+ * "mendeteksi…" bertahan selama proses menggantung dan user tak punya jalan
21
+ * keluar (tak ada Esc di kotak progres). Timeout = pesan jujur, UI pulih.
22
+ * Semantik timeout di-share lewat withTimeout() (paritas picker/manager).
23
+ */
13
24
 
14
25
  export interface WizardPreset {
15
26
  label: string
@@ -148,7 +159,7 @@ export async function runSetupWizardView(opts: SetupWizardViewOptions): Promise<
148
159
  )
149
160
  screen.paintRegion(box.lines, box.topRow)
150
161
  try {
151
- const message = await opts.onSubmit(targetUrl, apiKey)
162
+ const message = await withTimeout(() => opts.onSubmit(targetUrl, apiKey), 60_000)
152
163
  // Pesan dari jaringan (nama model/gateway) — sanitasi sebelum tampil.
153
164
  screen.clearRegion()
154
165
  const doneBox = dialogBox(
package/src/ui/tui/app.ts CHANGED
@@ -131,6 +131,19 @@ export function timerHighlight(ms: number): TimerHighlight {
131
131
  return "seconds"
132
132
  }
133
133
 
134
+ /**
135
+ * Indeks awal jendela dropdown yang menjaga item terpilih (`sel`) selalu tampil.
136
+ * Sebelum A1, jendela selalu `slice(0, visible)` sehingga `sel >= visible` tak
137
+ * pernah tersorot tetapi Enter tetap mengirim `hints[sel]` — perintah destruktif
138
+ * yang tak terlihat. Kontrak: untuk `0 <= sel < total` berlaku
139
+ * `start <= sel < start + min(visible, total)`.
140
+ */
141
+ export function dropdownWindowStart(sel: number, visible: number, total: number): number {
142
+ const v = Math.max(1, Math.floor(visible))
143
+ if (total <= v) return 0
144
+ return Math.max(0, Math.min(sel - v + 1, total - v))
145
+ }
146
+
134
147
  interface FrameLayout {
135
148
  frame: string[]
136
149
  cursor: { row: number; col: number }
@@ -292,8 +305,6 @@ export class TuiApp {
292
305
  */
293
306
  private busUnsubs: (() => void)[] = []
294
307
  private repaintTimer: ReturnType<typeof setTimeout> | undefined
295
- /** Ukuran transkrip saat terakhir ikut ekor (basis indikator "baru"). */
296
- private tailSize = 0
297
308
  /** Ukuran transkrip saat mulai scroll ke atas (basis hitung baris baru). */
298
309
  private scrollBase = 0
299
310
  /** Panjang visual terakhir (kunci posisi baca agar stream tak merampasnya). */
@@ -486,8 +497,7 @@ export class TuiApp {
486
497
  this.thinkingActive = false
487
498
  })
488
499
  sub("context:compacted")
489
- this.tailSize = this.transcript.total()
490
- this.scrollBase = this.tailSize
500
+ this.scrollBase = this.transcript.total()
491
501
  this.setMouseMode(mouseSelectionEnabled() ? "drag" : "off")
492
502
  this.paint(screen)
493
503
  await done
@@ -694,7 +704,10 @@ export class TuiApp {
694
704
  if (this.state.line || this.editing) {
695
705
  this.state = createState()
696
706
  this.histIdx = -1
697
- this.editing = false
707
+ // Prompt TETAP tampil setelah Esc: kontrak I13 mensyaratkan prompt
708
+ // ada saat idle, dan menyembunyikannya membuat layar terlihat mati
709
+ // sampai user menekan tombol berikutnya (audit 2026-11-12, MEDIUM-4).
710
+ this.editing = true
698
711
  this.paintCurrent()
699
712
  }
700
713
  return
@@ -869,6 +882,9 @@ export class TuiApp {
869
882
  this.followTail()
870
883
  this.abortHintOn = false
871
884
  if (!line) {
885
+ // Enter pada baris kosong tetap idle: prompt harus langsung kembali
886
+ // (I13), bukan menghilang sampai ketikan berikutnya.
887
+ this.editing = true
872
888
  this.paintCurrent()
873
889
  return
874
890
  }
@@ -1120,8 +1136,7 @@ export class TuiApp {
1120
1136
  if (this.scrollBack === 0 && pages > 0) this.scrollBase = this.transcript.total()
1121
1137
  this.scrollBack = Math.max(0, Math.round(this.scrollBack + pages * page))
1122
1138
  if (this.scrollBack === 0) {
1123
- this.tailSize = this.transcript.total()
1124
- this.scrollBase = this.tailSize
1139
+ this.scrollBase = this.transcript.total()
1125
1140
  }
1126
1141
  this.paintCurrent()
1127
1142
  }
@@ -1130,7 +1145,7 @@ export class TuiApp {
1130
1145
  * Scroll per BARIS (bukan per halaman) — dipakai auto-scroll seleksi agar
1131
1146
  * gulirnya halus & presisi. `n` = baris terbungkus (+ = ke atas/lama,
1132
1147
  * - = ke bawah/baru); di-clamp ke [0, wrapped - viewH]. Menjaga basis
1133
- * `tailSize`/`scrollBase` sama seperti `scrollBy`.
1148
+ * `scrollBase` sama seperti `scrollBy`.
1134
1149
  */
1135
1150
  private scrollRows(n: number): void {
1136
1151
  const cols = process.stdout.columns || 80
@@ -1141,8 +1156,7 @@ export class TuiApp {
1141
1156
  if (this.scrollBack === 0 && n > 0) this.scrollBase = this.transcript.total()
1142
1157
  this.scrollBack = Math.max(0, Math.min(this.scrollBack + n, maxBack))
1143
1158
  if (this.scrollBack === 0) {
1144
- this.tailSize = this.transcript.total()
1145
- this.scrollBase = this.tailSize
1159
+ this.scrollBase = this.transcript.total()
1146
1160
  }
1147
1161
  this.paintCurrent()
1148
1162
  }
@@ -1165,8 +1179,7 @@ export class TuiApp {
1165
1179
  this.scrollBack = Math.max(0, curWrapped - viewH)
1166
1180
  } else {
1167
1181
  this.scrollBack = 0
1168
- this.tailSize = this.transcript.total()
1169
- this.scrollBase = this.tailSize
1182
+ this.scrollBase = this.transcript.total()
1170
1183
  }
1171
1184
  this.paintCurrent()
1172
1185
  }
@@ -1174,8 +1187,7 @@ export class TuiApp {
1174
1187
  /** Kembali ke ekor: dipakai tiap ketikan/submit baru (I18). */
1175
1188
  private followTail(): void {
1176
1189
  this.scrollBack = 0
1177
- this.tailSize = this.transcript.total()
1178
- this.scrollBase = this.tailSize
1190
+ this.scrollBase = this.transcript.total()
1179
1191
  }
1180
1192
 
1181
1193
  /** Kosongkan transkrip (/clear): viewport + basis scroll ikut di-reset agar
@@ -1234,7 +1246,10 @@ export class TuiApp {
1234
1246
  const content = this.thinkingActive ? thinkingDots(now, start) : status
1235
1247
  return [this.activityRow(content, cols)]
1236
1248
  }
1237
- if (!this.editing) return [""]
1249
+ // Idle: prompt tetap tampil. Dulu baris kosong menggantikannya sehingga
1250
+ // setelah Esc/Enter-kosong layar terlihat mati (I13: prompt tampil saat
1251
+ // boot/idle) — audit 2026-11-12, MEDIUM-4.
1252
+ if (!this.editing) return [chunkByWidth(PROMPT_FIRST, Math.max(10, cols))[0] ?? ""]
1238
1253
  return this.composerLayout(cols).rows
1239
1254
  }
1240
1255
 
@@ -1277,7 +1292,11 @@ export class TuiApp {
1277
1292
  * jalan atau sudah quit.
1278
1293
  */
1279
1294
  repaint(): void {
1280
- if (!this.quitRequested) this.paintCurrent()
1295
+ // Suspend = pemilik layar lain (popup/approval) sedang melukis region
1296
+ // sendiri; melukis frame penuh di sini akan menimpanya. Sebelumnya guard
1297
+ // ini hanya ada di `requestPaint`, jadi API publik tak konsisten (audit
1298
+ // 2026-11-12, MEDIUM-9).
1299
+ if (!this.quitRequested && this.suspended === 0) this.paintCurrent()
1281
1300
  }
1282
1301
 
1283
1302
  private viewportHeight(rows: number, cols: number): number {
@@ -1401,11 +1420,19 @@ export class TuiApp {
1401
1420
  const hints = this.host.listCommands(this.state.line)
1402
1421
  if (!hints.length) return []
1403
1422
  const room = Math.max(0, rows - 2 - this.composerHeight(cols, busy) - 3)
1404
- const shown = hints.slice(0, Math.min(MAX_DROPDOWN_ROWS, room))
1423
+ const visible = Math.max(1, Math.min(MAX_DROPDOWN_ROWS, room))
1424
+ const total = hints.length
1425
+ // A1: jendela MENGIKUTI `sel`, bukan selalu slice dari index 0. `sel` bisa
1426
+ // wrap melewati jumlah baris terlihat (mis. 24 perintah → sel 9..23), dan
1427
+ // bila jendela tetap index 0, tak ada baris tersorot tetapi Enter tetap
1428
+ // mengirim hints[sel] — perintah yang tak pernah terlihat (destruktif untuk
1429
+ // /clear, /undo). `start` menjaga item terpilih selalu tampil.
1430
+ const start = dropdownWindowStart(this.state.sel, visible, total)
1431
+ const shown = hints.slice(start, start + visible)
1405
1432
  const w = Math.max(10, cols)
1406
1433
  const out: string[] = []
1407
1434
  shown.forEach((h, i) => {
1408
- const picked = i === this.state.sel
1435
+ const picked = start + i === this.state.sel
1409
1436
  const text = sanitizeAnsiLine(h).replace(/^\/+/, "")
1410
1437
  out.push(picked ? c.accent(c.bold(text)) : text)
1411
1438
  })
@@ -1592,8 +1619,11 @@ export class TuiApp {
1592
1619
  private copySelection(): void {
1593
1620
  const selection = this.selection
1594
1621
  if (!selection) return
1595
- const text = this.transcript.selectionText(selection.anchor, selection.focus).trim()
1596
- if (!text) {
1622
+ // Salin teks ASLI (bukan `.trim()`): indentasi baris pertama dan newline di
1623
+ // ekor adalah bagian dari konten yang dipilih pengguna (blok kode/teks
1624
+ // berindentasi). Trim hanya untuk mendeteksi "seleksi kosong".
1625
+ const text = this.transcript.selectionText(selection.anchor, selection.focus)
1626
+ if (!text.trim()) {
1597
1627
  this.selection = null
1598
1628
  this.paintCurrent()
1599
1629
  return
@@ -1625,9 +1655,16 @@ export class TuiApp {
1625
1655
  this.turnStartedAt = 0
1626
1656
  }
1627
1657
  const newCount = this.scrollBack > 0 ? this.transcript.total() - this.scrollBase : 0
1658
+ // Baris indikator WAJIB dipotong ke lebar frame seperti baris lain: teks
1659
+ // locale id lebih panjang dari terminal sempit (51 kolom untuk abort hint),
1660
+ // dan baris lebih lebar dari `cols` membungkus sendiri → frame jadi
1661
+ // `rows+1`, alt-screen scroll, seluruh diff CUP meleset (audit 2026-11-12,
1662
+ // HIGH-3).
1628
1663
  const indicator: string[] = []
1629
- if (busy && this.abortHintOn) indicator.push(c.warning(t("app.abortHint")))
1630
- else if (newCount > 0) indicator.push(c.muted(t("app.newBelow", { n: newCount })))
1664
+ if (busy && this.abortHintOn)
1665
+ indicator.push(c.warning(truncateToWidth(t("app.abortHint"), width)))
1666
+ else if (newCount > 0)
1667
+ indicator.push(c.muted(truncateToWidth(t("app.newBelow", { n: newCount }), width)))
1631
1668
 
1632
1669
  const allMenu = this.menuRows(height, width, busy)
1633
1670
  const allComposer = this.composerRows(width, snap, busy, now)
@@ -1681,6 +1718,9 @@ export class TuiApp {
1681
1718
  } else {
1682
1719
  shownComposer = allComposer.slice(0, composerH)
1683
1720
  cursorRow = viewH + menu.length + indicator.length + 1
1721
+ // Kursor parkir tepat setelah prompt saat idle (bukan kolom 1) supaya
1722
+ // caret terlihat di tempat user akan mengetik.
1723
+ if (!busy) cursorCol = displayWidth(PROMPT_FIRST) + 1
1684
1724
  }
1685
1725
 
1686
1726
  const started = this.turnStartedAt || now
@@ -17,7 +17,7 @@ import type {
17
17
  } from "../contract.ts"
18
18
  import { t } from "../i18n/locale.ts"
19
19
  import { renderActivityPanel } from "../render/activity-panel.ts"
20
- import { paintLedger, runMarker, statusGlyph, statusWord } from "../render/ledger.ts"
20
+ import { paintLedger, runMarker, statusWord } from "../render/ledger.ts"
21
21
  import { parseFence, renderInline } from "../render/markdown.ts"
22
22
  import { type MarkdownTable, parseMarkdownBlocks } from "../render/markdown-table.ts"
23
23
  import { sanitizeAnsi, sanitizeAnsiLine, stripSgr } from "../render/sanitize.ts"
@@ -33,6 +33,10 @@ import { defaultUiState, type UiSessionState } from "../session-state.ts"
33
33
  // substansi berbeda (viewport vs riwayat yang bisa di-replay).
34
34
  export const TRANSCRIPT_CAP = 5000
35
35
  export const TRANSCRIPT_TEXT_MAX_CHARS = 1_000_000
36
+ /** Baris pending lebih panjang dari ini tidak dimemo (kunci = isi baris). */
37
+ const PENDING_MEMO_LINE_MAX = 4096
38
+ /** Batas entri memo proyeksi pending sebelum dibuang seluruhnya. */
39
+ const PENDING_MEMO_MAX_ENTRIES = 4000
36
40
  /** Baris thinking yang terlihat di area live (Fase 3). */
37
41
  const MAX_THINKING_ROWS = 10
38
42
  const TRANSCRIPT_TRUNCATION_MARKER = "… [transcript truncated: turn cap exceeded]"
@@ -319,7 +323,7 @@ export class Transcript {
319
323
  }),
320
324
  bus.on("provider:extension", (e: { kind: string; data: unknown }) => this.extension(e)),
321
325
  bus.on("context:compacted", (e: { reason: string }) =>
322
- this.push(c.muted(t("ts.compacted", { reason: sanitizeAnsiLine(e.reason ?? "") }))),
326
+ this.push(c.muted(this.compactedLabel(e.reason ?? ""))),
323
327
  ),
324
328
  ]
325
329
  if (opts.onPresentationEvent) {
@@ -327,6 +331,37 @@ export class Transcript {
327
331
  }
328
332
  }
329
333
 
334
+ /**
335
+ * Label hasil kompaksi yang JUJUR soal sebab dan akibat.
336
+ *
337
+ * Kernel mengirim `pressure:<level>` saat benar-benar menyusut dan
338
+ * `pressure:<level>:no-op` saat tak ada yang bisa dibuang. Dulu keduanya
339
+ * tampil sama ("dipadatkan: pressure:critical:no-op") sehingga sesi yang
340
+ * konteksnya TIDAK menyusut terlihat seakan berhasil dipadatkan — user lalu
341
+ * bingung kenapa turn berikut tetap gagal. Pemetaan ini memisahkan empat
342
+ * kondisi yang berbeda tindak lanjutnya: no-op, fixpoint, mustahil (biaya
343
+ * tetap), dan ringkasan LLM gagal.
344
+ */
345
+ private compactedLabel(reason: string): string {
346
+ const clean = sanitizeAnsiLine(reason)
347
+ if (!clean) return t("ts.compacted", { reason: "-" })
348
+ if (clean.endsWith(":no-op")) {
349
+ const base = clean.slice(0, -":no-op".length)
350
+ return t("ts.compactedNoOp", { reason: base })
351
+ }
352
+ const kept = /^fixpoint:(\d+)$/.exec(clean)
353
+ if (kept) return t("ts.compactedFixpoint", { kept: kept[1] ?? "0" })
354
+ const impossible = /^impossible:(\d+):(\d+)$/.exec(clean)
355
+ if (impossible)
356
+ return t("ts.compactedImpossible", {
357
+ fixed: impossible[1] ?? "0",
358
+ trigger: impossible[2] ?? "0",
359
+ })
360
+ if (clean.startsWith("llm-failed:"))
361
+ return t("ts.compactedLlmFailed", { reason: clean.slice("llm-failed:".length) })
362
+ return t("ts.compacted", { reason: clean })
363
+ }
364
+
330
365
  /** Teks model mengalir — ditahan sebagai ekor hidup sampai commit. */
331
366
  stream(text: string): void {
332
367
  if (!text) return
@@ -500,6 +535,7 @@ export class Transcript {
500
535
  clear(): void {
501
536
  this.lines = []
502
537
  this.rowCache.clear()
538
+ this.pendingRowMemo.clear()
503
539
  this.tables = []
504
540
  this.ids = []
505
541
  this.sourcePrefixes = []
@@ -750,7 +786,9 @@ export class Transcript {
750
786
  }
751
787
  // thinking/running aktif: bangun segar (jarang — hanya saat turn berjalan,
752
788
  // dan repaint-nya sudah dicoalesce 30ms, bukan per-keypress).
753
- const rows: TranscriptRow[] = [...this.committedRows(w), ...this.pendingRows(w)]
789
+ // Urutan: committed → activity (thinking/running/panel) → pending. Jawaban di
790
+ // ekor agar jangkar stabil saat streaming (activity mendorong histori, bukan jawaban).
791
+ const rows: TranscriptRow[] = [...this.committedRows(w)]
754
792
  if (!this.thinkingAreaMode() && this.thinkingTail) {
755
793
  for (const chunk of this.thinkingTail.split("\n")) {
756
794
  const chunkRows = chunk === "" ? [""] : wrapByWidth(chunk, w)
@@ -785,8 +823,10 @@ export class Transcript {
785
823
  })
786
824
  }
787
825
  // Panel aktivitas (Fase 2): baris grup tool terminal — tampil di bawah
788
- // running, di atas transkrip. Hanya saat ada activity.
826
+ // running, di atas jawaban (pending). Hanya saat ada activity.
789
827
  rows.push(...panel)
828
+ // Jawaban streaming berada di ekor (di bawah semua activity turn berjalan).
829
+ rows.push(...this.pendingRows(w))
790
830
  return rows
791
831
  }
792
832
 
@@ -847,13 +887,28 @@ export class Transcript {
847
887
  return rows
848
888
  }
849
889
 
890
+ /**
891
+ * Memo proyeksi baris pending, dikunci isi baris (bukan indeks).
892
+ *
893
+ * Cache `pendingProjection` lama hanya valid per `pendingVersion`, dan versi
894
+ * itu naik SETIAP delta — jadi tiap paint memproyeksikan ulang seluruh
895
+ * jawaban. Biayanya O(pending) per frame → total O(n²) per turn (audit
896
+ * 2026-11-12, CRITICAL-1): terukur 295 ms/frame pada 200 KB dan 1,4 dtk/
897
+ * frame pada batas 1 MB. Mayoritas baris saat streaming sudah final, jadi
898
+ * proyeksi per baris dimemo: yang tumbuh hanya baris terakhir.
899
+ *
900
+ * Dikunci juga `w` dan fenceState karena keduanya mengubah hasil proyeksi.
901
+ * Baris sangat panjang tidak dimemo (kuncinya akan sebesar barisnya sendiri).
902
+ */
903
+ private pendingRowMemo = new Map<string, TranscriptRow[]>()
904
+
850
905
  /** Proyeksi `pending` (jawaban streaming) + marker truncasi. Di-cache per
851
- * (width, pendingVersion, truncated): tanpa ini `parseMarkdownBlocks(pending)`
852
- * + `normalizeAssistantOutput` diulang penuh tiap paint saat jawaban panjang
853
- * mengalir (O(pending) per frame). pendingVersion naik di stream/commit/clear. */
906
+ * (width, pendingVersion, truncated) untuk hasil total; proyeksi per baris
907
+ * dimemo terpisah agar delta baru tidak memaksa kerja ulang penuh. */
854
908
  private pendingRows(w: number): TranscriptRow[] {
855
909
  if (!this.pending) {
856
910
  this.pendingProjection = null
911
+ this.pendingRowMemo.clear()
857
912
  return []
858
913
  }
859
914
  if (
@@ -872,8 +927,23 @@ export class Transcript {
872
927
  if (block.type === "table") rows.push(...this.projectTable(block.table, -1, w))
873
928
  else
874
929
  for (const line of block.text.split("\n")) {
930
+ const fenceState = pendingFence(line)
931
+ const memoKey =
932
+ line.length <= PENDING_MEMO_LINE_MAX ? `${w}\u0000${fenceState}\u0000${line}` : null
933
+ const memo = memoKey === null ? undefined : this.pendingRowMemo.get(memoKey)
934
+ if (memo) {
935
+ rows.push(...memo)
936
+ continue
937
+ }
875
938
  const clean = stripSgr(sanitizeAnsi(line))
876
- rows.push(...this.projectText(line, clean, -1, w, false, "", true, pendingFence(line)))
939
+ const produced = this.projectText(line, clean, -1, w, false, "", true, fenceState)
940
+ if (memoKey !== null) {
941
+ // Batas sederhana: memo adalah cache tampilan, bukan struktur
942
+ // data — dibuang seluruhnya saat terlalu besar.
943
+ if (this.pendingRowMemo.size >= PENDING_MEMO_MAX_ENTRIES) this.pendingRowMemo.clear()
944
+ this.pendingRowMemo.set(memoKey, produced)
945
+ }
946
+ rows.push(...produced)
877
947
  }
878
948
  }
879
949
  }
@@ -1094,20 +1164,22 @@ export class Transcript {
1094
1164
  return
1095
1165
  }
1096
1166
  if (event.type === "turn.completed") {
1097
- this.commit()
1098
1167
  this.commitThinking()
1168
+ // Flush panel SEBELUM commit jawaban agar urutan persist = transient (panel di
1169
+ // atas jawaban; tanpa ini panel "lompat" ke bawah saat turn selesai).
1170
+ this.flushActivityFold()
1171
+ this.commit()
1099
1172
  // minimizeActivity ON / activityPanel ON → fold meringkas sendiri (nama
1100
1173
  // tool + ok/gagal); turnSummary (turn · files · durasi) dilewati agar
1101
1174
  // tidak ada dua ringkasan.
1102
1175
  if (!this.uiState.minimizeActivity && !this.uiState.activityPanel)
1103
1176
  this.turnSummary(event.summary, event)
1104
- this.flushActivityFold()
1105
1177
  return
1106
1178
  }
1107
1179
  if (event.type === "turn.failed" || event.type === "turn.cancelled") {
1108
- this.commit()
1109
1180
  this.commitThinking()
1110
1181
  this.flushActivityFold()
1182
+ this.commit()
1111
1183
  return
1112
1184
  }
1113
1185
  // F-TASK-1: status task kanonik (t<n>) + DAG dirender sebagai baris ledger,
@@ -1220,7 +1292,7 @@ export class Transcript {
1220
1292
  : denyReason
1221
1293
  ? `: ${truncateToWidth(sanitizeAnsi(denyReason), 200, "…").split("\n")[0] ?? ""}`
1222
1294
  : ""
1223
- const line = ` ${statusGlyph(status)} ${name}${targetText} ${statusWord(status)}${retry}${child}${verificationMark}${provenanceMark}${message}`
1295
+ const line = ` ${name}${targetText} ${statusWord(status)}${retry}${child}${verificationMark}${provenanceMark}${message}`
1224
1296
  // Lipat aktivitas (opencode-like): saat minimizeActivity ATAU panel
1225
1297
  // aktivitas aktif, baris ledger per-tool TIDAK boleh menghilang diam-diam
1226
1298
  // — ditahan lalu dirangkum saat turn selesai (panel: per keluarga tool;
@@ -1278,7 +1350,7 @@ export class Transcript {
1278
1350
  const targetText = target ? ` ${truncateToWidth(sanitizeAnsiLine(target), 120, "")}` : ""
1279
1351
  const line =
1280
1352
  verification.verdict === "present"
1281
- ? ` ${statusGlyph("completed")} ${name}${targetText} verified`
1353
+ ? ` ${name}${targetText} verified`
1282
1354
  : ` ? ${name}${targetText} unverified (${verification.verdict})`
1283
1355
  this.append(
1284
1356
  verification.verdict === "present" ? paintLedger("completed", line) : c.muted(line),
@@ -1306,13 +1378,11 @@ export class Transcript {
1306
1378
  ? `: ${truncateToWidth(sanitizeAnsiLine(String(rationale)), 200, "…")}`
1307
1379
  : ""
1308
1380
  const next = event.nextAction ? ` next=${sanitizeAnsiLine(String(event.nextAction))}` : ""
1309
- const glyph =
1310
- verdict === "PASS"
1311
- ? glyphs.check
1312
- : verdict === "FAIL" || verdict === "BLOCKED"
1313
- ? glyphs.cross
1314
- : "?"
1315
- const line = ` ${glyph} consequence ${sanitizeAnsiLine(verdict)}${rule}${next}${reason}`
1381
+ // Paritas renderer linear (simple.ts): marker netral `glyphs.bullet`
1382
+ // (●/*). Logika lama memakai glyphs.check/cross (="" setelah ikon
1383
+ // dihapus) + "?", sehingga baris PASS tampil tanpa penanda (dua spasi)
1384
+ // dan divergen antar permukaan — kelas OAP-001.
1385
+ const line = ` ${glyphs.bullet} consequence ${sanitizeAnsiLine(verdict)}${rule}${next}${reason}`
1316
1386
  const paint =
1317
1387
  verdict === "FAIL" || verdict === "BLOCKED"
1318
1388
  ? c.error(line)
@@ -1335,7 +1405,7 @@ export class Transcript {
1335
1405
  this.commit()
1336
1406
  if (event.type === "context.cutoff") {
1337
1407
  const reason = event.reason ? `: ${sanitizeAnsiLine(String(event.reason))}` : ""
1338
- const line = ` ▪ context cutoff${reason}`
1408
+ const line = ` ${glyphs.bullet} context cutoff${reason}`
1339
1409
  this.append(c.warning(line), {
1340
1410
  kind: "system",
1341
1411
  ...(event.seq !== undefined ? { seq: event.seq } : {}),
@@ -1350,7 +1420,7 @@ export class Transcript {
1350
1420
  used != null
1351
1421
  ? ` ${used.toLocaleString()}${window ? `/${window.toLocaleString()}` : ""} tokens`
1352
1422
  : ""
1353
- const line = ` ▪ context window${tokens}${pct}`
1423
+ const line = ` ${glyphs.bullet} context window${tokens}${pct}`
1354
1424
  this.append(c.muted(line), {
1355
1425
  kind: "system",
1356
1426
  ...(event.seq !== undefined ? { seq: event.seq } : {}),
@@ -1381,7 +1451,7 @@ export class Transcript {
1381
1451
  ? " [verified]"
1382
1452
  : ` [${event.taskVerification?.verdict ?? "unverified"}]`
1383
1453
  : ""
1384
- const line = ` ▪ ${sanitizeAnsiLine(id)} ${status}${parent}${deps}${rev}${verify}`
1454
+ const line = ` ${glyphs.bullet} ${sanitizeAnsiLine(id)} ${status}${parent}${deps}${rev}${verify}`
1385
1455
  const paint =
1386
1456
  raw === "FAILED"
1387
1457
  ? c.error(line)
@@ -17,6 +17,16 @@ export interface CompactionStrategy {
17
17
  * The signal is the turn's abort signal (user abort, session.abort, timeout).
18
18
  */
19
19
  compactAsync?(store: ContextStore, opts: { keepRecentTurns: number }, signal: AbortSignal): Promise<readonly Message[]>;
20
+ /**
21
+ * Lapisan pertama sebelum kompaksi penuh: pangkas ISI hasil tool lama
22
+ * menjadi sentinel pendek. Opsional dan aditif — tanpa ini perilaku lama utuh.
23
+ *
24
+ * Mengembalikan daftar pesan baru (atau yang sama bila tak memangkas) dan
25
+ * WAJIB mempertahankan pasangan `assistant(toolCalls)` → `tool` serta pesan
26
+ * lain apa adanya. Loop memakai hasilnya hanya bila jumlah token benar-benar
27
+ * turun, jadi implementasi tak perlu (dan tak boleh) menebak sendiri.
28
+ */
29
+ microcompact?(store: ContextStore, opts: { budgetTokens?: number }): readonly Message[];
20
30
  }
21
31
 
22
32
  export const mechanicalCompaction: CompactionStrategy = {
@@ -15,10 +15,20 @@ export class AgentError extends Error {
15
15
  constructor(
16
16
  readonly kind: AgentErrorKind,
17
17
  message: string,
18
- options?: { cause?: unknown },
18
+ options?: {
19
+ cause?: unknown
20
+ /** Diagnostik terstruktur untuk kegagalan yang butuh ANGKA, bukan hanya
21
+ * prosa (mis. `budget_exceeded` dengan `reason: "fixpoint"` + berapa
22
+ * token tersisa). Pemanggil bisa menampilkan sebab yang tepat alih-alih
23
+ * menyuruh user "coba lagi" pada kondisi yang tak akan berubah. */
24
+ details?: Record<string, unknown>
25
+ },
19
26
  ) {
20
27
  super(message, options);
28
+ if (options?.details) this.details = options.details;
21
29
  }
30
+ /** Rincian mesin-terbaca; `undefined` bila tak ada. */
31
+ readonly details?: Record<string, unknown>;
22
32
  }
23
33
 
24
34
  /**
@@ -135,5 +135,10 @@ function serializeContent(value: unknown, maxTokens: number): unknown {
135
135
  if (text.length <= maxChars) return text;
136
136
  const headLen = Math.max(0, Math.floor(maxChars * 0.7));
137
137
  const tailLen = Math.max(0, maxChars - headLen - 12);
138
- return `${text.slice(0, headLen)}\n…[truncated]…\n${text.slice(-tailLen)}`;
138
+ // Penanda menyebut CARA mengambil sisa, bukan sekadar "terpotong": tanpa itu
139
+ // model tahu ada yang hilang tapi tak tahu harus berbuat apa, lalu menebak
140
+ // atau menyerah. Pola head+tail dipilih agar awal dan akhir (lokasi error /
141
+ // ringkasan hasil) tetap terbaca.
142
+ const omitted = text.length - headLen - tailLen;
143
+ return `${text.slice(0, headLen)}\n…[output dipotong: ${omitted} karakter tidak ditampilkan; jalankan ulang tool dengan batas lebih sempit (mis. path/baris/pola spesifik) atau baca bertahap]…\n${text.slice(-tailLen)}`;
139
144
  }
@@ -5,7 +5,7 @@ import type { RecoveryAction } from "./errors.ts";
5
5
  import type { ExecutorDeps } from "./executor.ts";
6
6
  import type { StreamRequest, FinishReason } from "./provider.ts";
7
7
  import { snapshotMessages, snapshotState, snapshotStep, snapshotToolCall, snapshotToolResult, snapshotToolSchemas } from "./snapshot.ts";
8
- import { estimateSessionContext } from "./tokens.ts";
8
+ import { estimateSessionContext, estimateSystem, estimateTools } from "./tokens.ts";
9
9
  import type { ToolSchema } from "./tool.ts";
10
10
  import type { ToolCall, ToolResult } from "./types.ts";
11
11
  import type { SessionInternal, Step, TurnResult } from "./session.ts";
@@ -51,6 +51,9 @@ export async function executeTurn(
51
51
  // turn. The hard cap prevents a no-progress compactor from looping forever.
52
52
  let budgetCompactions = 0;
53
53
  const maxBudgetCompactions = 3;
54
+ // Berapa kali berturut-turut kompaksi tidak mengurangi apa pun. Dipakai untuk
55
+ // membedakan "konteks penuh tapi bisa dipadatkan" dari "sudah di titik tetap".
56
+ let noProgressCompactions = 0;
54
57
  let compactedForRecovery = false;
55
58
 
56
59
  // Resolve once for the turn: model switching is a between-turn operation,
@@ -78,7 +81,46 @@ export async function executeTurn(
78
81
  limitTokens: contextWindowTokens,
79
82
  });
80
83
  let reduced = false;
84
+ // Lapisan termurah lebih dulu: pangkas isi hasil tool lama. Ini TIDAK
85
+ // memanggil model apa pun, jadi aman dicoba di setiap titik tekanan — bila
86
+ // ia berhasil menurunkan token di bawah ambang, kompaksi penuh (mahal +
87
+ // lossy) tidak perlu dijalankan sama sekali.
88
+ if (s.budget.shouldCompact(pressure) && s.compaction.microcompact) {
89
+ const beforeMicro = contextTokens(s);
90
+ try {
91
+ const trimmed = s.compaction.microcompact(s.store, { budgetTokens: contextWindowTokens });
92
+ if (trimmed !== s.store.messages) {
93
+ s.store.replace(0, s.store.messages.length, trimmed);
94
+ }
95
+ } catch {
96
+ // Microcompact adalah optimisasi; kegagalannya tidak boleh menggagalkan
97
+ // turn. Kompaksi penuh di bawah tetap menjadi jaringnya.
98
+ }
99
+ const afterMicro = contextTokens(s);
100
+ if (afterMicro < beforeMicro) {
101
+ const freed = beforeMicro - afterMicro;
102
+ s.events.emit({ type: "context:compacted", reason: `microcompact:${freed}` });
103
+ pressure = s.budget.evaluate({ usedTokens: afterMicro, limitTokens: contextWindowTokens });
104
+ }
105
+ }
81
106
  if (s.budget.shouldCompact(pressure) && budgetCompactions < maxBudgetCompactions) {
107
+ // Biaya TETAP (system prompt + skema tool + pesan yang tak boleh dibuang)
108
+ // tidak pernah tersentuh kompaksi. Bila biaya itu sendiri sudah melebihi
109
+ // jendela, mencoba kompaksi hanya membakar satu panggilan LLM untuk
110
+ // menghasilkan no-op — laporkan sekali dengan angka, lalu berhenti
111
+ // mencoba. Ini membedakan "perlu dipadatkan" dari "mustahil dipadatkan".
112
+ const fixed = fixedContextTokens(s);
113
+ if (fixed > 0 && fixed >= contextWindowTokens) {
114
+ s.events.emit({
115
+ type: "context:compacted",
116
+ reason: `impossible:${fixed}:${contextWindowTokens}`,
117
+ });
118
+ throw new AgentError(
119
+ "budget_exceeded",
120
+ `context window exceeded before compaction (fixed instructions and tool schemas alone cost ${fixed} > ${contextWindowTokens}); compaction cannot help — reduce the fixed instructions/tools or select a model with a larger context window`,
121
+ { details: { reason: "impossible", fixedTokens: fixed, windowTokens: contextWindowTokens } },
122
+ );
123
+ }
82
124
  const before = s.store.messages.length;
83
125
  await compactStore(s, signal);
84
126
  budgetCompactions++;
@@ -95,15 +137,40 @@ export async function executeTurn(
95
137
  usedTokens: contextTokens(s),
96
138
  limitTokens: contextWindowTokens,
97
139
  });
140
+ if (!reduced) noProgressCompactions++;
141
+ else noProgressCompactions = 0;
98
142
  }
99
143
  if (s.budget.shouldCompact(pressure) && reduced && budgetCompactions < maxBudgetCompactions) {
100
144
  continue;
101
145
  }
102
146
  if (pressure === "critical") {
103
147
  const used = contextTokens(s);
148
+ // Bila kompaksi berulang TIDAK mengurangi apa pun, penyebabnya bukan
149
+ // pesan yang bisa dibuang melainkan biaya tetap: system prompt + skema
150
+ // tool + ekor verbatim `keepRecentTurns` yang tak bisa dipotong lagi.
151
+ // Mencoba lagi tak akan berubah; laporkan SEBAB-nya dengan angka supaya
152
+ // user tahu harus mengurangi instruksi/alat atau memilih model berjendela
153
+ // lebih besar — bukan sekadar pesan "context window exceeded" yang
154
+ // menyiratkan "coba lagi".
155
+ const fixed = contextTokens(s);
156
+ if (noProgressCompactions > 0) {
157
+ throw new AgentError(
158
+ "budget_exceeded",
159
+ `context compaction cannot reduce this session further (fixpoint: ${fixed} > ${contextWindowTokens} after ${noProgressCompactions} compaction attempt(s) with ${s.store.messages.length} message(s) left); the remaining cost is fixed instructions, tool schemas, or the retained tail — reduce them or select a model with a larger context window`,
160
+ {
161
+ details: {
162
+ reason: "fixpoint",
163
+ fixedTokens: fixed,
164
+ windowTokens: contextWindowTokens,
165
+ keptMessages: s.store.messages.length,
166
+ },
167
+ },
168
+ );
169
+ }
104
170
  throw new AgentError(
105
171
  "budget_exceeded",
106
172
  `context window exceeded after compaction (${used} > ${contextWindowTokens}); reduce the prompt, tool output, or fixed instructions, or select a model with a larger context window`,
173
+ { details: { reason: "critical", fixedTokens: used, windowTokens: contextWindowTokens } },
107
174
  );
108
175
  }
109
176
 
@@ -381,6 +448,22 @@ function contextTokens(s: SessionInternal): number {
381
448
  return estimateSessionContext(s.store, system, s.registry.list(), s.estimator);
382
449
  }
383
450
 
451
+ /**
452
+ * Biaya yang TIDAK bisa dikurangi kompaksi: system prompt + skema tool.
453
+ *
454
+ * KENAPA dipisah dari `contextTokens`: kompaksi hanya bisa membuang/memadatkan
455
+ * PESAN. Bila system + tools saja sudah melebihi jendela, setiap percobaan
456
+ * kompaksi dijamin no-op. Memisahkan angka ini membuat loop bisa menyimpulkan
457
+ * "mustahil dipadatkan" tanpa membakar panggilan LLM.
458
+ */
459
+ function fixedContextTokens(s: SessionInternal): number {
460
+ let system = s.system;
461
+ try {
462
+ system = s.systemForContext?.() ?? system;
463
+ } catch {}
464
+ return estimateSystem(system, s.estimator) + estimateTools(s.registry.list(), s.estimator);
465
+ }
466
+
384
467
  // The single compaction seam. Prefers the strategy's optional async method
385
468
  // (LLM summary) and always falls back to the sync strategy on failure — an
386
469
  // async compactor must never be able to crash the loop.
@@ -393,7 +476,14 @@ async function compactStore(s: SessionInternal, signal: AbortSignal): Promise<vo
393
476
  return;
394
477
  } catch (error) {
395
478
  if (signal.aborted) throw abortError(signal);
396
- // fall through to sync mechanical compaction
479
+ // Kegagalan ringkasan LLM TIDAK boleh diam: fallback mekanikal memang
480
+ // benar, tapi tanpa jejak ini sesi panjang terlihat "dipadatkan" padahal
481
+ // isinya hasil pemangkasan mekanis yang jauh lebih miskin. Laporkan
482
+ // sebabnya agar penyebab (timeout, thrash, model menolak) bisa dibedah.
483
+ const reason = String((error as Error)?.message ?? error)
484
+ .replace(/\s+/g, " ")
485
+ .slice(0, 160)
486
+ s.events.emit({ type: "context:compacted", reason: `llm-failed:${reason}` })
397
487
  }
398
488
  }
399
489
  s.store.replace(0, s.store.messages.length, s.compaction.compact(s.store, opts));