claudeshift-cli 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,249 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from claudeshift.telemetry.pricing import PLAN_QUOTAS, PlanQuota
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class DetectedPlan:
15
+ plan: PlanQuota
16
+ provider: str
17
+ source: str
18
+ raw_tier: str = ""
19
+
20
+
21
+ def _safe_json(path: Path) -> dict[str, Any]:
22
+ if not path.is_file():
23
+ return {}
24
+ try:
25
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
26
+ return data if isinstance(data, dict) else {}
27
+ except Exception:
28
+ return {}
29
+
30
+
31
+ def _decode_jwt_payload_readonly(jwt_token: str) -> dict[str, Any]:
32
+ """Read-only base64url decode of non-sensitive JWT claims (plan type only). Never stored/logged."""
33
+ parts = jwt_token.split(".")
34
+ if len(parts) < 2:
35
+ return {}
36
+ segment = parts[1]
37
+ padding = "=" * (-len(segment) % 4)
38
+ try:
39
+ raw = base64.urlsafe_b64decode((segment + padding).encode("ascii"))
40
+ data = json.loads(raw.decode("utf-8", errors="replace"))
41
+ return data if isinstance(data, dict) else {}
42
+ except Exception:
43
+ return {}
44
+
45
+
46
+ def _detect_claude_plan(target_home: Path) -> DetectedPlan | None:
47
+ creds = _safe_json(target_home / ".claude" / ".credentials.json")
48
+ oauth = creds.get("claudeAiOauth")
49
+ if isinstance(oauth, dict):
50
+ sub_type = str(oauth.get("subscriptionType") or "").lower()
51
+ tier = str(oauth.get("rateLimitTier") or "").lower()
52
+ combined = f"{sub_type} {tier}".strip()
53
+
54
+ if "20x" in combined or "max_20" in combined or "max20" in combined:
55
+ return DetectedPlan(PLAN_QUOTAS["max20"], "claude", "claude-credentials", combined)
56
+ if "5x" in combined or "max_5" in combined or "max5" in combined or "max" in sub_type:
57
+ return DetectedPlan(PLAN_QUOTAS["max5"], "claude", "claude-credentials", combined)
58
+ if "team" in combined:
59
+ return DetectedPlan(PLAN_QUOTAS["claude_team"], "claude", "claude-credentials", combined)
60
+ if "enterprise" in combined:
61
+ return DetectedPlan(PLAN_QUOTAS["claude_enterprise"], "claude", "claude-credentials", combined)
62
+ if "pro" in combined:
63
+ return DetectedPlan(PLAN_QUOTAS["pro"], "claude", "claude-credentials", combined)
64
+ if "free" in combined:
65
+ return DetectedPlan(PLAN_QUOTAS["claude_free"], "claude", "claude-credentials", combined)
66
+
67
+ cfg = _safe_json(target_home / ".claude.json")
68
+ acct = cfg.get("oauthAccount")
69
+ if isinstance(acct, dict):
70
+ billing = str(acct.get("billingType") or "").lower()
71
+ org_type = str(acct.get("organizationType") or "").lower()
72
+ combined = f"{billing} {org_type}".strip()
73
+ if "max_20" in combined or "20x" in combined:
74
+ return DetectedPlan(PLAN_QUOTAS["max20"], "claude", "claude-config", combined)
75
+ if "max" in combined:
76
+ return DetectedPlan(PLAN_QUOTAS["max5"], "claude", "claude-config", combined)
77
+ if "pro" in combined:
78
+ return DetectedPlan(PLAN_QUOTAS["pro"], "claude", "claude-config", combined)
79
+ if "team" in combined:
80
+ return DetectedPlan(PLAN_QUOTAS["claude_team"], "claude", "claude-config", combined)
81
+ if "free" in combined:
82
+ return DetectedPlan(PLAN_QUOTAS["claude_free"], "claude", "claude-config", combined)
83
+
84
+ if cfg.get("primaryApiKey") or os.getenv("ANTHROPIC_API_KEY"):
85
+ return DetectedPlan(PLAN_QUOTAS["api"], "claude", "api-key", "api")
86
+
87
+ return None
88
+
89
+
90
+ def _map_codex_plan_name(raw_plan: str, source: str) -> DetectedPlan | None:
91
+ low = raw_plan.strip().lower()
92
+ if not low:
93
+ return None
94
+ if low == "go" or "chatgpt_go" in low or low.endswith("_go") or low.startswith("go_"):
95
+ return DetectedPlan(PLAN_QUOTAS["codex_go"], "codex", source, low)
96
+ if "pro" in low:
97
+ return DetectedPlan(PLAN_QUOTAS["codex_pro"], "codex", source, low)
98
+ if "plus" in low:
99
+ return DetectedPlan(PLAN_QUOTAS["codex_plus"], "codex", source, low)
100
+ if "team" in low:
101
+ return DetectedPlan(PLAN_QUOTAS["codex_team"], "codex", source, low)
102
+ if "enterprise" in low or "business" in low:
103
+ return DetectedPlan(PLAN_QUOTAS["codex_enterprise"], "codex", source, low)
104
+ if "free" in low:
105
+ return DetectedPlan(PLAN_QUOTAS["codex_free"], "codex", source, low)
106
+ if "api" in low:
107
+ return DetectedPlan(PLAN_QUOTAS["api"], "codex", source, low)
108
+
109
+ # Dynamic passthrough: never discard a newly introduced provider tier name!
110
+ clean_title = raw_plan.strip().replace("_", " ").title()
111
+ dynamic_plan = PlanQuota(
112
+ id=f"codex_{low}",
113
+ label=f"ChatGPT {clean_title} / Codex",
114
+ window_hours=5,
115
+ window_cost_budget_usd=15.0,
116
+ window_token_budget=15_000_000,
117
+ )
118
+ return DetectedPlan(dynamic_plan, "codex", source, low)
119
+
120
+
121
+ def _peek_latest_codex_session_plan(target_home: Path) -> str:
122
+ """Quickly inspect the newest Codex JSONL log for rate_limits.plan_type (read-only)."""
123
+ base = target_home / ".codex" / "sessions"
124
+ if not base.is_dir():
125
+ return ""
126
+ try:
127
+ candidates = sorted(
128
+ (p for p in base.rglob("*.jsonl") if p.is_file()),
129
+ key=lambda p: p.stat().st_mtime,
130
+ reverse=True,
131
+ )
132
+ except OSError:
133
+ return ""
134
+
135
+ for fpath in candidates[:3]:
136
+ found = ""
137
+ try:
138
+ with fpath.open("r", encoding="utf-8", errors="replace") as fh:
139
+ for line in fh:
140
+ if "plan_type" not in line:
141
+ continue
142
+ try:
143
+ obj = json.loads(line)
144
+ except json.JSONDecodeError:
145
+ continue
146
+ payload = obj.get("payload") if isinstance(obj, dict) else None
147
+ rl = payload.get("rate_limits") if isinstance(payload, dict) else None
148
+ if isinstance(rl, dict) and isinstance(rl.get("plan_type"), str):
149
+ val = rl["plan_type"].strip()
150
+ if val:
151
+ found = val
152
+ except OSError:
153
+ continue
154
+ if found:
155
+ return found
156
+ return ""
157
+
158
+
159
+ def _detect_codex_plan(target_home: Path, session_hint: str = "") -> DetectedPlan | None:
160
+ # 1. Inspect ~/.codex/auth.json first (direct keys + JWT chatgpt_plan_type claim)
161
+ auth = _safe_json(target_home / ".codex" / "auth.json")
162
+ if auth:
163
+ for key in ("plan", "plan_type", "subscription", "tier", "chatgpt_plan_type"):
164
+ if isinstance(auth.get(key), str):
165
+ mapped = _map_codex_plan_name(auth[key], "codex-auth")
166
+ if mapped:
167
+ return mapped
168
+
169
+ tokens = auth.get("tokens")
170
+ if isinstance(tokens, dict):
171
+ for tok_key in ("id_token", "access_token"):
172
+ tok_val = tokens.get(tok_key)
173
+ if isinstance(tok_val, str) and "." in tok_val:
174
+ claims = _decode_jwt_payload_readonly(tok_val)
175
+ auth_ns = claims.get("https://api.openai.com/auth")
176
+ if isinstance(auth_ns, dict):
177
+ plan_type = str(auth_ns.get("chatgpt_plan_type") or "")
178
+ mapped = _map_codex_plan_name(plan_type, "codex-auth-claim")
179
+ if mapped:
180
+ return mapped
181
+ for top_key in ("chatgpt_plan_type", "plan_type"):
182
+ if isinstance(claims.get(top_key), str):
183
+ mapped = _map_codex_plan_name(claims[top_key], "codex-auth-claim")
184
+ if mapped:
185
+ return mapped
186
+
187
+ if auth.get("OPENAI_API_KEY") and not auth.get("tokens"):
188
+ return DetectedPlan(PLAN_QUOTAS["api"], "codex", "codex-api-key", "apikey")
189
+
190
+ # 2. Check session log hint (either passed from scanner or peeked for 'doctor')
191
+ hint = session_hint or _peek_latest_codex_session_plan(target_home)
192
+ if hint:
193
+ mapped = _map_codex_plan_name(hint, "codex-session-log")
194
+ if mapped:
195
+ return mapped
196
+
197
+ if os.getenv("OPENAI_API_KEY") and not (target_home / ".codex" / "auth.json").is_file():
198
+ return DetectedPlan(PLAN_QUOTAS["api"], "codex", "env-api-key", "apikey")
199
+
200
+ return None
201
+
202
+
203
+ def _detect_gemini_plan(target_home: Path) -> DetectedPlan | None:
204
+ settings = _safe_json(target_home / ".gemini" / "settings.json")
205
+ auth_type = str(
206
+ settings.get("selectedAuthType")
207
+ or (settings.get("security") or {}).get("auth", {}).get("selectedType", "")
208
+ ).lower()
209
+ if "api-key" in auth_type or "gemini-api-key" in auth_type:
210
+ return DetectedPlan(PLAN_QUOTAS["api"], "gemini", "gemini-settings", auth_type)
211
+ if "oauth" in auth_type:
212
+ return DetectedPlan(PLAN_QUOTAS["gemini_free"], "gemini", "gemini-settings", auth_type)
213
+ if os.getenv("GEMINI_API_KEY"):
214
+ return DetectedPlan(PLAN_QUOTAS["api"], "gemini", "env-api-key", "api")
215
+ return None
216
+
217
+
218
+ def detect_active_plan(
219
+ target_home: Path,
220
+ provider: str = "all",
221
+ dominant_provider: str | None = None,
222
+ session_plan_hint: str = "",
223
+ ) -> DetectedPlan:
224
+ """Auto-detect the real subscription tier. Never fabricates a paid plan if unverified."""
225
+ preferred = dominant_provider or (provider if provider != "all" else "claude")
226
+
227
+ if preferred == "codex":
228
+ found = _detect_codex_plan(target_home, session_hint=session_plan_hint)
229
+ if found:
230
+ return found
231
+ return DetectedPlan(PLAN_QUOTAS["codex_free"], "codex", "unverified", "free")
232
+
233
+ if preferred == "claude":
234
+ found = _detect_claude_plan(target_home)
235
+ if found:
236
+ return found
237
+ if provider == "all":
238
+ found_codex = _detect_codex_plan(target_home, session_hint=session_plan_hint)
239
+ if found_codex:
240
+ return found_codex
241
+ return DetectedPlan(PLAN_QUOTAS["claude_free"], "claude", "unverified", "free")
242
+
243
+ if preferred == "gemini":
244
+ found = _detect_gemini_plan(target_home)
245
+ if found:
246
+ return found
247
+ return DetectedPlan(PLAN_QUOTAS["gemini_free"], "gemini", "unverified", "free")
248
+
249
+ return DetectedPlan(PLAN_QUOTAS["api"], preferred, "unverified", "api")
File without changes
@@ -0,0 +1,200 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import defaultdict
4
+ from dataclasses import dataclass
5
+ from datetime import datetime, timedelta, timezone
6
+ from typing import Any
7
+
8
+ from claudeshift.telemetry.parser import UsageEvent
9
+ from claudeshift.telemetry.pricing import PLAN_QUOTAS, PlanQuota, resolve_model_rate
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class ModelBreakdown:
14
+ model: str
15
+ requests: int
16
+ input_tokens: int
17
+ output_tokens: int
18
+ cache_read_tokens: int
19
+ cache_write_tokens: int
20
+ total_tokens: int
21
+ cost_usd: float
22
+ rate_estimated: bool = False
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ProjectBreakdown:
27
+ project: str
28
+ sessions: int
29
+ requests: int
30
+ total_tokens: int
31
+ cost_usd: float
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class UsageReport:
36
+ generated_at: str
37
+ plan: PlanQuota
38
+ plan_source: str
39
+ budget_usd: float
40
+ # Active 5-hour rolling window metrics
41
+ window_requests: int
42
+ window_tokens: int
43
+ window_cost_usd: float
44
+ window_pct: float
45
+ alert_level: str # OK | WARNING | CRITICAL
46
+ # Burn-rate & ETA (based on last 60 minutes)
47
+ burn_tokens_per_min: float
48
+ burn_usd_per_hour: float
49
+ eta_minutes: float | None
50
+ window_reset_in_minutes: float | None
51
+ # Today (UTC day) & All-time totals
52
+ today_requests: int
53
+ today_tokens: int
54
+ today_cost_usd: float
55
+ total_requests: int
56
+ total_tokens: int
57
+ total_cost_usd: float
58
+ # Breakdowns
59
+ models: tuple[ModelBreakdown, ...]
60
+ projects: tuple[ProjectBreakdown, ...]
61
+ # Scanner perf stats
62
+ files_scanned: int
63
+ cache_hits: int
64
+ parsed_fresh: int
65
+
66
+
67
+ def compute_usage_report(
68
+ events: list[UsageEvent],
69
+ plan_id: str = "max5",
70
+ custom_budget_usd: float | None = None,
71
+ now_utc: datetime | None = None,
72
+ scan_stats: dict[str, Any] | None = None,
73
+ resolved_plan: PlanQuota | None = None,
74
+ plan_source: str = "manual",
75
+ ) -> UsageReport:
76
+ now = now_utc or datetime.now(timezone.utc)
77
+ now_epoch = now.timestamp()
78
+ plan = resolved_plan or PLAN_QUOTAS.get(plan_id.lower(), PLAN_QUOTAS["max5"])
79
+ budget_usd = (
80
+ custom_budget_usd
81
+ if (custom_budget_usd and custom_budget_usd > 0)
82
+ else plan.window_cost_budget_usd
83
+ )
84
+
85
+ window_cutoff = (now - timedelta(hours=plan.window_hours)).timestamp()
86
+ burn_cutoff = (now - timedelta(minutes=60)).timestamp()
87
+ today_start = datetime(now.year, now.month, now.day, tzinfo=timezone.utc).timestamp()
88
+
89
+ window_events = [e for e in events if e.epoch >= window_cutoff]
90
+ burn_events = [e for e in events if e.epoch >= burn_cutoff]
91
+ today_events = [e for e in events if e.epoch >= today_start]
92
+
93
+ window_tokens = sum(e.total_tokens for e in window_events)
94
+ window_cost = round(sum(e.cost_usd for e in window_events), 4)
95
+ window_pct = min(999.9, round((window_cost / budget_usd) * 100.0, 1)) if budget_usd > 0 else 0.0
96
+
97
+ if window_pct >= 90.0:
98
+ alert_level = "CRITICAL"
99
+ elif window_pct >= 75.0:
100
+ alert_level = "WARNING"
101
+ else:
102
+ alert_level = "OK"
103
+
104
+ if burn_events:
105
+ span_min = max(5.0, (now_epoch - burn_events[0].epoch) / 60.0)
106
+ span_min = min(60.0, span_min)
107
+ burn_tok = sum(e.total_tokens for e in burn_events)
108
+ burn_usd = sum(e.cost_usd for e in burn_events)
109
+ burn_tokens_per_min = round(burn_tok / span_min, 1)
110
+ burn_usd_per_hour = round((burn_usd / span_min) * 60.0, 2)
111
+ else:
112
+ burn_tokens_per_min = 0.0
113
+ burn_usd_per_hour = 0.0
114
+
115
+ remaining_usd = max(0.0, budget_usd - window_cost)
116
+ if burn_usd_per_hour > 0.01 and remaining_usd > 0:
117
+ eta_minutes: float | None = round((remaining_usd / burn_usd_per_hour) * 60.0, 1)
118
+ elif remaining_usd <= 0 and window_events:
119
+ eta_minutes = 0.0
120
+ else:
121
+ eta_minutes = None
122
+
123
+ if window_events:
124
+ oldest_in_window = window_events[0].epoch
125
+ reset_epoch = oldest_in_window + (plan.window_hours * 3600)
126
+ window_reset_in_minutes: float | None = max(0.0, round((reset_epoch - now_epoch) / 60.0, 1))
127
+ else:
128
+ window_reset_in_minutes = None
129
+
130
+ by_model: dict[str, list[UsageEvent]] = defaultdict(list)
131
+ by_project: dict[str, list[UsageEvent]] = defaultdict(list)
132
+ for e in events:
133
+ by_model[e.model].append(e)
134
+ by_project[e.project].append(e)
135
+
136
+ models = tuple(
137
+ sorted(
138
+ (
139
+ ModelBreakdown(
140
+ model=m,
141
+ requests=len(evs),
142
+ input_tokens=sum(x.input_tokens for x in evs),
143
+ output_tokens=sum(x.output_tokens for x in evs),
144
+ cache_read_tokens=sum(x.cache_read_tokens for x in evs),
145
+ cache_write_tokens=sum(x.cache_write_tokens for x in evs),
146
+ total_tokens=sum(x.total_tokens for x in evs),
147
+ cost_usd=round(sum(x.cost_usd for x in evs), 4),
148
+ rate_estimated=resolve_model_rate(m).estimated,
149
+ )
150
+ for m, evs in by_model.items()
151
+ ),
152
+ key=lambda x: x.cost_usd,
153
+ reverse=True,
154
+ )
155
+ )
156
+
157
+ projects = tuple(
158
+ sorted(
159
+ (
160
+ ProjectBreakdown(
161
+ project=p,
162
+ sessions=len({x.session_id for x in evs}),
163
+ requests=len(evs),
164
+ total_tokens=sum(x.total_tokens for x in evs),
165
+ cost_usd=round(sum(x.cost_usd for x in evs), 4),
166
+ )
167
+ for p, evs in by_project.items()
168
+ ),
169
+ key=lambda x: x.cost_usd,
170
+ reverse=True,
171
+ )
172
+ )
173
+
174
+ stats = scan_stats or {}
175
+ return UsageReport(
176
+ generated_at=now.isoformat(timespec="seconds"),
177
+ plan=plan,
178
+ plan_source=plan_source,
179
+ budget_usd=budget_usd,
180
+ window_requests=len(window_events),
181
+ window_tokens=window_tokens,
182
+ window_cost_usd=window_cost,
183
+ window_pct=window_pct,
184
+ alert_level=alert_level,
185
+ burn_tokens_per_min=burn_tokens_per_min,
186
+ burn_usd_per_hour=burn_usd_per_hour,
187
+ eta_minutes=eta_minutes,
188
+ window_reset_in_minutes=window_reset_in_minutes,
189
+ today_requests=len(today_events),
190
+ today_tokens=sum(e.total_tokens for e in today_events),
191
+ today_cost_usd=round(sum(e.cost_usd for e in today_events), 4),
192
+ total_requests=len(events),
193
+ total_tokens=sum(e.total_tokens for e in events),
194
+ total_cost_usd=round(sum(e.cost_usd for e in events), 4),
195
+ models=models,
196
+ projects=projects,
197
+ files_scanned=int(stats.get("files_scanned", 0)),
198
+ cache_hits=int(stats.get("cache_hits", 0)),
199
+ parsed_fresh=int(stats.get("parsed_fresh", 0)),
200
+ )
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+
3
+ from rich.console import Group
4
+ from rich.panel import Panel
5
+ from rich.table import Table
6
+ from rich.text import Text
7
+
8
+ from claudeshift.telemetry.analytics import UsageReport
9
+
10
+
11
+ def format_tokens(n: int) -> str:
12
+ if n >= 1_000_000:
13
+ return f"{n / 1_000_000:.2f}M"
14
+ if n >= 1_000:
15
+ return f"{n / 1_000:.1f}K"
16
+ return str(n)
17
+
18
+
19
+ def format_minutes(mins: float | None) -> str:
20
+ if mins is None:
21
+ return "idle"
22
+ if mins <= 0:
23
+ return "NOW"
24
+ h = int(mins // 60)
25
+ m = int(mins % 60)
26
+ return f"{h}h {m}m" if h > 0 else f"{m}m"
27
+
28
+
29
+ def _render_gauge(pct: float, width: int = 32) -> Text:
30
+ clamped = max(0.0, min(100.0, pct))
31
+ filled = round((clamped / 100.0) * width)
32
+ empty = width - filled
33
+ color = "red" if pct >= 90 else ("yellow" if pct >= 75 else "green")
34
+ bar = Text()
35
+ bar.append("█" * filled, style=f"bold {color}")
36
+ bar.append("░" * empty, style="dim")
37
+ bar.append(f" {pct:.1f}%", style=f"bold {color}")
38
+ return bar
39
+
40
+
41
+ def build_usage_summary_renderable(report: UsageReport, active_profile: str | None) -> Group:
42
+ alert_style = {"OK": "green", "WARNING": "yellow", "CRITICAL": "bold red"}[report.alert_level]
43
+ profile_label = active_profile or "untracked"
44
+
45
+ gauge = _render_gauge(report.window_pct)
46
+ header = Table.grid(padding=(0, 2))
47
+ header.add_column(style="bold", no_wrap=True)
48
+ header.add_column()
49
+
50
+ header.add_row(
51
+ "Active Profile:",
52
+ f"[cyan]{profile_label}[/cyan] | Plan: [bold]{report.plan.label}[/bold] [dim]({report.plan_source})[/dim]",
53
+ )
54
+ header.add_row("5h Session Gauge:", gauge)
55
+ header.add_row(
56
+ "5h Usage / Budget:",
57
+ f"[bold]${report.window_cost_usd:.2f}[/bold] / ${report.budget_usd:.2f} "
58
+ f"([cyan]{format_tokens(report.window_tokens)}[/cyan] tokens, {report.window_requests} reqs) "
59
+ f"— Status: [{alert_style}]{report.alert_level}[/{alert_style}]",
60
+ )
61
+ header.add_row(
62
+ "Today (UTC):",
63
+ f"[bold]${report.today_cost_usd:.2f}[/bold] ({format_tokens(report.today_tokens)} tokens, {report.today_requests} reqs)",
64
+ )
65
+ header.add_row(
66
+ "All-Time Scanned:",
67
+ f"[bold]${report.total_cost_usd:.2f}[/bold] ({format_tokens(report.total_tokens)} tokens across {report.files_scanned} log files)",
68
+ )
69
+
70
+ panel = Panel(
71
+ header,
72
+ title="[bold cyan]claudeshift :: Local Token & Quota Summary[/bold cyan]",
73
+ border_style="red" if report.alert_level == "CRITICAL" else "cyan",
74
+ )
75
+
76
+ model_table = Table(title="Breakdown by Model", header_style="bold magenta")
77
+ model_table.add_column("Model", style="cyan")
78
+ model_table.add_column("Reqs", justify="right")
79
+ model_table.add_column("Input", justify="right")
80
+ model_table.add_column("Output", justify="right")
81
+ model_table.add_column("Cache Read", justify="right", style="dim")
82
+ model_table.add_column("Est. API Cost", justify="right", style="bold green")
83
+
84
+ for m in report.models[:8]:
85
+ cost_str = f"~${m.cost_usd:.3f}" if m.rate_estimated else f"${m.cost_usd:.3f}"
86
+ model_table.add_row(
87
+ m.model,
88
+ str(m.requests),
89
+ format_tokens(m.input_tokens),
90
+ format_tokens(m.output_tokens),
91
+ format_tokens(m.cache_read_tokens),
92
+ cost_str,
93
+ )
94
+
95
+ return Group(panel, model_table)
96
+
97
+
98
+ def build_live_monitor_renderable(
99
+ report: UsageReport,
100
+ active_profile: str | None,
101
+ interval_sec: float,
102
+ ) -> Group:
103
+ alert_style = {"OK": "bold green", "WARNING": "bold yellow", "CRITICAL": "bold red"}[report.alert_level]
104
+ border = "red" if report.alert_level == "CRITICAL" else ("yellow" if report.alert_level == "WARNING" else "magenta")
105
+
106
+ grid = Table.grid(padding=(0, 2))
107
+ grid.add_column(style="bold", no_wrap=True)
108
+ grid.add_column()
109
+
110
+ grid.add_row(
111
+ "Profile / Plan:",
112
+ f"[cyan]{active_profile or 'untracked'}[/cyan] • {report.plan.label} [dim]({report.plan_source})[/dim]",
113
+ )
114
+ grid.add_row("5-Hour Window:", _render_gauge(report.window_pct, width=36))
115
+ grid.add_row(
116
+ "Window Spend:",
117
+ f"[bold]${report.window_cost_usd:.2f}[/bold] / ${report.budget_usd:.2f} "
118
+ f"({format_tokens(report.window_tokens)} tokens) • Alert: [{alert_style}]{report.alert_level}[/{alert_style}]",
119
+ )
120
+ grid.add_row(
121
+ "Live Burn Rate:",
122
+ f"[bold yellow]{format_tokens(int(report.burn_tokens_per_min))}/min[/bold yellow] • "
123
+ f"[bold green]${report.burn_usd_per_hour:.2f}/hr[/bold green] • "
124
+ f"Est. Time to Limit: [bold cyan]{format_minutes(report.eta_minutes)}[/bold cyan]",
125
+ )
126
+ grid.add_row(
127
+ "Window Rollover:",
128
+ f"Oldest active event expires in [cyan]{format_minutes(report.window_reset_in_minutes)}[/cyan]",
129
+ )
130
+ grid.add_row(
131
+ "Scanner Engine:",
132
+ f"[dim]{report.files_scanned} files ({report.cache_hits} cached, {report.parsed_fresh} fresh) • refresh {interval_sec:.0f}s • Ctrl+C to exit[/dim]",
133
+ )
134
+
135
+ top_panel = Panel(
136
+ grid,
137
+ title="[bold magenta]claudeshift PRO :: Live Quota & Burn-Rate Radar[/bold magenta]",
138
+ border_style=border,
139
+ )
140
+
141
+ proj_table = Table(title="Top Projects by Cost", header_style="bold cyan")
142
+ proj_table.add_column("Project", style="white")
143
+ proj_table.add_column("Sessions", justify="right")
144
+ proj_table.add_column("Requests", justify="right")
145
+ proj_table.add_column("Tokens", justify="right", style="cyan")
146
+ proj_table.add_column("Est. Cost", justify="right", style="bold green")
147
+
148
+ for p in report.projects[:6]:
149
+ proj_table.add_row(
150
+ p.project,
151
+ str(p.sessions),
152
+ str(p.requests),
153
+ format_tokens(p.total_tokens),
154
+ f"${p.cost_usd:.3f}",
155
+ )
156
+
157
+ return Group(top_panel, proj_table)