跳到主要内容

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

浏览文件

app.go

209 行 · 6.6 KB历史下载
1package cli
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "sync"
9
10 "github.com/sylvinus/agent-vm/internal/cage"
11 "github.com/sylvinus/agent-vm/internal/paths"
12 "github.com/sylvinus/agent-vm/internal/state"
13 "github.com/sylvinus/agent-vm/internal/ui"
14 "github.com/sylvinus/agent-vm/internal/vm"
15 "github.com/sylvinus/agent-vm/internal/vmname"
16)
17
18// app is what the commands work with.
19type app struct {
20 io IO
21 ui *ui.UI
22 state state.Dir
23 privateStorage []string
24 names vmname.Limit
25 cageProfile string
26
27 migrateOnce sync.Once
28 migrate func() // moves 0.2's VMs, when set
29 backOnce sync.Once
30 newBack func() (vm.Backend, error)
31 back vm.Backend
32 backErr error
33}
34
35// backend is made on first use: most commands never need Lima. The first
36// use by a command that changes VMs also moves 0.2's VMs (migrateOld).
37func (e *app) backend() (vm.Backend, error) {
38 e.migrateOnce.Do(func() {
39 if e.migrate != nil {
40 e.migrate()
41 }
42 })
43 return e.readOnlyBackend()
44}
45
46// readOnlyBackend is backend without the move of 0.2's VMs, for commands
47// that only look (list, status, doctor, info, install). A command that goes
48// on to change VMs asks for backend, which moves them then.
49func (e *app) readOnlyBackend() (vm.Backend, error) {
50 e.backOnce.Do(func() { e.back, e.backErr = e.newBack() })
51 return e.back, e.backErr
52}
53
54// migratedMarker says the VMs of 0.2 were moved into agent-vm's Lima home.
55const migratedMarker = ".agent-vm-lima-migrated"
56
57// oldLimaHome is where 0.2 kept its VMs: Lima's home, $LIMA_HOME or ~/.lima.
58func oldLimaHome() string {
59 if h := vm.UserLimaHome(); h != "" {
60 return paths.Host(absOr(h))
61 }
62 return paths.Host(filepath.Join(paths.Home(), ".lima"))
63}
64
65// absOr is p made absolute, as it is when that cannot be done: a relative
66// folder would defeat the checks that compare locations.
67func absOr(p string) string {
68 if abs, err := filepath.Abs(p); err == nil {
69 return abs
70 }
71 return p
72}
73
74// migrated reports whether 0.2's VMs were moved already.
75func (e *app) migrated() bool {
76 _, err := os.Stat(e.state.Path(migratedMarker))
77 return err == nil
78}
79
80// unmovedOld are 0.2's VMs that have not been moved yet, and the Lima home
81// they are in. None for an app with no move wired (migrate unset).
82func (e *app) unmovedOld() ([]vm.OldVM, string) {
83 old := oldLimaHome()
84 if e.migrate == nil || e.migrated() || sameDir(old, LimaHome(e.state)) {
85 return nil, old
86 }
87 vms, _ := vm.FindOld(old, vmname.OldPrefix)
88 return vms, old
89}
90
91// migrateOld moves, once, the VMs agent-vm 0.2 made in the user's Lima home
92// into its own (see LimaHome). Asked on a terminal, yes by default. Without
93// one, the stopped ones are moved and the running ones left: moving stops
94// them, which cuts sessions nobody agreed to cut. A VM that could not be
95// moved stays, and is offered again.
96func (e *app) migrateOld(ctx context.Context, old, now string) {
97 if e.migrated() || sameDir(old, now) {
98 return
99 }
100 vms, err := vm.FindOld(old, vmname.OldPrefix)
101 if err != nil || len(vms) == 0 {
102 return
103 }
104 w := e.io.Stderr
105 fmt.Fprintf(w, "agent-vm now keeps its VMs in %s, apart from your own Lima's. Found in %s:\n", now, old)
106 running := false
107 for _, v := range vms {
108 state := ""
109 if v.Running {
110 state, running = " (running)", true
111 }
112 fmt.Fprintf(w, " %s, as %s%s\n", v.Name, e.names.FromOld(v.Name), state)
113 }
114 canAsk := e.ui.CanAsk()
115 if running && canAsk {
116 fmt.Fprintln(w, "Running ones are stopped first: sessions using them are cut.")
117 }
118 if canAsk && !e.ui.AskYN("Move them there now?", true) {
119 fmt.Fprintf(w, "Not moved: this agent-vm does not see them until they are. They stay in %s.\n", old)
120 return
121 }
122 failed := false
123 for _, v := range vms {
124 if v.Running && !canAsk {
125 fmt.Fprintf(w, "%s is running and stays in %s: no terminal to ask whether to cut its sessions. Stop it, or run agent-vm in a terminal.\n", v.Name, old)
126 failed = true
127 continue
128 }
129 to := e.names.FromOld(v.Name)
130 fmt.Fprintf(w, "Moving %s...\n", v.Name)
131 if err := vm.MoveOld(ctx, old, now, v.Name, to); err != nil {
132 fmt.Fprintf(w, "Error: could not move %s: %v. It stays in %s.\n", v.Name, err, old)
133 failed = true
134 continue
135 }
136 if err := e.state.Rename(v.Name, to); err != nil {
137 fmt.Fprintf(w, "Warning: %s moved, but not all that agent-vm knows of it: %v\n", to, err)
138 }
139 }
140 if failed {
141 return
142 }
143 if err := e.state.Write(migratedMarker, []byte(old+"\n")); err != nil {
144 fmt.Fprintf(w, "Warning: could not record that they were moved: %v. They are looked for in %s again next time.\n", err, old)
145 }
146 fmt.Fprintln(w, "Done: they keep their shares and settings, under their new names.")
147}
148
149// sameDir reports whether a and b are one folder, links resolved where they
150// exist.
151func sameDir(a, b string) bool {
152 if fa, err := os.Stat(a); err == nil {
153 if fb, err := os.Stat(b); err == nil {
154 return os.SameFile(fa, fb)
155 }
156 }
157 return filepath.Clean(a) == filepath.Clean(b)
158}
159
160// LimaHome is where agent-vm's Lima keeps its VMs: its own, so that the
161// user's limactl, of another version, never runs them, and nothing of the
162// user's own Lima is touched. AGENT_VM_LIMA_HOME overrides it, made
163// absolute.
164func LimaHome(st state.Dir) string {
165 if h := os.Getenv("AGENT_VM_LIMA_HOME"); h != "" {
166 return paths.Host(absOr(h))
167 }
168 return st.Path("lima")
169}
170
171func newApp(io IO) (*app, error) {
172 st, err := state.Default()
173 if err != nil {
174 return nil, err
175 }
176 u := ui.New()
177 u.Stderr = io.Stderr
178 e := &app{io: io, ui: u, state: st}
179 // Names that fit this machine's socket paths (a long home, a long user
180 // name): cut in their folder part, not refused.
181 e.names = vmname.Limit(vm.MaxName(LimaHome(st)))
182 e.migrate = func() { e.migrateOld(context.Background(), oldLimaHome(), LimaHome(st)) }
183 // Cage owns a separate profile; it never imports another tool's VMs.
184 if config := os.Getenv(cage.ConfigEnv); config != "" {
185 e.migrate = nil
186 e.cageProfile = filepath.Dir(config)
187 e.privateStorage, err = cage.StoragePrivatePaths(filepath.Dir(config))
188 if err != nil {
189 return nil, err
190 }
191 e.privateStorage = append(e.privateStorage, filepath.Dir(config))
192 }
193 e.newBack = func() (vm.Backend, error) {
194 // Every VM there is agent-vm's: list, rm and destroy-all take them
195 // all. Never a Lima home the user's own VMs live in.
196 if h := LimaHome(st); sameDir(h, oldLimaHome()) {
197 return nil, fmt.Errorf("agent-vm's Lima home %s is also your own Lima's home: set AGENT_VM_LIMA_HOME to a folder for agent-vm alone", h)
198 }
199 return vm.NewLima(LimaHome(st), string(st))
200 }
201 return e, nil
202}
203
204func (e *app) instanceName(dir string) string {
205 if e.cageProfile != "" {
206 return cage.InstanceName(e.cageProfile, dir)
207 }
208 return e.names.Name(dir)
209}