| 1 | |
| 2 | """Launch the official guest CLI and export only its subscription status fields.""" |
| 3 | import runpy |
| 4 | from datetime import datetime |
| 5 | import hashlib |
| 6 | import json |
| 7 | import os |
| 8 | from pathlib import Path |
| 9 | import re |
| 10 | import shutil |
| 11 | import signal |
| 12 | import socket |
| 13 | import stat |
| 14 | import subprocess |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import time |
| 18 | |
| 19 | |
| 20 | if os.name == "nt": |
| 21 | platform_path = Path(__file__).with_name("windows_cli_platform.py") |
| 22 | if not platform_path.exists(): |
| 23 | platform_path = Path(__file__).parent.parent / "workbench/windows_cli_platform.py" |
| 24 | _platform = runpy.run_path(platform_path) |
| 25 | fcntl = _platform["FileLock"] |
| 26 | else: |
| 27 | import fcntl |
| 28 | |
| 29 | SHIM = "/usr/local/lib/cage-claude-bin" |
| 30 | OPEN = "/usr/local/libexec/cage-cli/bin/cage-open" if sys.platform == "darwin" else "/usr/local/bin/cage-open" |
| 31 | HELPER = "/usr/local/bin/cage-claude-account" |
| 32 | DEFAULT = "default" |
| 33 | |
| 34 | |
| 35 | def shared_root(): |
| 36 | return Path(os.environ["CAGE_CLI_SHARED_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/claude-shared" |
| 37 | |
| 38 | |
| 39 | class SharedResourceConflict(ValueError): |
| 40 | pass |
| 41 | |
| 42 | |
| 43 | def profile(account_id): |
| 44 | if account_id != DEFAULT and not re.fullmatch("[0-9a-f]{24}", account_id): |
| 45 | raise ValueError("invalid account ID") |
| 46 | root = Path(os.environ["CAGE_CLI_ACCOUNT_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/claude-accounts" |
| 47 | return root / account_id |
| 48 | |
| 49 | |
| 50 | def config_directory(base): |
| 51 | return Path.home() / ".claude" if base.name == DEFAULT else base / "config" |
| 52 | |
| 53 | |
| 54 | def cli_environment(base): |
| 55 | env = os.environ.copy() |
| 56 | |
| 57 | path = [p for p in env.get("PATH", os.defpath).split(os.pathsep) if p and p != SHIM] |
| 58 | env["PATH"] = os.pathsep.join([str(Path.home() / ".local/bin"), *path]) |
| 59 | if sys.platform == "darwin" and Path("/usr/local/libexec/cage-cli/bin/claude").is_file(): |
| 60 | env["PATH"] = "/usr/local/libexec/cage-cli/bin:/usr/local/bin:" + env["PATH"] |
| 61 | if base.name == DEFAULT: |
| 62 | |
| 63 | |
| 64 | |
| 65 | return env |
| 66 | env["CLAUDE_CONFIG_DIR"] = str(config_directory(base)) |
| 67 | for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", |
| 68 | "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", |
| 69 | "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_USE_GATEWAY"): |
| 70 | env.pop(name, None) |
| 71 | return env |
| 72 | |
| 73 | |
| 74 | def identity(binary, env, cwd, settings=(), timeout=10, pass_fds=()): |
| 75 | result = subprocess.run([binary, *settings, "auth", "status"], cwd=cwd, env=env, timeout=timeout, |
| 76 | stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, pass_fds=pass_fds) |
| 77 | |
| 78 | |
| 79 | data = json.loads(result.stdout) |
| 80 | reported_dir = data.get("configDirectory") |
| 81 | correct_dir = isinstance(reported_dir, str) and Path(reported_dir) == Path(env.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") |
| 82 | if result.returncode not in (0, 1) or not correct_dir: |
| 83 | raise ValueError("unexpected auth status") |
| 84 | ok = (result.returncode == 0 and data.get("loggedIn") is True and data.get("authMethod") == "claude.ai" |
| 85 | and data.get("apiProvider") == "firstParty") |
| 86 | if not ok: |
| 87 | return {"logged_in": False} |
| 88 | return {"logged_in": True, "email": data.get("email"), "organization": data.get("orgId") or data.get("orgName"), |
| 89 | "plan": data.get("subscriptionType")} |
| 90 | |
| 91 | |
| 92 | def subject(summary): |
| 93 | if not summary.get("logged_in") or not summary.get("email"): |
| 94 | return None |
| 95 | email = summary["email"].strip().lower() |
| 96 | organization = (summary.get("organization") or "").strip() |
| 97 | return hashlib.sha256(f"{email}\n{organization}".encode()).hexdigest() |
| 98 | |
| 99 | |
| 100 | def json_file(path): |
| 101 | try: |
| 102 | return json.loads(path.read_text()) |
| 103 | except FileNotFoundError: |
| 104 | return {} |
| 105 | |
| 106 | |
| 107 | def valid_window(data, now): |
| 108 | if not isinstance(data, dict): |
| 109 | return None |
| 110 | used, reset = data.get("used_percentage"), data.get("resets_at") |
| 111 | if type(used) not in (int, float) or not 0 <= used <= 100: |
| 112 | return None |
| 113 | if type(reset) != int or (reset != 0 and reset <= now): |
| 114 | return None |
| 115 | return {"used_percentage": used, "resets_at": reset} |
| 116 | |
| 117 | |
| 118 | def read_quota(base): |
| 119 | try: |
| 120 | stored = json_file(base / "quota.json") |
| 121 | except (ValueError, OSError): |
| 122 | return None |
| 123 | if not isinstance(stored, dict): |
| 124 | return None |
| 125 | digest = stored.get("identity", "") |
| 126 | seen = stored.get("observed_at") |
| 127 | now = int(time.time()) |
| 128 | if not isinstance(digest, str) or not re.fullmatch("[a-f0-9]{64}", digest) or type(seen) != int or not 0 < seen <= now: |
| 129 | return None |
| 130 | result = {} |
| 131 | for key in ("five_hour", "seven_day"): |
| 132 | window = valid_window(stored.get(key), now) |
| 133 | if window: |
| 134 | window_seen = stored[key].get("observed_at", seen) |
| 135 | if type(window_seen) == int and 0 < window_seen <= now: |
| 136 | result[key] = {**window, "observed_at": window_seen} |
| 137 | if result: |
| 138 | return {**result, "identity": digest, "observed_at": seen} |
| 139 | return None |
| 140 | |
| 141 | |
| 142 | def save_usage(base, data, expected, confirm_subject, query_started=None, deadline=None): |
| 143 | rate = data.get("rate_limits") |
| 144 | if not isinstance(rate, dict): |
| 145 | return |
| 146 | now = int(time.time()) |
| 147 | with (base / "quota.lock").open("a") as lock: |
| 148 | if deadline is None: |
| 149 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 150 | else: |
| 151 | while True: |
| 152 | try: |
| 153 | fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 154 | break |
| 155 | except BlockingIOError: |
| 156 | if time.monotonic() >= deadline: |
| 157 | raise TimeoutError("usage cache busy") |
| 158 | time.sleep(.05) |
| 159 | path = base / "quota.json" |
| 160 | previous = read_quota(base) or {} |
| 161 | if previous.get("identity") != expected: |
| 162 | previous = {} |
| 163 | windows = {} |
| 164 | changed = False |
| 165 | for key in ("five_hour", "seven_day"): |
| 166 | old = previous.get(key) |
| 167 | new = valid_window(rate.get(key), now) |
| 168 | |
| 169 | |
| 170 | redraw = query_started is None and old and new and all(old[field] == new[field] for field in ("resets_at", "used_percentage")) |
| 171 | older = old and new and (0 < new["resets_at"] < old["resets_at"] or |
| 172 | (query_started is None and old["resets_at"] == new["resets_at"] and new["used_percentage"] < old["used_percentage"])) |
| 173 | if old and (not new or redraw or older or (query_started is not None and old["observed_at"] > query_started)): |
| 174 | windows[key] = old |
| 175 | elif new: |
| 176 | windows[key] = {**new, "observed_at": now} |
| 177 | changed = True |
| 178 | |
| 179 | |
| 180 | if changed and expected and confirm_subject() == expected: |
| 181 | windows["observed_at"] = now |
| 182 | windows["identity"] = expected |
| 183 | with tempfile.NamedTemporaryFile(mode="w", dir=base, delete=False) as tmp: |
| 184 | json.dump(windows, tmp, separators=(",", ":")) |
| 185 | os.replace(tmp.name, path) |
| 186 | |
| 187 | |
| 188 | def reported_window(percent, stamp, now): |
| 189 | reset = 0 |
| 190 | if stamp is not None: |
| 191 | try: |
| 192 | dt = datetime.fromisoformat(stamp.replace("Z", "+00:00")) |
| 193 | if dt.tzinfo is None: |
| 194 | return None |
| 195 | reset = int(dt.timestamp()) |
| 196 | except (AttributeError, ValueError, OverflowError): |
| 197 | return None |
| 198 | return valid_window({"used_percentage": percent, "resets_at": reset}, now) |
| 199 | |
| 200 | |
| 201 | def usage_windows(raw, now): |
| 202 | |
| 203 | |
| 204 | report = None |
| 205 | for line in raw.splitlines(): |
| 206 | message = json.loads(line) |
| 207 | if message.get("type") in ("user", "assistant"): |
| 208 | raise ValueError("unexpected conversation during usage query") |
| 209 | if message.get("type") == "result" and (message.get("is_error") or message.get("num_turns") != 0): |
| 210 | raise ValueError("unexpected inference result") |
| 211 | if message.get("type") == "control_response": |
| 212 | response = message.get("response") or {} |
| 213 | if response.get("request_id") == "quota": |
| 214 | if report is not None or response.get("subtype") != "success": |
| 215 | raise ValueError("failed usage response") |
| 216 | report = response.get("response") |
| 217 | if not isinstance(report, dict) or type(report.get("rate_limits_available")) is not bool: |
| 218 | raise ValueError("missing structured usage response") |
| 219 | session = report.get("session") |
| 220 | if not isinstance(session, dict) or session.get("total_cost_usd") != 0 or session.get("model_usage"): |
| 221 | raise ValueError("unexpected model use") |
| 222 | if not report["rate_limits_available"]: |
| 223 | return False, {} |
| 224 | rate = report.get("rate_limits") or {} |
| 225 | windows = {} |
| 226 | for key in ("five_hour", "seven_day"): |
| 227 | meter = rate.get(key) |
| 228 | if isinstance(meter, dict): |
| 229 | reading = reported_window(meter.get("utilization"), meter.get("resets_at"), now) |
| 230 | if reading: |
| 231 | windows[key] = reading |
| 232 | |
| 233 | |
| 234 | candidates = {"session": "five_hour", "weekly_all": "seven_day"} |
| 235 | rows = {} |
| 236 | ambiguous = set() |
| 237 | for row in rate.get("limits") or (): |
| 238 | if not isinstance(row, dict): |
| 239 | continue |
| 240 | key = candidates.get(row.get("kind")) |
| 241 | if not key or key in windows or key in ambiguous: |
| 242 | continue |
| 243 | reading = reported_window(row.get("percent"), row.get("resets_at"), now) |
| 244 | if reading and key in rows and rows[key] != reading: |
| 245 | ambiguous.add(key) |
| 246 | del rows[key] |
| 247 | elif reading: |
| 248 | rows[key] = reading |
| 249 | return True, {**rows, **windows} |
| 250 | |
| 251 | |
| 252 | def changed_identity(): |
| 253 | return {"logged_in": False, "usage_status": "identity_changed", "usage_checked_at": int(time.time())} |
| 254 | |
| 255 | |
| 256 | def invoke_usage(binary, env, cwd, options, timeout): |
| 257 | command = [binary, *options, "-p", "--input-format", "stream-json", "--verbose", "--output-format", "stream-json", |
| 258 | "--no-session-persistence", "--strict-mcp-config", "--tools", ""] |
| 259 | request = {"type": "control_request", "request_id": "quota", "request": {"subtype": "get_usage", "skip_behaviors": True}} |
| 260 | result = subprocess.run(command, cwd=cwd, env=env, timeout=timeout, input=(json.dumps(request) + "\n").encode(), |
| 261 | stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) |
| 262 | if result.returncode != 0 or len(result.stdout) > (2 << 20): |
| 263 | raise ValueError("usage command failed") |
| 264 | return usage_windows(result.stdout, int(time.time())) |
| 265 | |
| 266 | |
| 267 | def query_usage(binary, env, base, expected): |
| 268 | if not expected or not re.fullmatch("[a-f0-9]{64}", expected): |
| 269 | raise ValueError("missing expected account") |
| 270 | deadline = time.monotonic() + 12 |
| 271 | started = int(time.time()) |
| 272 | status = "error" |
| 273 | summary = {} |
| 274 | options = ["--setting-sources", "user", "--settings", '{"disableAllHooks":true}'] |
| 275 | with tempfile.TemporaryDirectory(prefix="cage-claude-usage-") as cwd: |
| 276 | try: |
| 277 | summary = identity(binary, env, cwd, options, timeout=4) |
| 278 | if subject(summary) != expected: |
| 279 | return changed_identity() |
| 280 | |
| 281 | timeout = min(8, deadline - time.monotonic() - 2) |
| 282 | try: |
| 283 | available, windows = invoke_usage(binary, env, cwd, options, max(.1, timeout)) |
| 284 | except (OSError, ValueError, TypeError, AttributeError, subprocess.SubprocessError): |
| 285 | windows = None |
| 286 | after = identity(binary, env, cwd, options, timeout=max(.1, min(4, deadline - time.monotonic()))) |
| 287 | if subject(after) != expected: |
| 288 | return changed_identity() |
| 289 | summary = after |
| 290 | if windows: |
| 291 | base.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 292 | save_usage(base, {"rate_limits": windows}, expected, lambda: expected, started, deadline) |
| 293 | if windows is not None: |
| 294 | status = {0: "unavailable", 1: "partial", 2: "reported"}[len(windows)] if available else "not_applicable" |
| 295 | except (OSError, ValueError, TypeError, AttributeError, subprocess.SubprocessError): |
| 296 | |
| 297 | |
| 298 | pass |
| 299 | if subject(summary) == expected: |
| 300 | previous = read_quota(base) |
| 301 | if previous and previous["identity"] == expected: |
| 302 | summary["quota"] = previous |
| 303 | if status == "unavailable": |
| 304 | status = "cached" |
| 305 | summary.update(usage_status=status, usage_checked_at=int(time.time())) |
| 306 | return summary |
| 307 | |
| 308 | |
| 309 | def has_status_line(base): |
| 310 | |
| 311 | |
| 312 | if os.name == "nt": |
| 313 | policy = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "ClaudeCode" |
| 314 | elif sys.platform == "darwin": |
| 315 | policy = Path("/Library/Application Support/ClaudeCode") |
| 316 | else: |
| 317 | policy = Path("/etc/claude-code") |
| 318 | paths = [config_directory(base) / "settings.json", policy / "managed-settings.json"] |
| 319 | if os.name != "nt": |
| 320 | paths.extend((policy / "managed-settings.d").glob("*.json")) |
| 321 | for folder in (Path.cwd(), *Path.cwd().parents): |
| 322 | paths += [folder / ".claude/settings.json", folder / ".claude/settings.local.json"] |
| 323 | for path in paths: |
| 324 | try: |
| 325 | settings = json_file(path) |
| 326 | if not isinstance(settings, dict) or "statusLine" in settings or settings.get("allowManagedHooksOnly"): |
| 327 | return True |
| 328 | except (OSError, ValueError): |
| 329 | return True |
| 330 | return False |
| 331 | |
| 332 | |
| 333 | def settings_flags(args): |
| 334 | flags = [] |
| 335 | iterator = iter(args) |
| 336 | for arg in iterator: |
| 337 | if arg == "--": |
| 338 | break |
| 339 | key, equals, _ = arg.partition("=") |
| 340 | if key in ("--settings", "--setting-sources"): |
| 341 | flags.append(arg) |
| 342 | if not equals: |
| 343 | value = next(iterator, None) |
| 344 | if value is None: |
| 345 | raise ValueError("missing CLI setting") |
| 346 | flags.append(value) |
| 347 | return flags |
| 348 | |
| 349 | |
| 350 | def shared_profile_resources(base): |
| 351 | """Share local customizations; credentials, synced skills and history stay private.""" |
| 352 | config = config_directory(base) |
| 353 | common = Path.home() / ".claude" |
| 354 | common.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 355 | if config == common: |
| 356 | return |
| 357 | lock_dir = shared_root() |
| 358 | lock_dir.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 359 | with (lock_dir / "resources.lock").open("a") as lock: |
| 360 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 361 | conflict = "账号的技能或指令与共用资料同名冲突,请先核对 ~/.claude 中的对应文件;原文件已保留" |
| 362 | def check(local, shared): |
| 363 | if (local.is_symlink() or os.name == "nt" and local.is_junction()): |
| 364 | if local.resolve() != shared.resolve(): |
| 365 | raise SharedResourceConflict(conflict) |
| 366 | elif local.exists() and shared.exists(): |
| 367 | if local.is_dir() and shared.is_dir(): |
| 368 | for child in local.iterdir(): |
| 369 | check(child, shared / child.name) |
| 370 | elif not (local.is_file() and shared.is_file() and local.read_bytes() == shared.read_bytes()): |
| 371 | raise SharedResourceConflict(conflict) |
| 372 | def merge(local, shared): |
| 373 | if (local.is_symlink() or os.name == "nt" and local.is_junction()): |
| 374 | if local.resolve() == shared.resolve(): |
| 375 | return |
| 376 | raise SharedResourceConflict(conflict) |
| 377 | if local.exists(): |
| 378 | if local.is_dir() and shared.is_dir(): |
| 379 | for child in list(local.iterdir()): |
| 380 | merge(child, shared / child.name) |
| 381 | if child.is_symlink(): |
| 382 | child.unlink() |
| 383 | local.rmdir() |
| 384 | elif not shared.exists(): |
| 385 | shared.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 386 | local.rename(shared) |
| 387 | elif local.is_file() and shared.is_file() and local.read_bytes() == shared.read_bytes(): |
| 388 | |
| 389 | backup = lock_dir / "backups" / base.name / local.relative_to(config) |
| 390 | backup.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 391 | if not backup.exists(): |
| 392 | shutil.copy2(local, backup) |
| 393 | local.unlink() |
| 394 | else: |
| 395 | |
| 396 | raise SharedResourceConflict(conflict) |
| 397 | if not shared.exists(): |
| 398 | if local.name in ("CLAUDE.md", "AGENTS.md"): |
| 399 | shared.touch(mode=0o600) |
| 400 | else: |
| 401 | shared.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 402 | local.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 403 | if os.name == "nt": |
| 404 | _platform["resource_link"](local, shared) |
| 405 | else: |
| 406 | local.symlink_to(shared, target_is_directory=shared.is_dir()) |
| 407 | |
| 408 | |
| 409 | local, shared = config / "skills", common / "skills" |
| 410 | local.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 411 | shared.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 412 | names = {p.name for folder in (local, shared) for p in folder.iterdir()} - {"synced"} |
| 413 | resources = [(config / name, common / name) for name in |
| 414 | ("commands", "agents", "rules", "agent-memory", "CLAUDE.md", "AGENTS.md")] |
| 415 | resources += [(local / name, shared / name) for name in sorted(names)] |
| 416 | |
| 417 | |
| 418 | for source, destination in resources: |
| 419 | check(source, destination) |
| 420 | for source, destination in resources: |
| 421 | if source.exists() and not source.is_symlink(): |
| 422 | backup = lock_dir / "backups" / base.name / source.relative_to(config) |
| 423 | if backup.exists(): |
| 424 | backup = backup.with_name(backup.name + "-" + str(time.time_ns())) |
| 425 | backup.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 426 | if source.is_dir(): |
| 427 | shutil.copytree(source, backup, symlinks=True) |
| 428 | else: |
| 429 | shutil.copy2(source, backup) |
| 430 | merge(source, destination) |
| 431 | |
| 432 | |
| 433 | def shared_launch_arguments(base, args, settings_fd=None): |
| 434 | """Apply a stable project memory location without sharing auth/settings files.""" |
| 435 | lock_dir = shared_root() |
| 436 | lock_dir.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 437 | with (lock_dir / "resources.lock").open("a") as lock: |
| 438 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 439 | return shared_launch_arguments_locked(base, args, settings_fd) |
| 440 | |
| 441 | |
| 442 | def shared_launch_arguments_locked(base, args, settings_fd): |
| 443 | directory = Path.cwd().resolve() |
| 444 | try: |
| 445 | git = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], |
| 446 | cwd=directory, capture_output=True, text=True, timeout=2) |
| 447 | if git.returncode == 0: |
| 448 | common_git = Path(git.stdout.strip()) |
| 449 | if common_git.name == ".git": |
| 450 | directory = common_git.parent.resolve() |
| 451 | except (OSError, subprocess.SubprocessError): |
| 452 | pass |
| 453 | key = re.sub(r"[^a-zA-Z0-9]", "-", str(directory)) |
| 454 | if len(key) > 180: |
| 455 | key = key[:140] + "-" + hashlib.sha256(str(directory).encode()).hexdigest()[:32] |
| 456 | memory = Path.home() / ".claude/projects" / key / "memory" |
| 457 | own_memory = config_directory(base) / "projects" / key / "memory" |
| 458 | memory.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 459 | |
| 460 | |
| 461 | if own_memory != memory and own_memory.exists() and not (own_memory.is_symlink() or os.name == "nt" and own_memory.is_junction()): |
| 462 | sources = [source for source in own_memory.rglob("*") if source.is_file()] |
| 463 | for source in sources: |
| 464 | destination = memory / source.relative_to(own_memory) |
| 465 | if destination.exists() and (not destination.is_file() or destination.read_bytes() != source.read_bytes()): |
| 466 | raise SharedResourceConflict("账号的项目记忆与共用记忆冲突,原记忆已保留,请先核对") |
| 467 | for source in sources: |
| 468 | if source.is_file(): |
| 469 | destination = memory / source.relative_to(own_memory) |
| 470 | if destination.exists() and destination.read_bytes() != source.read_bytes(): |
| 471 | raise SharedResourceConflict("账号的项目记忆与共用记忆冲突,原记忆已保留,请先核对") |
| 472 | destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 473 | if not destination.exists(): |
| 474 | shutil.copy2(source, destination) |
| 475 | backup = shared_root() / "backups" / base.name / "projects" / key / "memory" |
| 476 | backup.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 477 | if backup.exists(): |
| 478 | backup = backup.with_name(backup.name + "-" + str(time.time_ns())) |
| 479 | own_memory.rename(backup) |
| 480 | if os.name == "nt": |
| 481 | _platform["resource_link"](own_memory, memory) |
| 482 | else: |
| 483 | own_memory.symlink_to(memory, target_is_directory=True) |
| 484 | settings = {"autoMemoryDirectory": str(memory)} |
| 485 | |
| 486 | |
| 487 | common_settings = json_file(Path.home() / ".claude/settings.json") |
| 488 | shared_keys = {"model", "permissions", "hooks", "statusLine", "attribution", "language", |
| 489 | "effortLevel", "alwaysThinkingEnabled", "includeCoAuthoredBy", "respectGitignore", |
| 490 | "spinnerTipsEnabled", "outputStyle", "disableAllHooks", "includeGitInstructions", |
| 491 | "theme", "skipDangerousModePermissionPrompt", "tui", "autoMemoryEnabled"} |
| 492 | if isinstance(common_settings, dict): |
| 493 | settings.update({key: value for key, value in common_settings.items() if key in shared_keys}) |
| 494 | |
| 495 | paths = [Path.home() / ".claude/settings.json", config_directory(base) / "settings.json"] |
| 496 | for parent in reversed((Path.cwd(), *Path.cwd().parents)): |
| 497 | paths += [parent / ".claude/settings.json", parent / ".claude/settings.local.json"] |
| 498 | for path in paths: |
| 499 | stored = json_file(path) |
| 500 | if path != Path.home() / ".claude/settings.json" and isinstance(stored, dict): |
| 501 | |
| 502 | |
| 503 | for key in shared_keys & stored.keys(): |
| 504 | settings.pop(key, None) |
| 505 | if isinstance(stored, dict) and "autoMemoryDirectory" in stored: |
| 506 | settings["autoMemoryDirectory"] = stored["autoMemoryDirectory"] |
| 507 | result, iterator = [], iter(args) |
| 508 | for arg in iterator: |
| 509 | if arg == "--": |
| 510 | result += [arg, *iterator] |
| 511 | break |
| 512 | if arg == "--settings" or arg.startswith("--settings="): |
| 513 | value = next(iterator) if arg == "--settings" else arg.split("=", 1)[1] |
| 514 | supplied = json.loads(value) if value.lstrip().startswith("{") else json.loads(Path(value).read_text()) |
| 515 | settings.update(supplied) |
| 516 | else: |
| 517 | result.append(arg) |
| 518 | data = json.dumps(settings, separators=(",", ":")).encode() |
| 519 | if settings_fd is not None: |
| 520 | |
| 521 | |
| 522 | with os.fdopen(os.dup(settings_fd), "r+b") as snapshot: |
| 523 | snapshot.seek(0) |
| 524 | snapshot.truncate() |
| 525 | snapshot.write(data) |
| 526 | snapshot.flush() |
| 527 | snapshot.seek(0) |
| 528 | return ["--settings", "/dev/fd/" + str(settings_fd), *result] |
| 529 | folder = base / "launch-settings" |
| 530 | folder.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 531 | path = folder / (hashlib.sha256(data).hexdigest() + ".json") |
| 532 | if not path.exists(): |
| 533 | with tempfile.NamedTemporaryFile(dir=folder, delete=False) as stream: |
| 534 | stream.write(data) |
| 535 | temporary = stream.name |
| 536 | os.replace(temporary, path) |
| 537 | return ["--settings", str(path), *result] |
| 538 | |
| 539 | |
| 540 | def main(args, *, mobile_settings_fd=None, verify_mobile=None): |
| 541 | mode, account_id, *rest = args |
| 542 | if mode == "quotas": |
| 543 | result = {} |
| 544 | for candidate in [account_id, *rest]: |
| 545 | quota = read_quota(profile(candidate)) |
| 546 | if quota: |
| 547 | result[candidate] = quota |
| 548 | print(json.dumps(result)) |
| 549 | return 0 |
| 550 | base = profile(account_id) |
| 551 | if account_id == DEFAULT and mode == "login": |
| 552 | raise ValueError("new logins require a private profile") |
| 553 | if mode in ("usage", "snapshot") and account_id == DEFAULT and not config_directory(base).is_dir(): |
| 554 | print(json.dumps(changed_identity() if mode == "usage" else {"logged_in": False})) |
| 555 | return 0 |
| 556 | original_umask = os.umask(0o077) |
| 557 | if account_id != DEFAULT: |
| 558 | config_directory(base).mkdir(mode=0o700, parents=True, exist_ok=True) |
| 559 | elif mode == "statusline": |
| 560 | base.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 561 | env = cli_environment(base) |
| 562 | if account_id == DEFAULT: |
| 563 | directory = env.get("CLAUDE_CONFIG_DIR") or str(config_directory(base)) |
| 564 | endpoint = env.get("ANTHROPIC_BASE_URL", "").rstrip("/") |
| 565 | if Path(directory) != config_directory(base) or endpoint not in ("", "https://api.anthropic.com"): |
| 566 | if mode in ("snapshot", "usage"): |
| 567 | print(json.dumps(changed_identity() if mode == "usage" else {"logged_in": False})) |
| 568 | return 0 |
| 569 | raise ValueError("not the default subscription configuration") |
| 570 | binary = os.environ.get("CAGE_CLI_BINARY") if os.name == "nt" else shutil.which("claude", path=env["PATH"]) |
| 571 | if not binary: |
| 572 | raise ValueError("Claude is not installed") |
| 573 | if mode == "usage": |
| 574 | if len(rest) != 1: |
| 575 | raise ValueError("usage requires an expected account") |
| 576 | print(json.dumps(query_usage(binary, env, base, rest[0]))) |
| 577 | return 0 |
| 578 | expected = env.get("CAGE_CLAUDE_SUBJECT") |
| 579 | if mode == "statusline": |
| 580 | raw = sys.stdin.buffer.read((1 << 20) + 1) |
| 581 | if len(raw) <= 1 << 20: |
| 582 | save_usage(base, json.loads(raw), expected, lambda: subject(identity(binary, env, Path.cwd()))) |
| 583 | print("Cage · Claude") |
| 584 | return 0 |
| 585 | if mode == "snapshot": |
| 586 | summary = identity(binary, env, Path.home()) |
| 587 | quota = read_quota(base) |
| 588 | if quota and quota["identity"] == subject(summary): |
| 589 | summary["quota"] = quota |
| 590 | print(json.dumps(summary)) |
| 591 | return 0 |
| 592 | if mode == "login": |
| 593 | env.update(CAGE_CLAUDE_LOGIN=account_id) |
| 594 | if os.name != "nt": |
| 595 | env["BROWSER"] = OPEN |
| 596 | |
| 597 | |
| 598 | def interrupted(_signum, _frame): |
| 599 | raise KeyboardInterrupt() |
| 600 | if hasattr(signal, "SIGHUP"): |
| 601 | signal.signal(signal.SIGHUP, interrupted) |
| 602 | signal.signal(signal.SIGTERM, interrupted) |
| 603 | try: |
| 604 | (base / "quota.json").unlink(missing_ok=True) |
| 605 | return subprocess.call([binary, "auth", "login", *([] if os.name == "nt" else ["--claudeai"])], cwd=Path.home(), env=env) |
| 606 | finally: |
| 607 | if os.name != "nt": |
| 608 | subprocess.run([OPEN, "--finish-login"], env=env, timeout=8, check=False, |
| 609 | stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 610 | if mode == "run": |
| 611 | shared_profile_resources(base) |
| 612 | if not settings_flags(rest) and not has_status_line(base): |
| 613 | rest = ["--settings", json.dumps({"statusLine": {"type": "command", "command": f"{HELPER} statusline {account_id}"}}), *rest] |
| 614 | rest = shared_launch_arguments(base, rest, mobile_settings_fd) |
| 615 | |
| 616 | |
| 617 | options = settings_flags(rest) |
| 618 | |
| 619 | |
| 620 | pass_fds = () if mobile_settings_fd is None else (mobile_settings_fd,) |
| 621 | reading = identity(binary, env, Path.cwd(), options, pass_fds=pass_fds) if expected else None |
| 622 | if not expected or subject(reading) != expected: |
| 623 | print("此项目未使用所选 Claude 订阅。请检查项目配置和账号登录状态。", file=sys.stderr) |
| 624 | return 1 |
| 625 | if mobile_settings_fd is not None: |
| 626 | verify_mobile(reading) |
| 627 | os.lseek(mobile_settings_fd, 0, os.SEEK_SET) |
| 628 | |
| 629 | |
| 630 | os.umask(original_umask) |
| 631 | if os.name == "nt": |
| 632 | return subprocess.call([binary, *rest], env=env) |
| 633 | os.execve(binary, [binary, *rest], env) |
| 634 | raise ValueError("unknown operation") |
| 635 | |
| 636 | |
| 637 | def macos_open(args): |
| 638 | login = os.environ.get("CAGE_CLAUDE_LOGIN", "") |
| 639 | if len(args) != 1 or not re.fullmatch("[0-9a-f]{24}", login): |
| 640 | return 2 |
| 641 | finish = args[0] == "--finish-login" |
| 642 | data = {"action": "login-finish" if finish else "login-open", "login": login} |
| 643 | if not finish: |
| 644 | from urllib.parse import urlsplit |
| 645 | url = urlsplit(args[0]) |
| 646 | if len(args[0]) > 8192 or url.scheme != "https" or url.username or url.password or url.hostname not in ( |
| 647 | "claude.ai", "claude.com", "console.anthropic.com", "platform.claude.com", "platform.anthropic.com"): |
| 648 | return 2 |
| 649 | data["url"] = args[0] |
| 650 | address = Path.home() / "Library/Application Support/Cage/Login/open.sock" |
| 651 | owner = address.lstat() |
| 652 | if not stat.S_ISSOCK(owner.st_mode) or owner.st_uid != os.getuid() or owner.st_mode & 0o077: |
| 653 | return 1 |
| 654 | with socket.socket(socket.AF_UNIX) as client: |
| 655 | client.settimeout(12) |
| 656 | client.connect(str(address)) |
| 657 | client.sendall(json.dumps(data).encode()) |
| 658 | client.shutdown(socket.SHUT_WR) |
| 659 | with client.makefile("rb") as reply: |
| 660 | return 0 if reply.read(4) == b"OK" else 1 |
| 661 | |
| 662 | |
| 663 | if __name__ == "__main__": |
| 664 | try: |
| 665 | sys.exit(macos_open(sys.argv[1:]) if sys.platform == "darwin" and Path(sys.argv[0]).name == "cage-open" else main(sys.argv[1:])) |
| 666 | except KeyboardInterrupt: |
| 667 | sys.exit(130) |
| 668 | except SharedResourceConflict as error: |
| 669 | print(str(error), file=sys.stderr) |
| 670 | sys.exit(1) |
| 671 | except (OSError, ValueError, subprocess.SubprocessError, TypeError): |
| 672 | |
| 673 | print("无法读取 Claude 订阅状态或启动官方 CLI,请检查环境组件与登录状态。", file=sys.stderr) |
| 674 | sys.exit(1) |