| 1 | package cli |
| 2 | |
| 3 | import ( |
| 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 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | const codePrep = ` |
| 33 | command -v code-server >/dev/null 2>&1 || { echo missing; exit 0; } |
| 34 | cfg="$HOME/.config/code-server/agent-vm-$(hostname).yaml" |
| 35 | if [ ! -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 |
| 40 | fi |
| 41 | echo "config=$cfg" |
| 42 | echo "password=$(sed -n "s/^password: //p" "$cfg")" |
| 43 | pgrep -u "$(id -u)" -af -- "--config $cfg" \ |
| 44 | | sed -n "s/.*--bind-addr 127\.0\.0\.1:\([0-9]*\).*/running=\1/p" | head -n 1 |
| 45 | if 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 |
| 50 | else |
| 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 |
| 55 | fi |
| 56 | exit 0 |
| 57 | ` |
| 58 | |
| 59 | var hex4 = regexp.MustCompile(`^[0-9a-f]{4}$`) |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | func 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 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | func 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 | |
| 96 | func 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 | |
| 106 | |
| 107 | |
| 108 | func (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 | |
| 120 | func (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 | |
| 137 | func (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 | |
| 171 | |
| 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 | |
| 182 | |
| 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 | |
| 200 | |
| 201 | tty := ui.IsTerminal(os.Stdin) && ui.IsTerminal(os.Stdout) |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 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 | } |