graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(codex): chain previous_response_id across user turns
justrach42b52c5993ee
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex a5b5ae49..99ebbbdd 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -10,7 +10,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 499,+ "test_count_baseline": 502,"required_invariants": [{"id": "goal-epochs",diff --git a/src/agent.zig b/src/agent.zigindex 87039413..fe9fc008 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -80,11 +80,12 @@ pub const Agent = struct {subagent_provider: ?Provider = null, // optional model pin for every direct child/workflow/judgesubagent_cross_provider: bool = false, // user explicitly allowed the pin to cross a provider/data boundarymessages: std.json.Array,- // Codex Responses WS delta transport: one WS held across a turn's tool loop,- // sending previous_response_id + only new items. Reset by closeCodexWs.+ // Codex Responses WS delta transport: one WS held ACROSS user turns (codex_chain.zig), sending previous_response_id + only new items. Reset by closeCodexWs.codex_ws: ?*ws.WsClient = null,codex_prev_id: ?[]const u8 = null, // last response.id (gpa-owned); null = re-anchor with full inputcodex_sent_upto: usize = 0, // messages the server already holds; delta = messages[codex_sent_upto..]+ codex_chain_rewrites: u32 = 0, // history_rewrites when the chain was anchored; a later compaction/trim invalidates it+ codex_props_fp: u64 = 0, // request properties the server anchored on (model/effort/fast/tools/instructions)codex_ws_used_ms: i64 = 0, // .awake-clock ms of the WS's last successful use; gates the idle preemptive re-anchor (#codex-ws)sub: bool,label: []const u8,@@ -351,9 +352,9 @@ pub const Agent = struct {/// Run until the model stops (or, in strict mode, calls/// attempt_completion). Returns the final assistant text (arena-owned).- /// Close the held codex Responses WS session and reset the delta state. Called- /// at both ends of runTurn so each turn gets a fresh connection and re-anchors- /// with full input (the server only holds state within one live connection).+ /// Close the held codex Responses WS session and reset the delta state, so the+ /// next request re-anchors with full input. The chain now spans user turns+ /// (codex_chain.zig guards it), so this is for errors, idle and compaction.pub fn closeCodexWs(self: *Agent) void {if (self.codex_ws) |c| {c.deinit(self.gpa);@@ -370,8 +371,7 @@ pub const Agent = struct {// Defensive for restored/embedded agents whose provider was assigned// directly instead of going through providers.applyProvider.try self.ensureRootTools(self.provider.kind);- self.closeCodexWs(); // fresh codex WS session per turn- defer self.closeCodexWs();+ // No per-turn teardown: the socket and the chain span user turns, guarded by codex_chain.usable instead.self.completed = null;if (!self.sub) esc_cancel.store(false, .release); // fresh turn, no stale cancelwhile (true) {diff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex 4ab5dc7f..2dd88e9b 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -9,6 +9,7 @@ const max_tokens = main_mod.max_tokens;const Agent = @import("agent.zig").Agent;const serde = @import("serde.zig");const http_headers = @import("http_headers.zig");+const codex_chain = @import("codex_chain.zig");const pricing = @import("pricing.zig");const writeAnthropicMessages = serde.writeAnthropicMessages;const writeAnthropicTools = serde.writeAnthropicTools;@@ -185,12 +186,15 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo// send previous_response_id + only the items the server does not yet// hold, instead of the full history (avoids the huge frame that the// backend rejects → WriteFailed). Full input otherwise (first turn/SSE).- if (self.codex_ws != null) if (self.codex_prev_id) |pid| {+ // ONE gate for both fields: emitting previous_response_id beside a full+ // input would make the server re-prepend a history we also sent.+ const chain = codex_chain.chainUsable(self);+ if (chain) {try s.objectField("previous_response_id");- try s.write(pid);- };+ try s.write(self.codex_prev_id.?);+ }try s.objectField("input");- if (self.codex_ws != null and self.codex_prev_id != null and self.codex_sent_upto <= self.messages.items.len) {+ if (chain) {var delta = std.json.Array.init(self.arena);for (self.messages.items[self.codex_sent_upto..]) |m| try delta.append(m);try s.write(Value{ .array = delta });diff --git a/src/agent_steps.zig b/src/agent_steps.zigindex a16501eb..c9117e5f 100644--- a/src/agent_steps.zig+++ b/src/agent_steps.zig@@ -20,6 +20,7 @@ const ToolCall = tools_mod.ToolCall;const messages_mod = @import("messages.zig");const util = @import("util.zig");const eval_control = @import("agent_eval_control.zig");+const codex_chain = @import("codex_chain.zig");const toolResultMessage = messages_mod.toolResultMessage;fn surfaceUnstreamedText(self: *Agent, text: []const u8) !void {@@ -78,9 +79,11 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {// Codex WS delta: the server now holds up to here (the output items appended// above). The NEXT request sends previous_response_id + only what is appended- // after this point (the tool results below). Only while the WS session lives.+ // after this point - the tool results below, and on the following USER turn+ // that turn's prompt, since the chain outlives runTurn now. Only while the WS+ // session lives; codex_chain.record stamps what the anchor is valid for.if (self.codex_ws != null) {- self.codex_sent_upto = self.messages.items.len;+ codex_chain.record(self);if (response.get("id")) |idv| if (idv == .string and idv.string.len > 0) {if (self.codex_prev_id) |old| self.gpa.free(old);self.codex_prev_id = self.gpa.dupe(u8, idv.string) catch null;diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 34f3159b..389c68ea 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -23,6 +23,7 @@ const agent_mod = @import("agent.zig");const Agent = agent_mod.Agent;const ws = @import("ws.zig");+const http_headers = @import("http_headers.zig");const term = @import("term.zig");const tty = term.tty;@@ -176,10 +177,10 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {defer gpa.free(frame);const bearer = try std.fmt.allocPrint(arena, "Bearer {s}", .{provider.api_key});- var rnd: [16]u8 = undefined;- self.io.random(&rnd);- const hex = std.fmt.bytesToHex(rnd, .lower);- const sid = try std.fmt.allocPrint(arena, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] });+ // The SAME per-process session id the HTTP path sends, not a fresh one per+ // connect: this is what the backend partitions its prompt cache on, so a+ // new id per socket handed every re-anchor a cold partition.+ const sid = http_headers.sessionId(self.io);const headers = [_]ws.Header{.{ .name = "Authorization", .value = bearer },.{ .name = "chatgpt-account-id", .value = provider.account },diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex 83d08f52..999d6791 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -5,6 +5,7 @@ const Agent = @import("agent.zig").Agent;const textMessage = @import("messages.zig").textMessage;const ws = @import("ws.zig");const agent_ws = @import("agent_ws.zig");+const codex_chain = @import("codex_chain.zig");test "closeCodexWs resets the delta session state + frees the response id (codex-ws)" {var agent: Agent = undefined;@@ -85,6 +86,10 @@ test "buildBody (.responses): delta while WS live; full input after closeCodexWs.codex_prev_id = try std.testing.allocator.dupe(u8, "resp_live"),.codex_sent_upto = 2, // server already holds messages[0..2]; delta = [2..]};+ // Anchor the chain the way codex_chain.record does after a response: the+ // delta is only sent when the request properties still match the ones the+ // server produced that response under.+ agent.codex_props_fp = codex_chain.propsFor(&agent);const delta_body = try agent.buildBody(null, false, false, false);defer std.testing.allocator.free(delta_body);@@ -121,6 +126,71 @@ test "buildBody (.responses): delta while WS live; full input after closeCodexWstry std.testing.expect(std.mem.indexOf(u8, title_body, "max_output_tokens") == null); // #codex: no top-level max_output_tokens even for the bounded title task}+// The chain now outlives runTurn, so buildBody is the last line of defence: a+// delta keyed to a history the server no longer mirrors would make it prepend+// a conversation that no longer exists. Each guard is exercised through the+// REAL body, not just the pure predicate.+test "buildBody (.responses): a cross-turn delta re-anchors when history or settings move" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ var msgs = std.json.Array.init(a);+ try msgs.append(try textMessage(a, "user", "first"));+ try msgs.append(try textMessage(a, "assistant", "second"));++ var dummy_ws: ws.WsClient = undefined; // buildBody only checks != null+ var agent: Agent = .{+ .gpa = std.testing.allocator,+ .arena = a,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://x/responses", .api_key = "k", .model = "gpt-5.6", .context = 270_000 },+ .messages = msgs,+ .sub = false,+ .label = "",+ .out = null,+ .codex_ws = &dummy_ws,+ .codex_prev_id = try std.testing.allocator.dupe(u8, "resp_turn1"),+ };+ defer std.testing.allocator.free(agent.codex_prev_id.?);+ codex_chain.record(&agent); // server holds all 2 messages after turn 1++ // The NEXT user turn appends a prompt. This is the whole point: before,+ // runTurn's teardown made this a full re-upload plus a fresh handshake.+ try agent.messages.append(try textMessage(a, "user", "second turn prompt"));+ const chained = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(chained);+ try std.testing.expect(std.mem.indexOf(u8, chained, "\"previous_response_id\":\"resp_turn1\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, chained, "second turn prompt") != null);+ try std.testing.expect(std.mem.indexOf(u8, chained, "\"first\"") == null); // the win: not re-uploaded++ // A compaction rewrote history in place. The length can still look fine, so+ // only the rewrite counter catches it.+ agent.history_rewrites += 1;+ const after_compact = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(after_compact);+ try std.testing.expect(std.mem.indexOf(u8, after_compact, "previous_response_id") == null);+ try std.testing.expect(std.mem.indexOf(u8, after_compact, "\"first\"") != null); // full resend+ agent.history_rewrites -= 1;++ // /effort changed between turns: chaining would attribute turn 2 to a+ // response the server generated under a different reasoning budget.+ agent.reasoning = .high;+ const after_effort = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(after_effort);+ try std.testing.expect(std.mem.indexOf(u8, after_effort, "previous_response_id") == null);+ agent.reasoning = .medium;++ // /clear reinitializes messages, leaving the history SHORTER than the+ // watermark: the server's copy is no longer a prefix of ours.+ agent.messages = std.json.Array.init(a);+ const after_clear = try agent.buildBody(null, false, false, false);+ defer std.testing.allocator.free(after_clear);+ try std.testing.expect(std.mem.indexOf(u8, after_clear, "previous_response_id") == null);+ try std.testing.expect(std.mem.indexOf(u8, after_clear, "second turn prompt") == null); // cleared, not resurrected+}+// Regression (#codex gpt-5.6): the Codex Responses backend rejects a top-level// `max_output_tokens` ("Unsupported parameter: max_output_tokens"), which hard-// failed EVERY turn including the title task. openai/codex never sends it at thediff --git a/src/codex_chain.zig b/src/codex_chain.zignew file mode 100644index 00000000..10029ed3--- /dev/null+++ b/src/codex_chain.zig@@ -0,0 +1,134 @@+//! Cross-turn `previous_response_id` chaining for the Codex Responses API.+//!+//! The backend holds the conversation behind a response id, so a follow-up+//! request can send `previous_response_id` plus ONLY the new items instead of+//! the whole history. graff already did that inside one turn's tool loop, but+//! runTurn tore the session down at both ends, so every user turn paid a fresh+//! handshake plus a full re-upload of the conversation. With `store:false` the+//! retained encrypted reasoning items are part of that resend, which is why the+//! cost grows per turn rather than staying flat.+//!+//! openai/codex keeps the socket across turns and GUARDS the chain instead of+//! tearing it down: `responses_request_properties_match` compares the request+//! properties, and `get_incremental_items` returns None - meaning full resend -+//! when the new input is not a clean extension of the last one. That guard is+//! what makes chaining safe without enumerating every place history can change.+//! `usable` below is the same idea written with state graff already tracks:+//!+//! - the history only GREW since we last sent (a /clear, /new or a trim+//! leaves it shorter, so the server's copy is not a prefix of ours),+//! - no compaction or emergency trim rewrote it in place (history_rewrites),+//! - the properties the server anchored the response on are unchanged.+//!+//! The per-request passes that also mutate history - capOversizedToolOutputs+//! and normalizeResponsesHistory - need no guard: both run before an item is+//! first sent and are idempotent afterwards, so neither rewrites a sent prefix.++const std = @import("std");+const Agent = @import("agent.zig").Agent;++/// The live agent's chain-invariant properties. Both the check and the record+/// go through here, so they can never disagree about what was compared.+pub fn propsFor(self: *const Agent) u64 {+ return propsFp(self.provider.model, @tagName(self.reasoning), self.fast, self.toolsJson(), self.systemPrompt());+}++/// May this request chain onto the held response instead of re-anchoring?+pub fn chainUsable(self: *const Agent) bool {+ return usable(+ self.codex_ws != null,+ self.codex_prev_id != null,+ self.codex_sent_upto,+ self.messages.items.len,+ self.history_rewrites,+ self.codex_chain_rewrites,+ propsFor(self),+ self.codex_props_fp,+ );+}++/// Anchor the chain on a response the server just produced: it now holds every+/// message we have, under these properties and this history generation.+pub fn record(self: *Agent) void {+ self.codex_sent_upto = self.messages.items.len;+ self.codex_chain_rewrites = self.history_rewrites;+ self.codex_props_fp = propsFor(self);+}++/// Fingerprint the request properties the server anchored its response on.+/// Codex compares these explicitly (`responses_request_properties_match`)+/// because chaining onto a response produced under a different model or+/// reasoning effort silently mixes two configurations into one conversation -+/// and `/model` and `/effort` can both change mid-session.+pub fn propsFp(model: []const u8, effort: []const u8, fast: bool, tools: []const u8, instructions: []const u8) u64 {+ var h = std.hash.Wyhash.init(0);+ // Length-prefixed rather than delimiter-joined: a model or effort name+ // containing the delimiter would otherwise alias onto another pairing.+ for ([_][]const u8{ model, effort, tools, instructions }) |part| {+ h.update(std.mem.asBytes(&part.len));+ h.update(part);+ }+ h.update(&[_]u8{@intFromBool(fast)});+ return h.final();+}++/// Whether the next request may chain (`previous_response_id` + delta input)+/// rather than re-anchoring with the full history. Pure, so the whole decision+/// table is testable without a socket or a provider.+pub fn usable(+ has_ws: bool,+ has_prev_id: bool,+ sent_upto: usize,+ len: usize,+ rewrites: u32,+ chain_rewrites: u32,+ props_now: u64,+ props_then: u64,+) bool {+ if (!has_ws or !has_prev_id) return false;+ // The server holds messages[0..sent_upto]. If our history is now SHORTER+ // than that, it is not an extension of what the server has - /clear and+ // /new reinitialize the array, and a trim can cut below the watermark.+ if (sent_upto > len) return false;+ // compact() and emergencyTrim() rewrite history IN PLACE, so the length+ // check alone would miss them: the array can be the same size or larger+ // while its early items are a summary the server never saw.+ if (rewrites != chain_rewrites) return false;+ return props_now == props_then;+}++test "propsFp: model, effort, fast, tools and instructions each break the chain" {+ const base = propsFp("gpt-5.6", "medium", false, "[]", "sys");+ try std.testing.expectEqual(base, propsFp("gpt-5.6", "medium", false, "[]", "sys")); // stable+ // Each field independently re-anchors: chaining onto a response produced+ // under different settings mixes configurations mid-conversation.+ try std.testing.expect(base != propsFp("gpt-5.6-codex", "medium", false, "[]", "sys"));+ try std.testing.expect(base != propsFp("gpt-5.6", "high", false, "[]", "sys"));+ try std.testing.expect(base != propsFp("gpt-5.6", "medium", true, "[]", "sys")); // /fast+ try std.testing.expect(base != propsFp("gpt-5.6", "medium", false, "[{}]", "sys")); // MCP server connected+ try std.testing.expect(base != propsFp("gpt-5.6", "medium", false, "[]", "sys2")); // /ultracode+ // Length-prefixing: "ab"+"c" must not collide with "a"+"bc".+ try std.testing.expect(propsFp("ab", "c", false, "", "") != propsFp("a", "bc", false, "", ""));+}++test "usable: chains only on a clean extension of what the server holds" {+ // The happy path: socket live, id held, history grew, nothing rewrote it.+ try std.testing.expect(usable(true, true, 4, 6, 0, 0, 7, 7));+ try std.testing.expect(usable(true, true, 4, 4, 0, 0, 7, 7)); // no new items is still an extension++ // No transport or no anchor -> the request must carry the full history.+ try std.testing.expect(!usable(false, true, 4, 6, 0, 0, 7, 7));+ try std.testing.expect(!usable(true, false, 4, 6, 0, 0, 7, 7));++ // /clear and /new reinitialize messages: the server's copy is no longer a+ // prefix of ours, and chaining would silently resurrect the cleared turns.+ try std.testing.expect(!usable(true, true, 4, 0, 0, 0, 7, 7));+ try std.testing.expect(!usable(true, true, 4, 3, 0, 0, 7, 7));++ // compact()/emergencyTrim() rewrite in place, so the length can still look+ // fine while the early items are a summary the server never received.+ try std.testing.expect(!usable(true, true, 4, 9, 1, 0, 7, 7));++ // /model or /effort changed between turns.+ try std.testing.expect(!usable(true, true, 4, 6, 0, 0, 8, 7));+}