统一用户与 Agent 的配置和原生操作入口
补齐配置命名操作,提供共用认证与连接代次的 HTTP、二进制和 WebSocket 入口。桌面原生队列复用现有桥与系统认证,客户端偏好写入同一存储,并以私有窗口证明保护认领和回执。 验证:独立暂存源码的 Go 回归、race 与 vet;123 项前端测试、lint 和构建;真实 CLI、轻客户端与浏览器双向配置验证;Windows/Linux CLI 交叉编译;网站检查。物理系统授权与真实客机未实测。
补齐配置命名操作,提供共用认证与连接代次的 HTTP、二进制和 WebSocket 入口。桌面原生队列复用现有桥与系统认证,客户端偏好写入同一存储,并以私有窗口证明保护认领和回执。 验证:独立暂存源码的 Go 回归、race 与 vet;123 项前端测试、lint 和构建;真实 CLI、轻客户端与浏览器双向配置验证;Windows/Linux CLI 交叉编译;网站检查。物理系统授权与真实客机未实测。
| @@ -4,6 +4,8 @@ Start with [the complete Agent guide](docs/guide/agent.md). It covers locating t | ||
| 4 | 4 | |
| 5 | 5 | Run `<installed Cage CLI> agent capabilities` to discover the protocol and supported input fields. Every `agent` command returns JSON. The source guide may describe functionality absent from a published release; detect support before configuring it. |
| 6 | 6 | |
| 7 | 新增:The Agent uses the same configuration, account checks, native operations and client preferences as the user interface. Use `agent routes` for the live HTTP route list, `agent request METHOD /api/PATH` for JSON or file operations, and `agent socket /api/PATH` for WebSocket NDJSON. Desktop configuration and selected workloads require an explicit scope and connection generation as described in the guide. Native credential operations stay inside the existing OS bridge. | |
| 8 | 新增: | |
| 7 | 9 | Website entry points: [agent.md](https://lee-xeo.github.io/Claude-Cage/agent.md), [llms.txt](https://lee-xeo.github.io/Claude-Cage/llms.txt), [download helper](https://lee-xeo.github.io/Claude-Cage/agent-bootstrap.mjs). |
| 8 | 10 | |
| 9 | 11 | `AGENTS.md` contains repository contributor instructions. Product users and their agents should follow the usage guide above. |
| @@ -14,6 +14,7 @@ import ( | ||
| 14 | 14 | "path/filepath" |
| 15 | 15 | "syscall" |
| 16 | 16 | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/agentcli" | |
| 17 | 18 | "github.com/sylvinus/agent-vm/internal/cage" |
| 18 | 19 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 19 | 20 | "github.com/sylvinus/agent-vm/internal/version" |
| @@ -21,6 +22,9 @@ import ( | ||
| 21 | 22 | ) |
| 22 | 23 | |
| 23 | 24 | func main() { |
| 25 | 新增: if len(os.Args) > 1 && os.Args[1] == "agent" { | |
| 26 | 新增: os.Exit(agentcli.ClientMain(os.Args[2:], os.Stdin, os.Stdout)) | |
| 27 | 新增: } | |
| 24 | 28 | if err := run(os.Args[1:]); err != nil { |
| 25 | 29 | diagnostics.Log("error", "client", err.Error()) |
| 26 | 30 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| @@ -1,357 +1,10 @@ | ||
| 1 | 1 | package main |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 删除: "context" | |
| 5 | 删除: "encoding/json" | |
| 6 | 删除: "errors" | |
| 7 | 删除: "flag" | |
| 4 | 新增: "github.com/sylvinus/agent-vm/internal/agentcli" | |
| 8 | 5 | "io" |
| 9 | 删除: "os" | |
| 10 | 删除: "os/signal" | |
| 11 | 删除: "path/filepath" | |
| 12 | 删除: "runtime" | |
| 13 | 删除: "time" | |
| 14 | 删除: | |
| 15 | 删除: "github.com/sylvinus/agent-vm/internal/cage" | |
| 16 | 删除: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 17 | 删除: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 删除: "github.com/sylvinus/agent-vm/internal/version" | |
| 19 | 删除: "github.com/sylvinus/agent-vm/internal/workbench" | |
| 20 | 6 | ) |
| 21 | 7 | |
| 22 | 删除:type agentReply struct { | |
| 23 | 删除: Protocol int `json:"protocol"` | |
| 24 | 删除: Version string `json:"version"` | |
| 25 | 删除: Profile string `json:"config_path,omitempty"` | |
| 26 | 删除: Status string `json:"status"` | |
| 27 | 删除: Data any `json:"data,omitempty"` | |
| 28 | 删除: Error *workbench.AgentError `json:"error,omitempty"` | |
| 29 | 删除:} | |
| 30 | 删除: | |
| 31 | 8 | func runAgent(args []string, stdin io.Reader, stdout io.Writer) int { |
| 32 | 删除: reply := agentReply{Protocol: workbench.AgentProtocol, Version: version.Version, Status: "completed"} | |
| 33 | 删除: finish := func(data any, err error) int { | |
| 34 | 删除: reply.Data = data | |
| 35 | 删除: code := 0 | |
| 36 | 删除: if err != nil { | |
| 37 | 删除: reply.Status = "error" | |
| 38 | 删除: code = 1 | |
| 39 | 删除: var ae *workbench.AgentError | |
| 40 | 删除: if errors.As(err, &ae) { | |
| 41 | 删除: reply.Error = ae | |
| 42 | 删除: } else { | |
| 43 | 删除: reply.Error = &workbench.AgentError{Code: "operation_failed", Message: "Cage could not complete the operation. Inspect diagnostics.", NextAction: "doctor"} | |
| 44 | 删除: } | |
| 45 | 删除: if reply.Error.Code == "invalid_input" || reply.Error.Code == "unknown_operation" { | |
| 46 | 删除: code = 2 | |
| 47 | 删除: } | |
| 48 | 删除: if reply.Error.Code == "account_locked" || reply.Error.Code == "user_action_required" { | |
| 49 | 删除: code = 3 | |
| 50 | 删除: } | |
| 51 | 删除: if reply.Error.Code == "wait_timeout" { | |
| 52 | 删除: code = 4 | |
| 53 | 删除: } | |
| 54 | 删除: } | |
| 55 | 删除: if json.NewEncoder(stdout).Encode(reply) != nil { | |
| 56 | 删除: return 1 | |
| 57 | 删除: } | |
| 58 | 删除: return code | |
| 59 | 删除: } | |
| 60 | 删除: bad := func(message string) int { | |
| 61 | 删除: return finish(nil, &workbench.AgentError{Code: "invalid_input", Message: message, NextAction: "capabilities"}) | |
| 62 | 删除: } | |
| 63 | 删除: command := "capabilities" | |
| 64 | 删除: if len(args) > 0 { | |
| 65 | 删除: command = args[0] | |
| 66 | 删除: args = args[1:] | |
| 67 | 删除: } | |
| 68 | 删除: operand := "" | |
| 69 | 删除: if command == "call" || command == "job" { | |
| 70 | 删除: if len(args) == 0 { | |
| 71 | 删除: return bad("call needs an operation; job needs a job id.") | |
| 72 | 删除: } | |
| 73 | 删除: operand, args = args[0], args[1:] | |
| 74 | 删除: } | |
| 75 | 删除: flags := flag.NewFlagSet("cage agent", flag.ContinueOnError) | |
| 76 | 删除: flags.SetOutput(io.Discard) | |
| 77 | 删除: config := flags.String("config", os.Getenv(cage.ConfigEnv), "") | |
| 78 | 删除: input := flags.String("input", "", "") | |
| 79 | 删除: output := flags.String("output", "", "") | |
| 80 | 删除: wait := flags.Duration("wait", 0, "") | |
| 81 | 删除: _ = flags.Bool("json", true, "") | |
| 82 | 删除: if flags.Parse(args) != nil || flags.NArg() != 0 { | |
| 83 | 删除: return bad("Usage: cage agent capabilities|doctor|init|service.start|host.inspect|call NAME|job ID|diagnostics [--config PATH] [--input -|FILE] [--wait 5m] [--output PATH]") | |
| 84 | 删除: } | |
| 85 | 删除: if *wait < 0 || *wait > 24*time.Hour { | |
| 86 | 删除: return bad("--wait must be between 0 and 24h.") | |
| 87 | 删除: } | |
| 88 | 删除: if *input != "" && command != "call" { | |
| 89 | 删除: return bad("--input is valid only for call.") | |
| 90 | 删除: } | |
| 91 | 删除: if *output != "" && command != "diagnostics" { | |
| 92 | 删除: return bad("--output is valid only for diagnostics.") | |
| 93 | 删除: } | |
| 94 | 删除: if *wait != 0 && command != "call" && command != "job" { | |
| 95 | 删除: return bad("--wait is valid only for call and job.") | |
| 96 | 删除: } | |
| 97 | 删除: if *config == "" { | |
| 98 | 删除: home, err := os.UserHomeDir() | |
| 99 | 删除: if err != nil { | |
| 100 | 删除: return finish(nil, err) | |
| 101 | 删除: } | |
| 102 | 删除: *config = filepath.Join(home, ".claude-cage", "config.json") | |
| 103 | 删除: } | |
| 104 | 删除: path, err := filepath.Abs(*config) | |
| 105 | 删除: if err != nil { | |
| 106 | 删除: return finish(nil, err) | |
| 107 | 删除: } | |
| 108 | 删除: reply.Profile = path | |
| 109 | 删除: ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) | |
| 110 | 删除: defer stop() | |
| 111 | 删除: switch command { | |
| 112 | 删除: case "help", "--help", "capabilities": | |
| 113 | 删除: return finish(map[string]any{"platform": runtime.GOOS, "arch": runtime.GOARCH, "commands": []string{"capabilities", "doctor", "init", "service.start", "host.inspect", "call NAME", "job ID", "diagnostics"}, "operations": workbench.AgentOperations(), "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 workload at config_path; remote use via authenticated SSH on the owning host", "job_retention": "only the latest job; query promptly and never resubmit an unknown mutation automatically"}, nil) | |
| 114 | 删除: case "init": | |
| 115 | 删除: if _, err := os.Stat(path); err == nil { | |
| 116 | 删除: if _, err := cage.Load(path); err != nil { | |
| 117 | 删除: return finish(nil, &workbench.AgentError{Code: "config_invalid", Message: "Existing configuration is invalid. Preserve it and export diagnostics.", NextAction: "diagnostics"}) | |
| 118 | 删除: } | |
| 119 | 删除: return finish(map[string]bool{"created": false}, nil) | |
| 120 | 删除: } else if !os.IsNotExist(err) { | |
| 121 | 删除: return finish(nil, err) | |
| 122 | 删除: } | |
| 123 | 删除: if err := host.EnsurePrivateDir(filepath.Dir(path)); err != nil { | |
| 124 | 删除: return finish(nil, err) | |
| 125 | 删除: } | |
| 126 | 删除: file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) | |
| 127 | 删除: if err != nil { | |
| 128 | 删除: return finish(nil, err) | |
| 129 | 删除: } | |
| 130 | 删除: err = host.ProtectFile(path) | |
| 131 | 删除: if err == nil { | |
| 132 | 删除: err = json.NewEncoder(file).Encode(cage.DefaultConfig()) | |
| 133 | 删除: } | |
| 134 | 删除: if e := file.Close(); err == nil { | |
| 135 | 删除: err = e | |
| 136 | 删除: } | |
| 137 | 删除: return finish(map[string]bool{"created": err == nil}, err) | |
| 138 | 删除: case "service.start": | |
| 139 | 删除: if err := host.ConfigureWindowsRuntime(); err != nil { | |
| 140 | 删除: return finish(nil, err) | |
| 141 | 删除: } | |
| 142 | 删除: startup, cancel := context.WithTimeout(ctx, 15*time.Second) | |
| 143 | 删除: defer cancel() | |
| 144 | 删除: if err := workbench.AgentStartService(startup, path); err != nil { | |
| 145 | 删除: return finish(nil, err) | |
| 146 | 删除: } | |
| 147 | 删除: return finish(map[string]bool{"service_ready": true}, nil) | |
| 148 | 删除: case "host.inspect": | |
| 149 | 删除: probe, cancel := context.WithTimeout(ctx, 20*time.Second) | |
| 150 | 删除: defer cancel() | |
| 151 | 删除: return finish(guestos.Inspect(probe), nil) | |
| 152 | 删除: case "doctor": | |
| 153 | 删除: return finish(agentDoctor(ctx, path), nil) | |
| 154 | 删除: case "diagnostics": | |
| 155 | 删除: if !filepath.IsAbs(*output) { | |
| 156 | 删除: return bad("diagnostics requires --output with an absolute local ZIP path.") | |
| 157 | 删除: } | |
| 158 | 删除: if _, err := os.Lstat(*output); !os.IsNotExist(err) { | |
| 159 | 删除: return bad("Choose a new output path; existing files are preserved.") | |
| 160 | 删除: } | |
| 161 | 删除: if err := workbench.ExportAgentDiagnostics(path, *output); err != nil { | |
| 162 | 删除: return finish(nil, err) | |
| 163 | 删除: } | |
| 164 | 删除: return finish(map[string]string{"path": *output}, nil) | |
| 165 | 删除: case "call", "job": | |
| 166 | 删除: var data json.RawMessage | |
| 167 | 删除: if command == "call" { | |
| 168 | 删除: body := []byte("{}") | |
| 169 | 删除: if *input != "" { | |
| 170 | 删除: reader := stdin | |
| 171 | 删除: if *input != "-" { | |
| 172 | 删除: f, e := os.Open(*input) | |
| 173 | 删除: if e != nil { | |
| 174 | 删除: return finish(nil, e) | |
| 175 | 删除: } | |
| 176 | 删除: defer f.Close() | |
| 177 | 删除: reader = f | |
| 178 | 删除: } | |
| 179 | 删除: body, err = io.ReadAll(io.LimitReader(reader, (12<<20)+1)) | |
| 180 | 删除: if err != nil { | |
| 181 | 删除: return finish(nil, err) | |
| 182 | 删除: } | |
| 183 | 删除: } | |
| 184 | 删除: var object map[string]json.RawMessage | |
| 185 | 删除: if len(body) > 12<<20 || json.Unmarshal(body, &object) != nil || object == nil { | |
| 186 | 删除: return bad("Input must be one JSON object of at most 12 MiB.") | |
| 187 | 删除: } | |
| 188 | 删除: for _, op := range workbench.AgentOperations() { | |
| 189 | 删除: if op.Name == operand && !op.Mutates && len(object) > 0 { | |
| 190 | 删除: return bad("Read operations accept no input fields.") | |
| 191 | 删除: } | |
| 192 | 删除: } | |
| 193 | 删除: data, err = workbench.AgentCall(ctx, path, operand, body) | |
| 194 | 删除: } else { | |
| 195 | 删除: data, err = workbench.AgentJob(ctx, path, operand) | |
| 196 | 删除: } | |
| 197 | 删除: if err != nil { | |
| 198 | 删除: return finish(nil, err) | |
| 199 | 删除: } | |
| 200 | 删除: if command == "call" && operand == "project.open" { | |
| 201 | 删除: var project struct { | |
| 202 | 删除: Approval string `json:"approval"` | |
| 203 | 删除: } | |
| 204 | 删除: _ = json.Unmarshal(data, &project) | |
| 205 | 删除: if project.Approval != "" { | |
| 206 | 删除: return finish(data, &workbench.AgentError{Code: "user_action_required", Message: "Complete project access authorization in the local Cage window, then inspect project state.", NextAction: "open_desktop"}) | |
| 207 | 删除: } | |
| 208 | 删除: } | |
| 209 | 删除: var job workbench.Job | |
| 210 | 删除: _ = json.Unmarshal(data, &job) | |
| 211 | 删除: if job.ID == "" { | |
| 212 | 删除: return finish(data, nil) | |
| 213 | 删除: } | |
| 214 | 删除: if *wait > 0 && job.Running { | |
| 215 | 删除: data, err = agentWait(ctx, path, job.ID, *wait) | |
| 216 | 删除: if err != nil { | |
| 217 | 删除: return finish(data, err) | |
| 218 | 删除: } | |
| 219 | 删除: _ = json.Unmarshal(data, &job) | |
| 220 | 删除: } | |
| 221 | 删除: if job.Running { | |
| 222 | 删除: reply.Status = "accepted" | |
| 223 | 删除: return finish(data, nil) | |
| 224 | 删除: } | |
| 225 | 删除: if job.Canceled { | |
| 226 | 删除: return finish(data, &workbench.AgentError{Code: "job_canceled", Message: "The original job was canceled. Inspect status before retrying.", NextAction: "status"}) | |
| 227 | 删除: } | |
| 228 | 删除: if job.Error != "" { | |
| 229 | 删除: return finish(data, &workbench.AgentError{Code: "job_failed", Message: job.Error, NextAction: "doctor"}) | |
| 230 | 删除: } | |
| 231 | 删除: return finish(data, nil) | |
| 232 | 删除: default: | |
| 233 | 删除: return bad("Unknown agent command. Run cage agent capabilities.") | |
| 234 | 删除: } | |
| 235 | 删除:} | |
| 236 | 删除: | |
| 237 | 删除:func agentWait(parent context.Context, path, id string, duration time.Duration) (json.RawMessage, error) { | |
| 238 | 删除: ctx, cancel := context.WithTimeout(parent, duration) | |
| 239 | 删除: defer cancel() | |
| 240 | 删除: tick := time.NewTicker(500 * time.Millisecond) | |
| 241 | 删除: defer tick.Stop() | |
| 242 | 删除: var latest json.RawMessage | |
| 243 | 删除: for { | |
| 244 | 删除: select { | |
| 245 | 删除: case <-ctx.Done(): | |
| 246 | 删除: 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} | |
| 247 | 删除: case <-tick.C: | |
| 248 | 删除: data, err := workbench.AgentJob(ctx, path, id) | |
| 249 | 删除: if ctx.Err() != nil { | |
| 250 | 删除: continue | |
| 251 | 删除: } | |
| 252 | 删除: if err != nil { | |
| 253 | 删除: return latest, err | |
| 254 | 删除: } | |
| 255 | 删除: latest = data | |
| 256 | 删除: var job workbench.Job | |
| 257 | 删除: if json.Unmarshal(data, &job) != nil || job.ID != id { | |
| 258 | 删除: return data, &workbench.AgentError{Code: "job_not_found", Message: "Original job state is unavailable. Inspect status before retrying.", NextAction: "status"} | |
| 259 | 删除: } | |
| 260 | 删除: if !job.Running { | |
| 261 | 删除: return data, nil | |
| 262 | 删除: } | |
| 263 | 删除: } | |
| 264 | 删除: } | |
| 265 | 删除:} | |
| 266 | 删除: | |
| 267 | 删除:func agentDoctor(ctx context.Context, path string) map[string]any { | |
| 268 | 删除: result := map[string]any{"note": "Read-only snapshot. No repairs were applied; missing services were not started."} | |
| 269 | 删除: checks := []map[string]any{} | |
| 270 | 删除: add := func(code, status, next string) { | |
| 271 | 删除: checks = append(checks, map[string]any{"code": code, "status": status, "next_action": next}) | |
| 272 | 删除: } | |
| 273 | 删除: if _, err := os.Stat(path); os.IsNotExist(err) { | |
| 274 | 删除: add("config_missing", "blocked", "init") | |
| 275 | 删除: } else if _, err := cage.Load(path); err != nil { | |
| 276 | 删除: add("config_invalid", "blocked", "diagnostics") | |
| 277 | 删除: } else { | |
| 278 | 删除: add("config_valid", "ok", "") | |
| 279 | 删除: } | |
| 280 | 删除: for _, name := range []string{"account.json", "proxy/sources.json"} { | |
| 281 | 删除: if err := host.CheckPrivateFile(filepath.Join(filepath.Dir(path), filepath.FromSlash(name))); err != nil && !os.IsNotExist(err) { | |
| 282 | 删除: add("private_file_permissions", "blocked", "repair_profile_permissions") | |
| 283 | 删除: } | |
| 284 | 删除: } | |
| 285 | 删除: data, err := workbench.AgentCall(ctx, path, "account.status", nil) | |
| 286 | 删除: if err != nil { | |
| 287 | 删除: var ae *workbench.AgentError | |
| 288 | 删除: if errors.As(err, &ae) { | |
| 289 | 删除: add(ae.Code, "blocked", ae.NextAction) | |
| 290 | 删除: } else { | |
| 291 | 删除: add("service_unavailable", "blocked", "service.start") | |
| 292 | 删除: } | |
| 293 | 删除: } else { | |
| 294 | 删除: var account struct { | |
| 295 | 删除: Exists bool `json:"exists"` | |
| 296 | 删除: Unlocked bool `json:"unlocked"` | |
| 297 | 删除: } | |
| 298 | 删除: _ = json.Unmarshal(data, &account) | |
| 299 | 删除: if !account.Exists { | |
| 300 | 删除: add("account_missing", "blocked", "account.create") | |
| 301 | 删除: } else if !account.Unlocked { | |
| 302 | 删除: add("account_locked", "blocked", "account.unlock") | |
| 303 | 删除: } else { | |
| 304 | 删除: add("account_unlocked", "ok", "") | |
| 305 | 删除: if proxy, e := workbench.AgentCall(ctx, path, "proxy.status", nil); e == nil { | |
| 306 | 删除: result["proxy"] = proxy | |
| 307 | 删除: var view struct { | |
| 308 | 删除: Active bool `json:"active"` | |
| 309 | 删除: Running bool `json:"running"` | |
| 310 | 删除: Sources []any `json:"sources"` | |
| 311 | 删除: } | |
| 312 | 删除: _ = json.Unmarshal(proxy, &view) | |
| 313 | 删除: switch { | |
| 314 | 删除: case len(view.Sources) == 0: | |
| 315 | 删除: add("proxy_missing", "blocked", "proxy.import") | |
| 316 | 删除: case !view.Active: | |
| 317 | 删除: add("proxy_unapplied", "blocked", "proxy.select") | |
| 318 | 删除: case !view.Running: | |
| 319 | 删除: add("proxy_stopped", "blocked", "proxy.restart") | |
| 320 | 删除: default: | |
| 321 | 删除: add("proxy_running", "ok", "") | |
| 322 | 删除: } | |
| 323 | 删除: } else { | |
| 324 | 删除: add("proxy_status_unavailable", "blocked", "diagnostics") | |
| 325 | 删除: } | |
| 326 | 删除: if state, e := workbench.AgentCall(ctx, path, "status", nil); e == nil { | |
| 327 | 删除: result["environment"] = state | |
| 328 | 删除: var view struct { | |
| 329 | 删除: Ready bool `json:"ready"` | |
| 330 | 删除: Running bool `json:"vm_running"` | |
| 331 | 删除: Update bool `json:"environment_update_required"` | |
| 332 | 删除: Job workbench.Job `json:"job"` | |
| 333 | 删除: NetworkError string `json:"network_error"` | |
| 334 | 删除: } | |
| 335 | 删除: _ = json.Unmarshal(state, &view) | |
| 336 | 删除: switch { | |
| 337 | 删除: case view.Job.Running: | |
| 338 | 删除: add("job_running", "waiting", "job "+view.Job.ID) | |
| 339 | 删除: case view.Job.Error != "": | |
| 340 | 删除: add("job_failed", "blocked", "diagnostics") | |
| 341 | 删除: case view.Update: | |
| 342 | 删除: add("environment_update_required", "blocked", "environment.update") | |
| 343 | 删除: case !view.Running || !view.Ready: | |
| 344 | 删除: add("environment_not_ready", "blocked", "environment.start") | |
| 345 | 删除: case view.NetworkError != "": | |
| 346 | 删除: add("network_not_ready", "blocked", "inspect_network_policy") | |
| 347 | 删除: default: | |
| 348 | 删除: add("environment_ready", "ok", "") | |
| 349 | 删除: } | |
| 350 | 删除: } else { | |
| 351 | 删除: add("environment_status_unavailable", "blocked", "diagnostics") | |
| 352 | 删除: } | |
| 353 | 删除: } | |
| 354 | 删除: } | |
| 355 | 删除: result["checks"] = checks | |
| 356 | 删除: return result | |
| 9 | 新增: return agentcli.Main(args, stdin, stdout) | |
| 357 | 10 | } |
| @@ -24,7 +24,7 @@ keywords: Agent CLI JSON 自动化 配置 接口 安装 诊断 修复 capabiliti | ||
| 24 | 24 | |
| 25 | 25 | `agent capabilities` 输出本构建的协议版本、操作清单、输入字段和退出码,不启动后台或创建配置。首次配置与每次升级后都先读取一次。机器阅读入口为 `/agent.md`、`/llms.txt`、`/llms-full.txt`,使用 Cage 的外部 Agent 从本页开始。 |
| 26 | 26 | |
| 27 | 删除:所有 `agent` 命令自动输出 JSON,`--json` 可省略。示例把 `cage` 作为占位命令;执行时替换为上表路径。`--config /absolute/path/config.json` 明确选择配置;省略时使用 `CLAUDE_CAGE_CONFIG`,再省略则使用用户主目录下的 `.claude-cage/config.json`。每次输出中的 `config_path` 是实际目标。桌面配置的远端选择不会改变这个目标;管理服务器时,在经过用户授权的 SSH 通道内,在服务器上运行同一接口并明确路径。 | |
| 27 | 新增:所有 `agent` 命令自动输出 JSON,`--json` 可省略。示例把 `cage` 作为占位命令;执行时替换为上表路径。`--config /absolute/path/config.json` 明确选择配置;省略时使用 `CLAUDE_CAGE_CONFIG`,再省略则使用用户主目录下的 `.claude-cage/config.json`。每次输出中的 `config_path` 是实际目标。桌面配置的远端选择不会改变这个目标;管理服务器时,也可通过下文的 desktop / selected 范围管理桌面连接,或在授权的 SSH 通道内运行服务器接口。 | |
| 28 | 28 | |
| 29 | 29 | ## 下载、校验与安装 |
| 30 | 30 | |
| @@ -124,7 +124,7 @@ cage agent call settings.get | ||
| 124 | 124 | |
| 125 | 125 | 首次需要换存储位置时,在安装前用 `storage.set`,输入 `directory`、`previous`、`migrate`;后两项分别来自 `storage.get` 的 `directory` 和 `has_environment`。已有环境的迁移会停止任务并保留备份,应先保存工作。资源配置用 `resources.set` 的 `allocation` 对象;修改保存后再以 `{}` 调用应用资源,会重启环境。容器资源由服务器部署管理。 |
| 126 | 126 | |
| 127 | 删除:只发送需要修改的设置,先预检再应用;未指定字段会保留,包括出口规则对象中未指定的 IP、国家和城市基准。`null` 不用于清空字段。 | |
| 127 | 新增:只发送需要修改的设置,先预检再应用;browser_home_url 单独通过 browser.preferences.set 保存,环境设置分开提交;未指定字段会保留,包括出口规则对象中未指定的 IP、国家和城市基准。`null` 不用于清空字段。 | |
| 128 | 128 | |
| 129 | 129 | ```json |
| 130 | 130 | {"patch":{"auto_timezone":true,"auto_language":true},"dry_run":true} |
| @@ -149,11 +149,11 @@ cage agent call network.check --wait 5m | ||
| 149 | 149 | |
| 150 | 150 | 以 `status.ready`、`vm_running` 以及 `safety` 中当前配置对应的网络检查与授权共同判断可用性;`proxy.status.network_open` 可辅助检查外网是否已放行。网络暂停时保持用户的暂停意图,只有用户要求恢复联网才运行 `network.check`。完成首次引导使用 `initialization.set` 的 `{"action":"complete"}`,后台会再次核对环境与网络状态。 |
| 151 | 151 | |
| 152 | 删除:打开项目使用 `project.open`:`{"workspace":"用户授权的绝对路径","add":true,"activate":true}`。它会让客机访问这个目录,改动会影响主机文件。返回 `approval` 表示仍需在本机 Cage 窗口完成系统授权。Claude 的服务登录仍在 Cage 内的官方工具中完成;本接口不会导入主机 Claude 凭据。 | |
| 152 | 新增:打开项目使用 `project.open`:`{"workspace":"用户授权的绝对路径","add":true,"activate":true}`。它会让客机访问这个目录,改动会影响主机文件。返回 `approval` 表示等待系统授权;Agent 可以调用相同的 `/api/macos/project-approval` 查看、操作该窗口。Claude 的服务登录仍在 Cage 内的官方工具中完成;本接口不会导入主机 Claude 凭据。 | |
| 153 | 153 | |
| 154 | 154 | ## JSON 结果和异步任务 |
| 155 | 155 | |
| 156 | 删除:每次命令的 stdout 只有一个 JSON 对象。格式示例: | |
| 156 | 新增:除流式 `socket` 外,每次命令的 stdout 只有一个 JSON 对象;`socket` 的 NDJSON 格式见下文。格式示例: | |
| 157 | 157 | |
| 158 | 158 | ```json |
| 159 | 159 | {"protocol":1,"version":"构建版本","config_path":"绝对配置路径","status":"accepted","data":{"id":"012345abcdef","kind":"start","running":true,"message":"正在准备…"}} |
| @@ -175,7 +175,7 @@ cage agent job 012345abcdef --wait 30m | ||
| 175 | 175 | |
| 176 | 176 | `--wait` 为有限等待,范围为 0 到 24 小时;不指定时立即返回。等待或客户端断开不会自动取消作业。后台只保留最近一个作业,后续作业会替换查询记录,重启也可能失去记录。`job_not_found`、`outcome_unknown` 或连接中断后,先读 `status` 和相应配置,核对副作用;不要把其他任务成功当成原任务成功。`job_canceled` 单独表示取消,不能视为完成。 |
| 177 | 177 | |
| 178 | 删除:输入必须是单个 JSON 对象,最大 12 MiB。未知命令和字段会被拒绝。能力清单的 `input_schema` 描述允许字段;当前平台、系统状态和字段组合仍由后台验证。输出错误与任务日志会脱敏,正常字段中的项目路径、节点 ID、镜像计划和设置 URL 会保留以支持后续操作;这些结果仍属于用户私有数据。 | |
| 178 | 新增:命名 call 的输入必须是单个 JSON 对象,最大 12 MiB;request 支持原始二进制文件流。未知命令和字段会被拒绝。能力清单的 `input_schema` 描述允许字段;当前平台、系统状态和字段组合仍由后台验证。错误说明经过脱敏,正常业务结果保持接口原值。用户可以查看的密码、Cookie、配对码等,在同样的再次验证和权限检查通过后也可由 Agent 读取,应通过私有管道处理,避免默认记录或回显。 | |
| 179 | 179 | |
| 180 | 180 | ## 定位问题与恢复 |
| 181 | 181 | |
| @@ -195,7 +195,7 @@ cage agent job 012345abcdef --wait 30m | ||
| 195 | 195 | | `job_failed` | 保留 `data.error` 与脱敏的任务日志,检查当前配置、来源可用性、空间与主机条件。 | |
| 196 | 196 | | `outcome_unknown`、`job_not_found` | 读取实际副作用;代理导入、安装和迁移都不能盲目重新提交。 | |
| 197 | 197 | | 外网未放行或检查失败 | 检查所选代理、链路、出口规则、时间和位置;保持失败时关闭外网。用户授权后可切换节点或重检,不自动改为直连或降低规则。 | |
| 198 | 删除:| `user_action_required`、项目 `approval`、首次系统设置未完成 | 告诉用户在哪个窗口完成哪项操作;完成后查询原状态继续。 | | |
| 198 | 新增:| `user_action_required`、项目 `approval`、首次系统设置未完成 | 使用同一原生桥或客机授权窗口接口继续;系统要求生物认证、管理员确认时,完成验证后查询原状态。 | | |
| 199 | 199 | |
| 200 | 200 | ```sh |
| 201 | 201 | cage agent diagnostics --output /absolute/path/new-cage-diagnostics.zip |
| @@ -210,3 +210,96 @@ cage agent diagnostics --output /absolute/path/new-cage-diagnostics.zip | ||
| 210 | 210 | ## 交付给用户的结果 |
| 211 | 211 | |
| 212 | 212 | 完成后用几句话说明:实际安装的版本和路径、使用的配置与客机、代理是否应用、环境是否运行、网络检查是否通过、项目是否连接。列出需要用户完成的授权和登录,以及尚未验证的范围。仅完成下载、模拟请求或单平台编译时,分别报告,不写成完整安装或三平台实测成功。 |
| 213 | 新增: | |
| 214 | 新增:## 用户与 Agent 的操作空间 | |
| 215 | 新增: | |
| 216 | 新增:命名操作是常用配置的快捷方式。通用 `request` 访问与界面相同的 HTTP API,`socket` 连接同一 WebSocket,原生操作交给实际桌面窗口的现有桥接执行。两种入口使用同一账户权限、密码重认证、项目授权、网络门槛和平台能力。用户授权 Agent 完成配置后,Cage 不因为调用者是 Agent 增加一轮产品确认。系统自身要求的 Touch ID、管理员认证等仍然有效。 | |
| 217 | 新增: | |
| 218 | 新增:### 先选择目标 | |
| 219 | 新增: | |
| 220 | 新增:| 范围 | 目标 | | |
| 221 | 新增:| --- | --- | | |
| 222 | 新增:| `local`,完整应用默认 | 明确 config_path 对应的本机工作负载,固定本机,不跟随 SSH 切换。 | | |
| 223 | 新增:| `desktop` | 完整应用的桌面连接配置、SSH 主机、本机信任和原生窗口队列。需要桌面连接服务运行。 | | |
| 224 | 新增:| `selected` | 完整应用桌面当前选择的环境,必须带 `--connection`,值取 client.context.connection_id。切换后旧代次被拒绝。 | | |
| 225 | 新增:| `client`,轻量客户端默认 | 轻量客户端的连接服务;业务请求必须带当前 `--connection`,连接管理请求可不带。 | | |
| 226 | 新增: | |
| 227 | 新增:完整应用的 `--config` 仍指原主配置;desktop 范围会定位对应的 desktop-entry 服务。轻量客户端使用自己安装包中的 CLI,默认配置为 `~/.claude-cage/client/config.json`。需要桌面窗口时,Agent 可以用正常系统启动方式打开 Cage,再继续接口操作;没有要求用户必须亲手打开窗口。 | |
| 228 | 新增: | |
| 229 | 新增:```sh | |
| 230 | 新增:cage agent call client.context --scope desktop | |
| 231 | 新增:cage agent routes --scope desktop | |
| 232 | 新增:cage agent call settings.get --scope selected --connection 当前连接代次 | |
| 233 | 新增:``` | |
| 234 | 新增: | |
| 235 | 新增:`capabilities` 离线返回命名操作与实际输入类型。`routes` 在线读取当前监听器真正注册的路由,新增界面 API 会自动进入清单;平台与环境状态仍决定某路由当前是否可用。带 `{id}` / `{action}` 的模式需要替换为实际值。 | |
| 236 | 新增: | |
| 237 | 新增:### 配置能力对照 | |
| 238 | 新增: | |
| 239 | 新增:| 用户可操作内容 | Agent 的相同入口 | | |
| 240 | 新增:| --- | --- | | |
| 241 | 新增:| 名称、头像、密码、锁定、退出 | account.profile:username/avatar;account.password:old_password/password/confirm_password;account.lock/logout/suspend。 | | |
| 242 | 新增:| 本机信任、记住登录、设置密码保护 | desktop 范围 client.trusted-login:action 为 create/resume/enable/disable/protect,按同一规则提供 password、connection_id。 | | |
| 243 | 新增:| Touch ID 与快捷登录 | native.submit 提交 accountDevice,operation 为 status/enable/disable/unlock,kind 为 automatic/biometric;设备密钥由原生安全存储管理。Windows/Linux 不支持的操作与用户界面返回相同限制。 | | |
| 244 | 新增:| 首次启动的 Git 保护 | host.git 读取,host.git.enable 输入 confirm:true 启用;会修改主机全局 Git 保护配置,与界面动作相同。 | | |
| 245 | 新增:| 外观、字体、配色、自定义主题 | appearance.get/set 读写完整对象,appearance.codex 读取本机 Codex 外观导入;读取后保留未修改字段。 | | |
| 246 | 新增:| 出口位置检测、测速、连接和日志 | settings.probe 输入完整设置草稿;proxy.delay 输入 node_id;proxy.connections/logs。dry_run 仅静态校验。 | | |
| 247 | 新增:| 尚未开始安装时重选系统 | guest.reselect 输入 guest.options.pending.id,仍由原安装状态约束。 | | |
| 248 | 新增:| Claude 账号、额度、分组、启停、调度与排序 | claude-accounts.get/change,动作与字段类型由 capabilities 给出;业务 action 与界面相同。 | | |
| 249 | 新增:| 密码保险箱 | vault.get 列元数据;vault.change 的 action 为 save/delete/unblock/reveal;reveal 仍需 account_password,再次验证后返回真实密码;vault.browser 提供页面填充和保存。 | | |
| 250 | 新增:| 手机配对 | mobile.get/pair/remove;自建中继输入 admin/relay,配对结果是私密邀请码。 | | |
| 251 | 新增:| Tailscale 与 SSH 公钥 | tailscale.get,以及 install/connect/login/disconnect/logout/add-key/remove-key;公钥字段为 key。 | | |
| 252 | 新增:| 浏览器首页 | browser.preferences.get/set;set 立即更新浏览器,失败保留旧值,长度限制与界面一致。settings.patch 单独修改首页时复用同一保存流程。 | | |
| 253 | 新增:| Cookie、权限、扩展、收藏 | browser.cookies/settings/extensions;favorites.get/change。Cookie 的 mode、scope、id、cookieKey 与界面相同。 | | |
| 254 | 新增:| 客机首次设置、登录与授权窗口 | request 访问 /api/macos/first-setup、/api/macos/login、当前构建提供的 /api/macos/maintenance、/api/macos/project-approval;会话、截图和键鼠动作与界面一致。 | | |
| 255 | 新增:| SSH 主机与部署、指纹核对、连接与切换 | desktop 范围 client.hosts、client.hosts.create、client.candidate/commit/cancel/disconnect/local-stop;更新/删除主机使用 PUT/DELETE /api/client/hosts/主机ID。保留同一连接代次、候选、指纹和本机任务去留规则。 | | |
| 256 | 新增:| 已归档会话、名称、固定、账户切换 | request 访问 /api/cli/sessions 和 /api/cli/sessions/会话ID/{metadata,account,archive,restore,purge,open}。 | | |
| 257 | 新增:| 文件选择、主题导入导出、App 更新 | native.submit 调现有 chooseFolder、chooseGuestMedia、importTheme、exportTheme、appUpdate 等原生 action。系统选择器和签名检查照常执行。 | | |
| 258 | 新增: | |
| 259 | 新增:### 通用请求与文件 | |
| 260 | 新增: | |
| 261 | 新增:```sh | |
| 262 | 新增:cage agent request GET /api/settings | |
| 263 | 新增:cage agent request POST /api/browser/extensions/upload \ | |
| 264 | 新增: --input /private/path/extension.zip --content-type application/octet-stream | |
| 265 | 新增:cage agent request GET /api/diagnostics/export --output /absolute/path/new-report.zip | |
| 266 | 新增:cage agent request DELETE /api/client/hosts/主机ID --scope desktop | |
| 267 | 新增:``` | |
| 268 | 新增: | |
| 269 | 新增:JSON 请求通过私有文件或 `--input -` 传递;二进制请求使用文件流和正确的 Content-Type。输入大小由同一生产处理器约束。输出给出 http_status、content_type、必要的 recovery,以及 body 或保存文件的 path,合法的 202 会保留。输出文件排他创建,已有文件保留。同步请求期限为两分钟,长安装通过异步任务跟踪。 | |
| 270 | 新增: | |
| 271 | 新增:request 返回的是实际业务响应;Agent 仍需检查错误字段、任务状态和可见副作用。接口清单中的集合路径可带相同查询参数。新功能没有命名快捷方式时,直接用 request;这种差异不限制用户或 Agent 的操作权限。 | |
| 272 | 新增: | |
| 273 | 新增:WebSocket 用 `cage agent socket /api/terminals/终端ID/stream`。输入输出为 NDJSON,输入每行是 `{"type":"text","data":"原协议JSON字符串"}` 或 `{"type":"binary","data":"base64"}`。输出先发送 `{"protocol":1,"status":"connected"}`,随后为相同的帧对象,结束时输出标准命令结果。握手使用同一账户、Origin 和连接代次,可承载终端输入、尺寸调整和画面等已有消息。Ctrl+C 结束本地查看,断开不停止原终端;会话凭据由 CLI 持有。 | |
| 274 | 新增: | |
| 275 | 新增:### 原生窗口与客户端偏好 | |
| 276 | 新增: | |
| 277 | 新增:先从 client.context 取得实际连接代次,提交同一窗口的原生 action: | |
| 278 | 新增: | |
| 279 | 新增:```json | |
| 280 | 新增:{"connection_id":"当前代次","request":{"action":"accountDevice","operation":"status"}} | |
| 281 | 新增:``` | |
| 282 | 新增: | |
| 283 | 新增:```sh | |
| 284 | 新增:cage agent call native.submit --scope desktop --input /private/path/native.json | |
| 285 | 新增:cage agent request GET /api/agent/native/返回的ID --scope desktop | |
| 286 | 新增:``` | |
| 287 | 新增: | |
| 288 | 新增:原生队列属于当前窗口所在的监听器。认领与回执需要原生启动桥换取的窗口证明,普通网页会话无法抢占;证明只留在窗口闭包,不返回给 Agent。窗口只认领一次;pending/running 需要继续查询原 ID,completed 表示收到真实回执,failed 返回原生失败。连接切换、窗口关闭或丢失回执后不自动重放动作;两分钟内未被窗口认领的请求失败。记录过期或被后续记录替换后,先核对副作用。只有依赖原生窗口的操作需要打开窗口,普通配置可直接调用后台。 | |
| 289 | 新增: | |
| 290 | 新增:客户端的布局、音量与缩放使用 WebView 的原有存储。提交 `request.action:"clientPreferences"`,operation 为 get/set;set 的 values 使用下表原始字符串,null 恢复默认。写入成功回执后刷新当前窗口,使实际界面应用;远端偏好按同一实例后缀隔离。 | |
| 291 | 新增: | |
| 292 | 新增:| 逻辑键 | 原始字符串编码 | | |
| 293 | 新增:| --- | --- | | |
| 294 | 新增:| cage-sidebar-collapsed | `true` 或 `false` | | |
| 295 | 新增:| cage-browser-tab-layout | JSON 字符串,例如 `"vertical"`,在外层 JSON 中需要转义引号 | | |
| 296 | 新增:| cage-keyboard | `mac` / `native`,仅远端客户端;本机使用 settings.keyboard | | |
| 297 | 新增:| cage.audio | JSON 对象,例如 `{"muted":false,"volume":0.5}` | | |
| 298 | 新增:| cage-desktop-zoom | 0.75、0.9、1、1.1、1.25、1.5 | | |
| 299 | 新增:| cage-active | 当前标签 ID | | |
| 300 | 新增:| cage-tab-layout | get 返回的按项目保存名称、固定和顺序的对象 JSON | | |
| 301 | 新增:| cage-recent-environment | local 或主机 ID | | |
| 302 | 新增: | |
| 303 | 新增:外观走 appearance 持久接口,WebView 中的外观只是缓存;保存后可以通过原生 reconnect 刷新。原生动作继续交给三平台已有接收者,平台不支持时返回同样的不可用结果。已授权 Agent 可以操作产品内的授权窗口;系统要求的生物认证或管理员验证仍由系统执行。 | |
| 304 | 新增: | |
| 305 | 新增:原生设备凭据和启动票据属于内部运输。通用 request 不直接导出 device-enroll/device-unlock 等包装密钥;这些操作通过 native.submit 的 accountDevice 调用原有安全存储与生物认证,保留用户的同一操作能力。 | |
| @@ -0,0 +1,460 @@ | ||
| 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 | 新增:} | |
| @@ -1,4 +1,4 @@ | ||
| 1 | 删除:package main | |
| 1 | 新增:package agentcli | |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "bytes" |
| @@ -16,7 +16,7 @@ func TestAgentCLIProtocolAndInit(t *testing.T) { | ||
| 16 | 16 | run := func(args ...string) (int, agentReply) { |
| 17 | 17 | t.Helper() |
| 18 | 18 | var output bytes.Buffer |
| 19 | 删除: code := runAgent(append(args, "--config", path), strings.NewReader(""), &output) | |
| 19 | 新增: code := Main(append(args, "--config", path), strings.NewReader(""), &output) | |
| 20 | 20 | var reply agentReply |
| 21 | 21 | if json.Unmarshal(output.Bytes(), &reply) != nil || reply.Protocol != 1 { |
| 22 | 22 | t.Fatalf("not one protocol reply: %s", output.String()) |
| @@ -56,13 +56,13 @@ func TestAgentCLIProtocolAndInit(t *testing.T) { | ||
| 56 | 56 | func TestAgentCLIRejectsSecretArgumentsAndMalformedJSON(t *testing.T) { |
| 57 | 57 | for _, input := range []string{`null`, `[]`, `{} {}`, `{"password":"secret"} trailing`} { |
| 58 | 58 | var output bytes.Buffer |
| 59 | 删除: code := runAgent([]string{"call", "account.unlock", "--input", "-", "--config", filepath.Join(t.TempDir(), "config.json")}, strings.NewReader(input), &output) | |
| 59 | 新增: code := Main([]string{"call", "account.unlock", "--input", "-", "--config", filepath.Join(t.TempDir(), "config.json")}, strings.NewReader(input), &output) | |
| 60 | 60 | if code != 2 || strings.Contains(output.String(), "secret") { |
| 61 | 61 | t.Fatal(code, output.String()) |
| 62 | 62 | } |
| 63 | 63 | } |
| 64 | 64 | var output bytes.Buffer |
| 65 | 删除: code := runAgent([]string{"call", "account.unlock", "--password", "do-not-echo"}, strings.NewReader(""), &output) | |
| 65 | 新增: code := Main([]string{"call", "account.unlock", "--password", "do-not-echo"}, strings.NewReader(""), &output) | |
| 66 | 66 | if code != 2 || strings.Contains(output.String(), "do-not-echo") { |
| 67 | 67 | t.Fatal(output.String()) |
| 68 | 68 | } |
| @@ -7,7 +7,6 @@ import ( | ||
| 7 | 7 | "context" |
| 8 | 8 | "encoding/json" |
| 9 | 9 | "errors" |
| 10 | 删除: "io" | |
| 11 | 10 | "net/http" |
| 12 | 11 | "net/url" |
| 13 | 12 | "path/filepath" |
| @@ -16,6 +15,7 @@ import ( | ||
| 16 | 15 | "time" |
| 17 | 16 | |
| 18 | 17 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/remotehost" | |
| 19 | 19 | ) |
| 20 | 20 | |
| 21 | 21 | const AgentProtocol = 1 |
| @@ -28,9 +28,8 @@ type AgentOperation struct { | ||
| 28 | 28 | method, path string |
| 29 | 29 | } |
| 30 | 30 | |
| 31 | 删除:// Schemas describe the accepted fields; business validation remains with each | |
| 32 | 删除:// production handler. No arbitrary HTTP paths, credential export or deletion | |
| 33 | 删除:// of environments are exposed through this adapter. | |
| 31 | 新增:// Named operations are discoverable shortcuts for the same production handlers. | |
| 32 | 新增:// AgentRequest also accepts UI endpoints so the shortcut list is not a permission boundary. | |
| 34 | 33 | func AgentOperations() []AgentOperation { |
| 35 | 34 | object := func(fields map[string]string) map[string]any { |
| 36 | 35 | properties := map[string]any{} |
| @@ -43,37 +42,8 @@ func AgentOperations() []AgentOperation { | ||
| 43 | 42 | } |
| 44 | 43 | return map[string]any{"type": "object", "properties": properties, "additionalProperties": false} |
| 45 | 44 | } |
| 46 | 删除: from := func(value any) map[string]any { | |
| 47 | 删除: fields := map[string]string{} | |
| 48 | 删除: var walk func(reflect.Type) | |
| 49 | 删除: walk = func(t reflect.Type) { | |
| 50 | 删除: for i := 0; i < t.NumField(); i++ { | |
| 51 | 删除: f := t.Field(i) | |
| 52 | 删除: if f.Anonymous { | |
| 53 | 删除: walk(f.Type) | |
| 54 | 删除: continue | |
| 55 | 删除: } | |
| 56 | 删除: name := strings.Split(f.Tag.Get("json"), ",")[0] | |
| 57 | 删除: if name == "" || name == "-" { | |
| 58 | 删除: continue | |
| 59 | 删除: } | |
| 60 | 删除: kind := "string" | |
| 61 | 删除: switch f.Type.Kind() { | |
| 62 | 删除: case reflect.Bool: | |
| 63 | 删除: kind = "boolean" | |
| 64 | 删除: case reflect.Int: | |
| 65 | 删除: kind = "integer" | |
| 66 | 删除: case reflect.Slice: | |
| 67 | 删除: kind = "array" | |
| 68 | 删除: case reflect.Struct: | |
| 69 | 删除: kind = "object" | |
| 70 | 删除: } | |
| 71 | 删除: fields[name] = kind | |
| 72 | 删除: } | |
| 73 | 删除: } | |
| 74 | 删除: walk(reflect.TypeOf(value)) | |
| 75 | 删除: return object(fields) | |
| 76 | 删除: } | |
| 45 | 新增: from := func(value any) map[string]any { return agentSchema(reflect.TypeOf(value)) } | |
| 46 | 新增: | |
| 77 | 47 | var ops []AgentOperation |
| 78 | 48 | add := func(name, description, method, path string, schema map[string]any) { |
| 79 | 49 | ops = append(ops, AgentOperation{Name: name, Description: description, Mutates: method != "GET", InputSchema: schema, method: method, path: path}) |
| @@ -84,7 +54,7 @@ func AgentOperations() []AgentOperation { | ||
| 84 | 54 | } |
| 85 | 55 | get("status", "Environment readiness, network checks and current job", "/api/status") |
| 86 | 56 | get("account.status", "Account presence and lock state; no credentials", "/api/account") |
| 87 | 删除: post("account.create", "Create an account only on an empty profile; user chooses the password", "/api/account/create", object(map[string]string{"username": "string", "password": "string", "confirm_password": "string"})) | |
| 57 | 新增: post("account.create", "Create an account only on an empty profile; user chooses the password", "/api/account/create", object(map[string]string{"username": "string", "password": "string", "confirm_password": "string", "avatar": "string"})) | |
| 88 | 58 | post("account.unlock", "Unlock using a user-provided password via private input", "/api/account/unlock", object(map[string]string{"password": "string"})) |
| 89 | 59 | get("settings.get", "Read settings without proxy credentials", "/api/settings") |
| 90 | 60 | post("settings.patch", "Merge specified fields under the operation lock; dry_run validates without writing", "/api/agent/settings", object(map[string]string{"patch": "object", "dry_run": "boolean"})) |
| @@ -115,6 +85,64 @@ func AgentOperations() []AgentOperation { | ||
| 115 | 85 | post("network.check", "Run existing safety checks; may reopen networking when checks pass", "/api/safety/check", object(nil)) |
| 116 | 86 | post("network.pause", "Close external networking and persist pause intent", "/api/safety/close", object(nil)) |
| 117 | 87 | post("project.open", "Grant access only to a user-authorized directory; add=true remembers the grant", "/api/projects/open", object(map[string]string{"workspace": "string", "add": "boolean", "activate": "boolean"})) |
| 88 | 新增: | |
| 89 | 新增: for _, action := range []string{"profile", "password", "lock", "logout", "suspend"} { | |
| 90 | 新增: schema := object(nil) | |
| 91 | 新增: if action == "profile" { | |
| 92 | 新增: schema = object(map[string]string{"username": "string", "avatar": "string"}) | |
| 93 | 新增: } | |
| 94 | 新增: if action == "password" { | |
| 95 | 新增: schema = object(map[string]string{"old_password": "string", "password": "string", "confirm_password": "string"}) | |
| 96 | 新增: } | |
| 97 | 新增: post("account."+action, "Same account action and verification as the workbench", "/api/account/"+action, schema) | |
| 98 | 新增: } | |
| 99 | 新增: get("host.git", "Inspect the same host Git prerequisite as first setup", "/api/host/git") | |
| 100 | 新增: post("host.git.enable", "Enable the workbench's host Git protection with the same confirm=true authorization", "/api/host/git", object(map[string]string{"confirm": "boolean"})) | |
| 101 | 新增: get("appearance.get", "Read complete appearance and saved themes", "/api/appearance") | |
| 102 | 新增: post("appearance.set", "Save complete appearance using the workbench validator", "/api/appearance", from(Appearance{})) | |
| 103 | 新增: get("appearance.codex", "Read the same local Codex appearance import as the UI", "/api/appearance/codex") | |
| 104 | 新增: post("settings.probe", "Probe actual exit location for a complete settings draft", "/api/settings/probe", from(Settings{})) | |
| 105 | 新增: get("proxy.connections", "Inspect live proxy connections", "/api/proxy/connections") | |
| 106 | 新增: get("proxy.logs", "Inspect proxy logs", "/api/proxy/logs") | |
| 107 | 新增: post("proxy.delay", "Measure one proxy node", "/api/proxy/delay", object(map[string]string{"node_id": "string"})) | |
| 108 | 新增: add("guest.reselect", "Clear only the same unstarted installation the UI can reselect", "DELETE", "/api/environment/guest-systems", object(map[string]string{"id": "string"})) | |
| 109 | 新增: get("claude-accounts.get", "Read account roster, quotas and scheduling", "/api/claude-accounts") | |
| 110 | 新增: post("claude-accounts.change", "Apply the same join, cancel, update, scheduling, refresh and removal actions as the UI", "/api/claude-accounts", from(claudeAccountInput{})) | |
| 111 | 新增: get("vault.get", "List metadata; passwords remain hidden exactly as in the UI", "/api/vault") | |
| 112 | 新增: post("vault.change", "Save/delete/unblock; reveal requires the same account_password reauthentication as the UI", "/api/vault", object(map[string]string{"action": "string", "entry": "object", "id": "string", "origin": "string", "account_password": "string"})) | |
| 113 | 新增: ops[len(ops)-1].InputSchema["properties"].(map[string]any)["entry"] = from(vaultEntry{}) | |
| 114 | 新增: post("vault.browser", "Use the browser vault's existing save/fill/block actions", "/api/vault/browser", from(vaultBrowserInput{})) | |
| 115 | 新增: get("mobile.get", "Inspect phone pairing", "/api/mobile-pair") | |
| 116 | 新增: post("mobile.pair", "Generate the same phone pairing invitation", "/api/mobile-pair", object(map[string]string{"admin": "string", "relay": "string"})) | |
| 117 | 新增: add("mobile.remove", "Remove the same paired device", "DELETE", "/api/mobile-pair", object(nil)) | |
| 118 | 新增: get("tailscale.get", "Read guest private-network state", "/api/tailscale") | |
| 119 | 新增: for _, action := range []string{"install", "connect", "login", "disconnect", "logout", "add-key", "remove-key"} { | |
| 120 | 新增: schema := object(nil) | |
| 121 | 新增: if action == "add-key" || action == "remove-key" { | |
| 122 | 新增: schema = object(map[string]string{"key": "string"}) | |
| 123 | 新增: } | |
| 124 | 新增: post("tailscale."+action, "Run the same Tailscale action as the workbench", "/api/tailscale/"+action, schema) | |
| 125 | 新增: } | |
| 126 | 新增: get("browser.preferences.get", "Read the browser homepage", "/api/browser/preferences") | |
| 127 | 新增: post("browser.preferences.set", "Apply and persist the browser homepage with the same rollback as the UI", "/api/browser/preferences", object(map[string]string{"browser_home_url": "string"})) | |
| 128 | 新增: get("browser.tabs", "Read browser tabs and state", "/api/browser/tabs") | |
| 129 | 新增: for _, action := range []string{"settings", "cookies", "extensions", "internal-page", "info", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "split"} { | |
| 130 | 新增: post("browser."+action, "Use the browser's existing workbench action", "/api/browser/"+action, from(browserInput{})) | |
| 131 | 新增: } | |
| 132 | 新增: get("favorites.get", "Read bookmarks and folders", "/api/favorites") | |
| 133 | 新增: post("favorites.change", "Save, move, reorder or delete using the same collection owner", "/api/favorites", from(favoriteChange{})) | |
| 134 | 新增: get("terminals.get", "Read terminal sessions", "/api/terminals") | |
| 135 | 新增: post("terminals.create", "Create the same shell/Claude terminal as the UI", "/api/terminals", from(terminalRequest{})) | |
| 136 | 新增: get("client.context", "Read the desktop connection generation; use desktop scope", "/api/client/context") | |
| 137 | 新增: get("client.hosts", "Read saved SSH hosts; use desktop scope", "/api/client/hosts") | |
| 138 | 新增: post("client.hosts.create", "Save an SSH host through the desktop store", "/api/client/hosts", from(remotehost.HostProfile{})) | |
| 139 | 新增: get("client.local-status", "Inspect local workload from the desktop chooser", "/api/client/local-status") | |
| 140 | 新增: for _, action := range []string{"candidate", "commit", "cancel", "disconnect", "local-stop"} { | |
| 141 | 新增: post("client."+action, "Use the desktop chooser's same explicit connection/candidate protocol", "/api/client/"+action, from(switchRequest{})) | |
| 142 | 新增: } | |
| 143 | 新增: post("client.trusted-login", "Use create/resume/enable/disable/protect through the desktop's native trusted-login owner", "/api/client/trusted-login", object(map[string]string{"action": "string", "password": "string", "connection_id": "string"})) | |
| 144 | 新增: post("native.submit", "Queue an existing native bridge action or clientPreferences request for the desktop window; use desktop scope", "/api/agent/native", object(map[string]string{"request": "object", "connection_id": "string"})) | |
| 145 | 新增: | |
| 118 | 146 | get("diagnostics.status", "Read log collection status", "/api/diagnostics") |
| 119 | 147 | return ops |
| 120 | 148 | } |
| @@ -226,15 +254,7 @@ func agentConnect(ctx context.Context, configPath string) (*controllerClient, er | ||
| 226 | 254 | } |
| 227 | 255 | |
| 228 | 256 | func AgentCall(ctx context.Context, configPath, operation string, input json.RawMessage) (json.RawMessage, error) { |
| 229 | 删除: for _, op := range AgentOperations() { | |
| 230 | 删除: if op.Name == operation { | |
| 231 | 删除: if err := agentValidateInput(input, op.InputSchema); err != nil { | |
| 232 | 删除: return nil, err | |
| 233 | 删除: } | |
| 234 | 删除: return agentRequest(ctx, configPath, op.method, op.path, input) | |
| 235 | 删除: } | |
| 236 | 删除: } | |
| 237 | 删除: return nil, &AgentError{Code: "unknown_operation", Message: "Unknown operation. Read capabilities for supported names.", NextAction: "capabilities"} | |
| 257 | 新增: return AgentCallTarget(ctx, configPath, AgentTarget{}, operation, input) | |
| 238 | 258 | } |
| 239 | 259 | |
| 240 | 260 | func agentValidateInput(input json.RawMessage, schema map[string]any) error { |
| @@ -262,44 +282,11 @@ func AgentJob(ctx context.Context, configPath, id string) (json.RawMessage, erro | ||
| 262 | 282 | } |
| 263 | 283 | |
| 264 | 284 | func agentRequest(ctx context.Context, configPath, method, path string, input json.RawMessage) (json.RawMessage, error) { |
| 265 | 删除: c, err := agentConnect(ctx, configPath) | |
| 266 | 删除: if err != nil { | |
| 267 | 删除: return nil, err | |
| 268 | 删除: } | |
| 269 | 删除: defer c.close() | |
| 270 | 删除: request, err := http.NewRequestWithContext(ctx, method, c.origin+path, bytes.NewReader(input)) | |
| 271 | 删除: if err != nil { | |
| 272 | 删除: return nil, err | |
| 273 | 删除: } | |
| 274 | 删除: request.Header.Set("Origin", c.origin) | |
| 275 | 删除: request.Header.Set("Content-Type", "application/json") | |
| 276 | 删除: // Pin the local workload even if an older combined workbench has selected | |
| 277 | 删除: // a remote host. The gateway rejects a mismatched generation instead of | |
| 278 | 删除: // forwarding this request to whatever host happens to be selected. | |
| 279 | 删除: request.Header.Set(connectionHeader, "local") | |
| 280 | 删除: response, err := c.client.Do(request) | |
| 281 | 删除: if err != nil { | |
| 282 | 删除: return nil, &AgentError{Code: "outcome_unknown", Message: "The request was interrupted. Inspect status before retrying a mutation.", NextAction: "status"} | |
| 283 | 删除: } | |
| 284 | 删除: defer response.Body.Close() | |
| 285 | 删除: data, err := io.ReadAll(io.LimitReader(response.Body, (2<<20)+1)) | |
| 286 | 删除: if err != nil || len(data) > 2<<20 { | |
| 287 | 删除: return nil, &AgentError{Code: "invalid_response", Message: "Could not read a bounded controller response. Inspect status before retrying.", NextAction: "status"} | |
| 288 | 删除: } | |
| 289 | 删除: if response.StatusCode != http.StatusOK { | |
| 290 | 删除: e := agentHTTPError(response.StatusCode) | |
| 291 | 删除: // Production handlers can include file paths or subscription failures; | |
| 292 | 删除: // use the existing diagnostic scrubber before exposing their explanation. | |
| 293 | 删除: e.Message += " " + agentRedact(strings.TrimSpace(string(data))) | |
| 294 | 删除: return nil, e | |
| 295 | 删除: } | |
| 296 | 删除: if !json.Valid(data) { | |
| 297 | 删除: return nil, &AgentError{Code: "invalid_response", Message: "Controller returned invalid JSON.", NextAction: "doctor"} | |
| 298 | 删除: } | |
| 299 | 删除: return json.RawMessage(agentRedact(string(data))), nil | |
| 285 | 新增: response, err := AgentRequest(ctx, configPath, AgentTarget{}, method, path, strings.NewReader(string(input)), "application/json", "") | |
| 286 | 新增: return response.Data, err | |
| 300 | 287 | } |
| 301 | 288 | |
| 302 | 删除:func (s *Server) agentRoutes(mux *http.ServeMux) { | |
| 289 | 新增:func (s *Server) agentRoutes(mux routeRegistrar) { | |
| 303 | 290 | mux.HandleFunc("GET /api/agent/jobs/{id}", func(w http.ResponseWriter, r *http.Request) { |
| 304 | 291 | job := s.jobs.snapshot() |
| 305 | 292 | if job.ID == "" || job.ID != r.PathValue("id") { |
| @@ -346,6 +333,19 @@ func (s *Server) agentSettings(w http.ResponseWriter, r *http.Request) { | ||
| 346 | 333 | if !readJSON(w, r, &in) { |
| 347 | 334 | return |
| 348 | 335 | } |
| 336 | 新增: if home, ok := in.Patch["browser_home_url"]; ok && !in.DryRun { | |
| 337 | 新增: if len(in.Patch) != 1 { | |
| 338 | 新增: http.Error(w, "Change browser_home_url through browser.preferences.set separately from environment settings", 400) | |
| 339 | 新增: return | |
| 340 | 新增: } | |
| 341 | 新增: var value string | |
| 342 | 新增: if json.Unmarshal(home, &value) != nil { | |
| 343 | 新增: http.Error(w, "Invalid browser_home_url", 400) | |
| 344 | 新增: return | |
| 345 | 新增: } | |
| 346 | 新增: s.saveBrowserHome(w, r, value) | |
| 347 | 新增: return | |
| 348 | 新增: } | |
| 349 | 349 | if len(in.Patch) == 0 { |
| 350 | 350 | http.Error(w, "patch must contain at least one setting", 400) |
| 351 | 351 | return |
| @@ -371,6 +371,9 @@ func (s *Server) agentSettings(w http.ResponseWriter, r *http.Request) { | ||
| 371 | 371 | if d.Decode(&input) != nil { |
| 372 | 372 | return savedProfile{}, errors.New("unknown setting or invalid value") |
| 373 | 373 | } |
| 374 | 新增: if _, err := validateBrowserHome(input.BrowserHomeURL); err != nil { | |
| 375 | 新增: return savedProfile{}, err | |
| 376 | 新增: } | |
| 374 | 377 | c, p, err := proposedSettings(input, old, s.profile) |
| 375 | 378 | return savedProfile{Config: c, Preferences: p}, err |
| 376 | 379 | } |
| @@ -418,3 +421,42 @@ func mergeAgentSettings(current, patch map[string]json.RawMessage) error { | ||
| 418 | 421 | } |
| 419 | 422 | return nil |
| 420 | 423 | } |
| 424 | 新增: | |
| 425 | 新增:func agentSchema(t reflect.Type) map[string]any { | |
| 426 | 新增: for t.Kind() == reflect.Pointer { | |
| 427 | 新增: t = t.Elem() | |
| 428 | 新增: } | |
| 429 | 新增: switch t.Kind() { | |
| 430 | 新增: case reflect.Struct: | |
| 431 | 新增: properties := map[string]any{} | |
| 432 | 新增: for i := 0; i < t.NumField(); i++ { | |
| 433 | 新增: f := t.Field(i) | |
| 434 | 新增: if f.PkgPath != "" { | |
| 435 | 新增: continue | |
| 436 | 新增: } | |
| 437 | 新增: if f.Anonymous { | |
| 438 | 新增: for name, schema := range agentSchema(f.Type)["properties"].(map[string]any) { | |
| 439 | 新增: properties[name] = schema | |
| 440 | 新增: } | |
| 441 | 新增: continue | |
| 442 | 新增: } | |
| 443 | 新增: name := strings.Split(f.Tag.Get("json"), ",")[0] | |
| 444 | 新增: if name != "" && name != "-" { | |
| 445 | 新增: properties[name] = agentSchema(f.Type) | |
| 446 | 新增: } | |
| 447 | 新增: } | |
| 448 | 新增: return map[string]any{"type": "object", "properties": properties, "additionalProperties": false} | |
| 449 | 新增: case reflect.Map: | |
| 450 | 新增: return map[string]any{"type": "object", "additionalProperties": agentSchema(t.Elem())} | |
| 451 | 新增: case reflect.Slice, reflect.Array: | |
| 452 | 新增: return map[string]any{"type": "array", "items": agentSchema(t.Elem())} | |
| 453 | 新增: case reflect.Bool: | |
| 454 | 新增: return map[string]any{"type": "boolean"} | |
| 455 | 新增: case reflect.Int, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint32, reflect.Uint64: | |
| 456 | 新增: return map[string]any{"type": "integer"} | |
| 457 | 新增: case reflect.Float32, reflect.Float64: | |
| 458 | 新增: return map[string]any{"type": "number"} | |
| 459 | 新增: default: | |
| 460 | 新增: return map[string]any{"type": "string"} | |
| 461 | 新增: } | |
| 462 | 新增:} | |
| @@ -0,0 +1,208 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "sync" | |
| 7 | 新增: "time" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:type agentNativeItem struct { | |
| 11 | 新增: ID string `json:"id"` | |
| 12 | 新增: Connection string `json:"connection_id"` | |
| 13 | 新增: Request json.RawMessage `json:"request,omitempty"` | |
| 14 | 新增: Status string `json:"status"` | |
| 15 | 新增: Result json.RawMessage `json:"result,omitempty"` | |
| 16 | 新增: Error string `json:"error,omitempty"` | |
| 17 | 新增: created time.Time | |
| 18 | 新增:} | |
| 19 | 新增:type agentNativeQueue struct { | |
| 20 | 新增: mu sync.Mutex | |
| 21 | 新增: items []*agentNativeItem | |
| 22 | 新增: windows map[string]time.Time | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:// This queue belongs to the window listener, not the selected workload. It | |
| 26 | 新增:// invokes the exact installed native bridge, including its platform checks. | |
| 27 | 新增:func (s *Server) agentNativeRoutes(mux routeRegistrar) { | |
| 28 | 新增: mux.HandleFunc("GET /api/agent/native", s.agentNative) | |
| 29 | 新增: mux.HandleFunc("POST /api/agent/native", s.agentNative) | |
| 30 | 新增: mux.HandleFunc("POST /api/agent/native/window", s.agentNativeWindow) | |
| 31 | 新增: mux.HandleFunc("GET /api/agent/native/{id}", s.agentNative) | |
| 32 | 新增: mux.HandleFunc("POST /api/agent/native/{id}/complete", s.agentNative) | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func (s *Server) agentNative(w http.ResponseWriter, r *http.Request) { | |
| 36 | 新增: q := &s.agentNativeQueue | |
| 37 | 新增: id := r.PathValue("id") | |
| 38 | 新增: if r.Method == "POST" && id == "" { | |
| 39 | 新增: if !s.hasTrustedView(r) { | |
| 40 | 新增: http.Error(w, "Native submission requires the local launcher", 403) | |
| 41 | 新增: return | |
| 42 | 新增: } | |
| 43 | 新增: var in struct { | |
| 44 | 新增: Request json.RawMessage `json:"request"` | |
| 45 | 新增: Connection string `json:"connection_id"` | |
| 46 | 新增: } | |
| 47 | 新增: if !readJSON(w, r, &in, 12<<20) { | |
| 48 | 新增: return | |
| 49 | 新增: } | |
| 50 | 新增: var request map[string]json.RawMessage | |
| 51 | 新增: if json.Unmarshal(in.Request, &request) != nil || request == nil || in.Connection == "" { | |
| 52 | 新增: http.Error(w, "Native request and explicit connection_id required", 400) | |
| 53 | 新增: return | |
| 54 | 新增: } | |
| 55 | 新增: var action string | |
| 56 | 新增: _ = json.Unmarshal(request["action"], &action) | |
| 57 | 新增: if action == "" { | |
| 58 | 新增: http.Error(w, "Native action required", 400) | |
| 59 | 新增: return | |
| 60 | 新增: } | |
| 61 | 新增: if s.remote != nil && s.remote.context().ConnectionID != in.Connection { | |
| 62 | 新增: http.Error(w, "Connection changed", 409) | |
| 63 | 新增: return | |
| 64 | 新增: } | |
| 65 | 新增: q.mu.Lock() | |
| 66 | 新增: defer q.mu.Unlock() | |
| 67 | 新增: now := time.Now() | |
| 68 | 新增: kept := q.items[:0] | |
| 69 | 新增: for _, item := range q.items { | |
| 70 | 新增: if item.Status == "pending" && now.Sub(item.created) > 2*time.Minute { | |
| 71 | 新增: item.Status = "failed" | |
| 72 | 新增: item.Error = "Desktop did not claim this request in time. No native action was executed." | |
| 73 | 新增: item.Request = nil | |
| 74 | 新增: } | |
| 75 | 新增: if now.Sub(item.created) < 30*time.Minute { | |
| 76 | 新增: kept = append(kept, item) | |
| 77 | 新增: } | |
| 78 | 新增: } | |
| 79 | 新增: q.items = kept | |
| 80 | 新增: if len(q.items) >= 32 { | |
| 81 | 新增: for i, item := range q.items { | |
| 82 | 新增: if item.Status == "completed" || item.Status == "failed" { | |
| 83 | 新增: q.items = append(q.items[:i], q.items[i+1:]...) | |
| 84 | 新增: break | |
| 85 | 新增: } | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增: if len(q.items) >= 32 { | |
| 89 | 新增: http.Error(w, "Read or finish outstanding native requests before submitting more", 409) | |
| 90 | 新增: return | |
| 91 | 新增: } | |
| 92 | 新增: item := &agentNativeItem{ID: randomToken()[:24], Request: append(json.RawMessage(nil), in.Request...), Connection: in.Connection, Status: "pending", created: now} | |
| 93 | 新增: q.items = append(q.items, item) | |
| 94 | 新增: w.WriteHeader(http.StatusAccepted) | |
| 95 | 新增: jsonReply(w, item) | |
| 96 | 新增: return | |
| 97 | 新增: } | |
| 98 | 新增: q.mu.Lock() | |
| 99 | 新增: defer q.mu.Unlock() | |
| 100 | 新增: if (r.Method == "GET" && id == "") || r.Method == "POST" { | |
| 101 | 新增: until, ok := q.windows[r.Header.Get("X-Cage-Agent-Window")] | |
| 102 | 新增: if !ok || time.Now().After(until) { | |
| 103 | 新增: http.Error(w, "Native window proof required", 403) | |
| 104 | 新增: return | |
| 105 | 新增: } | |
| 106 | 新增: } | |
| 107 | 新增: if r.Method == "GET" && id == "" { | |
| 108 | 新增: if r.URL.Query().Get("consumer") != "window" { | |
| 109 | 新增: http.Error(w, "Window consumer required", 400) | |
| 110 | 新增: return | |
| 111 | 新增: } | |
| 112 | 新增: for _, item := range q.items { | |
| 113 | 新增: if item.Status == "pending" && item.Connection == requestConnection(r) { | |
| 114 | 新增: if time.Since(item.created) > 2*time.Minute { | |
| 115 | 新增: item.Status = "failed" | |
| 116 | 新增: item.Error = "Desktop did not claim this request in time. No native action was executed." | |
| 117 | 新增: item.Request = nil | |
| 118 | 新增: continue | |
| 119 | 新增: } | |
| 120 | 新增: item.Status = "running" | |
| 121 | 新增: jsonReply(w, item) | |
| 122 | 新增: return | |
| 123 | 新增: } | |
| 124 | 新增: } | |
| 125 | 新增: jsonReply(w, map[string]any{}) | |
| 126 | 新增: return | |
| 127 | 新增: } | |
| 128 | 新增: for _, item := range q.items { | |
| 129 | 新增: if item.ID == id { | |
| 130 | 新增: if item.Status == "pending" && time.Since(item.created) > 2*time.Minute { | |
| 131 | 新增: item.Status = "failed" | |
| 132 | 新增: item.Error = "Desktop did not claim this request in time. No native action was executed." | |
| 133 | 新增: item.Request = nil | |
| 134 | 新增: } | |
| 135 | 新增: if r.Method == "POST" { | |
| 136 | 新增: if item.Status == "completed" || item.Status == "failed" { | |
| 137 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 138 | 新增: return | |
| 139 | 新增: } | |
| 140 | 新增: if item.Status != "running" { | |
| 141 | 新增: http.Error(w, "Native request was not claimed", 409) | |
| 142 | 新增: return | |
| 143 | 新增: } | |
| 144 | 新增: var in struct { | |
| 145 | 新增: Result json.RawMessage `json:"result"` | |
| 146 | 新增: Error string `json:"error"` | |
| 147 | 新增: } | |
| 148 | 新增: if !readJSON(w, r, &in, 30<<20) { | |
| 149 | 新增: return | |
| 150 | 新增: } | |
| 151 | 新增: item.Result = in.Result | |
| 152 | 新增: item.Error = in.Error | |
| 153 | 新增: item.Request = nil | |
| 154 | 新增: item.Status = "completed" | |
| 155 | 新增: if in.Error != "" { | |
| 156 | 新增: item.Status = "failed" | |
| 157 | 新增: } | |
| 158 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 159 | 新增: return | |
| 160 | 新增: } | |
| 161 | 新增: if !s.hasTrustedView(r) { | |
| 162 | 新增: http.Error(w, "Native results require the local launcher", 403) | |
| 163 | 新增: return | |
| 164 | 新增: } | |
| 165 | 新增: jsonReply(w, item) | |
| 166 | 新增: return | |
| 167 | 新增: } | |
| 168 | 新增: } | |
| 169 | 新增: http.Error(w, "Native request unavailable; inspect state before repeating it", 410) | |
| 170 | 新增:} | |
| 171 | 新增: | |
| 172 | 新增:func (s *Server) agentNativeWindow(w http.ResponseWriter, r *http.Request) { | |
| 173 | 新增: var in struct { | |
| 174 | 新增: Ticket string `json:"ticket"` | |
| 175 | 新增: } | |
| 176 | 新增: if !readJSON(w, r, &in) { | |
| 177 | 新增: return | |
| 178 | 新增: } | |
| 179 | 新增: if !s.consumeTicket(in.Ticket) { | |
| 180 | 新增: http.Error(w, "A fresh native launch ticket is required", 403) | |
| 181 | 新增: return | |
| 182 | 新增: } | |
| 183 | 新增: q := &s.agentNativeQueue | |
| 184 | 新增: q.mu.Lock() | |
| 185 | 新增: defer q.mu.Unlock() | |
| 186 | 新增: if q.windows == nil { | |
| 187 | 新增: q.windows = map[string]time.Time{} | |
| 188 | 新增: } | |
| 189 | 新增: now := time.Now() | |
| 190 | 新增: for proof, until := range q.windows { | |
| 191 | 新增: if now.After(until) { | |
| 192 | 新增: delete(q.windows, proof) | |
| 193 | 新增: } | |
| 194 | 新增: } | |
| 195 | 新增: if len(q.windows) >= 64 { | |
| 196 | 新增: var oldest string | |
| 197 | 新增: var earliest time.Time | |
| 198 | 新增: for proof, until := range q.windows { | |
| 199 | 新增: if oldest == "" || until.Before(earliest) { | |
| 200 | 新增: oldest, earliest = proof, until | |
| 201 | 新增: } | |
| 202 | 新增: } | |
| 203 | 新增: delete(q.windows, oldest) | |
| 204 | 新增: } | |
| 205 | 新增: proof := randomToken() | |
| 206 | 新增: q.windows[proof] = now.Add(12 * time.Hour) | |
| 207 | 新增: jsonReply(w, map[string]string{"window_proof": proof}) | |
| 208 | 新增:} | |
| @@ -0,0 +1,391 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "reflect" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "testing" | |
| 14 | 新增: "time" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func parityJSON(t *testing.T, value any) []byte { | |
| 18 | 新增: t.Helper() | |
| 19 | 新增: body, err := json.Marshal(value) | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: return body | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func parityUI(t *testing.T, s *Server, method, path string, value any, status int) []byte { | |
| 27 | 新增: t.Helper() | |
| 28 | 新增: body := "" | |
| 29 | 新增: if value != nil { | |
| 30 | 新增: body = string(parityJSON(t, value)) | |
| 31 | 新增: } | |
| 32 | 新增: response := request(s, method, path, s.origin, body, true) | |
| 33 | 新增: if response.Code != status { | |
| 34 | 新增: t.Fatalf("UI %s %s: HTTP %d: %s", method, path, response.Code, response.Body.String()) | |
| 35 | 新增: } | |
| 36 | 新增: return response.Body.Bytes() | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func parityAgent(t *testing.T, s *Server, method, path string, value any, status int) []byte { | |
| 40 | 新增: t.Helper() | |
| 41 | 新增: var input io.Reader | |
| 42 | 新增: if value != nil { | |
| 43 | 新增: input = strings.NewReader(string(parityJSON(t, value))) | |
| 44 | 新增: } | |
| 45 | 新增: response, err := AgentRequest(context.Background(), s.configPath, AgentTarget{Scope: "local"}, method, path, input, "application/json", "") | |
| 46 | 新增: if response.HTTPStatus != status { | |
| 47 | 新增: t.Fatalf("Agent %s %s: HTTP %d, error %v", method, path, response.HTTPStatus, err) | |
| 48 | 新增: } | |
| 49 | 新增: if status == http.StatusOK && err != nil { | |
| 50 | 新增: t.Fatalf("Agent %s %s: %v", method, path, err) | |
| 51 | 新增: } | |
| 52 | 新增: if status >= 400 && err == nil { | |
| 53 | 新增: t.Fatalf("Agent reported success for HTTP %d", status) | |
| 54 | 新增: } | |
| 55 | 新增: return response.Data | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 58 | 新增:func parityDecode[T any](t *testing.T, body []byte) T { | |
| 59 | 新增: t.Helper() | |
| 60 | 新增: var value T | |
| 61 | 新增: if err := json.Unmarshal(body, &value); err != nil { | |
| 62 | 新增: t.Fatalf("decode: %v: %s", err, body) | |
| 63 | 新增: } | |
| 64 | 新增: return value | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func parityAccount(t *testing.T, s *Server) { | |
| 68 | 新增: t.Helper() | |
| 69 | 新增: s.account.lock() | |
| 70 | 新增: a, err := loadLocalAccount(s.profile) | |
| 71 | 新增: if err != nil { | |
| 72 | 新增: t.Fatal(err) | |
| 73 | 新增: } | |
| 74 | 新增: if err := a.create("Parity account", "parity-old-password", ""); err != nil { | |
| 75 | 新增: t.Fatal(err) | |
| 76 | 新增: } | |
| 77 | 新增: s.account = a | |
| 78 | 新增: t.Cleanup(a.lock) | |
| 79 | 新增:} | |
| 80 | 新增: | |
| 81 | 新增:func TestAgentParityAccountProfilePasswordAndLock(t *testing.T) { | |
| 82 | 新增: s := agentTestController(t) | |
| 83 | 新增: parityAccount(t, s) | |
| 84 | 新增: parityUI(t, s, "POST", "/api/account/profile", map[string]any{"username": "From UI", "avatar": ""}, 200) | |
| 85 | 新增: view := parityDecode[accountView](t, parityAgent(t, s, "GET", "/api/account", nil, 200)) | |
| 86 | 新增: if view.Username != "From UI" { | |
| 87 | 新增: t.Fatal("Agent did not read UI profile", view.Username) | |
| 88 | 新增: } | |
| 89 | 新增: data, err := AgentCall(context.Background(), s.configPath, "account.profile", parityJSON(t, map[string]any{"username": "From Agent", "avatar": ""})) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: t.Fatal(err) | |
| 92 | 新增: } | |
| 93 | 新增: if parityDecode[accountView](t, data).Username != "From Agent" { | |
| 94 | 新增: t.Fatal("Agent profile not confirmed") | |
| 95 | 新增: } | |
| 96 | 新增: view = parityDecode[accountView](t, parityUI(t, s, "GET", "/api/account", nil, 200)) | |
| 97 | 新增: if view.Username != "From Agent" { | |
| 98 | 新增: t.Fatal("UI did not read Agent profile") | |
| 99 | 新增: } | |
| 100 | 新增: stored, err := loadLocalAccount(s.profile) | |
| 101 | 新增: if err != nil { | |
| 102 | 新增: t.Fatal(err) | |
| 103 | 新增: } | |
| 104 | 新增: if stored.view().Username != "From Agent" { | |
| 105 | 新增: t.Fatal("profile success preceded persistence") | |
| 106 | 新增: } | |
| 107 | 新增: before, err := os.ReadFile(s.account.path) | |
| 108 | 新增: if err != nil { | |
| 109 | 新增: t.Fatal(err) | |
| 110 | 新增: } | |
| 111 | 新增: wrong := map[string]any{"old_password": "wrong", "password": "parity-new-password", "confirm_password": "parity-new-password"} | |
| 112 | 新增: parityAgent(t, s, "POST", "/api/account/password", wrong, 400) | |
| 113 | 新增: s.account.mu.Lock() | |
| 114 | 新增: s.account.nextAttempt = time.Time{} | |
| 115 | 新增: s.account.mu.Unlock() | |
| 116 | 新增: parityUI(t, s, "POST", "/api/account/password", wrong, 400) | |
| 117 | 新增: s.account.mu.Lock() | |
| 118 | 新增: s.account.nextAttempt = time.Time{} | |
| 119 | 新增: s.account.mu.Unlock() | |
| 120 | 新增: after, _ := os.ReadFile(s.account.path) | |
| 121 | 新增: if string(before) != string(after) { | |
| 122 | 新增: t.Fatal("rejected password change modified account") | |
| 123 | 新增: } | |
| 124 | 新增: parityAgent(t, s, "POST", "/api/account/password", map[string]any{"old_password": "parity-old-password", "password": "parity-new-password", "confirm_password": "parity-new-password"}, 200) | |
| 125 | 新增: parityUI(t, s, "POST", "/api/account/lock", map[string]any{}, 200) | |
| 126 | 新增: parityAgent(t, s, "GET", "/api/settings", nil, 423) | |
| 127 | 新增: parityUI(t, s, "GET", "/api/settings", nil, 423) | |
| 128 | 新增: parityUI(t, s, "POST", "/api/account/unlock", map[string]any{"password": "parity-old-password"}, 400) | |
| 129 | 新增: s.account.mu.Lock() | |
| 130 | 新增: s.account.nextAttempt = time.Time{} | |
| 131 | 新增: s.account.mu.Unlock() | |
| 132 | 新增: parityAgent(t, s, "POST", "/api/account/unlock", map[string]any{"password": "parity-new-password"}, 200) | |
| 133 | 新增: parityAgent(t, s, "POST", "/api/account/lock", map[string]any{}, 200) | |
| 134 | 新增: parityUI(t, s, "GET", "/api/settings", nil, 423) | |
| 135 | 新增: parityUI(t, s, "POST", "/api/account/unlock", map[string]any{"password": "parity-new-password"}, 200) | |
| 136 | 新增: stored, err = loadLocalAccount(s.profile) | |
| 137 | 新增: if err != nil { | |
| 138 | 新增: t.Fatal(err) | |
| 139 | 新增: } | |
| 140 | 新增: defer stored.lock() | |
| 141 | 新增: if err := stored.unlock("parity-new-password"); err != nil { | |
| 142 | 新增: t.Fatal("password update did not survive reload", err) | |
| 143 | 新增: } | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:func TestAgentParityAppearanceNestedValuesAndFavorites(t *testing.T) { | |
| 147 | 新增: s := agentTestController(t) | |
| 148 | 新增: appearance := defaultAppearance() | |
| 149 | 新增: appearance.Mode = "dark" | |
| 150 | 新增: appearance.UIFontSize = 18 | |
| 151 | 新增: appearance.Dark.Colors = map[string]string{"sidebar": "#123456", "focus": "#abcdef"} | |
| 152 | 新增: appearance.Dark.Terminal = map[string]string{"background": "#101010", "brightRed": "#ee1111"} | |
| 153 | 新增: appearance.CustomThemes = []SavedAppearanceTheme{{ID: "parity", Name: "Saved by UI", Light: appearance.Light, Dark: appearance.Dark}} | |
| 154 | 新增: parityUI(t, s, "POST", "/api/appearance", appearance, 200) | |
| 155 | 新增: read := parityDecode[Appearance](t, parityAgent(t, s, "GET", "/api/appearance", nil, 200)) | |
| 156 | 新增: if !reflect.DeepEqual(appearance, read) { | |
| 157 | 新增: t.Fatalf("Agent lost nested appearance values: %+v", read) | |
| 158 | 新增: } | |
| 159 | 新增: read.CustomThemes[0].Name = "Renamed by Agent" | |
| 160 | 新增: read.CodeFontSize = 17 | |
| 161 | 新增: read.Dark.Fonts.Code = "JetBrains Mono" | |
| 162 | 新增: data, err := AgentCall(context.Background(), s.configPath, "appearance.set", parityJSON(t, read)) | |
| 163 | 新增: if err != nil { | |
| 164 | 新增: t.Fatal(err) | |
| 165 | 新增: } | |
| 166 | 新增: if !reflect.DeepEqual(read, parityDecode[Appearance](t, data)) { | |
| 167 | 新增: t.Fatal("Agent appearance confirmation differs") | |
| 168 | 新增: } | |
| 169 | 新增: if !reflect.DeepEqual(read, parityDecode[Appearance](t, parityUI(t, s, "GET", "/api/appearance", nil, 200))) { | |
| 170 | 新增: t.Fatal("UI cannot see saved Agent appearance") | |
| 171 | 新增: } | |
| 172 | 新增: file, err := os.ReadFile(filepath.Join(s.profile, "appearance.json")) | |
| 173 | 新增: if err != nil { | |
| 174 | 新增: t.Fatal(err) | |
| 175 | 新增: } | |
| 176 | 新增: if !reflect.DeepEqual(read, parityDecode[Appearance](t, file)) { | |
| 177 | 新增: t.Fatal("appearance not durable") | |
| 178 | 新增: } | |
| 179 | 新增: folders := parityDecode[Favorites](t, parityUI(t, s, "POST", "/api/favorites", map[string]any{"action": "save_folder", "title": "UI folder"}, 200)) | |
| 180 | 新增: if len(folders.Folders) != 1 { | |
| 181 | 新增: t.Fatal("missing saved folder") | |
| 182 | 新增: } | |
| 183 | 新增: data, err = AgentCall(context.Background(), s.configPath, "favorites.change", parityJSON(t, map[string]any{"action": "save", "title": "Agent bookmark", "url": "https://example.test/path?q=one", "folder_id": folders.Folders[0].ID})) | |
| 184 | 新增: if err != nil { | |
| 185 | 新增: t.Fatal(err) | |
| 186 | 新增: } | |
| 187 | 新增: favorites := parityDecode[Favorites](t, data) | |
| 188 | 新增: if len(favorites.Items) != 1 || favorites.Items[0].FolderID != folders.Folders[0].ID { | |
| 189 | 新增: t.Fatal("Agent failed to use UI-created folder") | |
| 190 | 新增: } | |
| 191 | 新增: parityUI(t, s, "POST", "/api/favorites", map[string]any{"action": "save", "id": favorites.Items[0].ID, "title": "UI rename", "url": favorites.Items[0].URL, "folder_id": ""}, 200) | |
| 192 | 新增: favorites = parityDecode[Favorites](t, parityAgent(t, s, "GET", "/api/favorites", nil, 200)) | |
| 193 | 新增: if favorites.Items[0].Title != "UI rename" || favorites.Items[0].FolderID != "" { | |
| 194 | 新增: t.Fatal("Agent lost latest UI bookmark metadata") | |
| 195 | 新增: } | |
| 196 | 新增: file, err = os.ReadFile(filepath.Join(s.profile, "favorites.json")) | |
| 197 | 新增: if err != nil { | |
| 198 | 新增: t.Fatal(err) | |
| 199 | 新增: } | |
| 200 | 新增: if !reflect.DeepEqual(favorites, parityDecode[Favorites](t, file)) { | |
| 201 | 新增: t.Fatal("favorites not durable") | |
| 202 | 新增: } | |
| 203 | 新增: parityAgent(t, s, "POST", "/api/account/lock", map[string]any{}, 200) | |
| 204 | 新增: parityAgent(t, s, "POST", "/api/appearance", appearance, 423) | |
| 205 | 新增: parityUI(t, s, "POST", "/api/appearance", appearance, 423) | |
| 206 | 新增: parityAgent(t, s, "GET", "/api/favorites", nil, 423) | |
| 207 | 新增: parityUI(t, s, "GET", "/api/favorites", nil, 423) | |
| 208 | 新增:} | |
| 209 | 新增: | |
| 210 | 新增:func TestAgentParityVaultMetadataAndReauthentication(t *testing.T) { | |
| 211 | 新增: s := agentTestController(t) | |
| 212 | 新增: parityAccount(t, s) | |
| 213 | 新增: const secret = "parity-website-secret-should-not-be-redacted" | |
| 214 | 新增: entry := map[string]any{"origin": "https://vault.example.test/login", "username": "[email protected]", "password": secret} | |
| 215 | 新增: parityUI(t, s, "POST", "/api/vault", map[string]any{"action": "save", "entry": entry}, 200) | |
| 216 | 新增: listBody := parityAgent(t, s, "GET", "/api/vault", nil, 200) | |
| 217 | 新增: if strings.Contains(string(listBody), secret) { | |
| 218 | 新增: t.Fatal("ordinary Agent list leaked password") | |
| 219 | 新增: } | |
| 220 | 新增: list := parityDecode[vaultData](t, listBody) | |
| 221 | 新增: if len(list.Entries) != 1 || list.Entries[0].Origin != "https://vault.example.test" || list.Entries[0].Username != "[email protected]" { | |
| 222 | 新增: t.Fatal("Agent cannot discover UI record", string(listBody)) | |
| 223 | 新增: } | |
| 224 | 新增: id := list.Entries[0].ID | |
| 225 | 新增: reveal := map[string]any{"action": "reveal", "id": id, "account_password": "parity-old-password"} | |
| 226 | 新增: result, err := AgentCall(context.Background(), s.configPath, "vault.change", parityJSON(t, reveal)) | |
| 227 | 新增: if err != nil { | |
| 228 | 新增: t.Fatal(err) | |
| 229 | 新增: } | |
| 230 | 新增: if parityDecode[struct { | |
| 231 | 新增: Password string `json:"password"` | |
| 232 | 新增: }](t, result).Password != secret { | |
| 233 | 新增: t.Fatal("explicit authenticated reveal was redacted") | |
| 234 | 新增: } | |
| 235 | 新增: wrong := map[string]any{"action": "reveal", "id": id, "account_password": "wrong"} | |
| 236 | 新增: parityAgent(t, s, "POST", "/api/vault", wrong, 400) | |
| 237 | 新增: s.account.mu.Lock() | |
| 238 | 新增: s.account.nextAttempt = time.Time{} | |
| 239 | 新增: s.account.mu.Unlock() | |
| 240 | 新增: parityUI(t, s, "POST", "/api/vault", wrong, 400) | |
| 241 | 新增: s.account.mu.Lock() | |
| 242 | 新增: s.account.nextAttempt = time.Time{} | |
| 243 | 新增: s.account.mu.Unlock() | |
| 244 | 新增: parityAgent(t, s, "POST", "/api/vault", map[string]any{"action": "save", "entry": map[string]any{"id": id, "origin": "https://vault.example.test", "username": "changed-by-agent", "password": ""}}, 200) | |
| 245 | 新增: if parityDecode[struct { | |
| 246 | 新增: Password string `json:"password"` | |
| 247 | 新增: }](t, parityUI(t, s, "POST", "/api/vault", reveal, 200)).Password != secret { | |
| 248 | 新增: t.Fatal("Agent metadata edit erased password") | |
| 249 | 新增: } | |
| 250 | 新增: list = parityDecode[vaultData](t, parityUI(t, s, "GET", "/api/vault", nil, 200)) | |
| 251 | 新增: if list.Entries[0].Username != "changed-by-agent" { | |
| 252 | 新增: t.Fatal("UI missed Agent edit") | |
| 253 | 新增: } | |
| 254 | 新增: file, err := os.ReadFile(filepath.Join(s.profile, "password-vault.json")) | |
| 255 | 新增: if err != nil { | |
| 256 | 新增: t.Fatal(err) | |
| 257 | 新增: } | |
| 258 | 新增: if strings.Contains(string(file), secret) || strings.Contains(string(file), "changed-by-agent") { | |
| 259 | 新增: t.Fatal("vault persisted plaintext") | |
| 260 | 新增: } | |
| 261 | 新增: parityAgent(t, s, "POST", "/api/account/lock", map[string]any{}, 200) | |
| 262 | 新增: parityAgent(t, s, "POST", "/api/vault", reveal, 423) | |
| 263 | 新增: parityUI(t, s, "POST", "/api/vault", reveal, 423) | |
| 264 | 新增:} | |
| 265 | 新增: | |
| 266 | 新增:func TestAgentParityBrowserHomeFailureAndLength(t *testing.T) { | |
| 267 | 新增: s := agentTestController(t) | |
| 268 | 新增: s.preferences.BrowserHomeURL = "https://old.example.test/" | |
| 269 | 新增: s.preferences.ClaudeTerminalCommand = "claude --continue" | |
| 270 | 新增: if err := writePrivate(filepath.Join(s.profile, "workbench.json"), s.preferences); err != nil { | |
| 271 | 新增: t.Fatal(err) | |
| 272 | 新增: } | |
| 273 | 新增: before, err := os.ReadFile(filepath.Join(s.profile, "workbench.json")) | |
| 274 | 新增: if err != nil { | |
| 275 | 新增: t.Fatal(err) | |
| 276 | 新增: } | |
| 277 | 新增: s.ready = true | |
| 278 | 新增: guestCalls := 0 | |
| 279 | 新增: s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 280 | 新增: guestCalls++ | |
| 281 | 新增: if r.URL.Path != "/homepage" { | |
| 282 | 新增: t.Fatal("unexpected guest lifecycle operation", r.URL.Path) | |
| 283 | 新增: } | |
| 284 | 新增: return nil, errors.New("simulated offline guest transport") | |
| 285 | 新增: })) | |
| 286 | 新增: const replacement = "https://new.example.test/" | |
| 287 | 新增: parityUI(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": replacement}, 400) | |
| 288 | 新增: _, err = AgentCall(context.Background(), s.configPath, "settings.patch", parityJSON(t, map[string]any{"patch": map[string]any{"browser_home_url": replacement}})) | |
| 289 | 新增: if err == nil { | |
| 290 | 新增: t.Fatal("Agent accepted homepage runtime failure") | |
| 291 | 新增: } | |
| 292 | 新增: if guestCalls != 2 { | |
| 293 | 新增: t.Fatal("both entry points must reach the live browser", guestCalls) | |
| 294 | 新增: } | |
| 295 | 新增: after, _ := os.ReadFile(filepath.Join(s.profile, "workbench.json")) | |
| 296 | 新增: if string(before) != string(after) || s.preferences.BrowserHomeURL != "https://old.example.test/" { | |
| 297 | 新增: t.Fatal("failed update changed persisted or visible homepage") | |
| 298 | 新增: } | |
| 299 | 新增: tooLong := "https://example.test/" + strings.Repeat("a", 8192) | |
| 300 | 新增: parityUI(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": tooLong}, 400) | |
| 301 | 新增: parityAgent(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": tooLong}, 400) | |
| 302 | 新增: _, err = AgentCall(context.Background(), s.configPath, "settings.patch", parityJSON(t, map[string]any{"patch": map[string]any{"browser_home_url": tooLong}})) | |
| 303 | 新增: if err == nil { | |
| 304 | 新增: t.Fatal("Agent patch bypassed homepage limit") | |
| 305 | 新增: } | |
| 306 | 新增: if guestCalls != 2 { | |
| 307 | 新增: t.Fatal("invalid homepage reached guest") | |
| 308 | 新增: } | |
| 309 | 新增: s.ready = false | |
| 310 | 新增: parityUI(t, s, "POST", "/api/browser/preferences", map[string]any{"browser_home_url": replacement}, 200) | |
| 311 | 新增: data, err := AgentCall(context.Background(), s.configPath, "browser.preferences.get", nil) | |
| 312 | 新增: if err != nil { | |
| 313 | 新增: t.Fatal(err) | |
| 314 | 新增: } | |
| 315 | 新增: if parityDecode[map[string]string](t, data)["browser_home_url"] != replacement { | |
| 316 | 新增: t.Fatal("Agent cannot read UI homepage") | |
| 317 | 新增: } | |
| 318 | 新增: const final = "https://agent.example.test/" | |
| 319 | 新增: _, err = AgentCall(context.Background(), s.configPath, "settings.patch", parityJSON(t, map[string]any{"patch": map[string]any{"browser_home_url": final}})) | |
| 320 | 新增: if err != nil { | |
| 321 | 新增: t.Fatal(err) | |
| 322 | 新增: } | |
| 323 | 新增: if parityDecode[map[string]string](t, parityUI(t, s, "GET", "/api/browser/preferences", nil, 200))["browser_home_url"] != final { | |
| 324 | 新增: t.Fatal("UI missed Agent homepage") | |
| 325 | 新增: } | |
| 326 | 新增: var saved Preferences | |
| 327 | 新增: body, _ := os.ReadFile(filepath.Join(s.profile, "workbench.json")) | |
| 328 | 新增: _ = json.Unmarshal(body, &saved) | |
| 329 | 新增: if saved.BrowserHomeURL != final || saved.ClaudeTerminalCommand != "claude --continue" { | |
| 330 | 新增: t.Fatal("homepage success discarded unrelated preferences", saved) | |
| 331 | 新增: } | |
| 332 | 新增:} | |
| 333 | 新增: | |
| 334 | 新增:func TestAgentParityClaudeSchedulingPointerValues(t *testing.T) { | |
| 335 | 新增: s := agentTestController(t) | |
| 336 | 新增: firstID, secondID := strings.Repeat("a", 24), strings.Repeat("b", 24) | |
| 337 | 新增: list := claudeAccountList{Accounts: []claudeAccount{ | |
| 338 | 新增: {ID: firstID, Source: "default", Email: "[email protected]", Label: "First", Enabled: true, HandoffGroup: "shared"}, | |
| 339 | 新增: {ID: secondID, Source: "default", Email: "[email protected]", Label: "Second", Enabled: true, HandoffGroup: "shared"}, | |
| 340 | 新增: }, Scheduling: (claudeScheduling{}).defaults()} | |
| 341 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 342 | 新增: t.Fatal(err) | |
| 343 | 新增: } | |
| 344 | 新增: // UI input explicitly sets a pointer bool false and clears a pointer string. | |
| 345 | 新增: parityUI(t, s, "POST", "/api/claude-accounts", map[string]any{"action": "update", "id": firstID, "enabled": false, "handoff_group": ""}, 200) | |
| 346 | 新增: data, err := AgentCall(context.Background(), s.configPath, "claude-accounts.get", nil) | |
| 347 | 新增: if err != nil { | |
| 348 | 新增: t.Fatal(err) | |
| 349 | 新增: } | |
| 350 | 新增: view := parityDecode[claudePanel](t, data) | |
| 351 | 新增: if view.Accounts[0].Enabled || view.Accounts[0].HandoffGroup != "" { | |
| 352 | 新增: t.Fatal("Agent lost explicit false/empty UI fields") | |
| 353 | 新增: } | |
| 354 | 新增: data, err = AgentCall(context.Background(), s.configPath, "claude-accounts.change", parityJSON(t, map[string]any{"action": "update", "id": firstID, "enabled": true, "handoff_group": "from-agent"})) | |
| 355 | 新增: if err != nil { | |
| 356 | 新增: t.Fatal(err) | |
| 357 | 新增: } | |
| 358 | 新增: view = parityDecode[claudePanel](t, parityUI(t, s, "GET", "/api/claude-accounts", nil, 200)) | |
| 359 | 新增: if !view.Accounts[0].Enabled || view.Accounts[0].HandoffGroup != "from-agent" { | |
| 360 | 新增: t.Fatal("UI missed Agent pointer-field update") | |
| 361 | 新增: } | |
| 362 | 新增: _, err = AgentCall(context.Background(), s.configPath, "claude-accounts.change", parityJSON(t, map[string]any{"action": "scheduling", "scheduling": map[string]any{"mode": "sequential", "switch_policy": "wait"}, "order": []string{secondID, firstID}})) | |
| 363 | 新增: if err != nil { | |
| 364 | 新增: t.Fatal(err) | |
| 365 | 新增: } | |
| 366 | 新增: view = parityDecode[claudePanel](t, parityUI(t, s, "GET", "/api/claude-accounts", nil, 200)) | |
| 367 | 新增: if view.Scheduling.Mode != "sequential" || view.Scheduling.SwitchPolicy != "wait" || view.Accounts[0].ID != secondID { | |
| 368 | 新增: t.Fatal("UI lost nested scheduling or order", view) | |
| 369 | 新增: } | |
| 370 | 新增: stored, err := s.loadClaudeAccounts() | |
| 371 | 新增: if err != nil { | |
| 372 | 新增: t.Fatal(err) | |
| 373 | 新增: } | |
| 374 | 新增: if stored.Scheduling != view.Scheduling || stored.Accounts[0].ID != secondID { | |
| 375 | 新增: t.Fatal("scheduling/order success was not durable") | |
| 376 | 新增: } | |
| 377 | 新增: for _, input := range []map[string]any{ | |
| 378 | 新增: {"action": "update", "id": firstID, "enabled": "false"}, | |
| 379 | 新增: {"action": "scheduling", "scheduling": map[string]any{"mode": "sequential", "switch_policy": "wait", "unknown": true}}, | |
| 380 | 新增: } { | |
| 381 | 新增: body, _ := os.ReadFile(filepath.Join(s.profile, "claude-accounts.json")) | |
| 382 | 新增: if _, err := AgentCall(context.Background(), s.configPath, "claude-accounts.change", parityJSON(t, input)); err == nil { | |
| 383 | 新增: t.Fatal("Agent accepted invalid nested/pointer value", input) | |
| 384 | 新增: } | |
| 385 | 新增: parityUI(t, s, "POST", "/api/claude-accounts", input, 400) | |
| 386 | 新增: after, _ := os.ReadFile(filepath.Join(s.profile, "claude-accounts.json")) | |
| 387 | 新增: if string(body) != string(after) { | |
| 388 | 新增: t.Fatal("invalid scheduling write changed saved registry") | |
| 389 | 新增: } | |
| 390 | 新增: } | |
| 391 | 新增:} | |
| @@ -0,0 +1,27 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net/http" | |
| 5 | 新增: "sort" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:// Keep route discovery attached to the actual registrations. Adding a UI API | |
| 9 | 新增:// automatically makes it visible to an external agent on that same listener. | |
| 10 | 新增:type routeRegistrar interface { | |
| 11 | 新增: HandleFunc(string, func(http.ResponseWriter, *http.Request)) | |
| 12 | 新增:} | |
| 13 | 新增:type discoverableMux struct { | |
| 14 | 新增: *http.ServeMux | |
| 15 | 新增: patterns []string | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:func newDiscoverableMux() *discoverableMux { return &discoverableMux{ServeMux: http.NewServeMux()} } | |
| 19 | 新增:func (m *discoverableMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) { | |
| 20 | 新增: m.patterns = append(m.patterns, pattern) | |
| 21 | 新增: m.ServeMux.HandleFunc(pattern, handler) | |
| 22 | 新增:} | |
| 23 | 新增:func (m *discoverableMux) routes() []string { | |
| 24 | 新增: patterns := append([]string(nil), m.patterns...) | |
| 25 | 新增: sort.Strings(patterns) | |
| 26 | 新增: return patterns | |
| 27 | 新增:} | |
| @@ -0,0 +1,149 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "strings" | |
| 10 | 新增: "sync" | |
| 11 | 新增: "sync/atomic" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/gorilla/websocket" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:// AgentSocket carries the same WebSocket messages as the UI without exporting | |
| 18 | 新增:// session cookies. One NDJSON line in/out is {type:"text"|"binary",data:...}; | |
| 19 | 新增:// binary data uses JSON's []byte base64 encoding. | |
| 20 | 新增:func AgentSocket(ctx context.Context, configPath string, target AgentTarget, path string, input io.ReadCloser, output io.Writer) (returned error) { | |
| 21 | 新增: if !strings.HasPrefix(path, "/api/") || strings.ContainsAny(path, "\r\n\\") || strings.Contains(path, "#") || strings.Contains(path, "://") { | |
| 22 | 新增: return &AgentError{Code: "invalid_input", Message: "Use a relative /api/ WebSocket path", NextAction: "routes"} | |
| 23 | 新增: } | |
| 24 | 新增: c, err := agentConnectTarget(ctx, configPath, target) | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: return err | |
| 27 | 新增: } | |
| 28 | 新增: defer c.close() | |
| 29 | 新增: if target.Scope == "desktop" { | |
| 30 | 新增: return &AgentError{Code: "invalid_input", Message: "Use local or selected scope for a workload WebSocket", NextAction: "client.context"} | |
| 31 | 新增: } | |
| 32 | 新增: if target.Scope == "client" && target.Connection == "" { | |
| 33 | 新增: return &AgentError{Code: "invalid_input", Message: "Client sockets require an explicit connection generation", NextAction: "client.context"} | |
| 34 | 新增: } | |
| 35 | 新增: connection := "local" | |
| 36 | 新增: if target.Connection != "" { | |
| 37 | 新增: connection = target.Connection | |
| 38 | 新增: } | |
| 39 | 新增: req, _ := http.NewRequest("GET", c.origin, nil) | |
| 40 | 新增: headers := http.Header{"Origin": []string{c.origin}, connectionHeader: []string{connection}} | |
| 41 | 新增: for _, cookie := range c.client.Jar.Cookies(req.URL) { | |
| 42 | 新增: headers.Add("Cookie", cookie.String()) | |
| 43 | 新增: } | |
| 44 | 新增: dialer := websocket.Dialer{Proxy: nil, HandshakeTimeout: 15 * time.Second} | |
| 45 | 新增: ws, response, err := dialer.DialContext(ctx, "ws"+strings.TrimPrefix(c.origin, "http")+path, headers) | |
| 46 | 新增: if err != nil { | |
| 47 | 新增: if response != nil { | |
| 48 | 新增: return agentHTTPError(response.StatusCode) | |
| 49 | 新增: } | |
| 50 | 新增: return &AgentError{Code: "connection_failed", Message: "WebSocket connection failed", NextAction: "status"} | |
| 51 | 新增: } | |
| 52 | 新增: defer ws.Close() | |
| 53 | 新增: ws.SetReadLimit(32 << 20) | |
| 54 | 新增: stop := context.AfterFunc(ctx, func() { ws.Close() }) | |
| 55 | 新增: defer stop() | |
| 56 | 新增: type frame struct { | |
| 57 | 新增: Type string `json:"type"` | |
| 58 | 新增: Data json.RawMessage `json:"data"` | |
| 59 | 新增: } | |
| 60 | 新增: var mutex sync.Mutex | |
| 61 | 新增: emit := func(value any) error { | |
| 62 | 新增: mutex.Lock() | |
| 63 | 新增: defer mutex.Unlock() | |
| 64 | 新增: return json.NewEncoder(output).Encode(value) | |
| 65 | 新增: } | |
| 66 | 新增: if err := emit(map[string]any{"protocol": AgentProtocol, "status": "connected"}); err != nil { | |
| 67 | 新增: return err | |
| 68 | 新增: } | |
| 69 | 新增: inputDone := make(chan error, 1) | |
| 70 | 新增: var closing, inputFailed atomic.Bool | |
| 71 | 新增: defer func() { | |
| 72 | 新增: closing.Store(true) | |
| 73 | 新增: input.Close() | |
| 74 | 新增: <-inputDone | |
| 75 | 新增: if inputFailed.Load() { | |
| 76 | 新增: returned = &AgentError{Code: "invalid_input", Message: "Invalid NDJSON WebSocket input; the failed input was not executed", NextAction: "capabilities"} | |
| 77 | 新增: } | |
| 78 | 新增: }() | |
| 79 | 新增: go func() { | |
| 80 | 新增: decoder := json.NewDecoder(input) | |
| 81 | 新增: for { | |
| 82 | 新增: var value frame | |
| 83 | 新增: if err := decoder.Decode(&value); err != nil { | |
| 84 | 新增: if !errors.Is(err, io.EOF) && !closing.Load() { | |
| 85 | 新增: inputFailed.Store(true) | |
| 86 | 新增: ws.Close() | |
| 87 | 新增: } | |
| 88 | 新增: inputDone <- err | |
| 89 | 新增: return | |
| 90 | 新增: } | |
| 91 | 新增: var body []byte | |
| 92 | 新增: kind := websocket.TextMessage | |
| 93 | 新增: switch value.Type { | |
| 94 | 新增: case "text": | |
| 95 | 新增: var text string | |
| 96 | 新增: if json.Unmarshal(value.Data, &text) != nil { | |
| 97 | 新增: inputFailed.Store(true) | |
| 98 | 新增: inputDone <- io.ErrUnexpectedEOF | |
| 99 | 新增: ws.Close() | |
| 100 | 新增: return | |
| 101 | 新增: } | |
| 102 | 新增: body = []byte(text) | |
| 103 | 新增: case "binary": | |
| 104 | 新增: kind = websocket.BinaryMessage | |
| 105 | 新增: if json.Unmarshal(value.Data, &body) != nil { | |
| 106 | 新增: inputFailed.Store(true) | |
| 107 | 新增: inputDone <- io.ErrUnexpectedEOF | |
| 108 | 新增: ws.Close() | |
| 109 | 新增: return | |
| 110 | 新增: } | |
| 111 | 新增: default: | |
| 112 | 新增: inputFailed.Store(true) | |
| 113 | 新增: inputDone <- io.ErrUnexpectedEOF | |
| 114 | 新增: ws.Close() | |
| 115 | 新增: return | |
| 116 | 新增: } | |
| 117 | 新增: ws.SetWriteDeadline(time.Now().Add(30 * time.Second)) | |
| 118 | 新增: if err := ws.WriteMessage(kind, body); err != nil { | |
| 119 | 新增: inputDone <- err | |
| 120 | 新增: ws.Close() | |
| 121 | 新增: return | |
| 122 | 新增: } | |
| 123 | 新增: } | |
| 124 | 新增: }() | |
| 125 | 新增: for { | |
| 126 | 新增: kind, body, err := ws.ReadMessage() | |
| 127 | 新增: if err != nil { | |
| 128 | 新增: if ctx.Err() != nil { | |
| 129 | 新增: return nil | |
| 130 | 新增: } | |
| 131 | 新增: if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) { | |
| 132 | 新增: return nil | |
| 133 | 新增: } | |
| 134 | 新增: return &AgentError{Code: "connection_closed", Message: "WebSocket closed; inspect the original session before reconnecting", NextAction: "status"} | |
| 135 | 新增: } | |
| 136 | 新增: var value any | |
| 137 | 新增: switch kind { | |
| 138 | 新增: case websocket.TextMessage: | |
| 139 | 新增: value = map[string]any{"type": "text", "data": string(body)} | |
| 140 | 新增: case websocket.BinaryMessage: | |
| 141 | 新增: value = map[string]any{"type": "binary", "data": body} | |
| 142 | 新增: default: | |
| 143 | 新增: continue | |
| 144 | 新增: } | |
| 145 | 新增: if err := emit(value); err != nil { | |
| 146 | 新增: return err | |
| 147 | 新增: } | |
| 148 | 新增: } | |
| 149 | 新增:} | |
| @@ -83,14 +83,8 @@ func TestAgentSettingsPatchPreservesOmittedFields(t *testing.T) { | ||
| 83 | 83 | if err != nil { |
| 84 | 84 | t.Fatal(err) |
| 85 | 85 | } |
| 86 | 删除: s.jobs.workers.Wait() | |
| 87 | 删除: job := s.jobs.snapshot() | |
| 88 | 删除: if job.Error != "" { | |
| 89 | 删除: t.Fatal(job.Error) | |
| 90 | 删除: } | |
| 91 | 删除: data, err = AgentJob(context.Background(), s.configPath, job.ID) | |
| 92 | 删除: if err != nil { | |
| 93 | 删除: t.Fatal(err) | |
| 86 | 新增: if !strings.Contains(string(data), "https://example.org/") { | |
| 87 | 新增: t.Fatal("homepage was not confirmed", string(data)) | |
| 94 | 88 | } |
| 95 | 89 | if s.preferences.ClaudeTerminalCommand != "claude --verbose" || s.preferences.BrowserHomeURL != "https://example.org/" { |
| 96 | 90 | t.Fatalf("preferences lost: %+v", s.preferences) |
| @@ -0,0 +1,189 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "net/url" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:// AgentTarget separates the desktop's client configuration from its selected | |
| 19 | 新增:// workload. A selected workload always requires an explicit generation. | |
| 20 | 新增:type AgentTarget struct { | |
| 21 | 新增: Scope string `json:"scope"` | |
| 22 | 新增: Connection string `json:"connection_id,omitempty"` | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:func agentConnectTarget(ctx context.Context, configPath string, target AgentTarget) (*controllerClient, error) { | |
| 26 | 新增: if target.Scope == "" || target.Scope == "local" { | |
| 27 | 新增: return agentConnect(ctx, configPath) | |
| 28 | 新增: } | |
| 29 | 新增: if target.Scope != "desktop" && target.Scope != "selected" && target.Scope != "client" { | |
| 30 | 新增: return nil, &AgentError{Code: "invalid_input", Message: "scope must be local, desktop, selected or client.", NextAction: "capabilities"} | |
| 31 | 新增: } | |
| 32 | 新增: if target.Scope == "selected" && target.Connection == "" { | |
| 33 | 新增: return nil, &AgentError{Code: "invalid_input", Message: "selected scope requires --connection from client.context.", NextAction: "client.context"} | |
| 34 | 新增: } | |
| 35 | 新增: path := desktopConfigPath(configPath) | |
| 36 | 新增: if target.Scope == "client" { | |
| 37 | 新增: path = configPath | |
| 38 | 新增: } | |
| 39 | 新增: c, err := connectController(filepath.Dir(path)) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: return nil, &AgentError{Code: "service_unavailable", Message: "Open the Cage desktop before managing client configuration.", NextAction: "open_desktop"} | |
| 42 | 新增: } | |
| 43 | 新增: want, err := currentController() | |
| 44 | 新增: if err != nil || !want.matches(c.launch.Controller) || (target.Scope != "client" && !c.launch.DesktopGateway) || (target.Scope == "client" && !c.launch.ClientOnly) || filepath.Clean(c.launch.ConfigPath) != filepath.Clean(path) { | |
| 45 | 新增: c.close() | |
| 46 | 新增: return nil, &AgentError{Code: "controller_mismatch", Message: "The desktop controller does not match this CLI and configuration.", NextAction: "open_desktop"} | |
| 47 | 新增: } | |
| 48 | 新增: u, _ := url.Parse(c.launch.URL) | |
| 49 | 新增: code, err := c.callContext(ctx, "POST", "/api/session", map[string]string{"token": u.Fragment}, nil) | |
| 50 | 新增: if err != nil || code != 200 { | |
| 51 | 新增: c.close() | |
| 52 | 新增: return nil, agentHTTPError(401) | |
| 53 | 新增: } | |
| 54 | 新增: c.client.Jar.SetCookies(u, []*http.Cookie{{Name: cookieName + "_" + u.Port() + "-desktop", Value: trustedViewProof(c.record.Token), Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode}}) | |
| 55 | 新增: return c, nil | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 58 | 新增:type AgentResponse struct { | |
| 59 | 新增: HTTPStatus int `json:"http_status"` | |
| 60 | 新增: ContentType string `json:"content_type,omitempty"` | |
| 61 | 新增: Recovery string `json:"recovery,omitempty"` | |
| 62 | 新增: Data json.RawMessage `json:"body,omitempty"` | |
| 63 | 新增: Path string `json:"path,omitempty"` | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:// AgentRequest accepts the same HTTP paths and payloads as the workbench. The | |
| 67 | 新增:// URL is relative to an authenticated, pinned controller, never caller-owned. | |
| 68 | 新增:// Binary uploads/downloads use streams; JSON results preserve business values, | |
| 69 | 新增:// including secrets explicitly requested using the UI's reauthentication. | |
| 70 | 新增:func AgentRequest(ctx context.Context, configPath string, target AgentTarget, method, path string, input io.Reader, contentType, output string) (AgentResponse, error) { | |
| 71 | 新增: var result AgentResponse | |
| 72 | 新增: u, err := url.Parse(path) | |
| 73 | 新增: if err != nil || u.IsAbs() || u.Host != "" || !strings.HasPrefix(u.Path, "/api/") || u.Fragment != "" || strings.ContainsAny(path, "\r\n\\") || strings.Contains(u.Path, "//") || strings.Contains(u.Path, "/../") { | |
| 74 | 新增: return result, &AgentError{Code: "invalid_input", Message: "Use a relative /api/ path without a host, fragment or traversal.", NextAction: "capabilities"} | |
| 75 | 新增: } | |
| 76 | 新增: switch method { | |
| 77 | 新增: case "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD": | |
| 78 | 新增: default: | |
| 79 | 新增: return result, &AgentError{Code: "invalid_input", Message: "Unsupported HTTP method.", NextAction: "capabilities"} | |
| 80 | 新增: } | |
| 81 | 新增: // These endpoints are internal transports, not user actions. Device | |
| 82 | 新增: // enrollment/unlock must run inside the same native credential store and | |
| 83 | 新增: // biometric policy as the desktop; never return its wrapping secret. | |
| 84 | 新增: if u.Path == "/api/agent/native/window" || u.Path == "/api/account/device-enroll" || u.Path == "/api/account/device-unlock" || u.Path == "/api/account/device-revoke" || u.Path == "/api/session" || u.Path == "/api/launch" || u.Path == "/api/handoff" || u.Path == "/api/desktop-owner" || strings.HasPrefix(u.Path, "/api/desktop-local/") { | |
| 85 | 新增: return result, &AgentError{Code: "native_transport_required", Message: "Use native.submit with the same accountDevice or desktop action. Transport credentials are not exported.", NextAction: "native.submit"} | |
| 86 | 新增: } | |
| 87 | 新增: // Client-only operations must address the desktop explicitly. Ordinary | |
| 88 | 新增: // business routes on that listener require the selected target's generation. | |
| 89 | 新增: clientPath := strings.HasPrefix(u.Path, "/api/client/") || strings.HasPrefix(u.Path, "/api/agent/native") || u.Path == "/api/agent/routes" | |
| 90 | 新增: if target.Scope == "client" && !clientPath && target.Connection == "" { | |
| 91 | 新增: return result, &AgentError{Code: "invalid_input", Message: "Client workload requests require the explicit selected --connection", NextAction: "client.context"} | |
| 92 | 新增: } | |
| 93 | 新增: if target.Scope == "desktop" && !clientPath { | |
| 94 | 新增: return result, &AgentError{Code: "invalid_input", Message: "Use selected scope with --connection for workload requests through the desktop.", NextAction: "client.context"} | |
| 95 | 新增: } | |
| 96 | 新增: if output != "" { | |
| 97 | 新增: if !filepath.IsAbs(output) { | |
| 98 | 新增: return result, &AgentError{Code: "invalid_input", Message: "output must be an absolute new file path", NextAction: "capabilities"} | |
| 99 | 新增: } | |
| 100 | 新增: if _, err := os.Lstat(output); !os.IsNotExist(err) { | |
| 101 | 新增: return result, &AgentError{Code: "invalid_input", Message: "Existing output files are preserved", NextAction: "capabilities"} | |
| 102 | 新增: } | |
| 103 | 新增: } | |
| 104 | 新增: c, err := agentConnectTarget(ctx, configPath, target) | |
| 105 | 新增: if err != nil { | |
| 106 | 新增: return result, err | |
| 107 | 新增: } | |
| 108 | 新增: defer c.close() | |
| 109 | 新增: c.client.Timeout = 2 * time.Minute | |
| 110 | 新增: req, err := http.NewRequestWithContext(ctx, method, c.origin+path, input) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: return result, err | |
| 113 | 新增: } | |
| 114 | 新增: req.Header.Set("Origin", c.origin) | |
| 115 | 新增: if contentType != "" { | |
| 116 | 新增: req.Header.Set("Content-Type", contentType) | |
| 117 | 新增: } | |
| 118 | 新增: connection := "local" | |
| 119 | 新增: if target.Connection != "" { | |
| 120 | 新增: connection = target.Connection | |
| 121 | 新增: } | |
| 122 | 新增: req.Header.Set(connectionHeader, connection) | |
| 123 | 新增: response, err := c.client.Do(req) | |
| 124 | 新增: if err != nil { | |
| 125 | 新增: return result, &AgentError{Code: "outcome_unknown", Message: "The request was interrupted. Inspect the original target before repeating a mutation.", NextAction: "status"} | |
| 126 | 新增: } | |
| 127 | 新增: defer response.Body.Close() | |
| 128 | 新增: result.HTTPStatus = response.StatusCode | |
| 129 | 新增: result.ContentType = response.Header.Get("Content-Type") | |
| 130 | 新增: result.Recovery = response.Header.Get("X-Cage-Recovery") | |
| 131 | 新增: if response.StatusCode < 200 || response.StatusCode >= 300 { | |
| 132 | 新增: body, _ := io.ReadAll(io.LimitReader(response.Body, 64<<10)) | |
| 133 | 新增: e := agentHTTPError(response.StatusCode) | |
| 134 | 新增: e.Message += " " + agentRedact(strings.TrimSpace(string(body))) | |
| 135 | 新增: return result, e | |
| 136 | 新增: } | |
| 137 | 新增: if output != "" { | |
| 138 | 新增: if !filepath.IsAbs(output) { | |
| 139 | 新增: return result, &AgentError{Code: "invalid_input", Message: "output must be an absolute new file path.", NextAction: "capabilities"} | |
| 140 | 新增: } | |
| 141 | 新增: f, err := os.CreateTemp(filepath.Dir(output), ".cage-agent-response-*") | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: return result, err | |
| 144 | 新增: } | |
| 145 | 新增: defer os.Remove(f.Name()) | |
| 146 | 新增: if err := host.ProtectFile(f.Name()); err != nil { | |
| 147 | 新增: f.Close() | |
| 148 | 新增: return result, err | |
| 149 | 新增: } | |
| 150 | 新增: _, copyErr := io.Copy(f, response.Body) | |
| 151 | 新增: err = errors.Join(copyErr, f.Sync(), f.Close()) | |
| 152 | 新增: if err != nil { | |
| 153 | 新增: return result, err | |
| 154 | 新增: } | |
| 155 | 新增: if err = os.Link(f.Name(), output); err != nil { | |
| 156 | 新增: return result, err | |
| 157 | 新增: } | |
| 158 | 新增: result.Path = output | |
| 159 | 新增: return result, nil | |
| 160 | 新增: } | |
| 161 | 新增: if response.StatusCode == 204 || method == "HEAD" { | |
| 162 | 新增: return result, nil | |
| 163 | 新增: } | |
| 164 | 新增: data, err := io.ReadAll(io.LimitReader(response.Body, (32<<20)+1)) | |
| 165 | 新增: if err != nil || len(data) > 32<<20 { | |
| 166 | 新增: return result, &AgentError{Code: "invalid_response", Message: "Response exceeds 32 MiB or was interrupted; use --output for a file response.", NextAction: "status"} | |
| 167 | 新增: } | |
| 168 | 新增: if !json.Valid(data) { | |
| 169 | 新增: return result, &AgentError{Code: "output_required", Message: "This response is not JSON. Use --output with a new absolute file path for binary or streaming content.", NextAction: "capabilities"} | |
| 170 | 新增: } | |
| 171 | 新增: result.Data = data | |
| 172 | 新增: return result, nil | |
| 173 | 新增:} | |
| 174 | 新增: | |
| 175 | 新增:func AgentCallTarget(ctx context.Context, configPath string, target AgentTarget, operation string, input json.RawMessage) (json.RawMessage, error) { | |
| 176 | 新增: for _, op := range AgentOperations() { | |
| 177 | 新增: if op.Name == operation { | |
| 178 | 新增: if err := agentValidateInput(input, op.InputSchema); err != nil { | |
| 179 | 新增: return nil, err | |
| 180 | 新增: } | |
| 181 | 新增: if len(input) == 0 { | |
| 182 | 新增: input = json.RawMessage(`{}`) | |
| 183 | 新增: } | |
| 184 | 新增: result, err := AgentRequest(ctx, configPath, target, op.method, op.path, strings.NewReader(string(input)), "application/json", "") | |
| 185 | 新增: return result.Data, err | |
| 186 | 新增: } | |
| 187 | 新增: } | |
| 188 | 新增: return nil, &AgentError{Code: "unknown_operation", Message: "Unknown operation. Read capabilities or use request for an existing UI endpoint.", NextAction: "capabilities"} | |
| 189 | 新增:} | |
| @@ -0,0 +1,312 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "net/http/httptest" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "testing" | |
| 14 | 新增: "time" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func TestAgentRoutesComeFromTheActualListener(t *testing.T) { | |
| 18 | 新增: s := agentTestController(t) | |
| 19 | 新增: response, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/agent/routes", nil, "", "") | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: var routes []string | |
| 24 | 新增: _ = json.Unmarshal(response.Data, &routes) | |
| 25 | 新增: for _, pattern := range []string{"POST /api/agent/native", "POST /api/browser/extensions/upload", "POST /api/account/{action}", "GET /api/proxy"} { | |
| 26 | 新增: found := false | |
| 27 | 新增: for _, route := range routes { | |
| 28 | 新增: found = found || route == pattern | |
| 29 | 新增: } | |
| 30 | 新增: if !found { | |
| 31 | 新增: t.Fatal("missing registered UI route", pattern) | |
| 32 | 新增: } | |
| 33 | 新增: } | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:func TestAgentRawInputAndBinaryOutputUseProductionHandler(t *testing.T) { | |
| 37 | 新增: s := agentTestController(t) | |
| 38 | 新增: s.ready = true | |
| 39 | 新增: var received string | |
| 40 | 新增: s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 41 | 新增: body := make([]byte, 4) | |
| 42 | 新增: _, _ = r.Body.Read(body) | |
| 43 | 新增: received = string(body) | |
| 44 | 新增: return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"upload":"accepted"}`))}, nil | |
| 45 | 新增: })) | |
| 46 | 新增: // Existing UI upload boundary validates and forwards the binary archive. | |
| 47 | 新增: upload, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "POST", "/api/browser/extensions/upload", strings.NewReader("ZIP!"), "application/octet-stream", "") | |
| 48 | 新增: if err != nil || !strings.Contains(string(upload.Data), "accepted") { | |
| 49 | 新增: t.Fatal(upload, err) | |
| 50 | 新增: } | |
| 51 | 新增: if received != "ZIP!" { | |
| 52 | 新增: t.Fatal("raw upload never reached production receiver", err, received) | |
| 53 | 新增: } | |
| 54 | 新增: path := filepath.Join(t.TempDir(), "bundle.zip") | |
| 55 | 新增: result, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/diagnostics/export", nil, "", path) | |
| 56 | 新增: if err != nil || result.Path != path { | |
| 57 | 新增: t.Fatal(result, err) | |
| 58 | 新增: } | |
| 59 | 新增: before, err := os.ReadFile(path) | |
| 60 | 新增: if err != nil || len(before) < 2 || string(before[:2]) != "PK" { | |
| 61 | 新增: t.Fatal("not a real diagnostic ZIP", err) | |
| 62 | 新增: } | |
| 63 | 新增: _, err = AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/diagnostics/export", nil, "", path) | |
| 64 | 新增: if err == nil { | |
| 65 | 新增: t.Fatal("existing output replaced") | |
| 66 | 新增: } | |
| 67 | 新增: after, _ := os.ReadFile(path) | |
| 68 | 新增: if string(after) != string(before) { | |
| 69 | 新增: t.Fatal("original output changed") | |
| 70 | 新增: } | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:func TestAgentNativeQueueClaimsOnceAndKeepsReceipts(t *testing.T) { | |
| 74 | 新增: s := agentTestController(t) | |
| 75 | 新增: s.account.lock() // Native account unlock must be reachable from the lock screen. | |
| 76 | 新增: if w := request(s, "POST", "/api/agent/native", s.origin, `{"connection_id":"local","request":{"action":"accountDevice"}}`, true); w.Code != 403 { | |
| 77 | 新增: t.Fatal("submission lacked launcher proof", w.Code) | |
| 78 | 新增: } | |
| 79 | 新增: data, err := AgentCall(context.Background(), s.configPath, "native.submit", json.RawMessage(`{"connection_id":"local","request":{"action":"accountDevice","operation":"status"}}`)) | |
| 80 | 新增: if err != nil { | |
| 81 | 新增: t.Fatal(err) | |
| 82 | 新增: } | |
| 83 | 新增: var item agentNativeItem | |
| 84 | 新增: _ = json.Unmarshal(data, &item) | |
| 85 | 新增: if item.Status != "pending" { | |
| 86 | 新增: t.Fatal(string(data)) | |
| 87 | 新增: } | |
| 88 | 新增: if w := request(s, "GET", "/api/agent/native?consumer=window", "", "", true); w.Code != 403 { | |
| 89 | 新增: t.Fatal("ordinary session could claim native request", w.Code) | |
| 90 | 新增: } | |
| 91 | 新增: ticket := s.issueTicket() | |
| 92 | 新增: registered := request(s, "POST", "/api/agent/native/window", s.origin, `{"ticket":"`+ticket+`"}`, true) | |
| 93 | 新增: var grant struct { | |
| 94 | 新增: Proof string `json:"window_proof"` | |
| 95 | 新增: } | |
| 96 | 新增: _ = json.Unmarshal(registered.Body.Bytes(), &grant) | |
| 97 | 新增: if registered.Code != 200 || len(grant.Proof) != 64 { | |
| 98 | 新增: t.Fatal("native ticket was not exchanged", registered.Code) | |
| 99 | 新增: } | |
| 100 | 新增: if replay := request(s, "POST", "/api/agent/native/window", s.origin, `{"ticket":"`+ticket+`"}`, true); replay.Code != 403 { | |
| 101 | 新增: t.Fatal("native ticket replay accepted") | |
| 102 | 新增: } | |
| 103 | 新增: claim := func(connection string) *httptest.ResponseRecorder { | |
| 104 | 新增: r := httptest.NewRequest("GET", s.origin+"/api/agent/native?consumer=window", nil) | |
| 105 | 新增: r.Header.Set(connectionHeader, connection) | |
| 106 | 新增: r.Header.Set("X-Cage-Agent-Window", grant.Proof) | |
| 107 | 新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) | |
| 108 | 新增: w := httptest.NewRecorder() | |
| 109 | 新增: s.handler().ServeHTTP(w, r) | |
| 110 | 新增: return w | |
| 111 | 新增: } | |
| 112 | 新增: if w := claim("old-generation"); strings.Contains(w.Body.String(), item.ID) { | |
| 113 | 新增: t.Fatal("wrong window claimed action") | |
| 114 | 新增: } | |
| 115 | 新增: if w := claim("local"); !strings.Contains(w.Body.String(), item.ID) { | |
| 116 | 新增: t.Fatal("correct window cannot claim", w.Code, w.Body.String()) | |
| 117 | 新增: } | |
| 118 | 新增: if w := claim("local"); strings.Contains(w.Body.String(), item.ID) { | |
| 119 | 新增: t.Fatal("native operation replayed") | |
| 120 | 新增: } | |
| 121 | 新增: complete := "/api/agent/native/" + item.ID + "/complete" | |
| 122 | 新增: for _, body := range []string{`{"result":{"supported":false}}`, `{"result":{"supported":true}}`} { | |
| 123 | 新增: if denied := request(s, "POST", complete, s.origin, body, true); denied.Code != 403 { | |
| 124 | 新增: t.Fatal("ordinary session forged native completion") | |
| 125 | 新增: } | |
| 126 | 新增: r := httptest.NewRequest("POST", s.origin+complete, strings.NewReader(body)) | |
| 127 | 新增: r.Header.Set("Origin", s.origin) | |
| 128 | 新增: r.Header.Set("Content-Type", "application/json") | |
| 129 | 新增: r.Header.Set("X-Cage-Agent-Window", grant.Proof) | |
| 130 | 新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) | |
| 131 | 新增: w := httptest.NewRecorder() | |
| 132 | 新增: s.handler().ServeHTTP(w, r) | |
| 133 | 新增: if w.Code != 200 { | |
| 134 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 135 | 新增: } | |
| 136 | 新增: } | |
| 137 | 新增: result, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/agent/native/"+item.ID, nil, "", "") | |
| 138 | 新增: if err != nil { | |
| 139 | 新增: t.Fatal(err) | |
| 140 | 新增: } | |
| 141 | 新增: if !strings.Contains(string(result.Data), `"supported":false`) { | |
| 142 | 新增: t.Fatal("repeated completion changed original result", string(result.Data)) | |
| 143 | 新增: } | |
| 144 | 新增: if w := request(s, "GET", "/api/agent/native/"+item.ID, "", "", true); w.Code != 403 { | |
| 145 | 新增: t.Fatal("untrusted view read native secret") | |
| 146 | 新增: } | |
| 147 | 新增:} | |
| 148 | 新增: | |
| 149 | 新增:func TestAgentDesktopConfigurationUsesExplicitSelection(t *testing.T) { | |
| 150 | 新增: full := filepath.Join(t.TempDir(), "config.json") | |
| 151 | 新增: s := agentTestController(t) | |
| 152 | 新增: // Reuse this production listener under the actual desktop-entry location. | |
| 153 | 新增: s.desktopEntry = true | |
| 154 | 新增: endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { jsonReply(w, map[string]bool{"ok": true}) })) | |
| 155 | 新增: t.Cleanup(endpoint.Close) | |
| 156 | 新增: s.remote = newDesktopGateway(s.profile, &gatewayLocalFixture{endpoint: endpoint, status: DesktopLocalStatus{Known: true}}) | |
| 157 | 新增: t.Cleanup(s.remote.close) | |
| 158 | 新增: path := desktopConfigPath(full) | |
| 159 | 新增: if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { | |
| 160 | 新增: t.Fatal(err) | |
| 161 | 新增: } | |
| 162 | 新增: record, err := os.ReadFile(filepath.Join(s.profile, "control.json")) | |
| 163 | 新增: if err != nil { | |
| 164 | 新增: t.Fatal(err) | |
| 165 | 新增: } | |
| 166 | 新增: if err := os.WriteFile(filepath.Join(filepath.Dir(path), "control.json"), record, 0600); err != nil { | |
| 167 | 新增: t.Fatal(err) | |
| 168 | 新增: } | |
| 169 | 新增: lock, err := openControllerLock(filepath.Dir(path), os.O_CREATE|os.O_RDWR) | |
| 170 | 新增: if err != nil { | |
| 171 | 新增: t.Fatal(err) | |
| 172 | 新增: } | |
| 173 | 新增: if err := lockController(lock); err != nil { | |
| 174 | 新增: t.Fatal(err) | |
| 175 | 新增: } | |
| 176 | 新增: defer func() { unlockController(lock); lock.Close() }() | |
| 177 | 新增: s.configPath = path | |
| 178 | 新增: target := AgentTarget{Scope: "desktop"} | |
| 179 | 新增: result, err := AgentRequest(context.Background(), full, target, "GET", "/api/client/context", nil, "", "") | |
| 180 | 新增: if err != nil { | |
| 181 | 新增: t.Fatal(err) | |
| 182 | 新增: } | |
| 183 | 新增: var current ClientContext | |
| 184 | 新增: _ = json.Unmarshal(result.Data, ¤t) | |
| 185 | 新增: if !current.DesktopGateway || current.ConnectionID == "" { | |
| 186 | 新增: t.Fatal(string(result.Data)) | |
| 187 | 新增: } | |
| 188 | 新增: body := `{"name":"test host","host":"127.0.0.1","port":22,"user":"qa","auth":{"kind":"agent"}}` | |
| 189 | 新增: result, err = AgentRequest(context.Background(), full, target, "POST", "/api/client/hosts", strings.NewReader(body), "application/json", "") | |
| 190 | 新增: if err != nil { | |
| 191 | 新增: t.Fatal(err) | |
| 192 | 新增: } | |
| 193 | 新增: if result.HTTPStatus != 200 || !strings.Contains(string(result.Data), "test host") { | |
| 194 | 新增: t.Fatal(string(result.Data)) | |
| 195 | 新增: } | |
| 196 | 新增: _, err = AgentRequest(context.Background(), full, target, "POST", "/api/stop", strings.NewReader(`{}`), "application/json", "") | |
| 197 | 新增: var ae *AgentError | |
| 198 | 新增: if !errors.As(err, &ae) || ae.Code != "invalid_input" { | |
| 199 | 新增: t.Fatal("implicit target accepted", err) | |
| 200 | 新增: } | |
| 201 | 新增: _, err = AgentRequest(context.Background(), full, AgentTarget{Scope: "selected", Connection: "old"}, "POST", "/api/stop", strings.NewReader(`{}`), "application/json", "") | |
| 202 | 新增: if !errors.As(err, &ae) || ae.Code != "state_conflict" { | |
| 203 | 新增: t.Fatal("stale target accepted", err) | |
| 204 | 新增: } | |
| 205 | 新增: // A real candidate creation returns 202. The HTTP adapter must preserve it. | |
| 206 | 新增: result, err = AgentRequest(context.Background(), full, target, "POST", "/api/client/candidate", strings.NewReader(`{"mode":"local","connection_id":"`+current.ConnectionID+`"}`), "application/json", "") | |
| 207 | 新增: if err != nil || result.HTTPStatus != 202 { | |
| 208 | 新增: t.Fatalf("candidate 202 rejected: %+v %v", result, err) | |
| 209 | 新增: } | |
| 210 | 新增:} | |
| 211 | 新增: | |
| 212 | 新增:func TestAgentSocketUsesTheSameTerminalAndAccountLock(t *testing.T) { | |
| 213 | 新增: s := agentTestController(t) | |
| 214 | 新增: t.Cleanup(s.terminals.close) | |
| 215 | 新增: session, err := s.terminals.start(terminalChildCommand("echo"), "/project", "shell") | |
| 216 | 新增: if err != nil { | |
| 217 | 新增: t.Fatal(err) | |
| 218 | 新增: } | |
| 219 | 新增: input, writer := io.Pipe() | |
| 220 | 新增: output, reader := io.Pipe() | |
| 221 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
| 222 | 新增: defer cancel() | |
| 223 | 新增: done := make(chan error, 1) | |
| 224 | 新增: go func() { | |
| 225 | 新增: err := AgentSocket(ctx, s.configPath, AgentTarget{}, "/api/terminals/"+session.id+"/stream", input, reader) | |
| 226 | 新增: reader.Close() | |
| 227 | 新增: done <- err | |
| 228 | 新增: }() | |
| 229 | 新增: type frame struct { | |
| 230 | 新增: Status string `json:"status"` | |
| 231 | 新增: Type string `json:"type"` | |
| 232 | 新增: Data json.RawMessage `json:"data"` | |
| 233 | 新增: } | |
| 234 | 新增: decoder := json.NewDecoder(output) | |
| 235 | 新增: var connected frame | |
| 236 | 新增: if err := decoder.Decode(&connected); err != nil || connected.Status != "connected" { | |
| 237 | 新增: t.Fatal(connected, err) | |
| 238 | 新增: } | |
| 239 | 新增: payload, _ := json.Marshal(map[string]any{"type": "input", "data": terminalInputLine("agent-socket-parity")}) | |
| 240 | 新增: if err := json.NewEncoder(writer).Encode(map[string]any{"type": "text", "data": string(payload)}); err != nil { | |
| 241 | 新增: t.Fatal(err) | |
| 242 | 新增: } | |
| 243 | 新增: var captured strings.Builder | |
| 244 | 新增: for !strings.Contains(captured.String(), "child:agent-socket-parity") { | |
| 245 | 新增: var item frame | |
| 246 | 新增: if err := decoder.Decode(&item); err != nil { | |
| 247 | 新增: t.Fatal(err, captured.String()) | |
| 248 | 新增: } | |
| 249 | 新增: if item.Type == "binary" { | |
| 250 | 新增: var data []byte | |
| 251 | 新增: _ = json.Unmarshal(item.Data, &data) | |
| 252 | 新增: captured.Write(data) | |
| 253 | 新增: } | |
| 254 | 新增: } | |
| 255 | 新增: cancel() | |
| 256 | 新增: writer.Close() | |
| 257 | 新增: output.Close() | |
| 258 | 新增: if err := <-done; err != nil { | |
| 259 | 新增: t.Fatal(err) | |
| 260 | 新增: } | |
| 261 | 新增: s.account.lock() | |
| 262 | 新增: if err := AgentSocket(context.Background(), s.configPath, AgentTarget{}, "/api/terminals/"+session.id+"/stream", io.NopCloser(strings.NewReader("")), io.Discard); err == nil { | |
| 263 | 新增: t.Fatal("locked account retained terminal access") | |
| 264 | 新增: } | |
| 265 | 新增:} | |
| 266 | 新增: | |
| 267 | 新增:func TestAgentHostGitUsesSameExplicitConsentAndPreservesConfig(t *testing.T) { | |
| 268 | 新增: path := isolatedGitConfig(t) | |
| 269 | 新增: s := agentTestController(t) | |
| 270 | 新增: if _, err := AgentCall(context.Background(), s.configPath, "host.git.enable", json.RawMessage(`{}`)); err == nil { | |
| 271 | 新增: t.Fatal("missing explicit consent accepted") | |
| 272 | 新增: } | |
| 273 | 新增: _, err := AgentCall(context.Background(), s.configPath, "host.git.enable", json.RawMessage(`{"confirm":true}`)) | |
| 274 | 新增: if err != nil { | |
| 275 | 新增: t.Fatal(err) | |
| 276 | 新增: } | |
| 277 | 新增: body, err := os.ReadFile(path) | |
| 278 | 新增: if err != nil || !strings.Contains(string(body), "bareRepository = explicit") || !strings.Contains(string(body), "name = Cage Test") { | |
| 279 | 新增: t.Fatal("real Git config not preserved", err, string(body)) | |
| 280 | 新增: } | |
| 281 | 新增: ui := request(s, "GET", "/api/host/git", "", "", true) | |
| 282 | 新增: if !strings.Contains(ui.Body.String(), `"ready":true`) { | |
| 283 | 新增: t.Fatal(ui.Body.String()) | |
| 284 | 新增: } | |
| 285 | 新增:} | |
| 286 | 新增: | |
| 287 | 新增:func TestAgentDoesNotExportNativeDeviceWrappingCredentials(t *testing.T) { | |
| 288 | 新增: for _, path := range []string{"/api/agent/native/window", "/api/account/device-enroll", "/api/account/device-unlock", "/api/account/device-revoke", "/api/launch", "/api/session", "/api/desktop-local/trusted-login"} { | |
| 289 | 新增: _, err := AgentRequest(context.Background(), filepath.Join(t.TempDir(), "config.json"), AgentTarget{}, "POST", path, strings.NewReader(`{}`), "application/json", "") | |
| 290 | 新增: var ae *AgentError | |
| 291 | 新增: if !errors.As(err, &ae) || ae.Code != "native_transport_required" { | |
| 292 | 新增: t.Fatal(path, err) | |
| 293 | 新增: } | |
| 294 | 新增: } | |
| 295 | 新增:} | |
| 296 | 新增: | |
| 297 | 新增:func TestAgentSocketRejectsMalformedInputWithoutWaitingForRemote(t *testing.T) { | |
| 298 | 新增: s := agentTestController(t) | |
| 299 | 新增: t.Cleanup(s.terminals.close) | |
| 300 | 新增: session, err := s.terminals.start(terminalChildCommand("echo"), "/project", "shell") | |
| 301 | 新增: if err != nil { | |
| 302 | 新增: t.Fatal(err) | |
| 303 | 新增: } | |
| 304 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 305 | 新增: defer cancel() | |
| 306 | 新增: started := time.Now() | |
| 307 | 新增: err = AgentSocket(ctx, s.configPath, AgentTarget{}, "/api/terminals/"+session.id+"/stream", io.NopCloser(strings.NewReader("malformed JSON")), io.Discard) | |
| 308 | 新增: var ae *AgentError | |
| 309 | 新增: if !errors.As(err, &ae) || ae.Code != "invalid_input" || time.Since(started) > time.Second { | |
| 310 | 新增: t.Fatal("malformed input hung or was reported as success", err) | |
| 311 | 新增: } | |
| 312 | 新增:} | |
| @@ -24,10 +24,22 @@ func (s *Server) browserPreferences(w http.ResponseWriter, r *http.Request) { | ||
| 24 | 24 | if !readJSON(w, r, &input) { |
| 25 | 25 | return |
| 26 | 26 | } |
| 27 | 删除: home := strings.TrimSpace(input.Home) | |
| 27 | 新增: s.saveBrowserHome(w, r, input.Home) | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:func validateBrowserHome(value string) (string, error) { | |
| 31 | 新增: home := strings.TrimSpace(value) | |
| 28 | 32 | parsed, err := url.Parse(home) |
| 29 | 33 | if err != nil || len(home) > 8192 || parsed == nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.Hostname() == "" || parsed.User != nil { |
| 30 | 删除: requestError(w, errors.New("新标签页地址必须是完整的 HTTP 或 HTTPS 网址,且不能包含用户名或密码")) | |
| 34 | 新增: return "", errors.New("新标签页地址必须是完整的 HTTP 或 HTTPS 网址,且不能包含用户名或密码") | |
| 35 | 新增: } | |
| 36 | 新增: return home, nil | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func (s *Server) saveBrowserHome(w http.ResponseWriter, r *http.Request, value string) { | |
| 40 | 新增: home, err := validateBrowserHome(value) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: requestError(w, err) | |
| 31 | 43 | return |
| 32 | 44 | } |
| 33 | 45 | if !s.op.TryLock() { |
| @@ -63,7 +63,7 @@ func (s *Server) macBrowserExchange(ctx context.Context, request macBrowserReque | ||
| 63 | 63 | return client.request(ctx, "POST", "/"+action, request) |
| 64 | 64 | } |
| 65 | 65 | |
| 66 | 删除:func (s *Server) registerMacOSBrowserRoutes(mux *http.ServeMux) { | |
| 66 | 新增:func (s *Server) registerMacOSBrowserRoutes(mux routeRegistrar) { | |
| 67 | 67 | mux.HandleFunc("POST /api/macos-browser/action", func(w http.ResponseWriter, r *http.Request) { |
| 68 | 68 | if s.macosGuest == nil { |
| 69 | 69 | http.NotFound(w, r) |
| @@ -15,7 +15,7 @@ const macOSWindowSocketCommand = `exec /usr/bin/nc -U "$HOME/Library/Caches/dev. | ||
| 15 | 15 | |
| 16 | 16 | // The native trial has a dedicated standard-user SSH identity. The guest GUI |
| 17 | 17 | // agent accepts only Claude operations on its protected per-user Unix socket. |
| 18 | 删除:func (s *Server) registerMacOSClaudeRoutes(mux *http.ServeMux) { | |
| 18 | 新增:func (s *Server) registerMacOSClaudeRoutes(mux routeRegistrar) { | |
| 19 | 19 | mux.HandleFunc("POST /api/macos/claude/window", s.macOSClaudeWindow) |
| 20 | 20 | mux.HandleFunc("GET /api/macos/claude/connection", s.macOSWindowConnection) |
| 21 | 21 | mux.HandleFunc("GET /api/macos/claude/frames", s.macOSWindowFrames) |
| @@ -50,7 +50,7 @@ func (p *mobilePairing) pairedRequestLocked(r *http.Request) bool { | ||
| 50 | 50 | return p.roomCtx != nil && p.roomCtx.Err() == nil && p.roomProof != "" && equalSecret(p.roomProof, r.Header.Get(mobilelink.PhoneRoomHeader)) |
| 51 | 51 | } |
| 52 | 52 | |
| 53 | 删除:func (s *Server) mobileSurfaceRoutes(mux *http.ServeMux) { | |
| 53 | 新增:func (s *Server) mobileSurfaceRoutes(mux routeRegistrar) { | |
| 54 | 54 | mux.HandleFunc("GET /api/mobile/browser/favorites", s.serveFavorites) |
| 55 | 55 | mux.HandleFunc("POST /api/mobile/browser/favorites", s.serveFavorites) |
| 56 | 56 | for _, surface := range []phoneSurface{phoneBrowser, phoneDesktop} { |
| @@ -10,7 +10,7 @@ import ( | ||
| 10 | 10 | "unicode/utf8" |
| 11 | 11 | ) |
| 12 | 12 | |
| 13 | 删除:func (s *Server) mobileCLIRoutes(mux *http.ServeMux) { | |
| 13 | 新增:func (s *Server) mobileCLIRoutes(mux routeRegistrar) { | |
| 14 | 14 | // Desktop history follows the selected local or SSH host. Mobile routes |
| 15 | 15 | // remain pinned to the paired computer by the remote gateway. |
| 16 | 16 | mux.HandleFunc("GET /api/cli/sessions", s.mobileSessions) |
| @@ -9,7 +9,7 @@ func nativeWorkbenchRoute(path string) bool { | ||
| 9 | 9 | return true |
| 10 | 10 | } |
| 11 | 11 | switch path { |
| 12 | 删除: case "/api/agent/settings": | |
| 12 | 新增: case "/api/agent/settings", "/api/agent/routes": | |
| 13 | 13 | return true |
| 14 | 14 | case "/api/account", "/api/session", "/api/launch", "/api/handoff", "/api/remote/manifest", |
| 15 | 15 | "/api/appearance", "/api/favorites", "/api/status", "/api/settings", "/api/settings/probe", |
| @@ -42,6 +42,7 @@ type controlFile struct { | ||
| 42 | 42 | Controller ControllerIdentity `json:"controller"` |
| 43 | 43 | } |
| 44 | 44 | type Server struct { |
| 45 | 新增: agentNativeQueue agentNativeQueue | |
| 45 | 46 | macSetupProjectsChecked time.Time |
| 46 | 47 | macSetupProjectsAttempt time.Time |
| 47 | 48 | macosGuest *guestos.MacOSProfile |
| @@ -311,8 +312,12 @@ func serve(configPath string, clientOnly bool, fullConfigPath string) (returned | ||
| 311 | 312 | return err |
| 312 | 313 | } |
| 313 | 314 | func (s *Server) handler() http.Handler { |
| 314 | 删除: mux := http.NewServeMux() | |
| 315 | 新增: mux := newDiscoverableMux() | |
| 316 | 新增: mux.HandleFunc("GET /api/agent/routes", func(w http.ResponseWriter, r *http.Request) { | |
| 317 | 新增: jsonReply(w, mux.routes()) | |
| 318 | 新增: }) | |
| 315 | 319 | s.agentRoutes(mux) |
| 320 | 新增: s.agentNativeRoutes(mux) | |
| 316 | 321 | s.mobileCLIRoutes(mux) |
| 317 | 322 | s.mobileSurfaceRoutes(mux) |
| 318 | 323 | mux.HandleFunc("GET /api/mobile-pair", s.phoneStatus) |
| @@ -498,6 +503,10 @@ func (s *Server) handler() http.Handler { | ||
| 498 | 503 | return |
| 499 | 504 | } |
| 500 | 505 | } |
| 506 | 新增: if strings.HasPrefix(r.URL.Path, "/api/agent/native") || r.URL.Path == "/api/agent/routes" { | |
| 507 | 新增: mux.ServeHTTP(w, r) | |
| 508 | 新增: return | |
| 509 | 新增: } | |
| 501 | 510 | if s.windowsGuest != nil && !windowsWorkbenchRoute(r.URL.Path) { |
| 502 | 511 | s.windowsUnavailable(w) |
| 503 | 512 | return |
| @@ -36,13 +36,15 @@ try { | ||
| 36 | 36 | assert.equal(call(['call', 'settings.get'], undefined, 3).error.code, 'account_locked'); |
| 37 | 37 | call(['call', 'account.create', '--input', '-'], { username: 'Agent acceptance', password: 'Ephemeral-Test-Password-123!', confirm_password: 'Ephemeral-Test-Password-123!' }); |
| 38 | 38 | const before = call(['call', 'settings.get']).data; |
| 39 | 删除: const patch = { browser_home_url: 'https://example.org/' }; | |
| 39 | 新增: const patch = { balanced_display: !before.balanced_display }; | |
| 40 | 40 | call(['call', 'settings.patch', '--input', '-'], { patch, dry_run: true }); |
| 41 | 41 | assert.deepEqual(call(['call', 'settings.get']).data, before); |
| 42 | 42 | const applied = call(['call', 'settings.patch', '--input', '-', '--wait', '10s'], { patch }); |
| 43 | 43 | assert.equal(applied.status, 'completed'); assert.equal(applied.data.running, false); |
| 44 | 44 | assert.equal(call(['job', applied.data.id]).data.id, applied.data.id); |
| 45 | 删除: assert.equal(call(['call', 'settings.get']).data.browser_home_url, patch.browser_home_url); | |
| 45 | 新增: assert.equal(call(['call', 'settings.get']).data.balanced_display, patch.balanced_display); | |
| 46 | 新增: call(['call','browser.preferences.set','--input','-'],{browser_home_url:'https://example.org/'}); | |
| 47 | 新增: assert.equal(call(['call','settings.get']).data.browser_home_url,'https://example.org/'); | |
| 46 | 48 | const rejected = call(['call', 'settings.patch', '--input', '-'], { patch: { proxy_url: 'socks5://127.0.0.1:1' } }, 1); |
| 47 | 49 | assert.equal(rejected.error.code, 'request_rejected'); |
| 48 | 50 | const proxy = call(['call', 'proxy.status']); |
| @@ -0,0 +1,73 @@ | ||
| 1 | 新增:// Real lightweight client entry point and controller; no remote host connection. | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { spawnSync } from "node:child_process"; | |
| 4 | 新增:import { mkdtemp, readFile, rm, stat } from "node:fs/promises"; | |
| 5 | 新增:import { tmpdir } from "node:os"; | |
| 6 | 新增:import { isAbsolute, join } from "node:path"; | |
| 7 | 新增:import { setTimeout } from "node:timers/promises"; | |
| 8 | 新增:const binary = process.argv[2]; | |
| 9 | 新增:assert.ok(binary && isAbsolute(binary), "Pass an absolute cage-client binary."); | |
| 10 | 新增:const root = await mkdtemp(join(tmpdir(), "cage-agent-client-")); | |
| 11 | 新增:const config = join(root, "config.json"); | |
| 12 | 新增:let pid; | |
| 13 | 新增:const invoke = (args) => { | |
| 14 | 新增: const result = spawnSync(binary, args, { | |
| 15 | 新增: encoding: "utf8", | |
| 16 | 新增: timeout: 30000, | |
| 17 | 新增: env: { ...process.env, CLAUDE_CAGE_CONFIG: config }, | |
| 18 | 新增: }); | |
| 19 | 新增: assert.ifError(result.error); | |
| 20 | 新增: assert.equal( | |
| 21 | 新增: result.status, | |
| 22 | 新增: 0, | |
| 23 | 新增: `Client operation failed: ${result.stdout} ${result.stderr}`, | |
| 24 | 新增: ); | |
| 25 | 新增: return JSON.parse(result.stdout); | |
| 26 | 新增:}; | |
| 27 | 新增:try { | |
| 28 | 新增: const capabilities = invoke(["agent", "capabilities"]); | |
| 29 | 新增: assert.ok( | |
| 30 | 新增: capabilities.data.operations.some((x) => x.name === "client.hosts"), | |
| 31 | 新增: ); | |
| 32 | 新增: invoke(["desktop", "--json"]); | |
| 33 | 新增: pid = JSON.parse(await readFile(join(root, "control.json"), "utf8")).pid; | |
| 34 | 新增: const context = invoke(["agent", "call", "client.context"]); | |
| 35 | 新增: assert.equal(context.data.client_only, true); | |
| 36 | 新增: const doctor = invoke(["agent", "doctor"]); | |
| 37 | 新增: assert.equal(doctor.data.scope, "client"); | |
| 38 | 新增: assert.equal(doctor.data.snapshot.client_only, true); | |
| 39 | 新增: assert.equal(doctor.data.snapshot.connection_id, context.data.connection_id); | |
| 40 | 新增: const routes = invoke(["agent", "routes"]); | |
| 41 | 新增: assert.ok(routes.data.includes("POST /api/agent/native")); | |
| 42 | 新增: const hosts = invoke(["agent", "call", "client.hosts"]); | |
| 43 | 新增: assert.deepEqual(hosts.data.hosts, []); | |
| 44 | 新增: console.log( | |
| 45 | 新增: "PASS: lightweight client exposes the shared Agent protocol, native queue route, exact client context, scope-aware doctor and saved host collection. No remote host or VM was started.", | |
| 46 | 新增: ); | |
| 47 | 新增:} finally { | |
| 48 | 新增: if (pid) { | |
| 49 | 新增: try { | |
| 50 | 新增: process.kill(pid, "SIGTERM"); | |
| 51 | 新增: } catch (error) { | |
| 52 | 新增: if (error.code !== "ESRCH") throw error; | |
| 53 | 新增: } | |
| 54 | 新增: let retired = false; | |
| 55 | 新增: for (let i = 0; i < 100; i++) { | |
| 56 | 新增: try { | |
| 57 | 新增: await stat(join(root, "control.json")); | |
| 58 | 新增: } catch (error) { | |
| 59 | 新增: if (error.code === "ENOENT") { | |
| 60 | 新增: retired = true; | |
| 61 | 新增: break; | |
| 62 | 新增: } | |
| 63 | 新增: throw error; | |
| 64 | 新增: } | |
| 65 | 新增: await setTimeout(100); | |
| 66 | 新增: } | |
| 67 | 新增: assert.ok( | |
| 68 | 新增: retired, | |
| 69 | 新增: "Client controller is still running; preserve its test profile.", | |
| 70 | 新增: ); | |
| 71 | 新增: } | |
| 72 | 新增: await rm(root, { recursive: true, force: true }); | |
| 73 | 新增:} | |
| @@ -0,0 +1,190 @@ | ||
| 1 | 新增:// Real CLI, controller HTTP and compiled UI; only the host OS bridge is a stub. | |
| 2 | 新增:// No VM is created. The initialization record is an isolated existing-user | |
| 3 | 新增:// fixture so the stopped workbench, including its sidebar, can be inspected. | |
| 4 | 新增:import assert from 'node:assert/strict'; | |
| 5 | 新增:import { execFile } from 'node:child_process'; | |
| 6 | 新增:import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; | |
| 7 | 新增:import { createRequire } from 'node:module'; | |
| 8 | 新增:import { tmpdir } from 'node:os'; | |
| 9 | 新增:import { isAbsolute, join } from 'node:path'; | |
| 10 | 新增:import { request as httpRequest } from 'node:http'; | |
| 11 | 新增:import { setTimeout } from 'node:timers/promises'; | |
| 12 | 新增: | |
| 13 | 新增:const binary = process.argv[2]; | |
| 14 | 新增:assert.ok(binary && isAbsolute(binary), 'Pass an absolute newly built Cage CLI binary path.'); | |
| 15 | 新增:const { chromium } = createRequire(import.meta.url)(process.env.CAGE_PLAYWRIGHT_MODULE || 'playwright'); | |
| 16 | 新增:const profile = await mkdtemp(join(tmpdir(), 'cage-agent-native-browser-')); | |
| 17 | 新增:const config = join(profile, 'profile', 'config.json'); | |
| 18 | 新增:let pid, browser; | |
| 19 | 新增:const errors = []; | |
| 20 | 新增:const operations = []; | |
| 21 | 新增:const claims = []; | |
| 22 | 新增:const refreshTickets = new Set(); | |
| 23 | 新增:let registrations = 0; | |
| 24 | 新增:let prooflessClaims = 0; | |
| 25 | 新增: | |
| 26 | 新增:async function cli(args, input) { | |
| 27 | 新增: const child = execFile(binary, ['agent', ...args, '--config', config], { timeout: 30000, encoding: 'utf8', maxBuffer: 4 << 20 }); | |
| 28 | 新增: if (input !== undefined) child.stdin.end(JSON.stringify(input)); | |
| 29 | 新增: const result = await new Promise((resolve, reject) => { | |
| 30 | 新增: let stdout = '', stderr = ''; | |
| 31 | 新增: child.stdout.on('data', chunk => { stdout += chunk; }); | |
| 32 | 新增: child.stderr.on('data', chunk => { stderr += chunk; }); | |
| 33 | 新增: child.on('error', reject); | |
| 34 | 新增: child.on('close', code => { | |
| 35 | 新增: if (code !== 0) reject(new Error(`Agent ${args[0]} failed (${code}): ${stdout} ${stderr}`)); | |
| 36 | 新增: else resolve(JSON.parse(stdout)); | |
| 37 | 新增: }); | |
| 38 | 新增: }); | |
| 39 | 新增: assert.equal(result.protocol, 1); | |
| 40 | 新增: return result; | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:async function entry() { | |
| 44 | 新增: const record = JSON.parse(await readFile(join(profile, 'profile', 'control.json'), 'utf8')); | |
| 45 | 新增: return new Promise((resolve, reject) => { | |
| 46 | 新增: const body = JSON.stringify({ token: record.token }); | |
| 47 | 新增: const request = httpRequest({ hostname: 'localhost', port: record.port, path: '/api/launch', method: 'POST', headers: { Origin: `http://localhost:${record.port}`, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, response => { | |
| 48 | 新增: let data = ''; | |
| 49 | 新增: response.setEncoding('utf8'); | |
| 50 | 新增: response.on('data', chunk => { data += chunk; }); | |
| 51 | 新增: response.on('end', () => { | |
| 52 | 新增: if (response.statusCode !== 200) { reject(new Error('Could not authenticate the isolated launch entry.')); return; } | |
| 53 | 新增: resolve(JSON.parse(data).url); | |
| 54 | 新增: }); | |
| 55 | 新增: }); | |
| 56 | 新增: request.on('error', reject); | |
| 57 | 新增: request.setTimeout(10000, () => request.destroy(new Error('Isolated controller launch timed out.'))); | |
| 58 | 新增: request.end(body); | |
| 59 | 新增: }); | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:async function submit(request) { | |
| 63 | 新增: const reply = await cli(['request', 'POST', '/api/agent/native', '--input', '-'], { request, connection_id: 'local' }); | |
| 64 | 新增: assert.equal(reply.status, 'accepted'); | |
| 65 | 新增: assert.equal(reply.data.http_status, 202); | |
| 66 | 新增: assert.equal(reply.data.body.status, 'pending'); | |
| 67 | 新增: assert.ok(reply.data.body.id); | |
| 68 | 新增: return reply.data.body.id; | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:async function completed(id) { | |
| 72 | 新增: const deadline = Date.now() + 20000; | |
| 73 | 新增: while (Date.now() < deadline) { | |
| 74 | 新增: const reply = await cli(['request', 'GET', `/api/agent/native/${id}`]); | |
| 75 | 新增: const item = reply.data.body; | |
| 76 | 新增: if (item.status === 'completed' || item.status === 'failed') return item; | |
| 77 | 新增: assert.ok(['pending', 'running'].includes(item.status), 'Unknown native request status.'); | |
| 78 | 新增: await setTimeout(150); | |
| 79 | 新增: } | |
| 80 | 新增: throw new Error('The compiled desktop consumer did not complete its original request.'); | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:try { | |
| 84 | 新增: await cli(['init']); | |
| 85 | 新增: await writeFile(join(profile, 'profile', 'initialization.json'), JSON.stringify({ version: 1, completed: true }), { mode: 0o600 }); | |
| 86 | 新增: await cli(['service.start']); | |
| 87 | 新增: pid = JSON.parse(await readFile(join(profile, 'profile', 'control.json'), 'utf8')).pid; | |
| 88 | 新增: await cli(['call', 'account.create', '--input', '-'], { username: 'Agent browser acceptance', password: 'Ephemeral-Browser-Password-123!', confirm_password: 'Ephemeral-Browser-Password-123!' }); | |
| 89 | 新增: browser = await chromium.launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH }); | |
| 90 | 新增: const context = await browser.newContext({ viewport: { width: 1280, height: 900 } }); | |
| 91 | 新增: const page = await context.newPage(); | |
| 92 | 新增: page.on('pageerror', error => errors.push(error.message)); | |
| 93 | 新增: page.on('response', async response => { | |
| 94 | 新增: if (new URL(response.url()).pathname === '/api/agent/native/window' && response.status() === 200) registrations++; | |
| 95 | 新增: if (new URL(response.url()).pathname === '/api/agent/native' && response.request().method() === 'GET') { | |
| 96 | 新增: if (!response.request().headers()['x-cage-agent-window']) prooflessClaims++; | |
| 97 | 新增: try { | |
| 98 | 新增: const value = await response.json(); if (value.id) claims.push(value.id); | |
| 99 | 新增: } catch { /* A reload can end the observation response. */ } | |
| 100 | 新增: } | |
| 101 | 新增: }); | |
| 102 | 新增: await page.exposeFunction('__cageNativeTest', async request => { | |
| 103 | 新增: operations.push({ action: request.action, operation: request.operation, connection_id: request.connection_id }); | |
| 104 | 新增: if (request.action === 'accountDevice') { | |
| 105 | 新增: if (request.operation === 'status') return { supported: true, biometric_available: true, device_status: { automatic: 'disabled', biometric: 'disabled' } }; | |
| 106 | 新增: throw new Error('请完成 Touch ID 用户验证(操作系统桥验收替身)。'); | |
| 107 | 新增: } | |
| 108 | 新增: if (request.action === 'refreshSession') { | |
| 109 | 新增: const url = await entry(); | |
| 110 | 新增: refreshTickets.add(new URL(url).hash.slice(1)); | |
| 111 | 新增: return { url }; | |
| 112 | 新增: } | |
| 113 | 新增: if (request.action === 'appUpdate') return { phase: 'manual', currentVersion: 'acceptance-fixture', message: 'OS updater fixture; no app files are modified.' }; | |
| 114 | 新增: if (request.action === 'appearance' || request.action === 'workbenchReady' || request.action === 'clipboardSyncCancel') return true; | |
| 115 | 新增: throw new Error(`Unexpected OS bridge action in this smoke test: ${request.action}`); | |
| 116 | 新增: }); | |
| 117 | 新增: await page.addInitScript(() => { | |
| 118 | 新增: window.cageNativeBridge = { postMessage: request => window.__cageNativeTest(request) }; | |
| 119 | 新增: // Count real document boots across the consumer's requested reload. | |
| 120 | 新增: sessionStorage.setItem('agent-native-browser-boots', String(Number(sessionStorage.getItem('agent-native-browser-boots') || 0) + 1)); | |
| 121 | 新增: }); | |
| 122 | 新增: await page.goto(await entry()); | |
| 123 | 新增: await page.locator('.app').waitFor({ timeout: 20000 }); | |
| 124 | 新增: await page.getByRole('complementary', { name: '项目与终端' }).waitFor(); | |
| 125 | 新增: const boot = await page.evaluate(() => Number(sessionStorage.getItem('agent-native-browser-boots'))); | |
| 126 | 新增: const origin = new URL(page.url()).origin; | |
| 127 | 新增: const ordinaryClaim = await context.request.get(`${origin}/api/agent/native?consumer=window`, { headers: { 'X-Cage-Connection': 'local' } }); | |
| 128 | 新增: assert.equal(ordinaryClaim.status(), 403, 'A browser session without native window proof could claim an OS action.'); | |
| 129 | 新增: const initial = await cli(['call', 'status']); | |
| 130 | 新增: assert.equal(initial.data.vm_running, false); | |
| 131 | 新增: assert.equal(initial.data.ready, false); | |
| 132 | 新增: | |
| 133 | 新增: const preference = await submit({ action: 'clientPreferences', operation: 'set', values: { 'cage-sidebar-collapsed': 'true', 'cage-browser-tab-layout': '"vertical"', 'cage.audio': '{"muted":true,"volume":0.25}' } }); | |
| 134 | 新增: const saved = await completed(preference); | |
| 135 | 新增: assert.equal(saved.status, 'completed'); | |
| 136 | 新增: assert.equal(saved.result.reload_required, true); | |
| 137 | 新增: await page.waitForFunction(previous => Number(sessionStorage.getItem('agent-native-browser-boots')) > previous, boot); | |
| 138 | 新增: await page.locator('.app.sidebar-collapsed').waitFor(); | |
| 139 | 新增: assert.equal(await page.getByRole('complementary', { name: '项目与终端' }).count(), 0, 'The real workbench did not apply sidebar state after reload.'); | |
| 140 | 新增: assert.deepEqual(await page.evaluate(() => ({ sidebar: localStorage.getItem('cage-sidebar-collapsed'), layout: localStorage.getItem('cage-browser-tab-layout'), audio: localStorage.getItem('cage.audio') })), { sidebar: 'true', layout: '"vertical"', audio: '{"muted":true,"volume":0.25}' }); | |
| 141 | 新增: | |
| 142 | 新增: const read = await completed(await submit({ action: 'clientPreferences', operation: 'get' })); | |
| 143 | 新增: assert.equal(read.status, 'completed'); | |
| 144 | 新增: assert.equal(read.result.values['cage-sidebar-collapsed'], 'true'); | |
| 145 | 新增: assert.equal(read.result.values['cage-browser-tab-layout'], '"vertical"'); | |
| 146 | 新增: | |
| 147 | 新增: const biometric = await completed(await submit({ action: 'accountDevice', operation: 'enable', kind: 'biometric' })); | |
| 148 | 新增: assert.equal(biometric.status, 'failed'); | |
| 149 | 新增: assert.match(biometric.error, /请完成 Touch ID 用户验证/); | |
| 150 | 新增: assert.equal(operations.filter(item => item.action === 'accountDevice' && item.operation === 'enable').length, 1, 'The failed biometric action was repeated.'); | |
| 151 | 新增: | |
| 152 | 新增: const refreshed = await completed(await submit({ action: 'refreshSession' })); | |
| 153 | 新增: assert.equal(refreshed.status, 'completed'); | |
| 154 | 新增: assert.deepEqual(refreshed.result, { refreshed: true }); | |
| 155 | 新增: assert.ok(refreshTickets.size > 0); | |
| 156 | 新增: for (const ticket of refreshTickets) assert.ok(!JSON.stringify(refreshed).includes(ticket), 'The native refresh ticket reached Agent output.'); | |
| 157 | 新增: const forgedCompletion = await context.request.post(`${origin}/api/agent/native/${refreshed.id}/complete`, { headers: { Origin: origin, 'X-Cage-Connection': 'local' }, data: { result: { forged: true } } }); | |
| 158 | 新增: assert.equal(forgedCompletion.status(), 403, 'A browser session without window proof could forge an OS completion.'); | |
| 159 | 新增: | |
| 160 | 新增: const restored = await completed(await submit({ action: 'clientPreferences', operation: 'set', values: { 'cage-sidebar-collapsed': 'false' } })); | |
| 161 | 新增: assert.equal(restored.status, 'completed'); | |
| 162 | 新增: await page.getByRole('complementary', { name: '项目与终端' }).waitFor(); | |
| 163 | 新增: assert.equal(await page.locator('.app.sidebar-collapsed').count(), 0); | |
| 164 | 新增: // The reverse direction uses the real user control, then the Agent reads | |
| 165 | 新增: // the same stored state rather than a separate Agent-only preference. | |
| 166 | 新增: await page.getByRole('button', { name: '收起侧栏', exact: true }).click(); | |
| 167 | 新增: await page.locator('.app.sidebar-collapsed').waitFor(); | |
| 168 | 新增: const userChanged = await completed(await submit({ action: 'clientPreferences', operation: 'get' })); | |
| 169 | 新增: assert.equal(userChanged.status, 'completed'); | |
| 170 | 新增: assert.equal(userChanged.result.values['cage-sidebar-collapsed'], 'true'); | |
| 171 | 新增: assert.ok(registrations >= 2, 'Document reload did not establish an independent native window proof.'); | |
| 172 | 新增: assert.equal(prooflessClaims, 0, 'The real consumer omitted its window proof.'); | |
| 173 | 新增: const persistedClientState = await page.evaluate(() => JSON.stringify({ local: { ...localStorage }, session: { ...sessionStorage } })); | |
| 174 | 新增: for (const ticket of refreshTickets) assert.ok(!persistedClientState.includes(ticket), 'A native registration ticket was persisted by the UI.'); | |
| 175 | 新增: assert.equal(claims.filter(id => id === preference).length, 1, 'A native request was claimed more than once.'); | |
| 176 | 新增: assert.deepEqual(errors, []); | |
| 177 | 新增: console.log('PASS: real Cage CLI + HTTP + compiled UI native queue, private window registration, ordinary-session claim/completion rejection, single claim, bidirectional sidebar preference, persistence/reload, OS verification failure, private refresh result and no VM startup. OS bridge was a fixture; no physical Touch ID or app installation was tested.'); | |
| 178 | 新增:} finally { | |
| 179 | 新增: await browser?.close(); | |
| 180 | 新增: if (pid) { | |
| 181 | 新增: try { process.kill(pid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; } | |
| 182 | 新增: let retired = false; | |
| 183 | 新增: for (let attempt = 0; attempt < 100; attempt++) { | |
| 184 | 新增: try { await stat(join(profile, 'profile', 'control.json')); } catch (error) { if (error.code === 'ENOENT') { retired = true; break; } throw error; } | |
| 185 | 新增: await setTimeout(100); | |
| 186 | 新增: } | |
| 187 | 新增: assert.ok(retired, 'Test controller did not retire; preserve its isolated directory.'); | |
| 188 | 新增: } | |
| 189 | 新增: await rm(profile, { recursive: true, force: true }); | |
| 190 | 新增:} | |
| @@ -0,0 +1,179 @@ | ||
| 1 | 新增:// External agents use the same native bridge as this window. No script or | |
| 2 | 新增:// expression is accepted: native actions retain their existing platform checks. | |
| 3 | 新增:import { clientStorageKey } from "./client-context.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:export const agentClientPreferences = Object.freeze([ | |
| 6 | 新增: { key: "cage-active", scoped: true, format: "string", description: "当前标签 ID" }, | |
| 7 | 新增: { key: "cage-sidebar-collapsed", scoped: true, format: "JSON boolean", description: "侧栏收起状态" }, | |
| 8 | 新增: { key: "cage-browser-tab-layout", scoped: true, format: 'JSON "horizontal" | "vertical"', description: "浏览器标签排列" }, | |
| 9 | 新增: { key: "cage-tab-layout", scoped: true, format: "JSON object", description: "按工作区保存的标签名称、固定与顺序" }, | |
| 10 | 新增: { key: "cage-keyboard", scoped: true, remoteOnly: true, format: 'string "mac" | "native"', description: "远端环境在当前客户端的快捷键习惯;本机使用 settings.keyboard" }, | |
| 11 | 新增: { key: "cage.audio", scoped: false, format: "JSON {muted:boolean, volume:number 0..1}", description: "当前客户端的声音偏好" }, | |
| 12 | 新增: { key: "cage-desktop-zoom", scoped: false, format: "string number: 0.75, 0.9, 1, 1.1, 1.25, 1.5", description: "Claude Desktop 显示比例" }, | |
| 13 | 新增: { key: "cage-recent-environment", scoped: false, format: "string", description: "最近选择的 local 或主机 ID" }, | |
| 14 | 新增:]); | |
| 15 | 新增: | |
| 16 | 新增:const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value); | |
| 17 | 新增:function validPreference(key, raw) { | |
| 18 | 新增: if (raw === null) return true; | |
| 19 | 新增: if (typeof raw !== "string") return false; | |
| 20 | 新增: if (["cage-active", "cage-recent-environment"].includes(key)) return true; | |
| 21 | 新增: if (key === "cage-keyboard") return ["mac", "native"].includes(raw); | |
| 22 | 新增: if (key === "cage-desktop-zoom") return [0.75, 0.9, 1, 1.1, 1.25, 1.5].includes(Number(raw)); | |
| 23 | 新增: let value; | |
| 24 | 新增: try { value = JSON.parse(raw); } catch { return false; } | |
| 25 | 新增: if (key === "cage-sidebar-collapsed") return typeof value === "boolean"; | |
| 26 | 新增: if (key === "cage-browser-tab-layout") return ["horizontal", "vertical"].includes(value); | |
| 27 | 新增: if (key === "cage.audio") return object(value) && typeof value.muted === "boolean" && Number.isFinite(value.volume) && value.volume >= 0 && value.volume <= 1 && Object.keys(value).every(field => ["muted", "volume"].includes(field)); | |
| 28 | 新增: if (key === "cage-tab-layout") { | |
| 29 | 新增: if (!object(value)) return false; | |
| 30 | 新增: return Object.values(value).every(workspace => object(workspace) && Object.entries(workspace).every(([id, metadata]) => { | |
| 31 | 新增: if (id === "order") return Array.isArray(metadata) && metadata.every(item => typeof item === "string"); | |
| 32 | 新增: if (id === "sessionOrder") return object(metadata) && Object.values(metadata).every(order => Array.isArray(order) && order.every(item => typeof item === "string")); | |
| 33 | 新增: return object(metadata) && Object.entries(metadata).every(([field, item]) => field === "title" ? typeof item === "string" : field === "pinned" && typeof item === "boolean"); | |
| 34 | 新增: })); | |
| 35 | 新增: } | |
| 36 | 新增: return false; | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:function connectionChanged() { | |
| 40 | 新增: const error = new Error("工作环境已切换;未在新环境重放原生操作,请核对原操作结果。"); | |
| 41 | 新增: error.code = "connection_changed"; | |
| 42 | 新增: return error; | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:export function clientPreferences(request, context, storage) { | |
| 46 | 新增: if (!["get", "set"].includes(request.operation)) throw new Error("客户端偏好操作须为 get 或 set。"); | |
| 47 | 新增: const keys = new Map(agentClientPreferences.map(item => [item.key, item])); | |
| 48 | 新增: const path = (key) => keys.get(key).scoped ? clientStorageKey(key, context) : key; | |
| 49 | 新增: if (request.operation === "set") { | |
| 50 | 新增: if (!object(request.values) || !Object.keys(request.values).length) throw new Error("请提供要修改的客户端偏好 values。"); | |
| 51 | 新增: // Validate the whole patch before changing any storage entry. | |
| 52 | 新增: for (const [key, raw] of Object.entries(request.values)) { | |
| 53 | 新增: if (!keys.has(key)) throw new Error("客户端偏好包含不支持的键。外观请通过 appearance 接口修改。"); | |
| 54 | 新增: if (keys.get(key).remoteOnly && context.mode !== "remote") throw new Error("本机键盘习惯请通过 settings.keyboard 修改。"); | |
| 55 | 新增: if (!validPreference(key, raw)) throw new Error("客户端偏好格式无效,请保留对应设置使用的原始字符串格式。"); | |
| 56 | 新增: } | |
| 57 | 新增: const previous = new Map(Object.keys(request.values).map(key => [path(key), storage.getItem(path(key))])); | |
| 58 | 新增: try { | |
| 59 | 新增: for (const [key, raw] of Object.entries(request.values)) { | |
| 60 | 新增: if (raw === null) storage.removeItem(path(key)); | |
| 61 | 新增: else storage.setItem(path(key), raw); | |
| 62 | 新增: } | |
| 63 | 新增: } catch (error) { | |
| 64 | 新增: for (const [key, raw] of previous) { | |
| 65 | 新增: try { if (raw === null) storage.removeItem(key); else storage.setItem(key, raw); } catch { /* Keep the original storage failure. */ } | |
| 66 | 新增: } | |
| 67 | 新增: throw error; | |
| 68 | 新增: } | |
| 69 | 新增: } | |
| 70 | 新增: const available = agentClientPreferences.filter(item => !item.remoteOnly || context.mode === "remote"); | |
| 71 | 新增: return { | |
| 72 | 新增: connection_id: context.connection_id, | |
| 73 | 新增: values: Object.fromEntries(available.map(item => [item.key, storage.getItem(path(item.key))])), | |
| 74 | 新增: storage_keys: Object.fromEntries(available.map(item => [item.key, path(item.key)])), | |
| 75 | 新增: fields: available, | |
| 76 | 新增: reload_required: request.operation === "set", | |
| 77 | 新增: }; | |
| 78 | 新增:} | |
| 79 | 新增: | |
| 80 | 新增:export async function executeAgentNative(item, { native, getContext, storage }) { | |
| 81 | 新增: const context = getContext(); | |
| 82 | 新增: if (!item.connection_id || item.connection_id !== context.connection_id) throw connectionChanged(); | |
| 83 | 新增: const request = item.request; | |
| 84 | 新增: if (!object(request) || typeof request.action !== "string") throw new Error("原生请求格式无效。"); | |
| 85 | 新增: let result; | |
| 86 | 新增: if (request.action === "clientPreferences") result = clientPreferences(request, context, storage); | |
| 87 | 新增: else { | |
| 88 | 新增: const { action, connection_id: ignoredConnection, ...extra } = request; | |
| 89 | 新增: void ignoredConnection; | |
| 90 | 新增: result = await native(action, extra); | |
| 91 | 新增: // Native session tickets belong to the transport. An agent can request a | |
| 92 | 新增: // refresh, but never receives the launch URL or its secret fragment. | |
| 93 | 新增: if (action === "refreshSession") result = { refreshed: true }; | |
| 94 | 新增: } | |
| 95 | 新增: if (getContext().connection_id !== item.connection_id) throw connectionChanged(); | |
| 96 | 新增: return result === undefined ? null : result; | |
| 97 | 新增:} | |
| 98 | 新增: | |
| 99 | 新增:export function createAgentNativeConsumer({ api, native, nativeAvailable, getContext, storage, reload, getOrigin = () => globalThis.location?.origin, schedule = setTimeout, cancel = clearTimeout, interval = 750, onError = () => {} }) { | |
| 100 | 新增: let stopped = true; | |
| 101 | 新增: let timer; | |
| 102 | 新增: let running = false; | |
| 103 | 新增: let completion; | |
| 104 | 新增: let proof; | |
| 105 | 新增: const registerWindow = async () => { | |
| 106 | 新增: const entry = await native("refreshSession"); | |
| 107 | 新增: let url; | |
| 108 | 新增: try { url = new URL(entry?.url); } catch { throw new Error("无法验证原生窗口入口,请重新连接 Cage。"); } | |
| 109 | 新增: if (url.origin !== getOrigin() || !url.hash.slice(1)) throw new Error("原生窗口入口已改变;未把验证票据发送到其他地址,请重新连接 Cage。"); | |
| 110 | 新增: const value = await api("/agent/native/window", { ticket: url.hash.slice(1) }); | |
| 111 | 新增: if (typeof value?.window_proof !== "string" || !value.window_proof) throw new Error("原生窗口认证未完成,请重新连接 Cage。"); | |
| 112 | 新增: proof = value.window_proof; | |
| 113 | 新增: }; | |
| 114 | 新增: const poll = async () => { | |
| 115 | 新增: if (stopped || running) return; | |
| 116 | 新增: if (!nativeAvailable()) { timer = schedule(poll, interval); return; } | |
| 117 | 新增: running = true; | |
| 118 | 新增: try { | |
| 119 | 新增: if (!proof) await registerWindow(); | |
| 120 | 新增: if (!completion) { | |
| 121 | 新增: if (stopped) return; | |
| 122 | 新增: const item = await api("/agent/native?consumer=window", undefined, undefined, { "X-Cage-Agent-Window": proof }); | |
| 123 | 新增: if (item?.id) { | |
| 124 | 新增: if (stopped) { | |
| 125 | 新增: completion = { id: item.id, body: { error: "桌面窗口已关闭,原生操作未执行。" } }; | |
| 126 | 新增: } else { | |
| 127 | 新增: try { | |
| 128 | 新增: const result = await executeAgentNative(item, { native, getContext, storage }); | |
| 129 | 新增: completion = { id: item.id, body: { result }, reload: result?.reload_required === true }; | |
| 130 | 新增: } catch (error) { | |
| 131 | 新增: completion = { id: item.id, body: { error: error?.message || "原生操作未完成,请核对当前窗口。" } }; | |
| 132 | 新增: } | |
| 133 | 新增: } | |
| 134 | 新增: } | |
| 135 | 新增: } | |
| 136 | 新增: if (completion) { | |
| 137 | 新增: const pending = completion; | |
| 138 | 新增: await api(`/agent/native/${encodeURIComponent(pending.id)}/complete`, pending.body, undefined, { "X-Cage-Agent-Window": proof }); | |
| 139 | 新增: completion = undefined; | |
| 140 | 新增: if (pending.reload && !stopped) { stopped = true; reload(); } | |
| 141 | 新增: } | |
| 142 | 新增: } catch (error) { | |
| 143 | 新增: // Only a completion receipt is retried. An accepted native action is | |
| 144 | 新增: // never re-executed after a lost connection or lost response. | |
| 145 | 新增: if (error?.status === 401 || error?.status === 403) proof = undefined; | |
| 146 | 新增: onError(error); | |
| 147 | 新增: } finally { | |
| 148 | 新增: running = false; | |
| 149 | 新增: if (!stopped) timer = schedule(poll, interval); | |
| 150 | 新增: } | |
| 151 | 新增: }; | |
| 152 | 新增: return { | |
| 153 | 新增: start() { if (!stopped) return; stopped = false; void poll(); }, | |
| 154 | 新增: stop() { stopped = true; if (timer !== undefined) cancel(timer); }, | |
| 155 | 新增: }; | |
| 156 | 新增:} | |
| 157 | 新增: | |
| 158 | 新增:let installedConsumer; | |
| 159 | 新增:export function installAgentNativeConsumer(dependencies, environment = globalThis) { | |
| 160 | 新增: if (installedConsumer || !environment.document || !environment.window) return; | |
| 161 | 新增: const consumer = createAgentNativeConsumer({ | |
| 162 | 新增: ...dependencies, | |
| 163 | 新增: storage: { | |
| 164 | 新增: getItem: key => environment.localStorage.getItem(key), | |
| 165 | 新增: setItem: (key, value) => environment.localStorage.setItem(key, value), | |
| 166 | 新增: removeItem: key => environment.localStorage.removeItem(key), | |
| 167 | 新增: }, | |
| 168 | 新增: reload: () => environment.location.reload(), | |
| 169 | 新增: getOrigin: () => environment.location.origin, | |
| 170 | 新增: }); | |
| 171 | 新增: installedConsumer = consumer; | |
| 172 | 新增: const start = () => { if (dependencies.nativeAvailable()) consumer.start(); }; | |
| 173 | 新增: environment.window.addEventListener("cage-session-ready", start); | |
| 174 | 新增: environment.window.addEventListener("pagehide", () => consumer.stop()); | |
| 175 | 新增: environment.window.addEventListener("pageshow", start); | |
| 176 | 新增: // A fresh launch URL must first be exchanged by ClientRoot/AccountProvider. | |
| 177 | 新增: // Existing windows without a fragment already hold their session cookie. | |
| 178 | 新增: if (!environment.location?.hash) start(); | |
| 179 | 新增:} | |
| @@ -0,0 +1,208 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import test from "node:test"; | |
| 3 | 新增:import { agentClientPreferences, clientPreferences, createAgentNativeConsumer, executeAgentNative } from "./agent-native.js"; | |
| 4 | 新增: | |
| 5 | 新增:const context = { mode: "remote", connection_id: "generation-a", instance_id: "server-one" }; | |
| 6 | 新增:function storage() { | |
| 7 | 新增: const values = new Map(); | |
| 8 | 新增: return { values, getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key) }; | |
| 9 | 新增:} | |
| 10 | 新增:const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); }; | |
| 11 | 新增:function clock() { | |
| 12 | 新增: const scheduled = []; | |
| 13 | 新增: return { scheduled, schedule: callback => { scheduled.push(callback); return callback; }, cancel: callback => { const index = scheduled.indexOf(callback); if (index >= 0) scheduled.splice(index, 1); }, tick: async () => { scheduled.shift()?.(); await flush(); } }; | |
| 14 | 新增:} | |
| 15 | 新增:function consumerForTest(dependencies) { | |
| 16 | 新增: return createAgentNativeConsumer({ | |
| 17 | 新增: ...dependencies, | |
| 18 | 新增: getOrigin: () => "http://localhost:17777", | |
| 19 | 新增: native: async (action, extra) => action === "refreshSession" ? { url: "http://localhost:17777/#fresh-native-ticket" } : dependencies.native(action, extra), | |
| 20 | 新增: api: async (path, body, method, headers) => { | |
| 21 | 新增: if (path === "/agent/native/window") { | |
| 22 | 新增: assert.deepEqual(body, { ticket: "fresh-native-ticket" }); | |
| 23 | 新增: return { window_proof: "private-window-proof" }; | |
| 24 | 新增: } | |
| 25 | 新增: assert.equal(headers?.["X-Cage-Agent-Window"], "private-window-proof"); | |
| 26 | 新增: return dependencies.api(path, body, method, headers); | |
| 27 | 新增: }, | |
| 28 | 新增: }); | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:test("client preference writes use the window's remote instance and preserve original string encodings", () => { | |
| 32 | 新增: const state = storage(); | |
| 33 | 新增: state.setItem("unrelated-token", "keep-private"); | |
| 34 | 新增: state.setItem("cage-sidebar-collapsed:remote:server-two", "false"); | |
| 35 | 新增: const values = { | |
| 36 | 新增: "cage-sidebar-collapsed": "true", | |
| 37 | 新增: "cage-browser-tab-layout": '"vertical"', | |
| 38 | 新增: "cage-keyboard": "native", | |
| 39 | 新增: "cage.audio": '{"muted":false,"volume":0.25}', | |
| 40 | 新增: "cage-desktop-zoom": "1.25", | |
| 41 | 新增: "cage-tab-layout": '{"/workspace":{"order":["browser-1"],"sessionOrder":{"/project":["session-1"]},"browser-1":{"title":"Saved title","pinned":true}}}', | |
| 42 | 新增: }; | |
| 43 | 新增: const result = clientPreferences({ operation: "set", values }, context, state); | |
| 44 | 新增: assert.equal(result.reload_required, true); | |
| 45 | 新增: assert.equal(state.getItem("cage-sidebar-collapsed:remote:server-one"), "true"); | |
| 46 | 新增: assert.equal(state.getItem("cage-sidebar-collapsed:remote:server-two"), "false"); | |
| 47 | 新增: assert.equal(state.getItem("cage-browser-tab-layout:remote:server-one"), '"vertical"'); | |
| 48 | 新增: assert.equal(state.getItem("cage.audio"), values["cage.audio"]); | |
| 49 | 新增: assert.deepEqual(result.values["cage-keyboard"], "native"); | |
| 50 | 新增: assert.ok(!JSON.stringify(result).includes("keep-private")); | |
| 51 | 新增: assert.ok(!JSON.stringify(result).includes("unrelated-token")); | |
| 52 | 新增: assert.equal(result.storage_keys["cage-keyboard"], "cage-keyboard:remote:server-one"); | |
| 53 | 新增: assert.ok(agentClientPreferences.length >= 8); | |
| 54 | 新增:}); | |
| 55 | 新增: | |
| 56 | 新增:test("invalid or server-owned preference patches do not change any earlier field", () => { | |
| 57 | 新增: const state = storage(); | |
| 58 | 新增: for (const values of [ | |
| 59 | 新增: { "cage-sidebar-collapsed": "true", "unknown": "secret" }, | |
| 60 | 新增: { "cage-sidebar-collapsed": "true", "cage.audio": '{"volume":5,"muted":false}' }, | |
| 61 | 新增: { "cage-appearance": "{}" }, | |
| 62 | 新增: { "cage-tab-layout": '{"project":{"order":{}}}' }, | |
| 63 | 新增: { "cage-browser-tab-layout": "vertical" }, | |
| 64 | 新增: ]) assert.throws(() => clientPreferences({ operation: "set", values }, context, state)); | |
| 65 | 新增: assert.equal(state.values.size, 0); | |
| 66 | 新增: assert.throws(() => clientPreferences({ operation: "set", values: { "cage-keyboard": "mac" } }, { mode: "local" }, state), /settings.keyboard/); | |
| 67 | 新增:}); | |
| 68 | 新增: | |
| 69 | 新增:test("partial storage failure restores entries already changed in the patch", () => { | |
| 70 | 新增: const state = storage(); | |
| 71 | 新增: state.setItem("cage.audio", '{"volume":1,"muted":false}'); | |
| 72 | 新增: const original = state.setItem; | |
| 73 | 新增: state.setItem = (key, value) => { if (key === "cage-desktop-zoom") throw new Error("full"); original(key, value); }; | |
| 74 | 新增: assert.throws(() => clientPreferences({ operation: "set", values: { "cage.audio": '{"volume":0,"muted":true}', "cage-desktop-zoom": "1.5" } }, context, state), /full/); | |
| 75 | 新增: assert.equal(state.getItem("cage.audio"), '{"volume":1,"muted":false}'); | |
| 76 | 新增:}); | |
| 77 | 新增: | |
| 78 | 新增:test("a late native result is rejected and a request for an old generation never invokes the bridge", async () => { | |
| 79 | 新增: let current = context, release, calls = 0; | |
| 80 | 新增: const dependencies = { storage: storage(), getContext: () => current, native: () => { calls++; return new Promise(resolve => { release = resolve; }); } }; | |
| 81 | 新增: await assert.rejects(executeAgentNative({ connection_id: "old", request: { action: "chooseFolder" } }, dependencies), { code: "connection_changed" }); | |
| 82 | 新增: assert.equal(calls, 0); | |
| 83 | 新增: const pending = executeAgentNative({ connection_id: context.connection_id, request: { action: "accountDevice", operation: "unlock", kind: "biometric", connection_id: "malicious-override" } }, dependencies); | |
| 84 | 新增: current = { ...context, connection_id: "generation-b" }; | |
| 85 | 新增: release({ unlocked: true }); | |
| 86 | 新增: await assert.rejects(pending, { code: "connection_changed" }); | |
| 87 | 新增: assert.equal(calls, 1); | |
| 88 | 新增:}); | |
| 89 | 新增: | |
| 90 | 新增:test("native operations retain their production checks and never return the refresh ticket", async () => { | |
| 91 | 新增: let received; | |
| 92 | 新增: const deps = { storage: storage(), getContext: () => context, native: async (action, input) => { received = { action, input }; return { url: "http://localhost:17777/#private-ticket" }; } }; | |
| 93 | 新增: const result = await executeAgentNative({ connection_id: context.connection_id, request: { action: "refreshSession", connection_id: "override" } }, deps); | |
| 94 | 新增: assert.deepEqual(result, { refreshed: true }); | |
| 95 | 新增: assert.deepEqual(received, { action: "refreshSession", input: {} }); | |
| 96 | 新增: deps.native = async () => { throw new Error("macOS 要求 Touch ID"); }; | |
| 97 | 新增: await assert.rejects(executeAgentNative({ connection_id: context.connection_id, request: { action: "accountDevice", operation: "unlock" } }, deps), /Touch ID/); | |
| 98 | 新增:}); | |
| 99 | 新增: | |
| 100 | 新增:test("lost completion response retries the receipt without repeating a native action", async () => { | |
| 101 | 新增: const timers = clock(); let actions = 0, claims = 0, completes = 0; | |
| 102 | 新增: const consumer = consumerForTest({ | |
| 103 | 新增: ...timers, getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, | |
| 104 | 新增: native: async () => { actions++; return { ok: true }; }, | |
| 105 | 新增: api: async path => { | |
| 106 | 新增: if (path.includes("consumer=window")) { claims++; return claims === 1 ? { id: "request-1", connection_id: context.connection_id, request: { action: "clipboardRead" } } : {}; } | |
| 107 | 新增: completes++; if (completes === 1) throw new Error("lost acknowledgement"); return { ok: true }; | |
| 108 | 新增: }, | |
| 109 | 新增: }); | |
| 110 | 新增: consumer.start(); await flush(); | |
| 111 | 新增: assert.equal(actions, 1); assert.equal(completes, 1); | |
| 112 | 新增: await timers.tick(); | |
| 113 | 新增: assert.equal(actions, 1); assert.equal(completes, 2); assert.equal(claims, 1); | |
| 114 | 新增: consumer.stop(); assert.equal(timers.scheduled.length, 0); | |
| 115 | 新增:}); | |
| 116 | 新增: | |
| 117 | 新增:test("preference reload follows a successful receipt and never a lost one", async () => { | |
| 118 | 新增: const timers = clock(); let completes = 0, reloads = 0; | |
| 119 | 新增: const consumer = consumerForTest({ | |
| 120 | 新增: ...timers, getContext: () => context, storage: storage(), reload: () => { reloads++; }, nativeAvailable: () => true, | |
| 121 | 新增: native: async () => { throw new Error("must use client preference handler"); }, | |
| 122 | 新增: api: async path => { | |
| 123 | 新增: if (path.includes("consumer=window")) return { id: "request-1", connection_id: context.connection_id, request: { action: "clientPreferences", operation: "set", values: { "cage-sidebar-collapsed": "true" } } }; | |
| 124 | 新增: completes++; if (completes === 1) throw new Error("lost"); return {}; | |
| 125 | 新增: }, | |
| 126 | 新增: }); | |
| 127 | 新增: consumer.start(); await flush(); assert.equal(reloads, 0); | |
| 128 | 新增: await timers.tick(); assert.equal(reloads, 1); assert.equal(timers.scheduled.length, 0); | |
| 129 | 新增:}); | |
| 130 | 新增: | |
| 131 | 新增:test("two desktop consumers execute a claimed operation once and stopping cancels future polling", async () => { | |
| 132 | 新增: const pending = [{ id: "request-1", connection_id: context.connection_id, request: { action: "chooseFolder" } }]; | |
| 133 | 新增: let actions = 0, polls = 0; | |
| 134 | 新增: const consumers = []; | |
| 135 | 新增: const clocks = []; | |
| 136 | 新增: for (let i = 0; i < 2; i++) { | |
| 137 | 新增: const timers = clock(); clocks.push(timers); | |
| 138 | 新增: consumers.push(consumerForTest({ ...timers, getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, | |
| 139 | 新增: native: async () => { actions++; return "/chosen/project"; }, | |
| 140 | 新增: api: async path => { if (path.includes("consumer=window")) { polls++; return pending.shift() || {}; } return {}; }, | |
| 141 | 新增: })); | |
| 142 | 新增: } | |
| 143 | 新增: consumers.forEach(consumer => consumer.start()); await flush(); | |
| 144 | 新增: assert.equal(actions, 1); assert.equal(polls, 2); | |
| 145 | 新增: consumers.forEach(consumer => consumer.stop()); | |
| 146 | 新增: for (const timers of clocks) { await timers.tick(); assert.equal(timers.scheduled.length, 0); } | |
| 147 | 新增: assert.equal(polls, 2); | |
| 148 | 新增:}); | |
| 149 | 新增: | |
| 150 | 新增:test("a window stopped while waiting for a claim reports non-execution", async () => { | |
| 151 | 新增: const timers = clock(); let release, actions = 0, body; | |
| 152 | 新增: const consumer = consumerForTest({ ...timers, getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, | |
| 153 | 新增: native: async () => { actions++; }, | |
| 154 | 新增: api: async (path, value) => { if (path.includes("consumer=window")) return new Promise(resolve => { release = resolve; }); body = value; return {}; }, | |
| 155 | 新增: }); | |
| 156 | 新增: consumer.start(); await flush(); consumer.stop(); release({ id: "request-1", connection_id: context.connection_id, request: { action: "chooseFolder" } }); await flush(); | |
| 157 | 新增: assert.equal(actions, 0); assert.match(body.error, /未执行/); assert.equal(timers.scheduled.length, 0); | |
| 158 | 新增:}); | |
| 159 | 新增: | |
| 160 | 新增:test("a native registration ticket never goes to a changed origin or starts an action", async () => { | |
| 161 | 新增: const timers = clock(); let requests = 0, actions = 0; | |
| 162 | 新增: const consumer = createAgentNativeConsumer({ ...timers, getOrigin: () => "http://localhost:17777", getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, | |
| 163 | 新增: native: async action => { if (action === "refreshSession") return { url: "http://attacker.invalid/#secret-ticket" }; actions++; }, | |
| 164 | 新增: api: async () => { requests++; }, | |
| 165 | 新增: }); | |
| 166 | 新增: consumer.start(); await flush(); consumer.stop(); | |
| 167 | 新增: assert.equal(requests, 0); assert.equal(actions, 0); | |
| 168 | 新增:}); | |
| 169 | 新增: | |
| 170 | 新增:test("expired window proof registers anew and retries only the original completion", async () => { | |
| 171 | 新增: const timers = clock(); let registrations = 0, actions = 0, claims = 0, completes = 0; | |
| 172 | 新增: const receipts = []; | |
| 173 | 新增: const consumer = createAgentNativeConsumer({ ...timers, getOrigin: () => "http://localhost:17777", getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, | |
| 174 | 新增: native: async action => action === "refreshSession" ? { url: `http://localhost:17777/#ticket-${registrations + 1}` } : (actions++, { ok: true }), | |
| 175 | 新增: api: async (path, body, method, headers) => { | |
| 176 | 新增: if (path === "/agent/native/window") { registrations++; assert.equal(body.ticket, `ticket-${registrations}`); return { window_proof: `proof-${registrations}` }; } | |
| 177 | 新增: assert.equal(headers["X-Cage-Agent-Window"], `proof-${registrations}`); | |
| 178 | 新增: if (path.includes("consumer=window")) { claims++; return { id: "original", connection_id: context.connection_id, request: { action: "chooseFolder" } }; } | |
| 179 | 新增: completes++; receipts.push(body); | |
| 180 | 新增: if (completes === 1) { const error = new Error("expired"); error.status = 403; throw error; } | |
| 181 | 新增: return {}; | |
| 182 | 新增: }, | |
| 183 | 新增: }); | |
| 184 | 新增: consumer.start(); await flush(); | |
| 185 | 新增: assert.equal(actions, 1); assert.equal(completes, 1); assert.equal(registrations, 1); | |
| 186 | 新增: await timers.tick(); consumer.stop(); | |
| 187 | 新增: assert.equal(registrations, 2); assert.equal(claims, 1); assert.equal(actions, 1); assert.equal(completes, 2); | |
| 188 | 新增: assert.deepEqual(receipts[0], receipts[1]); | |
| 189 | 新增: assert.ok(!JSON.stringify(receipts).includes("proof-")); | |
| 190 | 新增: assert.ok(!JSON.stringify(receipts).includes("ticket-")); | |
| 191 | 新增:}); | |
| 192 | 新增: | |
| 193 | 新增:test("independent desktop consumers retain distinct private window proofs", async () => { | |
| 194 | 新增: const proofs = new Set(); const consumers = []; let registrations = 0; | |
| 195 | 新增: for (let i = 0; i < 2; i++) { | |
| 196 | 新增: const timers = clock(); | |
| 197 | 新增: const consumer = createAgentNativeConsumer({ ...timers, getOrigin: () => "http://localhost:17777", getContext: () => context, storage: storage(), reload: () => {}, nativeAvailable: () => true, | |
| 198 | 新增: native: async () => ({ url: `http://localhost:17777/#window-${i}` }), | |
| 199 | 新增: api: async (path, body, method, headers) => { | |
| 200 | 新增: if (path === "/agent/native/window") { registrations++; return { window_proof: body.ticket + "-proof" }; } | |
| 201 | 新增: proofs.add(headers["X-Cage-Agent-Window"]); return {}; | |
| 202 | 新增: }, | |
| 203 | 新增: }); | |
| 204 | 新增: consumers.push(consumer); consumer.start(); | |
| 205 | 新增: } | |
| 206 | 新增: await flush(); consumers.forEach(consumer => consumer.stop()); | |
| 207 | 新增: assert.equal(registrations, 2); assert.equal(proofs.size, 2); | |
| 208 | 新增:}); | |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { reportDiagnostic } from "./diagnostics.mjs"; |
| 2 | 2 | import { httpErrorMessage, connectionErrorMessage, operationName, nativeFailureMessage } from "./error-message.mjs"; |
| 3 | 3 | import { assertConnection, connectionHeaders, getClientContext, isProjectSharesPath } from "./client-context.mjs"; |
| 4 | 新增:import { installAgentNativeConsumer } from "./agent-native.js"; | |
| 4 | 5 | let sessionRenewal; |
| 5 | 6 | async function responseError(response, path, method = "GET") { |
| 6 | 7 | const error = new Error( |
| @@ -30,11 +31,11 @@ async function renewSession() { | ||
| 30 | 31 | } |
| 31 | 32 | return sessionRenewal; |
| 32 | 33 | } |
| 33 | 删除:export async function api(path, body, method) { | |
| 34 | 新增:export async function api(path, body, method, headers = {}) { | |
| 34 | 35 | const connection = getClientContext().connection_id; |
| 35 | 36 | const options = { |
| 36 | 37 | method: method || (body === undefined ? "GET" : "POST"), |
| 37 | 删除: headers: { ...connectionHeaders(path), ...(body === undefined ? {} : { "Content-Type": "application/json" }) }, | |
| 38 | 新增: headers: { ...connectionHeaders(path), ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers }, | |
| 38 | 39 | body: body === undefined ? undefined : JSON.stringify(body), |
| 39 | 40 | }; |
| 40 | 41 | const send = async () => { |
| @@ -53,7 +54,7 @@ export async function api(path, body, method) { | ||
| 53 | 54 | let value; |
| 54 | 55 | try { value = await response.json(); } |
| 55 | 56 | catch (error) { reportDiagnostic("frontend", error); throw new Error(`${operationName(path, options.method)}失败:后台返回的结果格式无效。请重新连接;仍出现时在设置中导出诊断包。`, { cause: error }); } |
| 56 | 删除: if (path !== "/session" && (!path.startsWith("/client/") || isProjectSharesPath(path))) assertConnection(connection); | |
| 57 | 新增: if (path !== "/session" && !path.startsWith("/agent/native") && (!path.startsWith("/client/") || isProjectSharesPath(path))) assertConnection(connection); | |
| 57 | 58 | return value; |
| 58 | 59 | } |
| 59 | 60 | export async function uploadFile(path, file, { signal, onProgress } = {}) { |
| @@ -135,3 +136,5 @@ export function normalizeURL(text) { | ||
| 135 | 136 | ).href; |
| 136 | 137 | return "https://www.google.com/search?q=" + encodeURIComponent(value); |
| 137 | 138 | } |
| 139 | 新增: | |
| 140 | 新增:installAgentNativeConsumer({ api, native, nativeAvailable, getContext: getClientContext }); | |
| @@ -10,5 +10,6 @@ | ||
| 10 | 10 | |
| 11 | 11 | Discover installed capabilities before changing anything: <installed CLI> agent capabilities |
| 12 | 12 | Current source documentation may describe features absent from published releases. |
| 13 | 删除:The CLI targets the local workload at config_path. For a remote server, run it through authorized SSH on that server. | |
| 13 | 新增:The full CLI defaults to the local workload at config_path. Use --scope desktop for client configuration and --scope selected --connection GENERATION for the chosen workload. The lightweight client defaults to --scope client. Remote SSH execution is also supported. | |
| 14 | 新增:Run agent routes against the live listener to discover its registered HTTP routes. agent request and agent socket use the same API and permissions as the UI; native.submit invokes the actual desktop bridge and clientPreferences accesses the same window storage. | |
| 14 | 15 | Preserve existing profile data, accounts, projects and VM disks. Never disable network isolation or system security checks to complete setup. |