| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | _ "embed" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "regexp" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "al.essio.dev/pkg/shellescape" |
| 15 | "github.com/google/uuid" |
| 16 | "github.com/sylvinus/agent-vm/internal/cliconversation" |
| 17 | ) |
| 18 | |
| 19 | |
| 20 | var mobileSupervisor string |
| 21 | |
| 22 | var mobileCCSProfile = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$") |
| 23 | |
| 24 | type mobileEpochKey struct{} |
| 25 | |
| 26 | var errMobileLocked = errors.New("Cage 已锁定,请重新解锁后操作") |
| 27 | |
| 28 | |
| 29 | |
| 30 | func (s *Server) mobileAuthorized(ctx context.Context) bool { |
| 31 | epoch, _ := ctx.Value(mobileEpochKey{}).(context.Context) |
| 32 | return len(s.account.key) == 32 && epoch != nil && epoch == s.account.epoch && epoch.Err() == nil && ctx.Err() == nil |
| 33 | } |
| 34 | |
| 35 | func mobileLaunchArgs(launcher string, account claudeSelection) ([]string, error) { |
| 36 | parts := strings.Fields(launcher) |
| 37 | if len(parts) == 2 && parts[0] == "ccs" && mobileCCSProfile.MatchString(parts[1]) { |
| 38 | if account.ID != "" { |
| 39 | return nil, errors.New("当前账号池需要直接使用 claude 启动命令") |
| 40 | } |
| 41 | return parts, nil |
| 42 | } |
| 43 | if len(parts) != 1 || parts[0] != "claude" { |
| 44 | return nil, errors.New("移动会话支持 claude 或 ccs 配置名,请在主机检查 Claude 启动命令") |
| 45 | } |
| 46 | if account.ID == "" && account.GuestID == "" { |
| 47 | return parts, nil |
| 48 | } |
| 49 | boundDefault := account.ID == "" && account.GuestID == "default" |
| 50 | if (!boundDefault && !validClaudeID(account.ID)) || !validClaudeGuestID(account.GuestID) || len(account.Subject) != 64 { |
| 51 | return nil, errors.New("Claude 账号身份无效") |
| 52 | } |
| 53 | return []string{"env", "CAGE_CLAUDE_SUBJECT=" + account.Subject, "/usr/local/bin/cage-claude-account", "run", account.GuestID}, nil |
| 54 | } |
| 55 | |
| 56 | func sharedCLILauncher(launcher string) bool { |
| 57 | _, err := mobileLaunchArgs(launcher, claudeSelection{}) |
| 58 | return err == nil |
| 59 | } |
| 60 | |
| 61 | func (s *Server) mobileRunner(prefix []string) cliconversation.Runner { |
| 62 | return cliconversation.Runner{SupervisedStdin: true, Command: func(ctx context.Context, workspace string, args []string) (*exec.Cmd, error) { |
| 63 | |
| 64 | |
| 65 | login := `exec 3>&1 1>&2; exec /bin/bash -lc ` + shellescape.Quote(`exec 1>&3 3>&-; cd -- "$1" && shift && exec "$@"`) + ` "$0" "$@"` |
| 66 | argv := []string{"/usr/bin/python3", "-I", "-c", mobileSupervisor, guestPath(workspace), "/bin/bash", "-c", |
| 67 | login, "cage-mobile-cli", guestPath(workspace)} |
| 68 | argv = append(argv, mobileIdentityCommand(prefix, args)...) |
| 69 | command := "exec " + shellescape.QuoteCommand(argv) |
| 70 | return s.sshCommand(ctx, "-T", s.sshTarget(), "--", command), nil |
| 71 | }} |
| 72 | } |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | func (s *Server) prepareMobileLaunch(record *mobileRecord) (claudeSelection, string, cliconversation.Runner, error) { |
| 78 | var empty cliconversation.Runner |
| 79 | if s.windowsGuest != nil { |
| 80 | return claudeSelection{}, "", empty, errWindowsLegacyMobile |
| 81 | } |
| 82 | s.mu.Lock() |
| 83 | ready, closing, update, configured := s.ready, s.closing, s.guestUpdateRequired, claudeTerminalCommand(s.preferences) |
| 84 | s.mu.Unlock() |
| 85 | if closing || !ready || !s.vmRunning() || s.busy() { |
| 86 | return claudeSelection{}, "", empty, errTerminalNotReady |
| 87 | } |
| 88 | if _, err := s.connectProject(record.Workspace, false); err != nil { |
| 89 | return claudeSelection{}, "", empty, err |
| 90 | } |
| 91 | selection, launcher := record.Account, record.Launcher |
| 92 | if launcher == "" { |
| 93 | launcher = configured |
| 94 | var err error |
| 95 | selection, err = s.selectTerminalClaudeAccount(launcher, "", false, record.Workspace) |
| 96 | if err != nil { |
| 97 | return selection, "", empty, err |
| 98 | } |
| 99 | |
| 100 | |
| 101 | if launcher == "claude" && selection.ID == "" && !update { |
| 102 | if epoch, ok := s.account.access(); ok { |
| 103 | if status, _, err := s.inspectClaudeDefault(epoch, true); err == nil && status.subject() != "" { |
| 104 | selection = claudeSelection{GuestID: "default", Subject: status.subject()} |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | } else if launcher != configured { |
| 109 | return selection, "", empty, errors.New("主机已更改 Claude 启动命令。请恢复原配置或新建会话") |
| 110 | } |
| 111 | if selection.ID != "" { |
| 112 | if update { |
| 113 | return selection, "", empty, errGuestUpdateRequired |
| 114 | } |
| 115 | s.claudeAccounts.mu.Lock() |
| 116 | list, err := s.loadClaudeAccounts() |
| 117 | s.claudeAccounts.mu.Unlock() |
| 118 | if err != nil { |
| 119 | return selection, "", empty, err |
| 120 | } |
| 121 | account := list.find(selection.ID) |
| 122 | if account == nil || !account.Enabled || account.Status != "ready" || account.guestID() != selection.GuestID || claudeIdentityHash(account.Email, account.Organization) != selection.Subject { |
| 123 | return selection, "", empty, errors.New("原会话的 Claude 账号已停用或发生变化") |
| 124 | } |
| 125 | if _, err = s.terminals.existingClaudeLogin(selection.ID, false); err != nil { |
| 126 | return selection, "", empty, err |
| 127 | } |
| 128 | } |
| 129 | prefix, err := mobileLaunchArgs(launcher, selection) |
| 130 | return selection, launcher, s.mobileRunner(prefix), err |
| 131 | } |
| 132 | |
| 133 | func findMobileTurn(record *mobileRecord, id string) *mobileTurn { |
| 134 | for i := range record.Turns { |
| 135 | if record.Turns[i].ID == id { |
| 136 | return &record.Turns[i] |
| 137 | } |
| 138 | } |
| 139 | return nil |
| 140 | } |
| 141 | func (s *Server) submitMobileTurn(ctx context.Context, id, requestID, prompt string) (mobileSession, error) { |
| 142 | var empty mobileSession |
| 143 | if !s.op.TryLock() { |
| 144 | return empty, errTerminalBusy |
| 145 | } |
| 146 | defer s.op.Unlock() |
| 147 | m := &s.mobileCLI |
| 148 | m.mu.Lock() |
| 149 | record, err := m.record(s.profile, id) |
| 150 | if err != nil { |
| 151 | m.mu.Unlock() |
| 152 | return empty, err |
| 153 | } |
| 154 | if record.Deleted { |
| 155 | m.mu.Unlock() |
| 156 | return empty, os.ErrNotExist |
| 157 | } |
| 158 | if record.Archived { |
| 159 | m.mu.Unlock() |
| 160 | return empty, errors.New("此会话已归档,请先撤销归档") |
| 161 | } |
| 162 | if previous := findMobileTurn(record, requestID); previous != nil { |
| 163 | view := record.snapshot() |
| 164 | m.mu.Unlock() |
| 165 | if previous.Prompt != prompt { |
| 166 | return empty, errors.New("同一发送编号已用于另一条消息") |
| 167 | } |
| 168 | return view, nil |
| 169 | } |
| 170 | if m.active[id] != nil || len(m.active) >= 4 { |
| 171 | m.mu.Unlock() |
| 172 | return empty, errors.New("已有轮次在运行,请等待或停止后重试") |
| 173 | } |
| 174 | size := len(prompt) + mobileReplyLimit |
| 175 | if record.SingleTurn { |
| 176 | m.mu.Unlock() |
| 177 | return empty, errors.New("此配置只能进行单轮对话,请新建会话") |
| 178 | } |
| 179 | for _, t := range record.Turns { |
| 180 | size += len(t.Prompt) + len(t.Text) |
| 181 | for _, tool := range t.Tools { |
| 182 | size += len(tool.ID) + len(tool.Name) + len(tool.Detail) + 64 |
| 183 | } |
| 184 | } |
| 185 | if size > mobileHistoryLimit || len(record.Turns) >= 256 { |
| 186 | m.mu.Unlock() |
| 187 | return empty, errors.New("会话已达到移动历史容量,请新建会话继续") |
| 188 | } |
| 189 | m.mu.Unlock() |
| 190 | |
| 191 | selection, launcher, runner, err := s.prepareMobileLaunch(record) |
| 192 | if err != nil { |
| 193 | return empty, err |
| 194 | } |
| 195 | return s.admitMobileTurn(ctx, record, requestID, prompt, selection, launcher, runner) |
| 196 | } |
| 197 | |
| 198 | |
| 199 | |
| 200 | func (s *Server) admitMobileTurn(request context.Context, record *mobileRecord, requestID, prompt string, selection claudeSelection, launcher string, runner cliconversation.Runner) (mobileSession, error) { |
| 201 | var empty mobileSession |
| 202 | if err := request.Err(); err != nil { |
| 203 | return empty, err |
| 204 | } |
| 205 | parent, finish, err := s.beginActivity(context.Background()) |
| 206 | if err != nil { |
| 207 | return empty, err |
| 208 | } |
| 209 | ctx, cancel := context.WithCancel(parent) |
| 210 | m := &s.mobileCLI |
| 211 | s.account.mu.Lock() |
| 212 | if !s.mobileAuthorized(request) { |
| 213 | s.account.mu.Unlock() |
| 214 | cancel() |
| 215 | finish() |
| 216 | return empty, errMobileLocked |
| 217 | } |
| 218 | m.mu.Lock() |
| 219 | record.Account, record.Launcher = selection, launcher |
| 220 | resume := record.Resume |
| 221 | |
| 222 | |
| 223 | record.Resume = true |
| 224 | if len(record.Turns) == 0 { |
| 225 | title := []rune(strings.Join(strings.Fields(prompt), " ")) |
| 226 | record.Title = string(title[:min(len(title), 40)]) |
| 227 | } |
| 228 | record.Turns = append(record.Turns, mobileTurn{ID: requestID, Prompt: prompt, Status: "running"}) |
| 229 | record.changed() |
| 230 | if err = writePrivate(mobileRecordPath(s.profile, record.ID), record); err != nil { |
| 231 | m.mu.Unlock() |
| 232 | s.account.mu.Unlock() |
| 233 | cancel() |
| 234 | finish() |
| 235 | return empty, errors.New("无法保存消息,未启动执行") |
| 236 | } |
| 237 | run := &mobileRun{record: record, cancel: cancel, done: make(chan struct{}), approvalGate: make(chan struct{}, 1)} |
| 238 | if m.active == nil { |
| 239 | m.active = make(map[string]*mobileRun) |
| 240 | } |
| 241 | m.active[record.ID] = run |
| 242 | view := record.snapshot() |
| 243 | m.mu.Unlock() |
| 244 | s.account.mu.Unlock() |
| 245 | if selection.ID != "" { |
| 246 | s.noteClaudeSelection(selection.ID, record.Workspace) |
| 247 | } |
| 248 | go func() { |
| 249 | defer finish() |
| 250 | defer close(run.done) |
| 251 | defer cancel() |
| 252 | turn := &record.Turns[len(record.Turns)-1] |
| 253 | runner.Approve = func(ctx context.Context, request cliconversation.PermissionRequest) bool { |
| 254 | return m.awaitMobileDecision(ctx, run, turn, request) |
| 255 | } |
| 256 | runner.OnTools = func(tools []cliconversation.ToolActivity) { |
| 257 | m.mu.Lock() |
| 258 | defer m.mu.Unlock() |
| 259 | turn.Tools = tools |
| 260 | record.changed() |
| 261 | } |
| 262 | result, runErr := runner.Run(ctx, cliconversation.Turn{Workspace: record.Workspace, SessionID: record.CLIID, Prompt: prompt, Resume: resume}, func(delta string) { |
| 263 | m.mu.Lock() |
| 264 | defer m.mu.Unlock() |
| 265 | if turn.Status != "running" || turn.Truncated || delta == "" { |
| 266 | return |
| 267 | } |
| 268 | remain := mobileReplyLimit - len(turn.Text) |
| 269 | part := mobileTrim(delta, remain) |
| 270 | turn.Text += part |
| 271 | turn.Truncated = len(part) < len(delta) |
| 272 | record.changed() |
| 273 | }) |
| 274 | m.mu.Lock() |
| 275 | defer m.mu.Unlock() |
| 276 | record.Resume = resume || result.Started |
| 277 | record.SingleTurn = result.SingleTurn && result.Started |
| 278 | turn.Approval = nil |
| 279 | run.pending = nil |
| 280 | switch { |
| 281 | case ctx.Err() != nil || turn.Status == "stopping": |
| 282 | turn.Status = "stopped" |
| 283 | case runErr != nil: |
| 284 | turn.Status, turn.Error = "failed", runErr.Error() |
| 285 | default: |
| 286 | turn.Status = "completed" |
| 287 | } |
| 288 | if result.Text != "" { |
| 289 | turn.Text = mobileTrim(result.Text, mobileReplyLimit) |
| 290 | turn.Truncated = len(turn.Text) < len(result.Text) |
| 291 | } |
| 292 | turn.DeniedTools = slices.Clone(result.DeniedTools) |
| 293 | record.changed() |
| 294 | if err := writePrivate(mobileRecordPath(s.profile, record.ID), record); err != nil { |
| 295 | |
| 296 | |
| 297 | turn.Error = "本轮结果未能保存,请检查主机磁盘后重新读取会话" |
| 298 | turn.Status = "failed" |
| 299 | run.cancel = nil |
| 300 | } else { |
| 301 | delete(m.active, record.ID) |
| 302 | } |
| 303 | if m.catalog != nil { |
| 304 | m.catalog[record.ID] = record.summary() |
| 305 | } |
| 306 | }() |
| 307 | return view, nil |
| 308 | } |
| 309 | |
| 310 | func (s *Server) stopMobileTurn(id, requestID string) (mobileSession, error) { |
| 311 | m := &s.mobileCLI |
| 312 | m.mu.Lock() |
| 313 | defer m.mu.Unlock() |
| 314 | record, err := m.record(s.profile, id) |
| 315 | if err != nil { |
| 316 | return mobileSession{}, err |
| 317 | } |
| 318 | turn := findMobileTurn(record, requestID) |
| 319 | if turn == nil { |
| 320 | return mobileSession{}, os.ErrNotExist |
| 321 | } |
| 322 | run := m.active[id] |
| 323 | if run != nil && run.cancel != nil && turn.Status == "running" && turn == &record.Turns[len(record.Turns)-1] { |
| 324 | turn.Status = "stopping" |
| 325 | turn.Approval = nil |
| 326 | run.pending = nil |
| 327 | record.changed() |
| 328 | run.cancel() |
| 329 | } |
| 330 | return record.snapshot(), nil |
| 331 | } |
| 332 | |
| 333 | func (m *mobileCLIStore) awaitMobileDecision(ctx context.Context, run *mobileRun, turn *mobileTurn, request cliconversation.PermissionRequest) bool { |
| 334 | |
| 335 | |
| 336 | ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) |
| 337 | defer cancel() |
| 338 | select { |
| 339 | case run.approvalGate <- struct{}{}: |
| 340 | case <-ctx.Done(): |
| 341 | return false |
| 342 | } |
| 343 | defer func() { <-run.approvalGate }() |
| 344 | pending := &mobileDecision{ctx: ctx, reply: make(chan bool, 1)} |
| 345 | m.mu.Lock() |
| 346 | if ctx.Err() != nil || turn.Status != "running" { |
| 347 | m.mu.Unlock() |
| 348 | return false |
| 349 | } |
| 350 | run.pending = pending |
| 351 | turn.Approval = &mobileApproval{ID: uuid.NewString(), Tool: request.Tool, Input: request.Input} |
| 352 | run.record.changed() |
| 353 | m.mu.Unlock() |
| 354 | defer func() { |
| 355 | m.mu.Lock() |
| 356 | defer m.mu.Unlock() |
| 357 | if run.pending == pending { |
| 358 | run.pending = nil |
| 359 | turn.Approval = nil |
| 360 | run.record.changed() |
| 361 | } |
| 362 | }() |
| 363 | select { |
| 364 | case <-ctx.Done(): |
| 365 | return false |
| 366 | case allow := <-pending.reply: |
| 367 | return allow && ctx.Err() == nil |
| 368 | } |
| 369 | } |