跳到主要内容

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

浏览文件

agent.go

463 行 · 22.7 KB历史下载
1package workbench
2
3// The agent adapter uses the same authenticated local workload as the desktop.
4// It never follows the desktop gateway's currently selected remote connection.
5import (
6 "bytes"
7 "context"
8 "encoding/json"
9 "errors"
10 "net/http"
11 "net/url"
12 "path/filepath"
13 "reflect"
14 "strings"
15 "time"
16
17 "github.com/sylvinus/agent-vm/internal/diagnostics"
18 "github.com/sylvinus/agent-vm/internal/remotehost"
19)
20
21const AgentProtocol = 1
22
23type AgentOperation struct {
24 Name string `json:"name"`
25 Description string `json:"description"`
26 Mutates bool `json:"mutates"`
27 InputSchema map[string]any `json:"input_schema"`
28 method, path string
29}
30
31// 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.
33func AgentOperations() []AgentOperation {
34 object := func(fields map[string]string) map[string]any {
35 properties := map[string]any{}
36 for name, kind := range fields {
37 if kind == "array" {
38 properties[name] = map[string]any{"type": kind, "items": map[string]string{"type": "string"}}
39 } else {
40 properties[name] = map[string]string{"type": kind}
41 }
42 }
43 return map[string]any{"type": "object", "properties": properties, "additionalProperties": false}
44 }
45 from := func(value any) map[string]any { return agentSchema(reflect.TypeOf(value)) }
46
47 var ops []AgentOperation
48 add := func(name, description, method, path string, schema map[string]any) {
49 ops = append(ops, AgentOperation{Name: name, Description: description, Mutates: method != "GET", InputSchema: schema, method: method, path: path})
50 }
51 get := func(name, description, path string) { add(name, description, "GET", path, object(nil)) }
52 post := func(name, description, path string, schema map[string]any) {
53 add(name, description, "POST", path, schema)
54 }
55 get("status", "Environment readiness, network checks and current job", "/api/status")
56 get("account.status", "Account presence and lock state; no credentials", "/api/account")
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"}))
58 post("account.unlock", "Unlock using a user-provided password via private input", "/api/account/unlock", object(map[string]string{"password": "string"}))
59 get("settings.get", "Read settings without proxy credentials", "/api/settings")
60 post("settings.patch", "Merge specified fields under the operation lock; dry_run validates without writing", "/api/agent/settings", object(map[string]string{"patch": "object", "dry_run": "boolean"}))
61 // Include the production Settings schema inside the patch field.
62 ops[len(ops)-1].InputSchema["properties"].(map[string]any)["patch"] = from(Settings{})
63 ops[len(ops)-1].InputSchema["properties"].(map[string]any)["patch"].(map[string]any)["properties"].(map[string]any)["exit_policy"] = object(map[string]string{"mode": "string", "scope": "string", "ip": "string", "country_code": "string", "region": "string", "city": "string"})
64 post("settings.restore", "Restore the saved previous settings and restart the environment; inspect status and obtain permission to interrupt work first", "/api/restore", object(nil))
65 get("proxy.status", "List source and node IDs without subscription URLs or node secrets", "/api/proxy")
66 proxy := from(proxyInput{})
67 for _, action := range []string{"import", "refresh", "edit", "delete", "select", "route", "restart", "stop"} {
68 post("proxy."+action, "Proxy operation; import creates a source, refresh updates an existing source. Read state before retrying. select/route applies the route", "/api/proxy/"+action, proxy)
69 }
70 get("guest.options", "Available guest systems and resumable installation state", "/api/environment/guest-systems")
71 get("guest.match", "Inspect a host-matching clean image plan; pass key as clone_key and plan.host.system as guest_system to environment.start", "/api/environment/guest-systems/clone")
72 post("guest.activate", "Activate an installed guest; controller may retire, reconnect afterwards", "/api/environment/guest-systems/activate", object(nil))
73 get("initialization.status", "Read initial setup state", "/api/environment/initialization")
74 post("initialization.set", "action: begin, install or complete; complete requires verified readiness", "/api/environment/initialization", object(map[string]string{"action": "string"}))
75 post("environment.start", "Start or resume installation. Omit guest_system for an existing environment; use guest.options for supported choices", "/api/start", from(guestInstallRequest{}))
76 post("environment.stop", "Stop the environment and active terminals; preserves persistent data", "/api/stop", object(nil))
77 get("environment.versions", "Read installed component and tool versions", "/api/environment/versions")
78 post("environment.update", "Update guest components; may restart guest services", "/api/environment/update", object(nil))
79 post("environment.tools", "Update tools to this build's versions", "/api/environment/tools", object(nil))
80 get("resources.get", "Read platform resource limits and recommendations", "/api/environment/resources")
81 post("resources.set", "Save allocation={automatic,memory_gib,cpus}; send {} separately to apply and restart", "/api/environment/resources", object(map[string]string{"allocation": "object"}))
82 ops[len(ops)-1].InputSchema["properties"].(map[string]any)["allocation"] = object(map[string]string{"automatic": "boolean", "memory_gib": "integer", "cpus": "integer"})
83 get("storage.get", "Read storage location and migration prerequisites", "/api/environment/storage")
84 post("storage.set", "Migrate using the previous directory and has_environment value from storage.get; stops running tasks", "/api/environment/storage", object(map[string]string{"directory": "string", "previous": "string", "migrate": "boolean"}))
85 post("network.check", "Run existing safety checks; may reopen networking when checks pass", "/api/safety/check", object(nil))
86 post("network.pause", "Close external networking and persist pause intent", "/api/safety/close", object(nil))
87 post("project.open", "Grant access only to a user-authorized directory; add=true remembers the grant", "/api/projects/open", object(map[string]string{"workspace": "string", "add": "boolean", "activate": "boolean"}))
88 post("project.remove", "Remove an added directory and revoke its share. Close its terminals, running sessions and editor first. Preserve files and history", "/api/projects/remove", object(map[string]string{"workspace": "string"}))
89
90 for _, action := range []string{"profile", "password", "lock", "logout", "suspend"} {
91 schema := object(nil)
92 if action == "profile" {
93 schema = object(map[string]string{"username": "string", "avatar": "string"})
94 }
95 if action == "password" {
96 schema = object(map[string]string{"old_password": "string", "password": "string", "confirm_password": "string"})
97 }
98 post("account."+action, "Same account action and verification as the workbench", "/api/account/"+action, schema)
99 }
100 get("host.git", "Inspect the same host Git prerequisite as first setup", "/api/host/git")
101 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"}))
102 get("appearance.get", "Read complete appearance and saved themes", "/api/appearance")
103 post("appearance.set", "Save complete appearance using the workbench validator", "/api/appearance", from(Appearance{}))
104 get("appearance.codex", "Read the same local Codex appearance import as the UI", "/api/appearance/codex")
105 post("settings.probe", "Probe actual exit location for a complete settings draft", "/api/settings/probe", from(Settings{}))
106 get("proxy.connections", "Inspect live proxy connections", "/api/proxy/connections")
107 get("proxy.logs", "Inspect proxy logs", "/api/proxy/logs")
108 post("proxy.delay", "Measure one proxy node", "/api/proxy/delay", object(map[string]string{"node_id": "string"}))
109 add("guest.reselect", "Clear only the same unstarted installation the UI can reselect", "DELETE", "/api/environment/guest-systems", object(map[string]string{"id": "string"}))
110 get("claude-accounts.get", "Read account roster, quotas and scheduling", "/api/claude-accounts")
111 post("claude-accounts.change", "Apply the same join, cancel, update, scheduling, refresh and removal actions as the UI", "/api/claude-accounts", from(claudeAccountInput{}))
112 get("vault.get", "List metadata; passwords remain hidden exactly as in the UI", "/api/vault")
113 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"}))
114 ops[len(ops)-1].InputSchema["properties"].(map[string]any)["entry"] = from(vaultEntry{})
115 post("vault.browser", "Use the browser vault's existing save/fill/block actions", "/api/vault/browser", from(vaultBrowserInput{}))
116 get("mobile.get", "Inspect phone pairing", "/api/mobile-pair")
117 post("mobile.pair", "Generate the same phone pairing invitation", "/api/mobile-pair", object(map[string]string{"admin": "string", "relay": "string"}))
118 add("mobile.remove", "Remove the same paired device", "DELETE", "/api/mobile-pair", object(nil))
119 get("tailscale.get", "Read guest private-network state", "/api/tailscale")
120 for _, action := range []string{"install", "connect", "login", "disconnect", "logout", "add-key", "remove-key"} {
121 schema := object(nil)
122 if action == "add-key" || action == "remove-key" {
123 schema = object(map[string]string{"key": "string"})
124 }
125 post("tailscale."+action, "Run the same Tailscale action as the workbench", "/api/tailscale/"+action, schema)
126 }
127 get("browser.preferences.get", "Read the browser homepage", "/api/browser/preferences")
128 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"}))
129 get("browser.tabs", "Read browser tabs and state", "/api/browser/tabs")
130 for _, action := range []string{"settings", "cookies", "extensions", "internal-page", "info", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "split"} {
131 post("browser."+action, "Use the browser's existing workbench action", "/api/browser/"+action, from(browserInput{}))
132 }
133 get("favorites.get", "Read bookmarks and folders", "/api/favorites")
134 post("favorites.change", "Save, move, reorder or delete using the same collection owner", "/api/favorites", from(favoriteChange{}))
135 get("terminals.get", "Read terminal sessions", "/api/terminals")
136 post("terminals.create", "Create the same shell/Claude terminal as the UI", "/api/terminals", from(terminalRequest{}))
137 get("client.context", "Read the desktop connection generation; use desktop scope", "/api/client/context")
138 get("client.hosts", "Read saved SSH hosts; use desktop scope", "/api/client/hosts")
139 post("client.hosts.create", "Save an SSH host through the desktop store", "/api/client/hosts", from(remotehost.HostProfile{}))
140 get("client.local-status", "Inspect local workload from the desktop chooser", "/api/client/local-status")
141 for _, action := range []string{"candidate", "commit", "cancel", "disconnect", "local-stop"} {
142 post("client."+action, "Use the desktop chooser's same explicit connection/candidate protocol", "/api/client/"+action, from(switchRequest{}))
143 }
144 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"}))
145 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"}))
146
147 get("diagnostics.status", "Read log collection status", "/api/diagnostics")
148 return ops
149}
150
151type AgentError struct {
152 Code string `json:"code"`
153 Message string `json:"message"`
154 NextAction string `json:"next_action"`
155 Retryable bool `json:"retryable"`
156 HTTPStatus int `json:"http_status,omitempty"`
157}
158
159func (e *AgentError) Error() string { return e.Message }
160
161func agentHTTPError(code int) *AgentError {
162 e := &AgentError{Code: "request_rejected", Message: "Cage rejected the operation. Check the input and run doctor.", NextAction: "doctor", HTTPStatus: code}
163 switch code {
164 case 401:
165 e.Code = "authentication_failed"
166 e.NextAction = "service.start"
167 case 423:
168 e.Code = "account_locked"
169 e.Message = "Unlock Cage before configuring the environment."
170 e.NextAction = "account.unlock"
171 case 403:
172 e.Code = "user_action_required"
173 e.Message = "This operation requires a local system or account action."
174 e.NextAction = "open_desktop"
175 case 409:
176 e.Code = "state_conflict"
177 e.Message = "The environment state does not permit this operation. Read status before retrying."
178 e.NextAction = "status"
179 case 410:
180 e.Code = "job_not_found"
181 e.Message = "The original job is no longer available. Inspect state before submitting again."
182 e.NextAction = "status"
183 case 404:
184 e.Code = "unsupported_operation"
185 e.Message = "This controller or guest does not support the operation."
186 e.NextAction = "capabilities"
187 case 429, 503:
188 e.Code = "service_busy"
189 e.NextAction = "status"
190 e.Retryable = true
191 }
192 return e
193}
194
195// AgentStartService starts only an absent service. It never hands off, upgrades
196// or stops an existing controller as a side effect of an agent call.
197func AgentStartService(ctx context.Context, configPath string) error {
198 profile := filepath.Dir(configPath)
199 c, err := connectController(profile)
200 if err == nil {
201 defer c.close()
202 return agentCheckController(c, configPath)
203 }
204 if !errors.Is(err, errControllerUnavailable) || !controllerLockFree(profile) {
205 return &AgentError{Code: "service_unavailable", Message: "The controller cannot be authenticated. Preserve its data and inspect diagnostics.", NextAction: "doctor"}
206 }
207 if err := startController(configPath); err != nil {
208 return &AgentError{Code: "service_start_failed", Message: "Cage could not start its controller.", NextAction: "doctor"}
209 }
210 timer := time.NewTicker(100 * time.Millisecond)
211 defer timer.Stop()
212 for {
213 select {
214 case <-ctx.Done():
215 return &AgentError{Code: "service_start_timeout", Message: "The controller has not become ready. It may still be starting.", NextAction: "doctor", Retryable: true}
216 case <-timer.C:
217 c, err := connectController(profile)
218 if err == nil {
219 defer c.close()
220 return agentCheckController(c, configPath)
221 }
222 }
223 }
224}
225
226func agentCheckController(c *controllerClient, configPath string) error {
227 want, err := currentController()
228 if err != nil || !want.matches(c.launch.Controller) || c.launch.DesktopGateway || c.launch.ClientOnly {
229 return &AgentError{Code: "controller_mismatch", Message: "Use the CLI shipped with the running workload. No controller was replaced.", NextAction: "open_desktop"}
230 }
231 if filepath.Clean(c.launch.ConfigPath) != filepath.Clean(configPath) {
232 return &AgentError{Code: "config_path_mismatch", Message: "This directory's controller uses a different configuration filename. Use its original absolute config path.", NextAction: "doctor"}
233 }
234 return nil
235}
236
237func agentConnect(ctx context.Context, configPath string) (*controllerClient, error) {
238 c, err := connectController(filepath.Dir(configPath))
239 if err != nil {
240 return nil, &AgentError{Code: "service_unavailable", Message: "The local Cage controller is unavailable. Run service.start or doctor.", NextAction: "service.start"}
241 }
242 fail := func(err error) (*controllerClient, error) { c.close(); return nil, err }
243 if err := agentCheckController(c, configPath); err != nil {
244 return fail(err)
245 }
246 u, _ := url.Parse(c.launch.URL)
247 code, err := c.callContext(ctx, "POST", "/api/session", map[string]string{"token": u.Fragment}, nil)
248 if err != nil || code != 200 {
249 return fail(agentHTTPError(401))
250 }
251 // Same proof as the existing local desktop transport. Possession is checked
252 // through the private launcher record; account locking still applies.
253 c.client.Jar.SetCookies(u, []*http.Cookie{{Name: cookieName + "_" + u.Port() + "-desktop", Value: trustedViewProof(c.record.Token), Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode}})
254 return c, nil
255}
256
257func AgentCall(ctx context.Context, configPath, operation string, input json.RawMessage) (json.RawMessage, error) {
258 return AgentCallTarget(ctx, configPath, AgentTarget{}, operation, input)
259}
260
261func agentValidateInput(input json.RawMessage, schema map[string]any) error {
262 if len(input) == 0 {
263 input = json.RawMessage(`{}`)
264 }
265 var value map[string]json.RawMessage
266 if json.Unmarshal(input, &value) != nil || value == nil {
267 return &AgentError{Code: "invalid_input", Message: "Expected one JSON object.", NextAction: "capabilities"}
268 }
269 properties := schema["properties"].(map[string]any)
270 for key := range value {
271 if _, ok := properties[key]; !ok {
272 return &AgentError{Code: "invalid_input", Message: "Unknown input field; read the operation's input_schema.", NextAction: "capabilities"}
273 }
274 }
275 return nil
276}
277
278func AgentJob(ctx context.Context, configPath, id string) (json.RawMessage, error) {
279 if len(id) != 12 || strings.Trim(id, "0123456789abcdef") != "" {
280 return nil, &AgentError{Code: "invalid_input", Message: "Expected a 12-character job id.", NextAction: "status"}
281 }
282 return agentRequest(ctx, configPath, "GET", "/api/agent/jobs/"+id, nil)
283}
284
285func agentRequest(ctx context.Context, configPath, method, path string, input json.RawMessage) (json.RawMessage, error) {
286 response, err := AgentRequest(ctx, configPath, AgentTarget{}, method, path, strings.NewReader(string(input)), "application/json", "")
287 return response.Data, err
288}
289
290func (s *Server) agentRoutes(mux routeRegistrar) {
291 mux.HandleFunc("GET /api/agent/jobs/{id}", func(w http.ResponseWriter, r *http.Request) {
292 job := s.jobs.snapshot()
293 if job.ID == "" || job.ID != r.PathValue("id") {
294 http.Error(w, "Original job no longer available", http.StatusGone)
295 return
296 }
297 jsonReply(w, job)
298 })
299 mux.HandleFunc("POST /api/agent/settings", s.agentSettings)
300}
301
302func agentRedact(data string) string {
303 var value any
304 if json.Unmarshal([]byte(data), &value) != nil {
305 return diagnostics.Redact(data)
306 }
307 var clean func(any)
308 clean = func(value any) {
309 switch v := value.(type) {
310 case map[string]any:
311 for key, item := range v {
312 if text, ok := item.(string); ok && (key == "error" || key == "log" || key == "message" || key == "reason" || strings.HasSuffix(key, "_error")) {
313 v[key] = diagnostics.Redact(text)
314 } else {
315 clean(item)
316 }
317 }
318 case []any:
319 for _, item := range v {
320 clean(item)
321 }
322 }
323 }
324 clean(value)
325 body, _ := json.Marshal(value)
326 return string(body)
327}
328
329func (s *Server) agentSettings(w http.ResponseWriter, r *http.Request) {
330 var in struct {
331 Patch map[string]json.RawMessage `json:"patch"`
332 DryRun bool `json:"dry_run"`
333 }
334 if !readJSON(w, r, &in) {
335 return
336 }
337 if home, ok := in.Patch["browser_home_url"]; ok && !in.DryRun {
338 if len(in.Patch) != 1 {
339 http.Error(w, "Change browser_home_url through browser.preferences.set separately from environment settings", 400)
340 return
341 }
342 var value string
343 if json.Unmarshal(home, &value) != nil {
344 http.Error(w, "Invalid browser_home_url", 400)
345 return
346 }
347 s.saveBrowserHome(w, r, value)
348 return
349 }
350 if len(in.Patch) == 0 {
351 http.Error(w, "patch must contain at least one setting", 400)
352 return
353 }
354 propose := func() (savedProfile, error) {
355 old, err := loadConfig(s.configPath)
356 if err != nil {
357 return savedProfile{}, err
358 }
359 s.mu.Lock()
360 p := s.preferences
361 s.mu.Unlock()
362 data, _ := json.Marshal(settingsView(old, p))
363 fields := map[string]json.RawMessage{}
364 _ = json.Unmarshal(data, &fields)
365 if err := mergeAgentSettings(fields, in.Patch); err != nil {
366 return savedProfile{}, err
367 }
368 data, _ = json.Marshal(fields)
369 var input Settings
370 d := json.NewDecoder(bytes.NewReader(data))
371 d.DisallowUnknownFields()
372 if d.Decode(&input) != nil {
373 return savedProfile{}, errors.New("unknown setting or invalid value")
374 }
375 if _, err := validateBrowserHome(input.BrowserHomeURL); err != nil {
376 return savedProfile{}, err
377 }
378 c, p, err := proposedSettings(input, old, s.profile)
379 return savedProfile{Config: c, Preferences: p}, err
380 }
381 // Validate even when a different job is running; the real mutation reloads
382 // current settings only after acquiring the shared operation lock.
383 v, err := propose()
384 if err != nil {
385 requestError(w, err)
386 return
387 }
388 if in.DryRun {
389 jsonReply(w, settingsView(v.Config, v.Preferences))
390 return
391 }
392 s.launch(w, "settings", func() error {
393 v, err := propose()
394 if err != nil {
395 return err
396 }
397 return s.apply(v, true)
398 })
399}
400
401// An exit_policy patch must retain its existing IP/region anchor when only one
402// field changes. Null never clears a setting implicitly.
403func mergeAgentSettings(current, patch map[string]json.RawMessage) error {
404 for key, value := range patch {
405 value = bytes.TrimSpace(value)
406 if bytes.Equal(value, []byte("null")) {
407 return errors.New("settings cannot be null")
408 }
409 var nested map[string]json.RawMessage
410 if len(value) > 0 && value[0] == '{' && json.Unmarshal(value, &nested) == nil {
411 existing := map[string]json.RawMessage{}
412 _ = json.Unmarshal(current[key], &existing)
413 if existing == nil {
414 existing = map[string]json.RawMessage{}
415 }
416 if err := mergeAgentSettings(existing, nested); err != nil {
417 return err
418 }
419 value, _ = json.Marshal(existing)
420 }
421 current[key] = value
422 }
423 return nil
424}
425
426func agentSchema(t reflect.Type) map[string]any {
427 for t.Kind() == reflect.Pointer {
428 t = t.Elem()
429 }
430 switch t.Kind() {
431 case reflect.Struct:
432 properties := map[string]any{}
433 for i := 0; i < t.NumField(); i++ {
434 f := t.Field(i)
435 if f.PkgPath != "" {
436 continue
437 }
438 if f.Anonymous {
439 for name, schema := range agentSchema(f.Type)["properties"].(map[string]any) {
440 properties[name] = schema
441 }
442 continue
443 }
444 name := strings.Split(f.Tag.Get("json"), ",")[0]
445 if name != "" && name != "-" {
446 properties[name] = agentSchema(f.Type)
447 }
448 }
449 return map[string]any{"type": "object", "properties": properties, "additionalProperties": false}
450 case reflect.Map:
451 return map[string]any{"type": "object", "additionalProperties": agentSchema(t.Elem())}
452 case reflect.Slice, reflect.Array:
453 return map[string]any{"type": "array", "items": agentSchema(t.Elem())}
454 case reflect.Bool:
455 return map[string]any{"type": "boolean"}
456 case reflect.Int, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint32, reflect.Uint64:
457 return map[string]any{"type": "integer"}
458 case reflect.Float32, reflect.Float64:
459 return map[string]any{"type": "number"}
460 default:
461 return map[string]any{"type": "string"}
462 }
463}