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
//! Concurrent execution of one already-prepared, source-ordered tool batch.
//!
//! This module is deliberately only the execution engine: every pre-execution
//! decision (hook rewrite, exposure lookup, short-circuit) has already been made
//! by the caller, and every
//! publication decision (transcript commit, strong-acceptance seams, lifecycle
//! emission) is still owned by the caller. The engine's whole contract is
//!
//! 1. refuse a batch whose cancellation is already observable, starting nothing,
//! 2. otherwise run every executable slot concurrently rather than serially,
//! 3. own every future it starts, with no detached work, and cancel every started
//!    run before dropping it, including when the caller drops this future,
//! 4. latch the highest-ranked typed control-path failure, cancel the siblings,
//!    and still join all of them, and
//! 5. return outcomes strictly in source order, or a single stable failure.
//!
//! Ordinary
//! execution errors are already business results by the time
//! [`StepToolSnapshot::execute`] returns, so only [`ExecutionError`] reaches this
//! engine as fatal, and a fatal batch materializes nothing.

use std::error;
use std::fmt::{self, Display, Formatter};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;

use crate::cancel::Token;

use crate::runtime::event::ToolEmitter;
use crate::runtime::tool::{CallDisposition, ExecutionError, Invocation, StepToolSnapshot};
use crate::value::tool_call::{ToolCall, ToolResult};

/// One closed business outcome held at one source position of a batch.
///
/// [`crate::runtime::tool::ExecutionOutcome`] is mintable only by the routing
/// seam that produced it, so batch entries the caller already settled cannot be
/// expressed in that type. This is the batch-level equivalent: the same closed
/// pair of model-visible result and stable disposition, for both executed and
/// caller-settled positions.
#[derive(Clone, Debug)]
pub struct Outcome {
    result: ToolResult,
    disposition: CallDisposition,
}

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

    /// Returns the stable disposition reached at this source position.
    #[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)
    }
}

/// The dispositions a caller can settle a source position with before routing.
///
/// This is the closed subset of [`CallDisposition`] that is reachable without
/// routing a call: a hook short-circuit or block, an output-token truncation,
/// or terminal unwinding. [`CallDisposition::Executed`] and
/// [`CallDisposition::Rejected`] are deliberately not expressible here, because
/// they are facts about a call that
/// actually reached the routing seam and can therefore only be produced by
/// [`StepToolSnapshot::execute`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SettledDisposition {
    /// A hook supplied a result without execution.
    ShortCircuited,
    /// A hook blocked execution.
    Blocked,
    /// Output-token truncation left the call incomplete.
    Truncated,
    /// Terminal unwinding began before another stable disposition.
    NotExecuted,
}

impl SettledDisposition {
    /// Widens this pre-routing state into the closed disposition vocabulary.
    #[must_use]
    pub const fn disposition(self) -> CallDisposition {
        match self {
            Self::ShortCircuited => CallDisposition::ShortCircuited,
            Self::Blocked => CallDisposition::Blocked,
            Self::Truncated => CallDisposition::Truncated,
            Self::NotExecuted => CallDisposition::NotExecuted,
        }
    }
}

/// One owned, already-routed execution unit.
struct Executable {
    snapshot: Arc<StepToolSnapshot>,
    invocation: Invocation,
    call: ToolCall,
}

type PreparedRun = Pin<Box<dyn Future<Output = Result<Outcome, ExecutionError>> + Send>>;

impl Executable {
    /// Erases one owned unit into a future that borrows nothing from the batch.
    fn into_run(self, cancellation: Token) -> PreparedRun {
        Box::pin(async move {
            // Routing, admission, cancellation racing, and open-output mapping
            // all stay in the single `StepToolSnapshot::execute` seam.
            let outcome = self
                .snapshot
                .execute(&self.invocation, &self.call, &cancellation)
                .await?;
            let (result, disposition) = outcome.into_parts();
            Ok(Outcome {
                result,
                disposition,
            })
        })
    }
}

enum Slot {
    Settled(Outcome),
    Executable(Executable),
}

/// One source-ordered batch entry the caller has finished preparing.
pub struct PreparedToolCall {
    slot: Slot,
}

impl fmt::Debug for PreparedToolCall {
    /// Says whether this position still has to run, and names the call if so.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut prepared = formatter.debug_struct("PreparedToolCall");
        match &self.slot {
            Slot::Settled(outcome) => prepared
                .field("settled", &true)
                .field("disposition", &outcome.disposition),
            Slot::Executable(executable) => prepared
                .field("settled", &false)
                .field("call", &executable.call),
        }
        .finish()
    }
}

impl PreparedToolCall {
    /// Reserves this source position for an outcome the caller already decided,
    /// such as a hook short-circuit or a blocked call.
    ///
    /// The engine never inspects, re-orders, or re-derives a settled outcome; it
    /// only guarantees the outcome keeps this exact source position. Only the
    /// pre-routing dispositions of [`SettledDisposition`] can be settled this
    /// way, so a settled slot can never claim a fact that belongs to the routing
    /// seam.
    #[must_use]
    pub const fn settled(result: ToolResult, disposition: SettledDisposition) -> Self {
        Self {
            slot: Slot::Settled(Outcome {
                result,
                disposition: disposition.disposition(),
            }),
        }
    }

    /// Reserves this source position for a call the engine must actually execute.
    ///
    /// The per-call [`Invocation`] is minted here from `snapshot`, `call` and
    /// the caller's per-call `emitter`, so the executor
    /// always observes this Step's frozen transcript under this call's own
    /// identity. Because the invocation is never accepted from outside, an
    /// invocation belonging to a different Step, a different call, or a different
    /// emitter is not expressible at this seam.
    #[must_use]
    pub fn executable(
        snapshot: Arc<StepToolSnapshot>,
        session_id: Option<String>,
        call: ToolCall,
        emitter: ToolEmitter,
    ) -> Self {
        let invocation = snapshot.invocation(session_id, call.id().clone(), emitter);
        Self {
            slot: Slot::Executable(Executable {
                snapshot,
                invocation,
                call,
            }),
        }
    }
}

/// Where a batch failure was observed.
///
/// Batch-level cancellation is observed by the engine itself rather than reported
/// by any slot, so it deliberately carries no source index: attributing it to a
/// slot would invent a fact the engine never learned.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorOrigin {
    /// The failure was reported by the executable slot at this source index.
    Slot(usize),
    /// The engine observed the failure for the batch as a whole.
    Batch,
}

/// The single stable control-path failure of one prepared batch.
///
/// A failed batch materializes no outcomes at all, so the caller can never
/// publish a partial batch. The retained source identifies where the failure was
/// observed, not merely which slot finished first.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Error {
    origin: ErrorOrigin,
    error: ExecutionError,
}

impl Error {
    /// Returns where the reported failure was observed.
    ///
    /// Named `origin` rather than `source` so it cannot shadow
    /// [`std::error::Error::source`], which this type also has.
    #[must_use]
    pub const fn origin(&self) -> ErrorOrigin {
        self.origin
    }

    /// Returns the latched tool execution failure.
    #[must_use]
    pub const fn execution(&self) -> &ExecutionError {
        &self.error
    }

    /// Transfers the latched tool execution failure.
    #[must_use]
    pub fn into_execution(self) -> ExecutionError {
        self.error
    }

    /// Returns the latched tool execution failure.
    #[deprecated(since = "0.3.0", note = "use `execution` instead")]
    #[must_use]
    pub const fn error(&self) -> &ExecutionError {
        self.execution()
    }

    /// Transfers the latched tool execution failure.
    #[deprecated(since = "0.3.0", note = "use `into_execution` instead")]
    #[must_use]
    pub fn into_error(self) -> ExecutionError {
        self.into_execution()
    }

    /// The failure of a batch that never reached, or already left, its slots.
    const fn batch(error: ExecutionError) -> Self {
        Self {
            origin: ErrorOrigin::Batch,
            error,
        }
    }

    /// Creates the batch-level cancellation used by a pre-routing caller.
    pub(crate) const fn cancelled_batch() -> Self {
        Self::batch(ExecutionError::Cancelled)
    }
}

impl Display for Error {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self.origin {
            ErrorOrigin::Slot(index) => write!(
                formatter,
                "prepared tool batch failed at source index {index}: {}",
                self.error
            ),
            ErrorOrigin::Batch => write!(
                formatter,
                "prepared tool batch failed with no source position: {}",
                self.error
            ),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(&self.error)
    }
}

/// Latches the batch failure that outranks any already-latched one.
///
/// Cancellation is the weakest failure: it is what every sibling reports once the
/// engine cancels them, so it must never displace a real fatal, while a real
/// fatal always displaces an already-latched cancellation - whether the fatal is
/// observed in the same poll pass as that cancellation or in a later one.
///
/// Between two failures of equal rank the first one *observed* wins, and nothing
/// later can displace it. One poll pass examines slots in source order, so two
/// equal-rank failures that become ready in the same pass resolve to the lower
/// source index. Across passes the earlier pass wins regardless of index, which
/// is exactly the sequencing the caller already observed. Either way the reported
/// failure is independent of the executor's completion order within a pass.
pub(super) fn latch(latched: &mut Option<Error>, index: usize, error: ExecutionError) {
    let outranks = match latched {
        None => true,
        Some(existing) => {
            existing.error == ExecutionError::Cancelled && error != ExecutionError::Cancelled
        }
    };
    if outranks {
        *latched = Some(Error {
            origin: ErrorOrigin::Slot(index),
            error,
        });
    }
}

struct Worker {
    index: usize,
    run: Option<PreparedRun>,
}

/// Every run this batch has started, plus the token that cancels them.
///
/// The token and the runs are owned together so that the ordering guarantee holds
/// on every exit path, including a panic or a caller that simply drops the batch
/// future: `Drop` cancels first and only then drops the still-unfinished futures,
/// which is what a run that releases resources on observed cancellation needs.
/// Dropping the runs in the opposite order would let them observe a live token.
struct OwnedRuns {
    siblings: Token,
    workers: Vec<Worker>,
}

impl Drop for OwnedRuns {
    fn drop(&mut self) {
        self.siblings.cancel();
        self.workers.clear();
    }
}

/// Executes one prepared, source-ordered batch concurrently.
///
/// Every executable slot is started before any of them is awaited to completion,
/// so slots genuinely overlap. All started work is owned by this future: no slot
/// is spawned or detached, and the returned value is produced only after every
/// started run has been joined, including on the failing path.
///
/// # Cancellation
///
/// Siblings are cancelled through a child of `cancellation`, so latching a fatal
/// never cancels the caller's own token, while cancelling `cancellation`
/// externally cancels the whole batch. A cancellation that is already observable
/// when this future is first polled fails the batch immediately and starts
/// nothing, even for an empty batch or one with no executable slot; the same
/// check is repeated after every run has been joined, so a cancellation that
/// arrives while the batch runs is never reported as a successful batch.
///
/// Cancellation is a request, not a completion guarantee, and this engine never
/// abandons started work in order to escape one. [`StepToolSnapshot::execute`]
/// races each executor against the token. The engine therefore has no liveness
/// upper bound of its own: bounding the batch in wall-clock time is the caller's
/// responsibility, for example by wrapping this future in a timeout. Dropping
/// this future is always safe and never detaches anything, because every started
/// run is cancelled before it is dropped.
///
/// # Errors
///
/// Returns [`Error`] when the batch is cancelled, or when any slot
/// reports a typed [`ExecutionError`]. A failed batch materializes nothing, so the
/// caller can never publish a partial batch. The reported failure is chosen by
/// rank rather than by completion time: a real fatal always outranks a
/// cancellation, and between failures of equal rank the first observed one wins -
/// within one poll pass that is the lower source index, and across passes it is
/// the earlier pass. Sibling cancellation is requested only after a whole poll
/// pass, which keeps every failure that was already ready in that pass eligible
/// for the same rule.
///
/// Ordinary executor failures are not errors here: [`StepToolSnapshot::execute`]
/// has already mapped them to business results, so they are returned in order
/// like any other outcome.
///
/// # Panics
///
/// A batch that neither failed nor was cancelled must have materialized an
/// outcome for every slot, and this asserts it before returning. Failing that
/// assertion would mean a slot was joined without producing either an outcome or
/// a [`ExecutionError`], which is a defect in this engine rather than anything a caller
/// can provoke.
pub async fn execute_prepared(
    entries: Vec<PreparedToolCall>,
    cancellation: &Token,
) -> Result<Vec<Outcome>, Error> {
    // Checked before anything is started, so an already-cancelled batch cannot
    // execute a tool, and cannot succeed by having nothing to execute.
    if cancellation.is_cancelled() {
        return Err(Error::batch(ExecutionError::Cancelled));
    }

    let mut outcomes: Vec<Option<Outcome>> = Vec::with_capacity(entries.len());
    let mut runs = OwnedRuns {
        siblings: cancellation.child_token(),
        workers: Vec::new(),
    };
    for (index, entry) in entries.into_iter().enumerate() {
        match entry.slot {
            Slot::Settled(outcome) => outcomes.push(Some(outcome)),
            Slot::Executable(executable) => {
                outcomes.push(None);
                let run = executable.into_run(runs.siblings.clone());
                runs.workers.push(Worker {
                    index,
                    run: Some(run),
                });
            }
        }
    }

    let mut latched: Option<Error> = None;
    let siblings = runs.siblings.clone();
    std::future::poll_fn(|context| {
        let mut joined = true;
        for worker in &mut runs.workers {
            let Some(run) = worker.run.as_mut() else {
                continue;
            };
            match run.as_mut().poll(context) {
                Poll::Pending => joined = false,
                Poll::Ready(Ok(outcome)) => {
                    worker.run = None;
                    outcomes[worker.index] = Some(outcome);
                }
                Poll::Ready(Err(error)) => {
                    worker.run = None;
                    latch(&mut latched, worker.index, error);
                }
            }
        }
        // Cancelling after the pass, not inside it, keeps every failure that was
        // already ready in this pass eligible for the priority rule above.
        if latched.is_some() {
            siblings.cancel();
        }
        if joined {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    })
    .await;

    if let Some(failure) = latched {
        return Err(failure);
    }
    // Re-checked at the closing boundary: a cancellation that every slot happened
    // to outrun still cancels the batch rather than publishing it.
    if cancellation.is_cancelled() {
        return Err(Error::batch(ExecutionError::Cancelled));
    }
    Ok(outcomes
        .into_iter()
        .map(|slot| slot.expect("every joined slot of a non-failing batch materialized an outcome"))
        .collect())
}