package codex import ( "bytes" "encoding/json" "io" "amadan.net/oficina/equipo/internal/runner/provider" ) const MaxFrameBytes = 1024 * 1024 const errProtocol provider.Error = "codex_protocol_rejected" type envelope struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` Result json.RawMessage `json:"result"` Error json.RawMessage `json:"error"` } func parse(raw []byte) (envelope, error) { var v envelope if len(raw) == 0 || len(raw) > MaxFrameBytes || !uniqueJSON(raw) || json.Unmarshal(raw, &v) != nil { return v, errProtocol } if len(v.ID) > 0 { var s string var n int64 if json.Unmarshal(v.ID, &s) != nil && json.Unmarshal(v.ID, &n) != nil { return v, errProtocol } if bytes.Equal(v.ID, []byte("null")) { return v, errProtocol } } if v.Method != "" { if len(v.Result) > 0 || len(v.Error) > 0 || len(v.Params) == 0 { return v, errProtocol } } else if len(v.ID) == 0 || (len(v.Result) == 0) == (len(v.Error) == 0) { return v, errProtocol } return v, nil } // Decode retains the complete frame, including provider IDs and usage totals. func Decode(raw []byte) ([]provider.Event, error) { v, e := parse(raw) if e != nil { return nil, e } if v.Method == "deprecationNotice" { if !pinnedDeprecation(v) { return nil, errProtocol } return nil, nil } if v.Method == "account/rateLimits/updated" { var params map[string]json.RawMessage var limits map[string]json.RawMessage if len(v.ID) != 0 || json.Unmarshal(v.Params, ¶ms) != nil || len(params) != 1 || json.Unmarshal(params["rateLimits"], &limits) != nil || limits == nil { return nil, errProtocol } // Global subscription telemetry has no thread or turn to journal as an event. // The durable capture still retains the frame; account/updated stays fenced. return nil, nil } if v.Method == "" || disabledRemoteControl(v) { return nil, nil } var p struct { ConversationID string `json:"conversationId"` ThreadID string `json:"threadId"` TurnID string `json:"turnId"` Thread struct{ ID string } Turn struct{ ID, Status string } Item struct { Type, ID, Delivery string Questions json.RawMessage } } if json.Unmarshal(v.Params, &p) != nil { return nil, errProtocol } if p.ThreadID == "" { p.ThreadID = p.Thread.ID } if (v.Method == "execCommandApproval" || v.Method == "applyPatchApproval") && p.ThreadID == "" { p.ThreadID = p.ConversationID } if p.TurnID == "" { p.TurnID = p.Turn.ID } switch v.Method { case "turn/started", "turn/completed", "thread/tokenUsage/updated", "item/started", "item/completed", "item/agentMessage/delta", "item/commandExecution/outputDelta": if p.ThreadID == "" || p.TurnID == "" { return nil, errProtocol } } kind := v.Method switch v.Method { case "thread/started": kind = "session.init" case "turn/started": kind = "turn.started" case "turn/completed": if p.Turn.ID == "" || p.ThreadID == "" { return nil, errProtocol } switch p.Turn.Status { case "completed": kind = "turn.completed" case "failed", "interrupted": kind = "turn.failed" default: return nil, errProtocol } case "thread/tokenUsage/updated": kind = "usage" case "item/agentMessage/delta": kind = "message.delta" case "item/commandExecution/outputDelta": kind = "tool.output" case "item/started", "item/completed": if p.Item.Type == "commandExecution" || p.Item.Type == "dynamicToolCall" || p.Item.Type == "mcpToolCall" || p.Item.Type == "fileChange" { if v.Method == "item/started" { kind = "tool.started" } else { kind = "tool.completed" } } } if len(v.ID) > 0 { kind = "request" } request := "" if len(v.ID) > 0 { request = string(v.ID) } // JSON preserves string versus numeric server IDs. if v.Method == "item/completed" && p.Item.Type == "agentMessage" && p.Item.Delivery == "async" && len(p.Item.Questions) > 0 && string(p.Item.Questions) != "null" { if p.Item.ID == "" { return nil, errProtocol } kind = "request" request = "async:" + p.Item.ID } return []provider.Event{{SessionID: p.ThreadID, TurnID: p.TurnID, RequestID: 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 disabledRemoteControl(v envelope) bool { var p struct{ Status string } return v.Method == "remoteControl/status/changed" && len(v.ID) == 0 && json.Unmarshal(v.Params, &p) == nil && p.Status == "disabled" }