a2a_protocol_server/tool_loop/executor.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`ToolLoopExecutor`]: a [`ToolLoop`] as an A2A task.
5
6use std::future::Future;
7use std::pin::Pin;
8
9use a2a_protocol_types::approval::ApprovalRequest;
10use a2a_protocol_types::artifact::Artifact;
11use a2a_protocol_types::error::{A2aError, A2aResult};
12use a2a_protocol_types::events::{StreamResponse, TaskArtifactUpdateEvent, TaskStatusUpdateEvent};
13use a2a_protocol_types::message::{Message, Part};
14use a2a_protocol_types::task::{TaskState, TaskStatus};
15
16use super::answer::{Answer, FINISH_REASON_LENGTH, FINISH_REASON_METADATA_KEY};
17use super::idempotency;
18use super::run::{LoopError, ToolLoop};
19use super::steering::Side;
20use super::trace::Sink;
21use crate::executor::AgentExecutor;
22use crate::executor_helpers::EventEmitter;
23use crate::request_context::RequestContext;
24use crate::streaming::EventQueueWriter;
25
26/// The id of the artifact carrying the answer.
27pub const ANSWER_ARTIFACT_ID: &str = "answer";
28
29/// The id of the artifact carrying the tool trace.
30///
31/// One line per call and its result, emitted when at least one tool ran. It
32/// is what lets a caller tell an answer the tools backed from one the model
33/// made up.
34pub const TRACE_ARTIFACT_ID: &str = "tool-trace";
35
36/// An [`AgentExecutor`] that answers each message by running a [`ToolLoop`].
37///
38/// The loop is wholly inside one A2A task: the caller sees `Working`, the
39/// answer artifact ([`ANSWER_ARTIFACT_ID`]), the trace artifact
40/// ([`TRACE_ARTIFACT_ID`]) when a tool ran, and `Completed`. The prompt is
41/// the message's text parts, joined by newlines; a message with none is
42/// refused as an invalid request.
43///
44/// A run that ends without an answer fails the task with the failure-class
45/// extension (`a2a_protocol_types::failure`): `transient` when the model
46/// provider may come back (HTTP 429, 502, 503 or 504, a timeout, no
47/// connection), `internal` for any other provider failure or a tool that
48/// returned [`ToolError::Fatal`], `budget-exhausted` when the model was
49/// still calling tools at the turn bound, the caller's budget
50/// (`RequestContext::budget`, ADR 0023) ran out (its token usage charged to
51/// the `tokens` meter), or the model hit its output limit before writing
52/// any text, and `policy-refusal` when the provider's content filter
53/// withheld the answer. A final reply with no text is such a run
54/// ([`LoopError::EmptyAnswer`]). The status message says which, in words.
55/// Cancellation ends the run at the next turn or call, with nothing
56/// written: the cancel path writes `Canceled`.
57///
58/// A reply that has text but stopped at the output limit completes the task:
59/// the answer artifact's metadata and the `Completed` status message both
60/// carry [`FINISH_REASON_METADATA_KEY`], so a caller can tell a cut-off
61/// answer from one that ended by itself.
62///
63/// Each run's call keys are scoped to the task and the message it answers
64/// (ADR 0026): another message to the same task is new work, with new keys.
65///
66/// [`with_drafts`](Self::with_drafts) also streams each turn's text as it
67/// arrives, to an artifact of its own.
68///
69/// [`ToolError::Fatal`]: super::ToolError::Fatal
70#[derive(Debug)]
71pub struct ToolLoopExecutor {
72 pub(super) tool_loop: ToolLoop,
73 drafts: bool,
74 steering: bool,
75}
76
77impl ToolLoopExecutor {
78 /// An executor running `tool_loop` for each message.
79 #[must_use]
80 pub const fn new(tool_loop: ToolLoop) -> Self {
81 Self {
82 tool_loop,
83 drafts: false,
84 steering: false,
85 }
86 }
87
88 /// Reads the turn's steering inbox
89 /// ([`RequestContext::inbox`](crate::RequestContext::inbox)) before each
90 /// model turn, and adds each message's text to the conversation as a
91 /// user turn, so a caller can correct course while the run works (ADR
92 /// 0036). Off by default. Needs a handler built with
93 /// [`with_steering`](crate::RequestHandlerBuilder::with_steering); without
94 /// one there is no inbox and this does nothing.
95 ///
96 /// The text is the sender's: it is user text like the prompt, with the
97 /// sender's authority over the task and no more. It cannot cancel the run
98 /// (`CancelTask` does), approve an action, or lift a budget. A message
99 /// that arrives during the turn that answers is not read: the run is
100 /// over, and the message is counted as unread.
101 #[must_use]
102 pub const fn with_steering(mut self) -> Self {
103 self.steering = true;
104 self
105 }
106
107 /// Streams each turn's text, as the model sends it, to a draft artifact
108 /// of the turn's own, `draft-1`, `draft-2` and so on
109 /// ([`draft_artifact_id`](super::draft_artifact_id)), each closed with
110 /// `lastChunk` when the next turn starts or the run ends; the answer
111 /// artifact is sent at the end, as without (audit L5). A turn's text is
112 /// known to be the answer only when the turn ends, which is why it is
113 /// not streamed into the answer itself. Needs a model that streams
114 /// ([`ToolModel::complete_streaming`](super::ToolModel::complete_streaming);
115 /// [`OpenAiChatModel`](super::OpenAiChatModel) does); with one that
116 /// does not, no draft is sent. Off by default, since the drafts are
117 /// artifacts a client reading every artifact would now see.
118 #[must_use]
119 pub const fn with_drafts(mut self) -> Self {
120 self.drafts = true;
121 self
122 }
123
124 /// The run, its turns' text streamed to drafts when [`Self::drafts`].
125 async fn run(
126 &self,
127 ctx: &RequestContext,
128 emit: &EventEmitter<'_>,
129 prompt: &str,
130 trace: &Sink,
131 ) -> A2aResult<Result<super::Answer, LoopError>> {
132 // A decision on a call the run is parked on finds that run by the id of the
133 // request, which is the run's journal key; any other message is new work,
134 // keyed by the task and the message it answers.
135 let approval = ctx.approval().filter(|_| self.tool_loop.has_journal());
136 let scope = approval.map_or_else(
137 || idempotency::task_scope(&ctx.task_id.0, &ctx.message.id.0),
138 |a| a.request.request_id.clone(),
139 );
140 let verdict = approval.map(|a| super::journaling::Verdict {
141 digest: a.request.digest.clone(),
142 approved: a.is_approved(),
143 by: a.approver.clone(),
144 });
145 let cancel = &ctx.cancellation_token;
146 let inbox = if self.steering { ctx.inbox() } else { None };
147 // From the authenticated request, never from what the model wrote.
148 let identity = super::policy::TrustedIdentity {
149 tenant: ctx.tenant().map(str::to_owned),
150 principal: ctx.caller_identity().map(str::to_owned),
151 task: Some(ctx.task_id.0.clone()),
152 };
153 if !self.drafts {
154 let side = Side {
155 drafts: None,
156 inbox,
157 trace: Some(trace),
158 identity: Some(&identity),
159 approval: verdict.as_ref(),
160 };
161 return Ok(self
162 .tool_loop
163 .run_drafting(&scope, prompt, cancel, ctx.budget(), side)
164 .await);
165 }
166 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
167 let side = Side {
168 drafts: Some(&tx),
169 inbox,
170 trace: Some(trace),
171 identity: Some(&identity),
172 approval: verdict.as_ref(),
173 };
174 let run = self
175 .tool_loop
176 .run_drafting(&scope, prompt, cancel, ctx.budget(), side);
177 tokio::pin!(run);
178 let mut drafts = super::drafts::Drafts::default();
179 let result = loop {
180 tokio::select! {
181 biased;
182 Some((turn, piece)) = rx.recv() => drafts.push(emit, turn, piece).await?,
183 result = &mut run => break result,
184 }
185 };
186 // Cancelled: the cancel path writes `Canceled`, and nothing after.
187 if matches!(result, Err(LoopError::Cancelled)) {
188 return Ok(result);
189 }
190 while let Ok((turn, piece)) = rx.try_recv() {
191 drafts.push(emit, turn, piece).await?;
192 }
193 drafts.close(emit).await?;
194 Ok(result)
195 }
196}
197
198impl AgentExecutor for ToolLoopExecutor {
199 fn execute<'a>(
200 &'a self,
201 ctx: &'a RequestContext,
202 queue: &'a dyn EventQueueWriter,
203 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
204 Box::pin(async move {
205 let prompt = ctx.message.texts().collect::<Vec<_>>().join("\n");
206 if prompt.trim().is_empty() && ctx.approval().is_none() {
207 return Err(A2aError::invalid_params(
208 "the message has no text to answer",
209 ));
210 }
211 let cancel = &ctx.cancellation_token;
212 if cancel.is_cancelled() {
213 return Ok(());
214 }
215 let emit = EventEmitter::new(ctx, queue);
216 emit.status(TaskState::Working).await?;
217
218 let trace = Sink::default();
219 match self.run(ctx, &emit, &prompt, &trace).await? {
220 Ok(answer) => complete(ctx, queue, &emit, answer).await,
221 Err(LoopError::Cancelled) => Ok(()),
222 Err(LoopError::AwaitingApproval(needed)) => {
223 // The calls made so far have run; the caller sees them, and
224 // then the question. The decision for this digest, from an
225 // approver the gate admits, is what resumes the run.
226 send_trace(&emit, &trace).await?;
227 let question = format!(
228 "Approval needed before calling '{}': {}",
229 needed.tool, needed.summary
230 );
231 let request =
232 ApprovalRequest::new(needed.request_id, needed.summary, needed.digest);
233 emit.request_approval(request, question).await.map(|_| ())
234 }
235 Err(e @ (LoopError::TurnLimit(_) | LoopError::Budget(_))) => {
236 send_trace(&emit, &trace).await?;
237 emit.fail(e.failure_class(), e.to_string()).await
238 }
239 Err(e) => {
240 // The whole error is the operator's; the caller gets
241 // `caller_message`, without the provider's body or URL.
242 trace_warn!(error = %e, "the run failed");
243 send_trace(&emit, &trace).await?;
244 emit.fail(e.failure_class(), e.caller_message()).await
245 }
246 }
247 })
248 }
249}
250
251/// What the status message of a task that completed with a cut-off answer
252/// says, for a person reading it; the machine-readable form is
253/// [`FINISH_REASON_METADATA_KEY`].
254const TRUNCATED_NOTE: &str =
255 "The answer was cut off at the model's output limit and may be incomplete.";
256
257/// Writes the answer artifact, the trace artifact when a tool ran, and
258/// `Completed`. A reply cut off at the output limit
259/// ([`Answer::truncated`]) is still a completed task, since the text is real
260/// and may be enough, but the answer artifact and the status message both
261/// carry [`FINISH_REASON_METADATA_KEY`], so that a caller can tell it from
262/// an answer that ended on its own (audit M-1).
263async fn complete(
264 ctx: &RequestContext,
265 queue: &dyn EventQueueWriter,
266 emit: &EventEmitter<'_>,
267 answer: Answer,
268) -> A2aResult<()> {
269 let marker = answer
270 .truncated()
271 .then(|| serde_json::json!({ FINISH_REASON_METADATA_KEY: FINISH_REASON_LENGTH }));
272 let mut artifact = Artifact::new(ANSWER_ARTIFACT_ID, vec![Part::text(answer.text)]);
273 artifact.metadata.clone_from(&marker);
274 let mut update =
275 TaskArtifactUpdateEvent::new(ctx.task_id.clone(), ctx.context_id.clone(), artifact);
276 update.last_chunk = Some(true);
277 queue.write(StreamResponse::ArtifactUpdate(update)).await?;
278 if !answer.trace.is_empty() {
279 emit.artifact(
280 TRACE_ARTIFACT_ID,
281 vec![Part::text(answer.trace.join("\n"))],
282 None,
283 Some(true),
284 )
285 .await?;
286 }
287 let Some(marker) = marker else {
288 return emit.status(TaskState::Completed).await;
289 };
290 let mut note = Message::agent(
291 uuid::Uuid::new_v4().to_string(),
292 vec![Part::text(TRUNCATED_NOTE)],
293 );
294 note.task_id = Some(ctx.task_id.clone());
295 note.context_id = Some(ctx.context_id.clone());
296 note.metadata = Some(marker);
297 let mut status = TaskStatus::new(TaskState::Completed);
298 status.message = Some(note);
299 queue
300 .write(StreamResponse::StatusUpdate(TaskStatusUpdateEvent::new(
301 ctx.task_id.clone(),
302 ctx.context_id.clone(),
303 status,
304 )))
305 .await
306}
307
308/// Sends the trace of a run that failed, before the failure: the calls it made
309/// have run whatever became of the answer, and a caller that cannot see them
310/// retries with new idempotency keys and runs them again. Since M-1 an empty
311/// final reply after tools fails the task, where it used to complete it with
312/// this trace, and a run that hit the turn bound or its budget never had it
313/// (hostile campaign, wave 2, W2-LIVE-3). Nothing is sent when no call ran.
314async fn send_trace(emit: &EventEmitter<'_>, trace: &Sink) -> A2aResult<()> {
315 let lines = trace.take();
316 if lines.is_empty() {
317 return Ok(());
318 }
319 emit.artifact(
320 TRACE_ARTIFACT_ID,
321 vec![Part::text(lines.join("\n"))],
322 None,
323 Some(true),
324 )
325 .await
326}