Skip to content

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

Python

fix: ten verified-open issues (#261 #323 #248 #287 #299 #266 #198 #303 #294 #56 #313 #311 #286 #308 #192 #106)

justrache8a35e05947a
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 9e0082d6..263f0bea 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -4,3 +4,6 @@
{"id": "todo-preserves-completed", "why": "2896b32: a replace that omits an already-completed item must keep it. Omitting finished work used to delete it, erasing the record of what was done.", "args": [], "prompt": "finish one step then replace the list without it", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "migrate the schema", "status": "completed"}, {"content": "backfill the rows", "status": "pending"}]}}, {"tool": "todo_write", "arguments": {"todos": [{"content": "backfill the rows", "status": "in_progress"}]}}, {"tool": "todo_read", "arguments": {}}, {"text": "still on the backfill"}], "assert": [{"request_contains": {"index": -1, "text": "migrate the schema"}}, {"request_contains": {"index": -1, "text": "backfill the rows"}}]}
{"id": "compaction-keeps-completed", "why": "#318: compaction mid-run must not lose the goal or the items already completed under it. The summary used to drop them and the run restarted work it had finished.", "args": ["--goal", "ship the migration"], "prompt": "start the work", "controls_after_turn": [{"type": "compact"}], "second_prompt": "keep going", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "write the migration", "status": "completed"}, {"content": "run it against staging", "status": "pending"}]}}, {"text": "migration written"}, {"text": "summary of the session so far: the migration is written"}, {"text": "running it against staging now"}], "assert": [{"event": {"type": "compact", "ok": true}}, {"request_contains": {"index": -1, "text": "write the migration"}}, {"request_contains": {"index": -1, "text": "ship the migration"}}]}
{"id": "tool-budget-stops-the-run", "why": "A run that will not stop is worse than one that stops early. --max-tool-calls has to be enforced against the root agent, not just advertised.", "args": ["--max-tool-calls", "2"], "prompt": "keep calling the todo tool", "script": [{"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"text": "stopping"}], "assert": [{"events_at_least": {"match": {"type": "tool_call_started"}, "count": 2}}, {"events_at_most": {"match": {"type": "tool_call_started"}, "count": 2}}, {"event": {"type": "turn"}}]}
+{"id": "ambiguous-asks-instead-of-guessing", "why": "#106: an ambiguous request has to reach the human as an ask_user event and come back carrying THEIR words. The regression is a harness that buries the question in an ordinary tool_call the client cannot answer, or that answers it itself and lets the run continue on the guess.", "args": [], "prompt": "add caching", "controls_after_turn": [{"type": "answer", "text": "an external store, and cap it at 500 entries"}], "script": [{"tool": "ask_user", "arguments": {"question": "Should the cache live in process memory or in an external store?", "options": ["process memory", "external store"]}}, {"text": "using the external store, capped as you asked"}], "assert": [{"event": {"type": "ask_user", "question": "Should the cache live in process memory or in an external store?"}}, {"events_at_most": {"match": {"type": "tool_call", "name": "ask_user"}, "count": 0}}, {"event": {"type": "tool_result", "name": "ask_user", "is_error": false, "text": "an external store, and cap it at 500 entries"}}, {"request_contains": {"index": -1, "text": "cap it at 500 entries"}}, {"no_event": {"type": "tool_call", "name": "write_file"}}, {"final_text_contains": "using the external store"}]}
+{"id": "two-file-edit-lands-both", "why": "#106: a two-file change has to land on disk, not merely be reported. The second edit_file only matches if the first write really happened, and the closing bash check prints its marker only when both files hold the new text - a reported-but-absent edit fails the case instead of passing it.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "raise the timeout to 60 and mark the import in the client", "script": [{"tool": "write_file", "arguments": {"path": "settings.py", "content": "TIMEOUT = 30\n"}}, {"tool": "write_file", "arguments": {"path": "client.py", "content": "from settings import TIMEOUT\n"}}, {"tool": "edit_file", "arguments": {"path": "settings.py", "old_string": "TIMEOUT = 30", "new_string": "TIMEOUT = 60"}}, {"tool": "edit_file", "arguments": {"path": "client.py", "old_string": "from settings import TIMEOUT", "new_string": "from settings import TIMEOUT # noqa"}}, {"tool": "bash", "arguments": {"command": "grep -q 'TIMEOUT = 60' settings.py && grep -q noqa client.py && echo both-edits-on-disk"}}, {"text": "both files are updated"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "edit_file"}, "count": 2}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"event": {"type": "tool_result", "name": "bash", "text": "both-edits-on-disk\n"}}, {"request_contains": {"index": -1, "text": "settings.py"}}, {"request_contains": {"index": -1, "text": "client.py"}}, {"final_text_contains": "both files are updated"}]}
+{"id": "failed-bash-is-not-reported-as-success", "why": "#106: a command that fails must come back marked is_error with its exit status and stderr intact, so the next turn cannot mistake it for success. The regression is a swallowed failure - a non-zero exit finishing as an ok tool_call, or output trimmed away before the model sees why it broke.", "args": [], "prompt": "run the config check", "script": [{"tool": "bash", "arguments": {"command": "ls missing_config.yaml; exit 7"}}, {"text": "the config check failed, so I am not claiming it passed"}], "assert": [{"event": {"type": "tool_call_finished", "name": "bash", "is_error": true}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": false}, "count": 0}}, {"request_contains": {"index": -1, "text": "[exit code 7]"}}, {"request_contains": {"index": -1, "text": "No such file or directory"}}, {"final_text_contains": "the config check failed"}]}
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index cf6fc74f..05e52c9a 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -10,7 +10,7 @@
"src/main.zig",
"src/repl.zig"
],
- "test_count_baseline": 518,
+ "test_count_baseline": 529,
"required_invariants": [
{
"id": "goal-epochs",
diff --git a/src/agent_context.zig b/src/agent_context.zig
index 02b76e38..bac47879 100644
--- a/src/agent_context.zig
+++ b/src/agent_context.zig
@@ -380,7 +380,19 @@ test "inputOverCompactThreshold (#193): local estimate gates a pre-send compact"
agent.sys_normal = &util.repeatBytes("x", 40_000);
try std.testing.expect(inputOverCompactThreshold(&agent));
agent.sys_normal = "";
- // unknown window (context 0) never gates
+ // #192: the reported overflow was a PARALLEL tool batch, not one fat result.
+ // Each function_call_output below sits far under compactAt() on its own; only
+ // the six together cross it, and the continuation request carrying the whole
+ // batch is the one the backend rejected. The gate has to weigh the history it
+ // is about to send, not the item it just appended.
+ const parallel = "{\"type\":\"function_call_output\",\"output\":\"" ++ util.repeatBytes("x", 5000) ++ "\"}";
+ const one_result = try std.json.parseFromSliceLeaky(Value, a, parallel, .{});
+ for (0..6) |_| {
+ try std.testing.expect(!inputOverCompactThreshold(&agent)); // no prefix of the batch trips it
+ try agent.messages.append(one_result);
+ }
+ try std.testing.expect(inputOverCompactThreshold(&agent)); // jointly over → compact before the continuation
+ // unknown window (context 0) never gates, even on this over-threshold history
agent.provider.context = 0;
try std.testing.expect(!inputOverCompactThreshold(&agent));
}
diff --git a/src/agent_request.zig b/src/agent_request.zig
index e89725fe..3f5de815 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -307,7 +307,10 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
// object — pull the final `response` out of it (or an error).
if (self.provider.kind == .responses) {
const r = self.parseResponses(resp_body) catch {
- try self.say("unparseable codex response: {s}\n", .{resp_body[0..@min(resp_body.len, 600)]});
+ // #287/#299: sayApiError so the body snippet survives as
+ // last_api_error; with plain say a subagent's parent got only
+ // the literal "ApiError" for this failure.
+ try self.sayApiError("unparseable codex response: {s}", .{resp_body[0..@min(resp_body.len, 600)]});
if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
return error.ApiError;
};
diff --git a/src/agent_request_body.zig b/src/agent_request_body.zig
index 2dd88e9b..2fb8fc66 100644
--- a/src/agent_request_body.zig
+++ b/src/agent_request_body.zig
@@ -44,7 +44,12 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
if (is_kimi) {
if (pricing.kimiSupportsThinking(self.provider.model)) {
try s.objectField("thinking");
- try s.print("{s}", .{"{\"type\":\"enabled\"}"});
+ // #323: k2.6 bills the reasoning we replay every turn and
+ // then ignores it unless the request says keep:"all".
+ if (pricing.kimiKeepsReasoning(self.provider.model))
+ try s.print("{s}", .{"{\"type\":\"enabled\",\"keep\":\"all\"}"})
+ else
+ try s.print("{s}", .{"{\"type\":\"enabled\"}"});
if (pricing.kimiThinkingEffort(self.provider.model, @tagName(self.reasoning))) |effort| {
try s.objectField("output_config");
try s.beginObject();
@@ -155,6 +160,11 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
try s.beginObject();
try s.objectField("type");
try s.write("enabled");
+ // #323: same per-model opt-in as the Anthropic branch above.
+ if (pricing.kimiKeepsReasoning(self.provider.model)) {
+ try s.objectField("keep");
+ try s.write("all");
+ }
if (pricing.kimiThinkingEffort(self.provider.model, @tagName(self.reasoning))) |effort| {
try s.objectField("effort");
try s.write(effort);
@@ -282,6 +292,7 @@ test "Kimi request body follows live native or Anthropic protocol metadata" {
try std.testing.expect(std.mem.indexOf(u8, native, "\"reasoning_effort\"") == null);
try std.testing.expect(std.mem.indexOf(u8, native, "\"target\":{\"anyOf\":[{\"const\":\"one\",\"type\":\"string\"},{\"const\":\"two\",\"type\":\"string\"}]}") != null);
try std.testing.expect(std.mem.indexOf(u8, native, "\"oneOf\":[{\"required\":[\"target\"],\"type\":\"object\"},{\"required\":[\"other\"],\"type\":\"object\"}]") != null);
+ try std.testing.expect(std.mem.indexOf(u8, native, "\"keep\"") == null); // #323: k3 has no thinking.keep
agent.provider.kind = .anthropic;
agent.provider.auth = .x_api_key;
@@ -295,6 +306,7 @@ test "Kimi request body follows live native or Anthropic protocol metadata" {
try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"system\":[{\"type\":\"text\",\"text\":\"system\",\"cache_control\":{\"type\":\"ephemeral\"}}]") != null);
try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"content\":[{\"type\":\"text\",\"text\":\"hello\",\"cache_control\":{\"type\":\"ephemeral\"}}]") != null);
try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"input_schema\":{\"type\":\"object\"},\"cache_control\":{\"type\":\"ephemeral\"}") != null);
+ try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"keep\"") == null); // #323: k3 has no thinking.keep
}
// ── Retained-reasoning wire-format regressions ──────────────────────────────
@@ -546,4 +558,39 @@ test "anthropic asks for summarized thinking; other anthropic-format providers d
defer std.testing.allocator.free(body_c);
try std.testing.expect(std.mem.indexOf(u8, body_c, "\"thinking\":{\"type\":\"adaptive\"}") != null);
try std.testing.expect(std.mem.indexOf(u8, body_c, "\"display\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, body_c, "\"keep\"") == null); // #323: thinking.keep is Kimi-only
+}
+
+test "kimi k2.6 opts into thinking.keep so replayed reasoning is used, not just billed" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const saved = pricing.active_model_table;
+ defer pricing.active_model_table = saved;
+ // Live-catalog shape for a keep-wanting model. #323: k2.6 supports
+ // `thinking.keep` and defaults it to null, so without keep:"all" the
+ // reasoning_content we replay each turn is billed and then discarded.
+ const rows = [_]pricing.ModelInfo{.{ .provider = "kimi", .name = "kimi-k2.6", .context = 262_144, .supports_reasoning = true }};
+ try std.testing.expect(pricing.activateKimiModels(arena, &rows));
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "kimi-k2.6", .context = 262_144 },
+ .messages = std.json.Array.init(arena),
+ .sub = false,
+ .label = "",
+ .out = null,
+ .sys_normal = "system",
+ };
+ const keep = "\"thinking\":{\"type\":\"enabled\",\"keep\":\"all\"}";
+ const native = try agent.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(native);
+ try std.testing.expect(std.mem.indexOf(u8, native, keep) != null);
+ // Kimi's Anthropic transport carries the same opt-in.
+ agent.provider.kind = .anthropic;
+ const anthropic = try agent.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(anthropic);
+ try std.testing.expect(std.mem.indexOf(u8, anthropic, keep) != null);
}
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 352cbbca..c6310982 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -40,8 +40,18 @@ const sseIndex = Agent.sseIndex;
/// collect any function calls. Returns final text when no tools were
/// called, else null to loop after running them.
pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
- const output = response.get("output") orelse return error.ApiError;
- if (output != .array) return error.ApiError;
+ // #287/#299: every error.ApiError raised in this file has to leave a cause
+ // behind. subagent_run hands agent.last_api_error to the parent's tool
+ // result, so a bare `return error.ApiError` reached the parent as the
+ // literal string "ApiError" — the opaque failure both issues report.
+ const output = response.get("output") orelse {
+ try self.sayApiError("api error: codex response had no output field", .{});
+ return error.ApiError;
+ };
+ if (output != .array) {
+ try self.sayApiError("api error: codex response output was not an array", .{});
+ return error.ApiError;
+ }
var calls: std.ArrayList(ToolCall) = .empty;
defer calls.deinit(self.gpa);
@@ -117,12 +127,14 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
}
pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
+ // #287/#299: sayApiError, not say — the text has to survive as
+ // last_api_error for the subagent/workflow failure report, not just print.
const content = root.get("content") orelse {
- try self.say("[api error: response had no content]\n", .{});
+ try self.sayApiError("api error: response had no content", .{});
return error.ApiError;
};
if (content != .array) {
- try self.say("[api error: malformed content block]\n", .{});
+ try self.sayApiError("api error: malformed content block", .{});
return error.ApiError;
}
const stop_reason = if (root.get("stop_reason")) |s| (if (s == .string) s.string else "") else "";
@@ -177,17 +189,19 @@ pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
const choices = root.get("choices");
+ // #287/#299: same as the anthropic step — the parent only ever sees what
+ // sayApiError records, so these three shapes must name themselves.
if (choices == null or choices.? != .array or choices.?.array.items.len == 0 or choices.?.array.items[0] != .object) {
- try self.say("[api error: response had no choices]\n", .{});
+ try self.sayApiError("api error: response had no choices", .{});
return error.ApiError;
}
const choice = choices.?.array.items[0].object;
const message = choice.get("message") orelse {
- try self.say("[api error: choice had no message]\n", .{});
+ try self.sayApiError("api error: choice had no message", .{});
return error.ApiError;
};
const msg_obj = tools_mod.json_args.object(message) orelse {
- try self.say("[api error: choice message was not an object]\n", .{});
+ try self.sayApiError("api error: choice message was not an object", .{});
return error.ApiError;
};
try self.messages.append(message); // echo verbatim (content may be null)
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index dd10ec1f..856254d2 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -41,7 +41,7 @@ const WatchdogFired = http.WatchdogFired;
const sendHeadTask = http.sendHeadTask;
const headStallTask = http.headStallTask;
const streamLineTask = http.streamLineTask;
-const streamStallTask = http.streamStallTask;
+const streamStallWatch = http.streamStallWatch;
const watchdogError = http.watchdogError;
// escPressed/drainSteerStdin/rawNonblockStdin/ssePayload live in
@@ -342,9 +342,10 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
defer line.deinit();
stream: while (true) {
- // Race the line read against an idle-stall watchdog so a dead
- // stream can't hang the turn (the Esc escape below is TTY-only, so
- // --json/GUI sessions would otherwise wait forever).
+ // Race the line read against an idle-stall watchdog so a dead stream can't
+ // hang the turn (the Esc escape below is TTY-only, so --json/GUI sessions
+ // would otherwise wait forever). #56: a non-empty partial_text (cleared per
+ // stream above) means tokens already flowed, so the silence trips sooner.
read: {
const ReadDone = union(enum) { line: anyerror!usize, stall: WatchdogFired };
var rd_buf: [2]ReadDone = undefined;
@@ -366,7 +367,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
if (req.connection) |conn| conn.closing = true;
return error.StreamStalled;
};
- rsel.concurrent(.stall, streamStallTask, .{ self.io, orig_tio != null }) catch {
+ rsel.concurrent(.stall, streamStallWatch, .{ self.io, orig_tio != null, self.partial_text.items.len != 0 }) catch {
const r = rsel.await() catch |e| {
rsel.cancelDiscard();
return e;
@@ -399,11 +400,10 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
.stall => |w| {
self.flushStreamTail();
if (req.connection) |conn| conn.closing = true;
- // A user Esc is a deliberate cancel; a `.deadline` is a dead
- // or idle stream (no SSE bytes for stream_stall_ms) — end the
- // turn, but as error.StreamStalled so it is never recorded as
- // "[response interrupted by user]" (#134). The notice below is
- // for the deadline case only (Esc has its own message path).
+ // A user Esc is a deliberate cancel; a `.deadline` is a dead or
+ // idle stream (silent past this read's budget) — end the turn as
+ // error.StreamStalled so it is never recorded as "[response
+ // interrupted by user]" (#134). The notice below is deadline-only.
if (w == .deadline and !main_mod.json_mode) if (self.out) |o| {
o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};
o.flush() catch {};
diff --git a/src/exec.zig b/src/exec.zig
index 4553c8b9..d997743a 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -48,7 +48,8 @@ const confinedPath = approvals_mod.confinedPath;
const noSymlinkEscape = approvals_mod.noSymlinkEscape;
const jobs = @import("jobs.zig");
const runCapped = jobs.runCapped;
-const runCappedCwd = jobs.runCappedCwd; // #276 P0-1: bash cwd for a worktree-isolated agent
+const runCappedWithOptions = jobs.runCappedWithOptions;
+const toolRunOptions = jobs.toolRunOptions; // #266/#198: own the child's process group
const spawnJob = jobs.spawnJob;
const jobOutput = jobs.jobOutput;
const jobKill = jobs.jobKill;
@@ -66,6 +67,12 @@ const learning_privacy = @import("learning_privacy.zig");
/// no-deadline behavior (a human is watching and may want a long build).
const subagent_bash_deadline_ms: u64 = 120 * 1000;
+/// Wall-clock ceiling for one `codedb` query (#198). Every allowed subcommand
+/// is a read that normally answers in seconds; a query that has not returned
+/// in a minute is stuck, and before this it stayed stuck forever — the tool
+/// blocked on EOF with no deadline at all.
+const codedb_deadline_ms: u64 = 60 * 1000;
+
fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {
var argc: usize = 0;
for ([_][]const u8{ exe_path, "--learning-privacy", if (contribute) "aggregate" else "local", "learn", "run" }) |arg| {
@@ -214,10 +221,10 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// #276 P0-1: a worktree-isolated agent's bash calls run pinned to its
// own worktree — via std.process.Child.Cwd, per spawn, never a
// process-wide chdir — so parallel siblings never share a cwd.
- const run = if (ctx.agent_cwd) |cw|
- try runCappedCwd(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline, .{ .path = cw })
- else
- try runCapped(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline);
+ // #266/#198: toolRunOptions also gives the command its own process
+ // group, so an Esc cancel or the deadline kills what it spawned (ssh,
+ // xcodebuild) instead of leaving it running against a dead turn.
+ const run = try runCappedWithOptions(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline, toolRunOptions(ctx.agent_cwd));
defer gpa.free(run.stdout);
defer gpa.free(run.stderr);
@@ -344,15 +351,24 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
argv.append(gpa, "codedb") catch {};
argv.append(gpa, sub) catch {};
while (it.next()) |tok| argv.append(gpa, tok) catch {};
- var child = std.process.spawn(io, .{ .argv = argv.items, .stdin = .ignore, .stdout = .pipe, .stderr = .ignore }) catch {
- return .{ .text = try gpa.dupe(u8, "codedb isn't installed — it's open source at github.com/justrach/codedb; install it, then run `codedb` once in the repo to index it"), .is_error = true };
+ // #198: this used to spawn by hand and block until EOF — no deadline, no
+ // process group, no Esc check — which is how abandoned sessions ended up
+ // owning dozens of `codedb search` children still asleep days later. The
+ // capped runner owns the group and tears it down on Esc or the deadline.
+ const run = runCappedWithOptions(gpa, io, argv.items, 512 * 1024, 4096, codedb_deadline_ms, toolRunOptions(null)) catch |e| switch (e) {
+ error.FileNotFound => return .{ .text = try gpa.dupe(u8, "codedb isn't installed — it's open source at github.com/justrach/codedb; install it, then run `codedb` once in the repo to index it"), .is_error = true },
+ else => return failure(gpa, e),
};
- const out_file = child.stdout orelse return .{ .text = try gpa.dupe(u8, "codedb: no output stream"), .is_error = true };
- var rbuf: [4096]u8 = undefined;
- var fr = out_file.readerStreaming(io, &rbuf);
- const text = fr.interface.allocRemaining(gpa, .limited(512 * 1024)) catch |e| return failure(gpa, e);
- _ = child.wait(io) catch {};
- if (text.len == 0) return .{ .text = try gpa.dupe(u8, "(codedb returned nothing — try `codedb tree` to confirm the repo is indexed, or refine the query)") };
+ gpa.free(run.stderr);
+ const text = run.stdout;
+ if (run.timed_out) {
+ defer gpa.free(text);
+ return .{ .text = try std.fmt.allocPrint(gpa, "codedb {s} timed out after {d}s and was killed — narrow the query, or run it through bash if it really needs that long", .{ sub, codedb_deadline_ms / 1000 }), .is_error = true };
+ }
+ if (text.len == 0) {
+ defer gpa.free(text);
+ return .{ .text = try gpa.dupe(u8, "(codedb returned nothing — try `codedb tree` to confirm the repo is indexed, or refine the query)") };
+ }
// Context guard: an unbounded `read <big file>` once dumped 500KB into
// a subagent's context, ballooning it to 160k tokens and minutes-long
// API calls. Cap what reaches the model and point it at targeted reads.
diff --git a/src/http.zig b/src/http.zig
index 2ab46cb2..b1e3e95e 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -15,6 +15,7 @@ const agent_mod = @import("agent.zig");
const Provider = provider_mod.Provider;
const Agent = agent_mod.Agent;
const headers = @import("http_headers.zig");
+const stall = @import("http_stall.zig"); // #56: the watchdogs' pure budget arithmetic
/// Launch-scoped gate installed while the shared client's CA bundle warms in
/// the background. Null in unit tests and standalone pre-client subcommands.
@@ -228,16 +229,14 @@ fn postWatchdog(io: Io) WatchdogFired {
return .deadline;
}
-// A streaming response idle THIS LONG between SSE events (not total response
-// time — streamStallTask resets its clock on every line, so it measures the
-// gap between tokens/keep-alives/reasoning deltas) is treated as a dead or
-// hung connection and given up on, so a turn can't wait forever. Generous, so
-// a legit reasoning pause between tokens doesn't trip it; a model that streams
-// — even slowly — never does, since each event resets the clock. Only TOTAL
-// silence trips it. Tunable via GRAFF_STREAM_STALL_SECS (wired in
-// session_run.setupSkillsAndTheme) for providers that buffer a long reasoning
-// phase in complete silence. Giving up here is error.StreamStalled — a
-// harness stall, NEVER a user Esc interruption (#134).
+// A streaming response idle THIS LONG (not total response time — the watchdog
+// resets its clock on every line, so it measures the gap between tokens/
+// keep-alives/reasoning deltas) is a dead or hung connection, so a turn can't
+// wait forever. This is the PRE-first-token budget, generous because a silent
+// reasoning phase legitimately runs minutes; http_stall.budgetMs tightens it
+// once tokens are flowing (#56). Tunable via GRAFF_STREAM_STALL_SECS (wired in
+// session_run.setupSkillsAndTheme), which scales both regimes. Giving up here
+// is error.StreamStalled — a harness stall, NEVER a user Esc (#134).
pub var stream_stall_ms: u64 = 120 * 1000;
/// A response head (HTTP status line + headers) idle this long means the
@@ -299,11 +298,11 @@ pub fn streamLineTask(reader: *Io.Reader, w: *Io.Writer) anyerror!usize {
return reader.streamDelimiterEnding(w, '\n');
}
-/// Select-arm wrapper: fires after stream_stall_ms of no line (idle stall), or
+/// Select-arm wrapper: fires after this read's stall budget with no line, or
/// early on Esc — resets each line, so it measures the gap between lines.
-pub fn streamStallTask(io: Io, poll_stdin: bool) WatchdogFired {
+pub fn streamStallWatch(io: Io, poll_stdin: bool, tokens_flowing: bool) WatchdogFired {
var waited: u64 = 0;
- while (waited < stream_stall_ms) {
+ while (!stall.expired(waited, stream_stall_ms, tokens_flowing)) {
io.sleep(.fromMilliseconds(50), .awake) catch return .deadline; // canceled: a line arrived
waited += 50;
if (poll_stdin and Agent.drainSteerStdin(true)) {
@@ -315,6 +314,11 @@ pub fn streamStallTask(io: Io, poll_stdin: bool) WatchdogFired {
return .deadline;
}
+/// Pre-first-token arm: the codex WS reader has no per-read token signal (#56).
+pub fn streamStallTask(io: Io, poll_stdin: bool) WatchdogFired {
+ return streamStallWatch(io, poll_stdin, false);
+}
+
/// Select-arm wrapper: fires after head_stall_ms (head receive stall), or
/// early on Esc. Races postStream's send + receiveHead so a freshly-redialed
/// connection that the server accepts but never answers can't hang the turn
diff --git a/src/http_stall.zig b/src/http_stall.zig
new file mode 100644
index 00000000..42efaf8e
--- /dev/null
+++ b/src/http_stall.zig
@@ -0,0 +1,63 @@
+//! Stall-budget arithmetic for the streaming watchdogs (#56). Pure: no Io, no
+//! globals, so both regimes are testable at their boundary without sleeping
+//! through a real 120s stall. Lives beside http.zig (which is at the 600-line
+//! cap) the way http_headers.zig does; http.zig owns the watchdog loops and
+//! the configured budget, this owns the decision they make each tick.
+
+const std = @import("std");
+
+/// Once tokens are flowing, a stream gets this fraction of the pre-first-token
+/// budget: bytes were arriving and stopped, which is a dead socket rather than
+/// a model thinking, and the next token was milliseconds away. A fraction of
+/// the configured budget rather than a second env knob, so
+/// GRAFF_STREAM_STALL_SECS still scales BOTH regimes for a slow provider.
+const idle_divisor: u64 = 4;
+
+/// ...but never below this, so a small GRAFF_STREAM_STALL_SECS cannot shrink
+/// the between-lines budget to a couple of seconds and start killing healthy
+/// streams. Clamped to the configured budget, which always wins when smaller.
+const idle_floor_ms: u64 = 15 * 1000;
+
+/// How long a stream read may sit silent before the watchdog calls it dead.
+/// `base_ms` is the configured budget (http.stream_stall_ms); `tokens_flowing`
+/// says whether THIS stream has already emitted tokens.
+pub fn budgetMs(base_ms: u64, tokens_flowing: bool) u64 {
+ if (!tokens_flowing) return base_ms; // pre-first-token: a legit long reasoning pause
+ return @min(base_ms, @max(idle_floor_ms, base_ms / idle_divisor));
+}
+
+/// True once a silent read has outlasted its budget — the watchdog loop's only
+/// decision, split out so it can be exercised at the boundary in a unit test.
+pub fn expired(waited_ms: u64, base_ms: u64, tokens_flowing: bool) bool {
+ return waited_ms >= budgetMs(base_ms, tokens_flowing);
+}
+
+test "stall budget (#56): between-lines silence trips sooner than a pre-first-token pause" {
+ const base: u64 = 120 * 1000; // the shipped http.stream_stall_ms default
+
+ // Before the first token the full budget stands: a reasoning model can be
+ // silent for minutes before it emits anything, so nothing shorter is safe.
+ try std.testing.expectEqual(base, budgetMs(base, false));
+ try std.testing.expect(!expired(base - 1, base, false));
+ try std.testing.expect(expired(base, base, false));
+
+ // Tokens already flowed: a quarter of it (30s), so a dead stream is given
+ // up on 4x sooner instead of holding the turn for another 90s of silence.
+ try std.testing.expectEqual(@as(u64, 30 * 1000), budgetMs(base, true));
+ try std.testing.expect(!expired(30 * 1000 - 1, base, true));
+ try std.testing.expect(expired(30 * 1000, base, true));
+ // The whole point of the split: at 30s of silence the between-lines regime
+ // is done and the pre-first-token one is still waiting.
+ try std.testing.expect(expired(30 * 1000, base, true) and !expired(30 * 1000, base, false));
+
+ // GRAFF_STREAM_STALL_SECS (session_run writes http.stream_stall_ms, which
+ // arrives here as base_ms) keeps scaling both regimes.
+ try std.testing.expectEqual(@as(u64, 600 * 1000), budgetMs(600 * 1000, false));
+ try std.testing.expectEqual(@as(u64, 150 * 1000), budgetMs(600 * 1000, true));
+
+ // A short override floors the between-lines budget instead of shrinking it
+ // to seconds, and never outlasts the configured total.
+ try std.testing.expectEqual(idle_floor_ms, budgetMs(20 * 1000, true));
+ try std.testing.expectEqual(@as(u64, 5 * 1000), budgetMs(5 * 1000, true));
+ try std.testing.expect(expired(5 * 1000, 5 * 1000, true));
+}
diff --git a/src/jobs.zig b/src/jobs.zig
index d691f05d..3bf42933 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -37,6 +37,20 @@ pub fn runCappedCwd(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap
return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{ .cwd = cwd });
}
+/// Run options for a FOREGROUND tool subprocess (the `bash` and `codedb`
+/// tools). kill_process_tree is always on here: the child leads its own
+/// process group, so an Esc cancel or a deadline takes the grandchildren down
+/// with it instead of orphaning them onto init — the `ssh` left running after
+/// an interrupt in #266, the `codedb search` / `xcodebuild` trees that
+/// outlived their session for days in #198. `cwd` is null unless the caller is
+/// a worktree-isolated agent (#276 P0-1).
+pub fn toolRunOptions(cwd: ?[]const u8) CappedRunOptions {
+ return .{
+ .cwd = if (cwd) |path| .{ .path = path } else .inherit,
+ .kill_process_tree = true,
+ };
+}
+
const agent_worktree = @import("agent_worktree.zig");
pub const AgentWorktree = agent_worktree.AgentWorktree;
pub const AgentWorktreeError = agent_worktree.AgentWorktreeError;
@@ -259,6 +273,10 @@ const Job = struct {
const job_unread_cap = 256 * 1024;
const job_wait_cap_ms: u64 = 30_000;
+/// POSIX process groups; windows/wasi have none, so the group kills below and
+/// the job's own pgid are compiled out there (#198).
+const posix_groups = builtin.os.tag != .windows and builtin.os.tag != .wasi;
+
const Jobs = struct {
mutex: Io.Mutex = .init,
list: std.ArrayList(*Job) = .empty,
@@ -318,6 +336,10 @@ fn jobPump(job: *Job, gpa: Allocator, io: Io) void {
g_jobs.mutex.unlock(io);
var code: ?u8 = null;
if (killed) {
+ // #198: take the whole process group down first — a job's grandchildren
+ // (ssh, xcodebuild, codedb) survive a bare child.kill and are then
+ // reparented to init, where they sleep on for days.
+ if (comptime posix_groups) if (job.child.id) |pid| std.posix.kill(-pid, .KILL) catch {};
job.child.kill(io); // also reaps (wait would assert afterwards)
} else if (job.child.wait(io)) |term| {
code = switch (term) {
@@ -352,6 +374,9 @@ pub fn spawnJob(gpa: Allocator, io: Io, cmd: []const u8) !*Job {
.stdin = .ignore,
.stdout = .pipe,
.stderr = .pipe,
+ // #198: the job leads its own process group, so bash_kill / jobsReap
+ // reach everything it spawned, not just the shell.
+ .pgid = if (posix_groups) 0 else null,
});
const cmd_copy = gpa.dupe(u8, cmd) catch |e| {
child.kill(io);
@@ -498,6 +523,35 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {
g_jobs.list.deinit(gpa);
}
+test "foreground tool subprocesses own their process group (#266, #198)" {
+ const inherited = toolRunOptions(null);
+ try std.testing.expect(inherited.kill_process_tree);
+ try std.testing.expect(std.meta.activeTag(inherited.cwd) == .inherit);
+ const pinned = toolRunOptions("/tmp/graff-worktree");
+ try std.testing.expect(pinned.kill_process_tree);
+ try std.testing.expectEqualStrings("/tmp/graff-worktree", pinned.cwd.path);
+}
+
+test "killing a background job takes its grandchildren with it (#198)" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ // The job inherits this process's cwd, the one tmpDir resolved .zig-cache
+ // against, so the marker path is reachable from the shell. The grandchild
+ // detaches from the job's pipes or the pump never sees EOF; `sh` execs the
+ // trailing sleep, so a bare child kill orphans the marker subshell.
+ const cmd = try std.fmt.allocPrint(gpa, "(sleep 0.8; printf survived > .zig-cache/tmp/{s}/marker) >/dev/null 2>&1 & sleep 30", .{&tmp.sub_path});
+ defer gpa.free(cmd);
+ const id = (try spawnJob(gpa, io, cmd)).id;
+ defer jobsReap(gpa, io);
+ const killed = try jobKill(gpa, io, id);
+ gpa.free(killed.text);
+ io.sleep(.fromMilliseconds(1_200), .awake) catch {};
+ try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "marker", .{}));
+}
+
test "isolated capped runs clean descendants after timeout and normal exit" {
if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
const io = std.testing.io;
diff --git a/src/learn_delete.zig b/src/learn_delete.zig
index f36b2d74..58c767f6 100644
--- a/src/learn_delete.zig
+++ b/src/learn_delete.zig
@@ -7,13 +7,16 @@ const Allocator = std.mem.Allocator;
const eval = @import("learn_eval.zig");
const learn_run = @import("learn_run.zig");
+const mcp_teardown = @import("mcp_teardown.zig");
const receipt = @import("learn_receipt.zig");
const scoring = @import("scoring.zig");
const store_mod = @import("learn_store.zig");
const submit = @import("learn_submit.zig");
-const telemetry = @import("telemetry.zig");
const telemetry_net = @import("telemetry_net.zig");
+/// How long the collector gets to answer one DELETE before we stop waiting.
+const delete_deadline = Io.Duration.fromSeconds(10);
+
fn learningUrl(gpa: Allocator, endpoint: []const u8, run_id: []const u8) ![]u8 {
const logs_url = (try telemetry_net.otlpLogsUrl(gpa, endpoint)) orelse
return error.InvalidTelemetryEndpoint;
@@ -35,24 +38,69 @@ fn deleteRequest(client: *std.http.Client, url: []const u8, token: []const u8) u
return @intFromEnum(response.status);
}
-fn deleteWithDeadline(io: Io, client: *std.http.Client, url: []const u8, token: []const u8) u16 {
- const Done = union(enum) { status: u16, deadline: void };
- var done_buf: [2]Done = undefined;
- var select: Io.Select(Done) = .init(io, &done_buf);
- select.concurrent(.deadline, telemetry.Telemetry.flushDeadline, .{ io, Io.Duration.fromSeconds(10) }) catch return 0;
- select.concurrent(.status, deleteRequest, .{ client, url, token }) catch {
- select.cancelDiscard();
- return 0;
- };
- const first = select.await() catch {
- select.cancelDiscard();
- return 0;
- };
- select.cancelDiscard();
- return switch (first) {
- .status => |status| status,
- .deadline => 0,
- };
+/// One DELETE plus every byte it touches, in heap state the caller does not
+/// own. A request that overruns the deadline keeps running on a detached
+/// thread (#303), so nothing it reads may live in the caller's frame, and its
+/// client draws on a process-lifetime allocator rather than the session gpa:
+/// pool memory left behind by an abandoned request would otherwise surface in
+/// the gpa's exit-time leak report and read as a harness bug.
+const Deletion = struct {
+ client: std.http.Client,
+ url: []u8,
+ token: []u8,
+ status: u16 = 0,
+
+ fn create(heap: Allocator, io: Io, url: []const u8, token: []const u8) !*Deletion {
+ const self = try heap.create(Deletion);
+ errdefer heap.destroy(self);
+ const url_copy = try heap.dupe(u8, url);
+ errdefer heap.free(url_copy);
+ self.* = .{
+ .client = .{ .allocator = heap, .io = io },
+ .url = url_copy,
+ .token = try heap.dupe(u8, token),
+ };
+ return self;
+ }
+
+ fn destroy(self: *Deletion, heap: Allocator) void {
+ self.client.deinit();
+ heap.free(self.token);
+ heap.free(self.url);
+ heap.destroy(self);
+ }
+
+ fn send(self: *Deletion) void {
+ self.status = deleteRequest(&self.client, self.url, self.token);
+ }
+};
+
+/// Run `send(state)` under `deadline` and read back the status it recorded,
+/// or null when the deadline wins.
+///
+/// #303: work that overruns the deadline is ABANDONED, never cancelled. The
+/// old shape raced the request against the deadline in an Io.Select and then
+/// called cancelDiscard(), which cancels AND synchronously joins whatever is
+/// left. Against the real TLS collector that cancel landed inside an in-flight
+/// read and panicked, so `learn delete-remote` crashed instead of reporting a
+/// failure, and deletion is the one guarantee a user cannot work around.
+/// mcp_teardown.runBounded (#305) exists for exactly this shape: it detaches
+/// the work, waits out the deadline, and walks away without touching it again.
+fn statusWithin(io: Io, deadline: Io.Duration, comptime send: anytype, state: anytype) ?u16 {
+ // page_allocator, not the session gpa: the bookkeeping for an abandoned
+ // task is leaked on purpose and must not read as a harness leak at exit.
+ if (!mcp_teardown.runBounded(std.heap.page_allocator, io, deadline, send, .{state})) return null;
+ return state.status;
+}
+
+fn deleteWithDeadline(io: Io, url: []const u8, token: []const u8) u16 {
+ const heap = std.heap.page_allocator;
+ const deletion = Deletion.create(heap, io, url, token) catch return 0;
+ // Nothing is reclaimed on the null branch: the request is still in flight
+ // on a detached thread, so `deletion` is leaked on purpose (#303).
+ const status = statusWithin(io, delete_deadline, Deletion.send, deletion) orelse return 0;
+ deletion.destroy(heap);
+ return status;
}
pub fn command(
@@ -87,9 +135,7 @@ pub fn command(
const endpoint = try submit.deletionEndpoint(environ);
const url = try learningUrl(gpa, endpoint, run_id);
defer gpa.free(url);
- var client: std.http.Client = .{ .allocator = gpa, .io = io };
- defer client.deinit();
- switch (deleteWithDeadline(io, &client, url, &token)) {
+ switch (deleteWithDeadline(io, url, &token)) {
200, 202, 204 => try out.print(
"deleted remote aggregate receipt for run {s}; local evidence was not changed\n",
.{run_id},
@@ -110,3 +156,36 @@ test "learning receipt URL preserves endpoint query parameters" {
url,
);
}
+
+test "a DELETE that overruns its deadline is abandoned, not cancelled (#303)" {
+ // #303: `learn delete-remote` panicked against the real TLS collector
+ // because the deadline branch cancelled the losing request arm, and
+ // Io.Select.cancelDiscard() cancels AND synchronously joins its loser.
+ // The stall below parks where Io has no cancelation point at all, which
+ // is what an in-flight read looks like to a canceller: an implementation
+ // that joins its loser cannot come back before the stall ends, and this
+ // test catches it by finding the request already finished.
+ const Stall = struct {
+ io: Io,
+ status: u16 = 200,
+ finished: std.atomic.Value(bool) = .init(false),
+
+ fn send(self: *@This()) void {
+ // A spin, not io.sleep: io.sleep IS cancelable, so a sleeping
+ // stall would let the very shape this test rejects pass.
+ const end = Io.Timestamp.now(self.io, .awake).nanoseconds + 3 * std.time.ns_per_s;
+ while (Io.Timestamp.now(self.io, .awake).nanoseconds < end) std.atomic.spinLoopHint();
+ self.finished.store(true, .release);
+ }
+ };
+ const io = std.testing.io;
+ // page_allocator: abandoned state is leaked by design, and a
+ // leak-checking allocator would misreport that as a test failure.
+ const heap = std.heap.page_allocator;
+ const stall = try heap.create(Stall);
+ stall.* = .{ .io = io };
+ try std.testing.expect(statusWithin(io, .fromMilliseconds(50), Stall.send, stall) == null);
+ // Asserted on STATE, not on the clock: a shared CI runner makes elapsed
+ // time a flaky proxy, but "the request is still running" is exact.
+ try std.testing.expect(!stall.finished.load(.acquire));
+}
diff --git a/src/main.zig b/src/main.zig
index 8c173264..2a9a71d1 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -54,8 +54,7 @@ const util = @import("util.zig"); // shared JSON ObjectMap getters (strFieldObj/
const learn_store = @import("learn_store.zig");
const learn_eval = @import("learn_eval.zig");
const learn_cli = @import("learn_cli.zig");
-test {
- // build.zig's unit_tests root is main.zig only — reference every split-out module so their test blocks keep running.
+test { // unit_tests' root is main.zig only, so reference every split-out module or its tests silently never run
_ = pricing;
_ = models_cache;
_ = ansi;
@@ -590,6 +589,7 @@ test { // pull in tests from imported modules (mcp.zig)
// plain @import elsewhere (or a type-only alias) is NOT enough — it
// compiles to nothing; scripts/eval-tier1.sh --only reach catches one.
_ = @import("scoring_slot_test.zig");
+ _ = @import("learn_delete.zig"); // #303: its tests were dead until listed here
_ = @import("readline_history.zig");
_ = @import("goal_pacing_autonomous_test.zig");
_ = @import("goal_state.zig");
diff --git a/src/pricing.zig b/src/pricing.zig
index 52483fa2..3ce0547b 100644
--- a/src/pricing.zig
+++ b/src/pricing.zig
@@ -297,6 +297,14 @@ pub fn kimiThinkingEffort(model: []const u8, requested: []const u8) ?[]const u8
return info.support_efforts[info.support_efforts.len / 2];
}
+/// Kimi k2.6 defaults `thinking.keep` to null: the server bills the reasoning
+/// we replay each turn and then ignores it (#323). k2.7-code always preserves
+/// and k3 rejects the parameter; the live catalog says nothing about keep, so
+/// this is a seeded id check (a point release is spelled `k2.6` or `k2p6`).
+pub fn kimiKeepsReasoning(model: []const u8) bool {
+ return kimiSupportsThinking(model) and (std.mem.indexOf(u8, model, "k2.6") != null or std.mem.indexOf(u8, model, "k2p6") != null);
+}
+
fn pureKimiGeneration(name: []const u8) ?u32 {
if (name.len < 2 or name[0] != 'k') return null;
for (name[1..]) |c| if (!std.ascii.isDigit(c)) return null;
diff --git a/src/providers.zig b/src/providers.zig
index 0d81fe82..58d07f37 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -156,7 +156,12 @@ pub fn nextFallbackProvider(keys: Keys, after_id: []const u8, tried: []const []c
/// Only failures that clearly mean "this credential/model cannot serve the
/// request" are safe to fail over. Network flakes, rate limits, malformed
/// replies, context overflow, and interrupts stay on the selected provider.
-pub fn failoverEligible(detail: []const u8) bool {
+/// #294: the auth/model needles are universal, but the billing ones only
+/// qualify when the codegraff gateway raised them. A billing error from a
+/// provider the user keyed themselves is about their own account, and treating
+/// it as failover-eligible silently swapped their chosen model for some other
+/// provider's default.
+pub fn failoverEligible(provider_id: []const u8, detail: []const u8) bool {
const needles = [_][]const u8{
"unauthorized",
"authentication_error",
@@ -185,6 +190,10 @@ pub fn failoverEligible(detail: []const u8) bool {
"does not exist or you do not have access",
"you do not have access to model",
"you do not have access to this model",
+ };
+ for (needles) |needle| if (util.indexOfIgnoreCase(detail, needle) != null) return true;
+ if (!std.mem.eql(u8, provider_id, "codegraff")) return false;
+ const gateway_billing = [_][]const u8{
"insufficient_quota",
"quota exceeded",
"credits exhausted",
@@ -193,7 +202,7 @@ pub fn failoverEligible(detail: []const u8) bool {
"no credits",
"billing limit",
};
- for (needles) |needle| if (util.indexOfIgnoreCase(detail, needle) != null) return true;
+ for (gateway_billing) |needle| if (util.indexOfIgnoreCase(detail, needle) != null) return true;
return false;
}
@@ -223,7 +232,7 @@ pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*I
if (err != error.ApiError or root.partial_text.items.len != 0 or root.tool_calls_this_turn != 0)
return err;
const detail = root.last_api_error orelse return err;
- if (!failoverEligible(detail)) return err;
+ if (!failoverEligible(root.provider.id, detail)) return err;
const failed_id = root.provider.id;
const failed_model = root.provider.model;
root.ensureStoredKeys(keys);
@@ -371,14 +380,39 @@ test {
}
test "failoverEligible: accepts unavailable credentials/models, rejects transient or prompt errors" {
- try std.testing.expect(failoverEligible("codex api error: Unauthorized"));
- try std.testing.expect(failoverEligible("access token has expired"));
- try std.testing.expect(failoverEligible("model_not_found: rollout ended"));
- try std.testing.expect(failoverEligible("insufficient_quota"));
- try std.testing.expect(!failoverEligible("network error: HttpConnectionClosing"));
- try std.testing.expect(!failoverEligible("rate limited (429)"));
- try std.testing.expect(!failoverEligible("maximum context length exceeded"));
- try std.testing.expect(!failoverEligible("unparseable response"));
+ try std.testing.expect(failoverEligible("codex", "codex api error: Unauthorized"));
+ try std.testing.expect(failoverEligible("codex", "access token has expired"));
+ try std.testing.expect(failoverEligible("codex", "model_not_found: rollout ended"));
+ try std.testing.expect(failoverEligible("codegraff", "insufficient_quota"));
+ try std.testing.expect(!failoverEligible("codex", "network error: HttpConnectionClosing"));
+ try std.testing.expect(!failoverEligible("codex", "rate limited (429)"));
+ try std.testing.expect(!failoverEligible("codex", "maximum context length exceeded"));
+ try std.testing.expect(!failoverEligible("codex", "unparseable response"));
+}
+
+test "failoverEligible: billing needles only fire for the gateway (#294)" {
+ // The same detail string decides differently depending on who raised it:
+ // a low balance on the gateway is a reason to move, the user's own
+ // anthropic/codex billing is not.
+ const billing = [_][]const u8{
+ "your credit balance is too low",
+ "insufficient credits",
+ "credits exhausted",
+ "no credits remaining",
+ "billing limit reached",
+ "quota exceeded for this account",
+ "insufficient_quota",
+ };
+ for (billing) |detail| {
+ try std.testing.expect(failoverEligible("codegraff", detail));
+ try std.testing.expect(!failoverEligible("anthropic", detail));
+ try std.testing.expect(!failoverEligible("codex", detail));
+ try std.testing.expect(!failoverEligible("kimi", detail));
+ }
+ // Auth and model failures stay provider-agnostic.
+ try std.testing.expect(failoverEligible("anthropic", "invalid x-api-key"));
+ try std.testing.expect(failoverEligible("kimi", "model does not exist"));
+ try std.testing.expect(failoverEligible("codegraff", "unauthorized"));
}
test "nextFallbackProvider: rotates after the failed provider and skips missing or tried credentials" {
diff --git a/src/serde.zig b/src/serde.zig
index a2da152d..bc317b2d 100644
--- a/src/serde.zig
+++ b/src/serde.zig
@@ -165,16 +165,39 @@ pub fn writeAnthropicMessages(s: *std.json.Stringify, messages: std.json.Array,
try s.endArray();
}
+fn hasSchemaComposition(obj: std.json.ObjectMap) bool {
+ for ([_][]const u8{ "$ref", "allOf", "anyOf", "oneOf", "not", "if" }) |key| if (obj.get(key) != null) return true;
+ return false;
+}
+
+/// Issue #261: an MCP server may advertise an inputSchema with no root "type"
+/// (mcp.zig also defaults a missing one to `{}`), and it reached the wire
+/// verbatim — both Moonshot ("parameters.type is required and must be
+/// 'object'") and Anthropic reject the whole request for it, so no tool call
+/// ever got a chance to run. A tool's argument schema is an object by
+/// construction on both wires, so say so. A schema that already declares a
+/// type, or that defers to a root composition keyword, is left untouched.
+fn defaultRootObjectType(arena: Allocator, value: *Value) Allocator.Error!void {
+ if (value.* != .object) return;
+ if (value.object.get("type") != null or hasSchemaComposition(value.object)) return;
+ try value.object.put(arena, "type", .{ .string = "object" });
+}
+
/// Kimi's official Anthropic adapter places a cache breakpoint on the final
/// tool definition. The source catalog is already JSON, so rewrite only the
/// last object and fall back to the original bytes if a custom catalog is bad.
+/// The parse is unconditional because every catalog also needs the #261 root
+/// type repair, not just the cached ones.
pub fn writeAnthropicTools(s: *std.json.Stringify, arena: Allocator, raw: []const u8, cache: bool) !void {
- if (!cache) return s.print("{s}", .{raw});
const value = std.json.parseFromSliceLeaky(Value, arena, raw, .{ .allocate = .alloc_always }) catch return s.print("{s}", .{raw});
- if (value != .array or value.array.items.len == 0) return s.write(value);
+ if (value != .array or value.array.items.len == 0) return s.print("{s}", .{raw});
+ for (value.array.items) |*tool| {
+ if (tool.* != .object) continue;
+ if (tool.object.getPtr("input_schema")) |schema| try defaultRootObjectType(arena, schema);
+ }
try s.beginArray();
for (value.array.items, 0..) |tool, i| {
- if (i + 1 == value.array.items.len and tool == .object)
+ if (cache and i + 1 == value.array.items.len and tool == .object)
try writeObjectWithCache(s, tool.object)
else
try s.write(tool);
@@ -249,8 +272,11 @@ fn normalizeKimiSchema(arena: Allocator, value: *Value, root: bool) Allocator.Er
}
}
}
- const has_composition = obj.get("$ref") != null or obj.get("allOf") != null or obj.get("anyOf") != null or obj.get("oneOf") != null or obj.get("not") != null or obj.get("if") != null;
- if (!root and obj.get("type") == null and !has_composition) {
+ // The root never guesses (#261 wants "object" there, and inferredKimiType's
+ // fallback is "string"); every child keeps the kimi-code inference.
+ if (root) {
+ try defaultRootObjectType(arena, value);
+ } else if (obj.get("type") == null and !hasSchemaComposition(obj.*)) {
if (inferredKimiType(obj.*)) |kind| try obj.put(arena, "type", .{ .string = kind });
}
@@ -333,3 +359,57 @@ pub fn writeOpenAIMessageNormalized(s: *std.json.Stringify, m: Value) !void {
}
try s.endObject();
}
+
+fn renderKimiTools(arena: Allocator, raw: []const u8) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try writeKimiTools(&s, arena, raw);
+ return aw.writer.buffered();
+}
+
+fn renderAnthropicTools(arena: Allocator, raw: []const u8, cache: bool) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try writeAnthropicTools(&s, arena, raw, cache);
+ return aw.writer.buffered();
+}
+
+test "kimi tools give a typeless MCP root schema type object (#261)" {
+ var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ // mcp.zig substitutes `{}` for a server that advertises no inputSchema.
+ const empty = try renderKimiTools(arena, "[{\"type\":\"function\",\"function\":{\"name\":\"mcp__s__t\",\"description\":\"\",\"parameters\":{}}}]");
+ try std.testing.expect(std.mem.indexOf(u8, empty, "\"parameters\":{\"type\":\"object\"}") != null);
+
+ // Properties but no root type: the root says object, children still infer.
+ const props = try renderKimiTools(arena, "[{\"type\":\"function\",\"function\":{\"name\":\"mcp__s__t\",\"description\":\"\",\"parameters\":{\"properties\":{\"path\":{}}}}}]");
+ try std.testing.expect(std.mem.indexOf(u8, props, "\"parameters\":{\"properties\":{\"path\":{\"type\":\"string\"}},\"type\":\"object\"}") != null);
+
+ // A declared type and a root composition keyword are both left alone.
+ const typed = try renderKimiTools(arena, "[{\"type\":\"function\",\"function\":{\"name\":\"t\",\"description\":\"\",\"parameters\":{\"type\":\"string\"}}}]");
+ try std.testing.expect(std.mem.indexOf(u8, typed, "\"parameters\":{\"type\":\"string\"}") != null);
+ const composed = try renderKimiTools(arena, "[{\"type\":\"function\",\"function\":{\"name\":\"t\",\"description\":\"\",\"parameters\":{\"allOf\":[{\"type\":\"object\"}]}}}]");
+ try std.testing.expect(std.mem.indexOf(u8, composed, "\"parameters\":{\"allOf\":[{\"type\":\"object\"}]}") != null);
+}
+
+test "anthropic tools give a typeless MCP input_schema type object (#261)" {
+ var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const raw = "[{\"name\":\"mcp__s__t\",\"description\":\"\",\"input_schema\":{}}]";
+ try std.testing.expectEqualStrings(
+ "[{\"name\":\"mcp__s__t\",\"description\":\"\",\"input_schema\":{\"type\":\"object\"}}]",
+ try renderAnthropicTools(arena, raw, false),
+ );
+ // The repair survives the cache-breakpoint rewrite on the last tool.
+ const cached = try renderAnthropicTools(arena, raw, true);
+ try std.testing.expect(std.mem.indexOf(u8, cached, "\"input_schema\":{\"type\":\"object\"},\"cache_control\":{\"type\":\"ephemeral\"}") != null);
+
+ const composed = "[{\"name\":\"t\",\"description\":\"\",\"input_schema\":{\"oneOf\":[{\"type\":\"object\"}]}}]";
+ try std.testing.expectEqualStrings(composed, try renderAnthropicTools(arena, composed, false));
+ const typed = "[{\"name\":\"t\",\"description\":\"\",\"input_schema\":{\"type\":\"object\",\"properties\":{}}}]";
+ try std.testing.expectEqualStrings(typed, try renderAnthropicTools(arena, typed, false));
+}
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 64abe93e..513db41d 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -373,3 +373,43 @@ test "failureAllowsRetry keys off the harness's own retry-safety classification"
// classification was made, so it must keep retrying like before this fix.
try std.testing.expect(failureAllowsRetry("subagent finished without a report"));
}
+
+test "a child's api-error cause reaches the parent verbatim (#287/#299)" {
+ const gpa = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ // say() writes here instead of the terminal; what this pins is the copy
+ // sayApiError leaves behind on the agent.
+ var say_buf: [1024]u8 = undefined;
+ var sink = Io.Writer.fixed(&say_buf);
+ var child: Agent = .{
+ .gpa = gpa,
+ .arena = arena_state.allocator(),
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = true,
+ .label = "child",
+ .out = &sink,
+ };
+
+ // An empty body is a shape every wire format rejects. Each of these used to
+ // `return error.ApiError` without recording a cause, so subagentFailure
+ // fell back to @errorName and the parent's tool result read "ApiError" —
+ // the opaque failure #287/#299 report.
+ inline for (.{ Agent.stepAnthropic, Agent.stepOpenAI, Agent.stepResponses }) |step| {
+ child.last_api_error = null;
+ try std.testing.expectError(error.ApiError, step(&child, .empty));
+ try std.testing.expect(child.last_api_error != null);
+ const detail = child.last_api_error.?;
+
+ // This is the wiring runSub depends on: agent.last_api_error ->
+ // subagentFailure -> the string the parent's tool result carries.
+ const out = subagentFailure(gpa, "sa-001-abcd", error.ApiError, child.last_api_error);
+ defer gpa.free(out.text);
+ try std.testing.expect(out.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, detail) != null); // verbatim
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "ApiError") == null); // never the bare error name
+ }
+}
diff --git a/src/workflow.zig b/src/workflow.zig
index 27462252..9a3be3de 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -87,6 +87,32 @@ pub fn cappedPrevBody(arena: Allocator, text: []const u8, cap: usize) []const u8
return std.fmt.allocPrint(arena, "{s}\n\n…[{d} chars truncated — full result in the inspect file below]…\n\n{s}", .{ head, text.len - head.len - tail.len, tail }) catch text;
}
+// #248: a failed task's output text is the ONLY place the underlying API error
+// survives. The retry gate (failureAllowsRetry) read it and every render site
+// then threw it away, so a synthesis phase saw a detail-free "(no result —
+// task failed)" and could not tell a rate limit from a bad model id. The cap
+// is what makes surfacing it safe: at most max_workflow_tasks ×
+// fail_excerpt_cap (~1.7 KB) of error text can reach the next phase's prompt,
+// however large the error bodies were.
+pub const fail_excerpt_cap = 200;
+
+/// One-line, capped excerpt of a failed task's output, for the three render
+/// sites (#248). Head-biased because subagentFailure puts the cause right
+/// after its "subagent … failed …:" prefix. Newlines and tabs collapse to
+/// spaces so the excerpt can never break the "### label" header layout; blank
+/// input returns "" so callers keep the bare header.
+pub fn failExcerpt(arena: Allocator, text: []const u8) []const u8 {
+ const trimmed = std.mem.trim(u8, text, " \t\r\n");
+ if (trimmed.len == 0) return "";
+ const head = util.utf8Prefix(trimmed, fail_excerpt_cap);
+ const flat = arena.dupe(u8, head) catch return "";
+ for (flat) |*c| if (c.* == '\n' or c.* == '\r' or c.* == '\t') {
+ c.* = ' ';
+ };
+ if (head.len == trimmed.len) return flat;
+ return std.fmt.allocPrint(arena, "{s}…", .{flat}) catch flat;
+}
+
/// #5 conditional-phase gate: a phase carrying a non-empty `when` runs only when
/// that substring appears (case-insensitively) in the previous phase's results —
/// e.g. gate a synthesis phase on a findings sentinel so it never runs when the
@@ -155,7 +181,8 @@ pub fn pipelinePrompt(arena: Allocator, raw: []const u8, item: []const u8, prev:
/// runPipeline). Stages run SEQUENTIALLY here via DIRECT runSub calls — never a
/// nested io.async, which on a bounded pool could deadlock; different items run
/// concurrently. A failed stage is retried once (#2); a stage that still fails
-/// ends the chain with a terse marker rather than feeding its error downstream.
+/// ends the chain with a terse marker plus a capped one-line excerpt of its
+/// error (#248), rather than feeding the whole error downstream.
fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) ToolOutput {
const gpa = ctx.gpa;
var arena_state = std.heap.ArenaAllocator.init(gpa);
@@ -175,9 +202,17 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Tool
out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback)) |r| r.output else |e| failure(gpa, e);
}
if (out.is_error) {
+ // #248 — excerpt the stage's own error BEFORE freeing it, so
+ // the item's result says why the chain stopped, not just that
+ // it did.
+ const detail = failExcerpt(arena, out.text);
gpa.free(out.text);
+ const msg = if (detail.len > 0)
+ std.fmt.allocPrint(gpa, "(pipeline stopped at stage {d}/{d} \"{s}\": task failed)\n{s}", .{ stage_no, stages.len, st.label, detail })
+ else
+ std.fmt.allocPrint(gpa, "(pipeline stopped at stage {d}/{d} \"{s}\": task failed)", .{ stage_no, stages.len, st.label });
return .{
- .text = std.fmt.allocPrint(gpa, "(pipeline stopped at stage {d}/{d} \"{s}\": task failed)", .{ stage_no, stages.len, st.label }) catch (gpa.dupe(u8, "(pipeline stage failed)") catch ""),
+ .text = msg catch (gpa.dupe(u8, "(pipeline stage failed)") catch ""),
.is_error = true,
};
}
@@ -310,11 +345,15 @@ pub const PhaseTally = struct {
/// Build the hard-stop text for a phase where every task failed: the
/// assembled per-task failure headers plus a line naming the phase, so the
/// caller (or a human) can see exactly why the run stopped instead of
-/// silently receiving empty "evidence".
-pub fn buildAbortText(arena: Allocator, labels: []const []const u8, phase_no: usize, total_phases: usize, title: []const u8) ![]const u8 {
+/// silently receiving empty "evidence". `details` is parallel to `labels`
+/// (#248): each entry is that task's capped one-line error excerpt, or "" when
+/// the task left nothing to report.
+pub fn buildAbortText(arena: Allocator, labels: []const []const u8, details: []const []const u8, phase_no: usize, total_phases: usize, title: []const u8) ![]const u8 {
var aw: Io.Writer.Allocating = .init(arena);
- for (labels) |label| {
- try aw.writer.print("### {s} (no result — task failed)\n\n", .{label});
+ for (labels, details) |label, detail| {
+ try aw.writer.print("### {s} (no result — task failed)\n", .{label});
+ if (detail.len > 0) try aw.writer.print("{s}\n", .{detail});
+ try aw.writer.writeAll("\n");
}
try aw.writer.print("workflow aborted: every task in phase {d}/{d} ({s}) failed", .{ phase_no, total_phases, title });
return aw.writer.buffered();
@@ -511,7 +550,11 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
// answer from zero evidence. Abort the whole run instead of continuing;
// the per-phase defers above already free `outputs`.
if (phase_failed == tasks.len) {
- const abort_text = try buildAbortText(arena, labels, phase_no, phases.len, title);
+ // #248 — thread each failed task's own error into the abort text,
+ // so the caller reads the API error, not a wall of bare headers.
+ const details = try arena.alloc([]const u8, outputs.len);
+ for (outputs, details) |out, *d| d.* = failExcerpt(arena, out.text);
+ const abort_text = try buildAbortText(arena, labels, details, phase_no, phases.len, title);
return .{ .text = try gpa.dupe(u8, abort_text), .is_error = true };
}
@@ -534,7 +577,12 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
if (out.is_error) {
// Keep the failure visible to the next phase, but never feed its
// raw error text into {{prev}} as if it were a real result (#2).
- try aw.writer.print("### {s} (no result — task failed)\n\n", .{label});
+ // #248 sends a capped one-line excerpt of that error through,
+ // so a synthesis task can adapt to (say) a rate limit.
+ try aw.writer.print("### {s} (no result — task failed)\n", .{label});
+ const detail = failExcerpt(arena, out.text);
+ if (detail.len > 0) try aw.writer.print("{s}\n", .{detail});
+ try aw.writer.writeAll("\n");
} else {
try aw.writer.print("### {s}\n{s}\n\n", .{ label, cappedPrevBody(arena, out.text, per_task_cap) });
}
diff --git a/src/workflow_test.zig b/src/workflow_test.zig
index b5e2d1e0..ced7326e 100644
--- a/src/workflow_test.zig
+++ b/src/workflow_test.zig
@@ -20,6 +20,8 @@ const phaseTaskCap = workflow.phaseTaskCap;
const withContext = workflow.withContext;
const gateAllows = workflow.gateAllows;
const buildAbortText = workflow.buildAbortText;
+const failExcerpt = workflow.failExcerpt;
+const fail_excerpt_cap = workflow.fail_excerpt_cap;
const buildManifest = workflow.buildManifest;
const pipelinePrompt = workflow.pipelinePrompt;
const pipelineIsolationError = workflow.pipelineIsolationError;
@@ -92,22 +94,55 @@ test "gateAllows: empty when always runs, else case-insensitive substring (#5)"
try std.testing.expect(!gateAllows("", "ready")); // empty prev → skip
}
-test "buildAbortText names the phase index and title, and lists every failed task (U2)" {
+test "buildAbortText names the phase index and title, and surfaces each failed task's error (U2/#248)" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
const labels = [_][]const u8{ "scan A", "scan B" };
- const text = try buildAbortText(a, &labels, 2, 3, "Recon");
+ // Parallel per-task excerpts: one real API error, one task that left
+ // nothing to report.
+ const details = [_][]const u8{ "subagent sa-001 failed before producing a report: 429 rate_limit_exceeded [quota failure].", "" };
+ const text = try buildAbortText(a, &labels, &details, 2, 3, "Recon");
// Every failed task's header survives, so a human can see what was tried.
try std.testing.expect(std.mem.indexOf(u8, text, "### scan A (no result — task failed)") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "### scan B (no result — task failed)") != null);
+ // #248 — the underlying API error travels WITH the header instead of being
+ // consumed by the retry gate and dropped. This is the whole ask on the
+ // issue: a caller that only reads "task failed" cannot adapt.
+ try std.testing.expect(std.mem.indexOf(u8, text, "429 rate_limit_exceeded") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "### scan A (no result — task failed)\nsubagent sa-001 failed") != null);
// The abort line names the phase index/total and title — the whole point
// of this text existing instead of a silent empty {{prev}}.
try std.testing.expect(std.mem.indexOf(u8, text, "workflow aborted: every task in phase 2/3 (Recon) failed") != null);
}
+test "failExcerpt keeps the API error on one capped line, and stays empty when there is none (#248)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // A real subagentFailure text: the cause survives, flattened, so it can sit
+ // under a "### label" header without breaking that layout.
+ const raw = "subagent sa-001 failed before producing a report:\n{\"error\":\"rate_limit_exceeded\"}\t[quota failure].";
+ const one = failExcerpt(a, raw);
+ try std.testing.expect(std.mem.indexOf(u8, one, "rate_limit_exceeded") != null);
+ try std.testing.expect(std.mem.indexOfAny(u8, one, "\n\r\t") == null);
+
+ // A huge error body is capped, so one failure can never blow up the next
+ // phase's prompt — the reason the excerpt is bounded at all.
+ const huge = util.repeatBytes("E", 5000);
+ const capped = failExcerpt(a, &huge);
+ try std.testing.expect(capped.len < huge.len);
+ try std.testing.expect(capped.len <= fail_excerpt_cap + 8); // + the "…" marker
+ try std.testing.expect(std.mem.endsWith(u8, capped, "…"));
+
+ // Nothing to report → "" so the render sites keep the bare header rather
+ // than printing an empty detail line.
+ try std.testing.expectEqualStrings("", failExcerpt(a, " \n\t "));
+}
+
test "buildManifest reports ok/retried per phase and SKIPPED for a gated phase (U2)" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();