| 1 | package claude |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | |
| 8 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 9 | ) |
| 10 | |
| 11 | const MaxFrameBytes = 1024 * 1024 |
| 12 | const errProtocol provider.Error = "claude_protocol_rejected" |
| 13 | |
| 14 | func Decode(raw []byte) ([]provider.Event, error) { |
| 15 | if len(raw) == 0 || len(raw) > MaxFrameBytes || !uniqueJSON(raw) { |
| 16 | return nil, errProtocol |
| 17 | } |
| 18 | var v struct { |
| 19 | Type string `json:"type"` |
| 20 | Subtype string `json:"subtype"` |
| 21 | Session string `json:"session_id"` |
| 22 | Request string `json:"request_id"` |
| 23 | IsError *bool `json:"is_error"` |
| 24 | } |
| 25 | if json.Unmarshal(raw, &v) != nil || v.Type == "" || v.Session == "" { |
| 26 | return nil, errProtocol |
| 27 | } |
| 28 | kind := v.Type |
| 29 | switch v.Type { |
| 30 | case "system": |
| 31 | if v.Subtype == "init" { |
| 32 | kind = "session.init" |
| 33 | } |
| 34 | case "stream_event": |
| 35 | kind = "message.delta" |
| 36 | case "assistant": |
| 37 | kind = "message" |
| 38 | case "result": |
| 39 | if v.IsError == nil || v.Subtype == "" { |
| 40 | return nil, errProtocol |
| 41 | } |
| 42 | kind = "turn.failed" |
| 43 | if !*v.IsError && v.Subtype == "success" { |
| 44 | kind = "turn.completed" |
| 45 | } |
| 46 | } |
| 47 | return []provider.Event{{SessionID: v.Session, RequestID: v.Request, Kind: kind, Payload: bytes.Clone(raw)}}, nil |
| 48 | } |
| 49 | |
| 50 | func uniqueJSON(raw []byte) bool { |
| 51 | d := json.NewDecoder(bytes.NewReader(raw)) |
| 52 | d.UseNumber() |
| 53 | var value func() bool |
| 54 | value = func() bool { |
| 55 | token, e := d.Token() |
| 56 | if e != nil { |
| 57 | return false |
| 58 | } |
| 59 | delim, ok := token.(json.Delim) |
| 60 | if !ok { |
| 61 | return true |
| 62 | } |
| 63 | switch delim { |
| 64 | case '{': |
| 65 | seen := map[string]bool{} |
| 66 | for d.More() { |
| 67 | k, e := d.Token() |
| 68 | if e != nil { |
| 69 | return false |
| 70 | } |
| 71 | s, ok := k.(string) |
| 72 | if !ok || seen[s] { |
| 73 | return false |
| 74 | } |
| 75 | seen[s] = true |
| 76 | if !value() { |
| 77 | return false |
| 78 | } |
| 79 | } |
| 80 | end, e := d.Token() |
| 81 | return e == nil && end == json.Delim('}') |
| 82 | case '[': |
| 83 | for d.More() { |
| 84 | if !value() { |
| 85 | return false |
| 86 | } |
| 87 | } |
| 88 | end, e := d.Token() |
| 89 | return e == nil && end == json.Delim(']') |
| 90 | } |
| 91 | return false |
| 92 | } |
| 93 | if !value() { |
| 94 | return false |
| 95 | } |
| 96 | _, e := d.Token() |
| 97 | return e == io.EOF |
| 98 | } |
| 99 | |
| 100 | func userEnvelope(session, prompt string) ([]byte, error) { |
| 101 | if session == "" || prompt == "" { |
| 102 | return nil, errProtocol |
| 103 | } |
| 104 | raw, e := json.Marshal(struct { |
| 105 | Type string `json:"type"` |
| 106 | Message struct { |
| 107 | Role string `json:"role"` |
| 108 | Content string `json:"content"` |
| 109 | } `json:"message"` |
| 110 | Session string `json:"session_id"` |
| 111 | Parent *string `json:"parent_tool_use_id"` |
| 112 | }{Type: "user", Message: struct { |
| 113 | Role string `json:"role"` |
| 114 | Content string `json:"content"` |
| 115 | }{"user", prompt}, Session: session}) |
| 116 | if e != nil || len(raw) > MaxFrameBytes { |
| 117 | return nil, errProtocol |
| 118 | } |
| 119 | return append(raw, '\n'), nil |
| 120 | } |
| 121 | |
| 122 | // UserEnvelope is one stream-json user frame. |
| 123 | func UserEnvelope(session, prompt string) ([]byte, error) { return userEnvelope(session, prompt) } |
| 124 | |
| 125 | // MaxUserFrameBytes bounds a user frame that carries images: five model |
| 126 | // images of at most 1.5 MB each, base64, and the text. |
| 127 | const MaxUserFrameBytes = 12 << 20 |
| 128 | |
| 129 | // Image is one image for the model: its media type and bytes. |
| 130 | type Image struct { |
| 131 | MediaType string |
| 132 | Data []byte |
| 133 | } |
| 134 | |
| 135 | // UserContent is one stream-json user frame with the text first and each |
| 136 | // image as an image content block (source base64), as the Agent SDK's |
| 137 | // streaming input sends them. Without images it is UserEnvelope. |
| 138 | func UserContent(session, prompt string, images []Image) ([]byte, error) { |
| 139 | if len(images) == 0 { |
| 140 | return userEnvelope(session, prompt) |
| 141 | } |
| 142 | if session == "" || prompt == "" { |
| 143 | return nil, errProtocol |
| 144 | } |
| 145 | type source struct { |
| 146 | Type string `json:"type"` |
| 147 | MediaType string `json:"media_type"` |
| 148 | Data []byte `json:"data"` |
| 149 | } |
| 150 | type block struct { |
| 151 | Type string `json:"type"` |
| 152 | Text string `json:"text,omitempty"` |
| 153 | Source *source `json:"source,omitempty"` |
| 154 | } |
| 155 | content := []block{{Type: "text", Text: prompt}} |
| 156 | for _, im := range images { |
| 157 | switch im.MediaType { |
| 158 | case "image/png", "image/jpeg", "image/gif", "image/webp": |
| 159 | default: |
| 160 | return nil, errProtocol |
| 161 | } |
| 162 | content = append(content, block{Type: "image", Source: &source{Type: "base64", MediaType: im.MediaType, Data: im.Data}}) |
| 163 | } |
| 164 | raw, e := json.Marshal(struct { |
| 165 | Type string `json:"type"` |
| 166 | Message struct { |
| 167 | Role string `json:"role"` |
| 168 | Content []block `json:"content"` |
| 169 | } `json:"message"` |
| 170 | Session string `json:"session_id"` |
| 171 | Parent *string `json:"parent_tool_use_id"` |
| 172 | }{Type: "user", Message: struct { |
| 173 | Role string `json:"role"` |
| 174 | Content []block `json:"content"` |
| 175 | }{"user", content}, Session: session}) |
| 176 | if e != nil || len(raw) > MaxUserFrameBytes { |
| 177 | return nil, errProtocol |
| 178 | } |
| 179 | return append(raw, '\n'), nil |
| 180 | } |
| 181 | |
| 182 | // StreamText returns the text of a stream_event text delta. |
| 183 | func StreamText(raw []byte) (string, bool) { |
| 184 | var v struct { |
| 185 | Event struct { |
| 186 | Type string `json:"type"` |
| 187 | Delta struct { |
| 188 | Type string `json:"type"` |
| 189 | Text string `json:"text"` |
| 190 | } `json:"delta"` |
| 191 | } `json:"event"` |
| 192 | } |
| 193 | if json.Unmarshal(raw, &v) != nil || v.Event.Type != "content_block_delta" || v.Event.Delta.Type != "text_delta" { |
| 194 | return "", false |
| 195 | } |
| 196 | return v.Event.Delta.Text, v.Event.Delta.Text != "" |
| 197 | } |
| 198 | |
| 199 | // Result is the end of one turn. |
| 200 | type Result struct { |
| 201 | Text string |
| 202 | InputTokens, OutputTokens int64 |
| 203 | // CacheRead and CacheCreation are the prompt-cache counts; Model is |
| 204 | // the model that answered most of the turn (modelUsage's largest). |
| 205 | CacheRead, CacheCreation int64 |
| 206 | Model string |
| 207 | Failed bool |
| 208 | } |
| 209 | |
| 210 | // ParseResult reads a result frame. Provider error text is never surfaced. |
| 211 | func ParseResult(raw []byte) (Result, bool) { |
| 212 | var v struct { |
| 213 | Type string `json:"type"` |
| 214 | Subtype string `json:"subtype"` |
| 215 | IsError *bool `json:"is_error"` |
| 216 | Result string `json:"result"` |
| 217 | Usage struct { |
| 218 | Input int64 `json:"input_tokens"` |
| 219 | Output int64 `json:"output_tokens"` |
| 220 | CacheRead int64 `json:"cache_read_input_tokens"` |
| 221 | CacheCreation int64 `json:"cache_creation_input_tokens"` |
| 222 | } `json:"usage"` |
| 223 | Models map[string]struct { |
| 224 | Output int64 `json:"outputTokens"` |
| 225 | } `json:"modelUsage"` |
| 226 | } |
| 227 | if json.Unmarshal(raw, &v) != nil || v.Type != "result" || v.IsError == nil { |
| 228 | return Result{}, false |
| 229 | } |
| 230 | r := Result{InputTokens: v.Usage.Input, OutputTokens: v.Usage.Output, CacheRead: v.Usage.CacheRead, CacheCreation: v.Usage.CacheCreation, Failed: *v.IsError || v.Subtype != "success"} |
| 231 | most := int64(-1) |
| 232 | for name, m := range v.Models { |
| 233 | if m.Output > most || m.Output == most && name < r.Model { |
| 234 | r.Model, most = name, m.Output |
| 235 | } |
| 236 | } |
| 237 | if !r.Failed { |
| 238 | r.Text = v.Result |
| 239 | } |
| 240 | return r, true |
| 241 | } |
| 242 | |