From 4b4fba521a7a5db353696fc026452eb1321ab137 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sun, 13 Sep 2026 03:00:37 +0300 Subject: [PATCH 1/2] fix(opencode): bill session-level reasoning tokens at the output rate When none of a session's messages produce a priced call, the SQLite parser falls back to the totals on OpenCode's session row. That path passed tokens_output alone to calculateCost and dropped tokens_reasoning, while still reporting reasoningTokens, so thinking tokens were shown but never charged. OpenCode bills reasoning at the output rate and the per-message path already did the same. Route both the fallback and buildAssistantCall through billableOutputTokens so they share one rule with the cache-rehydration path. The per-message change is behaviour-neutral for opencode and kilo-code; it only removes the hand-rolled sum that let the fallback drift. Refs #1334 --- src/providers/session-message.ts | 7 +++- src/providers/sqlite-session-parser.ts | 10 ++++- tests/providers/opencode-file.test.ts | 20 ++++++++++ tests/providers/opencode.test.ts | 52 ++++++++++++++++++++++++++ 4 files changed, 85 insertions(+), 4 deletions(-) diff --git a/src/providers/session-message.ts b/src/providers/session-message.ts index f4e4eeac..993c9482 100644 --- a/src/providers/session-message.ts +++ b/src/providers/session-message.ts @@ -1,4 +1,4 @@ -import { calculateCost } from '../models.js' +import { billableOutputTokens, calculateCost } from '../models.js' import { extractBashCommands } from '../bash-utils.js' import type { ParsedProviderCall } from './types.js' @@ -133,7 +133,10 @@ export function buildAssistantCall(opts: { let costUSD = calculateCost( model, tokens.input, - tokens.output + tokens.reasoning, + // Same single source of truth the cache-rehydration path uses, so a fresh + // parse and a cached read can never disagree about whether this provider's + // reasoning tokens already sit inside its output count. (#1075, #1334) + billableOutputTokens(opts.providerName, tokens.output, tokens.reasoning), tokens.cacheWrite, tokens.cacheRead, 0, diff --git a/src/providers/sqlite-session-parser.ts b/src/providers/sqlite-session-parser.ts index 925a942b..a39d2841 100644 --- a/src/providers/sqlite-session-parser.ts +++ b/src/providers/sqlite-session-parser.ts @@ -1,7 +1,7 @@ import { readdir } from 'fs/promises' import { join } from 'path' -import { calculateCost } from '../models.js' +import { billableOutputTokens, calculateCost } from '../models.js' import { isSqliteAvailable, getSqliteLoadError, @@ -257,7 +257,13 @@ export function createSqliteSessionParser( if (!seenKeys.has(dedupKey)) { seenKeys.add(dedupKey) const model = sessionTokens.model ?? 'unknown' - let costUSD = calculateCost(model, sessionTokens.input, sessionTokens.output, sessionTokens.cacheWrite, sessionTokens.cacheRead, 0) + // OpenCode stores reasoning in its own session column and bills it + // at the output rate, so it has to join the output bucket here the + // same way the per-message path does. Routed through + // billableOutputTokens so this fallback can never drift from the + // per-message pricing in buildAssistantCall. (#1334) + const outputForCost = billableOutputTokens(config.providerName, sessionTokens.output, sessionTokens.reasoning) + let costUSD = calculateCost(model, sessionTokens.input, outputForCost, sessionTokens.cacheWrite, sessionTokens.cacheRead, 0) if (costUSD === 0 && sessionTokens.cost > 0) costUSD = sessionTokens.cost yield { provider: config.providerName, diff --git a/tests/providers/opencode-file.test.ts b/tests/providers/opencode-file.test.ts index 740ea039..3aa04ddc 100644 --- a/tests/providers/opencode-file.test.ts +++ b/tests/providers/opencode-file.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'os' import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { calculateCost } from '../../src/models.js' import { createOpenCodeProvider } from '../../src/providers/opencode.js' import type { ParsedProviderCall } from '../../src/providers/types.js' @@ -101,6 +102,25 @@ describe('opencode file-based provider - discovery', () => { }) describe('opencode file-based provider - parsing', () => { + it('bills reasoning tokens at the output rate', async () => { + await writeSession({ + messages: [{ + id: 'msg_a', + data: { + role: 'assistant', modelID: 'claude-sonnet-4-20250514', cost: 0, + tokens: { input: 1000, output: 200, reasoning: 500, cache: { read: 0, write: 0 } }, + time: { created: 1 }, + }, + parts: [{ type: 'text', text: 'done' }], + }], + }) + const calls = await parseAll() + expect(calls).toHaveLength(1) + expect(calls[0]!.reasoningTokens).toBe(500) + // Same rule as the SQLite twin: reasoning is billed as output. (#1334) + expect(calls[0]!.costUSD).toBeCloseTo(calculateCost('claude-sonnet-4-20250514', 1000, 200 + 500, 0, 0, 0), 10) + }) + it('extracts tokens, tools, bash commands, and the preceding user message', async () => { await writeSession({ messages: [ diff --git a/tests/providers/opencode.test.ts b/tests/providers/opencode.test.ts index 494cdac6..a7c31cc1 100644 --- a/tests/providers/opencode.test.ts +++ b/tests/providers/opencode.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from 'os' import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { isSqliteAvailable } from '../../src/sqlite.js' +import { calculateCost } from '../../src/models.js' import { createOpenCodeProvider } from '../../src/providers/opencode.js' import type { ParsedProviderCall } from '../../src/providers/types.js' @@ -849,6 +850,57 @@ skipUnlessSqlite('opencode provider - session parsing', () => { expect(calls[0]!.deduplicationKey).toBe('opencode:sess-1:session-level') }) + it('bills session-level reasoning tokens at the output rate', async () => { + const dbPath = createTestDb(tmpDir) + withTestDb(dbPath, (db) => { + db.exec(`ALTER TABLE session ADD COLUMN cost REAL`) + db.exec(`ALTER TABLE session ADD COLUMN tokens_input INTEGER`) + db.exec(`ALTER TABLE session ADD COLUMN tokens_output INTEGER`) + db.exec(`ALTER TABLE session ADD COLUMN tokens_reasoning INTEGER`) + db.exec(`ALTER TABLE session ADD COLUMN tokens_cache_read INTEGER`) + db.exec(`ALTER TABLE session ADD COLUMN tokens_cache_write INTEGER`) + db.exec(`ALTER TABLE session ADD COLUMN model TEXT`) + + insertSession(db, 'sess-1') + db.prepare(`UPDATE session SET cost = ?, tokens_input = ?, tokens_output = ?, tokens_reasoning = ?, tokens_cache_read = ?, tokens_cache_write = ?, model = ? WHERE id = ?`) + .run(0, 5000, 2000, 4000, 3000, 1000, JSON.stringify({ + providerID: 'anthropic', + id: 'claude-sonnet-4-20250514', + }), 'sess-1') + + insertMessage(db, 'msg-1', 'sess-1', 1700000001000, { + role: 'assistant', modelID: 'claude-sonnet-4-20250514', + }) + }) + + const calls = await collectCalls(createOpenCodeProvider(tmpDir), dbPath, 'sess-1') + expect(calls).toHaveLength(1) + expect(calls[0]!.reasoningTokens).toBe(4000) + // OpenCode charges reasoning tokens at the output rate, and + // billableOutputTokens says the same for this provider, so the session-level + // fallback has to price output + reasoning, not output alone. (#1334) + const model = 'anthropic/claude-sonnet-4-20250514' + expect(calls[0]!.costUSD).toBeCloseTo(calculateCost(model, 5000, 2000 + 4000, 1000, 3000, 0), 10) + expect(calls[0]!.costUSD).toBeGreaterThan(calculateCost(model, 5000, 2000, 1000, 3000, 0)) + }) + + it('bills per-message reasoning tokens at the output rate', async () => { + const dbPath = createTestDb(tmpDir) + withTestDb(dbPath, (db) => { + insertSession(db, 'sess-1') + insertMessage(db, 'msg-1', 'sess-1', 1700000001000, { + role: 'assistant', modelID: 'claude-sonnet-4-20250514', cost: 0, + tokens: { input: 1000, output: 200, reasoning: 500, cache: { read: 0, write: 0 } }, + }) + insertPart(db, 'part-1', 'msg-1', 'sess-1', { type: 'text', text: 'done' }) + }) + + const calls = await collectCalls(createOpenCodeProvider(tmpDir), dbPath, 'sess-1') + expect(calls).toHaveLength(1) + expect(calls[0]!.reasoningTokens).toBe(500) + expect(calls[0]!.costUSD).toBeCloseTo(calculateCost('claude-sonnet-4-20250514', 1000, 200 + 500, 0, 0, 0), 10) + }) + it('accepts role "model" as equivalent to "assistant"', async () => { const dbPath = createTestDb(tmpDir) withTestDb(dbPath, (db) => { From 27f46fd73de1cd8a9417a38d0bd4212136964d2b Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sun, 13 Sep 2026 03:00:37 +0300 Subject: [PATCH 2/2] docs: record the OpenCode reasoning fallback fix --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7aa85df..93b2fc8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - **The menubar second row's quota line now names the provider the flame is warning about.** "Quota remaining" picked each provider's *headline* window — weekly, else monthly, and only then the busiest one — which is the Capacity Dock's billing horizon, not a warning: on a machine with Cursor's API window at 100% and Claude's 5-hour window at 18%, the row reported Monthly 9.5% and Weekly 5% and read as if nothing were near a limit. Each provider now contributes its worst window, per-model rows included, which is exactly what the menu-bar flame already tints by, so the two surfaces agree. A provider backing off after a failed fetch keeps its last-known window instead of dropping out, so the row no longer vanishes — resizing the status item — for the length of a retry, matching what the dock shows dimmed. The row is also capped at 24 characters, shortening a long provider name ("GitHub Copilot 12% left · 6d 3h") rather than letting the second line more than double the item's width, and the two-line title now carries a VoiceOver label that reads as one phrase instead of a string with a newline in it. With the setting off nothing changed: the snapshot that feeds the row is no longer even built on a refresh, and the title is the single-row composition it has always been. (#1310) - **Every Copilot credential rung now follows its own GitHub host, not just the two read from files.** #1286 taught `hosts.json` and `apps.json` to carry the host their token came from, but the rungs that carried none — `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, and a token pasted into Settings — were still sent to `api.github.com`, so a user whose only Copilot credential is a GitHub Enterprise Cloud login got a 401 and a terminal failure with no way out. The environment rung now reads `GH_HOST` from the same environment as the token; the `gh` rung resolves the host from gh's own `hosts.yml` (`GH_CONFIG_DIR`, then `XDG_CONFIG_HOME/gh`, then `~/.config/gh`), picking it the way gh picks the host for `gh auth token` and without a second subprocess; and macOS Settings gains a GitHub host field next to the pasted token, defaulting to `github.com` and saved in the same Keychain record as the token so the two can never drift apart. Settings refuses a host no endpoint can be derived from at the field rather than storing it, the connection row no longer promises `api.github.com` before anything has been fetched, and every one of these new host sources is character-validated before a URL is built, so a crafted value such as `evil.com?.ghe.com` fails closed with no request instead of pointing the Authorization header at a host of its own choosing. `codeburn quota` is unchanged: it still reads only the editor-plugin files, which already carry their host. (#1306) - **Copilot live quota works for GitHub Enterprise Cloud enterprises on a `*.ghe.com` host.** Both readers hardcoded `https://api.github.com/copilot_internal/user` and threw away the host their credential came from, so a data-residency enterprise signed in on `.ghe.com` could only ever report `available: false` with "Temporarily unavailable". A discovered credential now carries its host — `hosts.json` is keyed by host and newer `apps.json` files key by `:` — and the request follows it: `api.github.com` for `github.com` and for any rung that carries no host of its own (an app-name `apps.json` key, `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, a pasted token), and `https://api..ghe.com/copilot_internal/user` for an enterprise host. The token and the host always come from the same entry, with `github.com` preferred when several hosts are signed in and otherwise the first `.ghe.com` tenant in sorted order; a host neither rule can address, such as a self-hosted GitHub Enterprise Server install, fails with a message naming that host instead of sending the credential to dotcom, and unreachable-host and HTTP failures name the host that was tried. The macOS Settings connection row now says which host answered. (#1286) +- **OpenCode's session-level fallback now bills reasoning tokens at the output rate.** When none of a session's messages produce a priced call, codeburn falls back to the totals on OpenCode's `session` row, and that path handed `tokens_output` alone to the pricing table while still reporting `tokens_reasoning` separately, so a reasoning model's thinking showed up in the token breakdown but was never charged (4,000 reasoning tokens on Sonnet 4 left a $0.11 session priced at $0.05). OpenCode itself charges reasoning at the output rate and codeburn's per-message path already did; the fallback and the per-message path now both go through `billableOutputTokens`, the same rule the cache-rehydration path uses, so the three can't drift apart again. Displayed token totals are unchanged. (#1334) ## 0.9.24 - 2026-09-04