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,455 @@
1
+ """Serialization helpers for ``--json`` structured output.
2
+
3
+ Centralizes the schema-v1 shapes so ``--list``/``--status``/``--switch`` agree on
4
+ field names (camelCase, matching the export envelope in transfer.py) and on how the
5
+ internal usage dict is projected to JSON. Callers build payloads here; the CLI does
6
+ the single ``json.dumps`` (see cli.py).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from datetime import datetime, timezone
13
+
14
+ from claude_swap import oauth, pace, subscription
15
+ from claude_swap.models import AccountPolicy
16
+ from claude_swap.poll_policy import parse_reset_ts
17
+
18
+ # Bump only on a breaking change to any payload shape. Scripts key off this.
19
+ SCHEMA_VERSION = 1
20
+
21
+ # Sentinel entries that ``_collect_usage`` / ``_fetch_active_usage`` yield in place
22
+ # of a usage dict. Kept here (the serialization hub) so the human renderer and the
23
+ # JSON projection agree instead of scattering raw strings.
24
+ USAGE_NO_CREDENTIALS = "no credentials"
25
+ USAGE_TOKEN_EXPIRED = "token expired"
26
+ # API-key (``/login`` managed key) accounts have no subscription quota; usage is
27
+ # reported as this sentinel instead of being fetched from the OAuth usage API.
28
+ USAGE_API_KEY = "api key"
29
+ # The active account's macOS Keychain was unreadable (locked / denied / timeout)
30
+ # with no plaintext fallback — distinct from a genuinely empty slot, so the user
31
+ # isn't misled into an unnecessary re-login.
32
+ USAGE_KEYCHAIN_UNAVAILABLE = "keychain unavailable"
33
+ # The stored refresh-token lineage is dead (repeated ``invalid_grant``). The
34
+ # account is quarantined from fetching until a re-login (``cswap login`` / ``add``)
35
+ # replaces the credential; distinct from "token expired" (which Claude Code can
36
+ # refresh on its own) because only the user can fix it.
37
+ USAGE_RELOGIN_REQUIRED = "re-login needed"
38
+ # The profile oracle proved the live credential belongs to a DIFFERENT account
39
+ # than the slot's identity (foreign credential under a stale config — partial
40
+ # cross-machine sync or a mid-``/login`` poll). Its quota is not this slot's, so
41
+ # recording it would poison history and autoswitch decisions; distinct from
42
+ # "token expired" because holding is wrong here — a switch repairs the drift
43
+ # (stash the foreign credential, restore the slot's backup), so autoswitch
44
+ # should treat the active as unknown-headroom and fail over.
45
+ USAGE_FOREIGN_CREDENTIAL = "foreign credential"
46
+
47
+
48
+ def _window_to_json(entry: dict) -> dict:
49
+ """Project a 5h/7d usage window to JSON, preserving raw ``resetsAt``.
50
+
51
+ ``countdown``/``clock`` are recomputed from ``resets_at`` at serialization
52
+ time (the store may serve a measurement hours after its fetch); entries
53
+ without ``resets_at`` fall back to the fetch-time strings.
54
+ """
55
+ out: dict = {"pct": entry["pct"]}
56
+ if "resets_at" in entry:
57
+ out["resetsAt"] = entry["resets_at"]
58
+ cell = oauth.fresh_reset_strings(entry)
59
+ if cell:
60
+ out["countdown"], out["clock"] = cell
61
+ return out
62
+
63
+
64
+ def _pace_fields(entry: dict, fetched_at: float | None) -> dict:
65
+ """Weekly-window pace fields (issue #125): additive, JSON-only.
66
+
67
+ Emitted only when pace is computable and not suppressed (see
68
+ ``claude_swap.pace.compute_pace``). ``projectedExhaustionAt`` is a linear
69
+ ETA — wide error bars against real, bursty usage — so it's kept out of
70
+ every human-facing surface and only ever appears here.
71
+ """
72
+ if fetched_at is None:
73
+ return {}
74
+ result = pace.compute_pace(entry, fetched_at=fetched_at)
75
+ if result is None:
76
+ return {}
77
+ out: dict = {
78
+ "expectedPct": round(result.expected_pct, 1),
79
+ "aheadOfPace": result.ahead,
80
+ }
81
+ eta = pace.projected_exhaustion_ts(result, fetched_at=fetched_at)
82
+ if eta is not None:
83
+ out["projectedExhaustionAt"] = (
84
+ datetime.fromtimestamp(eta, tz=timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
85
+ )
86
+ will_last = pace.will_last_to_reset(result)
87
+ if will_last is not None:
88
+ out["willLastToReset"] = will_last
89
+ return out
90
+
91
+
92
+ def _weekly_window_to_json(entry: dict, fetched_at: float | None) -> dict:
93
+ """A 7d/scoped window's JSON projection, with pace fields layered in."""
94
+ out = _window_to_json(entry)
95
+ out.update(_pace_fields(entry, fetched_at))
96
+ return out
97
+
98
+
99
+ def _scoped_window_to_json(entry: dict, fetched_at: float | None) -> dict:
100
+ """Project a per-model scoped weekly window, carrying its model name.
101
+
102
+ ``probeAfter`` marks a row the header probe read as spent and keeps
103
+ until then instead of asking again (``oauth._add_scoped_limits``). It
104
+ survives export so a machine importing the reading keeps it too.
105
+ """
106
+ out = _weekly_window_to_json(entry, fetched_at)
107
+ out["name"] = entry["name"]
108
+ if "probe_after" in entry:
109
+ out["probeAfter"] = entry["probe_after"]
110
+ return out
111
+
112
+
113
+ def usage_to_json(usage: dict, fetched_at: float | None = None) -> dict:
114
+ """Convert the internal usage dict to its camelCase JSON projection.
115
+
116
+ Sub-keys are emitted only when present in the source (the API does not always
117
+ return every window or pay-as-you-go spend). ``fetched_at`` is the
118
+ measurement's fetch time; passing it adds pace fields to the weekly
119
+ windows (``seven_day``, ``scoped``) only — never ``five_hour`` (issue #125).
120
+ """
121
+ out: dict = {}
122
+ if "five_hour" in usage:
123
+ out["fiveHour"] = _window_to_json(usage["five_hour"])
124
+ if "seven_day" in usage:
125
+ out["sevenDay"] = _weekly_window_to_json(usage["seven_day"], fetched_at)
126
+ if "spend" in usage:
127
+ spend = usage["spend"]
128
+ spend_out: dict = {
129
+ "used": spend["used"],
130
+ "limit": spend["limit"],
131
+ "pct": spend["pct"],
132
+ "currency": spend["currency"],
133
+ }
134
+ if "resets_at" in spend:
135
+ spend_out["resetsAt"] = spend["resets_at"]
136
+ cell = oauth.fresh_reset_strings(spend)
137
+ if cell:
138
+ spend_out["countdown"], spend_out["clock"] = cell
139
+ out["spend"] = spend_out
140
+ if "scoped" in usage:
141
+ out["scoped"] = [_scoped_window_to_json(w, fetched_at) for w in usage["scoped"]]
142
+ # A setup-token header-probe reading: its completeness and any refusal
143
+ # decide whether it may gate auto-switching, so both survive export.
144
+ if usage.get("source") == oauth.USAGE_SOURCE_HEADERS:
145
+ out["source"] = oauth.USAGE_SOURCE_HEADERS
146
+ rejected = usage.get("rejected")
147
+ if isinstance(rejected, dict):
148
+ out["rejected"] = {
149
+ "retryAfterS": rejected.get("retry_after_s"),
150
+ "resetsAt": rejected.get("resets_at"),
151
+ }
152
+ return out
153
+
154
+
155
+ def _is_number(value: object) -> bool:
156
+ return (
157
+ isinstance(value, (int, float))
158
+ and not isinstance(value, bool)
159
+ and math.isfinite(value)
160
+ )
161
+
162
+
163
+ def _window_from_json(window: object, label: str, nullable: bool = False) -> dict:
164
+ """One JSON window back to the internal shape, fetch-time strings rebuilt.
165
+
166
+ ``nullable`` admits ``"pct": null``, which :func:`usage_to_json` emits for
167
+ a 5h/7d window the API reported without a utilization figure.
168
+ """
169
+ if not isinstance(window, dict):
170
+ raise ValueError(f"{label} must be an object")
171
+ pct = window.get("pct")
172
+ if nullable and "pct" in window and pct is None:
173
+ pct_value = None
174
+ elif _is_number(pct) and pct >= 0:
175
+ pct_value = float(pct)
176
+ else:
177
+ raise ValueError(
178
+ f"{label}.pct must be a non-negative number{' or null' if nullable else ''}"
179
+ )
180
+ out: dict = {"pct": pct_value}
181
+ resets_at = window.get("resetsAt")
182
+ if resets_at is not None:
183
+ if not isinstance(resets_at, str):
184
+ raise ValueError(f"{label}.resetsAt must be an ISO-8601 string")
185
+ try:
186
+ out["countdown"], out["clock"] = oauth.format_reset(resets_at)
187
+ except (ValueError, TypeError):
188
+ raise ValueError(f"{label}.resetsAt is not an ISO-8601 time: {resets_at!r}")
189
+ out["resets_at"] = resets_at
190
+ return out
191
+
192
+
193
+ def usage_from_json(usage: object) -> dict:
194
+ """Read a ``usage`` object from ``list --json`` back into the internal dict.
195
+
196
+ The inverse of :func:`usage_to_json` for what the API measured: ``pct``,
197
+ ``resetsAt``, the spend amounts and the scoped model names. Everything
198
+ derived at serialization (countdown, clock, pace fields) is dropped, and
199
+ the fetch-time strings are rebuilt from ``resets_at``, which gives the
200
+ shape :func:`oauth.build_usage_result` stores. A 5h/7d window's ``pct``
201
+ may be ``null`` (reported without a figure), except in a ``source:
202
+ headers`` document, which the probe never produces that way. Raises
203
+ ``ValueError`` on anything malformed, so an importer can refuse a
204
+ document before writing any of it.
205
+ """
206
+ if not isinstance(usage, dict):
207
+ raise ValueError("usage must be an object")
208
+ out: dict = {}
209
+ if "fiveHour" in usage:
210
+ out["five_hour"] = _window_from_json(
211
+ usage["fiveHour"], "fiveHour", nullable=True
212
+ )
213
+ if "sevenDay" in usage:
214
+ out["seven_day"] = _window_from_json(
215
+ usage["sevenDay"], "sevenDay", nullable=True
216
+ )
217
+ if "spend" in usage:
218
+ spend = usage["spend"]
219
+ out_spend = _window_from_json(spend, "spend")
220
+ for key in ("used", "limit"):
221
+ if not _is_number(spend.get(key)):
222
+ raise ValueError(f"spend.{key} must be a number")
223
+ out_spend[key] = float(spend[key])
224
+ if not isinstance(spend.get("currency"), str):
225
+ raise ValueError("spend.currency must be a string")
226
+ out_spend["currency"] = spend["currency"]
227
+ out["spend"] = out_spend
228
+ if "scoped" in usage:
229
+ if not isinstance(usage["scoped"], list):
230
+ raise ValueError("scoped must be a list")
231
+ scoped = []
232
+ for i, window in enumerate(usage["scoped"]):
233
+ label = f"scoped[{i}]"
234
+ entry = _window_from_json(window, label)
235
+ name = window.get("name")
236
+ if not isinstance(name, str) or not name:
237
+ raise ValueError(f"{label}.name must be a non-empty string")
238
+ probe_after = window.get("probeAfter")
239
+ if probe_after is not None:
240
+ if not isinstance(probe_after, str) or parse_reset_ts(probe_after) is None:
241
+ raise ValueError(f"{label}.probeAfter must be an ISO-8601 time")
242
+ entry["probe_after"] = probe_after
243
+ scoped.append({"name": name, **entry})
244
+ out["scoped"] = scoped
245
+ if "rejected" in usage:
246
+ rejected = usage["rejected"]
247
+ if not isinstance(rejected, dict):
248
+ raise ValueError("rejected must be an object")
249
+ retry_after = rejected.get("retryAfterS")
250
+ if retry_after is not None and not _is_number(retry_after):
251
+ raise ValueError("rejected.retryAfterS must be a number or null")
252
+ resets_at = rejected.get("resetsAt")
253
+ if resets_at is not None and not isinstance(resets_at, str):
254
+ raise ValueError("rejected.resetsAt must be an ISO-8601 string or null")
255
+ out["rejected"] = {"retry_after_s": retry_after, "resets_at": resets_at}
256
+ if not out:
257
+ raise ValueError("usage carries no windows")
258
+ if usage.get("source") == oauth.USAGE_SOURCE_HEADERS:
259
+ # The header probe never reports a window without a figure, and one
260
+ # would pass the completeness check while contributing no window.
261
+ for key, label in (("five_hour", "fiveHour"), ("seven_day", "sevenDay")):
262
+ if key in out and out[key]["pct"] is None:
263
+ raise ValueError(f"{label}.pct cannot be null in a headers reading")
264
+ out["source"] = oauth.USAGE_SOURCE_HEADERS
265
+ return out
266
+
267
+
268
+ def usage_fields(
269
+ entry: dict | str | None, fetched_at: float | None = None
270
+ ) -> tuple[str, dict | None]:
271
+ """Map a collected usage entry to ``(usageStatus, usage|None)``.
272
+
273
+ A collected entry is one of: a usage dict, the ``USAGE_TOKEN_EXPIRED`` sentinel
274
+ (active token expired and the refresh was deferred this pass — lock
275
+ contention, unattributable lineage, or a failed persist; retried
276
+ automatically — or a live session's credential refused, which only that
277
+ session may renew), the ``USAGE_API_KEY`` sentinel
278
+ (managed API-key account, no subscription quota), the
279
+ ``USAGE_KEYCHAIN_UNAVAILABLE`` sentinel (active Keychain unreadable), the
280
+ ``USAGE_FOREIGN_CREDENTIAL`` sentinel (live credential proven to belong to
281
+ another account; usage suppressed, a switch repairs the drift), the
282
+ ``USAGE_NO_CREDENTIALS`` sentinel, or ``None`` (fetch failed). ``fetched_at``
283
+ is forwarded to ``usage_to_json`` for the weekly pace fields (issue #125).
284
+ """
285
+ if isinstance(entry, dict):
286
+ return "ok", usage_to_json(entry, fetched_at)
287
+ if entry == USAGE_TOKEN_EXPIRED:
288
+ return "token_expired", None
289
+ if entry == USAGE_API_KEY:
290
+ return "api_key", None
291
+ if entry == USAGE_KEYCHAIN_UNAVAILABLE:
292
+ return "keychain_unavailable", None
293
+ if entry == USAGE_RELOGIN_REQUIRED:
294
+ return "relogin_required", None
295
+ if entry == USAGE_FOREIGN_CREDENTIAL:
296
+ return "foreign_credential", None
297
+ if isinstance(entry, str):
298
+ return "no_credentials", None
299
+ return "unavailable", None
300
+
301
+
302
+ def account_ref(number: int | None, email: str) -> dict:
303
+ """A minimal account reference, used for switch ``from``/``to``."""
304
+ return {"number": number, "email": email}
305
+
306
+
307
+ def usage_freshness_fields(
308
+ fetched_at: float | None, age_s: float | None
309
+ ) -> dict:
310
+ """Additive ``usageFetchedAt``/``usageAgeSeconds`` fields describing how
311
+ old the served ``usage`` measurement is (the store may serve last-good
312
+ data on fetch failure). Emitted under these names only alongside a
313
+ non-null ``usage``; ``last_good_usage_fields`` reuses them renamed to
314
+ ``lastGoodFetchedAt``/``lastGoodAgeSeconds`` for null-``usage`` rows."""
315
+ if fetched_at is None:
316
+ return {}
317
+ fields: dict = {"usageFetchedAt": _timestamp(fetched_at)}
318
+ if age_s is not None:
319
+ fields["usageAgeSeconds"] = round(age_s, 1)
320
+ return fields
321
+
322
+
323
+ def _timestamp(epoch_s: float) -> str:
324
+ return (
325
+ datetime.fromtimestamp(epoch_s, tz=timezone.utc)
326
+ .isoformat(timespec="seconds")
327
+ .replace("+00:00", "Z")
328
+ )
329
+
330
+
331
+ def usage_failure_fields(
332
+ status: str, last_error: str | None, backoff_until: float | None
333
+ ) -> dict:
334
+ """Additive ``usageError``/``usageRetryAt`` fields for a row that is
335
+ ``unavailable`` with nothing else to say for itself: the last fetch
336
+ failure by kind (``http-429``, ``timeout``, ...) and, while the store is
337
+ backing off from it, when the next attempt is due. Every other status
338
+ already explains the null ``usage``, so nothing is added to it."""
339
+ if status != "unavailable" or not last_error:
340
+ return {}
341
+ out = {"usageError": last_error}
342
+ if backoff_until is not None:
343
+ out["usageRetryAt"] = _timestamp(backoff_until)
344
+ return out
345
+
346
+
347
+ def last_good_usage_fields(
348
+ usage: dict | None, fetched_at: float | None, age_s: float | None
349
+ ) -> dict:
350
+ """Display-grade last-good usage, separate from decision-grade ``usage``."""
351
+ if not isinstance(usage, dict) or fetched_at is None:
352
+ return {}
353
+ freshness = usage_freshness_fields(fetched_at, age_s)
354
+ out = {
355
+ "lastGoodUsage": usage_to_json(usage, fetched_at),
356
+ "lastGoodFetchedAt": freshness["usageFetchedAt"],
357
+ }
358
+ if "usageAgeSeconds" in freshness:
359
+ out["lastGoodAgeSeconds"] = freshness["usageAgeSeconds"]
360
+ return out
361
+
362
+
363
+ def subscription_plan_fields(record: dict) -> dict:
364
+ """JSON for a stored plan record: label, raw fields, expiry, and age.
365
+
366
+ ``fetchedAt`` is always present, so a script can tell a plan fetched this
367
+ morning from one that has not refreshed in days and decide for itself how
368
+ far to trust ``expired``.
369
+ """
370
+ plan = record["plan"]
371
+ fields = {
372
+ "label": subscription.plan_label(plan),
373
+ "tier": plan["tier"],
374
+ }
375
+ for key in ("organizationType", "billingType", "subscriptionStatus"):
376
+ if key in plan:
377
+ fields[key] = plan[key]
378
+ name = plan.get("planDisplayName")
379
+ if isinstance(name, str) and name:
380
+ fields["planDisplayName"] = name
381
+ fields["expired"] = subscription.is_expired(plan)
382
+ fields["fetchedAt"] = _timestamp(record["fetchedAt"])
383
+ return fields
384
+
385
+
386
+ def account_row(
387
+ number: int,
388
+ email: str,
389
+ org_name: str,
390
+ org_uuid: str,
391
+ active: bool,
392
+ usage_entry: dict | str | None,
393
+ *,
394
+ usage_fetched_at: float | None = None,
395
+ usage_age_s: float | None = None,
396
+ last_good_usage: dict | None = None,
397
+ last_error: str | None = None,
398
+ backoff_until: float | None = None,
399
+ alias: str = "",
400
+ disabled: bool = False,
401
+ policy: AccountPolicy = AccountPolicy(),
402
+ login_expires_at: str | None = None,
403
+ subscription_plan: dict | None = None,
404
+ ) -> dict:
405
+ """A full account row for ``--list``. ``backoff_until`` is the live
406
+ backoff only; a lapsed one is the caller's to withhold."""
407
+ status, usage = usage_fields(usage_entry, usage_fetched_at)
408
+ row = {
409
+ "number": number,
410
+ "email": email,
411
+ "organizationName": org_name,
412
+ "organizationUuid": org_uuid,
413
+ "isOrganization": bool(org_uuid),
414
+ "active": active,
415
+ "usageStatus": status,
416
+ "usage": usage,
417
+ }
418
+ if alias:
419
+ row["alias"] = alias
420
+ # Additive field: present only when the slot is held out of rotation, so
421
+ # existing consumers keying on the base schema are unaffected.
422
+ if disabled:
423
+ row["disabled"] = True
424
+ # Same convention for the per-account policy: a slot on the global default
425
+ # emits neither key, so a fleet that never sets a policy produces rows
426
+ # byte-identical to those from before this feature existed.
427
+ if policy.threshold is not None:
428
+ row["threshold"] = policy.threshold
429
+ # Additive field: when the stored login records the expiry of its refresh
430
+ # token (see ``oauth.login_expires_at_iso``), scripts can warn ahead of the
431
+ # ``relogin_required`` that follows; absent when the login carries none.
432
+ if login_expires_at:
433
+ row["loginExpiresAt"] = login_expires_at
434
+ # Additive field: the slot's subscription plan once one has been fetched
435
+ # (see ``subscription``); a slot never fetched emits no key at all.
436
+ if subscription_plan:
437
+ row["plan"] = subscription_plan_fields(subscription_plan)
438
+ if usage is not None:
439
+ row.update(usage_freshness_fields(usage_fetched_at, usage_age_s))
440
+ else:
441
+ row.update(
442
+ last_good_usage_fields(
443
+ last_good_usage, usage_fetched_at, usage_age_s
444
+ )
445
+ )
446
+ row.update(usage_failure_fields(status, last_error, backoff_until))
447
+ return row
448
+
449
+
450
+ def error_envelope(exc: Exception) -> dict:
451
+ """The structured error payload emitted on a handled ClaudeSwitchError."""
452
+ return {
453
+ "schemaVersion": SCHEMA_VERSION,
454
+ "error": {"type": type(exc).__name__, "message": str(exc)},
455
+ }