Skip to content

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

Python

fix(gemini): echo v1_ id and thought signatures on streamed tool turns

justrach90cc25b7c970
diff --git a/graff-evals/harnesses.json b/graff-evals/harnesses.json
index 82aeee7d..a18558df 100644
--- a/graff-evals/harnesses.json
+++ b/graff-evals/harnesses.json
@@ -69,5 +69,13 @@
"usage": "pi-json",
"capabilities": [],
"default_model": "deepseek-v4-flash"
+ },
+ "pi-codegraff": {
+ "cmd": ["pi", "-p", "--mode", "json", "--provider", "codegraff", "--model", "{model}", "--no-session", "{prompt}"],
+ "answer": "pi-json",
+ "usage": "pi-json",
+ "capabilities": [],
+ "default_model": "gemini-3.7-flash",
+ "note": "uses ~/.pi/agent/models.json provider codegraff → gateway.codegraff.com; Gemini tool loops need the codegraff-gemini-echo extension"
}
}
diff --git a/graff-evals/pi-extensions/README.md b/graff-evals/pi-extensions/README.md
new file mode 100644
index 00000000..81a0a1f0
--- /dev/null
+++ b/graff-evals/pi-extensions/README.md
@@ -0,0 +1,22 @@
+# Pi + Codegraff Gemini echo
+
+Pi's `openai-completions` assembler keeps `role` / `content` / `tool_calls` and drops the fields Gemini Interactions needs on the next turn:
+
+- `message.id` starting with `v1_`
+- `thought_signature` on the message and each `tool_calls[]` entry
+- `extra_content` if present
+
+Without those, a `role:tool` follow-up 400s (`request_rejected`, ~217 bytes). Do **not** rewrite `role: "tool"` to `role: "function"`.
+
+Install the extension (Pi auto-loads `~/.pi/agent/extensions/*.ts`):
+
+```bash
+mkdir -p ~/.pi/agent/extensions
+cp graff-evals/pi-extensions/codegraff-gemini-echo.ts ~/.pi/agent/extensions/
+```
+
+Smoke:
+
+```bash
+python3 graff-evals/run.py --harness pi-codegraff --model gemini-3.7-flash --task fix-fib
+```
diff --git a/graff-evals/pi-extensions/codegraff-gemini-echo.ts b/graff-evals/pi-extensions/codegraff-gemini-echo.ts
new file mode 100644
index 00000000..db264dc4
--- /dev/null
+++ b/graff-evals/pi-extensions/codegraff-gemini-echo.ts
@@ -0,0 +1,114 @@
+// Echo Gemini Interactions fields the Codegraff gateway needs on tool follow-ups.
+// Pi's openai-completions assembler keeps role/content/tool_calls and drops
+// message.id (v1_…), thought_signature, and extra_content — the next request
+// then 400s with request_rejected (~217 bytes). Do not rewrite role:tool.
+
+const GATEWAY = "gateway.codegraff.com";
+
+type Echo = {
+ id?: string;
+ thought_signature?: string;
+ extra_content?: unknown;
+ tool_sigs: Record<string, string>;
+};
+
+let last: Echo = { tool_sigs: {} };
+
+function parseSse(text: string): void {
+ for (const line of text.split("\n")) {
+ if (!line.startsWith("data: ")) continue;
+ const payload = line.slice(6).trim();
+ if (!payload || payload === "[DONE]") continue;
+ let ev: any;
+ try {
+ ev = JSON.parse(payload);
+ } catch {
+ continue;
+ }
+ if (typeof ev.id === "string" && ev.id.startsWith("v1_")) last.id = ev.id;
+ const choice = ev.choices?.[0];
+ const delta = choice?.delta ?? choice?.message;
+ if (!delta || typeof delta !== "object") continue;
+ if (typeof delta.id === "string" && delta.id.startsWith("v1_")) last.id = delta.id;
+ if (typeof delta.thought_signature === "string" && delta.thought_signature) {
+ last.thought_signature = delta.thought_signature;
+ }
+ if (delta.extra_content) last.extra_content = delta.extra_content;
+ if (!Array.isArray(delta.tool_calls)) continue;
+ for (const tc of delta.tool_calls) {
+ if (!tc || typeof tc !== "object") continue;
+ const sig =
+ (typeof tc.thought_signature === "string" && tc.thought_signature) ||
+ tc.extra_content?.google?.thought_signature;
+ if (typeof sig === "string" && sig) {
+ if (typeof tc.id === "string" && tc.id) last.tool_sigs[tc.id] = sig;
+ last.thought_signature ??= sig;
+ }
+ }
+ }
+}
+
+function wrapFetch(): void {
+ const g = globalThis as typeof globalThis & { __cgGeminiEchoFetch?: boolean };
+ if (g.__cgGeminiEchoFetch) return;
+ g.__cgGeminiEchoFetch = true;
+ const orig = globalThis.fetch.bind(globalThis);
+ globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.href
+ : (input as Request).url;
+ const res = await orig(input, init);
+ if (!url.includes(GATEWAY) || !res.body) return res;
+ const decoder = new TextDecoder();
+ let buf = "";
+ const transform = new TransformStream<Uint8Array, Uint8Array>({
+ transform(chunk, controller) {
+ controller.enqueue(chunk);
+ buf += decoder.decode(chunk, { stream: true });
+ let nl = buf.indexOf("\n");
+ while (nl >= 0) {
+ parseSse(buf.slice(0, nl + 1));
+ buf = buf.slice(nl + 1);
+ nl = buf.indexOf("\n");
+ }
+ },
+ flush() {
+ if (buf) parseSse(buf);
+ },
+ });
+ return new Response(res.body.pipeThrough(transform), res);
+ };
+}
+
+wrapFetch();
+
+export default function (pi: { on: (event: string, fn: (event: any) => unknown) => void }) {
+ pi.on("before_provider_request", (event) => {
+ const payload = event.payload;
+ const msgs = payload?.messages;
+ if (!Array.isArray(msgs)) return;
+ const hasAssistant = msgs.some((m: { role?: string }) => m?.role === "assistant");
+ if (!hasAssistant) {
+ last = { tool_sigs: {} };
+ return;
+ }
+ for (let i = msgs.length - 1; i >= 0; i--) {
+ const m = msgs[i];
+ if (m?.role !== "assistant") continue;
+ if (last.id && !m.id) m.id = last.id;
+ if (last.thought_signature && !m.thought_signature) m.thought_signature = last.thought_signature;
+ if (last.extra_content && !m.extra_content) m.extra_content = last.extra_content;
+ if (Array.isArray(m.tool_calls)) {
+ for (const tc of m.tool_calls) {
+ const sig = (tc.id && last.tool_sigs[tc.id]) || last.thought_signature;
+ if (sig && !tc.thought_signature) tc.thought_signature = sig;
+ }
+ }
+ break;
+ }
+ return payload;
+ });
+}
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 58b41c8b..ae347261 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -426,6 +426,7 @@ const CallAcc = struct {
id: []const u8 = "",
name: []const u8 = "",
args: std.ArrayList(u8) = .empty,
+ thought_signature: []const u8 = "",
};
pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
@@ -437,6 +438,9 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
var role: []const u8 = "assistant";
var finish: ?Value = null;
var usage: ?Value = null;
+ var message_id: []const u8 = "";
+ var thought_signature: []const u8 = "";
+ var extra_content: ?Value = null;
var saw_chunk = false;
var it = std.mem.tokenizeScalar(u8, body, '\n');
while (it.next()) |raw_line| {
@@ -457,11 +461,30 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
if (c0.object.get("finish_reason")) |fr| if (fr == .string) {
finish = fr;
};
+ if (v.object.get("id")) |xid| if (xid == .string and std.mem.startsWith(u8, xid.string, "v1_")) {
+ message_id = xid.string;
+ };
+ if (c0.object.get("message")) |msg| if (msg == .object) {
+ if (msg.object.get("id")) |xid| {
+ if (xid == .string and std.mem.startsWith(u8, xid.string, "v1_")) message_id = xid.string;
+ }
+ if (msg.object.get("thought_signature")) |ts| {
+ if (ts == .string and ts.string.len > 0) thought_signature = ts.string;
+ }
+ if (msg.object.get("extra_content")) |ec| extra_content = ec;
+ };
const d = c0.object.get("delta") orelse continue;
if (d != .object) continue;
if (d.object.get("role")) |x| if (x == .string) {
role = x.string;
};
+ if (d.object.get("id")) |xid| {
+ if (xid == .string and std.mem.startsWith(u8, xid.string, "v1_")) message_id = xid.string;
+ }
+ if (d.object.get("thought_signature")) |ts| {
+ if (ts == .string and ts.string.len > 0) thought_signature = ts.string;
+ }
+ if (d.object.get("extra_content")) |ec| extra_content = ec;
if (d.object.get("content")) |x| if (x == .string) try content.appendSlice(result_arena, x.string);
if (d.object.get("reasoning_content")) |x| if (x == .string) try reasoning_content.appendSlice(result_arena, x.string);
if (d.object.get("reasoning")) |x| if (x == .string) try reasoning.appendSlice(result_arena, x.string);
@@ -479,6 +502,10 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
if (tc.object.get("id")) |x| if (x == .string and x.string.len > 0) {
acc.id = x.string;
};
+ if (tc.object.get("thought_signature")) |x| if (x == .string and x.string.len > 0) {
+ acc.thought_signature = x.string;
+ };
+ if (tc.object.get("extra_content")) |ec| extra_content = extra_content orelse ec;
if (tc.object.get("function")) |f| if (f == .object) {
if (f.object.get("name")) |x| if (x == .string and x.string.len > 0) {
acc.name = x.string;
@@ -492,6 +519,9 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
var message: std.json.ObjectMap = .empty;
try message.put(result_arena, "role", .{ .string = try result_arena.dupe(u8, role) }); // #124: role slices the scratch parse tree; dupe so it survives the per-request scratch reset
+ if (message_id.len > 0) try message.put(result_arena, "id", .{ .string = try result_arena.dupe(u8, message_id) });
+ if (thought_signature.len > 0) try message.put(result_arena, "thought_signature", .{ .string = try result_arena.dupe(u8, thought_signature) });
+ if (extra_content) |ec| try message.put(result_arena, "extra_content", ec);
try message.put(result_arena, "content", if (content.items.len > 0) Value{ .string = content.items } else .null);
if (reasoning_content.items.len > 0) try message.put(result_arena, "reasoning_content", .{ .string = reasoning_content.items });
if (reasoning.items.len > 0) try message.put(result_arena, "reasoning", .{ .string = reasoning.items });
@@ -506,6 +536,8 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
try tc.put(result_arena, "id", .{ .string = try result_arena.dupe(u8, c.id) }); // #124: dupe off the scratch parse tree
try tc.put(result_arena, "type", .{ .string = "function" });
try tc.put(result_arena, "function", .{ .object = function });
+ const call_sig = if (c.thought_signature.len > 0) c.thought_signature else thought_signature;
+ if (call_sig.len > 0) try tc.put(result_arena, "thought_signature", .{ .string = try result_arena.dupe(u8, call_sig) });
try tcs.append(.{ .object = tc });
}
if (tcs.items.len > 0) try message.put(result_arena, "tool_calls", .{ .array = tcs });
@@ -522,7 +554,7 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
return r;
}
-test "assembleOpenAI preserves streamed reasoning history" {
+test "assembleOpenAI preserves streamed reasoning and Gemini echo fields" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
@@ -539,12 +571,13 @@ test "assembleOpenAI preserves streamed reasoning history" {
};
const root = (try agent.assembleOpenAI(
- "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\"}}]}\n" ++
- "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"think \"}}]}\n" ++
- "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"deep\"}}]}\n" ++
- "data: {\"choices\":[{\"delta\":{\"reasoning\":\"alt \"}}]}\n" ++
- "data: {\"choices\":[{\"delta\":{\"reasoning\":\"path\"}}]}\n" ++
- "data: {\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n" ++
+ "data: {\"id\":\"v1_thread\",\"choices\":[{\"delta\":{\"role\":\"assistant\",\"thought_signature\":\"SIG\"}}]}\n" ++
+ "data: {\"id\":\"v1_thread\",\"choices\":[{\"delta\":{\"reasoning_content\":\"think \"}}]}\n" ++
+ "data: {\"id\":\"v1_thread\",\"choices\":[{\"delta\":{\"reasoning_content\":\"deep\"}}]}\n" ++
+ "data: {\"id\":\"v1_thread\",\"choices\":[{\"delta\":{\"reasoning\":\"alt \"}}]}\n" ++
+ "data: {\"id\":\"v1_thread\",\"choices\":[{\"delta\":{\"reasoning\":\"path\"}}]}\n" ++
+ "data: {\"id\":\"v1_thread\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"c1\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{}\"},\"thought_signature\":\"SIG\"}]}}]}\n" ++
+ "data: {\"id\":\"v1_thread\",\"choices\":[{\"delta\":{\"content\":\"done\"},\"finish_reason\":\"tool_calls\"}]}\n" ++
"data: [DONE]\n",
)).?;
const choices = root.get("choices").?;
@@ -553,4 +586,7 @@ test "assembleOpenAI preserves streamed reasoning history" {
try std.testing.expectEqualStrings("done", message.get("content").?.string);
try std.testing.expectEqualStrings("think deep", message.get("reasoning_content").?.string);
try std.testing.expectEqualStrings("alt path", message.get("reasoning").?.string);
+ try std.testing.expectEqualStrings("v1_thread", message.get("id").?.string);
+ try std.testing.expectEqualStrings("SIG", message.get("thought_signature").?.string);
+ try std.testing.expectEqualStrings("SIG", message.get("tool_calls").?.array.items[0].object.get("thought_signature").?.string);
}
diff --git a/src/session_run.zig b/src/session_run.zig
index 650ce65c..caece926 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -168,8 +168,12 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
else => |e| std.process.fatal("turn failed: {t}", .{e}),
}
};
+ const had_schema = pending_schema != null;
if (pending_schema) |schema_json| {
root.output_schema = schema_json;
+ // Gemini (via the gateway) accepts json_schema then ignores it, so the
+ // #543 sox path never learns. Force schema-in-prompt + structured_output.
+ if (std.mem.startsWith(u8, root.provider.model, "gemini")) root.sox_json_object = true;
root.text_only = true;
defer {
root.text_only = false;
@@ -183,7 +187,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
break :blk final_text;
};
}
- try out.print("{s}\n", .{final_text});
+ try out.print("{s}\n", .{if (had_schema) unwrapFencedJson(final_text) else final_text});
try out.flush();
// Usage summary → stderr, so stdout stays exactly the answer.
pricing.printUsageFooter(io);
@@ -516,3 +520,20 @@ pub fn startBackgroundLearning(gpa: Allocator, arena: Allocator, io: Io, environ
.skipped => {},
}
}
+
+/// `--output-schema` checks `json.load` the printed answer. Models that ignore
+/// json_schema often wrap the object in a markdown fence; strip that only.
+fn unwrapFencedJson(text: []const u8) []const u8 {
+ const trimmed = std.mem.trim(u8, text, " \t\r\n");
+ if (!std.mem.startsWith(u8, trimmed, "```")) return trimmed;
+ var rest = trimmed[3..];
+ if (std.mem.startsWith(u8, rest, "json")) rest = rest[4..];
+ rest = std.mem.trimStart(u8, rest, " \t\r\n");
+ if (std.mem.lastIndexOf(u8, rest, "```")) |end| return std.mem.trim(u8, rest[0..end], " \t\r\n");
+ return rest;
+}
+
+test "unwrapFencedJson strips a markdown fence and leaves bare JSON alone" {
+ try std.testing.expectEqualStrings("{\"a\":1}", unwrapFencedJson("```json\n{\"a\":1}\n```\n"));
+ try std.testing.expectEqualStrings("{\"a\":1}", unwrapFencedJson("{\"a\":1}"));
+}