package claude import ( "bytes" "encoding/json" "io" "amadan.net/oficina/equipo/internal/runner/provider" ) const MaxFrameBytes = 1024 * 1024 const errProtocol provider.Error = "claude_protocol_rejected" func Decode(raw []byte) ([]provider.Event, error) { if len(raw) == 0 || len(raw) > MaxFrameBytes || !uniqueJSON(raw) { return nil, errProtocol } var v struct { Type string `json:"type"` Subtype string `json:"subtype"` Session string `json:"session_id"` Request string `json:"request_id"` IsError *bool `json:"is_error"` } if json.Unmarshal(raw, &v) != nil || v.Type == "" || v.Session == "" { return nil, errProtocol } kind := v.Type switch v.Type { case "system": if v.Subtype == "init" { kind = "session.init" } case "stream_event": kind = "message.delta" case "assistant": kind = "message" case "result": if v.IsError == nil || v.Subtype == "" { return nil, errProtocol } kind = "turn.failed" if !*v.IsError && v.Subtype == "success" { kind = "turn.completed" } } return []provider.Event{{SessionID: v.Session, RequestID: v.Request, Kind: kind, Payload: bytes.Clone(raw)}}, nil } func uniqueJSON(raw []byte) bool { d := json.NewDecoder(bytes.NewReader(raw)) d.UseNumber() var value func() bool value = func() bool { token, e := d.Token() if e != nil { return false } delim, ok := token.(json.Delim) if !ok { return true } switch delim { case '{': seen := map[string]bool{} for d.More() { k, e := d.Token() if e != nil { return false } s, ok := k.(string) if !ok || seen[s] { return false } seen[s] = true if !value() { return false } } end, e := d.Token() return e == nil && end == json.Delim('}') case '[': for d.More() { if !value() { return false } } end, e := d.Token() return e == nil && end == json.Delim(']') } return false } if !value() { return false } _, e := d.Token() return e == io.EOF } func userEnvelope(session, prompt string) ([]byte, error) { if session == "" || prompt == "" { return nil, errProtocol } raw, e := json.Marshal(struct { Type string `json:"type"` Message struct { Role string `json:"role"` Content string `json:"content"` } `json:"message"` Session string `json:"session_id"` Parent *string `json:"parent_tool_use_id"` }{Type: "user", Message: struct { Role string `json:"role"` Content string `json:"content"` }{"user", prompt}, Session: session}) if e != nil || len(raw) > MaxFrameBytes { return nil, errProtocol } return append(raw, '\n'), nil } // UserEnvelope is one stream-json user frame. func UserEnvelope(session, prompt string) ([]byte, error) { return userEnvelope(session, prompt) } // MaxUserFrameBytes bounds a user frame that carries images: five model // images of at most 1.5 MB each, base64, and the text. const MaxUserFrameBytes = 12 << 20 // Image is one image for the model: its media type and bytes. type Image struct { MediaType string Data []byte } // UserContent is one stream-json user frame with the text first and each // image as an image content block (source base64), as the Agent SDK's // streaming input sends them. Without images it is UserEnvelope. func UserContent(session, prompt string, images []Image) ([]byte, error) { if len(images) == 0 { return userEnvelope(session, prompt) } if session == "" || prompt == "" { return nil, errProtocol } type source struct { Type string `json:"type"` MediaType string `json:"media_type"` Data []byte `json:"data"` } type block struct { Type string `json:"type"` Text string `json:"text,omitempty"` Source *source `json:"source,omitempty"` } content := []block{{Type: "text", Text: prompt}} for _, im := range images { switch im.MediaType { case "image/png", "image/jpeg", "image/gif", "image/webp": default: return nil, errProtocol } content = append(content, block{Type: "image", Source: &source{Type: "base64", MediaType: im.MediaType, Data: im.Data}}) } raw, e := json.Marshal(struct { Type string `json:"type"` Message struct { Role string `json:"role"` Content []block `json:"content"` } `json:"message"` Session string `json:"session_id"` Parent *string `json:"parent_tool_use_id"` }{Type: "user", Message: struct { Role string `json:"role"` Content []block `json:"content"` }{"user", content}, Session: session}) if e != nil || len(raw) > MaxUserFrameBytes { return nil, errProtocol } return append(raw, '\n'), nil } // StreamText returns the text of a stream_event text delta. func StreamText(raw []byte) (string, bool) { var v struct { Event struct { Type string `json:"type"` Delta struct { Type string `json:"type"` Text string `json:"text"` } `json:"delta"` } `json:"event"` } if json.Unmarshal(raw, &v) != nil || v.Event.Type != "content_block_delta" || v.Event.Delta.Type != "text_delta" { return "", false } return v.Event.Delta.Text, v.Event.Delta.Text != "" } // Result is the end of one turn. type Result struct { Text string InputTokens, OutputTokens int64 // CacheRead and CacheCreation are the prompt-cache counts; Model is // the model that answered most of the turn (modelUsage's largest). CacheRead, CacheCreation int64 Model string Failed bool } // ParseResult reads a result frame. Provider error text is never surfaced. func ParseResult(raw []byte) (Result, bool) { var v struct { Type string `json:"type"` Subtype string `json:"subtype"` IsError *bool `json:"is_error"` Result string `json:"result"` Usage struct { Input int64 `json:"input_tokens"` Output int64 `json:"output_tokens"` CacheRead int64 `json:"cache_read_input_tokens"` CacheCreation int64 `json:"cache_creation_input_tokens"` } `json:"usage"` Models map[string]struct { Output int64 `json:"outputTokens"` } `json:"modelUsage"` } if json.Unmarshal(raw, &v) != nil || v.Type != "result" || v.IsError == nil { return Result{}, false } r := Result{InputTokens: v.Usage.Input, OutputTokens: v.Usage.Output, CacheRead: v.Usage.CacheRead, CacheCreation: v.Usage.CacheCreation, Failed: *v.IsError || v.Subtype != "success"} most := int64(-1) for name, m := range v.Models { if m.Output > most || m.Output == most && name < r.Model { r.Model, most = name, m.Output } } if !r.Failed { r.Text = v.Result } return r, true }