提交记录修改.github/workflows/macos-build.yml+2 −0看文件
修改.github/workflows/www.yml+4 −2看文件
新增AGENT-USE.md+9 −0看文件
修改README.md+1 −0看文件
新增cmd/cage/agent.go+357 −0看文件
新增cmd/cage/agent_test.go+76 −0看文件
修改cmd/cage/main.go+4 −0看文件
修改docs/README.md+1 −0看文件
新增docs/guide/agent.md+212 −0看文件
修改docs/guide/index.md+1 −0看文件
新增internal/workbench/agent.go+420 −0看文件
新增internal/workbench/agent_test.go+268 −0看文件
修改internal/workbench/control_lifecycle.go+2 −0看文件
修改internal/workbench/diagnostics.go+36 −12看文件
修改internal/workbench/jobs.go+2 −0看文件
修改internal/workbench/macos_login.go+3 −0看文件
修改internal/workbench/native_routes.go+3 −0看文件
修改internal/workbench/server.go+2 −1看文件
新增scripts/agent-bootstrap.test.mjs+65 −0看文件
新增scripts/agent-cli-smoke.mjs+68 −0看文件
新增www/public/agent-bootstrap.mjs+147 −0看文件
新增www/public/cage-install.sh+18 −0看文件
新增www/public/llms.txt+14 −0看文件
修改www/scripts/check-site.mjs+8 −0看文件
新增www/src/pages/agent.md.ts+6 −0看文件
新增www/src/pages/llms-full.txt.ts+1 −0看文件
| @@ -73,6 +73,8 @@ jobs: | ||
| 73 | 73 | go vet ./cmd/cage ./internal/cage ./internal/managedproxy ./internal/workbench |
| 74 | 74 | - name: Native application updater |
| 75 | 75 | run: bash scripts/test-app-updates.sh |
| 76 | 新增: - name: External Agent CLI with an isolated profile | |
| 77 | 新增: run: node scripts/agent-cli-smoke.mjs "$PWD/_output/Cage.app/Contents/Resources/cage" | |
| 76 | 78 | - name: Native account credential status |
| 77 | 79 | run: bash scripts/test-account-device.sh |
| 78 | 80 | - name: Patched networking and shared files |
| @@ -2,9 +2,9 @@ name: Website and public releases | ||
| 2 | 2 | on: |
| 3 | 3 | push: |
| 4 | 4 | branches: [main] |
| 5 | 删除: paths: ['www/**', 'assets/**', 'README*.md', 'docs/guide/**', 'scripts/verify-macos-release.sh', '.github/workflows/www.yml'] | |
| 5 | 新增: paths: ['www/**', 'assets/**', 'README*.md', 'docs/guide/**', 'scripts/agent-*.mjs', 'scripts/verify-macos-release.sh', '.github/workflows/www.yml'] | |
| 6 | 6 | pull_request: |
| 7 | 删除: paths: ['www/**', 'assets/**', 'README*.md', 'docs/guide/**', 'scripts/verify-macos-release.sh', '.github/workflows/www.yml'] | |
| 7 | 新增: paths: ['www/**', 'assets/**', 'README*.md', 'docs/guide/**', 'scripts/agent-*.mjs', 'scripts/verify-macos-release.sh', '.github/workflows/www.yml'] | |
| 8 | 8 | release: |
| 9 | 9 | types: [published] |
| 10 | 10 | workflow_dispatch: |
| @@ -61,6 +61,8 @@ jobs: | ||
| 61 | 61 | cache-dependency-path: www/package-lock.json |
| 62 | 62 | - run: npm ci --prefix www |
| 63 | 63 | - run: node --test www/scripts/sync-release.test.mjs |
| 64 | 新增: - name: Agent package discovery and verification | |
| 65 | 新增: run: node --test scripts/agent-bootstrap.test.mjs | |
| 64 | 66 | - name: Resolve the public download version |
| 65 | 67 | env: |
| 66 | 68 | RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }} |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:# Use Cage with an external Agent | |
| 2 | 新增: | |
| 3 | 新增:Start with [the complete Agent guide](docs/guide/agent.md). It covers locating the installed CLI, release download and checksum verification, platform installation, accounts, proxy setup, guest installation, settings, job tracking and recovery. | |
| 4 | 新增: | |
| 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 | 新增: | |
| 7 | 新增: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 | 新增: | |
| 9 | 新增:`AGENTS.md` contains repository contributor instructions. Product users and their agents should follow the usage guide above. | |
| @@ -104,6 +104,7 @@ macOS 和已签名 Windows 版本支持通过所选代理更新;Windows 未签 | ||
| 104 | 104 | |
| 105 | 105 | | 你要做什么 | 从这里开始 | |
| 106 | 106 | |---|---| |
| 107 | 新增:| 让自己的 Agent 下载、安装、配置和排查 Cage | [Agent 使用指南](https://lee-xeo.github.io/Claude-Cage/docs/agent/) | | |
| 107 | 108 | | 第一次安装、配置代理、打开项目 | [安装与首次启动](https://lee-xeo.github.io/Claude-Cage/docs/installation/) | |
| 108 | 109 | | 选择 macOS、Windows、Debian 或 Ubuntu 22.04 客机,使用原生开发工具 | [选择客机系统](https://lee-xeo.github.io/Claude-Cage/docs/guest-systems/) | |
| 109 | 110 | | 添加多个订阅、查看额度和分配终端 | [多账号与额度](https://lee-xeo.github.io/Claude-Cage/docs/accounts/) | |
| @@ -0,0 +1,357 @@ | ||
| 1 | 新增:package main | |
| 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 | 新增: "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 | 新增:) | |
| 21 | 新增: | |
| 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 | 新增: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 | |
| 357 | 新增:} | |
| @@ -0,0 +1,76 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "strings" | |
| 10 | 新增: "testing" | |
| 11 | 新增: "time" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestAgentCLIProtocolAndInit(t *testing.T) { | |
| 15 | 新增: path := filepath.Join(t.TempDir(), "profile", "config.json") | |
| 16 | 新增: run := func(args ...string) (int, agentReply) { | |
| 17 | 新增: t.Helper() | |
| 18 | 新增: var output bytes.Buffer | |
| 19 | 新增: code := runAgent(append(args, "--config", path), strings.NewReader(""), &output) | |
| 20 | 新增: var reply agentReply | |
| 21 | 新增: if json.Unmarshal(output.Bytes(), &reply) != nil || reply.Protocol != 1 { | |
| 22 | 新增: t.Fatalf("not one protocol reply: %s", output.String()) | |
| 23 | 新增: } | |
| 24 | 新增: return code, reply | |
| 25 | 新增: } | |
| 26 | 新增: if code, _ := run("capabilities"); code != 0 { | |
| 27 | 新增: t.Fatal(code) | |
| 28 | 新增: } | |
| 29 | 新增: if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) { | |
| 30 | 新增: t.Fatal("discovery created profile") | |
| 31 | 新增: } | |
| 32 | 新增: if code, _ := run("init"); code != 0 { | |
| 33 | 新增: t.Fatal(code) | |
| 34 | 新增: } | |
| 35 | 新增: before, _ := os.ReadFile(path) | |
| 36 | 新增: if code, _ := run("init"); code != 0 { | |
| 37 | 新增: t.Fatal("not idempotent") | |
| 38 | 新增: } | |
| 39 | 新增: after, _ := os.ReadFile(path) | |
| 40 | 新增: if !bytes.Equal(before, after) { | |
| 41 | 新增: t.Fatal("repeat init overwrote config") | |
| 42 | 新增: } | |
| 43 | 新增: for _, args := range [][]string{{"call", "status", "--input", "-"}, {"wat"}, {"doctor", "--wait", "1s"}, {"capabilities", "--wait", "-1s"}, {"call"}} { | |
| 44 | 新增: if code, _ := run(args...); code != 2 { | |
| 45 | 新增: t.Fatalf("usage accepted %v: %d", args, code) | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: if err := os.WriteFile(path, []byte("damaged"), 0600); err != nil { | |
| 49 | 新增: t.Fatal(err) | |
| 50 | 新增: } | |
| 51 | 新增: if code, reply := run("init"); code != 1 || reply.Error.Code != "config_invalid" { | |
| 52 | 新增: t.Fatal("damaged config silently replaced") | |
| 53 | 新增: } | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:func TestAgentCLIRejectsSecretArgumentsAndMalformedJSON(t *testing.T) { | |
| 57 | 新增: for _, input := range []string{`null`, `[]`, `{} {}`, `{"password":"secret"} trailing`} { | |
| 58 | 新增: var output bytes.Buffer | |
| 59 | 新增: code := runAgent([]string{"call", "account.unlock", "--input", "-", "--config", filepath.Join(t.TempDir(), "config.json")}, strings.NewReader(input), &output) | |
| 60 | 新增: if code != 2 || strings.Contains(output.String(), "secret") { | |
| 61 | 新增: t.Fatal(code, output.String()) | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: var output bytes.Buffer | |
| 65 | 新增: code := runAgent([]string{"call", "account.unlock", "--password", "do-not-echo"}, strings.NewReader(""), &output) | |
| 66 | 新增: if code != 2 || strings.Contains(output.String(), "do-not-echo") { | |
| 67 | 新增: t.Fatal(output.String()) | |
| 68 | 新增: } | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:func TestAgentWaitTimeoutKeepsOriginalJobID(t *testing.T) { | |
| 72 | 新增: data, err := agentWait(context.Background(), filepath.Join(t.TempDir(), "config.json"), "012345abcdef", time.Millisecond) | |
| 73 | 新增: if err == nil || data != nil || !strings.Contains(err.Error(), "job may still be running") { | |
| 74 | 新增: t.Fatal(string(data), err) | |
| 75 | 新增: } | |
| 76 | 新增:} | |
| @@ -34,6 +34,7 @@ import ( | ||
| 34 | 34 | const help = `Claude Cage — local isolated Claude development |
| 35 | 35 | |
| 36 | 36 | cage desktop Open the unified Cage workbench (desktop launcher) |
| 37 | 新增:cage agent Discover and use the versioned, JSON-only external Agent interface | |
| 37 | 38 | cage serve Run its private localhost control service |
| 38 | 39 | cage server-entry --json Issue a private SSH remote connection entry |
| 39 | 40 | cage container-configure --json Configure a Linux container from JSON stdin |
| @@ -89,6 +90,9 @@ func run() int { | ||
| 89 | 90 | fmt.Print(help) |
| 90 | 91 | return 0 |
| 91 | 92 | } |
| 93 | 新增: if args[0] == "agent" { | |
| 94 | 新增: return runAgent(args[1:], os.Stdin, os.Stdout) | |
| 95 | 新增: } | |
| 92 | 96 | if args[0] == "verify-web-assets" { |
| 93 | 97 | if len(args) != 1 { |
| 94 | 98 | return 2 |
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | | 你要做什么 | 从这里开始 | |
| 10 | 10 | |---|---| |
| 11 | 新增:| 让自己的 Agent 下载、安装、配置 Cage,跟踪任务并排查故障 | [Agent 使用指南](guide/agent.md) | | |
| 11 | 12 | | 选择 macOS、Windows、Linux 安装包,配置代理并打开第一个项目 | [开始使用](getting-started.md) | |
| 12 | 13 | | 选择与主机同类的客机系统,了解原生工具、镜像与数据保留 | [选择客机系统](guide/guest-systems.md) | |
| 13 | 14 | | 查看快捷键、文件保存、关闭与退出行为 | [日常使用](getting-started.md#日常使用) | |
| @@ -0,0 +1,212 @@ | ||
| 1 | 新增:--- | |
| 2 | 新增:title: 让 Agent 配置 Cage | |
| 3 | 新增:description: 给外部 Agent 的完整入口:下载校验、安装、配置代理与客机、任务跟踪、故障定位和恢复。 | |
| 4 | 新增:group: 开始使用 | |
| 5 | 新增:order: 5 | |
| 6 | 新增:keywords: Agent CLI JSON 自动化 配置 接口 安装 诊断 修复 capabilities doctor llms | |
| 7 | 新增:--- | |
| 8 | 新增: | |
| 9 | 新增:你可以把下面这段话交给自己的 Agent,让它根据你的目标准备 Cage。你只需提供自己的代理来源、选择工作环境,并在操作系统要求时完成授权。Cage 账户密码、Claude 登录、许可证确认和项目共享范围由你决定。 | |
| 10 | 新增: | |
| 11 | 新增:> 请阅读 https://lee-xeo.github.io/Claude-Cage/agent.md ,协助我安装、配置并验证 Cage。先检查本机安装和接口能力,再按实际状态操作;完成后告诉我环境是否就绪、网络是否通过检查,以及还需要我完成什么。保留所有现有账户、项目和虚拟机数据。 | |
| 12 | 新增: | |
| 13 | 新增:本页是当前源码与开发构建的接口说明。公开 Release 可能尚未包含 `cage agent`。安装后必须先运行能力探测;遇到未知命令时,使用该版本的界面和发行说明,或安装用户授权的较新构建。不要仅凭版本字符串推断接口已存在。 | |
| 14 | 新增: | |
| 15 | 新增:## Agent 从哪里开始 | |
| 16 | 新增: | |
| 17 | 新增:下文的 `cage` 代表 Cage 安装包内的后台 CLI。先找到实际文件;不要把桌面启动程序或 Linux 上同名的 Wayland 程序当作 CLI。 | |
| 18 | 新增: | |
| 19 | 新增:| 平台 | 默认 CLI 位置 | 调用示例 | | |
| 20 | 新增:| --- | --- | --- | | |
| 21 | 新增:| macOS | `/Applications/Cage.app/Contents/Resources/cage` | `"/Applications/Cage.app/Contents/Resources/cage" agent capabilities` | | |
| 22 | 新增:| Windows | `%LOCALAPPDATA%\Programs\Cage\resources\cage.exe`,自定义安装目录以实际位置为准 | `& "$env:LOCALAPPDATA\Programs\Cage\resources\cage.exe" agent capabilities` | | |
| 23 | 新增:| Linux | `/usr/bin/claude-cage` | `claude-cage agent capabilities` | | |
| 24 | 新增: | |
| 25 | 新增:`agent capabilities` 输出本构建的协议版本、操作清单、输入字段和退出码,不启动后台或创建配置。首次配置与每次升级后都先读取一次。机器阅读入口为 `/agent.md`、`/llms.txt`、`/llms-full.txt`,使用 Cage 的外部 Agent 从本页开始。 | |
| 26 | 新增: | |
| 27 | 新增:所有 `agent` 命令自动输出 JSON,`--json` 可省略。示例把 `cage` 作为占位命令;执行时替换为上表路径。`--config /absolute/path/config.json` 明确选择配置;省略时使用 `CLAUDE_CAGE_CONFIG`,再省略则使用用户主目录下的 `.claude-cage/config.json`。每次输出中的 `config_path` 是实际目标。桌面配置的远端选择不会改变这个目标;管理服务器时,在经过用户授权的 SSH 通道内,在服务器上运行同一接口并明确路径。 | |
| 28 | 新增: | |
| 29 | 新增:## 下载、校验与安装 | |
| 30 | 新增: | |
| 31 | 新增:下载助手位于官网的 `/agent-bootstrap.mjs`,需要 Node.js 20 或更新版本,无额外依赖。可以先下载并检查脚本,再执行。它只发现 Release、下载和校验安装包;输出后续安装步骤与参数数组。Agent 按平台执行安装,系统权限提示由用户处理。 | |
| 32 | 新增: | |
| 33 | 新增:macOS/Linux 也可先获取 `/cage-install.sh` 再运行,参数与下载助手相同,需要 Node 和 curl。`/install.sh` 保留给上游 agent-vm 兼容流程,安装 Cage 时使用本节列出的专用入口。 | |
| 34 | 新增: | |
| 35 | 新增:```sh | |
| 36 | 新增:curl --proto '=https' --proto-redir '=https' -fL \ | |
| 37 | 新增: https://lee-xeo.github.io/Claude-Cage/agent-bootstrap.mjs -o agent-bootstrap.mjs | |
| 38 | 新增:node agent-bootstrap.mjs plan --platform darwin-arm64 | |
| 39 | 新增:node agent-bootstrap.mjs download --platform darwin-arm64 \ | |
| 40 | 新增: --version v0.1.6-alpha-preview --destination /absolute/path/downloads | |
| 41 | 新增:``` | |
| 42 | 新增: | |
| 43 | 新增:Windows 可用 PowerShell 下载脚本后执行 `node .\agent-bootstrap.mjs plan --platform win32-amd64`;Linux 的平台参数为 `linux-amd64`。省略平台时自动识别当前 Node 进程的平台和架构。指定 `--version` 会固定发行标签;省略时查询 GitHub 的 latest Release,它可能不包含预发行版,也可能缺少某个平台的附件。 | |
| 44 | 新增: | |
| 45 | 新增:助手从同一标签读取安装包与 `SHA256SUMS`,拒绝不完整附件、重复校验项、HTTP 降级和校验不符。下载使用独立临时文件,成功后才生成目标文件;目标已存在时保留它并报错。失败后可以重新下载到新的目标目录。Windows 只有未签名预览包时,返回 `unsigned_package_requires_consent`;用户明确选择该预览后才添加 `--allow-unsigned`。 | |
| 46 | 新增: | |
| 47 | 新增:下载使用主机网络,需能访问 GitHub API 与 Release 附件。Node 24 支持通过 `node --use-env-proxy agent-bootstrap.mjs ...` 使用用户明确配置的 `HTTPS_PROXY` / `HTTP_PROXY`;也可使用用户现有的主机 TUN。不要回显代理凭据。较旧 Node 的 fetch 不自动采用这些环境代理;连接失败时先排查主机下载网络,避免反复重建 Cage 配置。 | |
| 48 | 新增: | |
| 49 | 新增:| 平台 | 安装与验证 | | |
| 50 | 新增:| --- | --- | | |
| 51 | 新增:| macOS | 只读挂载 DMG,检查应用签名与 Gatekeeper 结果,按[安装指南](installation.md)放入应用程序目录。更新前保存任务并停止旧环境;保留可恢复的旧应用,安装失败时回滚应用文件。不要移除隔离属性或关闭系统校验来继续安装。 | | |
| 52 | 新增:| Windows | 检查下载包的签名状态;在用户授权的安装上下文运行安装器。`/S` 支持静默安装;已有自定义安装目录以安装记录为准。系统安全提示、Hyper-V 启用与重启可能需要用户操作。 | | |
| 53 | 新增:| Linux | 在用户授权的权限上下文执行 `sudo apt-get install -- /absolute/path/Cage-版本-linux-amd64.deb`,由包管理器检查依赖。公共命令名是 `claude-cage`。 | | |
| 54 | 新增: | |
| 55 | 新增:安装、更新与卸载只处理应用文件。保留 `.claude-cage`、用户指定的数据目录、共享项目与持久虚拟机磁盘。已有账户重新出现创建界面时,首先核对 `config_path` 与原数据位置;不要创建替代账户或初始化旧数据目录。下载成功与应用已安装是两个状态;安装后验证真实 CLI 文件和 `agent capabilities`,再开始配置。 | |
| 56 | 新增: | |
| 57 | 新增:## 第一次配置的完整顺序 | |
| 58 | 新增: | |
| 59 | 新增:先明确用户希望使用哪类客机,以及哪个目录可以共享。Agent 可以探测主机条件、根据报告提出选择,不能替用户接受许可证、降低出口规则或授权未指定的主机目录。 | |
| 60 | 新增: | |
| 61 | 新增:```sh | |
| 62 | 新增:cage agent capabilities | |
| 63 | 新增:cage agent doctor | |
| 64 | 新增:cage agent init | |
| 65 | 新增:cage agent service.start | |
| 66 | 新增:cage agent call account.status | |
| 67 | 新增:cage agent host.inspect | |
| 68 | 新增:``` | |
| 69 | 新增: | |
| 70 | 新增:`init` 仅创建缺失的默认配置;已有有效配置会保留,损坏配置会报错。`service.start` 只启动缺失的本机后台,复用同一构建的现有后台,拒绝替换不匹配的构建。它不启动虚拟机。`doctor` 只读取当前状态,不启动服务、不更改网络或应用修复。 | |
| 71 | 新增: | |
| 72 | 新增:账户存在且已解锁时继续下一步。否则让用户在 Cage 中创建或解锁;用户选择通过 Agent 提供密码时,可用下面的私有输入格式调用 `account.create` 或 `account.unlock`。命令行参数不接受密码。账户创建只适用于真正空白的 profile。 | |
| 73 | 新增: | |
| 74 | 新增:```json | |
| 75 | 新增:{"username":"用户选择的名称","password":"用户提供的密码","confirm_password":"同一个密码"} | |
| 76 | 新增:``` | |
| 77 | 新增: | |
| 78 | 新增:```sh | |
| 79 | 新增:cage agent call account.create --input /private/path/account.json | |
| 80 | 新增:cage agent call account.unlock --input - | |
| 81 | 新增:``` | |
| 82 | 新增: | |
| 83 | 新增:`--input -` 读取一个完整 JSON 对象后等待 EOF。Agent 应通过子进程的标准输入传递凭据,或使用访问受限的临时文件并及时清理。不要把含密码的示例值、订阅链接或节点密钥写进共享日志、提交记录、聊天回显和 shell 历史。这个接口面向用户授权、在主机同一操作系统账户下运行的 Agent,权限与本机工作台一致;它不是给不受信任插件使用的受限远程接口。 | |
| 84 | 新增: | |
| 85 | 新增:### 导入代理并确认出口 | |
| 86 | 新增: | |
| 87 | 新增:先读 `proxy.status`。已有可用来源时复用,避免重复导入。首次导入可用用户提供的订阅链接,也可用私有文件中的 Clash/Mihomo 配置或分享链接。 | |
| 88 | 新增: | |
| 89 | 新增:```json | |
| 90 | 新增:{"name":"我的代理","url":"https://用户自己的订阅地址","interval_hours":0,"host_download":true} | |
| 91 | 新增:``` | |
| 92 | 新增: | |
| 93 | 新增:```sh | |
| 94 | 新增:cage agent call proxy.import --input /private/path/subscription.json --wait 2m | |
| 95 | 新增:cage agent call proxy.status | |
| 96 | 新增:``` | |
| 97 | 新增: | |
| 98 | 新增:`host_download:true` 明确允许主机联网下载这份订阅,仅用于订阅获取;客机不会因此获得直连回退。已有 Cage 代理时,可省略它让订阅经过现有代理。不要自动从本机浏览器、代理软件或其他 Agent 的凭据文件提取订阅。 | |
| 99 | 新增: | |
| 100 | 新增:从返回的来源和节点列表选择用户要求的出口;不要把订阅中的第一个节点当成用户已经同意的出口。 | |
| 101 | 新增: | |
| 102 | 新增:```json | |
| 103 | 新增:{"node_id":"proxy.status 返回的节点 ID"} | |
| 104 | 新增:``` | |
| 105 | 新增: | |
| 106 | 新增:```sh | |
| 107 | 新增:cage agent call proxy.select --input /private/path/selection.json --wait 2m | |
| 108 | 新增:cage agent call proxy.status | |
| 109 | 新增:``` | |
| 110 | 新增: | |
| 111 | 新增:链式代理使用 `proxy.route`,输入 `{"node_ids":["入口ID","最终出口ID"]}`,顺序为入口到出口。更新订阅使用 `proxy.refresh` 和已有来源 `id`;`proxy.import` 每次创建来源,不能盲目重试。成功应用代理只表示代理已准备好,客机启动后的安全检查还需单独验证。 | |
| 112 | 新增: | |
| 113 | 新增:### 准备环境并打开项目 | |
| 114 | 新增: | |
| 115 | 新增:```sh | |
| 116 | 新增:cage agent call guest.options | |
| 117 | 新增:cage agent call guest.match | |
| 118 | 新增:cage agent call storage.get | |
| 119 | 新增:cage agent call resources.get | |
| 120 | 新增:cage agent call settings.get | |
| 121 | 新增:``` | |
| 122 | 新增: | |
| 123 | 新增:根据实际可用性选择系统。`guest.match` 给出匹配主机版本的干净镜像方案;将返回的 `key` 作为 `clone_key`,将 `plan.host.system` 作为 `guest_system` 传给 `environment.start`。镜像下载量、磁盘、主机权限和系统授权条件见[客机系统指南](guest-systems.md)。它不复制主机账户和个人文件。已有客机应继续原安装,保留原系统与介质信息。 | |
| 124 | 新增: | |
| 125 | 新增:首次需要换存储位置时,在安装前用 `storage.set`,输入 `directory`、`previous`、`migrate`;后两项分别来自 `storage.get` 的 `directory` 和 `has_environment`。已有环境的迁移会停止任务并保留备份,应先保存工作。资源配置用 `resources.set` 的 `allocation` 对象;修改保存后再以 `{}` 调用应用资源,会重启环境。容器资源由服务器部署管理。 | |
| 126 | 新增: | |
| 127 | 新增:只发送需要修改的设置,先预检再应用;未指定字段会保留,包括出口规则对象中未指定的 IP、国家和城市基准。`null` 不用于清空字段。 | |
| 128 | 新增: | |
| 129 | 新增:```json | |
| 130 | 新增:{"patch":{"auto_timezone":true,"auto_language":true},"dry_run":true} | |
| 131 | 新增:``` | |
| 132 | 新增: | |
| 133 | 新增:```sh | |
| 134 | 新增:cage agent call settings.patch --input /private/path/settings-check.json | |
| 135 | 新增:# 应用时把 dry_run 改为 false,再提交同一 patch。 | |
| 136 | 新增:cage agent call settings.patch --input /private/path/settings-apply.json --wait 2m | |
| 137 | 新增:cage agent call environment.start --input /private/path/guest-choice.json --wait 30m | |
| 138 | 新增:``` | |
| 139 | 新增: | |
| 140 | 新增:已有环境的 `environment.start` 可以不带输入。首次选择的 JSON 字段为 `guest_system`、`clone_key` 或需要的 `media`、`sha256`;只在用户明确接受对应条款时传 `editor_terms:true`。可用系统以 `guest.options` 为准。安装成功且 `guest.options.activate:true` 时调用 `guest.activate`,随后重新调用 `service.start` 并读取状态。激活会让旧后台退出;请求中断时先核对安装状态再决定下一步。 | |
| 141 | 新增: | |
| 142 | 新增:系统首次设置、macOS 权限、Windows 登录或重启需要用户完成时,报告具体需要做的事和恢复查询命令。不要用无限重试掩盖等待用户操作。安装进度在作业的 `setup_progress` 中;`prepared`、安装完成、运行和联网分别检查。 | |
| 143 | 新增: | |
| 144 | 新增:```sh | |
| 145 | 新增:cage agent call status | |
| 146 | 新增:cage agent call initialization.status | |
| 147 | 新增:cage agent call network.check --wait 5m | |
| 148 | 新增:``` | |
| 149 | 新增: | |
| 150 | 新增:以 `status.ready`、`vm_running` 以及 `safety` 中当前配置对应的网络检查与授权共同判断可用性;`proxy.status.network_open` 可辅助检查外网是否已放行。网络暂停时保持用户的暂停意图,只有用户要求恢复联网才运行 `network.check`。完成首次引导使用 `initialization.set` 的 `{"action":"complete"}`,后台会再次核对环境与网络状态。 | |
| 151 | 新增: | |
| 152 | 新增:打开项目使用 `project.open`:`{"workspace":"用户授权的绝对路径","add":true,"activate":true}`。它会让客机访问这个目录,改动会影响主机文件。返回 `approval` 表示仍需在本机 Cage 窗口完成系统授权。Claude 的服务登录仍在 Cage 内的官方工具中完成;本接口不会导入主机 Claude 凭据。 | |
| 153 | 新增: | |
| 154 | 新增:## JSON 结果和异步任务 | |
| 155 | 新增: | |
| 156 | 新增:每次命令的 stdout 只有一个 JSON 对象。格式示例: | |
| 157 | 新增: | |
| 158 | 新增:```json | |
| 159 | 新增:{"protocol":1,"version":"构建版本","config_path":"绝对配置路径","status":"accepted","data":{"id":"012345abcdef","kind":"start","running":true,"message":"正在准备…"}} | |
| 160 | 新增:``` | |
| 161 | 新增: | |
| 162 | 新增:| 字段或退出码 | 含义 | | |
| 163 | 新增:| --- | --- | | |
| 164 | 新增:| `status: completed`,退出 0 | 本次读取或同步操作完成;异步作业已确认成功。仍需根据数据核对环境和网络是否达到目标。 | | |
| 165 | 新增:| `status: accepted`,退出 0 | 作业被接受,仍在运行;保存 `data.id` 并查询。 | | |
| 166 | 新增:| `status: error`,退出 1 | 操作失败,查看稳定的 `error.code`、`message`、`next_action` 和 `retryable`。 | | |
| 167 | 新增:| 退出 2 | 命令或输入错误,修正后再提交。 | | |
| 168 | 新增:| 退出 3 | 需要用户解锁或完成授权。 | | |
| 169 | 新增:| 退出 4,`wait_timeout` | 本次等待结束,后台任务可能继续;查询原任务,避免重复提交。 | | |
| 170 | 新增: | |
| 171 | 新增:```sh | |
| 172 | 新增:cage agent job 012345abcdef | |
| 173 | 新增:cage agent job 012345abcdef --wait 30m | |
| 174 | 新增:``` | |
| 175 | 新增: | |
| 176 | 新增:`--wait` 为有限等待,范围为 0 到 24 小时;不指定时立即返回。等待或客户端断开不会自动取消作业。后台只保留最近一个作业,后续作业会替换查询记录,重启也可能失去记录。`job_not_found`、`outcome_unknown` 或连接中断后,先读 `status` 和相应配置,核对副作用;不要把其他任务成功当成原任务成功。`job_canceled` 单独表示取消,不能视为完成。 | |
| 177 | 新增: | |
| 178 | 新增:输入必须是单个 JSON 对象,最大 12 MiB。未知命令和字段会被拒绝。能力清单的 `input_schema` 描述允许字段;当前平台、系统状态和字段组合仍由后台验证。输出错误与任务日志会脱敏,正常字段中的项目路径、节点 ID、镜像计划和设置 URL 会保留以支持后续操作;这些结果仍属于用户私有数据。 | |
| 179 | 新增: | |
| 180 | 新增:## 定位问题与恢复 | |
| 181 | 新增: | |
| 182 | 新增:先运行 `doctor`,核对配置路径、账户和后台,再用 `status`、`proxy.status`、`environment.versions` 找到失败阶段。修复后重复对应查询,只有真实状态达到目标才报告恢复成功。 | |
| 183 | 新增: | |
| 184 | 新增:| 稳定错误码或可见状态 | Agent 的下一步 | | |
| 185 | 新增:| --- | --- | | |
| 186 | 新增:| `config_missing` | 核对用户数据位置;真正首次使用才运行 `init`。 | | |
| 187 | 新增:| `config_invalid`、`private_file_permissions` | 保留配置与磁盘,导出诊断,检查原文件和权限;不要覆盖整个 profile。 | | |
| 188 | 新增:| `service_unavailable` | 核对实际 CLI 与路径,执行 `service.start`;失败时导出离线诊断。 | | |
| 189 | 新增:| `controller_mismatch` | 使用与运行后台同一应用内的 CLI;更新需要保存并停止已有任务,Agent 不会自动接管。 | | |
| 190 | 新增:| `config_path_mismatch` | 同一目录的后台使用了另一个配置文件名;改用原后台的绝对配置路径,保留所有现有文件。 | | |
| 191 | 新增:| `account_locked` | 用户在 Cage 解锁,或通过私有输入调用 `account.unlock`。 | | |
| 192 | 新增:| `request_rejected`、`invalid_input` | 读取本构建能力与错误说明,修正字段或节点/来源 ID;不要重复原请求。 | | |
| 193 | 新增:| `state_conflict`、`service_busy` | 读取当前任务和系统状态;有在途任务时等待原任务完成。 | | |
| 194 | 新增:| `unsupported_operation` | 检查当前平台和客机的能力,使用对应版本指南。 | | |
| 195 | 新增:| `job_failed` | 保留 `data.error` 与脱敏的任务日志,检查当前配置、来源可用性、空间与主机条件。 | | |
| 196 | 新增:| `outcome_unknown`、`job_not_found` | 读取实际副作用;代理导入、安装和迁移都不能盲目重新提交。 | | |
| 197 | 新增:| 外网未放行或检查失败 | 检查所选代理、链路、出口规则、时间和位置;保持失败时关闭外网。用户授权后可切换节点或重检,不自动改为直连或降低规则。 | | |
| 198 | 新增:| `user_action_required`、项目 `approval`、首次系统设置未完成 | 告诉用户在哪个窗口完成哪项操作;完成后查询原状态继续。 | | |
| 199 | 新增: | |
| 200 | 新增:```sh | |
| 201 | 新增:cage agent diagnostics --output /absolute/path/new-cage-diagnostics.zip | |
| 202 | 新增:``` | |
| 203 | 新增: | |
| 204 | 新增:诊断导出在后台不可用时也能收集主机日志;可连接时尝试补充客机信息。使用新的输出文件名,已有文件会保留。诊断包经过现有脱敏流程,分享前仍由用户决定。不要把原始配置、订阅地址、密钥、账户文件或虚拟机磁盘作为诊断附件自动上传。 | |
| 205 | 新增: | |
| 206 | 新增:更新组件用 `environment.update`,更新工具用 `environment.tools`,均可通过作业接口跟踪。`environment.stop` 会终止环境内活动任务,保留磁盘和登录资料。应用升级、跨版本回滚及卸载仍遵循[维护与数据指南](maintenance.md),以安装器和系统包管理器为入口。 | |
| 207 | 新增: | |
| 208 | 新增:`status.can_restore:true` 时可用 `settings.restore` 恢复已保存的上一份设置并重启环境;这会中断现有任务,先保存工作。配置文件本身已经损坏、路径选错或账户无法读取时,保留原文件并先核对备份,不能用恢复命令代替数据定位。 | |
| 209 | 新增: | |
| 210 | 新增:## 交付给用户的结果 | |
| 211 | 新增: | |
| 212 | 新增:完成后用几句话说明:实际安装的版本和路径、使用的配置与客机、代理是否应用、环境是否运行、网络检查是否通过、项目是否连接。列出需要用户完成的授权和登录,以及尚未验证的范围。仅完成下载、模拟请求或单平台编译时,分别报告,不写成完整安装或三平台实测成功。 | |
| @@ -29,6 +29,7 @@ Cage 把终端、浏览器、编辑器和官方 Claude Desktop 放进同一个 | ||
| 29 | 29 | |
| 30 | 30 | | 你想做什么 | 阅读哪篇 | |
| 31 | 31 | | --- | --- | |
| 32 | 新增:| 把安装、配置与排障交给自己的 Agent | [让 Agent 配置 Cage](agent.md) | | |
| 32 | 33 | | 安装应用、换盘、准备本机虚拟化 | [安装与首次启动](installation.md) | |
| 33 | 34 | | 使用与主机同类的系统、选择原生开发工具 | [选择客机系统](guest-systems.md) | |
| 34 | 35 | | 导入订阅、连接住宅代理、设置出口规则 | [网络与代理](network.md) | |
| @@ -0,0 +1,420 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:// The agent adapter uses the same authenticated local workload as the desktop. | |
| 4 | 新增:// It never follows the desktop gateway's currently selected remote connection. | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "errors" | |
| 10 | 新增: "io" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "net/url" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "reflect" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "time" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:const AgentProtocol = 1 | |
| 22 | 新增: | |
| 23 | 新增:type AgentOperation struct { | |
| 24 | 新增: Name string `json:"name"` | |
| 25 | 新增: Description string `json:"description"` | |
| 26 | 新增: Mutates bool `json:"mutates"` | |
| 27 | 新增: InputSchema map[string]any `json:"input_schema"` | |
| 28 | 新增: method, path string | |
| 29 | 新增:} | |
| 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. | |
| 34 | 新增:func AgentOperations() []AgentOperation { | |
| 35 | 新增: object := func(fields map[string]string) map[string]any { | |
| 36 | 新增: properties := map[string]any{} | |
| 37 | 新增: for name, kind := range fields { | |
| 38 | 新增: if kind == "array" { | |
| 39 | 新增: properties[name] = map[string]any{"type": kind, "items": map[string]string{"type": "string"}} | |
| 40 | 新增: } else { | |
| 41 | 新增: properties[name] = map[string]string{"type": kind} | |
| 42 | 新增: } | |
| 43 | 新增: } | |
| 44 | 新增: return map[string]any{"type": "object", "properties": properties, "additionalProperties": false} | |
| 45 | 新增: } | |
| 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 | 新增: } | |
| 77 | 新增: var ops []AgentOperation | |
| 78 | 新增: add := func(name, description, method, path string, schema map[string]any) { | |
| 79 | 新增: ops = append(ops, AgentOperation{Name: name, Description: description, Mutates: method != "GET", InputSchema: schema, method: method, path: path}) | |
| 80 | 新增: } | |
| 81 | 新增: get := func(name, description, path string) { add(name, description, "GET", path, object(nil)) } | |
| 82 | 新增: post := func(name, description, path string, schema map[string]any) { | |
| 83 | 新增: add(name, description, "POST", path, schema) | |
| 84 | 新增: } | |
| 85 | 新增: get("status", "Environment readiness, network checks and current job", "/api/status") | |
| 86 | 新增: 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"})) | |
| 88 | 新增: post("account.unlock", "Unlock using a user-provided password via private input", "/api/account/unlock", object(map[string]string{"password": "string"})) | |
| 89 | 新增: get("settings.get", "Read settings without proxy credentials", "/api/settings") | |
| 90 | 新增: 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"})) | |
| 91 | 新增: // Include the production Settings schema inside the patch field. | |
| 92 | 新增: ops[len(ops)-1].InputSchema["properties"].(map[string]any)["patch"] = from(Settings{}) | |
| 93 | 新增: ops[len(ops)-1].InputSchema["properties"].(map[string]any)["patch"].(map[string]any)["properties"].(map[string]any)["exit_policy"] = object(map[string]string{"mode": "string", "scope": "string", "ip": "string", "country_code": "string", "region": "string", "city": "string"}) | |
| 94 | 新增: post("settings.restore", "Restore the saved previous settings and restart the environment; inspect status and obtain permission to interrupt work first", "/api/restore", object(nil)) | |
| 95 | 新增: get("proxy.status", "List source and node IDs without subscription URLs or node secrets", "/api/proxy") | |
| 96 | 新增: proxy := from(proxyInput{}) | |
| 97 | 新增: for _, action := range []string{"import", "refresh", "edit", "delete", "select", "route", "restart", "stop"} { | |
| 98 | 新增: post("proxy."+action, "Proxy operation; import creates a source, refresh updates an existing source. Read state before retrying. select/route applies the route", "/api/proxy/"+action, proxy) | |
| 99 | 新增: } | |
| 100 | 新增: get("guest.options", "Available guest systems and resumable installation state", "/api/environment/guest-systems") | |
| 101 | 新增: get("guest.match", "Inspect a host-matching clean image plan; pass key as clone_key and plan.host.system as guest_system to environment.start", "/api/environment/guest-systems/clone") | |
| 102 | 新增: post("guest.activate", "Activate an installed guest; controller may retire, reconnect afterwards", "/api/environment/guest-systems/activate", object(nil)) | |
| 103 | 新增: get("initialization.status", "Read initial setup state", "/api/environment/initialization") | |
| 104 | 新增: post("initialization.set", "action: begin, install or complete; complete requires verified readiness", "/api/environment/initialization", object(map[string]string{"action": "string"})) | |
| 105 | 新增: post("environment.start", "Start or resume installation. Omit guest_system for an existing environment; use guest.options for supported choices", "/api/start", from(guestInstallRequest{})) | |
| 106 | 新增: post("environment.stop", "Stop the environment and active terminals; preserves persistent data", "/api/stop", object(nil)) | |
| 107 | 新增: get("environment.versions", "Read installed component and tool versions", "/api/environment/versions") | |
| 108 | 新增: post("environment.update", "Update guest components; may restart guest services", "/api/environment/update", object(nil)) | |
| 109 | 新增: post("environment.tools", "Update tools to this build's versions", "/api/environment/tools", object(nil)) | |
| 110 | 新增: get("resources.get", "Read platform resource limits and recommendations", "/api/environment/resources") | |
| 111 | 新增: post("resources.set", "Save allocation={automatic,memory_gib,cpus}; send {} separately to apply and restart", "/api/environment/resources", object(map[string]string{"allocation": "object"})) | |
| 112 | 新增: ops[len(ops)-1].InputSchema["properties"].(map[string]any)["allocation"] = object(map[string]string{"automatic": "boolean", "memory_gib": "integer", "cpus": "integer"}) | |
| 113 | 新增: get("storage.get", "Read storage location and migration prerequisites", "/api/environment/storage") | |
| 114 | 新增: post("storage.set", "Migrate using the previous directory and has_environment value from storage.get; stops running tasks", "/api/environment/storage", object(map[string]string{"directory": "string", "previous": "string", "migrate": "boolean"})) | |
| 115 | 新增: post("network.check", "Run existing safety checks; may reopen networking when checks pass", "/api/safety/check", object(nil)) | |
| 116 | 新增: post("network.pause", "Close external networking and persist pause intent", "/api/safety/close", object(nil)) | |
| 117 | 新增: 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"})) | |
| 118 | 新增: get("diagnostics.status", "Read log collection status", "/api/diagnostics") | |
| 119 | 新增: return ops | |
| 120 | 新增:} | |
| 121 | 新增: | |
| 122 | 新增:type AgentError struct { | |
| 123 | 新增: Code string `json:"code"` | |
| 124 | 新增: Message string `json:"message"` | |
| 125 | 新增: NextAction string `json:"next_action"` | |
| 126 | 新增: Retryable bool `json:"retryable"` | |
| 127 | 新增: HTTPStatus int `json:"http_status,omitempty"` | |
| 128 | 新增:} | |
| 129 | 新增: | |
| 130 | 新增:func (e *AgentError) Error() string { return e.Message } | |
| 131 | 新增: | |
| 132 | 新增:func agentHTTPError(code int) *AgentError { | |
| 133 | 新增: e := &AgentError{Code: "request_rejected", Message: "Cage rejected the operation. Check the input and run doctor.", NextAction: "doctor", HTTPStatus: code} | |
| 134 | 新增: switch code { | |
| 135 | 新增: case 401: | |
| 136 | 新增: e.Code = "authentication_failed" | |
| 137 | 新增: e.NextAction = "service.start" | |
| 138 | 新增: case 423: | |
| 139 | 新增: e.Code = "account_locked" | |
| 140 | 新增: e.Message = "Unlock Cage before configuring the environment." | |
| 141 | 新增: e.NextAction = "account.unlock" | |
| 142 | 新增: case 403: | |
| 143 | 新增: e.Code = "user_action_required" | |
| 144 | 新增: e.Message = "This operation requires a local system or account action." | |
| 145 | 新增: e.NextAction = "open_desktop" | |
| 146 | 新增: case 409: | |
| 147 | 新增: e.Code = "state_conflict" | |
| 148 | 新增: e.Message = "The environment state does not permit this operation. Read status before retrying." | |
| 149 | 新增: e.NextAction = "status" | |
| 150 | 新增: case 410: | |
| 151 | 新增: e.Code = "job_not_found" | |
| 152 | 新增: e.Message = "The original job is no longer available. Inspect state before submitting again." | |
| 153 | 新增: e.NextAction = "status" | |
| 154 | 新增: case 404: | |
| 155 | 新增: e.Code = "unsupported_operation" | |
| 156 | 新增: e.Message = "This controller or guest does not support the operation." | |
| 157 | 新增: e.NextAction = "capabilities" | |
| 158 | 新增: case 429, 503: | |
| 159 | 新增: e.Code = "service_busy" | |
| 160 | 新增: e.NextAction = "status" | |
| 161 | 新增: e.Retryable = true | |
| 162 | 新增: } | |
| 163 | 新增: return e | |
| 164 | 新增:} | |
| 165 | 新增: | |
| 166 | 新增:// AgentStartService starts only an absent service. It never hands off, upgrades | |
| 167 | 新增:// or stops an existing controller as a side effect of an agent call. | |
| 168 | 新增:func AgentStartService(ctx context.Context, configPath string) error { | |
| 169 | 新增: profile := filepath.Dir(configPath) | |
| 170 | 新增: c, err := connectController(profile) | |
| 171 | 新增: if err == nil { | |
| 172 | 新增: defer c.close() | |
| 173 | 新增: return agentCheckController(c, configPath) | |
| 174 | 新增: } | |
| 175 | 新增: if !errors.Is(err, errControllerUnavailable) || !controllerLockFree(profile) { | |
| 176 | 新增: return &AgentError{Code: "service_unavailable", Message: "The controller cannot be authenticated. Preserve its data and inspect diagnostics.", NextAction: "doctor"} | |
| 177 | 新增: } | |
| 178 | 新增: if err := startController(configPath); err != nil { | |
| 179 | 新增: return &AgentError{Code: "service_start_failed", Message: "Cage could not start its controller.", NextAction: "doctor"} | |
| 180 | 新增: } | |
| 181 | 新增: timer := time.NewTicker(100 * time.Millisecond) | |
| 182 | 新增: defer timer.Stop() | |
| 183 | 新增: for { | |
| 184 | 新增: select { | |
| 185 | 新增: case <-ctx.Done(): | |
| 186 | 新增: return &AgentError{Code: "service_start_timeout", Message: "The controller has not become ready. It may still be starting.", NextAction: "doctor", Retryable: true} | |
| 187 | 新增: case <-timer.C: | |
| 188 | 新增: c, err := connectController(profile) | |
| 189 | 新增: if err == nil { | |
| 190 | 新增: defer c.close() | |
| 191 | 新增: return agentCheckController(c, configPath) | |
| 192 | 新增: } | |
| 193 | 新增: } | |
| 194 | 新增: } | |
| 195 | 新增:} | |
| 196 | 新增: | |
| 197 | 新增:func agentCheckController(c *controllerClient, configPath string) error { | |
| 198 | 新增: want, err := currentController() | |
| 199 | 新增: if err != nil || !want.matches(c.launch.Controller) || c.launch.DesktopGateway || c.launch.ClientOnly { | |
| 200 | 新增: return &AgentError{Code: "controller_mismatch", Message: "Use the CLI shipped with the running workload. No controller was replaced.", NextAction: "open_desktop"} | |
| 201 | 新增: } | |
| 202 | 新增: if filepath.Clean(c.launch.ConfigPath) != filepath.Clean(configPath) { | |
| 203 | 新增: return &AgentError{Code: "config_path_mismatch", Message: "This directory's controller uses a different configuration filename. Use its original absolute config path.", NextAction: "doctor"} | |
| 204 | 新增: } | |
| 205 | 新增: return nil | |
| 206 | 新增:} | |
| 207 | 新增: | |
| 208 | 新增:func agentConnect(ctx context.Context, configPath string) (*controllerClient, error) { | |
| 209 | 新增: c, err := connectController(filepath.Dir(configPath)) | |
| 210 | 新增: if err != nil { | |
| 211 | 新增: return nil, &AgentError{Code: "service_unavailable", Message: "The local Cage controller is unavailable. Run service.start or doctor.", NextAction: "service.start"} | |
| 212 | 新增: } | |
| 213 | 新增: fail := func(err error) (*controllerClient, error) { c.close(); return nil, err } | |
| 214 | 新增: if err := agentCheckController(c, configPath); err != nil { | |
| 215 | 新增: return fail(err) | |
| 216 | 新增: } | |
| 217 | 新增: u, _ := url.Parse(c.launch.URL) | |
| 218 | 新增: code, err := c.callContext(ctx, "POST", "/api/session", map[string]string{"token": u.Fragment}, nil) | |
| 219 | 新增: if err != nil || code != 200 { | |
| 220 | 新增: return fail(agentHTTPError(401)) | |
| 221 | 新增: } | |
| 222 | 新增: // Same proof as the existing local desktop transport. Possession is checked | |
| 223 | 新增: // through the private launcher record; account locking still applies. | |
| 224 | 新增: c.client.Jar.SetCookies(u, []*http.Cookie{{Name: cookieName + "_" + u.Port() + "-desktop", Value: trustedViewProof(c.record.Token), Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode}}) | |
| 225 | 新增: return c, nil | |
| 226 | 新增:} | |
| 227 | 新增: | |
| 228 | 新增: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"} | |
| 238 | 新增:} | |
| 239 | 新增: | |
| 240 | 新增:func agentValidateInput(input json.RawMessage, schema map[string]any) error { | |
| 241 | 新增: if len(input) == 0 { | |
| 242 | 新增: input = json.RawMessage(`{}`) | |
| 243 | 新增: } | |
| 244 | 新增: var value map[string]json.RawMessage | |
| 245 | 新增: if json.Unmarshal(input, &value) != nil || value == nil { | |
| 246 | 新增: return &AgentError{Code: "invalid_input", Message: "Expected one JSON object.", NextAction: "capabilities"} | |
| 247 | 新增: } | |
| 248 | 新增: properties := schema["properties"].(map[string]any) | |
| 249 | 新增: for key := range value { | |
| 250 | 新增: if _, ok := properties[key]; !ok { | |
| 251 | 新增: return &AgentError{Code: "invalid_input", Message: "Unknown input field; read the operation's input_schema.", NextAction: "capabilities"} | |
| 252 | 新增: } | |
| 253 | 新增: } | |
| 254 | 新增: return nil | |
| 255 | 新增:} | |
| 256 | 新增: | |
| 257 | 新增:func AgentJob(ctx context.Context, configPath, id string) (json.RawMessage, error) { | |
| 258 | 新增: if len(id) != 12 || strings.Trim(id, "0123456789abcdef") != "" { | |
| 259 | 新增: return nil, &AgentError{Code: "invalid_input", Message: "Expected a 12-character job id.", NextAction: "status"} | |
| 260 | 新增: } | |
| 261 | 新增: return agentRequest(ctx, configPath, "GET", "/api/agent/jobs/"+id, nil) | |
| 262 | 新增:} | |
| 263 | 新增: | |
| 264 | 新增: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 | |
| 300 | 新增:} | |
| 301 | 新增: | |
| 302 | 新增:func (s *Server) agentRoutes(mux *http.ServeMux) { | |
| 303 | 新增: mux.HandleFunc("GET /api/agent/jobs/{id}", func(w http.ResponseWriter, r *http.Request) { | |
| 304 | 新增: job := s.jobs.snapshot() | |
| 305 | 新增: if job.ID == "" || job.ID != r.PathValue("id") { | |
| 306 | 新增: http.Error(w, "Original job no longer available", http.StatusGone) | |
| 307 | 新增: return | |
| 308 | 新增: } | |
| 309 | 新增: jsonReply(w, job) | |
| 310 | 新增: }) | |
| 311 | 新增: mux.HandleFunc("POST /api/agent/settings", s.agentSettings) | |
| 312 | 新增:} | |
| 313 | 新增: | |
| 314 | 新增:func agentRedact(data string) string { | |
| 315 | 新增: var value any | |
| 316 | 新增: if json.Unmarshal([]byte(data), &value) != nil { | |
| 317 | 新增: return diagnostics.Redact(data) | |
| 318 | 新增: } | |
| 319 | 新增: var clean func(any) | |
| 320 | 新增: clean = func(value any) { | |
| 321 | 新增: switch v := value.(type) { | |
| 322 | 新增: case map[string]any: | |
| 323 | 新增: for key, item := range v { | |
| 324 | 新增: if text, ok := item.(string); ok && (key == "error" || key == "log" || key == "message" || key == "reason" || strings.HasSuffix(key, "_error")) { | |
| 325 | 新增: v[key] = diagnostics.Redact(text) | |
| 326 | 新增: } else { | |
| 327 | 新增: clean(item) | |
| 328 | 新增: } | |
| 329 | 新增: } | |
| 330 | 新增: case []any: | |
| 331 | 新增: for _, item := range v { | |
| 332 | 新增: clean(item) | |
| 333 | 新增: } | |
| 334 | 新增: } | |
| 335 | 新增: } | |
| 336 | 新增: clean(value) | |
| 337 | 新增: body, _ := json.Marshal(value) | |
| 338 | 新增: return string(body) | |
| 339 | 新增:} | |
| 340 | 新增: | |
| 341 | 新增:func (s *Server) agentSettings(w http.ResponseWriter, r *http.Request) { | |
| 342 | 新增: var in struct { | |
| 343 | 新增: Patch map[string]json.RawMessage `json:"patch"` | |
| 344 | 新增: DryRun bool `json:"dry_run"` | |
| 345 | 新增: } | |
| 346 | 新增: if !readJSON(w, r, &in) { | |
| 347 | 新增: return | |
| 348 | 新增: } | |
| 349 | 新增: if len(in.Patch) == 0 { | |
| 350 | 新增: http.Error(w, "patch must contain at least one setting", 400) | |
| 351 | 新增: return | |
| 352 | 新增: } | |
| 353 | 新增: propose := func() (savedProfile, error) { | |
| 354 | 新增: old, err := loadConfig(s.configPath) | |
| 355 | 新增: if err != nil { | |
| 356 | 新增: return savedProfile{}, err | |
| 357 | 新增: } | |
| 358 | 新增: s.mu.Lock() | |
| 359 | 新增: p := s.preferences | |
| 360 | 新增: s.mu.Unlock() | |
| 361 | 新增: data, _ := json.Marshal(settingsView(old, p)) | |
| 362 | 新增: fields := map[string]json.RawMessage{} | |
| 363 | 新增: _ = json.Unmarshal(data, &fields) | |
| 364 | 新增: if err := mergeAgentSettings(fields, in.Patch); err != nil { | |
| 365 | 新增: return savedProfile{}, err | |
| 366 | 新增: } | |
| 367 | 新增: data, _ = json.Marshal(fields) | |
| 368 | 新增: var input Settings | |
| 369 | 新增: d := json.NewDecoder(bytes.NewReader(data)) | |
| 370 | 新增: d.DisallowUnknownFields() | |
| 371 | 新增: if d.Decode(&input) != nil { | |
| 372 | 新增: return savedProfile{}, errors.New("unknown setting or invalid value") | |
| 373 | 新增: } | |
| 374 | 新增: c, p, err := proposedSettings(input, old, s.profile) | |
| 375 | 新增: return savedProfile{Config: c, Preferences: p}, err | |
| 376 | 新增: } | |
| 377 | 新增: // Validate even when a different job is running; the real mutation reloads | |
| 378 | 新增: // current settings only after acquiring the shared operation lock. | |
| 379 | 新增: v, err := propose() | |
| 380 | 新增: if err != nil { | |
| 381 | 新增: requestError(w, err) | |
| 382 | 新增: return | |
| 383 | 新增: } | |
| 384 | 新增: if in.DryRun { | |
| 385 | 新增: jsonReply(w, settingsView(v.Config, v.Preferences)) | |
| 386 | 新增: return | |
| 387 | 新增: } | |
| 388 | 新增: s.launch(w, "settings", func() error { | |
| 389 | 新增: v, err := propose() | |
| 390 | 新增: if err != nil { | |
| 391 | 新增: return err | |
| 392 | 新增: } | |
| 393 | 新增: return s.apply(v, true) | |
| 394 | 新增: }) | |
| 395 | 新增:} | |
| 396 | 新增: | |
| 397 | 新增:// An exit_policy patch must retain its existing IP/region anchor when only one | |
| 398 | 新增:// field changes. Null never clears a setting implicitly. | |
| 399 | 新增:func mergeAgentSettings(current, patch map[string]json.RawMessage) error { | |
| 400 | 新增: for key, value := range patch { | |
| 401 | 新增: value = bytes.TrimSpace(value) | |
| 402 | 新增: if bytes.Equal(value, []byte("null")) { | |
| 403 | 新增: return errors.New("settings cannot be null") | |
| 404 | 新增: } | |
| 405 | 新增: var nested map[string]json.RawMessage | |
| 406 | 新增: if len(value) > 0 && value[0] == '{' && json.Unmarshal(value, &nested) == nil { | |
| 407 | 新增: existing := map[string]json.RawMessage{} | |
| 408 | 新增: _ = json.Unmarshal(current[key], &existing) | |
| 409 | 新增: if existing == nil { | |
| 410 | 新增: existing = map[string]json.RawMessage{} | |
| 411 | 新增: } | |
| 412 | 新增: if err := mergeAgentSettings(existing, nested); err != nil { | |
| 413 | 新增: return err | |
| 414 | 新增: } | |
| 415 | 新增: value, _ = json.Marshal(existing) | |
| 416 | 新增: } | |
| 417 | 新增: current[key] = value | |
| 418 | 新增: } | |
| 419 | 新增: return nil | |
| 420 | 新增:} | |
| @@ -0,0 +1,268 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "net/http/httptest" | |
| 10 | 新增: "net/url" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "strconv" | |
| 14 | 新增: "strings" | |
| 15 | 新增: "testing" | |
| 16 | 新增: "time" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:func agentTestController(t *testing.T) *Server { | |
| 23 | 新增: t.Helper() | |
| 24 | 新增: s := testServer(t) | |
| 25 | 新增: identity, err := currentController() | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: t.Fatal(err) | |
| 28 | 新增: } | |
| 29 | 新增: s.identity = identity | |
| 30 | 新增: server := httptest.NewServer(s.handler()) | |
| 31 | 新增: t.Cleanup(server.Close) | |
| 32 | 新增: u, _ := url.Parse(server.URL) | |
| 33 | 新增: port, _ := strconv.Atoi(u.Port()) | |
| 34 | 新增: s.origin = "http://localhost:" + u.Port() | |
| 35 | 新增: lock, err := openControllerLock(s.profile, os.O_CREATE|os.O_RDWR) | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: if err = lockController(lock); err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: t.Cleanup(func() { unlockController(lock); lock.Close() }) | |
| 43 | 新增: if err := writePrivate(filepath.Join(s.profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid(), Controller: identity}); err != nil { | |
| 44 | 新增: t.Fatal(err) | |
| 45 | 新增: } | |
| 46 | 新增: return s | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func TestAgentAuthenticationAndLockedAccount(t *testing.T) { | |
| 50 | 新增: s := agentTestController(t) | |
| 51 | 新增: if _, err := AgentCall(context.Background(), s.configPath, "settings.get", nil); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: s.account.lock() | |
| 55 | 新增: _, err := AgentCall(context.Background(), s.configPath, "settings.get", nil) | |
| 56 | 新增: var ae *AgentError | |
| 57 | 新增: if !errors.As(err, &ae) || ae.Code != "account_locked" { | |
| 58 | 新增: t.Fatalf("locked: %v", err) | |
| 59 | 新增: } | |
| 60 | 新增: if _, err := AgentCall(context.Background(), s.configPath, "account.status", nil); err != nil { | |
| 61 | 新增: t.Fatal(err) | |
| 62 | 新增: } | |
| 63 | 新增: if w := request(s, "POST", "/api/agent/settings", s.origin, `{"patch":{"keyboard":"native"}}`, false); w.Code != 401 { | |
| 64 | 新增: t.Fatal("agent routes bypassed session", w.Code) | |
| 65 | 新增: } | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:func TestAgentSettingsPatchPreservesOmittedFields(t *testing.T) { | |
| 69 | 新增: s := agentTestController(t) | |
| 70 | 新增: s.preferences.ClaudeTerminalCommand = "claude --verbose" | |
| 71 | 新增: before, err := cage.Load(s.configPath) | |
| 72 | 新增: if err != nil { | |
| 73 | 新增: t.Fatal(err) | |
| 74 | 新增: } | |
| 75 | 新增: data, err := AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"browser_home_url":"https://example.org/"},"dry_run":true}`)) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: t.Fatal(err) | |
| 78 | 新增: } | |
| 79 | 新增: if !strings.Contains(string(data), "https://example.org/") || s.preferences.BrowserHomeURL != "" { | |
| 80 | 新增: t.Fatalf("dry run: %s", data) | |
| 81 | 新增: } | |
| 82 | 新增: data, err = AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"browser_home_url":"https://example.org/"}}`)) | |
| 83 | 新增: if err != nil { | |
| 84 | 新增: t.Fatal(err) | |
| 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) | |
| 94 | 新增: } | |
| 95 | 新增: if s.preferences.ClaudeTerminalCommand != "claude --verbose" || s.preferences.BrowserHomeURL != "https://example.org/" { | |
| 96 | 新增: t.Fatalf("preferences lost: %+v", s.preferences) | |
| 97 | 新增: } | |
| 98 | 新增: after, _ := cage.Load(s.configPath) | |
| 99 | 新增: if before != after { | |
| 100 | 新增: t.Fatal("unrelated network config changed") | |
| 101 | 新增: } | |
| 102 | 新增: for _, input := range []string{`{"patch":{"proxy_url":"socks5://127.0.0.1:1"}}`, `{"patch":{"keyboard":null}}`, `{"patch":{"keyboard":"invalid"}}`, `{"patch":{}}`} { | |
| 103 | 新增: if _, err := AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(input)); err == nil { | |
| 104 | 新增: t.Fatal("accepted invalid patch", input) | |
| 105 | 新增: } | |
| 106 | 新增: } | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:func TestAgentPartialExitPolicyPreservesAnchor(t *testing.T) { | |
| 110 | 新增: s := agentTestController(t) | |
| 111 | 新增: cfg, err := cage.Load(s.configPath) | |
| 112 | 新增: if err != nil { | |
| 113 | 新增: t.Fatal(err) | |
| 114 | 新增: } | |
| 115 | 新增: cfg.ExitPolicy = cage.ExitPolicy{Mode: "dynamic", Scope: "city", IP: "8.8.8.8", CountryCode: "US", Region: "California", City: "Los Angeles"} | |
| 116 | 新增: if err := writePrivate(s.configPath, cfg); err != nil { | |
| 117 | 新增: t.Fatal(err) | |
| 118 | 新增: } | |
| 119 | 新增: data, err := AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"exit_policy":{"mode":"static"}},"dry_run":true}`)) | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: t.Fatal(err) | |
| 122 | 新增: } | |
| 123 | 新增: var view Settings | |
| 124 | 新增: _ = json.Unmarshal(data, &view) | |
| 125 | 新增: if view.ExitPolicy.Mode != "static" || view.ExitPolicy.Scope != "city" || view.ExitPolicy.IP != "8.8.8.8" || view.ExitPolicy.City != "Los Angeles" { | |
| 126 | 新增: t.Fatalf("network anchor discarded: %+v", view.ExitPolicy) | |
| 127 | 新增: } | |
| 128 | 新增: _, err = AgentCall(context.Background(), s.configPath, "settings.patch", json.RawMessage(`{"patch":{"exit_policy":{"ip":null}},"dry_run":true}`)) | |
| 129 | 新增: if err == nil { | |
| 130 | 新增: t.Fatal("null cleared network anchor") | |
| 131 | 新增: } | |
| 132 | 新增:} | |
| 133 | 新增: | |
| 134 | 新增:func TestAgentJobIdentityAndCancellation(t *testing.T) { | |
| 135 | 新增: s := agentTestController(t) | |
| 136 | 新增: s.setJobForTest(Job{ID: "012345abcdef", Running: true}) | |
| 137 | 新增: if _, err := AgentJob(context.Background(), s.configPath, "012345abcdef"); err != nil { | |
| 138 | 新增: t.Fatal(err) | |
| 139 | 新增: } | |
| 140 | 新增: s.setJobForTest(Job{ID: "abcdef012345"}) | |
| 141 | 新增: _, err := AgentJob(context.Background(), s.configPath, "012345abcdef") | |
| 142 | 新增: var ae *AgentError | |
| 143 | 新增: if !errors.As(err, &ae) || ae.Code != "job_not_found" { | |
| 144 | 新增: t.Fatalf("wrong job accepted: %v", err) | |
| 145 | 新增: } | |
| 146 | 新增: var manager jobManager | |
| 147 | 新增: manager.state = Job{ID: "012345abcdef", Running: true} | |
| 148 | 新增: execution := &jobExecution{id: manager.state.ID, ctx: context.Background()} | |
| 149 | 新增: manager.finishLocked(execution, context.Canceled) | |
| 150 | 新增: if manager.state.Running || !manager.state.Canceled { | |
| 151 | 新增: t.Fatalf("cancellation hidden: %+v", manager.state) | |
| 152 | 新增: } | |
| 153 | 新增:} | |
| 154 | 新增: | |
| 155 | 新增:func TestAgentRedactionPreservesOperationalValues(t *testing.T) { | |
| 156 | 新增: input := `{"id":"012345abcdef","clone_key":"` + strings.Repeat("a", 64) + `","workspace":"/Users/test/project","dns_url":"https://1.1.1.1/dns-query","error":"fetch https://secret.example/sub?token=very-secret failed","job":{"log":"password=hidden"}}` | |
| 157 | 新增: output := agentRedact(input) | |
| 158 | 新增: if !json.Valid([]byte(output)) || strings.Contains(output, "very-secret") || strings.Contains(output, "hidden") { | |
| 159 | 新增: t.Fatal(output) | |
| 160 | 新增: } | |
| 161 | 新增: for _, value := range []string{"012345abcdef", strings.Repeat("a", 64), "/Users/test/project", "https://1.1.1.1/dns-query"} { | |
| 162 | 新增: if !strings.Contains(output, value) { | |
| 163 | 新增: t.Fatal("operational field redacted", output) | |
| 164 | 新增: } | |
| 165 | 新增: } | |
| 166 | 新增:} | |
| 167 | 新增: | |
| 168 | 新增:func TestAgentNoImplicitStartAndUnknownInput(t *testing.T) { | |
| 169 | 新增: profile := t.TempDir() | |
| 170 | 新增: path := filepath.Join(profile, "config.json") | |
| 171 | 新增: for _, tc := range []struct{ op, input, code string }{{"does.not.exist", "{}", "unknown_operation"}, {"environment.stop", `{"surprise":true}`, "invalid_input"}, {"settings.get", "{}", "service_unavailable"}} { | |
| 172 | 新增: ctx, cancel := context.WithTimeout(context.Background(), time.Second) | |
| 173 | 新增: _, err := AgentCall(ctx, path, tc.op, json.RawMessage(tc.input)) | |
| 174 | 新增: cancel() | |
| 175 | 新增: var ae *AgentError | |
| 176 | 新增: if !errors.As(err, &ae) || ae.Code != tc.code { | |
| 177 | 新增: t.Fatalf("%s: %v", tc.op, err) | |
| 178 | 新增: } | |
| 179 | 新增: } | |
| 180 | 新增: if _, err := os.Stat(path); !os.IsNotExist(err) { | |
| 181 | 新增: t.Fatal("read created profile") | |
| 182 | 新增: } | |
| 183 | 新增: for _, path := range []string{"/api/agent/settings", "/api/agent/jobs/012345abcdef"} { | |
| 184 | 新增: if !macOSWorkbenchRoute(path) || !windowsWorkbenchRoute(path) { | |
| 185 | 新增: t.Fatal("missing native platform route", path) | |
| 186 | 新增: } | |
| 187 | 新增: } | |
| 188 | 新增: if !macOSSetupRoute("/api/agent/jobs/012345abcdef") { | |
| 189 | 新增: t.Fatal("cannot track first setup") | |
| 190 | 新增: } | |
| 191 | 新增:} | |
| 192 | 新增: | |
| 193 | 新增:func TestAgentCannotFollowSelectedRemote(t *testing.T) { | |
| 194 | 新增: s := agentTestController(t) | |
| 195 | 新增: s.remote = newRemoteGateway(s.profile) | |
| 196 | 新增: t.Cleanup(func() { s.remote.close() }) | |
| 197 | 新增: s.remote.setRemote(true) | |
| 198 | 新增: _, err := AgentCall(context.Background(), s.configPath, "environment.stop", json.RawMessage(`{}`)) | |
| 199 | 新增: var ae *AgentError | |
| 200 | 新增: if !errors.As(err, &ae) || ae.Code != "state_conflict" { | |
| 201 | 新增: t.Fatalf("remote target accepted: %v", err) | |
| 202 | 新增: } | |
| 203 | 新增: if s.jobs.snapshot().ID != "" { | |
| 204 | 新增: t.Fatal("remote rejection fell back to local mutation") | |
| 205 | 新增: } | |
| 206 | 新增:} | |
| 207 | 新增: | |
| 208 | 新增:func TestAgentRejectsOtherConfigFileInSameProfile(t *testing.T) { | |
| 209 | 新增: s := agentTestController(t) | |
| 210 | 新增: _, err := AgentCall(context.Background(), filepath.Join(s.profile, "other.json"), "account.status", nil) | |
| 211 | 新增: var ae *AgentError | |
| 212 | 新增: if !errors.As(err, &ae) || ae.Code != "config_path_mismatch" { | |
| 213 | 新增: t.Fatalf("wrong config accepted: %v", err) | |
| 214 | 新增: } | |
| 215 | 新增: s.clientOnly = true | |
| 216 | 新增: _, err = AgentCall(context.Background(), s.configPath, "account.status", nil) | |
| 217 | 新增: if !errors.As(err, &ae) || ae.Code != "controller_mismatch" { | |
| 218 | 新增: t.Fatalf("remote-only client accepted: %v", err) | |
| 219 | 新增: } | |
| 220 | 新增:} | |
| 221 | 新增: | |
| 222 | 新增:func TestAgentNativeDiagnosticExport(t *testing.T) { | |
| 223 | 新增: for _, system := range []string{"linux", "macos", "windows"} { | |
| 224 | 新增: t.Run(system, func(t *testing.T) { | |
| 225 | 新增: s := agentTestController(t) | |
| 226 | 新增: if system == "macos" { | |
| 227 | 新增: s.macosGuest = &guestos.MacOSProfile{Instance: "test", User: "test"} | |
| 228 | 新增: } | |
| 229 | 新增: if system == "windows" { | |
| 230 | 新增: s.windowsGuest = &guestos.WindowsProfile{} | |
| 231 | 新增: } | |
| 232 | 新增: s.account.lock() | |
| 233 | 新增: path := filepath.Join(t.TempDir(), "diagnostics.zip") | |
| 234 | 新增: if err := ExportAgentDiagnostics(s.configPath, path); err != nil { | |
| 235 | 新增: t.Fatal(err) | |
| 236 | 新增: } | |
| 237 | 新增: before, err := os.ReadFile(path) | |
| 238 | 新增: if err != nil || len(before) == 0 { | |
| 239 | 新增: t.Fatal("missing bundle", err) | |
| 240 | 新增: } | |
| 241 | 新增: archive, err := zip.OpenReader(path) | |
| 242 | 新增: if err != nil { | |
| 243 | 新增: t.Fatal(err) | |
| 244 | 新增: } | |
| 245 | 新增: defer archive.Close() | |
| 246 | 新增: for _, file := range archive.File { | |
| 247 | 新增: if file.Name == "manifest.json" { | |
| 248 | 新增: reader, err := file.Open() | |
| 249 | 新增: if err != nil { | |
| 250 | 新增: t.Fatal(err) | |
| 251 | 新增: } | |
| 252 | 新增: body, _ := io.ReadAll(reader) | |
| 253 | 新增: reader.Close() | |
| 254 | 新增: if !strings.Contains(string(body), `"guest_collection": "environment unavailable"`) { | |
| 255 | 新增: t.Fatal("did not use authenticated native diagnostic endpoint", string(body)) | |
| 256 | 新增: } | |
| 257 | 新增: } | |
| 258 | 新增: } | |
| 259 | 新增: if err := ExportAgentDiagnostics(s.configPath, path); err == nil { | |
| 260 | 新增: t.Fatal("overwrote previous diagnostic") | |
| 261 | 新增: } | |
| 262 | 新增: after, _ := os.ReadFile(path) | |
| 263 | 新增: if string(before) != string(after) { | |
| 264 | 新增: t.Fatal("existing bundle changed") | |
| 265 | 新增: } | |
| 266 | 新增: }) | |
| 267 | 新增: } | |
| 268 | 新增:} | |
| @@ -35,6 +35,8 @@ func (identity ControllerIdentity) matches(other ControllerIdentity) bool { | ||
| 35 | 35 | } |
| 36 | 36 | |
| 37 | 37 | type launchResponse struct { |
| 38 | 新增: ConfigPath string `json:"config_path,omitempty"` | |
| 39 | 新增: ClientOnly bool `json:"client_only,omitempty"` | |
| 38 | 40 | DesktopGateway bool `json:"desktop_gateway,omitempty"` |
| 39 | 41 | URL string `json:"url"` |
| 40 | 42 | Controller ControllerIdentity `json:"controller"` |
| @@ -109,6 +109,16 @@ func ExportDiagnostics(configPath, destination string) error { | ||
| 109 | 109 | } |
| 110 | 110 | |
| 111 | 111 | func ExportDiagnosticsForConnection(configPath, connectionID, destination string) error { |
| 112 | 新增: return exportDiagnostics(configPath, connectionID, destination, false) | |
| 113 | 新增:} | |
| 114 | 新增: | |
| 115 | 新增:// ExportAgentDiagnostics pins the owning local workload and uses its native | |
| 116 | 新增:// launcher proof. The output is exclusive even if another writer races it. | |
| 117 | 新增:func ExportAgentDiagnostics(configPath, destination string) error { | |
| 118 | 新增: return exportDiagnostics(configPath, "local", destination, true) | |
| 119 | 新增:} | |
| 120 | 新增: | |
| 121 | 新增:func exportDiagnostics(configPath, connectionID, destination string, agentLocal bool) error { | |
| 112 | 122 | if !filepath.IsAbs(destination) { |
| 113 | 123 | return errors.New("请选择本机绝对保存路径") |
| 114 | 124 | } |
| @@ -126,7 +136,13 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string | ||
| 126 | 136 | return err |
| 127 | 137 | } |
| 128 | 138 | export := func() error { |
| 129 | 删除: c, e := connectController(profile) | |
| 139 | 新增: var c *controllerClient | |
| 140 | 新增: var e error | |
| 141 | 新增: if agentLocal { | |
| 142 | 新增: c, e = agentConnect(context.Background(), configPath) | |
| 143 | 新增: } else { | |
| 144 | 新增: c, e = connectController(profile) | |
| 145 | 新增: } | |
| 130 | 146 | if e != nil { |
| 131 | 147 | if connectionID != "" && connectionID != "local" { |
| 132 | 148 | return errors.New("远程连接不可用,无法导出云端诊断包") |
| @@ -137,20 +153,25 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string | ||
| 137 | 153 | return store.Export(f, version.Version, nil, "controller unavailable or invalid; host logs only") |
| 138 | 154 | } |
| 139 | 155 | defer c.close() |
| 140 | 删除: parsed, e := url.Parse(c.launch.URL) | |
| 141 | 删除: if e != nil { | |
| 142 | 删除: return e | |
| 143 | 删除: } | |
| 144 | 删除: ticket := parsed.Fragment | |
| 145 | 删除: code, e := c.call("POST", "/api/session", map[string]string{"token": ticket}, nil) | |
| 146 | 删除: if e != nil || code != 200 { | |
| 147 | 删除: return errors.New("无法创建诊断导出会话,请重新打开 Cage") | |
| 148 | 删除: } | |
| 149 | 删除: if _, err := c.bindConnection(connectionID); err != nil { | |
| 150 | 删除: return err | |
| 156 | 新增: if !agentLocal { | |
| 157 | 新增: parsed, e := url.Parse(c.launch.URL) | |
| 158 | 新增: if e != nil { | |
| 159 | 新增: return e | |
| 160 | 新增: } | |
| 161 | 新增: ticket := parsed.Fragment | |
| 162 | 新增: code, e := c.call("POST", "/api/session", map[string]string{"token": ticket}, nil) | |
| 163 | 新增: if e != nil || code != 200 { | |
| 164 | 新增: return errors.New("无法创建诊断导出会话,请重新打开 Cage") | |
| 165 | 新增: } | |
| 166 | 新增: if _, err := c.bindConnection(connectionID); err != nil { | |
| 167 | 新增: return err | |
| 168 | 新增: } | |
| 151 | 169 | } |
| 152 | 170 | c.client.Timeout = 30 * time.Second |
| 153 | 171 | req, _ := http.NewRequest("GET", c.origin+"/api/diagnostics/export", nil) |
| 172 | 新增: if agentLocal { | |
| 173 | 新增: req.Header.Set(connectionHeader, "local") | |
| 174 | 新增: } | |
| 154 | 175 | response, e := c.client.Do(req) |
| 155 | 176 | if e != nil { |
| 156 | 177 | return e |
| @@ -184,6 +205,9 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string | ||
| 184 | 205 | return errors.New("诊断包未完整生成,请重新导出") |
| 185 | 206 | } |
| 186 | 207 | _ = archive.Close() |
| 208 | 新增: if agentLocal { | |
| 209 | 新增: return os.Link(temp, destination) | |
| 210 | 新增: } | |
| 187 | 211 | // Never follow a destination symlink or replace a directory. |
| 188 | 212 | if st, e := os.Lstat(destination); e == nil && !st.Mode().IsRegular() { |
| 189 | 213 | return errors.New("请选择普通文件作为保存位置") |
| @@ -13,6 +13,7 @@ import ( | ||
| 13 | 13 | ) |
| 14 | 14 | |
| 15 | 15 | type Job struct { |
| 16 | 新增: Canceled bool `json:"canceled,omitempty"` | |
| 16 | 17 | SetupProgress *SetupProgress `json:"setup_progress,omitempty"` |
| 17 | 18 | ID string `json:"id"` |
| 18 | 19 | Kind string `json:"kind"` |
| @@ -154,6 +155,7 @@ func (m *jobManager) finishLocked(execution *jobExecution, err error) { | ||
| 154 | 155 | m.state.Running = false |
| 155 | 156 | switch { |
| 156 | 157 | case errors.Is(err, context.Canceled): |
| 158 | 新增: m.state.Canceled = true | |
| 157 | 159 | m.state.Message = "已取消" |
| 158 | 160 | diagnostics.Log("info", "task", m.state.Kind+" canceled") |
| 159 | 161 | case err != nil: |
| @@ -27,6 +27,9 @@ func (s *Server) macSetupPending() bool { | ||
| 27 | 27 | } |
| 28 | 28 | |
| 29 | 29 | func macOSSetupRoute(path string) bool { |
| 30 | 新增: if strings.HasPrefix(path, "/api/agent/jobs/") { | |
| 31 | 新增: return true | |
| 32 | 新增: } | |
| 30 | 33 | if !strings.HasPrefix(path, "/api/") { |
| 31 | 34 | return true |
| 32 | 35 | } |
| @@ -9,6 +9,8 @@ func nativeWorkbenchRoute(path string) bool { | ||
| 9 | 9 | return true |
| 10 | 10 | } |
| 11 | 11 | switch path { |
| 12 | 新增: case "/api/agent/settings": | |
| 13 | 新增: return true | |
| 12 | 14 | case "/api/account", "/api/session", "/api/launch", "/api/handoff", "/api/remote/manifest", |
| 13 | 15 | "/api/appearance", "/api/favorites", "/api/status", "/api/settings", "/api/settings/probe", |
| 14 | 16 | "/api/start", "/api/stop", "/api/restore", "/api/host/git", "/api/projects/open", "/api/projects/directories", |
| @@ -20,6 +22,7 @@ func nativeWorkbenchRoute(path string) bool { | ||
| 20 | 22 | return true |
| 21 | 23 | } |
| 22 | 24 | for _, prefix := range []string{ |
| 25 | 新增: "/api/agent/jobs/", | |
| 23 | 26 | "/api/account/", "/api/terminals/", "/api/claude-accounts/", "/api/cli/sessions/", "/api/proxy/", |
| 24 | 27 | "/api/browser/", "/api/clipboard/files/", "/api/input/files/browser/", "/api/input/files/terminal/", |
| 25 | 28 | "/api/tailscale/", "/api/mobile/cli/", "/api/mobile/browser/", "/api/mobile/desktop/", "/api/diagnostics", |
| @@ -312,6 +312,7 @@ func serve(configPath string, clientOnly bool, fullConfigPath string) (returned | ||
| 312 | 312 | } |
| 313 | 313 | func (s *Server) handler() http.Handler { |
| 314 | 314 | mux := http.NewServeMux() |
| 315 | 新增: s.agentRoutes(mux) | |
| 315 | 316 | s.mobileCLIRoutes(mux) |
| 316 | 317 | s.mobileSurfaceRoutes(mux) |
| 317 | 318 | mux.HandleFunc("GET /api/mobile-pair", s.phoneStatus) |
| @@ -323,7 +324,7 @@ func (s *Server) handler() http.Handler { | ||
| 323 | 324 | if !s.launcherAuthenticated(w, r) { |
| 324 | 325 | return |
| 325 | 326 | } |
| 326 | 删除: jsonReply(w, launchResponse{DesktopGateway: s.desktopEntry, URL: s.origin + "/?launch=" + randomToken()[:8] + "#" + s.issueTicket(), Controller: s.identity}) | |
| 327 | 新增: jsonReply(w, launchResponse{ConfigPath: s.configPath, ClientOnly: s.clientOnly, DesktopGateway: s.desktopEntry, URL: s.origin + "/?launch=" + randomToken()[:8] + "#" + s.issueTicket(), Controller: s.identity}) | |
| 327 | 328 | }) |
| 328 | 329 | if s.desktopEntry || s.clientOnly { |
| 329 | 330 | mux.HandleFunc("POST /api/handoff", s.handoffEntry) |
| @@ -0,0 +1,65 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import { createHash } from 'node:crypto'; | |
| 3 | 新增:import { mkdtemp, readFile, rm, writeFile, readdir } from 'node:fs/promises'; | |
| 4 | 新增:import { tmpdir } from 'node:os'; | |
| 5 | 新增:import { join } from 'node:path'; | |
| 6 | 新增:import { test } from 'node:test'; | |
| 7 | 新增:import { parseArgs, selectAsset, checksumFor, makePlan, downloadPlan, httpsResponse } from '../www/public/agent-bootstrap.mjs'; | |
| 8 | 新增: | |
| 9 | 新增:const tag = 'v0.1.0-test'; | |
| 10 | 新增:const prefix = `https://github.com/Lee-xeo/Claude-Cage/releases/download/${tag}/`; | |
| 11 | 新增:const data = Buffer.from('fake package fixture'); | |
| 12 | 新增:const hash = createHash('sha256').update(data).digest('hex'); | |
| 13 | 新增:function release(platform) { | |
| 14 | 新增: const suffix = { 'darwin-arm64': 'macos-arm64.dmg', 'linux-amd64': 'linux-amd64.deb', 'win32-amd64': 'windows-amd64-setup-unsigned.exe' }[platform]; | |
| 15 | 新增: const name = `Cage-${tag.slice(1)}-${suffix}`; | |
| 16 | 新增: return { tag_name: tag, assets: [{ name, size: data.length, browser_download_url: prefix + name }, { name: 'SHA256SUMS', browser_download_url: prefix + 'SHA256SUMS' }] }; | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:test('select only exact platform artifacts and explicit unsigned consent', () => { | |
| 20 | 新增: for (const platform of ['darwin-arm64', 'linux-amd64', 'win32-amd64']) { | |
| 21 | 新增: const options = parseArgs(['plan', '--platform', platform, '--version', tag, '--allow-unsigned']); | |
| 22 | 新增: const selected = selectAsset(release(platform), options); | |
| 23 | 新增: assert.equal(selected.unsigned, platform === 'win32-amd64'); | |
| 24 | 新增: assert.equal(selected.tag, tag); | |
| 25 | 新增: } | |
| 26 | 新增: assert.throws(() => selectAsset(release('win32-amd64'), { platform: 'win32-amd64' }), { code: 'unsigned_package_requires_consent' }); | |
| 27 | 新增: assert.throws(() => parseArgs(['download', '--destination', 'relative']), { code: 'invalid_input' }); | |
| 28 | 新增: assert.throws(() => parseArgs(['--version', '../../bad']), { code: 'invalid_input' }); | |
| 29 | 新增: const wrong = release('linux-amd64'); wrong.assets[0].browser_download_url = 'https://example.org/package'; | |
| 30 | 新增: assert.throws(() => selectAsset(wrong, { platform: 'linux-amd64' }), { code: 'invalid_release' }); | |
| 31 | 新增:}); | |
| 32 | 新增: | |
| 33 | 新增:test('checksum manifest must identify exactly one package', () => { | |
| 34 | 新增: assert.equal(checksumFor(`${hash} Cage.deb\r\n`, 'Cage.deb'), hash); | |
| 35 | 新增: assert.throws(() => checksumFor(`${hash} other.deb`, 'Cage.deb'), { code: 'invalid_checksum_manifest' }); | |
| 36 | 新增: assert.throws(() => checksumFor(`${hash} Cage.deb\n${hash} *Cage.deb`, 'Cage.deb'), { code: 'invalid_checksum_manifest' }); | |
| 37 | 新增:}); | |
| 38 | 新增: | |
| 39 | 新增:test('plan pins metadata and sums to one release; downloads are verified and exclusive', async t => { | |
| 40 | 新增: const options = parseArgs(['plan', '--platform', 'linux-amd64', '--version', tag]); | |
| 41 | 新增: const metadata = release(options.platform); | |
| 42 | 新增: const fetchFixture = async url => { | |
| 43 | 新增: if (String(url).startsWith('https://api.github.com/')) return new Response(JSON.stringify(metadata)); | |
| 44 | 新增: if (String(url).endsWith('SHA256SUMS')) return new Response(`${hash} ${metadata.assets[0].name}\n`); | |
| 45 | 新增: return new Response(data); | |
| 46 | 新增: }; | |
| 47 | 新增: const plan = await makePlan(options, fetchFixture); | |
| 48 | 新增: assert.equal(plan.sha256, hash); | |
| 49 | 新增: assert.equal(plan.cli, '/usr/bin/claude-cage'); | |
| 50 | 新增: const directory = await mkdtemp(join(tmpdir(), 'cage-bootstrap-')); | |
| 51 | 新增: t.after(() => rm(directory, { recursive: true, force: true })); | |
| 52 | 新增: const result = await downloadPlan(plan, directory, fetchFixture); | |
| 53 | 新增: assert.deepEqual(await readFile(result.path), data); | |
| 54 | 新增: assert.ok(result.installation.argv.includes(result.path)); | |
| 55 | 新增: await writeFile(result.path, 'existing user file'); | |
| 56 | 新增: await assert.rejects(downloadPlan(plan, directory, fetchFixture), { code: 'EEXIST' }); | |
| 57 | 新增: assert.equal(await readFile(result.path, 'utf8'), 'existing user file'); | |
| 58 | 新增: await assert.rejects(downloadPlan({ ...plan, asset: 'bad.deb', sha256: '0'.repeat(64) }, directory, fetchFixture), { code: 'checksum_mismatch' }); | |
| 59 | 新增: assert.deepEqual(await readdir(directory), [plan.asset]); | |
| 60 | 新增:}); | |
| 61 | 新增: | |
| 62 | 新增:test('refuse HTTP redirects and redact transport failures at the CLI boundary', async () => { | |
| 63 | 新增: await assert.rejects(httpsResponse('https://example.org/', async () => new Response(null, { status: 302, headers: { location: 'http://example.org/' } })), { code: 'unsafe_download' }); | |
| 64 | 新增: await assert.rejects(httpsResponse('https://example.org/', async () => { throw new Error('https://secret.example/private?token=do-not-echo'); }), error => error.code === 'download_connection_failed' && !error.message.includes('do-not-echo')); | |
| 65 | 新增:}); | |
| @@ -0,0 +1,68 @@ | ||
| 1 | 新增:// Exercise the shipped entry point against a disposable profile, without a VM. | |
| 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 | 新增: | |
| 9 | 新增:const binary = process.argv[2]; | |
| 10 | 新增:assert.ok(binary && isAbsolute(binary), 'Pass an absolute Cage CLI binary path.'); | |
| 11 | 新增:const profile = await mkdtemp(join(tmpdir(), 'cage-agent-cli-')); | |
| 12 | 新增:const config = join(profile, 'profile', 'config.json'); | |
| 13 | 新增:let controllerPID; | |
| 14 | 新增:function call(args, input, expectedCode = 0) { | |
| 15 | 新增: const result = spawnSync(binary, ['agent', ...args, '--config', config], { input: input === undefined ? undefined : JSON.stringify(input), encoding: 'utf8', timeout: 30000 }); | |
| 16 | 新增: assert.ifError(result.error); | |
| 17 | 新增: assert.equal(result.status, expectedCode, `Unexpected exit from ${args[0]}: ${result.stdout} ${result.stderr}`); | |
| 18 | 新增: const reply = JSON.parse(result.stdout); | |
| 19 | 新增: assert.equal(reply.protocol, 1); | |
| 20 | 新增: assert.equal(reply.config_path, config); | |
| 21 | 新增: return reply; | |
| 22 | 新增:} | |
| 23 | 新增:try { | |
| 24 | 新增: const capabilities = call(['capabilities']); | |
| 25 | 新增: assert.ok(capabilities.data.operations.some(operation => operation.name === 'settings.patch')); | |
| 26 | 新增: assert.equal(call(['doctor']).data.checks[0].code, 'config_missing'); | |
| 27 | 新增: assert.equal(call(['call', 'settings.get'], undefined, 1).error.code, 'service_unavailable'); | |
| 28 | 新增: await assert.rejects(stat(join(profile, 'profile')), { code: 'ENOENT' }); | |
| 29 | 新增: call(['init']); | |
| 30 | 新增: const originalConfig = await readFile(config, 'utf8'); | |
| 31 | 新增: call(['init']); assert.equal(await readFile(config, 'utf8'), originalConfig); | |
| 32 | 新增: call(['service.start']); | |
| 33 | 新增: controllerPID = JSON.parse(await readFile(join(profile, 'profile', 'control.json'), 'utf8')).pid; | |
| 34 | 新增: call(['service.start']); | |
| 35 | 新增: assert.equal(JSON.parse(await readFile(join(profile, 'profile', 'control.json'), 'utf8')).pid, controllerPID); | |
| 36 | 新增: assert.equal(call(['call', 'settings.get'], undefined, 3).error.code, 'account_locked'); | |
| 37 | 新增: call(['call', 'account.create', '--input', '-'], { username: 'Agent acceptance', password: 'Ephemeral-Test-Password-123!', confirm_password: 'Ephemeral-Test-Password-123!' }); | |
| 38 | 新增: const before = call(['call', 'settings.get']).data; | |
| 39 | 新增: const patch = { browser_home_url: 'https://example.org/' }; | |
| 40 | 新增: call(['call', 'settings.patch', '--input', '-'], { patch, dry_run: true }); | |
| 41 | 新增: assert.deepEqual(call(['call', 'settings.get']).data, before); | |
| 42 | 新增: const applied = call(['call', 'settings.patch', '--input', '-', '--wait', '10s'], { patch }); | |
| 43 | 新增: assert.equal(applied.status, 'completed'); assert.equal(applied.data.running, false); | |
| 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); | |
| 46 | 新增: const rejected = call(['call', 'settings.patch', '--input', '-'], { patch: { proxy_url: 'socks5://127.0.0.1:1' } }, 1); | |
| 47 | 新增: assert.equal(rejected.error.code, 'request_rejected'); | |
| 48 | 新增: const proxy = call(['call', 'proxy.status']); | |
| 49 | 新增: assert.equal(proxy.data.sources.length, 0); | |
| 50 | 新增: assert.ok(!JSON.stringify(proxy).includes('proxy_url')); | |
| 51 | 新增: const bundle = join(profile, 'diagnostics.zip'); | |
| 52 | 新增: call(['diagnostics', '--output', bundle]); | |
| 53 | 新增: assert.ok((await stat(bundle)).size > 0); | |
| 54 | 新增: assert.equal(call(['diagnostics', '--output', bundle], undefined, 2).error.code, 'invalid_input'); | |
| 55 | 新增: console.log('PASS: real CLI discovery, offline doctor, no implicit writes, idempotent init/start, account locking, private input, dry run, settings patch, tracked completion, proxy status and diagnostic export.'); | |
| 56 | 新增:} finally { | |
| 57 | 新增: if (controllerPID) { | |
| 58 | 新增: try { process.kill(controllerPID, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; } | |
| 59 | 新增: // Wait for this test's controller to release its record before cleanup. | |
| 60 | 新增: let retired = false; | |
| 61 | 新增: for (let attempt = 0; attempt < 100; attempt++) { | |
| 62 | 新增: try { await stat(join(profile, 'profile', 'control.json')); } catch (error) { if (error.code === 'ENOENT') { retired = true; break; } throw error; } | |
| 63 | 新增: await setTimeout(100); | |
| 64 | 新增: } | |
| 65 | 新增: assert.ok(retired, 'Controller did not retire; preserve the isolated profile for inspection.'); | |
| 66 | 新增: } | |
| 67 | 新增: await rm(profile, { recursive: true, force: true }); | |
| 68 | 新增:} | |
| @@ -0,0 +1,147 @@ | ||
| 1 | 新增:#!/usr/bin/env node | |
| 2 | 新增:// Node >=20, standard library only. No installation or user data mutation. | |
| 3 | 新增:import { createHash } from 'node:crypto'; | |
| 4 | 新增:import { createWriteStream } from 'node:fs'; | |
| 5 | 新增:import { chmod, link, mkdir, mkdtemp, rm } from 'node:fs/promises'; | |
| 6 | 新增:import { isAbsolute, join, resolve } from 'node:path'; | |
| 7 | 新增:import { Readable, Transform } from 'node:stream'; | |
| 8 | 新增:import { pipeline } from 'node:stream/promises'; | |
| 9 | 新增:import { pathToFileURL } from 'node:url'; | |
| 10 | 新增: | |
| 11 | 新增:const repo = 'Lee-xeo/Claude-Cage'; | |
| 12 | 新增:const protocol = 1; | |
| 13 | 新增:export class BootstrapError extends Error { | |
| 14 | 新增: constructor(code, message, nextAction) { super(message); this.code = code; this.next_action = nextAction; } | |
| 15 | 新增:} | |
| 16 | 新增:const fail = (code, message, next = 'plan') => { throw new BootstrapError(code, message, next); }; | |
| 17 | 新增: | |
| 18 | 新增:export function parseArgs(args) { | |
| 19 | 新增: const options = { action: 'plan', platform: `${process.platform}-${process.arch === 'x64' ? 'amd64' : process.arch}`, version: '', destination: '', allowUnsigned: false }; | |
| 20 | 新增: if (args[0] && !args[0].startsWith('--')) options.action = args.shift(); | |
| 21 | 新增: for (let i = 0; i < args.length; i++) { | |
| 22 | 新增: const flag = args[i]; | |
| 23 | 新增: if (flag === '--allow-unsigned') { options.allowUnsigned = true; continue; } | |
| 24 | 新增: if (!['--platform', '--version', '--destination'].includes(flag) || !args[i + 1] || args[i + 1].startsWith('--')) fail('invalid_input', 'Usage: agent-bootstrap.mjs plan|download [--version TAG] [--platform darwin-arm64|win32-amd64|linux-amd64] [--destination ABSOLUTE_DIRECTORY] [--allow-unsigned]'); | |
| 25 | 新增: options[flag.slice(2)] = args[++i]; | |
| 26 | 新增: } | |
| 27 | 新增: if (!['plan', 'download'].includes(options.action)) fail('invalid_input', 'Action must be plan or download.'); | |
| 28 | 新增: if (!['darwin-arm64', 'win32-amd64', 'linux-amd64'].includes(options.platform)) fail('unsupported_platform', 'No desktop package is selected for this platform. Read the platform guide.'); | |
| 29 | 新增: if (options.version && !/^v?\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(options.version)) fail('invalid_input', 'Use an explicit release tag such as v0.1.6-alpha-preview.'); | |
| 30 | 新增: if (options.version && !options.version.startsWith('v')) options.version = `v${options.version}`; | |
| 31 | 新增: if (options.action === 'download' && !isAbsolute(options.destination)) fail('invalid_input', 'download requires --destination with an absolute directory path.'); | |
| 32 | 新增: return options; | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:// Validate HTTPS at every redirect; do not use browser credentials or tokens. | |
| 36 | 新增:export async function httpsResponse(url, fetchImpl = fetch) { | |
| 37 | 新增: for (let redirects = 0; redirects <= 5; redirects++) { | |
| 38 | 新增: const parsed = new URL(url); | |
| 39 | 新增: if (parsed.protocol !== 'https:' || parsed.username || parsed.password) fail('unsafe_download', 'Only public HTTPS downloads without embedded credentials are supported.'); | |
| 40 | 新增: let response; | |
| 41 | 新增: try { | |
| 42 | 新增: response = await fetchImpl(parsed, { redirect: 'manual', signal: AbortSignal.timeout(120000), headers: { 'User-Agent': 'Cage-Agent-Bootstrap/1', Accept: 'application/json, application/octet-stream' } }); | |
| 43 | 新增: } catch { | |
| 44 | 新增: fail('download_connection_failed', 'Could not connect to the public release service. Check host connectivity and user-configured proxy settings; Node 24 can use --use-env-proxy.', 'check_host_network'); | |
| 45 | 新增: } | |
| 46 | 新增: if ([301, 302, 303, 307, 308].includes(response.status)) { | |
| 47 | 新增: const location = response.headers.get('location'); | |
| 48 | 新增: await response.body?.cancel(); | |
| 49 | 新增: if (!location) fail('download_failed', 'Download redirect has no location.'); | |
| 50 | 新增: url = new URL(location, parsed).href; | |
| 51 | 新增: continue; | |
| 52 | 新增: } | |
| 53 | 新增: if (!response.ok) { await response.body?.cancel(); fail(response.status === 403 || response.status === 429 ? 'rate_limited' : 'download_failed', `Public download returned HTTP ${response.status}. Retry later or choose another published release.`); } | |
| 54 | 新增: return response; | |
| 55 | 新增: } | |
| 56 | 新增: fail('download_failed', 'Too many redirects.'); | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:async function boundedText(url, fetchImpl) { | |
| 60 | 新增: const response = await httpsResponse(url, fetchImpl); | |
| 61 | 新增: const chunks = []; let total = 0; | |
| 62 | 新增: for await (const chunk of response.body) { total += chunk.length; if (total > 4 * 1024 * 1024) fail('invalid_release', 'Release metadata is too large.'); chunks.push(chunk); } | |
| 63 | 新增: return Buffer.concat(chunks).toString('utf8').replace(/^\uFEFF/, ''); | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:export function selectAsset(release, options) { | |
| 67 | 新增: const tag = release.tag_name; | |
| 68 | 新增: if (!/^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(tag) || release.draft || (options.version && tag !== options.version)) fail('invalid_release', 'Release tag does not match the requested published release.'); | |
| 69 | 新增: const version = tag.slice(1); | |
| 70 | 新增: const suffix = { 'darwin-arm64': 'macos-arm64.dmg', 'linux-amd64': 'linux-amd64.deb', 'win32-amd64': 'windows-amd64-setup.exe' }[options.platform]; | |
| 71 | 新增: let asset = release.assets?.find(a => a.name === `Cage-${version}-${suffix}`); | |
| 72 | 新增: let unsigned = false; | |
| 73 | 新增: if (!asset && options.platform === 'win32-amd64') { | |
| 74 | 新增: asset = release.assets?.find(a => a.name === `Cage-${version}-windows-amd64-setup-unsigned.exe`); | |
| 75 | 新增: if (asset && !options.allowUnsigned) fail('unsigned_package_requires_consent', 'Only an unsigned Windows preview is available. Ask the user before selecting it with --allow-unsigned.', 'user_decision'); | |
| 76 | 新增: unsigned = !!asset; | |
| 77 | 新增: } | |
| 78 | 新增: const sums = release.assets?.find(a => a.name === 'SHA256SUMS'); | |
| 79 | 新增: if (!asset || !sums) fail('asset_unavailable', 'This release has no matching package and checksum manifest. Choose a published release containing both.'); | |
| 80 | 新增: if (!Number.isSafeInteger(asset.size) || asset.size <= 0) fail('invalid_release', 'The package has no valid published size.'); | |
| 81 | 新增: for (const item of [asset, sums]) { | |
| 82 | 新增: if (item.browser_download_url !== `https://github.com/${repo}/releases/download/${tag}/${item.name}`) fail('invalid_release', 'Unexpected release asset origin.'); | |
| 83 | 新增: } | |
| 84 | 新增: return { asset, sums, unsigned, tag, version }; | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:export function checksumFor(manifest, name) { | |
| 88 | 新增: const matches = manifest.split(/\r?\n/).map(line => line.match(/^([a-fA-F0-9]{64}) [ *](\S+)\s*$/)).filter(match => match && match[2] === name); | |
| 89 | 新增: if (matches.length !== 1) fail('invalid_checksum_manifest', 'Expected exactly one SHA-256 entry for the selected package.'); | |
| 90 | 新增: return matches[0][1].toLowerCase(); | |
| 91 | 新增:} | |
| 92 | 新增: | |
| 93 | 新增:export async function makePlan(options, fetchImpl = fetch) { | |
| 94 | 新增: const releaseURL = `https://api.github.com/repos/${repo}/releases/${options.version ? `tags/${options.version}` : 'latest'}`; | |
| 95 | 新增: let release; | |
| 96 | 新增: try { release = JSON.parse(await boundedText(releaseURL, fetchImpl)); } catch (error) { if (error instanceof BootstrapError) throw error; fail('invalid_release', 'Could not read public release metadata.'); } | |
| 97 | 新增: const selected = selectAsset(release, options); | |
| 98 | 新增: const sha256 = checksumFor(await boundedText(selected.sums.browser_download_url, fetchImpl), selected.asset.name); | |
| 99 | 新增: const cli = { 'darwin-arm64': '/Applications/Cage.app/Contents/Resources/cage', 'linux-amd64': '/usr/bin/claude-cage', 'win32-amd64': '%LOCALAPPDATA%\\Programs\\Cage\\resources\\cage.exe' }[options.platform]; | |
| 100 | 新增: const installation = { | |
| 101 | 新增: 'darwin-arm64': { guide: 'https://lee-xeo.github.io/Claude-Cage/docs/installation/', steps: ['Check codesign and spctl on the mounted Cage.app. Preserve macOS Gatekeeper checks.', 'For an update, save work and stop Cage through its existing UI before replacing app files.', 'Mount the verified DMG read-only with hdiutil attach -readonly -nobrowse. Copy Cage.app to /Applications using the existing installation guide; eject the mounted volume.', 'Run the installed CLI agent capabilities. If agent is unknown, this release predates Agent support; use its documented UI or an authorized newer build.'] }, | |
| 102 | 新增: 'linux-amd64': { guide: 'https://lee-xeo.github.io/Claude-Cage/docs/installation/', argv: ['sudo', 'apt-get', 'install', '--', '<downloaded_absolute_path>'], steps: ['Save work and stop Cage before an update. Run the package manager in the user-approved privilege context.', 'Run /usr/bin/claude-cage agent capabilities. The name cage belongs to a different Linux program.'] }, | |
| 103 | 新增: 'win32-amd64': { guide: 'https://lee-xeo.github.io/Claude-Cage/docs/installation/', argv: ['<downloaded_absolute_path>', '/S'], steps: ['Save work and stop Cage before an update. Inspect Get-AuthenticodeSignature on signed packages.', 'Run the installer in the user-approved context; system security prompts require the user.', 'Default per-user CLI: $env:LOCALAPPDATA\\Programs\\Cage\\resources\\cage.exe. Honor any custom install directory; then run agent capabilities.'] }, | |
| 104 | 新增: }[options.platform]; | |
| 105 | 新增: return { protocol, status: 'planned', release: selected.tag, release_url: `https://github.com/${repo}/releases/tag/${selected.tag}`, platform: options.platform, asset: selected.asset.name, url: selected.asset.browser_download_url, size: selected.asset.size, sha256, unsigned: selected.unsigned, cli, installation, data_policy: 'Preserve ~/.claude-cage, user projects and persistent VM disks. Downloads and application files are separate from profile data.' }; | |
| 106 | 新增:} | |
| 107 | 新增: | |
| 108 | 新增:export async function downloadPlan(plan, destination, fetchImpl = fetch) { | |
| 109 | 新增: if (!isAbsolute(destination)) fail('invalid_input', 'Destination must be an absolute directory.'); | |
| 110 | 新增: await mkdir(destination, { recursive: true }); | |
| 111 | 新增: const stage = await mkdtemp(join(destination, '.cage-download-')); | |
| 112 | 新增: try { | |
| 113 | 新增: const temp = join(stage, plan.asset); | |
| 114 | 新增: const response = await httpsResponse(plan.url, fetchImpl); | |
| 115 | 新增: const hash = createHash('sha256'); let size = 0; | |
| 116 | 新增: const verify = new Transform({ transform(chunk, encoding, callback) { | |
| 117 | 新增: size += chunk.length; | |
| 118 | 新增: if (size > plan.size) { callback(new BootstrapError('size_mismatch', 'Package exceeds the release size.', 'plan')); return; } | |
| 119 | 新增: hash.update(chunk); callback(null, chunk); | |
| 120 | 新增: } }); | |
| 121 | 新增: await pipeline(Readable.fromWeb(response.body), verify, createWriteStream(temp, { flags: 'wx', mode: 0o600 })); | |
| 122 | 新增: if (size !== plan.size || hash.digest('hex') !== plan.sha256) fail('checksum_mismatch', 'Package size or SHA-256 does not match the selected release. The staged download was discarded.'); | |
| 123 | 新增: await chmod(temp, 0o600); | |
| 124 | 新增: const path = join(destination, plan.asset); | |
| 125 | 新增: // link is exclusive: never truncate a prior download, application or data. | |
| 126 | 新增: await link(temp, path); | |
| 127 | 新增: const installation = { ...plan.installation }; | |
| 128 | 新增: if (installation.argv) installation.argv = installation.argv.map(arg => arg === '<downloaded_absolute_path>' ? path : arg); | |
| 129 | 新增: return { ...plan, status: 'downloaded', path, installation }; | |
| 130 | 新增: } finally { await rm(stage, { recursive: true, force: true }); } | |
| 131 | 新增:} | |
| 132 | 新增: | |
| 133 | 新增:export async function main(args = process.argv.slice(2)) { | |
| 134 | 新增: try { | |
| 135 | 新增: const options = parseArgs([...args]); | |
| 136 | 新增: let result = await makePlan(options); | |
| 137 | 新增: if (options.action === 'download') result = await downloadPlan(result, options.destination); | |
| 138 | 新增: process.stdout.write(`${JSON.stringify(result)}\n`); | |
| 139 | 新增: } catch (error) { | |
| 140 | 新增: // Network errors can contain URLs; use bounded static messages on unknown errors. | |
| 141 | 新增: const known = error instanceof BootstrapError; | |
| 142 | 新增: process.stdout.write(`${JSON.stringify({ protocol, status: 'error', error: { code: known ? error.code : error.code === 'EEXIST' ? 'destination_exists' : 'bootstrap_failed', message: known ? error.message : 'Could not prepare the package. Preserve existing files and inspect connectivity, destination permissions and available space.', next_action: known ? error.next_action : 'plan' } })}\n`); | |
| 143 | 新增: process.exitCode = known && error.code === 'invalid_input' ? 2 : 1; | |
| 144 | 新增: } | |
| 145 | 新增:} | |
| 146 | 新增: | |
| 147 | 新增:if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) await main(); | |
| @@ -0,0 +1,18 @@ | ||
| 1 | 新增:#!/bin/sh | |
| 2 | 新增:# Cage download/installation plan. No application or profile is changed. | |
| 3 | 新增:# sh install.sh plan [--version TAG] [--platform darwin-arm64|win32-amd64|linux-amd64] | |
| 4 | 新增:# sh install.sh download --destination /absolute/path [--version TAG] | |
| 5 | 新增:set -eu | |
| 6 | 新增:if ! command -v node >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1; then | |
| 7 | 新增: printf '%s\n' '{"protocol":1,"status":"error","error":{"code":"dependency_missing","message":"Cage bootstrap requires Node.js 20+ and curl. Read https://lee-xeo.github.io/Claude-Cage/agent.md","next_action":"install_dependencies"}}' | |
| 8 | 新增: exit 1 | |
| 9 | 新增:fi | |
| 10 | 新增:cage_bootstrap_tmp=$(mktemp -d) | |
| 11 | 新增:trap 'rm -rf "$cage_bootstrap_tmp"' EXIT | |
| 12 | 新增:trap 'exit 1' HUP INT TERM | |
| 13 | 新增:if ! curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --connect-timeout 15 --max-time 120 \ | |
| 14 | 新增: https://lee-xeo.github.io/Claude-Cage/agent-bootstrap.mjs -o "$cage_bootstrap_tmp/bootstrap.mjs"; then | |
| 15 | 新增: printf '%s\n' '{"protocol":1,"status":"error","error":{"code":"download_failed","message":"Could not download the public Cage bootstrap. No application or profile was changed.","next_action":"check_connectivity"}}' | |
| 16 | 新增: exit 1 | |
| 17 | 新增:fi | |
| 18 | 新增:node "$cage_bootstrap_tmp/bootstrap.mjs" "$@" | |
| @@ -0,0 +1,14 @@ | ||
| 1 | 新增:# Cage | |
| 2 | 新增: | |
| 3 | 新增:> Cage is a local and remote isolated development workbench. External agents can help users download, install, configure and diagnose it through the versioned JSON CLI. | |
| 4 | 新增: | |
| 5 | 新增:- [Agent guide](https://lee-xeo.github.io/Claude-Cage/agent.md): Read this first. Installation paths, protocol discovery, JSON input, tasks, recovery and user authorization boundaries. | |
| 6 | 新增:- [Full agent guide](https://lee-xeo.github.io/Claude-Cage/llms-full.txt): Plain-text copy of the same source. | |
| 7 | 新增:- [User guide](https://lee-xeo.github.io/Claude-Cage/docs/agent/): Rendered guide. | |
| 8 | 新增:- [Download helper](https://lee-xeo.github.io/Claude-Cage/agent-bootstrap.mjs): Node.js 20+, public release discovery and verified package download. Returns an installation plan; does not install. | |
| 9 | 新增:- [Releases](https://github.com/Lee-xeo/Claude-Cage/releases): Published packages and platform-specific validation limits. | |
| 10 | 新增: | |
| 11 | 新增:Discover installed capabilities before changing anything: <installed CLI> agent capabilities | |
| 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. | |
| 14 | 新增:Preserve existing profile data, accounts, projects and VM disks. Never disable network isolation or system security checks to complete setup. | |
| @@ -84,6 +84,14 @@ for (const code of codes) { | ||
| 84 | 84 | } |
| 85 | 85 | console.log(`Verified ${guideFiles.length} user guide pages, local links, anchors, search and homepage entries.`); |
| 86 | 86 | |
| 87 | 新增:const agentGuide = fs.readFileSync(path.join(dist, 'agent.md'), 'utf8'); | |
| 88 | 新增:assert.equal(agentGuide, fs.readFileSync(path.join(dist, 'llms-full.txt'), 'utf8'), 'Agent text copies must share the same source'); | |
| 89 | 新增:assert.ok(agentGuide.includes('agent capabilities') && agentGuide.includes('job_not_found'), 'Agent guide lacks discovery or recovery contract'); | |
| 90 | 新增:assert.ok(!agentGuide.includes('title: 让 Agent'), 'Agent Markdown must omit frontmatter'); | |
| 91 | 新增:for (const name of ['llms.txt', 'agent-bootstrap.mjs', 'cage-install.sh']) assert.ok(fs.existsSync(path.join(dist, name)), `Missing Agent entry ${name}`); | |
| 92 | 新增:assert.ok(fs.readFileSync(path.join(dist, 'docs/agent/index.html'), 'utf8').includes('JSON 结果和异步任务'), 'Rendered Agent guide missing'); | |
| 93 | 新增:console.log('Verified Agent Markdown, discovery, download helper and rendered guide.'); | |
| 94 | 新增: | |
| 87 | 95 | const screenshotManifest = JSON.parse(fs.readFileSync(path.join(root, 'www/public/docs/screenshots/manifest.json'), 'utf8')); |
| 88 | 96 | for (const shot of screenshotManifest) { |
| 89 | 97 | assert.ok(shot.version && shot.platform && shot.capturedAt && shot.source, `${shot.id}: screenshot provenance missing`); |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增:import guide from '../../../docs/guide/agent.md?raw'; | |
| 2 | 新增: | |
| 3 | 新增:export function GET() { | |
| 4 | 新增: const text = guide.replace(/^---\n[\s\S]*?\n---\n/, '').replace(/\]\(([a-z-]+)\.md(#[^)]*)?\)/g, (_, slug: string, hash = '') => `](https://lee-xeo.github.io/Claude-Cage/docs/${slug}/${hash})`); | |
| 5 | 新增: return new Response(text, { headers: { 'Content-Type': 'text/markdown; charset=utf-8' } }); | |
| 6 | 新增:} | |
| @@ -0,0 +1 @@ | ||
| 1 | 新增:export { GET } from './agent.md'; | |

