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>
impl<M: Client + 'static> Agent<M>
Sourcepub fn new(config: Config<M>) -> Result<Self, ConfigError>
pub fn new(config: Config<M>) -> Result<Self, ConfigError>
Consumes configuration, validates defaults, and freezes a fresh revision.
§Errors
ConfigError::Hooksif the hook roster does not build: an unnamed or duplicated registration, ashook::RegistryErrordescribes.ConfigError::InvalidDefaultsif 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::RevisionIdExhaustedif 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 thanu64::MAXrevisions.
Configuration is consumed either way. A rejected configuration cannot be corrected and retried; rebuild it.
Sourcepub async fn start(
&self,
session: Session,
input: Vec<Part>,
cancellation: Token,
) -> Result<Run<M>, StartError>
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.
StartError::AgentClosedifAgent::closealready won. Checked before the Session is touched, so a closed Agent cannot disturb one.StartError::SessionBusyif 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::Cancelledifcancellationwas 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::Admissionif a lease-bound admission or prepare transaction is rejected, carrying theLeaseError.StartError::Prepareif aRunHooks::prepareregistration or a transcript reservation failed, naming the registration.StartError::Transcriptif recording the admitted input failed, carrying thestore::Error.StartError::InvalidIdentityif the Session or Run identity is not a valid coordinate, andStartError::RunIdExhaustedif 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.
Sourcepub async fn start_observed(
&self,
session: Session,
input: Vec<Part>,
cancellation: Token,
) -> Result<(Run<M>, Stream), StartError>
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.
Sourcepub fn revision(&self) -> Revision<M>
pub fn revision(&self) -> Revision<M>
Returns an owned immutable revision handle without teardown authority.
Sourcepub async fn close(&self) -> Result<(), CloseError>
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::Hooksif teardown ran and some callbacks failed or panicked. Every registration’sOnCloseran regardless, in registration order, andTeardownError::entrieslists 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> Debug for Agent<M>
impl<M: Client> Debug for Agent<M>
Source§fn fmt(&self, formatter: &mut Formatter<'_>) -> Result
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.