graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(agent): local-model window override + estimate baseline + structured overflow detection + metering parity (#203, #204)
Rach Pradhan3a603d04d968
diff --git a/src/agent_request.zig b/src/agent_request.zigindex 5271f0ec..899a52cb 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -78,7 +78,14 @@ test "isAuthError (#148): auth failures only, not credits/rate/other" {/// 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) bool {+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"@@ -103,8 +110,8 @@ fn isContextOverflow(msg: []const u8) bool {/// `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.-fn recoverContextOverflow(self: *Agent, msg: []const u8, retried: *bool) bool {- if (!isContextOverflow(msg)) return false;+fn recoverContextOverflow(self: *Agent, msg: []const u8, code: ?[]const u8, retried: *bool) bool {+ if (!isContextOverflow(msg, code)) return false;self.last_context_tokens = self.provider.context;if (retried.* or self.emergencyTrim() == 0) return false;retried.* = true;@@ -112,18 +119,23 @@ fn recoverContextOverflow(self: *Agent, msg: []const u8, retried: *bool) bool {return true;}-test "isContextOverflow (#193): matches every provider's overflow phrasing, not unrelated errors" {+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"));- try std.testing.expect(isContextOverflow("This model's maximum context length is 128000 tokens. However, you requested 130000"));- try std.testing.expect(isContextOverflow("context_length_exceeded"));- try std.testing.expect(isContextOverflow("prompt is too long: 219373 tokens > 200000 maximum"));- try std.testing.expect(isContextOverflow("input length and max_tokens exceed context limit"));- // unrelated API errors must NOT trigger a trim + retry- try std.testing.expect(!isContextOverflow("The API Key appears to be invalid or may have expired."));- try std.testing.expect(!isContextOverflow("tool_choice is not supported"));- try std.testing.expect(!isContextOverflow("rate limit exceeded"));- try std.testing.expect(!isContextOverflow("model not found"));+ 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 "recordUsage (#202): floors the meter from the local estimate when usage is absent" {@@ -183,15 +195,15 @@ test "recoverContextOverflow (#193): overflow trims + retries once; guard and no// overflow + trimmable history -> recovers (retry the turn), guard flipsvar retried = false;- try std.testing.expect(recoverContextOverflow(&agent, "prompt is too long: 999 tokens > 100 maximum", &retried));+ try std.testing.expect(recoverContextOverflow(&agent, "prompt is too long: 999 tokens > 100 maximum", null, &retried));try std.testing.expect(retried);// a second overflow this request -> guard blocks a re-trim (no loop), but the// meter stays pinned to the window so the between-turns compaction still engages- try std.testing.expect(!recoverContextOverflow(&agent, "prompt is too long", &retried));+ try std.testing.expect(!recoverContextOverflow(&agent, "prompt is too long", null, &retried));try std.testing.expectEqual(agent.provider.context, agent.last_context_tokens);// an unrelated error never recovers, regardless of the guardvar retried2 = false;- try std.testing.expect(!recoverContextOverflow(&agent, "invalid api key", &retried2));+ try std.testing.expect(!recoverContextOverflow(&agent, "invalid api key", null, &retried2));try std.testing.expect(!retried2);}@@ -395,7 +407,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {// session would wedge (every retry resends the same// oversized history). Pin the meter to the window so the// ApiError compact-and-recover path engages.- if (isContextOverflow(msg)) {+ if (isContextOverflow(msg, null)) {self.last_context_tokens = self.provider.context;// #193: the local pre-send gate uses a byte/4 LOWER bound, so// the backend can still reject an input it let through. A good@@ -430,7 +442,8 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {const eo = if (root.get("error")) |ev| (if (ev == .object) ev.object else null) else null;const etype = if (eo) |e| (if (e.get("type")) |tv| (if (tv == .string) tv.string else "error") else "error") else "error";const emsg = if (eo) |e| (if (e.get("message")) |mv| (if (mv == .string) mv.string else "") else "") else "";- if (recoverContextOverflow(self, emsg, &context_retried)) continue; // #193: streamed error event that is an overflow → trim + retry+ const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;+ if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: streamed error event overflow (by code or phrasing) → trim + retryif (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });return error.ApiError;@@ -454,7 +467,8 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {const eo = if (root.get("error")) |ev| (if (ev == .object) ev.object else null) else null;const etype = if (eo) |e| (if (e.get("type")) |tv| (if (tv == .string) tv.string else "error") else "error") else "error";const emsg = if (eo) |e| (if (e.get("message")) |mv| (if (mv == .string) mv.string else "") else "") else "";- if (recoverContextOverflow(self, emsg, &context_retried)) continue; // #193: anthropic {"type":"error"} overflow → trim + retry+ const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;+ if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: {"type":"error"} overflow (by code or phrasing) → trim + retryif (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("api error ({s}): {s}", .{ etype, emsg });return error.ApiError;@@ -492,7 +506,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {// #193 follow-up: recover an anthropic/openai context-window rejection// in-turn instead of failing the turn (before this only codex recovered;// anthropic and openai died). Shared with the two error branches above.- if (recoverContextOverflow(self, msg, &context_retried)) continue;+ if (recoverContextOverflow(self, msg, null, &context_retried)) continue;if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);try self.sayApiError("api error: {s}", .{msg});return error.ApiError;@@ -675,7 +689,15 @@ pub fn fullInputEstimateTokens(self: *Agent) u64 {/// Guarded on a known window (compactAt()==0 → don't compact blindly).pub fn inputOverCompactThreshold(self: *Agent) bool {const threshold = self.provider.compactAt();- return threshold > 0 and fullInputEstimateTokens(self) >= threshold;+ if (threshold == 0) return false;+ // #203: fullInputEstimateTokens omits the ever-present system prompt + tool+ // schemas, so it undercounts the real input and this gate under-fires. Add a+ // baseline for that fixed prefill, clamped to 1/8 of the window so it can never+ // dominate a small (local) window. (Kept out of fullInputEstimateTokens itself,+ // which must stay pure over self.messages for the unit tests.)+ const prefill_baseline_tokens: u64 = 8000;+ const prefill = @min(prefill_baseline_tokens, self.provider.context / 8);+ return fullInputEstimateTokens(self) + prefill >= threshold;}test "inputOverCompactThreshold (#193): local estimate gates a pre-send compact" {diff --git a/src/pricing.zig b/src/pricing.zigindex 61c86ef7..ee34b16b 100644--- a/src/pricing.zig+++ b/src/pricing.zig@@ -303,6 +303,23 @@ pub fn contextFor(provider_id: []const u8, model: []const u8) u64 {return default_context;}+/// Whether a model has a catalogued context window (baked row or fresh overlay),+/// as opposed to falling through to default_context. Mirrors contextFor's lookup so+/// a caller can tell an unknown/local model from a known 200k one (#203) — needed+/// because contextFor returns default_context for both.+pub fn isKnownModel(provider_id: []const u8, model: []const u8) bool {+ for (models()) |m| {+ if (std.mem.eql(u8, m.provider, provider_id) and std.mem.eql(u8, m.name, model)) return true;+ }+ for (context_overlay) |m| {+ if (std.mem.eql(u8, m.name, model)) return true;+ }+ for (models()) |m| {+ if (std.mem.eql(u8, m.name, model)) return true;+ }+ return false;+}+/// Fuzzy model selection for `/model <query>` (graff-style). Exact name wins;/// otherwise case-insensitive substring, preferring a model whose provider has/// a key/login available so `/model sonnet` lands on a usable provider. Returnsdiff --git a/src/provider.zig b/src/provider.zigindex 09f57f3e..ac865363 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -14,6 +14,26 @@ const std = @import("std");const pricing = @import("pricing.zig");const contextFor = pricing.contextFor;+/// #203: declare the context window (tokens) for an unknown/local model whose real+/// window graff cannot look up, replacing the conservative default. Applied only+/// when contextFor falls back to default_context (see contextWindowFor) so it can+/// never shrink a known/catalogued window. Set from GRAFF_CONTEXT / GRAFF_CONTEXT_WINDOW.+pub var g_context_override: ?u64 = null;++/// #204: override the auto-compaction threshold as a percent of the window+/// (default 80). null → 80. Unlike codex we allow lowering AND raising (1..100).+pub var g_compact_pct_override: ?u8 = null;++/// The context window for a provider+model, honoring g_context_override for an+/// unknown/local model — i.e. only when contextFor returns the conservative default,+/// never overriding a known window (#203).+fn contextWindowFor(provider_id: []const u8, model: []const u8) u64 {+ // Only an unknown/local model (no catalogued window) takes the override, so a+ // global GRAFF_CONTEXT can never shrink a known model that happens to be 200k.+ if (g_context_override) |ov| if (!pricing.isKnownModel(provider_id, model)) return ov;+ return contextFor(provider_id, model);+}+/// Wire format + auth style + endpoint per provider. Base URLs and env-var/// names from models.dev/api.json (snapshot 2026-06-10); the anthropic and/// openai bases are the canonical ones (models.dev lists them as null).@@ -81,9 +101,12 @@ pub const Provider = struct {pub const Kind = enum { anthropic, openai, responses };pub const Auth = enum { x_api_key, bearer };- /// Auto-compact past 80% of the model's context window.+ /// Auto-compact past a percentage (default 80%) of the model's context window.+ /// GRAFF_COMPACT_PCT overrides the percentage, clamped to 1..100 (#204). Unlike+ /// codex's one-directional clamp, the override may lower OR raise the threshold.pub fn compactAt(p: Provider) u64 {- return p.context / 10 * 8;+ const pct: u64 = if (g_compact_pct_override) |o| @min(o, 100) else 80;+ return p.context / 100 * pct;}/// #201: absolute ceiling for a single tool output regardless of window size,@@ -156,7 +179,7 @@ pub const Keys = struct {.url = if (is_codex) g_codex_url_override orelse spec.url else spec.url,.api_key = key,.model = model,- .context = contextFor(spec.id, model),+ .context = contextWindowFor(spec.id, model),.account = if (is_codex) keys.codex_account else "",.source = keys.source(spec.id),};@@ -272,3 +295,24 @@ test "perOutputCap (#201): window-proportional with an absolute ceiling, keep_rep.context = 0;try std.testing.expectEqual(@as(usize, 0), p.perOutputCap());}++test "contextWindowFor (#203): GRAFF_CONTEXT overrides only an unknown/local model" {+ g_context_override = 8192;+ defer g_context_override = null;+ // unknown/local model (no catalogued window) → the override applies+ try std.testing.expectEqual(@as(u64, 8192), contextWindowFor("lmstudio", "some-local-gguf"));+ // a known, catalogued model keeps its real window even with the override set+ try std.testing.expect(pricing.isKnownModel("anthropic", "claude-opus-4-8"));+ try std.testing.expect(contextWindowFor("anthropic", "claude-opus-4-8") != 8192);+}++test "compactAt (#204): GRAFF_COMPACT_PCT overrides the 80% default, both directions" {+ var p: Provider = undefined;+ p.context = 100_000;+ try std.testing.expectEqual(@as(u64, 80_000), p.compactAt()); // default 80%+ g_compact_pct_override = 70;+ defer g_compact_pct_override = null;+ try std.testing.expectEqual(@as(u64, 70_000), p.compactAt()); // lowered+ g_compact_pct_override = 95;+ try std.testing.expectEqual(@as(u64, 95_000), p.compactAt()); // raised — no codex-style clamp to 90+}diff --git a/src/providers.zig b/src/providers.zigindex 25b4c7ab..5bab6f6b 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -86,6 +86,12 @@ fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: boolroot.effort_rejected = false; // new model may accept reasoning_effort; relearnroot.ws_off = false; // a previous Codex WS fallback must not leak across switchesroot.provider = p;+ // #204: a provider switch changes the window; don't carry the previous model's+ // absolute token count against it. Re-estimate from the (kept or translated)+ // history so the meter + compaction gate stay consistent until the next response+ // returns real usage. (The cross-format history-clear above already set 0;+ // fullInputEstimateTokens over an empty history is 0.)+ root.last_context_tokens = root.fullInputEstimateTokens();root.fallback_active = !persist;root.fallback_blocked = false;if (persist) saveModel(root.io, root.home, p.id, p.model);diff --git a/src/session_run.zig b/src/session_run.zigindex d4d6d698..2aa43485 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -368,6 +368,23 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:if (secs > 0) agent_ws.codex_ws_idle_ms = @intCast(@min(secs, 86_400) * 1000);} else |_| {}}+ // #203: GRAFF_CONTEXT / GRAFF_CONTEXT_WINDOW declares the context window (in+ // tokens) for an unknown/local model whose real window graff can't look up,+ // replacing the conservative 200k fallback so the compaction gate + per-output+ // cap are sized correctly. Only affects models that fall back to the default+ // (see provider.contextWindowFor). Ignored if unparseable or 0.+ if (environ_map.get("GRAFF_CONTEXT") orelse environ_map.get("GRAFF_CONTEXT_WINDOW")) |v| {+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |n| {+ if (n > 0) provider_mod.g_context_override = n;+ } else |_| {}+ }+ // #204: GRAFF_COMPACT_PCT overrides the auto-compaction threshold as a percent+ // of the window (default 80). Clamped to 1..100; ignored if unparseable or 0.+ if (environ_map.get("GRAFF_COMPACT_PCT")) |v| {+ if (std.fmt.parseInt(u8, std.mem.trim(u8, v, " \t"), 10)) |pct| {+ if (pct > 0) provider_mod.g_compact_pct_override = @min(pct, 100);+ } else |_| {}+ }ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;// GRAFF_WS_FORCE_FAIL_ONCE=1|true|on|yes arms the one-shot forced WS// connect failure (integration-test seam for the SSE fallback + ws_off