| 1 | """Run the common Claude session protocol in the ordinary macOS guest account.""" |
| 2 | import importlib.util |
| 3 | import json |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import re |
| 7 | import sys |
| 8 | |
| 9 | |
| 10 | source = Path(__file__).resolve().with_name("cli_channel.py") |
| 11 | spec = importlib.util.spec_from_file_location("cli_channel", source) |
| 12 | cli_channel = importlib.util.module_from_spec(spec) |
| 13 | spec.loader.exec_module(cli_channel) |
| 14 | os.environ["PATH"] = "/usr/local/libexec/cage-cli/bin:/usr/local/bin:" + os.environ.get("PATH", os.defpath) |
| 15 | |
| 16 | |
| 17 | def macos_launch(request): |
| 18 | prefix = request["prefix"] |
| 19 | managed = (len(prefix) == 5 and prefix[0] == "env" and re.fullmatch(r"CAGE_CLAUDE_SUBJECT=[a-f0-9]{64}", prefix[1]) |
| 20 | and prefix[2:4] == ["/usr/local/bin/cage-claude-account", "run"] |
| 21 | and (prefix[4] == "default" or re.fullmatch("[a-f0-9]{24}", prefix[4]))) |
| 22 | ccs = len(prefix) == 2 and prefix[0] == "ccs" and re.fullmatch("[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", prefix[1]) |
| 23 | if prefix != ["claude"] and not managed and not ccs: |
| 24 | raise ValueError("不支持的客机 Claude 启动命令") |
| 25 | |
| 26 | |
| 27 | subdir = request.get("project_subdir") |
| 28 | if subdir: |
| 29 | directory = os.open(".", os.O_RDONLY | os.O_DIRECTORY) |
| 30 | try: |
| 31 | device = os.fstat(directory).st_dev |
| 32 | for part in subdir.split("/"): |
| 33 | if part in ("", ".", ".."): |
| 34 | raise ValueError("会话目录无效") |
| 35 | child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory) |
| 36 | os.close(directory) |
| 37 | directory = child |
| 38 | if os.fstat(directory).st_dev != device: |
| 39 | raise ValueError("会话目录不属于当前挂载") |
| 40 | os.fchdir(directory) |
| 41 | finally: |
| 42 | os.close(directory) |
| 43 | return cli_channel.launch(request) |
| 44 | |
| 45 | |
| 46 | if __name__ == "__main__": |
| 47 | if sys.argv[1] == "macos-launch": |
| 48 | |
| 49 | |
| 50 | script = '"$1" -I "$2" macos-exec "$3"; exec /bin/zsh -i' |
| 51 | os.execv("/bin/zsh", ["zsh", "-c", script, "cage-claude", sys.executable, str(Path(__file__).resolve()), sys.argv[2]]) |
| 52 | if sys.argv[1] == "macos-exec": |
| 53 | os.umask(0o077) |
| 54 | sys.exit(macos_launch(json.loads(sys.argv[2])) or 0) |
| 55 | sys.exit(cli_channel.main() or 0) |