Skip to content
8 changes: 5 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,9 +399,11 @@ orchestrators call it the same way. What callers rely on:
spend and a worker that dies mid-step keeps it. Those entries are marked `running`, which makes
`usage_total.partial` true, as the turn in flight isn't in them; such a write never takes an entry back
(`usage.ledger.ahead`), and the step's completion replaces them with its final entries. A re-register keeps it, so
it holds every attempt and generation. A runner that doesn't set `ATTEMPT_EPOCH` writes entries with no attempt,
kept by step and role alone: exact for a run without retries, a lower bound for one with. A runner that writes the
instance some other way loses that spend from the ledger.
it holds every attempt and generation. `task/usage/summary.py` sums it by role, then by model, for the run summaries
(`agent-env run`, `eval run`, `task run`), unpriced usage counted apart, never as $0, and a cost priced on an
assumed rate (`cost_assumed`) shown as at most. A runner that doesn't set `ATTEMPT_EPOCH` writes entries with no
attempt, kept by step and role alone: exact for a run without retries, a lower bound for one with. A runner that
writes the instance some other way loses that spend from the ledger.
- The runner writes its run identifier to `context.metadata["workflow_id"]` before calling `run()`;
core stores it opaquely with the instance.
- Each step runs under `protocol_v1.authorized` for the deployed envs in its context: a protocol-client
Expand Down
26 changes: 25 additions & 1 deletion src/agent_env/bundle/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,13 @@
from agent_env.providers import build_sandbox_provider
from agent_env.store.base import NotFoundError
from agent_env.store.routing import namespace_routing, run_scope
from agent_env.task.store import record_task_cancelled
from agent_env.task.store import find_task_instance, record_task_cancelled
from agent_env.task.interrupts import Interrupts
from agent_env.task.lint import said
from agent_env.utils.progress import run_progress
from agent_env.task.task import Task, recorded_scores
from agent_env.task.teardown import TeardownReport, attempt_epoch, record_teardown, teardown_run
from agent_env.task.usage.summary import UsageSummary, summarize
from agent_env.task_step.context import TaskStepContext, sandbox_overrides

from .hub import SOURCE_KEY, HubSource
Expand Down Expand Up @@ -75,6 +76,7 @@ class TaskRun:
started: bool = True # False when it was cancelled before it started
torn_down: TeardownReport | None = None # None while its sandboxes are kept up
attempt_epoch: int | None = None # its instance's as its teardown began, which ``record_teardown`` is fenced by
usage: tuple[dict, ...] = () # its instance's ledger once the run ended, every attempt's entries

@property
def instance_id(self) -> str | None:
Expand All @@ -97,6 +99,11 @@ def models(self) -> dict[str, dict[str, str | None]]:
"""The model each step asked for, by role then step id; None leaves it to the agent."""
return self.context.metadata.get("models") or {}

@property
def usage_summary(self) -> UsageSummary | None:
"""The run's usage by role and model, from its ledger; None when it recorded none."""
return summarize(self.usage)

@property
def outcome(self) -> Outcome:
if self.cancelled:
Expand Down Expand Up @@ -276,6 +283,7 @@ def run_bundle(
source))
_mark_cancelled(runs, interrupts.reason)
_record_teardowns(runs)
runs = _with_usage(runs)
result = _bundle_run(plan, prepared.materialization, runs,
_skipped(plan, entries, every=not tasks and not evals))
if not interrupts.count:
Expand Down Expand Up @@ -390,6 +398,22 @@ def _mark_cancelled(runs: tuple[TaskRun, ...], reason: str) -> None:
record_task_cancelled(run.instance_id, reason, Task._utc_now_str())


def _with_usage(runs: tuple[TaskRun, ...]) -> tuple[TaskRun, ...]:
"""Each run with its instance's ledger, read once the run's last write has landed. A read that fails leaves the
run without it, logged, since the result and the teardown after it matter more than the cost line."""
def read(run: TaskRun) -> TaskRun:
if not run.instance_id:
return run
try:
with run_scope(run.task.id):
instance = find_task_instance(run.instance_id)
except Exception as e:
logger.warning("usage of %s not read: %r", run.instance_id, e)
return run
Comment thread
earakely-scale marked this conversation as resolved.
Resolved
return replace(run, usage=tuple(instance.usage)) if instance is not None else run
return tuple(read(run) for run in runs)


def _record_teardowns(runs: Sequence[TaskRun]) -> None:
"""Keep on each run's instance the context its teardown ended with, so ``agent-env task teardown`` finds what it
left up, those a step a signal cut short had recorded included, and nothing once all is down. Like
Expand Down
23 changes: 19 additions & 4 deletions src/agent_env/cli/eval/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
from agent_env.cli import submitted_runs
from agent_env.cli.banner import print_banner
from agent_env.cli.identity import get_agent_env_client_id
from agent_env.cli.usage_output import cost_line, sources_line
from agent_env.store.ids import fs_safe
from agent_env.task.interrupts import Interrupts
from agent_env.task.usage.summary import summarize
from agent_env.task_step.context import TaskStepContext


Expand Down Expand Up @@ -97,30 +99,43 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int,
# Summarize results
failures = []
successes = []
entries = []
for run in runs:
context = run.instance.context if run.instance else None
if output_dir and context is not None:
_write_context(TaskStepContext.from_dict(context), run.task.id, output_dir, prefix=f"{run.tag} ")
ledger = run.instance.usage if run.instance else []
summary = summarize(ledger)
entries += ledger
if run.completed:
successes.append((run.tag, (context or {}).get("metadata", {}).get("score")))
successes.append((run.tag, (context or {}).get("metadata", {}).get("score"), summary))
else:
failures.append((run.tag, run.outcome if run.done else "CANCELLED"))
failures.append((run.tag, run.outcome if run.done else "CANCELLED", summary))

if successes:
click.echo(click.style("Results:", fg="blue"))
for tag, score in successes:
for tag, score, summary in successes:
score_str = f" score={score}" if score is not None else ""
click.echo(click.style(f" {tag} PASSED{score_str}", fg="green"))
if cost := cost_line(summary):
click.echo(f" {cost}")

if len(successes) < total_runs:
for tag, outcome in failures:
for tag, outcome, summary in failures:
click.echo(click.style(f" {tag} {outcome}", fg="red"))
if cost := cost_line(summary):
click.echo(f" {cost}")
click.echo(click.style(
f"\n{len(successes)}/{total_runs} runs completed, {total_runs - len(successes)}/{total_runs} failed.",
fg="red",
))
else:
click.echo(click.style(f"\nAll {total_runs} runs completed!", fg="blue"))
total = summarize(entries)
if cost := cost_line(total, f"Cost over {len(runs)} runs", attempts=False):
click.echo(cost)
if sources := sources_line(total):
click.echo(sources)
if interrupts.count:
raise SystemExit(128 + interrupts.signum)
if len(successes) < total_runs:
Expand Down
9 changes: 9 additions & 0 deletions src/agent_env/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@
from agent_env.bundle.requires import UnmetRequirements
from agent_env.cli._install_prompt import offer_to_install
from agent_env.cli.teardown_output import echo_finish_teardown, gone
from agent_env.cli.usage_output import cost_line, sources_line
from agent_env.plugins._bundles import ALIAS_TABLES, installed_aliases
from agent_env.plugins._discovery import discovery_error
from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox
from agent_env.task.interrupts import Interrupts
from agent_env.task.teardown import TORN_DOWN_KEY, RecordedSandbox, TeardownReport, kind, recorded_sandboxes, sandbox_ids
from agent_env.task.usage.summary import summarize
from agent_env.task_step.context import TaskStepContext

_COLORS = {Outcome.PASSED: "green", Outcome.BELOW_ONE: "yellow", Outcome.UNSCORED: "yellow", Outcome.FAILED: "red",
Expand Down Expand Up @@ -202,6 +204,8 @@ def _summarize(result: BundleRun, verbose: bool) -> None:
click.echo(click.style(f" {_described(result, run)}", fg=_COLORS[run.outcome]))
if models := _models(run):
click.echo(f" models: {models}")
if cost := cost_line(run.usage_summary):
click.echo(f" {cost}")
if result.evals:
click.echo("Evals:")
for eval_run in result.evals:
Expand All @@ -210,9 +214,14 @@ def _summarize(result: BundleRun, verbose: bool) -> None:
line = f" {result.path(eval_run.entry)} v{eval_run.version}: {passed} of {len(eval_run.runs)} passed"
rest = [f"{failed} failed" if failed else "", f"{cancelled} cancelled" if cancelled else ""]
click.echo(", ".join([line, *filter(None, rest)]))
if cost := cost_line(summarize(entry for run in eval_run.runs for entry in run.usage),
f"cost over {len(eval_run.runs)} runs", attempts=False):
click.echo(f" {cost}")
for entry in result.skipped:
click.echo(f"{result.path(entry)} isn't named by any eval, so it didn't run; run it with "
f"--task {shlex.quote(entry.name)}")
if sources := sources_line(summarize(entry for run in result.runs for entry in run.usage)):
click.echo(sources)
if verbose:
_print_tracebacks(result)

Expand Down
17 changes: 17 additions & 0 deletions src/agent_env/cli/task/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@
from agent_env.cli import submitted_runs
from agent_env.cli.identity import get_agent_env_client_id
from agent_env.cli.teardown_output import echo_finish_teardown, echo_teardown, gone
from agent_env.cli.usage_output import cost_line, sources_line
from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox
from agent_env.runner.runner import KEEP_KEY, RunStatus
from agent_env.store.ids import derive_id, fs_safe, is_local_id, validate_local_id
from agent_env.store.routing import run_scope
from agent_env.task.interrupts import Interrupts
from agent_env.task.store import get_task_instance_store, new_instance_id
from agent_env.task.teardown import TeardownReport, attempt_epoch, kind, record_teardown, teardown_run
from agent_env.task.usage.summary import summarize
from agent_env.task_step.context import TaskStepContext, read_dual_keyed
from agent_env.task_step.task_steps.deploy_agent import DeployAgentTaskStep
from agent_env.task_step.context_ops import build_context_update_ops
Expand Down Expand Up @@ -480,6 +482,7 @@ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int,
click.echo(click.style("Task completed!" if k == 1 else f"All {k} runs completed!", fg="blue"))
elif k > 1:
click.echo(click.style(f"{completed}/{k} runs completed, {k - completed}/{k} failed.", fg="red"))
_echo_usage(runs, k)
if keep:
_settle_kept(_ended(runs), interrupts, interrupted)
if interrupted is not None:
Expand All @@ -488,6 +491,20 @@ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int,
raise SystemExit(1)


def _echo_usage(runs, k: int) -> None:
"""Each run's cost by role and model from its ledger, the runs' total when there were several, and where the costs
came from."""
ledgers = [(run.tag, run.instance.usage if run.instance else []) for run in runs]
for tag, ledger in ledgers:
if cost := cost_line(summarize(ledger)):
click.echo(f"{tag} {cost}" if tag else cost)
total = summarize(entry for _, ledger in ledgers for entry in ledger)
if k > 1 and (cost := cost_line(total, f"Cost over {k} runs", attempts=False)):
click.echo(cost)
if sources := sources_line(total):
click.echo(sources)


def _runnable(task_id: str, task_version: int | None, metadata: dict):
"""The stored task, checked before the first step a run with ``metadata`` runs (``runnable_task``); a refusal for
what it requires offers, in a terminal, to install it and run the command again."""
Expand Down
76 changes: 76 additions & 0 deletions src/agent_env/cli/usage_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""How the run summaries print a run's usage (``task.usage.summary``): one cost line per run and one closing line
naming where the costs came from."""

from __future__ import annotations

from agent_env.config.model import ModelRole
from agent_env.config.model_pricing import ReportedBy
from agent_env.task.usage.summary import Share, UsageSummary

_ROLE_NAMES = {role.value: role.record_key for role in ModelRole}
# The cost sources that aren't the price map, in the order they're named.
_REPORTED = {ReportedBy.PROVIDER: "the endpoint's bills", ReportedBy.HARNESS: "agents' own figures"}
_DOLLAR_PLACES = 4
_SMALLEST_DOLLARS = 0.0001 # the least a cost shows at _DOLLAR_PLACES; a smaller one reads "under" it
_THOUSAND, _MILLION = 1_000, 1_000_000
_TENTHS_OF_THOUSANDS_BELOW = 10 * _THOUSAND # a count under it shows one decimal: 1.2k, not 1k


def cost_line(summary: UsageSummary | None, label: str = "cost", attempts: bool = True) -> str | None:
"""``cost: $0.0532 (solver gpt-4.1-mini $0.0412, 115k in, 1.2k out; judge ...)``, each cost as ``_cost`` gives it
and, with ``attempts``, the attempts named when there were more than one; None for no usage."""
if summary is None:
return None
parts = [f"{summary.attempts} attempts"] if attempts and summary.attempts > 1 else []
return f"{label}: {_cost(summary)} ({'; '.join([*parts, *map(_share, summary.shares)])})"


def sources_line(summary: UsageSummary | None) -> str | None:
"""Where ``summary``'s costs came from, as ``Costs priced from LiteLLM's price map, litellm@1.80.0.``; None when
nothing was priced."""
sources = summary.sources if summary is not None else ()
if not sources:
return None
named = [f"LiteLLM's price map, {source}" for source in sources if source.startswith("litellm@")]
named += [name for source, name in _REPORTED.items() if source in sources]
named += [source for source in sources if not source.startswith("litellm@") and source not in _REPORTED]
return f"Costs priced from {'; '.join(named)}."


def _share(share: Share) -> str:
words = [f"{_ROLE_NAMES.get(share.role, share.role)} {share.model or 'an unnamed model'} {_cost(share)}"]
if share.input_tokens is not None:
words.append(f"{_count(share.input_tokens)} in")
if share.output_tokens is not None:
words.append(f"{_count(share.output_tokens)} out")
if share.partial:
words.append("partial")
return ", ".join(words)


def _cost(of: UsageSummary | Share) -> str:
"""``of``'s cost with what it is: ``at least`` when some usage went unpriced or uncounted, ``at most`` when some
was priced on an assumed rate, ``estimated`` when both, and ``unpriced`` when nothing was priced."""
if of.cost_usd is None:
return "unpriced"
lower, upper = of.lower_bound, of.upper_bound
word = "estimated " if lower and upper else "at least " if lower else "at most " if upper else ""
return f"{word}{_dollars(of.cost_usd)}"


def _dollars(usd: float) -> str:
if usd == 0:
return "$0"
if usd < _SMALLEST_DOLLARS:
return f"under ${_SMALLEST_DOLLARS:.{_DOLLAR_PLACES}f}"
return f"${usd:.{_DOLLAR_PLACES}f}"


def _count(n: int) -> str:
if n < _THOUSAND:
return str(n)
if n < _TENTHS_OF_THOUSANDS_BELOW:
return f"{n / _THOUSAND:.1f}k"
if n < _MILLION:
return f"{round(n / _THOUSAND)}k"
return f"{n / _MILLION:.1f}M"
Loading
Loading