跳到主要内容

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

浏览文件

guest_session.go

279 行 · 7.2 KB历史下载
1package workbench
2
3import (
4 "bufio"
5 "context"
6 _ "embed"
7 "errors"
8 "fmt"
9 "io"
10 "os/exec"
11 "strconv"
12 "strings"
13 "sync"
14 "time"
15
16 "al.essio.dev/pkg/shellescape"
17)
18
19//go:embed guest-session.py
20var guestSessionServer string
21
22const (
23 guestSessionReady = "CAGE-GUEST-SESSION 1"
24 guestSessionIdle = 30 * time.Second
25 guestSessionRetry = 30 * time.Second
26 guestSessionStartup = 5 * time.Second
27)
28
29var errGuestSessionEnded = errors.New("guest control session ended")
30
31type guestSessionReply struct {
32 code int
33 stdout, stderr []byte
34}
35
36// guestSession carries control scripts to a Linux guest over one SSH
37// connection. Opening a connection per script costs a key exchange, a login
38// shell and several processes on both sides, while status polls and display
39// changes arrive every second or two. It closes after a short idle period.
40type guestSession struct {
41 mu sync.Mutex
42 conn *guestSessionConn
43 retryAt time.Time
44 idle *time.Timer
45}
46
47type guestSessionConn struct {
48 cancel context.CancelFunc
49 stdin io.WriteCloser
50 writing sync.Mutex
51 mu sync.Mutex
52 waiting map[uint64]chan guestSessionReply
53 next uint64
54 ended chan struct{}
55}
56
57func (c *guestSessionConn) close() { c.cancel(); _ = c.stdin.Close() }
58
59func (c *guestSessionConn) alive() bool {
60 select {
61 case <-c.ended:
62 return false
63 default:
64 return true
65 }
66}
67
68func (c *guestSessionConn) receive(output *bufio.Reader, done func()) {
69 defer done()
70 defer close(c.ended)
71 defer c.close()
72 for {
73 line, err := output.ReadString('\n')
74 if err != nil {
75 return
76 }
77 fields := strings.Fields(line)
78 if len(fields) != 5 || fields[0] != "D" {
79 return
80 }
81 id, idErr := strconv.ParseUint(fields[1], 10, 64)
82 code, codeErr := strconv.Atoi(fields[2])
83 outSize, outErr := strconv.Atoi(fields[3])
84 errSize, errErr := strconv.Atoi(fields[4])
85 if idErr != nil || codeErr != nil || outErr != nil || errErr != nil || outSize < 0 || outSize > 1<<20 || errSize < 0 || errSize > 1<<16 {
86 return
87 }
88 data := make([]byte, outSize+errSize)
89 if _, err = io.ReadFull(output, data); err != nil {
90 return
91 }
92 c.mu.Lock()
93 waiter := c.waiting[id]
94 delete(c.waiting, id)
95 c.mu.Unlock()
96 if waiter != nil {
97 waiter <- guestSessionReply{code: code, stdout: data[:outSize], stderr: data[outSize:]}
98 }
99 }
100}
101
102// openGuestSession starts the server on the guest. The command's stdin and
103// stdout belong to the returned connection.
104func openGuestSession(parent context.Context, command func(context.Context) *exec.Cmd) (*guestSessionConn, error) {
105 ctx, cancel := context.WithCancel(parent)
106 cmd := command(ctx)
107 stdin, err := cmd.StdinPipe()
108 if err != nil {
109 cancel()
110 return nil, err
111 }
112 stdout, err := cmd.StdoutPipe()
113 if err != nil {
114 cancel()
115 return nil, err
116 }
117 if err = cmd.Start(); err != nil {
118 cancel()
119 return nil, err
120 }
121 conn := &guestSessionConn{cancel: cancel, stdin: stdin, waiting: map[uint64]chan guestSessionReply{}, ended: make(chan struct{})}
122 output := bufio.NewReaderSize(stdout, 64<<10)
123 ready := make(chan error, 1)
124 go func() {
125 // A login shell may print before the server starts.
126 for skipped := 0; skipped < 64; skipped++ {
127 line, err := output.ReadString('\n')
128 if err != nil {
129 ready <- err
130 return
131 }
132 if strings.TrimSpace(line) == guestSessionReady {
133 ready <- nil
134 return
135 }
136 }
137 ready <- errors.New("guest control session did not start")
138 }()
139 select {
140 case err = <-ready:
141 case <-time.After(guestSessionStartup):
142 err = errors.New("guest control session start timed out")
143 case <-ctx.Done():
144 err = ctx.Err()
145 }
146 if err != nil {
147 conn.close()
148 _ = cmd.Wait()
149 return nil, err
150 }
151 go conn.receive(output, func() { _ = cmd.Wait() })
152 return conn, nil
153}
154
155// run sends one script. sent reports whether the guest may have started it:
156// when false, the caller can safely use a connection of its own instead.
157func (g *guestSession) run(ctx context.Context, lifetime context.Context, command func(context.Context) *exec.Cmd, script string) (reply guestSessionReply, sent bool, err error) {
158 g.mu.Lock()
159 conn := g.conn
160 if conn == nil || !conn.alive() {
161 g.conn = nil
162 if time.Now().Before(g.retryAt) {
163 g.mu.Unlock()
164 return reply, false, errGuestSessionEnded
165 }
166 if conn, err = openGuestSession(lifetime, command); err != nil {
167 g.retryAt = time.Now().Add(guestSessionRetry)
168 g.mu.Unlock()
169 return reply, false, err
170 }
171 g.conn = conn
172 }
173 if g.idle != nil {
174 g.idle.Stop()
175 }
176 conn.mu.Lock()
177 conn.next++
178 id, waiter := conn.next, make(chan guestSessionReply, 1)
179 conn.waiting[id] = waiter
180 conn.mu.Unlock()
181 g.mu.Unlock()
182 defer g.release(conn)
183 forget := func() { conn.mu.Lock(); delete(conn.waiting, id); conn.mu.Unlock() }
184 conn.writing.Lock()
185 _, err = io.WriteString(conn.stdin, fmt.Sprintf("R %d %d\n%s", id, len(script), script))
186 conn.writing.Unlock()
187 if err != nil {
188 // A partial request never runs: the server needs its full length.
189 forget()
190 conn.close()
191 return reply, false, err
192 }
193 select {
194 case reply = <-waiter:
195 return reply, true, nil
196 case <-ctx.Done():
197 forget()
198 conn.writing.Lock()
199 _, _ = io.WriteString(conn.stdin, fmt.Sprintf("C %d\n", id))
200 conn.writing.Unlock()
201 return reply, true, ctx.Err()
202 case <-conn.ended:
203 forget()
204 return reply, true, errGuestSessionEnded
205 }
206}
207
208func (g *guestSession) release(conn *guestSessionConn) {
209 g.mu.Lock()
210 defer g.mu.Unlock()
211 conn.mu.Lock()
212 busy := len(conn.waiting) > 0
213 conn.mu.Unlock()
214 if busy || g.conn != conn {
215 return
216 }
217 if g.idle != nil {
218 g.idle.Stop()
219 }
220 g.idle = time.AfterFunc(guestSessionIdle, func() {
221 g.mu.Lock()
222 defer g.mu.Unlock()
223 conn.mu.Lock()
224 busy := len(conn.waiting) > 0
225 conn.mu.Unlock()
226 if g.conn == conn && !busy {
227 g.conn = nil
228 conn.close()
229 }
230 })
231}
232
233// close ends the connection; a script still running on it reports an error.
234func (g *guestSession) close() {
235 g.mu.Lock()
236 defer g.mu.Unlock()
237 if g.idle != nil {
238 g.idle.Stop()
239 }
240 if g.conn != nil {
241 g.conn.close()
242 g.conn = nil
243 }
244 g.retryAt = time.Time{}
245}
246
247func (s *Server) guestSessionCommand(ctx context.Context) *exec.Cmd {
248 return s.sshCommand(ctx, "-T", s.sshTarget(), "--", "exec /usr/bin/python3 -I -u -c "+shellescape.Quote(guestSessionServer))
249}
250
251// guestShared runs a script on the shared connection. ok is false when the
252// script was not sent and the caller should open a connection of its own.
253func (s *Server) guestShared(ctx context.Context, script string) (reply guestSessionReply, ok bool, err error) {
254 if s.windowsGuest != nil || s.macosGuest != nil {
255 return reply, false, nil
256 }
257 reply, sent, err := s.controlSession.run(ctx, s.lifetimeContext(), s.guestSessionCommand, script)
258 return reply, sent, err
259}
260
261// guestQuick is guest for idempotent scripts that run often or while the
262// user waits: status polls and display changes share one SSH connection.
263// The scripts must not depend on environment changed after it was opened.
264func (s *Server) guestQuick(ctx context.Context, script string) ([]byte, error) {
265 reply, ok, err := s.guestShared(ctx, script)
266 if !ok {
267 return s.guest(ctx, script)
268 }
269 if err != nil {
270 return nil, err
271 }
272 if len(reply.stdout) > 64<<10 {
273 return nil, errors.New("guest control response exceeded its limit")
274 }
275 if reply.code != 0 {
276 return nil, fmt.Errorf("guest control script: exit status %d", reply.code)
277 }
278 return reply.stdout, nil
279}