| 1 | |
| 2 | |
| 3 | package cliconversation |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "io" |
| 12 | "os/exec" |
| 13 | "regexp" |
| 14 | "slices" |
| 15 | "strings" |
| 16 | "time" |
| 17 | "unicode/utf8" |
| 18 | ) |
| 19 | |
| 20 | type Runner struct { |
| 21 | |
| 22 | |
| 23 | Command func(context.Context, string, []string) (*exec.Cmd, error) |
| 24 | |
| 25 | |
| 26 | Approve func(context.Context, PermissionRequest) bool |
| 27 | |
| 28 | |
| 29 | SupervisedStdin bool |
| 30 | OnTools func([]ToolActivity) |
| 31 | } |
| 32 | |
| 33 | type Turn struct { |
| 34 | Workspace string |
| 35 | SessionID string |
| 36 | Prompt string |
| 37 | Resume bool |
| 38 | } |
| 39 | |
| 40 | type Result struct { |
| 41 | Started bool |
| 42 | SingleTurn bool |
| 43 | Text string |
| 44 | DeniedTools []string |
| 45 | } |
| 46 | |
| 47 | var ( |
| 48 | sessionIDPattern = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$") |
| 49 | toolNamePattern = regexp.MustCompile("^[a-zA-Z0-9_.:-]{1,128}$") |
| 50 | ) |
| 51 | |
| 52 | const ( |
| 53 | maxPromptBytes = 64 << 10 |
| 54 | maxEventBytes = 8 << 20 |
| 55 | maxTextBytes = 1 << 20 |
| 56 | ) |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | func (r Runner) Run(ctx context.Context, turn Turn, onText func(string)) (Result, error) { |
| 62 | if r.Command == nil { |
| 63 | return Result{}, errors.New("尚未配置 Cage 客机 Claude Code 命令") |
| 64 | } |
| 65 | if turn.Workspace == "" || !sessionIDPattern.MatchString(turn.SessionID) { |
| 66 | return Result{}, errors.New("Claude Code 项目或会话标识无效") |
| 67 | } |
| 68 | if len(turn.Prompt) > maxPromptBytes || !utf8.ValidString(turn.Prompt) || strings.TrimSpace(turn.Prompt) == "" { |
| 69 | return Result{}, errors.New("消息为空、编码无效或超过 64 KiB") |
| 70 | } |
| 71 | if err := ctx.Err(); err != nil { |
| 72 | return Result{}, err |
| 73 | } |
| 74 | |
| 75 | |
| 76 | |
| 77 | args := []string{"--print", "--output-format", "stream-json", "--verbose", |
| 78 | "--include-partial-messages", "--safe-mode", "--setting-sources", "user", |
| 79 | "--disable-slash-commands"} |
| 80 | if r.Approve != nil { |
| 81 | args = append(args, "--input-format", "stream-json", "--permission-mode", "manual", |
| 82 | "--permission-prompts", "host", "--permission-prompt-tool", "stdio") |
| 83 | } else { |
| 84 | args = append(args, "--input-format", "text", "--permission-mode", "dontAsk") |
| 85 | } |
| 86 | if turn.Resume { |
| 87 | args = append(args, "--resume", turn.SessionID) |
| 88 | } else { |
| 89 | args = append(args, "--session-id", turn.SessionID) |
| 90 | } |
| 91 | |
| 92 | runCtx, cancel := context.WithCancel(ctx) |
| 93 | defer cancel() |
| 94 | cmd, err := r.Command(runCtx, turn.Workspace, args) |
| 95 | if err != nil { |
| 96 | return Result{}, err |
| 97 | } |
| 98 | if cmd == nil { |
| 99 | return Result{}, errors.New("无法准备 Claude Code 客机命令") |
| 100 | } |
| 101 | var input io.WriteCloser |
| 102 | if r.SupervisedStdin || r.Approve != nil { |
| 103 | input, err = cmd.StdinPipe() |
| 104 | if err != nil { |
| 105 | return Result{}, errors.New("无法准备 Claude Code 客机输入") |
| 106 | } |
| 107 | defer input.Close() |
| 108 | } else { |
| 109 | cmd.Stdin = strings.NewReader(turn.Prompt) |
| 110 | } |
| 111 | reader, writer := io.Pipe() |
| 112 | cmd.Stdout = writer |
| 113 | |
| 114 | |
| 115 | cmd.Stderr = io.Discard |
| 116 | cmd.WaitDelay = 2 * time.Second |
| 117 | if err := cmd.Start(); err != nil { |
| 118 | _ = reader.Close() |
| 119 | _ = writer.Close() |
| 120 | if err := ctx.Err(); err != nil { |
| 121 | return Result{}, err |
| 122 | } |
| 123 | return Result{}, errors.New("无法启动 Claude Code 客机连接") |
| 124 | } |
| 125 | if input != nil { |
| 126 | stop := context.AfterFunc(runCtx, func() { _ = input.Close() }) |
| 127 | defer stop() |
| 128 | } |
| 129 | done := make(chan error, 1) |
| 130 | go func() { |
| 131 | err := cmd.Wait() |
| 132 | _ = writer.Close() |
| 133 | done <- err |
| 134 | }() |
| 135 | var approvals *approvalStream |
| 136 | if r.Approve != nil { |
| 137 | approvals = &approvalStream{ctx: runCtx, cancel: cancel, input: input, supervised: r.SupervisedStdin, |
| 138 | turn: turn, approve: r.Approve, pending: make(map[string]context.CancelFunc), seen: make(map[string]bool)} |
| 139 | startup := time.AfterFunc(time.Minute, approvals.expireInitialization) |
| 140 | defer startup.Stop() |
| 141 | err = approvals.begin() |
| 142 | } else if input != nil { |
| 143 | |
| 144 | |
| 145 | sent := make(chan struct{}) |
| 146 | go func() { |
| 147 | defer close(sent) |
| 148 | if err := json.NewEncoder(input).Encode(turn.Prompt); err != nil { |
| 149 | cancel() |
| 150 | } |
| 151 | }() |
| 152 | defer func() { _ = input.Close(); <-sent }() |
| 153 | } |
| 154 | var result Result |
| 155 | if err == nil { |
| 156 | result, err = readResult(reader, turn.SessionID, onText, approvals, r.OnTools) |
| 157 | } |
| 158 | if err != nil { |
| 159 | cancel() |
| 160 | } |
| 161 | _ = reader.Close() |
| 162 | processErr := <-done |
| 163 | |
| 164 | |
| 165 | cancel() |
| 166 | if approvals != nil { |
| 167 | approvals.workers.Wait() |
| 168 | } |
| 169 | if err := ctx.Err(); err != nil { |
| 170 | return result, err |
| 171 | } |
| 172 | if approvals != nil { |
| 173 | if transportErr := approvals.failure(); transportErr != nil { |
| 174 | return result, transportErr |
| 175 | } |
| 176 | } |
| 177 | if err != nil { |
| 178 | return result, err |
| 179 | } |
| 180 | if processErr != nil { |
| 181 | return result, errors.New("Claude Code 进程退出异常,请检查客机连接、CLI 版本和登录状态") |
| 182 | } |
| 183 | return result, nil |
| 184 | } |
| 185 | |
| 186 | type cliEvent struct { |
| 187 | Type string `json:"type"` |
| 188 | Subtype string `json:"subtype"` |
| 189 | SessionID string `json:"session_id"` |
| 190 | ParentToolUseID *string `json:"parent_tool_use_id"` |
| 191 | } |
| 192 | |
| 193 | type resultEvent struct { |
| 194 | IsError bool `json:"is_error"` |
| 195 | Result string `json:"result"` |
| 196 | PermissionDenials []struct { |
| 197 | ToolName string `json:"tool_name"` |
| 198 | } `json:"permission_denials"` |
| 199 | } |
| 200 | |
| 201 | type streamEvent struct { |
| 202 | Event struct { |
| 203 | Type string `json:"type"` |
| 204 | Delta struct { |
| 205 | Type string `json:"type"` |
| 206 | Text string `json:"text"` |
| 207 | } `json:"delta"` |
| 208 | } `json:"event"` |
| 209 | } |
| 210 | |
| 211 | func readResult(reader io.Reader, sessionID string, onText func(string), approvals *approvalStream, onTools func([]ToolActivity)) (Result, error) { |
| 212 | var result Result |
| 213 | var finished bool |
| 214 | var emitted int |
| 215 | var tools []ToolActivity |
| 216 | scan := bufio.NewScanner(reader) |
| 217 | scan.Buffer(make([]byte, 32<<10), maxEventBytes) |
| 218 | for scan.Scan() { |
| 219 | line := bytes.TrimSpace(scan.Bytes()) |
| 220 | if len(line) == 0 { |
| 221 | continue |
| 222 | } |
| 223 | var e cliEvent |
| 224 | if err := json.Unmarshal(line, &e); err != nil || e.Type == "" { |
| 225 | if approvals != nil && !approvals.ready { |
| 226 | return result, errors.New("客机 Claude Code 未返回逐次审批初始化消息,请检查 CLI 版本") |
| 227 | } |
| 228 | return result, errors.New("Claude Code 返回了无效的消息格式") |
| 229 | } |
| 230 | if e.Type == "control_request" || e.Type == "control_cancel_request" || e.Type == "control_response" { |
| 231 | if approvals == nil { |
| 232 | return result, errors.New("Claude Code 需要未配置的交互式审批") |
| 233 | } |
| 234 | if e.SessionID != "" && !strings.EqualFold(e.SessionID, sessionID) { |
| 235 | return result, errors.New("Claude Code 审批会话不匹配") |
| 236 | } |
| 237 | if err := approvals.control(e.Type, line); err != nil { |
| 238 | return result, err |
| 239 | } |
| 240 | continue |
| 241 | } |
| 242 | if e.ParentToolUseID != nil { |
| 243 | continue |
| 244 | } |
| 245 | if e.Type == "system" && e.Subtype == "cage_identity_changed" { |
| 246 | return result, errors.New("会话使用的账号、凭据或上游已变化,请恢复原配置或新建会话") |
| 247 | } |
| 248 | if e.Type == "system" && e.Subtype == "cage_identity_single_turn" { |
| 249 | result.SingleTurn = true |
| 250 | continue |
| 251 | } |
| 252 | if e.Type == "system" && e.Subtype == "cage_identity_unverified" { |
| 253 | return result, errors.New("无法验证本会话原先使用的上游,请检查主机配置或新建会话") |
| 254 | } |
| 255 | if e.Type == "system" && e.Subtype == "cage_identity_unverified_start" { |
| 256 | return result, errors.New("无法验证当前 Claude 账号或上游配置,请在电脑 Cage 检查账号和环境配置") |
| 257 | } |
| 258 | if e.Type == "system" && e.Subtype == "init" { |
| 259 | if !strings.EqualFold(e.SessionID, sessionID) || finished { |
| 260 | return result, errors.New("Claude Code 初始化了其他会话") |
| 261 | } |
| 262 | result.Started = true |
| 263 | continue |
| 264 | } |
| 265 | if (e.Type == "assistant" || e.Type == "user") && onTools != nil && !finished && strings.EqualFold(e.SessionID, sessionID) { |
| 266 | var changed bool |
| 267 | tools, changed = updateTools(tools, e.Type, line) |
| 268 | if changed { |
| 269 | onTools(slices.Clone(tools)) |
| 270 | } |
| 271 | } |
| 272 | if e.Type != "stream_event" && e.Type != "result" { |
| 273 | continue |
| 274 | } |
| 275 | if !strings.EqualFold(e.SessionID, sessionID) || finished { |
| 276 | return result, errors.New("Claude Code 会话标识或结果顺序不匹配") |
| 277 | } |
| 278 | if e.Type == "stream_event" { |
| 279 | var stream streamEvent |
| 280 | if err := json.Unmarshal(line, &stream); err != nil { |
| 281 | return result, errors.New("Claude Code 文本事件无效") |
| 282 | } |
| 283 | if stream.Event.Type == "content_block_delta" && stream.Event.Delta.Type == "text_delta" { |
| 284 | text := stream.Event.Delta.Text |
| 285 | emitted += len(text) |
| 286 | if emitted > maxTextBytes { |
| 287 | return result, errors.New("Claude Code 回复超过 1 MiB") |
| 288 | } |
| 289 | if onText != nil && text != "" { |
| 290 | onText(text) |
| 291 | } |
| 292 | } |
| 293 | continue |
| 294 | } |
| 295 | finished = true |
| 296 | if approvals != nil { |
| 297 | if err := approvals.finish(); err != nil { |
| 298 | return result, err |
| 299 | } |
| 300 | } |
| 301 | var final resultEvent |
| 302 | if err := json.Unmarshal(line, &final); err != nil { |
| 303 | return result, errors.New("Claude Code 返回了无效的最终结果") |
| 304 | } |
| 305 | for _, denial := range final.PermissionDenials { |
| 306 | name := denial.ToolName |
| 307 | if !toolNamePattern.MatchString(name) { |
| 308 | name = "未知工具" |
| 309 | } |
| 310 | if !slices.Contains(result.DeniedTools, name) { |
| 311 | result.DeniedTools = append(result.DeniedTools, name) |
| 312 | } |
| 313 | if len(result.DeniedTools) == 64 { |
| 314 | break |
| 315 | } |
| 316 | } |
| 317 | if final.IsError || e.Subtype != "success" { |
| 318 | return result, errors.New("Claude Code 未完成本轮,请检查客机登录、网络和工具权限") |
| 319 | } |
| 320 | if !result.Started { |
| 321 | return result, errors.New("Claude Code 返回结果前未确认会话") |
| 322 | } |
| 323 | if len(final.Result) > maxTextBytes { |
| 324 | return result, errors.New("Claude Code 回复超过 1 MiB") |
| 325 | } |
| 326 | result.Text = final.Result |
| 327 | } |
| 328 | if scan.Err() != nil { |
| 329 | return result, errors.New("Claude Code 消息流中断或单条事件过大") |
| 330 | } |
| 331 | if !finished { |
| 332 | if approvals != nil && !approvals.ready { |
| 333 | return result, errors.New("客机 Claude Code 未确认逐次审批协议,请检查 CLI 版本") |
| 334 | } |
| 335 | return result, errors.New("Claude Code 未返回本轮结果,请检查客机连接、CLI 版本和登录状态") |
| 336 | } |
| 337 | return result, nil |
| 338 | } |