Skip to content

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

Python

fix(provider): #543 #544 — structured outputs survive deepseek, tunable non-stream deadline

Rach Pradhan3f297dd9c4ed
diff --git a/graff-evals/harnesses.json b/graff-evals/harnesses.json
index aed21463..82aeee7d 100644
--- a/graff-evals/harnesses.json
+++ b/graff-evals/harnesses.json
@@ -5,6 +5,7 @@
"usage": "graff-stderr",
"capabilities": ["output-schema"],
"schema_args": ["--output-schema", "{schema}"],
+ "env": {"GRAFF_POST_DEADLINE_SECS": "90"},
"default_model": "grok-4.6"
},
"graff-full": {
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 5e6c6c25..ec3a01da 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 1295,
+ "test_count_baseline": 1315,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/src/agent.zig b/src/agent.zig
index ef6edaa2..aee16c14 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -216,6 +216,7 @@ pub const Agent = struct {
streamed_args: ArgTool = .none, // which meta tool's prose streamed live this request
streamed_args_len: usize = 0, // raw bytes emitted for it (gates re-print suppression)
cap_new: bool = false, // provider rejected max_tokens → use max_completion_tokens
+ sox_json_object: bool = false, // #543: provider rejected response_format json_schema → json_object + schema-in-prompt
effort_rejected: bool = false, // model rejected reasoning_effort → drop it (e.g. gpt-5.5 on chat/completions wants /v1/responses)
output_schema: ?[]const u8 = null, // --output-schema: JSON schema the final answer must satisfy (response_format / text.format, #502)
next_ask_id: u64 = 1,
diff --git a/src/agent_request.zig b/src/agent_request.zig
index fd449879..2cd6d546 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -507,6 +507,14 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
self.cap_new = true; // provider wants the post-deprecation name
continue;
}
+ // #543: a provider without json_schema structured outputs (deepseek:
+ // "This response_format type is unavailable now") must not lose the
+ // --output-schema contract — retry in json_object mode with the
+ // schema moved into the prompt, on the same ladder as cap_new.
+ if (self.output_schema != null and !self.sox_json_object and std.mem.indexOf(u8, msg, "response_format") != null) {
+ self.sox_json_object = true;
+ continue;
+ }
if (!self.effort_rejected and mentionsReasoningEffort(msg)) {
self.effort_rejected = true; // model rejects the effort hint here; drop + retry
continue;
diff --git a/src/agent_request_body.zig b/src/agent_request_body.zig
index 9dc66c2d..8f3ef93e 100644
--- a/src/agent_request_body.zig
+++ b/src/agent_request_body.zig
@@ -167,17 +167,12 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
}
try s.endObject();
}
- // Sticky cache partition from the first request. Kimi keys by
- // project (cwd) so a new session still hits the warm prefix;
- // everyone else on this wire uses the per-conversation id
- // (OpenAI / codegraff / deepseek / xAI-chat). Children suffix
- // so they do not evict the root.
+ // Sticky cache partition from the first request. Durable per
+ // project so a new session still hits the warm system+tools
+ // prefix; children suffix so they do not evict the root.
var ckbuf: [96]u8 = undefined;
try s.objectField("prompt_cache_key");
- try s.write(if (is_kimi)
- http_headers.projectCacheKey(self.io, self.label, self, &ckbuf)
- else
- http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));
+ try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));
// Reasoning-effort hint for OpenAI-compatible providers that
// honor it (codegraff gateway, deepseek). Mirrors the
// Responses `reasoning.effort` set in the branch below.
@@ -186,8 +181,14 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
try s.write(if (self.reasoning == .ultra) "max" else @tagName(self.reasoning));
}
// --output-schema: structured outputs (xAI docs' response_format).
- if (self.output_schema) |schema_json|
- try @import("agent_request_body_responses.zig").writeResponseFormat(&s, schema_json);
+ // A provider that rejected json_schema (#543, deepseek) runs in
+ // json_object mode instead — the schema rides the prompt then.
+ if (self.output_schema) |schema_json| {
+ if (self.sox_json_object)
+ try @import("agent_request_body_responses.zig").writeJsonObjectFormat(&s)
+ else
+ try @import("agent_request_body_responses.zig").writeResponseFormat(&s, schema_json);
+ }
},
// The Responses-wire body (codex / xAI #502) lives in its own module
// under the 600-line ceiling; structured-output writers ride along.
@@ -454,9 +455,10 @@ test "retained reasoning: codex full resend keeps encrypted reasoning items and
try std.testing.expect(std.mem.indexOf(u8, body, "previous_response_id") == null);
// Because store:false makes every turn a full resend, the backend needs a
- // cache partition to land it in. openai/codex sends prompt_cache_key on
- // this exact path, defaulting it to the per-session UUID.
- const key = try std.fmt.allocPrint(arena, "\"prompt_cache_key\":\"{s}\"", .{http_headers.sessionId(agent.io)});
+ // cache partition to land it in. openai/codex send prompt_cache_key on
+ // this exact path, keyed by the durable project id.
+ var ckbuf: [96]u8 = undefined;
+ const key = try std.fmt.allocPrint(arena, "\"prompt_cache_key\":\"{s}\"", .{http_headers.promptCacheKey(agent.io, agent.label, &agent, &ckbuf)});
try std.testing.expect(std.mem.indexOf(u8, body, key) != null);
}
@@ -565,7 +567,9 @@ test "openai-wire bodies send a sticky prompt_cache_key; children isolate" {
const rs = std.mem.indexOf(u8, rb, needle) orelse return error.MissingPromptCacheKey;
const re = std.mem.indexOfScalarPos(u8, rb, rs + needle.len, '"') orelse return error.MissingPromptCacheKey;
const root_key = rb[rs + needle.len .. re];
- try std.testing.expectEqualStrings(http_headers.sessionId(root.io), root_key);
+ var rkbuf: [96]u8 = undefined;
+ try std.testing.expectEqualStrings(http_headers.promptCacheKey(root.io, root.label, &root, &rkbuf), root_key);
+ try std.testing.expect(!std.mem.eql(u8, root_key, http_headers.sessionId(root.io)));
var child = root;
child.sub = true;
diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zig
index 16ac1590..db0f9363 100644
--- a/src/agent_request_body_responses.zig
+++ b/src/agent_request_body_responses.zig
@@ -19,10 +19,11 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
const is_codex = std.mem.eql(u8, self.provider.id, "codex");
try s.objectField("instructions");
try s.write(try schemaAwarePrompt(self));
- // Sticky cache partition from the first request. Codex and OpenAI
- // document prompt_cache_key; xAI uses the same id as x-grok-conv-id.
- // Root = session id, child = suffix, so interleaved agents do not evict
- // each other. Effort is NOT flipped per turn — that would miss the prefix.
+ // Sticky cache partition from the first request. Codex/OpenAI document
+ // prompt_cache_key; xAI uses the same id as x-grok-conv-id (routes the
+ // request to the server that already has the prefix). Root = project
+ // id, child = suffix. Effort is NOT flipped per turn — that would miss
+ // the prefix.
var ckbuf: [96]u8 = undefined;
try s.objectField("prompt_cache_key");
try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));
@@ -87,6 +88,13 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
pub fn schemaAwarePrompt(self: *Agent) ![]const u8 {
const base = self.systemPrompt();
if (self.output_schema == null) return base;
+ // #543 degrade: this provider cannot enforce json_schema server-side
+ // (json_object mode only), so the schema itself must reach the model.
+ if (self.sox_json_object) return std.mem.concat(self.scratchAlloc(), u8, &.{
+ base,
+ "\n\nA JSON output schema is enforced on your final message. Use tools first to gather every fact you need; only the final message must match the schema — never guess values. This provider cannot enforce the schema server-side, so the final message must be a single JSON object that satisfies exactly this schema: ",
+ self.output_schema.?,
+ });
return std.mem.concat(self.scratchAlloc(), u8, &.{
base,
"\n\nA JSON output schema is enforced on your final message. Use tools first to gather every fact you need; only the final message must match the schema — never guess values.",
@@ -112,6 +120,16 @@ pub fn writeTextFormat(s: *std.json.Stringify, schema_json: []const u8) !void {
try s.endObject();
}
+/// #543 fallback for providers without json_schema support (deepseek): plain
+/// JSON mode — the schema constraint moves into the prompt (schemaAwarePrompt).
+pub fn writeJsonObjectFormat(s: *std.json.Stringify) !void {
+ try s.objectField("response_format");
+ try s.beginObject();
+ try s.objectField("type");
+ try s.write("json_object");
+ try s.endObject();
+}
+
/// Structured outputs on the chat-completions wire: response_format
/// json_schema (the shape xAI/OpenAI/compatible routers document).
pub fn writeResponseFormat(s: *std.json.Stringify, schema_json: []const u8) !void {
@@ -190,3 +208,22 @@ test "--output-schema rides text.format on Responses and response_format on chat
defer std.testing.allocator.free(plain_body);
try std.testing.expect(std.mem.indexOf(u8, plain_body, "response_format") == null);
}
+
+test "#543: json_schema rejection degrades to json_object with the schema moved into the prompt" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const schema = "{\"type\":\"object\",\"properties\":{\"answer\":{\"type\":\"string\"}},\"required\":[\"answer\"],\"additionalProperties\":false}";
+ var agent = try testAgentFor(arena_state.allocator(), "deepseek", .openai, "deepseek-v4-flash");
+ agent.output_schema = schema;
+ agent.sox_json_object = true; // learned via the request() quirk ladder on deepseek's rejection
+ const body = try agent.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(body);
+ // The wire carries plain JSON mode, never the rejected json_schema shape...
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"response_format\":{\"type\":\"json_object\"}") != null);
+ try std.testing.expect(std.mem.indexOf(u8, body, "json_schema") == null);
+ // ...so the schema itself must reach the model through the system prompt.
+ try std.testing.expect(std.mem.indexOf(u8, body, "cannot enforce the schema server-side") != null);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\\\"additionalProperties\\\":false") != null);
+ // json_object mode requires the word JSON in the prompt (deepseek docs) — the suffix carries it.
+ try std.testing.expect(std.mem.indexOf(u8, body, "JSON output schema") != null);
+}
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 2563f8da..f3442429 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -358,8 +358,8 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
const bearer = try std.fmt.allocPrint(arena, "Bearer {s}", .{provider.api_key});
// ChatGPT tail is codex-only (#502); xAI takes x-grok-conv-id instead —
- // the PER-CONVERSATION cache id (root/sub isolated), same sticky value as
- // the Responses body's prompt_cache_key, not the bare process session id.
+ // the project cache id (root/sub isolated), same sticky value as the
+ // Responses body's prompt_cache_key, not the per-process session id.
var conv_buf: [96]u8 = undefined;
const conv = http_headers.promptCacheKey(self.io, self.label, self, &conv_buf);
var hdrs: [7]ws.Header = undefined;
diff --git a/src/grok_spec_conformance.zig b/src/grok_spec_conformance.zig
index bf1721c0..cebf9883 100644
--- a/src/grok_spec_conformance.zig
+++ b/src/grok_spec_conformance.zig
@@ -49,6 +49,8 @@ test "grok spec: Chat Completions x-grok-conv-id is stable for root and isolated
const root_id = http_headers.promptCacheKey(io, "main", @ptrCast(&root_slot), &rbuf);
var rbuf2: [96]u8 = undefined;
try std.testing.expectEqualStrings(root_id, http_headers.promptCacheKey(io, "main", @ptrCast(&root_slot), &rbuf2));
+ try std.testing.expectEqualStrings(root_id, http_headers.projectRootId(io));
+ try std.testing.expect(!std.mem.eql(u8, root_id, http_headers.sessionId(io)));
const child_id = http_headers.promptCacheKey(io, "sub", @ptrCast(&child_slot), &cbuf);
try std.testing.expect(!std.mem.eql(u8, root_id, child_id));
diff --git a/src/http.zig b/src/http.zig
index 7a3f7896..2750749d 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -191,8 +191,11 @@ fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []co
/// Hard ceiling on one non-streaming request. The legitimate worst case
/// observed (a 160k-token subagent context) completed in ~134s; anything
-/// past this is a hung response, not a slow one.
-const post_deadline_ms: u64 = 5 * 60 * 1000;
+/// past this is a hung response, not a slow one. Tunable via
+/// GRAFF_POST_DEADLINE_SECS (#544): non-streaming callers (one-shots,
+/// subagents) have no inter-chunk stall signal, so this deadline is their
+/// ONLY hang detector — a harness with a tighter task timeout lowers it.
+pub var post_deadline_ms: u64 = 5 * 60 * 1000;
pub const WatchdogFired = enum { esc, deadline };
diff --git a/src/http_headers.zig b/src/http_headers.zig
index 4477f363..487cd6bc 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -12,13 +12,10 @@ var session_id_len: usize = 0;
/// with, and the critical section is a single one-time 36-byte format.
var session_id_lock: std.atomic.Value(bool) = .init(false);
-/// A UUIDv4 minted once per process, matching what openai/codex generates per
-/// session. It rides two places: the `session_id` header and `prompt_cache_key`
-/// on the Responses body, which is what the backend partitions its prompt cache
-/// on. This was a single hardcoded constant shared by every graff user on every
-/// machine, which is the worst case for that partition: one key carrying all
-/// traffic overflows and DEGRADES hit rate, so the full histories we resend
-/// each turn had no affinity to land on.
+/// A UUIDv4 minted once per process. Codex still sends this as the `session_id`
+/// header (ChatGPT backend identity). Prompt-cache affinity is `projectRootId`,
+/// not this value — a per-process random key made every new session's first
+/// call a cold partition.
pub fn sessionId(io: Io) []const u8 {
while (session_id_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
defer session_id_lock.store(false, .release);
@@ -42,55 +39,76 @@ pub fn sessionId(io: Io) []const u8 {
return session_id_buf[0..session_id_len];
}
-/// The cache-affinity partition for one agent. opencode keys per session for
-/// the same reason: every agent in the process used to share the session id,
-/// so interleaved root/sub requests — different prefixes under one key —
-/// evicted each other (root cache_read measured ~35% in benchmarks). Root
-/// ("main") keeps the bare session id; every other agent gets a unique suffix.
+/// Prompt-cache affinity for one agent. xAI routes `x-grok-conv-id` (Chat
+/// Completions) and `prompt_cache_key` (Responses) to the same server — that
+/// is how a prefix written earlier can still hit. Root is the durable
+/// per-project id; children get a suffix so interleaved root/sub prefixes
+/// do not evict each other.
pub fn promptCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: []u8) []const u8 {
- const base = sessionId(io);
- if (std.mem.eql(u8, label, "main")) return base;
- return std.fmt.bufPrint(buf, "{s}-{x}", .{ base, @intFromPtr(agent) }) catch base;
+ return projectCacheKey(io, label, agent, buf);
+}
+
+var project_id_buf: [36]u8 = undefined;
+var project_id_len: usize = 0;
+var project_id_lock: std.atomic.Value(bool) = .init(false);
+
+/// Durable per-project id (cwd-derived UUIDv5, no state to persist). A new
+/// session in the same repo reuses the bucket the last session wrote, so
+/// turn 1 can hit the warm system+tools prefix if the provider still has
+/// it. Different models do not share a cache (the server keys by model);
+/// they each get this same routing id so *their* later sessions can find
+/// *their* prefix. Same-project conversation tails may evict each other;
+/// the expensive prefix still hits.
+pub fn projectRootId(io: Io) []const u8 {
+ while (project_id_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
+ defer project_id_lock.store(false, .release);
+ if (project_id_len == 0) {
+ var raw: [16]u8 = undefined;
+ {
+ var cwd_buf: [4096]u8 = undefined;
+ const n = Io.Dir.cwd().realPathFile(io, ".", &cwd_buf) catch blk: {
+ @memcpy(cwd_buf[0..1], ".");
+ break :blk 1;
+ };
+ const cwd = cwd_buf[0..n];
+ var digest: [32]u8 = undefined;
+ var h = std.crypto.hash.sha2.Sha256.init(.{});
+ h.update("graff-kimi-project-cache-v1");
+ h.update(cwd);
+ h.final(&digest);
+ @memcpy(&raw, digest[0..16]);
+ raw[6] = (raw[6] & 0x0f) | 0x50; // version 5: name-derived
+ raw[8] = (raw[8] & 0x3f) | 0x80; // variant 1
+ }
+ const hex = std.fmt.bytesToHex(raw, .lower);
+ @memcpy(project_id_buf[0..8], hex[0..8]);
+ project_id_buf[8] = '-';
+ @memcpy(project_id_buf[9..13], hex[8..12]);
+ project_id_buf[13] = '-';
+ @memcpy(project_id_buf[14..18], hex[12..16]);
+ project_id_buf[18] = '-';
+ @memcpy(project_id_buf[19..23], hex[16..20]);
+ project_id_buf[23] = '-';
+ @memcpy(project_id_buf[24..36], hex[20..32]);
+ project_id_len = 36;
+ }
+ return project_id_buf[0..project_id_len];
}
-/// Kimi-only: a DURABLE per-project cache partition, derived from the cwd
-/// (UUIDv5-style, no state to persist). The kimi backend keys its prompt
-/// cache on prompt_cache_key, and a per-process random key made every new
-/// session's first call a cold partition — measured cache_read=0 on every
-/// first call in the k3 benchmark, where kimi-cli's fresh sessions hit ~19k.
-/// A per-project key lets the first call of a new session land on the warm
-/// shared system-prompt prefix (~2-4s). Same-project sessions share the
-/// partition: conversation tails evict each other, the expensive prefix still
-/// hits. Subagents keep a per-agent suffix (the eviction reasoning above).
pub fn projectCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: []u8) []const u8 {
- var raw: [16]u8 = undefined;
- {
- var cwd_buf: [4096]u8 = undefined;
- const n = Io.Dir.cwd().realPathFile(io, ".", &cwd_buf) catch blk: {
- @memcpy(cwd_buf[0..1], ".");
- break :blk 1;
- };
- const cwd = cwd_buf[0..n];
- var digest: [32]u8 = undefined;
- var h = std.crypto.hash.sha2.Sha256.init(.{});
- h.update("graff-kimi-project-cache-v1");
- h.update(cwd);
- h.final(&digest);
- @memcpy(&raw, digest[0..16]);
- raw[6] = (raw[6] & 0x0f) | 0x50; // version 5: name-derived
- raw[8] = (raw[8] & 0x3f) | 0x80; // variant 1
+ const base = projectRootId(io);
+ if (std.mem.eql(u8, label, "main")) {
+ if (buf.len >= base.len) {
+ @memcpy(buf[0..base.len], base);
+ return buf[0..base.len];
+ }
+ return base;
}
- const hex = std.fmt.bytesToHex(raw, .lower);
- const base = std.fmt.bufPrint(buf, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable;
- if (std.mem.eql(u8, label, "main")) return base;
- const suffix = std.fmt.bufPrint(buf[base.len..], "-{x}", .{@intFromPtr(agent)}) catch return base;
- return buf[0 .. base.len + suffix.len];
+ return std.fmt.bufPrint(buf, "{s}-{x}", .{ base, @intFromPtr(agent) }) catch base;
}
-/// /resume adopts the persisted key so k3/codex prompt-cache affinity survives
-/// the process boundary — both upstreams key the cache on the durable
-/// conversation id (kimi-code's sessionContext.sessionId; codex's ModelClient
-/// default), not a per-process UUID. No-op once this process has minted its own.
+/// /resume adopts the persisted Codex `session_id`. Prompt-cache routing
+/// uses `projectRootId` and does not need this. No-op once minted.
pub fn adoptSessionId(id: []const u8) void {
if (id.len != 36) return;
while (session_id_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
@@ -107,8 +125,8 @@ pub fn userAgent(provider: Provider) std.http.Client.Request.Headers.Value {
return .default;
}
-/// xAI Chat Completions + Responses: the official cache-routing header.
-/// `promptCacheKey` is the same sticky id used as Responses `prompt_cache_key`.
+/// xAI Chat Completions: `x-grok-conv-id` (Responses: `prompt_cache_key`).
+/// Same value on both — xAI routes that id to one server so the prefix hits.
pub fn wantsGrokConvId(provider_id: []const u8) bool {
return std.mem.eql(u8, provider_id, "xai");
}
@@ -157,7 +175,7 @@ pub fn providerHeadersWithConv(io: Io, provider: Provider, bearer: []const u8, b
count += 1;
}
if (wantsGrokConvId(provider.id)) {
- buf[count] = .{ .name = "x-grok-conv-id", .value = conv_id orelse sessionId(io) };
+ buf[count] = .{ .name = "x-grok-conv-id", .value = conv_id orelse projectRootId(io) };
count += 1;
}
return buf[0..count];
@@ -167,8 +185,7 @@ test "session_id is a stable per-process UUIDv4, not a shared constant" {
const io = std.testing.io;
const a = sessionId(io);
try std.testing.expectEqual(@as(usize, 36), a.len);
- // The value the backend partitions its prompt cache on used to be this
- // constant, identical for every session and every graff user.
+ // Codex session_id must not collapse to the old shared constant.
try std.testing.expect(!std.mem.eql(u8, a, "00000000-0000-0000-0000-000000000001"));
for ([_]usize{ 8, 13, 18, 23 }) |i| try std.testing.expectEqual(@as(u8, '-'), a[i]);
try std.testing.expectEqual(@as(u8, '4'), a[14]); // version nibble
@@ -177,8 +194,6 @@ test "session_id is a stable per-process UUIDv4, not a shared constant" {
if (i == 8 or i == 13 or i == 18 or i == 23) continue;
try std.testing.expect((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f'));
}
- // Stable within the process: the header and prompt_cache_key must agree,
- // and the key must not move turn to turn or it partitions nothing.
try std.testing.expectEqualStrings(a, sessionId(io));
var buf: [12]std.http.Header = undefined;
@@ -213,12 +228,25 @@ test "projectCacheKey is a durable per-project v5 UUID, stable across calls" {
var buf2: [96]u8 = undefined;
const b = projectCacheKey(std.testing.io, "main", agent, &buf2);
try std.testing.expectEqualStrings(a, b); // durable: no per-process randomness
+ try std.testing.expectEqualStrings(a, projectRootId(std.testing.io));
+ // Prompt-cache routing is this project id, not the per-process session UUID.
+ try std.testing.expect(!std.mem.eql(u8, a, sessionId(std.testing.io)));
+ var pbuf: [96]u8 = undefined;
+ try std.testing.expectEqualStrings(a, promptCacheKey(std.testing.io, "main", agent, &pbuf));
// Subagents get a per-agent suffix off the same partition (eviction rule).
var buf3: [96]u8 = undefined;
const sub = projectCacheKey(std.testing.io, "sub", agent, &buf3);
try std.testing.expect(std.mem.startsWith(u8, sub, a));
}
+test "x-grok-conv-id with no explicit conv still uses the project root id" {
+ const io = std.testing.io;
+ const xai: Provider = .{ .id = "xai", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.6", .context = 256_000 };
+ var buf: [12]std.http.Header = undefined;
+ const headers = providerHeadersWithConv(io, xai, "Bearer k", &buf, null);
+ try std.testing.expectEqualStrings(projectRootId(io), headerValue(headers, "x-grok-conv-id") orelse return error.MissingGrokConvId);
+}
+
test "adoptSessionId validates length and never overwrites a minted id" {
const io = std.testing.io;
const before = sessionId(io); // minted by whichever test ran first
diff --git a/src/providers.zig b/src/providers.zig
index ac478102..901cc113 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -112,6 +112,7 @@ fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool
// meter instead of replacing it with the structurally-low local estimate.
if (!same_selection) {
root.cap_new = false; // per-provider token-cap quirk; relearn on rejection
+ root.sox_json_object = false; // #543: json_schema support is per-provider; relearn
root.effort_rejected = false; // new model may accept reasoning_effort; relearn
root.ws_off = false; // a previous Codex WS fallback must not leak across switches
root.ws_transport_failures = 0;
@@ -501,6 +502,7 @@ test "applyProviderInner preserves the server meter on an exact model re-selecti
root.context_local_tokens = root.fullRequestEstimateTokens();
root.last_cache_read = 12_345;
root.cap_new = true;
+ root.sox_json_object = true;
root.effort_rejected = true;
root.ws_off = true;
root.ws_transport_failures = 2;
@@ -511,6 +513,7 @@ test "applyProviderInner preserves the server meter on an exact model re-selecti
try std.testing.expectEqual(@as(u64, 220_000), root.last_context_tokens);
try std.testing.expectEqual(@as(u64, 12_345), root.last_cache_read);
try std.testing.expect(root.cap_new);
+ try std.testing.expect(root.sox_json_object);
try std.testing.expect(root.effort_rejected);
try std.testing.expect(root.ws_off);
@@ -521,6 +524,7 @@ test "applyProviderInner preserves the server meter on an exact model re-selecti
try std.testing.expectEqual(root.last_context_tokens, root.context_local_tokens);
try std.testing.expectEqual(@as(u64, 0), root.last_cache_read);
try std.testing.expect(!root.cap_new);
+ try std.testing.expect(!root.sox_json_object); // #543: relearned per provider
try std.testing.expect(!root.effort_rejected);
try std.testing.expect(!root.ws_off);
try std.testing.expectEqual(@as(u8, 0), root.ws_transport_failures);
diff --git a/src/session.zig b/src/session.zig
index 8f731fc5..67110671 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -484,9 +484,8 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
root.todos.clearRetainingCapacity(); // never inherit another conversation's checklist (#318)
if (obj.get("todos")) |tv| try appendTodosFromValue(arena, &root.todos, tv);
root.todos_dirty = false; // restored todos are persisted state, never this-process completion evidence (#318)
- // The completion double-check is per-PROCESS state and leaked across /resume
- // (#318): an arm left by a refusal in the previous session short-circuited the
- // first attempt_completion of the resumed one, closing its goal unchecked.
+ // The completion double-check is per-PROCESS state (#318): a leftover arm
+ // short-circuited the resumed session's first attempt_completion.
root.completion_gate_armed = false;
root.completion_refused = false;
// #318: retire a restored-active goal whose checklist is already finished.
@@ -499,7 +498,8 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
root.session_title = title;
// Rebase the saved server-only delta onto today's prompt/tool-schema input.
restoreContextMeter(root, saved_context_tokens, saved_local_tokens);
- root.cap_new = false; // per-provider; relearn on rejection
+ root.cap_new = false; // per-provider (like sox/effort below); relearn on rejection
+ root.sox_json_object = false; // #543
root.effort_rejected = false;
root.ws_off = false; // transport failures belong to the prior live session
root.ws_transport_failures = 0;
diff --git a/src/session_settings.zig b/src/session_settings.zig
index eefa3e57..81efef11 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -86,6 +86,15 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
if (secs > 0) http_stall.head_ceiling_ms = @min(secs, 86_400) * 1000;
} else |_| {}
}
+ // #544: the non-streaming request deadline (default 5 min). One-shots and
+ // subagents run non-streamed, so this is their only hang detector; a
+ // harness with a tighter per-task budget lowers it so a wedged request
+ // retries inside that budget. Seconds; ignored if unparseable or 0.
+ if (environ_map.get("GRAFF_POST_DEADLINE_SECS")) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
+ if (secs > 0) http.post_deadline_ms = @min(secs, 86_400) * 1000;
+ } else |_| {}
+ }
// #codex-ws: GRAFF_CODEX_WS=off|0|false|no (case-insensitive, the
// GRAFF_FLEET predicate) forces the SSE transport for codex;
// GRAFF_WS_DEBUG=1 dumps the ws handshake + frames to stderr. This is the
diff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zig
index 593dbcab..257c7a00 100644
--- a/src/session_settings_tests.zig
+++ b/src/session_settings_tests.zig
@@ -37,6 +37,7 @@ const knobs = [_]Knob{
.{ .name = "GRAFF_FORCE_DROP_ALWAYS", .value = "1" },
.{ .name = "GRAFF_STREAM_STALL_SECS", .value = "7" },
.{ .name = "GRAFF_STREAM_HEAD_STALL_SECS", .value = "9" },
+ .{ .name = "GRAFF_POST_DEADLINE_SECS", .value = "90" },
.{ .name = "GRAFF_CODEX_WS", .value = "off" },
.{ .name = "GRAFF_CLOCK_SLEEP", .value = "1" },
.{ .name = "GRAFF_NO_LOCAL_TOOLS", .value = "1" },
@@ -79,6 +80,7 @@ const Saved = struct {
codex_ws: bool,
clock_sleep: bool,
stream_stall_ms: u64,
+ post_deadline_ms: u64,
codex_ws_idle_ms: i64,
context_override: ?u64,
compact_pct_override: ?u8,
@@ -98,6 +100,7 @@ const Saved = struct {
.codex_ws = main_mod.g_codex_ws,
.clock_sleep = main_mod.g_clock_sleep,
.stream_stall_ms = http.stream_stall_ms,
+ .post_deadline_ms = http.post_deadline_ms,
.codex_ws_idle_ms = agent_ws.codex_ws_idle_ms,
.context_override = provider_mod.g_context_override,
.compact_pct_override = provider_mod.g_compact_pct_override,
@@ -118,6 +121,7 @@ const Saved = struct {
main_mod.g_codex_ws = s.codex_ws;
main_mod.g_clock_sleep = s.clock_sleep;
http.stream_stall_ms = s.stream_stall_ms;
+ http.post_deadline_ms = s.post_deadline_ms;
agent_ws.codex_ws_idle_ms = s.codex_ws_idle_ms;
provider_mod.g_context_override = s.context_override;
provider_mod.g_compact_pct_override = s.compact_pct_override;
@@ -176,6 +180,7 @@ test "applyEnvKnobs actually applies the values it reads" {
try std.testing.expect(no_local_tools.enabled);
try std.testing.expect(ws.g_debug);
try std.testing.expectEqual(@as(u64, 7_000), http.stream_stall_ms); // seconds → ms
+ try std.testing.expectEqual(@as(u64, 90_000), http.post_deadline_ms); // #544: seconds → ms
try std.testing.expectEqual(@as(i64, 11_000), agent_ws.codex_ws_idle_ms);
try std.testing.expectEqual(@as(?u64, 123_456), provider_mod.g_context_override);
try std.testing.expectEqual(@as(?u8, 55), provider_mod.g_compact_pct_override);
diff --git a/src/spec_prompt_cache_conformance.zig b/src/spec_prompt_cache_conformance.zig
index 062e3c87..ee9a1c53 100644
--- a/src/spec_prompt_cache_conformance.zig
+++ b/src/spec_prompt_cache_conformance.zig
@@ -93,6 +93,12 @@ test "prompt cache: every baked provider pins a key or Anthropic prefix" {
return error.ChildNotIsolated;
}
if (k1.len == 0) return error.EmptyCacheKey;
+ var pkbuf: [96]u8 = undefined;
+ const want = http_headers.promptCacheKey(root.io, root.label, &root, &pkbuf);
+ if (!std.mem.eql(u8, k1, want)) {
+ std.debug.print("\n{s}: cache key is not the project id\n", .{spec.id});
+ return error.CacheKeyNotProject;
+ }
} else {
if (cacheKeyIn(first) != null) {
std.debug.print("\n{s}: unexpected prompt_cache_key on Anthropic wire\n", .{spec.id});
@@ -134,7 +140,9 @@ test "prompt cache: xAI Responses header and body agree; OpenAI Responses has a
var ca = try agentFor(a, cd, "main", .responses);
const cb = try ca.buildBody(null, false, true, true);
defer std.testing.allocator.free(cb);
- try std.testing.expectEqualStrings(http_headers.sessionId(ca.io), cacheKeyIn(cb) orelse return error.MissingPromptCacheKey);
+ var ckbuf: [96]u8 = undefined;
+ try std.testing.expectEqualStrings(http_headers.promptCacheKey(ca.io, ca.label, &ca, &ckbuf), cacheKeyIn(cb) orelse return error.MissingPromptCacheKey);
+ try std.testing.expect(!std.mem.eql(u8, http_headers.sessionId(ca.io), cacheKeyIn(cb).?));
}
test "prompt cache: effort is never auto-flipped (prefix stays)" {