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
@@ -132,6 +132,39 @@ function renderAssistantLine(line: string, fenceState: FenceState): string | nul
132
132
  return renderInline(line)
133
133
  }
134
134
 
135
+ /**
136
+ * Rapikan hanya whitespace presentasi jawaban model: hapus baris kosong di
137
+ * tepi dan batasi jeda berulang di luar fenced code. Isi code fence tetap
138
+ * literal karena spasi dan baris kosong di dalamnya adalah bagian contoh.
139
+ */
140
+ function normalizeAssistantOutput(text: string): string {
141
+ const lines = text.replace(/\r\n?/g, "\n").split("\n")
142
+ const out: string[] = []
143
+ let openFence: { char: string; len: number } | null = null
144
+ for (const line of lines) {
145
+ const fence = parseFence(line)
146
+ if (openFence) {
147
+ out.push(line)
148
+ if (fence && fence.char === openFence.char && fence.len >= openFence.len) openFence = null
149
+ continue
150
+ }
151
+ if (fence) {
152
+ openFence = fence
153
+ out.push(line)
154
+ continue
155
+ }
156
+ if (!line.trim()) {
157
+ if (out.length && out[out.length - 1] !== "") out.push("")
158
+ continue
159
+ }
160
+ out.push(line)
161
+ }
162
+ // Jika fence belum ditutup, baris kosong di ekor masih bagian dari contoh
163
+ // kode dan harus tetap literal. Hanya whitespace di luar fence yang dirapatkan.
164
+ if (!openFence) while (out.length && out[out.length - 1] === "") out.pop()
165
+ return out.join("\n")
166
+ }
167
+
135
168
  let selectionSegmenter: Intl.Segmenter | undefined
136
169
 
137
170
  function offsetAtColumn(text: string, start: number, end: number, column: number): number {
@@ -177,6 +210,11 @@ export class Transcript {
177
210
  private nextOrder = 1
178
211
  private pending = ""
179
212
  private pendingTruncated = false
213
+ private activeProviderAttempt: {
214
+ id: number
215
+ pendingLength: number
216
+ pendingTruncated: boolean
217
+ } | null = null
180
218
  private maxPendingChars: number
181
219
  /** Hitung monotonik baris yang pernah ditambah — basis indikator "baru"
182
220
  * yang kebal evict cap 5000 (size() menyusut saat tertua dibuang). */
@@ -250,6 +288,39 @@ export class Transcript {
250
288
 
251
289
  /** Chunk reasoning (`provider:extension` kind reasoning, data {text}). */
252
290
  extension(e: { kind: string; data: unknown }): void {
291
+ if (e.kind === "minicode:attempt") {
292
+ const data = e.data as {
293
+ phase?: unknown
294
+ attemptId?: unknown
295
+ hadVisibleOutput?: unknown
296
+ } | null
297
+ const id = data?.attemptId
298
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id < 1) return
299
+ if (data?.phase === "started") {
300
+ this.activeProviderAttempt = {
301
+ id,
302
+ pendingLength: this.pending.length,
303
+ pendingTruncated: this.pendingTruncated,
304
+ }
305
+ } else if (data?.phase === "completed") {
306
+ if (this.activeProviderAttempt?.id === id) this.activeProviderAttempt = null
307
+ } else if (data?.phase === "invalidated" && this.activeProviderAttempt?.id === id) {
308
+ this.pending = this.pending.slice(0, this.activeProviderAttempt.pendingLength)
309
+ this.pendingTruncated = this.activeProviderAttempt.pendingTruncated
310
+ this.activeProviderAttempt = null
311
+ // Reasoning dari attempt yang gagal tidak boleh tertinggal sebagai
312
+ // konten aktif/collapsible. Baris reasoning yang sudah dipaint tetap
313
+ // diberi marker append-only di bawah.
314
+ this.thinkingBuf = ""
315
+ this.thinkingTail = ""
316
+ if (data.hadVisibleOutput === true) {
317
+ this.push(c.warning(t("ts.providerAttemptDiscarded", { attempt: id })), {
318
+ kind: "diagnostic",
319
+ })
320
+ }
321
+ }
322
+ return
323
+ }
253
324
  if (e.kind !== "reasoning") return
254
325
  const text = (e.data as { text?: string } | null)?.text ?? ""
255
326
  if (!text) return
@@ -333,6 +404,7 @@ export class Transcript {
333
404
  this.meta = []
334
405
  this.pending = ""
335
406
  this.pendingTruncated = false
407
+ this.activeProviderAttempt = null
336
408
  this.thinkingBuf = ""
337
409
  this.thinkingTail = ""
338
410
  this.evicted = 0
@@ -517,13 +589,18 @@ export class Transcript {
517
589
  }
518
590
  if (this.pending) {
519
591
  const pendingFence = this.fenceTracker()
520
- for (const block of parseMarkdownBlocks(sanitizeAnsi(this.pending))) {
521
- if (block.type === "table") rows.push(...this.projectTable(block.table, -1, w))
522
- else
523
- for (const line of block.text.split("\n")) {
524
- const clean = stripSgr(sanitizeAnsi(line))
525
- rows.push(...this.projectText(line, clean, -1, w, false, "", true, pendingFence(line)))
526
- }
592
+ const pending = normalizeAssistantOutput(sanitizeAnsi(this.pending))
593
+ if (pending) {
594
+ for (const block of parseMarkdownBlocks(pending)) {
595
+ if (block.type === "table") rows.push(...this.projectTable(block.table, -1, w))
596
+ else
597
+ for (const line of block.text.split("\n")) {
598
+ const clean = stripSgr(sanitizeAnsi(line))
599
+ rows.push(
600
+ ...this.projectText(line, clean, -1, w, false, "", true, pendingFence(line)),
601
+ )
602
+ }
603
+ }
527
604
  }
528
605
  }
529
606
  if (this.pendingTruncated) {
@@ -668,11 +745,13 @@ export class Transcript {
668
745
 
669
746
  private commit(): void {
670
747
  if (!this.pending) return
671
- const text = this.pendingTruncated
748
+ const rawText = this.pendingTruncated
672
749
  ? `${this.pending}\n${TRANSCRIPT_TRUNCATION_MARKER}`
673
750
  : this.pending
674
751
  this.pending = ""
675
752
  this.pendingTruncated = false
753
+ const text = normalizeAssistantOutput(rawText)
754
+ if (!text) return
676
755
  for (const block of parseMarkdownBlocks(sanitizeAnsi(text))) {
677
756
  if (block.type === "table") this.appendTable(block.table, { kind: "assistant" })
678
757
  else {
@@ -1,14 +1,18 @@
1
1
  # vendor/minicore — JANGAN EDIT MANUAL
2
2
 
3
- Salinan kernel MiniCore agar `bun install` tidak membutuhkan clone sibling
4
- `../minicore`. Sumber kebenaran tetap repo minicore.
3
+ Salinan MiniCore dari source commit yang dipin, ditambah overlay host yang
4
+ diperiksa dari patch di `scripts/vendor-overlays/minicode-context.patch`.
5
+ Overlay memberi admission context per model dan system prompt dinamis;
6
+ simpan seam ini saat menyinkronkan source upstream.
5
7
 
6
8
  - source commit: `0d33571047c0ed3778986108fd42e4bde6828bb0`
9
+ - source hash: `c8d214bb8d5eea86`
10
+ - overlay sha256: `7545ff914e4f83745634ee106c9a2e774dfea3bf4541e58ea98eba216902d432`
7
11
  - files: 20
8
- - hash: `c8d214bb8d5eea86`
9
- - shipped hash: `78768e71a45254c3` (18 file) — fingerprint file vendor yang ikut paket npm
12
+ - hash: `b5e27f72d08afb98`
13
+ - shipped hash: `4998979304b3c6e2` (18 file) — fingerprint file vendor yang ikut paket npm
10
14
  (hash di atas mencakup test/fakes.ts yang sengaja tidak ikut paket;
11
15
  verifikasi dari paket terbit: hitung hash vendor/minicore di dalam tarball)
12
16
 
13
17
  Perbarui dengan `bun run vendor:minicore` (butuh `../minicore`).
14
- CI memverifikasi kesinkronan lewat `bun run vendor:check`.
18
+ `bun run vendor:check` memverifikasi source, overlay, dan fingerprint final.
@@ -45,11 +45,27 @@ export async function executeTurn(
45
45
  // compaction burned the one recovery retry (though recovery was never
46
46
  // tried), and vice versa. The recovery flag is ALWAYS set (a guard
47
47
  // against an infinite loop: force_compact_and_retry is exempt from
48
- // maxProviderRetries); the policy flag is set when a policy compaction
49
- // is attempted (once per turn, guarding against per-step O(n) repeats).
50
- let compactedForBudget = false;
48
+ // maxProviderRetries); policy compaction has a small per-turn hard cap,
49
+ // guarding against repeated no-progress work after tool output grows.
50
+ // Permit one follow-up policy compaction after tool results grow the current
51
+ // turn. The hard cap prevents a no-progress compactor from looping forever.
52
+ let budgetCompactions = 0;
53
+ const maxBudgetCompactions = 2;
51
54
  let compactedForRecovery = false;
52
55
 
56
+ // Resolve once for the turn: model switching is a between-turn operation,
57
+ // so budget admission and output accounting must use the same model window.
58
+ let contextWindowTokens = s.contextWindowTokens;
59
+ try {
60
+ const resolved = s.contextWindowTokensForModel?.(s.state.model);
61
+ if (typeof resolved === "number" && Number.isSafeInteger(resolved) && resolved > 0) {
62
+ contextWindowTokens = resolved;
63
+ }
64
+ } catch {
65
+ // Keep the validated numeric fallback; a metadata lookup must not bypass
66
+ // the kernel's context guard.
67
+ }
68
+
53
69
  while (true) {
54
70
  if (signal.aborted) throw abortError(signal);
55
71
  if (stepIndex >= s.maxSteps) throw new AgentError("max_steps_exceeded", `exceeded ${s.maxSteps} steps`);
@@ -59,28 +75,36 @@ export async function executeTurn(
59
75
  // prompt and tool schemas, which are sent on every request.
60
76
  let pressure = s.budget.evaluate({
61
77
  usedTokens: contextTokens(s),
62
- limitTokens: s.contextWindowTokens,
78
+ limitTokens: contextWindowTokens,
63
79
  });
64
- if (s.budget.shouldCompact(pressure) && !compactedForBudget) {
80
+ let reduced = false;
81
+ if (s.budget.shouldCompact(pressure) && budgetCompactions < maxBudgetCompactions) {
65
82
  const before = s.store.messages.length;
66
83
  await compactStore(s, signal);
67
- compactedForBudget = true;
84
+ budgetCompactions++;
68
85
  // The reason distinguishes the trigger and whether compaction
69
86
  // actually shrank the store (no-op = nothing evictable in messages;
70
87
  // reporters must tell that apart from fixed system+schema overhead,
71
88
  // which compaction never touches).
72
- const reduced = s.store.messages.length < before;
89
+ reduced = s.store.messages.length < before;
73
90
  s.events.emit({
74
91
  type: "context:compacted",
75
92
  reason: reduced ? `pressure:${pressure}` : `pressure:${pressure}:no-op`,
76
93
  });
77
94
  pressure = s.budget.evaluate({
78
95
  usedTokens: contextTokens(s),
79
- limitTokens: s.contextWindowTokens,
96
+ limitTokens: contextWindowTokens,
80
97
  });
81
98
  }
82
- if (pressure === "critical" && compactedForBudget) {
83
- throw new AgentError("budget_exceeded", "context window exceeded after compaction");
99
+ if (s.budget.shouldCompact(pressure) && reduced && budgetCompactions < maxBudgetCompactions) {
100
+ continue;
101
+ }
102
+ if (pressure === "critical") {
103
+ const used = contextTokens(s);
104
+ throw new AgentError(
105
+ "budget_exceeded",
106
+ `context window exceeded after compaction (${used} > ${contextWindowTokens}); reduce the prompt, tool output, or fixed instructions, or select a model with a larger context window`,
107
+ );
84
108
  }
85
109
 
86
110
  // Sample from the provider with deterministic recovery.
@@ -176,7 +200,11 @@ export async function executeTurn(
176
200
  throw new AgentError("provider", errorMessage ?? "provider error", { cause: providerError ?? action });
177
201
  case "force_compact_and_retry": {
178
202
  if (compactedForRecovery)
179
- throw new AgentError("budget_exceeded", errorMessage ?? "context too large", { cause: providerError ?? action });
203
+ throw new AgentError(
204
+ "budget_exceeded",
205
+ `context window exceeded after recovery compaction: ${errorMessage ?? "context too large"}`,
206
+ { cause: providerError ?? action },
207
+ );
180
208
  await compactStore(s, signal);
181
209
  // The recovery flag is ALWAYS set (even on no-op):
182
210
  // force_compact_and_retry is exempt from maxProviderRetries, so a
@@ -301,6 +329,9 @@ function toolErrorResult(call: ToolCall, message: string): ToolResult {
301
329
 
302
330
  function toProviderError(error: unknown, signal: AbortSignal): ProviderError {
303
331
  if (signal.aborted) throw abortError(signal);
332
+ // Host-side admission guards (context budget, shutdown, etc.) preserve their
333
+ // deterministic AgentError identity instead of entering provider retry.
334
+ if (error instanceof AgentError) throw error;
304
335
  if (error instanceof ProviderError) return error;
305
336
  if (error instanceof Error && error.name === "AbortError") {
306
337
  throw abortError(signal);
@@ -333,7 +364,11 @@ function delay(ms: number, signal: AbortSignal): Promise<void> {
333
364
  function contextTokens(s: SessionInternal): number {
334
365
  // Single source in tokens.ts `estimateSessionContext` — shared by the
335
366
  // loop and the Session getter so no duplicate estimator can drift.
336
- return estimateSessionContext(s.store, s.system, s.registry.list(), s.estimator);
367
+ let system = s.system;
368
+ try {
369
+ system = s.systemForContext?.() ?? system;
370
+ } catch {}
371
+ return estimateSessionContext(s.store, system, s.registry.list(), s.estimator);
337
372
  }
338
373
 
339
374
  // The single compaction seam. Prefers the strategy's optional async method
@@ -35,5 +35,9 @@ export interface StreamRequest {
35
35
  export interface ModelProvider {
36
36
  readonly id: string;
37
37
  readonly models: readonly string[];
38
+ /** Optional host metadata for per-model admission budgets. */
39
+ contextWindowTokensForModel?(model?: string): number;
40
+ /** Canonical provider/model key for per-model estimator state. */
41
+ contextModelIdentity?(model?: string): string | undefined;
38
42
  stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent>;
39
43
  }
@@ -35,6 +35,8 @@ export interface SessionConfig {
35
35
  permissions: PermissionHandler;
36
36
  tools?: readonly Tool[];
37
37
  system?: string;
38
+ /** Dynamic system prompt for host-controlled per-turn mode hints. */
39
+ systemForContext?: () => string;
38
40
  model?: string;
39
41
  cwd?: string;
40
42
  /**
@@ -59,6 +61,9 @@ export interface SessionConfig {
59
61
  recovery?: RecoveryPolicy;
60
62
  maxSteps?: number;
61
63
  contextWindowTokens?: number;
64
+ /** Resolve a model-specific context limit for each run. Additive app seam;
65
+ * the numeric option remains the fallback for existing library callers. */
66
+ contextWindowTokensForModel?: (model?: string) => number;
62
67
  toolResultMaxTokens?: number;
63
68
  keepRecentTurns?: number;
64
69
  /**
@@ -138,6 +143,7 @@ export interface SessionInternal {
138
143
  readonly registry: ToolRegistry;
139
144
  readonly executor: ToolExecutor;
140
145
  readonly system?: string;
146
+ readonly systemForContext?: () => string;
141
147
  readonly model?: string;
142
148
  readonly cwd?: string;
143
149
  readonly permissionMode?: string | (() => string);
@@ -147,6 +153,7 @@ export interface SessionInternal {
147
153
  readonly recovery: RecoveryPolicy;
148
154
  readonly maxSteps: number;
149
155
  readonly contextWindowTokens: number;
156
+ readonly contextWindowTokensForModel?: (model?: string) => number;
150
157
  readonly toolResultMaxTokens: number;
151
158
  readonly keepRecentTurns: number;
152
159
  readonly timeoutMs: number;
@@ -178,6 +185,7 @@ export function createSession(config: SessionConfig): Session {
178
185
  registry: createToolRegistry(config.tools ?? []),
179
186
  executor: config.executor ?? sequentialExecutor(),
180
187
  system: config.system,
188
+ systemForContext: config.systemForContext,
181
189
  model: config.model,
182
190
  cwd: config.cwd,
183
191
  permissionMode: config.permissionMode,
@@ -187,6 +195,7 @@ export function createSession(config: SessionConfig): Session {
187
195
  recovery: config.recovery ?? defaultRecoveryPolicy,
188
196
  maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS,
189
197
  contextWindowTokens: config.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS,
198
+ contextWindowTokensForModel: config.contextWindowTokensForModel,
190
199
  toolResultMaxTokens: config.toolResultMaxTokens ?? DEFAULT_TOOL_RESULT_MAX_TOKENS,
191
200
  keepRecentTurns: config.keepRecentTurns ?? DEFAULT_KEEP_RECENT_TURNS,
192
201
  timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
@@ -210,7 +219,11 @@ export function createSession(config: SessionConfig): Session {
210
219
  // Same source of truth as the loop — estimateSessionContext in
211
220
  // tokens.ts — never a duplicate estimator.
212
221
  get contextTokens() {
213
- return estimateSessionContext(store, config.system, impl.registry.list(), impl.estimator);
222
+ let system = config.system
223
+ try {
224
+ system = config.systemForContext?.() ?? system
225
+ } catch {}
226
+ return estimateSessionContext(store, system, impl.registry.list(), impl.estimator);
214
227
  },
215
228
  async run(input, opts) {
216
229
  if (impl.running) throw new AgentError("busy", "session is already running");