1use crate::a2a::{
2 A2aClient, Part as A2aPart, Role, TaskArtifactUpdateEvent, TaskStatusUpdateEvent, UpdateEvent,
3};
4use adk_core::{Agent, Content, Event, EventStream, InvocationContext, Part, Result};
5use async_trait::async_trait;
6use std::sync::Arc;
7
8#[derive(Clone)]
10pub struct RemoteA2aConfig {
11 pub name: String,
13 pub description: String,
15 pub agent_url: String,
20 pub streaming: Option<bool>,
23 pub credential_broker: Option<Arc<dyn adk_core::CredentialBroker>>,
27 pub credential_scopes: Vec<String>,
29 pub allowed_endpoint_origins: Vec<String>,
33}
34
35async fn brokered_token(
37 broker: &dyn adk_core::CredentialBroker,
38 acting: &adk_core::ActingContext,
39 resource: &str,
40 scopes: &[String],
41) -> Result<adk_core::ScopedToken> {
42 let resource = adk_core::resource_indicator(resource)?;
43 broker.token_for(acting, &resource, scopes).await
44}
45
46pub struct RemoteA2aAgent {
48 config: RemoteA2aConfig,
49}
50
51impl RemoteA2aAgent {
52 pub fn new(config: RemoteA2aConfig) -> Self {
53 Self { config }
54 }
55
56 pub fn builder(name: impl Into<String>) -> RemoteA2aAgentBuilder {
57 RemoteA2aAgentBuilder::new(name)
58 }
59}
60
61#[async_trait]
62impl Agent for RemoteA2aAgent {
63 fn name(&self) -> &str {
64 &self.config.name
65 }
66
67 fn description(&self) -> &str {
68 &self.config.description
69 }
70
71 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
72 &[]
73 }
74
75 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
76 let url = self.config.agent_url.clone();
77 let invocation_id = ctx.invocation_id().to_string();
78 let agent_name = self.config.name.clone();
79 let config_streaming = self.config.streaming;
80 let broker = self.config.credential_broker.clone();
81 let scopes = self.config.credential_scopes.clone();
82 let allowed_origins = self.config.allowed_endpoint_origins.clone();
83 let acting = ctx.acting_context();
84
85 let user_content = get_user_content_from_context(ctx.as_ref());
87
88 let stream = async_stream::stream! {
89 let mut client = match A2aClient::resolve_agent_card_allowing(&url, &allowed_origins).await {
91 Ok(card) => A2aClient::new(card),
92 Err(e) => {
93 yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
94 return;
95 }
96 };
97 if let Some(broker) = broker.as_deref() {
100 match brokered_token(broker, &acting, &url, &scopes).await {
101 Ok(token) => client = client.with_credential(token),
102 Err(e) => {
103 yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
104 return;
105 }
106 }
107 }
108
109 let use_streaming = config_streaming.unwrap_or(client.agent_card().capabilities.streaming);
111
112 let message = build_a2a_message(user_content);
114
115 if use_streaming {
116 match client.send_streaming_message(message).await {
118 Ok(mut event_stream) => {
119 use futures::StreamExt;
120 while let Some(result) = event_stream.next().await {
121 match result {
122 Ok(update_event) => {
123 if let Some(event) = convert_update_event(&invocation_id, &agent_name, update_event) {
124 yield Ok(event);
125 }
126 }
127 Err(e) => {
128 yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
129 return;
130 }
131 }
132 }
133 }
134 Err(e) => {
135 yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
136 }
137 }
138 } else {
139 match client.send_message(message).await {
141 Ok(rpc_response) => {
142 if let Some(result) = rpc_response.result {
143 match serde_json::from_value::<crate::a2a::Task>(result) {
144 Ok(task) => {
145 for event in convert_task_to_events(&invocation_id, &agent_name, task) {
146 yield Ok(event);
147 }
148 }
149 Err(e) => {
150 yield Ok(create_error_event(&invocation_id, &agent_name, &format!("failed to parse response: {e}")));
151 }
152 }
153 } else if let Some(error) = rpc_response.error {
154 yield Ok(create_error_event(&invocation_id, &agent_name, &format!("RPC error: {} ({})", error.message, error.code)));
155 }
156 }
157 Err(e) => {
158 yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
159 }
160 }
161 }
162 };
163
164 Ok(Box::pin(stream))
165 }
166}
167
168pub struct RemoteA2aAgentBuilder {
170 name: String,
171 description: String,
172 agent_url: Option<String>,
173 streaming: Option<bool>,
174 credential_broker: Option<Arc<dyn adk_core::CredentialBroker>>,
175 credential_scopes: Vec<String>,
176 allowed_endpoint_origins: Vec<String>,
177}
178
179impl RemoteA2aAgentBuilder {
180 pub fn new(name: impl Into<String>) -> Self {
181 Self {
182 name: name.into(),
183 description: String::new(),
184 agent_url: None,
185 streaming: None,
186 credential_broker: None,
187 credential_scopes: Vec::new(),
188 allowed_endpoint_origins: Vec::new(),
189 }
190 }
191
192 pub fn allow_endpoint_origin(mut self, origin: impl Into<String>) -> Self {
197 self.allowed_endpoint_origins.push(origin.into());
198 self
199 }
200
201 pub fn credential_broker(
206 mut self,
207 broker: Arc<dyn adk_core::CredentialBroker>,
208 scopes: Vec<String>,
209 ) -> Self {
210 self.credential_broker = Some(broker);
211 self.credential_scopes = scopes;
212 self
213 }
214
215 pub fn description(mut self, description: impl Into<String>) -> Self {
216 self.description = description.into();
217 self
218 }
219
220 pub fn agent_url(mut self, url: impl Into<String>) -> Self {
221 self.agent_url = Some(url.into());
222 self
223 }
224
225 pub fn streaming(mut self, streaming: bool) -> Self {
227 self.streaming = Some(streaming);
228 self
229 }
230
231 pub fn build(self) -> Result<RemoteA2aAgent> {
232 let agent_url = self
233 .agent_url
234 .ok_or_else(|| adk_core::AdkError::agent("RemoteA2aAgent requires agent_url"))?;
235
236 Ok(RemoteA2aAgent::new(RemoteA2aConfig {
237 name: self.name,
238 description: self.description,
239 agent_url,
240 streaming: self.streaming,
241 credential_broker: self.credential_broker,
242 credential_scopes: self.credential_scopes,
243 allowed_endpoint_origins: self.allowed_endpoint_origins,
244 }))
245 }
246}
247
248fn get_user_content_from_context(ctx: &dyn InvocationContext) -> Option<String> {
251 let content = ctx.user_content();
252 for part in &content.parts {
253 if let Part::Text { text } = part {
254 return Some(text.clone());
255 }
256 }
257 None
258}
259
260fn build_a2a_message(content: Option<String>) -> crate::a2a::Message {
261 let text = content.unwrap_or_default();
262 crate::a2a::Message::builder()
263 .role(Role::User)
264 .parts(vec![A2aPart::text(text)])
265 .message_id(uuid::Uuid::new_v4().to_string())
266 .build()
267}
268
269fn convert_update_event(
270 invocation_id: &str,
271 agent_name: &str,
272 update: UpdateEvent,
273) -> Option<Event> {
274 match update {
275 UpdateEvent::TaskArtifactUpdate(artifact_event) => {
276 let parts: Vec<Part> = artifact_event
277 .artifact
278 .parts
279 .iter()
280 .filter_map(|p| match p {
281 A2aPart::Text { text, .. } => Some(Part::Text { text: text.clone() }),
282 _ => None,
283 })
284 .collect();
285
286 if parts.is_empty() {
287 return None;
288 }
289
290 let mut event = Event::new(invocation_id.to_string());
291 event.author = agent_name.to_string();
292 event.llm_response.content = Some(Content { role: "model".to_string(), parts });
293 event.llm_response.partial = !artifact_event.last_chunk;
294 Some(event)
295 }
296 UpdateEvent::TaskStatusUpdate(status_event) => {
297 if status_event.final_update
299 && let Some(msg) = status_event.status.message
300 {
301 let mut event = Event::new(invocation_id.to_string());
302 event.author = agent_name.to_string();
303 event.llm_response.content = Some(Content {
304 role: "model".to_string(),
305 parts: vec![Part::Text { text: msg }],
306 });
307 event.llm_response.turn_complete = true;
308 return Some(event);
309 }
310 None
311 }
312 }
313}
314
315fn create_error_event(invocation_id: &str, agent_name: &str, error: &str) -> Event {
316 let mut event = Event::new(invocation_id.to_string());
317 event.author = agent_name.to_string();
318 event.llm_response.error_message = Some(error.to_string());
319 event.llm_response.turn_complete = true;
320 event
321}
322
323fn convert_task_to_events(
325 invocation_id: &str,
326 agent_name: &str,
327 task: crate::a2a::Task,
328) -> Vec<Event> {
329 let mut events = Vec::new();
330
331 if let Some(artifacts) = task.artifacts {
333 for artifact in artifacts {
334 let update = UpdateEvent::TaskArtifactUpdate(TaskArtifactUpdateEvent {
335 task_id: task.id.clone(),
336 context_id: task.context_id.clone(),
337 artifact,
338 append: false,
339 last_chunk: true,
340 });
341 if let Some(event) = convert_update_event(invocation_id, agent_name, update) {
342 events.push(event);
343 }
344 }
345 }
346
347 if let Some(history) = task.history {
349 for msg in history {
350 if msg.role == Role::Agent {
351 let parts: Vec<Part> = msg
352 .parts
353 .iter()
354 .filter_map(|p| match p {
355 A2aPart::Text { text, .. } => Some(Part::Text { text: text.clone() }),
356 _ => None,
357 })
358 .collect();
359
360 if !parts.is_empty() {
361 let mut event = Event::new(invocation_id.to_string());
362 event.author = agent_name.to_string();
363 event.llm_response.content = Some(Content { role: "model".to_string(), parts });
364 event.llm_response.turn_complete = false;
365 events.push(event);
366 }
367 }
368 }
369 }
370
371 let update = UpdateEvent::TaskStatusUpdate(TaskStatusUpdateEvent {
373 task_id: task.id,
374 context_id: task.context_id,
375 status: task.status,
376 final_update: true,
377 });
378 if let Some(event) = convert_update_event(invocation_id, agent_name, update) {
379 events.push(event);
380 }
381
382 events
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 #[test]
390 fn test_builder() {
391 let agent = RemoteA2aAgent::builder("test")
392 .description("Test agent")
393 .agent_url("http://localhost:8080")
394 .build()
395 .unwrap();
396
397 assert_eq!(agent.name(), "test");
398 assert_eq!(agent.description(), "Test agent");
399 }
400
401 #[test]
402 fn test_builder_missing_url() {
403 let result = RemoteA2aAgent::builder("test").build();
404 assert!(result.is_err());
405 }
406
407 #[test]
408 fn test_builder_streaming_option() {
409 let agent = RemoteA2aAgent::builder("test")
410 .agent_url("http://localhost:8080")
411 .streaming(true)
412 .build()
413 .unwrap();
414
415 assert_eq!(agent.config.streaming, Some(true));
416 }
417
418 #[test]
419 fn test_builder_streaming_default_is_none() {
420 let agent =
421 RemoteA2aAgent::builder("test").agent_url("http://localhost:8080").build().unwrap();
422
423 assert_eq!(agent.config.streaming, None);
424 }
425
426 #[test]
427 fn test_convert_task_to_events_with_artifacts_and_history() {
428 use crate::a2a::{Artifact, Message, Task, TaskState, TaskStatus};
429
430 let task = Task {
431 id: "task-123".to_string(),
432 context_id: Some("ctx-456".to_string()),
433 status: TaskStatus { state: TaskState::Completed, message: Some("Done".to_string()) },
434 artifacts: Some(vec![Artifact {
435 artifact_id: "art-1".to_string(),
436 name: Some("result".to_string()),
437 description: None,
438 parts: vec![A2aPart::text("artifact content".to_string())],
439 metadata: None,
440 extensions: None,
441 }]),
442 history: Some(vec![
443 Message::builder()
444 .role(Role::Agent)
445 .parts(vec![A2aPart::text("Hello from agent".to_string())])
446 .build(),
447 ]),
448 };
449
450 let events = convert_task_to_events("inv-1", "remote-agent", task);
451
452 assert_eq!(events.len(), 3);
454
455 assert_eq!(events[0].author, "remote-agent");
457 let content = events[0].llm_response.content.as_ref().unwrap();
458 assert_eq!(content.parts[0], Part::Text { text: "artifact content".to_string() });
459
460 assert_eq!(events[1].author, "remote-agent");
462 let content = events[1].llm_response.content.as_ref().unwrap();
463 assert_eq!(content.parts[0], Part::Text { text: "Hello from agent".to_string() });
464 assert!(!events[1].llm_response.turn_complete);
465
466 assert_eq!(events[2].author, "remote-agent");
468 assert!(events[2].llm_response.turn_complete);
469 }
470
471 #[test]
472 fn test_convert_task_to_events_empty_task() {
473 use crate::a2a::{Task, TaskState, TaskStatus};
474
475 let task = Task {
476 id: "task-empty".to_string(),
477 context_id: None,
478 status: TaskStatus { state: TaskState::Completed, message: None },
479 artifacts: None,
480 history: None,
481 };
482
483 let events = convert_task_to_events("inv-1", "agent", task);
484
485 assert!(events.is_empty());
488 }
489
490 #[test]
491 fn test_convert_task_to_events_status_with_message() {
492 use crate::a2a::{Task, TaskState, TaskStatus};
493
494 let task = Task {
495 id: "task-msg".to_string(),
496 context_id: None,
497 status: TaskStatus {
498 state: TaskState::Completed,
499 message: Some("All done".to_string()),
500 },
501 artifacts: None,
502 history: None,
503 };
504
505 let events = convert_task_to_events("inv-1", "agent", task);
506
507 assert_eq!(events.len(), 1);
508 assert!(events[0].llm_response.turn_complete);
509 let content = events[0].llm_response.content.as_ref().unwrap();
510 assert_eq!(content.parts[0], Part::Text { text: "All done".to_string() });
511 }
512}
513
514#[cfg(feature = "a2a-v1")]
517pub mod v1_remote {
518 use crate::a2a::client::v1_client::A2aV1Client;
527 use a2a_protocol_types::responses::SendMessageResponse;
528 use a2a_protocol_types::{AgentCard, AgentInterface};
529 use adk_core::{Agent, Content, Event, EventStream, InvocationContext, Part, Result};
530 use async_trait::async_trait;
531 use std::sync::Arc;
532
533 #[derive(Clone)]
535 pub struct RemoteA2aV1Config {
536 pub name: String,
538 pub description: String,
540 pub agent_card: AgentCard,
542 pub streaming: Option<bool>,
546 pub credential_broker: Option<Arc<dyn adk_core::CredentialBroker>>,
550 pub credential_scopes: Vec<String>,
552 pub send_configuration: Option<a2a_protocol_types::params::SendMessageConfiguration>,
555 pub hooks: RemoteAgentHooks,
557 }
558
559 pub type AgentCallback = Arc<
562 dyn Fn(
563 Arc<dyn adk_core::CallbackContext>,
564 ) -> futures::future::BoxFuture<'static, Result<Option<Content>>>
565 + Send
566 + Sync,
567 >;
568
569 pub type BeforeRequestCallback = Arc<
572 dyn Fn(&dyn InvocationContext, &mut a2a_protocol_types::Message) -> Result<Option<Event>>
573 + Send
574 + Sync,
575 >;
576
577 pub type AfterRequestCallback =
579 Arc<dyn Fn(&dyn InvocationContext, &Event) -> Result<Option<Event>> + Send + Sync>;
580
581 pub type EventConverter = Arc<
584 dyn Fn(&a2a_protocol_types::events::StreamResponse) -> Result<Option<Event>> + Send + Sync,
585 >;
586
587 pub type FromWirePart =
589 Arc<dyn Fn(&a2a_protocol_types::Part) -> Result<Option<Part>> + Send + Sync>;
590
591 pub type ToWirePart =
594 Arc<dyn Fn(&Part) -> Result<Option<a2a_protocol_types::Part>> + Send + Sync>;
595
596 pub type RemoteTaskCleanup =
598 Arc<dyn Fn(String) -> futures::future::BoxFuture<'static, ()> + Send + Sync>;
599
600 pub type CardProvider =
602 Arc<dyn Fn() -> futures::future::BoxFuture<'static, Result<AgentCard>> + Send + Sync>;
603
604 #[derive(Clone, Default)]
607 pub struct RemoteAgentHooks {
608 before_agent: Vec<AgentCallback>,
609 after_agent: Vec<AgentCallback>,
610 before_request: Vec<BeforeRequestCallback>,
611 after_request: Vec<AfterRequestCallback>,
612 event_converter: Option<EventConverter>,
613 from_wire_part: Option<FromWirePart>,
614 to_wire_part: Option<ToWirePart>,
615 remote_task_cleanup: Option<RemoteTaskCleanup>,
616 card_provider: Option<CardProvider>,
617 allow_transfer_to_agent: bool,
618 }
619
620 impl RemoteAgentHooks {
621 #[must_use]
623 pub fn before_agent(mut self, callback: AgentCallback) -> Self {
624 self.before_agent.push(callback);
625 self
626 }
627
628 #[must_use]
630 pub fn after_agent(mut self, callback: AgentCallback) -> Self {
631 self.after_agent.push(callback);
632 self
633 }
634
635 #[must_use]
637 pub fn before_request(mut self, callback: BeforeRequestCallback) -> Self {
638 self.before_request.push(callback);
639 self
640 }
641
642 #[must_use]
644 pub fn after_request(mut self, callback: AfterRequestCallback) -> Self {
645 self.after_request.push(callback);
646 self
647 }
648
649 #[must_use]
651 pub fn event_converter(mut self, converter: EventConverter) -> Self {
652 self.event_converter = Some(converter);
653 self
654 }
655
656 #[must_use]
658 pub fn from_wire_part(mut self, converter: FromWirePart) -> Self {
659 self.from_wire_part = Some(converter);
660 self
661 }
662
663 #[must_use]
665 pub fn to_wire_part(mut self, converter: ToWirePart) -> Self {
666 self.to_wire_part = Some(converter);
667 self
668 }
669
670 #[must_use]
672 pub fn remote_task_cleanup(mut self, cleanup: RemoteTaskCleanup) -> Self {
673 self.remote_task_cleanup = Some(cleanup);
674 self
675 }
676
677 #[must_use]
679 pub fn card_provider(mut self, provider: CardProvider) -> Self {
680 self.card_provider = Some(provider);
681 self
682 }
683
684 #[must_use]
688 pub fn allow_transfer_to_agent(mut self, allow: bool) -> Self {
689 self.allow_transfer_to_agent = allow;
690 self
691 }
692 }
693
694 impl RemoteA2aV1Config {
695 pub fn new(name: impl Into<String>, agent_card: AgentCard) -> Self {
698 Self {
699 name: name.into(),
700 description: agent_card.description.clone(),
701 agent_card,
702 streaming: None,
703 credential_broker: None,
704 credential_scopes: Vec::new(),
705 send_configuration: None,
706 hooks: RemoteAgentHooks::default(),
707 }
708 }
709 }
710
711 pub struct RemoteA2aV1Agent {
717 config: RemoteA2aV1Config,
718 }
719
720 impl RemoteA2aV1Agent {
721 pub fn new(config: RemoteA2aV1Config) -> Self {
723 Self { config }
724 }
725
726 pub async fn from_url(
735 name: impl Into<String>,
736 base_url: &str,
737 ) -> std::result::Result<Self, crate::a2a::client::v1_client::V1ClientError> {
738 let agent_card = A2aV1Client::resolve_agent_card(base_url).await?;
739 Ok(Self::new(RemoteA2aV1Config::new(name, agent_card)))
740 }
741
742 pub fn select_interface(card: &AgentCard) -> Option<&AgentInterface> {
747 use crate::a2a::client::v1_client::v1_interface;
748 v1_interface(card, "JSONRPC").or_else(|| v1_interface(card, "HTTP+JSON"))
749 }
750 }
751
752 #[async_trait]
753 impl Agent for RemoteA2aV1Agent {
754 fn name(&self) -> &str {
755 &self.config.name
756 }
757
758 fn description(&self) -> &str {
759 &self.config.description
760 }
761
762 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
763 &[]
764 }
765
766 async fn cancel_remote_task(
767 &self,
768 task_id: &str,
769 acting: &adk_core::ActingContext,
770 ) -> Result<()> {
771 let card = &self.config.agent_card;
772 let interface = Self::select_interface(card).ok_or_else(|| {
773 adk_core::AdkError::agent("no supported interface found in agent card")
774 })?;
775 let mut client = A2aV1Client::with_retry(
776 card.clone(),
777 crate::a2a::client::v1_client::RetryConfig { max_retries: 0, ..Default::default() },
778 );
779 if let Some(broker) = self.config.credential_broker.as_deref() {
780 let token = super::brokered_token(
781 broker,
782 acting,
783 &interface.url,
784 &self.config.credential_scopes,
785 )
786 .await?;
787 client = client.with_credential(token);
788 }
789 let cancelled = if interface.protocol_binding == "HTTP+JSON" {
790 client.cancel_task_rest(task_id).await
791 } else {
792 client.cancel_task(task_id).await
793 };
794 cancelled.map(drop).map_err(|error| {
795 adk_core::AdkError::agent(format!("cancel remote task {task_id}: {error}"))
796 })
797 }
798
799 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
800 let turn = self.turn(ctx.clone());
801 let hooks = self.config.hooks.clone();
802 let plugins = ctx.run_config().invocation_hooks.clone();
803 let invocation_id = ctx.invocation_id().to_string();
804 let agent_name = self.config.name.clone();
805 let stream = async_stream::stream! {
806 use futures::StreamExt;
807 let answer = |content: Content| {
808 let mut event = Event::new(invocation_id.clone());
809 event.author = agent_name.clone();
810 event.llm_response.content = Some(content);
811 event
812 };
813 let callback_ctx = ctx.clone() as Arc<dyn adk_core::CallbackContext>;
814
815 let mut early = None;
817 for plugin in &plugins {
818 match plugin.before_agent(callback_ctx.clone()).await {
819 Ok(Some(content)) => { early = Some(content); break; }
820 Ok(None) => {}
821 Err(error) => { yield Err(error); return; }
822 }
823 }
824 if early.is_none() {
825 for callback in &hooks.before_agent {
826 match callback(callback_ctx.clone()).await {
827 Ok(Some(content)) => { early = Some(content); break; }
828 Ok(None) => {}
829 Err(error) => { yield Err(error); return; }
830 }
831 }
832 }
833
834 if let Some(content) = early {
835 yield Ok(answer(content));
836 } else {
837 let mut turn = turn;
838 'events: while let Some(item) = turn.next().await {
839 let mut event = match item {
840 Ok(event) => event,
841 Err(error) => { yield Err(error); return; }
842 };
843 for callback in &hooks.after_request {
844 match callback(ctx.as_ref(), &event) {
845 Ok(Some(replacement)) => { event = replacement; break; }
846 Ok(None) => {}
847 Err(error) => {
848 yield Ok(create_v1_error_event(&invocation_id, &agent_name, &error.to_string()));
849 break 'events;
850 }
851 }
852 }
853 yield Ok(event);
854 }
855 }
856
857 for plugin in &plugins {
859 match plugin.after_agent(callback_ctx.clone()).await {
860 Ok(Some(content)) => { yield Ok(answer(content)); return; }
861 Ok(None) => {}
862 Err(error) => { yield Err(error); return; }
863 }
864 }
865 for callback in &hooks.after_agent {
866 match callback(callback_ctx.clone()).await {
867 Ok(Some(content)) => { yield Ok(answer(content)); return; }
868 Ok(None) => {}
869 Err(error) => { yield Err(error); return; }
870 }
871 }
872 };
873 Ok(Box::pin(stream))
874 }
875 }
876
877 impl RemoteA2aV1Agent {
878 fn turn(&self, ctx: Arc<dyn InvocationContext>) -> EventStream {
881 let card = self.config.agent_card.clone();
882 let hooks = self.config.hooks.clone();
883 let invocation_id = ctx.invocation_id().to_string();
884 let agent_name = self.config.name.clone();
885 let branch = ctx.branch().to_string();
886 let broker = self.config.credential_broker.clone();
887 let scopes = self.config.credential_scopes.clone();
888 let send_configuration = self.config.send_configuration.clone();
889 let acting = ctx.acting_context();
890 let run_streams = ctx.run_config().streaming_mode != adk_core::StreamingMode::None;
893 let streaming = self.config.streaming.unwrap_or(run_streams);
894
895 let keys = RemoteKeys::for_agent(&agent_name);
897 let state = ctx.session().state();
898 let remote_context = state.get(&keys.context_id).and_then(string_value);
899 let remote_task = state.get(&keys.task_id).and_then(string_value);
900 let outgoing = outgoing_turn(ctx.as_ref(), &agent_name, hooks.to_wire_part.as_ref());
901 let turn_ctx = ctx.clone();
902
903 let stream = async_stream::stream! {
904 let card = match &hooks.card_provider {
906 Some(provider) => match provider().await {
907 Ok(card) => card,
908 Err(e) => {
909 yield Ok(create_v1_error_event(&invocation_id, &agent_name, &format!("agent card resolution failed: {e}")));
910 return;
911 }
912 },
913 None => card,
914 };
915 let use_streaming = streaming && card.capabilities.streaming == Some(true);
916
917 if outgoing.parts.is_empty() {
919 let mut event = Event::new(invocation_id.clone());
920 event.author = agent_name.clone();
921 event.branch = branch.clone();
922 yield Ok(event);
923 return;
924 }
925
926 let interface = match Self::select_interface(&card) {
928 Some(i) => i.clone(),
929 None => {
930 yield Ok(create_v1_error_event(
931 &invocation_id,
932 &agent_name,
933 "no supported interface found in agent card (need JSONRPC or HTTP+JSON)",
934 ));
935 return;
936 }
937 };
938
939 let mut client = A2aV1Client::with_retry(
942 card.clone(),
943 crate::a2a::client::v1_client::RetryConfig {
944 max_retries: 0,
945 ..Default::default()
946 },
947 );
948 if let Some(broker) = broker.as_deref() {
949 match super::brokered_token(broker, &acting, &interface.url, &scopes).await {
950 Ok(token) => client = client.with_credential(token),
951 Err(e) => {
952 yield Ok(create_v1_error_event(&invocation_id, &agent_name, &e.to_string()));
953 return;
954 }
955 }
956 }
957
958 let client = Arc::new(client);
959 let rest = interface.protocol_binding == "HTTP+JSON";
960 let mut cleanup =
962 RemoteTaskCleanupGuard::new(client.clone(), rest, hooks.remote_task_cleanup.clone());
963
964 let task_id = remote_task.filter(|_| outgoing.answers_own_call);
967 let mut message = build_v1_message(outgoing.parts, remote_context, task_id);
968 for callback in &hooks.before_request {
969 match callback(turn_ctx.as_ref(), &mut message) {
970 Ok(Some(event)) => {
971 yield Ok(event);
972 return;
973 }
974 Ok(None) => {}
975 Err(e) => {
976 yield Ok(create_v1_error_event(&invocation_id, &agent_name, &e.to_string()));
977 return;
978 }
979 }
980 }
981
982 if use_streaming {
983 match client.stream_message_with(message, send_configuration.as_ref()).await {
986 Ok(mut updates) => {
987 use futures::StreamExt;
988
989 let mut finished = false;
990 let mut remote = RemoteEvents::new(&invocation_id, &agent_name).with_hooks(&hooks);
991 while let Some(update) = updates.next().await {
992 let stream_response = match update {
993 Ok(update) => update,
994 Err(e) => {
995 yield Ok(create_v1_error_event(&invocation_id, &agent_name, &e.to_string()));
996 return;
997 }
998 };
999 cleanup.observe(&stream_response);
1000 if ends_stream(&stream_response) {
1001 finished = true;
1002 let mut events = remote.handle(&stream_response);
1003 let last = events.pop().unwrap_or_else(|| remote.new_event());
1004 for event in events {
1005 yield Ok(event);
1006 }
1007 yield Ok(end_turn(last, &stream_response, &keys));
1008 let drain = async { while updates.next().await.is_some() {} };
1011 let _ = tokio::time::timeout(std::time::Duration::from_secs(2), drain).await;
1012 break;
1013 }
1014 for event in remote.handle(&stream_response) {
1015 yield Ok(event);
1016 }
1017 }
1018
1019 if !finished {
1020 yield Ok(create_v1_error_event(
1021 &invocation_id,
1022 &agent_name,
1023 &crate::a2a::client::truncated_stream_error().to_string(),
1024 ));
1025 }
1026 }
1027 Err(e) => {
1028 yield Ok(create_v1_error_event(
1029 &invocation_id,
1030 &agent_name,
1031 &format!("failed to send streaming message: {e}"),
1032 ));
1033 }
1034 }
1035 } else {
1036 let sent = if rest {
1038 client.send_message_rest_with(message, send_configuration.as_ref()).await
1039 } else {
1040 client.send_message_with(message, send_configuration.as_ref()).await
1041 };
1042 match sent {
1043 Ok(SendMessageResponse::Message(reply)) => {
1044 let resp = a2a_protocol_types::events::StreamResponse::Message(reply);
1046 cleanup.observe(&resp);
1047 let mut remote = RemoteEvents::new(&invocation_id, &agent_name).with_hooks(&hooks);
1048 let event = remote.handle(&resp).pop().unwrap_or_else(|| remote.new_event());
1049 yield Ok(end_turn(event, &resp, &keys));
1050 }
1051 Ok(SendMessageResponse::Task(task)) => {
1052 let resp = a2a_protocol_types::events::StreamResponse::Task(task);
1054 cleanup.observe(&resp);
1055 let mut remote = RemoteEvents::new(&invocation_id, &agent_name).with_hooks(&hooks);
1056 let event = remote.handle(&resp).pop().unwrap_or_else(|| remote.new_event());
1057 yield Ok(end_turn(event, &resp, &keys));
1058 }
1059 Ok(_) => {
1060 yield Ok(create_v1_error_event(
1061 &invocation_id,
1062 &agent_name,
1063 "unsupported SendMessage result: neither a task nor a message",
1064 ));
1065 }
1066 Err(e) => {
1067 yield Ok(create_v1_error_event(
1068 &invocation_id,
1069 &agent_name,
1070 &format!("failed to send message: {e}"),
1071 ));
1072 }
1073 }
1074 }
1075 };
1076
1077 Box::pin(stream)
1078 }
1079 }
1080
1081 struct RemoteKeys {
1083 context_id: String,
1085 task_id: String,
1087 }
1088
1089 impl RemoteKeys {
1090 fn for_agent(agent_name: &str) -> Self {
1091 Self {
1092 context_id: format!("a2a_remote:{agent_name}:context_id"),
1093 task_id: format!("a2a_remote:{agent_name}:task_id"),
1094 }
1095 }
1096 }
1097
1098 fn string_value(value: serde_json::Value) -> Option<String> {
1099 value.as_str().filter(|s| !s.is_empty()).map(str::to_string)
1100 }
1101
1102 struct OutgoingTurn {
1104 parts: Vec<a2a_protocol_types::Part>,
1105 answers_own_call: bool,
1108 }
1109
1110 fn outgoing_turn(
1119 ctx: &dyn InvocationContext,
1120 agent_name: &str,
1121 to_wire: Option<&ToWirePart>,
1122 ) -> OutgoingTurn {
1123 let outgoing_part = |part: &Part| match to_wire {
1124 Some(convert) => convert(part).ok().flatten(),
1125 None => outgoing_part(part),
1126 };
1127 let history = ctx.session().conversation_history_with_context(agent_name, ctx.branch());
1128 let since_reply =
1129 history.iter().rposition(|content| content.role == "model").map_or(0, |i| i + 1);
1130 let own_calls: std::collections::HashSet<String> = history
1133 .iter()
1134 .filter(|content| content.role == "model")
1135 .flat_map(|content| &content.parts)
1136 .filter_map(|part| match part {
1137 Part::FunctionCall { id: Some(id), .. } => Some(id.clone()),
1138 _ => None,
1139 })
1140 .collect();
1141 let mut answers_own_call = false;
1142 let mut parts = Vec::new();
1143 for part in history[since_reply..].iter().flat_map(|content| &content.parts) {
1144 match part {
1145 Part::FunctionResponse { function_response, id, .. }
1146 if !id.as_ref().is_some_and(|id| own_calls.contains(id)) =>
1147 {
1148 let result = serde_json::to_string(&function_response.response)
1149 .unwrap_or_else(|_| "<unserializable>".to_string());
1150 let name = if function_response.name.is_empty() {
1151 "<unnamed>"
1152 } else {
1153 function_response.name.as_str()
1154 };
1155 parts.push(a2a_protocol_types::Part::text(format!(
1156 "Tool {name} returned: {result}"
1157 )));
1158 }
1159 Part::FunctionResponse { .. } => {
1160 answers_own_call = true;
1161 parts.extend(outgoing_part(part));
1162 }
1163 other => parts.extend(outgoing_part(other)),
1164 }
1165 }
1166 if parts.is_empty() && history.is_empty() {
1167 parts = ctx.user_content().parts.iter().filter_map(outgoing_part).collect();
1168 }
1169 OutgoingTurn { parts, answers_own_call }
1170 }
1171
1172 struct RemoteTaskCleanupGuard {
1177 client: Arc<A2aV1Client>,
1178 rest: bool,
1179 task_id: Option<String>,
1180 settled: bool,
1181 custom: Option<RemoteTaskCleanup>,
1182 }
1183
1184 impl RemoteTaskCleanupGuard {
1185 fn new(client: Arc<A2aV1Client>, rest: bool, custom: Option<RemoteTaskCleanup>) -> Self {
1186 Self { client, rest, task_id: None, settled: false, custom }
1187 }
1188
1189 fn observe(&mut self, response: &a2a_protocol_types::events::StreamResponse) {
1191 use a2a_protocol_types::events::StreamResponse;
1192 let (task_id, state) = match response {
1193 StreamResponse::Task(task) => (Some(&task.id.0), Some(task.status.state)),
1194 StreamResponse::StatusUpdate(update) => {
1195 (Some(&update.task_id.0), Some(update.status.state))
1196 }
1197 StreamResponse::ArtifactUpdate(update) => (Some(&update.task_id.0), None),
1198 StreamResponse::Message(_) => {
1199 self.settled = true;
1200 (None, None)
1201 }
1202 _ => (None, None),
1203 };
1204 if let Some(task_id) = task_id {
1205 self.task_id = Some(task_id.clone());
1206 }
1207 if state.is_some_and(is_final_state) {
1208 self.settled = true;
1209 }
1210 }
1211 }
1212
1213 impl Drop for RemoteTaskCleanupGuard {
1214 fn drop(&mut self) {
1215 if self.settled {
1216 return;
1217 }
1218 let Some(task_id) = self.task_id.take() else { return };
1219 let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
1220 if let Some(custom) = self.custom.clone() {
1221 runtime.spawn(custom(task_id));
1222 return;
1223 }
1224 let (client, rest) = (self.client.clone(), self.rest);
1225 runtime.spawn(async move {
1226 let cancel = async {
1227 if rest {
1228 client.cancel_task_rest(&task_id).await.map(drop)
1229 } else {
1230 client.cancel_task(&task_id).await.map(drop)
1231 }
1232 };
1233 match tokio::time::timeout(std::time::Duration::from_secs(5), cancel).await {
1234 Ok(Ok(())) => {}
1235 Ok(Err(error)) => tracing::warn!(%task_id, %error, "failed to cancel task"),
1236 Err(_) => tracing::warn!(%task_id, "failed to cancel task: timed out"),
1237 }
1238 });
1239 }
1240 }
1241
1242 fn outgoing_part(part: &Part) -> Option<a2a_protocol_types::Part> {
1251 use crate::a2a::v1::convert::{
1252 media_part_to_wire, tagged_function_call_part, tagged_function_response_part,
1253 };
1254 match part {
1255 Part::Text { text } if !text.trim().is_empty() => {
1256 Some(a2a_protocol_types::Part::text(text.clone()))
1257 }
1258 Part::Thinking { thinking, .. } if !thinking.trim().is_empty() => {
1259 let mut wire = a2a_protocol_types::Part::text(thinking.clone());
1260 wire.metadata = Some(
1261 serde_json::json!({ crate::a2a::v1::convert::ADK_THOUGHT_METADATA_KEY: true }),
1262 );
1263 Some(wire)
1264 }
1265 Part::FunctionCall { name, args, id, .. } => {
1266 Some(tagged_function_call_part(name, args, id.as_deref(), false))
1267 }
1268 Part::FunctionResponse { function_response, id, .. } => {
1269 Some(tagged_function_response_part(
1270 &function_response.name,
1271 &function_response.response,
1272 id.as_deref(),
1273 ))
1274 }
1275 other => media_part_to_wire(other),
1276 }
1277 }
1278
1279 fn build_v1_message(
1282 parts: Vec<a2a_protocol_types::Part>,
1283 context_id: Option<String>,
1284 task_id: Option<String>,
1285 ) -> a2a_protocol_types::Message {
1286 let parts = if parts.is_empty() { vec![a2a_protocol_types::Part::text("")] } else { parts };
1287 a2a_protocol_types::Message {
1288 id: a2a_protocol_types::MessageId::new(uuid::Uuid::new_v4().to_string()),
1289 role: a2a_protocol_types::MessageRole::User,
1290 parts,
1291 task_id: task_id.map(a2a_protocol_types::TaskId::new),
1292 context_id: context_id.map(a2a_protocol_types::ContextId::new),
1293 reference_task_ids: None,
1294 extensions: None,
1295 metadata: None,
1296 }
1297 }
1298
1299 struct RemoteEvents {
1317 invocation_id: String,
1318 agent_name: String,
1319 aggregations: Vec<(String, Aggregation)>,
1321 converter: Option<EventConverter>,
1322 from_wire: Option<FromWirePart>,
1323 allow_transfer: bool,
1324 }
1325
1326 #[derive(Default)]
1327 struct Aggregation {
1328 parts: Vec<Part>,
1329 citations: Vec<adk_core::CitationSource>,
1330 custom: std::collections::HashMap<String, String>,
1331 usage: Option<adk_core::UsageMetadata>,
1332 }
1333
1334 impl RemoteEvents {
1335 fn new(invocation_id: &str, agent_name: &str) -> Self {
1336 Self {
1337 invocation_id: invocation_id.to_string(),
1338 agent_name: agent_name.to_string(),
1339 aggregations: Vec::new(),
1340 converter: None,
1341 from_wire: None,
1342 allow_transfer: false,
1343 }
1344 }
1345
1346 fn with_hooks(mut self, hooks: &RemoteAgentHooks) -> Self {
1348 self.converter = hooks.event_converter.clone();
1349 self.from_wire = hooks.from_wire_part.clone();
1350 self.allow_transfer = hooks.allow_transfer_to_agent;
1351 self
1352 }
1353
1354 fn handle(&mut self, response: &a2a_protocol_types::events::StreamResponse) -> Vec<Event> {
1356 use a2a_protocol_types::events::StreamResponse;
1357 let event = match &self.converter {
1358 Some(convert) => match convert(response) {
1359 Ok(event) => event,
1360 Err(error) => Some(create_v1_error_event(
1361 &self.invocation_id,
1362 &self.agent_name,
1363 &format!("failed to convert a2aEvent: {error}"),
1364 )),
1365 },
1366 None => self.to_event(response),
1367 };
1368 let event = event.map(|mut event| {
1369 if self.allow_transfer
1370 && let Some(agent) = transfer_target(response)
1371 {
1372 event.actions.transfer_to_agent = Some(agent);
1373 }
1374 event
1375 });
1376 if partial_flag(response).is_some() {
1377 return event.into_iter().collect();
1378 }
1379 match response {
1380 StreamResponse::StatusUpdate(update) if is_final_state(update.status.state) => {
1381 let mut events: Vec<Event> = std::mem::take(&mut self.aggregations)
1382 .into_iter()
1383 .map(|(_, aggregation)| self.joined(aggregation))
1384 .collect();
1385 events.extend(event);
1386 events
1387 }
1388 StreamResponse::Task(_) => {
1389 self.aggregations.clear();
1390 event.into_iter().collect()
1391 }
1392 StreamResponse::ArtifactUpdate(update) => {
1393 let Some(mut event) = event else { return Vec::new() };
1394 let id = update.artifact.id.0.clone();
1395 let last_chunk = update.last_chunk.unwrap_or(false);
1396 if update.append != Some(true) {
1397 self.aggregations.retain(|(existing, _)| *existing != id);
1398 if last_chunk {
1399 event.llm_response.partial = false;
1400 return vec![event];
1401 }
1402 }
1403 let mut aggregation = self
1404 .aggregations
1405 .iter()
1406 .position(|(existing, _)| *existing == id)
1407 .map(|index| self.aggregations.remove(index).1)
1408 .unwrap_or_default();
1409 aggregate(&mut aggregation, &event);
1410 if !last_chunk {
1411 self.aggregations.push((id, aggregation));
1412 return vec![event];
1413 }
1414 let joined = self.joined(aggregation);
1415 vec![event, joined]
1416 }
1417 _ => event.into_iter().collect(),
1418 }
1419 }
1420
1421 fn joined(&self, aggregation: Aggregation) -> Event {
1422 let mut event = self.new_event();
1423 event.llm_response.content =
1424 Some(Content { role: "model".to_string(), parts: aggregation.parts });
1425 if !aggregation.citations.is_empty() {
1426 event.llm_response.citation_metadata =
1427 Some(adk_core::CitationMetadata { citation_sources: aggregation.citations });
1428 }
1429 event.llm_response.usage_metadata = aggregation.usage;
1430 event.provider_metadata = aggregation.custom;
1431 event
1432 }
1433
1434 fn new_event(&self) -> Event {
1435 let mut event = Event::new(self.invocation_id.clone());
1436 event.author = self.agent_name.clone();
1437 event
1438 }
1439
1440 fn to_event(&self, response: &a2a_protocol_types::events::StreamResponse) -> Option<Event> {
1442 use a2a_protocol_types::events::StreamResponse;
1443 use a2a_protocol_types::task::TaskState;
1444 match response {
1445 StreamResponse::Task(task) => {
1446 let mut parts = Vec::new();
1447 for artifact in task.artifacts.iter().flatten() {
1448 parts.extend(adk_parts(&artifact.parts, self.from_wire.as_ref()));
1449 }
1450 let status = status_message(
1451 task.status.state,
1452 task.status.message.as_ref(),
1453 self.from_wire.as_ref(),
1454 );
1455 parts.extend(status.parts);
1456 let final_state = is_final_state(task.status.state);
1457 if parts.is_empty() && !final_state {
1458 return None;
1459 }
1460 let mut event = self.new_event();
1461 if !parts.is_empty() {
1462 if waits(task.status.state) {
1463 event.long_running_tool_ids =
1464 long_running_ids(&parts, &task_parts(task));
1465 }
1466 event.llm_response.content =
1467 Some(Content { role: "model".to_string(), parts });
1468 }
1469 event.llm_response.error_message = status.error;
1470 apply_metadata(
1471 &mut event,
1472 task.metadata.as_ref(),
1473 None,
1474 Some((&task.id.0, &task.context_id.0)),
1475 );
1476 event.llm_response.turn_complete = final_state;
1477 Some(event)
1478 }
1479 StreamResponse::Message(message) => {
1480 let parts = adk_parts(&message.parts, self.from_wire.as_ref());
1481 let mut event = self.new_event();
1482 if !parts.is_empty() {
1483 let role = if message.role == a2a_protocol_types::MessageRole::User {
1484 "user"
1485 } else {
1486 "model"
1487 };
1488 event.llm_response.content =
1489 Some(Content { role: role.to_string(), parts });
1490 }
1491 let ids = message
1492 .task_id
1493 .as_ref()
1494 .map(|t| t.0.as_str())
1495 .zip(message.context_id.as_ref().map(|c| c.0.as_str()));
1496 apply_metadata(&mut event, message.metadata.as_ref(), None, ids);
1497 event.llm_response.turn_complete = true;
1498 Some(event)
1499 }
1500 StreamResponse::ArtifactUpdate(update) => {
1501 let partial_flag = partial_flag(response);
1502 let last_chunk = update.last_chunk.unwrap_or(false);
1503 if update.artifact.parts.is_empty()
1504 || (partial_flag == Some(true) && last_chunk)
1505 {
1506 return None;
1507 }
1508 let parts = adk_parts(&update.artifact.parts, self.from_wire.as_ref());
1509 if parts.is_empty() {
1510 return None;
1511 }
1512 let mut event = self.new_event();
1513 event.long_running_tool_ids = long_running_ids(&parts, &update.artifact.parts);
1514 event.llm_response.content = Some(Content { role: "model".to_string(), parts });
1515 apply_metadata(
1516 &mut event,
1517 update.metadata.as_ref(),
1518 update.artifact.metadata.as_ref(),
1519 Some((&update.task_id.0, &update.context_id.0)),
1520 );
1521 event.llm_response.partial =
1522 partial_flag.unwrap_or(update.append == Some(true) || !last_chunk);
1523 Some(event)
1524 }
1525 StreamResponse::StatusUpdate(update) => {
1526 let ids = Some((update.task_id.0.as_str(), update.context_id.0.as_str()));
1527 if is_final_state(update.status.state) {
1528 let status = status_message(
1529 update.status.state,
1530 update.status.message.as_ref(),
1531 self.from_wire.as_ref(),
1532 );
1533 let mut event = self.new_event();
1534 let wire_parts = update
1535 .status
1536 .message
1537 .as_ref()
1538 .map(|m| m.parts.clone())
1539 .unwrap_or_default();
1540 event.long_running_tool_ids = long_running_ids(&status.parts, &wire_parts);
1541 if !status.parts.is_empty() {
1542 event.llm_response.content =
1543 Some(Content { role: "model".to_string(), parts: status.parts });
1544 }
1545 event.llm_response.error_message = status.error;
1546 apply_metadata(&mut event, update.metadata.as_ref(), None, ids);
1547 event.llm_response.turn_complete = true;
1548 return Some(event);
1549 }
1550 let message = update.status.message.as_ref()?;
1551 let mut parts = adk_parts(&message.parts, self.from_wire.as_ref());
1552 if parts.is_empty() {
1553 return None;
1554 }
1555 for part in &mut parts {
1557 if let Part::Text { text } = part {
1558 *part =
1559 Part::Thinking { thinking: std::mem::take(text), signature: None };
1560 }
1561 }
1562 let mut event = self.new_event();
1563 event.llm_response.content = Some(Content { role: "model".to_string(), parts });
1564 apply_metadata(&mut event, update.metadata.as_ref(), None, ids);
1565 event.llm_response.partial = true;
1566 event.llm_response.turn_complete = false;
1567 let _ = TaskState::Working;
1568 Some(event)
1569 }
1570 _ => None,
1571 }
1572 }
1573 }
1574
1575 fn partial_flag(response: &a2a_protocol_types::events::StreamResponse) -> Option<bool> {
1577 use a2a_protocol_types::events::StreamResponse;
1578 let metadata = match response {
1579 StreamResponse::ArtifactUpdate(update) => update.metadata.as_ref(),
1580 StreamResponse::StatusUpdate(update) => update.metadata.as_ref(),
1581 StreamResponse::Task(task) => task.metadata.as_ref(),
1582 StreamResponse::Message(message) => message.metadata.as_ref(),
1583 _ => None,
1584 };
1585 metadata
1586 .and_then(|metadata| metadata.get(crate::a2a::v1::convert::ADK_PARTIAL_METADATA_KEY))
1587 .and_then(serde_json::Value::as_bool)
1588 }
1589
1590 fn aggregate(aggregation: &mut Aggregation, event: &Event) {
1593 for part in event.content().into_iter().flat_map(|content| &content.parts) {
1594 match (part, aggregation.parts.last_mut()) {
1595 (Part::Text { text }, Some(Part::Text { text: last })) => last.push_str(text),
1596 (Part::Thinking { thinking, .. }, Some(Part::Thinking { thinking: last, .. })) => {
1597 last.push_str(thinking);
1598 }
1599 (part, _) => aggregation.parts.push(part.clone()),
1600 }
1601 }
1602 if let Some(citations) = &event.llm_response.citation_metadata {
1603 aggregation.citations.extend(citations.citation_sources.iter().cloned());
1604 }
1605 aggregation.custom.extend(event.provider_metadata.clone());
1606 if event.llm_response.usage_metadata.is_some() {
1607 aggregation.usage = event.llm_response.usage_metadata.clone();
1608 }
1609 }
1610
1611 fn transfer_target(response: &a2a_protocol_types::events::StreamResponse) -> Option<String> {
1613 use a2a_protocol_types::events::StreamResponse;
1614 let metadata = match response {
1615 StreamResponse::ArtifactUpdate(update) => update.metadata.as_ref(),
1616 StreamResponse::StatusUpdate(update) => update.metadata.as_ref(),
1617 StreamResponse::Task(task) => task.metadata.as_ref(),
1618 StreamResponse::Message(message) => message.metadata.as_ref(),
1619 _ => None,
1620 };
1621 metadata
1622 .and_then(|meta| {
1623 meta.get(crate::a2a::v1::processor::ADK_TRANSFER_TO_AGENT_METADATA_KEY)
1624 })
1625 .and_then(serde_json::Value::as_str)
1626 .filter(|agent| !agent.is_empty())
1627 .map(str::to_owned)
1628 }
1629
1630 fn is_final_state(state: a2a_protocol_types::task::TaskState) -> bool {
1632 use a2a_protocol_types::task::TaskState;
1633 matches!(
1634 state,
1635 TaskState::Completed
1636 | TaskState::Failed
1637 | TaskState::Canceled
1638 | TaskState::Rejected
1639 | TaskState::InputRequired
1640 | TaskState::AuthRequired
1641 )
1642 }
1643
1644 fn waits(state: a2a_protocol_types::task::TaskState) -> bool {
1645 matches!(
1646 state,
1647 a2a_protocol_types::task::TaskState::InputRequired
1648 | a2a_protocol_types::task::TaskState::AuthRequired
1649 )
1650 }
1651
1652 fn adk_parts(
1654 parts: &[a2a_protocol_types::Part],
1655 from_wire: Option<&FromWirePart>,
1656 ) -> Vec<Part> {
1657 parts
1658 .iter()
1659 .filter_map(|part| match from_wire {
1660 Some(convert) => convert(part).ok().flatten(),
1661 None => crate::a2a::v1::convert::wire_part_to_adk(part).ok(),
1662 })
1663 .filter(|part| !matches!(part, Part::Text { text } if text.is_empty()))
1664 .collect()
1665 }
1666
1667 fn task_parts(task: &a2a_protocol_types::Task) -> Vec<a2a_protocol_types::Part> {
1670 let mut parts: Vec<_> =
1671 task.artifacts.iter().flatten().flat_map(|artifact| artifact.parts.clone()).collect();
1672 parts.extend(task.status.message.iter().flat_map(|message| message.parts.clone()));
1673 parts
1674 }
1675
1676 fn long_running_ids(parts: &[Part], wire: &[a2a_protocol_types::Part]) -> Vec<String> {
1678 let marked: std::collections::HashSet<String> = wire
1679 .iter()
1680 .filter(|part| {
1681 part.metadata
1682 .as_ref()
1683 .and_then(|meta| {
1684 meta.get(crate::a2a::v1::convert::ADK_LONG_RUNNING_METADATA_KEY)
1685 })
1686 .and_then(serde_json::Value::as_bool)
1687 == Some(true)
1688 })
1689 .filter_map(|part| match &part.content {
1690 a2a_protocol_types::PartContent::Data(data) => {
1691 data.get("id").and_then(serde_json::Value::as_str).map(str::to_owned)
1692 }
1693 _ => None,
1694 })
1695 .collect();
1696 parts
1697 .iter()
1698 .filter_map(|part| match part {
1699 Part::FunctionCall { id: Some(id), .. } if marked.contains(id) => Some(id.clone()),
1700 _ => None,
1701 })
1702 .collect()
1703 }
1704
1705 struct StatusMessage {
1707 parts: Vec<Part>,
1708 error: Option<String>,
1709 }
1710
1711 fn status_message(
1712 state: a2a_protocol_types::task::TaskState,
1713 message: Option<&a2a_protocol_types::Message>,
1714 from_wire: Option<&FromWirePart>,
1715 ) -> StatusMessage {
1716 let failed = state == a2a_protocol_types::task::TaskState::Failed;
1717 let Some(message) = message else {
1718 return StatusMessage {
1719 parts: Vec::new(),
1720 error: failed.then(|| "a2a task failed".to_string()),
1721 };
1722 };
1723 let mut wire = message.parts.as_slice();
1724 let mut error = None;
1725 if failed
1726 && let Some(first) = wire.first()
1727 && let Some(text) = first.text_content().filter(|t| !t.is_empty())
1728 {
1729 error = Some(text.to_string());
1730 let marked = first
1731 .metadata
1732 .as_ref()
1733 .and_then(|meta| meta.get(crate::a2a::v1::convert::ADK_ERROR_MESSAGE_METADATA_KEY))
1734 .and_then(serde_json::Value::as_bool)
1735 == Some(true);
1736 if marked {
1737 wire = &wire[1..];
1738 }
1739 }
1740 if failed && error.is_none() {
1741 error = Some("a2a task failed".to_string());
1742 }
1743 StatusMessage { parts: adk_parts(wire, from_wire), error }
1744 }
1745
1746 fn apply_metadata(
1751 event: &mut Event,
1752 update_meta: Option<&serde_json::Value>,
1753 artifact_meta: Option<&serde_json::Value>,
1754 ids: Option<(&str, &str)>,
1755 ) {
1756 use crate::a2a::v1::processor::{
1757 ADK_CITATION_METADATA_KEY, ADK_CUSTOM_METADATA_KEY, ADK_ERROR_CODE_METADATA_KEY,
1758 ADK_ESCALATE_METADATA_KEY, ADK_USAGE_METADATA_KEY,
1759 };
1760 let mut meta =
1761 update_meta.and_then(serde_json::Value::as_object).cloned().unwrap_or_default();
1762 if let Some(artifact) = artifact_meta.and_then(serde_json::Value::as_object) {
1763 meta.extend(artifact.clone());
1764 }
1765 if let Some(citations) = meta
1766 .get(ADK_CITATION_METADATA_KEY)
1767 .and_then(|c| c.get("citations"))
1768 .and_then(serde_json::Value::as_array)
1769 {
1770 let sources = citations
1771 .iter()
1772 .map(|citation| {
1773 let text = |key: &str| {
1774 citation.get(key).and_then(serde_json::Value::as_str).map(str::to_owned)
1775 };
1776 let index = |key: &str| {
1777 citation.get(key).and_then(serde_json::Value::as_i64).map(|v| v as i32)
1778 };
1779 adk_core::CitationSource {
1780 uri: text("uri"),
1781 title: text("title"),
1782 start_index: index("startIndex"),
1783 end_index: index("endIndex"),
1784 license: text("license"),
1785 publication_date: text("publicationDate"),
1786 }
1787 })
1788 .collect();
1789 event.llm_response.citation_metadata =
1790 Some(adk_core::CitationMetadata { citation_sources: sources });
1791 }
1792 if let Some(usage) = meta.get(ADK_USAGE_METADATA_KEY) {
1793 let count =
1794 |key: &str| usage.get(key).and_then(serde_json::Value::as_i64).map(|v| v as i32);
1795 event.llm_response.usage_metadata = Some(adk_core::UsageMetadata {
1796 prompt_token_count: count("promptTokenCount").unwrap_or_default(),
1797 candidates_token_count: count("candidatesTokenCount").unwrap_or_default(),
1798 total_token_count: count("totalTokenCount").unwrap_or_default(),
1799 cache_read_input_token_count: count("cachedContentTokenCount"),
1800 thinking_token_count: count("thoughtsTokenCount"),
1801 ..Default::default()
1802 });
1803 }
1804 if let Some((task_id, context_id)) = ids {
1805 event.provider_metadata.insert(A2A_TASK_ID_KEY.to_string(), task_id.to_string());
1806 event.provider_metadata.insert(A2A_CONTEXT_ID_KEY.to_string(), context_id.to_string());
1807 }
1808 if let Some(custom) =
1809 meta.get(ADK_CUSTOM_METADATA_KEY).and_then(serde_json::Value::as_object)
1810 {
1811 for (key, value) in custom {
1812 let value = value.as_str().map_or_else(|| value.to_string(), str::to_owned);
1813 event.provider_metadata.insert(key.clone(), value);
1814 }
1815 }
1816 if let Some(code) =
1817 meta.get(ADK_ERROR_CODE_METADATA_KEY).and_then(serde_json::Value::as_str)
1818 {
1819 event.llm_response.error_code = Some(code.to_string());
1820 }
1821 let escalate = update_meta
1822 .and_then(|meta| meta.get(ADK_ESCALATE_METADATA_KEY))
1823 .and_then(serde_json::Value::as_bool)
1824 == Some(true);
1825 event.actions.escalate = escalate;
1826 }
1827
1828 pub const A2A_TASK_ID_KEY: &str = "a2a:task_id";
1830 pub const A2A_CONTEXT_ID_KEY: &str = "a2a:context_id";
1832
1833 fn end_turn(
1836 mut event: Event,
1837 resp: &a2a_protocol_types::events::StreamResponse,
1838 keys: &RemoteKeys,
1839 ) -> Event {
1840 use a2a_protocol_types::events::StreamResponse;
1841
1842 event.llm_response.turn_complete = true;
1843 let (context_id, task_id, state) = match resp {
1844 StreamResponse::StatusUpdate(update) => (
1845 Some(update.context_id.0.clone()),
1846 Some(update.task_id.0.clone()),
1847 Some(update.status.state),
1848 ),
1849 StreamResponse::Task(task) => {
1850 (Some(task.context_id.0.clone()), Some(task.id.0.clone()), Some(task.status.state))
1851 }
1852 StreamResponse::Message(message) => {
1853 (message.context_id.as_ref().map(|c| c.0.clone()), None, None)
1854 }
1855 _ => (None, None, None),
1856 };
1857 let waiting = state.is_some_and(waits);
1858 if let Some(context_id) = context_id {
1859 event.actions.state_delta.insert(keys.context_id.clone(), context_id.into());
1860 }
1861 let task_id = task_id.filter(|_| waiting);
1862 event.actions.state_delta.insert(
1863 keys.task_id.clone(),
1864 task_id.map_or(serde_json::Value::Null, serde_json::Value::String),
1865 );
1866 event
1867 }
1868
1869 fn ends_stream(response: &a2a_protocol_types::events::StreamResponse) -> bool {
1872 use a2a_protocol_types::events::StreamResponse;
1873 match response {
1874 StreamResponse::StatusUpdate(update) => is_final_state(update.status.state),
1875 StreamResponse::Task(task) => is_final_state(task.status.state),
1876 StreamResponse::Message(_) => true,
1877 _ => false,
1878 }
1879 }
1880
1881 fn create_v1_error_event(invocation_id: &str, agent_name: &str, error: &str) -> Event {
1883 let mut event = Event::new(invocation_id.to_string());
1884 event.author = agent_name.to_string();
1885 event.llm_response.error_message = Some(error.to_string());
1886 event.llm_response.turn_complete = true;
1887 event
1888 }
1889
1890 #[cfg(test)]
1891 mod tests {
1892 use super::*;
1893 use a2a_protocol_types::{AgentCapabilities, AgentInterface, AgentSkill};
1894
1895 fn make_test_card() -> AgentCard {
1896 AgentCard {
1897 name: "test-v1-agent".to_string(),
1898 url: Some("http://localhost:9999".to_string()),
1899 description: "A test v1 agent".to_string(),
1900 version: "1.0.0".to_string(),
1901 supported_interfaces: vec![
1902 AgentInterface {
1903 url: "http://localhost:9999/a2a".to_string(),
1904 protocol_binding: "JSONRPC".to_string(),
1905 protocol_version: "1.0".to_string(),
1906 tenant: None,
1907 },
1908 AgentInterface {
1909 url: "http://localhost:9999/rest".to_string(),
1910 protocol_binding: "HTTP+JSON".to_string(),
1911 protocol_version: "1.0".to_string(),
1912 tenant: None,
1913 },
1914 ],
1915 default_input_modes: vec!["text/plain".to_string()],
1916 default_output_modes: vec!["text/plain".to_string()],
1917 skills: vec![AgentSkill {
1918 id: "echo".to_string(),
1919 name: "Echo".to_string(),
1920 description: "Echoes input".to_string(),
1921 tags: vec![],
1922 examples: None,
1923 input_modes: None,
1924 output_modes: None,
1925 security_requirements: None,
1926 }],
1927 capabilities: AgentCapabilities::default(),
1928 provider: None,
1929 icon_url: None,
1930 documentation_url: None,
1931 security_schemes: None,
1932 security_requirements: None,
1933 signatures: None,
1934 }
1935 }
1936
1937 #[test]
1938 fn select_interface_prefers_jsonrpc() {
1939 let card = make_test_card();
1940 let selected = RemoteA2aV1Agent::select_interface(&card).unwrap();
1941 assert_eq!(selected.protocol_binding, "JSONRPC");
1942 assert_eq!(selected.url, "http://localhost:9999/a2a");
1943 }
1944
1945 #[test]
1946 fn select_interface_falls_back_to_http_json() {
1947 let mut card = make_test_card();
1948 card.supported_interfaces.retain(|i| i.protocol_binding != "JSONRPC");
1949 let selected = RemoteA2aV1Agent::select_interface(&card).unwrap();
1950 assert_eq!(selected.protocol_binding, "HTTP+JSON");
1951 assert_eq!(selected.url, "http://localhost:9999/rest");
1952 }
1953
1954 #[test]
1955 fn select_interface_returns_none_for_unsupported() {
1956 let mut card = make_test_card();
1957 card.supported_interfaces = vec![AgentInterface {
1958 url: "grpc://localhost:9999".to_string(),
1959 protocol_binding: "GRPC".to_string(),
1960 protocol_version: "1.0".to_string(),
1961 tenant: None,
1962 }];
1963 assert!(RemoteA2aV1Agent::select_interface(&card).is_none());
1964 }
1965
1966 #[test]
1967 fn select_interface_returns_none_for_empty() {
1968 let mut card = make_test_card();
1969 card.supported_interfaces = vec![];
1970 assert!(RemoteA2aV1Agent::select_interface(&card).is_none());
1971 }
1972
1973 #[test]
1974 fn new_agent_stores_config() {
1975 let card = make_test_card();
1976 let agent = RemoteA2aV1Agent::new(RemoteA2aV1Config {
1977 name: "my-agent".to_string(),
1978 description: "My remote agent".to_string(),
1979 agent_card: card,
1980 streaming: None,
1982 credential_broker: None,
1983 credential_scopes: Vec::new(),
1984 send_configuration: None,
1985 hooks: Default::default(),
1986 });
1987 assert_eq!(agent.name(), "my-agent");
1988 assert_eq!(agent.description(), "My remote agent");
1989 }
1990
1991 #[test]
1992 fn agent_has_no_sub_agents() {
1993 let card = make_test_card();
1994 let agent = RemoteA2aV1Agent::new(RemoteA2aV1Config {
1995 name: "test".to_string(),
1996 description: "test".to_string(),
1997 agent_card: card,
1998 streaming: None,
2000 credential_broker: None,
2001 credential_scopes: Vec::new(),
2002 send_configuration: None,
2003 hooks: Default::default(),
2004 });
2005 assert!(agent.sub_agents().is_empty());
2006 }
2007
2008 #[test]
2009 fn build_v1_message_with_content() {
2010 let msg = build_v1_message(vec![a2a_protocol_types::Part::text("hello")], None, None);
2011 assert_eq!(msg.role, a2a_protocol_types::MessageRole::User);
2012 assert_eq!(msg.parts.len(), 1);
2013 assert_eq!(msg.parts[0].text_content(), Some("hello"));
2014 assert!(msg.context_id.is_none() && msg.task_id.is_none());
2015 }
2016
2017 #[test]
2018 fn build_v1_message_without_content() {
2019 let msg = build_v1_message(Vec::new(), None, None);
2020 assert_eq!(msg.parts[0].text_content(), Some(""));
2021 }
2022
2023 #[test]
2024 fn a_message_continues_the_remote_conversation_and_its_waiting_task() {
2025 let msg = build_v1_message(
2026 vec![a2a_protocol_types::Part::text("again")],
2027 Some("ctx-7".to_string()),
2028 Some("task-7".to_string()),
2029 );
2030 assert_eq!(msg.context_id.unwrap().0, "ctx-7");
2031 assert_eq!(msg.task_id.unwrap().0, "task-7");
2032 }
2033
2034 #[test]
2035 fn answers_and_media_go_out_in_the_shape_every_sdk_reads() {
2036 let answer = outgoing_part(&Part::FunctionResponse {
2037 function_response: adk_core::FunctionResponseData::new(
2038 "request_approval",
2039 serde_json::json!({"status": "approved"}),
2040 ),
2041 id: Some("call-1".to_string()),
2042 annotations: None,
2043 })
2044 .unwrap();
2045 assert_eq!(
2046 serde_json::to_value(&answer).unwrap(),
2047 serde_json::json!({
2048 "data": {"id": "call-1", "name": "request_approval", "response": {"status": "approved"}},
2049 "metadata": {"adk_type": "function_response"}
2050 })
2051 );
2052 let image = outgoing_part(&Part::InlineData {
2053 mime_type: "image/png".to_string(),
2054 data: vec![1, 2, 3],
2055 uri: None,
2056 annotations: None,
2057 })
2058 .unwrap();
2059 assert_eq!(image.media_type.as_deref(), Some("image/png"));
2060 let thought =
2061 outgoing_part(&Part::Thinking { thinking: "hm".into(), signature: None }).unwrap();
2062 assert_eq!(thought.text_content(), Some("hm"));
2063 assert_eq!(thought.metadata.unwrap()["adk_thought"], true, "a thought stays a thought");
2064 }
2065
2066 #[test]
2067 fn a_waiting_remote_ends_the_turn_on_its_pending_call_and_keeps_its_task() {
2068 use crate::a2a::v1::convert::{
2069 tagged_function_call_part, tagged_function_response_part,
2070 };
2071 use a2a_protocol_types::events::{StreamResponse, TaskStatusUpdateEvent};
2072 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
2073
2074 let mut status = TaskStatus::new(TaskState::InputRequired);
2075 status.message = Some(a2a_protocol_types::Message {
2076 id: a2a_protocol_types::MessageId::new("m"),
2077 role: a2a_protocol_types::MessageRole::Agent,
2078 parts: vec![
2079 tagged_function_call_part(
2080 "request_approval",
2081 &serde_json::json!({"amount": 5}),
2082 Some("call-1"),
2083 true,
2084 ),
2085 tagged_function_response_part(
2086 "request_approval",
2087 &serde_json::json!({"status": "pending"}),
2088 Some("call-1"),
2089 ),
2090 ],
2091 task_id: None,
2092 context_id: None,
2093 reference_task_ids: None,
2094 extensions: None,
2095 metadata: None,
2096 });
2097 let resp = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2098 task_id: TaskId::new("task-1"),
2099 context_id: ContextId::new("ctx-1"),
2100 status,
2101 metadata: None,
2102 });
2103 let keys = RemoteKeys::for_agent("remote");
2104 let event = finish(&resp, &keys);
2105
2106 assert!(event.llm_response.turn_complete);
2107 assert_eq!(event.long_running_tool_ids, vec!["call-1".to_string()]);
2108 let parts = &event.llm_response.content.as_ref().unwrap().parts;
2109 assert!(
2110 matches!(&parts[0], Part::FunctionCall { name, .. } if name == "request_approval")
2111 );
2112 assert_eq!(event.actions.state_delta[&keys.context_id], "ctx-1");
2113 assert_eq!(event.actions.state_delta[&keys.task_id], "task-1");
2114
2115 let done = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2117 task_id: TaskId::new("task-1"),
2118 context_id: ContextId::new("ctx-1"),
2119 status: TaskStatus::new(TaskState::Completed),
2120 metadata: None,
2121 });
2122 let event = finish(&done, &keys);
2123 assert_eq!(event.actions.state_delta[&keys.context_id], "ctx-1");
2124 assert!(event.actions.state_delta[&keys.task_id].is_null());
2125 }
2126
2127 fn finish(resp: &a2a_protocol_types::events::StreamResponse, keys: &RemoteKeys) -> Event {
2129 let mut remote = RemoteEvents::new("inv", "remote");
2130 let event = remote.handle(resp).pop().unwrap_or_else(|| remote.new_event());
2131 end_turn(event, resp, keys)
2132 }
2133
2134 #[test]
2135 fn stream_payloads_parse_bare_wrapped_and_error_forms() {
2136 use a2a_protocol_types::events::StreamResponse;
2137 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
2138
2139 let update =
2140 StreamResponse::StatusUpdate(a2a_protocol_types::events::TaskStatusUpdateEvent {
2141 task_id: TaskId::new("t1"),
2142 context_id: ContextId::new("c1"),
2143 status: TaskStatus::new(TaskState::InputRequired),
2144 metadata: None,
2145 });
2146 let bare = serde_json::to_string(&update).unwrap();
2147 let wrapped =
2148 serde_json::json!({"jsonrpc": "2.0", "id": 1, "result": update}).to_string();
2149 use crate::a2a::client::v1_client::{V1ClientError, parse_stream_payload};
2150 for data in [bare, wrapped] {
2151 let parsed = parse_stream_payload(&data).unwrap().unwrap();
2152 assert!(ends_stream(&parsed));
2153 }
2154
2155 let error = r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"boom"}}"#;
2156 assert!(matches!(
2157 parse_stream_payload(error).unwrap(),
2158 Err(V1ClientError::JsonRpc { code: -32603, ref message, .. }) if message == "boom"
2159 ));
2160 assert!(parse_stream_payload("not json").is_none());
2161 }
2162
2163 #[test]
2164 fn working_and_artifact_updates_do_not_end_a_stream() {
2165 use a2a_protocol_types::events::StreamResponse;
2166 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
2167
2168 let working =
2169 StreamResponse::StatusUpdate(a2a_protocol_types::events::TaskStatusUpdateEvent {
2170 task_id: TaskId::new("t1"),
2171 context_id: ContextId::new("c1"),
2172 status: TaskStatus::new(TaskState::Working),
2173 metadata: None,
2174 });
2175 assert!(!ends_stream(&working));
2176 let artifact = StreamResponse::ArtifactUpdate(
2177 a2a_protocol_types::events::TaskArtifactUpdateEvent {
2178 task_id: TaskId::new("t1"),
2179 context_id: ContextId::new("c1"),
2180 artifact: a2a_protocol_types::artifact::Artifact::new(
2181 a2a_protocol_types::ArtifactId::new("a1"),
2182 vec![a2a_protocol_types::Part::text("hi")],
2183 ),
2184 append: None,
2185 last_chunk: Some(true),
2186 metadata: None,
2187 },
2188 );
2189 assert!(!ends_stream(&artifact));
2190 }
2191
2192 #[test]
2193 fn convert_status_update_with_message() {
2194 use a2a_protocol_types::events::TaskStatusUpdateEvent;
2195 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
2196
2197 let mut status = TaskStatus::new(TaskState::Completed);
2198 status.message = Some(a2a_protocol_types::Message {
2199 id: a2a_protocol_types::MessageId::new("msg-1"),
2200 role: a2a_protocol_types::MessageRole::Agent,
2201 parts: vec![a2a_protocol_types::Part::text("done!")],
2202 task_id: None,
2203 context_id: None,
2204 reference_task_ids: None,
2205 extensions: None,
2206 metadata: None,
2207 });
2208
2209 let status_event = TaskStatusUpdateEvent {
2210 task_id: TaskId::new("task-1"),
2211 context_id: ContextId::new("ctx-1"),
2212 status,
2213 metadata: None,
2214 };
2215
2216 let resp = a2a_protocol_types::events::StreamResponse::StatusUpdate(status_event);
2217 let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();
2218
2219 assert_eq!(event.author, "agent-1");
2220 assert!(event.llm_response.turn_complete);
2221 let content = event.llm_response.content.unwrap();
2222 assert_eq!(content.parts.len(), 1);
2223 match &content.parts[0] {
2224 Part::Text { text } => assert_eq!(text, "done!"),
2225 _ => panic!("expected text part"),
2226 }
2227 }
2228
2229 #[test]
2230 fn convert_status_update_terminal_without_message() {
2231 use a2a_protocol_types::events::TaskStatusUpdateEvent;
2232 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
2233
2234 let status_event = TaskStatusUpdateEvent {
2235 task_id: TaskId::new("task-1"),
2236 context_id: ContextId::new("ctx-1"),
2237 status: TaskStatus::new(TaskState::Failed),
2238 metadata: None,
2239 };
2240
2241 let resp = a2a_protocol_types::events::StreamResponse::StatusUpdate(status_event);
2242 let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();
2243
2244 assert!(event.llm_response.turn_complete);
2245 assert!(event.llm_response.content.is_none());
2246 }
2247
2248 #[test]
2249 fn a_failed_status_message_is_the_remote_error() {
2250 use a2a_protocol_types::events::TaskStatusUpdateEvent;
2251 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
2252
2253 let failed = |parts: Vec<a2a_protocol_types::Part>| {
2254 let mut status = TaskStatus::new(TaskState::Failed);
2255 status.message = Some(a2a_protocol_types::Message {
2256 id: a2a_protocol_types::MessageId::new("status-msg-1"),
2257 role: a2a_protocol_types::MessageRole::Agent,
2258 parts,
2259 task_id: None,
2260 context_id: None,
2261 reference_task_ids: None,
2262 extensions: None,
2263 metadata: None,
2264 });
2265 a2a_protocol_types::events::StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2266 task_id: TaskId::new("task-1"),
2267 context_id: ContextId::new("ctx-1"),
2268 status,
2269 metadata: None,
2270 })
2271 };
2272
2273 let marked = failed(vec![
2275 crate::a2a::v1::convert::error_message_part("Internal error: agent error: boom"),
2276 a2a_protocol_types::Part::text("partial answer"),
2277 ]);
2278 let event = RemoteEvents::new("inv-1", "agent-1").to_event(&marked).unwrap();
2279 assert_eq!(
2280 event.llm_response.error_message.as_deref(),
2281 Some("Internal error: agent error: boom")
2282 );
2283 let texts: Vec<_> =
2284 event.content().unwrap().parts.iter().filter_map(Part::text).collect();
2285 assert_eq!(texts, ["partial answer"], "the rest of the message is content");
2286 assert!(event.llm_response.turn_complete);
2287
2288 let unmarked = failed(vec![a2a_protocol_types::Part::text("boom")]);
2291 let event = RemoteEvents::new("inv-1", "agent-1").to_event(&unmarked).unwrap();
2292 assert_eq!(event.llm_response.error_message.as_deref(), Some("boom"));
2293 assert_eq!(event.content().unwrap().parts.len(), 1);
2294 }
2295
2296 fn artifact_update(
2297 id: &str,
2298 text: &str,
2299 append: Option<bool>,
2300 last_chunk: Option<bool>,
2301 metadata: Option<serde_json::Value>,
2302 ) -> a2a_protocol_types::events::StreamResponse {
2303 a2a_protocol_types::events::StreamResponse::ArtifactUpdate(
2304 a2a_protocol_types::events::TaskArtifactUpdateEvent {
2305 task_id: a2a_protocol_types::TaskId::new("task-1"),
2306 context_id: a2a_protocol_types::ContextId::new("ctx-1"),
2307 artifact: a2a_protocol_types::Artifact::new(
2308 a2a_protocol_types::ArtifactId::new(id),
2309 vec![a2a_protocol_types::Part::text(text)],
2310 ),
2311 append,
2312 last_chunk,
2313 metadata,
2314 },
2315 )
2316 }
2317
2318 fn completed() -> a2a_protocol_types::events::StreamResponse {
2319 a2a_protocol_types::events::StreamResponse::StatusUpdate(
2320 a2a_protocol_types::events::TaskStatusUpdateEvent {
2321 task_id: a2a_protocol_types::TaskId::new("task-1"),
2322 context_id: a2a_protocol_types::ContextId::new("ctx-1"),
2323 status: a2a_protocol_types::TaskStatus::new(
2324 a2a_protocol_types::TaskState::Completed,
2325 ),
2326 metadata: None,
2327 },
2328 )
2329 }
2330
2331 fn stored_text(events: &[Event]) -> Vec<String> {
2332 events
2333 .iter()
2334 .filter(|event| !event.llm_response.partial)
2335 .filter_map(|event| event.content())
2336 .map(|content| content.parts.iter().filter_map(Part::text).collect())
2337 .filter(|text: &String| !text.is_empty())
2338 .collect()
2339 }
2340
2341 #[test]
2342 fn chunks_from_a_go_server_are_partial_and_join_into_one_answer() {
2343 let mut remote = RemoteEvents::new("inv", "remote");
2345 let mut events = Vec::new();
2346 events.extend(remote.handle(&artifact_update("a", "Hel", None, None, None)));
2347 events.extend(remote.handle(&artifact_update("a", "lo", Some(true), None, None)));
2348 events.extend(remote.handle(&completed()));
2349
2350 assert!(events[0].llm_response.partial && events[1].llm_response.partial);
2351 assert_eq!(stored_text(&events), ["Hello"], "the session keeps the whole answer once");
2352 }
2353
2354 #[test]
2355 fn a_last_chunk_closes_its_artifacts_answer() {
2356 let mut remote = RemoteEvents::new("inv", "remote");
2357 let mut events = Vec::new();
2358 events.extend(remote.handle(&artifact_update("a", "one ", None, Some(false), None)));
2359 events.extend(remote.handle(&artifact_update(
2360 "a",
2361 "two",
2362 Some(true),
2363 Some(true),
2364 None,
2365 )));
2366 events.extend(remote.handle(&completed()));
2367 assert_eq!(stored_text(&events), ["one two"]);
2368 }
2369
2370 #[test]
2371 fn an_adk_servers_partial_artifact_and_its_reset_are_not_stored() {
2372 let partial = Some(serde_json::json!({"adk_partial": true}));
2373 let answer = Some(serde_json::json!({"adk_partial": false}));
2374 let mut remote = RemoteEvents::new("inv", "remote");
2375 let mut events = Vec::new();
2376 events.extend(remote.handle(&artifact_update(
2377 "tmp",
2378 "Hel",
2379 Some(false),
2380 None,
2381 partial.clone(),
2382 )));
2383 events.extend(remote.handle(&artifact_update(
2384 "main",
2385 "Hello",
2386 Some(false),
2387 None,
2388 answer,
2389 )));
2390 let reset = a2a_protocol_types::events::StreamResponse::ArtifactUpdate(
2392 a2a_protocol_types::events::TaskArtifactUpdateEvent {
2393 task_id: a2a_protocol_types::TaskId::new("task-1"),
2394 context_id: a2a_protocol_types::ContextId::new("ctx-1"),
2395 artifact: a2a_protocol_types::Artifact::new(
2396 a2a_protocol_types::ArtifactId::new("tmp"),
2397 vec![a2a_protocol_types::Part::data(serde_json::json!({}))],
2398 ),
2399 append: Some(false),
2400 last_chunk: Some(true),
2401 metadata: partial,
2402 },
2403 );
2404 assert!(remote.handle(&reset).is_empty(), "the reset is dropped");
2405 events.extend(remote.handle(&completed()));
2406 assert_eq!(stored_text(&events), ["Hello"]);
2407 }
2408
2409 #[test]
2410 fn a_transfer_the_remote_names_is_followed_only_when_allowed() {
2411 use a2a_protocol_types::task::{TaskState, TaskStatus};
2412 let done = a2a_protocol_types::events::StreamResponse::StatusUpdate(
2413 a2a_protocol_types::events::TaskStatusUpdateEvent {
2414 task_id: a2a_protocol_types::TaskId::new("task-1"),
2415 context_id: a2a_protocol_types::ContextId::new("ctx-1"),
2416 status: TaskStatus::new(TaskState::Completed),
2417 metadata: Some(serde_json::json!({"adk_transfer_to_agent": "billing"})),
2418 },
2419 );
2420 let ignored = RemoteEvents::new("inv", "remote").handle(&done);
2421 assert_eq!(ignored.last().unwrap().actions.transfer_to_agent, None, "off by default");
2422 let hooks = RemoteAgentHooks::default().allow_transfer_to_agent(true);
2423 let followed = RemoteEvents::new("inv", "remote").with_hooks(&hooks).handle(&done);
2424 assert_eq!(
2425 followed.last().unwrap().actions.transfer_to_agent.as_deref(),
2426 Some("billing")
2427 );
2428 }
2429
2430 #[test]
2431 fn progress_before_the_task_ends_is_the_remotes_reasoning() {
2432 use a2a_protocol_types::task::{TaskState, TaskStatus};
2433 let mut status = TaskStatus::new(TaskState::Working);
2434 status.message = Some(a2a_protocol_types::Message {
2435 id: a2a_protocol_types::MessageId::new("m"),
2436 role: a2a_protocol_types::MessageRole::Agent,
2437 parts: vec![a2a_protocol_types::Part::text("looking it up")],
2438 task_id: None,
2439 context_id: None,
2440 reference_task_ids: None,
2441 extensions: None,
2442 metadata: None,
2443 });
2444 let working = a2a_protocol_types::events::StreamResponse::StatusUpdate(
2445 a2a_protocol_types::events::TaskStatusUpdateEvent {
2446 task_id: a2a_protocol_types::TaskId::new("task-1"),
2447 context_id: a2a_protocol_types::ContextId::new("ctx-1"),
2448 status,
2449 metadata: Some(
2450 serde_json::json!({"adk_escalate": true, "adk_error_code": "E1"}),
2451 ),
2452 },
2453 );
2454 let event = RemoteEvents::new("inv", "remote").to_event(&working).unwrap();
2455 assert!(event.llm_response.partial && !event.llm_response.turn_complete);
2456 assert!(
2457 matches!(&event.content().unwrap().parts[0], Part::Thinking { thinking, .. } if thinking == "looking it up")
2458 );
2459 assert!(event.actions.escalate);
2460 assert_eq!(event.llm_response.error_code.as_deref(), Some("E1"));
2461 assert_eq!(event.provider_metadata[A2A_TASK_ID_KEY], "task-1");
2462 assert_eq!(event.provider_metadata[A2A_CONTEXT_ID_KEY], "ctx-1");
2463 }
2464
2465 #[test]
2466 fn a_direct_message_reply_ends_the_turn_with_its_text() {
2467 let reply = a2a_protocol_types::Message {
2468 id: a2a_protocol_types::MessageId::new("m-1"),
2469 role: a2a_protocol_types::MessageRole::Agent,
2470 parts: vec![a2a_protocol_types::Part::text("hello there")],
2471 task_id: None,
2472 context_id: None,
2473 reference_task_ids: None,
2474 extensions: None,
2475 metadata: None,
2476 };
2477 let resp = a2a_protocol_types::events::StreamResponse::Message(reply);
2478
2479 let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();
2480 assert_eq!(event.author, "agent-1");
2481 assert!(event.llm_response.turn_complete);
2482 let text: String = event
2483 .llm_response
2484 .content
2485 .expect("content")
2486 .parts
2487 .iter()
2488 .filter_map(Part::text)
2489 .collect();
2490 assert_eq!(text, "hello there");
2491 }
2492
2493 #[test]
2494 fn convert_status_update_non_terminal_without_message() {
2495 use a2a_protocol_types::events::TaskStatusUpdateEvent;
2496 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
2497
2498 let status_event = TaskStatusUpdateEvent {
2499 task_id: TaskId::new("task-1"),
2500 context_id: ContextId::new("ctx-1"),
2501 status: TaskStatus::new(TaskState::Working),
2502 metadata: None,
2503 };
2504
2505 let resp = a2a_protocol_types::events::StreamResponse::StatusUpdate(status_event);
2506 let result = RemoteEvents::new("inv-1", "agent-1").to_event(&resp);
2507
2508 assert!(result.is_none());
2510 }
2511
2512 #[test]
2513 fn convert_artifact_update_with_text() {
2514 use a2a_protocol_types::artifact::{Artifact, ArtifactId};
2515 use a2a_protocol_types::events::TaskArtifactUpdateEvent;
2516 use a2a_protocol_types::task::{ContextId, TaskId};
2517
2518 let artifact_event = TaskArtifactUpdateEvent {
2519 task_id: TaskId::new("task-1"),
2520 context_id: ContextId::new("ctx-1"),
2521 artifact: Artifact {
2522 id: ArtifactId::new("art-1"),
2523 name: Some("result".to_string()),
2524 description: None,
2525 parts: vec![a2a_protocol_types::Part::text("artifact content")],
2526 extensions: None,
2527 metadata: None,
2528 },
2529 append: None,
2530 last_chunk: Some(true),
2531 metadata: None,
2532 };
2533
2534 let resp = a2a_protocol_types::events::StreamResponse::ArtifactUpdate(artifact_event);
2535 let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();
2536
2537 assert_eq!(event.author, "agent-1");
2538 let content = event.llm_response.content.unwrap();
2539 assert_eq!(content.parts.len(), 1);
2540 match &content.parts[0] {
2541 Part::Text { text } => assert_eq!(text, "artifact content"),
2542 _ => panic!("expected text part"),
2543 }
2544 assert!(!event.llm_response.partial);
2546 }
2547
2548 #[test]
2549 fn convert_artifact_update_partial() {
2550 use a2a_protocol_types::artifact::{Artifact, ArtifactId};
2551 use a2a_protocol_types::events::TaskArtifactUpdateEvent;
2552 use a2a_protocol_types::task::{ContextId, TaskId};
2553
2554 let artifact_event = TaskArtifactUpdateEvent {
2555 task_id: TaskId::new("task-1"),
2556 context_id: ContextId::new("ctx-1"),
2557 artifact: Artifact {
2558 id: ArtifactId::new("art-1"),
2559 name: None,
2560 description: None,
2561 parts: vec![a2a_protocol_types::Part::text("partial...")],
2562 extensions: None,
2563 metadata: None,
2564 },
2565 append: None,
2566 last_chunk: Some(false),
2567 metadata: None,
2568 };
2569
2570 let resp = a2a_protocol_types::events::StreamResponse::ArtifactUpdate(artifact_event);
2571 let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();
2572
2573 assert!(event.llm_response.partial);
2574 }
2575
2576 #[test]
2577 fn create_v1_error_event_sets_fields() {
2578 let event = create_v1_error_event("inv-1", "agent-1", "something broke");
2579 assert_eq!(event.author, "agent-1");
2580 assert_eq!(event.llm_response.error_message.as_deref(), Some("something broke"));
2581 assert!(event.llm_response.turn_complete);
2582 }
2583 }
2584}