Skip to main content

adk_server/rest/controllers/
a2a.rs

1use crate::ServerConfig;
2use crate::a2a::{
3    AgentCard, Executor, ExecutorConfig, JsonRpcError, JsonRpcRequest, JsonRpcResponse, Message,
4    MessageSendParams, Task, TaskState, TaskStatus, TaskStatusUpdateEvent, TasksCancelParams,
5    TasksGetParams, UpdateEvent, build_agent_card, jsonrpc,
6};
7use crate::auth_bridge::{AuthenticatedCaller, RequestContext};
8use adk_runner::{Runner, RunnerConfig};
9use axum::{
10    extract::State,
11    http::StatusCode,
12    response::{
13        IntoResponse, Json,
14        sse::{Event, Sse},
15    },
16};
17use futures::stream::Stream;
18use serde_json::Value;
19use std::{
20    collections::HashMap,
21    convert::Infallible,
22    sync::Arc,
23    time::{Duration, Instant},
24};
25use tokio::sync::{Mutex, Notify, RwLock, mpsc, oneshot};
26use tokio_util::sync::CancellationToken;
27
28/// How many finished A2A task records a [`TaskStore`] keeps, and for how long.
29///
30/// A record is kept so `tasks/get` can report the outcome after `message/send`
31/// returns. Every record in the store belongs to an execution that has ended —
32/// running tasks are tracked separately and are never evicted.
33///
34/// The default keeps the newest 1,000 records for at most one hour.
35///
36/// # Example
37///
38/// ```rust
39/// use adk_server::A2aTaskRetention;
40/// use std::time::Duration;
41///
42/// let retention =
43///     A2aTaskRetention::default().with_max_finished(500).with_ttl(Duration::from_secs(600));
44/// assert_eq!(retention.max_finished, Some(500));
45/// assert_eq!(retention.ttl, Some(Duration::from_secs(600)));
46/// ```
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct A2aTaskRetention {
49    /// How many finished task records to keep, newest first. `None` keeps every record.
50    pub max_finished: Option<usize>,
51    /// How long a finished task record stays readable. `None` disables expiry.
52    pub ttl: Option<Duration>,
53}
54
55impl Default for A2aTaskRetention {
56    fn default() -> Self {
57        Self { max_finished: Some(1000), ttl: Some(Duration::from_secs(3600)) }
58    }
59}
60
61impl A2aTaskRetention {
62    /// Keeps every finished task record forever. The store then grows without bound.
63    pub fn unlimited() -> Self {
64        Self { max_finished: None, ttl: None }
65    }
66
67    /// Keeps at most `count` finished task records, evicting the oldest first.
68    pub fn with_max_finished(mut self, count: usize) -> Self {
69        self.max_finished = Some(count);
70        self
71    }
72
73    /// Expires a finished task record `ttl` after its execution ended.
74    pub fn with_ttl(mut self, ttl: Duration) -> Self {
75        self.ttl = Some(ttl);
76        self
77    }
78}
79
80/// A finished task, the principal that started it, and when it ended.
81struct StoredTask {
82    task: Task,
83    owner: Option<String>,
84    finished_at: Instant,
85}
86
87/// In-memory storage for finished A2A tasks.
88///
89/// Each record carries the authenticated user that started the task, or `None`
90/// when no authentication was configured. Owner-scoped reads
91/// ([`get_for`](Self::get_for)) only return a record to the same principal.
92/// Records are evicted according to the store's [`A2aTaskRetention`].
93pub struct TaskStore {
94    tasks: RwLock<HashMap<String, StoredTask>>,
95    retention: A2aTaskRetention,
96}
97
98impl Default for TaskStore {
99    fn default() -> Self {
100        Self::with_retention(A2aTaskRetention::default())
101    }
102}
103
104impl TaskStore {
105    /// Creates a store with the default [`A2aTaskRetention`].
106    pub fn new() -> Self {
107        Self::default()
108    }
109
110    /// Creates a store that evicts records according to `retention`.
111    pub fn with_retention(retention: A2aTaskRetention) -> Self {
112        Self { tasks: RwLock::new(HashMap::new()), retention }
113    }
114
115    /// Stores `task` without an owner.
116    ///
117    /// An ownerless record is visible only to unauthenticated callers. Use
118    /// [`store_for`](Self::store_for) to record the principal that started it.
119    pub async fn store(&self, task: Task) {
120        self.store_for(None, task).await;
121    }
122
123    /// Stores `task` as owned by `owner`, then applies the retention policy.
124    pub async fn store_for(&self, owner: Option<&str>, task: Task) {
125        let mut tasks = self.tasks.write().await;
126        tasks.insert(
127            task.id.clone(),
128            StoredTask { task, owner: owner.map(str::to_string), finished_at: Instant::now() },
129        );
130        self.evict(&mut tasks, Instant::now());
131    }
132
133    /// Returns a stored task regardless of its owner.
134    ///
135    /// This is for programmatic access by the server operator; request handlers
136    /// use [`get_for`](Self::get_for).
137    pub async fn get(&self, task_id: &str) -> Option<Task> {
138        let tasks = self.tasks.read().await;
139        tasks
140            .get(task_id)
141            .filter(|stored| !self.is_expired(stored))
142            .map(|stored| stored.task.clone())
143    }
144
145    /// Returns a stored task only when it belongs to `owner`.
146    ///
147    /// A task owned by someone else is reported exactly like a missing one, so the
148    /// response does not disclose that the ID exists.
149    pub async fn get_for(&self, owner: Option<&str>, task_id: &str) -> Option<Task> {
150        let tasks = self.tasks.read().await;
151        tasks
152            .get(task_id)
153            .filter(|stored| !self.is_expired(stored) && stored.owner.as_deref() == owner)
154            .map(|stored| stored.task.clone())
155    }
156
157    /// Removes a stored task regardless of its owner.
158    pub async fn remove(&self, task_id: &str) -> Option<Task> {
159        self.tasks.write().await.remove(task_id).map(|stored| stored.task)
160    }
161
162    /// Returns the number of records held, including expired ones not yet evicted.
163    pub async fn len(&self) -> usize {
164        self.tasks.read().await.len()
165    }
166
167    /// Returns `true` when the store holds no records.
168    pub async fn is_empty(&self) -> bool {
169        self.tasks.read().await.is_empty()
170    }
171
172    /// The owner of an unexpired record, or `None` when there is no such record.
173    async fn owner_of(&self, task_id: &str) -> Option<Option<String>> {
174        let tasks = self.tasks.read().await;
175        tasks
176            .get(task_id)
177            .filter(|stored| !self.is_expired(stored))
178            .map(|stored| stored.owner.clone())
179    }
180
181    fn is_expired(&self, stored: &StoredTask) -> bool {
182        self.retention.ttl.is_some_and(|ttl| stored.finished_at.elapsed() >= ttl)
183    }
184
185    fn evict(&self, tasks: &mut HashMap<String, StoredTask>, now: Instant) {
186        if let Some(ttl) = self.retention.ttl {
187            tasks.retain(|_, stored| now.saturating_duration_since(stored.finished_at) < ttl);
188        }
189        if let Some(max_finished) = self.retention.max_finished
190            && tasks.len() > max_finished
191        {
192            let mut by_age: Vec<(Instant, String)> =
193                tasks.iter().map(|(id, stored)| (stored.finished_at, id.clone())).collect();
194            by_age.sort();
195            let excess = tasks.len() - max_finished;
196            for (_, task_id) in by_age.into_iter().take(excess) {
197                tasks.remove(&task_id);
198            }
199        }
200    }
201}
202
203#[derive(Clone)]
204struct ActiveTask {
205    token: CancellationToken,
206    abort_handle: tokio::task::AbortHandle,
207    completion: Arc<Notify>,
208    context_id: String,
209    owner: Option<String>,
210}
211
212enum StreamTaskMessage {
213    Update(Box<UpdateEvent>),
214    Error(String),
215}
216
217/// A task that was registered and spawned.
218struct StartedTask {
219    result: oneshot::Receiver<adk_core::Result<Task>>,
220    updates: Option<mpsc::Receiver<StreamTaskMessage>>,
221}
222
223/// Controller for A2A protocol endpoints.
224///
225/// When the request carries an authenticated principal, the principal owns the
226/// session and every task it starts: the session user is the principal's
227/// `user_id`, and `tasks/get` and `tasks/cancel` only reach that principal's
228/// tasks. Without authentication the session user is `A2A_USER_{contextId}`.
229#[derive(Clone)]
230pub struct A2aController {
231    config: ServerConfig,
232    agent_card: AgentCard,
233    task_store: Arc<TaskStore>,
234    active_tasks: Arc<Mutex<HashMap<String, ActiveTask>>>,
235}
236
237impl A2aController {
238    pub fn new(config: ServerConfig, base_url: &str) -> Self {
239        Self::build(config, base_url, None)
240    }
241
242    /// Create a controller whose agent card also lists the skills in `skill_index`.
243    ///
244    /// The indexed skills are appended to the agent-derived `skills[]` entries
245    /// via [`agent_skills_from_index`](crate::a2a::agent_skills_from_index) and
246    /// served at `/.well-known/agent-card.json` and `/.well-known/agent.json`.
247    pub fn with_skill_index(
248        config: ServerConfig,
249        base_url: &str,
250        skill_index: Arc<adk_skill::SkillIndex>,
251    ) -> Self {
252        Self::build(config, base_url, Some(skill_index))
253    }
254
255    /// Replaces the bounds on retained finished-task records.
256    ///
257    /// Call this before the controller serves requests: it starts a fresh store.
258    ///
259    /// # Example
260    ///
261    /// ```rust,ignore
262    /// use adk_server::{A2aController, A2aTaskRetention};
263    ///
264    /// let controller = A2aController::new(config, "http://localhost:8080")
265    ///     .with_task_retention(A2aTaskRetention::default().with_max_finished(100));
266    /// ```
267    pub fn with_task_retention(mut self, retention: A2aTaskRetention) -> Self {
268        self.task_store = Arc::new(TaskStore::with_retention(retention));
269        self
270    }
271
272    fn build(
273        config: ServerConfig,
274        base_url: &str,
275        skill_index: Option<Arc<adk_skill::SkillIndex>>,
276    ) -> Self {
277        let root_agent = config.agent_loader.root_agent();
278        let invoke_url = format!("{}/a2a", base_url.trim_end_matches('/'));
279        let mut agent_card = build_agent_card(root_agent.as_ref(), &invoke_url);
280        if let Some(skill_index) = skill_index {
281            let indexed = crate::a2a::agent_skills_from_index(&skill_index);
282            tracing::debug!(skill.count = indexed.len(), "appending indexed skills to agent card");
283            agent_card.skills.extend(indexed);
284        }
285
286        Self {
287            config,
288            agent_card,
289            task_store: Arc::new(TaskStore::new()),
290            active_tasks: Arc::new(Mutex::new(HashMap::new())),
291        }
292    }
293}
294
295fn build_runner_config(
296    controller: &A2aController,
297    root_agent: Arc<dyn adk_core::Agent>,
298    cancellation_token: Option<CancellationToken>,
299    request_context: Option<RequestContext>,
300) -> Arc<RunnerConfig> {
301    runner_config_for(&controller.config, root_agent, cancellation_token, request_context)
302}
303
304/// The runner configuration for `root_agent` with the services `config` provides:
305/// sessions, governance, artifacts, memory, compaction and context caching. Both A2A
306/// versions run their agent with this.
307pub(crate) fn runner_config_for(
308    config: &ServerConfig,
309    root_agent: Arc<dyn adk_core::Agent>,
310    cancellation_token: Option<CancellationToken>,
311    request_context: Option<RequestContext>,
312) -> Arc<RunnerConfig> {
313    let mut builder = Runner::builder()
314        .app_name(root_agent.name())
315        .agent(root_agent)
316        .session_service(config.session_service.clone())
317        .governance(config.governance.clone());
318    if let Some(ref artifact_service) = config.artifact_service {
319        builder = builder.artifact_service(artifact_service.clone());
320    }
321    if let Some(ref memory_service) = config.memory_service {
322        builder = builder.memory_service(memory_service.clone());
323    }
324    if let Some(ref compaction_config) = config.compaction_config {
325        builder = builder.compaction_config(compaction_config.clone());
326    }
327    if let Some(ref context_cache_config) = config.context_cache_config {
328        builder = builder.context_cache_config(context_cache_config.clone());
329    }
330    if let Some(ref cache_capable) = config.cache_capable {
331        builder = builder.cache_capable(cache_capable.clone());
332    }
333    if let Some(cancellation_token) = cancellation_token {
334        builder = builder.cancellation_token(cancellation_token);
335    }
336    if let Some(request_context) = request_context {
337        builder = builder.request_context(request_context);
338    }
339    Arc::new(builder.build_config())
340}
341
342fn build_task_from_events(task_id: &str, context_id: &str, events: &[UpdateEvent]) -> Task {
343    let mut task = Task {
344        id: task_id.to_string(),
345        context_id: Some(context_id.to_string()),
346        status: TaskStatus { state: TaskState::Completed, message: None },
347        artifacts: Some(vec![]),
348        history: None,
349    };
350
351    for event in events {
352        match event {
353            UpdateEvent::TaskStatusUpdate(status) => {
354                task.status = status.status.clone();
355            }
356            UpdateEvent::TaskArtifactUpdate(update) => {
357                let artifacts = task.artifacts.get_or_insert_with(Vec::new);
358                let appended_to = artifacts.iter_mut().find(|artifact| {
359                    update.append && artifact.artifact_id == update.artifact.artifact_id
360                });
361                let Some(artifact) = appended_to else {
362                    artifacts.push(update.artifact.clone());
363                    continue;
364                };
365                // `append` adds to the artifact the update names (A2A 0.3); streamed text
366                // arrives as fragments of one text, so a fragment joins the text before it.
367                for part in &update.artifact.parts {
368                    match (artifact.parts.last_mut(), part) {
369                        (
370                            Some(crate::a2a::Part::Text { text, metadata: None }),
371                            crate::a2a::Part::Text { text: fragment, metadata: None },
372                        ) => text.push_str(fragment),
373                        _ => artifact.parts.push(part.clone()),
374                    }
375                }
376            }
377        }
378    }
379
380    task
381}
382
383fn build_failed_task(task_id: &str, context_id: &str, message: impl Into<String>) -> Task {
384    Task {
385        id: task_id.to_string(),
386        context_id: Some(context_id.to_string()),
387        status: TaskStatus { state: TaskState::Failed, message: Some(message.into()) },
388        artifacts: None,
389        history: None,
390    }
391}
392
393fn build_canceled_task(task_id: &str, context_id: &str) -> Task {
394    Task {
395        id: task_id.to_string(),
396        context_id: Some(context_id.to_string()),
397        status: TaskStatus { state: TaskState::Canceled, message: None },
398        artifacts: None,
399        history: None,
400    }
401}
402
403fn sanitize_internal_error(config: &ServerConfig, error: &adk_core::AdkError) -> String {
404    if config.security.expose_error_details {
405        error.to_string()
406    } else {
407        "Internal server error".to_string()
408    }
409}
410
411/// The error for a task the caller cannot see, whether missing or owned by another user.
412fn task_not_found(task_id: &str) -> JsonRpcError {
413    JsonRpcError::internal_error(format!("Task not found: {task_id}"))
414}
415
416/// Registers and spawns a task on behalf of `caller`.
417///
418/// # Errors
419///
420/// Returns an `invalid_params` JSON-RPC error when `task_id` names a running task,
421/// or a finished task owned by another principal.
422async fn start_task(
423    controller: &A2aController,
424    caller: AuthenticatedCaller,
425    context_id: String,
426    task_id: String,
427    message: Message,
428    stream_updates: bool,
429) -> Result<StartedTask, JsonRpcError> {
430    let owner = caller.user_id().map(str::to_string);
431
432    // The registry lock is held from the duplicate check until the entry is inserted.
433    // The spawned task removes its entry under the same lock, so it cannot finish
434    // before it is registered and leave a permanent `Working` entry behind.
435    let mut active_tasks = controller.active_tasks.lock().await;
436    let reused_by_other = controller
437        .task_store
438        .owner_of(&task_id)
439        .await
440        .is_some_and(|stored_owner| stored_owner != owner);
441    if active_tasks.contains_key(&task_id) || reused_by_other {
442        tracing::warn!(task.id = %task_id, "rejected a2a message with a task id already in use");
443        return Err(JsonRpcError::invalid_params(format!("task id '{task_id}' is already in use")));
444    }
445
446    let token = CancellationToken::new();
447    let completion = Arc::new(Notify::new());
448    let (task_tx, task_rx) = oneshot::channel();
449    let (stream_tx, stream_rx) = if stream_updates {
450        let (tx, rx) = mpsc::channel(32);
451        (Some(tx), Some(rx))
452    } else {
453        (None, None)
454    };
455
456    let root_agent = controller.config.agent_loader.root_agent();
457    let executor = Executor::new(ExecutorConfig {
458        app_name: root_agent.name().to_string(),
459        runner_config: build_runner_config(controller, root_agent, Some(token.clone()), caller.0),
460        cancellation_token: Some(token.clone()),
461        #[cfg(feature = "a2a-interceptors")]
462        interceptor_chain: controller.config.interceptor_chain.clone(),
463    });
464
465    let controller_clone = controller.clone();
466    let completion_clone = completion.clone();
467    let task_id_for_task = task_id.clone();
468    let context_id_for_task = context_id.clone();
469    let owner_for_task = owner.clone();
470
471    let join_handle = tokio::spawn(async move {
472        let result = executor
473            .execute_for_user(
474                owner_for_task.as_deref(),
475                &context_id_for_task,
476                &task_id_for_task,
477                &message,
478            )
479            .await;
480
481        match result {
482            Ok(events) => {
483                if let Some(sender) = stream_tx {
484                    for event in &events {
485                        if sender
486                            .send(StreamTaskMessage::Update(Box::new(event.clone())))
487                            .await
488                            .is_err()
489                        {
490                            break;
491                        }
492                    }
493                }
494
495                let task = build_task_from_events(&task_id_for_task, &context_id_for_task, &events);
496                controller_clone
497                    .task_store
498                    .store_for(owner_for_task.as_deref(), task.clone())
499                    .await;
500                let _ = task_tx.send(Ok(task));
501            }
502            Err(error) => {
503                let message = sanitize_internal_error(&controller_clone.config, &error);
504                if let Some(sender) = stream_tx {
505                    let _ = sender.send(StreamTaskMessage::Error(message.clone())).await;
506                }
507                controller_clone
508                    .task_store
509                    .store_for(
510                        owner_for_task.as_deref(),
511                        build_failed_task(&task_id_for_task, &context_id_for_task, message),
512                    )
513                    .await;
514                let _ = task_tx.send(Err(error));
515            }
516        }
517
518        controller_clone.active_tasks.lock().await.remove(&task_id_for_task);
519        completion_clone.notify_waiters();
520    });
521
522    active_tasks.insert(
523        task_id,
524        ActiveTask {
525            token,
526            abort_handle: join_handle.abort_handle(),
527            completion,
528            context_id,
529            owner,
530        },
531    );
532
533    Ok(StartedTask { result: task_rx, updates: stream_rx })
534}
535
536/// GET /.well-known/agent-card.json and /.well-known/agent.json - Serve the agent card
537pub async fn get_agent_card(State(controller): State<A2aController>) -> impl IntoResponse {
538    Json(controller.agent_card.clone())
539}
540
541/// POST /a2a - JSON-RPC endpoint for A2A protocol, without caller identity.
542///
543/// Every request is treated as unauthenticated: sessions belong to
544/// `A2A_USER_{contextId}` and only ownerless tasks are visible, even when an
545/// authentication layer ran in front of the route.
546#[deprecated(
547    note = "ignores the authenticated caller; mount `handle_jsonrpc_for_caller`, which the built-in routers use"
548)]
549pub async fn handle_jsonrpc(
550    State(controller): State<A2aController>,
551    Json(request): Json<JsonRpcRequest>,
552) -> impl IntoResponse {
553    handle_jsonrpc_for_caller(State(controller), AuthenticatedCaller::default(), Json(request))
554        .await
555}
556
557/// POST /a2a - JSON-RPC endpoint for the A2A protocol.
558///
559/// The authenticated principal, when present, owns the session and the tasks the
560/// request starts. `tasks/get` and `tasks/cancel` answer "not found" for a task
561/// owned by anyone else. Without authentication the session user is
562/// `A2A_USER_{contextId}`.
563pub async fn handle_jsonrpc_for_caller(
564    State(controller): State<A2aController>,
565    caller: AuthenticatedCaller,
566    Json(request): Json<JsonRpcRequest>,
567) -> Json<JsonRpcResponse> {
568    if request.jsonrpc != "2.0" {
569        return Json(JsonRpcResponse::error(
570            request.id,
571            JsonRpcError::invalid_request("Invalid JSON-RPC version"),
572        ));
573    }
574
575    match request.method.as_str() {
576        jsonrpc::methods::MESSAGE_SEND => {
577            handle_message_send(&controller, caller, request.params, request.id).await
578        }
579        jsonrpc::methods::TASKS_GET => {
580            handle_tasks_get(&controller, &caller, request.params, request.id).await
581        }
582        jsonrpc::methods::TASKS_CANCEL => {
583            handle_tasks_cancel(&controller, &caller, request.params, request.id).await
584        }
585        _ => Json(JsonRpcResponse::error(
586            request.id,
587            JsonRpcError::method_not_found(&request.method),
588        )),
589    }
590}
591
592/// POST /a2a/stream - SSE streaming endpoint for A2A protocol, without caller identity.
593///
594/// Every request is treated as unauthenticated; see [`handle_jsonrpc`].
595#[deprecated(
596    note = "ignores the authenticated caller; mount `handle_jsonrpc_stream_for_caller`, which the built-in routers use"
597)]
598pub async fn handle_jsonrpc_stream(
599    State(controller): State<A2aController>,
600    Json(request): Json<JsonRpcRequest>,
601) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, (StatusCode, Json<JsonRpcResponse>)>
602{
603    handle_jsonrpc_stream_for_caller(
604        State(controller),
605        AuthenticatedCaller::default(),
606        Json(request),
607    )
608    .await
609}
610
611/// POST /a2a/stream - SSE streaming endpoint for the A2A protocol.
612///
613/// Binds the session and the started task to the authenticated principal, as
614/// [`handle_jsonrpc_for_caller`] does.
615pub async fn handle_jsonrpc_stream_for_caller(
616    State(controller): State<A2aController>,
617    caller: AuthenticatedCaller,
618    Json(request): Json<JsonRpcRequest>,
619) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, (StatusCode, Json<JsonRpcResponse>)>
620{
621    let bad_request = |error: JsonRpcError| {
622        (StatusCode::BAD_REQUEST, Json(JsonRpcResponse::error(request.id.clone(), error)))
623    };
624
625    if request.jsonrpc != "2.0" {
626        return Err(bad_request(JsonRpcError::invalid_request("Invalid JSON-RPC version")));
627    }
628
629    if request.method != jsonrpc::methods::MESSAGE_SEND_STREAM
630        && request.method != jsonrpc::methods::MESSAGE_SEND
631    {
632        return Err(bad_request(JsonRpcError::method_not_found(&request.method)));
633    }
634
635    let params: MessageSendParams = match request.params.clone() {
636        Some(p) => serde_json::from_value(p)
637            .map_err(|e| bad_request(JsonRpcError::invalid_params(e.to_string())))?,
638        None => return Err(bad_request(JsonRpcError::invalid_params("Missing params"))),
639    };
640
641    let context_id =
642        params.message.context_id.clone().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
643    let task_id =
644        params.message.task_id.clone().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
645
646    let started = start_task(&controller, caller, context_id, task_id, params.message, true)
647        .await
648        .map_err(bad_request)?;
649
650    let stream = create_message_stream(started.updates, request.id.clone());
651
652    Ok(Sse::new(stream).keep_alive(
653        axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)).text("ping"),
654    ))
655}
656
657fn create_message_stream(
658    updates: Option<mpsc::Receiver<StreamTaskMessage>>,
659    request_id: Option<Value>,
660) -> impl Stream<Item = Result<Event, Infallible>> {
661    async_stream::stream! {
662        let Some(mut stream_rx) = updates else {
663            yield Ok(Event::default().event("done").data(""));
664            return;
665        };
666
667        while let Some(message) = stream_rx.recv().await {
668            match message {
669                StreamTaskMessage::Update(event) => {
670                    let event_data = match event.as_ref() {
671                        UpdateEvent::TaskStatusUpdate(status) => {
672                            serde_json::to_string(&JsonRpcResponse::success(
673                                request_id.clone(),
674                                serde_json::to_value(status).unwrap_or_default(),
675                            ))
676                        }
677                        UpdateEvent::TaskArtifactUpdate(artifact) => {
678                            serde_json::to_string(&JsonRpcResponse::success(
679                                request_id.clone(),
680                                serde_json::to_value(artifact).unwrap_or_default(),
681                            ))
682                        }
683                    };
684
685                    if let Ok(data) = event_data {
686                        yield Ok(Event::default().data(data));
687                    }
688                }
689                StreamTaskMessage::Error(message) => {
690                    let error_response = JsonRpcResponse::error(
691                        request_id.clone(),
692                        JsonRpcError::internal_error(message),
693                    );
694                    if let Ok(data) = serde_json::to_string(&error_response) {
695                        yield Ok(Event::default().data(data));
696                    }
697                }
698            }
699        }
700
701        // Send done event
702        yield Ok(Event::default().event("done").data(""));
703    }
704}
705
706async fn handle_message_send(
707    controller: &A2aController,
708    caller: AuthenticatedCaller,
709    params: Option<Value>,
710    id: Option<Value>,
711) -> Json<JsonRpcResponse> {
712    let params: MessageSendParams = match params {
713        Some(p) => match serde_json::from_value(p) {
714            Ok(p) => p,
715            Err(e) => {
716                return Json(JsonRpcResponse::error(
717                    id,
718                    JsonRpcError::invalid_params(e.to_string()),
719                ));
720            }
721        },
722        None => {
723            return Json(JsonRpcResponse::error(
724                id,
725                JsonRpcError::invalid_params("Missing params"),
726            ));
727        }
728    };
729
730    let context_id =
731        params.message.context_id.clone().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
732    let task_id =
733        params.message.task_id.clone().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
734
735    let started =
736        match start_task(controller, caller, context_id, task_id, params.message, false).await {
737            Ok(started) => started,
738            Err(error) => return Json(JsonRpcResponse::error(id, error)),
739        };
740
741    match started.result.await {
742        Ok(Ok(task)) => {
743            Json(JsonRpcResponse::success(id, serde_json::to_value(task).unwrap_or_default()))
744        }
745        Ok(Err(e)) => Json(JsonRpcResponse::error(
746            id,
747            JsonRpcError::internal_error_sanitized(
748                &e,
749                controller.config.security.expose_error_details,
750            ),
751        )),
752        Err(_) => {
753            Json(JsonRpcResponse::error(id, JsonRpcError::internal_error("Task execution aborted")))
754        }
755    }
756}
757
758async fn handle_tasks_get(
759    controller: &A2aController,
760    caller: &AuthenticatedCaller,
761    params: Option<Value>,
762    id: Option<Value>,
763) -> Json<JsonRpcResponse> {
764    let params: TasksGetParams = match params {
765        Some(p) => match serde_json::from_value(p) {
766            Ok(p) => p,
767            Err(e) => {
768                return Json(JsonRpcResponse::error(
769                    id,
770                    JsonRpcError::invalid_params(e.to_string()),
771                ));
772            }
773        },
774        None => {
775            return Json(JsonRpcResponse::error(
776                id,
777                JsonRpcError::invalid_params("Missing params"),
778            ));
779        }
780    };
781
782    let owner = caller.user_id();
783    let active_task = controller
784        .active_tasks
785        .lock()
786        .await
787        .get(&params.task_id)
788        .filter(|task| task.owner.as_deref() == owner)
789        .cloned();
790    if let Some(active_task) = active_task {
791        let task = Task {
792            id: params.task_id.clone(),
793            context_id: Some(active_task.context_id),
794            status: TaskStatus { state: TaskState::Working, message: None },
795            artifacts: None,
796            history: None,
797        };
798
799        return Json(JsonRpcResponse::success(id, serde_json::to_value(task).unwrap_or_default()));
800    }
801
802    match controller.task_store.get_for(owner, &params.task_id).await {
803        Some(task) => {
804            Json(JsonRpcResponse::success(id, serde_json::to_value(task).unwrap_or_default()))
805        }
806        None => Json(JsonRpcResponse::error(id, task_not_found(&params.task_id))),
807    }
808}
809
810async fn handle_tasks_cancel(
811    controller: &A2aController,
812    caller: &AuthenticatedCaller,
813    params: Option<Value>,
814    id: Option<Value>,
815) -> Json<JsonRpcResponse> {
816    let params: TasksCancelParams = match params {
817        Some(p) => match serde_json::from_value(p) {
818            Ok(p) => p,
819            Err(e) => {
820                return Json(JsonRpcResponse::error(
821                    id,
822                    JsonRpcError::invalid_params(e.to_string()),
823                ));
824            }
825        },
826        None => {
827            return Json(JsonRpcResponse::error(
828                id,
829                JsonRpcError::invalid_params("Missing params"),
830            ));
831        }
832    };
833
834    let owner = caller.user_id();
835    let active_task = controller
836        .active_tasks
837        .lock()
838        .await
839        .get(&params.task_id)
840        .filter(|task| task.owner.as_deref() == owner)
841        .cloned();
842
843    if let Some(active_task) = active_task {
844        active_task.token.cancel();
845
846        if tokio::time::timeout(Duration::from_secs(5), active_task.completion.notified())
847            .await
848            .is_err()
849        {
850            active_task.abort_handle.abort();
851            controller.active_tasks.lock().await.remove(&params.task_id);
852            controller
853                .task_store
854                .store_for(
855                    active_task.owner.as_deref(),
856                    build_canceled_task(&params.task_id, &active_task.context_id),
857                )
858                .await;
859        }
860
861        let status = TaskStatusUpdateEvent {
862            task_id: params.task_id,
863            context_id: Some(active_task.context_id),
864            status: TaskStatus { state: TaskState::Canceled, message: None },
865            final_update: true,
866        };
867
868        return Json(JsonRpcResponse::success(
869            id,
870            serde_json::to_value(status).unwrap_or_default(),
871        ));
872    }
873
874    let Some(stored) = controller.task_store.get_for(owner, &params.task_id).await else {
875        return Json(JsonRpcResponse::error(id, task_not_found(&params.task_id)));
876    };
877
878    let status = TaskStatusUpdateEvent {
879        task_id: params.task_id,
880        context_id: stored.context_id,
881        status: TaskStatus { state: TaskState::Canceled, message: None },
882        final_update: true,
883    };
884
885    Json(JsonRpcResponse::success(id, serde_json::to_value(status).unwrap_or_default()))
886}
887#[cfg(test)]
888mod tests {
889    use super::*;
890    use adk_core::{Agent, EventStream, InvocationContext, Result as AdkResult, SingleAgentLoader};
891    use adk_session::InMemorySessionService;
892    use async_trait::async_trait;
893    use futures::stream;
894
895    struct TestAgent;
896
897    #[async_trait]
898    impl Agent for TestAgent {
899        fn name(&self) -> &str {
900            "card_agent"
901        }
902
903        fn description(&self) -> &str {
904            "A card test agent"
905        }
906
907        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
908            &[]
909        }
910
911        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> AdkResult<EventStream> {
912            Ok(Box::pin(stream::empty()))
913        }
914    }
915
916    fn test_config() -> ServerConfig {
917        let agent_loader = Arc::new(SingleAgentLoader::new(Arc::new(TestAgent)));
918        let session_service = Arc::new(InMemorySessionService::new());
919        ServerConfig::new(agent_loader, session_service)
920    }
921
922    fn skill_doc(name: &str) -> adk_skill::SkillDocument {
923        adk_skill::SkillDocument {
924            id: format!("{name}-0123456789ab"),
925            name: name.to_string(),
926            description: format!("{name} description"),
927            version: None,
928            license: None,
929            compatibility: None,
930            tags: vec!["indexed".to_string()],
931            allowed_tools: vec![],
932            references: vec![],
933            trigger: false,
934            hint: None,
935            metadata: Default::default(),
936            body: String::new(),
937            path: format!("skills/{name}.skill.md").into(),
938            hash: "0123456789ab".to_string(),
939            last_modified: None,
940            triggers: vec![],
941        }
942    }
943
944    #[test]
945    fn with_skill_index_appends_indexed_skills_to_card() {
946        let index = Arc::new(adk_skill::SkillIndex::new(vec![
947            skill_doc("skill-one"),
948            skill_doc("skill-two"),
949        ]));
950
951        let controller =
952            A2aController::with_skill_index(test_config(), "http://localhost:8080", index);
953
954        let expected = serde_json::json!([
955            {
956                "id": "card_agent",
957                "name": "custom",
958                "description": "A card test agent",
959                "tags": ["custom_agent"],
960            },
961            {
962                "id": "skill-one",
963                "name": "skill-one",
964                "description": "skill-one description",
965                "tags": ["indexed"],
966            },
967            {
968                "id": "skill-two",
969                "name": "skill-two",
970                "description": "skill-two description",
971                "tags": ["indexed"],
972            },
973        ]);
974        assert_eq!(serde_json::to_value(&controller.agent_card.skills).unwrap(), expected);
975    }
976
977    #[test]
978    fn new_leaves_card_skills_agent_derived() {
979        let controller = A2aController::new(test_config(), "http://localhost:8080");
980
981        let expected = serde_json::json!([
982            {
983                "id": "card_agent",
984                "name": "custom",
985                "description": "A card test agent",
986                "tags": ["custom_agent"],
987            },
988        ]);
989        assert_eq!(serde_json::to_value(&controller.agent_card.skills).unwrap(), expected);
990    }
991
992    // ── Task store hygiene ─────────────────────────────────────────────────
993
994    /// Replies once `gate` is notified, so a test controls when a task finishes.
995    struct GatedAgent {
996        gate: Arc<Notify>,
997    }
998
999    #[async_trait]
1000    impl Agent for GatedAgent {
1001        fn name(&self) -> &str {
1002            "gated_agent"
1003        }
1004
1005        fn description(&self) -> &str {
1006            "replies when released"
1007        }
1008
1009        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1010            &[]
1011        }
1012
1013        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> AdkResult<EventStream> {
1014            let gate = self.gate.clone();
1015            let invocation_id = ctx.invocation_id().to_string();
1016            Ok(Box::pin(async_stream::stream! {
1017                gate.notified().await;
1018                let mut event = adk_core::Event::new(invocation_id);
1019                event.author = "gated_agent".to_string();
1020                event.llm_response.content =
1021                    Some(adk_core::Content::new("model").with_text("released"));
1022                yield Ok(event);
1023            }))
1024        }
1025    }
1026
1027    fn controller_with(agent: Arc<dyn Agent>) -> A2aController {
1028        let agent_loader = Arc::new(SingleAgentLoader::new(agent));
1029        let config = ServerConfig::new(agent_loader, Arc::new(InMemorySessionService::new()));
1030        A2aController::new(config, "http://localhost:8080")
1031    }
1032
1033    fn text_message(text: &str) -> Message {
1034        Message::builder()
1035            .role(crate::a2a::Role::User)
1036            .parts(vec![crate::a2a::Part::text(text.to_string())])
1037            .message_id(uuid::Uuid::new_v4().to_string())
1038            .build()
1039    }
1040
1041    /// A data part the converter does not understand, so execution fails before the agent runs.
1042    fn unconvertible_message() -> Message {
1043        let mut data = serde_json::Map::new();
1044        data.insert("not_a_function_call".to_string(), serde_json::json!("db-password=hunter2"));
1045        Message::builder()
1046            .role(crate::a2a::Role::User)
1047            .parts(vec![crate::a2a::Part::Data { data, metadata: None }])
1048            .message_id(uuid::Uuid::new_v4().to_string())
1049            .build()
1050    }
1051
1052    fn finished_task(task_id: &str) -> Task {
1053        build_task_from_events(task_id, "ctx", &[])
1054    }
1055
1056    #[tokio::test]
1057    async fn store_evicts_the_oldest_records_beyond_max_finished() {
1058        let store = TaskStore::with_retention(A2aTaskRetention::unlimited().with_max_finished(2));
1059        for task_id in ["t1", "t2", "t3"] {
1060            store.store(finished_task(task_id)).await;
1061        }
1062
1063        assert_eq!(store.len().await, 2);
1064        assert!(store.get("t1").await.is_none(), "the oldest record is evicted first");
1065        assert!(store.get("t2").await.is_some());
1066        assert!(store.get("t3").await.is_some());
1067    }
1068
1069    #[tokio::test]
1070    async fn store_expires_records_after_their_ttl() {
1071        let store = TaskStore::with_retention(
1072            A2aTaskRetention::unlimited().with_ttl(Duration::from_secs(60)),
1073        );
1074        let long_ago = Instant::now().checked_sub(Duration::from_secs(120)).unwrap();
1075        store.tasks.write().await.insert(
1076            "old".to_string(),
1077            StoredTask { task: finished_task("old"), owner: None, finished_at: long_ago },
1078        );
1079
1080        assert!(store.get("old").await.is_none(), "an expired record is not readable");
1081
1082        store.store(finished_task("new")).await;
1083        assert_eq!(store.len().await, 1, "storing a record evicts expired ones");
1084        assert!(store.get("new").await.is_some());
1085    }
1086
1087    #[tokio::test]
1088    async fn store_reads_are_scoped_to_the_owner() {
1089        let store = TaskStore::new();
1090        store.store_for(Some("alice"), finished_task("t1")).await;
1091
1092        assert!(store.get_for(Some("bob"), "t1").await.is_none());
1093        assert!(store.get_for(None, "t1").await.is_none());
1094        assert_eq!(
1095            serde_json::to_value(store.get_for(Some("alice"), "t1").await).unwrap(),
1096            serde_json::to_value(finished_task("t1")).unwrap()
1097        );
1098    }
1099
1100    #[tokio::test]
1101    async fn duplicate_task_id_is_rejected_and_the_running_task_keeps_its_handle() {
1102        let gate = Arc::new(Notify::new());
1103        let controller = controller_with(Arc::new(GatedAgent { gate: gate.clone() }));
1104        let caller = AuthenticatedCaller::default();
1105
1106        let first = start_task(
1107            &controller,
1108            caller.clone(),
1109            "ctx".to_string(),
1110            "dup".to_string(),
1111            text_message("one"),
1112            false,
1113        )
1114        .await
1115        .expect("the first task starts");
1116        let original_handle = controller.active_tasks.lock().await["dup"].abort_handle.id();
1117
1118        let duplicate = start_task(
1119            &controller,
1120            caller,
1121            "ctx".to_string(),
1122            "dup".to_string(),
1123            text_message("two"),
1124            false,
1125        )
1126        .await;
1127
1128        let error = duplicate.err().expect("a running task id cannot be reused");
1129        assert_eq!(
1130            serde_json::to_value(error).unwrap(),
1131            serde_json::json!({ "code": -32602, "message": "task id 'dup' is already in use" })
1132        );
1133        assert_eq!(
1134            controller.active_tasks.lock().await["dup"].abort_handle.id(),
1135            original_handle,
1136            "the running task's registration must not be replaced"
1137        );
1138
1139        gate.notify_one();
1140        let task = first.result.await.unwrap().unwrap();
1141        assert_eq!(task.status.state, TaskState::Completed);
1142    }
1143
1144    #[tokio::test]
1145    async fn finished_task_id_of_another_owner_cannot_be_reused() {
1146        let controller = controller_with(Arc::new(TestAgent));
1147        controller.task_store.store_for(Some("bob"), finished_task("bobs-task")).await;
1148
1149        let alice = AuthenticatedCaller(Some(RequestContext {
1150            user_id: "alice".to_string(),
1151            scopes: vec![],
1152            metadata: Default::default(),
1153        }));
1154        let attempt = start_task(
1155            &controller,
1156            alice,
1157            "ctx".to_string(),
1158            "bobs-task".to_string(),
1159            text_message("overwrite"),
1160            false,
1161        )
1162        .await;
1163
1164        assert!(attempt.is_err(), "another owner's record must not be overwritten");
1165        assert!(controller.task_store.get_for(Some("bob"), "bobs-task").await.is_some());
1166    }
1167
1168    #[tokio::test]
1169    async fn failed_task_record_carries_the_sanitized_error() {
1170        let controller = controller_with(Arc::new(TestAgent));
1171
1172        let started = start_task(
1173            &controller,
1174            AuthenticatedCaller::default(),
1175            "ctx".to_string(),
1176            "failing".to_string(),
1177            unconvertible_message(),
1178            false,
1179        )
1180        .await
1181        .unwrap();
1182        assert!(started.result.await.unwrap().is_err());
1183
1184        let stored = controller.task_store.get_for(None, "failing").await.unwrap();
1185        assert_eq!(
1186            serde_json::to_value(stored).unwrap(),
1187            serde_json::to_value(build_failed_task("failing", "ctx", "Internal server error"))
1188                .unwrap()
1189        );
1190    }
1191
1192    #[tokio::test]
1193    async fn fast_failing_tasks_leave_no_working_entry_behind() {
1194        let controller = controller_with(Arc::new(TestAgent));
1195
1196        for attempt in 0..50 {
1197            let task_id = format!("fast-{attempt}");
1198            let started = start_task(
1199                &controller,
1200                AuthenticatedCaller::default(),
1201                "ctx".to_string(),
1202                task_id.clone(),
1203                unconvertible_message(),
1204                false,
1205            )
1206            .await
1207            .unwrap();
1208            let _ = started.result.await;
1209
1210            // The spawned task removes its entry after reporting; wait for that step.
1211            for _ in 0..100 {
1212                if !controller.active_tasks.lock().await.contains_key(&task_id) {
1213                    break;
1214                }
1215                tokio::task::yield_now().await;
1216            }
1217            assert!(
1218                !controller.active_tasks.lock().await.contains_key(&task_id),
1219                "a finished task must not stay registered as running"
1220            );
1221        }
1222    }
1223}