Skip to main content

CompletionRunner

Struct CompletionRunner 

Source
pub struct CompletionRunner { /* private fields */ }
Expand description

A iteration style executor for completion.

Implementations§

Source§

impl CompletionRunner

Source

pub fn unbound(self) -> Self

Enables unbound mode for the completion runner.

Source

pub fn reserve_chat_history(self, chat_history: Vec<Message>) -> Self

Reserves the chat history for the completion runner.

Source

pub fn append_chat_history(&mut self, messages: Vec<Message>)

Appends messages to the chat history.

Source

pub fn chat_history_mut(&mut self) -> &mut [Message]

Returns mutable access to the accumulated chat history messages.

This allows callers to update already recorded messages in place while preserving message order. Use Self::append_chat_history to add new messages.

Source

pub fn is_done(&self) -> bool

Returns whether the completion has finished.

Source

pub fn is_idle(&self) -> bool

Returns whether the completion is idle, meaning it has no pending tasks.

Source

pub fn no_pending_tool_calls(&self) -> bool

Returns whether there are no pending tool calls.

Source

pub fn turns(&self) -> usize

Returns the number of turns executed.

Source

pub fn ctx(&self) -> &AgentCtx

Returns the agent context driving this completion.

Source

pub fn req(&self) -> &CompletionRequest

Get the original completion request.

Source

pub fn model(&self) -> &Model

Get the model used for this completion.

Source

pub fn chat_history(&self) -> &Vec<Message>

Returns the chat history of the completion so far.

Source

pub fn total_usage(&self) -> &Usage

Get the total usage accumulated so far, including all intermediate steps.

Source

pub fn current_usage(&self) -> &Usage

Get the usage from the most recent turn.

Source

pub fn tools_usage(&self) -> &HashMap<String, Usage>

Returns the accumulated usage of the tools so far.

Source

pub fn last_output(&self) -> Option<&AgentOutput>

Returns the most recent non-final output, when one is available.

Source

pub fn merge_discovered_tools(&self) -> Option<bool>

Returns the discovered-tool merge policy.

Some(true) forces discovered tool definitions into later requests, Some(false) keeps them only in discovery-tool output context, and None lets the runner probe whether the current model needs request-side merging.

Source

pub fn set_unbound(&mut self, unbound: bool)

Enables or disables unbound mode.

In unbound mode, reaching an idle boundary does not finalize the runner. The step still returns its latest AgentOutput, and later calls to Self::next return Ok(None) while the runner is idle until new input is queued via Self::follow_up or Self::steer. Terminal failures still finalize the runner.

This mode is primarily useful when driving CompletionRunner directly. A CompletionStream still terminates permanently after it yields None, per the Stream contract.

Source

pub fn set_merge_discovered_tools( &mut self, merge_discovered_tools: Option<bool>, )

Sets the discovered-tool merge policy.

Some(true) adds definitions returned by discovery tools such as tools_search and tools_select to later request tool lists, and compacts discovery output kept in conversation context. Some(false) keeps discovered schemas only in discovery-tool output context. None enables the repeated-selection probe so the runner can discover whether the current model needs request-side merging.

Source

pub fn set_allowed_callables(&mut self, allowed: Option<BTreeSet<String>>)

Restricts which callables (tools, agents, subagents) the runner may execute, regardless of the names the model emits.

None (the default) allows any registered callable. Some(set) permits only the lowercased names in set, plus any tool the model legitimately discovered through an allowed discovery tool (tracked in discovered_tools). An empty set therefore rejects every tool/agent call.

This is the enforcement point for subagent tool whitelists: constraining the definitions sent to the model is not sufficient, because the runner dispatches by name against the whole engine.

Source

pub fn with_allowed_callables(self, allowed: Option<BTreeSet<String>>) -> Self

Builder variant of Self::set_allowed_callables.

Source

pub fn steer(&mut self, message: impl Into<ContentPart>)

Queue a steering message to interrupt the agent mid-run. Delivered after current tool execution, skips remaining tools. No effect if the completion has finished.

Source

pub fn steer_content(&mut self, content: Vec<ContentPart>)

Queue a steering message with multiple content parts to interrupt the agent mid-run.

Source

pub fn steering_message_iter(&self) -> Iter<'_, ContentPart>

Returns the iter over the queued steering message content parts.

Source

pub fn follow_up(&mut self, message: impl Into<ContentPart>)

Queue a follow-up message for the next safe user turn. Delivered with the current pending tool-call results when they finish, or at the next idle boundary when no tools are pending. Steering still takes priority. No effect if the completion has finished.

Source

pub fn follow_up_content(&mut self, content: Vec<ContentPart>)

Queue a follow-up message with multiple content parts for the next safe user turn.

Source

pub fn follow_up_message_iter(&self) -> Iter<'_, ContentPart>

Returns the iter over the queued follow-up message content parts.

Source

pub fn discard_in_flight_request(&mut self)

Drops the current in-flight request after a transport-level model failure.

This keeps accumulated chat history, usage, artifacts, and queued follow-up messages, but removes request content that was already sent to the failed completion. Long-lived callers can use this before processing newly queued input, so stale tool results are not resent. Pending, unexecuted tool calls are closed in the visible history before their raw provider history is pruned.

Source

pub fn prune_req_raw_history(&mut self)

Prunes completed tool interactions from the accumulated provider raw history.

req.raw_history holds provider-native message JSON (OpenAI, Anthropic, and Gemini shapes all differ), so pruning rewrites the raw values in place rather than round-tripping through Message, which would drop or corrupt provider-specific formats. Tool-call requests, their results, and items left without meaningful content are removed; visible text and reasoning stay untouched.

Long-lived callers (for example subagent sessions) can invoke this at an idle boundary to reclaim context-window budget from tool payloads the model has already consumed. The call is a no-op unless the runner is idle, so an in-flight tool round is never left with an orphaned call or result.

Source

pub fn stop_current_task(&mut self, output: AgentOutput) -> AgentOutput

Stops the current task while keeping the runner reusable for later input.

This drops in-flight request state, pending tools, queued steering, and queued follow-up text, but it does not mark the runner done. The returned output is recorded as the latest idle-state output and includes accumulated usage/history so observers can account for work already performed before the stop.

Source

pub fn implicit_context(&mut self, message: Message)

Set an implicit context message that is automatically included in the next request.

Source

pub fn set_model(&mut self, model: Option<String>)

Selects the model label to use for subsequent completion turns.

Source

pub fn set_effort(&mut self, effort: Option<ModelEffort>)

Selects the reasoning/thinking effort to use for subsequent completion turns.

Source

pub fn set_tools(&mut self, tools: Vec<FunctionDefinition>)

Selects the tool definitions to use for subsequent completion turns.

Source

pub fn accumulate(&mut self, other: &Usage)

Accumulate usage from an intermediate step into the runner’s total usage.

Source

pub fn accumulate_tools_usage(&mut self, other: &HashMap<String, Usage>)

Accumulate tool usage from an intermediate step into the runner’s total tools usage.

Source

pub fn needs_compaction_with<F>(&self, pending_tokens: F) -> bool
where F: FnOnce() -> u64,

Returns whether the current runner should be compacted based on usage and turn count.

Source

pub async fn next(&mut self) -> Result<Option<AgentOutput>, BoxError>

Execute the next step.

  • Calls the model completion.
  • Automatically handles tool/agent calls and writes the results back to the conversation history.
  • If there are more steps, it constructs the next request and returns the current intermediate result.
  • If completed or failed, it returns the final result; the next call will return Ok(None).
  • In unbound mode, an idle boundary returns the latest step output without finalizing. A later call returns Ok(None) until new input is queued.
Source

pub async fn handoff( &mut self, compaction_prompt: Option<String>, ) -> Result<(Self, AgentOutput), BoxError>

Summarizes the current conversation into a single handoff message and swaps in a fresh runner seeded with that summary, discarding the bloated history. Pending tool calls are executed first unless queued steering interrupts them; interrupted calls are closed before compaction so provider tool-call requirements are not stranded. Queued follow-up or steering input is preserved and delivered after the handoff so user intent is not folded into the compaction prompt.

Source

pub async fn finalize( &mut self, prompt: Option<String>, ) -> Result<AgentOutput, BoxError>

Finalize the completion with an optional prompt.

Queued messages, plus the optional prompt, are processed through the normal runner flow. If the runner is already idle, finalization returns the latest intermediate output with accumulated usage, tool calls, artifacts, and chat history attached.

Auto Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Fruit for T
where T: Send + Downcast,

Source§

impl<T> Instrument for T

Source§

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

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

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.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pipe<T> for T

Source§

fn pipe<F, R>(self, f: F) -> R
where F: FnOnce(T) -> R,

Passes the value through a function. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

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

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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