Skip to main content

codewhale_protocol/
request.rs

1//! Provider-neutral outbound model-request boundary.
2//!
3//! The request DTOs in this module are consumed by the TUI transport today
4//! and are intentionally free of terminal, HTTP, or provider-client state.
5//! Keeping the logical request in `codewhale-protocol` lets a headless session
6//! prepare the same serializable value before the existing TUI client applies
7//! provider-specific wire shaping.
8
9use serde::{Deserialize, Serialize};
10
11use crate::role::Role;
12
13#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
14pub struct SafetyCheckConfig {
15    pub level: String,
16}
17
18#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
19pub struct ConversationTitleConfig {
20    pub enabled: bool,
21}
22
23/// Request payload handed to the model-client preparation seam.
24#[derive(Debug, Serialize, Deserialize, Clone)]
25pub struct MessageRequest {
26    pub model: String,
27    pub messages: Vec<Message>,
28    pub max_tokens: u32,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub system: Option<SystemPrompt>,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub tools: Option<Vec<Tool>>,
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub tool_choice: Option<serde_json::Value>,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub metadata: Option<serde_json::Value>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub thinking: Option<serde_json::Value>,
39    /// DeepSeek reasoning-effort tier: "off" | "low" | "medium" | "high" | "max".
40    /// Translated by the client into DeepSeek's `reasoning_effort` + `thinking` fields.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub reasoning_effort: Option<String>,
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub stream: Option<bool>,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub temperature: Option<f32>,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub top_p: Option<f32>,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub safety_check: Option<SafetyCheckConfig>,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub title: Option<ConversationTitleConfig>,
53}
54
55/// Inputs that distinguish a primary agent-turn request.
56///
57/// Provider-neutral defaults (`stream = true`, no metadata, no provider-side
58/// thinking object, and no sampling overrides) are applied once by
59/// [`prepare_primary_turn_request`]. Both the production turn loop and its
60/// read-only preview use this input so those defaults cannot drift.
61#[derive(Debug, Clone)]
62pub struct PrimaryTurnRequest {
63    pub model: String,
64    pub messages: Vec<Message>,
65    pub max_tokens: u32,
66    pub system: Option<SystemPrompt>,
67    pub tools: Option<Vec<Tool>>,
68    pub tool_choice: Option<serde_json::Value>,
69    pub reasoning_effort: Option<String>,
70}
71
72/// Prepare the provider-neutral request for a primary agent turn.
73///
74/// This function performs no I/O and no provider-specific transformation.
75/// The existing client transport remains responsible for secret redaction,
76/// protocol binding, dialect shaping, and endpoint selection.
77#[must_use]
78pub fn prepare_primary_turn_request(input: PrimaryTurnRequest) -> MessageRequest {
79    MessageRequest {
80        model: input.model,
81        messages: input.messages,
82        max_tokens: input.max_tokens,
83        system: input.system,
84        tools: input.tools,
85        tool_choice: input.tool_choice,
86        metadata: None,
87        thinking: None,
88        reasoning_effort: input.reasoning_effort,
89        stream: Some(true),
90        temperature: None,
91        top_p: None,
92        safety_check: None,
93        title: None,
94    }
95}
96
97/// System prompt representation (plain text or structured blocks).
98#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
99#[serde(untagged)]
100pub enum SystemPrompt {
101    Text(String),
102    Blocks(Vec<SystemBlock>),
103}
104
105/// A structured system prompt block.
106#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
107pub struct SystemBlock {
108    #[serde(rename = "type")]
109    pub block_type: String,
110    pub text: String,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub cache_control: Option<CacheControl>,
113}
114
115/// OpenAI-compatible image URL payload inside a multimodal message.
116#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
117pub struct ImageUrlContent {
118    pub url: String,
119}
120
121/// A chat message with role and content blocks.
122///
123/// `role` is a closed [`Role`] rather than a free-form string. It serializes
124/// to exactly the bytes the `String` field produced, so persisted sessions
125/// need no schema bump, and an unfamiliar role from a newer build loads as
126/// [`Role::Unrecognized`] instead of failing the session.
127#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
128pub struct Message {
129    pub role: Role,
130    pub content: Vec<ContentBlock>,
131}
132
133impl Message {
134    pub fn interrupted_assistant(text: &str) -> Self {
135        Self {
136            role: Role::InterruptedAssistant,
137            content: vec![ContentBlock::Text {
138                text: text.to_owned(),
139                cache_control: None,
140            }],
141        }
142    }
143}
144
145/// Internal role used for assistant text that was visible before a turn was interrupted.
146pub const INTERRUPTED_ASSISTANT_ROLE: &str = "assistant_interrupted";
147/// Prefix attached to interrupted assistant output when it is replayed as context.
148pub const INTERRUPTED_ASSISTANT_CONTEXT_PREFIX: &str = "[The following assistant output was interrupted before completion and may be incomplete or wrong]\n";
149
150/// Provider-owned reasoning continuity that is safe to replay only on the
151/// exact originating API and model. The encrypted payload is deliberately
152/// separate from readable [`ContentBlock::Thinking`] text.
153#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
154pub struct OpaqueReasoningState {
155    pub provider: String,
156    pub api: String,
157    pub model: String,
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub id: Option<String>,
160    pub encrypted_content: String,
161}
162
163/// A single content block inside a message.
164#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
165#[serde(tag = "type")]
166pub enum ContentBlock {
167    #[serde(rename = "text")]
168    Text {
169        text: String,
170        #[serde(skip_serializing_if = "Option::is_none")]
171        cache_control: Option<CacheControl>,
172    },
173    #[serde(rename = "image_url")]
174    ImageUrl { image_url: ImageUrlContent },
175    #[serde(rename = "thinking")]
176    Thinking {
177        thinking: String,
178        /// Anthropic signed-thinking signature (#3014). Only populated on the
179        /// native Messages dialect and serde-skipped when absent so OpenAI
180        /// dialects are unaffected. Anthropic rejects tool loops that drop or
181        /// modify signed thinking blocks, so replay this verbatim.
182        #[serde(skip_serializing_if = "Option::is_none", default)]
183        signature: Option<String>,
184        /// Opaque Responses-style continuity. Never synthesize this from the
185        /// readable `thinking` text or carry it across a route/model switch.
186        #[serde(skip_serializing_if = "Option::is_none", default)]
187        state: Option<OpaqueReasoningState>,
188        /// Anthropic `redacted_thinking` payload (`data`): the encrypted
189        /// replacement for a whole thinking block that the provider withheld
190        /// for safety reasons. It must be replayed byte-exact — the API
191        /// decrypts it to restore the turn's reasoning — and is mutually
192        /// exclusive with readable `thinking` text and with `signature`.
193        /// Stored on the same variant (instead of a sibling one) so existing
194        /// sessions and matches keep compiling; the serde field is absent
195        /// for every non-redacted block.
196        #[serde(skip_serializing_if = "Option::is_none", default)]
197        redacted_data: Option<String>,
198    },
199    #[serde(rename = "tool_use")]
200    ToolUse {
201        id: String,
202        name: String,
203        input: serde_json::Value,
204        /// Host-owned execution correlation, distinct from the provider's id.
205        /// Persisted with history; provider adapters project only wire fields.
206        /// Missing identifies legacy/provider-only history, never a new grant.
207        #[serde(default, skip_serializing_if = "Option::is_none")]
208        execution_id: Option<String>,
209        #[serde(skip_serializing_if = "Option::is_none")]
210        caller: Option<ToolCaller>,
211        /// Google thought signature captured from the OpenAI-compat route's
212        /// `extra_content.google.thought_signature` on the tool call. Google
213        /// requires replaying it with the tool result for thinking models;
214        /// skipped on the wire and in storage for every other provider.
215        #[serde(skip_serializing_if = "Option::is_none", default)]
216        thought_signature: Option<String>,
217    },
218    #[serde(rename = "tool_result")]
219    ToolResult {
220        tool_use_id: String,
221        content: String,
222        /// The exact host execution that produced this result, when recorded.
223        #[serde(default, skip_serializing_if = "Option::is_none")]
224        execution_id: Option<String>,
225        #[serde(skip_serializing_if = "Option::is_none")]
226        is_error: Option<bool>,
227        #[serde(skip_serializing_if = "Option::is_none")]
228        content_blocks: Option<Vec<serde_json::Value>>,
229    },
230    #[serde(rename = "server_tool_use")]
231    ServerToolUse {
232        id: String,
233        name: String,
234        input: serde_json::Value,
235        #[serde(default, skip_serializing_if = "Option::is_none")]
236        kind: Option<String>,
237        #[serde(default, skip_serializing_if = "Option::is_none")]
238        caller: Option<ToolCaller>,
239    },
240    #[serde(rename = "tool_search_tool_result")]
241    ToolSearchToolResult {
242        tool_use_id: String,
243        content: serde_json::Value,
244    },
245    #[serde(rename = "code_execution_tool_result")]
246    CodeExecutionToolResult {
247        tool_use_id: String,
248        content: serde_json::Value,
249    },
250    #[serde(rename = "web_search_tool_result")]
251    WebSearchToolResult {
252        tool_use_id: String,
253        content: serde_json::Value,
254        #[serde(default, skip_serializing_if = "Option::is_none")]
255        kind: Option<String>,
256    },
257    #[serde(rename = "web_fetch_tool_result")]
258    WebFetchToolResult {
259        tool_use_id: String,
260        content: serde_json::Value,
261        #[serde(default, skip_serializing_if = "Option::is_none")]
262        kind: Option<String>,
263        #[serde(default, skip_serializing_if = "Option::is_none")]
264        signature: Option<String>,
265    },
266    #[serde(rename = "web_search_call")]
267    WebSearchCall {
268        id: String,
269        status: String,
270        #[serde(default, skip_serializing_if = "Option::is_none")]
271        kind: Option<String>,
272        #[serde(default, skip_serializing_if = "Option::is_none")]
273        action: Option<serde_json::Value>,
274        #[serde(default, skip_serializing_if = "Option::is_none")]
275        sources: Option<serde_json::Value>,
276        #[serde(default, skip_serializing_if = "Option::is_none")]
277        page: Option<serde_json::Value>,
278        #[serde(default, skip_serializing_if = "Option::is_none")]
279        signature: Option<String>,
280        #[serde(default, skip_serializing_if = "Option::is_none")]
281        error: Option<serde_json::Value>,
282    },
283    #[serde(rename = "server_tool_calls")]
284    ServerToolCalls { steps: Vec<serde_json::Value> },
285    #[serde(rename = "file")]
286    File { file_id: String },
287}
288
289/// Identity for pairing host history without conflating a provider's reused
290/// string with a local execution. Legacy identity cannot establish a grant.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
292pub enum ToolCallKey<'a> {
293    Execution(&'a str),
294    LegacyProvider(&'a str),
295}
296
297impl<'a> ToolCallKey<'a> {
298    #[must_use]
299    pub fn as_str(self) -> &'a str {
300        match self {
301            Self::Execution(id) | Self::LegacyProvider(id) => id,
302        }
303    }
304}
305
306impl ContentBlock {
307    /// Pairing identity in persisted host history. An explicit execution id
308    /// never falls back to provider correlation, even if malformed or mismatched.
309    /// Wire adapters must continue using the original id/tool_use_id instead.
310    #[must_use]
311    pub fn tool_call_key(&self) -> Option<ToolCallKey<'_>> {
312        match self {
313            Self::ToolUse {
314                id, execution_id, ..
315            }
316            | Self::ToolResult {
317                tool_use_id: id,
318                execution_id,
319                ..
320            } => Some(
321                execution_id
322                    .as_deref()
323                    .map_or(ToolCallKey::LegacyProvider(id), ToolCallKey::Execution),
324            ),
325            Self::ServerToolUse { id, .. }
326            | Self::WebSearchCall { id, .. }
327            | Self::ToolSearchToolResult {
328                tool_use_id: id, ..
329            }
330            | Self::CodeExecutionToolResult {
331                tool_use_id: id, ..
332            }
333            | Self::WebSearchToolResult {
334                tool_use_id: id, ..
335            }
336            | Self::WebFetchToolResult {
337                tool_use_id: id, ..
338            } => Some(ToolCallKey::LegacyProvider(id)),
339            _ => None,
340        }
341    }
342
343    /// Build readable reasoning with no provider-owned continuity state.
344    #[must_use]
345    pub fn thinking(thinking: impl Into<String>) -> Self {
346        Self::Thinking {
347            thinking: thinking.into(),
348            signature: None,
349            state: None,
350            redacted_data: None,
351        }
352    }
353}
354
355/// Cache control metadata for tool definitions and blocks.
356#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
357pub struct CacheControl {
358    #[serde(rename = "type")]
359    pub cache_type: String,
360}
361
362/// Metadata describing who invoked a tool call.
363#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
364pub struct ToolCaller {
365    #[serde(rename = "type")]
366    pub caller_type: String,
367    #[serde(skip_serializing_if = "Option::is_none")]
368    pub tool_id: Option<String>,
369}
370
371/// Tool definition exposed to the model.
372#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
373pub struct Tool {
374    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
375    pub tool_type: Option<String>,
376    pub name: String,
377    pub description: String,
378    pub input_schema: serde_json::Value,
379    #[serde(skip_serializing_if = "Option::is_none")]
380    pub allowed_callers: Option<Vec<String>>,
381    #[serde(skip_serializing_if = "Option::is_none")]
382    pub defer_loading: Option<bool>,
383    #[serde(skip_serializing_if = "Option::is_none")]
384    pub input_examples: Option<Vec<serde_json::Value>>,
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub strict: Option<bool>,
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub cache_control: Option<CacheControl>,
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394    use serde_json::json;
395
396    #[test]
397    fn redacted_thinking_round_trips_through_persistence_serde() {
398        // Capture shape: the redacted payload rides the thinking variant and
399        // must survive the persisted-session round trip byte-exact.
400        let block = ContentBlock::Thinking {
401            thinking: String::new(),
402            signature: None,
403            state: None,
404            redacted_data: Some("ENC_REDACTED_PAYLOAD".to_string()),
405        };
406        let value = serde_json::to_value(&block).expect("thinking block serializes");
407        assert_eq!(
408            value,
409            json!({
410                "type": "thinking",
411                "thinking": "",
412                "redacted_data": "ENC_REDACTED_PAYLOAD",
413            }),
414            "the redacted payload must be on the persisted wire"
415        );
416        let round: ContentBlock =
417            serde_json::from_value(value).expect("redacted block deserializes");
418        assert_eq!(round, block, "round trip must be lossless");
419    }
420
421    #[test]
422    fn sessions_without_the_redacted_field_deserialize_unchanged() {
423        // A session persisted by an older build carries no `redacted_data`
424        // key; it must load unchanged with the field defaulting to `None`
425        // and must not gain the key on the way back out.
426        let value = json!({
427            "type": "thinking",
428            "thinking": "readable reasoning",
429            "signature": "sig-abc",
430        });
431        let block: ContentBlock =
432            serde_json::from_value(value).expect("legacy thinking block deserializes");
433        match &block {
434            ContentBlock::Thinking {
435                thinking,
436                signature,
437                state,
438                redacted_data,
439            } => {
440                assert_eq!(thinking, "readable reasoning");
441                assert_eq!(signature.as_deref(), Some("sig-abc"));
442                assert!(state.is_none());
443                assert!(redacted_data.is_none());
444            }
445            other => panic!("expected thinking block, got {other:?}"),
446        }
447        let serialized = serde_json::to_value(&block).expect("re-serializes");
448        assert!(
449            serialized.get("redacted_data").is_none(),
450            "a non-redacted block must not gain the serde field: {serialized}"
451        );
452    }
453
454    fn primary_turn() -> PrimaryTurnRequest {
455        PrimaryTurnRequest {
456            model: "deepseek-v4-flash".to_string(),
457            messages: vec![Message {
458                role: Role::User,
459                content: vec![ContentBlock::Text {
460                    text: "inspect the request".to_string(),
461                    cache_control: None,
462                }],
463            }],
464            max_tokens: 4096,
465            system: Some(SystemPrompt::Text("system".to_string())),
466            tools: Some(vec![Tool {
467                tool_type: None,
468                name: "read_file".to_string(),
469                description: "Read a file".to_string(),
470                input_schema: json!({"zeta": 1, "alpha": 2, "type": "object"}),
471                allowed_callers: None,
472                defer_loading: None,
473                input_examples: None,
474                strict: None,
475                cache_control: None,
476            }]),
477            tool_choice: Some(json!({"type": "auto"})),
478            reasoning_effort: Some("high".to_string()),
479        }
480    }
481
482    #[test]
483    fn primary_turn_preparation_has_stable_serialized_bytes() {
484        let first = prepare_primary_turn_request(primary_turn());
485        let second = prepare_primary_turn_request(primary_turn());
486        let first_bytes = serde_json::to_vec(&first).expect("serialize first request");
487        let second_bytes = serde_json::to_vec(&second).expect("serialize second request");
488
489        assert_eq!(first_bytes, second_bytes);
490        assert_eq!(
491            first_bytes,
492            br#"{"model":"deepseek-v4-flash","messages":[{"role":"user","content":[{"type":"text","text":"inspect the request"}]}],"max_tokens":4096,"system":"system","tools":[{"name":"read_file","description":"Read a file","input_schema":{"zeta":1,"alpha":2,"type":"object"}}],"tool_choice":{"type":"auto"},"reasoning_effort":"high","stream":true}"#
493        );
494    }
495
496    #[test]
497    fn persisted_messages_keep_their_pre_typed_role_bytes() {
498        // `Message::role` became a closed `Role` enum. Saved transcripts are
499        // plain JSON with a free-form role string, so the typed field has to
500        // produce byte-identical output and accept every string it used to —
501        // otherwise every session on disk would need a schema bump, and
502        // `session_manager` refuses a session whose schema_version exceeds
503        // CURRENT with no migration ladder to climb back down.
504        let persisted = br#"[{"role":"user","content":[{"type":"text","text":"a"}]},{"role":"assistant","content":[{"type":"text","text":"b"}]},{"role":"system","content":[{"type":"text","text":"c"}]},{"role":"assistant_interrupted","content":[{"type":"text","text":"d"}]},{"role":"developer","content":[{"type":"text","text":"e"}]}]"#;
505        let decoded: Vec<Message> = serde_json::from_slice(persisted).expect("load transcript");
506        assert_eq!(
507            decoded.iter().map(|m| m.role.clone()).collect::<Vec<_>>(),
508            vec![
509                Role::User,
510                Role::Assistant,
511                Role::System,
512                Role::InterruptedAssistant,
513                Role::Developer,
514            ]
515        );
516        assert_eq!(
517            serde_json::to_vec(&decoded).expect("re-save transcript"),
518            persisted.to_vec(),
519            "re-saving a loaded transcript must not change a single byte",
520        );
521    }
522
523    #[test]
524    fn tool_execution_identity_round_trips_without_changing_legacy_bytes() {
525        let legacy = br#"[{"role":"assistant","content":[{"type":"tool_use","id":"wire","name":"read","input":{},"caller":{"type":"code_execution","tool_id":"parent-wire"},"thought_signature":"signature"}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"wire","content":"result"}]}]"#;
526        let mut messages: Vec<Message> = serde_json::from_slice(legacy).unwrap();
527        assert_eq!(serde_json::to_vec(&messages).unwrap(), legacy);
528        for block in messages.iter_mut().flat_map(|message| &mut message.content) {
529            match block {
530                ContentBlock::ToolUse { execution_id, .. }
531                | ContentBlock::ToolResult { execution_id, .. } => {
532                    assert!(execution_id.is_none());
533                    *execution_id = Some("local-execution".to_string());
534                }
535                _ => unreachable!(),
536            }
537        }
538        let persisted = serde_json::to_vec(&messages).unwrap();
539        let restored: Vec<Message> = serde_json::from_slice(&persisted).unwrap();
540        assert_eq!(restored, messages);
541        assert_eq!(
542            restored[0].content[0].tool_call_key(),
543            restored[1].content[0].tool_call_key()
544        );
545        let ContentBlock::ToolUse {
546            id,
547            caller,
548            thought_signature,
549            ..
550        } = &restored[0].content[0]
551        else {
552            unreachable!()
553        };
554        assert_eq!(id, "wire");
555        assert_eq!(
556            caller.as_ref().unwrap().tool_id.as_deref(),
557            Some("parent-wire")
558        );
559        assert_eq!(thought_signature.as_deref(), Some("signature"));
560    }
561
562    #[test]
563    fn tool_history_keys_never_fall_back_or_cross_identity_domains() {
564        let call = |execution_id: Option<&str>| ContentBlock::ToolUse {
565            id: "same-string".to_string(),
566            name: "read".to_string(),
567            input: json!({}),
568            execution_id: execution_id.map(str::to_string),
569            caller: None,
570            thought_signature: None,
571        };
572        let legacy = call(None);
573        let local = call(Some("same-string"));
574        let different = call(Some("other-execution"));
575        let malformed = call(Some(""));
576        assert_eq!(
577            legacy.tool_call_key(),
578            Some(ToolCallKey::LegacyProvider("same-string"))
579        );
580        assert_eq!(
581            local.tool_call_key(),
582            Some(ToolCallKey::Execution("same-string"))
583        );
584        assert_ne!(legacy.tool_call_key(), local.tool_call_key());
585        assert_ne!(local.tool_call_key(), different.tool_call_key());
586        assert_eq!(malformed.tool_call_key(), Some(ToolCallKey::Execution("")));
587        assert_eq!(
588            std::collections::HashSet::from([
589                legacy.tool_call_key().unwrap(),
590                local.tool_call_key().unwrap(),
591            ])
592            .len(),
593            2
594        );
595    }
596
597    #[test]
598    fn primary_turn_preparation_owns_shared_defaults() {
599        let request = prepare_primary_turn_request(primary_turn());
600        assert_eq!(request.stream, Some(true));
601        assert!(request.metadata.is_none());
602        assert!(request.thinking.is_none());
603        assert!(request.temperature.is_none());
604        assert!(request.top_p.is_none());
605        assert!(request.safety_check.is_none());
606        assert!(request.title.is_none());
607    }
608
609    #[test]
610    fn deepseek_chatbot_blocks_and_request_options_round_trip() {
611        let blocks = vec![
612            ContentBlock::ServerToolUse {
613                id: "srv_1".to_string(),
614                name: "deepseek_web_search".to_string(),
615                input: json!({ "query": "rust 2024" }),
616                kind: Some("search".to_string()),
617                caller: Some(ToolCaller {
618                    caller_type: "direct".to_string(),
619                    tool_id: None,
620                }),
621            },
622            ContentBlock::WebSearchToolResult {
623                tool_use_id: "srv_1".to_string(),
624                content: json!([{ "type": "web_search_result_location", "url": "https://example.com" }]),
625                kind: Some("search".to_string()),
626            },
627            ContentBlock::WebFetchToolResult {
628                tool_use_id: "srv_2".to_string(),
629                content: json!({ "type": "web_fetch_result", "url": "https://example.com" }),
630                kind: Some("read_link".to_string()),
631                signature: Some("sig_abc".to_string()),
632            },
633            ContentBlock::WebSearchCall {
634                id: "ws_1".to_string(),
635                status: "completed".to_string(),
636                kind: Some("deep_search".to_string()),
637                action: Some(json!({ "type": "search", "query": "rust" })),
638                sources: Some(json!([{ "url": "https://example.com" }])),
639                page: Some(json!({ "url": "https://example.com" })),
640                signature: Some("sig_ws".to_string()),
641                error: None,
642            },
643            ContentBlock::ServerToolCalls {
644                steps: vec![json!({ "type": "search", "query": "rust" })],
645            },
646            ContentBlock::File {
647                file_id: "file_123".to_string(),
648            },
649        ];
650        assert_eq!(
651            blocks[0].tool_call_key(),
652            Some(ToolCallKey::LegacyProvider("srv_1"))
653        );
654        assert_eq!(
655            blocks[1].tool_call_key(),
656            Some(ToolCallKey::LegacyProvider("srv_1"))
657        );
658        assert_eq!(
659            blocks[2].tool_call_key(),
660            Some(ToolCallKey::LegacyProvider("srv_2"))
661        );
662        assert_eq!(
663            blocks[3].tool_call_key(),
664            Some(ToolCallKey::LegacyProvider("ws_1"))
665        );
666
667        let mut req = prepare_primary_turn_request(primary_turn());
668        req.safety_check = Some(SafetyCheckConfig {
669            level: "high".to_string(),
670        });
671        req.title = Some(ConversationTitleConfig { enabled: true });
672        req.messages = vec![
673            Message {
674                role: Role::LatestReminder,
675                content: vec![ContentBlock::Text {
676                    text: "Respond briefly".to_string(),
677                    cache_control: None,
678                }],
679            },
680            Message {
681                role: Role::User,
682                content: blocks,
683            },
684        ];
685        let encoded = serde_json::to_value(&req).expect("serialize");
686        assert_eq!(encoded["safety_check"]["level"], "high");
687        assert_eq!(encoded["title"]["enabled"], true);
688        let decoded: MessageRequest = serde_json::from_value(encoded).expect("deserialize");
689        assert_eq!(decoded.safety_check, req.safety_check);
690        assert_eq!(decoded.title, req.title);
691        assert_eq!(decoded.messages, req.messages);
692    }
693}