跳到主要内容

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

浏览文件

commands.go

320 行 · 11.0 KB历史下载
1package cli
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "os/signal"
8 "strconv"
9 "strings"
10 "syscall"
11 "time"
12
13 "github.com/sylvinus/agent-vm/internal/paths"
14 "github.com/sylvinus/agent-vm/internal/state"
15 "github.com/sylvinus/agent-vm/internal/ui"
16 "github.com/sylvinus/agent-vm/internal/vm"
17 "github.com/sylvinus/agent-vm/internal/vmname"
18)
19
20// session is what runs in the VM once it is up: an agent, a shell, a
21// command. It returns the exit status.
22type session func(s *start) int
23
24// endedBySignal is ctx for a run that a kill or a closed terminal (SIGTERM,
25// SIGHUP) must end: the command in the VM stops with it, and the cleanup
26// that follows (--rm, --scratch) runs on a context that does not end. A
27// Ctrl-C is not one: see inVM. Signals after the first are swallowed until
28// stop, so that the cleanup is not cut short.
29func endedBySignal(parent context.Context) (ctx context.Context, stop func()) {
30 ctx, cancel := context.WithCancel(parent)
31 sig := make(chan os.Signal, 4)
32 signal.Notify(sig, syscall.SIGTERM, syscall.SIGHUP)
33 done := make(chan struct{})
34 go func() {
35 for {
36 select {
37 case <-sig:
38 cancel()
39 case <-done:
40 return
41 }
42 }
43 }()
44 return ctx, func() {
45 signal.Stop(sig)
46 close(done)
47 cancel()
48 }
49}
50
51// inVM starts this directory's VM with opts, runs fn, then deletes the VM
52// when --rm asked: after fn whatever it returns, and after a start that
53// failed when this run made the VM (a VM that was there before is not
54// deleted for a start that did not go through). A kill or a closed terminal
55// (SIGTERM, SIGHUP) ends the command and still deletes. --scratch: see
56// scratch.
57func (e *app) inVM(ctx context.Context, opts VMOpts, fn session) int {
58 dir, err := vmname.AbsDir("")
59 if err != nil {
60 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
61 return 1
62 }
63 cleanup := context.WithoutCancel(ctx)
64 ctx, stop := endedBySignal(ctx)
65 defer stop()
66 if opts.Scratch {
67 return e.scratch(ctx, cleanup, opts, dir, fn)
68 }
69 s := &start{app: e, ctx: ctx, opts: opts, dir: dir, name: e.instanceName(dir)}
70 if os.Getenv("CLAUDE_CAGE_CONFIG") != "" {
71 b, err := s.backend()
72 if err != nil {
73 fmt.Fprintln(e.io.Stderr, err)
74 return 1
75 }
76 instances, err := b.List(ctx)
77 if err != nil {
78 fmt.Fprintln(e.io.Stderr, err)
79 return 1
80 }
81 for _, inst := range instances {
82 if inst.Status == vm.Running && inst.Name != s.name {
83 fmt.Fprintf(e.io.Stderr, "Cage uses one persistent environment per profile; stop legacy VM %s before connecting it.\n", inst.Name)
84 return 1
85 }
86 }
87 }
88 st := 1
89 started := s.ensureRunning() == nil
90 if started {
91 s.printResources()
92 // A Ctrl-C is the command's, in the VM, as a shell leaves it to the job
93 // it waits on: this run goes on to --rm and the terminal's reset.
94 sig := make(chan os.Signal, 1)
95 signal.Notify(sig, os.Interrupt)
96 st = fn(s)
97 signal.Stop(sig)
98 ui.ResetTermModes(os.Stdout)
99 }
100 if opts.RM && (started || s.created) && !e.removeVM(cleanup, s.name) && st == 0 {
101 st = 1
102 }
103 return st
104}
105
106// printResources says what the VM has, and when the base it was cloned
107// from was built: its agents and packages are that old.
108func (s *start) printResources() {
109 if inst, err := s.get(s.name); err == nil && inst != nil {
110 fmt.Fprintf(s.io.Stdout, " Resources: CPUs: %d, Memory: %d GiB, Disk: %d GiB\n", inst.CPUs, inst.Memory>>30, inst.Disk>>30)
111 }
112 if built, err := strconv.ParseInt(s.state.ReadMarker(state.VersionOf, s.name), 10, 64); err == nil && built >= 0 {
113 fmt.Fprintf(s.io.Stdout, " Base VM: built %s\n", time.Unix(built, 0).Format("2006-01-02"))
114 }
115}
116
117// lima runs args in the VM through a login zsh, from the project: agent PATH
118// entries and ~/.agent-vm.env are in ~/.zshenv. The command and its
119// arguments are positional parameters, never re-parsed; `env --` runs it,
120// leading VAR=value assignments working and a command starting with - not
121// taken for env's option. A command that is not there is said so, with
122// env's status (an agent installed only as an editor extension has none);
123// a path is env's to run, and to say why it cannot (126).
124func (s *start) lima(tty bool, args ...string) int {
125 b, err := s.backend()
126 if err != nil {
127 return 1
128 }
129 code, err := b.Shell(s.ctx, s.name, vm.ShellOpts{
130 Workdir: paths.Guest(s.dir),
131 Args: append([]string{"zsh", "-l", "-c",
132 `case "$1" in *=*|*/*) ;; *) command -v -- "$1" >/dev/null || { print -r -- "agent-vm: $1 is not installed in this VM." >&2; exit 127; } ;; esac; exec env -- "$@"`,
133 "agent-vm"}, args...),
134 Stdin: s.io.Stdin, Stdout: s.io.Stdout, Stderr: s.io.Stderr, Interactive: tty,
135 })
136 if err != nil {
137 s.warnf("Error: %v", err)
138 return 1
139 }
140 return code
141}
142
143// The agents, with the flag that lets each work unattended (safe in the
144// VM), and a terminal for the full-screen ones.
145var agents = map[string]struct {
146 cmd []string
147 tty bool
148}{
149 // The VM also enforces bypass mode with managed settings: Claude Code
150 // drops the flag when it relaunches itself.
151 "claude": {[]string{"claude", "--dangerously-skip-permissions"}, false},
152 // Approves every prompt that is not explicitly denied.
153 "opencode": {[]string{"opencode", "--auto"}, true},
154 "codex": {[]string{"codex", "--dangerously-bypass-approvals-and-sandbox"}, false},
155 "vibe": {[]string{"vibe", "--agent", "auto-approve"}, true},
156 // No permission prompts: it runs every tool as asked.
157 "pi": {[]string{"pi"}, true},
158}
159
160func (e *app) agentCmd(ctx context.Context, agent string, opts VMOpts, args []string) int {
161 a := agents[agent]
162 rest, tty, err := opts.split(args)
163 if err != nil {
164 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
165 return exitUsage
166 }
167 cmd := append(append([]string(nil), a.cmd...), rest...)
168 return e.inVM(ctx, opts, func(s *start) int { return s.lima(a.tty || tty, cmd...) })
169}
170
171// `run [--tty] <command> [args]`: --tty gives the command a terminal, which
172// full-screen programs need to draw.
173func (e *app) runCmd(ctx context.Context, opts VMOpts, args []string) int {
174 rest, tty, err := opts.split(args)
175 if err != nil {
176 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
177 return exitUsage
178 }
179 if len(rest) == 0 {
180 fmt.Fprintln(e.io.Stderr, "Usage: agent-vm run [--tty] <command> [args]")
181 return exitUsage
182 }
183 return e.inVM(ctx, opts, func(s *start) int { return s.lima(tty, rest...) })
184}
185
186// `shell [-c "command"]`: a login zsh in the VM, ~/.zshenv loaded. A word
187// it does not know is an error, not something skipped.
188func (e *app) shellCmd(ctx context.Context, opts VMOpts, args []string) int {
189 command := ""
190 for len(args) > 0 {
191 n, err := opts.take(args)
192 if err != nil {
193 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
194 return exitUsage
195 }
196 if n > 0 {
197 args = args[n:]
198 continue
199 }
200 switch args[0] {
201 case "-c", "--command":
202 if len(args) < 2 || args[1] == "" {
203 fmt.Fprintln(e.io.Stderr, "Error: -c/--command requires a command string.")
204 return exitUsage
205 }
206 command, args = args[1], args[2:]
207 default:
208 fmt.Fprintf(e.io.Stderr, "Error: unknown argument for shell: %s\nUsage: agent-vm [vm options] shell [-c \"command\"]\n", args[0])
209 return exitUsage
210 }
211 }
212 return e.inVM(ctx, opts, func(s *start) int {
213 if command != "" {
214 return s.shell(false, "zsh", "-l", "-c", command)
215 }
216 fmt.Fprintf(s.io.Stdout, "VM: %s | Dir: %s\n", s.name, s.dir)
217 if s.opts.RM {
218 fmt.Fprintln(s.io.Stdout, "Type 'exit' to leave. VM will be destroyed after exit.")
219 } else {
220 fmt.Fprintln(s.io.Stdout, "Type 'exit' to leave (VM keeps running). Use 'agent-vm stop' to stop it.")
221 }
222 return s.shell(true, "zsh", "-l")
223 })
224}
225
226// shellTo runs args in the VM from the project, on the terminal.
227func (s *start) shellTo(tty bool, args ...string) (int, error) {
228 b, err := s.backend()
229 if err != nil {
230 return 1, err
231 }
232 return b.Shell(s.ctx, s.name, vm.ShellOpts{Workdir: paths.Guest(s.dir), Args: args,
233 Stdin: s.io.Stdin, Stdout: s.io.Stdout, Stderr: s.io.Stderr, Interactive: tty})
234}
235
236// shell is shellTo's exit status. When the shell could not run at all (the
237// VM is not running, ssh fails), the reason is said and the status is 1: a
238// caller must not read that as the command's success.
239func (s *start) shell(tty bool, args ...string) int {
240 code, err := s.shellTo(tty, args...)
241 if err != nil {
242 s.warnf("Error: %v", err)
243 return 1
244 }
245 return code
246}
247
248// scratch: a new VM of its own, sharing nothing, deleted once fn returns,
249// whatever it returns, unless the user keeps it a while to look inside. A
250// Ctrl-C ends the command in the VM, not this run, which goes on to the
251// deletion. A run killed outright leaves its VM recorded with its pid, and
252// the next scratch run deletes it. cleanup is the context of the deletions,
253// which a kill of this run (ctx) does not end.
254func (e *app) scratch(ctx, cleanup context.Context, opts VMOpts, dir string, fn session) int {
255 dead, unknown := e.scratchLeftovers()
256 for _, left := range dead {
257 fmt.Fprintf(e.io.Stdout, "Deleting scratch VM '%s', left by a run that did not finish...\n", left)
258 e.deleteVM(cleanup, left)
259 }
260 for _, left := range unknown {
261 fmt.Fprintf(e.io.Stderr, "Note: scratch VM '%s' has a record without a process number, so it is not known whether a run still uses it: left alone. 'agent-vm rm %s' deletes it.\n", left, left)
262 }
263 name, err := e.names.Scratch(dir)
264 if err != nil {
265 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
266 return 1
267 }
268 if err := e.state.Write(state.ScratchOf+name, []byte(strconv.Itoa(os.Getpid())+"\n")); err != nil {
269 fmt.Fprintf(e.io.Stderr, "Error: could not record scratch VM '%s': %v\n", name, err)
270 return 1
271 }
272 opts.RM = true
273 s := &start{app: e, ctx: ctx, opts: opts, dir: dir, name: name}
274 st := 1
275 if s.ensureRunning() == nil {
276 s.printResources()
277 sig := make(chan os.Signal, 1)
278 signal.Notify(sig, os.Interrupt)
279 st = fn(s)
280 signal.Stop(sig)
281 ui.ResetTermModes(os.Stdout)
282 // Asked before the deletion, when it can be (yes by default): a no
283 // opens a shell in the VM, to look at what the command left, and
284 // asks again on its exit. No terminal, a question cut short, or a
285 // kill, deletes.
286 for ctx.Err() == nil && e.ui.CanAsk() && !e.ui.AskYN(fmt.Sprintf("Delete scratch VM '%s'?", name), true) {
287 fmt.Fprintf(e.io.Stdout, "A shell in scratch VM '%s'. Type 'exit' to be asked again.\n", name)
288 s.shell(true, "zsh", "-l")
289 ui.ResetTermModes(os.Stdout)
290 }
291 }
292 fmt.Fprintf(e.io.Stdout, "Deleting scratch VM '%s'...\n", name)
293 if !e.deleteVM(cleanup, name) {
294 st = 1
295 }
296 return st
297}
298
299// scratchLeftovers are the scratch VMs a run could not delete (killed, its
300// terminal closed), by their record: dead are those recorded by a run whose
301// pid is gone (a reused pid only delays the cleanup), unknown those whose
302// record holds no pid, which is no proof that no run uses them. Only names
303// Scratch makes.
304func (e *app) scratchLeftovers() (dead, unknown []string) {
305 ents, _ := os.ReadDir(string(e.state))
306 for _, f := range ents {
307 name, ok := strings.CutPrefix(f.Name(), state.ScratchOf)
308 if !ok || !vmname.IsScratch(name) {
309 continue
310 }
311 pid, err := strconv.Atoi(strings.TrimSpace(e.state.Read(f.Name())))
312 switch {
313 case err != nil || pid <= 0:
314 unknown = append(unknown, name)
315 case !alive(pid):
316 dead = append(dead, name)
317 }
318 }
319 return dead, unknown
320}