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/signin.py ADDED
@@ -0,0 +1,238 @@
1
+ """Sign in to an account through Claude Code, in a scratch profile.
2
+
3
+ ``cswap login`` adds or renews an account without touching the login Claude
4
+ Code is using. cswap does not speak OAuth for this: it runs the installed
5
+ ``claude auth login`` with ``CLAUDE_CONFIG_DIR`` pointing at a scratch
6
+ directory, the person finishes the sign-in in Claude Code's own prompt, and
7
+ this module reads back what Claude Code stored there and removes the
8
+ directory. Which slot the login belongs in is the switcher's decision
9
+ (``ClaudeAccountSwitcher.login_account``).
10
+
11
+ What the scratch directory does and does not isolate, read from the Claude
12
+ Code 2.1.332 binary:
13
+
14
+ - The config file (``<dir>/.claude.json``), the plaintext credential file
15
+ (``<dir>/.credentials.json``) and, on macOS, the Keychain item
16
+ (``Claude Code-credentials-<hash of the directory>``) follow
17
+ ``CLAUDE_CONFIG_DIR``. Session mode relies on the same thing.
18
+ - ``CLAUDE_SECURESTORAGE_CONFIG_DIR``, when defined, replaces the directory
19
+ for the credential store alone, and Claude Code exports it to the shells it
20
+ starts. Left in place it would send the new login to the live store, so it
21
+ is removed from the child's environment.
22
+ - The sign-in's logout step deletes a credential Claude Code created in the
23
+ Anthropic profile store (``ANTHROPIC_CONFIG_DIR``, else
24
+ ``$XDG_CONFIG_HOME/anthropic``, else ``~/.config/anthropic``), which the
25
+ config directory does not move. That variable is pointed into the scratch
26
+ directory.
27
+ - ``claude auth login`` does not revoke the login it replaces; ``claude auth
28
+ logout`` and ``/logout`` do. Cleanup therefore deletes the directory and its
29
+ Keychain item and never logs out, which would revoke the login just read.
30
+ - With ``CLAUDE_CODE_OAUTH_REFRESH_TOKEN`` set, ``claude auth login`` spends
31
+ that token instead of opening the browser. It is removed, together with the
32
+ variables that bypass account sign-in altogether.
33
+ - On Windows, ``CLAUDE_CODE_FORCE_WINDOWS_CREDMAN=1`` stores the login in the
34
+ Credential Manager instead of ``.credentials.json``, which is where it is
35
+ read back from. It is removed; the cached feature flag that turns the same
36
+ storage on lives in the config file, and a new directory has none.
37
+
38
+ ``claude auth login`` prints a link, opens the browser and accepts the code
39
+ pasted back, so the child inherits the terminal. It runs from inside the
40
+ scratch directory so that no project settings apply. Its exit status is not
41
+ proof of a stored login: the credential is read back, and a missing one is an
42
+ error.
43
+
44
+ The browser is not opened unless the caller asks for it. A browser that
45
+ already holds a claude.ai session completes the sign-in as that account
46
+ without asking, and ``--email`` does not change which account that is
47
+ (observed with Claude Code 2.1.332 and Safari, 2026-11-29), so opening it
48
+ unasked returns the wrong account whenever another one was wanted. The person
49
+ opens the printed link where the right account can sign in, a private window
50
+ for instance, and pastes back the code the page shows. Claude Code 2.1.332
51
+ starts the browser with the ``browser`` setting, else ``$BROWSER``, else
52
+ ``open``, and reads ``BROWSER=true`` as there being no browser; that value is
53
+ what keeps it from opening one. Only the macOS build was read for this.
54
+
55
+ One sign-in runs at a time. The scratch directory has a fixed path, which
56
+ fixes the name of its Keychain item, so a run that died half-way is cleaned
57
+ up by the next one. A sign-in does not start until both are gone: the
58
+ read-back takes the Keychain item before the credential file, so an item
59
+ left by an earlier sign-in could be returned as this one's login.
60
+
61
+ This module must not import ``switcher``.
62
+ """
63
+
64
+ from __future__ import annotations
65
+
66
+ import json
67
+ import os
68
+ import shutil
69
+ import subprocess
70
+ from dataclasses import dataclass
71
+ from pathlib import Path
72
+
73
+ from claude_swap import oauth
74
+ from claude_swap.exceptions import SignInError
75
+ from claude_swap.locking import FileLock
76
+ from claude_swap.session import (
77
+ AUTH_OVERRIDE_ENV_VARS,
78
+ delete_macos_keychain_entry,
79
+ read_config_dir_credentials,
80
+ )
81
+
82
+ SCRATCH_DIR_NAME = "signin"
83
+
84
+ # Removed from the child's environment on top of AUTH_OVERRIDE_ENV_VARS; the
85
+ # module docstring says why for each.
86
+ _SIGN_IN_ENV_DROPPED = (
87
+ "CLAUDE_SECURESTORAGE_CONFIG_DIR",
88
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
89
+ "CLAUDE_CODE_OAUTH_SCOPES",
90
+ "CLAUDE_CODE_FORCE_WINDOWS_CREDMAN",
91
+ )
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class SignIn:
96
+ """What Claude Code stored for one completed sign-in."""
97
+
98
+ email: str
99
+ organization_uuid: str
100
+ organization_name: str
101
+ account_uuid: str
102
+ #: The credential JSON exactly as Claude Code wrote it.
103
+ credentials: str
104
+ #: ``{"oauthAccount": ...}`` as JSON: the part of ``.claude.json`` a slot
105
+ #: keeps and a switch splices back.
106
+ config: str
107
+
108
+
109
+ def scratch_dir(backup_dir: Path) -> Path:
110
+ """The directory a sign-in runs in. It exists only while one is running."""
111
+ return backup_dir / SCRATCH_DIR_NAME
112
+
113
+
114
+ def sign_in_env(scratch: Path, open_browser: bool = False) -> dict[str, str]:
115
+ """The environment ``claude auth login`` gets for a scratch sign-in.
116
+
117
+ With ``open_browser`` the caller's own ``BROWSER``, if any, is left to
118
+ choose what opens the link.
119
+ """
120
+ dropped = set(AUTH_OVERRIDE_ENV_VARS) | set(_SIGN_IN_ENV_DROPPED)
121
+ env = {k: v for k, v in os.environ.items() if k not in dropped}
122
+ env["CLAUDE_CONFIG_DIR"] = str(scratch)
123
+ env["ANTHROPIC_CONFIG_DIR"] = str(scratch / "anthropic")
124
+ if not open_browser:
125
+ env["BROWSER"] = "true"
126
+ return env
127
+
128
+
129
+ def sign_in_command(claude_bin: str, email: str | None, sso: bool) -> list[str]:
130
+ """``claude auth login`` with the account hint and SSO flag passed on.
131
+
132
+ ``--email`` only pre-fills the address on the sign-in page; the account
133
+ that comes back is whatever the browser signs in.
134
+ """
135
+ command = [claude_bin, "auth", "login"]
136
+ if email:
137
+ command += ["--email", email]
138
+ if sso:
139
+ command.append("--sso")
140
+ return command
141
+
142
+
143
+ def run(
144
+ backup_dir: Path,
145
+ *,
146
+ email: str | None = None,
147
+ sso: bool = False,
148
+ open_browser: bool = False,
149
+ ) -> SignIn | None:
150
+ """Run one sign-in and return what it stored; ``None`` when cancelled.
151
+
152
+ ``open_browser`` lets Claude Code open the sign-in link itself. Without
153
+ it the person opens the printed link.
154
+
155
+ Raises:
156
+ SignInError: Claude Code is missing, another sign-in is running, the
157
+ sign-in failed, or it left no usable login behind.
158
+ """
159
+ claude_bin = shutil.which("claude")
160
+ if not claude_bin:
161
+ raise SignInError(
162
+ "'claude' was not found on PATH. Install Claude Code first."
163
+ )
164
+ lock = FileLock(backup_dir / ".signin.lock")
165
+ if not lock.acquire(timeout=0):
166
+ raise SignInError(
167
+ "Another cswap login is in progress. Finish or cancel it first."
168
+ )
169
+ scratch = scratch_dir(backup_dir)
170
+ try:
171
+ if not _remove_scratch(scratch):
172
+ raise SignInError(
173
+ "Could not clear what an earlier sign-in left behind: the "
174
+ f"directory {scratch} or, on macOS, its Keychain item. A "
175
+ "locked or busy Keychain is the usual cause. Retry, and "
176
+ "remove the directory if it is still there."
177
+ )
178
+ scratch.mkdir(mode=0o700, parents=True)
179
+ try:
180
+ returncode = subprocess.run(
181
+ sign_in_command(claude_bin, email, sso),
182
+ env=sign_in_env(scratch, open_browser),
183
+ cwd=scratch,
184
+ ).returncode
185
+ except KeyboardInterrupt:
186
+ return None
187
+ if returncode != 0:
188
+ raise SignInError(
189
+ f"Claude Code's sign-in did not complete (exit {returncode}). "
190
+ "Nothing was changed."
191
+ )
192
+ return _read_sign_in(scratch)
193
+ finally:
194
+ _remove_scratch(scratch)
195
+ lock.release()
196
+
197
+
198
+ def _read_sign_in(scratch: Path) -> SignIn:
199
+ """The identity and credential Claude Code left in the scratch directory."""
200
+ try:
201
+ config = json.loads((scratch / ".claude.json").read_text(encoding="utf-8"))
202
+ except (OSError, ValueError):
203
+ config = None
204
+ account = config.get("oauthAccount") if isinstance(config, dict) else None
205
+ email = account.get("emailAddress") if isinstance(account, dict) else None
206
+ if not email:
207
+ raise SignInError(
208
+ "Claude Code finished the sign-in without recording an account. "
209
+ "Nothing was changed."
210
+ )
211
+ # The exact string exported as CLAUDE_CONFIG_DIR: the Keychain item's name
212
+ # is a hash of it.
213
+ credentials = read_config_dir_credentials(str(scratch), strict_keychain=True)
214
+ tokens = oauth.extract_oauth_data(credentials) if credentials else None
215
+ if not tokens or not tokens.get("accessToken") or not tokens.get("refreshToken"):
216
+ raise SignInError(
217
+ f"Claude Code finished the sign-in for {email} but stored no "
218
+ "subscription login (a Console sign-in stores an API key instead). "
219
+ "Nothing was changed."
220
+ )
221
+ return SignIn(
222
+ email=email,
223
+ organization_uuid=account.get("organizationUuid") or "",
224
+ organization_name=account.get("organizationName") or "",
225
+ account_uuid=account.get("accountUuid") or "",
226
+ credentials=credentials,
227
+ config=json.dumps({"oauthAccount": account}),
228
+ )
229
+
230
+
231
+ def _remove_scratch(scratch: Path) -> bool:
232
+ """Delete the scratch directory and its Keychain item, if either exists.
233
+
234
+ ``False`` when one of them may still be there.
235
+ """
236
+ item_gone = delete_macos_keychain_entry(scratch)
237
+ shutil.rmtree(scratch, ignore_errors=True)
238
+ return item_gone and not scratch.exists()
@@ -0,0 +1,121 @@
1
+ """Snapshot source — the supported read path for dashboards and GUI shells.
2
+
3
+ Pacing is store-governed: the usage store's persisted poll plans plus its
4
+ freshness/backoff/claim gates (decided atomically in ``UsageStore.reserve``)
5
+ cap every surface at the same per-account cadence, so a dashboard repainting
6
+ every few seconds and a one-shot ``cswap list`` produce identical network
7
+ behavior. This class therefore just runs the same on-demand pass as ``cswap
8
+ list`` (``fetch=None``) each take — the store decides which accounts, if
9
+ any, may actually be fetched — and offers ``store_only`` for shells that
10
+ host an auto engine (which already collects on its own schedule).
11
+
12
+ ``take()`` is blocking (file locks, keychain subprocesses, network): call it
13
+ from a background thread, never a UI event loop.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import threading
20
+ from dataclasses import replace
21
+
22
+ from claude_swap.json_output import USAGE_TOKEN_EXPIRED
23
+ from claude_swap.models import AccountSnapshot, AccountsSnapshot
24
+ from claude_swap.switcher import ClaudeAccountSwitcher
25
+ from claude_swap.usage_store import UsageEntry
26
+
27
+ _logger = logging.getLogger("claude-swap")
28
+
29
+
30
+ class SnapshotSource:
31
+ """Takes one coherent snapshot per call; the store paces the network.
32
+
33
+ ``full=True`` (the user's explicit refresh) is accepted for API
34
+ stability but is no faster than a normal pass: even an explicit refresh
35
+ is capped by the store's serve TTL and poll plans. ``store_only=True``
36
+ reads the store without any network eligibility.
37
+ """
38
+
39
+ def __init__(self, switcher: ClaudeAccountSwitcher) -> None:
40
+ self.switcher = switcher
41
+ self._last: AccountsSnapshot | None = None
42
+ self._lock = threading.Lock()
43
+ self._plans_lock = threading.Lock()
44
+
45
+ def take(
46
+ self, *, full: bool = False, store_only: bool = False
47
+ ) -> AccountsSnapshot:
48
+ """Blocking snapshot pass; call from a thread worker."""
49
+ fetch: set[str] | None = set() if store_only else None
50
+ snap = self.switcher.accounts_snapshot(fetch=fetch)
51
+ with self._lock:
52
+ snap = self._reconcile(snap)
53
+ self._last = snap
54
+ return snap
55
+
56
+ def refresh_plans(self) -> None:
57
+ """Refresh due subscription plans; blocking, so call it from a worker.
58
+
59
+ The counterpart of ``take(store_only=True)``, which never reaches the
60
+ network: a shell whose snapshots are store-only calls this to keep its
61
+ plan labels current. Overlapping calls collapse into the running one.
62
+ Display-only, so a failure is logged and goes no further.
63
+ """
64
+ if not self._plans_lock.acquire(blocking=False):
65
+ return
66
+ try:
67
+ self.switcher.refresh_subscription_plans()
68
+ except Exception:
69
+ _logger.debug("plan refresh failed", exc_info=True)
70
+ finally:
71
+ self._plans_lock.release()
72
+
73
+ def _reconcile(self, snap: AccountsSnapshot) -> AccountsSnapshot:
74
+ if self._last is None:
75
+ return snap
76
+ previous = {acc.number: acc for acc in self._last.accounts}
77
+ accounts = tuple(
78
+ self._reconcile_account(acc, previous.get(acc.number), snap.taken_at)
79
+ for acc in snap.accounts
80
+ )
81
+ return replace(snap, accounts=accounts)
82
+
83
+ def _reconcile_account(
84
+ self,
85
+ acc: AccountSnapshot,
86
+ prev: AccountSnapshot | None,
87
+ taken_at: float,
88
+ ) -> AccountSnapshot:
89
+ if prev is None or account_identity(acc) != account_identity(prev):
90
+ return acc
91
+
92
+ prev_fetched = prev.usage.fetched_at
93
+ fetched = acc.usage.fetched_at
94
+ if prev_fetched is not None and (fetched is None or fetched < prev_fetched):
95
+ return replace(acc, usage=_with_current_age(prev.usage, taken_at))
96
+ if acc.usage.sentinel is not None:
97
+ return acc
98
+
99
+ if (
100
+ prev.usage.sentinel == USAGE_TOKEN_EXPIRED
101
+ and fetched == prev_fetched
102
+ ):
103
+ return replace(acc, usage=replace(acc.usage, sentinel=USAGE_TOKEN_EXPIRED))
104
+ return acc
105
+
106
+
107
+ def account_identity(acc: AccountSnapshot) -> tuple[str, str, str]:
108
+ """The identity discriminator for a slot across snapshots.
109
+
110
+ The single definition of "same account": snapshot reconciliation here and
111
+ the TUI's snapshot merge must agree, or an identity change (e.g. a slot
112
+ re-used by another login) is detected by one and missed by the other.
113
+ """
114
+ return (acc.email, acc.org_uuid, acc.kind)
115
+
116
+
117
+ def _with_current_age(usage: UsageEntry, taken_at: float) -> UsageEntry:
118
+ fetched = usage.fetched_at
119
+ if fetched is None:
120
+ return usage
121
+ return replace(usage, age_s=max(0.0, taken_at - fetched))
claude_swap/spawn.py ADDED
@@ -0,0 +1,135 @@
1
+ """Run short-lived helpers (``ps``, ``security``, ``claude``) without ``fork()``.
2
+
3
+ Once the kernel has sent a process a critical memory-pressure or process-limit
4
+ note, libmalloc loads MallocStackLogging.framework and from then on runs that
5
+ framework's fork hook in every child the process forks. With stack logging off,
6
+ the hook prints
7
+
8
+ MallocStackLogging: can't turn off malloc stack logging because it was not enabled.
9
+
10
+ to the stderr the child inherited, before the exec, so the line lands on the
11
+ terminal or across the TUI and past any ``capture_output`` (issue #517). The
12
+ hook stays for the life of the process. ``subprocess`` on macOS forks for every
13
+ call unless the executable carries a directory component and ``close_fds`` is
14
+ False (Darwin has no ``posix_spawn`` closefrom), which is why every polling
15
+ spawn added a line once the hook was armed.
16
+
17
+ :func:`run` takes the ``posix_spawn`` path only when the descriptors present
18
+ at call time make it match the fork path. ``close_fds=True`` closes every
19
+ descriptor above 2 in the child, while ``posix_spawn`` only drops those marked
20
+ close-on-exec; Python marks its own that way (PEP 446), a C library or the
21
+ launching process need not. So the switch happens only when no inheritable
22
+ descriptor above 2 exists when the call is made. Every other call shape, a
23
+ descriptor state that cannot be told, and every other platform run
24
+ ``subprocess.run`` unchanged. A directory-qualified executable is never looked
25
+ up on PATH, so ``/usr/bin/security`` stays pinned; a bare name is searched on
26
+ the PATH the child would get, as ``subprocess`` does, and made absolute,
27
+ because a relative hit would send CPython back to ``fork``.
28
+
29
+ The descriptor check is a snapshot, not the fork path's guarantee: a
30
+ descriptor another thread makes inheritable between the check and the launch
31
+ reaches the child, where ``close_fds=True`` would have closed it. Closing that
32
+ window needs Darwin's ``POSIX_SPAWN_CLOEXEC_DEFAULT``, which ``os.posix_spawn``
33
+ does not expose, and a native launcher is not worth a cosmetic bug. The
34
+ limitation is accepted on these grounds: Python creates descriptors
35
+ non-inheritable, no cswap code makes one inheritable, any that already exist
36
+ send the call down the fork path, and what a child could pick up is a copy it
37
+ holds only until it exits, whether that child is ``ps``, ``security`` or a
38
+ ``claude auth status`` run.
39
+ """
40
+
41
+ import logging
42
+ import os
43
+ import shutil
44
+ import subprocess
45
+ import sys
46
+ from collections.abc import Sequence
47
+ from typing import Any
48
+
49
+ _logger = logging.getLogger("claude-swap")
50
+
51
+ _FD_DIR = "/dev/fd"
52
+
53
+ # Keyword arguments on which CPython forks regardless, or that change what
54
+ # ``cmd[0]`` means. Such calls are passed through untouched.
55
+ _PASS_THROUGH = frozenset(
56
+ {
57
+ "close_fds",
58
+ "cwd",
59
+ "executable",
60
+ "extra_groups",
61
+ "group",
62
+ "pass_fds",
63
+ "preexec_fn",
64
+ "process_group",
65
+ "shell",
66
+ "start_new_session",
67
+ "umask",
68
+ "user",
69
+ }
70
+ )
71
+
72
+ _fallback_logged = False
73
+
74
+
75
+ def run(cmd: Sequence[str], **kwargs: Any) -> subprocess.CompletedProcess[Any]:
76
+ """``subprocess.run`` for an argv list; see the module docstring."""
77
+ if _spawn_path_applies(cmd, kwargs):
78
+ executable = _resolve(cmd[0], kwargs.get("env"))
79
+ if executable is not None and not _inheritable_fds_above_stdio():
80
+ return subprocess.run([executable, *cmd[1:]], close_fds=False, **kwargs)
81
+ return subprocess.run(cmd, **kwargs)
82
+
83
+
84
+ def _spawn_path_applies(cmd: Any, kwargs: dict[str, Any]) -> bool:
85
+ return (
86
+ sys.platform == "darwin"
87
+ and isinstance(cmd, (list, tuple))
88
+ and bool(cmd)
89
+ and not (_PASS_THROUGH & kwargs.keys())
90
+ )
91
+
92
+
93
+ def _resolve(name: Any, env: Any = None) -> str | None:
94
+ """``name`` when directory-qualified, else its absolute PATH hit, else None.
95
+
96
+ The search path is the one the child would get: ``env``'s PATH, the
97
+ parent's when no env is given, and ``os.defpath`` for an env without one,
98
+ exactly as ``subprocess`` searches.
99
+ """
100
+ if not isinstance(name, str):
101
+ return None
102
+ if os.path.dirname(name):
103
+ return name
104
+ found = shutil.which(name, path=os.pathsep.join(os.get_exec_path(env)))
105
+ return None if found is None else os.path.abspath(found)
106
+
107
+
108
+ def _inheritable_fds_above_stdio() -> bool:
109
+ """Would a descriptor above 2 survive an exec? True too when that cannot be told."""
110
+ try:
111
+ names = os.listdir(_FD_DIR)
112
+ except OSError:
113
+ return True
114
+ for name in names:
115
+ try:
116
+ fd = int(name)
117
+ except ValueError:
118
+ continue
119
+ if fd <= 2:
120
+ continue
121
+ try:
122
+ inheritable = os.get_inheritable(fd)
123
+ except OSError: # closed between the listing and the check
124
+ continue
125
+ if inheritable:
126
+ _note_fallback(fd)
127
+ return True
128
+ return False
129
+
130
+
131
+ def _note_fallback(fd: int) -> None:
132
+ global _fallback_logged
133
+ if not _fallback_logged:
134
+ _fallback_logged = True
135
+ _logger.debug("spawn: descriptor %d is inheritable, keeping the fork path", fd)