You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Avoid cold-cache replay penalties: Auto-compact per account before hitting 100% quota
#44039
Automatically compact eligible threads on a provider instance right before its 5-hour or weekly quota hits 100%, while server-side prompt caches are still warm, then arm Resume at reset or hand off cleanly into user-configured fallback targets.
Net savings per thread (after subtracting the warm /compact call itself): Because cached input reads cost 90% to 95% less than uncached cold input (0.05x to 0.10x vs. 1.00x, a 10x to 20x input cost gap):
OpenAI / Codex 272K default window (250K active tokens): A warm /compact reads 250K cached tokens (~12.5K to 25K input-equivalent) instead of replaying 250K cold tokens after reset, saving ~225K to 237K input-equivalent tokens per thread (~90% to 95% replay reduction).
1M context window sessions (900K active tokens on Claude 1M, Gemini, or OpenAI 1,050K API): A warm /compact reads 900K cached tokens (~45K to 90K input-equivalent) instead of replaying 900K cold tokens after reset, saving ~810K to 855K raw input tokens per thread (and up to ~1.4M+ standard-input-equivalent tokens where 2x long-context pricing applies above 272K).
Problem (Prioritized by Frequency & Impact)
Even a single user on one thread gets trapped when a 5-hour or weekly bucket runs out with hours left until refresh: Server-side prompt caches expire in minutes (5 min default on Claude, 30 min minimum on OpenAI/Codex, minutes-scale on Gemini/Antigravity), long before the quota refreshes. Once usage hits 100%, /compact is blocked because it requires model inference against that same exhausted quota bucket. When the quota finally refreshes, resuming replays the entire cold history at full uncached input weight (1.00x), burning a huge chunk of the fresh window immediately.
Concurrent threads overshoot 100% together: When multiple threads run concurrently on the same provider instance, in-flight turns finishing together can jump usage from ~95% straight to 100% before any thread has headroom left to compact.
Bloated cross-account or cross-provider handoffs: Switching a thread to a secondary provider instance or fallback provider mid-session forces ContextHandoffDelivery to truncate or summarize a massive uncompacted transcript instead of handing off a distilled summary.
Proposal (Prioritized by Implementation Order)
Enable pre-quota protection automatically by default per provider instance (providerInstanceId), requiring zero setup, with two optional overrides under Settings -> Providers -> Advanced (alongside Compact idle threads):
Evaluate quota strictly per provider instance (providerInstanceId, keeping separate work/personal accounts isolated) using existing cached usageLimits snapshots and active thread state:
Active threads on that instance (N): Reserve compaction headroom for every active/recent thread above the minimum context threshold on that instance (N * perThreadCompactReserve), weighted by thread token size (272K vs. 1M).
Safety & in-flight overhead (overheadMargin): Add a fixed safety margin plus estimated in-flight turn burn and between-poll token deltas so bursty tool loops and conservative polling intervals do not overshoot 100%.
Plan-tier scaling: Weight reserves by plan bucket size, capping effectiveThreshold at ~99% for a single serial 5h thread and scaling automatically when multiple heavy threads are active and adjusting for plan size. (params would ideally be tuned eventually)
When a provider instance crosses effectiveThreshold:
Pause new queued dispatches only on that instance (queueHeld), leaving other accounts/providers unaffected.
Let currently streaming turns on that instance finish at a clean turn boundary.
Dispatch compactThread across eligible open threads above the minimum context threshold while prompt caches are still warm, respecting each provider's native mechanics:
Provider / Runtime
Compaction & Cache Handling in Sweep
Claude Code (Claude)
Uses native compactThread and promptCacheExpiresAt; skips threads whose cache already expired unless fallback handoff is triggered (#17170).
OpenAI / Codex (Codex)
Uses native compactThread across 272K default or 1,050K API sessions; compacting threads above 272K avoids the 2x long-context input cliff on cold replay.
Antigravity / Gemini (Antigravity)
Uses ACP compact when advertised (agy1.5+, respecting its ~256K compaction clamp) and handles post-compaction ACP session rotation cleanly; skips older runtimes lacking compact.
Other ACP Registry Agents
Skips in-place compaction cleanly when unsupported (#22636), relying on ContextHandoffDelivery (T3CODE_CONTEXT_HANDOFF_TOKEN_CAP) during fallback handoff.
Record a single quiet timeline divider ("Compacted before quota limit").
Default (Resume at reset): Arm UsageLimitRecoveryWorker on swept threads so they resume cheaply from their compact summary once the quota refreshes.
User-configured fallback (once #18949 / #19695 is merged): Hand off active threads to the next user-configured provider instance or fallback provider using the freshly compacted summary.
Benefits & Limitations
Benefits
90% to 95% replay savings on every large thread: Saves ~225K to 237K input-equivalent tokens on 272K threads and ~810K to 855K+ on 1M threads, whether running one thread or many.
Zero-config, per-instance isolation: Works out of the box per providerInstanceId with zero extra quota-endpoint polling.
Prevents multi-thread overshoot & cleans up handoffs: Reserves headroom for concurrent turns plus overhead, and hands off distilled summaries instead of truncated transcripts.
Limitations & Trade-offs
Polling granularity: Conservative usage polling means extreme single-turn spikes between polls can still hit 100% before a sweep fires, though local per-turn delta estimation and overheadMargin minimize this.
Runtime capability gaps: Agents without native compaction (#22636, Antigravity < 1.5) cannot be compacted in-place and rely on handoff distillation instead.
Summary vs. verbatim detail: Compaction trades verbatim tool output for a concise summary (~8K to 23K tokens), which is why threads under 100K tokens (default) are skipped.
Related Discussions & Issues
#18949 (Continue a thread on another account when it hits a usage limit) & #19695 (Unified subscription and API usage with configurable fallback): Cover user-configured failover across accounts/providers; pre-compacting per instance ensures clean handoffs and cheap post-reset resumes.
#38726 (Agent Supervisor: Sleep Prevention, Auto-Answer & Provider Failover): Proposes ordered provider failover on quota exhaustion; this provides the pre-cutoff warm-cache compaction step ahead of failover.
#38080 (Stop before paid usage): Stops turns before overage billing; this compacts threads just before hitting the included-plan cap.
#24862 (Compact a large Claude thread before auto-resuming after a usage limit): Compacts after reset once the cache has already expired; pre-quota compaction avoids paying the uncached replay cost altogether.
#15128 (Auto-fork thread with distilled context on rate-limit / quota cutoff): Forks a single thread at cutoff; this sweeps all eligible threads on the provider instance ahead of cutoff.
#17170 (A setting to turn off compact-before-send on stale Claude threads): Explains why post-expiry compaction loses warm-cache savings and why a minimum context threshold is needed.
#5539, #6582, #6683, & #32078: Establish multi-account usageLimits tracking, pace visibility, and per-account UI rings; this acts automatically on those existing per-instance snapshots.
#40936 (Record prompt-cache lifetime and compaction point for Codex and Antigravity) & #22636: Supply per-provider cache TTL, compaction threshold metadata, and ACP capability gating.
(Note: Distinct from #2471, closed as not planned, as this does not rotate pooled credentials and only hands off to explicit user-configured fallback targets.)
Smallest Useful Scope (MVP)
Per-instance Auto threshold + overrides: Add Auto pre-quota threshold calculation (activeThreadsOnInstance + safety overhead margin, capped at 99%), an unrestricted Custom % / Off override, and a minimum context threshold (100K default) in Settings -> Providers -> Advanced.
Instance-scoped sweep + Resume at reset: Hold new dispatches on the threshold-crossing provider instance, compact eligible open threads above the minimum context threshold while caches are warm, and arm Resume at reset.
Fallback handoff integration: Hook post-sweep threads into user-configured cross-account/provider handoff once #18949 / #19695 is merged.
Acceptance Criteria
Enabled by default in Auto mode per provider instance using existing usageLimits snapshots, per-instance active thread count, and safety overhead margin, with an unrestricted Custom % / Off override and minimum context threshold (100K default) in Settings -> Providers -> Advanced.
Crossing the threshold holds new dispatches only on that provider instance, lets active turns finish cleanly, and compacts eligible threads above the minimum context threshold while prompt caches are warm.
Providers/runtimes without native compaction support (or with already-expired caches per #17170) are skipped cleanly without failing the sweep.
Swept threads automatically arm Resume at reset or hand off cleanly into user-configured fallback targets (#18949).
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Summary & Net Quota Savings
Automatically compact eligible threads on a provider instance right before its 5-hour or weekly quota hits 100%, while server-side prompt caches are still warm, then arm
Resume at resetor hand off cleanly into user-configured fallback targets.Net savings per thread (after subtracting the warm
/compactcall itself): Because cached input reads cost 90% to 95% less than uncached cold input (0.05x to 0.10xvs.1.00x, a 10x to 20x input cost gap):272Kdefault window (250K active tokens): A warm/compactreads 250K cached tokens (~12.5K to 25Kinput-equivalent) instead of replaying 250K cold tokens after reset, saving ~225K to 237K input-equivalent tokens per thread (~90% to 95% replay reduction).1Mcontext window sessions (900K active tokens on Claude 1M, Gemini, or OpenAI1,050KAPI): A warm/compactreads 900K cached tokens (~45K to 90Kinput-equivalent) instead of replaying 900K cold tokens after reset, saving ~810K to 855K raw input tokens per thread (and up to ~1.4M+ standard-input-equivalent tokens where 2x long-context pricing applies above 272K).Problem (Prioritized by Frequency & Impact)
5 mindefault on Claude,30 minminimum on OpenAI/Codex, minutes-scale on Gemini/Antigravity), long before the quota refreshes. Once usage hits 100%,/compactis blocked because it requires model inference against that same exhausted quota bucket. When the quota finally refreshes, resuming replays the entire cold history at full uncached input weight (1.00x), burning a huge chunk of the fresh window immediately.ContextHandoffDeliveryto truncate or summarize a massive uncompacted transcript instead of handing off a distilled summary.Proposal (Prioritized by Implementation Order)
Enable pre-quota protection automatically by default per provider instance (
providerInstanceId), requiring zero setup, with two optional overrides under Settings -> Providers -> Advanced (alongside Compact idle threads):Auto (Recommended)|Custom %(any percentage0.1% to 99.9%) |Off.Auto(defaults to100Ktokens or scales with the provider'sautoCompactWindow) |Custom tokens.Priority 1: Per-Instance Dynamic Headroom (
AutoMode)Evaluate quota strictly per provider instance (
providerInstanceId, keeping separate work/personal accounts isolated) using existing cachedusageLimitssnapshots and active thread state:N): Reserve compaction headroom for every active/recent thread above the minimum context threshold on that instance (N * perThreadCompactReserve), weighted by thread token size (272Kvs.1M).overheadMargin): Add a fixed safety margin plus estimated in-flight turn burn and between-poll token deltas so bursty tool loops and conservative polling intervals do not overshoot 100%.effectiveThresholdat~99%for a single serial 5h thread and scaling automatically when multiple heavy threads are active and adjusting for plan size. (params would ideally be tuned eventually)Priority 2: Instance-Scoped Warm-Cache Compaction Sweep
When a provider instance crosses
effectiveThreshold:queueHeld), leaving other accounts/providers unaffected.compactThreadacross eligible open threads above the minimum context threshold while prompt caches are still warm, respecting each provider's native mechanics:Claude)compactThreadandpromptCacheExpiresAt; skips threads whose cache already expired unless fallback handoff is triggered (#17170).Codex)compactThreadacross272Kdefault or1,050KAPI sessions; compacting threads above272Kavoids the 2x long-context input cliff on cold replay.Antigravity)compactwhen advertised (agy1.5+, respecting its~256Kcompaction clamp) and handles post-compaction ACP session rotation cleanly; skips older runtimes lackingcompact.ContextHandoffDelivery(T3CODE_CONTEXT_HANDOFF_TOKEN_CAP) during fallback handoff.Priority 3: Coordinated Reset Recovery or Fallback Handoff (#18949 / #19695 / #38726)
Resume at reset): ArmUsageLimitRecoveryWorkeron swept threads so they resume cheaply from their compact summary once the quota refreshes.Benefits & Limitations
Benefits
272Kthreads and ~810K to 855K+ on1Mthreads, whether running one thread or many.providerInstanceIdwith zero extra quota-endpoint polling.Limitations & Trade-offs
overheadMarginminimize this.< 1.5) cannot be compacted in-place and rely on handoff distillation instead.100Ktokens (default) are skipped.Related Discussions & Issues
usageLimitstracking, pace visibility, and per-account UI rings; this acts automatically on those existing per-instance snapshots.Smallest Useful Scope (MVP)
Autothreshold + overrides: AddAutopre-quota threshold calculation (activeThreadsOnInstance+ safety overhead margin, capped at99%), an unrestrictedCustom %/Offoverride, and a minimum context threshold (100Kdefault) in Settings -> Providers -> Advanced.Resume at reset: Hold new dispatches on the threshold-crossing provider instance, compact eligible open threads above the minimum context threshold while caches are warm, and armResume at reset.Acceptance Criteria
Automode per provider instance using existingusageLimitssnapshots, per-instance active thread count, and safety overhead margin, with an unrestrictedCustom %/Offoverride and minimum context threshold (100Kdefault) in Settings -> Providers -> Advanced.Resume at resetor hand off cleanly into user-configured fallback targets (#18949).All reactions