Skip to content

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

Python

Make harness startup and turns lighter

Rach Pradhan0aa8a55cf4cf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7c00664f..695ac825 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -51,6 +51,9 @@ jobs:
- name: JSON live-control protocol test
run: python3 scripts/test-json-controls.py zig-out/bin/graff
+ - name: Live JSON stream contains no raw stdout lines
+ run: python3 scripts/test-json-live.py zig-out/bin/graff
+
- name: PTY spinner anti-stealth test
run: python3 scripts/test-pty-spinner.py zig-out/bin/graff
@@ -66,6 +69,9 @@ jobs:
- name: Codex WS/SSE transport and mid-turn compaction test
run: python3 scripts/test-pty-codex-ws.py zig-out/bin/graff
+ - name: AI title and first turn run in parallel
+ run: python3 scripts/test-title-parallel.py zig-out/bin/graff
+
- name: Stream stall/drop is not a user Esc (#134/#132)
run: python3 scripts/test-stall-drop.py zig-out/bin/graff
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 8bec01b5..fc43521a 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -22,7 +22,7 @@ task, the model, and the network.
| `cost.py` | USD per task (each tool's own usage, [gateway prices](https://codegraff.com/docs/models)) | graff/deepseek-v4-pro **$0.022** vs Claude Code/Opus-4.8 **$0.51** vs Codex/gpt-5.5 **$0.42** |
| `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 of 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 |
+| `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 |
```sh
python3 benchmarks/cost.py
@@ -31,6 +31,11 @@ python3 benchmarks/latency.py 8
python3 benchmarks/memory_session.py 50 # N turns, one persistent session
```
+`memory_session.py` drives and samples one turn at a time so the child remains
+alive at every RSS sample. Set `GRAFF_BENCH_MODEL` to test a model other than
+`deepseek-v4-pro`; the script enables `GRAFF_MEM_DEBUG` itself and prints both
+arena capacities beside process RSS.
+
Tasks live in `tasks.py` (edit to test other work).
## Honest caveats (please read)
diff --git a/benchmarks/memory_session.py b/benchmarks/memory_session.py
index 8e4df3fd..25f12540 100644
--- a/benchmarks/memory_session.py
+++ b/benchmarks/memory_session.py
@@ -13,6 +13,7 @@ life of the process) — now with a number to confirm or refute a fix.
Run: CODEGRAFF_API_KEY=... python3 benchmarks/memory_session.py [N] [graff-path]
N defaults to 16; graff-path defaults to `graff` on PATH.
+ GRAFF_BENCH_MODEL selects the model (default: deepseek-v4-pro).
"""
import subprocess, json, os, sys
@@ -20,6 +21,8 @@ os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
N = int(sys.argv[1]) if len(sys.argv) > 1 else 16
GRAFF = sys.argv[2] if len(sys.argv) > 2 else "graff"
+MODEL = os.environ.get("GRAFF_BENCH_MODEL", "deepseek-v4-pro")
+SLOPE_LIMIT_MB = 0.1
# Short prompts that each stream a paragraph — many SSE events per turn (the
# parse-garbage axis #124 is about) without slow multi-tool work, so the RSS
@@ -44,40 +47,53 @@ def rss_mb(pid):
def main():
- env = {**os.environ, "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off"}
- p = subprocess.Popen([GRAFF, "--model", "deepseek-v4-pro", "--json"],
+ if N < 2:
+ raise SystemExit("N must be at least 2")
+ env = {**os.environ, "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off",
+ "GRAFF_MEM_DEBUG": "1"}
+ p = subprocess.Popen([GRAFF, "--model", MODEL, "--json"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, env=env, bufsize=1)
samples = []
try:
- # Queue all turns up front (small JSON lines fit the pipe buffer), keep
- # stdin open so the child stays alive for the final RSS sample, then read
- # + sample at each turn boundary. graff processes them sequentially.
+ # Drive one turn at a time and keep stdin open through every sample.
+ # Closing it up front races the final sample against process exit, which
+ # can produce a bogus 0 MB reading and a wildly negative slope.
for i in range(N):
p.stdin.write(json.dumps({"type": "user", "text": PROMPTS[i % len(PROMPTS)]}) + "\n")
- p.stdin.flush()
- p.stdin.close() # EOF after the queued turns so graff drains them all then exits
- done = 0
- while done < N:
- line = p.stdout.readline()
- if not line:
- raise RuntimeError("graff exited early after %d/%d turns" % (done, N))
- try:
- ev = json.loads(line)
- except Exception:
- continue
- if ev.get("type") == "error":
- print(" (error: %s)" % ev.get("message"))
- if ev.get("type") == "turn" and ev.get("complete"):
- done += 1
- r = rss_mb(p.pid)
- samples.append((done, r))
- print(" turn %2d: RSS = %7.1f MB" % (done, r))
+ p.stdin.flush()
+ arena = None
+ while True:
+ line = p.stdout.readline()
+ if not line:
+ raise RuntimeError("graff exited early after %d/%d turns (exit %s)" %
+ (i, N, p.poll()))
+ try:
+ ev = json.loads(line)
+ except Exception:
+ continue
+ if ev.get("type") == "error":
+ raise RuntimeError("turn %d failed: %s" % (i + 1, ev.get("message")))
+ if ev.get("type") == "mem":
+ arena = (ev.get("session_arena_kb", 0), ev.get("scratch_arena_kb", 0))
+ if ev.get("type") == "turn" and ev.get("complete"):
+ r = rss_mb(p.pid)
+ if r <= 0:
+ raise RuntimeError("could not sample RSS for live graff process %d" % p.pid)
+ samples.append((i + 1, r))
+ detail = (" arenas: session=%d KB scratch=%d KB" % arena) if arena else ""
+ print(" turn %2d: RSS = %7.1f MB%s" % (i + 1, r, detail))
+ break
finally:
- try:
- p.stdin.close(); p.terminate(); p.wait(timeout=5)
- except Exception:
- p.kill()
+ if p.stdin and not p.stdin.closed:
+ p.stdin.close()
+ if p.poll() is None:
+ p.terminate()
+ try:
+ p.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ p.kill()
+ p.wait()
tail = samples[2:] if len(samples) > 4 else samples # drop warmup
if len(tail) >= 2:
@@ -87,7 +103,12 @@ def main():
mx, my = sum(xs) / n, sum(ys) / n
den = sum((x - mx) ** 2 for x in xs) or 1.0
slope = sum((x - mx) * (y - my) for x, y in tail) / den
- verdict = "FLAT — no per-turn leak" if abs(slope) < 0.1 else "GROWING — leak present"
+ if slope > SLOPE_LIMIT_MB:
+ verdict = "GROWING — investigate retained memory"
+ elif slope < -SLOPE_LIMIT_MB:
+ verdict = "SHRINKING — no per-turn leak"
+ else:
+ verdict = "FLAT — no per-turn leak"
print("\nRSS growth over turns %d..%d: %+.3f MB/turn (%s)"
% (xs[0], xs[-1], slope, verdict))
print("first-tail %.1f MB -> peak %.1f MB" % (ys[0], max(ys)))
diff --git a/scripts/test-json-live.py b/scripts/test-json-live.py
new file mode 100644
index 00000000..9f2f464f
--- /dev/null
+++ b/scripts/test-json-live.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""Live local-backend proof that --json stdout stays strict JSONL."""
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+
+from codex_ws_mock import CodexMock, REPLY_TEXT
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+
+def decode(line: str) -> dict | None:
+ if not line.strip():
+ return None
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError as exc:
+ raise AssertionError(f"non-JSON stdout line: {line!r}") from exc
+ if not isinstance(event, dict) or not isinstance(event.get("type"), str):
+ raise AssertionError(f"malformed JSON event: {event!r}")
+ return event
+
+
+def main() -> None:
+ mock = CodexMock()
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-json-live-") as tmp:
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home)
+ with open(
+ os.path.join(codex_home, "auth.json"), "w", encoding="utf-8"
+ ) as fh:
+ json.dump(
+ {
+ "tokens": {
+ "access_token": "json-live-mock",
+ "account_id": "acct-json-live",
+ }
+ },
+ fh,
+ )
+ harness_dir = os.path.join(tmp, ".harness")
+ os.makedirs(harness_dir)
+ with open(
+ os.path.join(harness_dir, "settings.json"),
+ "w",
+ encoding="utf-8",
+ ) as fh:
+ json.dump({"skills": {"codedbpro": False}}, fh)
+
+ 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": codex_home,
+ "GRAFF_CODEX_URL": (
+ f"http://127.0.0.1:{port}/backend-api/codex/responses"
+ ),
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ )
+ process = subprocess.Popen(
+ [GRAFF, "--model", "codex", "--json", "--no-telemetry"],
+ cwd=tmp,
+ env=env,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ bufsize=1,
+ )
+ events: list[dict] = []
+ assert process.stdin is not None
+ assert process.stdout is not None
+ try:
+ for turn in range(2):
+ process.stdin.write(
+ json.dumps({"type": "user", "text": f"live turn {turn}"})
+ + "\n"
+ )
+ process.stdin.flush()
+ while True:
+ line = process.stdout.readline()
+ if not line:
+ stderr = process.stderr.read() if process.stderr else ""
+ raise AssertionError(
+ f"graff exited early ({process.poll()}): {stderr}"
+ )
+ event = decode(line)
+ if event is None:
+ continue
+ events.append(event)
+ if event.get("type") == "turn" and event.get("complete"):
+ break
+ process.stdin.close()
+ for line in process.stdout:
+ event = decode(line)
+ if event is not None:
+ events.append(event)
+ code = process.wait(timeout=5)
+ if code != 0:
+ stderr = process.stderr.read() if process.stderr else ""
+ raise AssertionError(f"graff exit={code}: {stderr}")
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ process.wait(timeout=5)
+
+ text_events = [event for event in events if event["type"] == "text"]
+ turns = [event for event in events if event["type"] == "turn"]
+ if len(text_events) != 2 or any(
+ event.get("text") != REPLY_TEXT for event in text_events
+ ):
+ raise AssertionError(f"missing unstreamed text events: {text_events!r}")
+ if len(turns) != 2 or any(
+ event.get("text") != REPLY_TEXT or not event.get("complete")
+ for event in turns
+ ):
+ raise AssertionError(f"bad terminal turn events: {turns!r}")
+ if mock.ws_turns != 2:
+ raise AssertionError(f"expected two WS turns, got {mock.ws_turns}")
+ finally:
+ mock.stop()
+ print("ok live Codex WS emits strict JSONL, including fallback text events")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-title-parallel.py b/scripts/test-title-parallel.py
new file mode 100644
index 00000000..6306c4cd
--- /dev/null
+++ b/scripts/test-title-parallel.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python3
+"""Prove the first-turn AI title request overlaps the real model turn."""
+
+import json
+import os
+import sys
+import tempfile
+import threading
+import time
+
+from codex_ws_mock import CodexMock
+from pty_harness import PtySession
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+MAIN_REPLY = "PARALLEL_TITLE_MAIN_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 main() -> None:
+ barrier = threading.Barrier(2)
+ lock = threading.Lock()
+ arrivals: list[tuple[float, str]] = []
+
+ def events(request) -> list[dict]:
+ instructions = request.body.get("instructions", "")
+ is_title = "You summarize what a coding session is about" in instructions
+ with lock:
+ arrivals.append((time.monotonic(), "title" if is_title else "main"))
+ # A serialized implementation blocks here for three seconds before the
+ # main request can start; true overlap sends both through together.
+ try:
+ barrier.wait(timeout=3.0)
+ except threading.BrokenBarrierError:
+ pass
+ text = "Parallel title generation" if is_title else MAIN_REPLY
+ return [
+ {
+ "type": "response.output_item.done",
+ "item": message_item(text, f"msg_parallel_{request.ordinal}"),
+ },
+ {
+ "type": "response.completed",
+ "response": {
+ "id": f"resp_parallel_{request.ordinal}",
+ "usage": {
+ "input_tokens": 100,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 10,
+ "total_tokens": 110,
+ },
+ },
+ },
+ ]
+
+ mock = CodexMock(events_for_request=events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-title-parallel-") as tmp:
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home)
+ with open(
+ os.path.join(codex_home, "auth.json"), "w", encoding="utf-8"
+ ) as fh:
+ json.dump(
+ {
+ "tokens": {
+ "access_token": "title-parallel-mock",
+ "account_id": "acct-title-parallel",
+ }
+ },
+ fh,
+ )
+ harness_dir = os.path.join(tmp, ".harness")
+ os.makedirs(harness_dir)
+ with open(
+ os.path.join(harness_dir, "settings.json"),
+ "w",
+ encoding="utf-8",
+ ) as fh:
+ json.dump({"skills": {"codedbpro": False}}, fh)
+
+ env = {
+ "HOME": tmp,
+ "CODEX_HOME": 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",
+ }
+ ambient = tuple(
+ name
+ for name in os.environ
+ if (
+ name.startswith("GRAFF_")
+ or name.startswith("CODEX_")
+ or name == "NO_COLOR"
+ )
+ and name not in env
+ )
+ with PtySession(
+ GRAFF,
+ ["--model", "codex", "--no-telemetry"],
+ cwd=tmp,
+ env=env,
+ unset_env=ambient,
+ timeout=10.0,
+ ) as session:
+ session.wait_for_literal("] ›")
+ cursor = len(session.raw)
+ session.send_line("make the title and answer overlap")
+ session.wait_for_literal(MAIN_REPLY, start=cursor)
+ session.wait_for_literal("] ›", start=cursor)
+ session.send_key("ctrl-d")
+ result = session.read_until_exit(5.0)
+ if result.timed_out or result.exit_code != 0:
+ raise AssertionError(
+ f"session exit={result.exit_code} timed_out={result.timed_out}"
+ )
+ finally:
+ mock.stop()
+
+ with lock:
+ observed = sorted(arrivals)
+ if len(observed) != 2 or {kind for _, kind in observed} != {"title", "main"}:
+ raise AssertionError(f"expected one title and one main request: {observed!r}")
+ delta_ms = (observed[1][0] - observed[0][0]) * 1000
+ if delta_ms > 750:
+ raise AssertionError(f"title/main requests serialized ({delta_ms:.1f}ms apart)")
+ print(f"ok AI title and main turn overlapped ({delta_ms:.1f}ms apart)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.py
index 06ddb9c6..95ced6c2 100644
--- a/sdk/py/harness_sdk.py
+++ b/sdk/py/harness_sdk.py
@@ -14,7 +14,7 @@ import urllib.request
from typing import Iterator, Optional
MODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "kimi-k2.6", "kimi-k2.7", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"]
-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "subagent", "workflow"]
+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow"]
PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index 5c0cfda7..633b5638 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -11,7 +11,7 @@ import { createInterface } from "node:readline";
export const HARNESS_VERSION = "0.4";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "kimi-k2.6" | "kimi-k2.7" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});
-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "subagent" | "workflow";
+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by `harness --json` (one JSON object per stdout line), each
@@ -417,4 +417,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {
}
export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "kimi-k2.6", "kimi-k2.7", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];
-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "subagent", "workflow"];
+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow"];
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index ced29c86..5964f7d5 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -10,7 +10,7 @@
export const HARNESS_VERSION = "0.4";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "kimi-k2.6" | "kimi-k2.7" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});
-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "subagent" | "workflow";
+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by the bridge (same `--json` contract as the stdio SDK).
@@ -247,4 +247,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat
}
export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "kimi-k2.6", "kimi-k2.7", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];
-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "subagent", "workflow"];
+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow"];
diff --git a/src/agent.zig b/src/agent.zig
index 78cd8e37..cb60e54a 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -35,6 +35,8 @@ const vision = @import("vision.zig");
const prompts = @import("prompts.zig");
const schema = @import("schema.zig");
const pricing = @import("pricing.zig");
+const models_cache = @import("models_cache.zig");
+const keys_cli = @import("keys_cli.zig");
const ansi = @import("ansi.zig");
const style = &ansi.style;
@@ -150,6 +152,8 @@ pub const Agent = struct {
snapshots: ?*tools_mod.Snapshots = null, // file-edit history for /rewind (root only)
pending_image: ?vision.PendingImage = null, // staged by /image, sent with the next turn
home: []const u8 = "", // $HOME, for /key persistence (set by main)
+ model_catalog: ?models_cache.LazyCodexCatalog = null, // demand-loaded dynamic Codex rows (root only)
+ stored_keys_loaded: bool = true, // false after an explicit-provider launch; model surfaces fill the remaining Keychain slots
keep_context: bool = true, // carry the conversation across wire-format model switches (/keepcontext)
reasoning: ReasoningEffort = .medium, // reasoning/thinking depth — codex, deepseek, codegraff (/effort, /reasoning)
fast: bool = false, // codex "fast" mode → priority service_tier (/fast)
@@ -258,6 +262,10 @@ pub const Agent = struct {
}
pub fn say(self: *Agent, comptime fmt: []const u8, args: anytype) !void {
+ // stdout is a strict JSONL transport in --json mode. Human-facing
+ // notices are represented by their structured terminal/error events;
+ // never leak an unframed line that breaks SDK parsers.
+ if (main_mod.json_mode and !self.sub) return;
if (self.out) |w| {
try w.print(fmt, args);
try w.flush();
@@ -309,6 +317,47 @@ pub const Agent = struct {
};
}
+ /// Root catalogs include meta + MCP tools and are much larger than the
+ /// subagent constants. Materialize only a wire format the session actually
+ /// uses; provider switching calls this before updating the context meter.
+ pub fn ensureRootTools(self: *Agent, kind: Provider.Kind) !void {
+ if (self.sub) return;
+ const slot = switch (kind) {
+ .anthropic => &self.tools_anthropic,
+ .openai => &self.tools_openai,
+ .responses => &self.tools_responses,
+ };
+ if (slot.*.len != 0) return;
+ const specs = try schema.effectiveRootSpecs(self.arena);
+ const connected: []const mcp.Tool = if (self.registry) |registry| registry.tools else &.{};
+ slot.* = try schema.renderRootTools(self.arena, kind, specs, connected);
+ }
+
+ /// A live MCP registry change invalidates provider-specific catalogs. The
+ /// active format is immediately rebuilt; inactive formats remain lazy.
+ pub fn invalidateRootTools(self: *Agent) void {
+ if (self.sub) return;
+ self.tools_anthropic = "";
+ self.tools_openai = "";
+ self.tools_responses = "";
+ }
+
+ pub noinline fn ensureModelCatalog(self: *Agent, keys: provider_mod.Keys) void {
+ if (self.model_catalog) |*catalog|
+ catalog.ensure(self.io, self.gpa, self.arena, self.home, keys.get("codex") orelse "", keys.codex_account);
+ }
+
+ pub fn reloadModelCatalog(self: *Agent, keys: provider_mod.Keys) void {
+ if (self.model_catalog) |*catalog| catalog.invalidate();
+ self.ensureModelCatalog(keys);
+ }
+
+ pub noinline fn ensureStoredKeys(self: *Agent, keys: *provider_mod.Keys) void {
+ if (self.stored_keys_loaded) return;
+ if (self.home.len != 0) keys_cli.loadMissingStoredKeys(self.io, self.gpa, self.arena, self.home, keys, .all);
+ self.stored_keys_loaded = true;
+ }
+
/// Run until the model stops (or, in strict mode, calls
/// attempt_completion). Returns the final assistant text (arena-owned).
/// Close the held codex Responses WS session and reset the delta state. Called
@@ -327,6 +376,9 @@ pub const Agent = struct {
}
pub fn runTurn(self: *Agent) anyerror![]const u8 {
+ // Defensive for restored/embedded agents whose provider was assigned
+ // directly instead of going through providers.applyProvider.
+ try self.ensureRootTools(self.provider.kind);
self.closeCodexWs(); // fresh codex WS session per turn
defer self.closeCodexWs();
self.completed = null;
@@ -383,6 +435,8 @@ pub const Agent = struct {
pub const inputOverCompactThreshold = @import("agent_request.zig").inputOverCompactThreshold;
pub const fullInputEstimateTokens = @import("agent_request.zig").fullInputEstimateTokens;
pub const fullRequestEstimateTokens = @import("agent_request.zig").fullRequestEstimateTokens;
+ pub const contextEstimate = @import("agent_request.zig").contextEstimate;
+ pub const contextEstimateFromInputBytes = @import("agent_request.zig").contextEstimateFromInputBytes;
pub const effectiveContextTokens = @import("agent_request.zig").effectiveContextTokens;
pub const pairContextMeterWithCurrentLocal = @import("agent_request.zig").pairContextMeterWithCurrentLocal;
pub const rebaseContextMeter = @import("agent_request.zig").rebaseContextMeter;
@@ -584,3 +638,37 @@ test "context percent saturates malformed or over-window server meters" {
try std.testing.expectEqual(@as(u64, 100), contextPercent(150_000, 100_000));
try std.testing.expectEqual(@as(u64, 100), contextPercent(std.math.maxInt(u64), 100_000));
}
+
+test "lazy root tool catalogs preserve MCP tools across provider formats" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io);
+ defer registry.deinit();
+ var connected = [_]mcp.Tool{.{
+ .server_index = 0,
+ .original_name = "search",
+ .qualified_name = "mcp__bench__search",
+ .description = "search the benchmark index",
+ .input_schema = .{ .object = .empty },
+ }};
+ registry.tools = &connected;
+
+ var agent: Agent = undefined;
+ agent.arena = arena;
+ agent.sub = false;
+ agent.registry = &registry;
+ agent.tools_anthropic = "";
+ agent.tools_openai = "";
+ agent.tools_responses = "";
+
+ try agent.ensureRootTools(.responses);
+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "mcp__bench__search") != null);
+ try std.testing.expectEqual(@as(usize, 0), agent.tools_openai.len);
+ try std.testing.expectEqual(@as(usize, 0), agent.tools_anthropic.len);
+
+ agent.invalidateRootTools();
+ try agent.ensureRootTools(.anthropic);
+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_anthropic, "mcp__bench__search") != null);
+ try std.testing.expectEqual(@as(usize, 0), agent.tools_responses.len);
+}
diff --git a/src/agent_context.zig b/src/agent_context.zig
index 79e7fc9e..92a4d20f 100644
--- a/src/agent_context.zig
+++ b/src/agent_context.zig
@@ -81,6 +81,30 @@ test "fullInputEstimateTokens (#174): counts retained reasoning the chained usag
try std.testing.expect(est > 2000); // ~8KB serialized / 4 bytes-per-token
}
+test "context estimate reuses an already-serialized history byte count" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var messages = std.json.Array.init(a);
+ try messages.append(try messages_mod.textMessage(a, "user", "measure this once"));
+
+ var agent: Agent = undefined;
+ agent.messages = messages;
+ agent.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5", .context = 100_000 };
+ agent.sub = false;
+ agent.strict = false;
+ agent.sys_normal = "system";
+ agent.sys_strict = "strict";
+ agent.tools_responses = "[]";
+ agent.last_context_tokens = 12_000;
+ agent.context_local_tokens = 8_000;
+
+ const input_bytes = jsonSerializedLen(Value{ .array = messages });
+ const estimate = contextEstimateFromInputBytes(&agent, input_bytes);
+ try std.testing.expectEqual(fullRequestEstimateTokens(&agent), estimate.local);
+ try std.testing.expectEqual(estimate.local + 4_000, estimate.effective);
+}
+
pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize) void {
self.last_cache_read = 0;
self.last_usage_includes_output = false;
@@ -137,9 +161,9 @@ pub fn recordUsage(self: *Agent, root: std.json.ObjectMap, req_body_len: usize)
/// request-body byte/4 when the history isn't serialized yet) when the API omits
/// usage, so auto-compaction still triggers. Never lowers an existing higher count.
fn floorContextTokens(self: *Agent, est: u64) void {
- const local = self.fullRequestEstimateTokens();
- self.last_context_tokens = @max(self.effectiveContextTokens(), @max(local, est));
- self.context_local_tokens = local;
+ const estimate = self.contextEstimate();
+ self.last_context_tokens = @max(estimate.effective, @max(estimate.local, est));
+ self.context_local_tokens = estimate.local;
}
/// A full-history request's nonzero provider usage is authoritative enough to
@@ -192,8 +216,7 @@ pub fn fullInputEstimateTokens(self: *Agent) u64 {
/// must additionally count the mutable system prompt and active tool schema. Keep
/// the old 8k conservative baseline when those serialize smaller, but never let it
/// hide an unbounded set_system_prompt/set_agent payload.
-pub fn fullRequestEstimateTokens(self: *Agent) u64 {
- const input_bytes = jsonSerializedLen(Value{ .array = self.messages });
+fn requestEstimateFromInputBytes(self: *Agent, input_bytes: usize) u64 {
const system_bytes = jsonSerializedLen(self.systemPrompt());
const total_bytes = input_bytes +| system_bytes +| self.toolsJson().len;
const measured: u64 = @intCast(total_bytes / 4);
@@ -202,13 +225,38 @@ pub fn fullRequestEstimateTokens(self: *Agent) u64 {
return @max(measured, input_tokens +| baseline);
}
+pub fn fullRequestEstimateTokens(self: *Agent) u64 {
+ return requestEstimateFromInputBytes(self, jsonSerializedLen(Value{ .array = self.messages }));
+}
+
+pub const ContextEstimate = struct {
+ local: u64,
+ effective: u64,
+};
+
+/// Compute the locally measurable request size and the hidden-token-adjusted
+/// occupancy in one history serialization. Callers that need both previously
+/// walked the entire JSON history twice.
+pub fn contextEstimate(self: *Agent) ContextEstimate {
+ return self.contextEstimateFromInputBytes(jsonSerializedLen(Value{ .array = self.messages }));
+}
+
+/// Variant for callers already serializing the history (session persistence).
+/// Reusing the observed byte count avoids a redundant full JSON walk.
+pub fn contextEstimateFromInputBytes(self: *Agent, input_bytes: usize) ContextEstimate {
+ const local = requestEstimateFromInputBytes(self, input_bytes);
+ return .{
+ .local = local,
+ .effective = local +| (self.last_context_tokens -| self.context_local_tokens),
+ };
+}
+
/// Current context occupancy: today's locally measurable request plus the
/// server-only delta paired with the last usage sample. This automatically
/// counts user/tool content appended after that sample without double-counting
/// provider output once step* advances the local anchor.
pub fn effectiveContextTokens(self: *Agent) u64 {
- const local = self.fullRequestEstimateTokens();
- return local +| (self.last_context_tokens -| self.context_local_tokens);
+ return self.contextEstimate().effective;
}
/// Pair a fresh provider usage sample with history after its response items
@@ -224,8 +272,9 @@ pub fn pairContextMeterWithCurrentLocal(self: *Agent) void {
/// Materialize local input mutations while retaining the server-only delta.
pub fn rebaseContextMeter(self: *Agent) void {
- self.last_context_tokens = self.effectiveContextTokens();
- self.context_local_tokens = self.fullRequestEstimateTokens();
+ const estimate = self.contextEstimate();
+ self.last_context_tokens = estimate.effective;
+ self.context_local_tokens = estimate.local;
self.last_cache_read = 0;
}
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 2f7f6c4e..61e3d736 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -39,6 +39,8 @@ pub const usageInt = context.usageInt;
pub const recordCost = context.recordCost;
pub const fullInputEstimateTokens = context.fullInputEstimateTokens;
pub const fullRequestEstimateTokens = context.fullRequestEstimateTokens;
+pub const contextEstimate = context.contextEstimate;
+pub const contextEstimateFromInputBytes = context.contextEstimateFromInputBytes;
pub const effectiveContextTokens = context.effectiveContextTokens;
pub const pairContextMeterWithCurrentLocal = context.pairContextMeterWithCurrentLocal;
pub const rebaseContextMeter = context.rebaseContextMeter;
@@ -53,7 +55,25 @@ pub const errorMessage = responses.errorMessage;
pub const buildBody = @import("agent_request_body.zig").buildBody;
+/// Keep the normal request hot path allocation-free while avoiding a permanent
+/// RSS high-water mark after one anomalously large stream. Small scratch arenas
+/// retain their pages for the next request; large ones return all pages to the
+/// backing allocator. History never lives here, so either reset mode is safe at
+/// the start of the next request.
+const scratch_retain_limit = 4 * 1024 * 1024;
+
+fn resetRequestScratch(scratch: *std.heap.ArenaAllocator) void {
+ if (scratch.queryCapacity() > scratch_retain_limit) {
+ _ = scratch.reset(.free_all);
+ } else {
+ _ = scratch.reset(.retain_capacity);
+ }
+}
+
pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
+ // Startup paints the prompt while CA loading continues. The root turn and
+ // title task rendezvous here, then issue their requests concurrently.
+ http.waitForClientReady(self.io);
self.last_request_context_overflow = false;
self.last_request_write_failed = false;
self.last_usage_includes_output = false;
@@ -65,7 +85,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
// can use the scratch arena for this request. Safe: all scratch data is
// consumed before the next request(); messages/todos/prompts live on the
// session arena.
- if (self.scratch_arena) |sa| _ = sa.reset(.retain_capacity);
+ if (self.scratch_arena) |sa| resetRequestScratch(sa);
// #148: a login-sourced OAuth token (kimi/xai, ~1h) expires mid-session and
// is minted only at startup; refresh it in place before the call when near
// expiry so a long session — or a subagent that inherited the on-disk token —
@@ -408,3 +428,19 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
return root;
}
}
+
+test "request scratch retains normal capacity but releases an oversized spike" {
+ var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer scratch.deinit();
+
+ _ = try scratch.allocator().alloc(u8, 1024);
+ const normal_capacity = scratch.queryCapacity();
+ try std.testing.expect(normal_capacity > 0);
+ resetRequestScratch(&scratch);
+ try std.testing.expectEqual(normal_capacity, scratch.queryCapacity());
+
+ _ = try scratch.allocator().alloc(u8, scratch_retain_limit + 1);
+ try std.testing.expect(scratch.queryCapacity() > scratch_retain_limit);
+ resetRequestScratch(&scratch);
+ try std.testing.expectEqual(@as(usize, 0), scratch.queryCapacity());
+}
diff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zig
index 47613898..19737dcb 100644
--- a/src/agent_request_policy.zig
+++ b/src/agent_request_policy.zig
@@ -102,9 +102,9 @@ pub fn recoverContextOverflow(self: *Agent, msg: []const u8, code: ?[]const u8,
self.last_request_context_overflow = true;
// Rejection proves at least the advertised window, not an exact total.
// Preserve stronger server/local evidence already above that floor.
- const local = self.fullRequestEstimateTokens();
- self.last_context_tokens = @max(self.effectiveContextTokens(), self.provider.context);
- self.context_local_tokens = local;
+ const estimate = self.contextEstimate();
+ self.last_context_tokens = @max(estimate.effective, self.provider.context);
+ self.context_local_tokens = estimate.local;
// compact() marks its synthetic summary request explicitly. Generic
// in-request recovery is destructive there: the synthetic compact
// instruction is the newest clean user turn, so emergencyTrim can discard
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 5e31bb4d..91eb5dfe 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -21,6 +21,13 @@ const messages_mod = @import("messages.zig");
const util = @import("util.zig");
const toolResultMessage = messages_mod.toolResultMessage;
+fn surfaceUnstreamedText(self: *Agent, text: []const u8) !void {
+ if (self.sub or self.streamed_text or text.len == 0) return;
+ if (main_mod.json_mode) {
+ self.emit(.{ .type = "text", .text = text });
+ } else try self.say("{s}\n", .{text});
+}
+
// ssePayload/sseIndex live in agent_stream.zig; reached through the Agent
// struct's member aliases.
const ssePayload = Agent.ssePayload;
@@ -50,7 +57,7 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {
if (std.mem.eql(u8, bt, "output_text")) {
if (block.object.get("text")) |txt| if (txt == .string) {
final_text = txt.string;
- if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{txt.string});
+ try surfaceUnstreamedText(self, txt.string);
};
}
}
@@ -116,7 +123,7 @@ pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
if (std.mem.eql(u8, kind, "text")) {
if (block.object.get("text")) |tx| if (tx == .string) {
final_text = tx.string;
- if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{final_text});
+ try surfaceUnstreamedText(self, final_text);
};
} else if (std.mem.eql(u8, kind, "tool_use")) {
const name = if (block.object.get("name")) |n| (if (n == .string) n.string else "") else "";
@@ -165,7 +172,7 @@ pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
var final_text: []const u8 = "";
if (message.object.get("content")) |c| if (c == .string and c.string.len > 0) {
final_text = c.string;
- if (!self.sub and !self.streamed_text) try self.say("{s}\n", .{c.string});
+ try surfaceUnstreamedText(self, c.string);
};
var calls: std.ArrayList(ToolCall) = .empty;
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 3ff14cdb..efa9b155 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -37,11 +37,6 @@ const models_cache = @import("models_cache.zig");
const command_catalog = @import("command_catalog.zig");
const serde = @import("serde.zig");
-const schema = @import("schema.zig");
-const renderRootTools = schema.renderRootTools;
-const root_specs = schema.root_specs;
-const effectiveRootSpecs = schema.effectiveRootSpecs; // #225: gate clock_sleep on the flag when re-rendering the tool lists
-
const mcp_cli = @import("mcp_cli.zig");
const persistMcpServer = mcp_cli.persistMcpServer;
@@ -67,6 +62,8 @@ fn providerModelCount(provider_id: []const u8) usize {
}
fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer) !void {
+ root.ensureStoredKeys(keys);
+ root.ensureModelCatalog(keys.*);
const saved = serde.loadModel(root.io, arena, root.home);
try out.print("{s}model health{s}\n", .{ style.bold, style.reset });
try out.print("active: {s} via {s} · {d}k ctx · compact@{d}k{s}{s}\n", .{
@@ -205,11 +202,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
};
- // Re-render the tool lists so the new tools reach the model.
- const root_tool_specs = try effectiveRootSpecs(arena); // #225: gate clock_sleep on the flag
- root.tools_anthropic = try renderRootTools(arena, .anthropic, root_tool_specs, reg.tools);
- root.tools_openai = try renderRootTools(arena, .openai, root_tool_specs, reg.tools);
- root.tools_responses = try renderRootTools(arena, .responses, root_tool_specs, reg.tools);
+ // Re-render the active catalog so the new tools reach the model;
+ // inactive provider formats stay lazy until a later switch.
+ root.invalidateRootTools();
+ try root.ensureRootTools(root.provider.kind);
root.rebaseContextMeter();
const persisted = persistMcpServer(root.io, arena, name, command, args.items);
var has_note = false;
@@ -235,11 +231,9 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
if (n == 0) {
try out.writeAll("no untrusted workspace MCP server(s) to connect.\n");
} else {
- // Re-render the tool lists so the new tools reach the model.
- const root_tool_specs = try effectiveRootSpecs(arena); // #225: gate clock_sleep on the flag
- root.tools_anthropic = try renderRootTools(arena, .anthropic, root_tool_specs, reg.tools);
- root.tools_openai = try renderRootTools(arena, .openai, root_tool_specs, reg.tools);
- root.tools_responses = try renderRootTools(arena, .responses, root_tool_specs, reg.tools);
+ // Re-render the active catalog; other wire formats remain lazy.
+ root.invalidateRootTools();
+ try root.ensureRootTools(root.provider.kind);
root.rebaseContextMeter();
try out.print("{s}✓{s} trusted workspace — connected {d} MCP server(s); {d} tool(s) total\n", .{ style.green, style.reset, n, reg.tools.len });
}
@@ -267,6 +261,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
if (std.mem.eql(u8, line, "/models")) {
+ root.ensureStoredKeys(keys);
+ root.ensureModelCatalog(keys.*);
try out.writeAll("model ctx compact@ provider key vision\n");
for (pricing.models()) |m| {
const has_key = keys.get(m.provider) != null;
@@ -394,6 +390,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
if (std.mem.startsWith(u8, line, "/resume")) {
+ root.ensureStoredKeys(keys);
const arg = std.mem.trim(u8, line["/resume".len..], " \t");
var name: []const u8 = if (arg.len == 0) "last" else arg;
// Bare /resume on a TTY: pick from the saved sessions interactively,
@@ -421,7 +418,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
const idx = listPicker(root, arena, out, "Resume session ›", sessions.items) orelse return true;
name = entries.items[idx].base;
}
- loadSession(root, keys.*, arena, name) catch |err| {
+ loadSession(root, keys, arena, name) catch |err| {
switch (err) {
error.FileNotFound => try out.print("no session named '{s}' ({s}{s} not found in cwd) — /sessions lists saved ones\n", .{ name, name, session_ext }),
else => try out.print("resume failed: {t}\n", .{err}),
diff --git a/src/commands_model.zig b/src/commands_model.zig
index b4097032..28bd0023 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -124,13 +124,15 @@ fn handleFallback(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Wri
pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
if (try handleFallback(root, arena, line, out)) return true;
if (std.mem.startsWith(u8, line, "/model") and !std.mem.startsWith(u8, line, "/models")) {
+ root.ensureStoredKeys(keys);
const arg = std.mem.trim(u8, line["/model".len..], " \t");
+ if (providers.modelQueryMayUseCodex(arg)) root.ensureModelCatalog(keys.*);
if (arg.len == 0) {
if (main_mod.use_color) { // interactive TTY → fuzzy picker
if (modelPicker(root, keys, arena, out)) |idx| {
const m = pricing.models()[idx];
const provider = keys.providerById(m.provider, m.name) catch {
- try offerProviderAuth(root, keys, arena, out, m.provider, m.name);
+ try offerProviderAuth(root, keys, arena, out, m.provider, m.name, false);
return true;
};
try switchProvider(root, arena, provider, out);
@@ -168,7 +170,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
const m = try arena.dupe(u8, mdl);
const provider = keys.providerById(pid, m) catch {
- try offerProviderAuth(root, keys, arena, out, pid, m);
+ try offerProviderAuth(root, keys, arena, out, pid, m, false);
return true;
};
try switchProvider(root, arena, provider, out);
@@ -184,7 +186,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
// baked default. One loaded → switch straight to it; many → list to pick.
if (isLocalUrl(spec.url)) {
const key = keys.get(spec.id) orelse {
- try offerProviderAuth(root, keys, arena, out, spec.id, pricing.providerDefaultModel(spec.id, spec.default_model));
+ try offerProviderAuth(root, keys, arena, out, spec.id, pricing.providerDefaultModel(spec.id, spec.default_model), true);
return true;
};
const murl = openAiModelsUrl(arena, spec.url);
@@ -205,7 +207,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
const default_model = pricing.providerDefaultModel(spec.id, spec.default_model);
const provider = keys.providerById(spec.id, default_model) catch {
- try offerProviderAuth(root, keys, arena, out, spec.id, default_model);
+ try offerProviderAuth(root, keys, arena, out, spec.id, default_model, true);
return true;
};
try switchProvider(root, arena, provider, out);
@@ -219,7 +221,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
const name = try arena.dupe(u8, resolved);
const provider = keys.providerFor(name) catch {
for (pricing.models()) |mt| if (std.mem.eql(u8, mt.name, name)) {
- try offerProviderAuth(root, keys, arena, out, mt.provider, name);
+ try offerProviderAuth(root, keys, arena, out, mt.provider, name, false);
return true;
};
try out.writeAll("no API key for any provider serving that model — see /models, or add one with /key <provider> <key>\n");
@@ -397,6 +399,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
if (std.mem.startsWith(u8, line, "/key")) {
+ root.ensureStoredKeys(keys);
const rest = std.mem.trim(u8, line["/key".len..], " \t");
if (rest.len == 0) { // show key status + how to add
try out.writeAll("API keys (✓ = set via env / Keychain / login):\n");
@@ -437,6 +440,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
if (std.mem.startsWith(u8, line, "/login")) {
+ root.ensureStoredKeys(keys);
// Interactive OAuth sign-in for the providers that have a device/PKCE
// flow (codegraff, codex/ChatGPT, kimi). Mirrors the `graff login`
// subcommands but runs in-session and pulls the fresh key into the live
diff --git a/src/fleet.zig b/src/fleet.zig
index 318badfb..84bcdb79 100644
--- a/src/fleet.zig
+++ b/src/fleet.zig
@@ -20,6 +20,7 @@ const root = @import("main.zig");
const trace = @import("trace.zig");
const telemetry_mod = @import("telemetry.zig");
const Telemetry = telemetry_mod.Telemetry;
+const http = @import("http.zig");
const trajectory_path = trace.trajectory_path;
// ── Agent types (the MAP-Elites niches) ─────────────────────────────────────
@@ -263,6 +264,7 @@ pub fn agentTypePrompt(name: []const u8) ?[]const u8 {
/// live beside it at /v1/elites.
pub fn pullElites(io: Io, arena: Allocator, client: *std.http.Client, telem: ?*Telemetry, endpoint: []const u8, provider_class: []const u8, eval_set_hash: []const u8, types: []const AgentType) []const AgentType {
if (endpoint.len == 0 or !root.g_fleet) return types;
+ http.waitForClientReady(io);
var base = std.mem.trimEnd(u8, endpoint, "/");
if (std.mem.endsWith(u8, base, "/v1/logs")) base = base[0 .. base.len - "/v1/logs".len];
// No eval suite → omit eval_set_hash entirely (NOT empty): the worker reads an
diff --git a/src/http.zig b/src/http.zig
index d77ffa95..c6fc196c 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -17,6 +17,14 @@ const Agent = agent_mod.Agent;
const anthropic_version = root.anthropic_version;
const kimi_user_agent = root.kimi_user_agent;
+/// Launch-scoped gate installed while the shared client's CA bundle warms in
+/// the background. Null in unit tests and standalone pre-client subcommands.
+pub var g_client_ready: ?*Io.Event = null;
+
+pub fn waitForClientReady(io: Io) void {
+ if (g_client_ready) |ready| ready.waitUncancelable(io);
+}
+
pub fn providerUserAgent(provider: Provider) std.http.Client.Request.Headers.Value {
if (std.mem.eql(u8, provider.id, "kimi")) {
return .{ .override = kimi_user_agent };
diff --git a/src/keys_cli.zig b/src/keys_cli.zig
index 4a32a73e..ec76a2e3 100644
--- a/src/keys_cli.zig
+++ b/src/keys_cli.zig
@@ -5,7 +5,8 @@
//! "simple-harness", account=provider id) via the `security` CLI — never on
//! disk in plaintext. Elsewhere they fall back to a 0600 file
//! (~/.simple-harness-keys.json). `harness key set <provider> <key>` writes;
-//! startup reads for any provider whose env var isn't set (env always wins).
+//! startup reads the selected provider first (env always wins), then fills the
+//! remaining providers when a picker, switch, resume, or fallback needs them.
//!
//! storeKey stays pub — commands_model.zig and pickers.zig back-import it as
//! `main_mod.storeKey`; isLocalUrl/openAiModelsUrl/fetchOpenAIModels stay pub
@@ -153,6 +154,75 @@ pub fn loadStoredKey(io: Io, arena: Allocator, home: []const u8, provider: []con
return null;
}
+pub const StoredKeyScope = union(enum) {
+ all,
+ provider: []const u8,
+ mask: [provider_specs.len]bool,
+
+ pub fn includes(scope: StoredKeyScope, index: usize, provider_id: []const u8) bool {
+ return switch (scope) {
+ .all => true,
+ .provider => |id| std.mem.eql(u8, id, provider_id),
+ .mask => |mask| mask[index],
+ };
+ }
+};
+
+test "StoredKeyScope selects all, one provider, or an exact mask" {
+ const all: StoredKeyScope = .all;
+ try std.testing.expect(all.includes(0, provider_specs[0].id));
+ const one: StoredKeyScope = .{ .provider = "deepseek" };
+ try std.testing.expect(one.includes(2, "deepseek"));
+ try std.testing.expect(!one.includes(1, "codegraff"));
+ var mask = [_]bool{false} ** provider_specs.len;
+ mask[1] = true;
+ const selected: StoredKeyScope = .{ .mask = mask };
+ try std.testing.expect(selected.includes(1, "codegraff"));
+ try std.testing.expect(!selected.includes(2, "deepseek"));
+}
+
+fn loadStoredKeyTask(io: Io, gpa: Allocator, home: []const u8, provider_id: []const u8) ?[]u8 {
+ var task_arena = std.heap.ArenaAllocator.init(gpa);
+ defer task_arena.deinit();
+ const key = loadStoredKey(io, task_arena.allocator(), home, provider_id) orelse return null;
+ return gpa.dupe(u8, key) catch null;
+}
+
+/// Fill selected missing credential slots. macOS stores one Keychain item per
+/// provider, so its independent `security` processes run concurrently with
+/// task-local arenas. Other platforms keep all keys in one JSON file: read and
+/// parse it once, then fill every selected slot from that single object.
+pub fn loadMissingStoredKeys(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: *provider_mod.Keys, scope: StoredKeyScope) void {
+ if (builtin.os.tag == .macos) {
+ var futures = [_]?Io.Future(?[]u8){null} ** provider_specs.len;
+ for (provider_specs, keys.values, 0..) |spec, value, i| {
+ if (value != null or !scope.includes(i, spec.id)) continue;
+ const task_args = .{ io, gpa, home, spec.id };
+ futures[i] = io.concurrent(loadStoredKeyTask, task_args) catch
+ io.async(loadStoredKeyTask, task_args);
+ }
+ for (&futures, &keys.values, &keys.sources) |*maybe_future, *value, *source| {
+ const owned = if (maybe_future.*) |*future| future.await(io) orelse continue else continue;
+ value.* = arena.dupe(u8, owned) catch null;
+ gpa.free(owned);
+ if (value.* != null) source.* = .stored;
+ }
+ return;
+ }
+
+ const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ home, keys_file }) catch return;
+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024)) catch return;
+ const parsed = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return;
+ if (parsed != .object) return;
+ for (provider_specs, &keys.values, &keys.sources, 0..) |spec, *value, *source, i| {
+ if (value.* != null or !scope.includes(i, spec.id)) continue;
+ const stored = parsed.object.get(spec.id) orelse continue;
+ if (stored != .string or stored.string.len == 0) continue;
+ value.* = stored.string;
+ source.* = .stored;
+ }
+}
+
/// `harness key set <provider> <key>` / `harness key list` — manage the safe
/// key store. Validates the provider id against provider_specs.
pub fn keyCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, args: []const []const u8) !void {
@@ -161,9 +231,11 @@ pub fn keyCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, ar
const out = &ow.interface;
if (args.len == 0 or std.mem.eql(u8, args[0], "list")) {
+ var stored_keys: provider_mod.Keys = .{ .values = [_]?[]const u8{null} ** provider_specs.len };
+ loadMissingStoredKeys(io, gpa, arena, home, &stored_keys, .all);
try out.writeAll("provider env var stored\n");
for (provider_specs) |spec| {
- const stored = loadStoredKey(io, arena, home, spec.id) != null;
+ const stored = stored_keys.get(spec.id) != null;
try out.print(" {s:<14}{s:<22}{s}\n", .{ spec.id, spec.env_key, if (stored) "yes" else "—" });
}
try out.flush();
diff --git a/src/main.zig b/src/main.zig
index 0a88c3aa..5db6a1c2 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -19,6 +19,12 @@
const std = @import("std");
const Io = std.Io;
+fn bootMark(io: Io, started: Io.Timestamp, enabled: bool, label: []const u8) void {
+ if (!enabled) return;
+ const ms = @max(0, started.untilNow(io, .awake).toMilliseconds());
+ std.debug.print("[boot +{d}ms] {s}\n", .{ ms, label });
+}
+
/// #131: pre-load the shared HTTP client's CA bundle single-threaded, so the
/// parallel subagents that share this client (on pool threads) never race the
/// lazy CA-bundle rescan on their first concurrent HTTPS connect. Zig std flags
@@ -31,6 +37,14 @@ fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) voi
client.ca_bundle.rescan(gpa, io, now) catch return;
client.now = now;
}
+
+/// Warm the shared client's CA bundle off the launch critical path. Outbound
+/// users wait on `http.g_client_ready`, so the prompt can paint during this
+/// scan without reintroducing the concurrent first-connect race above.
+fn prewarmCaBundleTask(client: *std.http.Client, gpa: std.mem.Allocator, io: Io, ready: *Io.Event) void {
+ defer ready.set(io);
+ prewarmCaBundle(client, gpa, io);
+}
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const mcp = @import("mcp.zig");
@@ -251,6 +265,8 @@ const startup = @import("startup.zig");
const session_start = @import("session_start.zig");
const session_run = @import("session_run.zig");
pub fn main(init: std.process.Init) !void {
+ const boot_started = Io.Timestamp.now(init.io, .awake);
+ const boot_debug = init.environ_map.get("GRAFF_BOOT_DEBUG") != null;
const gpa = init.gpa;
const io = init.io;
const arena = init.arena.allocator();
@@ -269,6 +285,7 @@ pub fn main(init: std.process.Init) !void {
if (builtin.os.tag == .windows) tty.enableVtOutput();
// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.
const flags = try args.parse(init);
+ bootMark(init.io, boot_started, boot_debug, "args");
// GRAFF_CODEX_URL: override the codex responses endpoint (localhost mocks / integration tests). Parsed BEFORE subcommand dispatch and
// resolveKeys — `graff models [refresh]` fetches the catalog inside runSubcommand and the initial Keys.build runs inside resolveKeys.
// environ_map slices are process-lifetime (resolveKeys stores them into Keys the same way), so the value is kept as-is without duping.
@@ -280,6 +297,7 @@ pub fn main(init: std.process.Init) !void {
// Credential/model resolution (env vars → on-disk logins → `harness key set` store, env always wins; then --model or the last-saved model) lives
// in startup.zig as resolveKeys() — pure over env/disk/arena, safe to call outside main()'s own stack frame.
const resolved_keys = try startup.resolveKeys(io, gpa, arena, init.environ_map, flags.model_flag);
+ bootMark(io, boot_started, boot_debug, "credentials/model");
var keys = resolved_keys.keys;
const default_provider = resolved_keys.default_provider;
const stale_saved_model = resolved_keys.stale_saved_model;
@@ -287,7 +305,14 @@ pub fn main(init: std.process.Init) !void {
const codex_account = resolved_keys.codex_account;
var client: std.http.Client = .{ .allocator = gpa, .io = io };
defer client.deinit();
- prewarmCaBundle(&client, gpa, io);
+ var client_ready: Io.Event = .unset;
+ http.g_client_ready = &client_ready;
+ var client_warm_fut = io.async(prewarmCaBundleTask, .{ &client, gpa, io, &client_ready });
+ bootMark(io, boot_started, boot_debug, "CA warm scheduled");
+ defer {
+ _ = client_warm_fut.await(io);
+ http.g_client_ready = null;
+ }
var stdin_buf: [64 * 1024]u8 = undefined;
var stdin_reader = Io.File.stdin().reader(io, &stdin_buf);
const in = &stdin_reader.interface;
@@ -299,6 +324,7 @@ pub fn main(init: std.process.Init) !void {
if (try session_start.runTitleCommand(io, gpa, arena, &client, default_provider, out, flags)) return;
try session_start.setupWorktreeAndBanner(io, gpa, arena, init.environ_map, flags, out, trace_path, codex_account, stale_saved_model, preferred_provider, default_provider);
+ bootMark(io, boot_started, boot_debug, "banner");
// Session trace (best-effort: a failed open just disables tracing).
var trace_buf: [8 * 1024]u8 = undefined;
@@ -348,6 +374,7 @@ pub fn main(init: std.process.Init) !void {
// auto-connect only with --yolo (trusted) or explicit per-session consent; otherwise start with an empty (but live) registry so `/mcp add`
// still works.
var registry_storage = try session_start.initRegistryConsent(io, gpa, arena, out, in, flags, mcp_config_path, use_color, json_mode);
+ bootMark(io, boot_started, boot_debug, "MCP registry");
defer registry_storage.deinit();
const registry: ?*mcp.Registry = &registry_storage;
// Per-skill/companion opt-outs, animation/theme settings, and the --selftest-spinner headless render live in session_start.zig. The theme/
@@ -362,13 +389,16 @@ pub fn main(init: std.process.Init) !void {
out.flush() catch {};
};
if (theme_setup.should_exit) return;
+ bootMark(io, boot_started, boot_debug, "settings/theme");
try session_start.connectCompanion(io, &registry_storage, flags, out, json_mode);
const mcp_tools: []const mcp.Tool = registry_storage.tools;
// If the metered companion connected, probe its license once so the note below can lean into paid tools (vs the conservative free-codedb note).
if (mcpServerConnected(mcp_tools, "codedbpro")) g_codedbpro_licensed = probeCodedbproLicensed(gpa, io);
+ bootMark(io, boot_started, boot_debug, "companion");
var approvals: Approvals = undefined;
try session_run.initApprovalsHooksFleet(io, gpa, arena, init.environ_map, &approvals, flags, out, json_mode);
+ bootMark(io, boot_started, boot_debug, "approvals/hooks/fleet");
defer {
for (approvals.prefixes.items) |p| gpa.free(p);
approvals.prefixes.deinit(gpa);
@@ -390,6 +420,7 @@ pub fn main(init: std.process.Init) !void {
);
const sys_normal = sys_prompt.sys_normal;
const sys_strict = sys_prompt.sys_strict;
+ bootMark(io, boot_started, boot_debug, "system prompt");
var snaps: Snapshots = .{ .gpa = gpa, .io = io };
defer snaps.deinit();
@@ -398,20 +429,23 @@ 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, mcp_tools, &snaps, flags, telem.endpoint);
+ 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);
+ root.model_catalog = resolved_keys.model_catalog;
+ root.stored_keys_loaded = resolved_keys.stored_keys_loaded;
root.scratch_arena = &scratch_state; // #124: route the root's transient parse garbage here; reset per request()
root.fallback_active = stale_saved_model != null;
root.fallback_blocked = root.fallback_active and preferred_provider != null and !std.mem.eql(u8, preferred_provider.?, root.provider.id) and !fallback_config.contains(root.fallback_allow, root.provider.id);
+ bootMark(io, boot_started, boot_debug, "root agent");
defer joinElites(io); // reap if the session quits before any turn joins it
- session_run.saveOrResumeSession(&root, keys, arena, flags);
+ session_run.saveOrResumeSession(&root, &keys, arena, flags);
// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL agent loop — each prompt runs a full root turn (tools + MCP) via
// replTurnCb, reusing the root agent's tool set + registry + system prompt. Self-contained — exits after.
- if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, keys, &client, in, out, arena, flags)) return;
+ if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, &keys, &client, in, out, arena, flags)) return;
// One-shot print mode: run the single prompt to completion, print the final text to stdout, exit.
if (flags.oneshot_prompt) |prompt_text| {
- try session_run.runOneshotPrompt(gpa, io, arena, &root, keys, &tracer, out, prompt_text);
+ try session_run.runOneshotPrompt(gpa, io, arena, &root, &keys, &tracer, out, prompt_text);
return;
}
@@ -431,7 +465,7 @@ pub fn main(init: std.process.Init) !void {
root.tools_used.deinit(gpa);
}
const interactive = use_color and !json_mode; // stdout is a TTY → enable line editing
- try session_run.restoreResumedSession(arena, out, &root, keys, flags, json_mode, g_cwd_display);
+ try session_run.restoreResumedSession(arena, out, &root, &keys, flags, json_mode, g_cwd_display);
// The interactive-REPL / --json-protocol loop lives in mainloop.zig. main() keeps owning every piece of storage the loop touches (root, keys,
// tracer/traj/telem via root, history, linebuf, stdin/stdout writers) — Ctx below only holds POINTERS into this stack frame, so nothing dangles
diff --git a/src/mainloop.zig b/src/mainloop.zig
index d49bccfc..26f6d7f8 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -197,19 +197,24 @@ pub fn run(ctx: *Ctx) !void {
// {"type":"score","prompt_sha":"...","score":0.7,"notes":"..."}
// appends an evaluation record for an agent variant to the
// trajectory archive (the DGM evaluation phase writing back).
+ var json_request: ?std.json.Parsed(Value) = null;
+ defer if (json_request) |*request| request.deinit();
const base_msg: []const u8 = if (loop_prompt) |lp| lp else if (goal_prompt) |gp| gp else if (main_mod.json_mode) blk: {
- const parsed = std.json.parseFromSliceLeaky(Value, ctx.arena, line, .{ .allocate = .alloc_always }) catch {
+ json_request = std.json.parseFromSlice(Value, ctx.gpa, line, .{ .allocate = .alloc_if_needed }) catch {
ctx.root.emit(.{ .type = "error", .message = "invalid JSON (expect {\"type\":\"user\",\"text\":\"...\"})" });
continue;
};
+ const parsed = json_request.?.value;
const rtype = if (parsed == .object)
(if (parsed.object.get("type")) |v| (if (v == .string) v.string else "") else "")
else
"";
if (std.mem.eql(u8, rtype, "set_model")) {
+ ctx.root.ensureStoredKeys(ctx.keys);
const provider_field = if (parsed.object.get("provider")) |v| (if (v == .string) v.string else "") else "";
const model_field = if (parsed.object.get("model")) |v| (if (v == .string) v.string else "") else "";
const legacy_name = if (parsed.object.get("name")) |v| (if (v == .string) v.string else "") else "";
+ if (providers.controlRequestMayUseCodex(provider_field, model_field, legacy_name)) ctx.root.ensureModelCatalog(ctx.keys.*);
const provider = providers.resolveProviderControlRequest(ctx.keys, ctx.arena, provider_field, model_field, legacy_name) catch |err| {
const label = providers.setModelRequestLabel(ctx.arena, provider_field, model_field, legacy_name) catch "<requested model>";
const message = switch (err) {
@@ -221,7 +226,7 @@ pub fn run(ctx: *Ctx) !void {
ctx.root.emit(.{ .type = "error", .message = message });
continue;
};
- const note = providers.applyProvider(ctx.root, ctx.arena, provider);
+ const note = try providers.applyProvider(ctx.root, ctx.arena, provider);
ctx.root.emit(.{ .type = "model", .ok = true, .provider = provider.id, .model = provider.model, .context = provider.context, .note = note });
continue;
}
@@ -373,15 +378,18 @@ pub fn run(ctx: *Ctx) !void {
// model can see (otherwise it only gets the path and resorts to OCR).
vision.stageGuiImageAttachment(ctx.root, msg);
- // Generate the AI tab-title concurrently (io.async), spawned BEFORE the
- // header so the first-turn header can wait for the summary title. Applied
- // after the turn on the happy path (below); the defer is the fallback for
+ // Generate the AI tab-title concurrently, spawned BEFORE the header and
+ // root turn. `concurrent` guarantees an independent execution slot on
+ // supported Io backends; async preserves portability as the fallback.
+ // Applied after the turn on the happy path (below); the defer is the fallback for
// an interrupted/stalled/dropped/errored turn (those `continue` before the
// apply step) so the generated title is never silently discarded.
var title_fut: ?Io.Future(?[]const u8) = null;
if (!main_mod.json_mode and ctx.root.ai_title and !ctx.root.ai_title_done) {
ctx.root.ai_title_done = true;
- title_fut = ctx.io.async(title_mod.titleTask, .{ ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, base_msg });
+ const title_args = .{ ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, base_msg };
+ title_fut = ctx.io.concurrent(title_mod.titleTask, title_args) catch
+ ctx.io.async(title_mod.titleTask, title_args);
}
defer if (title_fut) |*f| {
applyAiTitle(ctx, f);
@@ -455,7 +463,11 @@ pub fn run(ctx: *Ctx) !void {
// A failed turn must never kill the session: ApiError is already
// reported inside request(); anything else is surfaced here. Either
// way we drop back to the prompt (or emit a JSON error/turn event).
- const turn_result = providers.runTurnWithFallback(ctx.root, ctx.keys.*, ctx.arena, ctx.out);
+ const turn_result = providers.runTurnWithFallback(ctx.root, ctx.keys, ctx.arena, ctx.out);
+ // No successful-path history mutation occurs between the trajectory,
+ // terminal event, and compaction gate. Reuse one full-history scan for
+ // all three instead of serializing an increasingly large history 3x.
+ const post_turn_context_tokens = ctx.root.effectiveContextTokens();
if (trace.g_traj) |tj| {
const fp = scoring.promptFingerprint(ctx.root.systemPrompt());
const turn_ms: i64 = @intCast(@max(0, turn_started.untilNow(ctx.io, .awake).toMilliseconds()));
@@ -474,7 +486,7 @@ pub fn run(ctx: *Ctx) !void {
.task = util.utf8Prefix(base_msg, 160),
.tools = turn_tools,
.ok = turn_ok,
- .context_tokens = ctx.root.effectiveContextTokens(),
+ .context_tokens = post_turn_context_tokens,
});
// Preserve the failure reason in the archive: the turn node only
// records ok:false, so an adjacent error record keeps the
@@ -593,16 +605,18 @@ pub fn run(ctx: *Ctx) !void {
else
final_text;
ctx.root.emit(.{ .type = "finalizing" });
- const context_tokens = ctx.root.effectiveContextTokens();
- ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = true, .metadata_complete = context_tokens > 0 });
+ const context_tokens = post_turn_context_tokens;
// #124: allocator-level leak telemetry (GRAFF_MEM_DEBUG=1) — arena
// capacity per turn separates a session-arena leak from gpa-side
- // growth, which OS-level RSS sampling can't tell apart.
+ // growth, which OS-level RSS sampling can't tell apart. Emit this
+ // before the terminal turn event so protocol bridges that stop at
+ // `complete:true` never strand a debug event for the next request.
if (main_mod.g_mem_debug) ctx.root.emit(.{
.type = "mem",
.session_arena_kb = if (main_mod.g_session_arena) |a| a.queryCapacity() / 1024 else 0,
.scratch_arena_kb = if (ctx.root.scratch_arena) |a| a.queryCapacity() / 1024 else 0,
});
+ ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = true, .metadata_complete = context_tokens > 0 });
}
// Apply the AI summary title + fleet champions that ran in the background
@@ -624,7 +638,7 @@ pub fn run(ctx: *Ctx) !void {
}
}
- const context_tokens = ctx.root.effectiveContextTokens();
+ const context_tokens = post_turn_context_tokens;
if (context_tokens >= ctx.root.provider.compactAt()) {
// Trim on failure only when we're genuinely against the window — at
// 80–95% a transient compaction failure can recover next turn.
diff --git a/src/models_cache.zig b/src/models_cache.zig
index 3d4cfecc..6d9a48fc 100644
--- a/src/models_cache.zig
+++ b/src/models_cache.zig
@@ -45,6 +45,25 @@ const codex_cache_ttl_ms: i64 = 5 * 60 * 1000;
const codex_client_version_floor = "0.144.1";
pub var codex_catalog_source: []const u8 = "baked offline fallback";
+/// Session-owned demand loader. Non-Codex launches keep the baked rows until
+/// a picker, switch, resume, or fallback can actually observe Codex models.
+/// The loader is invalidated after an in-session Codex login so the new
+/// account receives its own catalog before selection.
+pub const LazyCodexCatalog = struct {
+ codex_home: []const u8,
+ loaded: bool = false,
+
+ pub noinline fn ensure(self: *LazyCodexCatalog, io: Io, gpa: Allocator, arena: Allocator, home: []const u8, token: []const u8, account: []const u8) void {
+ if (self.loaded) return;
+ loadCodexCatalog(io, gpa, arena, home, self.codex_home, token, account, false);
+ self.loaded = true;
+ }
+
+ pub fn invalidate(self: *LazyCodexCatalog) void {
+ self.loaded = false;
+ }
+};
+
/// models.dev provider ids to trust FIRST when a model id appears under
/// several providers — a vendor's own listing beats a reseller's markup
/// (models.dev keys resellers like requesty/openrouter/vercel alongside the
@@ -573,6 +592,16 @@ test "numField reads int and float JSON numbers; u64Field clamps" {
try std.testing.expectEqual(@as(u64, 0), u64Field(v.object, "missing"));
}
+test "lazy Codex catalog can be invalidated after account changes" {
+ const previous_source = codex_catalog_source;
+ defer codex_catalog_source = previous_source;
+ var catalog: LazyCodexCatalog = .{ .codex_home = "" };
+ catalog.ensure(std.testing.io, std.testing.allocator, std.testing.allocator, "", "", "");
+ try std.testing.expect(catalog.loaded);
+ catalog.invalidate();
+ try std.testing.expect(!catalog.loaded);
+}
+
test "findModel prefers the canonical vendor over a reseller markup" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
diff --git a/src/picker_auth.zig b/src/picker_auth.zig
index 88f56973..d89de330 100644
--- a/src/picker_auth.zig
+++ b/src/picker_auth.zig
@@ -17,6 +17,7 @@ const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const command_catalog = @import("command_catalog.zig");
+const pricing = @import("pricing.zig");
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
@@ -62,6 +63,8 @@ pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id:
}
}
}
+ if (std.mem.eql(u8, provider_id, "codex") and keys.get("codex") != null)
+ root.reloadModelCatalog(keys.*);
}
/// Read an API key without terminal echo or history persistence. The ordinary
@@ -109,6 +112,7 @@ pub fn offerProviderAuth(
out: *Io.Writer,
pid: []const u8,
model: []const u8,
+ default_selection: bool,
use_color: bool,
pick: PickerFn,
) !void {
@@ -205,7 +209,11 @@ pub fn offerProviderAuth(
}
// Auth done — switch now if the key/login took, else keep the current model.
- const provider = keys.providerById(pid, model) catch {
+ const selected_model = if (default_selection and std.mem.eql(u8, pid, "codex"))
+ pricing.providerDefaultModel(pid, provider_specs[si].default_model)
+ else
+ model;
+ const provider = keys.providerById(pid, selected_model) catch {
try out.print("still no usable key for {s} — kept {s}{s}{s}\n", .{ pid, style.cyan, root.provider.model, style.reset });
try out.flush();
return;
diff --git a/src/pickers.zig b/src/pickers.zig
index ca934dcf..f15cd0e4 100644
--- a/src/pickers.zig
+++ b/src/pickers.zig
@@ -490,8 +490,8 @@ pub const reloadLoginKey = picker_auth.reloadLoginKey;
/// When a model's provider has no key, offer OAuth login or key entry and then
/// switch to that model. The helper owns authentication while this module owns
/// the picker callback and the live color/TTY mode.
-pub fn offerProviderAuth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer, pid: []const u8, model: []const u8) !void {
- try picker_auth.offerProviderAuth(root, keys, arena, out, pid, model, main_mod.use_color, listPicker);
+pub fn offerProviderAuth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer, pid: []const u8, model: []const u8, default_selection: bool) !void {
+ try picker_auth.offerProviderAuth(root, keys, arena, out, pid, model, default_selection, main_mod.use_color, listPicker);
}
// Tests moved from main.zig alongside the functions they cover (#123 split).
diff --git a/src/providers.zig b/src/providers.zig
index 3d5f18a2..fe842e73 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -69,7 +69,7 @@ fn translateHistory(arena: Allocator, msgs: *std.json.Array, to_kind: Provider.K
msgs.* = out;
}
-fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool) []const u8 {
+fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool) ![]const u8 {
const same_format = root.provider.kind == p.kind;
const same_selection = same_format and
root.provider.context == p.context and
@@ -89,6 +89,9 @@ fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool
}
}
root.provider = p;
+ // Keep the context estimate and first request exact without eagerly
+ // materializing formats this session has never used.
+ try root.ensureRootTools(p.kind);
// #204: an actual provider/model switch changes the window and tokenizer, so
// re-estimate until the next response returns real usage. A no-op set_model is
// common in the GUI prompt-settings path; preserve its authoritative server
@@ -109,13 +112,13 @@ fn applyProviderInner(root: *Agent, arena: Allocator, p: Provider, persist: bool
}
/// An explicit /model or set_model selection becomes the next-launch default.
-pub fn applyProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
+pub fn applyProvider(root: *Agent, arena: Allocator, p: Provider) ![]const u8 {
return applyProviderInner(root, arena, p, true);
}
/// Automatic failover is session-local: preserve the user's saved preference
/// so a repaired credential/model is tried again on the next fresh launch.
-pub fn applyFallbackProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
+pub fn applyFallbackProvider(root: *Agent, arena: Allocator, p: Provider) ![]const u8 {
return applyProviderInner(root, arena, p, false);
}
@@ -192,7 +195,7 @@ pub fn failoverEligible(detail: []const u8) bool {
/// credential-backed providers on a clear auth/model/quota failure. Successful
/// fallback becomes active for this session but does not replace the saved
/// model preference.
-pub fn runTurnWithFallback(root: *Agent, keys: Keys, arena: Allocator, out: ?*Io.Writer) anyerror![]const u8 {
+pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*Io.Writer) anyerror![]const u8 {
if (root.fallback_blocked) return error.FallbackConsentRequired;
var attempted: [provider_specs.len][]const u8 = undefined;
var attempted_len: usize = 1;
@@ -207,10 +210,15 @@ pub fn runTurnWithFallback(root: *Agent, keys: Keys, arena: Allocator, out: ?*Io
if (!failoverEligible(detail)) return err;
const failed_id = root.provider.id;
const failed_model = root.provider.model;
- const fallback = nextFallbackProvider(keys, failed_id, attempted[0..attempted_len], root.fallback_allow) orelse return err;
+ root.ensureStoredKeys(keys);
+ var fallback = nextFallbackProvider(keys.*, failed_id, attempted[0..attempted_len], root.fallback_allow) orelse return err;
+ if (std.mem.eql(u8, fallback.id, "codex")) {
+ root.ensureModelCatalog(keys.*);
+ fallback = nextFallbackProvider(keys.*, failed_id, attempted[0..attempted_len], root.fallback_allow) orelse return err;
+ }
attempted[attempted_len] = fallback.id;
attempted_len += 1;
- const note = applyFallbackProvider(root, arena, fallback);
+ const note = try applyFallbackProvider(root, arena, fallback);
if (main_mod.json_mode) {
root.emit(.{ .type = "model", .ok = true, .provider = fallback.id, .model = fallback.model, .context = fallback.context, .note = "automatic session fallback; saved model preference kept" });
} else if (out) |w| {
@@ -264,6 +272,30 @@ pub fn resolveProviderControlRequest(
return resolveProviderRequest(keys, arena, legacy_name);
}
+/// Whether a human `/model` query can observe account-scoped Codex rows.
+/// Explicit non-Codex providers never need the dynamic catalog; bare/fuzzy
+/// model queries do because they may name a new account rollout.
+pub fn modelQueryMayUseCodex(query: []const u8) bool {
+ const arg = std.mem.trim(u8, query, " \t");
+ if (arg.len == 0) return true;
+ const provider_end = std.mem.indexOfAny(u8, arg, " /\t") orelse arg.len;
+ const provider_id = arg[0..provider_end];
+ for (provider_specs) |spec| {
+ if (!std.mem.eql(u8, spec.id, provider_id)) continue;
+ return std.mem.eql(u8, spec.id, "codex");
+ }
+ return true;
+}
+
+/// Structured set_model has separate provider/model fields. An explicit
+/// provider fully determines routing; a model-only request remains fuzzy.
+pub fn controlRequestMayUseCodex(provider_query: []const u8, model_query: []const u8, legacy_name: []const u8) bool {
+ const provider_id = std.mem.trim(u8, provider_query, " \t");
+ if (provider_id.len != 0) return std.mem.eql(u8, provider_id, "codex");
+ if (std.mem.trim(u8, model_query, " \t").len != 0) return true;
+ return modelQueryMayUseCodex(legacy_name);
+}
+
fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Provider {
const arg = std.mem.trim(u8, query, " \t");
if (arg.len == 0) return error.InvalidModelRequest;
@@ -304,7 +336,7 @@ pub fn setModelRequestLabel(arena: Allocator, provider_query: []const u8, model_
}
pub fn switchProvider(root: *Agent, arena: Allocator, p: Provider, out: *Io.Writer) !void {
- const note = applyProvider(root, arena, p);
+ const note = try applyProvider(root, arena, p);
try out.print("switched to {s} via {s} ({t} format, {d}k ctx) — {s} · saved for next session\n", .{
p.model, p.id, p.kind, p.context / 1000, note,
});
@@ -380,11 +412,15 @@ test "applyProviderInner preserves the server meter on an exact model re-selecti
var root: Agent = undefined;
root.provider = p;
+ root.arena = a;
+ root.registry = null;
root.messages = std.json.Array.init(a);
root.sub = false;
root.strict = false;
root.sys_normal = "";
root.sys_strict = "";
+ root.tools_anthropic = "";
+ root.tools_openai = "";
root.tools_responses = "";
root.keep_context = true;
root.last_context_tokens = 220_000;
@@ -393,7 +429,10 @@ test "applyProviderInner preserves the server meter on an exact model re-selecti
root.cap_new = true;
root.effort_rejected = true;
root.ws_off = true;
- _ = applyProviderInner(&root, a, p, false);
+ _ = try applyProviderInner(&root, a, p, false);
+ try std.testing.expect(root.tools_responses.len > 0);
+ try std.testing.expectEqual(@as(usize, 0), root.tools_anthropic.len);
+ try std.testing.expectEqual(@as(usize, 0), root.tools_openai.len);
try std.testing.expectEqual(@as(u64, 220_000), root.last_context_tokens);
try std.testing.expectEqual(@as(u64, 12_345), root.last_cache_read);
try std.testing.expect(root.cap_new);
@@ -402,13 +441,22 @@ test "applyProviderInner preserves the server meter on an exact model re-selecti
var changed = p;
changed.model = "gpt-5.1";
- _ = applyProviderInner(&root, a, changed, false);
+ _ = try applyProviderInner(&root, a, changed, false);
try std.testing.expectEqual(root.fullRequestEstimateTokens(), root.last_context_tokens);
try std.testing.expectEqual(root.last_context_tokens, root.context_local_tokens);
try std.testing.expectEqual(@as(u64, 0), root.last_cache_read);
try std.testing.expect(!root.cap_new);
try std.testing.expect(!root.effort_rejected);
try std.testing.expect(!root.ws_off);
+
+ var changed_format = changed;
+ changed_format.id = "deepseek";
+ changed_format.kind = .openai;
+ changed_format.model = "deepseek-chat";
+ _ = try applyProviderInner(&root, a, changed_format, false);
+ try std.testing.expect(root.tools_openai.len > 0);
+ try std.testing.expect(root.tools_responses.len > 0); // already paid for, remains cached
+ try std.testing.expectEqual(@as(usize, 0), root.tools_anthropic.len);
}
test "set_model control resolves explicit provider/model fields" {
@@ -431,6 +479,19 @@ test "set_model control resolves explicit provider/model fields" {
try std.testing.expectEqualStrings("user-loaded/model", local.model);
}
+test "Codex catalog demand follows model request routing" {
+ try std.testing.expect(modelQueryMayUseCodex(""));
+ try std.testing.expect(!modelQueryMayUseCodex("deepseek"));
+ try std.testing.expect(!modelQueryMayUseCodex("deepseek/deepseek-chat"));
+ try std.testing.expect(modelQueryMayUseCodex("codex"));
+ try std.testing.expect(modelQueryMayUseCodex("codex future-sol"));
+ try std.testing.expect(modelQueryMayUseCodex("future-account-rollout"));
+ try std.testing.expect(!controlRequestMayUseCodex("codegraff", "deepseek-v4-pro", ""));
+ try std.testing.expect(controlRequestMayUseCodex("codex", "", ""));
+ try std.testing.expect(controlRequestMayUseCodex("", "future-account-rollout", ""));
+ try std.testing.expect(!controlRequestMayUseCodex("", "", "openai"));
+}
+
test "extractText: string content, joined text blocks, and empties" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/readline.zig b/src/readline.zig
index 2856c3b2..dff25c84 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -156,17 +156,14 @@ pub fn readLine(
out.writeAll("\x1b[6n") catch {};
out.flush() catch {};
dsr: {
- var polls: usize = 0;
var esc: [16]u8 = undefined;
var n: usize = 0;
var in_esc = false;
while (true) {
- if (in.buffered().len == 0 and !inputPending()) { // 50ms poll
- polls += 1;
- if (polls >= 10) break :dsr; // no reply in ~500ms: fall back
- // to column 1 — a later reply is still adopted (CSI 'R').
- continue;
- }
+ // A local terminal answers DSR in a few milliseconds. Do not hold
+ // every prompt for 500ms when a multiplexer drops/delays it: the
+ // main loop's CSI 'R' arm adopts a late reply without losing layout.
+ if (in.buffered().len == 0 and !inputPendingTimed(20)) break :dsr;
const b = in.takeByte() catch break :dsr;
if (!in_esc) {
if (b == 0x1b) {
@@ -461,7 +458,7 @@ pub fn readLine(
redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);
},
'R' => { // late DSR cursor-position reply (slow or
- // multiplexed terminal missed the 500ms startup
+ // multiplexed terminal missed the 20ms startup
// window): adopt the real input column so the
// horizontal window stays exact instead of the
// column-1 fallback. Same narrow-terminal policy as
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 799de049..c807c272 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -304,7 +304,7 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
c.fallback_active = agent.fallback_active;
c.fallback_blocked = agent.fallback_blocked;
}
- const final = providers.runTurnWithFallback(&agent, c.keys, arena, &sink.writer) catch |err| switch (err) {
+ const final = providers.runTurnWithFallback(&agent, &c.keys, arena, &sink.writer) catch |err| switch (err) {
// A mid-stream stall (#134): the repl turn IS live (stream_quiet=false),
// so postStream can return error.StreamStalled. Don't collapse it to
// null — the pane renders that as "model call failed — check /model and
diff --git a/src/schema.zig b/src/schema.zig
index b735faf9..16d8474f 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -216,6 +216,21 @@ const workflow_spec = ToolSpec{
pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec };
+// The common catalog (clock_sleep off) is static too. Previously every root
+// startup allocated and filled a filtered ToolSpec array before rendering even
+// one provider catalog.
+const root_specs_without_clock = blk: {
+ var out: [root_specs.len - 1]ToolSpec = undefined;
+ var len: usize = 0;
+ for (root_specs) |tool| {
+ if (std.mem.eql(u8, tool.name, "clock_sleep")) continue;
+ out[len] = tool;
+ len += 1;
+ }
+ if (len != out.len) @compileError("root tool catalog must contain exactly one clock_sleep entry");
+ break :blk out;
+};
+
pub fn isMetaName(name: []const u8) bool {
return std.mem.eql(u8, name, "todo_write") or
std.mem.eql(u8, name, "todo_read") or
@@ -292,12 +307,9 @@ pub fn renderRootTools(
/// build their tool lists from base_specs only (tools_*_sub above), which
/// never included meta_specs/clock_sleep in the first place.
pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {
+ _ = arena;
if (root.g_clock_sleep) return &root_specs;
- var out: std.ArrayList(ToolSpec) = .empty;
- for (root_specs) |t| {
- if (!std.mem.eql(u8, t.name, "clock_sleep")) try out.append(arena, t);
- }
- return out.items;
+ return &root_specs_without_clock;
}
const Schema = union(enum) { raw: []const u8, value: Value };
@@ -504,6 +516,7 @@ test "effectiveRootSpecs: drops clock_sleep from the root tool catalog unless th
const off_specs = try effectiveRootSpecs(a);
try std.testing.expectEqual(root_specs.len - 1, off_specs.len);
for (off_specs) |t| try std.testing.expect(!std.mem.eql(u8, t.name, "clock_sleep"));
+ try std.testing.expectEqual(@as(usize, 0), arena_state.queryCapacity());
root.g_clock_sleep = true;
const on_specs = try effectiveRootSpecs(a);
diff --git a/src/serde.zig b/src/serde.zig
index 569e3409..03c88076 100644
--- a/src/serde.zig
+++ b/src/serde.zig
@@ -14,6 +14,8 @@ const util = @import("util.zig");
const history_file = ".simple-harness-history";
const model_file = ".simple-harness-model"; // remembers the last-selected provider+model
+pub const SavedModel = struct { pid: []const u8, model: []const u8 };
+
/// Persist the active provider+model so the next launch starts on it.
pub fn saveModel(io: Io, home: []const u8, pid: []const u8, model: []const u8) void {
if (home.len == 0) return;
@@ -28,7 +30,7 @@ pub fn saveModel(io: Io, home: []const u8, pid: []const u8, model: []const u8) v
}
/// Load the remembered provider+model (pid on line 1, model on line 2).
-pub fn loadModel(io: Io, arena: Allocator, home: []const u8) ?struct { pid: []const u8, model: []const u8 } {
+pub fn loadModel(io: Io, arena: Allocator, home: []const u8) ?SavedModel {
if (home.len == 0) return null;
const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ home, model_file }) catch return null;
const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(4096)) catch return null;
diff --git a/src/session.zig b/src/session.zig
index 1b562d8f..f37f5664 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -245,6 +245,11 @@ pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {
if (root.session_title) |title| try s.write(title) else try s.write(sessionTitle(root));
try s.objectField("updated_ms");
try s.write(unixMs(root.io));
+ try s.objectField("messages");
+ const messages_start = aw.writer.buffered().len;
+ try s.write(Value{ .array = root.messages });
+ const messages_bytes = aw.writer.buffered().len - messages_start;
+ const context_estimate = root.contextEstimateFromInputBytes(messages_bytes);
// Preserve the last authoritative provider reading across resume. Responses
// histories can contain compact encrypted-reasoning handles whose serialized
// byte size substantially underestimates their server-side token cost; without
@@ -253,14 +258,12 @@ pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {
// std.json.Value represents parsed integers as i64, so keep the persisted
// value inside the range loadSession can round-trip even if a malformed
// provider once reported an extreme unsigned count.
- try s.write(@min(root.effectiveContextTokens(), @as(u64, std.math.maxInt(i64))));
+ try s.write(@min(context_estimate.effective, @as(u64, std.math.maxInt(i64))));
// Pair the provider reading with the locally measurable request component.
// On resume we can preserve only their hidden-token delta while replacing
// this component with today's prompt/tool-schema estimate.
try s.objectField("context_local_tokens");
- try s.write(@min(root.fullRequestEstimateTokens(), @as(u64, std.math.maxInt(i64))));
- try s.objectField("messages");
- try s.write(Value{ .array = root.messages });
+ try s.write(@min(context_estimate.local, @as(u64, std.math.maxInt(i64))));
try s.endObject();
Io.Dir.cwd().createDir(root.io, ".graff", .default_dir) catch {};
@@ -351,7 +354,7 @@ fn restoreContextMeter(root: *Agent, saved_context_tokens: u64, saved_local_toke
/// Restore a saved session: parse the file (arena-owned), rebuild the
/// provider, and replace the live history. The wire format must still match
/// the restored provider's kind — same provider id guarantees it.
-pub fn loadSession(root: *Agent, keys: Keys, arena: Allocator, name: []const u8) !void {
+pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8) !void {
const path = try sessionPath(arena, name);
const data = Io.Dir.cwd().readFileAlloc(root.io, path, arena, .limited(8 * 1024 * 1024)) catch blk: {
// backward-compat: older builds wrote <name>.session.json in cwd.
@@ -374,7 +377,13 @@ pub fn loadSession(root: *Agent, keys: Keys, arena: Allocator, name: []const u8)
const saved_context_tokens = contextTokensFromSession(obj);
const saved_local_tokens = contextLocalTokensFromSession(obj);
+ root.ensureStoredKeys(keys);
+ if (std.mem.eql(u8, pid, "codex")) root.ensureModelCatalog(keys.*);
root.provider = try keys.providerById(pid, model);
+ // A resumed session may use a different wire format than the startup
+ // default. Materialize that catalog before rebasing its saved context
+ // meter, and keep every still-unused format lazy.
+ try root.ensureRootTools(root.provider.kind);
root.messages = msgs;
// Repair histories written by older builds where a Responses
// `function_call_output.output` was persisted as a byte array instead of a
diff --git a/src/session_run.zig b/src/session_run.zig
index cf46a60a..724ccd2a 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -52,7 +52,6 @@ const messages_mod = @import("messages.zig");
const session = @import("session.zig");
const fleet = @import("fleet.zig");
const hooks = @import("hooks.zig");
-const schema = @import("schema.zig");
/// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL
/// agent loop — each prompt runs a full root turn (tools + MCP) via
@@ -61,12 +60,19 @@ const schema = @import("schema.zig");
/// `root` is already a stable, fully-constructed main()-owned Agent by the
/// time this is called, so taking its address here is safe (this helper
/// only reads through the pointer, it never owns or returns Agent storage).
-pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {
+pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {
if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "repl"))) return false;
+ root.ensureStoredKeys(keys);
+ root.ensureModelCatalog(keys.*);
+ // The standalone chat REPL can switch wire formats inside its own model
+ // picker, so materialize every catalog only when this surface is entered.
+ try root.ensureRootTools(.anthropic);
+ try root.ensureRootTools(.openai);
+ try root.ensureRootTools(.responses);
var repl_ctx = repl_glue.ReplCtx{
.io = io,
.client = client,
- .keys = keys,
+ .keys = keys.*,
.home = root.home,
.provider = root.provider,
.fallback_allow = root.fallback_allow,
@@ -97,7 +103,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent
/// denies anything not pre-approved instead of prompting (there's no one to
/// ask). Moved out of main() verbatim (600-line goal); `root`/`tracer` are
/// already stable main()-owned storage by the time this runs.
-pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mod.Agent, keys: provider_mod.Keys, tracer: *trace.Tracer, out: *Io.Writer, prompt_text: []const u8) !void {
+pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mod.Agent, keys: *provider_mod.Keys, tracer: *trace.Tracer, out: *Io.Writer, prompt_text: []const u8) !void {
main_mod.unattended = true;
root.in = null; // gate: deny instead of prompt; ask_user: self-decide
root.out = null; // tool progress → stderr; stdout carries only the answer
@@ -195,14 +201,10 @@ pub fn buildRootAgent(
tracer: *trace.Tracer,
sys_normal: []const u8,
sys_strict: []const u8,
- mcp_tools: []const mcp.Tool,
snaps: *tools_mod.Snapshots,
flags: args.Flags,
telem_endpoint: []const u8,
) !agent_mod.Agent {
- // #225: clock_sleep only appears in the model's tool catalog when the
- // root-only feature flag is on (--clock-sleep / GRAFF_CLOCK_SLEEP=1).
- const root_tool_specs = try schema.effectiveRootSpecs(arena);
var root: agent_mod.Agent = .{
.snapshots = snaps,
.gpa = gpa,
@@ -221,10 +223,13 @@ pub fn buildRootAgent(
.tracer = tracer,
.sys_normal = sys_normal,
.sys_strict = sys_strict,
- .tools_anthropic = try schema.renderRootTools(arena, .anthropic, root_tool_specs, mcp_tools),
- .tools_openai = try schema.renderRootTools(arena, .openai, root_tool_specs, mcp_tools),
- .tools_responses = try schema.renderRootTools(arena, .responses, root_tool_specs, mcp_tools),
+ .tools_anthropic = "",
+ .tools_openai = "",
+ .tools_responses = "",
};
+ // Startup pays for one provider format, not all three. Other formats are
+ // rendered on first switch with the same built-in + live MCP inputs.
+ try root.ensureRootTools(default_provider.kind);
const fresh_session_name = try std.fmt.allocPrint(arena, "session-{d}", .{util.unixMs(io)});
root.session_name = if (flags.resume_flag) |name| (if (!flags.new_session_flag and !flags.no_resume_flag) name else fresh_session_name) else fresh_session_name;
repl_glue.loadThinkingSettings(io, arena, &root); // {"effort":...,"fast":...} persisted by /effort and /fast
@@ -251,7 +256,7 @@ pub fn buildRootAgent(
/// resume-target reload for a resumed one-shot. Moved out of main() verbatim
/// (600-line goal). Both are best-effort (`catch {}`), matching main()'s
/// former inline behavior exactly.
-pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: provider_mod.Keys, arena: Allocator, flags: args.Flags) void {
+pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocator, flags: args.Flags) void {
const will_resume = flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag;
if (!will_resume) session.saveSession(root, arena, root.session_name) catch {};
if (flags.oneshot_prompt != null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag) {
@@ -265,7 +270,7 @@ pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: provider_mod.Keys, aren
/// as what would trigger live compaction, summarizes up front instead of
/// re-billing the whole thing on the first turn. Moved out of main()
/// verbatim (600-line goal); `root` is already stable main()-owned storage.
-pub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, keys: provider_mod.Keys, flags: args.Flags, json_mode: bool, cwd_display: []const u8) !void {
+pub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, keys: *provider_mod.Keys, flags: args.Flags, json_mode: bool, cwd_display: []const u8) !void {
if (!(flags.oneshot_prompt == null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag)) return;
if (session.loadSession(root, keys, arena, root.session_name)) |_| {
if (root.messages.items.len > 0) {
diff --git a/src/startup.zig b/src/startup.zig
index 8c01186d..993c7577 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -43,8 +43,98 @@ pub const ResolvedKeys = struct {
stale_saved_model: ?[]const u8,
preferred_provider: ?[]const u8,
codex_account: ?[]const u8,
+ model_catalog: models_cache.LazyCodexCatalog,
+ stored_keys_loaded: bool,
};
+fn explicitProvider(model_flag: ?[]const u8) ?[]const u8 {
+ const query = model_flag orelse return null;
+ for (provider_mod.provider_specs) |spec|
+ if (std.mem.eql(u8, spec.id, query)) return spec.id;
+ return null;
+}
+
+/// Whether one stored credential can affect an explicit startup selection.
+/// Provider ids need one key; exact catalog model names need only providers
+/// that serve that model. Aliases/fuzzy queries retain the full scan because
+/// key availability participates in their tie-break.
+fn storedKeyMayAffectSelection(provider_id: []const u8, model_flag: ?[]const u8) bool {
+ const query = model_flag orelse return true;
+ if (explicitProvider(query)) |id| return std.mem.eql(u8, provider_id, id);
+ if (pricing.modelInTable(query)) return pricing.providerModelInTable(provider_id, query);
+ return true;
+}
+
+fn hasSelectiveStoredKeyScope(model_flag: ?[]const u8) bool {
+ const query = model_flag orelse return false;
+ return explicitProvider(query) != null or pricing.modelInTable(query);
+}
+
+fn startupStoredKeyScope(model_flag: ?[]const u8, selective: bool) keys_cli.StoredKeyScope {
+ if (!selective) return .all;
+ var mask = [_]bool{false} ** provider_mod.provider_specs.len;
+ for (provider_mod.provider_specs, 0..) |spec, i|
+ mask[i] = storedKeyMayAffectSelection(spec.id, model_flag);
+ return .{ .mask = mask };
+}
+
+fn startupNeedsCodexCatalog(keys: provider_mod.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) bool {
+ if (keys.get("codex") == null) return false;
+ if (model_flag) |query| {
+ for (provider_mod.provider_specs) |spec| if (std.mem.eql(u8, spec.id, query))
+ return std.mem.eql(u8, spec.id, "codex");
+ // A free-form query may name an account-only rollout.
+ return true;
+ }
+ if (saved) |selection| {
+ if (std.mem.eql(u8, selection.pid, "codex")) return true;
+ if (pricing.providerModelInTable(selection.pid, selection.model) and keys.get(selection.pid) != null) return false;
+ // A stale/keyless preference may fall through to Codex.
+ return true;
+ }
+ const fallback = keys.defaultProvider() catch return false;
+ return std.mem.eql(u8, fallback.id, "codex");
+}
+
+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);
+ try std.testing.expect(explicitProvider(null) == null);
+ try std.testing.expect(hasSelectiveStoredKeyScope("deepseek-v4-pro"));
+ try std.testing.expect(storedKeyMayAffectSelection("codegraff", "deepseek-v4-pro"));
+ try std.testing.expect(storedKeyMayAffectSelection("deepseek", "deepseek-v4-pro"));
+ try std.testing.expect(!storedKeyMayAffectSelection("anthropic", "deepseek-v4-pro"));
+ try std.testing.expect(storedKeyMayAffectSelection("anthropic", "opus"));
+ try std.testing.expect(storedKeyMayAffectSelection("openai", null));
+ const exact_scope = startupStoredKeyScope("deepseek-v4-pro", true);
+ try std.testing.expect(exact_scope.includes(1, "codegraff"));
+ try std.testing.expect(exact_scope.includes(2, "deepseek"));
+ try std.testing.expect(!exact_scope.includes(0, "anthropic"));
+
+ var keys: provider_mod.Keys = .{ .values = [_]?[]const u8{null} ** provider_mod.provider_specs.len };
+ for (provider_mod.provider_specs, &keys.values) |spec, *value| {
+ if (std.mem.eql(u8, spec.id, "deepseek") or std.mem.eql(u8, spec.id, "codex")) value.* = "test";
+ }
+ keys.codex_account = "account";
+
+ try std.testing.expect(!startupNeedsCodexCatalog(keys, "deepseek", null));
+ try std.testing.expect(startupNeedsCodexCatalog(keys, "codex", null));
+ try std.testing.expect(startupNeedsCodexCatalog(keys, "future-account-rollout", null));
+ try std.testing.expect(!startupNeedsCodexCatalog(keys, null, .{ .pid = "deepseek", .model = "deepseek-v4-pro" }));
+ try std.testing.expect(!startupNeedsCodexCatalog(keys, null, null));
+
+ for (provider_mod.provider_specs, &keys.values) |spec, *value| {
+ if (std.mem.eql(u8, spec.id, "deepseek")) value.* = null;
+ }
+ try std.testing.expect(startupNeedsCodexCatalog(keys, null, null));
+ try std.testing.expect(startupNeedsCodexCatalog(keys, null, .{ .pid = "deepseek", .model = "deepseek-v4-pro" }));
+
+ for (provider_mod.provider_specs, &keys.values) |spec, *value| {
+ if (std.mem.eql(u8, spec.id, "codex")) value.* = null;
+ }
+ try std.testing.expect(!startupNeedsCodexCatalog(keys, "codex", null));
+}
+
/// Resolves API keys/credentials (env vars → codegraff/codex/kimi on-disk
/// logins → the `harness key set` store, env always wins — same precedence
/// as before) and picks the startup model (--model flag, else the
@@ -108,36 +198,35 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
}
}
}
- // Stored keys (macOS Keychain / 0600 file via `harness key set`): fill any
- // provider slot still empty after env + the login loaders. env always wins.
+ // An explicit provider or exact catalog model can observe only its
+ // candidate providers. Load those stored keys now; model/fallback/resume
+ // surfaces fill the rest on demand. Aliases/default startup still need all
+ // keys because availability participates in their routing tie-break.
+ const selective_stored_keys = hasSelectiveStoredKeyScope(model_flag);
+ var stored_keys_loaded = !selective_stored_keys;
if (keys_cli.homeEnv(environ_map)) |home| {
- for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {
- if (value.* == null) {
- if (keys_cli.loadStoredKey(io, arena, home, spec.id)) |key| {
- value.* = key;
- source.* = .stored;
- }
+ if (selective_stored_keys) {
+ keys_cli.loadMissingStoredKeys(io, gpa, arena, home, &keys, startupStoredKeyScope(model_flag, true));
+ // Preserve the old diagnostics/fallback behavior when none of the
+ // selective candidates has any credential: only failed launches
+ // pay for the exhaustive scan.
+ if (keys.defaultProvider()) |_| {} else |_| {
+ keys_cli.loadMissingStoredKeys(io, gpa, arena, home, &keys, .all);
+ stored_keys_loaded = true;
}
- }
+ } else keys_cli.loadMissingStoredKeys(io, gpa, arena, home, &keys, .all);
}
- // Discover the account-scoped Codex catalog before model selection. This
- // mirrors openai/codex: 5-minute cache keyed by installed Codex version,
- // authenticated /models refresh, then stale/native/baked offline fallback.
- // Model names, rollout visibility, and context windows therefore do not
- // need a graff release. No Codex login/cache → the baked fallback remains.
- if (keys_cli.homeEnv(environ_map)) |home| {
- const codex_home = environ_map.get("CODEX_HOME") orelse
- (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");
- models_cache.loadCodexCatalog(
- io,
- gpa,
- arena,
- home,
- codex_home,
- keys.get("codex") orelse "",
- keys.codex_account,
- false,
- );
+ const home = keys_cli.homeEnv(environ_map) orelse "";
+ const codex_home = environ_map.get("CODEX_HOME") orelse
+ (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");
+ var model_catalog: models_cache.LazyCodexCatalog = .{ .codex_home = codex_home };
+ const saved_model: ?serde.SavedModel = if (model_flag == null) serde.loadModel(io, arena, home) else null;
+ // Dynamic Codex discovery is observable only when startup may select
+ // Codex. Explicit/saved non-Codex launches defer the version subprocess,
+ // native-cache parse, and possible refresh until a model surface needs it.
+ if (startupNeedsCodexCatalog(keys, model_flag, saved_model))
+ model_catalog.ensure(io, gpa, arena, home, keys.get("codex") orelse "", keys.codex_account);
+ if (home.len != 0) {
// Apply the independent models.dev price/context overlay after routing
// discovery. Provider-specific Codex windows remain authoritative.
models_cache.loadOverlay(io, arena, home);
@@ -164,7 +253,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
};
const nm = pricing.resolveModelName(keys, mname) orelse std.process.fatal("unknown --model '{s}' — run `graff models refresh` or see /models", .{mname});
default_provider = keys.providerFor(nm) catch std.process.fatal("no key/login for --model '{s}' — see /models", .{mname});
- } else if (serde.loadModel(io, arena, keys_cli.homeEnv(environ_map) orelse "")) |saved| {
+ } else if (saved_model) |saved| {
preferred_provider = saved.pid;
// No --model flag: resume the model chosen last session only if that
// exact provider/model pair is still in the catalog; model names can be
@@ -188,7 +277,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp
}
}
}
- return .{ .keys = keys, .default_provider = default_provider, .stale_saved_model = stale_saved_model, .preferred_provider = preferred_provider, .codex_account = codex_account };
+ return .{ .keys = keys, .default_provider = default_provider, .stale_saved_model = stale_saved_model, .preferred_provider = preferred_provider, .codex_account = codex_account, .model_catalog = model_catalog, .stored_keys_loaded = stored_keys_loaded };
}
pub const SystemPrompt = struct {
diff --git a/src/telemetry.zig b/src/telemetry.zig
index 074e5c05..3f5289ec 100644
--- a/src/telemetry.zig
+++ b/src/telemetry.zig
@@ -20,6 +20,7 @@ const g_cost = &pricing.g_cost;
const util = @import("util.zig");
const utf8Prefix = util.utf8Prefix;
const unixMs = util.unixMs;
+const http = @import("http.zig");
// For the session run id (score/run join key) and the propose-site
// fingerprint check. No cycle: scoring imports only std + pricing.
@@ -377,6 +378,7 @@ pub const Telemetry = struct {
}
pub fn postOtlp(client: *std.http.Client, url: []const u8, payload: []const u8) void {
+ http.waitForClientReady(client.io);
_ = client.fetch(.{
.location = .{ .url = url },
.method = .POST,