tea-model 0.1.0

Provider-neutral model port for tea-rs
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::str::FromStr;

use serde_json::Value;
use tea_protocol::{
    ExactCost, ExternalSource, HostedToolOutcome, MAX_HOSTED_TOOL_SOURCES, ModelId,
    ProtocolMetadata, ProviderContinuation, SourceCitation, StopReason, Usage,
};
use thiserror::Error;

use crate::ModelFailure;

/// Maximum UTF-8 bytes in one normalized text, thinking, or argument delta.
pub const MAX_MODEL_DELTA_BYTES: usize = 64 * 1024;
/// Maximum UTF-8 bytes in one opaque provider response or tool-call ID.
pub const MAX_PROVIDER_OPAQUE_ID_BYTES: usize = 256;
/// Largest concurrent tool-call index supported in one response.
pub const MAX_MODEL_STREAM_INDEX: u16 = 1023;
const MAX_COMPLETED_TOOL_ARGUMENT_BYTES: usize = 256 * 1024;
const MAX_COMPLETED_TOOL_ARGUMENT_DEPTH: usize = 32;

macro_rules! opaque_id {
    ($name:ident, $doc:literal) => {
        #[doc = $doc]
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(String);

        impl $name {
            /// Returns the bounded opaque provider value.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl FromStr for $name {
            type Err = ModelStreamValueError;

            fn from_str(value: &str) -> Result<Self, Self::Err> {
                if value.is_empty()
                    || value.len() > MAX_PROVIDER_OPAQUE_ID_BYTES
                    || value.chars().any(char::is_control)
                {
                    return Err(ModelStreamValueError::InvalidProviderOpaqueId);
                }
                Ok(Self(value.to_owned()))
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(&self.0)
            }
        }
    };
}

opaque_id!(
    ProviderResponseId,
    "Bounded opaque response identifier returned by a provider."
);
opaque_id!(
    ProviderToolCallId,
    "Bounded provider-scoped identifier joining streamed tool-call fragments."
);

/// Bounded zero-based content/tool index in one provider response.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModelStreamIndex(u16);

impl ModelStreamIndex {
    /// Creates a bounded stream index.
    ///
    /// # Errors
    ///
    /// Returns an error above [`MAX_MODEL_STREAM_INDEX`].
    pub const fn new(value: u16) -> Result<Self, ModelStreamValueError> {
        if value > MAX_MODEL_STREAM_INDEX {
            Err(ModelStreamValueError::InvalidStreamIndex)
        } else {
            Ok(Self(value))
        }
    }

    /// Returns the numeric index.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }
}

/// Bounded non-empty UTF-8 text or thinking delta.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Utf8Delta(String);

impl Utf8Delta {
    /// Creates a bounded delta.
    ///
    /// # Errors
    ///
    /// Returns an error when empty, oversized, or containing a null character.
    pub fn new(value: impl Into<String>) -> Result<Self, ModelStreamValueError> {
        let value = value.into();
        validate_delta(&value)?;
        Ok(Self(value))
    }

    /// Returns delta text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Metadata reported when a normalized provider response starts.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ModelResponseInfo {
    response_id: Option<ProviderResponseId>,
    response_model: Option<ModelId>,
    metadata: ProtocolMetadata,
}

impl ModelResponseInfo {
    /// Creates empty response metadata.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an opaque provider response ID.
    #[must_use]
    pub fn with_response_id(mut self, response_id: ProviderResponseId) -> Self {
        self.response_id = Some(response_id);
        self
    }

    /// Adds the concrete response model when it differs or is informative.
    #[must_use]
    pub fn with_response_model(mut self, response_model: ModelId) -> Self {
        self.response_model = Some(response_model);
        self
    }

    /// Adds bounded namespaced response metadata.
    #[must_use]
    pub fn with_metadata(mut self, metadata: ProtocolMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    /// Returns the provider response ID.
    #[must_use]
    pub const fn response_id(&self) -> Option<&ProviderResponseId> {
        self.response_id.as_ref()
    }

    /// Returns the concrete response model.
    #[must_use]
    pub const fn response_model(&self) -> Option<&ModelId> {
        self.response_model.as_ref()
    }

    /// Returns bounded response metadata.
    #[must_use]
    pub const fn metadata(&self) -> &ProtocolMetadata {
        &self.metadata
    }
}

/// Start of one provider-streamed tool call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolCallStarted {
    index: ModelStreamIndex,
    provider_call_id: ProviderToolCallId,
    tool_name: String,
}

impl ToolCallStarted {
    /// Creates a validated tool-call start.
    ///
    /// # Errors
    ///
    /// Returns an error when the tool name is not canonical.
    pub fn new(
        index: ModelStreamIndex,
        provider_call_id: ProviderToolCallId,
        tool_name: impl Into<String>,
    ) -> Result<Self, ModelStreamValueError> {
        let tool_name = tool_name.into();
        validate_tool_name(&tool_name)?;
        Ok(Self {
            index,
            provider_call_id,
            tool_name,
        })
    }

    /// Returns the response-local stream index.
    #[must_use]
    pub const fn index(&self) -> ModelStreamIndex {
        self.index
    }

    /// Returns the provider call ID.
    #[must_use]
    pub const fn provider_call_id(&self) -> &ProviderToolCallId {
        &self.provider_call_id
    }

    /// Returns the canonical tool name.
    #[must_use]
    pub fn tool_name(&self) -> &str {
        &self.tool_name
    }
}

/// Incomplete provider tool-arguments fragment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolArgumentsDelta {
    index: ModelStreamIndex,
    provider_call_id: ProviderToolCallId,
    delta: String,
}

impl ToolArgumentsDelta {
    /// Creates a bounded incomplete argument fragment.
    ///
    /// # Errors
    ///
    /// Returns an error when the fragment is empty, oversized, or contains a
    /// null character.
    pub fn new(
        index: ModelStreamIndex,
        provider_call_id: ProviderToolCallId,
        delta: impl Into<String>,
    ) -> Result<Self, ModelStreamValueError> {
        let delta = delta.into();
        validate_delta(&delta)?;
        Ok(Self {
            index,
            provider_call_id,
            delta,
        })
    }

    /// Returns the response-local stream index.
    #[must_use]
    pub const fn index(&self) -> ModelStreamIndex {
        self.index
    }

    /// Returns the provider call ID.
    #[must_use]
    pub const fn provider_call_id(&self) -> &ProviderToolCallId {
        &self.provider_call_id
    }

    /// Returns the incomplete UTF-8 argument fragment.
    #[must_use]
    pub fn delta(&self) -> &str {
        &self.delta
    }
}

/// Completed, parsed provider tool call safe for later canonical projection.
#[derive(Debug, Clone, PartialEq)]
pub struct ToolCallCompleted {
    index: ModelStreamIndex,
    provider_call_id: ProviderToolCallId,
    tool_name: String,
    arguments: Value,
}

impl ToolCallCompleted {
    /// Creates a validated completed call with object arguments.
    ///
    /// # Errors
    ///
    /// Returns an error for an invalid name, non-object arguments, or bounded
    /// JSON violations.
    pub fn new(
        index: ModelStreamIndex,
        provider_call_id: ProviderToolCallId,
        tool_name: impl Into<String>,
        arguments: Value,
    ) -> Result<Self, ModelStreamValueError> {
        let tool_name = tool_name.into();
        validate_tool_name(&tool_name)?;
        validate_completed_arguments(&arguments)?;
        Ok(Self {
            index,
            provider_call_id,
            tool_name,
            arguments,
        })
    }

    /// Returns the response-local stream index.
    #[must_use]
    pub const fn index(&self) -> ModelStreamIndex {
        self.index
    }

    /// Returns the provider call ID.
    #[must_use]
    pub const fn provider_call_id(&self) -> &ProviderToolCallId {
        &self.provider_call_id
    }

    /// Returns the canonical tool name.
    #[must_use]
    pub fn tool_name(&self) -> &str {
        &self.tool_name
    }

    /// Returns complete parsed object arguments.
    #[must_use]
    pub const fn arguments(&self) -> &Value {
        &self.arguments
    }
}

/// Start of one provider-hosted tool activity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostedToolStarted {
    index: ModelStreamIndex,
    provider_call_id: ProviderToolCallId,
    tool_name: String,
}

impl HostedToolStarted {
    /// Creates a validated hosted tool start.
    ///
    /// # Errors
    ///
    /// Returns an error when the tool name is not canonical.
    pub fn new(
        index: ModelStreamIndex,
        provider_call_id: ProviderToolCallId,
        tool_name: impl Into<String>,
    ) -> Result<Self, ModelStreamValueError> {
        let tool_name = tool_name.into();
        validate_tool_name(&tool_name)?;
        Ok(Self {
            index,
            provider_call_id,
            tool_name,
        })
    }

    /// Returns the response-local stream index.
    #[must_use]
    pub const fn index(&self) -> ModelStreamIndex {
        self.index
    }

    /// Returns the provider activity identifier.
    #[must_use]
    pub const fn provider_call_id(&self) -> &ProviderToolCallId {
        &self.provider_call_id
    }

    /// Returns the canonical hosted tool name.
    #[must_use]
    pub fn tool_name(&self) -> &str {
        &self.tool_name
    }
}

/// Complete provider-hosted tool activity safe for canonical projection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostedToolCompleted {
    index: ModelStreamIndex,
    provider_call_id: ProviderToolCallId,
    tool_name: String,
    arguments: Value,
    outcome: HostedToolOutcome,
    sources: Vec<ExternalSource>,
    continuation: Option<ProviderContinuation>,
}

impl HostedToolCompleted {
    /// Creates one validated complete hosted activity.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid identity, arguments, or source bounds.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        index: ModelStreamIndex,
        provider_call_id: ProviderToolCallId,
        tool_name: impl Into<String>,
        arguments: Value,
        outcome: HostedToolOutcome,
        sources: Vec<ExternalSource>,
        continuation: Option<ProviderContinuation>,
    ) -> Result<Self, ModelStreamValueError> {
        let tool_name = tool_name.into();
        validate_tool_name(&tool_name)?;
        validate_completed_arguments(&arguments)?;
        if sources.len() > MAX_HOSTED_TOOL_SOURCES {
            return Err(ModelStreamValueError::TooManyHostedToolSources);
        }
        Ok(Self {
            index,
            provider_call_id,
            tool_name,
            arguments,
            outcome,
            sources,
            continuation,
        })
    }

    /// Returns the response-local stream index.
    #[must_use]
    pub const fn index(&self) -> ModelStreamIndex {
        self.index
    }

    /// Returns the provider activity identifier.
    #[must_use]
    pub const fn provider_call_id(&self) -> &ProviderToolCallId {
        &self.provider_call_id
    }

    /// Returns the canonical hosted tool name.
    #[must_use]
    pub fn tool_name(&self) -> &str {
        &self.tool_name
    }

    /// Returns normalized object arguments.
    #[must_use]
    pub const fn arguments(&self) -> &Value {
        &self.arguments
    }

    /// Returns the provider-reported terminal outcome.
    #[must_use]
    pub const fn outcome(&self) -> &HostedToolOutcome {
        &self.outcome
    }

    /// Returns normalized sources in provider order.
    #[must_use]
    pub fn sources(&self) -> &[ExternalSource] {
        &self.sources
    }

    /// Returns opaque same-provider continuation data.
    #[must_use]
    pub const fn continuation(&self) -> Option<&ProviderContinuation> {
        self.continuation.as_ref()
    }
}

/// Provider-streamed citation awaiting canonical hosted call identity mapping.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelSourceCitation {
    provider_call_id: Option<ProviderToolCallId>,
    citation: SourceCitation,
}

impl ModelSourceCitation {
    /// Creates a normalized citation without a canonical tool-call identifier.
    ///
    /// # Errors
    ///
    /// Returns an error when an adapter attempts to assign kernel-owned identity.
    pub fn new(
        provider_call_id: Option<ProviderToolCallId>,
        citation: SourceCitation,
    ) -> Result<Self, ModelStreamValueError> {
        if citation.tool_call_id().is_some() {
            return Err(ModelStreamValueError::CitationAlreadyCanonical);
        }
        Ok(Self {
            provider_call_id,
            citation,
        })
    }

    /// Returns the related provider activity identifier, when available.
    #[must_use]
    pub const fn provider_call_id(&self) -> Option<&ProviderToolCallId> {
        self.provider_call_id.as_ref()
    }

    /// Returns the normalized provider-neutral citation.
    #[must_use]
    pub const fn citation(&self) -> &SourceCitation {
        &self.citation
    }
}

/// Successful terminal model completion data.
#[derive(Debug, Clone, PartialEq)]
pub struct ModelCompletion {
    stop_reason: StopReason,
    usage: Option<Usage>,
    cost: Option<ExactCost>,
    metadata: ProtocolMetadata,
}

impl ModelCompletion {
    /// Creates a normal successful completion.
    #[must_use]
    pub fn completed() -> Self {
        Self {
            stop_reason: StopReason::Completed,
            usage: None,
            cost: None,
            metadata: ProtocolMetadata::default(),
        }
    }

    /// Creates successful terminal completion data.
    ///
    /// # Errors
    ///
    /// Returns an error for cancelled, error, or unknown stop reasons. Those
    /// outcomes must use [`ModelEvent::Failed`].
    pub fn new(stop_reason: StopReason) -> Result<Self, ModelStreamValueError> {
        if !matches!(
            stop_reason,
            StopReason::Completed
                | StopReason::Length
                | StopReason::ToolUse
                | StopReason::PauseTurn
        ) {
            return Err(ModelStreamValueError::InvalidCompletionReason);
        }
        Ok(Self {
            stop_reason,
            usage: None,
            cost: None,
            metadata: ProtocolMetadata::default(),
        })
    }

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

    /// Adds exact provider-reported cost.
    #[must_use]
    pub fn with_cost(mut self, cost: ExactCost) -> Self {
        self.cost = Some(cost);
        self
    }

    /// Adds bounded terminal metadata.
    #[must_use]
    pub fn with_metadata(mut self, metadata: ProtocolMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    /// Returns the normalized stop reason.
    #[must_use]
    pub const fn stop_reason(&self) -> &StopReason {
        &self.stop_reason
    }

    /// Returns normalized token usage when reported.
    #[must_use]
    pub const fn usage(&self) -> Option<&Usage> {
        self.usage.as_ref()
    }

    /// Returns exact provider-reported cost when available.
    #[must_use]
    pub const fn cost(&self) -> Option<&ExactCost> {
        self.cost.as_ref()
    }

    /// Returns bounded terminal metadata.
    #[must_use]
    pub const fn metadata(&self) -> &ProtocolMetadata {
        &self.metadata
    }
}

/// One normalized provider stream event.
#[derive(Debug, Clone, PartialEq)]
pub enum ModelEvent {
    /// Provider accepted the request and began one response.
    Started(ModelResponseInfo),
    /// Visible assistant text fragment.
    TextDelta(Utf8Delta),
    /// Assistant reasoning fragment.
    ThinkingDelta(Utf8Delta),
    /// Start of a provider tool call.
    ToolCallStarted(ToolCallStarted),
    /// Incomplete tool argument fragment, never executable by itself.
    ToolArgumentsDelta(ToolArgumentsDelta),
    /// Completed tool call with parsed object arguments.
    ToolCallCompleted(ToolCallCompleted),
    /// Start of a provider-hosted tool activity.
    HostedToolStarted(HostedToolStarted),
    /// Completed provider-hosted tool activity with normalized sources.
    HostedToolCompleted(HostedToolCompleted),
    /// Citation emitted for assistant text and an external source.
    SourceCitation(ModelSourceCitation),
    /// Successful terminal event.
    Completed(ModelCompletion),
    /// Failed or cancelled terminal event.
    Failed(ModelFailure),
}

impl ModelEvent {
    /// Returns visible text for a text-delta event.
    #[must_use]
    pub fn as_text_delta(&self) -> Option<&str> {
        match self {
            Self::TextDelta(delta) => Some(delta.as_str()),
            _ => None,
        }
    }

    /// Returns reasoning text for a thinking-delta event.
    #[must_use]
    pub fn as_thinking_delta(&self) -> Option<&str> {
        match self {
            Self::ThinkingDelta(delta) => Some(delta.as_str()),
            _ => None,
        }
    }

    /// Returns the tool-call start payload.
    #[must_use]
    pub const fn as_tool_call_started(&self) -> Option<&ToolCallStarted> {
        match self {
            Self::ToolCallStarted(call) => Some(call),
            _ => None,
        }
    }

    /// Returns the incomplete tool-arguments payload.
    #[must_use]
    pub const fn as_tool_arguments_delta(&self) -> Option<&ToolArgumentsDelta> {
        match self {
            Self::ToolArgumentsDelta(delta) => Some(delta),
            _ => None,
        }
    }

    /// Returns the completed tool-call payload.
    #[must_use]
    pub const fn as_tool_call_completed(&self) -> Option<&ToolCallCompleted> {
        match self {
            Self::ToolCallCompleted(call) => Some(call),
            _ => None,
        }
    }

    /// Returns the hosted tool start payload.
    #[must_use]
    pub const fn as_hosted_tool_started(&self) -> Option<&HostedToolStarted> {
        match self {
            Self::HostedToolStarted(call) => Some(call),
            _ => None,
        }
    }

    /// Returns the hosted tool completion payload.
    #[must_use]
    pub const fn as_hosted_tool_completed(&self) -> Option<&HostedToolCompleted> {
        match self {
            Self::HostedToolCompleted(call) => Some(call),
            _ => None,
        }
    }

    /// Returns the normalized source citation payload.
    #[must_use]
    pub const fn as_source_citation(&self) -> Option<&ModelSourceCitation> {
        match self {
            Self::SourceCitation(citation) => Some(citation),
            _ => None,
        }
    }
}

/// Deterministic validator for normalized provider stream grammar.
#[derive(Debug, Default)]
pub struct ModelStreamValidator {
    started: bool,
    terminal: Option<bool>,
    event_count: usize,
    completed_tool_calls: usize,
    completed_hosted_tools: usize,
    active_tools: BTreeMap<ModelStreamIndex, (ProviderToolCallId, String)>,
    active_hosted_tools: BTreeMap<ModelStreamIndex, (ProviderToolCallId, String)>,
    completed_hosted_ids: BTreeSet<ProviderToolCallId>,
    seen_tool_indexes: BTreeSet<ModelStreamIndex>,
}

impl ModelStreamValidator {
    /// Creates an empty stream grammar validator.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Observes one event in source order.
    ///
    /// # Errors
    ///
    /// Returns a typed violation when the event does not follow normalized
    /// stream grammar. Rejected events do not advance validator state.
    pub fn observe(&mut self, event: &ModelEvent) -> Result<(), ModelStreamViolation> {
        if self.terminal.is_some() {
            return Err(ModelStreamViolation::EventAfterTerminal);
        }
        if !self.started {
            if matches!(event, ModelEvent::Started(_)) {
                self.started = true;
                self.event_count += 1;
                return Ok(());
            }
            return Err(ModelStreamViolation::EventBeforeStart);
        }

        match event {
            ModelEvent::Started(_) => return Err(ModelStreamViolation::DuplicateStart),
            ModelEvent::ToolCallStarted(call) => {
                if self.seen_tool_indexes.contains(&call.index()) {
                    return Err(ModelStreamViolation::DuplicateToolIndex);
                }
                self.seen_tool_indexes.insert(call.index());
                self.active_tools.insert(
                    call.index(),
                    (call.provider_call_id().clone(), call.tool_name().to_owned()),
                );
            }
            ModelEvent::HostedToolStarted(call) => {
                if self.seen_tool_indexes.contains(&call.index()) {
                    return Err(ModelStreamViolation::DuplicateToolIndex);
                }
                self.seen_tool_indexes.insert(call.index());
                self.active_hosted_tools.insert(
                    call.index(),
                    (call.provider_call_id().clone(), call.tool_name().to_owned()),
                );
            }
            ModelEvent::ToolArgumentsDelta(delta) => {
                let Some((call_id, _)) = self.active_tools.get(&delta.index()) else {
                    return Err(ModelStreamViolation::UnknownToolIndex);
                };
                if call_id != delta.provider_call_id() {
                    return Err(ModelStreamViolation::ToolIdentityMismatch);
                }
            }
            ModelEvent::ToolCallCompleted(call) => {
                let Some((call_id, tool_name)) = self.active_tools.get(&call.index()) else {
                    return Err(ModelStreamViolation::UnknownToolIndex);
                };
                if call_id != call.provider_call_id() || tool_name != call.tool_name() {
                    return Err(ModelStreamViolation::ToolIdentityMismatch);
                }
                self.active_tools.remove(&call.index());
                self.completed_tool_calls += 1;
            }
            ModelEvent::HostedToolCompleted(call) => {
                let Some((call_id, tool_name)) = self.active_hosted_tools.get(&call.index()) else {
                    return Err(ModelStreamViolation::UnknownToolIndex);
                };
                if call_id != call.provider_call_id() || tool_name != call.tool_name() {
                    return Err(ModelStreamViolation::ToolIdentityMismatch);
                }
                self.active_hosted_tools.remove(&call.index());
                self.completed_hosted_ids
                    .insert(call.provider_call_id().clone());
                self.completed_hosted_tools += 1;
            }
            ModelEvent::SourceCitation(citation) => {
                if citation
                    .provider_call_id()
                    .is_some_and(|call_id| !self.completed_hosted_ids.contains(call_id))
                {
                    return Err(ModelStreamViolation::UnknownHostedCitation);
                }
            }
            ModelEvent::Completed(_) => {
                if !self.active_tools.is_empty() || !self.active_hosted_tools.is_empty() {
                    return Err(ModelStreamViolation::IncompleteToolCalls);
                }
                self.terminal = Some(true);
            }
            ModelEvent::Failed(_) => {
                self.terminal = Some(false);
            }
            ModelEvent::TextDelta(_) | ModelEvent::ThinkingDelta(_) => {}
        }
        self.event_count += 1;
        Ok(())
    }

    /// Finishes validation after the stream returns `None`.
    ///
    /// # Errors
    ///
    /// Returns an error when start or terminal events are missing.
    pub fn finish(self) -> Result<ModelStreamSummary, ModelStreamViolation> {
        if !self.started {
            return Err(ModelStreamViolation::MissingStart);
        }
        let succeeded = self.terminal.ok_or(ModelStreamViolation::MissingTerminal)?;
        Ok(ModelStreamSummary {
            event_count: self.event_count,
            completed_tool_calls: self.completed_tool_calls,
            completed_hosted_tools: self.completed_hosted_tools,
            succeeded,
        })
    }
}

/// Summary of one fully validated normalized stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ModelStreamSummary {
    event_count: usize,
    completed_tool_calls: usize,
    completed_hosted_tools: usize,
    succeeded: bool,
}

impl ModelStreamSummary {
    /// Returns accepted event count including start and terminal events.
    #[must_use]
    pub const fn event_count(self) -> usize {
        self.event_count
    }

    /// Returns the number of completed tool calls.
    #[must_use]
    pub const fn completed_tool_calls(self) -> usize {
        self.completed_tool_calls
    }

    /// Returns the number of completed provider-hosted activities.
    #[must_use]
    pub const fn completed_hosted_tools(self) -> usize {
        self.completed_hosted_tools
    }

    /// Returns whether termination was successful rather than failed.
    #[must_use]
    pub const fn succeeded(self) -> bool {
        self.succeeded
    }
}

/// Normalized stream grammar violation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum ModelStreamViolation {
    /// A non-start event appeared before `Started`.
    #[error("model stream event appeared before start")]
    EventBeforeStart,
    /// No start event was observed.
    #[error("model stream is missing start")]
    MissingStart,
    /// More than one start event appeared.
    #[error("model stream contains duplicate start")]
    DuplicateStart,
    /// Stream ended without success or failure.
    #[error("model stream is missing terminal event")]
    MissingTerminal,
    /// An event appeared after success or failure.
    #[error("model stream event appeared after terminal event")]
    EventAfterTerminal,
    /// A response-local tool index was started more than once concurrently.
    #[error("model stream contains duplicate active tool index")]
    DuplicateToolIndex,
    /// A tool fragment or completion references no active call.
    #[error("model stream references an unknown tool index")]
    UnknownToolIndex,
    /// Tool index, provider ID, or name changed within one call.
    #[error("model stream tool identity changed")]
    ToolIdentityMismatch,
    /// Successful termination left one or more calls incomplete.
    #[error("model stream completed with incomplete tool calls")]
    IncompleteToolCalls,
    /// A citation references no completed provider-hosted activity.
    #[error("model stream citation references an unknown hosted tool")]
    UnknownHostedCitation,
}

/// Error returned by normalized stream value constructors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum ModelStreamValueError {
    /// Provider opaque identifier is empty, oversized, or contains controls.
    #[error("provider opaque identifier is invalid")]
    InvalidProviderOpaqueId,
    /// Stream index exceeds the supported response-local range.
    #[error("model stream index is invalid")]
    InvalidStreamIndex,
    /// Delta is empty, oversized, or contains a null character.
    #[error("model stream delta is invalid")]
    InvalidDelta,
    /// Tool name is not canonical.
    #[error("model tool name is invalid")]
    InvalidToolName,
    /// Completed tool arguments must be an object.
    #[error("completed tool arguments must be a JSON object")]
    ToolArgumentsMustBeObject,
    /// Completed tool arguments exceed JSON bounds.
    #[error("completed tool arguments exceed supported bounds")]
    ToolArgumentsOutOfBounds,
    /// Hosted tool returned too many normalized sources.
    #[error("hosted tool returned too many sources")]
    TooManyHostedToolSources,
    /// Provider adapters cannot assign kernel-owned citation identity.
    #[error("model citation already contains a canonical tool-call identifier")]
    CitationAlreadyCanonical,
    /// Successful completion used a failure-only or unknown stop reason.
    #[error("successful completion stop reason is invalid")]
    InvalidCompletionReason,
    /// Failure message is empty, oversized, or contains a null character.
    #[error("model failure message is invalid")]
    InvalidFailureMessage,
}

fn validate_delta(value: &str) -> Result<(), ModelStreamValueError> {
    if value.is_empty() || value.len() > MAX_MODEL_DELTA_BYTES || value.contains('\0') {
        Err(ModelStreamValueError::InvalidDelta)
    } else {
        Ok(())
    }
}

fn validate_tool_name(value: &str) -> Result<(), ModelStreamValueError> {
    let mut bytes = value.bytes();
    if value.len() > 128
        || !bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
        || !bytes.all(|byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-' | b'.')
        })
    {
        Err(ModelStreamValueError::InvalidToolName)
    } else {
        Ok(())
    }
}

fn validate_completed_arguments(arguments: &Value) -> Result<(), ModelStreamValueError> {
    if !arguments.is_object() {
        return Err(ModelStreamValueError::ToolArgumentsMustBeObject);
    }
    if serde_json::to_vec(arguments)
        .map_err(|_| ModelStreamValueError::ToolArgumentsOutOfBounds)?
        .len()
        > MAX_COMPLETED_TOOL_ARGUMENT_BYTES
        || json_depth(arguments) > MAX_COMPLETED_TOOL_ARGUMENT_DEPTH
    {
        return Err(ModelStreamValueError::ToolArgumentsOutOfBounds);
    }
    Ok(())
}

fn json_depth(value: &Value) -> usize {
    match value {
        Value::Array(values) => 1 + values.iter().map(json_depth).max().unwrap_or(0),
        Value::Object(values) => 1 + values.values().map(json_depth).max().unwrap_or(0),
        _ => 1,
    }
}