Repository navigation
Bill the plugin model calls and the session completion tokens (#387, partial) - #394
Conversation
…pletion tokens Closes #387 in part; see the PR for the acceptance criteria this does not meet and why. Two reporting gaps made the plugin's cost look smaller than it is. Capture is a separate `generate.text` call made after the turn. It appears in no session's event stream, so anything reading session usage reports zero for it. Measured on a real seat: about 4.7k tokens per session, roughly a third of what the session itself generated, billed to nobody. The host offers no receipt to fix this with -- `ctx.generate` exposes exactly one member, `text`, and it resolves to `{ text }` with no `usage` and no `tokens` (probed against a running host with a throwaway plugin, 2026-11-11). So the receipt line carries chars/4 and says `receipt=none`, and every surface that renders it says "estimate, no provider receipt". An estimate labelled as one beats a zero that reads as free. `Measured` carried only `input`, `cache.read` and `cache.write`. `input` is the uncached remainder, so the prompt side alone understates a session badly (one bench run reported 13,393 of 187,856 tokens that moved), and the completion side was absent entirely. It now carries `output` and `reasoning`, kept split because on a reasoning-heavy seat that is where the cost goes -- 94% of a capture call's completion tokens were reasoning. Both are optional on the persisted payload: a newer panel reads a file an older plugin wrote, and an absent number stays absent rather than rendering as "generated nothing". A defect the new tests caught before it shipped: `Number("")` is 0, so a `capture_cost` line whose character count failed to render would have been billed as a free capture -- the same error this ticket exists to remove. A blank or non-numeric count is now skipped rather than read as zero. The cost receipt is written after the #211 teardown check, so a pass disposed mid-model-call is not billed: its store is already gone. That undercounts by one call at teardown, and a test pins it so the trade-off is renegotiated rather than lost. - src/identity/host-events.ts: SessionUsage gains output and reasoning - src/status/payload.ts: Measured gains them as optional; StoreCounts gains captureCost - src/status/metrics.ts: captureCost() reads capture_cost evidence, windows it, skips malformed lines - src/capture/runtime.ts: emits capture_cost with session, trigger, chars and estimate - src/tools/status-tool.ts, src/status/report.ts: render both, with the caveat and a reason at zero - test/capture-cost.test.ts: 13 tests, including a parked reply that lands after the turn Co-authored-by: OpenCode <[email protected]>
WhollyMindless
left a comment
There was a problem hiding this comment.
One independently reproduced follow-up on c0462978670639ade042fbf3d6cffb2bec29c0ea:
P2 — the supported message.updated path reports the last message as a session-wide completion total (src/status/report.ts:119, src/events.ts:267, src/identity/host-events.ts:107). The adapter discards message identity, and measuredTurns.set(sessionID, ...) replaces the prior receipt. With final message-1 usage of 50 answer + 20 reasoning and message-2 usage of 60 + 30, the real hook/status path renders 90 completion tok ... (provider-reported, session-wide), although the two messages produced 160. A streaming update to message 1 is included in the probe, so simply summing every event would double-count instead.
Could this either retain the latest receipt per message and sum those for this compatibility path, or label that path's number as the latest message rather than session-wide? A genuinely cumulative session.usage.updated source should keep its replacement semantics. The existing prompt/cache overwrite predates this PR; the new completion-total wording is the part being reported here.
Validation: Windows/Bun 1.4.4; 96 focused capture-cost/host/status/disposal tests pass, typecheck passes, plus one separate harness probe (5 assertions) reproduces the display above. Synthetic event replay only; no claim about incidence on a live current host. The labelled capture estimate and its disclosed teardown undercount are separate from this finding. Please feel free to defer the compatibility path if that is the intended support boundary.
Review finding on #394 (WhollyMindless), reproduced as stated: on the `message.updated` compatibility path the adapter discarded message identity and `measuredTurns.set` replaced the prior receipt, so final usage of 50+20 and 60+30 rendered "90 completion tok ... (provider-reported, session-wide)" where the session produced 160. Fix in the direction the review offered first: retain the latest receipt PER MESSAGE and sum those for the compatibility path. Streaming updates for the same message still overwrite each other (the probe's streaming case is pinned); a second message ADDS. `session.usage.updated` keeps its replacement semantics untouched -- it is genuinely cumulative, and folding it would double-count. - src/identity/host-events.ts: SessionUsage gains messageID (message.updated) and cumulative (session.usage.updated only); foldUsage() owns the per-message ledger; forgetUsage() evicts it - src/events.ts: fold, do not overwrite - src/inject/epochs.ts + src/index.ts: the session LRU evicts the per-message ledger with the epoch, the measurement, and the counters -- nothing outlives its tracked session - test/host.test.ts: the review's arithmetic pinned (160, not 90), streaming overwrite, cumulative replace, eviction-then-fresh-session A host that mixes both sources on one session is undefined by this design (the next message fold ignores the cumulative total); no host observed does, and the two paths were already mutually exclusive in practice. Co-authored-by: OpenCode <[email protected]>
|
@WhollyMindless finding confirmed and fixed in
One boundary stated: a host mixing both sources on one session is undefined here (the next message fold ignores the cumulative total); no observed host does, and the paths were already mutually exclusive in practice. Your note that the prompt/cache overwrite predates the PR is correct — untouched, out of this finding's scope.
|
WhollyMindless
left a comment
There was a problem hiding this comment.
Independently replayed the original message/streaming sequence on 208a73f5ed9a9841b310e20cd0cd89304f0a3586: the report now shows 160 completion tokens (110 answer + 50 reasoning), with the earlier message retained and its streaming replacement counted once. The reported last-message/session-total finding is resolved.
97 focused cost/host/status/disposal tests, the separate hook-to-status replay (5 assertions), and typecheck pass on Windows/Bun 1.4.4. No live-host mixed-source behavior or provider-cost accuracy is claimed.
Union resolution in src/capture/runtime.ts: keep the S1 attested-failures block and the lessonSet, and keep the prompt hoisted so its length can be billed. The hoisted buildCapturePrompt call now passes `attested`, which is what main's inline call did.
Review status: resolved — verified, branch unblocked at
|
The characterization test read only the probe plugin's own file, so deleting the fake model's `usage` block left it green: it could not tell the host's contract apart from a provider that had stopped reporting. The fake now records the final chunk it actually wrote (served.jsonl, exposed at /__served), and the test requires both that the probe's generate call reached the model and that the chunk served back to it carried prompt_tokens 111 / completion_tokens 22. Also from the review: - #394 is OPEN and `capture_cost` is not on any merged tree. The header and the flip instruction now say "PR #394 (open)" instead of sending a future author to a symbol that is not on main. - Route 2 is not blocked. Re-probed with a 20 s timeout on every await, it resolves in 37-80 ms on v2.2.5 and 39-62 ms on the CI pin v2.0.26, and the route-2 session's assistant message carries the provider's numbers in the guest db. The comment now gives the real reason to decline it: it changes what capture writes, which is exactly what AC 3 measures. - Guests this test creates are removed in afterAll, and startFake() reaps its own temp dir in stop(), so a full e2e pass leaves no psi-e2e-fake-* behind. - Each contract gets its own expectation message, so an unrelated new ctx.generate member cannot be read as the usage flip. - The probe plugin types its context structurally in its own file, which returns the branch to main's 542 lint warnings.
There was a problem hiding this comment.
Approving.
The completion-total finding is resolved: the compatibility path keeps a receipt per message and sums them, a streaming update replaces the same message rather than adding to it, and a genuinely cumulative source keeps replacement semantics. The branch also merges ce36c65 cleanly at f2017e3.
Full gate green, CI green. Not merged — the merge is left to a human.
# [0.24.0](v0.23.1...v0.24.0) (2026-11-12) ### Bug Fixes * **inject:** render the memory block in a canonical order so re-ranking stops busting the prompt cache ([2b81069](2b81069)), closes [#162](#162) [#388](#388) * **recall:** make the canonical order total and let the caveat follow the survivors ([b2ee863](b2ee863)), closes [#396](#396) * **status:** sum per-message receipts; session-wide means session-wide ([208a73f](208a73f)), closes [#394](#394) ### Features * **status:** bill the plugin's own model calls and the session's completion tokens ([c046297](c046297)), closes [#387](#387) [#211](#211)
|
🎉 This PR is included in version 0.24.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
Part of #386. Partially addresses #387 — three of its five criteria, and one of them cannot be met with the current host API. Details below rather than in a follow-up comment.
What this does
Capture is now billed. Capture is a separate
generate.textcall made after the turn. It appears in no session's event stream, so anything reading session usage reports zero for it — measured at roughly 4.7k tokens per session, about a third of what the session itself generated, billed to nobody for the plugin's whole history.The session's completion tokens are reported.
Measuredcarried onlyinput,cache.read,cache.write.inputis the uncached remainder, so the prompt side alone understates a session badly (one bench run reported 13,393 of 187,856 tokens that actually moved), and the completion side was absent entirely. Nowoutputandreasoning, kept split: 94% of a capture call's completion tokens were reasoning, and folding them together hides where the cost goes.AC status, stated before review
capture 0 tok — no capture call in the window, and an unread cost renders nothing at allsession=and appears only when the reply landsbilledFromand the plugin's number agree within 2% on the same wire logWhy criterion 1's capture half is unimplementable today
Probed against a running host with a throwaway plugin (
opencode serve+opencode run --server, 2026-11-11):ctx.generatehas exactly one member:text.generate.text({ model, prompt })resolves to{ text }. Nousage, notokens.status/<session>.json, and itsmeasuredreflects only the session's own turns.ctx.sessiondoes exposecreate/prompt/wait. A capture run through those would emit usage events and could be billed honestly, butsession.promptblocks, and moving capture onto it changes its execution path — which would need the transport result re-verified before it could be trusted.So the honest options were: an estimate that says it is an estimate, or a zero. This ships the first.
Defect the new tests caught before it shipped
Number("")is0. Acapture_costline whose character count failed to render would have been billed as a free capture — the exact failure mode this ticket exists to remove. Blank or non-numeric counts are now skipped rather than read as zero.Deliberate undercount, pinned by test
The receipt is written after the #211 teardown check, because a disposed pass has no store left to write to. Its tokens go unbilled. A test asserts this rather than leaving it as an accident, so the trade-off gets renegotiated in one place instead of silently widening.
Verification
bun run gate— 1204 unit tests, 30 e2e against a real opencode host, typecheck and lint clean.Not in this PR
ctx.session.*.