fix(qwen): follow Qwen Code's own rule when the total cannot decide

Without a total in the band, Qwen Code's outputTokenCount falls back to the
auth type: thoughts are inside candidates for openai, openai-responses and
qwen-oauth, beside them otherwise. The auth type rides on user records'
executionContext. Records without one keep thoughts out, the conservative
side Qwen Code's own cost ledger also takes.
This commit is contained in:
Resham Joshi 2026-11-06 05:49:24 -08:00
parent efbc0db4f9
commit c41b4040ae
2 changed files with 38 additions and 11 deletions

View file

@ -36,6 +36,7 @@ type QwenEntry = {
subtype?: string
cwd?: string
model?: string
executionContext?: { authType?: string }
message?: {
role: string
parts: QwenPart[]
@ -69,6 +70,21 @@ function isoTimestamp(value: string | undefined, fallback: string): string {
return fallback
}
// Qwen Code's outputTokenCount (packages/core/src/telemetry/gen-ai-usage.ts):
// thoughts sit inside candidates on the OpenAI-compatible, Responses and Qwen
// OAuth backends and beside them elsewhere; a total in the band both allow
// decides, else the auth type does. Records older than the auth type on user
// records leave it unknown, and then thoughts are not added: the converters
// Qwen Code ships mostly fold them in, and its own cost ledger bills
// candidates alone without a total.
const THOUGHTS_IN_CANDIDATES = new Set(['openai', 'openai-responses', 'qwen-oauth'])
function billedOutputTokens(candidates: number, thoughts: number, total: number, prompt: number, authType: string | undefined): number {
const derived = total - prompt
if (total > 0 && derived >= candidates && derived <= candidates + thoughts) return derived
return authType === undefined || THOUGHTS_IN_CANDIDATES.has(authType) ? candidates : candidates + thoughts
}
function extractTools(parts: QwenPart[]): { tools: string[]; bashCommands: string[] } {
const tools: string[] = []
const bashCommands: string[] = []
@ -97,6 +113,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
const lines = raw.split('\n').filter(l => l.trim())
let pendingUserMessage = ''
let authType: string | undefined
for (const line of lines) {
let entry: QwenEntry
@ -105,6 +122,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
} catch {
continue
}
if (typeof entry.executionContext?.authType === 'string') authType = entry.executionContext.authType
if (entry.type === 'user' && entry.message) {
const texts = (entry.message.parts ?? [])
@ -134,11 +152,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>): SessionPars
const thoughts = usage.thoughtsTokenCount ?? 0
const cachedTokens = usage.cachedContentTokenCount ?? 0
const inputTokens = Math.max(0, prompt - cachedTokens)
// Thoughts sit inside candidates on OpenAI-compatible and Qwen OAuth
// backends and beside them on Gemini; a total in that band says which,
// as Qwen Code's own outputTokenCount (telemetry/gen-ai-usage.ts) decides.
const derived = (usage.totalTokenCount ?? 0) - prompt
const billedOutput = derived >= candidates && derived <= candidates + thoughts ? derived : candidates + thoughts
const billedOutput = billedOutputTokens(candidates, thoughts, usage.totalTokenCount ?? 0, prompt, authType)
const reasoningTokens = Math.min(thoughts, billedOutput)
const outputTokens = billedOutput - reasoningTokens

View file

@ -7,27 +7,29 @@ import { calculateCost, loadPricing } from '../../src/models.js'
import { createQwenProvider } from '../../src/providers/qwen.js'
import type { ParsedProviderCall } from '../../src/providers/types.js'
let dir: string
const dirs: string[] = []
beforeAll(async () => {
await loadPricing()
})
afterEach(async () => {
await rm(dir, { recursive: true, force: true })
await Promise.all(dirs.splice(0).map(d => rm(d, { recursive: true, force: true })))
})
const model = 'qwen3-coder-flash'
async function parseUsage(usageMetadata: Record<string, number>): Promise<ParsedProviderCall[]> {
dir = await mkdtemp(join(tmpdir(), 'codeburn-qwen-test-'))
async function parseUsage(usageMetadata: Record<string, number>, authType?: string): Promise<ParsedProviderCall[]> {
const dir = await mkdtemp(join(tmpdir(), 'codeburn-qwen-test-'))
dirs.push(dir)
const chats = join(dir, '-tmp-demo', 'chats')
await mkdir(chats, { recursive: true })
await writeFile(join(chats, 's1.jsonl'), JSON.stringify({
const user = { uuid: 'u1', sessionId: 's1', timestamp: '2026-10-20T09:59:59.000Z', type: 'user', message: { role: 'user', parts: [{ text: 'go' }] }, executionContext: { modelId: model, authType } }
await writeFile(join(chats, 's1.jsonl'), [...(authType ? [user] : []), {
uuid: 'a1', sessionId: 's1', timestamp: '2026-10-20T10:00:00.000Z', type: 'assistant', model,
message: { role: 'model', parts: [{ text: 'done' }] },
usageMetadata,
}) + '\n')
}].map(r => JSON.stringify(r)).join('\n') + '\n')
const provider = createQwenProvider(dir)
const [source] = await provider.discoverSessions()
const calls: ParsedProviderCall[] = []
@ -57,4 +59,15 @@ describe('qwen provider', () => {
expect(call!.reasoningTokens).toBe(50)
expect(call!.costUSD).toBeCloseTo(calculateCost(model, 1_000, 200, 0, 0, 0), 12)
})
it('without a total, the recorded auth type decides, and an unknown one adds no thoughts', async () => {
const usage = { promptTokenCount: 1_000, candidatesTokenCount: 200, thoughtsTokenCount: 50, cachedContentTokenCount: 0 }
const [gemini] = await parseUsage(usage, 'gemini')
expect(gemini!.costUSD).toBeCloseTo(calculateCost(model, 1_000, 250, 0, 0, 0), 12)
const [openai] = await parseUsage(usage, 'openai')
expect(openai!.costUSD).toBeCloseTo(calculateCost(model, 1_000, 200, 0, 0, 0), 12)
const [unknown] = await parseUsage(usage)
expect(unknown!.costUSD).toBeCloseTo(calculateCost(model, 1_000, 200, 0, 0, 0), 12)
})
})