Skip to main content

adk_server/a2a/v1/
processor.rs

1//! Turns an agent run's events into A2A task updates, as adk-go's A2A executor does
2//! (`server/adka2a/v2`: `processor.go`, `task_artifact.go`, `metadata.go`,
3//! `input_required.go`).
4//!
5//! Every event with content becomes one artifact update carrying all of its parts: text,
6//! thoughts (`adk_thought`), files, function calls and responses (`adk_type`), and anything
7//! else as JSON data. Each update carries the event's `adk_*` metadata. Long-running calls
8//! move out of the artifacts into the `INPUT_REQUIRED` status message, and the first model
9//! error fails the task. [`OutputMode`] decides how updates map to artifacts.
10
11use std::collections::{HashMap, HashSet};
12
13use a2a_protocol_types::Part as WirePart;
14use a2a_protocol_types::artifact::{Artifact, ArtifactId};
15use a2a_protocol_types::task::TaskState;
16use adk_core::{Event, Part};
17use serde_json::{Map, Value, json};
18
19use super::convert::{
20    ADK_PARTIAL_METADATA_KEY, adk_parts_to_wire, error_message_part, tagged_function_call_part,
21};
22use crate::a2a::processor::{Awaiting, awaiting};
23
24/// The function a held call's confirmation is asked and answered with, as adk-go names it.
25pub const REQUEST_CONFIRMATION_FUNCTION: &str = "adk_request_confirmation";
26
27/// `adk_invocation_id`: the invocation an update came from.
28pub const ADK_INVOCATION_ID_METADATA_KEY: &str = "adk_invocation_id";
29/// `adk_author`: the agent that wrote the event.
30pub const ADK_AUTHOR_METADATA_KEY: &str = "adk_author";
31/// `adk_branch`: the event's branch in a multi-agent run.
32pub const ADK_BRANCH_METADATA_KEY: &str = "adk_branch";
33/// `adk_usage_metadata`: token counts, in the Gemini API's camelCase shape.
34pub const ADK_USAGE_METADATA_KEY: &str = "adk_usage_metadata";
35/// `adk_citation_metadata`: citations, in the Gemini API's shape.
36pub const ADK_CITATION_METADATA_KEY: &str = "adk_citation_metadata";
37/// `adk_custom_metadata`: the event's own metadata, without ADK's internal markers.
38pub const ADK_CUSTOM_METADATA_KEY: &str = "adk_custom_metadata";
39/// `adk_error_code`: the model error code of the event.
40pub const ADK_ERROR_CODE_METADATA_KEY: &str = "adk_error_code";
41/// `adk_escalate`: an event of the run asked to escalate.
42pub const ADK_ESCALATE_METADATA_KEY: &str = "adk_escalate";
43/// `adk_transfer_to_agent`: the agent the run last transferred to.
44pub const ADK_TRANSFER_TO_AGENT_METADATA_KEY: &str = "adk_transfer_to_agent";
45
46/// How a run's output is laid out in artifacts, as adk-go's `OutputMode`.
47#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
48pub enum OutputMode {
49    /// One artifact holds the run's answer: each non-partial event appends to it, with
50    /// `lastChunk` set as adk-python reads it. Streamed partial events replace a separate
51    /// artifact marked `adk_partial`, which is emptied (`{}`, `lastChunk`) when the run
52    /// ends. adk-go's default (`artifact-per-run`).
53    #[default]
54    ArtifactPerRun,
55    /// Each event starts a new artifact; an author's partial events build one artifact up
56    /// until its non-partial event closes it with `lastChunk` (`artifact-per-event`).
57    ArtifactPerEvent,
58}
59
60/// One artifact update a run produces, before it is stored and sent.
61#[derive(Debug, Clone)]
62pub struct ArtifactUpdate {
63    /// The artifact, or the chunk of it, the update carries.
64    pub artifact: Artifact,
65    /// Whether the parts go onto the artifact with the same ID instead of replacing it.
66    pub append: bool,
67    /// Whether this is the artifact's last chunk.
68    pub last_chunk: bool,
69    /// The update's metadata (`adk_*` keys).
70    pub metadata: Option<Map<String, Value>>,
71}
72
73/// The status a run ends on, before it is stored and sent.
74#[derive(Debug, Clone)]
75pub struct FinalStatus {
76    /// The state the task ends in.
77    pub state: TaskState,
78    /// The status message's parts; none for no message.
79    pub parts: Vec<WirePart>,
80    /// The update's metadata (`adk_*` keys).
81    pub metadata: Map<String, Value>,
82}
83
84/// Follows one agent run's events (see the module documentation).
85pub(super) struct EventProcessor {
86    base_meta: Map<String, Value>,
87    maker: ArtifactMaker,
88    escalate: bool,
89    transfer_to_agent: Option<String>,
90    failed: Option<FinalStatus>,
91    pending: Vec<WirePart>,
92    pending_call_ids: HashSet<String>,
93    awaiting_auth: bool,
94    /// Each author's text streamed in partial events since its last non-partial one.
95    streamed: HashMap<String, String>,
96    /// Converts parts instead of [`adk_parts_to_wire`], when set.
97    to_wire_part: Option<super::hooks::ToWirePart>,
98}
99
100impl EventProcessor {
101    /// A processor whose updates carry `base_meta` (`adk_app_name`, `adk_user_id`,
102    /// `adk_session_id`).
103    pub fn new(mode: OutputMode, base_meta: Map<String, Value>) -> Self {
104        Self {
105            base_meta,
106            maker: ArtifactMaker::new(mode),
107            escalate: false,
108            transfer_to_agent: None,
109            failed: None,
110            pending: Vec::new(),
111            pending_call_ids: HashSet::new(),
112            awaiting_auth: false,
113            streamed: HashMap::new(),
114            to_wire_part: None,
115        }
116    }
117
118    /// Converts each part with `converter` instead of the default conversion.
119    pub fn with_to_wire_part(mut self, converter: Option<super::hooks::ToWirePart>) -> Self {
120        self.to_wire_part = converter;
121        self
122    }
123
124    /// `parts` of `event` as A2A parts, through the converter when one is set. A converter
125    /// error leaves the part out and is logged.
126    fn to_wire(&self, event: &Event, parts: &[Part], long_running_ids: &[String]) -> Vec<WirePart> {
127        let Some(convert) = &self.to_wire_part else {
128            return adk_parts_to_wire(parts, long_running_ids);
129        };
130        parts
131            .iter()
132            .filter_map(|part| match convert(event, part) {
133                Ok(converted) => converted,
134                Err(error) => {
135                    tracing::warn!(%error, "A2A part converter failed; part left out");
136                    None
137                }
138            })
139            .collect()
140    }
141
142    /// The artifact update `event` produces, if it has content to show.
143    pub fn process(&mut self, event: &Event) -> Option<ArtifactUpdate> {
144        self.escalate |= event.actions.escalate;
145        if let Some(agent) = &event.actions.transfer_to_agent
146            && !agent.is_empty()
147        {
148            self.transfer_to_agent = Some(agent.clone());
149        }
150        self.awaiting_auth |= awaiting(event) == Some(Awaiting::Auth);
151
152        let meta = event_meta(&self.base_meta, event);
153        let mut remaining = self.take_pending(event);
154        self.join_streamed_text(event, &mut remaining);
155
156        let error_code = event.llm_response.error_code.as_deref().filter(|code| !code.is_empty());
157        let error_message =
158            event.llm_response.error_message.as_deref().filter(|message| !message.is_empty());
159        let parts = self.to_wire(event, &remaining, &event.long_running_tool_ids);
160        if (error_code.is_some() || error_message.is_some()) && self.failed.is_none() {
161            let message = error_message.unwrap_or_default();
162            let text = match error_code {
163                Some(code) => format!("llm error response (code {code}): {message:?}"),
164                None => format!("llm error response: {message:?}"),
165            };
166            let mut status_parts = vec![error_message_part(text)];
167            status_parts.extend(parts.iter().cloned());
168            self.failed = Some(FinalStatus {
169                state: TaskState::Failed,
170                parts: status_parts,
171                metadata: meta.clone(),
172            });
173        }
174        if parts.is_empty() {
175            return None;
176        }
177        Some(self.maker.transform(event, parts, meta))
178    }
179
180    /// The update that empties the temporary partial artifact, sent before the final
181    /// status when partial events were streamed ([`OutputMode::ArtifactPerRun`]).
182    pub fn final_artifact_update(&mut self) -> Option<ArtifactUpdate> {
183        self.maker.final_update()
184    }
185
186    /// The status the run ends on: the first model error, else the calls waiting on the
187    /// caller, else `COMPLETED`. It carries `adk_escalate` and `adk_transfer_to_agent`.
188    pub fn final_status(&mut self) -> FinalStatus {
189        let mut status = if let Some(failed) = self.failed.take() {
190            failed
191        } else if !self.pending.is_empty() {
192            let state =
193                if self.awaiting_auth { TaskState::AuthRequired } else { TaskState::InputRequired };
194            FinalStatus { state, parts: std::mem::take(&mut self.pending), metadata: Map::new() }
195        } else {
196            FinalStatus {
197                state: TaskState::Completed,
198                parts: Vec::new(),
199                metadata: self.base_meta.clone(),
200            }
201        };
202        if self.escalate {
203            status.metadata.insert(ADK_ESCALATE_METADATA_KEY.to_string(), Value::Bool(true));
204        }
205        if let Some(agent) = &self.transfer_to_agent {
206            status.metadata.insert(
207                ADK_TRANSFER_TO_AGENT_METADATA_KEY.to_string(),
208                Value::String(agent.clone()),
209            );
210        }
211        status
212    }
213
214    /// Makes a non-partial event that ends streamed deltas carry the whole answer, as an
215    /// `LlmAgent` final event does (`content_complete`): an author's text streamed in
216    /// partial events goes in front of the final event's text, unless that text already
217    /// starts with it.
218    fn join_streamed_text(&mut self, event: &Event, parts: &mut Vec<Part>) {
219        let text: String = parts.iter().filter_map(|part| part.text()).collect();
220        if event.llm_response.partial {
221            self.streamed.entry(event.author.clone()).or_default().push_str(&text);
222            return;
223        }
224        let Some(streamed) = self.streamed.remove(&event.author) else { return };
225        let complete = event
226            .llm_response
227            .provider_metadata
228            .as_ref()
229            .and_then(|metadata| metadata.get("content_complete"))
230            .and_then(Value::as_bool)
231            == Some(true);
232        if complete || streamed.is_empty() || text.starts_with(&streamed) {
233            return;
234        }
235        match parts.iter_mut().find_map(|part| match part {
236            Part::Text { text } => Some(text),
237            _ => None,
238        }) {
239            Some(first) => first.insert_str(0, &streamed),
240            None => parts.insert(0, Part::Text { text: streamed }),
241        }
242    }
243
244    /// Moves `event`'s long-running calls, and the interim responses to them, into the
245    /// pending status message; returns the parts that stay in the artifact. A tool
246    /// confirmation request is pending too.
247    fn take_pending(&mut self, event: &Event) -> Vec<Part> {
248        // A held call asks its caller to confirm it, as adk-go asks: a long-running
249        // `adk_request_confirmation` call that names the original call. It takes the held
250        // call's ID, so the answer decides that call.
251        if let Some(request) = &event.actions.tool_confirmation {
252            let id = request
253                .function_call_id
254                .clone()
255                .unwrap_or_else(|| format!("adk-confirm-{}", uuid::Uuid::new_v4()));
256            if self.pending_call_ids.insert(id.clone()) {
257                let args = json!({
258                    "originalFunctionCall": {
259                        "id": request.function_call_id,
260                        "name": request.tool_name,
261                        "args": request.args,
262                    },
263                    "toolConfirmation": { "hint": "", "confirmed": false },
264                });
265                self.pending.push(tagged_function_call_part(
266                    REQUEST_CONFIRMATION_FUNCTION,
267                    &args,
268                    Some(&id),
269                    true,
270                ));
271            }
272        }
273        let Some(content) = event.content() else { return Vec::new() };
274        // A call is long-running when the event lists its id; older events list the tool
275        // name instead.
276        let listed = |name: &str, id: &str| {
277            event.long_running_tool_ids.iter().any(|listed| listed == id || listed == name)
278        };
279        let mut remaining = Vec::with_capacity(content.parts.len());
280        for part in &content.parts {
281            match part {
282                Part::FunctionCall { id: Some(id), name, .. } if listed(name, id) => {
283                    if self.pending_call_ids.insert(id.clone()) {
284                        let wire = self.to_wire(
285                            event,
286                            std::slice::from_ref(part),
287                            std::slice::from_ref(id),
288                        );
289                        self.pending.extend(wire);
290                    }
291                }
292                Part::FunctionResponse { function_response, id: Some(id), .. }
293                    if listed(&function_response.name, id)
294                        || self.pending_call_ids.contains(id) =>
295                {
296                    let response_key = format!("response:{id}");
297                    if self.pending_call_ids.insert(response_key) {
298                        let wire = self.to_wire(event, std::slice::from_ref(part), &[]);
299                        self.pending.extend(wire);
300                    }
301                }
302                other => remaining.push(other.clone()),
303            }
304        }
305        remaining
306    }
307}
308
309/// The metadata of `event`'s update: `base` plus the event's invocation, author and
310/// branch, its citations and token usage, its own metadata, and its model error code.
311fn event_meta(base: &Map<String, Value>, event: &Event) -> Map<String, Value> {
312    let mut meta = base.clone();
313    for (key, value) in [
314        (ADK_INVOCATION_ID_METADATA_KEY, &event.invocation_id),
315        (ADK_AUTHOR_METADATA_KEY, &event.author),
316        (ADK_BRANCH_METADATA_KEY, &event.branch),
317    ] {
318        if !value.is_empty() {
319            meta.insert(key.to_string(), Value::String(value.clone()));
320        }
321    }
322    if let Some(citations) = &event.llm_response.citation_metadata {
323        let citations: Vec<Value> = citations
324            .citation_sources
325            .iter()
326            .map(|source| {
327                let mut citation = Map::new();
328                let fields = [
329                    ("uri", source.uri.clone().map(Value::String)),
330                    ("title", source.title.clone().map(Value::String)),
331                    ("startIndex", source.start_index.map(Value::from)),
332                    ("endIndex", source.end_index.map(Value::from)),
333                    ("license", source.license.clone().map(Value::String)),
334                    ("publicationDate", source.publication_date.clone().map(Value::String)),
335                ];
336                for (key, value) in fields {
337                    if let Some(value) = value {
338                        citation.insert(key.to_string(), value);
339                    }
340                }
341                Value::Object(citation)
342            })
343            .collect();
344        meta.insert(ADK_CITATION_METADATA_KEY.to_string(), json!({ "citations": citations }));
345    }
346    if let Some(usage) = &event.llm_response.usage_metadata {
347        let mut counts = Map::new();
348        counts.insert("promptTokenCount".to_string(), usage.prompt_token_count.into());
349        counts.insert("candidatesTokenCount".to_string(), usage.candidates_token_count.into());
350        counts.insert("totalTokenCount".to_string(), usage.total_token_count.into());
351        if let Some(cached) = usage.cache_read_input_token_count {
352            counts.insert("cachedContentTokenCount".to_string(), cached.into());
353        }
354        if let Some(thoughts) = usage.thinking_token_count {
355            counts.insert("thoughtsTokenCount".to_string(), thoughts.into());
356        }
357        meta.insert(ADK_USAGE_METADATA_KEY.to_string(), Value::Object(counts));
358    }
359    let custom: Map<String, Value> = event
360        .provider_metadata
361        .iter()
362        .filter(|(key, _)| !key.starts_with("adk.") && !key.starts_with("adk_"))
363        .map(|(key, value)| (key.clone(), Value::String(value.clone())))
364        .collect();
365    if !custom.is_empty() {
366        meta.insert(ADK_CUSTOM_METADATA_KEY.to_string(), Value::Object(custom));
367    }
368    if let Some(code) = event.llm_response.error_code.as_deref().filter(|code| !code.is_empty()) {
369        meta.insert(ADK_ERROR_CODE_METADATA_KEY.to_string(), Value::String(code.to_string()));
370    }
371    meta
372}
373
374/// Lays updates out in artifacts according to the [`OutputMode`].
375enum ArtifactMaker {
376    PerRun {
377        /// The artifact of the run's answer, once one update was sent.
378        response_id: Option<String>,
379        /// The temporary artifact of streamed partial events.
380        partial_id: Option<String>,
381    },
382    PerEvent {
383        /// Each author's artifact still receiving partial events.
384        open: HashMap<String, String>,
385    },
386}
387
388impl ArtifactMaker {
389    fn new(mode: OutputMode) -> Self {
390        match mode {
391            OutputMode::ArtifactPerRun => Self::PerRun { response_id: None, partial_id: None },
392            OutputMode::ArtifactPerEvent => Self::PerEvent { open: HashMap::new() },
393        }
394    }
395
396    fn transform(
397        &mut self,
398        event: &Event,
399        mut parts: Vec<WirePart>,
400        meta: Map<String, Value>,
401    ) -> ArtifactUpdate {
402        match self {
403            Self::PerRun { response_id, partial_id } => {
404                let partial = event.llm_response.partial;
405                let slot = if partial { partial_id } else { response_id };
406                let existing = slot.clone();
407                let id = slot.get_or_insert_with(new_artifact_id).clone();
408                let mut metadata = meta;
409                metadata.insert(ADK_PARTIAL_METADATA_KEY.to_string(), Value::Bool(partial));
410                if partial {
411                    for part in &mut parts {
412                        mark_partial(part);
413                    }
414                }
415                let mut artifact = Artifact::new(ArtifactId::new(id), parts);
416                if partial {
417                    artifact.metadata = Some(json!({ ADK_PARTIAL_METADATA_KEY: true }));
418                }
419                ArtifactUpdate {
420                    artifact,
421                    // A partial update replaces the temporary artifact; the answer grows.
422                    append: !partial && existing.is_some(),
423                    // A finished event's chunk is complete: adk-python reads `lastChunk`
424                    // to tell answers from streamed chunks (adk-go reads `adk_partial`).
425                    last_chunk: !partial,
426                    metadata: Some(metadata),
427                }
428            }
429            Self::PerEvent { open } => {
430                let partial = event.llm_response.partial;
431                let continuing = open.get(&event.author).cloned();
432                let id = continuing.clone().unwrap_or_else(new_artifact_id);
433                if partial {
434                    open.insert(event.author.clone(), id.clone());
435                } else {
436                    open.remove(&event.author);
437                }
438                let mut artifact = Artifact::new(ArtifactId::new(id), parts);
439                if !meta.is_empty() {
440                    artifact.metadata = Some(Value::Object(meta));
441                }
442                ArtifactUpdate {
443                    artifact,
444                    append: continuing.is_some() && partial,
445                    last_chunk: !partial,
446                    metadata: None,
447                }
448            }
449        }
450    }
451
452    fn final_update(&mut self) -> Option<ArtifactUpdate> {
453        let Self::PerRun { partial_id, .. } = self else { return None };
454        let id = partial_id.take()?;
455        let mut reset = WirePart::data(json!({}));
456        mark_partial(&mut reset);
457        let mut artifact = Artifact::new(ArtifactId::new(id), vec![reset]);
458        artifact.metadata = Some(json!({ ADK_PARTIAL_METADATA_KEY: true }));
459        let mut metadata = Map::new();
460        metadata.insert(ADK_PARTIAL_METADATA_KEY.to_string(), Value::Bool(true));
461        Some(ArtifactUpdate { artifact, append: false, last_chunk: true, metadata: Some(metadata) })
462    }
463}
464
465fn new_artifact_id() -> String {
466    uuid::Uuid::new_v4().to_string()
467}
468
469/// Marks `part` as part of a streamed partial event.
470fn mark_partial(part: &mut WirePart) {
471    let mut metadata = match part.metadata.take() {
472        Some(Value::Object(metadata)) => metadata,
473        _ => Map::new(),
474    };
475    metadata.insert(ADK_PARTIAL_METADATA_KEY.to_string(), Value::Bool(true));
476    part.metadata = Some(Value::Object(metadata));
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use adk_core::{Content, EventActions, FunctionResponseData, UsageMetadata};
483
484    fn event(author: &str, parts: Vec<Part>, partial: bool) -> Event {
485        let mut event = Event::new("inv-1");
486        event.author = author.to_string();
487        event.set_content(Content { role: "model".to_string(), parts });
488        event.llm_response.partial = partial;
489        event
490    }
491
492    fn text(value: &str) -> Part {
493        Part::Text { text: value.to_string() }
494    }
495
496    fn base() -> Map<String, Value> {
497        let mut base = Map::new();
498        base.insert("adk_app_name".to_string(), json!("app"));
499        base
500    }
501
502    fn data(part: &WirePart) -> Option<&Value> {
503        match &part.content {
504            a2a_protocol_types::PartContent::Data(data) => Some(data),
505            _ => None,
506        }
507    }
508
509    fn texts(update: &ArtifactUpdate) -> Vec<String> {
510        update
511            .artifact
512            .parts
513            .iter()
514            .filter_map(|part| part.text_content().map(str::to_owned))
515            .collect()
516    }
517
518    #[test]
519    fn one_artifact_per_run_holds_the_answer_and_partials_go_to_a_temporary_one() {
520        let mut processor = EventProcessor::new(OutputMode::ArtifactPerRun, base());
521        let first = processor.process(&event("a", vec![text("Hel")], true)).unwrap();
522        let second = processor.process(&event("a", vec![text("lo")], true)).unwrap();
523        let answer = processor.process(&event("a", vec![text("Hello")], false)).unwrap();
524        let more = processor.process(&event("a", vec![text("Bye")], false)).unwrap();
525        let reset = processor.final_artifact_update().unwrap();
526
527        assert_eq!(first.artifact.id, second.artifact.id);
528        assert!(
529            !first.append && !second.append,
530            "a partial update replaces the temporary artifact"
531        );
532        assert_eq!(first.metadata.as_ref().unwrap()[ADK_PARTIAL_METADATA_KEY], true);
533        assert_eq!(
534            first.artifact.parts[0].metadata.as_ref().unwrap()[ADK_PARTIAL_METADATA_KEY],
535            true
536        );
537        assert_ne!(answer.artifact.id, first.artifact.id);
538        assert!(!answer.append && more.append, "the answer grows from its first update");
539        assert_eq!(answer.artifact.id, more.artifact.id);
540        assert!(answer.last_chunk && more.last_chunk, "a finished event's chunk is complete");
541        assert!(!first.last_chunk && !second.last_chunk);
542        assert_eq!(answer.metadata.as_ref().unwrap()[ADK_PARTIAL_METADATA_KEY], false);
543        assert_eq!(texts(&answer), ["Hello"]);
544        assert_eq!(reset.artifact.id, first.artifact.id);
545        assert!(reset.last_chunk && !reset.append);
546        assert_eq!(data(&reset.artifact.parts[0]), Some(&json!({})));
547        assert!(processor.final_artifact_update().is_none());
548    }
549
550    #[test]
551    fn one_artifact_per_event_closes_an_authors_partials() {
552        let mut processor = EventProcessor::new(OutputMode::ArtifactPerEvent, base());
553        let partial = processor.process(&event("a", vec![text("Hel")], true)).unwrap();
554        let other = processor.process(&event("b", vec![text("Hi")], false)).unwrap();
555        let more = processor.process(&event("a", vec![text("lo")], true)).unwrap();
556        let done = processor.process(&event("a", vec![text("Hello")], false)).unwrap();
557        let next = processor.process(&event("a", vec![text("Again")], false)).unwrap();
558
559        assert!(!partial.append && !partial.last_chunk);
560        assert_ne!(other.artifact.id, partial.artifact.id);
561        assert!(other.last_chunk);
562        assert_eq!(more.artifact.id, partial.artifact.id);
563        assert!(more.append);
564        assert_eq!(done.artifact.id, partial.artifact.id);
565        assert!(!done.append && done.last_chunk, "a non-partial event replaces the chunks");
566        assert_ne!(next.artifact.id, done.artifact.id);
567        assert!(done.metadata.is_none());
568        assert_eq!(done.artifact.metadata.as_ref().unwrap()[ADK_AUTHOR_METADATA_KEY], "a");
569        assert!(processor.final_artifact_update().is_none());
570    }
571
572    #[test]
573    fn every_part_type_is_emitted_and_tagged() {
574        let mut processor = EventProcessor::new(OutputMode::ArtifactPerRun, base());
575        let update = processor
576            .process(&event(
577                "a",
578                vec![
579                    Part::Thinking { thinking: "hmm".to_string(), signature: None },
580                    text("answer"),
581                    Part::FunctionCall {
582                        name: "add".to_string(),
583                        args: json!({"a": 1}),
584                        id: Some("c1".to_string()),
585                        thought_signature: None,
586                    },
587                    Part::FunctionResponse {
588                        function_response: FunctionResponseData::new("add", json!({"result": 1})),
589                        id: Some("c1".to_string()),
590                        annotations: None,
591                    },
592                ],
593                false,
594            ))
595            .unwrap();
596        let parts = &update.artifact.parts;
597        assert_eq!(parts.len(), 4);
598        assert_eq!(parts[0].text_content(), Some("hmm"));
599        assert_eq!(parts[0].metadata.as_ref().unwrap()["adk_thought"], true);
600        assert_eq!(parts[1].text_content(), Some("answer"));
601        assert_eq!(parts[2].metadata.as_ref().unwrap()["adk_type"], "function_call");
602        assert_eq!(parts[2].metadata.as_ref().unwrap()["adk_is_long_running"], false);
603        assert_eq!(data(&parts[2]).unwrap()["id"], "c1");
604        assert_eq!(parts[3].metadata.as_ref().unwrap()["adk_type"], "function_response");
605    }
606
607    #[test]
608    fn each_update_carries_the_events_metadata() {
609        let mut processor = EventProcessor::new(OutputMode::ArtifactPerRun, base());
610        let mut answer = event("writer", vec![text("x")], false);
611        answer.branch = "root.writer".to_string();
612        answer.llm_response.usage_metadata = Some(UsageMetadata {
613            prompt_token_count: 3,
614            candidates_token_count: 2,
615            total_token_count: 5,
616            ..Default::default()
617        });
618        answer.provider_metadata.insert("adk.budget.recorded".to_string(), "true".to_string());
619        answer.provider_metadata.insert("trace".to_string(), "t-1".to_string());
620        let update = processor.process(&answer).unwrap();
621        let meta = update.metadata.unwrap();
622
623        assert_eq!(meta["adk_app_name"], "app");
624        assert_eq!(meta[ADK_INVOCATION_ID_METADATA_KEY], "inv-1");
625        assert_eq!(meta[ADK_AUTHOR_METADATA_KEY], "writer");
626        assert_eq!(meta[ADK_BRANCH_METADATA_KEY], "root.writer");
627        assert_eq!(
628            meta[ADK_USAGE_METADATA_KEY],
629            json!({"promptTokenCount": 3, "candidatesTokenCount": 2, "totalTokenCount": 5})
630        );
631        assert_eq!(meta[ADK_CUSTOM_METADATA_KEY], json!({"trace": "t-1"}));
632    }
633
634    #[test]
635    fn long_running_calls_wait_in_the_status_message_not_the_artifact() {
636        let mut processor = EventProcessor::new(OutputMode::ArtifactPerRun, base());
637        let mut call = event(
638            "a",
639            vec![
640                text("I need approval."),
641                Part::FunctionCall {
642                    name: "approve".to_string(),
643                    args: json!({}),
644                    id: Some("c1".to_string()),
645                    thought_signature: None,
646                },
647            ],
648            false,
649        );
650        call.long_running_tool_ids = vec!["c1".to_string()];
651        let interim = event(
652            "a",
653            vec![Part::FunctionResponse {
654                function_response: FunctionResponseData::new(
655                    "approve",
656                    json!({"status": "pending"}),
657                ),
658                id: Some("c1".to_string()),
659                annotations: None,
660            }],
661            false,
662        );
663        let update = processor.process(&call).unwrap();
664        assert!(processor.process(&interim).is_none(), "the interim response waits too");
665        let status = processor.final_status();
666
667        assert_eq!(texts(&update), ["I need approval."]);
668        assert_eq!(update.artifact.parts.len(), 1);
669        assert_eq!(status.state, TaskState::InputRequired);
670        assert_eq!(status.parts.len(), 2);
671        assert_eq!(status.parts[0].metadata.as_ref().unwrap()["adk_is_long_running"], true);
672        assert!(status.metadata.is_empty(), "INPUT_REQUIRED carries only the run's actions");
673    }
674
675    #[test]
676    fn the_first_model_error_fails_the_run() {
677        let mut processor = EventProcessor::new(OutputMode::ArtifactPerRun, base());
678        let mut failed = event("a", vec![text("partial answer")], false);
679        failed.llm_response.error_code = Some("SAFETY".to_string());
680        failed.llm_response.error_message = Some("blocked".to_string());
681        let mut later = event("a", vec![], false);
682        later.llm_response.error_message = Some("again".to_string());
683        assert!(processor.process(&failed).is_some(), "its parts still reach the artifact");
684        processor.process(&later);
685        let status = processor.final_status();
686
687        assert_eq!(status.state, TaskState::Failed);
688        assert_eq!(
689            status.parts[0].text_content(),
690            Some(r#"llm error response (code SAFETY): "blocked""#)
691        );
692        assert_eq!(status.parts[0].metadata.as_ref().unwrap()["adk_is_error_message"], true);
693        assert_eq!(status.parts[1].text_content(), Some("partial answer"));
694        assert_eq!(status.metadata[ADK_ERROR_CODE_METADATA_KEY], "SAFETY");
695    }
696
697    #[test]
698    fn the_final_status_carries_escalation_and_the_last_transfer() {
699        let mut processor = EventProcessor::new(OutputMode::ArtifactPerRun, base());
700        let mut first = event("a", vec![text("x")], false);
701        first.actions = EventActions {
702            escalate: true,
703            transfer_to_agent: Some("b".to_string()),
704            ..Default::default()
705        };
706        let mut second = event("b", vec![text("y")], false);
707        second.actions.transfer_to_agent = Some("c".to_string());
708        processor.process(&first);
709        processor.process(&second);
710        let status = processor.final_status();
711
712        assert_eq!(status.state, TaskState::Completed);
713        assert!(status.parts.is_empty());
714        assert_eq!(status.metadata["adk_app_name"], "app");
715        assert_eq!(status.metadata[ADK_ESCALATE_METADATA_KEY], true);
716        assert_eq!(status.metadata[ADK_TRANSFER_TO_AGENT_METADATA_KEY], "c");
717    }
718}