Skip to main content

Runner

Struct Runner 

Source
pub struct Runner<A> { /* private fields */ }
Expand description

A configured run: the agent, its transformer chain and its cancellation token.

let runner = Runner::new(MyAgent).transformer(FilterToolCalls::deny(["internal_debug"]));
let token = runner.cancellation_token();   // hand this to the transport
let stream = runner.run(RunAgentInput::new("thread-1", "run-1"));

Implementations§

Source§

impl<A> Runner<A>

Source

pub fn new(agent: A) -> Self

Wraps an agent.

Source

pub fn transformer(self, transformer: impl StreamTransformer + 'static) -> Self

Appends a transformer to the chain. See StreamTransformer.

Source

pub fn transformers(self, chain: TransformerChain) -> Self

Replaces the whole transformer chain.

Source

pub fn cancellation(self, token: CancellationToken) -> Self

Uses an existing cancellation token instead of the fresh one.

Source

pub fn cancellation_token(&self) -> CancellationToken

A handle on this run’s cancellation, for the transport to trip when the client disconnects.

Source

pub fn echo_input(self, echo: bool) -> Self

Echoes the request back on RUN_STARTED, so a recorded stream replays without the original HTTP body. Off by default — it is the largest payload in the protocol.

This decides only what goes on the wire. The verifier and every transformer learn the request’s history either way (see StreamTransformer::seed), so a resumed run behaves the same with and without the echo.

Source

pub fn event_buffer_capacity(self, capacity: NonZeroUsize) -> Self

Limits queued events, including lifecycle events, after transformation.

Emission is synchronous, so it cannot wait for a slow consumer. When full, the sink rejects the next event, appends one reserved RUN_ERROR with code EVENT_BUFFER_FULL, then closes the stream. Already accepted events retain their order. This terminal error bypasses transformers.

The default remains unbounded. This bounds event count, not payload bytes or allocations made by an agent/transformer before emission. Applications with durable execution should reconnect from committed state; this transport failure does not decide business success.

Source§

impl<A: Agent> Runner<A>

Source

pub fn run(self, input: RunAgentInput) -> impl Stream<Item = Event> + Send

Starts the run.

The returned stream emits RUN_STARTED first and exactly one of RUN_FINISHED / RUN_ERROR last — including when the agent body does nothing, and when it returns Err through a ?.

The stream yields Event, not Result<Event>: whatever goes wrong inside a run is reported in the stream, as RUN_ERROR, so there is no error left for an item to carry.

A panic inside the agent is not caught; it unwinds through whoever is polling the stream, as it would through any other future. Use the transport’s own panic handling if you need a response body for that case.

§The run lives as long as the stream

The agent advances only while the stream is polled, and is dropped with it. A stream dropped before its terminal event leaves a run that stopped where it was: no RUN_FINISHED and no RUN_ERROR, for anyone. That is the right lifetime for a run that answers one request, where the response body is the stream and a client that goes away takes the run with it.

It is the wrong one for a run that outlives its response. Take the halves with into_parts instead; the module docs say what else such a server needs.

Source

pub fn into_parts( self, input: RunAgentInput, ) -> (impl Future<Output = ()> + Send, EventReceiver)

Starts the run as its two halves: the future that drives the agent, and the receiver of what it emits.

For a run that is not tied to one response. Put the driver on an executor of your choosing and send the events wherever they are stored and fanned out. The agent then advances whether or not anyone is reading, and a client that disconnects ends nothing.

Everything run promises holds for the halves: RUN_STARTED first, exactly one terminal event last, the transformer chain, the cancellation token, the typed emitters and the ordering checks. run is these two halves joined in one stream.

let runner = Runner::new(Greeter);
let (driver, mut events) = runner.into_parts(RunAgentInput::new("thread-1", "run-1"));

// Any executor will do: the driver is a plain future.
let run = tokio::spawn(driver);

// Store each event, and send it to whoever is on the thread now.
let mut stored = Vec::new();
while let Some(event) = events.next().await {
    stored.push(event);
}
// The receiver ended, so nothing more will arrive: stop the driver.
run.abort();

assert_eq!(stored.first().map(Event::event_type), Some(EventType::RunStarted));
assert_eq!(stored.last().map(Event::event_type), Some(EventType::RunFinished));
§What the stream did for you

Three things, which are now the caller’s:

  • Poll the driver to completion. The terminal event is emitted by the driver, after the agent returns. A driver dropped earlier ends the receiver with no terminal event.
  • Drop the driver when the receiver ends. The receiver ends when the driver has finished, and also when a bounded queue overflows (event_buffer_capacity): the sink then queues its RUN_ERROR and closes. An agent that ignores the error its emit returned can go on awaiting forever, and nothing it does after that reaches anyone.
  • Keep the receiver, or cancel. Dropping the receiver fails every later emit with Error::Disconnected, which unwinds an agent that uses ?. To stop a run on purpose, trip the cancellation_token: the run then closes what it opened and ends with a cancelled RUN_FINISHED.

The receiver holds one run’s events for one reader. Giving them to several clients, and to one that joins later, is the application’s: RunProgress builds what a client that joins a run in progress is sent first.

Source

pub fn continue_run( self, input: RunAgentInput, sent: &[Event], ) -> Result<(impl Future<Output = ()> + Send + use<A>, EventReceiver)>

Carries on a run that another driver began: the same halves as into_parts, for a run whose first events are already sent.

sent is every event of the run that went out, in order, as stored. It may begin with the runs that came before on the same stream; the run continued is the last one it starts. input is the request the run is continued from: the thread and run ids of the run, the messages it started with, and the state as it stands now, which the agent reads as its own.

The driver emits no RUN_STARTED, and it ends the run with exactly one terminal event, as any driver does. What it emits continues the stream that sent began:

  • the ordering checks start from where the run is, so an entity the earlier driver left open can be continued and closed, and has to be closed before RUN_FINISHED;
  • the first state the agent publishes is compared with the state the events sent left a client holding, and goes out as a delta against it;
  • a subagent left active is closed by the agent, or by the driver when the run is cancelled;
  • the ids the context hands out count on from the ones sent used, and are never one of them.

The transformers start fresh. They are seeded with input.messages and then shown sent (StreamTransformer::replay), and from there they are fed what the agent emits. sent is the output of the earlier driver’s chain, so a transformer learns from it what a consumer was sent, and not what that chain kept back: FilterToolCalls lets this driver finish and answer a call that was sent, and drops an event of a call it has no record of, which is what a call the earlier filter dropped looks like from here.

An entity the earlier driver opened has no handle here. Continue and close it with RunContext::emit, naming its id. A run that is cancelled cannot: every emit fails once the token is tripped. So the driver closes what sent left open before the RUN_FINISHED that cancels the run, innermost first and each under the subagent that opened it: a message, a tool call, a reasoning message, a reasoning block, a step. A run that is not cancelled has to close them itself, and its RUN_FINISHED is refused while one is open, with the verify feature or without. echo_input has nothing to echo on, since no RUN_STARTED is sent.

/// Finishes the sentence another process left open.
struct Finisher;

impl Agent for Finisher {
    type State = ();
    async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
        ctx.emit(Event::text_message_content("msg-1", " world"))?;
        ctx.emit(Event::text_message_end("msg-1"))?;
        Ok(RunOutcome::Success)
    }
}

// What the store holds of the run: the process driving it stopped here.
let sent = [
    Event::run_started("thread-1", "run-1"),
    Event::text_message_start("msg-1", TextMessageRole::Assistant),
    Event::text_message_content("msg-1", "Hello"),
];

let request = RunAgentInput::new("thread-1", "run-1");
let (driver, events) = Runner::new(Finisher).continue_run(request, &sent)?;
tokio::spawn(driver);

let rest: Vec<EventType> = events.map(|event| event.event_type()).collect().await;
assert_eq!(
    rest,
    [
        EventType::TextMessageContent,
        EventType::TextMessageEnd,
        EventType::RunFinished,
    ]
);
§Errors

Nothing is driven and nothing is emitted when there is no run to continue:

  • Error::Verification when sent holds no RUN_STARTED, when the last run it starts already ended, or, with the verify feature, when an event in it breaks the ordering rules: the error is that event’s;
  • Error::Json when a STATE_DELTA in sent carries a patch that is not well formed;
  • Error::Protocol when input names another thread or run than the last RUN_STARTED in sent.

Trait Implementations§

Source§

impl<A> Debug for Runner<A>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<A> !RefUnwindSafe for Runner<A>

§

impl<A> !Sync for Runner<A>

§

impl<A> !UnwindSafe for Runner<A>

§

impl<A> Freeze for Runner<A>
where A: Freeze,

§

impl<A> Send for Runner<A>
where A: Send,

§

impl<A> Unpin for Runner<A>
where A: Unpin,

§

impl<A> UnsafeUnpin for Runner<A>
where A: 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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.

§

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. 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.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more