agentusage 0.1.9

Local-first agent usage tracking
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
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    env,
    io::{self, IsTerminal},
};

pub mod postgres;
pub mod schema;
pub mod sqlite;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawEvent {
    pub event_id: String,
    pub source_system: String,
    pub source_channel: String,
    pub occurred_at: DateTime<Utc>,
    pub payload: serde_json::Value,
    pub payload_hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UsageMetric {
    pub metric_id: String,
    pub occurred_at: DateTime<Utc>,
    pub provider_id: String,
    pub agent_name: String,
    pub session_id: Option<String>,
    pub dimension: String,
    pub name: String,
    pub dedup_key: String,
}

/// One imported provider event. The source JSONL is retained here for audit,
/// while the common columns let the dashboard query without reopening files.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct IngestRecord {
    pub record_id: String,
    pub source_path: String,
    pub line_number: i64,
    pub occurred_at: Option<DateTime<Utc>>,
    pub provider_id: String,
    pub agent_name: String,
    pub session_id: Option<String>,
    pub event_type: String,
    pub payload_type: Option<String>,
    pub model: Option<String>,
    pub client: Option<String>,
    pub project: Option<String>,
    pub tool_name: Option<String>,
    pub payload: serde_json::Value,
    pub dedup_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UsageEvent {
    pub event_id: String,
    pub occurred_at: DateTime<Utc>,
    pub provider_id: String,
    pub agent_name: String,
    pub account_id: Option<String>,
    pub session_id: Option<String>,
    pub model: Option<String>,
    pub client: Option<String>,
    pub project: Option<String>,
    pub input_tokens: i64,
    pub output_tokens: i64,
    pub reasoning_tokens: i64,
    pub cache_read_tokens: i64,
    pub cache_write_tokens: i64,
    pub total_tokens: i64,
    pub cost_usd: f64,
    pub ai_units_nano: i64,
    pub request_multiplier: f64,
    pub ai_credits: f64,
    pub requests: i64,
    pub prompts: i64,
    pub lines_added: i64,
    pub lines_removed: i64,
    pub dedup_key: String,
    pub raw_event_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FileCursor {
    pub path: String,
    pub byte_offset: i64,
    pub file_size: i64,
    pub last_event_hash: Option<String>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UsageSummary {
    pub from: DateTime<Utc>,
    pub to: DateTime<Utc>,
    pub sessions: i64,
    pub requests: i64,
    pub prompts: i64,
    pub input_tokens: i64,
    pub output_tokens: i64,
    pub reasoning_tokens: i64,
    pub cache_read_tokens: i64,
    pub cache_write_tokens: i64,
    pub total_tokens: i64,
    pub cost_usd: f64,
    pub ai_units_nano: i64,
    pub request_multiplier: f64,
    pub ai_credits: f64,
    pub lines_added: i64,
    pub lines_removed: i64,
    pub models: BTreeMap<String, UsageBucket>,
    pub clients: BTreeMap<String, UsageBucket>,
    pub projects: BTreeMap<String, UsageBucket>,
    pub tools: BTreeMap<String, i64>,
    pub languages: BTreeMap<String, i64>,
    pub primary_used_percent: Option<f64>,
    pub primary_window_minutes: Option<i64>,
    pub primary_resets_at: Option<i64>,
}

/// Extract quota from one provider payload. The caller is responsible for
/// selecting the latest raw event before calling this function.
pub fn quota_from_payload(value: &serde_json::Value) -> Option<(f64, Option<i64>, Option<i64>)> {
    fn walk(value: &serde_json::Value) -> Option<(f64, Option<i64>, Option<i64>)> {
        if let serde_json::Value::Object(object) = value {
            let number = |keys: &[&str]| {
                keys.iter().find_map(|key| {
                    object.get(*key).and_then(|value| {
                        value
                            .as_f64()
                            .or_else(|| value.as_i64().map(|value| value as f64))
                            .or_else(|| value.as_str()?.parse::<f64>().ok())
                    })
                })
            };
            if let Some(used) =
                number(&["used_percent", "usedPercent", "percent_used", "percentUsed"])
            {
                return Some((
                    used,
                    number(&["window_minutes", "windowMinutes", "window"])
                        .map(|value| value as i64),
                    number(&["resets_at", "resetsAt", "reset_at", "resetAt"])
                        .map(|value| value as i64),
                ));
            }
            for child in object.values() {
                if let Some(result) = walk(child) {
                    return Some(result);
                }
            }
        } else if let serde_json::Value::Array(values) = value {
            for child in values {
                if let Some(result) = walk(child) {
                    return Some(result);
                }
            }
        }
        None
    }
    walk(value)
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UsageBucket {
    pub requests: i64,
    pub input_tokens: i64,
    pub output_tokens: i64,
    pub reasoning_tokens: i64,
    pub cache_read_tokens: i64,
    pub cache_write_tokens: i64,
    pub total_tokens: i64,
    pub cost_usd: f64,
    pub ai_units_nano: i64,
    pub request_multiplier: f64,
    pub ai_credits: f64,
}

impl UsageSummary {
    pub fn cache_hit_rate(&self) -> Option<f64> {
        let denominator = self.input_tokens + self.cache_read_tokens + self.cache_write_tokens;
        (denominator > 0 && self.cache_read_tokens > 0)
            .then(|| self.cache_read_tokens as f64 / denominator as f64 * 100.0)
    }
}

pub trait UsageStore {
    fn begin_batch(&mut self) -> Result<()> {
        Ok(())
    }
    fn end_batch(&mut self) -> Result<()> {
        Ok(())
    }
    fn append_record(&mut self, record: &IngestRecord) -> Result<bool> {
        let _ = record;
        Ok(false)
    }
    fn append_raw_event(&mut self, event: &RawEvent) -> Result<bool>;
    fn append_usage_event(&mut self, event: &UsageEvent) -> Result<bool>;
    fn append_metric(&mut self, metric: &UsageMetric) -> Result<bool> {
        let _ = metric;
        Ok(false)
    }
    fn cursor(&mut self, path: &str) -> Result<Option<FileCursor>>;
    fn save_cursor(&mut self, cursor: &FileCursor) -> Result<()>;
    fn summary(&mut self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<UsageSummary>;
    fn summary_for_agent(
        &mut self,
        agent_name: Option<&str>,
        from: DateTime<Utc>,
        to: DateTime<Utc>,
    ) -> Result<UsageSummary>;
}

pub enum Backend {
    Sqlite(sqlite::SqliteStore),
    Postgres(postgres::PostgresStore),
}

impl Backend {
    pub fn open(mode: BackendMode) -> Result<Self> {
        Self::open_for_agent(mode, "codex")
    }

    pub fn open_for_agent(mode: BackendMode, agent: &str) -> Result<Self> {
        match mode {
            BackendMode::Sqlite => Ok(Self::Sqlite(sqlite::SqliteStore::open(
                &crate::config::agent_db_path(agent)?,
            )?)),
            BackendMode::Postgres => {
                let url = env::var("AGENTUSAGE_POSTGRES_URL")
                    .map_err(|_| anyhow::anyhow!("AGENTUSAGE_POSTGRES_URL is not set"))?;
                Ok(Self::Postgres(postgres::PostgresStore::connect(&url)?))
            }
        }
    }

    pub fn open_read_only_for_agent(mode: BackendMode, agent: &str) -> Result<Self> {
        match mode {
            BackendMode::Sqlite => Ok(Self::Sqlite(sqlite::SqliteStore::open_read_only(
                &crate::config::agent_db_path(agent)?,
            )?)),
            BackendMode::Postgres => {
                let url = env::var("AGENTUSAGE_POSTGRES_URL")
                    .map_err(|_| anyhow::anyhow!("AGENTUSAGE_POSTGRES_URL is not set"))?;
                Ok(Self::Postgres(postgres::PostgresStore::connect(&url)?))
            }
        }
    }

    pub fn quick_summary_for_agent(
        &mut self,
        agent_name: &str,
        from: DateTime<Utc>,
        to: DateTime<Utc>,
    ) -> Result<UsageSummary> {
        match self {
            Self::Sqlite(store) => store.quick_summary_for_agent(agent_name, from, to),
            Self::Postgres(store) => store.summary_for_agent(Some(agent_name), from, to),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendMode {
    Sqlite,
    Postgres,
}

pub fn prepare_backend(interactive: bool) -> Result<BackendMode> {
    prepare_backend_for_agent(interactive, "codex")
}

pub fn prepare_backend_for_agent(interactive: bool, agent: &str) -> Result<BackendMode> {
    let sqlite_path = crate::config::agent_db_path(agent)?;
    if sqlite_path.exists() {
        match sqlite::SqliteStore::open(&sqlite_path) {
            Ok(_) => {
                eprintln!(
                    "[agentusage] storage backend=sqlite path={}",
                    sqlite_path.display()
                );
                return Ok(BackendMode::Sqlite);
            }
            Err(error) => {
                eprintln!(
                    "[agentusage] SQLite database exists but could not be opened path={} error={error:#}",
                    sqlite_path.display()
                );
            }
        }
    }
    let postgres_url = env::var("AGENTUSAGE_POSTGRES_URL")
        .ok()
        .filter(|value| !value.trim().is_empty());
    if let Some(url) = postgres_url.as_deref()
        && postgres::PostgresStore::connect(url).is_ok()
    {
        eprintln!("[agentusage] storage backend=postgres status=connected");
        return Ok(BackendMode::Postgres);
    }
    if !interactive || !io::stdin().is_terminal() {
        anyhow::bail!(
            "no initialized SQLite or PostgreSQL usage storage found; run `agentusage sync {agent}` after selecting a database backend"
        );
    }
    println!("No initialized usage storage backend was found.");
    println!("Choose the preferred backend:");
    println!("[s] Initialize SQLite at {}", sqlite_path.display());
    if postgres_url.is_some() {
        println!("[p] Initialize PostgreSQL from AGENTUSAGE_POSTGRES_URL");
    }
    println!("Enter your choice [s/p]:");
    let mut answer = String::new();
    io::stdin().read_line(&mut answer)?;
    match answer.trim().to_ascii_lowercase().as_str() {
        "s" | "sqlite" => {
            sqlite::SqliteStore::open(&sqlite_path)?;
            eprintln!(
                "[agentusage] storage backend=sqlite initialized path={}",
                sqlite_path.display()
            );
            Ok(BackendMode::Sqlite)
        }
        "p" | "postgres" if postgres_url.is_some() => {
            postgres::PostgresStore::connect(postgres_url.as_deref().unwrap())?;
            eprintln!("[agentusage] storage backend=postgres initialized");
            Ok(BackendMode::Postgres)
        }
        _ => anyhow::bail!("no storage backend selected; choose SQLite or PostgreSQL"),
    }
}

impl UsageStore for Backend {
    fn begin_batch(&mut self) -> Result<()> {
        match self {
            Self::Sqlite(store) => store.begin_batch(),
            Self::Postgres(store) => store.begin_batch(),
        }
    }

    fn end_batch(&mut self) -> Result<()> {
        match self {
            Self::Sqlite(store) => store.end_batch(),
            Self::Postgres(store) => store.end_batch(),
        }
    }

    fn append_record(&mut self, record: &IngestRecord) -> Result<bool> {
        match self {
            Self::Sqlite(store) => store.append_record(record),
            Self::Postgres(store) => store.append_record(record),
        }
    }

    fn append_raw_event(&mut self, event: &RawEvent) -> Result<bool> {
        match self {
            Self::Sqlite(store) => store.append_raw_event(event),
            Self::Postgres(store) => store.append_raw_event(event),
        }
    }
    fn append_usage_event(&mut self, event: &UsageEvent) -> Result<bool> {
        match self {
            Self::Sqlite(store) => store.append_usage_event(event),
            Self::Postgres(store) => store.append_usage_event(event),
        }
    }

    fn append_metric(&mut self, metric: &UsageMetric) -> Result<bool> {
        match self {
            Self::Sqlite(store) => store.append_metric(metric),
            Self::Postgres(store) => store.append_metric(metric),
        }
    }
    fn cursor(&mut self, path: &str) -> Result<Option<FileCursor>> {
        match self {
            Self::Sqlite(store) => store.cursor(path),
            Self::Postgres(store) => store.cursor(path),
        }
    }
    fn save_cursor(&mut self, cursor: &FileCursor) -> Result<()> {
        match self {
            Self::Sqlite(store) => store.save_cursor(cursor),
            Self::Postgres(store) => store.save_cursor(cursor),
        }
    }
    fn summary(&mut self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<UsageSummary> {
        match self {
            Self::Sqlite(store) => store.summary(from, to),
            Self::Postgres(store) => store.summary(from, to),
        }
    }
    fn summary_for_agent(
        &mut self,
        agent_name: Option<&str>,
        from: DateTime<Utc>,
        to: DateTime<Utc>,
    ) -> Result<UsageSummary> {
        match self {
            Self::Sqlite(store) => store.summary_for_agent(agent_name, from, to),
            Self::Postgres(store) => store.summary_for_agent(agent_name, from, to),
        }
    }
}

pub fn add_event(summary: &mut UsageSummary, event: &UsageEvent) {
    summary.requests += event.requests;
    summary.prompts += event.prompts;
    summary.input_tokens += event.input_tokens;
    summary.output_tokens += event.output_tokens;
    summary.reasoning_tokens += event.reasoning_tokens;
    summary.cache_read_tokens += event.cache_read_tokens;
    summary.cache_write_tokens += event.cache_write_tokens;
    summary.total_tokens += event.total_tokens;
    summary.cost_usd += event.cost_usd;
    summary.ai_units_nano += event.ai_units_nano;
    summary.ai_credits += event.ai_credits;
    summary.lines_added += event.lines_added;
    summary.lines_removed += event.lines_removed;
    let bucket = UsageBucket {
        requests: event.requests,
        input_tokens: event.input_tokens,
        output_tokens: event.output_tokens,
        reasoning_tokens: event.reasoning_tokens,
        cache_read_tokens: event.cache_read_tokens,
        cache_write_tokens: event.cache_write_tokens,
        total_tokens: event.total_tokens,
        cost_usd: event.cost_usd,
        ai_units_nano: event.ai_units_nano,
        request_multiplier: event.request_multiplier,
        ai_credits: event.ai_credits,
    };
    if let Some(model) = &event.model {
        add_bucket(summary.models.entry(model.clone()).or_default(), &bucket);
    }
    if let Some(client) = &event.client {
        add_bucket(summary.clients.entry(client.clone()).or_default(), &bucket);
    }
    if let Some(project) = &event.project {
        add_bucket(
            summary.projects.entry(project.clone()).or_default(),
            &bucket,
        );
    }
}

fn add_bucket(target: &mut UsageBucket, value: &UsageBucket) {
    target.requests += value.requests;
    target.input_tokens += value.input_tokens;
    target.output_tokens += value.output_tokens;
    target.reasoning_tokens += value.reasoning_tokens;
    target.cache_read_tokens += value.cache_read_tokens;
    target.cache_write_tokens += value.cache_write_tokens;
    target.total_tokens += value.total_tokens;
    target.cost_usd += value.cost_usd;
    target.ai_units_nano += value.ai_units_nano;
    target.request_multiplier += value.request_multiplier;
    target.ai_credits += value.ai_credits;
}

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

    #[test]
    fn extracts_quota_from_latest_codex_payload_shape() {
        let payload = serde_json::json!({
            "payload": {
                "rate_limits": {
                    "primary": {
                        "used_percent": 26.0,
                        "window_minutes": 10080,
                        "resets_at": 1785091968
                    }
                }
            }
        });
        assert_eq!(
            quota_from_payload(&payload),
            Some((26.0, Some(10080), Some(1785091968)))
        );
    }
}