reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
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
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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
//! Owned model requests and strict provider-neutral stream grammar.
//!
//! The request carries two tool lanes: client-local tools are explicit
//! descriptors, while provider-hosted capabilities remain opaque extensions.
//! The stream grammar states delta and final lifecycles explicitly, so a
//! provider adapter cannot leave a consumer guessing which it received.

use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fmt;
use std::future::Future;

use futures_core::Stream;

use crate::opaque::{Envelope, Payload};
use crate::redact;
use crate::transcript::item::{Assistant, Item, ModelVisibility};
use crate::value::content::{
    KnownPartKind, Part, Segment, SegmentExtensions, is_valid_system_instruction,
};
use crate::value::tool_call::{self, Id, ToolCall};

/// One client-executed tool advertised to the model.
#[derive(Clone)]
pub struct ClientTool {
    name: tool_call::Name,
    description: String,
    input_schema: Payload,
}

impl fmt::Debug for ClientTool {
    /// Names the tool and sizes what the model would read about it.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ClientTool")
            .field("name", &self.name)
            .field("description", &redact::Bytes(self.description.len()))
            .field("input_schema", &self.input_schema)
            .finish()
    }
}

impl ClientTool {
    /// Creates an owned local-tool descriptor.
    #[must_use]
    pub const fn new(name: tool_call::Name, description: String, input_schema: Payload) -> Self {
        Self {
            name,
            description,
            input_schema,
        }
    }

    /// Returns the canonical tool name.
    #[must_use]
    pub const fn name(&self) -> &tool_call::Name {
        &self.name
    }

    /// Returns the model-facing description.
    #[must_use]
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Returns the provider-neutral input schema bytes.
    ///
    /// Uninterpreted: core never parses them, so this is where a per-tool
    /// constrained-sampling setting — a strict schema, a grammar, or a provider
    /// envelope around either — reaches the adapter that wrote it.
    #[must_use]
    pub const fn input_schema(&self) -> &Payload {
        &self.input_schema
    }
}

/// Provider-neutral tool-selection behavior.
#[derive(Clone, Debug)]
pub enum ToolChoice {
    /// Let the model decide whether to call a tool.
    Auto,
    /// Disable tool calls.
    None,
    /// Require some tool call.
    Required,
    /// Require one named local tool.
    Specific(tool_call::Name),
}

/// Sampling controls for one model request.
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct SamplingParams {
    /// Sampling temperature; absent delegates to the provider.
    pub temperature: Option<f64>,
    /// Provider-neutral reasoning effort label.
    pub reasoning_effort: Option<String>,
    /// Maximum generated token count.
    pub max_output_tokens: Option<u64>,
    /// Whether parallel tool calls are requested.
    pub parallel_tool_calls: bool,
    /// Optional structured-output schema bytes.
    ///
    /// This constrains the *response*. Constraining one tool's arguments is a
    /// per-tool concern and travels in that tool's
    /// [`ClientTool::input_schema`], which core likewise never parses.
    pub output_schema: Option<Payload>,
    /// Ordered generation stop strings.
    pub stop_sequences: Vec<String>,
    /// Optional tool-selection constraint.
    pub tool_choice: Option<ToolChoice>,
}

impl fmt::Debug for SamplingParams {
    /// Prints the controls that classify a request and counts the strings.
    ///
    /// `stop_sequences` is the one field here that carries text bound for the
    /// model, and a `Vec<String>` has no element type that redacts itself, so it
    /// reports a length instead.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SamplingParams")
            .field("temperature", &self.temperature)
            .field("reasoning_effort", &self.reasoning_effort)
            .field("max_output_tokens", &self.max_output_tokens)
            .field("parallel_tool_calls", &self.parallel_tool_calls)
            .field("output_schema", &self.output_schema)
            .field("stop_sequences", &redact::Items(self.stop_sequences.len()))
            .field("tool_choice", &self.tool_choice)
            .finish()
    }
}

/// A stable failure while projecting owned transcript items into a model request.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RequestError {
    /// A system-instruction text block was empty.
    #[non_exhaustive]
    EmptySystemInstructionText {
        /// Zero-based block position.
        index: usize,
    },
    /// A system-instruction block had a known, non-text kind.
    #[non_exhaustive]
    NonTextSystemInstruction {
        /// Zero-based block position.
        index: usize,
        /// Original canonical numeric kind.
        kind: i64,
    },
    /// A system-instruction block had no portable interpretation.
    #[non_exhaustive]
    UnknownSystemInstruction {
        /// Zero-based block position.
        index: usize,
        /// Original canonical numeric kind.
        kind: i64,
    },
    /// A new user, system, or assistant item appeared before all preceding calls closed.
    ToolExchangeNotClosed,
    /// An assistant tool call had an empty correlation identity.
    EmptyToolCallId,
    /// An assistant tool call had an empty tool name.
    #[non_exhaustive]
    EmptyToolCallName {
        /// Nonempty call identity whose name was empty.
        call_id: String,
    },
    /// An assistant tool-call identity was reused anywhere in the request.
    #[non_exhaustive]
    DuplicateToolCallId {
        /// Reused global call identity.
        call_id: String,
    },
    /// A model-visible tool result had an empty correlation identity.
    EmptyToolResultId,
    /// A model-visible tool result had an empty tool name.
    #[non_exhaustive]
    EmptyToolResultName {
        /// Nonempty pending call identity.
        call_id: String,
    },
    /// A model-visible tool result did not correspond to a pending call.
    #[non_exhaustive]
    OrphanToolResult {
        /// Result identity that was not pending.
        call_id: String,
    },
    /// A model-visible result named a different tool from its pending call.
    #[non_exhaustive]
    ToolResultNameMismatch {
        /// Pending call identity.
        call_id: String,
        /// Tool name recorded by the assistant call.
        expected: String,
        /// Tool name recorded by the result.
        actual: String,
    },
    /// End-of-history arrived with calls that had no model-visible results.
    #[non_exhaustive]
    UnresolvedToolCalls {
        /// Number of still-pending calls.
        count: usize,
    },
}

impl fmt::Display for RequestError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptySystemInstructionText { index } => {
                write!(
                    formatter,
                    "system instruction text at index {index} is empty"
                )
            }
            Self::NonTextSystemInstruction { index, kind } => write!(
                formatter,
                "system instruction part at index {index} has non-text kind {kind}"
            ),
            Self::UnknownSystemInstruction { index, kind } => write!(
                formatter,
                "system instruction part at index {index} has unknown kind {kind}"
            ),
            Self::ToolExchangeNotClosed => {
                formatter.write_str("message appears before the preceding tool exchange is closed")
            }
            Self::EmptyToolCallId => formatter.write_str("assistant tool call id is empty"),
            Self::EmptyToolCallName { call_id } => {
                write!(formatter, "assistant tool call {call_id} has an empty name")
            }
            Self::DuplicateToolCallId { call_id } => {
                write!(formatter, "duplicate assistant tool call id: {call_id}")
            }
            Self::EmptyToolResultId => formatter.write_str("tool result call id is empty"),
            Self::EmptyToolResultName { call_id } => {
                write!(formatter, "tool result {call_id} has an empty name")
            }
            Self::OrphanToolResult { call_id } => {
                write!(formatter, "orphan tool result: {call_id}")
            }
            Self::ToolResultNameMismatch {
                call_id,
                expected,
                actual,
            } => write!(
                formatter,
                "tool result {call_id} names {actual}, expected {expected}"
            ),
            Self::UnresolvedToolCalls { count } => {
                write!(
                    formatter,
                    "request ends with {count} unresolved tool call(s)"
                )
            }
        }
    }
}

impl Error for RequestError {}

/// Mutable preparation for exactly one model request.
///
/// ```compile_fail
/// use reef_core::runtime::model;
/// let plan = model::RequestPlan::new();
/// let request = plan.try_into_request(vec![]).unwrap();
/// plan.sampling_mut(); // freezing consumes the only mutable preparation value
/// # drop(request);
/// ```
#[derive(Clone, Debug, Default)]
pub struct RequestPlan {
    system_instruction: Vec<Part>,
    tools: Vec<ClientTool>,
    params: SamplingParams,
    extensions: Vec<Envelope>,
    ephemeral: Vec<Part>,
}

impl RequestPlan {
    /// Creates an empty per-Step preparation value.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the ordered system instruction.
    #[must_use]
    pub fn system_instruction(&self) -> &[Part] {
        &self.system_instruction
    }

    /// Appends one system-instruction block.
    pub fn push_system_instruction(&mut self, part: Part) -> &mut Self {
        self.system_instruction.push(part);
        self
    }

    /// Appends system-instruction blocks in iteration order.
    pub fn extend_system_instruction(
        &mut self,
        parts: impl IntoIterator<Item = Part>,
    ) -> &mut Self {
        self.system_instruction.extend(parts);
        self
    }

    /// Removes every system-instruction block.
    pub fn clear_system_instruction(&mut self) -> &mut Self {
        self.system_instruction.clear();
        self
    }

    /// Returns the client-local tool lane.
    #[must_use]
    pub fn tools(&self) -> &[ClientTool] {
        &self.tools
    }

    /// Appends one client-local tool descriptor.
    pub fn push_tool(&mut self, tool: ClientTool) -> &mut Self {
        self.tools.push(tool);
        self
    }

    /// Appends client-local tool descriptors in iteration order.
    pub fn extend_tools(&mut self, tools: impl IntoIterator<Item = ClientTool>) -> &mut Self {
        self.tools.extend(tools);
        self
    }

    /// Removes every client-local tool descriptor.
    pub fn clear_tools(&mut self) -> &mut Self {
        self.tools.clear();
        self
    }

    /// Returns the sampling controls for mutation.
    pub const fn sampling_mut(&mut self) -> &mut SamplingParams {
        &mut self.params
    }

    /// Returns the provider-hosted extension lane.
    #[must_use]
    pub fn extensions(&self) -> &[Envelope] {
        &self.extensions
    }

    /// Appends one provider-hosted extension.
    pub fn push_extension(&mut self, extension: Envelope) -> &mut Self {
        self.extensions.push(extension);
        self
    }

    /// Appends provider-hosted extensions in iteration order.
    pub fn extend_extensions(
        &mut self,
        extensions: impl IntoIterator<Item = Envelope>,
    ) -> &mut Self {
        self.extensions.extend(extensions);
        self
    }

    /// Removes every provider-hosted extension.
    pub fn clear_extensions(&mut self) -> &mut Self {
        self.extensions.clear();
        self
    }

    /// Returns volatile per-Step content.
    #[must_use]
    pub fn ephemeral(&self) -> &[Part] {
        &self.ephemeral
    }

    /// Appends one volatile per-Step block.
    pub fn push_ephemeral(&mut self, part: Part) -> &mut Self {
        self.ephemeral.push(part);
        self
    }

    /// Appends volatile per-Step blocks in iteration order.
    pub fn extend_ephemeral(&mut self, parts: impl IntoIterator<Item = Part>) -> &mut Self {
        self.ephemeral.extend(parts);
        self
    }

    /// Removes every volatile per-Step block.
    pub fn clear_ephemeral(&mut self) -> &mut Self {
        self.ephemeral.clear();
        self
    }

    /// Consumes the writable window and freezes a validated, model-visible request.
    ///
    /// # This is the item-to-message projection
    ///
    /// It is the crate's only one, and there is no second message vocabulary to
    /// project *into*: the projected value is the same closed [`Item`] history
    /// minus everything the model must not see. Two rules apply, in this order.
    ///
    /// 1. **`ModelVisibility`.** Every [`ModelVisibility::Hidden`] record is omitted,
    ///    whatever its variant. A provider therefore never has to consult
    ///    [`Item`] visibility itself: by construction every item in
    ///    [`Request::messages`] is [`ModelVisibility::Visible`].
    /// 2. **The exchange grammar**, checked over what survives rule 1. Hiding an
    ///    assistant record hides the calls it carries, so a result that is still
    ///    visible has become an orphan and is refused rather than sent; hiding a
    ///    result whose call is visible leaves that call unanswered and is
    ///    refused too. Reef's own commits cannot produce either, because a
    ///    committed result takes the visibility of the record carrying its call.
    ///
    /// What this projection deliberately does *not* do is normalise segments
    /// across providers. Deciding that one provider's [`Segment::Thinking`] is
    /// unusable by another requires knowing both providers' rules, which core
    /// does not and must not learn. A composition layer that changes model
    /// mid-session performs that rewrite in a
    /// [`ModelHooks::before_model`](crate::runtime::hook::ModelHooks::before_model)
    /// registration, returning
    /// [`BeforeModelDecision::Modify`](crate::runtime::hook::BeforeModelDecision::Modify)
    /// with a request re-frozen through this same boundary.
    ///
    /// This is the only `Request` construction boundary: it validates system
    /// instructions, applies visibility projection, closes tool-call/result
    /// exchanges, owns both tool lanes, and rejects invalid input before
    /// [`Client::generate`] can be invoked.
    ///
    /// # Errors
    ///
    /// Freezing refuses a request no provider should be asked to answer. Nothing
    /// is validated lazily and no partial [`Request`] escapes, so a caller that
    /// gets an error has changed nothing.
    ///
    /// The system instruction is checked first, block by block, and each variant
    /// carries the offending block's index:
    /// [`EmptySystemInstructionText`](RequestError::EmptySystemInstructionText)
    /// for a text block with no text,
    /// [`NonTextSystemInstruction`](RequestError::NonTextSystemInstruction) for a
    /// block whose kind is known but is not text, and
    /// [`UnknownSystemInstruction`](RequestError::UnknownSystemInstruction) for
    /// one whose numeric kind has no portable interpretation. A system
    /// instruction of zero blocks is valid; a present block that says nothing is
    /// not.
    ///
    /// The rest is the exchange grammar, applied to what survives the visibility
    /// rule above. It fails when the history is not a closed sequence of
    /// call-and-answer:
    ///
    /// - [`ToolExchangeNotClosed`](RequestError::ToolExchangeNotClosed) if a user,
    ///   system, or assistant record appears while an earlier call is still
    ///   unanswered.
    /// - [`EmptyToolCallId`](RequestError::EmptyToolCallId),
    ///   [`EmptyToolCallName`](RequestError::EmptyToolCallName), or
    ///   [`DuplicateToolCallId`](RequestError::DuplicateToolCallId) for a call
    ///   that cannot be correlated: identities are unique across the whole
    ///   request, not merely within one assistant record.
    /// - [`EmptyToolResultId`](RequestError::EmptyToolResultId),
    ///   [`EmptyToolResultName`](RequestError::EmptyToolResultName),
    ///   [`OrphanToolResult`](RequestError::OrphanToolResult), or
    ///   [`ToolResultNameMismatch`](RequestError::ToolResultNameMismatch) for a
    ///   result that answers no pending call or answers it under another tool's
    ///   name.
    /// - [`UnresolvedToolCalls`](RequestError::UnresolvedToolCalls), with a count,
    ///   if the history ends with calls nobody answered.
    ///
    /// The last two are also how a half-hidden exchange is refused, and the
    /// reason is the projection above rather than provider etiquette: hiding an
    /// assistant record hides the calls it carries, so a still-visible result has
    /// become an orphan, and hiding only the result leaves its call unanswered.
    /// Reef's own commits cannot produce either, because a committed result takes
    /// the visibility of the record carrying its call — so seeing one of these
    /// from a rewritten history means the rewrite split an exchange in half.
    pub fn try_into_request(self, messages: Vec<Item>) -> Result<Request, RequestError> {
        validate_system_instruction(&self.system_instruction)?;

        validate_model_messages(&messages)?;
        let visible = messages
            .into_iter()
            .filter(is_model_visible)
            .collect::<Vec<_>>();

        Ok(Request {
            system_instruction: self.system_instruction,
            messages: visible,
            tools: self.tools,
            params: self.params,
            extensions: self.extensions,
            ephemeral: self.ephemeral,
        })
    }
}

fn validate_system_instruction(parts: &[Part]) -> Result<(), RequestError> {
    if is_valid_system_instruction(parts) {
        return Ok(());
    }

    let mut invalid_index = 0;
    for (index, part) in parts.iter().enumerate() {
        if part.kind().known() != Some(KnownPartKind::Text) || part.fields().text().is_empty() {
            invalid_index = index;
            break;
        }
    }
    let part = &parts[invalid_index];
    match part.kind().known() {
        None => Err(RequestError::UnknownSystemInstruction {
            index: invalid_index,
            kind: part.kind().as_i64(),
        }),
        Some(KnownPartKind::Text) => Err(RequestError::EmptySystemInstructionText {
            index: invalid_index,
        }),
        Some(_) => Err(RequestError::NonTextSystemInstruction {
            index: invalid_index,
            kind: part.kind().as_i64(),
        }),
    }
}

fn is_model_visible(item: &Item) -> bool {
    match item {
        Item::User(user) => user.visibility() == ModelVisibility::Visible,
        Item::Assistant(assistant) => assistant.visibility() == ModelVisibility::Visible,
        Item::ToolResult(result) => result.visibility() == ModelVisibility::Visible,
        Item::System(system) => system.visibility() == ModelVisibility::Visible,
    }
}

/// Validates the visible projection and returns every globally used call id.
///
/// This is the authoritative exchange walk used both by formal request freezing
/// and by hook-output validation against the same frozen transcript.
fn validate_model_messages(messages: &[Item]) -> Result<HashSet<String>, RequestError> {
    let mut pending = HashMap::<String, String>::new();
    let mut seen = HashSet::<String>::new();
    for item in messages.iter().filter(|item| is_model_visible(item)) {
        match item {
            Item::User(_) | Item::System(_) if !pending.is_empty() => {
                return Err(RequestError::ToolExchangeNotClosed);
            }
            Item::Assistant(assistant) => {
                if !pending.is_empty() {
                    return Err(RequestError::ToolExchangeNotClosed);
                }
                validate_assistant_tool_calls(assistant, &mut pending, &mut seen)?;
            }
            Item::ToolResult(result) => {
                validate_tool_result(result.call_id(), result.tool_name(), &mut pending)?;
            }
            Item::User(_) | Item::System(_) => {}
        }
    }
    if !pending.is_empty() {
        return Err(RequestError::UnresolvedToolCalls {
            count: pending.len(),
        });
    }
    Ok(seen)
}

/// Validates one hook-produced assistant against the frozen transcript.
///
/// Visible call identities share the exact global `seen` set built by
/// [`RequestPlan::try_into_request`]. Hidden records remain outside that set, as
/// they do during request projection, while their own call shape and within-record
/// uniqueness are still checked for lifecycle-coordinate safety.
pub(crate) fn validate_assistant(
    assistant: &Assistant,
    transcript: &[Item],
) -> Result<(), RequestError> {
    let mut seen = if assistant.visibility() == ModelVisibility::Visible {
        validate_model_messages(transcript)?
    } else {
        HashSet::new()
    };
    validate_assistant_tool_calls(assistant, &mut HashMap::new(), &mut seen)
}

fn validate_assistant_tool_calls(
    assistant: &Assistant,
    pending: &mut HashMap<String, String>,
    seen: &mut HashSet<String>,
) -> Result<(), RequestError> {
    for segment in assistant.content() {
        if let Segment::ToolCall { call, .. } = segment {
            validate_tool_call(call, pending, seen)?;
        }
    }
    Ok(())
}

fn validate_tool_call(
    call: &ToolCall,
    pending: &mut HashMap<String, String>,
    seen: &mut HashSet<String>,
) -> Result<(), RequestError> {
    let call_id = call.id().as_str();
    if call_id.is_empty() {
        return Err(RequestError::EmptyToolCallId);
    }
    if call.name().as_str().is_empty() {
        return Err(RequestError::EmptyToolCallName {
            call_id: call_id.into(),
        });
    }
    if !seen.insert(call_id.into()) {
        return Err(RequestError::DuplicateToolCallId {
            call_id: call_id.into(),
        });
    }
    pending.insert(call_id.into(), call.name().as_str().into());
    Ok(())
}

fn validate_tool_result(
    call_id: &Id,
    tool_name: &tool_call::Name,
    pending: &mut HashMap<String, String>,
) -> Result<(), RequestError> {
    let call_id = call_id.as_str();
    if call_id.is_empty() {
        return Err(RequestError::EmptyToolResultId);
    }
    if tool_name.as_str().is_empty() {
        return Err(RequestError::EmptyToolResultName {
            call_id: call_id.into(),
        });
    }
    let Some(expected) = pending.get(call_id) else {
        return Err(RequestError::OrphanToolResult {
            call_id: call_id.into(),
        });
    };
    if expected != tool_name.as_str() {
        return Err(RequestError::ToolResultNameMismatch {
            call_id: call_id.into(),
            expected: expected.clone(),
            actual: tool_name.as_str().into(),
        });
    }
    pending.remove(call_id);
    Ok(())
}

/// The complete owned input to one model call.
///
/// Its fields are immutable from the public API; provider adapters receive an
/// owned value and must map local tools and hosted extensions through their
/// distinct lanes.
#[derive(Clone, Debug)]
pub struct Request {
    system_instruction: Vec<Part>,
    messages: Vec<Item>,
    tools: Vec<ClientTool>,
    params: SamplingParams,
    extensions: Vec<Envelope>,
    ephemeral: Vec<Part>,
}

impl Request {
    /// Returns ordered portable system content.
    #[must_use]
    pub fn system_instruction(&self) -> &[Part] {
        &self.system_instruction
    }
    /// Returns the owned transcript projection.
    ///
    /// Every item here is [`ModelVisibility::Visible`] and every tool exchange in it is
    /// closed, because [`RequestPlan::try_into_request`] is the only way to build this
    /// value and it applies both rules. A provider adapter maps what it is
    /// given; it never has to decide what the model may see.
    #[must_use]
    pub fn messages(&self) -> &[Item] {
        &self.messages
    }
    /// Returns only client-local tools.
    #[must_use]
    pub fn tools(&self) -> &[ClientTool] {
        &self.tools
    }
    /// Returns frozen sampling controls.
    #[must_use]
    pub const fn sampling(&self) -> &SamplingParams {
        &self.params
    }
    /// Returns only provider-hosted/model-native extensions.
    #[must_use]
    pub fn extensions(&self) -> &[Envelope] {
        &self.extensions
    }
    /// Returns volatile tail content for this call.
    ///
    /// Ephemeral content is a lane of its own: it is never an [`Item`], never
    /// enters the transcript, and never survives the Step that produced it. A
    /// replay or equivalence check drawn over the transcript, or over
    /// [`Request::messages`], therefore already excludes it and needs no
    /// separate switch to say so.
    #[must_use]
    pub fn ephemeral(&self) -> &[Part] {
        &self.ephemeral
    }
}

/// Static identity and capabilities snapshotted by an Agent revision.
///
/// Every [`Client`] has to return one of these, so a later capability flag would
/// break every provider in existence if callers built it with a struct literal.
/// Fields are therefore private: construction goes through [`Info::new`] plus the
/// capability setters, and a capability added later defaults to "unsupported" for
/// providers that predate it.
///
/// # The named capability set is closed
///
/// A named field is admissible here only when it states something about a
/// reef-owned primitive: [`Info::supports_tools`] is a statement about reef's
/// tool mechanism, [`Info::supports_thinking`] about
/// [`Segment::Thinking`] and
/// [`ContentKind::Thinking`], [`Info::supports_vision`] about non-text
/// [`PartKind`](crate::value::content::PartKind)s, and
/// [`Info::context_window`] is a count of reef's own
/// [`Item`] budget. Wire-protocol quirks, thinking formats, pricing tiers and
/// session-affinity formats describe providers rather than reef primitives, so
/// they travel in the [`Envelope`] extension channel and core never learns their
/// vocabulary.
///
/// ```
/// use reef_core::opaque;
/// use reef_core::runtime::model;
///
/// let info = model::Info::new("example-model".to_owned(), 200_000)
///     .with_tools(true)
///     .with_thinking(true)
///     .with_extension(
///         opaque::Envelope::try_new(
///             "example.compat".to_owned(),
///             "matrix".to_owned(),
///             opaque::Payload::copy_from_slice(br#"{"thinkingFormat":"example"}"#),
///         )
///         .unwrap(),
///     );
///
/// assert_eq!(info.id(), "example-model");
/// assert_eq!(info.context_window(), 200_000);
/// assert!(info.supports_tools() && info.supports_thinking() && !info.supports_vision());
/// // Provider-defined bytes; core never parsed them.
/// let compat = info.extension("example.compat", "matrix").unwrap();
/// assert_eq!(compat.as_bytes(), br#"{"thinkingFormat":"example"}"#);
/// assert!(info.extension("example.compat", "absent").is_none());
/// ```
///
/// # Equality
///
/// Field by field, and the extension list **in order**. Two snapshots are equal
/// when they name the same model, state the same context window, answer every
/// capability the same way, and carry the same extensions in the same
/// positions; an [`Envelope`] compares by the byte-wise rule that type
/// documents, so equality here inherits it rather than interpreting a payload.
/// The identifier compares exactly — no case folding, no trimming — because it
/// is a provider-owned string core assigns no structure to.
///
/// Ordering is part of it because [`Info::extensions`] publishes insertion
/// order. A set-like equality would let `a == b` hold while
/// `a.extensions() != b.extensions()`, which is a value disagreeing with its own
/// accessor; and a provider whose snapshot lists its extensions in a different
/// order on each call is not returning the immutable snapshot this type is
/// documented to be, so the stricter reading is also the one that catches that.
///
/// The relation is total, so this is an [`Eq`]. Growth stays additive: a
/// capability added later has a defined "unsupported" default, so two values
/// that were equal before it existed are still equal after.
///
/// ```
/// use reef_core::opaque;
/// use reef_core::runtime::model;
///
/// let extension = |kind: &str| {
///     opaque::Envelope::try_new(
///         "example.compat".to_owned(),
///         kind.to_owned(),
///         opaque::Payload::copy_from_slice(b"{}"),
///     )
///     .unwrap()
/// };
/// let info = |first: &str, second: &str| {
///     model::Info::new("example-model".to_owned(), 200_000)
///         .with_extensions([extension(first), extension(second)])
/// };
///
/// assert_eq!(info("a", "b"), info("a", "b"));
/// // The same two facts, listed the other way round.
/// assert_ne!(info("a", "b"), info("b", "a"));
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Info {
    id: String,
    context_window: u64,
    supports_tools: bool,
    supports_vision: bool,
    supports_thinking: bool,
    extensions: Vec<Envelope>,
}

impl Info {
    /// Creates a capability snapshot that supports nothing beyond plain text.
    #[must_use]
    pub const fn new(id: String, context_window: u64) -> Self {
        Self {
            id,
            context_window,
            supports_tools: false,
            supports_vision: false,
            supports_thinking: false,
            extensions: Vec::new(),
        }
    }

    /// Declares whether client-local tool calling is supported.
    #[must_use]
    pub const fn with_tools(mut self, supported: bool) -> Self {
        self.supports_tools = supported;
        self
    }

    /// Declares whether image input is supported.
    #[must_use]
    pub const fn with_vision(mut self, supported: bool) -> Self {
        self.supports_vision = supported;
        self
    }

    /// Declares whether reasoning output is supported.
    #[must_use]
    pub const fn with_thinking(mut self, supported: bool) -> Self {
        self.supports_thinking = supported;
        self
    }

    /// Appends one provider-supplied capability fact.
    #[must_use]
    pub fn with_extension(mut self, extension: Envelope) -> Self {
        self.extensions.push(extension);
        self
    }

    /// Appends provider-supplied capability facts in iteration order.
    #[must_use]
    pub fn with_extensions(mut self, extensions: impl IntoIterator<Item = Envelope>) -> Self {
        self.extensions.extend(extensions);
        self
    }

    /// Returns the provider model identifier.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns the maximum input size in tokens.
    #[must_use]
    pub const fn context_window(&self) -> u64 {
        self.context_window
    }

    /// Reports whether client-local tool calling is supported.
    #[must_use]
    pub const fn supports_tools(&self) -> bool {
        self.supports_tools
    }

    /// Reports whether image input is supported.
    #[must_use]
    pub const fn supports_vision(&self) -> bool {
        self.supports_vision
    }

    /// Reports whether reasoning output is supported.
    #[must_use]
    pub const fn supports_thinking(&self) -> bool {
        self.supports_thinking
    }

    /// Returns every provider-supplied capability fact in insertion order.
    #[must_use]
    pub fn extensions(&self) -> &[Envelope] {
        &self.extensions
    }

    /// Returns the first capability fact matching `namespace` and `kind`.
    #[must_use]
    pub fn extension(&self, namespace: &str, kind: &str) -> Option<&Payload> {
        self.extensions
            .iter()
            .find(|extension| extension.namespace() == namespace && extension.kind() == kind)
            .map(Envelope::data)
    }
}

/// Portable semantic reason for generation completion.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CompletionReason {
    /// Provider supplied no portable classification.
    Unknown,
    /// The model ended normally.
    Stop,
    /// An output limit was reached.
    Length,
    /// The model requested one or more tools.
    ToolCalls,
    /// Provider safety filtering ended generation.
    ContentFilter,
}

/// Token consumption reported by a provider, as one increment.
///
/// This is the payload of [`Event::Usage`], which is incremental: these five
/// numbers describe the tokens consumed since the previous usage event of the
/// same generation, and a consumer adds them up.
///
/// ```
/// use reef_core::runtime::model;
///
/// // The common case: a provider that reports one total per call.
/// let usage = model::TokenUsage::new(1_200, 340);
/// assert_eq!(usage.total, 1_540);
///
/// // A provider that also breaks its counts down. Neither detail is added to
/// // the count it belongs to; both are already inside it.
/// let detailed = model::TokenUsage::new(1_200, 340)
///     .with_cached(900)
///     .with_reasoning(210);
/// assert_eq!(detailed.prompt, 1_200);
/// assert_eq!(detailed.total, 1_540);
/// assert_eq!(detailed.cached, 900);
/// assert_eq!(detailed.reasoning, 210);
/// ```
///
/// # What the five numbers mean
///
/// The two detail fields are **parts of** the counts above them, not additions
/// to them, which is the convention providers that report them already use. An
/// adapter that added them separately would make every budget over-count.
///
/// - `prompt` is every input token, `cached` included.
/// - `completion` is every output token, `reasoning` included.
/// - `total` is the provider's own total for this increment. [`Self::new`] sets
///   it to `prompt + completion`, which is what a provider that reports no
///   separate total means; [`Self::with_total`] states a different one, for a
///   provider that does.
///
/// # The fields are public, deliberately
///
/// Every other value type in this crate hides its fields, and this one does not,
/// because the rule is about who has to construct the value rather than about
/// consistency of style. A struct that a trait method *returns* — [`Info`], two
/// types away — must be buildable by every provider that will ever exist, so a
/// field added later would break all of them, and its fields are private with a
/// builder in front. A `TokenUsage` is built inside one optional event, and read
/// by policies that want all five numbers at once. Privatising the fields would
/// add five getters to the five setters, make the `#[non_exhaustive]` above a
/// no-op that then has to be removed, and buy nothing: the attribute already
/// stops an external struct literal, so a sixth field stays additive either way.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct TokenUsage {
    /// Input tokens consumed, including [`cached`](Self::cached).
    pub prompt: u64,
    /// Output tokens generated, including [`reasoning`](Self::reasoning).
    pub completion: u64,
    /// Provider-reported total for this increment.
    pub total: u64,
    /// The part of [`prompt`](Self::prompt) that was served from cache.
    pub cached: u64,
    /// The part of [`completion`](Self::completion) that was reasoning.
    pub reasoning: u64,
}

impl TokenUsage {
    /// Reports one increment of input and output tokens.
    ///
    /// `total` becomes `prompt + completion`, saturating; the two detail fields
    /// are zero. Each is stated separately by the builder below when a provider
    /// reports it.
    #[must_use]
    pub const fn new(prompt: u64, completion: u64) -> Self {
        Self {
            prompt,
            completion,
            total: prompt.saturating_add(completion),
            cached: 0,
            reasoning: 0,
        }
    }

    /// States a provider-reported total that is not `prompt + completion`.
    #[must_use]
    pub const fn with_total(mut self, total: u64) -> Self {
        self.total = total;
        self
    }

    /// States how much of [`prompt`](Self::prompt) came from cache.
    #[must_use]
    pub const fn with_cached(mut self, cached: u64) -> Self {
        self.cached = cached;
        self
    }

    /// States how much of [`completion`](Self::completion) was reasoning.
    #[must_use]
    pub const fn with_reasoning(mut self, reasoning: u64) -> Self {
        self.reasoning = reasoning;
        self
    }
}

/// Whether a streamed portable content item is answer text or reasoning.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContentKind {
    /// User-visible assistant answer text.
    Text,
    /// Model reasoning or thinking content.
    Thinking,
}

/// One normalized event produced by a model provider adapter.
///
/// Deltas open an item identity and finals close it. Tool calls have an explicit
/// start/arguments/final lifecycle; [`StreamGrammar`] validates every pairing.
///
/// **Deltas are optional.** A provider that answers in one frame emits the final
/// alone, and the final's payload is the whole item; see
/// [`StreamGrammar::accept`]. What a final may never do is contradict deltas
/// that were actually sent.
#[derive(Clone)]
pub enum Event {
    /// A fragment of one text or thinking item.
    ContentDelta {
        /// Stable item identity.
        id: String,
        /// Portable content lane.
        kind: ContentKind,
        /// Next exact text fragment.
        delta: String,
    },
    /// The complete content and extensions for the same item.
    ContentFinal {
        /// Identity opened by preceding deltas, or by this event when there were
        /// none.
        id: String,
        /// Content lane, matching every delta.
        kind: ContentKind,
        /// The whole item: the exact concatenation of all deltas, or, when no
        /// delta was sent, the content itself.
        content: String,
        /// Provider data owned by this final item.
        extensions: SegmentExtensions,
    },
    /// Opens a client-local tool call.
    ///
    /// A provider that delivers a call complete in one frame may omit this and
    /// send only [`ToolCallFinal`](Event::ToolCallFinal), which names the tool
    /// itself.
    ToolCallStart {
        /// Model-assigned call identity.
        id: Id,
        /// Selected local tool name.
        name: tool_call::Name,
    },
    /// Adds opaque argument bytes to the open tool call.
    ToolCallArgumentsDelta {
        /// Identity of the open call.
        id: Id,
        /// Next exact argument fragment.
        delta: Payload,
    },
    /// Closes a tool call with the exact accumulated identity, name, and bytes.
    ///
    /// When no argument delta preceded it, this event *is* the call: its
    /// identity, tool name and argument bytes are the whole of what reef records
    /// and what the executor receives.
    ToolCallFinal {
        /// Complete call value.
        call: ToolCall,
        /// Provider data owned by this call.
        extensions: SegmentExtensions,
    },
    /// Reports token accounting without changing item lifecycle.
    ///
    /// # Usage is incremental, and normalising it is the adapter's obligation
    ///
    /// A generation may carry any number of these. **Each one reports the tokens
    /// consumed since the previous `Usage` of the same generation**, so a
    /// generation's totals are the sum of its usage events, and one event
    /// carrying the whole call's totals is the ordinary single-increment case.
    ///
    /// Reef does not and cannot check this. A provider that reports running
    /// totals and a provider that reports increments emit sequences core has no
    /// way to tell apart, so the rule is an obligation on the adapter rather than
    /// a grammar rule: **an adapter for a provider that reports running totals
    /// must emit the difference**, or withhold the numbers and emit one event at
    /// the end. An adapter that forwards running totals verbatim is not
    /// well-formed, and nothing will say so.
    ///
    /// The rule is chosen because summation is the only operation available to
    /// the consumer that receives these. They reach a hook through
    /// [`ObserverHooks::model_event`](crate::runtime::hook::ObserverHooks::model_event)
    /// and nowhere else, one event at a time, with no per-generation accumulator
    /// of reef's own to subtract from — so a budget policy adds them up. Under
    /// the incremental rule that is exact at every scope: within a generation,
    /// across the generations of a Run, and across Runs. Forwarded running
    /// totals would double-count, and every budget built on them would fire
    /// early.
    Usage(TokenUsage),
    /// The single terminal event.
    Done {
        /// Provider's verbatim finish label.
        finish_reason: String,
        /// Portable completion classification.
        completion: CompletionReason,
        /// Provider data owned by the assistant record.
        provider_data: Vec<Envelope>,
    },
}

impl fmt::Debug for Event {
    /// Keeps every identity and lane, and sizes the two content fields.
    ///
    /// `delta` and `content` are the only members of this enum that own model
    /// bytes directly. Everything else either identifies an item, classifies a
    /// lane, counts tokens, or is a value that already redacts itself — and a
    /// stream is debugged by its lifecycle, which those facts describe fully.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ContentDelta { id, kind, delta } => formatter
                .debug_struct("ContentDelta")
                .field("id", id)
                .field("kind", kind)
                .field("delta", &redact::Bytes(delta.len()))
                .finish(),
            Self::ContentFinal {
                id,
                kind,
                content,
                extensions,
            } => formatter
                .debug_struct("ContentFinal")
                .field("id", id)
                .field("kind", kind)
                .field("content", &redact::Bytes(content.len()))
                .field("extensions", extensions)
                .finish(),
            Self::ToolCallStart { id, name } => formatter
                .debug_struct("ToolCallStart")
                .field("id", id)
                .field("name", name)
                .finish(),
            Self::ToolCallArgumentsDelta { id, delta } => formatter
                .debug_struct("ToolCallArgumentsDelta")
                .field("id", id)
                .field("delta", delta)
                .finish(),
            Self::ToolCallFinal { call, extensions } => formatter
                .debug_struct("ToolCallFinal")
                .field("call", call)
                .field("extensions", extensions)
                .finish(),
            Self::Usage(usage) => formatter.debug_tuple("Usage").field(usage).finish(),
            Self::Done {
                finish_reason,
                completion,
                provider_data,
            } => formatter
                .debug_struct("Done")
                .field("finish_reason", finish_reason)
                .field("completion", completion)
                .field("provider_data", provider_data)
                .finish(),
        }
    }
}

/// A stable normalized-stream grammar violation.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum StreamError {
    /// An item identity was empty.
    EmptyItemId,
    /// A tool name was empty.
    EmptyToolName,
    /// An identity was reopened or reused after completion.
    DuplicateItemId(String),
    /// An event did not match the identity's active lifecycle.
    InvalidLifecycle(String),
    /// A final payload differed from accumulated deltas.
    FinalPayloadMismatch(String),
    /// Terminal arrived while one or more items remained open.
    UnfinishedItems,
    /// An event was observed after terminal.
    EventAfterDone,
    /// End-of-stream occurred without terminal.
    MissingTerminal,
}

impl fmt::Display for StreamError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyItemId => formatter.write_str("model stream item id is empty"),
            Self::EmptyToolName => formatter.write_str("model stream tool name is empty"),
            Self::DuplicateItemId(id) => write!(formatter, "duplicate model stream item id: {id}"),
            Self::InvalidLifecycle(id) => {
                write!(formatter, "invalid model stream lifecycle for: {id}")
            }
            Self::FinalPayloadMismatch(id) => {
                write!(formatter, "model stream final payload mismatch for: {id}")
            }
            Self::UnfinishedItems => {
                formatter.write_str("model stream terminal has unfinished items")
            }
            Self::EventAfterDone => {
                formatter.write_str("model stream event emitted after terminal")
            }
            Self::MissingTerminal => formatter.write_str("model stream ended without terminal"),
        }
    }
}

impl Error for StreamError {}

enum OpenItem {
    Content { kind: ContentKind, value: String },
    Tool { name: String, arguments: Vec<u8> },
}

/// Incremental validator for exactly one [`Client`] event stream.
#[derive(Default)]
pub struct StreamGrammar {
    open: HashMap<String, OpenItem>,
    seen: HashSet<String>,
    done: bool,
}

impl fmt::Debug for StreamGrammar {
    /// Reports the validator's position in the stream, not the stream.
    ///
    /// The open map accumulates the exact text and argument bytes each item has
    /// produced so far, so it is counted rather than shown; the counts and the
    /// terminal flag are what a grammar violation is actually diagnosed from.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("StreamGrammar")
            .field("open", &self.open.len())
            .field("seen", &self.seen.len())
            .field("done", &self.done)
            .finish()
    }
}

impl StreamGrammar {
    /// Creates a validator before the first event.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Validates one event without taking ownership from its consumer.
    ///
    /// # Errors
    ///
    /// A rejected event means the provider's stream is not a well-formed
    /// sequence, which the caller must treat as a failed generation rather than
    /// as a recoverable gap: the accumulated state is no longer a faithful
    /// picture of what the provider sent.
    ///
    /// - [`EventAfterDone`](StreamError::EventAfterDone) for anything at all
    ///   after the terminal event. Checked before the event's own shape, because
    ///   after a terminal there is no lifecycle left to be consistent with.
    /// - [`EmptyItemId`](StreamError::EmptyItemId) for an event with no identity,
    ///   and [`EmptyToolName`](StreamError::EmptyToolName) for a tool event that
    ///   does not name a tool. Neither can be correlated with anything.
    /// - [`DuplicateItemId`](StreamError::DuplicateItemId) if an identity that
    ///   already completed is opened again. Identities are single-use for the
    ///   whole stream, so a reused one is a provider defect rather than a second
    ///   item.
    /// - [`InvalidLifecycle`](StreamError::InvalidLifecycle) if the event does not
    ///   fit the identity's active state — content deltas for a tool call, a
    ///   tool final for an identity opened as content, or a content kind that
    ///   changed mid-item.
    /// - [`FinalPayloadMismatch`](StreamError::FinalPayloadMismatch) if a final
    ///   payload is not exactly what the deltas accumulated. This is the check
    ///   that makes incremental output trustworthy: a consumer that rendered the
    ///   deltas has already shown the user something, so a final that disagrees
    ///   cannot be silently preferred.
    /// - [`UnfinishedItems`](StreamError::UnfinishedItems) if the terminal event
    ///   arrives while any identity is still open.
    ///
    /// # Deltas are optional
    ///
    /// A final may open its own item. [`Event::ContentFinal`] for an identity no
    /// delta ever opened, and [`Event::ToolCallFinal`] whose call accumulated no
    /// [`ToolCallArgumentsDelta`](Event::ToolCallArgumentsDelta) — whether or not
    /// a [`ToolCallStart`](Event::ToolCallStart) announced it — are both
    /// well-formed, and the final's payload is the item. A provider that answers
    /// in one frame is not required to synthesise a delta equal to its own
    /// payload, which is the workaround every adapter for such a provider would
    /// otherwise have to invent.
    ///
    /// Nothing about the mismatch rule is relaxed by this. What
    /// `FinalPayloadMismatch` protects is a consumer that has *already rendered*
    /// something, so it applies exactly when deltas were sent: a final that
    /// contradicts a non-empty accumulation is still rejected. With no deltas
    /// there is nothing rendered for the final to contradict.
    ///
    /// Identities are spent either way. A single-frame final inserts its
    /// identity, so reusing it afterwards is
    /// [`DuplicateItemId`](StreamError::DuplicateItemId) exactly as reusing a
    /// streamed one is.
    pub fn accept(&mut self, event: &Event) -> Result<(), StreamError> {
        if self.done {
            return Err(StreamError::EventAfterDone);
        }
        match event {
            Event::ContentDelta { id, kind, delta } => self.content_delta(id, *kind, delta),
            Event::ContentFinal {
                id, kind, content, ..
            } => self.content_final(id, *kind, content),
            Event::ToolCallStart { id, name } => self.tool_start(id, name),
            Event::ToolCallArgumentsDelta { id, delta } => self.tool_delta(id, delta),
            Event::ToolCallFinal { call, .. } => self.tool_final(call),
            Event::Usage(_) => Ok(()),
            Event::Done { .. } if self.open.is_empty() => {
                self.done = true;
                Ok(())
            }
            Event::Done { .. } => Err(StreamError::UnfinishedItems),
        }
    }

    /// Verifies that the producer ended after exactly one terminal event.
    ///
    /// # Errors
    ///
    /// [`MissingTerminal`](StreamError::MissingTerminal) if the stream ended
    /// without one. This is the one violation [`accept`](Self::accept) cannot
    /// report, because it is the absence of an event rather than a bad one: a
    /// stream that simply stops is indistinguishable, event by event, from one
    /// that is still going.
    pub fn finish(self) -> Result<(), StreamError> {
        if self.done {
            Ok(())
        } else {
            Err(StreamError::MissingTerminal)
        }
    }

    fn content_delta(
        &mut self,
        id: &str,
        kind: ContentKind,
        delta: &str,
    ) -> Result<(), StreamError> {
        self.require_id(id)?;
        if let Some(item) = self.open.get_mut(id) {
            return match item {
                OpenItem::Content {
                    kind: active,
                    value,
                } if *active == kind => {
                    value.push_str(delta);
                    Ok(())
                }
                _ => Err(StreamError::InvalidLifecycle(id.into())),
            };
        }
        if !self.seen.insert(id.into()) {
            return Err(StreamError::DuplicateItemId(id.into()));
        }
        self.open.insert(
            id.into(),
            OpenItem::Content {
                kind,
                value: delta.into(),
            },
        );
        Ok(())
    }

    fn content_final(
        &mut self,
        id: &str,
        kind: ContentKind,
        content: &str,
    ) -> Result<(), StreamError> {
        self.require_id(id)?;
        match self.open.get(id) {
            Some(OpenItem::Content {
                kind: active,
                value,
            }) if *active == kind && value == content => {}
            Some(OpenItem::Content { kind: active, .. }) if *active == kind => {
                return Err(StreamError::FinalPayloadMismatch(id.into()));
            }
            Some(_) => return Err(StreamError::InvalidLifecycle(id.into())),
            // A provider that does not stream sends the whole item in one
            // frame. Nothing was accumulated, so nothing can disagree with the
            // final, and the identity is spent exactly as a streamed one is.
            None => {
                if self.seen.insert(id.into()) {
                    return Ok(());
                }
                return Err(StreamError::DuplicateItemId(id.into()));
            }
        }
        self.open.remove(id);
        Ok(())
    }

    fn tool_start(&mut self, id: &Id, name: &tool_call::Name) -> Result<(), StreamError> {
        let id = id.as_str();
        self.require_id(id)?;
        if name.as_str().is_empty() {
            return Err(StreamError::EmptyToolName);
        }
        if !self.seen.insert(id.into()) {
            return Err(StreamError::DuplicateItemId(id.into()));
        }
        self.open.insert(
            id.into(),
            OpenItem::Tool {
                name: name.as_str().into(),
                arguments: Vec::new(),
            },
        );
        Ok(())
    }

    fn tool_delta(&mut self, id: &Id, delta: &Payload) -> Result<(), StreamError> {
        let id = id.as_str();
        self.require_id(id)?;
        match self.open.get_mut(id) {
            Some(OpenItem::Tool { arguments, .. }) => {
                arguments.extend_from_slice(delta.as_bytes());
                Ok(())
            }
            _ => Err(StreamError::InvalidLifecycle(id.into())),
        }
    }

    fn tool_final(&mut self, call: &ToolCall) -> Result<(), StreamError> {
        let id = call.id().as_str();
        self.require_id(id)?;
        if call.name().as_str().is_empty() {
            return Err(StreamError::EmptyToolName);
        }
        match self.open.get(id) {
            // An open call with nothing accumulated is the single-frame shape:
            // the start announced the call and the final carries all of it.
            Some(OpenItem::Tool { name, arguments })
                if name == call.name().as_str()
                    && (arguments.is_empty() || arguments == call.arguments().as_bytes()) => {}
            Some(OpenItem::Tool { .. }) => {
                return Err(StreamError::FinalPayloadMismatch(id.into()));
            }
            Some(OpenItem::Content { .. }) => {
                return Err(StreamError::InvalidLifecycle(id.into()));
            }
            // A call announced by its own final, with no start at all.
            None => {
                if self.seen.insert(id.into()) {
                    return Ok(());
                }
                return Err(StreamError::DuplicateItemId(id.into()));
            }
        }
        self.open.remove(id);
        Ok(())
    }

    const fn require_id(&self, id: &str) -> Result<(), StreamError> {
        if id.is_empty() {
            Err(StreamError::EmptyItemId)
        } else {
            Ok(())
        }
    }
}

/// Narrow, statically dispatched model provider boundary.
///
/// This is the one trait reef cannot ship an implementation of: it is the
/// adapter between reef's [`Request`] and whatever actually answers it. Two
/// methods, one of which is a constant.
///
/// The explicit RPITIT future follows ADR-013 and avoids `async-trait`. The
/// returned stream remains provider-owned; callers must apply [`StreamGrammar`].
///
/// # Implementing it
///
/// [`Client::Stream`] is bounded by [`Stream`], which lives in `futures-core`.
/// That crate is deliberately combinator-free — there is no `stream::iter` and
/// no `StreamExt` — so the associated type is a type you write, with a
/// `poll_next`, and it is about ten lines. Reach for the bound through
/// [`reef_core::futures_core`](crate::futures_core) rather than adding the crate
/// yourself, so the two versions cannot disagree.
///
/// This is the whole of a provider that replays a fixed script, which is what a
/// test double looks like:
///
/// ```
/// use std::future::{Future, ready};
/// use std::pin::Pin;
/// use std::task::{Context, Poll};
///
/// use reef_core::futures_core::Stream;
/// use reef_core::runtime::model;
/// use reef_core::value::content;
///
/// /// The events of one call, oldest first.
/// #[derive(Debug)]
/// struct Scripted(std::collections::VecDeque<model::Event>);
///
/// impl Stream for Scripted {
///     type Item = Result<model::Event, Unreachable>;
///
///     fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
///         // A script is always ready, so this never registers a waker. A real
///         // adapter polls its transport here and returns `Poll::Pending` when
///         // that transport has registered one.
///         Poll::Ready(self.0.pop_front().map(Ok))
///     }
/// }
///
/// #[derive(Debug)]
/// struct Unreachable;
///
/// impl std::fmt::Display for Unreachable {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         f.write_str("a scripted provider cannot fail")
///     }
/// }
///
/// impl std::error::Error for Unreachable {}
///
/// #[derive(Debug)]
/// struct ScriptedModel;
///
/// impl model::Client for ScriptedModel {
///     type Error = Unreachable;
///     type Stream = Scripted;
///
///     fn info(&self) -> model::Info {
///         model::Info::new("scripted/v1".to_owned(), 8_192).with_tools(true)
///     }
///
///     fn generate(
///         &self,
///         request: model::Request,
///     ) -> impl Future<Output = Result<Self::Stream, Self::Error>> + Send {
///         // `request.messages()` is already projected: every item in it is
///         // model-visible and every tool exchange in it is closed.
///         let _turns = request.messages().len();
///         ready(Ok(Scripted(
///             [
///                 model::Event::ContentFinal {
///                     id: "answer".to_owned(),
///                     kind: model::ContentKind::Text,
///                     content: "Hello.".to_owned(),
///                     extensions: content::SegmentExtensions::new(String::new(), None, None),
///                 },
///                 model::Event::Usage(model::TokenUsage::new(12, 3)),
///                 model::Event::Done {
///                     finish_reason: "stop".to_owned(),
///                     completion: model::CompletionReason::Stop,
///                     provider_data: Vec::new(),
///                 },
///             ]
///             .into(),
///         )))
///     }
/// }
/// ```
///
/// Every event that stream yields is checked by [`StreamGrammar`] before reef
/// acts on it, so an adapter can validate its own output against the same rules
/// in its own tests.
pub trait Client: Send + Sync {
    /// Provider-specific call failure.
    type Error: Error + Send + Sync + 'static;
    /// Normalized event stream for one call.
    type Stream: Stream<Item = Result<Event, Self::Error>> + Send;

    /// Returns the immutable model capability snapshot.
    fn info(&self) -> Info;
    /// Starts one model call from an owned request.
    fn generate(
        &self,
        request: Request,
    ) -> impl Future<Output = Result<Self::Stream, Self::Error>> + Send;
}