Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(adapters): price each request's tokens by the arm that signed it
Jack Rudenko7f47a921a9ce
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex 26a42bba..c00127e7 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -136,6 +136,7 @@ import { hasPlanLimitWording, isQuotaExhaustionError } from "./shared/quota-exhaimport { connectionFaultHeaders, recoveryHoldHeaders } from "./shared/recovery-marker.js";import {CREDENTIAL_DECIDED_PROVIDERS,+ type RequestBilling,isSubscriptionProvider,} from "./shared/remote-provider-types.js";import {@@ -613,11 +614,23 @@ export class ComposedHandler implements ModelHandler {*/private markHopSigned(hop: HopAttempt, binding: AuthBinding | undefined): void {hop.arm = binding?.auth?.arm ?? null;+ hop.billing = this.signedBilling(binding).subscription ? "subscription" : "metered";+ }++ /**+ * The billing of a request signed with `binding`, by the rule above: the+ * signing arm for a credential-decided provider, the fixed category for+ * every other one. The ONE derivation shared by the hop label+ * (`markHopSigned`) and the request's cost updates (`handleStream`), so the+ * two cannot disagree.+ */+ private signedBilling(binding: AuthBinding | undefined): RequestBilling {const name = this.provider.name.toLowerCase();- const subscription = CREDENTIAL_DECIDED_PROVIDERS.has(name)- ? hop.arm === "oauth"- : isSubscriptionProvider(name);- hop.billing = subscription ? "subscription" : "metered";+ return {+ subscription: CREDENTIAL_DECIDED_PROVIDERS.has(name)+ ? binding?.auth?.arm === "oauth"+ : isSubscriptionProvider(name),+ };}/**@@ -2970,6 +2983,10 @@ export class ComposedHandler implements ModelHandler {response,adapter,claudeRequest,+ // Decided from the binding this request was finally signed with (a 401+ // re-sign replaced it above); every leg of a Responses turn signs on+ // that same arm, or the leg issuer refuses it.+ this.signedBilling(binding),toolNameMap,onStreamComplete,(code, message) => {@@ -3245,6 +3262,7 @@ export class ComposedHandler implements ModelHandler {response: Response,adapter: BaseModelAdapter,claudeRequest: any,+ billing: RequestBilling,toolNameMap?: Map<string, string>,onComplete?: () => void,onApiError?: (code: string, message: string) => void,@@ -3259,20 +3277,24 @@ export class ComposedHandler implements ModelHandler {// same number and is used for COST ONLY; see UsageCacheDetail and// `context-window.md`, which records what happens when a reduced count// reaches the context accounting (auto-compaction silently disarms).+ //+ // `billing` is THIS request's signing decision, passed into every cost+ // update rather than read from the tracker's pricing lookup, whose+ // credential-decided answer is the process-wide last-signed arm.const onTokenUpdate = (input: number, output: number, detail?: UsageCacheDetail) => {const strategy = this.options.tokenStrategy || "standard";switch (strategy) {case "accumulate-both":- this.tokenTracker.accumulateBoth(input, output, detail);+ this.tokenTracker.accumulateBoth(input, output, detail, billing);break;case "delta-aware":- this.tokenTracker.updateWithDelta(input, output, detail);+ this.tokenTracker.updateWithDelta(input, output, detail, billing);break;case "local":this.tokenTracker.updateLocal(input, output, detail);break;default:- this.tokenTracker.update(input, output, detail);+ this.tokenTracker.update(input, output, detail, billing);break;}// Fire onComplete after token update so recordStats() sees the final token counts.@@ -3366,7 +3388,7 @@ export class ComposedHandler implements ModelHandler {// Earlier legs of a retried turn: cost only, before the stats snapshot// that onTokenUpdate fires.onExtraBilledInput: (input, detail) =>- this.tokenTracker.addBilledInputTokens(input, detail),+ this.tokenTracker.addBilledInputTokens(input, detail, billing),onTurnSummary: responsesTurn?.onTurnSummary,codeMode: responsesTurn?.codeMode,});diff --git a/packages/cli/src/handlers/shared/remote-provider-types.ts b/packages/cli/src/handlers/shared/remote-provider-types.tsindex b537553d..8094710a 100644--- a/packages/cli/src/handlers/shared/remote-provider-types.ts+++ b/packages/cli/src/handlers/shared/remote-provider-types.ts@@ -355,6 +355,17 @@ export function registerDynamicPricingLookup(_dynamicLookup = fn;}+/**+ * How one signed request is billed, decided when it was signed. For a+ * `CREDENTIAL_DECIDED_PROVIDERS` member that is the arm of the credential that+ * signed it (`RequestAuth.arm === "oauth"` ⇒ subscription); for every other+ * provider it is its fixed `SUBSCRIPTION_PROVIDERS` category. Carried with the+ * request into its cost updates, never stored on a shared object.+ */+export interface RequestBilling {+ subscription: boolean;+}+/*** Get pricing for a model.* Lookup order:@@ -370,12 +381,21 @@ export function registerDynamicPricingLookup(* measured dead — see the FREE_PROVIDERS tombstone above for the re-entry test a* genuinely free provider would have to meet. A provider that charges nothing but* is not listed here lands on step 3's estimate, which is a visible guess.+ *+ * `billing` is the decision of ONE signed request (`RequestBilling`). When it is+ * given, it replaces step 1's `isSubscriptionProvider` call, whose answer for a+ * credential-decided provider is the process-wide last-signed arm, which a+ * concurrent request can change before this request's usage arrives.*/-export function getModelPricing(provider: string, modelName: string): ModelPricing {+export function getModelPricing(+ provider: string,+ modelName: string,+ billing?: RequestBilling+): ModelPricing {const p = provider.toLowerCase();// 1. Subscription providers- if (isSubscriptionProvider(p)) {+ if (billing ? billing.subscription : isSubscriptionProvider(p)) {return { inputCostPer1M: 0, outputCostPer1M: 0, isSubscription: true };}diff --git a/packages/cli/src/handlers/shared/token-tracker.ts b/packages/cli/src/handlers/shared/token-tracker.tsindex eec1c130..dcd27b54 100644--- a/packages/cli/src/handlers/shared/token-tracker.ts+++ b/packages/cli/src/handlers/shared/token-tracker.ts@@ -16,7 +16,11 @@ import { TOOL_NAME_SHAPE } from "../../adapters/tool-name-utils.js";import { type PlanUsage, isPlanStale } from "../../auth/quota/types.js";import { log } from "../../logger.js";import { resolveTokenFilePath } from "../../session/token-file.js";-import { type ModelPricing, getModelPricing } from "./remote-provider-types.js";+import {+ type ModelPricing,+ type RequestBilling,+ getModelPricing,+} from "./remote-provider-types.js";export interface TokenTrackerConfig {contextWindow: number;@@ -104,6 +108,15 @@ export function computeCacheReadDiscount(return (discountedTokens / 1_000_000) * perMillionSaved;}+/**+ * Every cost-bearing update below takes an optional `billing`: the decision of+ * the request whose usage it records (`RequestBilling`, decided when that+ * request was signed). Absent, pricing falls back to `isSubscriptionProvider`,+ * which for a credential-decided provider (`openai-codex`) reads the+ * process-wide last-signed arm. The tracker never stores it: one tracker is+ * shared by every request of its handler, so a stored arm would be the same+ * race one level down.+ */export class TokenTracker {private port: number;private config: TokenTrackerConfig;@@ -255,14 +268,19 @@ export class TokenTracker {* Standard update: assign input (latest context), accumulate output.* Used by most remote providers (Gemini, AnthropicCompat, Vertex, RemoteProvider, etc.)*/- update(inputTokens: number, outputTokens: number, detail?: UsageCacheDetail): void {+ update(+ inputTokens: number,+ outputTokens: number,+ detail?: UsageCacheDetail,+ billing?: RequestBilling+ ): void {this.sessionInputTokens = inputTokens;this.lastInputTokens = inputTokens;this.sessionOutputTokens += outputTokens;this.sessionBilledInputTokens += inputTokens;this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;- const pricing = this.getPricing();+ const pricing = this.getPricing(billing);// This strategy charges the whole context every turn, so the whole context// is what the cache discount is clamped against.const cost =@@ -271,20 +289,25 @@ export class TokenTracker {this.cacheReadDiscount(pricing, inputTokens, detail);this.sessionTotalCost += cost;- this.writeFile(inputTokens, this.sessionOutputTokens, pricing.isEstimate);+ this.writeFile(inputTokens, this.sessionOutputTokens, pricing.isEstimate, pricing);}/*** Accumulate both input and output tokens.* Used by OllamaCloud where cost is calculated on cumulative totals.*/- accumulateBoth(inputTokens: number, outputTokens: number, detail?: UsageCacheDetail): void {+ accumulateBoth(+ inputTokens: number,+ outputTokens: number,+ detail?: UsageCacheDetail,+ billing?: RequestBilling+ ): void {this.sessionInputTokens += inputTokens;this.lastInputTokens = this.sessionInputTokens;this.sessionOutputTokens += outputTokens;this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;- const pricing = this.getPricing();+ const pricing = this.getPricing(billing);// ASSIGNED from cumulative totals, so the discount must be cumulative too: a// per-turn subtraction here would be thrown away by the next turn's// assignment. `sessionCacheReadTokens` is the running total, clamped against@@ -302,7 +325,7 @@ export class TokenTracker {// already sums input itself, so `+=` here would count every earlier turn again.this.sessionBilledInputTokens = this.sessionInputTokens;- this.writeFile(this.sessionInputTokens, this.sessionOutputTokens, pricing.isEstimate);+ this.writeFile(this.sessionInputTokens, this.sessionOutputTokens, pricing.isEstimate, pricing);}/**@@ -323,11 +346,15 @@ export class TokenTracker {* follows does. The cache discount uses the same clamp as `update()`, so a* retry that re-sent a cached body is charged as cached.*/- addBilledInputTokens(inputTokens: number, detail?: UsageCacheDetail): void {+ addBilledInputTokens(+ inputTokens: number,+ detail?: UsageCacheDetail,+ billing?: RequestBilling+ ): void {if (!(inputTokens > 0)) return;this.sessionBilledInputTokens += inputTokens;this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;- const pricing = this.getPricing();+ const pricing = this.getPricing(billing);this.sessionTotalCost +=(inputTokens / 1_000_000) * pricing.inputCostPer1M -this.cacheReadDiscount(pricing, inputTokens, detail);@@ -340,7 +367,12 @@ export class TokenTracker {* inputTokens = full context size from the API (not incremental)* Only charges for the delta (new tokens added since last request).*/- updateWithDelta(inputTokens: number, outputTokens: number, detail?: UsageCacheDetail): void {+ updateWithDelta(+ inputTokens: number,+ outputTokens: number,+ detail?: UsageCacheDetail,+ billing?: RequestBilling+ ): void {let incrementalInputTokens: number;// The status file always reports THIS request's context, even when the@@ -375,7 +407,7 @@ export class TokenTracker {this.sessionOutputTokens += outputTokens;this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;- const pricing = this.getPricing();+ const pricing = this.getPricing(billing);this.sessionBilledInputTokens += incrementalInputTokens;// The clamp matters MOST here: this strategy charges only the growth, which// on a cached continuation is a handful of tokens against a cache read of@@ -387,7 +419,7 @@ export class TokenTracker {this.cacheReadDiscount(pricing, incrementalInputTokens, detail);this.sessionTotalCost += cost;- this.writeFile(inputTokens, this.sessionOutputTokens, pricing.isEstimate);+ this.writeFile(inputTokens, this.sessionOutputTokens, pricing.isEstimate, pricing);}/**@@ -398,7 +430,8 @@ export class TokenTracker {inputTokens: number,outputTokens: number,actualCost: number | undefined,- detail?: UsageCacheDetail+ detail?: UsageCacheDetail,+ billing?: RequestBilling): void {this.sessionInputTokens = inputTokens;this.lastInputTokens = inputTokens;@@ -415,14 +448,14 @@ export class TokenTracker {} else {// The computed fallback is the `update` arithmetic, so it takes the// `update` treatment: full context charged, discount clamped against it.- const pricing = this.getPricing();+ const pricing = this.getPricing(billing);const inputCost = (inputTokens / 1_000_000) * pricing.inputCostPer1M;const outputCost = (outputTokens / 1_000_000) * pricing.outputCostPer1M;this.sessionTotalCost +=inputCost + outputCost - this.cacheReadDiscount(pricing, inputTokens, detail);}- this.writeFile(inputTokens, this.sessionOutputTokens);+ this.writeFile(inputTokens, this.sessionOutputTokens, undefined, this.getPricing(billing));}/**@@ -477,8 +510,8 @@ export class TokenTracker {return this.sessionOutputTokens;}- private getPricing(): ModelPricing {- return getModelPricing(this.config.providerName, this.config.modelName);+ private getPricing(billing?: RequestBilling): ModelPricing {+ return getModelPricing(this.config.providerName, this.config.modelName, billing);}/** Instance shim over `computeCacheReadDiscount` — see that function. */@@ -499,7 +532,12 @@ export class TokenTracker {return name.charAt(0).toUpperCase() + name.slice(1);}- private writeFile(inputTokens: number, outputTokens: number, isEstimate?: boolean): void {+ private writeFile(+ inputTokens: number,+ outputTokens: number,+ isEstimate?: boolean,+ requestPricing?: ModelPricing+ ): void {// The choke point of every write: each update path ends here.if (this.config.writesTokenFile === false) return;try {@@ -519,7 +557,9 @@ export class TokenTracker {const leftPct =cw > 0 ? Math.max(0, Math.min(100, Math.round(((cw - inputTokens) / cw) * 100))) : -1;- const pricing = this.getPricing();+ // The pricing of the update that is writing, when it has one, so the+ // published rates match the request just charged.+ const pricing = requestPricing ?? this.getPricing();const isFreeModel =pricing.isFree || (pricing.inputCostPer1M === 0 && pricing.outputCostPer1M === 0);