Skip to main content

a2a_server/
handler.rs

1// Copyright AGNTCY Contributors (https://github.com/agntcy)
2// Copyright A2A Contributors (https://github.com/a2aproject)
3// SPDX-License-Identifier: Apache-2.0
4use a2a::*;
5use async_trait::async_trait;
6use futures::{
7    StreamExt, future,
8    stream::{self, BoxStream},
9};
10use std::{
11    collections::HashMap,
12    sync::{Arc, Mutex, MutexGuard, PoisonError},
13};
14use tokio::sync::{RwLock, broadcast, oneshot};
15
16use crate::middleware::ServiceParams;
17use crate::pagination::resolve_page_size;
18use crate::task_store::apply_history_length;
19
20const EXECUTION_BUFFER_CAPACITY: usize = 32;
21
22/// What a subscription attaches to: the events to come, the task as of the
23/// last event already published, and that event's sequence.
24type Resubscription = (broadcast::Receiver<ExecutionEvent>, Option<Task>, u64);
25
26#[derive(Clone)]
27struct ExecutionEvent {
28    sequence: u64,
29    result: Result<StreamResponse, A2AError>,
30}
31
32#[derive(Default)]
33struct ActiveExecutionState {
34    sequence: u64,
35    snapshot_task: Option<Task>,
36}
37
38struct ActiveExecution {
39    sender: broadcast::Sender<ExecutionEvent>,
40    state: RwLock<ActiveExecutionState>,
41}
42
43impl ActiveExecution {
44    fn new(task: Task) -> Arc<Self> {
45        let (sender, _) = broadcast::channel(EXECUTION_BUFFER_CAPACITY);
46        Arc::new(Self {
47            sender,
48            state: RwLock::new(ActiveExecutionState {
49                sequence: 0,
50                snapshot_task: Some(task),
51            }),
52        })
53    }
54
55    fn subscribe(&self) -> broadcast::Receiver<ExecutionEvent> {
56        self.sender.subscribe()
57    }
58
59    async fn resubscribe(&self) -> Resubscription {
60        let receiver = self.sender.subscribe();
61        let state = self.state.read().await;
62        (receiver, state.snapshot_task.clone(), state.sequence)
63    }
64
65    async fn publish(
66        &self,
67        result: Result<&StreamResponse, &A2AError>,
68        snapshot_task: Option<Task>,
69    ) {
70        let mut state = self.state.write().await;
71        // An event can be persisted before cancellation, but held up while
72        // its push notification is sent. It must not restore the old snapshot
73        // or reach subscribers after the cancellation has been published.
74        if state
75            .snapshot_task
76            .as_ref()
77            .is_some_and(|task| task.status.state.is_terminal())
78        {
79            return;
80        }
81        if let Some(task) = snapshot_task {
82            state.snapshot_task = Some(task);
83        }
84        state.sequence += 1;
85        let sequence = state.sequence;
86
87        // Task state remains available for a later subscription, but transient
88        // events do not need to be allocated when no subscriber is listening.
89        if self.sender.receiver_count() == 0 {
90            return;
91        }
92
93        let event = ExecutionEvent {
94            sequence,
95            result: result.cloned().map_err(Clone::clone),
96        };
97        // Keep sequence assignment and broadcast ordered with the snapshot.
98        let _ = self.sender.send(event);
99    }
100
101    async fn snapshot_is_terminal(&self) -> bool {
102        let state = self.state.read().await;
103        state
104            .snapshot_task
105            .as_ref()
106            .is_some_and(|task| task.status.state.is_terminal())
107    }
108}
109
110#[derive(Default)]
111struct ExecutionManager {
112    executions: RwLock<HashMap<TaskId, Arc<ActiveExecution>>>,
113    /// Subscriptions to tasks with no registered execution, which `start`
114    /// attaches to the next one. Taken under `executions` by `start` and
115    /// `subscribe`, alone by `Waiter::drop` and `release`, never across an
116    /// await.
117    waiting: Mutex<HashMap<TaskId, Vec<oneshot::Sender<Resubscription>>>>,
118}
119
120impl ExecutionManager {
121    fn waiting(&self) -> MutexGuard<'_, HashMap<TaskId, Vec<oneshot::Sender<Resubscription>>>> {
122        self.waiting.lock().unwrap_or_else(PoisonError::into_inner)
123    }
124
125    async fn start(&self, task: Task) -> Result<Arc<ActiveExecution>, A2AError> {
126        let mut executions = self.executions.write().await;
127        if executions.contains_key(&task.id) {
128            return Err(A2AError::invalid_request(format!(
129                "task execution is already in progress: {}",
130                task.id
131            )));
132        }
133
134        let active = ActiveExecution::new(task.clone());
135        executions.insert(task.id.clone(), active.clone());
136        // Subscribed before the executor runs, so they miss none of its events.
137        let waiting = self.waiting().remove(&task.id).unwrap_or_default();
138        for waiter in waiting {
139            let _ = waiter.send((active.subscribe(), Some(task.clone()), 0));
140        }
141        Ok(active)
142    }
143
144    async fn get(&self, task_id: &str) -> Option<Arc<ActiveExecution>> {
145        let executions = self.executions.read().await;
146        executions.get(task_id).cloned()
147    }
148
149    /// Subscribes to the task's registered execution or, when there is none,
150    /// to the next one `start` registers. Decided under the registry lock, so
151    /// an execution registering meanwhile is either found here or finds the
152    /// waiter.
153    async fn subscribe(self: &Arc<Self>, task_id: &str) -> Waiter {
154        let (sender, receiver) = oneshot::channel();
155        let executions = self.executions.read().await;
156        match executions.get(task_id) {
157            Some(active) => {
158                let _ = sender.send(active.resubscribe().await);
159            }
160            None => {
161                self.waiting()
162                    .entry(task_id.to_owned())
163                    .or_default()
164                    .push(sender);
165            }
166        }
167        drop(executions);
168        Waiter {
169            manager: Arc::clone(self),
170            task_id: task_id.to_owned(),
171            attached: Some(receiver),
172        }
173    }
174
175    /// Ends the subscriptions still waiting for the task's next execution
176    /// with its final snapshot: a canceled task has no execution for them to
177    /// follow, and a terminal snapshot closes their streams.
178    fn release(&self, task: &Task) {
179        let waiting = self.waiting().remove(&task.id).unwrap_or_default();
180        for waiter in waiting {
181            let (_, events) = broadcast::channel(1);
182            let _ = waiter.send((events, Some(task.clone()), 0));
183        }
184    }
185
186    async fn finish(&self, task_id: &str, active: &Arc<ActiveExecution>) {
187        let mut executions = self.executions.write().await;
188        let should_remove = executions
189            .get(task_id)
190            .is_some_and(|current| Arc::ptr_eq(current, active));
191        if should_remove {
192            executions.remove(task_id);
193        }
194    }
195}
196
197/// Ends the subscriptions still waiting for a task when dropped, so a cancel
198/// that fails part-way leaves none of them behind.
199struct ReleaseOnDrop<'a> {
200    manager: &'a ExecutionManager,
201    task: Task,
202}
203
204impl Drop for ReleaseOnDrop<'_> {
205    fn drop(&mut self) {
206        self.manager.release(&self.task);
207    }
208}
209
210/// Complete an attached execution when cancellation exits after `begin_cancel`
211/// returned the committed final state, including when its future is dropped.
212struct FinishCancelOnDrop {
213    manager: Arc<ExecutionManager>,
214    active: Option<Arc<ActiveExecution>>,
215    task: Task,
216    armed: bool,
217    runtime: Option<tokio::runtime::Handle>,
218}
219
220impl FinishCancelOnDrop {
221    async fn finish(&mut self, publish_canceled: bool) {
222        if self.armed {
223            if let Some(active) = &self.active {
224                if publish_canceled {
225                    active
226                        .publish(Ok(&status_update(&self.task)), Some(self.task.clone()))
227                        .await;
228                }
229                self.manager.finish(&self.task.id, active).await;
230            }
231            self.armed = false;
232        }
233    }
234}
235
236async fn finish_cancel(
237    manager: Arc<ExecutionManager>,
238    active: Option<Arc<ActiveExecution>>,
239    task: Task,
240) {
241    let active = match active {
242        Some(active) => Some(active),
243        None => manager.get(&task.id).await,
244    };
245    if let Some(active) = active {
246        active
247            .publish(Ok(&status_update(&task)), Some(task.clone()))
248            .await;
249        manager.finish(&task.id, &active).await;
250    }
251}
252
253impl Drop for FinishCancelOnDrop {
254    fn drop(&mut self) {
255        if self.armed {
256            let manager = self.manager.clone();
257            let active = self.active.take();
258            let task = self.task.clone();
259            if let Some(runtime) = &self.runtime {
260                runtime.spawn(finish_cancel(manager, active, task));
261            }
262        }
263    }
264}
265
266/// A subscription that `ExecutionManager::start` attaches to the task's next
267/// execution. Dropped first, it leaves nothing behind in the registry.
268struct Waiter {
269    manager: Arc<ExecutionManager>,
270    task_id: TaskId,
271    attached: Option<oneshot::Receiver<Resubscription>>,
272}
273
274impl Waiter {
275    /// The execution attached so far, if any.
276    fn attached(&mut self) -> Option<Resubscription> {
277        self.attached.as_mut()?.try_recv().ok()
278    }
279
280    /// The events of the execution once attached; none if the handler goes
281    /// away first.
282    fn into_stream(mut self) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
283        stream::once(async move { self.attached.as_mut()?.await.ok() })
284            .filter_map(future::ready)
285            .flat_map(|(receiver, snapshot_task, sequence)| {
286                subscription_stream(receiver, snapshot_task, sequence)
287            })
288            .boxed()
289    }
290}
291
292impl Drop for Waiter {
293    fn drop(&mut self) {
294        // Closing the receiver is what marks this waiter's own sender closed.
295        self.attached = None;
296        let mut waiting = self.manager.waiting();
297        if let Some(waiters) = waiting.get_mut(&self.task_id) {
298            waiters.retain(|waiter| !waiter.is_closed());
299            if waiters.is_empty() {
300                waiting.remove(&self.task_id);
301            }
302        }
303    }
304}
305
306struct ExecutionRuntime {
307    executor: Arc<dyn crate::AgentExecutor>,
308    task_store: Arc<dyn crate::TaskStore>,
309    push_config_store: Option<Arc<dyn crate::PushConfigStore>>,
310    push_sender: Option<Arc<crate::HttpPushSender>>,
311    execution_manager: Arc<ExecutionManager>,
312}
313
314struct SubscriptionState {
315    receiver: broadcast::Receiver<ExecutionEvent>,
316    snapshot_task: Option<Task>,
317    min_sequence: u64,
318    done: bool,
319}
320
321fn is_terminal_event(event: &StreamResponse) -> bool {
322    match event {
323        StreamResponse::Task(task) => task.status.state.is_terminal(),
324        StreamResponse::StatusUpdate(update) => update.status.state.is_terminal(),
325        _ => false,
326    }
327}
328
329fn task_id_for_event(event: &StreamResponse) -> Option<&str> {
330    match event {
331        StreamResponse::Task(task) => Some(&task.id),
332        StreamResponse::StatusUpdate(update) => Some(&update.task_id),
333        StreamResponse::ArtifactUpdate(update) => Some(&update.task_id),
334        StreamResponse::Message(_) => None,
335    }
336}
337
338fn should_interrupt_non_streaming(
339    req: &SendMessageRequest,
340    event: &StreamResponse,
341) -> Option<TaskId> {
342    if req
343        .configuration
344        .as_ref()
345        .and_then(|config| config.return_immediately)
346        .unwrap_or(false)
347    {
348        return match event {
349            StreamResponse::Message(_) => None,
350            _ => task_id_for_event(event).map(ToOwned::to_owned),
351        };
352    }
353
354    match event {
355        StreamResponse::Task(task) if task.status.state == TaskState::AuthRequired => {
356            Some(task.id.clone())
357        }
358        StreamResponse::StatusUpdate(update) if update.status.state == TaskState::AuthRequired => {
359            Some(update.task_id.clone())
360        }
361        _ => None,
362    }
363}
364
365async fn send_push_notifications(
366    task_id: &str,
367    push_config_store: Option<&dyn crate::PushConfigStore>,
368    push_sender: Option<&crate::HttpPushSender>,
369    event: &StreamResponse,
370) -> Result<(), A2AError> {
371    let Some(push_config_store) = push_config_store else {
372        return Ok(());
373    };
374    let Some(push_sender) = push_sender else {
375        return Ok(());
376    };
377
378    let configs = push_config_store.list(task_id).await?;
379    for config in configs {
380        push_sender.send_push(&config, event.clone()).await?;
381    }
382
383    Ok(())
384}
385
386async fn save_task(task_store: &dyn crate::TaskStore, mut task: Task) -> Result<Task, A2AError> {
387    // DM-SERIAL-001: a persisted/returned task status must carry a timestamp.
388    // This is the single persistence chokepoint for executor events, so
389    // backfilling here covers the task-snapshot and status-update paths
390    // alike, while preserving any timestamp the executor already supplied.
391    if task.status.timestamp.is_none() {
392        task.status.timestamp = Some(chrono::Utc::now());
393    }
394    match task_store.update(task.clone()).await {
395        Ok(_) => Ok(task),
396        Err(error) if error.code == error_code::TASK_NOT_FOUND => {
397            task_store.create(task.clone()).await?;
398            Ok(task)
399        }
400        Err(error) => Err(error),
401    }
402}
403
404/// DM-SERIAL-001: backfills a missing status timestamp on the event itself,
405/// before it is both persisted (via `apply_event_to_task`/`save_task`) and
406/// broadcast to any live subscriber -- `save_task`'s own backfill only
407/// covers what gets persisted; a subscriber watching `send_streaming_message`
408/// or `subscribe_to_task` receives the broadcast event directly, never a
409/// reload from the store, so backfilling only at persistence time still
410/// leaves a live subscriber seeing a timestamp-less status.
411fn backfill_status_timestamp(event: &mut StreamResponse) {
412    let status = match event {
413        StreamResponse::Task(task) => &mut task.status,
414        StreamResponse::StatusUpdate(update) => &mut update.status,
415        StreamResponse::ArtifactUpdate(_) | StreamResponse::Message(_) => return,
416    };
417    if status.timestamp.is_none() {
418        status.timestamp = Some(chrono::Utc::now());
419    }
420}
421
422async fn apply_event_to_task(
423    task_store: &dyn crate::TaskStore,
424    current_task: Option<Task>,
425    event: &StreamResponse,
426) -> Result<Option<Task>, A2AError> {
427    match event {
428        StreamResponse::Task(task) => save_task(task_store, task.clone()).await.map(Some),
429        StreamResponse::StatusUpdate(update) => {
430            let mut task = match current_task {
431                Some(task) => task,
432                None => task_store
433                    .get(&update.task_id)
434                    .await?
435                    .ok_or_else(|| A2AError::task_not_found(&update.task_id))?,
436            };
437            task.status = update.status.clone();
438            save_task(task_store, task).await.map(Some)
439        }
440        StreamResponse::ArtifactUpdate(update) => {
441            let mut task = match current_task {
442                Some(task) => task,
443                None => task_store
444                    .get(&update.task_id)
445                    .await?
446                    .ok_or_else(|| A2AError::task_not_found(&update.task_id))?,
447            };
448            let artifacts = task.artifacts.get_or_insert_with(Vec::new);
449            let existing = artifacts
450                .iter_mut()
451                .find(|artifact| artifact.artifact_id == update.artifact.artifact_id);
452            if update.append.unwrap_or(false) {
453                let artifact = existing.ok_or_else(A2AError::invalid_agent_response)?;
454                artifact.parts.extend(update.artifact.parts.iter().cloned());
455                if let Some(metadata) = &update.artifact.metadata {
456                    artifact
457                        .metadata
458                        .get_or_insert_with(Default::default)
459                        .extend(metadata.clone());
460                }
461            } else if let Some(artifact) = existing {
462                *artifact = update.artifact.clone();
463            } else {
464                artifacts.push(update.artifact.clone());
465            }
466            save_task(task_store, task).await.map(Some)
467        }
468        StreamResponse::Message(_) => Ok(current_task),
469    }
470}
471
472/// The task an execution that failed midway leaves behind: FAILED, so a
473/// caller polling `GetTask` or listing tasks sees it end. The status message
474/// is the sanitized error; the error itself still reaches the live
475/// subscribers. A task already terminal (canceled meanwhile) is left alone.
476///
477/// The FAILED state is pushed to the task's webhooks (§4.3.3); a failed push
478/// is dropped, as the task is already FAILED.
479async fn fail_task(
480    runtime: &ExecutionRuntime,
481    task: Option<Task>,
482    error: &A2AError,
483) -> Option<Task> {
484    let mut task = task.filter(|task| !task.status.state.is_terminal())?;
485    let text = crate::sanitized_internal_error(&error.message).message;
486    task.status = TaskStatus {
487        state: TaskState::Failed,
488        message: Some(Message {
489            task_id: Some(task.id.clone()),
490            context_id: Some(task.context_id.clone()),
491            ..Message::new(Role::Agent, vec![Part::text(text)])
492        }),
493        timestamp: Some(chrono::Utc::now()),
494    };
495    let task = save_task(runtime.task_store.as_ref(), task).await.ok()?;
496    let _ = send_push_notifications(
497        &task.id,
498        runtime.push_config_store.as_deref(),
499        runtime.push_sender.as_deref(),
500        &status_update(&task),
501    )
502    .await;
503    Some(task)
504}
505
506/// The status update that delivers a task's current status: the shape a
507/// transition the handler commits itself (FAILED on an execution error,
508/// CANCELED on `begin_cancel`) is pushed in, like one the executor emits.
509fn status_update(task: &Task) -> StreamResponse {
510    StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
511        task_id: task.id.clone(),
512        context_id: task.context_id.clone(),
513        status: task.status.clone(),
514        metadata: None,
515    })
516}
517
518fn subscription_stream(
519    receiver: broadcast::Receiver<ExecutionEvent>,
520    snapshot_task: Option<Task>,
521    min_sequence: u64,
522) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
523    Box::pin(futures::stream::unfold(
524        SubscriptionState {
525            receiver,
526            snapshot_task,
527            min_sequence,
528            done: false,
529        },
530        |mut state| async move {
531            if state.done {
532                return None;
533            }
534
535            if let Some(task) = state.snapshot_task.take() {
536                if task.status.state.is_terminal() {
537                    state.done = true;
538                }
539                return Some((Ok(StreamResponse::Task(task)), state));
540            }
541
542            loop {
543                match state.receiver.recv().await {
544                    Ok(event) if event.sequence <= state.min_sequence => continue,
545                    Ok(event) => {
546                        state.min_sequence = event.sequence;
547                        match &event.result {
548                            Ok(item) if is_terminal_event(item) => state.done = true,
549                            // §3.1.2: a Message answer is "exactly one Message
550                            // object and then close immediately". Nothing may
551                            // follow an answering Message on that execution, so
552                            // attached and waiting subscriptions (§3.1.6), which
553                            // follow the same execution, end at the Message too,
554                            // and a pending cancellation's later items do not
555                            // follow it.
556                            Ok(StreamResponse::Message(_)) | Err(_) => state.done = true,
557                            _ => {}
558                        }
559                        return Some((event.result.clone(), state));
560                    }
561                    Err(broadcast::error::RecvError::Lagged(_)) => {
562                        state.done = true;
563                        return Some((
564                            Err(crate::sanitized_internal_error(
565                                "subscription fell behind active execution",
566                            )),
567                            state,
568                        ));
569                    }
570                    Err(broadcast::error::RecvError::Closed) => return None,
571                }
572            }
573        },
574    ))
575}
576
577async fn drive_execution(
578    runtime: ExecutionRuntime,
579    task_id: TaskId,
580    active: Arc<ActiveExecution>,
581    exec_ctx: crate::ExecutorContext,
582) {
583    let mut current_task = {
584        let state = active.state.read().await;
585        state.snapshot_task.clone()
586    };
587    let mut stream = runtime.executor.execute(exec_ctx);
588    let mut failure = None;
589    // §3.1.2: a response is one Message, or a Task and its updates, not both.
590    let (mut answered, mut tracked) = (false, false);
591
592    while let Some(result) = stream.next().await {
593        if active.snapshot_is_terminal().await {
594            break;
595        }
596
597        match result {
598            Ok(mut event) => {
599                let message = matches!(event, StreamResponse::Message(_));
600                if answered || (message && tracked) {
601                    failure = Some(A2AError::invalid_agent_response());
602                    break;
603                }
604                answered = message;
605                tracked |= !message;
606                backfill_status_timestamp(&mut event);
607                match apply_event_to_task(runtime.task_store.as_ref(), current_task.clone(), &event)
608                    .await
609                {
610                    Ok(updated_task) => {
611                        current_task = updated_task.clone();
612                        if let Err(error) = send_push_notifications(
613                            &task_id,
614                            runtime.push_config_store.as_deref(),
615                            runtime.push_sender.as_deref(),
616                            &event,
617                        )
618                        .await
619                        {
620                            failure = Some(error);
621                            break;
622                        }
623                        active.publish(Ok(&event), updated_task).await;
624                        if is_terminal_event(&event) {
625                            break;
626                        }
627                    }
628                    Err(error) => {
629                        failure = Some(error);
630                        break;
631                    }
632                }
633            }
634            Err(error) => {
635                failure = Some(error);
636                break;
637            }
638        }
639    }
640
641    if let Some(error) = failure {
642        let failed = fail_task(&runtime, current_task, &error).await;
643        active.publish(Err(&error), failed).await;
644    }
645
646    runtime.execution_manager.finish(&task_id, &active).await;
647}
648
649/// Transport-agnostic request handler interface.
650///
651/// This is the core interface consumed by all protocol bindings
652/// (JSON-RPC, REST, gRPC). The [`DefaultRequestHandler`] provides a
653/// standard implementation that orchestrates task lifecycle, storage,
654/// and executor dispatch.
655#[async_trait]
656pub trait RequestHandler: Send + Sync + 'static {
657    async fn send_message(
658        &self,
659        params: &ServiceParams,
660        req: SendMessageRequest,
661    ) -> Result<SendMessageResponse, A2AError>;
662
663    async fn send_streaming_message(
664        &self,
665        params: &ServiceParams,
666        req: SendMessageRequest,
667    ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError>;
668
669    async fn get_task(&self, params: &ServiceParams, req: GetTaskRequest)
670    -> Result<Task, A2AError>;
671
672    async fn list_tasks(
673        &self,
674        params: &ServiceParams,
675        req: ListTasksRequest,
676    ) -> Result<ListTasksResponse, A2AError>;
677
678    async fn cancel_task(
679        &self,
680        params: &ServiceParams,
681        req: CancelTaskRequest,
682    ) -> Result<Task, A2AError>;
683
684    async fn subscribe_to_task(
685        &self,
686        params: &ServiceParams,
687        req: SubscribeToTaskRequest,
688    ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError>;
689
690    async fn create_push_config(
691        &self,
692        params: &ServiceParams,
693        req: TaskPushNotificationConfig,
694    ) -> Result<TaskPushNotificationConfig, A2AError>;
695
696    async fn get_push_config(
697        &self,
698        params: &ServiceParams,
699        req: GetTaskPushNotificationConfigRequest,
700    ) -> Result<TaskPushNotificationConfig, A2AError>;
701
702    async fn list_push_configs(
703        &self,
704        params: &ServiceParams,
705        req: ListTaskPushNotificationConfigsRequest,
706    ) -> Result<ListTaskPushNotificationConfigsResponse, A2AError>;
707
708    async fn delete_push_config(
709        &self,
710        params: &ServiceParams,
711        req: DeleteTaskPushNotificationConfigRequest,
712    ) -> Result<(), A2AError>;
713
714    async fn get_extended_agent_card(
715        &self,
716        params: &ServiceParams,
717        req: GetExtendedAgentCardRequest,
718    ) -> Result<AgentCard, A2AError>;
719}
720
721/// Decides whether a request may proceed.
722///
723/// The handler never treats a non-empty header as a principal. An
724/// implementation must validate whatever credential it accepts (token, DID,
725/// session) and return [`A2AError`] when that check fails. `task_id` is set
726/// when the method addresses one task and is reserved for owner checks.
727pub trait RequestAuthorizer: Send + Sync {
728    fn authorize(&self, params: &ServiceParams, task_id: Option<&str>) -> Result<(), A2AError>;
729}
730
731impl<F> RequestAuthorizer for F
732where
733    F: Fn(&ServiceParams, Option<&str>) -> Result<(), A2AError> + Send + Sync,
734{
735    fn authorize(&self, params: &ServiceParams, task_id: Option<&str>) -> Result<(), A2AError> {
736        self(params, task_id)
737    }
738}
739
740/// Default implementation of [`RequestHandler`] that orchestrates
741/// task lifecycle management, storage, and executor dispatch.
742pub struct DefaultRequestHandler {
743    executor: Arc<dyn crate::AgentExecutor>,
744    task_store: Arc<dyn crate::TaskStore>,
745    execution_manager: Arc<ExecutionManager>,
746    push_config_store: Option<Arc<dyn crate::PushConfigStore>>,
747    push_sender: Option<Arc<crate::HttpPushSender>>,
748    capabilities: AgentCapabilities,
749    default_input_modes: Vec<String>,
750    authorizer: Option<Arc<dyn RequestAuthorizer>>,
751    extended_agent_card: Option<Arc<dyn ExtendedAgentCardResolver>>,
752}
753
754/// Supplies the authenticated extended Agent Card (§12.4, §10.1).
755///
756/// A resolver rather than a stored card because §12.4 has the extended card
757/// fetched *under a security scheme*: which skills an agent reveals can
758/// legitimately differ by caller, and `ServiceParams` is where the caller's
759/// credentials arrive. An agent serving one card to everyone can ignore the
760/// argument — [`DefaultRequestHandler::with_extended_agent_card`] wraps a
761/// plain card for exactly that case.
762pub trait ExtendedAgentCardResolver: Send + Sync {
763    fn resolve(&self, params: &ServiceParams) -> Result<AgentCard, A2AError>;
764}
765
766impl<F> ExtendedAgentCardResolver for F
767where
768    F: Fn(&ServiceParams) -> Result<AgentCard, A2AError> + Send + Sync,
769{
770    fn resolve(&self, params: &ServiceParams) -> Result<AgentCard, A2AError> {
771        self(params)
772    }
773}
774
775impl DefaultRequestHandler {
776    pub fn new(executor: impl crate::AgentExecutor, task_store: impl crate::TaskStore) -> Self {
777        DefaultRequestHandler {
778            executor: Arc::new(executor),
779            task_store: Arc::new(task_store),
780            execution_manager: Arc::new(ExecutionManager::default()),
781            push_config_store: None,
782            push_sender: None,
783            capabilities: AgentCapabilities::default(),
784            default_input_modes: Vec::new(),
785            authorizer: None,
786            extended_agent_card: None,
787        }
788    }
789
790    /// Serve `card` as the extended Agent Card, identically for every caller.
791    ///
792    /// Also declares the `extendedAgentCard` capability, since serving one
793    /// and advertising it should not be two separate things to remember —
794    /// an explicit `with_capabilities(..)` still overrides it either way.
795    pub fn with_extended_agent_card(mut self, card: AgentCard) -> Self {
796        self.capabilities.extended_agent_card.get_or_insert(true);
797        self.with_extended_agent_card_resolver(move |_: &ServiceParams| Ok(card.clone()))
798    }
799
800    /// Serve an extended Agent Card computed per caller, so an agent can
801    /// reveal different skills to different principals (§12.4).
802    pub fn with_extended_agent_card_resolver(
803        mut self,
804        resolver: impl ExtendedAgentCardResolver + 'static,
805    ) -> Self {
806        self.capabilities.extended_agent_card.get_or_insert(true);
807        self.extended_agent_card = Some(Arc::new(resolver));
808        self
809    }
810
811    /// Install an authorizer. The default handler does not enforce one.
812    pub fn with_authorizer(mut self, authorizer: impl RequestAuthorizer + 'static) -> Self {
813        self.authorizer = Some(Arc::new(authorizer));
814        self
815    }
816
817    fn authorize(&self, params: &ServiceParams, task_id: Option<&str>) -> Result<(), A2AError> {
818        self.require_extensions(params)?;
819        match &self.authorizer {
820            Some(authorizer) => authorizer.authorize(params, task_id),
821            None => Ok(()),
822        }
823    }
824
825    /// §3.3.4: a request that does not activate every extension the card
826    /// marks `required` is refused. Activation is the `A2A-Extensions`
827    /// service parameter, comma-separated or repeated (§9.2, §10.2, §11.2).
828    fn require_extensions(&self, params: &ServiceParams) -> Result<(), A2AError> {
829        let Some(extensions) = &self.capabilities.extensions else {
830            return Ok(());
831        };
832        let activated: Vec<&str> = params
833            .get(&SVC_PARAM_EXTENSIONS.to_ascii_lowercase())
834            .into_iter()
835            .flatten()
836            .flat_map(|value| value.split(','))
837            .map(str::trim)
838            .collect();
839        match extensions
840            .iter()
841            .find(|ext| ext.required == Some(true) && !activated.contains(&ext.uri.as_str()))
842        {
843            Some(missing) => Err(A2AError::extension_support_required(&missing.uri)),
844            None => Ok(()),
845        }
846    }
847
848    pub fn with_push_config_store(
849        mut self,
850        push_config_store: impl crate::PushConfigStore,
851    ) -> Self {
852        self.push_sender = Some(Arc::new(crate::HttpPushSender::new(None)));
853        self.push_config_store = Some(Arc::new(push_config_store));
854        // Only a default: an explicit `Some(false)` from `with_capabilities`
855        // stands, so the result no longer depends on which builder method was
856        // called last.
857        self.capabilities.push_notifications.get_or_insert(true);
858        self
859    }
860
861    pub fn with_push_notifications(
862        mut self,
863        push_config_store: impl crate::PushConfigStore,
864        push_sender: crate::HttpPushSender,
865    ) -> Self {
866        self.push_config_store = Some(Arc::new(push_config_store));
867        self.push_sender = Some(Arc::new(push_sender));
868        self.capabilities.push_notifications.get_or_insert(true);
869        self
870    }
871
872    pub fn with_capabilities(mut self, capabilities: AgentCapabilities) -> Self {
873        self.capabilities = capabilities;
874        self
875    }
876
877    /// Declares the media types incoming message parts may use (§5.1's
878    /// `defaultInputModes`). Empty (the default) means unrestricted, so
879    /// embedders that never call this see no change in behavior.
880    pub fn with_default_input_modes(mut self, modes: impl Into<Vec<String>>) -> Self {
881        self.default_input_modes = modes.into();
882        self
883    }
884
885    /// A part with a declared, non-empty media type that isn't among the
886    /// advertised `defaultInputModes` is rejected; a part that declares none
887    /// is unrestricted, and so is every part when no modes were declared.
888    fn validate_content_types(&self, message: &Message) -> Result<(), A2AError> {
889        if self.default_input_modes.is_empty() {
890            return Ok(());
891        }
892        let supported = message.parts.iter().all(|part| {
893            part.media_type.as_deref().is_none_or(|media_type| {
894                media_type.is_empty() || self.default_input_modes.iter().any(|m| m == media_type)
895            })
896        });
897        if supported {
898            Ok(())
899        } else {
900            Err(A2AError::content_type_not_supported())
901        }
902    }
903
904    /// §13.3: refuse a capability-gated operation the card does not declare.
905    ///
906    /// `None` means "not restricted", not "refused". `AgentCapabilities::
907    /// default()` leaves every field `None` and most embedders never call
908    /// [`Self::with_capabilities`], so treating `None` as a refusal would
909    /// break all of them at once. Only an explicit `Some(false)` refuses.
910    fn require_capability(
911        declared: Option<bool>,
912        unsupported: impl FnOnce() -> A2AError,
913    ) -> Result<(), A2AError> {
914        match declared {
915            Some(false) => Err(unsupported()),
916            _ => Ok(()),
917        }
918    }
919
920    fn require_streaming(&self) -> Result<(), A2AError> {
921        Self::require_capability(self.capabilities.streaming, || {
922            A2AError::unsupported_operation("the agent card does not declare streaming")
923        })
924    }
925
926    fn require_push_notifications(&self) -> Result<(), A2AError> {
927        Self::require_capability(
928            self.capabilities.push_notifications,
929            A2AError::push_notification_not_supported,
930        )
931    }
932
933    /// The push-config store, refusing first when the card declares that the
934    /// agent does not support push notifications (§13.3). Distinct from
935    /// [`Self::push_config_store`], which reports the *deployment* state — a
936    /// store that was never supplied — with the same error code.
937    fn push_config_store_checked(&self) -> Result<&dyn crate::PushConfigStore, A2AError> {
938        self.require_push_notifications()?;
939        self.push_config_store()
940    }
941
942    fn push_config_store(&self) -> Result<&dyn crate::PushConfigStore, A2AError> {
943        self.push_config_store
944            .as_deref()
945            .ok_or_else(A2AError::push_notification_not_supported)
946    }
947
948    async fn load_task(&self, task_id: &str) -> Result<Task, A2AError> {
949        self.task_store
950            .get(task_id)
951            .await?
952            .ok_or_else(|| A2AError::task_not_found(task_id))
953    }
954
955    async fn prepare_task_for_execution(
956        &self,
957        req: &SendMessageRequest,
958    ) -> Result<(Task, Option<Task>, String), A2AError> {
959        // A2A §3.4.2: a client-provided taskId MUST reference an existing task,
960        // and client-provided ids for *creating* tasks are not supported. Only
961        // an absent taskId may mint a new one.
962        let task_id = match req.message.task_id.clone() {
963            Some(id) => id,
964            None => new_task_id(),
965        };
966        let stored = self.task_store.get(&task_id).await?;
967        if stored.is_none() && req.message.task_id.is_some() {
968            return Err(A2AError::task_not_found(&task_id));
969        }
970        if stored
971            .as_ref()
972            .is_some_and(|task| task.status.state.is_terminal())
973        {
974            return Err(A2AError::unsupported_operation(format!(
975                "task {task_id} has already reached a terminal state"
976            )));
977        }
978
979        // A2A §3.4.3: reject a mismatching contextId/taskId pair, and infer
980        // contextId from the task when only taskId is given.
981        let context_id = match stored.as_ref() {
982            Some(task) => {
983                if let Some(requested) = req.message.context_id.as_deref() {
984                    if requested != task.context_id {
985                        return Err(A2AError::invalid_params(format!(
986                            "contextId {requested} does not match task {task_id}, \
987                             which belongs to context {}",
988                            task.context_id
989                        )));
990                    }
991                }
992                task.context_id.clone()
993            }
994            None => req
995                .message
996                .context_id
997                .clone()
998                .unwrap_or_else(new_context_id),
999        };
1000
1001        let task = if let Some(mut existing) = stored.clone() {
1002            // A continuation turn's own incoming message was never otherwise
1003            // recorded anywhere: the executor only sees it via `ctx.message`
1004            // for deciding this turn's behavior, and `apply_event_to_task`
1005            // only ever merges status/artifact deltas onto the snapshot
1006            // started here, never anything content-derived. Append it so
1007            // `history` actually accumulates across turns. The agent's last
1008            // word (an INPUT_REQUIRED question) lives only in `status.message`
1009            // and the next status replaces it, so it goes in first.
1010            let asked = existing.status.message.clone();
1011            let history = existing.history.get_or_insert_with(Vec::new);
1012            if let Some(asked) = asked.filter(|asked| {
1013                history
1014                    .iter()
1015                    .all(|seen| seen.message_id != asked.message_id)
1016            }) {
1017                history.push(asked);
1018            }
1019            history.push(req.message.clone());
1020            existing
1021        } else {
1022            let task = Task {
1023                id: task_id,
1024                context_id: context_id.clone(),
1025                status: TaskStatus {
1026                    state: TaskState::Submitted,
1027                    message: None,
1028                    timestamp: Some(chrono::Utc::now()),
1029                },
1030                artifacts: None,
1031                history: Some(vec![req.message.clone()]),
1032                metadata: None,
1033            };
1034            self.task_store.create(task.clone()).await?;
1035            task
1036        };
1037
1038        Ok((task, stored, context_id))
1039    }
1040
1041    async fn save_request_push_config(
1042        &self,
1043        task_id: &str,
1044        req: &SendMessageRequest,
1045    ) -> Result<(), A2AError> {
1046        let Some(config) = req
1047            .configuration
1048            .as_ref()
1049            .and_then(|configuration| configuration.task_push_notification_config.clone())
1050        else {
1051            return Ok(());
1052        };
1053
1054        let mut config = config;
1055        config.task_id = task_id.to_string();
1056        if config.tenant.is_none() {
1057            config.tenant = req.tenant.clone();
1058        }
1059        self.push_config_store_checked()?.save(config).await?;
1060        Ok(())
1061    }
1062
1063    async fn start_execution(
1064        &self,
1065        params: &ServiceParams,
1066        req: SendMessageRequest,
1067        include_task_snapshot_in_context: bool,
1068    ) -> Result<(TaskId, BoxStream<'static, Result<StreamResponse, A2AError>>), A2AError> {
1069        if req.message.role != Role::User {
1070            let received = match req.message.role {
1071                Role::Agent => "ROLE_AGENT",
1072                Role::Unspecified => "ROLE_UNSPECIFIED",
1073                Role::User => "ROLE_USER",
1074            };
1075            return Err(A2AError::invalid_params(format!(
1076                "client messages must have role ROLE_USER, got decoded role {received}"
1077            )));
1078        }
1079        self.validate_content_types(&req.message)?;
1080        let (task, stored_task, context_id) = self.prepare_task_for_execution(&req).await?;
1081        let task_id = task.id.clone();
1082        self.save_request_push_config(&task_id, &req).await?;
1083        let active = self.execution_manager.start(task.clone()).await?;
1084        let receiver = active.subscribe();
1085
1086        let exec_ctx = crate::ExecutorContext {
1087            message: Some(req.message),
1088            task_id: task_id.clone(),
1089            stored_task: if include_task_snapshot_in_context {
1090                Some(task.clone())
1091            } else {
1092                stored_task
1093            },
1094            context_id,
1095            metadata: req.metadata,
1096            user: None,
1097            service_params: params.clone(),
1098            tenant: req.tenant,
1099        };
1100
1101        let runtime = ExecutionRuntime {
1102            executor: Arc::clone(&self.executor),
1103            task_store: Arc::clone(&self.task_store),
1104            push_config_store: self.push_config_store.clone(),
1105            push_sender: self.push_sender.clone(),
1106            execution_manager: Arc::clone(&self.execution_manager),
1107        };
1108        let active_execution = active.clone();
1109        let execution_task_id = task_id.clone();
1110
1111        tokio::spawn(async move {
1112            drive_execution(runtime, execution_task_id, active_execution, exec_ctx).await;
1113        });
1114
1115        Ok((task_id, subscription_stream(receiver, None, 0)))
1116    }
1117}
1118
1119#[async_trait]
1120impl RequestHandler for DefaultRequestHandler {
1121    async fn send_message(
1122        &self,
1123        params: &ServiceParams,
1124        req: SendMessageRequest,
1125    ) -> Result<SendMessageResponse, A2AError> {
1126        self.authorize(params, req.message.task_id.as_deref())?;
1127        // ACTS CORE-HIST-003: configuration.historyLength governs this
1128        // response's own inline task the same way it governs a later
1129        // GetTask, so it has to be applied here too, not just there.
1130        let history_length = req
1131            .configuration
1132            .as_ref()
1133            .and_then(|configuration| configuration.history_length);
1134        let (task_id, mut stream) = self.start_execution(params, req.clone(), true).await?;
1135        let mut last_event = None;
1136
1137        while let Some(item) = stream.next().await {
1138            let event = item?;
1139
1140            if let Some(interrupt_task_id) = should_interrupt_non_streaming(&req, &event) {
1141                let mut task = self.load_task(&interrupt_task_id).await?;
1142                apply_history_length(&mut task, history_length);
1143                return Ok(SendMessageResponse::Task(task));
1144            }
1145
1146            match event {
1147                StreamResponse::Message(message) => {
1148                    return Ok(SendMessageResponse::Message(message));
1149                }
1150                other => last_event = Some(other),
1151            }
1152        }
1153
1154        match last_event {
1155            Some(StreamResponse::Task(mut task)) => {
1156                apply_history_length(&mut task, history_length);
1157                Ok(SendMessageResponse::Task(task))
1158            }
1159            Some(StreamResponse::StatusUpdate(update)) => {
1160                let mut task = self.load_task(&update.task_id).await?;
1161                apply_history_length(&mut task, history_length);
1162                Ok(SendMessageResponse::Task(task))
1163            }
1164            Some(StreamResponse::ArtifactUpdate(update)) => {
1165                let mut task = self.load_task(&update.task_id).await?;
1166                apply_history_length(&mut task, history_length);
1167                Ok(SendMessageResponse::Task(task))
1168            }
1169            Some(StreamResponse::Message(message)) => Ok(SendMessageResponse::Message(message)),
1170            None => {
1171                let mut task = self.load_task(&task_id).await?;
1172                apply_history_length(&mut task, history_length);
1173                Ok(SendMessageResponse::Task(task))
1174            }
1175        }
1176    }
1177
1178    async fn send_streaming_message(
1179        &self,
1180        params: &ServiceParams,
1181        req: SendMessageRequest,
1182    ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError> {
1183        self.authorize(params, req.message.task_id.as_deref())?;
1184        self.require_streaming()?;
1185        // The history cap binds every Task in the response, streamed ones too.
1186        let history_length = req
1187            .configuration
1188            .as_ref()
1189            .and_then(|configuration| configuration.history_length);
1190        let (_, stream) = self.start_execution(params, req, false).await?;
1191        Ok(Box::pin(stream.map(move |item| {
1192            item.map(|mut event| {
1193                if let StreamResponse::Task(task) = &mut event {
1194                    apply_history_length(task, history_length);
1195                }
1196                event
1197            })
1198        })))
1199    }
1200
1201    async fn get_task(
1202        &self,
1203        params: &ServiceParams,
1204        req: GetTaskRequest,
1205    ) -> Result<Task, A2AError> {
1206        self.authorize(params, Some(&req.id))?;
1207        let mut task = self
1208            .task_store
1209            .get(&req.id)
1210            .await?
1211            .ok_or_else(|| A2AError::task_not_found(&req.id))?;
1212        apply_history_length(&mut task, req.history_length);
1213        Ok(task)
1214    }
1215
1216    /// Bounds the page twice, and neither is redundant: `TaskStore` is a
1217    /// public trait.
1218    ///
1219    /// Clamping `page_size` before the call bounds a store that honours it
1220    /// -- the ordinary case, and the one that turns `pageSize=999999999`
1221    /// into a real query. Truncating the response bounds a store that
1222    /// ignores it, which cannot be detected from here.
1223    ///
1224    /// On truncation the store's `next_page_token` is left alone: paging is
1225    /// the store's own scheme (the in-tree stores use offsets, another may
1226    /// use an opaque cursor) so no correct token can be synthesised. See
1227    /// [`TaskStore::list`](crate::TaskStore::list).
1228    async fn list_tasks(
1229        &self,
1230        params: &ServiceParams,
1231        req: ListTasksRequest,
1232    ) -> Result<ListTasksResponse, A2AError> {
1233        self.authorize(params, None)?;
1234        let page_size = resolve_page_size(req.page_size);
1235        let req = ListTasksRequest {
1236            page_size: Some(page_size as i32),
1237            ..req
1238        };
1239        let mut response = self.task_store.list(&req).await?;
1240        response.tasks.truncate(page_size);
1241        for task in &mut response.tasks {
1242            apply_history_length(task, req.history_length);
1243            // §3.1.4: artifacts are omitted unless the caller asks for them.
1244            if req.include_artifacts != Some(true) {
1245                task.artifacts = None;
1246            }
1247        }
1248        Ok(response)
1249    }
1250
1251    async fn cancel_task(
1252        &self,
1253        params: &ServiceParams,
1254        req: CancelTaskRequest,
1255    ) -> Result<Task, A2AError> {
1256        self.authorize(params, Some(&req.id))?;
1257        let task = self.load_task(&req.id).await?;
1258
1259        // Idempotent: re-cancelling an already-canceled task is a no-op that
1260        // returns the current task (matching a2a-go). Other terminal states
1261        // are still not cancelable, per A2A and a2a-cli SPEC.md §10.4.
1262        if task.status.state == TaskState::Canceled {
1263            return Ok(task);
1264        }
1265        if task.status.state.is_terminal() {
1266            return Err(A2AError::task_not_cancelable(&req.id));
1267        }
1268
1269        // Atomically transition the task to CANCELED so two concurrent cancel
1270        // requests cannot both pass the check-then-act window.
1271        let task = match self.task_store.begin_cancel(&req.id).await {
1272            Ok(task) => task,
1273            Err(error) if error.code == error_code::TASK_NOT_CANCELABLE => {
1274                // Raced with another cancel or with task completion. Keep the
1275                // same semantics as the upfront check: a task another cancel
1276                // already moved to CANCELED is returned (idempotent); any
1277                // other terminal state is still not cancelable.
1278                let raced = self.load_task(&req.id).await?;
1279                if raced.status.state == TaskState::Canceled {
1280                    return Ok(raced);
1281                }
1282                return Err(error);
1283            }
1284            Err(error) => return Err(error),
1285        };
1286
1287        // The task is canceled in the store from here on, however the rest of
1288        // this ends, so no subscription may stay waiting for its next turn.
1289        let _release = ReleaseOnDrop {
1290            manager: &self.execution_manager,
1291            task: task.clone(),
1292        };
1293
1294        let mut finish_cancel_guard = FinishCancelOnDrop {
1295            manager: Arc::clone(&self.execution_manager),
1296            active: None,
1297            task: task.clone(),
1298            armed: true,
1299            runtime: tokio::runtime::Handle::try_current().ok(),
1300        };
1301        let active_execution = self.execution_manager.get(&req.id).await;
1302        finish_cancel_guard.active = active_execution.clone();
1303
1304        let exec_ctx = crate::ExecutorContext {
1305            message: None,
1306            task_id: req.id.clone(),
1307            stored_task: Some(task.clone()),
1308            context_id: task.context_id.clone(),
1309            metadata: req.metadata,
1310            user: None,
1311            service_params: params.clone(),
1312            tenant: req.tenant,
1313        };
1314
1315        let mut stream = self.executor.cancel(exec_ctx);
1316        let mut current_task = Some(task);
1317        let mut terminal_pushed = false;
1318
1319        while let Some(event) = stream.next().await {
1320            match event {
1321                Ok(mut event) => {
1322                    backfill_status_timestamp(&mut event);
1323                    let updated_task = match apply_event_to_task(
1324                        self.task_store.as_ref(),
1325                        current_task.clone(),
1326                        &event,
1327                    )
1328                    .await
1329                    {
1330                        Ok(task) => task,
1331                        Err(error) => {
1332                            finish_cancel_guard.finish(true).await;
1333                            return Err(error);
1334                        }
1335                    };
1336                    current_task = updated_task.clone();
1337
1338                    if let Err(error) = send_push_notifications(
1339                        &req.id,
1340                        self.push_config_store.as_deref(),
1341                        self.push_sender.as_deref(),
1342                        &event,
1343                    )
1344                    .await
1345                    {
1346                        // The push error belongs to this caller. Subscribers
1347                        // instead receive the already-committed cancellation.
1348                        finish_cancel_guard.finish(true).await;
1349                        return Err(error);
1350                    }
1351
1352                    if let Some(active) = &active_execution {
1353                        active.publish(Ok(&event), updated_task).await;
1354                    }
1355
1356                    if is_terminal_event(&event) {
1357                        terminal_pushed = true;
1358                        break;
1359                    }
1360                }
1361                Err(error) => {
1362                    if let Some(active) = &active_execution {
1363                        active.publish(Err(&error), None).await;
1364                    }
1365                    // CANCELED is committed: push it before the error returns,
1366                    // without letting a failed push replace that error.
1367                    if let Ok(task) = self.load_task(&req.id).await {
1368                        let _ = send_push_notifications(
1369                            &req.id,
1370                            self.push_config_store.as_deref(),
1371                            self.push_sender.as_deref(),
1372                            &status_update(&task),
1373                        )
1374                        .await;
1375                    }
1376                    return Err(error);
1377                }
1378            }
1379        }
1380
1381        finish_cancel_guard.finish(!terminal_pushed).await;
1382
1383        // A subscription to a task between turns has no execution to follow
1384        // into the cancel; the final snapshot ends it. Subscriptions register
1385        // before reading the store, so one that read the task before
1386        // `begin_cancel` is waiting now, and one that reads it later finds it
1387        // terminal.
1388        let task = self.load_task(&req.id).await?;
1389        // `begin_cancel` committed CANCELED on its own; an executor whose
1390        // cancel emits no terminal event leaves that update to push here.
1391        if !terminal_pushed {
1392            send_push_notifications(
1393                &req.id,
1394                self.push_config_store.as_deref(),
1395                self.push_sender.as_deref(),
1396                &status_update(&task),
1397            )
1398            .await?;
1399        }
1400        self.execution_manager.release(&task);
1401        Ok(task)
1402    }
1403
1404    async fn subscribe_to_task(
1405        &self,
1406        params: &ServiceParams,
1407        req: SubscribeToTaskRequest,
1408    ) -> Result<BoxStream<'static, Result<StreamResponse, A2AError>>, A2AError> {
1409        self.authorize(params, Some(&req.id))?;
1410        self.require_streaming()?;
1411        // Registered before the store is read: an execution that starts from
1412        // here on attaches this subscription itself, so nothing is missed.
1413        let mut waiter = self.execution_manager.subscribe(&req.id).await;
1414        if let Some((receiver, snapshot_task, sequence)) = waiter.attached() {
1415            return Ok(subscription_stream(receiver, snapshot_task, sequence));
1416        }
1417
1418        // A registry miss also happens once a task finishes and its
1419        // execution is cleaned up, so it doesn't by itself mean the task
1420        // never existed -- check the store to tell the two apart before
1421        // reporting TaskNotFoundError.
1422        let task = self.load_task(&req.id).await?;
1423        // An execution that started while the store was read may have moved
1424        // the task on already; the waiter has everything it published.
1425        if let Some((receiver, snapshot_task, sequence)) = waiter.attached() {
1426            return Ok(subscription_stream(receiver, snapshot_task, sequence));
1427        }
1428        if task.status.state.is_terminal() {
1429            return Err(A2AError::unsupported_operation(format!(
1430                "task {} has already reached a terminal state",
1431                req.id
1432            )));
1433        }
1434
1435        // The task is between turns, in an interrupted state; §3.1.6 allows
1436        // subscribing to any non-terminal task. The stream opens with the
1437        // task as stored, then follows the execution the next message starts
1438        // to its end, as a resubscription would (TCK STREAM-SUB-002).
1439        Ok(stream::once(async move { Ok(StreamResponse::Task(task)) })
1440            .chain(waiter.into_stream())
1441            .boxed())
1442    }
1443
1444    async fn create_push_config(
1445        &self,
1446        params: &ServiceParams,
1447        req: TaskPushNotificationConfig,
1448    ) -> Result<TaskPushNotificationConfig, A2AError> {
1449        self.authorize(params, Some(&req.task_id))?;
1450        self.push_config_store_checked()?.save(req).await
1451    }
1452
1453    async fn get_push_config(
1454        &self,
1455        params: &ServiceParams,
1456        req: GetTaskPushNotificationConfigRequest,
1457    ) -> Result<TaskPushNotificationConfig, A2AError> {
1458        self.authorize(params, Some(&req.task_id))?;
1459        self.push_config_store_checked()?
1460            .get(&req.task_id, &req.id)
1461            .await
1462    }
1463
1464    async fn list_push_configs(
1465        &self,
1466        params: &ServiceParams,
1467        req: ListTaskPushNotificationConfigsRequest,
1468    ) -> Result<ListTaskPushNotificationConfigsResponse, A2AError> {
1469        self.authorize(params, Some(&req.task_id))?;
1470        let mut configs = self.push_config_store_checked()?.list(&req.task_id).await?;
1471        configs.sort_by(|left, right| left.id.cmp(&right.id));
1472
1473        // Paging for push configs is done here, not in the store: the store
1474        // is asked for every config for the task and the page is cut from
1475        // that. PushConfigStore is public, so this clamp is what bounds the
1476        // response for an implementation with no per-task limit of its own.
1477        let page_size = resolve_page_size(req.page_size);
1478        let start = if let Some(ref token) = req.page_token {
1479            token
1480                .parse::<usize>()
1481                .map_err(|_| A2AError::invalid_params("invalid page token"))?
1482        } else {
1483            0
1484        };
1485        let start = start.min(configs.len());
1486        let end = (start + page_size).min(configs.len());
1487        let next_page_token = (end < configs.len()).then(|| end.to_string());
1488
1489        Ok(ListTaskPushNotificationConfigsResponse {
1490            configs: configs[start..end].to_vec(),
1491            next_page_token,
1492        })
1493    }
1494
1495    async fn delete_push_config(
1496        &self,
1497        params: &ServiceParams,
1498        req: DeleteTaskPushNotificationConfigRequest,
1499    ) -> Result<(), A2AError> {
1500        self.authorize(params, Some(&req.task_id))?;
1501        self.push_config_store_checked()?
1502            .delete(&req.task_id, &req.id)
1503            .await
1504    }
1505
1506    async fn get_extended_agent_card(
1507        &self,
1508        params: &ServiceParams,
1509        _req: GetExtendedAgentCardRequest,
1510    ) -> Result<AgentCard, A2AError> {
1511        self.authorize(params, None)?;
1512        Self::require_capability(self.capabilities.extended_agent_card, || {
1513            A2AError::unsupported_operation(
1514                "the agent card does not declare an extended agent card",
1515            )
1516        })?;
1517        match &self.extended_agent_card {
1518            Some(resolver) => resolver.resolve(params),
1519            // A2A defines a code for exactly this condition.
1520            // UNSUPPORTED_OPERATION would say the agent does not do extended
1521            // cards at all, when the truth is that this deployment has not
1522            // configured one — the client can act on that difference.
1523            None => Err(A2AError::extended_card_not_configured()),
1524        }
1525    }
1526}
1527
1528#[cfg(test)]
1529mod tests {
1530    use super::*;
1531    use crate::executor::ExecutorContext;
1532    use crate::pagination::{DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE};
1533    use crate::push::{InMemoryPushConfigStore, PushConfigStore};
1534    use crate::task_store::{InMemoryTaskStore, TaskStore, TaskVersion};
1535
1536    use crate::test_util::install_crypto_provider;
1537    use axum::{
1538        Router,
1539        body::Bytes,
1540        extract::State,
1541        http::{HeaderMap, StatusCode, header},
1542        routing::post,
1543    };
1544    use futures::stream;
1545    use std::sync::Arc;
1546    use std::sync::atomic::{AtomicI32, Ordering};
1547    use tokio::{
1548        net::TcpListener,
1549        sync::{Notify, mpsc, oneshot},
1550        time::{Duration, timeout},
1551    };
1552
1553    struct EchoExecutor;
1554
1555    struct CountingExecutor(Arc<AtomicI32>);
1556
1557    impl crate::AgentExecutor for CountingExecutor {
1558        fn execute(
1559            &self,
1560            ctx: ExecutorContext,
1561        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1562            self.0.fetch_add(1, Ordering::SeqCst);
1563            EchoExecutor.execute(ctx)
1564        }
1565
1566        fn cancel(
1567            &self,
1568            ctx: ExecutorContext,
1569        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1570            EchoExecutor.cancel(ctx)
1571        }
1572    }
1573
1574    struct PushEventExecutor;
1575
1576    struct ResumableExecutor {
1577        release: Arc<Notify>,
1578    }
1579
1580    #[derive(Debug)]
1581    struct CapturedPush {
1582        authorization: Option<String>,
1583        notification_token: Option<String>,
1584        event: StreamResponse,
1585    }
1586
1587    impl crate::AgentExecutor for EchoExecutor {
1588        fn execute(
1589            &self,
1590            ctx: ExecutorContext,
1591        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1592            let task = Task {
1593                id: ctx.task_id.clone(),
1594                context_id: ctx.context_id.clone(),
1595                status: TaskStatus {
1596                    state: TaskState::Completed,
1597                    message: ctx.message,
1598                    timestamp: None,
1599                },
1600                artifacts: None,
1601                history: None,
1602                metadata: None,
1603            };
1604            Box::pin(stream::once(async move { Ok(StreamResponse::Task(task)) }))
1605        }
1606
1607        fn cancel(
1608            &self,
1609            ctx: ExecutorContext,
1610        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1611            let task = Task {
1612                id: ctx.task_id.clone(),
1613                context_id: ctx.context_id.clone(),
1614                status: TaskStatus {
1615                    state: TaskState::Canceled,
1616                    message: None,
1617                    timestamp: None,
1618                },
1619                artifacts: None,
1620                history: None,
1621                metadata: None,
1622            };
1623            Box::pin(stream::once(async move { Ok(StreamResponse::Task(task)) }))
1624        }
1625    }
1626
1627    impl crate::AgentExecutor for PushEventExecutor {
1628        fn execute(
1629            &self,
1630            ctx: ExecutorContext,
1631        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1632            let working = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
1633                task_id: ctx.task_id.clone(),
1634                context_id: ctx.context_id.clone(),
1635                status: TaskStatus {
1636                    state: TaskState::Working,
1637                    message: None,
1638                    timestamp: None,
1639                },
1640                metadata: None,
1641            });
1642            let completed = StreamResponse::Task(Task {
1643                id: ctx.task_id.clone(),
1644                context_id: ctx.context_id.clone(),
1645                status: TaskStatus {
1646                    state: TaskState::Completed,
1647                    message: ctx.message,
1648                    timestamp: None,
1649                },
1650                artifacts: None,
1651                history: ctx.stored_task.and_then(|task| task.history),
1652                metadata: None,
1653            });
1654
1655            Box::pin(stream::iter(vec![Ok(working), Ok(completed)]))
1656        }
1657
1658        fn cancel(
1659            &self,
1660            ctx: ExecutorContext,
1661        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1662            let task = Task {
1663                id: ctx.task_id.clone(),
1664                context_id: ctx.context_id.clone(),
1665                status: TaskStatus {
1666                    state: TaskState::Canceled,
1667                    message: None,
1668                    timestamp: None,
1669                },
1670                artifacts: None,
1671                history: None,
1672                metadata: None,
1673            };
1674            Box::pin(stream::once(async move { Ok(StreamResponse::Task(task)) }))
1675        }
1676    }
1677
1678    impl crate::AgentExecutor for ResumableExecutor {
1679        fn execute(
1680            &self,
1681            ctx: ExecutorContext,
1682        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1683            let release = self.release.clone();
1684            let working_task = Task {
1685                id: ctx.task_id.clone(),
1686                context_id: ctx.context_id.clone(),
1687                status: TaskStatus {
1688                    state: TaskState::Working,
1689                    message: None,
1690                    timestamp: None,
1691                },
1692                artifacts: None,
1693                history: ctx.stored_task.and_then(|task| task.history),
1694                metadata: None,
1695            };
1696            let completed_task = Task {
1697                id: working_task.id.clone(),
1698                context_id: working_task.context_id.clone(),
1699                status: TaskStatus {
1700                    state: TaskState::Completed,
1701                    message: None,
1702                    timestamp: None,
1703                },
1704                artifacts: None,
1705                history: working_task.history.clone(),
1706                metadata: None,
1707            };
1708
1709            Box::pin(stream::unfold(
1710                (Some(working_task), Some((release, completed_task))),
1711                |(working_task, completion)| async move {
1712                    if let Some(task) = working_task {
1713                        return Some((Ok(StreamResponse::Task(task)), (None, completion)));
1714                    }
1715
1716                    if let Some((release, task)) = completion {
1717                        release.notified().await;
1718                        return Some((Ok(StreamResponse::Task(task)), (None, None)));
1719                    }
1720
1721                    None
1722                },
1723            ))
1724        }
1725
1726        fn cancel(
1727            &self,
1728            ctx: ExecutorContext,
1729        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1730            let task = Task {
1731                id: ctx.task_id.clone(),
1732                context_id: ctx.context_id.clone(),
1733                status: TaskStatus {
1734                    state: TaskState::Canceled,
1735                    message: None,
1736                    timestamp: None,
1737                },
1738                artifacts: None,
1739                history: None,
1740                metadata: None,
1741            };
1742            Box::pin(stream::once(async move { Ok(StreamResponse::Task(task)) }))
1743        }
1744    }
1745
1746    /// Plays the events a test scripts for each call: `execute` gets the
1747    /// context with the incoming message, `cancel` the one without. A step
1748    /// can wait on a `Notify` first, so a test orders the executor against
1749    /// its own calls without sleeping.
1750    struct ScriptedExecutor<F>(F);
1751
1752    type Step = (Option<Arc<Notify>>, Result<StreamResponse, A2AError>);
1753
1754    impl<F> crate::AgentExecutor for ScriptedExecutor<F>
1755    where
1756        F: Fn(&ExecutorContext) -> Vec<Step> + Send + Sync + 'static,
1757    {
1758        fn execute(
1759            &self,
1760            ctx: ExecutorContext,
1761        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1762            play((self.0)(&ctx))
1763        }
1764
1765        fn cancel(
1766            &self,
1767            ctx: ExecutorContext,
1768        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1769            play((self.0)(&ctx))
1770        }
1771    }
1772
1773    fn play(steps: Vec<Step>) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1774        Box::pin(stream::iter(steps).then(|(gate, event)| async move {
1775            if let Some(gate) = gate {
1776                gate.notified().await;
1777            }
1778            event
1779        }))
1780    }
1781
1782    fn status_event(
1783        ctx: &ExecutorContext,
1784        state: TaskState,
1785        message: Option<Message>,
1786    ) -> StreamResponse {
1787        StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
1788            task_id: ctx.task_id.clone(),
1789            context_id: ctx.context_id.clone(),
1790            status: TaskStatus {
1791                state,
1792                message,
1793                timestamp: None,
1794            },
1795            metadata: None,
1796        })
1797    }
1798
1799    /// Mirrors itk's own `tck-multi-turn` ACTS behavior: only ever emits a
1800    /// `StatusUpdate`, never a full `Task`, so a test against it exercises
1801    /// exactly the path a real executor that never touches `history` relies
1802    /// on the server to handle.
1803    struct MultiTurnExecutor;
1804
1805    impl crate::AgentExecutor for MultiTurnExecutor {
1806        fn execute(
1807            &self,
1808            ctx: ExecutorContext,
1809        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1810            let done = ctx
1811                .message
1812                .as_ref()
1813                .and_then(Message::text)
1814                .is_some_and(|text| text.trim().eq_ignore_ascii_case("done"));
1815            let state = if done {
1816                TaskState::Completed
1817            } else {
1818                TaskState::InputRequired
1819            };
1820            let update = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
1821                task_id: ctx.task_id.clone(),
1822                context_id: ctx.context_id.clone(),
1823                status: TaskStatus {
1824                    state,
1825                    message: None,
1826                    timestamp: None,
1827                },
1828                metadata: None,
1829            });
1830            Box::pin(stream::once(async move { Ok(update) }))
1831        }
1832
1833        fn cancel(
1834            &self,
1835            ctx: ExecutorContext,
1836        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
1837            let task = Task {
1838                id: ctx.task_id.clone(),
1839                context_id: ctx.context_id.clone(),
1840                status: TaskStatus {
1841                    state: TaskState::Canceled,
1842                    message: None,
1843                    timestamp: None,
1844                },
1845                artifacts: None,
1846                history: None,
1847                metadata: None,
1848            };
1849            Box::pin(stream::once(async move { Ok(StreamResponse::Task(task)) }))
1850        }
1851    }
1852
1853    /// A `TaskStore` that behaves exactly like `InMemoryTaskStore` except
1854    /// for `list`, which it drives from the fields below.
1855    ///
1856    /// `TaskStore` is public, so nothing obliges a third-party
1857    /// implementation to bound its own response. Only a decorator can model
1858    /// that; everything else delegates, so a cap test cannot accidentally
1859    /// depend on stub behaviour.
1860    struct PagingTaskStore {
1861        inner: InMemoryTaskStore,
1862        count: usize,
1863        /// `true` models a well-behaved store, bounded by the handler
1864        /// clamping the request; `false` models one that ignores
1865        /// `page_size`, bounded only by the handler truncating the response.
1866        honour_page_size: bool,
1867        /// The `page_size` the handler actually asked for. Recorded because
1868        /// the response bound alone cannot distinguish a clamped request
1869        /// from an unclamped one -- both end up 100 items wide.
1870        seen_page_size: Arc<AtomicI32>,
1871        /// Continuation token the store reports, so truncation's handling of
1872        /// it can be observed.
1873        next_page_token: String,
1874    }
1875
1876    impl PagingTaskStore {
1877        fn new(count: usize, honour_page_size: bool) -> Self {
1878            Self {
1879                inner: InMemoryTaskStore::new(),
1880                count,
1881                honour_page_size,
1882                seen_page_size: Arc::new(AtomicI32::new(-1)),
1883                next_page_token: String::new(),
1884            }
1885        }
1886
1887        fn with_next_page_token(mut self, token: &str) -> Self {
1888            self.next_page_token = token.to_string();
1889            self
1890        }
1891    }
1892
1893    #[async_trait]
1894    impl TaskStore for PagingTaskStore {
1895        async fn create(&self, task: Task) -> Result<TaskVersion, A2AError> {
1896            self.inner.create(task).await
1897        }
1898
1899        async fn update(&self, task: Task) -> Result<TaskVersion, A2AError> {
1900            self.inner.update(task).await
1901        }
1902
1903        async fn get(&self, task_id: &str) -> Result<Option<Task>, A2AError> {
1904            self.inner.get(task_id).await
1905        }
1906
1907        async fn begin_cancel(&self, task_id: &str) -> Result<Task, A2AError> {
1908            self.inner.begin_cancel(task_id).await
1909        }
1910
1911        async fn list(&self, req: &ListTasksRequest) -> Result<ListTasksResponse, A2AError> {
1912            self.seen_page_size
1913                .store(req.page_size.unwrap_or(-1), Ordering::SeqCst);
1914            let served = if self.honour_page_size {
1915                req.page_size.unwrap_or(i32::MAX).max(0) as usize
1916            } else {
1917                self.count
1918            }
1919            .min(self.count);
1920            let tasks = (0..served)
1921                .map(|i| Task {
1922                    id: format!("t-{i:04}"),
1923                    context_id: "c1".into(),
1924                    status: TaskStatus {
1925                        state: TaskState::Completed,
1926                        message: None,
1927                        timestamp: None,
1928                    },
1929                    artifacts: None,
1930                    history: None,
1931                    metadata: None,
1932                })
1933                .collect::<Vec<_>>();
1934            let total = tasks.len() as i32;
1935            Ok(ListTasksResponse {
1936                tasks,
1937                next_page_token: self.next_page_token.clone(),
1938                page_size: total,
1939                total_size: total,
1940            })
1941        }
1942    }
1943
1944    /// The push-config equivalent, and the only way to reach the handler's
1945    /// page cap on that path: `InMemoryPushConfigStore` caps a task at
1946    /// `MAX_PUSH_CONFIGS_PER_TASK` (50), below the page cap of 100, so
1947    /// nothing routed through it can make the clamp bind. Everything but
1948    /// `list` delegates.
1949    struct PagingPushConfigStore {
1950        inner: InMemoryPushConfigStore,
1951        count: usize,
1952    }
1953
1954    impl PagingPushConfigStore {
1955        fn new(count: usize) -> Self {
1956            Self {
1957                inner: InMemoryPushConfigStore::new(),
1958                count,
1959            }
1960        }
1961    }
1962
1963    #[async_trait]
1964    impl crate::PushConfigStore for PagingPushConfigStore {
1965        async fn save(
1966            &self,
1967            config: TaskPushNotificationConfig,
1968        ) -> Result<TaskPushNotificationConfig, A2AError> {
1969            self.inner.save(config).await
1970        }
1971
1972        async fn get(
1973            &self,
1974            task_id: &str,
1975            config_id: &str,
1976        ) -> Result<TaskPushNotificationConfig, A2AError> {
1977            self.inner.get(task_id, config_id).await
1978        }
1979
1980        async fn list(&self, task_id: &str) -> Result<Vec<TaskPushNotificationConfig>, A2AError> {
1981            Ok((0..self.count)
1982                .map(|i| TaskPushNotificationConfig {
1983                    task_id: task_id.to_string(),
1984                    url: format!("https://example.com/hook/{i}"),
1985                    id: Some(format!("cfg-{i:04}")),
1986                    token: None,
1987                    authentication: None,
1988                    tenant: None,
1989                })
1990                .collect())
1991        }
1992
1993        async fn delete(&self, task_id: &str, config_id: &str) -> Result<(), A2AError> {
1994            self.inner.delete(task_id, config_id).await
1995        }
1996
1997        async fn delete_all(&self, task_id: &str) -> Result<(), A2AError> {
1998            self.inner.delete_all(task_id).await
1999        }
2000    }
2001
2002    /// How the cancel of an `InputRequiredExecutor` ends.
2003    enum Cancel {
2004        Cancels,
2005        Fails,
2006        /// Appends to an artifact the task does not have, which the handler
2007        /// cannot apply to the task.
2008        SendsAnInapplicableEvent,
2009    }
2010
2011    /// Asks for input on the task's first turn and completes on the next;
2012    /// its cancel reports the task canceled, or ends as asked to.
2013    struct InputRequiredExecutor {
2014        cancel: Cancel,
2015    }
2016
2017    impl crate::AgentExecutor for InputRequiredExecutor {
2018        fn execute(
2019            &self,
2020            ctx: ExecutorContext,
2021        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
2022            let state = match ctx.stored_task.as_ref().map(|task| &task.status.state) {
2023                Some(TaskState::InputRequired) => TaskState::Completed,
2024                _ => TaskState::InputRequired,
2025            };
2026            let update = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2027                task_id: ctx.task_id,
2028                context_id: ctx.context_id,
2029                status: TaskStatus {
2030                    state,
2031                    message: None,
2032                    timestamp: None,
2033                },
2034                metadata: None,
2035            });
2036            Box::pin(stream::once(async move { Ok(update) }))
2037        }
2038
2039        fn cancel(
2040            &self,
2041            ctx: ExecutorContext,
2042        ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
2043            let event = match self.cancel {
2044                Cancel::Fails => Err(A2AError::internal("cancel failed")),
2045                Cancel::SendsAnInapplicableEvent => {
2046                    Ok(StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
2047                        task_id: ctx.task_id,
2048                        context_id: ctx.context_id,
2049                        artifact: Artifact {
2050                            artifact_id: "missing".into(),
2051                            name: None,
2052                            description: None,
2053                            parts: vec![Part::text("tail")],
2054                            metadata: None,
2055                            extensions: None,
2056                        },
2057                        append: Some(true),
2058                        last_chunk: None,
2059                        metadata: None,
2060                    }))
2061                }
2062                Cancel::Cancels => Ok(StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2063                    task_id: ctx.task_id,
2064                    context_id: ctx.context_id,
2065                    status: TaskStatus {
2066                        state: TaskState::Canceled,
2067                        message: None,
2068                        timestamp: None,
2069                    },
2070                    metadata: None,
2071                })),
2072            };
2073            Box::pin(stream::once(async move { event }))
2074        }
2075    }
2076
2077    /// Pre-create a task so a message may legitimately reference it: A2A
2078    /// §3.4.2 forbids client-provided taskIds for *creating* tasks.
2079    async fn seed_task(handler: &DefaultRequestHandler, task_id: &str, context_id: &str) {
2080        handler
2081            .task_store
2082            .create(Task {
2083                id: task_id.into(),
2084                context_id: context_id.into(),
2085                status: TaskStatus {
2086                    state: TaskState::Submitted,
2087                    message: None,
2088                    timestamp: None,
2089                },
2090                artifacts: None,
2091                history: None,
2092                metadata: None,
2093            })
2094            .await
2095            .unwrap();
2096    }
2097
2098    fn make_handler() -> DefaultRequestHandler {
2099        DefaultRequestHandler::new(EchoExecutor, InMemoryTaskStore::new())
2100    }
2101
2102    fn make_handler_with_push_configs() -> DefaultRequestHandler {
2103        DefaultRequestHandler::new(EchoExecutor, InMemoryTaskStore::new())
2104            .with_push_config_store(InMemoryPushConfigStore::new())
2105    }
2106
2107    fn make_push_delivery_handler() -> DefaultRequestHandler {
2108        // URL validation is disabled because the test webhook runs on
2109        // 127.0.0.1; the default HttpPushSender rejects loopback targets.
2110        DefaultRequestHandler::new(PushEventExecutor, InMemoryTaskStore::new())
2111            .with_push_notifications(
2112                InMemoryPushConfigStore::new(),
2113                crate::HttpPushSender::new(Some(crate::HttpPushSenderConfig {
2114                    validate_urls: false,
2115                    ..Default::default()
2116                })),
2117            )
2118    }
2119
2120    fn make_resumable_handler() -> (DefaultRequestHandler, Arc<Notify>) {
2121        let release = Arc::new(Notify::new());
2122        (
2123            DefaultRequestHandler::new(
2124                ResumableExecutor {
2125                    release: release.clone(),
2126                },
2127                InMemoryTaskStore::new(),
2128            ),
2129            release,
2130        )
2131    }
2132
2133    fn make_input_required_handler() -> DefaultRequestHandler {
2134        DefaultRequestHandler::new(
2135            InputRequiredExecutor {
2136                cancel: Cancel::Cancels,
2137            },
2138            InMemoryTaskStore::new(),
2139        )
2140    }
2141
2142    /// A task whose first turn ended asking for input: stored, but with no
2143    /// execution registered any more.
2144    async fn task_awaiting_input(handler: &DefaultRequestHandler) -> Task {
2145        let response = handler
2146            .send_message(
2147                &ServiceParams::new(),
2148                SendMessageRequest {
2149                    message: make_message(),
2150                    configuration: None,
2151                    metadata: None,
2152                    tenant: None,
2153                },
2154            )
2155            .await
2156            .unwrap();
2157        let mut task = None;
2158        if let SendMessageResponse::Task(sent) = response {
2159            task = Some(sent);
2160        }
2161        let task = task.expect("expected a task");
2162        assert_eq!(task.status.state, TaskState::InputRequired);
2163        assert!(handler.execution_manager.get(&task.id).await.is_none());
2164        task
2165    }
2166
2167    fn make_message() -> Message {
2168        Message::new(Role::User, vec![Part::text("hello")])
2169    }
2170
2171    async fn capture_push(
2172        State(sender): State<mpsc::UnboundedSender<CapturedPush>>,
2173        headers: HeaderMap,
2174        body: Bytes,
2175    ) -> StatusCode {
2176        let captured = CapturedPush {
2177            authorization: headers
2178                .get(header::AUTHORIZATION)
2179                .and_then(|value| value.to_str().ok())
2180                .map(ToOwned::to_owned),
2181            notification_token: headers
2182                .get("A2A-Notification-Token")
2183                .and_then(|value| value.to_str().ok())
2184                .map(ToOwned::to_owned),
2185            event: serde_json::from_slice(&body).unwrap(),
2186        };
2187        sender.send(captured).unwrap();
2188        StatusCode::ACCEPTED
2189    }
2190
2191    async fn start_push_webhook() -> (
2192        String,
2193        mpsc::UnboundedReceiver<CapturedPush>,
2194        oneshot::Sender<()>,
2195        tokio::task::JoinHandle<()>,
2196    ) {
2197        let (sender, receiver) = mpsc::unbounded_channel();
2198        let app = Router::new()
2199            .route("/", post(capture_push))
2200            .with_state(sender);
2201        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2202        let address = listener.local_addr().unwrap();
2203        let (shutdown_tx, shutdown_rx) = oneshot::channel();
2204        let server = tokio::spawn(async move {
2205            axum::serve(listener, app)
2206                .with_graceful_shutdown(async {
2207                    let _ = shutdown_rx.await;
2208                })
2209                .await
2210                .unwrap();
2211        });
2212
2213        (format!("http://{address}/"), receiver, shutdown_tx, server)
2214    }
2215
2216    async fn next_push(receiver: &mut mpsc::UnboundedReceiver<CapturedPush>) -> CapturedPush {
2217        timeout(Duration::from_secs(5), receiver.recv())
2218            .await
2219            .unwrap()
2220            .unwrap()
2221    }
2222
2223    #[tokio::test]
2224    async fn test_client_role_validation_precedes_task_creation_and_execution() {
2225        for role in [Role::Agent, Role::Unspecified] {
2226            for streaming in [false, true] {
2227                let executions = Arc::new(AtomicI32::new(0));
2228                let handler = DefaultRequestHandler::new(
2229                    CountingExecutor(executions.clone()),
2230                    InMemoryTaskStore::new(),
2231                );
2232                let mut message = make_message();
2233                message.role = role.clone();
2234                let req = SendMessageRequest {
2235                    message,
2236                    configuration: None,
2237                    metadata: None,
2238                    tenant: None,
2239                };
2240                let error = if streaming {
2241                    match handler
2242                        .send_streaming_message(&ServiceParams::new(), req)
2243                        .await
2244                    {
2245                        Ok(_) => panic!("invalid role was accepted"),
2246                        Err(error) => error,
2247                    }
2248                } else {
2249                    handler
2250                        .send_message(&ServiceParams::new(), req)
2251                        .await
2252                        .unwrap_err()
2253                };
2254                assert_eq!(error.code, error_code::INVALID_PARAMS);
2255                let received = match role {
2256                    Role::Agent => "ROLE_AGENT",
2257                    Role::Unspecified => "ROLE_UNSPECIFIED",
2258                    Role::User => "ROLE_USER",
2259                };
2260                assert_eq!(
2261                    error.message,
2262                    format!(
2263                        "client messages must have role ROLE_USER, got decoded role {received}"
2264                    )
2265                );
2266                assert_eq!(executions.load(Ordering::SeqCst), 0);
2267                let tasks = handler
2268                    .task_store
2269                    .list(&ListTasksRequest {
2270                        context_id: None,
2271                        status: None,
2272                        page_size: None,
2273                        page_token: None,
2274                        history_length: None,
2275                        status_timestamp_after: None,
2276                        include_artifacts: None,
2277                        tenant: None,
2278                    })
2279                    .await
2280                    .unwrap();
2281                assert!(tasks.tasks.is_empty());
2282            }
2283        }
2284    }
2285
2286    #[tokio::test]
2287    async fn test_invalid_client_role_does_not_change_existing_task() {
2288        for streaming in [false, true] {
2289            let executions = Arc::new(AtomicI32::new(0));
2290            let handler = DefaultRequestHandler::new(
2291                CountingExecutor(executions.clone()),
2292                InMemoryTaskStore::new(),
2293            );
2294            seed_task(&handler, "existing-task", "existing-context").await;
2295            let before = handler.task_store.get("existing-task").await.unwrap();
2296            let mut message = make_message();
2297            message.role = Role::Agent;
2298            message.task_id = Some("existing-task".into());
2299            message.context_id = Some("existing-context".into());
2300            let request = SendMessageRequest {
2301                message,
2302                configuration: None,
2303                metadata: None,
2304                tenant: None,
2305            };
2306            let error = if streaming {
2307                match handler
2308                    .send_streaming_message(&ServiceParams::new(), request)
2309                    .await
2310                {
2311                    Ok(_) => panic!("invalid role was accepted"),
2312                    Err(error) => error,
2313                }
2314            } else {
2315                handler
2316                    .send_message(&ServiceParams::new(), request)
2317                    .await
2318                    .unwrap_err()
2319            };
2320            assert_eq!(error.code, error_code::INVALID_PARAMS);
2321            assert_eq!(
2322                handler.task_store.get("existing-task").await.unwrap(),
2323                before
2324            );
2325            assert_eq!(executions.load(Ordering::SeqCst), 0);
2326        }
2327    }
2328
2329    #[tokio::test]
2330    async fn test_user_role_executes_in_unary_and_streaming_requests() {
2331        use futures::StreamExt;
2332
2333        for streaming in [false, true] {
2334            let executions = Arc::new(AtomicI32::new(0));
2335            let handler = DefaultRequestHandler::new(
2336                CountingExecutor(executions.clone()),
2337                InMemoryTaskStore::new(),
2338            );
2339            let request = SendMessageRequest {
2340                message: make_message(),
2341                configuration: None,
2342                metadata: None,
2343                tenant: None,
2344            };
2345            let task = if streaming {
2346                let mut stream = handler
2347                    .send_streaming_message(&ServiceParams::new(), request)
2348                    .await
2349                    .unwrap();
2350                match stream.next().await.unwrap().unwrap() {
2351                    StreamResponse::Task(task) => task,
2352                    other => panic!("expected task response, got {other:?}"),
2353                }
2354            } else {
2355                match handler
2356                    .send_message(&ServiceParams::new(), request)
2357                    .await
2358                    .unwrap()
2359                {
2360                    SendMessageResponse::Task(task) => task,
2361                    other => panic!("expected task response, got {other:?}"),
2362                }
2363            };
2364            assert_eq!(task.status.state, TaskState::Completed);
2365            assert_eq!(executions.load(Ordering::SeqCst), 1);
2366        }
2367    }
2368
2369    #[tokio::test]
2370    async fn test_role_validation_does_not_block_canceling_existing_task() {
2371        let executions = Arc::new(AtomicI32::new(0));
2372        let handler = DefaultRequestHandler::new(
2373            CountingExecutor(executions.clone()),
2374            InMemoryTaskStore::new(),
2375        );
2376        seed_task(&handler, "pending-task", "pending-context").await;
2377        let task = handler
2378            .cancel_task(
2379                &ServiceParams::new(),
2380                CancelTaskRequest {
2381                    id: "pending-task".into(),
2382                    metadata: None,
2383                    tenant: None,
2384                },
2385            )
2386            .await
2387            .unwrap();
2388        assert_eq!(task.status.state, TaskState::Canceled);
2389        assert_eq!(executions.load(Ordering::SeqCst), 0);
2390    }
2391
2392    #[tokio::test]
2393    async fn test_send_message_creates_task() {
2394        let handler = make_handler();
2395        let params = ServiceParams::new();
2396        let req = SendMessageRequest {
2397            message: make_message(),
2398            configuration: None,
2399            metadata: None,
2400            tenant: None,
2401        };
2402        let result = handler.send_message(&params, req).await.unwrap();
2403        match result {
2404            SendMessageResponse::Task(task) => {
2405                assert_eq!(task.status.state, TaskState::Completed);
2406            }
2407            _ => panic!("expected Task response"),
2408        }
2409    }
2410
2411    #[tokio::test]
2412    async fn test_send_streaming_message() {
2413        use futures::StreamExt;
2414        let handler = make_handler();
2415        let params = ServiceParams::new();
2416        let req = SendMessageRequest {
2417            message: make_message(),
2418            configuration: None,
2419            metadata: None,
2420            tenant: None,
2421        };
2422        let mut stream = handler.send_streaming_message(&params, req).await.unwrap();
2423        let event = stream.next().await.unwrap().unwrap();
2424        assert!(matches!(event, StreamResponse::Task(_)));
2425    }
2426
2427    /// DM-SERIAL-001: `save_task`'s backfill only covers what gets persisted
2428    /// -- a live subscriber receives the broadcast event directly, never a
2429    /// reload from the store, so the timestamp must also be backfilled on
2430    /// the event itself before it is published.
2431    #[tokio::test]
2432    async fn test_streamed_task_event_has_a_backfilled_timestamp() {
2433        use futures::StreamExt;
2434        let handler = make_handler();
2435        let params = ServiceParams::new();
2436        let req = SendMessageRequest {
2437            message: make_message(),
2438            configuration: None,
2439            metadata: None,
2440            tenant: None,
2441        };
2442        let mut stream = handler.send_streaming_message(&params, req).await.unwrap();
2443        let event = stream.next().await.unwrap().unwrap();
2444        match event {
2445            StreamResponse::Task(task) => assert!(
2446                task.status.timestamp.is_some(),
2447                "a live-streamed task event must carry a backfilled timestamp"
2448            ),
2449            other => panic!("unexpected event: {other:?}"),
2450        }
2451    }
2452
2453    /// `ArtifactUpdate` and `Message` carry no status of their own, so the
2454    /// backfill must leave them alone rather than panic on the missing arm.
2455    #[test]
2456    fn test_backfill_status_timestamp_ignores_events_without_a_status() {
2457        let mut artifact_update = StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
2458            task_id: "t1".into(),
2459            context_id: "c1".into(),
2460            artifact: Artifact {
2461                artifact_id: "a1".into(),
2462                name: None,
2463                description: None,
2464                parts: vec![Part::text("payload")],
2465                metadata: None,
2466                extensions: None,
2467            },
2468            append: None,
2469            last_chunk: None,
2470            metadata: None,
2471        });
2472        let before = artifact_update.clone();
2473        backfill_status_timestamp(&mut artifact_update);
2474        assert_eq!(artifact_update, before);
2475
2476        let mut message = StreamResponse::Message(make_message());
2477        let before = message.clone();
2478        backfill_status_timestamp(&mut message);
2479        assert_eq!(message, before);
2480    }
2481
2482    /// DM-SERIAL-001: a status update whose status omits a timestamp must be
2483    /// backfilled before the task is persisted, so a returned task never
2484    /// carries a timestamp-less status.
2485    #[tokio::test]
2486    async fn test_status_update_backfills_missing_timestamp() {
2487        let store = InMemoryTaskStore::new();
2488        store
2489            .create(Task {
2490                id: "t-backfill".into(),
2491                context_id: "ctx".into(),
2492                status: TaskStatus {
2493                    state: TaskState::Submitted,
2494                    message: None,
2495                    timestamp: Some(chrono::Utc::now()),
2496                },
2497                artifacts: None,
2498                history: None,
2499                metadata: None,
2500            })
2501            .await
2502            .unwrap();
2503
2504        let updated = apply_event_to_task(
2505            &store,
2506            None,
2507            &StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2508                task_id: "t-backfill".into(),
2509                context_id: "ctx".into(),
2510                status: TaskStatus {
2511                    state: TaskState::Working,
2512                    message: None,
2513                    timestamp: None,
2514                },
2515                metadata: None,
2516            }),
2517        )
2518        .await
2519        .unwrap()
2520        .expect("status update yields a task");
2521
2522        assert_eq!(updated.status.state, TaskState::Working);
2523        assert!(
2524            updated.status.timestamp.is_some(),
2525            "missing status timestamp must be backfilled"
2526        );
2527    }
2528
2529    /// A timestamp supplied by the executor is authoritative and must be kept
2530    /// verbatim, not overwritten by the backfill.
2531    #[tokio::test]
2532    async fn test_status_update_preserves_supplied_timestamp() {
2533        let store = InMemoryTaskStore::new();
2534        store
2535            .create(Task {
2536                id: "t-preserve".into(),
2537                context_id: "ctx".into(),
2538                status: TaskStatus {
2539                    state: TaskState::Submitted,
2540                    message: None,
2541                    timestamp: None,
2542                },
2543                artifacts: None,
2544                history: None,
2545                metadata: None,
2546            })
2547            .await
2548            .unwrap();
2549
2550        let supplied = chrono::DateTime::parse_from_rfc3339("2020-01-02T03:04:05Z")
2551            .unwrap()
2552            .with_timezone(&chrono::Utc);
2553
2554        let updated = apply_event_to_task(
2555            &store,
2556            None,
2557            &StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2558                task_id: "t-preserve".into(),
2559                context_id: "ctx".into(),
2560                status: TaskStatus {
2561                    state: TaskState::Working,
2562                    message: None,
2563                    timestamp: Some(supplied),
2564                },
2565                metadata: None,
2566            }),
2567        )
2568        .await
2569        .unwrap()
2570        .expect("status update yields a task");
2571
2572        assert_eq!(updated.status.timestamp, Some(supplied));
2573    }
2574
2575    /// The task-snapshot arm persists through the same `save_task` chokepoint,
2576    /// so an executor `Task` event whose status omits a timestamp must also be
2577    /// backfilled (DM-SERIAL-001).
2578    #[tokio::test]
2579    async fn test_task_snapshot_backfills_missing_timestamp() {
2580        let store = InMemoryTaskStore::new();
2581
2582        let returned = apply_event_to_task(
2583            &store,
2584            None,
2585            &StreamResponse::Task(Task {
2586                id: "t-snapshot".into(),
2587                context_id: "ctx".into(),
2588                status: TaskStatus {
2589                    state: TaskState::Completed,
2590                    message: None,
2591                    timestamp: None,
2592                },
2593                artifacts: None,
2594                history: None,
2595                metadata: None,
2596            }),
2597        )
2598        .await
2599        .unwrap()
2600        .expect("task event yields a task");
2601
2602        assert!(
2603            returned.status.timestamp.is_some(),
2604            "missing status timestamp must be backfilled on the task-snapshot path"
2605        );
2606        let persisted = store.get("t-snapshot").await.unwrap().unwrap();
2607        assert!(
2608            persisted.status.timestamp.is_some(),
2609            "the persisted task must carry a timestamp"
2610        );
2611    }
2612
2613    /// A timestamp already present on a task snapshot is authoritative and
2614    /// must survive the persistence chokepoint unchanged.
2615    #[tokio::test]
2616    async fn test_task_snapshot_preserves_supplied_timestamp() {
2617        let store = InMemoryTaskStore::new();
2618
2619        let supplied = chrono::DateTime::parse_from_rfc3339("2021-06-07T08:09:10Z")
2620            .unwrap()
2621            .with_timezone(&chrono::Utc);
2622
2623        let returned = apply_event_to_task(
2624            &store,
2625            None,
2626            &StreamResponse::Task(Task {
2627                id: "t-snapshot-kept".into(),
2628                context_id: "ctx".into(),
2629                status: TaskStatus {
2630                    state: TaskState::Completed,
2631                    message: None,
2632                    timestamp: Some(supplied),
2633                },
2634                artifacts: None,
2635                history: None,
2636                metadata: None,
2637            }),
2638        )
2639        .await
2640        .unwrap()
2641        .expect("task event yields a task");
2642
2643        assert_eq!(returned.status.timestamp, Some(supplied));
2644        let persisted = store.get("t-snapshot-kept").await.unwrap().unwrap();
2645        assert_eq!(persisted.status.timestamp, Some(supplied));
2646    }
2647
2648    #[tokio::test]
2649    async fn test_stream_disconnect_preserves_execution_for_resubscription() {
2650        use futures::StreamExt;
2651
2652        let (handler, release) = make_resumable_handler();
2653        let params = ServiceParams::new();
2654        let mut message = make_message();
2655        message.task_id = Some("t-disconnect".into());
2656        message.context_id = Some("c-disconnect".into());
2657        seed_task(&handler, "t-disconnect", "c-disconnect").await;
2658
2659        let mut stream = handler
2660            .send_streaming_message(
2661                &params,
2662                SendMessageRequest {
2663                    message,
2664                    configuration: None,
2665                    metadata: None,
2666                    tenant: None,
2667                },
2668            )
2669            .await
2670            .unwrap();
2671
2672        let initial = stream.next().await.unwrap().unwrap();
2673        match initial {
2674            StreamResponse::Task(task) => assert_eq!(task.status.state, TaskState::Working),
2675            _ => panic!("expected initial working task"),
2676        }
2677        drop(stream);
2678
2679        let mut resumed = handler
2680            .subscribe_to_task(
2681                &params,
2682                SubscribeToTaskRequest {
2683                    id: "t-disconnect".into(),
2684                    tenant: None,
2685                },
2686            )
2687            .await
2688            .unwrap();
2689
2690        let snapshot = resumed.next().await.unwrap().unwrap();
2691        match snapshot {
2692            StreamResponse::Task(task) => assert_eq!(task.status.state, TaskState::Working),
2693            _ => panic!("expected working task snapshot"),
2694        }
2695
2696        release.notify_waiters();
2697
2698        let terminal = resumed.next().await.unwrap().unwrap();
2699        match terminal {
2700            StreamResponse::Task(task) => {
2701                assert_eq!(task.status.state, TaskState::Completed)
2702            }
2703            _ => panic!("expected terminal task"),
2704        }
2705        assert!(resumed.next().await.is_none());
2706    }
2707
2708    #[tokio::test]
2709    async fn test_active_execution_keeps_snapshot_without_subscribers() {
2710        let task = Task {
2711            id: "t-buffering".into(),
2712            context_id: "c-buffering".into(),
2713            status: TaskStatus {
2714                state: TaskState::Working,
2715                message: None,
2716                timestamp: None,
2717            },
2718            artifacts: None,
2719            history: None,
2720            metadata: None,
2721        };
2722        let active = ActiveExecution::new(task.clone());
2723
2724        let event = StreamResponse::Task(task.clone());
2725        active.publish(Ok(&event), Some(task)).await;
2726
2727        let (mut receiver, snapshot_task, sequence) = active.resubscribe().await;
2728        assert_eq!(snapshot_task.unwrap().id, "t-buffering");
2729        assert_eq!(sequence, 1);
2730        assert!(receiver.try_recv().is_err());
2731    }
2732
2733    #[tokio::test]
2734    async fn test_active_execution_publishes_errors_to_subscribers() {
2735        let task = Task {
2736            id: "t-buffering-error".into(),
2737            context_id: "c-buffering-error".into(),
2738            status: TaskStatus {
2739                state: TaskState::Working,
2740                message: None,
2741                timestamp: None,
2742            },
2743            artifacts: None,
2744            history: None,
2745            metadata: None,
2746        };
2747        let active = ActiveExecution::new(task);
2748        let mut receiver = active.subscribe();
2749        let error = A2AError::internal("execution failed");
2750
2751        active.publish(Err(&error), None).await;
2752
2753        let event = receiver.recv().await.unwrap();
2754        assert_eq!(event.sequence, 1);
2755        assert_eq!(event.result.unwrap_err().code, error.code);
2756    }
2757
2758    /// An execution that fails midway leaves its task FAILED with a
2759    /// sanitized status message; the error itself still reaches the caller.
2760    #[tokio::test]
2761    async fn test_execution_error_leaves_the_task_failed() {
2762        let handler = DefaultRequestHandler::new(
2763            ScriptedExecutor(|ctx: &ExecutorContext| {
2764                vec![
2765                    (None, Ok(status_event(ctx, TaskState::Working, None))),
2766                    (None, Err(A2AError::internal("executor exploded"))),
2767                ]
2768            }),
2769            InMemoryTaskStore::new(),
2770        );
2771        let events: Vec<_> = handler
2772            .send_streaming_message(&ServiceParams::new(), send_request())
2773            .await
2774            .unwrap()
2775            .collect()
2776            .await;
2777        assert!(matches!(events.last(), Some(Err(error)) if error.message == "executor exploded"));
2778        let task_id = task_id_for_event(events[0].as_ref().unwrap())
2779            .unwrap()
2780            .to_owned();
2781
2782        let task = handler
2783            .get_task(
2784                &ServiceParams::new(),
2785                GetTaskRequest {
2786                    id: task_id,
2787                    history_length: None,
2788                    tenant: None,
2789                },
2790            )
2791            .await
2792            .unwrap();
2793        assert_eq!(task.status.state, TaskState::Failed);
2794        assert_eq!(
2795            task.status.message.as_ref().and_then(Message::text),
2796            Some("Internal error")
2797        );
2798    }
2799
2800    /// An event the server cannot apply fails the task the same way.
2801    #[tokio::test]
2802    async fn test_unappliable_event_leaves_the_task_failed() {
2803        let handler = DefaultRequestHandler::new(
2804            ScriptedExecutor(|ctx: &ExecutorContext| {
2805                let append = StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
2806                    task_id: ctx.task_id.clone(),
2807                    context_id: ctx.context_id.clone(),
2808                    artifact: Artifact {
2809                        artifact_id: "unknown".into(),
2810                        name: None,
2811                        description: None,
2812                        parts: vec![Part::text("more")],
2813                        metadata: None,
2814                        extensions: None,
2815                    },
2816                    append: Some(true),
2817                    last_chunk: None,
2818                    metadata: None,
2819                });
2820                vec![(None, Ok(append))]
2821            }),
2822            InMemoryTaskStore::new(),
2823        );
2824        let error = handler
2825            .send_message(&ServiceParams::new(), send_request())
2826            .await
2827            .unwrap_err();
2828        assert_eq!(error.code, error_code::INVALID_AGENT_RESPONSE);
2829
2830        let listed = handler
2831            .list_tasks(
2832                &ServiceParams::new(),
2833                ListTasksRequest {
2834                    context_id: None,
2835                    status: None,
2836                    page_size: None,
2837                    page_token: None,
2838                    history_length: None,
2839                    status_timestamp_after: None,
2840                    include_artifacts: None,
2841                    tenant: None,
2842                },
2843            )
2844            .await
2845            .unwrap();
2846        assert_eq!(listed.tasks[0].status.state, TaskState::Failed);
2847    }
2848
2849    /// A push the sender cannot deliver, with `fail_on_error`, fails the task
2850    /// as well.
2851    #[tokio::test]
2852    async fn test_failed_push_leaves_the_task_failed() {
2853        let handler = DefaultRequestHandler::new(
2854            ScriptedExecutor(|ctx: &ExecutorContext| {
2855                vec![(None, Ok(status_event(ctx, TaskState::Working, None)))]
2856            }),
2857            InMemoryTaskStore::new(),
2858        )
2859        .with_push_notifications(
2860            InMemoryPushConfigStore::new(),
2861            crate::HttpPushSender::new(Some(crate::HttpPushSenderConfig {
2862                fail_on_error: true,
2863                ..Default::default()
2864            })),
2865        );
2866        let mut request = send_request();
2867        request.configuration = Some(SendMessageConfiguration {
2868            accepted_output_modes: None,
2869            // A loopback webhook is refused by the default URL validation.
2870            task_push_notification_config: Some(TaskPushNotificationConfig {
2871                url: "http://127.0.0.1:9/callback".into(),
2872                ..push_config("")
2873            }),
2874            history_length: None,
2875            return_immediately: None,
2876        });
2877        handler
2878            .send_message(&ServiceParams::new(), request)
2879            .await
2880            .unwrap_err();
2881
2882        let listed = handler
2883            .list_tasks(
2884                &ServiceParams::new(),
2885                ListTasksRequest {
2886                    context_id: None,
2887                    status: None,
2888                    page_size: None,
2889                    page_token: None,
2890                    history_length: None,
2891                    status_timestamp_after: None,
2892                    include_artifacts: None,
2893                    tenant: None,
2894                },
2895            )
2896            .await
2897            .unwrap();
2898        assert_eq!(listed.tasks[0].status.state, TaskState::Failed);
2899    }
2900
2901    /// Cancelling a running task leaves it CANCELED: the execution the cancel
2902    /// stops is not a failure.
2903    #[tokio::test]
2904    async fn test_canceled_task_is_not_marked_failed() {
2905        let gate = Arc::new(Notify::new());
2906        let handler = DefaultRequestHandler::new(
2907            ScriptedExecutor(move |ctx: &ExecutorContext| {
2908                if ctx.message.is_some() {
2909                    vec![
2910                        (None, Ok(status_event(ctx, TaskState::Working, None))),
2911                        (
2912                            Some(gate.clone()),
2913                            Ok(status_event(ctx, TaskState::Working, None)),
2914                        ),
2915                    ]
2916                } else {
2917                    vec![(None, Ok(status_event(ctx, TaskState::Canceled, None)))]
2918                }
2919            }),
2920            InMemoryTaskStore::new(),
2921        );
2922        let mut request = send_request();
2923        request.configuration = Some(SendMessageConfiguration {
2924            accepted_output_modes: None,
2925            task_push_notification_config: None,
2926            history_length: None,
2927            return_immediately: Some(true),
2928        });
2929        handler
2930            .send_message(&ServiceParams::new(), request)
2931            .await
2932            .unwrap();
2933        let task_id = handler
2934            .list_tasks(
2935                &ServiceParams::new(),
2936                ListTasksRequest {
2937                    context_id: None,
2938                    status: None,
2939                    page_size: None,
2940                    page_token: None,
2941                    history_length: None,
2942                    status_timestamp_after: None,
2943                    include_artifacts: None,
2944                    tenant: None,
2945                },
2946            )
2947            .await
2948            .unwrap()
2949            .tasks[0]
2950            .id
2951            .clone();
2952        let canceled = handler
2953            .cancel_task(
2954                &ServiceParams::new(),
2955                CancelTaskRequest {
2956                    id: task_id.clone(),
2957                    metadata: None,
2958                    tenant: None,
2959                },
2960            )
2961            .await
2962            .unwrap();
2963        assert_eq!(canceled.status.state, TaskState::Canceled);
2964
2965        let stored = handler
2966            .get_task(
2967                &ServiceParams::new(),
2968                GetTaskRequest {
2969                    id: task_id,
2970                    history_length: None,
2971                    tenant: None,
2972                },
2973            )
2974            .await
2975            .unwrap();
2976        assert_eq!(stored.status.state, TaskState::Canceled);
2977    }
2978
2979    /// The agent's INPUT_REQUIRED question stays in history between the
2980    /// turn that asked it and the answer.
2981    #[tokio::test]
2982    async fn test_continuation_keeps_the_question_in_history() {
2983        let handler = DefaultRequestHandler::new(
2984            ScriptedExecutor(|ctx: &ExecutorContext| {
2985                let asked = ctx
2986                    .message
2987                    .as_ref()
2988                    .and_then(Message::text)
2989                    .is_some_and(|text| text == "ask");
2990                let event = if asked {
2991                    let question = Message::new(Role::Agent, vec![Part::text("Which file?")]);
2992                    status_event(ctx, TaskState::InputRequired, Some(question))
2993                } else {
2994                    status_event(ctx, TaskState::Completed, None)
2995                };
2996                vec![(None, Ok(event))]
2997            }),
2998            InMemoryTaskStore::new(),
2999        );
3000        let params = ServiceParams::new();
3001        let ask = SendMessageRequest {
3002            message: Message::new(Role::User, vec![Part::text("ask")]),
3003            ..send_request()
3004        };
3005        handler.send_message(&params, ask).await.unwrap();
3006        let task_id = handler
3007            .list_tasks(
3008                &params,
3009                ListTasksRequest {
3010                    context_id: None,
3011                    status: None,
3012                    page_size: None,
3013                    page_token: None,
3014                    history_length: None,
3015                    status_timestamp_after: None,
3016                    include_artifacts: None,
3017                    tenant: None,
3018                },
3019            )
3020            .await
3021            .unwrap()
3022            .tasks[0]
3023            .id
3024            .clone();
3025        let answer = SendMessageRequest {
3026            message: Message {
3027                task_id: Some(task_id.clone()),
3028                ..Message::new(Role::User, vec![Part::text("main.rs")])
3029            },
3030            ..send_request()
3031        };
3032        handler.send_message(&params, answer).await.unwrap();
3033
3034        let task = handler
3035            .get_task(
3036                &params,
3037                GetTaskRequest {
3038                    id: task_id,
3039                    history_length: None,
3040                    tenant: None,
3041                },
3042            )
3043            .await
3044            .unwrap();
3045        let said: Vec<_> = task
3046            .history
3047            .unwrap()
3048            .iter()
3049            .map(|message| message.text().unwrap().to_owned())
3050            .collect();
3051        assert_eq!(said, ["ask", "Which file?", "main.rs"]);
3052    }
3053
3054    /// An agent that asks "Which file?" on "ask" and completes on any other
3055    /// message. With `in_history`, the question is already in the `history`
3056    /// of the task snapshot it emits, as an agent that records it itself does.
3057    fn asking_handler(in_history: bool) -> DefaultRequestHandler {
3058        DefaultRequestHandler::new(
3059            ScriptedExecutor(move |ctx: &ExecutorContext| {
3060                let asked = ctx
3061                    .message
3062                    .as_ref()
3063                    .and_then(Message::text)
3064                    .is_some_and(|text| text == "ask");
3065                let event = match (asked, &ctx.message) {
3066                    (true, Some(ask)) if in_history => {
3067                        let question = Message::new(Role::Agent, vec![Part::text("Which file?")]);
3068                        StreamResponse::Task(Task {
3069                            id: ctx.task_id.clone(),
3070                            context_id: ctx.context_id.clone(),
3071                            status: TaskStatus {
3072                                state: TaskState::InputRequired,
3073                                message: Some(question.clone()),
3074                                timestamp: None,
3075                            },
3076                            artifacts: None,
3077                            history: Some(vec![ask.clone(), question]),
3078                            metadata: None,
3079                        })
3080                    }
3081                    (true, _) => {
3082                        let question = Message::new(Role::Agent, vec![Part::text("Which file?")]);
3083                        status_event(ctx, TaskState::InputRequired, Some(question))
3084                    }
3085                    (false, _) => status_event(ctx, TaskState::Completed, None),
3086                };
3087                vec![(None, Ok(event))]
3088            }),
3089            InMemoryTaskStore::new(),
3090        )
3091    }
3092
3093    /// Sends "ask", then "main.rs" to the task it created, and returns the
3094    /// task's history as text.
3095    async fn answer_the_question(handler: &DefaultRequestHandler, streaming: bool) -> Vec<String> {
3096        async fn turn(handler: &DefaultRequestHandler, streaming: bool, message: Message) {
3097            let params = ServiceParams::new();
3098            let request = SendMessageRequest {
3099                message,
3100                ..send_request()
3101            };
3102            if streaming {
3103                let _: Vec<_> = handler
3104                    .send_streaming_message(&params, request)
3105                    .await
3106                    .unwrap()
3107                    .collect()
3108                    .await;
3109            } else {
3110                handler.send_message(&params, request).await.unwrap();
3111            }
3112        }
3113
3114        let params = ServiceParams::new();
3115        turn(
3116            handler,
3117            streaming,
3118            Message::new(Role::User, vec![Part::text("ask")]),
3119        )
3120        .await;
3121        let task_id = handler
3122            .list_tasks(
3123                &params,
3124                ListTasksRequest {
3125                    context_id: None,
3126                    status: None,
3127                    page_size: None,
3128                    page_token: None,
3129                    history_length: None,
3130                    status_timestamp_after: None,
3131                    include_artifacts: None,
3132                    tenant: None,
3133                },
3134            )
3135            .await
3136            .unwrap()
3137            .tasks[0]
3138            .id
3139            .clone();
3140        let answer = Message {
3141            task_id: Some(task_id.clone()),
3142            ..Message::new(Role::User, vec![Part::text("main.rs")])
3143        };
3144        turn(handler, streaming, answer).await;
3145        let task = handler
3146            .get_task(
3147                &params,
3148                GetTaskRequest {
3149                    id: task_id,
3150                    history_length: None,
3151                    tenant: None,
3152                },
3153            )
3154            .await
3155            .unwrap();
3156        task.history
3157            .unwrap()
3158            .iter()
3159            .map(|message| message.text().unwrap().to_owned())
3160            .collect()
3161    }
3162
3163    /// `send_streaming_message` continues a task through the same path.
3164    #[tokio::test]
3165    async fn test_streamed_continuation_keeps_the_question_in_history() {
3166        let said = answer_the_question(&asking_handler(false), true).await;
3167        assert_eq!(said, ["ask", "Which file?", "main.rs"]);
3168    }
3169
3170    /// A question the agent already put in `history` is not added twice.
3171    #[tokio::test]
3172    async fn test_continuation_does_not_repeat_a_question_already_in_history() {
3173        let said = answer_the_question(&asking_handler(true), false).await;
3174        assert_eq!(said, ["ask", "Which file?", "main.rs"]);
3175    }
3176
3177    /// `configuration.historyLength` caps the Task snapshots of a stream as
3178    /// it caps the task a blocking send returns.
3179    #[tokio::test]
3180    async fn test_streamed_task_snapshots_respect_history_length() {
3181        let handler = DefaultRequestHandler::new(
3182            ScriptedExecutor(|ctx: &ExecutorContext| {
3183                let history = ["one", "two", "three"]
3184                    .map(|text| Message::new(Role::User, vec![Part::text(text)]))
3185                    .to_vec();
3186                let task = Task {
3187                    id: ctx.task_id.clone(),
3188                    context_id: ctx.context_id.clone(),
3189                    status: TaskStatus {
3190                        state: TaskState::Completed,
3191                        message: None,
3192                        timestamp: None,
3193                    },
3194                    artifacts: None,
3195                    history: Some(history),
3196                    metadata: None,
3197                };
3198                vec![(None, Ok(StreamResponse::Task(task)))]
3199            }),
3200            InMemoryTaskStore::new(),
3201        );
3202        let request = SendMessageRequest {
3203            configuration: Some(SendMessageConfiguration {
3204                accepted_output_modes: None,
3205                task_push_notification_config: None,
3206                history_length: Some(1),
3207                return_immediately: None,
3208            }),
3209            ..send_request()
3210        };
3211        let events: Vec<_> = handler
3212            .send_streaming_message(&ServiceParams::new(), request)
3213            .await
3214            .unwrap()
3215            .collect()
3216            .await;
3217        assert!(matches!(
3218            &events[..],
3219            [Ok(StreamResponse::Task(task))] if task.history.as_ref().map(Vec::len) == Some(1)
3220        ));
3221    }
3222
3223    /// A Message after the task's own events is an invalid agent response,
3224    /// not the answer (§3.1.2), and the task fails.
3225    #[tokio::test]
3226    async fn test_message_after_task_events_is_an_invalid_agent_response() {
3227        let handler = DefaultRequestHandler::new(
3228            ScriptedExecutor(|ctx: &ExecutorContext| {
3229                vec![
3230                    (None, Ok(status_event(ctx, TaskState::Working, None))),
3231                    (
3232                        None,
3233                        Ok(StreamResponse::Message(Message::new(
3234                            Role::Agent,
3235                            vec![Part::text("late")],
3236                        ))),
3237                    ),
3238                ]
3239            }),
3240            InMemoryTaskStore::new(),
3241        );
3242        let error = handler
3243            .send_message(&ServiceParams::new(), send_request())
3244            .await
3245            .unwrap_err();
3246        assert_eq!(error.code, error_code::INVALID_AGENT_RESPONSE);
3247    }
3248
3249    /// Nothing may follow a Message that answered the request: the response
3250    /// stream ends at the Message (§3.1.2), and the later event fails the
3251    /// task in the store.
3252    #[tokio::test]
3253    async fn test_event_after_an_answering_message_fails_the_task_behind_the_closed_stream() {
3254        let handler = DefaultRequestHandler::new(
3255            ScriptedExecutor(|ctx: &ExecutorContext| {
3256                vec![
3257                    (
3258                        None,
3259                        Ok(StreamResponse::Message(Message::new(
3260                            Role::Agent,
3261                            vec![Part::text("answer")],
3262                        ))),
3263                    ),
3264                    (None, Ok(status_event(ctx, TaskState::Completed, None))),
3265                ]
3266            }),
3267            InMemoryTaskStore::new(),
3268        );
3269        let stream = handler
3270            .send_streaming_message(&ServiceParams::new(), send_request())
3271            .await
3272            .unwrap();
3273        let events = within(stream.collect::<Vec<_>>()).await;
3274        assert!(
3275            matches!(&events[..], [Ok(StreamResponse::Message(_))]),
3276            "{events:?}"
3277        );
3278
3279        let task_id = only_task_id(&handler).await;
3280        timeout(Duration::from_secs(5), async {
3281            while handler.execution_manager.get(&task_id).await.is_some() {
3282                tokio::task::yield_now().await;
3283            }
3284        })
3285        .await
3286        .unwrap();
3287        let task = handler
3288            .get_task(
3289                &ServiceParams::new(),
3290                GetTaskRequest {
3291                    id: task_id,
3292                    history_length: None,
3293                    tenant: None,
3294                },
3295            )
3296            .await
3297            .unwrap();
3298        assert_eq!(task.status.state, TaskState::Failed);
3299    }
3300
3301    /// The id of the one task the handler stores.
3302    async fn only_task_id(handler: &DefaultRequestHandler) -> TaskId {
3303        let listed = handler
3304            .list_tasks(
3305                &ServiceParams::new(),
3306                ListTasksRequest {
3307                    context_id: None,
3308                    status: None,
3309                    page_size: None,
3310                    page_token: None,
3311                    history_length: None,
3312                    status_timestamp_after: None,
3313                    include_artifacts: None,
3314                    tenant: None,
3315                },
3316            )
3317            .await
3318            .unwrap();
3319        assert_eq!(listed.tasks.len(), 1);
3320        listed.tasks[0].id.clone()
3321    }
3322
3323    /// An event after an answering Message is classified at the execution
3324    /// layer as an invalid agent response, before any response stream.
3325    #[tokio::test]
3326    async fn test_event_after_an_answering_message_is_published_as_an_invalid_agent_response() {
3327        let late = Arc::new(Notify::new());
3328        let handler = DefaultRequestHandler::new(
3329            ScriptedExecutor({
3330                let late = late.clone();
3331                move |ctx: &ExecutorContext| {
3332                    let message = Message::new(Role::Agent, vec![Part::text("answer")]);
3333                    vec![
3334                        (None, Ok(StreamResponse::Message(message))),
3335                        (
3336                            Some(late.clone()),
3337                            Ok(status_event(ctx, TaskState::Completed, None)),
3338                        ),
3339                    ]
3340                }
3341            }),
3342            InMemoryTaskStore::new(),
3343        );
3344        let _stream = handler
3345            .send_streaming_message(&ServiceParams::new(), send_request())
3346            .await
3347            .unwrap();
3348        let task_id = only_task_id(&handler).await;
3349        // The execution waits for `late`, so it is still registered.
3350        let mut events = handler
3351            .execution_manager
3352            .get(&task_id)
3353            .await
3354            .expect("the execution waits for its late event")
3355            .subscribe();
3356        late.notify_one();
3357        let result = within(async {
3358            loop {
3359                match events.recv().await.unwrap().result {
3360                    Ok(StreamResponse::Message(_)) => continue,
3361                    other => break other,
3362                }
3363            }
3364        })
3365        .await;
3366        assert!(
3367            matches!(&result, Err(error) if error.code == error_code::INVALID_AGENT_RESPONSE),
3368            "{result:?}"
3369        );
3370    }
3371
3372    /// Bounds a wait of a test, so a stream that stays open fails it.
3373    async fn within<T>(future: impl Future<Output = T>) -> T {
3374        timeout(Duration::from_secs(5), future)
3375            .await
3376            .expect("timed out")
3377    }
3378
3379    /// The gates of `cancel_race_handler`'s executor.
3380    #[derive(Default)]
3381    struct CancelRace {
3382        /// Releases the Message that answers any message but "ask".
3383        answer: Arc<Notify>,
3384        /// Notified when the cancel calls the executor: CANCELED is then
3385        /// committed and the cancel holds the execution.
3386        canceling: Arc<Notify>,
3387        /// Releases the cancel's CANCELED status.
3388        cancel_ends: Arc<Notify>,
3389    }
3390
3391    /// An executor that leaves the task awaiting input on "ask", answers any
3392    /// other message with a Message, and is canceled with CANCELED, each
3393    /// step behind the gates of the returned `CancelRace`.
3394    fn cancel_race_handler() -> (Arc<DefaultRequestHandler>, CancelRace) {
3395        let race = CancelRace::default();
3396        let (answer, canceling, cancel_ends) = (
3397            race.answer.clone(),
3398            race.canceling.clone(),
3399            race.cancel_ends.clone(),
3400        );
3401        let handler = DefaultRequestHandler::new(
3402            ScriptedExecutor(move |ctx: &ExecutorContext| match &ctx.message {
3403                Some(message) if message.text() == Some("ask") => {
3404                    vec![(None, Ok(status_event(ctx, TaskState::InputRequired, None)))]
3405                }
3406                Some(_) => {
3407                    let message = Message::new(Role::Agent, vec![Part::text("answer")]);
3408                    vec![(Some(answer.clone()), Ok(StreamResponse::Message(message)))]
3409                }
3410                None => {
3411                    canceling.notify_one();
3412                    vec![(
3413                        Some(cancel_ends.clone()),
3414                        Ok(status_event(ctx, TaskState::Canceled, None)),
3415                    )]
3416                }
3417            }),
3418            InMemoryTaskStore::new(),
3419        );
3420        (Arc::new(handler), race)
3421    }
3422
3423    fn start_cancel(
3424        handler: &Arc<DefaultRequestHandler>,
3425        task_id: &str,
3426    ) -> tokio::task::JoinHandle<Result<Task, A2AError>> {
3427        let handler = Arc::clone(handler);
3428        let request = CancelTaskRequest {
3429            id: task_id.into(),
3430            metadata: None,
3431            tenant: None,
3432        };
3433        tokio::spawn(async move { handler.cancel_task(&ServiceParams::new(), request).await })
3434    }
3435
3436    /// Releases a cancel `start_cancel` started and checks its own answer.
3437    async fn finish_cancel(
3438        race: &CancelRace,
3439        cancel: tokio::task::JoinHandle<Result<Task, A2AError>>,
3440    ) {
3441        race.cancel_ends.notify_one();
3442        let canceled = within(cancel).await.unwrap().unwrap();
3443        assert_eq!(canceled.status.state, TaskState::Canceled);
3444    }
3445
3446    /// §3.1.2: a Message answer is "exactly one Message object and then close
3447    /// immediately", also while a cancel of the request's task waits for the
3448    /// executor: the stream closes before the cancel ends, its CANCELED
3449    /// status never follows the Message, and the cancel itself succeeds.
3450    #[tokio::test]
3451    async fn test_message_answer_ends_the_stream_before_a_pending_cancel() {
3452        let (handler, race) = cancel_race_handler();
3453        let mut stream = handler
3454            .send_streaming_message(&ServiceParams::new(), send_request())
3455            .await
3456            .unwrap();
3457        let task_id = only_task_id(&handler).await;
3458        let cancel = start_cancel(&handler, &task_id);
3459        within(race.canceling.notified()).await;
3460        race.answer.notify_one();
3461
3462        assert!(matches!(
3463            within(stream.next()).await,
3464            Some(Ok(StreamResponse::Message(_)))
3465        ));
3466        assert!(within(stream.next()).await.is_none());
3467        assert!(!cancel.is_finished(), "the cancel is still pending");
3468        finish_cancel(&race, cancel).await;
3469    }
3470
3471    /// A subscription attached to the running execution ends at its Message
3472    /// too, while the cancel is pending.
3473    #[tokio::test]
3474    async fn test_message_answer_ends_an_attached_subscription_before_a_pending_cancel() {
3475        let (handler, race) = cancel_race_handler();
3476        let _stream = handler
3477            .send_streaming_message(&ServiceParams::new(), send_request())
3478            .await
3479            .unwrap();
3480        let task_id = only_task_id(&handler).await;
3481        let subscription = handler
3482            .subscribe_to_task(
3483                &ServiceParams::new(),
3484                SubscribeToTaskRequest {
3485                    id: task_id.clone(),
3486                    tenant: None,
3487                },
3488            )
3489            .await
3490            .unwrap();
3491        let cancel = start_cancel(&handler, &task_id);
3492        within(race.canceling.notified()).await;
3493        race.answer.notify_one();
3494
3495        let items = within(subscription.collect::<Vec<_>>()).await;
3496        assert!(
3497            matches!(
3498                &items[..],
3499                [Ok(StreamResponse::Task(task)), Ok(StreamResponse::Message(_))]
3500                    if task.status.state == TaskState::Submitted
3501            ),
3502            "{items:?}"
3503        );
3504        assert!(!cancel.is_finished(), "the cancel is still pending");
3505        finish_cancel(&race, cancel).await;
3506    }
3507
3508    /// A subscription waiting for a task's next turn follows that turn to its
3509    /// Message and ends there, while the cancel is pending.
3510    #[tokio::test]
3511    async fn test_message_answer_ends_a_waiting_subscription_before_a_pending_cancel() {
3512        let (handler, race) = cancel_race_handler();
3513        let params = ServiceParams::new();
3514        let ask = SendMessageRequest {
3515            message: Message::new(Role::User, vec![Part::text("ask")]),
3516            ..send_request()
3517        };
3518        let SendMessageResponse::Task(task) = handler.send_message(&params, ask).await.unwrap()
3519        else {
3520            panic!("expected a task awaiting input");
3521        };
3522        assert_eq!(task.status.state, TaskState::InputRequired);
3523        let subscription = handler
3524            .subscribe_to_task(
3525                &params,
3526                SubscribeToTaskRequest {
3527                    id: task.id.clone(),
3528                    tenant: None,
3529                },
3530            )
3531            .await
3532            .unwrap();
3533
3534        let follow_up = SendMessageRequest {
3535            message: Message {
3536                task_id: Some(task.id.clone()),
3537                ..Message::new(Role::User, vec![Part::text("go")])
3538            },
3539            ..send_request()
3540        };
3541        let _stream = handler
3542            .send_streaming_message(&params, follow_up)
3543            .await
3544            .unwrap();
3545        let cancel = start_cancel(&handler, &task.id);
3546        within(race.canceling.notified()).await;
3547        race.answer.notify_one();
3548
3549        // The stored task, the task as the turn found it, then the answer.
3550        let items = within(subscription.collect::<Vec<_>>()).await;
3551        assert!(
3552            matches!(
3553                &items[..],
3554                [
3555                    Ok(StreamResponse::Task(stored)),
3556                    Ok(StreamResponse::Task(found)),
3557                    Ok(StreamResponse::Message(_)),
3558                ] if stored.status.state == TaskState::InputRequired
3559                    && found.status.state == TaskState::InputRequired
3560            ),
3561            "{items:?}"
3562        );
3563        assert!(!cancel.is_finished(), "the cancel is still pending");
3564        finish_cancel(&race, cancel).await;
3565    }
3566
3567    #[tokio::test]
3568    async fn test_active_execution_drops_errors_without_subscribers() {
3569        let task = Task {
3570            id: "t-error-no-sub".into(),
3571            context_id: "c-error-no-sub".into(),
3572            status: TaskStatus {
3573                state: TaskState::Working,
3574                message: None,
3575                timestamp: None,
3576            },
3577            artifacts: None,
3578            history: None,
3579            metadata: None,
3580        };
3581        let active = ActiveExecution::new(task.clone());
3582        let error = A2AError::internal("execution failed");
3583
3584        // Publish error without any subscribers
3585        active.publish(Err(&error), Some(task.clone())).await;
3586
3587        // Resubscribe to verify snapshot was updated but no event was buffered
3588        let (mut receiver, snapshot_task, sequence) = active.resubscribe().await;
3589        assert_eq!(snapshot_task.unwrap().id, "t-error-no-sub");
3590        assert_eq!(sequence, 1);
3591        assert!(receiver.try_recv().is_err());
3592    }
3593
3594    #[tokio::test]
3595    async fn test_active_execution_publishes_events_with_snapshot_updates() {
3596        let initial_task = Task {
3597            id: "t-snapshot-update".into(),
3598            context_id: "c-snapshot-update".into(),
3599            status: TaskStatus {
3600                state: TaskState::Working,
3601                message: None,
3602                timestamp: None,
3603            },
3604            artifacts: None,
3605            history: None,
3606            metadata: None,
3607        };
3608        let active = ActiveExecution::new(initial_task.clone());
3609        let mut receiver = active.subscribe();
3610
3611        let updated_task = Task {
3612            id: "t-snapshot-update".into(),
3613            context_id: "c-snapshot-update".into(),
3614            status: TaskStatus {
3615                state: TaskState::Working,
3616                message: None,
3617                timestamp: None,
3618            },
3619            artifacts: None,
3620            history: None,
3621            metadata: None,
3622        };
3623
3624        let event = StreamResponse::Task(updated_task.clone());
3625        active.publish(Ok(&event), Some(updated_task.clone())).await;
3626
3627        // Verify event was published to subscriber
3628        let published = receiver.recv().await.unwrap();
3629        assert_eq!(published.sequence, 1);
3630        match published.result {
3631            Ok(StreamResponse::Task(task)) => {
3632                assert_eq!(task.id, "t-snapshot-update");
3633            }
3634            _ => panic!("expected Ok(Task) event"),
3635        }
3636
3637        // Verify snapshot was updated
3638        let (_, snapshot_task, sequence) = active.resubscribe().await;
3639        assert_eq!(snapshot_task.unwrap().id, "t-snapshot-update");
3640        assert_eq!(sequence, 1);
3641    }
3642
3643    #[tokio::test]
3644    async fn test_active_execution_broadcasts_to_multiple_subscribers() {
3645        let task = Task {
3646            id: "t-multi-sub".into(),
3647            context_id: "c-multi-sub".into(),
3648            status: TaskStatus {
3649                state: TaskState::Working,
3650                message: None,
3651                timestamp: None,
3652            },
3653            artifacts: None,
3654            history: None,
3655            metadata: None,
3656        };
3657        let active = ActiveExecution::new(task.clone());
3658
3659        // Create two subscribers
3660        let mut sub1 = active.subscribe();
3661        let mut sub2 = active.subscribe();
3662
3663        let event = StreamResponse::Task(task);
3664        active.publish(Ok(&event), None).await;
3665
3666        // Both subscribers should receive the same event
3667        let evt1 = sub1.recv().await.unwrap();
3668        let evt2 = sub2.recv().await.unwrap();
3669
3670        assert_eq!(evt1.sequence, 1);
3671        assert_eq!(evt2.sequence, 1);
3672        assert!(matches!(evt1.result, Ok(StreamResponse::Task(_))));
3673        assert!(matches!(evt2.result, Ok(StreamResponse::Task(_))));
3674    }
3675
3676    #[tokio::test]
3677    async fn test_get_task_not_found() {
3678        let handler = make_handler();
3679        let params = ServiceParams::new();
3680        let req = GetTaskRequest {
3681            id: "nonexistent".into(),
3682            history_length: None,
3683            tenant: None,
3684        };
3685        let result = handler.get_task(&params, req).await;
3686        assert!(result.is_err());
3687    }
3688
3689    // A2A §3.4.2 / §3.4.3: taskId and contextId rules on send_message (#248).
3690
3691    fn send_req(task_id: Option<&str>, context_id: Option<&str>) -> SendMessageRequest {
3692        let mut msg = make_message();
3693        msg.task_id = task_id.map(Into::into);
3694        msg.context_id = context_id.map(Into::into);
3695        SendMessageRequest {
3696            message: msg,
3697            configuration: None,
3698            metadata: None,
3699            tenant: None,
3700        }
3701    }
3702
3703    #[tokio::test]
3704    async fn test_send_message_rejects_unsupported_content_type() {
3705        install_crypto_provider();
3706        let handler = make_handler().with_default_input_modes(vec!["text/plain".into()]);
3707        let mut req = send_req(None, None);
3708        req.message.parts = vec![
3709            Part::data(serde_json::json!({"value": "unsupported"}))
3710                .with_media_type("application/x-unsupported-type-12345"),
3711        ];
3712        let err = handler
3713            .send_message(&ServiceParams::new(), req)
3714            .await
3715            .expect_err("an undeclared content type must be rejected");
3716        assert_eq!(err.code, error_code::CONTENT_TYPE_NOT_SUPPORTED);
3717    }
3718
3719    #[tokio::test]
3720    async fn test_send_message_accepts_a_declared_content_type() {
3721        install_crypto_provider();
3722        let handler = make_handler().with_default_input_modes(vec!["text/plain".into()]);
3723        let mut req = send_req(None, None);
3724        req.message.parts = vec![Part::text("hello").with_media_type("text/plain")];
3725        handler
3726            .send_message(&ServiceParams::new(), req)
3727            .await
3728            .expect("a declared content type must be accepted");
3729    }
3730
3731    #[tokio::test]
3732    async fn test_send_message_allows_any_content_type_when_none_declared() {
3733        install_crypto_provider();
3734        let handler = make_handler();
3735        let mut req = send_req(None, None);
3736        req.message.parts = vec![
3737            Part::data(serde_json::json!({"value": "x"})).with_media_type("application/x-anything"),
3738        ];
3739        handler
3740            .send_message(&ServiceParams::new(), req)
3741            .await
3742            .expect("no declared modes means no restriction");
3743    }
3744
3745    #[tokio::test]
3746    async fn test_send_message_unknown_task_id_is_not_found() {
3747        install_crypto_provider();
3748        let handler = make_handler();
3749        // §3.4.2: a client-provided taskId MUST reference an existing task, and
3750        // MUST NOT create one. Silently minting a task here is what let a
3751        // mistyped or replayed id start a fresh conversation.
3752        let err = handler
3753            .send_message(&ServiceParams::new(), send_req(Some("t-absent"), None))
3754            .await
3755            .expect_err("an unknown taskId must not create a task");
3756        assert_eq!(err.code, error_code::TASK_NOT_FOUND);
3757        assert!(
3758            handler.task_store.get("t-absent").await.unwrap().is_none(),
3759            "the rejected id must not have been created"
3760        );
3761    }
3762
3763    #[tokio::test]
3764    async fn test_send_message_to_terminal_task_is_rejected() {
3765        install_crypto_provider();
3766        let handler = make_handler();
3767        handler
3768            .task_store
3769            .create(Task {
3770                id: "t-done".into(),
3771                context_id: "c-done".into(),
3772                status: TaskStatus {
3773                    state: TaskState::Completed,
3774                    message: None,
3775                    timestamp: None,
3776                },
3777                artifacts: None,
3778                history: None,
3779                metadata: None,
3780            })
3781            .await
3782            .unwrap();
3783        let err = handler
3784            .send_message(&ServiceParams::new(), send_req(Some("t-done"), None))
3785            .await
3786            .expect_err("a follow-up to a terminal task must not be accepted");
3787        assert_eq!(err.code, error_code::UNSUPPORTED_OPERATION);
3788    }
3789
3790    #[tokio::test]
3791    async fn test_send_message_mismatched_context_id_is_rejected() {
3792        install_crypto_provider();
3793        let handler = make_handler();
3794        seed_task(&handler, "t-ctx", "c-real").await;
3795        // §3.4.3: previously the stored contextId silently won, so a client
3796        // addressing the wrong conversation was never told.
3797        let err = handler
3798            .send_message(
3799                &ServiceParams::new(),
3800                send_req(Some("t-ctx"), Some("c-wrong")),
3801            )
3802            .await
3803            .expect_err("a mismatching contextId must be rejected");
3804        assert_eq!(err.code, error_code::INVALID_PARAMS);
3805        assert!(
3806            err.message.contains("c-wrong"),
3807            "error names the bad id: {}",
3808            err.message
3809        );
3810    }
3811
3812    #[tokio::test]
3813    async fn test_send_message_matching_context_id_is_accepted() {
3814        install_crypto_provider();
3815        let handler = make_handler();
3816        seed_task(&handler, "t-ok", "c-ok").await;
3817        handler
3818            .send_message(&ServiceParams::new(), send_req(Some("t-ok"), Some("c-ok")))
3819            .await
3820            .expect("a matching pair must be accepted");
3821    }
3822
3823    #[tokio::test]
3824    async fn test_send_message_accumulates_history_across_turns() {
3825        // ACTS CORE-HIST-005/006: a multi-turn conversation's history must
3826        // include every turn's message, not just the one that created the
3827        // task. MultiTurnExecutor only ever emits a StatusUpdate, so this
3828        // exercises prepare_task_for_execution's continuation path exactly
3829        // as a real executor (which never touches history itself) does.
3830        install_crypto_provider();
3831        let handler = DefaultRequestHandler::new(MultiTurnExecutor, InMemoryTaskStore::new());
3832
3833        let mut turn1 = make_message();
3834        turn1.parts = vec![Part::text("turn one")];
3835        let resp1 = handler
3836            .send_message(
3837                &ServiceParams::new(),
3838                SendMessageRequest {
3839                    message: turn1,
3840                    configuration: None,
3841                    metadata: None,
3842                    tenant: None,
3843                },
3844            )
3845            .await
3846            .unwrap();
3847        let task_id = match resp1 {
3848            SendMessageResponse::Task(t) => t.id,
3849            SendMessageResponse::Message(_) => panic!("expected a task"),
3850        };
3851
3852        for text in ["turn two", "done"] {
3853            let mut turn = make_message();
3854            turn.task_id = Some(task_id.clone());
3855            turn.parts = vec![Part::text(text)];
3856            handler
3857                .send_message(
3858                    &ServiceParams::new(),
3859                    SendMessageRequest {
3860                        message: turn,
3861                        configuration: None,
3862                        metadata: None,
3863                        tenant: None,
3864                    },
3865                )
3866                .await
3867                .unwrap();
3868        }
3869
3870        let task = handler.task_store.get(&task_id).await.unwrap().unwrap();
3871        let history = task.history.expect("history must accumulate across turns");
3872        let texts: Vec<_> = history.iter().map(|m| m.text()).collect();
3873        assert_eq!(
3874            texts,
3875            vec![Some("turn one"), Some("turn two"), Some("done")]
3876        );
3877    }
3878
3879    #[tokio::test]
3880    async fn test_send_message_applies_configuration_history_length_to_its_own_response() {
3881        // ACTS CORE-HIST-003: configuration.historyLength must govern
3882        // SendMessage's own inline task the same way history_length governs
3883        // a later GetTask, rather than always including the just-sent
3884        // message regardless of what was asked for.
3885        install_crypto_provider();
3886        let handler = DefaultRequestHandler::new(MultiTurnExecutor, InMemoryTaskStore::new());
3887        let mut message = make_message();
3888        message.parts = vec![Part::text("done")];
3889        let resp = handler
3890            .send_message(
3891                &ServiceParams::new(),
3892                SendMessageRequest {
3893                    message,
3894                    configuration: Some(SendMessageConfiguration {
3895                        accepted_output_modes: None,
3896                        task_push_notification_config: None,
3897                        history_length: Some(0),
3898                        return_immediately: None,
3899                    }),
3900                    metadata: None,
3901                    tenant: None,
3902                },
3903            )
3904            .await
3905            .unwrap();
3906        let task = match resp {
3907            SendMessageResponse::Task(t) => t,
3908            SendMessageResponse::Message(_) => panic!("expected a task"),
3909        };
3910        assert!(
3911            task.history.is_none_or(|h| h.is_empty()),
3912            "historyLength=0 must clear history on SendMessage's own response"
3913        );
3914    }
3915
3916    #[tokio::test]
3917    async fn test_send_message_infers_context_id_from_the_task() {
3918        install_crypto_provider();
3919        let handler = make_handler();
3920        seed_task(&handler, "t-infer", "c-infer").await;
3921        // §3.4.3: contextId MUST be inferred when only taskId is given.
3922        handler
3923            .send_message(&ServiceParams::new(), send_req(Some("t-infer"), None))
3924            .await
3925            .unwrap();
3926        let task = handler.task_store.get("t-infer").await.unwrap().unwrap();
3927        assert_eq!(task.context_id, "c-infer");
3928    }
3929
3930    #[tokio::test]
3931    async fn test_send_message_without_task_id_still_creates_one() {
3932        install_crypto_provider();
3933        let handler = make_handler();
3934        // The server generates the id. A contextId alone is allowed and starts
3935        // a new task within that conversation.
3936        let resp = handler
3937            .send_message(&ServiceParams::new(), send_req(None, Some("c-new")))
3938            .await
3939            .expect("a message with no taskId must still create a task");
3940        let _ = resp;
3941        let listed = handler
3942            .task_store
3943            .list(&ListTasksRequest {
3944                context_id: Some("c-new".into()),
3945                status: None,
3946                page_size: None,
3947                page_token: None,
3948                history_length: None,
3949                include_artifacts: None,
3950                status_timestamp_after: None,
3951                tenant: None,
3952            })
3953            .await
3954            .unwrap();
3955        assert_eq!(listed.tasks.len(), 1);
3956        assert_eq!(listed.tasks[0].context_id, "c-new");
3957    }
3958
3959    #[tokio::test]
3960    async fn test_get_task_after_send() {
3961        let handler = make_handler();
3962        let params = ServiceParams::new();
3963        let mut msg = make_message();
3964        msg.task_id = Some("t1".into());
3965        msg.context_id = Some("c1".into());
3966        seed_task(&handler, "t1", "c1").await;
3967        let req = SendMessageRequest {
3968            message: msg,
3969            configuration: None,
3970            metadata: None,
3971            tenant: None,
3972        };
3973        handler.send_message(&params, req).await.unwrap();
3974        let task = handler
3975            .get_task(
3976                &params,
3977                GetTaskRequest {
3978                    id: "t1".into(),
3979                    history_length: None,
3980                    tenant: None,
3981                },
3982            )
3983            .await
3984            .unwrap();
3985        assert_eq!(task.id, "t1");
3986    }
3987
3988    #[tokio::test]
3989    async fn test_list_tasks() {
3990        let handler = make_handler();
3991        let params = ServiceParams::new();
3992        let req = ListTasksRequest {
3993            context_id: None,
3994            status: None,
3995            page_size: None,
3996            page_token: None,
3997            history_length: None,
3998            status_timestamp_after: None,
3999            include_artifacts: None,
4000            tenant: None,
4001        };
4002        let resp = handler.list_tasks(&params, req).await.unwrap();
4003        assert!(resp.tasks.is_empty());
4004    }
4005
4006    /// ListTasks omits artifacts unless `includeArtifacts` is true (§3.1.4).
4007    #[tokio::test]
4008    async fn test_list_tasks_includes_artifacts_only_on_request() {
4009        let store = InMemoryTaskStore::new();
4010        store
4011            .create(Task {
4012                id: "t-artifact".into(),
4013                context_id: "ctx".into(),
4014                status: TaskStatus {
4015                    state: TaskState::Completed,
4016                    message: None,
4017                    timestamp: Some(chrono::Utc::now()),
4018                },
4019                artifacts: Some(vec![Artifact {
4020                    artifact_id: "a1".into(),
4021                    name: None,
4022                    description: None,
4023                    parts: vec![Part::text("result")],
4024                    metadata: None,
4025                    extensions: None,
4026                }]),
4027                history: None,
4028                metadata: None,
4029            })
4030            .await
4031            .unwrap();
4032        let handler = DefaultRequestHandler::new(EchoExecutor, store);
4033        let params = ServiceParams::new();
4034        for (include_artifacts, expected) in
4035            [(None, false), (Some(false), false), (Some(true), true)]
4036        {
4037            let resp = handler
4038                .list_tasks(
4039                    &params,
4040                    ListTasksRequest {
4041                        context_id: None,
4042                        status: None,
4043                        page_size: None,
4044                        page_token: None,
4045                        history_length: None,
4046                        status_timestamp_after: None,
4047                        include_artifacts,
4048                        tenant: None,
4049                    },
4050                )
4051                .await
4052                .unwrap();
4053            assert_eq!(
4054                resp.tasks[0].artifacts.is_some(),
4055                expected,
4056                "include_artifacts={include_artifacts:?}"
4057            );
4058        }
4059    }
4060
4061    #[tokio::test]
4062    async fn test_cancel_task_not_found() {
4063        let handler = make_handler();
4064        let params = ServiceParams::new();
4065        let req = CancelTaskRequest {
4066            id: "nonexistent".into(),
4067            metadata: None,
4068            tenant: None,
4069        };
4070        let result = handler.cancel_task(&params, req).await;
4071        assert!(result.is_err());
4072    }
4073
4074    #[tokio::test]
4075    async fn test_cancel_task_working() {
4076        let handler = make_handler();
4077        let params = ServiceParams::new();
4078        // First create a task via the store directly
4079        let task = Task {
4080            id: "t2".into(),
4081            context_id: "c2".into(),
4082            status: TaskStatus {
4083                state: TaskState::Working,
4084                message: None,
4085                timestamp: None,
4086            },
4087            artifacts: None,
4088            history: None,
4089            metadata: None,
4090        };
4091        handler.task_store.create(task).await.unwrap();
4092        let req = CancelTaskRequest {
4093            id: "t2".into(),
4094            metadata: None,
4095            tenant: None,
4096        };
4097        let result = handler.cancel_task(&params, req).await.unwrap();
4098        assert_eq!(result.status.state, TaskState::Canceled);
4099    }
4100
4101    #[tokio::test]
4102    async fn test_cancel_task_concurrent_both_succeed_idempotently() {
4103        let handler = Arc::new(make_handler());
4104        let params = ServiceParams::new();
4105        let task = Task {
4106            id: "t-race".into(),
4107            context_id: "c-race".into(),
4108            status: TaskStatus {
4109                state: TaskState::Working,
4110                message: None,
4111                timestamp: None,
4112            },
4113            artifacts: None,
4114            history: None,
4115            metadata: None,
4116        };
4117        handler.task_store.create(task).await.unwrap();
4118
4119        let handlers = vec![Arc::clone(&handler), Arc::clone(&handler)];
4120        let mut results = Vec::new();
4121        for handler in handlers {
4122            let params = params.clone();
4123            let req = CancelTaskRequest {
4124                id: "t-race".into(),
4125                metadata: None,
4126                tenant: None,
4127            };
4128            results.push(tokio::spawn(async move {
4129                handler.cancel_task(&params, req).await
4130            }));
4131        }
4132        for result in results {
4133            let task = result.await.unwrap().unwrap();
4134            assert_eq!(task.status.state, TaskState::Canceled);
4135        }
4136    }
4137
4138    #[tokio::test]
4139    async fn test_cancel_task_already_completed() {
4140        let handler = make_handler();
4141        let params = ServiceParams::new();
4142        let task = Task {
4143            id: "t3".into(),
4144            context_id: "c3".into(),
4145            status: TaskStatus {
4146                state: TaskState::Completed,
4147                message: None,
4148                timestamp: None,
4149            },
4150            artifacts: None,
4151            history: None,
4152            metadata: None,
4153        };
4154        handler.task_store.create(task).await.unwrap();
4155        let req = CancelTaskRequest {
4156            id: "t3".into(),
4157            metadata: None,
4158            tenant: None,
4159        };
4160        let result = handler.cancel_task(&params, req).await;
4161        match result {
4162            Ok(_) => panic!("expected cancel of COMPLETED to fail"),
4163            Err(error) => assert_eq!(error.code, error_code::TASK_NOT_CANCELABLE),
4164        }
4165    }
4166
4167    #[tokio::test]
4168    async fn test_cancel_task_already_canceled_is_idempotent() {
4169        let handler = make_handler();
4170        let params = ServiceParams::new();
4171        let task = Task {
4172            id: "t-canceled".into(),
4173            context_id: "c-canceled".into(),
4174            status: TaskStatus {
4175                state: TaskState::Canceled,
4176                message: None,
4177                timestamp: None,
4178            },
4179            artifacts: None,
4180            history: None,
4181            metadata: None,
4182        };
4183        handler.task_store.create(task).await.unwrap();
4184        let req = CancelTaskRequest {
4185            id: "t-canceled".into(),
4186            metadata: None,
4187            tenant: None,
4188        };
4189        let result = handler.cancel_task(&params, req).await.unwrap();
4190        assert_eq!(result.status.state, TaskState::Canceled);
4191    }
4192
4193    #[tokio::test]
4194    async fn test_cancel_task_failed_and_rejected_are_not_cancelable() {
4195        let handler = make_handler();
4196        let params = ServiceParams::new();
4197        for (id, state) in [
4198            ("t-failed", TaskState::Failed),
4199            ("t-rejected", TaskState::Rejected),
4200        ] {
4201            handler
4202                .task_store
4203                .create(Task {
4204                    id: id.into(),
4205                    context_id: format!("c-{id}"),
4206                    status: TaskStatus {
4207                        state,
4208                        message: None,
4209                        timestamp: None,
4210                    },
4211                    artifacts: None,
4212                    history: None,
4213                    metadata: None,
4214                })
4215                .await
4216                .unwrap();
4217            let result = handler
4218                .cancel_task(
4219                    &params,
4220                    CancelTaskRequest {
4221                        id: id.into(),
4222                        metadata: None,
4223                        tenant: None,
4224                    },
4225                )
4226                .await;
4227            match result {
4228                Ok(_) => panic!("expected cancel of {id} to fail"),
4229                Err(error) => assert_eq!(error.code, error_code::TASK_NOT_CANCELABLE),
4230            }
4231        }
4232    }
4233
4234    fn task_with_history(id: &str, context_id: &str, n: usize) -> Task {
4235        Task {
4236            id: id.into(),
4237            context_id: context_id.into(),
4238            status: TaskStatus {
4239                state: TaskState::Completed,
4240                message: None,
4241                timestamp: None,
4242            },
4243            artifacts: None,
4244            history: Some(
4245                (0..n)
4246                    .map(|i| Message::new(Role::User, vec![Part::text(format!("m{i}"))]))
4247                    .collect(),
4248            ),
4249            metadata: None,
4250        }
4251    }
4252
4253    #[tokio::test]
4254    async fn test_get_task_applies_history_length() {
4255        let handler = make_handler();
4256        let params = ServiceParams::new();
4257        handler
4258            .task_store
4259            .create(task_with_history("hist", "c", 3))
4260            .await
4261            .unwrap();
4262
4263        let full = handler
4264            .get_task(
4265                &params,
4266                GetTaskRequest {
4267                    id: "hist".into(),
4268                    history_length: None,
4269                    tenant: None,
4270                },
4271            )
4272            .await
4273            .unwrap();
4274        assert_eq!(full.history.as_ref().unwrap().len(), 3);
4275
4276        let last = handler
4277            .get_task(
4278                &params,
4279                GetTaskRequest {
4280                    id: "hist".into(),
4281                    history_length: Some(1),
4282                    tenant: None,
4283                },
4284            )
4285            .await
4286            .unwrap();
4287        assert_eq!(last.history.as_ref().unwrap().len(), 1);
4288
4289        for hl in [0, -1] {
4290            let empty = handler
4291                .get_task(
4292                    &params,
4293                    GetTaskRequest {
4294                        id: "hist".into(),
4295                        history_length: Some(hl),
4296                        tenant: None,
4297                    },
4298                )
4299                .await
4300                .unwrap();
4301            assert!(
4302                empty.history.as_ref().unwrap().is_empty(),
4303                "history_length={hl} must clear history"
4304            );
4305        }
4306    }
4307
4308    fn reject_unauthenticated(
4309        _params: &ServiceParams,
4310        _task_id: Option<&str>,
4311    ) -> Result<(), A2AError> {
4312        Err(A2AError::invalid_request("authentication required"))
4313    }
4314
4315    #[tokio::test]
4316    async fn test_authorizer_rejects_handler_methods() {
4317        let handler = DefaultRequestHandler::new(EchoExecutor, InMemoryTaskStore::new())
4318            .with_authorizer(reject_unauthenticated)
4319            .with_push_config_store(InMemoryPushConfigStore::new());
4320        let params = ServiceParams::new();
4321
4322        assert!(
4323            handler
4324                .send_message(
4325                    &params,
4326                    SendMessageRequest {
4327                        message: make_message(),
4328                        configuration: None,
4329                        metadata: None,
4330                        tenant: None,
4331                    },
4332                )
4333                .await
4334                .is_err()
4335        );
4336        assert!(
4337            handler
4338                .get_task(
4339                    &params,
4340                    GetTaskRequest {
4341                        id: "t".into(),
4342                        history_length: None,
4343                        tenant: None,
4344                    },
4345                )
4346                .await
4347                .is_err()
4348        );
4349        assert!(
4350            handler
4351                .list_tasks(
4352                    &params,
4353                    ListTasksRequest {
4354                        context_id: None,
4355                        status: None,
4356                        page_size: None,
4357                        page_token: None,
4358                        history_length: None,
4359                        status_timestamp_after: None,
4360                        include_artifacts: None,
4361                        tenant: None,
4362                    },
4363                )
4364                .await
4365                .is_err()
4366        );
4367        assert!(
4368            handler
4369                .cancel_task(
4370                    &params,
4371                    CancelTaskRequest {
4372                        id: "t".into(),
4373                        metadata: None,
4374                        tenant: None,
4375                    },
4376                )
4377                .await
4378                .is_err()
4379        );
4380        assert!(
4381            handler
4382                .subscribe_to_task(
4383                    &params,
4384                    SubscribeToTaskRequest {
4385                        id: "t".into(),
4386                        tenant: None,
4387                    },
4388                )
4389                .await
4390                .is_err()
4391        );
4392        assert!(
4393            handler
4394                .create_push_config(
4395                    &params,
4396                    TaskPushNotificationConfig {
4397                        url: "https://example.com/push".into(),
4398                        id: None,
4399                        task_id: "t".into(),
4400                        token: None,
4401                        authentication: None,
4402                        tenant: None,
4403                    },
4404                )
4405                .await
4406                .is_err()
4407        );
4408        assert!(
4409            handler
4410                .get_push_config(
4411                    &params,
4412                    GetTaskPushNotificationConfigRequest {
4413                        task_id: "t".into(),
4414                        id: "cfg".into(),
4415                        tenant: None,
4416                    },
4417                )
4418                .await
4419                .is_err()
4420        );
4421        assert!(
4422            handler
4423                .list_push_configs(
4424                    &params,
4425                    ListTaskPushNotificationConfigsRequest {
4426                        task_id: "t".into(),
4427                        page_size: None,
4428                        page_token: None,
4429                        tenant: None,
4430                    },
4431                )
4432                .await
4433                .is_err()
4434        );
4435        assert!(
4436            handler
4437                .delete_push_config(
4438                    &params,
4439                    DeleteTaskPushNotificationConfigRequest {
4440                        task_id: "t".into(),
4441                        id: "cfg".into(),
4442                        tenant: None,
4443                    },
4444                )
4445                .await
4446                .is_err()
4447        );
4448        assert!(
4449            handler
4450                .get_extended_agent_card(&params, GetExtendedAgentCardRequest { tenant: None })
4451                .await
4452                .is_err()
4453        );
4454    }
4455
4456    #[tokio::test]
4457    async fn test_subscribe_to_an_unknown_task_is_not_found() {
4458        let handler = make_handler();
4459        let params = ServiceParams::new();
4460        let req = SubscribeToTaskRequest {
4461            id: "t1".into(),
4462            tenant: None,
4463        };
4464        let result = handler.subscribe_to_task(&params, req).await;
4465        match result {
4466            Ok(_) => panic!("expected subscribe_to_task to fail"),
4467            Err(error) => assert_eq!(error.code, error_code::TASK_NOT_FOUND),
4468        }
4469        assert!(handler.execution_manager.waiting().is_empty());
4470    }
4471
4472    #[tokio::test]
4473    async fn test_subscribe_to_terminal_task_is_unsupported_not_not_found() {
4474        let handler = make_handler();
4475        handler
4476            .task_store
4477            .create(Task {
4478                id: "t-done".into(),
4479                context_id: "c-done".into(),
4480                status: TaskStatus {
4481                    state: TaskState::Completed,
4482                    message: None,
4483                    timestamp: None,
4484                },
4485                artifacts: None,
4486                history: None,
4487                metadata: None,
4488            })
4489            .await
4490            .unwrap();
4491        let result = handler
4492            .subscribe_to_task(
4493                &ServiceParams::new(),
4494                SubscribeToTaskRequest {
4495                    id: "t-done".into(),
4496                    tenant: None,
4497                },
4498            )
4499            .await;
4500        match result {
4501            Ok(_) => panic!("expected subscribe_to_task to fail"),
4502            Err(error) => assert_eq!(error.code, error_code::UNSUPPORTED_OPERATION),
4503        }
4504        assert!(handler.execution_manager.waiting().is_empty());
4505    }
4506
4507    #[tokio::test]
4508    async fn test_subscribe_to_a_task_awaiting_input_opens_with_the_stored_task() {
4509        let handler = make_input_required_handler();
4510        let params = ServiceParams::new();
4511        let task = task_awaiting_input(&handler).await;
4512        let stored = handler
4513            .get_task(
4514                &params,
4515                GetTaskRequest {
4516                    id: task.id.clone(),
4517                    history_length: None,
4518                    tenant: None,
4519                },
4520            )
4521            .await
4522            .unwrap();
4523        assert_eq!(stored.status.state, TaskState::InputRequired);
4524
4525        let mut subscription = handler
4526            .subscribe_to_task(
4527                &params,
4528                SubscribeToTaskRequest {
4529                    id: task.id.clone(),
4530                    tenant: None,
4531                },
4532            )
4533            .await
4534            .unwrap();
4535        match subscription.next().await.unwrap().unwrap() {
4536            StreamResponse::Task(first) => assert_eq!(first, stored),
4537            other => panic!("expected the stored task first, got {other:?}"),
4538        }
4539    }
4540
4541    #[tokio::test]
4542    async fn test_cancel_ends_a_subscription_to_a_task_awaiting_input() {
4543        let handler = make_input_required_handler();
4544        let params = ServiceParams::new();
4545        let task = task_awaiting_input(&handler).await;
4546        let subscription = handler
4547            .subscribe_to_task(
4548                &params,
4549                SubscribeToTaskRequest {
4550                    id: task.id.clone(),
4551                    tenant: None,
4552                },
4553            )
4554            .await
4555            .unwrap();
4556
4557        let canceled = handler
4558            .cancel_task(
4559                &params,
4560                CancelTaskRequest {
4561                    id: task.id.clone(),
4562                    metadata: None,
4563                    tenant: None,
4564                },
4565            )
4566            .await
4567            .unwrap();
4568        assert_eq!(canceled.status.state, TaskState::Canceled);
4569
4570        // The stored task, then the canceled one, and the stream ends.
4571        let events: Vec<_> = timeout(Duration::from_secs(5), subscription.collect())
4572            .await
4573            .expect("the subscription outlived the canceled task");
4574        assert!(matches!(
4575            events.as_slice(),
4576            [Ok(StreamResponse::Task(stored)), Ok(StreamResponse::Task(last))]
4577                if stored.status.state == TaskState::InputRequired
4578                    && last.status.state == TaskState::Canceled
4579        ));
4580        assert!(handler.execution_manager.waiting().is_empty());
4581    }
4582
4583    #[tokio::test]
4584    async fn test_cancel_failing_part_way_still_ends_a_waiting_subscription() {
4585        for (cancel, code) in [
4586            (Cancel::Fails, error_code::INTERNAL_ERROR),
4587            (
4588                Cancel::SendsAnInapplicableEvent,
4589                error_code::INVALID_AGENT_RESPONSE,
4590            ),
4591        ] {
4592            let handler = DefaultRequestHandler::new(
4593                InputRequiredExecutor { cancel },
4594                InMemoryTaskStore::new(),
4595            );
4596            let params = ServiceParams::new();
4597            let task = task_awaiting_input(&handler).await;
4598            let subscription = handler
4599                .subscribe_to_task(
4600                    &params,
4601                    SubscribeToTaskRequest {
4602                        id: task.id.clone(),
4603                        tenant: None,
4604                    },
4605                )
4606                .await
4607                .unwrap();
4608
4609            let error = handler
4610                .cancel_task(
4611                    &params,
4612                    CancelTaskRequest {
4613                        id: task.id.clone(),
4614                        metadata: None,
4615                        tenant: None,
4616                    },
4617                )
4618                .await
4619                .unwrap_err();
4620            assert_eq!(error.code, code);
4621
4622            // The store holds the task canceled before the executor ran.
4623            let events: Vec<_> = timeout(Duration::from_secs(5), subscription.collect())
4624                .await
4625                .expect("the subscription outlived the canceled task");
4626            assert!(matches!(
4627                events.as_slice(),
4628                [Ok(StreamResponse::Task(stored)), Ok(StreamResponse::Task(last))]
4629                    if stored.status.state == TaskState::InputRequired
4630                        && last.status.state == TaskState::Canceled
4631            ));
4632            assert!(handler.execution_manager.waiting().is_empty());
4633        }
4634    }
4635
4636    #[tokio::test]
4637    async fn test_subscriptions_to_a_task_awaiting_input_follow_its_next_turn() {
4638        let handler = make_input_required_handler();
4639        let params = ServiceParams::new();
4640        let task = task_awaiting_input(&handler).await;
4641        let subscribe = || SubscribeToTaskRequest {
4642            id: task.id.clone(),
4643            tenant: None,
4644        };
4645        let first = handler
4646            .subscribe_to_task(&params, subscribe())
4647            .await
4648            .unwrap();
4649        let second = handler
4650            .subscribe_to_task(&params, subscribe())
4651            .await
4652            .unwrap();
4653
4654        // The whole next turn runs before either stream is polled: what it
4655        // publishes must still reach both.
4656        let mut follow_up = make_message();
4657        follow_up.task_id = Some(task.id.clone());
4658        let response = handler
4659            .send_message(
4660                &params,
4661                SendMessageRequest {
4662                    message: follow_up,
4663                    configuration: None,
4664                    metadata: None,
4665                    tenant: None,
4666                },
4667            )
4668            .await
4669            .unwrap();
4670        assert!(matches!(
4671            response,
4672            SendMessageResponse::Task(task) if task.status.state == TaskState::Completed
4673        ));
4674
4675        // The stored task, the task as the turn found it, then the turn.
4676        let follows_the_turn = |events: Vec<Result<StreamResponse, A2AError>>| {
4677            matches!(
4678                events.as_slice(),
4679                [
4680                    Ok(StreamResponse::Task(stored)),
4681                    Ok(StreamResponse::Task(found)),
4682                    Ok(StreamResponse::StatusUpdate(turn)),
4683                ] if stored.status.state == TaskState::InputRequired
4684                    && found.status.state == TaskState::InputRequired
4685                    && turn.status.state == TaskState::Completed
4686            )
4687        };
4688        assert!(follows_the_turn(first.collect().await));
4689        assert!(follows_the_turn(second.collect().await));
4690
4691        // Over: a new subscription is refused as for any finished task.
4692        let result = handler.subscribe_to_task(&params, subscribe()).await;
4693        assert!(matches!(result, Err(error) if error.code == error_code::UNSUPPORTED_OPERATION));
4694    }
4695
4696    #[tokio::test]
4697    async fn test_a_dropped_subscription_to_a_task_awaiting_input_unregisters() {
4698        let handler = make_input_required_handler();
4699        let params = ServiceParams::new();
4700        let task = task_awaiting_input(&handler).await;
4701        let subscription = handler
4702            .subscribe_to_task(
4703                &params,
4704                SubscribeToTaskRequest {
4705                    id: task.id.clone(),
4706                    tenant: None,
4707                },
4708            )
4709            .await
4710            .unwrap();
4711        assert_eq!(handler.execution_manager.waiting().len(), 1);
4712        drop(subscription);
4713        assert!(handler.execution_manager.waiting().is_empty());
4714    }
4715
4716    #[tokio::test]
4717    async fn test_send_message_return_immediately_allows_resubscribe() {
4718        use futures::StreamExt;
4719
4720        let (handler, release) = make_resumable_handler();
4721        let params = ServiceParams::new();
4722        let mut message = make_message();
4723        message.task_id = Some("t-resume".into());
4724        message.context_id = Some("c-resume".into());
4725        seed_task(&handler, "t-resume", "c-resume").await;
4726
4727        let response = handler
4728            .send_message(
4729                &params,
4730                SendMessageRequest {
4731                    message,
4732                    configuration: Some(SendMessageConfiguration {
4733                        accepted_output_modes: None,
4734                        task_push_notification_config: None,
4735                        history_length: None,
4736                        return_immediately: Some(true),
4737                    }),
4738                    metadata: None,
4739                    tenant: None,
4740                },
4741            )
4742            .await
4743            .unwrap();
4744
4745        match response {
4746            SendMessageResponse::Task(task) => {
4747                assert_eq!(task.status.state, TaskState::Working);
4748            }
4749            _ => panic!("expected Task response"),
4750        }
4751
4752        let mut subscription = handler
4753            .subscribe_to_task(
4754                &params,
4755                SubscribeToTaskRequest {
4756                    id: "t-resume".into(),
4757                    tenant: None,
4758                },
4759            )
4760            .await
4761            .unwrap();
4762
4763        let snapshot = subscription.next().await.unwrap().unwrap();
4764        match snapshot {
4765            StreamResponse::Task(task) => assert_eq!(task.status.state, TaskState::Working),
4766            _ => panic!("expected snapshot task"),
4767        }
4768
4769        release.notify_waiters();
4770
4771        let terminal = subscription.next().await.unwrap().unwrap();
4772        match terminal {
4773            StreamResponse::Task(task) => assert_eq!(task.status.state, TaskState::Completed),
4774            _ => panic!("expected terminal task"),
4775        }
4776
4777        assert!(subscription.next().await.is_none());
4778
4779        let result = handler
4780            .subscribe_to_task(
4781                &params,
4782                SubscribeToTaskRequest {
4783                    id: "t-resume".into(),
4784                    tenant: None,
4785                },
4786            )
4787            .await;
4788        match result {
4789            Ok(_) => panic!("expected subscribe_to_task to fail after completion"),
4790            Err(error) => assert_eq!(error.code, error_code::UNSUPPORTED_OPERATION),
4791        }
4792    }
4793
4794    #[tokio::test]
4795    async fn test_push_config_not_supported_without_store() {
4796        let handler = make_handler();
4797        let params = ServiceParams::new();
4798        let result = handler
4799            .create_push_config(
4800                &params,
4801                TaskPushNotificationConfig {
4802                    task_id: "t1".into(),
4803                    url: "http://example.com".into(),
4804                    id: None,
4805                    token: None,
4806                    authentication: None,
4807                    tenant: None,
4808                },
4809            )
4810            .await;
4811        assert!(result.is_err());
4812    }
4813
4814    #[tokio::test]
4815    async fn test_list_push_configs_invalid_page_token_errors() {
4816        install_crypto_provider();
4817        let handler = make_handler_with_push_configs();
4818        let params = ServiceParams::new();
4819        handler
4820            .create_push_config(
4821                &params,
4822                TaskPushNotificationConfig {
4823                    task_id: "t1".into(),
4824                    url: "https://example.com/callback".into(),
4825                    id: Some("cfg-1".into()),
4826                    token: None,
4827                    authentication: None,
4828                    tenant: None,
4829                },
4830            )
4831            .await
4832            .unwrap();
4833
4834        let result = handler
4835            .list_push_configs(
4836                &params,
4837                ListTaskPushNotificationConfigsRequest {
4838                    task_id: "t1".into(),
4839                    page_size: None,
4840                    page_token: Some("not-a-number".into()),
4841                    tenant: None,
4842                },
4843            )
4844            .await;
4845        assert!(result.is_err());
4846        assert_eq!(result.unwrap_err().code, error_code::INVALID_PARAMS);
4847    }
4848
4849    #[tokio::test]
4850    async fn test_list_tasks_page_size_cap_bounds_a_store_that_ignores_it() {
4851        install_crypto_provider();
4852        // A store that pays no attention to page_size. Clamping the request
4853        // does nothing here; only truncating the response bounds it.
4854        let handler = DefaultRequestHandler::new(
4855            EchoExecutor,
4856            PagingTaskStore::new(MAX_PAGE_SIZE * 3, false),
4857        );
4858
4859        let resp = handler
4860            .list_tasks(
4861                &ServiceParams::new(),
4862                ListTasksRequest {
4863                    context_id: None,
4864                    status: None,
4865                    page_size: Some(1_000_000),
4866                    page_token: None,
4867                    history_length: None,
4868                    include_artifacts: None,
4869                    status_timestamp_after: None,
4870                    tenant: None,
4871                },
4872            )
4873            .await
4874            .unwrap();
4875
4876        assert_eq!(resp.tasks.len(), MAX_PAGE_SIZE);
4877    }
4878
4879    #[tokio::test]
4880    async fn test_paging_stores_delegate_everything_except_list() {
4881        install_crypto_provider();
4882        // The cap tests above are only measuring the handler if these two
4883        // doubles differ from the real stores in `list` and nowhere else.
4884        // Pin that, so a later edit cannot quietly make them lie.
4885        let tasks = PagingTaskStore::new(0, true);
4886        let task = Task {
4887            id: "t-delegated".into(),
4888            context_id: "c1".into(),
4889            status: TaskStatus {
4890                state: TaskState::Submitted,
4891                message: None,
4892                timestamp: None,
4893            },
4894            artifacts: None,
4895            history: None,
4896            metadata: None,
4897        };
4898        tasks.create(task.clone()).await.unwrap();
4899        assert_eq!(
4900            tasks
4901                .get("t-delegated")
4902                .await
4903                .unwrap()
4904                .map(|t| t.status.state),
4905            Some(TaskState::Submitted)
4906        );
4907        let mut done = task.clone();
4908        done.status.state = TaskState::Completed;
4909        tasks.update(done).await.unwrap();
4910        assert_eq!(
4911            tasks
4912                .get("t-delegated")
4913                .await
4914                .unwrap()
4915                .map(|t| t.status.state),
4916            Some(TaskState::Completed)
4917        );
4918
4919        // begin_cancel has no default (#250), so this must reach
4920        // InMemoryTaskStore's atomic implementation -- and refuse a task that
4921        // is already terminal, as the trait documents.
4922        let mut cancelable = task.clone();
4923        cancelable.id = "t-cancelable".into();
4924        cancelable.status.state = TaskState::Working;
4925        tasks.create(cancelable).await.unwrap();
4926        assert_eq!(
4927            tasks
4928                .begin_cancel("t-cancelable")
4929                .await
4930                .unwrap()
4931                .status
4932                .state,
4933            TaskState::Canceled
4934        );
4935        assert_eq!(
4936            tasks.begin_cancel("t-delegated").await.unwrap_err().code,
4937            error_code::TASK_NOT_CANCELABLE
4938        );
4939
4940        let configs = PagingPushConfigStore::new(0);
4941        configs
4942            .save(TaskPushNotificationConfig {
4943                task_id: "t1".into(),
4944                url: "https://example.com/callback".into(),
4945                id: Some("cfg-1".into()),
4946                token: None,
4947                authentication: None,
4948                tenant: None,
4949            })
4950            .await
4951            .unwrap();
4952        assert_eq!(
4953            configs.get("t1", "cfg-1").await.unwrap().id.as_deref(),
4954            Some("cfg-1")
4955        );
4956        configs.delete("t1", "cfg-1").await.unwrap();
4957        assert!(configs.get("t1", "cfg-1").await.is_err());
4958        configs.delete_all("t1").await.unwrap();
4959    }
4960
4961    #[tokio::test]
4962    async fn test_list_tasks_page_size_cap_bounds_a_store_that_honours_it() {
4963        install_crypto_provider();
4964        // The ordinary case: the store does what it is asked, so what it is
4965        // asked for has to be bounded. Without the clamp this store would
4966        // build a million tasks.
4967        let store = PagingTaskStore::new(MAX_PAGE_SIZE * 3, true);
4968        let seen = Arc::clone(&store.seen_page_size);
4969        let handler = DefaultRequestHandler::new(EchoExecutor, store);
4970
4971        let resp = handler
4972            .list_tasks(
4973                &ServiceParams::new(),
4974                ListTasksRequest {
4975                    context_id: None,
4976                    status: None,
4977                    page_size: Some(1_000_000),
4978                    page_token: None,
4979                    history_length: None,
4980                    include_artifacts: None,
4981                    status_timestamp_after: None,
4982                    tenant: None,
4983                },
4984            )
4985            .await
4986            .unwrap();
4987
4988        assert_eq!(resp.tasks.len(), MAX_PAGE_SIZE);
4989        // The point of the clamp: the store is never asked for the million.
4990        // Asserting only on the response would pass with no clamp at all,
4991        // because the response bound would hide it.
4992        assert_eq!(seen.load(Ordering::SeqCst), MAX_PAGE_SIZE as i32);
4993    }
4994
4995    #[tokio::test]
4996    async fn test_list_tasks_truncation_keeps_the_store_continuation_token() {
4997        install_crypto_provider();
4998        // Truncating must not strand the remainder. The handler cannot
4999        // synthesise a token for a paging scheme it does not own, so the
5000        // store's own token has to survive untouched -- otherwise a caller
5001        // that lost 200 tasks has no way to ask for them.
5002        let handler = DefaultRequestHandler::new(
5003            EchoExecutor,
5004            PagingTaskStore::new(MAX_PAGE_SIZE * 3, false)
5005                .with_next_page_token("cursor-from-store"),
5006        );
5007
5008        let resp = handler
5009            .list_tasks(
5010                &ServiceParams::new(),
5011                ListTasksRequest {
5012                    context_id: None,
5013                    status: None,
5014                    page_size: None,
5015                    page_token: None,
5016                    history_length: None,
5017                    include_artifacts: None,
5018                    status_timestamp_after: None,
5019                    tenant: None,
5020                },
5021            )
5022            .await
5023            .unwrap();
5024
5025        assert_eq!(resp.tasks.len(), DEFAULT_PAGE_SIZE);
5026        assert_eq!(resp.next_page_token, "cursor-from-store");
5027    }
5028
5029    #[tokio::test]
5030    async fn test_list_tasks_honours_a_page_size_under_the_cap() {
5031        install_crypto_provider();
5032        // The clamp is an upper bound, not a floor: a modest request must
5033        // reach the store unchanged.
5034        let store = PagingTaskStore::new(MAX_PAGE_SIZE * 3, true);
5035        let seen = Arc::clone(&store.seen_page_size);
5036        let handler = DefaultRequestHandler::new(EchoExecutor, store);
5037
5038        let resp = handler
5039            .list_tasks(
5040                &ServiceParams::new(),
5041                ListTasksRequest {
5042                    context_id: None,
5043                    status: None,
5044                    page_size: Some(7),
5045                    page_token: None,
5046                    history_length: None,
5047                    include_artifacts: None,
5048                    status_timestamp_after: None,
5049                    tenant: None,
5050                },
5051            )
5052            .await
5053            .unwrap();
5054
5055        assert_eq!(seen.load(Ordering::SeqCst), 7);
5056        assert_eq!(resp.tasks.len(), 7);
5057    }
5058
5059    #[tokio::test]
5060    async fn test_list_push_configs_page_size_cap_bounds_a_custom_store() {
5061        install_crypto_provider();
5062        // InMemoryPushConfigStore caps a task at 50 configs, below the page
5063        // cap of 100, so it can never reach the clamp. A store without that
5064        // limit can, and is what the clamp exists for.
5065        let handler = DefaultRequestHandler::new(EchoExecutor, InMemoryTaskStore::new())
5066            .with_push_config_store(PagingPushConfigStore::new(MAX_PAGE_SIZE * 3));
5067
5068        let resp = handler
5069            .list_push_configs(
5070                &ServiceParams::new(),
5071                ListTaskPushNotificationConfigsRequest {
5072                    task_id: "t1".into(),
5073                    page_size: Some(1_000_000),
5074                    page_token: None,
5075                    tenant: None,
5076                },
5077            )
5078            .await
5079            .unwrap();
5080
5081        assert_eq!(resp.configs.len(), MAX_PAGE_SIZE);
5082        // The remainder must stay reachable, or the cap silently truncates.
5083        assert_eq!(resp.next_page_token.as_deref(), Some("100"));
5084    }
5085
5086    #[tokio::test]
5087    async fn test_list_push_configs_page_size_is_capped() {
5088        install_crypto_provider();
5089        let handler = make_handler_with_push_configs();
5090        let params = ServiceParams::new();
5091        // Keep the count below InMemoryPushConfigStore's per-task cap
5092        // (MAX_PUSH_CONFIGS_PER_TASK), which rejects the 51st config.
5093        for i in 0..40 {
5094            handler
5095                .create_push_config(
5096                    &params,
5097                    TaskPushNotificationConfig {
5098                        task_id: "t1".into(),
5099                        url: format!("https://example.com/callback/{i}"),
5100                        id: Some(format!("cfg-{i:03}")),
5101                        token: None,
5102                        authentication: None,
5103                        tenant: None,
5104                    },
5105                )
5106                .await
5107                .unwrap();
5108        }
5109
5110        // Requesting a huge page size must not error and returns everything
5111        // available. This does NOT exercise the cap -- 40 < MAX_PAGE_SIZE, so
5112        // a capped and an uncapped implementation agree here. The cap itself
5113        // is pinned by test_list_push_configs_page_size_cap_bounds_a_custom_store,
5114        // which is the only route that can reach it.
5115        let resp = handler
5116            .list_push_configs(
5117                &params,
5118                ListTaskPushNotificationConfigsRequest {
5119                    task_id: "t1".into(),
5120                    page_size: Some(1000),
5121                    page_token: None,
5122                    tenant: None,
5123                },
5124            )
5125            .await
5126            .unwrap();
5127        assert_eq!(resp.configs.len(), 40);
5128    }
5129
5130    #[tokio::test]
5131    async fn test_push_config_crud_with_store() {
5132        install_crypto_provider();
5133        let handler = make_handler_with_push_configs();
5134        let params = ServiceParams::new();
5135
5136        let created = handler
5137            .create_push_config(
5138                &params,
5139                TaskPushNotificationConfig {
5140                    task_id: "t1".into(),
5141                    url: "https://example.com/first".into(),
5142                    id: Some("cfg-1".into()),
5143                    token: None,
5144                    authentication: None,
5145                    tenant: Some("tenant-a".into()),
5146                },
5147            )
5148            .await
5149            .unwrap();
5150        assert_eq!(created.id.as_deref(), Some("cfg-1"));
5151
5152        handler
5153            .create_push_config(
5154                &params,
5155                TaskPushNotificationConfig {
5156                    task_id: "t1".into(),
5157                    url: "https://example.com/second".into(),
5158                    id: Some("cfg-2".into()),
5159                    token: None,
5160                    authentication: None,
5161                    tenant: Some("tenant-a".into()),
5162                },
5163            )
5164            .await
5165            .unwrap();
5166
5167        let fetched = handler
5168            .get_push_config(
5169                &params,
5170                GetTaskPushNotificationConfigRequest {
5171                    task_id: "t1".into(),
5172                    id: "cfg-1".into(),
5173                    tenant: Some("tenant-a".into()),
5174                },
5175            )
5176            .await
5177            .unwrap();
5178        assert_eq!(fetched.url, "https://example.com/first");
5179
5180        let first_page = handler
5181            .list_push_configs(
5182                &params,
5183                ListTaskPushNotificationConfigsRequest {
5184                    task_id: "t1".into(),
5185                    page_size: Some(1),
5186                    page_token: Some("0".into()),
5187                    tenant: Some("tenant-a".into()),
5188                },
5189            )
5190            .await
5191            .unwrap();
5192        assert_eq!(first_page.configs.len(), 1);
5193        assert_eq!(first_page.configs[0].id.as_deref(), Some("cfg-1"));
5194        assert_eq!(first_page.next_page_token.as_deref(), Some("1"));
5195
5196        let default_page = handler
5197            .list_push_configs(
5198                &params,
5199                ListTaskPushNotificationConfigsRequest {
5200                    task_id: "t1".into(),
5201                    page_size: Some(0),
5202                    page_token: None,
5203                    tenant: Some("tenant-a".into()),
5204                },
5205            )
5206            .await
5207            .unwrap();
5208        assert_eq!(default_page.configs.len(), 2);
5209        assert!(default_page.next_page_token.is_none());
5210
5211        handler
5212            .delete_push_config(
5213                &params,
5214                DeleteTaskPushNotificationConfigRequest {
5215                    task_id: "t1".into(),
5216                    id: "cfg-1".into(),
5217                    tenant: Some("tenant-a".into()),
5218                },
5219            )
5220            .await
5221            .unwrap();
5222
5223        let remaining = handler
5224            .list_push_configs(
5225                &params,
5226                ListTaskPushNotificationConfigsRequest {
5227                    task_id: "t1".into(),
5228                    page_size: None,
5229                    page_token: None,
5230                    tenant: Some("tenant-a".into()),
5231                },
5232            )
5233            .await
5234            .unwrap();
5235        assert_eq!(remaining.configs.len(), 1);
5236        assert_eq!(remaining.configs[0].id.as_deref(), Some("cfg-2"));
5237    }
5238
5239    #[tokio::test]
5240    async fn test_send_message_request_push_config_delivers_webhooks() {
5241        install_crypto_provider();
5242        let (url, mut receiver, shutdown_tx, server) = start_push_webhook().await;
5243        let handler = make_push_delivery_handler();
5244        let params = ServiceParams::new();
5245        let mut message = make_message();
5246        message.task_id = Some("t-push-request".into());
5247        message.context_id = Some("c-push-request".into());
5248        seed_task(&handler, "t-push-request", "c-push-request").await;
5249
5250        let response = handler
5251            .send_message(
5252                &params,
5253                SendMessageRequest {
5254                    message,
5255                    configuration: Some(SendMessageConfiguration {
5256                        accepted_output_modes: None,
5257                        task_push_notification_config: Some(TaskPushNotificationConfig {
5258                            task_id: String::new(),
5259                            url: url.clone(),
5260                            id: Some("cfg-request".into()),
5261                            token: Some("notify-token".into()),
5262                            authentication: Some(AuthenticationInfo {
5263                                scheme: "bearer".into(),
5264                                credentials: Some("secret-token".into()),
5265                            }),
5266                            tenant: None,
5267                        }),
5268                        history_length: None,
5269                        return_immediately: None,
5270                    }),
5271                    metadata: None,
5272                    tenant: None,
5273                },
5274            )
5275            .await
5276            .unwrap();
5277
5278        match response {
5279            SendMessageResponse::Task(task) => assert_eq!(task.status.state, TaskState::Completed),
5280            _ => panic!("expected Task response"),
5281        }
5282
5283        let saved = handler
5284            .get_push_config(
5285                &params,
5286                GetTaskPushNotificationConfigRequest {
5287                    task_id: "t-push-request".into(),
5288                    id: "cfg-request".into(),
5289                    tenant: None,
5290                },
5291            )
5292            .await
5293            .unwrap();
5294        assert_eq!(saved.url, url);
5295
5296        let first = next_push(&mut receiver).await;
5297        assert_eq!(first.authorization.as_deref(), Some("Bearer secret-token"));
5298        assert_eq!(first.notification_token.as_deref(), Some("notify-token"));
5299        match first.event {
5300            StreamResponse::StatusUpdate(update) => {
5301                assert_eq!(update.task_id, "t-push-request");
5302                assert_eq!(update.status.state, TaskState::Working);
5303            }
5304            _ => panic!("expected status update push"),
5305        }
5306
5307        let second = next_push(&mut receiver).await;
5308        assert_eq!(second.authorization.as_deref(), Some("Bearer secret-token"));
5309        assert_eq!(second.notification_token.as_deref(), Some("notify-token"));
5310        match second.event {
5311            StreamResponse::Task(task) => {
5312                assert_eq!(task.id, "t-push-request");
5313                assert_eq!(task.status.state, TaskState::Completed);
5314            }
5315            _ => panic!("expected final task push"),
5316        }
5317
5318        shutdown_tx.send(()).unwrap();
5319        server.await.unwrap();
5320    }
5321
5322    #[tokio::test]
5323    async fn test_send_message_stored_push_config_delivers_webhooks() {
5324        install_crypto_provider();
5325        let (url, mut receiver, shutdown_tx, server) = start_push_webhook().await;
5326        let handler = make_push_delivery_handler();
5327        let params = ServiceParams::new();
5328
5329        handler
5330            .create_push_config(
5331                &params,
5332                TaskPushNotificationConfig {
5333                    task_id: "t-push-stored".into(),
5334                    url: url.clone(),
5335                    id: Some("cfg-stored".into()),
5336                    token: Some("stored-token".into()),
5337                    authentication: None,
5338                    tenant: None,
5339                },
5340            )
5341            .await
5342            .unwrap();
5343
5344        let mut message = make_message();
5345        message.task_id = Some("t-push-stored".into());
5346        message.context_id = Some("c-push-stored".into());
5347        seed_task(&handler, "t-push-stored", "c-push-stored").await;
5348        let response = handler
5349            .send_message(
5350                &params,
5351                SendMessageRequest {
5352                    message,
5353                    configuration: None,
5354                    metadata: None,
5355                    tenant: None,
5356                },
5357            )
5358            .await
5359            .unwrap();
5360
5361        match response {
5362            SendMessageResponse::Task(task) => assert_eq!(task.status.state, TaskState::Completed),
5363            _ => panic!("expected Task response"),
5364        }
5365
5366        let first = next_push(&mut receiver).await;
5367        assert_eq!(first.notification_token.as_deref(), Some("stored-token"));
5368        match first.event {
5369            StreamResponse::StatusUpdate(update) => {
5370                assert_eq!(update.task_id, "t-push-stored");
5371                assert_eq!(update.status.state, TaskState::Working);
5372            }
5373            _ => panic!("expected status update push"),
5374        }
5375
5376        let second = next_push(&mut receiver).await;
5377        assert_eq!(second.notification_token.as_deref(), Some("stored-token"));
5378        match second.event {
5379            StreamResponse::Task(task) => {
5380                assert_eq!(task.id, "t-push-stored");
5381                assert_eq!(task.status.state, TaskState::Completed);
5382            }
5383            _ => panic!("expected final task push"),
5384        }
5385
5386        shutdown_tx.send(()).unwrap();
5387        server.await.unwrap();
5388    }
5389
5390    fn handler_with_extensions(extensions: Vec<(&str, Option<bool>)>) -> DefaultRequestHandler {
5391        make_handler().with_capabilities(AgentCapabilities {
5392            streaming: None,
5393            push_notifications: None,
5394            extensions: Some(
5395                extensions
5396                    .into_iter()
5397                    .map(|(uri, required)| AgentExtension {
5398                        uri: uri.into(),
5399                        description: None,
5400                        required,
5401                        params: None,
5402                    })
5403                    .collect(),
5404            ),
5405            extended_agent_card: None,
5406        })
5407    }
5408
5409    /// §3.3.4: a request that does not activate an extension the card marks
5410    /// `required` is refused with ExtensionSupportRequiredError, on every
5411    /// operation.
5412    #[tokio::test]
5413    async fn test_required_extension_not_activated_is_refused() {
5414        let handler = handler_with_extensions(vec![
5415            ("urn:ext:optional", None),
5416            ("urn:ext:required", Some(true)),
5417        ]);
5418        let mut params = ServiceParams::new();
5419        params.insert("a2a-extensions".into(), vec!["urn:ext:optional".into()]);
5420
5421        let error = handler
5422            .send_message(&params, send_request())
5423            .await
5424            .unwrap_err();
5425        assert_eq!(error.code, error_code::EXTENSION_SUPPORT_REQUIRED);
5426        assert!(
5427            error.message.contains("urn:ext:required"),
5428            "{}",
5429            error.message
5430        );
5431
5432        let error = handler
5433            .get_task(
5434                &params,
5435                GetTaskRequest {
5436                    id: "t1".into(),
5437                    history_length: None,
5438                    tenant: None,
5439                },
5440            )
5441            .await
5442            .unwrap_err();
5443        assert_eq!(error.code, error_code::EXTENSION_SUPPORT_REQUIRED);
5444    }
5445
5446    /// The required extension may arrive comma-separated in one value or as
5447    /// a repeated service parameter; an optional one need not arrive at all.
5448    #[tokio::test]
5449    async fn test_required_extension_activated_is_accepted() {
5450        let handler = handler_with_extensions(vec![
5451            ("urn:ext:optional", Some(false)),
5452            ("urn:ext:required", Some(true)),
5453        ]);
5454        for activated in [
5455            vec!["urn:ext:other, urn:ext:required".to_string()],
5456            vec!["urn:ext:other".to_string(), "urn:ext:required".to_string()],
5457        ] {
5458            let mut params = ServiceParams::new();
5459            params.insert("a2a-extensions".into(), activated);
5460            handler.send_message(&params, send_request()).await.unwrap();
5461        }
5462
5463        // Nothing required: no activation needed.
5464        let handler = handler_with_extensions(vec![("urn:ext:optional", None)]);
5465        handler
5466            .send_message(&ServiceParams::new(), send_request())
5467            .await
5468            .unwrap();
5469    }
5470
5471    fn push_delivery_handler(executor: impl crate::AgentExecutor) -> DefaultRequestHandler {
5472        DefaultRequestHandler::new(executor, InMemoryTaskStore::new()).with_push_notifications(
5473            InMemoryPushConfigStore::new(),
5474            crate::HttpPushSender::new(Some(crate::HttpPushSenderConfig {
5475                validate_urls: false,
5476                ..Default::default()
5477            })),
5478        )
5479    }
5480
5481    /// §4.3.3: the FAILED state an execution error leaves behind is a task
5482    /// update, so the webhook learns the task ended.
5483    #[tokio::test]
5484    async fn test_execution_error_pushes_the_failed_state() {
5485        install_crypto_provider();
5486        let (url, mut receiver, shutdown_tx, server) = start_push_webhook().await;
5487        let handler = push_delivery_handler(ScriptedExecutor(|ctx: &ExecutorContext| {
5488            vec![
5489                (None, Ok(status_event(ctx, TaskState::Working, None))),
5490                (None, Err(A2AError::internal("boom"))),
5491            ]
5492        }));
5493        let mut request = send_request();
5494        request.configuration = Some(SendMessageConfiguration {
5495            accepted_output_modes: None,
5496            task_push_notification_config: Some(TaskPushNotificationConfig {
5497                url: url.clone(),
5498                ..push_config("")
5499            }),
5500            history_length: None,
5501            return_immediately: None,
5502        });
5503        handler
5504            .send_message(&ServiceParams::new(), request)
5505            .await
5506            .unwrap_err();
5507
5508        let working = next_push(&mut receiver).await.event;
5509        assert!(
5510            matches!(working, StreamResponse::StatusUpdate(ref update) if update.status.state == TaskState::Working),
5511            "{working:?}"
5512        );
5513        let failed = next_push(&mut receiver).await.event;
5514        assert!(
5515            matches!(
5516                failed,
5517                StreamResponse::StatusUpdate(ref update)
5518                    if update.status.state == TaskState::Failed && update.status.message.is_some()
5519            ),
5520            "{failed:?}"
5521        );
5522
5523        shutdown_tx.send(()).unwrap();
5524        server.await.unwrap();
5525    }
5526
5527    struct PausedPushStore {
5528        inner: InMemoryPushConfigStore,
5529        calls: AtomicI32,
5530        started: Arc<Notify>,
5531        resume: Arc<Notify>,
5532    }
5533
5534    #[async_trait]
5535    impl PushConfigStore for PausedPushStore {
5536        async fn save(
5537            &self,
5538            config: TaskPushNotificationConfig,
5539        ) -> Result<TaskPushNotificationConfig, A2AError> {
5540            self.inner.save(config).await
5541        }
5542
5543        async fn get(
5544            &self,
5545            task_id: &str,
5546            config_id: &str,
5547        ) -> Result<TaskPushNotificationConfig, A2AError> {
5548            self.inner.get(task_id, config_id).await
5549        }
5550
5551        async fn list(&self, _task_id: &str) -> Result<Vec<TaskPushNotificationConfig>, A2AError> {
5552            if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
5553                self.started.notify_one();
5554                self.resume.notified().await;
5555                Ok(Vec::new())
5556            } else {
5557                Err(A2AError::internal("push store unavailable"))
5558            }
5559        }
5560
5561        async fn delete(&self, task_id: &str, config_id: &str) -> Result<(), A2AError> {
5562            self.inner.delete(task_id, config_id).await
5563        }
5564
5565        async fn delete_all(&self, task_id: &str) -> Result<(), A2AError> {
5566            self.inner.delete_all(task_id).await
5567        }
5568    }
5569
5570    #[tokio::test]
5571    async fn test_cancel_push_failure_rejects_in_flight_older_event() {
5572        install_crypto_provider();
5573        let started = Arc::new(Notify::new());
5574        let resume = Arc::new(Notify::new());
5575        let handler = DefaultRequestHandler::new(
5576            ScriptedExecutor(|ctx: &ExecutorContext| {
5577                if ctx.message.is_some() {
5578                    vec![(None, Ok(status_event(ctx, TaskState::Working, None)))]
5579                } else {
5580                    vec![(None, Ok(status_event(ctx, TaskState::Canceled, None)))]
5581                }
5582            }),
5583            InMemoryTaskStore::new(),
5584        )
5585        .with_push_notifications(
5586            PausedPushStore {
5587                inner: InMemoryPushConfigStore::new(),
5588                calls: AtomicI32::new(0),
5589                started: started.clone(),
5590                resume: resume.clone(),
5591            },
5592            crate::HttpPushSender::new(None),
5593        );
5594        let params = ServiceParams::new();
5595        seed_task(&handler, "t-push-race", "c-push-race").await;
5596        // A delivery failure must not prevent the owner from inspecting and
5597        // removing the task's push configurations.
5598        for id in ["cfg-1", "cfg-2"] {
5599            handler
5600                .create_push_config(
5601                    &params,
5602                    TaskPushNotificationConfig {
5603                        id: Some(id.into()),
5604                        ..push_config("t-push-race")
5605                    },
5606                )
5607                .await
5608                .unwrap();
5609        }
5610        let mut request = send_request();
5611        request.message.task_id = Some("t-push-race".into());
5612        let _stream = handler
5613            .send_streaming_message(&params, request)
5614            .await
5615            .unwrap();
5616        timeout(Duration::from_secs(5), started.notified())
5617            .await
5618            .unwrap();
5619        let active = handler.execution_manager.get("t-push-race").await.unwrap();
5620        let mut subscriber = active.subscribe();
5621
5622        assert!(
5623            handler
5624                .cancel_task(
5625                    &params,
5626                    CancelTaskRequest {
5627                        id: "t-push-race".into(),
5628                        metadata: None,
5629                        tenant: None,
5630                    }
5631                )
5632                .await
5633                .is_err()
5634        );
5635        assert!(matches!(
5636            subscriber.recv().await.unwrap().result,
5637            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
5638        ));
5639        let get_config = |id: &str| GetTaskPushNotificationConfigRequest {
5640            task_id: "t-push-race".into(),
5641            id: id.into(),
5642            tenant: None,
5643        };
5644        assert_eq!(
5645            handler
5646                .get_push_config(&params, get_config("cfg-1"))
5647                .await
5648                .unwrap()
5649                .id
5650                .as_deref(),
5651            Some("cfg-1")
5652        );
5653        handler
5654            .delete_push_config(
5655                &params,
5656                DeleteTaskPushNotificationConfigRequest {
5657                    task_id: "t-push-race".into(),
5658                    id: "cfg-1".into(),
5659                    tenant: None,
5660                },
5661            )
5662            .await
5663            .unwrap();
5664        assert!(
5665            handler
5666                .get_push_config(&params, get_config("cfg-1"))
5667                .await
5668                .is_err()
5669        );
5670        handler
5671            .push_config_store_checked()
5672            .unwrap()
5673            .delete_all("t-push-race")
5674            .await
5675            .unwrap();
5676        assert!(
5677            handler
5678                .get_push_config(&params, get_config("cfg-2"))
5679                .await
5680                .is_err()
5681        );
5682        resume.notify_one();
5683        timeout(Duration::from_secs(5), async {
5684            while Arc::strong_count(&active) > 1 {
5685                tokio::task::yield_now().await;
5686            }
5687        })
5688        .await
5689        .expect("execution did not finish");
5690
5691        assert!(active.snapshot_is_terminal().await);
5692        assert!(matches!(
5693            subscriber.try_recv(),
5694            Err(broadcast::error::TryRecvError::Empty)
5695        ));
5696        assert_eq!(
5697            handler.load_task("t-push-race").await.unwrap().status.state,
5698            TaskState::Canceled
5699        );
5700    }
5701
5702    #[tokio::test]
5703    async fn test_cancel_push_failure_notifies_and_releases_active_execution() {
5704        install_crypto_provider();
5705        let handler = DefaultRequestHandler::new(
5706            ScriptedExecutor(|ctx: &ExecutorContext| {
5707                vec![(None, Ok(status_event(ctx, TaskState::Canceled, None)))]
5708            }),
5709            InMemoryTaskStore::new(),
5710        )
5711        .with_push_notifications(
5712            InMemoryPushConfigStore::new(),
5713            crate::HttpPushSender::new(None),
5714        );
5715        let params = ServiceParams::new();
5716        seed_task(&handler, "t-cancel-push-error", "c-cancel-push-error").await;
5717        let task = handler.load_task("t-cancel-push-error").await.unwrap();
5718        let active = handler.execution_manager.start(task).await.unwrap();
5719        let mut subscriber = active.subscribe();
5720        handler
5721            .create_push_config(
5722                &params,
5723                TaskPushNotificationConfig {
5724                    url: "http://127.0.0.1:9/callback".into(),
5725                    ..push_config("t-cancel-push-error")
5726                },
5727            )
5728            .await
5729            .unwrap();
5730
5731        handler
5732            .cancel_task(
5733                &params,
5734                CancelTaskRequest {
5735                    id: "t-cancel-push-error".into(),
5736                    metadata: None,
5737                    tenant: None,
5738                },
5739            )
5740            .await
5741            .unwrap_err();
5742
5743        let event = timeout(Duration::from_secs(1), subscriber.recv())
5744            .await
5745            .expect("the active subscriber must not remain blocked")
5746            .unwrap();
5747        assert!(matches!(
5748            event.result,
5749            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
5750        ));
5751        assert!(active.snapshot_is_terminal().await);
5752        assert!(
5753            handler
5754                .execution_manager
5755                .get("t-cancel-push-error")
5756                .await
5757                .is_none()
5758        );
5759        assert_eq!(
5760            handler
5761                .load_task("t-cancel-push-error")
5762                .await
5763                .unwrap()
5764                .status
5765                .state,
5766            TaskState::Canceled
5767        );
5768    }
5769
5770    #[tokio::test]
5771    async fn test_cancel_push_failure_ends_running_stream() {
5772        install_crypto_provider();
5773        let gate = Arc::new(Notify::new());
5774        let resume = gate.clone();
5775        let handler = DefaultRequestHandler::new(
5776            ScriptedExecutor(move |ctx: &ExecutorContext| {
5777                if ctx.message.is_some() {
5778                    vec![
5779                        (None, Ok(status_event(ctx, TaskState::Working, None))),
5780                        (
5781                            Some(gate.clone()),
5782                            Ok(status_event(ctx, TaskState::Completed, None)),
5783                        ),
5784                    ]
5785                } else {
5786                    vec![(None, Ok(status_event(ctx, TaskState::Canceled, None)))]
5787                }
5788            }),
5789            InMemoryTaskStore::new(),
5790        )
5791        .with_push_notifications(
5792            InMemoryPushConfigStore::new(),
5793            crate::HttpPushSender::new(None),
5794        );
5795        let params = ServiceParams::new();
5796        let mut stream = handler
5797            .send_streaming_message(&params, send_request())
5798            .await
5799            .unwrap();
5800        let working = timeout(Duration::from_secs(5), stream.next())
5801            .await
5802            .unwrap()
5803            .unwrap()
5804            .unwrap();
5805        let task_id = match working {
5806            StreamResponse::StatusUpdate(event) => {
5807                assert_eq!(event.status.state, TaskState::Working);
5808                event.task_id
5809            }
5810            event => panic!("expected working status, got {event:?}"),
5811        };
5812        handler
5813            .create_push_config(
5814                &params,
5815                TaskPushNotificationConfig {
5816                    url: "http://127.0.0.1:9/callback".into(),
5817                    ..push_config(&task_id)
5818                },
5819            )
5820            .await
5821            .unwrap();
5822
5823        assert!(
5824            handler
5825                .cancel_task(
5826                    &params,
5827                    CancelTaskRequest {
5828                        id: task_id.clone(),
5829                        metadata: None,
5830                        tenant: None,
5831                    }
5832                )
5833                .await
5834                .is_err()
5835        );
5836        assert!(matches!(
5837            timeout(Duration::from_secs(5), stream.next())
5838                .await
5839                .unwrap()
5840                .unwrap(),
5841            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
5842        ));
5843        assert!(stream.next().await.is_none());
5844        resume.notify_one();
5845        tokio::task::yield_now().await;
5846        assert_eq!(
5847            handler.load_task(&task_id).await.unwrap().status.state,
5848            TaskState::Canceled
5849        );
5850    }
5851
5852    #[tokio::test]
5853    async fn test_empty_cancel_unblocks_running_stream() {
5854        let gate = Arc::new(Notify::new());
5855        let release = gate.clone();
5856        let handler = DefaultRequestHandler::new(
5857            ScriptedExecutor(move |ctx: &ExecutorContext| {
5858                if ctx.message.is_some() {
5859                    vec![
5860                        (None, Ok(status_event(ctx, TaskState::Working, None))),
5861                        (
5862                            Some(gate.clone()),
5863                            Ok(status_event(ctx, TaskState::Completed, None)),
5864                        ),
5865                    ]
5866                } else {
5867                    Vec::<Step>::new()
5868                }
5869            }),
5870            InMemoryTaskStore::new(),
5871        );
5872        let params = ServiceParams::new();
5873        let mut stream = handler
5874            .send_streaming_message(&params, send_request())
5875            .await
5876            .unwrap();
5877        let working = timeout(Duration::from_secs(2), stream.next())
5878            .await
5879            .unwrap()
5880            .unwrap()
5881            .unwrap();
5882        assert!(
5883            matches!(
5884                &working,
5885                StreamResponse::StatusUpdate(update) if update.status.state == TaskState::Working
5886            ),
5887            "expected working status, got {working:?}"
5888        );
5889        let task_id = task_id_for_event(&working)
5890            .expect("working status has a task ID")
5891            .to_owned();
5892        let canceled = handler
5893            .cancel_task(
5894                &params,
5895                CancelTaskRequest {
5896                    id: task_id.clone(),
5897                    metadata: None,
5898                    tenant: None,
5899                },
5900            )
5901            .await
5902            .unwrap();
5903        assert_eq!(canceled.status.state, TaskState::Canceled);
5904        assert_eq!(
5905            handler.load_task(&task_id).await.unwrap().status.state,
5906            TaskState::Canceled
5907        );
5908        let next = timeout(Duration::from_millis(500), stream.next())
5909            .await
5910            .expect("stream remained blocked after successful cancellation");
5911        assert!(
5912            matches!(next, Some(Ok(StreamResponse::StatusUpdate(update))) if update.status.state == TaskState::Canceled)
5913        );
5914        assert!(stream.next().await.is_none());
5915        release.notify_one();
5916    }
5917
5918    #[tokio::test]
5919    async fn cancel_event_application_error_finishes_attached_execution() {
5920        let handler = DefaultRequestHandler::new(
5921            InputRequiredExecutor {
5922                cancel: Cancel::SendsAnInapplicableEvent,
5923            },
5924            InMemoryTaskStore::new(),
5925        );
5926        seed_task(&handler, "t-apply-error", "c-apply-error").await;
5927        let task = handler.load_task("t-apply-error").await.unwrap();
5928        let active = handler.execution_manager.start(task).await.unwrap();
5929        let mut subscriber = active.subscribe();
5930
5931        let error = handler
5932            .cancel_task(
5933                &ServiceParams::new(),
5934                CancelTaskRequest {
5935                    id: "t-apply-error".into(),
5936                    metadata: None,
5937                    tenant: None,
5938                },
5939            )
5940            .await
5941            .unwrap_err();
5942        assert_eq!(error.code, error_code::INVALID_AGENT_RESPONSE);
5943        let delivered = timeout(Duration::from_secs(5), subscriber.recv())
5944            .await
5945            .expect("subscriber did not receive cancellation")
5946            .unwrap();
5947        assert!(matches!(
5948            delivered.result,
5949            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
5950        ));
5951        timeout(Duration::from_secs(5), async {
5952            while handler
5953                .execution_manager
5954                .get("t-apply-error")
5955                .await
5956                .is_some()
5957            {
5958                tokio::task::yield_now().await;
5959            }
5960        })
5961        .await
5962        .expect("active execution was not removed");
5963    }
5964
5965    struct CancelUpdateFailsStore(InMemoryTaskStore);
5966
5967    #[async_trait]
5968    impl TaskStore for CancelUpdateFailsStore {
5969        async fn create(&self, task: Task) -> Result<TaskVersion, A2AError> {
5970            self.0.create(task).await
5971        }
5972
5973        async fn update(&self, _task: Task) -> Result<TaskVersion, A2AError> {
5974            Err(A2AError::internal("cancel event persistence failed"))
5975        }
5976
5977        async fn get(&self, id: &str) -> Result<Option<Task>, A2AError> {
5978            self.0.get(id).await
5979        }
5980
5981        async fn list(&self, req: &ListTasksRequest) -> Result<ListTasksResponse, A2AError> {
5982            self.0.list(req).await
5983        }
5984
5985        async fn begin_cancel(&self, id: &str) -> Result<Task, A2AError> {
5986            self.0.begin_cancel(id).await
5987        }
5988    }
5989
5990    #[tokio::test]
5991    async fn cancel_event_store_failure_returns_error_and_ends_subscriber() {
5992        let handler = DefaultRequestHandler::new(
5993            InputRequiredExecutor {
5994                cancel: Cancel::Cancels,
5995            },
5996            CancelUpdateFailsStore(InMemoryTaskStore::new()),
5997        );
5998        seed_task(&handler, "t-store-error", "c-store-error").await;
5999        let task = handler.load_task("t-store-error").await.unwrap();
6000        let active = handler.execution_manager.start(task).await.unwrap();
6001        let mut subscriber = active.subscribe();
6002
6003        let error = handler
6004            .cancel_task(
6005                &ServiceParams::new(),
6006                CancelTaskRequest {
6007                    id: "t-store-error".into(),
6008                    metadata: None,
6009                    tenant: None,
6010                },
6011            )
6012            .await
6013            .unwrap_err();
6014        assert_eq!(error.message, "cancel event persistence failed");
6015        let delivered = timeout(Duration::from_secs(5), subscriber.recv())
6016            .await
6017            .expect("subscriber did not receive cancellation")
6018            .unwrap();
6019        assert!(matches!(
6020            delivered.result,
6021            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
6022        ));
6023        assert!(
6024            handler
6025                .execution_manager
6026                .get("t-store-error")
6027                .await
6028                .is_none()
6029        );
6030    }
6031
6032    #[tokio::test]
6033    async fn dropped_cancel_request_finishes_attached_execution() {
6034        let started = Arc::new(Notify::new());
6035        let gate = Arc::new(Notify::new());
6036        let handler = Arc::new(DefaultRequestHandler::new(
6037            ScriptedExecutor({
6038                let started = started.clone();
6039                move |ctx: &ExecutorContext| {
6040                    started.notify_one();
6041                    vec![(
6042                        Some(gate.clone()),
6043                        Ok(status_event(ctx, TaskState::Canceled, None)),
6044                    )]
6045                }
6046            }),
6047            InMemoryTaskStore::new(),
6048        ));
6049        seed_task(&handler, "t-aborted-cancel", "c-aborted-cancel").await;
6050        let task = handler.load_task("t-aborted-cancel").await.unwrap();
6051        let active = handler.execution_manager.start(task).await.unwrap();
6052        let mut subscriber = active.subscribe();
6053        let call = tokio::spawn({
6054            let handler = handler.clone();
6055            async move {
6056                handler
6057                    .cancel_task(
6058                        &ServiceParams::new(),
6059                        CancelTaskRequest {
6060                            id: "t-aborted-cancel".into(),
6061                            metadata: None,
6062                            tenant: None,
6063                        },
6064                    )
6065                    .await
6066            }
6067        });
6068        timeout(Duration::from_secs(5), started.notified())
6069            .await
6070            .expect("cancel did not start");
6071        call.abort();
6072        assert!(call.await.unwrap_err().is_cancelled());
6073
6074        let delivered = timeout(Duration::from_secs(5), subscriber.recv())
6075            .await
6076            .expect("subscriber did not receive cancellation")
6077            .unwrap();
6078        assert!(matches!(
6079            delivered.result,
6080            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
6081        ));
6082        timeout(Duration::from_secs(5), async {
6083            while handler
6084                .execution_manager
6085                .get("t-aborted-cancel")
6086                .await
6087                .is_some()
6088            {
6089                tokio::task::yield_now().await;
6090            }
6091        })
6092        .await
6093        .expect("active execution was not removed");
6094    }
6095
6096    #[tokio::test]
6097    async fn dropped_cancel_while_waiting_for_execution_registry_finishes_subscriber() {
6098        let handler = Arc::new(DefaultRequestHandler::new(
6099            InputRequiredExecutor {
6100                cancel: Cancel::Cancels,
6101            },
6102            InMemoryTaskStore::new(),
6103        ));
6104        seed_task(&handler, "t-blocked-registry", "c-blocked-registry").await;
6105        let task = handler.load_task("t-blocked-registry").await.unwrap();
6106        let active = handler.execution_manager.start(task).await.unwrap();
6107        let mut subscriber = active.subscribe();
6108        let registry_lock = handler.execution_manager.executions.write().await;
6109        let call = tokio::spawn({
6110            let handler = handler.clone();
6111            async move {
6112                handler
6113                    .cancel_task(
6114                        &ServiceParams::new(),
6115                        CancelTaskRequest {
6116                            id: "t-blocked-registry".into(),
6117                            metadata: None,
6118                            tenant: None,
6119                        },
6120                    )
6121                    .await
6122            }
6123        });
6124        timeout(Duration::from_secs(5), async {
6125            while handler
6126                .load_task("t-blocked-registry")
6127                .await
6128                .unwrap()
6129                .status
6130                .state
6131                != TaskState::Canceled
6132            {
6133                tokio::task::yield_now().await;
6134            }
6135        })
6136        .await
6137        .expect("cancellation was not committed");
6138        call.abort();
6139        assert!(call.await.unwrap_err().is_cancelled());
6140        drop(registry_lock);
6141
6142        let delivered = timeout(Duration::from_secs(5), subscriber.recv())
6143            .await
6144            .expect("subscriber did not receive cancellation")
6145            .unwrap();
6146        assert!(matches!(
6147            delivered.result,
6148            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
6149        ));
6150        timeout(Duration::from_secs(5), async {
6151            while handler
6152                .execution_manager
6153                .get("t-blocked-registry")
6154                .await
6155                .is_some()
6156            {
6157                tokio::task::yield_now().await;
6158            }
6159        })
6160        .await
6161        .expect("active execution was not removed");
6162    }
6163
6164    #[tokio::test]
6165    async fn cancellation_guard_dropped_off_runtime_still_finishes_execution() {
6166        let handler = DefaultRequestHandler::new(
6167            InputRequiredExecutor {
6168                cancel: Cancel::Cancels,
6169            },
6170            InMemoryTaskStore::new(),
6171        );
6172        seed_task(&handler, "t-drop-thread", "c-drop-thread").await;
6173        let task = handler.load_task("t-drop-thread").await.unwrap();
6174        let active = handler.execution_manager.start(task).await.unwrap();
6175        let mut subscriber = active.subscribe();
6176        let task = handler
6177            .task_store
6178            .begin_cancel("t-drop-thread")
6179            .await
6180            .unwrap();
6181        let guard = FinishCancelOnDrop {
6182            manager: handler.execution_manager.clone(),
6183            active: Some(active),
6184            task,
6185            armed: true,
6186            runtime: Some(tokio::runtime::Handle::current()),
6187        };
6188        std::thread::spawn(move || drop(guard)).join().unwrap();
6189
6190        let delivered = timeout(Duration::from_secs(5), subscriber.recv())
6191            .await
6192            .expect("subscriber did not receive cancellation")
6193            .unwrap();
6194        assert!(matches!(
6195            delivered.result,
6196            Ok(StreamResponse::StatusUpdate(ref update)) if update.status.state == TaskState::Canceled
6197        ));
6198        timeout(Duration::from_secs(5), async {
6199            while handler
6200                .execution_manager
6201                .get("t-drop-thread")
6202                .await
6203                .is_some()
6204            {
6205                tokio::task::yield_now().await;
6206            }
6207        })
6208        .await
6209        .expect("active execution was not removed");
6210    }
6211
6212    /// The CANCELED state `begin_cancel` commits is pushed even when the
6213    /// executor's cancel emits nothing, and only once when it does.
6214    #[tokio::test]
6215    async fn test_cancel_pushes_the_canceled_state_once() {
6216        install_crypto_provider();
6217        for executor_emits_canceled in [false, true] {
6218            let (url, mut receiver, shutdown_tx, server) = start_push_webhook().await;
6219            let handler = push_delivery_handler(ScriptedExecutor(move |ctx: &ExecutorContext| {
6220                if executor_emits_canceled {
6221                    vec![(None, Ok(status_event(ctx, TaskState::Canceled, None)))]
6222                } else {
6223                    Vec::<Step>::new()
6224                }
6225            }));
6226            let params = ServiceParams::new();
6227            seed_task(&handler, "t-cancel-push", "c-cancel-push").await;
6228            handler
6229                .create_push_config(
6230                    &params,
6231                    TaskPushNotificationConfig {
6232                        url: url.clone(),
6233                        ..push_config("t-cancel-push")
6234                    },
6235                )
6236                .await
6237                .unwrap();
6238
6239            let task = handler
6240                .cancel_task(
6241                    &params,
6242                    CancelTaskRequest {
6243                        id: "t-cancel-push".into(),
6244                        metadata: None,
6245                        tenant: None,
6246                    },
6247                )
6248                .await
6249                .unwrap();
6250            assert_eq!(task.status.state, TaskState::Canceled);
6251
6252            let pushed = next_push(&mut receiver).await.event;
6253            assert!(
6254                matches!(
6255                    pushed,
6256                    StreamResponse::StatusUpdate(ref update)
6257                        if update.task_id == "t-cancel-push" && update.status.state == TaskState::Canceled
6258                ),
6259                "{pushed:?}"
6260            );
6261            assert!(
6262                timeout(Duration::from_millis(200), receiver.recv())
6263                    .await
6264                    .is_err(),
6265                "the CANCELED state was pushed twice"
6266            );
6267
6268            shutdown_tx.send(()).unwrap();
6269            server.await.unwrap();
6270        }
6271    }
6272
6273    /// A cancel stream that fails still leaves the task CANCELED, so the
6274    /// webhook gets that state and the caller still gets the error.
6275    #[tokio::test]
6276    async fn test_failed_cancel_still_pushes_the_canceled_state() {
6277        install_crypto_provider();
6278        let (url, mut receiver, shutdown_tx, server) = start_push_webhook().await;
6279        let handler = push_delivery_handler(ScriptedExecutor(|_ctx: &ExecutorContext| {
6280            vec![(None, Err(A2AError::internal("boom")))]
6281        }));
6282        let params = ServiceParams::new();
6283        seed_task(&handler, "t-cancel-error", "c-cancel-error").await;
6284        handler
6285            .create_push_config(
6286                &params,
6287                TaskPushNotificationConfig {
6288                    url: url.clone(),
6289                    ..push_config("t-cancel-error")
6290                },
6291            )
6292            .await
6293            .unwrap();
6294
6295        handler
6296            .cancel_task(
6297                &params,
6298                CancelTaskRequest {
6299                    id: "t-cancel-error".into(),
6300                    metadata: None,
6301                    tenant: None,
6302                },
6303            )
6304            .await
6305            .unwrap_err();
6306
6307        let pushed = next_push(&mut receiver).await.event;
6308        assert!(
6309            matches!(
6310                pushed,
6311                StreamResponse::StatusUpdate(ref update)
6312                    if update.task_id == "t-cancel-error" && update.status.state == TaskState::Canceled
6313            ),
6314            "{pushed:?}"
6315        );
6316
6317        shutdown_tx.send(()).unwrap();
6318        server.await.unwrap();
6319    }
6320
6321    #[tokio::test]
6322    async fn test_extended_agent_card_not_configured() {
6323        let handler = make_handler();
6324        let params = ServiceParams::new();
6325        let result = handler
6326            .get_extended_agent_card(&params, GetExtendedAgentCardRequest { tenant: None })
6327            .await;
6328        assert!(result.is_err());
6329    }
6330
6331    #[test]
6332    fn test_with_capabilities() {
6333        let handler = make_handler().with_capabilities(AgentCapabilities {
6334            streaming: Some(true),
6335            push_notifications: None,
6336            extensions: None,
6337            extended_agent_card: None,
6338        });
6339        assert_eq!(handler.capabilities.streaming, Some(true));
6340    }
6341
6342    #[test]
6343    fn test_with_push_config_store_enables_push_capability() {
6344        install_crypto_provider();
6345        let handler = make_handler_with_push_configs();
6346        assert_eq!(handler.capabilities.push_notifications, Some(true));
6347    }
6348
6349    // §13.3 (#203): a capability the card does not declare is not served.
6350
6351    fn caps(streaming: Option<bool>, push: Option<bool>) -> AgentCapabilities {
6352        AgentCapabilities {
6353            streaming,
6354            push_notifications: push,
6355            extensions: None,
6356            extended_agent_card: None,
6357        }
6358    }
6359
6360    fn send_request() -> SendMessageRequest {
6361        SendMessageRequest {
6362            message: Message::new(Role::User, vec![Part::text("hi")]),
6363            configuration: None,
6364            metadata: None,
6365            tenant: None,
6366        }
6367    }
6368
6369    fn push_config(task_id: &str) -> TaskPushNotificationConfig {
6370        TaskPushNotificationConfig {
6371            task_id: task_id.into(),
6372            url: "https://example.com/callback".into(),
6373            id: Some("cfg-1".into()),
6374            token: None,
6375            authentication: None,
6376            tenant: None,
6377        }
6378    }
6379
6380    #[tokio::test]
6381    async fn test_streaming_refused_when_the_card_declares_it_absent() {
6382        let handler = make_handler().with_capabilities(caps(Some(false), None));
6383        let params = ServiceParams::new();
6384
6385        // The Ok arm is a BoxStream, which is not Debug, so match rather
6386        // than unwrap_err().
6387        match handler
6388            .send_streaming_message(&params, send_request())
6389            .await
6390        {
6391            Err(error) => assert_eq!(error.code, error_code::UNSUPPORTED_OPERATION),
6392            Ok(_) => panic!("streaming must be refused when the card declares it absent"),
6393        }
6394
6395        match handler
6396            .subscribe_to_task(
6397                &params,
6398                SubscribeToTaskRequest {
6399                    id: "t1".into(),
6400                    tenant: None,
6401                },
6402            )
6403            .await
6404        {
6405            Err(error) => assert_eq!(error.code, error_code::UNSUPPORTED_OPERATION),
6406            Ok(_) => panic!("subscribe must be refused when the card declares it absent"),
6407        }
6408    }
6409
6410    #[tokio::test]
6411    async fn test_push_refused_when_the_card_declares_it_absent() {
6412        // A store *is* configured; the card declaring `false` is what refuses.
6413        // Before #203 this combination served push regardless.
6414        let handler = make_handler_with_push_configs().with_capabilities(caps(None, Some(false)));
6415        let params = ServiceParams::new();
6416
6417        let error = handler
6418            .create_push_config(&params, push_config("t1"))
6419            .await
6420            .unwrap_err();
6421        assert_eq!(error.code, error_code::PUSH_NOTIFICATION_NOT_SUPPORTED);
6422
6423        let error = handler
6424            .list_push_configs(
6425                &params,
6426                ListTaskPushNotificationConfigsRequest {
6427                    task_id: "t1".into(),
6428                    page_size: None,
6429                    page_token: None,
6430                    tenant: None,
6431                },
6432            )
6433            .await
6434            .unwrap_err();
6435        assert_eq!(error.code, error_code::PUSH_NOTIFICATION_NOT_SUPPORTED);
6436    }
6437
6438    /// The regression guard. `AgentCapabilities::default()` leaves every field
6439    /// `None`, and most embedders never call `with_capabilities`; if `None`
6440    /// started meaning "refuse", all of them would break at once.
6441    #[tokio::test]
6442    async fn test_undeclared_capabilities_stay_permissive() {
6443        let handler = make_handler_with_push_configs();
6444        let params = ServiceParams::new();
6445
6446        assert!(
6447            handler
6448                .send_streaming_message(&params, send_request())
6449                .await
6450                .is_ok(),
6451            "an undeclared capability must not be treated as refused"
6452        );
6453        assert!(
6454            handler
6455                .create_push_config(&params, push_config("t1"))
6456                .await
6457                .is_ok()
6458        );
6459    }
6460
6461    /// Supplying a store defaults the capability to `true` but must not
6462    /// override an explicit `false`, so the outcome does not depend on which
6463    /// builder method was called last.
6464    #[tokio::test]
6465    async fn test_builder_order_does_not_change_the_declared_capability() {
6466        let params = ServiceParams::new();
6467
6468        for handler in [
6469            make_handler()
6470                .with_capabilities(caps(None, Some(false)))
6471                .with_push_config_store(InMemoryPushConfigStore::new()),
6472            make_handler()
6473                .with_push_config_store(InMemoryPushConfigStore::new())
6474                .with_capabilities(caps(None, Some(false))),
6475        ] {
6476            let error = handler
6477                .create_push_config(&params, push_config("t1"))
6478                .await
6479                .unwrap_err();
6480            assert_eq!(error.code, error_code::PUSH_NOTIFICATION_NOT_SUPPORTED);
6481        }
6482    }
6483
6484    /// `with_push_notifications` defaults the capability the same way as
6485    /// `with_push_config_store`, and likewise must not override an explicit
6486    /// `false`. It had no unit test before #203 — only an example — so the
6487    /// two builders could have drifted apart unnoticed.
6488    #[tokio::test]
6489    async fn test_with_push_notifications_defaults_the_capability() {
6490        let params = ServiceParams::new();
6491
6492        let handler = make_handler().with_push_notifications(
6493            InMemoryPushConfigStore::new(),
6494            crate::HttpPushSender::new(None),
6495        );
6496        assert_eq!(handler.capabilities.push_notifications, Some(true));
6497        assert!(
6498            handler
6499                .create_push_config(&params, push_config("t1"))
6500                .await
6501                .is_ok()
6502        );
6503
6504        let handler = make_handler()
6505            .with_capabilities(caps(None, Some(false)))
6506            .with_push_notifications(
6507                InMemoryPushConfigStore::new(),
6508                crate::HttpPushSender::new(None),
6509            );
6510        assert_eq!(handler.capabilities.push_notifications, Some(false));
6511        let error = handler
6512            .create_push_config(&params, push_config("t1"))
6513            .await
6514            .unwrap_err();
6515        assert_eq!(error.code, error_code::PUSH_NOTIFICATION_NOT_SUPPORTED);
6516    }
6517
6518    /// A store that was never supplied still reports the same code — that is
6519    /// the deployment state, distinct from the card's declaration.
6520    #[tokio::test]
6521    async fn test_missing_store_still_reports_push_unsupported() {
6522        let handler = make_handler();
6523        let error = handler
6524            .create_push_config(&ServiceParams::new(), push_config("t1"))
6525            .await
6526            .unwrap_err();
6527        assert_eq!(error.code, error_code::PUSH_NOTIFICATION_NOT_SUPPORTED);
6528    }
6529
6530    /// Reported in #161 against a different crate (`a2a-protocol-server`),
6531    /// but worth pinning here: two tasks sharing a `contextId` must each
6532    /// carry only their own artifacts. The task store is keyed by task id,
6533    /// so there is no path by which a context could aggregate them — this
6534    /// test exists so that stays true.
6535    #[tokio::test]
6536    async fn test_artifacts_do_not_aggregate_across_tasks_in_one_context() {
6537        let handler = make_handler();
6538        let params = ServiceParams::new();
6539        let context_id = "ctx-shared";
6540
6541        for (task_id, artifact_id) in [("t-first", "a-1"), ("t-second", "a-2")] {
6542            handler
6543                .task_store
6544                .create(Task {
6545                    id: task_id.into(),
6546                    context_id: context_id.into(),
6547                    status: TaskStatus {
6548                        state: TaskState::Working,
6549                        message: None,
6550                        timestamp: None,
6551                    },
6552                    artifacts: None,
6553                    history: None,
6554                    metadata: None,
6555                })
6556                .await
6557                .unwrap();
6558
6559            apply_event_to_task(
6560                handler.task_store.as_ref(),
6561                None,
6562                &StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
6563                    task_id: task_id.into(),
6564                    context_id: context_id.into(),
6565                    artifact: Artifact {
6566                        artifact_id: artifact_id.into(),
6567                        name: None,
6568                        description: None,
6569                        parts: vec![Part::text("payload")],
6570                        metadata: None,
6571                        extensions: None,
6572                    },
6573                    append: None,
6574                    last_chunk: None,
6575                    metadata: None,
6576                }),
6577            )
6578            .await
6579            .unwrap();
6580        }
6581
6582        for (task_id, expected) in [("t-first", "a-1"), ("t-second", "a-2")] {
6583            let task = handler
6584                .get_task(
6585                    &params,
6586                    GetTaskRequest {
6587                        id: task_id.into(),
6588                        history_length: None,
6589                        tenant: None,
6590                    },
6591                )
6592                .await
6593                .unwrap();
6594            let ids: Vec<&str> = task
6595                .artifacts
6596                .as_deref()
6597                .unwrap_or_default()
6598                .iter()
6599                .map(|a| a.artifact_id.as_str())
6600                .collect();
6601            assert_eq!(
6602                ids,
6603                vec![expected],
6604                "{task_id} must carry only its own artifact"
6605            );
6606        }
6607    }
6608    // §12.4 / §10.1 (#204): the extended Agent Card.
6609
6610    fn extended_card(name: &str) -> AgentCard {
6611        AgentCard {
6612            name: name.into(),
6613            description: "extended".into(),
6614            version: "1.0".into(),
6615            supported_interfaces: vec![],
6616            capabilities: AgentCapabilities::default(),
6617            default_input_modes: vec![],
6618            default_output_modes: vec![],
6619            skills: vec![],
6620            provider: None,
6621            documentation_url: None,
6622            icon_url: None,
6623            security_schemes: None,
6624            security_requirements: None,
6625            signatures: None,
6626        }
6627    }
6628
6629    fn extended_request() -> GetExtendedAgentCardRequest {
6630        GetExtendedAgentCardRequest { tenant: None }
6631    }
6632
6633    #[tokio::test]
6634    async fn test_extended_agent_card_is_served_when_configured() {
6635        let handler = make_handler().with_extended_agent_card(extended_card("secret skills"));
6636        let card = handler
6637            .get_extended_agent_card(&ServiceParams::new(), extended_request())
6638            .await
6639            .unwrap();
6640        assert_eq!(card.name, "secret skills");
6641    }
6642
6643    /// Configuring a card also declares the capability, so serving one and
6644    /// advertising it are not two things to remember.
6645    #[tokio::test]
6646    async fn test_configuring_an_extended_card_declares_the_capability() {
6647        let handler = make_handler().with_extended_agent_card(extended_card("x"));
6648        assert_eq!(handler.capabilities.extended_agent_card, Some(true));
6649    }
6650
6651    /// A2A gives this condition its own code. Before #204 it reported
6652    /// `UNSUPPORTED_OPERATION`, which says the agent does not do extended
6653    /// cards at all rather than that this deployment has not configured one.
6654    #[tokio::test]
6655    async fn test_unconfigured_extended_card_reports_its_own_code() {
6656        let handler = make_handler().with_capabilities(AgentCapabilities {
6657            streaming: None,
6658            push_notifications: None,
6659            extensions: None,
6660            extended_agent_card: Some(true),
6661        });
6662        let error = handler
6663            .get_extended_agent_card(&ServiceParams::new(), extended_request())
6664            .await
6665            .unwrap_err();
6666        assert_eq!(error.code, error_code::EXTENDED_CARD_NOT_CONFIGURED);
6667        assert_ne!(error.code, error_code::UNSUPPORTED_OPERATION);
6668    }
6669
6670    /// The capability gate from #203 runs first: a card declaring
6671    /// `extendedAgentCard: false` refuses before the configured/unconfigured
6672    /// distinction is even reached.
6673    #[tokio::test]
6674    async fn test_capability_gate_precedes_the_not_configured_check() {
6675        let handler = make_handler()
6676            .with_extended_agent_card(extended_card("x"))
6677            .with_capabilities(AgentCapabilities {
6678                streaming: None,
6679                push_notifications: None,
6680                extensions: None,
6681                extended_agent_card: Some(false),
6682            });
6683        let error = handler
6684            .get_extended_agent_card(&ServiceParams::new(), extended_request())
6685            .await
6686            .unwrap_err();
6687        assert_eq!(error.code, error_code::UNSUPPORTED_OPERATION);
6688    }
6689
6690    /// §12.4 fetches the extended card under a security scheme, so a
6691    /// resolver can vary what it reveals by caller.
6692    #[tokio::test]
6693    async fn test_resolver_sees_the_caller_params() {
6694        let handler = make_handler().with_extended_agent_card_resolver(|params: &ServiceParams| {
6695            let privileged = params.contains_key("x-privileged");
6696            Ok(extended_card(if privileged { "full" } else { "limited" }))
6697        });
6698
6699        let card = handler
6700            .get_extended_agent_card(&ServiceParams::new(), extended_request())
6701            .await
6702            .unwrap();
6703        assert_eq!(card.name, "limited");
6704
6705        let mut params = ServiceParams::new();
6706        params.insert("x-privileged".into(), vec!["yes".into()]);
6707        let card = handler
6708            .get_extended_agent_card(&params, extended_request())
6709            .await
6710            .unwrap();
6711        assert_eq!(card.name, "full");
6712    }
6713}
6714
6715#[cfg(test)]
6716mod lag_coverage_tests {
6717    use super::*;
6718    use futures::StreamExt;
6719
6720    #[tokio::test]
6721    async fn test_subscription_lag_is_reported_as_a_sanitized_internal_error() {
6722        // A subscriber that falls behind the active execution gets a generic
6723        // INTERNAL_ERROR rather than the broadcast internals, and the stream
6724        // terminates instead of spinning on a lost buffer.
6725        let (sender, receiver) = broadcast::channel(1);
6726
6727        for sequence in 0..4 {
6728            let _ = sender.send(ExecutionEvent {
6729                sequence,
6730                result: Ok(StreamResponse::Message(a2a::Message {
6731                    message_id: "lag-probe".to_string(),
6732                    role: a2a::Role::Agent,
6733                    parts: Vec::new(),
6734                    context_id: None,
6735                    task_id: None,
6736                    metadata: None,
6737                    extensions: None,
6738                    reference_task_ids: None,
6739                })),
6740            });
6741        }
6742
6743        let mut stream = subscription_stream(receiver, None, 0);
6744        let item = stream.next().await.expect("lagged item");
6745
6746        let error = item.expect_err("lag must surface as an error");
6747        assert_eq!(error.code, a2a::error_code::INTERNAL_ERROR);
6748        assert_eq!(error.message, "Internal error");
6749
6750        // `done` is set on lag, so the stream ends rather than repeating.
6751        assert!(stream.next().await.is_none());
6752    }
6753}