1use serde::{Deserialize, Serialize};
10
11use crate::role::Role;
12
13#[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 #[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#[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#[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#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
83#[serde(untagged)]
84pub enum SystemPrompt {
85 Text(String),
86 Blocks(Vec<SystemBlock>),
87}
88
89#[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#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
101pub struct ImageUrlContent {
102 pub url: String,
103}
104
105#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
112pub struct Message {
113 pub role: Role,
114 pub content: Vec<ContentBlock>,
115}
116
117pub const INTERRUPTED_ASSISTANT_ROLE: &str = "assistant_interrupted";
119pub const INTERRUPTED_ASSISTANT_CONTEXT_PREFIX: &str = "[The following assistant output was interrupted before completion and may be incomplete or wrong]\n";
121
122#[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#[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 #[serde(skip_serializing_if = "Option::is_none", default)]
155 signature: Option<String>,
156 #[serde(skip_serializing_if = "Option::is_none", default)]
159 state: Option<OpaqueReasoningState>,
160 #[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 #[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 #[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 #[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#[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 #[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 #[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#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
281pub struct CacheControl {
282 #[serde(rename = "type")]
283 pub cache_type: String,
284}
285
286#[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#[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 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 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 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}