| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "regexp" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 15 | ) |
| 16 | |
| 17 | var windowsCLIRelayStage = regexp.MustCompile(`Windows guest channel unavailable \((profile|pairing|connect|server_proof|client_proof|hello|transfer):[A-Za-z0-9_]+\)`) |
| 18 | |
| 19 | type windowsCLIStderr struct{ buffer bytes.Buffer } |
| 20 | |
| 21 | func (w *windowsCLIStderr) Write(data []byte) (int, error) { |
| 22 | n := len(data) |
| 23 | |
| 24 | |
| 25 | _, _ = w.buffer.Write(data[:min(n, 4096-w.buffer.Len())]) |
| 26 | return n, nil |
| 27 | } |
| 28 | |
| 29 | |
| 30 | |
| 31 | func windowsCLIProcessError(ctx context.Context, stderr string) error { |
| 32 | if errors.Is(ctx.Err(), context.DeadlineExceeded) { |
| 33 | return errors.New("等待 Windows 会话服务响应超时,请稍后重试;持续失败时在设置中导出诊断包") |
| 34 | } |
| 35 | if errors.Is(ctx.Err(), context.Canceled) { |
| 36 | return errors.New("Windows 会话请求已取消") |
| 37 | } |
| 38 | stage := windowsCLIRelayStage.FindStringSubmatch(stderr) |
| 39 | if len(stage) == 2 { |
| 40 | switch stage[1] { |
| 41 | case "profile": |
| 42 | return errors.New("无法读取 Windows 环境配置,请在设置中检查环境状态") |
| 43 | case "pairing", "server_proof", "client_proof": |
| 44 | return errors.New("Windows 环境的安全配对校验未完成,请在设置中检查环境连接") |
| 45 | case "connect": |
| 46 | return errors.New("未能连接 Windows 会话服务,请确认 Windows 环境已启动;持续失败时在设置中导出诊断包") |
| 47 | case "hello", "transfer": |
| 48 | return errors.New("Windows 会话服务的通信未完成,请确认 Windows 桌面已登录后重试;持续失败时在设置中导出诊断包") |
| 49 | } |
| 50 | } |
| 51 | return errors.New("未能读取 Windows 会话服务的响应,请稍后重试;持续失败时在设置中导出诊断包") |
| 52 | } |
| 53 | |
| 54 | func windowsCLIProfileID(profile string) string { |
| 55 | sum := sha256.Sum256([]byte(profile)) |
| 56 | return hex.EncodeToString(sum[:8]) |
| 57 | } |
| 58 | |
| 59 | |
| 60 | |
| 61 | func (s *Server) windowsCLIRequest(ctx context.Context, request map[string]any, output any) error { |
| 62 | request["profile"] = windowsCLIProfileID(s.profile) |
| 63 | if request["action"] == "channel" { |
| 64 | encoded, err := json.Marshal(request["input"]) |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | var input map[string]any |
| 69 | if err := json.Unmarshal(encoded, &input); err != nil { |
| 70 | return err |
| 71 | } |
| 72 | if path, ok := input["workspace"].(string); ok && path != "" { |
| 73 | binding, err := s.windowsProjectForGuest(path) |
| 74 | if err != nil { |
| 75 | return err |
| 76 | } |
| 77 | input["project_id"], input["grant"] = binding.ID, binding.Grant |
| 78 | } |
| 79 | request["input"] = input |
| 80 | } |
| 81 | data, err := json.Marshal(request) |
| 82 | if err != nil || len(data) > 4<<20 { |
| 83 | return errors.New("Windows Claude 请求无效") |
| 84 | } |
| 85 | ctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 86 | defer cancel() |
| 87 | cmd, err := guestos.WindowsRelayCommand(ctx, s.profile, "cli") |
| 88 | if err != nil { |
| 89 | return err |
| 90 | } |
| 91 | cmd.Stdin = bytes.NewReader(append(data, '\n')) |
| 92 | var stderr windowsCLIStderr |
| 93 | cmd.Stderr = &stderr |
| 94 | cmd.WaitDelay = 2 * time.Second |
| 95 | var result bytes.Buffer |
| 96 | cmd.Stdout = &boundedWindowsStatusWriter{buffer: &result, remaining: 4 << 20} |
| 97 | if err := cmd.Run(); err != nil { |
| 98 | return windowsCLIProcessError(ctx, stderr.buffer.String()) |
| 99 | } |
| 100 | raw := json.RawMessage(result.Bytes()) |
| 101 | var wrapper map[string]json.RawMessage |
| 102 | if json.Unmarshal(raw, &wrapper) != nil { |
| 103 | return errors.New("Windows Claude Code 响应无效") |
| 104 | } |
| 105 | if wrapper["error"] != nil { |
| 106 | var reason string |
| 107 | if json.Unmarshal(wrapper["error"], &reason) == nil && reason == "requires_gui_login" { |
| 108 | return errors.New("Windows 桌面尚未登录或已锁定,请登录并解锁 Windows 桌面后重试") |
| 109 | } |
| 110 | return errors.New("Windows Claude Code 操作未能完成,原账号与聊天记录已保留") |
| 111 | } |
| 112 | if value, ok := wrapper["result"]; ok { |
| 113 | raw = value |
| 114 | } |
| 115 | if json.Unmarshal(raw, output) != nil { |
| 116 | return errors.New("Windows Claude Code 响应无效") |
| 117 | } |
| 118 | return nil |
| 119 | } |
| 120 | func (s *Server) readWindowsClaudeAccount(ctx context.Context, mode, id, subject string) (claudeGuestSnapshot, error) { |
| 121 | var result claudeGuestSnapshot |
| 122 | if !validClaudeGuestID(id) { |
| 123 | return result, errors.New("Claude 账号 ID 无效") |
| 124 | } |
| 125 | err := s.windowsCLIRequest(ctx, map[string]any{"action": "account", "mode": mode, "account": id, "subject": subject}, &result) |
| 126 | return result, err |
| 127 | } |
| 128 | func (s *Server) windowsProjectForGuest(path string) (*windowsProjectBinding, error) { |
| 129 | s.mu.Lock() |
| 130 | defer s.mu.Unlock() |
| 131 | for _, share := range s.projectShares { |
| 132 | if share.windowsProject != nil && strings.EqualFold(share.windowsProject.Path, path) { |
| 133 | select { |
| 134 | case <-share.done: |
| 135 | continue |
| 136 | default: |
| 137 | } |
| 138 | binding := *share.windowsProject |
| 139 | return &binding, nil |
| 140 | } |
| 141 | } |
| 142 | return nil, errors.New("Windows 项目授权已断开,请重新连接项目") |
| 143 | } |
| 144 | func cliWorkspaceWithin(path, root string, windows bool) bool { |
| 145 | if windows { |
| 146 | path, root = strings.ToLower(strings.ReplaceAll(path, "\\", "/")), strings.ToLower(strings.ReplaceAll(root, "\\", "/")) |
| 147 | } |
| 148 | return root != "" && (path == root || strings.HasPrefix(path, strings.TrimRight(root, "/")+"/")) |
| 149 | } |
| 150 | func (s *Server) createWindowsCLITerminal(input terminalRequest) (*terminalSession, error) { |
| 151 | kind := input.Kind |
| 152 | if kind == "" { |
| 153 | kind = "shell" |
| 154 | } |
| 155 | if kind != "shell" && kind != "claude" && kind != "claude-login" { |
| 156 | return nil, errors.New("终端类型无效") |
| 157 | } |
| 158 | if kind == "shell" && (input.ClaudeAccountID != "" || input.sharedID != "") { |
| 159 | return nil, errors.New("普通终端不能指定 Claude 账号或会话") |
| 160 | } |
| 161 | s.mu.Lock() |
| 162 | ready, closing, command := s.ready, s.closing, claudeTerminalCommand(s.preferences) |
| 163 | s.mu.Unlock() |
| 164 | if closing { |
| 165 | return nil, errTerminalsClosed |
| 166 | } |
| 167 | if !ready || s.busy() { |
| 168 | return nil, errTerminalNotReady |
| 169 | } |
| 170 | var record *mobileRecord |
| 171 | if input.sharedID != "" { |
| 172 | s.mobileCLI.mu.Lock() |
| 173 | found, err := s.mobileCLI.record(s.profile, input.sharedID) |
| 174 | s.mobileCLI.mu.Unlock() |
| 175 | if err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | record = found |
| 179 | if record.Switch != nil && record.Switch.Phase == "preparing" { |
| 180 | return nil, errors.New("账号交接尚未完成,请先重试或取消交接") |
| 181 | } |
| 182 | if record.Archived || record.Deleted { |
| 183 | return nil, errors.New("此会话已归档或删除,请先从已归档会话恢复") |
| 184 | } |
| 185 | if existing := s.terminals.get(record.TerminalID); existing != nil { |
| 186 | if existing.ownsConversation() { |
| 187 | return existing, nil |
| 188 | } |
| 189 | if existing.summary()["closed"] == true { |
| 190 | s.terminals.remove(record.TerminalID) |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | if kind != "claude-login" { |
| 195 | if err := s.terminals.canStart(); err != nil { |
| 196 | return nil, err |
| 197 | } |
| 198 | } |
| 199 | if kind == "claude" && (!sharedCLILauncher(command) || record != nil && record.Launcher != "" && record.Launcher != command) { |
| 200 | return nil, errors.New("Windows 原生共享会话支持 claude 或 ccs 配置名启动命令") |
| 201 | } |
| 202 | workspace := s.workspace() |
| 203 | var project *windowsProjectBinding |
| 204 | var err error |
| 205 | if kind != "claude-login" { |
| 206 | workspace, err = s.connectProject(input.Workspace, false) |
| 207 | if err != nil { |
| 208 | return nil, err |
| 209 | } |
| 210 | project, err = s.windowsProjectForHost(workspace) |
| 211 | if err != nil { |
| 212 | return nil, err |
| 213 | } |
| 214 | } |
| 215 | var selection claudeSelection |
| 216 | var finished func() |
| 217 | var conversation *mobileRecord |
| 218 | if kind != "shell" { |
| 219 | login := kind == "claude-login" |
| 220 | if record != nil && record.Terminal { |
| 221 | selection = record.Account |
| 222 | } else { |
| 223 | selection, err = s.selectTerminalClaudeAccount(command, input.ClaudeAccountID, login, workspace) |
| 224 | } |
| 225 | if err != nil { |
| 226 | return nil, err |
| 227 | } |
| 228 | if selection.ID != "" { |
| 229 | if !validClaudeID(selection.ID) || !validClaudeGuestID(selection.GuestID) || login && selection.GuestID == "default" { |
| 230 | return nil, errors.New("Claude 账号 ID 无效") |
| 231 | } |
| 232 | if login && s.mobileCLI.activeAccounts()[selection.ID] > 0 { |
| 233 | return nil, errors.New("请先结束该账号正在执行的移动 CLI 轮次,再重新登录") |
| 234 | } |
| 235 | if existing, conflict := s.terminals.existingClaudeLogin(selection.ID, login); existing != nil || conflict != nil { |
| 236 | return existing, conflict |
| 237 | } |
| 238 | if !login && selection.Subject == "" { |
| 239 | return nil, errors.New("Claude 账号状态已变化,请重试") |
| 240 | } |
| 241 | if login { |
| 242 | finished = func() { |
| 243 | ctx, cancel := context.WithTimeout(s.lifetimeContext(), 12*time.Second) |
| 244 | defer cancel() |
| 245 | _ = s.confirmClaudeLogin(ctx, selection.ID) |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | operation := "terminal" |
| 251 | request := map[string]any{"action": "open", "cols": 100, "rows": 30, "workspace": "project", "shell": "powershell"} |
| 252 | if kind != "shell" { |
| 253 | operation = "cli" |
| 254 | account := selection.GuestID |
| 255 | if account == "" { |
| 256 | account = "default" |
| 257 | } |
| 258 | request = map[string]any{"action": "terminal", "profile": windowsCLIProfileID(s.profile), "kind": kind, "cols": 100, "rows": 30, "account": account, "subject": selection.Subject} |
| 259 | if kind == "claude" { |
| 260 | parts, _ := mobileLaunchArgs(command, selection) |
| 261 | if len(parts) == 2 && parts[0] == "ccs" { |
| 262 | request["ccs_profile"] = parts[1] |
| 263 | } |
| 264 | payload, found, err := s.prepareTerminalConversation(workspace, selection, input.sharedID) |
| 265 | if err != nil { |
| 266 | return nil, err |
| 267 | } |
| 268 | conversation = found |
| 269 | var value map[string]any |
| 270 | if json.Unmarshal([]byte(payload), &value) != nil { |
| 271 | return nil, errors.New("Claude 会话请求无效") |
| 272 | } |
| 273 | request["conversation"] = value |
| 274 | } |
| 275 | } |
| 276 | if project != nil { |
| 277 | request["project_id"], request["grant"] = project.ID, project.Grant |
| 278 | } |
| 279 | cmd, err := guestos.WindowsRelayCommand(s.lifetimeContext(), s.profile, operation) |
| 280 | if err != nil { |
| 281 | return nil, err |
| 282 | } |
| 283 | if input.requestContext != nil { |
| 284 | s.account.mu.Lock() |
| 285 | if !s.mobileAuthorized(input.requestContext) { |
| 286 | s.account.mu.Unlock() |
| 287 | return nil, errMobileLocked |
| 288 | } |
| 289 | } |
| 290 | session, err := s.terminals.startSessionWithPTY(cmd, workspace, input.Kind, selection, finished, func() (terminalPTY, error) { return startWindowsGuestTerminalRequest(cmd, request) }) |
| 291 | if input.requestContext != nil { |
| 292 | s.account.mu.Unlock() |
| 293 | } |
| 294 | if err == nil && conversation != nil { |
| 295 | session.mu.Lock() |
| 296 | session.sharedID, session.connectionID = conversation.ID, conversation.Connection |
| 297 | session.mu.Unlock() |
| 298 | s.mobileCLI.mu.Lock() |
| 299 | conversation.TerminalID = session.id |
| 300 | err = writePrivate(mobileRecordPath(s.profile, conversation.ID), conversation) |
| 301 | s.mobileCLI.mu.Unlock() |
| 302 | if err != nil { |
| 303 | s.terminals.remove(session.id) |
| 304 | return nil, err |
| 305 | } |
| 306 | s.prepareCLIConnection(session, conversation.ID) |
| 307 | s.monitorClaudeAccount(session, conversation.ID) |
| 308 | } |
| 309 | if err == nil && kind == "claude" && selection.ID != "" { |
| 310 | s.noteClaudeSelection(selection.ID, workspace) |
| 311 | } |
| 312 | return session, err |
| 313 | } |