Skip to main content

AgentLoop

Struct AgentLoop 

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

Drives an LLM through a bounded multi-turn tool-calling conversation.

Why: Encapsulates the repetitive, error-prone control flow (call → extract tool calls → dispatch → append → repeat) behind one run method so call sites express intent (“run this task”) not mechanics. What: Holds the config, an Arc<dyn LlmClientTrait> (mockable in tests), an Arc<ToolRegistry> whose schemas are advertised and whose dispatch_gated executes tool calls, and three OPTIONAL collaborators set via builder methods after construction: (#2056) a sink notified around every tool dispatch, (#2056) a cancel flag checked once per turn boundary, and (#2265 fix #5) a stop_signal closure checked at that SAME turn boundary. All three default to None, so every existing call site (run_task, runner::in_process) is unaffected. Test: agent_loop::tests::*.

Implementations§

Source§

impl AgentLoop

Source

pub fn new( config: AgentLoopConfig, llm: Arc<dyn LlmClientTrait>, registry: Arc<ToolRegistry>, ) -> Self

Construct an agent loop from its three core collaborators.

Why: Constructor injection keeps the loop testable — production passes a real LlmClient, tests pass a scripted mock, both as Arc<dyn LlmClientTrait>. What: Stores the config, LLM client, and tool registry; sink/cancel/ stop_signal start None — attach them via Self::with_tool_event_sink/Self::with_cancel_flag/ Self::with_stop_signal when the caller needs them (#2056’s daemon-driven task execution attaches the first two; run_task’s PM loop attaches stop_signal (#2265 fix #5); the delegated engineer’s own loop attaches none of them). Test: agent_loop::tests::two_turn_flow_completes.

Source

pub fn with_tool_event_sink(self, sink: Arc<dyn ToolEventSink>) -> Self

Attach a ToolEventSink notified around every tool dispatch (#2056).

Why: Lets a daemon-driven run make its tool activity observable to a session.attached client without forking the dispatch loop. What: Builder-style setter; returns self for chaining. Test: agent_loop::tests::sink_receives_started_then_finished_in_order.

Source

pub fn with_cancel_flag(self, cancel: Arc<AtomicBool>) -> Self

Attach a cancellation flag checked once per turn boundary (#2056).

Why: session.cancel on an in-flight daemon-driven run must stop the loop cooperatively; sharing one Arc<AtomicBool> between the caller and every loop it spawns (PM + any delegated sub-agent loops) is the cheapest possible cancellation signal. What: Builder-style setter; returns self for chaining. The flag is checked with Ordering::Relaxed — only “has it been set at all” matters, not fine-grained memory ordering with other state. Test: agent_loop::tests::cancel_flag_aborts_before_next_turn.

Source

pub fn with_stop_signal( self, signal: Arc<dyn Fn() -> bool + Send + Sync>, ) -> Self

Attach an external stop condition checked once per turn boundary (#2265 fix #5).

Why: Some callers know, independently of this loop’s own turn/timeout budget, that a shared external condition has made further turns pointless — run_task’s PM loop is the motivating case: once its shared redelegation::RedelegationCapSignal latches (the engineer delegation retry decorator has exhausted MAX_REDELEGATIONS), every subsequent delegate_to_agent call is a guaranteed dead end, so the PM must stop issuing them rather than silently burning its remaining max_turns one doomed tool call at a time (the exact bake-off L1 regression this fix closes). Modelled as a boolean-returning closure, not a narrower RedelegationCapSignal-specific hook, so agent_loop stays generic and does not need to depend on run_task. What: Builder-style setter; returns self for chaining. Checked with the SAME turn-boundary placement as Self::with_cancel_flag — once per iteration, before the next chat call, never mid-tool-call — so a tool dispatch already in flight always completes and is answered first. Test: agent_loop::tests::stop_signal_aborts_before_next_turn.

Source

pub async fn run( &self, system: &str, task: &str, ) -> Result<AgentOutput, AgentLoopError>

Run the loop to completion (or to a budget limit) and return the output.

Why: This is the single public entry point; it owns the whole lifecycle so callers never reconstruct the loop body incorrectly. What: Wraps run_inner in a tokio::time::timeout. On timeout, returns AgentLoopError::Timeout carrying whatever partial output run_inner had accumulated up to the deadline. Test: agent_loop::tests::two_turn_flow_completes, turn_cap_returns_partial_transcript, and timeout_returns_partial.

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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
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> 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<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