gemini-cli-sdk 0.1.0

Rust SDK wrapping Google's Gemini CLI as a subprocess via JSON-RPC 2.0
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//! Translation layer: wire format types ↔ unified public types.
//!
//! This module provides two translation directions:
//!
//! - **Inbound** (wire → public): [`translate_content_block`] for individual
//!   blocks; [`TranslationContext::translate`] for streaming [`SessionUpdate`]
//!   events accumulated into [`Message`] values.
//! - **Outbound** (public → wire): [`user_content_to_wire`] and
//!   [`prompt_to_wire`] for building `session/prompt` request payloads.
//!
//! All translation is best-effort and lossless for unknown fields — the wire
//! types carry `#[serde(flatten)] pub extra: Value` which is propagated where
//! applicable.

use std::collections::HashMap;

use serde_json::{json, Value};

use crate::permissions::ToolInputCache;
use crate::types::content::{
    Base64ImageSource, ContentBlock, ImageBlock, ImageSource, TextBlock, ThinkingBlock,
    ToolResultBlock, ToolResultContent, ToolUseBlock, UserContent,
};
use crate::types::messages::{
    AssistantMessage, AssistantMessageInner, Message, StreamEvent, UserMessage, UserMessageInner,
};
use crate::wire::{SessionUpdate, WireContentBlock};

// ── Wire ContentBlock → Unified ContentBlock ─────────────────────────────────

/// Translate a single wire content block into the unified [`ContentBlock`] type.
///
/// The mapping is:
///
/// | Wire `type`      | Unified variant              |
/// |-----------------|------------------------------|
/// | `"text"`         | `ContentBlock::Text`         |
/// | `"image"`        | `ContentBlock::Image`        |
/// | `"resource_link"`| `ContentBlock::Text` (inline markdown link) |
/// | `"resource"`     | `ContentBlock::Text` (resource text field)  |
/// | anything else    | `ContentBlock::Text` (labelled fallback)     |
pub(crate) fn translate_content_block(wire: &WireContentBlock) -> ContentBlock {
    match wire.content_type.as_str() {
        "text" => ContentBlock::Text(TextBlock {
            text: wire.text.clone().unwrap_or_default(),
            extra: Value::Object(Default::default()),
        }),
        "image" => ContentBlock::Image(ImageBlock {
            source: ImageSource::Base64(Base64ImageSource {
                media_type: wire
                    .mime_type
                    .clone()
                    .unwrap_or_else(|| "image/png".to_string()),
                data: wire.data.clone().unwrap_or_default(),
            }),
            extra: Value::Object(Default::default()),
        }),
        "resource_link" => {
            let name = wire.name.as_deref().unwrap_or("resource");
            let uri = wire.uri.as_deref().unwrap_or("");
            ContentBlock::Text(TextBlock {
                text: format!("[{name}]({uri})"),
                extra: Value::Object(Default::default()),
            })
        }
        "resource" => {
            let text = wire
                .resource
                .as_ref()
                .and_then(|r| r.get("text"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            ContentBlock::Text(TextBlock {
                text,
                extra: Value::Object(Default::default()),
            })
        }
        other => ContentBlock::Text(TextBlock {
            text: format!("[unknown content type: {other}]"),
            extra: wire.extra.clone(),
        }),
    }
}

// ── SessionUpdate → Message(s) ───────────────────────────────────────────────

/// Accumulated state for a single prompt turn, used to produce typed
/// [`Message`] values from a sequence of streaming [`SessionUpdate`] events.
///
/// Create one `TranslationContext` per session and call [`translate`] for each
/// update as it arrives. Call [`reset_turn`] between turns to clear
/// accumulated text and in-flight tool call state.
///
/// [`translate`]: TranslationContext::translate
/// [`reset_turn`]: TranslationContext::reset_turn
pub(crate) struct TranslationContext {
    /// Stable session identifier; stamped onto every emitted [`Message`].
    pub session_id: String,
    /// Model identifier; included in [`AssistantMessage`] payloads.
    pub model: String,
    accumulated_text: String,
    accumulated_thinking: String,
    tool_calls: HashMap<String, ToolCallState>,
    tool_input_cache: Option<ToolInputCache>,
}

/// Internal state for an in-progress tool call.
struct ToolCallState {
    id: String,
    name: String,
    input: Value,
}

impl TranslationContext {
    /// Create a new context for the given session and model.
    #[allow(dead_code)]
    pub fn new(session_id: String, model: String) -> Self {
        Self {
            session_id,
            model,
            accumulated_text: String::new(),
            accumulated_thinking: String::new(),
            tool_calls: HashMap::new(),
            tool_input_cache: None,
        }
    }

    /// Create a new context wired to a [`ToolInputCache`] populated by the permission handler.
    /// When a cache is provided, tool call inputs captured during permission requests are
    /// embedded in the emitted [`ToolUseBlock`]s.
    pub fn new_with_cache(session_id: String, model: String, cache: ToolInputCache) -> Self {
        Self {
            session_id,
            model,
            accumulated_text: String::new(),
            accumulated_thinking: String::new(),
            tool_calls: HashMap::new(),
            tool_input_cache: Some(cache),
        }
    }

    /// Translate a [`SessionUpdate`] into zero or more [`Message`] values.
    ///
    /// Most variants produce exactly one message. `ToolCallUpdate` with a
    /// terminal status (`"completed"` or `"failed"`) emits three messages:
    /// a `StreamEvent`, the corresponding `AssistantMessage` carrying the
    /// `ToolUse` block, and an `AssistantMessage` carrying the `ToolResult`
    /// block.
    pub fn translate(&mut self, update: SessionUpdate) -> Vec<Message> {
        match update {
            SessionUpdate::AgentThoughtChunk { content } => {
                if let Some(text) = content.text {
                    self.accumulated_thinking.push_str(&text);
                }
                vec![Message::Assistant(AssistantMessage {
                    message: AssistantMessageInner {
                        role: "assistant".to_string(),
                        content: vec![ContentBlock::Thinking(ThinkingBlock {
                            thinking: self.accumulated_thinking.clone(),
                            extra: Value::Object(Default::default()),
                        })],
                        model: self.model.clone(),
                        stop_reason: String::new(),
                        stop_sequence: None,
                        extra: Value::Object(Default::default()),
                    },
                    session_id: self.session_id.clone(),
                })]
            }

            SessionUpdate::AgentMessageChunk { content } => {
                if let Some(text) = content.text {
                    self.accumulated_text.push_str(&text);
                }
                vec![Message::Assistant(AssistantMessage {
                    message: AssistantMessageInner {
                        role: "assistant".to_string(),
                        content: vec![ContentBlock::Text(TextBlock {
                            text: self.accumulated_text.clone(),
                            extra: Value::Object(Default::default()),
                        })],
                        model: self.model.clone(),
                        stop_reason: String::new(),
                        stop_sequence: None,
                        extra: Value::Object(Default::default()),
                    },
                    session_id: self.session_id.clone(),
                })]
            }

            SessionUpdate::ToolCall {
                tool_call_id,
                title,
                kind,
                status,
                locations,
            } => {
                let cached_input = self.cached_input(&tool_call_id);

                self.tool_calls
                    .entry(tool_call_id.clone())
                    .or_insert(ToolCallState {
                        id: tool_call_id.clone(),
                        name: title.clone(),
                        input: cached_input,
                    });

                let locations_value =
                    serde_json::to_value(&locations).unwrap_or(Value::Array(Vec::new()));

                vec![Message::StreamEvent(StreamEvent {
                    event_type: "tool_call".to_string(),
                    data: json!({
                        "tool_call_id": tool_call_id,
                        "title": title,
                        "kind": kind,
                        "status": status,
                        "locations": locations_value,
                    }),
                    session_id: self.session_id.clone(),
                })]
            }

            SessionUpdate::ToolCallUpdate {
                tool_call_id,
                status,
                content,
            } => {
                let mut messages = vec![Message::StreamEvent(StreamEvent {
                    event_type: "tool_call_update".to_string(),
                    data: json!({
                        "tool_call_id": &tool_call_id,
                        "status": &status,
                    }),
                    session_id: self.session_id.clone(),
                })];

                if status == "completed" || status == "failed" {
                    // Auto-register if the CLI skipped the tool_call notification
                    // (e.g. when the call went through the permission request flow).
                    if !self.tool_calls.contains_key(&tool_call_id) {
                        let cached_input = self.cached_input(&tool_call_id);

                        // Derive tool name from the tool_call_id prefix (e.g. "run_shell_command-123…").
                        let name = tool_call_id
                            .rsplit_once('-')
                            .map(|(prefix, _)| prefix.to_string())
                            .unwrap_or_else(|| tool_call_id.clone());

                        self.tool_calls.insert(
                            tool_call_id.clone(),
                            ToolCallState {
                                id: tool_call_id.clone(),
                                name,
                                input: cached_input,
                            },
                        );
                    }

                    if let Some(state) = self.tool_calls.get(&tool_call_id) {
                        messages.push(Message::Assistant(AssistantMessage {
                            message: AssistantMessageInner {
                                role: "assistant".to_string(),
                                content: vec![ContentBlock::ToolUse(ToolUseBlock {
                                    id: state.id.clone(),
                                    name: state.name.clone(),
                                    input: state.input.clone(),
                                    extra: Value::Object(Default::default()),
                                })],
                                model: self.model.clone(),
                                stop_reason: String::new(),
                                stop_sequence: None,
                                extra: Value::Object(Default::default()),
                            },
                            session_id: self.session_id.clone(),
                        }));

                        let result_content = content
                            .map(|blocks| {
                                blocks
                                    .iter()
                                    .filter_map(|b| match b.content_type.as_str() {
                                        "text" => Some(ToolResultContent::Text {
                                            text: b.text.clone().unwrap_or_default(),
                                        }),
                                        // The CLI wraps tool output in a "content" block
                                        // with the actual text nested as extra.content.text.
                                        "content" => {
                                            let text = b
                                                .extra
                                                .get("content")
                                                .and_then(|c| c.get("text"))
                                                .and_then(|t| t.as_str())
                                                .unwrap_or("")
                                                .to_string();
                                            if text.is_empty() {
                                                None
                                            } else {
                                                Some(ToolResultContent::Text { text })
                                            }
                                        }
                                        _ => None,
                                    })
                                    .collect::<Vec<_>>()
                            })
                            .unwrap_or_default();

                        let is_error = status == "failed";

                        messages.push(Message::Assistant(AssistantMessage {
                            message: AssistantMessageInner {
                                role: "assistant".to_string(),
                                content: vec![ContentBlock::ToolResult(ToolResultBlock {
                                    tool_use_id: tool_call_id,
                                    content: result_content,
                                    is_error,
                                    extra: Value::Object(Default::default()),
                                })],
                                model: self.model.clone(),
                                stop_reason: String::new(),
                                stop_sequence: None,
                                extra: Value::Object(Default::default()),
                            },
                            session_id: self.session_id.clone(),
                        }));
                    }
                }

                messages
            }

            SessionUpdate::Plan { entries } => {
                vec![Message::StreamEvent(StreamEvent {
                    event_type: "plan".to_string(),
                    data: serde_json::to_value(&entries).unwrap_or(Value::Array(Vec::new())),
                    session_id: self.session_id.clone(),
                })]
            }

            SessionUpdate::UsageUpdate { cost, size, used } => {
                vec![Message::StreamEvent(StreamEvent {
                    event_type: "usage_update".to_string(),
                    data: json!({ "cost": cost, "size": size, "used": used }),
                    session_id: self.session_id.clone(),
                })]
            }

            SessionUpdate::SessionInfoUpdate { title } => {
                vec![Message::StreamEvent(StreamEvent {
                    event_type: "session_info".to_string(),
                    data: json!({ "title": title }),
                    session_id: self.session_id.clone(),
                })]
            }

            SessionUpdate::UserMessageChunk { content } => {
                let block = translate_content_block(&content);
                vec![Message::User(UserMessage {
                    message: UserMessageInner {
                        role: "user".to_string(),
                        content: vec![block],
                        extra: Value::Object(Default::default()),
                    },
                    session_id: self.session_id.clone(),
                })]
            }

            SessionUpdate::Unknown { kind, data } => {
                vec![Message::StreamEvent(StreamEvent {
                    event_type: kind,
                    data,
                    session_id: self.session_id.clone(),
                })]
            }
        }
    }

    /// Look up the cached raw input for a tool call, falling back to an empty object.
    fn cached_input(&self, tool_call_id: &str) -> Value {
        self.tool_input_cache
            .as_ref()
            .and_then(|cache| cache.lock().ok()?.get(tool_call_id).cloned())
            .unwrap_or_else(|| Value::Object(Default::default()))
    }

    /// Reset accumulated state in preparation for the next prompt turn.
    ///
    /// Clears the accumulated text buffer, the thinking buffer, and all
    /// in-flight tool call state. Call this after a turn completes (i.e.
    /// after a `session/prompt` result is received) before processing the
    /// next turn's stream of updates.
    pub fn reset_turn(&mut self) {
        self.accumulated_text.clear();
        self.accumulated_thinking.clear();
        self.tool_calls.clear();
    }
}

// ── UserContent → WireContentBlock ───────────────────────────────────────────

/// Translate outbound [`UserContent`] into the wire [`WireContentBlock`] format
/// required by `session/prompt` requests.
pub(crate) fn user_content_to_wire(content: &UserContent) -> WireContentBlock {
    match content {
        UserContent::Text { text } => WireContentBlock {
            content_type: "text".to_string(),
            text: Some(text.clone()),
            ..Default::default()
        },
        UserContent::Image { source } => match source {
            ImageSource::Base64(b64) => WireContentBlock {
                content_type: "image".to_string(),
                data: Some(b64.data.clone()),
                mime_type: Some(b64.media_type.clone()),
                ..Default::default()
            },
            ImageSource::Url(url_src) => WireContentBlock {
                content_type: "image".to_string(),
                uri: Some(url_src.url.clone()),
                ..Default::default()
            },
        },
    }
}

/// Translate a plain-text prompt string into a one-element list of wire content
/// blocks suitable for the `prompt` field of a `session/prompt` request.
#[allow(dead_code)]
pub(crate) fn prompt_to_wire(prompt: &str) -> Vec<WireContentBlock> {
    vec![WireContentBlock {
        content_type: "text".to_string(),
        text: Some(prompt.to_string()),
        ..Default::default()
    }]
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── translate_content_block ───────────────────────────────────────────────

    #[test]
    fn test_translate_text_content_block() {
        let wire = WireContentBlock {
            content_type: "text".to_string(),
            text: Some("Hello, world!".to_string()),
            ..Default::default()
        };
        let block = translate_content_block(&wire);
        match block {
            ContentBlock::Text(t) => assert_eq!(t.text, "Hello, world!"),
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_image_content_block() {
        let wire = WireContentBlock {
            content_type: "image".to_string(),
            data: Some("iVBORw0KGgo=".to_string()),
            mime_type: Some("image/png".to_string()),
            ..Default::default()
        };
        let block = translate_content_block(&wire);
        match block {
            ContentBlock::Image(img) => match img.source {
                ImageSource::Base64(b64) => {
                    assert_eq!(b64.media_type, "image/png");
                    assert_eq!(b64.data, "iVBORw0KGgo=");
                }
                other => panic!("expected Base64 source, got {other:?}"),
            },
            other => panic!("expected Image, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_image_defaults_mime_type() {
        // When mime_type is absent the translation must fall back to "image/png".
        let wire = WireContentBlock {
            content_type: "image".to_string(),
            data: Some("abc".to_string()),
            ..Default::default()
        };
        let block = translate_content_block(&wire);
        match block {
            ContentBlock::Image(img) => match img.source {
                ImageSource::Base64(b64) => assert_eq!(b64.media_type, "image/png"),
                _ => panic!("expected Base64"),
            },
            _ => panic!("expected Image"),
        }
    }

    #[test]
    fn test_translate_resource_link() {
        let wire = WireContentBlock {
            content_type: "resource_link".to_string(),
            name: Some("README".to_string()),
            uri: Some("file:///project/README.md".to_string()),
            ..Default::default()
        };
        let block = translate_content_block(&wire);
        match block {
            ContentBlock::Text(t) => {
                assert_eq!(t.text, "[README](file:///project/README.md)");
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_resource_link_missing_fields_use_defaults() {
        let wire = WireContentBlock {
            content_type: "resource_link".to_string(),
            ..Default::default()
        };
        let block = translate_content_block(&wire);
        match block {
            ContentBlock::Text(t) => assert_eq!(t.text, "[resource]()"),
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_resource_type() {
        let wire = WireContentBlock {
            content_type: "resource".to_string(),
            resource: Some(json!({ "text": "file contents here" })),
            ..Default::default()
        };
        let block = translate_content_block(&wire);
        match block {
            ContentBlock::Text(t) => assert_eq!(t.text, "file contents here"),
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_unknown_content_type() {
        let wire = WireContentBlock {
            content_type: "some_future_type".to_string(),
            ..Default::default()
        };
        let block = translate_content_block(&wire);
        match block {
            ContentBlock::Text(t) => {
                assert!(
                    t.text.contains("some_future_type"),
                    "fallback text must name the unknown type; got: {}", t.text
                );
            }
            other => panic!("expected Text fallback, got {other:?}"),
        }
    }

    // ── TranslationContext helpers ────────────────────────────────────────────

    fn make_ctx() -> TranslationContext {
        TranslationContext::new("sess-test".to_string(), "gemini-2.5-pro".to_string())
    }

    // ── TranslationContext::translate ─────────────────────────────────────────

    #[test]
    fn test_translate_thought_chunk_accumulates() {
        let mut ctx = make_ctx();
        let text_block = WireContentBlock {
            content_type: "text".to_string(),
            text: Some("part1 ".to_string()),
            ..Default::default()
        };
        let msgs = ctx.translate(SessionUpdate::AgentThoughtChunk {
            content: text_block,
        });
        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::Assistant(m) => match &m.message.content[0] {
                ContentBlock::Thinking(t) => assert_eq!(t.thinking, "part1 "),
                other => panic!("expected Thinking block, got {other:?}"),
            },
            other => panic!("expected Assistant, got {other:?}"),
        }

        // Second chunk must append.
        let text_block2 = WireContentBlock {
            content_type: "text".to_string(),
            text: Some("part2".to_string()),
            ..Default::default()
        };
        let msgs2 = ctx.translate(SessionUpdate::AgentThoughtChunk {
            content: text_block2,
        });
        match &msgs2[0] {
            Message::Assistant(m) => match &m.message.content[0] {
                ContentBlock::Thinking(t) => assert_eq!(t.thinking, "part1 part2"),
                other => panic!("expected Thinking, got {other:?}"),
            },
            other => panic!("expected Assistant, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_message_chunk_accumulates() {
        let mut ctx = make_ctx();

        let chunk1 = WireContentBlock {
            content_type: "text".to_string(),
            text: Some("Hello".to_string()),
            ..Default::default()
        };
        ctx.translate(SessionUpdate::AgentMessageChunk { content: chunk1 });

        let chunk2 = WireContentBlock {
            content_type: "text".to_string(),
            text: Some(", world".to_string()),
            ..Default::default()
        };
        let msgs = ctx.translate(SessionUpdate::AgentMessageChunk { content: chunk2 });

        match &msgs[0] {
            Message::Assistant(m) => match &m.message.content[0] {
                ContentBlock::Text(t) => assert_eq!(t.text, "Hello, world"),
                other => panic!("expected Text, got {other:?}"),
            },
            other => panic!("expected Assistant, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_tool_call_emits_stream_event() {
        let mut ctx = make_ctx();
        let msgs = ctx.translate(SessionUpdate::ToolCall {
            tool_call_id: "tc-001".to_string(),
            title: "Read file".to_string(),
            kind: "read_file".to_string(),
            status: "in_progress".to_string(),
            locations: vec![],
        });

        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::StreamEvent(ev) => {
                assert_eq!(ev.event_type, "tool_call");
                assert_eq!(ev.data["tool_call_id"], "tc-001");
                assert_eq!(ev.data["title"], "Read file");
                assert_eq!(ev.data["kind"], "read_file");
                assert_eq!(ev.data["status"], "in_progress");
                assert_eq!(ev.session_id, "sess-test");
            }
            other => panic!("expected StreamEvent, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_tool_call_update_intermediate_emits_one_message() {
        let mut ctx = make_ctx();
        // Register the tool call first so there is state to look up.
        ctx.translate(SessionUpdate::ToolCall {
            tool_call_id: "tc-001".to_string(),
            title: "Read file".to_string(),
            kind: "read_file".to_string(),
            status: "in_progress".to_string(),
            locations: vec![],
        });

        let msgs = ctx.translate(SessionUpdate::ToolCallUpdate {
            tool_call_id: "tc-001".to_string(),
            status: "running".to_string(),
            content: None,
        });
        // Non-terminal status → only the StreamEvent.
        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::StreamEvent(ev) => assert_eq!(ev.event_type, "tool_call_update"),
            other => panic!("expected StreamEvent, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_tool_call_update_completed_emits_three_messages() {
        let mut ctx = make_ctx();
        ctx.translate(SessionUpdate::ToolCall {
            tool_call_id: "tc-002".to_string(),
            title: "Shell".to_string(),
            kind: "shell".to_string(),
            status: "in_progress".to_string(),
            locations: vec![],
        });

        let result_block = WireContentBlock {
            content_type: "text".to_string(),
            text: Some("output text".to_string()),
            ..Default::default()
        };

        let msgs = ctx.translate(SessionUpdate::ToolCallUpdate {
            tool_call_id: "tc-002".to_string(),
            status: "completed".to_string(),
            content: Some(vec![result_block]),
        });

        // StreamEvent + ToolUse AssistantMessage + ToolResult AssistantMessage.
        assert_eq!(msgs.len(), 3);

        match &msgs[0] {
            Message::StreamEvent(ev) => assert_eq!(ev.event_type, "tool_call_update"),
            other => panic!("expected StreamEvent at index 0, got {other:?}"),
        }

        match &msgs[1] {
            Message::Assistant(m) => match &m.message.content[0] {
                ContentBlock::ToolUse(tu) => {
                    assert_eq!(tu.id, "tc-002");
                    assert_eq!(tu.name, "Shell");
                }
                other => panic!("expected ToolUse at index 1, got {other:?}"),
            },
            other => panic!("expected Assistant at index 1, got {other:?}"),
        }

        match &msgs[2] {
            Message::Assistant(m) => match &m.message.content[0] {
                ContentBlock::ToolResult(tr) => {
                    assert_eq!(tr.tool_use_id, "tc-002");
                    assert!(!tr.is_error);
                    assert_eq!(tr.content.len(), 1);
                    match &tr.content[0] {
                        ToolResultContent::Text { text } => assert_eq!(text, "output text"),
                        other => panic!("expected Text result, got {other:?}"),
                    }
                }
                other => panic!("expected ToolResult at index 2, got {other:?}"),
            },
            other => panic!("expected Assistant at index 2, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_tool_call_failed_sets_is_error() {
        let mut ctx = make_ctx();
        ctx.translate(SessionUpdate::ToolCall {
            tool_call_id: "tc-003".to_string(),
            title: "Shell".to_string(),
            kind: "shell".to_string(),
            status: "in_progress".to_string(),
            locations: vec![],
        });

        let msgs = ctx.translate(SessionUpdate::ToolCallUpdate {
            tool_call_id: "tc-003".to_string(),
            status: "failed".to_string(),
            content: None,
        });

        assert_eq!(msgs.len(), 3);
        match &msgs[2] {
            Message::Assistant(m) => match &m.message.content[0] {
                ContentBlock::ToolResult(tr) => assert!(tr.is_error),
                other => panic!("expected ToolResult, got {other:?}"),
            },
            other => panic!("expected Assistant, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_plan() {
        use crate::wire::WirePlanEntry;
        let mut ctx = make_ctx();
        let entries = vec![
            WirePlanEntry {
                content: "Step 1".to_string(),
                priority: "high".to_string(),
                status: "pending".to_string(),
                extra: Value::Object(Default::default()),
            },
            WirePlanEntry {
                content: "Step 2".to_string(),
                priority: "normal".to_string(),
                status: "pending".to_string(),
                extra: Value::Object(Default::default()),
            },
        ];
        let msgs = ctx.translate(SessionUpdate::Plan { entries });
        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::StreamEvent(ev) => {
                assert_eq!(ev.event_type, "plan");
                assert!(ev.data.is_array());
                assert_eq!(ev.data.as_array().unwrap().len(), 2);
            }
            other => panic!("expected StreamEvent, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_usage_update() {
        let mut ctx = make_ctx();
        let msgs = ctx.translate(SessionUpdate::UsageUpdate {
            cost: Some(0.0042),
            size: None,
            used: None,
        });
        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::StreamEvent(ev) => {
                assert_eq!(ev.event_type, "usage_update");
                assert!((ev.data["cost"].as_f64().unwrap() - 0.0042_f64).abs() < f64::EPSILON);
            }
            other => panic!("expected StreamEvent, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_session_info_update() {
        let mut ctx = make_ctx();
        let msgs = ctx.translate(SessionUpdate::SessionInfoUpdate {
            title: Some("My session".to_string()),
        });
        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::StreamEvent(ev) => {
                assert_eq!(ev.event_type, "session_info");
                assert_eq!(ev.data["title"], "My session");
            }
            other => panic!("expected StreamEvent, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_unknown_session_update() {
        let mut ctx = make_ctx();
        let msgs = ctx.translate(SessionUpdate::Unknown {
            kind: "future_event".to_string(),
            data: json!({ "foo": 42 }),
        });
        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::StreamEvent(ev) => {
                assert_eq!(ev.event_type, "future_event");
                assert_eq!(ev.data["foo"], 42);
                assert_eq!(ev.session_id, "sess-test");
            }
            other => panic!("expected StreamEvent, got {other:?}"),
        }
    }

    #[test]
    fn test_translate_user_message_chunk() {
        let mut ctx = make_ctx();
        let wire = WireContentBlock {
            content_type: "text".to_string(),
            text: Some("User said this".to_string()),
            ..Default::default()
        };
        let msgs = ctx.translate(SessionUpdate::UserMessageChunk { content: wire });
        assert_eq!(msgs.len(), 1);
        match &msgs[0] {
            Message::User(u) => {
                assert_eq!(u.session_id, "sess-test");
                match &u.message.content[0] {
                    ContentBlock::Text(t) => assert_eq!(t.text, "User said this"),
                    other => panic!("expected Text, got {other:?}"),
                }
            }
            other => panic!("expected User, got {other:?}"),
        }
    }

    #[test]
    fn test_reset_turn() {
        let mut ctx = make_ctx();

        // Accumulate some text and thought content.
        ctx.translate(SessionUpdate::AgentMessageChunk {
            content: WireContentBlock {
                content_type: "text".to_string(),
                text: Some("accumulated".to_string()),
                ..Default::default()
            },
        });
        ctx.translate(SessionUpdate::AgentThoughtChunk {
            content: WireContentBlock {
                content_type: "text".to_string(),
                text: Some("thinking".to_string()),
                ..Default::default()
            },
        });
        ctx.translate(SessionUpdate::ToolCall {
            tool_call_id: "tc-x".to_string(),
            title: "T".to_string(),
            kind: "k".to_string(),
            status: "s".to_string(),
            locations: vec![],
        });

        assert!(!ctx.accumulated_text.is_empty());
        assert!(!ctx.accumulated_thinking.is_empty());
        assert!(!ctx.tool_calls.is_empty());

        ctx.reset_turn();

        assert!(ctx.accumulated_text.is_empty(), "text must be cleared");
        assert!(ctx.accumulated_thinking.is_empty(), "thinking must be cleared");
        assert!(ctx.tool_calls.is_empty(), "tool calls must be cleared");
    }

    // ── prompt_to_wire ────────────────────────────────────────────────────────

    #[test]
    fn test_prompt_to_wire() {
        let blocks = prompt_to_wire("Say hello");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].content_type, "text");
        assert_eq!(blocks[0].text.as_deref(), Some("Say hello"));
    }

    // ── user_content_to_wire ──────────────────────────────────────────────────

    #[test]
    fn test_user_content_to_wire_text() {
        let uc = UserContent::Text {
            text: "ping".to_string(),
        };
        let wire = user_content_to_wire(&uc);
        assert_eq!(wire.content_type, "text");
        assert_eq!(wire.text.as_deref(), Some("ping"));
        assert!(wire.data.is_none());
        assert!(wire.mime_type.is_none());
    }

    #[test]
    fn test_user_content_to_wire_image_base64() {
        let uc = UserContent::image_base64("image/jpeg", "deadbeef==");
        let wire = user_content_to_wire(&uc);
        assert_eq!(wire.content_type, "image");
        assert_eq!(wire.data.as_deref(), Some("deadbeef=="));
        assert_eq!(wire.mime_type.as_deref(), Some("image/jpeg"));
        assert!(wire.text.is_none());
    }

    #[test]
    fn test_user_content_to_wire_image_url() {
        let uc = UserContent::image_url("https://example.com/photo.png");
        let wire = user_content_to_wire(&uc);
        assert_eq!(wire.content_type, "image");
        assert_eq!(wire.uri.as_deref(), Some("https://example.com/photo.png"));
        assert!(wire.data.is_none());
    }
}