Skip to main content

adk_server/a2a/v1/
request_handler.rs

1//! A2A v1.0.0 request handler — shared dispatch layer.
2//!
3//! The [`RequestHandler`] maps operation names to executor/store calls and is
4//! used by both the JSON-RPC and REST transport handlers. It owns references
5//! to the [`V1Executor`], [`TaskStore`], [`PushNotificationSender`], and
6//! [`CachedAgentCard`].
7//!
8//! When a [`RunnerConfig`] is provided, `message_send` and `message_stream`
9//! invoke the agent through the ADK Runner for real LLM generation. Without
10//! a runner config, they fall back to stub behavior (state transitions only).
11//!
12//! Operations run on behalf of a caller ([`RequestHandler::for_caller`]). An
13//! authenticated caller owns the session and every task it creates; tasks owned
14//! by anyone else are reported as not found.
15//!
16//! [`RunnerConfig`]: adk_runner::RunnerConfig
17
18use std::collections::HashMap;
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
21
22use a2a_protocol_types::events::StreamResponse;
23use a2a_protocol_types::params::SendMessageConfiguration;
24use a2a_protocol_types::responses::TaskListResponse;
25use a2a_protocol_types::task::{Task, TaskState};
26use a2a_protocol_types::{AgentCard, Message, TaskPushNotificationConfig};
27use futures::StreamExt;
28use futures::stream::BoxStream;
29use tokio::sync::RwLock;
30use tokio_util::sync::CancellationToken;
31
32use super::card::CachedAgentCard;
33use super::convert::internal_task_to_wire;
34use super::error::A2aError;
35use super::executor::V1Executor;
36use super::processor::OutputMode;
37use super::push::PushNotificationSender;
38use super::run::{RunContext, adk_task_metadata};
39use super::task_store::{ListTasksParams, TaskStore, TaskStoreEntry};
40use crate::auth_bridge::RequestContext;
41
42/// When the task's status last changed: its status timestamp, or the entry's update time
43/// when the status has none. `statusTimestampAfter` filters on it, as a2a-go does.
44fn status_time(entry: &TaskStoreEntry) -> chrono::DateTime<chrono::Utc> {
45    entry
46        .status
47        .timestamp
48        .as_deref()
49        .and_then(|timestamp| chrono::DateTime::parse_from_rfc3339(timestamp).ok())
50        .map_or(entry.updated_at, |time| time.with_timezone(&chrono::Utc))
51}
52
53/// `SendMessage` and `SendStreamingMessage` params, as interceptors see them.
54#[derive(serde::Serialize, serde::Deserialize)]
55struct SendParams {
56    message: Message,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    configuration: Option<SendMessageConfiguration>,
59}
60
61/// `GetTask` params, as interceptors see them.
62#[derive(serde::Serialize, serde::Deserialize)]
63#[serde(rename_all = "camelCase")]
64struct TaskQuery {
65    id: String,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    history_length: Option<u32>,
68}
69
70/// Params that name one task, as interceptors see them.
71#[derive(serde::Serialize, serde::Deserialize)]
72struct TaskIdOnly {
73    id: String,
74}
75
76/// `CreateTaskPushNotificationConfig` params, as interceptors see them.
77#[derive(serde::Serialize, serde::Deserialize)]
78#[serde(rename_all = "camelCase")]
79struct PushConfigCreate {
80    task_id: String,
81    config: TaskPushNotificationConfig,
82}
83
84/// Params that name one push config, as interceptors see them.
85#[derive(serde::Serialize, serde::Deserialize)]
86#[serde(rename_all = "camelCase")]
87struct PushConfigRef {
88    task_id: String,
89    id: String,
90}
91
92fn to_json<T: serde::Serialize>(value: &T) -> Result<serde_json::Value, A2aError> {
93    serde_json::to_value(value)
94        .map_err(|e| A2aError::Internal { message: format!("interceptor JSON: {e}") })
95}
96
97fn from_json<T: serde::de::DeserializeOwned>(value: serde_json::Value) -> Result<T, A2aError> {
98    serde_json::from_value(value)
99        .map_err(|e| A2aError::InvalidParams { message: format!("interceptor JSON: {e}") })
100}
101
102/// The task a message runs on, and whether the agent runs: a waiting task asked again for
103/// a missing answer does not run.
104struct PreparedTask {
105    task_id: String,
106    context_id: String,
107    runs: bool,
108}
109
110/// The IDs of the calls a waiting task's status message asks its caller to answer.
111fn pending_call_ids(entry: &TaskStoreEntry) -> Vec<String> {
112    let Some(message) = &entry.status.message else { return Vec::new() };
113    message
114        .parts
115        .iter()
116        .filter(|part| {
117            part.metadata
118                .as_ref()
119                .and_then(|metadata| metadata.get(super::convert::ADK_TYPE_METADATA_KEY))
120                .and_then(serde_json::Value::as_str)
121                == Some("function_call")
122        })
123        .filter_map(|part| match &part.content {
124            a2a_protocol_types::PartContent::Data(data) => {
125                data.get("id").and_then(serde_json::Value::as_str)
126            }
127            _ => None,
128        })
129        .map(str::to_owned)
130        .collect()
131}
132
133/// The pending call IDs among `pending` that `msg` answers with a function response.
134fn answered_calls(msg: &Message, pending: &[String]) -> Vec<String> {
135    msg.parts
136        .iter()
137        .filter_map(|part| super::convert::wire_part_to_adk(part).ok())
138        .filter_map(|part| match part {
139            adk_core::Part::FunctionResponse { id: Some(id), .. } if pending.contains(&id) => {
140                Some(id)
141            }
142            _ => None,
143        })
144        .collect()
145}
146
147/// A push notification config's URL must be an absolute `http` or `https` URL with a host.
148fn validate_push_url(url: &str) -> Result<(), A2aError> {
149    let valid = reqwest::Url::parse(url).is_ok_and(|parsed| {
150        matches!(parsed.scheme(), "http" | "https")
151            && parsed.host_str().is_some_and(|host| !host.is_empty())
152    });
153    if valid {
154        Ok(())
155    } else {
156        Err(A2aError::InvalidParams {
157            message: format!("push notification URL {url:?} is not an absolute http(s) URL"),
158        })
159    }
160}
161
162/// Validates an ID string (messageId or taskId).
163fn validate_id(id: &str, field_name: &str) -> Result<(), A2aError> {
164    let trimmed = id.trim();
165    if trimmed.is_empty() {
166        return Err(A2aError::InvalidParams {
167            message: format!("{field_name} must not be empty or whitespace-only"),
168        });
169    }
170    if id.len() > 256 {
171        return Err(A2aError::InvalidParams {
172            message: format!("{field_name} exceeds 256 character limit ({} chars)", id.len()),
173        });
174    }
175    Ok(())
176}
177
178/// Validates a message for well-formedness before processing.
179fn validate_message(msg: &Message) -> Result<(), A2aError> {
180    if msg.parts.is_empty() {
181        return Err(A2aError::InvalidParams {
182            message: "message must contain at least one part".to_string(),
183        });
184    }
185    validate_id(&msg.id.0, "messageId")?;
186    if let Some(ref metadata) = msg.metadata {
187        let size = serde_json::to_vec(metadata).map(|v| v.len()).unwrap_or(0);
188        if size > 65_536 {
189            return Err(A2aError::InvalidParams {
190                message: format!("metadata exceeds 64 KB limit ({size} bytes)"),
191            });
192        }
193    }
194    Ok(())
195}
196
197/// Idempotency key: the owner scopes a `messageId`, so one caller's ID cannot
198/// return another caller's task.
199type IdempotencyKey = (Option<String>, String);
200
201/// Builds the extended agent card for a caller (`GetExtendedAgentCard`), as a2a-go's
202/// extended card producer: `None` is an unauthenticated caller.
203pub type ExtendedCardProducer = Arc<
204    dyn Fn(
205            Option<RequestContext>,
206        ) -> futures::future::BoxFuture<'static, Result<AgentCard, A2aError>>
207        + Send
208        + Sync,
209>;
210
211/// Shared dispatch layer for A2A v1.0.0 operations.
212///
213/// Maps operation names to executor/store calls. Used by both the JSON-RPC
214/// handler and the REST handler.
215///
216/// When constructed with a [`adk_runner::RunnerConfig`] via [`RequestHandler::with_runner`],
217/// `message_send` and `message_stream` invoke the agent through the ADK Runner
218/// for real LLM generation. Without a runner config, they perform state
219/// transitions only (useful for protocol-level testing).
220///
221/// The operation methods on `RequestHandler` act for an unauthenticated caller.
222/// Use [`for_caller`](Self::for_caller) to act for an authenticated one; the
223/// bundled transports do this with the principal from the request extensions.
224pub struct RequestHandler {
225    executor: Arc<V1Executor>,
226    task_store: Arc<dyn TaskStore>,
227    agent_card: Arc<RwLock<CachedAgentCard>>,
228    runner_config: Option<Arc<adk_runner::RunnerConfig>>,
229    /// (owner, messageId) → taskId mapping for idempotent request handling.
230    idempotency_map: RwLock<HashMap<IdempotencyKey, String>>,
231    /// The agent runs in progress, so `tasks_cancel` can stop them.
232    running: Arc<RunningTasks>,
233    /// How a run's output is laid out in artifacts.
234    output_mode: OutputMode,
235    /// Builds the extended agent card, when the agent offers one.
236    extended_card: Option<ExtendedCardProducer>,
237    /// Hooks into each run.
238    hooks: super::hooks::ExecutorHooks,
239    /// Fails a run whose agent produces nothing for this long.
240    inactivity_timeout: Option<std::time::Duration>,
241    /// Limits how many runs go at once.
242    limiter: Option<Arc<super::run::RunLimiter>>,
243    /// Run around each operation.
244    interceptors: Vec<Arc<dyn super::interceptor::CallInterceptor>>,
245}
246
247impl RequestHandler {
248    /// Creates a new request handler without a runner (stub mode).
249    pub fn new(
250        executor: Arc<V1Executor>,
251        task_store: Arc<dyn TaskStore>,
252        push_sender: Arc<dyn PushNotificationSender>,
253        agent_card: Arc<RwLock<CachedAgentCard>>,
254    ) -> Self {
255        executor.set_push_sender(push_sender);
256        Self {
257            executor,
258            task_store,
259            agent_card,
260            runner_config: None,
261            idempotency_map: RwLock::new(HashMap::new()),
262            running: Arc::default(),
263            output_mode: OutputMode::default(),
264            extended_card: None,
265            hooks: super::hooks::ExecutorHooks::default(),
266            inactivity_timeout: None,
267            limiter: None,
268            interceptors: Vec::new(),
269        }
270    }
271
272    /// Creates a new request handler with a runner for real LLM invocation.
273    pub fn with_runner(
274        executor: Arc<V1Executor>,
275        task_store: Arc<dyn TaskStore>,
276        push_sender: Arc<dyn PushNotificationSender>,
277        agent_card: Arc<RwLock<CachedAgentCard>>,
278        runner_config: Arc<adk_runner::RunnerConfig>,
279    ) -> Self {
280        executor.set_push_sender(push_sender);
281        Self {
282            executor,
283            task_store,
284            agent_card,
285            runner_config: Some(runner_config),
286            idempotency_map: RwLock::new(HashMap::new()),
287            running: Arc::default(),
288            output_mode: OutputMode::default(),
289            extended_card: None,
290            hooks: super::hooks::ExecutorHooks::default(),
291            inactivity_timeout: None,
292            limiter: None,
293            interceptors: Vec::new(),
294        }
295    }
296
297    /// Runs `interceptor` around each operation, after the ones added before it; see
298    /// [`CallInterceptor`](super::interceptor::CallInterceptor).
299    #[must_use]
300    pub fn with_interceptor(
301        mut self,
302        interceptor: Arc<dyn super::interceptor::CallInterceptor>,
303    ) -> Self {
304        self.interceptors.push(interceptor);
305        self
306    }
307
308    /// Fails a run whose agent produces nothing for `timeout`, as a2a-go's inactivity
309    /// timeout does: the agent is stopped and the task fails with `agent inactivity timeout`.
310    #[must_use]
311    pub fn with_inactivity_timeout(mut self, timeout: std::time::Duration) -> Self {
312        self.inactivity_timeout = Some(timeout);
313        self
314    }
315
316    /// Refuses a message when `limits` already has as many runs going, as a2a-go's
317    /// concurrency limits do (`max concurrency limit reached`).
318    #[must_use]
319    pub fn with_concurrency_limits(mut self, limits: super::run::ConcurrencyLimits) -> Self {
320        self.limiter = Some(super::run::RunLimiter::new(limits));
321        self
322    }
323
324    /// Calls `hooks` at their points in each run; see [`ExecutorHooks`](super::hooks::ExecutorHooks).
325    #[must_use]
326    pub fn with_hooks(mut self, hooks: super::hooks::ExecutorHooks) -> Self {
327        self.hooks = hooks;
328        self
329    }
330
331    /// Serves `producer`'s card for `GetExtendedAgentCard`, built for each caller. Without
332    /// one, the method answers `ExtendedAgentCardNotConfigured`.
333    #[must_use]
334    pub fn with_extended_card(mut self, producer: ExtendedCardProducer) -> Self {
335        self.extended_card = Some(producer);
336        self
337    }
338
339    /// Lays each run's output out in artifacts as `mode` says, as adk-go's executor option
340    /// of the same name. The default is [`OutputMode::ArtifactPerRun`].
341    #[must_use]
342    pub fn with_output_mode(mut self, mode: OutputMode) -> Self {
343        self.output_mode = mode;
344        self
345    }
346
347    /// Returns a view of this handler that acts on behalf of `caller`.
348    ///
349    /// With `Some(caller)`, the agent session belongs to `caller.user_id`, every
350    /// created task is owned by that user, and operations on tasks owned by anyone
351    /// else fail with [`A2aError::TaskNotFound`]. With `None` — no authentication
352    /// configured — the session user is `A2A_USER_{contextId}` and only ownerless tasks
353    /// are visible.
354    ///
355    /// # Example
356    ///
357    /// ```rust,ignore
358    /// let task = handler.for_caller(Some(request_context)).message_send(msg).await?;
359    /// ```
360    pub fn for_caller(&self, caller: Option<RequestContext>) -> CallerScope<'_> {
361        CallerScope { handler: self, caller, extensions: Vec::new() }
362    }
363
364    /// Refuses a call that leaves out an extension the agent card marks `required`, with
365    /// `ExtensionSupportRequired` (-32008), as a2a-go does.
366    ///
367    /// # Errors
368    ///
369    /// Returns [`A2aError::ExtensionSupportRequired`] naming the first missing extension.
370    pub async fn require_extensions(
371        &self,
372        requested: &super::extensions::RequestedExtensions,
373    ) -> Result<(), A2aError> {
374        let card = self.agent_card.read().await;
375        let missing = card.card.capabilities.extensions.iter().flatten().find(|extension| {
376            extension.required == Some(true) && !requested.contains(&extension.uri)
377        });
378        match missing {
379            Some(extension) => {
380                Err(A2aError::ExtensionSupportRequired { uri: extension.uri.clone() })
381            }
382            None => Ok(()),
383        }
384    }
385
386    /// Sends a message as an unauthenticated caller; see [`CallerScope::message_send`].
387    ///
388    /// # Errors
389    ///
390    /// See [`CallerScope::message_send`].
391    pub async fn message_send(&self, msg: Message) -> Result<Task, A2aError> {
392        self.for_caller(None).message_send(msg).await
393    }
394
395    /// Sends a message with the request's configuration as an unauthenticated caller; see
396    /// [`CallerScope::message_send_with`].
397    ///
398    /// # Errors
399    ///
400    /// See [`CallerScope::message_send_with`].
401    pub async fn message_send_with(
402        &self,
403        msg: Message,
404        configuration: Option<&SendMessageConfiguration>,
405    ) -> Result<Task, A2aError> {
406        self.for_caller(None).message_send_with(msg, configuration).await
407    }
408
409    /// Sends a streaming message as an unauthenticated caller; see
410    /// [`CallerScope::message_stream`].
411    ///
412    /// # Errors
413    ///
414    /// See [`CallerScope::message_stream`].
415    pub async fn message_stream(
416        &self,
417        msg: Message,
418    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
419        self.for_caller(None).message_stream(msg).await
420    }
421
422    /// Streams a message with its `configuration` for an unauthenticated caller; see
423    /// [`CallerScope::message_stream_with`].
424    ///
425    /// # Errors
426    ///
427    /// See [`CallerScope::message_stream_with`].
428    pub async fn message_stream_with(
429        &self,
430        msg: Message,
431        configuration: Option<&SendMessageConfiguration>,
432    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
433        self.for_caller(None).message_stream_with(msg, configuration).await
434    }
435
436    /// Retrieves an ownerless task; see [`CallerScope::tasks_get`].
437    ///
438    /// # Errors
439    ///
440    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or has an owner.
441    pub async fn tasks_get(
442        &self,
443        task_id: &str,
444        history_len: Option<u32>,
445    ) -> Result<Task, A2aError> {
446        self.for_caller(None).tasks_get(task_id, history_len).await
447    }
448
449    /// Cancels an ownerless task; see [`CallerScope::tasks_cancel`].
450    ///
451    /// # Errors
452    ///
453    /// See [`CallerScope::tasks_cancel`].
454    pub async fn tasks_cancel(&self, task_id: &str) -> Result<Task, A2aError> {
455        self.for_caller(None).tasks_cancel(task_id).await
456    }
457
458    /// Lists ownerless tasks; see [`CallerScope::tasks_list`].
459    ///
460    /// # Errors
461    ///
462    /// See [`CallerScope::tasks_list`].
463    pub async fn tasks_list(&self, params: ListTasksParams) -> Result<TaskListResponse, A2aError> {
464        self.for_caller(None).tasks_list(params).await
465    }
466
467    /// Subscribes to an ownerless task; see [`CallerScope::tasks_subscribe`].
468    ///
469    /// # Errors
470    ///
471    /// See [`CallerScope::tasks_subscribe`].
472    pub async fn tasks_subscribe(
473        &self,
474        task_id: &str,
475    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
476        self.for_caller(None).tasks_subscribe(task_id).await
477    }
478
479    /// Creates a push notification configuration on an ownerless task; see
480    /// [`CallerScope::push_config_create`].
481    ///
482    /// # Errors
483    ///
484    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or has an owner.
485    pub async fn push_config_create(
486        &self,
487        task_id: &str,
488        config: TaskPushNotificationConfig,
489    ) -> Result<TaskPushNotificationConfig, A2aError> {
490        self.for_caller(None).push_config_create(task_id, config).await
491    }
492
493    /// Retrieves a push notification configuration from an ownerless task; see
494    /// [`CallerScope::push_config_get`].
495    ///
496    /// # Errors
497    ///
498    /// Returns [`A2aError::TaskNotFound`] if the task or config does not exist.
499    pub async fn push_config_get(
500        &self,
501        task_id: &str,
502        config_id: &str,
503    ) -> Result<TaskPushNotificationConfig, A2aError> {
504        self.for_caller(None).push_config_get(task_id, config_id).await
505    }
506
507    /// Lists the push notification configurations of an ownerless task; see
508    /// [`CallerScope::push_config_list`].
509    ///
510    /// # Errors
511    ///
512    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or has an owner.
513    pub async fn push_config_list(
514        &self,
515        task_id: &str,
516    ) -> Result<Vec<TaskPushNotificationConfig>, A2aError> {
517        self.for_caller(None).push_config_list(task_id).await
518    }
519
520    /// Deletes a push notification configuration from an ownerless task; see
521    /// [`CallerScope::push_config_delete`].
522    ///
523    /// # Errors
524    ///
525    /// Returns [`A2aError::TaskNotFound`] if the task or config does not exist.
526    pub async fn push_config_delete(&self, task_id: &str, config_id: &str) -> Result<(), A2aError> {
527        self.for_caller(None).push_config_delete(task_id, config_id).await
528    }
529
530    /// Returns the extended agent card for an unauthenticated caller; see
531    /// [`agent_card_extended_for`](Self::agent_card_extended_for).
532    ///
533    /// # Errors
534    ///
535    /// See [`agent_card_extended_for`](Self::agent_card_extended_for).
536    pub async fn agent_card_extended(&self) -> Result<AgentCard, A2aError> {
537        self.agent_card_extended_for(None).await
538    }
539
540    /// Returns the extended agent card for `caller`, from the handler's
541    /// [`ExtendedCardProducer`], as a2a-go serves it.
542    ///
543    /// # Errors
544    ///
545    /// Returns [`A2aError::UnsupportedOperation`] when the agent card says the agent offers
546    /// no extended card (`capabilities.extendedAgentCard: false`),
547    /// [`A2aError::ExtendedAgentCardNotConfigured`] when the handler has no producer, and
548    /// the producer's own error.
549    pub async fn agent_card_extended_for(
550        &self,
551        caller: Option<RequestContext>,
552    ) -> Result<AgentCard, A2aError> {
553        if self.agent_card.read().await.card.capabilities.extended_agent_card == Some(false) {
554            return Err(A2aError::UnsupportedOperation {
555                method: "GetExtendedAgentCard: the agent card declares no extended card"
556                    .to_string(),
557            });
558        }
559        let producer =
560            self.extended_card.as_ref().ok_or(A2aError::ExtendedAgentCardNotConfigured)?;
561        producer(caller).await
562    }
563
564    /// Refuses `operation` when the agent card says the agent does not offer it.
565    ///
566    /// A capability the card leaves unstated is not checked, so a hand-assembled card that
567    /// states none keeps serving everything.
568    /// [`A2aV1Server`](super::server::A2aV1Server) states every capability.
569    async fn require(&self, operation: Capability) -> Result<(), A2aError> {
570        let capabilities = self.agent_card.read().await.card.capabilities.clone();
571        match operation {
572            Capability::Streaming(method) if capabilities.streaming == Some(false) => {
573                Err(A2aError::UnsupportedOperation {
574                    method: format!("{method}: the agent card does not declare streaming"),
575                })
576            }
577            Capability::PushNotifications if capabilities.push_notifications == Some(false) => {
578                Err(A2aError::PushNotificationNotSupported)
579            }
580            _ => Ok(()),
581        }
582    }
583
584    /// Returns a reference to the underlying executor.
585    pub fn executor(&self) -> &Arc<V1Executor> {
586        &self.executor
587    }
588
589    /// Returns a reference to the underlying task store.
590    pub fn task_store(&self) -> &Arc<dyn TaskStore> {
591        &self.task_store
592    }
593}
594
595/// A [`RequestHandler`] acting on behalf of one caller.
596///
597/// Created by [`RequestHandler::for_caller`]. Every operation is scoped to the
598/// caller: tasks it creates are owned by the caller's `user_id`, and a task owned
599/// by anyone else is reported as [`A2aError::TaskNotFound`] — the same answer as
600/// for a task that does not exist, so task IDs cannot be probed.
601pub struct CallerScope<'a> {
602    handler: &'a RequestHandler,
603    caller: Option<RequestContext>,
604    extensions: Vec<String>,
605}
606
607impl CallerScope<'_> {
608    /// Runs `call` with `params` through the handler's call interceptors; see
609    /// [`CallInterceptor`](super::interceptor::CallInterceptor).
610    async fn intercepted<P, R, F, Fut>(
611        &self,
612        method: &'static str,
613        params: P,
614        call: F,
615    ) -> Result<R, A2aError>
616    where
617        P: serde::Serialize + serde::de::DeserializeOwned,
618        R: serde::Serialize + serde::de::DeserializeOwned,
619        F: FnOnce(P) -> Fut,
620        Fut: std::future::Future<Output = Result<R, A2aError>>,
621    {
622        let interceptors = &self.handler.interceptors;
623        if interceptors.is_empty() {
624            return call(params).await;
625        }
626        let context = self.call_context(method);
627        let mut value = to_json(&params)?;
628        for interceptor in interceptors {
629            if let Some(answer) = interceptor.before(&context, &mut value).await? {
630                return from_json(answer);
631            }
632        }
633        let result = call(from_json(value)?).await?;
634        let mut value = to_json(&result)?;
635        for interceptor in interceptors.iter().rev() {
636            interceptor.after(&context, &mut value).await?;
637        }
638        from_json(value)
639    }
640
641    /// [`intercepted`](Self::intercepted) for a streaming operation: `after` runs on each
642    /// event, and an answer from `before` is the stream's one event.
643    async fn intercepted_stream<P, F, Fut>(
644        &self,
645        method: &'static str,
646        params: P,
647        call: F,
648    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError>
649    where
650        P: serde::Serialize + serde::de::DeserializeOwned,
651        F: FnOnce(P) -> Fut,
652        Fut: std::future::Future<
653                Output = Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError>,
654            >,
655    {
656        let interceptors = self.handler.interceptors.clone();
657        if interceptors.is_empty() {
658            return call(params).await;
659        }
660        let context = Arc::new(self.call_context(method));
661        let mut value = to_json(&params)?;
662        for interceptor in &interceptors {
663            if let Some(answer) = interceptor.before(&context, &mut value).await? {
664                let event: StreamResponse = from_json(answer)?;
665                return Ok(futures::stream::once(async move { Ok(event) }).boxed());
666            }
667        }
668        let stream = call(from_json(value)?).await?;
669        Ok(stream
670            .then(move |item| {
671                let interceptors = interceptors.clone();
672                let context = context.clone();
673                async move {
674                    let mut value = to_json(&item?)?;
675                    for interceptor in interceptors.iter().rev() {
676                        interceptor.after(&context, &mut value).await?;
677                    }
678                    from_json(value)
679                }
680            })
681            .boxed())
682    }
683
684    fn call_context(&self, method: &'static str) -> super::interceptor::CallContext {
685        super::interceptor::CallContext {
686            method,
687            caller: self.caller.clone(),
688            extensions: self.extensions.clone(),
689        }
690    }
691
692    /// The caller this scope acts for; `None` without authentication.
693    pub fn caller(&self) -> Option<&RequestContext> {
694        self.caller.as_ref()
695    }
696
697    /// Acts with the extensions the caller asked for, which each run's hooks see.
698    #[must_use]
699    pub fn with_extensions(mut self, requested: super::extensions::RequestedExtensions) -> Self {
700        self.extensions = requested.0;
701        self
702    }
703
704    /// The authenticated user this scope acts for, or `None` without authentication.
705    pub fn owner(&self) -> Option<&str> {
706        self.caller.as_ref().map(|context| context.user_id.as_str())
707    }
708
709    /// Loads a task, treating one owned by another caller as missing.
710    async fn owned_task(&self, task_id: &str) -> Result<TaskStoreEntry, A2aError> {
711        let entry = self.handler.task_store.get_task(task_id).await?;
712        if entry.owner() == self.owner() {
713            Ok(entry)
714        } else {
715            Err(A2aError::TaskNotFound { task_id: task_id.to_string() })
716        }
717    }
718
719    fn idempotency_key(&self, message_id: &str) -> IdempotencyKey {
720        (self.owner().map(str::to_string), message_id.to_string())
721    }
722
723    /// Sends a message and waits for the task to finish or to stop for the caller.
724    ///
725    /// The same as [`message_send_with`](Self::message_send_with) without a configuration.
726    ///
727    /// # Errors
728    ///
729    /// See [`message_send_with`](Self::message_send_with).
730    pub async fn message_send(&self, msg: Message) -> Result<Task, A2aError> {
731        self.message_send_with(msg, None).await
732    }
733
734    /// Sends a message, creating a task or continuing one, and runs the agent on it.
735    ///
736    /// The agent runs on its own, detached from this call: a caller that goes away, or a
737    /// request that times out, does not stop the run, and the run always settles the task.
738    /// With `returnImmediately` set in `configuration`, the call returns the `SUBMITTED`
739    /// task at once (A2A §3.2.2). Otherwise it returns once the task finishes or stops for
740    /// the caller. Either way, [`tasks_cancel`](Self::tasks_cancel) stops the run.
741    ///
742    /// A message that names an `INPUT_REQUIRED` task must answer every call the task
743    /// waits on; otherwise the task asks again, naming the call with no answer
744    /// (`no input provided for function call ID "…"`), and the agent does not run.
745    ///
746    /// # Errors
747    ///
748    /// Returns [`A2aError::TaskNotFound`] for a `taskId` that names no task of this
749    /// caller's, [`A2aError::InvalidParams`] when the message's `contextId` is not that
750    /// task's, [`A2aError::UnsupportedOperation`] when that task has ended or is still
751    /// running, and an error if task creation or the store fails. A failed run is not an
752    /// error: the task is returned `FAILED`, with the error as its status message.
753    pub async fn message_send_with(
754        &self,
755        msg: Message,
756        configuration: Option<&SendMessageConfiguration>,
757    ) -> Result<Task, A2aError> {
758        self.intercepted(
759            "SendMessage",
760            SendParams { message: msg, configuration: configuration.cloned() },
761            |p: SendParams| async move {
762                self.message_send_with_direct(p.message, p.configuration.as_ref()).await
763            },
764        )
765        .await
766    }
767
768    /// [`message_send_with`](Self::message_send_with) without the call interceptors.
769    async fn message_send_with_direct(
770        &self,
771        msg: Message,
772        configuration: Option<&SendMessageConfiguration>,
773    ) -> Result<Task, A2aError> {
774        validate_message(&msg)?;
775        let handler = self.handler;
776        if configuration.is_some_and(|c| c.task_push_notification_config.is_some()) {
777            handler.require(Capability::PushNotifications).await?;
778        }
779
780        let idempotency_key = self.idempotency_key(&msg.id.0);
781        if let Some(existing_task_id) = self.idempotent_task(&idempotency_key).await? {
782            return self.tasks_get_direct(&existing_task_id, None).await;
783        }
784
785        // Refused before a task exists when the run limit is reached.
786        let permit = self.acquire_run()?;
787        let prepared = self.prepare_task(&msg).await?;
788        let task_id = prepared.task_id.clone();
789        if let Some(config) = configuration.and_then(|c| c.task_push_notification_config.clone()) {
790            self.push_config_create_direct(&task_id, config).await?;
791        }
792        handler.idempotency_map.write().await.insert(idempotency_key, task_id.clone());
793
794        if prepared.runs {
795            let return_immediately =
796                configuration.and_then(|c| c.return_immediately).unwrap_or(false);
797            let submitted = handler.task_store.get_task(&task_id).await?;
798            let run = self.start_run(&prepared, msg, permit).await?;
799            if return_immediately {
800                return internal_task_to_wire(&submitted);
801            }
802            // The run is its own task; waiting for it here does not tie it to this call.
803            if let Err(error) = run.await {
804                tracing::warn!(%task_id, %error, "A2A run did not finish");
805            }
806        }
807
808        let entry = handler.task_store.get_task(&task_id).await?;
809        internal_task_to_wire(&entry)
810    }
811
812    /// The task an earlier request with the same idempotency key created, if it still
813    /// exists.
814    async fn idempotent_task(&self, key: &IdempotencyKey) -> Result<Option<String>, A2aError> {
815        let handler = self.handler;
816        let Some(existing) = handler.idempotency_map.read().await.get(key).cloned() else {
817            return Ok(None);
818        };
819        match self.owned_task(&existing).await {
820            Ok(_) => Ok(Some(existing)),
821            Err(A2aError::TaskNotFound { .. }) => {
822                handler.idempotency_map.write().await.remove(key);
823                Ok(None)
824            }
825            Err(error) => Err(error),
826        }
827    }
828
829    /// Starts the run of a prepared task: the agent when the handler has one, otherwise
830    /// the `WORKING` and `COMPLETED` transitions alone. Returns the run's handle.
831    /// A place for one more run under the handler's concurrency limits, scoped by the
832    /// caller; `None` without limits.
833    fn acquire_run(&self) -> Result<Option<super::run::RunPermit>, A2aError> {
834        let Some(limiter) = &self.handler.limiter else { return Ok(None) };
835        let scope = self.caller.as_ref().map_or("anonymous", |caller| caller.user_id.as_str());
836        limiter.acquire(scope).map(Some)
837    }
838
839    async fn start_run(
840        &self,
841        prepared: &PreparedTask,
842        msg: Message,
843        permit: Option<super::run::RunPermit>,
844    ) -> Result<tokio::task::JoinHandle<()>, A2aError> {
845        let handler = self.handler;
846        let (task_id, context_id) = (prepared.task_id.clone(), prepared.context_id.clone());
847        let Some(runner_config) = handler.runner_config.clone() else {
848            let executor = handler.executor.clone();
849            executor.transition_state(&task_id, &context_id, TaskState::Working, None).await?;
850            executor.transition_state(&task_id, &context_id, TaskState::Completed, None).await?;
851            return Ok(tokio::spawn(async {}));
852        };
853        // Registered before the run starts, so a cancel that races it still stops it.
854        let guard = handler.running.start(&task_id, runner_config.cancellation_token.as_ref());
855        let cancellation = guard.token().clone();
856        let run = RunContext {
857            executor: handler.executor.clone(),
858            runner_config,
859            caller: self.caller.clone(),
860            output_mode: handler.output_mode,
861            hooks: handler.hooks.clone(),
862            extensions: self.extensions.clone(),
863            inactivity_timeout: handler.inactivity_timeout,
864        };
865        Ok(super::run::spawn(run, task_id, context_id, msg, cancellation, (guard, permit)))
866    }
867
868    /// The `INPUT_REQUIRED` or `AUTH_REQUIRED` task `msg` continues, if any (see
869    /// [`message_send_with`](Self::message_send_with)).
870    ///
871    /// A message that names its task continues it. A message that names only a context
872    /// continues that context's `INPUT_REQUIRED` task when it answers one of the calls the
873    /// task waits on; any other such message starts a new task in the context.
874    ///
875    /// # Errors
876    ///
877    /// Returns [`A2aError::TaskNotFound`] for a `taskId` that names no task of this
878    /// caller's, [`A2aError::InvalidParams`] when the message's `contextId` is not that
879    /// task's, and [`A2aError::UnsupportedOperation`] when that task has ended or is still
880    /// running.
881    async fn task_to_continue(&self, msg: &Message) -> Result<Option<TaskStoreEntry>, A2aError> {
882        if let Some(task_id) = &msg.task_id {
883            validate_id(&task_id.0, "taskId")?;
884            let entry = self.owned_task(&task_id.0).await?;
885            if let Some(context_id) = &msg.context_id
886                && context_id.0 != entry.context_id
887            {
888                return Err(A2aError::InvalidParams {
889                    message: format!(
890                        "contextId {} is not the context of task {}",
891                        context_id.0, entry.id
892                    ),
893                });
894            }
895            return match entry.status.state {
896                TaskState::InputRequired | TaskState::AuthRequired => Ok(Some(entry)),
897                state if is_terminal_state(state) => Err(A2aError::UnsupportedOperation {
898                    method: format!("a message to task {} in terminal state {state:?}", entry.id),
899                }),
900                state => Err(A2aError::UnsupportedOperation {
901                    method: format!("a message to task {} while it is {state:?}", entry.id),
902                }),
903            };
904        }
905
906        if let Some(ctx_id) = &msg.context_id
907            && let Some(existing) = self.handler.task_store.find_task_by_context(&ctx_id.0).await?
908            && existing.status.state == TaskState::InputRequired
909            && existing.owner() == self.owner()
910            && !answered_calls(msg, &pending_call_ids(&existing)).is_empty()
911        {
912            return Ok(Some(existing));
913        }
914        Ok(None)
915    }
916
917    /// Finds or creates the task `msg` runs on and records `msg` in its history.
918    ///
919    /// A new task is `SUBMITTED`. A waiting task is taken back to `SUBMITTED` for its run,
920    /// unless `msg` leaves one of its calls unanswered: then it asks again and does not
921    /// run (see [`message_send_with`](Self::message_send_with)).
922    ///
923    /// # Errors
924    ///
925    /// See [`task_to_continue`](Self::task_to_continue); also returns an error if task
926    /// creation or the store fails.
927    async fn prepare_task(&self, msg: &Message) -> Result<PreparedTask, A2aError> {
928        let handler = self.handler;
929        if let Some(existing) = self.task_to_continue(msg).await? {
930            let pending = pending_call_ids(&existing);
931            let answered = answered_calls(msg, &pending);
932            if existing.status.state == TaskState::InputRequired
933                && let Some(missing) = pending.iter().find(|id| !answered.contains(*id))
934            {
935                handler.executor.ask_again(&existing.id, msg.clone(), missing).await?;
936                return Ok(PreparedTask {
937                    task_id: existing.id,
938                    context_id: existing.context_id,
939                    runs: false,
940                });
941            }
942            let claimed = handler.executor.claim_waiting_task(&existing.id, msg.clone()).await?;
943            return Ok(PreparedTask {
944                task_id: claimed.id,
945                context_id: claimed.context_id,
946                runs: true,
947            });
948        }
949
950        let task_id = uuid::Uuid::new_v4().to_string();
951        let context_id = msg
952            .context_id
953            .as_ref()
954            .map(|c| c.0.clone())
955            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
956        let metadata =
957            handler.runner_config.as_ref().map(|_| adk_task_metadata()).unwrap_or_default();
958        handler
959            .executor
960            .create_task_with_metadata(&task_id, &context_id, self.owner(), metadata)
961            .await?;
962        handler.executor.add_history_message(&task_id, msg.clone()).await?;
963        Ok(PreparedTask { task_id, context_id, runs: true })
964    }
965
966    /// Sends a streaming message; see [`message_stream_with`](Self::message_stream_with).
967    ///
968    /// # Errors
969    ///
970    /// See [`message_stream_with`](Self::message_stream_with).
971    pub async fn message_stream(
972        &self,
973        msg: Message,
974    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
975        self.message_stream_with(msg, None).await
976    }
977
978    /// Sends a message, as [`message_send_with`](Self::message_send_with) does, and
979    /// streams the task's updates: the `SUBMITTED` task first, then each status and
980    /// artifact update the run makes, until the task ends or stops for the caller.
981    ///
982    /// The run does not depend on the stream: a client that disconnects leaves it running,
983    /// and [`tasks_subscribe`](Self::tasks_subscribe) follows it again. Each event the
984    /// agent produces is one artifact update carrying every part of the event, laid out as
985    /// the handler's [`OutputMode`] says; a model error, a cancel and calls that wait on
986    /// the caller end the stream on the matching status. These are the updates adk-go's
987    /// A2A executor makes.
988    ///
989    /// # Errors
990    ///
991    /// Returns the errors of [`message_send_with`](Self::message_send_with), and
992    /// [`A2aError::UnsupportedOperation`] when the agent card says the agent does not
993    /// stream.
994    pub async fn message_stream_with(
995        &self,
996        msg: Message,
997        configuration: Option<&SendMessageConfiguration>,
998    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
999        self.intercepted_stream(
1000            "SendStreamingMessage",
1001            SendParams { message: msg, configuration: configuration.cloned() },
1002            |p: SendParams| async move {
1003                self.message_stream_with_direct(p.message, p.configuration.as_ref()).await
1004            },
1005        )
1006        .await
1007    }
1008
1009    /// [`message_stream_with`](Self::message_stream_with) without the call interceptors.
1010    async fn message_stream_with_direct(
1011        &self,
1012        msg: Message,
1013        configuration: Option<&SendMessageConfiguration>,
1014    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
1015        self.handler.require(Capability::Streaming("SendStreamingMessage")).await?;
1016        validate_message(&msg)?;
1017        let handler = self.handler;
1018        if configuration.is_some_and(|c| c.task_push_notification_config.is_some()) {
1019            handler.require(Capability::PushNotifications).await?;
1020        }
1021
1022        let idempotency_key = self.idempotency_key(&msg.id.0);
1023        if let Some(existing_task_id) = self.idempotent_task(&idempotency_key).await? {
1024            let task = self.tasks_get_direct(&existing_task_id, None).await?;
1025            return Ok(futures::stream::once(async move { Ok(StreamResponse::Task(task)) }).boxed());
1026        }
1027
1028        // Refused before a task exists when the run limit is reached.
1029        let permit = self.acquire_run()?;
1030        let prepared = self.prepare_task(&msg).await?;
1031        let task_id = prepared.task_id.clone();
1032        if let Some(config) = configuration.and_then(|c| c.task_push_notification_config.clone()) {
1033            self.push_config_create_direct(&task_id, config).await?;
1034        }
1035        handler.idempotency_map.write().await.insert(idempotency_key, task_id.clone());
1036
1037        // Subscribe before the run starts, so the stream sees every update it makes.
1038        let mut updates = handler.executor.subscribe(&task_id);
1039        let first = internal_task_to_wire(&handler.task_store.get_task(&task_id).await?)?;
1040        let settled = ends_subscription(first.status.state);
1041        if prepared.runs {
1042            // Detached: the handle is not awaited, so dropping the stream leaves the run.
1043            drop(self.start_run(&prepared, msg, permit).await?);
1044        }
1045
1046        let stream = async_stream::stream! {
1047            yield Ok(StreamResponse::Task(first));
1048            if settled && !prepared.runs {
1049                return;
1050            }
1051            while let Some(update) = updates.recv().await {
1052                let ends = matches!(
1053                    &update,
1054                    StreamResponse::StatusUpdate(event) if ends_subscription(event.status.state)
1055                );
1056                yield Ok(update);
1057                if ends {
1058                    return;
1059                }
1060            }
1061        };
1062        Ok(stream.boxed())
1063    }
1064
1065    /// Retrieves one of this caller's tasks by ID.
1066    ///
1067    /// Optionally limits the number of history messages returned.
1068    ///
1069    /// # Errors
1070    ///
1071    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or belongs to
1072    /// another caller.
1073    pub async fn tasks_get(
1074        &self,
1075        task_id: &str,
1076        history_len: Option<u32>,
1077    ) -> Result<Task, A2aError> {
1078        self.intercepted(
1079            "GetTask",
1080            TaskQuery { id: task_id.to_string(), history_length: history_len },
1081            |p: TaskQuery| async move { self.tasks_get_direct(&p.id, p.history_length).await },
1082        )
1083        .await
1084    }
1085
1086    /// [`tasks_get`](Self::tasks_get) without the call interceptors.
1087    async fn tasks_get_direct(
1088        &self,
1089        task_id: &str,
1090        history_len: Option<u32>,
1091    ) -> Result<Task, A2aError> {
1092        validate_id(task_id, "taskId")?;
1093        let mut entry = self.owned_task(task_id).await?;
1094
1095        // Truncate history if requested
1096        if let Some(len) = history_len {
1097            let len = len as usize;
1098            if entry.history.len() > len {
1099                let start = entry.history.len() - len;
1100                entry.history = entry.history[start..].to_vec();
1101            }
1102        }
1103
1104        internal_task_to_wire(&entry)
1105    }
1106
1107    /// Cancels one of this caller's tasks: stops its agent run, if one is in progress,
1108    /// and moves it to `CANCELED`. The run ends without recording its partial output.
1109    ///
1110    /// # Errors
1111    ///
1112    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or belongs to
1113    /// another caller, or [`A2aError::TaskNotCancelable`] if the task is in a
1114    /// terminal state, including one its run reached while it was being cancelled.
1115    pub async fn tasks_cancel(&self, task_id: &str) -> Result<Task, A2aError> {
1116        self.intercepted(
1117            "CancelTask",
1118            TaskIdOnly { id: task_id.to_string() },
1119            |p: TaskIdOnly| async move { self.tasks_cancel_direct(&p.id).await },
1120        )
1121        .await
1122    }
1123
1124    /// [`tasks_cancel`](Self::tasks_cancel) without the call interceptors.
1125    async fn tasks_cancel_direct(&self, task_id: &str) -> Result<Task, A2aError> {
1126        validate_id(task_id, "taskId")?;
1127        let entry = self.owned_task(task_id).await?;
1128        let not_cancelable = |state: TaskState| A2aError::TaskNotCancelable {
1129            task_id: task_id.to_string(),
1130            current_state: format!("{state:?}"),
1131        };
1132
1133        if is_terminal_state(entry.status.state) {
1134            return Err(not_cancelable(entry.status.state));
1135        }
1136
1137        // Stop the run first. A run that ends in the meantime has already moved the task to
1138        // its final state, and the transition below then reports it as not cancelable.
1139        self.handler.running.cancel(task_id);
1140        match self
1141            .handler
1142            .executor
1143            .update_status(
1144                task_id,
1145                &entry.context_id,
1146                TaskState::Canceled,
1147                Vec::new(),
1148                Some(serde_json::Map::new()),
1149            )
1150            .await
1151        {
1152            Ok(_) => {}
1153            // The cancelled run may have recorded the cancellation first.
1154            Err(A2aError::InvalidStateTransition { .. }) => {
1155                let current = self.handler.task_store.get_task(task_id).await?;
1156                if current.status.state != TaskState::Canceled {
1157                    return Err(not_cancelable(current.status.state));
1158                }
1159            }
1160            Err(error) => return Err(error),
1161        }
1162
1163        // The remote tasks the waiting task waited on will get no answer now.
1164        if entry.status.state == TaskState::InputRequired
1165            && let Some(runner_config) = &self.handler.runner_config
1166        {
1167            super::run::cancel_waiting_remote_tasks(runner_config, self.caller.as_ref(), &entry)
1168                .await;
1169        }
1170
1171        let updated = self.handler.task_store.get_task(task_id).await?;
1172        internal_task_to_wire(&updated)
1173    }
1174
1175    /// Lists this caller's tasks, one page at a time (A2A §3.1.4).
1176    ///
1177    /// - **Filters:** `context_id`, `state`, and `status_timestamp_after` (RFC 3339; tasks
1178    ///   updated at or after it).
1179    /// - **Order:** most recently updated first.
1180    /// - **Page size:** `page_size` tasks per page, 50 when unset, between 1 and 100.
1181    ///   `next_page_token` continues the list, and is empty on the last page.
1182    /// - **Task contents:** each task keeps its last `history_length` messages (all when
1183    ///   unset). It keeps its artifacts only with `include_artifacts`.
1184    ///
1185    /// # Errors
1186    ///
1187    /// Returns [`A2aError::InvalidParams`] for a page size out of range, a malformed
1188    /// timestamp or page token, and an error if the task store fails.
1189    pub async fn tasks_list(&self, params: ListTasksParams) -> Result<TaskListResponse, A2aError> {
1190        self.intercepted("ListTasks", params, |p: ListTasksParams| async move {
1191            self.tasks_list_direct(p).await
1192        })
1193        .await
1194    }
1195
1196    /// [`tasks_list`](Self::tasks_list) without the call interceptors.
1197    async fn tasks_list_direct(
1198        &self,
1199        params: ListTasksParams,
1200    ) -> Result<TaskListResponse, A2aError> {
1201        // As a2a-go: a page size of 0 is no page size.
1202        let page_size = match params.page_size {
1203            None | Some(0) => DEFAULT_PAGE_SIZE,
1204            Some(size @ 1..=MAX_PAGE_SIZE) => size,
1205            Some(size) => {
1206                return Err(A2aError::InvalidParams {
1207                    message: format!("pageSize must be between 1 and {MAX_PAGE_SIZE}, got {size}"),
1208                });
1209            }
1210        };
1211        let updated_after = params
1212            .status_timestamp_after
1213            .as_deref()
1214            .map(|timestamp| {
1215                chrono::DateTime::parse_from_rfc3339(timestamp)
1216                    .map(|time| time.with_timezone(&chrono::Utc))
1217                    .map_err(|e| A2aError::InvalidParams {
1218                        message: format!("statusTimestampAfter {timestamp:?}: {e}"),
1219                    })
1220            })
1221            .transpose()?;
1222        let after = params
1223            .page_token
1224            .as_deref()
1225            .filter(|t| !t.is_empty())
1226            .map(PageCursor::decode)
1227            .transpose()?;
1228        let history_length = params.history_length;
1229        let include_artifacts = params.include_artifacts.unwrap_or(false);
1230
1231        let unpaged = ListTasksParams { page_size: None, page_token: None, ..params };
1232        let mut entries: Vec<TaskStoreEntry> = self
1233            .handler
1234            .task_store
1235            .list_tasks(unpaged)
1236            .await?
1237            .into_iter()
1238            .filter(|entry| entry.owner() == self.owner())
1239            .filter(|entry| updated_after.is_none_or(|after| status_time(entry) >= after))
1240            .collect();
1241        entries.sort_by(|a, b| b.updated_at.cmp(&a.updated_at).then_with(|| a.id.cmp(&b.id)));
1242
1243        let total_size = entries.len();
1244        let start = after.map_or(0, |cursor| {
1245            entries.iter().position(|entry| cursor.precedes(entry)).unwrap_or(entries.len())
1246        });
1247        let end = (start + page_size as usize).min(entries.len());
1248        let next_page_token = if end < entries.len() {
1249            PageCursor::after(&entries[end - 1]).encode()
1250        } else {
1251            String::new()
1252        };
1253
1254        let tasks = entries[start..end]
1255            .iter()
1256            .cloned()
1257            .map(|mut entry| {
1258                if let Some(len) = history_length {
1259                    let keep = entry.history.len().saturating_sub(len as usize);
1260                    entry.history.drain(..keep);
1261                }
1262                if !include_artifacts {
1263                    entry.artifacts.clear();
1264                }
1265                internal_task_to_wire(&entry)
1266            })
1267            .collect::<Result<Vec<_>, _>>()?;
1268        Ok(TaskListResponse {
1269            tasks,
1270            next_page_token,
1271            page_size,
1272            total_size: u32::try_from(total_size).unwrap_or(u32::MAX),
1273        })
1274    }
1275
1276    /// Subscribes to one of this caller's tasks (A2A §3.1.6): the stream starts with the
1277    /// task as it is now, then carries its updates as they happen, whichever request runs
1278    /// it. A send with `returnImmediately`, a stream another client opened, or a resumed
1279    /// task all qualify.
1280    ///
1281    /// The stream ends when the task reaches a terminal state or stops for its caller
1282    /// (`INPUT_REQUIRED`, `AUTH_REQUIRED`). When no run of the task is in progress, nothing
1283    /// will change it until a message continues it, so the stream holds the task and its
1284    /// status and ends.
1285    ///
1286    /// # Errors
1287    ///
1288    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or belongs to
1289    /// another caller, or [`A2aError::UnsupportedOperation`] if the task already reached a
1290    /// terminal state.
1291    pub async fn tasks_subscribe(
1292        &self,
1293        task_id: &str,
1294    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
1295        self.intercepted_stream(
1296            "SubscribeToTask",
1297            TaskIdOnly { id: task_id.to_string() },
1298            |p: TaskIdOnly| async move { self.tasks_subscribe_direct(&p.id).await },
1299        )
1300        .await
1301    }
1302
1303    /// [`tasks_subscribe`](Self::tasks_subscribe) without the call interceptors.
1304    async fn tasks_subscribe_direct(
1305        &self,
1306        task_id: &str,
1307    ) -> Result<BoxStream<'static, Result<StreamResponse, A2aError>>, A2aError> {
1308        self.handler.require(Capability::Streaming("SubscribeToTask")).await?;
1309        let entry = self.owned_task(task_id).await?;
1310        if is_terminal_state(entry.status.state) {
1311            return Err(A2aError::UnsupportedOperation {
1312                method: format!(
1313                    "subscribing to task {task_id} in terminal state {:?}",
1314                    entry.status.state
1315                ),
1316            });
1317        }
1318
1319        // Subscribe before reading the task, so no update falls between the snapshot and the
1320        // first live one. One that arrives twice only repeats a state the client has.
1321        let mut updates = self.handler.executor.subscribe(task_id);
1322        let snapshot = self.owned_task(task_id).await?;
1323        let task = internal_task_to_wire(&snapshot)?;
1324        // A task with no run in progress has nothing more to send: the snapshot is all.
1325        let settled =
1326            ends_subscription(snapshot.status.state) || !self.handler.running.contains(task_id);
1327
1328        let stream = async_stream::stream! {
1329            yield Ok(StreamResponse::Task(task));
1330            if settled {
1331                return;
1332            }
1333            while let Some(update) = updates.recv().await {
1334                let ends = matches!(
1335                    &update,
1336                    StreamResponse::StatusUpdate(event) if ends_subscription(event.status.state)
1337                );
1338                yield Ok(update);
1339                if ends {
1340                    return;
1341                }
1342            }
1343        };
1344        Ok(stream.boxed())
1345    }
1346
1347    /// Creates a push notification configuration for one of this caller's tasks.
1348    ///
1349    /// Assigns a server-generated config ID when the config has none, and stores the
1350    /// config on the task, replacing a config with the same ID.
1351    ///
1352    /// # Errors
1353    ///
1354    /// Returns [`A2aError::InvalidParams`] when the config's URL is not an absolute
1355    /// `http` or `https` URL, and [`A2aError::TaskNotFound`] if the task does not exist or
1356    /// belongs to another caller.
1357    pub async fn push_config_create(
1358        &self,
1359        task_id: &str,
1360        config: TaskPushNotificationConfig,
1361    ) -> Result<TaskPushNotificationConfig, A2aError> {
1362        self.intercepted(
1363            "CreateTaskPushNotificationConfig",
1364            PushConfigCreate { task_id: task_id.to_string(), config },
1365            |p: PushConfigCreate| async move {
1366                self.push_config_create_direct(&p.task_id, p.config).await
1367            },
1368        )
1369        .await
1370    }
1371
1372    /// [`push_config_create`](Self::push_config_create) without the call interceptors.
1373    async fn push_config_create_direct(
1374        &self,
1375        task_id: &str,
1376        mut config: TaskPushNotificationConfig,
1377    ) -> Result<TaskPushNotificationConfig, A2aError> {
1378        self.handler.require(Capability::PushNotifications).await?;
1379        validate_push_url(&config.url)?;
1380        self.owned_task(task_id).await?;
1381        if config.id.as_deref().is_none_or(str::is_empty) {
1382            config.id = Some(uuid::Uuid::new_v4().to_string());
1383        }
1384        config.task_id = Some(task_id.to_string());
1385        self.handler.executor.save_push_config(task_id, config).await
1386    }
1387
1388    /// Retrieves a push notification configuration by task ID and config ID.
1389    ///
1390    /// # Errors
1391    ///
1392    /// Returns [`A2aError::TaskNotFound`] if the task or config does not exist, or
1393    /// the task belongs to another caller.
1394    pub async fn push_config_get(
1395        &self,
1396        task_id: &str,
1397        config_id: &str,
1398    ) -> Result<TaskPushNotificationConfig, A2aError> {
1399        self.intercepted(
1400            "GetTaskPushNotificationConfig",
1401            PushConfigRef { task_id: task_id.to_string(), id: config_id.to_string() },
1402            |p: PushConfigRef| async move { self.push_config_get_direct(&p.task_id, &p.id).await },
1403        )
1404        .await
1405    }
1406
1407    /// [`push_config_get`](Self::push_config_get) without the call interceptors.
1408    async fn push_config_get_direct(
1409        &self,
1410        task_id: &str,
1411        config_id: &str,
1412    ) -> Result<TaskPushNotificationConfig, A2aError> {
1413        self.handler.require(Capability::PushNotifications).await?;
1414        let entry = self.owned_task(task_id).await?;
1415
1416        entry.push_configs.iter().find(|c| c.id.as_deref() == Some(config_id)).cloned().ok_or_else(
1417            || A2aError::TaskNotFound {
1418                task_id: format!("push config {config_id} on task {task_id}"),
1419            },
1420        )
1421    }
1422
1423    /// Lists all push notification configurations for one of this caller's tasks.
1424    ///
1425    /// # Errors
1426    ///
1427    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or belongs to
1428    /// another caller.
1429    pub async fn push_config_list(
1430        &self,
1431        task_id: &str,
1432    ) -> Result<Vec<TaskPushNotificationConfig>, A2aError> {
1433        self.intercepted(
1434            "ListTaskPushNotificationConfigs",
1435            TaskIdOnly { id: task_id.to_string() },
1436            |p: TaskIdOnly| async move { self.push_config_list_direct(&p.id).await },
1437        )
1438        .await
1439    }
1440
1441    /// [`push_config_list`](Self::push_config_list) without the call interceptors.
1442    async fn push_config_list_direct(
1443        &self,
1444        task_id: &str,
1445    ) -> Result<Vec<TaskPushNotificationConfig>, A2aError> {
1446        self.handler.require(Capability::PushNotifications).await?;
1447        let entry = self.owned_task(task_id).await?;
1448        Ok(entry.push_configs)
1449    }
1450
1451    /// Deletes a push notification configuration. Deleting a config the task does not have
1452    /// succeeds, as A2A config stores do.
1453    ///
1454    /// # Errors
1455    ///
1456    /// Returns [`A2aError::TaskNotFound`] if the task does not exist or belongs to another
1457    /// caller.
1458    pub async fn push_config_delete(&self, task_id: &str, config_id: &str) -> Result<(), A2aError> {
1459        self.intercepted("DeleteTaskPushNotificationConfig", PushConfigRef { task_id: task_id.to_string(), id: config_id.to_string() }, |p: PushConfigRef| async move { self.push_config_delete_direct(&p.task_id, &p.id).await }).await
1460    }
1461
1462    /// [`push_config_delete`](Self::push_config_delete) without the call interceptors.
1463    async fn push_config_delete_direct(
1464        &self,
1465        task_id: &str,
1466        config_id: &str,
1467    ) -> Result<(), A2aError> {
1468        self.handler.require(Capability::PushNotifications).await?;
1469        self.owned_task(task_id).await?;
1470        self.handler.executor.delete_push_config(task_id, config_id).await
1471    }
1472}
1473
1474/// An optional A2A operation the agent card can say the agent does not offer.
1475enum Capability {
1476    /// `SendStreamingMessage` or `SubscribeToTask`, named for the error.
1477    Streaming(&'static str),
1478    /// Push notification configuration.
1479    PushNotifications,
1480}
1481
1482/// `ListTasks` page size when the request sets none (A2A §3.1.4).
1483const DEFAULT_PAGE_SIZE: u32 = 50;
1484
1485/// The largest `ListTasks` page size a request may ask for (A2A §3.1.4).
1486const MAX_PAGE_SIZE: u32 = 100;
1487
1488/// Where a `ListTasks` page ended: the last task listed, in the list's order (most recently
1489/// updated first, then by ID). Its page token is opaque to the client.
1490struct PageCursor {
1491    updated_at: chrono::DateTime<chrono::Utc>,
1492    id: String,
1493}
1494
1495impl PageCursor {
1496    fn after(entry: &TaskStoreEntry) -> Self {
1497        Self { updated_at: entry.updated_at, id: entry.id.clone() }
1498    }
1499
1500    /// Whether `entry` comes after this cursor in the list's order.
1501    fn precedes(&self, entry: &TaskStoreEntry) -> bool {
1502        entry.updated_at < self.updated_at
1503            || (entry.updated_at == self.updated_at && entry.id > self.id)
1504    }
1505
1506    fn encode(&self) -> String {
1507        use base64::Engine as _;
1508        let raw = format!("{}|{}", self.updated_at.to_rfc3339(), self.id);
1509        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw)
1510    }
1511
1512    fn decode(token: &str) -> Result<Self, A2aError> {
1513        use base64::Engine as _;
1514        let invalid =
1515            || A2aError::InvalidParams { message: format!("invalid pageToken {token:?}") };
1516        let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD
1517            .decode(token)
1518            .ok()
1519            .and_then(|bytes| String::from_utf8(bytes).ok())
1520            .ok_or_else(invalid)?;
1521        let (time, id) = raw.split_once('|').ok_or_else(invalid)?;
1522        let updated_at = chrono::DateTime::parse_from_rfc3339(time)
1523            .map_err(|_| invalid())?
1524            .with_timezone(&chrono::Utc);
1525        Ok(Self { updated_at, id: id.to_string() })
1526    }
1527}
1528
1529/// The agent runs in progress, by task ID, so cancelling a task stops its run.
1530#[derive(Default)]
1531struct RunningTasks {
1532    next_run: AtomicU64,
1533    runs: Mutex<HashMap<String, (u64, CancellationToken)>>,
1534}
1535
1536impl RunningTasks {
1537    /// Registers a run of `task_id`. Its token is a child of `parent`, the runner
1538    /// configuration's own token, which therefore still stops it. The run stays registered
1539    /// until the returned guard is dropped.
1540    fn start(self: &Arc<Self>, task_id: &str, parent: Option<&CancellationToken>) -> RunGuard {
1541        let token = parent.map_or_else(CancellationToken::new, CancellationToken::child_token);
1542        let run = self.next_run.fetch_add(1, Ordering::Relaxed);
1543        self.runs().insert(task_id.to_string(), (run, token.clone()));
1544        RunGuard { running: Arc::clone(self), task_id: task_id.to_string(), run, token }
1545    }
1546
1547    /// Whether a run of `task_id` is in progress.
1548    fn contains(&self, task_id: &str) -> bool {
1549        self.runs().contains_key(task_id)
1550    }
1551
1552    /// Cancels the run of `task_id`, if one is in progress.
1553    fn cancel(&self, task_id: &str) {
1554        if let Some((_, token)) = self.runs().get(task_id) {
1555            token.cancel();
1556        }
1557    }
1558
1559    fn runs(&self) -> MutexGuard<'_, HashMap<String, (u64, CancellationToken)>> {
1560        self.runs.lock().unwrap_or_else(PoisonError::into_inner)
1561    }
1562}
1563
1564/// A registered run. Dropping it unregisters the run, unless a later run of the same task,
1565/// one that resumed it, has taken its place.
1566struct RunGuard {
1567    running: Arc<RunningTasks>,
1568    task_id: String,
1569    run: u64,
1570    token: CancellationToken,
1571}
1572
1573impl RunGuard {
1574    /// The token that stops this run.
1575    fn token(&self) -> &CancellationToken {
1576        &self.token
1577    }
1578}
1579
1580impl Drop for RunGuard {
1581    fn drop(&mut self) {
1582        let mut runs = self.running.runs();
1583        if runs.get(&self.task_id).is_some_and(|(run, _)| *run == self.run) {
1584            runs.remove(&self.task_id);
1585        }
1586    }
1587}
1588
1589/// Whether a task in `state` has nothing more for a subscriber until a message continues
1590/// it: it ended, or it waits on its caller.
1591fn ends_subscription(state: TaskState) -> bool {
1592    is_terminal_state(state) || matches!(state, TaskState::InputRequired | TaskState::AuthRequired)
1593}
1594
1595/// Returns `true` if the given task state is terminal.
1596fn is_terminal_state(state: TaskState) -> bool {
1597    matches!(
1598        state,
1599        TaskState::Completed | TaskState::Failed | TaskState::Canceled | TaskState::Rejected
1600    )
1601}
1602
1603#[cfg(test)]
1604mod tests {
1605    use super::super::push::NoOpPushNotificationSender;
1606    use super::super::task_store::InMemoryTaskStore;
1607    use super::*;
1608    use a2a_protocol_types::artifact::Artifact;
1609    use a2a_protocol_types::events::{TaskArtifactUpdateEvent, TaskStatusUpdateEvent};
1610    use a2a_protocol_types::task::{ContextId, TaskId};
1611    use a2a_protocol_types::{
1612        AgentCapabilities, AgentCard, AgentInterface, AgentSkill, MessageId, MessageRole, Part,
1613        TaskPushNotificationConfig,
1614    };
1615
1616    // ── message/stream must carry real agent output ────────────────────────
1617    //
1618    // The handler used to create a task and transition Working -> Completed without invoking the
1619    // Runner, so a client saw a task reporting success that produced nothing. Both reference ADK
1620    // implementations drive the runner and translate its events; these assert that contract.
1621
1622    /// Reads the text out of an A2A part, or `None` for non-text content.
1623    fn part_text(part: &a2a_protocol_types::Part) -> Option<&str> {
1624        match &part.content {
1625            a2a_protocol_types::PartContent::Text(text) => Some(text.as_str()),
1626            _ => None,
1627        }
1628    }
1629
1630    /// Emits `chunks` as partial events then a final one, the shape a streaming model produces.
1631    struct ChunkingAgent {
1632        chunks: Vec<String>,
1633    }
1634
1635    struct SnapshotAgent {
1636        prefix: String,
1637        snapshot: String,
1638    }
1639
1640    #[async_trait::async_trait]
1641    impl adk_core::Agent for SnapshotAgent {
1642        fn name(&self) -> &str {
1643            "snapshot_agent"
1644        }
1645
1646        fn description(&self) -> &str {
1647            "emits an authoritative response after text deltas"
1648        }
1649
1650        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
1651            &[]
1652        }
1653
1654        async fn run(
1655            &self,
1656            _ctx: Arc<dyn adk_core::InvocationContext>,
1657        ) -> adk_core::Result<adk_core::EventStream> {
1658            let mut first = adk_core::Event::new("invocation");
1659            first.set_content(adk_core::Content::new("model").with_text(&self.prefix));
1660            let mut delta = adk_core::Event::new("invocation");
1661            delta.llm_response.partial = true;
1662            delta.set_content(adk_core::Content::new("model").with_text("Hello"));
1663            let mut terminal = delta.clone();
1664            terminal.llm_response.partial = false;
1665            terminal.llm_response.provider_metadata =
1666                Some(serde_json::json!({"content_complete": true}));
1667            terminal.set_content(adk_core::Content::new("model").with_text(&self.snapshot));
1668            Ok(Box::pin(futures::stream::iter(vec![Ok(first), Ok(delta), Ok(terminal)])))
1669        }
1670    }
1671
1672    #[async_trait::async_trait]
1673    impl adk_core::Agent for ChunkingAgent {
1674        fn name(&self) -> &str {
1675            "chunking_agent"
1676        }
1677
1678        fn description(&self) -> &str {
1679            "emits partial text chunks"
1680        }
1681
1682        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
1683            &[]
1684        }
1685
1686        async fn run(
1687            &self,
1688            _ctx: Arc<dyn adk_core::InvocationContext>,
1689        ) -> adk_core::Result<adk_core::EventStream> {
1690            let chunks = self.chunks.clone();
1691            let last = chunks.len().saturating_sub(1);
1692            let events: Vec<adk_core::Result<adk_core::Event>> = chunks
1693                .into_iter()
1694                .enumerate()
1695                .map(|(i, text)| {
1696                    let mut event = adk_core::Event::new("chunking_agent");
1697                    event.llm_response.content =
1698                        Some(adk_core::Content::new("model").with_text(&text));
1699                    event.llm_response.partial = i < last;
1700                    Ok(event)
1701                })
1702                .collect();
1703            Ok(Box::pin(futures::stream::iter(events)))
1704        }
1705    }
1706
1707    /// Fails immediately, to check the terminal state is not reported as success.
1708    struct FailingAgent;
1709
1710    #[async_trait::async_trait]
1711    impl adk_core::Agent for FailingAgent {
1712        fn name(&self) -> &str {
1713            "failing_agent"
1714        }
1715
1716        fn description(&self) -> &str {
1717            "fails immediately"
1718        }
1719
1720        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
1721            &[]
1722        }
1723
1724        async fn run(
1725            &self,
1726            _ctx: Arc<dyn adk_core::InvocationContext>,
1727        ) -> adk_core::Result<adk_core::EventStream> {
1728            Ok(Box::pin(futures::stream::iter(vec![Err(adk_core::AdkError::model(
1729                "upstream exploded",
1730            ))])))
1731        }
1732    }
1733
1734    fn handler_with_agent(agent: Arc<dyn adk_core::Agent>) -> (RequestHandler, Arc<dyn TaskStore>) {
1735        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::new());
1736        let executor = Arc::new(V1Executor::new(store.clone()));
1737        let cached = Arc::new(RwLock::new(CachedAgentCard::new(make_test_agent_card())));
1738        let runner_config = Arc::new(
1739            adk_runner::Runner::builder()
1740                .app_name("a2a-stream-test")
1741                .agent(agent)
1742                .session_service(Arc::new(adk_session::InMemorySessionService::new()))
1743                .build_config(),
1744        );
1745        let handler = RequestHandler::with_runner(
1746            executor,
1747            store.clone(),
1748            Arc::new(NoOpPushNotificationSender),
1749            cached,
1750            runner_config,
1751        );
1752        (handler, store)
1753    }
1754
1755    /// Whether an update comes from streamed partial events (`adk_partial`).
1756    fn is_partial(update: &TaskArtifactUpdateEvent) -> bool {
1757        update.metadata.as_ref().and_then(|meta| meta.get("adk_partial"))
1758            == Some(&serde_json::json!(true))
1759    }
1760
1761    /// The answer a client builds from a stream's non-partial artifact updates.
1762    fn answer_text(updates: &[TaskArtifactUpdateEvent]) -> String {
1763        let mut text = String::new();
1764        for update in updates.iter().filter(|update| !is_partial(update)) {
1765            if update.append != Some(true) {
1766                text.clear();
1767            }
1768            text.extend(update.artifact.parts.iter().filter_map(part_text));
1769        }
1770        text
1771    }
1772
1773    /// The text of a stored task's artifacts, without the temporary partial one.
1774    fn stored_answer(entry: &TaskStoreEntry) -> String {
1775        entry
1776            .artifacts
1777            .iter()
1778            .filter(|artifact| {
1779                artifact.metadata.as_ref().and_then(|meta| meta.get("adk_partial")).is_none()
1780            })
1781            .flat_map(|artifact| artifact.parts.iter().filter_map(part_text))
1782            .collect()
1783    }
1784
1785    async fn stream_updates(
1786        handler: &RequestHandler,
1787    ) -> (String, Vec<TaskArtifactUpdateEvent>, Vec<TaskState>) {
1788        let mut stream = handler.message_stream(make_test_message()).await.expect("stream starts");
1789        let (mut task_id, mut artifacts, mut states) = (String::new(), Vec::new(), Vec::new());
1790        while let Some(item) = stream.next().await {
1791            match item.expect("no stream error") {
1792                StreamResponse::Task(task) => task_id = task.id.0,
1793                StreamResponse::ArtifactUpdate(e) => artifacts.push(e),
1794                StreamResponse::StatusUpdate(e) => states.push(e.status.state),
1795                _ => {}
1796            }
1797        }
1798        (task_id, artifacts, states)
1799    }
1800
1801    #[tokio::test]
1802    async fn streamed_chunks_fill_a_temporary_artifact_and_the_answer_has_its_own() {
1803        let (handler, store) = handler_with_agent(Arc::new(ChunkingAgent {
1804            chunks: vec!["Hel".into(), "lo ".into(), "world".into()],
1805        }));
1806        let (task_id, artifacts, states) = stream_updates(&handler).await;
1807
1808        // As adk-go's artifact-per-run layout: each chunk replaces a temporary artifact
1809        // marked `adk_partial`, the answer goes to its own artifact, and the temporary one
1810        // is emptied (`{}`, lastChunk) before the final status.
1811        assert_eq!(artifacts.len(), 4, "two chunks, the answer, the reset: {artifacts:?}");
1812        assert!(is_partial(&artifacts[0]) && is_partial(&artifacts[1]));
1813        assert_eq!(artifacts[0].artifact.id, artifacts[1].artifact.id);
1814        assert_eq!(artifacts[1].append, Some(false), "a chunk replaces the temporary artifact");
1815        assert!(!is_partial(&artifacts[2]));
1816        assert_ne!(artifacts[2].artifact.id, artifacts[0].artifact.id);
1817        assert_eq!(
1818            answer_text(&artifacts),
1819            "Hello world",
1820            "the final event carries the whole answer"
1821        );
1822        let reset = &artifacts[3];
1823        assert!(is_partial(reset) && reset.last_chunk == Some(true));
1824        assert_eq!(reset.artifact.id, artifacts[0].artifact.id);
1825        assert_eq!(states, vec![TaskState::Working, TaskState::Completed]);
1826
1827        let entry = store.get_task(&task_id).await.unwrap();
1828        assert_eq!(stored_answer(&entry), "Hello world", "tasks/get sees the answer");
1829    }
1830
1831    #[tokio::test]
1832    async fn an_authoritative_final_event_is_the_answer() {
1833        for prefix in ["", "Earlier. "] {
1834            for snapshot in ["Hello world", "Corrected", ""] {
1835                let (handler, store) = handler_with_agent(Arc::new(SnapshotAgent {
1836                    prefix: prefix.into(),
1837                    snapshot: snapshot.into(),
1838                }));
1839                let (task_id, artifacts, _) = stream_updates(&handler).await;
1840                let expected = format!("{prefix}{snapshot}");
1841                assert_eq!(answer_text(&artifacts), expected, "{prefix:?} {snapshot:?}");
1842                let entry = store.get_task(&task_id).await.unwrap();
1843                assert_eq!(stored_answer(&entry), expected, "{prefix:?} {snapshot:?}");
1844
1845                let (handler, _) = handler_with_agent(Arc::new(SnapshotAgent {
1846                    prefix: prefix.into(),
1847                    snapshot: snapshot.into(),
1848                }));
1849                let task = handler.message_send(make_test_message()).await.unwrap();
1850                let entry = store_entry_of(&task);
1851                assert_eq!(stored_answer(&entry), expected, "buffered {prefix:?} {snapshot:?}");
1852            }
1853        }
1854    }
1855
1856    /// A wire task as the store entry shape, for [`stored_answer`].
1857    fn store_entry_of(task: &Task) -> TaskStoreEntry {
1858        TaskStoreEntry {
1859            id: task.id.0.clone(),
1860            context_id: task.context_id.0.clone(),
1861            status: task.status.clone(),
1862            artifacts: task.artifacts.clone().unwrap_or_default(),
1863            history: Vec::new(),
1864            metadata: HashMap::new(),
1865            push_configs: Vec::new(),
1866            created_at: chrono::Utc::now(),
1867            updated_at: chrono::Utc::now(),
1868            version: 0,
1869        }
1870    }
1871
1872    /// The text of a status message's parts.
1873    fn status_text(status: &a2a_protocol_types::TaskStatus) -> String {
1874        status.message.iter().flat_map(|m| m.parts.iter().filter_map(part_text)).collect()
1875    }
1876
1877    #[tokio::test]
1878    async fn stream_failure_ends_on_a_failed_status_that_carries_the_error() {
1879        let (handler, store) = handler_with_agent(Arc::new(FailingAgent));
1880
1881        let stream = handler.message_stream(make_test_message()).await.expect("stream starts");
1882        let items: Vec<_> = stream.collect().await;
1883
1884        assert!(
1885            items.iter().all(Result::is_ok),
1886            "the error rides on the terminal status, not on a separate error item: {items:?}"
1887        );
1888        let states: Vec<_> = items
1889            .iter()
1890            .filter_map(|item| match item {
1891                Ok(StreamResponse::StatusUpdate(e)) => Some(e.status.state),
1892                _ => None,
1893            })
1894            .collect();
1895        assert!(
1896            !states.contains(&TaskState::Completed),
1897            "a failed run must never report Completed: {states:?}"
1898        );
1899
1900        // A2A §3.1.2: the stream closes at the terminal state, so the Failed status is last.
1901        let Some(Ok(StreamResponse::StatusUpdate(last))) = items.last() else {
1902            panic!("the stream must end on a status update: {items:?}");
1903        };
1904        assert_eq!(last.status.state, TaskState::Failed);
1905        let text = status_text(&last.status);
1906        assert!(text.contains("upstream exploded"), "the status message names the error: {text}");
1907
1908        // The stored task says the same, and so does a non-streaming send that fails.
1909        let stored = store.get_task(&last.task_id.0).await.unwrap();
1910        assert_eq!(status_text(&stored.status), text);
1911        let (handler, _) = handler_with_agent(Arc::new(FailingAgent));
1912        let sent = handler.message_send(make_test_message()).await.unwrap();
1913        assert_eq!(sent.status.state, TaskState::Failed);
1914        assert_eq!(status_text(&sent.status), text);
1915    }
1916
1917    // ── Waiting on the caller, continuing a task, cancel and returnImmediately ──
1918
1919    /// Asks for approval with a long-running call, the way a human-in-the-loop tool does,
1920    /// and answers once the caller sends the call's result.
1921    struct ApprovalAgent;
1922
1923    #[async_trait::async_trait]
1924    impl adk_core::Agent for ApprovalAgent {
1925        fn name(&self) -> &str {
1926            "approval_agent"
1927        }
1928
1929        fn description(&self) -> &str {
1930            "waits for an approval"
1931        }
1932
1933        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
1934            &[]
1935        }
1936
1937        async fn run(
1938            &self,
1939            ctx: Arc<dyn adk_core::InvocationContext>,
1940        ) -> adk_core::Result<adk_core::EventStream> {
1941            let approved = ctx.user_content().parts.iter().any(|part| {
1942                matches!(
1943                    part,
1944                    adk_core::Part::FunctionResponse { function_response, id: Some(id), .. }
1945                        if id == "call-approve"
1946                            && function_response.response["status"] == "approved"
1947                )
1948            });
1949            if approved {
1950                let mut done = adk_core::Event::new("inv");
1951                done.set_content(adk_core::Content::new("model").with_text("Approved."));
1952                return Ok(Box::pin(futures::stream::iter(vec![Ok(done)])));
1953            }
1954
1955            let mut call = adk_core::Event::new("inv");
1956            call.set_content(adk_core::Content {
1957                role: "model".to_string(),
1958                parts: vec![adk_core::Part::FunctionCall {
1959                    name: "request_approval".to_string(),
1960                    args: serde_json::json!({"amount": 500}),
1961                    id: Some("call-approve".to_string()),
1962                    thought_signature: None,
1963                }],
1964            });
1965            call.long_running_tool_ids = vec!["call-approve".to_string()];
1966            let mut interim = adk_core::Event::new("inv");
1967            interim.set_content(adk_core::Content {
1968                role: "user".to_string(),
1969                parts: vec![adk_core::Part::FunctionResponse {
1970                    function_response: adk_core::FunctionResponseData::new(
1971                        "request_approval",
1972                        serde_json::json!({"status": "pending"}),
1973                    ),
1974                    id: Some("call-approve".to_string()),
1975                    annotations: None,
1976                }],
1977            });
1978            let mut text = adk_core::Event::new("inv");
1979            text.set_content(adk_core::Content::new("model").with_text("Approval pending."));
1980            Ok(Box::pin(futures::stream::iter(vec![Ok(call), Ok(interim), Ok(text)])))
1981        }
1982    }
1983
1984    /// The caller's approval, a `function_response` data part tagged the way adk-python and
1985    /// adk-go tag it, sent for `task_id`.
1986    fn approval_for(task_id: &TaskId, context_id: Option<&ContextId>) -> Message {
1987        let part: Part = serde_json::from_value(serde_json::json!({
1988            "data": {"id": "call-approve", "name": "request_approval", "response": {"status": "approved"}},
1989            "metadata": {"adk_type": "function_response"}
1990        }))
1991        .unwrap();
1992        Message {
1993            id: MessageId::new("msg-2"),
1994            role: MessageRole::User,
1995            parts: vec![part],
1996            task_id: Some(task_id.clone()),
1997            context_id: context_id.cloned(),
1998            reference_task_ids: None,
1999            extensions: None,
2000            metadata: None,
2001        }
2002    }
2003
2004    fn artifact_texts(task: &Task) -> Vec<String> {
2005        task.artifacts
2006            .iter()
2007            .flatten()
2008            .flat_map(|artifact| artifact.parts.iter().filter_map(part_text).map(str::to_string))
2009            .collect()
2010    }
2011
2012    #[tokio::test]
2013    async fn a_waiting_task_names_the_pending_call_and_the_answer_continues_it() {
2014        let (handler, _) = handler_with_agent(Arc::new(ApprovalAgent));
2015
2016        let waiting = handler.message_send(make_test_message()).await.unwrap();
2017        assert_eq!(waiting.status.state, TaskState::InputRequired);
2018        let parts: Vec<_> = waiting
2019            .status
2020            .message
2021            .as_ref()
2022            .expect("the status names the pending call")
2023            .parts
2024            .iter()
2025            .map(|part| serde_json::to_value(part).unwrap())
2026            .collect();
2027        assert_eq!(
2028            parts,
2029            vec![
2030                serde_json::json!({
2031                    "data": {"id": "call-approve", "name": "request_approval", "args": {"amount": 500}},
2032                    "metadata": {"adk_type": "function_call", "adk_is_long_running": true}
2033                }),
2034                serde_json::json!({
2035                    "data": {"id": "call-approve", "name": "request_approval", "response": {"status": "pending"}},
2036                    "metadata": {"adk_type": "function_response"}
2037                }),
2038            ]
2039        );
2040
2041        let answer = approval_for(&waiting.id, Some(&waiting.context_id));
2042        let done = handler.message_send(answer).await.unwrap();
2043        assert_eq!(done.id, waiting.id, "the answer continues the same task");
2044        assert_eq!(done.status.state, TaskState::Completed);
2045        assert!(artifact_texts(&done).contains(&"Approved.".to_string()), "{done:?}");
2046    }
2047
2048    #[tokio::test]
2049    async fn a_stream_names_the_pending_call_and_a_task_id_alone_continues_the_task() {
2050        let (handler, _) = handler_with_agent(Arc::new(ApprovalAgent));
2051
2052        let items: Vec<_> =
2053            handler.message_stream(make_test_message()).await.unwrap().collect().await;
2054        let Some(Ok(StreamResponse::StatusUpdate(waiting))) = items.last() else {
2055            panic!("the stream ends on a status: {items:?}");
2056        };
2057        assert_eq!(waiting.status.state, TaskState::InputRequired);
2058        assert_eq!(waiting.status.message.as_ref().map(|m| m.parts.len()), Some(2));
2059
2060        // A2A §3.4: with only a taskId, the context is the task's.
2061        let answer = approval_for(&waiting.task_id, None);
2062        let items: Vec<_> = handler.message_stream(answer).await.unwrap().collect().await;
2063        let Some(Ok(StreamResponse::Task(first))) = items.first() else {
2064            panic!("the stream starts with the task: {items:?}");
2065        };
2066        assert_eq!(first.id, waiting.task_id, "the answer continues the same task");
2067        let Some(Ok(StreamResponse::StatusUpdate(last))) = items.last() else {
2068            panic!("the stream ends on a status: {items:?}");
2069        };
2070        assert_eq!(last.status.state, TaskState::Completed);
2071    }
2072
2073    #[tokio::test]
2074    async fn a_message_naming_a_task_it_cannot_continue_is_refused() {
2075        let (handler, _) = handler_with_agent(Arc::new(ApprovalAgent));
2076
2077        let mut unknown = make_test_message();
2078        unknown.task_id = Some(TaskId::new("no-such-task"));
2079        assert!(matches!(handler.message_send(unknown).await, Err(A2aError::TaskNotFound { .. })));
2080
2081        let waiting = handler.message_send(make_test_message()).await.unwrap();
2082        let elsewhere = approval_for(&waiting.id, Some(&ContextId::new("another-context")));
2083        assert!(matches!(
2084            handler.message_send(elsewhere).await,
2085            Err(A2aError::InvalidParams { .. })
2086        ));
2087
2088        let done = handler.message_send(approval_for(&waiting.id, None)).await.unwrap();
2089        assert_eq!(done.status.state, TaskState::Completed);
2090        let mut after_the_end = approval_for(&waiting.id, None);
2091        after_the_end.id = MessageId::new("msg-3");
2092        assert!(matches!(
2093            handler.message_send(after_the_end).await,
2094            Err(A2aError::UnsupportedOperation { .. })
2095        ));
2096    }
2097
2098    /// Answers after `delay` and records that it got that far.
2099    struct SlowAgent {
2100        delay: std::time::Duration,
2101        answered: Arc<std::sync::atomic::AtomicBool>,
2102    }
2103
2104    #[async_trait::async_trait]
2105    impl adk_core::Agent for SlowAgent {
2106        fn name(&self) -> &str {
2107            "slow_agent"
2108        }
2109
2110        fn description(&self) -> &str {
2111            "answers late"
2112        }
2113
2114        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
2115            &[]
2116        }
2117
2118        async fn run(
2119            &self,
2120            _ctx: Arc<dyn adk_core::InvocationContext>,
2121        ) -> adk_core::Result<adk_core::EventStream> {
2122            let delay = self.delay;
2123            let answered = self.answered.clone();
2124            Ok(Box::pin(async_stream::stream! {
2125                tokio::time::sleep(delay).await;
2126                answered.store(true, Ordering::SeqCst);
2127                let mut event = adk_core::Event::new("inv");
2128                event.set_content(adk_core::Content::new("model").with_text("Too late."));
2129                yield Ok(event);
2130            }))
2131        }
2132    }
2133
2134    fn slow_handler(
2135        delay_ms: u64,
2136    ) -> (RequestHandler, Arc<dyn TaskStore>, Arc<std::sync::atomic::AtomicBool>) {
2137        let answered = Arc::new(std::sync::atomic::AtomicBool::new(false));
2138        let (handler, store) = handler_with_agent(Arc::new(SlowAgent {
2139            delay: std::time::Duration::from_millis(delay_ms),
2140            answered: answered.clone(),
2141        }));
2142        (handler, store, answered)
2143    }
2144
2145    fn return_immediately() -> SendMessageConfiguration {
2146        serde_json::from_value(serde_json::json!({"returnImmediately": true})).unwrap()
2147    }
2148
2149    #[tokio::test]
2150    async fn return_immediately_answers_while_the_run_goes_on_in_the_background() {
2151        let (handler, store, _) = slow_handler(50);
2152
2153        let started = handler
2154            .message_send_with(make_test_message(), Some(&return_immediately()))
2155            .await
2156            .unwrap();
2157        assert_eq!(
2158            started.status.state,
2159            TaskState::Submitted,
2160            "the send returns the submitted task without waiting for the run"
2161        );
2162
2163        let mut state = TaskState::Submitted;
2164        for _ in 0..100 {
2165            state = store.get_task(&started.id.0).await.unwrap().status.state;
2166            if is_terminal_state(state) {
2167                break;
2168            }
2169            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
2170        }
2171        assert_eq!(state, TaskState::Completed);
2172        let done = handler.tasks_get(&started.id.0, None).await.unwrap();
2173        assert_eq!(artifact_texts(&done), vec!["Too late.".to_string()]);
2174    }
2175
2176    #[tokio::test]
2177    async fn cancel_stops_the_run_and_a_second_cancel_is_refused() {
2178        let (handler, store, answered) = slow_handler(300);
2179
2180        let started = handler
2181            .message_send_with(make_test_message(), Some(&return_immediately()))
2182            .await
2183            .unwrap();
2184        let canceled = handler.tasks_cancel(&started.id.0).await.unwrap();
2185        assert_eq!(canceled.status.state, TaskState::Canceled);
2186        assert!(matches!(
2187            handler.tasks_cancel(&started.id.0).await,
2188            Err(A2aError::TaskNotCancelable { .. })
2189        ));
2190
2191        tokio::time::sleep(std::time::Duration::from_millis(600)).await;
2192        assert!(
2193            !answered.load(Ordering::SeqCst),
2194            "cancelling stops the agent, not only the task's state"
2195        );
2196        let stored = store.get_task(&started.id.0).await.unwrap();
2197        assert_eq!(stored.status.state, TaskState::Canceled);
2198        assert!(stored.artifacts.is_empty(), "a cancelled run records no output");
2199    }
2200
2201    #[tokio::test]
2202    async fn cancelling_a_streamed_task_ends_the_stream_on_canceled() {
2203        let (handler, _, answered) = slow_handler(5_000);
2204
2205        let mut stream = handler.message_stream(make_test_message()).await.unwrap();
2206        let Some(Ok(StreamResponse::Task(task))) = stream.next().await else {
2207            panic!("the stream starts with the task");
2208        };
2209        let Some(Ok(StreamResponse::StatusUpdate(working))) = stream.next().await else {
2210            panic!("then reports it working");
2211        };
2212        assert_eq!(working.status.state, TaskState::Working);
2213
2214        let canceled = handler.tasks_cancel(&task.id.0).await.unwrap();
2215        assert_eq!(canceled.status.state, TaskState::Canceled);
2216        let rest: Vec<_> =
2217            tokio::time::timeout(std::time::Duration::from_secs(2), stream.collect::<Vec<_>>())
2218                .await
2219                .expect("a cancelled stream ends");
2220        let Some(Ok(StreamResponse::StatusUpdate(last))) = rest.last() else {
2221            panic!("the stream ends on a status: {rest:?}");
2222        };
2223        assert_eq!(last.status.state, TaskState::Canceled);
2224        assert!(!answered.load(Ordering::SeqCst));
2225    }
2226
2227    // ── Push notifications ──────────────────────────────────────────────────
2228
2229    /// Records what it would deliver: the URL and the update.
2230    #[derive(Default)]
2231    struct RecordingSender(std::sync::Mutex<Vec<(String, String)>>);
2232
2233    #[async_trait::async_trait]
2234    impl super::super::push::PushNotificationSender for RecordingSender {
2235        async fn send_status_update(
2236            &self,
2237            url: &str,
2238            event: &TaskStatusUpdateEvent,
2239            _config: &TaskPushNotificationConfig,
2240        ) -> Result<(), A2aError> {
2241            self.0.lock().unwrap().push((url.to_string(), format!("{:?}", event.status.state)));
2242            Ok(())
2243        }
2244
2245        async fn send_artifact_update(
2246            &self,
2247            url: &str,
2248            _event: &TaskArtifactUpdateEvent,
2249            _config: &TaskPushNotificationConfig,
2250        ) -> Result<(), A2aError> {
2251            self.0.lock().unwrap().push((url.to_string(), "artifact".to_string()));
2252            Ok(())
2253        }
2254    }
2255
2256    #[tokio::test]
2257    async fn a_push_config_sent_with_the_message_gets_every_update() {
2258        let sender = Arc::new(RecordingSender::default());
2259        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::new());
2260        let mut card = make_test_agent_card();
2261        card.capabilities = AgentCapabilities::none().with_push_notifications(true);
2262        let handler = RequestHandler::with_runner(
2263            Arc::new(V1Executor::new(store.clone())),
2264            store,
2265            sender.clone(),
2266            Arc::new(RwLock::new(CachedAgentCard::new(card))),
2267            Arc::new(
2268                adk_runner::Runner::builder()
2269                    .app_name("push")
2270                    .agent(Arc::new(ChunkingAgent { chunks: vec!["done".into()] }))
2271                    .session_service(Arc::new(adk_session::InMemorySessionService::new()))
2272                    .build_config(),
2273            ),
2274        );
2275        let configuration: SendMessageConfiguration = serde_json::from_value(serde_json::json!({
2276            "taskPushNotificationConfig": {"url": "https://hooks.example.com/a2a"}
2277        }))
2278        .unwrap();
2279
2280        let task =
2281            handler.message_send_with(make_test_message(), Some(&configuration)).await.unwrap();
2282        assert_eq!(handler.push_config_list(&task.id.0).await.unwrap().len(), 1);
2283
2284        // Delivery runs beside the task; wait for the last update.
2285        let mut delivered = Vec::new();
2286        for _ in 0..100 {
2287            delivered = sender.0.lock().unwrap().clone();
2288            if delivered.iter().any(|(_, what)| what == "Completed") {
2289                break;
2290            }
2291            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2292        }
2293        let what: Vec<&str> = delivered.iter().map(|(_, what)| what.as_str()).collect();
2294        assert_eq!(what, vec!["Working", "artifact", "Completed"]);
2295        assert!(delivered.iter().all(|(url, _)| url == "https://hooks.example.com/a2a"));
2296    }
2297
2298    // ── Media in artifacts ──────────────────────────────────────────────────
2299
2300    /// Answers with a caption and a PNG.
2301    struct ImageAgent;
2302
2303    #[async_trait::async_trait]
2304    impl adk_core::Agent for ImageAgent {
2305        fn name(&self) -> &str {
2306            "image_agent"
2307        }
2308
2309        fn description(&self) -> &str {
2310            "draws"
2311        }
2312
2313        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
2314            &[]
2315        }
2316
2317        async fn run(
2318            &self,
2319            _ctx: Arc<dyn adk_core::InvocationContext>,
2320        ) -> adk_core::Result<adk_core::EventStream> {
2321            let mut event = adk_core::Event::new("inv");
2322            event.set_content(
2323                adk_core::Content::new("model")
2324                    .with_text("A square.")
2325                    .with_inline_data("image/png", vec![0x89, b'P', b'N', b'G']),
2326            );
2327            Ok(Box::pin(futures::stream::iter(vec![Ok(event)])))
2328        }
2329    }
2330
2331    fn image_parts(artifacts: &[Artifact]) -> Vec<&a2a_protocol_types::Part> {
2332        artifacts
2333            .iter()
2334            .flat_map(|artifact| &artifact.parts)
2335            .filter(|part| part.media_type.as_deref() == Some("image/png"))
2336            .collect()
2337    }
2338
2339    #[tokio::test]
2340    async fn files_and_inline_data_reach_the_client_beside_the_text() {
2341        let (handler, store) = handler_with_agent(Arc::new(ImageAgent));
2342        let sent = handler.message_send(make_test_message()).await.unwrap();
2343        let artifacts = sent.artifacts.clone().unwrap_or_default();
2344        assert_eq!(artifact_texts(&sent), vec!["A square.".to_string()]);
2345        assert_eq!(image_parts(&artifacts).len(), 1, "{artifacts:?}");
2346
2347        let (handler, _) = handler_with_agent(Arc::new(ImageAgent));
2348        let updates: Vec<_> = handler
2349            .message_stream(make_test_message())
2350            .await
2351            .unwrap()
2352            .map(|item| item.unwrap())
2353            .collect()
2354            .await;
2355        let streamed: Vec<Artifact> = updates
2356            .iter()
2357            .filter_map(|update| match update {
2358                StreamResponse::ArtifactUpdate(event) => Some(event.artifact.clone()),
2359                _ => None,
2360            })
2361            .collect();
2362        assert_eq!(image_parts(&streamed).len(), 1, "the stream carries the image too");
2363        let stored = store.get_task(&sent.id.0).await.unwrap();
2364        assert_eq!(image_parts(&stored.artifacts).len(), 1);
2365    }
2366
2367    // ── ADK metadata ────────────────────────────────────────────────────────
2368
2369    #[tokio::test]
2370    async fn tasks_and_their_updates_name_the_adk_app_user_and_session() {
2371        use super::super::convert::{ADK_ERROR_MESSAGE_METADATA_KEY, ADK_EXTENSION_URI};
2372
2373        let (handler, store) =
2374            handler_with_agent(Arc::new(ChunkingAgent { chunks: vec!["hi".into()] }));
2375        let mut stream = handler.message_stream(make_test_message()).await.unwrap();
2376        let Some(Ok(StreamResponse::Task(task))) = stream.next().await else {
2377            panic!("the stream starts with the task");
2378        };
2379        let context = task.context_id.0.clone();
2380        // A new task carries only the extension marker; the run's first status update
2381        // names the app, user and session, and the task takes them on (as adk-go).
2382        let metadata = task.metadata.clone().expect("the task carries the ADK marker");
2383        assert_eq!(metadata, serde_json::json!({ ADK_EXTENSION_URI: true }));
2384        let task_id = task.id.0.clone();
2385        for update in stream.collect::<Vec<_>>().await {
2386            let metadata = match update.unwrap() {
2387                StreamResponse::StatusUpdate(event) => event.metadata,
2388                StreamResponse::ArtifactUpdate(event) => event.metadata,
2389                _ => continue,
2390            };
2391            assert_eq!(
2392                metadata.expect("every update carries it")["adk_session_id"],
2393                context.as_str()
2394            );
2395        }
2396        let stored = store.get_task(&task_id).await.unwrap().metadata;
2397        assert_eq!(stored["adk_app_name"], "a2a-stream-test");
2398        assert_eq!(stored["adk_session_id"], context.as_str());
2399        assert_eq!(stored["adk_user_id"], format!("A2A_USER_{context}"));
2400        assert_eq!(stored[ADK_EXTENSION_URI], true);
2401
2402        // A failed run marks its error text.
2403        let (handler, _) = handler_with_agent(Arc::new(FailingAgent));
2404        let failed = handler.message_send(make_test_message()).await.unwrap();
2405        let error_part = &failed.status.message.expect("the error").parts[0];
2406        assert_eq!(error_part.metadata.as_ref().unwrap()[ADK_ERROR_MESSAGE_METADATA_KEY], true);
2407    }
2408
2409    // ── Capabilities the card states ────────────────────────────────────────
2410
2411    #[tokio::test]
2412    async fn operations_the_card_says_are_off_are_refused() {
2413        let store = Arc::new(InMemoryTaskStore::new());
2414        let mut card = make_test_agent_card();
2415        card.capabilities = AgentCapabilities::none()
2416            .with_streaming(false)
2417            .with_push_notifications(false)
2418            .with_extended_agent_card(false);
2419        let handler = RequestHandler::new(
2420            Arc::new(V1Executor::new(store.clone())),
2421            store,
2422            Arc::new(NoOpPushNotificationSender),
2423            Arc::new(RwLock::new(CachedAgentCard::new(card))),
2424        );
2425
2426        let task = handler.message_send(make_test_message()).await.unwrap();
2427        assert!(matches!(
2428            handler.message_stream(make_test_message()).await,
2429            Err(A2aError::UnsupportedOperation { .. })
2430        ));
2431        assert!(matches!(
2432            handler.tasks_subscribe(&task.id.0).await,
2433            Err(A2aError::UnsupportedOperation { .. })
2434        ));
2435        assert!(matches!(
2436            handler.push_config_list(&task.id.0).await,
2437            Err(A2aError::PushNotificationNotSupported)
2438        ));
2439        let with_push: SendMessageConfiguration = serde_json::from_value(serde_json::json!({
2440            "taskPushNotificationConfig": {"url": "https://hooks.example.com/a2a"}
2441        }))
2442        .unwrap();
2443        let mut msg = make_test_message();
2444        msg.id = MessageId::new("msg-push");
2445        assert!(matches!(
2446            handler.message_send_with(msg, Some(&with_push)).await,
2447            Err(A2aError::PushNotificationNotSupported)
2448        ));
2449        // As a2a-go: a card that says there is no extended card refuses the method.
2450        assert!(matches!(
2451            handler.agent_card_extended().await,
2452            Err(A2aError::UnsupportedOperation { .. })
2453        ));
2454    }
2455
2456    // ── ListTasks pages ─────────────────────────────────────────────────────
2457
2458    #[tokio::test]
2459    async fn list_tasks_pages_through_every_task_once_newest_first() {
2460        let handler = make_handler();
2461        for i in 0..5 {
2462            let mut msg = make_test_message();
2463            msg.id = MessageId::new(format!("msg-{i}"));
2464            handler.message_send(msg).await.unwrap();
2465        }
2466
2467        let mut seen = Vec::new();
2468        let mut token = None;
2469        loop {
2470            let page = handler
2471                .tasks_list(ListTasksParams {
2472                    page_size: Some(2),
2473                    page_token: token.clone(),
2474                    ..Default::default()
2475                })
2476                .await
2477                .unwrap();
2478            assert_eq!(page.total_size, 5);
2479            assert_eq!(page.page_size, 2);
2480            assert!(page.tasks.len() <= 2);
2481            assert!(
2482                page.tasks.iter().all(|task| task.artifacts.is_none()),
2483                "no artifacts unless asked"
2484            );
2485            seen.extend(page.tasks.into_iter().map(|task| task.id.0));
2486            if page.next_page_token.is_empty() {
2487                break;
2488            }
2489            token = Some(page.next_page_token);
2490        }
2491        let mut unique = seen.clone();
2492        unique.sort();
2493        unique.dedup();
2494        assert_eq!((seen.len(), unique.len()), (5, 5), "every task once: {seen:?}");
2495
2496        // As a2a-go: a page size of 0 is the default page size.
2497        let default_page = handler
2498            .tasks_list(ListTasksParams { page_size: Some(0), ..Default::default() })
2499            .await
2500            .unwrap();
2501        assert_eq!(default_page.page_size, DEFAULT_PAGE_SIZE);
2502
2503        for bad in [
2504            ListTasksParams { page_size: Some(101), ..Default::default() },
2505            ListTasksParams { page_token: Some("not a token".into()), ..Default::default() },
2506            ListTasksParams {
2507                status_timestamp_after: Some("yesterday".into()),
2508                ..Default::default()
2509            },
2510        ] {
2511            assert!(matches!(handler.tasks_list(bad).await, Err(A2aError::InvalidParams { .. })));
2512        }
2513
2514        // Tasks updated before the cutoff are left out.
2515        let later = (chrono::Utc::now() + chrono::Duration::minutes(1)).to_rfc3339();
2516        let none = handler
2517            .tasks_list(ListTasksParams {
2518                status_timestamp_after: Some(later),
2519                ..Default::default()
2520            })
2521            .await
2522            .unwrap();
2523        assert_eq!(none.total_size, 0);
2524    }
2525
2526    // ── SubscribeToTask follows a running task ──────────────────────────────
2527
2528    /// Collects a subscription, which must end within two seconds.
2529    async fn collect_subscription(
2530        stream: BoxStream<'static, Result<StreamResponse, A2aError>>,
2531    ) -> Vec<StreamResponse> {
2532        tokio::time::timeout(std::time::Duration::from_secs(2), stream.collect::<Vec<_>>())
2533            .await
2534            .expect("the subscription ends")
2535            .into_iter()
2536            .map(|item| item.expect("no stream error"))
2537            .collect()
2538    }
2539
2540    fn last_state(updates: &[StreamResponse]) -> Option<TaskState> {
2541        updates.iter().rev().find_map(|update| match update {
2542            StreamResponse::StatusUpdate(event) => Some(event.status.state),
2543            _ => None,
2544        })
2545    }
2546
2547    fn streamed_text(updates: &[StreamResponse]) -> String {
2548        updates
2549            .iter()
2550            .filter_map(|update| match update {
2551                StreamResponse::ArtifactUpdate(event) => Some(&event.artifact),
2552                _ => None,
2553            })
2554            .flat_map(|artifact| artifact.parts.iter().filter_map(part_text))
2555            .collect()
2556    }
2557
2558    #[tokio::test]
2559    async fn a_subscriber_follows_a_background_run_to_its_end() {
2560        let (handler, _, _) = slow_handler(200);
2561        let started = handler
2562            .message_send_with(make_test_message(), Some(&return_immediately()))
2563            .await
2564            .unwrap();
2565
2566        let updates =
2567            collect_subscription(handler.tasks_subscribe(&started.id.0).await.unwrap()).await;
2568        let Some(StreamResponse::Task(first)) = updates.first() else {
2569            panic!("the subscription starts with the task: {updates:?}");
2570        };
2571        assert!(
2572            matches!(first.status.state, TaskState::Submitted | TaskState::Working),
2573            "the snapshot is the task as it stands: {:?}",
2574            first.status.state
2575        );
2576        assert_eq!(streamed_text(&updates), "Too late.", "the run's output reaches the subscriber");
2577        assert_eq!(last_state(&updates), Some(TaskState::Completed));
2578    }
2579
2580    #[tokio::test]
2581    async fn a_subscriber_follows_a_task_another_client_streams() {
2582        let (handler, _, _) = slow_handler(200);
2583        let mut stream = handler.message_stream(make_test_message()).await.unwrap();
2584        let Some(Ok(StreamResponse::Task(task))) = stream.next().await else {
2585            panic!("the stream starts with the task");
2586        };
2587        let streaming = tokio::spawn(stream.collect::<Vec<_>>());
2588
2589        let updates =
2590            collect_subscription(handler.tasks_subscribe(&task.id.0).await.unwrap()).await;
2591        assert_eq!(streamed_text(&updates), "Too late.");
2592        assert_eq!(last_state(&updates), Some(TaskState::Completed));
2593        streaming.await.unwrap();
2594    }
2595
2596    #[tokio::test]
2597    async fn a_task_waiting_on_its_caller_is_a_snapshot_and_a_finished_one_is_refused() {
2598        let (handler, _) = handler_with_agent(Arc::new(ApprovalAgent));
2599        let waiting = handler.message_send(make_test_message()).await.unwrap();
2600
2601        // As a2a-go: a task with no run in progress answers with its snapshot alone.
2602        let updates =
2603            collect_subscription(handler.tasks_subscribe(&waiting.id.0).await.unwrap()).await;
2604        let [StreamResponse::Task(snapshot)] = updates.as_slice() else {
2605            panic!("the subscription is the snapshot alone: {updates:?}");
2606        };
2607        assert_eq!(snapshot.status.state, TaskState::InputRequired);
2608
2609        handler.message_send(approval_for(&waiting.id, None)).await.unwrap();
2610        assert!(matches!(
2611            handler.tasks_subscribe(&waiting.id.0).await,
2612            Err(A2aError::UnsupportedOperation { .. })
2613        ));
2614    }
2615
2616    // ── Runs detached from their request ────────────────────────────────────
2617
2618    #[tokio::test]
2619    async fn a_run_outlives_the_stream_that_started_it() {
2620        let (handler, store, answered) = slow_handler(100);
2621        let mut stream = handler.message_stream(make_test_message()).await.unwrap();
2622        let Some(Ok(StreamResponse::Task(task))) = stream.next().await else {
2623            panic!("the stream starts with the task");
2624        };
2625        drop(stream);
2626
2627        let mut state = TaskState::Submitted;
2628        for _ in 0..100 {
2629            state = store.get_task(&task.id.0).await.unwrap().status.state;
2630            if is_terminal_state(state) {
2631                break;
2632            }
2633            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
2634        }
2635        assert_eq!(state, TaskState::Completed, "the client left; the run did not");
2636        assert!(answered.load(std::sync::atomic::Ordering::SeqCst));
2637    }
2638
2639    /// Panics as soon as its run is polled.
2640    struct PanickingAgent;
2641
2642    #[async_trait::async_trait]
2643    impl adk_core::Agent for PanickingAgent {
2644        fn name(&self) -> &str {
2645            "panicking_agent"
2646        }
2647
2648        fn description(&self) -> &str {
2649            "panics"
2650        }
2651
2652        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
2653            &[]
2654        }
2655
2656        async fn run(
2657            &self,
2658            _ctx: Arc<dyn adk_core::InvocationContext>,
2659        ) -> adk_core::Result<adk_core::EventStream> {
2660            Ok(Box::pin(async_stream::stream! {
2661                if true {
2662                    panic!("boom");
2663                }
2664                yield Ok(adk_core::Event::new("never"));
2665            }))
2666        }
2667    }
2668
2669    #[tokio::test]
2670    async fn a_panicking_agent_fails_its_task() {
2671        let (handler, _) = handler_with_agent(Arc::new(PanickingAgent));
2672        let task = handler.message_send(make_test_message()).await.unwrap();
2673        assert_eq!(task.status.state, TaskState::Failed);
2674        let text = status_text(&task.status);
2675        assert!(text.contains("agent run panicked: boom"), "{text}");
2676    }
2677
2678    #[tokio::test]
2679    async fn the_waiting_message_moves_into_history_when_the_task_goes_on() {
2680        let (handler, _) = handler_with_agent(Arc::new(ApprovalAgent));
2681        let waiting = handler.message_send(make_test_message()).await.unwrap();
2682        assert_eq!(waiting.status.state, TaskState::InputRequired);
2683
2684        let done = handler.message_send(approval_for(&waiting.id, None)).await.unwrap();
2685        let roles: Vec<MessageRole> =
2686            done.history.unwrap_or_default().iter().map(|message| message.role).collect();
2687        assert_eq!(
2688            roles,
2689            vec![MessageRole::User, MessageRole::Agent, MessageRole::User],
2690            "the question, the agent's waiting message, the answer"
2691        );
2692    }
2693
2694    #[tokio::test]
2695    async fn push_configs_are_validated_and_replaced_by_id() {
2696        let handler = make_handler();
2697        let task = handler.message_send(make_test_message()).await.unwrap();
2698        let config = |value: serde_json::Value| -> TaskPushNotificationConfig {
2699            serde_json::from_value(value).unwrap()
2700        };
2701
2702        for url in ["not a url", "ftp://hooks.example.com/a2a", "/relative"] {
2703            let err = handler
2704                .push_config_create(&task.id.0, config(serde_json::json!({"url": url})))
2705                .await
2706                .unwrap_err();
2707            assert!(matches!(err, A2aError::InvalidParams { .. }), "{url}: {err}");
2708        }
2709        handler
2710            .push_config_create(
2711                &task.id.0,
2712                config(serde_json::json!({"id": "c1", "url": "https://a.example/1"})),
2713            )
2714            .await
2715            .unwrap();
2716        handler
2717            .push_config_create(
2718                &task.id.0,
2719                config(serde_json::json!({"id": "c1", "url": "https://a.example/2"})),
2720            )
2721            .await
2722            .unwrap();
2723        let configs = handler.push_config_list(&task.id.0).await.unwrap();
2724        assert_eq!(configs.len(), 1, "a config with the same ID replaces the old one");
2725        assert_eq!(configs[0].url, "https://a.example/2");
2726    }
2727
2728    // ── Executor hooks ──────────────────────────────────────────────────────
2729
2730    /// Repeats the user's text.
2731    struct EchoAgent;
2732
2733    #[async_trait::async_trait]
2734    impl adk_core::Agent for EchoAgent {
2735        fn name(&self) -> &str {
2736            "echo_agent"
2737        }
2738
2739        fn description(&self) -> &str {
2740            "repeats"
2741        }
2742
2743        fn sub_agents(&self) -> &[Arc<dyn adk_core::Agent>] {
2744            &[]
2745        }
2746
2747        async fn run(
2748            &self,
2749            ctx: Arc<dyn adk_core::InvocationContext>,
2750        ) -> adk_core::Result<adk_core::EventStream> {
2751            let text: String =
2752                ctx.user_content().parts.iter().filter_map(adk_core::Part::text).collect();
2753            let mut event = adk_core::Event::new("echo");
2754            event.llm_response.content =
2755                Some(adk_core::Content::new("model").with_text(format!("echo: {text}")));
2756            Ok(Box::pin(futures::stream::iter(vec![Ok(event)])))
2757        }
2758    }
2759
2760    #[tokio::test]
2761    async fn executor_hooks_shape_a_run_as_adk_go_callbacks_do() {
2762        use super::super::hooks::ExecutorHooks;
2763        let cleaned = Arc::new(Mutex::new(Vec::new()));
2764        let cleanup_log = cleaned.clone();
2765        let hooks = ExecutorHooks::default()
2766            .before_execute(Arc::new(|run| {
2767                Box::pin(async move {
2768                    let text: String =
2769                        run.message.parts.iter().filter_map(|p| p.text_content()).collect();
2770                    if text.contains("forbidden") {
2771                        Err(A2aError::InvalidParams { message: "not allowed".to_string() })
2772                    } else {
2773                        Ok(())
2774                    }
2775                })
2776            }))
2777            .from_wire_part(Arc::new(|part| {
2778                Ok(part
2779                    .text_content()
2780                    .map(|text| adk_core::Part::Text { text: text.to_uppercase() }))
2781            }))
2782            .after_event(Arc::new(|run, _event, update| {
2783                update
2784                    .metadata
2785                    .get_or_insert_with(Default::default)
2786                    .insert("tenant".into(), run.user_id.clone().into());
2787                Ok(())
2788            }))
2789            .after_execute(Arc::new(|_run, status| {
2790                status.metadata.insert("audited".into(), true.into());
2791                Ok(())
2792            }))
2793            .on_cleanup(Arc::new(move |run, event| {
2794                cleanup_log.lock().unwrap().push((run.task_id.clone(), event.status.state));
2795            }));
2796        let (handler, _) = handler_with_agent(Arc::new(EchoAgent));
2797        let handler = handler.with_hooks(hooks);
2798
2799        let mut msg = make_test_message();
2800        msg.parts = vec![Part::text("hello")];
2801        let mut stream = handler.message_stream(msg).await.unwrap();
2802        let mut updates = Vec::new();
2803        while let Some(update) = stream.next().await {
2804            updates.push(update.unwrap());
2805        }
2806        let artifact = updates
2807            .iter()
2808            .find_map(|u| match u {
2809                StreamResponse::ArtifactUpdate(e) => Some(e),
2810                _ => None,
2811            })
2812            .expect("an artifact update");
2813        assert_eq!(
2814            artifact.artifact.parts[0].text_content(),
2815            Some("echo: HELLO"),
2816            "inbound converter"
2817        );
2818        assert_eq!(
2819            artifact.metadata.as_ref().unwrap()["tenant"],
2820            "A2A_USER_".to_string() + artifact.context_id.0.as_str()
2821        );
2822        let StreamResponse::StatusUpdate(last) = updates.last().unwrap() else {
2823            panic!("ends on a status")
2824        };
2825        assert_eq!(last.status.state, TaskState::Completed);
2826        assert_eq!(last.metadata.as_ref().unwrap()["audited"], true);
2827        assert_eq!(cleaned.lock().unwrap().len(), 1);
2828
2829        // A refused run fails its task, and the agent does not run.
2830        let mut msg = make_test_message();
2831        msg.id = MessageId::new("msg-forbidden");
2832        msg.parts = vec![Part::text("forbidden")];
2833        let task = handler.message_send(msg).await.unwrap();
2834        assert_eq!(task.status.state, TaskState::Failed);
2835        assert!(
2836            status_text(&task.status).starts_with("before execute: "),
2837            "{}",
2838            status_text(&task.status)
2839        );
2840        assert!(task.artifacts.unwrap_or_default().is_empty());
2841    }
2842
2843    #[tokio::test]
2844    async fn an_outbound_part_converter_replaces_the_default_conversion() {
2845        use super::super::hooks::ExecutorHooks;
2846        let hooks = ExecutorHooks::default().to_wire_part(Arc::new(|_event, part| {
2847            Ok(part.text().map(|text| Part::text(format!("[{text}]"))))
2848        }));
2849        let (handler, _) = handler_with_agent(Arc::new(EchoAgent));
2850        let task = handler.with_hooks(hooks).message_send(make_test_message()).await.unwrap();
2851        let texts = artifact_texts(&task);
2852        assert_eq!(texts.len(), 1);
2853        assert!(texts[0].starts_with("[echo: "), "{texts:?}");
2854    }
2855
2856    #[tokio::test]
2857    async fn a_required_extension_must_be_asked_for_and_reaches_the_run() {
2858        use super::super::extensions::RequestedExtensions;
2859        use super::super::hooks::ExecutorHooks;
2860        let required = "https://example.com/ext/billing";
2861        let (handler, _) = handler_with_agent(Arc::new(EchoAgent));
2862        {
2863            let mut card = handler.agent_card.write().await;
2864            let mut updated = card.card.clone();
2865            updated.capabilities.extensions =
2866                Some(vec![a2a_protocol_types::extensions::AgentExtension {
2867                    uri: required.to_string(),
2868                    description: None,
2869                    required: Some(true),
2870                    params: None,
2871                }]);
2872            card.update(updated);
2873        }
2874        let seen = Arc::new(Mutex::new(Vec::new()));
2875        let record = seen.clone();
2876        let handler =
2877            handler.with_hooks(ExecutorHooks::default().on_cleanup(Arc::new(move |run, _| {
2878                record.lock().unwrap().extend(run.extensions.clone());
2879            })));
2880
2881        let err = handler.require_extensions(&RequestedExtensions::default()).await.unwrap_err();
2882        assert!(
2883            matches!(err, A2aError::ExtensionSupportRequired { ref uri } if uri == required),
2884            "{err}"
2885        );
2886        let asked = RequestedExtensions(vec![required.to_string()]);
2887        handler.require_extensions(&asked).await.unwrap();
2888        handler
2889            .for_caller(None)
2890            .with_extensions(asked)
2891            .message_send(make_test_message())
2892            .await
2893            .unwrap();
2894        assert_eq!(*seen.lock().unwrap(), vec![required.to_string()]);
2895    }
2896
2897    #[tokio::test]
2898    async fn an_agent_that_goes_quiet_fails_its_task() {
2899        let (handler, _, _) = slow_handler(2_000);
2900        let handler = handler.with_inactivity_timeout(std::time::Duration::from_millis(100));
2901        let task = handler.message_send(make_test_message()).await.unwrap();
2902        assert_eq!(task.status.state, TaskState::Failed);
2903        assert!(
2904            status_text(&task.status).contains("agent inactivity timeout"),
2905            "{}",
2906            status_text(&task.status)
2907        );
2908    }
2909
2910    #[tokio::test]
2911    async fn runs_over_the_concurrency_limit_are_refused() {
2912        let (handler, store, _) = slow_handler(300);
2913        let handler = handler.with_concurrency_limits(super::super::run::ConcurrencyLimits {
2914            max_runs: 1,
2915            max_runs_for: None,
2916        });
2917        let first = handler
2918            .message_send_with(make_test_message(), Some(&return_immediately()))
2919            .await
2920            .unwrap();
2921        let mut second = make_test_message();
2922        second.id = MessageId::new("msg-second");
2923        let refused = handler.message_send(second).await.unwrap_err();
2924        assert!(refused.to_string().contains("max concurrency limit reached"), "{refused}");
2925
2926        for _ in 0..100 {
2927            if is_terminal_state(store.get_task(&first.id.0).await.unwrap().status.state) {
2928                break;
2929            }
2930            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
2931        }
2932        // The first run's place is given back when it ends.
2933        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
2934        let mut third = make_test_message();
2935        third.id = MessageId::new("msg-third");
2936        assert_eq!(handler.message_send(third).await.unwrap().status.state, TaskState::Completed);
2937    }
2938
2939    /// Uppercases sent text, tags results, refuses cancels, answers lookups of `canned`,
2940    /// and counts stream events, as a2a-go call interceptors can.
2941    struct TestInterceptor {
2942        stream_events: Arc<std::sync::atomic::AtomicUsize>,
2943    }
2944
2945    #[async_trait::async_trait]
2946    impl super::super::interceptor::CallInterceptor for TestInterceptor {
2947        async fn before(
2948            &self,
2949            call: &super::super::interceptor::CallContext,
2950            params: &mut serde_json::Value,
2951        ) -> Result<Option<serde_json::Value>, A2aError> {
2952            match call.method {
2953                "SendMessage" | "SendStreamingMessage" => {
2954                    for part in params["message"]["parts"].as_array_mut().into_iter().flatten() {
2955                        if let Some(text) = part["text"].as_str() {
2956                            part["text"] = text.to_uppercase().into();
2957                        }
2958                    }
2959                    Ok(None)
2960                }
2961                "CancelTask" => {
2962                    Err(A2aError::UnsupportedOperation { method: "cancel is off".to_string() })
2963                }
2964                "GetTask" if params["id"] == "canned" => Ok(Some(serde_json::json!({
2965                    "id": "canned",
2966                    "contextId": "ctx",
2967                    "status": {"state": "TASK_STATE_COMPLETED"},
2968                }))),
2969                _ => Ok(None),
2970            }
2971        }
2972
2973        async fn after(
2974            &self,
2975            call: &super::super::interceptor::CallContext,
2976            result: &mut serde_json::Value,
2977        ) -> Result<(), A2aError> {
2978            if call.method == "SendStreamingMessage" {
2979                self.stream_events.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2980            }
2981            if call.method == "SendMessage" {
2982                result["metadata"]["intercepted"] = true.into();
2983            }
2984            Ok(())
2985        }
2986    }
2987
2988    #[tokio::test]
2989    async fn call_interceptors_run_around_every_operation() {
2990        let stream_events = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2991        let (handler, _) = handler_with_agent(Arc::new(EchoAgent));
2992        let handler = handler
2993            .with_interceptor(Arc::new(TestInterceptor { stream_events: stream_events.clone() }));
2994
2995        let mut msg = make_test_message();
2996        msg.parts = vec![Part::text("quiet")];
2997        let task = handler.message_send(msg).await.unwrap();
2998        assert_eq!(artifact_texts(&task), vec!["echo: QUIET".to_string()], "params rewritten");
2999        assert_eq!(task.metadata.unwrap()["intercepted"], true, "result rewritten");
3000
3001        assert!(matches!(
3002            handler.tasks_cancel(&task.id.0).await,
3003            Err(A2aError::UnsupportedOperation { .. })
3004        ));
3005        assert_eq!(
3006            handler.tasks_get("canned", None).await.unwrap().id.0,
3007            "canned",
3008            "answered early"
3009        );
3010
3011        let mut msg = make_test_message();
3012        msg.id = MessageId::new("msg-stream");
3013        let events = handler.message_stream(msg).await.unwrap().collect::<Vec<_>>().await;
3014        assert_eq!(
3015            stream_events.load(std::sync::atomic::Ordering::SeqCst),
3016            events.len(),
3017            "after sees each event"
3018        );
3019    }
3020
3021    fn make_handler() -> RequestHandler {
3022        let store = Arc::new(InMemoryTaskStore::new());
3023        let executor = Arc::new(V1Executor::new(store.clone()));
3024        let push_sender = Arc::new(NoOpPushNotificationSender);
3025        let card = make_test_agent_card();
3026        let cached = Arc::new(RwLock::new(CachedAgentCard::new(card)));
3027        RequestHandler::new(executor, store, push_sender, cached)
3028    }
3029
3030    fn make_test_agent_card() -> AgentCard {
3031        AgentCard {
3032            name: "test-agent".to_string(),
3033            url: Some("http://localhost:8080".to_string()),
3034            description: "A test agent".to_string(),
3035            version: "1.0.0".to_string(),
3036            supported_interfaces: vec![AgentInterface {
3037                url: "http://localhost:8080/a2a".to_string(),
3038                protocol_binding: "JSONRPC".to_string(),
3039                protocol_version: "1.0".to_string(),
3040                tenant: None,
3041            }],
3042            default_input_modes: vec!["text/plain".to_string()],
3043            default_output_modes: vec!["text/plain".to_string()],
3044            skills: vec![AgentSkill {
3045                id: "echo".to_string(),
3046                name: "Echo".to_string(),
3047                description: "Echoes input".to_string(),
3048                tags: vec![],
3049                examples: None,
3050                input_modes: None,
3051                output_modes: None,
3052                security_requirements: None,
3053            }],
3054            capabilities: AgentCapabilities::none(),
3055            provider: None,
3056            icon_url: None,
3057            documentation_url: None,
3058            security_schemes: None,
3059            security_requirements: None,
3060            signatures: None,
3061        }
3062    }
3063
3064    fn make_test_message() -> Message {
3065        Message {
3066            id: MessageId::new("msg-1"),
3067            role: MessageRole::User,
3068            parts: vec![Part::text("hello")],
3069            task_id: None,
3070            context_id: None,
3071            reference_task_ids: None,
3072            extensions: None,
3073            metadata: None,
3074        }
3075    }
3076
3077    /// Fails the next `get` with a transient error when armed.
3078    struct FlakySessions {
3079        inner: adk_session::InMemorySessionService,
3080        fail_next_get: std::sync::atomic::AtomicBool,
3081    }
3082
3083    #[async_trait::async_trait]
3084    impl adk_session::SessionService for FlakySessions {
3085        async fn create(
3086            &self,
3087            req: adk_session::CreateRequest,
3088        ) -> adk_core::Result<Box<dyn adk_session::Session>> {
3089            self.inner.create(req).await
3090        }
3091
3092        async fn get(
3093            &self,
3094            req: adk_session::GetRequest,
3095        ) -> adk_core::Result<Box<dyn adk_session::Session>> {
3096            if self.fail_next_get.swap(false, std::sync::atomic::Ordering::SeqCst) {
3097                return Err(adk_core::AdkError::unavailable(
3098                    adk_core::ErrorComponent::Session,
3099                    "session.backend.timeout",
3100                    "the session backend timed out",
3101                ));
3102            }
3103            self.inner.get(req).await
3104        }
3105
3106        async fn list(
3107            &self,
3108            req: adk_session::ListRequest,
3109        ) -> adk_core::Result<Vec<Box<dyn adk_session::Session>>> {
3110            self.inner.list(req).await
3111        }
3112
3113        async fn delete(&self, req: adk_session::DeleteRequest) -> adk_core::Result<()> {
3114            self.inner.delete(req).await
3115        }
3116
3117        async fn append_event(
3118            &self,
3119            session_id: &str,
3120            event: adk_core::Event,
3121        ) -> adk_core::Result<()> {
3122            self.inner.append_event(session_id, event).await
3123        }
3124
3125        async fn append_event_for_identity(
3126            &self,
3127            req: adk_session::AppendEventRequest,
3128        ) -> adk_core::Result<()> {
3129            self.inner.append_event_for_identity(req).await
3130        }
3131    }
3132
3133    /// A transient failure reading the context's session fails the message and leaves the
3134    /// stored session as it was, instead of creating it again over its history.
3135    #[tokio::test]
3136    async fn message_send_keeps_the_session_when_its_lookup_fails() {
3137        use adk_session::SessionService;
3138
3139        let sessions = Arc::new(FlakySessions {
3140            inner: adk_session::InMemorySessionService::new(),
3141            fail_next_get: std::sync::atomic::AtomicBool::new(false),
3142        });
3143        let identity = adk_core::AdkIdentity::new(
3144            "a2a-stream-test".try_into().unwrap(),
3145            "a2a-ctx-kept".try_into().unwrap(),
3146            "ctx-kept".try_into().unwrap(),
3147        );
3148        sessions
3149            .create(adk_session::CreateRequest {
3150                app_name: "a2a-stream-test".to_string(),
3151                user_id: "a2a-ctx-kept".to_string(),
3152                session_id: Some("ctx-kept".to_string()),
3153                state: std::collections::HashMap::from([(
3154                    "plan".to_string(),
3155                    serde_json::json!("gold"),
3156                )]),
3157            })
3158            .await
3159            .unwrap();
3160        sessions
3161            .append_event_for_identity(adk_session::AppendEventRequest {
3162                identity: identity.clone(),
3163                event: adk_core::Event::new("earlier"),
3164            })
3165            .await
3166            .unwrap();
3167
3168        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::new());
3169        let handler = RequestHandler::with_runner(
3170            Arc::new(V1Executor::new(store.clone())),
3171            store,
3172            Arc::new(NoOpPushNotificationSender),
3173            Arc::new(RwLock::new(CachedAgentCard::new(make_test_agent_card()))),
3174            Arc::new(
3175                adk_runner::Runner::builder()
3176                    .app_name("a2a-stream-test")
3177                    .agent(Arc::new(ChunkingAgent { chunks: vec!["answer".into()] }))
3178                    .session_service(sessions.clone())
3179                    .build_config(),
3180            ),
3181        );
3182        let mut message = make_test_message();
3183        message.context_id = Some(a2a_protocol_types::ContextId::new("ctx-kept"));
3184
3185        sessions.fail_next_get.store(true, std::sync::atomic::Ordering::SeqCst);
3186        if let Ok(task) = handler.message_send(message).await {
3187            assert_ne!(task.status.state, TaskState::Completed);
3188        }
3189
3190        let stored = sessions.inner.get_for_identity(&identity).await.unwrap();
3191        assert_eq!(
3192            (stored.events().len(), stored.state().get("plan")),
3193            (1, Some(serde_json::json!("gold")))
3194        );
3195    }
3196
3197    // ── message_send ─────────────────────────────────────────────────────
3198
3199    #[tokio::test]
3200    async fn message_send_creates_and_completes_task() {
3201        let handler = make_handler();
3202        let msg = make_test_message();
3203
3204        let task = handler.message_send(msg).await.unwrap();
3205
3206        assert_eq!(task.status.state, TaskState::Completed);
3207        assert!(!task.id.0.is_empty());
3208        assert!(!task.context_id.0.is_empty());
3209        // History should contain the sent message
3210        assert!(task.history.is_some());
3211        assert_eq!(task.history.unwrap().len(), 1);
3212    }
3213
3214    #[tokio::test]
3215    async fn message_send_uses_provided_context_id() {
3216        let handler = make_handler();
3217        let mut msg = make_test_message();
3218        msg.context_id = Some(a2a_protocol_types::ContextId::new("my-ctx"));
3219
3220        let task = handler.message_send(msg).await.unwrap();
3221        assert_eq!(task.context_id.0, "my-ctx");
3222    }
3223
3224    // ── tasks_get ────────────────────────────────────────────────────────
3225
3226    #[tokio::test]
3227    async fn tasks_get_returns_task() {
3228        let handler = make_handler();
3229        let msg = make_test_message();
3230        let task = handler.message_send(msg).await.unwrap();
3231
3232        let retrieved = handler.tasks_get(&task.id.0, None).await.unwrap();
3233        assert_eq!(retrieved.id, task.id);
3234        assert_eq!(retrieved.status.state, TaskState::Completed);
3235    }
3236
3237    #[tokio::test]
3238    async fn tasks_get_truncates_history() {
3239        let handler = make_handler();
3240
3241        // Create a task and add multiple history messages
3242        let msg = make_test_message();
3243        let task = handler.message_send(msg).await.unwrap();
3244
3245        // Add more history
3246        let msg2 = Message {
3247            id: MessageId::new("msg-2"),
3248            role: MessageRole::Agent,
3249            parts: vec![Part::text("response")],
3250            task_id: None,
3251            context_id: None,
3252            reference_task_ids: None,
3253            extensions: None,
3254            metadata: None,
3255        };
3256        handler.task_store.add_history_message(&task.id.0, msg2).await.unwrap();
3257
3258        // Get with history_len=1 should only return the last message
3259        let retrieved = handler.tasks_get(&task.id.0, Some(1)).await.unwrap();
3260        assert_eq!(retrieved.history.unwrap().len(), 1);
3261    }
3262
3263    #[tokio::test]
3264    async fn tasks_get_not_found() {
3265        let handler = make_handler();
3266        let err = handler.tasks_get("nonexistent", None).await.unwrap_err();
3267        assert!(err.to_string().contains("nonexistent"));
3268    }
3269
3270    // ── tasks_cancel ─────────────────────────────────────────────────────
3271
3272    #[tokio::test]
3273    async fn tasks_cancel_cancels_working_task() {
3274        let handler = make_handler();
3275
3276        // Create a task in WORKING state
3277        let task_id = "cancel-test";
3278        let ctx_id = "ctx-cancel";
3279        handler.executor.create_task(task_id, ctx_id).await.unwrap();
3280        handler.executor.transition_state(task_id, ctx_id, TaskState::Working, None).await.unwrap();
3281
3282        let task = handler.tasks_cancel(task_id).await.unwrap();
3283        assert_eq!(task.status.state, TaskState::Canceled);
3284    }
3285
3286    #[tokio::test]
3287    async fn tasks_cancel_rejects_terminal_task() {
3288        let handler = make_handler();
3289        let msg = make_test_message();
3290        let task = handler.message_send(msg).await.unwrap();
3291
3292        // Task is COMPLETED (terminal) — cancel should fail
3293        let err = handler.tasks_cancel(&task.id.0).await.unwrap_err();
3294        assert!(matches!(err, A2aError::TaskNotCancelable { .. }));
3295    }
3296
3297    #[tokio::test]
3298    async fn tasks_cancel_not_found() {
3299        let handler = make_handler();
3300        let err = handler.tasks_cancel("nonexistent").await.unwrap_err();
3301        assert!(err.to_string().contains("nonexistent"));
3302    }
3303
3304    // ── tasks_list ───────────────────────────────────────────────────────
3305
3306    #[tokio::test]
3307    async fn tasks_list_returns_all_tasks() {
3308        let handler = make_handler();
3309
3310        handler.message_send(make_test_message()).await.unwrap();
3311        let mut msg2 = make_test_message();
3312        msg2.id = MessageId::new("msg-list-2");
3313        handler.message_send(msg2).await.unwrap();
3314
3315        let tasks = handler.tasks_list(ListTasksParams::default()).await.unwrap();
3316        assert_eq!(tasks.tasks.len(), 2);
3317    }
3318
3319    #[tokio::test]
3320    async fn tasks_list_filters_by_context_id() {
3321        let handler = make_handler();
3322
3323        let mut msg1 = make_test_message();
3324        msg1.context_id = Some(a2a_protocol_types::ContextId::new("ctx-a"));
3325        handler.message_send(msg1).await.unwrap();
3326
3327        let mut msg2 = make_test_message();
3328        msg2.id = MessageId::new("msg-ctx-b");
3329        msg2.context_id = Some(a2a_protocol_types::ContextId::new("ctx-b"));
3330        handler.message_send(msg2).await.unwrap();
3331
3332        let tasks = handler
3333            .tasks_list(ListTasksParams {
3334                context_id: Some("ctx-a".to_string()),
3335                ..Default::default()
3336            })
3337            .await
3338            .unwrap();
3339        assert_eq!(tasks.tasks.len(), 1);
3340        assert_eq!(tasks.tasks[0].context_id.0, "ctx-a");
3341    }
3342
3343    #[tokio::test]
3344    async fn tasks_list_with_page_size() {
3345        let handler = make_handler();
3346
3347        handler.message_send(make_test_message()).await.unwrap();
3348        let mut msg2 = make_test_message();
3349        msg2.id = MessageId::new("msg-page-2");
3350        handler.message_send(msg2).await.unwrap();
3351        let mut msg3 = make_test_message();
3352        msg3.id = MessageId::new("msg-page-3");
3353        handler.message_send(msg3).await.unwrap();
3354
3355        let tasks = handler
3356            .tasks_list(ListTasksParams { page_size: Some(2), ..Default::default() })
3357            .await
3358            .unwrap();
3359        assert_eq!(tasks.tasks.len(), 2);
3360    }
3361
3362    #[tokio::test]
3363    async fn tasks_list_empty() {
3364        let handler = make_handler();
3365        let tasks = handler.tasks_list(ListTasksParams::default()).await.unwrap();
3366        assert!(tasks.tasks.is_empty());
3367    }
3368
3369    // ── push_config_create / get / list / delete ─────────────────────────
3370
3371    #[tokio::test]
3372    async fn push_config_lifecycle() {
3373        let handler = make_handler();
3374
3375        // Create a task first
3376        let msg = make_test_message();
3377        let task = handler.message_send(msg).await.unwrap();
3378        let task_id = &task.id.0;
3379
3380        // Create push config
3381        let config = TaskPushNotificationConfig::new(task_id, "https://example.com/webhook");
3382        let created = handler.push_config_create(task_id, config).await.unwrap();
3383        assert!(created.id.is_some());
3384        assert_eq!(created.url, "https://example.com/webhook");
3385        let config_id = created.id.clone().unwrap();
3386
3387        // Get push config
3388        let retrieved = handler.push_config_get(task_id, &config_id).await.unwrap();
3389        assert_eq!(retrieved.url, "https://example.com/webhook");
3390
3391        // List push configs
3392        let configs = handler.push_config_list(task_id).await.unwrap();
3393        assert_eq!(configs.len(), 1);
3394
3395        // Delete push config
3396        handler.push_config_delete(task_id, &config_id).await.unwrap();
3397
3398        // Verify deleted
3399        let configs = handler.push_config_list(task_id).await.unwrap();
3400        assert!(configs.is_empty());
3401    }
3402
3403    #[tokio::test]
3404    async fn push_config_get_not_found() {
3405        let handler = make_handler();
3406        let msg = make_test_message();
3407        let task = handler.message_send(msg).await.unwrap();
3408
3409        let err = handler.push_config_get(&task.id.0, "nonexistent").await.unwrap_err();
3410        assert!(err.to_string().contains("nonexistent"));
3411    }
3412
3413    #[tokio::test]
3414    async fn deleting_a_push_config_the_task_lacks_succeeds() {
3415        let handler = make_handler();
3416        let msg = make_test_message();
3417        let task = handler.message_send(msg).await.unwrap();
3418
3419        // As A2A config stores do: a delete leaves the config absent either way.
3420        handler.push_config_delete(&task.id.0, "nonexistent").await.unwrap();
3421        let err = handler.push_config_delete("no-such-task", "nonexistent").await.unwrap_err();
3422        assert!(matches!(err, A2aError::TaskNotFound { .. }), "{err}");
3423    }
3424
3425    #[tokio::test]
3426    async fn push_config_create_task_not_found() {
3427        let handler = make_handler();
3428        let config = TaskPushNotificationConfig::new("nonexistent", "https://example.com/hook");
3429        let err = handler.push_config_create("nonexistent", config).await.unwrap_err();
3430        assert!(err.to_string().contains("nonexistent"));
3431    }
3432
3433    // ── agent_card_extended ──────────────────────────────────────────────
3434
3435    #[tokio::test]
3436    async fn the_extended_card_is_built_for_each_caller() {
3437        // Without a producer there is no extended card to serve.
3438        assert!(matches!(
3439            make_handler().agent_card_extended().await,
3440            Err(A2aError::ExtendedAgentCardNotConfigured)
3441        ));
3442
3443        let producer: ExtendedCardProducer = Arc::new(|caller: Option<RequestContext>| {
3444            Box::pin(async move {
3445                let mut card = make_test_agent_card();
3446                card.description = match caller {
3447                    Some(caller) => format!("for {}", caller.user_id),
3448                    None => "for anyone".to_string(),
3449                };
3450                Ok(card)
3451            })
3452        });
3453        let handler = make_handler().with_extended_card(producer);
3454        assert_eq!(handler.agent_card_extended().await.unwrap().description, "for anyone");
3455        let alice = RequestContext {
3456            user_id: "alice".to_string(),
3457            scopes: Vec::new(),
3458            metadata: HashMap::new(),
3459        };
3460        let card = handler.agent_card_extended_for(Some(alice)).await.unwrap();
3461        assert_eq!(card.description, "for alice");
3462    }
3463
3464    // ── message_stream ───────────────────────────────────────────────────
3465
3466    #[tokio::test]
3467    async fn message_stream_yields_events() {
3468        use a2a_protocol_types::events::StreamResponse;
3469
3470        let handler = make_handler();
3471        let mut msg = make_test_message();
3472        msg.id = MessageId::new("msg-stream-test");
3473
3474        let mut stream = handler.message_stream(msg).await.unwrap();
3475
3476        // First event should be a Task object
3477        let first = stream.next().await.unwrap().unwrap();
3478        assert!(matches!(first, StreamResponse::Task(_)), "first event should be Task");
3479
3480        // Should yield WORKING event
3481        let event1 = stream.next().await.unwrap().unwrap();
3482        assert!(matches!(
3483            event1,
3484            StreamResponse::StatusUpdate(ref e) if e.status.state == TaskState::Working
3485        ));
3486
3487        // Should yield COMPLETED event
3488        let event2 = stream.next().await.unwrap().unwrap();
3489        assert!(matches!(
3490            event2,
3491            StreamResponse::StatusUpdate(ref e) if e.status.state == TaskState::Completed
3492        ));
3493
3494        // Stream should end
3495        assert!(stream.next().await.is_none());
3496    }
3497
3498    // ── input validation ─────────────────────────────────────────────────
3499
3500    #[tokio::test]
3501    async fn message_send_rejects_empty_parts() {
3502        let handler = make_handler();
3503        let mut msg = make_test_message();
3504        msg.parts = vec![];
3505        let err = handler.message_send(msg).await.unwrap_err();
3506        assert!(matches!(err, A2aError::InvalidParams { .. }));
3507        assert!(err.to_string().contains("at least one part"));
3508    }
3509
3510    #[tokio::test]
3511    async fn message_send_rejects_empty_message_id() {
3512        let handler = make_handler();
3513        let mut msg = make_test_message();
3514        msg.id = MessageId::new("");
3515        let err = handler.message_send(msg).await.unwrap_err();
3516        assert!(matches!(err, A2aError::InvalidParams { .. }));
3517        assert!(err.to_string().contains("messageId"));
3518    }
3519
3520    #[tokio::test]
3521    async fn message_send_rejects_whitespace_message_id() {
3522        let handler = make_handler();
3523        let mut msg = make_test_message();
3524        msg.id = MessageId::new("   ");
3525        let err = handler.message_send(msg).await.unwrap_err();
3526        assert!(matches!(err, A2aError::InvalidParams { .. }));
3527    }
3528
3529    #[tokio::test]
3530    async fn message_send_rejects_long_message_id() {
3531        let handler = make_handler();
3532        let mut msg = make_test_message();
3533        msg.id = MessageId::new("x".repeat(257));
3534        let err = handler.message_send(msg).await.unwrap_err();
3535        assert!(matches!(err, A2aError::InvalidParams { .. }));
3536        assert!(err.to_string().contains("256"));
3537    }
3538
3539    #[tokio::test]
3540    async fn tasks_get_rejects_empty_task_id() {
3541        let handler = make_handler();
3542        let err = handler.tasks_get("", None).await.unwrap_err();
3543        assert!(matches!(err, A2aError::InvalidParams { .. }));
3544        assert!(err.to_string().contains("taskId"));
3545    }
3546
3547    #[tokio::test]
3548    async fn tasks_get_rejects_long_task_id() {
3549        let handler = make_handler();
3550        let long_id = "x".repeat(257);
3551        let err = handler.tasks_get(&long_id, None).await.unwrap_err();
3552        assert!(matches!(err, A2aError::InvalidParams { .. }));
3553    }
3554
3555    #[tokio::test]
3556    async fn tasks_cancel_rejects_empty_task_id() {
3557        let handler = make_handler();
3558        let err = handler.tasks_cancel("").await.unwrap_err();
3559        assert!(matches!(err, A2aError::InvalidParams { .. }));
3560    }
3561
3562    #[tokio::test]
3563    async fn message_send_rejects_oversized_metadata() {
3564        let handler = make_handler();
3565        let mut msg = make_test_message();
3566        // Create metadata > 64KB
3567        let big_value = "x".repeat(70_000);
3568        msg.metadata = Some(serde_json::json!({"big": big_value}));
3569        let err = handler.message_send(msg).await.unwrap_err();
3570        assert!(matches!(err, A2aError::InvalidParams { .. }));
3571        assert!(err.to_string().contains("64 KB"));
3572    }
3573
3574    // ── idempotency ──────────────────────────────────────────────────────
3575
3576    #[tokio::test]
3577    async fn message_send_idempotent_same_message_id() {
3578        let handler = make_handler();
3579        let msg1 = make_test_message();
3580        let msg2 = make_test_message(); // same messageId "msg-1"
3581
3582        let task1 = handler.message_send(msg1).await.unwrap();
3583        let task2 = handler.message_send(msg2).await.unwrap();
3584
3585        assert_eq!(task1.id, task2.id, "same messageId should return same task");
3586    }
3587
3588    #[tokio::test]
3589    async fn message_send_different_message_id_creates_new_task() {
3590        let handler = make_handler();
3591        let msg1 = make_test_message();
3592        let mut msg2 = make_test_message();
3593        msg2.id = MessageId::new("msg-2");
3594
3595        let task1 = handler.message_send(msg1).await.unwrap();
3596        let task2 = handler.message_send(msg2).await.unwrap();
3597
3598        assert_ne!(task1.id, task2.id, "different messageId should create different tasks");
3599    }
3600
3601    #[tokio::test]
3602    async fn message_stream_idempotent_returns_existing() {
3603        use a2a_protocol_types::events::StreamResponse;
3604
3605        let handler = make_handler();
3606        let msg1 = make_test_message();
3607
3608        // First call creates the task via message_send
3609        let task = handler.message_send(msg1).await.unwrap();
3610
3611        // Second call via message_stream with same messageId should return existing
3612        let msg2 = make_test_message(); // same messageId "msg-1"
3613        let mut stream = handler.message_stream(msg2).await.unwrap();
3614        let first = stream.next().await.unwrap().unwrap();
3615        match first {
3616            StreamResponse::Task(t) => assert_eq!(t.id.0, task.id.0),
3617            other => panic!("expected Task variant, got {other:?}"),
3618        }
3619    }
3620
3621    // ── multi-turn resume ────────────────────────────────────────────────
3622
3623    #[tokio::test]
3624    async fn a_context_message_continues_the_waiting_task_only_when_it_answers_its_call() {
3625        let handler = make_handler();
3626        let task_id = "resume-test";
3627        let ctx_id = "ctx-resume";
3628        handler.executor.create_task(task_id, ctx_id).await.unwrap();
3629        handler.executor.transition_state(task_id, ctx_id, TaskState::Working, None).await.unwrap();
3630        let call = super::super::convert::tagged_function_call_part(
3631            "approve",
3632            &serde_json::json!({}),
3633            Some("c1"),
3634            true,
3635        );
3636        handler
3637            .executor
3638            .transition_state_with_parts(task_id, ctx_id, TaskState::InputRequired, vec![call])
3639            .await
3640            .unwrap();
3641
3642        // A plain follow-up in the context starts a new task there, as adk-go does.
3643        let mut follow_up = make_test_message();
3644        follow_up.id = MessageId::new("msg-follow-up");
3645        follow_up.context_id = Some(a2a_protocol_types::ContextId::new(ctx_id));
3646        let new_task = handler.message_send(follow_up).await.unwrap();
3647        assert_ne!(new_task.id.0, task_id);
3648        assert_eq!(new_task.context_id.0, ctx_id);
3649        let waiting = handler.tasks_get(task_id, None).await.unwrap();
3650        assert_eq!(waiting.status.state, TaskState::InputRequired);
3651
3652        // An answer to the pending call continues the waiting task.
3653        let mut answer = make_test_message();
3654        answer.id = MessageId::new("msg-answer");
3655        answer.context_id = Some(a2a_protocol_types::ContextId::new(ctx_id));
3656        answer.parts = vec![super::super::convert::tagged_function_response_part(
3657            "approve",
3658            &serde_json::json!({"approved": true}),
3659            Some("c1"),
3660        )];
3661        let resumed = handler.message_send(answer).await.unwrap();
3662        assert_eq!(resumed.id.0, task_id);
3663        assert_eq!(resumed.status.state, TaskState::Completed);
3664    }
3665
3666    #[tokio::test]
3667    async fn an_answer_that_misses_a_pending_call_is_asked_again_without_running() {
3668        let handler = make_handler();
3669        let (task_id, ctx_id) = ("ask-again", "ctx-ask-again");
3670        handler.executor.create_task(task_id, ctx_id).await.unwrap();
3671        handler.executor.transition_state(task_id, ctx_id, TaskState::Working, None).await.unwrap();
3672        let calls = vec![
3673            super::super::convert::tagged_function_call_part(
3674                "approve",
3675                &serde_json::json!({}),
3676                Some("c1"),
3677                true,
3678            ),
3679            super::super::convert::tagged_function_call_part(
3680                "approve",
3681                &serde_json::json!({}),
3682                Some("c2"),
3683                true,
3684            ),
3685        ];
3686        handler
3687            .executor
3688            .transition_state_with_parts(task_id, ctx_id, TaskState::InputRequired, calls)
3689            .await
3690            .unwrap();
3691
3692        let mut partial_answer = make_test_message();
3693        partial_answer.id = MessageId::new("msg-partial-answer");
3694        partial_answer.task_id = Some(TaskId::new(task_id));
3695        partial_answer.parts = vec![super::super::convert::tagged_function_response_part(
3696            "approve",
3697            &serde_json::json!({"approved": true}),
3698            Some("c1"),
3699        )];
3700        let task = handler.message_send(partial_answer).await.unwrap();
3701
3702        assert_eq!(task.status.state, TaskState::InputRequired);
3703        let parts = task.status.message.expect("the task asks again").parts;
3704        assert_eq!(parts.len(), 3, "both pending calls, then the notice");
3705        assert_eq!(parts[2].text_content(), Some(r#"no input provided for function call ID "c2""#));
3706        assert_eq!(parts[2].metadata.as_ref().unwrap()["validation_error"], true);
3707        let history = task.history.expect("history");
3708        assert_eq!(history.last().unwrap().id.0, "msg-partial-answer");
3709    }
3710
3711    #[tokio::test]
3712    async fn message_send_creates_new_task_for_terminal_context() {
3713        let handler = make_handler();
3714
3715        // Create a completed task
3716        let mut msg1 = make_test_message();
3717        msg1.id = MessageId::new("msg-terminal-1");
3718        msg1.context_id = Some(a2a_protocol_types::ContextId::new("ctx-terminal"));
3719        let task1 = handler.message_send(msg1).await.unwrap();
3720        assert_eq!(task1.status.state, TaskState::Completed);
3721
3722        // Send another message with the same contextId — should create a new task
3723        let mut msg2 = make_test_message();
3724        msg2.id = MessageId::new("msg-terminal-2");
3725        msg2.context_id = Some(a2a_protocol_types::ContextId::new("ctx-terminal"));
3726        let task2 = handler.message_send(msg2).await.unwrap();
3727
3728        assert_ne!(task1.id, task2.id, "terminal context should create new task");
3729    }
3730
3731    #[tokio::test]
3732    async fn message_send_creates_new_task_without_context_id() {
3733        let handler = make_handler();
3734        let mut msg = make_test_message();
3735        msg.id = MessageId::new("msg-no-ctx");
3736        msg.context_id = None;
3737
3738        let task = handler.message_send(msg).await.unwrap();
3739        assert_eq!(task.status.state, TaskState::Completed);
3740    }
3741
3742    // ── Caller scoping ─────────────────────────────────────────────────────
3743    //
3744    // The session user was `a2a-{contextId}` and every operation looked tasks up by ID
3745    // alone, so an authenticated caller could reach another caller's session through its
3746    // contextId and read, cancel, or reconfigure its tasks through their IDs.
3747
3748    fn caller(user_id: &str) -> Option<RequestContext> {
3749        Some(RequestContext {
3750            user_id: user_id.to_string(),
3751            scopes: vec![],
3752            metadata: Default::default(),
3753        })
3754    }
3755
3756    fn message_in(message_id: &str, context_id: &str) -> Message {
3757        let mut msg = make_test_message();
3758        msg.id = MessageId::new(message_id);
3759        msg.context_id = Some(a2a_protocol_types::ContextId::new(context_id));
3760        msg
3761    }
3762
3763    fn is_not_found<T>(result: Result<T, A2aError>) -> bool {
3764        matches!(result, Err(A2aError::TaskNotFound { .. }))
3765    }
3766
3767    #[tokio::test]
3768    async fn another_callers_task_is_reported_as_missing() {
3769        let handler = make_handler();
3770        handler.executor.create_task_for("bob-task", "bob-ctx", Some("bob")).await.unwrap();
3771        handler
3772            .executor
3773            .transition_state("bob-task", "bob-ctx", TaskState::Working, None)
3774            .await
3775            .unwrap();
3776        let hook = TaskPushNotificationConfig::new("bob-task", "https://example.com/hook");
3777
3778        for scope in [handler.for_caller(caller("alice")), handler.for_caller(None)] {
3779            assert!(is_not_found(scope.tasks_get("bob-task", None).await));
3780            assert!(is_not_found(scope.tasks_cancel("bob-task").await));
3781            assert!(is_not_found(scope.tasks_subscribe("bob-task").await));
3782            assert!(is_not_found(scope.push_config_create("bob-task", hook.clone()).await));
3783            assert!(is_not_found(scope.push_config_list("bob-task").await));
3784            assert!(scope.tasks_list(ListTasksParams::default()).await.unwrap().tasks.is_empty());
3785        }
3786
3787        let bob = handler.for_caller(caller("bob"));
3788        assert_eq!(bob.tasks_get("bob-task", None).await.unwrap().status.state, TaskState::Working);
3789        assert_eq!(bob.tasks_list(ListTasksParams::default()).await.unwrap().tasks.len(), 1);
3790        assert_eq!(bob.tasks_cancel("bob-task").await.unwrap().status.state, TaskState::Canceled);
3791    }
3792
3793    #[tokio::test]
3794    async fn a_reused_message_id_does_not_return_another_callers_task() {
3795        let handler = make_handler();
3796        let bobs = handler
3797            .for_caller(caller("bob"))
3798            .message_send(message_in("shared-msg", "bob-ctx"))
3799            .await
3800            .unwrap();
3801
3802        let alices = handler
3803            .for_caller(caller("alice"))
3804            .message_send(message_in("shared-msg", "alice-ctx"))
3805            .await
3806            .unwrap();
3807        assert_ne!(alices.id, bobs.id);
3808        assert_eq!(alices.context_id.0, "alice-ctx");
3809
3810        let bob_retry = handler
3811            .for_caller(caller("bob"))
3812            .message_send(message_in("shared-msg", "bob-ctx"))
3813            .await
3814            .unwrap();
3815        assert_eq!(bob_retry.id, bobs.id, "bob's own retry still deduplicates");
3816    }
3817
3818    #[tokio::test]
3819    async fn another_callers_input_required_task_is_not_resumed() {
3820        let handler = make_handler();
3821        handler.executor.create_task_for("bob-task", "shared-ctx", Some("bob")).await.unwrap();
3822        for state in [TaskState::Working, TaskState::InputRequired] {
3823            handler.executor.transition_state("bob-task", "shared-ctx", state, None).await.unwrap();
3824        }
3825
3826        let alices = handler
3827            .for_caller(caller("alice"))
3828            .message_send(message_in("alice-msg", "shared-ctx"))
3829            .await
3830            .unwrap();
3831        assert_ne!(alices.id.0, "bob-task");
3832
3833        let bobs = handler.for_caller(caller("bob")).tasks_get("bob-task", None).await.unwrap();
3834        assert_eq!(bobs.status.state, TaskState::InputRequired);
3835        assert_eq!(bobs.history, None, "alice's message must not join bob's task");
3836    }
3837
3838    #[tokio::test]
3839    async fn the_session_belongs_to_the_authenticated_caller() {
3840        let sessions = Arc::new(adk_session::InMemorySessionService::new());
3841        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::new());
3842        let runner_config = Arc::new(
3843            adk_runner::Runner::builder()
3844                .app_name("a2a-identity")
3845                .agent(Arc::new(ChunkingAgent { chunks: vec!["ok".into()] }))
3846                .session_service(sessions.clone())
3847                .build_config(),
3848        );
3849        let handler = RequestHandler::with_runner(
3850            Arc::new(V1Executor::new(store.clone())),
3851            store,
3852            Arc::new(NoOpPushNotificationSender),
3853            Arc::new(RwLock::new(CachedAgentCard::new(make_test_agent_card()))),
3854            runner_config,
3855        );
3856
3857        handler.for_caller(caller("alice")).message_send(message_in("m1", "ctx-1")).await.unwrap();
3858
3859        use adk_session::SessionService;
3860        let session_for = |user_id: &str| {
3861            sessions.get(adk_session::GetRequest {
3862                app_name: "a2a-identity".to_string(),
3863                user_id: user_id.to_string(),
3864                session_id: "ctx-1".to_string(),
3865                num_recent_events: None,
3866                after: None,
3867            })
3868        };
3869        assert!(session_for("alice").await.is_ok());
3870        assert!(
3871            session_for("a2a-ctx-1").await.is_err(),
3872            "the client-chosen context ID must not name the session user"
3873        );
3874    }
3875
3876    #[tokio::test]
3877    async fn the_owner_is_not_sent_on_the_wire() {
3878        let handler = make_handler();
3879        let alice = handler.for_caller(caller("alice"));
3880
3881        let task = alice.message_send(message_in("m-send", "ctx")).await.unwrap();
3882        assert_eq!(task.metadata, None);
3883        let entry = handler.task_store.get_task(&task.id.0).await.unwrap();
3884        assert_eq!(entry.owner(), Some("alice"));
3885
3886        let events: Vec<_> =
3887            alice.message_stream(message_in("m-stream", "ctx")).await.unwrap().collect().await;
3888        for event in events {
3889            match event.unwrap() {
3890                StreamResponse::Task(task) => assert_eq!(task.metadata, None),
3891                StreamResponse::StatusUpdate(update) => assert_eq!(update.metadata, None),
3892                StreamResponse::ArtifactUpdate(update) => assert_eq!(update.metadata, None),
3893                StreamResponse::Message(message) => assert_eq!(message.metadata, None),
3894                // `StreamResponse` is `#[non_exhaustive]`; nothing else carries task metadata.
3895                _ => {}
3896            }
3897        }
3898    }
3899}