跳到主要内容

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

浏览文件

macos_claude.go

163 行 · 6.1 KB历史下载
1package workbench
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "net/http"
10 "strings"
11 "time"
12)
13
14const macOSWindowSocketCommand = `exec /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`
15
16// The native trial has a dedicated standard-user SSH identity. The guest GUI
17// agent accepts only Claude operations on its protected per-user Unix socket.
18func (s *Server) registerMacOSClaudeRoutes(mux routeRegistrar) {
19 mux.HandleFunc("POST /api/macos/claude/window", s.macOSClaudeWindow)
20 mux.HandleFunc("GET /api/macos/claude/connection", s.macOSWindowConnection)
21 mux.HandleFunc("GET /api/macos/claude/frames", s.macOSWindowFrames)
22}
23
24type macOSWindowRequest struct {
25 Action string `json:"action"`
26 Project string `json:"project,omitempty"`
27 Nonce string `json:"nonce,omitempty"`
28 Width int `json:"width,omitempty"`
29 Height int `json:"height,omitempty"`
30 Scale float64 `json:"scale,omitempty"`
31 Geometry string `json:"geometry,omitempty"`
32 Window uint32 `json:"window,omitempty"`
33 PID int32 `json:"pid,omitempty"`
34 X *float64 `json:"x,omitempty"`
35 Y *float64 `json:"y,omitempty"`
36 Delta *float64 `json:"delta,omitempty"`
37 DeltaX *float64 `json:"deltaX,omitempty"`
38 Text string `json:"text,omitempty"`
39 Key string `json:"key,omitempty"`
40 Code string `json:"code,omitempty"`
41 Down *bool `json:"down,omitempty"`
42 Phase string `json:"phase,omitempty"`
43 Button *int `json:"button,omitempty"`
44 Buttons int `json:"buttons,omitempty"`
45 Clicks int `json:"clicks,omitempty"`
46 Shift bool `json:"shift,omitempty"`
47 Cmd bool `json:"command,omitempty"`
48 Control bool `json:"control,omitempty"`
49 Alt bool `json:"alt,omitempty"`
50 Mode string `json:"mode,omitempty"`
51 Context string `json:"context,omitempty"`
52 Session string `json:"session,omitempty"`
53 After string `json:"after,omitempty"`
54 KeepAlive bool `json:"keepAlive,omitempty"`
55 Refresh bool `json:"refresh,omitempty"`
56 Wait bool `json:"wait,omitempty"`
57 Binary bool `json:"binary,omitempty"`
58 ID string `json:"id,omitempty"`
59 IDs []string `json:"ids,omitempty"`
60 Kind string `json:"kind,omitempty"`
61 Transfer string `json:"transfer,omitempty"`
62 Sequence int `json:"sequence"`
63 Path string `json:"path,omitempty"`
64 Error string `json:"error,omitempty"`
65 Files []string `json:"files,omitempty"`
66 Phone *phoneSurfaceInput `json:"phone,omitempty"`
67 PhoneToken string `json:"phone_token,omitempty"`
68}
69
70func (s *Server) macOSClaudeWindow(w http.ResponseWriter, r *http.Request) {
71 if s.macosGuest == nil {
72 http.NotFound(w, r)
73 return
74 }
75 var input macOSWindowRequest
76 if !readJSON(w, r, &input) {
77 return
78 }
79 if !validMacOSWindowRequest(input) {
80 http.Error(w, "客机窗口操作或尺寸无效", http.StatusBadRequest)
81 return
82 }
83 s.macOSWindowRPC(w, r, macOSWindowClientRequest(input, false))
84}
85
86var (
87 errMacWindowInput = errors.New("单次窗口输入过长")
88 errMacWindowConnect = errors.New("无法连接虚拟 Mac")
89)
90
91func (s *Server) macOSWindowRPC(w http.ResponseWriter, r *http.Request, input macOSWindowRequest) {
92 var reply []byte
93 var err error
94 if input.Action == "status" {
95 reply, err = s.desktopStatus.read(r.Context(), s.lifetimeContext(), func(ctx context.Context) ([]byte, error) { return s.macOSWindowCall(ctx, input) })
96 } else {
97 // Input and capture retain their own live guest ownership validation.
98 if input.Action == "launch" {
99 s.desktopStatus.invalidate()
100 defer s.desktopStatus.invalidate()
101 }
102 reply, err = s.macOSWindowCall(r.Context(), input)
103 }
104 if err != nil {
105 code := http.StatusServiceUnavailable
106 if errors.Is(err, errMacWindowInput) {
107 code = http.StatusBadRequest
108 }
109 if errors.Is(err, errMacWindowConnect) {
110 code = http.StatusBadGateway
111 }
112 http.Error(w, err.Error(), code)
113 return
114 }
115 w.Header().Set("Cache-Control", "no-store")
116 w.Header().Set("Content-Type", "application/json")
117 _, _ = w.Write(reply)
118}
119
120func (s *Server) macOSWindowCall(parent context.Context, input macOSWindowRequest) ([]byte, error) {
121 body, err := json.Marshal(input)
122 limit := 8000
123 if strings.HasPrefix(input.Action, "phone-") || input.Action == "text" || input.Action == "ime" {
124 // An 8 KiB UTF-8 message can expand sixfold when JSON escapes controls.
125 limit = 64 << 10
126 }
127 if err != nil || len(body) > limit {
128 return nil, errMacWindowInput
129 }
130
131 timeout := 12 * time.Second
132 socketWait := "9"
133 if input.Action == "launch" || input.Action == "phone-open" {
134 // On a cold guest disk macOS verifies the signed Electron bundle
135 // before LaunchServices reports success.
136 timeout = 55 * time.Second
137 socketWait = "50"
138 }
139 ctx, cancel := context.WithTimeout(parent, timeout)
140 defer cancel()
141 command := `exec /usr/bin/nc -w ` + socketWait + ` -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`
142 cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
143 cmd.Stdin = bytes.NewReader(append(body, '\n'))
144 reader, err := cmd.StdoutPipe()
145 if err == nil {
146 err = cmd.Start()
147 }
148 if err != nil {
149 return nil, errMacWindowConnect
150 }
151 // The agent returns one PNG (base64) or a small JSON status. Do not relay
152 // partial replies or log input, frame data, or guest application contents.
153 const maxReply = 12 << 20
154 reply, readErr := io.ReadAll(io.LimitReader(reader, maxReply+1))
155 if readErr != nil || len(reply) > maxReply {
156 cancel()
157 }
158 waitErr := cmd.Wait()
159 if readErr != nil || waitErr != nil || len(reply) > maxReply || !json.Valid(reply) {
160 return nil, errors.New("请先登录虚拟 Mac 的普通账户,并完成 Apple 设置助理。")
161 }
162 return reply, nil
163}