跳到主要内容

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

浏览文件

volumes.go

311 行 · 10.1 KB历史下载
1package mounts
2
3import (
4 "fmt"
5 "io"
6 "os"
7 "regexp"
8 "strings"
9 "unicode"
10 "unicode/utf8"
11
12 "github.com/sylvinus/agent-vm/internal/env"
13 "github.com/sylvinus/agent-vm/internal/paths"
14)
15
16// Entry is a usable line of ~/.agent-vm/volumes.
17type Entry struct {
18 Src string // ~ expanded, existing
19 Dst string // absolute and normalized, relative as written, or "" for Src's own path
20 Mode string // "ro" or "rw"
21 Line string // source:destination:mode, for messages
22}
23
24// Entries are the entries of the volumes file for the project dir:
25// source[:destination][:ro|rw[:project]], ro by default. One that cannot be
26// used is skipped, with a warning on warn. Nothing is created here.
27func Entries(file, dir, home string, refs []Ref, warn io.Writer) []Entry {
28 b, err := os.ReadFile(file)
29 if err != nil {
30 return nil
31 }
32 w := func(format string, a ...any) { fmt.Fprintf(warn, "Warning: "+format+"\n", a...) }
33 // Mount points are guest paths: the project's is its own path, as
34 // paths.Guest spells it (/c/Users/me/proj on Windows).
35 guestDir := paths.Guest(dir)
36 projMP := paths.Join("/", guestDir)
37 seen := map[string]bool{}
38 var out []Entry
39 content := string(b)
40 for _, raw := range strings.Split(strings.TrimSuffix(content, "\n"), "\n") {
41 if content == "" {
42 break
43 }
44 line, _, _ := strings.Cut(raw, "#")
45 line = strings.TrimFunc(line, isSpace)
46 if line == "" {
47 continue
48 }
49 // A control character is invalid unescaped in the mounts; the CR of a
50 // CRLF file went with the trim above.
51 if strings.IndexFunc(line, unicode.IsControl) >= 0 {
52 w("Mount entry '%s' (from ~/.agent-vm/volumes) contains a control character, skipping.", raw)
53 continue
54 }
55 line = hideDrives(line)
56 // After an explicit mode, a 4th field limits the entry to the
57 // projects it matches. An empty one is refused, not read as "no
58 // filter": an entry meant for one project would go in every one.
59 if before := line[:max(strings.LastIndexByte(line, ':'), 0)]; strings.Contains(line, ":") && (strings.HasSuffix(before, ":ro") || strings.HasSuffix(before, ":rw")) {
60 filter := showDrives(line[strings.LastIndexByte(line, ':')+1:])
61 line = before
62 if filter == "" {
63 w("Mount entry '%s' (from ~/.agent-vm/volumes) has an empty project filter; refusing to mount it in every project. Skipping.", raw)
64 continue
65 }
66 if !Matches(filter, dir, home, warn) {
67 continue
68 }
69 }
70 src, dst, mode, entry := line, "", "ro", showDrives(line)
71 if strings.HasSuffix(line, ":ro") || strings.HasSuffix(line, ":rw") {
72 mode = line[len(line)-2:]
73 line = line[:len(line)-3]
74 }
75 if s, d, ok := strings.Cut(line, ":"); ok {
76 src, dst = s, d
77 } else {
78 src = line
79 }
80 // On Windows: C:\x as C:/x, and 0.2's Git Bash spelling, /c/x, as C:/x.
81 src, dst = paths.FromGitBash(paths.Host(showDrives(src))), showDrives(dst)
82 // A ':' left in the destination is a field out of place: read as a
83 // destination, the entry would go in every project, its filter lost.
84 if strings.Contains(dst, ":") {
85 w("Mount entry '%s' (from ~/.agent-vm/volumes) does not read as source:destination:mode:project (the mode goes before the project, and is needed with one). Skipping.", raw)
86 continue
87 }
88 if strings.HasPrefix(src, "~") {
89 src = home + src[1:]
90 }
91 if strings.ContainsAny(src, "\"\\\n|") || strings.ContainsAny(dst, "\"\\\n|") {
92 w("Mount entry '%s' (from ~/.agent-vm/volumes) contains invalid characters (quote/backslash/newline/pipe), skipping.", raw)
93 continue
94 }
95 if why, bad := Unwritable(src + dst); bad {
96 w("Mount entry '%s' (from ~/.agent-vm/volumes) %s, skipping.", raw, why)
97 continue
98 }
99 if _, err := os.Stat(src); err != nil {
100 w("Mount path '%s' (from ~/.agent-vm/volumes) does not exist, skipping.", src)
101 continue
102 }
103 // Refused as a project, refused as a volume; a repository's own
104 // folder only when the VM could write it.
105 why, bad := UnsafeLocation(src, refs)
106 if !bad && mode == "rw" && isDir(src) {
107 why, bad = GitDirShare(src)
108 }
109 if bad {
110 w("Mount path '%s' (from ~/.agent-vm/volumes) %s, skipping.", src, why)
111 continue
112 }
113 // Where the VM sees it. At the project or above it, it would hide
114 // the project; at another entry's place, Lima would merge the two
115 // into one share, with the second one's mode.
116 mp := dst
117 if mp == "" {
118 mp = paths.Guest(src)
119 }
120 if !strings.HasPrefix(mp, "/") {
121 mp = guestDir + "/" + mp
122 }
123 mp = paths.Join("/", mp)
124 if strings.HasPrefix(dst, "/") {
125 dst = mp
126 }
127 if strings.HasPrefix(strings.TrimSuffix(projMP, "/")+"/", strings.TrimSuffix(mp, "/")+"/") {
128 w("Mount entry '%s' (from ~/.agent-vm/volumes) would be mounted at %s, which covers the project, skipping.", entry, mp)
129 continue
130 }
131 if seen[mp] {
132 w("Mount entry '%s' (from ~/.agent-vm/volumes) would be mounted at %s, as an entry before it, skipping.", entry, mp)
133 continue
134 }
135 seen[mp] = true
136 out = append(out, Entry{Src: src, Dst: dst, Mode: mode, Line: entry})
137 }
138 return out
139}
140
141// driveColon stands for a drive's colon (C:/) while a line is cut at its
142// other colons: control characters are refused before.
143const driveColon = "\x01"
144
145// hideDrives is line with, on Windows, the colon of each field starting
146// with a drive (C:/x, C:\x) made driveColon; line as is elsewhere.
147func hideDrives(line string) string {
148 if !paths.Windows() {
149 return line
150 }
151 var b strings.Builder
152 for i := 0; i < len(line); i++ {
153 if line[i] == ':' && i >= 1 && ('a' <= line[i-1]|0x20 && line[i-1]|0x20 <= 'z') && (i == 1 || line[i-2] == ':') &&
154 i+1 < len(line) && (line[i+1] == '/' || line[i+1] == '\\') {
155 b.WriteString(driveColon)
156 continue
157 }
158 b.WriteByte(line[i])
159 }
160 return b.String()
161}
162
163// showDrives undoes hideDrives.
164func showDrives(s string) string { return strings.ReplaceAll(s, driveColon, ":") }
165
166// RWDirs are the folders of entries the VM can write besides the project:
167// shares that are rw and directories.
168func RWDirs(entries []Entry) []string {
169 var out []string
170 for _, e := range entries {
171 if e.Mode == "rw" && isDir(e.Src) {
172 out = append(out, e.Src)
173 }
174 }
175 return out
176}
177
178// isSpace is what the shell's [[:space:]] trims.
179func isSpace(r rune) bool {
180 return r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == '\v' || r == '\f'
181}
182
183// Matches reports whether the project dir matches filter, the 4th field of
184// a volumes entry: a path, ~ expanded, where * matches anything, / included
185// (and ? and [...] as the shell has them). A filter that is not absolute
186// matches nothing, with a warning; ~user is not expanded.
187func Matches(filter, dir, home string, warn io.Writer) bool {
188 orig := filter
189 if filter == "~" || strings.HasPrefix(filter, "~/") {
190 filter = home + filter[1:]
191 }
192 // On Windows, C:\x as C:/x (a backslash is no escape there), and 0.2's
193 // /c/x as C:/x.
194 filter = paths.FromGitBash(paths.Host(filter))
195 if filter != paths.Root(filter) {
196 filter = strings.TrimSuffix(filter, "/")
197 }
198 if !paths.IsAbs(filter) {
199 fmt.Fprintf(warn, "Warning: Project filter '%s' (from ~/.agent-vm/volumes) is not an absolute path, skipping the entry.\n", orig)
200 return false
201 }
202 re, err := globRe(filter)
203 return err == nil && re.MatchString(dir)
204}
205
206// literal writes the first character of s, quoted, and says how many bytes
207// it took: the whole character, as string(byte) would not (é is two).
208// regexp reads an invalid byte as U+FFFD, in the pattern as in the path.
209func literal(b *strings.Builder, s string) int {
210 r, n := utf8.DecodeRuneInString(s)
211 if r == utf8.RuneError && n == 1 {
212 b.WriteString(`\x{FFFD}`)
213 } else {
214 b.WriteString(regexp.QuoteMeta(s[:n]))
215 }
216 return n
217}
218
219// globRe is a shell pattern as a regexp: * anything, / included, ? one
220// character, [...] a class ([!...] or [^...] negated).
221func globRe(p string) (*regexp.Regexp, error) {
222 var b strings.Builder
223 b.WriteString(`^`)
224 for i := 0; i < len(p); i++ {
225 switch c := p[i]; c {
226 case '*':
227 b.WriteString(`.*`)
228 case '?':
229 b.WriteString(`.`)
230 case '[':
231 j := i + 1
232 if j < len(p) && (p[j] == '!' || p[j] == '^') {
233 j++
234 }
235 if j < len(p) && p[j] == ']' {
236 j++
237 }
238 for j < len(p) && p[j] != ']' {
239 j++
240 }
241 if j >= len(p) {
242 b.WriteString(`\[`)
243 continue
244 }
245 class := p[i+1 : j]
246 if class[0] == '!' {
247 class = "^" + class[1:]
248 }
249 b.WriteString("[" + strings.ReplaceAll(class, `\`, `\\`) + "]")
250 i = j
251 case '\\':
252 if i+1 < len(p) {
253 i += literal(&b, p[i+1:])
254 } else {
255 b.WriteString(`\\`)
256 }
257 default:
258 i += literal(&b, p[i:]) - 1
259 }
260 }
261 b.WriteString(`$`)
262 return regexp.Compile(b.String())
263}
264
265// ProjectMountpoint makes, on the host, the mount point of a relative
266// destination rel, inside the project dir: a folder, or an empty file for a
267// file source src. virtiofs and 9p make mount points before the project is
268// mounted, and --readonly refuses the guest's write. No component may be
269// ".." or a symlink: the agent can write the project. Made without following
270// links (env.MkdirIn), since the VM could swap one in after the check.
271func ProjectMountpoint(dir, rel, src string, warn io.Writer) (string, bool) {
272 w := func(format string, a ...any) { fmt.Fprintf(warn, "Warning: "+format+"\n", a...) }
273 p, norm := dir, ""
274 for _, comp := range strings.Split(rel, "/") {
275 if comp == "" || comp == "." {
276 continue
277 }
278 if comp == ".." {
279 w("Mount destination '%s' (from ~/.agent-vm/volumes) goes out of the project with '..', skipping.", rel)
280 return "", false
281 }
282 p += "/" + comp
283 if norm != "" {
284 norm += "/"
285 }
286 norm += comp
287 if fi, err := os.Lstat(p); err == nil && fi.Mode()&os.ModeSymlink != 0 {
288 w("Mount destination '%s' (from ~/.agent-vm/volumes) goes through a symlink in the project (%s), skipping.", rel, p)
289 return "", false
290 }
291 }
292 if p == dir {
293 w("Mount destination '%s' (from ~/.agent-vm/volumes) is the project itself, skipping.", rel)
294 return "", false
295 }
296 kind, err := "file", error(nil)
297 if isDir(src) {
298 kind, err = "directory", env.MkdirIn(dir, norm)
299 } else {
300 err = env.TouchIn(dir, norm)
301 }
302 switch {
303 case err == nil:
304 return p, true
305 case err == env.ErrUnsafe:
306 w("Mount destination '%s' (from ~/.agent-vm/volumes) goes through a symlink in the project, or is not a %s there, skipping.", rel, kind)
307 default:
308 w("Cannot create the mount point '%s' (from ~/.agent-vm/volumes), skipping.", p)
309 }
310 return "", false
311}