| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "runtime" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | agentvm "github.com/sylvinus/agent-vm" |
| 17 | "github.com/sylvinus/agent-vm/internal/appupdate" |
| 18 | "github.com/sylvinus/agent-vm/internal/cage" |
| 19 | "github.com/sylvinus/agent-vm/internal/cli" |
| 20 | "github.com/sylvinus/agent-vm/internal/containerenv" |
| 21 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 22 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 23 | "github.com/sylvinus/agent-vm/internal/host" |
| 24 | "github.com/sylvinus/agent-vm/internal/hostproxy" |
| 25 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| 26 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 27 | "github.com/sylvinus/agent-vm/internal/workbench" |
| 28 | "io" |
| 29 | "os/signal" |
| 30 | "runtime/debug" |
| 31 | "sync" |
| 32 | "syscall" |
| 33 | ) |
| 34 | |
| 35 | const help = `Claude Cage — local isolated Claude development |
| 36 | |
| 37 | cage desktop Open the unified Cage workbench (desktop launcher) |
| 38 | cage agent Discover and use the versioned, JSON-only external Agent interface |
| 39 | cage serve Run its private localhost control service |
| 40 | cage server-entry --json Issue a private SSH remote connection entry |
| 41 | cage container-configure --json Configure a Linux container from JSON stdin |
| 42 | cage init Create a private profile; add and select nodes in Cage settings |
| 43 | cage check Verify proxy transport (no VM required) |
| 44 | cage guest-os --json Check host prerequisites for a same-system guest |
| 45 | On Windows, add --vm-id GUID to inspect one Hyper-V VM |
| 46 | cage proxy-start Start Cage's bundled proxy core with the applied node |
| 47 | cage proxy-stop Stop Cage's core and close external networking |
| 48 | cage setup Build the isolated base VM through the specified proxy |
| 49 | cage up Start the shared Cage environment, editor and browser |
| 50 | cage login Start cage services, then Claude's login flow inside the VM |
| 51 | cage access Inspect legacy viewer credentials (diagnostics only) |
| 52 | cage shell Open a shell in the shared environment |
| 53 | cage run COMMAND Execute a command in the shared environment |
| 54 | cage claude Run Claude Code in the shared environment |
| 55 | cage stop Stop the shared Cage environment |
| 56 | cage list List this cage profile's VMs |
| 57 | cage doctor Diagnose the VM |
| 58 | cage diagnostics --json PATH.zip Export a redacted diagnostic bundle |
| 59 | cage version Print this build's version. --min VERSION fails if older |
| 60 | cage licenses Print third-party license notices |
| 61 | |
| 62 | Configuration: ~/.claude-cage/config.json (override CLAUDE_CAGE_CONFIG). |
| 63 | Each configuration directory is an independent cage profile. |
| 64 | Only explicitly opened project folders are shared. No host Claude credentials are imported. |
| 65 | ` |
| 66 | |
| 67 | func main() { |
| 68 | defer func() { |
| 69 | if failure := recover(); failure != nil { |
| 70 | diagnostics.Log("error", "command", fmt.Sprintf("panic: %v\n%s", failure, debug.Stack())) |
| 71 | panic(failure) |
| 72 | } |
| 73 | }() |
| 74 | code := run() |
| 75 | if code != 0 { |
| 76 | diagnostics.Log("error", "command", "operation exited unsuccessfully") |
| 77 | } |
| 78 | os.Exit(code) |
| 79 | } |
| 80 | func run() int { |
| 81 | hostproxy.CaptureEnvironment() |
| 82 | |
| 83 | |
| 84 | |
| 85 | for _, name := range []string{ |
| 86 | "AGENT_VM_UNSAFE_OPEN_NETWORK", |
| 87 | "AGENT_VM_UNSAFE_WRITABLE_GIT", |
| 88 | "AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS", |
| 89 | } { |
| 90 | os.Unsetenv(name) |
| 91 | } |
| 92 | args := os.Args[1:] |
| 93 | if len(args) > 0 && args[0] == "host-download" { |
| 94 | ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 95 | defer cancel() |
| 96 | if err := hostDownload(ctx, args[1:], os.Stdout); err != nil { |
| 97 | return fail(err) |
| 98 | } |
| 99 | return 0 |
| 100 | } |
| 101 | if len(args) == 0 || args[0] == "help" || args[0] == "--help" || args[0] == "-h" { |
| 102 | fmt.Print(help) |
| 103 | return 0 |
| 104 | } |
| 105 | |
| 106 | |
| 107 | if args[0] == "version" || args[0] == "--version" || args[0] == "-V" || args[0] == "licenses" { |
| 108 | return cli.Main(args, cli.Stdio()) |
| 109 | } |
| 110 | if args[0] == "agent" { |
| 111 | return runAgent(args[1:], os.Stdin, os.Stdout) |
| 112 | } |
| 113 | if args[0] == "verify-web-assets" { |
| 114 | if len(args) != 1 { |
| 115 | return 2 |
| 116 | } |
| 117 | if err := workbench.VerifyWebAssets(); err != nil { |
| 118 | return fail(err) |
| 119 | } |
| 120 | return 0 |
| 121 | } |
| 122 | if len(args) == 1 && (args[0] == "verify-macos-guest" || args[0] == "verify-macos-trial") { |
| 123 | if !macGuestLoginAvailable() { |
| 124 | return fail(fmt.Errorf("this helper was built without the virtual Mac login view")) |
| 125 | } |
| 126 | return 0 |
| 127 | } |
| 128 | macGuestCommand := len(args) >= 2 && args[0] == "guest-os" && args[1] == "macos" |
| 129 | if args[0] == "guest-os" && !macGuestCommand { |
| 130 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| 131 | defer cancel() |
| 132 | if err := writeGuestOSInspection(ctx, args[1:], os.Stdout); err != nil { |
| 133 | return fail(err) |
| 134 | } |
| 135 | return 0 |
| 136 | } |
| 137 | if args[0] == "verify-vm-assets" { |
| 138 | if len(args) != 1 { |
| 139 | return 2 |
| 140 | } |
| 141 | dir, err := os.MkdirTemp("", "cage-vm-assets-") |
| 142 | if err != nil { |
| 143 | return fail(err) |
| 144 | } |
| 145 | defer os.RemoveAll(dir) |
| 146 | share, err := limaembed.WriteShare(dir) |
| 147 | if err != nil { |
| 148 | return fail(err) |
| 149 | } |
| 150 | if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" { |
| 151 | if _, err := share.GuestAgent("Darwin", "aarch64"); err != nil { |
| 152 | return fail(err) |
| 153 | } |
| 154 | } |
| 155 | return 0 |
| 156 | } |
| 157 | if err := host.ConfigureWindowsRuntime(); err != nil { |
| 158 | return fail(err) |
| 159 | } |
| 160 | path := os.Getenv(cage.ConfigEnv) |
| 161 | if path == "" { |
| 162 | home, _ := os.UserHomeDir() |
| 163 | path = filepath.Join(home, ".claude-cage", "config.json") |
| 164 | } |
| 165 | path, err := filepath.Abs(path) |
| 166 | if err != nil { |
| 167 | return fail(err) |
| 168 | } |
| 169 | store := diagnostics.New(filepath.Dir(path)) |
| 170 | diagnostics.SetDefault(store) |
| 171 | if args[0] == "windows-network-host" { |
| 172 | if len(args) != 1 { |
| 173 | return fail(fmt.Errorf("windows-network-host takes its bound configuration from the profile")) |
| 174 | } |
| 175 | if err := workbench.ServeWindowsPacketNetwork(path); err != nil { |
| 176 | return fail(err) |
| 177 | } |
| 178 | return 0 |
| 179 | } |
| 180 | if args[0] == "container-runtime" { |
| 181 | if len(args) != 2 { |
| 182 | return fail(fmt.Errorf("container-runtime prepare|start|stop|inspect")) |
| 183 | } |
| 184 | environment, err := containerenv.Load(filepath.Dir(path)) |
| 185 | if err != nil { |
| 186 | return fail(err) |
| 187 | } |
| 188 | ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 189 | defer cancel() |
| 190 | switch args[1] { |
| 191 | case "prepare": |
| 192 | err = environment.Prepare(ctx, os.Stdout) |
| 193 | case "start": |
| 194 | err = environment.Start(ctx, path, os.Stdout) |
| 195 | case "stop": |
| 196 | err = environment.Stop(ctx) |
| 197 | case "inspect": |
| 198 | inspection, inspectErr := environment.Inspect(ctx) |
| 199 | err = inspectErr |
| 200 | if err == nil { |
| 201 | err = json.NewEncoder(os.Stdout).Encode(inspection) |
| 202 | } |
| 203 | default: |
| 204 | err = fmt.Errorf("container-runtime prepare|start|stop|inspect") |
| 205 | } |
| 206 | if err != nil { |
| 207 | return fail(err) |
| 208 | } |
| 209 | return 0 |
| 210 | } |
| 211 | if args[0] == "container-configure" { |
| 212 | if len(args) != 2 || args[1] != "--json" { |
| 213 | return fail(fmt.Errorf("container-configure --json < configuration.json")) |
| 214 | } |
| 215 | if err := configureContainer(path); err != nil { |
| 216 | return fail(err) |
| 217 | } |
| 218 | return 0 |
| 219 | } |
| 220 | if args[0] == "container-install-script" { |
| 221 | if len(args) != 2 { |
| 222 | return fail(fmt.Errorf("container-install-script tools|services")) |
| 223 | } |
| 224 | script, err := containerInstallScript(args[1]) |
| 225 | if err != nil { |
| 226 | return fail(err) |
| 227 | } |
| 228 | _, err = io.WriteString(os.Stdout, script) |
| 229 | if err != nil { |
| 230 | return 1 |
| 231 | } |
| 232 | return 0 |
| 233 | } |
| 234 | if args[0] == "container-network" { |
| 235 | if len(args) != 1 { |
| 236 | return 2 |
| 237 | } |
| 238 | environment, err := containerenv.Load(filepath.Dir(path)) |
| 239 | if err != nil { |
| 240 | return fail(err) |
| 241 | } |
| 242 | ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 243 | defer cancel() |
| 244 | if err := environment.ServeNetwork(ctx, path); err != nil { |
| 245 | return fail(err) |
| 246 | } |
| 247 | return 0 |
| 248 | } |
| 249 | if args[0] == "container-tap" { |
| 250 | if len(args) != 1 { |
| 251 | return 2 |
| 252 | } |
| 253 | ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 254 | defer cancel() |
| 255 | if err := containerenv.RunTAP(ctx, os.Stdin, os.Stdout); err != nil { |
| 256 | return fail(err) |
| 257 | } |
| 258 | return 0 |
| 259 | } |
| 260 | if args[0] == "server-entry" { |
| 261 | if len(args) != 2 || args[1] != "--json" { |
| 262 | return fail(fmt.Errorf("server-entry --json")) |
| 263 | } |
| 264 | entry, err := workbench.ServerEntry(path) |
| 265 | if err != nil { |
| 266 | return fail(err) |
| 267 | } |
| 268 | if err := json.NewEncoder(os.Stdout).Encode(entry); err != nil { |
| 269 | return 1 |
| 270 | } |
| 271 | return 0 |
| 272 | } |
| 273 | if args[0] == "diagnostic-event" { |
| 274 | var event struct { |
| 275 | Source string `json:"source"` |
| 276 | Message string `json:"message"` |
| 277 | } |
| 278 | if json.NewDecoder(io.LimitReader(os.Stdin, 32<<10)).Decode(&event) != nil { |
| 279 | return 2 |
| 280 | } |
| 281 | if event.Source != "native" { |
| 282 | return 2 |
| 283 | } |
| 284 | if err := store.Record("error", event.Source, event.Message); err != nil { |
| 285 | return 1 |
| 286 | } |
| 287 | return 0 |
| 288 | } |
| 289 | if args[0] == "diagnostics" { |
| 290 | connection := "" |
| 291 | if len(args) == 5 && args[1] == "--json" && args[2] == "--connection" { |
| 292 | connection = args[3] |
| 293 | args = []string{args[0], args[1], args[4]} |
| 294 | } |
| 295 | if len(args) != 3 || args[1] != "--json" { |
| 296 | return fail(fmt.Errorf("diagnostics --json /absolute/path.zip")) |
| 297 | } |
| 298 | if err := workbench.ExportDiagnosticsForConnection(workbench.DesktopHelperConfig(path, connection), connection, args[2]); err != nil { |
| 299 | diagnostics.Log("error", "command", err.Error()) |
| 300 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 301 | return 1 |
| 302 | } |
| 303 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "ok"}) |
| 304 | return 0 |
| 305 | } |
| 306 | if args[0] == "log-relay" { |
| 307 | if len(args) != 2 { |
| 308 | return 2 |
| 309 | } |
| 310 | return relay(path, args[1]) |
| 311 | } |
| 312 | if args[0] == "app-update" { |
| 313 | return appupdate.Run(path, args[1:], os.Stdout) |
| 314 | } |
| 315 | connectionID := "" |
| 316 | if (args[0] == "clipboard-files" || args[0] == "upload-files" || args[0] == "browser-file" || args[0] == "desktop-file" || args[0] == "share-project") && len(args) >= 3 && args[2] == "--connection" { |
| 317 | if len(args) < 4 || args[3] == "" { |
| 318 | return fail(fmt.Errorf("missing file connection identity")) |
| 319 | } |
| 320 | connectionID = args[3] |
| 321 | args = append(append([]string{}, args[:2]...), args[4:]...) |
| 322 | } |
| 323 | if args[0] == "clipboard-files" { |
| 324 | if len(args) < 4 || args[1] != "--json" { |
| 325 | return fail(fmt.Errorf("clipboard-files --json --connection ID send|receive PATH...")) |
| 326 | } |
| 327 | result, err := workbench.ClipboardFilesForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2], args[3:]) |
| 328 | if err != nil { |
| 329 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"message": err.Error()}) |
| 330 | return 1 |
| 331 | } |
| 332 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 333 | return 0 |
| 334 | } |
| 335 | if args[0] == "desktop-file" { |
| 336 | if len(args) != 3 || args[1] != "--json" { |
| 337 | return fail(fmt.Errorf("desktop-file --json --connection ID REQUEST")) |
| 338 | } |
| 339 | result, err := workbench.DesktopFileForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2]) |
| 340 | if err != nil { |
| 341 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 342 | return 1 |
| 343 | } |
| 344 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 345 | return 0 |
| 346 | } |
| 347 | if args[0] == "share-project" { |
| 348 | if connectionID == "" || len(args) != 4 || args[1] != "--json" || (args[2] != "read" && args[2] != "write") { |
| 349 | return fail(fmt.Errorf("share-project --json --connection ID read|write DIRECTORY")) |
| 350 | } |
| 351 | result, err := workbench.ShareNativeCloudProject(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[3], args[2] == "read") |
| 352 | if err != nil { |
| 353 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 354 | return 1 |
| 355 | } |
| 356 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 357 | return 0 |
| 358 | } |
| 359 | if args[0] == "upload-files" { |
| 360 | if len(args) < 5 || args[1] != "--json" { |
| 361 | return fail(fmt.Errorf("upload-files --json browser|desktop|terminal ID PATH...")) |
| 362 | } |
| 363 | result, err := workbench.UploadHostFilesForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2], args[3], args[4:]) |
| 364 | if err != nil { |
| 365 | diagnostics.Log("error", "command", err.Error()) |
| 366 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 367 | return 1 |
| 368 | } |
| 369 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 370 | return 0 |
| 371 | } |
| 372 | if args[0] == "browser-file" { |
| 373 | if len(args) < 4 || len(args) > 5 || args[1] != "--json" { |
| 374 | return fail(fmt.Errorf("browser-file --json save|open|reveal ID [destination]")) |
| 375 | } |
| 376 | destination := "" |
| 377 | if len(args) == 5 { |
| 378 | destination = args[4] |
| 379 | } |
| 380 | result, err := workbench.BrowserFileForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2], args[3], destination) |
| 381 | if err != nil { |
| 382 | diagnostics.Log("error", "command", err.Error()) |
| 383 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 384 | return 1 |
| 385 | } |
| 386 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 387 | return 0 |
| 388 | } |
| 389 | if args[0] == "serve-desktop" { |
| 390 | if err := workbench.ServeDesktop(path); err != nil { |
| 391 | return fail(err) |
| 392 | } |
| 393 | return 0 |
| 394 | } |
| 395 | if args[0] == "serve" { |
| 396 | if err := workbench.Serve(path); err != nil { |
| 397 | return fail(err) |
| 398 | } |
| 399 | return 0 |
| 400 | } |
| 401 | if args[0] == "desktop" { |
| 402 | options := workbench.DesktopOptions{} |
| 403 | returnJSON := false |
| 404 | for _, argument := range args[1:] { |
| 405 | switch argument { |
| 406 | case "--json": |
| 407 | returnJSON = true |
| 408 | case "--complete-update": |
| 409 | options.CompleteUpdate = true |
| 410 | case "--existing": |
| 411 | options.UseExisting = true |
| 412 | default: |
| 413 | return fail(fmt.Errorf("unknown desktop option: %s", argument)) |
| 414 | } |
| 415 | } |
| 416 | entry, err := workbench.DesktopEntry(path, options) |
| 417 | if err != nil { |
| 418 | if returnJSON { |
| 419 | diagnostics.Log("error", "command", err.Error()) |
| 420 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 421 | return 1 |
| 422 | } |
| 423 | return fail(err) |
| 424 | } |
| 425 | |
| 426 | if returnJSON { |
| 427 | _ = json.NewEncoder(os.Stdout).Encode(entry) |
| 428 | } else { |
| 429 | if entry.URL == "" { |
| 430 | return fail(fmt.Errorf("%s", entry.Message)) |
| 431 | } |
| 432 | if err := openWorkbench(entry.URL); err != nil { |
| 433 | return fail(err) |
| 434 | } |
| 435 | fmt.Println("Cage workbench opened.") |
| 436 | } |
| 437 | return 0 |
| 438 | } |
| 439 | if args[0] == "prepare-update" { |
| 440 | stop, returnJSON := false, false |
| 441 | for _, argument := range args[1:] { |
| 442 | switch argument { |
| 443 | case "--stop": |
| 444 | stop = true |
| 445 | case "--json": |
| 446 | returnJSON = true |
| 447 | default: |
| 448 | return fail(fmt.Errorf("unknown prepare-update option: %s", argument)) |
| 449 | } |
| 450 | } |
| 451 | result, err := workbench.PrepareDesktopUpdate(path, stop) |
| 452 | if err != nil { |
| 453 | if returnJSON { |
| 454 | diagnostics.Log("error", "command", err.Error()) |
| 455 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 456 | return 1 |
| 457 | } |
| 458 | return fail(err) |
| 459 | } |
| 460 | if returnJSON { |
| 461 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 462 | } else if result.Status != "prepared" { |
| 463 | return fail(fmt.Errorf("%s", result.Message)) |
| 464 | } |
| 465 | return 0 |
| 466 | } |
| 467 | if args[0] == "init" { |
| 468 | if err = host.EnsurePrivateDir(filepath.Dir(path)); err != nil { |
| 469 | return fail(err) |
| 470 | } |
| 471 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) |
| 472 | if err != nil { |
| 473 | return fail(err) |
| 474 | } |
| 475 | enc := json.NewEncoder(f) |
| 476 | enc.SetIndent("", " ") |
| 477 | err = enc.Encode(cage.DefaultConfig()) |
| 478 | f.Close() |
| 479 | if err != nil { |
| 480 | return fail(err) |
| 481 | } |
| 482 | fmt.Println("Configuration created:", path) |
| 483 | return 0 |
| 484 | } |
| 485 | cfg, err := cage.Load(path) |
| 486 | management := args[0] == "stop" || args[0] == "list" || args[0] == "info" |
| 487 | if err != nil && !management { |
| 488 | return fail(err) |
| 489 | } |
| 490 | |
| 491 | os.Setenv(cage.ConfigEnv, path) |
| 492 | profile := filepath.Dir(path) |
| 493 | state := filepath.Join(profile, "state") |
| 494 | os.Unsetenv("CAGE_LIMA_CACHE_DIR") |
| 495 | os.Unsetenv("CAGE_LOGICAL_LIMA_HOME") |
| 496 | if !containerenv.Configured(profile) { |
| 497 | if err = guestos.RecoverWindowsStorage(context.Background(), profile); err != nil { |
| 498 | return fail(err) |
| 499 | } |
| 500 | lease, location, err := cage.AcquireStorageUse(profile) |
| 501 | if err != nil { |
| 502 | return fail(err) |
| 503 | } |
| 504 | defer lease.Close() |
| 505 | |
| 506 | |
| 507 | os.Setenv("CAGE_LIMA_CACHE_DIR", filepath.Join(location.Directory, "cache", "lima")) |
| 508 | if location.Custom { |
| 509 | |
| 510 | |
| 511 | realProfile, err := filepath.EvalSymlinks(profile) |
| 512 | if err != nil { |
| 513 | return fail(err) |
| 514 | } |
| 515 | state = filepath.Join(realProfile, "state") |
| 516 | os.Setenv("CAGE_LOGICAL_LIMA_HOME", filepath.Join(state, "lima")) |
| 517 | } |
| 518 | } |
| 519 | os.Setenv("AGENT_VM_STATE_DIR", state) |
| 520 | os.Setenv("AGENT_VM_LIMA_HOME", filepath.Join(state, "lima")) |
| 521 | |
| 522 | for _, name := range []string{"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "FTP_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "ftp_proxy", "no_proxy", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"} { |
| 523 | os.Unsetenv(name) |
| 524 | } |
| 525 | |
| 526 | |
| 527 | http.DefaultTransport = hostproxy.NewTransport() |
| 528 | if limaembed.Run(args) { |
| 529 | return 0 |
| 530 | } |
| 531 | if macGuestCommand { |
| 532 | ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 533 | defer cancel() |
| 534 | if err := runMacGuest(ctx, profile, state, args[2:]); err != nil { |
| 535 | return fail(err) |
| 536 | } |
| 537 | return 0 |
| 538 | } |
| 539 | if args[0] == "proxy-start" || args[0] == "proxy-stop" { |
| 540 | if err := proxyCommand(args[0], filepath.Dir(path), cfg); err != nil { |
| 541 | return fail(err) |
| 542 | } |
| 543 | return 0 |
| 544 | } |
| 545 | if handled, err := containerOperation(path, args, cfg); handled { |
| 546 | if err != nil { |
| 547 | return fail(err) |
| 548 | } |
| 549 | return 0 |
| 550 | } |
| 551 | |
| 552 | switch args[0] { |
| 553 | case "up", "login", "shell", "run", "claude", "stop", "doctor", "access", "name": |
| 554 | directory := cage.EnvironmentDir(filepath.Dir(path)) |
| 555 | if err := os.MkdirAll(directory, 0700); err != nil { |
| 556 | return fail(err) |
| 557 | } |
| 558 | if err := os.Chdir(directory); err != nil { |
| 559 | return fail(err) |
| 560 | } |
| 561 | } |
| 562 | if management { |
| 563 | code := cli.Main(args, cli.Stdio()) |
| 564 | if code == 0 && args[0] == "stop" { |
| 565 | if err := managedproxy.Stop(filepath.Dir(path)); err != nil { |
| 566 | return fail(err) |
| 567 | } |
| 568 | } |
| 569 | return code |
| 570 | } |
| 571 | if err := cfg.RequireManagedProxy(filepath.Dir(path)); err != nil { |
| 572 | return fail(err) |
| 573 | } |
| 574 | if err := cfg.CheckRunning(state); err != nil { |
| 575 | return fail(err) |
| 576 | } |
| 577 | |
| 578 | if args[0] == "check" { |
| 579 | e, err := cage.NewEgress(cfg) |
| 580 | if err != nil { |
| 581 | return fail(err) |
| 582 | } |
| 583 | client := &http.Client{Timeout: 25 * time.Second, Transport: &http.Transport{DialContext: e.DialContext, Proxy: nil}} |
| 584 | req, _ := http.NewRequestWithContext(context.Background(), "GET", "https://1.1.1.1/cdn-cgi/trace", nil) |
| 585 | r, err := client.Do(req) |
| 586 | if err != nil { |
| 587 | return fail(fmt.Errorf("proxy transport check failed (no direct fallback)")) |
| 588 | } |
| 589 | r.Body.Close() |
| 590 | if r.StatusCode != 200 { |
| 591 | return fail(fmt.Errorf("proxy check returned HTTP %d", r.StatusCode)) |
| 592 | } |
| 593 | fmt.Println("Proxy transport OK. Guest traffic still requires VM acceptance checks.") |
| 594 | return 0 |
| 595 | } |
| 596 | if args[0] == "setup" { |
| 597 | if err = os.MkdirAll(state, 0700); err != nil { |
| 598 | return fail(err) |
| 599 | } |
| 600 | if err = os.WriteFile(filepath.Join(state, "setup.sh"), []byte(cage.GuestSetup), 0600); err != nil { |
| 601 | return fail(err) |
| 602 | } |
| 603 | memory, cpus, resourceErr := cage.ConfiguredResourceLimits(path) |
| 604 | if resourceErr != nil { |
| 605 | return fail(resourceErr) |
| 606 | } |
| 607 | args = append([]string{"setup", "--memory", fmt.Sprint(memory), "--cpus", fmt.Sprint(cpus), "--disk", "24", "--preinstall=node,python,chromium,claude,code-server"}, args[1:]...) |
| 608 | } |
| 609 | if args[0] == "up" || args[0] == "login" { |
| 610 | result := cli.Main([]string{"run", "true"}, cli.Stdio()) |
| 611 | if result != 0 { |
| 612 | return result |
| 613 | } |
| 614 | if err := workbench.StartGuestServices(context.Background(), path, cfg, os.Stdout, os.Stderr); err != nil { |
| 615 | return fail(err) |
| 616 | } |
| 617 | fmt.Println("Cage local services are ready. Open Cage or run cage desktop to complete the required network checks. External networking stays closed until the workbench approves this VM; no local access password is required.") |
| 618 | if args[0] == "login" { |
| 619 | return cli.Main([]string{"run", "--tty", "bash", "-lc", "source /etc/profile.d/claude-cage.sh; exec claude auth login"}, cli.Stdio()) |
| 620 | } |
| 621 | return 0 |
| 622 | } |
| 623 | if args[0] == "update-tools" { |
| 624 | if result := cli.Main([]string{"run", "true"}, cli.Stdio()); result != 0 { |
| 625 | return result |
| 626 | } |
| 627 | if err := workbench.RunMaintenanceScript(context.Background(), path, cage.ToolsUpdateScript(), os.Stdout, os.Stderr); err != nil { |
| 628 | return fail(err) |
| 629 | } |
| 630 | return 0 |
| 631 | } |
| 632 | if args[0] == "access" { |
| 633 | args = []string{"run", "bash", "-c", `printf 'Editor password: '; sed -n 's/^password: //p' "$HOME/.config/claude-cage/code-server.yaml"; printf 'Browser password: '; cat "$HOME/.config/claude-cage/browser-password"; printf '\n'`} |
| 634 | } |
| 635 | allowed := map[string]bool{"setup": true, "run": true, "shell": true, "claude": true, "stop": true, "list": true, "doctor": true, "info": true, "name": true} |
| 636 | if !allowed[args[0]] { |
| 637 | return fail(fmt.Errorf("unknown cage command %q; see cage help", args[0])) |
| 638 | } |
| 639 | return cli.Main(args, cli.Stdio()) |
| 640 | } |
| 641 | |
| 642 | func containerInstallScript(kind string) (string, error) { |
| 643 | switch kind { |
| 644 | case "services": |
| 645 | return cage.GuestSetup, nil |
| 646 | case "tools": |
| 647 | script := "set -e\nexport CLAUDE_CAGE=1\n" + cage.APTBootstrapScript + "\n" + cage.ToolInstallPrelude() |
| 648 | enabled := map[string]bool{"NODE": true, "PYTHON": true, "CHROMIUM": true, "CLAUDE": true, "CODE_SERVER": true} |
| 649 | for _, name := range []string{"PYTHON", "NODE", "RUBY", "RUST", "GOLANG", "DOCKER", "CHROMIUM", "GH", "CLAUDE", "OPENCODE", "CODEX", "VIBE", "PI", "CODE_SERVER", "CODE_CLAUDE", "CODE_OPENCODE", "CODE_CODEX", "CODE_VIBE", "MCP_CHROME", "MCP_PLAYWRIGHT"} { |
| 650 | value := "0" |
| 651 | if enabled[name] { |
| 652 | value = "1" |
| 653 | } |
| 654 | script += "export AGENT_VM_INSTALL_" + name + "=" + value + "\n" |
| 655 | } |
| 656 | return script + agentvm.SetupScript, nil |
| 657 | default: |
| 658 | return "", fmt.Errorf("container-install-script tools|services") |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | |
| 663 | |
| 664 | func runGuestServiceStart(script string, stdio cli.IO, invoke func([]string, cli.IO) int) int { |
| 665 | stdio.Stdin = strings.NewReader(script) |
| 666 | return invoke([]string{"run", "bash", "-s"}, stdio) |
| 667 | } |
| 668 | |
| 669 | func fail(err error) int { |
| 670 | diagnostics.Log("error", "command", err.Error()) |
| 671 | fmt.Fprintln(os.Stderr, strings.TrimSpace(err.Error())) |
| 672 | return 1 |
| 673 | } |
| 674 | |
| 675 | func openWorkbench(address string) error { |
| 676 | if runtime.GOOS == "windows" { |
| 677 | return exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", address).Start() |
| 678 | } |
| 679 | command := "xdg-open" |
| 680 | if runtime.GOOS == "darwin" { |
| 681 | command = "open" |
| 682 | } |
| 683 | return exec.Command(command, address).Run() |
| 684 | } |
| 685 | |
| 686 | |
| 687 | |
| 688 | func relay(configPath, kind string) int { |
| 689 | var cmd *exec.Cmd |
| 690 | source := "controller" |
| 691 | if kind == "controller" { |
| 692 | exe, err := os.Executable() |
| 693 | if err != nil { |
| 694 | return fail(err) |
| 695 | } |
| 696 | cmd = exec.Command(exe, "serve") |
| 697 | } else if kind == "proxy" { |
| 698 | core, err := managedproxy.CorePath() |
| 699 | if err != nil { |
| 700 | return fail(err) |
| 701 | } |
| 702 | profile := filepath.Dir(configPath) |
| 703 | cmd = exec.Command(core, "-d", managedproxy.Dir(profile), "-f", filepath.Join(managedproxy.Dir(profile), "config.yaml")) |
| 704 | source = "proxy" |
| 705 | } else { |
| 706 | return 2 |
| 707 | } |
| 708 | configureRelayCommand(cmd) |
| 709 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) |
| 710 | store := diagnostics.New(filepath.Dir(configPath)) |
| 711 | out := store.Stream(source, "info") |
| 712 | defer out.Close() |
| 713 | stderr := store.Stream(source, "error") |
| 714 | defer stderr.Close() |
| 715 | cmd.Stdout, cmd.Stderr = out, stderr |
| 716 | if err := cmd.Start(); err != nil { |
| 717 | return fail(err) |
| 718 | } |
| 719 | diagnostics.Log("info", source, "process started") |
| 720 | signals := make(chan os.Signal, 1) |
| 721 | signal.Notify(signals, os.Interrupt, syscall.SIGTERM) |
| 722 | defer signal.Stop(signals) |
| 723 | done := make(chan struct{}) |
| 724 | var wg sync.WaitGroup |
| 725 | var forwarded os.Signal |
| 726 | wg.Add(1) |
| 727 | go func() { |
| 728 | defer wg.Done() |
| 729 | select { |
| 730 | case sig := <-signals: |
| 731 | forwarded = sig |
| 732 | _ = cmd.Process.Signal(sig) |
| 733 | case <-done: |
| 734 | } |
| 735 | }() |
| 736 | err := cmd.Wait() |
| 737 | close(done) |
| 738 | wg.Wait() |
| 739 | if err != nil { |
| 740 | if expectedRelayStop(err, forwarded) { |
| 741 | diagnostics.Log("info", source, "process stopped on request") |
| 742 | return 0 |
| 743 | } |
| 744 | diagnostics.Log("error", source, "process exited: "+err.Error()) |
| 745 | return 1 |
| 746 | } |
| 747 | diagnostics.Log("info", source, "process exited normally") |
| 748 | return 0 |
| 749 | } |
| 750 | |
| 751 | func expectedRelayStop(err error, forwarded os.Signal) bool { |
| 752 | signal, ok := forwarded.(syscall.Signal) |
| 753 | if !ok { |
| 754 | return false |
| 755 | } |
| 756 | var exit *exec.ExitError |
| 757 | if !errors.As(err, &exit) { |
| 758 | return false |
| 759 | } |
| 760 | status, ok := exit.Sys().(syscall.WaitStatus) |
| 761 | return ok && status.Signaled() && status.Signal() == signal || exit.ExitCode() == 128+int(signal) |
| 762 | } |