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
claude_swap/lines.py ADDED
@@ -0,0 +1,153 @@
1
+ """Switch lines per usage window.
2
+
3
+ One ``autoswitch.threshold`` compared against the binding window (the max of
4
+ the 5h/7d/per-model percentages) cannot express the policy most people want:
5
+ ~85-90 on the 5-hour window, which recycles in hours, and 97-99 on the weekly
6
+ ones, which are the budget. So each window gets its own line
7
+ (``autoswitch.weeklyThreshold`` for the windows that reset weekly) and the
8
+ engine judges every window against its own.
9
+
10
+ Three quantities per account, in the engine's vocabulary:
11
+
12
+ * RAW headroom (``oauth.account_headroom``, ``100 - max pct``) — physical:
13
+ can the account serve requests, is it exhausted. Untouched by lines.
14
+ * ``line_headroom`` per window — policy distance on the 5h scale. A window at
15
+ its line scores ``100 - threshold`` whatever its line, an exhausted one 0,
16
+ and each side of the line is linear in between (three anchors: 0% -> 100,
17
+ line -> 100 - threshold, 100% -> 0). With equal lines it is ``100 - pct``
18
+ bit for bit, so every margin the engine measures in points keeps its
19
+ meaning.
20
+ * the BINDING window — the window with the least line headroom, over-line
21
+ windows first. Its ``line_headroom`` is the account's policy headroom and
22
+ its ``over`` the account's verdict. With equal lines it is today's max-pct
23
+ window.
24
+
25
+ And one margin: ``line_room``, the points left before the nearest line, each
26
+ window counted in its own points, for asking whether a landing has room to
27
+ spare (``autoswitch.hysteresis_pct``) before it re-triggers.
28
+
29
+ Pure functions over the ``(label, pct, resets_at)`` triples
30
+ ``oauth.relevant_windows`` yields: no settings reads, no I/O, and no restated
31
+ percentages — the raw numbers flow to logs and screens untouched, and the
32
+ lines are applied only where the engine compares.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ from collections.abc import Iterable
38
+ from dataclasses import dataclass
39
+
40
+ from claude_swap.oauth import FIVE_HOUR_LABEL
41
+
42
+
43
+ def window_line(label: str, threshold: float, weekly_threshold: float | None) -> float:
44
+ """The switch line for one window: ``weekly_threshold`` for every window
45
+ that resets weekly (7d and per-model), ``threshold`` for the 5h window and
46
+ for all of them while no weekly line is configured."""
47
+ if weekly_threshold is None or label == FIVE_HOUR_LABEL:
48
+ return threshold
49
+ return weekly_threshold
50
+
51
+
52
+ def line_headroom(pct: float, line: float, threshold: float) -> float:
53
+ """Policy headroom of one window on the 5h scale (module docstring).
54
+
55
+ The arrangement is load-bearing for exactness at the anchors the engine
56
+ compares at: ``line - pct`` is exactly 0.0 at the line, so a window AT its
57
+ line scores exactly ``100 - threshold`` and a candidate sitting exactly
58
+ ``hysteresis_pct`` better is not refused over a 1e-14 residue (measured:
59
+ ``(line - pct) * (threshold / line)`` left one for 15 of the integer
60
+ line pairs); ``100 - pct`` is exactly 0.0 at 100%. Equal lines
61
+ short-circuit to ``100 - pct`` so the default configuration is
62
+ bit-identical to raw headroom.
63
+ """
64
+ if line == threshold:
65
+ return 100.0 - pct
66
+ if pct <= line:
67
+ return (100.0 - threshold) + threshold * (line - pct) / line
68
+ return (100.0 - threshold) * (100.0 - pct) / (100.0 - line)
69
+
70
+
71
+ def line_room(
72
+ windows: Iterable[tuple[str, float, str | None]],
73
+ threshold: float,
74
+ weekly_threshold: float | None = None,
75
+ ) -> float | None:
76
+ """Points left before the nearest switch line, each window counted in its
77
+ own points: the least ``line - pct`` over the windows, negative once one
78
+ is over. ``None`` when the account reports no window.
79
+
80
+ Not ``line_headroom - (100 - threshold)``: that is the room on the 5h
81
+ scale, ``threshold / line`` times the real points on any line but the
82
+ global one, so 10 points under a 98 weekly line (global 90) read 9.2, and
83
+ 8 points under an account's own 60 line read 12. Nor the binding window's
84
+ alone: it is chosen on that scale, so the window nearest its line in its
85
+ own points can be another one.
86
+ """
87
+ rooms = [
88
+ window_line(label, threshold, weekly_threshold) - pct
89
+ for label, pct, _ in windows
90
+ ]
91
+ return min(rooms) if rooms else None
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class BindingWindow:
96
+ """The window holding an account back, with the numbers the engine
97
+ compares: its raw ``pct`` and its own ``line`` (so a message can quote the
98
+ comparison actually made — "7d 93% < 97%"), ``resets_at`` (recovery
99
+ scheduling) and ``line_headroom`` (the account's policy headroom)."""
100
+
101
+ label: str
102
+ pct: float
103
+ line: float
104
+ resets_at: str | None
105
+ line_headroom: float
106
+
107
+ @property
108
+ def over(self) -> bool:
109
+ """At or over its own line — compared directly on the raw pct, never
110
+ through a rescaled value or a quotient against 1.0, so the verdict
111
+ cannot drift by a rounding ulp at the line."""
112
+ return self.pct >= self.line
113
+
114
+
115
+ def binding_window(
116
+ windows: Iterable[tuple[str, float, str | None]],
117
+ threshold: float,
118
+ weekly_threshold: float | None = None,
119
+ *,
120
+ scale: float | None = None,
121
+ ) -> BindingWindow | None:
122
+ """The window with the least policy headroom, over-line windows first;
123
+ ties keep the first in ``relevant_windows`` order (5h, 7d, then scoped).
124
+ ``None`` when the account reports no window.
125
+
126
+ Over-line first makes ``binding.over == any(window at/over its line)``
127
+ hold by construction, so the trigger, the landing gate and the all-above
128
+ census — which all read the binding window — can never disagree with a
129
+ per-window check. The ordering is the SAME one the engine ranks and
130
+ applies hysteresis on: choosing the window by one score and ranking by
131
+ another made 0.1 more usage look healthier whenever the choice flipped.
132
+
133
+ ``scale`` is the threshold the headroom is measured on, ``T`` in
134
+ ``line_headroom``; it defaults to ``threshold``. An account on a line of
135
+ its own passes that line as ``threshold`` and the global threshold as
136
+ ``scale``, so accounts on different lines are scored on one ruler and
137
+ their headroom compares directly. Each window's line and ``over`` do
138
+ not depend on it. In exact arithmetic neither does the window chosen,
139
+ but at a floating-point tie the rounding does, so every caller that
140
+ selects a window for one account must pass the same ``scale``.
141
+ """
142
+ best: BindingWindow | None = None
143
+ best_key: tuple[bool, float] | None = None
144
+ ruler = threshold if scale is None else scale
145
+ for label, pct, resets_at in windows:
146
+ line = window_line(label, threshold, weekly_threshold)
147
+ window = BindingWindow(
148
+ label, pct, line, resets_at, line_headroom(pct, line, ruler)
149
+ )
150
+ key = (not window.over, window.line_headroom)
151
+ if best_key is None or key < best_key:
152
+ best, best_key = window, key
153
+ return best
@@ -0,0 +1,371 @@
1
+ """The terminal layout of ``cswap list`` and ``cswap status``: usage bars.
2
+
3
+ When stdout is a terminal (``printer.stdout_is_terminal``), the account views draw
4
+ each usage window as a bar in the style of ``cswap watch``, colour the
5
+ figures by severity, and set the account header and the running instances
6
+ in columns. Output that is piped or captured keeps the plain text layout,
7
+ byte for byte, because scripts and the TUI's captured actions read it. So
8
+ does a window too narrow for the widest row with the shortest bar
9
+ (``BarLayout.fits``), which would otherwise wrap.
10
+
11
+ The pieces here are built as Rich ``Text`` and turned into a string by
12
+ ``to_ansi``, which goes through ``printer.colors_enabled`` like every other
13
+ line: with colour off (``NO_COLOR``, ``TERM=dumb``) the layout stays and the
14
+ colour goes. Rich picks the colour depth the terminal supports (truecolor,
15
+ 256 or 16 colours): from ``COLORTERM`` and ``TERM`` on macOS and Linux,
16
+ from the console's features on Windows.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import io
22
+ import shutil
23
+ from collections.abc import Iterable
24
+ from dataclasses import dataclass
25
+
26
+ from rich.cells import cell_len
27
+ from rich.console import Console
28
+ from rich.text import Text
29
+
30
+ from claude_swap import printer, subscription
31
+ from claude_swap.oauth import FIVE_HOUR_LABEL
32
+ from claude_swap.usage_bars import (
33
+ BAR_MAX,
34
+ WARN_PCT,
35
+ Palette,
36
+ bar_cells,
37
+ switch_line,
38
+ )
39
+ from claude_swap.usage_rows import UsageRow, pct_text
40
+
41
+ # How close a reset must be before its countdown reads as relief in sight
42
+ # (``countdown_style``): an hour for the 5h window, a day for the others.
43
+ _RELIEF_5H_S = 3600.0
44
+ _RELIEF_S = 86400.0
45
+
46
+ # Instance labels that name a Claude Code entrypoint rather than an IDE
47
+ # (``printer._ENTRYPOINT_LABELS``). Any other label is an IDE's name.
48
+ _ENTRYPOINT_TINTS = {
49
+ "CLI": "accent",
50
+ "Desktop": "info",
51
+ "SDK": "muted",
52
+ "MCP": "muted",
53
+ "Agent": "muted",
54
+ "Remote": "muted",
55
+ }
56
+
57
+ # The shortest bar of this layout. Two cells under ``usage_bars.BAR_MIN``,
58
+ # the floor of the TUI card, so that the widest usual block (a five-letter
59
+ # label, a countdown in days and "(ahead of pace)") needs 79 columns and
60
+ # keeps its bars on a window of 80.
61
+ ROW_BAR_MIN = 10
62
+
63
+ _console: Console | None = None
64
+
65
+ # The colour depth the Console renders at. "auto" lets Rich detect it (see
66
+ # the module docstring). Tests pin it, since Windows ignores the variables.
67
+ _COLOR_SYSTEM = "auto"
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class BarLayout:
72
+ """What the bar rows of one view need: the palette, the terminal width,
73
+ the columns before each row's tree glyph, the auto-switch lines, and the
74
+ widest label and widest tail (everything after the bar) of all the rows
75
+ the view shows, so every account's bars share one column and one width."""
76
+
77
+ palette: Palette
78
+ columns: int
79
+ indent: int
80
+ threshold: float | None
81
+ weekly_threshold: float | None
82
+ label_width: int
83
+ tail_width: int
84
+
85
+ @property
86
+ def bar_width(self) -> int:
87
+ """Bar cells: as many as the terminal leaves beside the widest label
88
+ and tail, within ``ROW_BAR_MIN``..``BAR_MAX``."""
89
+ return max(ROW_BAR_MIN, min(BAR_MAX, self._room))
90
+
91
+ @property
92
+ def fits(self) -> bool:
93
+ """Whether the widest row fits the terminal with a bar of at least
94
+ ``ROW_BAR_MIN`` cells. When it doesn't, the view prints its plain layout
95
+ instead of rows that wrap."""
96
+ return self._room >= ROW_BAR_MIN
97
+
98
+ @property
99
+ def _room(self) -> int:
100
+ """Columns left for the bar beside the widest label and tail."""
101
+ # tree glyph and space, "label:", space, bar, space, tail
102
+ return self.columns - self.indent - 2 - (self.label_width + 1) - 1 - 1 - self.tail_width
103
+
104
+
105
+ def make_layout(
106
+ indent: int,
107
+ threshold: float | None,
108
+ weekly_threshold: float | None,
109
+ labels: Iterable[str],
110
+ tails: Iterable[int],
111
+ ) -> BarLayout:
112
+ """A ``BarLayout`` for the current terminal and CLI theme, fitted to the
113
+ labels and tail widths (``tail_width``) of the rows the view shows.
114
+ A terminal of 16 colours gets ``Palette.BASIC``."""
115
+ if _get_console().color_system == "standard":
116
+ palette = Palette.BASIC
117
+ elif printer.current_theme() == "light":
118
+ palette = Palette.LIGHT
119
+ else:
120
+ palette = Palette.DARK
121
+ return BarLayout(
122
+ palette=palette,
123
+ columns=shutil.get_terminal_size((100, 24)).columns,
124
+ indent=indent,
125
+ threshold=threshold,
126
+ weekly_threshold=weekly_threshold,
127
+ label_width=max((len(label) for label in labels), default=0),
128
+ tail_width=max(tails, default=0),
129
+ )
130
+
131
+
132
+ def _get_console() -> Console:
133
+ """The Console that renders every line, created once. It writes to a
134
+ buffer, but detects the colour depth of the real terminal
135
+ (``_COLOR_SYSTEM``)."""
136
+ global _console
137
+ if _console is None:
138
+ _console = Console(
139
+ file=io.StringIO(),
140
+ color_system=_COLOR_SYSTEM,
141
+ force_terminal=True,
142
+ legacy_windows=False,
143
+ width=10_000,
144
+ highlight=False,
145
+ markup=False,
146
+ emoji=False,
147
+ soft_wrap=True,
148
+ )
149
+ return _console
150
+
151
+
152
+ def to_ansi(text: Text) -> str:
153
+ """``text`` as a string for ``print``: styled when colour is on, plain
154
+ otherwise. No wrapping and no trailing newline."""
155
+ if not printer.colors_enabled():
156
+ return text.plain
157
+ console = _get_console()
158
+ with console.capture() as capture:
159
+ console.print(text, end="")
160
+ return capture.get()
161
+
162
+
163
+ def countdown_style(row: UsageRow, palette: Palette) -> str:
164
+ """The countdown's colour: the ok colour when a window at or over the
165
+ warn band resets soon (relief is in sight), dim otherwise."""
166
+ if row.pct is None or row.resets_in_s is None or row.pct < WARN_PCT:
167
+ return "dim"
168
+ limit = _RELIEF_5H_S if row.label == FIVE_HOUR_LABEL else _RELIEF_S
169
+ return palette.sev_ok if row.resets_in_s <= limit else "dim"
170
+
171
+
172
+ def _marker_style(marker: str, palette: Palette) -> str:
173
+ return palette.sev_crit if "(!)" in marker else palette.sev_warn
174
+
175
+
176
+ def _append_tail(text: Text, row: UsageRow, palette: Palette, stale: bool) -> None:
177
+ """Everything after the bar: figure, reset, countdown, marker."""
178
+ pct_style = palette.severity(row.pct)
179
+ if stale:
180
+ pct_style = f"{pct_style} dim"
181
+ if row.kind == "rejected":
182
+ text.append("rejected", style=palette.sev_crit)
183
+ if row.reset is not None:
184
+ countdown, clock = row.reset
185
+ text.append(f" until {clock:<12} ", style=palette.muted)
186
+ text.append(f"in {countdown}", style="dim")
187
+ return
188
+ text.append(
189
+ pct_text(row), style=pct_style if row.pct is not None else palette.muted
190
+ )
191
+ if row.kind == "passed":
192
+ clock = row.reset[1] if row.reset else ""
193
+ text.append(f" {'reset':<6} {clock}", style=palette.muted)
194
+ return
195
+ if row.reset is not None:
196
+ countdown, clock = row.reset
197
+ text.append(f" resets {clock:<12} ", style=palette.muted)
198
+ if row.kind == "spend":
199
+ text.append(row.amounts or "", style=palette.muted)
200
+ return
201
+ text.append(f"in {countdown}", style=countdown_style(row, palette))
202
+ elif row.kind == "spend":
203
+ text.append(f" {row.amounts}", style=palette.muted)
204
+ return
205
+ if row.marker:
206
+ text.append(row.marker, style=_marker_style(row.marker, palette))
207
+
208
+
209
+ def tail_width(row: UsageRow) -> int:
210
+ """Columns the row takes after its bar (``_append_tail``)."""
211
+ text = Text()
212
+ _append_tail(text, row, Palette.DARK, False)
213
+ return cell_len(text.plain)
214
+
215
+
216
+ def usage_row_text(row: UsageRow, layout: BarLayout, *, stale: bool = False) -> Text:
217
+ """One bar row, sans tree glyph:
218
+ ``7d: ━━━━━━━━━╸──────────┃── 38% resets Dec 7 03:59 in 6d 1h``."""
219
+ palette = layout.palette
220
+ text = Text()
221
+ text.append(f"{row.label + ':':<{layout.label_width + 1}} ", style=palette.muted)
222
+ text.append(
223
+ bar_cells(
224
+ row.pct,
225
+ layout.bar_width,
226
+ stale=stale,
227
+ threshold=switch_line(row.label, layout.threshold, layout.weekly_threshold),
228
+ palette=palette,
229
+ )
230
+ )
231
+ text.append(" ")
232
+ _append_tail(text, row, palette, stale)
233
+ return text
234
+
235
+
236
+ def login_row_text(label: str, body: str, expired: bool, layout: BarLayout) -> Text:
237
+ """The login-expiry row, its body under the figures of the bar rows
238
+ above it, in the critical colour once the login has expired."""
239
+ palette = layout.palette
240
+ pad = " " * (layout.bar_width + 1)
241
+ text = Text()
242
+ text.append(f"{label + ':':<{layout.label_width + 1}} ", style=palette.muted)
243
+ text.append(pad + body, style=palette.sev_crit if expired else palette.muted)
244
+ return text
245
+
246
+
247
+ def tree(lines: list[Text]) -> list[Text]:
248
+ """Prefix each line with ``├`` and the last with ``└``, dimmed."""
249
+ out = []
250
+ for j, line in enumerate(lines):
251
+ glyph = "└" if j == len(lines) - 1 else "├"
252
+ out.append(Text.assemble((glyph, "dim"), " ", line))
253
+ return out
254
+
255
+
256
+ def plan_style(plan: dict, palette: Palette) -> str:
257
+ """The plan badge's colour: Pro muted, Max the accent, Ultra bold accent,
258
+ Team and Enterprise the info tint, a lapsed subscription the warn colour."""
259
+ if subscription.is_expired(plan):
260
+ return palette.sev_warn
261
+ label = subscription.plan_label(plan) or ""
262
+ if label.startswith("Ultra"):
263
+ return f"bold {palette.accent}"
264
+ if label.startswith("Max"):
265
+ return palette.accent
266
+ if label in ("Team", "Enterprise"):
267
+ return palette.info
268
+ return palette.muted
269
+
270
+
271
+ def account_header(
272
+ palette: Palette,
273
+ num: int | str,
274
+ email: str,
275
+ *,
276
+ alias: str | None,
277
+ tag: str | None,
278
+ active: bool,
279
+ disabled: bool,
280
+ plan: dict | None,
281
+ plan_age: str | None,
282
+ ) -> Text:
283
+ """`` 1 mujo mujo@example.com [Org] ACTIVE · Ultra``: the number
284
+ dim, the alias bold in the accent, the email muted (bold when there is
285
+ no alias), the ACTIVE badge on the accent (``[ACTIVE]`` without colour)."""
286
+ text = Text()
287
+ text.append(f"{num:>3} ", style="dim")
288
+ if alias:
289
+ text.append(alias, style=f"bold {palette.accent}")
290
+ text.append(f" {email}", style=palette.muted)
291
+ else:
292
+ text.append(email, style="bold")
293
+ if tag:
294
+ text.append(f" [{tag}]", style="dim")
295
+ if active:
296
+ text.append(" ")
297
+ if printer.colors_enabled():
298
+ text.append(
299
+ " ACTIVE ", style=f"bold {palette.background} on {palette.accent}"
300
+ )
301
+ else:
302
+ text.append("[ACTIVE]")
303
+ if disabled:
304
+ text.append(" (disabled)", style=palette.muted)
305
+ if plan:
306
+ text.append(" · ", style=palette.muted)
307
+ text.append(subscription.plan_label(plan) or "", style=plan_style(plan, palette))
308
+ if plan_age:
309
+ text.append(f" ({plan_age})", style="dim")
310
+ return text
311
+
312
+
313
+ def _instance_tint(label: str, palette: Palette) -> str:
314
+ return getattr(palette, _ENTRYPOINT_TINTS.get(label, "violet"))
315
+
316
+
317
+ def _count_text(counts: dict[str, int], palette: Palette) -> Text:
318
+ """``(2 sessions, IDE)`` with the number in the accent."""
319
+ text = Text()
320
+ text.append("(", style="dim")
321
+ sessions = counts["sessions"]
322
+ if sessions:
323
+ text.append(str(sessions), style=palette.accent)
324
+ text.append(f" session{'s' if sessions > 1 else ''}", style="dim")
325
+ if counts["ide"]:
326
+ text.append(", IDE" if sessions else "IDE", style="dim")
327
+ text.append(")", style="dim")
328
+ return text
329
+
330
+
331
+ def instance_lines(
332
+ groups: Iterable[tuple[tuple[str, str], dict[str, int]]],
333
+ palette: Palette,
334
+ columns: int,
335
+ ) -> list[Text]:
336
+ """The running-instances rows, busiest first, each label in its
337
+ entrypoint's tint: `` ● CLI ~/workspace/x (2 sessions)``. The
338
+ counts line up after the longest path while every row fits ``columns``,
339
+ and follow their own path otherwise, so one long path doesn't make every
340
+ row wrap."""
341
+ items = sorted(groups, key=lambda item: -(item[1]["sessions"] + item[1]["ide"]))
342
+ if not items:
343
+ return []
344
+ label_w = max(cell_len(label) for (label, _cwd), _c in items)
345
+ aligned = _instance_rows(items, palette, label_w, max(cell_len(cwd) for (_l, cwd), _c in items))
346
+ if all(cell_len(row.plain) <= columns for row in aligned):
347
+ return aligned
348
+ return _instance_rows(items, palette, label_w, 0)
349
+
350
+
351
+ def _instance_rows(
352
+ items: list[tuple[tuple[str, str], dict[str, int]]],
353
+ palette: Palette,
354
+ label_w: int,
355
+ path_w: int,
356
+ ) -> list[Text]:
357
+ """One row per instance group, labels padded to ``label_w`` and paths to
358
+ ``path_w`` (0: no padding)."""
359
+ out = []
360
+ for (label, cwd), counts in items:
361
+ tint = _instance_tint(label, palette)
362
+ text = Text(" ")
363
+ text.append("●", style=tint)
364
+ text.append(" ")
365
+ text.append(label + " " * (label_w - cell_len(label)), style=tint)
366
+ text.append(" ")
367
+ text.append(cwd + " " * max(0, path_w - cell_len(cwd)))
368
+ text.append(" ")
369
+ text.append(_count_text(counts, palette))
370
+ out.append(text)
371
+ return out
claude_swap/locking.py ADDED
@@ -0,0 +1,87 @@
1
+ """File locking for concurrent access protection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+ from typing import IO
9
+
10
+ # Platform-specific imports for file locking
11
+ if sys.platform == "win32":
12
+ import msvcrt
13
+ else:
14
+ import fcntl
15
+
16
+ from claude_swap.exceptions import LockError
17
+
18
+
19
+ class FileLock:
20
+ """Cross-process file lock using platform-specific APIs."""
21
+
22
+ def __init__(self, lock_path: Path, timeout: float = 10.0):
23
+ self.lock_path = lock_path
24
+ self.timeout = timeout
25
+ self._lock_file: IO | None = None
26
+ self._locked = False
27
+
28
+ def acquire(self, timeout: float | None = None) -> bool:
29
+ """Acquire exclusive lock with timeout.
30
+
31
+ Args:
32
+ timeout: Maximum seconds to wait for lock. Defaults to the
33
+ timeout given at construction.
34
+
35
+ Returns:
36
+ True if lock acquired, False if timeout.
37
+ """
38
+ if timeout is None:
39
+ timeout = self.timeout
40
+ self.lock_path.parent.mkdir(parents=True, exist_ok=True)
41
+ self._lock_file = open(self.lock_path, "w")
42
+
43
+ start = time.monotonic()
44
+ deadline = start + timeout
45
+ while True:
46
+ try:
47
+ if sys.platform == "win32":
48
+ # Windows: use msvcrt for file locking
49
+ msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_NBLCK, 1)
50
+ else:
51
+ # POSIX: use fcntl for file locking
52
+ fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
53
+ self._locked = True
54
+ return True
55
+ except (BlockingIOError, OSError):
56
+ if time.monotonic() - start > timeout:
57
+ self._lock_file.close()
58
+ self._lock_file = None
59
+ return False
60
+ # Clamped to the remaining budget, so `timeout` bounds the
61
+ # call: the deadline check above cannot fire while a full
62
+ # sleep is still running past it.
63
+ time.sleep(max(0.0, min(0.1, deadline - time.monotonic())))
64
+
65
+ def release(self) -> None:
66
+ """Release the lock."""
67
+ if self._lock_file and self._locked:
68
+ if sys.platform == "win32":
69
+ # Windows: unlock using msvcrt
70
+ try:
71
+ msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_UNLCK, 1)
72
+ except OSError:
73
+ pass # File may already be unlocked
74
+ else:
75
+ # POSIX: unlock using fcntl
76
+ fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_UN)
77
+ self._lock_file.close()
78
+ self._lock_file = None
79
+ self._locked = False
80
+
81
+ def __enter__(self) -> FileLock:
82
+ if not self.acquire():
83
+ raise LockError("Failed to acquire lock - another instance may be running")
84
+ return self
85
+
86
+ def __exit__(self, *args) -> None:
87
+ self.release()
@@ -0,0 +1,64 @@
1
+ """Logging configuration for Claude Swap."""
2
+
3
+ import logging
4
+ from logging.handlers import RotatingFileHandler
5
+ from pathlib import Path
6
+
7
+
8
+ class _LazyDirRotatingFileHandler(RotatingFileHandler):
9
+ """RotatingFileHandler that creates its parent dir on first emit.
10
+
11
+ Keeps the backup root from being materialized just because the switcher
12
+ was instantiated. Necessary so a no-op run (e.g. ``cswap --status`` with
13
+ no managed accounts) doesn't lay down ``cache/`` or log files inside the
14
+ XDG path, which would later trip the legacy → XDG migration collision
15
+ check if a legacy directory appeared between runs.
16
+ """
17
+
18
+ def _open(self): # type: ignore[override]
19
+ Path(self.baseFilename).parent.mkdir(parents=True, exist_ok=True)
20
+ return super()._open()
21
+
22
+
23
+ def setup_logging(log_dir: Path, debug: bool = False) -> logging.Logger:
24
+ """Setup logging with file and optional console output.
25
+
26
+ The log directory is *not* created eagerly; it materializes on the first
27
+ log record actually written, via ``_LazyDirRotatingFileHandler``.
28
+
29
+ Args:
30
+ log_dir: Directory to store log files.
31
+ debug: Enable debug logging to console.
32
+
33
+ Returns:
34
+ Configured logger instance.
35
+ """
36
+ logger = logging.getLogger("claude-swap")
37
+ logger.setLevel(logging.DEBUG if debug else logging.INFO)
38
+
39
+ # Clear any existing handlers
40
+ logger.handlers.clear()
41
+
42
+ # File handler - opens lazily so the dir is only created when something
43
+ # is actually logged.
44
+ log_file = log_dir / "claude-swap.log"
45
+ file_handler = _LazyDirRotatingFileHandler(
46
+ log_file,
47
+ maxBytes=1024 * 1024, # 1MB
48
+ backupCount=3,
49
+ delay=True,
50
+ )
51
+ file_handler.setLevel(logging.DEBUG)
52
+ file_handler.setFormatter(
53
+ logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
54
+ )
55
+ logger.addHandler(file_handler)
56
+
57
+ # Console handler for debug mode
58
+ if debug:
59
+ console_handler = logging.StreamHandler()
60
+ console_handler.setLevel(logging.DEBUG)
61
+ console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
62
+ logger.addHandler(console_handler)
63
+
64
+ return logger