跳到主要内容

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

浏览文件

terminal_service.go

493 行 · 16.1 KB历史下载
1package workbench
2
3import (
4 "context"
5 "encoding/hex"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "os/exec"
10 "sync"
11 "time"
12
13 "al.essio.dev/pkg/shellescape"
14)
15
16var (
17 errTerminalsClosed = errors.New("后台正在退出,请重新打开 Cage。")
18 errTerminalBusy = errors.New("环境正在执行其他操作")
19 errTerminalNotReady = errors.New("环境尚未就绪或正在重启")
20 errTerminalLimit = errors.New("最多保留 12 个终端,请先关闭不用的会话")
21 errTerminalStart = errors.New("无法创建终端连接")
22)
23
24type terminalRequest struct {
25 Workspace string `json:"workspace"`
26 Kind string `json:"kind"`
27 ClaudeAccountID string `json:"claude_account_id"`
28 sharedID string
29 requestContext context.Context
30}
31
32// terminalManager owns host PTYs; subscriptions only borrow their output. The
33// manager serializes process creation with closure so no process can be
34// published after shutdown has collected the sessions it needs to close.
35type terminalManager struct {
36 mu sync.Mutex
37 sessions map[string]*terminalSession
38 sequence int
39 closed bool
40 workers sync.WaitGroup
41}
42
43func (m *terminalManager) startSession(cmd *exec.Cmd, workspace, kind string, selection claudeSelection, finished func()) (*terminalSession, error) {
44 return m.startSessionWithPTY(cmd, workspace, kind, selection, finished, func() (terminalPTY, error) { return startTerminal(cmd, 100, 30) })
45}
46
47func (m *terminalManager) startSessionWithPTY(cmd *exec.Cmd, workspace, kind string, selection claudeSelection, finished func(), start func() (terminalPTY, error)) (*terminalSession, error) {
48 m.mu.Lock()
49 defer m.mu.Unlock()
50 if err := m.admissionErrorLocked(); err != nil {
51 return nil, err
52 }
53 file, err := start()
54 if err != nil {
55 return nil, errTerminalStart
56 }
57 m.sequence++
58 title := fmt.Sprintf("终端 %d", m.sequence)
59 if kind == "claude" {
60 title = fmt.Sprintf("Claude %d", m.sequence)
61 } else if kind == "claude-login" {
62 title = "Claude 账号登录"
63 }
64 session := newTerminalSession(file)
65 session.id, session.title, session.workspace, session.cmd = randomToken()[:16], title, workspace, cmd
66 session.kind, session.claudeAccountID = kind, selection.ID
67 if kind == "claude-login" {
68 session.loginGuestID = selection.GuestID
69 }
70 if selection.GuestID == "default" {
71 session.claudeAccountSource = "default"
72 } else if selection.ID != "" {
73 session.claudeAccountSource = "managed"
74 }
75 if m.sessions == nil {
76 m.sessions = make(map[string]*terminalSession)
77 }
78 m.sessions[session.id] = session
79 m.workers.Add(1)
80 go func() {
81 defer m.workers.Done()
82 session.run()
83 if finished != nil {
84 finished()
85 }
86 }()
87 return session, nil
88}
89
90func (m *terminalManager) admissionErrorLocked() error {
91 if m.closed {
92 return errTerminalsClosed
93 }
94 if len(m.sessions) >= 12 {
95 return errTerminalLimit
96 }
97 return nil
98}
99
100func (m *terminalManager) canStart() error {
101 m.mu.Lock()
102 defer m.mu.Unlock()
103 return m.admissionErrorLocked()
104}
105
106func (m *terminalManager) snapshot() []map[string]any {
107 m.mu.Lock()
108 defer m.mu.Unlock()
109 out := make([]map[string]any, 0, len(m.sessions))
110 for _, session := range m.sessions {
111 out = append(out, session.summary())
112 }
113 return out
114}
115
116func (m *terminalManager) hasLive() bool {
117 m.mu.Lock()
118 defer m.mu.Unlock()
119 for _, session := range m.sessions {
120 session.mu.Lock()
121 closed := session.closed
122 session.mu.Unlock()
123 if !closed {
124 return true
125 }
126 if session.done != nil {
127 select {
128 case <-session.done:
129 default:
130 return true
131 }
132 }
133 }
134 return false
135}
136
137func (m *terminalManager) get(id string) *terminalSession {
138 m.mu.Lock()
139 defer m.mu.Unlock()
140 return m.sessions[id]
141}
142
143func (m *terminalManager) forConversation(connection string) *terminalSession {
144 m.mu.Lock()
145 defer m.mu.Unlock()
146 for _, session := range m.sessions {
147 session.mu.Lock()
148 matches := session.connectionID == connection && !session.closed
149 session.mu.Unlock()
150 if matches {
151 return session
152 }
153 }
154 return nil
155}
156
157// Reattaching a repeated login request must not create a second OAuth flow.
158// A profile can serve many normal terminals or a single exclusive login.
159func (m *terminalManager) existingClaudeLogin(id string, login bool) (*terminalSession, error) {
160 m.mu.Lock()
161 defer m.mu.Unlock()
162 for _, session := range m.sessions {
163 if session.claudeAccountID != id {
164 continue
165 }
166 select {
167 case <-session.done:
168 continue
169 default:
170 }
171 if session.kind == "claude-login" && login {
172 return session, nil
173 }
174 if login || session.kind == "claude-login" {
175 return nil, errors.New("请先结束此账号的登录或运行中的终端,再更改登录身份")
176 }
177 }
178 return nil, nil
179}
180
181func (m *terminalManager) remove(id string) {
182 m.mu.Lock()
183 session := m.sessions[id]
184 m.mu.Unlock()
185 if session != nil {
186 // Keep its Claude account reserved until the old PTY has exited.
187 session.close()
188 m.mu.Lock()
189 delete(m.sessions, id)
190 m.mu.Unlock()
191 }
192}
193
194// closeAll keeps ended sessions visible until explicitly removed and permits
195// new terminals after the environment starts again. Environment operations
196// serialize this call with createTerminal using Server.op.
197func (m *terminalManager) closeAll() {
198 m.mu.Lock()
199 sessions := make([]*terminalSession, 0, len(m.sessions))
200 for _, session := range m.sessions {
201 sessions = append(sessions, session)
202 }
203 m.mu.Unlock()
204 for _, session := range sessions {
205 session.close()
206 }
207}
208
209func (m *terminalManager) close() {
210 m.mu.Lock()
211 m.closed = true
212 m.mu.Unlock()
213 m.closeAll()
214 // The final login-status observation also belongs to the session worker.
215 m.workers.Wait()
216}
217
218func (s *Server) createTerminal(input terminalRequest) (*terminalSession, error) {
219 if !s.op.TryLock() {
220 return nil, errTerminalBusy
221 }
222 defer s.op.Unlock()
223 return s.createTerminalLocked(input)
224}
225
226// Caller holds the environment operation lock through PTY publication.
227func (s *Server) createTerminalLocked(input terminalRequest) (*terminalSession, error) {
228 if s.windowsGuest != nil {
229 return s.createWindowsTerminal(input)
230 }
231 var sharedRecord *mobileRecord
232 if input.sharedID != "" {
233 s.mobileCLI.mu.Lock()
234 record, err := s.mobileCLI.record(s.profile, input.sharedID)
235 s.mobileCLI.mu.Unlock()
236 if err != nil {
237 return nil, err
238 }
239 sharedRecord = record
240 if record.Switch != nil && record.Switch.Phase == "preparing" {
241 return nil, errors.New("账号交接尚未完成,请先重试或取消交接")
242 }
243 if record.Archived || record.Deleted {
244 return nil, errors.New("此会话已归档或删除,请先从已归档会话恢复")
245 }
246 // The guest can be unreadable or not yet started while its host PTY
247 // already owns this conversation. A stale snapshot cannot start a copy.
248 if existing := s.terminals.get(record.TerminalID); existing != nil && existing.ownsConversation() {
249 return existing, nil
250 }
251 if existing := s.terminals.get(record.TerminalID); existing != nil && existing.summary()["closed"] == true {
252 s.terminals.remove(record.TerminalID)
253 }
254 }
255 s.mu.Lock()
256 closing := s.closing
257 componentUpdate := s.guestUpdateRequired
258 command := claudeTerminalCommand(s.preferences)
259 s.mu.Unlock()
260 if closing {
261 return nil, errTerminalsClosed
262 }
263 if sharedRecord != nil && (!sharedCLILauncher(command) || sharedRecord.Launcher != "" && sharedRecord.Launcher != command) {
264 return nil, errors.New("主机启动命令与原会话不一致,请恢复原配置后重试")
265 }
266 if s.macosGuest != nil {
267 if input.Kind == "claude" && !sharedCLILauncher(command) {
268 return nil, errors.New("macOS 客机支持 claude 或 ccs 配置名启动命令")
269 }
270 s.mu.Lock()
271 ready := s.ready
272 s.mu.Unlock()
273 if !ready {
274 return nil, errTerminalNotReady
275 }
276 }
277 if !s.vmRunning() || s.busy() {
278 return nil, errTerminalNotReady
279 }
280 // Reject a full manager before opening project shares. start checks again
281 // atomically with process publication because shutdown can race this work.
282 if input.Kind != "claude-login" {
283 if err := s.terminals.canStart(); err != nil {
284 return nil, err
285 }
286 }
287 if input.Kind != "" && input.Kind != "shell" && input.Kind != "claude" && input.Kind != "claude-login" {
288 return nil, errors.New("终端类型无效")
289 }
290 managed := input.Kind == "claude" || input.Kind == "claude-login"
291 if !managed && input.ClaudeAccountID != "" {
292 return nil, errors.New("普通终端不能指定 Claude 账号")
293 }
294 // Login works even when the last project is disconnected or has moved.
295 // It always runs from the guest home, without loading project settings.
296 workspace := s.workspace()
297 var err error
298 if input.Kind != "claude-login" {
299 if s.macOSLegacyWorkspace(sharedRecord) != "" {
300 workspace, err = s.projectWorkspace(sharedRecord.Workspace)
301 } else {
302 workspace, err = s.connectProject(input.Workspace, false)
303 }
304 if err != nil {
305 return nil, err
306 }
307 }
308 script := terminalScript(s.cliWorkspace(workspace), input.Kind, command)
309 if s.macosGuest != nil {
310 script = `cd -- "$HOME" && exec env TERM=xterm-256color COLORTERM=truecolor /bin/zsh -l`
311 if input.Kind != "claude-login" {
312 script = "exec /usr/local/libexec/cage-macos-terminal " + shellescape.Quote(macOSProjectPath(s.macosGuest.User, workspace))
313 }
314 }
315 var selection claudeSelection
316 var finished func()
317 if managed {
318 login := input.Kind == "claude-login"
319 if sharedRecord != nil && sharedRecord.Terminal {
320 selection = sharedRecord.Account
321 } else {
322 selection, err = s.selectTerminalClaudeAccount(command, input.ClaudeAccountID, login, workspace)
323 }
324 if err != nil {
325 return nil, err
326 }
327 if selection.ID != "" {
328 if componentUpdate {
329 return nil, errGuestUpdateRequired
330 }
331 if !validClaudeID(selection.ID) || !validClaudeGuestID(selection.GuestID) || (login && selection.GuestID == "default") {
332 return nil, errors.New("Claude 账号 ID 无效")
333 }
334 if login && s.mobileCLI.activeAccounts()[selection.ID] > 0 {
335 return nil, errors.New("请先结束该账号正在执行的移动 CLI 轮次,再重新登录")
336 }
337 if existing, conflict := s.terminals.existingClaudeLogin(selection.ID, login); existing != nil || conflict != nil {
338 return existing, conflict
339 }
340 if !login && selection.Subject == "" {
341 return nil, errors.New("Claude 账号状态已变化,请重试")
342 }
343 script = managedClaudeTerminalScript(s.cliWorkspace(workspace), command, selection.GuestID, selection.Subject, login)
344 if login {
345 if s.macosGuest != nil {
346 ctx, cancel := context.WithTimeout(s.lifetimeContext(), 20*time.Second)
347 _, browserErr := s.guestAPI(ctx, "", "GET", "/health", nil)
348 cancel()
349 if browserErr != nil {
350 return nil, errors.New("客机登录浏览器尚未就绪,请恢复浏览器连接后重试")
351 }
352 }
353 finished = func() {
354 ctx, cancel := context.WithTimeout(s.lifetimeContext(), 12*time.Second)
355 defer cancel()
356 _ = s.confirmClaudeLogin(ctx, selection.ID)
357 }
358 }
359 }
360 }
361 var conversation *mobileRecord
362 if input.Kind == "claude" && sharedCLILauncher(command) {
363 script, conversation, err = s.prepareTerminalConversation(workspace, selection, input.sharedID)
364 if err != nil {
365 return nil, err
366 }
367 }
368 cmd := s.sshCommand(s.lifetimeContext(), "-tt", s.sshTarget(), "--", script)
369 if input.requestContext != nil {
370 s.account.mu.Lock()
371 if !s.mobileAuthorized(input.requestContext) {
372 s.account.mu.Unlock()
373 return nil, errMobileLocked
374 }
375 }
376 session, err := s.terminals.startSession(cmd, workspace, input.Kind, selection, finished)
377 if input.requestContext != nil {
378 s.account.mu.Unlock()
379 }
380 if err == nil && conversation != nil {
381 session.mu.Lock()
382 session.sharedID = conversation.ID
383 session.connectionID = conversation.Connection
384 session.mu.Unlock()
385 s.mobileCLI.mu.Lock()
386 conversation.TerminalID = session.id
387 if saveErr := writePrivate(mobileRecordPath(s.profile, conversation.ID), conversation); saveErr != nil {
388 err = saveErr
389 }
390 s.mobileCLI.mu.Unlock()
391 if err != nil {
392 s.terminals.remove(session.id)
393 return nil, err
394 }
395 s.prepareCLIConnection(session, conversation.ID)
396 s.monitorClaudeAccount(session, conversation.ID)
397 }
398 if err == nil && input.Kind == "claude" && selection.ID != "" {
399 s.noteClaudeSelection(selection.ID, workspace)
400 }
401 return session, err
402}
403
404func validClaudeGuestID(id string) bool { return id == "default" || validClaudeID(id) }
405
406func (s *Server) selectTerminalClaudeAccount(command, requested string, login bool, workspace string) (claudeSelection, error) {
407 parts, valid := mobileLaunchArgs(command, claudeSelection{})
408 if !login && valid == nil && len(parts) == 2 && parts[0] == "ccs" {
409 if requested != "" && requested != "auto" {
410 return claudeSelection{}, errors.New("CCS 使用自己的配置,不能指定 Cage 账号")
411 }
412 return claudeSelection{}, nil
413 }
414 return s.selectClaudeAccount(requested, login, workspace)
415}
416
417func (s *Server) readClaudeGuestSnapshot(ctx context.Context, id string) (claudeGuestSnapshot, error) {
418 if s.windowsGuest != nil {
419 return s.readWindowsClaudeAccount(ctx, "snapshot", id, "")
420 }
421 return s.readClaudeGuestReport(ctx, id, claudeSnapshotCommand(id))
422}
423
424func (s *Server) readClaudeGuestUsage(ctx context.Context, id, subject string) (claudeGuestSnapshot, error) {
425 if _, err := hex.DecodeString(subject); err != nil || len(subject) != 64 {
426 return claudeGuestSnapshot{}, errors.New("Claude 账号身份无效")
427 }
428 if s.windowsGuest != nil {
429 return s.readWindowsClaudeAccount(ctx, "usage", id, subject)
430 }
431 return s.readClaudeGuestReport(ctx, id, claudeGuestReportCommand(id, subject))
432}
433
434func (s *Server) readClaudeGuestReport(ctx context.Context, id, command string) (claudeGuestSnapshot, error) {
435 var snapshot claudeGuestSnapshot
436 if !validClaudeGuestID(id) {
437 return snapshot, errors.New("Claude 账号 ID 无效")
438 }
439 data, err := s.guest(ctx, command)
440 if err != nil || json.Unmarshal(data, &snapshot) != nil {
441 return snapshot, errors.New("无法读取账号状态,请确认环境已启动并同步环境组件")
442 }
443 return snapshot, nil
444}
445
446func claudeSnapshotCommand(id string) string {
447 return claudeGuestReportCommand(id, "")
448}
449
450func claudeGuestReportCommand(id, subject string) string {
451 command := "exec /usr/local/bin/cage-claude-account snapshot " + id
452 if subject != "" {
453 command = "exec /usr/local/bin/cage-claude-account usage " + id + " " + shellescape.Quote(subject)
454 }
455 if id == "default" {
456 // Use the same login shell a regular terminal opens, including its
457 // configured API/provider environment. Isolate startup banners from
458 // the JSON output and keep the probe outside every shared project.
459 command = `set -o pipefail; cd "$HOME" && env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 /bin/bash -lic ` +
460 shellescape.Quote(`printf '\nCAGE_CLAUDE_SNAPSHOT '; `+command) +
461 ` | sed -n 's/^CAGE_CLAUDE_SNAPSHOT //p'`
462 }
463 return command
464}
465
466func managedClaudeTerminalScript(workspace, command, accountID, subject string, login bool) string {
467 if login {
468 return "cd \"$HOME\" && exec /usr/local/bin/cage-claude-account login " + shellescape.Quote(accountID)
469 }
470 // The interactive shell still interprets the user's saved command and
471 // remains useful when Claude exits. The shim scopes subsequent invocations
472 // in this shell to the same official CLI profile.
473 env := `export CAGE_CLAUDE_ACCOUNT_ID=` + shellescape.Quote(accountID) +
474 ` CAGE_CLAUDE_SUBJECT=` + shellescape.Quote(subject) + "; "
475 if accountID != "default" {
476 env += `export CLAUDE_CONFIG_DIR="$HOME/.local/share/cage/claude-accounts/$CAGE_CLAUDE_ACCOUNT_ID/config"; `
477 }
478 env += `export PATH="/usr/local/lib/cage-claude-bin:$PATH"; `
479 body := env + `eval "$CAGE_TERMINAL_COMMAND"; unset CAGE_TERMINAL_COMMAND; exec bash -i`
480 return "cd " + shellescape.Quote(workspace) +
481 " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 CAGE_TERMINAL_COMMAND=" +
482 shellescape.Quote(command) + " bash -lic " + shellescape.Quote(body)
483}
484
485// The saved command is interpreted only by the guest's interactive shell.
486// Reconnecting a viewer never executes it again; exiting Claude leaves a shell.
487func terminalScript(workspace, kind, command string) string {
488 prefix := "cd " + shellescape.Quote(workspace) + " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 "
489 if kind != "claude" {
490 return prefix + "bash -l"
491 }
492 return prefix + "CAGE_TERMINAL_COMMAND=" + shellescape.Quote(command) + " bash -lic " + shellescape.Quote("eval \"$CAGE_TERMINAL_COMMAND\"; unset CAGE_TERMINAL_COMMAND; exec bash -il")
493}