minicode-ai 0.23.0 → 0.26.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 (104) hide show
  1. package/README.md +5 -3
  2. package/cli/commands/config.ts +123 -0
  3. package/cli/setup.ts +107 -8
  4. package/cli/tui.ts +28 -2
  5. package/docs/README.md +2 -2
  6. package/docs/SUMMARY.md +10 -19
  7. package/docs/TERMINAL_CONTRACT.md +113 -28
  8. package/docs/architecture.md +1 -1
  9. package/docs/autonomous-scheduler.md +283 -2
  10. package/docs/choosing-mode.md +4 -4
  11. package/docs/concepts.md +39 -3
  12. package/docs/config.md +103 -5
  13. package/docs/environment.md +4 -0
  14. package/docs/getting-started.md +69 -5
  15. package/docs/repl.md +1 -1
  16. package/docs/security.md +49 -2
  17. package/docs/tools.md +2 -1
  18. package/package.json +2 -36
  19. package/src/app/provider-layer.ts +1 -1
  20. package/src/app/session.ts +187 -17
  21. package/src/config.ts +21 -8
  22. package/src/constants.ts +17 -1
  23. package/src/lib/net.ts +6 -15
  24. package/src/lib/public-http.ts +128 -0
  25. package/src/lib/safe-open.ts +21 -12
  26. package/src/memory/vector.ts +0 -31
  27. package/src/policy/auto-resume.ts +63 -0
  28. package/src/policy/compaction.ts +354 -70
  29. package/src/policy/context-budget.ts +4 -6
  30. package/src/policy/context-window-assign.ts +114 -0
  31. package/src/policy/context-window-catalog.ts +4 -1
  32. package/src/policy/context-window-presets.ts +165 -0
  33. package/src/policy/context-window.ts +19 -37
  34. package/src/policy/context.ts +11 -9
  35. package/src/policy/executor.ts +69 -27
  36. package/src/policy/microcompact.ts +76 -15
  37. package/src/policy/no-progress.ts +1 -1
  38. package/src/policy/permission.ts +5 -0
  39. package/src/policy/recovery-budget.ts +281 -0
  40. package/src/policy/scrub.ts +15 -2
  41. package/src/policy/step-escalation.ts +82 -0
  42. package/src/policy/tokenizer-registry.ts +1 -0
  43. package/src/policy/tool-contract.ts +11 -9
  44. package/src/presentation/reducer.ts +1 -0
  45. package/src/providers/anthropic.ts +3 -3
  46. package/src/providers/detect.ts +40 -7
  47. package/src/providers/provision.ts +23 -1
  48. package/src/runtime/child-execution.ts +4 -2
  49. package/src/runtime/execution-backend.ts +3 -0
  50. package/src/sandbox/os.ts +53 -9
  51. package/src/session/context-assembly.ts +11 -7
  52. package/src/session/persistence.ts +19 -3
  53. package/src/task/autonomous-policy.ts +7 -0
  54. package/src/task/graph-validate.ts +1 -1
  55. package/src/task/session-authority.ts +0 -5
  56. package/src/task/store.ts +0 -4
  57. package/src/tools/ask_user.ts +14 -1
  58. package/src/tools/bash.ts +68 -17
  59. package/src/tools/code_run.ts +19 -20
  60. package/src/tools/context.ts +10 -0
  61. package/src/tools/delete_file.ts +3 -2
  62. package/src/tools/edit.ts +5 -4
  63. package/src/tools/git.ts +70 -12
  64. package/src/tools/glob.ts +13 -5
  65. package/src/tools/grep.ts +26 -10
  66. package/src/tools/index.ts +3 -2
  67. package/src/tools/lsp.ts +15 -9
  68. package/src/tools/move_file.ts +4 -3
  69. package/src/tools/patch.ts +5 -4
  70. package/src/tools/read_file.ts +3 -2
  71. package/src/tools/read_image.ts +3 -2
  72. package/src/tools/task.ts +5 -1
  73. package/src/tools/todo.ts +4 -8
  74. package/src/tools/web_fetch.ts +13 -19
  75. package/src/tools/write_file.ts +4 -3
  76. package/src/ui/approval/prompt.ts +226 -77
  77. package/src/ui/assistant/simple.ts +61 -10
  78. package/src/ui/footer.ts +41 -29
  79. package/src/ui/i18n/en.ts +7 -0
  80. package/src/ui/i18n/id.ts +7 -0
  81. package/src/ui/input/prompt-engine.ts +53 -21
  82. package/src/ui/render/activity-group.ts +9 -0
  83. package/src/ui/render/activity-panel.ts +20 -2
  84. package/src/ui/render/ledger.ts +1 -9
  85. package/src/ui/render/logo.ts +0 -5
  86. package/src/ui/render/markdown-table.ts +0 -3
  87. package/src/ui/render/table-grid.ts +0 -3
  88. package/src/ui/render/theme.ts +31 -5
  89. package/src/ui/runtime/screen.ts +7 -1
  90. package/src/ui/screens/dialog.ts +45 -81
  91. package/src/ui/screens/form.ts +10 -10
  92. package/src/ui/screens/model-manager.ts +7 -10
  93. package/src/ui/screens/picker.ts +8 -11
  94. package/src/ui/screens/provider-manager.ts +9 -13
  95. package/src/ui/tui/app.ts +118 -20
  96. package/src/ui/tui/transcript.ts +179 -29
  97. package/vendor/minicore/src/core/loop.ts +20 -1
  98. package/vendor/minicore/src/core/session.ts +6 -0
  99. package/docs/P14_OPEN_WORK.md +0 -290
  100. package/docs/config-providers.md +0 -87
  101. package/docs/glossary.md +0 -39
  102. package/docs/quickstart.md +0 -60
  103. package/docs/security-model.md +0 -96
  104. package/docs/terminal.md +0 -91
@@ -42,6 +42,12 @@ import {
42
42
  type PermissionAsk,
43
43
  type PermissionMode,
44
44
  } from "../policy/permission.ts"
45
+ import {
46
+ planRecovery,
47
+ RECOVERY_ATTEMPT_QUOTA,
48
+ RECOVERY_BUDGET_MS,
49
+ } from "../policy/recovery-budget.ts"
50
+ import { DEFAULT_SESSION_MAX_STEPS, nextStepLimit } from "../policy/step-escalation.ts"
45
51
  import { getCachedTokenizer, loadTokenizer } from "../policy/tokenizer-registry.ts"
46
52
  import { contractForTool } from "../policy/tool-contract.ts"
47
53
  import { maxTurnsExceededError } from "../policy/usage.ts"
@@ -66,14 +72,119 @@ export const aggressiveBudgetPolicy: BudgetPolicy = {
66
72
  }
67
73
 
68
74
  // P2 cap wrapper: limit retryAfter to 30s without mutating original error.
69
- // F-12: sanitasi PENUH di satu titik sentral (mencakup adapter vendor yang
70
- // tak boleh disentuh): non-finite (Infinity/NaN) atau negatif → buang
71
- // (pakai backoff kernel); sangat besar → cap. Tanpa ini retryAfter=Infinity
72
- // menjadi setTimeout(Infinity) ≈ 1ms → hot fast-retry, bukan tunggu lama.
73
- // Diekspor agar teruji langsung (pola repo: pure/diekspor-untuk-test).
75
+ //
76
+ // [T-009 OBSERVATION.md] Anggaran pemulihan TIDAK lagi dinyatakan sebagai "berapa
77
+ // kali retry" di sini. Versi pertama perbaikan memakai angka lokal
78
+ // (5 percobaan) sementara resume turn punya angka lokal lain; karena keduanya
79
+ // berada di lapisan berbeda, biayanya BERKALI — provider yang mati permanen
80
+ // menahan user ~82 detik, padahal sebelumnya 7 detik. Sekarang retry provider
81
+ // memakai SATU anggaran bersama dari `src/policy/recovery-budget.ts`: satu
82
+ // anggaran waktu, satu kuota percobaan, jitter, dan `Retry-After` sebagai floor.
83
+ // Konsekuensinya biaya total konstan, berapa pun lapisan yang mencoba.
84
+ //
85
+ // `onError` di bawah tetap sinkron karena kontrak `RecoveryPolicy` kernel
86
+ // memintanya begitu. Status anggaran hidup di `RecoveryLedger` per panggilan
87
+ // logis yang dibuat pemanggil (lihat `createRecoveryLedger`).
88
+
89
+ /** Anggaran untuk 429: tetap 3 percobaan seperti kernel, TIDAK diperpanjang.
90
+ *
91
+ * KENAPA (riset 2026): 429 hampir selalu membawa `Retry-After`, dan `planRecovery`
92
+ * memperlakukannya sebagai floor. Backoff panjang justru salah — menunggu lebih
93
+ * lama daripada yang diminta hanya menambah jeda, sedangkan 429 permanen
94
+ * (spend cap Anthropic tanpa header, `credit_balance_exhausted` OpenAI) tidak
95
+ * pulih sama sekali. Kuota 3 membuat kegagalan itu cepat terlihat.
96
+ */
97
+ export const RATE_LIMIT_RETRY_ATTEMPTS = 3
98
+
99
+ /** Buku besar anggaran pemulihan untuk satu panggilan logis.
100
+ *
101
+ * Dipisah dari `cappedRecovery` karena kernel memanggil `onError` secara sinkron
102
+ * dengan `attempt` saja, sementara anggaran butuh JAM. Ledger memegang jam itu.
103
+ * Satu ledger = satu prompt user; retry provider dan resume turn memakai ledger
104
+ * yang sama supaya tidak ada perkalian biaya.
105
+ */
106
+ export interface RecoveryLedger {
107
+ /** Waktu mulai (epoch ms). */
108
+ readonly startedAtMs: number
109
+ /** Percobaan yang sudah dipakai (retry provider + resume turn). */
110
+ attemptsUsed(): number
111
+ /** Catat satu percobaan terpakai. */
112
+ consume(): void
113
+ /** Jeda berikutnya menurut anggaran bersama, atau null bila harus berhenti. */
114
+ nextDelay(failure: { category?: string; kind?: string; retryAfterMs?: number }): {
115
+ delayMs: number
116
+ attempt: number
117
+ } | null
118
+ /** Sisa anggaran waktu (ms) pada saat dipanggil. */
119
+ remainingMs(): number
120
+ }
121
+
122
+ /** Buat ledger baru untuk satu panggilan logis. `now` di-inject untuk uji. */
123
+ export function createRecoveryLedger(now: () => number = Date.now): RecoveryLedger {
124
+ const startedAtMs = now()
125
+ let used = 0
126
+ return {
127
+ startedAtMs,
128
+ attemptsUsed: () => used,
129
+ consume: () => {
130
+ used += 1
131
+ },
132
+ nextDelay(failure) {
133
+ const decision = planRecovery(
134
+ {
135
+ ...(failure.category !== undefined ? { category: failure.category } : {}),
136
+ ...(failure.kind !== undefined ? { kind: failure.kind } : {}),
137
+ ...(failure.retryAfterMs !== undefined ? { retryAfterMs: failure.retryAfterMs } : {}),
138
+ },
139
+ { startedAtMs, nowMs: now(), attemptsUsed: used },
140
+ { hasPrompt: true },
141
+ )
142
+ if (decision.action === "stop") return null
143
+ used = decision.attempt
144
+ return { delayMs: decision.delayMs, attempt: decision.attempt }
145
+ },
146
+ remainingMs: () => RECOVERY_BUDGET_MS - (now() - startedAtMs),
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Sanitasi `retryAfter` + keputusan retry untuk kegagalan provider.
152
+ *
153
+ * F-12 (dipertahankan): nilai non-finite (Infinity/NaN) atau negatif dibuang
154
+ * karena `setTimeout(Infinity)` berperilaku seperti ~1 ms → hot fast-retry, bukan
155
+ * tunggu lama; nilai sangat besar di-cap ke `LIMITS.RETRY_AFTER_MAX_MS`.
156
+ *
157
+ * Diekspor agar teruji langsung (pola repo: pure/diekspor-untuk-test).
158
+ */
74
159
  export const cappedRecovery = {
75
160
  onError(error: ProviderError, attempt: number): RecoveryAction {
161
+ const category = error.category
76
162
  const ra = error.retryAfterMs
163
+ const saneRetryAfter =
164
+ ra != null && Number.isFinite(ra) && ra >= 0
165
+ ? Math.min(ra, LIMITS.RETRY_AFTER_MAX_MS)
166
+ : undefined
167
+
168
+ // 429 punya plafon percobaan sendiri yang lebih ketat (lihat
169
+ // RATE_LIMIT_RETRY_ATTEMPTS). Selain itu keputusan jeda diserahkan ke
170
+ // anggaran bersama supaya retry dan resume tidak mengalikan biaya.
171
+ const cap = category === "rate_limit" ? RATE_LIMIT_RETRY_ATTEMPTS : RECOVERY_ATTEMPT_QUOTA
172
+ if (attempt > cap) return { type: "throw" }
173
+
174
+ const decision = planRecovery(
175
+ {
176
+ category,
177
+ ...(saneRetryAfter !== undefined ? { retryAfterMs: saneRetryAfter } : {}),
178
+ },
179
+ // Sinkron tanpa jam: pakai awal waktu nol. Pagar waktu sesungguhnya
180
+ // dipegang ledger di atas; di sini kuota + kategori yang menahan.
181
+ { startedAtMs: 0, nowMs: 0, attemptsUsed: attempt - 1 },
182
+ { hasPrompt: true },
183
+ )
184
+ if (decision.action === "retry") return { type: "retry", delayMs: decision.delayMs }
185
+
186
+ // Bukan urusan anggaran bersama → serahkan ke kebijakan kernel (mis.
187
+ // compaction untuk context_length_exceeded, langsung throw untuk auth).
77
188
  if (ra != null && (!Number.isFinite(ra) || ra < 0)) {
78
189
  const clean = new ProviderError(error.category, error.message, undefined)
79
190
  Object.assign(clean, { cause: (error as unknown as { cause?: unknown }).cause })
@@ -81,7 +192,6 @@ export const cappedRecovery = {
81
192
  }
82
193
  if (ra != null && ra > LIMITS.RETRY_AFTER_MAX_MS) {
83
194
  const capped = new ProviderError(error.category, error.message, LIMITS.RETRY_AFTER_MAX_MS)
84
- // preserve extra fields if any
85
195
  Object.assign(capped, { cause: (error as unknown as { cause?: unknown }).cause })
86
196
  return defaultRecoveryPolicy.onError(capped, attempt)
87
197
  }
@@ -206,6 +316,17 @@ export async function createMinicodeSession(
206
316
  toTokens: number
207
317
  observedTokens: number
208
318
  }) => void
319
+ /**
320
+ * [T-008 OBSERVATION.md] Dipanggil ketika batas langkah per turn naik satu
321
+ * tangga setelah `max_steps_exceeded`. Composition root memakainya untuk
322
+ * memberi tahu user (footer/log). Tidak pernah dipanggil untuk abort,
323
+ * timeout, atau error provider non-langkah.
324
+ */
325
+ onMaxStepsEscalated?: (info: {
326
+ fromSteps: number
327
+ toSteps: number
328
+ observedSteps: number
329
+ }) => void
209
330
  /**
210
331
  * [Area B · PROMPT 06] Penyimpanan binding persetujuan milik SESI.
211
332
  *
@@ -416,16 +537,14 @@ export async function createMinicodeSession(
416
537
  // 3. `beforeToolEffect` writes intent jurnal secara awaited.
417
538
  //
418
539
  // [Area B · PROMPT 06] Barrier ini juga BATAS EKSEKUSI verifikasi
419
- // persetujuan: setelah awaital intent jurnal + no-progress di atas, yang
420
- // tersisa ke `tool.execute` hanya kode sinkron kernel
421
- // (`permissions.check` → `validateArgs` → emit → execute), jadi verifikasi
422
- // di sini efektif sama dengan memeriksa tepat sebelum eksekusi. Membungkus
423
- // tool TIDAK dipakai: itu mengganti objek di array tool LIVE yang dipegang
424
- // kernel/`setWorkMode` (regresi `test/work-mode-runtime.test.ts`).
540
+ // persetujuan setelah await intent jurnal + no-progress. Executor memeriksa
541
+ // versi otorisasi lagi tepat sebelum tool.execute, setelah listener started.
542
+ // Wrapper per-call tidak mengubah array tool LIVE milik kernel/setWorkMode.
425
543
  //
426
544
  // Alasan deny "approval stale" dicatat terpisah karena handler base
427
545
  // menyimpan alasannya di peta privat; kernel membacanya lewat
428
546
  // `describeDenial` yang kita override.
547
+ let authorizationVersion = 0
429
548
  const staleDenyReasons = new Map<string, string>()
430
549
  // Barrier selalu dipasang (bukan hanya bila detector/journal ada): di sini
431
550
  // verifikasi persetujuan terjadi, dan ia harus berlaku di SETIAP konfigurasi
@@ -433,6 +552,7 @@ export async function createMinicodeSession(
433
552
  const withEffectBarrier: PermissionHandler = {
434
553
  ...permissions,
435
554
  check: async (call, deps) => {
555
+ const authorizedVersion = authorizationVersion
436
556
  const decision = await permissions.check(call, deps)
437
557
  // Kernel vendored saat ini hanya memblokir literal "deny". Validasi di
438
558
  // composition root ini menjaga production dispatch fail-closed tanpa
@@ -452,12 +572,17 @@ export async function createMinicodeSession(
452
572
  // Verifikasi lapis-2 (batas eksekusi): fail-closed saat target berubah
453
573
  // sejak user menyetujui.
454
574
  const verdict = verifyApprovalBinding(binding)
455
- if (verdict.kind === "stale") {
575
+ if (authorizedVersion !== authorizationVersion || verdict.kind === "stale") {
456
576
  const id = (call as { id?: string } | null)?.id
457
577
  if (id) {
458
578
  if (staleDenyReasons.size > 500)
459
579
  staleDenyReasons.delete(staleDenyReasons.keys().next().value as string)
460
- staleDenyReasons.set(id, `approval stale: ${verdict.reason}`)
580
+ staleDenyReasons.set(
581
+ id,
582
+ authorizedVersion !== authorizationVersion
583
+ ? "authorization changed while preparing tool execution; request fresh approval"
584
+ : `approval stale: ${verdict.kind === "stale" ? verdict.reason : "changed"}`,
585
+ )
461
586
  }
462
587
  return "deny"
463
588
  }
@@ -485,7 +610,10 @@ export async function createMinicodeSession(
485
610
  // (ToolContext's label); the DECISION is the handler's.
486
611
  if (onPermissions && !injected) {
487
612
  onPermissions({
488
- setMode: (m) => withMode.__setMode(m),
613
+ setMode: (m) => {
614
+ if (withMode.__getMode() !== m) authorizationVersion++
615
+ withMode.__setMode(m)
616
+ },
489
617
  getMode: () => withMode.__getMode(),
490
618
  // restrictBash adalah opsi tetap (bukan state handler) — dibaca langsung
491
619
  // dari closure, bukan lewat wrapper WorkMode yang tak meneruskannya.
@@ -501,7 +629,10 @@ export async function createMinicodeSession(
501
629
  __getWorkMode(): WorkMode
502
630
  }
503
631
  onWorkMode({
504
- setWorkMode: (m) => wm.__setWorkMode(m),
632
+ setWorkMode: (m) => {
633
+ if (wm.__getWorkMode() !== m) authorizationVersion++
634
+ wm.__setWorkMode(m)
635
+ },
505
636
  getWorkMode: () => wm.__getWorkMode(),
506
637
  })
507
638
  }
@@ -512,7 +643,9 @@ export async function createMinicodeSession(
512
643
  const pm = injected ? opts.permissionMode : withMode.__getMode()
513
644
  const wm = injected ? resolvedWorkMode : (wmCtl.__getWorkMode?.() ?? resolvedWorkMode)
514
645
  const planHint = pm === "plan" ? PLAN_PM_HINT : ""
515
- return baseSystem + planHint + workModeHint(wm)
646
+ const contextWindow = contextWindowForModel(currentContextModel())
647
+ const capacityHint = `\n\n# Harness context capacity\nThe harness currently budgets ${contextWindow} tokens for the selected model. This is the configured/resolved session limit, not a guarantee from the provider. It is independent of the Windows operating system and shell. System instructions, tool schemas, history, and output share this budget; compaction starts before the full window is exhausted. Preserve durable task progress before compaction.`
648
+ return baseSystem + planHint + workModeHint(wm) + capacityHint
516
649
  }
517
650
  // [CTX] Kalibrasi dipisahkan per identitas model agar berpindah ke model
518
651
  // lain tidak membawa rasio tokenizer/provider dari sesi sebelumnya.
@@ -636,6 +769,28 @@ export async function createMinicodeSession(
636
769
  } catch {}
637
770
  }
638
771
 
772
+ // ── Eskalasi adaptif batas langkah (T-008 OBSERVATION.md) ──────────────
773
+ // Batas langkah adalah backstop, bukan anggaran kerja. Turn yang mentok
774
+ // karena batas tidak boleh membuang kerja yang sudah dilakukan: naik satu
775
+ // tangga untuk turn berikutnya, bounded oleh STEP_LIMIT_CEILING. Berlaku
776
+ // hanya untuk sesi ini (bukan menulis config: itu niat operator).
777
+ //
778
+ // KENAPA dipicu HANYA oleh `max_steps_exceeded`: error lain (abort, timeout,
779
+ // provider, budget konteks) tidak akan tertolong oleh langkah tambahan.
780
+ let effectiveMaxSteps =
781
+ typeof rest.maxSteps === "number" && Number.isFinite(rest.maxSteps) && rest.maxSteps >= 1
782
+ ? Math.floor(rest.maxSteps)
783
+ : DEFAULT_SESSION_MAX_STEPS
784
+ const escalateMaxSteps = (observedSteps: number) => {
785
+ const next = nextStepLimit(effectiveMaxSteps, observedSteps)
786
+ if (next === undefined) return
787
+ const from = effectiveMaxSteps
788
+ effectiveMaxSteps = next
789
+ try {
790
+ rest.onMaxStepsEscalated?.({ fromSteps: from, toSteps: next, observedSteps })
791
+ } catch {}
792
+ }
793
+
639
794
  const dynamicProvider: ModelProvider = {
640
795
  id: provider.id,
641
796
  get models() {
@@ -825,6 +980,11 @@ export async function createMinicodeSession(
825
980
  contextWindowTokens: contextWindowForModel(currentContextModel()),
826
981
  contextWindowTokensForModel: contextWindowForModel,
827
982
  maxOutputTokensForModel: maxOutputTokensForModel,
983
+ // [T-008] Batas langkah adaptif: nilai eksplisit operator (bila ada) tetap
984
+ // titik awal, lalu naik satu tangga per `max_steps_exceeded`. Kernel membaca
985
+ // ini sekali per turn lewat seam aditif `maxStepsForRun`.
986
+ maxSteps: effectiveMaxSteps,
987
+ maxStepsForRun: () => effectiveMaxSteps,
828
988
  // Kompaksi lebih agresif (host-side): ringkas mulai 65% jendela, bukan 75%.
829
989
  budget: aggressiveBudgetPolicy,
830
990
  provider: dynamicProvider,
@@ -835,6 +995,7 @@ export async function createMinicodeSession(
835
995
  estimator: calibratedEstimator,
836
996
  recovery: cappedRecovery,
837
997
  executor: parallelExecutor({
998
+ getAuthorizationVersion: () => authorizationVersion,
838
999
  concurrency: safeConcurrency ?? LIMITS.EXECUTOR_CONCURRENCY,
839
1000
  writeConcurrency: safeWriteConcurrency ?? LIMITS.EXECUTOR_WRITE_CONCURRENCY,
840
1001
  }),
@@ -973,6 +1134,7 @@ export async function createMinicodeSession(
973
1134
  //
974
1135
  // Bukan pemicu: `max_steps_exceeded`, `max_turns`, `aborted`, timeout,
975
1136
  // dan error provider non-konteks — menaikkan jendela tak akan menolong.
1137
+ // (`max_steps_exceeded` punya jalurnya sendiri: eskalasi batas langkah.)
976
1138
  if (error instanceof AgentError && error.kind === "budget_exceeded") {
977
1139
  const reason = error.details?.reason
978
1140
  if (reason === "fixpoint" || reason === "critical") {
@@ -981,6 +1143,14 @@ export async function createMinicodeSession(
981
1143
  escalateContextWindow(modelForRun, used)
982
1144
  }
983
1145
  }
1146
+ // [T-008] Turn mentok batas langkah: naik satu tangga untuk turn
1147
+ // berikutnya. Kerja turn ini tetap hilang (kernel sudah berhenti), tapi
1148
+ // turn lanjutan tidak akan menabrak dinding yang sama. Bounded: satu
1149
+ // langkah per kejadian, dibatasi STEP_LIMIT_CEILING.
1150
+ if (error instanceof AgentError && error.kind === "max_steps_exceeded") {
1151
+ const used = typeof error.details?.steps === "number" ? error.details.steps : 0
1152
+ escalateMaxSteps(used)
1153
+ }
984
1154
  throw error
985
1155
  })
986
1156
  },
package/src/config.ts CHANGED
@@ -3,6 +3,10 @@ import { mkdir, readFile } from "node:fs/promises"
3
3
  import { join, resolve } from "node:path"
4
4
  import { atomicWriteText } from "./lib/atomic-write.ts"
5
5
  import { homeDir } from "./lib/db-path.ts"
6
+ import {
7
+ isValidContextWindowValue,
8
+ parseContextWindowInput,
9
+ } from "./policy/context-window-presets.ts"
6
10
 
7
11
  // In-process lock per path untuk mencegah lost-update saat Pool(3) sub-agent
8
12
  // menulis config yang sama secara paralel. Untuk lintas proses, atomicWriteText
@@ -67,6 +71,8 @@ export interface ProviderEntry {
67
71
  maxOutputTokens?: Record<string, number>
68
72
  /** Alias lama/global untuk batas output berlaku ke semua model provider. */
69
73
  maxOutputTokensDefault?: number
74
+ /** Cache dari metadata endpoint (Fase 7.1); `undefined` = default aktif. */
75
+ enablePromptCaching?: boolean
70
76
  providerHint?: string
71
77
  /** Knob generik reasoning effort — dipetakan per-wire (openai reasoning_effort, anthropic thinking, gemini). */
72
78
  reasoningEffort?: "low" | "medium" | "high"
@@ -214,14 +220,21 @@ export function normalizeConfig(raw: unknown): MinicodeConfig {
214
220
  const validContextWindows: Record<string, number> = {}
215
221
  if (source && typeof source === "object" && !Array.isArray(source)) {
216
222
  for (const [model, tokens] of Object.entries(source as Record<string, unknown>)) {
217
- if (
218
- (model === "*" || model.length > 0) &&
219
- typeof tokens === "number" &&
220
- Number.isSafeInteger(tokens) &&
221
- tokens > 0 &&
222
- tokens <= 20_000_000
223
- ) {
224
- validContextWindows[model] = tokens
223
+ if (model !== "*" && model.length === 0) continue
224
+ // Nilai boleh ANGKA atau STRING preset (`"128k"`, `"1M"`,
225
+ // `"1024x1024"`). String diterima karena itulah yang ditulis
226
+ // pengguna/perintah `minicode model context-window` untuk model
227
+ // yang providernya tidak melaporkan kapasitas; memaksa JSON
228
+ // berisi angka mentah membuat satu salah ketik menghasilkan
229
+ // jendela yang salah tanpa penjelasan. `"auto"` = hapus nilai.
230
+ if (typeof tokens === "number") {
231
+ if (isValidContextWindowValue(tokens)) validContextWindows[model] = tokens
232
+ continue
233
+ }
234
+ if (typeof tokens === "string") {
235
+ const parsed = parseContextWindowInput(tokens)
236
+ if (parsed !== undefined && isValidContextWindowValue(parsed))
237
+ validContextWindows[model] = parsed
225
238
  }
226
239
  }
227
240
  }
package/src/constants.ts CHANGED
@@ -12,6 +12,9 @@ export const LIMITS = {
12
12
  /** Tool output truncation */
13
13
  BASH_OUTPUT_MAX_CHARS: 20_000,
14
14
  BASH_DEFAULT_TIMEOUT_MS: 30_000,
15
+ /** Timeout default bash di mode `unrestricted` (30 menit): kompilasi/instal/
16
+ * push jaringan tak boleh mati oleh timeout pendek; `timeoutMs` tetap menang. */
17
+ UNRESTRICTED_BASH_TIMEOUT_MS: 1_800_000,
15
18
  /** bash background: proses hidup melewati batas turn, dipanggil via bash_output */
16
19
  BASH_BACKGROUND_MAX_JOBS: 8,
17
20
  BASH_BACKGROUND_MAX_LIFETIME_MS: 3_600_000,
@@ -130,12 +133,25 @@ export const LIMITS = {
130
133
  /** F-15: cap output git saat streaming (git_diff/log di repo raksasa). */
131
134
  GIT_OUTPUT_MAX_CHARS: 500_000,
132
135
  /** Executor & sub-agents — tuned for 4-core laptop (6/1) vs 8/2 server */
133
- DEFAULT_MAX_STEPS: 50,
136
+ /** [T-008 OBSERVATION.md] Batas langkah = backstop, bukan anggaran kerja.
137
+ * 50 terlalu kecil untuk kerja nyata (4 dari 5 `turn.failed` pada sesi
138
+ * 17b6a5ff adalah `exceeded 50 steps`). Default kini 200 dan NAIK satu tangga
139
+ * otomatis saat sesi terbukti mentok — lihat `src/policy/step-escalation.ts`.
140
+ * Sub-agent tetap 50 default (berjalan paralel, biaya runaway berlipat), juga
141
+ * dengan eskalasi adaptif. */
142
+ DEFAULT_MAX_STEPS: 200,
134
143
  EXECUTOR_CONCURRENCY: 6,
135
144
  EXECUTOR_WRITE_CONCURRENCY: 1,
136
145
  SUB_AGENT_POOL_SIZE: 3,
137
146
  SUB_AGENT_BUDGET_EXPLORE: 5,
138
147
  SUB_AGENT_BUDGET_PLAN: 15,
148
+ /** [T-008] Cap langkah eksplisit untuk sub-agent tetap 50 walau default sesi
149
+ * utama naik ke 200. Alasan: sub-agent berjalan PARALEL
150
+ * (`SUB_AGENT_POOL_SIZE`) dan tiap langkah = panggilan model sendiri; naiknya
151
+ * biaya runaway berlipat dengan jumlah sub-agent, sedangkan tugas sub-agent
152
+ * lebih sempit. Terpisah dari `DEFAULT_MAX_STEPS` supaya perubahan default
153
+ * sesi utama tidak diam-diam memperluas kewenangan delegasi. */
154
+ SUB_AGENT_MAX_STEPS: 50,
139
155
  SUB_AGENT_TIMEOUT_MS: 120_000,
140
156
  /** Network / providers */
141
157
  RETRY_AFTER_MAX_MS: 30_000,
package/src/lib/net.ts CHANGED
@@ -1,12 +1,6 @@
1
- // Penjaga jaringan bersama: validasi host anti-SSRF + re-resolve DNS per cek.
2
- // Dipakai web_fetch (tool), web_search, dan transport HTTP MCP — server MCP
3
- // remote yang menunjuk ke metadata endpoint adalah jalur SSRF yang identik,
4
- // jadi semuanya memakai satu penjaga yang sama.
5
- // CATATAN audit F7: istilah "DNS pinning" DILARANG di sini — yang dilakukan
6
- // fungsi ini adalah resolve-lalu-cek (check-then-connect), BUKAN menanam IP ke
7
- // socket. Residualnya jujur didokumentasikan di web_fetch (cek dan connect
8
- // bisa melihat IP berbeda); yang ditutup di sini adalah cache basi (noCache)
9
- // dan kegagalan DNS (strict) — pilih per jalur sesuai risikonya.
1
+ // Shared host validation. isPrivateHostWithDns performs resolve-and-check only;
2
+ // web_fetch uses public-http.ts to bind validated addresses to socket lookup.
3
+ // Other consumers still need their own connection-level policy.
10
4
  //
11
5
  // RESIDUAL anti-SSRF yang SENGAJA TIDAK ditutup (dokumentasi jujur, bukan
12
6
  // kelalaian): prefix IPv6 lain yang juga memuat alamat IPv4 tapi tidak
@@ -79,9 +73,8 @@ export function isPrivateHost(host: string): boolean {
79
73
  return isPrivateIPv4(h)
80
74
  }
81
75
 
82
- // DNS pinning untuk tutup DNS rebinding: resolve hostname → cek IP private
83
- // default timeout 400ms fail-open (web_fetch butuh availability); mode strict
84
- // fail-close untuk embedding/MCP (P1.4) agar DNS timeout tidak jadi SSRF bypass.
76
+ // Resolve-and-check only; legacy default is 400ms fail-open, strict is 1000ms
77
+ // fail-closed. Tool web_fetch uses the separate pinned public HTTP transport.
85
78
  const dnsCache = new Map<string, { addrs: string[]; at: number }>()
86
79
  export async function isPrivateHostWithDns(
87
80
  hostname: string,
@@ -111,9 +104,7 @@ export async function isPrivateHostWithDns(
111
104
  if (!opts.noCache) dnsCache.set(hostname, { addrs, at: Date.now() })
112
105
  for (const a of addrs) if (isPrivateHost(a) || isPrivateIPv4(a)) return true
113
106
  } catch {
114
- // lookup gagal/timeout → strict fail-close (embedding/MCP), default fail-open
115
- // agar web_fetch tidak block availability bila DNS lambat. Jangan cache
116
- // `addrs: []` saat gagal supaya panggilan strict berikutnya tetap mengecek ulang.
107
+ // Strict consumers fail closed on DNS errors. Never cache a failed lookup.
117
108
  if (opts.strict) return true
118
109
  } finally {
119
110
  if (timer !== undefined) clearTimeout(timer)
@@ -0,0 +1,128 @@
1
+ import { lookup } from "node:dns/promises"
2
+ import * as http from "node:http"
3
+ import * as https from "node:https"
4
+ import { isIP } from "node:net"
5
+ import { pipeline, Readable } from "node:stream"
6
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib"
7
+ import { isPrivateHost } from "./net.ts"
8
+
9
+ /** Resolve once and pass only validated addresses to the socket lookup.
10
+ * The original URL retains HTTP Host and HTTPS certificate/SNI validation.
11
+ * No proxy, connection pool, or automatic redirect can bypass this lookup. */
12
+ export async function fetchPublicUrl(
13
+ url: URL,
14
+ init: { signal: AbortSignal; headers: Record<string, string> },
15
+ ): Promise<Response> {
16
+ init.signal.throwIfAborted()
17
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("disallowed protocol")
18
+ const hostname = url.hostname.replace(/^\[|\]$/g, "")
19
+ if (isPrivateHost(hostname)) throw new Error(`blocked private host: ${hostname}`)
20
+ const family = isIP(hostname)
21
+ let addresses: { address: string; family: number }[]
22
+ if (family) addresses = [{ address: hostname, family }]
23
+ else {
24
+ const signal = AbortSignal.any([init.signal, AbortSignal.timeout(1000)])
25
+ let onAbort!: () => void
26
+ try {
27
+ addresses = await Promise.race([
28
+ lookup(hostname, { all: true }),
29
+ new Promise<never>((_, reject) => {
30
+ onAbort = () => reject(signal.reason)
31
+ signal.addEventListener("abort", onAbort, { once: true })
32
+ if (signal.aborted) onAbort()
33
+ }),
34
+ ])
35
+ } catch {
36
+ init.signal.throwIfAborted()
37
+ throw new Error(`blocked private host: ${hostname} (DNS resolution failed)`)
38
+ } finally {
39
+ signal.removeEventListener("abort", onAbort)
40
+ }
41
+ }
42
+ if (
43
+ !addresses.length ||
44
+ addresses.some((entry) => !isIP(entry.address) || isPrivateHost(entry.address))
45
+ ) {
46
+ throw new Error(`blocked private host: ${hostname}`)
47
+ }
48
+ init.signal.throwIfAborted()
49
+ const target = new URL(url)
50
+ target.username = ""
51
+ target.password = ""
52
+ return new Promise<Response>((resolve, reject) => {
53
+ const request = target.protocol === "https:" ? https.request : http.request
54
+ const req = request(
55
+ target,
56
+ {
57
+ method: "GET",
58
+ headers: init.headers,
59
+ signal: init.signal,
60
+ agent: false,
61
+ lookup: (_host, options, callback) => {
62
+ // Both Node and Bun may request all addresses for family autoselection.
63
+ if ((options as { all?: boolean }).all) {
64
+ callback(null, addresses as never)
65
+ } else {
66
+ const entry = addresses[0]!
67
+ callback(null, entry.address, entry.family)
68
+ }
69
+ },
70
+ },
71
+ (res) => {
72
+ let body: Readable = res
73
+ try {
74
+ const headers = new Headers()
75
+ for (let i = 0; i < res.rawHeaders.length; i += 2) {
76
+ headers.append(res.rawHeaders[i]!, res.rawHeaders[i + 1]!)
77
+ }
78
+ const status = res.statusCode ?? 502
79
+ if (status < 200 || status > 599) throw new Error(`invalid HTTP status: ${status}`)
80
+ const noBody = status === 204 || status === 205 || status === 304
81
+ if (noBody) res.resume()
82
+ else {
83
+ const encodings = (headers.get("content-encoding") ?? "")
84
+ .split(",")
85
+ .map((s) => s.trim().toLowerCase())
86
+ .filter((s) => s && s !== "identity")
87
+ for (const encoding of encodings.reverse()) {
88
+ const decoder =
89
+ encoding === "gzip"
90
+ ? createGunzip()
91
+ : encoding === "deflate"
92
+ ? createInflate()
93
+ : encoding === "br"
94
+ ? createBrotliDecompress()
95
+ : undefined
96
+ if (!decoder) throw new Error(`unsupported content encoding: ${encoding}`)
97
+ pipeline(body, decoder, () => {})
98
+ body = decoder
99
+ }
100
+ if (encodings.length) {
101
+ headers.delete("content-encoding")
102
+ headers.delete("content-length")
103
+ }
104
+ }
105
+ resolve(
106
+ new Response(
107
+ noBody ? null : (Readable.toWeb(body) as unknown as ReadableStream<Uint8Array>),
108
+ {
109
+ status,
110
+ statusText: res.statusMessage,
111
+ headers,
112
+ },
113
+ ),
114
+ )
115
+ } catch (error) {
116
+ body.destroy()
117
+ res.destroy()
118
+ reject(error)
119
+ }
120
+ },
121
+ )
122
+ req.once("error", reject)
123
+ req.end()
124
+ })
125
+ }
126
+
127
+ // A module boundary for transport-level tests without opening real network sockets.
128
+ export const publicHttp = { fetch: fetchPublicUrl }