跳到主要内容

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

浏览文件

cli_channel.go

584 行 · 19.8 KB历史下载
1package workbench
2
3import (
4 "bytes"
5 "compress/gzip"
6 "context"
7 "crypto/sha256"
8 _ "embed"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "os"
13 "strings"
14 "time"
15
16 "al.essio.dev/pkg/shellescape"
17 "github.com/google/uuid"
18 "github.com/sylvinus/agent-vm/internal/diagnostics"
19)
20
21//go:embed cli_channel.py
22var cliChannelHelper string
23
24//go:embed cli_channel.resume.md
25var cliResumePrompt string
26
27//go:embed claude_account_resume.md
28var claudeAccountResumePrompt string
29
30var cliChannelEncoded = func() string {
31 var helper strings.Builder
32 for _, line := range strings.Split(cliChannelHelper, "\n") {
33 if strings.TrimSpace(line) != "" && !strings.HasPrefix(strings.TrimSpace(line), "#") {
34 helper.WriteString(line + "\n")
35 }
36 }
37 bundle := []byte(strings.Join([]string{helper.String(), cliResumePrompt, claudeAccountResumePrompt}, "\x00"))
38 var compressed bytes.Buffer
39 writer, _ := gzip.NewWriterLevel(&compressed, gzip.BestCompression)
40 _, _ = writer.Write(bundle)
41 _ = writer.Close()
42 return cliTransport85(compressed.Bytes())
43}()
44
45// Python's RFC 1924 base85 alphabet has no single quote. It fits the compressed
46// helper within Windows' command limit without expanding shell quoting.
47func cliTransport85(data []byte) string {
48 const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"
49 var out strings.Builder
50 for len(data) > 0 {
51 n := min(4, len(data))
52 var value uint64
53 for i := 0; i < 4; i++ {
54 value <<= 8
55 if i < n {
56 value |= uint64(data[i])
57 }
58 }
59 var block [5]byte
60 for i := 4; i >= 0; i-- {
61 block[i] = alphabet[value%85]
62 value /= 85
63 }
64 out.Write(block[:n+1])
65 data = data[n:]
66 }
67 return out.String()
68}
69
70type terminalConversation struct {
71 NativeCCSUnverified bool `json:"native_ccs_unverified"`
72 AccountFailure string `json:"account_failure"`
73 ResumePending bool `json:"resume_pending"`
74 NativeHistory bool `json:"native_history"`
75 CLIID string `json:"cli_id"`
76 Config string `json:"config"`
77 Connection string `json:"connection"`
78 Workspace string `json:"workspace"`
79 Title string `json:"title"`
80 UpdatedAt float64 `json:"updated_at"`
81 Turns []mobileTurn `json:"turns"`
82 CanSend bool `json:"can_send"`
83 ChannelReady bool `json:"channel_ready"`
84 HasHistory bool `json:"has_history"`
85 Running bool `json:"running"`
86 Active bool `json:"active"`
87 ConnectionNotice string `json:"connection_notice"`
88 HistoryTruncated bool `json:"history_truncated"`
89}
90
91func cliChannelCommand(mode, argument string) string {
92 // Versioned helpers let an open terminal keep its original protocol while a
93 // rebuilt host begins new sessions. No account configuration is overwritten.
94 bootstrap := fmt.Sprintf(`import base64, gzip, os, pathlib, sys, tempfile
95folder = pathlib.Path.home() / ".local/share/cage/cli-channel-code"
96folder.mkdir(parents=True, exist_ok=True, mode=0o700)
97name = "%x"
98files = gzip.decompress(base64.b85decode("%s")).decode("utf-8").split("\0")
99for suffix, content in zip((".py", ".resume.md", ".account-resume.md"), files):
100 path = folder / (name + suffix)
101 if not path.exists():
102 with tempfile.NamedTemporaryFile(dir=folder, delete=False) as stream:
103 stream.write(content.encode("utf-8"))
104 temporary = stream.name
105 os.replace(temporary, path)
106path = folder / (name + ".py")
107os.execv(sys.executable, [sys.executable, "-I", str(path), *sys.argv[1:]])
108`, sha256.Sum256([]byte(cliChannelHelper+cliResumePrompt+claudeAccountResumePrompt)), cliChannelEncoded)
109 return shellescape.QuoteCommand([]string{"python3", "-I", "-c", bootstrap, mode, argument})
110}
111
112func (s *Server) runCLIChannel(ctx context.Context, mode string, input any, output any) error {
113 started := time.Now()
114 epoch, ok := s.account.access()
115 if !ok {
116 return errMobileLocked
117 }
118 ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
119 stop := context.AfterFunc(epoch, cancel)
120 defer func() { stop(); cancel() }()
121 if s.windowsGuest != nil {
122 return s.windowsCLIRequest(ctx, map[string]any{"action": "channel", "mode": mode, "input": input}, output)
123 }
124 data, err := json.Marshal(input)
125 if err != nil {
126 return err
127 }
128 command := "exec /bin/bash -c " + shellescape.Quote("exec 3>&1 1>&2; exec /bin/bash -lc "+shellescape.Quote("exec 1>&3 3>&-; exec "+s.cliHelperCommand(mode, "-")))
129 cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
130 cmd.Stdin = strings.NewReader(string(data))
131 var stderr fileControlStderr
132 cmd.Stderr = &stderr
133 cmd.WaitDelay = 2 * time.Second
134 result, err := cmd.Output()
135 if err != nil || len(result) > 4<<20 || json.Unmarshal(result, output) != nil {
136 failure := "guest_response"
137 message := "电脑未能读取会话状态,聊天记录已保留。"
138 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
139 failure, message = "timeout", "电脑读取运行环境超时,暂时无法获取会话状态。"
140 } else if err != nil {
141 failure = "guest_command"
142 if cmd.ProcessState != nil && cmd.ProcessState.ExitCode() == 255 {
143 failure, message = "ssh_connection", "电脑暂时无法连接运行环境,聊天记录已保留。"
144 }
145 }
146 exit := -1
147 if cmd.ProcessState != nil {
148 exit = cmd.ProcessState.ExitCode()
149 }
150 // Record transport and protocol evidence without terminal output,
151 // prompts, account paths or raw SSH/Python error messages.
152 _ = diagnostics.New(s.profile).Record("warn", "cli-channel", fmt.Sprintf("operation=%s failure=%s exit=%d elapsed_ms=%d context=%v output_bytes=%d stderr_bytes=%d", mode, failure, exit, time.Since(started).Milliseconds(), ctx.Err(), len(result), len(stderr.data)))
153 return errors.New(message)
154 }
155 return nil
156}
157
158func (s *Server) discoverTerminalConversations(ctx context.Context, paths []string) error {
159 s.conversationMu.Lock()
160 defer s.conversationMu.Unlock()
161 s.mu.Lock()
162 ready := s.ready && !s.closing
163 s.mu.Unlock()
164 if !ready {
165 return nil
166 }
167 accounts := []string{"default"}
168 s.claudeAccounts.mu.Lock()
169 list, err := s.loadClaudeAccounts()
170 s.claudeAccounts.mu.Unlock()
171 if err != nil {
172 return err
173 }
174 for _, account := range list.Accounts {
175 if account.guestID() != "default" {
176 accounts = append(accounts, account.guestID())
177 }
178 }
179 workspaces := make(map[string]string, len(paths))
180 for _, path := range paths {
181 if s.windowsGuest != nil {
182 binding, err := s.windowsProjectForHost(path)
183 if err == nil {
184 workspaces[binding.Path] = path
185 }
186 } else {
187 workspaces[s.cliWorkspace(path)] = path
188 }
189 }
190 var found []terminalConversation
191 if err := s.runCLIChannel(ctx, "discover", map[string]any{"accounts": accounts, "workspaces": workspaces}, &found); err != nil {
192 return err
193 }
194 m := &s.mobileCLI
195 m.mu.Lock()
196 defer m.mu.Unlock()
197 known := map[string]*mobileRecord{}
198 running := map[string]bool{}
199 for id := range m.catalog {
200 record, err := m.record(s.profile, id)
201 if err != nil {
202 return err
203 }
204 known[record.CLIID] = record
205 for _, execution := range record.Executions {
206 known[execution.CLIID] = record
207 }
208 }
209 for _, item := range found {
210 var workspace, matched string
211 for guest, path := range workspaces {
212 if cliWorkspaceWithin(item.Workspace, guest, s.windowsGuest != nil) && len(guest) > len(matched) {
213 workspace, matched = path, guest
214 }
215 }
216 if workspace == "" || !validCLIUUID(item.CLIID) {
217 continue
218 }
219 record := known[item.CLIID]
220 if record != nil && record.CLIID != item.CLIID {
221 continue
222 }
223 if record != nil && (record.Deleted || record.Archived) {
224 continue
225 }
226 if record != nil && !record.Terminal {
227 continue
228 }
229 if record == nil {
230 record = &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{ID: uuid.NewString(), Workspace: workspace}, Turns: []mobileTurn{}}, CLIID: item.CLIID, Terminal: true, Resume: true}
231 record.Generation = m.epochLocked()
232 record.Account.GuestID = "default"
233 for _, account := range list.Accounts {
234 config := strings.ReplaceAll(item.Config, "\\", "/")
235 if strings.Contains(config, "/claude-accounts/"+account.guestID()+"/") || s.windowsGuest != nil && strings.HasSuffix(strings.ToLower(config), "/accounts/"+account.guestID()+"/config") {
236 record.Account = claudeSelection{ID: account.ID, GuestID: account.guestID(), Subject: claudeIdentityHash(account.Email, account.Organization)}
237 }
238 }
239 }
240 record.Workspace = workspace
241 record.Active = item.Active
242 record.Title, record.GuestConfig, record.Connection = item.Title, item.Config, item.Connection
243 record.GuestWorkspace = item.Workspace
244 if item.Connection != "" {
245 if terminal := s.terminals.forConversation(item.Connection); terminal != nil {
246 record.TerminalID = terminal.id
247 terminal.mu.Lock()
248 terminal.sharedID = record.ID
249 terminal.mu.Unlock()
250 }
251 }
252 record.UpdatedAt = time.UnixMilli(int64(item.UpdatedAt * 1000)).UTC()
253 if err := writePrivate(mobileRecordPath(s.profile, record.ID), record); err != nil {
254 return err
255 }
256 m.catalog[record.ID] = record.summary()
257 running[record.ID] = running[record.ID] || item.Running
258 known[record.CLIID] = record
259 }
260 m.running = running
261 return nil
262}
263
264func (s *Server) terminalConversationView(ctx context.Context, id string) (mobileSession, error) {
265 s.conversationMu.Lock()
266 defer s.conversationMu.Unlock()
267 m := &s.mobileCLI
268 m.mu.Lock()
269 record, err := m.record(s.profile, id)
270 m.mu.Unlock()
271 if err != nil {
272 return mobileSession{}, err
273 }
274 var current terminalConversation
275 input := map[string]any{"cli_id": record.CLIID, "config": record.GuestConfig, "connection": record.Connection, "account": record.Account.GuestID}
276 if err := s.windowsConversationInput(record, input); err != nil {
277 return mobileSession{}, err
278 }
279 if err := s.runCLIChannel(ctx, "view", input, &current); err != nil {
280 return mobileSession{}, err
281 }
282 root := s.cliWorkspace(record.Workspace)
283 if legacy := s.macOSLegacyWorkspace(record); legacy != "" {
284 root = legacy
285 }
286 if s.windowsGuest != nil {
287 root = record.GuestWorkspace
288 }
289 if current.Workspace == "" && !current.HasHistory && record.TerminalID != "" {
290 if record.Switch != nil && record.Switch.Phase == "starting" && !current.Running {
291 if owner := s.terminals.get(record.TerminalID); owner == nil || !owner.ownsConversation() {
292 m.mu.Lock()
293 record.Switch.Phase, record.Switch.Error = "prepared", "目标账号未建立会话,请重试交接"
294 record.changed()
295 err = writePrivate(mobileRecordPath(s.profile, id), record)
296 m.mu.Unlock()
297 if err != nil {
298 return mobileSession{}, err
299 }
300 }
301 }
302 return record.snapshot(), nil
303 }
304 if !cliWorkspaceWithin(current.Workspace, root, s.windowsGuest != nil) {
305 return mobileSession{}, errors.New("终端的项目已变化,请重新读取会话列表")
306 }
307 if terminal := s.terminals.get(record.TerminalID); terminal != nil && current.Connection != "" && current.Workspace != "" {
308 terminal.mu.Lock()
309 if terminal.connectionID == current.Connection {
310 terminal.conversationEnded = !current.Running
311 }
312 terminal.mu.Unlock()
313 }
314 m.mu.Lock()
315 defer m.mu.Unlock()
316 // Reload after SSH so another request's identity and terminal attachment are
317 // retained. The guest owns transcript content, the host owns the public ID.
318 record, err = m.record(s.profile, id)
319 if err != nil {
320 return mobileSession{}, err
321 }
322 if record.Deleted {
323 return mobileSession{}, os.ErrNotExist
324 }
325 before, _ := json.Marshal(record)
326 record.Turns = adoptedMobileTurns(record.LegacyTurns, current.Turns)
327 if record.Turns == nil {
328 record.Turns = []mobileTurn{}
329 }
330 record.Title, record.ConnectionNotice = current.Title, current.ConnectionNotice
331 if s.macOSLegacyWorkspace(record) != "" {
332 record.ConnectionNotice = strings.TrimSpace(record.ConnectionNotice + "\n" + macOSLegacyWorkspaceNotice)
333 }
334 record.CanSend, record.HistoryTruncated = &current.CanSend, current.HistoryTruncated
335 record.GuestConfig, record.Connection = current.Config, current.Connection
336 record.GuestWorkspace = current.Workspace
337 record.Resume = record.Resume || current.HasHistory
338 record.TerminalRunning = current.Running
339 record.Active = current.Active
340 record.AccountFailure = current.AccountFailure
341 if current.NativeHistory {
342 record.ResumeTranscript = ""
343 }
344 if record.Switch != nil && record.Switch.Phase == "starting" && current.CLIID == record.Switch.TargetID {
345 if current.ChannelReady && !current.ResumePending || current.HasHistory && !current.Running {
346 record.Switch.Phase, record.Switch.Error = "completed", ""
347 if current.NativeHistory {
348 record.ResumeTranscript = ""
349 }
350 } else if !current.Running {
351 if owner := s.terminals.get(record.TerminalID); owner == nil || !owner.ownsConversation() {
352 record.Switch.Phase, record.Switch.Error = "prepared", "目标账号未建立会话,请重试交接"
353 }
354 }
355 }
356 after, _ := json.Marshal(record)
357 if string(before) != string(after) {
358 record.Revision++
359 record.UpdatedAt = time.UnixMilli(int64(current.UpdatedAt * 1000)).UTC()
360 if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
361 return mobileSession{}, err
362 }
363 if m.catalog != nil {
364 m.catalog[id] = record.summary()
365 }
366 }
367 return record.snapshot(), nil
368}
369
370func (s *Server) terminalConversationAction(ctx context.Context, id string, input map[string]any) (mobileSession, error) {
371 if !s.op.TryLock() {
372 return mobileSession{}, errTerminalBusy
373 }
374 defer s.op.Unlock()
375 s.account.mu.Lock()
376 authorized := s.mobileAuthorized(ctx)
377 s.account.mu.Unlock()
378 if !authorized {
379 return mobileSession{}, errMobileLocked
380 }
381 m := &s.mobileCLI
382 m.mu.Lock()
383 record, err := m.record(s.profile, id)
384 m.mu.Unlock()
385 if err != nil {
386 return mobileSession{}, err
387 }
388 if record.Deleted {
389 return mobileSession{}, os.ErrNotExist
390 }
391 if input["action"] == "send" {
392 for _, previous := range record.LegacyTurns {
393 if previous.ID == input["request_id"] {
394 if previous.Prompt != input["text"] {
395 return mobileSession{}, errors.New("同一发送编号已用于另一条消息")
396 }
397 view := record.snapshot()
398 view.AcknowledgedRequestID = previous.ID
399 return view, nil
400 }
401 }
402 }
403 if record.Connection == "" {
404 return mobileSession{}, errors.New("会话连接尚未就绪,请稍后重试")
405 }
406 if record.Archived {
407 return mobileSession{}, errors.New("此会话已归档,请先撤销归档")
408 }
409 input["cli_id"], input["connection"] = record.CLIID, record.Connection
410 if err := s.windowsConversationInput(record, input); err != nil {
411 return mobileSession{}, err
412 }
413 var response struct {
414 OK bool `json:"ok"`
415 Error string `json:"error"`
416 }
417 if err := s.runCLIChannel(ctx, "rpc", input, &response); err != nil {
418 return mobileSession{}, err
419 }
420 if !response.OK {
421 return mobileSession{}, errors.New(response.Error)
422 }
423 if input["action"] == "send" {
424 // The guest already committed this message. Return its receipt now;
425 // fetching the transcript is a separate read, not part of admission.
426 s.account.mu.Lock()
427 defer s.account.mu.Unlock()
428 if !s.mobileAuthorized(ctx) {
429 return mobileSession{}, errMobileLocked
430 }
431 m.mu.Lock()
432 defer m.mu.Unlock()
433 record, err = m.record(s.profile, id)
434 if err != nil {
435 return mobileSession{}, err
436 }
437 view := record.snapshot()
438 requestID, _ := input["request_id"].(string)
439 if findMobileTurn(record, requestID) == nil {
440 text, _ := input["text"].(string)
441 view.Turns = append(view.Turns, mobileTurn{ID: requestID, Prompt: text, Status: "queued"})
442 }
443 view.AcknowledgedRequestID = requestID
444 return view, nil
445 }
446 return s.terminalConversationView(ctx, id)
447}
448
449func (s *Server) prepareTerminalConversation(workspace string, selection claudeSelection, existing string) (string, *mobileRecord, error) {
450 s.mu.Lock()
451 launcher := claudeTerminalCommand(s.preferences)
452 s.mu.Unlock()
453 s.claudeAccounts.mu.Lock()
454 list, loadErr := s.loadClaudeAccounts()
455 s.claudeAccounts.mu.Unlock()
456 if loadErr != nil {
457 return "", nil, loadErr
458 }
459 m := &s.mobileCLI
460 id := existing
461 if id == "" {
462 id = uuid.NewString()
463 }
464 if _, err := m.create(s.profile, workspace, id); err != nil {
465 return "", nil, err
466 }
467 m.mu.Lock()
468 defer m.mu.Unlock()
469 record, err := m.record(s.profile, id)
470 if err != nil {
471 return "", nil, err
472 }
473 legacyWorkspace := ""
474 if existing != "" {
475 legacyWorkspace = s.macOSLegacyWorkspace(record)
476 }
477 if selection.ID == "" && selection.Subject == "" {
478 selection.GuestID = ""
479 }
480 prefix, err := mobileLaunchArgs(launcher, selection)
481 if err != nil {
482 return "", nil, err
483 }
484 record.Terminal, record.Account, record.Launcher = true, selection, launcher
485 if record.SwitchPolicy == "" {
486 record.SwitchPolicy = list.Scheduling.SwitchPolicy
487 if a := list.find(selection.ID); a != nil {
488 record.AccountLabel = a.Label
489 }
490 }
491 record.TerminalID, record.TerminalRunning = "", true
492 record.Connection = uuid.NewString()
493 if record.ResumeTranscript != "" && record.Switch != nil {
494 record.Connection = record.Switch.ID
495 }
496 payload := map[string]any{"id": record.Connection, "session_id": record.CLIID, "prefix": prefix, "config": record.GuestConfig}
497 if record.Resume {
498 payload["resume"] = record.CLIID
499 }
500 if record.ResumeTranscript != "" {
501 payload["resume_transcript"] = record.ResumeTranscript
502 payload["resume"] = ""
503 payload["switch_id"] = record.Switch.ID
504 payload["continue_after_switch"] = record.Switch.Continue
505 }
506 if s.macosGuest != nil && record.GuestWorkspace != "" {
507 root := s.cliWorkspace(workspace)
508 if legacyWorkspace != "" {
509 root = legacyWorkspace
510 }
511 if !cliWorkspaceWithin(record.GuestWorkspace, root, false) {
512 return "", nil, errors.New("会话目录不在已授权的 macOS 项目内")
513 }
514 payload["project_subdir"] = strings.TrimPrefix(strings.TrimPrefix(record.GuestWorkspace, root), "/")
515 }
516 data, _ := json.Marshal(payload)
517 record.CanSend = new(bool)
518 record.ConnectionNotice = ""
519 if legacyWorkspace != "" {
520 record.ConnectionNotice = macOSLegacyWorkspaceNotice
521 }
522 if s.windowsGuest != nil {
523 binding, err := s.windowsProjectForHost(workspace)
524 if err != nil {
525 return "", nil, err
526 }
527 record.GuestWorkspace = binding.Path
528 if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
529 return "", nil, err
530 }
531 return string(data), record, nil
532 }
533 body := s.cliHelperCommand("launch", string(data)) + "; exec bash -i"
534 directory := record.GuestWorkspace
535 if directory == "" {
536 directory = s.cliWorkspace(workspace)
537 }
538 record.GuestWorkspace = directory
539 if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
540 return "", nil, err
541 }
542 if s.macosGuest != nil {
543 if legacyWorkspace != "" {
544 return "cd -- " + shellescape.Quote(legacyWorkspace) + " && exec " + s.cliHelperCommand("macos-launch", string(data)), record, nil
545 }
546 return s.macOSClaudeLaunch(workspace, string(data)), record, nil
547 }
548 script := "cd " + shellescape.Quote(directory) + " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 bash -lic " + shellescape.Quote(body)
549 return script, record, nil
550}
551
552func (s *Server) isTerminalConversation(id string) bool {
553 s.mobileCLI.mu.Lock()
554 defer s.mobileCLI.mu.Unlock()
555 record, err := s.mobileCLI.record(s.profile, id)
556 return err == nil && record.Terminal
557}
558
559func (s *Server) stopTerminalConversation(ctx context.Context, view mobileSession, turnID string) (mobileSession, error) {
560 if len(view.Turns) == 0 || view.Turns[len(view.Turns)-1].ID != turnID || view.Turns[len(view.Turns)-1].Status != "running" {
561 return view, errors.New("本轮运行状态已变化,请重新读取")
562 }
563 s.mobileCLI.mu.Lock()
564 record, err := s.mobileCLI.record(s.profile, view.ID)
565 s.mobileCLI.mu.Unlock()
566 if err != nil {
567 return view, err
568 }
569 terminal := s.terminals.get(record.TerminalID)
570 if terminal == nil {
571 return view, errors.New("请在电脑终端停止这次运行")
572 }
573 s.account.mu.Lock()
574 if !s.mobileAuthorized(ctx) {
575 s.account.mu.Unlock()
576 return view, errMobileLocked
577 }
578 err = terminal.enqueueInput(ctx, "\x1b")
579 s.account.mu.Unlock()
580 if err != nil {
581 return view, err
582 }
583 return s.terminalConversationAction(ctx, view.ID, map[string]any{"action": "stop"})
584}