跳到主要内容

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

浏览文件

guest-session.py

81 行 · 2.6 KB历史下载
1"""Run the workbench's control scripts over one SSH connection.
2
3Requests: "R <id> <length>\n" followed by the script, or "C <id>\n" to stop
4one. Replies: "D <id> <exit> <stdout length> <stderr length>\n" and both.
5"""
6import os
7import signal
8import subprocess
9import sys
10import threading
11
12# Above the caller's 64 KiB limit, so that it can tell an oversized answer.
13OUTPUT_LIMIT = 64 * 1024 + 256
14ERROR_LIMIT = 4096
15SCRIPT_LIMIT = 1 << 20
16requests, replies = sys.stdin.buffer, sys.stdout.buffer
17writing = threading.Lock()
18running = {}
19
20
21def stop(child):
22 try:
23 os.killpg(child.pid, signal.SIGKILL)
24 except OSError:
25 pass
26
27
28def keep(pipe, limit, exceeded=None):
29 """The first `limit` bytes. The rest is read and dropped, or refused."""
30 data = b''
31 while True:
32 chunk = pipe.read1(65536)
33 if not chunk:
34 return data
35 data += chunk[:limit - len(data)]
36 if len(data) == limit and exceeded:
37 exceeded()
38 exceeded = None
39
40
41def run(ident, script):
42 code, output, errors = 127, b'', []
43 try:
44 child = subprocess.Popen(['/bin/bash', '--noprofile', '--norc', '-c', script], stdin=subprocess.DEVNULL,
45 stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
46 except OSError as error:
47 errors.append(str(error).encode()[:ERROR_LIMIT])
48 else:
49 running[ident] = child
50 drain = threading.Thread(target=lambda: errors.append(keep(child.stderr, ERROR_LIMIT)), daemon=True)
51 drain.start()
52 output = keep(child.stdout, OUTPUT_LIMIT, lambda: stop(child))
53 code = child.wait()
54 drain.join()
55 running.pop(ident, None)
56 with writing:
57 replies.write(b'D %d %d %d %d\n' % (ident, code, len(output), len(errors[0])) + output + errors[0])
58 replies.flush()
59
60
61replies.write(b'CAGE-GUEST-SESSION 1\n')
62replies.flush()
63while True:
64 fields = requests.readline(64).split()
65 try:
66 if len(fields) == 3 and fields[0] == b'R' and 0 < int(fields[2]) <= SCRIPT_LIMIT:
67 script = requests.read(int(fields[2]))
68 if len(script) != int(fields[2]):
69 break
70 threading.Thread(target=run, args=(int(fields[1]), script.decode()), daemon=True).start()
71 elif len(fields) == 2 and fields[0] == b'C':
72 child = running.get(int(fields[1]))
73 if child:
74 stop(child)
75 else:
76 break
77 except ValueError:
78 break
79# The connection closed: nothing is left to receive an answer.
80for child in list(running.values()):
81 stop(child)