跳到主要内容

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

浏览文件

start.go

900 行 · 30.5 KB历史下载
1package cli
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "reflect"
13 "slices"
14 "strings"
15
16 "github.com/sylvinus/agent-vm/internal/cage"
17 "github.com/sylvinus/agent-vm/internal/env"
18 "github.com/sylvinus/agent-vm/internal/guard"
19 "github.com/sylvinus/agent-vm/internal/host"
20 "github.com/sylvinus/agent-vm/internal/mounts"
21 "github.com/sylvinus/agent-vm/internal/netguard"
22 "github.com/sylvinus/agent-vm/internal/paths"
23 "github.com/sylvinus/agent-vm/internal/runscript"
24 "github.com/sylvinus/agent-vm/internal/state"
25 "github.com/sylvinus/agent-vm/internal/vm"
26 "github.com/sylvinus/agent-vm/internal/vmname"
27)
28
29var errStop = errors.New("stop")
30
31// get is the VM name, nil when there is none.
32func (s *start) get(name string) (*vm.Instance, error) {
33 b, err := s.backend()
34 if err != nil {
35 return nil, err
36 }
37 inst, err := b.Get(s.ctx, name)
38 if errors.Is(err, vm.ErrNotFound) {
39 return nil, nil
40 }
41 return inst, err
42}
43
44func (s *start) running() bool {
45 inst, err := s.get(s.name)
46 return err == nil && inst != nil && inst.Status == vm.Running
47}
48
49// shares is what the VM gets now: the project and the volumes, writable or
50// not, with the read-only names when .git is protected; nothing for a
51// scratch VM. The mount type that goes with them is reverse-sshfs: with the
52// read-only names, it is what enforces them; without, the builtin SFTP
53// server still serves the shares alone.
54//
55// Built once per mode and names, so its warnings show once.
56func (s *start) shares(writable bool) ([]vm.Mount, []mounts.FileMount) {
57 if s.opts.Scratch {
58 return []vm.Mount{}, nil
59 }
60 n := s.names
61 if !s.protect {
62 n = []string{}
63 }
64 key := fmt.Sprint(writable, n)
65 if s.built != nil && s.builtKey == key {
66 return s.built, s.builtFiles
67 }
68 s.built, s.builtFiles = mounts.Build(mounts.Shares{
69 VM: s.name, Dir: s.dir, Writable: writable, Names: n,
70 Entries: s.entries(s.dir, s.io.Stderr), StateDir: string(s.state), Warn: s.io.Stderr,
71 })
72 s.builtKey = key
73 return s.built, s.builtFiles
74}
75
76// applyShares gives the stopped VM its shares, and records the single files
77// of the volumes for the bind once it runs.
78func (s *start) applyShares(writable bool) error {
79 b, err := s.backend()
80 if err != nil {
81 return err
82 }
83 ms, files := s.shares(writable)
84 mt := vm.ReverseSSHFS
85 if err := b.Edit(s.ctx, s.name, vm.Settings{Mounts: &ms, MountType: &mt}); err != nil {
86 s.warnf("Error: could not set the shares of VM '%s':\n%v", s.name, err)
87 return errStop
88 }
89 cache := s.state.Marker(state.FileMountsOf, s.name)
90 if err := os.Remove(cache); err != nil && !os.IsNotExist(err) {
91 s.warnf("Error: could not remove %s:\n%v", cache, err)
92 return errStop
93 }
94 if len(files) > 0 {
95 var lines []string
96 for _, f := range files {
97 lines = append(lines, f.Line())
98 }
99 if err := s.state.Write(state.FileMountsOf+s.name, []byte(strings.Join(lines, "\n")+"\n")); err != nil {
100 s.warnf("Error: could not record the single files of ~/.agent-vm/volumes for VM '%s':\n%v", s.name, err)
101 return errStop
102 }
103 }
104 return nil
105}
106
107// applyResources gives the stopped VM the memory, CPUs and SSH port asked
108// for. The disk apart, with a warning only: it can grow, not shrink.
109func (s *start) applyResources() error {
110 b, err := s.backend()
111 if err != nil {
112 return err
113 }
114 set := vm.Settings{CPUs: s.opts.CPUs, MemoryGiB: s.opts.Memory}
115 if s.opts.SSHPort >= 0 {
116 p := s.opts.SSHPort
117 set.SSHLocalPort = &p
118 }
119 if err := b.Edit(s.ctx, s.name, set); err != nil {
120 s.warnf("Error: could not set the memory, CPUs or SSH port of VM '%s':\n%v", s.name, err)
121 return errStop
122 }
123 if s.opts.Disk > 0 {
124 if err := b.Edit(s.ctx, s.name, vm.Settings{DiskGiB: s.opts.Disk}); err != nil {
125 s.warnf("Warning: cannot set the disk of VM '%s' to %d GiB: it can grow, not shrink ('agent-vm setup --disk %d' for a smaller base).\n%v", s.name, s.opts.Disk, s.opts.Disk, err)
126 }
127 }
128 return nil
129}
130
131// resourcesDiffer: would the resources asked change anything? Compared in
132// bytes; the disk one way, since it can only grow. True when the VM cannot
133// be read: never "no change" from missing information.
134func (s *start) resourcesDiffer(inst *vm.Instance) bool {
135 o := s.opts
136 switch {
137 case inst == nil:
138 return true
139 case o.CPUs > 0 && o.CPUs != inst.CPUs:
140 return true
141 case o.Memory > 0 && int64(o.Memory)<<30 != inst.Memory:
142 return true
143 case o.Disk > 0 && int64(o.Disk)<<30 > inst.Disk:
144 return true
145 }
146 return false
147}
148
149// stopToChange stops the VM to change it, then asks what its start did not,
150// a running VM having been asked nothing.
151func (s *start) stopToChange() error {
152 if !s.stopVM(s.ctx, s.name) {
153 s.warnf("Error: could not stop VM '%s': nothing was changed.", s.name)
154 return errStop
155 }
156 if s.vmUp {
157 s.vmUp = false
158 if !s.checks() {
159 s.warnf("VM '%s' is stopped.", s.name)
160 return errStop
161 }
162 }
163 return nil
164}
165
166// beforeBoot fails unless what Lima would boot the stopped VM with is what
167// agent-vm set: every share with the read-only names when protected, no
168// share for a scratch VM.
169func (s *start) beforeBoot() error {
170 inst, err := s.get(s.name)
171 if err != nil || inst == nil {
172 s.warnf("Error: could not read Lima's config for VM '%s', so what it would boot with is not known.", s.name)
173 return errStop
174 }
175 // Each that applies, none in place of another: --readonly with .git
176 // protected must hold both.
177 var whys []string
178 if s.opts.Scratch && len(inst.Mounts) > 0 {
179 whys = append(whys, "a share, though a scratch VM gets none")
180 }
181 if err := vm.Confined(inst); err != nil {
182 whys = append(whys, err.Error())
183 }
184 if s.protect && !s.opts.Scratch {
185 whys = append(whys, unprotected(inst, s.names))
186 }
187 if s.opts.ReadOnly {
188 whys = append(whys, notReadOnly(inst))
189 }
190 for _, why := range whys {
191 if why != "" {
192 s.warnf("Error: VM '%s' would not boot as asked: %s.", s.name, why)
193 return errStop
194 }
195 }
196 if err := policiesErr(s.state); err != nil {
197 s.warnf("Error: %v", err)
198 return errStop
199 }
200 return nil
201}
202
203// policiesErr is what the hostagent would stop on in the network and
204// guarded files: said here, where the user sees it, not in Lima's log.
205func policiesErr(st state.Dir) error {
206 if _, err := netguard.Load(string(st)); err != nil {
207 return err
208 }
209 _, err := guard.Load(string(st), "")
210 return err
211}
212
213// configErr says so when Lima cannot read inst's config.
214func (s *start) configErr(inst *vm.Instance) bool {
215 if inst == nil || inst.ConfigErr == nil {
216 return false
217 }
218 s.warnf("Error: Lima cannot read the config of VM '%s':\n %v\n'agent-vm --reset <command>' re-clones it.", inst.Name, inst.ConfigErr)
219 return true
220}
221
222// limaOverridesOK says so when Lima's default.yaml or override.yaml would
223// add to what agent-vm sets for every VM.
224func (s *start) limaOverridesOK() bool {
225 found := vm.LimaOverrides(LimaHome(s.state))
226 for _, f := range found {
227 s.warnf("Error: %s adds to every VM's config (shares, mount type...): agent-vm makes and starts no VM while it is there. Move it out of the way.", f)
228 }
229 return len(found) == 0
230}
231
232// The verdicts on a VM's shares, "" when they hold. Each starts from
233// vm.Confined: only the builtin SFTP server over reverse-sshfs enforces
234// anything on the host.
235
236// unprotected says why inst's shares leave .git writable: not confined, or
237// a share without one of names (mounts.BaseNames when nil; more is no less
238// safe).
239func unprotected(inst *vm.Instance, names []string) string {
240 if err := vm.Confined(inst); err != nil {
241 return err.Error()
242 }
243 if names == nil {
244 names = mounts.BaseNames
245 }
246 for _, m := range inst.Mounts {
247 if slices.ContainsFunc(names, func(n string) bool { return !slices.Contains(m.SSHFS.ReadonlyNames, n) }) {
248 return "the share of " + m.Location + " lacks the read-only names"
249 }
250 }
251 return ""
252}
253
254// notReadOnly says why inst's shares are not all read-only on the host.
255func notReadOnly(inst *vm.Instance) string {
256 if err := vm.Confined(inst); err != nil {
257 return err.Error()
258 }
259 for _, m := range inst.Mounts {
260 if m.Writable {
261 return "a writable share of " + m.Location
262 }
263 }
264 return ""
265}
266
267// sharesDiffer reports whether inst's shares differ from want, Lima's
268// defaults (sshfs's cache on, no SFTP driver named) filled in on both.
269func sharesDiffer(inst *vm.Instance, want []vm.Mount) bool {
270 if len(inst.Mounts) == 0 && len(want) == 0 {
271 return false
272 }
273 norm := func(ms []vm.Mount) []vm.Mount {
274 out := make([]vm.Mount, len(ms))
275 for i, m := range ms {
276 o := vm.SSHFS{}
277 if m.SSHFS != nil {
278 o = *m.SSHFS
279 }
280 if o.Cache == nil {
281 on := true
282 o.Cache = &on
283 }
284 if len(o.ReadonlyNames) == 0 {
285 o.ReadonlyNames = nil
286 }
287 m.SSHFS = &o
288 out[i] = m
289 }
290 return out
291 }
292 return !reflect.DeepEqual(norm(inst.Mounts), norm(want)) || inst.MountType != vm.ReverseSSHFS
293}
294
295// allReadOnly reports whether every share of inst is read-only.
296func allReadOnly(inst *vm.Instance) bool {
297 for _, m := range inst.Mounts {
298 if m.Writable {
299 return false
300 }
301 }
302 return len(inst.Mounts) > 0
303}
304
305// ensureRunning makes the project's VM exist and run, with its shares as
306// asked: cloned from the base, changed while stopped, the security checks
307// done first. Under the VM's lock: another run in the same folder waits for
308// this one to be done with the VM, and cleans up nothing of it meanwhile.
309func (s *start) ensureRunning() error {
310 // A scratch VM has a name of its own, which no other run uses.
311 if !s.opts.Scratch {
312 unlock, err := s.lockVM(s.ctx, s.name)
313 if err != nil {
314 s.warnf("Error: could not lock VM '%s': %v", s.name, err)
315 return errStop
316 }
317 defer unlock()
318 }
319 return s.ensureRunningLocked()
320}
321
322func (s *start) ensureRunningLocked() error {
323 o := &s.opts
324 if o.Scratch && (o.Reset || o.ReadOnly) {
325 s.warnf("Error: --scratch makes a new VM that shares nothing: --reset and --readonly do not go with it.")
326 return errStop
327 }
328 wantWritable := !o.ReadOnly
329 o.CPUs = host.Cap("cpus", o.CPUs, s.io.Stderr)
330 o.Memory = host.Cap("memory", o.Memory, s.io.Stderr)
331 host.WarnDiskSpace(LimaHome(s.state), o.Disk, s.io.Stderr)
332 b, err := s.backend()
333 if err != nil {
334 s.warnf("Error: %v", err)
335 return errStop
336 }
337 if !s.limaOverridesOK() {
338 return errStop
339 }
340 warnDomains(s.state, s.io.Stderr)
341 // Two VMs set to one port: the second would fail to start.
342 if o.SSHPort > 0 {
343 if all, err := b.List(s.ctx); err == nil {
344 for _, v := range all {
345 if v.Name != s.name && v.SSHPortConfig == o.SSHPort {
346 s.warnf("Error: SSH port %d is already set for VM '%s'.", o.SSHPort, v.Name)
347 return errStop
348 }
349 }
350 }
351 }
352 // `cd ~ && agent-vm shell` would hand the VM your dotfiles and SSH
353 // keys, read-write; a share holding agent-vm's own files lets the VM
354 // change what the host runs next. agent-vm's own clone may be shared
355 // once the security prompts are off: working on agent-vm in its VM.
356 if !o.Scratch {
357 refs := s.refs()
358 if _, off := s.promptsDisabledBy(); off {
359 var others []mounts.Ref
360 for _, r := range refs {
361 if r.What != mounts.SelfRef {
362 others = append(others, r)
363 }
364 }
365 if _, bad := mounts.UnsafeProject(s.dir, others); !bad {
366 if why, self := mounts.UnsafeLocation(s.dir, refs); self {
367 s.warnf("Warning: sharing %s with the VM: it %s. The VM can change the agent-vm this machine runs next.", s.dir, why)
368 s.confirmUnsafe()
369 }
370 refs = others
371 }
372 }
373 if why, bad := mounts.UnsafeProject(s.dir, refs); bad {
374 s.warnf("Error: refusing to share %s with a VM: it %s.\nRun agent-vm from a project directory.", s.dir, why)
375 return errStop
376 }
377 if why, bad := mounts.Unmountable(s.dir); bad {
378 s.warnf("Error: project path %s:\n %s\nRename the directory, then retry.", why, s.dir)
379 return errStop
380 }
381 }
382 // A run interrupted while Lima made it leaves a folder without lima.yaml.
383 // Under the VM's lock: no other run is making it now.
384 if d := filepath.Join(LimaHome(s.state), s.name); isDirNoYAML(d) {
385 s.warnf("Detected partial VM state at %s (no lima.yaml): cleaning up.", d)
386 if err := os.RemoveAll(d); err != nil {
387 s.warnf("Error: could not remove %s:\n%v", d, err)
388 return errStop
389 }
390 }
391 base, err := s.get(vmname.Template)
392 if err != nil {
393 s.warnf("Error: could not query Lima: %v", err)
394 return errStop
395 }
396 if s.configErr(base) {
397 return errStop
398 }
399 if _, merr := os.Stat(s.state.Path(state.BaseVersion)); base == nil || merr != nil {
400 if base != nil {
401 s.warnf("Error: Base VM setup did not complete. Run 'agent-vm setup' again.")
402 } else {
403 s.warnf("Error: Base VM not found. Run 'agent-vm setup' first.")
404 }
405 return errStop
406 }
407
408 s.vmUp = !o.Reset && s.running()
409 if !s.checks() {
410 return errStop
411 }
412 inst, err := s.get(s.name)
413 if err != nil {
414 s.warnf("Error: could not query Lima: %v", err)
415 return errStop
416 }
417 if !o.Reset && s.configErr(inst) {
418 return errStop
419 }
420 // Lima's hostagent died under it: the VM is cut off, and blocks its next
421 // start.
422 if inst != nil && inst.Orphaned {
423 s.warnf("Warning: VM '%s' was left running without Lima's host agent, cut off: stopping it.", s.name)
424 if !s.stopVM(s.ctx, s.name) {
425 s.warnf("Error: could not stop VM '%s'. See 'agent-vm list'.", s.name)
426 return errStop
427 }
428 if inst, err = s.get(s.name); err != nil {
429 s.warnf("Error: could not query Lima: %v", err)
430 return errStop
431 }
432 }
433 if o.Reset && inst != nil {
434 fmt.Fprintf(s.io.Stdout, "Resetting VM '%s'...\n", s.name)
435 if !s.deleteVM(s.ctx, s.name) {
436 return errStop
437 }
438 inst = nil
439 }
440
441 // 0.1.0 recorded no version for its bases, and their VMs have no sshfs,
442 // which the shares need; 0.2 migrated them in place.
443 if inst != nil && !o.Scratch && !exists(s.state.Marker(state.BuiltByOf, s.name)) && !exists(s.state.Marker(state.SSHFSOf, s.name)) {
444 s.warnf("Error: VM '%s' comes from a base built by agent-vm 0.1.0, without the sshfs its shares need. Run 'agent-vm setup', then 'agent-vm --reset <command>' here.", s.name)
445 return errStop
446 }
447
448 isNew := inst == nil
449 applyResize := false
450 if isNew {
451 fmt.Fprintf(s.io.Stdout, "Creating VM '%s'...\n", s.name)
452 marks, err := s.cloneBase()
453 if err != nil {
454 s.warnf("Error: could not clone the base template into '%s':\n%v", s.name, err)
455 if errors.Is(err, vm.ErrNameTooLong) {
456 s.warnf(" The VM's name comes from the project folder's: give the folder a shorter name.")
457 }
458 return errStop
459 }
460 s.created = true
461 for _, k := range []string{state.BuiltByOf, state.SSHFSOf} {
462 os.Remove(s.state.Marker(k, s.name))
463 }
464 if marks.builtBy != nil {
465 if err := s.state.Write(state.BuiltByOf+s.name, marks.builtBy); err != nil {
466 s.warnf("Error: could not record which agent-vm built the base of VM '%s': %v", s.name, err)
467 s.dropNew()
468 return errStop
469 }
470 } else if s.protect {
471 // 0.1.0's bases have no sshfs for the protected shares.
472 s.warnf("Error: the base VM was built by agent-vm 0.1.0, without what the shares that keep .git read-only need. Run 'agent-vm setup' to build a new one.")
473 s.dropNew()
474 return errStop
475 }
476 // Configured before its first start. A clone that could not be holds
477 // nothing yet: it goes, and the next run starts over.
478 if s.applyShares(wantWritable) != nil || s.applyResources() != nil {
479 s.dropNew()
480 return errStop
481 }
482 fmt.Fprint(s.io.Stdout, s.notes)
483 if marks.version != nil {
484 if err := s.state.Write(state.VersionOf+s.name, marks.version); err != nil {
485 s.warnf("Warning: could not record the base VM '%s' was cloned from: %v. Every start will say that the base has been updated.", s.name, err)
486 }
487 }
488 } else if ((o.Disk > 0 || o.Memory > 0 || o.CPUs > 0) && s.resourcesDiffer(inst)) || (o.SSHPort >= 0 && o.SSHPort != inst.SSHPortConfig) {
489 // Only when the request differs: a caller passing its defaults every
490 // time would otherwise be asked every time. Declined, the VM keeps
491 // its settings and everything below still applies.
492 applyResize = true
493 if s.running() {
494 fmt.Fprintf(s.io.Stdout, "VM '%s' is currently running. It must be stopped to apply new settings.\n", s.name)
495 if s.ui.CanAsk() && s.ui.AskYN("Stop the VM and apply changes?", false) {
496 fmt.Fprintln(s.io.Stdout, "Stopping VM...")
497 if err := s.stopToChange(); err != nil {
498 return err
499 }
500 } else {
501 fmt.Fprintln(s.io.Stdout, "Not applied: the VM keeps its current settings.")
502 applyResize = false
503 }
504 }
505 }
506 if applyResize {
507 fmt.Fprintln(s.io.Stdout, "Updating VM settings...")
508 if err := s.applyResources(); err != nil {
509 return err
510 }
511 }
512 if s.staleState(s.name) == "1" {
513 s.warnf("Warning: Base VM has been updated since this VM was cloned. Use --reset to re-clone from the new base.")
514 }
515
516 // The shares Lima has, against those asked: a stopped VM is changed
517 // before it boots, so nothing starting with it gets a writable window; a
518 // running one keeps its shares until stopped, or is offered a restart.
519 wasRunning := s.running()
520 if inst, err = s.get(s.name); err != nil || inst == nil {
521 s.warnf("Error: could not query Lima: %v", err)
522 return errStop
523 }
524 want, _ := s.shares(wantWritable)
525 wasProtected := len(inst.Mounts) > 0 && unprotected(inst, nil) == ""
526 gitStale := !o.Scratch && wasProtected != s.protect
527 namesStale := s.protect && wasProtected && unprotected(inst, s.names) != ""
528 stale := sharesDiffer(inst, want)
529 if !o.ReadOnly && wasRunning && s.protect && (gitStale || namesStale) {
530 if gitStale {
531 s.warnf("Warning: VM '%s' is running with .git writable, so the agent can still write .git.", s.name)
532 } else {
533 s.warnf("Warning: VM '%s' runs with an older list of read-only names (it needs %s), so the agent can still write the new ones.", s.name, strings.Join(s.names, ", "))
534 }
535 if _, off := s.promptsDisabledBy(); !off && s.ui.CanAsk() && s.ui.AskYN("Restart it now to apply them? Sessions using it are cut.", true) {
536 if err := s.stopToChange(); err != nil {
537 return err
538 }
539 wasRunning = false
540 } else if !s.confirmUnsafe() {
541 s.warnf("Aborted. 'agent-vm stop', then run again.")
542 return errStop
543 }
544 }
545 switch {
546 case gitStale && wasRunning && !s.protect:
547 s.warnf("Note: VM '%s' keeps .git read-only until it stops.", s.name)
548 case !wasRunning && stale:
549 switch {
550 case gitStale && s.protect:
551 fmt.Fprintf(s.io.Stdout, "Making every .git read-only for VM '%s'...\n", s.name)
552 case gitStale:
553 if cageWritableGit() {
554 fmt.Fprintf(s.io.Stdout, "Enabling Git writes in Cage projects for VM '%s'...\n", s.name)
555 } else {
556 s.warnf("Making .git writable for VM '%s' (%s)...", s.name, map[bool]string{true: "--unsafe-writable-git", false: "AGENT_VM_UNSAFE_WRITABLE_GIT=1"}[o.UnsafeWritableGit])
557 }
558 case namesStale:
559 fmt.Fprintf(s.io.Stdout, "Making %s read-only for VM '%s'...\n", strings.Join(s.names, ", "), s.name)
560 }
561 if gitStale || namesStale {
562 fmt.Fprint(s.io.Stdout, s.notes)
563 }
564 if !isNew {
565 switch {
566 case !wantWritable && !allReadOnly(inst):
567 fmt.Fprintf(s.io.Stdout, "Making every share of VM '%s' read-only...\n", s.name)
568 case wantWritable && allReadOnly(inst):
569 fmt.Fprintf(s.io.Stdout, "VM '%s' was left read-only by --readonly; making it writable again...\n", s.name)
570 }
571 }
572 if err := s.applyShares(wantWritable); err != nil {
573 return err
574 }
575 }
576
577 if wasRunning {
578 s.notePolicyChange()
579 } else if err := s.boot(); err != nil {
580 return err
581 }
582 return s.afterBoot(isNew, wasRunning, wantWritable)
583}
584
585// baseMarkers are the base's markers as they were when it was cloned: nil
586// for one that was not there.
587type baseMarkers struct{ builtBy, version []byte }
588
589// cloneBase clones the base template into the VM, under the base's lock: a
590// setup swapping the base in is not cloned from half way. The base's markers
591// are read under it too, so that they are those of the base cloned.
592func (s *start) cloneBase() (baseMarkers, error) {
593 var m baseMarkers
594 b, err := s.backend()
595 if err != nil {
596 return m, err
597 }
598 unlock, err := s.lockVM(s.ctx, vmname.Template)
599 if err != nil {
600 return m, err
601 }
602 defer unlock()
603 if err := b.Clone(s.ctx, vmname.Template, s.name); err != nil {
604 return m, err
605 }
606 m.builtBy, _ = os.ReadFile(s.state.Path(state.BaseBuiltBy))
607 m.version, _ = os.ReadFile(s.state.Path(state.BaseVersion))
608 return m, nil
609}
610
611// dropNew deletes the VM this run just made and could not set up.
612func (s *start) dropNew() {
613 if s.deleteVM(context.WithoutCancel(s.ctx), s.name) {
614 s.created = false
615 }
616}
617
618func isDirNoYAML(d string) bool {
619 if fi, err := os.Stat(d); err != nil || !fi.IsDir() {
620 return false
621 }
622 _, err := os.Stat(filepath.Join(d, "lima.yaml"))
623 return err != nil
624}
625
626// boot starts the stopped VM, its config checked first.
627func (s *start) boot() error {
628 if err := s.beforeBoot(); err != nil {
629 return err
630 }
631 // Existing environments also require KVM. Otherwise Lima silently falls
632 // back to software emulation after a host loses virtualization support.
633 if !skipPrereqs && !host.LinuxPrereqs(s.io.Stderr) {
634 return errStop
635 }
636 // Windows: QEMU's folder on PATH (winget does not put it there), for the
637 // hostagent this starts.
638 if !host.WindowsPrereqs(s.io.Stdout, s.io.Stderr) {
639 return errStop
640 }
641 fmt.Fprintf(s.io.Stdout, "Starting VM '%s'...\n", s.name)
642 b, _ := s.backend()
643 var log bytes.Buffer
644 if err := s.startVM(s.ctx, b, s.name, &log); err != nil {
645 ha := paths.Host(filepath.Join(LimaHome(s.state), s.name, "ha.stderr.log"))
646 s.warnf("Error: Failed to start VM '%s'.\n--- Lima's output ---\n%s%v\nFull log: %s", s.name, log.String(), err, ha)
647 host.WindowsStartHint(s.io.Stderr, ha)
648 return errStop
649 }
650 s.recordPolicy()
651 return nil
652}
653
654// afterBoot brings the running VM's shares in line with the mode asked, by
655// a write probe on the project (which pushes the env too), then installs
656// the terminal's terminfo, runs the runtime scripts and binds single files.
657func (s *start) afterBoot(isNew, wasRunning, wantWritable bool) error {
658 o := s.opts
659 guest := paths.Guest(s.dir)
660 var guestEnv, guestRuntime, projectRuntime, payload string
661 if o.Scratch {
662 if code, err := s.shellRun(nil, "", "sh", "-c", `sudo install -d -o "$(id -u)" -g "$(id -g)" "$1"`, "sh", guest); err != nil || code != 0 {
663 s.warnf("Error: could not make %s in VM '%s'.", s.dir, s.name)
664 return errStop
665 }
666 // Only the shared file: the project's stays out. Read as the other
667 // path does, a regular file only (a FIFO would block the start).
668 if b, ok := readRegular(s.state.Path("env")); ok {
669 payload = strings.TrimRight(env.StripCR(b), "\n")
670 }
671 } else {
672 pe := env.ProjectEnvFile(s.dir)
673 projectRuntime = runscript.ProjectPath(s.dir)
674 // By their path in the project, the one the VM has.
675 if rel, ok := env.ProjectRel(s.dir, pe); ok {
676 guestEnv = guest + "/" + rel
677 }
678 if rel, ok := env.ProjectRel(s.dir, projectRuntime); ok {
679 guestRuntime = guest + "/" + rel
680 }
681 payload = strings.TrimRight(env.Payload(s.state.Path("env"), s.dir), "\n")
682 }
683 probe := s.probe(payload, guestEnv, guestRuntime)
684 if o.Scratch && probe.writable != "true" {
685 s.warnf("Error: %s is not writable in VM '%s'.", s.dir, s.name)
686 return errStop
687 }
688 inst, _ := s.get(s.name)
689 want := fmt.Sprint(wantWritable)
690 if !o.Scratch && (probe.writable != want || !wantWritable && inst != nil && !allReadOnly(inst)) {
691 switch {
692 case probe.writable == "lost":
693 s.warnf("Warning: the project share is not mounted in VM '%s': what was written in %s in the VM since then is on the VM's own disk, and hidden once the share is back.", s.name, s.dir)
694 s.warnf("Project share is not mounted; repairing...")
695 case wantWritable && wasRunning && inst != nil && allReadOnly(inst):
696 fmt.Fprintf(s.io.Stdout, "VM '%s' runs read-only (--readonly). It must be restarted to make its shares writable.\n", s.name)
697 if !s.ui.CanAsk() || !s.ui.AskYN("Stop the VM and make it writable? Sessions using it are cut.", false) {
698 s.warnf("Error: not restarted. Pass --readonly to use it as it is, or 'agent-vm stop' it first.")
699 return errStop
700 }
701 case !wantWritable && wasRunning:
702 fmt.Fprintf(s.io.Stdout, "VM '%s' was already running. It must be restarted to make its shares read-only.\n", s.name)
703 if !s.ui.CanAsk() || !s.ui.AskYN("Stop the VM and apply --readonly?", false) {
704 // Carrying on writable after --readonly was asked for is the
705 // one outcome that must not be silent.
706 s.warnf("Error: --readonly was requested but not applied. Aborting.")
707 return errStop
708 }
709 case wantWritable:
710 s.warnf("Project mount is not writable; repairing...")
711 }
712 // Stopped for sure first: applying read-only shares while it still
713 // runs writable would claim what is not true.
714 if err := s.stopToChange(); err != nil {
715 return err
716 }
717 if err := s.applyShares(wantWritable); err != nil {
718 return err
719 }
720 if err := s.beforeBoot(); err != nil {
721 return err
722 }
723 b, _ := s.backend()
724 if err := s.startVM(s.ctx, b, s.name, io.Discard); err != nil {
725 s.warnf("Error: VM '%s' did not come back up after changing the project mount.", s.name)
726 return errStop
727 }
728 s.recordPolicy()
729 if probe = s.probe(payload, guestEnv, guestRuntime); probe.writable != want {
730 switch {
731 case probe.writable == "lost":
732 s.warnf("Error: the project share did not mount in VM '%s':\n %s\nLima's log: %s", s.name, s.dir, filepath.Join(LimaHome(s.state), s.name, "ha.stderr.log"))
733 case wantWritable:
734 s.warnf("Error: project directory is still not writable inside the VM:\n %s\nThe host mount failed to attach. Try 'agent-vm --reset <command>'\nto re-clone the VM from the base template.", s.dir)
735 default:
736 s.warnf("Error: failed to mount the project directory read-only:\n %s", s.dir)
737 }
738 return errStop
739 }
740 }
741 // --readonly is claimed once every share Lima has is read-only: the
742 // builtin SFTP server enforces it on the host.
743 if o.ReadOnly {
744 inst, _ := s.get(s.name)
745 if inst == nil {
746 s.warnf("Error: --readonly cannot hold: could not read Lima's config for VM '%s'.", s.name)
747 return errStop
748 }
749 why := notReadOnly(inst)
750 if why == "" && !allReadOnly(inst) {
751 why = "no share"
752 }
753 if why != "" {
754 s.warnf("Error: --readonly cannot hold: VM '%s' runs with %s.", s.name, why)
755 return errStop
756 }
757 fmt.Fprintln(s.io.Stdout, "Read-only: the project and every other share (enforced on the host).")
758 }
759
760 s.terminfo()
761 if _, err := os.Stat(s.state.Path("runtime.sh")); err == nil {
762 fmt.Fprintln(s.io.Stdout, "Running user runtime setup...")
763 s.runHostScript(s.state.Path("runtime.sh"))
764 }
765 switch {
766 case guestRuntime != "":
767 if probe.runtimeFound {
768 fmt.Fprintln(s.io.Stdout, "Running project runtime setup...")
769 s.shellRun(nil, guest, "zsh", "-lc", `[ -f "$3" ] || exit 0; i="$(awk "$1" "$3")" && awk "$2" "$3" | "$i" -s`,
770 "agent-vm", runscript.ShebangAWK, runscript.StripCRAWK, guestRuntime)
771 }
772 case projectRuntime != "" && isFile(projectRuntime):
773 fmt.Fprintln(s.io.Stdout, "Running project runtime setup...")
774 s.runHostScript(projectRuntime)
775 }
776 s.bindFiles(isNew)
777 if path := os.Getenv(cage.ConfigEnv); path != "" {
778 cfg, err := cage.Load(path)
779 if err != nil {
780 return err
781 }
782 code, err := s.shellRun(strings.NewReader(cfg.EnvironmentScript()), paths.Guest(s.dir), "bash", "-s")
783 if err != nil || code != 0 {
784 return fmt.Errorf("cage environment could not be applied (exit %d): %w", code, err)
785 }
786 }
787 return nil
788}
789
790func isFile(p string) bool { fi, err := os.Stat(p); return err == nil && fi.Mode().IsRegular() }
791
792// readRegular is the content of p when it is a regular file once links are
793// followed. Another kind (a FIFO, a device) is not read: it could block.
794func readRegular(p string) (string, bool) {
795 if !isFile(p) {
796 return "", false
797 }
798 b, err := os.ReadFile(p)
799 return string(b), err == nil
800}
801
802// runHostScript runs a runtime script the host reads in the VM, piped in,
803// CRs dropped, under the shell it declares, from a login zsh: the VM's PATH
804// and ~/.agent-vm.env apply.
805func (s *start) runHostScript(path string) {
806 b, ok := readRegular(path)
807 if !ok {
808 s.warnf("Warning: could not read %s (not a regular file, or unreadable): not run.", path)
809 return
810 }
811 interp := runscript.Interpreter(b)
812 s.shellRun(strings.NewReader(env.StripCR(b)), paths.Guest(s.dir), "zsh", "-lc", "exec "+interp+" -s")
813}
814
815// shellRun runs args in the VM, its output on the command's, and returns
816// the exit status.
817func (s *start) shellRun(stdin io.Reader, workdir string, args ...string) (int, error) {
818 b, err := s.backend()
819 if err != nil {
820 return 0, err
821 }
822 if stdin == nil {
823 stdin = strings.NewReader("")
824 }
825 return b.Shell(s.ctx, s.name, vm.ShellOpts{Workdir: workdir, Args: args, Stdin: stdin, Stdout: s.io.Stdout, Stderr: s.io.Stderr})
826}
827
828// terminfo puts the host's terminfo entry in the VM, for terminals Debian
829// does not know (xterm-ghostty, xterm-kitty), once per VM and $TERM.
830func (s *start) terminfo() {
831 t := os.Getenv("TERM")
832 if t == "" || s.state.ReadMarker(state.TermOf, s.name) == t {
833 return
834 }
835 entry, err := exec.CommandContext(s.ctx, "infocmp", "-x", t).Output()
836 if err != nil {
837 return
838 }
839 b, _ := s.backend()
840 code, err := b.Shell(s.ctx, s.name, vm.ShellOpts{Args: []string{"sudo", "tic", "-x", "-"}, Stdin: bytes.NewReader(entry), Stdout: io.Discard, Stderr: io.Discard})
841 if err != nil || code != 0 {
842 s.warnf("Warning: failed to install '%s' terminfo inside VM.", t)
843 return
844 }
845 if err := s.state.Write(state.TermOf+s.name, []byte(t+"\n")); err != nil {
846 s.warnf("Warning: could not record that VM '%s' has the terminfo of '%s': %v", s.name, t, err)
847 }
848}
849
850// bindFiles binds the single files of ~/.agent-vm/volumes in place in the
851// VM, an existing VM's staged copy refreshed first, so an edit saved by
852// rename on the host shows. A bind does not survive a restart, and is
853// skipped when there.
854func (s *start) bindFiles(isNew bool) {
855 b, err := os.ReadFile(s.state.Marker(state.FileMountsOf, s.name))
856 if err != nil {
857 return
858 }
859 var entries []string
860 for _, line := range strings.Split(strings.TrimSuffix(string(b), "\n"), "\n") {
861 f := strings.SplitN(line, "|", 4)
862 if len(f) != 4 || f[1] == "" {
863 continue
864 }
865 switch {
866 case isNew:
867 case !exists(f[0]):
868 s.warnf("Warning: Mount source '%s' no longer exists; VM will see the last-staged copy.", f[0])
869 case !mounts.Stage(f[0], f[1], s.io.Stderr):
870 s.warnf("Warning: Failed to refresh staged '%s'; VM may see stale content.", f[0])
871 }
872 if f[2] != "" && f[3] != "" {
873 entries = append(entries, f[2]+"|"+f[3])
874 }
875 }
876 if len(entries) == 0 {
877 return
878 }
879 fmt.Fprintln(s.io.Stdout, "Mounting individual files...")
880 // The paths as arguments, never in the script.
881 code, err := s.shellRun(nil, "", append([]string{"sudo", "bash", "-c", `
882 set -e
883 for entry in "$@"; do
884 bind_src="${entry%%|*}"
885 bind_dst="${entry#*|}"
886 if ! findmnt -no TARGET "$bind_dst" >/dev/null 2>&1; then
887 mkdir -p "$(dirname "$bind_dst")" && touch "$bind_dst"
888 mount --bind "$bind_src" "$bind_dst"
889 mount -o remount,ro,bind "$bind_dst"
890 fi
891 done
892 `, "--"}, entries...)...)
893 if err != nil {
894 s.warnf("Warning: could not bind the single files of ~/.agent-vm/volumes in VM '%s': %v", s.name, err)
895 } else if code != 0 {
896 s.warnf("Warning: binding the single files of ~/.agent-vm/volumes in VM '%s' failed (status %d).", s.name, code)
897 }
898}
899
900func exists(p string) bool { _, err := os.Stat(p); return err == nil }