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>
impl<A> Runner<A>
Sourcepub fn transformer(self, transformer: impl StreamTransformer + 'static) -> Self
pub fn transformer(self, transformer: impl StreamTransformer + 'static) -> Self
Appends a transformer to the chain. See StreamTransformer.
Sourcepub fn transformers(self, chain: TransformerChain) -> Self
pub fn transformers(self, chain: TransformerChain) -> Self
Replaces the whole transformer chain.
Sourcepub fn cancellation(self, token: CancellationToken) -> Self
pub fn cancellation(self, token: CancellationToken) -> Self
Uses an existing cancellation token instead of the fresh one.
Sourcepub fn cancellation_token(&self) -> CancellationToken
pub fn cancellation_token(&self) -> CancellationToken
A handle on this run’s cancellation, for the transport to trip when the client disconnects.
Sourcepub fn echo_input(self, echo: bool) -> Self
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.
Sourcepub fn event_buffer_capacity(self, capacity: NonZeroUsize) -> Self
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>
impl<A: Agent> Runner<A>
Sourcepub fn run(self, input: RunAgentInput) -> impl Stream<Item = Event> + Send
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.
Sourcepub fn into_parts(
self,
input: RunAgentInput,
) -> (impl Future<Output = ()> + Send, EventReceiver)
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 itsRUN_ERRORand 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 thecancellation_token: the run then closes what it opened and ends with a cancelledRUN_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.
Sourcepub fn continue_run(
self,
input: RunAgentInput,
sent: &[Event],
) -> Result<(impl Future<Output = ()> + Send + use<A>, EventReceiver)>
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
sentused, 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::Verificationwhensentholds noRUN_STARTED, when the last run it starts already ended, or, with theverifyfeature, when an event in it breaks the ordering rules: the error is that event’s;Error::Jsonwhen aSTATE_DELTAinsentcarries a patch that is not well formed;Error::Protocolwheninputnames another thread or run than the lastRUN_STARTEDinsent.