Skip to content

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

Python

Gemini: continue the stored Interaction instead of replaying history

justrach3d7484b1809f
diff --git a/docs/adr/0271-gemini-interactions-continue-the-stored-interaction.md b/docs/adr/0271-gemini-interactions-continue-the-stored-interaction.md
new file mode 100644
index 00000000..f15e2816
--- /dev/null
+++ b/docs/adr/0271-gemini-interactions-continue-the-stored-interaction.md
@@ -0,0 +1,48 @@
+# 0271. Gemini continues the stored Interaction instead of replaying history
+
+Status: accepted 2026-10-08
+
+## Context
+
+The direct Google provider speaks the Interactions API. graff sent
+`store:false` and the whole step list on every request, so a long session paid
+for its full history as input on every call; implicit caching only discounted
+part of it. The endpoint can hold the conversation itself: a request that names
+a stored Interaction in `previous_interaction_id` sends only the steps added
+since, and the endpoint reports only those as `total_input_tokens` (the whole
+prompt is reported separately as `raw_prompt_token`). In a probe, a 38k-token
+history continued with a short question reported 134 input tokens.
+
+The earlier writer skipped this because the id had to stay consistent with
+graff's own history through compaction, trims and edits.
+
+## Decision
+
+Interactions requests are stored (the endpoint's default) and continue the last
+stored Interaction whenever graff's history is a clean extension of what the
+server holds. `interactions_chain.zig` owns the rule:
+
+- When an answer arrives, graff records its id, how many messages the server
+ now holds, and a hash of those messages' wire form.
+- A request chains only if the same prefix still hashes the same under the
+ same model and there is at least one new step to send. Anything else — a
+ /clear, a rewind, a compaction or trim, an in-place edit of an earlier step,
+ a model switch, a message appended while a request was in flight — sends the
+ full history, which anchors a new chain.
+- A chained request the endpoint rejects (expired or unknown id) is resent once
+ with the full history.
+- `system_instruction`, `tools` and `generation_config` are sent on every
+ request, as the endpoint does not carry them over.
+- The context meter reads `raw_prompt_token`, so compaction still sees the real
+ window size; cost reads what was billed; the held prefix shows as a cache read.
+
+`GRAFF_INTERACTIONS_STORE=0` (or off/false/no) restores the stateless shape:
+`store:false` and a full replay on every request.
+
+## Consequences
+
+Long Gemini sessions stop re-sending their history, which cuts input billed per
+call to roughly the new steps. Interactions are now retained by Google under its
+storage policy; users who must not have that set `GRAFF_INTERACTIONS_STORE=0`.
+Hashing the history costs one serialization pass per request, which the full
+replay already paid.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 92ceaf64..3aed0ab3 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -289,6 +289,7 @@ record only when you need the evidence or the edge cases.
| [0260](0260-clef-compaction-replaces-client-summary.md) | `GRAFF_CLEF_COMPACT=1` routes client-summary compactions through the gateway's server-side `POST /v1/compact` (Clef decision-model pruning, text verbatim); OpenAI-family server paths are untouched and any failure falls back to the summary. |
| [0261](0261-client-summary-stays-the-compactor.md) | The client summary stays the compactor: `GRAFF_CLEF_COMPACT` defaults off (Clef rarely pruned and mostly fell back to the summary in measurement); first-party Responses routes use only the provider's own compaction. Supersedes 0260's default. |
| [0270](0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.md) | A stdio MCP server whose connection closes goes back to dormant with its launch config and restarts on its next call; the failed call is never replayed, and after two restarts in a session its tools are withdrawn as before. |
+| [0271](0271-gemini-interactions-continue-the-stored-interaction.md) | Direct Gemini (Interactions) requests are stored and continue the last Interaction with `previous_interaction_id` plus only the new steps while a content hash proves graff's history extends it; any rewrite, model switch or rejected id falls back to a full replay. `GRAFF_INTERACTIONS_STORE=0` keeps it stateless. |
## When to write one
diff --git a/src/agent.zig b/src/agent.zig
index 241ff6c9..610628bc 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -96,6 +96,7 @@ pub const Agent = struct {
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)
codex_ws_opened_ms: i64 = 0, // first connect time; xAI/codex WS hard-cap is 25 minutes
+ ix_chain: @import("interactions_chain.zig").Chain = .{}, // Interactions previous_interaction_id chain (interactions_chain.zig)
sub: bool,
/// This agent is served NO tools at all — the `tools` field is omitted
/// from the request rather than sent empty, which every provider accepts.
diff --git a/src/agent_overflow.zig b/src/agent_overflow.zig
index 98603cca..6e771d49 100644
--- a/src/agent_overflow.zig
+++ b/src/agent_overflow.zig
@@ -220,7 +220,9 @@ pub fn readCompletion(kind: Provider.Kind, root: std.json.ObjectMap) Completion
// than a bare thought counts as content the turn actually produced.
.interactions => {
if (usageOf(root)) |u| {
- c.input_tokens = nonNegative(usageInt(u, "total_input_tokens"));
+ // A continued Interaction reports only its new steps as input;
+ // raw_prompt_token is the whole prompt the window holds.
+ c.input_tokens = nonNegative(@max(usageInt(u, "total_input_tokens"), usageInt(u, "raw_prompt_token")));
c.output_tokens = nonNegative(usageInt(u, "total_output_tokens") +| usageInt(u, "total_thought_tokens"));
}
if (str(root, "status")) |s| c.stop = stopFromString(kind, s);
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 2beda2e0..a85a8bf3 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -499,6 +499,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
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 "";
const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;
+ if (@import("interactions_chain.zig").dropRejected(self, body)) continue; // stored Interaction gone → full replay
if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: streamed error event overflow (by code or phrasing) → trim + retry
if (policy.retryWithout(self, emsg, &force, &stream_usage)) continue; // ADR 0219: Anthropic errors take the ladder too
if (try policy.afterServerErrorOrParseReject(self, etype, ecode, emsg, &server_retries, &gw_retry)) continue;
@@ -549,6 +550,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
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 "";
const ecode = if (eo) |e| (if (e.get("code")) |cv| (if (cv == .string) cv.string else null) else null) else null;
+ if (@import("interactions_chain.zig").dropRejected(self, body)) continue; // stored Interaction gone → full replay
if (recoverContextOverflow(self, emsg, ecode, &context_retried)) continue; // #193/#203: {"type":"error"} overflow (by code or phrasing) → trim + retry
if (policy.retryWithout(self, emsg, &force, &stream_usage)) continue; // ADR 0219: Anthropic errors take the ladder too
if (try policy.afterServerErrorOrParseReject(self, etype, ecode, emsg, &server_retries, &gw_retry)) continue;
@@ -557,6 +559,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
return error.ApiError;
};
if (apiErrorMessage(root)) |msg| {
+ if (@import("interactions_chain.zig").dropRejected(self, body)) continue; // stored Interaction gone → full replay
if (policy.retryWithout(self, msg, &force, &stream_usage)) continue;
// #148: a stale login token 401s here with the provider's "API Key
// invalid/expired"; adopt a newer on-disk token or force a refresh
diff --git a/src/interactions_chain.zig b/src/interactions_chain.zig
new file mode 100644
index 00000000..354d7c86
--- /dev/null
+++ b/src/interactions_chain.zig
@@ -0,0 +1,277 @@
+//! Server-side state on Google's Interactions wire (ADR 0271).
+//!
+//! A stored Interaction keeps every step it was sent and every step it
+//! produced. A follow-up that names it in `previous_interaction_id` sends only
+//! the steps added since, and the endpoint reports — and bills — only those as
+//! input: a 38k-token history continued with a short question comes back as
+//! ~130 `total_input_tokens`, with the whole prompt in `raw_prompt_token`.
+//! Before this, graff sent `store:false` and replayed every step every request.
+//!
+//! The chain is used only while graff's history is a clean extension of what
+//! the server holds, and the guard is content rather than bookkeeping:
+//! `history_fp` hashes the wire form of messages[0..upto] when the chain is
+//! recorded, and a request chains only when that prefix still hashes the same
+//! under the same model. A /clear, a rewind, a compaction, a trim, an in-place
+//! edit of an earlier step, or a model switch therefore sends a full replay,
+//! which anchors a new chain. A chained request the endpoint rejects (an
+//! expired or unknown id) is resent once as a full replay (agent_request.zig).
+//!
+//! GRAFF_INTERACTIONS_STORE=0 restores the stateless shape: `store:false` and a
+//! full replay every request, so Google keeps nothing.
+
+const std = @import("std");
+const Value = std.json.Value;
+const Wyhash = std.hash.Wyhash;
+
+const Agent = @import("agent.zig").Agent;
+
+/// Off only by GRAFF_INTERACTIONS_STORE=0 (session_settings.applyEnvKnobs).
+pub var g_store = true;
+
+const max_id = 256;
+
+pub const Chain = struct {
+ id_buf: [max_id]u8 = undefined,
+ id_len: usize = 0, // 0 = no chain: the next request is a full replay
+ upto: usize = 0, // messages the server holds behind the id
+ history_fp: u64 = 0, // hash of messages[0..upto] as written on the wire
+ model_fp: u64 = 0,
+ /// The request in flight: how many messages it carried and the hash state
+ /// after them, so recording its answer only hashes the answer's steps.
+ sent_len: usize = 0,
+ sent_state: ?Wyhash = null,
+ sent_model_fp: u64 = 0,
+
+ pub fn id(self: *const Chain) ?[]const u8 {
+ return if (self.id_len == 0) null else self.id_buf[0..self.id_len];
+ }
+
+ pub fn clear(self: *Chain) void {
+ self.id_len = 0;
+ self.upto = 0;
+ }
+};
+
+pub const Plan = struct {
+ prev_id: ?[]const u8 = null,
+ /// First message to send; 0 = full replay.
+ from: usize = 0,
+};
+
+fn modelFp(model: []const u8) u64 {
+ return Wyhash.hash(0, model);
+}
+
+/// Feed each message's wire form (session_wake.writeWire) into `h`.
+fn hashMessages(h: *Wyhash, items: []const Value) !void {
+ var buf: [1024]u8 = undefined;
+ var hw: std.Io.Writer.Hashing(Wyhash) = .initHasher(h.*, &buf);
+ for (items) |m| {
+ var s: std.json.Stringify = .{ .writer = &hw.writer };
+ try @import("session_wake.zig").writeWire(&s, m);
+ }
+ try hw.writer.flush();
+ h.* = hw.hasher;
+}
+
+fn digest(h: Wyhash) u64 {
+ var copy = h;
+ return copy.final();
+}
+
+/// Decide what the next request sends, and remember what it carried so the
+/// answer can extend the chain. Called once per body build.
+pub fn plan(self: *Agent) !Plan {
+ const c = &self.ix_chain;
+ c.sent_state = null;
+ if (!g_store) {
+ c.clear();
+ return .{};
+ }
+ const items = self.messages.items;
+ const model = modelFp(self.provider.model);
+ var h = Wyhash.init(0);
+ var out: Plan = .{};
+ var hashed: usize = 0;
+ // `upto < len`: an empty delta is not a request the endpoint accepts.
+ if (c.id_len > 0 and c.model_fp == model and c.upto < items.len) {
+ try hashMessages(&h, items[0..c.upto]);
+ hashed = c.upto;
+ if (digest(h) == c.history_fp) out = .{ .prev_id = c.id(), .from = c.upto };
+ }
+ if (out.prev_id == null) c.clear();
+ try hashMessages(&h, items[hashed..]);
+ c.sent_len = items.len;
+ c.sent_state = h;
+ c.sent_model_fp = model;
+ return out;
+}
+
+/// Anchor the chain on the Interaction that just answered: the server now
+/// holds what the request carried plus `steps`. Call before the steps are
+/// appended to history. Anything else appended in between (or a response
+/// without an id) leaves no chain, so the next request replays in full.
+pub fn record(self: *Agent, root: std.json.ObjectMap, steps: []const Value) !void {
+ const c = &self.ix_chain;
+ const state = c.sent_state orelse return;
+ c.sent_state = null;
+ c.clear();
+ if (self.messages.items.len != c.sent_len) return;
+ const id_v = root.get("id") orelse return;
+ if (id_v != .string or id_v.string.len == 0 or id_v.string.len > max_id) return;
+ var h = state;
+ try hashMessages(&h, steps);
+ @memcpy(c.id_buf[0..id_v.string.len], id_v.string);
+ c.id_len = id_v.string.len;
+ c.upto = c.sent_len + steps.len;
+ c.history_fp = digest(h);
+ c.model_fp = c.sent_model_fp;
+}
+
+/// A rejected request that named a stored Interaction: drop the chain so the
+/// rebuilt request replays in full. Bounded by construction — the rebuilt body
+/// carries no previous_interaction_id, so its own failure returns false.
+pub fn dropRejected(self: *Agent, body: []const u8) bool {
+ if (self.provider.kind != .interactions) return false;
+ if (std.mem.indexOf(u8, body, "\"previous_interaction_id\"") == null) return false;
+ self.ix_chain.clear();
+ if (self.tracer) |tr| tr.note("interactions", "chained request rejected — resending the full history");
+ return true;
+}
+
+fn testAgent(arena: std.mem.Allocator) Agent {
+ return .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = .{ .id = "google", .kind = .interactions, .auth = .goog_api_key, .url = "", .api_key = "", .model = "gemini-3.8-flash", .context = 1_000_000 },
+ .messages = std.json.Array.init(arena),
+ .sub = false,
+ .label = "",
+ .out = null,
+ };
+}
+
+fn parse(arena: std.mem.Allocator, text: []const u8) !Value {
+ return std.json.parseFromSliceLeaky(Value, arena, text, .{});
+}
+
+fn answer(arena: std.mem.Allocator, id: []const u8) !std.json.ObjectMap {
+ var root: std.json.ObjectMap = .empty;
+ try root.put(arena, "id", .{ .string = id });
+ return root;
+}
+
+/// One model turn: plan the request, then record and append the answer.
+fn turn(agent: *Agent, arena: std.mem.Allocator, id: []const u8, step_json: []const u8) !Plan {
+ var p = try plan(agent);
+ // prev_id points into the chain, which record() is about to overwrite.
+ if (p.prev_id) |held| p.prev_id = try arena.dupe(u8, held);
+ const st = try parse(arena, step_json);
+ try record(agent, try answer(arena, id), &.{st});
+ try agent.messages.append(st);
+ return p;
+}
+
+test "a turn that extends history chains and sends only the new steps" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a);
+ const steps = @import("interactions_steps.zig");
+
+ try agent.messages.append(try steps.userInput(a, "first"));
+ const p1 = try turn(&agent, a, "v1_one", "{\"type\":\"model_output\",\"content\":[{\"type\":\"text\",\"text\":\"ok\"}]}");
+ try std.testing.expect(p1.prev_id == null); // nothing stored yet: full replay
+ try std.testing.expectEqual(@as(usize, 0), p1.from);
+
+ try agent.messages.append(try steps.userInput(a, "second"));
+ const p2 = try turn(&agent, a, "v1_two", "{\"type\":\"function_call\",\"id\":\"c1\",\"name\":\"bash\",\"arguments\":{}}");
+ try std.testing.expectEqualStrings("v1_one", p2.prev_id.?);
+ try std.testing.expectEqual(@as(usize, 2), p2.from); // just "second"
+
+ // A tool result rides on the newest Interaction.
+ try agent.messages.append(try steps.functionResult(a, "c1", "bash", "out"));
+ const p3 = try plan(&agent);
+ try std.testing.expectEqualStrings("v1_two", p3.prev_id.?);
+ try std.testing.expectEqual(@as(usize, 4), p3.from);
+}
+
+test "any change to what the server holds falls back to a full replay" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const steps = @import("interactions_steps.zig");
+ const reply = "{\"type\":\"model_output\",\"content\":[{\"type\":\"text\",\"text\":\"ok\"}]}";
+
+ // An in-place edit of a sent step (compaction, a trim, a capped output).
+ var edited = testAgent(a);
+ try edited.messages.append(try steps.userInput(a, "first"));
+ _ = try turn(&edited, a, "v1_one", reply);
+ edited.messages.items[0] = try steps.userInput(a, "summary of earlier work");
+ try edited.messages.append(try steps.userInput(a, "next"));
+ try std.testing.expect((try plan(&edited)).prev_id == null);
+
+ // /clear then a history that grows back past the watermark.
+ var cleared = testAgent(a);
+ try cleared.messages.append(try steps.userInput(a, "first"));
+ _ = try turn(&cleared, a, "v1_one", reply);
+ cleared.messages.clearRetainingCapacity();
+ for ([_][]const u8{ "a", "b", "c" }) |t| try cleared.messages.append(try steps.userInput(a, t));
+ try std.testing.expect((try plan(&cleared)).prev_id == null);
+
+ // A model switch.
+ var switched = testAgent(a);
+ try switched.messages.append(try steps.userInput(a, "first"));
+ _ = try turn(&switched, a, "v1_one", reply);
+ switched.provider.model = "gemini-3.8-pro";
+ try switched.messages.append(try steps.userInput(a, "next"));
+ try std.testing.expect((try plan(&switched)).prev_id == null);
+
+ // Nothing new to send: an empty delta is never chained.
+ var idle = testAgent(a);
+ try idle.messages.append(try steps.userInput(a, "first"));
+ _ = try turn(&idle, a, "v1_one", reply);
+ try std.testing.expect((try plan(&idle)).prev_id == null);
+}
+
+test "a message appended while the request was in flight leaves no chain" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const steps = @import("interactions_steps.zig");
+ var agent = testAgent(a);
+ try agent.messages.append(try steps.userInput(a, "first"));
+ _ = try plan(&agent);
+ try agent.messages.append(try steps.userInput(a, "steer")); // the server never saw this
+ try record(&agent, try answer(a, "v1_one"), &.{});
+ try std.testing.expect(agent.ix_chain.id() == null);
+}
+
+test "the opt-out keeps every request stateless" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const steps = @import("interactions_steps.zig");
+ const saved = g_store;
+ defer g_store = saved;
+ g_store = false;
+ var agent = testAgent(a);
+ try agent.messages.append(try steps.userInput(a, "first"));
+ _ = try turn(&agent, a, "v1_one", "{\"type\":\"model_output\",\"content\":[]}");
+ try agent.messages.append(try steps.userInput(a, "next"));
+ try std.testing.expect((try plan(&agent)).prev_id == null);
+ try std.testing.expect(agent.ix_chain.id() == null);
+}
+
+test "a rejected chained request drops the chain once" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a);
+ agent.ix_chain.id_len = 3;
+ try std.testing.expect(dropRejected(&agent, "{\"previous_interaction_id\":\"v1_x\",\"input\":[]}"));
+ try std.testing.expect(agent.ix_chain.id() == null);
+ try std.testing.expect(!dropRejected(&agent, "{\"input\":[]}")); // the full replay failed on its own merits
+}
diff --git a/src/interactions_steps.zig b/src/interactions_steps.zig
index 55a08d94..4ff38890 100644
--- a/src/interactions_steps.zig
+++ b/src/interactions_steps.zig
@@ -65,15 +65,22 @@ pub fn assistantText(arena: Allocator, root: std.json.ObjectMap) ![]const u8 {
/// output, so a tally that skipped it would understate every call.
/// `total_cached_tokens` is the cached PORTION of the input, matching how the
/// other wires report a cache read.
+///
+/// A request that continued a stored Interaction reports only its new steps as
+/// `total_input_tokens`; the whole prompt is `raw_prompt_token`. The context
+/// meter reads the whole prompt (compaction depends on it), the cost only what
+/// was billed, and the held prefix shows as a cache read: it was not resent.
pub fn recordUsage(self: *@import("agent.zig").Agent, u: std.json.ObjectMap, fallback: u64) void {
const ctx = @import("agent_context.zig");
const in_tokens = ctx.usageInt(u, "total_input_tokens");
+ const prompt = @max(in_tokens, ctx.usageInt(u, "raw_prompt_token"));
const out_tokens = ctx.usageInt(u, "total_output_tokens") +| ctx.usageInt(u, "total_thought_tokens");
- const total = @max(ctx.usageInt(u, "total_tokens"), in_tokens +| out_tokens);
+ const total = @max(ctx.usageInt(u, "total_tokens"), prompt +| out_tokens);
if (total > 0) ctx.replaceContextTokens(self, @intCast(total)) else ctx.floorContextTokens(self, fallback);
self.last_usage_includes_output = total > 0;
const cached = ctx.usageInt(u, "total_cached_tokens");
- if (cached > 0) self.last_cache_read = @intCast(cached);
+ const held = prompt - in_tokens;
+ if (cached +| held > 0) self.last_cache_read = @intCast(cached +| held);
self.recordCost(@max(in_tokens - cached, 0), cached, 0, out_tokens);
}
@@ -113,6 +120,8 @@ pub fn step(self: *@import("agent.zig").Agent, root: std.json.ObjectMap) !?[]con
try self.sayApiError("api error: interaction steps were not a list", .{});
return error.ApiError;
}
+ // The stored Interaction now holds these steps too (interactions_chain.zig).
+ try @import("interactions_chain.zig").record(self, root, steps.array.items);
// Echo every step back verbatim next turn — the thought signature is opaque
// and the endpoint validates it, so it must survive unedited.
for (steps.array.items) |st| try self.messages.append(st);
diff --git a/src/interactions_wire.zig b/src/interactions_wire.zig
index 02632f3c..2139c465 100644
--- a/src/interactions_wire.zig
+++ b/src/interactions_wire.zig
@@ -15,9 +15,10 @@
//! - unknown fields fail the WHOLE request ("Unknown parameter 'strict' at
//! 'tools[0]'"), so nothing generic may be sprayed into this body.
//!
-//! `store:false` keeps graff's own history authoritative, matching what the
-//! Responses wire already does; server-side state via previous_interaction_id
-//! is deliberately not used yet (it would need the id to survive compaction).
+//! graff's own history stays authoritative. The server-side copy is used only
+//! while it matches: a request continues the last stored Interaction with
+//! `previous_interaction_id` and only the new steps when interactions_chain.zig
+//! proves graff's history extends it, and replays every step otherwise.
const std = @import("std");
@@ -36,9 +37,18 @@ pub fn thinkingLevel(effort: []const u8) []const u8 {
pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_tool: bool, stream: bool) !void {
try s.objectField("system_instruction");
try s.write(try @import("agent_request_body_responses.zig").schemaAwarePrompt(self));
- // graff replays the full step list every turn, so the server keeps nothing.
- try s.objectField("store");
- try s.write(false);
+ const chain = @import("interactions_chain.zig");
+ const plan = try chain.plan(self);
+ // Stored by default (the field's default is true) so the next request can
+ // continue this one; GRAFF_INTERACTIONS_STORE=0 keeps nothing server-side.
+ if (!chain.g_store) {
+ try s.objectField("store");
+ try s.write(false);
+ }
+ if (plan.prev_id) |id| {
+ try s.objectField("previous_interaction_id");
+ try s.write(id);
+ }
try s.objectField("generation_config");
try s.beginObject();
try s.objectField("thinking_level");
@@ -56,7 +66,7 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
}
try s.objectField("input");
try s.beginArray();
- for (self.messages.items) |m| try @import("session_wake.zig").writeWire(s, m);
+ for (self.messages.items[plan.from..]) |m| try @import("session_wake.zig").writeWire(s, m);
try s.endArray();
if (stream) {
try s.objectField("stream");
diff --git a/src/session_settings.zig b/src/session_settings.zig
index a4af6397..64f089b6 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -160,6 +160,8 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
// 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;
+ // GRAFF_INTERACTIONS_STORE=0: Google Interactions stays stateless (store:false, full replay; interactions_chain).
+ if (environ_map.get("GRAFF_INTERACTIONS_STORE")) |v| @import("interactions_chain.zig").g_store = !(std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "off") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no"));
if (environ_map.get("GRAFF_WS_PREWARM")) |v| @import("agent_ws_prewarm.zig").g_enabled = std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "true");
// GRAFF_NO_NATIVE_FOLD: presence-based — restore full power-tool schemas
// in every request (the pre-fold interactive surface).