跳到主要内容

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

浏览文件

vmname.go

173 行 · 5.3 KB历史下载
1// Package vmname names the VM of a project directory, as 0.2 did but for
2// its prefix: the VMs it made are moved under those names (FromOld).
3package vmname
4
5import (
6 "crypto/rand"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "os"
12 "path/filepath"
13 "regexp"
14 "strings"
15
16 "github.com/sylvinus/agent-vm/internal/paths"
17)
18
19// OldPrefix began every name 0.2 gave its VMs, in a Lima home it shared
20// with the user's: agent-vm's own has no use for it (see FromOld).
21const OldPrefix = "agent-vm-"
22
23// Template is the base VM every project's VM is cloned from. No project VM
24// has its name: theirs end with a hash.
25const Template = "base"
26
27// The names Scratch makes.
28var scratchRe = regexp.MustCompile(`^[A-Za-z0-9-]+-scratch-[0-9a-f]{8}$`)
29
30// Limit is the instance-name length supported by one Lima home. Zero
31// selects Lima's normal 76-byte cap.
32type Limit int
33
34// Name is the VM of the project dir, spelled as `pwd` spells it: the name
35// hashes that string, so /tmp/ and /tmp give one VM and a symlink to the
36// project another. <base>-<hash>, base the folder's name with every run of
37// other characters than ASCII letters and digits made one "-" ("project"
38// when nothing is left), and hash 8 hex digits of the path's SHA-256. On
39// Windows, the path as Git Bash spelled it (/c/...), as 0.2 hashed it.
40func Name(dir string) string { return Limit(0).Name(dir) }
41
42func (limit Limit) Name(dir string) string {
43 dir = paths.Guest(dir)
44 sum := sha256.Sum256([]byte(dir))
45 b := base(dir, 0)
46 if b == "" {
47 b = "project"
48 }
49 return limit.fit(b, "-"+hex.EncodeToString(sum[:])[:8])
50}
51
52// fit is b+suffix, b cut to keep it within MaxLen, never to nothing.
53func (limit Limit) fit(b, suffix string) string {
54 if limit == 0 {
55 limit = 76
56 }
57 if n := int(limit) - len(suffix); len(b) > n {
58 b = strings.TrimRight(b[:max(n, 1)], "-")
59 if b == "" {
60 b = "p"
61 }
62 }
63 return b + suffix
64}
65
66// FromOld is the name of the VM 0.2 named old: without OldPrefix, its base
67// template Template, cut as Name cuts a name too long here.
68func FromOld(old string) string { return Limit(0).FromOld(old) }
69
70func (limit Limit) FromOld(old string) string {
71 if old == OldPrefix+"base" {
72 return Template
73 }
74 n := strings.TrimPrefix(old, OldPrefix)
75 if i := strings.LastIndexByte(n, '-'); i > 0 {
76 return limit.fit(n[:i], n[i:])
77 }
78 return n
79}
80
81// Scratch is a new name for a --scratch VM started in dir: its own, so it is
82// never the folder's VM and several can run at once. Short enough for Lima:
83// 76 characters, and a socket path under the Lima home of at most 104 on
84// macOS.
85func Scratch(dir string) (string, error) { return Limit(0).Scratch(dir) }
86
87func (limit Limit) Scratch(dir string) (string, error) {
88 var b [4]byte
89 if _, err := rand.Read(b[:]); err != nil {
90 return "", fmt.Errorf("cannot read random bytes to name the VM: %w", err)
91 }
92 name := base(dir, 20)
93 if name == "" {
94 name = "project"
95 }
96 return limit.fit(name, "-scratch-"+hex.EncodeToString(b[:])), nil
97}
98
99// IsScratch reports whether name looks like one Scratch makes. It only
100// looks like it: a project folder named "x-scratch" gets a VM named
101// "x-scratch-<hash>", which matches. Deleting a VM unasked takes more than
102// the name, a marker of a --scratch run (state.ScratchOf).
103func IsScratch(name string) bool {
104 return scratchRe.MatchString(name)
105}
106
107// base is the last element of dir, every run of bytes other than ASCII
108// letters and digits made one "-", cut to max bytes when max > 0, without a
109// "-" at either end. As `basename | tr -cs 'a-zA-Z0-9' '-'` did, the newline
110// basename prints counts as one of those bytes.
111func base(dir string, max int) string {
112 b := basename(dir) + "\n"
113 var out []byte
114 for i := 0; i < len(b); i++ {
115 c := b[i]
116 if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' {
117 out = append(out, c)
118 } else if len(out) == 0 || out[len(out)-1] != '-' {
119 out = append(out, '-')
120 }
121 }
122 if max > 0 && len(out) > max {
123 out = out[:max]
124 }
125 s := string(out)
126 if max > 0 {
127 // Cut, it may end with several: the scratch name trims every one.
128 return strings.Trim(s, "-")
129 }
130 s = strings.TrimPrefix(s, "-")
131 return strings.TrimSuffix(s, "-")
132}
133
134// basename is what basename(1) prints for p: its last element, trailing
135// slashes ignored, "/" for the root.
136func basename(p string) string {
137 if p == "" {
138 return ""
139 }
140 t := strings.TrimRight(p, "/")
141 if t == "" {
142 return "/"
143 }
144 return t[strings.LastIndexByte(t, '/')+1:]
145}
146
147// ErrNoDir is returned by AbsDir for a directory that does not exist.
148var ErrNoDir = errors.New("no such directory")
149
150// AbsDir is dir (the current directory when empty) as the commands that
151// start a VM spell theirs: absolute, logical (symlinks kept, as `pwd` does;
152// os.Getwd returns $PWD when it names the current directory), without "."
153// or "..". It refuses a directory that does not exist, and a path holding a
154// control character, which would forge lines of `info`'s key=value output.
155func AbsDir(dir string) (string, error) {
156 if dir == "" || !filepath.IsAbs(dir) {
157 wd, err := os.Getwd()
158 if err != nil {
159 return "", err
160 }
161 dir = filepath.Join(wd, dir)
162 }
163 dir = filepath.Clean(dir)
164 if st, err := os.Stat(dir); err != nil || !st.IsDir() {
165 return "", fmt.Errorf("%w: %s", ErrNoDir, dir)
166 }
167 for _, r := range dir {
168 if r < 0x20 || r == 0x7f {
169 return "", errors.New("the directory name contains a control character")
170 }
171 }
172 return paths.Host(dir), nil
173}