跳到主要内容

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

浏览文件

network_recovery.go

193 行 · 6.8 KB历史下载
1package workbench
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "time"
8
9 "github.com/sylvinus/agent-vm/internal/cage"
10 "github.com/sylvinus/agent-vm/internal/diagnostics"
11 "github.com/sylvinus/agent-vm/internal/usererror"
12)
13
14type networkRecovery struct {
15 RunID, Configuration string
16 PauseVersion uint64
17 Epoch uint64
18 Next time.Time
19 Attempts int
20 pressureLogged bool
21}
22
23// Called with s.mu held. Reuse the ordinary network status text on every
24// platform; no independent timer or cached permission is introduced.
25func (s *Server) networkRecoveryMessageLocked(now time.Time) string {
26 r := s.recovery
27 if r.RunID == "" || s.networkPaused || s.closing || s.safety.pauseVersion != r.PauseVersion || s.safety.Gate == nil || s.safety.Gate.RunID != r.RunID || s.safety.Gate.Configuration != r.Configuration || s.safety.Gate.Mode == cage.GateOpen {
28 return ""
29 }
30 if s.safety.Gate.Mode == cage.GateClosed && s.safety.Gate.Epoch != r.Epoch {
31 return "" // A newer closure must not promise this recovery will run.
32 }
33 job := s.jobs.snapshot()
34 if s.safety.Gate.Mode != cage.GateClosed && (!job.Running || job.Kind != "network-recovery") {
35 return "" // A manual check owns the next transition.
36 }
37 if job.Running {
38 if job.Kind == "network-recovery" {
39 return "正在执行自动完整重检,通过后恢复联网"
40 }
41 return "自动重检正在等待当前操作完成"
42 }
43 if !s.ready {
44 return "自动重检正在等待环境就绪"
45 }
46 if now.Before(r.Next) {
47 seconds := (r.Next.Sub(now) + time.Second - 1) / time.Second
48 return fmt.Sprintf("自动重检将在 %d 秒后尝试", seconds)
49 }
50 if r.pressureLogged {
51 return "自动重检正在等待内存压力缓解"
52 }
53 return "自动重检正在等待后台调度"
54}
55
56func (s *Server) scheduleNetworkRecovery(state cage.GateStatus) {
57 s.mu.Lock()
58 defer s.mu.Unlock()
59 if s.networkPaused || s.closing || state.Mode != cage.GateClosed || state.Report == nil {
60 return
61 }
62 s.recovery = networkRecovery{RunID: state.RunID, Configuration: state.Configuration, Epoch: state.Epoch, PauseVersion: s.safety.pauseVersion, Next: time.Now().Add(15 * time.Second)}
63 diagnostics.Log("warn", "network", "temporary monitoring failure; full recheck scheduled: "+state.Reason)
64}
65
66func recoveryMatches(r networkRecovery, state cage.GateStatus, configuration string, paused bool, generation uint64) bool {
67 return r.RunID != "" && !paused && generation == r.PauseVersion && state.RunID == r.RunID && state.Configuration == r.Configuration && configuration == r.Configuration && state.Epoch == r.Epoch && state.Mode == cage.GateClosed
68}
69
70// Called with s.op held. Admission uses the ordinary job queue and never changes
71// saved network intent. The worker rechecks after acquiring s.op as well.
72func (s *Server) recoverNetwork() {
73 s.mu.Lock()
74 r := s.recovery
75 closing, paused, ready, jobRunning := s.closing, s.networkPaused, s.ready, s.jobs.snapshot().Running
76 s.mu.Unlock()
77 if r.RunID == "" {
78 return
79 }
80 timing := s.startMonitorTiming()
81 defer s.recordMonitorTiming("recovery", timing)
82 switch {
83 case closing || paused:
84 timing.result = "cancelled"
85 return
86 case !ready:
87 timing.result = "environment_not_ready"
88 return
89 case jobRunning:
90 timing.result = "job_running"
91 return
92 case time.Now().Before(r.Next):
93 timing.result = "retry_not_due"
94 return
95 }
96 // The resource manager refreshes UpdatedAt even when a sample fails.
97 // Only a recent pressure measurement should postpone the full gate check.
98 resources, err := cage.ReadResourceStatus(s.instanceDir())
99 guestPressure := resources.Pressure && time.Since(resources.ObservedAt) <= 10*time.Second
100 if err == nil && (guestPressure || resources.HostPressure) {
101 timing.result = "memory_pressure"
102 s.mu.Lock()
103 logWait := s.recovery == r && !r.pressureLogged
104 if logWait {
105 s.recovery.pressureLogged = true
106 }
107 s.mu.Unlock()
108 if logWait {
109 diagnostics.Log("info", "network", fmt.Sprintf("automatic recheck waiting for memory pressure to subside (guest=%t, host=%t)", guestPressure, resources.HostPressure))
110 }
111 return
112 }
113 _, _ = s.submitJob("network-recovery", func() error { return s.runNetworkRecovery(r, s.runSafetyCheck) })
114}
115
116func (s *Server) runNetworkRecovery(expected networkRecovery, recheck func() error) error {
117 s.mu.Lock()
118 stopped := s.closing || s.networkPaused || s.safety.pauseVersion != expected.PauseVersion
119 if stopped {
120 s.recovery = networkRecovery{}
121 }
122 s.mu.Unlock()
123 if stopped {
124 return context.Canceled
125 }
126 client, err := s.gateClient()
127 if err != nil {
128 return s.finishNetworkRecovery(expected, err)
129 }
130 ctx, cancel := context.WithTimeout(s.operationContext(), 5*time.Second)
131 state, err := client.Status(ctx)
132 cancel()
133 if err != nil {
134 return s.finishNetworkRecovery(expected, err)
135 }
136 cfg, err := loadConfig(s.configPath)
137 if err != nil {
138 return s.finishNetworkRecovery(expected, err)
139 }
140 s.mu.Lock()
141 valid := !s.closing && s.recovery == expected && recoveryMatches(expected, state, cfg.Fingerprint(), s.networkPaused, s.safety.pauseVersion)
142 if !valid {
143 s.recovery = networkRecovery{}
144 }
145 s.mu.Unlock()
146 if !valid {
147 return context.Canceled
148 }
149 if err := s.operationContext().Err(); err != nil {
150 return err
151 }
152 s.setMessage("正在重新检查环境与出口,通过后自动恢复联网…")
153 err = recheck()
154 return s.finishNetworkRecovery(expected, err)
155}
156
157func (s *Server) finishNetworkRecovery(expected networkRecovery, err error) error {
158 // A failed full check changes the gate epoch. Keep that exact epoch for the
159 // next attempt, while preserving user/configuration changes as cancellation.
160 var current cage.GateStatus
161 if err != nil {
162 if client, e := s.gateClient(); e == nil {
163 ctx, cancel := context.WithTimeout(s.lifetimeContext(), 3*time.Second)
164 current, _ = client.Status(ctx)
165 cancel()
166 }
167 }
168 s.mu.Lock()
169 defer s.mu.Unlock()
170 if s.recovery != expected {
171 return err
172 }
173 if err == nil || s.closing || s.networkPaused || s.safety.pauseVersion != expected.PauseVersion || errors.Is(err, context.Canceled) {
174 s.recovery = networkRecovery{}
175 return err
176 }
177 if current.RunID != "" {
178 if current.RunID != expected.RunID || current.Configuration != expected.Configuration || current.Mode != cage.GateClosed {
179 s.recovery = networkRecovery{}
180 return err
181 }
182 s.recovery.Epoch = current.Epoch
183 }
184 s.recovery.Attempts++
185 delay := time.Duration(min(300, 15<<min(s.recovery.Attempts, 5))) * time.Second
186 s.recovery.Next = time.Now().Add(delay)
187 s.recovery.pressureLogged = false
188 // Show the latest full-check failure rather than the initial monitoring
189 // error, which may describe a different missing sample by this point.
190 s.safety.monitorError = diagnostics.Redact(usererror.Display("自动完整重检", err, "等待下一次重检;仍失败时导出诊断包。").Error())
191 diagnostics.Log("warn", "network", fmt.Sprintf("automatic recheck attempt %d failed; next attempt in %s", s.recovery.Attempts, delay))
192 return err
193}