burnclock 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.
burnclock_cli/main.py ADDED
@@ -0,0 +1,1408 @@
1
+ """burnclock CLI — thin Typer + Rich layer over burnclock_core.
2
+
3
+ No TUI imports at module level: Textual is loaded ONLY inside `burnclock watch`
4
+ on a TTY (optional extra `[tui]`; import/runtime failure degrades to the
5
+ plain refresh loop + one stderr warning). httpx only loads when a provider
6
+ fetch actually happens (burnclock_core.providers.deepseek imports it lazily), so
7
+ `burnclock config show` stays lean.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib
13
+ import json
14
+ import os
15
+ import sys
16
+ import time
17
+ import tomllib
18
+ from datetime import date, datetime, timezone
19
+ from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
20
+ from pathlib import Path
21
+ from typing import Annotated, Any, Callable
22
+
23
+ import typer
24
+ from rich.console import Console
25
+ from rich.table import Table
26
+
27
+ from burnclock_core import __version__
28
+ from burnclock_core.config import (
29
+ Config,
30
+ ConfigError,
31
+ load_config,
32
+ render_config_toml,
33
+ write_provider_budget,
34
+ )
35
+ from burnclock_core.schema import EXIT_USAGE, PROVIDER_SLUGS, State
36
+ from burnclock_core.usage import probe as usage_probe, probe_summary_lines
37
+
38
+ app = typer.Typer(
39
+ name="burnclock",
40
+ help="Burnclock: AI budget runway at a glance — balances, burn, days-left. Estimates, not billing truth.",
41
+ add_completion=False,
42
+ no_args_is_help=False,
43
+ context_settings={"help_option_names": ["-h", "--help"]},
44
+ )
45
+ config_app = typer.Typer(help="Inspect burnclock configuration.", no_args_is_help=True)
46
+ app.add_typer(config_app, name="config")
47
+ budget_app = typer.Typer(help="View or set per-provider monthly budgets.", no_args_is_help=True)
48
+ app.add_typer(budget_app, name="budget")
49
+
50
+ # Piped stdout is ALWAYS plain text. Rich 15 forces color when it sees
51
+ # GITHUB_ACTIONS, which would break the zero-ANSI contract for scripts and
52
+ # agents; an explicit user force-flag still wins.
53
+ if not sys.stdout.isatty() and not (
54
+ os.environ.get("FORCE_COLOR") or os.environ.get("CLICOLOR_FORCE")
55
+ ):
56
+ # TERM=dumb, not just NO_COLOR: Rich 15 lets GITHUB_ACTIONS override NO_COLOR.
57
+ os.environ["NO_COLOR"] = "1"
58
+ os.environ["TERM"] = "dumb"
59
+
60
+ out_console = Console() # stdout
61
+ err_console = Console(stderr=True)
62
+
63
+ SUPPORTED_FORMATS = ("json", "table")
64
+
65
+
66
+ class CliError(Exception):
67
+ def __init__(self, message: str, code: int) -> None:
68
+ super().__init__(message)
69
+ self.code = code
70
+
71
+
72
+ def format_decimal(value: Any, places: int = 2) -> str:
73
+ """Render a Decimal (or float) balance with fixed-point decimals.
74
+
75
+ str(float) yields artifacts like 33.989999999999995; quantize first.
76
+ """
77
+ if value is None:
78
+ return ""
79
+ try:
80
+ quant = Decimal(str(value)).quantize(Decimal("1." + "0" * places), rounding=ROUND_HALF_UP)
81
+ except Exception:
82
+ return str(value)
83
+ return format(quant, "f")
84
+
85
+
86
+ def _resolve_format(output: str | None, json_flag: bool) -> str:
87
+ """-o wins over the --json alias (CRITIC #19)."""
88
+ if output is not None:
89
+ fmt = output.lower()
90
+ if fmt == "yaml":
91
+ raise CliError("output format 'yaml' is not implemented yet (planned post-B1)", 2)
92
+ if fmt not in SUPPORTED_FORMATS:
93
+ raise CliError(f"invalid output format {output!r} (expected: json, table, yaml)", 2)
94
+ return fmt
95
+ if json_flag:
96
+ return "json"
97
+ return "table"
98
+
99
+
100
+ def _load_config(path: Path | None) -> Config:
101
+ try:
102
+ # F7: an explicit --config path that does not exist is a config error
103
+ # (exit 3); the absent default path still falls back to defaults.
104
+ return load_config(path, explicit=path is not None)
105
+ except ConfigError as exc:
106
+ err_console.print(f"[red]config error:[/red] {exc}")
107
+ raise typer.Exit(code=3) from exc
108
+
109
+
110
+ def _print_debug(lines: list[str]) -> None:
111
+ for line in lines:
112
+ err_console.print(f"[dim]debug:[/dim] {line}", highlight=False)
113
+
114
+
115
+ def _maybe_print_upgrade_nudge() -> None:
116
+ """B5-B1: at most ONE stderr line when a newer PyPI release exists.
117
+
118
+ Human output paths only — this is never called on a `--json` path, and
119
+ `maybe_nudge` itself is TTY-only, 24 h-cached, and silent-fail. Written
120
+ raw to stderr so no Rich markup/ANSI can ever reach a piped stream.
121
+ """
122
+ try:
123
+ from burnclock_core.upgrade import maybe_nudge
124
+
125
+ line = maybe_nudge(__version__)
126
+ except Exception:
127
+ return # the nudge must never break a command
128
+ if line:
129
+ try:
130
+ sys.stderr.write(line + "\n")
131
+ sys.stderr.flush()
132
+ except Exception:
133
+ return
134
+
135
+
136
+ def _combined_pricer(enabled: frozenset[str]) -> Callable:
137
+ """Dispatch each row to its billing_provider's pricer (F1 fix).
138
+
139
+ CRITIC-C R2: a network-capable pricer is NEVER built for a provider
140
+ outside `enabled` — deepseek is offline-safe and always allowed;
141
+ openrouter (and openai-codex, which prices at OR rates) only when
142
+ openrouter is enabled. Disabled-provider rows price to None and burn
143
+ excludes them with a note — never a live fetch (never-fetched-when-
144
+ disabled invariant).
145
+ """
146
+ cache: dict[str, Any] = {}
147
+
148
+ def price(model, last_seen, tokens):
149
+ bp = (tokens.get("billing_provider") or "").strip().lower()
150
+ if bp not in cache:
151
+ from burnclock_core.pricing import build_pricer
152
+ if bp == "deepseek":
153
+ cache[bp] = build_pricer("deepseek")
154
+ elif bp in enabled:
155
+ cache[bp] = build_pricer(bp)
156
+ elif bp == "openai-codex" and "openrouter" in enabled:
157
+ cache[bp] = build_pricer("openai-codex")
158
+ else:
159
+ cache[bp] = None
160
+ fn = cache[bp]
161
+ return fn(model, last_seen, tokens) if fn is not None else None
162
+
163
+ return price
164
+
165
+
166
+ # --- B2-C2 HERO rendering helpers -------------------------------------------
167
+
168
+ _BAR_CELLS = 12
169
+ _BAR_FILLED = "█"
170
+ _BAR_EMPTY = "░"
171
+
172
+
173
+ def _budget_bar_line(label: str, budget: dict) -> str | None:
174
+ """`DeepSeek budget: ████████░░░░ 62% ($31.12 of $50.00 this month)`.
175
+
176
+ None when the row has no monthly budget or no computed month spend (the
177
+ B1 placeholder shape) — never a fabricated bar.
178
+ """
179
+ limit = budget.get("limit")
180
+ spent = budget.get("spent_est")
181
+ if limit is None or spent is None or limit <= 0:
182
+ return None
183
+ filled = max(0, min(_BAR_CELLS, round(_BAR_CELLS * spent / limit)))
184
+ bar = _BAR_FILLED * filled + _BAR_EMPTY * (_BAR_CELLS - filled)
185
+ return (
186
+ f"{label} budget: {bar} {spent / limit * 100:.0f}% "
187
+ f"(${format_decimal(spent)} of ${format_decimal(limit)} this month)"
188
+ )
189
+
190
+
191
+ def _row_label(provider: dict) -> str:
192
+ return str(provider.get("label") or provider.get("id") or "?")
193
+
194
+
195
+ def _status_human_view(envelope: dict, aggregate: dict | None) -> None:
196
+ """Status view: the 4 B1 columns + Burn/day + Runway (paid) + bars + footer."""
197
+ from burnclock_core.forecast import render_runway
198
+
199
+ table = Table(title="burnclock — AI budget status", show_lines=False)
200
+ table.add_column("Provider", style="bold")
201
+ table.add_column("State")
202
+ table.add_column("Balance")
203
+ table.add_column("Error")
204
+ table.add_column("Burn/day")
205
+ table.add_column("Runway (paid)")
206
+
207
+ for provider in envelope["providers"]:
208
+ # B2-C2 CONT4: dashboard disabled rows render dash placeholders —
209
+ # nothing was fetched, so nothing is fabricated.
210
+ if provider.get("status") == "disabled":
211
+ table.add_row(_row_label(provider), "disabled", "—", "—", "—", "—")
212
+ continue
213
+ balance = provider.get("balance") or {}
214
+ amount = balance.get("amount")
215
+ forecast = provider.get("forecast") or {}
216
+ daily = (forecast.get("forecast_inputs") or {}).get("daily_burn_usd")
217
+ paid = forecast.get("runway_days_paid")
218
+ table.add_row(
219
+ _row_label(provider),
220
+ str(provider.get("status", "?")),
221
+ f"{format_decimal(amount)} {balance.get('currency', '')}".strip()
222
+ if amount is not None
223
+ else "n/a",
224
+ provider.get("error") or "",
225
+ f"{format_decimal(daily)}/d" if daily is not None else "—",
226
+ render_runway(Decimal(str(paid)) if paid is not None else None),
227
+ )
228
+ if not envelope["providers"]:
229
+ table.add_row("(no enabled providers)", "-", "-", "", "—", "—")
230
+ out_console.print(table)
231
+
232
+ for provider in envelope["providers"]:
233
+ line = _budget_bar_line(_row_label(provider), provider.get("budget") or {})
234
+ if line:
235
+ out_console.print(line)
236
+
237
+ if aggregate is not None and aggregate.get("spend_usd_sum") is not None:
238
+ sources = ",".join(aggregate.get("cost_source") or [])
239
+ # F7: the two counters render distinctly when unparseable rows exist
240
+ # (M > 0); otherwise the footer keeps its original wording.
241
+ unparseable = aggregate.get("unparseable_calls", 0)
242
+ excluded_segment = (
243
+ f"{aggregate.get('unattributed_calls', 0)} calls excluded "
244
+ f"(unpriced/foreign) · {unparseable} unparseable"
245
+ if unparseable
246
+ else f"{aggregate.get('unattributed_calls', 0)} unattributed calls excluded"
247
+ )
248
+ out_console.print(
249
+ f"burn window: last {aggregate.get('window_days')}d · "
250
+ f"${format_decimal(aggregate.get('daily_burn_usd'))}/day · "
251
+ f"{aggregate.get('priced_calls')} priced calls · "
252
+ f"sources: {sources} · "
253
+ f"{excluded_segment}"
254
+ )
255
+ else:
256
+ out_console.print("forecast: insufficient history (no costed calls in window)")
257
+
258
+
259
+ def _forecast_human_view(envelope: dict, aggregate: dict | None) -> None:
260
+ """Forecast view: runways (HERO), budget, crosses-on + inputs + caveats."""
261
+ from burnclock_core.forecast import render_runway
262
+ from rich.text import Text
263
+
264
+ table = Table(title="burnclock — forecast", show_lines=False)
265
+ table.add_column("Provider", style="bold")
266
+ table.add_column("Daily burn")
267
+ table.add_column("Paid runway")
268
+ table.add_column("Total runway")
269
+ table.add_column("Monthly budget")
270
+ table.add_column("Crosses on")
271
+
272
+ for provider in envelope["providers"]:
273
+ forecast = provider.get("forecast") or {}
274
+ daily = (forecast.get("forecast_inputs") or {}).get("daily_burn_usd")
275
+ paid = forecast.get("runway_days_paid")
276
+ total = forecast.get("runway_days_total")
277
+ paid_text = render_runway(Decimal(str(paid)) if paid is not None else None)
278
+ # HERO column: hot when the paid runway is near (< 30d cyan, < 7d red).
279
+ paid_style = None
280
+ if paid is not None:
281
+ if paid < 7:
282
+ paid_style = "bold red"
283
+ elif paid < 30:
284
+ paid_style = "bold cyan"
285
+ budget = provider.get("budget") or {}
286
+ limit = budget.get("limit")
287
+ spent = budget.get("spent_est")
288
+ budget_text = (
289
+ f"spent ${format_decimal(spent)} of ${format_decimal(limit)}"
290
+ if limit is not None and spent is not None
291
+ else "—"
292
+ )
293
+ # Crosses column: a PAST date means the budget is already crossed
294
+ # -> render "over" (bold red); JSON keeps the real (possibly past) date.
295
+ crosses_raw = forecast.get("crosses_budget_on")
296
+ crosses_cell: Any = "—"
297
+ if crosses_raw is not None:
298
+ if date.fromisoformat(str(crosses_raw)) <= datetime.now(timezone.utc).date():
299
+ crosses_cell = Text("over", style="bold red")
300
+ else:
301
+ crosses_cell = str(crosses_raw)
302
+ table.add_row(
303
+ _row_label(provider),
304
+ f"${format_decimal(daily)}" if daily is not None else "—",
305
+ Text(paid_text, style=paid_style) if paid_style else paid_text,
306
+ render_runway(Decimal(str(total)) if total is not None else None),
307
+ budget_text,
308
+ crosses_cell,
309
+ )
310
+ if not envelope["providers"]:
311
+ table.add_row("(no enabled providers)", "—", "—", "—", "—", "—")
312
+ out_console.print(table)
313
+
314
+ # Same one-budget concept as the status view: per-provider bars.
315
+ for provider in envelope["providers"]:
316
+ line = _budget_bar_line(_row_label(provider), provider.get("budget") or {})
317
+ if line:
318
+ out_console.print(line)
319
+
320
+ caveats: list[str] = []
321
+ for provider in envelope["providers"]:
322
+ forecast = provider.get("forecast") or {}
323
+ if not forecast:
324
+ continue
325
+ inputs = forecast.get("forecast_inputs") or {}
326
+ rendered = " ".join(f"{key}={value}" for key, value in inputs.items())
327
+ out_console.print(f"[dim]{_row_label(provider)} forecast inputs: {rendered}[/dim]")
328
+ for caveat in forecast.get("caveats") or []:
329
+ if caveat not in caveats:
330
+ caveats.append(caveat)
331
+ for caveat in caveats:
332
+ out_console.print(f"[dim]caveat: {caveat}[/dim]")
333
+
334
+ unattributed = (aggregate or {}).get("unattributed_calls", 0)
335
+ if unattributed:
336
+ out_console.print(
337
+ f"[dim]unattributed aux/foreign spend excluded: {unattributed} calls[/dim]"
338
+ )
339
+
340
+
341
+ @app.callback(invoke_without_command=True)
342
+ def main_callback(
343
+ ctx: typer.Context,
344
+ json_flag: bool = typer.Option(False, "--json", help="machine output (alias of -o json; -o wins)"),
345
+ output: str | None = typer.Option(None, "-o", "--output", help="output format: json | table (yaml reserved)"),
346
+ debug: bool = typer.Option(False, "-d", "--debug", help="debug output (redacted at the HTTP layer)"),
347
+ config: Path | None = typer.Option(None, "--config", help="path to config.toml", exists=False),
348
+ version: bool = typer.Option(False, "--version", help="print version and exit"),
349
+ ) -> None:
350
+ """Global flags shared by every command."""
351
+ ctx.ensure_object(dict)
352
+ ctx.obj["debug"] = debug
353
+ ctx.obj["config"] = config
354
+ try:
355
+ ctx.obj["format"] = _resolve_format(output, json_flag)
356
+ except CliError as exc:
357
+ err_console.print(str(exc))
358
+ raise typer.Exit(code=exc.code) from exc
359
+ if version:
360
+ out_console.print(f"burnclock {__version__}")
361
+ raise typer.Exit(code=0)
362
+ if ctx.invoked_subcommand is None:
363
+ # `burnclock` with no subcommand: run status in the REQUESTED format (F3)
364
+ # — `--json` / `-o json` must produce an envelope, not a table.
365
+ _status_impl(ctx, fmt=ctx.obj.get("format", "table"), view="status")
366
+
367
+
368
+ def _collect(config: Config, debug: bool) -> tuple[dict[str, Any], dict[str, Any] | None]:
369
+ """Shared fetch + burn/forecast block for status/forecast/dashboard.
370
+
371
+ Fetches deepseek (when enabled) and OpenRouter (only when enabled),
372
+ computes the B2-C2 burn/forecast/budget block from state.db (best-effort),
373
+ and returns `(envelope, aggregate)`. `aggregate` is the combined burn dict
374
+ for the human footer, or None when no rows were costed. Extracted so the
375
+ dashboard command reuses it verbatim — no duplication.
376
+ """
377
+ from burnclock_core.providers import deepseek # lazy: keeps config show lean
378
+
379
+ provider_cfg = config.provider("deepseek")
380
+ if provider_cfg is None or not provider_cfg.enabled:
381
+ result = None
382
+ else:
383
+ result = deepseek.fetch_balance(
384
+ provider_cfg.key_env or "DEEPSEEK_API_KEY",
385
+ warn_usd=provider_cfg.warn_usd,
386
+ alert_usd=provider_cfg.alert_usd,
387
+ )
388
+ if debug:
389
+ _print_debug(result.debug)
390
+
391
+ # OpenRouter: fetch only when the provider is enabled (default disabled
392
+ # -> skipped, no HTTP).
393
+ or_result = None
394
+ or_cfg = config.provider("openrouter")
395
+ if or_cfg is not None and or_cfg.enabled:
396
+ from burnclock_core.providers import openrouter
397
+
398
+ or_result = openrouter.fetch_balance(or_cfg.key_env or "OPENROUTER_API_KEY")
399
+ if debug:
400
+ _print_debug(or_result.debug)
401
+
402
+ # B3-A: Moonshot/xAI/MiniMax/fal — same lazy per-slug dispatch, fetched
403
+ # ONLY when enabled (all four default disabled -> skipped, no HTTP).
404
+ # xAI: missing team_id -> CONFIG_ERROR (exit 3), missing key ->
405
+ # KEY_REJECTED (exit 4) — decided by the row via envelope_exit, never
406
+ # patched in the CLI.
407
+ b3_results: dict[str, Any] = {}
408
+ for slug, default_key_env in (
409
+ ("moonshot", "MOONSHOT_API_KEY"),
410
+ ("xai", "XAI_MANAGEMENT_API_KEY"),
411
+ ("minimax", "MINIMAX_API_KEY"),
412
+ ("fal", "FAL_KEY"),
413
+ ):
414
+ b3_cfg = config.provider(slug)
415
+ if b3_cfg is None or not b3_cfg.enabled:
416
+ continue
417
+ module = importlib.import_module(f"burnclock_core.providers.{slug}")
418
+ fetch_kwargs: dict[str, Any] = {}
419
+ if slug == "xai":
420
+ fetch_kwargs["team_id"] = b3_cfg.team_id
421
+ elif slug == "minimax":
422
+ fetch_kwargs["region"] = b3_cfg.region or "auto"
423
+ elif slug == "fal":
424
+ fetch_kwargs["billing_mode"] = b3_cfg.billing_mode or "auto"
425
+ b3_result = module.fetch_balance(b3_cfg.key_env or default_key_env, **fetch_kwargs)
426
+ b3_results[slug] = b3_result
427
+ if debug:
428
+ _print_debug(b3_result.debug)
429
+
430
+ probe_lines: list[str] = []
431
+ if debug:
432
+ probe_result = usage_probe(config.hermes.resolved_home)
433
+ probe_lines = probe_summary_lines(probe_result)
434
+ _print_debug(probe_lines)
435
+
436
+ probe_error = (
437
+ probe_lines[-1] if probe_lines and probe_lines[-1].startswith("probe note") else None
438
+ )
439
+
440
+ # B2-C2 HERO block: burn/forecast/budget from state.db. Best-effort ONLY:
441
+ # any failure degrades to a probe note — never a crash, never fabricated
442
+ # numbers. Provider attribution is billing_provider == slug; aux/foreign
443
+ # rows land in neither per-provider list (they surface via the combined
444
+ # burn as the unattributed line item).
445
+ forecasts: list[Any] = []
446
+ budget_spend: dict[str, Decimal] = {}
447
+ aggregate: dict[str, Any] | None = None
448
+ # F8: set when the deepseek burn actually used the deepseek pricer
449
+ # (deepseek rows present in the window) -> the deepseek row's forecast
450
+ # caveats gain DEEPSEEK_CAVEATS (deduped against the §3.6 set).
451
+ deepseek_rows_in_window = False
452
+ try:
453
+ from burnclock_core.burn import compute_burn, month_spend
454
+ from burnclock_core.forecast import compute_forecast
455
+ from burnclock_core.pricing import build_pricer
456
+ from burnclock_core.usage import fetch_usage_rows
457
+
458
+ now_dt = datetime.now(timezone.utc)
459
+ rows = fetch_usage_rows(config.hermes.resolved_home)
460
+ providers_rows = {
461
+ "deepseek": [r for r in rows if r.get("billing_provider") == "deepseek"],
462
+ "openrouter": [r for r in rows if r.get("billing_provider") == "openrouter"],
463
+ }
464
+ pricers = {
465
+ "deepseek": build_pricer("deepseek"),
466
+ "openrouter": build_pricer("openrouter"),
467
+ }
468
+ for pid, provider_result in (("deepseek", result), ("openrouter", or_result)):
469
+ if provider_result is None or provider_result.usd is None:
470
+ continue
471
+ price_fn = pricers[pid] or (lambda m, t, toks: None)
472
+ burns = compute_burn(
473
+ providers_rows[pid],
474
+ now=now_dt,
475
+ window_days=config.settings.burn_window_days,
476
+ price_fn=price_fn,
477
+ )
478
+ if pid == "deepseek" and (burns.priced_calls + burns.excluded_calls) > 0:
479
+ deepseek_rows_in_window = True # F8: deepseek rows in window
480
+ pid_cfg = config.provider(pid)
481
+ budget = pid_cfg.budget_monthly_usd if pid_cfg else None
482
+ month = month_spend(providers_rows[pid], now=now_dt, price_fn=price_fn)
483
+ budget_spend[pid] = month
484
+ forecasts.append(
485
+ compute_forecast(
486
+ provider_id=pid,
487
+ granted_usd=provider_result.usd.granted,
488
+ topped_up_usd=provider_result.usd.topped_up,
489
+ burn=burns,
490
+ budget_usd=Decimal(str(budget)) if budget is not None else None,
491
+ now=now_dt.date(),
492
+ month_spend_usd=month,
493
+ )
494
+ )
495
+ if rows:
496
+ # Combined (aux-inclusive) burn: the top-level forecast_inputs
497
+ # values + the unattributed line item in the forecast view.
498
+ # R2: the combined pricer may only dispatch to ENABLED providers
499
+ # (deepseek always; openrouter only when its config flag is on —
500
+ # the same fetch set as the status command). Disabled-provider
501
+ # rows are excluded, never live-fetched.
502
+ or_cfg = config.provider("openrouter")
503
+ enabled = frozenset(
504
+ {"deepseek"}
505
+ | ({"openrouter"} if or_cfg is not None and or_cfg.enabled else set())
506
+ )
507
+ combined = compute_burn(
508
+ rows,
509
+ now=now_dt,
510
+ window_days=config.settings.burn_window_days,
511
+ price_fn=_combined_pricer(enabled),
512
+ )
513
+ aggregate = {
514
+ "window_days": combined.window_days,
515
+ "window_start": (
516
+ combined.window_start.strftime("%Y-%m-%d")
517
+ if combined.window_start
518
+ else None
519
+ ),
520
+ "spend_usd_sum": combined.spend_usd,
521
+ "daily_burn_usd": combined.daily_burn_usd,
522
+ "cost_source": combined.cost_sources_used,
523
+ "priced_calls": combined.priced_calls,
524
+ "unattributed_calls": combined.excluded_calls,
525
+ "unparseable_calls": combined.unparseable_calls,
526
+ }
527
+ except Exception as exc:
528
+ probe_error = f"forecast unavailable: {exc}"
529
+
530
+ from burnclock_core.envelope import build_status_envelope, envelope_exit
531
+
532
+ has_results = result is not None or or_result is not None or bool(b3_results)
533
+ envelope = build_status_envelope(
534
+ config=config,
535
+ deepseek=result,
536
+ openrouter=or_result,
537
+ probe_error=probe_error if has_results else None,
538
+ forecasts=forecasts,
539
+ budget_spend=budget_spend,
540
+ forecast_aggregate=aggregate,
541
+ )
542
+ if b3_results:
543
+ # B3-A: fetched B3 rows join the SAME envelope (deepseek, openrouter,
544
+ # then B3) — the envelope's own shape is untouched.
545
+ _append_b3_rows(envelope, config, b3_results)
546
+
547
+ # F8: append the deepseek rate-model caveats (peak/holiday) to the
548
+ # deepseek row's forecast caveats IFF its burn used the deepseek pricer
549
+ # (deepseek rows present in the window); deduped against what is there.
550
+ if deepseek_rows_in_window:
551
+ from burnclock_core.pricing import DEEPSEEK_CAVEATS
552
+
553
+ for row in envelope["providers"]:
554
+ if row.get("id") != "deepseek":
555
+ continue
556
+ caveats = (row.get("forecast") or {}).get("caveats")
557
+ if caveats is None:
558
+ continue
559
+ for caveat in DEEPSEEK_CAVEATS:
560
+ if caveat not in caveats:
561
+ caveats.append(caveat)
562
+ return envelope, aggregate
563
+
564
+
565
+ # B3-A: row labels + §3.5 semantics for the B3 adapters (fal flips to
566
+ # "postpaid" only via its explicit config hint — carried on the result).
567
+ _B3_ROW_META: dict[str, tuple[str, str]] = {
568
+ "moonshot": ("Moonshot", "prepaid"),
569
+ "xai": ("xAI", "prepaid"),
570
+ "minimax": ("MiniMax", "prepaid"),
571
+ "fal": ("fal", "prepaid"),
572
+ }
573
+
574
+
575
+ def _b3_threshold_state(result: Any, provider: Any) -> State:
576
+ """§3.2 threshold states for a B3 row (F3).
577
+
578
+ Only balance-bearing success rows are thresholded: EMPTY at/below zero,
579
+ CRITICAL below the provider's `alert_usd`, LOW below `warn_usd`. Missing
580
+ thresholds (None — the shipped default for all four B3 adapters) skip
581
+ LOW/CRITICAL rather than inventing values; balance-None rows (postpaid
582
+ fal, plan_quota) keep their adapter state. Non-OK/EMPTY adapter states
583
+ (auth/config/error/unreachable) are never rewritten.
584
+ """
585
+ state = result.state
586
+ if state not in (State.OK, State.EMPTY):
587
+ return state
588
+ amount = getattr(result, "balance_usd", None)
589
+ if amount is None:
590
+ return state
591
+ if amount <= 0:
592
+ return State.EMPTY
593
+ alert_usd = getattr(provider, "alert_usd", None)
594
+ warn_usd = getattr(provider, "warn_usd", None)
595
+ if alert_usd is not None and amount < Decimal(str(alert_usd)):
596
+ return State.CRITICAL
597
+ if warn_usd is not None and amount < Decimal(str(warn_usd)):
598
+ return State.LOW
599
+ return State.OK
600
+
601
+
602
+ def _append_b3_rows(envelope: dict[str, Any], config: Config, results: dict[str, Any]) -> None:
603
+ """Append the fetched B3 adapter rows to the envelope (B3-A).
604
+
605
+ Mirrors the deepseek/openrouter row shape — no envelope restructuring.
606
+ The row state decides its own exit code via envelope_exit (CONFIG_ERROR
607
+ -> 3, KEY_REJECTED/PERMISSION_DENIED -> 4, LOW/CRITICAL/EMPTY -> 5,
608
+ UNREACHABLE -> 6); `disabled_providers` (dashboard) is untouched — only
609
+ fetched providers land here.
610
+
611
+ F2: each row carries the adapter's `caveats` as an additive key (the
612
+ deepseek-row precedent) — never folded into `error`. F4: MiniMax
613
+ sk-cp- rows are `plan_quota` and emit `quota` while OMITTING `balance`
614
+ (absent, not null, per §3.5).
615
+ """
616
+ updated_at = str(envelope.get("generated_at") or "")
617
+ for slug, result in results.items():
618
+ label, semantics = _B3_ROW_META.get(slug, (slug, "prepaid"))
619
+ quota_percent = getattr(result, "quota_percent", None)
620
+ if slug == "minimax" and quota_percent is not None:
621
+ semantics = "plan_quota" # sk-cp- token-plan rows carry quota facts, no dollars
622
+ row_semantics = getattr(result, "semantics", None) or semantics
623
+ provider = config.provider(slug)
624
+ amount = getattr(result, "balance_usd", None)
625
+ currency = getattr(result, "currency", None) or "USD"
626
+ row: dict[str, Any] = {
627
+ "id": slug,
628
+ "label": label,
629
+ "semantics": row_semantics,
630
+ "verification": result.verification,
631
+ "status": _b3_threshold_state(result, provider).value,
632
+ "http_status": result.http_status,
633
+ "status_since": None,
634
+ "budget": {
635
+ "limit": provider.budget_monthly_usd if provider else None,
636
+ "currency": config.settings.currency,
637
+ "spend_window": "calendar_month",
638
+ "spent_est": None,
639
+ "cost_status": "estimated",
640
+ "remaining_budget": None,
641
+ },
642
+ "runway_days_paid": None, # B3 forecast lands later
643
+ "runway_days_total": None,
644
+ "crosses_budget_on": None,
645
+ "updated_at": updated_at,
646
+ "error": result.error_text,
647
+ }
648
+ if row_semantics == "plan_quota":
649
+ # §3.5 per-semantics nullability: quota present, balance ABSENT.
650
+ row["quota"] = {
651
+ "kind": "tokens",
652
+ "total": getattr(result, "quota_total", None),
653
+ "used": getattr(result, "quota_used", None),
654
+ "remaining": getattr(result, "quota_remaining", None),
655
+ "resets_at": getattr(result, "quota_resets_at", None),
656
+ }
657
+ else:
658
+ row["balance"] = {
659
+ "amount": float(amount) if amount is not None else None,
660
+ "currency": currency,
661
+ "granted": None,
662
+ "topped_up": None,
663
+ }
664
+ caveats = getattr(result, "caveats", None)
665
+ if caveats:
666
+ row["caveats"] = list(caveats)
667
+ envelope["providers"].append(row)
668
+
669
+
670
+ def _compute_alerts(
671
+ envelope: dict[str, Any],
672
+ min_usd: float | None = None,
673
+ min_days: float | None = None,
674
+ ) -> list[dict[str, Any]]:
675
+ """B3-B: `status --min/--min-days` alert entries (PLAN §9.1 Wave B3-b).
676
+
677
+ - `--min`: the CLI value ALONE (config warn_usd/alert_usd are NOT
678
+ consulted). Fires when an ENABLED provider row has a NUMERIC balance
679
+ below the threshold; negative balances fire; balance-None providers
680
+ (postpaid fal, fetch failures) are skipped — never exit 5 on
681
+ None < threshold.
682
+ - `--min-days`: reads row["forecast"]["runway_days_paid"] (top-level
683
+ runway fields are None — never used). Undefined runway
684
+ (insufficient_history / fetch failed / no key) is skipped, never
685
+ alerted; EMPTY + runway 0 -> ONE alert entry.
686
+
687
+ Envelope entries: {provider, kind: "min_balance"|"min_days", threshold,
688
+ actual} — additive, schema_version unchanged.
689
+ """
690
+ alerts: list[dict[str, Any]] = []
691
+ for row in envelope.get("providers", []):
692
+ if row.get("status") == "disabled":
693
+ continue # nothing was fetched — never alerted
694
+ provider = row.get("id")
695
+ if min_usd is not None:
696
+ amount = (row.get("balance") or {}).get("amount")
697
+ if amount is not None and float(amount) < min_usd:
698
+ alerts.append(
699
+ {
700
+ "provider": provider,
701
+ "kind": "min_balance",
702
+ "threshold": min_usd,
703
+ "actual": float(amount),
704
+ }
705
+ )
706
+ if min_days is not None:
707
+ paid = (row.get("forecast") or {}).get("runway_days_paid")
708
+ if paid is not None and float(paid) < min_days:
709
+ alerts.append(
710
+ {
711
+ "provider": provider,
712
+ "kind": "min_days",
713
+ "threshold": min_days,
714
+ "actual": float(paid),
715
+ }
716
+ )
717
+ return alerts
718
+
719
+
720
+ def _status_impl(
721
+ ctx: typer.Context,
722
+ fmt: str,
723
+ view: str = "status",
724
+ min_usd: float | None = None,
725
+ min_days: float | None = None,
726
+ ) -> None:
727
+ from burnclock_core.envelope import envelope_exit
728
+ from burnclock_core.schema import EXIT_THRESHOLD, worst_exit
729
+
730
+ config = _load_config(ctx.obj.get("config"))
731
+ envelope, aggregate = _collect(config, bool(ctx.obj.get("debug")))
732
+
733
+ # F8: envelope_exit is the SOLE exit computation — the envelope rows
734
+ # carry status + http_status, so ERROR rows self-report their code.
735
+ # An empty provider set exits 0 (envelope_exit([]) == 0).
736
+ exit_code = envelope_exit(envelope)
737
+
738
+ # B3-B: `--min` / `--min-days` alerts ride the SAME envelope as an
739
+ # additive `alerts` list. Alerts are machine-path semantics: they combine
740
+ # with state-derived exits under worst_exit — both firing is still ONE
741
+ # exit 5.
742
+ alerts = _compute_alerts(envelope, min_usd=min_usd, min_days=min_days)
743
+ if alerts:
744
+ # F9: EXTEND, never overwrite — dedupe by (kind, provider) so a
745
+ # pre-populated alerts list can never silently lose entries.
746
+ existing = envelope.setdefault("alerts", [])
747
+ seen = {(a.get("kind"), a.get("provider")) for a in existing}
748
+ for alert in alerts:
749
+ key = (alert.get("kind"), alert.get("provider"))
750
+ if key in seen:
751
+ continue
752
+ existing.append(alert)
753
+ seen.add(key)
754
+ envelope["alerts"] = existing
755
+ exit_code = worst_exit(exit_code, EXIT_THRESHOLD)
756
+
757
+ if fmt == "json":
758
+ out_console.print_json(json.dumps(envelope))
759
+ raise typer.Exit(code=exit_code)
760
+
761
+ # Human view: status is data, not failure — exit 0 whenever output was produced.
762
+ if view == "forecast":
763
+ _forecast_human_view(envelope, aggregate)
764
+ else:
765
+ _status_human_view(envelope, aggregate)
766
+ # B3-B human alert lines: name the provider + actual vs threshold.
767
+ for alert in alerts:
768
+ if alert["kind"] == "min_balance":
769
+ out_console.print(
770
+ f"[red]ALERT[/red] {alert['provider']}: balance "
771
+ f"${format_decimal(alert['actual'])} is below --min "
772
+ f"${format_decimal(alert['threshold'])}"
773
+ )
774
+ else:
775
+ out_console.print(
776
+ f"[red]ALERT[/red] {alert['provider']}: runway "
777
+ f"{format_decimal(alert['actual'])}d is below --min-days "
778
+ f"{format_decimal(alert['threshold'])}d"
779
+ )
780
+ _maybe_print_upgrade_nudge()
781
+ raise typer.Exit(code=0)
782
+
783
+
784
+ def _dashboard_impl(ctx: typer.Context, fmt: str, filters: list[str] | None) -> None:
785
+ """B2-C2 CONT4: the FULL table view — every known provider slug.
786
+
787
+ Fetched providers (exactly the status fetch set: deepseek when enabled,
788
+ OpenRouter when enabled) render as in status; every other known slug
789
+ renders a disabled row (State "disabled", all other cells "—").
790
+ Optional positional provider filters narrow the rows; an unknown name is
791
+ a provider-slug validation failure (exit 3 — plan amendment 2026-10-16;
792
+ exit 2 remains for unknown commands/flags/formats) naming the valid slugs.
793
+
794
+ JSON: the status envelope + one extra top-level `disabled_providers` key
795
+ (slugs not fetched — the fetch-disabled set, config order); `providers`
796
+ stays the fetched rows only. Exit follows envelope_exit of the FETCHED
797
+ envelope (same rules as status) — a filter narrows what is SHOWN, never
798
+ what an attempted fetch means for the exit code. Disabled-only with no
799
+ fetch attempt -> exit 0.
800
+ """
801
+ from burnclock_core.envelope import envelope_exit
802
+
803
+ config = _load_config(ctx.obj.get("config"))
804
+ known = sorted(config.providers)
805
+ requested = list(dict.fromkeys(filters or []))
806
+ unknown = [slug for slug in requested if slug not in config.providers]
807
+ if unknown:
808
+ err_console.print(
809
+ f"[red]unknown provider:[/red] {', '.join(unknown)} "
810
+ f"(valid slugs: {', '.join(known)})"
811
+ )
812
+ raise typer.Exit(code=3)
813
+
814
+ envelope, aggregate = _collect(config, bool(ctx.obj.get("debug")))
815
+ exit_code = envelope_exit(envelope)
816
+
817
+ fetched = {row["id"]: row for row in envelope["providers"]}
818
+ # "Enabled" in dashboard terms = actually fetched (deepseek when its
819
+ # config flag is on; openrouter only when enabled). Every other known
820
+ # slug — including config-enabled-but-unfetchable ones (fal, minimax,
821
+ # moonshot, xai) — is fetch-disabled.
822
+ disabled = [slug for slug in known if slug not in fetched]
823
+
824
+ if fmt == "json":
825
+ payload = dict(envelope)
826
+ payload["providers"] = [
827
+ row for row in envelope["providers"] if not requested or row["id"] in requested
828
+ ]
829
+ payload["disabled_providers"] = [
830
+ slug for slug in disabled if not requested or slug in requested
831
+ ]
832
+ out_console.print_json(json.dumps(payload))
833
+ raise typer.Exit(code=exit_code)
834
+
835
+ # Human rows: config order, filter-aware. Every non-fetched slug gets
836
+ # the disabled row — nothing was fetched, so nothing is fabricated.
837
+ display_rows: list[dict[str, Any]] = []
838
+ for slug in known:
839
+ if requested and slug not in requested:
840
+ continue
841
+ if slug in fetched:
842
+ display_rows.append(fetched[slug])
843
+ continue
844
+ display_rows.append(
845
+ {"id": slug, "label": slug, "status": "disabled", "budget": {}}
846
+ )
847
+
848
+ display_envelope = dict(envelope)
849
+ display_envelope["providers"] = display_rows
850
+ _status_human_view(display_envelope, aggregate)
851
+ _maybe_print_upgrade_nudge()
852
+ raise typer.Exit(code=0)
853
+
854
+
855
+ @app.command("status")
856
+ def status_cmd(
857
+ ctx: typer.Context,
858
+ json_flag: bool = typer.Option(False, "--json", help="machine output (alias of -o json; -o wins)"),
859
+ output: str | None = typer.Option(None, "-o", "--output", help="output format: json | table"),
860
+ debug: bool = typer.Option(False, "-d", "--debug", help="debug output (redacted)"),
861
+ min_usd: float | None = typer.Option(
862
+ None,
863
+ "--min",
864
+ help="alert (exit 5, machine path) when an enabled provider's balance is below this USD — the CLI value alone; config warn/alert thresholds are not consulted",
865
+ ),
866
+ min_days: float | None = typer.Option(
867
+ None,
868
+ "--min-days",
869
+ help="alert (exit 5, machine path) when an enabled provider's paid runway is below this many days (forecast.runway_days_paid)",
870
+ ),
871
+ ) -> None:
872
+ """Provider status: human table (exit 0) or envelope v1 (exit per §3.3)."""
873
+ # Command-level flags override globals; -o still wins over --json.
874
+ if debug:
875
+ ctx.obj["debug"] = True
876
+ if output is not None or json_flag:
877
+ try:
878
+ ctx.obj["format"] = _resolve_format(output, json_flag)
879
+ except CliError as exc:
880
+ err_console.print(str(exc))
881
+ raise typer.Exit(code=exc.code) from exc
882
+ _status_impl(
883
+ ctx,
884
+ ctx.obj.get("format", "table"),
885
+ view="status",
886
+ min_usd=min_usd,
887
+ min_days=min_days,
888
+ )
889
+
890
+
891
+ @app.command("forecast")
892
+ def forecast_cmd(
893
+ ctx: typer.Context,
894
+ json_flag: bool = typer.Option(False, "--json", help="machine output (alias of -o json; -o wins)"),
895
+ output: str | None = typer.Option(None, "-o", "--output", help="output format: json | table"),
896
+ debug: bool = typer.Option(False, "-d", "--debug", help="debug output (redacted)"),
897
+ ) -> None:
898
+ """Forecast: paid runway, burn/day, budget crossing — estimates, not billing truth."""
899
+ if debug:
900
+ ctx.obj["debug"] = True
901
+ if output is not None or json_flag:
902
+ try:
903
+ ctx.obj["format"] = _resolve_format(output, json_flag)
904
+ except CliError as exc:
905
+ err_console.print(str(exc))
906
+ raise typer.Exit(code=exc.code) from exc
907
+ _status_impl(ctx, ctx.obj.get("format", "table"), view="forecast")
908
+
909
+
910
+ @app.command("dashboard")
911
+ def dashboard_cmd(
912
+ ctx: typer.Context,
913
+ providers: Annotated[list[str] | None, typer.Argument()] = None,
914
+ json_flag: bool = typer.Option(False, "--json", help="machine output (alias of -o json; -o wins)"),
915
+ output: str | None = typer.Option(None, "-o", "--output", help="output format: json | table"),
916
+ debug: bool = typer.Option(False, "-d", "--debug", help="debug output (redacted)"),
917
+ ) -> None:
918
+ """Dashboard: every known provider — live rows as in status, disabled rows for the rest."""
919
+ if debug:
920
+ ctx.obj["debug"] = True
921
+ if output is not None or json_flag:
922
+ try:
923
+ ctx.obj["format"] = _resolve_format(output, json_flag)
924
+ except CliError as exc:
925
+ err_console.print(str(exc))
926
+ raise typer.Exit(code=exc.code) from exc
927
+ _dashboard_impl(ctx, ctx.obj.get("format", "table"), providers)
928
+
929
+
930
+ # --- B3-B: `watch` (§3.3 amendment F4) --------------------------------------
931
+
932
+ _WATCH_DEFAULT_INTERVAL_S = 60.0
933
+ _WATCH_MIN_INTERVAL_S = 5.0
934
+
935
+
936
+ def _stdout_is_tty() -> bool:
937
+ """Injectable TTY probe: the TUI runs ONLY on an interactive stdout."""
938
+ try:
939
+ return bool(sys.stdout.isatty())
940
+ except Exception:
941
+ return False
942
+
943
+
944
+ def _run_watch_tui(config: Config, interval_s: float, debug: bool) -> None:
945
+ """Textual TUI for `burnclock watch` on a TTY (optional extra `[tui]`).
946
+
947
+ Textual is imported LAZILY here — never at module level, never on a
948
+ piped path. ImportError (not installed) or any runtime failure is caught
949
+ by the caller, which degrades to the plain refresh loop + one stderr
950
+ warning.
951
+ """
952
+ from textual.app import App, ComposeResult
953
+ from textual.widgets import Static
954
+
955
+ class BurnclockWatchApp(App):
956
+ """Minimal live table: one refresh per interval, no ANSI questions
957
+ (Textual owns the screen only on a real terminal)."""
958
+
959
+ def compose(self) -> ComposeResult:
960
+ yield Static("burnclock watch — loading…", id="rows")
961
+
962
+ def on_mount(self) -> None:
963
+ self.refresh_rows()
964
+ self.set_interval(interval_s, self.refresh_rows)
965
+
966
+ def refresh_rows(self) -> None:
967
+ try:
968
+ envelope, _aggregate = _collect(config, debug)
969
+ except Exception as exc: # refresh failure never kills the TUI
970
+ self.query_one("#rows", Static).update(f"burnclock watch: refresh failed: {exc}")
971
+ return
972
+ lines: list[str] = []
973
+ for row in envelope.get("providers", []):
974
+ balance = row.get("balance") or {}
975
+ amount = balance.get("amount")
976
+ balance_text = (
977
+ f" {format_decimal(amount)} {balance.get('currency', '')}".rstrip()
978
+ if amount is not None
979
+ else ""
980
+ )
981
+ lines.append(f"{_row_label(row)}: {row.get('status', '?')}{balance_text}")
982
+ if not lines:
983
+ lines = ["(no enabled providers)"]
984
+ lines.append(f"(refreshing every {interval_s:g}s — q or Ctrl+C to quit)")
985
+ self.query_one("#rows", Static).update("\n".join(lines))
986
+
987
+ BurnclockWatchApp().run()
988
+
989
+
990
+ def _watch_impl(ctx: typer.Context, interval_s: float, fmt: str) -> None:
991
+ """`watch` loop (§3.3 B3 amendment F4):
992
+
993
+ - TTY + no --json -> Textual TUI; import/runtime failure degrades to the
994
+ plain loop + ONE stderr warning.
995
+ - piped/non-TTY stdout: NO TUI EVER. Without --json -> the plain status
996
+ table per refresh; with --json -> JSON LINES: one FULL envelope object
997
+ per refresh, flushed, self-describing, no accumulated array.
998
+ ZERO ANSI/CSI bytes on piped stdout (plain renderer + raw writes).
999
+ - Ctrl+C -> exit 130; a JSON line is flushed only once complete.
1000
+ """
1001
+ config = _load_config(ctx.obj.get("config"))
1002
+ debug = bool(ctx.obj.get("debug"))
1003
+
1004
+ if fmt != "json" and _stdout_is_tty():
1005
+ tui_error: Exception | None = None
1006
+ try:
1007
+ _run_watch_tui(config, interval_s, debug)
1008
+ except ImportError as exc:
1009
+ tui_error = exc
1010
+ except Exception as exc: # runtime TUI failure -> degrade, never crash
1011
+ tui_error = exc
1012
+ if tui_error is None:
1013
+ raise typer.Exit(code=0) # user quit the TUI cleanly
1014
+ err_console.print(
1015
+ f"[yellow]watch: TUI unavailable ({tui_error}) — "
1016
+ "falling back to the plain refresh loop[/yellow]"
1017
+ )
1018
+
1019
+ try:
1020
+ while True:
1021
+ envelope, aggregate = _collect(config, debug)
1022
+ if fmt == "json":
1023
+ # Complete objects only: json.dumps finishes before the write,
1024
+ # and the line is flushed as a whole (no partial JSON lines).
1025
+ sys.stdout.write(json.dumps(envelope) + "\n")
1026
+ sys.stdout.flush()
1027
+ else:
1028
+ _status_human_view(envelope, aggregate)
1029
+ time.sleep(interval_s)
1030
+ except KeyboardInterrupt:
1031
+ raise typer.Exit(code=130) from None
1032
+
1033
+
1034
+ @app.command("watch")
1035
+ def watch_cmd(
1036
+ ctx: typer.Context,
1037
+ interval: str = typer.Option(
1038
+ str(int(_WATCH_DEFAULT_INTERVAL_S)),
1039
+ "--interval",
1040
+ help="refresh interval in seconds (default 60; clamped to a minimum of 5)",
1041
+ ),
1042
+ json_flag: bool = typer.Option(False, "--json", help="JSON LINES: one full envelope per refresh"),
1043
+ debug: bool = typer.Option(False, "-d", "--debug", help="debug output (redacted)"),
1044
+ ) -> None:
1045
+ """Watch balances live: Textual TUI on a TTY; plain table/JSONL when piped."""
1046
+ if debug:
1047
+ ctx.obj["debug"] = True
1048
+ if json_flag:
1049
+ ctx.obj["format"] = "json"
1050
+ try:
1051
+ interval_s = float(interval)
1052
+ except (TypeError, ValueError):
1053
+ err_console.print(
1054
+ f"[red]invalid --interval:[/red] {interval!r} (expected a number of seconds)"
1055
+ )
1056
+ raise typer.Exit(code=2)
1057
+ # Min 5s: clamp, don't error (NaN/inf also clamp to the floor).
1058
+ if not interval_s == interval_s or interval_s in (float("inf"), float("-inf")):
1059
+ interval_s = _WATCH_MIN_INTERVAL_S
1060
+ interval_s = max(_WATCH_MIN_INTERVAL_S, interval_s)
1061
+ _watch_impl(ctx, interval_s, ctx.obj.get("format", "table"))
1062
+
1063
+
1064
+ @config_app.command("show")
1065
+ def config_show(
1066
+ ctx: typer.Context,
1067
+ json_flag: bool = typer.Option(False, "--json", help="machine output (alias of -o json; -o wins)"),
1068
+ output: str | None = typer.Option(None, "-o", "--output", help="output format: json | table"),
1069
+ ) -> None:
1070
+ """Print the effective configuration (defaults + file + env overrides)."""
1071
+ if output is not None or json_flag:
1072
+ try:
1073
+ ctx.obj["format"] = _resolve_format(output, json_flag)
1074
+ except CliError as exc:
1075
+ err_console.print(str(exc))
1076
+ raise typer.Exit(code=exc.code) from exc
1077
+ config = _load_config(ctx.obj.get("config"))
1078
+
1079
+ if ctx.obj.get("format") == "json":
1080
+ payload = {
1081
+ "config_path": str(config.config_path),
1082
+ "loaded_from": str(config.loaded_from) if config.loaded_from else None,
1083
+ "settings": {
1084
+ "currency": config.settings.currency,
1085
+ "burn_window_days": config.settings.burn_window_days,
1086
+ "cache_ttl_balance_s": config.settings.cache_ttl_balance_s,
1087
+ "cache_ttl_usage_s": config.settings.cache_ttl_usage_s,
1088
+ },
1089
+ "providers": {
1090
+ slug: {
1091
+ k: v
1092
+ for k, v in {
1093
+ "enabled": p.enabled,
1094
+ "key_env": p.key_env,
1095
+ "admin_key_env": p.admin_key_env,
1096
+ "warn_usd": p.warn_usd,
1097
+ "alert_usd": p.alert_usd,
1098
+ "budget_monthly_usd": p.budget_monthly_usd,
1099
+ "team_id": p.team_id,
1100
+ }.items()
1101
+ if v is not None
1102
+ }
1103
+ for slug, p in sorted(config.providers.items())
1104
+ },
1105
+ "hermes": {
1106
+ "home": config.hermes.home,
1107
+ "resolved_home": str(config.hermes.resolved_home),
1108
+ "profiles": list(config.hermes.profiles),
1109
+ },
1110
+ }
1111
+ out_console.print_json(json.dumps(payload))
1112
+ else:
1113
+ # markup=False: TOML section headers like [settings] must not be
1114
+ # interpreted (and stripped) as Rich markup.
1115
+ out_console.print(render_config_toml(config), markup=False)
1116
+ out_console.print("")
1117
+ source = str(config.loaded_from) if config.loaded_from else f"{config.config_path} (not found — using defaults)"
1118
+ out_console.print(f"# config file: {source}", markup=False)
1119
+ out_console.print(f"# hermes home: {config.hermes.resolved_home} (from '{config.hermes.home}')", markup=False)
1120
+ _maybe_print_upgrade_nudge()
1121
+ raise typer.Exit(code=0)
1122
+
1123
+
1124
+ @config_app.command("path")
1125
+ def config_path_cmd(ctx: typer.Context) -> None:
1126
+ """Print the config file path ($XDG_CONFIG_HOME/burnclock/config.toml)."""
1127
+ config = _load_config(ctx.obj.get("config"))
1128
+ out_console.print(str(config.config_path))
1129
+ raise typer.Exit(code=0)
1130
+
1131
+
1132
+ # --- B2-D: budget get/set/unset (config persistence, headless-safe) ---------
1133
+
1134
+ _BUDGET_MAX_USD = Decimal("1000000")
1135
+
1136
+
1137
+ def _validate_provider_slug(slug: str) -> str:
1138
+ if slug not in PROVIDER_SLUGS:
1139
+ err_console.print(
1140
+ f"[red]unknown provider:[/red] {slug} "
1141
+ f"(frozen slugs: {', '.join(PROVIDER_SLUGS)})"
1142
+ )
1143
+ raise typer.Exit(code=3)
1144
+ return slug
1145
+
1146
+
1147
+ def _parse_budget_amount(amount: str) -> Decimal | None:
1148
+ """USD amount (> 0, <= 1,000,000) or literal `none` -> None (clear).
1149
+
1150
+ Anything else is a config-class failure: exit 3, no write.
1151
+ """
1152
+ text = amount.strip().lower()
1153
+ if text == "none":
1154
+ return None
1155
+ try:
1156
+ value = Decimal(text)
1157
+ except InvalidOperation:
1158
+ value = Decimal("NaN")
1159
+ if not value.is_finite() or value <= 0 or value > _BUDGET_MAX_USD:
1160
+ err_console.print(
1161
+ f"[red]invalid amount:[/red] {amount!r} "
1162
+ "(use a number > 0 and <= 1000000, or 'none' to clear)"
1163
+ )
1164
+ raise typer.Exit(code=3)
1165
+ return value
1166
+
1167
+
1168
+ def _file_budget_overrides(config: Config, slug: str) -> bool:
1169
+ """True when config.toml itself sets this provider's budget_monthly_usd."""
1170
+ if config.loaded_from is None or not config.loaded_from.exists():
1171
+ return False
1172
+ try:
1173
+ data = tomllib.loads(config.loaded_from.read_text(encoding="utf-8"))
1174
+ except (OSError, tomllib.TOMLDecodeError):
1175
+ return False
1176
+ prov = data.get("providers")
1177
+ if not isinstance(prov, dict):
1178
+ return False
1179
+ entry = prov.get(slug)
1180
+ return isinstance(entry, dict) and "budget_monthly_usd" in entry
1181
+
1182
+
1183
+ def _budget_display(budget: float | None) -> str:
1184
+ return format_decimal(budget) if budget is not None else "—"
1185
+
1186
+
1187
+ def _budget_line(config: Config, slug: str) -> str:
1188
+ """`deepseek budget_monthly_usd = 50.00 (default)` / `= — (default)`."""
1189
+ p = config.provider(slug)
1190
+ budget = p.budget_monthly_usd if p else None
1191
+ source = "config.toml" if _file_budget_overrides(config, slug) else "default"
1192
+ return f"{slug} budget_monthly_usd = {_budget_display(budget)} ({source})"
1193
+
1194
+
1195
+ def _offline_or_pricer() -> OpenRouterPricer:
1196
+ """Offline-safe OpenRouterPricer for the dry-run alert simulation (R1).
1197
+
1198
+ Serves a warm cache when present, otherwise the bundled OR_FALLBACK
1199
+ table — the fetcher is suppressed, so NO network call can ever happen.
1200
+ """
1201
+ from burnclock_core.pricing import DEFAULT_CACHE_DIR, OpenRouterPricer
1202
+
1203
+ def _no_fetch() -> dict:
1204
+ raise RuntimeError("network suppressed: offline alert simulation")
1205
+
1206
+ return OpenRouterPricer(DEFAULT_CACHE_DIR, fetcher=_no_fetch)
1207
+
1208
+
1209
+ def _alert_simulation_line(config: Config, slug: str, budget: Decimal) -> str:
1210
+ """D7: offline alert simulation for `budget set --dry-run` — NO API calls.
1211
+
1212
+ Dispatch BY SLUG (CRITIC-C R1): `deepseek` rows price with the offline
1213
+ DeepSeek table (F2 — tier-3 log-priced rows count too); `openrouter`
1214
+ rows with the offline-safe OpenRouterPricer (cache/OR_FALLBACK, fetcher
1215
+ suppressed); any other slug has no offline pricer -> the honest
1216
+ "unavailable (no offline pricer for <slug>)" line. Only slug-attributed
1217
+ rows are summed, so the line names the ACTUAL provider and carries a
1218
+ spend-only suffix whenever other providers' rows exist (openrouter
1219
+ always carries its "offline rates" caveat). Any read failure (state.db
1220
+ missing/unreadable/no rows) degrades to the honest "unavailable" line —
1221
+ never a fabricated number.
1222
+ """
1223
+ if slug == "deepseek":
1224
+ slug_label = "deepseek"
1225
+ elif slug == "openrouter":
1226
+ slug_label = "openrouter"
1227
+ else:
1228
+ return f"alert simulation: unavailable (no offline pricer for {slug})"
1229
+ try:
1230
+ from burnclock_core.burn import month_spend
1231
+ from burnclock_core.usage import fetch_usage_rows
1232
+
1233
+ rows = fetch_usage_rows(config.hermes.resolved_home)
1234
+ if not rows:
1235
+ return "alert simulation: unavailable (state.db unreadable)"
1236
+ now_dt = datetime.now(timezone.utc)
1237
+ if slug == "deepseek":
1238
+ from burnclock_core.pricing import deepseek_price as price_fn
1239
+
1240
+ suffix = (
1241
+ " (deepseek spend only)"
1242
+ if any(r.get("billing_provider") != "deepseek" for r in rows)
1243
+ else ""
1244
+ )
1245
+ else:
1246
+ price_fn = _offline_or_pricer()
1247
+ suffix = " (openrouter spend only, offline rates)"
1248
+ provider_rows = [r for r in rows if r.get("billing_provider") == slug]
1249
+ spend = month_spend(provider_rows, now=now_dt, price_fn=price_fn)
1250
+ spent_txt = format_decimal(spend)
1251
+ budget_txt = format_decimal(budget)
1252
+ if spend >= budget:
1253
+ return (
1254
+ f"alert simulation: would fire CRITICAL on {slug_label} at current spend "
1255
+ f"(${spent_txt} spent this month >= ${budget_txt} budget){suffix}"
1256
+ )
1257
+ return (
1258
+ "alert simulation: would not fire at current spend "
1259
+ f"(${spent_txt} spent this month < ${budget_txt} budget){suffix}"
1260
+ )
1261
+ except Exception:
1262
+ return "alert simulation: unavailable (state.db unreadable)"
1263
+
1264
+
1265
+ def _budget_set_impl(
1266
+ ctx: typer.Context,
1267
+ slug: str,
1268
+ budget: Decimal | None,
1269
+ yes: bool,
1270
+ dry_run: bool,
1271
+ ) -> None:
1272
+ """Shared write path for `budget set` / `budget unset` (B2-D rulings)."""
1273
+ config = _load_config(ctx.obj.get("config"))
1274
+ path = config.config_path
1275
+
1276
+ if dry_run:
1277
+ out_console.print(f"[providers.{slug}]", markup=False)
1278
+ if budget is None:
1279
+ out_console.print("budget_monthly_usd = none (the key is removed)", markup=False)
1280
+ else:
1281
+ out_console.print(f"budget_monthly_usd = {float(budget)}", markup=False)
1282
+ out_console.print(
1283
+ f"would write: {path} (comments in an existing file are dropped)",
1284
+ markup=False,
1285
+ )
1286
+ # D7: offline alert simulation — computed from state.db only.
1287
+ if budget is None:
1288
+ out_console.print(
1289
+ "alert simulation: no budget after unset (no alert thresholds for this provider)",
1290
+ markup=False,
1291
+ )
1292
+ else:
1293
+ out_console.print(_alert_simulation_line(config, slug, budget), markup=False)
1294
+ raise typer.Exit(code=0)
1295
+
1296
+ # Headless safety (CRITIC #30): a non-TTY without --yes/--dry-run never writes.
1297
+ if not yes and not sys.stdout.isatty():
1298
+ err_console.print("[red]headless: pass --yes or --dry-run[/red]")
1299
+ raise typer.Exit(code=3)
1300
+
1301
+ if not yes:
1302
+ if not typer.confirm(f"Overwrite {path}?"):
1303
+ out_console.print("no changes made")
1304
+ raise typer.Exit(code=0)
1305
+
1306
+ try:
1307
+ write_provider_budget(path, slug, budget)
1308
+ except (ConfigError, OSError) as exc:
1309
+ err_console.print(f"[red]config error:[/red] {exc}")
1310
+ raise typer.Exit(code=3) from exc
1311
+
1312
+ out_console.print(_budget_line(_load_config(ctx.obj.get("config")), slug))
1313
+ raise typer.Exit(code=0)
1314
+
1315
+
1316
+ @budget_app.command("get")
1317
+ def budget_get(
1318
+ ctx: typer.Context,
1319
+ provider: str | None = typer.Argument(None, help="provider slug (omit for all configured providers)"),
1320
+ ) -> None:
1321
+ """Show resolved monthly budgets (config.toml override vs code default)."""
1322
+ config = _load_config(ctx.obj.get("config"))
1323
+ if provider is not None:
1324
+ out_console.print(_budget_line(config, _validate_provider_slug(provider)))
1325
+ raise typer.Exit(code=0)
1326
+
1327
+ slugs = [slug for slug, p in sorted(config.providers.items()) if p.enabled]
1328
+ if "deepseek" not in slugs:
1329
+ slugs.append("deepseek") # deepseek is always listed
1330
+
1331
+ table = Table(title="burnclock — monthly budgets", show_lines=False)
1332
+ table.add_column("Provider", style="bold")
1333
+ table.add_column("Monthly budget")
1334
+ table.add_column("Source")
1335
+ for slug in slugs:
1336
+ p = config.provider(slug)
1337
+ budget = p.budget_monthly_usd if p else None
1338
+ source = "config.toml" if _file_budget_overrides(config, slug) else "default"
1339
+ table.add_row(slug, _budget_display(budget), source)
1340
+ out_console.print(table)
1341
+ raise typer.Exit(code=0)
1342
+
1343
+
1344
+ # B2-C2 CONT4: `budget show` is an exact alias of `budget get` — same
1345
+ # function object, so arguments, options, validation, and output are identical.
1346
+ budget_app.command("show")(budget_get)
1347
+
1348
+
1349
+ @budget_app.command("set")
1350
+ def budget_set(
1351
+ ctx: typer.Context,
1352
+ provider: str = typer.Argument(..., help="provider slug"),
1353
+ amount: str = typer.Argument(..., help="monthly budget in USD (> 0, <= 1000000) or 'none' to clear"),
1354
+ yes: bool = typer.Option(False, "--yes", help="write without an interactive confirmation (required when headless)"),
1355
+ dry_run: bool = typer.Option(False, "--dry-run", help="show what would be written; write nothing"),
1356
+ ) -> None:
1357
+ """Set a provider's monthly budget in config.toml (per-provider)."""
1358
+ slug = _validate_provider_slug(provider)
1359
+ budget = _parse_budget_amount(amount)
1360
+ _budget_set_impl(ctx, slug, budget, yes=yes, dry_run=dry_run)
1361
+
1362
+
1363
+ @budget_app.command("unset")
1364
+ def budget_unset(
1365
+ ctx: typer.Context,
1366
+ provider: str = typer.Argument(..., help="provider slug"),
1367
+ yes: bool = typer.Option(False, "--yes", help="write without an interactive confirmation (required when headless)"),
1368
+ dry_run: bool = typer.Option(False, "--dry-run", help="show what would be written; write nothing"),
1369
+ ) -> None:
1370
+ """Clear a provider's monthly budget (alias for `budget set PROVIDER none`)."""
1371
+ slug = _validate_provider_slug(provider)
1372
+ _budget_set_impl(ctx, slug, None, yes=yes, dry_run=dry_run)
1373
+
1374
+
1375
+ @app.command("completion")
1376
+ def completion_cmd(
1377
+ shell: str = typer.Argument(..., help="shell to generate a script for: bash, zsh, or fish"),
1378
+ ) -> None:
1379
+ """Print a static shell completion script (bash, zsh, fish) to stdout."""
1380
+ from burnclock_cli.completions import SUPPORTED_SHELLS, completion_script
1381
+
1382
+ script = completion_script(shell)
1383
+ if script is None:
1384
+ err_console.print(
1385
+ f"[red]unsupported shell:[/red] {shell!r} "
1386
+ f"(supported shells: {', '.join(SUPPORTED_SHELLS)})"
1387
+ )
1388
+ raise typer.Exit(code=EXIT_USAGE)
1389
+ # Raw write: completion output is plain text, never Rich-rendered, so it
1390
+ # stays byte-identical (zero ANSI/CSI) even on a TTY.
1391
+ sys.stdout.write(script)
1392
+ sys.stdout.flush()
1393
+ raise typer.Exit(code=0)
1394
+
1395
+
1396
+ @app.command("version")
1397
+ def version_cmd() -> None:
1398
+ """Print the burnclock version."""
1399
+ out_console.print(f"burnclock {__version__}")
1400
+ raise typer.Exit(code=0)
1401
+
1402
+
1403
+ def run() -> None:
1404
+ app()
1405
+
1406
+
1407
+ if __name__ == "__main__":
1408
+ run()