Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/agent_env/agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
46 changes: 36 additions & 10 deletions src/agent_env/agents/agents/codex/a2a_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
ContextObjectTrajectoryRequest,
ContextTrajectoryRequest,
InlineSkillRequest,
ModelUsage,
ObjectSnapshotLoadRequest,
ObjectSnapshotSaveRequest,
SkillAddResponse,
Expand All @@ -67,6 +68,7 @@
from codex_bridge import (
SESSIONS_DIR,
CodexResult,
ThreadCalls,
find_rollout_path,
get_last_attribution_snapshot,
kill_running_clis,
Expand Down Expand Up @@ -571,12 +573,18 @@ 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:
# 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``). 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:
Expand All @@ -590,10 +598,28 @@ def _usage(result: CodexResult) -> 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,
provider_details=details)
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)


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),
**{ours: total(theirs, of) for ours, theirs in _COUNT_NAMES.items()}, input_includes_cache=True)
for name, of in by_model.items())


@a2a_agent(
Expand Down Expand Up @@ -767,7 +793,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()
)

Expand Down
115 changes: 54 additions & 61 deletions src/agent_env/agents/agents/codex/codex_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -255,66 +267,47 @@ 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_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
try:
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]:
Expand Down Expand Up @@ -344,27 +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))
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 += (read_rollout_requests(child) or 0) - requests
current = read_rollout_usage(child)
if result.token_usage is None or current is None:
result.model_requests += made
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(after.model, delta, made))


def _usage_delta(
Expand Down Expand Up @@ -969,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
Expand Down Expand Up @@ -1033,22 +1025,23 @@ 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 = (
"codex cumulative token counters regressed; "
"incremental usage is unavailable"
)
result.warnings.append(warning)
else:
result.threads = [ThreadCalls(after.model, dict(result.token_usage), result.model_requests)]
_add_subagent_calls(result, subagent_baselines)
return result

Expand Down
6 changes: 3 additions & 3 deletions src/agent_env/agents/agents/codex/requirements.txt
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
16 changes: 6 additions & 10 deletions src/agent_env/agents/agents/gemini/a2a_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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")
Expand Down
6 changes: 3 additions & 3 deletions src/agent_env/agents/agents/gemini/requirements.txt
Original file line number Diff line number Diff line change
@@ -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
4 changes: 3 additions & 1 deletion src/agent_env/agents/agents/hermes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Loading
Loading