跳到主要内容

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

浏览文件

job_stop.go

86 行 · 2.1 KB历史下载
1package cage
2
3import (
4 "encoding/json"
5 "errors"
6 "os"
7 "path/filepath"
8 "regexp"
9 "sync"
10 "time"
11)
12
13const JobEnv = "CLAUDE_CAGE_JOB_ID"
14
15var jobIDPattern = regexp.MustCompile(`^[a-f0-9]{12,64}$`)
16
17// RequestJobStop covers detached hostagents which may initialize after their
18// launching command was cancelled. The private marker belongs to one job;
19// it cannot cancel a subsequent start with a fresh ID.
20func RequestJobStop(profile, id string) error {
21 if !jobIDPattern.MatchString(id) {
22 return errors.New("invalid Cage job identifier")
23 }
24 dir := filepath.Join(profile, "stopped-jobs")
25 if err := os.MkdirAll(dir, 0700); err != nil {
26 return err
27 }
28 f, err := os.OpenFile(filepath.Join(dir, id), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
29 if os.IsExist(err) {
30 return nil
31 }
32 if err != nil {
33 return err
34 }
35 return f.Close()
36}
37
38func InstanceJobID(state, name string) string {
39 if filepath.Base(name) != name {
40 return ""
41 }
42 data, err := os.ReadFile(filepath.Join(state, "lima", name, "cage-running.json"))
43 if err != nil || len(data) > 4096 {
44 return ""
45 }
46 var record runningProfile
47 if json.Unmarshal(data, &record) != nil || !jobIDPattern.MatchString(record.JobID) {
48 return ""
49 }
50 return record.JobID
51}
52
53// WatchJobStop is installed before starting the VM driver. onStop signals
54// this hostagent itself; it never guesses or signals another process's PID.
55func WatchJobStop(profile, id string, onStop func()) (func(), error) {
56 if id == "" {
57 return func() {}, nil
58 }
59 if !jobIDPattern.MatchString(id) {
60 return nil, errors.New("invalid Cage job identifier")
61 }
62 path := filepath.Join(profile, "stopped-jobs", id)
63 stopped := func() bool { _, err := os.Lstat(path); return err == nil || !os.IsNotExist(err) }
64 if stopped() {
65 return nil, errors.New("Cage startup was cancelled")
66 }
67 done := make(chan struct{})
68 var once sync.Once
69 stop := func() { once.Do(func() { close(done) }) }
70 go func() {
71 ticker := time.NewTicker(100 * time.Millisecond)
72 defer ticker.Stop()
73 for {
74 select {
75 case <-done:
76 return
77 case <-ticker.C:
78 if stopped() {
79 onStop()
80 return
81 }
82 }
83 }
84 }()
85 return stop, nil
86}