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,337 @@
1
+ """Cadence policy for the ``/api/oauth/usage`` endpoint — every number in one place.
2
+
3
+ The endpoint enforces a budget on non-first-party clients: a **~60-minute
4
+ window of ~28-30 requests per identity × UA-class** (measured 2026-07-11,
5
+ probe3, two runs: a rested identity admitted 30 requests before the first
6
+ 429; the post-drain 429 oscillation ended exactly when the drain burst aged
7
+ 60 minutes; steady 1/180 s polling then ran 96 minutes from a rested window
8
+ with zero 429s). It is NOT a bucket with a refill rate: capacity returns
9
+ only as old requests age out of the trailing hour, so a burst saturates the
10
+ identity for up to a full hour — pausing does not restore headroom early,
11
+ and earlier "refill rate" estimates were artifacts of measuring while
12
+ saturated.
13
+
14
+ What that identity is depends on which 429 regime the org is on — the two
15
+ regimes coexist across orgs (see the Retry-After discussion in
16
+ ``usage_store``). Under the fixed-deadline regime it is the **account/org**
17
+ (measured 2026-07-28: a freshly minted token was blocked 135 s after issue,
18
+ which a per-token counter cannot produce). Under the saturated-edge
19
+ (``Retry-After: 0``) regime it is the **access token** (measured 2026-07-29,
20
+ probe4: at saturation, a freshly minted token of the same lineage was
21
+ admitted while the old token stayed blocked, requests interleaved). Plan for
22
+ the account-scoped case — it is the conservative one: re-authenticating
23
+ cannot be relied on to clear a block, and two machines holding different
24
+ tokens for one account may share one budget, which is what
25
+ ``POST_429_BACKOFF_MULT`` below exists to converge.
26
+
27
+ Error bars: the horizon is bracketed to ~55-64 minutes from a single
28
+ transition event, the exact edge algorithm (likely a Cloudflare
29
+ sliding-window approximation) is undocumented, and Anthropic can retune it
30
+ any day — so the constants below lean only on the robust parts: a sustained
31
+ rate safely under the cap, and an ~hour recovery horizon. The budget target
32
+ is an **average of at most ~1 request / 3 minutes** (20/hour vs the ~28-30/
33
+ hour cap), leaving ~8-10 requests/hour of headroom for manual commands,
34
+ wake-from-sleep catch-up, and the bounded urgent mode below.
35
+
36
+ Health invariant to watch in the logs: steady state shows zero http-429.
37
+ A post-burst 429 does NOT reliably clear at its stated horizon — measured
38
+ over one machine's full log (re-measured 2026-08-03; re-derive rather than
39
+ trust this verbatim, it ages as the log grows — method recorded next to
40
+ ``usage_store.RETRY_AFTER_MARGIN_S``), 20 of 35 lapsed blocks re-blocked
41
+ within 900s of their own deadline (+2s..+887s), each for a fresh full hour
42
+ ("of 35", not 38 raw gaps: 3 are negative — NOT a uniform mechanism (one has
43
+ no within-block revision at all, one is revised BACKWARD mid-block, one is
44
+ unchanged — see usage_store.RETRY_AFTER_MARGIN_S's comment for the per-gap
45
+ detail) — excluded from both numerator and denominator; round 8 switched
46
+ from the prior "21 of 36"/"2 of 38" figures here to these, on the OTHER of
47
+ two equally-reproducing readings — see usage_store.RETRY_AFTER_MARGIN_S's
48
+ comment for which reading and why).
49
+ The prior "10 of 23" figure here did not reproduce under any of 40 method
50
+ variants swept and is superseded. That is why the wait is Retry-After plus
51
+ ``usage_store.RETRY_AFTER_MARGIN_S`` and not Retry-After alone. What would
52
+ mean this model needs revisiting is a 429 episode at modest rates that
53
+ outlasts an hour *past* that margin.
54
+
55
+ Plans computed here are persisted per account in the usage store
56
+ (``nextPollAt``/``pollIntervalS``) by whichever collector fetched, so every
57
+ surface — ``cswap list``, the TUI, the menu bar, the auto engine — inherits
58
+ the same cadence no matter how often it repaints.
59
+
60
+ If a future probe revises the measured shape, adjust the constants in this
61
+ module only.
62
+ """
63
+
64
+ from __future__ import annotations
65
+
66
+ import random
67
+ from collections.abc import Callable
68
+ from datetime import datetime
69
+
70
+ from claude_swap import oauth
71
+ from claude_swap.lines import window_line
72
+
73
+ # Freshness floor shared by every collector: an entry younger than this is
74
+ # served from the store without any fetch, so the maximum sustained rate on
75
+ # one token is 1/SERVE_TTL_S regardless of how many surfaces are open.
76
+ SERVE_TTL_S = 180.0
77
+
78
+ # Normal cadence floor — movement can halve an interval down to this, never
79
+ # below.
80
+ MIN_INTERVAL_S = 180.0
81
+
82
+ # Urgent mode: the ACTIVE account, with some window that ROSE this poll to
83
+ # within ESCALATION_MARGIN_PCT of its own switch line (i.e. actually burning
84
+ # toward a limit — a window dropping into the band just gained room). Judged
85
+ # per window rather than on the binding max: a 5h window closing on its line
86
+ # under a flat, higher weekly window is exactly the burn a max-only rule is
87
+ # blind to. Bounded by construction: either the line is crossed (the engine
88
+ # switches away) or the rise stops (the next poll decays back to
89
+ # MIN_INTERVAL_S) — worst case margin/movement-delta ≈ 15 polls per episode,
90
+ # inside the measured ~28-30 request rolling-hour window; overshoot on top of
91
+ # steady traffic is absorbed by the post-429 floor below.
92
+ URGENT_INTERVAL_S = 60.0
93
+
94
+ # Decay ceilings for an account whose usage is not moving: the active account
95
+ # stays reasonably fresh, an idle alternate drifts out to ten minutes.
96
+ ACTIVE_MAX_INTERVAL_S = 300.0
97
+ CANDIDATE_DEFAULT_INTERVAL_S = 300.0
98
+ CANDIDATE_MAX_INTERVAL_S = 600.0
99
+
100
+ # Exhaustion is stable enough to poll slowly, but not to stop polling until a
101
+ # reported reset. Quota grants and provider-side corrections can make an
102
+ # account usable before that timestamp, and decision-grade status must not age
103
+ # into "unavailable" while the scheduler is deliberately waiting. Ten-minute
104
+ # polling (six requests/hour) stays below the measured budget and
105
+ # detects recovery promptly; a nearer reported reset still pulls the next poll
106
+ # forward.
107
+ EXHAUSTED_INTERVAL_S = 600.0
108
+
109
+ # An account whose binding (max) pct moved at least this much between polls
110
+ # is being consumed somewhere (this machine, another PC, session mode) →
111
+ # tighten; an unmoved one backs off toward its ceiling. Urgent mode reads the
112
+ # same delta per window, rising only.
113
+ MOVEMENT_DELTA_PCT = 1.0
114
+
115
+ # ±fraction applied to each scheduled interval so independent processes
116
+ # (watch + menu bar + auto) drift apart instead of fetching in lockstep.
117
+ JITTER_FRAC = 0.1
118
+
119
+ # Reaction to a 429 with ``Retry-After: 0`` (the saturated-window edge):
120
+ # probe at most every 5 minutes (≤12/hour) so aging-out — up to ~30/hour —
121
+ # outpaces the probing (used by the usage store's failure backoff)...
122
+ EDGE_BACKOFF_S = 300.0
123
+ # ...and while any 429 was seen on the token within this window, floor the
124
+ # planned cadence here so freed capacity accumulates instead of being
125
+ # re-spent. The window matches the saturation horizon: a full trailing hour
126
+ # takes up to 60 minutes to age out.
127
+ POST_429_MIN_INTERVAL_S = 360.0
128
+ RECENT_429_WINDOW_S = 3600.0
129
+
130
+ # AIMD on a contended budget. The budget is shared across every machine
131
+ # polling the same account (under the account-scoped regime a machine with its
132
+ # own token is no less a competitor — see the module docstring on scope),
133
+ # none of them can see the others, and the endpoint
134
+ # exposes no remaining-request count — only a Retry-After once already
135
+ # blocked. So while 429s recur, each successful poll multiplicatively grows the
136
+ # interval (×POST_429_BACKOFF_MULT) toward POST_429_MAX_INTERVAL_S — wider than
137
+ # the normal candidate ceiling so several machines can each back off far enough
138
+ # that their combined rate fits under the budget. Movement (a real success run
139
+ # with no recent 429) decays it back down. This is TCP-style congestion control:
140
+ # the budget gets fair-shared by reaction alone, with no machine count or
141
+ # shared state to configure.
142
+ POST_429_BACKOFF_MULT = 1.5
143
+ POST_429_MAX_INTERVAL_S = 1800.0
144
+
145
+ # The engine escalates to a full candidate refresh when any of the active
146
+ # account's windows is within this margin of its own switch line (decision
147
+ # policy, but the urgent-mode cadence keys on the same band, so it lives with
148
+ # the cadence numbers).
149
+ ESCALATION_MARGIN_PCT = 15.0
150
+
151
+ # Never schedule a poll later than a known window reset (+ slack): stored
152
+ # usage is obsolete the moment the window rolls over.
153
+ RESET_SLACK_S = 60.0
154
+
155
+ # The header probe's per-model request (``usage.fableProbe``) stops once that
156
+ # model's weekly bucket is spent: usage only rises within a window, so until
157
+ # the bucket resets another request can only be refused or billed to usage
158
+ # credits. Unlike the account-level poll above, which keeps a slow cadence at
159
+ # exhaustion to notice an early grant, this pause is complete, because a
160
+ # request on credits costs money the user did not agree to spend; the price
161
+ # is that a bucket Anthropic resets early reads as spent until its advertised
162
+ # reset. A spent response that names neither a reset nor a Retry-After is
163
+ # asked about again after SCOPED_PROBE_RETRY_S, and no deadline further away
164
+ # than a weekly bucket's own period is honoured.
165
+ SCOPED_PROBE_RETRY_S = 3600.0
166
+ SCOPED_PROBE_MAX_PAUSE_S = 7 * 86400.0
167
+
168
+
169
+ def binding_pct(usage: dict | None, models: tuple[str, ...] = ()) -> float | None:
170
+ """Utilization of the binding (worst) relevant window, or None."""
171
+ headroom = oauth.account_headroom(usage, models)
172
+ return None if headroom is None else 100.0 - headroom
173
+
174
+
175
+ def limiting_reset_ts(
176
+ usage: dict | None, models: tuple[str, ...] = ()
177
+ ) -> float | None:
178
+ """Epoch when the last of the ≥100% relevant windows resets (account
179
+ usable again)."""
180
+ latest: float | None = None
181
+ for _, pct, resets_at in oauth.relevant_windows(usage, models):
182
+ if pct < 100.0:
183
+ continue
184
+ ts = parse_reset_ts(resets_at)
185
+ if ts is not None and (latest is None or ts > latest):
186
+ latest = ts
187
+ return latest
188
+
189
+
190
+ def earliest_future_reset_ts(
191
+ usage: dict | None, now: float, models: tuple[str, ...] = ()
192
+ ) -> float | None:
193
+ """Epoch of the next relevant-window reset ahead of ``now``, any
194
+ utilization."""
195
+ earliest: float | None = None
196
+ for _, _, resets_at in oauth.relevant_windows(usage, models):
197
+ ts = parse_reset_ts(resets_at)
198
+ if ts is not None and ts > now and (earliest is None or ts < earliest):
199
+ earliest = ts
200
+ return earliest
201
+
202
+
203
+ def parse_reset_ts(resets_at: str | None) -> float | None:
204
+ if not resets_at:
205
+ return None
206
+ try:
207
+ return datetime.fromisoformat(
208
+ str(resets_at).replace("Z", "+00:00")
209
+ ).timestamp()
210
+ except ValueError:
211
+ return None
212
+
213
+
214
+ def scoped_probe_after(
215
+ now: float, resets_at: str | None, retry_after_s: float | None
216
+ ) -> float:
217
+ """Epoch before which a per-model bucket just read as spent is not
218
+ probed again.
219
+
220
+ The server's Retry-After when the refusal carried a positive one, else
221
+ the bucket's reset, else ``SCOPED_PROBE_RETRY_S`` from now. Never past
222
+ the bucket's reset (the stored row describes nothing after it) and never
223
+ more than ``SCOPED_PROBE_MAX_PAUSE_S`` away.
224
+ """
225
+ reset_ts = parse_reset_ts(resets_at)
226
+ if retry_after_s is not None and retry_after_s > 0:
227
+ until = now + retry_after_s
228
+ elif reset_ts is not None:
229
+ until = reset_ts
230
+ else:
231
+ until = now + SCOPED_PROBE_RETRY_S
232
+ if reset_ts is not None:
233
+ until = min(until, reset_ts)
234
+ return min(until, now + SCOPED_PROBE_MAX_PAUSE_S)
235
+
236
+
237
+ def scoped_probe_paused(row: dict, now: float) -> bool:
238
+ """Whether a stored per-model row is still kept in place of a new probe.
239
+
240
+ True while its ``probe_after`` (:func:`scoped_probe_after`) lies ahead
241
+ and its own reset has not passed. A deadline more than
242
+ ``SCOPED_PROBE_MAX_PAUSE_S`` away is not one this module writes (a
243
+ reading imported from another machine can carry anything), so it pauses
244
+ nothing.
245
+ """
246
+ until = parse_reset_ts(row.get("probe_after"))
247
+ if until is None or not now < until <= now + SCOPED_PROBE_MAX_PAUSE_S:
248
+ return False
249
+ reset_ts = parse_reset_ts(row.get("resets_at"))
250
+ return reset_ts is None or now < reset_ts
251
+
252
+
253
+ def plan_after_fetch(
254
+ *,
255
+ prev_interval_s: float | None,
256
+ prev_usage: dict | None,
257
+ new_usage: dict | None,
258
+ is_active: bool,
259
+ threshold: float,
260
+ models: tuple[str, ...],
261
+ recent_429: bool,
262
+ now: float,
263
+ weekly_threshold: float | None = None,
264
+ rng: Callable[[], float] = random.random,
265
+ ) -> tuple[float, float]:
266
+ """``(next_poll_at, interval_s)`` for an account just fetched successfully.
267
+
268
+ Movement (binding pct changed ≥ ``MOVEMENT_DELTA_PCT`` since the previous
269
+ poll) halves the interval, floored at ``MIN_INTERVAL_S`` — or drops to
270
+ ``URGENT_INTERVAL_S`` when one of the active account's windows rose by
271
+ that much into the escalation band under its own line (``threshold`` for
272
+ the 5h window, ``weekly_threshold`` when set for the weekly ones). No
273
+ movement backs off ×1.5 toward the account's ceiling;
274
+ unknown utilization uses the default. A recent 429 on this token floors
275
+ the cadence at ``POST_429_MIN_INTERVAL_S`` (and suppresses urgent mode)
276
+ until ``RECENT_429_WINDOW_S`` has passed. The scheduled time gets
277
+ ``JITTER_FRAC`` noise, is never later than the account's next window
278
+ reset (+ ``RESET_SLACK_S``). An at-limit account keeps a bounded slow
279
+ poll instead of sleeping until that reset, so an early provider-side
280
+ quota grant is observed and its decision-grade status stays current.
281
+ """
282
+ default = MIN_INTERVAL_S if is_active else CANDIDATE_DEFAULT_INTERVAL_S
283
+ ceiling = ACTIVE_MAX_INTERVAL_S if is_active else CANDIDATE_MAX_INTERVAL_S
284
+ base = prev_interval_s or default
285
+ prev_pct = binding_pct(prev_usage, models)
286
+ new_pct = binding_pct(new_usage, models)
287
+ if prev_pct is None or new_pct is None:
288
+ moving = False
289
+ interval = default
290
+ elif abs(new_pct - prev_pct) >= MOVEMENT_DELTA_PCT:
291
+ moving = True
292
+ interval = max(MIN_INTERVAL_S, base / 2)
293
+ else:
294
+ # Floored so a sub-floor base (urgent mode's 60s) snaps straight back
295
+ # to the normal cadence once movement stops, instead of decaying
296
+ # through 90s/135s polls that the budget never intended.
297
+ moving = False
298
+ interval = min(ceiling, max(MIN_INTERVAL_S, base * 1.5))
299
+ # Per window, by label, rising only: the window that matters for a switch
300
+ # may not be the max (5h climbing under a flat higher 7d), and a window
301
+ # that just dropped into the band is a rollover, not a burn.
302
+ prev_pcts = {
303
+ label: pct for label, pct, _ in oauth.relevant_windows(prev_usage, models)
304
+ }
305
+ rising_in_band = any(
306
+ label in prev_pcts
307
+ and pct - prev_pcts[label] >= MOVEMENT_DELTA_PCT
308
+ and pct >= window_line(label, threshold, weekly_threshold) - ESCALATION_MARGIN_PCT
309
+ for label, pct, _ in oauth.relevant_windows(new_usage, models)
310
+ )
311
+ if is_active and rising_in_band and not recent_429:
312
+ interval = URGENT_INTERVAL_S
313
+ if recent_429:
314
+ # AIMD additive-increase: grow the interval multiplicatively from the
315
+ # last one toward the wider 429 ceiling, so machines sharing a
316
+ # contended token each retreat until their combined rate fits the
317
+ # budget. Floored at POST_429_MIN_INTERVAL_S for the first 429.
318
+ increased = max(base * POST_429_BACKOFF_MULT, POST_429_MIN_INTERVAL_S)
319
+ interval = min(POST_429_MAX_INTERVAL_S, max(interval, increased))
320
+
321
+ headroom = oauth.account_headroom(new_usage, models)
322
+ if headroom is not None and headroom <= 0:
323
+ # Keep probing exhausted accounts: Anthropic can grant/reset quota
324
+ # before the previously advertised timestamp. Preserve a wider
325
+ # post-429 interval if congestion control already selected one.
326
+ interval = max(interval, EXHAUSTED_INTERVAL_S)
327
+
328
+ next_poll = now + interval * (1.0 + JITTER_FRAC * (2.0 * rng() - 1.0))
329
+ if headroom is not None and headroom <= 0:
330
+ reset_ts = limiting_reset_ts(new_usage, models)
331
+ if reset_ts is not None and reset_ts > now:
332
+ next_poll = min(next_poll, reset_ts + RESET_SLACK_S)
333
+ else:
334
+ reset_ts = earliest_future_reset_ts(new_usage, now, models)
335
+ if reset_ts is not None:
336
+ next_poll = min(next_poll, reset_ts + RESET_SLACK_S)
337
+ return next_poll, interval
claude_swap/printer.py ADDED
@@ -0,0 +1,252 @@
1
+ """Console output formatting for Claude Swap.
2
+
3
+ Provides subtle, modern terminal styling with a single warm accent color,
4
+ dim secondary text, and bold for structure. Inspired by Claude Code's
5
+ restrained aesthetic. Falls back to plain text when colors aren't supported.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import os
12
+ import sys
13
+ import time
14
+ from pathlib import Path
15
+
16
+ # ANSI escape codes -- structural, theme-independent
17
+ _RESET = "\033[0m"
18
+ _BOLD = "\033[1m"
19
+ _DIM = "\033[2m"
20
+
21
+ _PALETTES: dict[str, dict[str, str]] = {
22
+ "dark": {
23
+ "accent": "\033[38;5;173m", # warm salmon/terracotta (xterm 173)
24
+ "muted": "\033[38;5;250m", # soft gray -- readable, but quieter than normal
25
+ "red": "\033[31m",
26
+ "yellow": "\033[33m",
27
+ },
28
+ "light": {
29
+ "accent": "\033[38;2;149;76;42m", # #954c2a burnt sienna
30
+ "muted": "\033[38;2;99;93;85m", # #635d55
31
+ "red": "\033[38;2;173;49;40m", # #ad3128
32
+ "yellow": "\033[38;2;121;89;17m", # #795911 deep ochre
33
+ },
34
+ }
35
+
36
+ _colors_enabled: bool | None = None # lazy-initialized
37
+ _theme: str = "dark"
38
+
39
+
40
+ def set_theme(name: str) -> None:
41
+ """Select the CLI color palette. Unknown names fall back to dark."""
42
+ global _theme
43
+ _theme = name if name in _PALETTES else "dark"
44
+
45
+
46
+ def current_theme() -> str:
47
+ """The CLI palette in use: ``"dark"`` or ``"light"``."""
48
+ return _theme
49
+
50
+
51
+ def _pal(key: str) -> str:
52
+ return _PALETTES[_theme][key]
53
+
54
+
55
+ def _enable_windows_vt() -> bool:
56
+ """Enable VT processing on Windows console."""
57
+ if sys.platform != "win32":
58
+ return True
59
+ try:
60
+ import ctypes
61
+
62
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
63
+ handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
64
+ mode = ctypes.c_ulong()
65
+ kernel32.GetConsoleMode(handle, ctypes.byref(mode))
66
+ kernel32.SetConsoleMode(handle, mode.value | 0x0004) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
67
+ return True
68
+ except Exception:
69
+ return False
70
+
71
+
72
+ def force_utf8_output() -> None:
73
+ """Make stdout/stderr encode UTF-8 so ● → ├ ─ └ don't crash on a legacy
74
+ console (cp1252 on Windows, or an ASCII/C locale). errors="replace" keeps
75
+ output flowing on any stream that still can't render a glyph. No-op where
76
+ the stream can't be reconfigured (replaced/captured streams in tests)."""
77
+ for stream in (sys.stdout, sys.stderr):
78
+ reconfigure = getattr(stream, "reconfigure", None)
79
+ if reconfigure is None:
80
+ continue
81
+ try:
82
+ reconfigure(encoding="utf-8", errors="replace")
83
+ except (ValueError, OSError):
84
+ pass
85
+
86
+
87
+ def _detect_color_support() -> bool:
88
+ """Detect whether the terminal supports ANSI colors."""
89
+ # Respect NO_COLOR convention (https://no-color.org/)
90
+ if os.environ.get("NO_COLOR") is not None:
91
+ return False
92
+ # Respect FORCE_COLOR for CI/testing
93
+ if os.environ.get("FORCE_COLOR") is not None:
94
+ return True
95
+ # Not a TTY (piped output) -> no color
96
+ if not hasattr(sys.stdout, "isatty") or not sys.stdout.isatty():
97
+ return False
98
+ # Windows: try to enable VT processing
99
+ if sys.platform == "win32":
100
+ return _enable_windows_vt()
101
+ # POSIX: check TERM
102
+ if os.environ.get("TERM", "") == "dumb":
103
+ return False
104
+ return True
105
+
106
+
107
+ def stdout_is_terminal() -> bool:
108
+ """Whether stdout is a terminal: the condition for the bar layout of
109
+ ``cswap list`` and ``cswap status`` (``list_view``).
110
+
111
+ Not ``colors_enabled()``: ``FORCE_COLOR`` and ``force_color`` turn colour
112
+ on for output that is piped or captured, and that output keeps the plain
113
+ layout.
114
+ """
115
+ isatty = getattr(sys.stdout, "isatty", None)
116
+ try:
117
+ return bool(isatty and isatty())
118
+ except (ValueError, OSError):
119
+ return False
120
+
121
+
122
+ def colors_enabled() -> bool:
123
+ """Return whether color output is active. Caches on first call."""
124
+ global _colors_enabled
125
+ if _colors_enabled is None:
126
+ _colors_enabled = _detect_color_support()
127
+ return _colors_enabled
128
+
129
+
130
+ @contextlib.contextmanager
131
+ def force_color():
132
+ """Temporarily force colored output on, restoring the prior cache after.
133
+
134
+ Used by the TUI when capturing CLI output into a buffer: capture redirects
135
+ stdout to a non-tty StringIO, which would otherwise disable color — but the
136
+ TUI re-renders the ANSI itself, so it wants the codes emitted.
137
+ """
138
+ global _colors_enabled
139
+ saved = _colors_enabled
140
+ _colors_enabled = True
141
+ try:
142
+ yield
143
+ finally:
144
+ _colors_enabled = saved
145
+
146
+
147
+ def _style(text: str, *codes: str) -> str:
148
+ """Apply ANSI codes to text if colors are enabled."""
149
+ if not colors_enabled():
150
+ return text
151
+ prefix = "".join(codes)
152
+ return f"{prefix}{text}{_RESET}"
153
+
154
+
155
+ # --- Inline stylers (return styled strings for composing lines) ---
156
+
157
+
158
+ def accent(text: str) -> str:
159
+ """Warm accent color for important elements."""
160
+ return _style(text, _pal("accent"))
161
+
162
+
163
+ def muted(text: str) -> str:
164
+ """Slightly dimmer than normal -- for usage stats, org tags."""
165
+ return _style(text, _pal("muted"))
166
+
167
+
168
+ def dimmed(text: str) -> str:
169
+ """Dim for tertiary info -- tree connectors, hints."""
170
+ return _style(text, _DIM)
171
+
172
+
173
+ def bolded(text: str) -> str:
174
+ """Bold (no color) for structure."""
175
+ return _style(text, _BOLD)
176
+
177
+
178
+ def bold_accent(text: str) -> str:
179
+ """Bold + accent for key markers like (active)."""
180
+ return _style(text, _BOLD, _pal("accent"))
181
+
182
+
183
+ def yellowed(text: str) -> str:
184
+ """Yellow for warning-toned text (string form; ``warning()`` prints)."""
185
+ return _style(text, _pal("yellow"))
186
+
187
+
188
+ # --- Line printers (call print() internally) ---
189
+
190
+
191
+ def error(msg: str) -> None:
192
+ """Print an error message (red) to stderr."""
193
+ print(_style(msg, _pal("red")), file=sys.stderr)
194
+
195
+
196
+ def warning(msg: str, *, file=None) -> None:
197
+ """Print a warning message (yellow).
198
+
199
+ ``file`` routes it elsewhere than stdout — stderr for anything a
200
+ long-running process emits, since stderr stays line-buffered when it is
201
+ redirected to a file and stdout does not.
202
+ """
203
+ print(_style(msg, _pal("yellow")), file=file)
204
+
205
+
206
+ # --- Display helpers for process detection ---
207
+
208
+ _ENTRYPOINT_LABELS: dict[str, str] = {
209
+ "cli": "CLI",
210
+ "claude-vscode": "VS Code",
211
+ "claude-desktop": "Desktop",
212
+ "sdk-cli": "SDK",
213
+ "sdk-ts": "SDK",
214
+ "sdk-py": "SDK",
215
+ "mcp": "MCP",
216
+ "local-agent": "Agent",
217
+ "remote": "Remote",
218
+ }
219
+
220
+ _IDE_SHORT_NAMES: dict[str, str] = {
221
+ "Visual Studio Code": "VS Code",
222
+ }
223
+
224
+
225
+ def entrypoint_label(entrypoint: str) -> str:
226
+ """Return a human-readable label for a Claude Code entrypoint."""
227
+ return _ENTRYPOINT_LABELS.get(entrypoint, entrypoint)
228
+
229
+
230
+ def ide_short_name(ide_name: str) -> str:
231
+ """Return a short display name for an IDE."""
232
+ return _IDE_SHORT_NAMES.get(ide_name, ide_name)
233
+
234
+
235
+ def abbreviate_path(path: str) -> str:
236
+ """Replace the user's home directory prefix with ~."""
237
+ home = str(Path.home())
238
+ if path.startswith(home):
239
+ return "~" + path[len(home):]
240
+ return path
241
+
242
+
243
+ def format_age(started_at_ms: int) -> str:
244
+ """Format a millisecond epoch timestamp as a human-readable age."""
245
+ elapsed = int(time.time()) - (started_at_ms // 1000)
246
+ if elapsed < 60:
247
+ return "just now"
248
+ if elapsed < 3600:
249
+ return f"{elapsed // 60}m ago"
250
+ if elapsed < 86400:
251
+ return f"{elapsed // 3600}h ago"
252
+ return f"{elapsed // 86400}d ago"