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 InferenceAdapter> (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 InferenceAdapter>,
registry: Arc<ToolRegistry>,
) -> Self
pub fn new( config: AgentLoopConfig, llm: Arc<dyn InferenceAdapter>, 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 InferenceAdapter>.
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_permission_gate(self, gate: Arc<PermissionGate>) -> Self
pub fn with_permission_gate(self, gate: Arc<PermissionGate>) -> Self
Attach the per-agent permission gate consulted before every tool dispatch (#7948).
Why: the gate’s map comes from the agent this loop runs as, which only
the construction site knows — the same reason with_agent exists.
What: builder-style setter; returns self for chaining.
Test: agent_loop::tests::permission_gate::deny_never_dispatches.
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_events::sink_receives_started_then_finished_in_order.
Sourcepub fn with_agent(self, name: impl Into<String>) -> Self
pub fn with_agent(self, name: impl Into<String>) -> Self
Declare which agent this loop runs as, for tool-event attribution (UI Phase 1).
Why: one ToolEventSink is shared by the PM’s loop and every
delegated sub-agent’s loop, so the sink cannot know who is calling it
— only the loop does. Without this, a UI can attribute a tool call
only by interleaving the event stream against AgentSpawned/
AgentDone ordering, which is exactly the fragile inference this
ticket removes.
What: name should match the name the rest of the taxonomy already
uses for this agent (LlmRequested.agent_name, AgentSpawned.agent,
PmDelegating.agent) so the UI can join them; the two production
delegation sites pass params.agent_name (PM) and the runner’s
agent_name (sub-agent) for exactly that reason. Unset loops emit
events::UNATTRIBUTED_AGENT.
Test: agent_loop::tests::sink_events::sink_events_are_attributed_to_the_agent,
agent_loop::tests::sink_events::unattributed_loop_emits_unknown_agent.
Sourcepub fn with_agent_id(self, id: impl Into<String>) -> Self
pub fn with_agent_id(self, id: impl Into<String>) -> Self
Declare this loop’s STABLE per-spawn id, for tool-event attribution (DOC-39 AC-13.1/13.2).
Why: agent names the sub-agent KIND (e.g. "python-engineer"), but
two concurrently-delegated sub-agents of the SAME kind share that
name and were, before this existed, indistinguishable on the event
stream except by fragile AgentSpawned/AgentDone ordering
inference — exactly the gap DOC-39 AC-13 closes. agent_id is a
per-spawn identity: production mints a fresh UUID v4 once per
delegation (runner::in_process::InProcessAgentRunner::run_pipeline)
and once per PM session
(task::executor::run_and_record/run_task::execute_run_task, both
via a session- or run-scoped id), then attaches it here.
What: Builder-style setter; returns self for chaining. Unset loops
emit events::UNATTRIBUTED_AGENT_ID. Additive alongside agent:
callers that never opt in keep emitting the pre-existing sentinel,
same as agent itself.
Test: agent_loop::tests::sink_events::sequentially_spawned_same_named_loops_get_distinct_agent_ids.
Sourcepub fn with_session_id(self, session_id: impl Into<String>) -> Self
pub fn with_session_id(self, session_id: impl Into<String>) -> Self
Declare this loop’s session id, stamped on every durable compression-telemetry JSONL record it emits (issue #3867).
Why: telemetry::CompressionEvent.session_id needs “tcode’s real
session id” per the issue’s schema notes, but AgentLoop itself is
deliberately session-agnostic everywhere else (see sink.rs’s doc
note: “a session id the engine layer must not know about”) — this
mirrors Self::with_agent_id’s existing precedent of accepting a
caller-supplied identity as an explicit opt-in rather than reaching
into a session layer this crate’s lower engine module must not
depend on.
What: Builder-style setter; returns self for chaining. Unset loops
emit session_id: None on every telemetry record — never a
fabricated id (issue #3867: “null is acceptable when no natural id
exists, but never fabricate one”).
Test: agent_loop::tests::cadence_fire_writes_compression_telemetry.
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