Repository navigation
Description
Problem
historyCompact only compacts prior RuntimeEvents at a turn boundary. During one long active turn, provider-visible messages can exceed the selected model's context window before another boundary exists.
activeToolResultPrune bounds individual large tool results but does not bound aggregate message growth. semanticCompact covers part of this path, but it is invocation-local and is not enabled consistently across Desktop, TUI, and headless. The runtime therefore has no surface-independent guarantee that a long turn will compact and continue before the provider rejects it for context length.
Direction
Establish one runtime-owned active-turn context invariant:
- measure the next provider request against the selected model context window and reserve;
- compact a safe completed prefix before crossing the high-water threshold;
- preserve the exact recent tail and complete tool call/result pairs;
- continue the same turn automatically after compaction;
- prevent the replaced raw span from being re-injected on later steps or recovery;
- reuse or merge the existing semantic and history compaction seams instead of adding a parallel implementation.
Record the trigger, replacement, token savings, auxiliary model usage, continuation, and fail-open reason in existing context-budget diagnostics.
Done when
- A deterministic long single-turn test triggers compaction before provider context exhaustion.
- The same turn and run continue without another user message.
- Completed tool calls are not executed again.
- Replaced raw messages are not re-injected after compaction.
- The next provider request remains within the configured model budget.
- Desktop, TUI, and headless use the same runtime invariant, with surface policy limited to explicit thresholds or opt-outs.
- If no safe compact span can be produced, the runtime reports an explicit context-budget outcome instead of relying on a provider context-length error.
Non-goals
- Benchmark-specific threshold tuning.
- A second compaction storage or replay protocol.
- Changing verifier or task-completion authority.
Activity
Astro-Han commentedon Jul 14, 2026
Implementation plan
Scoping this issue against the boundary reached in #981 discussion: this issue owns the standard Context compaction capacity invariant, extended to
phase=mid_turn. It is fully decoupled from the attention-first experiment line (#981 / #986); neither blocks the other, and nothing here touches thesemanticCompact/activeFullCompactexperiment surfaces.Mechanism. Reuse the existing historyCompact V2
HistoryCompactCheckpointprotocol for mid-turn capacity compaction. The protocol is already turn-agnostic (pure event-prefix cursor + digest math); what actually changes:ai-sdk-backend.ts,event.turnId !== input.turnId);summarizeHistoryCompactLLM seam; no deterministic fallback — if the summarizer fails or no safe boundary exists, report an explicit outcome instead.Triggering — two lines of defense.
reason: context_limit): atprepareStep, compare last step's real provider usage plus a tail-delta estimate againstcontextWindow − reserve; compact before sending. char/4 estimation remains only as cold-start fallback. (All surveyed peers — Codex, opencode, gemini-cli, pi — anchor on real usage rather than pure character estimates.)reason: overflow): classify provider context-length errors inclassifyError(currently bucketed asOther), compact once, resend once — a pi-style single-retry latch. A second failure terminates with the explicit outcome.Explicit outcome. When compaction cannot produce a provider-safe request, the turn ends with a first-class
context_budget_exhaustedoutcome (with detail such asno_safe_completed_span/summarizer_failed) instead of a raw provider error.Defaults. The invariant becomes runtime-owned: a backend that receives no explicit policy derives it from the selected model's
contextWindow − reserve, including mid_turn. All three surfaces get it by default; surface policy is limited to explicit thresholds or opt-outs (MAKA_CONTEXT_HISTORY_COMPACT_MID_TURN=off). Desktop'ssemanticCompactdefault flips to off (it is the #981 experiment, not the standard mechanism). Headless benchmark baselines that need the old behavior opt out explicitly.Naming. Existing identifiers are untouched. New dimensions:
phase: 'pre_turn' | 'mid_turn'on checkpoints/diagnostics (absent = pre_turn),reason: 'context_limit' | 'overflow', outcomecontext_budget_exhausted. Notriggerdimension for now;reasonalready covers a futureuser_requested. The declared-but-unwiredreactive_prompt_too_longon the experiment types stays untouched.Delivery — three PRs.
feat(runtime): mid-turn capacity compaction — event-level boundary selection, mid_turn V2 checkpoints, proactive real-usage trigger,context_budget_exhaustedoutcome, same-turn continuation, deterministic long-turn tests.feat(runtime): reactive recovery — context-length error classification + single compact-and-retry latch.feat: runtime-owned defaults + three-surface alignment + DesktopsemanticCompactdefault off + headless opt-out, with cross-surface E2E covering the done-when list.Non-goals unchanged from the issue body; additionally out of scope here: any change to #986, deterministic summary fallback, benchmark threshold tuning, new compaction storage or replay protocols.
feat(runtime): mid-turn capacity compaction with a single final-paylo…
fix: reland merges reverted by #1005's snapshot squash (#1014)
feat(runtime): reactive context-overflow compact-and-retry recovery (#…
feat: runtime-owned context compaction defaults across surfaces (#1018)
Astro-Han commentedon Jul 15, 2026
Closing as completed by #996, #1017, and #1018.
The runtime now owns the active-turn context invariant:
contextWindow - reserve;mid_turncheckpoint before the projection is replaced;[compact block, verbatim head anchor, preserved tail];context_budget_exhausted;Acceptance is covered at the runtime boundary that owns
prepareStep:A Desktop Playwright test was intentionally not added because its fake backend bypasses
prepareStepand would only simulate the mechanism under test. The runtime streaming integration suite exercises the realAiSdkBackendpipeline.Final verification on current
main:npm --workspace @maka/runtime test— 1936 tests, 1929 passed, 7 skipped, 0 failed.