Skip to content

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

Python

feat: add consented cross-provider worker shapes

Rach Pradhan32f10fb6f50b
diff --git a/README.md b/README.md
index 33dc30f8..96c80b84 100644
--- a/README.md
+++ b/README.md
@@ -367,6 +367,9 @@ usage:
flags:
--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
+ --subagent-provider <id> route pinned workers through this explicit provider
+ --allow-cross-provider-subagents
+ consent to worker prompts/code going to another 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) …)
@@ -750,19 +753,32 @@ 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
+without silently crossing credential, billing, or data-boundary domains.
+Cross-provider workers require an explicit provider and a separate consent
+flag—for example, when both Codex and Kimi are available:
+
+```sh
+graff --model gpt-5.6-sol \
+ --subagent-provider kimi --subagent-model k3 \
+ --allow-cross-provider-subagents
+```
+
+The consent matters because worker prompts, selected code, and tool results go
+to Kimi while root calls continue to go to Codex; telemetry/upload settings are
+independent of that model traffic. Omitting the consent flag fails closed. 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. If
-`/model` later crosses to another provider, children inherit that current root
-instead of using the old pin; switching back restores the compatible pin.
+`/model` later crosses to another provider, a provider-local pin follows the
+current root until it is compatible again. An explicitly consented cross-
+provider pin remains fixed.
- 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.
+- Operational API traces and child trajectory nodes record the provider and
+ model that actually handled each child.
</details>
diff --git a/benchmarks/README.md b/benchmarks/README.md
index d4f2d620..8ce87cff 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -23,7 +23,7 @@ task, the model, and the network.
| `memory.py` | Peak RSS + CPU (`/usr/bin/time -l`) | graff **~25 MB** floor vs Node **~410 MB** vs Rust **~206 MB** |
| `latency.py` | One-shot turn latency, same gpt-5.5 endpoint, concurrent pairs | graff **4.4 s** vs codex **8.9 s** (one-shot only) |
| `memory_session.py` | RSS-vs-turn slope plus session/scratch arena capacity for ONE persistent `--json` session (the #124 leak detector; `memory.py` is one-shot peak RSS and structurally blind to per-turn growth) | flat slope after warmup = no per-turn leak |
-| `model_shape.py` | Correctness, latency, tool/model calls, and routing for all-Sol vs Sol-root/Terra-workers | writes a local correctness-first paired report; no default promotion |
+| `model_shape.py` | Correctness, quality-diversity, latency, tool/model calls, and routing for configurable Sol-root worker shapes | writes a local correctness-first paired report; no default promotion |
```sh
python3 benchmarks/cost.py
@@ -42,8 +42,8 @@ Tasks live in `tasks.py` (edit to test other work).
### Root/worker model shapes
-`model_shape.py` creates three disposable synthetic Python repositories and
-runs paired arms with the same `gpt-5.6-sol` root:
+`model_shape.py` creates disposable synthetic repositories and runs paired arms
+with the same `gpt-5.6-sol` root. Its defaults remain:
- `all-sol`: both direct workers also use Sol;
- `sol-terra`: both direct workers use `gpt-5.6-terra`.
@@ -51,9 +51,12 @@ runs paired arms with the same `gpt-5.6-sol` root:
Every run must produce exactly two correctly routed child trajectory nodes.
Visible tests provide normal agent feedback, while held-back cases grade the
finished workspace afterward. The report selects correctness first and total
-tool economy second, but keeps promotion manual until at least 20 independent
-task pairs are present. One repetition is therefore a smoke/effect-size check;
-seven repetitions across the three fixtures provide 21 pairs:
+tool economy second. It also builds a small QD archive whose cells are declared
+task niches: QD score sums each niche elite's normalized correctness, qualified
+coverage counts fully correct/valid cells, and tool calls then wall time break
+fitness ties. Promotion stays manual until at least 20 independent task pairs
+are present. One repetition is therefore a smoke/effect-size check; seven
+repetitions across the three core fixtures provide 21 pairs:
```sh
python3 benchmarks/model_shape.py \
@@ -62,10 +65,22 @@ python3 benchmarks/model_shape.py \
--output-root /path/to/results
```
+To compare Sol workers with explicitly consented Kimi K3 workers on the three
+frontend niches (responsive layout, accessible interaction, and form state):
+
+```sh
+python3 benchmarks/model_shape.py \
+ --graff zig-out/bin/graff \
+ --task-set frontend \
+ --worker codex:gpt-5.6-sol \
+ --worker kimi:k3 \
+ --output-root /path/to/results
+```
+
The runner disables external telemetry, behavioral upload, fleet sharing,
Smolify, and optional companion tools. Only synthetic fixture content reaches
-the selected Codex account. Operational traces and the JSON report stay inside
-the output directory.
+the selected provider accounts. Operational traces and the JSON report stay
+inside the output directory.
## Honest caveats (please read)
diff --git a/benchmarks/model_shape.py b/benchmarks/model_shape.py
index 08873552..377b278b 100644
--- a/benchmarks/model_shape.py
+++ b/benchmarks/model_shape.py
@@ -1,10 +1,10 @@
#!/usr/bin/env python3
-"""Correctness-first benchmark for Sol-root / Terra-worker model shapes.
+"""Correctness-first benchmark for Sol-root / configurable-worker shapes.
-The benchmark creates fresh synthetic Python repositories, asks graff to use
-exactly two parallel direct subagents, grades the resulting code with visible
-and held-back tests, and reads run-local traces for latency/tool/model evidence.
-No source from the repository containing this script is sent to a model.
+The benchmark creates fresh synthetic repositories, asks graff to use exactly
+two parallel direct subagents, grades the result with visible and held-back
+tests, and reads run-local traces for latency/tool/model evidence. No source
+from the repository containing this script is sent to a model.
"""
from __future__ import annotations
@@ -25,18 +25,41 @@ import tempfile
import time
from typing import Any
-from model_shape_tasks import TASKS, Task
+from model_shape_frontend_tasks import TASKS as FRONTEND_TASKS
+from model_shape_metrics import quality_diversity
+from model_shape_tasks import TASKS as CORE_TASKS, Task
+ROOT_PROVIDER = "codex"
ROOT_MODEL = "gpt-5.6-sol"
WORKER_MODEL = "gpt-5.6-terra"
MINIMUM_PAIRS_FOR_PROMOTION = 20
+ALL_TASKS = CORE_TASKS + FRONTEND_TASKS
@dataclass(frozen=True)
class Arm:
name: str
+ worker_provider: str
worker_model: str
+ allow_cross_provider: bool
+
+
+def arm_for(spec: str) -> Arm:
+ try:
+ provider, model = spec.split(":", 1)
+ except ValueError as exc:
+ raise ValueError("worker shape must be provider:model") from exc
+ if not provider or not model:
+ raise ValueError("worker shape must be provider:model")
+ if provider == ROOT_PROVIDER and model == ROOT_MODEL:
+ name = "all-sol"
+ elif provider == ROOT_PROVIDER:
+ name = "sol-" + model.removeprefix("gpt-5.6-")
+ else:
+ safe_model = re.sub(r"[^a-z0-9]+", "-", model.lower()).strip("-")
+ name = f"sol-{provider}-{safe_model}"
+ return Arm(name, provider, model, provider != ROOT_PROVIDER)
COMMON_REQUEST = """
@@ -154,10 +177,14 @@ def trace_metrics(root: Path, arm: Arm) -> dict[str, Any]:
)
api = [row for row in trace_rows if row.get("ev") == "api"]
tools = [row for row in trace_rows if row.get("ev") == "tool"]
+ retries = [row for row in trace_rows if row.get("ev") == "retry"]
children = [row for row in traj_rows if row.get("kind") == "subagent"]
root_api = [row for row in api if row.get("agent") == "main"]
worker_api = [row for row in api if row.get("agent") != "main"]
expected_children = all(row.get("model") == arm.worker_model for row in children)
+ expected_child_providers = all(
+ row.get("provider") == arm.worker_provider for row in children
+ )
expected_root = all(row.get("model") == ROOT_MODEL for row in root_api)
expected_worker_api = all(
row.get("model") == arm.worker_model for row in worker_api
@@ -177,13 +204,16 @@ def trace_metrics(root: Path, arm: Arm) -> dict[str, Any]:
"response_bytes_sum": sum(max(0, row.get("resp_bytes", 0)) for row in api),
"tool_calls": len(tools),
"tool_errors": sum(bool(row.get("is_error")) for row in tools),
+ "provider_retries": len(retries),
"root_tool_calls": sum(not bool(row.get("from_sub")) for row in tools),
"worker_tool_calls": sum(bool(row.get("from_sub")) for row in tools),
"child_nodes": len(children),
+ "child_providers": [row.get("provider") for row in children],
"child_models": [row.get("model") for row in children],
"shape_valid": (
len(children) == 2
and expected_children
+ and expected_child_providers
and expected_root
and expected_worker_api
and len(worker_api) >= 2
@@ -220,7 +250,14 @@ def run_one(
"--max-model-calls", "24",
"--max-tool-calls", "48",
]
- if arm.worker_model != ROOT_MODEL:
+ if arm.worker_provider != ROOT_PROVIDER:
+ command.extend(
+ [
+ "--subagent-provider", arm.worker_provider,
+ "--allow-cross-provider-subagents",
+ ]
+ )
+ if arm.worker_model != ROOT_MODEL or arm.worker_provider != ROOT_PROVIDER:
command.extend(["--subagent-model", arm.worker_model])
prompt = f"{COMMON_REQUEST}\n\n{task.request}"
stdin = (
@@ -276,7 +313,9 @@ def run_one(
return {
"task": task.name,
"arm": arm.name,
+ "root_provider": ROOT_PROVIDER,
"root_model": ROOT_MODEL,
+ "worker_provider": arm.worker_provider,
"worker_model": arm.worker_model,
"repetition": repetition,
"returncode": returncode,
@@ -318,6 +357,9 @@ def aggregate(rows: list[dict[str, Any]], arms: tuple[Arm, ...]) -> dict[str, An
"median_tool_errors": statistics.median(
row["metrics"]["tool_errors"] for row in selected
),
+ "median_provider_retries": statistics.median(
+ row["metrics"]["provider_retries"] for row in selected
+ ),
"median_context_tokens_sum": statistics.median(
row["metrics"]["context_tokens_sum"] for row in selected
),
@@ -444,7 +486,14 @@ def main() -> int:
parser.add_argument("--repetitions", type=int, default=1)
parser.add_argument("--seed", type=int, default=246)
parser.add_argument("--output-root")
- parser.add_argument("--tasks", nargs="*", choices=[task.name for task in TASKS])
+ parser.add_argument("--task-set", choices=("core", "frontend", "all"), default="core")
+ parser.add_argument("--tasks", nargs="*", choices=[task.name for task in ALL_TASKS])
+ parser.add_argument(
+ "--worker",
+ action="append",
+ metavar="PROVIDER:MODEL",
+ help="exactly two root-worker arms; defaults to Codex Sol and Terra",
+ )
args = parser.parse_args()
if args.repetitions < 1:
parser.error("--repetitions must be positive")
@@ -460,13 +509,26 @@ def main() -> int:
prefix=f"codegraff-model-shape-{datetime.now(timezone.utc):%Y%m%dT%H%M%SZ}-"
)
)
- tasks = tuple(
- task for task in TASKS if not args.tasks or task.name in args.tasks
- )
- arms = (
- Arm("all-sol", ROOT_MODEL),
- Arm("sol-terra", WORKER_MODEL),
+ task_pool = {
+ "core": CORE_TASKS,
+ "frontend": FRONTEND_TASKS,
+ "all": ALL_TASKS,
+ }[args.task_set]
+ tasks = tuple(task for task in task_pool if not args.tasks or task.name in args.tasks)
+ if not tasks:
+ parser.error("selected task set is empty")
+ worker_specs = args.worker or (
+ f"{ROOT_PROVIDER}:{ROOT_MODEL}",
+ f"{ROOT_PROVIDER}:{WORKER_MODEL}",
)
+ if len(worker_specs) != 2:
+ parser.error("--worker must be supplied exactly twice")
+ try:
+ arms = tuple(arm_for(spec) for spec in worker_specs)
+ except ValueError as exc:
+ parser.error(str(exc))
+ if arms[0].name == arms[1].name:
+ parser.error("worker arms must be distinct")
schedule = []
rng = random.Random(args.seed)
for repetition in range(1, args.repetitions + 1):
@@ -498,7 +560,9 @@ def main() -> int:
"graff": str(graff),
"seed": args.seed,
"repetitions": args.repetitions,
+ "task_set": args.task_set,
"tasks": [task.name for task in tasks],
+ "task_niches": {task.name: task.niche for task in tasks},
"privacy": {
"workspace": "synthetic",
"external_telemetry": False,
@@ -507,11 +571,13 @@ def main() -> int:
"arms": [asdict(arm) for arm in arms],
"runs": rows,
"aggregate": aggregate(rows, arms),
+ "quality_diversity": quality_diversity(rows, arms, tasks),
}
report["comparison"] = compare(rows, arms)
report_path = output_root / "report.json"
report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print("\n" + json.dumps(report["aggregate"], indent=2))
+ print("\nquality diversity:\n" + json.dumps(report["quality_diversity"], indent=2))
print("\ncomparison:\n" + json.dumps(report["comparison"], indent=2))
print(f"\nreport: {report_path}")
return 0
diff --git a/benchmarks/model_shape_frontend_tasks.py b/benchmarks/model_shape_frontend_tasks.py
new file mode 100644
index 00000000..c9e82783
--- /dev/null
+++ b/benchmarks/model_shape_frontend_tasks.py
@@ -0,0 +1,295 @@
+"""Deterministic frontend fixtures for the model-shape benchmark."""
+
+from model_shape_tasks import Task
+
+
+TASKS = (
+ Task(
+ name="responsive_portfolio",
+ niche="responsive_layout",
+ source_name="portfolio.html",
+ source="""\
+<!doctype html>
+<html lang="en">
+<head>
+ <title>Selected work</title>
+ <style>
+ body { margin: 0; font-family: sans-serif; }
+ .projects { display: flex; width: 1200px; gap: 12px; }
+ .card { width: 360px; padding: 12px; background: #eee; }
+ .card img { width: 360px; height: 220px; }
+ a { color: blue; }
+ </style>
+</head>
+<body>
+ <div class="nav"><a href="/">Mira</a><a href="#work">Work</a></div>
+ <div id="work">
+ <div class="projects">
+ <div class="card"><img src="one.jpg"><h2>Transit map</h2><a href="/one">Read</a></div>
+ <div class="card"><img src="two.jpg"><h2>Field notes</h2><a href="/two">Read</a></div>
+ <div class="card"><img src="three.jpg"><h2>Type study</h2><a href="/three">Read</a></div>
+ </div>
+ </div>
+</body>
+</html>
+""",
+ visible_tests="""\
+import re
+import unittest
+from pathlib import Path
+
+
+def source():
+ return Path("portfolio.html").read_text().lower()
+
+
+class PortfolioTests(unittest.TestCase):
+ def test_landmarks_and_project_articles(self):
+ text = source()
+ self.assertIn("<nav", text)
+ self.assertIn("<main", text)
+ self.assertGreaterEqual(text.count("<article"), 3)
+
+ def test_fluid_grid(self):
+ compact = re.sub(r"\\s+", "", source())
+ self.assertIn("display:grid", compact)
+ self.assertRegex(compact, r"repeat\\(auto-fit,minmax\\(")
+
+ def test_mobile_breakpoint_removes_fixed_layout(self):
+ text = source()
+ self.assertRegex(text, r"@media\\s*\\([^)]*max-width")
+ self.assertNotRegex(text, r"\\.projects\\s*\\{[^}]*width\\s*:\\s*1200px")
+
+ def test_keyboard_focus_is_visible(self):
+ self.assertIn(":focus-visible", source())
+
+
+if __name__ == "__main__":
+ unittest.main()
+""",
+ visible_count=4,
+ hidden_grader="""\
+import json
+import re
+from pathlib import Path
+
+s = Path("portfolio.html").read_text().lower()
+c = re.sub(r"\\s+", "", s)
+results = {
+ "viewport": bool(re.search(r'<meta[^>]+name=["\\']viewport["\\']', s)),
+ "design_tokens": ":root" in s and "--space-" in s and "var(--" in s,
+ "border_box": "box-sizing:border-box" in c,
+ "reduced_motion": "@media(prefers-reduced-motion:reduce)" in c,
+ "responsive_images": "max-width:100%" in c and "height:auto" in c,
+}
+print(json.dumps(results, sort_keys=True))
+""",
+ hidden_count=5,
+ request="""\
+Repair `portfolio.html` into a polished, responsive portfolio page without
+external libraries. Keep the three projects and links. Use semantic nav/main/
+article landmarks, a fluid CSS grid using `repeat(auto-fit, minmax(...))`, a
+mobile max-width breakpoint, visible keyboard focus, a viewport meta tag,
+border-box sizing, reusable `:root` spacing/color variables, responsive images,
+and a reduced-motion media query. Avoid a fixed-width projects container.
+Only edit `portfolio.html`.
+""",
+ ),
+ Task(
+ name="accessible_modal",
+ niche="accessibility_interaction",
+ source_name="modal.html",
+ source="""\
+<!doctype html>
+<html lang="en">
+<head>
+ <meta name="viewport" content="width=device-width">
+ <title>Delete project</title>
+ <style>
+ #modal { position: absolute; top: 30px; left: 30px; background: white; }
+ .hidden { display: none; }
+ </style>
+</head>
+<body>
+ <main>
+ <h1>Projects</h1>
+ <button id="open">Delete project</button>
+ <p>The project contains seven files.</p>
+ </main>
+ <div id="modal" class="hidden">
+ <h2>Delete?</h2>
+ <button id="cancel">Cancel</button>
+ <button id="confirm">Delete</button>
+ </div>
+ <script>
+ const modal = document.querySelector("#modal");
+ document.querySelector("#open").onclick = () => modal.classList.remove("hidden");
+ document.querySelector("#cancel").onclick = () => modal.classList.add("hidden");
+ </script>
+</body>
+</html>
+""",
+ visible_tests="""\
+import re
+import unittest
+from pathlib import Path
+
+
+def source():
+ return Path("modal.html").read_text().lower()
+
+
+class ModalTests(unittest.TestCase):
+ def test_dialog_relationships(self):
+ text = source()
+ self.assertRegex(text, r'role=["\\']dialog["\\']')
+ self.assertRegex(text, r'aria-modal=["\\']true["\\']')
+ self.assertRegex(text, r'aria-labelledby=["\\'][^"\\']+["\\']')
+
+ def test_opener_announces_dialog(self):
+ text = source()
+ self.assertIn("aria-haspopup=\"dialog\"", text)
+ self.assertRegex(text, r'aria-controls=["\\']modal["\\']')
+
+ def test_escape_closes_and_focus_returns(self):
+ compact = re.sub(r"\\s+", "", source())
+ self.assertIn('key==="escape"', compact)
+ self.assertRegex(compact, r"(open|opener)\\.focus\\(\\)")
+
+ def test_tab_focus_is_trapped(self):
+ text = source()
+ self.assertIn("queryselectorall", text)
+ self.assertIn("document.activeelement", text)
+ self.assertRegex(text, r'key\\s*===?\\s*["\\']tab["\\']')
+
+
+if __name__ == "__main__":
+ unittest.main()
+""",
+ visible_count=4,
+ hidden_grader="""\
+import json
+import re
+from pathlib import Path
+
+s = Path("modal.html").read_text().lower()
+c = re.sub(r"\\s+", "", s)
+label = re.search(r'aria-labelledby=["\\']([^"\\']+)["\\']', s)
+results = {
+ "label_target": bool(label and re.search(r'id=["\\']' + re.escape(label.group(1)) + r'["\\']', s)),
+ "named_close": bool(re.search(r'<button[^>]+(aria-label=["\\'][^"\\']+["\\']|id=["\\']cancel["\\'])', s)),
+ "background_inert": ".inert=true" in c and ".inert=false" in c,
+ "backdrop_close": (".target===modal" in c or ".target==modal" in c),
+ "scroll_lock": "body.style.overflow" in c,
+}
+print(json.dumps(results, sort_keys=True))
+""",
+ hidden_count=5,
+ request="""\
+Repair `modal.html` into an accessible destructive-action modal without
+libraries. The opener must expose its dialog relationship. The modal needs a
+programmatic label, `role=dialog`, and `aria-modal=true`; opening moves focus
+inside, makes the page main inert, and locks body scrolling. Trap Tab and
+Shift+Tab within the modal. Escape, Cancel, and backdrop clicks close it,
+restore background state and scrolling, and return focus to the opener. Give
+the close control an accessible name and center the overlay responsively.
+Only edit `modal.html`.
+""",
+ ),
+ Task(
+ name="persistent_theme_form",
+ niche="form_state",
+ source_name="settings.html",
+ source="""\
+<!doctype html>
+<html lang="en">
+<head>
+ <meta name="viewport" content="width=device-width">
+ <title>Account settings</title>
+ <style>
+ body { font-family: sans-serif; background: white; color: black; }
+ .error { color: red; }
+ </style>
+</head>
+<body>
+ <button id="theme">Theme</button>
+ <form id="settings">
+ <div>Email</div>
+ <input id="email">
+ <span class="error"></span>
+ <div>Team size</div>
+ <input id="size">
+ <button>Save</button>
+ </form>
+ <script>
+ document.querySelector("#theme").onclick = () => document.body.classList.toggle("dark");
+ document.querySelector("#settings").onsubmit = event => event.preventDefault();
+ </script>
+</body>
+</html>
+""",
+ visible_tests="""\
+import re
+import unittest
+from pathlib import Path
+
+
+def source():
+ return Path("settings.html").read_text().lower()
+
+
+class SettingsTests(unittest.TestCase):
+ def test_inputs_have_explicit_labels(self):
+ text = source()
+ self.assertRegex(text, r'<label[^>]+for=["\\']email["\\']')
+ self.assertRegex(text, r'<label[^>]+for=["\\']size["\\']')
+
+ def test_errors_are_connected_and_announced(self):
+ text = source()
+ self.assertIn("aria-describedby", text)
+ self.assertRegex(text, r'role=["\\']alert["\\']')
+
+ def test_submit_uses_constraint_validation(self):
+ text = source()
+ self.assertTrue("checkvalidity" in text or "reportvalidity" in text)
+ self.assertIn("setcustomvalidity", text)
+
+ def test_theme_is_persisted_and_applied(self):
+ text = source()
+ self.assertIn("localstorage", text)
+ self.assertIn("data-theme", text)
+
+
+if __name__ == "__main__":
+ unittest.main()
+""",
+ visible_count=4,
+ hidden_grader="""\
+import json
+import re
+from pathlib import Path
+
+s = Path("settings.html").read_text().lower()
+c = re.sub(r"\\s+", "", s)
+results = {
+ "system_theme": "prefers-color-scheme" in s and "matchmedia" in s,
+ "pressed_state": "aria-pressed" in s and "setattribute" in s,
+ "focus_visible": ":focus-visible" in s,
+ "reduced_motion": "@media(prefers-reduced-motion:reduce)" in c,
+ "input_hints": 'autocomplete="email"' in s and 'inputmode="numeric"' in s,
+}
+print(json.dumps(results, sort_keys=True))
+""",
+ hidden_count=5,
+ request="""\
+Repair `settings.html` as an accessible account-settings form without
+libraries. Add explicit labels and appropriate email/numeric input hints.
+Connect validation text with `aria-describedby`, announce errors, use native
+constraint validation plus a positive plain-integer team-size rule, and clear
+custom errors when corrected. Implement a light/dark theme toggle that updates
+`data-theme` and `aria-pressed`, persists an explicit choice in localStorage,
+and otherwise follows `prefers-color-scheme`. Add design tokens, visible
+keyboard focus, and reduced-motion handling. Only edit `settings.html`.
+""",
+ ),
+)
diff --git a/benchmarks/model_shape_metrics.py b/benchmarks/model_shape_metrics.py
new file mode 100644
index 00000000..bd3c2981
--- /dev/null
+++ b/benchmarks/model_shape_metrics.py
@@ -0,0 +1,77 @@
+"""Quality-diversity metrics for model-shape benchmark reports."""
+
+from __future__ import annotations
+
+from typing import Any, Iterable
+
+
+def quality_diversity(
+ rows: list[dict[str, Any]],
+ arms: Iterable[Any],
+ tasks: Iterable[Any],
+) -> dict[str, Any]:
+ """Build a tiny correctness-first archive over declared task niches.
+
+ QD score is the sum of each niche elite's normalized correctness. Qualified
+ coverage counts niches whose elite is fully correct with the requested
+ provider/model shape. Tool calls and wall time only break correctness ties.
+ """
+ niches = sorted({task.niche for task in tasks})
+ task_niches = {task.name: task.niche for task in tasks}
+ result: dict[str, Any] = {
+ "definition": {
+ "cell": "task_niche",
+ "fitness": "shape_valid_cases_passed / cases_total",
+ "elite_tiebreak": "fewer_tool_calls_then_lower_wall_ms",
+ "qualified": "fitness == 1.0",
+ },
+ "niches": niches,
+ "arms": {},
+ }
+ for arm in arms:
+ archive: dict[str, Any] = {}
+ for niche in niches:
+ candidates = [
+ row
+ for row in rows
+ if row["arm"] == arm.name and task_niches.get(row["task"]) == niche
+ ]
+ if not candidates:
+ continue
+
+ def fitness(row: dict[str, Any]) -> float:
+ if not row["metrics"].get("shape_valid", True):
+ return 0.0
+ total = row["checks"]["total"]
+ return row["checks"]["passed"] / total if total else 0.0
+
+ elite = max(
+ candidates,
+ key=lambda row: (
+ fitness(row),
+ -row["metrics"]["tool_calls"],
+ -row["wall_ms"],
+ ),
+ )
+ archive[niche] = {
+ "task": elite["task"],
+ "repetition": elite.get("repetition", 1),
+ "fitness": fitness(elite),
+ "fully_correct": fitness(elite) == 1.0,
+ "tool_calls": elite["metrics"]["tool_calls"],
+ "wall_ms": elite["wall_ms"],
+ }
+ qd_score = sum(cell["fitness"] for cell in archive.values())
+ qualified = sum(cell["fully_correct"] for cell in archive.values())
+ result["arms"][arm.name] = {
+ "archive": archive,
+ "occupied_cells": len(archive),
+ "qualified_cells": qualified,
+ "qualified_coverage": qualified / len(niches) if niches else 0.0,
+ "qd_score": qd_score,
+ "normalized_qd_score": qd_score / len(niches) if niches else 0.0,
+ "elite_tool_calls": sum(
+ cell["tool_calls"] for cell in archive.values()
+ ),
+ }
+ return result
diff --git a/benchmarks/model_shape_tasks.py b/benchmarks/model_shape_tasks.py
index 6d4af50c..59b2d4ef 100644
--- a/benchmarks/model_shape_tasks.py
+++ b/benchmarks/model_shape_tasks.py
@@ -6,6 +6,7 @@ from dataclasses import dataclass
@dataclass(frozen=True)
class Task:
name: str
+ niche: str
source_name: str
source: str
visible_tests: str
@@ -19,6 +20,7 @@ class Task:
TASKS = (
Task(
name="expiring_lru",
+ niche="cache_lifecycle",
source_name="lease_cache.py",
source="""\
from collections import OrderedDict
@@ -175,6 +177,7 @@ counts only live entries. Preserve normal `KeyError(key)` behavior.
),
Task(
name="route_precedence",
+ niche="routing_rules",
source_name="router.py",
source="""\
from urllib.parse import urlsplit
@@ -292,6 +295,7 @@ An explicit HEAD route wins, otherwise HEAD may fall back to GET.
),
Task(
name="atomic_inventory",
+ niche="transactional_state",
source_name="inventory.py",
source="""\
class OrderConflict(Exception):
@@ -435,4 +439,3 @@ work. Caller mutations must never alter internal state; `snapshot` is a copy.
""",
),
)
-
diff --git a/benchmarks/test_model_shape.py b/benchmarks/test_model_shape.py
index 83c5affe..c0fb9ffa 100644
--- a/benchmarks/test_model_shape.py
+++ b/benchmarks/test_model_shape.py
@@ -10,6 +10,8 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
import model_shape
+from model_shape_frontend_tasks import TASKS as FRONTEND_TASKS
+from model_shape_metrics import quality_diversity
from model_shape_tasks import TASKS
@@ -26,20 +28,26 @@ def fake_run(
"arm": arm,
"repetition": repetition,
"wall_ms": wall_ms,
- "checks": {"passed": passed},
+ "checks": {
+ "passed": passed,
+ "total": 9,
+ "fully_correct": passed == 9,
+ },
"metrics": {
"tool_calls": tools,
"api_calls": 4,
"context_tokens_sum": 100,
"response_bytes_sum": 200,
+ "provider_retries": 0,
+ "shape_valid": True,
},
}
def check_selection() -> None:
arms = (
- model_shape.Arm("all-sol", model_shape.ROOT_MODEL),
- model_shape.Arm("sol-terra", model_shape.WORKER_MODEL),
+ model_shape.arm_for("codex:gpt-5.6-sol"),
+ model_shape.arm_for("codex:gpt-5.6-terra"),
)
rows = []
for index in range(3):
@@ -85,10 +93,13 @@ def check_fixtures() -> None:
"expiring_lru": 2,
"route_precedence": 3,
"atomic_inventory": 0,
+ "responsive_portfolio": 0,
+ "accessible_modal": 1,
+ "persistent_theme_form": 0,
}
with tempfile.TemporaryDirectory(prefix="shape-fixture-check-") as raw:
base = Path(raw)
- for task in TASKS:
+ for task in TASKS + FRONTEND_TASKS:
root = base / task.name
digest = model_shape.initialize_workspace(root, task)
grade = model_shape.run_checks(task, root, digest)
@@ -98,9 +109,29 @@ def check_fixtures() -> None:
assert grade["tests_unchanged"] is True
+def check_quality_diversity() -> None:
+ arms = (
+ model_shape.arm_for("codex:gpt-5.6-sol"),
+ model_shape.arm_for("kimi:k3"),
+ )
+ rows = []
+ for task in FRONTEND_TASKS:
+ rows.append(fake_run(task.name, "all-sol", 8, 120, 12))
+ rows.append(fake_run(task.name, "sol-kimi-k3", 9, 100, 8))
+ qd = quality_diversity(rows, arms, FRONTEND_TASKS)
+ baseline = qd["arms"]["all-sol"]
+ kimi = qd["arms"]["sol-kimi-k3"]
+ assert baseline["qualified_coverage"] == 0
+ assert round(baseline["normalized_qd_score"], 6) == round(8 / 9, 6)
+ assert kimi["qualified_coverage"] == 1
+ assert kimi["qd_score"] == 3
+ assert kimi["elite_tool_calls"] == 24
+
+
def main() -> None:
check_selection()
check_fixtures()
+ check_quality_diversity()
print("ok model-shape selection policy and synthetic fixtures")
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
index 1a3e55d0..ea3d9c8a 100644
--- a/docs/releases/v0.0.215.md
+++ b/docs/releases/v0.0.215.md
@@ -61,9 +61,18 @@ and connects Streamable HTTP tools without a Node bridge.
`--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.
+- `--subagent-provider <id>` can opt into a worker on another service, but only
+ with `--allow-cross-provider-subagents`. Without that separate consent the
+ process fails before a model call, because worker prompts, code, and tool
+ results cross a credential, billing, and data boundary. The HTTP session API
+ exposes the same explicit provider/model/consent fields.
+- Every split is visible in operational API traces and local child trajectory
+ nodes, including the actual child provider and model. Without a pin, children
+ continue to inherit the root provider/model.
+- The reusable benchmark now supports configurable `provider:model` arms,
+ three deterministic frontend niches, and a correctness-first
+ quality-diversity archive. Fully correct, correctly routed cells determine
+ coverage; tools and wall time only break correctness ties.
## Streamable HTTP MCP and OAuth
@@ -105,6 +114,15 @@ and connects Streamable HTTP tools without a Node bridge.
more summed context tokens, and was 2.5% slower on one task. Three pairs are
intentionally under the 20-pair promotion floor, so the result is provisional
and cannot change the default.
+- A separate live frontend smoke run compared all-Sol with Sol-root/Kimi-K3
+ workers. All-Sol won provisionally: its normalized QD score was 0.815 versus
+ 0.667, it completed all 3/3 requested shapes versus K3's 2/3, and it was
+ faster on every pair (K3 used 66.8% more total wall time). K3 did use 58.2%
+ fewer tools, 35.4% fewer API calls, and 50.0% fewer summed context tokens,
+ while matching 9/9 correctness on the form and responsive niches. The
+ accessibility arm timed out after 10 minutes and one responsive call observed
+ and recovered from Kimi engine overload. With only three pairs, K3 remains an
+ explicit experiment rather than an automatic frontend route.
This branch intentionally requires manual promotion until the evidence is
adequately powered.
diff --git a/src/agent.zig b/src/agent.zig
index a19dac47..05242385 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -56,7 +56,6 @@ pub const Goal = struct {
created_ms: i64 = 0,
updated_ms: i64 = 0,
};
-
/// One agent: a message history plus the POST/tool-dispatch loop. The root
/// agent prints to stdout; subagents (sub = true) run on pool threads and
/// log through std.debug.print, which locks stderr and is thread-safe.
@@ -77,6 +76,7 @@ pub const Agent = struct {
client: *std.http.Client,
provider: Provider,
subagent_provider: ?Provider = null, // optional model pin for every direct child/workflow/judge
+ subagent_cross_provider: bool = false, // user explicitly allowed the pin to cross a provider/data boundary
messages: std.json.Array,
// Codex Responses WS delta transport: one WS held across a turn's tool loop,
// sending previous_response_id + only new items. Reset by closeCodexWs.
diff --git a/src/agent_eval.zig b/src/agent_eval.zig
index ff208fcd..2ee940e7 100644
--- a/src/agent_eval.zig
+++ b/src/agent_eval.zig
@@ -219,6 +219,7 @@ pub fn runJudge(self: *Agent, rubric: []const u8, eval_output: []const u8, note:
.client = self.client,
.provider = self.provider,
.subagent_provider = self.subagent_provider,
+ .subagent_cross_provider = self.subagent_cross_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 00e29205..d20d1fe9 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -135,6 +135,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
.client = self.client,
.provider = self.provider,
.subagent_provider = self.subagent_provider,
+ .subagent_cross_provider = self.subagent_cross_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 d395d1dc..9c368c3a 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -46,7 +46,9 @@ 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_provider_flag: ?[]const u8 = null,
subagent_model_flag: ?[]const u8 = null,
+ allow_cross_provider_subagents_flag: bool = false,
system_prompt_flag: ?[]const u8 = null,
append_system_flag: ?[]const u8 = null,
host_flag: []const u8 = "127.0.0.1", // harness serve
@@ -151,9 +153,14 @@ 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-provider")) {
+ const pv = it.next() orelse std.process.fatal("--subagent-provider needs a value — harness --help", .{});
+ flags.subagent_provider_flag = try arena.dupe(u8, pv);
} 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, "--allow-cross-provider-subagents")) {
+ flags.allow_cross_provider_subagents_flag = true;
} 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 440cd6e5..a491b316 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -90,6 +90,8 @@ 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
+ \\ --subagent-provider <id> route pinned workers through this provider
+ \\ --allow-cross-provider-subagents confirm prompts/code may go to the worker 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 8caaceff..d1c2d0f9 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -300,7 +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 subagent_provider = startup.resolveSubagentProvider(keys, default_provider, flags.subagent_provider_flag orelse init.environ_map.get("GRAFF_SUBAGENT_PROVIDER"), flags.subagent_model_flag orelse init.environ_map.get("GRAFF_SUBAGENT_MODEL"), flags.allow_cross_provider_subagents_flag);
const stale_saved_model = resolved_keys.stale_saved_model;
const preferred_provider = resolved_keys.preferred_provider;
const codex_account = resolved_keys.codex_account;
diff --git a/src/schema.zig b/src/schema.zig
index 6e4c57dd..71d8e420 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -53,7 +53,6 @@ const schema_protocol_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
@@ -64,19 +63,20 @@ 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\",\"subagentModel\",\"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\",\"subagentProvider\",\"subagentModel\",\"allowCrossProviderSubagents\",\"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"}
\\ ]
\\}
;
-
/// Launch flags relevant to SDK clients, embedded verbatim in `--schema`
/// output so generated clients can surface them as first-class options.
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": "--subagent-provider", "arg": "id", "description": "route pinned workers through this explicit provider; GRAFF_SUBAGENT_PROVIDER is the lower-precedence equivalent"},
+ \\ {"flag": "--allow-cross-provider-subagents", "arg": null, "description": "explicitly consent to sending worker prompts, code, and tool results to a provider different from the root"},
\\ {"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 f70aee3f..3a63e084 100644
--- a/src/serve.zig
+++ b/src/serve.zig
@@ -24,7 +24,9 @@ const ServeConfig = struct {
token: ?[]const u8,
yolo: bool,
model: ?[]const u8,
+ subagent_provider: ?[]const u8,
subagent_model: ?[]const u8,
+ allow_cross_provider_subagents: bool,
system_prompt: ?[]const u8,
append_system_prompt: ?[]const u8,
max_tool_calls: ?u64,
@@ -224,7 +226,9 @@ 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_provider = st.cfg.subagent_provider;
var subagent_model = st.cfg.subagent_model;
+ var allow_cross_provider_subagents = st.cfg.allow_cross_provider_subagents;
var yolo = st.cfg.yolo;
var sys = st.cfg.system_prompt;
var append_sys = st.cfg.append_system_prompt;
@@ -241,6 +245,12 @@ fn serveCreate(st: *ServeState, req: *std.http.Server.Request) !void {
if (v.object.get("subagentModel") orelse v.object.get("subagent_model")) |m| if (m == .string) {
subagent_model = m.string;
};
+ if (v.object.get("subagentProvider") orelse v.object.get("subagent_provider")) |p| if (p == .string) {
+ subagent_provider = p.string;
+ };
+ if (v.object.get("allowCrossProviderSubagents") orelse v.object.get("allow_cross_provider_subagents")) |a| if (a == .bool) {
+ allow_cross_provider_subagents = a.bool;
+ };
if (v.object.get("yolo")) |y| if (y == .bool) {
yolo = y.bool;
};
@@ -265,7 +275,9 @@ 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_provider) |p| try argv.appendSlice(arena, &.{ "--subagent-provider", p });
if (subagent_model) |m| try argv.appendSlice(arena, &.{ "--subagent-model", m });
+ if (allow_cross_provider_subagents) try argv.append(arena, "--allow-cross-provider-subagents");
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 c5cb5a24..0731ad82 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -238,6 +238,7 @@ pub fn buildRootAgent(
.client = client,
.provider = default_provider,
.subagent_provider = subagent_provider,
+ .subagent_cross_provider = flags.allow_cross_provider_subagents_flag,
.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 2ffb4cae..d364020c 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -34,6 +34,7 @@ const oauth = @import("oauth.zig");
const pricing = @import("pricing.zig");
const models_cache = @import("models_cache.zig");
const kimi_catalog = @import("kimi_catalog.zig");
+const subagent_selection = @import("subagent_selection.zig");
const serde = @import("serde.zig");
const skills = @import("skills.zig");
const prompts = @import("prompts.zig");
@@ -115,40 +116,7 @@ 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"));
-}
+pub const resolveSubagentProvider = subagent_selection.resolveSubagentProvider;
test "Codex catalog loads at startup only when selection can observe it" {
try std.testing.expectEqualStrings("deepseek", explicitProvider("deepseek").?);
@@ -482,7 +450,9 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
.token = token,
.yolo = flags.yolo_flag,
.model = flags.model_flag,
+ .subagent_provider = flags.subagent_provider_flag,
.subagent_model = flags.subagent_model_flag,
+ .allow_cross_provider_subagents = flags.allow_cross_provider_subagents_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 f1d52d04..614e4af9 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -150,17 +150,18 @@ fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[
return .{ .text = text, .is_error = true };
}
-fn childProvider(root: Provider, pinned: ?Provider) Provider {
+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)) child else root;
+ return if (std.mem.eql(u8, child.id, root.id) or allow_cross_provider) child else root;
}
-test "child model pin cannot cross the current root provider" {
+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).model);
- try std.testing.expectEqualStrings("claude", childProvider(anthropic_root, terra).model);
+ 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);
}
/// Run one isolated subagent to completion: fresh arena, fresh history,
@@ -178,7 +179,7 @@ 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 = childProvider(ctx.provider, ctx.subagent_provider);
+ const child_provider = childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);
var agent: Agent = .{
.gpa = gpa,
@@ -371,7 +372,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(childProvider(ctx.provider, ctx.subagent_provider).model);
+ const pclass = providerClass(childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider).model);
const run_id: []const u8 = &scoring.g_run_id;
for (jfuts, 0..) |*jf, k| {
const i = vidx[k];
diff --git a/src/subagent_selection.zig b/src/subagent_selection.zig
new file mode 100644
index 00000000..b89af288
--- /dev/null
+++ b/src/subagent_selection.zig
@@ -0,0 +1,130 @@
+//! Startup-time routing for the optional worker model shape.
+//!
+//! A provider boundary is materially different from a model pin: prompts,
+//! tool results, billing, and credentials move to another service. Cross-
+//! provider workers therefore require both an explicit provider and an
+//! explicit consent flag.
+const std = @import("std");
+
+const pricing = @import("pricing.zig");
+const provider_mod = @import("provider.zig");
+
+pub const Error = error{
+ UnknownModel,
+ UnknownProvider,
+ ModelNotOnProvider,
+ CrossProviderConsentRequired,
+ MissingKey,
+};
+
+fn knownProvider(id: []const u8) bool {
+ for (provider_mod.provider_specs) |spec| {
+ if (std.mem.eql(u8, spec.id, id)) return true;
+ }
+ return false;
+}
+
+fn modelForProvider(provider_id: []const u8, query: []const u8) ?[]const u8 {
+ for (pricing.models()) |model| {
+ if (std.mem.eql(u8, model.provider, provider_id) and
+ std.mem.eql(u8, model.name, query)) return model.name;
+ }
+ for (pricing.models()) |model| {
+ if (std.mem.eql(u8, model.provider, provider_id) and
+ pricing.modelAliasEquals(model.name, query)) return model.name;
+ }
+ var query_buf: [128]u8 = undefined;
+ const normalized_query = pricing.normalizeModelAlias(&query_buf, query);
+ var candidate: ?[]const u8 = null;
+ for (pricing.models()) |model| {
+ if (!std.mem.eql(u8, model.provider, provider_id)) continue;
+ var name_buf: [128]u8 = undefined;
+ const normalized_name = pricing.normalizeModelAlias(&name_buf, model.name);
+ if (std.mem.indexOf(u8, normalized_name, normalized_query) == null) continue;
+ if (candidate != null) return null;
+ candidate = model.name;
+ }
+ return candidate;
+}
+
+pub fn subagentProvider(
+ keys: provider_mod.Keys,
+ root: provider_mod.Provider,
+ provider_query: ?[]const u8,
+ model_query: []const u8,
+ allow_cross_provider: bool,
+) Error!provider_mod.Provider {
+ const requested_provider = if (provider_query) |raw|
+ std.mem.trim(u8, raw, " \t\r\n")
+ else
+ root.id;
+ if (!knownProvider(requested_provider)) return error.UnknownProvider;
+ if (!std.mem.eql(u8, requested_provider, root.id) and !allow_cross_provider)
+ return error.CrossProviderConsentRequired;
+
+ const requested_model = std.mem.trim(u8, model_query, " \t\r\n");
+ const model = modelForProvider(requested_provider, requested_model) orelse {
+ if (pricing.resolveModelName(keys, requested_model) != null)
+ return error.ModelNotOnProvider;
+ return error.UnknownModel;
+ };
+ return keys.providerById(requested_provider, model) catch error.MissingKey;
+}
+
+pub fn resolveSubagentProvider(
+ keys: provider_mod.Keys,
+ root: provider_mod.Provider,
+ provider_query: ?[]const u8,
+ model_query: ?[]const u8,
+ allow_cross_provider: bool,
+) ?provider_mod.Provider {
+ const raw_provider = provider_query orelse "";
+ const requested_provider = std.mem.trim(u8, raw_provider, " \t\r\n");
+ const raw_model = model_query orelse {
+ if (requested_provider.len != 0)
+ std.process.fatal("--subagent-provider requires --subagent-model", .{});
+ return null;
+ };
+ const requested_model = std.mem.trim(u8, raw_model, " \t\r\n");
+ if (requested_model.len == 0)
+ std.process.fatal("--subagent-model/GRAFF_SUBAGENT_MODEL cannot be empty", .{});
+ const provider_arg: ?[]const u8 = if (requested_provider.len == 0) null else requested_provider;
+ return subagentProvider(keys, root, provider_arg, requested_model, allow_cross_provider) catch |err| switch (err) {
+ error.UnknownModel => std.process.fatal("unknown subagent model '{s}' — run `graff models refresh` or see /models", .{requested_model}),
+ error.UnknownProvider => std.process.fatal("unknown subagent provider '{s}' — run `graff models` to list providers", .{requested_provider}),
+ error.ModelNotOnProvider => std.process.fatal("subagent model '{s}' is not available through provider '{s}'", .{ requested_model, if (provider_arg) |id| id else root.id }),
+ error.CrossProviderConsentRequired => std.process.fatal("subagent provider '{s}' differs from root provider '{s}' — add --allow-cross-provider-subagents to confirm prompts and code may be sent to both providers", .{ requested_provider, root.id }),
+ error.MissingKey => std.process.fatal("no key/login for subagent model '{s}' via '{s}'", .{ requested_model, if (provider_arg) |id| id else root.id }),
+ };
+}
+
+test "worker selection stays provider-local unless explicitly allowed" {
+ 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") or
+ std.mem.eql(u8, spec.id, "kimi")) value.* = "test-token";
+ }
+ const root = try keys.providerById("codex", "gpt-5.6-sol");
+ const terra = try subagentProvider(keys, root, null, "5.6-terra", false);
+ try std.testing.expectEqualStrings("codex", terra.id);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", terra.model);
+ try std.testing.expectError(
+ error.CrossProviderConsentRequired,
+ subagentProvider(keys, root, "kimi", "k3", false),
+ );
+ const kimi = try subagentProvider(keys, root, "kimi", "k3", true);
+ try std.testing.expectEqualStrings("kimi", kimi.id);
+ try std.testing.expectEqualStrings("k3", kimi.model);
+ try std.testing.expectError(
+ error.ModelNotOnProvider,
+ subagentProvider(keys, root, null, "gpt-5.6", false),
+ );
+ try std.testing.expectError(
+ error.UnknownModel,
+ subagentProvider(keys, root, null, "not-a-real-model", false),
+ );
+ try std.testing.expectError(
+ error.UnknownProvider,
+ subagentProvider(keys, root, "not-a-provider", "k3", true),
+ );
+}
diff --git a/src/tools.zig b/src/tools.zig
index 4eb7e1a1..49573435 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -160,6 +160,7 @@ pub const ToolCtx = struct {
client: *std.http.Client,
provider: Provider,
subagent_provider: ?Provider = null,
+ subagent_cross_provider: bool = false,
registry: ?*mcp.Registry,
from_sub: bool,
approvals: ?*Approvals,