cdx-manager 0.20.2 → 0.20.4

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.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <br clear="left"/>
6
6
 
7
- [![License](https://img.shields.io/badge/license-MIT-4C8BF5)](LICENSE) ![Version](https://img.shields.io/badge/version-v0.20.2-4C8BF5) ![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?logo=python&logoColor=white)
7
+ [![License](https://img.shields.io/badge/license-MIT-4C8BF5)](LICENSE) ![Version](https://img.shields.io/badge/version-v0.20.4-4C8BF5) ![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?logo=python&logoColor=white)
8
8
 
9
9
  **Stop guessing which AI account still has quota.** `cdx` tracks the rate-limit window of every Codex and Claude account you own, tells you which one is usable right now, and launches it with isolated auth — in one command.
10
10
 
@@ -500,6 +500,7 @@ cdx history --summary --from 2026-05-01 --to 2026-05-28
500
500
  | `cdx label <name> --clear [--json]` | Clear a session label |
501
501
  | `cdx login <name> [--json]` | Re-authenticate a session (logout + login) |
502
502
  | `cdx logout <name> [--json]` | Log out of a session |
503
+ | `cdx auth refresh <name\|all> [--json]` | Make a locked, non-generation Codex auth probe; reports `login_required` when interactive login is needed |
503
504
  | `cdx disable <name> [--json]` | Disable a session without deleting it; disabled sessions stay visible and cannot launch |
504
505
  | `cdx enable <name> [--json]` | Re-enable a disabled session |
505
506
  | `cdx config <name> [--json]` | Show persistent launch settings for a session |
@@ -1077,6 +1078,24 @@ Without `--yes`, an interactive confirmation is required. `cdx` sends an idempot
1077
1078
 
1078
1079
  ## Troubleshooting
1079
1080
 
1081
+ ### Codex credential refresh
1082
+
1083
+ `cdx auth refresh work` makes a provider-native, non-generation request for one
1084
+ managed Codex profile. It can refresh an expiring access token, but never starts
1085
+ an agent or submits a prompt. Use `cdx auth refresh all --json` when a scheduler
1086
+ needs a stable result; CDX never installs or enables that scheduler for you.
1087
+
1088
+ For example, a user-owned daily cron entry can run:
1089
+
1090
+ ```sh
1091
+ 0 6 * * * cdx auth refresh all --json
1092
+ ```
1093
+
1094
+ `locked` means an interactive session owns the profile refresh lock and was left
1095
+ untouched. `login_required` means the provider rejected the local refresh token;
1096
+ run the supplied `cdx login <name>` command interactively. Hosts keep independent
1097
+ rotating credentials, so copying an auth file is not ongoing credential sync.
1098
+
1080
1099
  - **`cdx <name>` fails with "not authenticated"** — run `cdx login <name>` first.
1081
1100
  - **One of two Codex accounts keeps asking for login** — run `cdx doctor --json` and inspect each Codex session's `codex_auth_file`, `codex_live_auth`, and `codex_stale_auth_logs` checks. If recent logs mention expired auth, repair only that isolated profile with `cdx login <name>`. Codex Business profiles can share the same `tokens.account_id`; `cdx doctor` reports `codex_shared_account_id` as a workspace-level clue, not proof that two profiles use the same user. Newly created sessions seed from the current global `~/.codex/auth.json` when one exists. For two separate Codex accounts, create or repair each session by running `cdx login <name>` for that session; `cdx login` does not log out first, so use `cdx logout <name>` explicitly only when you want to clear that isolated profile.
1082
1101
  - **`cdx` says no compatible Python 3 interpreter was found** — install Python 3 and make `py -3`, `python`, or `python3` available on PATH.
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.20.2
1
+ 0.20.4
@@ -0,0 +1,23 @@
1
+ # CDX Manager 0.20.3
2
+
3
+ ## Fixes
4
+
5
+ - Playwright, npm, pip, and uv now share one cache under `<CDX_HOME>/shared-cache`
6
+ instead of each isolated profile re-downloading its own copy, since profile
7
+ isolation redirects `HOME` per profile and those tools resolve their cache
8
+ dir from it.
9
+ - A session now prints a short line when it ends, cleanly or by Ctrl-C/a
10
+ forwarded signal: the session name, how long it ran, and this run's own
11
+ cost (or token count when the model isn't priced). A genuine provider
12
+ crash still gets no line.
13
+
14
+ ## Performance
15
+
16
+ - `cdx status --refresh` is faster: ~2.5s → ~2.2s on a 15-profile fleet,
17
+ verified to return identical data before and after. The Claude auth probe
18
+ now runs concurrently across sessions instead of one at a time, and no
19
+ longer spawns `claude auth status` twice per session (the probe and the
20
+ usage refresh were each independently running the exact same command).
21
+ - `cdx disk profiles --candidates` is faster too: ~5.1s → ~4.6s, same
22
+ before/after verification. Per-profile `du` calls now run concurrently
23
+ instead of one profile at a time.
@@ -0,0 +1,12 @@
1
+ # CDX Manager 0.20.4
2
+
3
+ ## Authentication
4
+
5
+ - Added `cdx auth refresh <name|all> [--json]`, a locked, no-generation Codex
6
+ authentication probe. It can refresh an active provider session when the
7
+ upstream CLI supports it, but never opens a browser, prompts for credentials,
8
+ or fabricates a token.
9
+ - The result distinguishes `valid`, `locked`, `login_required`, and `failed`
10
+ without exposing credential material.
11
+ - Documented manual use and an opt-in cron example. CDX never installs or
12
+ enables a scheduler on its own.
@@ -331,6 +331,28 @@
331
331
  "x86_64-pc-windows-msvc": "3513680e96fd5f669c2f2868b3a195899e48ed4d5f3dce080289f90648e60199",
332
332
  "x86_64-unknown-linux-musl": "ee86688537638671ceec1d805d23124d8511c11ab62836f14fa2545b418741d2"
333
333
  }
334
+ },
335
+ "v0.20.2": {
336
+ "github_tarball_sha256": "aeadbd180438862b7b1c0cdb31aece5c3ddbfbf2f20631733ffc48e1fd0a9fb7",
337
+ "github_zip_sha256": "79043ee3366f4e3006a51038d011416d510acd29e1cb35038519a3c4ff91571f",
338
+ "tray_assets": {
339
+ "aarch64-apple-darwin": "3da1c5b786fffe757e2d763cf36a5bf6dd9baf6bec06c3f4ba1d521a9919fbe9",
340
+ "aarch64-unknown-linux-musl": "8f9b0181b95d010ea3a13154d0a41fe150e32982847e43a3bba6c5674a8dea6e",
341
+ "x86_64-apple-darwin": "e35682db7adc4c6b4e2a9c112124411726f522423180c3a753bfb8aa7aa1008a",
342
+ "x86_64-pc-windows-msvc": "5ceff82ecd907fda949dfc27835112ad9e3597da78191a0ede4f7d9db82607a8",
343
+ "x86_64-unknown-linux-musl": "db70bb77f08fd954a7378561954d00ad3084b4ada99a4930aa8f021978439e65"
344
+ }
345
+ },
346
+ "v0.20.3": {
347
+ "github_tarball_sha256": "40990d89ea7130452a95b6cf6a3a63c804f36f08250cf3c325ce7fb63601f875",
348
+ "github_zip_sha256": "be334f6b23145a61d936d50d9609d6a9e6ba2e0749233aede0ed9ce8ff20df8e",
349
+ "tray_assets": {
350
+ "aarch64-apple-darwin": "5ec913f779c11df19aab1f09e8c68dcb4ec54d4a66b3dfbda43d73d67c597797",
351
+ "aarch64-unknown-linux-musl": "d59f41e9521175e22200b38638896d76c2d27f538e52a1f123e1dfdd6521cf4a",
352
+ "x86_64-apple-darwin": "1ec60ca652a18f3991b5d42c64cdf090eb19a658a88005d82642cb6ea9b6455e",
353
+ "x86_64-pc-windows-msvc": "1f9971c1aee7e92685370db1e6a4bcf37b6012fa7452fc14ca3dd545998af82e",
354
+ "x86_64-unknown-linux-musl": "2aabbc00b0fa3a2c8862cc1a5425a074fec99f072bf7b695d31e6e96b9b08c5d"
355
+ }
334
356
  }
335
357
  }
336
358
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cdx-manager",
3
- "version": "0.20.2",
3
+ "version": "0.20.4",
4
4
  "description": "Terminal session manager for Codex and Claude accounts.",
5
5
  "license": "MIT",
6
6
  "author": "Alexandre Agostini",
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cdx-manager"
7
- version = "0.20.2"
7
+ version = "0.20.4"
8
8
  description = "Terminal session manager for Codex and Claude accounts."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -30,8 +30,9 @@ def _is_stale(session, now=None, ttl_seconds=CLAUDE_REFRESH_TTL_SECONDS):
30
30
  return (now - updated_at.astimezone(now.tzinfo)).total_seconds() >= ttl_seconds
31
31
 
32
32
 
33
- def _refresh_claude_sessions(service, refresh_fn=None, target_names=None, force=False, ttl_seconds=CLAUDE_REFRESH_TTL_SECONDS):
33
+ def _refresh_claude_sessions(service, refresh_fn=None, target_names=None, force=False, ttl_seconds=CLAUDE_REFRESH_TTL_SECONDS, already_auth_refreshed=None):
34
34
  refresh_fn = refresh_fn or refresh_claude_session_status
35
+ already_auth_refreshed = already_auth_refreshed or set()
35
36
  target_names = set(target_names or [])
36
37
  sessions = service["list_sessions"]()
37
38
  claude_sessions = [
@@ -52,7 +53,17 @@ def _refresh_claude_sessions(service, refresh_fn=None, target_names=None, force=
52
53
 
53
54
  def fetch(s):
54
55
  try:
55
- usage = refresh_fn(s)
56
+ # The auth-probe phase right before this one already ran
57
+ # `claude auth status` for this session (see
58
+ # commands/status.py:_refresh_claude_auth_states), which is the
59
+ # exact side effect this refresh needs before reading
60
+ # credentials from disk. Skip re-running it - but only when
61
+ # refresh_fn is the real default, since a caller-injected
62
+ # refresh_fn (tests, mocks) may not accept auth_refresher.
63
+ if refresh_fn is refresh_claude_session_status and s["name"] in already_auth_refreshed:
64
+ usage = refresh_fn(s, auth_refresher=lambda _auth_home: None)
65
+ else:
66
+ usage = refresh_fn(s)
56
67
  if inspect.isawaitable(usage):
57
68
  raise CdxError("Claude refresh function returned an awaitable from a sync callable.")
58
69
  if usage:
package/src/cli.py CHANGED
@@ -13,6 +13,7 @@ from .cli_commands import (
13
13
  _directory_child_sizes,
14
14
  _directory_size_bytes,
15
15
  handle_add,
16
+ handle_auth,
16
17
  handle_can_resume,
17
18
  handle_clean,
18
19
  handle_config,
@@ -151,6 +152,7 @@ __all__ = [
151
152
 
152
153
 
153
154
  _COMMAND_HANDLERS = {
155
+ "auth": handle_auth,
154
156
  "add": handle_add,
155
157
  "cp": handle_copy,
156
158
  "clean": handle_clean,
@@ -236,6 +238,7 @@ def _print_help(use_color=False):
236
238
  f" {_style('cdx status <name> [--json] [--refresh|--cached] [--timeout SECONDS]', '36', use_color)}",
237
239
  f" {_style('cdx next [--json] [--refresh]', '36', use_color)}",
238
240
  f" {_style('cdx reset <name> [--yes] [--json]', '36', use_color)}",
241
+ f" {_style('cdx auth refresh <name|all> [--json]', '36', use_color)}",
239
242
  f" {_style('cdx select --provider PROVIDER [--min-reasoning-effort minimal|low|medium|high|xhigh] [--min-power minimal|low|medium|high|xhigh] [--require-ready] [--refresh] --json', '36', use_color)}",
240
243
  f" {_style('cdx run [session] --cwd PATH (--prompt-file PATH|--prompt TEXT|--prompt-file -) [--provider PROVIDER] [--model MODEL] [--kind assistant|code-review] [--reasoning-effort minimal|low|medium|high|xhigh] [--power minimal|low|medium|high|xhigh] [--permission review|default|auto|full|workspace-write|read-only|danger-full-access] [--timeout-seconds N] [--detach] [--refresh] --json', '36', use_color)}",
241
244
  f" {_style('cdx runs [--limit N] [--since 7d|today|DATE] --json', '36', use_color)}",
package/src/cli_args.py CHANGED
@@ -25,6 +25,7 @@ DOCTOR_USAGE = "Usage: cdx doctor [--severity OK|WARN|FAIL[,OK|WARN|FAIL...]] [-
25
25
  DISK_USAGE = "Usage: cdx disk [profiles] [--candidates] [--json]"
26
26
  REPAIR_USAGE = "Usage: cdx repair [--dry-run] [--force] [--json]"
27
27
  UPDATE_USAGE = "Usage: cdx update [all] [--check] [--yes] [--json] [--version TAG]"
28
+ AUTH_USAGE = "Usage: cdx auth refresh <name|all> [--json]"
28
29
  EXPORT_USAGE = "Usage: cdx export <file> [--include-auth] [--force] [--json] [--sessions name1,name2] [--passphrase-env VAR|--passphrase-stdin]"
29
30
  IMPORT_USAGE = "Usage: cdx import <file> [--force|--merge] [--allow-authless-force] [--json] [--sessions name1,name2] [--passphrase-env VAR|--passphrase-stdin]"
30
31
  CONTEXT_USAGE = "Usage: cdx context show|path|init|edit|clear|set|append [text...] [--json]"
@@ -909,6 +910,18 @@ def _parse_update_args(args):
909
910
  return parsed
910
911
 
911
912
 
913
+ def _parse_auth_args(args):
914
+ parsed = _parse_flag_args(args, {
915
+ "--json": {"key": "json", "type": "bool", "default": False},
916
+ }, AUTH_USAGE, positionals_key="values", max_positionals=2)
917
+ if len(parsed["values"]) != 2 or parsed["values"][0] != "refresh":
918
+ raise CdxError(AUTH_USAGE)
919
+ target = parsed["values"][1]
920
+ if not target.strip():
921
+ raise CdxError(AUTH_USAGE)
922
+ return {"target": target, "json": parsed["json"]}
923
+
924
+
912
925
  def _parse_export_args(args):
913
926
  parsed = _parse_flag_args(args, {
914
927
  "--include-auth": {"key": "include_auth", "type": "bool", "default": False},
@@ -41,6 +41,9 @@ from .cli_view import handle_view as handle_view # re-export for cli.py / tests
41
41
  from .commands.auth import ( # re-export for cli.py / tests
42
42
  _confirm_reset as _confirm_reset,
43
43
  )
44
+ from .commands.auth import (
45
+ handle_auth as handle_auth,
46
+ )
44
47
  from .commands.auth import (
45
48
  handle_login as handle_login,
46
49
  )
@@ -276,4 +279,3 @@ from .commands.tray import (
276
279
  handle_tray as handle_tray,
277
280
  )
278
281
 
279
-
@@ -3,12 +3,14 @@
3
3
  Split out of cli_commands.py. Moved verbatim; re-exported by cli_commands.
4
4
  """
5
5
 
6
+ import json
6
7
  import time
7
8
  import uuid
8
9
 
9
- from ..cli_args import _parse_flag_args, _parse_json_flag
10
+ from ..cli_args import _parse_auth_args, _parse_flag_args, _parse_json_flag
10
11
  from ..cli_helpers import (
11
12
  _bootstrap_claude_setup_token,
13
+ _json_failure,
12
14
  _json_success,
13
15
  _local_now_iso,
14
16
  _make_notify_progress,
@@ -16,7 +18,7 @@ from ..cli_helpers import (
16
18
  _write_json,
17
19
  )
18
20
  from ..cli_render import _success, _warn
19
- from ..codex_usage import consume_codex_rate_limit_reset_credit
21
+ from ..codex_usage import consume_codex_rate_limit_reset_credit, fetch_codex_rate_limit_diagnostic
20
22
  from ..config import PROVIDER_ANTIGRAVITY, PROVIDER_CLAUDE, PROVIDER_CODEX, PROVIDER_OLLAMA
21
23
  from ..errors import CdxError
22
24
  from ..notify import (
@@ -33,6 +35,61 @@ def _confirm_reset(name):
33
35
  answer = input(f"Consume one banked Codex reset for {name}? [y/N] ")
34
36
  return answer.strip().lower() in ("y", "yes")
35
37
 
38
+
39
+ def _refresh_needs_login(diagnostic):
40
+ """Classify known provider auth failures without returning provider text."""
41
+ text = json.dumps(diagnostic.get("response") or {}).lower()
42
+ return any(marker in text for marker in (
43
+ "not logged in", "unauthorized", "authentication token is expired",
44
+ "token_expired", "invalid_grant", "http 401",
45
+ ))
46
+
47
+
48
+ def _refresh_result(session, diagnostic):
49
+ if diagnostic.get("ok"):
50
+ return {"session": session["name"], "provider": PROVIDER_CODEX, "outcome": "valid"}
51
+ if diagnostic.get("reason") == "auth_locked":
52
+ return {"session": session["name"], "provider": PROVIDER_CODEX, "outcome": "locked"}
53
+ if _refresh_needs_login(diagnostic):
54
+ return {
55
+ "session": session["name"], "provider": PROVIDER_CODEX,
56
+ "outcome": "login_required", "login_command": f"cdx login {session['name']}",
57
+ }
58
+ return {"session": session["name"], "provider": PROVIDER_CODEX, "outcome": "failed"}
59
+
60
+
61
+ def handle_auth(rest, ctx):
62
+ parsed = _parse_auth_args(rest)
63
+ target = parsed["target"]
64
+ if target == "all":
65
+ sessions = [session for session in ctx["service"]["list_sessions"]()
66
+ if session["provider"] == PROVIDER_CODEX]
67
+ else:
68
+ session = ctx["service"]["get_session"](target)
69
+ if not session:
70
+ raise CdxError(f"Unknown session: {target}")
71
+ if session["provider"] != PROVIDER_CODEX:
72
+ raise CdxError("Authentication refresh is only available for Codex sessions.")
73
+ sessions = [session]
74
+ if not sessions:
75
+ raise CdxError("No managed Codex sessions to refresh.")
76
+
77
+ probe = ctx["options"].get("fetchCodexRateLimitDiagnostic") or fetch_codex_rate_limit_diagnostic
78
+ results = [_refresh_result(session, probe(session)) for session in sessions]
79
+ failures = [result for result in results if result["outcome"] in ("login_required", "failed")]
80
+ message = "Codex authentication probe completed" if not failures else "Codex authentication probe needs attention"
81
+ if parsed["json"]:
82
+ payload = (
83
+ _json_failure("auth.refresh", "auth_refresh_failed", message, results=results)
84
+ if failures else _json_success("auth.refresh", message, results=results)
85
+ )
86
+ _write_json(ctx, payload)
87
+ else:
88
+ for result in results:
89
+ suffix = f"; run {result['login_command']}" if result.get("login_command") else ""
90
+ ctx["out"](f"{result['session']}: {result['outcome']}{suffix}\n")
91
+ return 1 if failures else 0
92
+
36
93
  def handle_ready(rest, ctx):
37
94
  """`cdx ready`: schedule an OS notification for the next session to come back.
38
95
 
@@ -26,7 +26,14 @@ from ..config import PROVIDER_CODEX
26
26
  from ..context_store import install_context_for_session, write_context
27
27
  from ..errors import CdxError
28
28
  from ..interactive_usage import extract_interactive_usage, transcript_predates_run, usage_delta
29
- from ..provider_runtime import _conversation_id, _ensure_session_authentication, _get_auth_home, _run_interactive_provider_command
29
+ from ..provider_runtime import (
30
+ INTERRUPT_EXIT_CODES,
31
+ _conversation_id,
32
+ _ensure_session_authentication,
33
+ _get_auth_home,
34
+ _run_interactive_provider_command,
35
+ )
36
+ from ..run_usage import estimate_cost
30
37
 
31
38
 
32
39
  def _parse_launch_args(args):
@@ -268,6 +275,8 @@ def handle_launch(command, ctx, initial_prompt=None, resume=False, force_json=No
268
275
  run_info = _attach_interactive_usage(
269
276
  session, run_info, ctx["service"]["get_launch_history"](session["name"], limit=50)
270
277
  )
278
+ if not json_flag and error.exit_code in INTERRUPT_EXIT_CODES:
279
+ ctx["out"](f"{_goodbye_line(session, run_info, ctx['use_color'])}\n")
271
280
  if runtime_run_id:
272
281
  ctx["service"]["finish_session_runtime"](
273
282
  session["name"],
@@ -283,15 +292,18 @@ def handle_launch(command, ctx, initial_prompt=None, resume=False, force_json=No
283
292
  **run_info,
284
293
  })
285
294
  raise
295
+ success_run_info = _attach_interactive_usage(
296
+ session, run_info, ctx["service"]["get_launch_history"](session["name"], limit=50)
297
+ )
286
298
  ctx["service"]["record_launch_history"](session["name"], {
287
299
  "status": "success",
288
300
  "action": "resume" if resume else "launch",
289
301
  "cwd": cwd,
290
302
  "exit_code": 0,
291
- **_attach_interactive_usage(
292
- session, run_info, ctx["service"]["get_launch_history"](session["name"], limit=50)
293
- ),
303
+ **success_run_info,
294
304
  })
305
+ if not json_flag:
306
+ ctx["out"](f"{_goodbye_line(session, success_run_info, ctx['use_color'])}\n")
295
307
  if json_flag:
296
308
  extra = {"session": ctx["service"]["get_session"](session["name"]), "cwd": cwd}
297
309
  if capability:
@@ -300,6 +312,29 @@ def handle_launch(command, ctx, initial_prompt=None, resume=False, force_json=No
300
312
  return 0
301
313
 
302
314
 
315
+ def _goodbye_line(session, run_info, use_color):
316
+ """One line printed when a session ends: cleanly, or by SIGINT/SIGTERM/SIGHUP.
317
+
318
+ Not printed for a genuine provider crash (a nonzero exit that isn't one
319
+ of those signals) - that path already gets its own error message.
320
+
321
+ Local import: `commands.status` imports `handle_launch` from this module,
322
+ so importing it back at module scope would be circular.
323
+ """
324
+ from .status import _format_duration_ms, _format_token_count, _format_usd
325
+
326
+ parts = [f"Session {session['name']} ended", _format_duration_ms(run_info.get("duration_ms"))]
327
+ usage = run_info.get("usage")
328
+ cost = estimate_cost(usage, run_info.get("usage_model"))
329
+ if cost is not None:
330
+ parts.append(_format_usd(cost))
331
+ elif isinstance(usage, dict):
332
+ total_tokens = sum(v for v in usage.values() if isinstance(v, (int, float)))
333
+ if total_tokens:
334
+ parts.append(f"{_format_token_count(total_tokens)} tokens")
335
+ return _dim(" · ".join(parts), use_color)
336
+
337
+
303
338
  def _attach_interactive_usage(session, run_info, history=None):
304
339
  """Attach this run's own token usage without affecting launch outcome.
305
340
 
@@ -9,6 +9,7 @@ import shlex
9
9
  import shutil
10
10
  import subprocess
11
11
  import sys
12
+ import threading
12
13
  import time
13
14
  from datetime import datetime
14
15
 
@@ -83,20 +84,35 @@ def _directory_size_bytes(path, runner=None):
83
84
  return total
84
85
 
85
86
  def _directory_child_sizes(path, runner=None, progress=None):
86
- rows = []
87
87
  try:
88
88
  names = os.listdir(path)
89
89
  except OSError:
90
- return rows
90
+ return []
91
91
  children = [(name, os.path.join(path, name)) for name in names if os.path.isdir(os.path.join(path, name))]
92
- for index, (name, child_path) in enumerate(children, start=1):
92
+ # `du` per profile is I/O-bound (a subprocess spawn + directory walk), so
93
+ # one profile's measurement doesn't block the next - same reasoning as
94
+ # the auth-probe fix in commands/status.py. Progress is announced from
95
+ # the main thread, in listing order, before dispatch: du itself only
96
+ # runs concurrently, so the printed order still matches `len(children)`.
97
+ sizes = [None] * len(children)
98
+ threads = []
99
+
100
+ def measure(index, child_path):
101
+ sizes[index] = _directory_size_bytes(child_path, runner=runner)
102
+
103
+ for index, (name, child_path) in enumerate(children):
93
104
  if progress:
94
- progress("profile", name, index, len(children))
95
- rows.append({
96
- "name": name,
97
- "path": child_path,
98
- "bytes": _directory_size_bytes(child_path, runner=runner),
99
- })
105
+ progress("profile", name, index + 1, len(children))
106
+ t = threading.Thread(target=measure, args=(index, child_path), daemon=True)
107
+ threads.append(t)
108
+ t.start()
109
+ for t in threads:
110
+ t.join()
111
+
112
+ rows = [
113
+ {"name": name, "path": child_path, "bytes": sizes[index]}
114
+ for index, (name, child_path) in enumerate(children)
115
+ ]
100
116
  rows.sort(key=lambda row: row["bytes"], reverse=True)
101
117
  for row in rows:
102
118
  row["size"] = _format_bytes(row["bytes"])
@@ -170,11 +186,15 @@ def _collect_old_logs(profile_name, profile_path, days, now=None):
170
186
  )
171
187
 
172
188
  def _collect_profile_cleanup_candidates(base_dir, *, old_log_days=30, runner=None, now=None, progress=None):
173
- candidates = []
174
189
  profiles = list(_iter_profile_dirs(base_dir))
175
- for index, (profile_name, profile_path) in enumerate(profiles, start=1):
176
- if progress:
177
- progress("candidates", profile_name, index, len(profiles))
190
+ # Same reasoning as _directory_child_sizes: each profile's du calls and
191
+ # log walk are independent I/O, so profiles scan concurrently. Each
192
+ # thread only appends to its own slot in `per_profile`, never a shared list.
193
+ per_profile = [None] * len(profiles)
194
+ threads = []
195
+
196
+ def scan(index, profile_name, profile_path):
197
+ local = []
178
198
  tmp_dir = os.path.join(profile_path, ".tmp")
179
199
  tmp_targets = [
180
200
  ("tmp-marketplaces", os.path.join(tmp_dir, "marketplaces"), "temporary marketplace cache/staging"),
@@ -198,7 +218,7 @@ def _collect_profile_cleanup_candidates(base_dir, *, old_log_days=30, runner=Non
198
218
  mtime = datetime.fromtimestamp(os.path.getmtime(path)).isoformat()
199
219
  except OSError:
200
220
  mtime = None
201
- candidates.append(_candidate(
221
+ local.append(_candidate(
202
222
  profile_name,
203
223
  kind,
204
224
  path,
@@ -208,7 +228,19 @@ def _collect_profile_cleanup_candidates(base_dir, *, old_log_days=30, runner=Non
208
228
  ))
209
229
  old_logs = _collect_old_logs(profile_name, profile_path, old_log_days, now=now)
210
230
  if old_logs and old_logs["bytes"] > 0:
211
- candidates.append(old_logs)
231
+ local.append(old_logs)
232
+ per_profile[index] = local
233
+
234
+ for index, (profile_name, profile_path) in enumerate(profiles):
235
+ if progress:
236
+ progress("candidates", profile_name, index + 1, len(profiles))
237
+ t = threading.Thread(target=scan, args=(index, profile_name, profile_path), daemon=True)
238
+ threads.append(t)
239
+ t.start()
240
+ for t in threads:
241
+ t.join()
242
+
243
+ candidates = [item for local in per_profile for item in (local or [])]
212
244
  candidates.sort(key=lambda item: item["bytes"], reverse=True)
213
245
  return candidates
214
246
 
@@ -4,6 +4,7 @@ Split out of cli_commands.py. Moved verbatim; re-exported by cli_commands.
4
4
  """
5
5
 
6
6
  import os
7
+ import threading
7
8
  import time
8
9
  from datetime import datetime
9
10
 
@@ -40,7 +41,14 @@ from ..cli_render import _dim, _info, _pad_table, _style, _warn
40
41
  from ..commands.launch import handle_launch
41
42
  from ..config import PROVIDER_CLAUDE
42
43
  from ..errors import CdxError
43
- from ..provider_runtime import AUTH_PROBE_AUTHENTICATED, AUTH_PROBE_DEGRADED, _probe_provider_auth_status
44
+ from ..provider_runtime import (
45
+ AUTH_PROBE_AUTHENTICATED,
46
+ AUTH_PROBE_DEGRADED,
47
+ AUTH_PROBE_TIMEOUT_SECONDS,
48
+ _get_auth_home,
49
+ _has_local_claude_auth,
50
+ _probe_provider_auth_status,
51
+ )
44
52
  from ..run_usage import (
45
53
  USAGE_KEYS,
46
54
  estimate_cost,
@@ -692,6 +700,7 @@ def handle_status(rest, ctx):
692
700
  ctx.get("refresh_fn"),
693
701
  target_names=args if len(args) == 1 else None,
694
702
  force=parsed["refresh"],
703
+ already_auth_refreshed=auth_refresh.get("probed"),
695
704
  )
696
705
  )
697
706
  refresh_errors = [
@@ -746,40 +755,84 @@ def handle_status(rest, ctx):
746
755
 
747
756
  def _refresh_claude_auth_states(service, target_names=None, spawn_sync=None, env_override=None):
748
757
  target_names = set(target_names or [])
758
+ candidates = [
759
+ session for session in service["list_sessions"]()
760
+ if session["provider"] == PROVIDER_CLAUDE
761
+ and session.get("enabled", True) is not False
762
+ and (not target_names or session["name"] in target_names)
763
+ and (session.get("auth") or {}).get("status") in ("authenticated", "logged_out")
764
+ ]
765
+ if not candidates:
766
+ return {"updated": [], "errors": [], "probed": set()}
767
+
749
768
  errors = []
750
- updated = []
751
- for session in service["list_sessions"]():
752
- if session["provider"] != PROVIDER_CLAUDE:
753
- continue
754
- if session.get("enabled", True) is False:
755
- continue
756
- if target_names and session["name"] not in target_names:
757
- continue
758
- if (session.get("auth") or {}).get("status") not in ("authenticated", "logged_out"):
759
- continue
769
+ results = {}
770
+ threads = []
771
+ # Sessions without a local credentials file are the ones whose probe
772
+ # below actually spawns `claude auth status` (see _probe_provider_auth_status);
773
+ # the Claude usage refresh right after this call spawns that exact same
774
+ # command again to refresh its own on-disk copy before reading it. Track
775
+ # them so the caller can skip that second, redundant spawn.
776
+ probed = {
777
+ session["name"] for session in candidates
778
+ if not _has_local_claude_auth(_get_auth_home(session))
779
+ }
780
+
781
+ # The probe itself is the slow part (a subprocess spawn per session on a
782
+ # cache miss); it doesn't touch shared state, so it's safe to run
783
+ # concurrently, same as the sibling Claude usage refresh right after this
784
+ # call. Side effects (service["update_auth_state"]) still run serially,
785
+ # after every thread has joined.
786
+ def probe(session):
760
787
  try:
761
- auth_status = _probe_provider_auth_status(
788
+ results[session["name"]] = _probe_provider_auth_status(
762
789
  session,
763
790
  spawn_sync=spawn_sync,
764
791
  env_override=env_override,
765
792
  )
766
- if auth_status == AUTH_PROBE_DEGRADED:
767
- errors.append({
768
- "session": session["name"],
769
- "error": "Auth probe timed out; authentication status is degraded.",
770
- })
771
- continue
772
- now = _local_now_iso()
773
- service["update_auth_state"](session["name"], lambda auth, auth_status=auth_status, now=now: {
774
- **auth,
775
- "status": "authenticated" if auth_status == AUTH_PROBE_AUTHENTICATED else "logged_out",
776
- "lastCheckedAt": now,
777
- **({"lastAuthenticatedAt": now} if auth_status == AUTH_PROBE_AUTHENTICATED else {}),
778
- })
779
- updated.append(session["name"])
780
793
  except Exception as error:
781
794
  errors.append({"session": session["name"], "error": str(error)})
782
- return {"updated": updated, "errors": errors}
795
+
796
+ for session in candidates:
797
+ t = threading.Thread(target=probe, args=(session,), daemon=True)
798
+ threads.append(t)
799
+ t.start()
800
+ for t in threads:
801
+ t.join(timeout=AUTH_PROBE_TIMEOUT_SECONDS + 1)
802
+
803
+ results = dict(results)
804
+ errors = list(errors)
805
+
806
+ updated = []
807
+ now = _local_now_iso()
808
+ for session in candidates:
809
+ auth_status = results.get(session["name"])
810
+ if auth_status is None:
811
+ continue
812
+ if auth_status == AUTH_PROBE_DEGRADED:
813
+ errors.append({
814
+ "session": session["name"],
815
+ "error": "Auth probe timed out; authentication status is degraded.",
816
+ })
817
+ # A timed-out probe never finished running `claude auth status`,
818
+ # so its on-disk credentials aren't necessarily fresh - don't
819
+ # tell the caller this session's auth refresh can be skipped.
820
+ probed.discard(session["name"])
821
+ continue
822
+ service["update_auth_state"](session["name"], lambda auth, auth_status=auth_status, now=now: {
823
+ **auth,
824
+ "status": "authenticated" if auth_status == AUTH_PROBE_AUTHENTICATED else "logged_out",
825
+ "lastCheckedAt": now,
826
+ **({"lastAuthenticatedAt": now} if auth_status == AUTH_PROBE_AUTHENTICATED else {}),
827
+ })
828
+ updated.append(session["name"])
829
+ for session in candidates:
830
+ if session["name"] not in results:
831
+ # Probe raised/never completed for this session (exception or a
832
+ # join() that outran an unresponsive thread); same reasoning as
833
+ # the degraded case above.
834
+ probed.discard(session["name"])
835
+ return {"updated": updated, "errors": errors, "probed": probed}
783
836
 
784
837
  def _rows_by_session(rows):
785
838
  return {
@@ -20,6 +20,7 @@ from .config import (
20
20
  PROVIDER_CODEX,
21
21
  PROVIDER_OLLAMA,
22
22
  REASONING_EFFORT_VALUES,
23
+ get_cdx_home,
23
24
  split_extra_args,
24
25
  )
25
26
  from .errors import CdxError
@@ -158,6 +159,25 @@ def _home_env_overrides(auth_home):
158
159
  return overrides
159
160
 
160
161
 
162
+ def _shared_tool_cache_overrides(env):
163
+ """Pin tool download/build caches to one shared dir, outside any profile home.
164
+
165
+ Profile isolation redirects HOME to a per-profile auth_home (see
166
+ `_home_env_overrides`), and several dev tools resolve their cache dir from
167
+ HOME. Left alone, that means every profile re-downloads its own copy of
168
+ Playwright's browsers, npm/pip/uv packages, etc. `env` here is the ambient
169
+ env, before HOME gets swapped, so `get_cdx_home(env)` resolves the same
170
+ real per-user location regardless of which profile is launching.
171
+ """
172
+ shared_cache = os.path.join(get_cdx_home(env), "shared-cache")
173
+ return {
174
+ "PLAYWRIGHT_BROWSERS_PATH": os.path.join(shared_cache, "playwright"),
175
+ "NPM_CONFIG_CACHE": os.path.join(shared_cache, "npm"),
176
+ "PIP_CACHE_DIR": os.path.join(shared_cache, "pip"),
177
+ "UV_CACHE_DIR": os.path.join(shared_cache, "uv"),
178
+ }
179
+
180
+
161
181
  def _anthropic_profile_name():
162
182
  return "default"
163
183
 
@@ -562,6 +582,8 @@ def _build_launch_spec(session, cwd=None, env_override=None, initial_prompt=None
562
582
  cwd = cwd or os.getcwd()
563
583
  env_override = env_override or {}
564
584
  env = {**os.environ, **env_override}
585
+ for key, value in _shared_tool_cache_overrides(env).items():
586
+ env.setdefault(key, value)
565
587
  env.update(launch_notify_env(session, notifications_enabled(session)))
566
588
  initial_prompt = _with_launch_preferences(session, initial_prompt, env=env)
567
589
  _validate_initial_prompt(initial_prompt)
@@ -1190,11 +1212,17 @@ def _probe_provider_auth(session, spawn_sync=None, env_override=None, trust_loca
1190
1212
  ) == AUTH_PROBE_AUTHENTICATED
1191
1213
 
1192
1214
 
1215
+ _SIGNAL_EXIT_CODES = {signal.SIGINT: 130, signal.SIGTERM: 143}
1216
+ if hasattr(signal, "SIGHUP"):
1217
+ _SIGNAL_EXIT_CODES[signal.SIGHUP] = 129
1218
+
1219
+ # The exit codes above, on their own: what a caller checks to tell "the user
1220
+ # killed this session" apart from "the provider process crashed on its own".
1221
+ INTERRUPT_EXIT_CODES = frozenset(_SIGNAL_EXIT_CODES.values())
1222
+
1223
+
1193
1224
  def _signal_exit_code(sig):
1194
- mapping = {signal.SIGINT: 130, signal.SIGTERM: 143}
1195
- if hasattr(signal, "SIGHUP"):
1196
- mapping[signal.SIGHUP] = 129
1197
- return mapping.get(sig, 1)
1225
+ return _SIGNAL_EXIT_CODES.get(sig, 1)
1198
1226
 
1199
1227
 
1200
1228
  def _signal_name(sig):