vtcode-core 0.104.0

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
use crate::llm::provider::{
    AnthropicOptionalStringOverride, AnthropicOptionalU32Override, AnthropicRequestOverrides,
    AnthropicThinkingDisplayOverride, AnthropicThinkingModeOverride, ContentPart, FinishReason,
    LLMRequest, LLMResponse, Message, MessageContent, MessageRole, ParallelToolConfig, ToolCall,
    ToolChoice, ToolDefinition,
};
use crate::llm::providers::anthropic_types::{
    AnthropicOutputConfig, AnthropicOutputFormat, ThinkingConfig, ThinkingDisplay,
};
use crate::llm::providers::common::normalize_reasoning_detail_object;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::sync::Arc;

/// Anthropic Messages API request.
#[derive(Debug, Deserialize, Clone)]
pub struct AnthropicMessagesRequest {
    pub model: String,
    pub max_tokens: u32,
    pub messages: Vec<AnthropicMessage>,
    #[serde(default)]
    pub system: Option<AnthropicSystemPrompt>,
    #[serde(default)]
    pub stream: bool,
    #[serde(default)]
    pub temperature: Option<f32>,
    #[serde(default)]
    pub top_p: Option<f32>,
    #[serde(default)]
    pub top_k: Option<i32>,
    #[serde(default)]
    pub stop_sequences: Option<Vec<String>>,
    #[serde(default)]
    pub tools: Option<Vec<AnthropicTool>>,
    #[serde(default)]
    pub tool_choice: Option<Value>,
    #[serde(default)]
    pub thinking: Option<ThinkingConfig>,
    #[serde(default)]
    pub betas: Option<Vec<String>>,
    #[serde(default)]
    pub context_management: Option<Value>,
    #[serde(default)]
    pub output_config: Option<AnthropicOutputConfig>,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AnthropicMessage {
    pub role: String,
    pub content: AnthropicContent,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum AnthropicContent {
    Text(String),
    Blocks(Vec<AnthropicContentBlock>),
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(tag = "type")]
pub enum AnthropicContentBlock {
    #[serde(rename = "text")]
    Text {
        text: String,
        #[serde(default)]
        citations: Option<Value>,
        #[serde(default)]
        cache_control: Option<Value>,
    },
    #[serde(rename = "image")]
    Image { source: AnthropicImageSource },
    #[serde(rename = "tool_use")]
    ToolUse {
        id: String,
        name: String,
        input: Value,
    },
    #[serde(rename = "tool_result")]
    ToolResult {
        tool_use_id: String,
        content: AnthropicContent,
        is_error: Option<bool>,
    },
    #[serde(rename = "thinking")]
    Thinking {
        thinking: String,
        #[serde(default)]
        signature: Option<String>,
    },
    #[serde(rename = "redacted_thinking")]
    RedactedThinking { data: String },
    #[serde(rename = "server_tool_use")]
    ServerToolUse {
        id: String,
        name: String,
        input: Value,
    },
    #[serde(rename = "container_upload")]
    ContainerUpload { file_id: String },
    #[serde(rename = "code_execution_tool_result")]
    CodeExecutionToolResult { tool_use_id: String, content: Value },
    #[serde(rename = "bash_code_execution_tool_result")]
    BashCodeExecutionToolResult { tool_use_id: String, content: Value },
    #[serde(rename = "text_editor_code_execution_tool_result")]
    TextEditorCodeExecutionToolResult { tool_use_id: String, content: Value },
    #[serde(rename = "web_search_tool_result")]
    WebSearchToolResult { tool_use_id: String, content: Value },
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AnthropicImageSource {
    pub r#type: String,
    pub media_type: String,
    pub data: String,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum AnthropicSystemPrompt {
    Text(String),
    Blocks(Vec<AnthropicContentBlock>),
}

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum AnthropicTool {
    Function {
        name: String,
        description: Option<String>,
        input_schema: Value,
        #[serde(default)]
        input_examples: Option<Vec<Value>>,
        #[serde(default)]
        strict: Option<bool>,
        #[serde(default)]
        allowed_callers: Option<Vec<String>>,
    },
    Native {
        #[serde(rename = "type")]
        tool_type: String,
        name: String,
        #[serde(flatten, default)]
        options: serde_json::Map<String, Value>,
    },
}

#[derive(Debug, Serialize, Clone)]
pub struct AnthropicMessagesResponse {
    pub id: String,
    pub r#type: String,
    pub role: String,
    pub model: String,
    pub content: Vec<AnthropicContentBlock>,
    pub stop_reason: Option<String>,
    pub stop_sequence: Option<String>,
    pub usage: AnthropicUsage,
}

#[derive(Debug, Serialize, Clone)]
pub struct AnthropicUsage {
    pub input_tokens: u32,
    pub output_tokens: u32,
}

#[derive(Debug, Serialize)]
#[serde(tag = "type")]
pub enum AnthropicStreamEvent {
    #[serde(rename = "message_start")]
    MessageStart { message: AnthropicMessagesResponse },
    #[serde(rename = "content_block_start")]
    ContentBlockStart {
        index: u32,
        content_block: AnthropicContentBlock,
    },
    #[serde(rename = "content_block_delta")]
    ContentBlockDelta {
        index: u32,
        delta: AnthropicContentDelta,
    },
    #[serde(rename = "content_block_stop")]
    ContentBlockStop { index: u32 },
    #[serde(rename = "message_delta")]
    MessageDelta {
        delta: AnthropicDelta,
        usage: AnthropicUsage,
    },
    #[serde(rename = "message_stop")]
    MessageStop,
    #[serde(rename = "ping")]
    Ping {},
    #[serde(rename = "error")]
    Error { error: AnthropicError },
}

#[derive(Debug, Serialize)]
#[serde(tag = "type")]
pub enum AnthropicContentDelta {
    #[serde(rename = "text_delta")]
    TextDelta { text: String },
    #[serde(rename = "input_json_delta")]
    InputJsonDelta { partial_json: String },
    #[serde(rename = "thinking_delta")]
    ThinkingDelta { thinking: String },
    #[serde(rename = "signature_delta")]
    SignatureDelta { signature: String },
}

#[derive(Debug, Serialize)]
pub struct AnthropicDelta {
    pub stop_reason: Option<String>,
    pub stop_sequence: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct AnthropicError {
    pub r#type: String,
    pub message: String,
}

#[derive(Default)]
struct ConvertedAnthropicBlocks {
    content_parts: Vec<ContentPart>,
    tool_calls: Vec<ToolCall>,
    reasoning_chunks: Vec<String>,
    reasoning_details: Vec<Value>,
    emitted_messages: Vec<Message>,
}

pub fn convert_anthropic_to_llm_request(request: AnthropicMessagesRequest) -> LLMRequest {
    let (tool_choice, parallel_tool_config) =
        parse_anthropic_tool_choice(request.tool_choice.as_ref());
    let effort = request
        .output_config
        .as_ref()
        .and_then(|config| config.effort.clone());
    let output_format = request.output_config.as_ref().and_then(|config| {
        config
            .format
            .as_ref()
            .map(|AnthropicOutputFormat::JsonSchema { schema }| schema.clone())
    });
    let task_budget_tokens = request
        .output_config
        .as_ref()
        .and_then(|config| config.task_budget.as_ref())
        .map(|budget| budget.total);
    let anthropic_request_overrides = Some(AnthropicRequestOverrides {
        thinking_mode: compatibility_thinking_mode(&request.model, request.thinking.as_ref()),
        thinking_display: compatibility_thinking_display(request.thinking.as_ref()),
        effort: effort
            .as_ref()
            .map(|effort| AnthropicOptionalStringOverride::Explicit(effort.clone()))
            .unwrap_or(AnthropicOptionalStringOverride::Omit),
        task_budget_tokens: task_budget_tokens
            .map(AnthropicOptionalU32Override::Explicit)
            .unwrap_or(AnthropicOptionalU32Override::Omit),
    });

    let system_prompt = request
        .system
        .map(extract_system_prompt_text)
        .filter(|value| !value.is_empty())
        .map(Arc::new);

    let mut messages = Vec::new();
    for anthropic_msg in request.messages {
        let role = anthropic_role_to_message_role(&anthropic_msg.role);

        match anthropic_msg.content {
            AnthropicContent::Text(text) => {
                if !text.is_empty() {
                    messages.push(Message::base(role, MessageContent::Text(text)));
                }
            }
            AnthropicContent::Blocks(blocks) => {
                let converted = convert_anthropic_blocks(&blocks);
                messages.extend(converted.emitted_messages);

                if !converted.content_parts.is_empty()
                    || !converted.tool_calls.is_empty()
                    || !converted.reasoning_chunks.is_empty()
                {
                    let mut message =
                        Message::base(role, message_content_from_parts(converted.content_parts));
                    if !converted.tool_calls.is_empty() {
                        message.tool_calls = Some(converted.tool_calls);
                    }
                    if !converted.reasoning_chunks.is_empty()
                        && message.role == MessageRole::Assistant
                    {
                        message.reasoning = Some(converted.reasoning_chunks.join("\n"));
                    }
                    if !converted.reasoning_details.is_empty()
                        && message.role == MessageRole::Assistant
                    {
                        message.reasoning_details = Some(converted.reasoning_details);
                    }
                    messages.push(message);
                }
            }
        }
    }

    let tools = if let Some(anthropic_tools) = request.tools {
        let mut converted_tools = Vec::new();
        for tool in anthropic_tools {
            let tool_def = match tool {
                AnthropicTool::Function {
                    name,
                    description,
                    input_schema,
                    input_examples,
                    strict,
                    allowed_callers,
                } => {
                    let mut tool = ToolDefinition::function(
                        name,
                        description.unwrap_or_default(),
                        input_schema,
                    );
                    tool.input_examples = input_examples;
                    tool.strict = strict;
                    tool.allowed_callers = allowed_callers;
                    tool
                }
                AnthropicTool::Native {
                    tool_type, options, ..
                } => {
                    if tool_type.starts_with("web_search_") {
                        ToolDefinition {
                            tool_type,
                            function: None,
                            allowed_callers: None,
                            input_examples: None,
                            web_search: (!options.is_empty()).then_some(Value::Object(options)),
                            hosted_tool_config: None,
                            shell: None,
                            grammar: None,
                            strict: None,
                            defer_loading: None,
                        }
                    } else if tool_type.starts_with("code_execution_")
                        || tool_type.starts_with("memory_")
                    {
                        ToolDefinition {
                            tool_type,
                            function: None,
                            allowed_callers: None,
                            input_examples: None,
                            web_search: None,
                            hosted_tool_config: None,
                            shell: None,
                            grammar: None,
                            strict: None,
                            defer_loading: None,
                        }
                    } else {
                        continue;
                    }
                }
            };
            converted_tools.push(tool_def);
        }
        if converted_tools.is_empty() {
            None
        } else {
            Some(Arc::new(converted_tools))
        }
    } else {
        None
    };

    LLMRequest {
        messages,
        system_prompt,
        tools,
        model: request.model,
        max_tokens: Some(request.max_tokens),
        temperature: request.temperature,
        stream: request.stream,
        output_format,
        tool_choice,
        parallel_tool_calls: None,
        parallel_tool_config,
        reasoning_effort: None,
        effort,
        verbosity: None,
        do_sample: None,
        top_p: request.top_p,
        top_k: request.top_k,
        presence_penalty: None,
        frequency_penalty: None,
        stop_sequences: request.stop_sequences,
        thinking_budget: None,
        betas: request.betas,
        context_management: request.context_management,
        prefill: None,
        character_reinforcement: false,
        character_name: None,
        coding_agent_settings: None,
        metadata: None,
        previous_response_id: None,
        response_store: None,
        responses_include: None,
        service_tier: None,
        prompt_cache_key: None,
        prompt_cache_profile: None,
        anthropic_request_overrides,
    }
}

pub fn convert_llm_to_anthropic_response(response: LLMResponse) -> AnthropicMessagesResponse {
    use uuid::Uuid;

    let mut content_blocks = Vec::new();
    let mut preserved_reasoning = false;

    if let Some(reasoning_details) = response.reasoning_details.as_ref() {
        for detail in reasoning_details {
            let Some(normalized) =
                normalize_reasoning_detail_object(&Value::String(detail.clone()))
            else {
                continue;
            };

            match normalized.get("type").and_then(|value| value.as_str()) {
                Some("thinking") => {
                    let thinking = normalized
                        .get("thinking")
                        .and_then(|value| value.as_str())
                        .unwrap_or_default()
                        .to_string();
                    let signature = normalized
                        .get("signature")
                        .and_then(|value| value.as_str())
                        .map(ToOwned::to_owned);
                    content_blocks.push(AnthropicContentBlock::Thinking {
                        thinking,
                        signature,
                    });
                    preserved_reasoning = true;
                }
                Some("redacted_thinking") => {
                    let data = normalized
                        .get("data")
                        .and_then(|value| value.as_str())
                        .unwrap_or_default()
                        .to_string();
                    content_blocks.push(AnthropicContentBlock::RedactedThinking { data });
                    preserved_reasoning = true;
                }
                _ => {}
            }
        }
    }

    if !preserved_reasoning
        && let Some(reasoning) = response.reasoning.as_ref()
        && !reasoning.trim().is_empty()
    {
        content_blocks.push(AnthropicContentBlock::Thinking {
            thinking: reasoning.clone(),
            signature: None,
        });
    }

    if let Some(content) = response.content.as_ref()
        && !content.is_empty()
    {
        content_blocks.push(AnthropicContentBlock::Text {
            text: content.clone(),
            citations: None,
            cache_control: None,
        });
    }

    if let Some(tool_calls) = response.tool_calls.as_ref() {
        for call in tool_calls {
            if let Some(func) = &call.function {
                let input = call
                    .parsed_arguments()
                    .unwrap_or_else(|_| Value::String(func.arguments.clone()));
                content_blocks.push(AnthropicContentBlock::ToolUse {
                    id: call.id.clone(),
                    name: func.name.clone(),
                    input,
                });
            }
        }
    }

    let usage = response.usage.unwrap_or_default();
    let model = if response.model.trim().is_empty() {
        "unknown".to_string()
    } else {
        response.model
    };

    AnthropicMessagesResponse {
        id: Uuid::new_v4().to_string(),
        r#type: "message".to_string(),
        role: "assistant".to_string(),
        model,
        content: content_blocks,
        stop_reason: Some(anthropic_stop_reason(response.finish_reason)),
        stop_sequence: None,
        usage: AnthropicUsage {
            input_tokens: usage.prompt_tokens,
            output_tokens: usage.completion_tokens,
        },
    }
}

pub(crate) fn anthropic_stop_reason(finish_reason: FinishReason) -> String {
    match finish_reason {
        FinishReason::Stop => "end_turn".to_string(),
        FinishReason::Length => "max_tokens".to_string(),
        FinishReason::ToolCalls => "tool_use".to_string(),
        FinishReason::ContentFilter => "content_filter".to_string(),
        FinishReason::Pause => "pause_turn".to_string(),
        FinishReason::Refusal => "refusal".to_string(),
        FinishReason::Error(message) => message,
    }
}

fn parse_anthropic_tool_choice(
    tool_choice: Option<&Value>,
) -> (Option<ToolChoice>, Option<Box<ParallelToolConfig>>) {
    let Some(choice) = tool_choice else {
        return (None, None);
    };
    let Some(choice_obj) = choice.as_object() else {
        return (None, None);
    };

    let disable_parallel_tool_use = choice_obj
        .get("disable_parallel_tool_use")
        .and_then(Value::as_bool)
        .unwrap_or(false);

    let parsed_tool_choice = match choice_obj.get("type").and_then(Value::as_str) {
        Some("auto") => Some(ToolChoice::Auto),
        Some("none") => Some(ToolChoice::None),
        Some("any") => Some(ToolChoice::Any),
        Some("tool") => choice_obj
            .get("name")
            .and_then(Value::as_str)
            .map(|name| ToolChoice::function(name.to_string())),
        _ => None,
    };

    let parallel_tool_config = disable_parallel_tool_use.then(|| {
        Box::new(ParallelToolConfig {
            disable_parallel_tool_use: true,
            max_parallel_tools: Some(1),
            encourage_parallel: false,
        })
    });

    (parsed_tool_choice, parallel_tool_config)
}

fn anthropic_role_to_message_role(role: &str) -> MessageRole {
    match role {
        "assistant" => MessageRole::Assistant,
        "system" => MessageRole::System,
        "tool" => MessageRole::Tool,
        _ => MessageRole::User,
    }
}

fn extract_system_prompt_text(system_prompt: AnthropicSystemPrompt) -> String {
    match system_prompt {
        AnthropicSystemPrompt::Text(text) => text,
        AnthropicSystemPrompt::Blocks(blocks) => blocks
            .iter()
            .map(anthropic_block_text)
            .filter(|text| !text.is_empty())
            .collect::<Vec<_>>()
            .join("\n"),
    }
}

fn convert_anthropic_blocks(blocks: &[AnthropicContentBlock]) -> ConvertedAnthropicBlocks {
    let mut converted = ConvertedAnthropicBlocks::default();

    for block in blocks {
        match block {
            AnthropicContentBlock::Text { text, .. } => {
                converted
                    .content_parts
                    .push(ContentPart::text(text.clone()));
            }
            AnthropicContentBlock::Image { source } => {
                converted.content_parts.push(ContentPart::image(
                    source.data.clone(),
                    source.media_type.clone(),
                ));
            }
            AnthropicContentBlock::ToolUse { id, name, input }
            | AnthropicContentBlock::ServerToolUse { id, name, input } => {
                converted.tool_calls.push(ToolCall::function(
                    id.clone(),
                    name.clone(),
                    input.to_string(),
                ));
            }
            AnthropicContentBlock::ToolResult {
                tool_use_id,
                content,
                ..
            } => converted.emitted_messages.push(Message::tool_response(
                tool_use_id.clone(),
                anthropic_content_text(content),
            )),
            AnthropicContentBlock::Thinking {
                thinking,
                signature,
            } => {
                converted.reasoning_chunks.push(thinking.clone());
                let mut detail = json!({
                    "type": "thinking",
                    "thinking": thinking,
                });
                if let Some(signature) = signature
                    && let Some(obj) = detail.as_object_mut()
                {
                    obj.insert("signature".to_string(), Value::String(signature.clone()));
                }
                converted.reasoning_details.push(detail);
            }
            AnthropicContentBlock::RedactedThinking { data } => {
                converted.reasoning_details.push(json!({
                    "type": "redacted_thinking",
                    "data": data,
                }));
            }
            AnthropicContentBlock::ContainerUpload { file_id } => {
                converted
                    .content_parts
                    .push(ContentPart::file_from_id(file_id.clone()));
            }
            AnthropicContentBlock::CodeExecutionToolResult {
                tool_use_id,
                content,
            }
            | AnthropicContentBlock::BashCodeExecutionToolResult {
                tool_use_id,
                content,
            }
            | AnthropicContentBlock::TextEditorCodeExecutionToolResult {
                tool_use_id,
                content,
            }
            | AnthropicContentBlock::WebSearchToolResult {
                tool_use_id,
                content,
            } => converted.emitted_messages.push(Message::tool_response(
                tool_use_id.clone(),
                serialize_value(content),
            )),
        }
    }

    converted
}

fn message_content_from_parts(parts: Vec<ContentPart>) -> MessageContent {
    if parts.len() == 1
        && let ContentPart::Text { text } = &parts[0]
    {
        return MessageContent::Text(text.clone());
    }

    MessageContent::Parts(parts)
}

fn anthropic_content_text(content: &AnthropicContent) -> String {
    match content {
        AnthropicContent::Text(text) => text.clone(),
        AnthropicContent::Blocks(blocks) => blocks
            .iter()
            .map(anthropic_block_text)
            .filter(|text| !text.is_empty())
            .collect::<Vec<_>>()
            .join("\n"),
    }
}

fn anthropic_block_text(block: &AnthropicContentBlock) -> String {
    match block {
        AnthropicContentBlock::Text { text, .. } => text.clone(),
        AnthropicContentBlock::Thinking { thinking, .. } => thinking.clone(),
        AnthropicContentBlock::RedactedThinking { .. } => "[REDACTED THINKING]".to_string(),
        AnthropicContentBlock::Image { .. } => "[Image]".to_string(),
        AnthropicContentBlock::ContainerUpload { file_id } => format!("[File: {file_id}]"),
        AnthropicContentBlock::ToolUse { name, input, .. }
        | AnthropicContentBlock::ServerToolUse { name, input, .. } => {
            format!("[Tool call: {name} with args: {input}]")
        }
        AnthropicContentBlock::ToolResult {
            tool_use_id,
            content,
            ..
        } => format!(
            "[Tool result {}: {}]",
            tool_use_id,
            anthropic_content_text(content)
        ),
        AnthropicContentBlock::CodeExecutionToolResult {
            tool_use_id,
            content,
        }
        | AnthropicContentBlock::BashCodeExecutionToolResult {
            tool_use_id,
            content,
        }
        | AnthropicContentBlock::TextEditorCodeExecutionToolResult {
            tool_use_id,
            content,
        }
        | AnthropicContentBlock::WebSearchToolResult {
            tool_use_id,
            content,
        } => {
            format!(
                "[Tool result {}: {}]",
                tool_use_id,
                serialize_value(content)
            )
        }
    }
}

fn compatibility_thinking_mode(
    model: &str,
    thinking: Option<&ThinkingConfig>,
) -> AnthropicThinkingModeOverride {
    match thinking {
        Some(ThinkingConfig::Adaptive { .. }) => AnthropicThinkingModeOverride::Adaptive,
        Some(ThinkingConfig::Enabled { budget_tokens, .. }) => {
            AnthropicThinkingModeOverride::ManualBudget(*budget_tokens)
        }
        Some(ThinkingConfig::Disabled) => AnthropicThinkingModeOverride::Disabled,
        None => {
            let is_mythos = model
                == crate::config::constants::models::anthropic::CLAUDE_MYTHOS_PREVIEW
                || model
                    .contains(crate::config::constants::models::anthropic::CLAUDE_MYTHOS_PREVIEW);
            if is_mythos {
                AnthropicThinkingModeOverride::Adaptive
            } else {
                AnthropicThinkingModeOverride::Disabled
            }
        }
    }
}

fn compatibility_thinking_display(
    thinking: Option<&ThinkingConfig>,
) -> AnthropicThinkingDisplayOverride {
    let display = match thinking {
        Some(ThinkingConfig::Adaptive { display })
        | Some(ThinkingConfig::Enabled { display, .. }) => *display,
        Some(ThinkingConfig::Disabled) | None => None,
    };

    match display {
        Some(ThinkingDisplay::Summarized) => AnthropicThinkingDisplayOverride::Summarized,
        Some(ThinkingDisplay::Omitted) => AnthropicThinkingDisplayOverride::Omitted,
        None => AnthropicThinkingDisplayOverride::Inherit,
    }
}

fn serialize_value(value: &Value) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| json!({ "value": value }).to_string())
}