graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(subagent): exact model pins fall through to sub-first routing (#292 follow-up)
Rach Pradhan360cc59e72e4
diff --git a/src/schema.zig b/src/schema.zigindex 527730d4..90c321de 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -169,9 +169,9 @@ const meta_specs = [_]ToolSpec{const subagent_spec = ToolSpec{.name = "subagent",- .desc = "Delegate a self-contained task to a subagent. It has bash, read_file, edit_file, write_file, codedb (code search), and skill (load an installed playbook); it cannot spawn further subagents and does NOT share your context — the prompt must be self-contained. Returns the subagent final report. Call several times in one response to run tasks in parallel. Pick a persona with agent (builtins: reviewer, researcher, implementer, skeptic — plus any in .harness/agents/), or give the child a custom system_prompt; the trajectory log records the lineage either way. Set run_in_background true to launch it asynchronously instead: you get the agent id back immediately and keep working, then fetch the result with agent_output. Which model this child runs on is decided in this order: model/tier given on THIS call > the chosen persona's own model:/tier: frontmatter > the session default (--subagent-model, else the default tier ladder) > the root model; within one level an exact model wins over tier. The child's reasoning effort is pinned the same way: effort on THIS call > the persona's effort: frontmatter > the worker default (medium) — an independent axis, so an effort-only override keeps the persona's model pin. Exact model pins are provider-local — they choose a different model on the child's current provider only. An explicit tier ask is the portable lever: when the child's own provider has no such rung, sub-first routing checks every logged-in flat-rate subscription and seats the worker on the best sub serving that rung (the login is the standing consent; metered cross-provider routing still needs --subagent-provider + --allow-cross-provider-subagents). A pin that cannot be honored is ignored (the spawn still runs on the session default) rather than failing.",+ .desc = "Delegate a self-contained task to a subagent. It has bash, read_file, edit_file, write_file, codedb (code search), and skill (load an installed playbook); it cannot spawn further subagents and does NOT share your context — the prompt must be self-contained. Returns the subagent final report. Call several times in one response to run tasks in parallel. Pick a persona with agent (builtins: reviewer, researcher, implementer, skeptic — plus any in .harness/agents/), or give the child a custom system_prompt; the trajectory log records the lineage either way. Set run_in_background true to launch it asynchronously instead: you get the agent id back immediately and keep working, then fetch the result with agent_output. Which model this child runs on is decided in this order: model/tier given on THIS call > the chosen persona's own model:/tier: frontmatter > the session default (--subagent-model, else the default tier ladder) > the root model; within one level an exact model wins over tier. The child's reasoning effort is pinned the same way: effort on THIS call > the persona's effort: frontmatter > the worker default (medium) — an independent axis, so an effort-only override keeps the persona's model pin. Exact model pins resolve provider-locally first — a name the child's own provider serves always wins; one it does not serve falls through to a logged-in flat-rate subscription serving that exact name (never a fuzzy match). An explicit tier ask is the portable lever: when the child's own provider has no such rung, sub-first routing checks every logged-in flat-rate subscription and seats the worker on the best sub serving that rung (the login is the standing consent; metered cross-provider routing still needs --subagent-provider + --allow-cross-provider-subagents). A pin that cannot be honored is ignored (the spawn still runs on the session default) rather than failing.",.schema =- \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task description"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider. Provider-local only — for a portable 'cheapest seat' ask use tier instead, which sub-first routing may seat on a logged-in flat-rate subscription."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this child its own scratch git worktree (auto-removed if it finishes with no changes, kept + reported if it has any) instead of the shared working tree — use for parallel agents that edit files. Default shared_cwd (today's behavior), unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (default false). Poll status/result with agent_output (id, optional wait_ms). A spawn beyond the concurrency cap is queued, never failed."}}, "required": ["description", "prompt"]}+ \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task description"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider — except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this child its own scratch git worktree (auto-removed if it finishes with no changes, kept + reported if it has any) instead of the shared working tree — use for parallel agents that edit files. Default shared_cwd (today's behavior), unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (default false). Poll status/result with agent_output (id, optional wait_ms). A spawn beyond the concurrency cap is queued, never failed."}}, "required": ["description", "prompt"]},};diff --git a/src/subagent_pin.zig b/src/subagent_pin.zigindex b24ba5df..943998f5 100644--- a/src/subagent_pin.zig+++ b/src/subagent_pin.zig@@ -33,12 +33,16 @@//! overrides a persona that says `model: gpt-5.6-sol` — otherwise a per-spawn//! override could not lower a persona's pin, which is its whole point.//!-//! PROVIDER LOCALITY. A pin resolves only against the catalog rows of the+//! PROVIDER LOCALITY. A pin resolves FIRST against the catalog rows of the//! provider the child was ALREADY going to use (root, or --subagent-provider-//! once --allow-cross-provider-subagents consented). So a pin can never move-//! prompts, code, or billing to a second provider: that decision stays with-//! the startup flag and its consent gate, exactly as #292 requires, and-//! Provider.withModel makes it structurally impossible here.+//! once --allow-cross-provider-subagents consented), and a locally-served+//! name always wins: no boundary crossed, no billing moved. The one+//! exception is FLAT-RATE SUBSCRIPTION ROUTING — a logged-in device-login+//! sub is marginal-cost-zero and the login itself is the user's standing+//! consent for that vendor, so an explicit tier ask (subscriptionRung) or an+//! exact model name the child's provider does not serve (subscriptionModel)+//! may be seated on the sub. Metered cross-provider routing still keeps the+//! startup flag and its consent gate, exactly as #292 requires.//!//! GRACEFUL FALLBACK. Every failure to honour a pin resolves to a null//! provider, which the spawn path reads as "keep the session default".@@ -112,6 +116,7 @@ pub const Outcome = enum {no_rung, // the ladder has no model at that rungrung_pricier, // the rung would cost more than the child's current modelsub_routed, // the rung went to a logged-in flat-rate subscription instead+ model_sub_routed, // an exact pin the child's provider does not serve went to a logged-in sub that doespub fn describe(self: Outcome) []const u8 {return switch (self) {@@ -124,6 +129,7 @@ pub const Outcome = enum {.no_rung => "tier pin ignored: this provider's ladder has no model at that rung — kept the session default",.rung_pricier => "tier pin ignored: that rung is pricier than this agent's model — cost never escalates implicitly; pin the model by name to escalate",.sub_routed => "tier routed to a logged-in flat-rate subscription — marginal cost zero outranks metered spend; the login is the user's standing consent for that vendor",+ .model_sub_routed => "model pin routed to a logged-in flat-rate subscription that serves it — the child's provider does not; the login is the user's standing consent for that vendor",};}};@@ -310,6 +316,37 @@ fn subscriptionRung(tier: Tier, base: Provider) ?Resolved {return best;}+/// EXACT-name sub routing, the model axis's counterpart to subscriptionRung:+/// when a pin names a model the child's own provider does not serve, a+/// logged-in flat-rate subscription that DOES serve that exact name (or one+/// of its aliases) honors it — the same standing-consent rule as the tier+/// path, and metered cross-provider keeps its explicit bar. The match is+/// strictly exact/alias, never modelForProvider's substring fallback: a+/// fuzzy hit crossing a provider boundary could seat a model the pin did not+/// name, which is worse than the silent no-op this rescues. Bench scores+/// break the rare tie of two subs serving one name. `src` rides through so+/// the trace still says explicit-pin/persona, not ladder — no rung was+/// consulted.+fn subscriptionModel(query: []const u8, base: Provider, src: Source) ?Resolved {+ const keys = bench_priors.g_keys orelse return null;+ var best: ?Resolved = null;+ var best_score: f64 = -1;+ for (subscription_providers) |sid| {+ if (std.mem.eql(u8, sid, base.id)) continue; // the base's own catalog already answered provider-locally+ for (pricing.models()) |model| {+ if (!std.mem.eql(u8, model.provider, sid)) continue;+ if (!std.mem.eql(u8, model.name, query) and !pricing.modelAliasEquals(model.name, query)) continue;+ const prov = keys.providerById(sid, model.name) catch continue; // not logged in → not a candidate+ const s = bench_priors.scoreFor(sid, model.name) orelse 0;+ if (best == null or s > best_score) {+ best = .{ .provider = prov, .outcome = .model_sub_routed, .source = src };+ best_score = s;+ }+ }+ }+ return best;+}+/// Summed in+out $/1M. An unpriced BASE has no ceiling to enforce (whole/// subscription families like codex carry no per-token price — blocking/// there would kill every intra-family rung); a priced base with an unpriced@@ -346,6 +383,13 @@ fn finish(base: Provider, name: ?[]const u8, source: Source) Resolved {/// with --subagent-provider, an explicit human choice no auto-route may/// override), else resolve the model axis provider-locally against `base`;/// the effort axis rides through verbatim (it needs no catalog).+///+/// Exact model pins are provider-local FIRST: the child's own provider+/// serving the name crosses no boundary and moves no billing, so it always+/// wins. Only when local resolution comes back unknown_model — the pin would+/// otherwise silently no-op — does subscriptionModel try a logged-in+/// flat-rate sub that serves the exact name, under the same login-is-consent+/// rule as the tier path.pub fn forSpawn(base: Provider, obj: std.json.ObjectMap, sub_ok: bool) Resolved {return forSpawnIn(base, obj, sub_ok, .{});}@@ -355,8 +399,17 @@ pub fn forSpawn(base: Provider, obj: std.json.ObjectMap, sub_ok: bool) Resolvedpub fn forSpawnIn(base: Provider, obj: std.json.ObjectMap, sub_ok: bool, cell: Cell) Resolved {const pin = requested(obj);if (pin.isNone()) return .{};+ const pin_src: Source = if (pin.from_persona) .persona else .explicit_pin;var out: Resolved = blk: {- if (sub_ok and pin.model == null) if (pin.tier) |t| if (subscriptionRung(t, base)) |r| break :blk r;+ if (sub_ok) {+ if (pin.model) |q| {+ const local = resolveIn(base, pin, cell);+ if (local.outcome != .unknown_model) break :blk local;+ if (subscriptionModel(q, base, pin_src)) |r| break :blk r;+ break :blk local; // keep the reported unknown_model + its reason+ }+ if (pin.tier) |t| if (subscriptionRung(t, base)) |r| break :blk r;+ }break :blk resolveIn(base, pin, cell);};if (pin.effort) |e| {diff --git a/src/subagent_pin_tests.zig b/src/subagent_pin_tests.zigindex 0346dcb9..d8cdb1d8 100644--- a/src/subagent_pin_tests.zig+++ b/src/subagent_pin_tests.zig@@ -227,12 +227,47 @@ test "sub-first routing: a logged-in flat-rate sub outranks metered for explicit// auto-route may override: back to the provider-local path (deepseek has// no small rung → no_rung, session default kept).try std.testing.expectEqual(pin_mod.Outcome.no_rung, pin_mod.forSpawn(dsv, obj(a, "{\"tier\":\"small\"}"), false).outcome);- // Explicit model pins stay provider-local — naming a model is a statement- // about THIS provider, never a silent hop.- try std.testing.expectEqual(pin_mod.Outcome.unknown_model, pin_mod.forSpawn(dsv, obj(a, "{\"model\":\"gpt-5.6-luna\"}"), true).outcome);+ // Exact model pins: provider-local first, but a name the child's provider+ // does not serve falls through to a logged-in sub that serves it exactly+ // — the same standing consent as the tier path, rescuing a pin that used+ // to silently no-op.+ const mrouted = pin_mod.forSpawn(dsv, obj(a, "{\"model\":\"gpt-5.6-luna\"}"), true);+ try std.testing.expectEqual(pin_mod.Outcome.model_sub_routed, mrouted.outcome);+ try std.testing.expectEqualStrings("codex", mrouted.provider.?.id);+ try std.testing.expectEqualStrings("gpt-5.6-luna", mrouted.provider.?.model);+ try std.testing.expect(mrouted.outcome.describe().len > 0);+ // …under the identical gates: an explicit --subagent-provider+ // (sub_ok=false) forbids the hop…+ try std.testing.expectEqual(pin_mod.Outcome.unknown_model, pin_mod.forSpawn(dsv, obj(a, "{\"model\":\"gpt-5.6-luna\"}"), false).outcome);+ // …and the match is strictly exact/alias — a substring must NOT cross a+ // provider boundary to find a model the pin did not name.+ try std.testing.expectEqual(pin_mod.Outcome.unknown_model, pin_mod.forSpawn(dsv, obj(a, "{\"model\":\"luna\"}"), true).outcome);// No login (g_keys null) → no candidates → the metered ceiling rules.bench.g_keys = null;try std.testing.expectEqual(pin_mod.Outcome.no_rung, pin_mod.forSpawn(dsv, obj(a, "{\"tier\":\"small\"}"), true).outcome);+ try std.testing.expectEqual(pin_mod.Outcome.unknown_model, pin_mod.forSpawn(dsv, obj(a, "{\"model\":\"gpt-5.6-luna\"}"), true).outcome);+}++test "exact pin: the child's own provider wins over a logged-in sub serving the same name" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const bench = @import("bench_priors.zig");+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = .{ .values = @splat(null) };+ for (provider_mod.provider_specs, 0..) |spec, i| {+ if (std.mem.eql(u8, spec.id, "codex")) keys.values[i] = "tok";+ }+ bench.g_keys = &keys;+ // openai's own catalog serves gpt-5.6-luna — the pin resolves locally+ // (.pinned), never hopping to the codex sub that serves the same name:+ // a locally-served pin crosses no boundary and moves no billing.+ const oai: Provider = .{ .id = "openai", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "gpt-5.6", .context = 1_050_000 };+ const got = pin_mod.forSpawn(oai, obj(a, "{\"model\":\"gpt-5.6-luna\"}"), true);+ try std.testing.expectEqual(pin_mod.Outcome.pinned, got.outcome);+ try std.testing.expectEqualStrings("openai", got.provider.?.id);+ try std.testing.expectEqualStrings("gpt-5.6-luna", got.provider.?.model);}test "two logins split the tiers: k3 is mid, luna is the mechanical rung (#471)" {@@ -334,14 +369,20 @@ test "a kimi root borrows codex's cheap rung: small -> luna when it is logged intry std.testing.expectEqual(pin_mod.Outcome.same, pin_mod.forSpawn(kimi_root, obj(a, "{\"tier\":\"frontier\"}"), true).outcome);}-test "a pin never crosses a provider boundary" {+test "without a login, a pin never crosses a provider boundary" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();- // Whatever the base provider is, the answer is that same provider — the- // cross-provider decision stays with --subagent-provider and its consent- // flag, which resolved `base` before a pin was ever consulted.+ // Self-sufficient about login state: sub-first/model sub routing only+ // ever crosses to a LOGGED-IN flat-rate sub, so with g_keys null every+ // pin answer stays on the base provider. The metered cross-provider+ // decision stays with --subagent-provider and its consent flag, which+ // resolved `base` before a pin was ever consulted.+ const bench = @import("bench_priors.zig");+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ bench.g_keys = null;const bases = [_]Provider{codexBase(),.{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-4-8", .context = 200_000 },