1use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, PartialEq)]
8#[serde(tag = "role", rename_all = "lowercase")]
9pub enum Message {
10 User {
11 content: Vec<ContentBlock>,
12 },
13 Assistant {
14 content: Vec<ContentBlock>,
15 #[serde(skip_serializing_if = "Option::is_none", default)]
16 stop_reason: Option<StopReason>,
17 #[serde(skip_serializing_if = "Option::is_none", default)]
18 model: Option<String>,
19 },
20 System {
22 content: String,
23 kind: SystemKind,
24 },
25}
26
27#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
28#[serde(rename_all = "lowercase")]
29pub enum Role {
30 User,
31 Assistant,
32}
33
34#[derive(Debug, Clone, Copy, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
35#[serde(rename_all = "snake_case")]
36pub enum SystemKind {
37 LocalCommand,
38 Reminder,
39 Notice,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, PartialEq)]
46#[serde(tag = "type", rename_all = "snake_case")]
47pub enum ContentBlock {
48 Text {
49 text: String,
50 #[serde(skip_serializing_if = "Option::is_none", default)]
51 cache_control: Option<serde_json::Value>,
52 },
53 Image {
54 source: ImageSource,
55 },
56 Document {
57 source: ImageSource,
58 #[serde(skip_serializing_if = "Option::is_none", default)]
59 title: Option<String>,
60 },
61 ToolUse {
62 id: String,
63 name: String,
64 input: serde_json::Value,
65 },
66 ToolResult {
67 tool_use_id: String,
68 content: ToolResultContent,
70 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
71 is_error: bool,
72 },
73 Thinking {
74 thinking: String,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 signature: Option<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
80 provider: Option<String>,
81 },
82 RedactedThinking {
83 data: String,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 provider: Option<String>,
86 },
87 #[serde(rename = "cache_edits")]
92 CacheEdits {
93 cache_edits: Vec<CacheEdit>,
94 },
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, PartialEq)]
98#[serde(tag = "type", rename_all = "snake_case")]
99pub enum ImageSource {
100 Base64 { media_type: String, data: String },
101 Url { url: String },
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, PartialEq)]
108#[serde(untagged)]
109pub enum ToolResultContent {
110 Text(String),
111 Blocks(Vec<ContentBlock>),
112}
113
114impl ToolResultContent {
115 pub fn text(s: impl Into<String>) -> Self {
117 Self::Text(s.into())
118 }
119 pub fn is_empty(&self) -> bool {
121 match self {
122 Self::Text(s) => s.is_empty(),
123 Self::Blocks(b) => b.is_empty(),
124 }
125 }
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, PartialEq)]
131#[serde(tag = "type", rename_all = "snake_case")]
132pub enum CacheEdit {
133 DeleteToolResult { tool_use_id: String },
134}
135
136#[derive(Debug, Clone, Copy, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
138#[serde(rename_all = "snake_case")]
139pub enum StopReason {
140 EndTurn,
141 MaxTokens,
142 ToolUse,
143 StopSequence,
144 PauseTurn,
145 MaxTurns,
148 #[serde(other)]
150 Unknown,
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156 use serde_json::json;
157
158 #[test]
159 fn user_text_roundtrip() {
160 let m = Message::User {
161 content: vec![ContentBlock::Text {
162 text: "hi".into(),
163 cache_control: None,
164 }],
165 };
166 let s = serde_json::to_value(&m).unwrap();
167 assert_eq!(s["role"], "user");
168 assert_eq!(s["content"][0]["type"], "text");
169 let back: Message = serde_json::from_value(s).unwrap();
170 assert_eq!(m, back);
171 }
172
173 #[test]
174 fn assistant_with_tool_use() {
175 let m = Message::Assistant {
176 content: vec![ContentBlock::ToolUse {
177 id: "toolu_01".into(),
178 name: "Bash".into(),
179 input: json!({"command": "ls"}),
180 }],
181 stop_reason: Some(StopReason::ToolUse),
182 model: Some("claude-sonnet-4-6".into()),
183 };
184 let s = serde_json::to_string(&m).unwrap();
185 let back: Message = serde_json::from_str(&s).unwrap();
186 assert_eq!(m, back);
187 }
188
189 #[test]
190 fn tool_result_content_string_form() {
191 let v = json!({
192 "type": "tool_result",
193 "tool_use_id": "toolu_01",
194 "content": "hello stdout",
195 });
196 let block: ContentBlock = serde_json::from_value(v).unwrap();
197 match block {
198 ContentBlock::ToolResult {
199 content, is_error, ..
200 } => {
201 assert_eq!(content, ToolResultContent::Text("hello stdout".into()));
202 assert!(!is_error);
203 }
204 _ => panic!("wrong variant"),
205 }
206 }
207
208 #[test]
209 fn tool_result_content_blocks_form() {
210 let v = json!({
211 "type": "tool_result",
212 "tool_use_id": "toolu_01",
213 "content": [{"type":"text","text":"a"}, {"type":"text","text":"b"}],
214 "is_error": true,
215 });
216 let block: ContentBlock = serde_json::from_value(v).unwrap();
217 match block {
218 ContentBlock::ToolResult {
219 content, is_error, ..
220 } => {
221 assert!(matches!(content, ToolResultContent::Blocks(ref v) if v.len() == 2));
222 assert!(is_error);
223 }
224 _ => panic!("wrong variant"),
225 }
226 }
227
228 #[test]
229 fn unknown_stop_reason_does_not_break() {
230 let v = json!("a_new_reason_anthropic_invented");
231 let r: StopReason = serde_json::from_value(v).unwrap();
232 assert_eq!(r, StopReason::Unknown);
233 }
234
235 #[test]
236 fn system_message_does_not_have_role_lowercase_collision() {
237 let m = Message::System {
238 content: "compacted".into(),
239 kind: SystemKind::Notice,
240 };
241 let s = serde_json::to_value(&m).unwrap();
242 assert_eq!(s["role"], "system");
243 assert_eq!(s["kind"], "notice");
244 }
245
246 #[test]
247 fn stop_reason_known_variants_roundtrip() {
248 for reason in [
249 StopReason::EndTurn,
250 StopReason::MaxTokens,
251 StopReason::ToolUse,
252 StopReason::StopSequence,
253 StopReason::PauseTurn,
254 StopReason::MaxTurns,
255 ] {
256 let json = serde_json::to_value(reason).unwrap();
257 let back: StopReason = serde_json::from_value(json).unwrap();
258 assert_eq!(reason, back);
259 }
260 assert_eq!(
261 serde_json::to_value(StopReason::MaxTurns).unwrap(),
262 "max_turns",
263 "the name the engine ends a turn with"
264 );
265 }
266
267 #[test]
268 fn cache_control_text_block_roundtrip() {
269 let block = ContentBlock::Text {
270 text: "cached prefix".into(),
271 cache_control: Some(serde_json::json!({"type": "ephemeral"})),
272 };
273 let json = serde_json::to_value(&block).unwrap();
274 assert_eq!(json["type"], "text");
275 assert_eq!(json["cache_control"]["type"], "ephemeral");
276 let back: ContentBlock = serde_json::from_value(json).unwrap();
277 assert_eq!(block, back);
278 }
279
280 #[test]
281 fn cache_control_none_omitted_from_json() {
282 let block = ContentBlock::Text {
283 text: "no cache".into(),
284 cache_control: None,
285 };
286 let json = serde_json::to_value(&block).unwrap();
287 assert!(json.get("cache_control").is_none());
288 }
289
290 #[test]
291 fn image_base64_roundtrip() {
292 let block = ContentBlock::Image {
293 source: ImageSource::Base64 {
294 media_type: "image/png".into(),
295 data: "iVBORw0KGgo=".into(),
296 },
297 };
298 let json = serde_json::to_value(&block).unwrap();
299 assert_eq!(json["type"], "image");
300 assert_eq!(json["source"]["type"], "base64");
301 let back: ContentBlock = serde_json::from_value(json).unwrap();
302 assert_eq!(block, back);
303 }
304
305 #[test]
306 fn image_url_roundtrip() {
307 let block = ContentBlock::Image {
308 source: ImageSource::Url {
309 url: "https://example.com/img.png".into(),
310 },
311 };
312 let json = serde_json::to_string(&block).unwrap();
313 let back: ContentBlock = serde_json::from_str(&json).unwrap();
314 assert_eq!(block, back);
315 }
316
317 #[test]
318 fn thinking_block_roundtrip() {
319 let block = ContentBlock::Thinking {
320 thinking: "Let me think...".into(),
321 signature: Some("sig_abc123".into()),
322 provider: None,
323 };
324 let json = serde_json::to_string(&block).unwrap();
325 let back: ContentBlock = serde_json::from_str(&json).unwrap();
326 assert_eq!(block, back);
327 }
328
329 #[test]
330 fn unsigned_thinking_has_no_signature_key_and_reads_back() {
331 let block = ContentBlock::Thinking {
332 thinking: "reasoning".into(),
333 signature: None,
334 provider: None,
335 };
336 let json = serde_json::to_value(&block).unwrap();
337 assert_eq!(
338 json,
339 serde_json::json!({"type": "thinking", "thinking": "reasoning"})
340 );
341 let back: ContentBlock = serde_json::from_value(json).unwrap();
342 assert_eq!(block, back);
343 }
344
345 #[test]
346 fn redacted_thinking_block_roundtrip() {
347 let block = ContentBlock::RedactedThinking {
348 data: "redacted_data".into(),
349 provider: None,
350 };
351 let json = serde_json::to_string(&block).unwrap();
352 let back: ContentBlock = serde_json::from_str(&json).unwrap();
353 assert_eq!(block, back);
354 }
355
356 #[test]
357 fn role_serialization_user() {
358 assert_eq!(
359 serde_json::to_value(Role::User).unwrap(),
360 serde_json::json!("user")
361 );
362 }
363
364 #[test]
365 fn role_serialization_assistant() {
366 assert_eq!(
367 serde_json::to_value(Role::Assistant).unwrap(),
368 serde_json::json!("assistant")
369 );
370 }
371
372 #[test]
373 fn tool_result_content_is_empty() {
374 assert!(ToolResultContent::Text("".into()).is_empty());
375 assert!(ToolResultContent::Blocks(vec![]).is_empty());
376 assert!(!ToolResultContent::Text("hello".into()).is_empty());
377 assert!(!ToolResultContent::Blocks(vec![ContentBlock::Text {
378 text: "x".into(),
379 cache_control: None,
380 }])
381 .is_empty());
382 }
383
384 #[test]
385 fn system_kind_serialization() {
386 assert_eq!(
387 serde_json::to_value(SystemKind::LocalCommand).unwrap(),
388 serde_json::json!("local_command")
389 );
390 assert_eq!(
391 serde_json::to_value(SystemKind::Reminder).unwrap(),
392 serde_json::json!("reminder")
393 );
394 assert_eq!(
395 serde_json::to_value(SystemKind::Notice).unwrap(),
396 serde_json::json!("notice")
397 );
398 }
399}