graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
release: ship OpenAI compaction in v0.0.250
Rach Pradhan267468344f25
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7beb2c80..de195711 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,22 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.+## v0.0.250 (2026-08-12)++- First-party OpenAI server compaction now installs the complete canonical+ `/responses/compact` output transactionally on both the Codex subscription+ and official Platform Responses routes. Missing, invalid, or empty output+ leaves history intact and falls back to readable local compaction; other+ providers remain local-only.+- The official `openai` provider uses the Responses API with ordinary bearer+ authentication, without inheriting ChatGPT backend headers, WebSocket+ chaining, or Codex-only priority behavior.+- REPL tool activity is visible again as stable terse start/result rows with+ human-readable command, path, URL, or description previews instead of raw+ JSON or cursor-rewriting output.+- Controlled replay evidence covers 21/21 perfect continuations across the+ first-party OpenAI host/auth paths, including long paired tool histories.+## v0.0.249 (2026-08-12)- Folded native tools become callable immediately after their schemas loaddiff --git a/benchmarks/official_openai_compaction_replay.py b/benchmarks/official_openai_compaction_replay.pynew file mode 100644index 00000000..65ceaebc--- /dev/null+++ b/benchmarks/official_openai_compaction_replay.py@@ -0,0 +1,229 @@+#!/usr/bin/env python3+"""Replay frozen tool history through the official OpenAI Platform compact path."""++from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import statistics+import time+from typing import Any+import urllib.error+import urllib.request++DEFAULT_FIXTURE = Path(+ "/tmp/compact_bench/runs/none1/.graff/sessions/"+ "auditing-zig-constants-and-recording-answers.session.json"+)+BASE = "https://api.openai.com/v1"+SYSTEM = (+ "You are a deterministic continuation scorer. Never call tools or inspect "+ "the filesystem. Answer only from retained conversation state and follow "+ "the requested output format exactly."+)+EXPECTED = {+ 1: "61701",+ 2: "89665",+ 3: "43973",+ 4: "26089",+ 5: '"ember-986"',+ 6: "89289",+ 7: '"welkin-815"',+ 8: '"kindle-443"',+ 9: '"hollow-765"',+ 10: "23041",+}+NAMES = (+ "OBSIDIAN_ALPHA", "LANTERN_ALPHA", "COPSE_BETA", "NUMEN_BETA",+ "EMBER_GAMMA", "QUORUM_GAMMA", "WELKIN_DELTA", "KINDLE_DELTA",+ "HOLLOW_EPSILO", "MARROW_EPSILO",+)+PROBE = (+ "Using only the retained conversation state, answer these constants again. "+ "Do not call tools. Reply with EXACTLY ten lines and no other text:\n"+ + "\n".join(f"Q{i}: exact value of {name}" for i, name in enumerate(NAMES, 1))+)+++def args() -> argparse.Namespace:+ parser = argparse.ArgumentParser()+ parser.add_argument("--fixture", type=Path, default=DEFAULT_FIXTURE)+ parser.add_argument("--out", type=Path, required=True)+ parser.add_argument("--models", nargs="+", default=["gpt-5.6-sol", "gpt-5.6-luna"])+ parser.add_argument("--trials", type=int, default=3)+ parser.add_argument("--timeout", type=int, default=420)+ return parser.parse_args()+++def canonical(value: Any) -> bytes:+ return json.dumps(value, sort_keys=True, separators=(",", ":")).encode()+++def post(key: str, path: str, body: dict[str, Any], timeout: int) -> tuple[dict[str, Any], dict[str, int]]:+ payload = json.dumps(body, separators=(",", ":")).encode()+ request = urllib.request.Request(+ BASE + path,+ data=payload,+ method="POST",+ headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},+ )+ started = time.monotonic()+ try:+ with urllib.request.urlopen(request, timeout=timeout) as response:+ raw = response.read()+ return json.loads(raw), {+ "status": response.status,+ "ms": round((time.monotonic() - started) * 1000),+ "request_bytes": len(payload),+ "response_bytes": len(raw),+ "errors": 0,+ }+ except urllib.error.HTTPError as error:+ raw = error.read()+ try:+ message = json.loads(raw).get("error", {}).get("message", "OpenAI API error")+ except json.JSONDecodeError:+ message = "non-JSON OpenAI API error"+ raise RuntimeError(f"HTTP {error.code}: {message}") from error+++def response_text(response: dict[str, Any]) -> str:+ text = response.get("output_text")+ if isinstance(text, str):+ return text+ chunks = []+ for item in response.get("output", []):+ if item.get("type") != "message":+ continue+ for content in item.get("content", []):+ if content.get("type") == "output_text":+ chunks.append(content.get("text", ""))+ return "".join(chunks)+++def score(text: str) -> tuple[int, dict[str, str]]:+ got = {+ match.group(1): match.group(2).strip()+ for match in re.finditer(r"(?m)^Q(10|[1-9]):\s*([^\r\n]+)", text)+ }+ return sum(got.get(str(i)) == value for i, value in EXPECTED.items()), got+++def usage(response: dict[str, Any]) -> dict[str, int]:+ value = response.get("usage") or {}+ details = value.get("input_tokens_details") or {}+ return {+ "input_tokens": int(value.get("input_tokens", 0)),+ "cached_tokens": int(details.get("cached_tokens", 0)),+ "output_tokens": int(value.get("output_tokens", 0)),+ "total_tokens": int(value.get("total_tokens", 0)),+ }+++def replayable_fixture(path: Path) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ raw = path.read_bytes()+ data = json.loads(raw)+ original = data.get("messages", [])+ messages = [item for item in original if item.get("type") != "reasoning"]+ call_ids = {item.get("call_id") for item in messages if item.get("type") == "function_call"}+ output_ids = {item.get("call_id") for item in messages if item.get("type") == "function_call_output"}+ if not messages or call_ids != output_ids:+ raise SystemExit("fixture must retain exactly paired function calls and outputs")+ return messages, {+ "fixture": str(path.resolve()),+ "fixture_sha256": hashlib.sha256(raw).hexdigest(),+ "platform_input_sha256": hashlib.sha256(canonical(messages)).hexdigest(),+ "original_items": len(original),+ "platform_items": len(messages),+ "removed_backend_reasoning_items": len(original) - len(messages),+ "function_calls": sum(item.get("type") == "function_call" for item in messages),+ "function_outputs": sum(item.get("type") == "function_call_output" for item in messages),+ }+++def run_trial(key: str, model: str, trial: int, messages: list[dict[str, Any]], timeout: int) -> dict[str, Any]:+ started = time.monotonic()+ compacted, compact_wire = post(key, "/responses/compact", {+ "model": model,+ "instructions": SYSTEM,+ "input": messages,+ }, timeout)+ output = compacted.get("output")+ if not isinstance(output, list) or not output:+ raise RuntimeError("compact response had no output array")+ probe = {"type": "message", "role": "user", "content": PROBE}+ response, response_wire = post(key, "/responses", {+ "model": model,+ "instructions": SYSTEM,+ "input": output + [probe],+ "store": False,+ }, timeout)+ text = response_text(response)+ correct, answers = score(text)+ metrics = {+ "model": model,+ "trial": trial,+ "correct": correct,+ "of": len(EXPECTED),+ "answers": answers,+ "wall_ms": round((time.monotonic() - started) * 1000),+ "api_errors": compact_wire["errors"] + response_wire["errors"],+ "compact_ms": compact_wire["ms"],+ "continuation_ms": response_wire["ms"],+ "request_bytes": compact_wire["request_bytes"] + response_wire["request_bytes"],+ "response_bytes": compact_wire["response_bytes"] + response_wire["response_bytes"],+ "compact_output_types": [item.get("type") for item in output],+ "compact_output_items": len(output),+ "compact_usage": usage(compacted),+ "continuation_usage": usage(response),+ }+ return metrics+++def main() -> None:+ options = args()+ key = os.environ.get("OPENAI_API_KEY")+ if not key:+ raise SystemExit("OPENAI_API_KEY is required")+ if options.trials < 1:+ raise SystemExit("--trials must be positive")+ options.out.mkdir(parents=True, exist_ok=True)+ messages, fixture = replayable_fixture(options.fixture)+ manifest = {+ **fixture,+ "base_url": BASE,+ "models": options.models,+ "trials": options.trials,+ "probe": PROBE,+ "expected": EXPECTED,+ }+ (options.out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")+ results = []+ for model in options.models:+ model_dir = options.out / model+ model_dir.mkdir(exist_ok=True)+ for trial in range(1, options.trials + 1):+ metrics = run_trial(key, model, trial, messages, options.timeout)+ results.append(metrics)+ (model_dir / f"trial-{trial}.json").write_text(json.dumps(metrics, indent=2) + "\n")+ print(+ f"model={model} trial={trial} score={metrics['correct']}/{metrics['of']} "+ f"compact_items={metrics['compact_output_items']} wall={metrics['wall_ms']}ms",+ flush=True,+ )+ (options.out / "results.json").write_text(json.dumps(results, indent=2) + "\n")+ for model in options.models:+ rows = [row for row in results if row["model"] == model]+ print(+ f"summary model={model} perfect={sum(row['correct'] == row['of'] for row in rows)}/{len(rows)} "+ f"median_wall={statistics.median(row['wall_ms'] for row in rows):.0f}ms",+ flush=True,+ )+++if __name__ == "__main__":+ main()diff --git a/benchmarks/openai-server-compaction-controlled-replay.html b/benchmarks/openai-server-compaction-controlled-replay.htmlnew file mode 100644index 00000000..688e4833--- /dev/null+++ b/benchmarks/openai-server-compaction-controlled-replay.html@@ -0,0 +1,187 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>OpenAI compaction: latest-item failure and full-history fix</title>+ <style>+ :root { color-scheme:dark; --bg:#07110f; --panel:#0c1916; --panel2:#10231d; --line:#24443a; --text:#e9f5f0; --muted:#9bb8ad; --green:#059669; --mint:#3bd7a1; --gold:#efc75e; --red:#ff7a70; --blue:#6ca8ff; }+ * { box-sizing:border-box; }+ body { margin:0; color:var(--text); background:radial-gradient(circle at 86% 0,rgba(5,150,105,.2),transparent 31rem),linear-gradient(180deg,#091611,var(--bg) 36rem); font:15px/1.58 ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace; }+ main { width:min(1120px,calc(100% - 36px)); margin:auto; padding:62px 0 84px; }+ h1 { max-width:980px; margin:12px 0 18px; font:800 clamp(36px,6vw,68px)/.99 ui-sans-serif,system-ui,sans-serif; letter-spacing:-.055em; }+ h2 { margin:0 0 18px; font:750 clamp(25px,4vw,39px)/1.08 ui-sans-serif,system-ui,sans-serif; letter-spacing:-.035em; }+ h3 { margin:6px 0 8px; font-size:17px; }+ p,li { color:var(--muted); }+ code { color:#c7f8e5; background:#071511; border:1px solid var(--line); padding:2px 5px; border-radius:5px; overflow-wrap:anywhere; }+ section { margin-top:68px; }+ .eyebrow { color:var(--mint); text-transform:uppercase; letter-spacing:.16em; font-size:12px; font-weight:800; }+ .lede { max-width:900px; color:#c8dcd4; font:19px/1.55 ui-sans-serif,system-ui,sans-serif; }+ .chips { display:flex; flex-wrap:wrap; gap:8px; margin-top:25px; }+ .chip { padding:7px 10px; border:1px solid var(--line); border-radius:999px; background:rgba(12,25,22,.82); color:#bcd2ca; font-size:12px; }+ .grid { display:grid; grid-template-columns:repeat(12,1fr); gap:14px; }+ .card { grid-column:span 4; padding:20px; border:1px solid var(--line); border-radius:14px; background:linear-gradient(145deg,var(--panel2),var(--panel)); }+ .card.wide { grid-column:span 6; }+ .card .k { color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.1em; }+ .card .v { margin-top:7px; font:750 31px/1 ui-sans-serif,system-ui,sans-serif; letter-spacing:-.04em; }+ .good { color:var(--mint); } .warn { color:var(--gold); } .bad { color:var(--red); }+ .callout { margin-top:18px; padding:18px 20px; border-left:4px solid var(--gold); border-radius:0 10px 10px 0; background:rgba(239,199,94,.08); color:#e9dfbb; }+ .callout.badline { border-color:var(--red); background:rgba(255,122,112,.08); color:#f3c8c3; }+ .callout.goodline { border-color:var(--green); background:rgba(5,150,105,.11); color:#c9ebdf; }+ .table-wrap { overflow:auto; border:1px solid var(--line); border-radius:14px; }+ table { width:100%; min-width:790px; border-collapse:collapse; background:rgba(12,25,22,.83); }+ th,td { padding:13px 16px; text-align:left; vertical-align:top; border-bottom:1px solid var(--line); }+ th { background:#10231d; color:#cce5dc; font-size:12px; text-transform:uppercase; letter-spacing:.08em; }+ tr:last-child td { border-bottom:0; } td:first-child { color:#bad1c8; }+ .flow { display:grid; grid-template-columns:1fr auto 1fr auto 1fr; align-items:center; gap:12px; margin-top:24px; }+ .step { min-height:145px; padding:17px; border:1px solid var(--line); border-radius:12px; background:var(--panel); }+ .arrow { color:var(--mint); font-size:24px; }+ .source { color:#78998c; font-size:12px; }+ footer { margin-top:72px; padding-top:22px; border-top:1px solid var(--line); color:#729286; font-size:12px; }+ @media(max-width:780px){ .card,.card.wide{grid-column:span 12}.flow{grid-template-columns:1fr}.arrow{transform:rotate(90deg);justify-self:center} }+ </style>+</head>+<body><main>+ <header>+ <div class="eyebrow">Controlled replay · live OpenAI Responses · 2026-08-12</div>+ <h1>The reliability bug was our contract, not OpenAI compaction.</h1>+ <p class="lede">The old experiment kept only the latest opaque in-stream item and recovered all ten tool-derived facts in just one of three trials. Matching OpenAI's full-output contract recovered every fact in all nine ChatGPT/Codex-backend trials and all twelve separate official Platform trials through <code>api.openai.com/v1</code>.</p>+ <div class="chips">+ <span class="chip">ChatGPT/Codex backend: 9 / 9</span><span class="chip">Official Platform: 12 / 12</span><span class="chip">gpt-5.6-sol</span><span class="chip">gpt-5.6-luna</span><span class="chip">gpt-5.6-terra</span><span class="chip">gpt-5.6</span><span class="chip">OpenAI only</span><span class="chip">no credentials captured</span>+ </div>+ </header>++ <section>+ <div class="eyebrow">Decision signal</div>+ <h2>Use full-output replacement; delete the latest-item assumption</h2>+ <div class="grid">+ <div class="card"><div class="k">Old server mechanism</div><div class="v bad">1 / 3</div><p>Trial scores: 10/10, 0/10, 0/10.</p></div>+ <div class="card"><div class="k">Fixed server mechanism</div><div class="v good">3 / 3</div><p>10/10 exact facts in every continuation.</p></div>+ <div class="card"><div class="k">Local control</div><div class="v good">3 / 3</div><p>Still 10/10 in every paired trial.</p></div>+ </div>+ <div class="callout goodline"><strong>Recommendation:</strong> adopt the standalone full-history transaction for first-party OpenAI Responses routes, with Codegraff's readable local compactor as the failure fallback. The contract is green on both the subscription-backed ChatGPT/Codex backend and the metered official Platform host. Never enable this protocol for non-OpenAI models; keep rollout guarded while natural multi-compaction sessions accumulate production-like evidence.</div>+ </section>++ <section>+ <div class="eyebrow">Root cause and correction</div>+ <h2>“Newest opaque item” is not Codex's replacement-history contract</h2>+ <div class="flow">+ <div class="step"><div class="eyebrow">Before</div><h3>Lossy in-stream prune</h3><p>Request <code>context_management</code>, find the newest encrypted item, drop every older item, and continue from that one item.</p></div>+ <div class="arrow">→</div>+ <div class="step"><div class="eyebrow">Codex parity</div><h3>Standalone transaction</h3><p>POST model, instructions, and the complete Responses input to <code>/responses/compact</code>.</p></div>+ <div class="arrow">→</div>+ <div class="step"><div class="eyebrow">After</div><h3>Install every output item</h3><p>Validate and deep-clone all three retained messages plus <code>compaction_summary</code>, then reset the chain and meters.</p></div>+ </div>+ <div class="callout"><strong>Transactional boundary:</strong> network, JSON, missing-output, empty-output, and malformed-item failures leave the original history untouched. Only a fully validated non-empty output array is installed; otherwise the existing local summary path runs.</div>+ </section>++ <section>+ <div class="eyebrow">Controlled method</div>+ <h2>The fixture and exact probe stayed frozen</h2>+ <ul>+ <li>Fixture: 175,308 bytes, 40 Responses items, 14 function calls, 14 exactly paired outputs, and ten planted facts read from tool results.</li>+ <li>Canonical message SHA-256: <code>227e22af1daf667a591a958467e4236b1cbb487799bec8af1a72a56d4cee2aef</code>.</li>+ <li>Fixed server arm: resume the fixture in the revised binary, trigger automatic OpenAI compaction, require a saved <code>compaction_summary</code>, then ask the no-tools ten-line probe.</li>+ <li>Local arm: resume the same fixture, invoke the real JSON <code>{"type":"compact"}</code> control, then ask the identical probe.</li>+ <li>Trial order alternated server→local, local→server, server→local. All six final arms completed with zero recorded API errors.</li>+ </ul>+ </section>++ <section>+ <div class="eyebrow">Before / after retention</div>+ <h2>The all-or-nothing failures disappeared</h2>+ <div class="table-wrap"><table>+ <thead><tr><th>Trial</th><th>Old: latest item</th><th>Fixed: full output</th><th>Local control</th><th>Fixed saved shape</th></tr></thead>+ <tbody>+ <tr><td>1</td><td class="good"><strong>10 / 10</strong></td><td class="good"><strong>10 / 10</strong></td><td class="good"><strong>10 / 10</strong></td><td>3 messages + summary</td></tr>+ <tr><td>2</td><td class="bad"><strong>0 / 10</strong></td><td class="good"><strong>10 / 10</strong></td><td class="good"><strong>10 / 10</strong></td><td>3 messages + summary</td></tr>+ <tr><td>3</td><td class="bad"><strong>0 / 10</strong></td><td class="good"><strong>10 / 10</strong></td><td class="good"><strong>10 / 10</strong></td><td>3 messages + summary</td></tr>+ </tbody>+ </table></div>+ <p>The old failed continuations answered all ten facts <code>unknown</code>. Every fixed trial saved an actual <code>compaction_summary</code>; a silent local fallback therefore cannot explain the green result.</p>+ </section>++ <section>+ <div class="eyebrow">Model and horizon matrix</div>+ <h2>Both routed Codex models passed; the longer valid history passed</h2>+ <div class="table-wrap"><table>+ <thead><tr><th>Case</th><th>Fixture</th><th>Server retention</th><th>Real replacements</th><th>Median continuation input</th><th>Median wall</th></tr></thead>+ <tbody>+ <tr><td><code>gpt-5.6-sol</code></td><td>40 items · 14 call/output pairs</td><td class="good"><strong>3 / 3 at 10/10</strong></td><td>3 / 3</td><td>4,034 tokens</td><td>21,110 ms</td></tr>+ <tr><td><code>gpt-5.6-luna</code></td><td>40 items · 14 call/output pairs</td><td class="good"><strong>3 / 3 at 10/10</strong></td><td>3 / 3</td><td>3,830 tokens</td><td>22,026 ms</td></tr>+ <tr><td><code>gpt-5.6-sol</code> long</td><td>72 items · 28 call/output pairs</td><td class="good"><strong>3 / 3 at 10/10</strong></td><td>3 / 3</td><td>4,842 tokens</td><td>19,095 ms</td></tr>+ </tbody>+ </table></div>+ <p>The live <code>graff route</code> catalog exposed <code>sol</code> as Codex frontier and <code>luna</code> as Codex small; there was no first-party Codex mid rung to test. OpenAI-compatible gateway models were deliberately excluded because the implementation enables this protocol only for the exact first-party <code>codex</code> and <code>openai</code> provider IDs.</p>+ <div class="callout"><strong>Long-fixture validity:</strong> encrypted reasoning items are authentication-bound to their original item IDs and were never duplicated or rewritten. The 72-item fixture retained the original eight reasoning items and duplicated only replay-safe messages plus 14 uniquely re-keyed function-call/output pairs, yielding 28 exactly paired calls and outputs. A discarded invalid prototype that rewrote encrypted item IDs correctly failed and fell back locally; it is not counted.</div>+ </section>++ <section>+ <div class="eyebrow">Official OpenAI Platform path</div>+ <h2>The public <code>api.openai.com</code> route is independently green</h2>+ <p>This matrix did not route through ChatGPT subscription infrastructure or Codegraff's provider selection. The replay driver called <code>POST https://api.openai.com/v1/responses/compact</code> with an OpenAI Platform project key, then called <code>POST https://api.openai.com/v1/responses</code> with the complete returned output plus the frozen probe.</p>+ <div class="table-wrap"><table>+ <thead><tr><th>Official model ID</th><th>Retention</th><th>Compact output each trial</th><th>Median continuation input</th><th>Median full wall</th></tr></thead>+ <tbody>+ <tr><td><code>gpt-5.6-sol</code></td><td class="good"><strong>3 / 3 at 10/10</strong></td><td>3 messages + compaction</td><td>1,591 tokens</td><td>10,127 ms</td></tr>+ <tr><td><code>gpt-5.6-luna</code></td><td class="good"><strong>3 / 3 at 10/10</strong></td><td>3 messages + compaction</td><td>1,842 tokens</td><td>7,024 ms</td></tr>+ <tr><td><code>gpt-5.6-terra</code></td><td class="good"><strong>3 / 3 at 10/10</strong></td><td>3 messages + compaction</td><td>1,943 tokens</td><td>8,393 ms</td></tr>+ <tr><td><code>gpt-5.6</code></td><td class="good"><strong>3 / 3 at 10/10</strong></td><td>3 messages + compaction</td><td>1,610 tokens</td><td>10,019 ms</td></tr>+ </tbody>+ </table></div>+ <div class="callout"><strong>Cross-auth fixture boundary:</strong> the eight encrypted reasoning items minted by the ChatGPT/Codex backend cannot be replayed under a Platform project key, so the official-host fixture excludes only those authentication-bound ciphertext items. It preserves all 14 function calls, all 14 paired outputs, all user messages, and the same ten facts. The Platform compact input is 32 items / 71,720 tokens; all twelve compactions returned the canonical four-item window.</div>+ <p>The official OpenAI API reference lists the standalone endpoint and these model IDs, and its compaction guide says the returned window generally contains retained items plus the opaque compaction item and must be passed forward as-is. These results independently confirm that contract.</p>+ </section>++ <section>+ <div class="eyebrow">Latency and accounting</div>+ <h2>The fixed path stayed faster, but token totals are not comparable</h2>+ <div class="table-wrap"><table>+ <thead><tr><th>Median metric</th><th>Old latest-item</th><th>Fixed full-output</th><th>Local control</th></tr></thead>+ <tbody>+ <tr><td>Perfect retention</td><td class="bad">1 / 3</td><td class="good"><strong>3 / 3</strong></td><td class="good"><strong>3 / 3</strong></td></tr>+ <tr><td>Wall time</td><td>11,986 ms</td><td><strong>21,110 ms</strong></td><td>33,693 ms</td></tr>+ <tr><td>Provider transactions</td><td>2 direct calls</td><td>1 compact + 1 continuation</td><td>3 traced calls</td></tr>+ <tr><td>Continuation input</td><td>Not isolated</td><td><strong>4,034 tokens</strong></td><td>Not isolated</td></tr>+ <tr><td>Recorded API errors</td><td>0</td><td>0</td><td>0</td></tr>+ <tr><td>Summary visibility</td><td>Opaque item only</td><td>Retained messages + opaque summary</td><td><strong>Readable prose</strong></td></tr>+ </tbody>+ </table></div>+ <p class="source">Wall time includes the fixed arm's standalone compact transaction. Codegraff's ordinary model-call trace does not instrument that direct HTTP helper, so the fixed arm's 4,034-token median is continuation input only—not total compaction work. The old 73,149-token and local 94,878-token totals used different trace boundaries and must not be presented as a causal token saving.</p>+ </section>++ <section>+ <div class="eyebrow">Implementation guardrails</div>+ <h2>The experiment now fails safe</h2>+ <div class="grid">+ <div class="card wide"><div class="k">Provider boundary</div><h3>Exact first-party gate</h3><p>Server compaction requires both <code>kind == responses</code> and <code>id == codex</code>. A Responses-compatible gateway remains disabled even under the force-on override.</p></div>+ <div class="card wide"><div class="k">Lifecycle coverage</div><h3>Fresh and resumed sessions</h3><p>In-turn, between-turn, and restored-session automatic compaction all route through the server policy. Resume still never authorizes destructive trimming on failure.</p></div>+ <div class="card wide"><div class="k">Failure behavior</div><h3>Original history survives</h3><p>Invalid endpoint responses do not mutate messages or token anchors. The REPL/JSON stream reports the fallback, then the existing local compactor runs.</p></div>+ <div class="card wide"><div class="k">No in-stream ambiguity</div><h3>One owner</h3><p>The Responses request no longer emits <code>context_management</code>; automatic compaction is one explicit standalone transaction.</p></div>+ </div>+ </section>++ <section>+ <div class="eyebrow">Reproducibility</div>+ <h2>Binary, raw roots, and checks</h2>+ <div class="table-wrap"><table><tbody>+ <tr><td>Experiment script</td><td><code>benchmarks/repeated_compaction_replay.py</code></td></tr>+ <tr><td>HTML report</td><td><code>benchmarks/openai-server-compaction-controlled-replay.html</code></td></tr>+ <tr><td>Experimental branch</td><td><code>experiment/openai-server-longhorizon</code></td></tr>+ <tr><td>Fixed binary SHA-256</td><td><code>9851e52a78237b2a07a8a5f39f95e6df4ae6acc7a17a0608d6968e04d652b70e</code></td></tr>+ <tr><td>Fixture SHA-256</td><td><code>9bb71603c47f0a706ddb6c59b055dbeee5aade204bb03901d5bde585e1eb9687</code></td></tr>+ <tr><td>Old raw root</td><td><code>/tmp/openai-server-compaction-replay-20260812-final</code></td></tr>+ <tr><td>Sol standard root</td><td><code>/tmp/openai-server-compaction-replay-20260812-full-output-final2</code></td></tr>+ <tr><td>Luna standard root</td><td><code>/tmp/openai-server-compaction-replay-20260812-luna</code></td></tr>+ <tr><td>Sol long root</td><td><code>/tmp/openai-server-compaction-replay-20260812-sol-long-final</code></td></tr>+ <tr><td>Official Platform driver</td><td><code>benchmarks/official_openai_compaction_replay.py</code></td></tr>+ <tr><td>Official Platform root</td><td><code>/tmp/openai-platform-compaction-replay-20260812</code></td></tr>+ <tr><td>Official Platform input SHA-256</td><td><code>2671b09c305431f98fa03e32edabc82f3adccbdc8529c2b16fb800cefbdb7c13</code></td></tr>+ <tr><td>Long fixture SHA-256</td><td><code>96d1e6cf887c001cc8d38b864b9ed705058728c144d577ff9d0d7a5ca4bec19d</code></td></tr>+ <tr><td>Verification</td><td><code>zig fmt --check</code>, <code>zig build test</code>, <code>zig build -p zig-out-openai-compact</code></td></tr>+ </tbody></table></div>+ <p class="source">Credentials were read from the existing Codex auth file for ChatGPT-backend requests and the secure OpenAI key store for official Platform requests. No access token, account ID, authorization header, API key, or keychain data is stored in benchmark output or this report. Twenty-one green full-output trials prove the targeted regression across two first-party auth/host paths, four official model IDs, and the synthetic longer fixture; they do not estimate a production failure rate or replace natural multi-compaction soak testing.</p>+ </section>++ <footer>Codegraff controlled compaction replay · ChatGPT/Codex backend + official OpenAI Platform · standalone full-output replacement · OpenAI only.</footer>+</main></body></html>diff --git a/benchmarks/openai-server-compaction-longhorizon.html b/benchmarks/openai-server-compaction-longhorizon.htmlnew file mode 100644index 00000000..33ea8ea1--- /dev/null+++ b/benchmarks/openai-server-compaction-longhorizon.html@@ -0,0 +1,203 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>OpenAI server compaction — long-horizon experiment</title>+ <style>+ :root {+ color-scheme: dark;+ --bg: #07110f;+ --panel: #0c1916;+ --panel-2: #10221d;+ --line: #234239;+ --text: #e8f5ef;+ --muted: #9db8ad;+ --emerald: #059669;+ --mint: #39d6a0;+ --gold: #f1c75b;+ --blue: #6ba7ff;+ --coral: #ff7d73;+ }+ * { box-sizing: border-box; }+ body {+ margin: 0;+ background:+ radial-gradient(circle at 85% 0%, rgba(5,150,105,.18), transparent 28rem),+ linear-gradient(180deg, #08130f 0, var(--bg) 32rem);+ color: var(--text);+ font: 15px/1.55 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ }+ main { width: min(1120px, calc(100% - 36px)); margin: 0 auto; padding: 64px 0 84px; }+ .eyebrow { color: var(--mint); text-transform: uppercase; letter-spacing: .16em; font-size: 12px; font-weight: 800; }+ h1 { max-width: 900px; margin: 12px 0 16px; font-size: clamp(34px, 6vw, 68px); line-height: .98; letter-spacing: -.055em; }+ h2 { margin: 0 0 18px; font-size: clamp(24px, 4vw, 38px); line-height: 1.08; letter-spacing: -.035em; }+ h3 { margin: 5px 0 8px; font-size: 17px; }+ p { color: var(--muted); }+ code { color: #c7f8e5; background: #071511; border: 1px solid var(--line); padding: 2px 5px; border-radius: 5px; }+ .lede { max-width: 850px; font: 19px/1.55 ui-sans-serif, system-ui, sans-serif; color: #c9ddd5; }+ .meta { display: flex; flex-wrap: wrap; gap: 8px; margin: 26px 0 0; }+ .chip { border: 1px solid var(--line); background: rgba(12,25,22,.8); color: #bad1c8; padding: 7px 10px; border-radius: 999px; font-size: 12px; }+ section { margin-top: 68px; }+ .grid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 14px; }+ .card { grid-column: span 4; padding: 20px; border: 1px solid var(--line); border-radius: 14px; background: linear-gradient(145deg, var(--panel-2), var(--panel)); }+ .card .k { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .1em; }+ .card .v { margin-top: 6px; font: 700 30px/1 ui-sans-serif, system-ui, sans-serif; letter-spacing: -.04em; }+ .good { color: var(--mint); }+ .warn { color: var(--gold); }+ .bad { color: var(--coral); }+ .callout { margin-top: 18px; padding: 18px 20px; border-left: 4px solid var(--gold); background: rgba(241,199,91,.08); border-radius: 0 10px 10px 0; color: #e8deb9; }+ .callout.goodline { border-left-color: var(--emerald); background: rgba(5,150,105,.1); color: #c8ebde; }+ .bars { display: grid; gap: 13px; margin: 24px 0; }+ .bar-row { display: grid; grid-template-columns: 145px 1fr 115px; align-items: center; gap: 12px; }+ .track { height: 14px; overflow: hidden; border-radius: 999px; background: #132821; border: 1px solid #26463c; }+ .bar { height: 100%; border-radius: inherit; background: linear-gradient(90deg, var(--emerald), var(--mint)); }+ .bar.client { background: linear-gradient(90deg, #427acc, var(--blue)); }+ .table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: 14px; }+ table { width: 100%; border-collapse: collapse; min-width: 760px; background: rgba(12,25,22,.8); }+ th, td { padding: 13px 16px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; }+ th { color: #cbe5da; background: #10231d; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; }+ tr:last-child td { border-bottom: 0; }+ td:first-child { color: #b9d0c7; }+ ol, ul { color: var(--muted); padding-left: 22px; }+ li { margin: 9px 0; }+ .flow { display: grid; grid-template-columns: 1fr auto 1fr auto 1fr; align-items: center; gap: 12px; margin-top: 24px; }+ .step { min-height: 118px; padding: 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; }+ .arrow { color: var(--mint); font-size: 24px; }+ .source { font-size: 12px; color: #78998c; }+ footer { margin-top: 72px; padding-top: 22px; border-top: 1px solid var(--line); color: #6f9184; font-size: 12px; }+ @media (max-width: 780px) {+ .card { grid-column: span 12; }+ .bar-row { grid-template-columns: 110px 1fr 90px; }+ .flow { grid-template-columns: 1fr; }+ .arrow { transform: rotate(90deg); justify-self: center; }+ }+ </style>+</head>+<body>+<main>+ <header>+ <div class="eyebrow">Codegraff compaction experiment · 2026-08-12</div>+ <h1>OpenAI server compaction survived the horizon. It did not win this run.</h1>+ <p class="lede">A paired live run used the same experimental binary, model, 12-step chained task, token facts, and forced-low 4% threshold. Automatic OpenAI compaction completed the task after pruning 52 earlier history items. Local prose compaction also completed it—and happened to use fewer calls, fewer total tokens, and less wall time.</p>+ <div class="meta">+ <span class="chip">model: gpt-5.6-sol</span>+ <span class="chip">provider: Codex (ChatGPT OAuth)</span>+ <span class="chip">12 chained steps</span>+ <span class="chip">GRAFF_COMPACT_PCT=4</span>+ <span class="chip">one paired trial</span>+ <span class="chip">no credentials captured</span>+ </div>+ </header>++ <section>+ <div class="eyebrow">Verdict</div>+ <h2>Functional pass; efficiency result is inconclusive</h2>+ <div class="grid">+ <div class="card"><div class="k">Server active-session recall</div><div class="v good">12 / 12</div><p>Every one-time token was reported correctly after the compaction boundary.</p></div>+ <div class="card"><div class="k">Actual server prune</div><div class="v good">52 items</div><p>One encrypted <code>compaction</code> anchor replaced the earlier client history.</p></div>+ <div class="card"><div class="k">Observed local advantage</div><div class="v warn">106 sec</div><p>The local arm finished 48.4% faster in this single live trajectory.</p></div>+ </div>+ <div class="callout"><strong>Do not read the cost delta as a clean compactor benchmark.</strong> The server arm chose 36 model calls—12 shell calls plus repeated reads and edits. The local arm chose 16 calls and appended with <code>tee</code>. That trajectory divergence dominates total token and wall-time comparisons.</div>+ </section>++ <section>+ <div class="eyebrow">OpenAI-only scope</div>+ <h2>The experiment cannot activate on another vendor</h2>+ <div class="flow">+ <div class="step"><div class="eyebrow">Gate 1</div><h3>Responses wire</h3><p>The provider must use the OpenAI Responses item protocol.</p></div>+ <div class="arrow">→</div>+ <div class="step"><div class="eyebrow">Gate 2</div><h3><code>id == "codex" || id == "openai"</code></h3><p>The provider must be one of Codegraff's exact first-party OpenAI routes.</p></div>+ <div class="arrow">→</div>+ <div class="step"><div class="eyebrow">Result</div><h3>Server compaction eligible</h3><p>Any other provider remains on local readable compaction.</p></div>+ </div>+ <div class="callout goodline"><strong>Still local:</strong> Anthropic, Kimi, xAI, DeepSeek, Codegraff Gateway, OpenAI-compatible routers, and hypothetical non-OpenAI Responses gateways. The official <code>openai</code> Platform route is eligible now that it uses the Responses API.</div>+ <p class="source">Implementation: <code>src/agent_server_compact.zig</code>. Regression coverage forces a fake Responses-compatible gateway on and proves the exact provider gate still returns false.</p>+ </section>++ <section>+ <div class="eyebrow">Measured results</div>+ <h2>Same answer quality, different trajectories</h2>+ <div class="bars">+ <div class="bar-row"><strong>Server input</strong><div class="track"><div class="bar" style="width:100%"></div></div><span>280,888</span></div>+ <div class="bar-row"><strong>Local input</strong><div class="track"><div class="bar client" style="width:34.3%"></div></div><span>96,358</span></div>+ <div class="bar-row"><strong>Server wall</strong><div class="track"><div class="bar" style="width:100%"></div></div><span>324.3 sec</span></div>+ <div class="bar-row"><strong>Local wall</strong><div class="track"><div class="bar client" style="width:67.4%"></div></div><span>218.6 sec</span></div>+ </div>+ <div class="table-wrap">+ <table>+ <thead><tr><th>Metric</th><th>OpenAI server</th><th>Codegraff local</th><th>Read</th></tr></thead>+ <tbody>+ <tr><td>Phase-1 facts</td><td><strong class="good">12 / 12</strong></td><td><strong class="good">12 / 12</strong></td><td>Functional tie</td></tr>+ <tr><td>Wall time</td><td>324.3 sec</td><td><strong>218.6 sec</strong></td><td>Server 48.4% slower</td></tr>+ <tr><td>Model calls</td><td>36</td><td><strong>16</strong></td><td>Trajectory diverged</td></tr>+ <tr><td>Total input tokens</td><td>280,888</td><td><strong>96,358</strong></td><td>Server 2.92×</td></tr>+ <tr><td>Cached input tokens</td><td>237,056</td><td>57,088</td><td>Server 4.15×</td></tr>+ <tr><td>Uncached input tokens</td><td>43,832</td><td><strong>39,270</strong></td><td>Server 11.6% higher</td></tr>+ <tr><td>Output tokens</td><td><strong>1,817</strong></td><td>2,075</td><td>Server 12.4% lower</td></tr>+ <tr><td>Successful compactions</td><td>1 server prune</td><td>2 local summaries</td><td>Local also had 5 overload failures</td></tr>+ <tr><td>Final session bytes</td><td>27,441</td><td><strong>2,655</strong></td><td>Opaque blob + suffix versus prose summary</td></tr>+ <tr><td>Flat-rate charge shown</td><td>$0.0000</td><td>$0.0000</td><td>Both used the logged-in subscription</td></tr>+ </tbody>+ </table>+ </div>+ </section>++ <section>+ <div class="eyebrow">What happened</div>+ <h2>The server boundary worked as designed</h2>+ <ol>+ <li>This early experiment asked the Responses stream for automatic compaction at 4% of the model's 272k window; the released mechanism instead calls <code>/responses/compact</code> explicitly at the guarded threshold.</li>+ <li>The service emitted a real encrypted <code>compaction</code> output item during the chained workflow.</li>+ <li>The experiment originally retained only the newest opaque item. Follow-up controlled replay found that insufficient, so v0.0.250 transactionally installs the endpoint's complete canonical <code>output</code> array and resets its token anchors.</li>+ <li>The agent then completed the remaining chained steps and returned all 12 authoritative facts correctly.</li>+ </ol>+ <p class="source">Request directive: <code>src/agent_server_compact.zig:111-130</code>. Safe history replacement: <code>src/agent_server_compact.zig:132-189</code>. Near-limit local fallback: <code>src/agent_server_compact.zig:192-212</code>.</p>+ </section>++ <section>+ <div class="eyebrow">Long-horizon method</div>+ <h2>A sequential workflow that must cross compaction</h2>+ <ul>+ <li>The fixture generated 12 one-time token facts and a randomized chain. Each probe reveals only the next step, preventing batching.</li>+ <li>Each step emitted 26 filler lines below the tool-result spill threshold, forcing context to accumulate.</li>+ <li>Both arms used the same binary, model, seed, task, credentials source, context threshold, and maximum-call budget. Only <code>GRAFF_SERVER_COMPACT=1</code> versus <code>0</code> changed.</li>+ <li>The server arm used one prune and no local summaries. The local arm completed two summaries; five additional summary attempts encountered transient OpenAI overload errors and safely preserved history.</li>+ </ul>+ <div class="callout"><strong>Cold-recall appendix:</strong> the local arm returned 12/12 in its fresh process. The server arm's first fresh-process request was rejected as overloaded before any model call; a later retry returned 12/12. Both agents had deliberately written the facts to disk, and the harness also leaves captured stdout in the task directory, so cold recall demonstrates recoverability—not compaction fidelity.</div>+ </section>++ <section>+ <div class="eyebrow">Interpretation</div>+ <h2>Useful proof, not a ship/no-ship verdict</h2>+ <div class="grid">+ <div class="card"><div class="k">Proven</div><h3>Continuity</h3><p>The automatic service item was ingested, old history was actually removed, the Responses chain re-anchored, and the task still finished perfectly.</p></div>+ <div class="card"><div class="k">Not proven</div><h3>Efficiency win</h3><p>The arms took different action strategies, and n=1 cannot separate compaction policy from ordinary model nondeterminism.</p></div>+ <div class="card"><div class="k">Decision</div><h3>Keep it gated</h3><p>Continue as an OpenAI/Codex-only experiment with local fallback; do not generalize it to other providers.</p></div>+ </div>+ <p>The earlier fixed coding-context benchmark found server compaction cheaper than local summaries. This longer agentic run found the opposite observed totals. Together they suggest server compaction is sensitive to workload shape and to the post-compaction action policy. A causal follow-up should replay a scripted sequence of identical tool calls across both arms and repeat each arm several times.</p>+ </section>++ <section>+ <div class="eyebrow">Reproducibility</div>+ <h2>Experimental binary and evidence</h2>+ <div class="table-wrap">+ <table>+ <tbody>+ <tr><td>Worktree</td><td><code>.graff/worktrees/openai-server-longhorizon</code></td></tr>+ <tr><td>Branch</td><td><code>experiment/openai-server-longhorizon</code></td></tr>+ <tr><td>Base commit</td><td><code>bccd9cc2f56ba13edc497365891745f3c7971b39</code></td></tr>+ <tr><td>Binary</td><td><code>zig-out-openai-compact/bin/graff</code></td></tr>+ <tr><td>Binary SHA-256</td><td><code>e6ba230247fabe58b88fbe4c4b79002437cc61228d146b46149d47c2b2868922</code></td></tr>+ <tr><td>Verification</td><td><code>zig fmt --check src/agent_server_compact.zig</code>, <code>zig build test</code>, <code>zig build -p zig-out-openai-compact</code></td></tr>+ <tr><td>Raw run root</td><td><code>/tmp/openai-server-longhorizon-20260811</code></td></tr>+ </tbody>+ </table>+ </div>+ <p class="source">Single live trial. Timing and provider overloads are environment-dependent. No access token, account identifier, authorization header, or user content beyond the synthetic fixture is embedded in this report.</p>+ </section>++ <footer>Codegraff benchmark report · standalone HTML · OpenAI Responses server compaction remains capability-gated with Codegraff local compaction as fallback.</footer>+</main>+</body>+</html>diff --git a/benchmarks/repeated_compaction_replay.py b/benchmarks/repeated_compaction_replay.pynew file mode 100644index 00000000..0c064079--- /dev/null+++ b/benchmarks/repeated_compaction_replay.py@@ -0,0 +1,588 @@+#!/usr/bin/env python3+"""Repeated live A/B over one canonical Responses tool trajectory.++The server arm loads the frozen history into the experimental Codegraff binary,+lets automatic compaction replace it with the complete `/responses/compact`+output, then sends the continuation probe. The local arm loads the same history,+invokes Codegraff's JSON compact control, and sends the identical probe. The+legacy latest-item function remains below to preserve the before methodology;+trial order alternates to reduce time bias.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import subprocess+import time+from typing import Any+import urllib.error+import urllib.request+import uuid++DEFAULT_FIXTURE = Path(+ "/tmp/compact_bench/runs/none1/.graff/sessions/"+ "auditing-zig-constants-and-recording-answers.session.json"+)+DEFAULT_AUTH = Path.home() / ".codex" / "auth.json"+CODEX_BASE = "https://chatgpt.com/backend-api/codex"+EXPECTED = {+ 1: "61701",+ 2: "89665",+ 3: "43973",+ 4: "26089",+ 5: '"ember-986"',+ 6: "89289",+ 7: '"welkin-815"',+ 8: '"kindle-443"',+ 9: '"hollow-765"',+ 10: "23041",+}+QUESTIONS = [+ (1, "OBSIDIAN_ALPHA"),+ (2, "LANTERN_ALPHA"),+ (3, "COPSE_BETA"),+ (4, "NUMEN_BETA"),+ (5, "EMBER_GAMMA"),+ (6, "QUORUM_GAMMA"),+ (7, "WELKIN_DELTA"),+ (8, "KINDLE_DELTA"),+ (9, "HOLLOW_EPSILO"),+ (10, "MARROW_EPSILO"),+]+SYSTEM = (+ "You are a deterministic continuation scorer. Never call tools or inspect "+ "the filesystem. Answer only from retained conversation state and follow "+ "the requested output format exactly."+)+PROBE = (+ "Using only the retained conversation state, answer these constants again. "+ "Do not call tools. Reply with EXACTLY ten lines and no other text:\n"+ + "\n".join(f"Q{n}: exact value of {name}" for n, name in QUESTIONS)+)+ACK = "Reply with only ACK."+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser()+ parser.add_argument("--binary", type=Path, required=True)+ parser.add_argument("--fixture", type=Path, default=DEFAULT_FIXTURE)+ parser.add_argument("--auth", type=Path, default=DEFAULT_AUTH)+ parser.add_argument("--out", type=Path, required=True)+ parser.add_argument("--trials", type=int, default=3)+ parser.add_argument("--model", default="gpt-5.6-sol")+ parser.add_argument("--compact-pct", type=int, default=6)+ parser.add_argument("--context-window", type=int, default=272_000)+ parser.add_argument("--timeout", type=int, default=420)+ return parser.parse_args()+++def canonical(value: Any) -> bytes:+ return json.dumps(value, sort_keys=True, separators=(",", ":")).encode()+++def strings(value: Any):+ if isinstance(value, str):+ yield value+ elif isinstance(value, list):+ for child in value:+ yield from strings(child)+ elif isinstance(value, dict):+ for child in value.values():+ yield from strings(child)+++def output_text(stdout: str) -> str:+ found: list[str] = []+ for line in stdout.splitlines():+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue+ for text in strings(event):+ if "Q1:" in text or "Q10:" in text:+ found.append(text)+ return "\n".join(found)+++def score(text: str) -> tuple[int, dict[str, str]]:+ got = {}+ for match in re.finditer(r"(?m)^Q(10|[1-9]):\s*([^\r\n]+)", text):+ got[match.group(1)] = match.group(2).strip()+ correct = sum(got.get(str(n)) == expected for n, expected in EXPECTED.items())+ return correct, got+++def usage_metrics(usage: dict[str, Any] | None) -> dict[str, int]:+ usage = usage or {}+ details = usage.get("input_tokens_details") or {}+ return {+ "input_tokens": int(usage.get("input_tokens", 0)),+ "cache_read_tokens": int(details.get("cached_tokens", 0)),+ "output_tokens": int(usage.get("output_tokens", 0)),+ "total_tokens": int(usage.get("total_tokens", 0)),+ }+++def add_metrics(left: dict[str, int], right: dict[str, int]) -> dict[str, int]:+ return {key: left.get(key, 0) + right.get(key, 0) for key in left | right}+++def load_auth(path: Path) -> tuple[str, str]:+ auth = json.loads(path.read_text())+ tokens = auth.get("tokens", auth)+ token = tokens.get("access_token")+ account = tokens.get("account_id") or auth.get("account_id")+ if not token or not account:+ raise SystemExit(f"Codex auth lacks access_token/account_id: {path}")+ return token, account+++def run_stream(+ args: argparse.Namespace,+ body: dict[str, Any],+) -> tuple[list[dict[str, Any]], str, dict[str, Any] | None, dict[str, int]]:+ token, account = load_auth(args.auth)+ payload = json.dumps(body, separators=(",", ":")).encode()+ attempts = errors = response_bytes = 0+ started = time.monotonic()+ for retry in range(3):+ attempts += 1+ request = urllib.request.Request(+ CODEX_BASE + "/responses",+ data=payload,+ method="POST",+ headers={+ "Authorization": f"Bearer {token}",+ "chatgpt-account-id": account,+ "OpenAI-Beta": "responses=experimental",+ "originator": "codex_cli_rs",+ "session_id": str(uuid.uuid4()),+ "Content-Type": "application/json",+ "Accept": "text/event-stream",+ },+ )+ items: list[dict[str, Any]] = []+ text: list[str] = []+ usage = None+ try:+ with urllib.request.urlopen(request, timeout=args.timeout) as response:+ for raw in response:+ response_bytes += len(raw)+ line = raw.decode("utf-8", "replace").strip()+ if not line.startswith("data:"):+ continue+ data = line[5:].strip()+ if data == "[DONE]":+ break+ try:+ event = json.loads(data)+ except json.JSONDecodeError:+ continue+ event_type = event.get("type", "")+ if event_type == "response.output_item.done":+ items.append(event.get("item", {}))+ elif event_type == "response.output_text.delta":+ text.append(event.get("delta", ""))+ elif event_type in ("response.completed", "response.incomplete"):+ result = event.get("response", {})+ usage = result.get("usage")+ known = {item.get("id") for item in items}+ for item in result.get("output", []):+ if item.get("id") not in known:+ items.append(item)+ return items, "".join(text), usage, {+ "http_attempts": attempts,+ "http_errors": errors,+ "request_bytes": len(payload) * attempts,+ "response_bytes": response_bytes,+ "api_ms": round((time.monotonic() - started) * 1000),+ }+ except urllib.error.HTTPError as error:+ errors += 1+ if error.code not in (429, 500, 502, 503, 504) or retry == 2:+ raise+ time.sleep(2 ** retry)+ raise RuntimeError("unreachable")+++def trace_metrics(trial_dir: Path) -> dict[str, int]:+ events = []+ for trace in (trial_dir / ".graff" / "traces").glob("*.jsonl"):+ for line in trace.read_text(errors="replace").splitlines():+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue+ if event.get("ev") == "api":+ events.append(event)+ return {+ "api_calls": len(events),+ "api_errors": sum(bool(event.get("is_error")) for event in events),+ "api_ms": sum(int(event.get("ms", 0)) for event in events),+ "request_bytes": sum(int(event.get("req_bytes", 0)) for event in events),+ "response_bytes": sum(int(event.get("resp_bytes", 0)) for event in events),+ "context_tokens": sum(int(event.get("context_tokens", 0)) for event in events),+ "cache_read_tokens": sum(int(event.get("cache_read_tokens", 0)) for event in events),+ }+++def run_latest_item_server(args: argparse.Namespace, trial: int, fixture: dict[str, Any]) -> dict[str, Any]:+ trial_dir = args.out / f"trial-{trial}" / "server"+ trial_dir.mkdir(parents=True)+ messages = fixture["messages"]+ threshold = args.context_window // 100 * args.compact_pct+ started = time.monotonic()+ items1, ack, usage1, wire1 = run_stream(+ args,+ {+ "model": args.model,+ "store": False,+ "stream": True,+ "instructions": SYSTEM,+ "input": messages + [{"type": "message", "role": "user", "content": ACK}],+ "context_management": [{"type": "compaction", "compact_threshold": threshold}],+ },+ )+ compacted = [+ item for item in items1+ if item.get("type") in ("compaction", "compaction_summary")+ ]+ if not compacted:+ raise RuntimeError(f"server trial {trial} returned no compaction item")+ latest = compacted[-1]+ items2, answer, usage2, wire2 = run_stream(+ args,+ {+ "model": args.model,+ "store": False,+ "stream": True,+ "instructions": SYSTEM,+ "input": [+ latest,+ {"type": "message", "role": "user", "content": PROBE},+ ],+ "context_management": [{"type": "compaction", "compact_threshold": threshold}],+ },+ )+ wall_ms = round((time.monotonic() - started) * 1000)+ correct, got = score(answer)+ usage = add_metrics(usage_metrics(usage1), usage_metrics(usage2))+ wire = add_metrics(wire1, wire2)+ (trial_dir / "answer.txt").write_text(answer)+ metrics = {+ "trial": trial,+ "arm": "server",+ "returncode": 0,+ "timed_out": False,+ "wall_ms": wall_ms,+ "correct": correct,+ "of": len(EXPECTED),+ "answers": got,+ "ack": ack,+ "api_calls": 2,+ "api_errors": wire["http_errors"],+ "context_tokens": usage["input_tokens"],+ "cache_read_tokens": usage["cache_read_tokens"],+ "output_tokens": usage["output_tokens"],+ "request_bytes": wire["request_bytes"],+ "response_bytes": wire["response_bytes"],+ "api_ms": wire["api_ms"],+ "session_bytes": len(canonical([latest])),+ "message_count": 1,+ "compaction_items": len(compacted),+ "function_calls": 0,+ "function_outputs": 0,+ "phase1_item_types": [item.get("type") for item in items1],+ "phase2_item_types": [item.get("type") for item in items2],+ }+ (trial_dir / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n")+ return metrics+++def run_server(args: argparse.Namespace, trial: int, fixture: dict[str, Any]) -> dict[str, Any]:+ del fixture # the binary reads the byte-identical copied session+ trial_dir = args.out / f"trial-{trial}" / "server"+ sessions = trial_dir / ".graff" / "sessions"+ sessions.mkdir(parents=True)+ session_path = sessions / "frozen.session.json"+ shutil.copy2(args.fixture, session_path)+ session = json.loads(session_path.read_text())+ session["context_tokens"] = 0+ session["context_local_tokens"] = 0+ session_path.write_text(json.dumps(session, separators=(",", ":")))++ stdin = json.dumps({"type": "user", "text": PROBE}) + "\n"+ env = {+ **os.environ,+ "GRAFF_SERVER_COMPACT": "1",+ "GRAFF_COMPACT_PCT": str(args.compact_pct),+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_LEARN_AUTO": "off",+ "GRAFF_FLEET": "off",+ }+ command = [+ str(args.binary.resolve()),+ "--json",+ "--resume",+ "frozen",+ "--model",+ args.model,+ "--no-telemetry",+ "--system-prompt",+ SYSTEM,+ "--max-model-calls",+ "8",+ ]+ started = time.monotonic()+ try:+ completed = subprocess.run(+ command,+ cwd=trial_dir,+ env=env,+ input=stdin,+ text=True,+ capture_output=True,+ timeout=args.timeout,+ )+ timed_out = False+ except subprocess.TimeoutExpired as error:+ completed = subprocess.CompletedProcess(+ command,+ -1,+ stdout=error.stdout or "",+ stderr=error.stderr or "",+ )+ timed_out = True+ wall_ms = round((time.monotonic() - started) * 1000)+ (trial_dir / "stdout.jsonl").write_text(completed.stdout)+ (trial_dir / "stderr.txt").write_text(completed.stderr)+ answer = output_text(completed.stdout)+ (trial_dir / "answer.txt").write_text(answer)+ correct, got = score(answer)+ data = json.loads(session_path.read_text())+ types = [message.get("type", message.get("role", "unknown")) for message in data["messages"]]+ trace = trace_metrics(trial_dir)+ turn_event: dict[str, Any] = {}+ for line in completed.stdout.splitlines():+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue+ if event.get("type") == "turn":+ turn_event = event+ if turn_event:+ trace["api_calls"] = int(turn_event.get("api_calls", trace["api_calls"]))+ trace["context_tokens"] = int(turn_event.get("input_tokens", trace["context_tokens"]))+ trace["cache_read_tokens"] = int(turn_event.get("cache_read_tokens", trace["cache_read_tokens"]))+ compact_items = types.count("compaction") + types.count("compaction_summary")+ metrics = {+ "trial": trial,+ "arm": "server",+ "mechanism": "binary /responses/compact full-output replacement",+ "returncode": completed.returncode,+ "timed_out": timed_out,+ "wall_ms": wall_ms,+ "correct": correct,+ "of": len(EXPECTED),+ "answers": got,+ **trace,+ "untraced_compact_api_calls": 1 if compact_items else 0,+ "output_tokens": int(turn_event.get("output_tokens", 0)),+ "session_bytes": session_path.stat().st_size,+ "message_count": len(types),+ "compaction_items": compact_items,+ "server_compaction_observed": compact_items > 0,+ "function_calls": types.count("function_call"),+ "function_outputs": types.count("function_call_output"),+ "message_types": types,+ }+ (trial_dir / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n")+ return metrics+++def run_local(args: argparse.Namespace, trial: int) -> dict[str, Any]:+ trial_dir = args.out / f"trial-{trial}" / "local"+ sessions = trial_dir / ".graff" / "sessions"+ sessions.mkdir(parents=True)+ session_path = sessions / "frozen.session.json"+ shutil.copy2(args.fixture, session_path)+ session = json.loads(session_path.read_text())+ session["context_tokens"] = 0+ session["context_local_tokens"] = 0+ session_path.write_text(json.dumps(session, separators=(",", ":")))++ stdin = "".join(+ json.dumps(control) + "\n"+ for control in (+ {"type": "compact"},+ {"type": "user", "text": PROBE},+ )+ )+ env = {+ **os.environ,+ "GRAFF_SERVER_COMPACT": "0",+ "GRAFF_COMPACT_PCT": "100",+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_LEARN_AUTO": "off",+ "GRAFF_FLEET": "off",+ }+ command = [+ str(args.binary.resolve()),+ "--json",+ "--resume",+ "frozen",+ "--model",+ args.model,+ "--no-telemetry",+ "--system-prompt",+ SYSTEM,+ "--max-model-calls",+ "8",+ ]+ started = time.monotonic()+ try:+ completed = subprocess.run(+ command,+ cwd=trial_dir,+ env=env,+ input=stdin,+ text=True,+ capture_output=True,+ timeout=args.timeout,+ )+ timed_out = False+ except subprocess.TimeoutExpired as error:+ completed = subprocess.CompletedProcess(+ command,+ -1,+ stdout=error.stdout or "",+ stderr=error.stderr or "",+ )+ timed_out = True+ wall_ms = round((time.monotonic() - started) * 1000)+ (trial_dir / "stdout.jsonl").write_text(completed.stdout)+ (trial_dir / "stderr.txt").write_text(completed.stderr)+ answer = output_text(completed.stdout)+ (trial_dir / "answer.txt").write_text(answer)+ correct, got = score(answer)+ data = json.loads(session_path.read_text())+ types = [message.get("type", message.get("role", "unknown")) for message in data["messages"]]+ compact_events = []+ turn_event: dict[str, Any] = {}+ for line in completed.stdout.splitlines():+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue+ if event.get("type") == "compact" and event.get("ok"):+ compact_events.append(event)+ elif event.get("type") == "turn":+ turn_event = event+ trace = trace_metrics(trial_dir)+ if turn_event:+ trace["api_calls"] = int(turn_event.get("api_calls", trace["api_calls"]))+ trace["context_tokens"] = int(turn_event.get("input_tokens", trace["context_tokens"]))+ trace["cache_read_tokens"] = int(turn_event.get("cache_read_tokens", trace["cache_read_tokens"]))+ metrics = {+ "trial": trial,+ "arm": "local",+ "returncode": completed.returncode,+ "timed_out": timed_out,+ "wall_ms": wall_ms,+ "correct": correct,+ "of": len(EXPECTED),+ "answers": got,+ **trace,+ "output_tokens": int(turn_event.get("output_tokens", 0)),+ "session_bytes": session_path.stat().st_size,+ "message_count": len(types),+ "compaction_items": 0,+ "local_compact_events": len(compact_events),+ "local_summary_chars": sum(int(event.get("chars", 0)) for event in compact_events),+ "function_calls": types.count("function_call"),+ "function_outputs": types.count("function_call_output"),+ "message_types": types,+ }+ (trial_dir / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n")+ return metrics+++def validate_fixture(path: Path) -> tuple[dict[str, Any], dict[str, Any]]:+ raw = path.read_bytes()+ data = json.loads(raw)+ messages = data.get("messages", [])+ kinds = [message.get("type", message.get("role", "unknown")) for message in messages]+ call_ids = {message.get("call_id") for message in messages if message.get("type") == "function_call"}+ output_ids = {message.get("call_id") for message in messages if message.get("type") == "function_call_output"}+ if not messages or call_ids != output_ids:+ raise SystemExit("fixture must have non-empty history and exactly paired tool calls/results")+ manifest = {+ "fixture": str(path.resolve()),+ "fixture_sha256": hashlib.sha256(raw).hexdigest(),+ "message_sha256": hashlib.sha256(canonical(messages)).hexdigest(),+ "fixture_bytes": len(raw),+ "fixture_messages": len(messages),+ "fixture_function_calls": kinds.count("function_call"),+ "fixture_function_outputs": kinds.count("function_call_output"),+ "fixture_context_tokens": data.get("context_tokens"),+ }+ return data, manifest+++def main() -> None:+ args = parse_args()+ args.binary = args.binary.resolve()+ args.fixture = args.fixture.resolve()+ args.auth = args.auth.expanduser().resolve()+ args.out = args.out.resolve()+ if args.trials < 1 or not 1 <= args.compact_pct <= 100:+ raise SystemExit("--trials must be positive and --compact-pct must be 1..100")+ if not args.binary.is_file() or not os.access(args.binary, os.X_OK):+ raise SystemExit(f"binary is not executable: {args.binary}")+ if not args.fixture.is_file() or not args.auth.is_file():+ raise SystemExit("fixture and Codex auth file must exist")+ args.out.mkdir(parents=True, exist_ok=True)+ fixture, fixture_manifest = validate_fixture(args.fixture)+ manifest = {+ **fixture_manifest,+ "binary": str(args.binary),+ "binary_sha256": hashlib.sha256(args.binary.read_bytes()).hexdigest(),+ "model": args.model,+ "compact_pct": args.compact_pct,+ "context_window": args.context_window,+ "compact_threshold": args.context_window // 100 * args.compact_pct,+ "trials": args.trials,+ "probe": PROBE,+ "expected": EXPECTED,+ }+ (args.out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")++ results = []+ for trial in range(1, args.trials + 1):+ order = ("server", "local") if trial % 2 else ("local", "server")+ for arm in order:+ result = (+ run_server(args, trial, fixture)+ if arm == "server"+ else run_local(args, trial)+ )+ results.append(result)+ print(+ f"trial={trial} arm={arm} score={result['correct']}/{result['of']} "+ f"calls={result['api_calls']} context={result['context_tokens']} "+ f"cached={result['cache_read_tokens']} wall={result['wall_ms']}ms "+ f"compactions={result.get('compaction_items', 0) + result.get('local_compact_events', 0)}",+ flush=True,+ )+ (args.out / "results.json").write_text(json.dumps(results, indent=2) + "\n")+ print(f"wrote {args.out / 'results.json'}")+++if __name__ == "__main__":+ main()diff --git a/docs/releases/v0.0.250.md b/docs/releases/v0.0.250.mdnew file mode 100644index 00000000..0c664413--- /dev/null+++ b/docs/releases/v0.0.250.md@@ -0,0 +1,29 @@+# v0.0.250 (2026-08-12)++This release makes OpenAI server-side compaction safe across both first-party+host and authentication paths, while restoring useful tool visibility in the+REPL.++- **Canonical compact history.** Graff installs the entire validated+ `/responses/compact` `output` array, rather than retaining only its newest+ opaque item. Installation is transactional: missing, malformed, or empty+ output preserves the original history and uses readable local compaction as+ the fallback.+- **Strict first-party boundary.** Server compaction is limited to Responses+ requests from the exact `codex` and `openai` providers. Non-OpenAI providers+ continue to use local compaction.+- **Official Platform Responses route.** The `openai` provider now targets+ `https://api.openai.com/v1/responses` with ordinary bearer authentication.+ ChatGPT backend identity headers, Codex WebSocket chaining, and Codex-only+ priority behavior remain exclusive to `codex`.+- **Readable REPL tool rows.** Tool starts and results appear as stable terse+ rows with short command, path, URL, description, or result previews. This+ avoids raw JSON noise and the output corruption risk of cursor-up rewriting+ during parallel work.++The implementation was exercised with controlled continuation replays on both+first-party OpenAI routes: 9/9 perfect trials through the ChatGPT/Codex backend+and 12/12 through the official Platform across `gpt-5.6-sol`,+`gpt-5.6-luna`, `gpt-5.6-terra`, and `gpt-5.6`. The long fixture preserved 28+paired function calls and outputs; invalid remote responses were separately+verified to retain the original local history.diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 16053e43..9c6bf03f 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -14,7 +14,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 1211,+ "test_count_baseline": 1212,"test_count_slack": 25,"required_invariants": [{diff --git a/src/agent.zig b/src/agent.zigindex acf33f87..eeec939e 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -434,6 +434,7 @@ pub const Agent = struct {pub const emergencyTrim = @import("agent_compact.zig").emergencyTrim;pub const compactOrRecover = @import("agent_compact.zig").compactOrRecover;pub const autocompact = @import("agent_server_compact.zig").autocompact;+ pub const autocompactResumed = @import("agent_server_compact.zig").autocompactResumed;pub const capOversizedToolOutputs = @import("agent_compact.zig").capOversizedToolOutputs;// The live streaming path (thinking spinner, live "Thinking" reasoningdiff --git a/src/agent_prompt.zig b/src/agent_prompt.zigindex 66293733..ae9848a3 100644--- a/src/agent_prompt.zig+++ b/src/agent_prompt.zig@@ -44,9 +44,9 @@ fn status(self: *Agent) engine_events.PromptStatus {} else null,.cache_read = self.last_cache_read,.cost = cost(self),- // The Fast badge is a `responses`-shaped concept; on any other wire- // format the flag exists but means nothing, so no badge is offered.- .fast = self.fast and self.provider.kind == .responses,+ // Fast priority is exclusive to the ChatGPT/Codex route; the official+ // OpenAI Platform Responses provider does not inherit that contract.+ .fast = self.fast and std.mem.eql(u8, self.provider.id, "codex"),.fallback = self.fallback_active,.plan = main_mod.plan_mode,.strict = self.strict,diff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex f0ff8793..030d80e8 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -182,9 +182,9 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo}},.responses => {- // Codex / ChatGPT Responses API. system prompt → instructions; history- // items are valid input items; stream is required (we buffer + parse the- // SSE); reasoning items return encrypted and are passed back per turn.+ // First-party OpenAI Responses API. system prompt → instructions;+ // history items are valid input items; stream is required (we buffer ++ // parse SSE); reasoning items return encrypted and pass back per turn.try s.objectField("instructions");try s.write(self.systemPrompt());// Pin our full resends to a per-session cache partition, the way@@ -223,10 +223,9 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.objectField("parallel_tool_calls");try s.write(true);}- // Codex "fast" mode (/fast): request the priority service- // tier for lower latency. This branch is codex-only, so it is- // never emitted for other providers.- if (self.fast) {+ // Codex "fast" mode (/fast): request the priority service tier for+ // lower latency. The Platform key route does not inherit this mode.+ if (self.fast and std.mem.eql(u8, self.provider.id, "codex")) {try s.objectField("service_tier");try s.write("priority");}@@ -246,8 +245,8 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.write(false);server_compact.noteExposure(self);try server_compact.writeContextManagement(self, &s);- // No top-level max_output_tokens: the codex backend rejects it- // ("Unsupported parameter") on gpt-5.6-* — codex sets it only as a tool argument.+ // No top-level max_output_tokens: the Codex backend rejects it on+ // gpt-5.6-*; leaving it absent is also valid on the Platform route.try s.objectField("stream");try s.write(true);},diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zigindex 2b1a080b..fc5633b7 100644--- a/src/agent_server_compact.zig+++ b/src/agent_server_compact.zig@@ -1,25 +1,16 @@//! Server-side autocompaction for the Responses wire (codex / OpenAI family).//!-//! Verified against the live codex backend (gpt-5.6-sol, ChatGPT OAuth,-//! store:false): it honors `context_management: [{"type":"compaction",-//! "compact_threshold":N}]` — when the rendered window crosses N the server-//! runs a compaction pass IN-STREAM and emits opaque `compaction` output items-//! (Fernet-encrypted state blobs). Those items flow through parseResponses and-//! stepResponses into history untouched, so no ingestion change was needed.-//! Sending only the latest blob + a new message continues the conversation-//! with full recall (probe: .graff/scratch/compact_continue.py), which is the-//! docs' "drop items before the most recent compaction item" latency rule.+//! OpenAI Codex parity uses the standalone `/responses/compact` transaction:+//! send the complete Responses history, then install the endpoint's complete+//! `output` array. Keeping only an in-stream encrypted item is not equivalent:+//! repeated tool-history replay retained 10/10 facts only 1/3 times, while the+//! endpoint's retained messages + compaction_summary restored 10/10.//!//! Policy split vs the client-side path (agent_compact.zig):-//! - .responses providers: autocompact prunes local history to the newest-//! server blob (zero model calls, near-lossless); the client-side summary-//! survives only as the near-the-wall (95%) fallback, and manual /compact-//! stays client-side so the handoff remains inspectable.-//! - every other provider kind: unchanged legacy policy.-//!-//! The opaque blob's server-side lifetime under store:false is unknown; if a-//! resumed session's blob is ever rejected, the ordinary overflow recovery-//! ladder (agent_overflow.zig) is the safety net.+//! - the first-party `codex` Responses provider: automatic compaction calls+//! the standalone endpoint and transactionally replaces the full history;+//! local prose compaction remains the failure fallback and manual path.+//! - every other provider kind/id: unchanged legacy policy.const std = @import("std");const Io = std.Io;@@ -28,6 +19,7 @@ const Agent = @import("agent.zig").Agent;const Provider = @import("provider.zig").Provider;const telemetry = @import("telemetry.zig");const keys_cli = @import("keys_cli.zig");+const http = @import("http.zig");/// GRAFF_SERVER_COMPACT=0/false/off forces the client arm, =1 forces the/// server arm (session_settings.applyEnvKnobs). Default: A/B assignment.@@ -53,8 +45,11 @@ pub fn assignArm(io: Io, arena: std.mem.Allocator, home: []const u8) void {}/// Is the server-compaction path active for this provider?+/// Restrict this to OpenAI's two first-party providers, not merely the Responses+/// wire, so a future compatible gateway cannot inherit the opaque compaction+/// protocol accidentally.pub fn enabled(p: Provider) bool {- if (p.kind != .responses) return false;+ if (p.kind != .responses or !(std.mem.eql(u8, p.id, "codex") or std.mem.eql(u8, p.id, "openai"))) return false;if (g_server_compact_override) |o| return o;return g_ab_arm orelse false;}@@ -105,107 +100,137 @@ pub fn noteClientSummary(chars: usize) void {pushExp(d);}-/// Emit the compaction directive on a Responses request body. The threshold-/// mirrors the client-side trigger (compactAt: 80% of the window,-/// GRAFF_COMPACT_PCT-aware) so the server compacts at the point graff would-/// have.-pub fn writeContextManagement(self: *const Agent, s: anytype) !void {- if (!enabled(self.provider)) return;- try writeContextManagementBody(self, s);+/// Automatic compaction is a standalone transaction. Do not also request+/// in-stream compaction: its single opaque item is not the full replacement+/// history returned by `/responses/compact`.+pub fn writeContextManagement(_: *const Agent, _: anytype) !void {}++const ReplacementCounts = struct { old: usize, new: usize };++fn compactEndpoint(gpa: std.mem.Allocator, response_url: []const u8) ![]u8 {+ const base = std.mem.trimEnd(u8, response_url, "/");+ if (std.mem.endsWith(u8, base, "/responses/compact")) return gpa.dupe(u8, base);+ if (!std.mem.endsWith(u8, base, "/responses")) return error.InvalidCompactEndpoint;+ return std.fmt.allocPrint(gpa, "{s}/compact", .{base});}-fn writeContextManagementBody(self: *const Agent, s: anytype) !void {- try s.objectField("context_management");- try s.beginArray();+fn compactRequestBody(self: *Agent) ![]u8 {+ var aw: Io.Writer.Allocating = .init(self.gpa);+ errdefer aw.deinit();+ var s: std.json.Stringify = .{ .writer = &aw.writer };try s.beginObject();- try s.objectField("type");- try s.write("compaction");- try s.objectField("compact_threshold");- try s.write(self.provider.compactAt());+ try s.objectField("model");+ try s.write(self.provider.model);+ try s.objectField("instructions");+ try s.write(self.systemPrompt());+ try s.objectField("input");+ try s.write(std.json.Value{ .array = self.messages });try s.endObject();- try s.endArray();+ return aw.toOwnedSlice();}-/// Drop every item before the most recent server compaction blob; the blob-/// carries the pruned state (verified live). Returns false when there is no-/// usable blob, so the caller falls back to the client-side policy.-///-/// Pair safety: a function_call_output AFTER the blob whose call was pruned-/// would orphan locally (normalizeResponsesHistory doesn't repair pairing), so-/// such histories are left to the client-side path. In practice the trailing-/// blob lands at a response boundary where pairs are complete.-pub fn pruneToLatestBlob(self: *Agent) bool {- return pruneIf(self, enabled(self.provider));+fn cloneJsonValue(arena: std.mem.Allocator, value: std.json.Value) std.mem.Allocator.Error!std.json.Value {+ return switch (value) {+ .string => |src| .{ .string = try arena.dupe(u8, src) },+ .number_string => |src| .{ .number_string = try arena.dupe(u8, src) },+ .array => |src| blk: {+ var out = std.json.Array.init(arena);+ try out.ensureTotalCapacity(src.items.len);+ for (src.items) |item_value| try out.append(try cloneJsonValue(arena, item_value));+ break :blk .{ .array = out };+ },+ .object => |src| blk: {+ var out: std.json.ObjectMap = .empty;+ var it = src.iterator();+ while (it.next()) |entry| {+ const key = try arena.dupe(u8, entry.key_ptr.*);+ try out.put(arena, key, try cloneJsonValue(arena, entry.value_ptr.*));+ }+ break :blk .{ .object = out };+ },+ else => value,+ };}-fn pruneIf(self: *Agent, server_arm: bool) bool {- if (!server_arm or self.provider.kind != .responses) return false;- const items = self.messages.items;- var blob_idx: ?usize = null;- for (items, 0..) |m, i| {- if (m != .object) continue;- const t = m.object.get("type") orelse continue;- if (t != .string) continue;- if (std.mem.eql(u8, t.string, "compaction") or std.mem.eql(u8, t.string, "compaction_summary")) blob_idx = i;- }- const k = blob_idx orelse return false;- if (k == 0) return false; // already anchored on the blob- // Collect the call_ids that survive, then reject if any surviving output- // references a pruned call.- var surviving: std.ArrayList([]const u8) = .empty;- defer surviving.deinit(self.gpa);- for (items[k..]) |m| {- if (m != .object) continue;- const t = m.object.get("type") orelse continue;- if (t != .string or !std.mem.eql(u8, t.string, "function_call")) continue;- const cid = m.object.get("call_id") orelse continue;- if (cid == .string) surviving.append(self.gpa, cid.string) catch return false;+/// Validate and install the endpoint's complete replacement history. Parsing+/// happens in a temporary arena; no live field changes until every returned item+/// has been validated and cloned into the session arena.+fn installCompactResponse(self: *Agent, body: []const u8) !ReplacementCounts {+ var parse_state = std.heap.ArenaAllocator.init(self.gpa);+ defer parse_state.deinit();+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, parse_state.allocator(), body, .{ .allocate = .alloc_always }) catch+ return error.InvalidCompactResponse;+ if (parsed != .object) return error.InvalidCompactResponse;+ const output = parsed.object.get("output") orelse return error.InvalidCompactResponse;+ if (output != .array) return error.InvalidCompactResponse;+ if (output.array.items.len == 0) return error.EmptyCompactOutput;+ for (output.array.items) |response_item| {+ if (response_item != .object) return error.InvalidCompactResponse;+ const item_type = response_item.object.get("type") orelse return error.InvalidCompactResponse;+ if (item_type != .string or item_type.string.len == 0) return error.InvalidCompactResponse;}- for (items[k..]) |m| {- if (m != .object) continue;- const t = m.object.get("type") orelse continue;- if (t != .string or !std.mem.eql(u8, t.string, "function_call_output")) continue;- const cid = m.object.get("call_id") orelse continue;- if (cid != .string) continue;- for (surviving.items) |sid| {- if (std.mem.eql(u8, sid, cid.string)) break;- } else return false; // orphaned output — not safe to prune- }- const dropped = k;- var fresh = std.json.Array.init(self.arena);- fresh.appendSlice(items[k..]) catch return false;- self.messages = fresh;- // Mirror compact()'s post-install meter reset: both anchors recompute- // lazily, and the goal note died with the pruned prefix (#318).++ var replacement = std.json.Array.init(self.arena);+ try replacement.ensureTotalCapacity(output.array.items.len);+ for (output.array.items) |response_item|+ try replacement.append(try cloneJsonValue(self.arena, response_item));++ const counts: ReplacementCounts = .{ .old = self.messages.items.len, .new = replacement.items.len };+ self.closeCodexWs();+ self.messages = replacement;self.last_context_tokens = 0;self.context_local_tokens = 0;self.goal_note_fp = 0;- self.history_rewrites +%= 1; // breaks the codex chain → next request re-anchors- notePrune(dropped);- if (!main_mod.json_mode) self.say("[server compacted context: {d} earlier item(s) now carried by the model's compaction state]\n", .{dropped}) catch {};- return true;+ self.history_rewrites +%= 1;+ notePrune(counts.old -| counts.new);+ return counts;+}++fn remoteCompact(self: *Agent) !ReplacementCounts {+ const body = try compactRequestBody(self);+ defer self.gpa.free(body);+ const url = try compactEndpoint(self.gpa, self.provider.url);+ defer self.gpa.free(url);+ var compact_provider = self.provider;+ compact_provider.url = url;+ const response = try http.postWatched(self.gpa, self.io, self.client, compact_provider, body);+ defer self.gpa.free(response);+ return installCompactResponse(self, response);}/// The autocompact entry point shared by every automatic compaction site-/// (agent.zig's in-turn pre-send gate, mainloop's post-failure and-/// between-turns checks). Non-responses providers get the legacy policy-/// unchanged.+/// (agent.zig's in-turn pre-send gate and mainloop's between-turn checks).+/// Non-responses providers get the legacy policy unchanged.pub fn autocompact(self: *Agent, recovery_meter: u64) void {autocompactIf(self, recovery_meter, enabled(self.provider));}+/// Restored sessions compact before their first turn, but resume alone must+/// never authorize destructive recovery. A failed server transaction therefore+/// takes the same local-summary fallback with `trim_on_fail = false`.+pub fn autocompactResumed(self: *Agent) void {+ autocompactIf(self, 0, enabled(self.provider));+}+fn autocompactIf(self: *Agent, recovery_meter: u64, server_arm: bool) void {+ const near_limit = self.provider.nearContextLimit(recovery_meter);if (!server_arm or self.provider.kind != .responses) {- self.compactOrRecover(self.provider.nearContextLimit(recovery_meter));+ self.compactOrRecover(near_limit);return;}- if (pruneIf(self, true)) return;- // No blob yet: the server compacts in-stream at the same threshold, so- // trust it at the ordinary compactAt line; the client-side summary (and- // its destructive fallback) is reserved for genuinely near the wall, where- // shipping the request itself would risk an over-cap hard failure (#163).- if (self.provider.nearContextLimit(recovery_meter))- self.compactOrRecover(true);+ const counts = remoteCompact(self) catch |err| {+ if (err == error.Interrupted) return;+ if (main_mod.json_mode)+ self.emit(.{ .type = "compact", .ok = false, .mechanism = "server", .message = @errorName(err), .fallback = "local" })+ else+ self.say("[server compaction unavailable: {t}; falling back to local summary]\n", .{err}) catch {};+ self.compactOrRecover(near_limit);+ return;+ };+ if (main_mod.json_mode)+ self.emit(.{ .type = "compact", .ok = true, .mechanism = "server", .items_before = counts.old, .items_after = counts.new })+ else+ self.say("[server compacted context: replaced {d} history item(s) with {d}]\n", .{ counts.old, counts.new }) catch {};}const test_support = @import("agent_compact_test_support.zig");@@ -229,7 +254,7 @@ fn item(a: std.mem.Allocator, typ: []const u8, call_id: ?[]const u8) !std.json.Vreturn .{ .object = obj };}-test "enabled: responses-only; unassigned defaults to client; override wins" {+test "enabled: OpenAI Responses only; unassigned defaults to client; override wins" {var p: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "m", .context = 272_000 };try std.testing.expect(!enabled(p)); // no assignment in tests → client armp.kind = .anthropic;@@ -237,7 +262,12 @@ test "enabled: responses-only; unassigned defaults to client; override wins" {p.kind = .openai;try std.testing.expect(!enabled(p));p.kind = .responses;+ p.id = "compatible-gateway";g_server_compact_override = true;+ try std.testing.expect(!enabled(p));+ p.id = "codex";+ try std.testing.expect(enabled(p));+ p.id = "openai";try std.testing.expect(enabled(p));g_server_compact_override = false;try std.testing.expect(!enabled(p));@@ -251,97 +281,95 @@ test "armForId: deterministic bucketing of the install id" {_ = armForId(&other); // both buckets are reachable outcomes; no crash, pure}-test "writeContextManagement: threshold mirrors compactAt; silent for other kinds" {+test "compactEndpoint: derives only the standalone Responses endpoint" {+ const a = std.testing.allocator;+ const derived = try compactEndpoint(a, "https://chatgpt.com/backend-api/codex/responses/");+ defer a.free(derived);+ try std.testing.expectEqualStrings("https://chatgpt.com/backend-api/codex/responses/compact", derived);+ try std.testing.expectError(error.InvalidCompactEndpoint, compactEndpoint(a, "https://example.com/v1/chat/completions"));+}++test "compactRequestBody: sends model, instructions, and the complete history" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();var agent = testAgent(a, .responses);- var aw: @import("std").Io.Writer.Allocating = .init(a);- var s: std.json.Stringify = .{ .writer = &aw.writer };- try s.beginObject();- try writeContextManagementBody(&agent, &s);- try s.endObject();- try std.testing.expect(std.mem.indexOf(u8, aw.written(), "\"context_management\":[{\"type\":\"compaction\",\"compact_threshold\":80000}]") != null); // 80% of 100k- agent.provider.kind = .anthropic;- var aw2: @import("std").Io.Writer.Allocating = .init(a);- var s2: std.json.Stringify = .{ .writer = &aw2.writer };- try s2.beginObject();- try writeContextManagement(&agent, &s2);- try s2.endObject();- try std.testing.expectEqualStrings("{}", aw2.written());+ agent.provider.model = "gpt-test";+ agent.sys_normal = "system-test";+ try agent.messages.append(try item(a, "message", null));+ try agent.messages.append(try item(a, "function_call", "call-1"));+ const body = try compactRequestBody(&agent);+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, body, .{});+ try std.testing.expectEqualStrings("gpt-test", parsed.object.get("model").?.string);+ try std.testing.expectEqualStrings("system-test", parsed.object.get("instructions").?.string);+ try std.testing.expectEqual(@as(usize, 2), parsed.object.get("input").?.array.items.len);+ try std.testing.expect(parsed.object.get("context_management") == null);}-test "pruneToLatestBlob: no blob or blob-first leaves history untouched" {+test "writeContextManagement: standalone transaction emits no in-stream directive" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();var agent = testAgent(a, .responses);- try agent.messages.append(try item(a, "message", null));- try std.testing.expect(!pruneIf(&agent, true));- try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);- // blob already at the head: nothing to prune- var agent2 = testAgent(a, .responses);- try agent2.messages.append(try item(a, "compaction", null));- try agent2.messages.append(try item(a, "message", null));- try std.testing.expect(!pruneIf(&agent2, true));- try std.testing.expectEqual(@as(usize, 2), agent2.messages.items.len);- try std.testing.expectEqual(@as(u32, 0), agent2.history_rewrites);+ var aw: Io.Writer.Allocating = .init(a);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.beginObject();+ try writeContextManagement(&agent, &s);+ try s.endObject();+ try std.testing.expectEqualStrings("{}", aw.written());}-test "pruneToLatestBlob: prunes to the newest blob and resets the meters" {+test "installCompactResponse: installs the complete retained history and resets its anchors" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();var agent = testAgent(a, .responses);- try agent.messages.append(try item(a, "message", null)); // pruned- try agent.messages.append(try item(a, "compaction", null)); // older blob — superseded- try agent.messages.append(try item(a, "message", null)); // pruned- try agent.messages.append(try item(a, "compaction", null)); // newest blob- try agent.messages.append(try item(a, "function_call", "c1")); // pair survives intact- try agent.messages.append(try item(a, "function_call_output", "c1"));+ try agent.messages.append(try item(a, "message", null));agent.last_context_tokens = 200_000;agent.context_local_tokens = 190_000;- try std.testing.expect(pruneIf(&agent, true));- try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);- try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);+ const body =+ "{\"output\":[" +++ "{\"type\":\"message\",\"role\":\"user\",\"content\":[{\"type\":\"input_text\",\"text\":\"kept user\"}]}," +++ "{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"kept assistant\"}]}," +++ "{\"type\":\"message\",\"role\":\"user\",\"content\":[{\"type\":\"input_text\",\"text\":\"recent user\"}]}," +++ "{\"type\":\"compaction_summary\",\"encrypted_content\":\"opaque\"}]}";+ const counts = try installCompactResponse(&agent, body);+ try std.testing.expectEqual(@as(usize, 1), counts.old);+ try std.testing.expectEqual(@as(usize, 4), counts.new);+ try std.testing.expectEqual(@as(usize, 4), agent.messages.items.len);+ try std.testing.expectEqualStrings("message", agent.messages.items[0].object.get("type").?.string);+ try std.testing.expectEqualStrings("kept user", agent.messages.items[0].object.get("content").?.array.items[0].object.get("text").?.string);+ try std.testing.expectEqualStrings("compaction_summary", agent.messages.items[3].object.get("type").?.string);try std.testing.expectEqual(@as(u32, 1), agent.history_rewrites);try std.testing.expectEqual(@as(u64, 0), agent.last_context_tokens);try std.testing.expectEqual(@as(u64, 0), agent.context_local_tokens);}-test "pruneToLatestBlob: an orphaned tool output refuses the prune" {+test "installCompactResponse: malformed or empty output preserves the original history" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();var agent = testAgent(a, .responses);- try agent.messages.append(try item(a, "function_call", "c1")); // pruned by the cut- try agent.messages.append(try item(a, "compaction", null));- try agent.messages.append(try item(a, "function_call_output", "c1")); // orphan if pruned- try std.testing.expect(!pruneIf(&agent, true));- try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);-}--test "pruneIf: never fires off the server arm or off responses" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const a = arena_state.allocator();- var agent = testAgent(a, .anthropic);try agent.messages.append(try item(a, "message", null));- try agent.messages.append(try item(a, "compaction", null));- try std.testing.expect(!pruneIf(&agent, true));- try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);+ agent.last_context_tokens = 88_000;+ try std.testing.expectError(error.InvalidCompactResponse, installCompactResponse(&agent, "{not json"));+ try std.testing.expectError(error.EmptyCompactOutput, installCompactResponse(&agent, "{\"output\":[]}"));+ try std.testing.expectError(error.InvalidCompactResponse, installCompactResponse(&agent, "{\"output\":{}}"));+ try std.testing.expectError(error.InvalidCompactResponse, installCompactResponse(&agent, "{\"output\":[{}]}"));+ try std.testing.expectError(error.InvalidCompactResponse, installCompactResponse(&agent, "{\"output\":[{\"type\":7}]}"));+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);+ try std.testing.expectEqualStrings("message", agent.messages.items[0].object.get("type").?.string);+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);+ try std.testing.expectEqual(@as(u64, 88_000), agent.last_context_tokens);}-test "autocompact: responses providers hold at the ordinary threshold without a blob" {+test "installCompactResponse: a non-item output element preserves the original history" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();- var agent = testAgent(a, .responses); // context 100_000+ var agent = testAgent(a, .responses);try agent.messages.append(try item(a, "message", null));- // Over the 80% compactAt line but under the 95% wall, no blob: the server- // owns compaction now, so history must survive untouched (legacy policy- // would have run a summary here).- autocompactIf(&agent, 85_000, true);+ try std.testing.expectError(error.InvalidCompactResponse, installCompactResponse(&agent, "{\"output\":[42]}"));try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);}diff --git a/src/agent_tool_render.zig b/src/agent_tool_render.zigindex 1c651876..691a2574 100644--- a/src/agent_tool_render.zig+++ b/src/agent_tool_render.zig@@ -36,30 +36,59 @@ const ToolInvocation = engine_events.ToolInvocation;const ToolOutcome = engine_events.ToolOutcome;const BatchOutcome = engine_events.BatchOutcome;-/// How much of a call's JSON arguments the ⚙ line shows. A byte cap, not a-/// character one: the cut may split a UTF-8 sequence, exactly as before.-const arg_preview_bytes: usize = 160;+/// Keep tool activity useful without dumping model-facing JSON into the REPL.+const detail_preview_bytes: usize = 96;/// How much of a result's first line the ✓ line shows.const result_preview_bytes: usize = 100;-/// The ⚙ announcement line. Suppressed when the call's prose already streamed-/// live out of its arguments — the line would just repeat what was read.+fn stringField(input: std.json.Value, field: []const u8) ?[]const u8 {+ if (input != .object) return null;+ const value = input.object.get(field) orelse return null;+ return if (value == .string) value.string else null;+}++/// Pick one human-readable field for tools whose intent is obvious from a path,+/// command, URL, or short label. Unknown tools still get a name-only line.+fn toolDetail(t: ToolInvocation) []const u8 {+ const field = if (std.mem.eql(u8, t.name, "bash"))+ "command"+ else if (std.mem.eql(u8, t.name, "read_file") or+ std.mem.eql(u8, t.name, "edit_file") or+ std.mem.eql(u8, t.name, "write_file"))+ "path"+ else if (std.mem.eql(u8, t.name, "webfetch"))+ "url"+ else if (std.mem.eql(u8, t.name, "codedb"))+ "command"+ else if (std.mem.eql(u8, t.name, "subagent"))+ "description"+ else if (std.mem.eql(u8, t.name, "imagegen"))+ "prompt"+ else if (std.mem.eql(u8, t.name, "peer_message"))+ "text"+ else+ return "";+ const detail = stringField(t.input, field) orelse return "";+ const end = std.mem.indexOfScalar(u8, detail, '\n') orelse detail.len;+ return std.mem.trim(u8, detail[0..end], " \t\r");+}++/// A terse activity line: always show ordinary tool calls, but never their raw+/// argument object. Suppress only user-facing prose that already streamed live.pub fn toolUseLine(a: *Agent, t: ToolInvocation) void {if (t.arg_streamed) return;- var args: Io.Writer.Allocating = .init(a.gpa);- defer args.deinit();- var s: std.json.Stringify = .{ .writer = &args.writer };- s.write(t.input) catch return;- const full = args.writer.buffered();- const shown = if (full.len > arg_preview_bytes) full[0..arg_preview_bytes] else full;+ const detail = toolDetail(t);+ const shown = if (detail.len > detail_preview_bytes) detail[0..detail_preview_bytes] else detail;var line: Io.Writer.Allocating = .init(a.gpa);defer line.deinit();- line.writer.print("{s}⚙{s} {s}{s} {s}{s}{s}{s}\n", .{- style.dim, style.reset, style.accent, t.name,- style.dim, shown,- if (full.len > arg_preview_bytes) "…" else "",+ line.writer.print("{s}⚙{s} {s}{s}{s}", .{ style.dim, style.reset, style.accent, t.name, style.reset }) catch return;+ if (shown.len > 0) line.writer.print("{s} · {s}{s}{s}", .{+ style.dim,+ shown,+ if (shown.len < detail.len) "…" else "",style.reset,}) catch return;+ line.writer.writeByte('\n') catch return;sayText(a, line.writer.buffered());}@@ -83,12 +112,11 @@ pub fn toolResultLine(a: *Agent, r: ToolOutcome) void {(std.fmt.bufPrint(&tbuf, " ({d}ms)", .{r.ms}) catch "")else"";- w.print(" {s}{s}{s}{s}{s}{s} {s}{s}{s}{s}\n", .{- mc, mark, style.reset, style.dim, timing, style.reset,- style.dim, shown,- if (truncated) "…" else "",- style.reset,+ w.print(" {s}{s}{s} {s}{s}{s}{s}{s}", .{+ mc, mark, style.reset, style.accent, r.name, style.reset, style.dim, timing,}) catch return;+ if (shown.len > 0) w.print(" · {s}{s}", .{ shown, if (truncated) "…" else "" }) catch return;+ w.print("{s}\n", .{style.reset}) catch return;w.flush() catch return;}@@ -155,24 +183,27 @@ test "the ⚙ line reproduces the old inline announcement, cap and ellipsis inclconst input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"fixture.txt\"}", .{});toolUseLine(&a, .{ .name = "read_file", .input = input });- try std.testing.expectEqualStrings("⚙ read_file {\"path\":\"fixture.txt\"}\n", aw.writer.buffered());+ try std.testing.expectEqualStrings("⚙ read_file · fixture.txt\n", aw.writer.buffered());// Prose that already streamed live is not announced a second time.aw.clearRetainingCapacity();toolUseLine(&a, .{ .name = "attempt_completion", .input = input, .arg_streamed = true });try std.testing.expectEqualStrings("", aw.writer.buffered());- // Over the cap: exactly arg_preview_bytes of JSON, then the ellipsis.+ // Unknown tools remain visible without leaking arbitrary argument JSON.+ aw.clearRetainingCapacity();+ toolUseLine(&a, .{ .name = "todo_write", .input = input });+ try std.testing.expectEqualStrings("⚙ todo_write\n", aw.writer.buffered());++ // Long readable details are capped to one terse line.aw.clearRetainingCapacity();- const long = try std.fmt.allocPrint(arena_state.allocator(), "{{\"q\":\"{s}\"}}", .{&util.repeatBytes("x", 400)});+ const long = try std.fmt.allocPrint(arena_state.allocator(), "{{\"command\":\"{s}\"}}", .{&util.repeatBytes("x", 400)});const long_input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), long, .{});- toolUseLine(&a, .{ .name = "codedb", .input = long_input });+ toolUseLine(&a, .{ .name = "bash", .input = long_input });const line = aw.writer.buffered();- try std.testing.expect(std.mem.startsWith(u8, line, "⚙ codedb {\"q\":\"xxx"));+ try std.testing.expect(std.mem.startsWith(u8, line, "⚙ bash · xxx"));try std.testing.expect(std.mem.endsWith(u8, line, "…\n"));- // The literal, not arg_preview_bytes: this asserts the conversion kept the- // pre-#422 inline cap, and asserting the constant against itself would not.- try std.testing.expectEqual(@as(usize, 160), line.len - "⚙ codedb ".len - "…\n".len);+ try std.testing.expectEqual(@as(usize, 96), line.len - "⚙ bash · ".len - "…\n".len);}test "the result line marks success, failure and cancellation and previews one line" {@@ -187,15 +218,15 @@ test "the result line marks success, failure and cancellation and previews one lvar a = testAgent(&aw.writer);toolResultLine(&a, .{ .name = "read_file", .text = "line one\nline two\n", .is_error = false });- try std.testing.expectEqualStrings(" ✓ line one…\n", aw.writer.buffered());+ try std.testing.expectEqualStrings(" ✓ read_file · line one…\n", aw.writer.buffered());aw.clearRetainingCapacity();toolResultLine(&a, .{ .name = "bash", .text = "boom", .is_error = true });- try std.testing.expectEqualStrings(" ✗ boom\n", aw.writer.buffered());+ try std.testing.expectEqualStrings(" ✗ bash · boom\n", aw.writer.buffered());aw.clearRetainingCapacity();toolResultLine(&a, .{ .name = "bash", .text = "stopped", .is_error = true, .cancelled = true });- try std.testing.expectEqualStrings(" ⊘ stopped\n", aw.writer.buffered());+ try std.testing.expectEqualStrings(" ⊘ bash · stopped\n", aw.writer.buffered());// Meta tools draw their own UX; the ✓ line stays out of their way.aw.clearRetainingCapacity();@@ -209,13 +240,13 @@ test "the result line marks success, failure and cancellation and previews one ltoolResultLine(&a, .{ .name = "bash", .text = &long, .is_error = false });const rline = aw.writer.buffered();try std.testing.expect(std.mem.endsWith(u8, rline, "…\n"));- try std.testing.expectEqual(@as(usize, 100), rline.len - " ✓ ".len - "…\n".len);+ try std.testing.expectEqual(@as(usize, 100), rline.len - " ✓ bash · ".len - "…\n".len);// --timing adds the measured duration between the mark and the preview.aw.clearRetainingCapacity();main_mod.show_timing = true;toolResultLine(&a, .{ .name = "bash", .text = "ok", .is_error = false, .ms = 42 });- try std.testing.expectEqualStrings(" ✓ (42ms) ok\n", aw.writer.buffered());+ try std.testing.expectEqualStrings(" ✓ bash (42ms) · ok\n", aw.writer.buffered());}test "batch tallies and meta notices render the old wording verbatim" {diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 6ea41af3..dbb7e469 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -57,7 +57,8 @@ const drainSteerStdin = Agent.drainSteerStdin;/// back this session. Subagents/quiet turns keep the non-streaming SSE path.pub fn wsEligible(self: *Agent) bool {return main_mod.g_codex_ws and !self.ws_off and !self.sub and- self.provider.kind == .responses and self.out != null and !self.stream_quiet;+ self.provider.kind == .responses and std.mem.eql(u8, self.provider.id, "codex") and+ self.out != null and !self.stream_quiet;}/// (#codex-ws) Client-side idle limit on the held codex WS, opencode'sdiff --git a/src/cli.zig b/src/cli.zigindex 67cc4976..68f2d100 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -21,6 +21,11 @@ const harness_version = root.harness_version;pub const changelog_text =\\What's new\\──────────+ \\0.0.250+ \\ • First-party OpenAI compaction preserves the complete canonical compact output on both Codex subscription and official Platform Responses routes+ \\ • Invalid remote compaction falls back locally without mutating history; non-OpenAI providers remain local-only+ \\ • REPL tool calls use stable terse start/result rows with readable previews instead of raw JSON+ \\\\0.0.249\\ • Folded native tools become callable as soon as their schemas load; the active catalog now rebuilds instead of advertising unreachable tools\\ • Turn events and generated TypeScript SDKs expose cumulative input, output, cache-read, and cache-write token usagediff --git a/src/commands_model.zig b/src/commands_model.zigindex 8b3f3f66..1bcbf896 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -305,7 +305,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,_ = saveThinkingSettings(root.io, root.gpa, root.reasoning, root.fast, root.ultracode_mode, root.show_thinking, root.ai_title);try out.print("fast mode: {s}{s}\n", .{if (root.fast) "on" else "off",- if (root.provider.kind != .responses) " (codex only — current model ignores it)" else "",+ if (!std.mem.eql(u8, root.provider.id, "codex")) " (codex only — current model ignores it)" else "",});try out.flush();return true;diff --git a/src/engine_sink.zig b/src/engine_sink.zigindex 7e5e1a13..b579911b 100644--- a/src/engine_sink.zig+++ b/src/engine_sink.zig@@ -237,8 +237,8 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {// the one file down here that still reaches the palette; the moments// the terminal never drew (the dispatch/close brackets, refusals) are// silent rather than absent from the vocabulary.- .tool_call_announced => |t| if (repl.g_debug) tool_render.toolUseLine(a, t),- .tool_result => |r| if (repl.g_debug) tool_render.toolResultLine(a, r),+ .tool_call_announced => |t| tool_render.toolUseLine(a, t),+ .tool_result => |r| tool_render.toolResultLine(a, r),.tool_call_started, .tool_call_finished, .tool_rejected => {},.parallel_batch_started => |b| if (repl.g_debug) tool_render.parallelBatchStarted(a, b.count),.parallel_batch_finished => |b| if (repl.g_debug) tool_render.parallelBatchFinished(a, b),diff --git a/src/engine_sink_tests.zig b/src/engine_sink_tests.zigindex 0a429835..23cd745e 100644--- a/src/engine_sink_tests.zig+++ b/src/engine_sink_tests.zig@@ -281,16 +281,12 @@ test "TuiSink keeps tool diagnostics behind REPL debug mode (slice 1c)" {const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "line one\nline two\n", .is_error = false };s.emit(undefined, .{ .tool_call_announced = call });- s.emit(undefined, .{ .tool_result = done });- try std.testing.expectEqualStrings("", aw.writer.buffered());-- repl.g_debug = true;- s.emit(undefined, .{ .tool_call_announced = call });s.emit(undefined, .{ .tool_call_started = call }); // silent: the ⚙ line already said its.emit(undefined, .{ .tool_result = done });s.emit(undefined, .{ .tool_call_finished = done }); // silents.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } }); // silent- try std.testing.expectEqualStrings("⚙ read_file {\"path\":\"fixture.txt\"}\n ✓ line one…\n", aw.writer.buffered());+ // Exactly the two lines the eval golden's tool turn shows, even without debug diagnostics.+ try std.testing.expectEqualStrings("⚙ read_file · fixture.txt\n ✓ read_file · line one…\n", aw.writer.buffered());}test "TuiSink renders a plain text delta exactly as the no-color TTY did" {diff --git a/src/http_headers.zig b/src/http_headers.zigindex 8d4224a8..ab1081c7 100644--- a/src/http_headers.zig+++ b/src/http_headers.zig@@ -93,7 +93,9 @@ pub fn providerHeaders(io: Io, provider: Provider, bearer: []const u8, buf: *[12const identity = kimi_catalog.identityHeaders(buf[count..]);count += identity.len;}- if (provider.kind == .responses) {+ // These identify the ChatGPT/Codex backend. The official Platform Responses+ // endpoint needs only normal bearer auth and rejects backend-only identity.+ if (std.mem.eql(u8, provider.id, "codex")) {buf[count] = .{ .name = "chatgpt-account-id", .value = provider.account };count += 1;buf[count] = .{ .name = "OpenAI-Beta", .value = "responses=experimental" };@@ -136,6 +138,16 @@ test "session_id is a stable per-process UUIDv4, not a shared constant" {return error.SessionIdHeaderMissing;}+test "official OpenAI Responses uses Platform headers, not ChatGPT backend identity" {+ const io = std.testing.io;+ var buf: [12]std.http.Header = undefined;+ const p: Provider = .{ .id = "openai", .kind = .responses, .auth = .bearer, .url = "https://api.openai.com/v1/responses", .api_key = "k", .model = "gpt-5.6", .context = 272_000 };+ const headers = providerHeaders(io, p, "Bearer k", &buf);+ try std.testing.expectEqual(@as(usize, 1), headers.len);+ try std.testing.expectEqualStrings("authorization", headers[0].name);+ try std.testing.expectEqualStrings("Bearer k", headers[0].value);+}+test "adoptSessionId validates length and never overwrites a minted id" {const io = std.testing.io;const before = sessionId(io); // minted by whichever test ran firstdiff --git a/src/provider.zig b/src/provider.zigindex 8f11c013..72d392be 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -72,7 +72,7 @@ pub const provider_specs = [_]ProviderSpec{.{ .id = "anthropic", .display_name = "Anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "https://api.anthropic.com/v1/messages", .env_key = "ANTHROPIC_API_KEY", .default_model = "claude-opus-4-8", .catalog = .anthropic, .models_url = "https://api.anthropic.com/v1/models?limit=1000" },.{ .id = "codegraff", .display_name = "Codegraff", .kind = .openai, .auth = .bearer, .url = "https://gateway.codegraff.com/v1/chat/completions", .env_key = "CODEGRAFF_API_KEY", .default_model = "deepseek-v4-pro", .login = .codegraff_device, .catalog = .openai, .models_url = "https://gateway.codegraff.com/v1/models", .takes_effort = true },.{ .id = "deepseek", .display_name = "DeepSeek", .kind = .openai, .auth = .bearer, .url = "https://api.deepseek.com/chat/completions", .env_key = "DEEPSEEK_API_KEY", .default_model = "deepseek-v4-pro", .takes_effort = true },- .{ .id = "openai", .display_name = "OpenAI", .kind = .openai, .auth = .bearer, .url = "https://api.openai.com/v1/chat/completions", .env_key = "OPENAI_API_KEY", .default_model = "gpt-5.6" },+ .{ .id = "openai", .display_name = "OpenAI", .kind = .responses, .auth = .bearer, .url = "https://api.openai.com/v1/responses", .env_key = "OPENAI_API_KEY", .default_model = "gpt-5.6" },.{ .id = "minimax", .display_name = "MiniMax", .kind = .anthropic, .auth = .bearer, .url = "https://api.minimax.io/anthropic/v1/messages", .env_key = "MINIMAX_API_KEY", .default_model = "MiniMax-M3" },.{ .id = "xiaomi", .display_name = "Xiaomi", .kind = .openai, .auth = .bearer, .url = "https://api.xiaomimimo.com/v1/chat/completions", .env_key = "XIAOMI_API_KEY", .default_model = "mimo-v2.5-pro" },.{ .id = "kilo", .display_name = "Kilo Gateway", .kind = .openai, .auth = .bearer, .url = "https://api.kilo.ai/api/gateway/v1/chat/completions", .env_key = "KILO_API_KEY", .default_model = "kilo-auto/small" },@@ -149,8 +149,8 @@ pub const Provider = struct {account: []const u8 = "", // ChatGPT account id, codex/responses onlysource: Keys.CredentialSource = .none, // #148: how api_key was obtained — only .login tokens auto-refresh- // Wire format. `responses` is the OpenAI Responses API as served by the- // ChatGPT backend (Codex login) — input items, not chat messages.+ // Wire format. `responses` is the first-party OpenAI Responses API as served+ // by both the Platform endpoint and ChatGPT backend — input items, not chat messages.pub const Kind = enum { anthropic, openai, responses };pub const Auth = enum { x_api_key, bearer };diff --git a/src/session_run.zig b/src/session_run.zigindex 175182fc..c5b507d6 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -371,7 +371,7 @@ pub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod/// overflow can still override this.pub fn compactResumedSession(root: *agent_mod.Agent) void {if (root.inputOverCompactThreshold()) {- root.compactOrRecover(false);+ root.autocompactResumed();}}