Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(codex): previous_response_id delta transport — stop resending full history over the WS

justrachb109ce71a60d
diff --git a/src/agent.zig b/src/agent.zig
index d3ddbeb1..08dadb39 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -26,6 +26,7 @@ const provider_mod = @import("provider.zig");
const Provider = provider_mod.Provider;
const ReasoningEffort = main_mod.ReasoningEffort;
+const ws = @import("ws.zig"); // codex Responses WS transport (delta continuation held across a turn)
const mcp = @import("mcp.zig");
const approvals_mod = @import("approvals.zig");
const trace = @import("trace.zig");
@@ -86,6 +87,12 @@ pub const Agent = struct {
client: *std.http.Client,
provider: Provider,
messages: std.json.Array,
+ // Codex Responses WS delta transport: one WS held across a turn's tool loop,
+ // sending previous_response_id + only the new items instead of the full
+ // history each step. Reset per turn by runTurn via closeCodexWs.
+ codex_ws: ?*ws.WsClient = null,
+ codex_prev_id: ?[]const u8 = null, // last response.id (gpa-owned); null = re-anchor with full input
+ codex_sent_upto: usize = 0, // messages the server already holds; delta = messages[codex_sent_upto..]
sub: bool,
label: []const u8,
out: ?*Io.Writer,
@@ -266,7 +273,24 @@ 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).
+ pub fn closeCodexWs(self: *Agent) void {
+ if (self.codex_ws) |c| {
+ c.deinit(self.gpa);
+ self.codex_ws = null;
+ }
+ if (self.codex_prev_id) |p| {
+ self.gpa.free(p);
+ self.codex_prev_id = null;
+ }
+ self.codex_sent_upto = 0;
+ }
+
pub fn runTurn(self: *Agent) anyerror![]const u8 {
+ self.closeCodexWs(); // fresh codex WS session per turn
+ defer self.closeCodexWs();
self.completed = null;
if (!self.sub) esc_cancel.store(false, .release); // fresh turn, no stale cancel
while (true) {
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index 231bfa94..a0685e4e 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -336,6 +336,18 @@ test "cleanUserTurn: plain user text yes; assistant/tool_result no" {
try std.testing.expect(!cleanUserTurn(tr));
}
+test "closeCodexWs resets the delta session state + frees the response id (codex-ws)" {
+ var agent: Agent = undefined;
+ agent.gpa = std.testing.allocator;
+ agent.codex_ws = null; // no live WsClient to deinit in a unit test
+ agent.codex_prev_id = try std.testing.allocator.dupe(u8, "resp_abc123"); // must be freed (leak-checked)
+ agent.codex_sent_upto = 5;
+ agent.closeCodexWs();
+ try std.testing.expect(agent.codex_prev_id == null); // freed + nulled
+ try std.testing.expectEqual(@as(usize, 0), agent.codex_sent_upto); // delta boundary reset
+ try std.testing.expect(agent.codex_ws == null);
+}
+
test "emergencyCutIndex: cuts at a clean user turn at/after the midpoint" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/agent_request.zig b/src/agent_request.zig
index eeb747fa..48ee9020 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -349,6 +349,7 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
// Collect the done-items and synthesize a {output, usage} object.
var items = std.json.Array.init(self.arena);
var usage: ?Value = null;
+ var resp_id: ?[]const u8 = null; // response.id, for previous_response_id delta continuation (#codex-ws)
var saw_completed = false;
var err_msg: ?[]const u8 = null;
var it = std.mem.tokenizeScalar(u8, body, '\n');
@@ -367,6 +368,9 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
saw_completed = true;
if (v.object.get("response")) |r| if (r == .object) {
if (r.object.get("usage")) |u| usage = u;
+ if (r.object.get("id")) |idv| if (idv == .string) {
+ resp_id = idv.string;
+ };
};
} else if (std.mem.eql(u8, t.string, "response.failed") or std.mem.eql(u8, t.string, "error")) {
err_msg = errorMessage(v.object) orelse "codex stream reported a failure";
@@ -376,6 +380,7 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
var resp: std.json.ObjectMap = .empty;
try resp.put(self.arena, "output", .{ .array = items });
if (usage) |u| try resp.put(self.arena, "usage", u);
+ if (resp_id) |rid| try resp.put(self.arena, "id", .{ .string = rid });
return .{ .ok = resp };
}
if (err_msg) |m| return .{ .err = m };
@@ -546,8 +551,22 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
// returned encrypted and passed back for cross-turn continuity.
try s.objectField("instructions");
try s.write(self.systemPrompt());
+ // 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
+ // backend rejects → WriteFailed). Full input otherwise (first turn/SSE).
+ if (self.codex_ws != null) if (self.codex_prev_id) |pid| {
+ try s.objectField("previous_response_id");
+ try s.write(pid);
+ };
try s.objectField("input");
- try s.write(Value{ .array = self.messages });
+ if (self.codex_ws != null and self.codex_prev_id != null and self.codex_sent_upto <= self.messages.items.len) {
+ 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 });
+ } else {
+ try s.write(Value{ .array = self.messages });
+ }
if (tools) |t| {
try s.objectField("tools");
try s.print("{s}", .{t});
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 1111cd3a..9328e34b 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -66,6 +66,17 @@ 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.
+ if (self.codex_ws != null) {
+ self.codex_sent_upto = self.messages.items.len;
+ 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;
+ };
+ }
+
if (calls.items.len > 0) {
const results = try self.runTools(calls.items);
for (calls.items, results) |call, r| {
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index b847f525..b422dfae 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -134,12 +134,20 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
defer self.spinnerStop();
if (self.tracer) |tr| tr.note("ws", "connecting");
- var client = ws.WsClient.connect(gpa, self.io, url, false, &headers) catch |e| {
- if (self.tracer) |tr| tr.note("ws", @errorName(e));
- return e;
- };
- defer client.deinit(gpa);
- if (self.tracer) |tr| tr.note("ws", "connected");
+ // Hold ONE WS across the turn's tool loop (codex-style): the first request
+ // dials; subsequent requests reuse it and send previous_response_id + delta.
+ // The open connection IS the sticky context (no x-codex-turn-state to echo).
+ if (self.codex_ws == null) {
+ self.codex_ws = ws.WsClient.connect(gpa, self.io, url, false, &headers) catch |e| {
+ if (self.tracer) |tr| tr.note("ws", @errorName(e));
+ return e;
+ };
+ if (self.tracer) |tr| tr.note("ws", "connected");
+ } else if (self.tracer) |tr| tr.note("ws", "reuse (delta)");
+ const client = self.codex_ws.?;
+ // Any error → close + reset the session so the next request re-anchors (fresh
+ // WS full history, or SSE fallback via postLive's ws_off path). Never leaks.
+ errdefer self.closeCodexWs();
try client.sendText(frame);
var full: Io.Writer.Allocating = .init(gpa);
@@ -186,6 +194,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
}
}
if (fbuf.items.len == 0) continue :stream;
+
// Wrap the ws frame as an SSE data: line so parseResponses/isStreamEnd
// (shared with the SSE path) handle reassembly + completion.
try full.writer.writeAll("data: ");