a2a_protocol_client/delegation/steer.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Steering a delegated child while it works (ADR 0036): a message to the
5//! child's running task, delivered to its executor's inbox.
6//!
7//! [`Delegation::steer`] sends one, and [`steer_all`] sends one to each of
8//! several children at once, reporting what became of each. The agent must
9//! take steering (its card declares
10//! `https://a2a-rust.com/extensions/steering/v1`); one that does not refuses
11//! the message as it refuses any message to a working task, and that refusal
12//! is the error you get. The reply says where the message went and never that
13//! the executor acted on it ([`Steering`]).
14
15use std::sync::Arc;
16
17use a2a_protocol_types::error::A2aError;
18use a2a_protocol_types::idempotency;
19use a2a_protocol_types::responses::SendMessageResponse;
20use a2a_protocol_types::steering::{self, Delivery, Receipt};
21use a2a_protocol_types::task::{ContextId, Task, TaskId};
22use a2a_protocol_types::{Message, MessageSendParams};
23
24use super::Delegation;
25use crate::client::A2aClient;
26use crate::error::{ClientError, ClientResult};
27
28/// What the agent did with a steering message.
29#[derive(Debug)]
30#[non_exhaustive]
31pub enum Steering {
32 /// The message is in the running turn's inbox, or on its way to the
33 /// replica that holds the turn, or was already delivered by an earlier
34 /// attempt: [`Delivery`] says which. It does not say the executor read or
35 /// acted on it.
36 Delivered {
37 /// Where the message went.
38 delivery: Delivery,
39 /// The task as the agent reported it.
40 task: Task,
41 },
42 /// The agent answered, but did not deliver the message to a running
43 /// turn: the task was not running (it had parked at `input-required`, say)
44 /// and the message was handled as any other message to it. What the agent
45 /// answered is here; look at the task's state to see what happened.
46 NotSteered(SendMessageResponse),
47}
48
49/// Steers one child, from anywhere.
50///
51/// It owns what it needs and borrows nothing from the [`Delegation`], so a
52/// parent can steer a child from one task while another waits on it. From
53/// [`Delegation::steer_handle`].
54#[derive(Debug, Clone)]
55pub struct SteerHandle {
56 client: Arc<A2aClient>,
57 tenant: Option<String>,
58 task_id: String,
59 context_id: Option<String>,
60}
61
62impl SteerHandle {
63 /// The child's task id.
64 #[must_use]
65 pub fn task_id(&self) -> &str {
66 &self.task_id
67 }
68
69 /// Sends `message` to the child's running task: names the task (and its
70 /// context, when known), lists the steering extension, and, when the
71 /// agent is known to honour idempotency keys and the message has none,
72 /// gives it a fresh one, so a client with a retry policy can retry a
73 /// delivery whose answer was lost without delivering it twice.
74 ///
75 /// # Errors
76 ///
77 /// The client's: the agent refused the message (a full inbox is `503`
78 /// with `Retry-After`; a task that ended is an error naming it; an agent
79 /// that does not take steering refuses it as it refuses any message to a
80 /// working task), or the call failed. An answer that carries a receipt
81 /// that is not one is [`ClientError::Protocol`].
82 pub async fn steer(&self, mut message: Message) -> ClientResult<Steering> {
83 message.task_id = Some(TaskId::new(self.task_id.as_str()));
84 if let Some(context) = &self.context_id {
85 message.context_id = Some(ContextId::new(context.as_str()));
86 }
87 steering::declare(&mut message);
88 if self.client.honours_idempotency() && matches!(idempotency::key_of(&message), Ok(None)) {
89 // A fresh key is 64 hex digits, always valid, so this cannot fail.
90 let _ = idempotency::set_key(&mut message, &super::fresh_key());
91 }
92 let mut params = MessageSendParams::new(message);
93 params.tenant.clone_from(&self.tenant);
94 let response = self.client.send_message(params).await?;
95 let receipt = match &response {
96 SendMessageResponse::Task(task) => {
97 Receipt::read(task).map_err(ClientError::Protocol)?
98 }
99 _ => None,
100 };
101 Ok(match (receipt, response) {
102 (Some(receipt), SendMessageResponse::Task(task)) => Steering::Delivered {
103 delivery: receipt.delivery,
104 task,
105 },
106 (_, response) => Steering::NotSteered(response),
107 })
108 }
109}
110
111impl Delegation {
112 /// A handle that steers this child from anywhere ([`SteerHandle`]), once
113 /// an event has named the child; `None` before that.
114 #[must_use]
115 pub fn steer_handle(&self) -> Option<SteerHandle> {
116 Some(SteerHandle {
117 client: Arc::clone(&self.client),
118 tenant: self.tenant.clone(),
119 task_id: self.task_id.clone()?,
120 context_id: self.context_id.clone(),
121 })
122 }
123
124 /// Sends `message` to the child's running task, so its executor can
125 /// read it between steps; see [`SteerHandle::steer`] for what is added to
126 /// the message and how it can be refused.
127 ///
128 /// The child must have been named by an event
129 /// ([`next_event`](Self::next_event), or [`task_id`](Self::task_id)
130 /// answering `Some`): nothing is sent before that.
131 ///
132 /// # Errors
133 ///
134 /// [`ClientError::Transport`] when the child has not been named yet;
135 /// [`SteerHandle::steer`]'s otherwise.
136 pub async fn steer(&self, message: Message) -> ClientResult<Steering> {
137 match self.steer_handle() {
138 Some(handle) => handle.steer(message).await,
139 None => Err(not_named()),
140 }
141 }
142}
143
144fn not_named() -> ClientError {
145 ClientError::Transport(
146 "the delegated child has not been named by an event yet, so there is no task to steer; \
147 nothing was sent"
148 .to_owned(),
149 )
150}
151
152/// What became of the message sent to one child by [`steer_all`].
153#[derive(Debug)]
154#[non_exhaustive]
155pub struct ChildSteering {
156 /// The child's task id, when it had been named.
157 pub task_id: Option<String>,
158 /// What the agent did with the message, or why it was not delivered.
159 pub result: ClientResult<Steering>,
160}
161
162/// One child's steering send, running: its task id, and the send if it could be made.
163type Sent = (
164 Option<String>,
165 Option<tokio::task::JoinHandle<ClientResult<Steering>>>,
166);
167
168/// Steers each of `children` at once, with a message made by `message` for
169/// each (a message needs its own id, so the closure is called once per
170/// child), and returns what became of each, in the order given.
171///
172/// Waits for every child: each send is bounded by the client's own timeout,
173/// one that fails or is refused does not stop the others, and the caller
174/// learns the whole outcome at once, which is what a fan-out of corrections
175/// is for. A child not yet named is reported as such, with nothing sent.
176/// ADR 0033's group of delegations will wrap this.
177///
178/// ```rust,no_run
179/// use a2a_protocol_client::delegation::{Delegation, steer_all};
180/// use a2a_protocol_types::Message;
181/// # async fn run(children: Vec<Delegation>) {
182/// let outcomes = steer_all(&children, || {
183/// Message::user_text(uuid::Uuid::new_v4().to_string(), "stop at the first match")
184/// })
185/// .await;
186/// for child in outcomes {
187/// println!("{:?}: {:?}", child.task_id, child.result.is_ok());
188/// }
189/// # }
190/// ```
191pub async fn steer_all<'a, I, F>(children: I, mut message: F) -> Vec<ChildSteering>
192where
193 I: IntoIterator<Item = &'a Delegation>,
194 F: FnMut() -> Message,
195{
196 let sent: Vec<Sent> = children
197 .into_iter()
198 .map(|child| {
199 let task_id = child.task_id().map(str::to_owned);
200 let handle = child.steer_handle().map(|handle| {
201 let message = message();
202 tokio::spawn(async move { handle.steer(message).await })
203 });
204 (task_id, handle)
205 })
206 .collect();
207 let mut outcomes = Vec::with_capacity(sent.len());
208 for (task_id, handle) in sent {
209 let result = match handle {
210 None => Err(not_named()),
211 Some(handle) => handle.await.unwrap_or_else(|e| {
212 Err(ClientError::Protocol(A2aError::internal(format!(
213 "the steering send panicked: {e}"
214 ))))
215 }),
216 };
217 outcomes.push(ChildSteering { task_id, result });
218 }
219 outcomes
220}