Skip to main content

lean_ctx/proxy/
usage.rs

1//! Real provider-reported token usage extraction.
2//!
3//! The proxy already rewrites requests; this module reads the *response* so the
4//! dashboard/terminal can show **measured** cost (the user's real provider bill)
5//! instead of an estimate. All three providers report the exact model and the
6//! billed token breakdown — including prompt-cache reads/writes — in the final
7//! event of a stream (or the body of a non-streaming response):
8//!
9//! - Anthropic: `message_start` carries model + input/cache tokens, the final
10//!   `message_delta` carries `output_tokens`. Non-streaming: one `usage` object.
11//! - OpenAI Responses: the `response.completed` event nests `response.usage`.
12//! - OpenAI Chat Completions: the final chunk carries `usage` (needs
13//!   `stream_options.include_usage`, which the proxy injects).
14//! - Gemini: every chunk carries `usageMetadata`; the last one has the totals.
15//!
16//! [`RealUsage`] normalizes every provider onto the four billable buckets that
17//! `crate::core::gain::model_pricing::ModelCost::estimate_usd` prices:
18//! uncached input, output (incl. reasoning/thoughts), cache-read, cache-write.
19
20use futures::{Stream, StreamExt};
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23
24/// Where provider usage was observed, not an assertion of answer quality or
25/// successful generation. Terminal usage also accompanies failed responses.
26#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
27#[serde(rename_all = "snake_case")]
28pub enum UsageBoundary {
29    BodyEnd,
30    ProviderTerminalUsage,
31    StreamEnd,
32    StreamError,
33}
34
35/// Payload-free local measurement. Unknown cost stays unknown; neither HTTP
36/// status nor receipt of usage supplies the private runtime's quality label.
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
38#[serde(deny_unknown_fields)]
39pub struct ResponseObservation {
40    pub schema_version: u8,
41    pub http_status: u16,
42    /// Monotonic elapsed time from upstream dispatch (including retries) to
43    /// the indicated usage boundary, not necessarily full response latency.
44    pub usage_observed_ms: u64,
45    pub boundary: UsageBoundary,
46    pub provider_cost_usd: Option<f64>,
47}
48
49/// LLM provider whose response shape a [`Scanner`] understands.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum Provider {
52    Anthropic,
53    /// Covers both Chat Completions and the Responses API (same `usage` dialects
54    /// are detected by field name).
55    OpenAi,
56    Gemini,
57}
58
59impl Provider {
60    /// Maps the proxy's `provider_label` (`"Anthropic"`, `"OpenAI"`/`"ChatGPT"`, else Gemini).
61    pub fn from_label(label: &str) -> Self {
62        match label {
63            "Anthropic" | "Bedrock" => Self::Anthropic,
64            "OpenAI" | "ChatGPT" | "Azure" => Self::OpenAi,
65            _ => Self::Gemini,
66        }
67    }
68}
69
70/// One LLM turn's real, provider-reported usage, normalized to billable buckets.
71///
72/// `output_tokens` already includes reasoning/thinking tokens (they are billed at
73/// the output rate); `reasoning_tokens` is retained only for display.
74#[derive(Debug, Clone, Default, PartialEq)]
75pub struct RealUsage {
76    pub model: String,
77    /// Input tokens billed at the input rate (cache reads/writes excluded).
78    pub input_tokens: u64,
79    /// Output tokens billed at the output rate (includes reasoning/thoughts).
80    pub output_tokens: u64,
81    /// Input tokens served from the prompt cache (billed at the cache-read rate).
82    pub cache_read_tokens: u64,
83    /// Input tokens written to the prompt cache (Anthropic + OpenRouter models
84    /// with explicit cache-write pricing; 0 elsewhere).
85    pub cache_write_tokens: u64,
86    /// Reasoning/thinking subset of `output_tokens` (display only).
87    pub reasoning_tokens: u64,
88    /// USD the provider *actually charged* for this turn, when the response
89    /// reports it. OpenRouter: `usage.cost` in credits (≡ USD); for BYOK
90    /// requests the separate `cost_details.upstream_inference_cost` is added
91    /// when it differs from `cost` (#746 — non-BYOK mirrors cost there).
92    /// The measured figure beats any price-table estimate wherever both exist.
93    /// `None` for providers that report tokens only (Anthropic/OpenAI/Gemini).
94    pub provider_cost_usd: Option<f64>,
95    /// Holdout arms for this turn: output shaping (#895 Track B) and input
96    /// compression (#1905), each `None` when that holdout is off. Stamped from
97    /// the request, not parsed from the response.
98    pub cohort: super::holdout::Cohorts,
99    /// Request-side gateway context (enterprise#11/#17/#18): identity tags,
100    /// compression savings and baseline inputs, stamped from the request before
101    /// it left for the upstream. `None` outside the forward path (e.g. tests
102    /// that only parse response bodies).
103    pub wire: Option<Box<WireContext>>,
104    /// Present only for measured upstream responses, never cache hits or
105    /// synthetic parser inputs. Kept local in the existing usage meter.
106    pub response_observation: Option<ResponseObservation>,
107}
108
109/// Request-side context the forward path knows and the response scanner does
110/// not: who sent the request (gateway identity, enterprise#11), what the proxy
111/// saved on the wire, and the counterfactual-baseline inputs (enterprise#18).
112/// Travels inside [`RealUsage`] so `usage_meter::record` stays the single
113/// choke-point through which every measured turn flows.
114#[derive(Debug, Clone, Default, PartialEq)]
115pub struct WireContext {
116    /// Provider label (`Anthropic|OpenAI|ChatGPT|Gemini`) of the serving route.
117    pub provider: String,
118    /// Person tag from the gateway key (enterprise#11).
119    pub person: Option<String>,
120    /// Team tag from the gateway key.
121    pub team: Option<String>,
122    /// Project: `x-leanctx-project` header wins over the key's default project.
123    pub project: Option<String>,
124    /// Estimated tokens this request saved through wire compression
125    /// (bytes/4 heuristic, same basis as the proxy stats).
126    pub saved_tokens: u64,
127    /// Estimated request tokens BEFORE lean-ctx compression (bytes/4) — the
128    /// SEE-attribution input of the avoided-cost baseline (enterprise#18).
129    pub uncompressed_input_tokens: u64,
130    /// True when the serving upstream is a local/loopback endpoint — billed via
131    /// the transparent `local_shadow_rate`, never 0 (enterprise#15/#18).
132    pub is_local: bool,
133    /// Originally requested model when the router downgraded/aliased it
134    /// (enterprise#13); `None` for passthrough.
135    pub routed_from: Option<String>,
136    /// Provider-counted input tokens of the ORIGINAL (uncompressed) request,
137    /// from the free `count_tokens` probe (#701). `None` when metering is off
138    /// or no probe was spawned; an empty slot at read time (probe failed or
139    /// still in flight) degrades the row to the local estimate.
140    pub counterfactual: Option<super::counterfactual::CounterfactualSlot>,
141    /// Complete, validated OCLA lineage for managed HTTP requests. `None` keeps
142    /// legacy, malformed and non-HTTP traffic explicitly unmanaged.
143    pub lineage: Option<crate::core::ocla::OclaRequestContext>,
144}
145
146impl WireContext {
147    #[must_use]
148    pub fn ocla_request_context(&self) -> Option<&crate::core::ocla::OclaRequestContext> {
149        self.lineage.as_ref()
150    }
151}
152
153impl RealUsage {
154    /// Projects measured proxy usage into the payload-free canonical OCLA record.
155    /// Missing lineage is unmanaged; invalid data and arithmetic overflow fail
156    /// closed for OCLA without disturbing the existing usage pipeline.
157    pub fn to_ocla_usage_record(
158        &self,
159    ) -> crate::core::ocla::OclaResult<Option<crate::core::ocla::UsageRecord>> {
160        use crate::core::ocla::{OclaError, UsageRecord};
161
162        let Some(context) = self
163            .wire
164            .as_deref()
165            .and_then(WireContext::ocla_request_context)
166            .cloned()
167        else {
168            return Ok(None);
169        };
170        context.validate()?;
171        if self.model.trim().is_empty() {
172            return Err(OclaError::InvalidRequest("model is required".into()));
173        }
174        let input_tokens = self
175            .input_tokens
176            .checked_add(self.cache_read_tokens)
177            .and_then(|value| value.checked_add(self.cache_write_tokens))
178            .ok_or_else(|| OclaError::InvalidRequest("input token total overflow".into()))?;
179        let provider_billed_tokens = input_tokens
180            .checked_add(self.output_tokens)
181            .ok_or_else(|| OclaError::InvalidRequest("billed token total overflow".into()))?;
182
183        Ok(Some(UsageRecord {
184            context,
185            model: self.model.clone(),
186            input_tokens,
187            output_tokens: self.output_tokens,
188            provider_billed_tokens,
189        }))
190    }
191
192    /// True once any model, token or measured-cost field has been observed —
193    /// the gate for recording. Avoids emitting empty rows for streams that
194    /// never reported usage.
195    fn is_meaningful(&self) -> bool {
196        !self.model.is_empty()
197            || self.input_tokens > 0
198            || self.output_tokens > 0
199            || self.cache_read_tokens > 0
200            || self.cache_write_tokens > 0
201            || self.provider_cost_usd.is_some()
202    }
203}
204
205/// Upper bound on a single buffered line before we give up on it. Usage events
206/// are tiny; this only guards against a pathological newline-free stream.
207const MAX_LINE_BYTES: usize = 1 << 20; // 1 MiB
208
209/// Incrementally extracts [`RealUsage`] from a response stream (or a full body).
210///
211/// `feed` is called with raw response chunks and keeps only the trailing partial
212/// line buffered (O(1) memory beyond one line); `finalize` returns the merged
213/// usage once the stream ends.
214pub struct Scanner {
215    provider: Provider,
216    /// Model parsed from the request URL (Gemini puts it there, not in the body).
217    url_model: Option<String>,
218    /// Holdout arms (#895, #1905), stamped onto the usage at finalize.
219    cohort: super::holdout::Cohorts,
220    /// Request-side gateway context (enterprise#11/#18), stamped at finalize.
221    wire: Option<Box<WireContext>>,
222    /// Billed USD from a gateway response header (#1189), stamped at finalize
223    /// unless the body already reported the charge.
224    header_cost: Option<f64>,
225    buf: Vec<u8>,
226    usage: RealUsage,
227    terminal_usage_seen: bool,
228    anthropic_final_usage_seen: bool,
229    response_clock: Option<(std::time::Instant, u16)>,
230    stream_failed: bool,
231}
232
233impl Scanner {
234    pub fn new(provider: Provider, url_model: Option<String>) -> Self {
235        Self {
236            provider,
237            url_model,
238            cohort: super::holdout::Cohorts::default(),
239            wire: None,
240            header_cost: None,
241            buf: Vec::new(),
242            usage: RealUsage::default(),
243            terminal_usage_seen: false,
244            anthropic_final_usage_seen: false,
245            response_clock: None,
246            stream_failed: false,
247        }
248    }
249
250    /// Starts measurement at the caller's actual upstream dispatch boundary.
251    #[must_use]
252    pub(crate) fn with_response_clock(
253        mut self,
254        started: Option<std::time::Instant>,
255        status: u16,
256    ) -> Self {
257        self.response_clock = started.map(|started| (started, status));
258        self
259    }
260
261    pub(super) fn mark_stream_error(&mut self) {
262        self.stream_failed = true;
263    }
264
265    /// Tags the usage this scanner produces with its output and compression holdout arms.
266    #[must_use]
267    pub fn with_cohort(mut self, cohort: super::holdout::Cohorts) -> Self {
268        self.cohort = cohort;
269        self
270    }
271
272    /// Attaches the request-side gateway context (identity tags, wire savings,
273    /// baseline inputs — enterprise#11/#17/#18) stamped onto the usage record.
274    #[must_use]
275    pub fn with_wire_context(mut self, wire: Option<Box<WireContext>>) -> Self {
276        self.wire = wire;
277        self
278    }
279
280    /// Attaches a billed USD figure reported by the upstream via a response
281    /// header (LiteLLM `x-litellm-response-cost`, or the operator-configured
282    /// `[proxy] cost_response_header`, #1189). Applied at finalize only when
283    /// the body did not already carry a measured cost — a body figure
284    /// (OpenRouter `usage.cost`) is the bill itself and always wins.
285    #[must_use]
286    pub fn with_header_cost(mut self, cost: Option<f64>) -> Self {
287        self.header_cost = cost.filter(|c| c.is_finite() && *c >= 0.0);
288        self
289    }
290
291    /// Feeds a raw streaming chunk, scanning every complete line it completes.
292    pub fn feed(&mut self, chunk: &[u8]) {
293        self.buf.extend_from_slice(chunk);
294        while let Some(nl) = self.buf.iter().position(|&b| b == b'\n') {
295            let mut line: Vec<u8> = self.buf.drain(..=nl).collect();
296            line.pop(); // drop '\n'
297            if line.last() == Some(&b'\r') {
298                line.pop();
299            }
300            self.scan_line(&line);
301        }
302        if self.buf.len() > MAX_LINE_BYTES {
303            self.buf.clear();
304        }
305    }
306
307    /// Feeds a complete non-streaming JSON response body.
308    pub fn feed_body(&mut self, body: &[u8]) {
309        if let Ok(v) = serde_json::from_slice::<Value>(body) {
310            self.absorb(&v);
311        }
312    }
313
314    /// A provider terminal measurement is independent of later transport EOF.
315    pub(super) fn has_terminal_usage(&self) -> bool {
316        self.terminal_usage_seen && (self.usage.is_meaningful() || self.header_cost.is_some())
317    }
318
319    /// Retain only an observed terminal measurement on an interrupted stream.
320    pub(super) fn finalize_terminal(self) -> Option<RealUsage> {
321        if self.has_terminal_usage() {
322            self.finalize_at(UsageBoundary::ProviderTerminalUsage)
323        } else {
324            None
325        }
326    }
327
328    /// Consumes the scanner, flushing any trailing partial line (a final event
329    /// may arrive without a newline) and returning the merged usage if any.
330    pub fn finalize(self) -> Option<RealUsage> {
331        self.finalize_at(UsageBoundary::StreamEnd)
332    }
333
334    pub(crate) fn finalize_at(mut self, boundary: UsageBoundary) -> Option<RealUsage> {
335        if !self.buf.is_empty() {
336            let line = std::mem::take(&mut self.buf);
337            self.scan_line(&line);
338        }
339        // Gateway header cost (#1189): measured, but the body figure is the
340        // bill itself (OpenRouter usage.cost) and keeps priority when present.
341        if self.usage.provider_cost_usd.is_none() {
342            self.usage.provider_cost_usd = self.header_cost;
343        }
344        if self.usage.is_meaningful() {
345            self.usage.cohort = self.cohort;
346            self.usage.wire = self.wire;
347            self.usage.response_observation =
348                self.response_clock
349                    .map(|(started, status)| ResponseObservation {
350                        schema_version: 1,
351                        http_status: status,
352                        usage_observed_ms: u64::try_from(started.elapsed().as_millis())
353                            .unwrap_or(u64::MAX),
354                        boundary: if self.stream_failed {
355                            UsageBoundary::StreamError
356                        } else {
357                            boundary
358                        },
359                        provider_cost_usd: self.usage.provider_cost_usd,
360                    });
361            Some(self.usage)
362        } else {
363            None
364        }
365    }
366
367    fn scan_line(&mut self, line: &[u8]) {
368        let Ok(text) = std::str::from_utf8(line) else {
369            return;
370        };
371        let trimmed = text.trim();
372        if trimmed.is_empty() {
373            return;
374        }
375        // Cheap pre-filter: skip the bulk of the stream (content deltas) and only
376        // JSON-parse lines that can carry usage or the model name.
377        if !self.line_might_be_relevant(trimmed) {
378            return;
379        }
380        let json_str = if let Some(rest) = trimmed.strip_prefix("data:") {
381            // SSE (Anthropic, OpenAI, Gemini with alt=sse).
382            let r = rest.trim();
383            if r.is_empty() || r == "[DONE]" {
384                return;
385            }
386            r
387        } else if trimmed.starts_with('{') {
388            // NDJSON / array-element line (Gemini x-ndjson). Tolerate the array
389            // punctuation a streamed JSON array puts around an element.
390            trimmed
391                .trim_start_matches([',', '['])
392                .trim_end_matches([',', ']'])
393                .trim()
394        } else {
395            return;
396        };
397        if let Ok(v) = serde_json::from_str::<Value>(json_str) {
398            self.absorb(&v);
399        }
400    }
401
402    fn line_might_be_relevant(&self, s: &str) -> bool {
403        match self.provider {
404            // Anthropic `message_start`/`message_delta` and OpenAI `usage`/
405            // `response.*` events all contain the substring "usage".
406            Provider::Anthropic => s.contains("usage") || s.contains("message_stop"),
407            Provider::OpenAi => s.contains("usage"),
408            Provider::Gemini => s.contains("usageMetadata"),
409        }
410    }
411
412    fn absorb(&mut self, v: &Value) {
413        match self.provider {
414            Provider::Anthropic => absorb_anthropic(&mut self.usage, v),
415            Provider::OpenAi => absorb_openai(&mut self.usage, v),
416            Provider::Gemini => absorb_gemini(&mut self.usage, v, self.url_model.as_deref()),
417        }
418        match self.provider {
419            Provider::Anthropic => {
420                if v.get("type").and_then(Value::as_str) == Some("message_delta")
421                    && v.pointer("/usage/output_tokens")
422                        .and_then(Value::as_u64)
423                        .is_some()
424                {
425                    self.anthropic_final_usage_seen = true;
426                }
427                self.terminal_usage_seen |= self.anthropic_final_usage_seen
428                    && v.get("type").and_then(Value::as_str) == Some("message_stop");
429            }
430            Provider::OpenAi => {
431                let response_terminal = matches!(
432                    v.get("type").and_then(Value::as_str),
433                    Some("response.completed" | "response.incomplete" | "response.failed")
434                ) && has_reported_totals(
435                    v.pointer("/response/usage"),
436                    "input_tokens",
437                    "output_tokens",
438                );
439                let chat_terminal =
440                    has_reported_totals(v.get("usage"), "prompt_tokens", "completion_tokens")
441                        && v.get("choices")
442                            .and_then(Value::as_array)
443                            .is_some_and(Vec::is_empty);
444                self.terminal_usage_seen |= response_terminal || chat_terminal;
445            }
446            // finishReason is per candidate, not proof that the entire request
447            // has finished. Preserve EOF accounting without inventing a terminal.
448            Provider::Gemini => {}
449        }
450    }
451}
452
453fn has_reported_totals(usage: Option<&Value>, input: &str, output: &str) -> bool {
454    usage.is_some_and(|usage| {
455        (usage.get(input).and_then(Value::as_u64).is_some()
456            && usage.get(output).and_then(Value::as_u64).is_some())
457            || usage
458                .get("cost")
459                .and_then(Value::as_f64)
460                .is_some_and(|cost| cost.is_finite() && cost >= 0.0)
461    })
462}
463
464/// Anthropic: model + input/cache live on `message` (streaming `message_start`
465/// or a non-streaming body); `output_tokens` arrives later on the event-level
466/// `usage` of `message_delta`. Latest non-zero wins, so the cumulative final
467/// delta is authoritative.
468fn absorb_anthropic(u: &mut RealUsage, v: &Value) {
469    let msg = v.get("message").unwrap_or(v);
470    if let Some(model) = msg.get("model").and_then(Value::as_str)
471        && !model.is_empty()
472    {
473        u.model = model.to_string();
474    }
475    let Some(usage) = msg.get("usage").or_else(|| v.get("usage")) else {
476        return;
477    };
478    if let Some(n) = usage.get("input_tokens").and_then(Value::as_u64) {
479        u.input_tokens = n;
480    }
481    if let Some(n) = usage.get("cache_read_input_tokens").and_then(Value::as_u64) {
482        u.cache_read_tokens = n;
483    }
484    if let Some(n) = usage
485        .get("cache_creation_input_tokens")
486        .and_then(Value::as_u64)
487    {
488        u.cache_write_tokens = n;
489    }
490    if let Some(n) = usage.get("output_tokens").and_then(Value::as_u64)
491        && n > 0
492    {
493        u.output_tokens = n;
494    }
495}
496
497/// OpenAI Chat Completions + Responses. `response.completed` nests the payload
498/// under `response`; chat chunks and non-streaming bodies are top-level. Both
499/// `usage` dialects are accepted (Responses: `input_tokens`/`output_tokens`;
500/// Chat: `prompt_tokens`/`completion_tokens`). `cached_tokens` is the cache-read
501/// portion of the reported input; OpenAI bills no separate cache write, but
502/// OpenRouter reports one (`prompt_tokens_details.cache_write_tokens`) for
503/// models with explicit cache-write pricing.
504///
505/// OpenRouter usage accounting additionally carries the money actually charged:
506/// `usage.cost` (credits ≡ USD) and, for BYOK requests, the upstream provider's
507/// own bill under `cost_details.upstream_inference_cost`. Their sum is this
508/// turn's real price — measured, not table-derived.
509fn absorb_openai(u: &mut RealUsage, v: &Value) {
510    let root = v.get("response").unwrap_or(v);
511    if let Some(model) = root.get("model").and_then(Value::as_str)
512        && !model.is_empty()
513    {
514        u.model = model.to_string();
515    }
516    let Some(usage) = root.get("usage") else {
517        return;
518    };
519    if usage.is_null() {
520        // `response.created` / `response.in_progress` carry `usage: null`.
521        return;
522    }
523
524    // Measured cost (OpenRouter dialect). Parsed before the token guard so a
525    // cost-bearing usage object is never lost, and `0` is preserved — a
526    // `:free` model's real price IS zero, not "unknown".
527    if let Some(cost) = usage.get("cost").and_then(Value::as_f64) {
528        let upstream = usage
529            .get("cost_details")
530            .and_then(|d| d.get("upstream_inference_cost"))
531            .and_then(Value::as_f64)
532            .unwrap_or(0.0);
533        // #746: non-BYOK responses may mirror `cost` in upstream_inference_cost;
534        // summing both would double-count. BYOK responses split the total:
535        // `cost` = OpenRouter fee (small), `upstream` = provider bill (large,
536        // always different from cost). Only add when genuinely distinct.
537        let byok_upstream = if upstream > 0.0 && upstream != cost {
538            upstream
539        } else {
540            0.0
541        };
542        u.provider_cost_usd = Some(cost + byok_upstream);
543    }
544
545    let total_input = usage
546        .get("input_tokens")
547        .or_else(|| usage.get("prompt_tokens"))
548        .and_then(Value::as_u64)
549        .unwrap_or(0);
550    let total_output = usage
551        .get("output_tokens")
552        .or_else(|| usage.get("completion_tokens"))
553        .and_then(Value::as_u64)
554        .unwrap_or(0);
555    let input_details = usage
556        .get("input_tokens_details")
557        .or_else(|| usage.get("prompt_tokens_details"));
558    let cached = input_details
559        .and_then(|d| d.get("cached_tokens"))
560        .and_then(Value::as_u64)
561        .unwrap_or(0);
562    let cache_write = input_details
563        .and_then(|d| d.get("cache_write_tokens"))
564        .and_then(Value::as_u64)
565        .unwrap_or(0);
566    let reasoning = usage
567        .get("output_tokens_details")
568        .or_else(|| usage.get("completion_tokens_details"))
569        .and_then(|d| d.get("reasoning_tokens"))
570        .and_then(Value::as_u64)
571        .unwrap_or(0);
572
573    if total_input == 0 && total_output == 0 {
574        return;
575    }
576    // OpenRouter counts cache writes inside prompt_tokens (unlike Anthropic's
577    // separate bucket) — subtract both cached reads and writes so the three
578    // buckets stay disjoint and are never double-priced.
579    u.input_tokens = total_input
580        .saturating_sub(cached)
581        .saturating_sub(cache_write);
582    u.cache_read_tokens = cached;
583    u.cache_write_tokens = cache_write;
584    u.output_tokens = total_output;
585    u.reasoning_tokens = reasoning;
586}
587
588/// Gemini: `usageMetadata` carries the counts; `modelVersion` (or the request
589/// URL) the model. `thoughtsTokenCount` is billed at the output rate and is not
590/// part of `candidatesTokenCount`, so it is added into `output_tokens`.
591fn absorb_gemini(u: &mut RealUsage, v: &Value, url_model: Option<&str>) {
592    if let Some(mv) = v.get("modelVersion").and_then(Value::as_str)
593        && !mv.is_empty()
594    {
595        u.model = mv.to_string();
596    } else if u.model.is_empty()
597        && let Some(m) = url_model
598        && !m.is_empty()
599    {
600        u.model = m.to_string();
601    }
602    let Some(um) = v.get("usageMetadata") else {
603        return;
604    };
605    let prompt = um
606        .get("promptTokenCount")
607        .and_then(Value::as_u64)
608        .unwrap_or(0);
609    let candidates = um
610        .get("candidatesTokenCount")
611        .and_then(Value::as_u64)
612        .unwrap_or(0);
613    let cached = um
614        .get("cachedContentTokenCount")
615        .and_then(Value::as_u64)
616        .unwrap_or(0);
617    let thoughts = um
618        .get("thoughtsTokenCount")
619        .and_then(Value::as_u64)
620        .unwrap_or(0);
621    if prompt == 0 && candidates == 0 && thoughts == 0 {
622        return;
623    }
624    u.input_tokens = prompt.saturating_sub(cached);
625    u.cache_read_tokens = cached;
626    u.cache_write_tokens = 0;
627    u.output_tokens = candidates + thoughts;
628    u.reasoning_tokens = thoughts;
629}
630
631/// Extracts the model from a Gemini request path
632/// (`/v1beta/models/{model}:generateContent`). Returns `None` for other paths.
633pub fn gemini_model_from_path(path: &str) -> Option<String> {
634    let after = path.rsplit_once("/models/").map(|(_, m)| m)?;
635    let model = after.split(':').next().unwrap_or(after).trim();
636    if model.is_empty() {
637        None
638    } else {
639        Some(model.to_string())
640    }
641}
642
643/// Wraps a response byte stream so every chunk is forwarded **byte-for-byte**
644/// while a [`Scanner`] observes it; on stream end the merged usage is recorded.
645/// Memory overhead is one buffered SSE line, never the whole response.
646pub fn tee_stream<S, B, E>(
647    inner: S,
648    scanner: Scanner,
649) -> impl Stream<Item = Result<B, E>> + Send + 'static
650where
651    S: Stream<Item = Result<B, E>> + Send + Unpin + 'static,
652    B: AsRef<[u8]> + Send + 'static,
653    E: Send + 'static,
654{
655    futures::stream::unfold(
656        (inner, Some(scanner)),
657        |(mut inner, mut scanner)| async move {
658            match inner.next().await {
659                Some(Ok(chunk)) => {
660                    if let Some(s) = scanner.as_mut() {
661                        s.feed(chunk.as_ref());
662                    }
663                    if scanner.as_ref().is_some_and(Scanner::has_terminal_usage)
664                        && let Some(usage) = scanner.take().and_then(Scanner::finalize_terminal)
665                    {
666                        super::usage_meter::record(&usage);
667                    }
668                    Some((Ok(chunk), (inner, scanner)))
669                }
670                Some(err) => {
671                    if let Some(mut s) = scanner.take() {
672                        s.mark_stream_error();
673                        if let Some(usage) = s.finalize_at(UsageBoundary::StreamError) {
674                            super::usage_meter::record(&usage);
675                        }
676                    }
677                    Some((err, (inner, scanner)))
678                }
679                None => {
680                    if let Some(s) = scanner.take()
681                        && let Some(usage) = s.finalize()
682                    {
683                        super::usage_meter::record(&usage);
684                    }
685                    None
686                }
687            }
688        },
689    )
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695
696    fn feed_lines(
697        provider: Provider,
698        url_model: Option<&str>,
699        lines: &[&str],
700    ) -> Option<RealUsage> {
701        let mut s = Scanner::new(provider, url_model.map(str::to_string));
702        for line in lines {
703            s.feed(line.as_bytes());
704            s.feed(b"\n");
705        }
706        s.finalize()
707    }
708
709    #[test]
710    fn anthropic_merges_message_start_and_delta() {
711        let u = feed_lines(
712            Provider::Anthropic,
713            None,
714            &[
715                r#"data: {"type":"message_start","message":{"model":"claude-opus-4-5-20251101","usage":{"input_tokens":100,"cache_read_input_tokens":2000,"cache_creation_input_tokens":50,"output_tokens":1}}}"#,
716                r#"data: {"type":"content_block_delta","index":0,"delta":{"text":"hello"}}"#,
717                r#"data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":73}}"#,
718                "data: {\"type\":\"message_stop\"}",
719            ],
720        )
721        .expect("usage");
722        assert_eq!(u.model, "claude-opus-4-5-20251101");
723        assert_eq!(u.input_tokens, 100);
724        assert_eq!(u.cache_read_tokens, 2000);
725        assert_eq!(u.cache_write_tokens, 50);
726        assert_eq!(u.output_tokens, 73);
727    }
728
729    #[test]
730    fn anthropic_non_streaming_body() {
731        let mut s = Scanner::new(Provider::Anthropic, None);
732        s.feed_body(
733            br#"{"model":"claude-sonnet-4-5","usage":{"input_tokens":24,"output_tokens":18,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}"#,
734        );
735        let u = s.finalize().expect("usage");
736        assert_eq!(u.model, "claude-sonnet-4-5");
737        assert_eq!(u.input_tokens, 24);
738        assert_eq!(u.output_tokens, 18);
739    }
740
741    #[test]
742    fn scanner_stamps_wire_context_onto_usage() {
743        // enterprise#11/#17: the request-side context must survive scanning and
744        // arrive on the finalized record that usage_meter/store consume.
745        let wire = Box::new(WireContext {
746            provider: "Anthropic".into(),
747            person: Some("yves".into()),
748            team: None,
749            project: Some("billing".into()),
750            saved_tokens: 42,
751            uncompressed_input_tokens: 500,
752            is_local: false,
753            routed_from: None,
754            counterfactual: None,
755            lineage: None,
756        });
757        let mut s = Scanner::new(Provider::Anthropic, None).with_wire_context(Some(wire.clone()));
758        s.feed_body(
759            br#"{"model":"claude-sonnet-4-5","usage":{"input_tokens":24,"output_tokens":18}}"#,
760        );
761        let u = s.finalize().expect("usage");
762        assert_eq!(u.wire, Some(wire));
763    }
764
765    fn managed_context() -> crate::core::ocla::OclaRequestContext {
766        crate::core::ocla::OclaRequestContext {
767            request_id: "req-1".into(),
768            session_id: "session-1".into(),
769            agent_id: "agent-1".into(),
770            content_ref: "blake3:abc".into(),
771            tenant_id: None,
772            trace_id: "tr-unit".into(),
773            task_id: None,
774            parent_task_id: None,
775        }
776    }
777
778    #[test]
779    fn ocla_projection_includes_cache_tokens_once() {
780        let usage = RealUsage {
781            model: "gpt-5".into(),
782            input_tokens: 100,
783            output_tokens: 40,
784            cache_read_tokens: 20,
785            cache_write_tokens: 5,
786            wire: Some(Box::new(WireContext {
787                lineage: Some(managed_context()),
788                ..Default::default()
789            })),
790            ..Default::default()
791        };
792        let record = usage
793            .to_ocla_usage_record()
794            .expect("valid projection")
795            .expect("managed record");
796        assert_eq!(record.input_tokens, 125);
797        assert_eq!(record.output_tokens, 40);
798        assert_eq!(record.provider_billed_tokens, 165);
799        assert_eq!(record.context, managed_context());
800    }
801
802    #[test]
803    fn ocla_projection_keeps_missing_lineage_unmanaged() {
804        let usage = RealUsage {
805            model: "gpt-5".into(),
806            input_tokens: 1,
807            ..Default::default()
808        };
809        assert_eq!(usage.to_ocla_usage_record().unwrap(), None);
810    }
811
812    #[test]
813    fn ocla_projection_fails_closed_on_overflow_or_invalid_context() {
814        let overflow = RealUsage {
815            model: "gpt-5".into(),
816            input_tokens: u64::MAX,
817            cache_read_tokens: 1,
818            wire: Some(Box::new(WireContext {
819                lineage: Some(managed_context()),
820                ..Default::default()
821            })),
822            ..Default::default()
823        };
824        assert!(overflow.to_ocla_usage_record().is_err());
825
826        let mut invalid = managed_context();
827        invalid.request_id.clear();
828        let invalid = RealUsage {
829            model: "gpt-5".into(),
830            wire: Some(Box::new(WireContext {
831                lineage: Some(invalid),
832                ..Default::default()
833            })),
834            ..Default::default()
835        };
836        assert!(invalid.to_ocla_usage_record().is_err());
837    }
838
839    #[test]
840    fn openai_responses_completed_event() {
841        let u = feed_lines(
842            Provider::OpenAi,
843            None,
844            &[
845                r#"data: {"type":"response.created","response":{"model":"gpt-5.4","usage":null}}"#,
846                r#"data: {"type":"response.completed","response":{"model":"gpt-5.4","usage":{"input_tokens":1289,"input_tokens_details":{"cached_tokens":289},"output_tokens":685,"output_tokens_details":{"reasoning_tokens":640},"total_tokens":1974}}}"#,
847            ],
848        )
849        .expect("usage");
850        assert_eq!(u.model, "gpt-5.4");
851        assert_eq!(u.input_tokens, 1000); // 1289 - 289 cached
852        assert_eq!(u.cache_read_tokens, 289);
853        assert_eq!(u.output_tokens, 685);
854        assert_eq!(u.reasoning_tokens, 640);
855    }
856
857    #[test]
858    fn openai_chat_final_usage_chunk() {
859        let u = feed_lines(
860            Provider::OpenAi,
861            None,
862            &[
863                r#"data: {"choices":[{"delta":{"content":"hi"}}],"model":"gpt-5.4-mini"}"#,
864                r#"data: {"choices":[],"model":"gpt-5.4-mini","usage":{"prompt_tokens":500,"prompt_tokens_details":{"cached_tokens":100},"completion_tokens":40,"total_tokens":540}}"#,
865                "data: [DONE]",
866            ],
867        )
868        .expect("usage");
869        assert_eq!(u.model, "gpt-5.4-mini");
870        assert_eq!(u.input_tokens, 400);
871        assert_eq!(u.cache_read_tokens, 100);
872        assert_eq!(u.output_tokens, 40);
873        assert_eq!(u.provider_cost_usd, None, "OpenAI reports no usage.cost");
874    }
875
876    #[test]
877    fn openrouter_cost_and_cache_writes_are_measured() {
878        // #1179: OpenRouter usage accounting — the final streamed chunk carries
879        // the billed USD (`cost`) and the cache-write bucket inside
880        // prompt_tokens_details. All three token buckets must stay disjoint.
881        let u = feed_lines(
882            Provider::OpenAi,
883            None,
884            &[
885                r#"data: {"choices":[{"delta":{"content":"hi"}}],"model":"deepseek/deepseek-v4-flash-20260423"}"#,
886                r#"data: {"choices":[],"model":"deepseek/deepseek-v4-flash-20260423","usage":{"prompt_tokens":700,"prompt_tokens_details":{"cached_tokens":150,"cache_write_tokens":50},"completion_tokens":40,"cost":0.0123,"cost_details":{"upstream_inference_cost":null},"total_tokens":740}}"#,
887                "data: [DONE]",
888            ],
889        )
890        .expect("usage");
891        assert_eq!(u.input_tokens, 500, "700 - 150 cached - 50 cache-write");
892        assert_eq!(u.cache_read_tokens, 150);
893        assert_eq!(u.cache_write_tokens, 50);
894        assert_eq!(u.output_tokens, 40);
895        let cost = u.provider_cost_usd.expect("measured cost");
896        assert!((cost - 0.0123).abs() < 1e-12);
897    }
898
899    #[test]
900    fn openrouter_byok_adds_upstream_inference_cost() {
901        let mut s = Scanner::new(Provider::OpenAi, None);
902        s.feed_body(
903            br#"{"model":"anthropic/claude-sonnet-5","usage":{"prompt_tokens":100,"completion_tokens":10,"cost":0.05,"cost_details":{"upstream_inference_cost":0.95}}}"#,
904        );
905        let u = s.finalize().expect("usage");
906        let cost = u.provider_cost_usd.expect("measured cost");
907        assert!(
908            (cost - 1.0).abs() < 1e-12,
909            "OpenRouter fee + BYOK upstream bill"
910        );
911    }
912
913    /// #746: non-BYOK responses mirror `cost` in `upstream_inference_cost`.
914    /// The gateway must not sum both — that would double-count.
915    #[test]
916    fn non_byok_upstream_equal_to_cost_is_not_doubled() {
917        let mut s = Scanner::new(Provider::OpenAi, None);
918        s.feed_body(
919            br#"{"model":"deepseek/deepseek-v4-flash","usage":{"prompt_tokens":50,"completion_tokens":5,"cost":0.000001568,"cost_details":{"upstream_inference_cost":0.000001568}}}"#,
920        );
921        let u = s.finalize().expect("usage");
922        let cost = u.provider_cost_usd.expect("measured cost");
923        assert!(
924            (cost - 0.000001568).abs() < 1e-15,
925            "#746: must book cost once, not 2x; got {cost}"
926        );
927    }
928
929    #[test]
930    fn gateway_header_cost_fills_when_body_has_none() {
931        // #1189: a LiteLLM-style gateway reports the bill in a header; tokens
932        // come from a normal OpenAI-shaped body without `usage.cost`.
933        let mut s = Scanner::new(Provider::OpenAi, None).with_header_cost(Some(0.0042));
934        s.feed_body(
935            br#"{"model":"azure-gpt-4o","usage":{"prompt_tokens":100,"completion_tokens":10}}"#,
936        );
937        let u = s.finalize().expect("usage");
938        assert_eq!(u.provider_cost_usd, Some(0.0042), "header is measured");
939    }
940
941    #[test]
942    fn body_reported_cost_beats_the_header_figure() {
943        // OpenRouter behind another gateway: `usage.cost` is the bill itself.
944        let mut s = Scanner::new(Provider::OpenAi, None).with_header_cost(Some(9.99));
945        s.feed_body(
946            br#"{"model":"deepseek/deepseek-v4-flash","usage":{"prompt_tokens":100,"completion_tokens":10,"cost":0.05}}"#,
947        );
948        let u = s.finalize().expect("usage");
949        assert_eq!(u.provider_cost_usd, Some(0.05), "body wins over header");
950    }
951
952    #[test]
953    fn openrouter_free_model_reports_zero_cost_as_measured() {
954        let mut s = Scanner::new(Provider::OpenAi, None);
955        s.feed_body(
956            br#"{"model":"poolside/laguna-xs-2.1:free","usage":{"prompt_tokens":80,"completion_tokens":20,"cost":0}}"#,
957        );
958        let u = s.finalize().expect("usage");
959        assert_eq!(u.provider_cost_usd, Some(0.0), "free is a price, not a gap");
960    }
961
962    #[test]
963    fn gemini_usage_metadata_with_url_model() {
964        let u = feed_lines(
965            Provider::Gemini,
966            Some("gemini-2.5-pro"),
967            &[
968                r#"data: {"candidates":[{"content":{"parts":[{"text":"hi"}]}}],"usageMetadata":{"promptTokenCount":25,"candidatesTokenCount":7,"thoughtsTokenCount":39,"totalTokenCount":71}}"#,
969            ],
970        )
971        .expect("usage");
972        assert_eq!(u.model, "gemini-2.5-pro");
973        assert_eq!(u.input_tokens, 25);
974        assert_eq!(u.output_tokens, 46); // candidates 7 + thoughts 39
975        assert_eq!(u.reasoning_tokens, 39);
976    }
977
978    #[test]
979    fn gemini_prefers_model_version_over_url() {
980        let u = feed_lines(
981            Provider::Gemini,
982            Some("gemini-2.5-pro"),
983            &[
984                r#"data: {"modelVersion":"gemini-2.5-pro-002","usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"cachedContentTokenCount":4,"totalTokenCount":15}}"#,
985            ],
986        )
987        .expect("usage");
988        assert_eq!(u.model, "gemini-2.5-pro-002");
989        assert_eq!(u.input_tokens, 6); // 10 - 4 cached
990        assert_eq!(u.cache_read_tokens, 4);
991        assert_eq!(u.output_tokens, 5);
992    }
993
994    #[test]
995    fn split_chunks_reassemble_across_feed_calls() {
996        let mut s = Scanner::new(Provider::Anthropic, None);
997        let line = r#"data: {"type":"message_delta","delta":{},"usage":{"output_tokens":42}}"#;
998        let bytes = format!("{line}\n");
999        let (a, b) = bytes.as_bytes().split_at(20);
1000        s.feed(a);
1001        s.feed(b);
1002        let u = s.finalize().expect("usage");
1003        assert_eq!(u.output_tokens, 42);
1004    }
1005
1006    #[test]
1007    fn no_usage_yields_none() {
1008        let out = feed_lines(
1009            Provider::OpenAi,
1010            None,
1011            &[r#"data: {"choices":[{"delta":{"content":"hi"}}],"model":"gpt-5.4"}"#],
1012        );
1013        assert!(out.is_none(), "content-only stream reports no usage");
1014    }
1015
1016    #[test]
1017    fn final_event_without_trailing_newline() {
1018        let mut s = Scanner::new(Provider::Anthropic, None);
1019        s.feed(br#"data: {"type":"message_delta","delta":{},"usage":{"output_tokens":7}}"#);
1020        let u = s.finalize().expect("flushes trailing partial line");
1021        assert_eq!(u.output_tokens, 7);
1022    }
1023
1024    #[test]
1025    fn gemini_model_from_path_extracts() {
1026        assert_eq!(
1027            gemini_model_from_path("/v1beta/models/gemini-2.5-pro:streamGenerateContent")
1028                .as_deref(),
1029            Some("gemini-2.5-pro")
1030        );
1031        assert_eq!(
1032            gemini_model_from_path("/v1beta/models/gemini-2.5-flash:generateContent").as_deref(),
1033            Some("gemini-2.5-flash")
1034        );
1035        assert_eq!(gemini_model_from_path("/v1/chat/completions"), None);
1036    }
1037
1038    #[test]
1039    fn terminal_usage_requires_provider_completion_and_reported_totals() {
1040        for kind in [
1041            "response.completed",
1042            "response.incomplete",
1043            "response.failed",
1044        ] {
1045            let mut scanner = Scanner::new(Provider::OpenAi, None);
1046            scanner.feed_body(serde_json::json!({
1047                "type": kind,
1048                "response": {"model": "terminal", "usage": {"input_tokens": 5, "output_tokens": 2}}
1049            }).to_string().as_bytes());
1050            assert!(scanner.has_terminal_usage());
1051        }
1052        for (provider, event) in [
1053            (
1054                Provider::OpenAi,
1055                serde_json::json!({"type":"response.in_progress","response":{"usage":{"input_tokens":5,"output_tokens":2}}}),
1056            ),
1057            (
1058                Provider::OpenAi,
1059                serde_json::json!({"type":"response.completed","response":{"usage":{"input_tokens":5}}}),
1060            ),
1061            (
1062                Provider::OpenAi,
1063                serde_json::json!({"choices":[],"usage":null}),
1064            ),
1065            (
1066                Provider::Gemini,
1067                serde_json::json!({"candidates":[{"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":2}}),
1068            ),
1069        ] {
1070            let mut scanner = Scanner::new(provider, None);
1071            scanner.feed_body(event.to_string().as_bytes());
1072            assert!(!scanner.has_terminal_usage());
1073        }
1074        let mut chat = Scanner::new(Provider::OpenAi, None);
1075        chat.feed_body(
1076            br#"{"model":"chat","choices":[],"usage":{"prompt_tokens":5,"completion_tokens":2}}"#,
1077        );
1078        assert!(chat.has_terminal_usage());
1079        let mut anthropic = Scanner::new(Provider::Anthropic, None);
1080        anthropic.feed(b"data: {\"type\":\"message_start\",\"message\":{\"model\":\"anthropic\",\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\n");
1081        anthropic.feed(b"data: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":2}}\n");
1082        assert!(!anthropic.has_terminal_usage());
1083        anthropic.feed(b"data: {\"type\":\"message_stop\"}\n");
1084        assert!(anthropic.has_terminal_usage());
1085    }
1086
1087    fn terminal_usage_frame(model: &str) -> Vec<u8> {
1088        format!(
1089            "data: {}\n\n",
1090            serde_json::json!({
1091                "type": "response.completed",
1092                "response": {
1093                    "model": model,
1094                    "usage": {
1095                        "input_tokens": 120,
1096                        "output_tokens": 7,
1097                        "input_tokens_details": {"cached_tokens": 20},
1098                        "cost": 0.0125
1099                    }
1100                }
1101            })
1102        )
1103        .into_bytes()
1104    }
1105
1106    fn measured_requests(model: &str) -> u64 {
1107        super::super::usage_meter::snapshot()
1108            .into_iter()
1109            .find(|usage| usage.model == model)
1110            .map_or(0, |usage| usage.requests)
1111    }
1112
1113    #[tokio::test]
1114    async fn terminal_usage_clean_eof_records_once() {
1115        let _isolation = crate::core::data_dir::isolated_data_dir();
1116        let model = "terminal-evidence-clean-eof";
1117        let before = measured_requests(model);
1118        let frame = terminal_usage_frame(model);
1119        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1120        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::OpenAi, None)));
1121        assert_eq!(teed.next().await, Some(Ok(frame)));
1122        assert_eq!(teed.next().await, None);
1123        drop(teed);
1124        assert_eq!(measured_requests(model), before + 1);
1125    }
1126
1127    #[tokio::test]
1128    async fn terminal_usage_received_before_drop_is_recorded_once() {
1129        let _isolation = crate::core::data_dir::isolated_data_dir();
1130        let model = "terminal-evidence-client-drop";
1131        let before = measured_requests(model);
1132        let frame = terminal_usage_frame(model);
1133        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1134        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::OpenAi, None)));
1135        assert_eq!(teed.next().await, Some(Ok(frame)));
1136        drop(teed);
1137        assert_eq!(measured_requests(model), before + 1);
1138    }
1139
1140    #[tokio::test]
1141    async fn terminal_usage_received_before_error_is_recorded_once() {
1142        let _isolation = crate::core::data_dir::isolated_data_dir();
1143        let model = "terminal-evidence-upstream-error";
1144        let before = measured_requests(model);
1145        let frame = terminal_usage_frame(model);
1146        let source = futures::stream::iter(vec![Ok(frame.clone()), Err(())]);
1147        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::OpenAi, None)));
1148        assert_eq!(teed.next().await, Some(Ok(frame)));
1149        assert_eq!(teed.next().await, Some(Err(())));
1150        drop(teed);
1151        assert_eq!(measured_requests(model), before + 1);
1152    }
1153
1154    #[tokio::test]
1155    async fn terminal_usage_retains_header_cost_without_model_or_body_tokens() {
1156        let _isolation = crate::core::data_dir::isolated_data_dir();
1157        let before = super::super::usage_meter::snapshot()
1158            .into_iter()
1159            .find(|usage| usage.model == "unknown");
1160        let before_requests = before.as_ref().map_or(0, |usage| usage.requests);
1161        let before_cost = before.as_ref().map_or(0.0, |usage| usage.cost_usd);
1162        let frame = b"data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":0,\"output_tokens\":0}}}\n".to_vec();
1163        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1164        let scanner = Scanner::new(Provider::OpenAi, None).with_header_cost(Some(0.0042));
1165        let mut teed = Box::pin(tee_stream(source, scanner));
1166        assert_eq!(teed.next().await, Some(Ok(frame)));
1167        drop(teed);
1168        let measured = super::super::usage_meter::snapshot()
1169            .into_iter()
1170            .find(|usage| usage.model == "unknown")
1171            .unwrap();
1172        assert_eq!(measured.requests, before_requests + 1);
1173        assert!((measured.cost_usd - before_cost - 0.0042).abs() < 1e-9);
1174    }
1175
1176    #[tokio::test]
1177    async fn terminal_usage_partial_input_does_not_become_completed_spend_on_drop() {
1178        let _isolation = crate::core::data_dir::isolated_data_dir();
1179        let model = "terminal-evidence-partial-input";
1180        let before = measured_requests(model);
1181        let frame = format!(
1182            "data: {}\n\n",
1183            serde_json::json!({
1184                "type": "message_start",
1185                "message": {
1186                    "model": model,
1187                    "usage": {"input_tokens": 5, "output_tokens": 1}
1188                }
1189            })
1190        )
1191        .into_bytes();
1192        let source = futures::stream::iter(vec![Ok::<_, ()>(frame.clone())]);
1193        let mut teed = Box::pin(tee_stream(source, Scanner::new(Provider::Anthropic, None)));
1194        assert_eq!(teed.next().await, Some(Ok(frame)));
1195        drop(teed);
1196        assert_eq!(measured_requests(model), before);
1197    }
1198
1199    #[tokio::test]
1200    async fn tee_stream_passes_bytes_through_and_records() {
1201        let chunks: Vec<Result<Vec<u8>, std::convert::Infallible>> = vec![
1202            Ok(b"data: {\"type\":\"message_start\",\"message\":{\"model\":\"claude-haiku-4.5\",\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\n".to_vec()),
1203            Ok(b"data: {\"type\":\"message_delta\",\"delta\":{},\"usage\":{\"output_tokens\":9}}\n".to_vec()),
1204        ];
1205        let inner = futures::stream::iter(chunks);
1206        let scanner = Scanner::new(Provider::Anthropic, None);
1207        let teed = tee_stream(inner, scanner);
1208        let collected: Vec<_> = teed.collect().await;
1209        // Byte-for-byte passthrough preserved.
1210        assert_eq!(collected.len(), 2);
1211        assert!(collected.iter().all(std::result::Result::is_ok));
1212    }
1213}