graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(ci): format and split oversized Zig modules
Rach Pradhanc648c98308f4
diff --git a/src/agent.zig b/src/agent.zigindex 3ede5a5f..154ad00a 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -592,10 +592,7 @@ pub const Agent = struct {pub const isTableSeparator = @import("agent_table.zig").isTableSeparator;};-test "agent prompt helper suite" {+test {_ = @import("agent_prompt.zig");-}--test "lazy root tool catalogs preserve MCP tools across provider formats" {try agent_tests.lazyRootTools(Agent);}diff --git a/src/agent_worktree.zig b/src/agent_worktree.zignew file mode 100644index 00000000..295b8ff4--- /dev/null+++ b/src/agent_worktree.zig@@ -0,0 +1,106 @@+//! Per-agent git-worktree isolation for fanned-out subagents.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const process_runner = @import("process_runner.zig");+const runCapped = process_runner.runCapped;+const ranOk = process_runner.ranOk;++pub const AgentWorktree = struct { path: []const u8, branch: []const u8 };+pub const AgentWorktreeError = error{ NotAGitRepo, CreateFailed };+pub const AgentWorktreeOutcome = struct { kept: bool };++pub fn isolationFailureText(err: anyerror) []const u8 {+ return switch (err) {+ error.NotAGitRepo => "isolation:\"worktree\" requested but this isn't a git repository (or `git` isn't on PATH) — worktrees need a git repo; drop isolation, or set isolation_fallback:true to run in the shared working tree instead",+ error.CreateFailed => "isolation:\"worktree\" requested but `git worktree add` failed (dirty HEAD, a name collision, or a git error) — set isolation_fallback:true to run in the shared working tree instead, or retry",+ else => "isolation:\"worktree\" requested but setup failed — set isolation_fallback:true to run in the shared working tree instead, or retry",+ };+}++pub fn agentWorktreeNames(arena: Allocator, sub_id: []const u8, nonce: []const u8) !AgentWorktree {+ return .{+ .path = try std.fmt.allocPrint(arena, ".graff/worktrees/agent-{s}-{s}", .{ sub_id, nonce }),+ .branch = try std.fmt.allocPrint(arena, "graff/agents/{s}-{s}", .{ sub_id, nonce }),+ };+}++pub fn agentWorktreeCreate(gpa: Allocator, io: Io, arena: Allocator, sub_id: []const u8) (AgentWorktreeError || Allocator.Error)!AgentWorktree {+ const probe = runCapped(gpa, io, &.{ "git", "rev-parse", "--is-inside-work-tree" }, 4096, 4096, 15_000) catch return error.NotAGitRepo;+ defer {+ gpa.free(probe.stdout);+ gpa.free(probe.stderr);+ }+ if (!ranOk(probe)) return error.NotAGitRepo;++ var raw: [4]u8 = undefined;+ io.random(&raw);+ const nonce = std.fmt.bytesToHex(raw, .lower);+ const names = try agentWorktreeNames(arena, sub_id, &nonce);+ const add = runCapped(gpa, io, &.{ "git", "worktree", "add", names.path, "-b", names.branch }, 8192, 8192, 60_000) catch return error.CreateFailed;+ defer {+ gpa.free(add.stdout);+ gpa.free(add.stderr);+ }+ if (!ranOk(add)) return error.CreateFailed;++ var buf: [4096]u8 = undefined;+ const n = Io.Dir.cwd().realPathFile(io, names.path, &buf) catch return .{ .path = names.path, .branch = names.branch };+ return .{ .path = try arena.dupe(u8, buf[0..n]), .branch = names.branch };+}++pub fn isWorktreeStatusDirty(porcelain: []const u8) bool {+ return std.mem.trim(u8, porcelain, " \t\r\n").len > 0;+}++pub fn agentWorktreeFinish(gpa: Allocator, io: Io, wt: AgentWorktree) AgentWorktreeOutcome {+ const st = runCapped(gpa, io, &.{ "git", "-C", wt.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return .{ .kept = true };+ defer {+ gpa.free(st.stdout);+ gpa.free(st.stderr);+ }+ if (!ranOk(st) or isWorktreeStatusDirty(st.stdout)) return .{ .kept = true };++ if (runCapped(gpa, io, &.{ "git", "worktree", "remove", "--force", wt.path }, 8192, 8192, 30_000)) |r| {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ } else |_| {}+ if (runCapped(gpa, io, &.{ "git", "branch", "-D", wt.branch }, 8192, 8192, 30_000)) |r| {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ } else |_| {}+ return .{ .kept = false };+}++test "agentWorktreeNames: unique path/branch per nonce, never collide across repeated spawns (#276)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const first = try agentWorktreeNames(a, "sa-001-dead", "aa11bb22");+ try std.testing.expectEqualStrings(".graff/worktrees/agent-sa-001-dead-aa11bb22", first.path);+ try std.testing.expectEqualStrings("graff/agents/sa-001-dead-aa11bb22", first.branch);++ const second = try agentWorktreeNames(a, "sa-001-dead", "cc33dd44");+ try std.testing.expect(!std.mem.eql(u8, first.path, second.path));+ try std.testing.expect(!std.mem.eql(u8, first.branch, second.branch));+}++test "isWorktreeStatusDirty: clean drives auto-cleanup, tracked or untracked changes drive retention (#276)" {+ try std.testing.expect(!isWorktreeStatusDirty(""));+ try std.testing.expect(!isWorktreeStatusDirty("\n \n"));+ try std.testing.expect(isWorktreeStatusDirty(" M src/foo.zig\n"));+ try std.testing.expect(isWorktreeStatusDirty("?? new_file.zig\n"));+}++test "isolationFailureText: friendly, distinct messages for the non-git and create-failed error paths (#276)" {+ const not_git = isolationFailureText(error.NotAGitRepo);+ try std.testing.expect(std.mem.indexOf(u8, not_git, "isn't a git repository") != null);+ try std.testing.expect(std.mem.indexOf(u8, not_git, "isolation_fallback") != null);++ const create_failed = isolationFailureText(error.CreateFailed);+ try std.testing.expect(std.mem.indexOf(u8, create_failed, "git worktree add") != null);+ try std.testing.expect(std.mem.indexOf(u8, create_failed, "isolation_fallback") != null);+ try std.testing.expect(!std.mem.eql(u8, not_git, create_failed));+}diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex ba177300..ff9078f0 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -179,9 +179,9 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,else"done";try out.print(" {s}{d:>3}{s} {s}{s:<8}{s} {d:>7}ms {s}\n", .{- style.accent, job.id, style.reset,- if (job.done) style.dim else style.green, status, style.reset,- job.usage.duration_ms, utf8Prefix(job.label, 60),+ style.accent, job.id, style.reset,+ if (job.done) style.dim else style.green, status, style.reset,+ job.usage.duration_ms, utf8Prefix(job.label, 60),});}}diff --git a/src/http_warm.zig b/src/http_warm.zignew file mode 100644index 00000000..ff5c88cf--- /dev/null+++ b/src/http_warm.zig@@ -0,0 +1,19 @@+//! Shared HTTP client CA-bundle warming.++const std = @import("std");+const Io = std.Io;++/// Pre-load the shared HTTP client's CA bundle single-threaded so concurrent+/// agents never race Zig's lazy first-connect rescan.+pub fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) void {+ const now = Io.Clock.real.now(io);+ client.ca_bundle.rescan(gpa, io, now) catch return;+ client.now = now;+}++/// Warm off the launch critical path. Outbound users wait on+/// `http.g_client_ready`, so prompt painting can overlap the scan safely.+pub fn prewarmCaBundleTask(client: *std.http.Client, gpa: std.mem.Allocator, io: Io, ready: *Io.Event) void {+ defer ready.set(io);+ prewarmCaBundle(client, gpa, io);+}diff --git a/src/jobs.zig b/src/jobs.zigindex c6b6ee0f..4cfa327d 100644--- a/src/jobs.zig+++ b/src/jobs.zig@@ -36,6 +36,17 @@ const Agent = agent_mod.Agent;pub fn runCappedCwd(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64, cwd: std.process.Child.Cwd) !CappedRun {return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{ .cwd = cwd });}++const agent_worktree = @import("agent_worktree.zig");+pub const AgentWorktree = agent_worktree.AgentWorktree;+pub const AgentWorktreeError = agent_worktree.AgentWorktreeError;+pub const AgentWorktreeOutcome = agent_worktree.AgentWorktreeOutcome;+pub const isolationFailureText = agent_worktree.isolationFailureText;+pub const agentWorktreeNames = agent_worktree.agentWorktreeNames;+pub const agentWorktreeCreate = agent_worktree.agentWorktreeCreate;+pub const isWorktreeStatusDirty = agent_worktree.isWorktreeStatusDirty;+pub const agentWorktreeFinish = agent_worktree.agentWorktreeFinish;+/// True if the current git working tree has uncommitted *tracked* changes/// (staged or unstaged). Untracked files (`?? …`) don't count — `git reset/// --hard` leaves them alone, so they're safe around a worktree land.@@ -53,151 +64,6 @@ fn gitTreeDirty(gpa: Allocator, io: Io) bool {return false;}-// ── Per-agent worktree isolation (#276 P0-1) ────────────────────────────────-// Extends the session-level `-w`/`graff worktree` mechanism (above) down to-// one worktree per fanned-out subagent, opt-in via `isolation:"worktree"` on-// a subagent/workflow-task spawn (see subagent.zig's `runSub`, fleet.zig's-// `resolveIsolation`). The critical difference from `-w`: nothing here ever-// chdirs the process. `agentWorktreeCreate` returns an absolute path that the-// caller threads through as the child `Agent`'s `agent_cwd` → `ToolCtx.agent_cwd`-// → per-tool-call `bash` cwd / file-op path prefix, so parallel siblings on the-// same pool each keep their own working tree with no shared-state race.--/// One agent's scratch worktree: an absolute path (resolved once at creation,-/// since every later use — bash cwd, file-op path join, `git -C` for status/-/// removal — runs from a pool thread that never chdirs) and its branch name.-pub const AgentWorktree = struct { path: []const u8, branch: []const u8 };--pub const AgentWorktreeError = error{ NotAGitRepo, CreateFailed };--/// User-facing explanation for a failed `isolation:"worktree"` request (#276-/// design point 5: "non-git repo → explicit, friendly error"). Takes `anyerror`-/// (not `AgentWorktreeError`) so the caller — catching the wider error set-/// `agentWorktreeCreate` actually returns (it's `Allocator.Error`-fallible too)-/// — never has to narrow the value first; unrecognized errors still get a-/// sensible fallback message instead of failing to compile/format.-pub fn isolationFailureText(err: anyerror) []const u8 {- return switch (err) {- error.NotAGitRepo => "isolation:\"worktree\" requested but this isn't a git repository (or `git` isn't on PATH) — worktrees need a git repo; drop isolation, or set isolation_fallback:true to run in the shared working tree instead",- error.CreateFailed => "isolation:\"worktree\" requested but `git worktree add` failed (dirty HEAD, a name collision, or a git error) — set isolation_fallback:true to run in the shared working tree instead, or retry",- else => "isolation:\"worktree\" requested but setup failed — set isolation_fallback:true to run in the shared working tree instead, or retry",- };-}--/// Deterministic name generator, kept separate from the git calls below so-/// it's unit-testable without a real `Io`: `.graff/worktrees/agent-<id>` on-/// branch `graff/agents/<id>`, `id = "<sub_id>-<nonce>"`. `sub_id` is already-/// unique within one `graff` process (subagentId's monotonic ordinal); the-/// caller-supplied `nonce` (fresh randomness from `io.random`, hex-encoded)-/// covers the cross-process case too — two concurrent `graff` invocations in-/// the same repo whose own per-process counters happen to line up still never-/// collide on a path or branch name.-pub fn agentWorktreeNames(arena: Allocator, sub_id: []const u8, nonce: []const u8) !AgentWorktree {- return .{- .path = try std.fmt.allocPrint(arena, ".graff/worktrees/agent-{s}-{s}", .{ sub_id, nonce }),- .branch = try std.fmt.allocPrint(arena, "graff/agents/{s}-{s}", .{ sub_id, nonce }),- };-}--/// Create a scratch git worktree, branched from HEAD, for one fanned-out-/// subagent. `error.NotAGitRepo` when the target isn't a git repository at-/// all (or `git` isn't on PATH); `error.CreateFailed` for anything else-/// `git worktree add` rejects.-pub fn agentWorktreeCreate(gpa: Allocator, io: Io, arena: Allocator, sub_id: []const u8) (AgentWorktreeError || Allocator.Error)!AgentWorktree {- const probe = runCapped(gpa, io, &.{ "git", "rev-parse", "--is-inside-work-tree" }, 4096, 4096, 15_000) catch return error.NotAGitRepo;- defer {- gpa.free(probe.stdout);- gpa.free(probe.stderr);- }- if (!ranOk(probe)) return error.NotAGitRepo;-- var raw: [4]u8 = undefined;- io.random(&raw);- const nonce = std.fmt.bytesToHex(raw, .lower);- const names = try agentWorktreeNames(arena, sub_id, &nonce);- const add = runCapped(gpa, io, &.{ "git", "worktree", "add", names.path, "-b", names.branch }, 8192, 8192, 60_000) catch return error.CreateFailed;- defer {- gpa.free(add.stdout);- gpa.free(add.stderr);- }- if (!ranOk(add)) return error.CreateFailed;-- var buf: [4096]u8 = undefined;- const n = Io.Dir.cwd().realPathFile(io, names.path, &buf) catch return .{ .path = names.path, .branch = names.branch };- return .{ .path = try arena.dupe(u8, buf[0..n]), .branch = names.branch };-}--/// Pure decision extracted from `agentWorktreeFinish`: any `git status-/// --porcelain` output (tracked OR untracked — unlike the session-level-/// `gitTreeDirty` above, a subagent's brand-new untracked file is real work-/// worth keeping, not noise to auto-discard) means the worktree is dirty.-pub fn isWorktreeStatusDirty(porcelain: []const u8) bool {- return std.mem.trim(u8, porcelain, " \t\r\n").len > 0;-}--pub const AgentWorktreeOutcome = struct { kept: bool };--/// Called when a worktree-isolated subagent finishes normally (#276 design-/// point 3): an unchanged worktree is removed with its branch — no trace left-/// in `git worktree list` — a changed one is kept for the orchestrator to-/// inspect/land. Never called on a crash (see subagent.zig's runSub): a-/// worktree this function didn't get to run against is left in place,-/// unconditionally, so a crash never silently discards changes. If the status-/// check itself fails to run, this also keeps the worktree rather than guess.-pub fn agentWorktreeFinish(gpa: Allocator, io: Io, wt: AgentWorktree) AgentWorktreeOutcome {- const st = runCapped(gpa, io, &.{ "git", "-C", wt.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return .{ .kept = true };- defer {- gpa.free(st.stdout);- gpa.free(st.stderr);- }- if (!ranOk(st) or isWorktreeStatusDirty(st.stdout)) return .{ .kept = true };-- if (runCapped(gpa, io, &.{ "git", "worktree", "remove", "--force", wt.path }, 8192, 8192, 30_000)) |r| {- gpa.free(r.stdout);- gpa.free(r.stderr);- } else |_| {}- if (runCapped(gpa, io, &.{ "git", "branch", "-D", wt.branch }, 8192, 8192, 30_000)) |r| {- gpa.free(r.stdout);- gpa.free(r.stderr);- } else |_| {}- return .{ .kept = false };-}--test "agentWorktreeNames: unique path/branch per nonce, never collide across repeated spawns (#276)" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();-- const first = try agentWorktreeNames(a, "sa-001-dead", "aa11bb22");- try std.testing.expectEqualStrings(".graff/worktrees/agent-sa-001-dead-aa11bb22", first.path);- try std.testing.expectEqualStrings("graff/agents/sa-001-dead-aa11bb22", first.branch);-- // Same sub_id (e.g. two processes whose own counters line up) but a- // different nonce — the collision case the nonce exists to prevent —- // still produces distinct names.- const second = try agentWorktreeNames(a, "sa-001-dead", "cc33dd44");- try std.testing.expect(!std.mem.eql(u8, first.path, second.path));- try std.testing.expect(!std.mem.eql(u8, first.branch, second.branch));-}--test "isWorktreeStatusDirty: clean drives auto-cleanup, tracked or untracked changes drive retention (#276)" {- try std.testing.expect(!isWorktreeStatusDirty("")); // clean → agentWorktreeFinish removes it- try std.testing.expect(!isWorktreeStatusDirty("\n \n")); // whitespace-only porcelain output is still clean- try std.testing.expect(isWorktreeStatusDirty(" M src/foo.zig\n")); // tracked edit → kept- try std.testing.expect(isWorktreeStatusDirty("?? new_file.zig\n")); // untracked-only still counts as changes → kept-}--test "isolationFailureText: friendly, distinct messages for the non-git and create-failed error paths (#276)" {- const not_git = isolationFailureText(error.NotAGitRepo);- try std.testing.expect(std.mem.indexOf(u8, not_git, "isn't a git repository") != null);- try std.testing.expect(std.mem.indexOf(u8, not_git, "isolation_fallback") != null);-- const create_failed = isolationFailureText(error.CreateFailed);- try std.testing.expect(std.mem.indexOf(u8, create_failed, "git worktree add") != null);- try std.testing.expect(std.mem.indexOf(u8, create_failed, "isolation_fallback") != null);- try std.testing.expect(!std.mem.eql(u8, not_git, create_failed));-}-/// Per-turn checkpoint commit for `-w` sessions. The worktree branch is a/// throwaway scratch branch, so committing every turn is free and gives durable/// rewind points across restarts; `graff worktree merge` later --squashes thediff --git a/src/main.zig b/src/main.zigindex 790c438a..46c2987c 100644--- a/src/main.zig+++ b/src/main.zig@@ -4,27 +4,9 @@//! run-exclusive JSONL tracing under `.graff/traces`.const std = @import("std");const Io = std.Io;--/// #131: pre-load the shared HTTP client's CA bundle single-threaded, so the-/// parallel subagents that share this client (on pool threads) never race the-/// lazy CA-bundle rescan on their first concurrent HTTPS connect. Zig std flags-/// that race itself ("TODO data race here on ca_bundle"): when two threads both-/// rescan+swap+deinit the bundle, a handshake reading it mid-swap fails instantly-/// with error.TlsInitializationFailed (ms=0, resp_bytes=0 — see #131). Warming it-/// here sets client.now, so every later connect skips the rescan entirely.-pub fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) void {- const now = Io.Clock.real.now(io);- client.ca_bundle.rescan(gpa, io, now) catch return;- client.now = now;-}--/// Warm the shared client's CA bundle off the launch critical path. Outbound-/// users wait on `http.g_client_ready`, so the prompt can paint during this-/// scan without reintroducing the concurrent first-connect race above.-fn prewarmCaBundleTask(client: *std.http.Client, gpa: std.mem.Allocator, io: Io, ready: *Io.Event) void {- defer ready.set(io);- prewarmCaBundle(client, gpa, io);-}+const http_warm = @import("http_warm.zig");+pub const prewarmCaBundle = http_warm.prewarmCaBundle;+const prewarmCaBundleTask = http_warm.prewarmCaBundleTask;const Value = std.json.Value;const Allocator = std.mem.Allocator;const mcp = @import("mcp.zig");diff --git a/src/schema.zig b/src/schema.zigindex fd225fa2..9a0f39be 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -22,38 +22,7 @@ const provider_specs = provider_mod.provider_specs;/// Documentation of the `--json` stdio protocol, embedded verbatim in/// `--schema` output so SDK generators/users know the request/event contract.-const schema_protocol_json =- \\{- \\ "transport": "newline-delimited JSON over stdin/stdout (--json)",- \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",- \\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to this run's file under .graff/trajectories (the aggregate append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",- \\ "events": [- \\ {"type": "text", "text": "assistant text delta"},- \\ {"type": "reasoning", "text": "reasoning/thinking delta (GUI shows a collapsible Thinking block)"},- \\ {"type": "started", "provider": "provider", "model": "model"},- \\ {"type": "model_call_started", "provider": "provider", "model": "model"},- \\ {"type": "model_call_finished", "provider": "provider", "model": "model", "ok": true, "ms": 0},- \\ {"type": "tool_call", "name": "tool", "input": {}},- \\ {"type": "tool_call_started", "name": "tool", "input": {}},- \\ {"type": "tool_rejected", "name": "tool", "reason": "budget|duplicate", "input": {}, "message": "..."},- \\ {"type": "ask_user", "call_id": "...", "question": "...", "input": {"question": "...", "options": ["..."]}},- \\ {"type": "tool_result", "name": "tool", "is_error": false, "text": "..."},- \\ {"type": "tool_call_finished", "name": "tool", "is_error": false, "ms": 0},- \\ {"type": "agent_usage", "id": "sa-...", "ok": true, "duration_ms": 0, "tool_calls": 0, "context_tokens": 0, "cache_read_tokens": 0},- \\ {"type": "finalizing"},- \\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0, "complete": true, "metadata_complete": true},- \\ {"type": "system_prompt", "ok": true, "append": false, "chars": 0},- \\ {"type": "model", "ok": true, "provider": "provider", "model": "model", "context": 0, "note": "context kept"},- \\ {"type": "compact", "ok": true, "chars": 0},- \\ {"type": "mode", "ok": true, "mode": "plan"},- \\ {"type": "agent", "ok": true, "id": "reviewer", "chars": 0},- \\ {"type": "effort", "ok": true, "level": "medium", "applies": true},- \\ {"type": "fast", "ok": true, "on": true, "applies": true},- \\ {"type": "score", "ok": true, "prompt_sha": "..."},- \\ {"type": "error", "message": "..."}- \\ ]- \\}-;+const schema_protocol_json = @import("schema_protocol.zig").json;/// Documentation of the `harness serve` HTTP bridge, embedded verbatim in/// `--schema` output. Same request/event contract as the stdio protocol —/// one POST = one protocol request, streamed back as NDJSON until that@@ -629,4 +598,3 @@ test "subagent_spec: run_in_background is a boolean, optional (not in required),const required = parsed.value.object.get("required").?.array.items;for (required) |r| try std.testing.expect(!std.mem.eql(u8, r.string, "run_in_background"));}-diff --git a/src/schema_protocol.zig b/src/schema_protocol.zignew file mode 100644index 00000000..395da7a6--- /dev/null+++ b/src/schema_protocol.zig@@ -0,0 +1,34 @@+//! Embedded documentation for Graff's newline-delimited JSON protocol.++pub const json =+ \\{+ \\ "transport": "newline-delimited JSON over stdin/stdout (--json)",+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",+ \\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to this run's file under .graff/trajectories (the aggregate append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",+ \\ "events": [+ \\ {"type": "text", "text": "assistant text delta"},+ \\ {"type": "reasoning", "text": "reasoning/thinking delta (GUI shows a collapsible Thinking block)"},+ \\ {"type": "started", "provider": "provider", "model": "model"},+ \\ {"type": "model_call_started", "provider": "provider", "model": "model"},+ \\ {"type": "model_call_finished", "provider": "provider", "model": "model", "ok": true, "ms": 0},+ \\ {"type": "tool_call", "name": "tool", "input": {}},+ \\ {"type": "tool_call_started", "name": "tool", "input": {}},+ \\ {"type": "tool_rejected", "name": "tool", "reason": "budget|duplicate", "input": {}, "message": "..."},+ \\ {"type": "ask_user", "call_id": "...", "question": "...", "input": {"question": "...", "options": ["..."]}},+ \\ {"type": "tool_result", "name": "tool", "is_error": false, "text": "..."},+ \\ {"type": "tool_call_finished", "name": "tool", "is_error": false, "ms": 0},+ \\ {"type": "agent_usage", "id": "sa-...", "ok": true, "duration_ms": 0, "tool_calls": 0, "context_tokens": 0, "cache_read_tokens": 0},+ \\ {"type": "finalizing"},+ \\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0, "complete": true, "metadata_complete": true},+ \\ {"type": "system_prompt", "ok": true, "append": false, "chars": 0},+ \\ {"type": "model", "ok": true, "provider": "provider", "model": "model", "context": 0, "note": "context kept"},+ \\ {"type": "compact", "ok": true, "chars": 0},+ \\ {"type": "mode", "ok": true, "mode": "plan"},+ \\ {"type": "agent", "ok": true, "id": "reviewer", "chars": 0},+ \\ {"type": "effort", "ok": true, "level": "medium", "applies": true},+ \\ {"type": "fast", "ok": true, "on": true, "applies": true},+ \\ {"type": "score", "ok": true, "prompt_sha": "..."},+ \\ {"type": "error", "message": "..."}+ \\ ]+ \\}+;diff --git a/src/subagent.zig b/src/subagent.zigindex 3ac86078..4dcc21ef 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -65,370 +65,13 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {return run.output;}--/// Surface a workflow subagent as a synthetic `tool_call` / `tool_result` on the-/// --json GUI stream so each parallel worker shows as its own live row — the-/// orchestrator's children otherwise run detached (out=null), so the GUI only-/// ever saw the single `workflow` op. Pool-thread safe: serializes on g_gui_mu-/// with Agent.emit (same json stdout writer, g_out). No-op outside --json mode.-fn guiEmit(io: Io, ev: anytype) void {- if (!main_mod.json_mode) return;- const w = main_mod.g_out orelse return;- main_mod.g_gui_mu.lockUncancelable(io);- defer main_mod.g_gui_mu.unlock(io);- var s: std.json.Stringify = .{ .writer = w };- s.write(ev) catch return;- w.writeByte('\n') catch return;- w.flush() catch return;-}--/// Coarse classification of a subagent's underlying API/transport failure, so-/// the tool result can tell the orchestrator what actually broke and whether a-/// retry is worth it — the bare `error.ApiError` propagation carried none of it.-const FailKind = enum {- quota, // rate limit / out of credits / overloaded- transport, // network drop / stream stall — usually transient- model, // model missing / decommissioned / unavailable- invalid, // bad arguments / unsupported param / context too long- auth, // key invalid / expired / unauthorized- unknown, // no detail to classify against-- fn label(self: FailKind) []const u8 {- return switch (self) {- .quota => "quota/rate-limit",- .transport => "transport",- .model => "model-availability",- .invalid => "invalid-arguments",- .auth => "auth",- .unknown => "unknown",- };- }-- /// Is re-running the identical task likely to succeed? Transient failures- /// (quota backoff, transport flake) yes; a bad model / argument / credential- /// just fails again until the cause is fixed.- fn retrySafe(self: FailKind) bool {- return switch (self) {- .quota, .transport, .unknown => true,- .model, .invalid, .auth => false,- };- }-};--fn containsAnyCI(hay: []const u8, needles: []const []const u8) bool {- for (needles) |n| if (util.indexOfIgnoreCase(hay, n) != null) return true;- return false;-}--/// Classify a child turn's failure from its error kind and the child agent's-/// captured `last_api_error` detail (the provider's error type + message, or a-/// transport reason). The detail is the authoritative signal; the error kind-/// only distinguishes a stream stall/drop, whose stale envelope would mislead.-/// Order matters: quota/auth/model phrases are checked before the broad-/// `invalid_request_error` type so a rate-limit or missing-model envelope isn't-/// swallowed as a generic "invalid" just because that type string contains it.-fn classifyFailure(err: anyerror, detail: ?[]const u8) FailKind {- switch (err) {- error.StreamStalled, error.StreamDropped => return .transport,- else => {},- }- const msg = detail orelse return .unknown;- if (containsAnyCI(msg, &.{ "network error", "stream stalled", "stream dropped", "timed out", "connection reset", "connection closed" })) return .transport;- if (containsAnyCI(msg, &.{ "rate limit", "rate_limit", "quota", "429", "overloaded", "out of credits", "credits", "billing", "too many requests" })) return .quota;- if (containsAnyCI(msg, &.{ "api key", "unauthorized", "expired", "authentication", "invalid_api_key", "401" })) return .auth;- if (containsAnyCI(msg, &.{ "does not exist", "not found", "no such model", "decommission", "no longer", "model_not_found", "unavailable", "404" })) return .model;- if (containsAnyCI(msg, &.{ "context length", "context window", "invalid", "unsupported", "not supported", "must be", "too long", "400", "parameter", "max_tokens", "bad request" })) return .invalid;- return .unknown;-}--/// Build the is_error tool result for a subagent whose child turn failed at the-/// API/transport layer. Threads the child's own diagnostic — provider status /-/// message, a coarse category, and whether a retry is worth it — up to the-/// orchestrator instead of collapsing to an opaque bare `error: ApiError`.-/// `detail` is the child agent's `last_api_error`; formatted into `gpa` before-/// the child arena that owns it is freed on return.-fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[]const u8) ToolOutput {- const kind = classifyFailure(err, detail);- const cause = detail orelse @errorName(err);- const retry = if (kind.retrySafe())- "retry is likely safe — re-run the same task (after a short backoff for quota/transport)"- else- "retry is NOT safe as-is — fix the cause first (switch model, correct arguments, or re-auth)";- const text = std.fmt.allocPrint(- gpa,- "subagent {s} failed before producing a report: {s} [{s} failure]. {s}",- .{ sub_id, cause, kind.label(), retry },- ) catch return .{ .is_error = true };- return .{ .text = text, .is_error = true };-}--fn childProvider(root: Provider, pinned: ?Provider, allow_cross_provider: bool) Provider {- const child = pinned orelse return root;- return if (std.mem.eql(u8, child.id, root.id) or allow_cross_provider) child else root;-}--test "child model pin crosses the current root provider only with consent" {- const codex_root: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5.6-sol", .context = 272_000 };- const terra: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5.6-terra", .context = 272_000 };- const anthropic_root: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "", .model = "claude", .context = 200_000 };- try std.testing.expectEqualStrings("gpt-5.6-terra", childProvider(codex_root, terra, false).model);- try std.testing.expectEqualStrings("claude", childProvider(anthropic_root, terra, false).model);- try std.testing.expectEqualStrings("gpt-5.6-terra", childProvider(anthropic_root, terra, true).model);-}--/// Duration/tool-call/context usage for one subagent run — the numbers-/// runSub already computes for the trajectory node, now also handed back to-/// the caller so a background completion event (#276 P0-3) can carry them.-/// Zero-valued when the child never ran at all (an early rejection before-/// `agent.runTurn()`, e.g. depth limit or isolation setup failure).-pub const AgentUsage = struct {- duration_ms: u64 = 0,- tool_calls: u32 = 0,- context_tokens: u64 = 0,- cache_read_tokens: u64 = 0,-};--/// #276 P0-2: the wire shape of a subagent completion's usage event, emitted-/// on every runSub return (see the guiEmit call site below). A named struct-/// + pure constructor — not an inline anonymous literal — so the-/// id/ok/AgentUsage → wire-field mapping is unit-testable without needing-/// json_mode/g_out plumbing (same rationale as agentStatusText below).-const AgentUsageEvent = struct {- type: []const u8 = "agent_usage",- id: []const u8,- ok: bool,- duration_ms: u64,- tool_calls: u32,- context_tokens: u64,- cache_read_tokens: u64,-};--fn agentUsageEvent(sub_id: []const u8, ok: bool, usage: AgentUsage) AgentUsageEvent {- return .{- .id = sub_id,- .ok = ok,- .duration_ms = usage.duration_ms,- .tool_calls = usage.tool_calls,- .context_tokens = usage.context_tokens,- .cache_read_tokens = usage.cache_read_tokens,- };-}--test "agentUsageEvent: maps AgentUsage fields onto the wire event without transposition (#276 P0-2)" {- const ev = agentUsageEvent("sa-007-abcd", true, .{ .duration_ms = 4110, .tool_calls = 6, .context_tokens = 1820, .cache_read_tokens = 340 });- try std.testing.expectEqualStrings("agent_usage", ev.type);- try std.testing.expectEqualStrings("sa-007-abcd", ev.id);- try std.testing.expect(ev.ok);- try std.testing.expectEqual(@as(u64, 4110), ev.duration_ms);- try std.testing.expectEqual(@as(u32, 6), ev.tool_calls);- try std.testing.expectEqual(@as(u64, 1820), ev.context_tokens);- try std.testing.expectEqual(@as(u64, 340), ev.cache_read_tokens);-- const failed = agentUsageEvent("sa-008-efgh", false, .{});- try std.testing.expect(!failed.ok);- try std.testing.expectEqual(@as(u64, 0), failed.duration_ms);-}--/// runSub's result: the tool-facing output plus the usage summary above.-/// Every direct caller (execSubagent, workflowTask, workflowRetryTask,-/// judgeTask, workflow.zig's pipelineChain) only ever wanted `.output`-/// before #276 P0-3; `spawnSubBackground`'s pump is the one caller that-/// also reads `.usage`.-pub const SubRun = struct { output: ToolOutput, usage: AgentUsage };--/// Run one isolated subagent to completion: fresh arena, fresh history,-/// same shared http client and the configured child provider (or the root-/// provider when no child model is pinned). `sys_override` swaps the-/// lean default system prompt for a per-child variant (swarm prompt-/// evolution); either way the run is recorded as a trajectory node under-/// the turn that spawned it, with the prompt's fingerprint.-pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) !SubRun {- const gpa = ctx.gpa;- if (ctx.run_budget) |budget| if (ctx.depth >= budget.max_depth) return .{- .output = .{- .text = try gpa.dupe(u8, "agent depth limit reached (max depth 1) — do this work in the current agent"),- .is_error = true,- },- .usage = .{},- };- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const arena = arena_state.allocator();- const child_provider = childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);-- var agent: Agent = .{- .gpa = gpa,- .arena = arena,- .io = ctx.io,- .client = ctx.client,- .provider = child_provider,- .messages = std.json.Array.init(arena),- .sub = true,- .label = label,- .out = null,- .approvals = ctx.approvals,- .tracer = ctx.tracer,- .run_budget = ctx.run_budget,- .depth = ctx.depth + 1,- .call_kind = if (std.mem.eql(u8, kind, "judge_task"))- .judge- else if (std.mem.eql(u8, kind, "workflow_retry"))- .workflow_retry- else- .child,- .sys_override = sys_override,- };- const sub_start = Io.Timestamp.now(ctx.io, .awake);- if (sys_override) |so| if (telemetry.g_telem) |t| {- if (fleet.promptIsPublic(so)) _ = learning_privacy.approveTemplate(ctx.io, so);- t.countVariant();- // fleet:propose (docs §9.B) — a niche's elite was mutated into a variant.- const child_fp = promptFingerprint(so);- var parent_buf: [16]u8 = undefined;- var parent_sha: []const u8 = "";- if (niche.len > 0) if (agentTypePrompt(niche)) |ep| {- parent_buf = promptFingerprint(ep);- parent_sha = &parent_buf;- };- // Oversized genomes skip the propose (review F6): the server verifies- // the fingerprint over the carried text, so a truncated genome would- // be dropped there anyway — and the fingerprint the scores reference- // stays computed over the full text.- if (so.len <= telemetry.Telemetry.max_propose_text)- t.fleetEvent("propose", niche, &child_fp, parent_sha, providerClass(agent.provider.model), "", 0, so)- else if (ctx.tracer) |tr| tr.note("fleet", "propose skipped: genome > 64KB");- };- // Stable id + sprite for this child's card and its inspectable detail file.- const ordinal = cards.g_subagent_seq.fetchAdd(1, .monotonic);- var id_buf: [40]u8 = undefined;- const sub_id = cards.subagentId(&id_buf, ordinal, label, prompt);- const sprite = cards.subagentSprite(ordinal);- cards.subagentLaunchCard(arena, sub_id, sprite, label, kind, prompt);-- // #276 P0-1: opt-in per-agent git-worktree isolation, threaded through as- // this child's own `agent.agent_cwd` (never a process-wide chdir), so- // parallel siblings fanned out from the same turn each keep their own- // working tree — see jobs.zig's "Per-agent worktree isolation" section.- // Creation failure fails the spawn outright unless the caller explicitly- // allowed falling back to the shared cwd (design point 4 — a silent- // fallback would reintroduce the very race isolation exists to prevent).- var wt: ?jobs.AgentWorktree = null;- var isolation_note: []const u8 = "";- if (isolation == .worktree) {- if (jobs.agentWorktreeCreate(gpa, ctx.io, arena, sub_id)) |created| {- wt = created;- } else |err| {- if (!isolation_fallback) return .{- .output = .{ .text = try gpa.dupe(u8, jobs.isolationFailureText(err)), .is_error = true },- .usage = .{},- };- isolation_note = "\n\n[note: isolation:\"worktree\" failed and fell back to the shared working tree — isolation_fallback:true allowed it]";- }- }- agent.agent_cwd = if (wt) |w| w.path else null;-- // Live agent tree: surface workflow_task children as their own GUI rows.- const wf_task = std.mem.eql(u8, kind, "workflow_task");- if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label } });- try agent.messages.append(try textMessage(arena, "user", prompt));- defer agent.tools_used.deinit(gpa);- const report = agent.runTurn();- const run_ms: i64 = @intCast(@max(0, sub_start.untilNow(ctx.io, .awake).toMilliseconds()));- const run_ok = if (report) |r| r.len > 0 else |_| false;- if (wf_task) guiEmit(ctx.io, .{ .type = "tool_result", .name = "subagent", .is_error = !run_ok });- const used_tools = agent.tools_used.render(arena);- // #276 P0-3: usage summary for a background completion event, captured- // once here (right after the child's turn tree is fully joined) and- // threaded through every remaining return point below, success or- // failure alike — the two early returns above happen before the child- // ever runs, so they carry the zero value instead.- const usage: AgentUsage = .{- .duration_ms = @intCast(run_ms),- .tool_calls = @intCast(agent.tools_used.count()),- .context_tokens = agent.effectiveContextTokens(),- .cache_read_tokens = agent.last_cache_read,- };- // #276 P0-2: every runSub completion — the synchronous execSubagent path- // included, which historically discarded `usage` entirely (only a- // background job's polled agent_output ever saw it) — now also emits a- // structured completion event over the --json stream, so an SDK driving- // the protocol programmatically can see real per-call token/duration- // usage without needing run_in_background+agent_output for the common- // synchronous case. No-ops outside --json mode (guiEmit).- guiEmit(ctx.io, agentUsageEvent(sub_id, run_ok, usage));- const fp = promptFingerprint(agent.systemPrompt());- if (trace.g_traj) |tj| {- tj.capturePrompt(fp, agent.systemPrompt());- tj.node(.{- .id = tj.nextId(),- .parent = tj.currentTurn(),- .kind = kind,- .label = label,- .provider = agent.provider.id,- .model = agent.provider.model,- .t = tj.elapsedMs(),- .ms = run_ms,- .prompt_sha = &fp,- .prompt_mutated = sys_override != null,- .niche = niche, // MAP-Elites niche, so a local /agents promote can group scores by it- .task = util.utf8Prefix(prompt, 160),- .tools = used_tools,- .ok = run_ok,- .context_tokens = agent.effectiveContextTokens(),- });- }- if (telemetry.g_telem) |t| t.runEvent(&fp, sys_override != null, run_ok, run_ms, used_tools);- // A child API/transport failure used to collapse to a bare "error: ApiError"- // once execTool's catch ran failure() on the propagated error. Instead- // surface the child's own diagnostic (provider status/message + a coarse- // category + retry guidance) as an is_error result, duped into gpa before- // the child arena that owns last_api_error is freed on return.- const text = report catch |err| {- // #276 P0-1: a crashed child leaves its worktree exactly as-is — never- // silently cleaned up, since we can't safely tell "no changes yet"- // from "changes we're about to lose" once the run failed abnormally.- var out = subagentFailure(gpa, sub_id, err, agent.last_api_error);- if (wt) |w| {- const combined = std.fmt.allocPrint(gpa, "{s}\n\n[worktree left in place after failure — path: {s}, branch: {s}]", .{ out.text, w.path, w.branch }) catch return .{ .output = out, .usage = usage };- gpa.free(out.text);- out.text = combined;- }- return .{ .output = out, .usage = usage };- };- const empty = text.len == 0;- const report_body = if (empty) "subagent finished without a report" else text;- // Persist the full report + metadata so it can be inspected from the- // terminal, then render the completion card with the inspect: path.- const detail = cards.writeSubagentDetail(ctx.io, arena, sub_id, label, kind, prompt, report_body, !empty, run_ms, used_tools);- cards.subagentDoneCard(arena, sub_id, sprite, label, !empty, run_ms, used_tools, detail);-- // #276 P0-1: the child completed normally — finish an isolated worktree- // now (an unchanged one is removed with its branch, silently; a changed- // one is kept and its path/branch ride along in the result so the- // orchestrator can inspect/land it), or carry the isolation_fallback note.- var extra: []const u8 = isolation_note;- var extra_owned = false;- if (wt) |w| {- const outcome = jobs.agentWorktreeFinish(gpa, ctx.io, w);- if (outcome.kept) {- extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept (has changes) — path: {s}, branch: {s}]", .{ w.path, w.branch }) catch "";- extra_owned = extra.len > 0;- }- }- defer if (extra_owned) gpa.free(extra);-- if (empty) return .{- .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}", .{ report_body, extra }), .is_error = true },- .usage = usage,- };- // Append the inspect: path so the orchestrator can cite the detail file.- if (detail) |p|- return .{- .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}\n\n[subagent {s} · inspect: {s}]{s}", .{ text, sub_id, p, extra }) },- .usage = usage,- };- return .{ .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}", .{ text, extra }) }, .usage = usage };-}+const subagent_run = @import("subagent_run.zig");+pub const AgentUsage = subagent_run.AgentUsage;+pub const SubRun = subagent_run.SubRun;+pub const runSub = subagent_run.runSub;+const childProvider = subagent_run.childProvider;+const FailKind = subagent_run.FailKind;+const classifyFailure = subagent_run.classifyFailure;// ── Async, fire-and-forget background subagents (#276 P0-3) ────────────────// Extends jobs.zig's background-bash-job pattern (Job/g_jobs/spawnJob/@@ -749,7 +392,6 @@ test "agentStatusText: composes with isolation:\"worktree\" — a kept-worktreetry std.testing.expect(std.mem.indexOf(u8, out, "branch: graff/agents/sa-001-aa11") != null);}-/// One task inside a workflow phase; never throws, suitable for io.async./// `niche` is the task's MAP-Elites cell, threaded through so runSub's/// fleet:propose — and scoreVariants' submit — tag the variant's genome.@@ -775,7 +417,6 @@ pub fn judgeTask(ctx: ToolCtx, prompt: []const u8) ToolOutput {return run.output;}-/// Build the judge prompt that scores one workflow variant's output against its/// task on a 0-100 scale (see scoreVariants). Bounded: the task spec and output/// tail are truncated so a fat phase can't blow up the judge's context.diff --git a/src/subagent_run.zig b/src/subagent_run.zignew file mode 100644index 00000000..2c7197c7--- /dev/null+++ b/src/subagent_run.zig@@ -0,0 +1,302 @@+//! One isolated subagent run: provider selection, failure classification,+//! worktree lifecycle, usage emission, and trajectory recording.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const main_mod = @import("main.zig");+const Agent = @import("agent.zig").Agent;+const Provider = @import("provider.zig").Provider;+const util = @import("util.zig");+const tools = @import("tools.zig");+const ToolCtx = tools.ToolCtx;+const ToolOutput = tools.ToolOutput;+const telemetry = @import("telemetry.zig");+const scoring = @import("scoring.zig");+const promptFingerprint = scoring.promptFingerprint;+const providerClass = scoring.providerClass;+const fleet = @import("fleet.zig");+const Isolation = fleet.Isolation;+const learning_privacy = @import("learning_privacy.zig");+const jobs = @import("jobs.zig");+const cards = @import("cards.zig");+const trace = @import("trace.zig");+const textMessage = @import("messages.zig").textMessage;++fn guiEmit(io: Io, ev: anytype) void {+ if (!main_mod.json_mode) return;+ const w = main_mod.g_out orelse return;+ main_mod.g_gui_mu.lockUncancelable(io);+ defer main_mod.g_gui_mu.unlock(io);+ var s: std.json.Stringify = .{ .writer = w };+ s.write(ev) catch return;+ w.writeByte('\n') catch return;+ w.flush() catch return;+}++pub const FailKind = enum {+ quota,+ transport,+ model,+ invalid,+ auth,+ unknown,++ fn label(self: FailKind) []const u8 {+ return switch (self) {+ .quota => "quota/rate-limit",+ .transport => "transport",+ .model => "model-availability",+ .invalid => "invalid-arguments",+ .auth => "auth",+ .unknown => "unknown",+ };+ }++ pub fn retrySafe(self: FailKind) bool {+ return switch (self) {+ .quota, .transport, .unknown => true,+ .model, .invalid, .auth => false,+ };+ }+};++fn containsAnyCI(hay: []const u8, needles: []const []const u8) bool {+ for (needles) |n| if (util.indexOfIgnoreCase(hay, n) != null) return true;+ return false;+}++pub fn classifyFailure(err: anyerror, detail: ?[]const u8) FailKind {+ switch (err) {+ error.StreamStalled, error.StreamDropped => return .transport,+ else => {},+ }+ const msg = detail orelse return .unknown;+ if (containsAnyCI(msg, &.{ "network error", "stream stalled", "stream dropped", "timed out", "connection reset", "connection closed" })) return .transport;+ if (containsAnyCI(msg, &.{ "rate limit", "rate_limit", "quota", "429", "overloaded", "out of credits", "credits", "billing", "too many requests" })) return .quota;+ if (containsAnyCI(msg, &.{ "api key", "unauthorized", "expired", "authentication", "invalid_api_key", "401" })) return .auth;+ if (containsAnyCI(msg, &.{ "does not exist", "not found", "no such model", "decommission", "no longer", "model_not_found", "unavailable", "404" })) return .model;+ if (containsAnyCI(msg, &.{ "context length", "context window", "invalid", "unsupported", "not supported", "must be", "too long", "400", "parameter", "max_tokens", "bad request" })) return .invalid;+ return .unknown;+}++fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[]const u8) ToolOutput {+ const kind = classifyFailure(err, detail);+ const cause = detail orelse @errorName(err);+ const retry = if (kind.retrySafe())+ "retry is likely safe — re-run the same task (after a short backoff for quota/transport)"+ else+ "retry is NOT safe as-is — fix the cause first (switch model, correct arguments, or re-auth)";+ const text = std.fmt.allocPrint(+ gpa,+ "subagent {s} failed before producing a report: {s} [{s} failure]. {s}",+ .{ sub_id, cause, kind.label(), retry },+ ) catch return .{ .is_error = true };+ return .{ .text = text, .is_error = true };+}++pub fn childProvider(root: Provider, pinned: ?Provider, allow_cross_provider: bool) Provider {+ const child = pinned orelse return root;+ return if (std.mem.eql(u8, child.id, root.id) or allow_cross_provider) child else root;+}++pub const AgentUsage = struct {+ duration_ms: u64 = 0,+ tool_calls: u32 = 0,+ context_tokens: u64 = 0,+ cache_read_tokens: u64 = 0,+};++const AgentUsageEvent = struct {+ type: []const u8 = "agent_usage",+ id: []const u8,+ ok: bool,+ duration_ms: u64,+ tool_calls: u32,+ context_tokens: u64,+ cache_read_tokens: u64,+};++fn agentUsageEvent(sub_id: []const u8, ok: bool, usage: AgentUsage) AgentUsageEvent {+ return .{+ .id = sub_id,+ .ok = ok,+ .duration_ms = usage.duration_ms,+ .tool_calls = usage.tool_calls,+ .context_tokens = usage.context_tokens,+ .cache_read_tokens = usage.cache_read_tokens,+ };+}++pub const SubRun = struct { output: ToolOutput, usage: AgentUsage };++pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) !SubRun {+ const gpa = ctx.gpa;+ if (ctx.run_budget) |budget| if (ctx.depth >= budget.max_depth) return .{+ .output = .{+ .text = try gpa.dupe(u8, "agent depth limit reached (max depth 1) — do this work in the current agent"),+ .is_error = true,+ },+ .usage = .{},+ };+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const child_provider = childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);++ var agent: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = ctx.io,+ .client = ctx.client,+ .provider = child_provider,+ .messages = std.json.Array.init(arena),+ .sub = true,+ .label = label,+ .out = null,+ .approvals = ctx.approvals,+ .tracer = ctx.tracer,+ .run_budget = ctx.run_budget,+ .depth = ctx.depth + 1,+ .call_kind = if (std.mem.eql(u8, kind, "judge_task"))+ .judge+ else if (std.mem.eql(u8, kind, "workflow_retry"))+ .workflow_retry+ else+ .child,+ .sys_override = sys_override,+ };+ const sub_start = Io.Timestamp.now(ctx.io, .awake);+ if (sys_override) |so| if (telemetry.g_telem) |t| {+ if (fleet.promptIsPublic(so)) _ = learning_privacy.approveTemplate(ctx.io, so);+ t.countVariant();+ const child_fp = promptFingerprint(so);+ var parent_buf: [16]u8 = undefined;+ var parent_sha: []const u8 = "";+ if (niche.len > 0) if (fleet.agentTypePrompt(niche)) |ep| {+ parent_buf = promptFingerprint(ep);+ parent_sha = &parent_buf;+ };+ if (so.len <= telemetry.Telemetry.max_propose_text)+ t.fleetEvent("propose", niche, &child_fp, parent_sha, providerClass(agent.provider.model), "", 0, so)+ else if (ctx.tracer) |tr| tr.note("fleet", "propose skipped: genome > 64KB");+ };++ const ordinal = cards.g_subagent_seq.fetchAdd(1, .monotonic);+ var id_buf: [40]u8 = undefined;+ const sub_id = cards.subagentId(&id_buf, ordinal, label, prompt);+ const sprite = cards.subagentSprite(ordinal);+ cards.subagentLaunchCard(arena, sub_id, sprite, label, kind, prompt);++ var wt: ?jobs.AgentWorktree = null;+ var isolation_note: []const u8 = "";+ if (isolation == .worktree) {+ if (jobs.agentWorktreeCreate(gpa, ctx.io, arena, sub_id)) |created| {+ wt = created;+ } else |err| {+ if (!isolation_fallback) return .{+ .output = .{ .text = try gpa.dupe(u8, jobs.isolationFailureText(err)), .is_error = true },+ .usage = .{},+ };+ isolation_note = "\n\n[note: isolation:\"worktree\" failed and fell back to the shared working tree — isolation_fallback:true allowed it]";+ }+ }+ agent.agent_cwd = if (wt) |w| w.path else null;++ const wf_task = std.mem.eql(u8, kind, "workflow_task");+ if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label } });+ try agent.messages.append(try textMessage(arena, "user", prompt));+ defer agent.tools_used.deinit(gpa);+ const report = agent.runTurn();+ const run_ms: i64 = @intCast(@max(0, sub_start.untilNow(ctx.io, .awake).toMilliseconds()));+ const run_ok = if (report) |r| r.len > 0 else |_| false;+ if (wf_task) guiEmit(ctx.io, .{ .type = "tool_result", .name = "subagent", .is_error = !run_ok });+ const used_tools = agent.tools_used.render(arena);+ const usage: AgentUsage = .{+ .duration_ms = @intCast(run_ms),+ .tool_calls = @intCast(agent.tools_used.count()),+ .context_tokens = agent.effectiveContextTokens(),+ .cache_read_tokens = agent.last_cache_read,+ };+ guiEmit(ctx.io, agentUsageEvent(sub_id, run_ok, usage));+ const fp = promptFingerprint(agent.systemPrompt());+ if (trace.g_traj) |tj| {+ tj.capturePrompt(fp, agent.systemPrompt());+ tj.node(.{+ .id = tj.nextId(),+ .parent = tj.currentTurn(),+ .kind = kind,+ .label = label,+ .provider = agent.provider.id,+ .model = agent.provider.model,+ .t = tj.elapsedMs(),+ .ms = run_ms,+ .prompt_sha = &fp,+ .prompt_mutated = sys_override != null,+ .niche = niche,+ .task = util.utf8Prefix(prompt, 160),+ .tools = used_tools,+ .ok = run_ok,+ .context_tokens = agent.effectiveContextTokens(),+ });+ }+ if (telemetry.g_telem) |t| t.runEvent(&fp, sys_override != null, run_ok, run_ms, used_tools);+ const text = report catch |err| {+ var out = subagentFailure(gpa, sub_id, err, agent.last_api_error);+ if (wt) |w| {+ const combined = std.fmt.allocPrint(gpa, "{s}\n\n[worktree left in place after failure — path: {s}, branch: {s}]", .{ out.text, w.path, w.branch }) catch return .{ .output = out, .usage = usage };+ gpa.free(out.text);+ out.text = combined;+ }+ return .{ .output = out, .usage = usage };+ };+ const empty = text.len == 0;+ const report_body = if (empty) "subagent finished without a report" else text;+ const detail = cards.writeSubagentDetail(ctx.io, arena, sub_id, label, kind, prompt, report_body, !empty, run_ms, used_tools);+ cards.subagentDoneCard(arena, sub_id, sprite, label, !empty, run_ms, used_tools, detail);++ var extra: []const u8 = isolation_note;+ var extra_owned = false;+ if (wt) |w| {+ const outcome = jobs.agentWorktreeFinish(gpa, ctx.io, w);+ if (outcome.kept) {+ extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept (has changes) — path: {s}, branch: {s}]", .{ w.path, w.branch }) catch "";+ extra_owned = extra.len > 0;+ }+ }+ defer if (extra_owned) gpa.free(extra);++ if (empty) return .{+ .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}", .{ report_body, extra }), .is_error = true },+ .usage = usage,+ };+ if (detail) |p| return .{+ .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}\n\n[subagent {s} · inspect: {s}]{s}", .{ text, sub_id, p, extra }) },+ .usage = usage,+ };+ return .{ .output = .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}", .{ text, extra }) }, .usage = usage };+}++test "child model pin crosses the current root provider only with consent" {+ const codex_root: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5.6-sol", .context = 272_000 };+ const terra: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5.6-terra", .context = 272_000 };+ const anthropic_root: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "", .model = "claude", .context = 200_000 };+ try std.testing.expectEqualStrings("gpt-5.6-terra", childProvider(codex_root, terra, false).model);+ try std.testing.expectEqualStrings("claude", childProvider(anthropic_root, terra, false).model);+ try std.testing.expectEqualStrings("gpt-5.6-terra", childProvider(anthropic_root, terra, true).model);+}++test "agentUsageEvent maps AgentUsage fields onto the wire event" {+ const ev = agentUsageEvent("sa-007-abcd", true, .{ .duration_ms = 4110, .tool_calls = 6, .context_tokens = 1820, .cache_read_tokens = 340 });+ try std.testing.expectEqualStrings("agent_usage", ev.type);+ try std.testing.expectEqualStrings("sa-007-abcd", ev.id);+ try std.testing.expect(ev.ok);+ try std.testing.expectEqual(@as(u64, 4110), ev.duration_ms);+ try std.testing.expectEqual(@as(u32, 6), ev.tool_calls);+ try std.testing.expectEqual(@as(u64, 1820), ev.context_tokens);+ try std.testing.expectEqual(@as(u64, 340), ev.cache_read_tokens);+ const failed = agentUsageEvent("sa-008-efgh", false, .{});+ try std.testing.expect(!failed.ok);+ try std.testing.expectEqual(@as(u64, 0), failed.duration_ms);+}