swink-agent 0.12.0

Core scaffolding for running LLM-powered agentic loops
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
//! Foundation types for the swink agent.
//!
//! This module defines every type that crosses a public boundary in the harness.
//! All other modules depend on it; it depends on nothing else in the crate.

mod custom_message;
pub mod message_codec;
mod model;

pub use custom_message::*;
pub use message_codec::{
    MessageSlot, SerializedCustomMessage, SerializedMessages, clone_messages_for_send,
    restore_messages, restore_single_custom, serialize_messages,
};
pub use model::*;

use std::collections::HashMap;
use std::fmt;
use std::ops::{Add, AddAssign};
use std::sync::Arc;

use serde::{Deserialize, Serialize};

// ─── Content ────────────────────────────────────────────────────────────────

/// The atomic unit of all message content.
///
/// Different variants are permitted in different message roles:
/// - `Text`: user, assistant, tool result
/// - `Thinking`: assistant only
/// - `ToolCall`: assistant only
/// - `Image`: user, tool result
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    /// A plain text string.
    Text { text: String },

    /// A reasoning / chain-of-thought string with an optional provider signature.
    Thinking {
        thinking: String,
        signature: Option<String>,
    },

    /// A tool invocation with an ID, tool name, parsed arguments, and an
    /// optional partial JSON buffer used during streaming.
    ToolCall {
        id: String,
        name: String,
        arguments: serde_json::Value,
        partial_json: Option<String>,
    },

    /// Image data from a supported source type.
    Image { source: ImageSource },

    /// An extension content block for plugin-defined types.
    ///
    /// Allows multimodal plugins to pass structured data without flattening to `Text`.
    Extension {
        type_name: String,
        data: serde_json::Value,
    },
}

impl ContentBlock {
    /// Extract concatenated text from a slice of content blocks.
    ///
    /// Returns the joined text of all `Text` variants, ignoring other block types.
    pub fn extract_text(blocks: &[Self]) -> String {
        let mut result = String::new();
        for block in blocks {
            if let Self::Text { text } = block {
                result.push_str(text);
            }
        }
        result
    }
}

/// Source for image data.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ImageSource {
    /// Base64-encoded image data with a media type.
    Base64 { media_type: String, data: String },

    /// A URL pointing to an image.
    Url { url: String, media_type: String },

    /// A local file path pointing to an image.
    File {
        path: std::path::PathBuf,
        media_type: String,
    },
}

// ─── Messages ───────────────────────────────────────────────────────────────

/// A message from the user.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserMessage {
    pub content: Vec<ContentBlock>,
    pub timestamp: u64,
    /// Provider-agnostic cache hint for this message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_hint: Option<crate::context_cache::CacheHint>,
}

impl UserMessage {
    /// Create a new user message with the given content.
    ///
    /// `timestamp` defaults to now and `cache_hint` defaults to `None`.
    #[must_use]
    pub fn new(content: Vec<ContentBlock>) -> Self {
        Self {
            content,
            timestamp: crate::util::now_timestamp(),
            cache_hint: None,
        }
    }

    #[must_use]
    pub const fn with_timestamp(mut self, timestamp: u64) -> Self {
        self.timestamp = timestamp;
        self
    }

    #[must_use]
    pub fn with_cache_hint(mut self, cache_hint: crate::context_cache::CacheHint) -> Self {
        self.cache_hint = Some(cache_hint);
        self
    }
}

/// A message from the assistant (LLM response).
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantMessage {
    pub content: Vec<ContentBlock>,
    pub provider: String,
    pub model_id: String,
    pub usage: Usage,
    pub cost: Cost,
    pub stop_reason: StopReason,
    pub error_message: Option<String>,
    /// Structured error classification carried from the stream `Error` event.
    ///
    /// When present, the agent loop uses this to classify the error without
    /// falling back to string matching on `error_message`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_kind: Option<crate::stream_error_kind::StreamErrorKind>,
    pub timestamp: u64,
    /// Provider-agnostic cache hint for this message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_hint: Option<crate::context_cache::CacheHint>,
}

impl AssistantMessage {
    /// Create a new assistant message with the given content, provider, and model ID.
    ///
    /// `usage`/`cost` default to zero, `stop_reason` defaults to
    /// [`StopReason::Stop`], `error_message`/`error_kind` default to `None`,
    /// `timestamp` defaults to now, and `cache_hint` defaults to `None`.
    #[must_use]
    pub fn new(
        content: Vec<ContentBlock>,
        provider: impl Into<String>,
        model_id: impl Into<String>,
    ) -> Self {
        Self {
            content,
            provider: provider.into(),
            model_id: model_id.into(),
            usage: Usage::default(),
            cost: Cost::default(),
            stop_reason: StopReason::Stop,
            error_message: None,
            error_kind: None,
            timestamp: crate::util::now_timestamp(),
            cache_hint: None,
        }
    }

    #[must_use]
    pub fn with_usage(mut self, usage: Usage) -> Self {
        self.usage = usage;
        self
    }

    #[must_use]
    pub fn with_cost(mut self, cost: Cost) -> Self {
        self.cost = cost;
        self
    }

    #[must_use]
    pub const fn with_stop_reason(mut self, stop_reason: StopReason) -> Self {
        self.stop_reason = stop_reason;
        self
    }

    #[must_use]
    pub fn with_error_message(mut self, error_message: impl Into<String>) -> Self {
        self.error_message = Some(error_message.into());
        self
    }

    #[must_use]
    pub const fn with_error_kind(
        mut self,
        error_kind: crate::stream_error_kind::StreamErrorKind,
    ) -> Self {
        self.error_kind = Some(error_kind);
        self
    }

    #[must_use]
    pub const fn with_timestamp(mut self, timestamp: u64) -> Self {
        self.timestamp = timestamp;
        self
    }

    #[must_use]
    pub fn with_cache_hint(mut self, cache_hint: crate::context_cache::CacheHint) -> Self {
        self.cache_hint = Some(cache_hint);
        self
    }
}

/// Returns a message whose `provider` and `model_id` are **empty strings**.
///
/// This is convenient as a builder base in tests, but it is not a valid
/// provider response on its own — pricing and telemetry keyed on those
/// identifiers will not resolve. Construct real messages with
/// [`AssistantMessage::new`], which requires both identifiers.
impl Default for AssistantMessage {
    fn default() -> Self {
        Self::new(Vec::new(), String::new(), String::new())
    }
}

/// The result of a tool execution, sent back to the LLM.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolResultMessage {
    pub tool_call_id: String,
    pub content: Vec<ContentBlock>,
    pub is_error: bool,
    pub timestamp: u64,
    /// Structured data for display — not sent to the LLM.
    #[serde(default)]
    pub details: serde_json::Value,
    /// Provider-agnostic cache hint for this message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_hint: Option<crate::context_cache::CacheHint>,
}

impl ToolResultMessage {
    /// Create a new tool result message.
    ///
    /// `is_error` defaults to `false`, `timestamp` defaults to now,
    /// `details` defaults to `Value::Null`, and `cache_hint` defaults to `None`.
    #[must_use]
    pub fn new(tool_call_id: impl Into<String>, content: Vec<ContentBlock>) -> Self {
        Self {
            tool_call_id: tool_call_id.into(),
            content,
            is_error: false,
            timestamp: crate::util::now_timestamp(),
            details: serde_json::Value::Null,
            cache_hint: None,
        }
    }

    #[must_use]
    pub const fn with_is_error(mut self, is_error: bool) -> Self {
        self.is_error = is_error;
        self
    }

    #[must_use]
    pub fn with_details(mut self, details: serde_json::Value) -> Self {
        self.details = details;
        self
    }

    #[must_use]
    pub const fn with_timestamp(mut self, timestamp: u64) -> Self {
        self.timestamp = timestamp;
        self
    }

    #[must_use]
    pub fn with_cache_hint(mut self, cache_hint: crate::context_cache::CacheHint) -> Self {
        self.cache_hint = Some(cache_hint);
        self
    }
}

/// A discriminated union of the three LLM message roles.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "snake_case")]
pub enum LlmMessage {
    User(UserMessage),
    Assistant(AssistantMessage),
    ToolResult(ToolResultMessage),
}

// ─── Usage & Cost ───────────────────────────────────────────────────────────

/// Token usage counters for an LLM response.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Usage {
    pub input: u64,
    pub output: u64,
    pub cache_read: u64,
    pub cache_write: u64,
    pub total: u64,
    /// Provider-specific extra metrics (reasoning tokens, search tokens, etc.).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub extra: HashMap<String, u64>,
}

impl Usage {
    /// Merge another `Usage` into this one by summing all fields.
    pub fn merge(&mut self, other: &Self) {
        *self += other.clone();
    }

    #[must_use]
    pub const fn with_input(mut self, input: u64) -> Self {
        self.input = input;
        self
    }

    #[must_use]
    pub const fn with_output(mut self, output: u64) -> Self {
        self.output = output;
        self
    }

    #[must_use]
    pub const fn with_cache_read(mut self, cache_read: u64) -> Self {
        self.cache_read = cache_read;
        self
    }

    #[must_use]
    pub const fn with_cache_write(mut self, cache_write: u64) -> Self {
        self.cache_write = cache_write;
        self
    }

    #[must_use]
    pub const fn with_total(mut self, total: u64) -> Self {
        self.total = total;
        self
    }

    #[must_use]
    pub fn with_extra(mut self, extra: HashMap<String, u64>) -> Self {
        self.extra = extra;
        self
    }
}

impl Add for Usage {
    type Output = Self;

    fn add(mut self, rhs: Self) -> Self::Output {
        self += rhs;
        self
    }
}

impl AddAssign for Usage {
    fn add_assign(&mut self, rhs: Self) {
        self.input += rhs.input;
        self.output += rhs.output;
        self.cache_read += rhs.cache_read;
        self.cache_write += rhs.cache_write;
        self.total += rhs.total;
        for (k, v) in rhs.extra {
            *self.extra.entry(k).or_insert(0) += v;
        }
    }
}

/// Per-category and total cost breakdown (floating-point currency values).
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Cost {
    pub input: f64,
    pub output: f64,
    pub cache_read: f64,
    pub cache_write: f64,
    pub total: f64,
    /// Provider-specific extra cost categories.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub extra: HashMap<String, f64>,
}

impl Cost {
    /// Returns `true` when every cost category — including [`Cost::extra`] — is zero.
    ///
    /// Used to detect an adapter that did not price its own response, so the
    /// agent loop can fall back to catalog pricing via
    /// [`price_assistant_message`](crate::price_assistant_message).
    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.input == 0.0
            && self.output == 0.0
            && self.cache_read == 0.0
            && self.cache_write == 0.0
            && self.total == 0.0
            && self.extra.values().all(|v| *v == 0.0)
    }

    #[must_use]
    pub const fn with_input(mut self, input: f64) -> Self {
        self.input = input;
        self
    }

    #[must_use]
    pub const fn with_output(mut self, output: f64) -> Self {
        self.output = output;
        self
    }

    #[must_use]
    pub const fn with_cache_read(mut self, cache_read: f64) -> Self {
        self.cache_read = cache_read;
        self
    }

    #[must_use]
    pub const fn with_cache_write(mut self, cache_write: f64) -> Self {
        self.cache_write = cache_write;
        self
    }

    #[must_use]
    pub const fn with_total(mut self, total: f64) -> Self {
        self.total = total;
        self
    }

    #[must_use]
    pub fn with_extra(mut self, extra: HashMap<String, f64>) -> Self {
        self.extra = extra;
        self
    }
}

impl Add for Cost {
    type Output = Self;

    fn add(mut self, rhs: Self) -> Self::Output {
        self += rhs;
        self
    }
}

impl AddAssign for Cost {
    fn add_assign(&mut self, rhs: Self) {
        self.input += rhs.input;
        self.output += rhs.output;
        self.cache_read += rhs.cache_read;
        self.cache_write += rhs.cache_write;
        self.total += rhs.total;
        for (k, v) in rhs.extra {
            *self.extra.entry(k).or_insert(0.0) += v;
        }
    }
}

// ─── Stop Reason ────────────────────────────────────────────────────────────

/// Indicates why assistant generation ended.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    /// Natural end of generation.
    Stop,
    /// Output token limit reached.
    Length,
    /// Model requested a tool call.
    ToolUse,
    /// Cancelled by the caller.
    Aborted,
    /// An error occurred during generation.
    Error,
    /// Agent loop terminated due to a transfer signal.
    Transfer,
}

// ─── Agent Result ───────────────────────────────────────────────────────────

/// The value returned by non-streaming invocations.
#[non_exhaustive]
pub struct AgentResult {
    /// All new messages produced during the run.
    pub messages: Vec<AgentMessage>,
    /// The final stop reason from the last assistant message.
    pub stop_reason: StopReason,
    /// Aggregated token usage across all turns in the run.
    pub usage: Usage,
    /// Aggregated cost across all turns in the run.
    pub cost: Cost,
    /// Optional error string if the run ended in an error state.
    pub error: Option<String>,
    /// Optional transfer signal when the run ended with `StopReason::Transfer`.
    pub transfer_signal: Option<crate::transfer::TransferSignal>,
}

impl AgentResult {
    /// Create a new agent result from the produced messages and final stop reason.
    ///
    /// `usage`/`cost` default to zero, and `error`/`transfer_signal` default
    /// to `None`.
    #[must_use]
    pub fn new(messages: Vec<AgentMessage>, stop_reason: StopReason) -> Self {
        Self {
            messages,
            stop_reason,
            usage: Usage::default(),
            cost: Cost::default(),
            error: None,
            transfer_signal: None,
        }
    }

    #[must_use]
    pub fn with_usage(mut self, usage: Usage) -> Self {
        self.usage = usage;
        self
    }

    #[must_use]
    pub fn with_cost(mut self, cost: Cost) -> Self {
        self.cost = cost;
        self
    }

    #[must_use]
    pub fn with_error(mut self, error: impl Into<String>) -> Self {
        self.error = Some(error.into());
        self
    }

    #[must_use]
    pub fn with_transfer_signal(
        mut self,
        transfer_signal: crate::transfer::TransferSignal,
    ) -> Self {
        self.transfer_signal = Some(transfer_signal);
        self
    }

    /// Extract the text content from the last assistant message, if any.
    ///
    /// Iterates messages in reverse order, finds the first `Assistant` message,
    /// and returns its concatenated text blocks. Returns an empty string if no
    /// assistant message is found or if the assistant message contains no text.
    pub fn assistant_text(&self) -> String {
        self.messages
            .iter()
            .rev()
            .find_map(|msg| match msg {
                AgentMessage::Llm(LlmMessage::Assistant(a)) => Some(a),
                _ => None,
            })
            .map(|a| ContentBlock::extract_text(&a.content))
            .unwrap_or_default()
    }
}

impl fmt::Debug for AgentResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgentResult")
            .field("messages", &self.messages)
            .field("stop_reason", &self.stop_reason)
            .field("usage", &self.usage)
            .field("cost", &self.cost)
            .field("error", &self.error)
            .field("transfer_signal", &self.transfer_signal)
            .finish()
    }
}

// ─── Agent Context ──────────────────────────────────────────────────────────

/// The immutable snapshot passed into each loop turn.
///
/// Contains the system prompt, current message history, and the list of
/// available tools. The loop never mutates a context in place — each turn
/// produces a new snapshot.
#[non_exhaustive]
pub struct AgentContext {
    pub system_prompt: String,
    pub messages: Vec<AgentMessage>,
    /// The tools available during this turn.
    pub tools: Vec<Arc<dyn crate::tool::AgentTool>>,
}

impl AgentContext {
    /// Create a new agent context from the system prompt, message history,
    /// and available tools.
    #[must_use]
    pub fn new(
        system_prompt: impl Into<String>,
        messages: Vec<AgentMessage>,
        tools: Vec<Arc<dyn crate::tool::AgentTool>>,
    ) -> Self {
        Self {
            system_prompt: system_prompt.into(),
            messages,
            tools,
        }
    }
}

impl fmt::Debug for AgentContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgentContext")
            .field("system_prompt", &self.system_prompt)
            .field("messages", &self.messages)
            .field("tools", &format_args!("[{} tool(s)]", self.tools.len()))
            .finish()
    }
}

// ─── Serde Helpers ──────────────────────────────────────────────────────

fn serialize_arc_vec<S, T>(value: &Arc<Vec<T>>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
    T: Serialize,
{
    value.as_ref().serialize(serializer)
}

fn deserialize_arc_vec<'de, D, T>(deserializer: D) -> Result<Arc<Vec<T>>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de>,
{
    let v = Vec::<T>::deserialize(deserializer)?;
    Ok(Arc::new(v))
}

// ─── Turn Snapshot ──────────────────────────────────────────────────────

/// A point-in-time snapshot of agent state at a turn boundary.
///
/// Emitted as part of `TurnEnd` events to support external replay, auditing,
/// and debugging. Contains the full context at the moment the turn completed.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TurnSnapshot {
    /// Zero-based index of this turn within the current agent loop run.
    pub turn_index: usize,
    /// The LLM messages present in the context at the turn boundary.
    ///
    /// Each message is wrapped in an `Arc` shared with the loop's internal
    /// history and with neighbouring turn snapshots, so building a snapshot
    /// costs pointer bumps for the unchanged history prefix instead of a
    /// deep copy of every message on every turn. The outer `Arc` keeps
    /// forwarding the snapshot to multiple subscribers cheap. Serialization
    /// is transparent: the JSON shape is a plain array of messages.
    #[serde(
        serialize_with = "serialize_arc_vec",
        deserialize_with = "deserialize_arc_vec"
    )]
    pub messages: Arc<Vec<Arc<LlmMessage>>>,
    /// Accumulated token usage up to and including this turn.
    pub usage: Usage,
    /// Accumulated cost up to and including this turn.
    pub cost: Cost,
    /// Stop reason from the assistant message that ended this turn.
    pub stop_reason: StopReason,
    /// Session state changes during this turn, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state_delta: Option<crate::StateDelta>,
}

impl TurnSnapshot {
    /// Create a new turn snapshot from the turn index, message history, and
    /// stop reason.
    ///
    /// `usage`/`cost` default to zero and `state_delta` defaults to `None`.
    #[must_use]
    pub fn new(
        turn_index: usize,
        messages: Arc<Vec<Arc<LlmMessage>>>,
        stop_reason: StopReason,
    ) -> Self {
        Self {
            turn_index,
            messages,
            usage: Usage::default(),
            cost: Cost::default(),
            stop_reason,
            state_delta: None,
        }
    }

    #[must_use]
    pub fn with_usage(mut self, usage: Usage) -> Self {
        self.usage = usage;
        self
    }

    #[must_use]
    pub fn with_cost(mut self, cost: Cost) -> Self {
        self.cost = cost;
        self
    }

    #[must_use]
    pub fn with_state_delta(mut self, state_delta: crate::StateDelta) -> Self {
        self.state_delta = Some(state_delta);
        self
    }
}

// ─── Compile-time Send + Sync assertions ────────────────────────────────────

const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}

    assert_send_sync::<ContentBlock>();
    assert_send_sync::<ImageSource>();
    assert_send_sync::<UserMessage>();
    assert_send_sync::<AssistantMessage>();
    assert_send_sync::<ToolResultMessage>();
    assert_send_sync::<LlmMessage>();
    assert_send_sync::<AgentMessage>();
    assert_send_sync::<Usage>();
    assert_send_sync::<Cost>();
    assert_send_sync::<StopReason>();
    assert_send_sync::<ThinkingLevel>();
    assert_send_sync::<ThinkingBudgets>();
    assert_send_sync::<ModelCapabilities>();
    assert_send_sync::<ModelSpec>();
    assert_send_sync::<AgentResult>();
    assert_send_sync::<AgentContext>();
    assert_send_sync::<TurnSnapshot>();
    assert_send_sync::<CustomMessageRegistry>();
    assert_send_sync::<crate::error::DowncastError>();
};

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

    #[test]
    fn content_block_extension_serde_roundtrip() {
        let block = ContentBlock::Extension {
            type_name: "audio_clip".into(),
            data: serde_json::json!({"duration_ms": 1500, "codec": "opus"}),
        };
        let json = serde_json::to_string(&block).unwrap();
        let parsed: ContentBlock = serde_json::from_str(&json).unwrap();
        assert_eq!(block, parsed);
    }

    #[test]
    fn extract_text_ignores_extension() {
        let blocks = vec![
            ContentBlock::Text {
                text: "hello ".into(),
            },
            ContentBlock::Extension {
                type_name: "image".into(),
                data: serde_json::json!({"url": "https://example.com/img.png"}),
            },
            ContentBlock::Text {
                text: "world".into(),
            },
        ];
        assert_eq!(ContentBlock::extract_text(&blocks), "hello world");
    }

    #[test]
    fn usage_extra_add_merges_maps() {
        let a = Usage {
            input: 10,
            output: 5,
            extra: HashMap::from([
                ("reasoning_tokens".into(), 100),
                ("search_tokens".into(), 50),
            ]),
            ..Default::default()
        };
        let b = Usage {
            input: 20,
            output: 10,
            extra: HashMap::from([("reasoning_tokens".into(), 200), ("new_metric".into(), 30)]),
            ..Default::default()
        };
        let c = a + b;
        assert_eq!(c.input, 30);
        assert_eq!(c.output, 15);
        assert_eq!(c.extra["reasoning_tokens"], 300);
        assert_eq!(c.extra["search_tokens"], 50);
        assert_eq!(c.extra["new_metric"], 30);
    }

    #[test]
    fn cost_extra_add_merges_maps() {
        let a = Cost {
            input: 0.01,
            output: 0.02,
            extra: HashMap::from([("reasoning_cost".into(), 0.05)]),
            ..Default::default()
        };
        let b = Cost {
            input: 0.03,
            output: 0.04,
            extra: HashMap::from([
                ("reasoning_cost".into(), 0.10),
                ("search_cost".into(), 0.02),
            ]),
            ..Default::default()
        };
        let c = a + b;
        assert!((c.input - 0.04).abs() < f64::EPSILON);
        assert!((c.output - 0.06).abs() < f64::EPSILON);
        assert!((c.extra["reasoning_cost"] - 0.15).abs() < f64::EPSILON);
        assert!((c.extra["search_cost"] - 0.02).abs() < f64::EPSILON);
    }

    #[test]
    fn model_spec_with_provider_config() {
        let config = serde_json::json!({
            "temperature": 0.7,
            "top_p": 0.9,
        });

        let spec = ModelSpec::new("anthropic", "claude-3").with_provider_config(config.clone());

        assert_eq!(spec.provider_config, Some(config));
        assert_eq!(spec.provider, "anthropic");
        assert_eq!(spec.model_id, "claude-3");
    }

    #[test]
    fn provider_config_as_typed() {
        #[derive(Debug, Deserialize, PartialEq)]
        struct MyConfig {
            temperature: f64,
            max_tokens: u32,
        }

        let spec = ModelSpec::new("openai", "gpt-4").with_provider_config(serde_json::json!({
            "temperature": 0.5,
            "max_tokens": 1024,
        }));

        let config: Option<MyConfig> = spec.provider_config_as();
        assert_eq!(
            config,
            Some(MyConfig {
                temperature: 0.5,
                max_tokens: 1024,
            })
        );

        // None when no provider_config is set.
        let spec_none = ModelSpec::new("openai", "gpt-4");
        let config_none: Option<MyConfig> = spec_none.provider_config_as();
        assert!(config_none.is_none());
    }

    #[test]
    fn model_capabilities_builder_chain() {
        let caps = ModelCapabilities::none()
            .with_thinking(true)
            .with_vision(true)
            .with_tool_use(true)
            .with_streaming(true)
            .with_structured_output(true)
            .with_max_context_window(200_000)
            .with_max_output_tokens(16384);

        assert!(caps.supports_thinking);
        assert!(caps.supports_vision);
        assert!(caps.supports_tool_use);
        assert!(caps.supports_streaming);
        assert!(caps.supports_structured_output);
        assert_eq!(caps.max_context_window, Some(200_000));
        assert_eq!(caps.max_output_tokens, Some(16384));
    }

    #[test]
    fn model_capabilities_serde_roundtrip() {
        let caps = ModelCapabilities::none()
            .with_thinking(true)
            .with_tool_use(true)
            .with_max_context_window(128_000);
        let json = serde_json::to_string(&caps).unwrap();
        let parsed: ModelCapabilities = serde_json::from_str(&json).unwrap();
        assert_eq!(caps, parsed);
    }

    #[test]
    fn model_spec_with_capabilities() {
        let caps = ModelCapabilities::none()
            .with_thinking(true)
            .with_streaming(true);
        let spec = ModelSpec::new("test", "model-1").with_capabilities(caps.clone());
        assert_eq!(spec.capabilities, Some(caps.clone()));
        assert_eq!(spec.capabilities(), caps);
    }

    #[test]
    fn model_spec_capabilities_defaults_when_none() {
        let spec = ModelSpec::new("test", "model-1");
        assert!(spec.capabilities.is_none());
        let caps = spec.capabilities();
        assert!(!caps.supports_thinking);
        assert_eq!(caps.max_context_window, None);
    }

    // ─── Custom Message Serialization ────────────────────────────────────

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct MockNotification {
        title: String,
        body: String,
    }

    impl CustomMessage for MockNotification {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn type_name(&self) -> Option<&str> {
            Some("mock_notification")
        }

        fn to_json(&self) -> Option<serde_json::Value> {
            serde_json::to_value(self).ok()
        }
    }

    #[test]
    fn custom_message_serialize_roundtrip() {
        let msg = MockNotification {
            title: "Hello".into(),
            body: "World".into(),
        };

        let envelope = serialize_custom_message(&msg).expect("serialization supported");
        assert_eq!(envelope["type"], "mock_notification");
        assert_eq!(envelope["data"]["title"], "Hello");

        let mut registry = CustomMessageRegistry::new();
        registry.register_type::<MockNotification>("mock_notification");

        let restored = deserialize_custom_message(&registry, &envelope).unwrap();
        let downcasted = restored
            .as_any()
            .downcast_ref::<MockNotification>()
            .unwrap();
        assert_eq!(downcasted, &msg);
    }

    #[test]
    fn custom_message_default_returns_none() {
        #[derive(Debug)]
        struct Bare;
        impl CustomMessage for Bare {
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }
        }
        let bare = Bare;
        assert!(bare.type_name().is_none());
        assert!(bare.to_json().is_none());
        assert!(serialize_custom_message(&bare).is_none());
    }

    #[test]
    fn registry_unknown_type_returns_error() {
        let registry = CustomMessageRegistry::new();
        let envelope = serde_json::json!({"type": "unknown", "data": {}});
        let result = deserialize_custom_message(&registry, &envelope);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("no deserializer registered"));
    }

    #[test]
    fn registry_contains_check() {
        let mut registry = CustomMessageRegistry::new();
        assert!(!registry.has_type_name("mock_notification"));
        registry.register_type::<MockNotification>("mock_notification");
        assert!(registry.has_type_name("mock_notification"));
    }

    #[test]
    fn assistant_text_extracts_last_assistant_message() {
        let result = AgentResult {
            messages: vec![
                AgentMessage::Llm(LlmMessage::User(UserMessage {
                    content: vec![ContentBlock::Text {
                        text: "hi".to_string(),
                    }],
                    timestamp: 0,
                    cache_hint: None,
                })),
                AgentMessage::Llm(LlmMessage::Assistant(AssistantMessage {
                    content: vec![ContentBlock::Text {
                        text: "first".to_string(),
                    }],
                    provider: "test".to_string(),
                    model_id: "m".to_string(),
                    usage: Usage::default(),
                    cost: Cost::default(),
                    stop_reason: StopReason::Stop,
                    error_message: None,
                    error_kind: None,
                    timestamp: 0,
                    cache_hint: None,
                })),
                AgentMessage::Llm(LlmMessage::Assistant(AssistantMessage {
                    content: vec![ContentBlock::Text {
                        text: "second".to_string(),
                    }],
                    provider: "test".to_string(),
                    model_id: "m".to_string(),
                    usage: Usage::default(),
                    cost: Cost::default(),
                    stop_reason: StopReason::Stop,
                    error_message: None,
                    error_kind: None,
                    timestamp: 0,
                    cache_hint: None,
                })),
            ],
            stop_reason: StopReason::Stop,
            usage: Usage::default(),
            cost: Cost::default(),
            error: None,
            transfer_signal: None,
        };
        assert_eq!(result.assistant_text(), "second");
    }

    #[test]
    fn assistant_text_returns_empty_when_no_assistant() {
        let result = AgentResult {
            messages: vec![AgentMessage::Llm(LlmMessage::User(UserMessage {
                content: vec![ContentBlock::Text {
                    text: "hi".to_string(),
                }],
                timestamp: 0,
                cache_hint: None,
            }))],
            stop_reason: StopReason::Stop,
            usage: Usage::default(),
            cost: Cost::default(),
            error: None,
            transfer_signal: None,
        };
        assert_eq!(result.assistant_text(), "");
    }

    #[test]
    fn assistant_text_returns_empty_when_no_messages() {
        let result = AgentResult {
            messages: vec![],
            stop_reason: StopReason::Stop,
            usage: Usage::default(),
            cost: Cost::default(),
            error: None,
            transfer_signal: None,
        };
        assert_eq!(result.assistant_text(), "");
    }

    #[test]
    fn deserialize_custom_message_missing_fields() {
        let registry = CustomMessageRegistry::new();

        let no_type = serde_json::json!({"data": {}});
        assert!(
            deserialize_custom_message(&registry, &no_type)
                .unwrap_err()
                .contains("missing 'type'")
        );

        let no_data = serde_json::json!({"type": "foo"});
        assert!(
            deserialize_custom_message(&registry, &no_data)
                .unwrap_err()
                .contains("missing 'data'")
        );
    }
}