| 1 | package cliconversation |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "sync" |
| 9 | ) |
| 10 | |
| 11 | |
| 12 | |
| 13 | type PermissionRequest struct { |
| 14 | Tool string |
| 15 | Input json.RawMessage |
| 16 | } |
| 17 | |
| 18 | const maxApprovalBytes = 8 << 10 |
| 19 | const initRequestID = "cage-cli-initialize" |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | type approvalStream struct { |
| 25 | ctx context.Context |
| 26 | cancel context.CancelFunc |
| 27 | input io.WriteCloser |
| 28 | supervised bool |
| 29 | approve func(context.Context, PermissionRequest) bool |
| 30 | turn Turn |
| 31 | |
| 32 | mu sync.Mutex |
| 33 | ready bool |
| 34 | ended bool |
| 35 | pending map[string]context.CancelFunc |
| 36 | seen map[string]bool |
| 37 | workers sync.WaitGroup |
| 38 | writeErr error |
| 39 | } |
| 40 | |
| 41 | func (p *approvalStream) expireInitialization() { |
| 42 | p.mu.Lock() |
| 43 | defer p.mu.Unlock() |
| 44 | if !p.ready && p.ctx.Err() == nil { |
| 45 | p.writeErr = errors.New("客机 Claude Code 未在一分钟内确认逐次审批,请检查 CLI 版本") |
| 46 | p.cancel() |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | func (p *approvalStream) failure() error { |
| 51 | p.mu.Lock() |
| 52 | defer p.mu.Unlock() |
| 53 | return p.writeErr |
| 54 | } |
| 55 | |
| 56 | func (p *approvalStream) begin() error { |
| 57 | p.mu.Lock() |
| 58 | defer p.mu.Unlock() |
| 59 | if p.supervised { |
| 60 | if err := json.NewEncoder(p.input).Encode(map[string]bool{"stream": true}); err != nil { |
| 61 | return errors.New("无法开始客机审批通道") |
| 62 | } |
| 63 | } |
| 64 | return p.sendLocked(map[string]any{"type": "control_request", "request_id": initRequestID, |
| 65 | "request": map[string]any{"subtype": "initialize", "hooks": map[string]any{}}}) |
| 66 | } |
| 67 | |
| 68 | func (p *approvalStream) sendLocked(frame any) error { |
| 69 | if p.supervised { |
| 70 | frame = map[string]any{"input": frame} |
| 71 | } |
| 72 | if err := json.NewEncoder(p.input).Encode(frame); err != nil { |
| 73 | p.writeErr = errors.New("Claude Code 审批通道已断开") |
| 74 | p.cancel() |
| 75 | return p.writeErr |
| 76 | } |
| 77 | return nil |
| 78 | } |
| 79 | |
| 80 | type controlFrame struct { |
| 81 | RequestID string `json:"request_id"` |
| 82 | Request struct { |
| 83 | Subtype string `json:"subtype"` |
| 84 | Tool string `json:"tool_name"` |
| 85 | Input json.RawMessage `json:"input"` |
| 86 | } `json:"request"` |
| 87 | Response struct { |
| 88 | Subtype string `json:"subtype"` |
| 89 | RequestID string `json:"request_id"` |
| 90 | } `json:"response"` |
| 91 | } |
| 92 | |
| 93 | func (p *approvalStream) control(kind string, line []byte) error { |
| 94 | var frame controlFrame |
| 95 | if err := json.Unmarshal(line, &frame); err != nil { |
| 96 | return errors.New("Claude Code 审批消息格式无效") |
| 97 | } |
| 98 | p.mu.Lock() |
| 99 | defer p.mu.Unlock() |
| 100 | if p.ended { |
| 101 | return nil |
| 102 | } |
| 103 | if kind == "control_response" { |
| 104 | if p.ready || frame.Response.RequestID != initRequestID || frame.Response.Subtype != "success" { |
| 105 | return errors.New("客机 Claude Code 无法初始化逐次审批,请检查 CLI 版本") |
| 106 | } |
| 107 | p.ready = true |
| 108 | return p.sendLocked(map[string]any{"type": "user", "session_id": p.turn.SessionID, "parent_tool_use_id": nil, |
| 109 | "message": map[string]string{"role": "user", "content": p.turn.Prompt}}) |
| 110 | } |
| 111 | id := frame.RequestID |
| 112 | if id == "" || len(id) > 256 { |
| 113 | return errors.New("Claude Code 审批请求标识无效") |
| 114 | } |
| 115 | if kind == "control_cancel_request" { |
| 116 | if cancel := p.pending[id]; cancel != nil { |
| 117 | delete(p.pending, id) |
| 118 | cancel() |
| 119 | } |
| 120 | return nil |
| 121 | } |
| 122 | if !p.ready || p.seen[id] { |
| 123 | return errors.New("Claude Code 审批请求重复或未初始化") |
| 124 | } |
| 125 | if len(p.seen) >= 1024 || len(p.pending) >= 16 { |
| 126 | return errors.New("本轮工具请求超出容量,已停止执行") |
| 127 | } |
| 128 | p.seen[id] = true |
| 129 | if frame.Request.Subtype != "can_use_tool" { |
| 130 | return p.sendLocked(map[string]any{"type": "control_response", "response": map[string]string{ |
| 131 | "subtype": "error", "request_id": id, "error": "Unsupported control request"}}) |
| 132 | } |
| 133 | request := PermissionRequest{Tool: frame.Request.Tool, Input: frame.Request.Input} |
| 134 | |
| 135 | |
| 136 | if !toolNamePattern.MatchString(request.Tool) || len(request.Input) == 0 || len(request.Input) > maxApprovalBytes || request.Input[0] != '{' { |
| 137 | return p.answerLocked(id, false, nil) |
| 138 | } |
| 139 | ctx, cancel := context.WithCancel(p.ctx) |
| 140 | p.pending[id] = cancel |
| 141 | p.workers.Add(1) |
| 142 | go func() { |
| 143 | defer p.workers.Done() |
| 144 | defer cancel() |
| 145 | allowed := p.approve(ctx, PermissionRequest{Tool: request.Tool, Input: append(json.RawMessage(nil), request.Input...)}) |
| 146 | p.mu.Lock() |
| 147 | defer p.mu.Unlock() |
| 148 | if p.pending[id] == nil || ctx.Err() != nil || p.ended { |
| 149 | return |
| 150 | } |
| 151 | delete(p.pending, id) |
| 152 | _ = p.answerLocked(id, allowed, request.Input) |
| 153 | }() |
| 154 | return nil |
| 155 | } |
| 156 | |
| 157 | func (p *approvalStream) answerLocked(id string, allowed bool, input json.RawMessage) error { |
| 158 | answer := map[string]any{"behavior": "deny", "message": "Cage did not approve this tool call."} |
| 159 | if allowed { |
| 160 | answer = map[string]any{"behavior": "allow", "updatedInput": input} |
| 161 | } |
| 162 | return p.sendLocked(map[string]any{"type": "control_response", "response": map[string]any{ |
| 163 | "subtype": "success", "request_id": id, "response": answer}}) |
| 164 | } |
| 165 | |
| 166 | func (p *approvalStream) finish() error { |
| 167 | p.mu.Lock() |
| 168 | defer p.mu.Unlock() |
| 169 | p.ended = true |
| 170 | for _, cancel := range p.pending { |
| 171 | cancel() |
| 172 | } |
| 173 | if !p.ready { |
| 174 | return errors.New("客机 Claude Code 未确认逐次审批协议") |
| 175 | } |
| 176 | if p.writeErr != nil { |
| 177 | return p.writeErr |
| 178 | } |
| 179 | if p.supervised { |
| 180 | if err := json.NewEncoder(p.input).Encode(map[string]bool{"finish": true}); err != nil { |
| 181 | return errors.New("无法结束 Claude Code 客机输入") |
| 182 | } |
| 183 | return nil |
| 184 | } |
| 185 | if err := p.input.Close(); err != nil { |
| 186 | return errors.New("无法结束 Claude Code 输入") |
| 187 | } |
| 188 | return nil |
| 189 | } |