跳到主要内容

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

提交记录

统一用户与 Agent 的配置和原生操作入口

补齐配置命名操作,提供共用认证与连接代次的 HTTP、二进制和 WebSocket 入口。桌面原生队列复用现有桥与系统认证,客户端偏好写入同一存储,并以私有窗口证明保护认领和回执。 验证:独立暂存源码的 Go 回归、race 与 vet;123 项前端测试、lint 和构建;真实 CLI、轻客户端与浏览器双向配置验证;Windows/Linux CLI 交叉编译;网站检查。物理系统授权与真实客机未实测。

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