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
//! Immutable tool registration, per-Step exposure, mapping, and admission.
//!
//! The registration and snapshot split follows ADR-009. Runtime names are
//! validated here while [`crate::value::tool_call::Name`] remains the open
//! wire value validated at model boundaries.

use std::collections::HashSet;
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;
#[cfg(test)]
use std::task::{Context, Waker};

use crate::cancel::Token;

use crate::opaque::{Envelope, EnvelopeError, Payload};
use crate::redact;
use crate::runtime::event::ToolEmitter;
use crate::runtime::model::{ClientTool, RequestPlan};
use crate::transcript::store::Snapshot;
use crate::value::tool_call::{self, Id, ToolCall, ToolPartError, ToolResult};

/// A stable validation failure for a runtime tool name.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum NameError {
    /// The local name component is empty.
    EmptyLocal,
    /// A supplied namespace is empty.
    EmptyNamespace,
    /// A component contains the reserved namespace separator `/`.
    ReservedSeparator,
}

impl Display for NameError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyLocal => formatter.write_str("tool local name is empty"),
            Self::EmptyNamespace => formatter.write_str("tool namespace is empty"),
            Self::ReservedSeparator => formatter.write_str("tool name component contains '/'"),
        }
    }
}

impl Error for NameError {}

/// A nonempty, namespace-aware canonical runtime tool name.
///
/// The namespace is **syntax only**. Core owns the grammar — an optional
/// namespace component, one reserved `/` separator, both components non-empty —
/// and the canonical spelling used as the collision and routing key. It assigns
/// no meaning to any namespace value, reserves none, and derives no behaviour
/// from one; deciding what a namespace stands for is composition-layer policy.
///
/// Namespacing creates no resolution order: `a/x` and `x` are different
/// canonical names and never collide, while two registrations of `a/x` collide
/// regardless of which source produced each.
///
/// [`Name::to_wire`] and [`Name::parse_canonical`] are inverses, so a
/// composition layer that aggregates several tool sources can recover core's
/// exact collision key from an advertised spelling instead of re-implementing
/// the split.
///
/// ```
/// use reef_core::runtime::tool;
///
/// let scoped = tool::Name::namespaced("server".to_owned(), "search".to_owned()).unwrap();
/// let wire = scoped.to_wire();
/// assert_eq!(wire.as_str(), "server/search");
/// assert_eq!(tool::Name::parse_canonical(wire.as_str()).unwrap(), scoped);
///
/// // A namespaced name never collides with the bare local spelling.
/// let plain = tool::Name::parse_canonical("search").unwrap();
/// assert_eq!(plain.namespace(), None);
/// assert_ne!(plain, scoped);
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Name {
    namespace: Option<String>,
    local: String,
    canonical: String,
}

impl Name {
    /// Creates an unnamespaced tool name.
    ///
    /// # Errors
    ///
    /// [`NameError::EmptyLocal`] if `local` has no characters, or
    /// [`NameError::ReservedSeparator`] if it contains `/`. The separator is
    /// refused rather than escaped because it is the collision key's only
    /// structure: a local name carrying one would be indistinguishable from a
    /// namespaced name built by [`Name::namespaced`].
    pub fn local(local: String) -> Result<Self, NameError> {
        Self::from_parts(None, local)
    }

    /// Creates a namespaced tool name.
    ///
    /// # Errors
    ///
    /// [`NameError::EmptyLocal`] for an empty `local`,
    /// [`NameError::EmptyNamespace`] for an empty `namespace` — which would spell
    /// the same canonical name as an unnamespaced one while claiming to be
    /// scoped — or [`NameError::ReservedSeparator`] if either component contains
    /// `/`. Nothing here validates what the namespace means: core owns the
    /// grammar and reserves no value.
    pub fn namespaced(namespace: String, local: String) -> Result<Self, NameError> {
        Self::from_parts(Some(namespace), local)
    }

    /// Splits a canonical spelling back into its validated components.
    ///
    /// This is the exact inverse of [`Name::canonical`] and [`Name::to_wire`]:
    /// the spelling is split at its first reserved separator and the components
    /// are validated by the same rules [`Name::local`] and [`Name::namespaced`]
    /// apply, so no caller has to reproduce the split to obtain core's collision
    /// key.
    ///
    /// # Errors
    ///
    /// Returns [`NameError::EmptyLocal`] for an empty spelling or one ending in
    /// the separator, [`NameError::EmptyNamespace`] for one beginning with it,
    /// and [`NameError::ReservedSeparator`] for a spelling carrying more than
    /// one.
    pub fn parse_canonical(canonical: &str) -> Result<Self, NameError> {
        match canonical.split_once('/') {
            Some((namespace, local)) => {
                Self::from_parts(Some(namespace.to_owned()), local.to_owned())
            }
            None => Self::from_parts(None, canonical.to_owned()),
        }
    }

    fn from_parts(namespace: Option<String>, local: String) -> Result<Self, NameError> {
        if local.is_empty() {
            return Err(NameError::EmptyLocal);
        }
        if local.contains('/') {
            return Err(NameError::ReservedSeparator);
        }
        if matches!(namespace.as_deref(), Some("")) {
            return Err(NameError::EmptyNamespace);
        }
        if namespace
            .as_deref()
            .is_some_and(|value| value.contains('/'))
        {
            return Err(NameError::ReservedSeparator);
        }
        let canonical = namespace
            .as_ref()
            .map_or_else(|| local.clone(), |value| format!("{value}/{local}"));
        Ok(Self {
            namespace,
            local,
            canonical,
        })
    }

    /// Returns the optional namespace.
    #[must_use]
    pub fn namespace(&self) -> Option<&str> {
        self.namespace.as_deref()
    }

    /// Returns the nonempty local component.
    #[must_use]
    pub fn local_name(&self) -> &str {
        &self.local
    }

    /// Returns the stable canonical spelling used for collision and routing.
    #[must_use]
    pub fn canonical(&self) -> &str {
        &self.canonical
    }

    /// Renders the uninterpreted wire spelling advertised to a model.
    ///
    /// The result is a [`crate::value::tool_call::Name`], the open leaf value a
    /// model emission also arrives as, which is what makes the advertise/route
    /// round trip typed on both sides.
    #[must_use]
    pub fn to_wire(&self) -> tool_call::Name {
        tool_call::Name::new(self.canonical.clone())
    }
}

/// An owned, provider-neutral model descriptor.
///
/// [`Descriptor::input_schema`] is a [`Payload`] — uninterpreted owned bytes —
/// and it is the per-tool channel a composition layer constrains sampling
/// through. Core never parses it, so a strict JSON schema, a grammar, or a
/// provider-specific envelope around either are all expressible here, and the
/// adapter that writes the bytes is the same one that reads them. This is why
/// [`crate::runtime::model::SamplingParams::output_schema`] being request-level
/// is not a gap: the tool-level placement already exists, one level down.
#[derive(Clone)]
pub struct Descriptor {
    name: Name,
    description: String,
    input_schema: Payload,
}

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

impl Descriptor {
    /// Creates a descriptor from owned fields.
    #[must_use]
    pub const fn new(name: Name, description: String, input_schema: Payload) -> Self {
        Self {
            name,
            description,
            input_schema,
        }
    }

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

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

    /// Returns the provider-neutral input schema.
    ///
    /// Core assigns these bytes no meaning; they reach the provider unchanged as
    /// [`ClientTool::input_schema`].
    #[must_use]
    pub const fn input_schema(&self) -> &Payload {
        &self.input_schema
    }

    fn client_model_tool(&self) -> ClientTool {
        // Matches `ClientTool`'s owned producer shape.
        ClientTool::new(
            self.name.to_wire(),
            self.description.clone(),
            self.input_schema.clone(),
        )
    }
}

/// An ordinary executor failure that becomes a business result.
///
/// The message is what the model is told: reef records
/// [`Display`] as the tool's output and the transcript keeps text,
/// not types. So the message has to be complete on its own, and
/// [`with_source`](Self::with_source) does not extend it — attaching a source
/// keeps the concrete failure as a *value*, for whoever inspects this error in
/// process, and changes nothing about what the model reads.
///
/// That inspection is why the source exists. An executor almost always fails
/// *because* something underneath it did — an I/O error, a transport failure, a
/// timeout — and a composition layer that wraps executors, retries them, or
/// classifies their failures needs the reason by its type rather than by
/// matching on a sentence:
///
/// ```
/// use std::io;
/// use reef_core::runtime::tool;
///
/// let failure = tool::ExecutorError::new("reading the manifest failed".to_owned())
///     .with_source(io::Error::from(io::ErrorKind::NotFound));
///
/// // The message alone is what the model sees.
/// assert_eq!(failure.to_string(), "reading the manifest failed");
///
/// // The reason is still recoverable by its own type.
/// let cause = std::error::Error::source(&failure).expect("a source was attached");
/// let cause = cause.downcast_ref::<io::Error>().expect("the concrete cause");
/// assert_eq!(cause.kind(), io::ErrorKind::NotFound);
/// ```
#[derive(Clone)]
pub struct ExecutorError {
    message: String,
    source: Option<Arc<dyn Error + Send + Sync>>,
}

impl ExecutorError {
    /// Creates an owned executor diagnostic.
    #[must_use]
    pub const fn new(message: String) -> Self {
        Self {
            message,
            source: None,
        }
    }

    /// Retains the concrete failure this diagnostic is about.
    ///
    /// Returned from [`Error::source`], so the cause downcasts back to the
    /// caller's own type. It does not affect the message, equality, or what the
    /// model is told; see the type's own documentation for why.
    #[must_use]
    pub fn with_source(mut self, source: impl Error + Send + Sync + 'static) -> Self {
        self.source = Some(Arc::new(source));
        self
    }
}

impl fmt::Debug for ExecutorError {
    /// Renders the message and then every link of the chain, each through `Display`.
    ///
    /// Printing only the message would discard the reason
    /// [`with_source`](Self::with_source) retains, which is the part a reader is
    /// usually after. `Display` rather than the link's own `Debug`, because a
    /// cause is whatever an executor handed back: text this crate neither writes
    /// nor reviews, whose `Display` is the diagnostic the type is contracted to
    /// produce. This is the same rendering [`HookError`] uses.
    ///
    /// [`HookError`]: crate::runtime::hook::HookError
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        let mut tuple = formatter.debug_tuple("ExecutorError");
        tuple.field(&self.message);
        let mut link = Error::source(self);
        while let Some(error) = link {
            tuple.field(&error.to_string());
            link = error.source();
        }
        tuple.finish()
    }
}

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

/// Compares the diagnostic message and nothing else.
///
/// A retained source is an arbitrary third-party error with no equality of its
/// own, so there is no answer to whether two of them are "the same"; comparing
/// them by pointer would make two errors that say the same thing unequal, which
/// is worse than not comparing them. The message is what this type is compared
/// for — asserting on a diagnostic — so that is what equality means here.
impl PartialEq for ExecutorError {
    fn eq(&self, other: &Self) -> bool {
        self.message == other.message
    }
}

impl Eq for ExecutorError {}

impl Error for ExecutorError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source
            .as_ref()
            .map(|source| source.as_ref() as &(dyn Error + 'static))
    }
}

/// The closed per-call context supplied to one [`Executor::execute`].
///
/// This is trusted runtime-provided context, never a dependency-injection bag:
/// optional capabilities such as process execution are constructor-injected into
/// the concrete executor and never flow through here.
///
/// The struct has no public constructor and no public fields, so only a core
/// adapter can mint one. Its emit capability is limited to
/// [`crate::runtime::event::ToolEmitter`], which itself can only produce audit
/// and error facts, so producer authority and outward event state never leak to
/// an executor.
#[derive(Debug)]
pub struct Invocation {
    session_id: Option<String>,
    transcript: Snapshot,
    call_id: Id,
    emitter: ToolEmitter,
}

impl Invocation {
    /// Returns the trusted host-provided session identity, when one exists.
    ///
    /// Core does not require this to be nonempty or globally unique; treat it as
    /// correlation metadata rather than an authorization credential. Model tool
    /// arguments can never override it.
    #[must_use]
    pub fn session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    /// Returns the frozen Step-top transcript shared by every provider
    /// resolution and every invocation in the same Step.
    #[must_use]
    pub const fn transcript(&self) -> &Snapshot {
        &self.transcript
    }

    /// Returns the model-assigned identity of this invocation within its Step.
    #[must_use]
    pub const fn call_id(&self) -> &Id {
        &self.call_id
    }

    /// Returns the invocation-scoped audit/error emit capability.
    #[must_use]
    pub const fn emitter(&self) -> &ToolEmitter {
        &self.emitter
    }

    pub(crate) const fn new(
        session_id: Option<String>,
        transcript: Snapshot,
        call_id: Id,
        emitter: ToolEmitter,
    ) -> Self {
        Self {
            session_id,
            transcript,
            call_id,
            emitter,
        }
    }
}

/// A concrete executor with one registration-specific output type.
///
/// An executor returns whatever type is natural for it — a `String`, a struct, a
/// byte buffer — and [`Registration::client`] pairs that type with the one
/// mapper that turns it into a closed [`ToolResult`]. Nothing else in the crate
/// sees [`Executor::Output`], which is why it can be anything.
///
/// **An ordinary failure is not `Err`.** `Err(ExecutorError)` says the adapter
/// itself broke; a tool that ran and did not like what it found returns
/// `Ok(...)` and lets the mapper produce
/// [`crate::value::tool_call::ToolResult::BusinessError`],
/// which the model reads and can act on.
///
/// ```
/// use std::future::{Future, ready};
/// use std::sync::Arc;
///
/// use reef_core::cancel;
/// use reef_core::opaque;
/// use reef_core::runtime::tool;
/// use reef_core::value::tool_call;
///
/// #[derive(Debug)]
/// struct Reverse;
///
/// impl tool::Executor for Reverse {
///     type Output = String;
///
///     fn execute(
///         &self,
///         _invocation: &tool::Invocation,
///         call: &tool_call::ToolCall,
///         _cancellation: cancel::Token,
///     ) -> impl Future<Output = Result<Self::Output, tool::ExecutorError>> + Send {
///         // Arguments are uninterpreted bytes: reef never parsed them, and the
///         // schema this tool published is what promised their shape.
///         let arguments = String::from_utf8_lossy(call.arguments().as_bytes()).into_owned();
///         ready(Ok(arguments.chars().rev().collect()))
///     }
/// }
///
/// let registration = tool::Registration::client(
///     tool::Descriptor::new(
///         tool::Name::local("text.reverse".to_owned()).unwrap(),
///         "Reverses its arguments".to_owned(),
///         opaque::Payload::copy_from_slice(br#"{"type":"object"}"#),
///     ),
///     Arc::new(Reverse),
///     // The mapper is the only thing that sees `Output`.
///     Arc::new(|output: String| Ok(tool_call::ToolResult::success_text(output))),
/// );
/// assert_eq!(registration.lane(), tool::Lane::Client);
/// ```
///
/// # Cancellation
///
/// The future returned by [`execute`](Executor::execute) must be
/// cancellation-safe; that method's own documentation states exactly what reef
/// requires of it.
pub trait Executor: Send + Sync + 'static {
    /// Open adapter output consumed only by the paired registration mapper.
    type Output: Send + 'static;

    /// Executes one effective call under its closed invocation context; ordinary
    /// errors become business results only when execution completion wins its
    /// race with cancellation.
    ///
    /// The returned future must be cancellation-safe: its caller may drop it at
    /// any await point after first cancelling the supplied token. Dropping the
    /// future must synchronously release resources or initiate owned cleanup,
    /// and it must not detach any work. If background work is unavoidable, the
    /// future itself must own that work and its `Drop` path must abort it or
    /// otherwise synchronously bring it under cleanup that remains owned.
    fn execute(
        &self,
        invocation: &Invocation,
        call: &ToolCall,
        cancellation: Token,
    ) -> impl Future<Output = Result<Self::Output, ExecutorError>> + Send;
}

/// A fatal failure while converting an open executor output to closed [`ToolResult`].
///
/// This consumer-constructed enum is exhaustive: adding another mapping category
/// is a breaking API change. Every current variant follows the same fatal
/// [`ExecutionError::Mapping`] route.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MappingError {
    /// Required/absent/null output presence was inconsistent.
    InvalidPresence(String),
    /// Metadata could not be represented by the portable closed value.
    UnsupportedMetadata(String),
    /// A model-facing part was not valid tool output.
    ToolPart(ToolPartError),
    /// An opaque extension envelope was invalid.
    OpaqueEnvelope(EnvelopeError),
    /// The adapter violated its output protocol.
    Protocol(String),
}

impl Display for MappingError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPresence(context) => {
                write!(formatter, "invalid output presence: {context}")
            }
            Self::UnsupportedMetadata(context) => {
                write!(formatter, "unsupported metadata: {context}")
            }
            Self::ToolPart(error) => write!(formatter, "invalid tool part: {error}"),
            Self::OpaqueEnvelope(error) => write!(formatter, "invalid opaque envelope: {error}"),
            Self::Protocol(context) => {
                write!(formatter, "tool mapping protocol failure: {context}")
            }
        }
    }
}

impl Error for MappingError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::ToolPart(error) => Some(error),
            Self::OpaqueEnvelope(error) => Some(error),
            Self::InvalidPresence(_) | Self::UnsupportedMetadata(_) | Self::Protocol(_) => None,
        }
    }
}

type ErasedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
type DeferredMapping = Box<dyn FnOnce() -> Result<ToolResult, MappingError> + Send>;

enum ErasedExecutionError {
    Cancelled,
    Mapping(MappingError),
}

fn linearize_execution<'a>(
    mut execution: ErasedFuture<'a, Result<DeferredMapping, ExecutorError>>,
    cancellation: Token,
    executor_cancellation: Token,
) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>> {
    Box::pin(async move {
        let mut cancellation_wait = Box::pin(cancellation.cancelled());
        let outcome = std::future::poll_fn(|context| {
            if cancellation_wait.as_mut().poll(context).is_ready() {
                return Poll::Ready(None);
            }
            execution.as_mut().poll(context).map(Some)
        })
        .await;
        match outcome {
            None => {
                executor_cancellation.cancel();
                // Executor's cancellation-safety contract makes dropping
                // the unfinished future the synchronous cleanup boundary. The batch
                // engine joins only the outer worker that calls this routing primitive.
                drop(execution);
                Err(ErasedExecutionError::Cancelled)
            }
            Some(Ok(mapper)) => mapper().map_err(ErasedExecutionError::Mapping),
            // The message and not the chain: this text is model-visible content,
            // and how a chain of failures should read to a model is the
            // composition layer's decision, not reef's. `ExecutorError`
            // documents the message as the complete rendered reason for exactly
            // this reason; a retained source stays a value for whoever inspects
            // it in process.
            Some(Err(error)) => Ok(ToolResult::error_text(error.to_string())),
        }
    })
}

trait ErasedExecutor: Send + Sync {
    fn execute_mapped<'a>(
        &'a self,
        invocation: &'a Invocation,
        call: &'a ToolCall,
        cancellation: Token,
    ) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>>;
}

struct TypedExecutor<E: Executor> {
    executor: Arc<E>,
    mapper: Arc<dyn Fn(E::Output) -> Result<ToolResult, MappingError> + Send + Sync>,
}

impl<E> ErasedExecutor for TypedExecutor<E>
where
    E: Executor,
{
    fn execute_mapped<'a>(
        &'a self,
        invocation: &'a Invocation,
        call: &'a ToolCall,
        cancellation: Token,
    ) -> ErasedFuture<'a, Result<ToolResult, ErasedExecutionError>> {
        let executor_cancellation = cancellation.child_token();
        let execution_token = executor_cancellation.clone();
        let mapper = Arc::clone(&self.mapper);
        let execution: ErasedFuture<'a, Result<DeferredMapping, ExecutorError>> =
            Box::pin(async move {
                self.executor
                    .execute(invocation, call, execution_token)
                    .await
                    .map(|output| Box::new(move || mapper(output)) as DeferredMapping)
            });
        linearize_execution(execution, cancellation, executor_cancellation)
    }
}

/// The execution lane exposed to a model.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Lane {
    /// The host dispatches this tool through the captured local executor.
    Client,
    /// The model provider executes this capability natively.
    Hosted,
}

/// One fully owned registration, suitable for static or dynamic providers.
///
/// A registration is one entry in a [`Registry`]: what the model is told about a
/// tool ([`Descriptor`]) and who runs it. The latter is the choice between the
/// two constructors, and it is the whole of the [`Lane`] distinction —
/// [`Registration::client`] pairs an [`Executor`] with its mapper and reef
/// dispatches the call itself, while [`Registration::hosted`] declares a
/// capability the *provider* executes and carries the opaque envelope that
/// configures it.
///
/// ```
/// use reef_core::opaque;
/// use reef_core::runtime::tool;
///
/// let hosted = tool::Registration::hosted(
///     tool::Descriptor::new(
///         tool::Name::local("web.search".to_owned()).unwrap(),
///         "Provider-run web search".to_owned(),
///         opaque::Payload::copy_from_slice(b"{}"),
///     ),
///     // Uninterpreted by reef, and passed to the provider unchanged.
///     opaque::Envelope::try_new(
///         "example.provider".to_owned(),
///         "web_search".to_owned(),
///         opaque::Payload::copy_from_slice(br#"{"max_results":5}"#),
///     )
///     .unwrap(),
/// );
/// assert_eq!(hosted.lane(), tool::Lane::Hosted);
///
/// let mut registry = tool::RegistryBuilder::new();
/// registry.register(hosted);
/// // Names are canonical and collisions fail closed, before any side effect.
/// assert!(registry.build().is_ok());
/// ```
///
/// [`Executor`] carries the client-lane example.
#[derive(Clone)]
pub struct Registration {
    descriptor: Descriptor,
    executor: Option<Arc<dyn ErasedExecutor>>,
    hosted_extension: Option<Envelope>,
}

impl Debug for Registration {
    /// Shows what was registered and whether a local dispatcher backs it.
    ///
    /// The executor is a trait object with no `Debug`, and its presence is the
    /// fact that matters anyway: it is exactly what makes this a client lane
    /// rather than a hosted one.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Registration")
            .field("descriptor", &self.descriptor)
            .field("executor", &redact::Presence(self.executor.is_some()))
            .field("hosted_extension", &self.hosted_extension)
            .finish()
    }
}

impl Registration {
    /// Statically pairs a client executor output with its only mapper.
    #[must_use]
    pub fn client<E, M>(descriptor: Descriptor, executor: Arc<E>, mapper: Arc<M>) -> Self
    where
        E: Executor,
        M: Fn(E::Output) -> Result<ToolResult, MappingError> + Send + Sync + 'static,
    {
        Self {
            descriptor,
            executor: Some(Arc::new(TypedExecutor { executor, mapper })),
            hosted_extension: None,
        }
    }

    /// Creates a model-native registration with an owned provider extension and
    /// no local dispatcher.
    #[must_use]
    pub fn hosted(descriptor: Descriptor, extension: Envelope) -> Self {
        Self {
            descriptor,
            executor: None,
            hosted_extension: Some(extension),
        }
    }

    /// Returns the owned model descriptor.
    #[must_use]
    pub const fn descriptor(&self) -> &Descriptor {
        &self.descriptor
    }

    /// Returns the immutable execution lane.
    #[must_use]
    pub const fn lane(&self) -> Lane {
        if self.executor.is_some() {
            Lane::Client
        } else {
            Lane::Hosted
        }
    }
}

/// A stable static-registry construction failure.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RegistryError {
    /// Two static registrations used the same canonical name.
    StaticCollision(Name),
}

impl Display for RegistryError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::StaticCollision(name) => {
                write!(formatter, "duplicate static tool: {}", name.canonical())
            }
        }
    }
}

impl Error for RegistryError {}

/// A nonfatal failure from one dynamic provider resolution.
///
/// The message is the stable operator diagnostic rendered by [`Display`]. A
/// concrete underlying failure can be retained with
/// [`with_source`](Self::with_source), so an outward [`Kind::Error`] consumer can
/// inspect and downcast the complete error chain without changing that
/// diagnostic. Equality compares the message only because an arbitrary error
/// source has no meaningful general equality operation.
///
/// [`Kind::Error`]: crate::runtime::event::Kind::Error
#[derive(Clone)]
pub struct ProviderError {
    message: String,
    source: Option<Arc<dyn Error + Send + Sync>>,
}

impl ProviderError {
    /// Creates an owned provider error without an underlying cause.
    #[must_use]
    pub const fn new(message: String) -> Self {
        Self {
            message,
            source: None,
        }
    }

    /// Retains the concrete failure that caused this provider to degrade.
    ///
    /// The source is returned from [`Error::source`] and does not affect the
    /// displayed message or equality.
    #[must_use]
    pub fn with_source(mut self, source: impl Error + Send + Sync + 'static) -> Self {
        self.source = Some(Arc::new(source));
        self
    }
}

impl fmt::Debug for ProviderError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        let mut tuple = formatter.debug_tuple("ProviderError");
        tuple.field(&self.message);
        let mut link = Error::source(self);
        while let Some(error) = link {
            tuple.field(&error.to_string());
            link = error.source();
        }
        tuple.finish()
    }
}

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

impl PartialEq for ProviderError {
    fn eq(&self, other: &Self) -> bool {
        self.message == other.message
    }
}

impl Eq for ProviderError {}

impl Error for ProviderError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source
            .as_ref()
            .map(|source| source.as_ref() as &(dyn Error + 'static))
    }
}

/// One all-or-nothing dynamic provider observation.
#[derive(Debug)]
pub struct ProviderResolution {
    entries: Vec<Registration>,
    error: Option<ProviderError>,
}

impl ProviderResolution {
    /// Creates a successful provider observation.
    #[must_use]
    pub const fn success(entries: Vec<Registration>) -> Self {
        Self {
            entries,
            error: None,
        }
    }

    /// Creates a failed observation; all supplied partial entries are discarded.
    #[must_use]
    pub const fn failed(partial_entries: Vec<Registration>, error: ProviderError) -> Self {
        Self {
            entries: partial_entries,
            error: Some(error),
        }
    }
}

/// A dynamic tool source resolved exactly once by each Step resolution.
///
/// # The resolved tool set may differ every Step, and that is not a loophole
///
/// [`Provider::resolve`] runs once per Step, so a provider may legitimately
/// return a different set at every Step of the same Run: tools that appear once
/// a file is opened, a scope that narrows after a denial, a catalogue that a
/// search step widens. This does **not** contradict the rule that configuration
/// is fixed for a Run. What is frozen is the
/// [`agent::Revision`](crate::runtime::agent::Revision) — the provider roster,
/// the hook roster, the system instruction — not the *result* of consulting
/// that roster. The roster is the configuration; the resolution is a per-Step
/// observation of it, exactly like the transcript the same Step freezes.
///
/// Anyone reaching for a way to make the tool set vary within a Run therefore
/// already has one, and any proposal to relax the Run-granularity rule on those
/// grounds is answering a problem that does not exist. What a Run genuinely
/// cannot do is add or remove a *provider*, change the model client, or change
/// the hook set; that is a successor Run with a new revision.
///
/// # Why this boundary awaits
///
/// A tool set that varies per Step is usually one somebody has to go and ask
/// for: a remote catalogue, a tenant entitlement lookup, a capability handshake.
/// [`Executor`] already awaits for the same reason, and this boundary produces
/// the resolution that execution is routed against, so a synchronous signature
/// here would leave the only boundary that decides *which* tools exist as the
/// only one unable to ask. Explicit boxed-future erasure follows ADR-013, so
/// awaiting costs this registry boundary no object safety.
///
/// A background refresher is not an equivalent: it answers with whatever it
/// last fetched, which is the one thing a Step-top resolution must not do when
/// the Step's own request is the thing that has to see the new tool.
pub trait Provider: Send + Sync + 'static {
    /// Resolves owned entries from the provider's current state against the
    /// exact frozen Step-top transcript later handed to every
    /// [`Invocation`] in the same Step.
    ///
    /// Resolution is all-or-nothing: a [`ProviderResolution::failed`]
    /// observation discards every partial entry and degrades this provider only.
    /// Resolution runs once per Step, which is what lets the resolved tool set
    /// differ between Steps without any Run-level binding changing.
    ///
    /// # Cancellation
    ///
    /// The returned future must be cancellation-safe on the same terms
    /// [`Executor::execute`] states: the caller may drop it at any await point
    /// after cancelling the supplied token, and dropping it must release
    /// resources synchronously rather than detach work. Nothing observable has
    /// happened at this point in the Step — no request is materialized and no
    /// executor has run — so a dropped resolution leaves nothing to undo.
    fn resolve<'a>(
        &'a self,
        transcript: &'a Snapshot,
        cancellation: Token,
    ) -> Pin<Box<dyn Future<Output = ProviderResolution> + Send + 'a>>;
}

/// Mutable registration surface consumed into an immutable registry.
#[derive(Default)]
pub struct RegistryBuilder {
    static_entries: Vec<Registration>,
    providers: Vec<Arc<dyn Provider>>,
}

impl Debug for RegistryBuilder {
    /// Shows what has been registered so far and how many providers will run.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        debug_registry(
            "RegistryBuilder",
            &self.static_entries,
            &self.providers,
            formatter,
        )
    }
}

// A registry and the builder it is frozen from hold the same two lanes, and a
// provider is an `Arc<dyn Provider>` with no `Debug`, so both report the static
// names they will expose and count the providers they will consult.
fn debug_registry(
    name: &str,
    static_entries: &[Registration],
    providers: &[Arc<dyn Provider>],
    formatter: &mut Formatter<'_>,
) -> fmt::Result {
    formatter
        .debug_struct(name)
        .field(
            "static_entries",
            &static_entries
                .iter()
                .map(|entry| entry.descriptor.name.canonical())
                .collect::<Vec<_>>(),
        )
        .field("providers", &providers.len())
        .finish()
}

impl RegistryBuilder {
    /// Creates an empty registry builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds one owned static registration.
    pub fn register(&mut self, registration: Registration) -> &mut Self {
        self.static_entries.push(registration);
        self
    }

    /// Adds one dynamic provider handle.
    pub fn provider(&mut self, provider: Arc<dyn Provider>) -> &mut Self {
        self.providers.push(provider);
        self
    }

    /// Validates all static names and freezes the registry.
    ///
    /// # Errors
    ///
    /// [`RegistryError::StaticCollision`], naming the tool, if two static
    /// registrations share one canonical name. It fails here rather than at
    /// resolution so that no model ever sees an ambiguous roster and no executor
    /// runs for a call whose routing was already undecidable — a collision is a
    /// wiring mistake, and the build is the last moment at which nothing has
    /// happened yet.
    ///
    /// Providers cannot be checked here, because they resolve per Step. A name
    /// that only collides once a provider has produced it is reported by
    /// [`Registry::resolve_step`] as [`StepResolutionError::Collision`] — the
    /// same fail-closed rule, applied at the only moment the full set exists, and
    /// still before any model request or executor sees it.
    pub fn build(self) -> Result<Registry, RegistryError> {
        let mut names = HashSet::new();
        for entry in &self.static_entries {
            if !names.insert(entry.descriptor.name.clone()) {
                return Err(RegistryError::StaticCollision(
                    entry.descriptor.name.clone(),
                ));
            }
        }
        Ok(Registry {
            static_entries: self.static_entries,
            providers: self.providers,
        })
    }
}

/// An immutable, shareable static registry and provider set.
#[derive(Clone)]
pub struct Registry {
    static_entries: Vec<Registration>,
    providers: Vec<Arc<dyn Provider>>,
}

impl Debug for Registry {
    /// Shows the frozen static names and how many providers back them.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        debug_registry("Registry", &self.static_entries, &self.providers, formatter)
    }
}

/// Filters model exposure before a Step snapshot materializes.
///
/// This is crate-private and ADR-027 records why. The correction point is real
/// and the runtime applies it, but the only production filter is [`ExposeAll`]:
/// a composition layer that wants a narrower Step roster narrows what its own
/// [`Provider`] returns, or filters `Request::tools` in an
/// [`ModelHooks::before_model`](crate::runtime::hook::ModelHooks::before_model)
/// registration paired with a
/// [`Block`](crate::runtime::hook::ToolCallDecision::Block) in
/// [`ToolHooks::before_tool_call`](crate::runtime::hook::ToolHooks::before_tool_call).
///
/// The `Sync` bound is what holding this filter across a provider's await costs
/// (ADR-024 D3), and it is the whole of it: the filter is only ever borrowed, so
/// nothing here has to be `Send`.
pub(crate) trait ExposureFilter: Sync {
    /// Returns whether one validated registration remains exposed and routable.
    fn exposed(&self, descriptor: &Descriptor, lane: Lane) -> bool;
}

/// A filter that exposes every validated registration.
#[derive(Debug)]
pub(crate) struct ExposeAll;

impl ExposureFilter for ExposeAll {
    fn exposed(&self, _descriptor: &Descriptor, _lane: Lane) -> bool {
        true
    }
}

/// A dynamic collision discovered before model or executor activity.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum StepResolutionError {
    /// A dynamic name collided within/across providers or with a static name.
    Collision(Name),
}

impl Display for StepResolutionError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Collision(name) => write!(formatter, "Step tool collision: {}", name.canonical()),
        }
    }
}

impl Error for StepResolutionError {}

/// The result of one resolve-once Step boundary.
#[derive(Debug)]
pub struct StepResolution {
    snapshot: StepToolSnapshot,
    provider_errors: Vec<ProviderError>,
}

impl StepResolution {
    /// Returns the immutable Step snapshot.
    #[must_use]
    pub const fn snapshot(&self) -> &StepToolSnapshot {
        &self.snapshot
    }

    /// Transfers the immutable Step snapshot.
    #[must_use]
    pub fn into_snapshot(self) -> StepToolSnapshot {
        self.snapshot
    }

    /// Splits this resolution into its owned snapshot and the ordered
    /// per-degraded-provider diagnostics.
    ///
    /// This is the crate-private twin of
    /// [`into_snapshot`](Self::into_snapshot) plus
    /// [`provider_errors`](Self::provider_errors), and it exists so
    /// the loop can publish one nonfatal Error per degraded provider without the
    /// public surface growing a second accessor for a value the pair above
    /// already exposes. The diagnostics stay in provider registration order.
    #[must_use]
    pub(crate) fn into_parts(self) -> (StepToolSnapshot, Vec<ProviderError>) {
        (self.snapshot, self.provider_errors)
    }

    /// Returns one nonfatal diagnostic for each degraded provider.
    #[must_use]
    pub fn provider_errors(&self) -> &[ProviderError] {
        &self.provider_errors
    }
}

impl Registry {
    /// Resolves every provider once against one frozen transcript snapshot,
    /// validates the full set, and then freezes one owned Step snapshot that
    /// reuses that exact transcript version.
    ///
    /// Providers are resolved in registration order, one await at a time. The
    /// order is the registration order for the same reason the hook fan-outs
    /// use it — it is the only order a composition layer declared — and the
    /// sequencing is deliberate rather than incidental: a concurrent fan-out
    /// would make the diagnostic order of degraded providers depend on which
    /// remote answered first, and this value is compared in tests and logs.
    ///
    /// Every validated registration is exposed. Narrowing the roster is a
    /// composition-layer decision taken one rail earlier, in what a [`Provider`]
    /// returns, or one rail later, in what an
    /// [`OnBeforeModel`](crate::runtime::hook::ModelHooks::before_model)
    /// registration leaves in `Request::tools`; ADR-027 records why core
    /// publishes neither a filter nor a mount point for one.
    ///
    /// # Errors
    ///
    /// Returns [`StepResolutionError::Collision`] before any model request or
    /// executor dispatch can observe the ambiguity.
    pub async fn resolve_step(
        &self,
        transcript: Snapshot,
        cancellation: &Token,
    ) -> Result<StepResolution, StepResolutionError> {
        self.resolve_step_filtered(transcript, cancellation, &ExposeAll)
            .await
    }

    /// Resolves as [`resolve_step`](Self::resolve_step) does, then drops every
    /// registration the correction hides from both the model and the router.
    ///
    /// The correction is applied after validation, so a name that collides is
    /// still an error even when the filter would have hidden it: hiding an
    /// ambiguity is not the same as not having one.
    pub(crate) async fn resolve_step_filtered(
        &self,
        transcript: Snapshot,
        cancellation: &Token,
        correction: &dyn ExposureFilter,
    ) -> Result<StepResolution, StepResolutionError> {
        let mut entries = self.static_entries.clone();
        let mut provider_errors = Vec::new();
        for provider in &self.providers {
            let resolution = provider.resolve(&transcript, cancellation.clone()).await;
            if let Some(error) = resolution.error {
                provider_errors.push(error);
            } else {
                entries.extend(resolution.entries);
            }
        }

        let mut names = HashSet::new();
        for entry in &entries {
            if !names.insert(entry.descriptor.name.clone()) {
                return Err(StepResolutionError::Collision(
                    entry.descriptor.name.clone(),
                ));
            }
        }
        entries.retain(|entry| correction.exposed(&entry.descriptor, entry.lane()));
        Ok(StepResolution {
            snapshot: StepToolSnapshot {
                entries,
                transcript,
            },
            provider_errors,
        })
    }

    /// Resolves a registry that registered no dynamic provider, without a runtime.
    ///
    /// [`resolve_step`](Self::resolve_step) awaits its providers, and most
    /// fixtures across the runtime tests have none: they build a snapshot out of
    /// static registrations so that some other boundary has one to route
    /// against. Those tests are synchronous, and making each of them claim a
    /// reactor to drive a future that cannot park would say something false
    /// about what they exercise. The `Pending` arm is the assertion that the
    /// caller really is such a fixture.
    #[cfg(test)]
    pub(crate) fn resolve_step_without_providers(
        &self,
        transcript: Snapshot,
        cancellation: &Token,
        correction: &dyn ExposureFilter,
    ) -> Result<StepResolution, StepResolutionError> {
        let mut resolving =
            Box::pin(self.resolve_step_filtered(transcript, cancellation, correction));
        match resolving
            .as_mut()
            .poll(&mut Context::from_waker(Waker::noop()))
        {
            Poll::Ready(resolved) => resolved,
            Poll::Pending => {
                panic!("a registry with no dynamic provider resolves on its first poll")
            }
        }
    }
}

/// A fatal or cancellation outcome from routing one local call.
///
/// Unknown tool names are deliberately absent: an unexposed name is an ordinary
/// business rejection, not a control-path failure, so the model can be told
/// about it in the transcript instead of the Run failing.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ExecutionError {
    /// A hosted/model-native capability was sent to the local path.
    Hosted(String),
    /// Cancellation won the control path.
    Cancelled,
    /// Output mapping failed fatally.
    Mapping(MappingError),
}

impl Display for ExecutionError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hosted(name) => {
                write!(formatter, "hosted tool is not locally dispatchable: {name}")
            }
            Self::Cancelled => formatter.write_str("tool run cancelled"),
            Self::Mapping(error) => write!(formatter, "tool output mapping failed: {error}"),
        }
    }
}

impl Error for ExecutionError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Mapping(error) => Some(error),
            Self::Hosted(_) | Self::Cancelled => None,
        }
    }
}

/// The furthest stable disposition reached by a started `ToolCall`.
///
/// Only [`Self::Executed`] and [`Self::Rejected`] can be produced by
/// [`StepToolSnapshot::execute`]; the remaining states are reached by the hook
/// and terminal-unwind paths that observe the same closed vocabulary.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum CallDisposition {
    /// Entered tool execution.
    Executed,
    /// A hook supplied a result without execution.
    ShortCircuited,
    /// A hook blocked execution.
    Blocked,
    /// Core rejected an unavailable call.
    Rejected,
    /// Output-token truncation left the call incomplete.
    Truncated,
    /// Terminal unwinding began before another stable disposition.
    NotExecuted,
}

/// One closed business outcome of routing an accepted effective call.
///
/// A successful route always carries both the model-visible closed result and
/// the disposition fact later published by lifecycle observations, so callers
/// never re-derive the disposition from the result's shape.
#[derive(Clone, Debug)]
pub struct ExecutionOutcome {
    result: ToolResult,
    disposition: CallDisposition,
}

impl ExecutionOutcome {
    /// Returns the model-visible closed result.
    #[must_use]
    pub const fn result(&self) -> &ToolResult {
        &self.result
    }

    /// Returns the stable disposition reached by this call.
    #[must_use]
    pub const fn disposition(&self) -> CallDisposition {
        self.disposition
    }

    /// Transfers the closed result and its disposition.
    #[must_use]
    pub fn into_parts(self) -> (ToolResult, CallDisposition) {
        (self.result, self.disposition)
    }
}

/// One immutable model-exposure and host-routing snapshot.
#[derive(Debug)]
pub struct StepToolSnapshot {
    entries: Vec<Registration>,
    transcript: Snapshot,
}

impl StepToolSnapshot {
    /// Creates the crate-private shallow twin used by `StepSnapshot`.
    ///
    /// Registrations retain the same executor/mapper handles and the transcript
    /// retains the same shared item backing; no provider is resolved again.
    #[must_use]
    pub(crate) fn shallow_clone(&self) -> Self {
        Self {
            entries: self.entries.clone(),
            transcript: self.transcript.clone(),
        }
    }

    /// Returns the frozen Step-top transcript shared by this Step's provider
    /// resolution and every invocation minted from this snapshot.
    #[must_use]
    pub const fn transcript(&self) -> &Snapshot {
        &self.transcript
    }

    /// Returns every frozen exposed descriptor and lane in deterministic order.
    #[must_use]
    pub fn exposure(&self) -> impl ExactSizeIterator<Item = (&Descriptor, Lane)> {
        self.entries
            .iter()
            .map(|entry| (&entry.descriptor, entry.lane()))
    }

    /// Materializes the client/local lane for [`crate::runtime::model::RequestPlan`].
    #[must_use]
    pub fn client_model_tools(&self) -> Vec<ClientTool> {
        self.entries
            .iter()
            .filter(|entry| entry.lane() == Lane::Client)
            .map(|entry| entry.descriptor.client_model_tool())
            .collect()
    }

    /// Materializes the hosted/model-native lane for
    /// [`crate::runtime::model::RequestPlan`].
    #[must_use]
    pub fn hosted_model_extensions(&self) -> Vec<Envelope> {
        self.entries
            .iter()
            .filter_map(|entry| entry.hosted_extension.clone())
            .collect()
    }

    /// Applies both model-visible lanes from this exact Step snapshot.
    pub fn apply_to_plan(&self, plan: &mut RequestPlan) {
        plan.extend_tools(self.client_model_tools())
            .extend_extensions(self.hosted_model_extensions());
    }

    /// Mints one invocation whose transcript shares this snapshot's exact
    /// immutable backing, so no caller can substitute another transcript version.
    ///
    /// Minting requires both a core-resolved snapshot and a
    /// [`ToolEmitter`], whose outward authority and [`crate::value::lifecycle::Coord`]
    /// are stamped by core. Neither the outward producer nor any run state is
    /// reachable through this seam. Outside a live run, pass
    /// [`ToolEmitter::closed`].
    #[must_use]
    pub fn invocation(
        &self,
        session_id: Option<String>,
        call_id: Id,
        emitter: ToolEmitter,
    ) -> Invocation {
        Invocation::new(session_id, self.transcript.clone(), call_id, emitter)
    }

    /// Routes one accepted effective call to its captured executor.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutionError`] only for control-path failures: hosted
    /// misrouting, cancellation, and fatal output mapping. Unknown names and
    /// ordinary executor failures are business outcomes.
    pub async fn execute(
        &self,
        invocation: &Invocation,
        call: &ToolCall,
        cancellation: &Token,
    ) -> Result<ExecutionOutcome, ExecutionError> {
        if cancellation.is_cancelled() {
            return Err(ExecutionError::Cancelled);
        }
        // A registration is keyed by a validated `Name`, so the binding is
        // recovered by parsing the emission back into one — the inverse of the
        // `to_wire` spelling that advertised it — rather than by comparing
        // strings. An emission the grammar rejects cannot name any registration,
        // and it stays a business result: the model has to be told which name it
        // asked for, which is why the raw emission is reported unchanged.
        let emitted = call.name().as_str();
        let Some(entry) = Name::parse_canonical(emitted).ok().and_then(|name| {
            self.entries
                .iter()
                .find(|candidate| candidate.descriptor.name == name)
        }) else {
            return Ok(rejected(format!("unknown tool: {emitted}")));
        };
        let Some(executor) = &entry.executor else {
            return Err(ExecutionError::Hosted(emitted.to_owned()));
        };

        match executor
            .execute_mapped(invocation, call, cancellation.clone())
            .await
        {
            Ok(result) => Ok(ExecutionOutcome {
                result,
                disposition: CallDisposition::Executed,
            }),
            Err(ErasedExecutionError::Cancelled) => Err(ExecutionError::Cancelled),
            Err(ErasedExecutionError::Mapping(error)) => Err(ExecutionError::Mapping(error)),
        }
    }
}

fn rejected(message: String) -> ExecutionOutcome {
    // Matches the closed `ToolResult::error_text` business-result producer.
    ExecutionOutcome {
        result: ToolResult::error_text(message),
        disposition: CallDisposition::Rejected,
    }
}