Skip to content
Source
Sign inSign up
TanStack/ai

ai-claude-code: usage.cost is the whole session's spend when a run resumes a Claude Code session #2222

Openozolcar(GitHub profile, opens in a new tab) opened this issue 2 comments
ozolcar(GitHub profile, opens in a new tab)commented

TanStack AI version

@tanstack/ai 1.8.0, @tanstack/ai-claude-code 1.0.3, @tanstack/ai-sandbox 1.5.0, @tanstack/ai-sandbox-local-process 1.0.0 (all latest on npm)

Framework/Library version

Node 26.12.0, server only (no UI framework involved)

Describe the bug and the steps to reproduce it

When a chat() run resumes an earlier Claude Code session (modelOptions.sessionId, which becomes --resume), the CLI's result.total_cost_usd covers the whole session, not only this run: the CLI saves the session's totals when it exits and restores them on resume (Agent SDK docs, Track cost and usage, "Accumulate costs across multiple calls"). buildUsage copies it into usage.cost unchanged (src/stream/translate.ts:115, result.cost = totalCostUsd, read from message.total_cost_usd at :447). usageAttributes then sends that figure as gen_ai.usage.cost (@tanstack/ai src/middlewares/usage-attributes.ts). So summing usage.cost per run counts a resumed session's earlier spend again on every run.

The fake CLI below reports a session total the way the CLI does on --resume: run 1 costs $0.25 and the resumed run 2 costs $0.50, so run 2 reports $0.75. The repro shows that the adapter passes that total through as run 2's usage.cost.

Steps:

  1. Install @tanstack/ai@1.8.0, @tanstack/ai-claude-code@1.0.3, @tanstack/ai-sandbox@1.5.0 and @tanstack/ai-sandbox-local-process@1.0.0 in an ESM package, and create an empty work/ folder.
  2. Save fake-claude.mjs and repro.mjs below next to each other, and run chmod +x fake-claude.mjs.
  3. Run node repro.mjs.

fake-claude.mjs (make it executable with chmod +x):

#!/usr/bin/env node
// Stands in for the `claude` CLI. Records argv and the thinking env, then prints the
// stream-json lines that @tanstack/ai-claude-code parses.
import { writeFileSync } from 'node:fs'

for await (const _ of process.stdin); // read the prompt, as the CLI does (exiting first gives the runner EPIPE)
const argv = process.argv.slice(2)
writeFileSync(new URL('./last-call.json', import.meta.url), JSON.stringify({ argv, MAX_THINKING_TOKENS: process.env.MAX_THINKING_TOKENS }))

// On --resume the CLI restores the session's saved totals, so result.total_cost_usd is the
// session total (https://code.claude.com/docs/en/agent-sdk/cost-tracking). Here
// run 1 costs $0.25 and the resumed run 2 costs $0.50, so run 2 reports $0.75.
const resumed = argv.includes('--resume')
const say = (line) => console.log(JSON.stringify(line))
say({ type: 'system', subtype: 'init', session_id: 'sess-1', model: 'x', tools: [] })
say({ type: 'assistant', parent_tool_use_id: null, message: { id: resumed ? 'm2' : 'm1', content: [{ type: 'text', text: 'ok' }] } })
say({ type: 'result', subtype: 'success', usage: { input_tokens: 1, output_tokens: 1 }, total_cost_usd: resumed ? 0.75 : 0.25 })

repro.mjs:

// #2222: usage.cost is the session total, not this run's cost, when a run resumes a session.
import { chat } from '@tanstack/ai'
import { claudeCodeText } from '@tanstack/ai-claude-code'
import { defineSandbox, withSandbox } from '@tanstack/ai-sandbox'
import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'

const sandbox = defineSandbox({ id: 'repro', provider: localProcessSandbox({ dir: new URL('./work', import.meta.url).pathname }) })
const adapter = claudeCodeText('claude-opus-4-8', { claudeExecutable: new URL('./fake-claude.mjs', import.meta.url).pathname, emitDiff: false })

const costs = []
for (const sessionId of [undefined, 'sess-1']) {
  const stream = chat({ adapter, messages: [{ role: 'user', content: 'hi' }], threadId: 't1', modelOptions: { sessionId }, middleware: [withSandbox(sandbox)] })
  for await (const c of stream) if (c.type === 'RUN_FINISHED') costs.push(c.usage.cost)
}
console.log(`usage.cost per run: ${costs.join(', ')}; sum ${costs[0] + costs[1]}`)
// Fixed: usage.cost per run: 0.25, 0.5; sum 0.75 (the fake CLI: run 1 costs $0.25, resumed run 2 costs $0.50)

Output:

usage.cost per run: 0.25, 0.75; sum 1

Expected: usage.cost is the cost of this run only (0.25, 0.5; sum 0.75 here), for example the session total minus the total the session reported before this run. Or the adapter puts the session total in its own field (such as providerUsageDetails.sessionTotalCostUsd) and leaves cost empty when it cannot compute a per-run figure.

Inline above. Plain Node script with no network, no model and no API key. fake-claude.mjs stands in for the claude CLI through claudeExecutable: it records the argv the adapter passes and prints the stream-json lines the adapter parses.

Screenshots or Videos (Optional)

None.

Do you intend to try to help solve this bug with your own PR?

Maybe, I'll investigate and start debugging

Terms & Code of Conduct

  • I agree to follow this project's Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
  1. tanstack-source added labelsbug

  2. Thanks for the report, @ozolcar! To help us reproduce this, could you add a minimal reproduction?

    A runnable example makes fixes dramatically faster — you can fork one of the official examples, or use StackBlitz / CodeSandbox. For TypeScript-only issues, a TS Playground link works too.

    Automated triage — a maintainer will follow up.
  3. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer

  4. I added a minimal, runnable reproduction to the description: a plain Node script with no network, no model and no API key, tested on the current npm releases.

Sign in to join this conversation.