| 1 | """Windows-native primitives used by the shared CLI algorithms.""" |
| 2 | import ctypes |
| 3 | from ctypes import wintypes |
| 4 | import errno |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | import struct |
| 8 | import time |
| 9 | |
| 10 | kernel = ctypes.WinDLL("kernel32.dll", use_last_error=True) |
| 11 | kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] |
| 12 | kernel.OpenProcess.restype = wintypes.HANDLE |
| 13 | kernel.CloseHandle.argtypes = [wintypes.HANDLE] |
| 14 | kernel.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] |
| 15 | kernel.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)] |
| 16 | kernel.GetProcessTimes.argtypes = [wintypes.HANDLE, ctypes.POINTER(ctypes.c_ulonglong), ctypes.POINTER(ctypes.c_ulonglong), ctypes.POINTER(ctypes.c_ulonglong), ctypes.POINTER(ctypes.c_ulonglong)] |
| 17 | kernel.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT] |
| 18 | kernel.ProcessIdToSessionId.argtypes = [wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)] |
| 19 | |
| 20 | class FileLock: |
| 21 | LOCK_EX, LOCK_NB = 2, 4 |
| 22 | @staticmethod |
| 23 | def flock(file, operation): |
| 24 | import msvcrt |
| 25 | fd = file if isinstance(file, int) else file.fileno() |
| 26 | if os.fstat(fd).st_size == 0: |
| 27 | os.write(fd, b"\0") |
| 28 | while True: |
| 29 | os.lseek(fd, 0, os.SEEK_SET) |
| 30 | try: |
| 31 | msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) |
| 32 | return |
| 33 | except OSError as error: |
| 34 | if error.errno not in (errno.EACCES, errno.EDEADLK): |
| 35 | raise |
| 36 | if operation & FileLock.LOCK_NB: |
| 37 | raise BlockingIOError(errno.EAGAIN, "private state is busy") from error |
| 38 | time.sleep(.05) |
| 39 | |
| 40 | def process_live(pid): |
| 41 | try: |
| 42 | handle = kernel.OpenProcess(0x1000, False, int(pid)) |
| 43 | if not handle: |
| 44 | return False |
| 45 | try: |
| 46 | result = wintypes.DWORD() |
| 47 | return bool(kernel.GetExitCodeProcess(handle, ctypes.byref(result))) and result.value == 259 |
| 48 | finally: |
| 49 | kernel.CloseHandle(handle) |
| 50 | except (ValueError, TypeError, OverflowError): |
| 51 | return False |
| 52 | |
| 53 | def process_fingerprint(pid): |
| 54 | if not process_live(pid): |
| 55 | return "" |
| 56 | handle = kernel.OpenProcess(0x1000, False, int(pid)) |
| 57 | if not handle: |
| 58 | return "" |
| 59 | try: |
| 60 | name = ctypes.create_unicode_buffer(32768); size = wintypes.DWORD(len(name)) |
| 61 | created, exited, kern, user = [ctypes.c_ulonglong() for _ in range(4)] |
| 62 | session = wintypes.DWORD() |
| 63 | if not kernel.QueryFullProcessImageNameW(handle, 0, name, ctypes.byref(size)) or not kernel.GetProcessTimes(handle, *map(ctypes.byref, (created, exited, kern, user))) or not kernel.ProcessIdToSessionId(int(pid), ctypes.byref(session)): |
| 64 | return "" |
| 65 | return (created.value, os.path.normcase(name.value), session.value) |
| 66 | finally: |
| 67 | kernel.CloseHandle(handle) |
| 68 | |
| 69 | def terminate_cli(pid, force=False): |
| 70 | fingerprint = process_fingerprint(pid) |
| 71 | expected = os.environ.get("CAGE_CLI_BINARY") |
| 72 | own = wintypes.DWORD() |
| 73 | if not fingerprint or not expected or not kernel.ProcessIdToSessionId(os.getpid(), ctypes.byref(own)) or fingerprint[2] != own.value or fingerprint[1] != os.path.normcase(str(Path(expected).resolve())): |
| 74 | raise ValueError("原生 Claude 进程身份不匹配,未停止其他程序") |
| 75 | handle = kernel.OpenProcess(0x1001, False, int(pid)) |
| 76 | if not handle: |
| 77 | raise ProcessLookupError("CLI process no longer exists") |
| 78 | try: |
| 79 | if process_fingerprint(pid) != fingerprint or not kernel.TerminateProcess(handle, 130): |
| 80 | raise ValueError("无法停止已核验的原生 Claude 进程") |
| 81 | finally: |
| 82 | kernel.CloseHandle(handle) |
| 83 | |
| 84 | def resource_link(path, target): |
| 85 | path, target = Path(path), Path(target) |
| 86 | if not target.is_dir(): |
| 87 | os.link(target, path) |
| 88 | return |
| 89 | |
| 90 | substitute = ("\\??\\" + str(target.resolve())).encode("utf-16le") |
| 91 | display = str(target.resolve()).encode("utf-16le") |
| 92 | names = substitute + b"\0\0" + display + b"\0\0" |
| 93 | value = struct.pack("<IHHHHHH", 0xA0000003, 8 + len(names), 0, 0, len(substitute), len(substitute) + 2, len(display)) + names |
| 94 | kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE] |
| 95 | kernel.CreateFileW.restype = wintypes.HANDLE |
| 96 | kernel.DeviceIoControl.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), wintypes.LPVOID] |
| 97 | path.mkdir() |
| 98 | handle = kernel.CreateFileW(str(path), 0x40000000, 7, None, 3, 0x02200000, None) |
| 99 | try: |
| 100 | if handle == wintypes.HANDLE(-1).value: |
| 101 | raise ctypes.WinError(ctypes.get_last_error()) |
| 102 | data = ctypes.create_string_buffer(value); returned = wintypes.DWORD() |
| 103 | if not kernel.DeviceIoControl(handle, 0x900A4, data, len(value), None, 0, ctypes.byref(returned), None): |
| 104 | raise ctypes.WinError(ctypes.get_last_error()) |
| 105 | except Exception: |
| 106 | if handle != wintypes.HANDLE(-1).value: |
| 107 | kernel.CloseHandle(handle); handle = wintypes.HANDLE(-1).value |
| 108 | path.rmdir() |
| 109 | raise |
| 110 | finally: |
| 111 | if handle != wintypes.HANDLE(-1).value: |
| 112 | kernel.CloseHandle(handle) |
| 113 | |
| 114 | |
| 115 | def launch_cli(args, request, connection, state_file): |
| 116 | |
| 117 | import runpy |
| 118 | import subprocess |
| 119 | account = runpy.run_path(os.environ["CAGE_CLI_ACCOUNT_HELPER"]) |
| 120 | base = account["profile"](request.get("account") or "default") |
| 121 | env = account["cli_environment"](base) |
| 122 | account["shared_profile_resources"](base) |
| 123 | args = [args[0], *account["shared_launch_arguments"](base, args[1:], None)] |
| 124 | if request.get("subject"): |
| 125 | reading = account["identity"](args[0], env, Path.cwd(), account["settings_flags"](args[1:])) |
| 126 | if account["subject"](reading) != request["subject"]: |
| 127 | raise ValueError("项目与所选 Claude 账号身份不一致") |
| 128 | child = CliProcess(args, env) |
| 129 | with state_file(connection) as state: |
| 130 | state["pid"] = child.pid |
| 131 | try: |
| 132 | code = child.wait() |
| 133 | finally: |
| 134 | child.close() |
| 135 | with state_file(connection) as state: |
| 136 | state["closed"] = True |
| 137 | state["busy"] = False |
| 138 | shell = os.environ.get("CAGE_CLI_SHELL") |
| 139 | if not shell: |
| 140 | return code |
| 141 | |
| 142 | |
| 143 | setup = 'function global:claude { & $env:CAGE_CLI_PYTHON -X utf8 -I $env:CAGE_CLI_ACCOUNT_HELPER run $env:CAGE_CLAUDE_ACCOUNT_ID @args }' |
| 144 | return subprocess.call([shell, "-NoLogo", "-NoExit", "-Command", setup], env=env) |
| 145 | |
| 146 | |
| 147 | class CliProcess: |
| 148 | """A suspended native Claude process and its own nested job tree.""" |
| 149 | def __init__(self, args, env): |
| 150 | import _winapi |
| 151 | import subprocess |
| 152 | class Basic(ctypes.Structure): |
| 153 | _fields_ = [('process_time', ctypes.c_longlong), ('job_time', ctypes.c_longlong), |
| 154 | ('flags', wintypes.DWORD), ('minimum', ctypes.c_size_t), ('maximum', ctypes.c_size_t), |
| 155 | ('active', wintypes.DWORD), ('affinity', ctypes.c_size_t), |
| 156 | ('priority', wintypes.DWORD), ('scheduling', wintypes.DWORD)] |
| 157 | class IO(ctypes.Structure): |
| 158 | _fields_ = [('counters', ctypes.c_ulonglong * 6)] |
| 159 | class Limits(ctypes.Structure): |
| 160 | _fields_ = [('basic', Basic), ('io', IO), ('process_memory', ctypes.c_size_t), |
| 161 | ('job_memory', ctypes.c_size_t), ('peak_process', ctypes.c_size_t), ('peak_job', ctypes.c_size_t)] |
| 162 | kernel.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPCWSTR] |
| 163 | kernel.CreateJobObjectW.restype = wintypes.HANDLE |
| 164 | kernel.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD] |
| 165 | kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE] |
| 166 | kernel.ResumeThread.argtypes = [wintypes.HANDLE] |
| 167 | kernel.ResumeThread.restype = wintypes.DWORD |
| 168 | self.job = kernel.CreateJobObjectW(None, None) |
| 169 | self.handle = None |
| 170 | if not self.job: |
| 171 | raise ctypes.WinError(ctypes.get_last_error()) |
| 172 | try: |
| 173 | limits = Limits(); limits.basic.flags = 0x2000 |
| 174 | if not kernel.SetInformationJobObject(self.job, 9, ctypes.byref(limits), ctypes.sizeof(limits)): |
| 175 | raise ctypes.WinError(ctypes.get_last_error()) |
| 176 | process, thread, self.pid, _ = _winapi.CreateProcess(args[0], subprocess.list2cmdline(args), None, None, |
| 177 | True, 0x00000004 | 0x00000400, env, None, subprocess.STARTUPINFO()) |
| 178 | self.handle = process |
| 179 | try: |
| 180 | if not kernel.AssignProcessToJobObject(self.job, process) or kernel.ResumeThread(thread) == 0xffffffff: |
| 181 | raise ctypes.WinError(ctypes.get_last_error()) |
| 182 | except BaseException: |
| 183 | _winapi.TerminateProcess(process, 1) |
| 184 | raise |
| 185 | finally: |
| 186 | _winapi.CloseHandle(thread) |
| 187 | except BaseException: |
| 188 | self.close() |
| 189 | raise |
| 190 | |
| 191 | def wait(self): |
| 192 | import _winapi |
| 193 | _winapi.WaitForSingleObject(self.handle, _winapi.INFINITE) |
| 194 | return _winapi.GetExitCodeProcess(self.handle) |
| 195 | |
| 196 | def close(self): |
| 197 | import _winapi |
| 198 | if self.job: |
| 199 | kernel.CloseHandle(self.job); self.job = None |
| 200 | if self.handle: |
| 201 | _winapi.WaitForSingleObject(self.handle, _winapi.INFINITE) |
| 202 | _winapi.CloseHandle(self.handle); self.handle = None |
| 203 | |
| 204 | |
| 205 | def launch_ccs_parent(request, channel): |
| 206 | import json |
| 207 | import subprocess |
| 208 | import sys |
| 209 | connection = channel['identifier'](request['id']) |
| 210 | sid = channel['identifier'](request.get('resume') or request['session_id']) |
| 211 | profile = request['ccs_profile'] |
| 212 | root = channel['ROOT'] / connection |
| 213 | root.mkdir(parents=True, exist_ok=True) |
| 214 | context = {'id':connection, 'session_id':sid, 'profile':profile, 'folder':str(root), |
| 215 | 'binary':os.environ['CAGE_CLI_BINARY'], 'python':sys.executable, |
| 216 | 'helper':str(Path(channel['__file__']).resolve()), 'main':os.environ['CAGE_CCS_MAIN'], |
| 217 | 'resume':bool(request.get('resume'))} |
| 218 | channel['save'](root / 'ccs-launch.json', context) |
| 219 | env = dict(os.environ, CAGE_CCS_LAUNCH_FILE=str(root / 'ccs-launch.json')) |
| 220 | args = [env['CAGE_CCS_NODE'], '--require', env['CAGE_CCS_PRELOAD'], env['CAGE_CCS_MAIN'], profile, |
| 221 | '--resume' if request.get('resume') else '--session-id', sid, '--setting-sources', 'user'] |
| 222 | with channel['state_file'](connection) as state: |
| 223 | if channel['live'](state.get('pid')) and not state.get('closed'): |
| 224 | raise ValueError('目标会话已有进程,未重复启动') |
| 225 | state.update(cli_id=sid, config=str(Path(env.get('CLAUDE_CONFIG_DIR') or Path.home()/'.claude')), |
| 226 | workspace=str(Path.cwd()), closed=False, busy=False, channel_pid=None, |
| 227 | pid=os.getpid(), updated_at=__import__('time').time(), native_ccs_pending=True) |
| 228 | child = CliProcess(args, env) |
| 229 | try: |
| 230 | child.wait() |
| 231 | finally: |
| 232 | child.close() |
| 233 | with channel['state_file'](connection) as state: |
| 234 | state['closed'] = True |
| 235 | state['busy'] = False |
| 236 | shell = env.get('CAGE_CLI_SHELL') |
| 237 | if not shell: |
| 238 | return 0 |
| 239 | setup = 'function global:ccs { & $env:CAGE_CCS_NODE $env:CAGE_CCS_MAIN @args }; function global:claude { & $env:CAGE_CLI_BINARY @args }' |
| 240 | return subprocess.call([shell, '-NoLogo', '-NoExit', '-Command', setup], env=env) |
| 241 | |
| 242 | |
| 243 | def launch_ccs_live(filename, channel): |
| 244 | import json |
| 245 | import runpy |
| 246 | import subprocess |
| 247 | import tempfile |
| 248 | import time |
| 249 | import sys |
| 250 | source = Path(filename) |
| 251 | if source.is_symlink() or source.stat().st_size > 1 << 20: |
| 252 | raise ValueError('CCS 实际启动记录无效') |
| 253 | metadata = json.loads(source.read_text(encoding='utf-8')) |
| 254 | connection = channel['identifier'](metadata['id']) |
| 255 | sid = channel['identifier'](metadata['session_id']) |
| 256 | folder = channel['ROOT'] / connection |
| 257 | if source.parent.resolve() != folder.resolve() or not source.name.startswith('ccs-actual-'): |
| 258 | raise ValueError('CCS 实际启动记录不属于此会话') |
| 259 | source.unlink() |
| 260 | context = channel['read_json'](folder/'ccs-launch.json') |
| 261 | if context['id'] != connection or context['session_id'] != sid or context['profile'] != metadata['profile']: |
| 262 | raise ValueError('CCS 实际启动记录已变化') |
| 263 | original = metadata['actual_args'] |
| 264 | if not isinstance(original, list) or any(not isinstance(arg, str) for arg in original): |
| 265 | raise ValueError('CCS 参数无效') |
| 266 | binary = os.environ['CAGE_CLI_BINARY'] |
| 267 | args = original.copy() |
| 268 | identity = runpy.run_path(os.environ['CAGE_CLI_IDENTITY_HELPER']) |
| 269 | snapshot = tempfile.NamedTemporaryFile(dir=folder, suffix='.settings.json', delete=False) |
| 270 | verified = False |
| 271 | notice = '此 CCS 配置尚未通过共享身份核验,终端仍可使用。' |
| 272 | try: |
| 273 | try: |
| 274 | settings_file = Path(metadata['settings_source']) |
| 275 | expected_file = Path(metadata['expected_settings_source']) |
| 276 | if metadata['profile_type'] != 'settings' or not settings_file.is_absolute() or settings_file.resolve() != expected_file.resolve(): |
| 277 | raise identity['Unverified']() |
| 278 | |
| 279 | |
| 280 | settings = identity['read_settings'](settings_file) |
| 281 | position = args.index('--settings') |
| 282 | if Path(args[position + 1]).resolve() != settings_file.resolve(): |
| 283 | raise identity['Unverified']() |
| 284 | del args[position:position + 2] |
| 285 | _, args, env, material = identity['resolve_actual_context'](binary, ['ccs',metadata['profile']], args, dict(os.environ), settings, snapshot) |
| 286 | identity['validate_shared_mcp'](args, [Path.cwd()/'.mcp.json', Path(os.environ.get('ProgramFiles','C:/Program Files'))/'ClaudeCode/managed-mcp.json'], config_env=env, workspace=Path.cwd()) |
| 287 | snapshot.seek(0); settings = json.load(snapshot) |
| 288 | hooks = settings.setdefault('hooks', {}) |
| 289 | if not isinstance(hooks, dict): raise identity['Unverified']() |
| 290 | handler = {'type':'command', 'command':sys.executable, 'args':['-X','utf8','-I',str(Path(channel['__file__']).resolve()),'hook',connection], 'timeout':5} |
| 291 | for event in ('SessionStart','UserPromptSubmit','MessageDisplay','PreToolUse','PostToolUse','PostToolUseFailure','Stop','StopFailure','SessionEnd'): |
| 292 | entries = hooks.setdefault(event, []) |
| 293 | if not isinstance(entries, list): raise identity['Unverified']() |
| 294 | entries.append({'hooks':[handler.copy()]}) |
| 295 | snapshot.seek(0); snapshot.truncate(); snapshot.write(json.dumps(settings,ensure_ascii=False).encode('utf-8')) |
| 296 | snapshot.flush() |
| 297 | channel['save'](folder/'mcp.json', {'mcpServers':{'cage':{'command':sys.executable,'args':['-X','utf8','-I',str(Path(channel['__file__']).resolve()),'serve',connection]}}}) |
| 298 | args += ['--mcp-config',str(folder/'mcp.json'),'--dangerously-load-development-channels','server:cage'] |
| 299 | disabled = identity['shared_channels_disabled']() |
| 300 | identity['bind'](sid, context['resume'], material) |
| 301 | verified = True; notice = '' |
| 302 | except identity['Changed']: |
| 303 | raise ValueError('CCS 账号或配置身份已变化,聊天记录已保留,请新建会话。') |
| 304 | except (identity['Unverified'], OSError, ValueError, KeyError, TypeError, IndexError, subprocess.SubprocessError): |
| 305 | if context['resume']: |
| 306 | raise ValueError('CCS 原会话身份暂时无法核验,聊天记录已保留。') |
| 307 | |
| 308 | |
| 309 | args, env, disabled = original, dict(os.environ), False |
| 310 | child = CliProcess([binary,*args], env) |
| 311 | with channel['state_file'](connection) as state: |
| 312 | state.update(pid=child.pid, native_ccs_pending=False, native_ccs_unverified=not verified, |
| 313 | native_ccs_notice=notice, blocked=disabled, |
| 314 | config=str(Path(env.get('CLAUDE_CONFIG_DIR') or Path.home()/'.claude').resolve()), |
| 315 | cli_id=sid, workspace=str(Path.cwd()), closed=False, updated_at=time.time()) |
| 316 | try: |
| 317 | return child.wait() |
| 318 | finally: |
| 319 | child.close() |
| 320 | with channel['state_file'](connection) as state: |
| 321 | state['closed'] = True; state['busy'] = False |
| 322 | finally: |
| 323 | snapshot.close(); Path(snapshot.name).unlink(missing_ok=True) |