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,24 @@
1
+ """Multi-account switcher for Claude Code."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+
6
+ def _installed_distribution() -> tuple[str, str]:
7
+ """The installed distribution's name and version.
8
+
9
+ llmswap ships this package as ``llmswap-cli``; an old standalone install of
10
+ claude-swap still reports as ``claude-swap``.
11
+ """
12
+ for name in ("llmswap-cli", "claude-swap"):
13
+ try:
14
+ return name, version(name)
15
+ except PackageNotFoundError:
16
+ continue
17
+ return "llmswap-cli", "0+unknown"
18
+
19
+
20
+ DIST_NAME, __version__ = _installed_distribution()
21
+
22
+ from claude_swap.switcher import ClaudeAccountSwitcher
23
+
24
+ __all__ = ["ClaudeAccountSwitcher", "__version__"]
@@ -0,0 +1,6 @@
1
+ """Allow running as `python -m claude_swap`."""
2
+
3
+ from claude_swap.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,330 @@
1
+ """Run the menu bar from inside a wrapper ``.app`` so the process has a bundle ID.
2
+
3
+ ``cswap menubar`` is a console script: the process macOS sees is a bare Python
4
+ interpreter somewhere under ``~/.local/share/uv`` (or a pipx venv), and
5
+ ``NSRunningApplication.bundleIdentifier`` for it is nil. Menu bar managers key
6
+ every status item by that identifier (Dimble, Ice, Bartender, SaneBar all do),
7
+ and an item whose owner has none is simply skipped: it never shows up in their
8
+ panel and cannot be hidden, ordered or given a hotkey.
9
+
10
+ The fix is a minimal bundle built on demand::
11
+
12
+ /Applications/claude-swap Menubar.app/
13
+ Contents/
14
+ Info.plist CFBundleIdentifier com.claude-swap.menubar, LSUIElement
15
+ pyvenv.cfg home = <directory of the real interpreter>
16
+ lib/
17
+ python3.X -> <sys.prefix>/lib/python3.X the install's site-packages
18
+ libpython3.X.dylib -> <base>/lib/... the stub interpreter's dylib
19
+ MacOS/python byte copy of the real interpreter
20
+
21
+ LaunchServices identifies a process by its executable's path, so the
22
+ interpreter must physically live under ``Contents/MacOS`` (a symlink resolves to
23
+ the original and keeps the nil identity; a copy is ~20 MB, once). CPython then
24
+ finds ``pyvenv.cfg`` one directory up and treats ``Contents`` as its venv:
25
+ ``home`` points it at the stdlib, the ``lib`` links at the installed packages.
26
+ So the copy runs the very same claude-swap, just under a name macOS can see.
27
+
28
+ ``Contents/lib`` is a real directory, not a symlink to the venv's ``lib``: many
29
+ managed interpreters (uv's CPython 3.12/3.13, for one) are small stubs linked
30
+ against ``@executable_path/../lib/libpython3.X.dylib``, so the copy resolves
31
+ that path inside the bundle, where the venv's ``lib`` has no such library and
32
+ dyld aborts the process before Python even starts. Recent python-build-
33
+ standalone releases link libpython statically and never look. The directory
34
+ holds links to both: the venv's per-version package dirs and the base
35
+ install's ``libpython*``.
36
+
37
+ The bundle lives in ``/Applications`` because the menu bar host
38
+ (``MenuBarAgent``, macOS 26+) resolves a status item's owning bundle from the
39
+ app's location: for an app anywhere else (``~/Applications`` and
40
+ ``~/Library/Application Support`` included) the item's identity reads as nil,
41
+ and the moment a menu bar manager hides *anything* through the system's
42
+ assessment-mode allowlist, a nil identity matches nothing and the item is taken
43
+ down with the hidden ones (fif7y/dimble#30 traced the same failure for iStat
44
+ Menus). When ``/Applications`` is not writable the bundle falls back to the data
45
+ directory: the menu bar still works, managers just cannot keep it visible.
46
+
47
+ The bundle is rebuilt (cheaply: only what changed) on every ``cswap menubar``
48
+ start and the process re-execs into it before AppKit loads. ``uv tool
49
+ --reinstall`` recreating the venv or a managed-Python version bump therefore
50
+ never leaves a stale bundle behind, and launchd keeps the same pid throughout.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import os
56
+ import plistlib
57
+ import shutil
58
+ import stat
59
+ import subprocess
60
+ import sys
61
+ import tempfile
62
+ from pathlib import Path
63
+
64
+ from claude_swap.printer import warning
65
+
66
+ BUNDLE_ID = "com.claude-swap.menubar"
67
+ BUNDLE_NAME = "claude-swap"
68
+ BUNDLE_DIRNAME = "claude-swap Menubar.app"
69
+ APPLICATIONS_DIR = Path("/Applications")
70
+ OPT_OUT_ENV = "CLAUDE_SWAP_NO_BUNDLE"
71
+
72
+
73
+ def bundle_dir(backup_dir: Path, applications: Path = APPLICATIONS_DIR) -> Path:
74
+ """``/Applications`` when writable (see module docstring), else the data dir."""
75
+ if os.access(applications, os.W_OK):
76
+ return applications
77
+ return Path(backup_dir)
78
+
79
+
80
+ def bundle_path(backup_dir: Path, applications: Path = APPLICATIONS_DIR) -> Path:
81
+ """Where the wrapper bundle lives for this install."""
82
+ return bundle_dir(backup_dir, applications) / BUNDLE_DIRNAME
83
+
84
+
85
+ def remove(backup_dir: Path, applications: Path | None = None) -> list[Path]:
86
+ """Delete the wrapper bundle wherever an earlier run may have put it.
87
+
88
+ Both homes are tried, not just the one :func:`bundle_path` would pick now:
89
+ ``/Applications`` may have been writable when the bundle was built and not
90
+ be any more, or the other way round. ``applications`` is read at call time
91
+ so tests can point it elsewhere. Returns the paths that existed and went.
92
+ """
93
+ if applications is None:
94
+ applications = APPLICATIONS_DIR
95
+ removed: list[Path] = []
96
+ for home in (applications, Path(backup_dir)):
97
+ candidate = home / BUNDLE_DIRNAME
98
+ if candidate.is_dir():
99
+ shutil.rmtree(candidate)
100
+ removed.append(candidate)
101
+ return removed
102
+
103
+
104
+ def in_bundle(executable: Path | None = None) -> bool:
105
+ """Whether ``executable`` (default: this interpreter) runs inside our bundle."""
106
+ exe = Path(executable or sys.executable)
107
+ contents = exe.parent.parent
108
+ if contents.name != "Contents" or contents.parent.suffix != ".app":
109
+ return False
110
+ try:
111
+ info = plistlib.loads((contents / "Info.plist").read_bytes())
112
+ except (OSError, plistlib.InvalidFileException, ValueError):
113
+ return False
114
+ return isinstance(info, dict) and info.get("CFBundleIdentifier") == BUNDLE_ID
115
+
116
+
117
+ def _same_file_content(src: Path, dst: Path) -> bool:
118
+ """Cheap staleness check: a copy made with mtime preserved matches on both."""
119
+ try:
120
+ a, b = src.stat(), dst.stat()
121
+ except OSError:
122
+ return False
123
+ return a.st_size == b.st_size and a.st_mtime_ns == b.st_mtime_ns
124
+
125
+
126
+ def _write_if_changed(path: Path, data: bytes) -> None:
127
+ """Atomic write, skipped when the file already holds ``data``."""
128
+ try:
129
+ if path.read_bytes() == data:
130
+ return
131
+ except OSError:
132
+ pass
133
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
134
+ with os.fdopen(fd, "wb") as fh:
135
+ fh.write(data)
136
+ os.chmod(tmp, 0o644)
137
+ os.replace(tmp, path)
138
+
139
+
140
+ def _copy_if_changed(src: Path, dst: Path) -> None:
141
+ """Copy ``src`` over ``dst`` atomically, preserving mode and mtime.
142
+
143
+ A running instance keeps executing the old inode, so replacing the file
144
+ under it is safe; writing into it in place would not be.
145
+ """
146
+ if _same_file_content(src, dst):
147
+ return
148
+ fd, tmp = tempfile.mkstemp(dir=dst.parent, prefix=f".{dst.name}.")
149
+ try:
150
+ with os.fdopen(fd, "wb") as out, src.open("rb") as inp:
151
+ while chunk := inp.read(1 << 20):
152
+ out.write(chunk)
153
+ st = src.stat()
154
+ os.chmod(tmp, stat.S_IMODE(st.st_mode) | 0o700)
155
+ os.utime(tmp, ns=(st.st_atime_ns, st.st_mtime_ns))
156
+ os.replace(tmp, dst)
157
+ except BaseException:
158
+ try:
159
+ os.unlink(tmp)
160
+ except OSError:
161
+ pass
162
+ raise
163
+
164
+
165
+ def _symlink_if_changed(target: Path, link: Path) -> None:
166
+ if link.is_symlink() and os.readlink(link) == str(target):
167
+ return
168
+ tmp = link.with_name(f".{link.name}.{os.getpid()}")
169
+ if tmp.is_symlink():
170
+ tmp.unlink()
171
+ os.symlink(str(target), tmp)
172
+ if link.exists() and not link.is_symlink():
173
+ raise OSError(f"{link} exists and is not a symlink")
174
+ os.replace(tmp, link)
175
+
176
+
177
+ def _populate_lib(lib: Path, venv_lib: Path, base_lib: Path) -> None:
178
+ """Fill ``Contents/lib`` with links to the venv's dirs and the base libpython.
179
+
180
+ The copied interpreter may be a stub that dyld-loads
181
+ ``@executable_path/../lib/libpython3.X.dylib``, so this directory must hold
182
+ that library as well as the venv's ``python3.X`` (see module docstring).
183
+ Links that stopped matching (a Python version bump, a reinstall) are pruned.
184
+ """
185
+ if lib.is_symlink(): # the earlier layout: lib -> <venv>/lib; no libpython
186
+ lib.unlink()
187
+ lib.mkdir(exist_ok=True)
188
+ targets: dict[str, Path] = {}
189
+ if venv_lib.is_dir():
190
+ targets = {p.name: p for p in sorted(venv_lib.iterdir())}
191
+ for dylib in sorted(base_lib.glob("libpython*")):
192
+ targets.setdefault(dylib.name, dylib)
193
+ for name, target in targets.items():
194
+ _symlink_if_changed(target, lib / name)
195
+ for entry in lib.iterdir():
196
+ if entry.name not in targets and entry.is_symlink():
197
+ entry.unlink()
198
+
199
+
200
+ def build(
201
+ backup_dir: Path,
202
+ *,
203
+ executable: Path | None = None,
204
+ prefix: Path | None = None,
205
+ applications: Path = APPLICATIONS_DIR,
206
+ ) -> Path:
207
+ """Create or refresh the bundle; returns the bundled interpreter's path.
208
+
209
+ ``executable`` is the real interpreter to copy (default: the base
210
+ interpreter behind this process, through any venv symlink) and ``prefix``
211
+ the install whose ``lib`` holds claude-swap (default: ``sys.prefix``).
212
+ Idempotent: unchanged parts are left untouched.
213
+ """
214
+ src = Path(
215
+ executable or getattr(sys, "_base_executable", None) or sys.executable
216
+ ).resolve()
217
+ lib_target = Path(prefix or sys.prefix) / "lib"
218
+
219
+ contents = bundle_path(backup_dir, applications) / "Contents"
220
+ macos = contents / "MacOS"
221
+ macos.mkdir(parents=True, exist_ok=True)
222
+
223
+ # The interpreter itself is the bundle's executable: menu bar managers
224
+ # recognise a (re)launched app by "its executable is CFBundleExecutable"
225
+ # before they re-adopt its icon, and a launcher script in between would
226
+ # hide the match.
227
+ _write_if_changed(
228
+ contents / "Info.plist",
229
+ plistlib.dumps(
230
+ {
231
+ "CFBundleIdentifier": BUNDLE_ID,
232
+ "CFBundleName": BUNDLE_NAME,
233
+ "CFBundleExecutable": "python",
234
+ "CFBundlePackageType": "APPL",
235
+ "LSUIElement": True,
236
+ }
237
+ ),
238
+ )
239
+ # `home` is the directory holding the base interpreter; CPython derives
240
+ # the stdlib location from it exactly as it does for a normal venv.
241
+ _write_if_changed(
242
+ contents / "pyvenv.cfg",
243
+ f"home = {src.parent}\ninclude-system-site-packages = false\n".encode(),
244
+ )
245
+ _populate_lib(contents / "lib", lib_target, src.parent.parent / "lib")
246
+ python = macos / "python"
247
+ _copy_if_changed(src, python)
248
+ return python
249
+
250
+
251
+ def interpreter_error(python: Path) -> str | None:
252
+ """Run the bundled interpreter once; the error if it cannot start, else None.
253
+
254
+ Importing claude_swap exercises both failure modes of a bad bundle: a stub
255
+ interpreter whose libpython is missing aborts in dyld, and a broken ``lib``
256
+ wiring leaves site-packages unreachable.
257
+ """
258
+ try:
259
+ proc = subprocess.run(
260
+ [str(python), "-c", "import claude_swap"],
261
+ capture_output=True,
262
+ text=True,
263
+ timeout=30,
264
+ )
265
+ except (OSError, subprocess.SubprocessError) as exc:
266
+ return str(exc)
267
+ if proc.returncode != 0:
268
+ lines = (proc.stderr or proc.stdout).strip().splitlines()
269
+ return lines[-1] if lines else f"exit status {proc.returncode}"
270
+ return None
271
+
272
+
273
+ def reexec_reason(platform: str = sys.platform, environ=None) -> str | None:
274
+ """Why this process should NOT re-exec into the bundle; None when it should."""
275
+ environ = os.environ if environ is None else environ
276
+ if platform != "darwin":
277
+ return "not macOS"
278
+ if environ.get(OPT_OUT_ENV):
279
+ return f"{OPT_OUT_ENV} is set"
280
+ if getattr(sys, "_framework", ""):
281
+ # A framework build's bin/python is a stub that spawns Python.app from
282
+ # a path relative to itself; a copy of the stub finds nothing. The
283
+ # menu bar's framework_build_warning already covers these installs.
284
+ return "framework build of Python"
285
+ if in_bundle():
286
+ return "already in the bundle"
287
+ return None
288
+
289
+
290
+ def maybe_reexec(backup_dir: Path, argv: list[str] | None = None) -> str | None:
291
+ """Replace this process with the same command run from inside the bundle.
292
+
293
+ Returns only when staying put, with the reason; on success ``execv`` never
294
+ returns. A bundle that cannot be built, whose interpreter fails its startup
295
+ check, or that ``execv`` refuses falls back to the plain interpreter (the
296
+ menu bar still works, it just stays invisible to menu bar managers).
297
+ """
298
+ reason = reexec_reason()
299
+ if reason:
300
+ return reason
301
+ if bundle_dir(backup_dir) != APPLICATIONS_DIR:
302
+ warning(
303
+ f"{APPLICATIONS_DIR} is not writable, so the menu bar bundle lives "
304
+ f"in {backup_dir}; menu bar managers will hide its icon along with "
305
+ "anything else they hide.",
306
+ file=sys.stderr,
307
+ )
308
+ try:
309
+ python = build(backup_dir)
310
+ except OSError as exc:
311
+ return _stay_put(f"could not build {bundle_path(backup_dir)}: {exc}")
312
+ error = interpreter_error(python)
313
+ if error:
314
+ return _stay_put(f"the bundled interpreter cannot start: {error}")
315
+ args = sys.argv[1:] if argv is None else argv
316
+ try:
317
+ os.execv(str(python), [str(python), "-m", "claude_swap", *args])
318
+ except OSError as exc:
319
+ return _stay_put(f"could not exec {python}: {exc}")
320
+ return None # pragma: no cover - execv does not return
321
+
322
+
323
+ def _stay_put(reason: str) -> str:
324
+ """Warn that the plain interpreter keeps running, and hand back the reason."""
325
+ warning(
326
+ f"Menu bar managers will not see this icon ({reason}); "
327
+ "the menu bar itself works as before.",
328
+ file=sys.stderr,
329
+ )
330
+ return reason
@@ -0,0 +1,219 @@
1
+ """Terminal appearance detection and theme resolution.
2
+
3
+ Determines whether the terminal has a light or dark background by querying it
4
+ with OSC 11 (``ESC ] 11 ; ? BEL``) followed by DA1 (``ESC [ c``), reading
5
+ through the ordered DA1 reply, and classifying the preceding ``rgb:…`` reply by
6
+ perceived luminance. Cross-cutting: both the CLI printer and the TUI resolve
7
+ their theme through here.
8
+
9
+ The query MUST happen while this process owns the terminal in cooked mode —
10
+ before Textual's input driver starts — or the reply is reissued as keystrokes.
11
+ Everything fails safe to ``None`` (→ resolved ``dark``): a terminal that doesn't
12
+ answer, a pipe, Windows, or a parse failure never blocks indefinitely and never
13
+ errors.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import re
20
+ import select
21
+ import sys
22
+ import time
23
+
24
+ _QUERY = b"\x1b]11;?\x07" # OSC 11, BEL-terminated
25
+ _DA1_QUERY = b"\x1b[c" # ordered response boundary
26
+ # DA1 lets unsupported terminals return promptly; the cap mainly covers SSH
27
+ # latency or a non-conforming terminal that answers neither query.
28
+ _TIMEOUT_S = 1.0
29
+ _MAX_REPLY = 256
30
+ # The full `ESC ]11;` opener is required so interleaved or echoed input (e.g.
31
+ # a shell echoing back a pasted escape sequence) can't be misparsed as a
32
+ # background reply just because `]11;rgb:`/`]11;#` appears somewhere in the
33
+ # buffer without the ESC that actually starts an OSC sequence.
34
+ _RGB = re.compile(
35
+ rb"\x1b\]11;rgb:([0-9a-fA-F]+)/([0-9a-fA-F]+)/([0-9a-fA-F]+)"
36
+ rb"(?:\x07|\x1b\\)"
37
+ )
38
+ _HEX = re.compile(rb"\x1b\]11;#([0-9a-fA-F]{6})(?:\x07|\x1b\\)")
39
+ # A primary device-attributes reply is CSI ? Ps c. Requiring ``?`` and at
40
+ # least the private marker keeps an echoed DA1 query (CSI c) from looking
41
+ # complete; Ps itself may legally be empty.
42
+ _DA1_REPLY = re.compile(rb"(?:\x1b\[|\x9b)\?[0-9;:]*c")
43
+
44
+ # Cache: the terminal background can't change within a process, so query once.
45
+ _UNSET = object()
46
+ _cache: object | str | None = _UNSET
47
+
48
+
49
+ def _reset_cache() -> None:
50
+ """Test helper: forget any cached detection result."""
51
+ global _cache
52
+ _cache = _UNSET
53
+
54
+
55
+ def _parse_osc11(reply: bytes) -> tuple[float, float, float] | None:
56
+ """Parse an OSC 11 reply into (r, g, b) each normalised to 0..1."""
57
+ m = _RGB.search(reply)
58
+ if m:
59
+ return tuple(
60
+ int(h, 16) / (16 ** len(h) - 1) for h in m.groups()
61
+ ) # type: ignore[return-value]
62
+ m = _HEX.search(reply)
63
+ if m:
64
+ h = m.group(1).decode("ascii")
65
+ return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)) # type: ignore[return-value]
66
+ return None
67
+
68
+
69
+ def _classify(reply: bytes) -> str | None:
70
+ """Light/dark from an OSC 11 reply, or None if unparseable."""
71
+ rgb = _parse_osc11(reply)
72
+ if rgb is None:
73
+ return None
74
+ r, g, b = rgb
75
+ luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b # BT.709-weighted brightness on gamma-encoded channels (approx.)
76
+ return "light" if luminance > 0.5 else "dark"
77
+
78
+
79
+ def _query_terminal_background() -> bytes | None:
80
+ """Send OSC 11 + DA1 and read through the DA1 reply. None on any failure.
81
+
82
+ Isolated so tests can substitute a canned reply without a real tty.
83
+
84
+ Terminals process queries in order. DA1 is widely supported, so its reply
85
+ marks the point after any OSC 11 reply and prevents a slower colour reply
86
+ from being reissued as shell input after this process restores the tty.
87
+ The timeout remains a safety cap for high-latency or non-conforming
88
+ terminals.
89
+
90
+ ``TERM=dumb`` and the Linux console don't support this colour query.
91
+ Likewise, tmux and screen don't pass it through to the outer terminal by
92
+ default. Those environments short-circuit to ``None`` (resolving to
93
+ ``dark``) without probing. Fails safe either way.
94
+ """
95
+ if os.name == "nt":
96
+ return None
97
+ if os.environ.get("TERM") in ("dumb", "linux"):
98
+ return None
99
+ if os.environ.get("TMUX") or os.environ.get("STY"):
100
+ return None
101
+ try:
102
+ import termios
103
+ import tty
104
+ except ImportError:
105
+ return None
106
+ try:
107
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
108
+ return None
109
+ except (ValueError, OSError):
110
+ # isatty() can raise on a closed stream.
111
+ return None
112
+ try:
113
+ fd = sys.stdin.fileno()
114
+ old = termios.tcgetattr(fd)
115
+ except (termios.error, OSError):
116
+ return None
117
+ try:
118
+ # TCSANOW (not TCSADRAIN): draining first can block under terminal
119
+ # flow control, and there's no pending output to drain anyway.
120
+ tty.setcbreak(fd, termios.TCSANOW)
121
+ sys.stdout.write((_QUERY + _DA1_QUERY).decode("latin-1"))
122
+ sys.stdout.flush()
123
+ deadline = time.monotonic() + _TIMEOUT_S
124
+ buf = b""
125
+ while time.monotonic() < deadline and len(buf) < _MAX_REPLY:
126
+ remaining = deadline - time.monotonic()
127
+ ready, _, _ = select.select([fd], [], [], max(0.0, remaining))
128
+ if not ready:
129
+ break
130
+ chunk = os.read(fd, 32)
131
+ if not chunk:
132
+ break
133
+ buf += chunk
134
+ # Do not stop at the OSC reply: the DA1 response is the ordered
135
+ # boundary proving that no colour-query bytes are still in flight.
136
+ if _DA1_REPLY.search(buf) is not None:
137
+ break
138
+ return buf or None
139
+ except (termios.error, OSError, ValueError):
140
+ return None
141
+ finally:
142
+ try:
143
+ termios.tcsetattr(fd, termios.TCSANOW, old)
144
+ except (termios.error, OSError):
145
+ pass
146
+
147
+
148
+ def detect_terminal_background() -> str | None:
149
+ """'light' | 'dark' from the terminal background, or None if undetectable.
150
+
151
+ Cached per process. MUST be first called in cooked mode (before app.run()).
152
+ """
153
+ global _cache
154
+ if _cache is _UNSET:
155
+ reply = _query_terminal_background()
156
+ _cache = _classify(reply) if reply is not None else None
157
+ return _cache # type: ignore[return-value]
158
+
159
+
160
+ def resolve_theme(setting: str, detect=detect_terminal_background) -> str:
161
+ """Resolve a ui.theme setting to a concrete 'light'/'dark'.
162
+
163
+ 'dark'/'light' pass through without probing; 'auto' follows ``detect()``,
164
+ falling back to 'dark' when detection yields None.
165
+ """
166
+ if setting in ("dark", "light"):
167
+ return setting
168
+ return detect() or "dark"
169
+
170
+
171
+ def cli_should_probe(argv: list[str], *, colors_enabled: bool) -> bool:
172
+ """Whether the CLI should probe the terminal background before dispatch.
173
+
174
+ False when colors are off (nothing will render the theme anyway), when
175
+ the first token is ``run``, ``rc`` or ``remote-control`` (each execs a
176
+ child that takes over the terminal),
177
+ or when ``--json`` is present (the OSC query must never precede
178
+ machine-readable output on stdout).
179
+ """
180
+ if not colors_enabled:
181
+ return False
182
+ if argv and argv[0] in ("run", "rc", "remote-control"):
183
+ return False
184
+ if "--json" in argv:
185
+ return False
186
+ return True
187
+
188
+
189
+ def cli_theme(setting: str, *, detect=detect_terminal_background, colors: bool) -> str:
190
+ """Resolve a theme for a plain-CLI invocation: probe only when color will
191
+ actually be emitted; otherwise auto degrades to dark without a tty query."""
192
+ if setting == "auto" and not colors:
193
+ return "dark"
194
+ return resolve_theme(setting, detect=detect)
195
+
196
+
197
+ def drain_stdin() -> None:
198
+ """Discard any pending terminal input (e.g. a late OSC reply) so it isn't
199
+ reissued as keystrokes once Textual takes over. Best-effort; POSIX only.
200
+
201
+ A reply that arrives after the detection deadline and after this drain
202
+ can, in principle, still reach the running app as stray keystrokes —
203
+ inherent to any finite-timeout OSC probe, not fully closeable here.
204
+ """
205
+ if os.name == "nt":
206
+ return
207
+ try:
208
+ import termios
209
+ except ImportError:
210
+ return
211
+ try:
212
+ if not sys.stdin.isatty():
213
+ return
214
+ except (ValueError, OSError):
215
+ return
216
+ try:
217
+ termios.tcflush(sys.stdin.fileno(), termios.TCIFLUSH)
218
+ except (termios.error, OSError):
219
+ pass