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
//! Immutable Agent configuration and linearizable teardown ownership.

mod config;
mod error;
pub(crate) mod start;

pub use config::{Config, Revision};
pub use error::{CloseError, ClosePanickedError, ConfigError, StartError, TeardownError};
#[cfg(not(test))]
#[expect(
    unused_imports,
    reason = "admission freezes the linear owner that the Run module will consume"
)]
pub(crate) use start::AdmittedStart;
#[cfg(test)]
pub(crate) use start::AdmittedStart;

use std::num::NonZeroU64;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use crate::cancel::Token;
#[cfg(test)]
use crate::transcript::store;
#[cfg(test)]
use std::collections::VecDeque;
#[cfg(test)]
use std::sync::Barrier;
#[cfg(test)]
use std::sync::atomic::AtomicUsize;
use tokio::sync::Notify;

use crate::runtime::event::Stream;
use crate::runtime::hook;
use crate::runtime::model::{Client, RequestPlan};
use crate::runtime::run::Run;
use crate::runtime::session::Session;
use crate::value::content::Part;

static NEXT_REVISION_ID: AtomicU64 = AtomicU64::new(1);

/// Cloneable handle to one immutable revision and its private teardown authority.
///
/// An Agent is configuration that has been frozen: [`Agent::new`] consumes a
/// [`Config`] and produces a [`Revision`] that never changes again. Starting a
/// Run against a different model, tool roster or hook roster means building a
/// second Agent — see [`Revision`] for the exact extent of that rule and for
/// what it deliberately leaves free.
///
/// It is `Clone`, and every clone shares one teardown authority: whichever one
/// calls [`close`](Agent::close) first runs each hook's `OnClose` exactly once
/// and every other caller receives that same cached result.
///
/// ```
/// # use std::future::{Future, ready};
/// # use std::pin::Pin;
/// # use std::sync::Arc;
/// # use std::task::{Context, Poll};
/// # use reef_core::futures_core::Stream;
/// # use reef_core::runtime::model;
/// # #[derive(Debug)] struct Offline;
/// # #[derive(Debug)] struct Once(bool);
/// # impl Stream for Once {
/// #     type Item = Result<model::Event, std::convert::Infallible>;
/// #     fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
/// #         if std::mem::replace(&mut self.0, true) { return Poll::Ready(None); }
/// #         Poll::Ready(Some(Ok(model::Event::Done { finish_reason: "stop".to_owned(), completion: model::CompletionReason::Stop, provider_data: Vec::new() })))
/// #     }
/// # }
/// # impl model::Client for Offline {
/// #     type Error = std::convert::Infallible;
/// #     type Stream = Once;
/// #     fn info(&self) -> model::Info { model::Info::new("offline".to_owned(), 8_192) }
/// #     fn generate(&self, _: model::Request) -> impl Future<Output = Result<Self::Stream, Self::Error>> + Send { ready(Ok(Once(false))) }
/// # }
/// use reef_core::cancel;
/// use reef_core::runtime::{agent, hook, session, tool};
/// use reef_core::value::{content, lifecycle};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let config = agent::Config::new(
///     Arc::new(Offline),
///     tool::RegistryBuilder::new().build().unwrap(),
///     hook::RegistryBuilder::new(),
/// );
/// let agent = agent::Agent::new(config).unwrap();
///
/// let session = session::Session::new("conversation-1".to_owned(), None);
/// let (run, mut events) = agent
///     .start_observed(session, vec![content::Part::text("Hi.".to_owned())], cancel::Token::new())
///     .await
///     .unwrap();
/// assert_eq!(run.revision().id(), agent.revision().id());
///
/// while events.recv().await.is_some() {}
/// let terminal = run.wait().await;
/// assert_eq!(terminal.outcome(), lifecycle::Outcome::Completed);
///
/// // Closing is refused while a Run is attached, and is exactly once after.
/// agent.close().await.unwrap();
/// assert!(agent.close().await.is_ok());
/// # }
/// ```
pub struct Agent<M: Client> {
    inner: Arc<AgentInner<M>>,
}

impl<M: Client> std::fmt::Debug for Agent<M> {
    /// Identifies the agent by the revision every Run of it will freeze.
    ///
    /// The phase behind the state mutex is deliberately not read: an agent's
    /// phase changes under the reader, and a formatter that took that lock
    /// could block inside teardown, which is the one moment it is most likely
    /// to be called from.
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Agent")
            .field("revision", &self.inner.revision.id())
            .finish()
    }
}

impl<M: Client> Clone for Agent<M> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

struct AgentInner<M: Client> {
    revision: Revision<M>,
    hooks: hook::RuntimeRegistry,
    state: Mutex<AgentState>,
    closed: Notify,
    #[cfg(test)]
    close_wait_probe: Mutex<Arc<CloseWaitProbe>>,
    #[cfg(test)]
    start_snapshot_results: Mutex<VecDeque<Option<store::Error>>>,
}

#[cfg(test)]
pub(crate) struct CloseWaitProbe {
    waiters: usize,
    observations: AtomicUsize,
    observed_closing: Barrier,
    resume: Barrier,
    rechecked_closing: Barrier,
}

#[cfg(test)]
impl CloseWaitProbe {
    fn new(waiters: usize) -> Self {
        Self {
            waiters,
            observations: AtomicUsize::new(0),
            observed_closing: Barrier::new(waiters + 1),
            resume: Barrier::new(waiters + 1),
            rechecked_closing: Barrier::new(waiters + 1),
        }
    }

    fn pause_before_await(&self) {
        if self.observations.fetch_add(1, Ordering::SeqCst) < self.waiters {
            self.observed_closing.wait();
            self.resume.wait();
        } else {
            self.rechecked_closing.wait();
        }
    }

    pub(crate) fn wait_until_closing_observed(&self) {
        self.observed_closing.wait();
    }

    pub(crate) fn notify_waiters_one_by_one<M: Client>(&self, agent: &Agent<M>) {
        for _ in 0..self.waiters {
            agent.inner.closed.notify_one();
        }
    }

    pub(crate) fn resume_waiters(&self) {
        self.resume.wait();
    }

    pub(crate) fn wait_until_closing_rechecked(&self) {
        self.rechecked_closing.wait();
    }
}

struct AgentState {
    phase: AgentPhase,
    active_runs: usize,
}

enum AgentPhase {
    Open,
    Closing,
    Closed(Result<(), CloseError>),
}

enum CloseDecision {
    Winner,
    Wait,
    Cached(Result<(), CloseError>),
}

impl<M: Client + 'static> Agent<M> {
    /// Consumes configuration, validates defaults, and freezes a fresh revision.
    ///
    /// # Errors
    ///
    /// - [`ConfigError::Hooks`] if the hook roster does not build: an unnamed
    ///   or duplicated registration, as [`hook::RegistryError`] describes.
    /// - [`ConfigError::InvalidDefaults`] if the default request material is not a
    ///   valid request. The defaults are frozen through the real request boundary
    ///   against an empty history, so an unusable system instruction is reported
    ///   here rather than at the first Step of every Run this Agent would start.
    /// - [`ConfigError::RevisionIdExhausted`] if the process-wide revision identity
    ///   space is used up. Identities are nonzero and monotonic for the life of the
    ///   process and are never reused, so this is reachable only after more than
    ///   `u64::MAX` revisions.
    ///
    /// Configuration is consumed either way. A rejected configuration cannot be
    /// corrected and retried; rebuild it.
    pub fn new(config: Config<M>) -> Result<Self, ConfigError> {
        Self::new_with_counter(config, &NEXT_REVISION_ID)
    }

    /// Admits one Session use, spawns its sole Run task, and returns its public handle.
    ///
    /// This compatibility entry point leaves the unique event stream on the Run for
    /// [`Run::take_events`](crate::runtime::run::Run::take_events). If outward events
    /// are required, prefer [`Agent::start_observed`], which transfers that stream
    /// before the task can run and therefore has no start-then-take race.
    ///
    /// Both halves are synchronous: ADR-015 makes admission a straight-line
    /// sequence that never yields, and spawning the Run task returns as soon as
    /// the task is queued. `async` here is the caller-facing contract rather
    /// than an implementation fact — it states that a Tokio runtime must be
    /// live, which is what makes the spawn legal, and it keeps the facade's
    /// three lifecycle entries the same shape.
    ///
    /// # Errors
    ///
    /// Every variant here is **pre-admission**: a `StartError` means no Run exists,
    /// the Session lease and Agent attachment have been rolled back, and the
    /// transcript is as it was. Once admission completes, failure is reported by the
    /// returned Run's terminal instead.
    ///
    /// - [`StartError::AgentClosed`] if [`Agent::close`] already won. Checked before
    ///   the Session is touched, so a closed Agent cannot disturb one.
    /// - [`StartError::SessionBusy`] if the Session already has an active lease.
    ///   Retryable once that Run has fully exited; this is the one-active-Run rule,
    ///   not a transient lock.
    /// - [`StartError::Cancelled`] if `cancellation` was already observable, or
    ///   became so, before the last pre-admission commit. A cancellation that first
    ///   becomes visible at or after that commit yields an admitted Run whose
    ///   terminal is canceled instead — so a caller racing cancellation against
    ///   start must handle both.
    /// - [`StartError::Admission`] if a lease-bound admission or prepare
    ///   transaction is rejected, carrying the
    ///   [`LeaseError`](crate::runtime::session::LeaseError).
    /// - [`StartError::Prepare`] if a [`RunHooks::prepare`](super::hook::RunHooks::prepare)
    ///   registration or a transcript reservation failed, naming the registration.
    /// - [`StartError::Transcript`] if recording the admitted input failed, carrying
    ///   the [`store::Error`](crate::transcript::store::Error).
    /// - [`StartError::InvalidIdentity`] if the Session or Run identity is not a
    ///   valid coordinate, and [`StartError::RunIdExhausted`] if the process-wide Run
    ///   identity space is used up.
    ///
    /// # Panics
    ///
    /// If no Tokio runtime is active to spawn the Run task, or if the Agent state,
    /// Session, mailbox, event-control, or hook-fact lock is poisoned, per the
    /// crate-level [lock-poisoning contract](crate#lock-poisoning).
    #[expect(
        clippy::unused_async,
        reason = "ADR-015 keeps the public facade awaited; admission itself never yields"
    )]
    pub async fn start(
        &self,
        session: Session,
        input: Vec<Part>,
        cancellation: Token,
    ) -> Result<Run<M>, StartError> {
        let admitted = self.admit_start(session, input, cancellation)?;
        Ok(Run::spawn(admitted))
    }

    /// Admits one Session use and atomically returns its Run and outward event stream.
    ///
    /// This has the same admission, execution, and failure semantics as [`Agent::start`],
    /// but transfers the unique [`Stream`] to the caller before the Run task is spawned.
    /// Use this entry point when outward observation is required: even if the Run finishes
    /// before the caller is scheduled again, terminal cleanup cannot discard the returned
    /// stream or its queued events.
    ///
    /// The paired Run has no stream left to take, so
    /// [`Run::take_events`](crate::runtime::run::Run::take_events) returns
    /// [`EventsTakenError`](crate::runtime::run::EventsTakenError). Holding the returned
    /// stream without polling it retains queued ordinary events and leaves strong
    /// deliveries waiting for their existing accept-or-reject decision.
    ///
    /// # Errors
    ///
    /// Returns the same pre-admission [`StartError`] variants as [`Agent::start`]. No Run
    /// or stream is returned on error.
    ///
    /// # Panics
    ///
    /// Under the same conditions as [`Agent::start`], including when no Tokio runtime is
    /// active to spawn the Run task.
    #[expect(
        clippy::unused_async,
        reason = "ADR-015 keeps the public facade awaited; admission itself never yields"
    )]
    pub async fn start_observed(
        &self,
        session: Session,
        input: Vec<Part>,
        cancellation: Token,
    ) -> Result<(Run<M>, Stream), StartError> {
        let admitted = self.admit_start(session, input, cancellation)?;
        Ok(Run::spawn_observed(admitted))
    }

    pub(crate) fn new_with_counter(
        config: Config<M>,
        revision_ids: &AtomicU64,
    ) -> Result<Self, ConfigError> {
        let Config {
            model,
            tools,
            hooks,
            system_instruction,
            sampling,
            model_extensions,
        } = config;
        // Only Agent construction consumes the public hook roster into the
        // teardown-bearing crate-private runtime registry.
        let hooks = hooks.build_runtime().map_err(ConfigError::Hooks)?;

        // Validate through the real `RequestPlan::try_into_request` producer.
        let mut defaults = RequestPlan::new();
        defaults
            .extend_system_instruction(system_instruction.iter().cloned())
            .extend_extensions(model_extensions.iter().cloned());
        *defaults.sampling_mut() = sampling.clone();
        defaults
            .try_into_request(Vec::new())
            .map_err(ConfigError::InvalidDefaults)?;

        let id = allocate_revision_id(revision_ids)?;
        let revision = Revision {
            id,
            model,
            tools,
            hook_names: hooks.names().map(str::to_owned).collect(),
            hooks_require_session_state: hooks.requires_session_state(),
            system_instruction: system_instruction.into(),
            sampling,
            model_extensions: model_extensions.into(),
        };
        Ok(Self {
            inner: Arc::new(AgentInner {
                revision,
                hooks,
                state: Mutex::new(AgentState {
                    phase: AgentPhase::Open,
                    active_runs: 0,
                }),
                closed: Notify::new(),
                #[cfg(test)]
                close_wait_probe: Mutex::new(Arc::new(CloseWaitProbe::new(0))),
                #[cfg(test)]
                start_snapshot_results: Mutex::new(VecDeque::new()),
            }),
        })
    }

    /// Returns an owned immutable revision handle without teardown authority.
    #[must_use]
    pub fn revision(&self) -> Revision<M> {
        self.inner.revision.clone()
    }

    /// Closes an idle Agent exactly once, or reports an exact retryable busy count.
    ///
    /// # Errors
    ///
    /// - [`CloseError::Busy`], carrying the exact number of attachments observed at
    ///   the linearization point, if any Run still owns this Agent. This is the
    ///   retryable one, and it is deliberately inert: admission is not sealed and no
    ///   teardown callback runs, so a busy close changes nothing and can be repeated
    ///   after stopping or awaiting the Runs it counted.
    /// - [`CloseError::Hooks`] if teardown ran and some callbacks failed or panicked.
    ///   Every registration's `OnClose` ran regardless, in registration order, and
    ///   [`TeardownError::entries`] lists each failure with its hook's name. To keep
    ///   that guarantee even for a legal panic payload whose destructor also panics,
    ///   each captured panic payload is deliberately forgotten. This leaks one
    ///   payload value per panicking callback, on this pathological path only.
    ///
    /// The second is final rather than retryable: the Agent is closed, the result is
    /// cached, and a later or concurrent close returns this same value without
    /// invoking teardown again.
    ///
    /// # Panics
    ///
    /// If the Agent phase lock is poisoned, per the crate-level
    /// [lock-poisoning contract](crate#lock-poisoning). That lock is the one
    /// place `Open`, `Closing`, and `Closed` linearize, so a poisoned one means
    /// the Agent's close authority is no longer trustworthy; a teardown callback
    /// cannot cause it, because a panicking `OnClose` is caught at its own
    /// boundary and reported as [`CloseError::Hooks`] instead.
    pub async fn close(&self) -> Result<(), CloseError> {
        loop {
            let notified = self.inner.closed.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            match self.close_decision()? {
                CloseDecision::Winner => break,
                CloseDecision::Wait => notified.await,
                CloseDecision::Cached(result) => return result,
            }
        }

        let failures = self.inner.hooks.close();
        let result = if failures.is_empty() {
            Ok(())
        } else {
            Err(CloseError::Hooks(TeardownError(failures.into())))
        };
        let mut state = self.inner.state.lock().expect("Agent state lock poisoned");
        state.phase = AgentPhase::Closed(result.clone());
        drop(state);
        self.inner.closed.notify_waiters();
        result
    }

    fn close_decision(&self) -> Result<CloseDecision, CloseError> {
        let decision = {
            let mut state = self.inner.state.lock().expect("Agent state lock poisoned");
            match &state.phase {
                AgentPhase::Open if state.active_runs != 0 => {
                    return Err(CloseError::Busy {
                        active_runs: state.active_runs,
                    });
                }
                AgentPhase::Open => {
                    state.phase = AgentPhase::Closing;
                    CloseDecision::Winner
                }
                AgentPhase::Closing => CloseDecision::Wait,
                AgentPhase::Closed(result) => CloseDecision::Cached(result.clone()),
            }
        };
        #[cfg(test)]
        if matches!(&decision, CloseDecision::Wait) {
            self.pause_close_waiter_before_await();
        }
        Ok(decision)
    }

    #[cfg(test)]
    pub(crate) fn install_close_wait_probe(&self, waiters: usize) -> Arc<CloseWaitProbe> {
        let probe = Arc::new(CloseWaitProbe::new(waiters));
        *self
            .inner
            .close_wait_probe
            .lock()
            .expect("close wait probe lock poisoned") = Arc::clone(&probe);
        probe
    }

    #[cfg(test)]
    fn pause_close_waiter_before_await(&self) {
        let probe = self
            .inner
            .close_wait_probe
            .lock()
            .expect("close wait probe lock poisoned")
            .clone();
        probe.pause_before_await();
    }

    pub(crate) fn reserve_attachment(&self) -> Result<AttachmentGuard<M>, StartError> {
        let mut state = self.inner.state.lock().expect("Agent state lock poisoned");
        match state.phase {
            AgentPhase::Open => {
                state.active_runs += 1;
                Ok(AttachmentGuard {
                    inner: Arc::clone(&self.inner),
                })
            }
            AgentPhase::Closing | AgentPhase::Closed(_) => Err(StartError::AgentClosed),
        }
    }
}

pub(crate) struct AttachmentGuard<M: Client> {
    inner: Arc<AgentInner<M>>,
}

impl<M: Client> Drop for AttachmentGuard<M> {
    fn drop(&mut self) {
        let mut state = self.inner.state.lock().expect("Agent state lock poisoned");
        state.active_runs -= 1;
    }
}

#[cfg_attr(
    coverage,
    expect(
        deprecated,
        reason = "fetch_update preserves Reef's 1.85 MSRV; nightly renamed it to try_update"
    )
)]
pub(crate) fn allocate_revision_id(counter: &AtomicU64) -> Result<NonZeroU64, ConfigError> {
    match counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
        value.checked_add(1)
    }) {
        Ok(value) => NonZeroU64::new(value).ok_or(ConfigError::RevisionIdExhausted),
        Err(_) => Err(ConfigError::RevisionIdExhausted),
    }
}