跳到主要内容

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

浏览文件

vms.go

258 行 · 7.7 KB历史下载
1package cli
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "strings"
9 "text/tabwriter"
10
11 "github.com/docker/go-units"
12
13 "github.com/sylvinus/agent-vm/internal/paths"
14 "github.com/sylvinus/agent-vm/internal/vm"
15 "github.com/sylvinus/agent-vm/internal/vmname"
16)
17
18// target is the VM `stop` and `rm` act on: the current directory's, or one
19// named as `list` prints it. Agent-vm's Lima home holds its VMs alone (see
20// newApp), so any name there is one of them. A VM no folder names any more
21// (renamed, deleted) is reached by its name. The status is 0 when the VM is
22// found, else the exit status of the command.
23func (e *app) target(ctx context.Context, verb string, args []string) (name string, status int) {
24 switch len(args) {
25 case 0:
26 wd, err := vmname.AbsDir("")
27 if err != nil {
28 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
29 return "", 1
30 }
31 name = e.instanceName(wd)
32 case 1:
33 name = args[0]
34 default:
35 fmt.Fprintf(e.io.Stderr, "Usage: agent-vm %s [vm-name]\n", verb)
36 return "", exitUsage
37 }
38 b, err := e.backend()
39 if err == nil {
40 _, err = b.Get(ctx, name)
41 }
42 switch {
43 case err == nil:
44 return name, 0
45 case errors.Is(err, vm.ErrNotFound) && len(args) == 0:
46 fmt.Fprintln(e.io.Stderr, "No VM found for this directory.")
47 fmt.Fprintf(e.io.Stderr, "Run 'agent-vm list' to see existing VMs, then 'agent-vm %s <vm-name>'.\n", verb)
48 case errors.Is(err, vm.ErrNotFound):
49 fmt.Fprintf(e.io.Stderr, "Error: no such VM: %s\n", name)
50 fmt.Fprintln(e.io.Stderr, "Run 'agent-vm list' to see existing VMs.")
51 default:
52 fmt.Fprintf(e.io.Stderr, "Error: could not query Lima: %v\n", err)
53 }
54 return "", 1
55}
56
57func (e *app) stopCmd(ctx context.Context, args []string) int {
58 name, status := e.target(ctx, "stop", args)
59 if status != 0 {
60 return status
61 }
62 fmt.Fprintf(e.io.Stdout, "Stopping VM '%s'...\n", name)
63 if !e.stopVM(ctx, name) {
64 fmt.Fprintf(e.io.Stderr, "Error: VM '%s' is still running, or Lima cannot say. See 'agent-vm list'.\n", name)
65 return 1
66 }
67 fmt.Fprintln(e.io.Stdout, "VM stopped.")
68 return 0
69}
70
71// startVM starts name on b. Lima's hostagent outlives the command, so a start
72// that fails (the VM never came up) would leave it running, cut off: it is
73// stopped. Not after an interrupt: that start goes on in the background, as
74// limactl's does, and the next command finds the VM up.
75func (e *app) startVM(ctx context.Context, b vm.Backend, name string, log io.Writer) error {
76 err := b.Start(ctx, name, log)
77 if err != nil && ctx.Err() == nil {
78 if stopErr := b.Stop(ctx, name); stopErr != nil {
79 err = errors.Join(err, fmt.Errorf("stopping VM '%s' failed, it may still be running: %w", name, stopErr))
80 }
81 }
82 return err
83}
84
85// stopVM stops name, and reports whether it is known to be stopped.
86func (e *app) stopVM(ctx context.Context, name string) bool {
87 b, err := e.backend()
88 if err != nil {
89 return false
90 }
91 _ = b.Stop(ctx, name)
92 inst, err := b.Get(ctx, name)
93 return err == nil && inst.Status == vm.Stopped
94}
95
96func (e *app) rmCmd(ctx context.Context, args []string) int {
97 name, status := e.target(ctx, "rm", args)
98 if status != 0 {
99 return status
100 }
101 if !e.removeVM(ctx, name) {
102 return 1
103 }
104 return 0
105}
106
107// removeVM stops and deletes name, saying so, and reports whether it is gone.
108func (e *app) removeVM(ctx context.Context, name string) bool {
109 fmt.Fprintf(e.io.Stdout, "Stopping and deleting VM '%s'...\n", name)
110 if !e.deleteVM(ctx, name) {
111 return false
112 }
113 fmt.Fprintln(e.io.Stdout, "VM destroyed.")
114 return true
115}
116
117// deleteVM stops and deletes name, then forgets what agent-vm knew of it.
118// Fails, saying so, when it is still there (or cannot be asked): --reset
119// would otherwise go on with the old VM and its shares.
120func (e *app) deleteVM(ctx context.Context, name string) bool {
121 b, err := e.backend()
122 if err == nil {
123 _ = b.Delete(ctx, name)
124 _, err = b.Get(ctx, name)
125 }
126 if !errors.Is(err, vm.ErrNotFound) {
127 fmt.Fprintf(e.io.Stderr, "Error: could not delete VM '%s'. See 'agent-vm list', then retry.\n", name)
128 return false
129 }
130 if err := e.state.Forget(name, vmname.Template); err != nil {
131 fmt.Fprintf(e.io.Stderr, "Warning: %v\n", err)
132 }
133 return true
134}
135
136// `destroy-all`: every agent-vm VM, the base template included: the command
137// that gives the disk space back. `agent-vm setup` rebuilds the template.
138func (e *app) destroyAllCmd(ctx context.Context, args []string) int {
139 if len(args) > 0 {
140 fmt.Fprintln(e.io.Stderr, "Usage: agent-vm destroy-all")
141 return exitUsage
142 }
143 vms, err := e.agentVMs(ctx)
144 if err != nil {
145 fmt.Fprintf(e.io.Stderr, "Error: could not query Lima: %v\n", err)
146 return 1
147 }
148 if len(vms) == 0 {
149 fmt.Fprintln(e.io.Stdout, "No agent-vm VMs found.")
150 return 0
151 }
152 fmt.Fprintln(e.io.Stdout, "This will destroy the following VMs:")
153 base := false
154 for _, v := range vms {
155 fmt.Fprintln(e.io.Stdout, v.Name)
156 base = base || v.Name == vmname.Template
157 }
158 if base {
159 fmt.Fprintf(e.io.Stdout, "(%s is the base template: 'agent-vm setup' rebuilds it.)\n", vmname.Template)
160 }
161 if !e.ui.CanAsk() {
162 fmt.Fprintln(e.io.Stderr, "Error: destroy-all asks before it deletes, and there is no terminal to ask on. Nothing was destroyed.")
163 return 1
164 }
165 if !e.ui.AskYN("Continue?", false) {
166 fmt.Fprintln(e.io.Stdout, "Aborted.")
167 return 0
168 }
169 st := 0
170 for _, v := range vms {
171 fmt.Fprintf(e.io.Stdout, "Destroying %s...\n", v.Name)
172 if !e.deleteVM(ctx, v.Name) {
173 st = 1
174 }
175 }
176 if st != 0 {
177 return st
178 }
179 fmt.Fprintln(e.io.Stdout, "All VMs destroyed.")
180 return 0
181}
182
183// agentVMs lists the VMs, after moving 0.2's: for the commands that change
184// them.
185func (e *app) agentVMs(ctx context.Context) ([]*vm.Instance, error) {
186 b, err := e.backend()
187 if err != nil {
188 return nil, err
189 }
190 return b.List(ctx)
191}
192
193// lookVMs lists the VMs without moving 0.2's: for the commands that only look.
194func (e *app) lookVMs(ctx context.Context) ([]*vm.Instance, error) {
195 b, err := e.readOnlyBackend()
196 if err != nil {
197 return nil, err
198 }
199 return b.List(ctx)
200}
201
202// `list`, `status`: the agent-vm VMs as Lima's table shows them, the
203// current directory's marked with >, and the base each was cloned from in a
204// last column. Read-only: 0.2's VMs are said to wait, not moved.
205func (e *app) listCmd(ctx context.Context, args []string) int {
206 if len(args) > 0 {
207 fmt.Fprintln(e.io.Stderr, "Usage: agent-vm list")
208 return exitUsage
209 }
210 current := ""
211 if wd, err := vmname.AbsDir(""); err == nil {
212 current = e.instanceName(wd)
213 }
214 vms, err := e.lookVMs(ctx)
215 if err != nil {
216 fmt.Fprintf(e.io.Stderr, "Error: could not query Lima: %v\n", err)
217 return 1
218 }
219 if old, from := e.unmovedOld(); len(old) > 0 {
220 fmt.Fprintf(e.io.Stderr, "%d VM(s) of agent-vm 0.2 in %s are not listed: the next command that starts a VM offers to move them.\n", len(old), from)
221 }
222 if len(vms) == 0 {
223 fmt.Fprintln(e.io.Stdout, " (no VMs)")
224 return 0
225 }
226 lines := strings.Split(strings.TrimSuffix(table(vms), "\n"), "\n")
227 w := 0
228 for _, l := range lines {
229 w = max(w, len(l))
230 }
231 fmt.Fprintf(e.io.Stdout, " %-*s %s\n", w, lines[0], "BASE")
232 for i, l := range lines[1:] {
233 mark := " "
234 if vms[i].Name == current {
235 mark = ">"
236 }
237 fmt.Fprintf(e.io.Stdout, "%s %-*s %s\n", mark, w, l, e.state.BaseLabel(vms[i].Name, vmname.Template))
238 }
239 return 0
240}
241
242// table is Lima's `limactl list` table, every column shown.
243func table(vms []*vm.Instance) string {
244 var b strings.Builder
245 w := tabwriter.NewWriter(&b, 4, 8, 4, ' ', 0)
246 fmt.Fprintln(w, "NAME\tSTATUS\tSSH\tVMTYPE\tARCH\tCPUS\tMEMORY\tDISK\tDIR")
247 home := paths.Home()
248 for _, v := range vms {
249 dir := paths.Host(v.Dir)
250 if rel, ok := paths.In(dir, home); ok {
251 dir = strings.TrimSuffix("~/"+rel, "/.")
252 }
253 fmt.Fprintf(w, "%s\t%s\t%s:%d\t%s\t%s\t%d\t%s\t%s\t%s\n", v.Name, v.Status, v.SSHAddress, v.SSHLocalPort,
254 v.VMType, v.Arch, v.CPUs, units.BytesSize(float64(v.Memory)), units.BytesSize(float64(v.Disk)), dir)
255 }
256 w.Flush()
257 return b.String()
258}