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. A fourth optional collaborator,
(#2279) finish_gate, is set via Self::with_finish_gate — see
FinishGate’s docs.
Test: agent_loop::tests::*.
Implementations§
Source§impl AgentLoop
impl AgentLoop
Sourcepub fn new(
config: AgentLoopConfig,
llm: Arc<dyn LlmClientTrait>,
registry: Arc<ToolRegistry>,
) -> Self
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.
Sourcepub fn with_tool_event_sink(self, sink: Arc<dyn ToolEventSink>) -> Self
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.
Sourcepub fn with_cancel_flag(self, cancel: Arc<AtomicBool>) -> Self
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.
Sourcepub fn with_stop_signal(
self,
signal: Arc<dyn Fn() -> bool + Send + Sync>,
) -> Self
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.
Sourcepub fn with_finish_gate(self, gate: FinishGate) -> Self
pub fn with_finish_gate(self, gate: FinishGate) -> Self
Attach a FinishGate consulted the moment a successful
finish_task call would otherwise terminate the loop (#2279).
Why: Gives a caller a hook to reject a premature finish_task with a
recoverable retry instead of letting the loop terminate — see
FinishGate’s docs for how the delegated-engineer and delegating-PM
cases differ. None (the default) is a pure no-op; every existing
call site that never attaches a gate is unaffected.
What: Builder-style setter; returns self for chaining.
Test: agent_loop::tests::finish_gate_trips_and_recovers,
agent_loop::tests::finish_gate_inert_without_named_test_command.
Sourcepub fn with_redundant_run_suppression(self) -> Self
pub fn with_redundant_run_suppression(self) -> Self
Enable redundant full-suite test re-run suppression (#2682).
Why: The complement to Self::with_finish_gate’s verify gate — where
that guarantees the suite runs at least once, this stops it running more
than needed. Opt-in (default false) and attached at the same single
delegated-engineer construction site (runner::in_process) so both
gates bracket the same loop; call sites that never opt in are a pure
no-op.
What: Builder-style setter; returns self for chaining. When set,
Self::dispatch_all consults
crate::redundant_run::is_redundant_test_rerun before spawning a
bash test command and short-circuits a redundant one.
Test: agent_loop::tests::redundant_test_rerun_is_suppressed,
agent_loop::tests::test_rerun_after_edit_is_not_suppressed.
Sourcepub async fn run(
&self,
system: &str,
task: &str,
) -> Result<AgentOutput, AgentLoopError>
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 for a fresh, one-shot run —
run_task and the delegated engineer’s own loop, neither of which
participate in cross-run persistence, always start from a clean slate.
What: Seeds a brand-new Transcript (system + task), then
delegates to Self::run_with_transcript. Because a fresh seed’s
assistant_text_mark() is always 0, the returned output’s content
is identical to the pre-#2344 behaviour (the whole run’s joined
assistant text) — this method’s observable contract is unchanged.
Test: agent_loop::tests::two_turn_flow_completes,
turn_cap_returns_partial_transcript, and timeout_returns_partial.
Sourcepub async fn run_with_transcript(
&self,
transcript: &mut Transcript,
task: &str,
) -> Result<AgentOutput, AgentLoopError>
pub async fn run_with_transcript( &self, transcript: &mut Transcript, task: &str, ) -> Result<AgentOutput, AgentLoopError>
Run the loop against an ALREADY-PREPARED transcript instead of seeding a fresh one (#2344 — the persistent-session entry point).
Why: task::executor::run_and_record needs the PM’s conversation to
survive across repeated task.run calls on the same session:
session::SessionRegistry::begin_pm_transcript either seeds fresh (a
session’s first run) or appends the new request as a user turn onto
the session’s existing, growing history (every run after that) —
either way, transcript arrives here already holding exactly the
messages this run should send. Self::run is just this method
called with a freshly seeded transcript, so both entry points share
one loop implementation.
What: Records transcript.assistant_text_mark() BEFORE driving the
loop, runs the SAME timeout-wrapped run_inner body run used to,
then rewrites content on the resulting AgentOutput (success or any
partial-abort variant, via AgentLoopError::partial_output_mut) to
transcript.assistant_text_since(mark) — scoping THIS call’s reported
answer to only the turns it produced, even though the transcript
itself keeps the full cumulative history for the model and for
session.get_transcript. Skips the rewrite when summary.is_some():
an explicit finish_task completion (#2072) already carries a
deliberate, structured summary via build_finish_output, which must
not be clobbered by the plain assistant-text join.
Test: agent_loop::tests::run_with_transcript_does_not_reseed_system_message,
agent_loop::tests::run_with_transcript_scopes_output_to_new_turns,
agent_loop::tests::run_with_transcript_scopes_partial_output_on_turn_cap,
agent_loop::tests::run_with_transcript_does_not_clobber_finish_task_summary.
Auto Trait Implementations§
impl !RefUnwindSafe for AgentLoop
impl !UnwindSafe for AgentLoop
impl Freeze for AgentLoop
impl Send for AgentLoop
impl Sync for AgentLoop
impl Unpin for AgentLoop
impl UnsafeUnpin for AgentLoop
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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