Repository navigation
fix: preserve OpenCode provider-reported costs in metrics - #3780
Conversation
…tence OpenCode step_finish events carry the provider's actual cost in part.cost, but the parser dropped it and the metrics pipeline fell back to catalog pricing, which custom LiteLLM model ids do not have. The result was a zero llm_executions cost and a NULL llm_logs cost. Parse per-step costs (counted once per part id) and cumulative result totals (replace, never add), carry the value as providerCostUsd through AgentExecutionResult, ClaudeCodeResponse and ClaudeResult, and prefer a valid reported cost over the catalog estimate. Missing and invalid costs fall back to the existing behaviour; a reported zero is kept. Co-authored-by: Copilot <[email protected]>
|
/review astra fable |
|
✅ AI Code Review Complete requested by @integry Posted 2 reviews: |
🔍 AI Code Review — astraOverall EvaluationThis PR needs changes before merge. It carries OpenCode’s reported cost through task execution and several job adapters, but PR reviews still lose that cost. The parser can also promote a partial step subtotal to the authoritative price for a whole run. The visible objective identifies missing detail records on large executions, and the PR leaves that part unresolved. The supplied issue description ends mid-section, so its remaining acceptance criteria could not be assessed. ✅ Reported zero survives — The task adapters preserve an explicit ✅ Repeated steps are counted once — The parser deduplicates reported step costs by part ID. A focused test covers a repeated part followed by a distinct billable step. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F1: 🔴 PR review executions still lose provider cost
F2: 🔴 A partial step subtotal overrides whole-run pricing
F3: 🔴 Large-execution detail persistence remains unresolved
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Test the stored log costThe log tests stop at the object returned by ScoreThe task path handles reported zero and duplicate steps correctly, but review executions and mixed-cost runs can still record the wrong price. Large-run detail persistence remains unverified, and all three current head checks were skipped. Score: 5/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
🔍 AI Code Review — fableOverall EvaluationThe PR reads the cost OpenCode emits on I found no verified blocker in the changed code. I would not call it merge-ready yet, for three reasons:
The issue and PR descriptions are truncated in the supplied context, so I could not check the full acceptance criteria. ✅ Separate field for "reported" versus "estimated" — ✅ Additive step costs with repeat protection — ✅ Failure paths keep the spend — Merge blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S2: 🟢 Confirm a reported zero is really a cost
S3: 🟢 Analysis runs still record $0 executions
S4: 🟢 Issue's missing-detail-records half is untouchedIssue #3781 also reports an execution with a summary row but no S5: 🟢
|
- Propagate providerCostUsd through AnalysisResult, review metrics, and suppressLlmLog analysis callers - Avoid overriding catalog pricing with partial step-cost subtotals or letting a zero cumulative summary erase positive step costs - Refactor OpenCodeAgent.executeTask, applyOpenCodeCost, and calculateCost to satisfy ESLint complexity and max-lines rules - Add regression tests for partial/cumulative cost edge cases, review metrics, and OpenCodeAgent executeTask/analyze wiring Co-authored-by: Copilot <[email protected]>
Summary miners suppress the agent's own log and write one llm_logs row per batch, so the provider cost returned on AnalysisResult was dropped. Sum it across every retry and fallback call; when any call returns no cost, leave it unset so the catalog estimate still applies instead of a partial sum. Adds real-SQLite tests asserting llm_logs.cost_usd for summed retries, partial coverage, an explicit zero, and a failed keyword extraction call. Co-authored-by: Copilot <[email protected]>
|
/review astra fable |
|
✅ AI Code Review Complete requested by @integry Posted 2 reviews: |
🔍 AI Code Review — astraOverall EvaluationThe PR carries OpenCode costs through execution and analysis results into both metrics tables. It needs changes before merge. Two parser branches contradict the stated cost rules, and the new batch accounting can persist a partial retry cost as the full charge. The current head has 20 passed checks and no failed or pending checks. ✅ Provider pricing takes precedence — ✅ Execution and analysis both propagate cost — The agent-level test follows two priced steps through Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F4: 🔴 An unpriced step discards known spend
F5: 🔴 A reported zero total loses precedence
F6: 🔴 Synthetic failover hides charged attempts
F7: 🔴 Rejected attempts bypass batch tracking
SuggestionsThese are optional follow-ups and are not sent to S8: 🟢 Exercise non-finite JSON input directlyThe non-finite parser fixture passes ScoreThe direct execution and analysis paths have good coverage, and all current checks are green. The parser discrepancies and incomplete retry accounting still affect the persisted costs this PR is intended to correct. Score: 5/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
🔍 AI Code Review — fableOverall EvaluationThis PR carries OpenCode's reported cost from ✅ Cost is never double-counted or silently partial — ✅ Zero versus absent is preserved end to end — every adapter forwards with ✅ Other agents are unaffected — only OpenCode sets Merge blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S9: 🟢 Reported zero may mean "price unknown"The PR treats an explicit S10: 🟢 PR description contradicts the partial-cost behaviourThe Limitations section says that when only some S11: 🟢 Tracker misses attempts that never return
S12: 🟢 Cost validity predicate is written three times"Finite, non-negative number" is implemented separately in S13: 🟢 Speculative
|
|
/fix F4 F5 F6 F7 |
|
✅ Applied the requested follow-up changes in commit e82d9c6
Summary of ChangesApplied F4–F7 for PR #3780.
All six targeted test suites passed. Core type checking and linting for the changed source files passed. The LLM Log preview shows the verified Separate observations outside the selected fixes: the LLM Logs API maps stored zero costs to Review digestRisk-tiered paths
Diff size: 7 files changed, +170/−69 lines Visual previewRouted summarization cost in the LLM LogThe Usage column shows $0.750 for a summarization call whose two physical attempts reported $0.25 and $0.50. 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
Applied F4–F7 for PR integry#3780. - OpenCode sums deduplicated, valid step costs when no cumulative total is available. A valid cumulative total takes precedence, including `$0`. - Synthetic routing returns the combined cost of all physical analysis attempts to all four callers. If any attempt’s cost is unknown, the combined total is unknown. - File and directory batches mark cost coverage incomplete when analysis rejects. A later parsing failure preserves any cost the analysis already reported. All six targeted test suites passed. Core type checking and linting for the changed source files passed. The LLM Log preview shows the verified `$0.750` failover total. Separate observations outside the selected fixes: the LLM Logs API maps stored zero costs to `null`, the routing details display raw model IDs, and PR review comments still calculate cost from catalog pricing. PR: integry#3780 Comment by: @integry (ID: 7138343005) Model: GPT-6.2 Sol ProPR-Agent: codex/gpt-6.2-sol
|
/review astra |
|
✅ AI Code Review Complete requested by @integry Posted 1 review: |
🔍 AI Code Review — astraOverall EvaluationThe PR needs a localized correction before merge. It carries OpenCode’s reported cost through execution and analysis, but synthetic routing still loses known spend when every member returns a retryable failure. ✅ Zero survives propagation — The parser, result adapters, and metrics calculation preserve an explicit ✅ Repeated events are handled correctly — Replayed step IDs count once, and a cumulative Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F8: 🔴 Preserve known spend on route exhaustion
SuggestionsThese are optional follow-ups and are not sent to S15: 🟢 Test a decreasing snapshotThe largest-snapshot test supplies ScoreThe direct OpenCode paths and successful failover have substantial coverage. Fully priced route exhaustion still leaves incorrect cost records. No check runs were reported for the current head. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
/fix F8 |
|
✅ Applied the requested follow-up changes in commit 1064f3b
Summary of ChangesF8 is fixed: when a synthetic route runs out of members after every attempt reported a cost, the summed cost now reaches the caller's log instead of being dropped. What changed
One addition beyond the literal findingWhen a member's failure reason contains a retryable-looking word such as "timeout", the batch retry re-enters the already exhausted route. That re-entry runs no attempt, but the tracker treated it as an unknown-cost call and discarded the total again. The error now also carries the number of attempts that ran, and the tracker skips a zero-attempt exhaustion. Retry and fallback behaviour is unchanged. Verification
No visual preview: the change only affects stored cost values on a failure path. Separate observation (not changed)
Review digestRisk-tiered paths
Diff size: 6 files changed, +151/−9 lines 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
F8 is fixed: when a synthetic route runs out of members after every attempt reported a cost, the summed cost now reaches the caller's log instead of being dropped.
## What changed
- **Routing** (`syntheticRoutingService.ts`, `syntheticRoutingTypes.ts`): `SyntheticRoutingSession.analyze` records the accumulated cost on the `SyntheticPoolExhaustedError`. It does so only when at least one attempt ran in that call and every attempt reported a valid cost; a missing cost or a thrown attempt still leaves it unknown.
- **Keyword extraction and semantic scoring**: their failure logs now read the cost from the exhaustion error.
- **File and directory batches** (`analyzeWithProviderCost` in `summaryMinerMetrics.ts`): the tracker adds the exhaustion error's cost instead of marking the total unknown, so a priced fallback afterwards yields the full sum.
## One addition beyond the literal finding
When a member's failure reason contains a retryable-looking word such as "timeout", the batch retry re-enters the already exhausted route. That re-entry runs no attempt, but the tracker treated it as an unknown-cost call and discarded the total again. The error now also carries the number of attempts that ran, and the tracker skips a zero-attempt exhaustion. Retry and fallback behaviour is unchanged.
## Verification
- `test/summaryMinerBatchFallback.test.ts` passes 44/44; the 9 new regressions fail with the source change reverted.
- New regressions cover:
- fully priced exhaustion for all four callers ($0.25 + $0.50 logged as $0.75).
- exhaustion followed by a priced fallback for file and directory batches ($0.875).
- exhaustion with a missing or thrown attempt cost (stays unknown).
- an all-zero total.
- Core `tsc --noEmit` and `eslint src/ --max-warnings 0` are clean. To stay under the 400-line lint limit in `syntheticRoutingService.ts`, I merged its two imports from `syntheticRoutingTypes.js` into one.
- `planFileGeneration`, `opencodeCostReporting`, `llmMetricsProviderCost` and `reviewResultMetricsReasoningLevel` pass.
- `opencodeExecutionLog` has one failing test, with or without this change: it cannot create a temp directory under the read-only `/tmp/git-processor` in this container.
No visual preview: the change only affects stored cost values on a failure path.
## Separate observation (not changed)
`withRetry` treats a pool-exhaustion error as retryable whenever a member's failure reason matches its message patterns ("timeout", "connection", …), so an exhausted route gets pointlessly re-entered up to three times before fallback.
PR: integry#3780
Comment by: @integry (ID: 7141747175)
Model: Claude Fable 5.2
ProPR-Agent: claude/claude-fable-5-2
|
/review astra |
|
✅ AI Code Review Complete requested by @integry Posted 1 review: |
🔍 AI Code Review — astraOverall EvaluationThe PR carries OpenCode’s reported cost from JSONL events into execution metrics and analysis logs. It needs minor changes before merge. A capacity wait can still erase a fully known batch cost, and a post-execution verification failure can leave the execution metric inconsistent with its log. No check runs were reported for the current head. This was a read-only static review. ✅ Zero survives the full path — The parser, result adapters, and metrics calculation preserve an explicit ✅ Repeated events are handled correctly — The parser counts each priced step ID once and gives a cumulative result total precedence over the step sum. Tests cover both a repeated step and a zero cumulative total following positive steps. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F9: 🔴 Preserve known spend across capacity waits
F10: 🔴 Keep cost through post-execution verification
SuggestionsThese are optional follow-ups and are not sent to S16: 🟢 Exercise a decreasing cumulative snapshotThe test named “keeps the largest cumulative total” uses ScoreThe primary reporting path handles zero, duplicates, and catalog fallback well. Two localized failure paths still lose known spend or produce conflicting accounting records. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
/fix F9 F10 |
|
✅ Applied the requested follow-up changes in commit 759226d
Summary of ChangesF9 and F10 are both fixed, with regressions that fail on the previous code and pass now. Core F9: known spend across capacity waits
The cost-summing logic moved into two small helpers in Regressions in
F10: cost through post-execution verificationIn The regression in Separate observations (not changed)
No visual preview: the change is not user-visible. Review digestRisk-tiered paths
Diff size: 6 files changed, +226/−37 lines 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
F9 and F10 are both fixed, with regressions that fail on the previous code and pass now. Core `tsc --noEmit` and `eslint src/ --max-warnings 0` are clean, and the summary-miner, OpenCode, capacity and synthetic-routing suites I ran all pass. ## F9: known spend across capacity waits - **Selection-time wait:** a capacity error raised while selecting the next member now carries the call's attempt count and accumulated cost. It is the same error object, so its capacity-error identity is unchanged. - **Tracker:** a wait with no attempt behind it is ignored, and a wait after priced attempts adds their total. Both file and directory batch logging now keep the full sum when a later retry succeeds. - **Same defect in sibling paths, also corrected:** - A capacity error thrown by the physical member itself (admission wait) was passed through unannotated; it now carries the prior spend too. - `OpenCodeAgent.analyze` returns a capacity wait as a failed result rather than throwing. The routing session now treats that as zero spend, not unknown spend. - Keyword extraction and semantic scoring read the same carried cost, so they pick this up without their own change. The cost-summing logic moved into two small helpers in `syntheticRoutingTypes.ts` to keep `syntheticRoutingService.ts` under the 400-line and complexity lint gates. Regressions in `test/summaryMinerBatchFallback.test.ts` (9 new cases): - wait at selection and at admission after a `$0.25` attempt. - wait before the first attempt. - wait returned as a failed result. - file and directory batches where a retry succeeds after the wait (`0.75` after a priced attempt, `0.5` after none). - a direct agent with no routing session. ## F10: cost through post-execution verification In `OpenCodeAgent.executeTask`, verification now runs on the completed response before the log is written. If it throws, that same response is marked failed with the verification message, keeping its cost, tokens and session id, and the log is persisted once. The regression in `test/opencodeExecutionLog.test.ts` asserts one failed log with `costUsd` 0.75 and a returned failure with the same `providerCostUsd`. ## Separate observations (not changed) - The session only arms selection-time capacity deferral for the first selection, so the F9 trace (a selection-time wait after a priced attempt) is not reachable through the built-in selector today. The regression simulates it by overriding `select`; the admission-wait and failed-result paths are the ones that occur in practice. - In this container, the existing analyze test in `opencodeExecutionLog.test.ts` only passes with `OPENCODE_ANALYSIS_ROOT` pointed at a writable directory, because `/tmp/git-processor` is read-only here. That is environmental, not caused by this change. No visual preview: the change is not user-visible. PR: integry#3780 Comment by: @integry (ID: 7144025768) Model: Claude Fable 5.2 ProPR-Agent: claude/claude-fable-5-2
|
/review |
|
✅ AI Code Review Complete requested by @integry Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR carries OpenCode’s reported cost through parsing, result adapters, execution metrics, and logs. The retry and failover accounting is consistent with preserving known totals without presenting incomplete totals as authoritative. Ready to merge within the reviewed scope. ✅ Zero remains meaningful — Parsing and metrics distinguish an explicit zero from missing cost, and valid provider costs take precedence over catalog estimates. ✅ Failure costs are retained — Failed-result adapters and OpenCode logging preserve reported spend, including the post-execution verification path. ✅ Coverage follows propagation — Added tests cover parsing, adapter forwarding, persistence, retries, failover, and capacity waits. This was a static review of the supplied code. No commands or tests were run, as requested. No current-head check runs were reported. Merge blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S17: 🟢 Isolate parser testsConsider separating the pure parsing tests in ScoreThe implementation addresses the stated objective with substantial coverage and no verified merge blockers. Runtime validation remains unconfirmed in this review. 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
@czehentner please check if the PRs still look good and work as intended after the fix loops |
@integry from a visual check they look good, I will be able to deploy to my staging not before tomorrow to confirm with my live setup. |
|
🔀 Resolved merge conflicts from Conflicting Files
Resolution SummaryThe merge is resolved. Both branches had added the same feature: an optional The three flagged conflicts:
Two problems git merged without flagging: the typecheck showed that git had kept both sides' declarations of the field. That caused
In both I removed Checks on the merged tree:
🤖 Resolution Details
System-triggered merge conflict resolution |
Automatically resolved merge conflicts after merging target branch into PR branch. Resolved conflicts in: - packages/core/src/agents/types.ts - packages/core/src/utils/llmMetrics.ts - src/jobs/prCommentJobUtils.ts PR: integry#3780 Model: Claude Opus 5.5
|
@integry confirmed in local staging. cost reports come through via opencode 👍
|
|
/review |
|
/review |
|
✅ AI Code Review Complete requested by @integry Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR carries OpenCode’s reported cost through execution, analysis, logging, and metrics, with substantial coverage for retries and failover. It needs one localized correction before merge: direct-agent capacity waits returned as failed results incorrectly invalidate subsequent known costs. ✅ Zero remains meaningful — Parsing and metrics distinguish an explicit zero from an absent cost, preserving provider precedence over catalog estimates. ✅ Failover accounting — Routed analysis totals include priced failed attempts, and tests cover exhaustion, fallback, and unknown spend. The supplied current-head status reports 20 passed checks and no failed or pending checks. This review uses static analysis of the supplied code; no commands were run. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F11: 🔴 Returned capacity waits invalidate known costs
SuggestionsThese are optional follow-ups and are not sent to S18: 🟢 Remove duplicate cost assignments
ScoreThe implementation has strong coverage and passing current-head checks, but one reachable retry path still loses the provider cost this PR intends to preserve. The required correction is localized. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
/fix F11 |
|
✅ Applied the requested follow-up changes in commit 82838d6
Summary of ChangesF11 is fixed: a capacity wait that a direct agent returns as a failed result no longer marks the batch's known cost as incomplete. What changed
Regressions added (
|
| Command | Description | Example |
|---|---|---|
/merge |
Merge target branch into this PR and resolve conflicts | /merge |
/review |
Request an AI code review | /review or /review claude-sonnet |
/fix |
Address review blockers, or blockers and suggestions with /fix all |
/fix, /fix all, or /fix F3 S5 |
/switch |
Change the AI model for this PR | /switch claude-opus |
/use |
Override the model for a single follow-up run | /use claude-sonnet |
/ultrafix |
Loop review→fix cycles until score goal is met | /ultrafix or /ultrafix goal=8 max=10 |
🤖 Generated by ProPR
Processing comment ID: 7296908608✓
F11 is fixed: a capacity wait that a direct agent returns as a failed result no longer marks the batch's known cost as incomplete.
## What changed
- **`summaryMinerMetrics.ts`**: `analyzeWithProviderCost` now runs returned results from direct agents through `analysisAttemptCost`. A failed result that only waited for capacity and reports no cost is treated as "no provider reached", the same as the thrown form.
- **`summaryMinerBatch.ts` / `summaryMinerDirectoryBatch.ts`**: both callers pass a new `routed` flag (`!!routingSession`). Routed results are taken as reported, because the routing session has already classified its attempts. Reclassifying them would let a capacity result hide an earlier unpriced attempt.
## Regressions added (`test/summaryMinerBatchFallback.test.ts`)
- File and directory batch: a priced attempt followed by a direct agent returning a capacity wait logs the priced attempt's cost (0.25) instead of `NULL`.
- Tracker level: returned capacity wait, then a priced retry, gives 0.5.
- The existing thrown capacity wait test now also covers the directory batch.
- Guards: a non-capacity failed result still leaves the total unknown, and a routed capacity result without a total stays unknown.
The suite passes 59/59. With the fix reverted, the three new returned-result tests fail. Core `tsc --noEmit` and eslint on the touched source files are clean, and `opencodeCostReporting.test.ts` passes 14/14.
## Independent discovery (not changed)
The finding's step 4 is not reachable through the batches as written. Once the batch turns the returned failure into a plain `Error`, its message ("Timed out waiting for agent capacity…") matches no retry pattern, so the batch fails instead of retrying; only the thrown form is retried, via the error name. That is why the batch-level regression uses the reachable order (priced attempt first, capacity wait second) and the wait-then-priced-retry order is covered at tracker level. Whether a returned capacity wait should be retried like the thrown one is a separate behaviour question, left alone here.
No visual preview: the change is not visible in the UI.
PR: integry#3780
Comment by: @integry (ID: 7296908608)
Model: Claude Fable 5.2
ProPR-Agent: claude/claude-fable-5-2
|
/review |
|
✅ AI Code Review Complete requested by @integry Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR carries OpenCode’s reported cost through execution results, analysis results, metrics, and logs, while accounting for retries and synthetic failover. It is merge-ready within the reviewed scope, conditional on pending checks completing successfully. ✅ Zero remains meaningful — Parsing and propagation distinguish an explicit zero from missing cost, and metrics prefer valid provider totals over catalog estimates. ✅ Retry costs remain complete — Batch tracking accumulates priced attempts and leaves totals unknown when an actual attempt lacks pricing, preventing a partial total from being reported as authoritative. ✅ Relevant regression coverage — Added tests cover duplicate step IDs, cumulative totals, failed calls, fallback attempts, capacity waits, and downstream persistence. This assessment is based on static review of the supplied diff and context. No commands or tests were run. The supplied current-head status reports no failed checks, with ten pending. Merge blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S19: 🟢 Remove duplicate cost assignmentsIn S20: 🟢 Clarify verification test boundariesThe new post-execution verification test mocks ScoreThe implementation addresses the cost-reporting objective with substantial coverage of propagation and recovery paths. Static review found no merge blockers; pending checks still need to complete. Score: 8/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
Merged, thank you! The follow-up keeps a capacity wait that returns as a failed result from voiding the known cost, with a regression test, and CI was fully green on the final head. |
Brings czehentner's OpenCode cost reporting (integry#3780) and execution-detail persistence (integry#3782) into the epic. Conflicts resolved by keeping both sides: reported provider cost and detail persistence from main, compute usage and the runtime abstraction from the epic. Main's OpenCode response builder now types its result from runAgent and wraps it with attachComputeUsage. Co-Authored-By: Claude Opus 5.5 <[email protected]>


Summary
refs #3781
OpenCode reports the provider's actual cost in
step_finishevents (part.cost). That value was dropped at parse time, so metrics fell back to model-catalog pricing. Custom LiteLLM model ids have no catalog entry, sollm_executions.cost_usdbecame0andllm_logs.cost_usdbecameNULL, even though token counts were recorded correctly.Root cause (verified against current code)
parseOpenCodeJsonl()aggregated tokens only and never readcost.OpenCodeAgenttherefore had no cost to put onAgentExecutionResult, and never passed one tocreateLlmLogFromAgentExecution().toClaudeResult()(and the otherAgentExecutionResult/ClaudeCodeResponse→ClaudeResultadapters) did not forward a cost.calculateCost()inllmMetrics.tsonly used the catalog, falling back tofinalResult.*cost*(never set for OpenCode);persistLlmLog()then computed a catalog estimate that returnsundefinedfor unknown models →NULL.Changes
openCodeParsing.ts: extract cost.step_finishparts add their own cost; a repeated part id is counted once.resultevents carry a running total, which replaces the step sum (max over snapshots) so nothing is double-counted.0is a real cost; no cost →undefined.OpenCodeAgent.ts: setscost/providerCostUsdon the result andcostUsdon both log paths (execution and analysis).providerCostUsdonAgentExecutionResult,ClaudeCodeResponseandClaudeResult, forwarded by the issue, PR-comment, error-handler, goal-metrics and failed-execution adapters.llmMetrics.ts: a valid provider cost is preferred over the catalog estimate; otherwise the existing logic is unchanged.llmLogger.ts:createLlmLogFromAnalysisacceptscostUsd(the existingpersistLlmLogalready keeps a provided cost, including0).Token accounting (including cache-read handling) is untouched. Other agents never set
providerCostUsd, so their behaviour is unchanged.Tests
test/opencodeCostReporting.test.ts: multiplestep_finishsums, duplicate parts, cumulative totals without double counting, explicit zero vs missing, invalid values, non-cost events, unchanged token usage,toClaudeResult()/ failure adapters / log-entry propagation.test/llmMetricsProviderCost.test.ts: custom model unknown to the catalog, provider cost beats catalog, reported zero, invalid costs fall back, catalog fallback preserved.llmLogger,llmMetrics*suites still pass (llmMetrics.test.tsneeds a live Redis and was not run).npx tsc --noEmit(core) andeslint src/are clean.Before / after
llm_executions.cost_usd0.000.8750for three steps of 0.25 + 0.5 + 0.125)llm_logs.cost_usdNULLLimitations
step_finishevents carry a cost, the known costs are summed (an undercount, but better than0).step_finishparts andresultsummary events only.