← Back to Pull requests

feat(agents): OpenCode reports each turn's token usage, counted at a model relay of its own #865

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 21, 2026 05:28 UTC
Author

What changes

The OpenCode agent sent only Usage(tool_call_count=...), so its tokens and cost were never seen. Now each turn reports what every model call it made used, counted at a model relay of the turn's own. This is P8's third PR (FD-5980), after Claude Code and Codex (#850) and Gemini (#861); Letta Code follows on the same relay.

  • A model relay per turn (src/agent_env/utils/model_relay/model_relay.py, new). OpenCode's provider baseURL now points at a loopback relay, which forwards each call to the endpoint as the endpoint answered it.

  • - Each POST to Chat Completions, Responses or Messages is counted from the answer's own usage, read with Usage.from_model_response. That is the last usage of a stream (OpenCode always asks for it: include_usage), or a JSON body's.
    - A refused call (an error status, or none at all) counts nothing. One answered without usage, or with only zeros, counts as unreported.
    - An answer is read to its end even when the CLI hung up, so a call in flight when the CLI was stopped is still counted if it completes within the relay's 5 s shutdown.
    - It asks for answers uncompressed, so their usage can be read.
    - Its path names a token of the turn's own, so a process left from another turn reaches no other turn's relay.
    - It can replace the CLI's headers with its own and answer GET .../models itself, which Letta Code needs next. OpenCode keeps sending its own key and attribution headers, as before.
  • The relay is shared through agent-env's own sources. utils/model_relay is a shared source (shared_sources.toml) that OpenCode's image and install.sh copy beside the bridge, as they already do the egress rule. Letta Code takes the same file next.

  • The turn's usage is the relay's count (opencode_bridge.run_opencode): every step, a subagent's session, compaction, the session title and an answered retry. input_tokens counts the cache; provider_details has model_calls and unreported_calls. The timeout and turn-limit paths keep it too.

  • The agent adds aiohttp (the relay's server and client, as Letta Code's) and raises its protocol floor to 0.1.597, the first whose Usage has the cache fields, so it gets a new image. The README says how usage is counted.
  • How the design was chosen

    A workflow read the agent and OpenCode 1.17.18's source: a reader, then a skeptic who checked each claim (29 claims; 1 corrected) and looked for calls the reader missed. OpenCode's own step_finish parts carry each step's tokens. They miss several kinds of call:

  • the title call, which writes no part;

  • a call answered before its first chunk, or in flight when the bridge stops the CLI;

  • a subagent's steps, which are in child sessions the parsed stream leaves out unless exported one by one.
  • Their cache write is always empty, and their input is clamped. A relay sees every call the provider makes, whatever OpenCode's internals do between releases.

    Decisions to review

  • The session title stays on. The reading proposed turning OpenCode's title call off, since no output records it. With the relay it's counted like any other call, so there's no reason left to change the agent's behaviour.

  • The relay is a shared source, not a copy in each agent. One file, tested once (tst/unit/agents/test_model_relay.py), taken by every agent that counts at a relay.
  • Tests

  • tst/unit/agents/test_model_relay.py, the relay on loopback against a stand-in endpoint:

  • - A streamed Claude answer is forwarded byte for byte and counted from its last usage (cache read and write). Responses' response.completed, Messages' message_start and message_delta, and a JSON body are read too.
    - A 429 counts nothing; a 200 without usage, or with zeros, is unknown.
    - A call whose client hung up mid-stream is read to its end and counted.
    - Another turn's token reaches nothing, and models is answered locally.
    - The relay's headers replace the CLI's when it has some.
    - An unreachable endpoint is a 502 that counts nothing.
  • test_opencode_bridge_config.py: the provider's baseURL is the relay's, the relay forwards to the endpoint's API root, the CLI's own LITELLM_BASE_URL is unchanged, and the turn's usage is the relay's count. That count, on the recorded opencode-baseline-claude turn, equals the proxy's 19,489 in (9,342 read from the cache, 9,539 written) and 105 out.

  • The OpenCode tests use a stand-in relay (a fixture), since the unit tier blocks sockets.

  • All 1,146 agent tests and the build-context, bundle and published-image tests (1,535) pass.
  • E2E against the real proxy

    On an admin host, on this branch's image, through a logging pass-through in front of Scale's LiteLLM proxy. Each run's stored entries were compared with the proxy's usage for every call the solver made:

    | Scenario | Model | Calls | Stored entry |
    |---|---|---|---|
    | One turn | claude-haiku-4-5 | 3 (title included) | exact: 19,489 in, 9,342 cache read, 9,539 written, 105 out |
    | One turn | gpt-4.1-mini | 3 | exact |
    | A chat with a user simulator | claude-haiku-4-5, gpt-4.1-mini | 5 + 2 | exact, both roles |
    | A chat with a user simulator | gpt-4.1-mini, gpt-4.1-nano | 5 + 3 | exact, both roles |
    | A subagent | claude-haiku-4-5 | 5 | exact, the child session's calls included |
    | A subagent | gpt-4.1-mini | 5 | exact |
    | An effort setting | claude-haiku-4-5 | 3 | exact |
    | Stopped at its turn limit | gpt-4.1-mini | 2 | exact |
    | One turn | gemini-2.5-flash | 3 | 3 unreported, no counts: Scale's proxy sent no usage on these streamed chat completions (the pass-through saw none either) |

    Before this PR each of those entries had no tokens at all.

    Chaos

    A 25-minute chaos run with injected 500s is running; its results go here.

    Images

    The agent's folder changed, so it gets a new image at the next release, promoted on its own (S6).

    Docs

    For FD-6263 (P7/P8 items) and FD-6442: OpenCode reports tokens and cache tokens for every call a turn makes, subagents, compaction and the title included, counted at a model relay; a refused call counts nothing and one answered without usage is unreported; Scale's proxy sends no usage on Gemini's streamed chat completions, so OpenCode's Gemini turns are unknown there. For agent authors: the shared model relay, and how an agent takes it (shared_sources.toml).

    🤖 Generated with Claude Code

    <!-- greptile_comment -->

    <!-- greptile_summary -->

    <h2><a href="https://app.greptile.com/api/retrigger?id=114969869&amp;sig=7209aaf13f23e6fb21ec3088a6a90eea78e14db13b03246b209257da43236a7c"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2" align="right"></picture></a><a href="https://app.greptile.com/-/switch-tenant?tenant=scale-ai&amp;next=%2Fscaleapi%2Fagentenv-framework%2Fpull%2F865&amp;utm_source=greptile_review&amp;utm_medium=github&amp;utm_campaign=view_in_greptile"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img alt="View in Greptile" src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2" align="right"></picture></a>Confidence Score: 5/5</h2>

    <!-- greptile-impact-verdict --> The PR appears safe to merge; no new blocking issues were found.

    <h3>Summary</h3>

    OpenCode now reports each turn's model usage through a shared loopback relay.

  • OpenCode turns now report token and cache usage from every answered model call.
  • <!-- greptile_confidence_score:5 -->

    <sub>Reviews (3) · Last reviewed commit: "fix(agents): the model relay judges an a..." · Reviewed by Greptile</sub>

    <!-- /greptile_comment -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: greptile-apps[bot] Review duration: 18m
    All Vouch review confidence checks passed
    Residual risk 0.48 = Change Risk (0.80) × (1 − Review Confidence (0.40)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.80 · 650 lines diff across 8 files
    0.80
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    40%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Sensitive Paths sensitive_paths
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #865"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: medium confidence: 40.5% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 80.2% (HIGH) · Higher = larger blast radius
    80.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 40.5% · Lower = rushed or shallow review
    40.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 47.8% · Moderate risk
    47.8%