跳到主要内容

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

浏览文件

shared_clipboard.go

603 行 · 17.9 KB历史下载
1package workbench
2
3import (
4 "bufio"
5 "bytes"
6 "compress/zlib"
7 "context"
8 "encoding/base64"
9 "encoding/json"
10 "errors"
11 "io"
12 "net/http"
13 "net/url"
14 "os/exec"
15 "path/filepath"
16 "slices"
17 "sync"
18 "time"
19
20 "al.essio.dev/pkg/shellescape"
21 "github.com/google/uuid"
22 "github.com/sylvinus/agent-vm/internal/cage"
23 "github.com/sylvinus/agent-vm/internal/clipboardfiles"
24 "github.com/sylvinus/agent-vm/internal/guestos"
25)
26
27const clipboardWireLimit = 30 << 20
28
29// 保留当前后端配套的客机脚本,使已有 Linux 客机也能建立剪贴板连接。
30// 将脚本压缩为单个参数,避免完整脚本经过两层转义后超出 Windows 进程命令行上限。
31var linuxClipboardCommand = sync.OnceValues(func() (string, error) {
32 var compressed bytes.Buffer
33 writer := zlib.NewWriter(&compressed)
34 if _, err := io.WriteString(writer, cage.SharedClipboardHelper); err != nil {
35 return "", err
36 }
37 if err := writer.Close(); err != nil {
38 return "", err
39 }
40 // 移除载荷参数后,辅助脚本仍收到原有操作参数,stdin 也仍用于剪贴板协议。
41 const bootstrap = `import base64,sys,zlib; exec(compile(zlib.decompress(base64.b64decode(sys.argv.pop(1))), '<cage-shared-clipboard>', 'exec'))`
42 return "exec sudo -n /usr/bin/python3 -c " + shellescape.Quote(bootstrap) + " " +
43 base64.StdEncoding.EncodeToString(compressed.Bytes()), nil
44})
45
46type clipboardPayload struct {
47 Hello *clipboardHello `json:"hello,omitempty"`
48 Text *string `json:"text,omitempty"`
49 PNG string `json:"png,omitempty"`
50 Files json.RawMessage `json:"files,omitempty"`
51 Error string `json:"error,omitempty"`
52 Source string `json:"source,omitempty"`
53 Serial int `json:"serial,omitempty"`
54 Ack int `json:"ack,omitempty"`
55 Release []string `json:"release,omitempty"`
56}
57
58type clipboardHello struct {
59 Version int `json:"version"`
60 OS string `json:"os"`
61 Session string `json:"session"`
62 Formats []string `json:"formats"`
63 Available bool `json:"available"`
64 FileRelease bool `json:"file_release,omitempty"`
65}
66
67// The profile chooses the transport. A guest file selection can never choose
68// an executable, account, remote command or host path.
69func (s *Server) clipboardCommand(ctx context.Context, operation string, selection clipboardFileSelection) (*exec.Cmd, string, error) {
70 win, err := guestos.LoadWindowsProfile(s.profile)
71 if err != nil {
72 return nil, "", err
73 }
74 if win != nil {
75 if s.macosGuest != nil {
76 return nil, "", errors.New("客机绑定冲突")
77 }
78 args := []string{}
79 if operation == "export" {
80 args = append(args, "--paths-stdin")
81 }
82 cmd, err := guestos.WindowsRelayCommand(ctx, s.profile, operation, args...)
83 if err == nil && operation == "export" {
84 data, _ := json.Marshal(selection.Paths)
85 cmd.Stdin = bytes.NewReader(data)
86 }
87 return cmd, "guest", err
88 }
89 if s.macosGuest != nil {
90 if operation != "stream" && operation != "import" && operation != "export" && operation != "upload" && operation != "request" {
91 return nil, "", errors.New("剪贴板操作无效")
92 }
93 if operation == "export" && selection.User != "guest" {
94 return nil, "", errors.New("剪贴板文件来源无效")
95 }
96 command := "exec '/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard' --client " + operation
97 cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
98 if operation == "export" {
99 data, _ := json.Marshal(selection.Paths)
100 cmd.Stdin = bytes.NewReader(data)
101 }
102 return cmd, "guest", nil
103 }
104 command, err := linuxClipboardCommand()
105 if err != nil {
106 return nil, "", err
107 }
108 switch operation {
109 case "stream":
110 case "import":
111 s.mu.Lock()
112 session := s.clipboardGuestSession
113 s.mu.Unlock()
114 command += " --import --session " + shellescape.Quote(session)
115 case "export":
116 if selection.User != "cage" && selection.User != "cage-browser" {
117 return nil, "", errors.New("剪贴板文件来源无效")
118 }
119 command += " --export-user " + selection.User + " --paths-stdin"
120 default:
121 return nil, "", errors.New("剪贴板操作无效")
122 }
123 cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
124 if operation == "export" {
125 data, _ := json.Marshal(selection.Paths)
126 cmd.Stdin = bytes.NewReader(data)
127 }
128 return cmd, "cage", nil
129}
130
131type clipboardFileSelection struct {
132 Paths []string
133 User string
134 lease *clipboardFileLease
135}
136
137type clipboardFileLease struct {
138 readers int
139 retired bool
140 release func()
141}
142
143func (s *Server) registerClipboardFiles(paths []string, user string) string {
144 s.mu.Lock()
145 if s.clipboardFiles == nil {
146 s.clipboardFiles = map[string]clipboardFileSelection{}
147 }
148 for id, previous := range s.clipboardFiles {
149 if previous.User == user && slices.Equal(previous.Paths, paths) {
150 s.mu.Unlock()
151 return id
152 }
153 }
154 // These are transient selection references, never file contents or history.
155 var releases []func()
156 if len(s.clipboardFiles) >= 100 {
157 releases = s.retireClipboardFilesLocked()
158 }
159 id := uuid.NewString()
160 ownedPaths := append([]string(nil), paths...)
161 lease := &clipboardFileLease{}
162 if release := s.clipboardRelease; release != nil {
163 lease.release = func() { release(ownedPaths) }
164 }
165 s.clipboardFiles[id] = clipboardFileSelection{Paths: ownedPaths, User: user, lease: lease}
166 s.mu.Unlock()
167 for _, release := range releases {
168 release()
169 }
170 return id
171}
172
173func (s *Server) retireClipboardFilesLocked() []func() {
174 var releases []func()
175 for id, selection := range s.clipboardFiles {
176 delete(s.clipboardFiles, id)
177 if selection.lease != nil {
178 selection.lease.retired = true
179 if selection.lease.readers == 0 && selection.lease.release != nil {
180 releases = append(releases, selection.lease.release)
181 }
182 }
183 }
184 return releases
185}
186
187func (s *Server) clearClipboardFiles() {
188 s.mu.Lock()
189 releases := s.retireClipboardFilesLocked()
190 s.mu.Unlock()
191 for _, release := range releases {
192 release()
193 }
194}
195
196func (s *Server) releaseClipboardFiles(id string) {
197 s.mu.Lock()
198 selection := s.clipboardFiles[id]
199 delete(s.clipboardFiles, id)
200 var release func()
201 if selection.lease != nil {
202 selection.lease.retired = true
203 if selection.lease.readers == 0 {
204 release = selection.lease.release
205 }
206 }
207 s.mu.Unlock()
208 if release != nil {
209 release()
210 }
211}
212
213func (s *Server) acquireClipboardFiles(id string) (clipboardFileSelection, func()) {
214 s.mu.Lock()
215 selection := s.clipboardFiles[id]
216 if selection.lease != nil {
217 selection.lease.readers++
218 }
219 s.mu.Unlock()
220 return selection, func() {
221 var release func()
222 s.mu.Lock()
223 if selection.lease != nil {
224 selection.lease.readers--
225 if selection.lease.retired && selection.lease.readers == 0 {
226 release = selection.lease.release
227 }
228 }
229 s.mu.Unlock()
230 if release != nil {
231 release()
232 }
233 }
234}
235
236func (s *Server) clipboardFileSelection(id string) clipboardFileSelection {
237 s.mu.Lock()
238 defer s.mu.Unlock()
239 selection := s.clipboardFiles[id]
240 selection.Paths = append([]string(nil), selection.Paths...)
241 return selection
242}
243
244func (s *Server) sharedClipboard(w http.ResponseWriter, r *http.Request) {
245 s.mu.Lock()
246 available := s.ready && !s.closing && s.clipboardCancel == nil
247 ctx, cancel := context.WithCancel(r.Context())
248 if available {
249 s.clipboardCancel = cancel
250 }
251 s.mu.Unlock()
252 if !available {
253 cancel()
254 http.Error(w, "剪贴板连接暂不可用", http.StatusConflict)
255 return
256 }
257 defer func() { cancel(); s.mu.Lock(); s.clipboardCancel = nil; s.clipboardRelease = nil; s.mu.Unlock() }()
258 // 以当前后端配套的辅助脚本启动连接,保留 stdin/stdout 传输剪贴板数据。
259 cmd, source, err := s.clipboardCommand(ctx, "stream", clipboardFileSelection{})
260 if err != nil {
261 http.Error(w, "剪贴板客机配置无效", 502)
262 return
263 }
264 in, err := cmd.StdinPipe()
265 if err != nil {
266 http.Error(w, "剪贴板连接失败", 502)
267 return
268 }
269 out, err := cmd.StdoutPipe()
270 if err != nil {
271 in.Close()
272 http.Error(w, "剪贴板连接失败", 502)
273 return
274 }
275 if err = cmd.Start(); err != nil {
276 in.Close()
277 out.Close()
278 http.Error(w, "剪贴板连接失败", 502)
279 return
280 }
281 defer func() { cancel(); in.Close(); out.Close(); _ = cmd.Wait() }()
282 ws, err := s.upgrade(w, r)
283 if err != nil {
284 return
285 }
286 defer ws.Close()
287 ws.SetReadLimit(clipboardWireLimit)
288 var writeMu sync.Mutex
289 writeGuest := func(payload clipboardPayload) error {
290 writeMu.Lock()
291 defer writeMu.Unlock()
292 timeout := time.AfterFunc(8*time.Second, func() { cancel(); in.Close() })
293 defer timeout.Stop()
294 return json.NewEncoder(in).Encode(payload)
295 }
296 done := make(chan struct{})
297 go func() {
298 defer close(done)
299 defer ws.Close()
300 scanner := bufio.NewScanner(out)
301 scanner.Buffer(make([]byte, 64<<10), clipboardWireLimit)
302 for scanner.Scan() {
303 var payload clipboardPayload
304 if json.Unmarshal(scanner.Bytes(), &payload) != nil {
305 return
306 }
307 if payload.Hello != nil {
308 hello := payload.Hello
309 expectedOS := "linux"
310 if source == "guest" {
311 expectedOS = "windows"
312 if s.macosGuest != nil {
313 expectedOS = "darwin"
314 }
315 }
316 if hello.Version != 1 || hello.OS != expectedOS || len(hello.Session) == 0 || len(hello.Session) > 256 {
317 return
318 }
319 s.mu.Lock()
320 changed := s.clipboardGuestSession != "" && s.clipboardGuestSession != hello.Session
321 s.mu.Unlock()
322 if changed {
323 s.clearClipboardFiles()
324 }
325 s.mu.Lock()
326 s.clipboardGuestSession = hello.Session
327 if hello.FileRelease {
328 s.clipboardRelease = func(paths []string) { _ = writeGuest(clipboardPayload{Release: paths}) }
329 } else {
330 s.clipboardRelease = nil
331 }
332 s.mu.Unlock()
333 }
334 if payload.Files != nil {
335 var paths []string
336 if json.Unmarshal(payload.Files, &paths) != nil || len(paths) == 0 || len(paths) > 100 {
337 return
338 }
339 if payload.Source != source && !(source == "cage" && payload.Source == "cage-browser") {
340 return
341 }
342 payload.Files, _ = json.Marshal(s.registerClipboardFiles(paths, payload.Source))
343 payload.Source = ""
344 }
345 _ = ws.SetWriteDeadline(time.Now().Add(15 * time.Second))
346 if ws.WriteJSON(payload) != nil {
347 return
348 }
349 }
350 }()
351 defer func() {
352 cancel()
353 in.Close()
354 out.Close()
355 ws.Close()
356 <-done
357 s.clearClipboardFiles()
358 }()
359 for {
360 var payload clipboardPayload
361 if ws.ReadJSON(&payload) != nil {
362 return
363 }
364 if payload.Release != nil {
365 return
366 }
367 if payload.Files != nil {
368 var id string
369 if json.Unmarshal(payload.Files, &id) != nil {
370 return
371 }
372 paths := s.clipboardFileSelection(id).Paths
373 if len(paths) == 0 {
374 return
375 }
376 payload.Files, _ = json.Marshal(paths)
377 }
378 if writeGuest(payload) != nil {
379 return
380 }
381 }
382}
383
384func (s *Server) clipboardArchive(w http.ResponseWriter, r *http.Request) {
385 if r.Method == http.MethodDelete {
386 s.releaseClipboardFiles(r.PathValue("id"))
387 jsonReply(w, map[string]bool{"ok": true})
388 return
389 }
390 ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute)
391 defer cancel()
392 if !s.vmRunning() {
393 http.Error(w, "请先启动环境", 409)
394 return
395 }
396 if r.Method == "GET" {
397 selection, release := s.acquireClipboardFiles(r.PathValue("id"))
398 defer release()
399 paths := selection.Paths
400 if len(paths) == 0 {
401 http.Error(w, "剪贴板文件已过期,请重新复制", 404)
402 return
403 }
404 // Export with the copying application's permissions. A URI written by
405 // a guest application cannot grant access to root-only files.
406 cmd, _, err := s.clipboardCommand(ctx, "export", selection)
407 if err != nil {
408 http.Error(w, "读取剪贴板文件失败", 502)
409 return
410 }
411 out, err := cmd.StdoutPipe()
412 if err != nil || cmd.Start() != nil {
413 http.Error(w, "读取剪贴板文件失败", 502)
414 return
415 }
416 defer out.Close()
417 w.Header().Set("Content-Type", "application/x-tar")
418 w.Header().Set("Trailer", "X-Cage-Clipboard-Status")
419 _, copied := io.Copy(w, out)
420 if copied != nil {
421 cancel()
422 }
423 finished := cmd.Wait()
424 status := "failed"
425 if copied == nil && finished == nil {
426 status = "ok"
427 }
428 w.Header().Set("X-Cage-Clipboard-Status", status)
429 return
430 }
431 cmd, source, err := s.clipboardCommand(ctx, "import", clipboardFileSelection{})
432 if err != nil {
433 http.Error(w, "传递剪贴板文件失败", 502)
434 return
435 }
436 cmd.Stdin = http.MaxBytesReader(w, r.Body, 201<<30)
437 out, err := cmd.StdoutPipe()
438 if err != nil || cmd.Start() != nil {
439 http.Error(w, "传递剪贴板文件失败", 502)
440 return
441 }
442 data, err := io.ReadAll(io.LimitReader(out, 65537))
443 out.Close()
444 finished := cmd.Wait()
445 var result struct {
446 Paths []string `json:"paths"`
447 }
448 if err != nil || finished != nil || len(data) > 65536 || json.Unmarshal(data, &result) != nil || len(result.Paths) == 0 {
449 http.Error(w, "传递剪贴板文件失败,请核对文件大小和名称", 502)
450 return
451 }
452 jsonReply(w, map[string]string{"files": s.registerClipboardFiles(result.Paths, source)})
453}
454
455// clipboardCopy reads only the new text produced by an explicit web copy.
456// The UI sends the keys on its existing window input queue between both phases.
457func (s *Server) clipboardCopy(w http.ResponseWriter, r *http.Request) {
458 if s.macosGuest == nil {
459 http.NotFound(w, r)
460 return
461 }
462 var request struct {
463 Phase string `json:"phase"`
464 Session string `json:"session"`
465 Revision *int `json:"revision"`
466 }
467 if !readJSON(w, r, &request) {
468 return
469 }
470 if request.Phase != "prepare" && request.Phase != "read" ||
471 request.Phase == "read" && (request.Revision == nil || *request.Revision < 0 || len(request.Session) == 0 || len(request.Session) > 256) {
472 http.Error(w, "剪贴板复制请求无效", http.StatusBadRequest)
473 return
474 }
475 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
476 defer cancel()
477 cmd, _, err := s.clipboardCommand(ctx, "request", clipboardFileSelection{})
478 if err != nil {
479 http.Error(w, "无法连接客机剪贴板", http.StatusBadGateway)
480 return
481 }
482 body, _ := json.Marshal(map[string]any{"operation": "copy-" + request.Phase, "revision": request.Revision, "session": request.Session})
483 cmd.Stdin = bytes.NewReader(append(body, '\n'))
484 out, err := cmd.StdoutPipe()
485 if err != nil || cmd.Start() != nil {
486 http.Error(w, "无法连接客机剪贴板", http.StatusBadGateway)
487 return
488 }
489 data, readErr := io.ReadAll(io.LimitReader(out, clipboardWireLimit+1))
490 out.Close()
491 finished := cmd.Wait()
492 var result struct {
493 Text *string `json:"text,omitempty"`
494 Session string `json:"session"`
495 Revision int `json:"revision"`
496 Error string `json:"error,omitempty"`
497 }
498 if readErr != nil || finished != nil || len(data) > clipboardWireLimit || json.Unmarshal(data, &result) != nil || result.Error != "" ||
499 len(result.Session) == 0 || request.Phase == "read" && (result.Text == nil || len(*result.Text) > 2<<20 || result.Session != request.Session || result.Revision == *request.Revision) {
500 http.Error(w, "未收到新的选中文本,请确认客机已解锁并重新复制", http.StatusConflict)
501 return
502 }
503 w.Header().Set("Cache-Control", "no-store")
504 jsonReply(w, result)
505}
506
507func writeClipboardArchive(output io.Writer, paths []string) error {
508 return clipboardfiles.Write(output, paths)
509}
510
511func readClipboardArchive(input io.Reader) ([]string, error) {
512 return clipboardfiles.Read(input)
513}
514
515// A tar EOF only ends the archive, not the guest process. Drain the HTTP body
516// before checking the producer's completion trailer or publishing local paths.
517func receiveClipboardArchive(response *http.Response, cache clipboardfiles.CacheStore) (clipboardfiles.CachedSelection, error) {
518 selection, err := cache.Read(response.Body)
519 if err == nil {
520 _, err = io.Copy(io.Discard, response.Body)
521 }
522 if err == nil && response.Trailer.Get("X-Cage-Clipboard-Status") != "ok" {
523 err = errors.New("剪贴板文件传递中断,请重新复制")
524 }
525 if err != nil {
526 if selection.ID != "" {
527 _ = cache.Release(selection.ID)
528 }
529 return clipboardfiles.CachedSelection{}, err
530 }
531 return selection, nil
532}
533
534// Native helpers stream bytes directly, keeping host paths out of the WebView.
535func ClipboardFilesForConnection(configPath, connectionID, operation string, args []string) (map[string]any, error) {
536 cache, err := clipboardfiles.UserCacheStore()
537 if err != nil {
538 return nil, err
539 }
540 if operation == "cache" && len(args) == 1 {
541 var request clipboardfiles.CacheRequest
542 if json.Unmarshal([]byte(args[0]), &request) != nil {
543 return nil, errors.New("剪贴板缓存请求无效")
544 }
545 return cache.Control(request)
546 }
547 client, err := connectController(filepath.Dir(configPath))
548 if err != nil {
549 return nil, err
550 }
551 defer client.close()
552 entry, _ := url.Parse(client.launch.URL)
553 status, err := client.call("POST", "/api/session", map[string]string{"token": entry.Fragment}, nil)
554 if err != nil || status != http.StatusOK {
555 return nil, errors.New("无法连接剪贴板会话")
556 }
557 if _, err = client.bindConnection(connectionID); err != nil {
558 return nil, err
559 }
560 client.client.Timeout = 30 * time.Minute
561 path := client.origin + "/api/clipboard/files"
562 var body io.Reader
563 method := "POST"
564 if (operation == "receive" || operation == "release") && len(args) == 1 && browserFileID.MatchString(args[0]) {
565 path += "/" + args[0]
566 method = "GET"
567 if operation == "release" {
568 method = http.MethodDelete
569 client.client.Timeout = 5 * time.Second
570 }
571 } else if operation == "send" {
572 reader, writer := io.Pipe()
573 defer reader.Close()
574 body = reader
575 go func() { writer.CloseWithError(writeClipboardArchive(writer, args)) }()
576 } else {
577 return nil, errors.New("剪贴板文件操作无效")
578 }
579 request, err := http.NewRequest(method, path, body)
580 if err != nil {
581 return nil, err
582 }
583 request.Header.Set("Origin", client.origin)
584 request.Header.Set("Content-Type", "application/x-tar")
585 response, err := client.client.Do(request)
586 if err != nil {
587 return nil, errors.New("剪贴板文件传递中断,请重新复制")
588 }
589 defer response.Body.Close()
590 if response.StatusCode != http.StatusOK {
591 return nil, errors.New("剪贴板文件传递失败,请重新复制")
592 }
593 if method == "GET" {
594 selection, err := receiveClipboardArchive(response, cache)
595 if err != nil {
596 return nil, err
597 }
598 return map[string]any{"paths": selection.Paths, "cache_id": selection.ID}, nil
599 }
600 var result map[string]any
601 err = json.NewDecoder(io.LimitReader(response.Body, 65537)).Decode(&result)
602 return result, err
603}