minicode-ai 0.14.1 → 0.14.4

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 (130) hide show
  1. package/README.md +34 -178
  2. package/cli/args.ts +10 -18
  3. package/cli/auto-update.ts +32 -2
  4. package/cli/commands/acp.ts +20 -27
  5. package/cli/commands/daemon.ts +6 -7
  6. package/cli/commands/exec.ts +12 -10
  7. package/cli/commands.ts +6 -9
  8. package/cli/index.ts +40 -17
  9. package/cli/provider-manager.ts +1 -3
  10. package/cli/setup.ts +174 -145
  11. package/cli/tui.ts +33 -38
  12. package/docs/CONTROL-PLANE-MAP.md +145 -0
  13. package/docs/OUTPUT_EVENT_MODEL.md +1 -1
  14. package/docs/OUTPUT_PROTOCOL_SPEC.md +8 -2
  15. package/docs/OUTPUT_RENDERING_SPEC.md +35 -6
  16. package/docs/OUTPUT_UX_RULES.md +1 -1
  17. package/docs/README.md +14 -102
  18. package/docs/SUMMARY.md +53 -0
  19. package/docs/TERMINAL_CONTRACT.md +136 -77
  20. package/docs/UI_RENDER_PIPELINE.md +204 -0
  21. package/docs/agents.md +5 -5
  22. package/docs/architecture.md +23 -12
  23. package/docs/choosing-mode.md +7 -7
  24. package/docs/cli.md +22 -29
  25. package/docs/concepts.md +1 -1
  26. package/docs/config.md +10 -5
  27. package/docs/contributing.md +6 -6
  28. package/docs/environment.md +3 -1
  29. package/docs/exec.md +5 -5
  30. package/docs/getting-started.md +14 -12
  31. package/docs/glossary.md +9 -7
  32. package/docs/mcp-lsp.md +1 -1
  33. package/docs/memory-sessions.md +7 -5
  34. package/docs/policy-sandbox.md +23 -15
  35. package/docs/quickstart.md +2 -2
  36. package/docs/repl.md +4 -3
  37. package/docs/security-model.md +16 -17
  38. package/docs/security.md +15 -30
  39. package/docs/skills.md +1 -1
  40. package/docs/tools.md +6 -6
  41. package/docs/verify-benchmark.md +16 -0
  42. package/package.json +5 -5
  43. package/scripts/vendor-overlays/minicode-context.patch +109 -0
  44. package/src/app/mentions.ts +4 -3
  45. package/src/app/provider-layer.ts +13 -1
  46. package/src/app/session.ts +229 -22
  47. package/src/app/tool-layer.ts +6 -0
  48. package/src/config.ts +30 -3
  49. package/src/constants.ts +19 -0
  50. package/src/daemon/control.ts +1 -1
  51. package/src/lib/git-hardening.ts +27 -22
  52. package/src/lib/safe-open.ts +73 -19
  53. package/src/lib/trusted-exec.ts +7 -4
  54. package/src/mcp/client.ts +34 -9
  55. package/src/mcp/server.ts +2 -3
  56. package/src/mcp/transport.ts +96 -42
  57. package/src/memory/files.ts +15 -4
  58. package/src/memory/vector.ts +5 -1
  59. package/src/policy/compaction.ts +272 -16
  60. package/src/policy/context-window.ts +73 -0
  61. package/src/policy/context.ts +76 -16
  62. package/src/policy/ratelimit.ts +47 -18
  63. package/src/policy/tool-contract.ts +4 -10
  64. package/src/policy/update-check.ts +83 -6
  65. package/src/policy/usage.ts +31 -14
  66. package/src/policy/work-mode.ts +1 -1
  67. package/src/presentation/adapter.ts +64 -2
  68. package/src/presentation/events.ts +6 -0
  69. package/src/presentation/model.ts +1 -0
  70. package/src/presentation/projection.ts +2 -0
  71. package/src/presentation/reducer.ts +1 -0
  72. package/src/providers/anthropic.ts +52 -19
  73. package/src/providers/guards.ts +158 -16
  74. package/src/providers/provision.ts +12 -3
  75. package/src/providers/responses.ts +61 -23
  76. package/src/providers/router.ts +56 -23
  77. package/src/providers/sse-bounds.ts +170 -0
  78. package/src/repo/repomap.ts +10 -11
  79. package/src/runtime/execution-backend.ts +7 -8
  80. package/src/sandbox/docker.ts +113 -9
  81. package/src/session/checkpoint.ts +9 -2
  82. package/src/session/context-projection.ts +14 -0
  83. package/src/session/context-selector.ts +58 -20
  84. package/src/session/persistence.ts +6 -3
  85. package/src/session/verification.ts +55 -16
  86. package/src/skills/loader.ts +16 -3
  87. package/src/task/model.ts +21 -70
  88. package/src/tools/bash.ts +6 -3
  89. package/src/tools/code_run.ts +6 -5
  90. package/src/tools/context.ts +8 -0
  91. package/src/tools/delete_file.ts +2 -1
  92. package/src/tools/edit.ts +2 -1
  93. package/src/tools/git.ts +128 -54
  94. package/src/tools/glob.ts +2 -1
  95. package/src/tools/grep.ts +31 -6
  96. package/src/tools/lsp.ts +5 -4
  97. package/src/tools/mcp_call.ts +3 -1
  98. package/src/tools/memory.ts +175 -180
  99. package/src/tools/move_file.ts +2 -1
  100. package/src/tools/patch.ts +2 -1
  101. package/src/tools/read_file.ts +94 -1
  102. package/src/tools/read_image.ts +2 -1
  103. package/src/tools/task.ts +9 -1
  104. package/src/tools/todo.ts +4 -5
  105. package/src/tools/web_fetch.ts +28 -12
  106. package/src/tools/web_search.ts +28 -9
  107. package/src/tools/write_file.ts +2 -1
  108. package/src/ui/assistant/simple.ts +72 -3
  109. package/src/ui/footer.ts +131 -66
  110. package/src/ui/i18n/en.ts +3 -11
  111. package/src/ui/i18n/id.ts +3 -11
  112. package/src/ui/input/input.ts +2 -3
  113. package/src/ui/input/prompt-engine.ts +2 -5
  114. package/src/ui/render/width.ts +107 -79
  115. package/src/ui/runtime/screen.ts +49 -37
  116. package/src/ui/screens/model-manager.ts +3 -10
  117. package/src/ui/screens/picker.ts +23 -40
  118. package/src/ui/screens/provider-manager.ts +12 -33
  119. package/src/ui/screens/wizard.ts +0 -1
  120. package/src/ui/tui/app.ts +265 -211
  121. package/src/ui/tui/transcript.ts +87 -8
  122. package/vendor/minicore/VENDOR.md +9 -5
  123. package/vendor/minicore/src/core/loop.ts +47 -12
  124. package/vendor/minicore/src/core/provider.ts +4 -0
  125. package/vendor/minicore/src/core/session.ts +14 -1
  126. package/CHANGELOG.md +0 -1185
  127. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +0 -489
  128. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +0 -391
  129. package/docs/PLAN_UIUX_V6.md +0 -209
  130. package/docs/changelog.md +0 -3
package/cli/setup.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  import { setupToolLayer } from "../src/app/tool-layer.ts"
15
15
  import type { MinicodeConfig } from "../src/config.ts"
16
16
  import { loadLastModel, localConfigNotice } from "../src/config.ts"
17
+ import { LIMITS } from "../src/constants.ts"
17
18
  import { runRunHooks, shouldRunHooks } from "../src/hooks/run.ts"
18
19
  import { homeDir } from "../src/lib/db-path.ts"
19
20
  import { closeAllLsp as lspCloseAll, setLspProcessSupervisor } from "../src/lsp/client.ts"
@@ -26,6 +27,8 @@ import {
26
27
  evaluateConsequence,
27
28
  isAceEnabled,
28
29
  } from "../src/policy/consequence-engine.ts"
30
+ import { minicodeEstimator } from "../src/policy/context.ts"
31
+ import { resolveContextWindow } from "../src/policy/context-window.ts"
29
32
  import type { NoProgressDetector } from "../src/policy/no-progress.ts"
30
33
  import type { PermissionAsk } from "../src/policy/permission.ts"
31
34
  import type { RateLimiter } from "../src/policy/ratelimit.ts"
@@ -36,7 +39,6 @@ import {
36
39
  primePricing,
37
40
  type UsageInitialSnapshot,
38
41
  watchBudgetLimit,
39
- watchContextWindowLimit,
40
42
  } from "../src/policy/usage.ts"
41
43
  import {
42
44
  buildBaselineNote,
@@ -224,6 +226,7 @@ import type {
224
226
  UiToolStatus,
225
227
  UiTurnSummary,
226
228
  } from "../src/ui/contract.ts"
229
+ import { sanitizeAnsi } from "../src/ui/render/sanitize.ts"
227
230
  import { c } from "../src/ui/render/theme.ts"
228
231
  // [Area A · PROMPT 06] State UI per-sesi. Satu instance per `createCliSession`.
229
232
  import { UiSessionState } from "../src/ui/session-state.ts"
@@ -298,18 +301,18 @@ export interface CliSessionOptions {
298
301
  /** Harness-P2: scope tool sesi — explore = subset read-only. */
299
302
  toolScope?: "full" | "explore"
300
303
  /**
301
- * P12 S2.2 — WorkMode (lapis intent di ATAS permission mode). Default
302
- * EXECUTE = perilaku lama. DISCUSS = read-only ceiling; PLAN = ceiling
304
+ * WorkMode (lapis intent di atas profil izin). Default DISCUSS = read-only;
305
+ * PLAN = ceiling
303
306
  * rencana (explore + tool rencana). TIDAK pernah memperluas permission mode
304
307
  * (INV-WM1). Diisi CLI dari --work-mode / MINICODE_WORK_MODE; diserahkan ke
305
308
  * setupToolLayer (visibilitas) dan createMinicodeSession (handler ceiling).
306
309
  */
307
310
  workMode?: "DISCUSS" | "PLAN" | "EXECUTE"
308
311
  /**
309
- * P12 S2.2 (D-2) — transparansi resume. Benar bila operator memberi sinyal
310
- * WorkMode eksplisit (--work-mode / MINICODE_WORK_MODE). WorkMode TIDAK
311
- * dipersist antar-sesi; saat resume tanpa sinyal eksplisit, WorkMode kembali
312
- * ke EXECUTE. Bila scope ini `false` DAN identitas sesi `resumed`, composition
312
+ * Transparansi resume. Benar bila operator memberi sinyal WorkMode eksplisit
313
+ * (--work-mode / MINICODE_WORK_MODE). Saat resume tanpa sinyal eksplisit,
314
+ * WorkMode tersimpan dipulihkan; legacy tanpa nilai kembali ke DISCUSS.
315
+ * Bila scope ini `false` DAN identitas sesi `resumed`, composition
313
316
  * root menulis SATU baris stderr human-facing (bukan output machine) agar
314
317
  * transisi tidak terjadi diam-diam.
315
318
  */
@@ -397,7 +400,7 @@ export interface CliSession {
397
400
  effectiveInitialModel: string
398
401
  effectiveTimeoutMs: number
399
402
  permissionMode: string
400
- /** P12 S2.2 — WorkMode efektif sesi ini (default EXECUTE). Dipakai label/
403
+ /** WorkMode efektif sesi ini (default DISCUSS). Dipakai label/
401
404
  * readout TUI; diisi composition root dari flag/env. */
402
405
  workMode: "DISCUSS" | "PLAN" | "EXECUTE"
403
406
  /** P12 S2.2 Slice 5 — handle kontrol WorkMode runtime (transisi operator
@@ -411,6 +414,8 @@ export interface CliSession {
411
414
  budgetStrict?: boolean
412
415
  /** F-CTX-1: jendela konteks yang dipakai footer TUI (window %) — flag --context-window. */
413
416
  contextWindowTokens?: number
417
+ /** Jendela dinamis mengikuti model yang dipilih saat sesi berjalan. */
418
+ getContextWindowTokens?: () => number
414
419
  /** Flag opt-in local config sesi ini — dipakai perintah REPL (/sync,
415
420
  * /provider, /model) agar konsisten dengan provider/tool yang aktif. */
416
421
  allowLocalConfig: boolean
@@ -899,7 +904,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
899
904
  runtimeMode,
900
905
  adoptTask,
901
906
  allowLocalConfig,
902
- workMode = "EXECUTE",
907
+ workMode = "DISCUSS",
903
908
  workModeExplicit = false,
904
909
  maxSteps,
905
910
  contextWindowTokens,
@@ -977,21 +982,21 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
977
982
  )
978
983
  }
979
984
  // P0.2 (Q5): saat `--resume` tanpa sinyal WorkMode eksplisit, pulihkan
980
- // WorkMode tersimpan dari metadata sesi (NULL legacy → default EXECUTE).
985
+ // WorkMode tersimpan dari metadata sesi (NULL legacy → default DISCUSS).
981
986
  //
982
987
  // [mode-architecture] --plan = alias warisan WorkMode PLAN (bukan permission
983
988
  // mode). Dilipat di sini (satu titik untuk semua pemanggil: index/exec/acp).
984
989
  const persistedWorkMode = identity.resumed ? loadSessionWorkMode(sessionId, cwd) : undefined
985
990
  const planAsWorkMode =
986
- plan && !workModeExplicit && workMode === "EXECUTE" ? ("PLAN" as const) : workMode
987
- if (plan && !workModeExplicit && workMode === "EXECUTE") {
991
+ plan && !workModeExplicit && workMode === "DISCUSS" ? ("PLAN" as const) : workMode
992
+ if (plan && !workModeExplicit && workMode === "DISCUSS") {
988
993
  process.stderr.write(
989
994
  `${c.dim("[deprecated] --plan is now WorkMode PLAN; use --work-mode PLAN\n")}`,
990
995
  )
991
996
  }
992
997
  const effectiveWorkMode: "DISCUSS" | "PLAN" | "EXECUTE" =
993
998
  identity.resumed && !workModeExplicit && !plan
994
- ? (persistedWorkMode ?? "EXECUTE")
999
+ ? (persistedWorkMode ?? "DISCUSS")
995
1000
  : planAsWorkMode
996
1001
  // P0.2 (Q4): tolak startup (fail-closed) bila `--verify` digabung dengan
997
1002
  // WorkMode DISCUSS atau PLAN (baik dari flag/env maupun pulihan `--resume`).
@@ -1122,40 +1127,28 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1122
1127
  if (!Number.isFinite(effectiveTimeoutMs) || effectiveTimeoutMs < 0) {
1123
1128
  process.stderr.write(`[warn] invalid timeout ${effectiveTimeoutMs}, fallback to 900000\n`)
1124
1129
  effectiveTimeoutMs = 900_000
1130
+ } else if (effectiveTimeoutMs > LIMITS.MAX_TIMER_DELAY_MS) {
1131
+ process.stderr.write(
1132
+ `[warn] timeout exceeds runtime limit; capped at ${LIMITS.MAX_TIMER_DELAY_MS}ms\n`,
1133
+ )
1134
+ effectiveTimeoutMs = LIMITS.MAX_TIMER_DELAY_MS
1135
+ }
1136
+ // `--timeout` adalah deadline satu pemanggilan prompt. Jangan menyalakan
1137
+ // timer saat sesi dibuat: sesi TUI/REPL bisa idle lama lalu menerima prompt
1138
+ // baru, yang harus mendapat jatah waktu baru.
1139
+ const createRunDeadline = () => {
1140
+ if (effectiveTimeoutMs === 0 || effectiveTimeoutMs === Infinity)
1141
+ return { signal: undefined, cancel: () => {} }
1142
+ const controller = new AbortController()
1143
+ const timer = setTimeout(
1144
+ () =>
1145
+ controller.abort(
1146
+ new AgentError("timeout", `run exceeded wall-clock timeout (${effectiveTimeoutMs}ms)`),
1147
+ ),
1148
+ effectiveTimeoutMs,
1149
+ )
1150
+ return { signal: controller.signal, cancel: () => clearTimeout(timer) }
1125
1151
  }
1126
- // [Fase 7 / Live #3] ROOT wall-clock timeout. Sebelumnya `--timeout` hanya
1127
- // dioper ke kernel turn (session.timeoutMs), sehingga setup/retry di luar
1128
- // turn (DB init, system prompt, provider connect) tidak diikat satu
1129
- // deadline — uji live: `--timeout 30000` selesai di TOTAL_MS=71967 karena
1130
- // ~42 dtk setup berada di luar pagar. Signal root ini dibuat di sini
1131
- // (sebelum setup) dan di-compose ke sinyal turn + diperiksa selama setup,
1132
- // jadi TOTAL_MS benar-benar menghormati batas pengguna.
1133
- // [Fase 10 / QF] `AbortSignal.timeout()` menembak dengan reason DOMException
1134
- // (bukan AgentError). `abortError()` kernel lalu mengklasifikasikannya sebagai
1135
- // "aborted" generik — bukan "timeout" — sehingga `--timeout` yang fire di
1136
- // tengah provider menggantung melaporkan "Run was aborted" alih-alih
1137
- // "Run exceeded timeout". Kita buat controller sendiri supaya reason-nya
1138
- // AgentError("timeout") → kernel mempertahankan identitas timeout.
1139
- const rootTimeoutSignal =
1140
- effectiveTimeoutMs === Infinity || effectiveTimeoutMs === 0
1141
- ? undefined
1142
- : (() => {
1143
- const rc = new AbortController()
1144
- const timer = setTimeout(
1145
- () =>
1146
- rc.abort(
1147
- new AgentError(
1148
- "timeout",
1149
- `run exceeded root wall-clock timeout (${effectiveTimeoutMs}ms)`,
1150
- ),
1151
- ),
1152
- effectiveTimeoutMs,
1153
- )
1154
- try {
1155
- ;(timer as unknown as { unref?: () => void })?.unref?.()
1156
- } catch {}
1157
- return rc.signal
1158
- })()
1159
1152
 
1160
1153
  // [mode-architecture] `--plan` legacy bukan lagi permission mode — pemetaannya
1161
1154
  // ke WorkMode PLAN terjadi di effectiveWorkMode (di atas). Sisa profil warisan
@@ -1218,6 +1211,35 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1218
1211
  modelRef.current = saved
1219
1212
  }
1220
1213
  }
1214
+ const effectiveDefaultModel = () => modelRef.current ?? cfg.providers[0]?.models[0]
1215
+ const warnedContextModels = new Set<string>()
1216
+ const routedContextModel = (model?: string) =>
1217
+ router.contextModelIdentity(model ?? effectiveDefaultModel()) ?? model ?? "default"
1218
+ const contextModelId = (requested?: string): string => {
1219
+ return routedContextModel(requested)
1220
+ }
1221
+ const getContextWindowTokens = (model?: string) => {
1222
+ const resolved = resolveContextWindow(cfg, routedContextModel(model), contextWindowTokens)
1223
+ if (resolved.source === "safe-default") {
1224
+ const key = resolved.providerId
1225
+ ? `${resolved.providerId}::${resolved.model ?? "default"}`
1226
+ : (resolved.model ?? "default")
1227
+ if (!warnedContextModels.has(key)) {
1228
+ warnedContextModels.add(key)
1229
+ process.stderr.write(
1230
+ `${c.yellow(`[context] no configured window for ${sanitizeAnsi(key)}; using fallback ${resolved.tokens} tokens. Set provider.contextWindows or --context-window for the exact limit.\n`)}`,
1231
+ )
1232
+ }
1233
+ }
1234
+ return resolved.tokens
1235
+ }
1236
+ const getReportedContextWindowTokens = (model?: string) => {
1237
+ const resolved = resolveContextWindow(cfg, routedContextModel(model), contextWindowTokens)
1238
+ return resolved.source === "safe-default" ? undefined : resolved.tokens
1239
+ }
1240
+ router.updateContextWindowResolver(getContextWindowTokens)
1241
+ // Emit the fallback warning immediately for the startup-selected model.
1242
+ getContextWindowTokens()
1221
1243
  const {
1222
1244
  systemExtra,
1223
1245
  skills: allLoadedSkills,
@@ -1269,14 +1291,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1269
1291
  if (identity.resumed) {
1270
1292
  // P0.2 (Q5 / Invariant #6) — transparansi resume: WorkMode dipulihkan dari
1271
1293
  // metadata sesi bila operator tidak memberi sinyal eksplisit (NULL legacy
1272
- // kembali ke default EXECUTE). Satu baris stderr human-facing memastikan
1294
+ // kembali ke default DISCUSS). Satu baris stderr human-facing memastikan
1273
1295
  // otoritas sesi hasil resume selalu terlihat eksplisit.
1274
1296
  const resumeNotice = !workModeExplicit
1275
1297
  ? persistedWorkMode !== undefined
1276
- ? `[resume] WorkMode ${effectiveWorkMode} restored from session; pass --work-mode DISCUSS|PLAN|EXECUTE to override\n`
1277
- : `[resume] WorkMode default EXECUTE (legacy session without saved workMode); pass --work-mode DISCUSS|PLAN to change\n`
1298
+ ? `[resume] WorkMode ${effectiveWorkMode === "EXECUTE" ? "BUILD" : effectiveWorkMode} restored from session; pass --work-mode DISCUSS|PLAN|BUILD to override\n`
1299
+ : `[resume] WorkMode default DISCUSS (legacy session without saved workMode); pass --work-mode PLAN|BUILD to change\n`
1278
1300
  : persistedWorkMode !== undefined && persistedWorkMode !== effectiveWorkMode
1279
- ? `[resume] WorkMode ${effectiveWorkMode} (overriding saved ${persistedWorkMode})\n`
1301
+ ? `[resume] WorkMode ${effectiveWorkMode === "EXECUTE" ? "BUILD" : effectiveWorkMode} (overriding saved ${persistedWorkMode === "EXECUTE" ? "BUILD" : persistedWorkMode})\n`
1280
1302
  : ""
1281
1303
  if (resumeNotice) process.stderr.write(resumeNotice)
1282
1304
  // P2.4: aktivasi default Thread SEBELUM seed kernel — backfill aditif
@@ -1333,8 +1355,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1333
1355
  // ContextSelection provenance-bound. P2.8 dipakai sebagai sumber
1334
1356
  // keputusan proyeksi + fallback identik; selector MEMPERLUAS dengan
1335
1357
  // budget-tail + laporan selectionBasis/freshness. Tak ada tulis kanonik.
1336
- // Budget pesan = contextWindowTokens dikurangi overhead system+tools;
1337
- // tanpa konfigurasi → tanpa batas (reproduksi P2.8 persis).
1358
+ // Batasi histori resume ke batas model, tanpa mengarang overhead.
1359
+ // Kernel menghitung system+tools aktual dan memadatkan sebelum request;
1360
+ // selector hanya membuang ke budget-tail bila pesan sendiri tak muat.
1338
1361
  const durableEvents = loadPresentationEvents(sessionId, cwd)
1339
1362
  const revision = countDurableCompactions(durableEvents as readonly { type: string }[])
1340
1363
  const rowsForSelector = loadThreadHistoryWithSeq(sessionId, defaultThread.thread_id, cwd)
@@ -1352,10 +1375,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1352
1375
  (view.source === "projection" && view.summary
1353
1376
  ? { baseSeq: view.coveredSeq, summaryText: view.summary }
1354
1377
  : undefined)
1355
- const messageBudget =
1356
- contextWindowTokens && contextWindowTokens > 0
1357
- ? contextWindowTokens
1358
- : Number.MAX_SAFE_INTEGER
1378
+ const selectedWindow = getContextWindowTokens()
1379
+ const messageBudget = selectedWindow
1359
1380
  // N1: turunkan frontier kanonis dari baris yang BARU DIBACA (sumber
1360
1381
  // kebenaran saat ini) dan teruskan ke selector — freshness dihitung
1361
1382
  // via assessContextFreshness (BUKAN hard-code "fresh"). Selector tetap
@@ -1373,7 +1394,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1373
1394
  rows: selectorRows,
1374
1395
  revision,
1375
1396
  ...(projectionSummary ? { projection: projectionSummary } : {}),
1376
- policy: { budgetTokens: messageBudget },
1397
+ policy: { budgetTokens: messageBudget, estimator: minicodeEstimator },
1377
1398
  canonicalFrontier,
1378
1399
  })
1379
1400
  initialMessages = selection.messages as readonly Message[]
@@ -1766,31 +1787,31 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1766
1787
  } catch {}
1767
1788
  }
1768
1789
  }
1769
- const compaction = process.env.DEEPSEEK_API_KEY
1770
- ? createLlmCompaction({
1771
- apiKey: process.env.DEEPSEEK_API_KEY,
1772
- baseUrl: process.env.DEEPSEEK_BASE_URL ?? "https://api.deepseek.com/v1",
1773
- model: "deepseek-chat",
1774
- cwd: cwd ?? process.cwd(),
1775
- onUsage: (u) => {
1776
- try {
1777
- // Angka sudah dinormalisasi di compactWithLlm (negatif/NaN → skip).
1778
- sessionEvents?.emit({
1779
- type: "provider:extension",
1780
- kind: "usage",
1781
- data: {
1782
- inputTokens: u.inputTokens,
1783
- outputTokens: u.outputTokens,
1784
- totalTokens: u.totalTokens,
1785
- // P1.4: atribusi biaya compaction memakai model yang benar-benar
1786
- // dipakai (deepseek-chat), bukan model utama sesi.
1787
- model: "deepseek-chat",
1788
- },
1789
- })
1790
- } catch {}
1791
- },
1792
- })
1793
- : undefined
1790
+ const compaction = createLlmCompaction({
1791
+ ...(process.env.DEEPSEEK_API_KEY ? { apiKey: process.env.DEEPSEEK_API_KEY } : {}),
1792
+ baseUrl: process.env.DEEPSEEK_BASE_URL ?? "https://api.deepseek.com/v1",
1793
+ model: "deepseek-chat",
1794
+ cwd: cwd ?? process.cwd(),
1795
+ getContextWindowTokens,
1796
+ onUsage: (u) => {
1797
+ try {
1798
+ // Angka sudah dinormalisasi di compactWithLlm (negatif/NaN → skip).
1799
+ sessionEvents?.emit({
1800
+ type: "provider:extension",
1801
+ kind: "usage",
1802
+ data: {
1803
+ inputTokens: u.inputTokens,
1804
+ outputTokens: u.outputTokens,
1805
+ totalTokens: u.totalTokens,
1806
+ source: "compaction",
1807
+ // P1.4: atribusi biaya compaction memakai model yang benar-benar
1808
+ // dipakai (deepseek-chat), bukan model utama sesi.
1809
+ model: "deepseek-chat",
1810
+ },
1811
+ })
1812
+ } catch {}
1813
+ },
1814
+ })
1794
1815
  const {
1795
1816
  sessionTools,
1796
1817
  evidenceMode,
@@ -1833,6 +1854,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1833
1854
  setSubAgentParentRouting({
1834
1855
  ...(rateLimiter ? { rateLimiter } : {}),
1835
1856
  ...(providerOverride ? { defaultProviderId: providerOverride } : {}),
1857
+ contextWindowTokensForModel: getContextWindowTokens,
1836
1858
  })
1837
1859
  // P2.9 — lineage parent Run untuk anak Sub-Agent. Composition root satu-
1838
1860
  //-satunya pemilik Run hidup; tooltak pernah mengarang id ini (vendor
@@ -1880,6 +1902,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1880
1902
  // dikompaksi; tidak pernah masuk histori kanonik. Absen = perilaku lama.
1881
1903
  systemExtra: `${runtimeStateHeader ? `${runtimeStateHeader}\n\n` : ""}${systemExtra ?? ""}${recoveryAppendix}`,
1882
1904
  model: modelRef.current,
1905
+ getContextModel: () => contextModelId(modelRef.current),
1906
+ contextWindowTokens: getContextWindowTokens(),
1907
+ contextWindowTokensForModel: getContextWindowTokens,
1883
1908
  // P13.6 — ask permission: composition root boleh menyuntik jalur headless
1884
1909
  // (daemon → ApprovalBroker). Tanpa injeksi tetap prompt TTY; non-TTY ⇒
1885
1910
  // deny (fail-closed), bukan izin diam-diam.
@@ -1928,7 +1953,6 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1928
1953
  noProgressDetector = detector
1929
1954
  },
1930
1955
  ...(maxSteps ? { maxSteps } : {}),
1931
- ...(contextWindowTokens ? { contextWindowTokens } : {}),
1932
1956
  ...(keepRecentTurns ? { keepRecentTurns } : {}),
1933
1957
  ...(safeConcurrency ? { concurrency: safeConcurrency } : {}),
1934
1958
  ...(safeWriteConcurrency ? { writeConcurrency: safeWriteConcurrency } : {}),
@@ -2195,6 +2219,10 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2195
2219
  ? e.result.usage.turns
2196
2220
  : session.state.turnCount
2197
2221
  const desc = `turn ${turn}`
2222
+ if (pre.mode === "unavailable") {
2223
+ warnLine(`checkpoint unavailable: ${pre.reason}; undo/redo will not cover turn ${turn}`)
2224
+ return
2225
+ }
2198
2226
  if (pre.mode === "git") {
2199
2227
  const after = await snapshotTree(cwd ?? ".", sessionId, `post-${turn}`)
2200
2228
  const checkpoint = await recordCheckpointFromTrees(
@@ -2610,29 +2638,33 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2610
2638
  }
2611
2639
  const previous = activeAgentSessionId
2612
2640
  activeAgentSessionId = sessionId
2641
+ const deadline = createRunDeadline()
2642
+ const runSignal = deadline.signal
2643
+ ? signal
2644
+ ? AbortSignal.any([signal, deadline.signal])
2645
+ : deadline.signal
2646
+ : signal
2613
2647
  try {
2614
- return await runPromptWithVerifyImpl(p, signal)
2648
+ return await runPromptWithVerifyImpl(p, runSignal)
2615
2649
  } finally {
2650
+ deadline.cancel()
2616
2651
  if (activeAgentSessionId === sessionId) activeAgentSessionId = previous ?? null
2617
2652
  }
2618
2653
  }
2619
2654
 
2620
2655
  async function runPromptWithVerifyImpl(p: string, signal?: AbortSignal): Promise<void> {
2621
- // [Fase 7 / Live #3] Root wall-clock: kalau timeout CLI sudah lewat saat
2622
- // turn mau mulai (setup/retry memakan seluruh budget), tolak langsung
2623
- // dengan alasan jelas — jangan biarkan turn baru melebihi deadline total.
2624
- if (rootTimeoutSignal?.aborted) {
2625
- const msg = `run exceeded root wall-clock timeout (${effectiveTimeoutMs}ms) before turn start`
2626
- process.stderr.write(`[timeout] ${msg}\n`)
2627
- throw new AgentError("timeout", msg)
2656
+ if (signal?.aborted) {
2657
+ const reason = signal.reason
2658
+ if ((reason as { kind?: unknown } | undefined)?.kind === "timeout") {
2659
+ const message = reason instanceof Error ? reason.message : "run exceeded wall-clock timeout"
2660
+ process.stderr.write(`[timeout] ${message}\n`)
2661
+ throw reason
2662
+ }
2663
+ throw new AgentError("aborted", "turn aborted", { cause: reason })
2628
2664
  }
2629
- // Composit root signal ke sinyal turn: deadline pengguna berlaku untuk
2630
- // SELURUH fase (setup + turn + retry), bukan hanya kernel turn.
2631
- const composedSignal = rootTimeoutSignal
2632
- ? signal
2633
- ? AbortSignal.any([signal, rootTimeoutSignal])
2634
- : rootTimeoutSignal
2635
- : signal
2665
+ // Sinyal per-prompt berlaku pada persiapan turn, provider retry, tool, dan
2666
+ // verify. Kernel memiliki timeout lapis kedua khusus eksekusi model.
2667
+ const composedSignal = signal
2636
2668
  // P2.2: pagar pra-turn (lihat ensureWriterFresh). Basi → turn dilewati
2637
2669
  // sebelum provider dibelanjakan; histori tak tersentuh.
2638
2670
  if (!ensureWriterFresh()) return
@@ -2724,7 +2756,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2724
2756
  // Occupancy konteks (bukan spend sesi) — budget cutoff adalah
2725
2757
  // peristiwa berbeda; field tetap konsisten dengan meter context.
2726
2758
  usedTokens: session.contextTokens,
2727
- windowTokens: contextWindowTokens ?? 0,
2759
+ windowTokens: getContextWindowTokens(),
2728
2760
  turnId: session.state.turnCount,
2729
2761
  })
2730
2762
  process.stderr.write(
@@ -2744,49 +2776,27 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2744
2776
  )
2745
2777
  },
2746
2778
  })
2747
- // [Fase 7 / Live #2] Pemutus aliran MID-STREAM untuk `--context-window`.
2748
- // Kernel hanya mengecek estimasi token pesan SEBELUM request (kompaksi);
2749
- // model yang menghasilkan respons sangat panjang bisa membakar jutaan
2750
- // token tanpa henti (uji live: --context-window 2000 → tokens=6.830.639).
2751
- // Watcher ini membaca token OUTPUT turn berjalan dari usage collector
2752
- // dan menggugurkan turn begitu melewati allowance output
2753
- // (max(256, W − estimasiInput)) — murah karena dijalankan per-event usage.
2754
- const stopCtxWindow = watchContextWindowLimit({
2755
- bus: session.events,
2756
- windowTokens: contextWindowTokens ?? 0,
2757
- getInputTokens: () => usage.get().inputTokens,
2758
- getOutputTokens: () => usage.get().outputTokens,
2759
- onOver: (allowed, actual) => {
2760
- const windowTokens = contextWindowTokens ?? 0
2761
- // F-CTX-1 + P1.4: meter occupancy konteks (bukan output cutoff).
2762
- // `actual` adalah token output yang memicu cutoff; occupancy adalah
2763
- // ukuran konteks saat ini dari kernel. Dua angka ini tidak boleh
2764
- // saling menggantikan.
2765
- const occupancy = session.contextTokens
2766
- presentation?.noteContextWindow({
2767
- usedTokens: occupancy,
2768
- windowTokens,
2769
- percent: windowTokens > 0 ? Math.min(100, (occupancy / windowTokens) * 100) : undefined,
2770
- costUsd: usage.getSession().cost,
2771
- turnId: session.state.turnCount,
2772
- })
2773
- // F-CTX-2: pemotongan mi-stream yang durable → masuk transkrip.
2774
- presentation?.noteContextCutoff({
2775
- reason: `context window exceeded: output ${actual} > allowance ${allowed} (window ${windowTokens})`,
2776
- usedTokens: actual,
2777
- windowTokens,
2778
- turnId: session.state.turnCount,
2779
- })
2780
- process.stderr.write(
2781
- `[context] stream truncated: context-window limit reached (output ${actual} > allowance ${allowed} of window ${contextWindowTokens})\n`,
2782
- )
2783
- ctl.abort(
2784
- new AgentError(
2785
- "budget_exceeded",
2786
- `context window exceeded: output ${actual} > allowance ${allowed} (window ${contextWindowTokens})`,
2787
- ),
2788
- )
2789
- },
2779
+ const stopContextGuard = session.events.on("provider:extension", (event) => {
2780
+ if (event.kind !== "context-window-limit") return
2781
+ const data = event.data as
2782
+ | { inputTokens?: unknown; outputTokens?: unknown; windowTokens?: unknown }
2783
+ | undefined
2784
+ const input = typeof data?.inputTokens === "number" ? data.inputTokens : 0
2785
+ const output = typeof data?.outputTokens === "number" ? data.outputTokens : 0
2786
+ const windowTokens =
2787
+ typeof data?.windowTokens === "number" && data.windowTokens > 0
2788
+ ? data.windowTokens
2789
+ : getContextWindowTokens()
2790
+ const usedTokens = input + output
2791
+ presentation?.noteContextCutoff({
2792
+ reason: `context guard stopped request: input ${input} + output ${output} (window ${windowTokens})`,
2793
+ usedTokens,
2794
+ windowTokens,
2795
+ turnId: session.state.turnCount,
2796
+ })
2797
+ process.stderr.write(
2798
+ `[context] request stopped at context budget: input ${input} + output ${output} (window ${windowTokens}).\n`,
2799
+ )
2790
2800
  })
2791
2801
  try {
2792
2802
  try {
@@ -2823,7 +2833,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2823
2833
  }
2824
2834
  } finally {
2825
2835
  stopWatch()
2826
- stopCtxWindow()
2836
+ stopContextGuard()
2827
2837
  if (s) s.removeEventListener("abort", onParentAbort)
2828
2838
  turnStatus?.endTurn()
2829
2839
  }
@@ -3099,7 +3109,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3099
3109
  )
3100
3110
  return
3101
3111
  }
3102
- // Perilaku lama dipertahankan untuk error non-pagar: persist best-effort.
3112
+ // Histori adalah bukti durable untuk turn ini. Error selain epoch harus
3113
+ // naik ke pemanggil agar one-shot tidak mengaku berhasil saat pesan hilang.
3114
+ throw e
3103
3115
  }
3104
3116
  }
3105
3117
 
@@ -3232,11 +3244,25 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3232
3244
  // uses — so autonomous work does not run a different model or a weaker
3233
3245
  // tool stack than the interactive session.
3234
3246
  sessionFactory: async (spec: AutonomousSessionSpec) => {
3247
+ const childProvider = spec.provider as {
3248
+ contextWindowTokensForModel?: (model?: string) => number
3249
+ contextModelIdentity?: (model?: string) => string | undefined
3250
+ }
3251
+ const contextWindowTokensForModel = childProvider.contextWindowTokensForModel
3235
3252
  const child = await createMinicodeSession({
3236
3253
  provider: spec.provider as never,
3237
3254
  tools: spec.tools as never,
3238
3255
  cwd: spec.cwd,
3239
3256
  systemExtra: spec.systemExtra,
3257
+ model: spec.model,
3258
+ ...(contextWindowTokensForModel
3259
+ ? {
3260
+ contextWindowTokens: contextWindowTokensForModel(spec.model),
3261
+ contextWindowTokensForModel,
3262
+ getContextModel: () =>
3263
+ childProvider.contextModelIdentity?.(spec.model) ?? spec.model,
3264
+ }
3265
+ : {}),
3240
3266
  // [PHASE 6U] The child conversation id is NOT a kernel config field.
3241
3267
  timeoutMs: spec.timeoutMs,
3242
3268
  // [PHASE 6U][SECURITY] The 6S handler, not a `readonly` MODE. This
@@ -3553,7 +3579,10 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3553
3579
  usage,
3554
3580
  budget,
3555
3581
  budgetStrict,
3556
- contextWindowTokens,
3582
+ get contextWindowTokens() {
3583
+ return getReportedContextWindowTokens()
3584
+ },
3585
+ getContextWindowTokens: () => getContextWindowTokens(),
3557
3586
  memoryHits,
3558
3587
  detachSimple: () => detachUI(),
3559
3588
  // [Area A · PROMPT 06] State UI sesi ini (lihat interface CliSession).