fix: Guard against null usage tokens (#565)

Closes #564
This commit is contained in:
Ben Brandt
2026-04-17 17:53:22 +02:00
committed by GitHub
parent ca1fe79e6f
commit f7dc300a16
2 changed files with 63 additions and 8 deletions

View File

@@ -1768,17 +1768,20 @@ function totalTokens(usage: UsageSnapshot): number {
/** Project a nullable API usage object into our non-null snapshot shape.
* Both SDK message_start and assistant message `usage` have `number | null`
* cache fields; we coerce absent values to 0 so `totalTokens` never hits
* NaN. Delta events have different semantics (cumulative + prev fallback)
* and are handled inline. */
* NaN. `input_tokens`/`output_tokens` are typed `number` by the SDK but
* synthetic or third-party-backend stream events have been observed emitting
* them as null/undefined — coerce those too so a malformed upstream event
* can't leak NaN into the wire `used` field. Delta events have different
* semantics (cumulative + prev fallback) and are handled inline. */
function snapshotFromUsage(usage: {
input_tokens: number;
output_tokens: number;
cache_read_input_tokens: number | null;
cache_creation_input_tokens: number | null;
input_tokens?: number | null;
output_tokens?: number | null;
cache_read_input_tokens?: number | null;
cache_creation_input_tokens?: number | null;
}): UsageSnapshot {
return {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
input_tokens: usage.input_tokens ?? 0,
output_tokens: usage.output_tokens ?? 0,
cache_read_input_tokens: usage.cache_read_input_tokens ?? 0,
cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
};