llmswap-cli 1.0.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.
Files changed (78) hide show
  1. claude_swap/__init__.py +24 -0
  2. claude_swap/__main__.py +6 -0
  3. claude_swap/app_bundle.py +330 -0
  4. claude_swap/appearance.py +219 -0
  5. claude_swap/autoswitch.py +3065 -0
  6. claude_swap/cache.py +44 -0
  7. claude_swap/claude_locks.py +279 -0
  8. claude_swap/cli.py +2265 -0
  9. claude_swap/credentials.py +2156 -0
  10. claude_swap/exceptions.py +102 -0
  11. claude_swap/fsutil.py +409 -0
  12. claude_swap/json_output.py +455 -0
  13. claude_swap/launch_agent.py +862 -0
  14. claude_swap/lines.py +153 -0
  15. claude_swap/list_view.py +371 -0
  16. claude_swap/locking.py +87 -0
  17. claude_swap/logging_config.py +64 -0
  18. claude_swap/macos_keychain.py +240 -0
  19. claude_swap/mappings.py +127 -0
  20. claude_swap/menubar.py +1433 -0
  21. claude_swap/migrations.py +360 -0
  22. claude_swap/models.py +329 -0
  23. claude_swap/oauth.py +1628 -0
  24. claude_swap/pace.py +161 -0
  25. claude_swap/paths.py +250 -0
  26. claude_swap/poll_policy.py +337 -0
  27. claude_swap/printer.py +252 -0
  28. claude_swap/process_detection.py +370 -0
  29. claude_swap/session.py +2696 -0
  30. claude_swap/settings.py +827 -0
  31. claude_swap/signin.py +238 -0
  32. claude_swap/snapshot_source.py +121 -0
  33. claude_swap/spawn.py +135 -0
  34. claude_swap/subscription.py +349 -0
  35. claude_swap/switcher.py +9807 -0
  36. claude_swap/transfer.py +807 -0
  37. claude_swap/tui/__init__.py +43 -0
  38. claude_swap/tui/app.py +482 -0
  39. claude_swap/tui/autoview.py +381 -0
  40. claude_swap/tui/cswap.tcss +205 -0
  41. claude_swap/tui/dashboard.py +434 -0
  42. claude_swap/tui/data.py +194 -0
  43. claude_swap/tui/modals.py +159 -0
  44. claude_swap/tui/theme.py +88 -0
  45. claude_swap/tui/widgets.py +544 -0
  46. claude_swap/update_check.py +509 -0
  47. claude_swap/usage_bars.py +208 -0
  48. claude_swap/usage_rows.py +160 -0
  49. claude_swap/usage_store.py +1429 -0
  50. llmswap/AGENTS.md +11 -0
  51. llmswap/__init__.py +3 -0
  52. llmswap/__main__.py +4 -0
  53. llmswap/cli.py +535 -0
  54. llmswap/config.py +101 -0
  55. llmswap/httpjson.py +50 -0
  56. llmswap/jwt.py +20 -0
  57. llmswap/menubar.py +218 -0
  58. llmswap/model.py +172 -0
  59. llmswap/paths.py +41 -0
  60. llmswap/providers/AGENTS.md +12 -0
  61. llmswap/providers/base.py +619 -0
  62. llmswap/providers/claude.py +187 -0
  63. llmswap/providers/codex.py +274 -0
  64. llmswap/providers/gemini.py +80 -0
  65. llmswap/providers/registry.py +30 -0
  66. llmswap/render.py +127 -0
  67. llmswap/rotate.py +102 -0
  68. llmswap/store.py +138 -0
  69. llmswap/tui.py +182 -0
  70. llmswap/usage_cache.py +72 -0
  71. llmswap/warm/plan.py +118 -0
  72. llmswap/warm/runner.py +175 -0
  73. llmswap/warm/schedule.py +264 -0
  74. llmswap_cli-1.0.0.dist-info/METADATA +181 -0
  75. llmswap_cli-1.0.0.dist-info/RECORD +78 -0
  76. llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
  77. llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
  78. llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,208 @@
1
+ """Usage bars and the palette that paints them, for every surface.
2
+
3
+ ``cswap watch`` (Textual) and ``cswap list``/``cswap status`` on a terminal
4
+ draw a usage window the same way: a severity-coloured fill on a dim track,
5
+ with a tick on the auto-switch line that window is judged against. This
6
+ module holds that bar and its colours without importing Textual, so the plain
7
+ CLI pays only for Rich (measured: ~5 ms on top of the ~33 ms CLI import), not
8
+ for the TUI framework. ``tui/theme.py`` maps these colours onto Textual's
9
+ design tokens.
10
+
11
+ ``bar_cells`` is a custom renderer rather than Textual's ``ProgressBar``
12
+ because the design needs three things the stock widget doesn't do: a
13
+ severity colour ramp, an optional threshold tick mark, and stale-measurement
14
+ dimming.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+ from typing import TYPE_CHECKING, ClassVar
21
+
22
+ from rich.text import Text
23
+
24
+ from claude_swap.oauth import FIVE_HOUR_LABEL
25
+
26
+ if TYPE_CHECKING:
27
+ from textual.theme import Theme
28
+
29
+ # Dark palette: neutral charcoal backgrounds, one warm terracotta accent (the
30
+ # xterm-173 tone printer.py uses for the CLI accent), desaturated severity
31
+ # colours so usage bars read calmly.
32
+ ACCENT = "#d7875f" # warm terracotta (xterm 173)
33
+ FOREGROUND = "#e8e4de" # soft, slightly warm off-white
34
+ MUTED = "#8a8a8a" # secondary text
35
+ BACKGROUND = "#141414"
36
+ SURFACE = "#1e1e1e"
37
+ PANEL = "#262626"
38
+ SEV_OK = "#87af87" # calm green: plenty of headroom
39
+ SEV_WARN = "#d7af5f" # amber: climbing (>= 70%)
40
+ SEV_CRIT = "#d75f5f" # soft red: near the limit (>= 90%)
41
+ TRACK = "#3a3a3a" # unfilled bar track
42
+ INFO = "#87afd7" # cool blue: Team/Enterprise plans, Desktop instances
43
+ VIOLET = "#af87d7" # IDE instances
44
+
45
+ # Light companion palette (same intent, tuned for a warm near-white base).
46
+ ACCENT_LIGHT = "#954c2a" # burnt sienna, deepened for AA on panel (worst-case row bg)
47
+ FOREGROUND_LIGHT = "#2b2723"
48
+ MUTED_LIGHT = "#635d55"
49
+ BACKGROUND_LIGHT = "#faf7f2"
50
+ SURFACE_LIGHT = "#efeae1"
51
+ PANEL_LIGHT = "#e2dbcf" # most-elevated = darkest (inverted from dark)
52
+ SEV_OK_LIGHT = "#3d6b3d" # forest green, deepened for AA on panel
53
+ SEV_WARN_LIGHT = "#795911" # deep ochre, deepened for AA on panel
54
+ SEV_CRIT_LIGHT = "#ad3128" # brick red, deepened for AA on panel
55
+ TRACK_LIGHT = "#cec7ba"
56
+ INFO_LIGHT = "#2f5f8f"
57
+ VIOLET_LIGHT = "#6b4c9a"
58
+
59
+ # Severity band edges. WARN mirrors where a user starts caring; CRIT mirrors
60
+ # the auto-switch default threshold so bar colour and switch behaviour agree.
61
+ WARN_PCT = 70.0
62
+ CRIT_PCT = 90.0
63
+
64
+ BAR_FILLED = "━"
65
+ BAR_HALF = "╸"
66
+ BAR_EMPTY = "─"
67
+ BAR_TICK = "┃"
68
+
69
+ # Bar width bounds of the TUI card. The CLI rows share the upper one and
70
+ # have a floor of their own (``list_view.ROW_BAR_MIN``).
71
+ BAR_MIN = 12
72
+ BAR_MAX = 30
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Palette:
77
+ """Resolved colours for Rich renderables.
78
+
79
+ Rich renderables bake colour into styles at render time, so they can't
80
+ read Textual's ``$variables`` the way the .tcss layer does. A Palette
81
+ carries one theme's colours so the same render code paints correctly in
82
+ either theme. In the TUI, resolve it from the Theme object (never
83
+ App.theme_variables, which lags the deferred CSS refresh)."""
84
+
85
+ accent: str
86
+ foreground: str
87
+ muted: str
88
+ sev_ok: str
89
+ sev_warn: str
90
+ sev_crit: str
91
+ track: str
92
+ # Only the CLI bar layout (``list_view``) paints these.
93
+ background: str = BACKGROUND
94
+ info: str = INFO
95
+ violet: str = VIOLET
96
+
97
+ DARK: ClassVar[Palette]
98
+ LIGHT: ClassVar[Palette]
99
+ BASIC: ClassVar[Palette]
100
+
101
+ def severity(self, pct: float | None) -> str:
102
+ if pct is None:
103
+ return self.muted
104
+ if pct >= CRIT_PCT:
105
+ return self.sev_crit
106
+ if pct >= WARN_PCT:
107
+ return self.sev_warn
108
+ return self.sev_ok
109
+
110
+ @classmethod
111
+ def from_theme(cls, theme: Theme) -> Palette:
112
+ return cls(
113
+ accent=theme.primary,
114
+ foreground=theme.foreground,
115
+ muted=theme.secondary,
116
+ sev_ok=theme.success,
117
+ sev_warn=theme.warning,
118
+ sev_crit=theme.error,
119
+ track=theme.variables.get("track", TRACK),
120
+ )
121
+
122
+
123
+ Palette.DARK = Palette(
124
+ accent=ACCENT,
125
+ foreground=FOREGROUND,
126
+ muted=MUTED,
127
+ sev_ok=SEV_OK,
128
+ sev_warn=SEV_WARN,
129
+ sev_crit=SEV_CRIT,
130
+ track=TRACK,
131
+ background=BACKGROUND,
132
+ info=INFO,
133
+ violet=VIOLET,
134
+ )
135
+ Palette.LIGHT = Palette(
136
+ accent=ACCENT_LIGHT,
137
+ foreground=FOREGROUND_LIGHT,
138
+ muted=MUTED_LIGHT,
139
+ sev_ok=SEV_OK_LIGHT,
140
+ sev_warn=SEV_WARN_LIGHT,
141
+ sev_crit=SEV_CRIT_LIGHT,
142
+ track=TRACK_LIGHT,
143
+ background=BACKGROUND_LIGHT,
144
+ info=INFO_LIGHT,
145
+ violet=VIOLET_LIGHT,
146
+ )
147
+ # For terminals with only the 16 standard colours. Rich maps a hex colour to
148
+ # the nearest of those, and the desaturated severity colours above all land
149
+ # on white, so this palette names the ANSI colours instead and keeps the
150
+ # severity readable.
151
+ Palette.BASIC = Palette(
152
+ accent="magenta",
153
+ foreground="default",
154
+ muted="default",
155
+ sev_ok="green",
156
+ sev_warn="yellow",
157
+ sev_crit="red",
158
+ track="bright_black",
159
+ background="black",
160
+ info="cyan",
161
+ violet="blue",
162
+ )
163
+
164
+
165
+ def switch_line(
166
+ label: str, threshold: float | None, weekly_threshold: float | None
167
+ ) -> float | None:
168
+ """The auto-switch line a bar row's tick marks: ``weekly_threshold``,
169
+ when set, on the 7d and per-model rows, which reset weekly, and
170
+ ``threshold`` on the 5h and spend (``$$``) rows and on every row while no
171
+ weekly line is set."""
172
+ if weekly_threshold is not None and label not in ("$$", FIVE_HOUR_LABEL):
173
+ return weekly_threshold
174
+ return threshold
175
+
176
+
177
+ def bar_cells(
178
+ pct: float | None,
179
+ width: int,
180
+ *,
181
+ stale: bool = False,
182
+ threshold: float | None = None,
183
+ palette: Palette = Palette.DARK,
184
+ ) -> Text:
185
+ """Just the bar glyphs: severity-coloured fill, track, optional tick."""
186
+ text = Text()
187
+ if pct is None:
188
+ text.append(BAR_EMPTY * width, style=palette.track)
189
+ return text
190
+ frac = min(max(pct, 0.0), 100.0) / 100.0
191
+ cells = frac * width
192
+ full = int(cells)
193
+ half = (cells - full) >= 0.5 and full < width
194
+ tick_at: int | None = None
195
+ if threshold is not None:
196
+ tick_at = min(width - 1, max(0, round(threshold / 100.0 * width)))
197
+ color = palette.severity(pct)
198
+ fill_style = f"{color} dim" if stale else color
199
+ for i in range(width):
200
+ if tick_at is not None and i == tick_at:
201
+ text.append(BAR_TICK, style=palette.sev_warn)
202
+ elif i < full:
203
+ text.append(BAR_FILLED, style=fill_style)
204
+ elif i == full and half:
205
+ text.append(BAR_HALF, style=fill_style)
206
+ else:
207
+ text.append(BAR_EMPTY, style=palette.track)
208
+ return text
@@ -0,0 +1,160 @@
1
+ """The rows of one usage measurement, as the CLI views show them.
2
+
3
+ ``build_usage_rows`` walks a measurement once and yields one ``UsageRow`` per
4
+ window it reports, in display order: spend, 5h, 7d, the per-model windows
5
+ (e.g. Fable), and a refused header probe. Each row keeps its figures (the
6
+ percentage, the reset strings, the seconds left), so the plain text layout
7
+ (``row_body``) and the bar layout of ``cswap list`` on a terminal render the
8
+ same walk instead of re-deriving it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import time
14
+ from dataclasses import dataclass
15
+ from datetime import datetime
16
+ from typing import Literal
17
+
18
+ from claude_swap import oauth, pace
19
+
20
+ RowKind = Literal["spend", "window", "passed", "rejected"]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class UsageRow:
25
+ """One window of a measurement.
26
+
27
+ ``kind`` is ``"passed"`` for a window whose reset has come
28
+ (``oauth.window_reset_passed``): its stored figure describes the window
29
+ that ended, so ``pct`` is None and ``reset`` holds when it ended.
30
+ ``pct`` is also None for a 5h/7d window reported without a figure.
31
+ ``reset`` is ``(countdown, clock)`` from ``oauth.fresh_reset_strings``,
32
+ ``resets_in_s`` the seconds until that reset when ``resets_at`` is
33
+ readable. ``marker`` is the trailing ``" (ahead of pace)"`` or
34
+ ``" (!)"``, and ``amounts`` the spend row's ``"$used / $limit"``.
35
+ """
36
+
37
+ label: str
38
+ kind: RowKind
39
+ pct: float | None
40
+ reset: tuple[str, str] | None
41
+ resets_in_s: float | None = None
42
+ marker: str = ""
43
+ amounts: str | None = None
44
+
45
+
46
+ def _pace_marker(window: dict, fetched_at: float | None) -> str:
47
+ """ " (ahead of pace)" when a weekly window is meaningfully ahead of pace, else ""."""
48
+ result = pace.compute_pace(window, fetched_at=fetched_at)
49
+ return " (ahead of pace)" if result and result.ahead else ""
50
+
51
+
52
+ def _resets_in_s(window: dict, now: float) -> float | None:
53
+ """Seconds until ``window`` resets, or None when ``resets_at`` is unreadable."""
54
+ try:
55
+ return datetime.fromisoformat(window["resets_at"]).timestamp() - now
56
+ except (KeyError, TypeError, ValueError):
57
+ return None
58
+
59
+
60
+ def _window_row(
61
+ label: str, window: dict, pct: float | None, marker: str, now: float
62
+ ) -> UsageRow:
63
+ return UsageRow(
64
+ label=label,
65
+ kind="window",
66
+ pct=pct,
67
+ reset=oauth.fresh_reset_strings(window),
68
+ resets_in_s=_resets_in_s(window, now),
69
+ marker=marker,
70
+ )
71
+
72
+
73
+ def _passed_row(label: str, window: dict) -> UsageRow:
74
+ return UsageRow(
75
+ label=label, kind="passed", pct=None, reset=oauth.fresh_reset_strings(window)
76
+ )
77
+
78
+
79
+ def build_usage_rows(usage: dict, fetched_at: float | None = None) -> list[UsageRow]:
80
+ """The rows of one measurement, in display order (module docstring)."""
81
+ now = time.time()
82
+ rows: list[UsageRow] = []
83
+ spend = usage.get("spend")
84
+ if spend:
85
+ rows.append(
86
+ UsageRow(
87
+ label="$$",
88
+ kind="spend",
89
+ pct=spend["pct"],
90
+ reset=oauth.fresh_reset_strings(spend),
91
+ resets_in_s=_resets_in_s(spend, now),
92
+ amounts=f"${spend['used']:,.2f} / ${spend['limit']:,.2f}",
93
+ )
94
+ )
95
+ for label, w in (("5h", usage.get("five_hour")), ("7d", usage.get("seven_day"))):
96
+ if not w:
97
+ continue
98
+ if oauth.window_reset_passed(w):
99
+ rows.append(_passed_row(label, w))
100
+ continue
101
+ # Pace only applies to the weekly (7d) window, never 5h (issue #125).
102
+ marker = _pace_marker(w, fetched_at) if label == "7d" else ""
103
+ pct = w.get("pct")
104
+ rows.append(
105
+ _window_row(
106
+ label, w, pct if isinstance(pct, (int, float)) else None, marker, now
107
+ )
108
+ )
109
+ for w in usage.get("scoped") or []:
110
+ if oauth.window_reset_passed(w):
111
+ rows.append(_passed_row(w["name"], w))
112
+ continue
113
+ # Per-model weekly limits (e.g. Fable). Flag ones at/over the limit so a
114
+ # maxed model, the usual reason to switch, stands out.
115
+ marker = " (!)" if w["pct"] >= 100 else _pace_marker(w, fetched_at)
116
+ rows.append(_window_row(w["name"], w, w["pct"], marker, now))
117
+ rejected = usage.get("rejected")
118
+ if isinstance(rejected, dict):
119
+ # A refused header probe (setup-tokens): at its limit until it ends.
120
+ rows.append(
121
+ UsageRow(
122
+ label="probe",
123
+ kind="rejected",
124
+ pct=100.0,
125
+ reset=oauth.fresh_reset_strings(rejected),
126
+ resets_in_s=_resets_in_s(rejected, now),
127
+ )
128
+ )
129
+ return rows
130
+
131
+
132
+ def pct_text(row: UsageRow) -> str:
133
+ """The row's figure, right-aligned in four columns: ``" 38%"``, ``" ?"``."""
134
+ return " ?" if row.pct is None else f"{row.pct:>3.0f}%"
135
+
136
+
137
+ def row_body(row: UsageRow) -> str:
138
+ """The plain-text body of a row, after its ``label:``::
139
+
140
+ 38% resets Dec 7 03:59 in 6d 1h (ahead of pace)
141
+ ? reset Nov 26 03:20
142
+ rejected until Dec 2 06:00 in 1d 3h
143
+
144
+ A passed window is laid out like a current row, so the clocks share a
145
+ column.
146
+ """
147
+ if row.kind == "rejected":
148
+ if row.reset is None:
149
+ return "rejected"
150
+ return f"rejected until {row.reset[1]:<12} in {row.reset[0]}"
151
+ if row.kind == "passed":
152
+ return f" ? {'reset':<6} {row.reset[1] if row.reset else ''}"
153
+ if row.kind == "spend":
154
+ if row.reset is None:
155
+ return f"{pct_text(row)} {row.amounts}"
156
+ return f"{pct_text(row)} resets {row.reset[1]:<12} {row.amounts}"
157
+ if row.reset is None:
158
+ return f"{pct_text(row)}{row.marker}"
159
+ countdown, clock = row.reset
160
+ return f"{pct_text(row)} resets {clock:<12} in {countdown}{row.marker}"