vibe_coding_tracker 1.1.0

Vibe Coding Tracker - AI coding assistant telemetry/usage parser, aggregate JSONL events into CodeAnalysis results
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use crate::display::common::ProviderTotal;
use crate::models::{PerProviderUsage, Provider, ProviderActiveDays, UsageResult};
use serde_json::Value;
use std::borrow::Cow;

/// Data structure for a usage row.
///
/// `output_tokens` is the user-visible response the model emitted;
/// `reasoning_tokens` is the separately-billed "thinking" budget (Gemini
/// `thoughts_tokens`, Codex `reasoning_output_tokens`, Copilot
/// `reasoningTokens`). Display layers typically present their sum in a
/// single "Output" column via `output_with_reasoning()` so the per-row
/// numbers reconcile with `total`, while `cost` is computed against the
/// per-token reasoning rate (when the model publishes one) via
/// `calculate_cost`.
#[derive(Default)]
pub struct UsageRow {
    /// Raw model name as reported by the session (the pricing-lookup key).
    pub model: String, // 原始模型名稱
    /// Name shown in the table; appends the fuzzy-matched pricing model in
    /// parentheses when the lookup was not exact.
    pub display_model: String, // 可能含 fuzzy match 提示的顯示名稱
    /// Prompt (input) tokens.
    pub input_tokens: i64,
    /// User-visible response tokens, excluding reasoning.
    pub output_tokens: i64,
    /// Separately-billed "thinking" tokens.
    pub reasoning_tokens: i64,
    /// Tokens served from the prompt cache.
    pub cache_read: i64,
    /// Tokens written to the prompt cache.
    pub cache_creation: i64,
    /// Sum of all token buckets for this model.
    pub total: i64,
    /// LiteLLM-priced cost in USD for this model's tokens.
    pub cost: f64,
}

impl UsageRow {
    /// Sum of output and reasoning tokens — the "total model-emitted
    /// tokens" figure most display tables want to show in an Output
    /// column so the row adds up to `total`.
    #[inline]
    pub fn output_with_reasoning(&self) -> i64 {
        self.output_tokens + self.reasoning_tokens
    }
}

/// Column-wise totals across every [`UsageRow`] in a summary.
#[derive(Default)]
pub struct UsageTotals {
    /// Summed prompt (input) tokens.
    pub input_tokens: i64,
    /// Summed response tokens, excluding reasoning.
    pub output_tokens: i64,
    /// Summed reasoning ("thinking") tokens.
    pub reasoning_tokens: i64,
    /// Summed cache-read tokens.
    pub cache_read: i64,
    /// Summed cache-creation tokens.
    pub cache_creation: i64,
    /// Summed total tokens.
    pub total: i64,
    /// Summed cost in USD.
    pub cost: f64,
}

impl UsageTotals {
    /// Adds every token bucket and the cost of `row` into these totals.
    pub fn accumulate(&mut self, row: &UsageRow) {
        self.input_tokens += row.input_tokens;
        self.output_tokens += row.output_tokens;
        self.reasoning_tokens += row.reasoning_tokens;
        self.cache_read += row.cache_read;
        self.cache_creation += row.cache_creation;
        self.total += row.total;
        self.cost += row.cost;
    }

    /// Same helper as [`UsageRow::output_with_reasoning`] for totals.
    #[inline]
    pub fn output_with_reasoning(&self) -> i64 {
        self.output_tokens + self.reasoning_tokens
    }
}

/// Per-provider totals for usage. `days_count` records how many distinct
/// days contributed to these totals so the display layer can show readers
/// the spread without computing a rate.
#[derive(Default, Clone)]
pub struct ProviderStats {
    /// Total tokens attributed to this provider.
    pub total_tokens: i64,
    /// Total cost in USD attributed to this provider.
    pub total_cost: f64,
    /// Number of distinct days that contributed to these totals.
    pub days_count: usize,
}

impl ProviderStats {
    /// Adds `row`'s total tokens and cost into these stats.
    fn accumulate_row(&mut self, row: &UsageRow) {
        self.total_tokens += row.total;
        self.total_cost += row.cost;
    }
}

/// Type alias for usage totals grouped by provider.
pub type UsageProviderTotals = crate::display::common::ProviderTotals<ProviderStats>;

/// Fully priced usage view shared by every output mode.
#[derive(Default)]
pub struct UsageSummary {
    /// Per-model rows, sorted by ascending cost (model name as tie-break).
    pub rows: Vec<UsageRow>,
    /// Column-wise totals across all rows.
    pub totals: UsageTotals,
    /// Per-provider totals for the summary footer.
    pub provider_totals: UsageProviderTotals,
}

/// Calculate per-provider totals using **source-directory** attribution.
///
/// Token aggregation is fed directly from the `per_provider` map that
/// `usage::calculator` populates from each session's source directory, so the
/// provider assignment is exact regardless of what model name the session
/// happens to carry. The previous "averages" variant divided by
/// `provider_days` to render a per-day rate; the structure is otherwise
/// identical.
pub fn calculate_provider_totals_from_per_provider(
    per_provider: &PerProviderUsage,
    provider_days: &ProviderActiveDays,
    pricing_map: &crate::pricing::ModelPricingMap,
    opencode_costs: &crate::constants::FastHashMap<String, f64>,
) -> UsageProviderTotals {
    let mut totals = UsageProviderTotals::default();

    totals.claude.days_count = provider_days.claude;
    totals.codex.days_count = provider_days.codex;
    totals.copilot.days_count = provider_days.copilot;
    totals.gemini.days_count = provider_days.gemini;
    totals.opencode.days_count = provider_days.opencode;
    totals.overall.days_count = provider_days.total;

    accumulate_provider(&mut totals.claude, &per_provider.claude, pricing_map, None);
    accumulate_provider(&mut totals.codex, &per_provider.codex, pricing_map, None);
    accumulate_provider(
        &mut totals.copilot,
        &per_provider.copilot,
        pricing_map,
        None,
    );
    accumulate_provider(&mut totals.gemini, &per_provider.gemini, pricing_map, None);
    accumulate_provider(
        &mut totals.opencode,
        &per_provider.opencode,
        pricing_map,
        Some(opencode_costs),
    );

    // "All Providers" row sums every provider's totals directly rather
    // than reusing the cross-provider merged `UsageData.models` map.
    // That merged map de-duplicates a shared model like `claude-sonnet-4-6`
    // (used by both Claude Code and Copilot CLI) into a single row, so
    // the underlying tokens are *not* double-counted — but we lose the
    // provider attribution needed to populate per-provider cost columns
    // on the same table, and the single merged row would price with one
    // model-lookup where summing per-provider already-priced stats keeps
    // cost consistent with each provider's own row above.
    totals.overall.total_tokens = totals.claude.total_tokens
        + totals.codex.total_tokens
        + totals.copilot.total_tokens
        + totals.gemini.total_tokens
        + totals.opencode.total_tokens;
    totals.overall.total_cost = totals.claude.total_cost
        + totals.codex.total_cost
        + totals.copilot.total_cost
        + totals.gemini.total_cost
        + totals.opencode.total_cost;

    totals
}

/// Prices every model in `usage` and folds the results into `stats`.
///
/// `opencode_costs` is `Some` only when accumulating the OpenCode provider, so
/// that its models price by exact match or fall back to OpenCode's stored cost.
fn accumulate_provider(
    stats: &mut ProviderStats,
    usage: &UsageResult,
    pricing_map: &crate::pricing::ModelPricingMap,
    opencode_costs: Option<&crate::constants::FastHashMap<String, f64>>,
) {
    for (model, raw_usage) in usage {
        let opencode_cost = opencode_costs.map(|m| m.get(model).copied().unwrap_or(0.0));
        let row = extract_usage_row(model, raw_usage, pricing_map, opencode_cost);
        stats.accumulate_row(&row);
    }
}

/// Build provider total rows for display.
pub fn build_provider_total_rows(
    totals: &UsageProviderTotals,
) -> Vec<ProviderTotal<'_, ProviderStats>> {
    let mut rows = Vec::with_capacity(6); // max 5 providers + overall

    if totals.claude.days_count > 0 {
        rows.push(ProviderTotal::new(
            Provider::ClaudeCode,
            &totals.claude,
            false,
        ));
    }

    if totals.codex.days_count > 0 {
        rows.push(ProviderTotal::new(Provider::Codex, &totals.codex, false));
    }

    if totals.copilot.days_count > 0 {
        rows.push(ProviderTotal::new(
            Provider::Copilot,
            &totals.copilot,
            false,
        ));
    }

    if totals.gemini.days_count > 0 {
        rows.push(ProviderTotal::new(Provider::Gemini, &totals.gemini, false));
    }

    if totals.opencode.days_count > 0 {
        rows.push(ProviderTotal::new(
            Provider::OpenCode,
            &totals.opencode,
            false,
        ));
    }

    if totals.overall.days_count > 0 || rows.is_empty() {
        rows.push(ProviderTotal::new_overall(&totals.overall));
    }

    rows
}

/// Build a summary from raw usage data.
///
/// `usage_data` is the cross-provider merged map (drives the per-model
/// table); `per_provider` is the source-directory-scoped map (drives the
/// per-provider footer). Keeping the two aggregations independent is what
/// lets Copilot-originated Claude tokens stay attributed to Copilot even
/// though they share a row with Claude Code tokens in the main table.
pub fn build_usage_summary(
    usage_data: &UsageResult,
    per_provider: &PerProviderUsage,
    provider_days: &ProviderActiveDays,
    pricing_map: &crate::pricing::ModelPricingMap,
    opencode_costs: &crate::constants::FastHashMap<String, f64>,
) -> UsageSummary {
    if usage_data.is_empty() {
        return UsageSummary::default();
    }

    let mut summary = UsageSummary::default();

    // Pre-allocate rows vector
    summary.rows.reserve(usage_data.len());

    // Extract rows first so we can sort by cost
    for (model, usage) in usage_data.iter() {
        let (cost, matched_model) =
            resolve_merged_row_cost(model, per_provider, pricing_map, opencode_costs)
                .unwrap_or_else(|| price_usage(model, usage, pricing_map, None));
        let row = build_usage_row(model, usage, cost, matched_model);
        summary.rows.push(row);
    }

    // Sort by cost ascending (higher cost at the bottom); tie-break by model name for stability
    summary.rows.sort_by(|a, b| {
        a.cost
            .partial_cmp(&b.cost)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.model.cmp(&b.model))
    });

    for row in &summary.rows {
        summary.totals.accumulate(row);
    }

    summary.provider_totals = calculate_provider_totals_from_per_provider(
        per_provider,
        provider_days,
        pricing_map,
        opencode_costs,
    );
    summary
}

/// Builds one priced [`UsageRow`] from a model's raw usage `Value`.
///
/// Token counts come from [`extract_token_counts`](crate::utils::extract_token_counts);
/// cost is resolved by [`resolve_model_cost`](crate::usage::resolve_model_cost).
/// `opencode_cost` is `Some` only for OpenCode-sourced usage, in which case a
/// model with no exact LiteLLM price falls back to OpenCode's stored cost
/// instead of a fuzzy match. When a non-exact LiteLLM key was used, the matched
/// model name is appended to `display_model` in parentheses.
fn extract_usage_row(
    model: &str,
    usage: &Value,
    pricing_map: &crate::pricing::ModelPricingMap,
    opencode_cost: Option<f64>,
) -> UsageRow {
    let (cost, matched_model) = price_usage(model, usage, pricing_map, opencode_cost);
    build_usage_row(model, usage, cost, matched_model)
}

/// Prices one raw usage value.
fn price_usage(
    model: &str,
    usage: &Value,
    pricing_map: &crate::pricing::ModelPricingMap,
    opencode_cost: Option<f64>,
) -> (f64, Option<String>) {
    use crate::usage::resolve_model_cost;
    use crate::utils::extract_token_counts;

    let counts = extract_token_counts(usage);
    resolve_model_cost(model, &counts, pricing_map, opencode_cost)
}

/// Prices a merged per-model row from provider-scoped usage pieces.
fn resolve_merged_row_cost(
    model: &str,
    per_provider: &PerProviderUsage,
    pricing_map: &crate::pricing::ModelPricingMap,
    opencode_costs: &crate::constants::FastHashMap<String, f64>,
) -> Option<(f64, Option<String>)> {
    let mut total_cost = 0.0;
    let mut matched_model = None;
    let mut found = false;

    for usage in [
        &per_provider.claude,
        &per_provider.codex,
        &per_provider.copilot,
        &per_provider.gemini,
    ] {
        if let Some(raw_usage) = usage.get(model) {
            found = true;
            let (cost, matched) = price_usage(model, raw_usage, pricing_map, None);
            total_cost += cost;
            if matched_model.is_none() {
                matched_model = matched;
            }
        }
    }

    if let Some(raw_usage) = per_provider.opencode.get(model) {
        found = true;
        let opencode_cost = opencode_costs.get(model).copied().unwrap_or(0.0);
        let (cost, matched) = price_usage(model, raw_usage, pricing_map, Some(opencode_cost));
        total_cost += cost;
        if matched_model.is_none() {
            matched_model = matched;
        }
    }

    found.then_some((total_cost, matched_model))
}

/// Builds one display row using an already-resolved cost.
fn build_usage_row(
    model: &str,
    usage: &Value,
    cost: f64,
    matched_model: Option<String>,
) -> UsageRow {
    use crate::utils::extract_token_counts;

    let counts = extract_token_counts(usage);

    // Use Cow<str> for display_model to avoid allocation when no annotation
    let display_model = if let Some(matched) = &matched_model {
        Cow::Owned(format!("{} ({})", model, matched))
    } else {
        Cow::Borrowed(model)
    };

    UsageRow {
        model: model.to_string(),
        display_model: display_model.into_owned(),
        input_tokens: counts.input_tokens,
        output_tokens: counts.output_tokens,
        reasoning_tokens: counts.reasoning_tokens,
        cache_read: counts.cache_read,
        cache_creation: counts.cache_creation,
        total: counts.total,
        cost,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pricing::{ModelPricing, ModelPricingMap, clear_pricing_cache};
    use serde_json::json;

    #[test]
    fn merged_rows_price_opencode_fallback_only_for_opencode_tokens() {
        clear_pricing_cache();

        let mut raw_pricing = std::collections::HashMap::new();
        raw_pricing.insert(
            "shared".to_string(),
            ModelPricing {
                input_cost_per_token: 0.01,
                ..Default::default()
            },
        );
        let pricing_map = ModelPricingMap::new(raw_pricing);

        let mut usage_data = UsageResult::default();
        usage_data.insert("shared-pro".to_string(), json!({"input_tokens": 200}));

        let mut per_provider = PerProviderUsage::default();
        per_provider
            .claude
            .insert("shared-pro".to_string(), json!({"input_tokens": 100}));
        per_provider
            .opencode
            .insert("shared-pro".to_string(), json!({"input_tokens": 100}));

        let mut opencode_costs = crate::constants::FastHashMap::default();
        opencode_costs.insert("shared-pro".to_string(), 7.0);

        let summary = build_usage_summary(
            &usage_data,
            &per_provider,
            &ProviderActiveDays::default(),
            &pricing_map,
            &opencode_costs,
        );

        assert_eq!(summary.rows.len(), 1);
        assert!((summary.rows[0].cost - 8.0).abs() < 1e-9);
        assert_eq!(summary.rows[0].display_model, "shared-pro (shared)");
    }
}