| 1 | //! The one normalized stream-event format both the `sse` and `events` |
| 2 | //! families speak. |
| 3 | //! |
| 4 | //! It is exactly the serde shape `codewhale_models::StreamEvent` already |
| 5 | //! deserializes (Anthropic-style `{"type": "content_block_delta", ...}`), so a |
| 6 | //! scripted provider script and a parser golden are the same language and a |
| 7 | //! TypeScript implementation needs no Rust type to read either. `StreamEvent` |
| 8 | //! is `Deserialize`-only; this module is its serializer, and |
| 9 | //! [`round_trips`] proves the two directions agree for every golden line. |
| 10 | |
| 11 | use codewhale_models::{ContentBlockStart, Delta, StreamEvent}; |
| 12 | use serde_json::{Value, json}; |
| 13 | |
| 14 | pub(super) fn to_json(event: &StreamEvent) -> Value { |
| 15 | match event { |
| 16 | StreamEvent::ToolProjectionWarning { |
| 17 | provider, |
| 18 | omitted_tool_names, |
| 19 | omitted_tool_count, |
| 20 | } => json!({ |
| 21 | "type": "tool_projection_warning", |
| 22 | "provider": provider, |
| 23 | "omitted_tool_names": omitted_tool_names, |
| 24 | "omitted_tool_count": omitted_tool_count, |
| 25 | }), |
| 26 | StreamEvent::MessageStart { message } => json!({ |
| 27 | "type": "message_start", |
| 28 | "message": serde_json::to_value(message).expect("MessageResponse serializes"), |
| 29 | }), |
| 30 | StreamEvent::ContentBlockStart { |
| 31 | index, |
| 32 | content_block, |
| 33 | } => json!({ |
| 34 | "type": "content_block_start", |
| 35 | "index": index, |
| 36 | "content_block": block_start_json(content_block), |
| 37 | }), |
| 38 | StreamEvent::ContentBlockDelta { index, delta } => json!({ |
| 39 | "type": "content_block_delta", |
| 40 | "index": index, |
| 41 | "delta": delta_json(delta), |
| 42 | }), |
| 43 | StreamEvent::ContentBlockStop { index } => json!({ |
| 44 | "type": "content_block_stop", |
| 45 | "index": index, |
| 46 | }), |
| 47 | StreamEvent::MessageDelta { delta, usage } => { |
| 48 | let mut delta_json = json!({ |
| 49 | "stop_reason": delta.stop_reason, |
| 50 | "stop_sequence": delta.stop_sequence, |
| 51 | }); |
| 52 | if let Some(title) = &delta.title { |
| 53 | delta_json["title"] = json!(title); |
| 54 | } |
| 55 | if let Some(stop_details) = &delta.stop_details { |
| 56 | delta_json["stop_details"] = stop_details.clone(); |
| 57 | } |
| 58 | if let Some(refusal) = &delta.refusal { |
| 59 | delta_json["refusal"] = json!(refusal); |
| 60 | } |
| 61 | let mut value = json!({ |
| 62 | "type": "message_delta", |
| 63 | "delta": delta_json, |
| 64 | }); |
| 65 | if let Some(usage) = usage { |
| 66 | value["usage"] = serde_json::to_value(usage).expect("Usage serializes"); |
| 67 | } |
| 68 | value |
| 69 | } |
| 70 | StreamEvent::MessageStop => json!({ "type": "message_stop" }), |
| 71 | StreamEvent::Ping => json!({ "type": "ping" }), |
| 72 | StreamEvent::Error { error } => json!({ "type": "error", "error": error }), |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn block_start_json(block: &ContentBlockStart) -> Value { |
| 77 | match block { |
| 78 | ContentBlockStart::Text { text } => json!({ "type": "text", "text": text }), |
| 79 | ContentBlockStart::Thinking { thinking } => { |
| 80 | json!({ "type": "thinking", "thinking": thinking }) |
| 81 | } |
| 82 | ContentBlockStart::RedactedThinking { data } => { |
| 83 | json!({ "type": "redacted_thinking", "data": data }) |
| 84 | } |
| 85 | ContentBlockStart::ToolUse { |
| 86 | id, |
| 87 | name, |
| 88 | input, |
| 89 | caller, |
| 90 | thought_signature, |
| 91 | } => { |
| 92 | let mut value = json!({ |
| 93 | "type": "tool_use", |
| 94 | "id": id, |
| 95 | "name": name, |
| 96 | "input": input, |
| 97 | }); |
| 98 | if let Some(caller) = caller { |
| 99 | value["caller"] = serde_json::to_value(caller).expect("ToolCaller serializes"); |
| 100 | } |
| 101 | if let Some(signature) = thought_signature { |
| 102 | value["thought_signature"] = json!(signature); |
| 103 | } |
| 104 | value |
| 105 | } |
| 106 | ContentBlockStart::ServerToolUse { |
| 107 | id, |
| 108 | name, |
| 109 | input, |
| 110 | kind, |
| 111 | caller, |
| 112 | } => { |
| 113 | let mut value = json!({ |
| 114 | "type": "server_tool_use", |
| 115 | "id": id, |
| 116 | "name": name, |
| 117 | "input": input, |
| 118 | }); |
| 119 | if let Some(kind) = kind { |
| 120 | value["kind"] = json!(kind); |
| 121 | } |
| 122 | if let Some(caller) = caller { |
| 123 | value["caller"] = serde_json::to_value(caller).expect("ToolCaller serializes"); |
| 124 | } |
| 125 | value |
| 126 | } |
| 127 | ContentBlockStart::WebSearchToolResult { |
| 128 | tool_use_id, |
| 129 | content, |
| 130 | kind, |
| 131 | } => { |
| 132 | let mut value = json!({ |
| 133 | "type": "web_search_tool_result", |
| 134 | "tool_use_id": tool_use_id, |
| 135 | "content": content, |
| 136 | }); |
| 137 | if let Some(kind) = kind { |
| 138 | value["kind"] = json!(kind); |
| 139 | } |
| 140 | value |
| 141 | } |
| 142 | ContentBlockStart::WebFetchToolResult { |
| 143 | tool_use_id, |
| 144 | content, |
| 145 | kind, |
| 146 | signature, |
| 147 | } => { |
| 148 | let mut value = json!({ |
| 149 | "type": "web_fetch_tool_result", |
| 150 | "tool_use_id": tool_use_id, |
| 151 | "content": content, |
| 152 | }); |
| 153 | if let Some(kind) = kind { |
| 154 | value["kind"] = json!(kind); |
| 155 | } |
| 156 | if let Some(signature) = signature { |
| 157 | value["signature"] = json!(signature); |
| 158 | } |
| 159 | value |
| 160 | } |
| 161 | ContentBlockStart::WebSearchCall { |
| 162 | id, |
| 163 | status, |
| 164 | kind, |
| 165 | action, |
| 166 | } => json!({ |
| 167 | "type": "web_search_call", |
| 168 | "id": id, |
| 169 | "status": status, |
| 170 | "kind": kind, |
| 171 | "action": action, |
| 172 | }), |
| 173 | ContentBlockStart::ServerToolCalls { steps } => json!({ |
| 174 | "type": "server_tool_calls", |
| 175 | "steps": steps, |
| 176 | }), |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | fn delta_json(delta: &Delta) -> Value { |
| 181 | match delta { |
| 182 | Delta::TextDelta { text } => json!({ "type": "text_delta", "text": text }), |
| 183 | Delta::ThinkingDelta { thinking } => { |
| 184 | json!({ "type": "thinking_delta", "thinking": thinking }) |
| 185 | } |
| 186 | Delta::InputJsonDelta { partial_json } => { |
| 187 | json!({ "type": "input_json_delta", "partial_json": partial_json }) |
| 188 | } |
| 189 | Delta::ToolCallIdDelta { id } => json!({ "type": "tool_call_id_delta", "id": id }), |
| 190 | Delta::SignatureDelta { signature } => { |
| 191 | json!({ "type": "signature_delta", "signature": signature }) |
| 192 | } |
| 193 | Delta::ThoughtSignatureDelta { thought_signature } => { |
| 194 | json!({ "type": "thought_signature_delta", "thought_signature": thought_signature }) |
| 195 | } |
| 196 | Delta::ReasoningStateDelta { state } => json!({ |
| 197 | "type": "reasoning_state_delta", |
| 198 | "state": serde_json::to_value(state).expect("OpaqueReasoningState serializes"), |
| 199 | }), |
| 200 | Delta::CitationsDelta { citation } => json!({ |
| 201 | "type": "citations_delta", |
| 202 | "citation": citation, |
| 203 | }), |
| 204 | Delta::RefusalDelta { refusal } => json!({ |
| 205 | "type": "refusal_delta", |
| 206 | "refusal": refusal, |
| 207 | }), |
| 208 | Delta::WebSearchCallDelta { |
| 209 | status, |
| 210 | kind, |
| 211 | action, |
| 212 | sources, |
| 213 | page, |
| 214 | signature, |
| 215 | error, |
| 216 | } => json!({ |
| 217 | "type": "web_search_call_delta", |
| 218 | "status": status, |
| 219 | "kind": kind, |
| 220 | "action": action, |
| 221 | "sources": sources, |
| 222 | "page": page, |
| 223 | "signature": signature, |
| 224 | "error": error, |
| 225 | }), |
| 226 | Delta::ServerToolCallsDelta { steps } => json!({ |
| 227 | "type": "server_tool_calls_delta", |
| 228 | "steps": steps, |
| 229 | }), |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | pub(super) fn from_json(value: &Value) -> anyhow::Result<StreamEvent> { |
| 234 | Ok(serde_json::from_value(value.clone())?) |
| 235 | } |
| 236 | |
| 237 | /// `value` deserializes into a `StreamEvent` that serializes back to itself. |
| 238 | pub(super) fn round_trips(value: &Value) -> Result<(), String> { |
| 239 | let event = from_json(value).map_err(|error| format!("{value} does not parse: {error}"))?; |
| 240 | let back = to_json(&event); |
| 241 | if super::golden::canonical(&back) == super::golden::canonical(value) { |
| 242 | Ok(()) |
| 243 | } else { |
| 244 | Err(format!("{value} round-trips to {back}")) |
| 245 | } |
| 246 | } |
| 247 |