Repository navigation
Expand file tree
/
Copy pathstats.py
More file actions
687 lines (602 loc) · 26.2 KB
/
Copy pathstats.py
File metadata and controls
687 lines (602 loc) · 26.2 KB
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
"""Handler for the /stats slash command.
Subcommands:
/stats → summary for last 24h
/stats today → last 24h (alias)
/stats week → last 168h
/stats month → last 720h
/stats cron → cost/failure breakdown by cron_job_id
/stats raw [N] → last N runs (default 20)
/stats providers → per-provider real vs estimated breakdown (last 24h)
/stats models → per-model breakdown within each provider (last 24h)
/stats efficiency → per-session efficiency scores (0-100, last 24h)
/stats smells → AI smell detection: anti-patterns in sessions (last 24h)
Date range support:
--from YYYY-MM-DD → start date (inclusive)
--to YYYY-MM-DD → end date (exclusive, defaults to now)
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from . import db, smell_detector
def _fmt_cost(v: Any) -> str:
if v is None:
return "$0.000000"
return f"${float(v):.6f}"
def _fmt_ms(v: Any) -> str:
if v is None:
return "—"
ms = float(v)
if ms >= 60_000:
return f"{ms / 60_000:.1f}m"
if ms >= 1_000:
return f"{ms / 1000:.1f}s"
return f"{int(ms)}ms"
def _fmt_int(v: Any) -> str:
if v is None:
return "0"
return f"{int(v):,}"
def _window_label(hours: int) -> str:
if hours <= 24:
return "last 24 h"
if hours <= 168:
return "last 7 days"
return f"last {hours // 24} days"
def _fmt_iso_display(iso: str) -> str:
"""Format an ISO timestamp for display in the date-range label.
Strips the time portion only when it is exactly T00:00:00, and drops
trailing timezone suffixes (Z, +00:00) so the label reads cleanly.
Microseconds are trimmed when present.
"""
s = iso.replace("Z", "").replace("+00:00", "")
if len(s) == 10: # pure date, e.g. "2026-06-16"
return s
if s.endswith("T00:00:00"):
return s[:10]
# Trim fractional seconds if present
if "." in s:
s = s.split(".")[0]
return s
def _date_range_label(date_from: str | None, date_to: str | None) -> str:
if date_from and date_to:
return f"{_fmt_iso_display(date_from)} to {_fmt_iso_display(date_to)}"
if date_from:
return f"since {_fmt_iso_display(date_from)}"
if date_to:
return f"until {_fmt_iso_display(date_to)}"
return "all time"
def _date_range_to_hours(date_from: str | None, date_to: str | None) -> int | None:
"""Convert date range to approximate hours for backward compat label."""
if not date_from:
return None
try:
from_dt = datetime.fromisoformat(date_from.replace("Z", "+00:00"))
to_dt = (
datetime.fromisoformat(date_to.replace("Z", "+00:00"))
if date_to
else datetime.now(timezone.utc)
)
hours = int((to_dt - from_dt).total_seconds() / 3600)
return hours
except Exception:
return None
def _summary_block(
window_hours: int | None = None, *, date_from: str | None = None, date_to: str | None = None
) -> str:
s = db.stats_summary(window_hours=window_hours, date_from=date_from, date_to=date_to)
total = s.get("total_runs") or 0
ok = s.get("ok_runs") or 0
failed = s.get("failed_runs") or 0
success_rate = f"{ok / total * 100:.1f}%" if total else "—"
api_calls = int(s.get("api_calls") or 0)
estimated_calls = int(s.get("estimated_llm_calls") or 0)
has_estimated = estimated_calls > 0
# Use ~ prefix on cost if any calls were estimated
cost_label = "Cost (est.) "
cost_val = s.get("cost_usd")
cost_str = f"~{_fmt_cost(cost_val)}" if has_estimated else _fmt_cost(cost_val)
label = _window_label(window_hours) if window_hours else _date_range_label(date_from, date_to)
lines = [
f"hermes-telemetry — {label}",
"=" * 44,
f" Sessions : {_fmt_int(total)}",
f" Success rate : {success_rate} (ok={_fmt_int(ok)}, failed={_fmt_int(failed)})",
f" API calls : {_fmt_int(api_calls)}",
f" Tool calls : {_fmt_int(s.get('tool_calls'))}",
f" Tokens in : {_fmt_int(s.get('tokens_in'))}",
f" Tokens out : {_fmt_int(s.get('tokens_out'))}",
f" {cost_label}: {cost_str}",
f" Avg latency : {_fmt_ms(s.get('avg_latency_ms'))}",
f" Avg duration : {_fmt_ms(s.get('avg_duration_ms'))}",
]
if has_estimated:
est_pct = f"{estimated_calls / api_calls * 100:.1f}%" if api_calls else "100%"
lines.append(f" Estimated data: {est_pct} of API calls")
if not s.get("parent_links_available", True):
lines.append(
" Note: Subagent tokens are included in the global total. Per-cron-job "
"budgets attribute them to the root job via subagent_edges (see /budget cron); "
"the per-session runs table still shows individual sessions."
)
moa_calls = int(s.get("moa_calls") or 0)
if moa_calls:
lines.append(
f" MoA calls : {_fmt_int(moa_calls)} "
"(aggregator only — reference-model tokens untracked, cost is a lower bound)"
)
top = s.get("top_tools") or []
if top:
lines.append("")
lines.append(" Top tools:")
lines.append(f" {'Tool':<30} {'Calls':>6} {'Failures':>8} {'Avg ms':>8}")
lines.append(" " + "-" * 56)
for t in top:
name = (t.get("tool_name") or "")[:30]
calls = _fmt_int(t.get("calls"))
fails = _fmt_int(t.get("failures"))
avg_ms = _fmt_ms(t.get("avg_ms"))
lines.append(f" {name:<30} {calls:>6} {fails:>8} {avg_ms:>8}")
return "\n".join(lines)
def _cron_block(
window_hours: int | None = None, *, date_from: str | None = None, date_to: str | None = None
) -> str:
rows = db.cost_by_job(window_hours=window_hours, date_from=date_from, date_to=date_to)
label = _window_label(window_hours) if window_hours else _date_range_label(date_from, date_to)
if not rows:
return f"No cron runs in {label}."
lines = [
f"hermes-telemetry — cron jobs ({label})",
"=" * 72,
f" {'Job ID':<20} {'Runs':>5} {'OK':>5} {'Fail':>5} {'Tok-in':>9} {'Tok-out':>9} {'Cost':>12} {'Avg dur':>9}",
" " + "-" * 70,
]
for r in rows:
job_id = (r.get("cron_job_id") or "?")[:20]
runs = _fmt_int(r.get("runs"))
ok = _fmt_int(r.get("ok_runs"))
fail = _fmt_int(r.get("failed_runs"))
tin = _fmt_int(r.get("tokens_in"))
tout = _fmt_int(r.get("tokens_out"))
cost = _fmt_cost(r.get("cost_usd"))
dur = _fmt_ms(r.get("avg_duration_ms"))
lines.append(
f" {job_id:<20} {runs:>5} {ok:>5} {fail:>5} {tin:>9} {tout:>9} {cost:>12} {dur:>9}"
)
since_iso = (
date_from
if date_from
else (datetime.now(timezone.utc) - timedelta(hours=window_hours or 720)).isoformat()
)
unattr = db.unattributed_child_cost(since_iso)
if unattr["edges"]:
lines.append("")
lines.append(
f" ⚠ {unattr['edges']} subagent edge(s) with an unrecorded parent — "
f"{_fmt_cost(unattr['unattributed_usd'])} unattributed to any cron job."
)
lines.append(" (Attributed subagent spend is reflected in `/budget cron`.)")
return "\n".join(lines)
def _providers_block(
window_hours: int | None = None, *, date_from: str | None = None, date_to: str | None = None
) -> str:
rows = db.stats_by_provider(window_hours=window_hours, date_from=date_from, date_to=date_to)
label = _window_label(window_hours) if window_hours else _date_range_label(date_from, date_to)
if not rows:
return f"No API calls recorded in {label}."
lines = [
f"hermes-telemetry — providers ({label})",
"=" * 72,
f" {'Provider':<28} {'Calls':>6} {'Real':>6} {'Est':>5} {'Est%':>6} "
f"{'Asm%':>6} {'Cost':>12}",
" " + "-" * 75,
]
for r in rows:
prov = (r.get("provider") or "(unknown)")[:28]
total = _fmt_int(r.get("total_calls"))
real = _fmt_int(r.get("real_calls"))
est = _fmt_int(r.get("estimated_calls"))
est_pct = f"{r.get('estimated_pct', 0.0) * 100:.0f}%"
asm_pct = f"{r.get('provider_assumed_pct', 0.0) * 100:.0f}%"
cost = _fmt_cost(r.get("cost_usd"))
lines.append(
f" {prov:<28} {total:>6} {real:>6} {est:>5} {est_pct:>6} {asm_pct:>6} {cost:>12}"
)
lines.append("")
lines.append(" Provider key:")
lines.append(" The provider label is whatever the Hermes gateway reports for each API")
lines.append(" call (post_api_request hook); it is stored verbatim and rows are grouped")
lines.append(" by it. It is NOT derived from the model name — so everything the gateway")
lines.append(" routes through OpenRouter shows up under its 'openrouter' label regardless")
lines.append(" of the model's own 'google/', 'openai/', 'anthropic/', \u2026 prefix.")
lines.append(" '(unknown)' = the gateway reported no provider for that call.")
lines.append("")
lines.append(
" Est% = share of calls where the provider returned no usage data "
"(tokens estimated locally)."
)
lines.append(
" If Est% > 0 for your main provider, budget hard-verdicts may be "
"degraded to soft under on_estimated.mode: warn_only."
)
lines.append(
" Asm% = share of calls priced with an assumed rate (issue #42): an "
"OpenRouter-sourced price applied because no provider-native rate was "
"registered. The cost counts as real spend; pin the rate in pricing.yaml "
"(models[<id>], omit _source) to make it explicit and clear Asm%."
)
# Check for estimated-price models
try:
import yaml
pricing_file = Path.home() / ".hermes" / "telemetry" / "pricing.yaml"
if pricing_file.exists():
cfg = yaml.safe_load(pricing_file.read_text()) or {}
est_models = cfg.get("_meta", {}).get("estimated_price_models", [])
if est_models:
lines.append("")
lines.append(
f" \u26a0\ufe0f {len(est_models)} model(s) have estimated pricing "
"(no fixed price from provider)."
)
lines.append(
" Budget hard-verdicts are degraded to soft under "
"on_estimated.mode: warn_only when these models are used."
)
# Show first few examples
for m in est_models[:5]:
lines.append(f" - {m}")
if len(est_models) > 5:
lines.append(f" ... and {len(est_models) - 5} more")
except Exception:
pass
return "\n".join(lines)
def _models_block(
window_hours: int | None = None, *, date_from: str | None = None, date_to: str | None = None
) -> str:
rows = db.stats_by_model(window_hours=window_hours, date_from=date_from, date_to=date_to)
label = _window_label(window_hours) if window_hours else _date_range_label(date_from, date_to)
if not rows:
return f"No API calls recorded in {label}."
# Subscription models (`_subscription: true` in pricing.yaml) are an
# explicitly declared $0 — surface them so the $0.00 footer can stop
# claiming every zero-cost row is a missing-pricing problem.
from . import pricing as _pricing
subscription_models = _pricing._load_custom_pricing().get("subscription_models", set())
lines = [
f"hermes-telemetry — models ({label})",
"=" * 108,
f" {'Provider':<20} {'Model':<46} {'Calls':>6} {'Real':>6} {'Est':>5} {'Cost':>12} Notes",
" " + "-" * 106,
]
sub_zero_count = 0
free_zero_count = 0
noentry_zero_count = 0
for r in rows:
prov = (r.get("provider") or "(unknown)")[:20]
# Model names (esp. OpenRouter's dated keys) are kept wide so the date
# suffix stays visible — that's the whole point of this view.
model = (r.get("model") or "(unknown)")[:46]
total = _fmt_int(r.get("total_calls"))
real = _fmt_int(r.get("real_calls"))
est = _fmt_int(r.get("estimated_calls"))
cost_v = float(r.get("cost_usd") or 0.0)
cost = _fmt_cost(cost_v)
note = ""
if cost_v == 0.0:
# Three-way split of $0.00 rows so the footer never nags about a
# deliberate zero. `is_explicitly_priced` is the authority for
# "intentional $0" vs "unknown model": it is True for a `:free`
# suffix variant (resolved to $0 by rule, incl. the dated ids a
# gateway actually sends) and for built-in $0 seeds, but False for a
# genuine lookup miss. Subscription is checked first — a declared
# `_subscription` model is also explicitly priced, but earns the more
# specific label.
model_raw = r.get("model") or ""
if model_raw.lower() in subscription_models:
note = "subscription/free-tier"
sub_zero_count += 1
elif _pricing.is_explicitly_priced(model_raw, r.get("provider") or ""):
note = "free tier"
free_zero_count += 1
else:
note = "no price entry"
noentry_zero_count += 1
lines.append(f" {prov:<20} {model:<46} {total:>6} {real:>6} {est:>5} {cost:>12} {note}")
lines.append("")
lines.append(" Rows are grouped by provider, then by calls (desc).")
if sub_zero_count:
lines.append(
f" {sub_zero_count} model(s) at $0.00 are subscription/free tier "
"(declared in pricing.yaml via `_subscription: true`)."
)
if free_zero_count:
lines.append(
f" {free_zero_count} model(s) at $0.00 are free tier "
"(`:free` suffix or built-in $0 price)."
)
if noentry_zero_count:
lines.append(
f" {noentry_zero_count} model(s) at $0.00 have no price entry in "
"pricing.yaml — run /setup pricing auto"
)
lines.append(" to refresh, or add them manually.")
return "\n".join(lines)
def _raw_block(limit: int = 20, *, date_from: str | None = None, date_to: str | None = None) -> str:
rows = db.recent_runs(limit, date_from=date_from, date_to=date_to)
if not rows:
return "No runs recorded yet."
lines = [
f"hermes-telemetry — last {limit} runs",
"=" * 80,
]
for r in rows:
(r.get("session_id") or "")[:32]
plat = (r.get("platform") or "")[:8]
model = (r.get("model") or "")[:24]
status = r.get("status") or "?"
cost = _fmt_cost(r.get("cost_usd"))
dur = _fmt_ms(r.get("duration_ms"))
started = (r.get("started_at") or "")[:16]
cron = r.get("cron_job_id") or ""
tag = f" [{cron}]" if cron else ""
lines.append(f" {started} {plat:<8} {model:<24} {status:<10} {cost} {dur}{tag}")
return "\n".join(lines)
_ISO_DATE_FORMATS = (
"%Y-%m-%d",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%SZ",
"%Y-%m-%dT%H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%S.%fZ",
)
def _parse_iso_date(raw: str) -> str | None:
"""Parse a date/timestamp into an ISO-8601 string with a UTC offset.
Returns None when the input isn't a recognized format — slash command args
are user-typed, so we surface a parse failure as "ignore this flag" rather
than raising, and the caller renders an error message inline.
"""
s = raw.strip()
if not s:
return None
# ``fromisoformat`` handles offsets like ``+00:00`` natively and accepts
# ``Z`` on Python 3.11+; it covers the timestamps produced by ``_utcnow``.
try:
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.isoformat()
except ValueError:
pass
# Legacy strptime formats for inputs that don't carry timezone info.
for fmt in _ISO_DATE_FORMATS:
try:
dt = datetime.strptime(s, fmt)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.isoformat()
except ValueError:
continue
return None
def _extract_date_flags(raw_args: str) -> tuple[str, str | None, str | None, str | None]:
"""Pull `--from <val>` and `--to <val>` out of a slash-command arg string.
Returns ``(remaining, date_from, date_to, error)`` where:
- ``remaining`` is the arg string with the flags removed (preset tokens
survive untouched and keep their original casing — the caller still
lowercases them).
- ``date_from`` / ``date_to`` are ISO-normalized or ``None``.
- ``error`` is a human-readable message if a flag value failed to parse,
otherwise ``None``. The caller short-circuits with that message.
"""
if not raw_args:
return ("", None, None, None)
tokens = raw_args.split()
out: list[str] = []
date_from: str | None = None
date_to: str | None = None
i = 0
while i < len(tokens):
tok = tokens[i]
if tok in ("--from", "--to"):
if i + 1 >= len(tokens):
return ("", None, None, f"Missing value for {tok}.")
parsed = _parse_iso_date(tokens[i + 1])
if parsed is None:
return (
"",
None,
None,
f"Invalid date for {tok}: {tokens[i + 1]!r} "
"(use YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ).",
)
if tok == "--from":
date_from = parsed
else:
date_to = parsed
i += 2
else:
out.append(tok)
i += 1
return (" ".join(out), date_from, date_to, None)
def _efficiency_block(
window_hours: int | None = None, *, date_from: str | None = None, date_to: str | None = None
) -> str:
rows = db.efficiency_runs(window_hours=window_hours, date_from=date_from, date_to=date_to)
label = _window_label(window_hours) if window_hours else _date_range_label(date_from, date_to)
if not rows:
return f"No completed sessions found for {label}."
avg_score = sum(r["efficiency_score"] for r in rows) / len(rows)
lines = [
f"hermes-telemetry -- efficiency score ({label})",
"=" * 72,
f" Average efficiency: {avg_score:.1f}/100",
f" Sessions scored: {len(rows)}",
"",
f" {'Score':>6} {'Status':<12} {'APICalls':>9} {'Tok in':>9} {'Tok out':>9} {'Cost':>12} Session",
" " + "-" * 85,
]
for r in rows:
score = r["efficiency_score"]
status = (r.get("status") or "?")[:12]
api = _fmt_int(r.get("api_calls"))
tin = _fmt_int(r.get("tokens_in"))
tout = _fmt_int(r.get("tokens_out"))
cost = _fmt_cost(r.get("cost_usd"))
sid = (r.get("session_id") or "")[:24]
lines.append(f" {score:>6.1f} {status:<12} {api:>9} {tin:>9} {tout:>9} {cost:>12} {sid}")
lines.append("")
lines.append(" Score ranges: 90+ Excellent, 70-89 Good, 50-69 Fair, <50 Needs attention")
lines.append(
" Formula: base(40) + output_ratio(0-60) - error_penalty(0-30) - turn_penalty(0-30)"
)
return "\n".join(lines)
def _smells_block(
window_hours: int | None = None, *, date_from: str | None = None, date_to: str | None = None
) -> str:
smells = smell_detector.detect_all(
window_hours=window_hours, date_from=date_from, date_to=date_to
)
label = _window_label(window_hours) if window_hours else _date_range_label(date_from, date_to)
if not smells:
return f"No AI smells detected for {label}."
lines = [
f"hermes-telemetry -- AI smell detection ({label})",
"=" * 72,
f" Smells detected: {len(smells)}",
"",
]
# Group by smell type for summary
from collections import Counter
type_counts = Counter(s["smell"] for s in smells)
for stype, count in sorted(type_counts.items()):
name = stype.replace("_", " ").title()
lines.append(f" {name:<20} : {count}")
lines.append("")
lines.append(f" {'Sev':<6} {'Smell':<20} {'Session':<26} Detail")
lines.append(" " + "-" * 70)
sev_map = {"high": "HIGH", "medium": "MED", "warning": "WARN"}
for s in smells[:50]:
sev = (sev_map.get(s["severity"], s["severity"]) or s["severity"]).upper()[:6]
name = s["smell"].replace("_", " ").title()[:20]
sid = (s.get("session_id") or "")[:26]
detail = (s.get("detail") or "")[:80]
lines.append(f" {sev:<6} {name:<20} {sid:<26} {detail}")
if len(smells) > 50:
lines.append(f" ... and {len(smells) - 50} more smells (truncated)")
lines.append("")
lines.append(" Smell types:")
lines.append(" Context Rotation — input tokens vastly outnumber output")
lines.append(" Loop Trap — single tool call dominates the session")
lines.append(" Tool Thrashing — many tool calls with high failure rate")
lines.append(" High Error Rate — elevated session failure rate")
lines.append(" Massive Session — extreme token/API call volumes")
lines.append("")
lines.append(" Severity: HIGH > MED > WARN")
return "\n".join(lines)
def handle(raw_args: str) -> str:
"""Entry point for /stats command handler (Slack slash command format).
Supports ``--from <iso>`` / ``--to <iso>`` flags alongside the preset
subcommands so the in-chat surface has parity with the standalone CLI.
When a date flag is supplied, the matching block ignores the preset window
and queries the (possibly bounded) date range instead.
"""
remaining, date_from, date_to, err = _extract_date_flags(raw_args or "")
if err:
return err
has_range = date_from is not None or date_to is not None
args = remaining.strip().lower()
if not args or args in ("today",):
if has_range:
return _summary_block(date_from=date_from, date_to=date_to)
return _summary_block(24)
if args == "week":
return (
_summary_block(168)
if not has_range
else _summary_block(date_from=date_from, date_to=date_to)
)
if args == "month":
return (
_summary_block(720)
if not has_range
else _summary_block(date_from=date_from, date_to=date_to)
)
if args in ("cron", "cron week"):
return (
_cron_block(168) if not has_range else _cron_block(date_from=date_from, date_to=date_to)
)
if args == "cron month":
return (
_cron_block(720) if not has_range else _cron_block(date_from=date_from, date_to=date_to)
)
if args == "cron today":
return (
_cron_block(24) if not has_range else _cron_block(date_from=date_from, date_to=date_to)
)
if args.startswith("raw"):
parts = args.split()
try:
limit = int(parts[1]) if len(parts) > 1 else 20
except ValueError:
limit = 20
if has_range:
return _raw_block(min(limit, 200), date_from=date_from, date_to=date_to)
return _raw_block(min(limit, 200))
if args.startswith("providers"):
sub = args[len("providers") :].strip()
if has_range and sub in ("", "today", "week", "month"):
return _providers_block(date_from=date_from, date_to=date_to)
if sub in ("", "today"):
return _providers_block(24)
if sub == "week":
return _providers_block(168)
if sub == "month":
return _providers_block(720)
if args.startswith("models"):
sub = args[len("models") :].strip()
if has_range and sub in ("", "today", "week", "month"):
return _models_block(date_from=date_from, date_to=date_to)
if sub in ("", "today"):
return _models_block(24)
if sub == "week":
return _models_block(168)
if sub == "month":
return _models_block(720)
if args.startswith("efficiency"):
sub = args[len("efficiency") :].strip()
if has_range and sub in ("", "today", "week", "month"):
return _efficiency_block(date_from=date_from, date_to=date_to)
if sub in ("", "today"):
return _efficiency_block(24)
if sub == "week":
return _efficiency_block(168)
if sub == "month":
return _efficiency_block(720)
if args.startswith("smells"):
sub = args[len("smells") :].strip()
if has_range and sub in ("", "today", "week", "month"):
return _smells_block(date_from=date_from, date_to=date_to)
if sub in ("", "today"):
return _smells_block(24)
if sub == "week":
return _smells_block(168)
if sub == "month":
return _smells_block(720)
return (
"Usage: /stats [today|week|month|cron|cron week|cron month|providers|models|efficiency|smells|raw [N]]\n"
" [--from YYYY-MM-DD[THH:MM:SS[Z]]] [--to YYYY-MM-DD[THH:MM:SS[Z]]]\n"
" /stats — last 24h summary\n"
" /stats week — last 7 days summary\n"
" /stats month — last 30 days summary\n"
" /stats cron — breakdown by cron job (last 7 days)\n"
" /stats providers — per-provider real vs estimated breakdown (24h)\n"
" /stats providers week — provider breakdown, last 7 days\n"
" /stats models — per-model breakdown within each provider (24h)\n"
" /stats models week — per-model breakdown, last 7 days\n"
" /stats efficiency — per-session efficiency scores (0-100, 24h)\n"
" /stats efficiency week — efficiency scores, last 7 days\n"
" /stats smells — AI smell detection (24h)\n"
" /stats smells week — AI smell detection, last 7 days\n"
" /stats raw [N] — last N raw run records (default 20)\n"
"\n"
"Date range examples (work the same way under the CLI):\n"
" /stats models --from 2026-06-16T12:00:00Z\n"
" /stats providers --from 2026-06-10 --to 2026-06-15"
)