Skip to main content

a2a_protocol_server/tool_loop/
run.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`ToolLoop`]: model turns and tool calls until the model answers.
5
6use std::collections::{BTreeMap, HashMap};
7use std::fmt;
8
9use a2a_protocol_types::budget::BudgetHandle;
10use tokio_util::sync::CancellationToken;
11
12use super::answer::Answer;
13use super::idempotency::{self, Secret};
14use super::journal::{ReceiptState, StepJournal};
15use super::journaling::{RunJournal, Verdict};
16pub use super::loop_error::LoopError;
17use super::model::{ChatMessage, ChatRequest, ToolCall, ToolModel};
18use super::policy::{CallStatus, TextCallRecovery, ToolPolicy, TraceContent, TrustedIdentity};
19use super::retry::ModelRetry;
20use super::run_support::charge_usage;
21use super::schema::ArgumentCheck;
22use super::steering::{Side, before_turn};
23use super::tool::ToolSet;
24use super::trace;
25use super::turn::Turn;
26use crate::rpc_span::{AgentRun, GenAiMeter, GenAiSpan, Reply};
27
28/// The turn bound when none is set.
29///
30/// Four more than the two rounds a discover-then-query catalogue needs
31/// (`examples/rig-agent` measured six as enough on 2026-10-20), and small
32/// enough that a model which never stops calling tools fails in seconds
33/// rather than at the executor timeout.
34pub const DEFAULT_MAX_TURNS: usize = 8;
35
36/// The tool calls one model reply may make when none is set.
37///
38/// The first this many run and the rest are dropped. A model that writes a
39/// hundred calls in one reply is broken or hostile, and with no bound a reply
40/// of 90,000 of them took a loop from 21 MB to 1.4 GB (hostile campaign, wave
41/// 2, W2-LIVE-5).
42pub const DEFAULT_MAX_CALLS_PER_TURN: usize = 64;
43
44/// Where a call came from, for the policy, and what a person has decided.
45#[derive(Clone, Copy)]
46struct Origin<'a> {
47    from_text: bool,
48    identity: Option<&'a TrustedIdentity>,
49    /// The decision on the call the run was parked on, when it is resumed.
50    approval: Option<&'a Verdict>,
51    /// Whether a call that needs approval has a journal to wait in.
52    can_park: bool,
53}
54
55/// A run's conversation, trace and record of answered calls, which a journal
56/// checkpoints.
57pub(super) struct Progress {
58    pub(super) messages: Vec<ChatMessage>,
59    pub(super) trace: Vec<String>,
60    pub(super) done: HashMap<String, String>,
61}
62
63/// A model, the tools it may call, and the bounded loop between them.
64///
65/// Each turn sends the preamble, the whole conversation and the whole
66/// catalogue; a reply with calls has them run and their results appended,
67/// and a reply without is the answer. What a call returns goes back to the
68/// model, errors included: an unknown tool, arguments that are not a JSON
69/// object and [`ToolError::Failed`](super::ToolError::Failed) are each that call's result, because
70/// that is how a model recovers. Only the provider failing, a
71/// [`ToolError::Fatal`](super::ToolError::Fatal), the turn bound and cancellation end a run.
72///
73/// Each call carries an idempotency key ([`ToolInvocation::idempotency_key`](super::ToolInvocation::idempotency_key),
74/// ADR 0026), and a call identical to one that already succeeded in the run
75/// is answered with the earlier result instead of being run again, unless
76/// its tool is [`read_only`](super::Tool::read_only).
77pub struct ToolLoop {
78    pub(super) model: Box<dyn ToolModel>,
79    pub(super) tools: ToolSet,
80    pub(super) preamble: String,
81    pub(super) max_turns: usize,
82    pub(super) max_calls_per_turn: usize,
83    pub(super) text_recovery: TextCallRecovery,
84    pub(super) trace_content: TraceContent,
85    pub(super) argument_check: ArgumentCheck,
86    pub(super) journal: super::journal_codec::JournalHandle,
87    pub(super) byte_limits: super::limits::ByteLimits,
88    /// The deployment's own pins, checked on resume.
89    pub(super) pin_labels: BTreeMap<String, String>,
90    /// Whether the idempotency secret was set, so keys agree across replicas.
91    pub(super) secret_set: bool,
92    policy: Option<Box<dyn ToolPolicy>>,
93    secret: Secret,
94    agent_name: Option<String>,
95    meter: GenAiMeter,
96    model_retry: Option<ModelRetry>,
97}
98
99impl fmt::Debug for ToolLoop {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.debug_struct("ToolLoop")
102            .field("model", &self.model.model_name())
103            .field("tools", &self.tools)
104            .field("max_turns", &self.max_turns)
105            .field("max_calls_per_turn", &self.max_calls_per_turn)
106            .field("text_recovery", &self.text_recovery)
107            .field("trace_content", &self.trace_content)
108            .field("argument_check", &self.argument_check)
109            .field("journal", &self.journal)
110            .field("policy", &self.policy.is_some())
111            .field("agent_name", &self.agent_name)
112            .field("model_retry", &self.model_retry)
113            .finish_non_exhaustive()
114    }
115}
116
117impl ToolLoop {
118    /// A loop over `model` and `tools`, with no preamble,
119    /// [`DEFAULT_MAX_TURNS`] and text-call recovery on.
120    #[must_use]
121    pub fn new(model: impl ToolModel, tools: ToolSet) -> Self {
122        Self {
123            model: Box::new(model),
124            tools,
125            preamble: String::new(),
126            max_turns: DEFAULT_MAX_TURNS,
127            max_calls_per_turn: DEFAULT_MAX_CALLS_PER_TURN,
128            text_recovery: TextCallRecovery::All,
129            trace_content: TraceContent::Full,
130            argument_check: ArgumentCheck::Off,
131            journal: super::journal_codec::JournalHandle::default(),
132            byte_limits: super::limits::ByteLimits::default(),
133            pin_labels: BTreeMap::new(),
134            secret_set: false,
135            policy: None,
136            secret: idempotency::fresh_secret(),
137            agent_name: None,
138            meter: GenAiMeter::default(),
139            model_retry: None,
140        }
141    }
142
143    /// The turn bound.
144    #[must_use]
145    pub const fn max_turns(&self) -> usize {
146        self.max_turns
147    }
148
149    /// The bound on the tool calls of one reply.
150    #[must_use]
151    pub const fn max_calls_per_turn(&self) -> usize {
152        self.max_calls_per_turn
153    }
154
155    /// Sends `user_text` and runs turns until the model answers without a
156    /// call. `cancel` is checked before each turn and each call, and a turn
157    /// or call in progress is abandoned when it fires. An answer is a final
158    /// reply with text: an empty or blank one is
159    /// [`LoopError::EmptyAnswer`], and one cut off at the model's output
160    /// limit is an [`Answer`] whose [`truncated`](Answer::truncated) is true.
161    ///
162    /// # Errors
163    ///
164    /// A [`LoopError`] naming why there is no answer.
165    pub async fn run(
166        &self,
167        user_text: &str,
168        cancel: &CancellationToken,
169    ) -> Result<Answer, LoopError> {
170        self.run_within(user_text, cancel, None).await
171    }
172
173    /// [`run`](Self::run), held to `budget` when there is one: no turn
174    /// starts once its deadline has passed, and each reply's reported token
175    /// usage (input plus output) is charged to its [`TOKENS_METER`](a2a_protocol_types::budget::TOKENS_METER), the run
176    /// ending once that is spent. A provider that reports no usage charges
177    /// nothing.
178    ///
179    /// # Errors
180    ///
181    /// As [`run`](Self::run), and [`LoopError::Budget`] when the budget runs
182    /// out.
183    pub async fn run_within(
184        &self,
185        user_text: &str,
186        cancel: &CancellationToken,
187        budget: Option<&BudgetHandle>,
188    ) -> Result<Answer, LoopError> {
189        self.run_scoped(&idempotency::fresh_scope(), user_text, cancel, budget)
190            .await
191    }
192
193    /// [`run_within`](Self::run_within), with the calls' idempotency keys
194    /// derived in `scope`. [`run`](Self::run) and `run_within` draw a fresh
195    /// scope for each run; [`ToolLoopExecutor`](super::ToolLoopExecutor)
196    /// uses the task and message ids, so that running the same message of
197    /// the same task again gives each call the key it had before. Give
198    /// different work different scopes: the same call in the same scope has
199    /// the same key.
200    ///
201    /// With a [journal](Self::with_journal) the scope is also the journal's
202    /// key: running the same scope again resumes the run it left, and two
203    /// pieces of work that share a scope share a checkpoint.
204    ///
205    /// # Errors
206    ///
207    /// As [`run_within`](Self::run_within).
208    pub async fn run_scoped(
209        &self,
210        scope: &str,
211        user_text: &str,
212        cancel: &CancellationToken,
213        budget: Option<&BudgetHandle>,
214    ) -> Result<Answer, LoopError> {
215        self.run_drafting(scope, user_text, cancel, budget, Side::default())
216            .await
217    }
218
219    /// [`run_scoped`](Self::run_scoped), each turn's text sent to `drafts`
220    /// as it arrives, with the turn's number, when given (audit L5).
221    pub(super) async fn run_drafting(
222        &self,
223        scope: &str,
224        user_text: &str,
225        cancel: &CancellationToken,
226        budget: Option<&BudgetHandle>,
227        side: Side<'_>,
228    ) -> Result<Answer, LoopError> {
229        let run = AgentRun::start(
230            &self.meter,
231            self.agent_name.as_deref(),
232            self.model.model_name(),
233        );
234        let result = self
235            .run_counted(&run, scope, user_text, cancel, budget, side)
236            .await;
237        run.ended(result.as_ref().err().map(LoopError::error_type).as_deref());
238        result
239    }
240
241    /// [`run_scoped`](Self::run_scoped), counting turns and calls in `run`.
242    async fn run_counted(
243        &self,
244        run: &AgentRun,
245        scope: &str,
246        user_text: &str,
247        cancel: &CancellationToken,
248        budget: Option<&BudgetHandle>,
249        side: Side<'_>,
250    ) -> Result<Answer, LoopError> {
251        let specs = self.tools.specs();
252        let names = self.tools.names();
253        let (mut journal, restored) =
254            RunJournal::open(self, scope, user_text, &specs, side.approval, side.identity).await?;
255        let (mut progress, first_turn, mut resume, identity, finished) = restored.begin(side.trace);
256        if let Some(done) = finished {
257            // Finished before: the same answer again, and nothing else (N04).
258            return Answer::from_reply(done.text, progress.trace, done.finish_reason);
259        }
260        let identity = identity.as_ref().or(side.identity);
261
262        for turn in first_turn..self.max_turns {
263            if cancel.is_cancelled() {
264                return Err(LoopError::Cancelled);
265            }
266            let (calls, from_text) = if let Some(r) = resume.take() {
267                (r.calls, r.recovered)
268            } else {
269                let reply = self
270                    .ask_model(run, turn, cancel, budget, &side, &specs, &mut progress)
271                    .await?;
272                match self.turn_of(reply, turn, &names, &side, &mut progress) {
273                    Turn::Answer(text, finish_reason) => {
274                        let answer =
275                            Answer::from_reply(text, progress.trace.clone(), finish_reason)?;
276                        journal.complete((turn, false), &progress, &answer).await?;
277                        return Ok(answer);
278                    }
279                    Turn::Calls(calls, from_text) => {
280                        journal.save((turn, from_text), &progress).await?;
281                        (calls, from_text)
282                    }
283                    Turn::Ambiguous(id) => return Err(LoopError::AmbiguousCalls { id }),
284                }
285            };
286            let origin = Origin {
287                from_text,
288                identity,
289                approval: side.approval,
290                can_park: journal.enabled(),
291            };
292            let step = (turn, from_text);
293            self.run_calls(
294                run,
295                calls,
296                step,
297                (cancel, scope, origin),
298                &side,
299                &mut progress,
300                &mut journal,
301            )
302            .await?;
303        }
304        Err(LoopError::TurnLimit(self.max_turns))
305    }
306
307    /// One model turn: what the caller said since the last is added to the
308    /// conversation, the model is asked, and its usage charged.
309    #[allow(clippy::too_many_arguments)]
310    async fn ask_model(
311        &self,
312        run: &AgentRun,
313        turn: usize,
314        cancel: &CancellationToken,
315        budget: Option<&BudgetHandle>,
316        side: &Side<'_>,
317        specs: &[super::model::ToolSpec],
318        progress: &mut Progress,
319    ) -> Result<super::model::ModelTurn, LoopError> {
320        before_turn(budget, side.inbox, &mut progress.messages)?;
321        run.inference_call();
322        let sink = side.sink(turn + 1);
323        let bytes = super::limits::request_bytes(&self.preamble, &progress.messages, specs);
324        if bytes > self.byte_limits.request {
325            return Err(LoopError::TooLarge {
326                bytes,
327                limit: self.byte_limits.request,
328            });
329        }
330        let request = ChatRequest::new(&self.preamble, &progress.messages, specs);
331        let reply = self
332            .retried_turn(request, cancel, sink.as_ref(), budget)
333            .await?;
334        charge_usage(budget, &reply)?;
335        Ok(reply)
336    }
337
338    /// Runs `calls`, one after another, each recorded before it runs and after
339    /// it ends; a call a person has to approve parks the run.
340    #[allow(clippy::too_many_arguments)]
341    async fn run_calls(
342        &self,
343        run: &AgentRun,
344        calls: Vec<ToolCall>,
345        step: (usize, bool),
346        (cancel, scope, origin): (&CancellationToken, &str, Origin<'_>),
347        side: &Side<'_>,
348        progress: &mut Progress,
349        journal: &mut RunJournal<'_>,
350    ) -> Result<(), LoopError> {
351        for call in calls {
352            if cancel.is_cancelled() {
353                return Err(LoopError::Cancelled);
354            }
355            // Written before the call runs: a call the journal cannot record is
356            // not run.
357            if journal.enabled() {
358                journal.started(step.0, &call, super::journaling::arguments_digest(&call));
359                journal.save(step, progress).await?;
360            }
361            match self
362                .call(run, &call, cancel, scope, &mut progress.done, origin)
363                .await
364            {
365                Ok((content, status)) => {
366                    let line = self.trace_line(&call, &content, status);
367                    trace::record(&mut progress.trace, side.trace, line);
368                    progress.messages.push(ChatMessage::ToolResult {
369                        call_id: call.id.clone(),
370                        name: call.name.clone(),
371                        content,
372                    });
373                    let state = match status {
374                        CallStatus::Ran => ReceiptState::Ran,
375                        CallStatus::Failed => ReceiptState::Failed,
376                        CallStatus::NotRun => ReceiptState::NotRun,
377                    };
378                    journal.ended(step.0, &call.id, state);
379                    journal.save(step, progress).await?;
380                }
381                Err(LoopError::AwaitingApproval(needed)) => {
382                    journal.park(step.0, &call, &needed, origin.identity);
383                    journal.save(step, progress).await?;
384                    return Err(LoopError::AwaitingApproval(needed));
385                }
386                Err(e) => return Err(e),
387            }
388        }
389        Ok(())
390    }
391
392    /// One model turn, in its span, abandoned if `cancel` fires.
393    async fn turn(
394        &self,
395        request: ChatRequest<'_>,
396        cancel: &CancellationToken,
397        sink: Option<&super::model::TextSink>,
398    ) -> Result<super::model::ModelTurn, LoopError> {
399        let span = GenAiSpan::chat(
400            self.model.provider_name(),
401            self.model.model_name(),
402            self.model.server(),
403            &self.meter,
404        );
405        let result = tokio::select! {
406            biased;
407            () = cancel.cancelled() => return Err(LoopError::Cancelled),
408            result = span.instrument(sink.map_or_else(
409                || self.model.complete(request),
410                |sink| self.model.complete_streaming(request, sink),
411            )) => result,
412        };
413        match result {
414            Ok(reply) => {
415                let usage = reply.usage.unwrap_or_default();
416                span.answered(Reply {
417                    input_tokens: usage.input_tokens,
418                    output_tokens: usage.output_tokens,
419                    response_model: reply.response_model.as_deref(),
420                    response_id: reply.response_id.as_deref(),
421                    finish_reason: reply.finish_reason.as_deref(),
422                });
423                Ok(reply)
424            }
425            Err(e) => {
426                span.failed(&e.error_type());
427                trace_warn!(error = %e, "tool loop: the model provider failed a turn");
428                Err(LoopError::Model(e))
429            }
430        }
431    }
432}
433
434#[path = "run_call.rs"]
435mod call;
436#[path = "run_config.rs"]
437mod config;
438#[path = "run_retried.rs"]
439mod retried;
440
441#[cfg(test)]
442#[path = "run_tests/mod.rs"]
443mod tests;