跳到主要内容

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

浏览文件

limaembed.go

194 行 · 6.5 KB历史下载
1// Package limaembed runs what Lima's libraries expect of limactl: they start
2// the current executable again for some commands (`hostagent`, from
3// instance.Start), and look for the guest agent and the templates next to it.
4package limaembed
5
6import (
7 "context"
8 "os"
9 "path/filepath"
10 "runtime"
11 "strings"
12
13 "github.com/sirupsen/logrus"
14 "github.com/spf13/cobra"
15
16 "github.com/docker/go-units"
17 "github.com/lima-vm/lima/v2/pkg/debugutil"
18 "github.com/lima-vm/lima/v2/pkg/driver"
19 "github.com/lima-vm/lima/v2/pkg/driver/external/server"
20 "github.com/lima-vm/lima/v2/pkg/envutil"
21 "github.com/lima-vm/lima/v2/pkg/hostagent"
22 "github.com/lima-vm/lima/v2/pkg/hostagent/dns"
23 "github.com/lima-vm/lima/v2/pkg/limatype"
24 "github.com/lima-vm/lima/v2/pkg/networks/usernet"
25 "github.com/lima-vm/lima/v2/pkg/osutil"
26 "github.com/lima-vm/sshocker/pkg/reversesshfs"
27
28 "github.com/sylvinus/agent-vm/internal/cage"
29 "github.com/sylvinus/agent-vm/internal/diagnostics"
30 "github.com/sylvinus/agent-vm/internal/guard"
31 "github.com/sylvinus/agent-vm/internal/guestos"
32 "github.com/sylvinus/agent-vm/internal/netguard"
33 "github.com/sylvinus/agent-vm/internal/state"
34 "github.com/sylvinus/agent-vm/internal/vmname"
35)
36
37// Run runs args (os.Args[1:]) when they are a command Lima's libraries start
38// this executable for, as limactl would, and reports whether they were. Such
39// a command never returns: it exits.
40func Run(args []string) bool {
41 var stopGateControl func()
42 var stopJobWatch func()
43 i := 0
44 for i < len(args) && args[i] == "--debug" {
45 i++
46 }
47 if i == len(args) || args[i] != "hostagent" {
48 return false
49 }
50 var diagnosticStream *diagnostics.Stream
51 if path := os.Getenv(cage.ConfigEnv); path != "" {
52 hostagent.ManageResources = func(ctx context.Context, dir string, cfg *limatype.LimaYAML, balloon driver.MemoryBalloon, read func(context.Context, string) ([]byte, error)) func() {
53 maximum, err := units.RAMInBytes(*cfg.Memory)
54 if err != nil || *cfg.OS != limatype.LINUX {
55 return func() {}
56 }
57 return cage.StartResourceManager(ctx, dir, uint64(maximum), *cfg.CPUs, read, balloon.SetMemoryTarget)
58 }
59 diagnosticStream = diagnostics.New(filepath.Dir(path)).Stream("vm-hostagent", "warn")
60 diagnostics.SetDefault(diagnostics.New(filepath.Dir(path)))
61 logrus.SetOutput(diagnosticStream)
62 defer diagnosticStream.Close()
63 }
64 if runtime.GOOS == "windows" {
65 windowsPath()
66 }
67 // Lima's own port forwarder, the one patched to never take a port a
68 // program of the host serves; not the ssh one.
69 os.Unsetenv("LIMA_SSH_PORT_FORWARDER")
70 // What the guest may reach (netguard): every connection it opens is made
71 // here, by the instance's netstack. An unreadable policy stops the VM
72 // rather than leave it open.
73 st, err := state.Default()
74 if err != nil {
75 logrus.Fatal(err)
76 }
77 policy, err := netguard.Load(string(st))
78 if err != nil {
79 logrus.Fatal(err)
80 }
81 usernet.Outbound = policy.Allows
82 if len(policy.Domains) > 0 {
83 // Both resolvers the guest can reach: the gateway's, which every
84 // query gets whatever the guest's iptables say, and the hostagent's.
85 usernet.Names, usernet.Answered = policy.Name, policy.Answered
86 dns.Names, dns.Answered = policy.Name, policy.Answered
87 }
88 if path := os.Getenv(cage.ConfigEnv); path != "" {
89 stopJobWatch, err = cage.WatchJobStop(filepath.Dir(path), os.Getenv(cage.JobEnv), notifyHostagentStop)
90 if err != nil {
91 logrus.Fatal(err)
92 }
93 cfg, err := cage.Load(path)
94 if err != nil {
95 logrus.Fatal(err)
96 }
97 if err = cfg.RequireManagedProxy(filepath.Dir(path)); err != nil {
98 logrus.Fatal(err)
99 }
100 usernet.Names, usernet.Answered = nil, nil
101 dns.Names, dns.Answered = nil, nil
102 name := args[len(args)-1]
103 if name == vmname.Template+"-building" {
104 // The base builder installs trusted tooling before any project is
105 // mounted. Project VMs always start with the external gate closed.
106 egress, err := cage.NewEgress(cfg)
107 if err != nil {
108 logrus.Fatal(err)
109 }
110 usernet.Outbound, usernet.GuestDial = egress.Allows, egress.DialContext
111 usernet.DNSExchange, dns.Exchange = egress.ExchangeDNS, egress.ExchangeDNS
112 } else {
113 gate, err := cage.NewEgressGate(cfg)
114 if err != nil {
115 logrus.Fatal(err)
116 }
117 if stopGateControl, err = cage.StartGateControl(path, filepath.Join(string(st), "lima", name), gate); err != nil {
118 logrus.Fatal(err)
119 }
120 if name == "mac" {
121 // The installed Mac profile binds this exact VZ instance. Other
122 // workloads retain their existing switch behavior.
123 if binding, err := guestos.LoadMacOSProfile(filepath.Dir(path)); err != nil {
124 logrus.Fatal(err)
125 } else if binding != nil && binding.Instance == name {
126 usernet.DroppedIPv6 = gate.ObserveDroppedIPv6
127 }
128 }
129 usernet.Outbound, usernet.GuestDial = gate.Allows, gate.DialContext
130 usernet.DNSExchange, dns.Exchange = gate.ExchangeDNS, gate.ExchangeDNS
131 }
132 if err := cfg.RecordRunning(string(st), args[len(args)-1]); err != nil {
133 logrus.Fatal(err)
134 }
135 }
136 // The user is asked before the VM changes a file their machine runs on
137 // its own (guard): the shares' SFTP server runs here.
138 if os.Getenv(cage.ConfigEnv) == "" {
139 g, err := guard.Load(string(st), args[len(args)-1])
140 if err != nil {
141 logrus.Fatal(err)
142 }
143 reversesshfs.Guard = g.Allow
144 } else {
145 // Cage grants normal file access inside explicitly shared directories.
146 reversesshfs.Guard = nil
147 }
148 root := &cobra.Command{
149 Use: "agent-vm",
150 SilenceUsage: true,
151 SilenceErrors: true,
152 PersistentPreRun: func(cmd *cobra.Command, _ []string) {
153 if debug, _ := cmd.Flags().GetBool("debug"); debug {
154 logrus.SetLevel(logrus.DebugLevel)
155 debugutil.Debug = true
156 }
157 },
158 }
159 root.PersistentFlags().Bool("debug", false, "debug mode")
160 root.AddCommand(newHostagentCommand())
161 root.SetArgs(args)
162 // Its events, as limactl's, and a notice for each port it forwards. The
163 // instance is the last argument.
164 root.SetOut(newEventWatch(os.Stdout, args[len(args)-1]))
165 if diagnosticStream != nil {
166 root.SetErr(diagnosticStream)
167 }
168
169 err = root.Execute()
170 if stopJobWatch != nil {
171 stopJobWatch()
172 }
173 if stopGateControl != nil {
174 stopGateControl()
175 }
176 server.Disconnect()
177 osutil.HandleExitError(err)
178 if err != nil {
179 logrus.Fatal(err)
180 }
181 os.Exit(0)
182 return true
183}
184
185// windowsPath puts QEMU's usual folders on PATH, as limactl's main does.
186func windowsPath() {
187 if extras, ok := os.LookupEnv("_LIMA_WINDOWS_EXTRA_PATH"); ok && strings.TrimSpace(extras) != "" {
188 _ = os.Setenv("PATH", strings.TrimSpace(extras)+string(filepath.ListSeparator)+os.Getenv("PATH"))
189 }
190 p := os.Getenv("PATH")
191 if np := envutil.AppendDirsToPath(p, envutil.PlatformCommonToolDirs); np != p {
192 _ = os.Setenv("PATH", np)
193 }
194}