cmd-usage 0.7.0

Live Command Code (commandcode.ai) usage dashboard: credits, 5-hour and weekly windows, plan limits. Watch mode or one-shot.
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
use crate::api::{CreditsResp, SubData, UsageSummary};
pub use cmduse_core::{compact, money, plan_monthly_cap, plan_name, PLANS};
use std::io::IsTerminal;

/// Colors unless `NO_COLOR` is set non-empty (no-color.org) or stdout is not a
/// terminal — piping a report must never leak SGR escapes.
pub fn color_enabled() -> bool {
    let no_color = std::env::var("NO_COLOR").is_ok_and(|v| !v.is_empty());
    !no_color && std::io::stdout().is_terminal()
}

pub const RESET: &str = "\x1b[0m";
pub const DIM: &str = "\x1b[2m";
pub const BOLD: &str = "\x1b[1m";
pub const GREEN: &str = "\x1b[32m";
pub const YELLOW: &str = "\x1b[33m";
pub const RED: &str = "\x1b[31m";
pub const CYAN: &str = "\x1b[36m";

pub fn color_for(pct: f64) -> &'static str {
    if pct >= 90.0 {
        RED
    } else if pct >= 70.0 {
        YELLOW
    } else {
        GREEN
    }
}

pub fn bar(used: f64, cap: f64, width: usize) -> String {
    let pct = if cap > 0.0 {
        (used / cap).clamp(0.0, 1.0)
    } else {
        0.0
    };
    let filled = (pct * width as f64).round() as usize;
    let pct_val = pct * 100.0;
    format!(
        "{}{pct_val:>5.1}%{} {}{}{}{}",
        color_for(pct_val),
        RESET,
        GREEN,
        "━".repeat(filled),
        DIM,
        "╱".repeat(width - filled)
    )
}

pub fn rel_time(reset_at: Option<f64>, now: u64) -> String {
    cmduse_core::rel_time(reset_at, Some(now))
}

/// Plan comparison table (mirrors the opencode plugin's plans table). The
/// current plan row is shown with a leading "*" and, when `colors`, in bold.
pub fn plans_table(current_plan_id: &str, colors: bool) -> String {
    // Empty id = plan unknown (no key/network): mark nothing rather than
    // falling through to plan_name("") == "Free" and bolding the wrong row.
    let mine = if current_plan_id.is_empty() {
        ""
    } else {
        plan_name(current_plan_id)
    };
    let (hl, rst) = if colors { (BOLD, RESET) } else { ("", "") };
    let mut o = format!(
        "{hl}{:<10} {:>8} {:>11} {:>8} {:>8}{rst}\n",
        "Plan", "Price", "Credits/mo", "5-hour", "Weekly"
    );
    for &(name, price, monthly, h5, wk) in PLANS {
        if name == mine {
            o.push_str(&format!(
                "{hl}*{:<9} {:>6}/mo {:>11} {:>8} {:>8}{rst}\n",
                name, price, monthly, h5, wk
            ));
        } else {
            o.push_str(&format!(
                " {:<9} {:>6}/mo {:>11} {:>8} {:>8}\n",
                name, price, monthly, h5, wk
            ));
        }
    }
    o.push_str("\nWindows throttle only included monthly credits; on-demand (`/extra`) credits are never throttled.\n");
    o
}

/// Plan table as JSON: array of {name, price, creditsMonthly, fiveHour, weekly, current}.
pub fn plans_json(current_plan_id: &str) -> String {
    let mine = if current_plan_id.is_empty() {
        ""
    } else {
        plan_name(current_plan_id)
    };
    let items: Vec<serde_json::Value> = PLANS
        .iter()
        .map(|(name, price, monthly, h5, wk)| {
            serde_json::json!({
                "name": name,
                "price": price,
                "creditsMonthly": monthly,
                "fiveHour": h5,
                "weekly": wk,
                "current": *name == mine,
            })
        })
        .collect();
    serde_json::Value::Array(items).to_string()
}

/// Machine-readable dashboard, one JSON object. Nested windows mirror the
/// CLI's own JSON (camelCase fields).
pub fn render_json(s: &Snapshot) -> String {
    use serde_json::{json, Value};

    fn win(w: &Option<crate::api::Window>) -> Value {
        match w {
            Some(w) => json!({
                "used": w.used,
                "cap": w.cap,
                "exceeded": w.exceeded,
                "resetAt": w.reset_at,
            }),
            None => Value::Null,
        }
    }
    json!({
        "plan": plan_name(&s.sub.plan_id),
        "status": s.sub.status,
        "periodEnd": s.sub.current_period_end.as_ref().map(|e| &e[..10.min(e.len())]),
        "monthlyCredits": s.credits.credits.monthly_credits,
        "monthlyCap": plan_monthly_cap(&s.sub.plan_id),
        "purchasedCredits": s.credits.credits.purchased_credits,
        "freeCredits": s.credits.credits.free_credits,
        "fiveHour": win(&s.credits.window_limits.five_hour),
        "weekly": win(&s.credits.window_limits.weekly),
        "summary": {
            "requests": s.summary.total_count,
            "cost": s.summary.total_cost,
            "tokensIn": s.summary.total_tokens_in,
            "tokensOut": s.summary.total_tokens_out,
            "successRate": s.summary.success_rate,
        },
        "error": s.err,
    })
    .to_string()
}

/// Elapsed % of a rolling window: window length = dur_secs, ends at reset_at.
pub fn elapsed_pct(reset_at: Option<f64>, dur_secs: u64, now: u64) -> Option<u8> {
    cmduse_core::elapsed_pct(reset_at, dur_secs, Some(now))
}

pub fn window_line(
    label: &str,
    w: &crate::api::Window,
    now: u64,
    bar_width: usize,
    dur_secs: Option<u64>,
) -> String {
    let flag = if w.exceeded {
        format!(" {RED}{BOLD}LIMIT EXCEEDED{RESET}")
    } else {
        String::new()
    };
    // Field order is importance order: watch frames get clipped to the
    // terminal width from the right, so the actionable parts (limit flag,
    // pace warning) must sit before the informational elapsed share.
    let thru = dur_secs
        .and_then(|d| elapsed_pct(w.reset_at, d, now))
        .map(|p| format!(" · {DIM}window {p}% elapsed{RESET}"))
        .unwrap_or_default();
    // burn-rate projection: spend rate over window elapsed time → when cap hits.
    // ponytail: assumes flat spend rate; bursty sessions shift the ETA.
    // upgrade: revisit if ETA misfires in practice (no server rate history yet).
    let pace = dur_secs
        .and_then(|d| {
            cmduse_core::pace_eta(w.reset_at, d, w.used, w.cap, now)
                .map(|secs| cmduse_core::duration(secs as u64))
        })
        .map(|eta| format!(" · {YELLOW}on pace to hit cap in {eta}{RESET}"))
        .unwrap_or_default();
    format!(
        " {BOLD}{label:<8}{RESET} {} {DIM}{} / {} · resets in {}{flag}{pace}{thru}{RESET}",
        bar(w.used, w.cap, bar_width),
        money(w.used),
        money(w.cap),
        rel_time(w.reset_at, now),
    )
}

pub struct Snapshot {
    pub sub: SubData,
    pub credits: CreditsResp,
    pub summary: UsageSummary,
    pub now: u64,
    pub err: Option<String>,
}

pub fn render(s: &Snapshot, bar_width: usize) -> String {
    // error: single minimal frame. Don't render fake zero-data plan/credits
    // below it (was: "Free · —" with $0.00 everywhere on API failure).
    if let Some(e) = &s.err {
        return format!(
            "{BOLD}Command Code Usage{RESET} {DIM}· fetch failed{RESET}\n{RED}error:{RESET} {e}\n{DIM}retrying on next refresh{RESET}"
        );
    }
    let mut o = String::new();
    o.push_str(&format!(
        "{BOLD}Command Code Usage{RESET} {DIM}· {} · {}{RESET}\n",
        plan_name(&s.sub.plan_id),
        s.sub.status
    ));
    if let Some(end) = &s.sub.current_period_end {
        o.push_str(&format!(
            "{DIM}Period ends {}{RESET}\n",
            &end[..10.min(end.len())]
        ));
    }
    o.push('\n');

    let monthly_cap = plan_monthly_cap(&s.sub.plan_id);
    match monthly_cap {
        Some(cap) => {
            o.push_str(&format!(
                "{BOLD}Credits{RESET} {} / {} monthly · {} purchased · {} free\n",
                money(s.credits.credits.monthly_credits),
                money(cap),
                money(s.credits.credits.purchased_credits),
                money(s.credits.credits.free_credits),
            ));
        }
        None => {
            o.push_str(&format!(
                "{BOLD}Credits{RESET} {} monthly · {} purchased · {} free\n",
                money(s.credits.credits.monthly_credits),
                money(s.credits.credits.purchased_credits),
                money(s.credits.credits.free_credits),
            ));
        }
    }

    o.push_str(&format!("\n{BOLD}Usage windows{RESET}\n"));
    // Monthly: cap from plan table, used = cap - remaining monthly credits.
    // reset_at is the subscription period end parsed by cmduse-core, which
    // honors an explicit +HH:MM offset when present and reads UTC otherwise.
    if let Some(cap) = monthly_cap {
        let (w, dur) = cmduse_core::monthly_window(
            cap,
            s.credits.credits.monthly_credits,
            s.sub.current_period_start.as_deref(),
            s.sub.current_period_end.as_deref(),
        );
        o.push_str(&window_line("Monthly", &w, s.now, bar_width, dur));
        o.push('\n');
    }
    match (
        &s.credits.window_limits.five_hour,
        &s.credits.window_limits.weekly,
    ) {
        (Some(h5), Some(wk)) => {
            o.push_str(&window_line(
                "5-hour",
                h5,
                s.now,
                bar_width,
                Some(cmduse_core::FIVE_HOUR_SECS),
            ));
            o.push('\n');
            o.push_str(&window_line(
                "Weekly",
                wk,
                s.now,
                bar_width,
                Some(cmduse_core::WEEKLY_SECS),
            ));
            o.push('\n');
        }
        (None, None) => {
            o.push_str(&format!(" {DIM}none on this plan (pay-as-you-go){RESET}\n"));
        }
        (h5, wk) => {
            if let Some(w) = h5 {
                o.push_str(&window_line(
                    "5-hour",
                    w,
                    s.now,
                    bar_width,
                    Some(cmduse_core::FIVE_HOUR_SECS),
                ));
                o.push('\n');
            }
            if let Some(w) = wk {
                o.push_str(&window_line(
                    "Weekly",
                    w,
                    s.now,
                    bar_width,
                    Some(cmduse_core::WEEKLY_SECS),
                ));
                o.push('\n');
            }
        }
    }

    o.push_str(&format!("\n{BOLD}This billing period{RESET}\n"));
    o.push_str(&format!(
        " Requests {CYAN}{}{RESET} · Cost {CYAN}{}{RESET} · Tokens {CYAN}{}{RESET} in / {CYAN}{}{RESET} out · Success {CYAN}{:.0}%{RESET}\n",
        compact(s.summary.total_count.unwrap_or(0)),
        money(s.summary.total_cost.unwrap_or(0.0)),
        compact(s.summary.total_tokens_in.unwrap_or(0)),
        compact(s.summary.total_tokens_out.unwrap_or(0)),
        s.summary.success_rate.unwrap_or(0.0),
    ));

    o
}

/// One-shot plain output (no ANSI colors), for scripts.
pub fn render_plain(s: &Snapshot) -> String {
    if let Some(e) = &s.err {
        return format!("Command Code Usage · fetch failed\nerror: {e}\n");
    }
    let mut o = String::new();
    o.push_str(&format!(
        "Command Code Usage · {} · {}\n",
        plan_name(&s.sub.plan_id),
        s.sub.status
    ));
    if let Some(end) = &s.sub.current_period_end {
        o.push_str(&format!("Period ends {}\n", &end[..10.min(end.len())]));
    }
    let monthly_cap = plan_monthly_cap(&s.sub.plan_id);
    match monthly_cap {
        Some(cap) => o.push_str(&format!(
            "Credits: {} / {} monthly, {} purchased, {} free\n",
            money(s.credits.credits.monthly_credits),
            money(cap),
            money(s.credits.credits.purchased_credits),
            money(s.credits.credits.free_credits),
        )),
        None => o.push_str(&format!(
            "Credits: {} monthly, {} purchased, {} free\n",
            money(s.credits.credits.monthly_credits),
            money(s.credits.credits.purchased_credits),
            money(s.credits.credits.free_credits),
        )),
    }
    // Monthly allowance window (cap from the plan table, reset from the
    // subscription period) — same math as the colored dashboard.
    if let Some(cap) = monthly_cap {
        let (w, dur) = cmduse_core::monthly_window(
            cap,
            s.credits.credits.monthly_credits,
            s.sub.current_period_start.as_deref(),
            s.sub.current_period_end.as_deref(),
        );
        o.push_str(&plain_window_line("Monthly", &w, s.now, dur));
    }
    if let Some(w) = &s.credits.window_limits.five_hour {
        o.push_str(&plain_window_line(
            "5-hour",
            w,
            s.now,
            Some(cmduse_core::FIVE_HOUR_SECS),
        ));
    }
    if let Some(w) = &s.credits.window_limits.weekly {
        o.push_str(&plain_window_line(
            "Weekly",
            w,
            s.now,
            Some(cmduse_core::WEEKLY_SECS),
        ));
    }
    o.push_str(&format!(
        "Period: {} requests, {}, {} in/{} out tokens\n",
        s.summary.total_count.unwrap_or(0),
        money(s.summary.total_cost.unwrap_or(0.0)),
        compact(s.summary.total_tokens_in.unwrap_or(0)),
        compact(s.summary.total_tokens_out.unwrap_or(0)),
    ));
    o
}

/// One plain (no-SGR) window line: usage %, dollars, reset countdown, elapsed
/// share, and the burn-rate pace warning. Mirrors `window_line` minus colors.
pub(crate) fn plain_window_line(
    label: &str,
    w: &crate::api::Window,
    now: u64,
    dur_secs: Option<u64>,
) -> String {
    let pct = if w.cap > 0.0 {
        w.used / w.cap * 100.0
    } else {
        0.0
    };
    let elapsed = dur_secs
        .and_then(|d| elapsed_pct(w.reset_at, d, now))
        .map(|p| format!(" · window {p}% elapsed"))
        .unwrap_or_default();
    // burn-rate projection, same as the colored dashboard: flat-spend estimate
    // of when the cap is hit at the current rate.
    let pace = dur_secs
        .and_then(|d| {
            cmduse_core::pace_eta(w.reset_at, d, w.used, w.cap, now)
                .map(|secs| cmduse_core::duration(secs as u64))
        })
        .map(|eta| format!(" · on pace to hit cap in {eta}"))
        .unwrap_or_default();
    let flag = if w.exceeded { " · LIMIT EXCEEDED" } else { "" };
    // Same importance order as the colored renderer: clipped watch frames must
    // keep the flag and the pace warning before the elapsed share.
    format!(
        "{label}: {pct:.0}% ({} / {}) · resets in {}{flag}{pace}{elapsed}\n",
        money(w.used),
        money(w.cap),
        rel_time(w.reset_at, now),
    )
}

/// ASCII cost trend: 8-point sparkline, last `cap` samples of $ spent.
pub fn sparkline(history: &[f64]) -> String {
    const BARS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
    if history.len() < 2 {
        return String::new();
    }
    let max = history.iter().cloned().fold(0.0_f64, f64::max);
    if max <= 0.0 {
        return "▁".repeat(history.len());
    }
    // any nonzero activity gets a visible bar; otherwise a 0.02 delta next
    // to an old 0.50 spike rounds to zero and looks dead
    history
        .iter()
        .map(|v| {
            let idx = (v / max * 7.0).round() as usize;
            BARS[idx.max(if *v > 0.0 { 1 } else { 0 })]
        })
        .collect()
}

/// Char-safe greedy word wrap; overlong words are hard-split. `w` is the
/// inner content width in characters.
fn wrap_chars(s: &str, w: usize) -> Vec<String> {
    if w == 0 {
        return vec![s.to_string()];
    }
    let mut out: Vec<String> = Vec::new();
    let mut cur = String::new();
    let mut cur_len = 0usize;
    for word in s.split(' ') {
        let mut word = word;
        if cur_len > 0 && cur_len + 1 + word.chars().count() > w {
            out.push(std::mem::take(&mut cur));
            cur_len = 0;
        }
        while word.chars().count() > w {
            let split = word
                .char_indices()
                .nth(w)
                .map(|(i, _)| i)
                .unwrap_or(word.len());
            let (head, tail) = word.split_at(split);
            if cur_len > 0 {
                out.push(std::mem::take(&mut cur));
                cur_len = 0;
            }
            out.push(head.to_string());
            word = tail;
        }
        if cur_len > 0 {
            cur.push(' ');
            cur_len += 1;
        }
        cur.push_str(word);
        cur_len += word.chars().count();
    }
    if cur_len > 0 {
        out.push(cur);
    }
    if out.is_empty() {
        out.push(String::new());
    }
    out
}

/// Boxed update notice for the watch frame. Wraps to the terminal width and
/// colours the whole box yellow when `colors`.
pub fn update_box(msg: &str, cols: Option<usize>, colors: bool) -> String {
    let msg_len = msg.chars().count();
    let max_inner = cols.map_or(msg_len, |c| c.saturating_sub(4).max(8));
    let inner = msg_len.min(max_inner).max(8);
    let bar = "─".repeat(inner + 2);
    let (hl, rst) = if colors { (YELLOW, RESET) } else { ("", "") };
    let mut out = format!("{hl}╭{bar}╮{rst}\n");
    for chunk in wrap_chars(msg, inner) {
        let body = format!("{chunk:<inner$}");
        out.push_str(&format!("{hl}│ {body} │{rst}\n"));
    }
    out.push_str(&format!("{hl}╰{bar}╯{rst}\n"));
    out
}