Skip to content

fix(agent-server): price turns run through OpenRouter at OpenRouter prices - #3490

Open
jjaeger94 wants to merge 3 commits into
Abilityai:devfrom
jjaeger94:fix/proxy-turn-cost
Open

jjaeger94 wants to merge 3 commits into
Abilityai:devfrom
jjaeger94:fix/proxy-turn-cost

Conversation

@jjaeger94

@jjaeger94 jjaeger94 commented Oct 9, 2026 •

Copy link
Copy Markdown

Description

When a Claude Code agent runs through OpenRouter, Trinity records the turn cost at Anthropic prices (#3489). Claude Code computes total_cost_usd from its own price table. For a model it does not know, modelUsage marks that figure "costBasis": "unknown", and on our DeepSeek Flash agents it came out about 25× too high.

This PR adds agent_server/services/provider_pricing.py with one function, turn_cost(result):

  • It reads the proxy host from ANTHROPIC_BASE_URL in the execution env (the same build_execution_env() the spawn uses, so it covers a .env-injected base URL). The host is re-read only when .env or the ANTHROPIC_BASE_URL override changes.
  • For a known proxy host (openrouter.ai only for now), it re-prices from modelUsage: input, output, cache-read and cache-write tokens of every model the turn touched, against https://openrouter.ai/api/v1/models. turn_cost never touches the network: it runs on the stdout reader thread. The list is loaded in a daemon thread at agent-server boot (prefetch_prices, startup hook in main.py) and refreshed in the background every 6 h. A failed refresh keeps the previous list and retries after 5 min.
  • In every other case it returns total_cost_usd unchanged: no proxy, an unknown host, a model missing from the list, no modelUsage, a price list that is not loaded yet, a failed fetch, or any exception. A plain Anthropic setup behaves exactly as before.
  • It is wired into the four places that read total_cost_usd: both parsers in stream_parser.py, _recover_metadata_from_jsonl and _recover_metadata_from_raw_messages.

Adding another provider means adding one entry to _PRICE_SOURCES.

Measured on a real turn: Trinity reported $0.311, modelUsage × OpenRouter prices gives $0.0137, and the turn's generations summed via /api/v1/generation cost $0.0116. That sum leaves out side calls such as WebSearch, which are not in the stream, while modelUsage counts them. After deploying this on v0.9.5, a one-word task logged provider pricing: openrouter.ai cost $0.005241 (native estimate $0.08736).

The code was written with Claude Code.

Related Issue

Fixes #3489

Journey Impact

Journey Impact: none: agent-server cost bookkeeping only. No user flow, endpoint or UI changes, and the cost value keeps its meaning (USD per turn).

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Testing

What ran:

  • Review follow-up (after merging dev): tests/unit/test_provider_pricing.py (19 tests) drives process_stream_line, both recovery paths, the no-blocking guarantee and _fetch_openrouter_prices over a canned payload. All unit tests touching the changed modules (59 files): 1666 passed locally on Python 3.13.
  • Original run: tests/unit/test_provider_pricing.py (10 tests, new, registered in tests/registry.json), together with the existing parser and recovery tests: test_claude_code_result_recovery, test_1870_completed_turn_recovery, test_1673_execution_error_not_success, test_claude_code_session_id_parser, test_1849_ede_diagnostic_filtered and test_model_context_catalog. 215 passed on v0.9.5.
  • I could not complete the full unit suite outside your CI environment, so I left "All existing tests pass" unticked for CI to confirm.
  • Deployed as an overlay on trinity-agent-base:v0.9.5 with two OpenRouter agents. Costs were checked against the OpenRouter key usage.

🤖 Generated with Claude Code

…rices

Claude Code prices every turn from its Anthropic price table. With
ANTHROPIC_BASE_URL pointing at OpenRouter and the model aliases mapped to a
non-Anthropic model, total_cost_usd is a guess at Anthropic prices for a model
Claude Code does not know (modelUsage marks it costBasis "unknown") — measured
~25x too high for DeepSeek Flash.

turn_cost() re-prices the result event from modelUsage (tokens per model,
cumulative over every API call of the turn) against the provider's public price
list, cached for 6h, and keeps the native figure whenever it cannot: no proxy,
unknown proxy host, a model missing from the list, no modelUsage, or a failed
price fetch. Wired into both stream parsers and the JSONL recovery path.

Fixes Abilityai#3489

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vybe

vybe commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-10-10): not on this train — rides the next one once fixed. Validation (/validate-pr + /review + /cso --diff) found the approach sound (live-fetched prices, fail-open to the native figure, no new egress risk), with one defect and one coverage gap that need your intent rather than a mechanical push:

  1. A fourth raw total_cost_usd reader is still unwired — docker/base-image/agent_server/services/error_classifier.py:343 (_recover_metadata_from_raw_messages, live via :479 on the empty-result recovery path) still does cost = msg.get("total_cost_usd"), so a turn recovered from raw_messages keeps the Anthropic-priced figure. cost = turn_cost(msg) plus the import closes it.
  2. No test drives the live parser. test_stream_parser_uses_turn_cost exercises parse_stream_json_output, which has no live callers in agent_server/; both spawn paths go through process_stream_line and recovery through _recover_metadata_from_jsonl. Please add a test that feeds an OpenRouter-shaped result record through process_stream_line (and ideally _recover_metadata_from_jsonl + the raw-messages recovery above), and a contract test for _fetch_openrouter_prices over a canned /api/v1/models payload (the cache-price fallback at lines 65–66 is untested).

Smaller notes, not blockers: _lock is held across the urlopen (a 5 s stall for every concurrent result parse once per TTL); _proxy_host() re-runs build_execution_env() per result event, so its "ignoring … from .env" warning now logs at spawn and at every result; docs/memory/architecture/agent-runtime.md still says Claude cost reporting is native. tests/registry.json conflicts with dev (routine append; merge dev). I have approved the workflow run so CI reports on the fork.

@github-actions

github-actions Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

✅ Nightly unit-suite clean when this PR is merged into dev, all 3 seeds (head_sha: f6c2219c04124b0e623c8ef0d4adc7d13cee290a).

@vybe

vybe commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-10-11): ejected again. Nothing has been pushed since the 2026-10-10 note, so both points it raised are still open. This train also sets status-needs-fix, so the PR stops reading as ready. Your next push clears the label.

  1. A reader of total_cost_usd is still unwired (mechanical). agent_server/services/error_classifier.py → _recover_metadata_from_raw_messages still does cost = msg.get("total_cost_usd"). An OpenRouter-shaped result run through it gives 0.311 (the Anthropic price). process_stream_line gives 0.0137 for the same result. Fix: cost = turn_cost(msg) plus the import. There's no import cycle.
  2. The tests don't exercise the parser production uses. test_stream_parser_uses_turn_cost drives parse_stream_json_output, which nothing in agent_server/ calls. Production goes through process_stream_line (headless_executor.py, claude_code.py), _recover_metadata_from_jsonl, and the raw-messages recovery above. None of those is tested, and neither is _fetch_openrouter_prices's payload parsing or its cache-price fallback.
  3. Needs your call: the price fetch runs on the result path. _prices_for holds _lock across urlopen(timeout=5), on the stdout reader thread. The timeout doesn't cover DNS. _drain_bounded waits only grace=5, so a slow fetch can leave the reader counted as leaked. Finalize then runs before cost and the result text are set, and the turn lands in exactly the recovery path from point 1. Prefetching at startup or refreshing in the background would keep turn_cost free of network I/O.

The conflict with dev is routine: the stream_parser.py import line (keep dev's line and add turn_cost below it) and a tests/registry.json union. Rides the next train once 1–3 are addressed.

@vybe vybe added the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Oct 11, 2026
jjaeger94 and others added 2 commits October 12, 2026 09:27
# Conflicts:
#	docker/base-image/agent_server/services/stream_parser.py
#	tests/registry.json
…e the last cost reader

Review follow-up for Abilityai#3489:

- _recover_metadata_from_raw_messages now prices through turn_cost, so a
  turn recovered from raw_messages no longer keeps the Anthropic-priced
  total_cost_usd.
- turn_cost never does network I/O. The price list loads in a daemon
  thread at agent-server boot (prefetch_prices) and whenever it is stale;
  until then the native figure is kept. The lock only guards the cache.
  A failed refresh keeps the previous list and retries after 5 minutes.
- _proxy_host re-runs build_execution_env only when .env or the
  ANTHROPIC_BASE_URL override changes, so its .env warnings no longer
  repeat on every result event.
- An explicit cache price of 0 is a price, not a missing one.
- Tests drive the production parsers (process_stream_line,
  _recover_metadata_from_jsonl, _recover_metadata_from_raw_messages), the
  no-blocking guarantee, and _fetch_openrouter_prices over a canned
  /api/v1/models payload.
- docs: agent-runtime.md describes cost behind a proxy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jjaeger94

Copy link
Copy Markdown
Author

Thanks for the thorough review. All three points are addressed in f6c2219, and dev is merged in, so the conflicts are resolved.

  1. Raw-messages recovery: _recover_metadata_from_raw_messages now uses cost = turn_cost(msg).
  2. Tests on the production paths: new tests feed an OpenRouter-shaped result through process_stream_line, _recover_metadata_from_jsonl and _recover_metadata_from_raw_messages. There is also a contract test for _fetch_openrouter_prices over a canned /api/v1/models payload. It covers the cache-price fallback, an explicit 0 cache price (now treated as a price, not as missing), and malformed or incomplete entries.
  3. No network I/O in turn_cost: I went with the background refresh. The list is prefetched at agent-server boot (startup hook in main.py) and refreshed in a daemon thread when stale, with one fetch in flight at a time. _lock now only guards the cache. Until the list is loaded, turn_cost returns the native figure. A failed refresh keeps the previous list and retries after 5 min. A test holds the fetch open and checks that turn_cost returns immediately.

Smaller notes: _proxy_host() now re-runs build_execution_env() only when .env or the ANTHROPIC_BASE_URL override changes, so the warning no longer repeats per result. agent-runtime.md now describes cost behind a proxy. The tests/registry.json entry is updated, and so is the PR description.

Written with Claude Code.

@vybe

vybe commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-11-04): re-validated at f6c2219c0 on a scratch merge with today's dev. All three points from 10-11 are closed, and the tests now drive the production parsers. Thanks for those. This still cannot ride, for two reasons.

Blocked on a product ruling. ent#1001 has since closed the .env route this issue reproduces with, and #2982 is still incubating. The open question for the operator is: should Trinity take OpenRouter repricing now for container-baseline proxies only, or hold it until #2982 provides a sanctioned proxy path? Nothing for you to do on that yet.

Findings to fix if it goes ahead:

  1. A sentinel price records $0 (provider_pricing.py:56, and the total at :190). The live /api/v1/models list has 7 models priced "-1", including openrouter/auto. That runs through process_stream_line as cost_usd=0.0 against a native 0.5, and loop_service.py:260 counts only cost > 0, so max_cost_usd silently stops counting those runs. This is against the issue's "falls back to native when it cannot be determined". "NaN" gives nan, 1e308 gives inf, a boolean gives $1 per token, and negative modelUsage tokens give a negative cost. Please drop any model whose price is missing, negative, non-finite or non-numeric, and return native unless the total is finite and non-negative. The vendor/garbage contract test pins the current behaviour and has to change too.
  2. The UI transcript keeps the Anthropic price. ExecutionDetail.vue:893 and TasksPanel.vue:1211 read msg.cost_usd ?? msg.total_cost_usd from the raw execution_log, which turn_cost does not touch. Stamping cost_usd on the raw result message fixes it, since the UI already prefers that. This one is from reading the code, not a browser run.
  3. It needs dev merged in. It conflicts in docs/memory/architecture/agent-runtime.md only, and this head has no check runs yet.

Smaller points: a 200 with an empty data list replaces the good prices for 6 hours (provider_pricing.py:88), and the startup hook, the cache_write arithmetic and the failure guard are not pinned by a test.

@vybe

vybe commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Product ruling (2026-11-19): go ahead now, for container-baseline proxies only. Recording the wrong price for a turn is a correctness problem on its own, and it does not need to wait for #2982: the pricing logic keys on the proxy host the container already runs with, so it carries over unchanged when #2982 adds a sanctioned way to set that host. The scope stays as ent#1001 left it, with no .env route.

@jjaeger94 that unblocks the three findings from the 11-04 note, which are now the whole list:

  1. Drop any model whose price is missing, negative, non-finite or non-numeric, and return the native figure unless the total is finite and non-negative (the -1 sentinel currently records $0). The vendor/garbage contract test changes with it.
  2. Stamp cost_usd on the raw result message so the transcript in ExecutionDetail.vue and TasksPanel.vue shows the same price.
  3. Merge dev (one conflict, in docs/memory/architecture/agent-runtime.md).

Please also say in the PR description that this covers container-baseline proxies only. status-needs-fix stays until that push; on a fork it is lifted by hand, so comment here when it is up.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants