跳到主要内容

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

浏览文件

guest_install.go

361 行 · 12.3 KB历史下载
1package workbench
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "runtime"
12 "strings"
13
14 "github.com/google/uuid"
15 "github.com/sylvinus/agent-vm/internal/cage"
16 "github.com/sylvinus/agent-vm/internal/guestos"
17 "github.com/sylvinus/agent-vm/internal/host"
18 "github.com/sylvinus/agent-vm/internal/hostimage"
19 "github.com/sylvinus/agent-vm/internal/hostproxy"
20)
21
22type guestInstallRequest struct {
23 EditorTerms bool `json:"editor_terms"`
24 System string `json:"guest_system"`
25 Media string `json:"media"`
26 SHA256 string `json:"sha256"`
27 CloneKey string `json:"clone_key,omitempty"`
28}
29
30type guestInstallView struct {
31 LinuxSystems []string `json:"linux_systems,omitempty"`
32 Reselect bool `json:"reselect,omitempty"`
33 System string `json:"system,omitempty"`
34 Available bool `json:"available"`
35 Reason string `json:"reason,omitempty"`
36 Fresh bool `json:"fresh"`
37 Pending *guestos.Installation `json:"pending,omitempty"`
38 Activate bool `json:"activate,omitempty"`
39}
40
41func (s *Server) guestInstallView() (guestInstallView, error) {
42 v := guestInstallView{}
43 if !s.localVMStorage() || s.macosGuest != nil || s.windowsGuest != nil {
44 return v, nil
45 }
46 pending, err := guestos.LoadInstallation(s.profile)
47 if err != nil {
48 return v, err
49 }
50 loc, err := cage.GetStorageLocation(s.profile)
51 if err != nil {
52 return v, err
53 }
54 v.Fresh = !loc.HasEnvironment
55 v.Pending = pending
56 if !v.Fresh && pending == nil {
57 return v, nil
58 }
59 v.LinuxSystems = linuxGuestSystems(runtime.GOOS, runtime.GOARCH)
60 switch {
61 case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
62 v.System = guestos.MacOS
63 case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
64 v.System = guestos.Windows11
65 case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
66 identity, hostErr := hostimage.Host(context.Background())
67 if hostErr != nil {
68 v.Reason = hostErr.Error()
69 } else {
70 v.System = identity.System
71 }
72 default:
73 return v, nil
74 }
75 if pending != nil {
76 v.Reselect, err = guestos.UnstartedInstallation(s.profile, *pending)
77 if err != nil {
78 return v, err
79 }
80 catalog := pending.SourceKind == guestos.LinuxImageSource && canInstallCatalogLinux(pending.System) && pending.Source.Host.Arch == runtime.GOARCH
81 if !catalog && pending.System != v.System {
82 return v, errors.New("客户机安装记录与这台宿主不匹配")
83 }
84 if pending.SourceKind == guestos.LinuxImageSource && !catalog {
85 return v, errors.New("客户机镜像架构与这台主机不匹配,请恢复原主机环境")
86 }
87 mac, err := guestos.LoadMacOSProfile(s.profile)
88 if err != nil {
89 return v, err
90 }
91 win, err := guestos.LoadWindowsProfile(s.profile)
92 if err != nil {
93 return v, err
94 }
95 v.Activate = (pending.System == guestos.MacOS && mac != nil) || (pending.System == guestos.Windows11 && win != nil)
96 if pending.System == guestos.Windows11 && win != nil {
97 cleanup, err := guestos.WindowsCloneCleanupPending(s.profile)
98 if err != nil {
99 return v, err
100 }
101 v.Activate = !cleanup
102 }
103 }
104 if v.System == "" {
105 return v, nil
106 }
107 if !hostimage.IsLinux(v.System) && !guestos.HasNativeWorkbenchKit(s.exe, v.System) {
108 v.Reason = "此构建缺少原生客户机安装组件"
109 return v, nil
110 }
111 v.Available = true
112 return v, nil
113}
114
115func (s *Server) guestInstallation(w http.ResponseWriter, r *http.Request) {
116 if !s.hasTrustedView(r) || !s.localVMStorage() {
117 http.Error(w, "请在本机 Cage 窗口选择客户机系统", http.StatusForbidden)
118 return
119 }
120 v, err := s.guestInstallView()
121 if err != nil {
122 requestError(w, err)
123 return
124 }
125 if r.Method == http.MethodGet {
126 if v.System == guestos.Windows11 && v.Available && v.Pending == nil {
127 check := guestos.Inspect(r.Context())
128 if !check.HostCheckPassed {
129 v.Available = false
130 v.Reason = check.Detail
131 }
132 }
133 jsonReply(w, v)
134 return
135 }
136 if r.Method == http.MethodDelete {
137 var body struct {
138 ID uuid.UUID `json:"id"`
139 }
140 if !readJSON(w, r, &body) {
141 return
142 }
143 if !v.Reselect || s.busy() || !s.op.TryLock() {
144 http.Error(w, "安装任务或磁盘已存在,请继续原安装", http.StatusConflict)
145 return
146 }
147 defer s.op.Unlock()
148 if err := guestos.ClearUnstartedInstallation(s.profile, body.ID); err != nil {
149 requestError(w, err)
150 return
151 }
152 jsonReply(w, map[string]bool{"cleared": true})
153 return
154 }
155 if !v.Activate || !s.op.TryLock() {
156 http.Error(w, "客户机尚未完成安装", http.StatusConflict)
157 return
158 }
159 if v.Pending != nil && v.Pending.System == guestos.Windows11 {
160 owner, err := s.installedWindowsVMOwner(*v.Pending)
161 if err != nil {
162 s.op.Unlock()
163 requestError(w, err)
164 return
165 }
166 s.handoffWithVMOwnerLocked(w, owner)
167 return
168 }
169 s.handoffLocked(w)
170}
171
172func (s *Server) installedWindowsVMOwner(install guestos.Installation) (string, error) {
173 binding, err := guestos.LoadWindowsProfile(s.profile)
174 if err != nil || binding == nil || install.System != guestos.Windows11 || install.ID == uuid.Nil {
175 return "", errors.New("Windows 安装绑定尚未确认,请继续原安装;原磁盘和账户已保留")
176 }
177 state, err := cage.StoragePhysicalPath(filepath.Join(s.profile, "state"))
178 if err != nil {
179 return "", err
180 }
181 expected := filepath.Join(state, "windows-"+strings.ReplaceAll(install.ID.String(), "-", ""))
182 receipt, err := os.ReadFile(filepath.Join(s.profile, "windows-install-vm.txt"))
183 id, parseErr := uuid.Parse(strings.TrimSpace(string(receipt)))
184 if err != nil || parseErr != nil || id != binding.VMID || !strings.EqualFold(filepath.Clean(binding.InstanceDirectory), filepath.Clean(expected)) {
185 return "", errors.New("Windows 安装记录与原客机不匹配,请核对原环境;现有数据已保留")
186 }
187 return "windows/" + binding.VMID.String() + "/Running", nil
188}
189
190func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in guestInstallRequest) {
191 if in.System == guestos.MacOS && !s.account.view().MacOSCredentialsReady {
192 http.Error(w, "请先注册或确认 Cage 账密,再安装 macOS 客机", http.StatusConflict)
193 return
194 }
195 v, err := s.guestInstallView()
196 if err != nil {
197 requestError(w, err)
198 return
199 }
200 catalog := canInstallCatalogLinux(in.System) && in.CloneKey == ""
201 if v.Pending != nil {
202 catalog = v.Pending.SourceKind == guestos.LinuxImageSource
203 }
204 if (!catalog && (!v.Available || v.System != in.System)) || !s.hasTrustedView(r) || (!v.Fresh && v.Pending == nil) || v.Activate {
205 http.Error(w, "当前环境无法安装所选客户机系统", http.StatusConflict)
206 return
207 }
208 install := guestos.Installation{Version: 1, System: in.System, Media: in.Media, SHA256: strings.ToLower(in.SHA256), ID: uuid.New(), EditorTerms: in.EditorTerms}
209 if v.Pending != nil {
210 if v.Pending.System != in.System || (in.Media != "" && in.Media != v.Pending.Media) || (in.SHA256 != "" && !strings.EqualFold(in.SHA256, v.Pending.SHA256)) {
211 http.Error(w, "必须使用原先选择的系统和安装介质继续安装", http.StatusConflict)
212 return
213 }
214 install = *v.Pending
215 } else if in.CloneKey != "" {
216 plan, planErr := s.hostClonePlan(r.Context())
217 if planErr != nil {
218 requestError(w, planErr)
219 return
220 }
221 if plan.Key() != in.CloneKey || plan.Host.System != in.System {
222 requestError(w, errors.New("本机版本或系统镜像信息已变化,请重新检测并匹配"))
223 return
224 }
225 install.Source = plan
226 } else if catalog {
227 if in.Media != "" || in.SHA256 != "" || in.EditorTerms {
228 requestError(w, errors.New("Ubuntu 使用 Cage 校验过的官方镜像,无需另选安装介质"))
229 return
230 }
231 plan, err := linuxGuestImagePlan(r.Context(), s.profile, in.System, runtime.GOARCH)
232 if err != nil {
233 requestError(w, err)
234 return
235 }
236 install.Source, install.SourceKind = plan, guestos.LinuxImageSource
237 }
238 if err := install.Validate(); err != nil {
239 requestError(w, err)
240 return
241 }
242 s.launch(w, "guest-install", func() error {
243 s.jobs.execution().setSetupProgress(&SetupProgress{Phase: "image", System: install.System, Label: "正在准备 " + guestProgressName(install.System) + " 安装材料"})
244 if err := requireHostGit(s.operationContext()); err != nil {
245 return err
246 }
247 cfg, err := loadConfig(s.configPath)
248 if err != nil {
249 return err
250 }
251 if err := cfg.RequireManagedProxy(s.profile); err != nil {
252 return err
253 }
254 lease, loc, err := cage.AcquireStorageUse(s.profile)
255 if err != nil {
256 return err
257 }
258 defer lease.Close()
259 current, err := guestos.LoadInstallation(s.profile)
260 if err != nil {
261 return err
262 }
263 if current == nil && loc.HasEnvironment || current != nil && *current != install {
264 return errors.New("已有其他环境或安装任务,请重新打开安装页面")
265 }
266 if install.Media != "" {
267 f, err := os.Stat(install.Media)
268 if err != nil || !f.Mode().IsRegular() {
269 return errors.New("原安装镜像不可读,请恢复其原路径后重试")
270 }
271 }
272 if install.System == guestos.Windows11 {
273 check := guestos.Inspect(s.operationContext())
274 if !check.HostCheckPassed {
275 return errors.New(check.Detail)
276 }
277 }
278 if err := guestos.SaveInstallation(s.profile, install); err != nil {
279 return err
280 }
281 if install.Source.Host.System != "" {
282 cache := filepath.Join(s.profile, "state", "guest-media", install.System)
283 unstarted, err := guestos.UnstartedInstallation(s.profile, install)
284 if err != nil {
285 return err
286 }
287 minimumGiB := 32
288 if hostimage.IsLinux(install.System) {
289 minimumGiB = 16
290 }
291 if !unstarted {
292 minimumGiB = 0
293 }
294 minimumGiB += int((install.Source.RemainingBytes(cache) + (1 << 30) - 1) / (1 << 30))
295 if available, ok := host.FreeGiB(cache); ok && available < minimumGiB {
296 return fmt.Errorf("创建所选系统至少需要 %d GiB 可用空间,当前有 %d GiB,请在存储设置中选择空间充足的位置", minimumGiB, available)
297 }
298 s.setMessage("正在准备 " + guestProgressName(install.System) + " 官方系统镜像…")
299 transport := hostproxy.NewTransport()
300 defer transport.CloseIdleConnections()
301 prepared, prepareErr := hostimage.Prepare(s.operationContext(), cache, install.Source, s.jobs.execution(), transport)
302 if prepareErr != nil {
303 return prepareErr
304 }
305 install.Source, install.Media = prepared, prepared.Path
306 install.SHA256 = strings.TrimPrefix(prepared.Digest, "sha256:")
307 if err := guestos.RecordPreparedMedia(s.profile, install.ID, prepared); err != nil {
308 return err
309 }
310 }
311 var credential macGuestCredential
312 if install.System == guestos.MacOS {
313 saved, err := s.account.savedMacGuestPassword(s.operationContext(), install.ID)
314 if err != nil {
315 return err
316 }
317 unstarted, err := guestos.UnstartedInstallation(s.profile, install)
318 if err != nil {
319 return err
320 }
321 if saved == "" && !unstarted {
322 return errors.New("客机安装凭据缺失,请恢复加密保险箱;现有账户和磁盘已保留")
323 }
324 credential, err = s.account.macGuestCredentials(s.operationContext(), install.ID)
325 if err != nil {
326 return err
327 }
328 }
329 if err := s.prepareEnvironment(); err != nil {
330 return err
331 }
332 if hostimage.IsLinux(install.System) {
333 if err := hostimage.WriteLinuxTemplate(filepath.Join(s.profile, "state"), install.Source); err != nil {
334 return err
335 }
336 if err := s.startEnvironment(true); err != nil {
337 return err
338 }
339 return guestos.FinishLinuxInstallation(s.profile, install.ID)
340 }
341 s.setMessage("正在安装所选客户机系统…")
342 s.jobs.execution().setSetupProgress(&SetupProgress{Phase: "packages", System: install.System, Label: "正在安装 " + guestProgressName(install.System) + " 系统"})
343 var cmd *exec.Cmd
344 if install.System == guestos.MacOS {
345 cmd = exec.CommandContext(s.operationContext(), s.exe, "guest-os", "macos", "install")
346 cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath, "CAGE_MACOS_ACCOUNT="+credential.Username)
347 cmd.Stdin = strings.NewReader(credential.Password)
348 } else {
349 cmd, err = guestos.WindowsInstallCommand(s.operationContext(), s.profile, filepath.Join(filepath.Dir(s.exe), "guest-os"), install)
350 if err != nil {
351 return err
352 }
353 }
354 cmd.Stdout = s.jobs.execution()
355 cmd.Stderr = s.jobs.execution()
356 if err := cmd.Run(); err != nil {
357 return fmt.Errorf("客户机安装未完成,已保留安装进度和文件。请点击「继续安装」。若仍失败,请在设置中导出诊断包:%w", err)
358 }
359 return nil
360 })
361}