Skip to main content

Agent

Struct Agent 

Source
pub struct Agent<M: Client> { /* private fields */ }
Expand description

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 first runs each hook’s OnClose exactly once and every other caller receives that same cached result.

use reef_core::cancel;
use reef_core::runtime::{agent, hook, session, tool};
use reef_core::value::{content, lifecycle};

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());

Implementations§

Source§

impl<M: Client + 'static> Agent<M>

Source

pub fn new(config: Config<M>) -> Result<Self, ConfigError>

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.

Source

pub async fn start( &self, session: Session, input: Vec<Part>, cancellation: Token, ) -> Result<Run<M>, StartError>

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. 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.

§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.

Source

pub async fn start_observed( &self, session: Session, input: Vec<Part>, cancellation: Token, ) -> Result<(Run<M>, Stream), StartError>

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 returns 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.

Source

pub fn revision(&self) -> Revision<M>

Returns an owned immutable revision handle without teardown authority.

Source

pub async fn close(&self) -> Result<(), CloseError>

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. 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.

Trait Implementations§

Source§

impl<M: Client> Clone for Agent<M>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<M: Client> Debug for Agent<M>

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

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.

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for Agent<M>

§

impl<M> !UnwindSafe for Agent<M>

§

impl<M> Freeze for Agent<M>
where Arc<AgentInner<M>>: Freeze,

§

impl<M> Send for Agent<M>
where Arc<AgentInner<M>>: Send,

§

impl<M> Sync for Agent<M>
where Arc<AgentInner<M>>: Sync,

§

impl<M> Unpin for Agent<M>
where Arc<AgentInner<M>>: Unpin,

§

impl<M> UnsafeUnpin for Agent<M>
where Arc<AgentInner<M>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.