跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录
修改.github/workflows/macos-build.yml+2 −0看文件
@@ -73,6 +73,8 @@ jobs:
7373 go vet ./cmd/cage ./internal/cage ./internal/managedproxy ./internal/workbench
7474 - name: Native application updater
7575 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"
7678 - name: Native account credential status
7779 run: bash scripts/test-account-device.sh
7880 - name: Patched networking and shared files
修改.github/workflows/www.yml+4 −2看文件
@@ -2,9 +2,9 @@ name: Website and public releases
22on:
33 push:
44 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']
66 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']
88 release:
99 types: [published]
1010 workflow_dispatch:
@@ -61,6 +61,8 @@ jobs:
6161 cache-dependency-path: www/package-lock.json
6262 - run: npm ci --prefix www
6363 - 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
6466 - name: Resolve the public download version
6567 env:
6668 RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }}
新增AGENT-USE.md+9 −0看文件
@@ -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.
修改README.md+1 −0看文件
@@ -104,6 +104,7 @@ macOS 和已签名 Windows 版本支持通过所选代理更新;Windows 未签
104104
105105| 你要做什么 | 从这里开始 |
106106|---|---|
107新增:| 让自己的 Agent 下载、安装、配置和排查 Cage | [Agent 使用指南](https://lee-xeo.github.io/Claude-Cage/docs/agent/) |
107108| 第一次安装、配置代理、打开项目 | [安装与首次启动](https://lee-xeo.github.io/Claude-Cage/docs/installation/) |
108109| 选择 macOS、Windows、Debian 或 Ubuntu 22.04 客机,使用原生开发工具 | [选择客机系统](https://lee-xeo.github.io/Claude-Cage/docs/guest-systems/) |
109110| 添加多个订阅、查看额度和分配终端 | [多账号与额度](https://lee-xeo.github.io/Claude-Cage/docs/accounts/) |
新增cmd/cage/agent.go+357 −0看文件
@@ -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新增:}
新增cmd/cage/agent_test.go+76 −0看文件
@@ -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新增:}
修改cmd/cage/main.go+4 −0看文件
@@ -34,6 +34,7 @@ import (
3434const help = `Claude Cage — local isolated Claude development
3535
3636cage desktop Open the unified Cage workbench (desktop launcher)
37新增:cage agent Discover and use the versioned, JSON-only external Agent interface
3738cage serve Run its private localhost control service
3839cage server-entry --json Issue a private SSH remote connection entry
3940cage container-configure --json Configure a Linux container from JSON stdin
@@ -89,6 +90,9 @@ func run() int {
8990 fmt.Print(help)
9091 return 0
9192 }
93新增: if args[0] == "agent" {
94新增: return runAgent(args[1:], os.Stdin, os.Stdout)
95新增: }
9296 if args[0] == "verify-web-assets" {
9397 if len(args) != 1 {
9498 return 2
修改docs/README.md+1 −0看文件
@@ -8,6 +8,7 @@
88
99| 你要做什么 | 从这里开始 |
1010|---|---|
11新增:| 让自己的 Agent 下载、安装、配置 Cage,跟踪任务并排查故障 | [Agent 使用指南](guide/agent.md) |
1112| 选择 macOS、Windows、Linux 安装包,配置代理并打开第一个项目 | [开始使用](getting-started.md) |
1213| 选择与主机同类的客机系统,了解原生工具、镜像与数据保留 | [选择客机系统](guide/guest-systems.md) |
1314| 查看快捷键、文件保存、关闭与退出行为 | [日常使用](getting-started.md#日常使用) |
新增docs/guide/agent.md+212 −0看文件
@@ -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新增:完成后用几句话说明:实际安装的版本和路径、使用的配置与客机、代理是否应用、环境是否运行、网络检查是否通过、项目是否连接。列出需要用户完成的授权和登录,以及尚未验证的范围。仅完成下载、模拟请求或单平台编译时,分别报告,不写成完整安装或三平台实测成功。
修改docs/guide/index.md+1 −0看文件
@@ -29,6 +29,7 @@ Cage 把终端、浏览器、编辑器和官方 Claude Desktop 放进同一个
2929
3030| 你想做什么 | 阅读哪篇 |
3131| --- | --- |
32新增:| 把安装、配置与排障交给自己的 Agent | [让 Agent 配置 Cage](agent.md) |
3233| 安装应用、换盘、准备本机虚拟化 | [安装与首次启动](installation.md) |
3334| 使用与主机同类的系统、选择原生开发工具 | [选择客机系统](guest-systems.md) |
3435| 导入订阅、连接住宅代理、设置出口规则 | [网络与代理](network.md) |
新增internal/workbench/agent.go+420 −0看文件
@@ -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新增:}
新增internal/workbench/agent_test.go+268 −0看文件
@@ -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新增:}
修改internal/workbench/control_lifecycle.go+2 −0看文件
@@ -35,6 +35,8 @@ func (identity ControllerIdentity) matches(other ControllerIdentity) bool {
3535}
3636
3737type launchResponse struct {
38新增: ConfigPath string `json:"config_path,omitempty"`
39新增: ClientOnly bool `json:"client_only,omitempty"`
3840 DesktopGateway bool `json:"desktop_gateway,omitempty"`
3941 URL string `json:"url"`
4042 Controller ControllerIdentity `json:"controller"`
修改internal/workbench/diagnostics.go+36 −12看文件
@@ -109,6 +109,16 @@ func ExportDiagnostics(configPath, destination string) error {
109109}
110110
111111func 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 {
112122 if !filepath.IsAbs(destination) {
113123 return errors.New("请选择本机绝对保存路径")
114124 }
@@ -126,7 +136,13 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string
126136 return err
127137 }
128138 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新增: }
130146 if e != nil {
131147 if connectionID != "" && connectionID != "local" {
132148 return errors.New("远程连接不可用,无法导出云端诊断包")
@@ -137,20 +153,25 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string
137153 return store.Export(f, version.Version, nil, "controller unavailable or invalid; host logs only")
138154 }
139155 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新增: }
151169 }
152170 c.client.Timeout = 30 * time.Second
153171 req, _ := http.NewRequest("GET", c.origin+"/api/diagnostics/export", nil)
172新增: if agentLocal {
173新增: req.Header.Set(connectionHeader, "local")
174新增: }
154175 response, e := c.client.Do(req)
155176 if e != nil {
156177 return e
@@ -184,6 +205,9 @@ func ExportDiagnosticsForConnection(configPath, connectionID, destination string
184205 return errors.New("诊断包未完整生成,请重新导出")
185206 }
186207 _ = archive.Close()
208新增: if agentLocal {
209新增: return os.Link(temp, destination)
210新增: }
187211 // Never follow a destination symlink or replace a directory.
188212 if st, e := os.Lstat(destination); e == nil && !st.Mode().IsRegular() {
189213 return errors.New("请选择普通文件作为保存位置")
修改internal/workbench/jobs.go+2 −0看文件
@@ -13,6 +13,7 @@ import (
1313)
1414
1515type Job struct {
16新增: Canceled bool `json:"canceled,omitempty"`
1617 SetupProgress *SetupProgress `json:"setup_progress,omitempty"`
1718 ID string `json:"id"`
1819 Kind string `json:"kind"`
@@ -154,6 +155,7 @@ func (m *jobManager) finishLocked(execution *jobExecution, err error) {
154155 m.state.Running = false
155156 switch {
156157 case errors.Is(err, context.Canceled):
158新增: m.state.Canceled = true
157159 m.state.Message = "已取消"
158160 diagnostics.Log("info", "task", m.state.Kind+" canceled")
159161 case err != nil:
修改internal/workbench/macos_login.go+3 −0看文件
@@ -27,6 +27,9 @@ func (s *Server) macSetupPending() bool {
2727}
2828
2929func macOSSetupRoute(path string) bool {
30新增: if strings.HasPrefix(path, "/api/agent/jobs/") {
31新增: return true
32新增: }
3033 if !strings.HasPrefix(path, "/api/") {
3134 return true
3235 }
修改internal/workbench/native_routes.go+3 −0看文件
@@ -9,6 +9,8 @@ func nativeWorkbenchRoute(path string) bool {
99 return true
1010 }
1111 switch path {
12新增: case "/api/agent/settings":
13新增: return true
1214 case "/api/account", "/api/session", "/api/launch", "/api/handoff", "/api/remote/manifest",
1315 "/api/appearance", "/api/favorites", "/api/status", "/api/settings", "/api/settings/probe",
1416 "/api/start", "/api/stop", "/api/restore", "/api/host/git", "/api/projects/open", "/api/projects/directories",
@@ -20,6 +22,7 @@ func nativeWorkbenchRoute(path string) bool {
2022 return true
2123 }
2224 for _, prefix := range []string{
25新增: "/api/agent/jobs/",
2326 "/api/account/", "/api/terminals/", "/api/claude-accounts/", "/api/cli/sessions/", "/api/proxy/",
2427 "/api/browser/", "/api/clipboard/files/", "/api/input/files/browser/", "/api/input/files/terminal/",
2528 "/api/tailscale/", "/api/mobile/cli/", "/api/mobile/browser/", "/api/mobile/desktop/", "/api/diagnostics",
修改internal/workbench/server.go+2 −1看文件
@@ -312,6 +312,7 @@ func serve(configPath string, clientOnly bool, fullConfigPath string) (returned
312312}
313313func (s *Server) handler() http.Handler {
314314 mux := http.NewServeMux()
315新增: s.agentRoutes(mux)
315316 s.mobileCLIRoutes(mux)
316317 s.mobileSurfaceRoutes(mux)
317318 mux.HandleFunc("GET /api/mobile-pair", s.phoneStatus)
@@ -323,7 +324,7 @@ func (s *Server) handler() http.Handler {
323324 if !s.launcherAuthenticated(w, r) {
324325 return
325326 }
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})
327328 })
328329 if s.desktopEntry || s.clientOnly {
329330 mux.HandleFunc("POST /api/handoff", s.handoffEntry)
新增scripts/agent-bootstrap.test.mjs+65 −0看文件
@@ -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新增:});
新增scripts/agent-cli-smoke.mjs+68 −0看文件
@@ -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新增:}
新增www/public/agent-bootstrap.mjs+147 −0看文件
@@ -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();
新增www/public/cage-install.sh+18 −0看文件
@@ -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" "$@"
新增www/public/llms.txt+14 −0看文件
@@ -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.
修改www/scripts/check-site.mjs+8 −0看文件
@@ -84,6 +84,14 @@ for (const code of codes) {
8484}
8585console.log(`Verified ${guideFiles.length} user guide pages, local links, anchors, search and homepage entries.`);
8686
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新增:
8795const screenshotManifest = JSON.parse(fs.readFileSync(path.join(root, 'www/public/docs/screenshots/manifest.json'), 'utf8'));
8896for (const shot of screenshotManifest) {
8997 assert.ok(shot.version && shot.platform && shot.capturedAt && shot.source, `${shot.id}: screenshot provenance missing`);
新增www/src/pages/agent.md.ts+6 −0看文件
@@ -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新增:}
新增www/src/pages/llms-full.txt.ts+1 −0看文件
@@ -0,0 +1 @@
1新增:export { GET } from './agent.md';