minicode-ai 0.22.0 → 0.25.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 (100) hide show
  1. package/README.md +2 -2
  2. package/cli/commands.ts +10 -0
  3. package/cli/index.ts +11 -0
  4. package/cli/setup.ts +64 -33
  5. package/cli/tui.ts +29 -3
  6. package/docs/README.md +2 -2
  7. package/docs/SUMMARY.md +10 -19
  8. package/docs/TERMINAL_CONTRACT.md +119 -32
  9. package/docs/architecture.md +1 -1
  10. package/docs/autonomous-scheduler.md +283 -2
  11. package/docs/choosing-mode.md +4 -4
  12. package/docs/concepts.md +39 -3
  13. package/docs/config.md +90 -4
  14. package/docs/environment.md +6 -0
  15. package/docs/getting-started.md +58 -2
  16. package/docs/repl.md +1 -1
  17. package/docs/security.md +49 -2
  18. package/docs/tools.md +2 -1
  19. package/package.json +2 -36
  20. package/src/app/provider-layer.ts +1 -1
  21. package/src/app/session.ts +129 -20
  22. package/src/config.ts +102 -2
  23. package/src/constants.ts +32 -4
  24. package/src/lib/safe-open.ts +21 -12
  25. package/src/memory/vector.ts +0 -31
  26. package/src/policy/compaction.ts +27 -0
  27. package/src/policy/context-budget.ts +132 -0
  28. package/src/policy/context-escalation.ts +140 -0
  29. package/src/policy/context-window.ts +14 -9
  30. package/src/policy/context.ts +10 -1
  31. package/src/policy/microcompact.ts +162 -0
  32. package/src/policy/no-progress.ts +1 -1
  33. package/src/policy/permission.ts +5 -0
  34. package/src/policy/scrub.ts +15 -2
  35. package/src/policy/tool-contract.ts +11 -9
  36. package/src/presentation/reducer.ts +1 -0
  37. package/src/providers/anthropic.ts +17 -3
  38. package/src/providers/detect.ts +155 -13
  39. package/src/providers/provision.ts +92 -1
  40. package/src/providers/responses.ts +13 -1
  41. package/src/session/persistence.ts +56 -0
  42. package/src/task/autonomous-policy.ts +7 -0
  43. package/src/task/graph-validate.ts +1 -1
  44. package/src/task/session-authority.ts +0 -5
  45. package/src/task/store.ts +0 -4
  46. package/src/tools/ask_user.ts +14 -1
  47. package/src/tools/bash.ts +57 -9
  48. package/src/tools/context.ts +10 -0
  49. package/src/tools/delete_file.ts +3 -2
  50. package/src/tools/edit.ts +5 -4
  51. package/src/tools/git.ts +70 -12
  52. package/src/tools/glob.ts +13 -5
  53. package/src/tools/grep.ts +26 -10
  54. package/src/tools/index.ts +3 -2
  55. package/src/tools/lsp.ts +15 -9
  56. package/src/tools/move_file.ts +4 -3
  57. package/src/tools/patch.ts +5 -4
  58. package/src/tools/read_file.ts +3 -2
  59. package/src/tools/read_image.ts +3 -2
  60. package/src/tools/task.ts +1 -0
  61. package/src/tools/todo.ts +4 -8
  62. package/src/tools/write_file.ts +4 -3
  63. package/src/ui/approval/prompt.ts +226 -77
  64. package/src/ui/assistant/simple.ts +1 -1
  65. package/src/ui/footer.ts +41 -29
  66. package/src/ui/i18n/en.ts +23 -4
  67. package/src/ui/i18n/id.ts +25 -4
  68. package/src/ui/input/input.ts +2 -2
  69. package/src/ui/render/activity-group.ts +1 -0
  70. package/src/ui/render/activity-panel.ts +21 -3
  71. package/src/ui/render/hint.ts +28 -0
  72. package/src/ui/render/ledger.ts +1 -9
  73. package/src/ui/render/logo.ts +86 -0
  74. package/src/ui/render/markdown-table.ts +0 -3
  75. package/src/ui/render/session-summary.ts +22 -1
  76. package/src/ui/render/table-grid.ts +0 -3
  77. package/src/ui/render/theme.ts +36 -5
  78. package/src/ui/runtime/screen.ts +11 -3
  79. package/src/ui/screens/dialog.ts +45 -81
  80. package/src/ui/screens/form.ts +29 -33
  81. package/src/ui/screens/lifecycle.ts +80 -0
  82. package/src/ui/screens/model-manager.ts +84 -91
  83. package/src/ui/screens/picker.ts +36 -33
  84. package/src/ui/screens/provider-manager.ts +50 -59
  85. package/src/ui/screens/watchdog.ts +27 -0
  86. package/src/ui/screens/wizard.ts +3 -20
  87. package/src/ui/tui/app.ts +97 -11
  88. package/src/ui/tui/transcript.ts +55 -16
  89. package/vendor/minicore/src/core/compact.ts +10 -0
  90. package/vendor/minicore/src/core/errors.ts +11 -1
  91. package/vendor/minicore/src/core/executor.ts +6 -1
  92. package/vendor/minicore/src/core/loop.ts +92 -2
  93. package/vendor/minicore/src/core/session.ts +8 -0
  94. package/vendor/minicore/src/providers/openai-compat.ts +15 -2
  95. package/docs/P14_OPEN_WORK.md +0 -290
  96. package/docs/config-providers.md +0 -87
  97. package/docs/glossary.md +0 -39
  98. package/docs/quickstart.md +0 -60
  99. package/docs/security-model.md +0 -96
  100. package/docs/terminal.md +0 -91
@@ -0,0 +1,27 @@
1
+ // Batas waktu aksi jaringan (deteksi model, save/delete provider/model, submit
2
+ // wizard). Provider/tool non-kooperatif yang gantung selamanya membuat popup
3
+ // mati (suspend tanpa listener/timer, raw-mode digenggam) — timeout = error
4
+ // jujur + UI pulih; aksi telat yang akhirnya selesai diabaikan hasilnya.
5
+ //
6
+ // Dipakai bersamaan oleh picker/model-manager/provider-manager/wizard sehingga
7
+ // semantik timeout TIDAK drift antar jendela (dulu tiga salinan nyaris identik
8
+ // yang berisiko melenceng per permukaan — kelas OAP-001).
9
+ import { t } from "../i18n/locale.ts"
10
+
11
+ export function withTimeout<T>(fn: () => Promise<T> | T, ms: number): Promise<T> {
12
+ let timer: ReturnType<typeof setTimeout> | undefined
13
+ const pending = Promise.resolve().then(fn)
14
+ // Rejection telat TANPA handler = unhandledRejection (Bun: crash proses).
15
+ pending.catch(() => {})
16
+ return Promise.race([
17
+ pending,
18
+ new Promise<never>((_, reject) => {
19
+ timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
20
+ try {
21
+ ;(timer as unknown as { unref?: () => void }).unref?.()
22
+ } catch {}
23
+ }),
24
+ ]).finally(() => {
25
+ if (timer) clearTimeout(timer)
26
+ })
27
+ }
@@ -10,6 +10,7 @@ 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"
13
14
 
14
15
  /**
15
16
  * Batas tunggu simpan-provider (audit 2026-11-12, MEDIUM-7).
@@ -18,26 +19,8 @@ import { runPicker } from "./picker.ts"
18
19
  * I/O config (kunci, tulis disk) yang bisa lambat; tanpa batas, kotak
19
20
  * "mendeteksi…" bertahan selama proses menggantung dan user tak punya jalan
20
21
  * keluar (tak ada Esc di kotak progres). Timeout = pesan jujur, UI pulih.
22
+ * Semantik timeout di-share lewat withTimeout() (paritas picker/manager).
21
23
  */
22
- async function withWatchdog<T>(fn: () => Promise<T>, ms = 60_000): Promise<T> {
23
- let timer: ReturnType<typeof setTimeout> | undefined
24
- const pending = Promise.resolve().then(fn)
25
- // Rejection telat tanpa handler = unhandledRejection (Bun: crash).
26
- pending.catch(() => {})
27
- try {
28
- return await Promise.race([
29
- pending,
30
- new Promise<never>((_, reject) => {
31
- timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
32
- try {
33
- ;(timer as unknown as { unref?: () => void }).unref?.()
34
- } catch {}
35
- }),
36
- ])
37
- } finally {
38
- if (timer) clearTimeout(timer)
39
- }
40
- }
41
24
 
42
25
  export interface WizardPreset {
43
26
  label: string
@@ -176,7 +159,7 @@ export async function runSetupWizardView(opts: SetupWizardViewOptions): Promise<
176
159
  )
177
160
  screen.paintRegion(box.lines, box.topRow)
178
161
  try {
179
- const message = await withWatchdog(() => opts.onSubmit(targetUrl, apiKey))
162
+ const message = await withTimeout(() => opts.onSubmit(targetUrl, apiKey), 60_000)
180
163
  // Pesan dari jaringan (nama model/gateway) — sanitasi sebelum tampil.
181
164
  screen.clearRegion()
182
165
  const doneBox = dialogBox(
package/src/ui/tui/app.ts CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  import { appendWrapped, shaveWrapped } from "../render/composer-wrap.ts"
27
27
  import { formatError } from "../render/errors.ts"
28
28
  import { sanitizeAnsi, sanitizeAnsiLine, stripSgr } from "../render/sanitize.ts"
29
- import { c } from "../render/theme.ts"
29
+ import { c, scrimMode, scrimSgr } from "../render/theme.ts"
30
30
  import { chunkByWidth, displayWidth, escapeLength, truncateToWidth } from "../render/width.ts"
31
31
  import { motionReduced } from "../runtime/motion.ts"
32
32
  import { type AltScreen, forceRestoreScreenForSignal, openAltScreen } from "../runtime/screen.ts"
@@ -79,6 +79,8 @@ const PROMPT_FIRST = "minicode › "
79
79
  const PROMPT_CONT = " · "
80
80
  const TIMER_TEXT = "00.00.00"
81
81
  const DOT_INTERVAL_MS = 200
82
+ /** Badge job background berputar lebih pelan dari dots (tidak berkedip). */
83
+ const WAITING_INTERVAL_MS = 400
82
84
  const DOT_PHASES = ["...", "..", ".", ".."] as const
83
85
  const MOUSE_DRAG_ON = "\x1b[?1002h\x1b[?1006h"
84
86
  const MOUSE_WHEEL_ON = "\x1b[?1000h\x1b[?1006h"
@@ -241,6 +243,10 @@ export class TuiApp {
241
243
  private thinkingActive = false
242
244
  private turnStartedAt = 0
243
245
  private activityTimer: ReturnType<typeof setTimeout> | undefined
246
+ // Clock badge job background: TERPISAH dari activityTimer karena job hidup
247
+ // justru saat turn IDLE (activityTimer hanya jalan saat busy).
248
+ private waitingTimer: ReturnType<typeof setTimeout> | undefined
249
+ private waitingStartedAt = 0
244
250
  /** Timestamp abort terakhir (ms) — deteksi double-tap Esc = quit. */
245
251
  private lastAbortAt = 0
246
252
  /** Hint "tekan lagi untuk keluar" tampil sekali setelah abort pertama. */
@@ -527,6 +533,7 @@ export class TuiApp {
527
533
  this.repaintTimer = undefined
528
534
  }
529
535
  this.stopActivityClock()
536
+ this.stopWaitingClock()
530
537
  this.stopAutoScroll()
531
538
  for (const unsubscribe of this.busUnsubs.splice(0)) {
532
539
  try {
@@ -923,6 +930,7 @@ export class TuiApp {
923
930
  this.host.abort()
924
931
  } catch {}
925
932
  this.stopActivityClock()
933
+ this.stopWaitingClock()
926
934
  this.quitRequested = true
927
935
  this.finish?.()
928
936
  }
@@ -1028,18 +1036,22 @@ export class TuiApp {
1028
1036
  }
1029
1037
 
1030
1038
  /**
1031
- * Bungkus baris dengan mode redup (\x1b[2m) untuk backdrop popup.
1032
- * Reset (\x1b[0m atau \x1b[22m) dan bold (\x1b[1m) di dalam teks dinetralkan
1033
- * agar peredupan tidak bocor di tengah baris yang diwarnai.
1039
+ * Bungkus baris dengan scrim latar netral bila tersedia. Reset SGR dalam
1040
+ * konten dipulihkan ke keadaan scrim agar warna teks tak mematikan backdrop.
1034
1041
  */
1035
1042
  static applyBackdropDim(ln: string): string {
1036
1043
  if (!ln) return ""
1044
+ const mode = scrimMode()
1045
+ if (mode === "none") return ln
1037
1046
  const esc = String.fromCharCode(27)
1038
- let s = ln.replaceAll(`${esc}[1m`, "")
1039
- s = s.replaceAll(`${esc}[22m`, `${esc}[2m`)
1040
- s = s.replaceAll(`${esc}[0m`, `${esc}[0m${esc}[2m`)
1041
- s = s.replaceAll(`${esc}[m`, `${esc}[0m${esc}[2m`)
1042
- return `${esc}[2m${s}${esc}[22m${esc}[0m`
1047
+ const scrim = scrimSgr(mode)
1048
+ // Bold DIPETAKAN ke scrim (bukan dibuang) dan `[22m` memulihkan scrim,
1049
+ // bukan meninggalkan teks normal (AUD-003).
1050
+ let s = ln.replaceAll(`${esc}[1m`, scrim)
1051
+ s = s.replaceAll(`${esc}[22m`, `${esc}[22m${scrim}`)
1052
+ s = s.replaceAll(`${esc}[0m`, `${esc}[0m${scrim}`)
1053
+ s = s.replaceAll(`${esc}[m`, `${esc}[0m${scrim}`)
1054
+ return `${scrim}${s}${esc}[22m${esc}[0m`
1043
1055
  }
1044
1056
 
1045
1057
  /** Layar redup sebagai backdrop popup: frame normal dibungkus faint. */
@@ -1221,6 +1233,46 @@ export class TuiApp {
1221
1233
  }
1222
1234
  }
1223
1235
 
1236
+ // Clock badge job background: berjalan selama ada job hidup, termasuk saat
1237
+ // turn idle (justru saat itulah job biasanya selesai).
1238
+ private startWaitingClock(): void {
1239
+ if (this.waitingTimer !== undefined || this.quitRequested) return
1240
+ if (!this.waitingStartedAt) this.waitingStartedAt = Date.now()
1241
+ const tick = () => {
1242
+ this.waitingTimer = undefined
1243
+ if (this.quitRequested) return
1244
+ if (!this.hasBackgroundJobs()) {
1245
+ this.waitingStartedAt = 0
1246
+ return
1247
+ }
1248
+ if (this.suspended === 0 && !this.released) this.paintCurrent()
1249
+ if (this.quitRequested) return
1250
+ this.startWaitingClock()
1251
+ }
1252
+ this.waitingTimer = setTimeout(tick, WAITING_INTERVAL_MS)
1253
+ try {
1254
+ ;(this.waitingTimer as unknown as { unref?: () => void }).unref?.()
1255
+ } catch {}
1256
+ }
1257
+
1258
+ private stopWaitingClock(): void {
1259
+ if (this.waitingTimer !== undefined) {
1260
+ clearTimeout(this.waitingTimer)
1261
+ this.waitingTimer = undefined
1262
+ }
1263
+ this.waitingStartedAt = 0
1264
+ }
1265
+
1266
+ /** Jumlah job hidup dari snapshot host (0 bila host tak melaporkan). */
1267
+ private hasBackgroundJobs(): boolean {
1268
+ try {
1269
+ const jobs = this.host.getStatus().footer.backgroundJobs ?? 0
1270
+ return jobs >= 1
1271
+ } catch {
1272
+ return false
1273
+ }
1274
+ }
1275
+
1224
1276
  private activityStatus(snap: TuiStatusSnapshot): string {
1225
1277
  const activity = snap.pinnedActivity
1226
1278
  if (!activity) return ""
@@ -1299,6 +1351,27 @@ export class TuiApp {
1299
1351
  if (!this.quitRequested && this.suspended === 0) this.paintCurrent()
1300
1352
  }
1301
1353
 
1354
+ // Titik masuk popup komposit (approval/ask_user): lukis kotak di atas
1355
+ // transkrip yang sudah redup. Geometri milik currentScreen.
1356
+ paintRegion(lines: string[], topRow: number): void {
1357
+ if (!this.currentScreen || this.quitRequested) return
1358
+ try {
1359
+ this.currentScreen.paintRegion(lines, topRow)
1360
+ } catch (error) {
1361
+ this.stopAfterRuntimeError(error)
1362
+ }
1363
+ }
1364
+
1365
+ /** Hapus region popup (pasangan paintRegion); App akan repaint penuh saat resume. */
1366
+ clearRegion(): void {
1367
+ if (!this.currentScreen) return
1368
+ try {
1369
+ this.currentScreen.clearRegion()
1370
+ } catch (error) {
1371
+ this.stopAfterRuntimeError(error)
1372
+ }
1373
+ }
1374
+
1302
1375
  private viewportHeight(rows: number, cols: number): number {
1303
1376
  const busy = this.isBusy()
1304
1377
  const inputH = this.composerHeight(cols, busy)
@@ -1619,8 +1692,11 @@ export class TuiApp {
1619
1692
  private copySelection(): void {
1620
1693
  const selection = this.selection
1621
1694
  if (!selection) return
1622
- const text = this.transcript.selectionText(selection.anchor, selection.focus).trim()
1623
- if (!text) {
1695
+ // Salin teks ASLI (bukan `.trim()`): indentasi baris pertama dan newline di
1696
+ // ekor adalah bagian dari konten yang dipilih pengguna (blok kode/teks
1697
+ // berindentasi). Trim hanya untuk mendeteksi "seleksi kosong".
1698
+ const text = this.transcript.selectionText(selection.anchor, selection.focus)
1699
+ if (!text.trim()) {
1624
1700
  this.selection = null
1625
1701
  this.paintCurrent()
1626
1702
  return
@@ -1651,6 +1727,10 @@ export class TuiApp {
1651
1727
  this.thinkingActive = false
1652
1728
  this.turnStartedAt = 0
1653
1729
  }
1730
+ // Badge hidup saat busy DAN idle; clock-nya terpisah dari activity.
1731
+ const backgroundJobs = snap.footer.backgroundJobs ?? 0
1732
+ if (backgroundJobs >= 1) this.startWaitingClock()
1733
+ else this.stopWaitingClock()
1654
1734
  const newCount = this.scrollBack > 0 ? this.transcript.total() - this.scrollBase : 0
1655
1735
  // Baris indikator WAJIB dipotong ke lebar frame seperti baris lain: teks
1656
1736
  // locale id lebih panjang dari terminal sempit (51 kolom untuk abort hint),
@@ -1733,6 +1813,12 @@ export class TuiApp {
1733
1813
  timer,
1734
1814
  timerActive: busy,
1735
1815
  timerHighlight: timerHighlight(elapsed),
1816
+ // Frame badge dihitung dari clock badge sendiri (waitingStartedAt),
1817
+ // bukan dari turn: job background berputar juga saat idle.
1818
+ backgroundFrame:
1819
+ backgroundJobs >= 1 && !motionReduced()
1820
+ ? Math.floor((now - (this.waitingStartedAt || now)) / WAITING_INTERVAL_MS)
1821
+ : 0,
1736
1822
  },
1737
1823
  width,
1738
1824
  )[0] ?? ""
@@ -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
@@ -323,7 +327,7 @@ export class Transcript {
323
327
  }),
324
328
  bus.on("provider:extension", (e: { kind: string; data: unknown }) => this.extension(e)),
325
329
  bus.on("context:compacted", (e: { reason: string }) =>
326
- this.push(c.muted(t("ts.compacted", { reason: sanitizeAnsiLine(e.reason ?? "") }))),
330
+ this.push(c.muted(this.compactedLabel(e.reason ?? ""))),
327
331
  ),
328
332
  ]
329
333
  if (opts.onPresentationEvent) {
@@ -331,6 +335,37 @@ export class Transcript {
331
335
  }
332
336
  }
333
337
 
338
+ /**
339
+ * Label hasil kompaksi yang JUJUR soal sebab dan akibat.
340
+ *
341
+ * Kernel mengirim `pressure:<level>` saat benar-benar menyusut dan
342
+ * `pressure:<level>:no-op` saat tak ada yang bisa dibuang. Dulu keduanya
343
+ * tampil sama ("dipadatkan: pressure:critical:no-op") sehingga sesi yang
344
+ * konteksnya TIDAK menyusut terlihat seakan berhasil dipadatkan — user lalu
345
+ * bingung kenapa turn berikut tetap gagal. Pemetaan ini memisahkan empat
346
+ * kondisi yang berbeda tindak lanjutnya: no-op, fixpoint, mustahil (biaya
347
+ * tetap), dan ringkasan LLM gagal.
348
+ */
349
+ private compactedLabel(reason: string): string {
350
+ const clean = sanitizeAnsiLine(reason)
351
+ if (!clean) return t("ts.compacted", { reason: "-" })
352
+ if (clean.endsWith(":no-op")) {
353
+ const base = clean.slice(0, -":no-op".length)
354
+ return t("ts.compactedNoOp", { reason: base })
355
+ }
356
+ const kept = /^fixpoint:(\d+)$/.exec(clean)
357
+ if (kept) return t("ts.compactedFixpoint", { kept: kept[1] ?? "0" })
358
+ const impossible = /^impossible:(\d+):(\d+)$/.exec(clean)
359
+ if (impossible)
360
+ return t("ts.compactedImpossible", {
361
+ fixed: impossible[1] ?? "0",
362
+ trigger: impossible[2] ?? "0",
363
+ })
364
+ if (clean.startsWith("llm-failed:"))
365
+ return t("ts.compactedLlmFailed", { reason: clean.slice("llm-failed:".length) })
366
+ return t("ts.compacted", { reason: clean })
367
+ }
368
+
334
369
  /** Teks model mengalir — ditahan sebagai ekor hidup sampai commit. */
335
370
  stream(text: string): void {
336
371
  if (!text) return
@@ -755,7 +790,9 @@ export class Transcript {
755
790
  }
756
791
  // thinking/running aktif: bangun segar (jarang — hanya saat turn berjalan,
757
792
  // dan repaint-nya sudah dicoalesce 30ms, bukan per-keypress).
758
- const rows: TranscriptRow[] = [...this.committedRows(w), ...this.pendingRows(w)]
793
+ // Urutan: committed → activity (thinking/running/panel) → pending. Jawaban di
794
+ // ekor agar jangkar stabil saat streaming (activity mendorong histori, bukan jawaban).
795
+ const rows: TranscriptRow[] = [...this.committedRows(w)]
759
796
  if (!this.thinkingAreaMode() && this.thinkingTail) {
760
797
  for (const chunk of this.thinkingTail.split("\n")) {
761
798
  const chunkRows = chunk === "" ? [""] : wrapByWidth(chunk, w)
@@ -790,8 +827,10 @@ export class Transcript {
790
827
  })
791
828
  }
792
829
  // Panel aktivitas (Fase 2): baris grup tool terminal — tampil di bawah
793
- // running, di atas transkrip. Hanya saat ada activity.
830
+ // running, di atas jawaban (pending). Hanya saat ada activity.
794
831
  rows.push(...panel)
832
+ // Jawaban streaming berada di ekor (di bawah semua activity turn berjalan).
833
+ rows.push(...this.pendingRows(w))
795
834
  return rows
796
835
  }
797
836
 
@@ -1129,20 +1168,22 @@ export class Transcript {
1129
1168
  return
1130
1169
  }
1131
1170
  if (event.type === "turn.completed") {
1132
- this.commit()
1133
1171
  this.commitThinking()
1172
+ // Flush panel SEBELUM commit jawaban agar urutan persist = transient (panel di
1173
+ // atas jawaban; tanpa ini panel "lompat" ke bawah saat turn selesai).
1174
+ this.flushActivityFold()
1175
+ this.commit()
1134
1176
  // minimizeActivity ON / activityPanel ON → fold meringkas sendiri (nama
1135
1177
  // tool + ok/gagal); turnSummary (turn · files · durasi) dilewati agar
1136
1178
  // tidak ada dua ringkasan.
1137
1179
  if (!this.uiState.minimizeActivity && !this.uiState.activityPanel)
1138
1180
  this.turnSummary(event.summary, event)
1139
- this.flushActivityFold()
1140
1181
  return
1141
1182
  }
1142
1183
  if (event.type === "turn.failed" || event.type === "turn.cancelled") {
1143
- this.commit()
1144
1184
  this.commitThinking()
1145
1185
  this.flushActivityFold()
1186
+ this.commit()
1146
1187
  return
1147
1188
  }
1148
1189
  // F-TASK-1: status task kanonik (t<n>) + DAG dirender sebagai baris ledger,
@@ -1341,13 +1382,11 @@ export class Transcript {
1341
1382
  ? `: ${truncateToWidth(sanitizeAnsiLine(String(rationale)), 200, "…")}`
1342
1383
  : ""
1343
1384
  const next = event.nextAction ? ` next=${sanitizeAnsiLine(String(event.nextAction))}` : ""
1344
- const glyph =
1345
- verdict === "PASS"
1346
- ? glyphs.check
1347
- : verdict === "FAIL" || verdict === "BLOCKED"
1348
- ? glyphs.cross
1349
- : "?"
1350
- const line = ` ${glyph} consequence ${sanitizeAnsiLine(verdict)}${rule}${next}${reason}`
1385
+ // Paritas renderer linear (simple.ts): marker netral `glyphs.bullet`
1386
+ // (●/*). Logika lama memakai glyphs.check/cross (="" setelah ikon
1387
+ // dihapus) + "?", sehingga baris PASS tampil tanpa penanda (dua spasi)
1388
+ // dan divergen antar permukaan — kelas OAP-001.
1389
+ const line = ` ${glyphs.bullet} consequence ${sanitizeAnsiLine(verdict)}${rule}${next}${reason}`
1351
1390
  const paint =
1352
1391
  verdict === "FAIL" || verdict === "BLOCKED"
1353
1392
  ? c.error(line)
@@ -1370,7 +1409,7 @@ export class Transcript {
1370
1409
  this.commit()
1371
1410
  if (event.type === "context.cutoff") {
1372
1411
  const reason = event.reason ? `: ${sanitizeAnsiLine(String(event.reason))}` : ""
1373
- const line = ` ▪ context cutoff${reason}`
1412
+ const line = ` ${glyphs.bullet} context cutoff${reason}`
1374
1413
  this.append(c.warning(line), {
1375
1414
  kind: "system",
1376
1415
  ...(event.seq !== undefined ? { seq: event.seq } : {}),
@@ -1385,7 +1424,7 @@ export class Transcript {
1385
1424
  used != null
1386
1425
  ? ` ${used.toLocaleString()}${window ? `/${window.toLocaleString()}` : ""} tokens`
1387
1426
  : ""
1388
- const line = ` ▪ context window${tokens}${pct}`
1427
+ const line = ` ${glyphs.bullet} context window${tokens}${pct}`
1389
1428
  this.append(c.muted(line), {
1390
1429
  kind: "system",
1391
1430
  ...(event.seq !== undefined ? { seq: event.seq } : {}),
@@ -1416,7 +1455,7 @@ export class Transcript {
1416
1455
  ? " [verified]"
1417
1456
  : ` [${event.taskVerification?.verdict ?? "unverified"}]`
1418
1457
  : ""
1419
- const line = ` ▪ ${sanitizeAnsiLine(id)} ${status}${parent}${deps}${rev}${verify}`
1458
+ const line = ` ${glyphs.bullet} ${sanitizeAnsiLine(id)} ${status}${parent}${deps}${rev}${verify}`
1420
1459
  const paint =
1421
1460
  raw === "FAILED"
1422
1461
  ? 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));
@@ -64,6 +64,12 @@ 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
+ /** Batas output model (`max_output_tokens`) bila endpoint melaporkannya.
68
+ * Seam aditif: dipakai loop untuk menghitung reserve output proporsional —
69
+ * tanpa ini kernel hanya bisa memakai reserve angka tetap, yang terlalu
70
+ * besar untuk model berbatas output kecil dan terlalu kecil untuk jendela
71
+ * raksasa. `undefined` = tak diketahui (pemanggil memakai default). */
72
+ maxOutputTokensForModel?: (model?: string) => number | undefined;
67
73
  toolResultMaxTokens?: number;
68
74
  keepRecentTurns?: number;
69
75
  /**
@@ -154,6 +160,7 @@ export interface SessionInternal {
154
160
  readonly maxSteps: number;
155
161
  readonly contextWindowTokens: number;
156
162
  readonly contextWindowTokensForModel?: (model?: string) => number;
163
+ readonly maxOutputTokensForModel?: (model?: string) => number | undefined;
157
164
  readonly toolResultMaxTokens: number;
158
165
  readonly keepRecentTurns: number;
159
166
  readonly timeoutMs: number;
@@ -196,6 +203,7 @@ export function createSession(config: SessionConfig): Session {
196
203
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS,
197
204
  contextWindowTokens: config.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS,
198
205
  contextWindowTokensForModel: config.contextWindowTokensForModel,
206
+ maxOutputTokensForModel: config.maxOutputTokensForModel,
199
207
  toolResultMaxTokens: config.toolResultMaxTokens ?? DEFAULT_TOOL_RESULT_MAX_TOKENS,
200
208
  keepRecentTurns: config.keepRecentTurns ?? DEFAULT_KEEP_RECENT_TURNS,
201
209
  timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
@@ -132,14 +132,27 @@ export function createOpenAICompatProvider(config: OpenAICompatConfig): ModelPro
132
132
  // the kernel would see (and execute) the same tool call twice.
133
133
  let finished = false;
134
134
  for await (const chunk of sse(response.body, signal)) {
135
- const usage = chunk.usage as { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | undefined;
135
+ const usage = chunk.usage as {
136
+ prompt_tokens?: number;
137
+ completion_tokens?: number;
138
+ total_tokens?: number;
139
+ // Fase 7: cache-hit alias (prompt_tokens_details.cached_tokens / cached_tokens).
140
+ prompt_tokens_details?: { cached_tokens?: number };
141
+ cached_tokens?: number;
142
+ } | undefined;
136
143
  // P8 + race: beberapa provider (b.ai dll) mengirim `usage` pada chunk
137
144
  // TERAKHIR setelah finish_reason. Jangan di-drop karena `finished`.
138
145
  if (usage && (usage.prompt_tokens != null || usage.completion_tokens != null || usage.total_tokens != null)) {
146
+ const cached = usage.prompt_tokens_details?.cached_tokens ?? usage.cached_tokens;
139
147
  yield {
140
148
  type: "extension",
141
149
  kind: "usage",
142
- data: { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens, totalTokens: usage.total_tokens },
150
+ data: {
151
+ inputTokens: usage.prompt_tokens,
152
+ outputTokens: usage.completion_tokens,
153
+ totalTokens: usage.total_tokens,
154
+ ...(typeof cached === "number" ? { cacheReadTokens: cached } : {}),
155
+ },
143
156
  };
144
157
  }
145
158
  if (finished) {