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