Skip to content

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

Python

feat: add root and subagent model shapes

Rach Pradhanc456bdd9f2f1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c498c87c..e0561760 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -91,6 +91,9 @@ jobs:
- name: PTY model preference and fallback test
run: python3 scripts/test-model-preference.py zig-out/bin/graff
+ - name: Root and subagent model-shape routing
+ run: python3 scripts/test-model-shape.py zig-out/bin/graff
+
- name: Codex WS/SSE transport and mid-turn compaction test
run: python3 scripts/test-pty-codex-ws.py zig-out/bin/graff
diff --git a/README.md b/README.md
index 4df59208..0e5f2f31 100644
--- a/README.md
+++ b/README.md
@@ -365,19 +365,20 @@ usage:
graff --schema print the machine-readable interface (SDK codegen)
flags:
- --model <name> start on this model (same fuzzy resolution as /model)
- --yolo skip all permission prompts for the session
- -p, --print one-shot print mode (answer on stdout, tool progress on stderr)
- --timing show per-tool wall-clock on result lines (✓ (312ms) …)
- --cost show running session spend in the prompt ([model · 12k tok · $0.0042])
- --json structured stdio protocol (JSON in, JSONL events out, SDK transport)
+ --model <name> start on this model (same fuzzy resolution as /model)
+ --subagent-model <name> pin children/workflows/judges to this model on the root provider
+ --yolo skip all permission prompts for the session
+ -p, --print one-shot print mode (answer on stdout, tool progress on stderr)
+ --timing show per-tool wall-clock on result lines (✓ (312ms) …)
+ --cost show running session spend in the prompt ([model · 12k tok · $0.0042])
+ --json structured stdio protocol (JSON in, JSONL events out, SDK transport)
--max-model-calls N cap provider calls across root, children, retries, titles, compaction, and judges (default 256)
-h, --help usage
-V, --version version
```
-Unknown flags are an error (with a pointer to `--help`), a missing `--model`
-value is an error, and `--help`/`--version` are handled before subcommand
+Unknown flags are an error (with a pointer to `--help`), missing model-flag
+values are errors, and `--help`/`--version` are handled before subcommand
dispatch, so `graff login --help` prints usage instead of starting an OAuth
flow. With no key configured at all, startup fails with the three quickest fixes
spelled out rather than a bare env-var list.
@@ -738,14 +739,28 @@ history, its own arena, and a subagent-specific system prompt (`execSubagent`).
Because tool calls already fan out via `io.async`, the model spawning three
subagents in one response gets three agent loops running concurrently, each
making its own HTTPS calls through the shared (thread-safe) `std.http.Client`.
-Subagents inherit the parent's provider, so deepseek subagents work the same as
-claude ones.
+Subagents inherit the parent's provider/model by default. A model shape can pin
+all direct children, workflow workers/retries, and LLM judges to another model
+on the same provider/account:
+
+```sh
+graff --model gpt-5.6-sol --subagent-model gpt-5.6-terra
+# equivalent lower-precedence worker setting:
+GRAFF_SUBAGENT_MODEL=gpt-5.6-terra graff --model gpt-5.6-sol
+```
+
+This keeps orchestration/synthesis on Sol and parallel execution on Terra
+without silently crossing credential, billing, or data-boundary domains. Put
+`ultracode` in a task (or run `/ultracode on`) when you want the root to
+actively fan work out; the model split itself does not force delegation.
- Depth capped at one level: subagents don't get the `subagent` tool.
- Subagents don't share the root agent's context, so the orchestrator must put
everything needed into the prompt (the tool description tells it so).
- Progress lines (`[label] ⚙ bash …`) go to stderr via `std.debug.print`, which
locks stderr and is safe from pool threads.
+- Operational API traces and child trajectory nodes record the model that
+ actually handled each call.
</details>
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
index 3df2a998..90a7c958 100644
--- a/docs/releases/v0.0.215.md
+++ b/docs/releases/v0.0.215.md
@@ -55,6 +55,16 @@ and connects Streamable HTTP tools without a Node bridge.
- Local genomes, reports, and immutable evidence are never deleted by the
remote deletion command.
+## Root/worker model shapes
+
+- `--subagent-model <name>` (or `GRAFF_SUBAGENT_MODEL`) keeps the root on
+ `--model` while routing direct subagents, workflow workers/retries, and judges
+ to the pinned model on the same provider. For example, Sol can orchestrate
+ and synthesize while Terra performs parallel delegated work.
+- The split does not silently cross provider/account boundaries and is visible
+ in operational API traces and local child trajectory nodes. Without a pin,
+ children continue to inherit the root provider/model.
+
## Streamable HTTP MCP and OAuth
- Remote MCP servers accept JSON or SSE Streamable HTTP responses, retain
diff --git a/scripts/test-model-shape.py b/scripts/test-model-shape.py
new file mode 100644
index 00000000..3e394485
--- /dev/null
+++ b/scripts/test-model-shape.py
@@ -0,0 +1,179 @@
+#!/usr/bin/env python3
+"""Live proof that a Sol root routes delegated work to Terra."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+
+from codex_ws_mock import CodexMock, RecordedRequest
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+ROOT_MODEL = "gpt-5.6-sol"
+CHILD_MODEL = "gpt-5.6-terra"
+CHILD_REPORT = "TERRA_WORKER_REPORT"
+FINAL_REPORT = "SOL_SYNTHESIS_OK"
+
+
+def message_item(text: str, item_id: str) -> dict:
+ return {
+ "type": "message",
+ "id": item_id,
+ "status": "completed",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": text, "annotations": []}],
+ }
+
+
+def response_events(item: dict, response_id: str) -> list[dict]:
+ return [
+ {"type": "response.output_item.done", "item": item},
+ {
+ "type": "response.completed",
+ "response": {
+ "id": response_id,
+ "usage": {
+ "input_tokens": 100,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 10,
+ "total_tokens": 110,
+ },
+ },
+ },
+ ]
+
+
+def events(request: RecordedRequest) -> list[dict]:
+ model = request.body.get("model")
+ if model == CHILD_MODEL:
+ return response_events(
+ message_item(CHILD_REPORT, "msg_terra_worker"),
+ "resp_terra_worker",
+ )
+ if request.ordinal == 1:
+ return response_events(
+ {
+ "type": "function_call",
+ "id": "fc_shape_worker",
+ "call_id": "call_shape_worker",
+ "name": "subagent",
+ "arguments": json.dumps({
+ "description": "terra worker",
+ "prompt": "Return the worker report exactly.",
+ }),
+ "status": "completed",
+ },
+ "resp_sol_delegate",
+ )
+ return response_events(
+ message_item(FINAL_REPORT, "msg_sol_synthesis"),
+ "resp_sol_synthesis",
+ )
+
+
+def main() -> None:
+ mock = CodexMock(events_for_request=events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-model-shape-") as tmp:
+ root = Path(tmp)
+ codex_home = root / "codex-home"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(json.dumps({
+ "tokens": {
+ "access_token": "model-shape-mock",
+ "account_id": "acct-model-shape",
+ },
+ }), encoding="utf-8")
+ (root / ".codegraff-codex-models.json").write_text(json.dumps({
+ "client_version": "0.144.1",
+ "fetched_at_ms": int(time.time() * 1000),
+ "models": [
+ {"name": ROOT_MODEL, "context": 372000},
+ {"name": CHILD_MODEL, "context": 372000},
+ ],
+ }), encoding="utf-8")
+ harness_dir = root / ".harness"
+ harness_dir.mkdir()
+ (harness_dir / "settings.json").write_text(json.dumps({
+ "ai_title": False,
+ "skills": {"codedbpro": False},
+ }), encoding="utf-8")
+
+ env = os.environ.copy()
+ for name in tuple(env):
+ if name.startswith("GRAFF_") or name.startswith("CODEX_"):
+ env.pop(name)
+ env.update({
+ "HOME": tmp,
+ "CODEX_HOME": str(codex_home),
+ "GRAFF_CODEX_URL": (
+ f"http://127.0.0.1:{port}/backend-api/codex/responses"
+ ),
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_BEHAVIOR_TRACE": "off",
+ "PATH": "/usr/bin:/bin",
+ })
+ completed = subprocess.run(
+ [
+ GRAFF,
+ "--model", ROOT_MODEL,
+ "--subagent-model", "5.6-terra",
+ "--no-resume",
+ "--no-telemetry",
+ "-p", "Delegate once, then synthesize.",
+ ],
+ cwd=tmp,
+ env=env,
+ text=True,
+ capture_output=True,
+ timeout=20,
+ check=False,
+ )
+ if completed.returncode != 0 or FINAL_REPORT not in completed.stdout:
+ raise AssertionError(
+ f"shape run failed ({completed.returncode}): "
+ f"stdout={completed.stdout!r} stderr={completed.stderr!r}"
+ )
+
+ requests = mock.recorded_requests()
+ models = [request.body.get("model") for request in requests]
+ if models != [ROOT_MODEL, CHILD_MODEL, ROOT_MODEL]:
+ raise AssertionError(f"wrong root/worker request shape: {models!r}")
+ final_input = requests[-1].body.get("input")
+ encoded = json.dumps(final_input, separators=(",", ":"))
+ if CHILD_REPORT not in encoded:
+ raise AssertionError("Sol synthesis did not receive the Terra report")
+
+ trajectory_files = list(root.glob(".graff/trajectories/*.jsonl"))
+ if len(trajectory_files) != 1:
+ raise AssertionError(f"expected one trajectory: {trajectory_files!r}")
+ records = [
+ json.loads(line)
+ for line in trajectory_files[0].read_text(encoding="utf-8").splitlines()
+ ]
+ children = [row for row in records if row.get("kind") == "subagent"]
+ if len(children) != 1:
+ raise AssertionError(f"missing child trajectory node: {children!r}")
+ if (
+ children[0].get("provider") != "codex"
+ or children[0].get("model") != CHILD_MODEL
+ ):
+ raise AssertionError(f"child model evidence is wrong: {children[0]!r}")
+ finally:
+ mock.stop()
+
+ print("ok Sol root -> Terra subagent -> Sol synthesis, with model evidence")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agent.zig b/src/agent.zig
index 8f72135c..a19dac47 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -76,10 +76,10 @@ pub const Agent = struct {
io: Io,
client: *std.http.Client,
provider: Provider,
+ subagent_provider: ?Provider = null, // optional model pin for every direct child/workflow/judge
messages: std.json.Array,
// Codex Responses WS delta transport: one WS held across a turn's tool loop,
- // sending previous_response_id + only the new items instead of the full
- // history each step. Reset per turn by runTurn via closeCodexWs.
+ // sending previous_response_id + only new items. Reset by closeCodexWs.
codex_ws: ?*ws.WsClient = null,
codex_prev_id: ?[]const u8 = null, // last response.id (gpa-owned); null = re-anchor with full input
codex_sent_upto: usize = 0, // messages the server already holds; delta = messages[codex_sent_upto..]
diff --git a/src/agent_eval.zig b/src/agent_eval.zig
index 9e7e8b77..ff208fcd 100644
--- a/src/agent_eval.zig
+++ b/src/agent_eval.zig
@@ -218,6 +218,7 @@ pub fn runJudge(self: *Agent, rubric: []const u8, eval_output: []const u8, note:
.io = self.io,
.client = self.client,
.provider = self.provider,
+ .subagent_provider = self.subagent_provider,
.registry = if (self.sub) null else self.registry,
.from_sub = self.sub,
.approvals = self.approvals,
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 28d4cbc8..00e29205 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -134,6 +134,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
.io = self.io,
.client = self.client,
.provider = self.provider,
+ .subagent_provider = self.subagent_provider,
.registry = if (self.sub) null else self.registry,
.from_sub = self.sub,
.approvals = self.approvals,
diff --git a/src/args.zig b/src/args.zig
index 04104235..d395d1dc 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -46,6 +46,7 @@ pub const Flags = struct {
selftest_markdown_flag: bool = false, // --selftest-markdown: render the real streaming markdown fixture in a PTY
update_check: bool = false, // graff update --check
model_flag: ?[]const u8 = null,
+ subagent_model_flag: ?[]const u8 = null,
system_prompt_flag: ?[]const u8 = null,
append_system_flag: ?[]const u8 = null,
host_flag: []const u8 = "127.0.0.1", // harness serve
@@ -150,6 +151,9 @@ pub fn parse(init: std.process.Init) !Flags {
} else if (std.mem.eql(u8, arg, "--model")) {
const mv = it.next() orelse std.process.fatal("--model needs a value — harness --help", .{});
flags.model_flag = try arena.dupe(u8, mv);
+ } else if (std.mem.eql(u8, arg, "--subagent-model")) {
+ const mv = it.next() orelse std.process.fatal("--subagent-model needs a value — harness --help", .{});
+ flags.subagent_model_flag = try arena.dupe(u8, mv);
} else if (std.mem.eql(u8, arg, "--system-prompt")) {
const sv = it.next() orelse std.process.fatal("--system-prompt needs a value — harness --help", .{});
flags.system_prompt_flag = try arena.dupe(u8, sv);
diff --git a/src/cli.zig b/src/cli.zig
index 013e7e08..440cd6e5 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -25,6 +25,7 @@ pub const changelog_text =
\\ • Local learning can race multiple prompt variants, rank correctness before tool economy, and expose only the winner to a hidden holdout
\\ • Runs checkpoint safely, keep promotion manual by default, and can bundle an aggregate-only signed grade submission
\\ • Aggregate receipts expire after 30 days and can be deleted remotely without deleting local evidence or requiring telemetry consent
+ \\ • Root/subagent model shapes can keep orchestration on Sol while routing parallel workers and judges to Terra
\\ • Remote MCP servers now support Streamable HTTP, OAuth discovery/PKCE/refresh, and an opt-out core Smolify connection
\\
\\0.0.209
@@ -88,6 +89,7 @@ pub const usage_text =
\\
\\flags:
\\ --model <name> start on this model (same fuzzy resolution as /model)
+ \\ --subagent-model <name> pin children/workflows/judges on the root provider
\\ --resume <name> resume/autosave <name>.session.json
\\ --new start a fresh autosaved session (default)
\\ --no-resume ignore --resume and start fresh
diff --git a/src/main.zig b/src/main.zig
index fa6e8abc..8caaceff 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -300,6 +300,7 @@ pub fn main(init: std.process.Init) !void {
boot.mark(io, "credentials/model");
var keys = resolved_keys.keys;
const default_provider = resolved_keys.default_provider;
+ const subagent_provider = startup.resolveSubagentProvider(keys, default_provider, flags.subagent_model_flag orelse init.environ_map.get("GRAFF_SUBAGENT_MODEL"));
const stale_saved_model = resolved_keys.stale_saved_model;
const preferred_provider = resolved_keys.preferred_provider;
const codex_account = resolved_keys.codex_account;
@@ -445,7 +446,7 @@ pub fn main(init: std.process.Init) !void {
// Root Agent construction + post-construction config (session name, persisted thinking/goal/eval settings, session-start trace note) + the
// backgrounded fleet-champion pull live in session_start.zig. `root`'s pointer fields (snapshots/client/tracer/approvals/registry) all reference
// already-stable main()-owned storage passed in by address, so returning the constructed Agent by value here is safe.
- var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, sys_strict, &snaps, flags, telem.endpoint);
+ var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, subagent_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, sys_strict, &snaps, flags, telem.endpoint);
root.run_budget = &invocation_budget;
root.model_catalog = resolved_keys.model_catalog;
root.stored_keys_loaded = resolved_keys.stored_keys_loaded;
diff --git a/src/schema.zig b/src/schema.zig
index 6c651c37..6e4c57dd 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -64,7 +64,7 @@ const schema_serve_json =
\\ "endpoints": [
\\ {"method": "GET", "path": "/healthz", "description": "liveness + version, no auth"},
\\ {"method": "GET", "path": "/v1/schema", "description": "this schema document"},
- \\ {"method": "POST", "path": "/v1/sessions", "description": "create a session (a graff --json child); optional JSON body {\"model\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"maxModelCalls\",\"dedupeToolCalls\"} overrides serve-level defaults; responds {\"session_id\":\"<16 hex>\"}"},
+ \\ {"method": "POST", "path": "/v1/sessions", "description": "create a session (a graff --json child); optional JSON body {\"model\",\"subagentModel\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"maxModelCalls\",\"dedupeToolCalls\"} overrides serve-level defaults; responds {\"session_id\":\"<16 hex>\"}"},
\\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / set_system_prompt / set_model / compact / set_mode / set_agent / score / answer); non-answer requests stream application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); answer requests return JSON ack while the original user stream continues; one non-answer request in flight per session at a time"},
\\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin"}
\\ ]
@@ -76,6 +76,7 @@ const schema_serve_json =
const schema_flags_json =
\\[
\\ {"flag": "--model", "arg": "name", "description": "start on this model (same fuzzy resolution as /model)"},
+ \\ {"flag": "--subagent-model", "arg": "name", "description": "pin direct subagents, workflow workers/retries, and judges to this model on the root provider; GRAFF_SUBAGENT_MODEL is the lower-precedence equivalent"},
\\ {"flag": "--yolo", "arg": null, "description": "skip all permission prompts for the session"},
\\ {"flag": "--system-prompt", "arg": "text", "description": "replace the built-in system prompt (cwd project-instructions file is still appended)"},
\\ {"flag": "--append-system-prompt", "arg": "text", "description": "append extra text to the end of the system prompt"},
diff --git a/src/serve.zig b/src/serve.zig
index ecc00aa2..f70aee3f 100644
--- a/src/serve.zig
+++ b/src/serve.zig
@@ -24,6 +24,7 @@ const ServeConfig = struct {
token: ?[]const u8,
yolo: bool,
model: ?[]const u8,
+ subagent_model: ?[]const u8,
system_prompt: ?[]const u8,
append_system_prompt: ?[]const u8,
max_tool_calls: ?u64,
@@ -223,6 +224,7 @@ fn serveCreate(st: *ServeState, req: *std.http.Server.Request) !void {
return respondJson(st, req, .payload_too_large, "{\"error\":\"body too large\"}");
var model = st.cfg.model;
+ var subagent_model = st.cfg.subagent_model;
var yolo = st.cfg.yolo;
var sys = st.cfg.system_prompt;
var append_sys = st.cfg.append_system_prompt;
@@ -236,6 +238,9 @@ fn serveCreate(st: *ServeState, req: *std.http.Server.Request) !void {
if (v.object.get("model")) |m| if (m == .string) {
model = m.string;
};
+ if (v.object.get("subagentModel") orelse v.object.get("subagent_model")) |m| if (m == .string) {
+ subagent_model = m.string;
+ };
if (v.object.get("yolo")) |y| if (y == .bool) {
yolo = y.bool;
};
@@ -260,6 +265,7 @@ fn serveCreate(st: *ServeState, req: *std.http.Server.Request) !void {
try argv.appendSlice(arena, &.{ st.exe, "--json" });
if (yolo) try argv.append(arena, "--yolo");
if (model) |m| try argv.appendSlice(arena, &.{ "--model", m });
+ if (subagent_model) |m| try argv.appendSlice(arena, &.{ "--subagent-model", m });
if (max_tools) |n| try argv.appendSlice(arena, &.{ "--max-tool-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });
if (max_models) |n| try argv.appendSlice(arena, &.{ "--max-model-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });
if (dedupe_tools) try argv.append(arena, "--dedupe-tool-calls");
diff --git a/src/session_run.zig b/src/session_run.zig
index 5d1c3002..c5cb5a24 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -217,6 +217,7 @@ pub fn buildRootAgent(
io: Io,
client: *std.http.Client,
default_provider: provider_mod.Provider,
+ subagent_provider: ?provider_mod.Provider,
environ_map: anytype,
out: *Io.Writer,
in: *Io.Reader,
@@ -236,6 +237,7 @@ pub fn buildRootAgent(
.io = io,
.client = client,
.provider = default_provider,
+ .subagent_provider = subagent_provider,
.home = keys_cli.homeEnv(environ_map) orelse "",
.messages = std.json.Array.init(arena),
.sub = false,
diff --git a/src/startup.zig b/src/startup.zig
index 0584fe85..2ffb4cae 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -115,6 +115,41 @@ fn startupNeedsKimiCatalog(keys: provider_mod.Keys, model_flag: ?[]const u8, sav
return std.mem.eql(u8, fallback.id, "kimi");
}
+pub const SubagentModelError = error{ UnknownModel, ModelNotOnRootProvider, MissingKey };
+
+/// Resolve a child model within the root's provider/account. Keeping the
+/// provider fixed prevents an innocent performance split from silently crossing
+/// credential, billing, or data-boundary domains.
+pub fn subagentProvider(keys: provider_mod.Keys, root: provider_mod.Provider, query: []const u8) SubagentModelError!provider_mod.Provider {
+ const model = pricing.resolveModelName(keys, query) orelse return error.UnknownModel;
+ if (!pricing.providerModelInTable(root.id, model)) return error.ModelNotOnRootProvider;
+ return keys.providerById(root.id, model) catch error.MissingKey;
+}
+
+pub fn resolveSubagentProvider(keys: provider_mod.Keys, root: provider_mod.Provider, query: ?[]const u8) ?provider_mod.Provider {
+ const raw = query orelse return null;
+ const requested = std.mem.trim(u8, raw, " \t\r\n");
+ if (requested.len == 0) std.process.fatal("--subagent-model/GRAFF_SUBAGENT_MODEL cannot be empty", .{});
+ return subagentProvider(keys, root, requested) catch |err| switch (err) {
+ error.UnknownModel => std.process.fatal("unknown subagent model '{s}' — run `graff models refresh` or see /models", .{requested}),
+ error.ModelNotOnRootProvider => std.process.fatal("subagent model '{s}' is not available through root provider '{s}'", .{ requested, root.id }),
+ error.MissingKey => std.process.fatal("no key/login for subagent model '{s}' via '{s}'", .{ requested, root.id }),
+ };
+}
+
+test "subagent model shape pins a cheaper model within the root provider" {
+ var keys: provider_mod.Keys = .{ .values = @splat(null) };
+ for (provider_mod.provider_specs, &keys.values) |spec, *value| {
+ if (std.mem.eql(u8, spec.id, "codex")) value.* = "test-token";
+ }
+ const root = try keys.providerById("codex", "gpt-5.6-sol");
+ const child = try subagentProvider(keys, root, "5.6-terra");
+ try std.testing.expectEqualStrings("codex", child.id);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", child.model);
+ try std.testing.expectError(error.ModelNotOnRootProvider, subagentProvider(keys, root, "gpt-5.6"));
+ try std.testing.expectError(error.UnknownModel, subagentProvider(keys, root, "not-a-real-model"));
+}
+
test "Codex catalog loads at startup only when selection can observe it" {
try std.testing.expectEqualStrings("deepseek", explicitProvider("deepseek").?);
try std.testing.expect(explicitProvider("deepseek-v4-pro") == null);
@@ -447,6 +482,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
.token = token,
.yolo = flags.yolo_flag,
.model = flags.model_flag,
+ .subagent_model = flags.subagent_model_flag,
.system_prompt = flags.system_prompt_flag,
.append_system_prompt = flags.append_system_flag,
.max_tool_calls = main_mod.max_tool_calls,
diff --git a/src/subagent.zig b/src/subagent.zig
index 0c06e9fc..bd999e54 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -150,8 +150,8 @@ fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[
}
/// Run one isolated subagent to completion: fresh arena, fresh history,
-/// same shared http client and provider. Runs entirely on this pool thread;
-/// its own tool calls fan out further via io.async. `sys_override` swaps the
+/// 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.
@@ -164,13 +164,14 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
+ const child_provider = ctx.subagent_provider orelse ctx.provider;
var agent: Agent = .{
.gpa = gpa,
.arena = arena,
.io = ctx.io,
.client = ctx.client,
- .provider = ctx.provider,
+ .provider = child_provider,
.messages = std.json.Array.init(arena),
.sub = true,
.label = label,
@@ -204,7 +205,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
// 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(ctx.provider.model), "", 0, so)
+ 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.
@@ -231,6 +232,8 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
.parent = tj.currentTurn(),
.kind = kind,
.label = label,
+ .provider = agent.provider.id,
+ .model = agent.provider.model,
.t = tj.elapsedMs(),
.ms = run_ms,
.prompt_sha = &fp,
@@ -354,7 +357,7 @@ pub fn scoreVariants(
const jfuts = arena.alloc(Io.Future(ToolOutput), vn) catch return;
for (jfuts, jprompts) |*jf, jp| jf.* = ctx.io.async(judgeTask, .{ ctx, jp });
- const pclass = providerClass(ctx.provider.model);
+ const pclass = providerClass((ctx.subagent_provider orelse ctx.provider).model);
const run_id: []const u8 = &scoring.g_run_id;
for (jfuts, 0..) |*jf, k| {
const i = vidx[k];
diff --git a/src/tools.zig b/src/tools.zig
index 42469446..4eb7e1a1 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -159,6 +159,7 @@ pub const ToolCtx = struct {
io: Io,
client: *std.http.Client,
provider: Provider,
+ subagent_provider: ?Provider = null,
registry: ?*mcp.Registry,
from_sub: bool,
approvals: ?*Approvals,