terraphim_usage 1.20.3

Usage tracking and analytics for Terraphim AI
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
use crate::UsageRegistry;
use crate::formatter::{format_usage_json, format_usage_text};
use clap::{Parser, Subcommand};
use jiff::Zoned;
use std::collections::BTreeMap;

#[derive(Parser)]
#[command(name = "terraphim", about = "Terraphim AI CLI")]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    Usage {
        #[command(subcommand)]
        action: UsageAction,
    },
}

#[derive(Subcommand)]
pub enum UsageAction {
    Show {
        #[arg(short, long)]
        provider: Option<String>,
        #[arg(long, default_value = "text", visible_alias = "fmt")]
        output_format: String,
    },
    History {
        #[arg(long)]
        since: Option<String>,
        #[arg(long)]
        until: Option<String>,
        #[arg(long, help = "Shorthand period, e.g. '7d', '30d'")]
        last: Option<String>,
        #[arg(short, long)]
        provider: Option<String>,
        #[arg(short, long)]
        model: Option<String>,
        #[arg(long, help = "Group results by model")]
        by_model: bool,
        #[arg(long, default_value = "text", visible_alias = "fmt")]
        output_format: String,
    },
    Export {
        #[arg(long, default_value = "json", visible_alias = "fmt")]
        output_format: String,
        #[arg(short, long)]
        output: Option<String>,
    },
    Alert {
        #[arg(short, long)]
        provider: Option<String>,
        #[arg(short, long)]
        budget: Option<f64>,
        #[arg(short, long, default_value = "80")]
        threshold: u8,
    },
    Budgets {
        #[arg(long, default_value = "text", visible_alias = "fmt")]
        output_format: String,
    },
}

fn resolve_since(last: &Option<String>, since: &Option<String>) -> String {
    if let Some(s) = since {
        return s.clone();
    }
    let days = match last {
        Some(period) => parse_period(period).unwrap_or(7),
        None => 7,
    };
    days_ago_date(days)
}

fn days_ago_date(days: i64) -> String {
    jiff::Span::new()
        .try_days(-days)
        .ok()
        .and_then(|span| Zoned::now().checked_add(span).ok())
        .map(|dt| dt.strftime("%Y-%m-%d").to_string())
        .unwrap_or_else(|| "2020-01-01".to_string())
}

fn month_start_date() -> String {
    let now = Zoned::now();
    format!("{}-{:02}-01", now.year(), now.month())
}

fn today_date() -> String {
    Zoned::now().strftime("%Y-%m-%d").to_string()
}

fn now_timestamp() -> String {
    let ts = jiff::Timestamp::now();
    ts.strftime("%Y-%m-%d %H:%M UTC").to_string()
}

fn parse_period(period: &str) -> Option<i64> {
    let period = period.to_lowercase();
    if let Some(num) = period.strip_suffix('d') {
        let days: i64 = num.parse().ok()?;
        return if days > 0 && days <= 3650 {
            Some(days)
        } else {
            None
        };
    }
    if let Some(num) = period.strip_suffix('w') {
        let weeks: i64 = num.parse().ok()?;
        let days = weeks * 7;
        return if days > 0 && days <= 3650 {
            Some(days)
        } else {
            None
        };
    }
    if let Some(num) = period.strip_suffix('m') {
        let months: i64 = num.parse().ok()?;
        let days = months * 30;
        return if days > 0 && days <= 3650 {
            Some(days)
        } else {
            None
        };
    }
    let days: i64 = period.parse().ok()?;
    if days > 0 && days <= 3650 {
        Some(days)
    } else {
        None
    }
}

struct ModelAggregation {
    total_tokens: i64,
    total_cost: f64,
    count: usize,
}

pub async fn execute_usage_action(
    action: UsageAction,
    registry: &UsageRegistry,
) -> Result<String, Box<dyn std::error::Error>> {
    match action {
        UsageAction::Show {
            provider,
            output_format,
        } => execute_show(provider, output_format, registry).await,
        UsageAction::History {
            since,
            until,
            last,
            provider,
            model,
            by_model,
            output_format,
        } => execute_history(since, until, last, provider, model, by_model, output_format).await,
        UsageAction::Export {
            output_format,
            output: _,
        } => execute_export(output_format).await,
        UsageAction::Alert {
            provider,
            budget,
            threshold,
        } => execute_alert(provider, budget, threshold).await,
        UsageAction::Budgets { output_format } => execute_budgets(output_format).await,
    }
}

async fn execute_show(
    provider: Option<String>,
    format: String,
    registry: &UsageRegistry,
) -> Result<String, Box<dyn std::error::Error>> {
    let mut results = Vec::new();

    let provider_ids: Vec<&str> = if let Some(ref p) = provider {
        vec![p.as_str()]
    } else {
        registry.ids()
    };

    for id in provider_ids {
        if let Some(p) = registry.get(id) {
            match p.fetch_usage().await {
                Ok(usage) => results.push(usage),
                Err(e) => eprintln!("Warning: Failed to fetch {} usage: {}", id, e),
            }
        }
    }

    let mut output = String::new();

    match format.as_str() {
        "json" => {
            let json_results: Vec<_> = results
                .iter()
                .map(format_usage_json)
                .collect::<Result<_, _>>()?;
            output.push_str(&format!("[{}]", json_results.join(",\n")));
        }
        _ => {
            output.push_str(&format!("AI Usage Summary - {}\n\n", now_timestamp()));
            for usage in &results {
                output.push_str(&format_usage_text(usage));
                output.push('\n');
            }
        }
    }

    #[cfg(feature = "persistence")]
    {
        let spend = aggregate_spend().await?;
        if !spend.is_empty() {
            output.push_str("Spend from Execution Records:\n");
            for (period, cost, tokens) in &spend {
                output.push_str(&format!("  {}: ${:.2} ({} tokens)\n", period, cost, tokens));
            }
        }
    }

    Ok(output)
}

#[cfg(feature = "persistence")]
async fn aggregate_spend() -> Result<Vec<(String, f64, i64)>, Box<dyn std::error::Error>> {
    use crate::store::UsageStore;

    let store = UsageStore::new();
    let mut result = Vec::new();

    let today_str = today_date();
    let week_str = days_ago_date(7);
    let month_str = month_start_date();

    for (label, since) in [
        ("Today", today_str),
        ("This week", week_str),
        ("This month", month_str),
    ] {
        let execs = store.query_executions(&since, None, None).await?;
        let cost: f64 = execs.iter().map(|e| e.cost_usd()).sum();
        let tokens: i64 = execs.iter().map(|e| e.total_tokens).sum();
        if cost > 0.0 || tokens > 0 {
            result.push((label.to_string(), cost, tokens));
        }
    }

    Ok(result)
}

#[cfg(not(feature = "persistence"))]
async fn aggregate_spend() -> Result<Vec<(String, f64, i64)>, Box<dyn std::error::Error>> {
    Ok(Vec::new())
}

#[cfg(feature = "persistence")]
async fn execute_history(
    since: Option<String>,
    until: Option<String>,
    last: Option<String>,
    provider: Option<String>,
    model: Option<String>,
    by_model: bool,
    format: String,
) -> Result<String, Box<dyn std::error::Error>> {
    use crate::store::UsageStore;

    let since_str = resolve_since(&last, &since);
    let store = UsageStore::new();
    let mut executions = store
        .query_executions(&since_str, until.as_deref(), None)
        .await?;

    if let Some(ref model_filter) = model {
        let filter_lower = model_filter.to_lowercase();
        executions.retain(|e| {
            e.model
                .as_deref()
                .map(|m| m.to_lowercase().contains(&filter_lower))
                .unwrap_or(false)
        });
    }

    if let Some(ref provider_filter) = provider {
        let filter_lower = provider_filter.to_lowercase();
        executions.retain(|e| {
            e.provider
                .as_deref()
                .map(|p| p.to_lowercase().contains(&filter_lower))
                .unwrap_or(false)
        });
    }

    if executions.is_empty() {
        return Ok(format!("No execution history found from {}.", since_str));
    }

    if by_model {
        return format_by_model(&executions, &since_str);
    }

    match format.as_str() {
        "json" => {
            let json = serde_json::to_string_pretty(&executions)?;
            Ok(json)
        }
        "csv" => {
            let mut csv = String::from(
                "agent,input_tokens,output_tokens,total_tokens,cost_usd,model,provider,success,started_at\n",
            );
            for exec in &executions {
                csv.push_str(&format!(
                    "{},{},{},{},{:.4},{},{},{},{}\n",
                    exec.agent_name,
                    exec.input_tokens,
                    exec.output_tokens,
                    exec.total_tokens,
                    exec.cost_usd(),
                    exec.model.as_deref().unwrap_or(""),
                    exec.provider.as_deref().unwrap_or(""),
                    exec.success,
                    exec.started_at,
                ));
            }
            Ok(csv)
        }
        _ => {
            let mut output = String::new();
            output.push_str(&format!(
                "Execution History ({} to {})\n\n",
                since_str,
                until.as_deref().unwrap_or("now")
            ));
            for exec in &executions {
                output.push_str(&format!(
                    "  [{}] {} - {} tokens, ${:.4} ({})\n",
                    if exec.success { "OK" } else { "FAIL" },
                    exec.agent_name,
                    exec.total_tokens,
                    exec.cost_usd(),
                    exec.started_at,
                ));
            }
            output.push_str(&format!("\nTotal: {} executions\n", executions.len()));
            Ok(output)
        }
    }
}

#[cfg(feature = "persistence")]
fn format_by_model(
    executions: &[crate::store::ExecutionRecord],
    since_str: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let mut grouped: BTreeMap<String, ModelAggregation> = BTreeMap::new();

    for exec in executions {
        let key = exec.model.as_deref().unwrap_or("unknown").to_string();
        let entry = grouped.entry(key).or_insert_with(|| ModelAggregation {
            total_tokens: 0,
            total_cost: 0.0,
            count: 0,
        });
        entry.total_tokens += exec.total_tokens;
        entry.total_cost += exec.cost_usd();
        entry.count += 1;
    }

    let mut output = String::new();
    output.push_str(&format!("Cost by Model (from {})\n\n", since_str));
    output.push_str(&format!(
        "{:<40} {:>12} {:>10} {:>6}\n",
        "Model", "Tokens", "Cost", "Calls"
    ));
    output.push_str(&"-".repeat(70));
    output.push('\n');

    let mut grand_tokens: i64 = 0;
    let mut grand_cost: f64 = 0.0;
    let mut grand_calls: usize = 0;

    for (model, agg) in &grouped {
        output.push_str(&format!(
            "{:<40} {:>12} ${:>9.2} {:>6}\n",
            truncate(model, 40),
            agg.total_tokens,
            agg.total_cost,
            agg.count
        ));
        grand_tokens += agg.total_tokens;
        grand_cost += agg.total_cost;
        grand_calls += agg.count;
    }

    output.push_str(&"-".repeat(70));
    output.push('\n');
    output.push_str(&format!(
        "{:<40} {:>12} ${:>9.2} {:>6}\n",
        "TOTAL", grand_tokens, grand_cost, grand_calls
    ));

    Ok(output)
}

fn truncate(s: &str, max_len: usize) -> String {
    if s.chars().count() <= max_len {
        return s.to_string();
    }
    let end: usize = s
        .char_indices()
        .nth(max_len.saturating_sub(3))
        .map(|(i, _)| i)
        .unwrap_or(s.len());
    format!("{}...", &s[..end])
}

#[cfg(not(feature = "persistence"))]
async fn execute_history(
    since: Option<String>,
    until: Option<String>,
    _last: Option<String>,
    _provider: Option<String>,
    _model: Option<String>,
    _by_model: bool,
    _format: String,
) -> Result<String, Box<dyn std::error::Error>> {
    Ok(format!(
        "History from {} to {} requires persistence feature",
        since.unwrap_or_default(),
        until.unwrap_or_else(|| "now".to_string())
    ))
}

#[cfg(feature = "persistence")]
async fn execute_export(format: String) -> Result<String, Box<dyn std::error::Error>> {
    use crate::store::UsageStore;

    let store = UsageStore::new();
    let since = days_ago_date(30);

    let export = store.export_usage_data(&since, None).await?;

    match format.as_str() {
        "csv" => {
            let mut csv = String::from("agent,budget_cents,spent_usd,total_tokens,executions\n");
            for m in &export.agent_metrics {
                csv.push_str(&format!(
                    "{},{},{:.2},{},{}\n",
                    m.agent_name,
                    m.budget_monthly_cents,
                    m.total_cost_usd(),
                    m.total_tokens(),
                    m.total_executions,
                ));
            }
            Ok(csv)
        }
        _ => {
            let json = serde_json::to_string_pretty(&export)?;
            Ok(json)
        }
    }
}

#[cfg(not(feature = "persistence"))]
async fn execute_export(format: String) -> Result<String, Box<dyn std::error::Error>> {
    Ok(format!("Export as {} requires persistence feature", format))
}

#[cfg(feature = "persistence")]
async fn execute_alert(
    provider: Option<String>,
    budget: Option<f64>,
    threshold: u8,
) -> Result<String, Box<dyn std::error::Error>> {
    use crate::store::UsageStore;

    let store = UsageStore::new();

    if let Some(budget_usd) = budget {
        let month_start = month_start_date();

        let executions = store.query_executions(&month_start, None, None).await?;
        let spent: f64 = executions.iter().map(|e| e.cost_usd()).sum();
        let spent = if spent.abs() < 0.005 { 0.0 } else { spent };
        let pct = if budget_usd > 0.0 {
            (spent / budget_usd) * 100.0
        } else {
            0.0
        };

        let status = if pct >= threshold as f64 {
            "ALERT"
        } else if pct >= (threshold as f64) * 0.9 {
            "WARNING"
        } else {
            "OK"
        };

        return Ok(format!(
            "{}: Monthly spend at ${:.2} ({:.1}% of ${:.2} budget, threshold: {}%)\nExecutions: {}, Tokens: {}",
            status,
            spent,
            pct,
            budget_usd,
            threshold,
            executions.len(),
            executions.iter().map(|e| e.total_tokens).sum::<i64>()
        ));
    }

    let agent_name = provider.unwrap_or_else(|| "*".to_string());

    if agent_name != "*" {
        if let Ok(Some(metrics)) = store.get_agent_metrics(&agent_name).await {
            let percentage = metrics.budget_percentage_used();
            let alert_config = crate::store::AlertConfig::default_for_agent(&agent_name);
            if let Some(triggered) = alert_config.should_alert(percentage) {
                Ok(format!(
                    "ALERT: {} has used {:.1}% of budget (threshold: {}%)",
                    agent_name, percentage, triggered
                ))
            } else {
                Ok(format!(
                    "OK: {} has used {:.1}% of budget (no threshold exceeded)",
                    agent_name, percentage
                ))
            }
        } else {
            Ok(format!(
                "Alert configured for {} at {}% threshold",
                agent_name, threshold
            ))
        }
    } else {
        Ok(format!(
            "Alert configured for all agents at {}% threshold",
            threshold
        ))
    }
}

#[cfg(not(feature = "persistence"))]
async fn execute_alert(
    provider: Option<String>,
    _budget: Option<f64>,
    threshold: u8,
) -> Result<String, Box<dyn std::error::Error>> {
    Ok(format!(
        "Alert for {:?} at {}% requires persistence feature",
        provider, threshold
    ))
}

#[cfg(feature = "persistence")]
async fn execute_budgets(format: String) -> Result<String, Box<dyn std::error::Error>> {
    use crate::store::{BudgetSnapshotRecord, UsageStore};

    let store = UsageStore::new();
    let metrics = store.list_agent_metrics().await?;

    if metrics.is_empty() {
        return Ok("No agent budget data found.".to_string());
    }

    let snapshots: Vec<_> = metrics
        .iter()
        .map(BudgetSnapshotRecord::from_agent_metrics)
        .collect();

    match format.as_str() {
        "json" => {
            let json = serde_json::to_string_pretty(&snapshots)?;
            Ok(json)
        }
        _ => {
            let mut output = String::new();
            output.push_str(&format!("Budget Status - {}\n\n", now_timestamp()));
            for snapshot in &snapshots {
                let status = match snapshot.verdict {
                    crate::store::BudgetVerdict::WithinBudget => "OK",
                    crate::store::BudgetVerdict::ApproachingLimit => "WARN",
                    crate::store::BudgetVerdict::Exceeded => "OVER",
                };
                output.push_str(&format!(
                    "  [{:>4}] {} - ${:.2}/${:.2} ({:.1}%)\n",
                    status,
                    snapshot.agent_name,
                    snapshot.spent_usd(),
                    snapshot.budget_usd(),
                    snapshot.percentage_used,
                ));
            }
            Ok(output)
        }
    }
}

#[cfg(not(feature = "persistence"))]
async fn execute_budgets(_format: String) -> Result<String, Box<dyn std::error::Error>> {
    Ok("Budget status requires persistence feature".to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_period_days() {
        assert_eq!(parse_period("7d"), Some(7));
        assert_eq!(parse_period("30d"), Some(30));
        assert_eq!(parse_period("1d"), Some(1));
    }

    #[test]
    fn test_parse_period_weeks() {
        assert_eq!(parse_period("1w"), Some(7));
        assert_eq!(parse_period("2w"), Some(14));
    }

    #[test]
    fn test_parse_period_months() {
        assert_eq!(parse_period("1m"), Some(30));
        assert_eq!(parse_period("3m"), Some(90));
    }

    #[test]
    fn test_parse_period_bare_number() {
        assert_eq!(parse_period("7"), Some(7));
    }

    #[test]
    fn test_parse_period_invalid() {
        assert_eq!(parse_period("abc"), None);
        assert_eq!(parse_period("0"), None);
        assert_eq!(parse_period("-5d"), None);
        assert_eq!(parse_period("9999d"), None);
    }

    #[test]
    fn test_resolve_since_explicit() {
        let result = resolve_since(&None, &Some("2026-01-01".to_string()));
        assert_eq!(result, "2026-01-01");
    }

    #[test]
    fn test_resolve_since_last() {
        let result = resolve_since(&Some("7d".to_string()), &None);
        let expected = days_ago_date(7);
        assert_eq!(result, expected);
    }

    #[test]
    fn test_resolve_since_default() {
        let result = resolve_since(&None, &None);
        let expected = days_ago_date(7);
        assert_eq!(result, expected);
    }

    #[test]
    fn test_month_start_date() {
        let result = month_start_date();
        let now = Zoned::now();
        let expected = format!("{}-{:02}-01", now.year(), now.month());
        assert_eq!(result, expected);
    }

    #[test]
    fn test_truncate_short() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_long() {
        assert_eq!(
            truncate("a_very_long_model_name_that_exceeds_limit", 20),
            "a_very_long_model..."
        );
    }

    #[test]
    fn test_truncate_multibyte() {
        let model = "openai/\u{1f525}-turbo";
        let truncated = truncate(model, 10);
        assert!(truncated.ends_with("..."));
        assert!(truncated.len() <= 20);
    }

    #[test]
    fn test_truncate_exact_boundary() {
        assert_eq!(truncate("12345", 5), "12345");
        assert_eq!(truncate("123456", 5), "12...");
    }
}