minicode-ai 0.22.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 (46) hide show
  1. package/cli/commands.ts +10 -0
  2. package/cli/index.ts +11 -0
  3. package/cli/setup.ts +64 -33
  4. package/cli/tui.ts +3 -3
  5. package/docs/TERMINAL_CONTRACT.md +39 -6
  6. package/docs/environment.md +3 -0
  7. package/package.json +1 -1
  8. package/src/app/session.ts +129 -20
  9. package/src/config.ts +100 -2
  10. package/src/constants.ts +29 -4
  11. package/src/policy/compaction.ts +27 -0
  12. package/src/policy/context-budget.ts +132 -0
  13. package/src/policy/context-escalation.ts +140 -0
  14. package/src/policy/context-window.ts +47 -9
  15. package/src/policy/context.ts +10 -1
  16. package/src/policy/microcompact.ts +162 -0
  17. package/src/providers/anthropic.ts +17 -3
  18. package/src/providers/detect.ts +128 -13
  19. package/src/providers/provision.ts +78 -1
  20. package/src/providers/responses.ts +13 -1
  21. package/src/session/persistence.ts +56 -0
  22. package/src/ui/assistant/simple.ts +1 -1
  23. package/src/ui/i18n/en.ts +19 -4
  24. package/src/ui/i18n/id.ts +21 -4
  25. package/src/ui/input/input.ts +2 -2
  26. package/src/ui/render/activity-panel.ts +21 -3
  27. package/src/ui/render/hint.ts +28 -0
  28. package/src/ui/render/logo.ts +91 -0
  29. package/src/ui/render/session-summary.ts +22 -1
  30. package/src/ui/render/theme.ts +5 -0
  31. package/src/ui/runtime/screen.ts +4 -2
  32. package/src/ui/screens/form.ts +19 -23
  33. package/src/ui/screens/lifecycle.ts +80 -0
  34. package/src/ui/screens/model-manager.ts +77 -81
  35. package/src/ui/screens/picker.ts +28 -22
  36. package/src/ui/screens/provider-manager.ts +47 -52
  37. package/src/ui/screens/watchdog.ts +27 -0
  38. package/src/ui/screens/wizard.ts +3 -20
  39. package/src/ui/tui/app.ts +5 -2
  40. package/src/ui/tui/transcript.ts +51 -16
  41. package/vendor/minicore/src/core/compact.ts +10 -0
  42. package/vendor/minicore/src/core/errors.ts +11 -1
  43. package/vendor/minicore/src/core/executor.ts +6 -1
  44. package/vendor/minicore/src/core/loop.ts +92 -2
  45. package/vendor/minicore/src/core/session.ts +8 -0
  46. package/vendor/minicore/src/providers/openai-compat.ts +15 -2
package/cli/commands.ts CHANGED
@@ -238,6 +238,16 @@ function statusLines(ctx: CommandContext): string[] {
238
238
  t("st.output", { v: u.outputTokens.toLocaleString() }),
239
239
  t("st.total", { v: u.totalTokens.toLocaleString() }),
240
240
  t("st.cost", { v: u.cost != null ? formatUsd(u.cost) : "N/A" }),
241
+ // Fase 7 (pengukuran cache): tampilkan hit/read hanya bila ada aktivitas cache —
242
+ // baris nol-byte untuk sesi tanpa caching (clean & minimal).
243
+ ...((u.cacheReadTokens ?? 0) > 0 || (u.cacheWriteTokens ?? 0) > 0
244
+ ? [
245
+ t("st.cache", {
246
+ read: (u.cacheReadTokens ?? 0).toLocaleString(),
247
+ write: (u.cacheWriteTokens ?? 0).toLocaleString(),
248
+ }),
249
+ ]
250
+ : []),
241
251
  t("st.budget", {
242
252
  v: ctx.budgetState(),
243
253
  extra: u.cost == null ? t("st.costUnknown") : "",
package/cli/index.ts CHANGED
@@ -543,6 +543,15 @@ let setupBar: LoadingBar | null = null
543
543
  const setupBarPhases: Record<string, { pct: number; label: MsgKey }> = {
544
544
  "provider-layer": { pct: 55, label: "loading.provider" },
545
545
  "rag-layer": { pct: 75, label: "loading.rag" },
546
+ // Load-histori resume (paling lambat saat repo berhistori banyak) — sekarang
547
+ // ter-instrumentasi via startupPhase di cli/setup.ts sehingga bar TIDAK mandeg
548
+ // diam di 75% selama loadSession/history/projection/select/workspace. Nilai pct
549
+ // hampiran berurutan; di-tune setelah MINICODE_DEBUG_STARTUP=1 diukur di repo besar.
550
+ "resume-session": { pct: 78, label: "loading.session" },
551
+ "resume-history": { pct: 82, label: "loading.session" },
552
+ "resume-projection": { pct: 84, label: "loading.session" },
553
+ "resume-select": { pct: 86, label: "loading.session" },
554
+ "resume-workspace": { pct: 88, label: "loading.session" },
546
555
  "tool-layer": { pct: 90, label: "loading.session" },
547
556
  "kernel-session": { pct: 98, label: "loading.session" },
548
557
  }
@@ -653,6 +662,8 @@ if (enterRepl) {
653
662
  sessionId: ctx.sessionId,
654
663
  model: ctx.modelRef.current ?? "default",
655
664
  totalTokens: u.totalTokens,
665
+ inputTokens: u.inputTokens,
666
+ cacheReadTokens: u.cacheReadTokens,
656
667
  ...(u.cost != null ? { cost: u.cost } : {}),
657
668
  durationMs: Date.now() - replStart,
658
669
  })
package/cli/setup.ts CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  } from "../src/app/session.ts"
14
14
  import { setupToolLayer } from "../src/app/tool-layer.ts"
15
15
  import type { MinicodeConfig } from "../src/config.ts"
16
- import { loadLastModel, localConfigNotice } from "../src/config.ts"
16
+ import { loadLang, loadLastModel, localConfigNotice } from "../src/config.ts"
17
17
  import { LIMITS } from "../src/constants.ts"
18
18
  import { runRunHooks, shouldRunHooks } from "../src/hooks/run.ts"
19
19
  import { homeDir } from "../src/lib/db-path.ts"
@@ -115,10 +115,7 @@ import {
115
115
  runtimeMetadataFromSelection,
116
116
  } from "../src/session/context-adapter.ts"
117
117
  import { type ContextOnlyArtifact, stripContextOnly } from "../src/session/context-assembly.ts"
118
- import {
119
- countDurableCompactions,
120
- deriveFrontierFromDurable,
121
- } from "../src/session/context-identity.ts"
118
+ import { deriveFrontierFromDurable } from "../src/session/context-identity.ts"
122
119
  import {
123
120
  produceSummaryProjection,
124
121
  readConsumableSummaryProjection,
@@ -148,6 +145,7 @@ import {
148
145
  appendPresentationEvents,
149
146
  backfillHistoryEventIds,
150
147
  completeRun,
148
+ countDurableCompactionEvents,
151
149
  createRun,
152
150
  DEFAULT_THREAD_ID,
153
151
  ensureDefaultThread,
@@ -156,6 +154,7 @@ import {
156
154
  listPersistedTurns,
157
155
  loadPresentationEvents,
158
156
  loadSession,
157
+ loadSessionMeta,
159
158
  loadSessionUsageSummary,
160
159
  loadSessionWorkMode,
161
160
  loadThreadHistoryWithSeq,
@@ -963,7 +962,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
963
962
  })
964
963
  const sessionId = identity.sid
965
964
  const bootId = identity.bootId
966
- startupWrite(`${c.dim(formatSessionIdentityLine(identity))}\n`)
965
+ // Identitas internal (sid/boot) — hanya --verbose; "resumed session …" sudah human-friendly.
966
+ if (verbose) startupWrite(`${c.dim(formatSessionIdentityLine(identity))}\n`)
967
967
 
968
968
  // P2.2 — admission penulis tunggal. Lease = admission; pagar mutasi =
969
969
  // writer_epoch (CAS di transaksi tulis). Komposisi ini MEMEGANG lease
@@ -985,9 +985,11 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
985
985
  )
986
986
  }
987
987
  }
988
- startupWrite(
989
- `${c.dim(`[writer] admitted sid=${sessionId} boot=${bootId} epoch=${expectedEpoch}${admission.admission.tookOver ? " (takeover)" : ""}${admission.admission.fresh ? " (fresh)" : ""}\n`)}`,
990
- )
988
+ // Lease sukses = internal; hanya --verbose (STALE/lease-lost tetap tampil).
989
+ if (verbose)
990
+ startupWrite(
991
+ `${c.dim(`[writer] admitted sid=${sessionId} boot=${bootId} epoch=${expectedEpoch}${admission.admission.tookOver ? " (takeover)" : ""}${admission.admission.fresh ? " (fresh)" : ""}\n`)}`,
992
+ )
991
993
  // [P14] Adopsi eksplisit berjalan SETELAH admission target (token target
992
994
  // sudah sah) dan SEBELUM turn pertama. Gagal = lepas lease target lalu
993
995
  // lempar error terklasifikasi; jangan pernah meninggalkan target terkunci
@@ -1360,11 +1362,17 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1360
1362
  `${c.dim(`[thread sid=${sessionId} tid=${defaultThread.thread_id} head=${defaultThread.head_seq}${backfilled > 0 ? ` backfilled=${backfilled}` : ""}]\n`)}`,
1361
1363
  )
1362
1364
  try {
1363
- const prev = loadSession(sessionId, cwd)
1364
- if (prev) {
1365
+ const meta = await startupPhase("resume-session", async () => loadSessionMeta(sessionId, cwd))
1366
+ if (meta) {
1365
1367
  resumeUsageSnapshot = loadSessionUsageSummary(sessionId, cwd)
1366
1368
  }
1367
- if (prev?.messages.length) {
1369
+ // BACA histori SEKALI (dengan seq). loadSessionMeta tidak decode messages,
1370
+ // jadi decode penuh tinggal SATU kali (dulu `loadSession` + `loadThreadHistoryWithSeq`
1371
+ // decode dua kali — akar lemot resume berhistori banyak, lihat audit perf).
1372
+ const rowsForSelector = await startupPhase("resume-history", async () =>
1373
+ loadThreadHistoryWithSeq(sessionId, defaultThread.thread_id, cwd),
1374
+ )
1375
+ if (meta && rowsForSelector.length) {
1368
1376
  // [Fase 4 / LOOP-13, LOOP-INV-16] Kumpulkan snapshot state operasional
1369
1377
  // deterministik dari sumber durable (TaskStore + usage historis) agar
1370
1378
  // header [RUNTIME_STATE_HEADER] ikut ke konteks resume — tak hilang
@@ -1381,7 +1389,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1381
1389
  totalTokens: resumeUsageSnapshot?.totalTokens ?? 0,
1382
1390
  cost: resumeUsageSnapshot?.totalCostUsd,
1383
1391
  }),
1384
- getTurnCount: () => prev.turnCount ?? 0,
1392
+ getTurnCount: () => meta.turnCount ?? 0,
1385
1393
  }
1386
1394
  operationalState = collectOperationalState(
1387
1395
  sessionId,
@@ -1400,16 +1408,15 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1400
1408
  // Batasi histori resume ke batas model, tanpa mengarang overhead.
1401
1409
  // Kernel menghitung system+tools aktual dan memadatkan sebelum request;
1402
1410
  // selector hanya membuang ke budget-tail bila pesan sendiri tak muat.
1403
- const durableEvents = loadPresentationEvents(sessionId, cwd)
1404
- const revision = countDurableCompactions(durableEvents as readonly { type: string }[])
1405
- const rowsForSelector = loadThreadHistoryWithSeq(sessionId, defaultThread.thread_id, cwd)
1411
+ // Hitung revisi kompaksi langsung dari kolom `type` — tanpa memuat +
1412
+ // decode seluruh presentation_events (dulu tarik ratusan ribu baris
1413
+ // hanya untuk menghitung revisi; kini COUNT(*) SQL, lihat audit perf).
1414
+ const revision = countDurableCompactionEvents(sessionId, cwd)
1406
1415
  // P3.4: proyeksi kanonik durable adalah sumber UTAMA untuk selector
1407
1416
  // (cakupan-valid: CURRENT atau STALE berjangkar utuh, P3.0 §8 D6),
1408
1417
  // sehingga `summary-plus-tail` menjadi perilaku produksi nyata.
1409
- const durableProjection = readConsumableSummaryProjection(
1410
- sessionId,
1411
- cwd,
1412
- defaultThread.thread_id,
1418
+ const durableProjection = await startupPhase("resume-projection", async () =>
1419
+ readConsumableSummaryProjection(sessionId, cwd, defaultThread.thread_id),
1413
1420
  )
1414
1421
  const projectionSummary = durableProjection
1415
1422
  const selectedWindow = getContextWindowTokens()
@@ -1425,15 +1432,17 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1425
1432
  rows: rowsToCanonicalRefs(selectorRows),
1426
1433
  revision,
1427
1434
  })
1428
- const selection = selectContext({
1429
- sessionId,
1430
- threadId: defaultThread.thread_id,
1431
- rows: selectorRows,
1432
- revision,
1433
- ...(projectionSummary ? { projection: projectionSummary } : {}),
1434
- policy: { budgetTokens: messageBudget, estimator: minicodeEstimator },
1435
- canonicalFrontier,
1436
- })
1435
+ const selection = await startupPhase("resume-select", async () =>
1436
+ selectContext({
1437
+ sessionId,
1438
+ threadId: defaultThread.thread_id,
1439
+ rows: selectorRows,
1440
+ revision,
1441
+ ...(projectionSummary ? { projection: projectionSummary } : {}),
1442
+ policy: { budgetTokens: messageBudget, estimator: minicodeEstimator },
1443
+ canonicalFrontier,
1444
+ }),
1445
+ )
1437
1446
  initialMessages = selection.messages as readonly Message[]
1438
1447
  // [Fase 4 / LOOP-13, LOOP-INV-16] Simpan snapshot state operasional
1439
1448
  // deterministik untuk dijadikan header di SYSTEM prompt (buffer kedua):
@@ -1452,14 +1461,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1452
1461
  runtimeContextMetadata = runtimeMetadataFromSelection(selection, revision)
1453
1462
  if (selection.contextOnly) {
1454
1463
  contextOnlyArtifact = selection.contextOnly
1455
- contextCanonicalBaseline = prev.messages
1464
+ contextCanonicalBaseline = rowsForSelector.map((r) => r.message)
1456
1465
  }
1457
- resumeTurnCount = prev.turnCount
1466
+ resumeTurnCount = meta.turnCount
1458
1467
  startupConsoleError(
1459
1468
  c.dim(
1460
1469
  // "(N messages)" dipertahankan VERBATIM (kontrak diagnostik yang
1461
1470
  // sudah dipakai test/CLI).
1462
- `[resumed session ${sessionId} (${prev.messages.length} messages)]\n`,
1471
+ `[resumed session ${sessionId} (${rowsForSelector.length} messages)]\n`,
1463
1472
  ),
1464
1473
  )
1465
1474
  // P3.3 — jejak provenance seleksi (baca-saja; tak mengubah perilaku).
@@ -1471,7 +1480,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1471
1480
  // P3 — validasi resume: bukan replay buta. Bila workspace berubah
1472
1481
  // sejak checkpoint terakhir (edit manual / run lain), beri tahu —
1473
1482
  // /undo tersedia bila perlu kembali. Best-effort, tak menggagalkan resume.
1474
- const div = await validateResumeWorkspace(cwd ?? ".", sessionId).catch(() => null)
1483
+ const div = await startupPhase("resume-workspace", async () =>
1484
+ validateResumeWorkspace(cwd ?? ".", sessionId).catch(() => null),
1485
+ )
1475
1486
  if (div && div.diverged > 0) {
1476
1487
  startupConsoleError(
1477
1488
  c.yellow(
@@ -1941,6 +1952,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1941
1952
 
1942
1953
  let permissions: PermissionControl | undefined
1943
1954
  let noProgressDetector: NoProgressDetector | null = null
1955
+ // Jendela konteks hasil eskalasi adaptif (0 = belum ada). Dipakai /status
1956
+ // untuk menampilkan angka efektif, bukan tebakan awal.
1957
+ const escalatedWindowRef = { current: 0 }
1944
1958
  const effectiveMaxTurns = (() => {
1945
1959
  const raw = (opts as { maxTurns?: number }).maxTurns ?? Number(process.env.MINICODE_MAX_TURNS)
1946
1960
  return typeof raw === "number" && Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : undefined
@@ -1954,11 +1968,17 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1954
1968
  const v = opts.writeConcurrency
1955
1969
  return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : undefined
1956
1970
  })()
1971
+ // Muat state.json.lang LEBIH AWAL (tui.ts memuatnya setelah sesi terbangun) agar
1972
+ // direktif chat di system prompt ikut pilihan user; resolusi tetap currentLocale().
1973
+ const { currentLocale, setConfigLocale } = await import("../src/ui/i18n/locale.ts")
1974
+ setConfigLocale((await loadLang().catch(() => undefined)) ?? null)
1975
+ const sessionLang = currentLocale()
1957
1976
  const session = await startupPhase("kernel-session", () =>
1958
1977
  createMinicodeSession({
1959
1978
  provider: router,
1960
1979
  tools: sessionTools,
1961
1980
  cwd,
1981
+ lang: sessionLang,
1962
1982
  permissionMode,
1963
1983
  restrictBash,
1964
1984
  allowLocalConfig,
@@ -2020,6 +2040,17 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2020
2040
  onNoProgress: (detector) => {
2021
2041
  noProgressDetector = detector
2022
2042
  },
2043
+ // Eskalasi jendela konteks: beritahu user secara eksplisit. Tanpa ini,
2044
+ // jendela yang naik otomatis terasa seperti angka ajaib — user perlu tahu
2045
+ // bahwa ada BUKTI overflow dan berapa nilai barunya, agar bisa memutuskan
2046
+ // menyetel `contextWindows` permanen bila perlu.
2047
+ onContextWindowEscalated: (info) => {
2048
+ startupWrite(
2049
+ `${c.yellow(`[context] window raised ${info.fromTokens} → ${info.toTokens} tokens for ${sanitizeAnsi(info.model)} after a verified context overflow (observed ${info.observedTokens}). Set provider.contextWindows to make it permanent.
2050
+ `)}`,
2051
+ )
2052
+ escalatedWindowRef.current = info.toTokens
2053
+ },
2023
2054
  ...(maxSteps ? { maxSteps } : {}),
2024
2055
  ...(keepRecentTurns ? { keepRecentTurns } : {}),
2025
2056
  ...(safeConcurrency ? { concurrency: safeConcurrency } : {}),
package/cli/tui.ts CHANGED
@@ -36,7 +36,7 @@ import type { UiBus } from "../src/ui/contract.ts"
36
36
  import { t } from "../src/ui/i18n/locale.ts"
37
37
  import { loadHistory } from "../src/ui/input/input.ts"
38
38
  import { formatUsd } from "../src/ui/render/money.ts"
39
- import { c } from "../src/ui/render/theme.ts"
39
+ import { c, glyphs } from "../src/ui/render/theme.ts"
40
40
  // [Area A · PROMPT 06] State UI milik SESI ini. TUI + printer linier sesi yang
41
41
  // sama berbagi state (satu instance), sesi lain di proses yang sama tak
42
42
  // tersentuh. Absen = instance default (fixture tes partial).
@@ -629,7 +629,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
629
629
  // WorkMode EXECUTE (BUILD) agar ceiling DISCUSS/PLAN tak menahan tulis.
630
630
  workModeControl?.setWorkMode("EXECUTE")
631
631
  app.repaint()
632
- transcript.pushInfo([c.warning(t("tui.unrestrictedOn"))])
632
+ transcript.pushInfo([c.warning(`${glyphs.unlock} ${t("tui.unrestrictedOn")}`)])
633
633
  return
634
634
  }
635
635
  mode = modeBeforeUnrestricted ?? "auto"
@@ -643,7 +643,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
643
643
  modeBeforeUnrestricted = null
644
644
  workModeBeforeUnrestricted = null
645
645
  app.repaint()
646
- transcript.pushInfo([c.muted(t("tui.unrestrictedOff", { m: mode }))])
646
+ transcript.pushInfo([c.muted(`${glyphs.unlock} ${t("tui.unrestrictedOff", { m: mode })}`)])
647
647
  return
648
648
  }
649
649
  if (name === "lang") {
@@ -1,4 +1,24 @@
1
- # Kontrak Terminal MiniCode (TUI fullscreen — v7.12, 2026-11-10)
1
+ # Kontrak Terminal MiniCode (TUI fullscreen — v7.13, 2026-11-13)
2
+
3
+ Perubahan v7.13: baris status kompaksi (`context:compacted`) kini **membedakan
4
+ hasil** alih-alih mencetak `reason` mentah. Sebelumnya sesi yang konteksnya TIDAK
5
+ menyusut tampil sebagai `… dipadatkan: pressure:critical:no-op` — terbaca seolah
6
+ berhasil, padahal turn berikutnya tetap kehabisan konteks. Empat kondisi sekarang
7
+ punya label berbeda karena tindak lanjut user berbeda: `… dipadatkan: tidak ada
8
+ yang bisa dibuang (<sebab>) — konteks tidak menyusut` (no-op), `… kompaksi
9
+ berhenti: target tak tercapai meski hanya N pesan tersisa` (fixpoint), `…
10
+ kompaksi mustahil: instruksi tetap + skema tool (N) sudah melebihi ambang M`
11
+ (biaya tetap), dan `… ringkasan LLM gagal (<sebab>), memakai ringkasan
12
+ mekanikal`. Label tetap satu baris redup (`c.muted`) dan tetap melewati
13
+ `sanitizeAnsiLine` sebelum tampil — teks sebab berasal dari error provider/model
14
+ (input tak terpercaya). Sumber: `src/ui/tui/transcript.ts` (`compactedLabel`),
15
+ kunci i18n `ts.compactedNoOp`/`ts.compactedFixpoint`/`ts.compactedImpossible`/
16
+ `ts.compactedLlmFailed`, dan emisi `reason` dari `vendor/minicore/src/core/
17
+ loop.ts`. Peta proteksi: `test/tui-classic.test.ts` (kontrak render transkrip)
18
+ + `test/compaction-limits.test.ts` (alasan `impossible:`/`fixpoint` yang
19
+ mendarat di event) + `test/control-plane.test.ts` (`llm-failed:` dilaporkan).
20
+ Nol perubahan pada lebar/geometri: label hanya teks lebih panjang pada jalur
21
+ yang sama, tetap dipotong sesuai aturan baris status yang ada.
2
22
 
3
23
  Perubahan v7.12: footer `context` & `metrics` (window %) kini **live per step**
4
24
  selama turn berjalan — kernel meng-emit estimasi konteks turn-store via event
@@ -177,11 +197,15 @@ Non-TTY (pipe/redirect/CI/file): **0 cursor control, 0 alternate screen,
177
197
  fail-closed di non-TTY/`TERM=dumb`. Siklus hidup region: render yang
178
198
  menyusut/bergeser membersihkan union lama+baru (tanpa baris hantu); tutup
179
199
  menghapus region sendiri sebelum pemilik repaint.
200
+ - `screen.ts` juga pemilik bentuk kursor: DECSCUSR `6 q` (bar tegak stabil)
201
+ dipancarkan saat caret ditampilkan (`paint`/`moveCursor`) — caret tak
202
+ menutupi karakter di bawahnya dan lebih tenang (clean & minimal). Tetap
203
+ TTY-only: non-TTY = 0 cursor control.
180
204
  - Isi popup: kotak terpusat (`dialog.ts`: border, judul opsional dalam garis
181
205
  atas, TANPA bayangan) di atas konten redup; `dialogBox` untuk komposit,
182
206
  `dialogFrame` (backdrop `░` faint) hanya untuk layar yang memiliki buffer
183
207
  sendiri.
184
- - **Lebar kotak popup TETAP** per permukaan (model 64, picker 64, provider 52,
208
+ - **Lebar kotak popup TETAP** per permukaan (model 64, picker 64, provider 64,
185
209
  form 64 — min=max): geometri stabil, tak bernapas saat filter/error.
186
210
  Nama/ID di DEPAN label (truncasi memakan ekor — tanggal/konteks boleh
187
211
  hilang, id selamat).
@@ -213,6 +237,13 @@ Non-TTY (pipe/redirect/CI/file): **0 cursor control, 0 alternate screen,
213
237
  `Del` + confirm dalam popup, tercatat); navigasi daftar = `↑↓` + `pgup/
214
238
  pgdn` + `home/end` di semua popup ber-daftar; hint footer tiap permukaan
215
239
  hanya tombol yang benar-benar berlaku di sana.
240
+ - **Hint aksi minimalis** (audit UI/UX 2026-11): satu baris di dasar body
241
+ picker/manager (`src/ui/render/hint.ts`, satu sumber), format `kunci label`
242
+ — kunci lebih terang, label redup, pemisah `·` — tanpa judul dan tanpa
243
+ footer dekoratif di dalam kotak. `/model`: **Enter = pilih model satu
244
+ langkah** (tanpa picker effort); **Tab = ubah thinking effort** terpisah
245
+ (Esc pada picker effort = batal effort, kembali ke daftar — manajer tak
246
+ pernah menutup diri di sana).
216
247
  - Approval tool & ask_user: blok pertanyaan + keputusan DICATAT di transkrip
217
248
  (jejak audit) dan layar di-repaint sebelum menjawab; input via askLine di
218
249
  baris kursor (aman: input App beku saat busy; Esc/Ctrl+C = abort + deny).
@@ -259,7 +290,7 @@ Non-TTY (pipe/redirect/CI/file): **0 cursor control, 0 alternate screen,
259
290
  geometri popup, dialog, dan viewport TUI.
260
291
  12. Long session tetap readable (cap 5000 baris, tertua dibuang). Proyeksi
261
292
  presentasi mempertahankan cap yang sama dan menambahkan satu marker
262
- `… N baris awal di luar viewport — riwayat penuh di model` yang melacak
293
+ `… N baris awal di luar viewport` yang melacak
263
294
  jumlah baris yang di-evict; `total()` tetap monotonik. Buffer jawaban
264
295
  live dibatasi 1.000.000 karakter dan menampilkan marker truncasi; satu
265
296
  layout paint tidak boleh memproyeksikan transcript dua kali.
@@ -337,7 +368,7 @@ Non-TTY (pipe/redirect/CI/file): **0 cursor control, 0 alternate screen,
337
368
  berkas histori lama). `/copy [n]` menyalin 1–10 turn terakhir (default 1,
338
369
  oldest-to-newest) melalui OSC 52.
339
370
  19. Dropdown `/` inline berbingkai; Enter pada menu melengkapi + kirim.
340
- 20. Lebar kotak popup TETAP per permukaan (model 64, picker 64, provider 52,
371
+ 20. Lebar kotak popup TETAP per permukaan (model 64, picker 64, provider 64,
341
372
  form 64 — min=max); nama/ID di depan label; seleksi murni warna; search
342
373
  selalu tampil.
343
374
  21. Form dalam popup: semua input teks/pilihan di dalam kotak (text/secret/
@@ -369,8 +400,10 @@ Non-TTY (pipe/redirect/CI/file): **0 cursor control, 0 alternate screen,
369
400
  `/help full`, pintasan via `/help keys`).
370
401
  25. Keybinding konsisten: Esc dua-tahap (isi tak hilang sekali tekan);
371
402
  backspace/delete edit-teks (hapus-data = confirm); navigasi daftar
372
- (`↑↓`, pgup/pgdn, home/end) di semua popup; hint footer akurat
373
- per permukaan; kursor diparkir di semua permukaan.
403
+ (`↑↓`, pgup/pgdn, home/end) di semua popup; hint aksi minimalis
404
+ (`kunci label`, kunci terang/label redup) akurat per permukaan;
405
+ kursor diparkir di semua permukaan; Enter `/model` = pilih satu
406
+ langkah, Tab = ubah effort.
374
407
  26. i18n dwibahasa: semua string user-visible lewat `t()`; id kunci = en
375
408
  (tsc mengawal); fallback kunci hilang → en; prioritas sesi > env >
376
409
  state.json > locale OS > en (di OS: `LC_ALL` > `LANG`, string kosong
@@ -57,6 +57,9 @@ Variabel yang paling menentukan perilaku (sisanya referensi di bawah):
57
57
  | `MINICODE_PROVIDER_ORDER` | Urutkan provider agnostik tanpa edit config: `openai,anthropic,deepseek` |
58
58
  | `MINICODE_EMBED_MODEL` | Model embedding untuk memory/vector (default `text-embedding-3-small`) |
59
59
  | `MINICODE_COMPACT_KEEP_TURNS` | Override keepRecentTurns kompaksi (bilangan ≥1; invalid → default kernel + warn) |
60
+ | `MINICODE_MICROCOMPACT` | `0` → matikan pemangkasan isi hasil tool lama (lapisan termurah sebelum kompaksi penuh). Default aktif; matikan bila sesi butuh seluruh output tool verbatim |
61
+ | `MINICODE_PROMPT_CACHE` | `0` → matikan prompt caching (`cache_control: ephemeral` Anthropic). Default aktif; kill-switch runtime bila gateway menolak header cache atau untuk diagnostik hit-rate (berpasangan dengan metrik cache di ringkasan sesi/`/status`) |
62
+ | `MINICODE_CONTEXT_PROBE` | `0` → matikan eskalasi adaptif jendela konteks (probe reaktif setelah overflow terverifikasi). Default aktif; probe juga dibatasi anggaran per-model/per-proses terlepas dari nilai ini |
60
63
  | `MINICODE_MEMORY_SCOPE` | Scope baca memory: `cwd` (default) \| `global` \| `all` (gabung, tanpa silent shadowing) |
61
64
  | `MINICODE_AUTO_MEMORY` | `0` → matikan auto-simpan summary/snippet ke memory (opt-out) |
62
65
  | `MINICODE_READ_VOLUME_GUARD` | `1` → aktifkan peringatan sekali per turn saat volume baca (char hasil tool) melewati ambang — penanda "banyak dibaca tanpa kompaksi" (risiko degradasi working-memory, bukan jendela token); default nonaktif |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minicode-ai",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Open-source terminal coding agent on a vendored zero-dependency MiniCore kernel — layered permissions, path jail, sandboxing, MCP/LSP, and durable shadow-git checkpoints",
5
5
  "type": "module",
6
6
  "private": false,
@@ -26,6 +26,8 @@ import {
26
26
  createIncrementalTokenCounter,
27
27
  minicodeEstimator,
28
28
  } from "../policy/context.ts"
29
+ import { contextBudgetFor, outputReserveFor } from "../policy/context-budget.ts"
30
+ import { nextLadderStep } from "../policy/context-escalation.ts"
29
31
  import { DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS } from "../policy/context-window.ts"
30
32
  import { parallelExecutor } from "../policy/executor.ts"
31
33
  import {
@@ -148,6 +150,8 @@ export async function createMinicodeSession(
148
150
  Omit<SessionConfig, "permissions" | "estimator" | "recovery" | "system" | "executor">
149
151
  > & {
150
152
  systemExtra?: string
153
+ /** Bahasa chat model ("id"/"en"); undefined = tanpa direktif (test/bench). */
154
+ lang?: "en" | "id"
151
155
  cwd?: string
152
156
  /** Live model identity used for per-model token calibration. */
153
157
  getContextModel?: () => string | undefined
@@ -190,6 +194,18 @@ export async function createMinicodeSession(
190
194
  noProgress?: NoProgressOptions | false
191
195
  /** Hook opsional agar composition root dapat mereset riwayat osilasi saat verify hijau. */
192
196
  onNoProgress?: (detector: NoProgressDetector) => void
197
+ /**
198
+ * Dipanggil saat jendela konteks dinaikkan otomatis setelah overflow
199
+ * terverifikasi. Composition root memakainya untuk memberi tahu user
200
+ * (footer/log) dan — bila diinginkan — mempersistensikan nilai baru.
201
+ * Tidak pernah dipanggil untuk 429/402/auth/jaringan.
202
+ */
203
+ onContextWindowEscalated?: (info: {
204
+ model: string
205
+ fromTokens: number
206
+ toTokens: number
207
+ observedTokens: number
208
+ }) => void
193
209
  /**
194
210
  * [Area B · PROMPT 06] Penyimpanan binding persetujuan milik SESI.
195
211
  *
@@ -267,6 +283,7 @@ export async function createMinicodeSession(
267
283
  cwd: defaultCwd,
268
284
  extra: opts.systemExtra ?? "",
269
285
  signal: (opts as unknown as { signal?: AbortSignal }).signal,
286
+ lang: opts.lang,
270
287
  })
271
288
  const {
272
289
  concurrency,
@@ -540,15 +557,48 @@ export async function createMinicodeSession(
540
557
  let lastProviderInputTokens: number | undefined
541
558
  let lastRequestMessageCount = 0
542
559
  const contextWindowForModel = (model?: string): number => {
560
+ // Eskalasi adaptif menang atas resolusi statis: ia adalah bukti dari
561
+ // endpoint bahwa jendela lebih besar daripada tebakan. Tetap tunduk pada
562
+ // nilai eksak operator? TIDAK: operator yang memasang flag eksplisit sudah
563
+ // dihormati di `contextWindowBase`, namun bila flag itu TERBUKTI kurang
564
+ // (overflow nyata terjadi), menaikkan satu anak tangga lebih benar daripada
565
+ // mengulang kegagalan yang sama.
566
+ const escalated = escalatedWindows.get(escalationKey(model))
567
+ if (escalated !== undefined) return escalated
568
+ return contextWindowBase(model)
569
+ }
570
+ // Batas output model: dipakai sebagai reserve output (bukan angka tetap 20k).
571
+ // Dicari dari metadata provider (`maxOutputTokens`, diisi dari `/models` bila
572
+ // endpoint melaporkannya); tanpa metadata → `undefined` = reserve default.
573
+ const maxOutputTokensForModel = (model?: string): number | undefined => {
574
+ try {
575
+ const fromCore = rest.maxOutputTokensForModel?.(model)
576
+ if (typeof fromCore === "number" && Number.isSafeInteger(fromCore) && fromCore > 0)
577
+ return fromCore
578
+ const fromProvider = (
579
+ provider as { maxOutputTokensForModel?: (m?: string) => number }
580
+ ).maxOutputTokensForModel?.(model)
581
+ if (
582
+ typeof fromProvider === "number" &&
583
+ Number.isSafeInteger(fromProvider) &&
584
+ fromProvider > 0
585
+ )
586
+ return fromProvider
587
+ } catch {}
588
+ return undefined
589
+ }
590
+ // ── Eskalasi adaptif jendela konteks ───────────────────────────────────
591
+ // Nilai yang dinaikkan SESI INI saja (bukan ditulis ke config: perubahan
592
+ // konfigurasi harus lewat /sync atau niat operator). Kunci = `provider::model`
593
+ // ternormalisasi; nilai = jendela hasil eskalasi.
594
+ const escalatedWindows = new Map<string, number>()
595
+ const escalationKey = (model?: string): string => {
596
+ const raw = model ?? currentContextModel() ?? "default"
597
+ return raw.includes("::") ? raw : `${provider.id}::${raw}`
598
+ }
599
+ /** Jendela "dasar" sebelum eskalasi: hasil resolusi biasa, tanpa eskalasi. */
600
+ const contextWindowBase = (model?: string): number => {
543
601
  const explicit = rest.contextWindowTokens
544
- if (
545
- !rest.contextWindowTokensForModel &&
546
- typeof explicit === "number" &&
547
- Number.isSafeInteger(explicit) &&
548
- explicit > 0
549
- ) {
550
- return explicit
551
- }
552
602
  try {
553
603
  const resolved =
554
604
  rest.contextWindowTokensForModel?.(model) ?? provider.contextWindowTokensForModel?.(model)
@@ -559,6 +609,33 @@ export async function createMinicodeSession(
559
609
  ? explicit
560
610
  : DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS
561
611
  }
612
+ /**
613
+ * Naikkan jendela satu anak tangga setelah overflow terverifikasi.
614
+ *
615
+ * KENAPA otomatis: user yang sedang bekerja tidak bisa tahu ada anak tangga
616
+ * berikutnya — dan sesi yang mati di tengah jalan jauh lebih mahal daripada
617
+ * satu eskalasi. Namun ia tetap BOUNDED: satu langkah per kejadian, tak
618
+ * pernah melebihi batas atas, dan hasilnya hanya berlaku untuk sesi ini.
619
+ */
620
+ const escalateContextWindow = (model: string | undefined, observedTokens: number) => {
621
+ const key = escalationKey(model)
622
+ const base = escalatedWindows.get(key) ?? contextWindowBase(model)
623
+ // Bila pengamatan sudah jelas melampaui jendela dasar, naik dari nilai
624
+ // pengamatan; kalau tidak, naik dari jendela yang sekarang dipakai.
625
+ const from = Math.max(base, Number.isFinite(observedTokens) ? observedTokens : 0)
626
+ const next = nextLadderStep(from)
627
+ if (next === undefined || next <= base) return
628
+ escalatedWindows.set(key, next)
629
+ try {
630
+ rest.onContextWindowEscalated?.({
631
+ model: key,
632
+ fromTokens: base,
633
+ toTokens: next,
634
+ observedTokens,
635
+ })
636
+ } catch {}
637
+ }
638
+
562
639
  const dynamicProvider: ModelProvider = {
563
640
  id: provider.id,
564
641
  get models() {
@@ -568,6 +645,7 @@ export async function createMinicodeSession(
568
645
  const system = computeLiveSystem()
569
646
  const model = req.model ?? currentContextModel()
570
647
  let limit = contextWindowForModel(model)
648
+ const maxOutputTokens = maxOutputTokensForModel(model)
571
649
  const estimatorModel = model?.includes("::") ? model : (currentContextModel() ?? model)
572
650
  let calibration = calibrationFor(estimatorModel)
573
651
  let estimator = (text: string) => preciseEstimator(estimatorModel, text)
@@ -598,10 +676,11 @@ export async function createMinicodeSession(
598
676
  }
599
677
  // Sisakan ruang framing dan respons minimum. Tanpa reserve, request yang
600
678
  // tepat menyentuh batas provider tetap ditolak setelah biaya dibakar.
601
- // Reserve ini HANYA headroom framing + respons minimum (skema tool sudah
602
- // termasuk di `inputTokens` via estimateTools), jadi cap 256 cukup —
603
- // tidak perlu diskala dengan ukuran skema tool.
604
- let reserve = Math.min(LIMITS.CONTEXT_WINDOW_RESERVE_CAP_TOKENS, Math.floor(limit / 10))
679
+ // Reserve dihitung dari anggaran konteks terpusat (`context-budget.ts`):
680
+ // `min(max_output_tokens, 20k)` dengan lantai 4k dan lantai 2% jendela.
681
+ // Nilai lama `min(256, limit/10)` praktis nol untuk jendela besar, jadi
682
+ // model berjendela 1M tetap kehabisan ruang jawaban di ambang batas.
683
+ let reserve = outputReserveFor(limit, maxOutputTokens)
605
684
  let outputAllowance = Math.max(0, limit - inputTokens - reserve)
606
685
  let outputTokens = 0
607
686
  const streamedText = createIncrementalTokenCounter()
@@ -626,6 +705,13 @@ export async function createMinicodeSession(
626
705
  // jalur recovery `force_compact_and_retry`: meringkas lalu coba lagi,
627
706
  // alih-alih mati `✗ Context window exceeded`. Bounded — loop recovery
628
707
  // menolak bila kompaksi no-op (compactedForRecovery sudah set).
708
+ //
709
+ // Eskalasi adaptif: overflow INI adalah bukti terverifikasi bahwa jendela
710
+ // yang kita pakai terlalu kecil ATAU penuh. Naikkan satu anak tangga untuk
711
+ // sesi ini supaya percobaan berikutnya (dan turn berikut) punya ruang.
712
+ // Hanya dipanggil pada jalur yang benar-benar kehabisan konteks — bukan
713
+ // 429/402/auth/jaringan.
714
+ escalateContextWindow(model, actualInput + actualOutput)
629
715
  return new ProviderError(
630
716
  "context_length_exceeded",
631
717
  `context window budget reached for the selected model: input ${actualInput} + output ${actualOutput} exceeds ${limit} tokens; reduce the prompt/tools or select a larger context window`,
@@ -665,7 +751,7 @@ export async function createMinicodeSession(
665
751
  estimateSystem(system, estimator) +
666
752
  estimateTools(tools, estimator),
667
753
  )
668
- reserve = Math.min(LIMITS.CONTEXT_WINDOW_RESERVE_CAP_TOKENS, Math.floor(limit / 10))
754
+ reserve = outputReserveFor(limit, maxOutputTokens)
669
755
  outputAllowance = Math.max(0, limit - inputTokens - reserve)
670
756
  }
671
757
  }
@@ -677,7 +763,7 @@ export async function createMinicodeSession(
677
763
  estimateSystem(system, estimator) +
678
764
  estimateTools(tools, estimator),
679
765
  )
680
- reserve = Math.min(LIMITS.CONTEXT_WINDOW_RESERVE_CAP_TOKENS, Math.floor(limit / 10))
766
+ reserve = outputReserveFor(limit, maxOutputTokens)
681
767
  outputAllowance = Math.max(0, limit - inputTokens - reserve)
682
768
  }
683
769
  admittedFactor = currentFactor
@@ -706,14 +792,16 @@ export async function createMinicodeSession(
706
792
  // sebenarnya konteks kepanjangan meski teksnya tak menyebut "context".
707
793
  // Reklasifikasi sebagai context_length_exceeded supaya kernel menempuh
708
794
  // compact-and-retry (bounded + no-op-safe) alih-alih mati fatal. Ambang
709
- // `localInputTokens >= CONTEXT_RECLASSIFY_400_MIN_LOCAL_TOKENS` = proxy
710
- // monotonik ukuran konteks berbasis chars/token estimator (toleran
711
- // terhadap under-count); sesi kecil dengan 400 format-argumen yang sah
712
- // tidak akan salah diklasifikasi.
795
+ // tanngal
796
+ // `localInputTokens >= contextReclassifyThreshold(limit)` — ambang
797
+ // RELATIF jendela (`min(50_000, window*0.5)`), bukan 50.000 mutlak.
798
+ // Angka mutlak membuat model berjendela < 50k mustahil menempuh
799
+ // compact-and-retry: jendelanya penuh jauh sebelum ambang tercapai,
800
+ // sehingga 400 generik selalu mati fatal.
713
801
  if (
714
802
  error instanceof ProviderError &&
715
803
  (error.category === "invalid_request" || error.category === "unknown") &&
716
- localInputTokens >= LIMITS.CONTEXT_RECLASSIFY_400_MIN_LOCAL_TOKENS
804
+ localInputTokens >= contextBudgetFor(limit, maxOutputTokens).reclassifyThreshold
717
805
  ) {
718
806
  throw overflow(inputTokens, outputTokens)
719
807
  }
@@ -736,6 +824,7 @@ export async function createMinicodeSession(
736
824
  ...rest,
737
825
  contextWindowTokens: contextWindowForModel(currentContextModel()),
738
826
  contextWindowTokensForModel: contextWindowForModel,
827
+ maxOutputTokensForModel: maxOutputTokensForModel,
739
828
  // Kompaksi lebih agresif (host-side): ringkas mulai 65% jendela, bukan 75%.
740
829
  budget: aggressiveBudgetPolicy,
741
830
  provider: dynamicProvider,
@@ -873,7 +962,27 @@ export async function createMinicodeSession(
873
962
  },
874
963
  run(input: string, runOpts?: { signal?: AbortSignal; model?: string }) {
875
964
  activeContextModel = runOpts?.model ?? opts.model
876
- return core.run(input, runOpts)
965
+ const modelForRun = activeContextModel
966
+ return core.run(input, runOpts).catch((error: unknown) => {
967
+ // Kernel melaporkan kehabisan konteks sebagai `budget_exceeded` dengan
968
+ // `details.reason` = `fixpoint` atau `critical`. Keduanya BUKTI
969
+ // terverifikasi bahwa jendela yang dipakai terlalu kecil untuk sesi ini
970
+ // — sama sahnya dengan penolakan provider. Tanpa eskalasi di sini,
971
+ // sesi yang sudah di titik tetap langsung mati padahal endpoint mungkin
972
+ // punya kapasitas jauh lebih besar.
973
+ //
974
+ // Bukan pemicu: `max_steps_exceeded`, `max_turns`, `aborted`, timeout,
975
+ // dan error provider non-konteks — menaikkan jendela tak akan menolong.
976
+ if (error instanceof AgentError && error.kind === "budget_exceeded") {
977
+ const reason = error.details?.reason
978
+ if (reason === "fixpoint" || reason === "critical") {
979
+ const used =
980
+ typeof error.details?.fixedTokens === "number" ? error.details.fixedTokens : 0
981
+ escalateContextWindow(modelForRun, used)
982
+ }
983
+ }
984
+ throw error
985
+ })
877
986
  },
878
987
  abort() {
879
988
  core.abort()