跳到主要内容

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

浏览文件

code.go

232 行 · 8.2 KB历史下载
1package cli
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "fmt"
8 "net"
9 "os"
10 "regexp"
11 "runtime"
12 "strconv"
13 "strings"
14 "time"
15 "unicode"
16
17 "github.com/sylvinus/agent-vm/internal/paths"
18 "github.com/sylvinus/agent-vm/internal/ui"
19 "github.com/sylvinus/agent-vm/internal/vm"
20)
21
22// codePrep runs in the VM before the editor starts, the candidate ports as
23// arguments. Prints `missing` without code-server, else its config file and
24// password, the port of an editor of this VM already running, and which
25// candidates something in the VM listens on (ss; without it, curl, any
26// answer but a refused connection, the VM's proxy bypassed).
27//
28// The password is made in the VM, on first use, never in the base: every VM
29// is a copy of the base disk, and one VM knowing another's password could
30// log into it through the host's loopback, which every VM reaches. The file
31// is named after the hostname, which Lima sets per VM.
32const codePrep = `
33command -v code-server >/dev/null 2>&1 || { echo missing; exit 0; }
34cfg="$HOME/.config/code-server/agent-vm-$(hostname).yaml"
35if [ ! -s "$cfg" ]; then
36 pw="$(od -An -N16 -tx1 /dev/urandom | tr -d " \n")"
37 [ "${#pw}" = 32 ] || exit 1
38 mkdir -p "${cfg%/*}" || exit 1
39 (umask 077 && printf "auth: password\npassword: %s\ncert: false\n" "$pw" > "$cfg") || exit 1
40fi
41echo "config=$cfg"
42echo "password=$(sed -n "s/^password: //p" "$cfg")"
43pgrep -u "$(id -u)" -af -- "--config $cfg" \
44 | sed -n "s/.*--bind-addr 127\.0\.0\.1:\([0-9]*\).*/running=\1/p" | head -n 1
45if command -v ss >/dev/null 2>&1; then
46 open=" $(ss -Hltn 2>/dev/null | awk "{ n = split(\$4, a, \":\"); printf \"%s \", a[n] }")"
47 for p in "$@"; do
48 case "$open" in *" $p "*) echo "listening=$p" ;; esac
49 done
50else
51 for p in "$@"; do
52 curl -s -o /dev/null --noproxy "*" --max-time 1 "http://127.0.0.1:$p/"
53 [ $? -eq 7 ] || echo "listening=$p"
54 done
55fi
56exit 0
57`
58
59var hex4 = regexp.MustCompile(`^[0-9a-f]{4}$`)
60
61// codePorts are ten host ports for the VM's editor, from 20000 to 29999,
62// from its name: the same on every start, so the browser finds the saved
63// password at the same address while the first is free. The last four
64// digits of the name's hash start them, so two VMs rarely share them.
65func codePorts(vmName string) []int {
66 h := ""
67 if len(vmName) >= 4 {
68 h = vmName[len(vmName)-4:]
69 }
70 if !hex4.MatchString(h) {
71 sum := sha256.Sum256([]byte(vmName))
72 h = hex.EncodeToString(sum[:])[:4]
73 }
74 n, _ := strconv.ParseInt(h, 16, 64)
75 base := 20000 + int(n)%9991
76 var out []int
77 for i := range 10 {
78 out = append(out, base+i)
79 }
80 return out
81}
82
83// codeHost is where the browser reaches the VM's editor: <vm>.localhost,
84// which browsers send to 127.0.0.1 on their own. Browsers keep cookies per
85// host name, not per port: on 127.0.0.1, a page served by any VM would get
86// the session cookie of every editor. Lowercase, at most 63 characters (a
87// DNS label), the hash at the end kept.
88func codeHost(vmName string) string {
89 l := strings.ToLower(vmName)
90 if len(l) > 63 {
91 l = l[:54] + "-" + l[len(l)-8:]
92 }
93 return l + ".localhost"
94}
95
96func hostPortOpen(p int) bool {
97 c, err := net.DialTimeout("tcp", "127.0.0.1:"+strconv.Itoa(p), time.Second)
98 if err == nil {
99 c.Close()
100 return true
101 }
102 return false
103}
104
105// codeSay prints the editor's address and password, and a note, in a box.
106// Safari leaves *.localhost to macOS, which may not resolve it: 127.0.0.1
107// then, in a window of its own.
108func (s *start) codeSay(port int, pw, note string) {
109 body := fmt.Sprintf(" Address: http://%s:%d/\n Password: %s\n", codeHost(s.name), port, pw)
110 if runtime.GOOS == "darwin" {
111 body += fmt.Sprintf("\nIf Safari does not open it: http://127.0.0.1:%d/ in a private window kept for this editor, so pages from other VMs never get its cookie.\n", port)
112 }
113 if note != "" {
114 body += "\n" + note + "\n"
115 }
116 s.ui.Box("VS Code", body)
117}
118
119// `code`: code-server for the project, in the foreground until Ctrl-C.
120func (e *app) codeCmd(ctx context.Context, opts VMOpts, args []string) int {
121 rest, tty, err := opts.split(args)
122 if err != nil {
123 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
124 return 1
125 }
126 if len(rest) > 0 || tty {
127 a := "--tty"
128 if len(rest) > 0 {
129 a = rest[0]
130 }
131 fmt.Fprintf(e.io.Stderr, "Error: unknown argument for code: %s\nUsage: agent-vm [vm options] code\n", a)
132 return 1
133 }
134 return e.inVM(ctx, opts, (*start).codeSession)
135}
136
137func (s *start) codeSession() int {
138 ports := codePorts(s.name)
139 args := []string{"zsh", "-lc", codePrep, "agent-vm-code"}
140 for _, p := range ports {
141 args = append(args, strconv.Itoa(p))
142 }
143 b, err := s.backend()
144 if err != nil {
145 return 1
146 }
147 var out strings.Builder
148 code, err := b.Shell(s.ctx, s.name, vm.ShellOpts{Args: args, Stdin: strings.NewReader(""), Stdout: &out, Stderr: s.io.Stderr})
149 if err != nil || code != 0 {
150 s.warnf("Error: could not set up the editor's password in VM '%s'.", s.name)
151 return 1
152 }
153 var cfg, pw, running string
154 listening := map[string]bool{}
155 for _, l := range strings.Split(out.String(), "\n") {
156 switch {
157 case l == "missing":
158 s.warnf("Error: code-server is not installed in VM '%s'.\n 'agent-vm setup --preinstall=default,code-claude' (or code-server alone) adds it to the base, then 'agent-vm --reset code'\n re-clones this VM (its disk is lost).", s.name)
159 return 1
160 case strings.HasPrefix(l, "config="):
161 cfg = strings.TrimPrefix(l, "config=")
162 case strings.HasPrefix(l, "password="):
163 pw = strings.TrimPrefix(l, "password=")
164 case strings.HasPrefix(l, "running="):
165 running = strings.TrimPrefix(l, "running=")
166 case strings.HasPrefix(l, "listening="):
167 listening[strings.TrimPrefix(l, "listening=")] = true
168 }
169 }
170 // Printed to the terminal: nothing the VM wrote may carry escape
171 // sequences.
172 if _, perr := strconv.Atoi(running); pw == "" || strings.IndexFunc(pw+cfg, unicode.IsControl) >= 0 || running != "" && perr != nil {
173 s.warnf("Error: could not read the editor's password in VM '%s'.", s.name)
174 return 1
175 }
176 if running != "" {
177 p, _ := strconv.Atoi(running)
178 s.codeSay(p, pw, fmt.Sprintf("The editor of VM '%s' already runs, from another terminal.", s.name))
179 return 0
180 }
181 // The first port free both here and in the VM: Lima forwards the VM's
182 // port to the same one here, and only when nothing holds it.
183 port := 0
184 for _, p := range ports {
185 if !listening[strconv.Itoa(p)] && !hostPortOpen(p) {
186 port = p
187 break
188 }
189 }
190 if port == 0 {
191 var ps []string
192 for _, p := range ports {
193 ps = append(ps, strconv.Itoa(p))
194 }
195 s.warnf("Error: no free port for the editor among: %s ", strings.Join(ps, " "))
196 return 1
197 }
198 s.codeSay(port, pw, "The password is kept in the VM, in "+cfg+". Ctrl-C stops the editor.")
199 // A terminal for Ctrl-C to reach code-server: without one, it would
200 // keep running in the VM once this command ends.
201 tty := ui.IsTerminal(os.Stdin) && ui.IsTerminal(os.Stdout)
202 // Bound to the VM's loopback, which Lima forwards to this machine's
203 // only. The cookie suffix keeps sessions apart at 127.0.0.1.
204 // --disable-proxy: no route from the browser to the VM's other ports;
205 // empty VSCODE_PROXY_URI leaves a link to localhost:<port> at that port
206 // here instead of rewriting it through the editor's /proxy/. An absolute
207 // template such as http://localhost:{{port}}/ breaks the workbench:
208 // code-server runs new URL() on it before substituting {{port}}, which
209 // throws Invalid URL (coder/code-server#6504).
210 // No experiments, and the built-in Copilot Chat never loads. Claude
211 // Code's login pages open without the link prompt, those paths only.
212 //
213 // Not a full boundary between VMs: no VM reaches this port itself
214 // (netguard), but any VM can listen on a port Lima forwards to this
215 // machine, and a page it serves can send the browser, with this editor's
216 // cookie, to a host name it chose.
217 return s.lima(tty, "VSCODE_PROXY_URI=", "code-server",
218 "--config", cfg,
219 "--bind-addr", "127.0.0.1:"+strconv.Itoa(port),
220 "--cookie-suffix", s.name,
221 "--app-name", s.name,
222 "--disable-telemetry",
223 "--disable-update-check",
224 "--disable-workspace-trust",
225 "--disable-proxy",
226 "--disable-getting-started-override",
227 "--link-protection-trusted-domains", "https://claude.com/cai/oauth",
228 "--link-protection-trusted-domains", "https://platform.claude.com/oauth",
229 "--vscode-option", "disable-experiments",
230 "--vscode-option", "disable-extension=GitHub.copilot-chat",
231 paths.Guest(s.dir))
232}