graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(context): overflow classifier gets non-overflow guards + two behavioral detectors (#414)
Rach Pradhan5d862f6e0cba
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b2f8415b..48ab460d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,24 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.-## v0.0.240 (unreleased)+## v0.0.241 (unreleased)++- Context-overflow classification got a guard list and two behavioral+ detectors (#414). Non-overflow patterns are now checked FIRST, so a+ throttle whose wording collides with an overflow phrase — Bedrock's+ `ThrottlingException: Too many tokens` is the canonical one — keeps riding+ the Retry-After ladder instead of triggering a compaction that cannot help.+ The overflow table itself grew from six substrings to the phrasings twelve+ more providers actually send (Bedrock, Gemini, Copilot, xAI, Groq,+ llama.cpp, Kimi, Mistral, Ollama, MiniMax, z.ai, Anthropic 413), and now+ matches case-insensitively. Two shapes that never send an error at all are+ caught from the reported usage instead: an HTTP 200 with an empty+ completion whose input is at or over the window (z.ai's silent overflow),+ and `finish_reason: length` with zero output while the input fills the+ window (a provider truncating the input to fit, seen on MiMo) — the latter+ is now named rather than shipped as an inexplicably short answer.++## v0.0.240 (2026-08-06)- The REPL/engine separation began (#422): agent output now flows through atyped event vocabulary and a strict sink boundary (`engine_events.zig` /diff --git a/scripts/test-pty-overflow.py b/scripts/test-pty-overflow.pyindex aed058d3..89968921 100644--- a/scripts/test-pty-overflow.py+++ b/scripts/test-pty-overflow.py@@ -14,6 +14,17 @@ precise:B. error.code = rate_limit_exceeded with a non-overflow message. graff must NOTmistake it for an overflow: the meter must not pin. Proves detection is precise.+#414 adds three more, covering the classifier's guard list and its two behavioral+detectors — the shapes where the provider never returns an error at all:++ C. Bedrock's "ThrottlingException: Too many tokens, please wait before trying+ again." — wording that collides with the generic "too many tokens" overflow+ fallback, but is a 429. It must ride the retry ladder; the meter must not pin.+ D. HTTP 200 with an EMPTY completion whose usage reports input at the window+ (the z.ai silent overflow). graff must classify it as overflow anyway.+ E. HTTP 200 with finish_reason=length and ZERO output at the window (MiMo+ truncating our input to fit). graff must name it, not ship a silent short answer.+Requires 127.0.0.1:1234 to be free (the lmstudio provider URL is fixed); skips if areal LM Studio (or anything) already holds it."""@@ -37,12 +48,23 @@ GRAFF = os.path.abspath(_arg) if os.sep in _arg else _argMETER_RE = re.compile(r"(\d+)k/(\d+)k ctx \((\d+)% · compact@(\d+)k\)")PINNED_RE = re.compile(r"(\d+)k/(\d+)k ctx \(100% · compact@\d+k\)")+# lmstudio/lmstudio is a CATALOGUED model (pricing.zig context_overlay), so its+# window is fixed at 200k and GRAFF_CONTEXT deliberately cannot shrink it (#203).+# The #414 behavioral fixtures report usage against this number; scenario D+# asserts the meter still reads it, so a catalog change fails loudly here.+LMSTUDIO_WINDOW = 200_000+class OpenAiErrorMock:- """Serves one fixed OpenAI-style error envelope for every /v1/chat/completions."""+ """Serves one fixed OpenAI-style body for every /v1/chat/completions.++ `error_obj` is wrapped as {"error": ...}; pass a `raw` body instead to serve a+ successful (HTTP 200) completion, which is how the #414 behavioral shapes are+ reproduced — they never send an error to keyword-match.+ """- def __init__(self, error_obj: dict) -> None:- self.body = json.dumps({"error": error_obj}).encode()+ def __init__(self, error_obj: dict | None = None, raw: dict | None = None) -> None:+ self.body = json.dumps(raw if raw is not None else {"error": error_obj}).encode()self.hits = 0parent = self@@ -75,9 +97,14 @@ class OpenAiErrorMock:self.httpd.server_close()-def _run(error_obj: dict, tmp: str):- """Run one turn against a mock returning error_obj; return (rendered_text, hits)."""- mock = OpenAiErrorMock(error_obj)+def _run(error_obj: dict, tmp: str, *, raw: dict | None = None, wait_for: str = "api error:"):+ """Run one turn against a mock; return (rendered_text, hits).++ `wait_for` is the literal that marks the turn as finished — an error turn ends+ with "api error:", but a #414 behavioral-overflow turn ends with a normal+ (empty) completion and is only visible through its own notice.+ """+ mock = OpenAiErrorMock(error_obj, raw=raw)mock.start()try:env = {@@ -102,8 +129,7 @@ def _run(error_obj: dict, tmp: str):session.wait_for_literal("] ›")cursor = len(session.raw)session.send_line("hello")- # The turn ends with an api error either way; wait for it, then settle.- session.wait_for_literal("api error:", start=cursor)+ session.wait_for_literal(wait_for, start=cursor)session.pump_for(1.5)rendered = terminal_text(bytes(session.raw[cursor:]))@@ -181,6 +207,67 @@ def main() -> None:)print("ok non-overflow error did not pin the meter (detection is precise)")+ # Scenario C (#414 guard): Bedrock's throttle wording collides head-on with+ # the generic "too many tokens" overflow fallback. It is a 429: it must ride+ # the retry ladder, never trigger a compaction.+ rendered, _ = _run(+ {+ "message": "ThrottlingException: Too many tokens, please wait before trying again.",+ "type": "throttling_error",+ },+ tmp,+ )+ if "Too many tokens" not in rendered:+ raise AssertionError(f"C: throttle error was not surfaced:\n{rendered}")+ stray = PINNED_RE.search(rendered)+ if stray:+ raise AssertionError(+ "C: a Bedrock THROTTLE was classified as context overflow — the "+ f"non-overflow guard list is not being consulted first ({stray.group(0)!r}):\n{rendered}"+ )+ print("ok bedrock 'Too many tokens' throttle stayed on the retry path (#414 guard)")++ # Scenario D (#414): z.ai's silent overflow. HTTP 200, an EMPTY completion,+ # and usage that says the input already filled the window. Nothing in the+ # body is an error, so only the behavioral detector can catch it.+ rendered, hits = _run(+ {},+ tmp,+ raw={+ "choices": [{"index": 0, "message": {"role": "assistant", "content": ""}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": LMSTUDIO_WINDOW, "completion_tokens": 0, "total_tokens": LMSTUDIO_WINDOW},+ },+ wait_for="silent_overflow",+ )+ if hits < 1:+ raise AssertionError("D: graff never reached the backend")+ if "silent_overflow" not in rendered:+ raise AssertionError(+ f"D: an HTTP 200 with no answer and over-window usage was accepted silently:\n{rendered}"+ )+ pinned = PINNED_RE.search(rendered)+ if not pinned:+ raise AssertionError(f"D: silent overflow did not pin the meter to the window:\n{rendered}")+ if pinned.group(2) != str(LMSTUDIO_WINDOW // 1000):+ raise AssertionError(f"D: lmstudio's catalogued window moved; update LMSTUDIO_WINDOW ({pinned.group(0)!r})")+ print("ok silent 200 (empty completion, usage at the window) classified as overflow (#414)")++ # Scenario E (#414): MiMo truncates an oversized input to fit the window,+ # then reports finish_reason=length with zero output. The reply is not a+ # real answer and must be named as such, not shipped as a short one.+ rendered, _ = _run(+ {},+ tmp,+ raw={+ "choices": [{"index": 0, "message": {"role": "assistant", "content": ""}, "finish_reason": "length"}],+ "usage": {"prompt_tokens": LMSTUDIO_WINDOW, "completion_tokens": 0, "total_tokens": LMSTUDIO_WINDOW},+ },+ wait_for="upstream_truncation",+ )+ if "upstream_truncation" not in rendered:+ raise AssertionError(f"E: upstream truncation surfaced as a silent short answer:\n{rendered}")+ print("ok finish_reason=length with zero output at the wall reported as truncation (#414)")+if __name__ == "__main__":main()diff --git a/src/agent_overflow.zig b/src/agent_overflow.zignew file mode 100644index 00000000..144ce5c9--- /dev/null+++ b/src/agent_overflow.zig@@ -0,0 +1,512 @@+//! Context-overflow classification and the recovery it drives (#193 arc, #414).+//!+//! Three questions, asked in this order:+//! 1. is this failure something OTHER than an over-window input — throttling,+//! a billing cap? A guard hit wins outright, so the retry/Retry-After+//! ladder is never shadowed by a compaction that cannot help.+//! 2. does the failure's structured code or wording name an over-window input?+//! 3. did the provider ACCEPT the oversized input and admit it only in its own+//! usage numbers — HTTP 200 with nothing generated — rather than in an error?+//!+//! (1) and (2) are `isContextOverflow`; (3) is `classifyCompletion`. The recovery+//! all three feed (pin the meter to the window, emergency-trim, retry the turn+//! once) is `applyOverflowRecovery`, shared by every wire format.++const std = @import("std");+const Value = std.json.Value;++const Agent = @import("agent.zig").Agent;+const Provider = @import("provider.zig").Provider;+const telemetry = @import("telemetry.zig");+const util = @import("util.zig");+const usageInt = @import("agent_context.zig").usageInt;++/// Non-overflow guards, tested BEFORE every overflow pattern and against both+/// the message and the structured code.+///+/// The motivating case is Bedrock, which formats throttling as+/// "ThrottlingException: Too many tokens, please wait before trying again." —+/// a 429 whose wording collides head-on with the generic "too many tokens"+/// overflow fallback below. Classifying that as overflow throws away real+/// conversation to fix a problem compaction cannot fix, AND shadows the+/// Retry-After backoff that would have worked.+///+/// Deliberately scoped to throttling / quota — the family whose remedy is+/// "wait", not "send less". Broader guards (a bare "overloaded", a generic+/// "server_error") were considered and rejected: a guard that swallows a REAL+/// overflow wedges the session forever, which is the #193 symptom and strictly+/// worse than one wasted compaction.+const non_overflow_needles = [_][]const u8{+ "throttlingexception", // bedrock: "ThrottlingException: Too many tokens, ..."+ "throttling error", // bedrock, formatBedrockError's human-readable prefix+ "throttled",+ "rate limit", // "rate limit exceeded", "Rate limit reached", "rate limited (429)"+ "rate_limit", // structured codes: rate_limit_exceeded / rate_limit_error+ "ratelimit",+ "too many requests", // generic HTTP 429 phrasing+ "tokens per minute", // anthropic org cap: "rate limit of 40000 input tokens per minute"+ "requests per minute",+ "please wait before trying again", // bedrock's throttle tail, verbatim+ "quota", // insufficient_quota / "exceeded your current quota" — isQuotaExceeded owns it+ "service unavailable",+};++/// Structured error codes that mean "input over the window" on their own (#203),+/// matched exactly so a local or non-English provider recovers even when its+/// message text is unfamiliar.+const overflow_codes = [_][]const u8{+ "context_length_exceeded", // openai+ "context_window_exceeded", // openai / responses+ "model_context_window_exceeded", // z.ai+ "request_too_large", // anthropic 413 (byte size, not token count)+};++/// Provider phrasings for "input over the window", matched case-insensitively —+/// the same rejection arrives Title-Cased from some gateways and lower-cased+/// from others, and a case-sensitive miss wedges the session.+const overflow_needles = [_][]const u8{+ // #193/#203, unchanged: the shapes graff already recovered from.+ "context window", // codex/responses: "exceeds the context window"+ "context length", // openai: "maximum context length is N tokens"; lmstudio+ "context_length_exceeded", // openai error code echoed into the message+ "context limit", // anthropic: "input length and max_tokens exceed context limit"+ "prompt is too long", // anthropic: "prompt is too long: N tokens > M maximum"+ "maximum context", // defensive: "maximum context ... exceeded"+ // #414: providers graff ships that phrase it differently. Each one is a+ // rejection the old table let die as a plain api error.+ "context_window_exceeded",+ "request_too_large", // anthropic 413+ "input is too long for requested model", // bedrock+ "input token count", // google: "The input token count (N) exceeds the maximum ..."+ "prompt token count", // github copilot: "prompt token count of N exceeds the limit of M"+ "maximum prompt length", // xai: "This model's maximum prompt length is N ..."+ "reduce the length of the messages", // groq+ "exceeds the available context size", // llama.cpp server+ "exceeded model token limit", // kimi for coding+ "too large for model with", // mistral: "... too large for model with N maximum context length"+ "prompt too long", // ollama: "prompt too long; exceeded max context length"+ // Generic fallbacks. These are the reason the guard list above exists: they+ // are broad enough to catch an unknown provider and broad enough to collide+ // with throttling, so they are only ever reached after the guards decline.+ "too many tokens",+ "token limit exceeded",+};++/// True if `msg`/`code` is a NON-overflow condition — throttling or a billing+/// cap — whose remedy is waiting, not compacting.+pub fn isNonOverflow(msg: []const u8, code: ?[]const u8) bool {+ for (non_overflow_needles) |n| {+ if (util.indexOfIgnoreCase(msg, n) != null) return true;+ if (code) |c| if (util.indexOfIgnoreCase(c, n) != null) return true;+ }+ return false;+}++/// True if `msg` is a provider's "input is over the context window" rejection,+/// across wire formats: codex/responses ("exceeds the context window"), openai+/// ("maximum context length", "context_length_exceeded"), anthropic ("prompt is+/// too long", "exceed context limit"), plus the #414 table above. Drives the+/// in-turn emergency-trim + retry recovery symmetrically for every provider+/// (#193) — before it, only the codex path recovered and anthropic/openai died+/// on an over-window turn.+pub fn isContextOverflow(msg: []const u8, code: ?[]const u8) bool {+ // #414: guards first, unconditionally. A throttle whose wording overlaps an+ // overflow pattern must ride the existing 429/Retry-After ladder instead.+ if (isNonOverflow(msg, code)) return false;+ if (code) |c| {+ for (overflow_codes) |k| if (std.ascii.eqlIgnoreCase(c, k)) return true;+ }+ for (overflow_needles) |n| if (util.indexOfIgnoreCase(msg, n) != null) return true;+ return false;+}++/// How the provider says it stopped, normalized across wire formats.+pub const StopKind = enum {+ normal, // end_turn / stop_sequence / stop+ length, // finish_reason "length" / stop_reason "max_tokens"+ other, // anything else, including "not reported"+};++/// One completed HTTP 200 response, reduced to the four numbers that decide+/// whether the provider silently overflowed.+pub const Completion = struct {+ /// Everything that occupied the window: prompt + cache reads + cache writes.+ input_tokens: u64 = 0,+ output_tokens: u64 = 0,+ stop: StopKind = .other,+ /// Any assistant text or any tool call — i.e. the turn produced something.+ has_content: bool = false,+};++pub const Verdict = enum {+ ok,+ /// z.ai: HTTP 200, nothing generated, usage says the input already filled+ /// (or overran) the window. The provider accepted an over-window request+ /// and answered with silence instead of an error.+ silent_overflow,+ /// Xiaomi MiMo: the server truncated an oversized input to exactly fit the+ /// window, leaving no room to generate, then reported finish_reason=length+ /// with zero output. The conversation the model saw is NOT the one we sent.+ upstream_truncation,+};++/// Percent of the window the reported input must fill before a `length` stop+/// counts as upstream truncation. 99 (not 100) because a provider's own+/// tokenizer rounds a few tokens differently than its advertised window, and a+/// server that truncates-to-fit lands one or two tokens short of the wall.+pub const truncation_fill_pct: u64 = 99;++/// Classify a successful (HTTP 200) response from its own reported usage.+///+/// Conservative by construction — three independent conditions must hold before+/// `upstream_truncation` fires, so an ORDINARY max-tokens completion (the model+/// genuinely wrote until it hit its output cap) can never trip it:+/// * `output_tokens == 0` — a normal length-stop spends its whole output+/// budget, so any generated token at all disqualifies it;+/// * `has_content == false` — and it leaves that text behind;+/// * the reported input fills >= 99% of the window — a normal length-stop+/// happens at any input size, including a two-line prompt.+/// `silent_overflow` needs an empty completion too: if the input is over our+/// window figure and the model STILL answered, the window figure is wrong (a+/// stale catalog row), and trimming real history over a bad constant is the+/// more expensive mistake.+pub fn classifyCompletion(c: Completion, window: u64) Verdict {+ if (window == 0) return .ok; // unknown window — never guess+ if (c.input_tokens == 0) return .ok; // no usage reported — nothing to judge+ if (c.has_content) return .ok;+ // Checked before the plain over-window rule so the more specific diagnosis+ // wins when a truncating provider lands exactly ON the window.+ if (c.stop == .length and c.output_tokens == 0 and+ c.input_tokens >= window / 100 * truncation_fill_pct) return .upstream_truncation;+ if (c.input_tokens >= window) return .silent_overflow;+ return .ok;+}++fn stopFromString(kind: Provider.Kind, s: []const u8) StopKind {+ if (std.mem.eql(u8, s, "length") or std.mem.eql(u8, s, "max_tokens")) return .length;+ return switch (kind) {+ .anthropic => if (std.mem.eql(u8, s, "end_turn") or std.mem.eql(u8, s, "stop_sequence")) .normal else .other,+ else => if (std.mem.eql(u8, s, "stop")) .normal else .other,+ };+}++fn str(obj: std.json.ObjectMap, name: []const u8) ?[]const u8 {+ const v = obj.get(name) orelse return null;+ return if (v == .string) v.string else null;+}++fn arr(obj: std.json.ObjectMap, name: []const u8) ?std.json.Array {+ const v = obj.get(name) orelse return null;+ return if (v == .array) v.array else null;+}++fn usageOf(root: std.json.ObjectMap) ?std.json.ObjectMap {+ const v = root.get("usage") orelse return null;+ return if (v == .object) v.object else null;+}++fn nonNegative(n: i64) u64 {+ return if (n > 0) @intCast(n) else 0;+}++/// Reduce a parsed 200 response to the numbers `classifyCompletion` needs.+/// Everything is optional: a provider that reports no usage yields+/// `input_tokens == 0`, which classifies as `.ok`.+pub fn readCompletion(kind: Provider.Kind, root: std.json.ObjectMap) Completion {+ var c: Completion = .{};+ return switch (kind) {+ .anthropic => {+ if (usageOf(root)) |u| {+ c.input_tokens = nonNegative(usageInt(u, "input_tokens") +|+ usageInt(u, "cache_read_input_tokens") +| usageInt(u, "cache_creation_input_tokens"));+ c.output_tokens = nonNegative(usageInt(u, "output_tokens"));+ }+ if (str(root, "stop_reason")) |s| c.stop = stopFromString(kind, s);+ if (arr(root, "content")) |blocks| for (blocks.items) |b| {+ if (b != .object) continue;+ const bt = str(b.object, "type") orelse continue;+ if (std.mem.eql(u8, bt, "tool_use")) c.has_content = true;+ if (std.mem.eql(u8, bt, "text")) {+ if (str(b.object, "text")) |t| if (t.len > 0) {+ c.has_content = true;+ };+ }+ };+ return c;+ },+ .openai => {+ if (usageOf(root)) |u| {+ // prompt_tokens already includes cached prompt tokens.+ c.input_tokens = nonNegative(usageInt(u, "prompt_tokens"));+ c.output_tokens = nonNegative(usageInt(u, "completion_tokens"));+ }+ const choices = arr(root, "choices") orelse return c;+ if (choices.items.len == 0 or choices.items[0] != .object) return c;+ const choice = choices.items[0].object;+ if (str(choice, "finish_reason")) |s| c.stop = stopFromString(kind, s);+ const message = choice.get("message") orelse return c;+ if (message != .object) return c;+ if (str(message.object, "content")) |t| if (t.len > 0) {+ c.has_content = true;+ };+ if (arr(message.object, "tool_calls")) |tc| if (tc.items.len > 0) {+ c.has_content = true;+ };+ return c;+ },+ .responses => {+ if (usageOf(root)) |u| {+ // Responses usage.input_tokens already includes cached input.+ c.input_tokens = nonNegative(usageInt(u, "input_tokens"));+ c.output_tokens = nonNegative(usageInt(u, "output_tokens"));+ }+ // parseResponses collapses every terminal to output items + an+ // `incomplete` flag, so there is no finish_reason to read: leave+ // `stop` at .other and let only the silent-overflow rule apply.+ if (arr(root, "output")) |items| for (items.items) |item| {+ if (item != .object) continue;+ const it = str(item.object, "type") orelse continue;+ if (std.mem.eql(u8, it, "function_call") or std.mem.eql(u8, it, "custom_tool_call")) c.has_content = true;+ if (!std.mem.eql(u8, it, "message")) continue;+ const blocks = arr(item.object, "content") orelse continue;+ for (blocks.items) |b| {+ if (b != .object) continue;+ if (str(b.object, "text")) |t| if (t.len > 0) {+ c.has_content = true;+ };+ }+ };+ return c;+ },+ };+}++/// Pin the meter to the window, emergency-trim, and retry the turn once.+///+/// Pins FIRST so the between-turns compaction engages even when we cannot+/// recover here — a rejected request returns no usage to correct the lagging+/// meter (#174). Guarded by `retried` (one `context_retried` per request) so a+/// second overflow falls through instead of looping. Returns true if the caller+/// should `continue` its rebuild loop.+fn applyOverflowRecovery(self: *Agent, retried: *bool) bool {+ self.last_request_context_overflow = true;+ // Rejection proves at least the advertised window, not an exact total.+ // Preserve stronger server/local evidence already above that floor.+ const estimate = self.contextEstimate();+ self.last_context_tokens = @max(estimate.effective, self.provider.context);+ self.context_local_tokens = estimate.local;+ // compact() marks its synthetic summary request explicitly. Generic+ // in-request recovery is destructive there: the synthetic compact+ // instruction is the newest clean user turn, so emergencyTrim can discard+ // the entire real conversation and retry with only "summarize it". Let the+ // outer compactOrRecover policy handle a failed summary after compact()'s+ // errdefer removes that synthetic instruction.+ if (self.compaction_request) return false;+ if (retried.* or self.emergencyTrim() == 0) return false;+ retried.* = true;+ if (self.tracer) |tr| tr.note("context", "input over the window — emergency-trimmed and retrying the turn");+ return true;+}++/// #193 follow-up: shared in-turn context-overflow recovery for the codex+/// failure branch and the three anthropic/openai error branches (streamed error+/// event, non-streamed `{"type":"error"}` envelope, and the generic+/// apiErrorMessage path). These wire formats send the full input each rebuild,+/// so — unlike the codex branch — no closeCodexWs re-anchor is needed.+pub fn recoverContextOverflow(self: *Agent, msg: []const u8, code: ?[]const u8, retried: *bool) bool {+ if (!isContextOverflow(msg, code)) return false;+ return applyOverflowRecovery(self, retried);+}++/// #414: the provider returned HTTP 200 and no answer, and only its own usage+/// numbers say why. Runs on every successful response, after recordUsage* has+/// already banked the sample. Compaction requests are excluded: an empty+/// summary is compact()'s own escalation (#379), and recovering here would+/// trim against the synthetic instruction.+///+/// Both verdicts surface DISTINCTLY — a line, a trace note, a telemetry event —+/// rather than reaching the user as an inexplicably short answer, and both then+/// take the ordinary overflow recovery. When recovery is unavailable (already+/// retried this request, or nothing left to trim) the reason is recorded as+/// `last_api_error` so a subagent's parent and the --json error event carry it.+pub fn recoverBehavioralOverflow(self: *Agent, root: std.json.ObjectMap, retried: *bool) bool {+ if (self.compaction_request) return false;+ const c = readCompletion(self.provider.kind, root);+ const window = self.provider.context;+ const verdict = classifyCompletion(c, window);+ if (verdict == .ok) return false;+ const kind: []const u8 = if (verdict == .silent_overflow) "silent_overflow" else "upstream_truncation";+ const what: []const u8 = if (verdict == .silent_overflow)+ "returned no answer while reporting"+ else+ "truncated the input to fit the window and had no room left to answer:";+ self.say("[{s}: {s} {s} {d} input tokens against a {d}-token window — compacting and retrying (#414)]\n", .{+ kind, self.provider.id, what, c.input_tokens, window,+ }) catch {};+ if (self.tracer) |tr| tr.note("context", kind);+ if (telemetry.g_telem) |t| t.errorEvent(kind, self.provider.id);+ const recovered = applyOverflowRecovery(self, retried);+ if (!recovered) self.last_api_error = std.fmt.allocPrint(+ self.arena,+ "{s}: {s} accepted {d} input tokens against a {d}-token window and produced no output — the reply is not a real answer",+ .{ kind, self.provider.id, c.input_tokens, window },+ ) catch null;+ return recovered;+}++const ClassifyRow = struct {+ msg: []const u8,+ code: ?[]const u8 = null,+ want: bool,+ why: []const u8,+};++test "isContextOverflow (#193/#203/#414): guards beat patterns; every provider phrasing still classifies" {+ const rows = [_]ClassifyRow{+ // ---- #414 guards: real throttle/quota strings that must ride the retry ladder+ .{ .msg = "ThrottlingException: Too many tokens, please wait before trying again.", .want = false, .why = "bedrock throttle collides with the generic 'too many tokens' fallback" },+ .{ .msg = "Throttling error: Too many tokens, please wait before trying again.", .want = false, .why = "bedrock formatBedrockError prefix" },+ .{ .msg = "Rate limit reached for gpt-4o: Limit 30000 tokens per minute", .code = "rate_limit_exceeded", .want = false, .why = "openai TPM cap" },+ .{ .msg = "This request would exceed your organization's rate limit of 40000 input tokens per minute.", .want = false, .why = "anthropic org TPM cap" },+ .{ .msg = "429 too many requests", .want = false, .why = "generic 429" },+ .{ .msg = "rate limited (429): quota/billing cap — You exceeded your current quota", .want = false, .why = "graff's own quota-cap marker must not compact" },+ .{ .msg = "Service unavailable: the model is starting up", .want = false, .why = "5xx, not a window" },+ .{ .msg = "de invoerlengte is te groot", .code = "rate_limit_error", .want = false, .why = "guard applies to the structured code too" },+ // A guard must NOT swallow a real overflow that merely mentions a limit.+ .{ .msg = "prompt is too long: 219373 tokens > 200000 maximum", .code = "rate_limit_exceeded", .want = false, .why = "documented precedence: guards win outright, even over an explicit overflow phrase" },+ // ---- regression rows: everything #193/#203 already classified, unchanged+ .{ .msg = "Your input exceeds the context window of 272000 tokens", .want = true, .why = "codex/responses" },+ .{ .msg = "This model's maximum context length is 128000 tokens. However, you requested 130000", .want = true, .why = "openai" },+ .{ .msg = "context_length_exceeded", .want = true, .why = "openai code echoed into the message" },+ .{ .msg = "prompt is too long: 219373 tokens > 200000 maximum", .want = true, .why = "anthropic" },+ .{ .msg = "input length and max_tokens exceed context limit", .want = true, .why = "anthropic" },+ .{ .msg = "de invoerlengte overschrijdt het venster", .code = "context_length_exceeded", .want = true, .why = "#203 structured code, unfamiliar text" },+ .{ .msg = "", .code = "context_window_exceeded", .want = true, .why = "#203 structured code, empty text" },+ .{ .msg = "maximum context reached", .want = true, .why = "defensive needle" },+ .{ .msg = "The API Key appears to be invalid or may have expired.", .want = false, .why = "auth" },+ .{ .msg = "tool_choice is not supported", .want = false, .why = "capability" },+ .{ .msg = "rate limit exceeded", .want = false, .why = "throttle" },+ .{ .msg = "model not found", .want = false, .why = "routing" },+ .{ .msg = "some unrelated failure", .code = "rate_limit_exceeded", .want = false, .why = "unrelated code" },+ // ---- #414 provider phrasings the old six-needle table let die as api errors+ .{ .msg = "Input is too long for requested model.", .want = true, .why = "bedrock" },+ .{ .msg = "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)", .want = true, .why = "google gemini" },+ .{ .msg = "prompt token count of 141000 exceeds the limit of 128000", .want = true, .why = "github copilot" },+ .{ .msg = "This model's maximum prompt length is 131072 but the request contains 537812 tokens", .want = true, .why = "xai/grok" },+ .{ .msg = "Please reduce the length of the messages or completion.", .want = true, .why = "groq" },+ .{ .msg = "the request exceeds the available context size, try increasing it", .want = true, .why = "llama.cpp" },+ .{ .msg = "Your request exceeded model token limit: 262144 (requested: 300000)", .want = true, .why = "kimi for coding" },+ .{ .msg = "Prompt contains 40000 tokens, too large for model with 32768 maximum context length", .want = true, .why = "mistral" },+ .{ .msg = "prompt too long; exceeded max context length by 4096 tokens", .want = true, .why = "ollama" },+ .{ .msg = "tokens to keep from the initial prompt is greater than the context length", .want = true, .why = "lm studio" },+ .{ .msg = "invalid params, context window exceeds limit", .want = true, .why = "minimax" },+ .{ .msg = "413 request_too_large: Request exceeds the maximum size", .want = true, .why = "anthropic 413 byte-size overflow" },+ .{ .msg = "", .code = "model_context_window_exceeded", .want = true, .why = "z.ai non-standard code" },+ .{ .msg = "Token limit exceeded for this request", .want = true, .why = "generic fallback" },+ // Case-insensitivity: the same rejection Title-Cased by a gateway.+ .{ .msg = "PROMPT IS TOO LONG: 219373 TOKENS > 200000 MAXIMUM", .want = true, .why = "case-insensitive match" },+ .{ .msg = "Context Length Exceeded", .want = true, .why = "case-insensitive match" },+ };+ for (rows) |r| {+ const got = isContextOverflow(r.msg, r.code);+ if (got != r.want) {+ std.debug.print("row failed ({s}): msg={s} code={?s} want={} got={}\n", .{ r.why, r.msg, r.code, r.want, got });+ return error.TestUnexpectedResult;+ }+ }+}++const CompletionRow = struct {+ kind: Provider.Kind,+ body: []const u8,+ window: u64,+ want: Verdict,+ why: []const u8,+};++test "classifyCompletion (#414): the silent-200 and truncate-then-length shapes, and what must NOT trip" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const rows = [_]CompletionRow{+ // ---- silent overflow (z.ai): HTTP 200, empty completion, usage at/over the window+ .{ .kind = .openai, .window = 128_000, .want = .silent_overflow, .why = "z.ai silent 200", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"stop"}],+ \\ "usage":{"prompt_tokens":131072,"completion_tokens":0,"total_tokens":131072}}+ },+ .{ .kind = .openai, .window = 128_000, .want = .silent_overflow, .why = "exactly AT the window still counts", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":null},"finish_reason":"stop"}],+ \\ "usage":{"prompt_tokens":128000,"completion_tokens":0}}+ },+ .{ .kind = .anthropic, .window = 200_000, .want = .silent_overflow, .why = "cache reads count toward the window", .body =+ \\{"stop_reason":"end_turn","content":[],+ \\ "usage":{"input_tokens":1000,"cache_read_input_tokens":199000,"output_tokens":0}}+ },+ .{ .kind = .responses, .window = 272_000, .want = .silent_overflow, .why = "reasoning-only output is not an answer", .body =+ \\{"output":[{"type":"reasoning","summary":[]}],+ \\ "usage":{"input_tokens":280000,"output_tokens":0}}+ },+ // ---- upstream truncation (MiMo): finish_reason=length, zero output, input fills the window+ .{ .kind = .openai, .window = 32_768, .want = .upstream_truncation, .why = "MiMo truncate-then-length", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"length"}],+ \\ "usage":{"prompt_tokens":32768,"completion_tokens":0,"total_tokens":32768}}+ },+ .{ .kind = .openai, .window = 32_768, .want = .upstream_truncation, .why = "99% fill: a truncating server lands a hair short", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"length"}],+ \\ "usage":{"prompt_tokens":32500,"completion_tokens":0}}+ },+ .{ .kind = .anthropic, .window = 200_000, .want = .upstream_truncation, .why = "anthropic spells the same stop max_tokens", .body =+ \\{"stop_reason":"max_tokens","content":[],+ \\ "usage":{"input_tokens":200000,"output_tokens":0}}+ },+ // ---- must NOT trip: an ORDINARY max-tokens completion+ .{ .kind = .openai, .window = 32_768, .want = .ok, .why = "normal max-tokens: real output, small input", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":"here is a very long answer that ran out of room"},"finish_reason":"length"}],+ \\ "usage":{"prompt_tokens":900,"completion_tokens":16000}}+ },+ .{ .kind = .openai, .window = 32_768, .want = .ok, .why = "normal max-tokens on a nearly-full window still generated", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":"partial answer"},"finish_reason":"length"}],+ \\ "usage":{"prompt_tokens":32700,"completion_tokens":68}}+ },+ .{ .kind = .openai, .window = 32_768, .want = .ok, .why = "length stop, zero output, but the input is nowhere near the wall", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"length"}],+ \\ "usage":{"prompt_tokens":900,"completion_tokens":0}}+ },+ // ---- must NOT trip: ordinary success, and the two "no evidence" cases+ .{ .kind = .openai, .window = 128_000, .want = .ok, .why = "an over-window figure the model ANSWERED means our window is wrong, not the history", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}],+ \\ "usage":{"prompt_tokens":131072,"completion_tokens":12}}+ },+ .{ .kind = .openai, .window = 128_000, .want = .ok, .why = "a tool call is content", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":null,"tool_calls":[{"id":"c1","function":{"name":"bash","arguments":"{}"}}]},"finish_reason":"tool_calls"}],+ \\ "usage":{"prompt_tokens":131072,"completion_tokens":9}}+ },+ .{ .kind = .openai, .window = 128_000, .want = .ok, .why = "empty answer but the input is well under the window (a terse model, not overflow)", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"stop"}],+ \\ "usage":{"prompt_tokens":40,"completion_tokens":0}}+ },+ .{ .kind = .openai, .window = 0, .want = .ok, .why = "unknown window never guesses", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"stop"}],+ \\ "usage":{"prompt_tokens":131072,"completion_tokens":0}}+ },+ .{ .kind = .openai, .window = 128_000, .want = .ok, .why = "no usage reported: nothing to judge", .body =+ \\{"choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"stop"}]}+ },+ .{ .kind = .responses, .window = 272_000, .want = .ok, .why = "a real responses answer", .body =+ \\{"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}],+ \\ "usage":{"input_tokens":280000,"output_tokens":4}}+ },+ .{ .kind = .anthropic, .window = 200_000, .want = .ok, .why = "anthropic text block is content", .body =+ \\{"stop_reason":"end_turn","content":[{"type":"text","text":"hi"}],+ \\ "usage":{"input_tokens":210000,"output_tokens":2}}+ },+ };+ for (rows) |r| {+ const parsed = try std.json.parseFromSliceLeaky(Value, a, r.body, .{ .allocate = .alloc_always });+ const got = classifyCompletion(readCompletion(r.kind, parsed.object), r.window);+ if (got != r.want) {+ std.debug.print("row failed ({s}): want={s} got={s}\n", .{ r.why, @tagName(r.want), @tagName(got) });+ return error.TestUnexpectedResult;+ }+ }+}diff --git a/src/agent_overflow_tests.zig b/src/agent_overflow_tests.zignew file mode 100644index 00000000..d961004d--- /dev/null+++ b/src/agent_overflow_tests.zig@@ -0,0 +1,153 @@+//! Recovery-side tests for agent_overflow.zig — the half that drives a live+//! Agent (pin the meter, emergency-trim, retry once). The pure classification+//! tables are tested next to the tables themselves, in agent_overflow.zig.++const std = @import("std");+const Value = std.json.Value;++const Agent = @import("agent.zig").Agent;+const overflow = @import("agent_overflow.zig");+const recoverContextOverflow = overflow.recoverContextOverflow;+const recoverBehavioralOverflow = overflow.recoverBehavioralOverflow;++test { // main.zig's test root lists this file; carry agent_overflow.zig's own tests in with it+ _ = overflow;+}++/// A history emergencyTrim can actually reclaim: one clean user turn followed+/// by fat tool outputs (the #163 shape trimOldestToolOutputs recovers from).+fn trimmableAgent(a: std.mem.Allocator, kind: @import("provider.zig").Provider.Kind, window: u64) !Agent {+ var msgs = std.json.Array.init(a);+ var um: std.json.ObjectMap = .empty;+ try um.put(a, "role", .{ .string = "user" });+ try um.put(a, "content", .{ .string = "do a thing" });+ try msgs.append(.{ .object = um });+ const big = try a.alloc(u8, 5000);+ @memset(big, 'x');+ var i: usize = 0;+ while (i < 10) : (i += 1) {+ var o: std.json.ObjectMap = .empty;+ try o.put(a, "type", .{ .string = "function_call_output" });+ try o.put(a, "call_id", .{ .string = "c" });+ try o.put(a, "output", .{ .string = big });+ try msgs.append(.{ .object = o });+ }+ var agent: Agent = undefined;+ agent.arena = a;+ agent.messages = msgs;+ agent.tracer = null;+ agent.provider = .{ .id = @tagName(kind), .kind = kind, .auth = .x_api_key, .url = "", .api_key = "", .model = "claude", .context = window };+ agent.last_context_tokens = 0;+ agent.sub = false;+ agent.strict = false;+ agent.sys_normal = "";+ agent.sys_strict = "";+ agent.tools_anthropic = "";+ agent.tools_openai = "";+ agent.context_local_tokens = agent.fullRequestEstimateTokens();+ agent.stream_quiet = true;+ agent.compaction_request = false;+ agent.last_request_context_overflow = false;+ agent.last_api_error = null;+ agent.out = null;+ agent.label = "test";+ return agent;+}++test "recoverContextOverflow (#414): a Bedrock throttle rides the retry ladder instead of compacting" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = try trimmableAgent(a, .anthropic, 100000);+ const before = agent.messages.items.len;++ // The whole point of the guard list: this string matches the generic+ // "too many tokens" overflow fallback, but it is a 429. Recovering here+ // would discard real history AND shadow the Retry-After backoff.+ var retried = false;+ try std.testing.expect(!recoverContextOverflow(&agent, "ThrottlingException: Too many tokens, please wait before trying again.", null, &retried));+ try std.testing.expect(!retried);+ try std.testing.expect(!agent.last_request_context_overflow); // meter untouched: no compaction is scheduled+ try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);+ try std.testing.expectEqual(before, agent.messages.items.len);+}++fn parse(a: std.mem.Allocator, body: []const u8) !std.json.ObjectMap {+ const v = try std.json.parseFromSliceLeaky(Value, a, body, .{ .allocate = .alloc_always });+ return v.object;+}++test "recoverBehavioralOverflow (#414): the silent 200 compacts and retries; a normal reply does not" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = try trimmableAgent(a, .openai, 128_000);++ // An ordinary answer is never touched, even at a high token count.+ const ok_body =+ \\{"choices":[{"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}],+ \\ "usage":{"prompt_tokens":120000,"completion_tokens":8}}+ ;+ var retried = false;+ try std.testing.expect(!recoverBehavioralOverflow(&agent, try parse(a, ok_body), &retried));+ try std.testing.expect(!retried);+ try std.testing.expect(!agent.last_request_context_overflow);+ try std.testing.expect(agent.last_api_error == null);++ // z.ai's shape: HTTP 200, no answer, usage over the window.+ const silent =+ \\{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"stop"}],+ \\ "usage":{"prompt_tokens":131072,"completion_tokens":0}}+ ;+ const before = agent.fullRequestEstimateTokens();+ try std.testing.expect(recoverBehavioralOverflow(&agent, try parse(a, silent), &retried));+ try std.testing.expect(retried);+ try std.testing.expect(agent.last_request_context_overflow);+ try std.testing.expect(agent.fullRequestEstimateTokens() < before); // history was actually trimmed+ try std.testing.expect(agent.last_api_error == null); // recovered -> nothing to report++ // Same request, second occurrence: the retry guard stops a loop, but the+ // meter stays pinned at the window so the between-turns compaction still+ // engages, and the now-unrecoverable condition is named instead of+ // surfacing as an inexplicably short answer.+ try std.testing.expect(!recoverBehavioralOverflow(&agent, try parse(a, silent), &retried));+ try std.testing.expectEqual(agent.provider.context, agent.last_context_tokens);+ try std.testing.expect(agent.last_api_error != null);+ try std.testing.expect(std.mem.indexOf(u8, agent.last_api_error.?, "silent_overflow") != null);++ // A compaction summary request owns its own empty-summary escalation (#379).+ agent.compaction_request = true;+ agent.last_api_error = null;+ var fresh = false;+ try std.testing.expect(!recoverBehavioralOverflow(&agent, try parse(a, silent), &fresh));+ try std.testing.expect(agent.last_api_error == null);+}++test "recoverBehavioralOverflow (#414): truncate-then-length is reported as truncation, not a short answer" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent = try trimmableAgent(a, .openai, 32_768);++ // A genuine max-tokens completion must never be reclassified: it generated.+ const normal_length =+ \\{"choices":[{"message":{"role":"assistant","content":"a long answer that ran out of room"},"finish_reason":"length"}],+ \\ "usage":{"prompt_tokens":32700,"completion_tokens":68}}+ ;+ var retried = false;+ try std.testing.expect(!recoverBehavioralOverflow(&agent, try parse(a, normal_length), &retried));+ try std.testing.expect(!agent.last_request_context_overflow);++ // MiMo: the server truncated our input to fit, so it had no room to answer.+ const truncated =+ \\{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"length"}],+ \\ "usage":{"prompt_tokens":32768,"completion_tokens":0}}+ ;+ try std.testing.expect(recoverBehavioralOverflow(&agent, try parse(a, truncated), &retried));+ try std.testing.expect(agent.last_request_context_overflow);++ // Unrecoverable repeat: the distinct diagnosis reaches last_api_error, which+ // is what a subagent's parent and the --json error event read.+ try std.testing.expect(!recoverBehavioralOverflow(&agent, try parse(a, truncated), &retried));+ try std.testing.expect(std.mem.indexOf(u8, agent.last_api_error.?, "upstream_truncation") != null);+}diff --git a/src/agent_request.zig b/src/agent_request.zigindex 20f624ed..fc209435 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -28,9 +28,15 @@ const run_budget_mod = @import("run_budget.zig");const wire_messages = @import("messages.zig");const policy = @import("agent_request_policy.zig");+const overflow = @import("agent_overflow.zig");const errorCode = policy.errorCode;const isQuotaExceeded = policy.isQuotaExceeded;-const recoverContextOverflow = policy.recoverContextOverflow;+const recoverContextOverflow = overflow.recoverContextOverflow;+// #414: an HTTP 200 that overflowed silently — the provider accepted an+// over-window input and answered with nothing (z.ai), or truncated our input+// to fit and had no room left to generate (MiMo). Neither shape produces an+// error to keyword-match, so it is classified from the reported usage instead.+const recoverBehavioralOverflow = overflow.recoverBehavioralOverflow;const retryAfterAuthRefresh = policy.retryAfterAuthRefresh;const retryTransientServerError = policy.retryTransientServerError;@@ -334,6 +340,13 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {.ok => |obj| {if (!self.compaction_request) self.compact_transport_failures = 0;self.recordUsageResponses(obj, body.len);+ // #414: an empty output whose usage already fills the window+ // is an overflow the provider never reported. Re-anchor like+ // the error branch above: the recovery trims full history.+ if (recoverBehavioralOverflow(self, obj, &context_retried)) {+ self.closeCodexWs();+ continue :rebuild;+ }if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });return obj;@@ -403,6 +416,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {return error.ApiError;};self.recordUsage(root, body.len);+ if (recoverBehavioralOverflow(self, root, &context_retried)) continue; // #414: silent overflow / upstream truncation → trim + retryif (!self.compaction_request) self.compact_transport_failures = 0;if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });@@ -466,6 +480,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {}self.recordUsage(root, body.len);+ if (recoverBehavioralOverflow(self, root, &context_retried)) continue; // #414: same, on the non-streamed bodyif (!self.compaction_request) self.compact_transport_failures = 0;if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, self.last_context_tokens, self.last_cache_read, false);if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_finished", .provider = self.provider.id, .model = self.provider.model, .ok = true, .ms = ms });diff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex ebaf6aa0..341006cb 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -315,31 +315,15 @@ test "retryAfterAuthRefresh (#402): a different ChatGPT account is never adoptedtry std.testing.expectEqualStrings("other-tok", sibling.provider.api_key);}-/// True if `msg` is a provider's "input is over the context window" rejection,-/// across wire formats: codex/responses ("exceeds the context window"), openai-/// ("maximum context length", "context_length_exceeded"), anthropic ("prompt is-/// too long", "exceed context limit"). Drives the in-turn emergency-trim + retry-/// recovery symmetrically for every provider (#193) — before it, only the codex-/// path recovered and anthropic/openai died on an over-window turn.-fn isContextOverflow(msg: []const u8, code: ?[]const u8) bool {- // #203: match the structured error code first (openai/codex parity — a local or- // non-English provider whose message text differs still recovers), then fall back- // to the human-readable phrasing.- if (code) |c| {- const codes = [_][]const u8{ "context_length_exceeded", "context_window_exceeded" };- for (codes) |k| if (std.mem.eql(u8, c, k)) return true;- }- const needles = [_][]const u8{- "context window", // codex/responses: "exceeds the context window"- "context length", // openai: "maximum context length is N tokens"- "context_length_exceeded", // openai error code echoed into the message- "context limit", // anthropic: "input length and max_tokens exceed context limit"- "prompt is too long", // anthropic: "prompt is too long: N tokens > M maximum"- "maximum context", // defensive: "maximum context ... exceeded"- };- for (needles) |n| if (std.mem.indexOf(u8, msg, n) != null) return true;- return false;-}+/// #414: overflow classification (which failures mean "the input is over the+/// window", which only look like it, and the HTTP-200 shapes that never say so)+/// moved to agent_overflow.zig — this file was at the 600-line cap and the new+/// guard list plus behavioral detectors did not fit. Re-exported so existing+/// call sites resolve, and the two tests below stay HERE deliberately: they are+/// the contract the request loop depends on, and moving their names would read+/// as deleted coverage in the behavioral eval harness.+pub const isContextOverflow = @import("agent_overflow.zig").isContextOverflow;+pub const recoverContextOverflow = @import("agent_overflow.zig").recoverContextOverflow;/// The structured error code from a parsed error envelope, if any: openai / lmstudio //// deepseek put it at root.error.code; some providers use a top-level root.code (#203).@@ -372,39 +356,6 @@ pub fn errorCode(root: std.json.ObjectMap) ?[]const u8 {return null;}-/// #193 follow-up: shared in-turn context-overflow recovery for the three-/// anthropic/openai error branches (streamed error event, non-streamed-/// `{"type":"error"}` envelope, and the generic apiErrorMessage path). Before-/// this, only the codex/.responses branch recovered — anthropic/openai died on an-/// over-window turn. Returns true if the caller should `continue` the rebuild loop-/// (emergency-trimmed, retry the same request once); false to fall through to the-/// normal error. Pins the meter to the window FIRST so the between-turns-/// compaction engages even when we can't recover here (the rejected request-/// returns no usage to correct the lagging meter). Guarded by `retried` (one-/// `context_retried` shared across every branch of a request) so a second overflow-/// falls through and never loops. These wire formats send the full input each-/// rebuild, so — unlike the codex branch — no closeCodexWs re-anchor is needed.-pub fn recoverContextOverflow(self: *Agent, msg: []const u8, code: ?[]const u8, retried: *bool) bool {- if (!isContextOverflow(msg, code)) return false;- self.last_request_context_overflow = true;- // Rejection proves at least the advertised window, not an exact total.- // Preserve stronger server/local evidence already above that floor.- const estimate = self.contextEstimate();- self.last_context_tokens = @max(estimate.effective, self.provider.context);- self.context_local_tokens = estimate.local;- // compact() marks its synthetic summary request explicitly. Generic- // in-request recovery is destructive there: the synthetic compact- // instruction is the newest clean user turn, so emergencyTrim can discard- // the entire real conversation and retry with only "summarize it". Let the- // outer compactOrRecover policy handle a failed summary after compact()'s- // errdefer removes that synthetic instruction.- if (self.compaction_request) return false;- if (retried.* or self.emergencyTrim() == 0) return false;- retried.* = true;- if (self.tracer) |tr| tr.note("context", "input over the window — emergency-trimmed and retrying the turn");- return true;-}-const max_server_retries: usize = 3; // #opencode-parity: bounded retries for a transient in-stream server overload/// #opencode-parity: an in-band error event (an SSE {"type":"error"} or a JSON@@ -477,25 +428,6 @@ test "isQuotaExceeded (#opencode-parity): billing cap detected, transient throtttry std.testing.expect(!isQuotaExceeded("429 too many requests"));}-test "isContextOverflow (#193/#203): matches structured code + every provider's phrasing, not unrelated errors" {- // codex/responses, openai, anthropic wire-format rejections all recover in-turn- try std.testing.expect(isContextOverflow("Your input exceeds the context window of 272000 tokens", null));- try std.testing.expect(isContextOverflow("This model's maximum context length is 128000 tokens. However, you requested 130000", null));- try std.testing.expect(isContextOverflow("context_length_exceeded", null));- try std.testing.expect(isContextOverflow("prompt is too long: 219373 tokens > 200000 maximum", null));- try std.testing.expect(isContextOverflow("input length and max_tokens exceed context limit", null));- // #203: a structured error code recovers even when the message text is unfamiliar- // (a local / non-English provider whose phrasing we don't match on)- try std.testing.expect(isContextOverflow("de invoerlengte overschrijdt het venster", "context_length_exceeded"));- try std.testing.expect(isContextOverflow("", "context_window_exceeded"));- // unrelated API errors must NOT trigger a trim + retry, by message or by code- try std.testing.expect(!isContextOverflow("The API Key appears to be invalid or may have expired.", null));- try std.testing.expect(!isContextOverflow("tool_choice is not supported", null));- try std.testing.expect(!isContextOverflow("rate limit exceeded", null));- try std.testing.expect(!isContextOverflow("model not found", null));- try std.testing.expect(!isContextOverflow("some unrelated failure", "rate_limit_exceeded"));-}-test "errorCode (#203): pulls root.error.code (openai/lmstudio), falls back to root.code, else null" {var arena = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena.deinit();@@ -525,6 +457,28 @@ test "errorCode (#203): pulls root.error.code (openai/lmstudio), falls back to rtry std.testing.expectEqualStrings("context_length_exceeded", errorCode(root4).?);}+test "isContextOverflow (#193/#203): matches structured code + every provider's phrasing, not unrelated errors" {+ // codex/responses, openai, anthropic wire-format rejections all recover in-turn+ try std.testing.expect(isContextOverflow("Your input exceeds the context window of 272000 tokens", null));+ try std.testing.expect(isContextOverflow("This model's maximum context length is 128000 tokens. However, you requested 130000", null));+ try std.testing.expect(isContextOverflow("context_length_exceeded", null));+ try std.testing.expect(isContextOverflow("prompt is too long: 219373 tokens > 200000 maximum", null));+ try std.testing.expect(isContextOverflow("input length and max_tokens exceed context limit", null));+ // #203: a structured error code recovers even when the message text is unfamiliar+ // (a local / non-English provider whose phrasing we don't match on)+ try std.testing.expect(isContextOverflow("de invoerlengte overschrijdt het venster", "context_length_exceeded"));+ try std.testing.expect(isContextOverflow("", "context_window_exceeded"));+ // unrelated API errors must NOT trigger a trim + retry, by message or by code+ try std.testing.expect(!isContextOverflow("The API Key appears to be invalid or may have expired.", null));+ try std.testing.expect(!isContextOverflow("tool_choice is not supported", null));+ try std.testing.expect(!isContextOverflow("rate limit exceeded", null));+ try std.testing.expect(!isContextOverflow("model not found", null));+ try std.testing.expect(!isContextOverflow("some unrelated failure", "rate_limit_exceeded"));+ // #414: the guard list is consulted FIRST — a throttle whose wording collides+ // with the generic "too many tokens" fallback stays on the retry ladder.+ try std.testing.expect(!isContextOverflow("ThrottlingException: Too many tokens, please wait before trying again.", null));+}+test "recoverContextOverflow (#193): overflow trims + retries once; guard and non-overflow fall through" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/main.zig b/src/main.zigindex 5c22abce..2f72e481 100644--- a/src/main.zig+++ b/src/main.zig@@ -585,10 +585,10 @@ test { // pull in tests from imported modules (mcp.zig)_ = mcp;_ = @import("mcp_rpc.zig");_ = @import("main_test.zig");- // A module whose tests must run needs an explicit reference here: a- // plain @import elsewhere (or a type-only alias) is NOT enough — it- // compiles to nothing; scripts/eval-tier1.sh --only reach catches one.+ // A module whose tests must run needs an explicit reference here: a plain @import+ // elsewhere (or a type-only alias) is NOT enough — it compiles to nothing; scripts/eval-tier1.sh --only reach catches one._ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped+ _ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here_ = @import("readline_history.zig");_ = @import("goal_pacing_autonomous_test.zig");