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,827 @@
1
+ """Tool settings persisted at ``<backup_root>/settings.json``.
2
+
3
+ One versioned JSON file for user-tunable claude-swap preferences, written
4
+ atomically with the backup dir's 0600/0700 modes. v1 carries the
5
+ ``autoswitch``, ``ui``, ``run``, ``updates`` and ``usage`` sections; other sections can
6
+ be added additively.
7
+ Unknown keys (future fields, other tools' experiments) survive a round trip.
8
+
9
+ ``settings.local.json`` beside it is opt-in: once someone creates it, it
10
+ overrides ``settings.json`` (a section present in both merges key by key, local
11
+ wins; any other value is replaced) and takes every write, so a version-controlled
12
+ ``settings.json`` is left alone. ``settings_write_path`` names the file a write
13
+ lands in.
14
+
15
+ Reading is forgiving — a missing or corrupt file yields defaults with a logged
16
+ warning, never a crash — so a bad hand edit degrades to default behavior.
17
+ A key nothing reads (a typo, or a key from another version) is kept in the
18
+ file but changes nothing. ``unrecognized_keys`` finds those: `cswap config`
19
+ lists them and the auto-switch loop logs them as it starts.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import dataclasses
25
+ import difflib
26
+ import json
27
+ import logging
28
+ import math
29
+ import os
30
+ import sys
31
+ from dataclasses import dataclass
32
+ from pathlib import Path
33
+
34
+ from claude_swap.exceptions import ConfigError
35
+ from claude_swap.fsutil import atomic_write_text, publish_target
36
+
37
+ SETTINGS_SCHEMA_VERSION = 1
38
+ SETTINGS_FILENAME = "settings.json"
39
+ LOCAL_SETTINGS_FILENAME = "settings.local.json"
40
+ AUTOSWITCH_STRATEGIES = (
41
+ "best", "weekly-first", "consume-first", "priority-consume-first",
42
+ )
43
+
44
+ _logger = logging.getLogger("claude-swap")
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class AutoSwitchSettings:
49
+ """Policy knobs for the auto-switch engine (``cswap auto``).
50
+
51
+ ``threshold`` is the switch line for the 5-hour window and, while
52
+ ``weekly_threshold`` is unset, for every window: each of an account's
53
+ usage windows (5h, 7d, and any per-model window named by ``model``) is
54
+ judged against its own line, and the engine looks for a better account
55
+ once any of them is at or over it. 90 rather than 95 leaves margin for the
56
+ macOS ~30s Keychain pickup tail and for heavy subagent turns burning past
57
+ the mark before a swap lands. ``weekly_threshold`` gives the 7-day window
58
+ and the per-model windows (they all reset weekly) their own line: the
59
+ weekly window is the budget, so it is worth running closer to its ceiling
60
+ than the 5-hour window, which recycles in hours. A proactive candidate
61
+ must itself sit below each of its lines (never land somewhere that
62
+ re-triggers next tick) and beat the active account by at least
63
+ ``hysteresis_pct`` points of headroom measured against those lines, so two
64
+ accounts hovering at the line never ping-pong while a strictly better
65
+ account is always taken. Under the ``consume-first`` strategy
66
+ ``hysteresis_pct`` is instead the room a landing needs: that many points
67
+ left under each of the target's own lines (``lines.line_room``).
68
+ """
69
+
70
+ threshold: float = 90.0
71
+ # Switch line for the 7-day window and every per-model scoped window.
72
+ # None = ``threshold`` governs every window (the default, today's policy).
73
+ weekly_threshold: float | None = None
74
+ interval_seconds: float = 60.0
75
+ cooldown_seconds: float = 300.0
76
+ hysteresis_pct: float = 10.0
77
+ strategy: str = "best" # Opt-in alternatives are in AUTOSWITCH_STRATEGIES.
78
+ include_api_key_accounts: bool = False
79
+ unhealthy_ticks: int = 3
80
+ # Comma-separated model display name(s) (e.g. "Fable" or "Fable,Opus"),
81
+ # or "all" for every scoped window an account reports. Each named model's
82
+ # per-model weekly limit is folded into the binding window, so the engine
83
+ # switches off an account whose model quota is exhausted even while its
84
+ # 5h/7d windows still have headroom. None = account-wide 5h/7d only
85
+ # (default).
86
+ model: str | None = None
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class UiSettings:
91
+ """Appearance preferences (``ui`` section). ``theme`` selects the TUI/CLI
92
+ color theme; ``auto`` follows terminal-background detection. ``org_tag``
93
+ picks when listings draw the ``[org]`` tag: ``on``, ``off``, or ``auto``
94
+ (only on accounts sharing an email with another managed account)."""
95
+
96
+ theme: str = "auto"
97
+ org_tag: str = "auto"
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class RunSettings:
102
+ """Defaults for ``cswap run`` (``run`` section); its flags override them.
103
+
104
+ ``share_history``: sessions of every account read and write the one chat
105
+ history in ``~/.claude``, so the account only decides whose quota is
106
+ used. Off gives each account a history of its own.
107
+ """
108
+
109
+ share_history: bool = True
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class UpdateSettings:
114
+ """Update notification (``updates`` section). ``check`` turns the daily
115
+ PyPI lookup behind the "newer version available" hint on or off;
116
+ ``cswap upgrade`` works either way."""
117
+
118
+ check: bool = True
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class UsageSettings:
123
+ """Usage collection preferences (``usage`` section).
124
+
125
+ ``header_probe``: the usage endpoint never answers a setup-token account
126
+ (``cswap add-token``), so read its 5h/7d utilization from the rate-limit
127
+ headers of a 1-output-token Haiku request instead. Each probe is a real,
128
+ if tiny, request against that account's quota, sent at the normal poll
129
+ cadence, so it is opt-in; off leaves such accounts at "usage unavailable".
130
+
131
+ ``fable_probe``: those headers report Fable's weekly limit only on a
132
+ Fable response, so also send a 1-output-token Fable request per poll and
133
+ show its row. A second opt-in because it spends Fable quota, which
134
+ agreeing to a Haiku token did not cover. It acts only with
135
+ ``header_probe`` on.
136
+
137
+ ``request_log``: log one INFO line per usage endpoint request (outcome,
138
+ slot, a token tag, process, request and cf-ray ids) so a 429 can be traced
139
+ to what sent it. Off by default; it adds no request.
140
+ """
141
+
142
+ header_probe: bool = False
143
+ fable_probe: bool = False
144
+ request_log: bool = False
145
+
146
+
147
+ _SECTION_DEFAULT_SOURCES = {
148
+ "autoswitch": AutoSwitchSettings,
149
+ "ui": UiSettings,
150
+ "run": RunSettings,
151
+ "updates": UpdateSettings,
152
+ "usage": UsageSettings,
153
+ }
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class SettingSpec:
158
+ """Metadata for one user-tunable settings.json key.
159
+
160
+ Single source of truth for bounds/choices: both the lenient clamp on load
161
+ (`_clamped`) and the strict validation in `cswap config set`
162
+ (`parse_setting_value`) read from here, so the two can't drift.
163
+ """
164
+
165
+ section: str # top-level JSON section ("autoswitch", "ui", "updates", "usage")
166
+ json_key: str # camelCase key inside the section
167
+ field: str # snake_case AutoSwitchSettings field
168
+ kind: str # "float" | "int" | "bool" | "choice"
169
+ lo: float | None = None
170
+ hi: float | None = None
171
+ choices: tuple[str, ...] = ()
172
+ help: str = ""
173
+
174
+ @property
175
+ def dotted(self) -> str:
176
+ return f"{self.section}.{self.json_key}"
177
+
178
+ @property
179
+ def default(self):
180
+ return getattr(_SECTION_DEFAULT_SOURCES[self.section](), self.field)
181
+
182
+
183
+ # settings.json uses camelCase (matching the repo's other JSON artifacts);
184
+ # dataclass fields stay snake_case.
185
+ SETTING_SPECS: dict[str, SettingSpec] = {
186
+ spec.dotted: spec
187
+ for spec in (
188
+ SettingSpec(
189
+ "autoswitch", "threshold", "threshold", "float", 40.0, 99.9,
190
+ help="Switch when the 5h window (or any window, if no weekly line) reaches this pct",
191
+ ),
192
+ SettingSpec(
193
+ "autoswitch", "weeklyThreshold", "weekly_threshold", "float", 50.0, 99.9,
194
+ help="Switch line for the 7d and per-model windows (unset: threshold)",
195
+ ),
196
+ SettingSpec(
197
+ "autoswitch", "intervalSeconds", "interval_seconds", "float", 15.0, 3600.0,
198
+ help="Poll interval for the cswap auto loop, in seconds",
199
+ ),
200
+ SettingSpec(
201
+ "autoswitch", "cooldownSeconds", "cooldown_seconds", "float", 0.0, 86400.0,
202
+ help="Minimum seconds between proactive switches",
203
+ ),
204
+ SettingSpec(
205
+ "autoswitch", "hysteresisPct", "hysteresis_pct", "float", 0.0, 50.0,
206
+ help="A target must beat the active account by this many pct of headroom",
207
+ ),
208
+ SettingSpec(
209
+ "autoswitch", "strategy", "strategy", "choice",
210
+ choices=AUTOSWITCH_STRATEGIES,
211
+ help="How auto-switch picks the target account",
212
+ ),
213
+ SettingSpec(
214
+ "autoswitch", "includeApiKeyAccounts", "include_api_key_accounts", "bool",
215
+ help="Allow rotating onto managed API-key accounts (bill per token)",
216
+ ),
217
+ SettingSpec(
218
+ "autoswitch", "unhealthyTicks", "unhealthy_ticks", "int", 1, 100,
219
+ help="Consecutive failed polls before an account is unhealthy",
220
+ ),
221
+ SettingSpec(
222
+ "autoswitch", "model", "model", "string",
223
+ help="Also switch on these models' weekly limits (e.g. Fable, Fable,Opus, or all)",
224
+ ),
225
+ SettingSpec(
226
+ "ui", "theme", "theme", "choice", choices=("dark", "light", "auto"),
227
+ help="Color theme; auto follows the terminal background",
228
+ ),
229
+ SettingSpec(
230
+ "ui", "orgTag", "org_tag", "choice", choices=("auto", "on", "off"),
231
+ help="Show the [org] tag beside accounts; auto only where accounts share an email",
232
+ ),
233
+ SettingSpec(
234
+ "run", "shareHistory", "share_history", "bool",
235
+ help="cswap run shares one chat history across accounts",
236
+ ),
237
+ SettingSpec(
238
+ "updates", "check", "check", "bool",
239
+ help="Check PyPI once a day and print a hint when a newer release exists",
240
+ ),
241
+ SettingSpec(
242
+ "usage", "headerProbe", "header_probe", "bool",
243
+ help="Read setup-token usage from a 1-token Haiku request's rate-limit headers (opt-in: uses quota)",
244
+ ),
245
+ SettingSpec(
246
+ "usage", "fableProbe", "fable_probe", "bool",
247
+ help="With usage.headerProbe, also read Fable's weekly limit from a 1-token Fable request (opt-in: uses Fable quota)",
248
+ ),
249
+ SettingSpec(
250
+ "usage", "requestLog", "request_log", "bool",
251
+ help="Log one line per usage request (slot, token tag, request id, cf-ray) to trace a 429 (opt-in)",
252
+ ),
253
+ )
254
+ }
255
+
256
+ _AUTOSWITCH_KEYS: dict[str, str] = {
257
+ spec.field: spec.json_key
258
+ for spec in SETTING_SPECS.values()
259
+ if spec.section == "autoswitch"
260
+ }
261
+
262
+ # Every key the loaders read, per section. Anything else in the file is read
263
+ # by nothing.
264
+ _SECTION_KEYS: dict[str, tuple[str, ...]] = {
265
+ section: tuple(
266
+ spec.json_key for spec in SETTING_SPECS.values() if spec.section == section
267
+ )
268
+ for section in _SECTION_DEFAULT_SOURCES
269
+ }
270
+
271
+ # How alike two names must be (difflib ratio, compared without case) before
272
+ # one is offered as the spelling the other meant. 0.9 admits one wrong,
273
+ # missing or extra character in all but the shortest names, and another word
274
+ # separator ("weekly_threshold"). A name that only shares a word with a real
275
+ # key ("maxThreshold", "holdSeconds") scores below it.
276
+ _TYPO_CUTOFF = 0.9
277
+
278
+ # A shortened name scores too low for that and is matched as a prefix:
279
+ # "interval" and "cooldown", which are `cswap auto` flag names, for
280
+ # intervalSeconds and cooldownSeconds. Shorter than this is not a name.
281
+ _PREFIX_MIN_LENGTH = 3
282
+
283
+
284
+ @dataclass(frozen=True)
285
+ class UnrecognizedKey:
286
+ """A key in settings.json that nothing reads, so it changes nothing.
287
+
288
+ ``dotted`` is ``section.key`` for a key inside a known section and the
289
+ bare name for a top-level key that is not a section. ``suggestion`` is
290
+ the valid name it most resembles, when one is close enough to be a typo.
291
+ The two are equal for a setting written flat at the top level
292
+ (``"autoswitch.threshold": 80``): the right name in the wrong place.
293
+ """
294
+
295
+ dotted: str
296
+ suggestion: str | None = None
297
+
298
+ def describe(self) -> str:
299
+ # The key is the file's own text, so it is quoted: a stray space or a
300
+ # newline in it stays visible and on one line.
301
+ if self.suggestion is None:
302
+ hint = ""
303
+ elif self.suggestion == self.dotted:
304
+ section, _, key = self.dotted.partition(".")
305
+ hint = f"; it belongs inside {section!r} as {key!r}"
306
+ else:
307
+ hint = f"; did you mean {self.suggestion}?"
308
+ return (
309
+ f"{self.dotted!r} is not a key this version reads, "
310
+ f"so it has no effect{hint}"
311
+ )
312
+
313
+
314
+ def settings_path(backup_root: Path) -> Path:
315
+ return backup_root / SETTINGS_FILENAME
316
+
317
+
318
+ def settings_stamp(backup_root: Path) -> tuple[float | None, float | None]:
319
+ """Change token for the effective settings: both files' mtimes."""
320
+ stamp = []
321
+ for path in (settings_path(backup_root), backup_root / LOCAL_SETTINGS_FILENAME):
322
+ try:
323
+ stamp.append(path.stat().st_mtime)
324
+ except OSError:
325
+ stamp.append(None)
326
+ return tuple(stamp)
327
+
328
+
329
+ def settings_write_path(backup_root: Path) -> Path:
330
+ """The file a settings write lands in: ``settings.local.json`` once someone
331
+ has created it, else ``settings.json``. ``lexists``: a dangling link counts,
332
+ as it does for ``atomic_write_json``."""
333
+ local = backup_root / LOCAL_SETTINGS_FILENAME
334
+ return local if os.path.lexists(local) else settings_path(backup_root)
335
+
336
+
337
+ def _overlay(base: dict, local: dict) -> dict:
338
+ """``base`` with ``local`` laid over it, one level under each section."""
339
+ out = dict(base)
340
+ for key, value in local.items():
341
+ old = out.get(key)
342
+ out[key] = {**old, **value} if isinstance(value, dict) and isinstance(old, dict) else value
343
+ return out
344
+
345
+
346
+ def parse_model_names(value: str | None) -> tuple[str, ...]:
347
+ """Split a comma-separated model list, trimmed and case-insensitively
348
+ deduped (first spelling wins). Shared by the auto engine and the manual
349
+ switch strategies so both read ``autoswitch.model`` identically."""
350
+ if not value:
351
+ return ()
352
+ seen: dict[str, str] = {}
353
+ for part in value.split(","):
354
+ name = part.strip()
355
+ if name and name.lower() not in seen:
356
+ seen[name.lower()] = name
357
+ return tuple(seen.values())
358
+
359
+
360
+ def _clamped(settings: AutoSwitchSettings) -> AutoSwitchSettings:
361
+ """Clamp values into the SETTING_SPECS ranges; bad types → the default."""
362
+
363
+ def num(value, default: float | None, lo: float, hi: float) -> float | None:
364
+ # json.loads accepts NaN/Infinity literals and min/max pass NaN
365
+ # through unclamped, so a non-finite float is garbage too (a NaN line
366
+ # would silently never be crossed). Floats only: an int is always
367
+ # finite, and isfinite() would overflow on one too large for a float
368
+ # — the clamp below handles that without ever converting it.
369
+ if (
370
+ isinstance(value, bool)
371
+ or not isinstance(value, (int, float))
372
+ or (isinstance(value, float) and not math.isfinite(value))
373
+ ):
374
+ return default
375
+ return float(min(max(value, lo), hi))
376
+
377
+ kwargs = {}
378
+ for spec in SETTING_SPECS.values():
379
+ if spec.section != "autoswitch":
380
+ continue
381
+ value = getattr(settings, spec.field)
382
+ if spec.kind in ("float", "int"):
383
+ clamped = num(value, spec.default, spec.lo, spec.hi)
384
+ kwargs[spec.field] = int(clamped) if spec.kind == "int" else clamped
385
+ elif spec.kind == "bool":
386
+ if isinstance(value, str):
387
+ # Never bool(str): bool("false") is True, so a hand-edited
388
+ # quoted "false" would switch the flag on rather than off. A
389
+ # quoted boolean is read by the same words `cswap config set`
390
+ # accepts; anything else is a bad type and reverts to the
391
+ # default like the other kinds do.
392
+ parsed = _BOOL_WORDS.get(value.strip().lower())
393
+ if parsed is None:
394
+ _logger.warning(
395
+ "settings.json: %s expects a boolean, got %r; using %r",
396
+ spec.dotted, value, spec.default,
397
+ )
398
+ parsed = spec.default
399
+ kwargs[spec.field] = parsed
400
+ else:
401
+ kwargs[spec.field] = bool(value)
402
+ elif spec.kind == "string":
403
+ # A non-empty string keeps as-is; anything else reverts to default
404
+ # (None) so a null/garbage settings.json value disables the filter.
405
+ kwargs[spec.field] = value if isinstance(value, str) and value else spec.default
406
+ else: # choice
407
+ if value not in spec.choices:
408
+ _logger.warning(
409
+ "settings.json: unsupported %s %r; using %r",
410
+ spec.dotted, value, spec.default,
411
+ )
412
+ value = spec.default
413
+ kwargs[spec.field] = value
414
+ return AutoSwitchSettings(**kwargs)
415
+
416
+
417
+ def _read_raw(path: Path) -> dict:
418
+ """``settings.json`` with the ``settings.local.json`` beside it laid over it."""
419
+ return _overlay(_read_file(path), _read_file(path.with_name(LOCAL_SETTINGS_FILENAME)))
420
+
421
+
422
+ def _read_file(path: Path) -> dict:
423
+ try:
424
+ raw = json.loads(path.read_text(encoding="utf-8").strip() or "{}")
425
+ except FileNotFoundError:
426
+ return {}
427
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError) as e:
428
+ _logger.warning("Could not read %s (%s); using defaults", path, e)
429
+ return {}
430
+ if not isinstance(raw, dict):
431
+ _logger.warning("%s is not a JSON object; using defaults", path)
432
+ return {}
433
+ return raw
434
+
435
+
436
+ def _nearest(name: str, valid: tuple[str, ...]) -> str | None:
437
+ """The valid name ``name`` most resembles, or None when none is close:
438
+ the only one it is a prefix of, else the nearest spelling."""
439
+ by_lower = {v.lower(): v for v in valid}
440
+ lowered = name.lower()
441
+ if len(lowered) >= _PREFIX_MIN_LENGTH:
442
+ longer = [v for low, v in by_lower.items() if low.startswith(lowered)]
443
+ if len(longer) == 1:
444
+ return longer[0]
445
+ close = difflib.get_close_matches(lowered, by_lower, n=1, cutoff=_TYPO_CUTOFF)
446
+ return by_lower[close[0]] if close else None
447
+
448
+
449
+ def _unrecognized(raw: dict) -> list[UnrecognizedKey]:
450
+ """Keys in a parsed settings file that no loader reads, in file order."""
451
+ found = []
452
+ for name, value in raw.items():
453
+ if name == "schemaVersion":
454
+ continue
455
+ known = _SECTION_KEYS.get(name)
456
+ if known is None:
457
+ # A dotted setting name here is the spelling `cswap config`
458
+ # prints, written as one flat key.
459
+ flat = name if name in SETTING_SPECS else None
460
+ found.append(
461
+ UnrecognizedKey(name, flat or _nearest(name, tuple(_SECTION_KEYS)))
462
+ )
463
+ elif isinstance(value, dict):
464
+ for key in value:
465
+ if key not in known:
466
+ near = _nearest(key, known)
467
+ found.append(
468
+ UnrecognizedKey(
469
+ f"{name}.{key}", f"{name}.{near}" if near else None
470
+ )
471
+ )
472
+ return found
473
+
474
+
475
+ def unrecognized_keys(backup_root: Path) -> list[UnrecognizedKey]:
476
+ """Keys in settings.json that nothing reads: a typo'd or misplaced key,
477
+ or one written by another version. They survive every write; they just
478
+ do nothing, which the file alone does not show."""
479
+ return _unrecognized(_read_raw(settings_path(backup_root)))
480
+
481
+
482
+ def log_unrecognized_keys(backup_root: Path) -> None:
483
+ """Log one warning per key ``unrecognized_keys`` finds.
484
+
485
+ For a process that keeps running to call once as it starts, not for the
486
+ loaders: they run on every command, so a key left in the file would add
487
+ a line to the log each time, and the first of them runs before the log
488
+ file is attached, where a warning lands on stderr instead.
489
+ """
490
+ for item in unrecognized_keys(backup_root):
491
+ _logger.warning("settings.json: %s", item.describe())
492
+
493
+
494
+ def load_settings(backup_root: Path) -> AutoSwitchSettings:
495
+ """Load the autoswitch section; missing/corrupt file or fields → defaults."""
496
+ raw = _read_raw(settings_path(backup_root))
497
+ section = raw.get("autoswitch")
498
+ if not isinstance(section, dict):
499
+ return AutoSwitchSettings()
500
+ kwargs = {}
501
+ for field, json_key in _AUTOSWITCH_KEYS.items():
502
+ if json_key in section:
503
+ kwargs[field] = section[json_key]
504
+ try:
505
+ settings = AutoSwitchSettings(**kwargs)
506
+ except TypeError:
507
+ settings = AutoSwitchSettings()
508
+ return _clamped(settings)
509
+
510
+
511
+ def load_ui_settings(backup_root: Path) -> UiSettings:
512
+ """Load the ui section; missing/corrupt file or a bad value → its default."""
513
+ raw = _read_raw(settings_path(backup_root))
514
+ section = raw.get("ui")
515
+ default = UiSettings()
516
+ if not isinstance(section, dict):
517
+ return default
518
+ fields = {}
519
+ for spec in (SETTING_SPECS["ui.theme"], SETTING_SPECS["ui.orgTag"]):
520
+ value = section.get(spec.json_key, spec.default)
521
+ if value not in spec.choices:
522
+ _logger.warning(
523
+ "settings.json: unsupported %s %r; using %r",
524
+ spec.dotted, value, spec.default,
525
+ )
526
+ value = spec.default
527
+ fields[spec.field] = value
528
+ return UiSettings(**fields)
529
+
530
+
531
+ def load_run_settings(backup_root: Path) -> RunSettings:
532
+ """Load the run section; missing/corrupt file or non-bool value → default."""
533
+ chosen = explicit_share_history(backup_root)
534
+ return RunSettings() if chosen is None else RunSettings(share_history=chosen)
535
+
536
+
537
+ def explicit_share_history(backup_root: Path) -> bool | None:
538
+ """``run.shareHistory`` as the user set it; None when they never did.
539
+
540
+ ``load_run_settings`` answers "what applies"; this answers "who decided".
541
+ The two differ where it matters: a default that cannot be honored (history
542
+ sharing on Windows) is dropped silently while a setting someone wrote
543
+ earns a warning, and only a user who never chose is told that sharing is
544
+ the default. A value that is not a boolean counts as never set.
545
+ """
546
+ section = _read_raw(settings_path(backup_root)).get("run")
547
+ value = section.get("shareHistory") if isinstance(section, dict) else None
548
+ return value if isinstance(value, bool) else None
549
+
550
+
551
+ def load_update_settings(backup_root: Path) -> UpdateSettings:
552
+ """Load the updates section; missing/corrupt file or non-boolean → default."""
553
+ raw = _read_raw(settings_path(backup_root))
554
+ section = raw.get("updates")
555
+ default = UpdateSettings()
556
+ if not isinstance(section, dict):
557
+ return default
558
+ check = section.get("check", default.check)
559
+ if not isinstance(check, bool):
560
+ _logger.warning(
561
+ "settings.json: updates.check %r is not true or false; using %r",
562
+ check, default.check,
563
+ )
564
+ return default
565
+ return UpdateSettings(check=check)
566
+
567
+
568
+ def load_usage_settings(backup_root: Path) -> UsageSettings:
569
+ """Load the usage section; missing/corrupt file → defaults, and a
570
+ non-bool value → that key's default."""
571
+ raw = _read_raw(settings_path(backup_root))
572
+ section = raw.get("usage")
573
+ default = UsageSettings()
574
+ if not isinstance(section, dict):
575
+ return default
576
+ values: dict[str, bool] = {}
577
+ for spec in SETTING_SPECS.values(): # every usage key is a boolean
578
+ if spec.section != "usage":
579
+ continue
580
+ field, json_key = spec.field, spec.json_key
581
+ fallback = getattr(default, field)
582
+ value = section.get(json_key, fallback)
583
+ if not isinstance(value, bool):
584
+ _logger.warning(
585
+ "settings.json: usage.%s must be true or false, got %r; "
586
+ "using %r", json_key, value, fallback,
587
+ )
588
+ value = fallback
589
+ values[field] = value
590
+ return UsageSettings(**values)
591
+
592
+
593
+ def save_settings(backup_root: Path, settings: AutoSwitchSettings) -> None:
594
+ """Write the autoswitch section, preserving unknown keys and sections."""
595
+ path = settings_write_path(backup_root)
596
+ raw = _read_file(path)
597
+ raw["schemaVersion"] = raw.get("schemaVersion", SETTINGS_SCHEMA_VERSION)
598
+ section = raw.get("autoswitch")
599
+ if not isinstance(section, dict):
600
+ section = {}
601
+ for field, json_key in _AUTOSWITCH_KEYS.items():
602
+ section[json_key] = getattr(settings, field)
603
+ raw["autoswitch"] = section
604
+ atomic_write_json(path, raw)
605
+
606
+
607
+ def setting_spec(dotted_key: str) -> SettingSpec:
608
+ """Look up a spec by dotted key; unknown keys raise with the valid list."""
609
+ spec = SETTING_SPECS.get(dotted_key)
610
+ if spec is None:
611
+ raise ConfigError(
612
+ f"unknown setting '{dotted_key}'\n"
613
+ f"Valid keys: {', '.join(SETTING_SPECS)}"
614
+ )
615
+ return spec
616
+
617
+
618
+ _BOOL_WORDS = {
619
+ "true": True, "1": True, "yes": True,
620
+ "false": False, "0": False, "no": False,
621
+ }
622
+
623
+
624
+ def parse_setting_value(spec: SettingSpec, raw_value: str):
625
+ """Strictly parse a CLI-provided string for `cswap config set`.
626
+
627
+ Unlike the forgiving clamp on load, out-of-range or mistyped values raise
628
+ ConfigError so the user learns about the problem when setting the value,
629
+ not by silently degraded behavior at `cswap auto` time.
630
+ """
631
+ if spec.kind == "bool":
632
+ # Never bool(str): bool("false") is True.
633
+ parsed = _BOOL_WORDS.get(raw_value.strip().lower())
634
+ if parsed is None:
635
+ raise ConfigError(
636
+ f"{spec.dotted} expects true or false (or 1/0, yes/no), "
637
+ f"got '{raw_value}'"
638
+ )
639
+ return parsed
640
+ if spec.kind == "choice":
641
+ if raw_value not in spec.choices:
642
+ raise ConfigError(
643
+ f"{spec.dotted} must be one of: {', '.join(spec.choices)}"
644
+ )
645
+ return raw_value
646
+ if spec.kind == "string":
647
+ value = raw_value.strip()
648
+ if not value:
649
+ raise ConfigError(
650
+ f"{spec.dotted} expects a non-empty value; use "
651
+ f"'cswap config unset {spec.dotted}' to clear it"
652
+ )
653
+ return value
654
+ try:
655
+ value = int(raw_value) if spec.kind == "int" else float(raw_value)
656
+ except ValueError:
657
+ noun = "an integer" if spec.kind == "int" else "a number"
658
+ # An optional number has no spelling for "unset" here; point at the
659
+ # command that clears it instead of leaving "none" as a dead end.
660
+ hint = (
661
+ f"; use 'cswap config unset {spec.dotted}' to clear it"
662
+ if spec.default is None
663
+ else ""
664
+ )
665
+ raise ConfigError(
666
+ f"{spec.dotted} expects {noun}, got '{raw_value}'{hint}"
667
+ ) from None
668
+ if not spec.lo <= value <= spec.hi:
669
+ raise ConfigError(
670
+ f"{spec.dotted} must be between {format_setting_value(spec.lo)} "
671
+ f"and {format_setting_value(spec.hi)}"
672
+ )
673
+ return value
674
+
675
+
676
+ def format_setting_value(value) -> str:
677
+ """Render a settings value the way settings.json writes it."""
678
+ if value is None:
679
+ return "(none)"
680
+ if isinstance(value, bool):
681
+ return "true" if value else "false"
682
+ if isinstance(value, float) and value.is_integer():
683
+ return str(int(value))
684
+ return str(value)
685
+
686
+
687
+ def _read_raw_for_write(path: Path) -> dict:
688
+ """Raw read for the config write path: a corrupt file errors, never {}.
689
+
690
+ ``_read_raw``'s degrade-to-defaults is right for reads, but a
691
+ read-modify-write starting from ``{}`` would replace a malformed (and
692
+ maybe hand-recoverable) file with a near-empty one.
693
+ """
694
+ try:
695
+ text = path.read_text(encoding="utf-8")
696
+ except FileNotFoundError:
697
+ return {}
698
+ except (OSError, UnicodeDecodeError) as e:
699
+ raise ConfigError(f"could not read {path}: {e}") from e
700
+ try:
701
+ raw = json.loads(text.strip() or "{}") # a touched, empty file is {}
702
+ except json.JSONDecodeError as e:
703
+ raise ConfigError(
704
+ f"{path} is not valid JSON ({e}); fix or delete it before "
705
+ "changing settings"
706
+ ) from e
707
+ if not isinstance(raw, dict):
708
+ raise ConfigError(
709
+ f"{path} is not a JSON object; fix or delete it before "
710
+ "changing settings"
711
+ )
712
+ return raw
713
+
714
+
715
+ def set_setting(backup_root: Path, dotted_key: str, raw_value: str):
716
+ """Validate and persist one key for `cswap config set`; returns the value.
717
+
718
+ Writes only the given key (plus schemaVersion) — deliberately not
719
+ ``save_settings``, which writes every known key and would freeze the
720
+ current defaults into the file, pinning users to them if a later version
721
+ changes a default. Unknown keys and sections in the file survive.
722
+ """
723
+ spec = setting_spec(dotted_key)
724
+ value = parse_setting_value(spec, raw_value)
725
+ path = settings_write_path(backup_root)
726
+ raw = _read_raw_for_write(path)
727
+ raw["schemaVersion"] = raw.get("schemaVersion", SETTINGS_SCHEMA_VERSION)
728
+ section = raw.get(spec.section)
729
+ if not isinstance(section, dict):
730
+ section = {}
731
+ section[spec.json_key] = value
732
+ raw[spec.section] = section
733
+ atomic_write_json(path, raw)
734
+ return value
735
+
736
+
737
+ def unset_setting(backup_root: Path, dotted_key: str) -> bool:
738
+ """Remove one key from the file writes land in; False if not set there (no write)."""
739
+ spec = setting_spec(dotted_key)
740
+ path = settings_write_path(backup_root)
741
+ raw = _read_raw_for_write(path)
742
+ section = raw.get(spec.section)
743
+ if not isinstance(section, dict) or spec.json_key not in section:
744
+ return False
745
+ raw["schemaVersion"] = raw.get("schemaVersion", SETTINGS_SCHEMA_VERSION)
746
+ del section[spec.json_key]
747
+ if not section:
748
+ del raw[spec.section]
749
+ atomic_write_json(path, raw)
750
+ return True
751
+
752
+
753
+ def effective_settings(backup_root: Path) -> list[tuple[SettingSpec, object, bool]]:
754
+ """(spec, effective value, explicitly set?) per key, in registry order.
755
+
756
+ "Set" means the key is present in the merged settings.json plus
757
+ settings.local.json — an explicit value equal to the default still counts
758
+ — so `cswap config`'s "(default)" marker reflects the files, not value
759
+ equality.
760
+ """
761
+ raw = _read_raw(settings_path(backup_root))
762
+ loaded = {
763
+ "autoswitch": load_settings(backup_root),
764
+ "ui": load_ui_settings(backup_root),
765
+ "run": load_run_settings(backup_root),
766
+ "updates": load_update_settings(backup_root),
767
+ "usage": load_usage_settings(backup_root),
768
+ }
769
+ rows = []
770
+ for spec in SETTING_SPECS.values():
771
+ section = raw.get(spec.section)
772
+ is_set = isinstance(section, dict) and spec.json_key in section
773
+ rows.append((spec, getattr(loaded[spec.section], spec.field), is_set))
774
+ return rows
775
+
776
+
777
+ def merged_with_cli(settings: AutoSwitchSettings, args) -> AutoSwitchSettings:
778
+ """Overlay non-None CLI overrides (argparse Namespace) onto settings."""
779
+ overrides = {}
780
+ for attr, field in (
781
+ ("threshold", "threshold"),
782
+ ("weekly_threshold", "weekly_threshold"),
783
+ ("interval", "interval_seconds"),
784
+ ("cooldown", "cooldown_seconds"),
785
+ ("include_api_key_accounts", "include_api_key_accounts"),
786
+ ("model", "model"),
787
+ ("strategy", "strategy"),
788
+ ):
789
+ value = getattr(args, attr, None)
790
+ if value is not None:
791
+ overrides[field] = value
792
+ if not overrides:
793
+ return settings
794
+ return _clamped(dataclasses.replace(settings, **overrides))
795
+
796
+
797
+ def atomic_write_json(path: Path, data: dict) -> None:
798
+ """Atomically write JSON with the backup dir's 0600/0700 modes.
799
+
800
+ Shared by settings.json and the autoswitch state file (and any future
801
+ machine-local state files beside them).
802
+
803
+ **Writes THROUGH a symlink, never over it.** A rename swaps a directory
804
+ ENTRY and does not follow links, so renaming onto a symlinked path
805
+ DETACHES the link: the write succeeds, the content is right, and the
806
+ link target silently stops receiving updates — until something restores
807
+ the link (a dotfiles deploy), taking every change written since with
808
+ it. Same shape as #192/#193, which fixed ``session.py``'s own writer;
809
+ this is the shared JSON writer. Three consequences, each deliberate:
810
+
811
+ - A DANGLING link still writes where it points; linking a path is a
812
+ request to write there.
813
+ - The temp file is created beside the RESOLVED target, so the rename
814
+ stays on one filesystem and remains atomic (beside the LINK it would
815
+ hit EXDEV whenever the target lives on another mount).
816
+ - The 0700 hardening stays on the directory cswap owns. Applying it to
817
+ the resolved parent would narrow a directory belonging to something
818
+ else, and raise ``PermissionError`` outright when that parent is not
819
+ ours to chmod. The written file still gets 0600, and ``mkstemp``
820
+ creates it 0600 to begin with, so the secret is never exposed.
821
+ """
822
+ target = publish_target(path)
823
+ target.parent.mkdir(parents=True, exist_ok=True)
824
+ if sys.platform != "win32":
825
+ # `path.parent`, NOT the target's: see the docstring.
826
+ os.chmod(path.parent, 0o700)
827
+ atomic_write_text(target, json.dumps(data, indent=2))