跳到主要内容

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

浏览文件

control_lifecycle.go

185 行 · 5.7 KB历史下载
1package workbench
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "net/http"
9 "os"
10 "path/filepath"
11 "time"
12
13 "github.com/sylvinus/agent-vm/internal/cage"
14 "github.com/sylvinus/agent-vm/internal/containerenv"
15 "github.com/sylvinus/agent-vm/internal/guestos"
16 "github.com/sylvinus/agent-vm/internal/managedproxy"
17 "github.com/sylvinus/agent-vm/internal/version"
18)
19
20const controlProtocol = 1
21
22type ControllerIdentity struct {
23 Version string `json:"version"`
24 Build string `json:"build"`
25 Protocol int `json:"protocol"`
26 PID int `json:"pid"`
27}
28
29func currentController() (ControllerIdentity, error) {
30 build, err := version.ExecutableIdentity()
31 return ControllerIdentity{Version: version.Version, Build: build, Protocol: controlProtocol, PID: os.Getpid()}, err
32}
33
34func (identity ControllerIdentity) matches(other ControllerIdentity) bool {
35 return identity.Build != "" && identity.Build == other.Build && identity.Protocol == other.Protocol
36}
37
38type launchResponse struct {
39 ConfigPath string `json:"config_path,omitempty"`
40 ClientOnly bool `json:"client_only,omitempty"`
41 DesktopGateway bool `json:"desktop_gateway,omitempty"`
42 URL string `json:"url"`
43 Controller ControllerIdentity `json:"controller"`
44}
45
46func (s *Server) launcherAuthenticated(w http.ResponseWriter, r *http.Request) bool {
47 var input struct {
48 Token string `json:"token"`
49 }
50 if !readJSON(w, r, &input) {
51 return false
52 }
53 if !equalSecret(input.Token, s.token) {
54 http.Error(w, "Launcher refused", http.StatusUnauthorized)
55 return false
56 }
57 return true
58}
59
60func (s *Server) handoff(w http.ResponseWriter, r *http.Request) {
61 if !s.launcherAuthenticated(w, r) {
62 return
63 }
64 if !s.op.TryLock() {
65 http.Error(w, "请先保存工作并停止环境,再完成更新。", http.StatusConflict)
66 return
67 }
68 s.handoffLocked(w)
69}
70
71// handoffLocked takes ownership of the operation lock and releases it on all paths.
72func (s *Server) handoffLocked(w http.ResponseWriter) {
73 s.handoffWithVMOwnerLocked(w, "")
74}
75
76// Installation activation may retain its newly provisioned, verified guest.
77// Ordinary updates pass no permitted owner and still require a stopped VM.
78func (s *Server) handoffWithVMOwnerLocked(w http.ResponseWriter, permittedOwner string) {
79 owners, probeError := controllerVMOwners(s.profile)
80 vmBusy := probeError != nil || len(owners) != 0 && (permittedOwner == "" || len(owners) != 1 || owners[0] != permittedOwner)
81 s.mu.Lock()
82 if s.closing {
83 s.mu.Unlock()
84 s.op.Unlock()
85 http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable)
86 return
87 }
88 busy := s.jobs.snapshot().Running || vmBusy
89 busy = busy || s.terminals.hasLive()
90 busy = busy || len(s.mobileCLI.activeAccounts()) != 0
91 if busy || s.shutdown == nil {
92 s.mu.Unlock()
93 s.op.Unlock()
94 http.Error(w, "请先保存工作并停止环境,再完成更新。", http.StatusConflict)
95 return
96 }
97 s.closing = true
98 s.mu.Unlock()
99 if err := managedproxy.Stop(s.profile); err != nil {
100 s.mu.Lock()
101 s.closing = false
102 s.mu.Unlock()
103 s.op.Unlock()
104 http.Error(w, "代理尚未停止,未继续后台更新。", http.StatusConflict)
105 return
106 }
107 // A fixed length keeps the complete acknowledgement readable even if
108 // cancellation prevents net/http from writing a final chunk afterwards.
109 w.Header().Set("Content-Type", "application/json")
110 w.Header().Set("Content-Length", "18")
111 _, _ = w.Write([]byte("{\"stopping\":true}\n"))
112 // Publish the acknowledgement before cancelling this request. Admission is
113 // already sealed; shutdown must not wait for requests while holding op.
114 _ = http.NewResponseController(w).Flush()
115 s.op.Unlock()
116 go s.shutdown()
117}
118
119func controllerHasVM(profile string) bool {
120 running, err := controllerVMState(profile)
121 return err != nil || running
122}
123
124// Callers that display a state must distinguish a missing VM from a failed probe.
125func controllerVMState(profile string) (bool, error) {
126 owners, err := controllerVMOwners(profile)
127 return len(owners) != 0, err
128}
129
130func controllerVMOwners(profile string) ([]string, error) {
131 binding, err := guestos.LoadWindowsProfile(profile)
132 if err != nil {
133 return nil, err
134 }
135 if binding != nil {
136 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
137 defer cancel()
138 state, err := guestos.WindowsVMResources(ctx, profile, 0, 0)
139 if err != nil {
140 return nil, err
141 }
142 if state.State == "" {
143 return nil, errors.New("无法确认已绑定 Windows 客机的运行状态,现有环境保持不变")
144 }
145 if state.State == "Off" || state.State == "Saved" {
146 return nil, nil
147 }
148 return []string{fmt.Sprintf("windows/%s/%s", binding.VMID, state.State)}, nil
149 }
150 if containerenv.Configured(profile) {
151 environment, err := containerenv.Load(profile)
152 if err != nil {
153 return nil, err
154 }
155 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
156 defer cancel()
157 state, err := environment.State(ctx)
158 if err != nil || !state.Running {
159 return nil, err
160 }
161 return []string{fmt.Sprintf("%s/%d", state.ContainerID, state.PID)}, nil
162 }
163 records, err := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-running.json"))
164 if err != nil {
165 return nil, err
166 }
167 var owners []string
168 for _, path := range records {
169 b, err := os.ReadFile(path)
170 if err != nil {
171 return nil, err
172 }
173 var record struct {
174 PID int `json:"pid"`
175 Started string `json:"started"`
176 }
177 if json.Unmarshal(b, &record) != nil || record.PID <= 0 {
178 return nil, errors.New("环境进程记录无效")
179 }
180 if processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started) {
181 owners = append(owners, fmt.Sprintf("%s/%d", filepath.Base(filepath.Dir(path)), record.PID))
182 }
183 }
184 return owners, nil
185}