graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
refactor(req-stats): extract GRAFF_REQ_STATS anatomy into req_stats.zig; cache-key helper into http_headers
Rach Pradhanf5248283da0d
diff --git a/src/agent_request.zig b/src/agent_request.zigindex bafd35e9..725bdaa5 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -63,14 +63,7 @@ pub const errorMessage = responses.errorMessage;pub const buildBody = @import("agent_request_body.zig").buildBody;-/// GRAFF_REQ_STATS=1 (set once at startup by session_settings.applyEnvKnobs):-/// print the per-call request breakdown in request() — the token-diet-/// program's measurement hook.-pub var g_req_stats = false;--fn reqStatsArmed() bool {- return g_req_stats;-}+const req_stats = @import("req_stats.zig"); // GRAFF_REQ_STATS anatomy (session_settings arms req_stats.g_armed)/// Keep the normal request hot path allocation-free while avoiding a permanent/// RSS high-water mark after one anomalously large stream. Small scratch arenas@@ -199,72 +192,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {self.streamed_args = .none;const body = try self.buildBody(tools, force, live, stream_usage);defer self.gpa.free(body);- // GRAFF_REQ_STATS=1: per-call request anatomy for the token-diet work- // — total body, tools JSON, system prompt; the remainder is messages.- // Byte sizes, not tokens (÷~4 for a rough token read). stderr, never- // json_mode's stdout.- if (reqStatsArmed()) {- std.debug.print(" [req] body={d}B tools={d}B system={d}B messages~={d}B\n", .{ body.len, if (tools) |t| t.len else 0, self.sys_normal.len, body.len -| (if (tools) |t| t.len else 0) -| self.sys_normal.len });- // Per-call body dump, for byte-diffing consecutive requests (cache-prefix forensics).- const dump_seq = struct {- var n: usize = 0;- };- dump_seq.n += 1;- var dpath: [64]u8 = undefined;- if (std.fmt.bufPrint(&dpath, "/tmp/graff-body-{d:0>3}.json", .{dump_seq.n})) |p| {- Io.Dir.cwd().writeFile(self.io, .{ .sub_path = p, .data = body }) catch {};- } else |_| {}- // One dump per process: the assembled system prompt, for offline segment attribution (#476).- const dumped = struct {- var done: bool = false;- };- if (!dumped.done and self.sys_normal.len > 10_000) {- dumped.done = true;- Io.Dir.cwd().writeFile(self.io, .{ .sub_path = "/tmp/graff-sys.txt", .data = self.sys_normal }) catch {};- }- // Per-server split: attribute each tool's serialized span by its- // name prefix (next-"name" boundary ≈ tool size, ±separators).- if (tools) |t| {- var cdbp: usize = 0;- var other_mcp: usize = 0;- var native: usize = 0;- var pos: usize = 0;- while (std.mem.indexOfPos(u8, t, pos, "\"name\":\"")) |n| {- const name_start = n + 8;- const name_end = std.mem.indexOfScalarPos(u8, t, name_start, '"') orelse break;- const next = std.mem.indexOfPos(u8, t, name_end, "\"name\":\"") orelse t.len;- const span = next - n;- const nm = t[name_start..name_end];- if (std.mem.startsWith(u8, nm, "mcp__codedbpro__")) cdbp += span else if (std.mem.startsWith(u8, nm, "mcp__")) other_mcp += span else native += span;- pos = name_end;- }- std.debug.print(" [req] tools split: native={d}B codedbpro={d}B other_mcp={d}B\n", .{ native, cdbp, other_mcp });- // Top-5 largest native specs — the deferral candidates list.- var sizes: [64]struct { span: usize, at: usize } = undefined;- var n_sizes: usize = 0;- pos = 0;- while (std.mem.indexOfPos(u8, t, pos, "\"name\":\"")) |n2| {- const ns = n2 + 8;- const ne = std.mem.indexOfScalarPos(u8, t, ns, '"') orelse break;- const nxt = std.mem.indexOfPos(u8, t, ne, "\"name\":\"") orelse t.len;- if (!std.mem.startsWith(u8, t[ns..ne], "mcp__") and n_sizes < sizes.len) {- sizes[n_sizes] = .{ .span = nxt - n2, .at = ns };- n_sizes += 1;- }- pos = ne;- }- var top: usize = 0;- while (top < 5 and top < n_sizes) : (top += 1) {- var bi: usize = 0;- for (sizes[0..n_sizes], 0..) |sz, j| if (sz.span > sizes[bi].span) {- bi = j;- };- const nm = t[sizes[bi].at .. std.mem.indexOfScalarPos(u8, t, sizes[bi].at, '"') orelse sizes[bi].at];- std.debug.print(" [req] {s}: {d}B\n", .{ nm, sizes[bi].span });- sizes[bi].span = 0;- }- }- }+ // GRAFF_REQ_STATS=1: per-call request anatomy + body dumps (req_stats.zig).+ req_stats.report(self.io, body, tools, self.sys_normal);const t0: Io.Timestamp = .now(self.io, .awake);if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_started", .provider = self.provider.id, .model = self.provider.model });// HTTP calls are flaky: a kept-alive connection the server closeddiff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex 6c6dfb85..94527f4d 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -22,17 +22,6 @@ pub fn responsesOutputLimit(self: *const Agent) u32 {return self.responses_output_limit orelse max_tokens;}-/// The cache-affinity partition for this agent. opencode keys per SESSION for-/// the same reason: every agent in the process used to share the session id,-/// so interleaved root/sub requests — completely different prefixes under one-/// key — evicted each other (root cache_read measured ~35% in benchmarks).-/// Root keeps the bare session id; every other agent gets its own suffix.-fn promptCacheKey(self: *const Agent, buf: []u8) []const u8 {- const base = http_headers.sessionId(self.io);- if (std.mem.eql(u8, self.label, "main")) return base;- return std.fmt.bufPrint(buf, "{s}-{x}", .{ base, @intFromPtr(self) }) catch base;-}-pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bool, stream_usage: bool) ![]u8 {var aw: Io.Writer.Allocating = .init(self.gpa);errdefer aw.deinit();@@ -182,7 +171,7 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: booif (is_kimi) {var ckbuf: [96]u8 = undefined;try s.objectField("prompt_cache_key");- try s.write(promptCacheKey(self, &ckbuf));+ try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));}// Reasoning-effort hint for OpenAI-compatible providers that// honor it (codegraff gateway, deepseek). Mirrors the@@ -193,10 +182,9 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo}},.responses => {- // Codex / ChatGPT Responses API. system prompt → instructions;- // history items are valid input items; stream is required by- // the backend (we buffer + parse the SSE). reasoning items are- // returned encrypted and passed back for cross-turn continuity.+ // Codex / ChatGPT Responses API. system prompt → instructions; history+ // items are valid input items; stream is required (we buffer + parse the+ // SSE); reasoning items return encrypted and are passed back per turn.try s.objectField("instructions");try s.write(self.systemPrompt());// Pin our full resends to a per-session cache partition, the way@@ -205,13 +193,9 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo// affinity hint for a prefix we re-upload every turn.var ckbuf: [96]u8 = undefined;try s.objectField("prompt_cache_key");- try s.write(promptCacheKey(self, &ckbuf));- // GPT-5.6 explicit caching (prompt_cache_options + per-item- // prompt_cache_breakpoint, openai-docs upgrading-to-gpt-5p6-sol.md)- // was probed here and is NOT shippable: the ChatGPT-codex route- // rejects both ("Unsupported parameter: prompt_cache_options",- // "Unknown parameter: input[0].prompt_cache_breakpoint"). Implicit- // caching + prompt_cache_key affinity is all this backend offers.+ try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));+ // GPT-5.6 explicit caching (prompt_cache_options / breakpoints) is+ // platform-API-only — this route 400s on both. Implicit + cache key is all.// Codex WS delta: once a response.id is held on a live WS session,// send previous_response_id + only the items the server does not yet// hold, instead of the full history (avoids the huge frame that the@@ -260,6 +244,7 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.endArray();try s.objectField("store");try s.write(false);+ server_compact.noteExposure(self);try server_compact.writeContextManagement(self, &s);// No top-level max_output_tokens: the codex backend rejects it// ("Unsupported parameter") on gpt-5.6-* models, hard-failing everydiff --git a/src/http_headers.zig b/src/http_headers.zigindex 4ce37db6..8d4224a8 100644--- a/src/http_headers.zig+++ b/src/http_headers.zig@@ -42,6 +42,17 @@ pub fn sessionId(io: Io) []const u8 {return session_id_buf[0..session_id_len];}+/// The cache-affinity partition for one agent. opencode keys per session for+/// the same reason: every agent in the process used to share the session id,+/// so interleaved root/sub requests — different prefixes under one key —+/// evicted each other (root cache_read measured ~35% in benchmarks). Root+/// ("main") keeps the bare session id; every other agent gets a unique suffix.+pub fn promptCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: []u8) []const u8 {+ const base = sessionId(io);+ if (std.mem.eql(u8, label, "main")) return base;+ return std.fmt.bufPrint(buf, "{s}-{x}", .{ base, @intFromPtr(agent) }) catch base;+}+/// /resume adopts the persisted key so k3/codex prompt-cache affinity survives/// the process boundary — both upstreams key the cache on the durable/// conversation id (kimi-code's sessionContext.sessionId; codex's ModelClientdiff --git a/src/req_stats.zig b/src/req_stats.zignew file mode 100644index 00000000..a9488fda--- /dev/null+++ b/src/req_stats.zig@@ -0,0 +1,77 @@+//! GRAFF_REQ_STATS=1 request anatomy (the token-diet program's measurement+//! hook): per-call body/tools/system byte split, a per-call body dump for+//! byte-diffing consecutive requests (cache-prefix forensics), a one-time+//! system-prompt dump for offline segment attribution (#476), and the+//! per-server tools split with the top-5 native specs. All output is stderr,+//! never json_mode's stdout. Extracted from agent_request.zig to keep that+//! file under the 600-line ceiling.++const std = @import("std");+const Io = std.Io;++/// Set once at startup by session_settings.applyEnvKnobs (GRAFF_REQ_STATS).+pub var g_armed = false;++pub fn report(io: Io, body: []const u8, tools: ?[]const u8, sys_normal: []const u8) void {+ if (!g_armed) return;+ std.debug.print(" [req] body={d}B tools={d}B system={d}B messages~={d}B\n", .{ body.len, if (tools) |t| t.len else 0, sys_normal.len, body.len -| (if (tools) |t| t.len else 0) -| sys_normal.len });+ // Per-call body dump, for byte-diffing consecutive requests.+ const dump_seq = struct {+ var n: usize = 0;+ };+ dump_seq.n += 1;+ var dpath: [64]u8 = undefined;+ if (std.fmt.bufPrint(&dpath, "/tmp/graff-body-{d:0>3}.json", .{dump_seq.n})) |p| {+ Io.Dir.cwd().writeFile(io, .{ .sub_path = p, .data = body }) catch {};+ } else |_| {}+ // One dump per process: the assembled system prompt.+ const dumped = struct {+ var done: bool = false;+ };+ if (!dumped.done and sys_normal.len > 10_000) {+ dumped.done = true;+ Io.Dir.cwd().writeFile(io, .{ .sub_path = "/tmp/graff-sys.txt", .data = sys_normal }) catch {};+ }+ // Per-server split: attribute each tool's serialized span by its name+ // prefix (next-"name" boundary ≈ tool size, ±separators).+ if (tools) |t| {+ var cdbp: usize = 0;+ var other_mcp: usize = 0;+ var native: usize = 0;+ var pos: usize = 0;+ while (std.mem.indexOfPos(u8, t, pos, "\"name\":\"")) |n| {+ const name_start = n + 8;+ const name_end = std.mem.indexOfScalarPos(u8, t, name_start, '"') orelse break;+ const next = std.mem.indexOfPos(u8, t, name_end, "\"name\":\"") orelse t.len;+ const span = next - n;+ const nm = t[name_start..name_end];+ if (std.mem.startsWith(u8, nm, "mcp__codedbpro__")) cdbp += span else if (std.mem.startsWith(u8, nm, "mcp__")) other_mcp += span else native += span;+ pos = name_end;+ }+ std.debug.print(" [req] tools split: native={d}B codedbpro={d}B other_mcp={d}B\n", .{ native, cdbp, other_mcp });+ // Top-5 largest native specs — the deferral candidates list.+ var sizes: [64]struct { span: usize, at: usize } = undefined;+ var n_sizes: usize = 0;+ pos = 0;+ while (std.mem.indexOfPos(u8, t, pos, "\"name\":\"")) |n2| {+ const ns = n2 + 8;+ const ne = std.mem.indexOfScalarPos(u8, t, ns, '"') orelse break;+ const nxt = std.mem.indexOfPos(u8, t, ne, "\"name\":\"") orelse t.len;+ if (!std.mem.startsWith(u8, t[ns..ne], "mcp__") and n_sizes < sizes.len) {+ sizes[n_sizes] = .{ .span = nxt - n2, .at = ns };+ n_sizes += 1;+ }+ pos = ne;+ }+ var top: usize = 0;+ while (top < 5 and top < n_sizes) : (top += 1) {+ var bi: usize = 0;+ for (sizes[0..n_sizes], 0..) |sz, j| if (sz.span > sizes[bi].span) {+ bi = j;+ };+ const nm = t[sizes[bi].at .. std.mem.indexOfScalarPos(u8, t, sizes[bi].at, '"') orelse sizes[bi].at];+ std.debug.print(" [req] {s}: {d}B\n", .{ nm, sizes[bi].span });+ sizes[bi].span = 0;+ }+ }+}diff --git a/src/session_settings.zig b/src/session_settings.zigindex a9d92684..ef838c8d 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -24,6 +24,7 @@ const native_fold = @import("native_fold.zig"); // GRAFF_NO_NATIVE_FOLD → enabconst mcp_schema_gate = @import("mcp_schema_gate.zig"); // GRAFF_STABLE_CATALOG → g_stable_catalogconst no_local_tools = @import("no_local_tools.zig"); // #330: GRAFF_NO_LOCAL_TOOLSconst tool_handle = @import("tool_handle.zig"); // #440: GRAFF_TOOL_HANDLE_BYTES+const server_compact = @import("agent_server_compact.zig"); // GRAFF_SERVER_COMPACT + #compact-ab assignmentconst provider_mod = @import("provider.zig");const skills = @import("skills.zig");const anim = @import("anim.zig");@@ -93,8 +94,8 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {// GRAFF_LEAN: presence-based, exactly matching session_start.leanSkipsMcp// (the MCP half of the same switch) — a "0" still means lean, by design.if (environ_map.get("GRAFF_LEAN") != null) no_local_tools.lean = true;- // GRAFF_REQ_STATS: presence-based request-anatomy print (agent_request).- agent_request.g_req_stats = environ_map.get("GRAFF_REQ_STATS") != null;+ // GRAFF_REQ_STATS: presence-based request-anatomy print (req_stats).+ @import("req_stats.zig").g_armed = environ_map.get("GRAFF_REQ_STATS") != null;// GRAFF_CODEX_FULL_RESEND: presence-based — never chain previous_response_id// (codex_chain); the opencode-shape experiment for cache-hit measurement.if (environ_map.get("GRAFF_CODEX_FULL_RESEND") != null) @import("codex_chain.zig").g_force_full_resend = true;@@ -133,11 +134,11 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {if (pct > 0) provider_mod.g_compact_pct_override = @min(pct, 100);} else |_| {}}- // GRAFF_SERVER_COMPACT=0/false/off: opt .responses providers (codex) out of- // server-side compaction back to client-side summaries. Default on.+ // GRAFF_SERVER_COMPACT=0/false/off: force the client arm; =1/true/on:+ // force the server arm. Unset → #compact-ab assignment decides.if (environ_map.get("GRAFF_SERVER_COMPACT")) |v| {const off = std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "off");- @import("agent_server_compact.zig").g_server_compact_override = !off;+ server_compact.g_server_compact_override = !off;}ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;// GRAFF_WS_FORCE_FAIL_ONCE proves a clean retry; the counted sibling proves@@ -152,6 +153,9 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out: *Io.Writer, flags: args.Flags, use_color: bool, json_mode: bool, cwd_display: []const u8) !ThemeSetup {try applyEnvKnobs(arena, environ_map);+ // #compact-ab: bucket this install into a compaction arm once per process.+ // After applyEnvKnobs so GRAFF_SERVER_COMPACT wins and skips assignment.+ server_compact.assignArm(io, arena, @import("keys_cli.zig").homeEnv(environ_map) orelse "");skills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connectanim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choiceanim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color theme