a2a_protocol_client/delegation/options.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! What a delegation is given beyond its message, in one value (audit H18,
5//! NEW-h-designs-5).
6//!
7//! A journal, a lease and a budget each had a constructor of their own
8//! ([`Delegation::start_journaled`], [`Delegation::start_leased`],
9//! [`Delegation::start_budgeted`]) and the three did not compose: a supervisor
10//! that kept a journal to survive a restart and leased its children to survive
11//! a crash could not ask for both, and after the restart nothing renewed the
12//! leases of the children it picked up again, so the restart the journal
13//! exists for killed the children it had recorded.
14//! [`Delegation::start_with`] and [`Delegation::reattach_with`] take them all.
15
16use std::sync::Arc;
17use std::time::Duration;
18
19use a2a_protocol_types::MessageSendParams;
20use a2a_protocol_types::budget::ChildGrant;
21use a2a_protocol_types::delegation_journal::{DelegationJournal, DelegationRecord};
22use a2a_protocol_types::idempotency;
23use a2a_protocol_types::lease::Lease;
24use a2a_protocol_types::lineage::Lineage;
25
26use super::renewal::Renewal;
27use super::{Delegation, HandOffPolicy, ResumePolicy, journal, refused};
28use crate::client::A2aClient;
29use crate::error::{ClientError, ClientResult};
30
31/// The journal a delegation keeps a record in.
32pub(super) enum JournalChoice {
33 /// A new record, written before the message is sent.
34 New {
35 journal: Arc<dyn DelegationJournal>,
36 owner: String,
37 agent: String,
38 },
39 /// A record that exists already, kept up to date from a reattach.
40 Existing {
41 journal: Arc<dyn DelegationJournal>,
42 record: String,
43 },
44 /// A record whose child was never named: its message is sent again under
45 /// the record's key (COR-06).
46 Resend {
47 journal: Arc<dyn DelegationJournal>,
48 record: DelegationRecord,
49 },
50}
51
52/// What a delegation is given beyond its message: a lease, a budget, a
53/// journal record, how a lost stream is resumed. Nothing is set by default,
54/// which is [`Delegation::start`].
55#[derive(Default)]
56pub struct DelegationOptions {
57 lease: Option<Duration>,
58 budget: Option<ChildGrant>,
59 journal: Option<JournalChoice>,
60 resume: Option<ResumePolicy>,
61 id_wait: Option<Duration>,
62 lineage: Option<Lineage>,
63 hand_off: Option<HandOffPolicy>,
64}
65
66impl std::fmt::Debug for DelegationOptions {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.debug_struct("DelegationOptions")
69 .field("lease", &self.lease)
70 .field("budget", &self.budget.is_some())
71 .field("journal", &self.journal.is_some())
72 .field("resume", &self.resume)
73 .field("id_wait", &self.id_wait)
74 .field("lineage", &self.lineage)
75 .field("hand_off", &self.hand_off)
76 .finish()
77 }
78}
79
80impl DelegationOptions {
81 /// No lease, no budget, no journal, and the default resume policy.
82 #[must_use]
83 pub fn new() -> Self {
84 Self::default()
85 }
86
87 /// Grants the child a lease of `ttl`, renewed every third of `ttl` until
88 /// the handle ends (see [`Delegation::start_leased`]).
89 #[must_use]
90 pub const fn with_lease(mut self, ttl: Duration) -> Self {
91 self.lease = Some(ttl);
92 self
93 }
94
95 /// Gives the child `grant`, a budget carved out of the parent's (see
96 /// [`Delegation::start_budgeted`]). A reattach cannot restore a grant.
97 #[must_use]
98 pub fn with_budget(mut self, grant: ChildGrant) -> Self {
99 self.budget = Some(grant);
100 self
101 }
102
103 /// Records the delegation in `journal` as a new record, owned by `owner`
104 /// and naming `agent`, written before the message is sent (see
105 /// [`Delegation::start_journaled`]).
106 #[must_use]
107 pub fn with_journal(
108 mut self,
109 journal: Arc<dyn DelegationJournal>,
110 owner: impl Into<String>,
111 agent: impl Into<String>,
112 ) -> Self {
113 self.journal = Some(JournalChoice::New {
114 journal,
115 owner: owner.into(),
116 agent: agent.into(),
117 });
118 self
119 }
120
121 /// Keeps `record`, a record in `journal` that
122 /// [`DelegationJournal::open`] listed, up to date: for
123 /// [`Delegation::reattach_with`].
124 #[must_use]
125 pub fn with_journal_record(
126 mut self,
127 journal: Arc<dyn DelegationJournal>,
128 record: impl Into<String>,
129 ) -> Self {
130 self.journal = Some(JournalChoice::Existing {
131 journal,
132 record: record.into(),
133 });
134 self
135 }
136
137 /// Sends the message again for `record`, a record in `journal` that
138 /// [`DelegationJournal::open`] listed with no task id: its supervisor
139 /// died, or its start failed, before the child was named
140 /// ([`Delegation::start_with`]). The message goes out under the record's
141 /// idempotency key, so an agent that honours keys answers with the child
142 /// the first send created instead of starting another, and the record is
143 /// kept up to date from then on. The message must be the one first sent:
144 /// the journal keeps none.
145 #[must_use]
146 pub fn resending(
147 mut self,
148 journal: Arc<dyn DelegationJournal>,
149 record: DelegationRecord,
150 ) -> Self {
151 self.journal = Some(JournalChoice::Resend { journal, record });
152 self
153 }
154
155 /// Gives the child `lineage`, the job it belongs to (ADR 0034): from an
156 /// executor, `RequestContext::child_lineage` in `a2a-protocol-server`,
157 /// which names this turn's job one level down with this task as the
158 /// parent. Then halting the job by its root stops the child on an agent
159 /// that honours the extension, as it stops this turn. An agent that does
160 /// not ignores it. A reattach sends no message, so it carries none.
161 #[must_use]
162 pub fn with_lineage(mut self, lineage: Lineage) -> Self {
163 self.lineage = Some(lineage);
164 self
165 }
166
167 /// Sets how a lost stream is resumed (see [`ResumePolicy`]).
168 #[must_use]
169 pub const fn with_resume(mut self, policy: ResumePolicy) -> Self {
170 self.resume = Some(policy);
171 self
172 }
173
174 /// Sets how long a cancel waits for the child's id (see
175 /// [`Delegation::with_id_wait`]).
176 #[must_use]
177 pub const fn with_id_wait(mut self, wait: Duration) -> Self {
178 self.id_wait = Some(wait);
179 self
180 }
181
182 /// Sets how a child whose turn a shutdown handed back is continued (see
183 /// [`HandOffPolicy`]; the default continues three times).
184 /// [`HandOffPolicy::never`] opts out.
185 #[must_use]
186 pub const fn with_hand_off(mut self, policy: HandOffPolicy) -> Self {
187 self.hand_off = Some(policy);
188 self
189 }
190}
191
192impl Delegation {
193 /// [`start`](Self::start) with every part of `options` at once: a lease
194 /// renewed until the handle ends, a budget settled when it does, a
195 /// journal record written before the message is sent.
196 ///
197 /// # Errors
198 ///
199 /// As [`start`](Self::start); also the journal's error, as
200 /// [`ClientError::Protocol`], when the record cannot be written (nothing
201 /// is sent then), and [`ClientError::Config`] when `options` names an
202 /// existing journal record, which only
203 /// [`reattach_with`](Self::reattach_with) can keep, or resends for a
204 /// record whose child was named, or that has no key to resend under. When
205 /// the agent refuses the request, a budget reservation is returned and a
206 /// new record is settled `not_started`: no child exists. A resent
207 /// record's is left open: an earlier send may have made a child.
208 pub async fn start_with(
209 client: Arc<A2aClient>,
210 mut params: MessageSendParams,
211 options: DelegationOptions,
212 ) -> ClientResult<Self> {
213 let DelegationOptions {
214 lease,
215 budget,
216 journal,
217 resume,
218 id_wait,
219 lineage,
220 hand_off,
221 } = options;
222 let (new_record, resent) = new_record_of(journal)?;
223 if let Some(lineage) = &lineage {
224 lineage.attach(&mut params.message);
225 }
226 prepare(&mut params, budget.as_ref(), lease);
227 // A resend goes out under its record's key, which it never takes off:
228 // a refusal of that key says the agent cannot deduplicate, and an
229 // unkeyed resend could start a second child.
230 let added = match &resent {
231 Some((_, record)) => {
232 resend_under(&mut params, record)?;
233 false
234 }
235 None => super::keys::add_key(&mut params),
236 };
237 let tenant = params.tenant.clone();
238 // Only a record this start wrote is settled `not_started` on a refusal.
239 let fresh = resent.is_none();
240 let record = match resent {
241 Some((journal, record)) => Some((journal, record.id)),
242 None => begin_record(new_record, ¶ms).await?,
243 };
244 let mut this = match Self::start_keyed(Arc::clone(&client), params, added).await {
245 Ok(this) => this,
246 Err(e) => {
247 if refused(&e) {
248 if let Some(grant) = budget {
249 grant.release();
250 }
251 if let (true, Some((journal, id))) = (fresh, &record) {
252 let _ = journal.settle(id, "not_started", journal::now_ms()).await;
253 }
254 }
255 return Err(e);
256 }
257 };
258 this.renewal = lease.map(|ttl| Renewal::spawn(client, tenant, ttl, &this.origin, None));
259 this.budget = budget.map(super::child_budget::ChildBudget::new);
260 if let Some((journal, id)) = record {
261 this = this.with_journal(journal, id);
262 }
263 Ok(this.with_options(resume, id_wait, hand_off))
264 }
265
266 /// [`reattach`](Self::reattach) with the lease, the journal record, the
267 /// resume policy and the id wait of `options`: the child is picked up
268 /// with its lease renewed again, from the moment the handle exists, and
269 /// its record kept up to date.
270 ///
271 /// A lease the child was granted before the restart lapses after its time
272 /// to live without a renewal; a supervisor that restarts must reattach, and
273 /// so start renewing, inside it. A budget grant cannot be restored: the
274 /// parent's meter died with the process, and the reservation was kept as
275 /// spent.
276 ///
277 /// # Errors
278 ///
279 /// As [`reattach`](Self::reattach); also [`ClientError::Config`] when
280 /// `options` carries a budget, or a new journal record (which is written
281 /// before a message is sent, and a reattach sends none).
282 pub async fn reattach_with(
283 client: Arc<A2aClient>,
284 tenant: Option<String>,
285 task_id: impl Into<String> + Send,
286 last_event_id: Option<String>,
287 options: DelegationOptions,
288 ) -> ClientResult<Self> {
289 if options.budget.is_some() {
290 return Err(ClientError::Config(
291 "a budget grant cannot be restored by Delegation::reattach_with".to_owned(),
292 ));
293 }
294 let existing = match options.journal {
295 None => None,
296 Some(JournalChoice::Existing { journal, record }) => Some((journal, record)),
297 Some(JournalChoice::Resend { .. }) => {
298 return Err(ClientError::Config(
299 "DelegationOptions::resending sends a message: use Delegation::start_with"
300 .to_owned(),
301 ));
302 }
303 Some(JournalChoice::New { .. }) => {
304 return Err(ClientError::Config(
305 "DelegationOptions::with_journal writes a new record before a message is \
306 sent; a reattach keeps an existing one: use with_journal_record"
307 .to_owned(),
308 ));
309 }
310 };
311 let mut this =
312 Self::reattach(Arc::clone(&client), tenant.clone(), task_id, last_event_id).await?;
313 if let Some(ttl) = options.lease {
314 // The child is named already, so its first renewal is made at
315 // once: the lease may be about to lapse.
316 this.renewal = Some(Renewal::spawn(
317 client,
318 tenant,
319 ttl,
320 &this.origin,
321 this.task_id.clone(),
322 ));
323 }
324 if let Some((journal, record)) = existing {
325 this = this.with_journal(journal, record);
326 }
327 Ok(this.with_options(options.resume, options.id_wait, options.hand_off))
328 }
329
330 /// [`start`](Self::start), granting the child a lease of `ttl` and
331 /// renewing it every third of `ttl` until this handle settles, is
332 /// cancelled, is detached or is dropped (see the [module docs](super)).
333 /// The agent must grant leases (its card declares
334 /// `a2a_protocol_types::lease::LEASE_EXTENSION_URI`); one that does not
335 /// ignores the grant, and the child runs as with [`start`](Self::start).
336 ///
337 /// # Errors
338 ///
339 /// As [`start`](Self::start); an agent that grants leases also refuses
340 /// a `ttl` outside its bounds.
341 pub async fn start_leased(
342 client: Arc<A2aClient>,
343 params: MessageSendParams,
344 ttl: Duration,
345 ) -> ClientResult<Self> {
346 Self::start_with(client, params, DelegationOptions::new().with_lease(ttl)).await
347 }
348
349 /// [`start`](Self::start) with `grant`, a budget carved out of the
350 /// parent's by `BudgetHandle::grant`, and a lease of `lease` as
351 /// [`start_leased`](Self::start_leased) grants one when it is `Some`.
352 ///
353 /// When the handle ends, the grant is settled. If the status update
354 /// that settled the child (terminal or interrupted) carried a budget
355 /// report, the parent is charged that spend instead of the reservation.
356 /// Any other ending (a lost stream, a cancel answered by `CancelTask`,
357 /// an unreachable child), a report-less update, or a handle detached or
358 /// dropped keeps the whole reservation as spent. An agent that does not
359 /// implement the extension reports nothing.
360 ///
361 /// # Errors
362 ///
363 /// As [`start`](Self::start). The reservation is returned only when the
364 /// error shows the agent refused the request, so no child exists: an
365 /// A2A error, an HTTP error status, an authentication challenge, or an
366 /// endpoint the client cannot use.
367 /// After a transport error or a timeout a child may be running, and the
368 /// reservation is kept.
369 pub async fn start_budgeted(
370 client: Arc<A2aClient>,
371 params: MessageSendParams,
372 grant: ChildGrant,
373 lease: Option<Duration>,
374 ) -> ClientResult<Self> {
375 let mut options = DelegationOptions::new().with_budget(grant);
376 if let Some(ttl) = lease {
377 options = options.with_lease(ttl);
378 }
379 Self::start_with(client, params, options).await
380 }
381
382 /// Applies the resume policy, the id wait and the hand-off policy of the
383 /// options, where given.
384 const fn with_options(
385 mut self,
386 resume: Option<ResumePolicy>,
387 id_wait: Option<Duration>,
388 hand_off: Option<HandOffPolicy>,
389 ) -> Self {
390 if let Some(policy) = resume {
391 self.resume_policy = policy;
392 }
393 if let Some(wait) = id_wait {
394 self.id_wait = wait;
395 }
396 if let Some(policy) = hand_off {
397 self.hand_off_policy = policy;
398 }
399 self
400 }
401}
402
403/// A new record to write: the journal, its owner, the agent it names.
404type NewRecord = (Arc<dyn DelegationJournal>, String, String);
405
406/// A record to resend for: the journal, and the record.
407type Resent = (Arc<dyn DelegationJournal>, DelegationRecord);
408
409/// The new record `journal` asks for, if it does, or the record to resend
410/// for. A record that exists cannot be started: only a reattach can keep one.
411fn new_record_of(
412 journal: Option<JournalChoice>,
413) -> ClientResult<(Option<NewRecord>, Option<Resent>)> {
414 match journal {
415 None => Ok((None, None)),
416 Some(JournalChoice::New {
417 journal,
418 owner,
419 agent,
420 }) => Ok((Some((journal, owner, agent)), None)),
421 Some(JournalChoice::Resend { journal, record }) => Ok((None, Some((journal, record)))),
422 Some(JournalChoice::Existing { .. }) => Err(ClientError::Config(
423 "DelegationOptions::with_journal_record names a record that exists: \
424 use Delegation::reattach_with, or with_journal for a new one"
425 .to_owned(),
426 )),
427 }
428}
429
430/// What goes into the message before it is sent: the budget and the lease.
431/// The key is the start's (`keys`).
432fn prepare(params: &mut MessageSendParams, budget: Option<&ChildGrant>, lease: Option<Duration>) {
433 if let Some(grant) = budget {
434 grant.budget().attach(&mut params.message);
435 }
436 if let Some(ttl) = lease {
437 Lease::new(ttl).attach(&mut params.message);
438 }
439}
440
441/// Puts `record`'s key on the message to resend for it: a record whose child
442/// was named is reattached, not resent, and one with no key cannot reach the
443/// child the first send made.
444fn resend_under(params: &mut MessageSendParams, record: &DelegationRecord) -> ClientResult<()> {
445 if record.task_id.is_some() {
446 return Err(ClientError::Config(format!(
447 "journal record {} names its child: use Delegation::reattach_with",
448 record.id
449 )));
450 }
451 let Some(key) = &record.idempotency_key else {
452 return Err(ClientError::Config(format!(
453 "journal record {} has no idempotency key, so a resend could start a second child",
454 record.id
455 )));
456 };
457 idempotency::set_key(&mut params.message, key)
458 .map_err(|e| ClientError::Config(format!("journal record {}: {e}", record.id)))
459}
460
461/// Writes the new record, if there is one, before anything is sent, and
462/// returns the journal with the record's id.
463async fn begin_record(
464 new_record: Option<NewRecord>,
465 params: &MessageSendParams,
466) -> ClientResult<Option<(Arc<dyn DelegationJournal>, String)>> {
467 let Some((journal, owner, agent)) = new_record else {
468 return Ok(None);
469 };
470 let key = idempotency::key_of(¶ms.message)
471 .ok()
472 .flatten()
473 .map(str::to_owned);
474 let record = journal::new_record(owner, agent, params.tenant.clone(), key);
475 journal::begin(&*journal, &record).await?;
476 Ok(Some((journal, record.id)))
477}