@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +448 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +788 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +149 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3633 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +141 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +93 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +288 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +426 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +400 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +59531 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,3633 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Fleet Auditor: Cross-Platform Agent Token Waste Auditor.
|
|
3
|
+
|
|
4
|
+
Detects agent systems (Claude Code, Codex, OpenClaw, NanoClaw, Hermes, OpenCode, IronClaw),
|
|
5
|
+
collects token usage data, identifies waste patterns, and recommends fixes with
|
|
6
|
+
dollar savings estimates.
|
|
7
|
+
|
|
8
|
+
Zero external dependencies. Python 3.10+.
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
python3 fleet.py detect # What systems are installed?
|
|
12
|
+
python3 fleet.py scan [--system X] [--days 30] # Collect into fleet.db
|
|
13
|
+
python3 fleet.py audit [--system X] [--days 30] # Waste detection
|
|
14
|
+
python3 fleet.py report [--system X] [--json] # Full report with $ savings
|
|
15
|
+
python3 fleet.py dashboard [--serve] # Generate fleet dashboard
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import shlex
|
|
24
|
+
import sqlite3
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
import time
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from datetime import datetime, timedelta, timezone
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
# Windows console-flash guard. A console-subsystem child spawned from a
|
|
34
|
+
# console-less parent -- which is exactly what the Claude Desktop app is -- makes
|
|
35
|
+
# Windows allocate a BRAND NEW console for it, i.e. the cmd window that flashes
|
|
36
|
+
# on screen. CREATE_NO_WINDOW suppresses that allocation. The attribute only
|
|
37
|
+
# exists on Windows builds of CPython, so getattr(..., 0) makes passing it a
|
|
38
|
+
# no-op everywhere else (creationflags=0 is the documented default).
|
|
39
|
+
_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
40
|
+
|
|
41
|
+
# ---------------------------------------------------------------------------
|
|
42
|
+
# Resolve shared.py: works from skill dir, plugin cache, or standalone
|
|
43
|
+
# ---------------------------------------------------------------------------
|
|
44
|
+
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
45
|
+
sys.path.insert(0, str(_SCRIPT_DIR))
|
|
46
|
+
_TOKEN_OPTIMIZER_SCRIPT_DIR = _SCRIPT_DIR.parent.parent / "token-optimizer" / "scripts"
|
|
47
|
+
if _TOKEN_OPTIMIZER_SCRIPT_DIR.exists():
|
|
48
|
+
sys.path.insert(0, str(_TOKEN_OPTIMIZER_SCRIPT_DIR))
|
|
49
|
+
from shared import ( # noqa: E402 — must follow sys.path.insert above
|
|
50
|
+
HOME,
|
|
51
|
+
CLAUDE_DIR,
|
|
52
|
+
normalize_model_name,
|
|
53
|
+
iter_jsonl,
|
|
54
|
+
parse_timestamp,
|
|
55
|
+
find_claude_jsonl_files,
|
|
56
|
+
find_subagent_jsonl_files,
|
|
57
|
+
clean_project_name,
|
|
58
|
+
init_sqlite_db,
|
|
59
|
+
estimate_tokens_from_file,
|
|
60
|
+
estimate_tokens_from_text,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
try: # noqa: E402
|
|
64
|
+
import codex_session # type: ignore
|
|
65
|
+
from runtime_env import codex_home, detect_runtime, runtime_home # type: ignore
|
|
66
|
+
except Exception: # pragma: no cover - optional Codex adapter dependency
|
|
67
|
+
codex_session = None
|
|
68
|
+
|
|
69
|
+
def detect_runtime() -> str:
|
|
70
|
+
return "claude"
|
|
71
|
+
|
|
72
|
+
def runtime_home() -> Path:
|
|
73
|
+
return CLAUDE_DIR
|
|
74
|
+
|
|
75
|
+
def codex_home() -> Path:
|
|
76
|
+
return HOME / ".codex"
|
|
77
|
+
|
|
78
|
+
try: # noqa: E402
|
|
79
|
+
import tomllib
|
|
80
|
+
except ModuleNotFoundError: # pragma: no cover - Python <3.11
|
|
81
|
+
tomllib = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# Measurements show wrapper overhead is negligible (synced with measure.py)
|
|
85
|
+
SKILL_WRAPPER_OVERHEAD = 0
|
|
86
|
+
|
|
87
|
+
def _estimate_skill_frontmatter_tokens(skill_md: Path) -> int:
|
|
88
|
+
"""Estimate tokens of a skill's YAML frontmatter only.
|
|
89
|
+
|
|
90
|
+
Claude Code loads only each skill's frontmatter (name + description)
|
|
91
|
+
into the session at startup. The SKILL.md body is loaded on demand
|
|
92
|
+
when the user invokes the skill via the Skill tool. Measuring the
|
|
93
|
+
full file over-counts overhead by ~10-20x.
|
|
94
|
+
|
|
95
|
+
Adds SKILL_WRAPPER_OVERHEAD (35 tokens) for the boilerplate Claude
|
|
96
|
+
wraps around each skill entry, and enforces a minimum floor of 50
|
|
97
|
+
tokens (matching measure.py's estimate_tokens_from_frontmatter).
|
|
98
|
+
|
|
99
|
+
Falls back to 100 tokens (the documented average) if frontmatter
|
|
100
|
+
cannot be parsed.
|
|
101
|
+
"""
|
|
102
|
+
try:
|
|
103
|
+
text = skill_md.read_text(encoding="utf-8", errors="replace")
|
|
104
|
+
except (OSError, PermissionError):
|
|
105
|
+
return 100
|
|
106
|
+
# Strip UTF-8 BOM that Windows editors may insert
|
|
107
|
+
text = text.lstrip('\ufeff')
|
|
108
|
+
if not text.startswith("---"):
|
|
109
|
+
return 100
|
|
110
|
+
# Look for the closing --- after the opening one
|
|
111
|
+
end_idx = text.find("\n---", 4)
|
|
112
|
+
if end_idx == -1:
|
|
113
|
+
return 100
|
|
114
|
+
frontmatter = text[: end_idx + 4]
|
|
115
|
+
return max(estimate_tokens_from_text(frontmatter) + SKILL_WRAPPER_OVERHEAD, 50)
|
|
116
|
+
|
|
117
|
+
# ---------------------------------------------------------------------------
|
|
118
|
+
# Constants
|
|
119
|
+
# ---------------------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
FLEET_DB_DIR = runtime_home() / "_backups" / "token-optimizer"
|
|
122
|
+
FLEET_DB = FLEET_DB_DIR / "fleet.db"
|
|
123
|
+
FLEET_DASHBOARD_PATH = FLEET_DB_DIR / "fleet-dashboard.html"
|
|
124
|
+
|
|
125
|
+
SCHEMA_VERSION = "1"
|
|
126
|
+
|
|
127
|
+
# ---------------------------------------------------------------------------
|
|
128
|
+
# Pricing (USD per token)
|
|
129
|
+
# ---------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
DEFAULT_PRICING: dict[str, dict[str, float]] = {
|
|
132
|
+
# Claude (Fable 5 / Opus 4.8 / Sonnet 4.6 / Haiku 4.5 pricing, verified 2026-05-30)
|
|
133
|
+
# cache_write = 5-minute TTL (1.25x input); cache_write_1h = 1-hour TTL (2x input).
|
|
134
|
+
"fable": {"input": 10.0/1e6, "output": 50.0/1e6, "cache_read": 1.0/1e6, "cache_write": 12.5/1e6, "cache_write_1h": 20.0/1e6},
|
|
135
|
+
"opus": {"input": 5.0/1e6, "output": 25.0/1e6, "cache_read": 0.5/1e6, "cache_write": 6.25/1e6, "cache_write_1h": 10.0/1e6},
|
|
136
|
+
# Generations priced off-family (verified 2026-09-24): Fable/Mythos 5.1 cache reads are
|
|
137
|
+
# 0.025x input; Opus 5.5 is $4/$20 with 0.05x reads. See _pricing_key().
|
|
138
|
+
"fable-5-1": {"input": 10.0/1e6, "output": 50.0/1e6, "cache_read": 0.25/1e6, "cache_write": 12.5/1e6, "cache_write_1h": 20.0/1e6},
|
|
139
|
+
"opus-5-5": {"input": 4.0/1e6, "output": 20.0/1e6, "cache_read": 0.2/1e6, "cache_write": 5.0/1e6, "cache_write_1h": 8.0/1e6},
|
|
140
|
+
"sonnet": {"input": 3.0/1e6, "output": 15.0/1e6, "cache_read": 0.3/1e6, "cache_write": 3.75/1e6, "cache_write_1h": 6.0/1e6},
|
|
141
|
+
"haiku": {"input": 1.0/1e6, "output": 5.0/1e6, "cache_read": 0.1/1e6, "cache_write": 1.25/1e6, "cache_write_1h": 2.0/1e6},
|
|
142
|
+
"gpt-5-codex": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
|
|
143
|
+
"gpt-5.1-codex": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
|
|
144
|
+
"gpt-5.1-codex-mini": {"input": 0.25/1e6, "output": 2.0/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
|
|
145
|
+
"gpt-5.1": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
|
|
146
|
+
"gpt-5.2": {"input": 1.75/1e6, "output": 14.0/1e6, "cache_read": 0.175/1e6, "cache_write": 0},
|
|
147
|
+
"gpt-5.2-codex": {"input": 1.75/1e6, "output": 14.0/1e6, "cache_read": 0.175/1e6, "cache_write": 0},
|
|
148
|
+
"gpt-5.3-codex": {"input": 1.75/1e6, "output": 14.0/1e6, "cache_read": 0.175/1e6, "cache_write": 0},
|
|
149
|
+
"gpt-5": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
|
|
150
|
+
"gpt-5-mini": {"input": 0.25/1e6, "output": 2.0/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
|
|
151
|
+
"gpt-5-nano": {"input": 0.05/1e6, "output": 0.40/1e6, "cache_read": 0.005/1e6, "cache_write": 0},
|
|
152
|
+
"gpt-5.4": {"input": 2.5/1e6, "output": 15.0/1e6, "cache_read": 0.25/1e6, "cache_write": 0},
|
|
153
|
+
"gpt-5.4-mini": {"input": 0.75/1e6, "output": 4.5/1e6, "cache_read": 0.075/1e6, "cache_write": 0},
|
|
154
|
+
"gpt-5.4-nano": {"input": 0.20/1e6, "output": 1.25/1e6, "cache_read": 0.02/1e6, "cache_write": 0},
|
|
155
|
+
"gpt-5.5": {"input": 5.0/1e6, "output": 30.0/1e6, "cache_read": 0.50/1e6, "cache_write": 0},
|
|
156
|
+
"gpt-5.5-pro": {"input": 30.0/1e6, "output": 180.0/1e6, "cache_read": 30.0/1e6, "cache_write": 0},
|
|
157
|
+
"gpt-6-astra": {"input": 10.0/1e6, "output": 50.0/1e6, "cache_read": 1.0/1e6, "cache_write": 12.50/1e6},
|
|
158
|
+
"gpt-5.6-sol": {"input": 5.0/1e6, "output": 30.0/1e6, "cache_read": 0.50/1e6, "cache_write": 6.25/1e6},
|
|
159
|
+
"gpt-5.6-terra": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 2.50/1e6},
|
|
160
|
+
"gpt-5.6-luna": {"input": 0.20/1e6, "output": 1.20/1e6, "cache_read": 0.02/1e6, "cache_write": 0.25/1e6},
|
|
161
|
+
"gpt-4.1": {"input": 2.0/1e6, "output": 8.0/1e6, "cache_read": 0.50/1e6, "cache_write": 0},
|
|
162
|
+
"gpt-4.1-mini": {"input": 0.40/1e6, "output": 1.60/1e6, "cache_read": 0.10/1e6, "cache_write": 0},
|
|
163
|
+
"gpt-4.1-nano": {"input": 0.10/1e6, "output": 0.40/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
|
|
164
|
+
"gpt-4o": {"input": 2.5/1e6, "output": 10.0/1e6, "cache_read": 1.25/1e6, "cache_write": 0},
|
|
165
|
+
"gpt-4o-mini": {"input": 0.15/1e6, "output": 0.6/1e6, "cache_read": 0.075/1e6, "cache_write": 0},
|
|
166
|
+
"o3-pro": {"input": 20.0/1e6, "output": 80.0/1e6, "cache_read": 5.0/1e6, "cache_write": 0},
|
|
167
|
+
"o3-mini": {"input": 1.10/1e6, "output": 4.40/1e6, "cache_read": 0.55/1e6, "cache_write": 0},
|
|
168
|
+
"o3": {"input": 2.0/1e6, "output": 8.0/1e6, "cache_read": 0.50/1e6, "cache_write": 0},
|
|
169
|
+
"o4-mini": {"input": 1.10/1e6, "output": 4.40/1e6, "cache_read": 0.275/1e6, "cache_write": 0},
|
|
170
|
+
"gemini-3.5-flash": {"input": 1.50/1e6, "output": 9.0/1e6, "cache_read": 0.15/1e6, "cache_write": 0},
|
|
171
|
+
"gemini-3.1-pro-preview": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 0},
|
|
172
|
+
"gemini-3.1-flash-lite": {"input": 0.25/1e6, "output": 1.50/1e6, "cache_read": 0.025/1e6, "cache_write": 0},
|
|
173
|
+
"gemini-3.1-pro": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 0},
|
|
174
|
+
"gemini-3-pro": {"input": 2.0/1e6, "output": 12.0/1e6, "cache_read": 0.20/1e6, "cache_write": 0},
|
|
175
|
+
"gemini-3-flash": {"input": 0.50/1e6, "output": 3.0/1e6, "cache_read": 0.05/1e6, "cache_write": 0},
|
|
176
|
+
"gemini-2.5-pro": {"input": 1.25/1e6, "output": 10.0/1e6, "cache_read": 0.125/1e6, "cache_write": 0},
|
|
177
|
+
"gemini-2.5-flash": {"input": 0.30/1e6, "output": 2.50/1e6, "cache_read": 0.03/1e6, "cache_write": 0},
|
|
178
|
+
"gemini-2.5-flash-lite": {"input": 0.10/1e6, "output": 0.40/1e6, "cache_read": 0.01/1e6, "cache_write": 0},
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
# Sonnet 5 introductory pricing ($2/$10; cache_read 0.2, cache_write 2.5[5m]/4.0[1h]) is in
|
|
182
|
+
# effect through 2026-08-31; the STANDARD rate ($3/$15) resumes 2026-09-01. DEFAULT_PRICING
|
|
183
|
+
# holds the canonical standard card; while the window is open we swap the introductory card in so
|
|
184
|
+
# fleet cost/waste dollars stay accurate today AND flip back automatically at UTC midnight (in
|
|
185
|
+
# lockstep with measure.py + the TS ports). Production reads the wall clock;
|
|
186
|
+
# TOKEN_OPTIMIZER_PRICING_AS_OF (YYYY-MM-DD) pins it for tests. The single "sonnet" bucket cannot
|
|
187
|
+
# isolate Sonnet 5, so Sonnet 4.6 is repriced too (accepted 2026-07-10). Mirrors measure.py.
|
|
188
|
+
_SONNET_STANDARD_RATES = {"input": 3.0/1e6, "output": 15.0/1e6, "cache_read": 0.3/1e6, "cache_write": 3.75/1e6, "cache_write_1h": 6.0/1e6}
|
|
189
|
+
_SONNET_INTRO_RATES = {"input": 2.0/1e6, "output": 10.0/1e6, "cache_read": 0.2/1e6, "cache_write": 2.5/1e6, "cache_write_1h": 4.0/1e6}
|
|
190
|
+
_SONNET_INTRO_PRICING_UNTIL = datetime(2026, 9, 1, tzinfo=timezone.utc)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _apply_sonnet_intro_pricing(as_of=None):
|
|
194
|
+
"""Swap the sonnet card to the introductory rate while it is in effect (idempotent). A naive
|
|
195
|
+
`as_of`/env date is treated as UTC. Returns True when introductory pricing is active."""
|
|
196
|
+
override = os.environ.get("TOKEN_OPTIMIZER_PRICING_AS_OF")
|
|
197
|
+
if as_of is None and override:
|
|
198
|
+
try:
|
|
199
|
+
as_of = datetime.strptime(override, "%Y-%m-%d")
|
|
200
|
+
except ValueError:
|
|
201
|
+
as_of = None
|
|
202
|
+
d = as_of or datetime.now(timezone.utc)
|
|
203
|
+
if d.tzinfo is None:
|
|
204
|
+
d = d.replace(tzinfo=timezone.utc)
|
|
205
|
+
intro = True # date gate retired; $2/$10 is the standard rate
|
|
206
|
+
DEFAULT_PRICING["sonnet"] = dict(_SONNET_INTRO_RATES if intro else _SONNET_STANDARD_RATES)
|
|
207
|
+
return intro
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
_apply_sonnet_intro_pricing()
|
|
211
|
+
|
|
212
|
+
# gpt-5.6-sol promotional pricing (date-gated). OpenAI documents the $4/$20 rate
|
|
213
|
+
# as "available at least through November 21, 2026." DEFAULT_PRICING holds the
|
|
214
|
+
# STANDARD card ($5/$30); while the promo window is open we swap the promo card
|
|
215
|
+
# in so fleet cost/waste dollars stay accurate today AND flip back automatically
|
|
216
|
+
# after 2026-11-21. Mirrors measure.py _apply_gpt56_sol_promo_pricing.
|
|
217
|
+
_GPT56_SOL_STANDARD_RATES = {"input": 5.0/1e6, "output": 30.0/1e6, "cache_read": 0.50/1e6, "cache_write": 6.25/1e6}
|
|
218
|
+
_GPT56_SOL_PROMO_RATES = {"input": 4.0/1e6, "output": 20.0/1e6, "cache_read": 0.40/1e6, "cache_write": 5.0/1e6}
|
|
219
|
+
_GPT56_SOL_PROMO_UNTIL = datetime(2026, 11, 21, tzinfo=timezone.utc)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _apply_gpt56_sol_promo_pricing(as_of=None):
|
|
223
|
+
"""Swap the gpt-5.6-sol card to the promotional rate while it is in effect (idempotent)."""
|
|
224
|
+
override = os.environ.get("TOKEN_OPTIMIZER_PRICING_AS_OF")
|
|
225
|
+
if as_of is None and override:
|
|
226
|
+
try:
|
|
227
|
+
as_of = datetime.strptime(override, "%Y-%m-%d")
|
|
228
|
+
except ValueError:
|
|
229
|
+
as_of = None
|
|
230
|
+
d = as_of or datetime.now(timezone.utc)
|
|
231
|
+
if d.tzinfo is None:
|
|
232
|
+
d = d.replace(tzinfo=timezone.utc)
|
|
233
|
+
if d < _GPT56_SOL_PROMO_UNTIL:
|
|
234
|
+
DEFAULT_PRICING["gpt-5.6-sol"] = dict(_GPT56_SOL_PROMO_RATES)
|
|
235
|
+
return True
|
|
236
|
+
DEFAULT_PRICING["gpt-5.6-sol"] = dict(_GPT56_SOL_STANDARD_RATES)
|
|
237
|
+
return False
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
_apply_gpt56_sol_promo_pricing()
|
|
241
|
+
|
|
242
|
+
_pricing_override: dict | None = None
|
|
243
|
+
# Models the user priced themselves in pricing.json: their flat card wins over
|
|
244
|
+
# the bundled over-100K tier (calculate_cost per_request).
|
|
245
|
+
_pricing_override_keys: set[str] = set()
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _load_pricing() -> dict[str, dict[str, float]]:
|
|
249
|
+
"""Load pricing with optional user override from pricing.json."""
|
|
250
|
+
global _pricing_override
|
|
251
|
+
if _pricing_override is not None:
|
|
252
|
+
return _pricing_override
|
|
253
|
+
|
|
254
|
+
pricing = dict(DEFAULT_PRICING)
|
|
255
|
+
pricing.update(_bundled_prices())
|
|
256
|
+
_pricing_override_keys.clear()
|
|
257
|
+
override_path = FLEET_DB_DIR / "pricing.json"
|
|
258
|
+
if override_path.exists():
|
|
259
|
+
try:
|
|
260
|
+
with open(override_path, "r", encoding="utf-8") as f:
|
|
261
|
+
user_pricing = json.load(f)
|
|
262
|
+
if not isinstance(user_pricing, dict):
|
|
263
|
+
user_pricing = {}
|
|
264
|
+
for model, rates in user_pricing.items():
|
|
265
|
+
if not isinstance(rates, dict):
|
|
266
|
+
continue
|
|
267
|
+
# Normalize the user's key the same way lookups are normalized, so
|
|
268
|
+
# adding "MiniMax-M3" (the name the unpriced warning shows) actually
|
|
269
|
+
# prices the run keyed as "minimax-m3".
|
|
270
|
+
model = _override_key(str(model))
|
|
271
|
+
merged = {**pricing.get(model, {}), **rates}
|
|
272
|
+
if "cache_write_1h" not in rates and ("input" in rates or "cache_write" in rates):
|
|
273
|
+
if merged.get("input"):
|
|
274
|
+
merged["cache_write_1h"] = merged["input"] * 2
|
|
275
|
+
elif merged.get("cache_write"):
|
|
276
|
+
merged["cache_write_1h"] = merged["cache_write"] * 1.6
|
|
277
|
+
pricing[model] = merged
|
|
278
|
+
_pricing_override_keys.add(model)
|
|
279
|
+
except (json.JSONDecodeError, PermissionError, OSError, TypeError, AttributeError):
|
|
280
|
+
pass
|
|
281
|
+
_pricing_override = pricing
|
|
282
|
+
return pricing
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
_BUNDLED_PRICES_PATH = Path(__file__).resolve().parent.parent.parent / "token-optimizer" / "pricing" / "prices.json"
|
|
286
|
+
_PRICE_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
|
|
287
|
+
_CLAUDE_GENERATION_RE = re.compile(
|
|
288
|
+
r"(fable|mythos|opus|sonnet|haiku)[-._]?(\d+)(?:[-._](\d{1,2}))?(?![0-9])")
|
|
289
|
+
# Claude 3-era ids put the version before the family ("claude-3-5-sonnet-20241022").
|
|
290
|
+
_CLAUDE_LEGACY_ID_RE = re.compile(r"claude-(\d)(?:[-.](\d))?-(opus|sonnet|haiku)(?![a-z])")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _bundled_prices() -> dict[str, dict[str, float]]:
|
|
294
|
+
"""Per-token cards from the auto-refreshed pricing/prices.json (read-only).
|
|
295
|
+
|
|
296
|
+
Same file measure.py reads, so fleet costs never drift from the dashboard.
|
|
297
|
+
Claude generation cards are hyphenated here ("opus_5_5" -> "opus-5-5").
|
|
298
|
+
Returns {} when the file is missing, oversized or malformed.
|
|
299
|
+
"""
|
|
300
|
+
try:
|
|
301
|
+
if _BUNDLED_PRICES_PATH.stat().st_size > 2 * 1024 * 1024:
|
|
302
|
+
return {}
|
|
303
|
+
doc = json.loads(_BUNDLED_PRICES_PATH.read_text(encoding="utf-8"))
|
|
304
|
+
except (OSError, ValueError):
|
|
305
|
+
return {}
|
|
306
|
+
if not isinstance(doc, dict) or doc.get("schema") != 1:
|
|
307
|
+
return {}
|
|
308
|
+
out: dict[str, dict[str, float]] = {}
|
|
309
|
+
for section in ("anthropic", "openai", "gemini"):
|
|
310
|
+
cards = doc.get(section)
|
|
311
|
+
if not isinstance(cards, dict):
|
|
312
|
+
continue
|
|
313
|
+
for key, card in cards.items():
|
|
314
|
+
if not isinstance(key, str) or not _PRICE_KEY_RE.match(key) or not isinstance(card, dict):
|
|
315
|
+
continue
|
|
316
|
+
rates = {}
|
|
317
|
+
for field in ("input", "output", "cache_read", "cache_write", "cache_write_1h"):
|
|
318
|
+
v = card.get(field)
|
|
319
|
+
if v is None:
|
|
320
|
+
continue
|
|
321
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0 <= v <= 1000:
|
|
322
|
+
rates = {}
|
|
323
|
+
break
|
|
324
|
+
rates[field] = float(v) / 1e6
|
|
325
|
+
if "input" not in rates or "output" not in rates:
|
|
326
|
+
continue
|
|
327
|
+
rates.setdefault("cache_read", rates["input"] if section != "anthropic" else rates["input"] * 0.1)
|
|
328
|
+
rates.setdefault("cache_write", rates["input"] * 1.25 if section == "anthropic" else 0.0)
|
|
329
|
+
if section == "anthropic":
|
|
330
|
+
rates.setdefault("cache_write_1h", rates["input"] * 2)
|
|
331
|
+
out[key.replace("_", "-") if section == "anthropic" else key] = rates
|
|
332
|
+
return out
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# Claude Haiku 5.5 is priced by prompt length: a single request whose full prompt
|
|
336
|
+
# (input + cache reads + cache writes) is over 100K tokens pays 5x on every rate.
|
|
337
|
+
# Same threshold and cards as measure.py (prices.json "anthropic_long_context").
|
|
338
|
+
ANTHROPIC_LONG_CONTEXT_INPUT_THRESHOLD = 100_000
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _bundled_long_context_prices() -> dict[str, dict[str, float]]:
|
|
342
|
+
"""Per-token over-100K Anthropic cards from prices.json, keyed like _bundled_prices."""
|
|
343
|
+
try:
|
|
344
|
+
if _BUNDLED_PRICES_PATH.stat().st_size > 2 * 1024 * 1024:
|
|
345
|
+
return {}
|
|
346
|
+
doc = json.loads(_BUNDLED_PRICES_PATH.read_text(encoding="utf-8"))
|
|
347
|
+
except (OSError, ValueError):
|
|
348
|
+
return {}
|
|
349
|
+
if not isinstance(doc, dict) or doc.get("schema") != 1:
|
|
350
|
+
return {}
|
|
351
|
+
cards = doc.get("anthropic_long_context")
|
|
352
|
+
if not isinstance(cards, dict):
|
|
353
|
+
return {}
|
|
354
|
+
out: dict[str, dict[str, float]] = {}
|
|
355
|
+
for key, card in cards.items():
|
|
356
|
+
if not isinstance(key, str) or not _PRICE_KEY_RE.match(key) or not isinstance(card, dict):
|
|
357
|
+
continue
|
|
358
|
+
rates = {}
|
|
359
|
+
for field in ("input", "output", "cache_read", "cache_write", "cache_write_1h"):
|
|
360
|
+
v = card.get(field)
|
|
361
|
+
if v is None:
|
|
362
|
+
continue
|
|
363
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0 <= v <= 1000:
|
|
364
|
+
rates = {}
|
|
365
|
+
break
|
|
366
|
+
rates[field] = float(v) / 1e6
|
|
367
|
+
if "input" in rates and "output" in rates:
|
|
368
|
+
rates.setdefault("cache_read", rates["input"] * 0.1)
|
|
369
|
+
rates.setdefault("cache_write", rates["input"] * 1.25)
|
|
370
|
+
rates.setdefault("cache_write_1h", rates["input"] * 2)
|
|
371
|
+
out[key.replace("_", "-")] = rates
|
|
372
|
+
return out
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _claude_generation_key(model_id: str) -> str | None:
|
|
376
|
+
"""'claude-opus-5-5' / 'opus-5-5' -> 'opus-5-5'; None when no generation."""
|
|
377
|
+
m = str(model_id or "").lower()
|
|
378
|
+
legacy = _CLAUDE_LEGACY_ID_RE.search(m)
|
|
379
|
+
if legacy:
|
|
380
|
+
major, minor, family = legacy.groups()
|
|
381
|
+
return f"{family}-{major}-{minor}" if minor else f"{family}-{major}"
|
|
382
|
+
g = _CLAUDE_GENERATION_RE.search(m)
|
|
383
|
+
if not g:
|
|
384
|
+
return None
|
|
385
|
+
family, major, minor = g.groups()
|
|
386
|
+
return f"{family}-{major}-{minor}" if minor else f"{family}-{major}"
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _override_key(model_id: str) -> str:
|
|
390
|
+
"""Key a user override in pricing.json lands on.
|
|
391
|
+
|
|
392
|
+
Uses the same generation granularity as lookups, so {"opus-5-5": ...}
|
|
393
|
+
reprices Opus 5.5 only, instead of being folded into the "opus" family card
|
|
394
|
+
and silently repricing every other Opus generation.
|
|
395
|
+
"""
|
|
396
|
+
return _claude_generation_key(model_id) or normalize_model_name(model_id) or model_id.lower()
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
# Same families the TS engines prefix-match: any GPT, any o-series, any Gemini.
|
|
400
|
+
_PREFIX_PRICED_RE = re.compile(r"^(gpt-|o\d|gemini-)")
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _pricing_key(model_id: str) -> str:
|
|
404
|
+
"""Rate-card key for a raw model id, finer than the family label.
|
|
405
|
+
|
|
406
|
+
Claude generations are priced differently (Opus 5.5 $4/$20, Opus 4.1
|
|
407
|
+
$15/$75, Fable 5.1 cache reads $0.25), so try "opus-5-5", then "opus-5",
|
|
408
|
+
then the family. Other providers match the longest priced id prefix, so a
|
|
409
|
+
dated snapshot prices as its base model. Mirrors measure.py.
|
|
410
|
+
"""
|
|
411
|
+
pricing = _load_pricing()
|
|
412
|
+
m = str(model_id or "").lower()
|
|
413
|
+
legacy = _CLAUDE_LEGACY_ID_RE.search(m)
|
|
414
|
+
if legacy:
|
|
415
|
+
major, minor, family = legacy.groups()
|
|
416
|
+
keys = [f"{family}-{major}-{minor}", f"{family}-{major}"] if minor else [f"{family}-{major}"]
|
|
417
|
+
if family == "sonnet":
|
|
418
|
+
keys.append("sonnet-legacy")
|
|
419
|
+
for key in keys:
|
|
420
|
+
if key in pricing:
|
|
421
|
+
return key
|
|
422
|
+
return normalize_model_name(model_id) or model_id
|
|
423
|
+
g = _CLAUDE_GENERATION_RE.search(m)
|
|
424
|
+
if g:
|
|
425
|
+
family, major, minor = g.groups()
|
|
426
|
+
for fam in ((family, "fable") if family == "mythos" else (family,)):
|
|
427
|
+
for key in ((f"{fam}-{major}-{minor}", f"{fam}-{major}") if minor else (f"{fam}-{major}",)):
|
|
428
|
+
if key in pricing:
|
|
429
|
+
return key
|
|
430
|
+
if family == "mythos":
|
|
431
|
+
return "fable"
|
|
432
|
+
else:
|
|
433
|
+
bare = m.rsplit("/", 1)[-1].rsplit(":", 1)[-1]
|
|
434
|
+
for key in sorted(pricing, key=len, reverse=True):
|
|
435
|
+
if _PREFIX_PRICED_RE.match(key) and (bare == key or bare.startswith(key + "-")):
|
|
436
|
+
return key
|
|
437
|
+
return normalize_model_name(model_id) or model_id
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def calculate_cost(tokens: "TokenBreakdown", model: str,
|
|
441
|
+
cache_write_1h: int = 0, cache_write_5m: int = 0,
|
|
442
|
+
per_request: bool = False) -> float:
|
|
443
|
+
"""Calculate USD cost for a token breakdown at given model rates.
|
|
444
|
+
|
|
445
|
+
``per_request=True`` says ``tokens`` is ONE API request: a model with an
|
|
446
|
+
over-100K card (Claude Haiku 5.5) then pays it when that request's full
|
|
447
|
+
prompt (input + cache reads + cache writes) exceeds the threshold. Totals
|
|
448
|
+
over many requests must leave it False, or every long session would be
|
|
449
|
+
repriced as if it were a single huge prompt.
|
|
450
|
+
|
|
451
|
+
For Claude models, pass cache_write_1h / cache_write_5m to apply the correct
|
|
452
|
+
per-TTL-tier rate (1h = 2x input; 5m = 1.25x input). When the split is
|
|
453
|
+
unavailable (both 0) the full tokens.cache_write uses the 5m rate.
|
|
454
|
+
"""
|
|
455
|
+
pricing = _load_pricing()
|
|
456
|
+
rates = pricing.get(model)
|
|
457
|
+
if not rates:
|
|
458
|
+
return 0.0
|
|
459
|
+
if (per_request and model not in _pricing_override_keys
|
|
460
|
+
and tokens.input + tokens.cache_read + tokens.cache_write
|
|
461
|
+
> ANTHROPIC_LONG_CONTEXT_INPUT_THRESHOLD):
|
|
462
|
+
rates = _bundled_long_context_prices().get(model, rates)
|
|
463
|
+
cost = 0.0
|
|
464
|
+
cost += tokens.input * rates.get("input", 0)
|
|
465
|
+
cost += tokens.output * rates.get("output", 0)
|
|
466
|
+
cost += tokens.cache_read * rates.get("cache_read", 0)
|
|
467
|
+
# Split cache-write cost by TTL tier when data is available.
|
|
468
|
+
if cache_write_1h or cache_write_5m:
|
|
469
|
+
unsplit = max(0, tokens.cache_write - cache_write_1h - cache_write_5m)
|
|
470
|
+
cost += cache_write_1h * rates.get("cache_write_1h", rates.get("cache_write", 0))
|
|
471
|
+
cost += (cache_write_5m + unsplit) * rates.get("cache_write", 0)
|
|
472
|
+
else:
|
|
473
|
+
cost += tokens.cache_write * rates.get("cache_write", 0)
|
|
474
|
+
return cost
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def model_is_priced(model: str) -> bool:
|
|
478
|
+
"""True when we have a pricing row for ``model``.
|
|
479
|
+
|
|
480
|
+
``calculate_cost`` returns 0.0 both for genuinely-free usage and for models
|
|
481
|
+
with no pricing row (self-hosted, gateway aliases like ``MiniMax-M3``,
|
|
482
|
+
OpenRouter names). Callers use this to tell "$0 because free" apart from
|
|
483
|
+
"$0 because unpriced" and surface the gap instead of reporting fake $0.
|
|
484
|
+
Model is normalized (lowercased) before lookup so it matches pricing keys.
|
|
485
|
+
"""
|
|
486
|
+
return _load_pricing().get(model) is not None
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _recorded_cost(*values) -> float | None:
|
|
490
|
+
"""Return the first value that is a REAL recorded cost, else None.
|
|
491
|
+
|
|
492
|
+
A source DB (e.g. Hermes) records its own cost for gateway models our
|
|
493
|
+
pricing table can't price. "Recorded" means present, numeric, finite, and
|
|
494
|
+
>= 0 — a recorded $0 is authoritative (free/comped), NOT an excuse to
|
|
495
|
+
re-price it. Empty strings, None, NaN, inf, negatives, and garbage
|
|
496
|
+
all fall through so the caller can price or flag instead of fabricating or
|
|
497
|
+
crashing on a bad cell.
|
|
498
|
+
"""
|
|
499
|
+
for v in values:
|
|
500
|
+
if v is None or v == "":
|
|
501
|
+
continue
|
|
502
|
+
try:
|
|
503
|
+
f = float(v)
|
|
504
|
+
except (TypeError, ValueError):
|
|
505
|
+
continue
|
|
506
|
+
if f >= 0 and math.isfinite(f):
|
|
507
|
+
return f
|
|
508
|
+
return None
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def unpriced_summary(runs) -> dict[str, int]:
|
|
512
|
+
"""{model: session_count} for runs whose $0 cost is unknown, not free.
|
|
513
|
+
|
|
514
|
+
A run counts when it has real token usage but $0 cost on a model with no
|
|
515
|
+
pricing row — i.e. the $0 is a gap, not a fact. Shared by ``cmd_scan`` and
|
|
516
|
+
``cmd_audit`` so both surfaces flag the same thing the same way.
|
|
517
|
+
|
|
518
|
+
Known limit: a run whose source DB *recorded* a genuine $0 (comped/free) on an
|
|
519
|
+
unpriced model is over-flagged here — we can't yet tell a recorded $0 from a
|
|
520
|
+
computed-because-unpriced $0 without a cost-source column. The over-warn is
|
|
521
|
+
safe (it points the user at pricing they can add or ignore), not a wrong total.
|
|
522
|
+
"""
|
|
523
|
+
out: dict[str, int] = {}
|
|
524
|
+
for r in runs:
|
|
525
|
+
# Require a real model name: an empty/blank model can't be priced OR named
|
|
526
|
+
# in the warning, and the dashboard SQL excludes it (model != '') — skip it
|
|
527
|
+
# here too so all three surfaces agree.
|
|
528
|
+
if not r.model:
|
|
529
|
+
continue
|
|
530
|
+
if r.cost_usd == 0.0 and r.tokens.total > 0 and not model_is_priced(r.model):
|
|
531
|
+
out[r.model] = out.get(r.model, 0) + 1
|
|
532
|
+
return out
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
# ---------------------------------------------------------------------------
|
|
536
|
+
# Data Model
|
|
537
|
+
# ---------------------------------------------------------------------------
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _with_measure_cli(text: str) -> str:
|
|
541
|
+
"""Swap a bare ``python3 measure.py`` in a fix snippet for the resolved script.
|
|
542
|
+
|
|
543
|
+
The sibling token-optimizer skill holds measure.py; when it is not there
|
|
544
|
+
(a standalone fleet-auditor install) the bare form is left as written.
|
|
545
|
+
"""
|
|
546
|
+
script = Path(__file__).resolve().parents[2] / "token-optimizer" / "scripts" / "measure.py"
|
|
547
|
+
if not script.is_file():
|
|
548
|
+
return text
|
|
549
|
+
try:
|
|
550
|
+
from refetch_fingerprint import hint_python, shell_path, _windows_hints
|
|
551
|
+
quoted, python = shell_path(str(script)), hint_python()
|
|
552
|
+
windows = _windows_hints()
|
|
553
|
+
except ImportError:
|
|
554
|
+
quoted, python, windows = shlex.quote(str(script)), "python3", False
|
|
555
|
+
# `VAR=x cmd` is Bash only: on Windows the runtime is a leading --runtime flag.
|
|
556
|
+
text = re.sub(
|
|
557
|
+
r"TOKEN_OPTIMIZER_RUNTIME=(\w+) python3 measure\.py",
|
|
558
|
+
(lambda m: f"{python} {quoted} --runtime {m.group(1)}") if windows
|
|
559
|
+
else (lambda m: f"TOKEN_OPTIMIZER_RUNTIME={m.group(1)} {python} {quoted}"),
|
|
560
|
+
text)
|
|
561
|
+
return text.replace("python3 measure.py", f"{python} {quoted}")
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
@dataclass
|
|
565
|
+
class TokenBreakdown:
|
|
566
|
+
input: int = 0
|
|
567
|
+
output: int = 0
|
|
568
|
+
cache_read: int = 0
|
|
569
|
+
cache_write: int = 0
|
|
570
|
+
|
|
571
|
+
@property
|
|
572
|
+
def total(self) -> int:
|
|
573
|
+
return self.input + self.output + self.cache_read + self.cache_write
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
@dataclass
|
|
577
|
+
class AgentRun:
|
|
578
|
+
system: str # "claude", "codex", "openclaw", "hermes", "opencode", "nanoclaw", "ironclaw"
|
|
579
|
+
session_id: str = ""
|
|
580
|
+
agent_name: str = ""
|
|
581
|
+
project: str = ""
|
|
582
|
+
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
|
583
|
+
duration_seconds: float = 0.0
|
|
584
|
+
tokens: TokenBreakdown = field(default_factory=TokenBreakdown)
|
|
585
|
+
cost_usd: float = 0.0
|
|
586
|
+
model: str = "" # Normalized: "opus", "sonnet", "haiku", etc.
|
|
587
|
+
context_window_size: int = 200_000
|
|
588
|
+
run_type: str = "manual" # "heartbeat", "task", "cron", "manual", "delegate"
|
|
589
|
+
outcome: str = "success" # "success", "failure", "empty", "loop", "abandoned"
|
|
590
|
+
message_count: int = 0
|
|
591
|
+
tools_used: list = field(default_factory=list)
|
|
592
|
+
source_path: str = ""
|
|
593
|
+
error_message: str | None = None
|
|
594
|
+
exit_code: int | None = None
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
@dataclass
|
|
598
|
+
class WasteFinding:
|
|
599
|
+
system: str
|
|
600
|
+
agent_name: str = ""
|
|
601
|
+
waste_type: str = ""
|
|
602
|
+
tier: int = 1
|
|
603
|
+
severity: str = "medium" # "low", "medium", "high", "critical"
|
|
604
|
+
confidence: float = 0.8
|
|
605
|
+
description: str = ""
|
|
606
|
+
monthly_waste_usd: float = 0.0
|
|
607
|
+
monthly_waste_tokens: int = 0
|
|
608
|
+
recommendation: str = ""
|
|
609
|
+
fix_snippet: str = ""
|
|
610
|
+
evidence: dict = field(default_factory=dict)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
# ---------------------------------------------------------------------------
|
|
614
|
+
# SQLite Schema
|
|
615
|
+
# ---------------------------------------------------------------------------
|
|
616
|
+
|
|
617
|
+
_FLEET_SCHEMA = """
|
|
618
|
+
CREATE TABLE IF NOT EXISTS fleet_runs (
|
|
619
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
620
|
+
source_path TEXT NOT NULL,
|
|
621
|
+
system TEXT NOT NULL,
|
|
622
|
+
session_id TEXT,
|
|
623
|
+
date TEXT NOT NULL,
|
|
624
|
+
agent_name TEXT,
|
|
625
|
+
project TEXT,
|
|
626
|
+
duration_seconds REAL,
|
|
627
|
+
input_tokens INTEGER,
|
|
628
|
+
output_tokens INTEGER,
|
|
629
|
+
cache_read_tokens INTEGER,
|
|
630
|
+
cache_write_tokens INTEGER,
|
|
631
|
+
cost_usd REAL,
|
|
632
|
+
model TEXT,
|
|
633
|
+
context_window_size INTEGER,
|
|
634
|
+
run_type TEXT,
|
|
635
|
+
outcome TEXT,
|
|
636
|
+
message_count INTEGER,
|
|
637
|
+
error_message TEXT,
|
|
638
|
+
exit_code INTEGER,
|
|
639
|
+
collected_at TEXT,
|
|
640
|
+
UNIQUE(system, source_path, session_id)
|
|
641
|
+
);
|
|
642
|
+
|
|
643
|
+
CREATE TABLE IF NOT EXISTS fleet_waste (
|
|
644
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
645
|
+
system TEXT NOT NULL,
|
|
646
|
+
agent_name TEXT,
|
|
647
|
+
waste_type TEXT NOT NULL,
|
|
648
|
+
tier INTEGER NOT NULL,
|
|
649
|
+
severity TEXT,
|
|
650
|
+
confidence REAL,
|
|
651
|
+
description TEXT,
|
|
652
|
+
monthly_waste_usd REAL,
|
|
653
|
+
monthly_waste_tokens INTEGER,
|
|
654
|
+
recommendation TEXT,
|
|
655
|
+
fix_snippet TEXT,
|
|
656
|
+
evidence_json TEXT,
|
|
657
|
+
detected_at TEXT
|
|
658
|
+
);
|
|
659
|
+
|
|
660
|
+
CREATE TABLE IF NOT EXISTS fleet_daily (
|
|
661
|
+
date TEXT,
|
|
662
|
+
system TEXT,
|
|
663
|
+
run_count INTEGER,
|
|
664
|
+
total_input INTEGER,
|
|
665
|
+
total_output INTEGER,
|
|
666
|
+
total_cost REAL,
|
|
667
|
+
empty_heartbeat_count INTEGER,
|
|
668
|
+
PRIMARY KEY (date, system)
|
|
669
|
+
);
|
|
670
|
+
|
|
671
|
+
CREATE TABLE IF NOT EXISTS fleet_meta (
|
|
672
|
+
key TEXT PRIMARY KEY,
|
|
673
|
+
value TEXT
|
|
674
|
+
);
|
|
675
|
+
"""
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _init_fleet_db() -> sqlite3.Connection:
|
|
679
|
+
"""Initialize fleet.db with schema and version tracking."""
|
|
680
|
+
conn = init_sqlite_db(FLEET_DB, _FLEET_SCHEMA)
|
|
681
|
+
# Set schema version if not present
|
|
682
|
+
cur = conn.execute("SELECT value FROM fleet_meta WHERE key = 'schema_version'")
|
|
683
|
+
row = cur.fetchone()
|
|
684
|
+
if not row:
|
|
685
|
+
conn.execute(
|
|
686
|
+
"INSERT INTO fleet_meta (key, value) VALUES (?, ?)",
|
|
687
|
+
("schema_version", SCHEMA_VERSION),
|
|
688
|
+
)
|
|
689
|
+
conn.commit()
|
|
690
|
+
return conn
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def _is_run_collected(conn: sqlite3.Connection, system: str, source_path: str, session_id: str) -> bool:
|
|
694
|
+
"""Check if a specific run has already been collected."""
|
|
695
|
+
cur = conn.execute(
|
|
696
|
+
"SELECT 1 FROM fleet_runs WHERE system = ? AND source_path = ? AND session_id = ?",
|
|
697
|
+
(system, source_path, session_id),
|
|
698
|
+
)
|
|
699
|
+
return cur.fetchone() is not None
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _insert_run(conn: sqlite3.Connection, run: AgentRun):
|
|
703
|
+
"""Insert an AgentRun into fleet_runs."""
|
|
704
|
+
conn.execute(
|
|
705
|
+
"""INSERT OR IGNORE INTO fleet_runs
|
|
706
|
+
(source_path, system, session_id, date, agent_name, project,
|
|
707
|
+
duration_seconds, input_tokens, output_tokens, cache_read_tokens,
|
|
708
|
+
cache_write_tokens, cost_usd, model, context_window_size,
|
|
709
|
+
run_type, outcome, message_count, error_message, exit_code, collected_at)
|
|
710
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
|
711
|
+
(
|
|
712
|
+
run.source_path,
|
|
713
|
+
run.system,
|
|
714
|
+
run.session_id,
|
|
715
|
+
run.timestamp.strftime("%Y-%m-%d"),
|
|
716
|
+
run.agent_name,
|
|
717
|
+
run.project,
|
|
718
|
+
run.duration_seconds,
|
|
719
|
+
run.tokens.input,
|
|
720
|
+
run.tokens.output,
|
|
721
|
+
run.tokens.cache_read,
|
|
722
|
+
run.tokens.cache_write,
|
|
723
|
+
run.cost_usd,
|
|
724
|
+
run.model,
|
|
725
|
+
run.context_window_size,
|
|
726
|
+
run.run_type,
|
|
727
|
+
run.outcome,
|
|
728
|
+
run.message_count,
|
|
729
|
+
run.error_message,
|
|
730
|
+
run.exit_code,
|
|
731
|
+
datetime.now(timezone.utc).isoformat(),
|
|
732
|
+
),
|
|
733
|
+
)
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _insert_waste(conn: sqlite3.Connection, finding: WasteFinding):
|
|
737
|
+
"""Insert a WasteFinding into fleet_waste."""
|
|
738
|
+
conn.execute(
|
|
739
|
+
"""INSERT INTO fleet_waste
|
|
740
|
+
(system, agent_name, waste_type, tier, severity, confidence,
|
|
741
|
+
description, monthly_waste_usd, monthly_waste_tokens,
|
|
742
|
+
recommendation, fix_snippet, evidence_json, detected_at)
|
|
743
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
|
744
|
+
(
|
|
745
|
+
finding.system,
|
|
746
|
+
finding.agent_name,
|
|
747
|
+
finding.waste_type,
|
|
748
|
+
finding.tier,
|
|
749
|
+
finding.severity,
|
|
750
|
+
finding.confidence,
|
|
751
|
+
finding.description,
|
|
752
|
+
finding.monthly_waste_usd,
|
|
753
|
+
finding.monthly_waste_tokens,
|
|
754
|
+
finding.recommendation,
|
|
755
|
+
finding.fix_snippet,
|
|
756
|
+
json.dumps(finding.evidence) if finding.evidence else None,
|
|
757
|
+
datetime.now(timezone.utc).isoformat(),
|
|
758
|
+
),
|
|
759
|
+
)
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _update_daily_aggregates(conn: sqlite3.Connection):
|
|
763
|
+
"""Rebuild fleet_daily from fleet_runs."""
|
|
764
|
+
conn.execute("DELETE FROM fleet_daily")
|
|
765
|
+
conn.execute("""
|
|
766
|
+
INSERT INTO fleet_daily (date, system, run_count, total_input, total_output, total_cost, empty_heartbeat_count)
|
|
767
|
+
SELECT
|
|
768
|
+
date, system,
|
|
769
|
+
COUNT(*) as run_count,
|
|
770
|
+
SUM(input_tokens) as total_input,
|
|
771
|
+
SUM(output_tokens) as total_output,
|
|
772
|
+
SUM(cost_usd) as total_cost,
|
|
773
|
+
SUM(CASE WHEN run_type = 'heartbeat' AND outcome = 'empty' THEN 1 ELSE 0 END) as empty_heartbeat_count
|
|
774
|
+
FROM fleet_runs
|
|
775
|
+
GROUP BY date, system
|
|
776
|
+
""")
|
|
777
|
+
conn.commit()
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
# ===================================================================
|
|
781
|
+
# ADAPTER PATTERN
|
|
782
|
+
# ===================================================================
|
|
783
|
+
|
|
784
|
+
class BaseAdapter:
|
|
785
|
+
"""Base class for agent system adapters.
|
|
786
|
+
|
|
787
|
+
Each adapter implements three methods:
|
|
788
|
+
- detect() -> (bool, float, str): Is this system installed? (found, confidence 0-1, detail)
|
|
789
|
+
- scan(since, conn) -> (list[AgentRun], list[str]): Collect runs since date. Returns (runs, errors).
|
|
790
|
+
- parse_config() -> dict: Extract system configuration for Tier 1 analysis.
|
|
791
|
+
"""
|
|
792
|
+
|
|
793
|
+
name: str = "base"
|
|
794
|
+
display_name: str = "Base"
|
|
795
|
+
|
|
796
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
797
|
+
"""Detect if this system is installed.
|
|
798
|
+
|
|
799
|
+
Returns (found, confidence, detail_message).
|
|
800
|
+
Confidence: 0.0-1.0 where 1.0 = definitely installed with data.
|
|
801
|
+
"""
|
|
802
|
+
return False, 0.0, "Not implemented"
|
|
803
|
+
|
|
804
|
+
def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
|
|
805
|
+
"""Scan for agent runs since the given datetime.
|
|
806
|
+
|
|
807
|
+
Returns (runs, errors) where errors is a list of non-fatal error messages.
|
|
808
|
+
If conn is provided, skips already-collected runs.
|
|
809
|
+
|
|
810
|
+
The default is for adapters that can detect a system but not read its
|
|
811
|
+
runs yet. It says so: a bare ([], []) printed "0 scanned" for a system
|
|
812
|
+
detect() had just reported as installed, the silent-zero of #149.
|
|
813
|
+
"""
|
|
814
|
+
return [], [f"{self.display_name} fleet collection is not implemented yet, "
|
|
815
|
+
f"so its runs are not counted here (0 is not a measurement)."]
|
|
816
|
+
|
|
817
|
+
def parse_config(self) -> dict:
|
|
818
|
+
"""Parse system configuration for Tier 1 waste analysis.
|
|
819
|
+
|
|
820
|
+
Returns dict with system-specific config details like:
|
|
821
|
+
- model settings, skill counts, cron configs, tool definitions
|
|
822
|
+
"""
|
|
823
|
+
return {}
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
class ClaudeCodeAdapter(BaseAdapter):
|
|
827
|
+
"""Adapter for Claude Code (~/.claude/projects/)."""
|
|
828
|
+
|
|
829
|
+
name = "claude"
|
|
830
|
+
display_name = "Claude Code"
|
|
831
|
+
|
|
832
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
833
|
+
projects_dir = CLAUDE_DIR / "projects"
|
|
834
|
+
if not projects_dir.exists():
|
|
835
|
+
return False, 0.0, "~/.claude/projects/ not found"
|
|
836
|
+
|
|
837
|
+
# Count JSONL files
|
|
838
|
+
jsonl_count = 0
|
|
839
|
+
for pd in projects_dir.iterdir():
|
|
840
|
+
if pd.is_dir():
|
|
841
|
+
jsonl_count += sum(1 for _ in pd.glob("*.jsonl"))
|
|
842
|
+
if jsonl_count > 5:
|
|
843
|
+
break
|
|
844
|
+
|
|
845
|
+
if jsonl_count == 0:
|
|
846
|
+
return True, 0.3, "~/.claude/projects/ exists but no session logs found"
|
|
847
|
+
|
|
848
|
+
return True, 1.0, f"Found {jsonl_count}+ session logs in ~/.claude/projects/"
|
|
849
|
+
|
|
850
|
+
def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
|
|
851
|
+
days = max(1, int((datetime.now(timezone.utc) - since).total_seconds() / 86400) + 1)
|
|
852
|
+
files = find_claude_jsonl_files(days=days)
|
|
853
|
+
|
|
854
|
+
runs = []
|
|
855
|
+
errors = []
|
|
856
|
+
|
|
857
|
+
for filepath, mtime, project_dir_name in files:
|
|
858
|
+
session_id = filepath.stem
|
|
859
|
+
|
|
860
|
+
# Skip already collected
|
|
861
|
+
if conn and _is_run_collected(conn, "claude", str(filepath), session_id):
|
|
862
|
+
continue
|
|
863
|
+
|
|
864
|
+
run = self._parse_session(filepath, project_dir_name)
|
|
865
|
+
if run:
|
|
866
|
+
runs.append(run)
|
|
867
|
+
|
|
868
|
+
# Also scan subagent files
|
|
869
|
+
for sub_path in find_subagent_jsonl_files(filepath):
|
|
870
|
+
sub_id = f"{session_id}/sub/{sub_path.stem}"
|
|
871
|
+
if conn and _is_run_collected(conn, "claude", str(sub_path), sub_id):
|
|
872
|
+
continue
|
|
873
|
+
sub_run = self._parse_session(sub_path, project_dir_name, is_subagent=True, parent_session=session_id)
|
|
874
|
+
if sub_run:
|
|
875
|
+
runs.append(sub_run)
|
|
876
|
+
|
|
877
|
+
return runs, errors
|
|
878
|
+
|
|
879
|
+
def _parse_session(self, filepath: Path, project_dir_name: str,
|
|
880
|
+
is_subagent: bool = False, parent_session: str = "") -> AgentRun | None:
|
|
881
|
+
"""Parse a single Claude Code JSONL session file into an AgentRun."""
|
|
882
|
+
total_input = 0
|
|
883
|
+
total_output = 0
|
|
884
|
+
total_cache_read = 0
|
|
885
|
+
total_cache_create = 0
|
|
886
|
+
total_cache_create_1h = 0
|
|
887
|
+
total_cache_create_5m = 0
|
|
888
|
+
exact_cost = 0.0
|
|
889
|
+
model_usage: dict[str, int] = {}
|
|
890
|
+
message_count = 0
|
|
891
|
+
api_calls = 0
|
|
892
|
+
current_req_key: str | None = None
|
|
893
|
+
current_usage: dict[str, Any] | None = None
|
|
894
|
+
tools_used_set: set[str] = set()
|
|
895
|
+
first_ts: datetime | None = None
|
|
896
|
+
last_ts: datetime | None = None
|
|
897
|
+
version = None
|
|
898
|
+
|
|
899
|
+
def add_usage(usage: dict[str, Any]) -> None:
|
|
900
|
+
nonlocal total_input, total_output, total_cache_read, total_cache_create
|
|
901
|
+
nonlocal total_cache_create_1h, total_cache_create_5m, api_calls, exact_cost
|
|
902
|
+
inp_tok = int(usage["input"])
|
|
903
|
+
out_tok = int(usage["output"])
|
|
904
|
+
cr = int(usage["cache_read"])
|
|
905
|
+
cc = int(usage["cache_write"])
|
|
906
|
+
cc_1h = int(usage["cache_write_1h"])
|
|
907
|
+
cc_5m = int(usage["cache_write_5m"])
|
|
908
|
+
total_input += inp_tok
|
|
909
|
+
total_output += out_tok
|
|
910
|
+
total_cache_read += cr
|
|
911
|
+
total_cache_create += cc
|
|
912
|
+
total_cache_create_1h += cc_1h
|
|
913
|
+
total_cache_create_5m += cc_5m
|
|
914
|
+
api_calls += 1
|
|
915
|
+
model_id = str(usage.get("model") or "unknown")
|
|
916
|
+
model_usage[model_id] = model_usage.get(model_id, 0) + inp_tok + cr + cc + out_tok
|
|
917
|
+
exact_cost += calculate_cost(
|
|
918
|
+
TokenBreakdown(input=inp_tok, output=out_tok, cache_read=cr, cache_write=cc),
|
|
919
|
+
_pricing_key(model_id),
|
|
920
|
+
cache_write_1h=cc_1h,
|
|
921
|
+
cache_write_5m=cc_5m,
|
|
922
|
+
per_request=True,
|
|
923
|
+
)
|
|
924
|
+
|
|
925
|
+
def flush_current_usage() -> None:
|
|
926
|
+
nonlocal current_req_key, current_usage
|
|
927
|
+
if current_usage is not None:
|
|
928
|
+
add_usage(current_usage)
|
|
929
|
+
current_req_key = None
|
|
930
|
+
current_usage = None
|
|
931
|
+
|
|
932
|
+
for record in iter_jsonl(filepath):
|
|
933
|
+
# Version
|
|
934
|
+
if version is None:
|
|
935
|
+
v = record.get("version")
|
|
936
|
+
if v:
|
|
937
|
+
version = v
|
|
938
|
+
|
|
939
|
+
# Timestamp
|
|
940
|
+
ts = parse_timestamp(record.get("timestamp"))
|
|
941
|
+
if ts:
|
|
942
|
+
if first_ts is None:
|
|
943
|
+
first_ts = ts
|
|
944
|
+
last_ts = ts
|
|
945
|
+
|
|
946
|
+
rec_type = record.get("type")
|
|
947
|
+
|
|
948
|
+
# Count messages
|
|
949
|
+
if rec_type in ("user", "assistant"):
|
|
950
|
+
message_count += 1
|
|
951
|
+
|
|
952
|
+
# Extract tool usage + token data from assistant messages
|
|
953
|
+
if rec_type == "assistant":
|
|
954
|
+
msg = record.get("message", {})
|
|
955
|
+
content = msg.get("content", [])
|
|
956
|
+
if isinstance(content, list):
|
|
957
|
+
for block in content:
|
|
958
|
+
if isinstance(block, dict) and block.get("type") == "tool_use":
|
|
959
|
+
tools_used_set.add(block.get("name", ""))
|
|
960
|
+
|
|
961
|
+
usage = msg.get("usage", {})
|
|
962
|
+
if usage:
|
|
963
|
+
inp_tok = usage.get("input_tokens", 0) or 0
|
|
964
|
+
out_tok = usage.get("output_tokens", 0) or 0
|
|
965
|
+
cr = usage.get("cache_read_input_tokens", 0) or 0
|
|
966
|
+
# Parse 1h/5m TTL split from cache_creation sub-object or flat keys.
|
|
967
|
+
cache_creation = usage.get("cache_creation", {})
|
|
968
|
+
if not isinstance(cache_creation, dict):
|
|
969
|
+
cache_creation = {}
|
|
970
|
+
cc_1h = (
|
|
971
|
+
cache_creation.get("ephemeral_1h_input_tokens", 0)
|
|
972
|
+
or usage.get("ephemeral_1h_input_tokens", 0)
|
|
973
|
+
or 0
|
|
974
|
+
)
|
|
975
|
+
cc_5m = (
|
|
976
|
+
cache_creation.get("ephemeral_5m_input_tokens", 0)
|
|
977
|
+
or usage.get("ephemeral_5m_input_tokens", 0)
|
|
978
|
+
or 0
|
|
979
|
+
)
|
|
980
|
+
cc = usage.get("cache_creation_input_tokens", 0) or (cc_1h + cc_5m)
|
|
981
|
+
model_id = msg.get("model", "unknown")
|
|
982
|
+
req_id = record.get("requestId")
|
|
983
|
+
current = {
|
|
984
|
+
"input": inp_tok,
|
|
985
|
+
"output": out_tok,
|
|
986
|
+
"cache_read": cr,
|
|
987
|
+
"cache_write": cc,
|
|
988
|
+
"cache_write_1h": cc_1h,
|
|
989
|
+
"cache_write_5m": cc_5m,
|
|
990
|
+
"model": model_id,
|
|
991
|
+
}
|
|
992
|
+
if not req_id:
|
|
993
|
+
flush_current_usage()
|
|
994
|
+
add_usage(current)
|
|
995
|
+
continue
|
|
996
|
+
key = str(req_id)
|
|
997
|
+
if current_req_key != key:
|
|
998
|
+
flush_current_usage()
|
|
999
|
+
current_req_key = key
|
|
1000
|
+
current_usage = current
|
|
1001
|
+
continue
|
|
1002
|
+
previous = current_usage
|
|
1003
|
+
if previous is None:
|
|
1004
|
+
current_usage = current
|
|
1005
|
+
continue
|
|
1006
|
+
previous["input"] = max(previous["input"], inp_tok)
|
|
1007
|
+
previous["output"] = max(previous["output"], out_tok)
|
|
1008
|
+
previous["cache_read"] = max(previous["cache_read"], cr)
|
|
1009
|
+
previous["cache_write"] = max(previous["cache_write"], cc)
|
|
1010
|
+
previous["cache_write_1h"] = max(previous["cache_write_1h"], cc_1h)
|
|
1011
|
+
previous["cache_write_5m"] = max(previous["cache_write_5m"], cc_5m)
|
|
1012
|
+
if model_id and model_id != "unknown":
|
|
1013
|
+
previous["model"] = model_id
|
|
1014
|
+
|
|
1015
|
+
if message_count == 0:
|
|
1016
|
+
return None
|
|
1017
|
+
|
|
1018
|
+
# Claude Code streaming writes cumulative usage chunks per requestId.
|
|
1019
|
+
# Chunks are emitted consecutively, so keep one in-flight accumulator and
|
|
1020
|
+
# flush it when the request id changes.
|
|
1021
|
+
flush_current_usage()
|
|
1022
|
+
|
|
1023
|
+
# Duration
|
|
1024
|
+
duration_seconds = 0.0
|
|
1025
|
+
if first_ts and last_ts:
|
|
1026
|
+
duration_seconds = max(0.0, (last_ts - first_ts).total_seconds())
|
|
1027
|
+
|
|
1028
|
+
# Dominant model
|
|
1029
|
+
dominant_model_raw = max(model_usage, key=model_usage.get) if model_usage else "unknown"
|
|
1030
|
+
model = normalize_model_name(dominant_model_raw) or dominant_model_raw
|
|
1031
|
+
|
|
1032
|
+
# Context window heuristic
|
|
1033
|
+
context_window = 200_000
|
|
1034
|
+
if model in ("fable", "opus", "sonnet") or "1m" in dominant_model_raw.lower():
|
|
1035
|
+
context_window = 1_000_000
|
|
1036
|
+
|
|
1037
|
+
# input_tokens from API = uncached input only
|
|
1038
|
+
# cache_read_input_tokens = tokens read from cache
|
|
1039
|
+
# cache_creation_input_tokens = tokens written to cache
|
|
1040
|
+
# Total context sent = uncached + cache_read + cache_create
|
|
1041
|
+
# Each priced at its own rate, so store separately.
|
|
1042
|
+
tokens = TokenBreakdown(
|
|
1043
|
+
input=total_input, # Uncached input only
|
|
1044
|
+
output=total_output,
|
|
1045
|
+
cache_read=total_cache_read,
|
|
1046
|
+
cache_write=total_cache_create,
|
|
1047
|
+
)
|
|
1048
|
+
|
|
1049
|
+
# Determine outcome (use total context = uncached + cache_read + cache_create)
|
|
1050
|
+
total_context = total_input + total_cache_read + total_cache_create
|
|
1051
|
+
outcome = "success"
|
|
1052
|
+
if message_count <= 2 and total_output < 200:
|
|
1053
|
+
outcome = "abandoned"
|
|
1054
|
+
elif total_output < 100 and total_context > 50_000:
|
|
1055
|
+
outcome = "empty"
|
|
1056
|
+
|
|
1057
|
+
# Determine run type
|
|
1058
|
+
run_type = "delegate" if is_subagent else "manual"
|
|
1059
|
+
|
|
1060
|
+
cost = calculate_cost(tokens, _pricing_key(dominant_model_raw),
|
|
1061
|
+
cache_write_1h=total_cache_create_1h,
|
|
1062
|
+
cache_write_5m=total_cache_create_5m)
|
|
1063
|
+
if exact_cost > 0:
|
|
1064
|
+
cost = exact_cost
|
|
1065
|
+
|
|
1066
|
+
return AgentRun(
|
|
1067
|
+
system="claude",
|
|
1068
|
+
session_id=filepath.stem if not is_subagent else f"{parent_session}/sub/{filepath.stem}",
|
|
1069
|
+
agent_name="subagent" if is_subagent else "main",
|
|
1070
|
+
project=clean_project_name(project_dir_name),
|
|
1071
|
+
timestamp=first_ts or datetime.now(timezone.utc),
|
|
1072
|
+
duration_seconds=duration_seconds,
|
|
1073
|
+
tokens=tokens,
|
|
1074
|
+
cost_usd=cost,
|
|
1075
|
+
model=model,
|
|
1076
|
+
context_window_size=context_window,
|
|
1077
|
+
run_type=run_type,
|
|
1078
|
+
outcome=outcome,
|
|
1079
|
+
message_count=message_count,
|
|
1080
|
+
tools_used=sorted(tools_used_set),
|
|
1081
|
+
source_path=str(filepath),
|
|
1082
|
+
)
|
|
1083
|
+
|
|
1084
|
+
def parse_config(self) -> dict:
|
|
1085
|
+
"""Parse Claude Code configuration for Tier 1 analysis."""
|
|
1086
|
+
config: dict[str, Any] = {
|
|
1087
|
+
"skills": [],
|
|
1088
|
+
"mcp_servers": [],
|
|
1089
|
+
"claude_md_tokens": 0,
|
|
1090
|
+
"memory_md_tokens": 0,
|
|
1091
|
+
"commands": [],
|
|
1092
|
+
"hooks": {},
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
# Skills
|
|
1096
|
+
# Only the YAML frontmatter (name + description) is loaded into the
|
|
1097
|
+
# session at startup. SKILL.md bodies load on demand when the user
|
|
1098
|
+
# invokes the skill. Measuring the full file over-counts by ~10-20x
|
|
1099
|
+
# and inflates skill_bloat findings.
|
|
1100
|
+
skills_dir = CLAUDE_DIR / "skills"
|
|
1101
|
+
if skills_dir.exists():
|
|
1102
|
+
for sd in skills_dir.iterdir():
|
|
1103
|
+
if sd.is_dir():
|
|
1104
|
+
skill_md = sd / "SKILL.md"
|
|
1105
|
+
if skill_md.exists():
|
|
1106
|
+
config["skills"].append({
|
|
1107
|
+
"name": sd.name,
|
|
1108
|
+
"tokens": _estimate_skill_frontmatter_tokens(skill_md),
|
|
1109
|
+
})
|
|
1110
|
+
|
|
1111
|
+
# CLAUDE.md
|
|
1112
|
+
claude_md = CLAUDE_DIR / "CLAUDE.md"
|
|
1113
|
+
if claude_md.exists():
|
|
1114
|
+
config["claude_md_tokens"] = estimate_tokens_from_file(claude_md)
|
|
1115
|
+
|
|
1116
|
+
# MEMORY.md files
|
|
1117
|
+
projects_dir = CLAUDE_DIR / "projects"
|
|
1118
|
+
if projects_dir.exists():
|
|
1119
|
+
for pd in projects_dir.iterdir():
|
|
1120
|
+
mem_file = pd / "memory" / "MEMORY.md"
|
|
1121
|
+
if mem_file.exists():
|
|
1122
|
+
config["memory_md_tokens"] = max(
|
|
1123
|
+
config["memory_md_tokens"],
|
|
1124
|
+
estimate_tokens_from_file(mem_file),
|
|
1125
|
+
)
|
|
1126
|
+
|
|
1127
|
+
# MCP servers from settings
|
|
1128
|
+
settings_path = CLAUDE_DIR / "settings.json"
|
|
1129
|
+
if settings_path.exists():
|
|
1130
|
+
try:
|
|
1131
|
+
with open(settings_path, "r", encoding="utf-8") as f:
|
|
1132
|
+
settings = json.load(f)
|
|
1133
|
+
mcp = settings.get("mcpServers", {})
|
|
1134
|
+
config["mcp_servers"] = list(mcp.keys())
|
|
1135
|
+
|
|
1136
|
+
# Hooks
|
|
1137
|
+
hooks = settings.get("hooks", {})
|
|
1138
|
+
config["hooks"] = hooks
|
|
1139
|
+
except (json.JSONDecodeError, PermissionError):
|
|
1140
|
+
pass
|
|
1141
|
+
|
|
1142
|
+
# Commands
|
|
1143
|
+
cmd_dir = CLAUDE_DIR / "commands"
|
|
1144
|
+
if cmd_dir.exists():
|
|
1145
|
+
for cf in cmd_dir.glob("*.md"):
|
|
1146
|
+
config["commands"].append(cf.stem)
|
|
1147
|
+
|
|
1148
|
+
return config
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
class CodexAdapter(BaseAdapter):
|
|
1152
|
+
"""Adapter for Codex (~/.codex/sessions/ and ~/.codex/archived_sessions/)."""
|
|
1153
|
+
|
|
1154
|
+
name = "codex"
|
|
1155
|
+
display_name = "Codex"
|
|
1156
|
+
|
|
1157
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
1158
|
+
if codex_session is None:
|
|
1159
|
+
return False, 0.0, "Codex parser unavailable"
|
|
1160
|
+
home = codex_home()
|
|
1161
|
+
roots = [home / "sessions", home / "archived_sessions"]
|
|
1162
|
+
if not home.exists():
|
|
1163
|
+
return False, 0.0, "~/.codex/ not found"
|
|
1164
|
+
jsonl_count = 0
|
|
1165
|
+
for root in roots:
|
|
1166
|
+
if root.exists():
|
|
1167
|
+
for _ in root.rglob("*.jsonl"):
|
|
1168
|
+
jsonl_count += 1
|
|
1169
|
+
if jsonl_count > 5:
|
|
1170
|
+
break
|
|
1171
|
+
if jsonl_count > 5:
|
|
1172
|
+
break
|
|
1173
|
+
if jsonl_count == 0:
|
|
1174
|
+
return True, 0.3, "~/.codex/ exists but no session logs found"
|
|
1175
|
+
return True, 1.0, f"Found {jsonl_count}+ session logs in ~/.codex/sessions/"
|
|
1176
|
+
|
|
1177
|
+
def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
|
|
1178
|
+
if codex_session is None:
|
|
1179
|
+
return [], ["Codex parser unavailable"]
|
|
1180
|
+
days = max(1, int((datetime.now(timezone.utc) - since).total_seconds() / 86400) + 1)
|
|
1181
|
+
files = codex_session.find_all_jsonl_files(days=days)
|
|
1182
|
+
runs: list[AgentRun] = []
|
|
1183
|
+
errors: list[str] = []
|
|
1184
|
+
|
|
1185
|
+
for filepath, _mtime, project_name in files:
|
|
1186
|
+
session_id = filepath.stem
|
|
1187
|
+
if conn and _is_run_collected(conn, "codex", str(filepath), session_id):
|
|
1188
|
+
continue
|
|
1189
|
+
try:
|
|
1190
|
+
parsed = codex_session.parse_session_jsonl(filepath)
|
|
1191
|
+
except Exception as exc:
|
|
1192
|
+
errors.append(f"{filepath}: {exc}")
|
|
1193
|
+
continue
|
|
1194
|
+
if not parsed:
|
|
1195
|
+
continue
|
|
1196
|
+
run = self._parsed_to_run(filepath, project_name, parsed)
|
|
1197
|
+
if run:
|
|
1198
|
+
runs.append(run)
|
|
1199
|
+
return runs, errors
|
|
1200
|
+
|
|
1201
|
+
def _parsed_to_run(self, filepath: Path, project_name: str, parsed: dict[str, Any]) -> AgentRun | None:
|
|
1202
|
+
input_total = int(parsed.get("total_input_tokens") or 0)
|
|
1203
|
+
cache_read = int(parsed.get("total_cache_read") or 0)
|
|
1204
|
+
output = int(parsed.get("total_output_tokens") or 0)
|
|
1205
|
+
if input_total <= 0 and output <= 0 and int(parsed.get("message_count") or 0) == 0:
|
|
1206
|
+
return None
|
|
1207
|
+
|
|
1208
|
+
model_usage = parsed.get("model_usage") or {}
|
|
1209
|
+
dominant_model_raw = max(model_usage, key=model_usage.get) if model_usage else "codex"
|
|
1210
|
+
model = normalize_model_name(str(dominant_model_raw)) or str(dominant_model_raw)
|
|
1211
|
+
tokens = TokenBreakdown(
|
|
1212
|
+
input=max(0, input_total - cache_read),
|
|
1213
|
+
output=output,
|
|
1214
|
+
cache_read=cache_read,
|
|
1215
|
+
cache_write=int(parsed.get("total_cache_create") or 0),
|
|
1216
|
+
)
|
|
1217
|
+
message_count = int(parsed.get("message_count") or 0)
|
|
1218
|
+
outcome = "success"
|
|
1219
|
+
if message_count <= 2 and output < 200:
|
|
1220
|
+
outcome = "abandoned"
|
|
1221
|
+
elif output < 100 and input_total > 50_000:
|
|
1222
|
+
outcome = "empty"
|
|
1223
|
+
|
|
1224
|
+
first_ts = parse_timestamp(parsed.get("first_ts"))
|
|
1225
|
+
return AgentRun(
|
|
1226
|
+
system="codex",
|
|
1227
|
+
session_id=str(parsed.get("slug") or filepath.stem),
|
|
1228
|
+
agent_name="main",
|
|
1229
|
+
project=project_name or filepath.parent.name,
|
|
1230
|
+
timestamp=first_ts or datetime.fromtimestamp(filepath.stat().st_mtime, timezone.utc),
|
|
1231
|
+
duration_seconds=float(parsed.get("duration_minutes") or 0) * 60,
|
|
1232
|
+
tokens=tokens,
|
|
1233
|
+
cost_usd=calculate_cost(tokens, _pricing_key(str(dominant_model_raw))),
|
|
1234
|
+
model=model,
|
|
1235
|
+
context_window_size=int(parsed.get("model_context_window") or 200_000),
|
|
1236
|
+
run_type="manual",
|
|
1237
|
+
outcome=outcome,
|
|
1238
|
+
message_count=message_count,
|
|
1239
|
+
tools_used=sorted((parsed.get("tool_calls") or {}).keys()),
|
|
1240
|
+
source_path=str(filepath),
|
|
1241
|
+
)
|
|
1242
|
+
|
|
1243
|
+
def parse_config(self) -> dict:
|
|
1244
|
+
config: dict[str, Any] = {
|
|
1245
|
+
"skills": [],
|
|
1246
|
+
"mcp_servers": [],
|
|
1247
|
+
"claude_md_tokens": 0,
|
|
1248
|
+
"instruction_file_label": "AGENTS.md",
|
|
1249
|
+
"memory_md_tokens": 0,
|
|
1250
|
+
"commands": [],
|
|
1251
|
+
"hooks": {},
|
|
1252
|
+
}
|
|
1253
|
+
home = codex_home()
|
|
1254
|
+
|
|
1255
|
+
for base in (home / "skills", home / "plugins" / "cache"):
|
|
1256
|
+
if not base.exists():
|
|
1257
|
+
continue
|
|
1258
|
+
for skill_md in base.rglob("SKILL.md"):
|
|
1259
|
+
config["skills"].append({
|
|
1260
|
+
"name": skill_md.parent.name,
|
|
1261
|
+
"tokens": _estimate_skill_frontmatter_tokens(skill_md),
|
|
1262
|
+
})
|
|
1263
|
+
|
|
1264
|
+
agents_tokens = 0
|
|
1265
|
+
for agents_name in ("AGENTS.override.md", "AGENTS.md"):
|
|
1266
|
+
agents_path = home / agents_name
|
|
1267
|
+
if agents_path.exists():
|
|
1268
|
+
agents_tokens += estimate_tokens_from_file(agents_path)
|
|
1269
|
+
config["claude_md_tokens"] = agents_tokens
|
|
1270
|
+
|
|
1271
|
+
memories_dir = home / "memories"
|
|
1272
|
+
if memories_dir.exists():
|
|
1273
|
+
for mem_file in memories_dir.rglob("*.md"):
|
|
1274
|
+
config["memory_md_tokens"] = max(
|
|
1275
|
+
config["memory_md_tokens"],
|
|
1276
|
+
estimate_tokens_from_file(mem_file),
|
|
1277
|
+
)
|
|
1278
|
+
|
|
1279
|
+
config_path = home / "config.toml"
|
|
1280
|
+
if config_path.exists() and tomllib is not None:
|
|
1281
|
+
try:
|
|
1282
|
+
with config_path.open("rb") as handle:
|
|
1283
|
+
cfg = tomllib.load(handle)
|
|
1284
|
+
mcp = cfg.get("mcp_servers", {})
|
|
1285
|
+
if isinstance(mcp, dict):
|
|
1286
|
+
config["mcp_servers"] = list(mcp.keys())
|
|
1287
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
1288
|
+
pass
|
|
1289
|
+
|
|
1290
|
+
hooks_path = Path.cwd() / ".codex" / "hooks.json"
|
|
1291
|
+
if hooks_path.exists():
|
|
1292
|
+
try:
|
|
1293
|
+
hooks_data = json.loads(hooks_path.read_text(encoding="utf-8"))
|
|
1294
|
+
hooks = hooks_data.get("hooks", {})
|
|
1295
|
+
config["hooks"] = hooks if isinstance(hooks, dict) else {}
|
|
1296
|
+
except (json.JSONDecodeError, OSError):
|
|
1297
|
+
pass
|
|
1298
|
+
|
|
1299
|
+
return config
|
|
1300
|
+
|
|
1301
|
+
|
|
1302
|
+
# Stubs for Phase 1.5+ adapters
|
|
1303
|
+
class OpenClawAdapter(BaseAdapter):
|
|
1304
|
+
name = "openclaw"
|
|
1305
|
+
display_name = "OpenClaw"
|
|
1306
|
+
|
|
1307
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
1308
|
+
for p in [HOME / ".openclaw", HOME / ".clawdbot", HOME / ".moltbot"]:
|
|
1309
|
+
if p.exists():
|
|
1310
|
+
sessions_json = p / "agents" if (p / "agents").is_dir() else None
|
|
1311
|
+
if sessions_json:
|
|
1312
|
+
return True, 0.8, f"Found {p.name} directory with agents/"
|
|
1313
|
+
return True, 0.4, f"Found {p.name} directory (no agents/ yet)"
|
|
1314
|
+
return False, 0.0, "No OpenClaw directories found"
|
|
1315
|
+
|
|
1316
|
+
def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
|
|
1317
|
+
return [], ["OpenClaw fleet collection is not implemented in this Python adapter; use the OpenClaw dashboard for OpenClaw runs."]
|
|
1318
|
+
|
|
1319
|
+
|
|
1320
|
+
class NanoClawAdapter(BaseAdapter):
|
|
1321
|
+
name = "nanoclaw"
|
|
1322
|
+
display_name = "NanoClaw"
|
|
1323
|
+
|
|
1324
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
1325
|
+
nc_dir = HOME / ".nanoclaw"
|
|
1326
|
+
if nc_dir.exists():
|
|
1327
|
+
return True, 0.6, "Found ~/.nanoclaw/"
|
|
1328
|
+
return False, 0.0, "~/.nanoclaw/ not found"
|
|
1329
|
+
|
|
1330
|
+
|
|
1331
|
+
class HermesAdapter(BaseAdapter):
|
|
1332
|
+
name = "hermes"
|
|
1333
|
+
display_name = "Hermes"
|
|
1334
|
+
|
|
1335
|
+
# Columns we read if present. state.db schema drifts across Hermes versions,
|
|
1336
|
+
# so scan() intersects this with the live table and never assumes a column.
|
|
1337
|
+
_WANT_COLUMNS = (
|
|
1338
|
+
"id", "model", "started_at", "ended_at", "end_reason",
|
|
1339
|
+
"message_count", "tool_call_count", "input_tokens", "output_tokens",
|
|
1340
|
+
"cache_read_tokens", "cache_write_tokens", "reasoning_tokens",
|
|
1341
|
+
"estimated_cost_usd", "actual_cost_usd", "cost_status", "cwd", "source",
|
|
1342
|
+
)
|
|
1343
|
+
|
|
1344
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
1345
|
+
state_db = HOME / ".hermes" / "state.db"
|
|
1346
|
+
if state_db.exists():
|
|
1347
|
+
return True, 1.0, "Found ~/.hermes/state.db"
|
|
1348
|
+
hermes_dir = HOME / ".hermes"
|
|
1349
|
+
if hermes_dir.exists():
|
|
1350
|
+
return True, 0.4, "Found ~/.hermes/ (no state.db)"
|
|
1351
|
+
return False, 0.0, "~/.hermes/ not found"
|
|
1352
|
+
|
|
1353
|
+
def scan(self, since: datetime, conn: sqlite3.Connection | None = None) -> tuple[list[AgentRun], list[str]]:
|
|
1354
|
+
"""Read runs from ~/.hermes/state.db.
|
|
1355
|
+
|
|
1356
|
+
BaseAdapter.scan() returned ([], []) so Hermes silently reported zero even
|
|
1357
|
+
under heavy use. We open the DB read-only (mode=ro): it can never write to
|
|
1358
|
+
Hermes's own state, and unlike immutable=1 it still reads committed WAL
|
|
1359
|
+
rows, so a scan run against a LIVE Hermes sees its most recent sessions
|
|
1360
|
+
instead of silently dropping everything since the last checkpoint.
|
|
1361
|
+
"""
|
|
1362
|
+
state_db = HOME / ".hermes" / "state.db"
|
|
1363
|
+
if not state_db.exists():
|
|
1364
|
+
return [], ["~/.hermes/state.db not found"]
|
|
1365
|
+
|
|
1366
|
+
runs: list[AgentRun] = []
|
|
1367
|
+
errors: list[str] = []
|
|
1368
|
+
db: sqlite3.Connection | None = None
|
|
1369
|
+
try:
|
|
1370
|
+
# as_uri() percent-encodes spaces / reserved chars in the path so a
|
|
1371
|
+
# home dir like "/Users/Alex Green/" doesn't corrupt the URI.
|
|
1372
|
+
db = sqlite3.connect(f"{state_db.as_uri()}?mode=ro", uri=True, timeout=5)
|
|
1373
|
+
db.row_factory = sqlite3.Row
|
|
1374
|
+
available = {r[1] for r in db.execute("PRAGMA table_info(sessions)").fetchall()}
|
|
1375
|
+
if not available:
|
|
1376
|
+
return [], ["~/.hermes/state.db has no 'sessions' table"]
|
|
1377
|
+
cols = [c for c in self._WANT_COLUMNS if c in available]
|
|
1378
|
+
if "id" not in cols or "started_at" not in available:
|
|
1379
|
+
# Without an id / started_at we can't dedup or window; bail loudly
|
|
1380
|
+
# rather than importing every row on every scan.
|
|
1381
|
+
return [], ["~/.hermes/state.db 'sessions' missing id/started_at columns"]
|
|
1382
|
+
since_ts = since.timestamp()
|
|
1383
|
+
rows = db.execute(
|
|
1384
|
+
f"SELECT {', '.join(cols)} FROM sessions WHERE started_at >= ?",
|
|
1385
|
+
(since_ts,),
|
|
1386
|
+
).fetchall()
|
|
1387
|
+
except sqlite3.Error as exc:
|
|
1388
|
+
return [], [f"~/.hermes/state.db read failed: {exc}"]
|
|
1389
|
+
finally:
|
|
1390
|
+
if db is not None:
|
|
1391
|
+
db.close()
|
|
1392
|
+
|
|
1393
|
+
for row in rows:
|
|
1394
|
+
try:
|
|
1395
|
+
run = self._row_to_run(row, row.keys())
|
|
1396
|
+
except (ValueError, TypeError) as exc:
|
|
1397
|
+
errors.append(f"hermes session {row['id'] if 'id' in row.keys() else '?'}: {exc}")
|
|
1398
|
+
continue
|
|
1399
|
+
if run is None:
|
|
1400
|
+
continue
|
|
1401
|
+
# Re-check the window in Python: a TEXT-stored started_at (older Hermes
|
|
1402
|
+
# schemas) compares lexically against the float bind in the SQL WHERE,
|
|
1403
|
+
# so old rows can leak past it. _row_to_run has already parsed the real
|
|
1404
|
+
# timestamp — trust that, not the storage-class comparison.
|
|
1405
|
+
if run.timestamp and run.timestamp < since:
|
|
1406
|
+
continue
|
|
1407
|
+
if conn and _is_run_collected(conn, "hermes", run.source_path, run.session_id):
|
|
1408
|
+
continue
|
|
1409
|
+
runs.append(run)
|
|
1410
|
+
return runs, errors
|
|
1411
|
+
|
|
1412
|
+
@staticmethod
|
|
1413
|
+
def _to_dt(value) -> datetime | None:
|
|
1414
|
+
"""Hermes stores started_at/ended_at as REAL epoch seconds, but older
|
|
1415
|
+
rows or exports may carry an ISO string — accept both."""
|
|
1416
|
+
if value is None or value == "":
|
|
1417
|
+
return None
|
|
1418
|
+
if isinstance(value, (int, float)):
|
|
1419
|
+
try:
|
|
1420
|
+
return datetime.fromtimestamp(float(value), timezone.utc)
|
|
1421
|
+
except (OverflowError, OSError, ValueError):
|
|
1422
|
+
return None
|
|
1423
|
+
return parse_timestamp(str(value))
|
|
1424
|
+
|
|
1425
|
+
def _row_to_run(self, row: sqlite3.Row, keys) -> AgentRun | None:
|
|
1426
|
+
def g(name, default=0):
|
|
1427
|
+
return row[name] if name in keys and row[name] is not None else default
|
|
1428
|
+
|
|
1429
|
+
input_total = int(g("input_tokens"))
|
|
1430
|
+
output = int(g("output_tokens"))
|
|
1431
|
+
cache_read = int(g("cache_read_tokens"))
|
|
1432
|
+
cache_write = int(g("cache_write_tokens"))
|
|
1433
|
+
message_count = int(g("message_count"))
|
|
1434
|
+
if input_total <= 0 and output <= 0 and cache_read <= 0 and message_count == 0:
|
|
1435
|
+
return None
|
|
1436
|
+
|
|
1437
|
+
model_raw = str(g("model", "") or "")
|
|
1438
|
+
model = normalize_model_name(model_raw) or model_raw or "unknown"
|
|
1439
|
+
# Hermes stores input_tokens and cache_read_tokens as SEPARATE columns
|
|
1440
|
+
# (a cache-heavy run has cache_read >> input_tokens), so input_tokens is
|
|
1441
|
+
# already the fresh-input count. Do NOT subtract cache_read — that floored
|
|
1442
|
+
# cache-heavy gateway runs to 0 input, corrupting the very numbers
|
|
1443
|
+
# the pricing guard exists to surface. (Codex's total_input_tokens IS inclusive, hence its
|
|
1444
|
+
# subtraction; Hermes is not.)
|
|
1445
|
+
tokens = TokenBreakdown(
|
|
1446
|
+
input=max(0, input_total),
|
|
1447
|
+
output=output,
|
|
1448
|
+
cache_read=cache_read,
|
|
1449
|
+
cache_write=cache_write,
|
|
1450
|
+
)
|
|
1451
|
+
|
|
1452
|
+
# Prefer Hermes's own recorded cost — it prices gateway models (MiniMax,
|
|
1453
|
+
# Kimi, DeepSeek...) our DEFAULT_PRICING can't, so they don't collapse to a
|
|
1454
|
+
# fake $0. A recorded value (incl. $0) is authoritative; only a
|
|
1455
|
+
# genuinely absent/garbage cost falls back to our table.
|
|
1456
|
+
db_cost = _recorded_cost(g("actual_cost_usd", None), g("estimated_cost_usd", None))
|
|
1457
|
+
cost = db_cost if db_cost is not None else calculate_cost(tokens, _pricing_key(model_raw) if model_raw else model)
|
|
1458
|
+
|
|
1459
|
+
started = self._to_dt(g("started_at", None))
|
|
1460
|
+
ended = self._to_dt(g("ended_at", None))
|
|
1461
|
+
duration = 0.0
|
|
1462
|
+
if started and ended and ended >= started:
|
|
1463
|
+
duration = (ended - started).total_seconds()
|
|
1464
|
+
|
|
1465
|
+
outcome = "success"
|
|
1466
|
+
if message_count <= 2 and output < 200:
|
|
1467
|
+
outcome = "abandoned"
|
|
1468
|
+
elif output < 100 and input_total > 50_000:
|
|
1469
|
+
outcome = "empty"
|
|
1470
|
+
|
|
1471
|
+
cwd = str(g("cwd", "") or "")
|
|
1472
|
+
return AgentRun(
|
|
1473
|
+
system="hermes",
|
|
1474
|
+
session_id=str(g("id", "")),
|
|
1475
|
+
# Keep Hermes's own source label (cli/api/subagent...) instead of
|
|
1476
|
+
# flattening every run to "main" — audit detectors group by agent_name.
|
|
1477
|
+
agent_name=str(g("source", "") or "") or "main",
|
|
1478
|
+
# Full cwd, not just the basename: two projects can share a leaf name
|
|
1479
|
+
# (~/work/foo vs ~/play/foo) and would otherwise merge in the dashboard.
|
|
1480
|
+
project=cwd or "unknown",
|
|
1481
|
+
timestamp=started or datetime.now(timezone.utc),
|
|
1482
|
+
duration_seconds=duration,
|
|
1483
|
+
tokens=tokens,
|
|
1484
|
+
cost_usd=cost,
|
|
1485
|
+
model=model,
|
|
1486
|
+
run_type="manual",
|
|
1487
|
+
outcome=outcome,
|
|
1488
|
+
message_count=message_count,
|
|
1489
|
+
source_path=f"hermes:state.db#{g('id', '')}",
|
|
1490
|
+
)
|
|
1491
|
+
|
|
1492
|
+
|
|
1493
|
+
class OpenCodeAdapter(BaseAdapter):
|
|
1494
|
+
name = "opencode"
|
|
1495
|
+
display_name = "OpenCode"
|
|
1496
|
+
|
|
1497
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
1498
|
+
# Check env var first
|
|
1499
|
+
data_dir = os.environ.get("OPENCODE_DATA_DIR")
|
|
1500
|
+
if data_dir and Path(data_dir).exists():
|
|
1501
|
+
return True, 0.9, f"Found $OPENCODE_DATA_DIR at {data_dir}"
|
|
1502
|
+
|
|
1503
|
+
oc_dir = HOME / ".local" / "share" / "opencode"
|
|
1504
|
+
if oc_dir.exists():
|
|
1505
|
+
return True, 0.8, "Found ~/.local/share/opencode/"
|
|
1506
|
+
appdata = os.environ.get("APPDATA", "")
|
|
1507
|
+
if appdata:
|
|
1508
|
+
win_dir = Path(appdata) / "opencode"
|
|
1509
|
+
if win_dir.exists():
|
|
1510
|
+
return True, 0.8, f"Found {win_dir}"
|
|
1511
|
+
return False, 0.0, "No OpenCode data directory found"
|
|
1512
|
+
|
|
1513
|
+
|
|
1514
|
+
class IronClawAdapter(BaseAdapter):
|
|
1515
|
+
name = "ironclaw"
|
|
1516
|
+
display_name = "IronClaw"
|
|
1517
|
+
|
|
1518
|
+
def detect(self) -> tuple[bool, float, str]:
|
|
1519
|
+
ic_dir = HOME / ".ironclaw"
|
|
1520
|
+
if ic_dir.exists():
|
|
1521
|
+
return True, 0.3, "Found ~/.ironclaw/ (needs connection config for full scan)"
|
|
1522
|
+
return False, 0.0, "~/.ironclaw/ not found"
|
|
1523
|
+
|
|
1524
|
+
|
|
1525
|
+
# Adapter registry
|
|
1526
|
+
ADAPTER_REGISTRY: list[type[BaseAdapter]] = [
|
|
1527
|
+
ClaudeCodeAdapter,
|
|
1528
|
+
CodexAdapter,
|
|
1529
|
+
OpenClawAdapter,
|
|
1530
|
+
NanoClawAdapter,
|
|
1531
|
+
HermesAdapter,
|
|
1532
|
+
OpenCodeAdapter,
|
|
1533
|
+
IronClawAdapter,
|
|
1534
|
+
]
|
|
1535
|
+
|
|
1536
|
+
|
|
1537
|
+
def _require_known_system(target_system):
|
|
1538
|
+
"""Exit 2 on a --system no adapter answers to. It used to filter every
|
|
1539
|
+
adapter out and print "0 new runs collected", a silent zero (#149 class)
|
|
1540
|
+
for a typo such as --system claude-code."""
|
|
1541
|
+
if target_system is None:
|
|
1542
|
+
return
|
|
1543
|
+
known = [cls.name for cls in ADAPTER_REGISTRY]
|
|
1544
|
+
if target_system not in known:
|
|
1545
|
+
print(f" Unknown --system {target_system!r}. Known systems: {', '.join(known)}.",
|
|
1546
|
+
file=sys.stderr)
|
|
1547
|
+
sys.exit(2)
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
# ===================================================================
|
|
1551
|
+
# WASTE PATTERN DETECTORS
|
|
1552
|
+
# ===================================================================
|
|
1553
|
+
|
|
1554
|
+
class BaseDetector:
|
|
1555
|
+
"""Base class for waste pattern detectors."""
|
|
1556
|
+
|
|
1557
|
+
name: str = ""
|
|
1558
|
+
tier: int = 1
|
|
1559
|
+
description: str = ""
|
|
1560
|
+
|
|
1561
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1562
|
+
"""Run detection and return findings. Empty list = no waste found."""
|
|
1563
|
+
return []
|
|
1564
|
+
|
|
1565
|
+
|
|
1566
|
+
# --- Tier 1: Static Config Analysis ---
|
|
1567
|
+
|
|
1568
|
+
class HeartbeatModelWaste(BaseDetector):
|
|
1569
|
+
"""Detect expensive models used for heartbeat/cron runs."""
|
|
1570
|
+
name = "heartbeat_model_waste"
|
|
1571
|
+
tier = 1
|
|
1572
|
+
description = "Expensive model for heartbeat/cron tasks"
|
|
1573
|
+
|
|
1574
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1575
|
+
findings = []
|
|
1576
|
+
heartbeat_runs = [r for r in runs if r.run_type in ("heartbeat", "cron")]
|
|
1577
|
+
if not heartbeat_runs:
|
|
1578
|
+
return findings
|
|
1579
|
+
|
|
1580
|
+
expensive_hb = [r for r in heartbeat_runs if r.model in ("fable", "opus", "sonnet")]
|
|
1581
|
+
if not expensive_hb:
|
|
1582
|
+
return findings
|
|
1583
|
+
|
|
1584
|
+
total_cost = sum(r.cost_usd for r in expensive_hb)
|
|
1585
|
+
days_spanned = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in expensive_hb}))
|
|
1586
|
+
monthly_cost = (total_cost / days_spanned) * 30
|
|
1587
|
+
|
|
1588
|
+
# Calculate savings if switched to haiku
|
|
1589
|
+
haiku_cost = 0.0
|
|
1590
|
+
for r in expensive_hb:
|
|
1591
|
+
haiku_cost += calculate_cost(r.tokens, "haiku")
|
|
1592
|
+
haiku_monthly = (haiku_cost / days_spanned) * 30
|
|
1593
|
+
savings = monthly_cost - haiku_monthly
|
|
1594
|
+
|
|
1595
|
+
if savings < 0.10:
|
|
1596
|
+
return findings
|
|
1597
|
+
|
|
1598
|
+
# v5.11.1: derive the "# was:" comment from the actual expensive
|
|
1599
|
+
# heartbeat models found, instead of the hardcoded "opus/sonnet" (which
|
|
1600
|
+
# was wrong whenever the waste was, e.g., fable-only).
|
|
1601
|
+
models_found = sorted({r.model for r in expensive_hb})
|
|
1602
|
+
was_comment = "/".join(models_found) if models_found else "expensive model"
|
|
1603
|
+
|
|
1604
|
+
findings.append(WasteFinding(
|
|
1605
|
+
system=system,
|
|
1606
|
+
waste_type=self.name,
|
|
1607
|
+
tier=self.tier,
|
|
1608
|
+
severity="high" if savings > 5.0 else "medium",
|
|
1609
|
+
confidence=0.9,
|
|
1610
|
+
description=f"{len(expensive_hb)} heartbeat/cron runs using {expensive_hb[0].model} instead of Haiku",
|
|
1611
|
+
monthly_waste_usd=savings,
|
|
1612
|
+
monthly_waste_tokens=sum(r.tokens.total for r in expensive_hb),
|
|
1613
|
+
recommendation=f"Route heartbeat/cron tasks to Haiku. Saves ~${savings:.2f}/month.",
|
|
1614
|
+
fix_snippet=f'# In your agent config, set heartbeat model:\nmodel: "haiku" # was: {was_comment}',
|
|
1615
|
+
evidence={"expensive_count": len(expensive_hb), "models_used": models_found},
|
|
1616
|
+
))
|
|
1617
|
+
return findings
|
|
1618
|
+
|
|
1619
|
+
|
|
1620
|
+
class SkillBloat(BaseDetector):
|
|
1621
|
+
"""Detect too many skills loaded per agent."""
|
|
1622
|
+
name = "skill_bloat"
|
|
1623
|
+
tier = 1
|
|
1624
|
+
description = "Too many skills loaded (~100 tokens each, every API call)"
|
|
1625
|
+
|
|
1626
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1627
|
+
skills = config.get("skills", [])
|
|
1628
|
+
if len(skills) <= 10:
|
|
1629
|
+
return []
|
|
1630
|
+
|
|
1631
|
+
total_skill_tokens = sum(s.get("tokens", 100) for s in skills)
|
|
1632
|
+
# ~100 tokens per skill per API call, estimate 20 API calls per session average
|
|
1633
|
+
monthly_sessions = 30 # rough estimate
|
|
1634
|
+
monthly_waste = total_skill_tokens * 20 * monthly_sessions
|
|
1635
|
+
|
|
1636
|
+
if system == "codex":
|
|
1637
|
+
monthly_cost = 0.0
|
|
1638
|
+
fix_snippet = _with_measure_cli("# Disable truly stale user skills with:\n# TOKEN_OPTIMIZER_RUNTIME=codex python3 measure.py codex-skill disable --path <skill-dir>")
|
|
1639
|
+
else:
|
|
1640
|
+
cost_per_token = 3.0 / 1e6 # sonnet input rate as baseline
|
|
1641
|
+
monthly_cost = monthly_waste * cost_per_token
|
|
1642
|
+
fix_snippet = _with_measure_cli("# Move unused skills out of ~/.claude/skills/\n# Check which skills you actually use:\n# python3 measure.py trends --days 30")
|
|
1643
|
+
|
|
1644
|
+
return [WasteFinding(
|
|
1645
|
+
system=system,
|
|
1646
|
+
waste_type=self.name,
|
|
1647
|
+
tier=self.tier,
|
|
1648
|
+
severity="medium" if len(skills) <= 20 else "high",
|
|
1649
|
+
confidence=0.8,
|
|
1650
|
+
description=f"{len(skills)} skills loaded ({total_skill_tokens:,} tokens overhead per API call)",
|
|
1651
|
+
monthly_waste_usd=monthly_cost,
|
|
1652
|
+
monthly_waste_tokens=monthly_waste,
|
|
1653
|
+
recommendation="Archive unused skills. Each removed skill saves ~100 tokens per API call across all sessions.",
|
|
1654
|
+
fix_snippet=fix_snippet,
|
|
1655
|
+
evidence={"skill_count": len(skills), "skill_names": [s.get("name", "?") for s in skills]},
|
|
1656
|
+
)]
|
|
1657
|
+
|
|
1658
|
+
|
|
1659
|
+
class ToolDefinitionBloat(BaseDetector):
|
|
1660
|
+
"""Detect tool definitions consuming >20% of context."""
|
|
1661
|
+
name = "tool_definition_bloat"
|
|
1662
|
+
tier = 1
|
|
1663
|
+
description = "Tool definitions consuming excessive context"
|
|
1664
|
+
|
|
1665
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1666
|
+
mcp_servers = config.get("mcp_servers", [])
|
|
1667
|
+
if len(mcp_servers) <= 3:
|
|
1668
|
+
return []
|
|
1669
|
+
|
|
1670
|
+
# Estimate: ~150 tokens per eager tool, ~15 per deferred, ~10 tools per server
|
|
1671
|
+
# Assume 30% eager, 70% deferred after ToolSearch
|
|
1672
|
+
tools_per_server = 10
|
|
1673
|
+
total_tools = len(mcp_servers) * tools_per_server
|
|
1674
|
+
eager_tools = int(total_tools * 0.3)
|
|
1675
|
+
deferred_tools = total_tools - eager_tools
|
|
1676
|
+
tool_tokens = (eager_tools * 150) + (deferred_tools * 15)
|
|
1677
|
+
|
|
1678
|
+
# Check if >20% of smallest likely context window
|
|
1679
|
+
context_pct = (tool_tokens / 200_000) * 100
|
|
1680
|
+
if context_pct < 15:
|
|
1681
|
+
return []
|
|
1682
|
+
|
|
1683
|
+
return [WasteFinding(
|
|
1684
|
+
system=system,
|
|
1685
|
+
waste_type=self.name,
|
|
1686
|
+
tier=self.tier,
|
|
1687
|
+
severity="high" if context_pct > 30 else "medium",
|
|
1688
|
+
confidence=0.6, # Rough estimate
|
|
1689
|
+
description=f"~{len(mcp_servers)} MCP servers with ~{total_tools} tools consuming ~{tool_tokens:,} tokens ({context_pct:.0f}% of 200K context)",
|
|
1690
|
+
monthly_waste_tokens=tool_tokens * 20 * 30, # per call * calls/session * sessions/month
|
|
1691
|
+
monthly_waste_usd=0, # Hard to monetize config overhead accurately
|
|
1692
|
+
recommendation="Disable unused MCP servers. Use ToolSearch (deferred loading) for large tool sets.",
|
|
1693
|
+
fix_snippet=(
|
|
1694
|
+
"# Check which MCP servers are actually used:\n"
|
|
1695
|
+
"# Codex: review ~/.codex/config.toml [mcp_servers]\n"
|
|
1696
|
+
"# Claude Code: review ~/.claude/settings.json mcpServers section"
|
|
1697
|
+
),
|
|
1698
|
+
evidence={"mcp_count": len(mcp_servers), "servers": mcp_servers[:10]},
|
|
1699
|
+
)]
|
|
1700
|
+
|
|
1701
|
+
|
|
1702
|
+
class MemoryConfigOverhead(BaseDetector):
|
|
1703
|
+
"""Detect memory/config files exceeding 5,000 tokens."""
|
|
1704
|
+
name = "memory_config_overhead"
|
|
1705
|
+
tier = 1
|
|
1706
|
+
description = "Injected config files exceeding 5,000 tokens"
|
|
1707
|
+
|
|
1708
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1709
|
+
findings = []
|
|
1710
|
+
|
|
1711
|
+
instruction_label = config.get("instruction_file_label", "CLAUDE.md")
|
|
1712
|
+
claude_md_tokens = config.get("claude_md_tokens", 0)
|
|
1713
|
+
if claude_md_tokens > 5000:
|
|
1714
|
+
findings.append(WasteFinding(
|
|
1715
|
+
system=system,
|
|
1716
|
+
waste_type=self.name,
|
|
1717
|
+
tier=self.tier,
|
|
1718
|
+
severity="medium" if claude_md_tokens <= 10000 else "high",
|
|
1719
|
+
confidence=0.9,
|
|
1720
|
+
description=f"{instruction_label} is {claude_md_tokens:,} tokens (injected every API call)",
|
|
1721
|
+
monthly_waste_tokens=claude_md_tokens * 20 * 30,
|
|
1722
|
+
monthly_waste_usd=0,
|
|
1723
|
+
recommendation=f"Slim {instruction_label} to <2,000 tokens. Move reference material to files loaded on demand.",
|
|
1724
|
+
fix_snippet=f"# Run token-optimizer for guided {instruction_label} optimization",
|
|
1725
|
+
evidence={"claude_md_tokens": claude_md_tokens},
|
|
1726
|
+
))
|
|
1727
|
+
|
|
1728
|
+
memory_tokens = config.get("memory_md_tokens", 0)
|
|
1729
|
+
if memory_tokens > 5000:
|
|
1730
|
+
findings.append(WasteFinding(
|
|
1731
|
+
system=system,
|
|
1732
|
+
waste_type=self.name,
|
|
1733
|
+
tier=self.tier,
|
|
1734
|
+
severity="medium",
|
|
1735
|
+
confidence=0.9,
|
|
1736
|
+
description=f"MEMORY.md is {memory_tokens:,} tokens (injected every API call)",
|
|
1737
|
+
monthly_waste_tokens=memory_tokens * 20 * 30,
|
|
1738
|
+
monthly_waste_usd=0,
|
|
1739
|
+
recommendation="Prune MEMORY.md. Keep it under 200 lines. Move details to individual memory files.",
|
|
1740
|
+
evidence={"memory_md_tokens": memory_tokens},
|
|
1741
|
+
))
|
|
1742
|
+
|
|
1743
|
+
return findings
|
|
1744
|
+
|
|
1745
|
+
|
|
1746
|
+
class StaleCronConfig(BaseDetector):
|
|
1747
|
+
"""Detect cron jobs hitting dead or archived repos."""
|
|
1748
|
+
name = "stale_cron"
|
|
1749
|
+
tier = 1
|
|
1750
|
+
description = "Cron jobs configured for non-existent paths"
|
|
1751
|
+
|
|
1752
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1753
|
+
# Claude Code doesn't have native cron, but hooks can serve as cron-like triggers
|
|
1754
|
+
# This detector is more relevant for OpenClaw/Hermes but we check hook paths here
|
|
1755
|
+
hooks = config.get("hooks", {})
|
|
1756
|
+
if not hooks:
|
|
1757
|
+
return []
|
|
1758
|
+
|
|
1759
|
+
findings = []
|
|
1760
|
+
for hook_name, hook_list in hooks.items():
|
|
1761
|
+
if not isinstance(hook_list, list):
|
|
1762
|
+
continue
|
|
1763
|
+
for hook in hook_list:
|
|
1764
|
+
if not isinstance(hook, dict):
|
|
1765
|
+
continue
|
|
1766
|
+
cmd = hook.get("command", "")
|
|
1767
|
+
# Check if command references a path that doesn't exist
|
|
1768
|
+
if cmd:
|
|
1769
|
+
parts = cmd.split()
|
|
1770
|
+
for part in parts:
|
|
1771
|
+
if part.startswith("/") and not part.startswith("/usr") and not part.startswith("/bin"):
|
|
1772
|
+
if not Path(part).exists() and not part.startswith("$"):
|
|
1773
|
+
findings.append(WasteFinding(
|
|
1774
|
+
system=system,
|
|
1775
|
+
waste_type=self.name,
|
|
1776
|
+
tier=self.tier,
|
|
1777
|
+
severity="low",
|
|
1778
|
+
confidence=0.5,
|
|
1779
|
+
description=f"Hook '{hook_name}' references non-existent path: {part}",
|
|
1780
|
+
recommendation="Remove or fix the hook referencing a dead path.",
|
|
1781
|
+
evidence={"hook": hook_name, "command": cmd, "missing_path": part},
|
|
1782
|
+
))
|
|
1783
|
+
return findings
|
|
1784
|
+
|
|
1785
|
+
|
|
1786
|
+
class BlockingHookDetector(BaseDetector):
|
|
1787
|
+
"""Detect Stop hooks that re-invoke the model via decision:block on every turn."""
|
|
1788
|
+
name = "blocking_hook"
|
|
1789
|
+
tier = 1
|
|
1790
|
+
description = "Stop hook re-invokes model every turn via decision:block"
|
|
1791
|
+
|
|
1792
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1793
|
+
hooks = config.get("hooks", {})
|
|
1794
|
+
if not hooks:
|
|
1795
|
+
return []
|
|
1796
|
+
|
|
1797
|
+
findings = []
|
|
1798
|
+
for hook_name, hook_list in hooks.items():
|
|
1799
|
+
if not isinstance(hook_list, list):
|
|
1800
|
+
continue
|
|
1801
|
+
for entry in hook_list:
|
|
1802
|
+
# Handle both flat {command: ...} and nested {hooks: [{command: ...}]}
|
|
1803
|
+
cmds_to_check = []
|
|
1804
|
+
if isinstance(entry, dict):
|
|
1805
|
+
if "command" in entry:
|
|
1806
|
+
cmds_to_check.append(entry["command"])
|
|
1807
|
+
for inner in entry.get("hooks", []):
|
|
1808
|
+
if isinstance(inner, dict):
|
|
1809
|
+
cmds_to_check.append(inner.get("command", ""))
|
|
1810
|
+
|
|
1811
|
+
for cmd in cmds_to_check:
|
|
1812
|
+
if not cmd:
|
|
1813
|
+
continue
|
|
1814
|
+
if '"decision"' in cmd and '"block"' in cmd:
|
|
1815
|
+
recent_runs = [r for r in runs
|
|
1816
|
+
if (datetime.now(timezone.utc) - r.timestamp).days <= 30]
|
|
1817
|
+
avg_turns = (sum(r.message_count for r in recent_runs) / max(len(recent_runs), 1)
|
|
1818
|
+
if recent_runs else 20)
|
|
1819
|
+
est_per_turn_tokens = 80
|
|
1820
|
+
est_monthly_cost = 0.0
|
|
1821
|
+
if recent_runs:
|
|
1822
|
+
days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in recent_runs}))
|
|
1823
|
+
sessions_per_month = (len(recent_runs) / days) * 30
|
|
1824
|
+
est_monthly_tokens = sessions_per_month * avg_turns * est_per_turn_tokens
|
|
1825
|
+
est_monthly_cost = est_monthly_tokens * 3.0 / 1_000_000
|
|
1826
|
+
|
|
1827
|
+
findings.append(WasteFinding(
|
|
1828
|
+
system=system,
|
|
1829
|
+
waste_type=self.name,
|
|
1830
|
+
tier=self.tier,
|
|
1831
|
+
severity="medium" if est_monthly_cost > 1.0 else "low",
|
|
1832
|
+
confidence=0.8,
|
|
1833
|
+
description=(
|
|
1834
|
+
f"{hook_name} hook uses decision:block, re-invoking the model "
|
|
1835
|
+
f"on every turn (~{est_per_turn_tokens} tok/turn, "
|
|
1836
|
+
f"~{avg_turns:.0f} turns/session)"
|
|
1837
|
+
),
|
|
1838
|
+
recommendation=(
|
|
1839
|
+
f"Remove the decision:block pattern from the {hook_name} hook. "
|
|
1840
|
+
"Use additionalContext injection instead of blocking+re-invoking."
|
|
1841
|
+
),
|
|
1842
|
+
evidence={"hook_event": hook_name, "command_preview": cmd[:100]},
|
|
1843
|
+
monthly_waste_tokens=int(est_monthly_cost / 3.0 * 1_000_000),
|
|
1844
|
+
monthly_waste_usd=round(est_monthly_cost, 2),
|
|
1845
|
+
))
|
|
1846
|
+
if any(kw in cmd for kw in ("curl ", " anthropic", " openai", " gemini")):
|
|
1847
|
+
findings.append(WasteFinding(
|
|
1848
|
+
system=system,
|
|
1849
|
+
waste_type="heavyweight_hook",
|
|
1850
|
+
tier=self.tier,
|
|
1851
|
+
severity="low",
|
|
1852
|
+
confidence=0.6,
|
|
1853
|
+
description=f"{hook_name} hook calls external API on every invocation",
|
|
1854
|
+
recommendation="Consider caching API responses or moving to an async pattern.",
|
|
1855
|
+
evidence={"hook_event": hook_name, "command_preview": cmd[:80]},
|
|
1856
|
+
))
|
|
1857
|
+
return findings
|
|
1858
|
+
|
|
1859
|
+
|
|
1860
|
+
class HeartbeatOverFrequency(BaseDetector):
|
|
1861
|
+
"""Detect heartbeat intervals < 5 minutes."""
|
|
1862
|
+
name = "heartbeat_over_frequency"
|
|
1863
|
+
tier = 1
|
|
1864
|
+
description = "Heartbeat interval too frequent (< 5 minutes)"
|
|
1865
|
+
|
|
1866
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1867
|
+
heartbeats = sorted(
|
|
1868
|
+
[r for r in runs if r.run_type in ("heartbeat", "cron")],
|
|
1869
|
+
key=lambda r: r.timestamp,
|
|
1870
|
+
)
|
|
1871
|
+
if len(heartbeats) < 3:
|
|
1872
|
+
return []
|
|
1873
|
+
|
|
1874
|
+
# Check intervals between consecutive heartbeats
|
|
1875
|
+
short_intervals = []
|
|
1876
|
+
for i in range(1, len(heartbeats)):
|
|
1877
|
+
gap = (heartbeats[i].timestamp - heartbeats[i - 1].timestamp).total_seconds()
|
|
1878
|
+
if 0 < gap < 300: # Less than 5 minutes
|
|
1879
|
+
short_intervals.append(gap)
|
|
1880
|
+
|
|
1881
|
+
if len(short_intervals) < 3:
|
|
1882
|
+
return []
|
|
1883
|
+
|
|
1884
|
+
avg_interval = sum(short_intervals) / len(short_intervals)
|
|
1885
|
+
# Estimate waste: each heartbeat costs ~input tokens at model rate
|
|
1886
|
+
avg_cost_per_hb = sum(r.cost_usd for r in heartbeats) / len(heartbeats)
|
|
1887
|
+
# How many extra heartbeats per month if interval is X instead of 5min?
|
|
1888
|
+
runs_per_hour_actual = 3600 / avg_interval
|
|
1889
|
+
runs_per_hour_optimal = 3600 / 300 # 12 per hour
|
|
1890
|
+
extra_runs_per_hour = max(0, runs_per_hour_actual - runs_per_hour_optimal)
|
|
1891
|
+
# Assume 16 active hours per day
|
|
1892
|
+
monthly_extra = extra_runs_per_hour * 16 * 30
|
|
1893
|
+
monthly_waste = monthly_extra * avg_cost_per_hb
|
|
1894
|
+
|
|
1895
|
+
if monthly_waste < 0.10:
|
|
1896
|
+
return []
|
|
1897
|
+
|
|
1898
|
+
return [WasteFinding(
|
|
1899
|
+
system=system,
|
|
1900
|
+
waste_type=self.name,
|
|
1901
|
+
tier=self.tier,
|
|
1902
|
+
severity="medium" if monthly_waste < 2.0 else "high",
|
|
1903
|
+
confidence=0.7,
|
|
1904
|
+
description=f"Heartbeats averaging {avg_interval:.0f}s interval ({len(short_intervals)} intervals < 5 min)",
|
|
1905
|
+
monthly_waste_usd=monthly_waste,
|
|
1906
|
+
recommendation=f"Increase heartbeat interval to 5+ minutes. Current average: {avg_interval:.0f}s.",
|
|
1907
|
+
fix_snippet="# Increase heartbeat interval in agent config:\nheartbeat_interval: 300 # 5 minutes",
|
|
1908
|
+
evidence={"avg_interval_seconds": avg_interval, "short_count": len(short_intervals)},
|
|
1909
|
+
)]
|
|
1910
|
+
|
|
1911
|
+
|
|
1912
|
+
# --- Tier 2: Session Log Analysis ---
|
|
1913
|
+
|
|
1914
|
+
class EmptyHeartbeatRuns(BaseDetector):
|
|
1915
|
+
"""Detect heartbeat runs with high input but near-zero output."""
|
|
1916
|
+
name = "empty_heartbeat"
|
|
1917
|
+
tier = 2
|
|
1918
|
+
description = "High input, <100 output, no state change (the #1 waste pattern)"
|
|
1919
|
+
|
|
1920
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1921
|
+
# Look for runs with high total context but near-zero output.
|
|
1922
|
+
# tokens.input = uncached only, so use .total for full context loaded.
|
|
1923
|
+
empty_runs = [
|
|
1924
|
+
r for r in runs
|
|
1925
|
+
if r.tokens.total > 5000 and r.tokens.output < 100 and r.message_count <= 4
|
|
1926
|
+
]
|
|
1927
|
+
|
|
1928
|
+
if not empty_runs:
|
|
1929
|
+
return []
|
|
1930
|
+
|
|
1931
|
+
# Filter false positives: require substantial context load or explicit "empty" outcome
|
|
1932
|
+
confirmed_empty = [r for r in empty_runs if r.tokens.total > 50_000 or r.outcome == "empty"]
|
|
1933
|
+
|
|
1934
|
+
if len(confirmed_empty) < 2:
|
|
1935
|
+
return []
|
|
1936
|
+
|
|
1937
|
+
total_waste_cost = sum(r.cost_usd for r in confirmed_empty)
|
|
1938
|
+
days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in confirmed_empty}))
|
|
1939
|
+
monthly_cost = (total_waste_cost / days) * 30
|
|
1940
|
+
monthly_tokens = sum(r.tokens.total for r in confirmed_empty)
|
|
1941
|
+
|
|
1942
|
+
return [WasteFinding(
|
|
1943
|
+
system=system,
|
|
1944
|
+
waste_type=self.name,
|
|
1945
|
+
tier=self.tier,
|
|
1946
|
+
severity="critical" if monthly_cost > 10 else "high" if monthly_cost > 2 else "medium",
|
|
1947
|
+
confidence=0.85,
|
|
1948
|
+
description=f"{len(confirmed_empty)} empty runs: high context load, near-zero useful output",
|
|
1949
|
+
monthly_waste_usd=monthly_cost,
|
|
1950
|
+
monthly_waste_tokens=monthly_tokens,
|
|
1951
|
+
recommendation="Add guard conditions to skip runs when there's nothing to do. Route idle checks to Haiku.",
|
|
1952
|
+
fix_snippet='# Add early-exit check in heartbeat script:\nif ! has_pending_work; then exit 0; fi',
|
|
1953
|
+
evidence={
|
|
1954
|
+
"empty_count": len(confirmed_empty),
|
|
1955
|
+
"avg_input": int(sum(r.tokens.input for r in confirmed_empty) / len(confirmed_empty)),
|
|
1956
|
+
"avg_output": int(sum(r.tokens.output for r in confirmed_empty) / len(confirmed_empty)),
|
|
1957
|
+
},
|
|
1958
|
+
)]
|
|
1959
|
+
|
|
1960
|
+
|
|
1961
|
+
class SessionHistoryBloat(BaseDetector):
|
|
1962
|
+
"""Detect sessions where context grows monotonically without compaction."""
|
|
1963
|
+
name = "session_history_bloat"
|
|
1964
|
+
tier = 2
|
|
1965
|
+
description = "Context tokens growing without compaction"
|
|
1966
|
+
|
|
1967
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
1968
|
+
# Look for long sessions (many messages) with high token totals
|
|
1969
|
+
long_sessions = [r for r in runs if r.message_count > 30 and r.tokens.total > 500_000]
|
|
1970
|
+
|
|
1971
|
+
if not long_sessions:
|
|
1972
|
+
return []
|
|
1973
|
+
|
|
1974
|
+
total_bloat_tokens = sum(r.tokens.input for r in long_sessions)
|
|
1975
|
+
# Estimate what compacted sessions would have cost (roughly 40% savings)
|
|
1976
|
+
savings_tokens = int(total_bloat_tokens * 0.4)
|
|
1977
|
+
days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in long_sessions}))
|
|
1978
|
+
if system == "codex":
|
|
1979
|
+
recommendation = "Use /compact at phase boundaries and install Codex compact prompt guidance plus balanced hooks."
|
|
1980
|
+
fix_snippet = _with_measure_cli("TOKEN_OPTIMIZER_RUNTIME=codex python3 measure.py codex-install --project .")
|
|
1981
|
+
else:
|
|
1982
|
+
recommendation = ("Compact earlier than the auto-compact line (about 967K tokens on 1M models unless you set /autocompact): run /compact when the conversation is long or changes topic. "
|
|
1983
|
+
"Set up Smart Compaction for automatic protection.")
|
|
1984
|
+
fix_snippet = _with_measure_cli("# Install Smart Compaction:\npython3 measure.py setup-smart-compact")
|
|
1985
|
+
|
|
1986
|
+
return [WasteFinding(
|
|
1987
|
+
system=system,
|
|
1988
|
+
waste_type=self.name,
|
|
1989
|
+
tier=self.tier,
|
|
1990
|
+
severity="medium",
|
|
1991
|
+
confidence=0.6,
|
|
1992
|
+
description=f"{len(long_sessions)} long sessions without apparent compaction (30+ messages, 500K+ input tokens)",
|
|
1993
|
+
monthly_waste_tokens=int((savings_tokens / days) * 30),
|
|
1994
|
+
recommendation=recommendation,
|
|
1995
|
+
fix_snippet=fix_snippet,
|
|
1996
|
+
evidence={"long_session_count": len(long_sessions), "total_input_tokens": total_bloat_tokens},
|
|
1997
|
+
)]
|
|
1998
|
+
|
|
1999
|
+
|
|
2000
|
+
class LoopDetection(BaseDetector):
|
|
2001
|
+
"""Detect sessions with many messages but trivially small output (stuck loops)."""
|
|
2002
|
+
name = "loop_detection"
|
|
2003
|
+
tier = 2
|
|
2004
|
+
description = "Many messages with near-zero output (stuck agent loops)"
|
|
2005
|
+
|
|
2006
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
2007
|
+
# Signal: many messages but almost zero TOTAL output, suggesting the agent
|
|
2008
|
+
# is stuck retrying without producing anything useful.
|
|
2009
|
+
# IMPORTANT: In Claude Code, output_tokens in JSONL only counts text output,
|
|
2010
|
+
# not tool calls. Many productive sessions have low output_tokens because
|
|
2011
|
+
# the real work happens via tool_use blocks. So we need very strict thresholds.
|
|
2012
|
+
# Only flag sessions with truly pathological output: <2 tokens per message average.
|
|
2013
|
+
loop_suspects = [
|
|
2014
|
+
r for r in runs
|
|
2015
|
+
if r.message_count > 20
|
|
2016
|
+
and r.tokens.output < (r.message_count * 2) # <2 tokens output per message
|
|
2017
|
+
and r.tokens.total > 100_000 # Heavy context loaded
|
|
2018
|
+
and r.outcome not in ("empty", "abandoned")
|
|
2019
|
+
and r.run_type == "manual" # Skip subagents (different output patterns)
|
|
2020
|
+
]
|
|
2021
|
+
|
|
2022
|
+
if len(loop_suspects) < 2:
|
|
2023
|
+
return []
|
|
2024
|
+
|
|
2025
|
+
# Estimate waste: these sessions loaded heavy context for nothing
|
|
2026
|
+
total_waste = sum(r.cost_usd for r in loop_suspects)
|
|
2027
|
+
days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in loop_suspects}))
|
|
2028
|
+
monthly_cost = (total_waste / days) * 30
|
|
2029
|
+
|
|
2030
|
+
if monthly_cost < 1.00:
|
|
2031
|
+
return []
|
|
2032
|
+
|
|
2033
|
+
return [WasteFinding(
|
|
2034
|
+
system=system,
|
|
2035
|
+
waste_type=self.name,
|
|
2036
|
+
tier=self.tier,
|
|
2037
|
+
severity="medium" if monthly_cost < 10 else "high",
|
|
2038
|
+
confidence=0.6,
|
|
2039
|
+
description=f"{len(loop_suspects)} sessions with 15+ messages but near-zero output (potential stuck loops)",
|
|
2040
|
+
monthly_waste_usd=monthly_cost,
|
|
2041
|
+
monthly_waste_tokens=sum(r.tokens.total for r in loop_suspects),
|
|
2042
|
+
recommendation="Check these sessions for retry storms or stuck tool calls. Consider adding timeout/loop-break logic.",
|
|
2043
|
+
evidence={
|
|
2044
|
+
"suspect_count": len(loop_suspects),
|
|
2045
|
+
"avg_messages": int(sum(r.message_count for r in loop_suspects) / len(loop_suspects)),
|
|
2046
|
+
"avg_output": int(sum(r.tokens.output for r in loop_suspects) / len(loop_suspects)),
|
|
2047
|
+
},
|
|
2048
|
+
)]
|
|
2049
|
+
|
|
2050
|
+
|
|
2051
|
+
class AbandonedSessions(BaseDetector):
|
|
2052
|
+
"""Detect sessions with 1-2 messages then stop (wasted startup cost)."""
|
|
2053
|
+
name = "abandoned_sessions"
|
|
2054
|
+
tier = 2
|
|
2055
|
+
description = "1-2 messages then abandoned (wasted context loading cost)"
|
|
2056
|
+
|
|
2057
|
+
def detect(self, runs: list[AgentRun], config: dict, system: str) -> list[WasteFinding]:
|
|
2058
|
+
abandoned = [
|
|
2059
|
+
r for r in runs
|
|
2060
|
+
if r.message_count <= 2
|
|
2061
|
+
and r.tokens.total > 10_000 # Had significant context loading
|
|
2062
|
+
and r.run_type == "manual" # Not a legitimate heartbeat/cron
|
|
2063
|
+
]
|
|
2064
|
+
|
|
2065
|
+
if len(abandoned) < 3:
|
|
2066
|
+
return []
|
|
2067
|
+
|
|
2068
|
+
total_waste = sum(r.cost_usd for r in abandoned)
|
|
2069
|
+
days = max(1, len({r.timestamp.strftime("%Y-%m-%d") for r in abandoned}))
|
|
2070
|
+
monthly_cost = (total_waste / days) * 30
|
|
2071
|
+
|
|
2072
|
+
if monthly_cost < 0.20:
|
|
2073
|
+
return []
|
|
2074
|
+
|
|
2075
|
+
return [WasteFinding(
|
|
2076
|
+
system=system,
|
|
2077
|
+
waste_type=self.name,
|
|
2078
|
+
tier=self.tier,
|
|
2079
|
+
severity="low" if monthly_cost < 1.0 else "medium",
|
|
2080
|
+
confidence=0.7,
|
|
2081
|
+
description=f"{len(abandoned)} sessions abandoned after 1-2 messages (startup cost wasted)",
|
|
2082
|
+
monthly_waste_usd=monthly_cost,
|
|
2083
|
+
monthly_waste_tokens=sum(r.tokens.total for r in abandoned),
|
|
2084
|
+
recommendation="Consider batching quick questions into fewer sessions to amortize startup cost.",
|
|
2085
|
+
evidence={"abandoned_count": len(abandoned), "avg_input": int(sum(r.tokens.input for r in abandoned) / len(abandoned))},
|
|
2086
|
+
)]
|
|
2087
|
+
|
|
2088
|
+
|
|
2089
|
+
# Detector registry
|
|
2090
|
+
DETECTOR_REGISTRY: list[type[BaseDetector]] = [
|
|
2091
|
+
# Tier 1: Static Config
|
|
2092
|
+
HeartbeatModelWaste,
|
|
2093
|
+
HeartbeatOverFrequency,
|
|
2094
|
+
BlockingHookDetector,
|
|
2095
|
+
SkillBloat,
|
|
2096
|
+
ToolDefinitionBloat,
|
|
2097
|
+
MemoryConfigOverhead,
|
|
2098
|
+
StaleCronConfig,
|
|
2099
|
+
# Tier 2: Session Analysis
|
|
2100
|
+
EmptyHeartbeatRuns,
|
|
2101
|
+
SessionHistoryBloat,
|
|
2102
|
+
LoopDetection,
|
|
2103
|
+
AbandonedSessions,
|
|
2104
|
+
]
|
|
2105
|
+
|
|
2106
|
+
|
|
2107
|
+
# ===================================================================
|
|
2108
|
+
# COMMANDS
|
|
2109
|
+
# ===================================================================
|
|
2110
|
+
|
|
2111
|
+
def cmd_detect(args: list[str]):
|
|
2112
|
+
"""Detect installed agent systems."""
|
|
2113
|
+
as_json = "--json" in args
|
|
2114
|
+
results = []
|
|
2115
|
+
|
|
2116
|
+
for adapter_cls in ADAPTER_REGISTRY:
|
|
2117
|
+
adapter = adapter_cls()
|
|
2118
|
+
found, confidence, detail = adapter.detect()
|
|
2119
|
+
results.append({
|
|
2120
|
+
"system": adapter.name,
|
|
2121
|
+
"display_name": adapter.display_name,
|
|
2122
|
+
"found": found,
|
|
2123
|
+
"confidence": confidence,
|
|
2124
|
+
"detail": detail,
|
|
2125
|
+
})
|
|
2126
|
+
|
|
2127
|
+
if as_json:
|
|
2128
|
+
print(json.dumps(results, indent=2))
|
|
2129
|
+
return
|
|
2130
|
+
|
|
2131
|
+
found_any = False
|
|
2132
|
+
print("\n Fleet Auditor: System Detection")
|
|
2133
|
+
print(" " + "=" * 40)
|
|
2134
|
+
for r in results:
|
|
2135
|
+
if r["found"]:
|
|
2136
|
+
found_any = True
|
|
2137
|
+
conf_label = "HIGH" if r["confidence"] >= 0.8 else "MEDIUM" if r["confidence"] >= 0.5 else "LOW"
|
|
2138
|
+
print(f" {r['display_name']:15s} [{conf_label}] {r['detail']}")
|
|
2139
|
+
if not found_any:
|
|
2140
|
+
print(" No agent systems detected.")
|
|
2141
|
+
print(" Supported: Claude Code, Codex, OpenClaw, NanoClaw, Hermes, OpenCode, IronClaw")
|
|
2142
|
+
print()
|
|
2143
|
+
|
|
2144
|
+
|
|
2145
|
+
def cmd_scan(args: list[str]):
|
|
2146
|
+
"""Collect agent runs into fleet.db."""
|
|
2147
|
+
days = 30
|
|
2148
|
+
target_system = None
|
|
2149
|
+
as_json = "--json" in args
|
|
2150
|
+
quiet = "--quiet" in args or "-q" in args
|
|
2151
|
+
|
|
2152
|
+
for i, a in enumerate(args):
|
|
2153
|
+
if a == "--days" and i + 1 < len(args):
|
|
2154
|
+
try:
|
|
2155
|
+
days = int(args[i + 1])
|
|
2156
|
+
except ValueError:
|
|
2157
|
+
pass
|
|
2158
|
+
elif a == "--system" and i + 1 < len(args):
|
|
2159
|
+
target_system = args[i + 1]
|
|
2160
|
+
_require_known_system(target_system)
|
|
2161
|
+
|
|
2162
|
+
since = datetime.now(timezone.utc) - timedelta(days=days)
|
|
2163
|
+
conn = _init_fleet_db()
|
|
2164
|
+
|
|
2165
|
+
total_new = 0
|
|
2166
|
+
total_errors = []
|
|
2167
|
+
scan_results = []
|
|
2168
|
+
# Collect every scanned run so we can flag models whose $0 is unknown
|
|
2169
|
+
# (no pricing row), not free — computed once via unpriced_summary() below.
|
|
2170
|
+
all_scanned_runs: list[AgentRun] = []
|
|
2171
|
+
|
|
2172
|
+
for adapter_cls in ADAPTER_REGISTRY:
|
|
2173
|
+
adapter = adapter_cls()
|
|
2174
|
+
if target_system and adapter.name != target_system:
|
|
2175
|
+
continue
|
|
2176
|
+
|
|
2177
|
+
found, confidence, _ = adapter.detect()
|
|
2178
|
+
if not found or confidence < 0.3:
|
|
2179
|
+
continue
|
|
2180
|
+
|
|
2181
|
+
t0 = time.time()
|
|
2182
|
+
runs, errors = adapter.scan(since, conn)
|
|
2183
|
+
elapsed = time.time() - t0
|
|
2184
|
+
|
|
2185
|
+
new_count = 0
|
|
2186
|
+
for run in runs:
|
|
2187
|
+
all_scanned_runs.append(run)
|
|
2188
|
+
if not _is_run_collected(conn, run.system, run.source_path, run.session_id):
|
|
2189
|
+
_insert_run(conn, run)
|
|
2190
|
+
new_count += 1
|
|
2191
|
+
|
|
2192
|
+
conn.commit()
|
|
2193
|
+
total_new += new_count
|
|
2194
|
+
total_errors.extend(errors)
|
|
2195
|
+
|
|
2196
|
+
scan_results.append({
|
|
2197
|
+
"system": adapter.name,
|
|
2198
|
+
"scanned": len(runs),
|
|
2199
|
+
"new": new_count,
|
|
2200
|
+
"errors": len(errors),
|
|
2201
|
+
"elapsed_ms": int(elapsed * 1000),
|
|
2202
|
+
})
|
|
2203
|
+
|
|
2204
|
+
# Update daily aggregates
|
|
2205
|
+
_update_daily_aggregates(conn)
|
|
2206
|
+
conn.close()
|
|
2207
|
+
|
|
2208
|
+
# One warning naming every unpriced model, so a $0.00 total reads as
|
|
2209
|
+
# "unknown, not free" and the user knows where to add rates.
|
|
2210
|
+
unpriced_sessions = unpriced_summary(all_scanned_runs)
|
|
2211
|
+
if unpriced_sessions:
|
|
2212
|
+
names = ", ".join(sorted(unpriced_sessions))
|
|
2213
|
+
n = sum(unpriced_sessions.values())
|
|
2214
|
+
total_errors.append(
|
|
2215
|
+
f"{n} session(s) on {len(unpriced_sessions)} unpriced model(s) ({names}): "
|
|
2216
|
+
f"cost shown as $0.00 is UNKNOWN, not free. Add rates to "
|
|
2217
|
+
f"{FLEET_DB_DIR / 'pricing.json'} to price them."
|
|
2218
|
+
)
|
|
2219
|
+
|
|
2220
|
+
if as_json:
|
|
2221
|
+
print(json.dumps({
|
|
2222
|
+
"total_new": total_new,
|
|
2223
|
+
"systems": scan_results,
|
|
2224
|
+
"errors": total_errors,
|
|
2225
|
+
"unpriced_models": unpriced_sessions,
|
|
2226
|
+
}, indent=2))
|
|
2227
|
+
return
|
|
2228
|
+
|
|
2229
|
+
if not quiet:
|
|
2230
|
+
print(f"\n Fleet Scan: {total_new} new runs collected ({days}-day window)")
|
|
2231
|
+
for sr in scan_results:
|
|
2232
|
+
print(f" {sr['system']:12s} {sr['new']:4d} new / {sr['scanned']:4d} scanned ({sr['elapsed_ms']}ms)")
|
|
2233
|
+
if total_errors:
|
|
2234
|
+
print(f" Warnings: {len(total_errors)}")
|
|
2235
|
+
for e in total_errors[:5]:
|
|
2236
|
+
print(f" - {e}")
|
|
2237
|
+
if unpriced_sessions:
|
|
2238
|
+
names = ", ".join(sorted(unpriced_sessions))
|
|
2239
|
+
n = sum(unpriced_sessions.values())
|
|
2240
|
+
print(f" ⚠ Unpriced: {n} session(s) on {names} priced at $0.00 (unknown, not free).")
|
|
2241
|
+
print(f" Add rates to {FLEET_DB_DIR / 'pricing.json'}.")
|
|
2242
|
+
print()
|
|
2243
|
+
|
|
2244
|
+
|
|
2245
|
+
def cmd_audit(args: list[str]):
|
|
2246
|
+
"""Run waste detection on collected data."""
|
|
2247
|
+
days = 30
|
|
2248
|
+
target_system = None
|
|
2249
|
+
as_json = "--json" in args
|
|
2250
|
+
min_confidence = 0.4
|
|
2251
|
+
|
|
2252
|
+
for i, a in enumerate(args):
|
|
2253
|
+
if a == "--days" and i + 1 < len(args):
|
|
2254
|
+
try:
|
|
2255
|
+
days = int(args[i + 1])
|
|
2256
|
+
except ValueError:
|
|
2257
|
+
pass
|
|
2258
|
+
elif a == "--system" and i + 1 < len(args):
|
|
2259
|
+
target_system = args[i + 1]
|
|
2260
|
+
_require_known_system(target_system)
|
|
2261
|
+
|
|
2262
|
+
# First, ensure we have data
|
|
2263
|
+
if not FLEET_DB.exists():
|
|
2264
|
+
print(" No fleet.db found. Run 'fleet.py scan' first.")
|
|
2265
|
+
sys.exit(1)
|
|
2266
|
+
|
|
2267
|
+
conn = _init_fleet_db()
|
|
2268
|
+
|
|
2269
|
+
# Load runs from DB
|
|
2270
|
+
cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
2271
|
+
query = "SELECT * FROM fleet_runs WHERE date >= ?"
|
|
2272
|
+
params: list = [cutoff]
|
|
2273
|
+
if target_system:
|
|
2274
|
+
query += " AND system = ?"
|
|
2275
|
+
params.append(target_system)
|
|
2276
|
+
|
|
2277
|
+
rows = conn.execute(query, params).fetchall()
|
|
2278
|
+
col_names = [desc[0] for desc in conn.execute(query, params).description] if rows else []
|
|
2279
|
+
|
|
2280
|
+
# Reconstruct AgentRun objects
|
|
2281
|
+
runs_by_system: dict[str, list[AgentRun]] = {}
|
|
2282
|
+
for row in rows:
|
|
2283
|
+
rd = dict(zip(col_names, row))
|
|
2284
|
+
system = rd["system"]
|
|
2285
|
+
run = AgentRun(
|
|
2286
|
+
system=system,
|
|
2287
|
+
session_id=rd.get("session_id", ""),
|
|
2288
|
+
agent_name=rd.get("agent_name", ""),
|
|
2289
|
+
project=rd.get("project", ""),
|
|
2290
|
+
timestamp=datetime.fromisoformat(rd["date"]) if rd.get("date") else datetime.now(timezone.utc),
|
|
2291
|
+
duration_seconds=rd.get("duration_seconds", 0) or 0,
|
|
2292
|
+
tokens=TokenBreakdown(
|
|
2293
|
+
input=rd.get("input_tokens", 0) or 0,
|
|
2294
|
+
output=rd.get("output_tokens", 0) or 0,
|
|
2295
|
+
cache_read=rd.get("cache_read_tokens", 0) or 0,
|
|
2296
|
+
cache_write=rd.get("cache_write_tokens", 0) or 0,
|
|
2297
|
+
),
|
|
2298
|
+
cost_usd=rd.get("cost_usd", 0) or 0,
|
|
2299
|
+
model=rd.get("model", ""),
|
|
2300
|
+
context_window_size=rd.get("context_window_size", 200_000) or 200_000,
|
|
2301
|
+
run_type=rd.get("run_type", "manual") or "manual",
|
|
2302
|
+
outcome=rd.get("outcome", "success") or "success",
|
|
2303
|
+
message_count=rd.get("message_count", 0) or 0,
|
|
2304
|
+
tools_used=[],
|
|
2305
|
+
source_path=rd.get("source_path", ""),
|
|
2306
|
+
error_message=rd.get("error_message"),
|
|
2307
|
+
exit_code=rd.get("exit_code"),
|
|
2308
|
+
)
|
|
2309
|
+
runs_by_system.setdefault(system, []).append(run)
|
|
2310
|
+
|
|
2311
|
+
# The dashboard/audit repro: flag runs priced at $0 only
|
|
2312
|
+
# because the model is unpriced, so the audit doesn't present a fake $0 total.
|
|
2313
|
+
audit_unpriced = unpriced_summary([r for rs in runs_by_system.values() for r in rs])
|
|
2314
|
+
|
|
2315
|
+
# Clear old waste findings
|
|
2316
|
+
conn.execute("DELETE FROM fleet_waste")
|
|
2317
|
+
|
|
2318
|
+
# Run detectors per system
|
|
2319
|
+
all_findings: list[WasteFinding] = []
|
|
2320
|
+
|
|
2321
|
+
for system, system_runs in runs_by_system.items():
|
|
2322
|
+
# Get config for Tier 1 detectors
|
|
2323
|
+
config = {}
|
|
2324
|
+
for adapter_cls in ADAPTER_REGISTRY:
|
|
2325
|
+
if adapter_cls.name == system:
|
|
2326
|
+
config = adapter_cls().parse_config()
|
|
2327
|
+
break
|
|
2328
|
+
|
|
2329
|
+
for detector_cls in DETECTOR_REGISTRY:
|
|
2330
|
+
detector = detector_cls()
|
|
2331
|
+
findings = detector.detect(system_runs, config, system)
|
|
2332
|
+
for f in findings:
|
|
2333
|
+
if f.confidence >= min_confidence:
|
|
2334
|
+
all_findings.append(f)
|
|
2335
|
+
_insert_waste(conn, f)
|
|
2336
|
+
|
|
2337
|
+
conn.commit()
|
|
2338
|
+
conn.close()
|
|
2339
|
+
|
|
2340
|
+
if as_json:
|
|
2341
|
+
output = []
|
|
2342
|
+
for f in all_findings:
|
|
2343
|
+
output.append({
|
|
2344
|
+
"system": f.system,
|
|
2345
|
+
"waste_type": f.waste_type,
|
|
2346
|
+
"tier": f.tier,
|
|
2347
|
+
"severity": f.severity,
|
|
2348
|
+
"confidence": f.confidence,
|
|
2349
|
+
"description": f.description,
|
|
2350
|
+
"monthly_waste_usd": f.monthly_waste_usd,
|
|
2351
|
+
"monthly_waste_tokens": f.monthly_waste_tokens,
|
|
2352
|
+
"recommendation": f.recommendation,
|
|
2353
|
+
"fix_snippet": f.fix_snippet,
|
|
2354
|
+
"evidence": f.evidence,
|
|
2355
|
+
})
|
|
2356
|
+
# Keep the documented list contract; unpriced surfaces in the text report
|
|
2357
|
+
# and in `scan --json` (machine-readable there).
|
|
2358
|
+
print(json.dumps(output, indent=2))
|
|
2359
|
+
return
|
|
2360
|
+
|
|
2361
|
+
# Text report
|
|
2362
|
+
print("\n Fleet Audit: Waste Pattern Analysis")
|
|
2363
|
+
print(" " + "=" * 50)
|
|
2364
|
+
if audit_unpriced:
|
|
2365
|
+
names = ", ".join(sorted(audit_unpriced))
|
|
2366
|
+
n = sum(audit_unpriced.values())
|
|
2367
|
+
print(f" ⚠ Unpriced: {n} session(s) on {names} counted at $0.00 (unknown, not free).")
|
|
2368
|
+
print(f" Costs and waste figures below UNDERSTATE these. Add rates to {FLEET_DB_DIR / 'pricing.json'}.")
|
|
2369
|
+
|
|
2370
|
+
if not all_findings:
|
|
2371
|
+
print(" No waste patterns detected. Your fleet looks clean!")
|
|
2372
|
+
print()
|
|
2373
|
+
return
|
|
2374
|
+
|
|
2375
|
+
# Sort by monthly waste (highest first), then severity
|
|
2376
|
+
severity_rank = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
|
2377
|
+
all_findings.sort(key=lambda f: (severity_rank.get(f.severity, 4), -f.monthly_waste_usd))
|
|
2378
|
+
|
|
2379
|
+
total_monthly_waste = sum(f.monthly_waste_usd for f in all_findings)
|
|
2380
|
+
|
|
2381
|
+
for i, f in enumerate(all_findings, 1):
|
|
2382
|
+
print(f"\n {i}. [{f.severity.upper():8s}] {f.description}")
|
|
2383
|
+
print(f" System: {f.system} | Tier {f.tier} | Confidence: {f.confidence:.0%}")
|
|
2384
|
+
if f.monthly_waste_usd > 0:
|
|
2385
|
+
print(f" Est. waste: ${f.monthly_waste_usd:.2f}/month")
|
|
2386
|
+
if f.monthly_waste_tokens > 0:
|
|
2387
|
+
print(f" Tokens: {f.monthly_waste_tokens:,}/month")
|
|
2388
|
+
print(f" Fix: {f.recommendation}")
|
|
2389
|
+
if f.fix_snippet:
|
|
2390
|
+
for line in f.fix_snippet.split("\n"):
|
|
2391
|
+
print(f" {line}")
|
|
2392
|
+
|
|
2393
|
+
if total_monthly_waste > 0:
|
|
2394
|
+
print(f"\n {'=' * 50}")
|
|
2395
|
+
print(f" Total estimated waste: ${total_monthly_waste:.2f}/month")
|
|
2396
|
+
print()
|
|
2397
|
+
|
|
2398
|
+
|
|
2399
|
+
def cmd_report(args: list[str]):
|
|
2400
|
+
"""Generate a full fleet report combining scan + audit data."""
|
|
2401
|
+
days = 30
|
|
2402
|
+
target_system = None
|
|
2403
|
+
as_json = "--json" in args
|
|
2404
|
+
|
|
2405
|
+
for i, a in enumerate(args):
|
|
2406
|
+
if a == "--days" and i + 1 < len(args):
|
|
2407
|
+
try:
|
|
2408
|
+
days = int(args[i + 1])
|
|
2409
|
+
except ValueError:
|
|
2410
|
+
pass
|
|
2411
|
+
elif a == "--system" and i + 1 < len(args):
|
|
2412
|
+
target_system = args[i + 1]
|
|
2413
|
+
_require_known_system(target_system)
|
|
2414
|
+
|
|
2415
|
+
if not FLEET_DB.exists():
|
|
2416
|
+
print(" No fleet.db found. Run 'fleet.py scan' first.")
|
|
2417
|
+
sys.exit(1)
|
|
2418
|
+
|
|
2419
|
+
conn = _init_fleet_db()
|
|
2420
|
+
cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
2421
|
+
|
|
2422
|
+
# Summary stats
|
|
2423
|
+
where = "WHERE date >= ?"
|
|
2424
|
+
params: list = [cutoff]
|
|
2425
|
+
if target_system:
|
|
2426
|
+
where += " AND system = ?"
|
|
2427
|
+
params.append(target_system)
|
|
2428
|
+
|
|
2429
|
+
stats = conn.execute(f"""
|
|
2430
|
+
SELECT
|
|
2431
|
+
system,
|
|
2432
|
+
COUNT(*) as runs,
|
|
2433
|
+
SUM(input_tokens) as total_input,
|
|
2434
|
+
SUM(output_tokens) as total_output,
|
|
2435
|
+
SUM(cost_usd) as total_cost,
|
|
2436
|
+
SUM(CASE WHEN outcome = 'empty' THEN 1 ELSE 0 END) as empty_runs,
|
|
2437
|
+
SUM(CASE WHEN outcome = 'abandoned' THEN 1 ELSE 0 END) as abandoned_runs,
|
|
2438
|
+
AVG(duration_seconds) as avg_duration,
|
|
2439
|
+
COUNT(DISTINCT date) as active_days
|
|
2440
|
+
FROM fleet_runs
|
|
2441
|
+
{where}
|
|
2442
|
+
GROUP BY system
|
|
2443
|
+
""", params).fetchall()
|
|
2444
|
+
|
|
2445
|
+
# Waste findings
|
|
2446
|
+
waste_rows = conn.execute("""
|
|
2447
|
+
SELECT system, waste_type, severity, description, monthly_waste_usd, recommendation
|
|
2448
|
+
FROM fleet_waste
|
|
2449
|
+
ORDER BY monthly_waste_usd DESC
|
|
2450
|
+
""").fetchall()
|
|
2451
|
+
|
|
2452
|
+
conn.close()
|
|
2453
|
+
|
|
2454
|
+
if as_json:
|
|
2455
|
+
report = {
|
|
2456
|
+
"period_days": days,
|
|
2457
|
+
"systems": [],
|
|
2458
|
+
"waste_findings": [],
|
|
2459
|
+
"total_cost": 0,
|
|
2460
|
+
"total_waste": 0,
|
|
2461
|
+
}
|
|
2462
|
+
for row in stats:
|
|
2463
|
+
system_data = {
|
|
2464
|
+
"system": row[0], "runs": row[1],
|
|
2465
|
+
"total_input": row[2] or 0, "total_output": row[3] or 0,
|
|
2466
|
+
"total_cost": row[4] or 0, "empty_runs": row[5] or 0,
|
|
2467
|
+
"abandoned_runs": row[6] or 0, "avg_duration_s": row[7] or 0,
|
|
2468
|
+
"active_days": row[8] or 0,
|
|
2469
|
+
}
|
|
2470
|
+
report["systems"].append(system_data)
|
|
2471
|
+
report["total_cost"] += system_data["total_cost"]
|
|
2472
|
+
for wr in waste_rows:
|
|
2473
|
+
report["waste_findings"].append({
|
|
2474
|
+
"system": wr[0], "type": wr[1], "severity": wr[2],
|
|
2475
|
+
"description": wr[3], "monthly_waste_usd": wr[4] or 0,
|
|
2476
|
+
"recommendation": wr[5],
|
|
2477
|
+
})
|
|
2478
|
+
report["total_waste"] += wr[4] or 0
|
|
2479
|
+
print(json.dumps(report, indent=2))
|
|
2480
|
+
return
|
|
2481
|
+
|
|
2482
|
+
# Text report
|
|
2483
|
+
print("\n Fleet Report")
|
|
2484
|
+
print(" " + "=" * 60)
|
|
2485
|
+
print(f" Period: last {days} days")
|
|
2486
|
+
|
|
2487
|
+
total_cost = 0.0
|
|
2488
|
+
total_runs = 0
|
|
2489
|
+
|
|
2490
|
+
for row in stats:
|
|
2491
|
+
system, runs, inp, out, cost, empty, abandoned, avg_dur, active_days = row
|
|
2492
|
+
cost = cost or 0
|
|
2493
|
+
total_cost += cost
|
|
2494
|
+
total_runs += runs
|
|
2495
|
+
|
|
2496
|
+
adapter_name = system
|
|
2497
|
+
for ac in ADAPTER_REGISTRY:
|
|
2498
|
+
if ac.name == system:
|
|
2499
|
+
adapter_name = ac.display_name
|
|
2500
|
+
break
|
|
2501
|
+
|
|
2502
|
+
print(f"\n {adapter_name}")
|
|
2503
|
+
print(f" Runs: {runs} ({active_days or 0} active days)")
|
|
2504
|
+
print(f" Tokens: {(inp or 0):,} input / {(out or 0):,} output")
|
|
2505
|
+
print(f" Cost: ${cost:.2f}")
|
|
2506
|
+
if empty:
|
|
2507
|
+
print(f" Empty runs: {empty} ({empty/runs*100:.0f}%)")
|
|
2508
|
+
if abandoned:
|
|
2509
|
+
print(f" Abandoned: {abandoned}")
|
|
2510
|
+
if avg_dur:
|
|
2511
|
+
print(f" Avg duration: {avg_dur/60:.1f} min")
|
|
2512
|
+
|
|
2513
|
+
print(f"\n {'=' * 60}")
|
|
2514
|
+
print(f" Total: {total_runs} runs, ${total_cost:.2f}")
|
|
2515
|
+
|
|
2516
|
+
if waste_rows:
|
|
2517
|
+
total_waste = sum((wr[4] or 0) for wr in waste_rows)
|
|
2518
|
+
print(f"\n Waste detected: ${total_waste:.2f}/month potential savings")
|
|
2519
|
+
print(" Run 'fleet.py audit' for detailed recommendations.")
|
|
2520
|
+
print()
|
|
2521
|
+
|
|
2522
|
+
|
|
2523
|
+
def cmd_dashboard(args: list[str]):
|
|
2524
|
+
"""Generate and open the fleet dashboard."""
|
|
2525
|
+
serve = "--serve" in args
|
|
2526
|
+
serve_port = 8080
|
|
2527
|
+
serve_host = "127.0.0.1"
|
|
2528
|
+
|
|
2529
|
+
for i, a in enumerate(args):
|
|
2530
|
+
if a == "--port" and i + 1 < len(args):
|
|
2531
|
+
try:
|
|
2532
|
+
serve_port = int(args[i + 1])
|
|
2533
|
+
except ValueError:
|
|
2534
|
+
pass
|
|
2535
|
+
elif a == "--host" and i + 1 < len(args):
|
|
2536
|
+
serve_host = args[i + 1]
|
|
2537
|
+
|
|
2538
|
+
if not FLEET_DB.exists():
|
|
2539
|
+
print(" No fleet.db found. Run 'fleet.py scan' first.")
|
|
2540
|
+
sys.exit(1)
|
|
2541
|
+
|
|
2542
|
+
# Load data for dashboard
|
|
2543
|
+
conn = _init_fleet_db()
|
|
2544
|
+
daily_rows = conn.execute(
|
|
2545
|
+
"SELECT date, system, run_count, total_input, total_output, total_cost, empty_heartbeat_count "
|
|
2546
|
+
"FROM fleet_daily ORDER BY date"
|
|
2547
|
+
).fetchall()
|
|
2548
|
+
|
|
2549
|
+
waste_rows = conn.execute(
|
|
2550
|
+
"SELECT system, waste_type, tier, severity, confidence, description, "
|
|
2551
|
+
"monthly_waste_usd, monthly_waste_tokens, recommendation, fix_snippet "
|
|
2552
|
+
"FROM fleet_waste ORDER BY monthly_waste_usd DESC"
|
|
2553
|
+
).fetchall()
|
|
2554
|
+
|
|
2555
|
+
system_stats = conn.execute("""
|
|
2556
|
+
SELECT system, COUNT(*), SUM(cost_usd), SUM(input_tokens), SUM(output_tokens),
|
|
2557
|
+
AVG(duration_seconds), COUNT(DISTINCT date),
|
|
2558
|
+
SUM(CASE WHEN outcome='empty' THEN 1 ELSE 0 END),
|
|
2559
|
+
SUM(CASE WHEN outcome='abandoned' THEN 1 ELSE 0 END)
|
|
2560
|
+
FROM fleet_runs GROUP BY system
|
|
2561
|
+
""").fetchall()
|
|
2562
|
+
|
|
2563
|
+
# Model mix per system
|
|
2564
|
+
model_mix = conn.execute("""
|
|
2565
|
+
SELECT system, model, COUNT(*), SUM(cost_usd)
|
|
2566
|
+
FROM fleet_runs WHERE model IS NOT NULL AND model != ''
|
|
2567
|
+
GROUP BY system, model ORDER BY SUM(cost_usd) DESC
|
|
2568
|
+
""").fetchall()
|
|
2569
|
+
|
|
2570
|
+
# Top projects by cost
|
|
2571
|
+
top_projects = conn.execute("""
|
|
2572
|
+
SELECT project, COUNT(*), SUM(cost_usd), SUM(input_tokens + cache_read_tokens + cache_write_tokens)
|
|
2573
|
+
FROM fleet_runs WHERE project IS NOT NULL AND project != ''
|
|
2574
|
+
GROUP BY project ORDER BY SUM(cost_usd) DESC LIMIT 10
|
|
2575
|
+
""").fetchall()
|
|
2576
|
+
|
|
2577
|
+
# Models with real tokens but $0 cost because they have no pricing row.
|
|
2578
|
+
# Surface them so the dashboard's Total Cost reads as understated, not real.
|
|
2579
|
+
# NULL-safe: `cost_usd = 0` alone would drop NULL-cost rows (SQL NULL equality),
|
|
2580
|
+
# and a single NULL token column would NULL the whole row's `a+b+c+d` sum. Per-
|
|
2581
|
+
# column SUM ignores NULLs, and OR-IS-NULL matches audit's `... or 0` coercion.
|
|
2582
|
+
unpriced_rows = conn.execute("""
|
|
2583
|
+
SELECT model, COUNT(*),
|
|
2584
|
+
SUM(COALESCE(input_tokens, 0)) + SUM(COALESCE(output_tokens, 0))
|
|
2585
|
+
+ SUM(COALESCE(cache_read_tokens, 0)) + SUM(COALESCE(cache_write_tokens, 0))
|
|
2586
|
+
FROM fleet_runs
|
|
2587
|
+
WHERE (cost_usd = 0 OR cost_usd IS NULL) AND model IS NOT NULL AND model != ''
|
|
2588
|
+
GROUP BY model
|
|
2589
|
+
""").fetchall()
|
|
2590
|
+
unpriced_models = {
|
|
2591
|
+
r[0]: r[1] for r in unpriced_rows
|
|
2592
|
+
if (r[2] or 0) > 0 and not model_is_priced(r[0])
|
|
2593
|
+
}
|
|
2594
|
+
|
|
2595
|
+
conn.close()
|
|
2596
|
+
|
|
2597
|
+
# Generate dashboard HTML
|
|
2598
|
+
dashboard_html = _generate_dashboard_html(
|
|
2599
|
+
daily_rows, waste_rows, system_stats, model_mix, top_projects, unpriced_models)
|
|
2600
|
+
|
|
2601
|
+
FLEET_DASHBOARD_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
2602
|
+
# Atomic: write a sibling temp file and rename it onto the final path.
|
|
2603
|
+
# The old truncate-in-place write meant a second invocation could hand the
|
|
2604
|
+
# browser (still resolving the file association from the first one) a
|
|
2605
|
+
# zero-byte or half-written page, and on Windows a reader holding the file
|
|
2606
|
+
# without FILE_SHARE_WRITE made the truncate raise. os.replace is atomic on
|
|
2607
|
+
# POSIX and MoveFileExW+REPLACE_EXISTING on Windows.
|
|
2608
|
+
_tmp_dashboard = FLEET_DASHBOARD_PATH.with_name(
|
|
2609
|
+
FLEET_DASHBOARD_PATH.name + f".tmp.{os.getpid()}"
|
|
2610
|
+
)
|
|
2611
|
+
try:
|
|
2612
|
+
with open(_tmp_dashboard, "w", encoding="utf-8") as f:
|
|
2613
|
+
f.write(dashboard_html)
|
|
2614
|
+
os.replace(_tmp_dashboard, FLEET_DASHBOARD_PATH)
|
|
2615
|
+
except BaseException:
|
|
2616
|
+
try:
|
|
2617
|
+
_tmp_dashboard.unlink()
|
|
2618
|
+
except OSError:
|
|
2619
|
+
pass
|
|
2620
|
+
raise
|
|
2621
|
+
|
|
2622
|
+
print(f" Fleet dashboard generated: {FLEET_DASHBOARD_PATH}")
|
|
2623
|
+
|
|
2624
|
+
if serve:
|
|
2625
|
+
_serve_dashboard(serve_host, serve_port)
|
|
2626
|
+
else:
|
|
2627
|
+
_open_in_browser(FLEET_DASHBOARD_PATH)
|
|
2628
|
+
|
|
2629
|
+
|
|
2630
|
+
def _generate_dashboard_html(daily_rows, waste_rows, system_stats, model_mix, top_projects,
|
|
2631
|
+
unpriced_models=None) -> str:
|
|
2632
|
+
"""Generate standalone fleet dashboard HTML matching Token Optimizer design system."""
|
|
2633
|
+
import html as html_mod
|
|
2634
|
+
unpriced_models = unpriced_models or {}
|
|
2635
|
+
|
|
2636
|
+
# Prepare data
|
|
2637
|
+
daily_data = [{"date": r[0], "system": r[1], "runs": r[2], "input": r[3] or 0,
|
|
2638
|
+
"output": r[4] or 0, "cost": r[5] or 0, "empty_hb": r[6] or 0} for r in daily_rows]
|
|
2639
|
+
|
|
2640
|
+
waste_data = [{"system": r[0], "type": r[1], "tier": r[2], "severity": r[3], "confidence": r[4],
|
|
2641
|
+
"description": r[5], "monthly_usd": r[6] or 0, "monthly_tokens": r[7] or 0,
|
|
2642
|
+
"recommendation": r[8], "fix": r[9] or ""} for r in waste_rows]
|
|
2643
|
+
|
|
2644
|
+
systems_data = [{"system": r[0], "runs": r[1], "cost": r[2] or 0, "input": r[3] or 0,
|
|
2645
|
+
"output": r[4] or 0, "avg_dur": r[5] or 0, "active_days": r[6] or 0,
|
|
2646
|
+
"empty": r[7] or 0, "abandoned": r[8] or 0} for r in system_stats]
|
|
2647
|
+
|
|
2648
|
+
# Model mix grouped by system
|
|
2649
|
+
model_data = {}
|
|
2650
|
+
for r in model_mix:
|
|
2651
|
+
model_data.setdefault(r[0], []).append({"model": r[1], "runs": r[2], "cost": r[3] or 0})
|
|
2652
|
+
|
|
2653
|
+
project_data = [{"project": r[0], "runs": r[1], "cost": r[2] or 0, "tokens": r[3] or 0} for r in top_projects]
|
|
2654
|
+
|
|
2655
|
+
total_cost = sum(s["cost"] for s in systems_data)
|
|
2656
|
+
total_waste = sum(w["monthly_usd"] for w in waste_data)
|
|
2657
|
+
total_runs = sum(s["runs"] for s in systems_data)
|
|
2658
|
+
total_active_days = max((s["active_days"] for s in systems_data), default=0)
|
|
2659
|
+
sev_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
|
|
2660
|
+
for w in waste_data:
|
|
2661
|
+
sev_counts[w["severity"]] = sev_counts.get(w["severity"], 0) + 1
|
|
2662
|
+
|
|
2663
|
+
def esc(s):
|
|
2664
|
+
return html_mod.escape(str(s))
|
|
2665
|
+
|
|
2666
|
+
def fmt_tokens(n):
|
|
2667
|
+
if n >= 1_000_000_000:
|
|
2668
|
+
return f"{n/1e9:.1f}B"
|
|
2669
|
+
if n >= 1_000_000:
|
|
2670
|
+
return f"{n/1e6:.1f}M"
|
|
2671
|
+
if n >= 1_000:
|
|
2672
|
+
return f"{n/1e3:.1f}K"
|
|
2673
|
+
return str(n)
|
|
2674
|
+
|
|
2675
|
+
def fmt_cost(n):
|
|
2676
|
+
if n >= 1000:
|
|
2677
|
+
return f"${n:,.0f}"
|
|
2678
|
+
return f"${n:.2f}"
|
|
2679
|
+
|
|
2680
|
+
# System display names
|
|
2681
|
+
sys_names = {ac.name: ac.display_name for ac in [cls() for cls in ADAPTER_REGISTRY]}
|
|
2682
|
+
|
|
2683
|
+
# Daily chart data as JSON
|
|
2684
|
+
daily_json = json.dumps(daily_data)
|
|
2685
|
+
model_json = json.dumps(model_data)
|
|
2686
|
+
|
|
2687
|
+
# Build system cards
|
|
2688
|
+
sys_html = ""
|
|
2689
|
+
for s in systems_data:
|
|
2690
|
+
name = sys_names.get(s["system"], s["system"])
|
|
2691
|
+
pct_empty = (s["empty"] / s["runs"] * 100) if s["runs"] > 0 else 0
|
|
2692
|
+
sys_html += f'''
|
|
2693
|
+
<div class="card">
|
|
2694
|
+
<div class="card-header"><span>{esc(name)}</span><span class="label">{esc(s["system"])}</span></div>
|
|
2695
|
+
<div class="metric-large">{fmt_cost(s["cost"])}</div>
|
|
2696
|
+
<div class="metric-sub">{s["runs"]:,} runs over {s["active_days"]} days</div>
|
|
2697
|
+
<div class="mini-stats">
|
|
2698
|
+
<div class="mini-stat-item"><span class="mini-val">{s["avg_dur"]/60:.0f}m</span><span class="mini-label">avg duration</span></div>
|
|
2699
|
+
<div class="mini-stat-item"><span class="mini-val">{pct_empty:.0f}%</span><span class="mini-label">empty runs</span></div>
|
|
2700
|
+
<div class="mini-stat-item"><span class="mini-val">{s["abandoned"]}</span><span class="mini-label">abandoned</span></div>
|
|
2701
|
+
</div>
|
|
2702
|
+
</div>'''
|
|
2703
|
+
|
|
2704
|
+
# Build waste cards
|
|
2705
|
+
waste_html = ""
|
|
2706
|
+
severity_colors = {"critical": "var(--c-danger)", "high": "var(--c-warning)", "medium": "var(--c-accent-cyan)", "low": "var(--c-text-dim)"}
|
|
2707
|
+
for i, w in enumerate(waste_data):
|
|
2708
|
+
waste_html += f'''
|
|
2709
|
+
<div class="waste-card {esc(w["severity"])}">
|
|
2710
|
+
<div class="waste-header">
|
|
2711
|
+
<div>
|
|
2712
|
+
<span class="waste-severity {esc(w["severity"])}">{esc(w["severity"])}</span>
|
|
2713
|
+
<span class="waste-system">{esc(sys_names.get(w["system"], w["system"]))}</span>
|
|
2714
|
+
</div>
|
|
2715
|
+
{f'<span class="waste-savings">{fmt_cost(w["monthly_usd"])}/mo</span>' if w["monthly_usd"] > 0.01 else ''}
|
|
2716
|
+
</div>
|
|
2717
|
+
<div class="waste-desc">{esc(w["description"])}</div>
|
|
2718
|
+
<div class="waste-rec">{esc(w["recommendation"])}</div>
|
|
2719
|
+
{f'<div class="waste-fix">{esc(w["fix"])}</div>' if w["fix"] else ''}
|
|
2720
|
+
</div>'''
|
|
2721
|
+
|
|
2722
|
+
# Build project rows
|
|
2723
|
+
proj_html = ""
|
|
2724
|
+
for p in project_data[:8]:
|
|
2725
|
+
proj_html += f'''
|
|
2726
|
+
<div class="proj-row">
|
|
2727
|
+
<span class="proj-name">{esc(p["project"])}</span>
|
|
2728
|
+
<span class="proj-stat">{p["runs"]:,} runs</span>
|
|
2729
|
+
<span class="proj-stat">{fmt_tokens(p["tokens"])} tok</span>
|
|
2730
|
+
<span class="proj-cost">{fmt_cost(p["cost"])}</span>
|
|
2731
|
+
</div>'''
|
|
2732
|
+
|
|
2733
|
+
# Banner + Total-Cost asterisk when unpriced models are present, so the
|
|
2734
|
+
# dollar figure isn't read as complete/real.
|
|
2735
|
+
unpriced_banner = ""
|
|
2736
|
+
cost_asterisk = ""
|
|
2737
|
+
if unpriced_models:
|
|
2738
|
+
n_sessions = sum(unpriced_models.values())
|
|
2739
|
+
names = ", ".join(esc(m) for m in sorted(unpriced_models))
|
|
2740
|
+
cost_asterisk = "*"
|
|
2741
|
+
unpriced_banner = f'''
|
|
2742
|
+
<div class="unpriced-banner">
|
|
2743
|
+
<strong>⚠ Cost is understated.</strong>
|
|
2744
|
+
{n_sessions} session(s) ran on {len(unpriced_models)} model(s) with no pricing data
|
|
2745
|
+
({names}), counted here as <strong>$0.00 — unknown, not free</strong>.
|
|
2746
|
+
Add rates to <code>{esc(str(FLEET_DB_DIR / "pricing.json"))}</code> to price them.
|
|
2747
|
+
</div>'''
|
|
2748
|
+
|
|
2749
|
+
# Main dashboard link
|
|
2750
|
+
main_dash = FLEET_DB_DIR / "dashboard.html"
|
|
2751
|
+
back_link = f'<a class="nav-item nav-back" href="file://{main_dash}">Token Optimizer</a>' if main_dash.exists() else ''
|
|
2752
|
+
|
|
2753
|
+
return f'''<!DOCTYPE html>
|
|
2754
|
+
<html lang="en">
|
|
2755
|
+
<head>
|
|
2756
|
+
<meta charset="UTF-8">
|
|
2757
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
2758
|
+
<title>Fleet Auditor</title>
|
|
2759
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
2760
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
2761
|
+
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;500&family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
|
2762
|
+
<style>
|
|
2763
|
+
*, *::before, *::after {{ box-sizing: border-box; margin: 0; padding: 0; outline: none; }}
|
|
2764
|
+
:root {{
|
|
2765
|
+
--c-bg: #0a0b10;
|
|
2766
|
+
--c-surface: #13151a;
|
|
2767
|
+
--c-surface-hover: #1c1f26;
|
|
2768
|
+
--c-accent-cyan: #00f0ff;
|
|
2769
|
+
--c-accent-blue: #0066ff;
|
|
2770
|
+
--c-accent-glow: rgba(0, 240, 255, 0.4);
|
|
2771
|
+
--c-text-main: #ffffff;
|
|
2772
|
+
--c-text-dim: #7d8ca3;
|
|
2773
|
+
--c-border: rgba(255, 255, 255, 0.08);
|
|
2774
|
+
--c-success: #22c55e;
|
|
2775
|
+
--c-warning: #f59e0b;
|
|
2776
|
+
--c-danger: #ef4444;
|
|
2777
|
+
--font-sans: 'Space Grotesk', sans-serif;
|
|
2778
|
+
--font-mono: 'JetBrains Mono', monospace;
|
|
2779
|
+
--s-1: 4px; --s-2: 8px; --s-3: 16px; --s-4: 24px; --s-5: 32px; --s-6: 64px;
|
|
2780
|
+
--glow-sm: 0 0 10px var(--c-accent-glow);
|
|
2781
|
+
--glow-text: 0 0 8px rgba(0, 240, 255, 0.6);
|
|
2782
|
+
}}
|
|
2783
|
+
body {{
|
|
2784
|
+
background-color: var(--c-bg);
|
|
2785
|
+
color: var(--c-text-main);
|
|
2786
|
+
font-family: var(--font-sans);
|
|
2787
|
+
font-weight: 300;
|
|
2788
|
+
font-size: 18px;
|
|
2789
|
+
line-height: 1.5;
|
|
2790
|
+
min-height: 100vh;
|
|
2791
|
+
overflow-x: hidden;
|
|
2792
|
+
-webkit-font-smoothing: antialiased;
|
|
2793
|
+
background-image: radial-gradient(circle at 50% 0%, #1a253a 0%, var(--c-bg) 60%);
|
|
2794
|
+
}}
|
|
2795
|
+
body::before {{
|
|
2796
|
+
content: "";
|
|
2797
|
+
position: fixed;
|
|
2798
|
+
top: 0; left: 0; width: 100%; height: 100%;
|
|
2799
|
+
background-image:
|
|
2800
|
+
linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
|
|
2801
|
+
linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px);
|
|
2802
|
+
background-size: 40px 40px;
|
|
2803
|
+
pointer-events: none;
|
|
2804
|
+
z-index: 0;
|
|
2805
|
+
}}
|
|
2806
|
+
h1, h2, h3, h4 {{ font-weight: 400; }}
|
|
2807
|
+
::-webkit-scrollbar {{ width: 6px; }}
|
|
2808
|
+
::-webkit-scrollbar-track {{ background: var(--c-bg); }}
|
|
2809
|
+
::-webkit-scrollbar-thumb {{ background: #333; border-radius: 3px; }}
|
|
2810
|
+
::-webkit-scrollbar-thumb:hover {{ background: #555; }}
|
|
2811
|
+
|
|
2812
|
+
.layout {{
|
|
2813
|
+
display: grid;
|
|
2814
|
+
grid-template-columns: 260px 1fr 340px;
|
|
2815
|
+
height: 100vh;
|
|
2816
|
+
width: 100vw;
|
|
2817
|
+
max-width: 1800px;
|
|
2818
|
+
margin: 0 auto;
|
|
2819
|
+
position: relative;
|
|
2820
|
+
z-index: 1;
|
|
2821
|
+
}}
|
|
2822
|
+
|
|
2823
|
+
/* NAV */
|
|
2824
|
+
.nav-col {{
|
|
2825
|
+
padding: var(--s-4);
|
|
2826
|
+
border-right: 1px solid var(--c-border);
|
|
2827
|
+
display: flex;
|
|
2828
|
+
flex-direction: column;
|
|
2829
|
+
justify-content: space-between;
|
|
2830
|
+
background: linear-gradient(90deg, transparent, rgba(0,0,0,0.2));
|
|
2831
|
+
backdrop-filter: blur(10px);
|
|
2832
|
+
}}
|
|
2833
|
+
.brand {{
|
|
2834
|
+
font-family: var(--font-sans);
|
|
2835
|
+
font-weight: 700;
|
|
2836
|
+
font-size: 24px;
|
|
2837
|
+
margin-bottom: var(--s-5);
|
|
2838
|
+
display: flex;
|
|
2839
|
+
align-items: center;
|
|
2840
|
+
gap: var(--s-2);
|
|
2841
|
+
color: var(--c-text-main);
|
|
2842
|
+
letter-spacing: -0.02em;
|
|
2843
|
+
}}
|
|
2844
|
+
.brand span {{
|
|
2845
|
+
width: 12px; height: 12px;
|
|
2846
|
+
background: var(--c-accent-cyan);
|
|
2847
|
+
border-radius: 2px;
|
|
2848
|
+
display: inline-block;
|
|
2849
|
+
box-shadow: var(--glow-sm);
|
|
2850
|
+
}}
|
|
2851
|
+
.nav-menu {{ display: flex; flex-direction: column; gap: 2px; }}
|
|
2852
|
+
.nav-item {{
|
|
2853
|
+
padding: 12px var(--s-2);
|
|
2854
|
+
cursor: pointer;
|
|
2855
|
+
opacity: 0.6;
|
|
2856
|
+
transition: all 0.3s cubic-bezier(0.2, 0.8, 0.2, 1);
|
|
2857
|
+
text-decoration: none;
|
|
2858
|
+
color: var(--c-text-main);
|
|
2859
|
+
display: flex;
|
|
2860
|
+
justify-content: space-between;
|
|
2861
|
+
align-items: center;
|
|
2862
|
+
font-family: var(--font-sans);
|
|
2863
|
+
text-transform: uppercase;
|
|
2864
|
+
letter-spacing: 0.1em;
|
|
2865
|
+
font-size: 15px;
|
|
2866
|
+
border-left: 2px solid transparent;
|
|
2867
|
+
}}
|
|
2868
|
+
.nav-item:hover, .nav-item.active {{
|
|
2869
|
+
opacity: 1;
|
|
2870
|
+
background: linear-gradient(90deg, rgba(0,240,255,0.05), transparent);
|
|
2871
|
+
border-left-color: var(--c-accent-cyan);
|
|
2872
|
+
text-shadow: var(--glow-text);
|
|
2873
|
+
}}
|
|
2874
|
+
.nav-item.active {{ font-weight: 600; }}
|
|
2875
|
+
.nav-badge {{
|
|
2876
|
+
font-family: var(--font-mono);
|
|
2877
|
+
font-size: 13px;
|
|
2878
|
+
color: var(--c-accent-cyan);
|
|
2879
|
+
border: 1px solid var(--c-accent-cyan);
|
|
2880
|
+
padding: 0 4px;
|
|
2881
|
+
border-radius: 2px;
|
|
2882
|
+
text-shadow: 0 0 5px var(--c-accent-cyan);
|
|
2883
|
+
}}
|
|
2884
|
+
.nav-separator {{
|
|
2885
|
+
height: 1px;
|
|
2886
|
+
background: var(--c-border);
|
|
2887
|
+
margin: var(--s-2) 0;
|
|
2888
|
+
}}
|
|
2889
|
+
.nav-back {{
|
|
2890
|
+
opacity: 0.4;
|
|
2891
|
+
font-size: 13px;
|
|
2892
|
+
margin-top: var(--s-3);
|
|
2893
|
+
border-left: 2px solid transparent;
|
|
2894
|
+
}}
|
|
2895
|
+
.nav-back:hover {{ opacity: 0.8; border-left-color: var(--c-text-dim); }}
|
|
2896
|
+
.user-profile {{
|
|
2897
|
+
font-size: 15px;
|
|
2898
|
+
color: var(--c-text-dim);
|
|
2899
|
+
border-top: 1px solid var(--c-border);
|
|
2900
|
+
padding-top: var(--s-3);
|
|
2901
|
+
font-family: var(--font-mono);
|
|
2902
|
+
}}
|
|
2903
|
+
.user-profile i {{ font-style: italic; color: var(--c-accent-cyan); }}
|
|
2904
|
+
|
|
2905
|
+
/* MAIN */
|
|
2906
|
+
.main-col {{
|
|
2907
|
+
padding: var(--s-5);
|
|
2908
|
+
overflow-y: auto;
|
|
2909
|
+
display: flex;
|
|
2910
|
+
flex-direction: column;
|
|
2911
|
+
gap: var(--s-5);
|
|
2912
|
+
}}
|
|
2913
|
+
.view {{ display: none; }}
|
|
2914
|
+
.view.active {{ display: flex; flex-direction: column; gap: var(--s-5); }}
|
|
2915
|
+
.section-header {{ margin-bottom: var(--s-2); }}
|
|
2916
|
+
.label {{
|
|
2917
|
+
font-size: 14px;
|
|
2918
|
+
text-transform: uppercase;
|
|
2919
|
+
letter-spacing: 0.15em;
|
|
2920
|
+
color: var(--c-text-dim);
|
|
2921
|
+
font-family: var(--font-mono);
|
|
2922
|
+
font-weight: 500;
|
|
2923
|
+
}}
|
|
2924
|
+
.section-header h1 {{
|
|
2925
|
+
font-family: var(--font-sans);
|
|
2926
|
+
font-weight: 300;
|
|
2927
|
+
font-size: 48px;
|
|
2928
|
+
margin: var(--s-2) 0;
|
|
2929
|
+
line-height: 1;
|
|
2930
|
+
letter-spacing: -0.02em;
|
|
2931
|
+
background: linear-gradient(180deg, #fff, #aaa);
|
|
2932
|
+
-webkit-background-clip: text;
|
|
2933
|
+
-webkit-text-fill-color: transparent;
|
|
2934
|
+
}}
|
|
2935
|
+
.section-header p {{
|
|
2936
|
+
font-size: 12px;
|
|
2937
|
+
color: var(--c-text-dim);
|
|
2938
|
+
max-width: 460px;
|
|
2939
|
+
line-height: 1.6;
|
|
2940
|
+
font-family: var(--font-mono);
|
|
2941
|
+
}}
|
|
2942
|
+
|
|
2943
|
+
/* CARDS */
|
|
2944
|
+
.card {{
|
|
2945
|
+
background: var(--c-surface);
|
|
2946
|
+
border: 1px solid var(--c-border);
|
|
2947
|
+
border-radius: 12px;
|
|
2948
|
+
padding: var(--s-4);
|
|
2949
|
+
transition: border-color 0.3s;
|
|
2950
|
+
}}
|
|
2951
|
+
.card:hover {{ border-color: rgba(255,255,255,0.15); }}
|
|
2952
|
+
.card-header {{
|
|
2953
|
+
display: flex;
|
|
2954
|
+
justify-content: space-between;
|
|
2955
|
+
align-items: center;
|
|
2956
|
+
margin-bottom: var(--s-3);
|
|
2957
|
+
font-size: 15px;
|
|
2958
|
+
}}
|
|
2959
|
+
.card-header span:first-child {{ font-weight: 500; }}
|
|
2960
|
+
.dashboard-grid {{
|
|
2961
|
+
display: grid;
|
|
2962
|
+
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
|
2963
|
+
gap: var(--s-3);
|
|
2964
|
+
}}
|
|
2965
|
+
.metric-large {{
|
|
2966
|
+
font-family: var(--font-mono);
|
|
2967
|
+
font-size: 36px;
|
|
2968
|
+
font-weight: 500;
|
|
2969
|
+
color: var(--c-accent-cyan);
|
|
2970
|
+
text-shadow: var(--glow-text);
|
|
2971
|
+
margin-bottom: var(--s-1);
|
|
2972
|
+
}}
|
|
2973
|
+
.metric-sub {{
|
|
2974
|
+
font-size: 13px;
|
|
2975
|
+
color: var(--c-text-dim);
|
|
2976
|
+
font-family: var(--font-mono);
|
|
2977
|
+
}}
|
|
2978
|
+
.mini-stats {{
|
|
2979
|
+
display: flex;
|
|
2980
|
+
gap: var(--s-4);
|
|
2981
|
+
margin-top: var(--s-3);
|
|
2982
|
+
padding-top: var(--s-3);
|
|
2983
|
+
border-top: 1px solid var(--c-border);
|
|
2984
|
+
}}
|
|
2985
|
+
.mini-stat-item {{ display: flex; flex-direction: column; }}
|
|
2986
|
+
.mini-val {{
|
|
2987
|
+
font-family: var(--font-mono);
|
|
2988
|
+
font-size: 16px;
|
|
2989
|
+
color: var(--c-text-main);
|
|
2990
|
+
}}
|
|
2991
|
+
.mini-label {{
|
|
2992
|
+
font-size: 11px;
|
|
2993
|
+
text-transform: uppercase;
|
|
2994
|
+
letter-spacing: 0.1em;
|
|
2995
|
+
color: var(--c-text-dim);
|
|
2996
|
+
}}
|
|
2997
|
+
|
|
2998
|
+
/* HERO STATS */
|
|
2999
|
+
.stat-row {{
|
|
3000
|
+
display: grid;
|
|
3001
|
+
grid-template-columns: repeat(4, 1fr);
|
|
3002
|
+
gap: var(--s-3);
|
|
3003
|
+
margin-bottom: var(--s-4);
|
|
3004
|
+
}}
|
|
3005
|
+
.stat-card {{
|
|
3006
|
+
background: var(--c-surface);
|
|
3007
|
+
border: 1px solid var(--c-border);
|
|
3008
|
+
border-radius: 12px;
|
|
3009
|
+
padding: var(--s-4);
|
|
3010
|
+
text-align: center;
|
|
3011
|
+
}}
|
|
3012
|
+
.stat-card-value {{
|
|
3013
|
+
font-family: var(--font-mono);
|
|
3014
|
+
font-size: 32px;
|
|
3015
|
+
font-weight: 500;
|
|
3016
|
+
color: var(--c-accent-cyan);
|
|
3017
|
+
text-shadow: var(--glow-text);
|
|
3018
|
+
}}
|
|
3019
|
+
.stat-card-label {{
|
|
3020
|
+
font-size: 11px;
|
|
3021
|
+
text-transform: uppercase;
|
|
3022
|
+
letter-spacing: 0.15em;
|
|
3023
|
+
color: var(--c-text-dim);
|
|
3024
|
+
margin-top: var(--s-1);
|
|
3025
|
+
}}
|
|
3026
|
+
|
|
3027
|
+
/* WASTE */
|
|
3028
|
+
.waste-card {{
|
|
3029
|
+
background: var(--c-surface);
|
|
3030
|
+
border: 1px solid var(--c-border);
|
|
3031
|
+
border-radius: 12px;
|
|
3032
|
+
padding: var(--s-4);
|
|
3033
|
+
margin-bottom: var(--s-3);
|
|
3034
|
+
border-left: 3px solid var(--c-text-dim);
|
|
3035
|
+
transition: border-color 0.3s;
|
|
3036
|
+
}}
|
|
3037
|
+
.waste-card.critical {{ border-left-color: var(--c-danger); }}
|
|
3038
|
+
.waste-card.high {{ border-left-color: var(--c-warning); }}
|
|
3039
|
+
.waste-card.medium {{ border-left-color: var(--c-accent-cyan); }}
|
|
3040
|
+
.waste-header {{
|
|
3041
|
+
display: flex;
|
|
3042
|
+
justify-content: space-between;
|
|
3043
|
+
align-items: center;
|
|
3044
|
+
margin-bottom: var(--s-2);
|
|
3045
|
+
}}
|
|
3046
|
+
.waste-severity {{
|
|
3047
|
+
font-size: 11px;
|
|
3048
|
+
font-weight: 600;
|
|
3049
|
+
text-transform: uppercase;
|
|
3050
|
+
letter-spacing: 0.1em;
|
|
3051
|
+
padding: 2px 8px;
|
|
3052
|
+
border-radius: 3px;
|
|
3053
|
+
margin-right: var(--s-2);
|
|
3054
|
+
}}
|
|
3055
|
+
.waste-severity.critical {{ background: rgba(239,68,68,0.2); color: var(--c-danger); }}
|
|
3056
|
+
.waste-severity.high {{ background: rgba(245,158,11,0.2); color: var(--c-warning); }}
|
|
3057
|
+
.waste-severity.medium {{ background: rgba(0,240,255,0.1); color: var(--c-accent-cyan); }}
|
|
3058
|
+
.waste-severity.low {{ background: rgba(125,140,163,0.1); color: var(--c-text-dim); }}
|
|
3059
|
+
.waste-system {{ font-size: 13px; color: var(--c-text-dim); }}
|
|
3060
|
+
.waste-desc {{ font-size: 16px; margin-bottom: var(--s-2); }}
|
|
3061
|
+
.waste-rec {{ font-size: 14px; color: var(--c-text-dim); margin-bottom: var(--s-2); }}
|
|
3062
|
+
.waste-savings {{
|
|
3063
|
+
font-family: var(--font-mono);
|
|
3064
|
+
font-size: 16px;
|
|
3065
|
+
color: var(--c-success);
|
|
3066
|
+
text-shadow: 0 0 6px rgba(34,197,94,0.4);
|
|
3067
|
+
}}
|
|
3068
|
+
.waste-fix {{
|
|
3069
|
+
margin-top: var(--s-2);
|
|
3070
|
+
padding: var(--s-2) var(--s-3);
|
|
3071
|
+
background: rgba(0,0,0,0.3);
|
|
3072
|
+
border-radius: 6px;
|
|
3073
|
+
font-family: var(--font-mono);
|
|
3074
|
+
font-size: 13px;
|
|
3075
|
+
color: var(--c-text-dim);
|
|
3076
|
+
white-space: pre-wrap;
|
|
3077
|
+
line-height: 1.6;
|
|
3078
|
+
}}
|
|
3079
|
+
|
|
3080
|
+
/* CHART (daily cost bars) */
|
|
3081
|
+
.chart-container {{ padding: var(--s-2) 0; }}
|
|
3082
|
+
.bar-chart {{
|
|
3083
|
+
display: flex;
|
|
3084
|
+
align-items: flex-end;
|
|
3085
|
+
gap: 2px;
|
|
3086
|
+
height: 120px;
|
|
3087
|
+
padding-top: var(--s-2);
|
|
3088
|
+
}}
|
|
3089
|
+
.bar {{
|
|
3090
|
+
flex: 1;
|
|
3091
|
+
background: var(--c-accent-cyan);
|
|
3092
|
+
border-radius: 2px 2px 0 0;
|
|
3093
|
+
min-width: 4px;
|
|
3094
|
+
opacity: 0.7;
|
|
3095
|
+
transition: opacity 0.2s;
|
|
3096
|
+
position: relative;
|
|
3097
|
+
}}
|
|
3098
|
+
.bar:hover {{ opacity: 1; }}
|
|
3099
|
+
.bar-label {{
|
|
3100
|
+
display: flex;
|
|
3101
|
+
justify-content: space-between;
|
|
3102
|
+
font-size: 11px;
|
|
3103
|
+
color: var(--c-text-dim);
|
|
3104
|
+
font-family: var(--font-mono);
|
|
3105
|
+
margin-top: var(--s-1);
|
|
3106
|
+
}}
|
|
3107
|
+
|
|
3108
|
+
/* PROJECTS */
|
|
3109
|
+
.proj-row {{
|
|
3110
|
+
display: flex;
|
|
3111
|
+
align-items: center;
|
|
3112
|
+
gap: var(--s-3);
|
|
3113
|
+
padding: var(--s-2) 0;
|
|
3114
|
+
border-bottom: 1px solid var(--c-border);
|
|
3115
|
+
font-size: 14px;
|
|
3116
|
+
}}
|
|
3117
|
+
.proj-row:last-child {{ border-bottom: none; }}
|
|
3118
|
+
.proj-name {{ flex: 1; font-weight: 400; }}
|
|
3119
|
+
.proj-stat {{ color: var(--c-text-dim); font-family: var(--font-mono); font-size: 13px; min-width: 80px; text-align: right; }}
|
|
3120
|
+
.proj-cost {{ font-family: var(--font-mono); font-size: 13px; color: var(--c-accent-cyan); min-width: 70px; text-align: right; }}
|
|
3121
|
+
|
|
3122
|
+
/* MODEL BAR */
|
|
3123
|
+
.model-bar {{
|
|
3124
|
+
display: flex;
|
|
3125
|
+
height: 24px;
|
|
3126
|
+
border-radius: 6px;
|
|
3127
|
+
overflow: hidden;
|
|
3128
|
+
margin-bottom: var(--s-2);
|
|
3129
|
+
}}
|
|
3130
|
+
.model-segment {{ transition: width 0.5s; }}
|
|
3131
|
+
.model-segment.fable {{ background: #e11d48; }}
|
|
3132
|
+
.model-segment.opus {{ background: #a855f7; }}
|
|
3133
|
+
.model-segment.sonnet {{ background: #3b82f6; }}
|
|
3134
|
+
.model-segment.haiku {{ background: #22c55e; }}
|
|
3135
|
+
.model-segment.other {{ background: #6b7280; }}
|
|
3136
|
+
.model-legend {{
|
|
3137
|
+
display: flex;
|
|
3138
|
+
gap: var(--s-3);
|
|
3139
|
+
flex-wrap: wrap;
|
|
3140
|
+
font-size: 12px;
|
|
3141
|
+
font-family: var(--font-mono);
|
|
3142
|
+
color: var(--c-text-dim);
|
|
3143
|
+
}}
|
|
3144
|
+
.model-legend-item {{ display: flex; align-items: center; gap: 6px; }}
|
|
3145
|
+
.model-legend-dot {{ width: 8px; height: 8px; border-radius: 2px; }}
|
|
3146
|
+
.model-legend-dot.fable {{ background: #e11d48; }}
|
|
3147
|
+
.model-legend-dot.opus {{ background: #a855f7; }}
|
|
3148
|
+
.model-legend-dot.sonnet {{ background: #3b82f6; }}
|
|
3149
|
+
.model-legend-dot.haiku {{ background: #22c55e; }}
|
|
3150
|
+
.model-legend-dot.other {{ background: #6b7280; }}
|
|
3151
|
+
|
|
3152
|
+
/* RIGHT PANEL */
|
|
3153
|
+
.config-col {{
|
|
3154
|
+
border-left: 1px solid var(--c-border);
|
|
3155
|
+
padding: var(--s-4);
|
|
3156
|
+
background: rgba(10,11,16,0.8);
|
|
3157
|
+
display: flex;
|
|
3158
|
+
flex-direction: column;
|
|
3159
|
+
gap: var(--s-4);
|
|
3160
|
+
overflow-y: auto;
|
|
3161
|
+
}}
|
|
3162
|
+
.section-title {{
|
|
3163
|
+
font-size: 14px;
|
|
3164
|
+
text-transform: uppercase;
|
|
3165
|
+
letter-spacing: 0.2em;
|
|
3166
|
+
margin-bottom: var(--s-3);
|
|
3167
|
+
color: var(--c-text-dim);
|
|
3168
|
+
padding-bottom: var(--s-1);
|
|
3169
|
+
border-bottom: 1px solid var(--c-border);
|
|
3170
|
+
font-family: var(--font-mono);
|
|
3171
|
+
}}
|
|
3172
|
+
.summary-metric {{
|
|
3173
|
+
font-family: var(--font-mono);
|
|
3174
|
+
font-size: 18px;
|
|
3175
|
+
color: var(--c-text-dim);
|
|
3176
|
+
margin-bottom: var(--s-3);
|
|
3177
|
+
}}
|
|
3178
|
+
.summary-metric .num {{
|
|
3179
|
+
color: var(--c-accent-cyan);
|
|
3180
|
+
text-shadow: var(--glow-text);
|
|
3181
|
+
}}
|
|
3182
|
+
.version-footer {{
|
|
3183
|
+
margin-top: auto;
|
|
3184
|
+
padding-top: var(--s-4);
|
|
3185
|
+
border-top: 1px solid var(--c-border);
|
|
3186
|
+
font-size: 13px;
|
|
3187
|
+
color: var(--c-text-dim);
|
|
3188
|
+
display: flex;
|
|
3189
|
+
justify-content: space-between;
|
|
3190
|
+
align-items: center;
|
|
3191
|
+
}}
|
|
3192
|
+
.version-footer a {{ color: var(--c-accent-cyan); text-decoration: none; }}
|
|
3193
|
+
.social-icons {{ display: flex; gap: var(--s-2); }}
|
|
3194
|
+
.social-link {{ color: var(--c-text-dim); transition: color 0.2s; }}
|
|
3195
|
+
.social-link:hover {{ color: var(--c-accent-cyan); }}
|
|
3196
|
+
|
|
3197
|
+
.empty-state {{
|
|
3198
|
+
text-align: center;
|
|
3199
|
+
padding: var(--s-6) var(--s-4);
|
|
3200
|
+
color: var(--c-text-dim);
|
|
3201
|
+
font-family: var(--font-mono);
|
|
3202
|
+
font-size: 14px;
|
|
3203
|
+
}}
|
|
3204
|
+
|
|
3205
|
+
@media (max-width: 1100px) {{
|
|
3206
|
+
.layout {{ grid-template-columns: 1fr; height: auto; }}
|
|
3207
|
+
.nav-col {{ display: none; }}
|
|
3208
|
+
.config-col {{ display: none; }}
|
|
3209
|
+
.stat-row {{ grid-template-columns: repeat(2, 1fr); }}
|
|
3210
|
+
}}
|
|
3211
|
+
.unpriced-banner {{
|
|
3212
|
+
background: rgba(245, 158, 11, 0.08);
|
|
3213
|
+
border: 1px solid var(--c-warning);
|
|
3214
|
+
border-radius: 8px;
|
|
3215
|
+
padding: var(--s-3);
|
|
3216
|
+
margin-bottom: var(--s-4);
|
|
3217
|
+
font-size: 15px;
|
|
3218
|
+
color: var(--c-text-main);
|
|
3219
|
+
line-height: 1.6;
|
|
3220
|
+
}}
|
|
3221
|
+
.unpriced-banner code {{
|
|
3222
|
+
font-family: var(--font-mono);
|
|
3223
|
+
font-size: 13px;
|
|
3224
|
+
color: var(--c-warning);
|
|
3225
|
+
word-break: break-all;
|
|
3226
|
+
}}
|
|
3227
|
+
</style>
|
|
3228
|
+
</head>
|
|
3229
|
+
<body>
|
|
3230
|
+
|
|
3231
|
+
<div class="layout">
|
|
3232
|
+
<!-- NAV -->
|
|
3233
|
+
<nav class="nav-col">
|
|
3234
|
+
<div>
|
|
3235
|
+
<div class="brand"><span></span> Fleet Auditor</div>
|
|
3236
|
+
<div class="nav-menu">
|
|
3237
|
+
<a class="nav-item active" data-view="overview">Overview</a>
|
|
3238
|
+
<a class="nav-item" data-view="waste">Waste <span class="nav-badge">{len(waste_data)}</span></a>
|
|
3239
|
+
<a class="nav-item" data-view="systems">Systems</a>
|
|
3240
|
+
<a class="nav-item" data-view="daily">Daily</a>
|
|
3241
|
+
<div class="nav-separator"></div>
|
|
3242
|
+
{back_link}
|
|
3243
|
+
</div>
|
|
3244
|
+
</div>
|
|
3245
|
+
<div class="user-profile">generated: <i>{datetime.now().strftime("%Y-%m-%d %H:%M")}</i></div>
|
|
3246
|
+
</nav>
|
|
3247
|
+
|
|
3248
|
+
<!-- MAIN -->
|
|
3249
|
+
<main class="main-col">
|
|
3250
|
+
<!-- Overview -->
|
|
3251
|
+
<div class="view active" id="view-overview">
|
|
3252
|
+
<div class="section-header">
|
|
3253
|
+
<div class="label">Fleet Token Audit</div>
|
|
3254
|
+
<h1>Overview</h1>
|
|
3255
|
+
<p>Cross-platform agent token usage and waste detection.</p>
|
|
3256
|
+
</div>
|
|
3257
|
+
{unpriced_banner}
|
|
3258
|
+
<div class="stat-row">
|
|
3259
|
+
<div class="stat-card">
|
|
3260
|
+
<div class="stat-card-value">{total_runs:,}</div>
|
|
3261
|
+
<div class="stat-card-label">Total Runs</div>
|
|
3262
|
+
</div>
|
|
3263
|
+
<div class="stat-card">
|
|
3264
|
+
<div class="stat-card-value">{fmt_cost(total_cost)}{cost_asterisk}</div>
|
|
3265
|
+
<div class="stat-card-label">Total Cost{" (understated)" if unpriced_models else ""}</div>
|
|
3266
|
+
</div>
|
|
3267
|
+
<div class="stat-card">
|
|
3268
|
+
<div class="stat-card-value">{len(systems_data)}</div>
|
|
3269
|
+
<div class="stat-card-label">Systems</div>
|
|
3270
|
+
</div>
|
|
3271
|
+
<div class="stat-card">
|
|
3272
|
+
<div class="stat-card-value" style="color: var(--c-success)">{fmt_cost(total_waste)}/mo</div>
|
|
3273
|
+
<div class="stat-card-label">Potential Savings</div>
|
|
3274
|
+
</div>
|
|
3275
|
+
</div>
|
|
3276
|
+
|
|
3277
|
+
<div class="dashboard-grid">
|
|
3278
|
+
{sys_html if sys_html else '<div class="empty-state">No systems scanned yet.<br>Run: python3 fleet.py scan</div>'}
|
|
3279
|
+
</div>
|
|
3280
|
+
</div>
|
|
3281
|
+
|
|
3282
|
+
<!-- Waste -->
|
|
3283
|
+
<div class="view" id="view-waste">
|
|
3284
|
+
<div class="section-header">
|
|
3285
|
+
<div class="label">Waste Detection</div>
|
|
3286
|
+
<h1>Findings</h1>
|
|
3287
|
+
<p>Identified waste patterns with dollar savings estimates and fix snippets.</p>
|
|
3288
|
+
</div>
|
|
3289
|
+
{waste_html if waste_html else '<div class="empty-state">No waste patterns detected.<br>Run: python3 fleet.py audit</div>'}
|
|
3290
|
+
</div>
|
|
3291
|
+
|
|
3292
|
+
<!-- Systems -->
|
|
3293
|
+
<div class="view" id="view-systems">
|
|
3294
|
+
<div class="section-header">
|
|
3295
|
+
<div class="label">System Breakdown</div>
|
|
3296
|
+
<h1>Systems</h1>
|
|
3297
|
+
<p>Per-system usage, model mix, and top projects.</p>
|
|
3298
|
+
</div>
|
|
3299
|
+
<div class="dashboard-grid">
|
|
3300
|
+
{sys_html if sys_html else '<div class="empty-state">No data yet.</div>'}
|
|
3301
|
+
</div>
|
|
3302
|
+
<div class="card" id="model-mix-card" style="margin-top: var(--s-3);">
|
|
3303
|
+
<div class="card-header"><span>Model Mix</span><span class="label">Cost distribution by model</span></div>
|
|
3304
|
+
<div id="model-mix-content"></div>
|
|
3305
|
+
</div>
|
|
3306
|
+
<div class="card" style="margin-top: var(--s-3);">
|
|
3307
|
+
<div class="card-header"><span>Top Projects</span><span class="label">By total cost</span></div>
|
|
3308
|
+
{proj_html if proj_html else '<div class="empty-state" style="padding: var(--s-3);">No project data.</div>'}
|
|
3309
|
+
</div>
|
|
3310
|
+
</div>
|
|
3311
|
+
|
|
3312
|
+
<!-- Daily -->
|
|
3313
|
+
<div class="view" id="view-daily">
|
|
3314
|
+
<div class="section-header">
|
|
3315
|
+
<div class="label">Time Series</div>
|
|
3316
|
+
<h1>Daily</h1>
|
|
3317
|
+
<p>Daily cost and run count over the scan window.</p>
|
|
3318
|
+
</div>
|
|
3319
|
+
<div class="card">
|
|
3320
|
+
<div class="card-header"><span>Daily Cost</span></div>
|
|
3321
|
+
<div class="chart-container">
|
|
3322
|
+
<div class="bar-chart" id="daily-chart"></div>
|
|
3323
|
+
<div class="bar-label" id="daily-labels"></div>
|
|
3324
|
+
</div>
|
|
3325
|
+
</div>
|
|
3326
|
+
<div class="card" style="margin-top: var(--s-3);">
|
|
3327
|
+
<div class="card-header"><span>Daily Runs</span></div>
|
|
3328
|
+
<div class="chart-container">
|
|
3329
|
+
<div class="bar-chart" id="runs-chart"></div>
|
|
3330
|
+
<div class="bar-label" id="runs-labels"></div>
|
|
3331
|
+
</div>
|
|
3332
|
+
</div>
|
|
3333
|
+
</div>
|
|
3334
|
+
</main>
|
|
3335
|
+
|
|
3336
|
+
<!-- RIGHT PANEL -->
|
|
3337
|
+
<aside class="config-col">
|
|
3338
|
+
<div class="section-title">Fleet Summary</div>
|
|
3339
|
+
<div class="summary-metric"><span class="num">{total_runs:,}</span> runs</div>
|
|
3340
|
+
<div class="summary-metric"><span class="num">{fmt_cost(total_cost)}</span> total</div>
|
|
3341
|
+
<div class="summary-metric"><span class="num">{total_active_days}</span> active days</div>
|
|
3342
|
+
|
|
3343
|
+
<div class="section-title">Waste Breakdown</div>
|
|
3344
|
+
<div class="summary-metric" style="font-size:14px;">
|
|
3345
|
+
{"".join(f'<div style="margin-bottom:4px;"><span style="color:{severity_colors.get(sev, "var(--c-text-dim)")}">{count}</span> {sev}</div>' for sev, count in sev_counts.items() if count > 0) or '<span style="color:var(--c-success)">Clean fleet</span>'}
|
|
3346
|
+
</div>
|
|
3347
|
+
<div class="summary-metric">
|
|
3348
|
+
Potential savings: <span class="num">{fmt_cost(total_waste)}/mo</span>
|
|
3349
|
+
</div>
|
|
3350
|
+
|
|
3351
|
+
<div class="section-title">Quick Commands</div>
|
|
3352
|
+
<div style="font-family: var(--font-mono); font-size: 12px; color: var(--c-text-dim); line-height: 2;">
|
|
3353
|
+
<div>fleet.py detect</div>
|
|
3354
|
+
<div>fleet.py scan --days 30</div>
|
|
3355
|
+
<div>fleet.py audit --json</div>
|
|
3356
|
+
<div>fleet.py report</div>
|
|
3357
|
+
<div>fleet.py dashboard</div>
|
|
3358
|
+
</div>
|
|
3359
|
+
|
|
3360
|
+
<div class="version-footer">
|
|
3361
|
+
<div>Built by <a href="https://linkedin.com/in/alexgreensh" target="_blank" rel="noopener">Alex Greenshpun</a></div>
|
|
3362
|
+
<div class="social-icons">
|
|
3363
|
+
<a href="https://github.com/alexgreensh/token-optimizer" target="_blank" rel="noopener" title="GitHub" class="social-link">
|
|
3364
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>
|
|
3365
|
+
</a>
|
|
3366
|
+
<a href="https://linkedin.com/in/alexgreensh" target="_blank" rel="noopener" title="LinkedIn" class="social-link">
|
|
3367
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
|
|
3368
|
+
</a>
|
|
3369
|
+
</div>
|
|
3370
|
+
</div>
|
|
3371
|
+
</aside>
|
|
3372
|
+
</div>
|
|
3373
|
+
|
|
3374
|
+
<script>
|
|
3375
|
+
var dailyData = {daily_json};
|
|
3376
|
+
var modelData = {model_json};
|
|
3377
|
+
|
|
3378
|
+
function esc(s) {{ return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }}
|
|
3379
|
+
function fmtCost(n) {{ return n >= 1000 ? '$' + n.toLocaleString(undefined, {{maximumFractionDigits:0}}) : '$' + n.toFixed(2); }}
|
|
3380
|
+
|
|
3381
|
+
// Nav switching
|
|
3382
|
+
document.querySelectorAll('.nav-item[data-view]').forEach(function(lnk) {{
|
|
3383
|
+
lnk.addEventListener('click', function(e) {{
|
|
3384
|
+
e.preventDefault();
|
|
3385
|
+
var v = this.getAttribute('data-view');
|
|
3386
|
+
document.querySelectorAll('.view').forEach(function(el) {{ el.classList.remove('active'); }});
|
|
3387
|
+
document.querySelectorAll('.nav-item').forEach(function(n) {{ n.classList.remove('active'); }});
|
|
3388
|
+
var target = document.getElementById('view-' + v);
|
|
3389
|
+
if (target) target.classList.add('active');
|
|
3390
|
+
this.classList.add('active');
|
|
3391
|
+
document.querySelector('.main-col').scrollTop = 0;
|
|
3392
|
+
}});
|
|
3393
|
+
}});
|
|
3394
|
+
|
|
3395
|
+
// Daily cost chart
|
|
3396
|
+
(function() {{
|
|
3397
|
+
var chart = document.getElementById('daily-chart');
|
|
3398
|
+
var labels = document.getElementById('daily-labels');
|
|
3399
|
+
if (!chart || !dailyData.length) return;
|
|
3400
|
+
|
|
3401
|
+
// Aggregate by date
|
|
3402
|
+
var byDate = {{}};
|
|
3403
|
+
dailyData.forEach(function(d) {{
|
|
3404
|
+
byDate[d.date] = (byDate[d.date] || 0) + d.cost;
|
|
3405
|
+
}});
|
|
3406
|
+
var dates = Object.keys(byDate).sort();
|
|
3407
|
+
var maxCost = Math.max.apply(null, dates.map(function(d) {{ return byDate[d]; }})) || 1;
|
|
3408
|
+
|
|
3409
|
+
dates.forEach(function(date) {{
|
|
3410
|
+
var bar = document.createElement('div');
|
|
3411
|
+
bar.className = 'bar';
|
|
3412
|
+
bar.style.height = Math.max(2, (byDate[date] / maxCost) * 100) + '%';
|
|
3413
|
+
bar.title = date + ': ' + fmtCost(byDate[date]);
|
|
3414
|
+
chart.appendChild(bar);
|
|
3415
|
+
}});
|
|
3416
|
+
|
|
3417
|
+
if (dates.length > 0) {{
|
|
3418
|
+
labels.innerHTML = '<span>' + dates[0] + '</span><span>' + dates[dates.length - 1] + '</span>';
|
|
3419
|
+
}}
|
|
3420
|
+
|
|
3421
|
+
// Runs chart
|
|
3422
|
+
var runsChart = document.getElementById('runs-chart');
|
|
3423
|
+
var runsLabels = document.getElementById('runs-labels');
|
|
3424
|
+
if (!runsChart) return;
|
|
3425
|
+
var byDateRuns = {{}};
|
|
3426
|
+
dailyData.forEach(function(d) {{
|
|
3427
|
+
byDateRuns[d.date] = (byDateRuns[d.date] || 0) + d.runs;
|
|
3428
|
+
}});
|
|
3429
|
+
var maxRuns = Math.max.apply(null, dates.map(function(d) {{ return byDateRuns[d] || 0; }})) || 1;
|
|
3430
|
+
dates.forEach(function(date) {{
|
|
3431
|
+
var bar = document.createElement('div');
|
|
3432
|
+
bar.className = 'bar';
|
|
3433
|
+
bar.style.height = Math.max(2, ((byDateRuns[date] || 0) / maxRuns) * 100) + '%';
|
|
3434
|
+
bar.style.background = '#3b82f6';
|
|
3435
|
+
bar.title = date + ': ' + (byDateRuns[date] || 0) + ' runs';
|
|
3436
|
+
runsChart.appendChild(bar);
|
|
3437
|
+
}});
|
|
3438
|
+
if (dates.length > 0) {{
|
|
3439
|
+
runsLabels.innerHTML = '<span>' + dates[0] + '</span><span>' + dates[dates.length - 1] + '</span>';
|
|
3440
|
+
}}
|
|
3441
|
+
}})();
|
|
3442
|
+
|
|
3443
|
+
// Model mix
|
|
3444
|
+
(function() {{
|
|
3445
|
+
var container = document.getElementById('model-mix-content');
|
|
3446
|
+
if (!container) return;
|
|
3447
|
+
var html = '';
|
|
3448
|
+
|
|
3449
|
+
for (var sys in modelData) {{
|
|
3450
|
+
var models = modelData[sys];
|
|
3451
|
+
var totalCost = 0;
|
|
3452
|
+
models.forEach(function(m) {{ totalCost += m.cost; }});
|
|
3453
|
+
if (totalCost <= 0) continue;
|
|
3454
|
+
|
|
3455
|
+
html += '<div style="margin-bottom: var(--s-3);"><div style="font-size:13px;color:var(--c-text-dim);margin-bottom:4px;">' + esc(sys) + '</div>';
|
|
3456
|
+
html += '<div class="model-bar">';
|
|
3457
|
+
models.forEach(function(m) {{
|
|
3458
|
+
var pct = (m.cost / totalCost * 100).toFixed(1);
|
|
3459
|
+
var cls = m.model.replace(/[^a-z0-9-]/g, '');
|
|
3460
|
+
html += '<div class="model-segment ' + cls + '" style="width:' + pct + '%" title="' + esc(m.model) + ': ' + pct + '% (' + fmtCost(m.cost) + ')"></div>';
|
|
3461
|
+
}});
|
|
3462
|
+
html += '</div><div class="model-legend">';
|
|
3463
|
+
models.forEach(function(m) {{
|
|
3464
|
+
var pct = (m.cost / totalCost * 100).toFixed(0);
|
|
3465
|
+
var cls = m.model.replace(/[^a-z0-9-]/g, '');
|
|
3466
|
+
html += '<div class="model-legend-item"><div class="model-legend-dot ' + cls + '"></div>' + esc(m.model) + ' ' + pct + '% (' + fmtCost(m.cost) + ')</div>';
|
|
3467
|
+
}});
|
|
3468
|
+
html += '</div></div>';
|
|
3469
|
+
}}
|
|
3470
|
+
|
|
3471
|
+
container.innerHTML = html || '<div class="empty-state" style="padding:var(--s-3);">No model data.</div>';
|
|
3472
|
+
}})();
|
|
3473
|
+
</script>
|
|
3474
|
+
</body>
|
|
3475
|
+
</html>'''
|
|
3476
|
+
|
|
3477
|
+
|
|
3478
|
+
def _open_in_browser(path: Path):
|
|
3479
|
+
"""Open a file in the default browser.
|
|
3480
|
+
|
|
3481
|
+
Windows: ``os.startfile`` -- the same helper ``measure.py::_open_in_browser``
|
|
3482
|
+
uses. Two earlier shapes were both wrong.
|
|
3483
|
+
|
|
3484
|
+
1. ``subprocess.run(["start", path], shell=True)`` (the original shape): ``shell=True``
|
|
3485
|
+
routes through ``cmd.exe /c``, a console-subsystem binary, so a
|
|
3486
|
+
console-less host (the Claude Desktop app) gets a brand-new console
|
|
3487
|
+
allocated -- the cmd window users saw flash. ``start`` is also a
|
|
3488
|
+
cmd BUILTIN, so without the shell there is no ``start.exe`` to exec.
|
|
3489
|
+
2. ``subprocess.run(["cmd", "/c", "start", "", path], creationflags=...)``
|
|
3490
|
+
(the first fix): dropping ``shell=True`` removed PYTHON's shell, not
|
|
3491
|
+
cmd.exe's PARSER. ``subprocess.list2cmdline`` quotes an argument only when
|
|
3492
|
+
it contains a space, tab or quote -- never on ``&``, ``^``, ``|``, ``(``,
|
|
3493
|
+
``)``. ``&`` is a LEGAL Windows account-name character, so a real path
|
|
3494
|
+
like ``C:\\Users\\R&D\\...\\fleet-dashboard.html`` reached cmd UNQUOTED,
|
|
3495
|
+
cmd split it at the ``&`` and executed the tail as a second command
|
|
3496
|
+
relative to the CWD. ``%VAR%`` expands even inside quotes, and the bare
|
|
3497
|
+
image name ``cmd`` resolves CWD-FIRST under CreateProcessW, so an
|
|
3498
|
+
untrusted working directory could supply the interpreter. The path is
|
|
3499
|
+
derived from ``CLAUDE_CONFIG_DIR`` (deliberately unconfined) and
|
|
3500
|
+
``HOME``/``USERPROFILE``, so this was command injection, not just
|
|
3501
|
+
breakage.
|
|
3502
|
+
|
|
3503
|
+
``os.startfile`` calls ShellExecuteW with the path as a real ARGUMENT: no
|
|
3504
|
+
command line is built, no parser sees the metacharacters, no console is
|
|
3505
|
+
allocated (so the no-flash fix needs no creationflags on this branch at all), and the
|
|
3506
|
+
browser it hands off to is a GUI app that stays visible.
|
|
3507
|
+
|
|
3508
|
+
``open`` / ``xdg-open`` keep ``creationflags=_NO_WINDOW``; it is ``0`` off
|
|
3509
|
+
Windows, where ``creationflags=0`` is the documented default, so POSIX
|
|
3510
|
+
behaviour is unchanged.
|
|
3511
|
+
|
|
3512
|
+
Failures are reported (the no-flash bug stayed hidden for months behind ``check=False``
|
|
3513
|
+
and a discarded returncode): any opener error prints the file:// URL to open
|
|
3514
|
+
by hand, matching ``measure.py``.
|
|
3515
|
+
"""
|
|
3516
|
+
import platform as _platform
|
|
3517
|
+
system = _platform.system()
|
|
3518
|
+
filepath = str(path)
|
|
3519
|
+
try:
|
|
3520
|
+
if system == "Darwin":
|
|
3521
|
+
subprocess.run(["open", filepath], check=True, timeout=10, creationflags=_NO_WINDOW)
|
|
3522
|
+
elif system == "Linux":
|
|
3523
|
+
subprocess.run(["xdg-open", filepath], check=True, timeout=10, creationflags=_NO_WINDOW)
|
|
3524
|
+
elif system == "Windows":
|
|
3525
|
+
os.startfile(filepath) # noqa: S606 -- ShellExecuteW, no command line, no console
|
|
3526
|
+
else:
|
|
3527
|
+
raise OSError(f"Unsupported platform: {system}")
|
|
3528
|
+
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError, FileNotFoundError):
|
|
3529
|
+
print("\n Could not auto-open browser. Open manually:")
|
|
3530
|
+
print(f" {Path(filepath).as_uri()}")
|
|
3531
|
+
|
|
3532
|
+
|
|
3533
|
+
def _serve_dashboard(host: str, port: int):
|
|
3534
|
+
"""Serve the fleet dashboard over HTTP: that one page and nothing else.
|
|
3535
|
+
|
|
3536
|
+
The old handler served the whole data folder, so fleet.db and the pricing
|
|
3537
|
+
overrides were downloadable, and with no Host check a DNS-rebinding page in
|
|
3538
|
+
the user's browser could read them. Now only the dashboard is served, and a
|
|
3539
|
+
request whose Host is not this server's own name is refused.
|
|
3540
|
+
"""
|
|
3541
|
+
import http.server
|
|
3542
|
+
|
|
3543
|
+
allowed_hosts = {"127.0.0.1", "localhost", "[::1]", host.lower()}
|
|
3544
|
+
page = FLEET_DASHBOARD_PATH
|
|
3545
|
+
|
|
3546
|
+
class _DashboardOnly(http.server.BaseHTTPRequestHandler):
|
|
3547
|
+
def _host_ok(self) -> bool:
|
|
3548
|
+
raw = (self.headers.get("Host") or "").strip().lower()
|
|
3549
|
+
# "[::1]:8080" -> "[::1]"; "localhost:8080" -> "localhost"
|
|
3550
|
+
name = raw[: raw.find("]") + 1] if raw.startswith("[") else raw.split(":", 1)[0]
|
|
3551
|
+
return name in allowed_hosts
|
|
3552
|
+
|
|
3553
|
+
def do_GET(self): # noqa: N802 (http.server API)
|
|
3554
|
+
if not self._host_ok():
|
|
3555
|
+
self.send_error(403, "Forbidden host")
|
|
3556
|
+
return
|
|
3557
|
+
if self.path.split("?", 1)[0] not in ("/", "/fleet-dashboard.html"):
|
|
3558
|
+
self.send_error(404)
|
|
3559
|
+
return
|
|
3560
|
+
try:
|
|
3561
|
+
body = page.read_bytes()
|
|
3562
|
+
except OSError:
|
|
3563
|
+
self.send_error(404)
|
|
3564
|
+
return
|
|
3565
|
+
self.send_response(200)
|
|
3566
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
3567
|
+
self.send_header("Content-Length", str(len(body)))
|
|
3568
|
+
self.send_header("Cache-Control", "no-store")
|
|
3569
|
+
self.end_headers()
|
|
3570
|
+
self.wfile.write(body)
|
|
3571
|
+
|
|
3572
|
+
def log_message(self, fmt, *a): # keep the terminal quiet
|
|
3573
|
+
pass
|
|
3574
|
+
|
|
3575
|
+
with http.server.HTTPServer((host, port), _DashboardOnly) as server:
|
|
3576
|
+
print(f" Serving fleet dashboard at http://{host}:{port}/fleet-dashboard.html")
|
|
3577
|
+
print(" Press Ctrl+C to stop.")
|
|
3578
|
+
try:
|
|
3579
|
+
server.serve_forever()
|
|
3580
|
+
except KeyboardInterrupt:
|
|
3581
|
+
print("\n Server stopped.")
|
|
3582
|
+
|
|
3583
|
+
|
|
3584
|
+
# ===================================================================
|
|
3585
|
+
# CLI ENTRY POINT
|
|
3586
|
+
# ===================================================================
|
|
3587
|
+
|
|
3588
|
+
def fleet_cli(args: list[str] | None = None):
|
|
3589
|
+
"""Main CLI entry point. Can be called from measure.py via lazy import."""
|
|
3590
|
+
if args is None:
|
|
3591
|
+
args = sys.argv[1:]
|
|
3592
|
+
|
|
3593
|
+
if not args or args[0] == "--help" or args[0] == "-h":
|
|
3594
|
+
print("""
|
|
3595
|
+
Fleet Auditor: Cross-Platform Agent Token Waste Auditor
|
|
3596
|
+
|
|
3597
|
+
Commands:
|
|
3598
|
+
detect Detect installed agent systems
|
|
3599
|
+
scan [--system X] [--days 30] Collect agent runs into fleet.db
|
|
3600
|
+
audit [--system X] [--days 30] Run waste pattern detection
|
|
3601
|
+
report [--system X] [--json] Full report with cost breakdown
|
|
3602
|
+
dashboard [--serve] Generate and open fleet dashboard
|
|
3603
|
+
|
|
3604
|
+
Flags:
|
|
3605
|
+
--json Output as JSON
|
|
3606
|
+
--days N Look back N days (default: 30)
|
|
3607
|
+
--system X Filter to one system (claude, openclaw, hermes, etc.)
|
|
3608
|
+
--serve Start HTTP server for dashboard
|
|
3609
|
+
--quiet, -q Suppress non-essential output
|
|
3610
|
+
""")
|
|
3611
|
+
return
|
|
3612
|
+
|
|
3613
|
+
cmd = args[0]
|
|
3614
|
+
cmd_args = args[1:]
|
|
3615
|
+
|
|
3616
|
+
if cmd == "detect":
|
|
3617
|
+
cmd_detect(cmd_args)
|
|
3618
|
+
elif cmd == "scan":
|
|
3619
|
+
cmd_scan(cmd_args)
|
|
3620
|
+
elif cmd == "audit":
|
|
3621
|
+
cmd_audit(cmd_args)
|
|
3622
|
+
elif cmd == "report":
|
|
3623
|
+
cmd_report(cmd_args)
|
|
3624
|
+
elif cmd == "dashboard":
|
|
3625
|
+
cmd_dashboard(cmd_args)
|
|
3626
|
+
else:
|
|
3627
|
+
print(f" Unknown command: {cmd}")
|
|
3628
|
+
print(" Run 'fleet.py --help' for usage.")
|
|
3629
|
+
sys.exit(1)
|
|
3630
|
+
|
|
3631
|
+
|
|
3632
|
+
if __name__ == "__main__":
|
|
3633
|
+
fleet_cli()
|