sashiko 0.2.1

Agentic code review system for Linux kernel
Documentation
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
// Copyright 2026 The Sashiko Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::ai::token_budget::TokenBudget;
use crate::ai::{
    AiProvider, AiRequest, AiResponse, AiRole, AiUsage, ProviderCapabilities, ToolCall,
};
use anyhow::{Context, Result};
use async_trait::async_trait;
use aws_sdk_bedrockruntime::Client;
use aws_sdk_bedrockruntime::types::{
    CachePointBlock, CachePointType, ContentBlock, ConversationRole, InferenceConfiguration,
    Message, SystemContentBlock, Tool, ToolConfiguration, ToolInputSchema, ToolResultBlock,
    ToolResultContentBlock, ToolSpecification, ToolUseBlock,
};
use aws_smithy_types::{Document, Number};
use std::collections::HashMap;
use tracing::info;

// --- serde_json::Value <-> aws_smithy_types::Document conversion ---

fn json_to_document(value: &serde_json::Value) -> Document {
    match value {
        serde_json::Value::Null => Document::Null,
        serde_json::Value::Bool(b) => Document::Bool(*b),
        serde_json::Value::Number(n) => {
            if let Some(u) = n.as_u64() {
                Document::Number(Number::PosInt(u))
            } else if let Some(i) = n.as_i64() {
                Document::Number(Number::NegInt(i))
            } else {
                Document::Number(Number::Float(n.as_f64().unwrap_or(0.0)))
            }
        }
        serde_json::Value::String(s) => Document::String(s.clone()),
        serde_json::Value::Array(arr) => {
            Document::Array(arr.iter().map(json_to_document).collect())
        }
        serde_json::Value::Object(obj) => {
            let map: HashMap<String, Document> = obj
                .iter()
                .map(|(k, v)| (k.clone(), json_to_document(v)))
                .collect();
            Document::Object(map)
        }
    }
}

fn document_to_json(doc: &Document) -> serde_json::Value {
    match doc {
        Document::Null => serde_json::Value::Null,
        Document::Bool(b) => serde_json::Value::Bool(*b),
        Document::Number(n) => match n {
            Number::PosInt(u) => serde_json::json!(*u),
            Number::NegInt(i) => serde_json::json!(*i),
            Number::Float(f) => serde_json::json!(*f),
        },
        Document::String(s) => serde_json::Value::String(s.clone()),
        Document::Array(arr) => {
            serde_json::Value::Array(arr.iter().map(document_to_json).collect())
        }
        Document::Object(obj) => {
            let map: serde_json::Map<String, serde_json::Value> = obj
                .iter()
                .map(|(k, v)| (k.clone(), document_to_json(v)))
                .collect();
            serde_json::Value::Object(map)
        }
    }
}

// --- Bedrock client ---

pub struct BedrockClient {
    client: tokio::sync::OnceCell<Client>,
    region: Option<String>,
    model_id: String,
    context_window_size: usize,
    enable_caching: bool,
    max_tokens: u32,
    thinking: Option<String>,
    effort: Option<String>,
}

impl BedrockClient {
    pub fn new(
        model_id: String,
        region: Option<String>,
        enable_caching: bool,
        max_tokens: u32,
        thinking: Option<String>,
        effort: Option<String>,
    ) -> Self {
        let context_window_size = if model_id.contains("claude") {
            200_000
        } else {
            128_000
        };

        Self {
            client: tokio::sync::OnceCell::new(),
            region,
            model_id,
            context_window_size,
            enable_caching,
            max_tokens,
            thinking,
            effort,
        }
    }

    async fn get_client(&self) -> &Client {
        self.client
            .get_or_init(|| async {
                let mut config_loader = aws_config::from_env();
                if let Some(r) = &self.region {
                    config_loader = config_loader.region(aws_config::Region::new(r.clone()));
                }
                let sdk_config = config_loader.load().await;
                Client::new(&sdk_config)
            })
            .await
    }
}

// --- Request translation ---

struct ConverseParams {
    messages: Vec<Message>,
    system: Option<Vec<SystemContentBlock>>,
    tool_config: Option<ToolConfiguration>,
    inference_config: Option<InferenceConfiguration>,
    additional_model_request_fields: Option<Document>,
}

fn build_additional_fields(thinking: Option<&str>, effort: Option<&str>) -> Option<Document> {
    let mut map: HashMap<String, Document> = HashMap::new();

    if let Some(t) = thinking {
        let mut thinking_obj: HashMap<String, Document> = HashMap::new();
        thinking_obj.insert("type".to_string(), Document::String(t.to_string()));
        map.insert("thinking".to_string(), Document::Object(thinking_obj));
    }

    if let Some(e) = effort {
        let mut output_cfg: HashMap<String, Document> = HashMap::new();
        output_cfg.insert("effort".to_string(), Document::String(e.to_string()));
        map.insert("output_config".to_string(), Document::Object(output_cfg));
    }

    if map.is_empty() {
        None
    } else {
        Some(Document::Object(map))
    }
}

/// Translate Sashiko's generic AiRequest into Bedrock Converse API parameters.
fn translate_request(
    request: &AiRequest,
    enable_caching: bool,
    max_tokens: u32,
    thinking: Option<&str>,
    effort: Option<&str>,
) -> Result<ConverseParams> {
    let system = request.system.as_ref().map(|s| {
        let mut blocks = vec![SystemContentBlock::Text(s.clone())];
        if enable_caching {
            blocks.push(SystemContentBlock::CachePoint(
                CachePointBlock::builder()
                    .r#type(CachePointType::Default)
                    .build()
                    .expect("CachePointBlock build"),
            ));
        }
        blocks
    });

    let mut messages: Vec<Message> = Vec::new();

    // We need to merge consecutive Tool messages into a single User message
    // because Bedrock requires alternating user/assistant turns.
    let mut pending_tool_results: Vec<ContentBlock> = Vec::new();

    let flush_tool_results =
        |pending: &mut Vec<ContentBlock>, messages: &mut Vec<Message>| -> Result<()> {
            if pending.is_empty() {
                return Ok(());
            }
            let mut builder = Message::builder().role(ConversationRole::User);
            for block in pending.drain(..) {
                builder = builder.content(block);
            }
            messages.push(
                builder
                    .build()
                    .context("Failed to build tool result message")?,
            );
            Ok(())
        };

    for msg in &request.messages {
        match msg.role {
            AiRole::System => {} // handled above
            AiRole::User => {
                flush_tool_results(&mut pending_tool_results, &mut messages)?;
                let text = msg.content.clone().unwrap_or_default();
                messages.push(
                    Message::builder()
                        .role(ConversationRole::User)
                        .content(ContentBlock::Text(text))
                        .build()
                        .context("Failed to build user message")?,
                );
            }
            AiRole::Assistant => {
                flush_tool_results(&mut pending_tool_results, &mut messages)?;
                let mut builder = Message::builder().role(ConversationRole::Assistant);
                if let Some(text) = &msg.content {
                    builder = builder.content(ContentBlock::Text(text.clone()));
                }
                if let Some(tool_calls) = &msg.tool_calls {
                    for call in tool_calls {
                        let input_doc = json_to_document(&call.arguments);
                        builder = builder.content(ContentBlock::ToolUse(
                            ToolUseBlock::builder()
                                .tool_use_id(&call.id)
                                .name(&call.function_name)
                                .input(input_doc)
                                .build()
                                .context("Failed to build tool use block")?,
                        ));
                    }
                }
                messages.push(
                    builder
                        .build()
                        .context("Failed to build assistant message")?,
                );
            }
            AiRole::Tool => {
                let tool_call_id = msg
                    .tool_call_id
                    .as_ref()
                    .context("Tool message missing tool_call_id")?;
                let result_text = msg.content.clone().unwrap_or_else(|| "{}".to_string());
                pending_tool_results.push(ContentBlock::ToolResult(
                    ToolResultBlock::builder()
                        .tool_use_id(tool_call_id)
                        .content(ToolResultContentBlock::Text(result_text))
                        .build()
                        .context("Failed to build tool result block")?,
                ));
            }
        }
    }
    flush_tool_results(&mut pending_tool_results, &mut messages)?;

    if enable_caching && let Some(last) = messages.last_mut() {
        let role = last.role().clone();
        let mut builder = Message::builder().role(role);
        for block in last.content().iter().cloned() {
            builder = builder.content(block);
        }
        builder = builder.content(ContentBlock::CachePoint(
            CachePointBlock::builder()
                .r#type(CachePointType::Default)
                .build()
                .expect("CachePointBlock build"),
        ));
        *last = builder
            .build()
            .context("Failed to rebuild last message with cachePoint")?;
    }

    let tool_config = request.tools.as_ref().and_then(|tools| {
        if tools.is_empty() {
            return None;
        }
        let mut bedrock_tools: Vec<Tool> = tools
            .iter()
            .filter_map(|t| {
                let schema_doc = json_to_document(&t.parameters);
                Some(Tool::ToolSpec(
                    ToolSpecification::builder()
                        .name(&t.name)
                        .description(&t.description)
                        .input_schema(ToolInputSchema::Json(schema_doc))
                        .build()
                        .ok()?,
                ))
            })
            .collect();
        if enable_caching && !bedrock_tools.is_empty() {
            bedrock_tools.push(Tool::CachePoint(
                CachePointBlock::builder()
                    .r#type(CachePointType::Default)
                    .build()
                    .expect("CachePointBlock build"),
            ));
        }
        ToolConfiguration::builder()
            .set_tools(Some(bedrock_tools))
            .build()
            .ok()
    });

    let inference_config = {
        let mut builder = InferenceConfiguration::builder().max_tokens(max_tokens as i32);
        #[allow(clippy::collapsible_if)]
        if thinking.is_none() {
            if let Some(temp) = request.temperature {
                builder = builder.temperature(temp);
            }
        }
        Some(builder.build())
    };

    let additional_model_request_fields = build_additional_fields(thinking, effort);

    Ok(ConverseParams {
        messages,
        system,
        tool_config,
        inference_config,
        additional_model_request_fields,
    })
}

/// Translate Bedrock Converse API response into Sashiko's generic AiResponse.
fn translate_response(
    output: &aws_sdk_bedrockruntime::operation::converse::ConverseOutput,
) -> Result<AiResponse> {
    let mut text_parts = Vec::new();
    let mut tool_calls = Vec::new();

    if let Some(aws_sdk_bedrockruntime::types::ConverseOutput::Message(ref msg)) = output.output {
        for block in msg.content() {
            match block {
                ContentBlock::Text(t) => text_parts.push(t.clone()),
                ContentBlock::ToolUse(tu) => {
                    let args = document_to_json(tu.input());
                    tool_calls.push(ToolCall {
                        id: tu.tool_use_id().to_string(),
                        function_name: tu.name().to_string(),
                        arguments: args,
                        thought_signature: None,
                    });
                }
                _ => {}
            }
        }
    }

    // Bedrock splits input into uncached + cache_read + cache_write; sum all
    // three for the true total.  cache_write isn't in AiUsage because Gemini
    // has no equivalent — the Bedrock log line still prints it for cost analysis.
    let usage = output.usage.as_ref().map(|u| {
        let cache_read = u.cache_read_input_tokens().unwrap_or(0);
        let cache_write = u.cache_write_input_tokens().unwrap_or(0);
        let total_input = u.input_tokens() + cache_read + cache_write;
        AiUsage {
            prompt_tokens: total_input as usize,
            completion_tokens: u.output_tokens() as usize,
            total_tokens: (total_input + u.output_tokens()) as usize,
            cached_tokens: if cache_read > 0 {
                Some(cache_read as usize)
            } else {
                None
            },
        }
    });

    Ok(AiResponse {
        content: if text_parts.is_empty() {
            None
        } else {
            Some(text_parts.join(""))
        },
        thought: None,
        thought_signature: None,
        tool_calls: if tool_calls.is_empty() {
            None
        } else {
            Some(tool_calls)
        },
        usage,
        truncated: false,
    })
}

fn estimate_tokens_generic(request: &AiRequest) -> usize {
    let mut total = 0;
    if let Some(system) = &request.system {
        total += TokenBudget::estimate_tokens(system);
    }
    for msg in &request.messages {
        if let Some(content) = &msg.content {
            total += TokenBudget::estimate_tokens(content);
        }
        if let Some(tool_calls) = &msg.tool_calls {
            for call in tool_calls {
                total += TokenBudget::estimate_tokens(&call.function_name);
                total += TokenBudget::estimate_tokens(&call.arguments.to_string());
            }
        }
    }
    if let Some(tools) = &request.tools {
        for tool in tools {
            total += TokenBudget::estimate_tokens(&tool.name);
            total += TokenBudget::estimate_tokens(&tool.description);
            total += TokenBudget::estimate_tokens(&tool.parameters.to_string());
        }
    }
    total
}

#[async_trait]
impl AiProvider for BedrockClient {
    async fn generate_content(&self, request: AiRequest) -> Result<AiResponse> {
        let params = translate_request(
            &request,
            self.enable_caching,
            self.max_tokens,
            self.thinking.as_deref(),
            self.effort.as_deref(),
        )?;

        let resp = self
            .get_client()
            .await
            .converse()
            .model_id(&self.model_id)
            .set_messages(Some(params.messages))
            .set_system(params.system)
            .set_tool_config(params.tool_config)
            .set_inference_config(params.inference_config)
            .set_additional_model_request_fields(params.additional_model_request_fields)
            .send()
            .await;

        let resp = match resp {
            Ok(r) => r,
            Err(e) => {
                let is_throttle = format!("{e:?}").contains("ThrottlingException");
                if is_throttle {
                    tracing::warn!("Bedrock throttled, waiting 30s before retry...");
                    tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                }
                return Err(anyhow::anyhow!("Bedrock Converse API error: {e:#}"));
            }
        };

        let usage_str = resp
            .usage
            .as_ref()
            .map(|u| {
                format!(
                    "in={}, out={}, cache_read={}, cache_write={}",
                    u.input_tokens(),
                    u.output_tokens(),
                    u.cache_read_input_tokens().unwrap_or(0),
                    u.cache_write_input_tokens().unwrap_or(0),
                )
            })
            .unwrap_or_else(|| "unknown".to_string());
        info!("Bedrock response received. Tokens: {}", usage_str);

        translate_response(&resp)
    }

    fn estimate_tokens(&self, request: &AiRequest) -> usize {
        estimate_tokens_generic(request)
    }

    fn get_capabilities(&self) -> ProviderCapabilities {
        ProviderCapabilities {
            model_name: self.model_id.clone(),
            context_window_size: self.context_window_size,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ai::{AiMessage, AiRequest, AiRole, AiTool, ToolCall};
    use serde_json::json;

    fn make_request(messages: Vec<AiMessage>) -> AiRequest {
        AiRequest {
            system: None,
            messages,
            tools: None,
            temperature: None,
            response_format: None,
            context_tag: None,
        }
    }

    #[test]
    fn test_json_document_roundtrip() {
        let pi_value = std::f64::consts::PI;
        let original = json!({
            "name": "test",
            "count": 42,
            "negative": -7,
            "ratio": pi_value,
            "active": true,
            "nothing": null,
            "tags": ["a", "b"],
            "nested": {"x": 1}
        });
        let doc = json_to_document(&original);
        let back = document_to_json(&doc);
        assert_eq!(original, back);
    }

    #[test]
    fn test_translate_system_and_user() -> Result<()> {
        let mut req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("Hello!".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);
        req.system = Some("You are helpful.".to_string());
        req.temperature = Some(0.5);

        let params = translate_request(&req, false, 4096, None, None)?;

        let sys = params.system.unwrap();
        assert_eq!(sys.len(), 1);
        if let SystemContentBlock::Text(t) = &sys[0] {
            assert_eq!(t, "You are helpful.");
        } else {
            panic!("Expected Text system block");
        }

        assert_eq!(params.messages.len(), 1);
        assert_eq!(params.messages[0].role(), &ConversationRole::User);
        if let ContentBlock::Text(t) = &params.messages[0].content()[0] {
            assert_eq!(t, "Hello!");
        } else {
            panic!("Expected Text content block");
        }

        let ic = params.inference_config.unwrap();
        assert_eq!(ic.temperature(), Some(0.5));

        Ok(())
    }

    #[test]
    fn test_translate_assistant_with_tool_calls() -> Result<()> {
        let req = make_request(vec![AiMessage {
            role: AiRole::Assistant,
            content: Some("Let me check.".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: Some(vec![ToolCall {
                id: "call_1".to_string(),
                function_name: "git_log".to_string(),
                arguments: json!({"n": 5}),
                thought_signature: None,
            }]),
            tool_call_id: None,
        }]);

        let params = translate_request(&req, false, 4096, None, None)?;
        let content = params.messages[0].content();
        assert_eq!(content.len(), 2);

        if let ContentBlock::Text(t) = &content[0] {
            assert_eq!(t, "Let me check.");
        } else {
            panic!("Expected Text block");
        }

        if let ContentBlock::ToolUse(tu) = &content[1] {
            assert_eq!(tu.tool_use_id(), "call_1");
            assert_eq!(tu.name(), "git_log");
            assert_eq!(document_to_json(tu.input()), json!({"n": 5}));
        } else {
            panic!("Expected ToolUse block");
        }

        Ok(())
    }

    #[test]
    fn test_translate_tool_result() -> Result<()> {
        let req = make_request(vec![AiMessage {
            role: AiRole::Tool,
            content: Some("commit abc123".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: Some("call_1".to_string()),
        }]);

        let params = translate_request(&req, false, 4096, None, None)?;
        assert_eq!(params.messages.len(), 1);
        assert_eq!(params.messages[0].role(), &ConversationRole::User);

        if let ContentBlock::ToolResult(tr) = &params.messages[0].content()[0] {
            assert_eq!(tr.tool_use_id(), "call_1");
        } else {
            panic!("Expected ToolResult block");
        }

        Ok(())
    }

    #[test]
    fn test_translate_tools() -> Result<()> {
        let mut req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);
        req.tools = Some(vec![AiTool {
            name: "read_file".to_string(),
            description: "Read a file".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {"path": {"type": "string"}}
            }),
        }]);

        let params = translate_request(&req, false, 4096, None, None)?;
        let tools = params.tool_config.unwrap().tools().to_vec();
        assert_eq!(tools.len(), 1);

        if let Tool::ToolSpec(spec) = &tools[0] {
            assert_eq!(spec.name(), "read_file");
            assert_eq!(spec.description(), Some("Read a file"));
        } else {
            panic!("Expected ToolSpec");
        }

        Ok(())
    }

    #[test]
    fn test_translate_empty_tools_omitted() -> Result<()> {
        let mut req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);
        req.tools = Some(vec![]);

        let params = translate_request(&req, false, 4096, None, None)?;
        assert!(params.tool_config.is_none());

        Ok(())
    }

    #[test]
    fn test_additional_fields_none_when_unset() {
        assert!(build_additional_fields(None, None).is_none());
    }

    #[test]
    fn test_additional_fields_thinking_and_effort() {
        let doc = build_additional_fields(Some("adaptive"), Some("xhigh")).unwrap();
        let json = document_to_json(&doc);
        assert_eq!(
            json,
            serde_json::json!({
                "thinking": {"type": "adaptive"},
                "output_config": {"effort": "xhigh"}
            })
        );
    }

    #[test]
    fn test_max_tokens_propagates_to_inference_config() -> Result<()> {
        let req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);

        let params = translate_request(&req, false, 8192, None, None)?;
        assert_eq!(params.inference_config.unwrap().max_tokens(), Some(8192));
        Ok(())
    }

    #[test]
    fn test_translate_request_wires_additional_fields() -> Result<()> {
        let req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);

        let params = translate_request(&req, false, 8192, Some("adaptive"), Some("high"))?;
        let extra = params.additional_model_request_fields.unwrap();
        let json = document_to_json(&extra);
        assert_eq!(json["thinking"]["type"], "adaptive");
        assert_eq!(json["output_config"]["effort"], "high");
        Ok(())
    }

    #[test]
    fn test_cache_point_inserted_when_enabled() -> Result<()> {
        let mut req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("Hello!".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);
        req.system = Some("System prompt.".to_string());

        let params = translate_request(&req, true, 4096, None, None)?;
        let sys = params.system.unwrap();
        assert_eq!(sys.len(), 2);
        assert!(matches!(&sys[0], SystemContentBlock::Text(_)));
        assert!(sys[1].is_cache_point());

        Ok(())
    }

    #[test]
    fn test_rolling_cache_point_on_last_message_when_enabled() -> Result<()> {
        let req = make_request(vec![
            AiMessage {
                role: AiRole::User,
                content: Some("first".to_string()),
                thought: None,
                thought_signature: None,
                tool_calls: None,
                tool_call_id: None,
            },
            AiMessage {
                role: AiRole::Assistant,
                content: Some("second".to_string()),
                thought: None,
                thought_signature: None,
                tool_calls: None,
                tool_call_id: None,
            },
        ]);

        let params = translate_request(&req, true, 4096, None, None)?;
        assert_eq!(params.messages.len(), 2);

        let first_content = params.messages[0].content();
        assert_eq!(first_content.len(), 1);
        assert!(!first_content[0].is_cache_point());

        let last_content = params.messages[1].content();
        assert_eq!(last_content.len(), 2);
        assert!(!last_content[0].is_cache_point());
        assert!(last_content[1].is_cache_point());

        Ok(())
    }

    #[test]
    fn test_rolling_cache_point_preserves_tool_result_blocks() -> Result<()> {
        let req = make_request(vec![
            AiMessage {
                role: AiRole::Tool,
                content: Some("result A".to_string()),
                thought: None,
                thought_signature: None,
                tool_calls: None,
                tool_call_id: Some("call_a".to_string()),
            },
            AiMessage {
                role: AiRole::Tool,
                content: Some("result B".to_string()),
                thought: None,
                thought_signature: None,
                tool_calls: None,
                tool_call_id: Some("call_b".to_string()),
            },
        ]);

        let params = translate_request(&req, true, 4096, None, None)?;
        assert_eq!(params.messages.len(), 1);
        let content = params.messages[0].content();
        assert_eq!(content.len(), 3);
        assert!(matches!(&content[0], ContentBlock::ToolResult(_)));
        assert!(matches!(&content[1], ContentBlock::ToolResult(_)));
        assert!(content[2].is_cache_point());
        Ok(())
    }

    #[test]
    fn test_no_rolling_cache_point_when_disabled() -> Result<()> {
        let req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);

        let params = translate_request(&req, false, 4096, None, None)?;
        let content = params.messages[0].content();
        assert_eq!(content.len(), 1);
        assert!(!content[0].is_cache_point());
        Ok(())
    }

    #[test]
    fn test_tool_cache_point_appended_when_enabled() -> Result<()> {
        let mut req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);
        req.tools = Some(vec![AiTool {
            name: "read_file".to_string(),
            description: "Read a file".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {"path": {"type": "string"}}
            }),
        }]);

        let params = translate_request(&req, true, 4096, None, None)?;
        let tools = params.tool_config.unwrap().tools().to_vec();
        assert_eq!(tools.len(), 2);
        assert!(matches!(&tools[0], Tool::ToolSpec(_)));
        assert!(tools[1].is_cache_point());
        Ok(())
    }

    #[test]
    fn test_tool_cache_point_absent_when_disabled() -> Result<()> {
        let mut req = make_request(vec![AiMessage {
            role: AiRole::User,
            content: Some("hi".to_string()),
            thought: None,
            thought_signature: None,
            tool_calls: None,
            tool_call_id: None,
        }]);
        req.tools = Some(vec![AiTool {
            name: "read_file".to_string(),
            description: "Read a file".to_string(),
            parameters: json!({"type": "object"}),
        }]);

        let params = translate_request(&req, false, 4096, None, None)?;
        let tools = params.tool_config.unwrap().tools().to_vec();
        assert_eq!(tools.len(), 1);
        assert!(matches!(&tools[0], Tool::ToolSpec(_)));
        Ok(())
    }
}