| 1 | package agentcli |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "flag" |
| 8 | "io" |
| 9 | "os" |
| 10 | "os/signal" |
| 11 | "path/filepath" |
| 12 | "runtime" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 18 | "github.com/sylvinus/agent-vm/internal/host" |
| 19 | "github.com/sylvinus/agent-vm/internal/version" |
| 20 | "github.com/sylvinus/agent-vm/internal/workbench" |
| 21 | ) |
| 22 | |
| 23 | type agentReply struct { |
| 24 | Protocol int `json:"protocol"` |
| 25 | Version string `json:"version"` |
| 26 | Profile string `json:"config_path,omitempty"` |
| 27 | Status string `json:"status"` |
| 28 | Data any `json:"data,omitempty"` |
| 29 | Error *workbench.AgentError `json:"error,omitempty"` |
| 30 | } |
| 31 | |
| 32 | func Main(args []string, stdin io.Reader, stdout io.Writer) int { |
| 33 | return runAgent(args, stdin, stdout, false) |
| 34 | } |
| 35 | func ClientMain(args []string, stdin io.Reader, stdout io.Writer) int { |
| 36 | return runAgent(args, stdin, stdout, true) |
| 37 | } |
| 38 | func runAgent(args []string, stdin io.Reader, stdout io.Writer, clientOnly bool) int { |
| 39 | reply := agentReply{Protocol: workbench.AgentProtocol, Version: version.Version, Status: "completed"} |
| 40 | finish := func(data any, err error) int { |
| 41 | reply.Data = data |
| 42 | code := 0 |
| 43 | if err != nil { |
| 44 | reply.Status = "error" |
| 45 | code = 1 |
| 46 | var ae *workbench.AgentError |
| 47 | if errors.As(err, &ae) { |
| 48 | reply.Error = ae |
| 49 | } else { |
| 50 | reply.Error = &workbench.AgentError{Code: "operation_failed", Message: "Cage could not complete the operation. Inspect diagnostics.", NextAction: "doctor"} |
| 51 | } |
| 52 | if reply.Error.Code == "invalid_input" || reply.Error.Code == "unknown_operation" { |
| 53 | code = 2 |
| 54 | } |
| 55 | if reply.Error.Code == "account_locked" || reply.Error.Code == "user_action_required" { |
| 56 | code = 3 |
| 57 | } |
| 58 | if reply.Error.Code == "wait_timeout" { |
| 59 | code = 4 |
| 60 | } |
| 61 | } |
| 62 | if json.NewEncoder(stdout).Encode(reply) != nil { |
| 63 | return 1 |
| 64 | } |
| 65 | return code |
| 66 | } |
| 67 | bad := func(message string) int { |
| 68 | return finish(nil, &workbench.AgentError{Code: "invalid_input", Message: message, NextAction: "capabilities"}) |
| 69 | } |
| 70 | command := "capabilities" |
| 71 | if len(args) > 0 { |
| 72 | command = args[0] |
| 73 | args = args[1:] |
| 74 | } |
| 75 | operand := "" |
| 76 | if command == "call" || command == "job" || command == "request" || command == "socket" { |
| 77 | if len(args) == 0 { |
| 78 | return bad("call needs NAME; job needs ID; request needs METHOD /api/PATH; socket needs /api/PATH.") |
| 79 | } |
| 80 | operand, args = args[0], args[1:] |
| 81 | } |
| 82 | requestPath := "" |
| 83 | if command == "request" { |
| 84 | if len(args) == 0 { |
| 85 | return bad("request needs METHOD /api/PATH") |
| 86 | } |
| 87 | requestPath, args = args[0], args[1:] |
| 88 | } |
| 89 | flags := flag.NewFlagSet("cage agent", flag.ContinueOnError) |
| 90 | flags.SetOutput(io.Discard) |
| 91 | config := flags.String("config", os.Getenv(cage.ConfigEnv), "") |
| 92 | input := flags.String("input", "", "") |
| 93 | output := flags.String("output", "", "") |
| 94 | wait := flags.Duration("wait", 0, "") |
| 95 | defaultScope := "local" |
| 96 | if clientOnly { |
| 97 | defaultScope = "client" |
| 98 | } |
| 99 | scope := flags.String("scope", defaultScope, "") |
| 100 | connection := flags.String("connection", "", "") |
| 101 | contentType := flags.String("content-type", "application/json", "") |
| 102 | _ = flags.Bool("json", true, "") |
| 103 | if flags.Parse(args) != nil || flags.NArg() != 0 { |
| 104 | return bad("Usage: cage agent capabilities|doctor|init|service.start|host.inspect|call NAME|request METHOD /api/PATH|socket /api/PATH|routes|job ID|diagnostics [--config PATH] [--input -|FILE] [--wait 5m] [--output PATH]") |
| 105 | } |
| 106 | if *wait < 0 || *wait > 24*time.Hour { |
| 107 | return bad("--wait must be between 0 and 24h.") |
| 108 | } |
| 109 | if *scope != "local" && *scope != "client" && *scope != "desktop" && *scope != "selected" { |
| 110 | return bad("scope must be local, client, desktop or selected") |
| 111 | } |
| 112 | if command != "call" && command != "request" && command != "socket" && command != "job" && command != "routes" && command != "doctor" && command != "diagnostics" && (*scope != defaultScope || *connection != "") { |
| 113 | return bad("scope and connection apply to call, request, socket, job, routes, doctor and diagnostics") |
| 114 | } |
| 115 | if *input != "" && command != "call" && command != "request" { |
| 116 | return bad("--input is valid only for call and request.") |
| 117 | } |
| 118 | if *output != "" && command != "diagnostics" && command != "request" { |
| 119 | return bad("--output is valid only for diagnostics and request.") |
| 120 | } |
| 121 | if *wait != 0 && command != "call" && command != "job" { |
| 122 | return bad("--wait is valid only for call and job.") |
| 123 | } |
| 124 | if *config == "" { |
| 125 | home, err := os.UserHomeDir() |
| 126 | if err != nil { |
| 127 | return finish(nil, err) |
| 128 | } |
| 129 | *config = filepath.Join(home, ".claude-cage", "config.json") |
| 130 | if clientOnly { |
| 131 | *config = filepath.Join(home, ".claude-cage", "client", "config.json") |
| 132 | } |
| 133 | } |
| 134 | path, err := filepath.Abs(*config) |
| 135 | if err != nil { |
| 136 | return finish(nil, err) |
| 137 | } |
| 138 | reply.Profile = path |
| 139 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) |
| 140 | defer stop() |
| 141 | switch command { |
| 142 | case "routes": |
| 143 | response, err := workbench.AgentRequest(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, "GET", "/api/agent/routes", nil, "", "") |
| 144 | return finish(response.Data, err) |
| 145 | case "help", "--help", "capabilities": |
| 146 | return finish(map[string]any{"platform": runtime.GOOS, "arch": runtime.GOARCH, "commands": []string{"capabilities", "doctor", "init", "service.start", "host.inspect", "call NAME", "request METHOD /api/PATH", "socket /api/PATH", "routes", "job ID", "diagnostics"}, "operations": workbench.AgentOperations(), "routes": "agent routes reads the actual registered routes from the chosen live listener", "exit_codes": map[string]int{"completed_or_accepted": 0, "operation_failed": 1, "invalid_input": 2, "user_action_required": 3, "wait_timeout": 4}, "guide": "https://lee-xeo.github.io/Claude-Cage/docs/agent/", "scope": "local: owning workload; desktop: client configuration; selected: explicit desktop connection generation; client: lightweight client listener", "request": map[string]any{"methods": []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"}, "path": "relative /api/ endpoint from the UI", "binary": "--input FILE --content-type application/octet-stream; --output ABSOLUTE_NEW_FILE", "native": "call native.submit --scope desktop; request GET /api/agent/native/ID --scope desktop; use the same native action and connection_id as the open window"}, "job_retention": "only the latest job; query promptly and never resubmit an unknown mutation automatically"}, nil) |
| 147 | case "init": |
| 148 | if _, err := os.Stat(path); err == nil { |
| 149 | if _, err := cage.Load(path); err != nil { |
| 150 | return finish(nil, &workbench.AgentError{Code: "config_invalid", Message: "Existing configuration is invalid. Preserve it and export diagnostics.", NextAction: "diagnostics"}) |
| 151 | } |
| 152 | return finish(map[string]bool{"created": false}, nil) |
| 153 | } else if !os.IsNotExist(err) { |
| 154 | return finish(nil, err) |
| 155 | } |
| 156 | if err := host.EnsurePrivateDir(filepath.Dir(path)); err != nil { |
| 157 | return finish(nil, err) |
| 158 | } |
| 159 | file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| 160 | if err != nil { |
| 161 | return finish(nil, err) |
| 162 | } |
| 163 | err = host.ProtectFile(path) |
| 164 | if err == nil { |
| 165 | err = json.NewEncoder(file).Encode(cage.DefaultConfig()) |
| 166 | } |
| 167 | if e := file.Close(); err == nil { |
| 168 | err = e |
| 169 | } |
| 170 | return finish(map[string]bool{"created": err == nil}, err) |
| 171 | case "service.start": |
| 172 | if clientOnly { |
| 173 | return finish(nil, &workbench.AgentError{Code: "user_action_required", Message: "Open the installed Cage client to start its connection service", NextAction: "open_desktop"}) |
| 174 | } |
| 175 | if err := host.ConfigureWindowsRuntime(); err != nil { |
| 176 | return finish(nil, err) |
| 177 | } |
| 178 | startup, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 179 | defer cancel() |
| 180 | if err := workbench.AgentStartService(startup, path); err != nil { |
| 181 | return finish(nil, err) |
| 182 | } |
| 183 | return finish(map[string]bool{"service_ready": true}, nil) |
| 184 | case "host.inspect": |
| 185 | probe, cancel := context.WithTimeout(ctx, 20*time.Second) |
| 186 | defer cancel() |
| 187 | return finish(guestos.Inspect(probe), nil) |
| 188 | case "doctor": |
| 189 | if *scope != "local" { |
| 190 | endpoint := "/api/client/context" |
| 191 | if *scope == "selected" { |
| 192 | endpoint = "/api/status" |
| 193 | } |
| 194 | response, err := workbench.AgentRequest(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, "GET", endpoint, nil, "", "") |
| 195 | return finish(map[string]any{"scope": *scope, "snapshot": response.Data, "note": "Read-only snapshot of the explicit target. No repairs were applied."}, err) |
| 196 | } |
| 197 | return finish(agentDoctor(ctx, path), nil) |
| 198 | case "diagnostics": |
| 199 | if !filepath.IsAbs(*output) { |
| 200 | return bad("diagnostics requires --output with an absolute local ZIP path.") |
| 201 | } |
| 202 | if _, err := os.Lstat(*output); !os.IsNotExist(err) { |
| 203 | return bad("Choose a new output path; existing files are preserved.") |
| 204 | } |
| 205 | if *scope != "local" { |
| 206 | result, err := workbench.AgentRequest(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, "GET", "/api/diagnostics/export", nil, "", *output) |
| 207 | return finish(result, err) |
| 208 | } |
| 209 | if err := workbench.ExportAgentDiagnostics(path, *output); err != nil { |
| 210 | return finish(nil, err) |
| 211 | } |
| 212 | return finish(map[string]string{"path": *output}, nil) |
| 213 | case "socket": |
| 214 | if *input != "" || *output != "" || *wait != 0 { |
| 215 | return bad("socket uses NDJSON stdin/stdout and no input/output/wait flags") |
| 216 | } |
| 217 | inputStream, ok := stdin.(io.ReadCloser) |
| 218 | if !ok { |
| 219 | inputStream = io.NopCloser(stdin) |
| 220 | } |
| 221 | err := workbench.AgentSocket(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, operand, inputStream, stdout) |
| 222 | return finish(nil, err) |
| 223 | case "request": |
| 224 | var reader io.Reader |
| 225 | if *input != "" { |
| 226 | reader = stdin |
| 227 | if *input != "-" { |
| 228 | f, err := os.Open(*input) |
| 229 | if err != nil { |
| 230 | return finish(nil, err) |
| 231 | } |
| 232 | defer f.Close() |
| 233 | reader = f |
| 234 | } |
| 235 | } |
| 236 | if reader == nil && operand != "GET" && operand != "HEAD" { |
| 237 | reader = strings.NewReader("{}") |
| 238 | } |
| 239 | if *output != "" { |
| 240 | if !filepath.IsAbs(*output) { |
| 241 | return bad("output requires an absolute new file path") |
| 242 | } |
| 243 | if _, err := os.Lstat(*output); !os.IsNotExist(err) { |
| 244 | return bad("existing output files are preserved") |
| 245 | } |
| 246 | } |
| 247 | result, err := workbench.AgentRequest(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, operand, requestPath, reader, *contentType, *output) |
| 248 | var shape struct { |
| 249 | ID string `json:"id"` |
| 250 | Running bool `json:"running"` |
| 251 | } |
| 252 | _ = json.Unmarshal(result.Data, &shape) |
| 253 | if result.HTTPStatus == 202 || (shape.ID != "" && shape.Running) { |
| 254 | reply.Status = "accepted" |
| 255 | } |
| 256 | return finish(result, err) |
| 257 | case "call", "job": |
| 258 | var data json.RawMessage |
| 259 | if command == "call" { |
| 260 | body := []byte("{}") |
| 261 | if *input != "" { |
| 262 | reader := stdin |
| 263 | if *input != "-" { |
| 264 | f, e := os.Open(*input) |
| 265 | if e != nil { |
| 266 | return finish(nil, e) |
| 267 | } |
| 268 | defer f.Close() |
| 269 | reader = f |
| 270 | } |
| 271 | body, err = io.ReadAll(io.LimitReader(reader, (12<<20)+1)) |
| 272 | if err != nil { |
| 273 | return finish(nil, err) |
| 274 | } |
| 275 | } |
| 276 | var object map[string]json.RawMessage |
| 277 | if len(body) > 12<<20 || json.Unmarshal(body, &object) != nil || object == nil { |
| 278 | return bad("Input must be one JSON object of at most 12 MiB.") |
| 279 | } |
| 280 | for _, op := range workbench.AgentOperations() { |
| 281 | if op.Name == operand && !op.Mutates && len(object) > 0 { |
| 282 | return bad("Read operations accept no input fields.") |
| 283 | } |
| 284 | } |
| 285 | data, err = workbench.AgentCallTarget(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, operand, body) |
| 286 | } else { |
| 287 | result, e := workbench.AgentRequest(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, "GET", "/api/agent/jobs/"+operand, nil, "", "") |
| 288 | data, err = result.Data, e |
| 289 | } |
| 290 | if err != nil { |
| 291 | return finish(nil, err) |
| 292 | } |
| 293 | |
| 294 | var job workbench.Job |
| 295 | _ = json.Unmarshal(data, &job) |
| 296 | var shape map[string]json.RawMessage |
| 297 | _ = json.Unmarshal(data, &shape) |
| 298 | if _, isJob := shape["running"]; job.ID == "" || !isJob { |
| 299 | var native struct { |
| 300 | Status string `json:"status"` |
| 301 | Error string `json:"error"` |
| 302 | } |
| 303 | _ = json.Unmarshal(data, &native) |
| 304 | if native.Status == "pending" || native.Status == "running" { |
| 305 | reply.Status = "accepted" |
| 306 | } |
| 307 | if native.Status == "failed" { |
| 308 | return finish(data, &workbench.AgentError{Code: "native_failed", Message: native.Error, NextAction: "status"}) |
| 309 | } |
| 310 | return finish(data, nil) |
| 311 | } |
| 312 | if *wait > 0 && job.Running { |
| 313 | data, err = agentWaitTarget(ctx, path, workbench.AgentTarget{Scope: *scope, Connection: *connection}, job.ID, *wait) |
| 314 | if err != nil { |
| 315 | return finish(data, err) |
| 316 | } |
| 317 | _ = json.Unmarshal(data, &job) |
| 318 | } |
| 319 | if job.Running { |
| 320 | reply.Status = "accepted" |
| 321 | return finish(data, nil) |
| 322 | } |
| 323 | if job.Canceled { |
| 324 | return finish(data, &workbench.AgentError{Code: "job_canceled", Message: "The original job was canceled. Inspect status before retrying.", NextAction: "status"}) |
| 325 | } |
| 326 | if job.Error != "" { |
| 327 | return finish(data, &workbench.AgentError{Code: "job_failed", Message: job.Error, NextAction: "doctor"}) |
| 328 | } |
| 329 | return finish(data, nil) |
| 330 | default: |
| 331 | return bad("Unknown agent command. Run cage agent capabilities.") |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | func agentWait(parent context.Context, path, id string, duration time.Duration) (json.RawMessage, error) { |
| 336 | return agentWaitTarget(parent, path, workbench.AgentTarget{}, id, duration) |
| 337 | } |
| 338 | |
| 339 | func agentWaitTarget(parent context.Context, path string, target workbench.AgentTarget, id string, duration time.Duration) (json.RawMessage, error) { |
| 340 | ctx, cancel := context.WithTimeout(parent, duration) |
| 341 | defer cancel() |
| 342 | tick := time.NewTicker(500 * time.Millisecond) |
| 343 | defer tick.Stop() |
| 344 | var latest json.RawMessage |
| 345 | for { |
| 346 | select { |
| 347 | case <-ctx.Done(): |
| 348 | return latest, &workbench.AgentError{Code: "wait_timeout", Message: "Waiting ended; the job may still be running. Query the same job id.", NextAction: "job " + id, Retryable: true} |
| 349 | case <-tick.C: |
| 350 | response, err := workbench.AgentRequest(ctx, path, target, "GET", "/api/agent/jobs/"+id, nil, "", "") |
| 351 | data := response.Data |
| 352 | if ctx.Err() != nil { |
| 353 | continue |
| 354 | } |
| 355 | if err != nil { |
| 356 | return latest, err |
| 357 | } |
| 358 | latest = data |
| 359 | var job workbench.Job |
| 360 | if json.Unmarshal(data, &job) != nil || job.ID != id { |
| 361 | return data, &workbench.AgentError{Code: "job_not_found", Message: "Original job state is unavailable. Inspect status before retrying.", NextAction: "status"} |
| 362 | } |
| 363 | if !job.Running { |
| 364 | return data, nil |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | func agentDoctor(ctx context.Context, path string) map[string]any { |
| 371 | result := map[string]any{"note": "Read-only snapshot. No repairs were applied; missing services were not started."} |
| 372 | checks := []map[string]any{} |
| 373 | add := func(code, status, next string) { |
| 374 | checks = append(checks, map[string]any{"code": code, "status": status, "next_action": next}) |
| 375 | } |
| 376 | if _, err := os.Stat(path); os.IsNotExist(err) { |
| 377 | add("config_missing", "blocked", "init") |
| 378 | } else if _, err := cage.Load(path); err != nil { |
| 379 | add("config_invalid", "blocked", "diagnostics") |
| 380 | } else { |
| 381 | add("config_valid", "ok", "") |
| 382 | } |
| 383 | for _, name := range []string{"account.json", "proxy/sources.json"} { |
| 384 | if err := host.CheckPrivateFile(filepath.Join(filepath.Dir(path), filepath.FromSlash(name))); err != nil && !os.IsNotExist(err) { |
| 385 | add("private_file_permissions", "blocked", "repair_profile_permissions") |
| 386 | } |
| 387 | } |
| 388 | data, err := workbench.AgentCall(ctx, path, "account.status", nil) |
| 389 | if err != nil { |
| 390 | var ae *workbench.AgentError |
| 391 | if errors.As(err, &ae) { |
| 392 | add(ae.Code, "blocked", ae.NextAction) |
| 393 | } else { |
| 394 | add("service_unavailable", "blocked", "service.start") |
| 395 | } |
| 396 | } else { |
| 397 | var account struct { |
| 398 | Exists bool `json:"exists"` |
| 399 | Unlocked bool `json:"unlocked"` |
| 400 | } |
| 401 | _ = json.Unmarshal(data, &account) |
| 402 | if !account.Exists { |
| 403 | add("account_missing", "blocked", "account.create") |
| 404 | } else if !account.Unlocked { |
| 405 | add("account_locked", "blocked", "account.unlock") |
| 406 | } else { |
| 407 | add("account_unlocked", "ok", "") |
| 408 | if proxy, e := workbench.AgentCall(ctx, path, "proxy.status", nil); e == nil { |
| 409 | result["proxy"] = proxy |
| 410 | var view struct { |
| 411 | Active bool `json:"active"` |
| 412 | Running bool `json:"running"` |
| 413 | Sources []any `json:"sources"` |
| 414 | } |
| 415 | _ = json.Unmarshal(proxy, &view) |
| 416 | switch { |
| 417 | case len(view.Sources) == 0: |
| 418 | add("proxy_missing", "blocked", "proxy.import") |
| 419 | case !view.Active: |
| 420 | add("proxy_unapplied", "blocked", "proxy.select") |
| 421 | case !view.Running: |
| 422 | add("proxy_stopped", "blocked", "proxy.restart") |
| 423 | default: |
| 424 | add("proxy_running", "ok", "") |
| 425 | } |
| 426 | } else { |
| 427 | add("proxy_status_unavailable", "blocked", "diagnostics") |
| 428 | } |
| 429 | if state, e := workbench.AgentCall(ctx, path, "status", nil); e == nil { |
| 430 | result["environment"] = state |
| 431 | var view struct { |
| 432 | Ready bool `json:"ready"` |
| 433 | Running bool `json:"vm_running"` |
| 434 | Update bool `json:"environment_update_required"` |
| 435 | Job workbench.Job `json:"job"` |
| 436 | NetworkError string `json:"network_error"` |
| 437 | } |
| 438 | _ = json.Unmarshal(state, &view) |
| 439 | switch { |
| 440 | case view.Job.Running: |
| 441 | add("job_running", "waiting", "job "+view.Job.ID) |
| 442 | case view.Job.Error != "": |
| 443 | add("job_failed", "blocked", "diagnostics") |
| 444 | case view.Update: |
| 445 | add("environment_update_required", "blocked", "environment.update") |
| 446 | case !view.Running || !view.Ready: |
| 447 | add("environment_not_ready", "blocked", "environment.start") |
| 448 | case view.NetworkError != "": |
| 449 | add("network_not_ready", "blocked", "inspect_network_policy") |
| 450 | default: |
| 451 | add("environment_ready", "ok", "") |
| 452 | } |
| 453 | } else { |
| 454 | add("environment_status_unavailable", "blocked", "diagnostics") |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | result["checks"] = checks |
| 459 | return result |
| 460 | } |