跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

cli_channel.py

923 行 · 45.0 KB历史下载
1"""Guest-side Claude terminal discovery and authenticated local channel bridge."""
2import contextlib
3import hashlib
4import json
5import os
6from pathlib import Path
7import re
8import runpy
9import shlex
10import shutil
11import signal
12import socket
13import socketserver
14import subprocess
15import sys
16import tempfile
17import threading
18import time
19import uuid
20
21
22if os.name == "nt":
23 _platform = runpy.run_path(Path(__file__).with_name("windows_cli_platform.py"))
24 fcntl = _platform["FileLock"]
25else:
26 import fcntl
27
28def process_fingerprint(pid):
29 if os.name == "nt":
30 return _platform["process_fingerprint"](pid)
31 return subprocess.run(["ps", "-o", "lstart=,comm=", "-p", str(pid)], capture_output=True, text=True, timeout=2).stdout
32
33def terminate_cli(pid, force=False):
34 if os.name == "nt":
35 return _platform["terminate_cli"](pid, force)
36 return os.kill(int(pid), signal.SIGKILL if force else signal.SIGTERM)
37
38ROOT = Path(os.environ["CAGE_CLI_STATE_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/cli-channels"
39PROMPT_LIMIT = 32 << 10
40REPLY_LIMIT = 128 << 10
41HISTORY_LIMIT = 448 << 10
42
43
44def identifier(value):
45 return str(uuid.UUID(value))
46
47
48def read_json(path, default=None):
49 try:
50 return json.loads(path.read_text())
51 except FileNotFoundError:
52 return default
53
54
55def save(path, value):
56 path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
57 with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream:
58 json.dump(value, stream, ensure_ascii=False)
59 temporary = stream.name
60 os.replace(temporary, path)
61
62
63@contextlib.contextmanager
64def state_file(connection):
65 folder = ROOT / identifier(connection)
66 folder.mkdir(parents=True, exist_ok=True, mode=0o700)
67 with (folder / "lock").open("a") as lock:
68 fcntl.flock(lock, fcntl.LOCK_EX)
69 path = folder / "state.json"
70 state = read_json(path, {})
71 yield state
72 save(path, state)
73
74
75def live(pid):
76 if os.name == "nt":
77 return _platform["process_live"](pid)
78 try:
79 os.kill(int(pid), 0)
80 return True
81 except (OSError, ValueError, TypeError):
82 return False
83
84
85def config_directory(account):
86 if account == "default":
87 return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude").resolve()
88 if not re.fullmatch(r"[0-9a-f]{24}", account):
89 raise ValueError("invalid account")
90 root = Path(os.environ["CAGE_CLI_ACCOUNT_ROOT"]) if os.name == "nt" else Path.home() / ".local/share/cage/claude-accounts"
91 return root / account / "config"
92
93
94def workspace_within(path, root):
95 if os.name == "nt":
96 path, root = path.replace("\\", "/").lower(), root.replace("\\", "/").lower()
97 return path == root or path.startswith(root.rstrip("/") + "/")
98
99
100def text_content(message):
101 content = message.get("content", [])
102 if isinstance(content, str):
103 return content
104 return "\n".join(item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text")
105
106
107def clip_text(text, limit):
108 return text.encode("utf-8")[:limit].decode("utf-8", errors="ignore")
109
110
111def channel_message(text):
112 match = re.match(r'^<channel\s+[^>]*cage_request="([0-9a-f-]{36})"[^>]*>\n?', text)
113 if not match or not text.endswith("</channel>"):
114 return None
115 # Only remove the framing newline. The user's text can itself contain XML
116 # tags, including </channel>, and must remain an opaque message body.
117 body = text[match.end():-len("</channel>")]
118 return match.group(1), body.removesuffix("\n")
119
120
121def update_tools(turn, role, content):
122 if not isinstance(content, list):
123 return
124 tools = turn.get("tools", [])
125 by_id = {tool["id"]: tool for tool in tools}
126 for block in content:
127 if not isinstance(block, dict):
128 continue
129 kind = block.get("type")
130 if role == "user" and kind == "tool_result":
131 result_id = block.get("tool_use_id")
132 tool = by_id.get(result_id) if isinstance(result_id, str) else None
133 if tool:
134 tool["status"] = "failed" if block.get("is_error") else "completed"
135 if role != "assistant" or kind not in ("tool_use", "server_tool_use"):
136 continue
137 key, name = block.get("id"), block.get("name")
138 if not isinstance(key, str) or not 0 < len(key.encode()) <= 128 or key in by_id or len(tools) >= 64:
139 continue
140 if not isinstance(name, str) or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", name):
141 continue
142 tool = {"id": key, "name": name, "status": "called"}
143 args = block.get("input")
144 if isinstance(args, dict):
145 for field in ("description", "subject", "file_path", "pattern", "query", "skill", "subagent_type"):
146 value = args.get(field)
147 if isinstance(value, str) and value.strip():
148 tool["detail"] = value.strip()[:160]
149 break
150 by_id[key] = tool
151 tools.append(tool)
152 if tools:
153 turn["tools"] = tools
154
155
156def transcript(path):
157 turns, seen, workspace, title = [], set(), "", ""
158 if not path or not path.is_file() or path.is_symlink():
159 return turns, workspace, title, seen
160 with path.open() as stream:
161 for line in stream:
162 if len(line) > 4 * 1024 * 1024:
163 continue
164 try:
165 row = json.loads(line)
166 except ValueError:
167 continue
168 if row.get("isSidechain"):
169 continue
170 workspace = row.get("cwd") or workspace
171 if row.get("type") == "custom-title":
172 title = row.get("customTitle") or title
173 key = row.get("uuid")
174 if not key or key in seen:
175 continue
176 seen.add(key)
177 message = row.get("message") or {}
178 if turns:
179 update_tools(turns[-1], row.get("type"), message.get("content"))
180 text = text_content(message)
181 if not text:
182 continue
183 if row.get("type") == "assistant" and message.get("model") == "<synthetic>" and text == "No response requested.":
184 continue
185 if row.get("type") == "user":
186 channel = channel_message(text) if row.get("isMeta") else None
187 if channel:
188 key, text = channel
189 seen.add(key)
190 elif row.get("isCompactSummary") or (row.get("isMeta") and not text.lstrip().startswith("<task-notification>")):
191 continue
192 turns.append({"id": key, "prompt": clip_text(text, PROMPT_LIMIT), "prompt_truncated": len(text.encode()) > PROMPT_LIMIT, "text": "", "status": "completed"})
193 turns = turns[-256:]
194 elif row.get("type") == "assistant" and turns:
195 turn = turns[-1]
196 value = turn["text"] + ("\n\n" if turn["text"] else "") + text
197 turn["text"], turn["truncated"] = clip_text(value, REPLY_LIMIT), len(value.encode()) > REPLY_LIMIT
198 return turns, workspace, title, seen
199
200
201def connection_for(session_id, config):
202 matches = []
203 for path in ROOT.glob("*/state.json"):
204 state = read_json(path, {})
205 if state.get("cli_id") == session_id and state.get("config") == str(config):
206 matches.append((path.parent.name, state))
207 return max(matches, key=lambda item: (live(item[1].get("pid")) and not item[1].get("closed"), live(item[1].get("channel_pid")), item[1].get("updated_at", 0)), default=("", {}))
208
209
210def view(config, session_id, path=None):
211 connection, state = connection_for(session_id, config)
212 path = path or next((config / "projects").glob("*/" + session_id + ".jsonl"), None)
213 native_history = path is not None
214 if path is None and state.get("resume_transcript"):
215 frozen = Path(state["resume_transcript"])
216 if frozen.parent.parent == ROOT.parent / "cli-account-switches" and frozen.name == "history.jsonl":
217 path = frozen
218 turns, workspace, title, received = transcript(path)
219 has_history = bool(turns)
220 if connection and any(sent["id"] in received for sent in state.get("sent", [])):
221 with state_file(connection) as latest:
222 latest["sent"] = [sent for sent in latest.get("sent", []) if sent["id"] not in received]
223 state = dict(latest)
224 running = live(state.get("pid")) and not state.get("closed")
225 channel = running and live(state.get("channel_pid")) and not state.get("blocked") and not state.get("policy_unavailable") and not state.get("native_ccs_unverified")
226 known = {turn["id"] for turn in turns}
227 for sent in state.get("sent", []):
228 if sent["id"] not in known:
229 turns.append({"id": sent["id"], "prompt": sent["text"], "text": "", "status": "interrupted" if sent.get("interrupted") else "queued"})
230 display = state.get("display")
231 if turns and display and state.get("busy") and display.get("text"):
232 text = display["text"]
233 if not turns[-1]["text"].endswith(text):
234 turns[-1]["text"] = clip_text((turns[-1]["text"] + "\n\n" + text).strip(), REPLY_LIMIT)
235 if turns:
236 if state.get("account_failure"):
237 turns[-1]["status"] = "failed"
238 elif state.get("stopped"):
239 turns[-1]["status"] = "stopped"
240 elif running and state.get("busy"):
241 turns[-1]["status"] = "running"
242 elif not running and turns[-1]["status"] == "queued":
243 turns[-1]["status"] = "interrupted"
244 approvals = state.get("approvals", [])
245 if running and approvals:
246 turns[-1]["status"] = "running"
247 turns[-1]["approval"] = {key: value for key, value in approvals[0].items() if key != "relay_id"}
248 shortened = any(turn.get("prompt_truncated") for turn in turns)
249 while len(turns) > 1 and len(json.dumps(turns, ensure_ascii=False).encode()) > HISTORY_LIMIT:
250 turns.pop(0)
251 shortened = True
252 modified = max(path.stat().st_mtime if path else 0, float(state.get("updated_at", 0)))
253 notice = state.get("native_ccs_notice", "")
254 if state.get("blocked"):
255 notice = "这台主机的 Claude Code 管理策略关闭了 Channels,请由主机管理员处理。"
256 elif state.get("policy_unavailable"):
257 notice = "Cage 默认环境的通道配置未能更新,请在电脑更新环境组件。"
258 return {"cli_id": session_id, "config": str(config), "connection": connection, "native_ccs_unverified": bool(state.get("native_ccs_unverified")),
259 "workspace": workspace or state.get("workspace", ""), "title": title or (turns[0]["prompt"][:40] if turns else "Claude Code"),
260 "updated_at": modified, "turns": turns, "running": bool(running), "active": bool(running and (state.get("busy") or state.get("approvals"))), "channel_ready": bool(channel), "can_send": bool(channel and not state.get("resume_task")), "has_history": has_history, "history_truncated": shortened,
261 "connection_notice": "" if channel else notice, "account_failure": state.get("account_failure", ""),
262 "resume_pending": bool(state.get("resume_task")), "native_history": native_history}
263
264
265def history_summary(path):
266 workspace, title = "", ""
267 with path.open() as stream:
268 for _ in range(64):
269 line = stream.readline(4 << 20)
270 if not line:
271 break
272 try:
273 row = json.loads(line)
274 except ValueError:
275 continue
276 workspace = row.get("cwd") or workspace
277 if row.get("type") == "user":
278 text = text_content(row.get("message") or {})
279 channel = channel_message(text) if row.get("isMeta") else None
280 if channel:
281 title = channel[1][:40]
282 elif not row.get("isMeta"):
283 title = text[:40]
284 if workspace and title:
285 break
286 # Names and directory changes are appended to the transcript. Read a
287 # bounded tail for the list, and load full message history only on opening.
288 with path.open("rb") as stream:
289 stream.seek(max(0, path.stat().st_size - (64 << 10)))
290 lines = stream.read().splitlines()
291 for line in lines:
292 try:
293 row = json.loads(line)
294 except (ValueError, UnicodeDecodeError):
295 continue
296 workspace = row.get("cwd") or workspace
297 if row.get("type") == "custom-title":
298 title = row.get("customTitle") or title
299 return workspace, title
300
301
302def discover(request):
303 allowed = request["workspaces"]
304 sessions = []
305 configs = {str(config_directory(account)) for account in request["accounts"]}
306 for state_path in ROOT.glob("*/state.json"):
307 state = read_json(state_path, {})
308 if state.get("config"):
309 configs.add(state["config"])
310 for config_name in configs:
311 config = Path(config_name)
312 running_ids = None
313 def observed_running():
314 nonlocal running_ids
315 if running_ids is None:
316 running_ids = {row.get("sessionId") for row in running_sessions(config_name)}
317 return running_ids
318 paths = sorted((config / "projects").glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
319 found = set()
320 for path in paths:
321 if path.is_symlink():
322 continue
323 try:
324 session_id = identifier(path.stem)
325 except ValueError:
326 continue
327 workspace, title = history_summary(path)
328 if not any(workspace_within(workspace, root) for root in allowed):
329 continue
330 connection, state = connection_for(session_id, config)
331 item = {"cli_id": session_id, "config": config_name, "connection": connection,
332 "workspace": workspace, "title": title or "Claude Code", "updated_at": path.stat().st_mtime,
333 "running": session_id in observed_running() or bool(live(state.get("pid")) and not state.get("closed")),
334 "active": bool(live(state.get("pid")) and not state.get("closed") and (state.get("busy") or state.get("approvals")))}
335 found.add(session_id)
336 sessions.append(item)
337 for state_path in ROOT.glob("*/state.json"):
338 state = read_json(state_path, {})
339 session_id = state.get("cli_id")
340 workspace = state.get("workspace", "")
341 if state.get("config") != config_name or not session_id or session_id in found or not any(workspace_within(workspace, root) for root in allowed):
342 continue
343 item = view(config, session_id)
344 item["running"] = item["running"] or session_id in observed_running()
345 item.pop("turns")
346 sessions.append(item)
347 return sessions
348
349
350def hook(connection):
351 payload = json.load(sys.stdin)
352 event = payload.get("hook_event_name")
353 with state_file(connection) as state:
354 if state.get("account_switch"):
355 if event == "UserPromptSubmit":
356 return {"decision": "block", "reason": "Cage 正在切换账号,请在目标会话中继续。"}
357 if event == "PreToolUse":
358 return {"hookSpecificOutput": {"hookEventName": event, "permissionDecision": "deny", "permissionDecisionReason": "Cage 正在切换账号。"}}
359 state["updated_at"] = time.time()
360 state["cli_id"] = identifier(payload["session_id"])
361 state["workspace"] = payload.get("cwd", state.get("workspace", ""))
362 state["config"] = str(config_directory("default"))
363 if event == "SessionStart":
364 state["closed"] = False
365 if event in ("UserPromptSubmit", "PreToolUse"):
366 state["busy"] = True
367 if event == "UserPromptSubmit":
368 state.pop("account_failure", None)
369 state.pop("stopped", None)
370 state.pop("pending_send", None)
371 if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop", "SessionEnd"):
372 state["approvals"] = []
373 if event in ("Stop", "StopFailure", "SessionEnd"):
374 state["busy"] = False
375 state.pop("display", None)
376 if event == "StopFailure":
377 state["account_failure"] = payload.get("error", "unknown")
378 if event == "SessionEnd":
379 state["closed"] = True
380 if event == "MessageDisplay":
381 current = state.get("display") or {}
382 if current.get("id") != payload.get("message_id"):
383 current = {"id": payload.get("message_id"), "text": "", "index": -1}
384 if payload.get("index", 0) > current["index"]:
385 current["text"] = clip_text(current["text"] + payload.get("delta", ""), REPLY_LIMIT)
386 current["index"] = payload.get("index", 0)
387 state["display"] = current
388 return {}
389
390
391def migrate_cage_policy():
392 if os.name == "nt":
393 # Organizational Windows policy is never rewritten by a GUI user.
394 return None
395 path = Path("/etc/claude-code/managed-settings.json")
396 original = {"permissions": {"defaultMode": "bypassPermissions"}, "tui": "fullscreen"}
397 if sys.platform != "linux":
398 return
399 try:
400 if read_json(path) != original:
401 return
402 except (OSError, ValueError):
403 return False
404 # Upgrade only the exact policy shipped by Cage. An administrator's
405 # explicit settings, including channelsEnabled=false, take precedence.
406 migration = '''import json, pathlib, tempfile, os
407p = pathlib.Path('/etc/claude-code/managed-settings.json')
408old = p.read_bytes()
409value = json.loads(old)
410if value == {"permissions": {"defaultMode": "bypassPermissions"}, "tui": "fullscreen"}:
411 backup = p.with_name('managed-settings.json.cage-before-channels')
412 if not backup.exists():
413 backup.write_bytes(old)
414 backup.chmod(0o600)
415 value['channelsEnabled'] = True
416 with tempfile.NamedTemporaryFile(dir=p.parent, mode='w', delete=False) as f:
417 json.dump(value, f)
418 name = f.name
419 os.chmod(name, 0o644)
420 os.replace(name, p)
421'''
422 try:
423 subprocess.run(["/usr/bin/sudo", "-n", "python3", "-I", "-c", migration], timeout=10,
424 stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
425 except (OSError, subprocess.SubprocessError):
426 return False
427 return True
428
429
430def active_session(session_id, config=""):
431 return bool(active_sessions(session_id, config))
432
433
434def active_sessions(session_id, config=""):
435 return [row for row in running_sessions(config) if row.get("sessionId") == session_id]
436
437
438def running_sessions(config=""):
439 env = dict(os.environ)
440 if config:
441 env["CLAUDE_CONFIG_DIR"] = config
442 listing = subprocess.run(["claude", "agents", "--json"], env=env, capture_output=True, text=True, timeout=10)
443 if listing.returncode != 0:
444 raise ValueError("无法检查原会话是否仍在运行")
445 return [row for row in json.loads(listing.stdout) if live(row.get("pid"))]
446
447
448def handoff_session(request):
449 session_id = identifier(request["cli_id"])
450 config = request["config"]
451 workspace = request["workspace"]
452 rows = active_sessions(session_id, config)
453 # A live shared channel is reusable even after the host service restarts.
454 _, state = connection_for(session_id, Path(config))
455 if live(state.get("pid")) and live(state.get("channel_pid")) and not state.get("closed"):
456 return {"running": True, "channel_ready": True}
457 for row in rows:
458 if row.get("cwd") != workspace:
459 raise ValueError("原会话的项目已变化,请重新读取会话列表")
460 # A waiting CLI has no executing tool. Resume its task on the shared
461 # channel so any permission decision is requested again on the phone.
462 if row.get("status") not in ("idle", "waiting") or row.get("kind") != "interactive":
463 return {"running": True}
464 for row in rows:
465 # Refresh the supported CLI registry immediately before signalling so
466 # stale discovery data cannot select a different process or workspace.
467 current = active_sessions(session_id, config)
468 matched = next((item for item in current if item.get("pid") == row["pid"] and item.get("cwd") == workspace and item.get("kind") == "interactive" and item.get("status") in ("idle", "waiting")), None)
469 if matched is None:
470 return {"running": bool(current)}
471 if matched["status"] == "waiting":
472 save(handoff_receipt(config, session_id), {"resume_task": True, "permission_mode": "manual" if matched.get("waitingFor") != "input needed" else ""})
473 try:
474 terminate_cli(row["pid"])
475 except ProcessLookupError:
476 pass
477 deadline = time.monotonic() + 5
478 while rows and time.monotonic() < deadline:
479 if not any(live(row["pid"]) for row in rows):
480 return {"running": False}
481 time.sleep(0.05)
482 return {"running": bool(rows)}
483
484
485def handoff_receipt(config, session_id):
486 key = hashlib.sha256((str(config) + "\n" + session_id).encode()).hexdigest()
487 return ROOT.parent / "cli-handoffs" / (key + ".json")
488
489
490def prepare_account_switch(request):
491 # Freeze only an idle source. Never resubmit prompts or tools here.
492 sid = identifier(request["cli_id"])
493 switch_id = identifier(request["switch_id"])
494 config = Path(request["config"]).resolve()
495 connection = identifier(request["connection"])
496 workspace = request["workspace"]
497 folder = ROOT.parent / "cli-account-switches" / switch_id
498 receipt = folder / "receipt.json"
499 binding = {key: request[key] for key in ("cli_id", "config", "connection", "workspace", "target_cli_id")}
500 if receipt.exists():
501 saved = read_json(receipt)
502 if saved["binding"] != binding:
503 raise ValueError("账号交接编号已用于另一项操作")
504 return {"transcript": str(folder / "history.jsonl")}
505 with state_file(connection) as state:
506 if state.get("cli_id") != sid or state.get("config") != str(config) or state.get("workspace") != workspace:
507 raise ValueError("原会话身份或项目已变化,请刷新后重试")
508 if state.get("busy") or state.get("approvals") or state.get("pending_send") or state.get("sent"):
509 raise ValueError("原会话仍有任务、待发消息或审批,请结束后再切换账号")
510 existing = state.get("account_switch")
511 if existing and existing != switch_id:
512 raise ValueError("此会话已有账号交接尚未完成")
513 state["account_switch"] = switch_id
514 save(ROOT / connection / "state.json", state)
515 rows = active_sessions(sid, str(config))
516 # Any other live worker in this account can represent a background
517 # child of the source. The registry does not expose a complete ancestry.
518 listing = subprocess.run(["claude", "agents", "--json"], env={**os.environ, "CLAUDE_CONFIG_DIR": str(config)}, capture_output=True, text=True, timeout=10)
519 if listing.returncode != 0:
520 raise ValueError("无法确认后台任务,未切换账号")
521 if any(row.get("sessionId") != sid and live(row.get("pid")) for row in json.loads(listing.stdout)):
522 raise ValueError("原账号仍有其他执行任务,请结束后台任务后再交接")
523 for row in rows:
524 if row.get("cwd") != workspace or row.get("status") != "idle" or row.get("kind") != "interactive":
525 raise ValueError("原 Claude Code 尚未安全停止,请先结束本轮任务")
526 pid = state.get("pid")
527 fingerprint = process_fingerprint(pid) if live(pid) else ""
528 def executing():
529 if not live(pid):
530 return False
531 if os.name == "nt":
532 return True
533 status = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True, timeout=2)
534 return bool(status.stdout.strip()) and not status.stdout.lstrip().startswith("Z")
535 if executing() and not any(row.get("pid") == pid for row in rows):
536 raise ValueError("无法核对原进程状态,请先退出原 Claude Code 后重试")
537 for row in rows:
538 terminate_cli(row["pid"])
539 deadline = time.monotonic() + 5
540 while executing() and time.monotonic() < deadline:
541 time.sleep(.05)
542 if executing():
543 latest = read_json(ROOT / connection / "state.json", {})
544 current = process_fingerprint(pid)
545 # The CLI can finish its SessionEnd hook but hang while shutting down
546 # its MCP child. Terminate only that same, already idle and fenced CLI.
547 if latest.get("closed") and latest.get("account_switch") == switch_id and fingerprint and current == fingerprint and not active_sessions(sid, str(config)):
548 terminate_cli(pid, True)
549 deadline = time.monotonic() + 1
550 while executing() and time.monotonic() < deadline:
551 time.sleep(.05)
552 if executing():
553 raise ValueError("原进程尚未退出,未启动目标账号")
554 path = next((config / "projects").glob("*/" + sid + ".jsonl"), None)
555 if path is None or path.is_symlink():
556 raise ValueError("原会话历史不可用,未切换账号")
557 pending = set()
558 for line in path.read_text().splitlines():
559 row = json.loads(line)
560 if row.get("isSidechain"):
561 continue
562 if row.get("cwd") and row["cwd"] != workspace:
563 raise ValueError("历史项目与当前项目不一致")
564 blocks = (row.get("message") or {}).get("content", [])
565 if not isinstance(blocks, list):
566 continue
567 for block in blocks:
568 if block.get("type") == "tool_use":
569 pending.add(block["id"])
570 elif block.get("type") == "tool_result":
571 pending.discard(block.get("tool_use_id"))
572 if pending:
573 raise ValueError("历史仍有结果未确认的工具,不能自动接续")
574 folder.mkdir(mode=0o700, parents=True, exist_ok=True)
575 target = folder / "history.jsonl"
576 with tempfile.NamedTemporaryFile(dir=folder, delete=False) as stream:
577 stream.write(path.read_bytes())
578 temporary = stream.name
579 os.replace(temporary, target)
580 save(receipt, {"binding": binding, "requests": state.get("requests", {})})
581 with state_file(connection) as state:
582 state["closed"] = True
583 return {"transcript": str(target)}
584
585
586def cancel_account_switch(request):
587 connection = identifier(request["connection"])
588 switch_id = identifier(request["switch_id"])
589 with state_file(connection) as state:
590 if state.get("cli_id") != identifier(request["cli_id"]) or state.get("account_switch") not in (None, switch_id):
591 raise ValueError("原会话交接已变化")
592 state.pop("account_switch", None)
593 # The source may already be stopped, but it remains resumable. Remove only
594 # this operation's frozen copy so a later retry cannot use stale history.
595 folder = ROOT.parent / "cli-account-switches" / switch_id
596 if folder.exists():
597 shutil.rmtree(folder)
598 return {"ok": True}
599
600
601def purge_session(request):
602 session_id = identifier(request["cli_id"])
603 config = Path(request["config"]) if request.get("config") else config_directory(request.get("account") or "default")
604 config = config.resolve()
605 workspace = request["workspace"].rstrip("/")
606 if active_session(session_id, str(config)):
607 raise ValueError("Claude Code 仍在运行这段会话,请先结束原终端中的 Claude Code")
608 projects = config / "projects"
609 if projects.is_symlink():
610 raise ValueError("会话目录是符号链接,请检查主机配置")
611 paths = list(projects.glob("*/" + session_id + ".jsonl"))
612 for path in paths:
613 if path.is_symlink() or path.parent.is_symlink():
614 raise ValueError("会话历史路径已变化,请检查主机配置")
615 directory, _ = history_summary(path)
616 if not workspace_within(directory, workspace):
617 raise ValueError("会话历史与已授权项目不一致")
618 key = hashlib.sha256((str(config) + "\n" + session_id).encode()).hexdigest()
619 receipt = ROOT.parent / "cli-deleted" / (key + ".json")
620 if not paths and request.get("expect_history") and not receipt.exists():
621 raise ValueError("当前账号配置中未找到原始会话,请核对主机配置后重试")
622 # The SDK's delete_session removes the transcript and its sibling session
623 # directory. Keep a content-free receipt so a lost response can be retried.
624 save(receipt, {"cli_id": session_id, "config": str(config), "complete": False})
625 for path in paths:
626 related = path.parent / session_id
627 if related.is_symlink():
628 related.unlink()
629 elif related.exists():
630 shutil.rmtree(related)
631 path.unlink(missing_ok=True)
632 for path in ROOT.glob("*/state.json"):
633 state = read_json(path, {})
634 if state.get("cli_id") == session_id and state.get("config") == str(config):
635 if live(state.get("pid")) and not state.get("closed"):
636 raise ValueError("会话通道尚未退出,请稍后重试")
637 shutil.rmtree(path.parent)
638 identity = ROOT.parent / "mobile-cli-identities" / session_id
639 identity.unlink(missing_ok=True)
640 handoff_receipt(config, session_id).unlink(missing_ok=True)
641 save(receipt, {"cli_id": session_id, "config": str(config), "complete": True})
642 for saved in (ROOT.parent / "cli-account-switches").glob("*/receipt.json"):
643 binding = read_json(saved, {}).get("binding", {})
644 if binding.get("cli_id") == session_id or binding.get("target_cli_id") == session_id:
645 shutil.rmtree(saved.parent)
646 return {"ok": True}
647
648
649def launch(request):
650 if os.name == "nt" and request.get("ccs_profile"):
651 return _platform["launch_ccs_parent"](request, globals())
652 policy_available = migrate_cage_policy()
653 connection = identifier(request["id"])
654 folder = ROOT / connection
655 folder.mkdir(parents=True, exist_ok=True, mode=0o700)
656 prefix = request["prefix"]
657 if os.name == "nt":
658 account_id = request.get("account") or "default"
659 os.environ["CLAUDE_CONFIG_DIR"] = str(config_directory(account_id))
660 if request.get("subject"):
661 os.environ["CAGE_CLAUDE_SUBJECT"] = request["subject"]
662 prefix = [os.environ["CAGE_CLI_BINARY"]]
663 request["prefix"] = prefix
664 elif len(prefix) == 5 and Path(prefix[2]).name == "cage-claude-account" and prefix[3] == "run":
665 os.environ["CLAUDE_CONFIG_DIR"] = str(config_directory(prefix[4]))
666 elif request.get("config"):
667 os.environ["CLAUDE_CONFIG_DIR"] = request["config"]
668 session_id = identifier(request.get("resume") or request.get("session_id") or connection)
669 _, previous = connection_for(session_id, config_directory("default"))
670 if request.get("resume"):
671 if active_session(request["resume"]):
672 raise ValueError("原会话仍在电脑终端运行,请先结束该终端中的 Claude Code 再接续")
673 command = shlex.join([sys.executable, *(["-X", "utf8"] if os.name == "nt" else []), "-I", str(Path(__file__).resolve()), "hook", connection])
674 events = ("SessionStart", "UserPromptSubmit", "MessageDisplay", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop", "StopFailure", "SessionEnd")
675 handler = {"type": "command", "command": command, "timeout": 5}
676 if os.name == "nt":
677 handler = {"type": "command", "command": sys.executable,
678 "args": ["-X", "utf8", "-I", str(Path(__file__).resolve()), "hook", connection], "timeout": 5}
679 settings = {"hooks": {event: [{"hooks": [handler.copy()]}] for event in events}}
680 prefix = request["prefix"]
681 if os.name == "nt":
682 account = runpy.run_path(os.environ["CAGE_CLI_ACCOUNT_HELPER"])
683 if not account["has_status_line"](account["profile"](account_id)):
684 status_command = shlex.join([sys.executable, "-X", "utf8", "-I", os.environ["CAGE_CLI_ACCOUNT_HELPER"], "statusline", account_id])
685 settings["statusLine"] = {"type": "command", "command": status_command}
686 elif len(prefix) == 5 and Path(prefix[2]).name == "cage-claude-account" and prefix[3] == "run":
687 account = runpy.run_path(prefix[2])
688 if not account["has_status_line"](account["profile"](prefix[4])):
689 settings["statusLine"] = {"type": "command", "command": prefix[2] + " statusline " + prefix[4]}
690 save(folder / "settings.json", settings)
691 config = {"mcpServers": {"cage": {"command": sys.executable, "args": [*(["-X", "utf8"] if os.name == "nt" else []), "-I", str(Path(__file__).resolve()), "serve", connection]}}}
692 save(folder / "mcp.json", config)
693 with state_file(connection) as state:
694 if live(state.get("pid")) and not state.get("closed"):
695 raise ValueError("目标会话已有进程,未重复启动")
696 state.update(cli_id=session_id, config=str(config_directory("default")),
697 workspace=str(Path.cwd()), pid=os.getpid(), closed=False, updated_at=time.time(), approvals=[], busy=False,
698 channel_pid=None, pending_send=None, display=None, stopped=False,
699 requests=previous.get("requests", {}), sent=previous.get("sent", []))
700 receipt = handoff_receipt(config_directory("default"), session_id)
701 transfer = read_json(receipt, {})
702 state["resume_task"] = previous.get("resume_task", False) or transfer.get("resume_task", False)
703 state["account_resume"] = previous.get("account_resume", False)
704 if request.get("resume_transcript"):
705 state["resume_transcript"] = request["resume_transcript"]
706 state["resume_task"] = bool(request.get("continue_after_switch"))
707 state["account_resume"] = True
708 transfer = read_json(ROOT.parent / "cli-account-switches" / identifier(request["switch_id"]) / "receipt.json", {})
709 state["requests"] = {**transfer.get("requests", {}), **state["requests"]}
710 state["handoff_permission_mode"] = transfer.get("permission_mode") or previous.get("handoff_permission_mode", "")
711 receipt.unlink(missing_ok=True)
712 for sent in state.get("sent", []):
713 sent["interrupted"] = True
714 try:
715 policy = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "ClaudeCode/managed-settings.json" if os.name == "nt" else Path("/Library/Application Support/ClaudeCode/managed-settings.json") if sys.platform == "darwin" else Path("/etc/claude-code/managed-settings.json")
716 managed = read_json(policy, {})
717 state["blocked"] = isinstance(managed, dict) and managed.get("channelsEnabled") is False
718 except (OSError, ValueError):
719 state["blocked"] = False
720 state["policy_unavailable"] = policy_available is False
721 args = [*request["prefix"], "--settings", str(folder / "settings.json"), "--mcp-config", str(folder / "mcp.json"),
722 "--dangerously-load-development-channels", "server:cage"]
723 if request.get("resume_transcript"):
724 expected = ROOT.parent / "cli-account-switches" / identifier(request["switch_id"]) / "history.jsonl"
725 if Path(request["resume_transcript"]) != expected or not expected.is_file():
726 raise ValueError("账号交接历史无效")
727 args += ["--resume", str(expected), "--fork-session", "--session-id", session_id]
728 else:
729 args += ["--resume", session_id] if request.get("resume") else ["--session-id", session_id]
730 if state.get("handoff_permission_mode") == "manual":
731 args += ["--permission-mode", "manual"]
732 if os.name == "nt":
733 return _platform["launch_cli"](args, request, connection, state_file)
734 os.execvpe(args[0], args, os.environ)
735
736
737def rpc(request):
738 connection = identifier(request["connection"])
739 os.chdir(ROOT / connection)
740 with socket.socket(socket.AF_UNIX) as client:
741 client.settimeout(5)
742 client.connect("rpc")
743 client.sendall(json.dumps(request).encode() + b"\n")
744 with client.makefile("rb") as stream:
745 return json.loads(stream.readline(1 << 20))
746
747
748def serve(connection):
749 connection = identifier(connection)
750 output_lock = threading.Lock()
751
752 def emit(message):
753 with output_lock:
754 sys.stdout.write(json.dumps({"jsonrpc": "2.0", **message}) + "\n")
755 sys.stdout.flush()
756
757 class Handler(socketserver.StreamRequestHandler):
758 def handle(self):
759 self.connection.settimeout(5)
760 try:
761 request = json.loads(self.rfile.readline(72 << 10))
762 with state_file(connection) as state:
763 if request["cli_id"] != state.get("cli_id") or state.get("closed"):
764 raise ValueError("终端已切换会话,请重新读取列表")
765 action = request["action"]
766 if state.get("account_switch"):
767 raise ValueError("此会话正在切换账号,请等待交接完成")
768 if action == "send":
769 request_id = identifier(request["request_id"])
770 text = request["text"]
771 if not text.strip() or len(text.encode()) > PROMPT_LIMIT:
772 raise ValueError("消息为空或过长")
773 digest = hashlib.sha256(text.encode()).hexdigest()
774 requests = state.setdefault("requests", {})
775 previous = requests.get(request_id)
776 if previous is not None:
777 if previous != digest:
778 raise ValueError("同一发送编号已用于另一条消息")
779 else:
780 if state.get("busy") or state.get("pending_send"):
781 raise ValueError("这段会话已有消息正在处理,请等待后重试")
782 state.pop("stopped", None)
783 state["pending_send"] = request_id
784 requests[request_id] = digest
785 state.setdefault("sent", []).append({"id": request_id, "text": text})
786 # Persist admission before writing to the CLI. A lost
787 # acknowledgement must never replay a channel event.
788 save(ROOT / connection / "state.json", state)
789 emit({"method": "notifications/claude/channel", "params": {"content": text, "meta": {"cage_request": request_id}}})
790 elif action == "approve":
791 pending = state.get("approvals", [])
792 if not pending or pending[0]["id"] != request["approval_id"] or type(request["allow"]) is not bool:
793 raise ValueError("审批已结束,请重新读取会话")
794 approval = pending.pop(0)
795 emit({"method": "notifications/claude/channel/permission", "params": {
796 "request_id": approval["relay_id"], "behavior": "allow" if request["allow"] else "deny"}})
797 elif action == "stop":
798 state["stopped"] = True
799 state["busy"] = False
800 state["approvals"] = []
801 elif action == "resume":
802 if state.get("resume_task"):
803 state["resume_task"] = False
804 state["busy"] = True
805 # Commit before notification; reconnecting must not
806 # inject the same continuation twice.
807 save(ROOT / connection / "state.json", state)
808 emit({"method": "notifications/claude/channel", "params": {
809 "content": Path(__file__).with_suffix(".account-resume.md" if state.get("account_resume") else ".resume.md").read_text(encoding="utf-8"),
810 "meta": {"cage_resume": "true"}}})
811 else:
812 raise ValueError("unsupported operation")
813 state["updated_at"] = time.time()
814 response = {"ok": True}
815 except (OSError, ValueError, KeyError, TypeError) as error:
816 response = {"error": str(error)}
817 self.wfile.write(json.dumps(response).encode() + b"\n")
818
819 os.chdir(ROOT / connection)
820 address = "rpc"
821 # A connection UUID is created once by the host. A second live server must
822 # fail to bind instead of stealing the first server's socket.
823 if Path(address).is_socket():
824 with socket.socket(socket.AF_UNIX) as probe:
825 try:
826 probe.connect(address)
827 except ConnectionRefusedError:
828 Path(address).unlink()
829 else:
830 raise ValueError("会话通道已在运行")
831 with socketserver.ThreadingUnixStreamServer(address, Handler) as server:
832 server.daemon_threads = True
833 os.chmod(address, 0o600)
834 threading.Thread(target=server.serve_forever, daemon=True).start()
835 try:
836 for line in sys.stdin:
837 message = json.loads(line)
838 method = message.get("method")
839 if method == "initialize":
840 emit({"id": message["id"], "result": {"protocolVersion": "2024-11-05", "serverInfo": {"name": "cage", "version": "1"},
841 "capabilities": {"experimental": {"claude/channel": {}, "claude/channel/permission": {}}},
842 "instructions": "The user is viewing this same Claude Code conversation from Cage on a phone. Respond normally in the conversation. Cage synchronizes the transcript."}})
843 elif method == "notifications/initialized":
844 with state_file(connection) as state:
845 state["channel_pid"] = os.getpid()
846 state["updated_at"] = time.time()
847 elif method == "notifications/claude/channel/permission_request":
848 params = message["params"]
849 preview = params.get("input_preview", "")
850 try:
851 arguments = json.loads(preview)
852 except ValueError:
853 arguments = {"preview": preview}
854 with state_file(connection) as state:
855 state.setdefault("approvals", []).append({"id": str(uuid.uuid4()), "relay_id": params["request_id"],
856 "tool": params["tool_name"], "input": arguments, "preview": True})
857 state["updated_at"] = time.time()
858 elif "id" in message:
859 if method == "ping":
860 emit({"id": message["id"], "result": {}})
861 else:
862 emit({"id": message["id"], "error": {"code": -32601, "message": "Method not supported"}})
863 finally:
864 server.shutdown()
865 Path(address).unlink(missing_ok=True)
866 with state_file(connection) as state:
867 state["channel_pid"] = None
868 state["approvals"] = []
869
870
871def main():
872 os.umask(0o077)
873 mode, argument = sys.argv[1:3]
874 if mode == "ccs-live" and os.name == "nt":
875 return _platform["launch_ccs_live"](argument, globals())
876 if mode == "serve":
877 return serve(argument)
878 if mode == "hook":
879 result = hook(argument)
880 else:
881 request = json.load(sys.stdin) if argument == "-" else json.loads(argument)
882 if mode == "launch":
883 return launch(request)
884 if mode == "discover":
885 result = discover(request)
886 elif mode == "view":
887 config = Path(request["config"]) if request.get("config") else config_directory(request.get("account") or "default")
888 state = read_json(ROOT / identifier(request.get("connection") or request["cli_id"]) / "state.json", {})
889 if state.get("cli_id") == request["cli_id"] and state.get("config"):
890 config = Path(state["config"])
891 result = view(config, identifier(request["cli_id"]))
892 elif mode == "rpc":
893 result = rpc(request)
894 elif mode == "active":
895 config = request.get("config") or str(config_directory(request.get("account") or "default"))
896 result = {"running": active_session(identifier(request["cli_id"]), config)}
897 elif mode == "handoff":
898 try:
899 result = handoff_session(request)
900 except (OSError, ValueError, subprocess.SubprocessError) as error:
901 result = {"error": str(error)}
902 elif mode == "purge":
903 try:
904 result = purge_session(request)
905 except (OSError, ValueError, subprocess.SubprocessError) as error:
906 result = {"error": str(error)}
907 elif mode == "account-switch":
908 try:
909 result = prepare_account_switch(request)
910 except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error:
911 result = {"error": str(error)}
912 elif mode == "account-switch-cancel":
913 try:
914 result = cancel_account_switch(request)
915 except (OSError, ValueError, KeyError) as error:
916 result = {"error": str(error)}
917 else:
918 raise ValueError("unsupported operation")
919 print(json.dumps(result, ensure_ascii=False))
920
921
922if __name__ == "__main__":
923 sys.exit(main() or 0)