graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
//! 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 {
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
defer arena_state.deinit();
return propsFp(self.provider.model, @tagName(self.reasoning), self.fast, wireTools(self, arena_state.allocator()), self.systemPrompt());
}
/// The `tools` a request carries. Where loads ride additional_tools items
/// (ADR 0221) the loaded tail stays off the wire, so a load does not end the
/// chain: its announcement travels in the delta instead.
fn wireTools(self: *const Agent, arena: std.mem.Allocator) []const u8 {
const additional_tools = @import("additional_tools.zig");
const tools = self.toolsJson();
if (self.sub or !additional_tools.active(self.provider)) return tools;
return additional_tools.stripTail(self, arena, tools);
}
/// GRAFF_CODEX_FULL_RESEND=1 (armed by session_settings.applyEnvKnobs):
/// never chain — every turn sends the full input, opencode's only shape
/// (they carry no previous_response_id at all). Experiment flag for the
/// cache-hit work: chained turns read back ~0 cached tokens, so the delta
/// optimization trades cheap cache reads for full-price re-uploads.
pub var g_force_full_resend = false;
/// xAI on-socket chaining (`previous_response_id` + delta input on the held
/// socket). Off by default: with store:false a chained response.create gets
/// one frame and then silence until the stall watchdog fires (~2 min), both on
/// a normal turn and after a generate:false warmup; store:true chains fine.
/// GRAFF_XAI_WS_CHAIN=1 opts in. A not-found, 25-min cap, or drop re-anchors
/// with full input (shouldDropChain).
pub var g_xai_ws_chain = false;
/// May this request chain onto the held response instead of re-anchoring?
/// Brands whose Responses WS holds prior state in-memory and accept
/// `previous_response_id` + delta input (including store:false / ZDR).
/// The ChatGPT plan route (ADR 0221) does, on the socket only.
pub fn chainBrandOk(provider_id: []const u8) bool {
return std.mem.eql(u8, provider_id, "codex") or std.mem.eql(u8, provider_id, "xai") or
std.mem.eql(u8, provider_id, "chatgpt-new");
}
/// A failed turn must drop the chain: not-found (ZDR / store:false evict),
/// the 25-minute connection cap, or a generic previous_response_id reject.
pub fn shouldDropChain(message: []const u8, code: ?[]const u8) bool {
// A delta chained onto rejected opaque state cannot repair that state.
// Re-anchor once with the complete canonical window instead; if that is
// rejected too, shouldReanchorRequest is false and the error surfaces.
if (@import("compaction_window.zig").rejectedByProvider(message, code)) return true;
if (code) |c| {
if (std.mem.indexOf(u8, c, "previous_response_not_found") != null) return true;
if (std.mem.indexOf(u8, c, "websocket_connection_limit_reached") != null) return true;
}
if (std.mem.indexOf(u8, message, "previous_response_not_found") != null) return true;
if (std.mem.indexOf(u8, message, "websocket connection limit") != null) return true;
if (std.mem.indexOf(u8, message, "previous_response_id") != null) return true;
return false;
}
/// Re-anchor only when the rejected request actually used the server-side
/// chain. A retained codex_prev_id is not enough: property changes and the
/// full-resend experiment deliberately emit full input while keeping it held.
pub fn shouldReanchorRequest(body: []const u8, message: []const u8, code: ?[]const u8) bool {
return std.mem.indexOf(u8, body, "\"previous_response_id\"") != null and shouldDropChain(message, code);
}
pub fn chainUsable(self: *const Agent) bool {
if (g_force_full_resend) return false;
const xai_chain = g_xai_ws_chain and std.mem.eql(u8, self.provider.id, "xai");
const always = std.mem.eql(u8, self.provider.id, "codex") or std.mem.eql(u8, self.provider.id, "chatgpt-new");
if (!always and !xai_chain) return false;
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));
}
test "chainUsable: xAI chains on a held socket when opted in" {
try std.testing.expect(!g_xai_ws_chain); // off by default (store:false chained turns stall)
const saved = g_xai_ws_chain;
defer g_xai_ws_chain = saved;
g_xai_ws_chain = true;
try std.testing.expect(usable(true, true, 1, 2, 0, 0, 7, 7));
}
test "chainBrandOk: xAI, codex and the ChatGPT plan chain; anthropic does not" {
try std.testing.expect(chainBrandOk("codex"));
try std.testing.expect(chainBrandOk("xai"));
try std.testing.expect(chainBrandOk("chatgpt-new"));
try std.testing.expect(!chainBrandOk("anthropic"));
try std.testing.expect(!chainBrandOk("kimi"));
}
test "shouldDropChain: not-found and 25-minute cap evict the in-memory id" {
try std.testing.expect(shouldDropChain("Previous response with id 'resp_abc' not found.", "previous_response_not_found"));
try std.testing.expect(shouldDropChain("Responses websocket connection limit reached (25 minutes).", "websocket_connection_limit_reached"));
try std.testing.expect(shouldDropChain("unsupported previous_response_id", null));
try std.testing.expect(!shouldDropChain("rate limited", "rate_limit_exceeded"));
}
test "shouldReanchorRequest requires a rejected previous_response_id request" {
const chained = "{\"previous_response_id\":\"resp_1\",\"input\":[]}";
const full = "{\"input\":[]}";
try std.testing.expect(shouldReanchorRequest(chained, "missing", "previous_response_not_found"));
try std.testing.expect(shouldReanchorRequest(chained, "unsupported previous_response_id", "invalid_request_error"));
try std.testing.expect(!shouldReanchorRequest(full, "missing", "previous_response_not_found"));
try std.testing.expect(!shouldReanchorRequest(chained, "bad request", "invalid_request_error"));
}
test "rejected encrypted state earns one full resend, never a retry loop" {
const chained = "{\"previous_response_id\":\"resp_1\",\"input\":[]}";
const full = "{\"input\":[{\"type\":\"compaction\"}]}";
const msg = "Encrypted content could not be decrypted or parsed.";
try std.testing.expect(shouldReanchorRequest(chained, msg, "invalid_encrypted_content"));
// Once the request already carries full input there is no new recovery
// shape to try; the terminal diagnostic must reach the user instead.
try std.testing.expect(!shouldReanchorRequest(full, msg, "invalid_encrypted_content"));
try std.testing.expect(!shouldReanchorRequest(chained, msg, "invalid_request_error"));
}