Overflow recovery only runs after the provider rejects the request, and the cap is never parsed from the error
Short description
Provider cap errors phrased "allows a context of up to 500,000 tokens" match overflow detection but extract no limit (detectedLimit=unknown), so Magic Context folds only after a rejected request has already surfaced an error to the user.
What happened?
A turn that added about 74k tokens of tool output pushed the next request past the provider's plan cap. The provider rejected it and the error appeared in the session. Only then did Magic Context recover: it logged "bumping percentage to 95% due to overflow recovery flag", ran the historian, dropped a large part of the history, and the retry succeeded. The user therefore sees a hard failure for a turn that was recoverable.
The provider message contains both numbers in plain text:
Your plan allows a context of up to 500,000 tokens, this request has an estimated 502,574
(maximum context length exceeded). Shorten the history or start a new session.
Magic Context detects the overflow but extracts neither number; the log records detectedLimit=unknown on both events.
What I expected: either a fold before sending, while the request still fits, or - once the provider has rejected it - the cap read out of the message so the next pass computes pressure against the real limit. The effective threshold here is execute_threshold_percentage: 82 (log: mode=percentage threshold=82%), i.e. 383,760 of the 468,000-token window, and both events happened below it at 77.7% and 65.6%.
What I observed, two consecutive events in one session:
04:34:02 bumping percentage to 95% due to overflow recovery flag (was 77.7%, detectedLimit=unknown)
363,835 -> 49,957 tokens, -313,878
04:59:37 bumping percentage to 95% due to overflow recovery flag (was 65.6%, detectedLimit=unknown)
307,077 -> 104,618 tokens, -202,459
The arithmetic of the rejected request closes exactly:
428,138 provider count of the previous request
+ 74,436 six tool results added in one turn
= 502,574 rejected estimate
Magic Context's own last measurement before that was 363,835, so its percentage stayed at 77.7% while the outgoing request was already over the cap. I cannot attribute the 64,303 gap between 363,835 and 428,138 from the logs alone; one candidate is that the provider counts the system prompt and tool definitions at a different weight than the usage field reports. I am flagging that as an open question rather than a claim.
Why the limit is not extracted, in packages/plugin/src/features/magic-context/overflow-detection.ts: detection works, /context[_ ]length[_ ]exceeded/i (line 43) matches "(maximum context length exceeded)". Extraction fails (lines 69-109): no pattern covers "allows a context of up to N tokens", and every capture is (\d+), which cannot match "500,000" - it would capture 500, and MIN_PLAUSIBLE_LIMIT = 1024 (line 116) discards that. The generic fallback /max(?:imum)?.*context.*?(\d+)/i (line 108) requires a digit after the word "context", and the numbers appear before it. parseReportedInputTokens (lines 361-379) misses "an estimated 502,574" for the same reason.
To repoduse, use a provider whose plan cap is below the model's advertised context window and which phrases the rejection as above with comma-separated numbers, then run a turn that adds more tokens than the remaining headroom (here six file reads of about 12.4k tokens each, 74,436 tokens total). The request is rejected, the error appears in the session, the following pass logs detectedLimit=unknown and recovers, and the retry succeeds.
A fix would normalize thousands separators before parsing and add patterns for this phrasing: /up to ([\d,]+) tokens/i and /allows a context of ([\d,]+) tokens/i for the limit, /estimated ([\d,]+)/i for the rejected input, with , stripped before parseInt. That turns detectedLimit=unknown into a persisted session override, so the threshold is computed against the real cap from then on.
Diagnostics
doctor --report on the reporting machine:
## Environment
- Plugin is outdated: installed 0.49.61, newest 0.49.63.
- magic-context CLI: v0.49.61 (installed plugin: v0.49.61)
- OS: linux x64
- Node: v26.13.1
- OpenCode: opencode v2.3.3
## Configuration
Config from `~/path-4`:
```jsonc
{
"$schema": "https://raw.githubusercontent.com/cortexkit/magic-context/master/assets/magic-context.schema.json",
"enabled": true,
"language": "en",
"prompt_surface": {
"default": "light"
},
"execute_threshold_percentage": {
"default": 82
},
"keep_reasoning_tokens": {
"deepseek-v4.1-flash": 30000,
"muse-spark-1.3-contributor": 30000
},
"sqlite": {
"mmap_size_mb": 256
},
"historian": {
"two_pass": true,
"disallowed_tools": [
"*"
],
"opencode": {
"model": "google/gemini-3.5-flash-lite",
"fallback_models": [
"opencode-go/gpt-5.6-luna",
"opencode-go/mimo-v2.6-pro"
]
}
},
"dreamer": {
"opencode": {
"model": "google/gemini-3.5-flash-lite",
"fallback_models": [
"opencode-go/gpt-5.6-luna",
"opencode-go/mimo-v2.6-pro"
]
}
},
"memory": {
"enabled": true,
"git_commit_indexing": {
"enabled": true
}
}
}
```
## Diagnostics
- Timestamp: 2026-11-19T05:22:00.619Z
- magic-context CLI: v0.49.61
- OS: linux x64
- Node: v26.13.1
- OpenCode installed: true [cli] (opencode v2.3.3)
- OpenCode session database: ~/path-8 (source=default, channel=latest)
- Plugin registered in opencode config: true
- Plugin registered in tui config: false
- magic-context.jsonc parse error: none
- Conflicts detected: none
- MC compaction mode: on
- Native compaction: auto=false, prune=false
### Config paths
```json
{
"configDir": "~/path-2",
"opencodeConfig": "~/path-3",
"opencodeConfigFormat": "jsonc",
"magicContextConfig": "~/path-4",
"tuiConfig": "~/path-5",
"tuiConfigFormat": "none",
"omoConfig": null
}
```
### magic-context.jsonc flags
```jsonc
{
"$schema": "https://raw.githubusercontent.com/cortexkit/magic-context/master/assets/magic-context.schema.json",
"enabled": true,
"language": "en",
"prompt_surface": {
"default": "light"
},
"execute_threshold_percentage": {
"default": 82
},
"keep_reasoning_tokens": {
"deepseek-v4.1-flash": 30000,
"muse-spark-1.3-contributor": 30000
},
"sqlite": {
"mmap_size_mb": 256
},
"historian": {
"two_pass": true,
"disallowed_tools": [
"*"
],
"opencode": {
"model": "google/gemini-3.5-flash-lite",
"fallback_models": [
"opencode-go/gpt-5.6-luna",
"opencode-go/mimo-v2.6-pro"
]
}
},
"dreamer": {
"opencode": {
"model": "google/gemini-3.5-flash-lite",
"fallback_models": [
"opencode-go/gpt-5.6-luna",
"opencode-go/mimo-v2.6-pro"
]
}
},
"memory": {
"enabled": true,
"git_commit_indexing": {
"enabled": true
}
}
}
```
### Plugin cache
```json
{
"path": "~/path-6",
"cached": "0.49.61",
"latest": "0.49.63",
"latest_source": "npm",
"installs": [
{
"layout": "opencode2",
"spec": "latest",
"path": "~/path-6",
"cached": "0.49.61"
}
]
}
```
### Storage
- Warning: Magic Context storage is at ~/path-7, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.
```json
{
"path": "~/path-7",
"source": "<text omitted>",
"exists": true,
"context_db_size": "490.6 MB"
}
```
### Recent sessions
Recent sessions: unavailable (SQLITE_ERROR: <text omitted>)
### Historian dumps
(Metadata only — XML content is not included in this report.)
`sessionDumps` lists the per-session directories under `<temp dir>/opencode/magic-context/historian/` that current plugins write to. `byProject` lists dumps that plugins up to 0.49.57 wrote under `<project>/.cortexkit/magic-context/historian/`, and `legacyDumps` those from plugins before 0.18.
```json
{
"sessionDumps": {
"dir": "path-14",
"count": 0,
"sessionCount": 0,
"sessions": []
},
"byProject": [],
"legacyDumps": {
"dir": "path-14",
"count": 0,
"recent": []
}
}
```
### Historian failures (session_meta)
_Note: this counter RESETS to 0 on every successful run — see 'Historian runs' below for the durable history._
_No sessions with historian failures._
### Historian runs (durable telemetry)
Per-session success/failure/no-op counts from `historian_runs` (never reset).
```json
[
{
"sessionId": "session-1",
"total": 12,
"success": 12,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-19T04:59:44.688Z"
},
{
"sessionId": "session-2",
"total": 10,
"success": 10,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-18T15:42:10.093Z"
},
{
"sessionId": "session-3",
"total": 26,
"success": 26,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-18T14:14:52.614Z"
},
{
"sessionId": "session-4",
"total": 3,
"success": 3,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-16T22:28:26.447Z"
},
{
"sessionId": "session-5",
"total": 1,
"success": 1,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-15T20:30:18.524Z"
},
{
"sessionId": "session-6",
"total": 7,
"success": 7,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-14T22:18:53.655Z"
},
{
"sessionId": "session-7",
"total": 4,
"success": 4,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-14T03:18:58.747Z"
},
{
"sessionId": "session-8",
"total": 3,
"success": 3,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-13T18:28:33.235Z"
},
{
"sessionId": "session-9",
"total": 11,
"success": 11,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-13T16:19:42.963Z"
},
{
"sessionId": "session-10",
"total": 1,
"success": 1,
"failed": 0,
"noop": 0,
"lastFailureReason": "",
"lastRunAt": "2026-11-11T23:41:19.443Z"
}
]
```
### Log files
- path-9: exists=true, grammar=legacy, lines=27290, size=7275 KB
- ~/path-10: exists=false, grammar=unknown, lines=0, size=0 KB
- ~/path-11: exists=false, grammar=unknown, lines=0, size=0 KB
- path-12: exists=true, grammar=unknown, lines=13, size=1 KB
- ~/path-13: exists=false, grammar=unknown, lines=0, size=0 KB
## Historian failure signals (log, sanitized)
_No historian failure log lines found in recent history._
## Recent errors (last 20, sanitized)
```
LOG magic-context <text omitted>
LOG magic-context <text omitted> ~/path-17
LOG magic-context <text omitted>
LOG magic-context <text omitted>
2026-11-19T04:58:29.215Z LOG magic-context [magic-context] embedding worker failed: <text omitted>
LOG magic-context <text omitted>
LOG magic-context <text omitted> ~/path-18
LOG magic-context <text omitted>
LOG magic-context <text omitted> ~/path-19
```
Plugin version
0.49.61
OpenCode version
2.3.2
Platform
linux x64
Client
OpenCode TUI (CLI)
Log output (optional)
[2026-11-19T04:32:25.218Z] [magic-context][ses_...] transform: unknown provider usage; using wire estimate for priced pass inputTokens=359430 percentage=76.8 trusted=true wireTokens=718860 pressureTokens=359430
[2026-11-19T04:34:02.730Z] [magic-context][ses_...] transform: bumping percentage to 95% due to overflow recovery flag (was 77.7%, detectedLimit=unknown)
[2026-11-19T04:34:12.955Z] [magic-context][ses_...] transform: recovery request admitted: about 49957 tokens, within 468000 of 468000; provider_overflow recovery ends
[2026-11-19T04:59:37.397Z] [magic-context][ses_...] transform: bumping percentage to 95% due to overflow recovery flag (was 65.6%, detectedLimit=unknown)
[2026-11-19T04:59:44.752Z] [magic-context][ses_...] transform: recovery chain done: the request is about 104594 tokens, under the 95% line 444600 (0 chained runs)
[2026-11-19T04:59:45.074Z] [magic-context][ses_...] transform: recovery request admitted: about 104618 tokens, within 468000 of 468000; provider_overflow recovery ends
Related: #859 added patterns to the same file for a different provider wording. #231 shows that Magic Context sets detected_context_limit only after a provider overflow.
Thanks for the precise report. You're right about the cause.
overflow-detection.ts recognises the rejection, but none of its limit patterns covers "allows a context of up to N tokens", and every capture reads plain digits, so "500,000" can never become a limit. With no limit extracted, the session never learns the real cap. Its pressure is still measured against the model's advertised window, and the next turn that crosses 500,000 fails the same way.
The fix, now being built for the next 0.49 patch:
- one number parser for every pattern that accepts grouped digits (
500,000,500 000,1_048_576) and refuses anything ambiguous; - patterns for this wording, for both the cap and the rejected request's size, always taking the "up to" number as the limit;
- a test through the real recovery path that the parsed cap is saved for the session, so later passes compute pressure against 500,000.
On folding before the first rejection: Magic Context can't know that a plan caps context below the model's window until the provider says so once. After this fix, that happens once per session instead of on every overflow.
On the 64k gap between the wire estimate (363,835) and the provider's count (428,138): we're tracing where that estimate comes from, and I'll report back here.
Fixed in v0.49.64, now on npm. Thanks @tobwen for the report and the diagnosis.
Every limit and request-size pattern now reads grouped numbers (500,000, 500 000, 1_048_576) and refuses ambiguous ones, and the "Your plan allows a context of up to N tokens" wording is recognised. Magic Context saves that cap for the session, so later turns measure pressure against the real limit instead of failing again each time the session grows past it.
Update the plugin and restart OpenCode or Pi. If the cap still isn't picked up, please reopen with the provider's exact error line.
@magic-alfonso @alfonso-magic-context @ualtinok
I guess this belongs here. An OpenAI-compatible provider refuses a request with HTTP 413:
code: cold_request_too_large
"This request adds about 383,000 new tokens to the session at once (limit 350,000 per request). Please shorten the new context or split it across several requests."
None of the 25 OVERFLOW_PATTERNS matches that message, and detection is message-only (no status- or code-based rule). detected_context_limit and needs_emergency_recovery stayed 0, no transform ran, and the same refusal repeated.
The limit is a per-request delta, not the context window: the provider lets a session grow past 350k in total. That suggests a cold-request signal rather than a lower detected_context_limit.
@tobwen you are right, and first an apology: your comment of 24 November sat unanswered because the issue was closed and I did not pick it up. Reopening.
I checked both wordings against the current code (0.49.90, overflow-detection.ts):
- Detection is by message text only. The list has 25 wordings, and neither "this request adds about N new tokens to the session at once (limit N per request)" nor "this request is too large to start a new session (limit N)" matches any of them.
- There is an HTTP 413 rule, but it also reads the message: it needs the digits
413in the text together with one of "entity", "payload", "context" or "prompt". Your message has none of them, and the status and thecodefield are not consulted for this decision. - So nothing is recorded: no detected limit, no recovery armed, and the next request is refused the same way. That matches what you saw.
This is separate from what the earlier fix in this issue covered (reading the cap from an error that is recognised). Here the error is not recognised at all.
One question, because it decides what the right handling is. You wrote that the 350,000 cap is per request and that a session can exceed it in total. Do you know, from the provider's documentation or from your logs, which requests it applies to? For example: every request whose prefix the provider has not cached ("cold"), which would include the first request after an idle period and the first after any change early in the conversation. If that is the rule, then a session above 350,000 tokens is one cache miss away from a refusal it cannot get out of, and the cap would have to be treated as the session's ceiling in practice. If you have a provider document that states it, a link would help.
We are reproducing both of your error bodies (status 413, type: invalid_request_error, code: cold_request_too_large, each wording) against a real OpenCode host with a mock provider now. Thank you for the offer to run a patch build against your session; I will take you up on it once there is one. No promise on the exact behaviour until the reproduction is in.
Released in 0.49.92. A provider's per-request limit on new tokens (HTTP 413 with cold_request_too_large, or a message such as "limit 350,000 per request") is now read as a size rejection: Magic Context makes room and the next attempt goes through. The limit it reports is kept for the session and used as the session's input limit while it is below the model's own window, so the session is reduced before it reaches that size again. A bare HTTP 413 with no such code or message is not treated as a size rejection.
Update with npx @cortexkit/magic-context@latest doctor, then restart the host. No database migration.
I am leaving this open for a few days. If you still see the rejection repeat on 0.49.92, the lines around it from doctor --issue would show which part did not apply.