跳到主要内容

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

浏览文件

envcmd.go

250 行 · 7.5 KB历史下载
1package cli
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10 "regexp"
11 "strings"
12
13 "golang.org/x/term"
14
15 "github.com/sylvinus/agent-vm/internal/env"
16 "github.com/sylvinus/agent-vm/internal/gitx"
17 "github.com/sylvinus/agent-vm/internal/paths"
18 "github.com/sylvinus/agent-vm/internal/vmname"
19)
20
21var keyRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
22
23// envFile is an env file: top is the project folder when the file is inside
24// it, and is then only touched without following links (env.ReadIn).
25type envFile struct {
26 path, top string
27}
28
29func (f envFile) read() ([]byte, error) {
30 if f.top != "" {
31 return env.ReadIn(f.top, strings.TrimPrefix(f.path, strings.TrimSuffix(f.top, "/")+"/"))
32 }
33 fi, err := os.Stat(f.path)
34 if errors.Is(err, os.ErrNotExist) || err == nil && !fi.Mode().IsRegular() {
35 return nil, env.ErrNoFile
36 }
37 return os.ReadFile(f.path)
38}
39
40// write replaces the file, atomically, mode 600.
41func (f envFile) write(data []byte) error {
42 if f.top != "" {
43 return env.WriteIn(f.top, strings.TrimPrefix(f.path, strings.TrimSuffix(f.top, "/")+"/"), data)
44 }
45 if err := os.MkdirAll(filepath.Dir(f.path), 0o755); err != nil {
46 return err
47 }
48 tmp, err := os.CreateTemp(filepath.Dir(f.path), filepath.Base(f.path)+".")
49 if err != nil {
50 return err
51 }
52 _, werr := tmp.Write(data)
53 if err := errors.Join(werr, tmp.Chmod(0o600), tmp.Close()); err != nil {
54 os.Remove(tmp.Name())
55 return err
56 }
57 if err := os.Rename(tmp.Name(), f.path); err != nil {
58 os.Remove(tmp.Name())
59 return err
60 }
61 return nil
62}
63
64// envVerb runs `env` (~/.agent-vm/env) and `project-env`: set, get, has,
65// unset, list, on a file the VM's shell sources, so the quoting is done
66// here, once. Writes are atomic and mode 600, other lines kept; list prints
67// names, never values. The file is held in memory, never in a temporary
68// file: it holds secrets.
69func (e *app) envVerb(verb string, f envFile, args []string) int {
70 stderr := e.io.Stderr
71 usage := fmt.Sprintf("Usage: agent-vm %s {set KEY [VALUE]|get KEY|has KEY|unset KEY|list}", verb)
72 action, key := "list", ""
73 if len(args) > 0 {
74 action = args[0]
75 }
76 if len(args) > 1 {
77 key = args[1]
78 }
79 switch action {
80 case "set", "get", "has", "unset":
81 if key == "" {
82 fmt.Fprintf(stderr, "Error: 'agent-vm %s %s' needs a KEY.\n", verb, action)
83 return 1
84 }
85 if !keyRe.MatchString(key) {
86 fmt.Fprintf(stderr, "Error: '%s' is not a valid environment variable name.\n", key)
87 return 1
88 }
89 case "list":
90 default:
91 fmt.Fprintln(stderr, usage)
92 return 1
93 }
94 // A word too many is refused: `set TOKEN my secret` would store "my".
95 maxArgs := map[string]int{"set": 3, "list": 1}[action]
96 if maxArgs == 0 {
97 maxArgs = 2
98 }
99 if len(args) > maxArgs {
100 fmt.Fprintf(stderr, "Error: too many arguments for 'agent-vm %s %s'. Quote a value with spaces.\n", verb, action)
101 fmt.Fprintln(stderr, usage)
102 return 1
103 }
104 // Without VALUE, read from stdin, typed unseen on a terminal: a value on
105 // the command line lands in the shell history and in `ps`. From a pipe,
106 // one trailing newline goes, as `echo` adds it.
107 value := ""
108 if action == "set" {
109 if len(args) == 3 {
110 value = args[2]
111 } else if in, ok := e.io.Stdin.(*os.File); ok && term.IsTerminal(int(in.Fd())) {
112 fmt.Fprintf(stderr, "Value for %s (not shown): ", key)
113 b, err := term.ReadPassword(int(in.Fd()))
114 fmt.Fprintln(stderr)
115 if err == nil {
116 value = string(b)
117 }
118 } else {
119 b, _ := io.ReadAll(e.io.Stdin)
120 value = strings.TrimSuffix(string(b), "\n")
121 }
122 if len(args) < 3 && value == "" {
123 fmt.Fprintf(stderr, "Error: 'agent-vm %s set %s' needs a VALUE, as an argument or on stdin.\n", verb, key)
124 return 1
125 }
126 }
127
128 content, err := f.read()
129 have := true
130 switch {
131 case err == nil:
132 case errors.Is(err, env.ErrNoFile):
133 have = false
134 case errors.Is(err, env.ErrUnsafe):
135 fmt.Fprintf(stderr, "Error: %s is a symlink, is reached through one, or is not a regular file.\n", f.path)
136 fmt.Fprintln(stderr, " agent-vm follows no link in the project, which the VM can write. Replace it with a plain file.")
137 return 2
138 default:
139 fmt.Fprintf(stderr, "Error: could not read %s\n", f.path)
140 return 2
141 }
142
143 switch action {
144 case "set", "unset":
145 if action == "unset" && !have {
146 return 0
147 }
148 next := env.Drop(string(content), key)
149 if action == "set" {
150 next += fmt.Sprintf("%s='%s'\n", key, env.SQEscape(value))
151 }
152 // A write dropped silently would tell the caller a secret was stored
153 // when it was not.
154 if err := f.write([]byte(next)); err != nil {
155 fmt.Fprintf(stderr, "Error: could not write %s\n", f.path)
156 return 1
157 }
158 case "get", "has":
159 if !have {
160 return 1
161 }
162 // Read, never sourced: the project's file is one the VM can write.
163 v, st := env.Lookup(string(content), key)
164 switch st {
165 case env.NotFound:
166 return 1
167 case env.Refused:
168 fmt.Fprintf(stderr, "Error: %s in %s uses, or comes after, shell syntax agent-vm does not evaluate\n", key, f.path)
169 fmt.Fprintf(stderr, " ($, backquotes, backslashes, ~, ;, | ...). Rewrite it with 'agent-vm %s set'.\n", verb)
170 return 2
171 }
172 if action == "get" {
173 fmt.Fprintln(e.io.Stdout, v)
174 }
175 case "list":
176 if !have {
177 return 0
178 }
179 seen := map[string]bool{}
180 for _, n := range env.Names(string(content)) {
181 if !seen[n] {
182 seen[n] = true
183 fmt.Fprintln(e.io.Stdout, n)
184 }
185 }
186 }
187 return 0
188}
189
190func (e *app) sharedEnvCmd(args []string) int {
191 return e.envVerb("env", envFile{path: e.state.Path("env")}, args)
192}
193
194func (e *app) projectEnvCmd(ctx context.Context, args []string) int {
195 wd, err := vmname.AbsDir("")
196 if err != nil {
197 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
198 return 1
199 }
200 f := envFile{path: env.ProjectEnvFile(wd)}
201 if rel, ok := env.ProjectRel(wd, f.path); ok {
202 f = envFile{path: wd + "/" + rel, top: wd}
203 }
204 if st := e.envVerb("project-env", f, args); st != 0 {
205 return st
206 }
207 // After a write that worked: when the file is new to the repository,
208 // and the user is looking.
209 if len(args) > 0 && args[0] == "set" {
210 e.warnUnignored(ctx, f.path)
211 }
212 return 0
213}
214
215// warnUnignored warns, with the line that fixes it, when file is tracked by
216// git or not ignored. Silent without git or a repository.
217func (e *app) warnUnignored(ctx context.Context, file string) {
218 if !gitx.Have() {
219 return
220 }
221 out, err := gitx.Untrusted(ctx, "-C", filepath.Dir(file), "rev-parse", "--show-toplevel").Output()
222 top := strings.TrimSuffix(string(out), "\n")
223 if err != nil || top == "" {
224 return
225 }
226 // git prints the top resolved (/var is a link to /private/var on
227 // macOS): the file's spelling must be, or the prefix below misses and
228 // the warning never fires.
229 if phys, err := filepath.EvalSymlinks(file); err == nil {
230 file = phys
231 }
232 // git prints C:/... on Windows, in either case for the drive.
233 rel, ok := paths.CutPrefix(filepath.ToSlash(file), filepath.ToSlash(top)+"/")
234 if !ok {
235 // A worktree elsewhere, an odd spelling: not something to lecture about.
236 return
237 }
238 qTop, qRel := env.SQEscape(top), env.SQEscape(rel)
239 if gitx.Untrusted(ctx, "-C", top, "ls-files", "--error-unmatch", file).Run() == nil {
240 fmt.Fprintf(e.io.Stderr, "Warning: %s is tracked by git: its contents are in the repository.\n", rel)
241 fmt.Fprintf(e.io.Stderr, " git -C '%s' rm --cached '%s' && echo '/%s' >> '%s/.gitignore'\n", qTop, qRel, qRel, qTop)
242 return
243 }
244 err = gitx.Untrusted(ctx, "-C", top, "check-ignore", "-q", file).Run()
245 var ee interface{ ExitCode() int }
246 if errors.As(err, &ee) && ee.ExitCode() == 1 {
247 fmt.Fprintf(e.io.Stderr, "Warning: %s is not ignored by git: it can be committed by accident.\n", rel)
248 fmt.Fprintf(e.io.Stderr, " echo '/%s' >> '%s/.gitignore'\n", qRel, qTop)
249 }
250}