From bf45ee494cfb5e1f917ccdb4921e15f780e099c7 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 12:05:15 -0800 Subject: [PATCH 1/3] feat(agents): Hermes and Codex give each turn's counts by model Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/AGENTS.md | 7 +-- .../agents/agents/codex/a2a_server.py | 37 ++++++++++++--- .../agents/agents/codex/codex_bridge.py | 40 ++++++++++++++++- .../agents/agents/codex/requirements.txt | 6 +-- src/agent_env/agents/agents/hermes/README.md | 4 +- .../agents/agents/hermes/a2a_server.py | 21 +++++++++ .../agents/agents/hermes/hermes_bridge.py | 13 +++--- .../agents/agents/hermes/requirements.txt | 6 +-- tst/unit/agents/codex/test_image_contract.py | 2 +- tst/unit/agents/codex/test_usage.py | 45 ++++++++++++++++--- .../agents/hermes/test_message_contract.py | 45 +++++++++++++++++-- 11 files changed, 192 insertions(+), 34 deletions(-) diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index a63bbbff5..89db3aa41 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -63,9 +63,10 @@ terminal state, `completed`, `failed` or `canceled`. Your `run()` is one turn. included (Claude Code's `result` events count only the main agent's). A cost the runtime couldn't price is unset, never 0. When the runtime knows each call's model, give the turn's counts by model in `Usage.models` on every turn (Claude Code from `modelUsage`, Gemini from its proxy's calls, OpenCode and Letta Code from the shared relay, which - reads each request's model): one `ModelUsage` per model, covering every call the turn counted, a call it can't name - under the configured model, so the host prices a subagent or side call on another model at that model's rate. Code - that sets these fields needs a `requirements.txt` protocol floor at the first release that has them. + reads each request's model, Codex from each thread's rollout, Hermes from the model its calls named): one `ModelUsage` + per model, covering every call the turn counted, a call it can't name under the configured model, so the host prices + a subagent or side call on another model at that model's rate. Code that sets these fields needs a + `requirements.txt` protocol floor at the first release that has them. - **Errors:** `agent_error`, the default, means the agent tried and failed; `infra_error` means the run couldn't happen, and agent-env may retry it. An exception that escapes `run()` becomes an opaque `infra_error`, its text never sent. diff --git a/src/agent_env/agents/agents/codex/a2a_server.py b/src/agent_env/agents/agents/codex/a2a_server.py index c8bea369f..05af7727a 100644 --- a/src/agent_env/agents/agents/codex/a2a_server.py +++ b/src/agent_env/agents/agents/codex/a2a_server.py @@ -47,6 +47,7 @@ ContextObjectTrajectoryRequest, ContextTrajectoryRequest, InlineSkillRequest, + ModelUsage, ObjectSnapshotLoadRequest, ObjectSnapshotSaveRequest, SkillAddResponse, @@ -67,6 +68,7 @@ from codex_bridge import ( SESSIONS_DIR, CodexResult, + ThreadCalls, find_rollout_path, get_last_attribution_snapshot, kill_running_clis, @@ -571,12 +573,13 @@ async def _stage_granted_workspace(source: ReadObject | None) -> Path | None: _INSTALL_COMMANDS_HOST = [_UNPACK, _ENDPOINT + f"bash {{work_dir}}/agent/install.sh host {{agent_name}} {{a2a_port}} {_HOST_WORKDIR}"] -def _usage(result: CodexResult) -> Usage: +def _usage(result: CodexResult, model: str | None = None) -> Usage: """The turn's tool calls and token counts: the CLI's own, for this turn alone, its subagents' included - (``token_usage``). OpenAI counts the cache in a call's input, so ``input_tokens`` holds the cached reads and writes, - and the reasoning is part of ``output_tokens``. A turn the CLI gave no counts for, as one whose counters went back, - reports none, its model requests counted in ``unreported_calls`` rather than as nothing used; a turn the bridge - stopped counts there too the request that was in flight, which the CLI never counted.""" + (``token_usage``), by the model each thread ran on (``models``). OpenAI counts the cache in a call's input, so + ``input_tokens`` holds the cached reads and writes, and the reasoning is part of ``output_tokens``. A turn the CLI + gave no counts for, as one whose counters went back, reports none, its model requests counted in + ``unreported_calls`` rather than as nothing used; a turn the bridge stopped counts there too the request that was in + flight, which the CLI never counted.""" counts = result.token_usage or {} details: dict[str, Any] = {} if result.model_requests is not None: @@ -593,7 +596,27 @@ def _usage(result: CodexResult) -> Usage: return Usage(tool_call_count=result.tool_call_count, input_tokens=inputs, output_tokens=outputs, total_tokens=inputs + outputs, cache_read_tokens=counts.get("cached_input_tokens"), cache_write_tokens=counts.get("cache_write_input_tokens"), input_includes_cache=True, - provider_details=details) + models=_by_model(result.threads, model), provider_details=details) + + +def _by_model(threads: list[ThreadCalls], model: str | None) -> tuple[ModelUsage, ...]: + """The threads' counts by the model each ran on, a subagent's as ``spawn_agent`` chose it, one whose rollout names + none counted as ``model``'s, the turn's; none when no model is known for a thread.""" + by_model: dict[str, list[ThreadCalls]] = {} + for thread in threads: + if not (name := thread.model or model): + return () + by_model.setdefault(name, []).append(thread) + + def total(name: str, of: list[ThreadCalls]) -> int | None: + values = [thread.counts[name] for thread in of if name in thread.counts] + return sum(values) if values else None + + return tuple(ModelUsage( + model=name, calls=None if any(thread.requests is None for thread in of) else sum(t.requests for t in of), + input_tokens=total("input_tokens", of), output_tokens=total("output_tokens", of), + cache_read_tokens=total("cached_input_tokens", of), cache_write_tokens=total("cache_write_input_tokens", of), + input_includes_cache=True) for name, of in by_model.items()) @a2a_agent( @@ -767,7 +790,7 @@ def _record_event(event: dict) -> None: .add_text(result.response or (result.error or "")) .add_data(data) .session_ref(result.session_id) - .usage(_usage(result)) + .usage(_usage(result, cfg.model)) .build() ) diff --git a/src/agent_env/agents/agents/codex/codex_bridge.py b/src/agent_env/agents/agents/codex/codex_bridge.py index 51ca3fb0a..c03078381 100644 --- a/src/agent_env/agents/agents/codex/codex_bridge.py +++ b/src/agent_env/agents/agents/codex/codex_bridge.py @@ -113,6 +113,16 @@ def cli_env(environ: Mapping[str, str], *, project_id: str | None = None, return env +@dataclass +class ThreadCalls: + """One thread's share of a turn, the turn's own or a subagent's: the model its rollout last ran on (its + ``turn_context``), its counts and its model requests.""" + + model: str | None + counts: dict[str, int] + requests: int | None + + @dataclass class CodexResult: response: str @@ -128,6 +138,8 @@ class CodexResult: usage: dict = field(default_factory=dict) token_usage: dict | None = None model_requests: int | None = None + # The threads `token_usage` sums, the turn's own first. + threads: list[ThreadCalls] = field(default_factory=list) # A model request the bridge's own stop cut short: the CLI counts a response only once it completes, so the one in # flight when the bridge stopped it at its tool-call limit, timeout or stall is in neither count. A stop during a # tool call cut none: the response that asked for the tool was counted. @@ -291,6 +303,27 @@ def read_rollout_usage(thread_id: str | None) -> dict[str, int] | None: return None +def read_rollout_model(thread_id: str | None) -> str | None: + """The model a native rollout's last turn ran on, as its ``turn_context`` names it.""" + path = find_rollout_path(thread_id) if thread_id else None + if path is None: + return None + try: + lines = path.read_text(errors="replace").splitlines() + except OSError: + return None + for line in reversed(lines): + try: + record = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(record, dict) and record.get("type") == "turn_context": + model = (record.get("payload") or {}).get("model") + if isinstance(model, str) and model: + return model + return None + + def read_rollout_requests(thread_id: str | None) -> int | None: """How many model requests a native rollout records: its token counts that raised the thread's total.""" path = find_rollout_path(thread_id) if thread_id else None @@ -353,8 +386,9 @@ def _add_subagent_calls(result: CodexResult, baselines: Mapping[str, tuple[dict[ """Adds what the turn's subagents used since the turn began to its own counts.""" for child in subagent_threads(result.session_id): usage, requests = baselines.get(child, (None, 0)) + made = (read_rollout_requests(child) or 0) - requests if result.model_requests is not None: - result.model_requests += (read_rollout_requests(child) or 0) - requests + result.model_requests += made current = read_rollout_usage(child) if result.token_usage is None or current is None: continue @@ -365,6 +399,7 @@ def _add_subagent_calls(result: CodexResult, baselines: Mapping[str, tuple[dict[ continue result.token_usage = {key: result.token_usage.get(key, 0) + delta.get(key, 0) for key in {**result.token_usage, **delta}} + result.threads.append(ThreadCalls(read_rollout_model(child), delta, made)) def _usage_delta( @@ -1049,6 +1084,9 @@ async def run_codex( "incremental usage is unavailable" ) result.warnings.append(warning) + else: + result.threads = [ThreadCalls(read_rollout_model(result.session_id), dict(result.token_usage), + result.model_requests)] _add_subagent_calls(result, subagent_baselines) return result diff --git a/src/agent_env/agents/agents/codex/requirements.txt b/src/agent_env/agents/agents/codex/requirements.txt index a72bf962b..602ef6008 100644 --- a/src/agent_env/agents/agents/codex/requirements.txt +++ b/src/agent_env/agents/agents/codex/requirements.txt @@ -1,7 +1,7 @@ # The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the -# image is built again only when this folder changes. The floor is the first whose Usage takes the prompt cache's -# counts (cache_read_tokens, cache_write_tokens, input_includes_cache); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.597 +# image is built again only when this folder changes. The floor is the first whose Usage gives a turn's counts by +# model (Usage.models); raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.640 tomli-w==1.2.0 # The CA certificates an installed agent's CLI trusts on a target that has none of its own; unpinned, so each build # takes the newest. diff --git a/src/agent_env/agents/agents/hermes/README.md b/src/agent_env/agents/agents/hermes/README.md index 822785e0c..0d146e300 100644 --- a/src/agent_env/agents/agents/hermes/README.md +++ b/src/agent_env/agents/agents/hermes/README.md @@ -46,7 +46,9 @@ the model no one is there to answer. A turn's usage counts every model call the turn made: its main calls and its auxiliary ones (title generation, compression), as Hermes' usage file reports them, and a `delegate_task` child's, from their `post_api_request` events, which the file leaves out. A turn killed before it wrote the file keeps the calls its events counted, marked as a lower -bound. Hermes' estimated cost is kept only where it priced the calls. The profile turns Hermes' background review off: +bound. The turn's counts are its model's (`Usage.models`): Hermes runs its auxiliary tasks on the main model and a +child inherits it, as the profile pins no other, so a turn whose calls named several models gives no breakdown. Hermes' +estimated cost is kept only where it priced the calls. The profile turns Hermes' background review off: its fork outlives the turn's process, which kills it before it reports what the proxy billed. The image is `python:3.11-slim` with Hermes, `pdftoppm` and the agent, running as the `agent` user. Hermes' runtime (its own Python, Node and ripgrep) and the profiles are under `/data/.hermes`, whatever the uid. It has no `install/v1`. diff --git a/src/agent_env/agents/agents/hermes/a2a_server.py b/src/agent_env/agents/agents/hermes/a2a_server.py index f8b2d4307..e26fe993e 100644 --- a/src/agent_env/agents/agents/hermes/a2a_server.py +++ b/src/agent_env/agents/agents/hermes/a2a_server.py @@ -11,6 +11,7 @@ import base64 import binascii import contextlib +import dataclasses import functools import json import logging @@ -45,6 +46,7 @@ DataPart, FilePart, InlineSkillRequest, + ModelUsage, ObjectSnapshotLoadRequest, ObjectSnapshotSaveRequest, SkillAddResponse, @@ -529,6 +531,25 @@ def _count(report: dict, name: str) -> int | None: def _usage(result) -> Usage: + """The turn's usage (``_counts``), its counts given as its model's when every call it made named one: Hermes runs + its auxiliary tasks on the main model, and a delegate_task child inherits it, as the bridge's config pins no other + for either. A turn whose calls named several models gives none rather than guess how they split.""" + usage = _counts(result) + calls = result.killed_calls if result.killed_calls is not None else result.side_calls + named = set(calls.models) if calls is not None else set() + if result.killed_calls is None and isinstance(model := result.usage.get("model"), str) and model: + named.add(model) + if len(named) != 1 or (usage.input_tokens is None and usage.output_tokens is None): + return usage + (model,) = named + return dataclasses.replace(usage, models=(ModelUsage( + model=model, calls=usage.provider_details.get("api_calls"), input_tokens=usage.input_tokens, + output_tokens=usage.output_tokens, cache_read_tokens=usage.cache_read_tokens, + cache_write_tokens=usage.cache_write_tokens, input_includes_cache=usage.input_includes_cache, + cost_usd=usage.cost_usd),)) + + +def _counts(result) -> Usage: """The turn's tool calls and token counts, with ``input_tokens`` counting the cache: its main model calls as Hermes' usage file counts them, its auxiliary calls (title generation, compression) as the file's ``auxiliary`` block counts them, and a delegate_task child's calls, which the file leaves out, from their events. Hermes' diff --git a/src/agent_env/agents/agents/hermes/hermes_bridge.py b/src/agent_env/agents/agents/hermes/hermes_bridge.py index a52626bc9..8d1230fcb 100644 --- a/src/agent_env/agents/agents/hermes/hermes_bridge.py +++ b/src/agent_env/agents/agents/hermes/hermes_bridge.py @@ -64,8 +64,8 @@ def profile_dir(context_id: str) -> Path: @dataclass class CallCounts: - """Model calls' counts as their post_api_request events give them, with ``input_tokens`` counting the cache; a call - whose event carried no usage is counted in ``unreported``.""" + """Model calls' counts as their post_api_request events give them, with ``input_tokens`` counting the cache, and the + models they named; a call whose event carried no usage is counted in ``unreported``.""" input_tokens: int = 0 output_tokens: int = 0 @@ -73,9 +73,12 @@ class CallCounts: cache_write_tokens: int = 0 calls: int = 0 unreported: int = 0 + models: set[str] = field(default_factory=set) - def add(self, usage: object) -> None: + def add(self, usage: object, model: object = None) -> None: self.calls += 1 + if isinstance(model, str) and model: + self.models.add(model) if not isinstance(usage, dict) or not (usage.get("prompt_tokens") or usage.get("output_tokens")): self.unreported += 1 return @@ -494,9 +497,9 @@ def on_line(self, line: str) -> None: if isinstance(event.get("session_id"), str) and event["session_id"] and not theirs: self.session_id = event["session_id"] if kind == "post_api_request": - self.all_calls.add(event.get("usage")) + self.all_calls.add(event.get("usage"), event.get("model")) if theirs: - self.side_calls.add(event.get("usage")) + self.side_calls.add(event.get("usage"), event.get("model")) if kind == "pre_tool_call": self.tool_calls.add(str(event.get("tool_call_id") or f"tool-{len(self.tool_calls)}")) elif kind == "post_llm_call" and isinstance(event.get("assistant_response"), str): diff --git a/src/agent_env/agents/agents/hermes/requirements.txt b/src/agent_env/agents/agents/hermes/requirements.txt index 219eb7912..e66ad8f4c 100644 --- a/src/agent_env/agents/agents/hermes/requirements.txt +++ b/src/agent_env/agents/agents/hermes/requirements.txt @@ -1,5 +1,5 @@ # The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the -# image is built again only when this folder changes. The floor is the first whose Usage takes the prompt cache's -# counts (cache_read_tokens, cache_write_tokens, input_includes_cache); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.597 +# image is built again only when this folder changes. The floor is the first whose Usage gives a turn's counts by +# model (Usage.models); raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.640 jsonschema>=4.18,<5 diff --git a/tst/unit/agents/codex/test_image_contract.py b/tst/unit/agents/codex/test_image_contract.py index eb5be7407..0ba67d776 100644 --- a/tst/unit/agents/codex/test_image_contract.py +++ b/tst/unit/agents/codex/test_image_contract.py @@ -54,7 +54,7 @@ def test_the_requirements_are_the_protocol_floor_the_config_writer_and_the_ca_bu requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] - assert requirements == ["agentenv-framework-protocol[agent]>=0.1.597", "tomli-w==1.2.0", "certifi"] + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.640", "tomli-w==1.2.0", "certifi"] def test_the_image_gives_the_models_python_the_document_libraries(): diff --git a/tst/unit/agents/codex/test_usage.py b/tst/unit/agents/codex/test_usage.py index b0510a660..c389055a2 100644 --- a/tst/unit/agents/codex/test_usage.py +++ b/tst/unit/agents/codex/test_usage.py @@ -5,7 +5,7 @@ import asyncio import json -from agentenv_protocol.a2a_agent import Usage +from agentenv_protocol.a2a_agent import ModelUsage, Usage from tst.unit.agents.codex.agent import a2a_server, codex_bridge @@ -95,12 +95,16 @@ async def exercise(): SUBAGENT_CALLS = [(PARENT, 11873, 0, 62), (CHILD, 11491, 2432, 11), (PARENT, 11957, 11776, 21), (PARENT, 12040, 11904, 5)] -def _write_rollout(sessions, thread, calls, parent=None): - """A thread's rollout as Codex writes it: its session_meta, then the thread's running total after each call.""" +def _write_rollout(sessions, thread, calls, parent=None, model=None): + """A thread's rollout as Codex writes it: its session_meta, the turn_context naming its model when one is given, + then the thread's running total after each call.""" meta = {"id": thread, "source": "exec"} if parent: meta |= {"parent_thread_id": parent, "source": {"subagent": {"thread_spawn": {"parent_thread_id": parent}}}} - records, total = [{"type": "session_meta", "payload": meta}], dict.fromkeys( + records = [{"type": "session_meta", "payload": meta}] + if model: + records.append({"type": "turn_context", "payload": {"cwd": "/app", "model": model, "effort": "medium"}}) + total = dict.fromkeys( ("input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"), 0) for inputs, cached, outputs in calls: total = {**total, "input_tokens": total["input_tokens"] + inputs, @@ -114,13 +118,13 @@ def _write_rollout(sessions, thread, calls, parent=None): def _turn(monkeypatch, tmp_path, rollouts, thread_id=None): - """Runs a turn whose CLI leaves ``rollouts`` (thread, calls, parent) behind.""" + """Runs a turn whose CLI leaves ``rollouts`` (thread, calls, parent, and optionally its model) behind.""" sessions = tmp_path / "sessions" monkeypatch.setattr(codex_bridge, "SESSIONS_DIR", sessions) async def cli(**kwargs): - for thread, calls, parent in rollouts: - _write_rollout(sessions, thread, calls, parent) + for thread, calls, parent, *model in rollouts: + _write_rollout(sessions, thread, calls, parent, *model) return codex_bridge.CodexResult(response="42", tool_call_count=1, session_id=PARENT) monkeypatch.setattr(codex_bridge, "_run_codex_once", cli) @@ -160,3 +164,30 @@ def test_a_later_turn_counts_only_what_its_subagents_used_in_it(monkeypatch, tmp assert result.model_requests == 3 assert {key: result.token_usage[key] for key in ("input_tokens", "cached_input_tokens", "output_tokens")} == { "input_tokens": 200 + 60 + 30, "cached_input_tokens": 100 + 40, "output_tokens": 2 + 3 + 4} + + +def test_a_turns_counts_are_given_by_the_model_each_thread_ran_on(monkeypatch, tmp_path): + """A subagent ``spawn_agent`` started on another model is that model's; the parent's calls are its own model's.""" + calls = {PARENT: [], CHILD: []} + for thread, *counts in SUBAGENT_CALLS: + calls[thread].append(counts) + + result = _turn(monkeypatch, tmp_path, [(PARENT, calls[PARENT], None, "gpt-5.3-codex"), + (CHILD, calls[CHILD], PARENT, "gpt-5.4-mini")]) + usage = a2a_server._usage(result, "gpt-5.3-codex") + + assert usage.models == ( + ModelUsage(model="gpt-5.3-codex", calls=3, input_tokens=11873 + 11957 + 12040, output_tokens=62 + 21 + 5, + cache_read_tokens=11776 + 11904, input_includes_cache=True), + ModelUsage(model="gpt-5.4-mini", calls=1, input_tokens=11491, output_tokens=11, cache_read_tokens=2432, + input_includes_cache=True)) + assert sum(row.input_tokens for row in usage.models) == usage.input_tokens + + +def test_a_thread_whose_rollout_names_no_model_counts_as_the_turns_and_none_known_gives_no_rows(monkeypatch, tmp_path): + result = _turn(monkeypatch, tmp_path, [(PARENT, [(100, 0, 1)], None), + (CHILD, [(50, 0, 2)], PARENT, "gpt-5.4-mini")]) + + assert [(row.model, row.input_tokens) for row in a2a_server._usage(result, "gpt-5.3-codex").models] == [ + ("gpt-5.3-codex", 100), ("gpt-5.4-mini", 50)] + assert a2a_server._usage(result).models == () diff --git a/tst/unit/agents/hermes/test_message_contract.py b/tst/unit/agents/hermes/test_message_contract.py index 318202a1e..ab6dc196e 100644 --- a/tst/unit/agents/hermes/test_message_contract.py +++ b/tst/unit/agents/hermes/test_message_contract.py @@ -13,7 +13,7 @@ from pathlib import Path import pytest -from agentenv_protocol.a2a_agent import Uploaded +from agentenv_protocol.a2a_agent import ModelUsage, Uploaded from tst.unit.agents.hermes.agent import a2a_server, hermes_bridge, hermes_kit from tst.unit.agents.hermes.conftest import result @@ -290,8 +290,8 @@ def _events(*events): return parser -def _call(turn, session, prompt, output): - return {"type": "post_api_request", "turn_id": turn, "session_id": session, +def _call(turn, session, prompt, output, model=None): + return {"type": "post_api_request", "turn_id": turn, "session_id": session, "model": model, "usage": {"input_tokens": prompt, "prompt_tokens": prompt, "output_tokens": output, "cache_read_tokens": 0, "cache_write_tokens": 0}} @@ -357,6 +357,45 @@ def test_a_killed_turn_keeps_the_calls_it_made_as_a_lower_bound(): assert usage.provider_details == {"api_calls": 2, "unreported_calls": 1} +def test_a_turns_counts_are_its_models_its_title_call_and_childs_included(): + """Every call a turn makes runs on its model: the title call routes to the main model and a child inherits it.""" + haiku = "claude-haiku-4-5" + parser = _events(_call("A", "parent", 13081, 82, haiku), _call("B", "child", 9161, 60, haiku), + _call("A", "parent", 13535, 4, haiku)) + report = {"model": "claude-haiku-4-5", "input_tokens": 26616, "output_tokens": 86, "total_tokens": 26702, + "cache_read_tokens": 0, "cache_write_tokens": 0, "api_calls": 2, "estimated_cost_usd": 0.0271, + "cost_status": "estimated", + "auxiliary": {"api_calls": 1, "input_tokens": 456, "output_tokens": 17, "cache_read_tokens": 0, + "cache_write_tokens": 0, "total_tokens": 473}, + "total_including_auxiliary": {"api_calls": 3, "estimated_cost_usd": 0.0275}} + + alone = a2a_server._usage(result(usage=report)) + delegated = a2a_server._usage(parser.result(b"", b"", 0, report)) + + assert alone.models == (ModelUsage(model="claude-haiku-4-5", calls=3, input_tokens=26616 + 456, + output_tokens=86 + 17, cache_read_tokens=0, cache_write_tokens=0, + input_includes_cache=True, cost_usd=0.0275),) + (row,) = delegated.models + assert (row.calls, row.input_tokens, row.output_tokens, row.cost_usd) == (4, 26616 + 456 + 9161, 86 + 17 + 60, None) + + +def test_a_turn_whose_calls_named_several_models_gives_no_rows(): + parser = _events(_call("A", "parent", 13081, 82, "claude-haiku-4-5"), _call("B", "child", 9161, 60, "gpt-4.1-mini")) + report = {"model": "claude-haiku-4-5", "input_tokens": 13081, "output_tokens": 82, "total_tokens": 13163, + "cache_read_tokens": 0, "cache_write_tokens": 0, "api_calls": 1} + + assert a2a_server._usage(parser.result(b"", b"", 0, report)).models == () + assert a2a_server._usage(result(usage={k: v for k, v in report.items() if k != "model"})).models == () + + +def test_a_killed_turns_counts_are_the_model_its_calls_named(): + parser = _events(_call("A", "s", 13073, 53, "claude-haiku-4-5"), _call("A", "s", 13156, 81, "claude-haiku-4-5")) + + (row,) = a2a_server._usage(result(usage={}, killed_calls=parser.all_calls)).models + + assert (row.model, row.calls, row.input_tokens, row.output_tokens) == ("claude-haiku-4-5", 2, 26229, 134) + + def test_the_profile_turns_hermes_review_fork_off(): config = hermes_bridge.build_config("m", None, {}, None, Path("/skills"), environ={"LITELLM_BASE_URL": "http://x"}) From 9fd9e11c4eea35182b4bff0cf5e96efbceb640ba Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 13:05:20 -0800 Subject: [PATCH 2/3] refactor(agents): the relay and Gemini build each model's row with ModelUsage.of, and the sandboxed proxy gives rows Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/agents/gemini/a2a_server.py | 16 ++++++---------- .../agents/agents/gemini/requirements.txt | 6 +++--- .../agents/agents/letta-code/requirements.txt | 6 +++--- .../agents/agents/opencode/requirements.txt | 6 +++--- .../agents/agents/proxy/requirements.txt | 6 +++--- src/agent_env/utils/model_relay/model_relay.py | 13 +------------ tst/unit/agents/gemini/test_image_contract.py | 2 +- tst/unit/agents/opencode/test_image_contract.py | 2 +- 8 files changed, 21 insertions(+), 36 deletions(-) diff --git a/src/agent_env/agents/agents/gemini/a2a_server.py b/src/agent_env/agents/agents/gemini/a2a_server.py index 93c62f645..7eb1d0d24 100644 --- a/src/agent_env/agents/agents/gemini/a2a_server.py +++ b/src/agent_env/agents/agents/gemini/a2a_server.py @@ -242,23 +242,18 @@ async def _settled(calls: _Calls) -> None: await asyncio.sleep(_IN_FLIGHT_POLL_S) -def _total(name: str, counts: list[dict]) -> int | None: - values = [of[name] for of in counts if of.get(name) is not None] - return sum(values) if values else None - - def _by_model(calls: _Calls, model: str | None) -> tuple[ModelUsage, ...]: """The answered calls' counts by the model each named, one that named none counted as ``model``'s; none when a call named none and no model is configured.""" - by_model: dict[str, list[dict]] = {} + by_model: dict[str, list[Usage]] = {} for record in calls.records: if record["outcome"] != "answered": continue if not (name := record["model"] or model): return () - by_model.setdefault(name, []).append(record["usage"]) - return tuple(ModelUsage(model=name, calls=len(of), **{count: _total(count, of) for count in _COUNTS[:4]}, - input_includes_cache=True) for name, of in by_model.items()) + by_model.setdefault(name, []).append(Usage(**{count: record["usage"].get(count) for count in _COUNTS[:4]}, + input_includes_cache=True)) + return tuple(ModelUsage.of(name, of) for name, of in by_model.items()) def _turn_usage(calls: _Calls, tool_calls: int, trajectory: list[dict], model: str | None = None) -> Usage: @@ -284,7 +279,8 @@ def _turn_usage(calls: _Calls, tool_calls: int, trajectory: list[dict], model: s return Usage(tool_call_count=tool_calls, provider_details=details) def total(name: str) -> int | None: - return _total(name, answered) + values = [counts[name] for counts in answered if counts.get(name) is not None] + return sum(values) if values else None if total("reasoning_tokens"): details["reasoning_tokens"] = total("reasoning_tokens") diff --git a/src/agent_env/agents/agents/gemini/requirements.txt b/src/agent_env/agents/agents/gemini/requirements.txt index f749fae80..21bc986b1 100644 --- a/src/agent_env/agents/agents/gemini/requirements.txt +++ b/src/agent_env/agents/agents/gemini/requirements.txt @@ -1,4 +1,4 @@ # The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the -# image is built again only when this folder changes. The floor is the first whose Usage gives a turn's counts by -# model (Usage.models); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.640 +# image is built again only when this folder changes. The floor is the first with ModelUsage.of, which gives a model's +# share of a turn from its calls; raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.643 diff --git a/src/agent_env/agents/agents/letta-code/requirements.txt b/src/agent_env/agents/agents/letta-code/requirements.txt index 96283bd84..40433631d 100644 --- a/src/agent_env/agents/agents/letta-code/requirements.txt +++ b/src/agent_env/agents/agents/letta-code/requirements.txt @@ -1,6 +1,6 @@ # The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the -# image is built again only when this folder changes. The floor is the first whose Usage gives a turn's counts by -# model (Usage.models); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.640 +# image is built again only when this folder changes. The floor is the first with ModelUsage.of, which gives a model's +# share of a turn from its calls; raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.643 jsonschema>=4.18,<5 aiohttp>=3.9,<4 diff --git a/src/agent_env/agents/agents/opencode/requirements.txt b/src/agent_env/agents/agents/opencode/requirements.txt index c204ff509..494d4ed4e 100644 --- a/src/agent_env/agents/agents/opencode/requirements.txt +++ b/src/agent_env/agents/agents/opencode/requirements.txt @@ -1,7 +1,7 @@ # The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the -# image is built again only when this folder changes. The floor is the first whose Usage gives a turn's counts by -# model (Usage.models); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.640 +# image is built again only when this folder changes. The floor is the first with ModelUsage.of, which gives a model's +# share of a turn from its calls; raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.643 jsonschema>=4.18,<5 # The model relay's server and client (model_relay.py). aiohttp>=3.9,<4 diff --git a/src/agent_env/agents/agents/proxy/requirements.txt b/src/agent_env/agents/agents/proxy/requirements.txt index cbb1ff189..ada1aeef8 100644 --- a/src/agent_env/agents/agents/proxy/requirements.txt +++ b/src/agent_env/agents/agents/proxy/requirements.txt @@ -1,4 +1,4 @@ # The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the -# image is built again only when this folder changes. The floor is the first whose proxy reports each turn's model usage, -# as the driver records it; raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.597 +# image is built again only when this folder changes. The floor is the first whose proxy gives each turn's counts by +# the model each recorded call named (Usage.models); raise it when the agent needs a newer protocol. +agentenv-framework-protocol[agent]>=0.1.643 diff --git a/src/agent_env/utils/model_relay/model_relay.py b/src/agent_env/utils/model_relay/model_relay.py index d43c83b4b..7eafed752 100644 --- a/src/agent_env/utils/model_relay/model_relay.py +++ b/src/agent_env/utils/model_relay/model_relay.py @@ -28,7 +28,6 @@ # How long the relay, once its turn is done, lets the calls it is still forwarding finish. _SHUTDOWN_S = 5.0 _COUNTS = ("input_tokens", "output_tokens", "total_tokens", "cache_read_tokens", "cache_write_tokens") -_ROW_COUNTS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") class Refusal(Exception): @@ -85,17 +84,7 @@ def _by_model(self, configured: str | None) -> tuple[ModelUsage, ...]: if (name := named or configured) is None: return () by_model.setdefault(name, []).append(usage) - - def total(of: list[Usage], name: str) -> int | None: - values = [getattr(usage, name) for usage in of if getattr(usage, name) is not None] - return sum(values) if values else None - - rows = [] - for name, of in by_model.items(): - flags = {usage.input_includes_cache for usage in of} - rows.append(ModelUsage(model=name, calls=len(of), **{count: total(of, count) for count in _ROW_COUNTS}, - input_includes_cache=flags.pop() if len(flags) == 1 else None)) - return tuple(rows) + return tuple(ModelUsage.of(name, of) for name, of in by_model.items()) class AnswerReader: diff --git a/tst/unit/agents/gemini/test_image_contract.py b/tst/unit/agents/gemini/test_image_contract.py index e466a4ac2..1ac9e0226 100644 --- a/tst/unit/agents/gemini/test_image_contract.py +++ b/tst/unit/agents/gemini/test_image_contract.py @@ -54,7 +54,7 @@ def test_the_image_installs_the_protocol_alone_from_its_requirements(): requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] - assert requirements == ["agentenv-framework-protocol[agent]>=0.1.640"] + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.643"] def test_the_image_gives_the_models_python_the_document_libraries(): diff --git a/tst/unit/agents/opencode/test_image_contract.py b/tst/unit/agents/opencode/test_image_contract.py index 8657ec767..312715c54 100644 --- a/tst/unit/agents/opencode/test_image_contract.py +++ b/tst/unit/agents/opencode/test_image_contract.py @@ -74,7 +74,7 @@ def test_the_requirements_are_the_protocol_floor_the_output_format_validator_and requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] - assert requirements == ["agentenv-framework-protocol[agent]>=0.1.640", "jsonschema>=4.18,<5", "aiohttp>=3.9,<4"] + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.643", "jsonschema>=4.18,<5", "aiohttp>=3.9,<4"] def test_node_is_pinned_by_version_and_checksum_for_the_image_and_an_install(): From 56597afff071f56a794e85bbfe79b18543b096db Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 13:27:02 -0800 Subject: [PATCH 3/3] refactor(agents): Codex reads each rollout once, its count names map in one place, and Hermes names its turn's models in a function of its own Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/codex/a2a_server.py | 15 ++- .../agents/agents/codex/codex_bridge.py | 123 ++++++------------ .../agents/agents/hermes/a2a_server.py | 17 ++- .../agents/codex/test_codex_bridge_events.py | 17 ++- 4 files changed, 71 insertions(+), 101 deletions(-) diff --git a/src/agent_env/agents/agents/codex/a2a_server.py b/src/agent_env/agents/agents/codex/a2a_server.py index 05af7727a..95d456357 100644 --- a/src/agent_env/agents/agents/codex/a2a_server.py +++ b/src/agent_env/agents/agents/codex/a2a_server.py @@ -573,6 +573,11 @@ async def _stage_granted_workspace(source: ReadObject | None) -> Path | None: _INSTALL_COMMANDS_HOST = [_UNPACK, _ENDPOINT + f"bash {{work_dir}}/agent/install.sh host {{agent_name}} {{a2a_port}} {_HOST_WORKDIR}"] +# Codex's names for the counts Usage takes; OpenAI's input counts the cache. +_COUNT_NAMES = {"input_tokens": "input_tokens", "output_tokens": "output_tokens", + "cache_read_tokens": "cached_input_tokens", "cache_write_tokens": "cache_write_input_tokens"} + + def _usage(result: CodexResult, model: str | None = None) -> Usage: """The turn's tool calls and token counts: the CLI's own, for this turn alone, its subagents' included (``token_usage``), by the model each thread ran on (``models``). OpenAI counts the cache in a call's input, so @@ -593,9 +598,8 @@ def _usage(result: CodexResult, model: str | None = None) -> Usage: return Usage(tool_call_count=result.tool_call_count, provider_details=details) if result.unreported_calls: details["unreported_calls"] = result.unreported_calls - return Usage(tool_call_count=result.tool_call_count, input_tokens=inputs, output_tokens=outputs, - total_tokens=inputs + outputs, cache_read_tokens=counts.get("cached_input_tokens"), - cache_write_tokens=counts.get("cache_write_input_tokens"), input_includes_cache=True, + return Usage(tool_call_count=result.tool_call_count, total_tokens=inputs + outputs, input_includes_cache=True, + **{ours: counts.get(theirs) for ours, theirs in _COUNT_NAMES.items()}, models=_by_model(result.threads, model), provider_details=details) @@ -614,9 +618,8 @@ def total(name: str, of: list[ThreadCalls]) -> int | None: return tuple(ModelUsage( model=name, calls=None if any(thread.requests is None for thread in of) else sum(t.requests for t in of), - input_tokens=total("input_tokens", of), output_tokens=total("output_tokens", of), - cache_read_tokens=total("cached_input_tokens", of), cache_write_tokens=total("cache_write_input_tokens", of), - input_includes_cache=True) for name, of in by_model.items()) + **{ours: total(theirs, of) for ours, theirs in _COUNT_NAMES.items()}, input_includes_cache=True) + for name, of in by_model.items()) @a2a_agent( diff --git a/src/agent_env/agents/agents/codex/codex_bridge.py b/src/agent_env/agents/agents/codex/codex_bridge.py index c03078381..e83a35b5b 100644 --- a/src/agent_env/agents/agents/codex/codex_bridge.py +++ b/src/agent_env/agents/agents/codex/codex_bridge.py @@ -267,65 +267,18 @@ def _kill_process_group(proc) -> None: proc.kill() -def read_rollout_usage(thread_id: str | None) -> dict[str, int] | None: - """Read Codex's latest cumulative token total from a native rollout.""" - if not thread_id: - return None - path = find_rollout_path(thread_id) - if path is None: - return None - try: - lines = path.read_text(errors="replace").splitlines() - except OSError: - return None - for line in reversed(lines): - try: - record = json.loads(line) - except json.JSONDecodeError: - continue - if record.get("type") != "event_msg": - continue - payload = record.get("payload") or {} - if payload.get("type") != "token_count": - continue - info = payload.get("info") or {} - total = info.get("total_token_usage") or {} - if not isinstance(total, dict): - continue - usage = { - key: int(total[key]) - for key in _USAGE_KEYS - if isinstance(total.get(key), (int, float)) - and not isinstance(total.get(key), bool) - } - if usage: - return usage - return None +@dataclass(frozen=True) +class Rollout: + """What a thread's native rollout says of its model calls: its latest running total (``usage``), how many model + requests raised that total, and the model its last turn ran on (its ``turn_context``).""" + usage: dict[str, int] | None = None + requests: int = 0 + model: str | None = None -def read_rollout_model(thread_id: str | None) -> str | None: - """The model a native rollout's last turn ran on, as its ``turn_context`` names it.""" - path = find_rollout_path(thread_id) if thread_id else None - if path is None: - return None - try: - lines = path.read_text(errors="replace").splitlines() - except OSError: - return None - for line in reversed(lines): - try: - record = json.loads(line) - except json.JSONDecodeError: - continue - if isinstance(record, dict) and record.get("type") == "turn_context": - model = (record.get("payload") or {}).get("model") - if isinstance(model, str) and model: - return model - return None - -def read_rollout_requests(thread_id: str | None) -> int | None: - """How many model requests a native rollout records: its token counts that raised the thread's total.""" +def read_rollout(thread_id: str | None) -> Rollout | None: + """The thread's native rollout, read in one pass; None when there's none to read.""" path = find_rollout_path(thread_id) if thread_id else None if path is None: return None @@ -333,21 +286,28 @@ def read_rollout_requests(thread_id: str | None) -> int | None: lines = path.read_text(errors="replace").splitlines() except OSError: return None - requests, last = 0, 0 + usage, requests, last, model = None, 0, 0, None for line in lines: try: record = json.loads(line) except json.JSONDecodeError: continue - if not isinstance(record, dict) or record.get("type") != "event_msg": + if not isinstance(record, dict): continue payload = record.get("payload") or {} - if payload.get("type") != "token_count": + if record.get("type") == "turn_context" and isinstance(payload.get("model"), str) and payload["model"]: + model = payload["model"] + if record.get("type") != "event_msg" or payload.get("type") != "token_count": + continue + total = (payload.get("info") or {}).get("total_token_usage") + if not isinstance(total, dict): continue - total = ((payload.get("info") or {}).get("total_token_usage") or {}).get("total_tokens") - if isinstance(total, int) and total > last: - requests, last = requests + 1, total - return requests + counts = {key: int(total[key]) for key in _USAGE_KEYS + if isinstance(total.get(key), (int, float)) and not isinstance(total.get(key), bool)} + usage = counts or usage + if isinstance(total.get("total_tokens"), int) and total["total_tokens"] > last: + requests, last = requests + 1, total["total_tokens"] + return Rollout(usage, requests, model) def subagent_threads(thread_id: str | None) -> list[str]: @@ -377,29 +337,27 @@ def subagent_threads(thread_id: str | None) -> list[str]: return found -def _subagent_baselines(thread_id: str | None) -> dict[str, tuple[dict[str, int] | None, int]]: - return {child: (read_rollout_usage(child), read_rollout_requests(child) or 0) - for child in subagent_threads(thread_id)} +def _subagent_baselines(thread_id: str | None) -> dict[str, Rollout]: + return {child: read_rollout(child) or Rollout() for child in subagent_threads(thread_id)} -def _add_subagent_calls(result: CodexResult, baselines: Mapping[str, tuple[dict[str, int] | None, int]]) -> None: +def _add_subagent_calls(result: CodexResult, baselines: Mapping[str, Rollout]) -> None: """Adds what the turn's subagents used since the turn began to its own counts.""" for child in subagent_threads(result.session_id): - usage, requests = baselines.get(child, (None, 0)) - made = (read_rollout_requests(child) or 0) - requests + before, after = baselines.get(child, Rollout()), read_rollout(child) or Rollout() + made = after.requests - before.requests if result.model_requests is not None: result.model_requests += made - current = read_rollout_usage(child) - if result.token_usage is None or current is None: + if result.token_usage is None or after.usage is None: continue - delta = _usage_delta(current, usage) + delta = _usage_delta(after.usage, before.usage) if delta is None: result.token_usage = None result.warnings.append(f"codex subagent {child}'s token counters regressed; incremental usage is unavailable") continue result.token_usage = {key: result.token_usage.get(key, 0) + delta.get(key, 0) for key in {**result.token_usage, **delta}} - result.threads.append(ThreadCalls(read_rollout_model(child), delta, made)) + result.threads.append(ThreadCalls(after.model, delta, made)) def _usage_delta( @@ -1004,8 +962,7 @@ async def run_codex( counts include its subagents' calls, read from their own rollouts. """ deadline = time.monotonic() + timeout_s - usage_baseline = read_rollout_usage(thread_id) - requests_baseline = read_rollout_requests(thread_id) or 0 + before = read_rollout(thread_id) or Rollout() subagent_baselines = _subagent_baselines(thread_id) retries_left = _configured_api_error_retries() attempt_prompt = prompt @@ -1068,15 +1025,14 @@ async def run_codex( result.tool_call_count = tool_call_count result.attempts = attempts result.error = error - requests = read_rollout_requests(result.session_id) - if requests is not None: - result.model_requests = requests - requests_baseline - cumulative_usage = result.usage or ( - read_rollout_usage(result.session_id) or {} - ) + after = read_rollout(result.session_id) + if after is not None: + result.model_requests = after.requests - before.requests + after = after or Rollout() + cumulative_usage = result.usage or after.usage or {} if cumulative_usage: result.token_usage = _usage_delta( - cumulative_usage, usage_baseline + cumulative_usage, before.usage ) if result.token_usage is None: warning = ( @@ -1085,8 +1041,7 @@ async def run_codex( ) result.warnings.append(warning) else: - result.threads = [ThreadCalls(read_rollout_model(result.session_id), dict(result.token_usage), - result.model_requests)] + result.threads = [ThreadCalls(after.model, dict(result.token_usage), result.model_requests)] _add_subagent_calls(result, subagent_baselines) return result diff --git a/src/agent_env/agents/agents/hermes/a2a_server.py b/src/agent_env/agents/agents/hermes/a2a_server.py index e26fe993e..a87760372 100644 --- a/src/agent_env/agents/agents/hermes/a2a_server.py +++ b/src/agent_env/agents/agents/hermes/a2a_server.py @@ -534,11 +534,7 @@ def _usage(result) -> Usage: """The turn's usage (``_counts``), its counts given as its model's when every call it made named one: Hermes runs its auxiliary tasks on the main model, and a delegate_task child inherits it, as the bridge's config pins no other for either. A turn whose calls named several models gives none rather than guess how they split.""" - usage = _counts(result) - calls = result.killed_calls if result.killed_calls is not None else result.side_calls - named = set(calls.models) if calls is not None else set() - if result.killed_calls is None and isinstance(model := result.usage.get("model"), str) and model: - named.add(model) + usage, named = _counts(result), _named_models(result) if len(named) != 1 or (usage.input_tokens is None and usage.output_tokens is None): return usage (model,) = named @@ -549,6 +545,17 @@ def _usage(result) -> Usage: cost_usd=usage.cost_usd),)) +def _named_models(result) -> set[str]: + """The models the turn's calls named: a killed turn's in their events; else the main loop's in the usage file and + each delegate_task child's in its events.""" + if result.killed_calls is not None: + return set(result.killed_calls.models) + named = set(result.side_calls.models) if result.side_calls is not None else set() + if isinstance(model := result.usage.get("model"), str) and model: + named.add(model) + return named + + def _counts(result) -> Usage: """The turn's tool calls and token counts, with ``input_tokens`` counting the cache: its main model calls as Hermes' usage file counts them, its auxiliary calls (title generation, compression) as the file's ``auxiliary`` diff --git a/tst/unit/agents/codex/test_codex_bridge_events.py b/tst/unit/agents/codex/test_codex_bridge_events.py index 0d707ac90..4d44c0375 100644 --- a/tst/unit/agents/codex/test_codex_bridge_events.py +++ b/tst/unit/agents/codex/test_codex_bridge_events.py @@ -284,13 +284,13 @@ def test_usage_is_incremental_from_existing_rollout( } monkeypatch.setattr( codex_bridge, - "read_rollout_usage", - lambda _: { + "read_rollout", + lambda _: codex_bridge.Rollout(usage={ "input_tokens": 100, "cached_input_tokens": 60, "cache_write_input_tokens": 10, "output_tokens": 10, - }, + }), ) spawn(ndjson(agent_message("x"), completed)) result = asyncio.run( @@ -329,7 +329,7 @@ def test_native_rollout_usage_is_read_for_snapshot_resume(monkeypatch, tmp_path) + "\n" ) monkeypatch.setattr(codex_bridge, "find_rollout_path", lambda _: rollout) - assert codex_bridge.read_rollout_usage("thread-1") == { + assert codex_bridge.read_rollout("thread-1").usage == { "input_tokens": 100, "cached_input_tokens": 60, "cache_write_input_tokens": 20, @@ -337,7 +337,8 @@ def test_native_rollout_usage_is_read_for_snapshot_resume(monkeypatch, tmp_path) } -def test_the_rollout_counts_a_model_request_per_token_count_that_raised_the_total(monkeypatch, tmp_path): +def test_the_rollout_counts_a_model_request_per_token_count_that_raised_the_total_and_names_its_last_model( + monkeypatch, tmp_path): def token_count(total): info = None if total is None else {"total_token_usage": {"input_tokens": total, "total_tokens": total}} return {"type": "event_msg", "payload": {"type": "token_count", "info": info}} @@ -345,11 +346,15 @@ def token_count(total): rollout = tmp_path / "rollout.jsonl" rollout.write_text("".join(json.dumps(record) + "\n" for record in ( {"type": "session_meta", "payload": {"id": "thread-1"}}, + {"type": "turn_context", "payload": {"model": "gpt-5.3-codex"}}, token_count(None), token_count(100), token_count(100), + {"type": "turn_context", "payload": {"model": "gpt-5.6-sol"}}, {"type": "response_item", "payload": {"type": "function_call"}}, token_count(250)))) monkeypatch.setattr(codex_bridge, "find_rollout_path", lambda _: rollout) - assert codex_bridge.read_rollout_requests("thread-1") == 2 + read = codex_bridge.read_rollout("thread-1") + + assert (read.requests, read.model, read.usage["input_tokens"]) == (2, "gpt-5.6-sol", 250) class _OpenStream(_FakeStream):