跳到主要内容

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

提交记录

fix: PID 被复用时不再把过期运行记录当成仍在运行

重启或异常退出后,cage-running.json 和 managed-process.json 里的 PID 可能被无关进程(例如 svchost)复用。原先只检查 PID 是否存在: 工作台误判 VM 仍在运行,界面停在“无法连接 VM 外网络门槛控制器”; Windows 代理核心记录的身份不符时直接报错,阻止重新启动代理。 - cage-running.json 增加 started 字段,记录宿主进程的启动时间 (Windows 创建时间、Linux boot_id + starttime、macOS p_starttime)。 vmAlive、controllerVMOwners、CheckRunning 和存储迁移检查在启动时间 明确不符时视为未运行;旧记录和无法读取启动时间时保持原有行为。 - Windows 代理核心记录身份不符,或进程无法终止且不是本用户的核心时, 删除过期记录与控制 socket,不终止其他进程。 - 新增 cage、workbench、managedproxy 单元测试。 Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

作者
aplainjane
时间
2026/11/07 21:05
提交
16cc0f5
上一个
bd53b2f
这个版本的全部文件
新增internal/cage/process_start_darwin.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package cage
2新增:
3新增:import (
4新增: "fmt"
5新增:
6新增: "golang.org/x/sys/unix"
7新增:)
8新增:
9新增:func processStartToken(pid int) string {
10新增: if pid <= 0 {
11新增: return ""
12新增: }
13新增: p, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
14新增: if err != nil || p.Proc.P_pid != int32(pid) {
15新增: return ""
16新增: }
17新增: t := p.Proc.P_starttime
18新增: if t.Sec == 0 && t.Usec == 0 {
19新增: return ""
20新增: }
21新增: return fmt.Sprintf("%d.%06d", t.Sec, t.Usec)
22新增:}
新增internal/cage/process_start_linux.go+35 −0看文件
@@ -0,0 +1,35 @@
1新增:package cage
2新增:
3新增:import (
4新增: "bytes"
5新增: "os"
6新增: "strconv"
7新增: "strings"
8新增:)
9新增:
10新增:// Linux start times are clock ticks since boot, so the boot ID keeps a PID
11新增:// reused after a reboot from matching a record from the previous boot.
12新增:func processStartToken(pid int) string {
13新增: if pid <= 0 {
14新增: return ""
15新增: }
16新增: boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
17新增: if err != nil {
18新增: return ""
19新增: }
20新增: stat, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
21新增: if err != nil {
22新增: return ""
23新增: }
24新增: // The command name may contain spaces or parentheses; fields resume after
25新增: // the last ')'. starttime is field 22, the 20th after the name.
26新增: i := bytes.LastIndexByte(stat, ')')
27新增: if i < 0 {
28新增: return ""
29新增: }
30新增: fields := strings.Fields(string(stat[i+1:]))
31新增: if len(fields) < 20 {
32新增: return ""
33新增: }
34新增: return strings.TrimSpace(string(boot)) + ":" + fields[19]
35新增:}
新增internal/cage/process_start_other.go+5 −0看文件
@@ -0,0 +1,5 @@
1新增://go:build !windows && !linux && !darwin
2新增:
3新增:package cage
4新增:
5新增:func processStartToken(int) string { return "" }
修改internal/cage/process_windows.go+21 −1看文件
@@ -1,6 +1,10 @@
11package cage
22
3删除:import "golang.org/x/sys/windows"
3新增:import (
4新增: "strconv"
5新增:
6新增: "golang.org/x/sys/windows"
7新增:)
48
59func profileProcessAlive(pid int) bool {
610 h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
@@ -11,3 +15,19 @@ func profileProcessAlive(pid int) bool {
1115 var code uint32
1216 return windows.GetExitCodeProcess(h, &code) == nil && code == 259
1317}
18新增:
19新增:func processStartToken(pid int) string {
20新增: if pid <= 0 {
21新增: return ""
22新增: }
23新增: h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
24新增: if err != nil {
25新增: return ""
26新增: }
27新增: defer windows.CloseHandle(h)
28新增: var created, exited, kernel, user windows.Filetime
29新增: if windows.GetProcessTimes(h, &created, &exited, &kernel, &user) != nil {
30新增: return ""
31新增: }
32新增: return strconv.FormatInt(created.Nanoseconds(), 10)
33新增:}
修改internal/cage/profile.go+21 −6看文件
@@ -12,10 +12,28 @@ import (
1212
1313type runningProfile struct {
1414 PID int `json:"pid"`
15新增: Started string `json:"started,omitempty"`
1516 Fingerprint string `json:"fingerprint"`
1617 JobID string `json:"job_id,omitempty"`
1718}
1819
20新增:// ProcessStartMatches reports false only when pid now belongs to a process
21新增:// started at a different time than the record. After a reboot or crash the
22新增:// recorded PID can be reused by an unrelated process. Records from older
23新增:// versions carry no start time and an unreadable start time cannot prove
24新增:// reuse; both keep the previous PID-only behavior.
25新增:func ProcessStartMatches(pid int, started string) bool {
26新增: if started == "" {
27新增: return true
28新增: }
29新增: current := processStartToken(pid)
30新增: return current == "" || current == started
31新增:}
32新增:
33新增:func (r runningProfile) alive() bool {
34新增: return r.PID > 0 && profileProcessAlive(r.PID) && ProcessStartMatches(r.PID, r.Started)
35新增:}
36新增:
1937func (c Config) Fingerprint() string {
2038 c.ExitPolicy = c.ExitPolicy.Normalized()
2139 b, _ := json.Marshal(c)
@@ -34,7 +52,8 @@ func (c Config) RecordRunning(state, name string) error {
3452// RecordRunningAt records the network owner's identity in the runtime's real
3553// instance directory; container environments do not create Lima metadata.
3654func (c Config) RecordRunningAt(dir string) error {
37删除: b, _ := json.Marshal(runningProfile{PID: os.Getpid(), Fingerprint: c.Fingerprint(), JobID: os.Getenv(JobEnv)})
55新增: pid := os.Getpid()
56新增: b, _ := json.Marshal(runningProfile{PID: pid, Started: processStartToken(pid), Fingerprint: c.Fingerprint(), JobID: os.Getenv(JobEnv)})
3857 f, err := os.CreateTemp(dir, ".running-*")
3958 if err != nil {
4059 return err
@@ -71,11 +90,7 @@ func (c Config) CheckRunning(state string) error {
7190 if json.Unmarshal(b, &r) != nil {
7291 return errors.New("invalid running cage profile record")
7392 }
74删除: if r.PID < 1 {
75删除: continue
76删除: }
77删除: alive := profileProcessAlive(r.PID)
78删除: if alive && r.Fingerprint != c.Fingerprint() {
93新增: if r.alive() && r.Fingerprint != c.Fingerprint() {
7994 return fmt.Errorf("cage configuration changed while a VM is running; run cage stop before restarting")
8095 }
8196 }
修改internal/cage/profile_test.go+41 −0看文件
@@ -1,6 +1,7 @@
11package cage
22
33import (
4新增: "encoding/json"
45 "os"
56 "path/filepath"
67 "testing"
@@ -21,3 +22,43 @@ func TestConfigChangeRequiresStop(t *testing.T) {
2122 t.Fatal("running profile silently changed")
2223 }
2324}
25新增:
26新增:func TestRunningRecordRejectsReusedPID(t *testing.T) {
27新增: dir := t.TempDir()
28新增: instance := filepath.Join(dir, "lima", "test")
29新增: os.MkdirAll(instance, 0700)
30新增: c := DefaultConfig()
31新增: if err := c.RecordRunning(dir, "test"); err != nil {
32新增: t.Fatal(err)
33新增: }
34新增: b, err := os.ReadFile(filepath.Join(instance, "cage-running.json"))
35新增: if err != nil {
36新增: t.Fatal(err)
37新增: }
38新增: var record runningProfile
39新增: if err := json.Unmarshal(b, &record); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: if record.Started == "" {
43新增: t.Skip("process start time is unavailable on this platform")
44新增: }
45新增: if !record.alive() {
46新增: t.Fatal("current owner was not recognized")
47新增: }
48新增: legacy := runningProfile{PID: record.PID}
49新增: if !legacy.alive() {
50新增: t.Fatal("legacy PID-only record was rejected")
51新增: }
52新增: reused := runningProfile{PID: record.PID, Started: record.Started + "0", Fingerprint: record.Fingerprint}
53新增: if reused.alive() {
54新增: t.Fatal("record from an earlier process with the same PID was treated as running")
55新增: }
56新增: b, _ = json.Marshal(reused)
57新增: if err := os.WriteFile(filepath.Join(instance, "cage-running.json"), b, 0600); err != nil {
58新增: t.Fatal(err)
59新增: }
60新增: c.Timezone = "Asia/Tokyo"
61新增: if err := c.CheckRunning(dir); err != nil {
62新增: t.Fatalf("stale record blocked a configuration change: %v", err)
63新增: }
64新增:}
修改internal/cage/storage.go+3 −2看文件
@@ -398,17 +398,18 @@ func stoppedStorage(source string) error {
398398 return err
399399 }
400400 var pid int
401新增: started := ""
401402 if name == "cage-running.json" {
402403 var record runningProfile
403404 err = json.Unmarshal(data, &record)
404删除: pid = record.PID
405新增: pid, started = record.PID, record.Started
405406 } else {
406407 pid, err = strconv.Atoi(strings.TrimSpace(string(data)))
407408 }
408409 if err != nil || pid < 1 {
409410 return fmt.Errorf("无法核验虚拟机进程记录 %s", name)
410411 }
411删除: if profileProcessAlive(pid) {
412新增: if profileProcessAlive(pid) && ProcessStartMatches(pid, started) {
412413 return fmt.Errorf("请先停止虚拟机 %s,再迁移环境", inst.Name())
413414 }
414415 }
修改internal/managedproxy/platform_windows.go+31 −2看文件
@@ -80,6 +80,11 @@ func stopWindowsCore(profile string) error {
8080 if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {
8181 return os.Remove(path)
8282 }
83新增: if errors.Is(err, windows.ERROR_ACCESS_DENIED) && !recordedCoreRunning(record) {
84新增: // The core runs as the current user, so a PID that cannot be
85新增: // terminated now belongs to another account's process.
86新增: return removeStaleCore(profile, path)
87新增: }
8388 if err != nil {
8489 return err
8590 }
@@ -88,8 +93,10 @@ func stopWindowsCore(profile string) error {
8893 if err != nil {
8994 return err
9095 }
91删除: if !strings.EqualFold(filepath.Clean(image), filepath.Clean(record.Executable)) || created != record.Created {
92删除: return errors.New("代理进程身份已变化,未停止其他进程")
96新增: if !sameCore(record, image, created) {
97新增: // The recorded core exited and its PID was reused, typically after a
98新增: // reboot. Forget the stale record and leave the other process alone.
99新增: return removeStaleCore(profile, path)
93100 }
94101 var code uint32
95102 if err := windows.GetExitCodeProcess(handle, &code); err != nil {
@@ -111,6 +118,28 @@ func stopWindowsCore(profile string) error {
111118 return os.Remove(path)
112119}
113120
121新增:func sameCore(record windowsCoreRecord, image string, created int64) bool {
122新增: return strings.EqualFold(filepath.Clean(image), filepath.Clean(record.Executable)) && created == record.Created
123新增:}
124新增:
125新增:func recordedCoreRunning(record windowsCoreRecord) bool {
126新增: handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, record.PID)
127新增: if err != nil {
128新增: return false
129新增: }
130新增: defer windows.CloseHandle(handle)
131新增: image, created, err := identifyCore(handle)
132新增: return err == nil && sameCore(record, image, created)
133新增:}
134新增:
135新增:func removeStaleCore(profile, path string) error {
136新增: _ = os.Remove(Socket(profile))
137新增: if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
138新增: return err
139新增: }
140新增: return nil
141新增:}
142新增:
114143func startWindowsCore(ctx context.Context, profile string, s Store) error {
115144 name, err := PhysicalInterface(ctx)
116145 if err != nil {
新增internal/managedproxy/platform_windows_test.go+36 −0看文件
@@ -0,0 +1,36 @@
1新增:package managedproxy
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "os"
6新增: "path/filepath"
7新增: "testing"
8新增:)
9新增:
10新增:// A PID reused after a reboot must neither be terminated nor block startup.
11新增:func TestStopWindowsCoreForgetsReusedPID(t *testing.T) {
12新增: exe, err := os.Executable()
13新增: if err != nil {
14新增: t.Fatal(err)
15新增: }
16新增: core := filepath.Join(filepath.Dir(exe), "mihomo.exe")
17新增: if err := os.WriteFile(core, []byte("placeholder"), 0700); err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: t.Cleanup(func() { _ = os.Remove(core) })
21新增: for name, pid := range map[string]uint32{"same user": uint32(os.Getpid()), "system": 4} {
22新增: t.Run(name, func(t *testing.T) {
23新增: profile := t.TempDir()
24新增: b, _ := json.Marshal(windowsCoreRecord{PID: pid, Executable: core, Created: 1})
25新增: if err := Write(windowsCoreRecordPath(profile), b); err != nil {
26新增: t.Fatal(err)
27新增: }
28新增: if err := stopWindowsCore(profile); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: if _, err := os.Lstat(windowsCoreRecordPath(profile)); !os.IsNotExist(err) {
32新增: t.Fatal("stale core record was kept")
33新增: }
34新增: })
35新增: }
36新增:}
修改internal/workbench/control_lifecycle.go+4 −2看文件
@@ -10,6 +10,7 @@ import (
1010 "path/filepath"
1111 "time"
1212
13新增: "github.com/sylvinus/agent-vm/internal/cage"
1314 "github.com/sylvinus/agent-vm/internal/containerenv"
1415 "github.com/sylvinus/agent-vm/internal/managedproxy"
1516 "github.com/sylvinus/agent-vm/internal/version"
@@ -139,12 +140,13 @@ func controllerVMOwners(profile string) ([]string, error) {
139140 return nil, err
140141 }
141142 var record struct {
142删除: PID int `json:"pid"`
143新增: PID int `json:"pid"`
144新增: Started string `json:"started"`
143145 }
144146 if json.Unmarshal(b, &record) != nil || record.PID <= 0 {
145147 return nil, errors.New("环境进程记录无效")
146148 }
147删除: if processExists(record.PID) {
149新增: if processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started) {
148150 owners = append(owners, fmt.Sprintf("%s/%d", filepath.Base(filepath.Dir(path)), record.PID))
149151 }
150152 }
新增internal/workbench/running_record_test.go+53 −0看文件
@@ -0,0 +1,53 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "os"
6新增: "path/filepath"
7新增: "testing"
8新增:
9新增: "github.com/sylvinus/agent-vm/internal/cage"
10新增:)
11新增:
12新增:func TestVMRecordWithReusedPIDIsNotRunning(t *testing.T) {
13新增: s := testServer(t)
14新增: s.preferences.Workspace, _ = filepath.EvalSymlinks(t.TempDir())
15新增: name := cage.InstanceName(s.profile, s.environmentDir())
16新增: dir := filepath.Join(s.profile, "state", "lima", name)
17新增: if err := os.MkdirAll(dir, 0700); err != nil {
18新增: t.Fatal(err)
19新增: }
20新增: cfg, err := loadConfig(s.configPath)
21新增: if err != nil {
22新增: t.Fatal(err)
23新增: }
24新增: if err := cfg.RecordRunningAt(dir); err != nil {
25新增: t.Fatal(err)
26新增: }
27新增: path := filepath.Join(dir, "cage-running.json")
28新增: var record map[string]any
29新增: b, _ := os.ReadFile(path)
30新增: if err := json.Unmarshal(b, &record); err != nil {
31新增: t.Fatal(err)
32新增: }
33新增: started, _ := record["started"].(string)
34新增: if started == "" {
35新增: t.Skip("process start time is unavailable on this platform")
36新增: }
37新增: if !s.vmRunning() {
38新增: t.Fatal("current owner was not recognized")
39新增: }
40新增: if owners, err := controllerVMOwners(s.profile); err != nil || len(owners) != 1 {
41新增: t.Fatalf("owners = %v, %v", owners, err)
42新增: }
43新增: record["started"] = started + "0"
44新增: if err := writePrivate(path, record); err != nil {
45新增: t.Fatal(err)
46新增: }
47新增: if s.vmRunning() {
48新增: t.Fatal("record from an earlier process with the same PID was treated as running")
49新增: }
50新增: if owners, err := controllerVMOwners(s.profile); err != nil || len(owners) != 0 {
51新增: t.Fatalf("stale owners = %v, %v", owners, err)
52新增: }
53新增:}
修改internal/workbench/runtime.go+3 −2看文件
@@ -553,11 +553,12 @@ func vmAlive(profile, workspace string) bool {
553553 return false
554554 }
555555 var record struct {
556删除: PID int `json:"pid"`
556新增: PID int `json:"pid"`
557新增: Started string `json:"started"`
557558 }
558559 if json.Unmarshal(b, &record) != nil || record.PID < 1 {
559560 return false
560561 }
561删除: return processExists(record.PID)
562新增: return processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started)
562563}
563564func (s *Server) vmRunning() bool { return vmAlive(s.profile, s.environmentDir()) }